@tbox.cn/app-build 1.0.0-alpha.1 → 1.0.0-alpha.11

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/dist/index.js CHANGED
@@ -16,7 +16,7 @@ var AppBuildError = class extends Error {
16
16
  import path2 from "path";
17
17
 
18
18
  // src/fs.ts
19
- import { existsSync } from "fs";
19
+ import { existsSync, readFileSync } from "fs";
20
20
  import { mkdir, readFile, readdir, rename, rm, writeFile } from "fs/promises";
21
21
  import path from "path";
22
22
  async function readText(file) {
@@ -25,6 +25,9 @@ async function readText(file) {
25
25
  async function readJson(file) {
26
26
  return JSON.parse(await readText(file));
27
27
  }
28
+ function readJsonSync(file) {
29
+ return JSON.parse(readFileSync(file, "utf8"));
30
+ }
28
31
  async function writeText(file, text) {
29
32
  await mkdir(path.dirname(file), { recursive: true });
30
33
  const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
@@ -127,8 +130,11 @@ function propertyName(node) {
127
130
  }
128
131
  function getProperty(obj, name) {
129
132
  for (const prop of obj.properties) {
130
- if (!ts.isPropertyAssignment(prop)) continue;
131
- if (propertyName(prop.name) === name) return prop.initializer;
133
+ if (ts.isPropertyAssignment(prop)) {
134
+ if (propertyName(prop.name) === name) return prop.initializer;
135
+ continue;
136
+ }
137
+ if (ts.isShorthandPropertyAssignment(prop) && prop.name.text === name) return prop.name;
132
138
  }
133
139
  return void 0;
134
140
  }
@@ -315,6 +321,17 @@ async function scanSkillDir(dir) {
315
321
  }
316
322
  return out;
317
323
  }
324
+ async function scanActionDir(dir) {
325
+ if (!existsSync3(dir)) return [];
326
+ const files = (await listFiles(dir)).filter((file) => file.endsWith(".action.ts"));
327
+ const out = [];
328
+ for (const file of files.sort()) {
329
+ const { expr } = await readExported(file, "action");
330
+ const id = stringProperty(expr, "id", `action (${path5.basename(file)})`);
331
+ out.push({ id, file, relativeFile: path5.relative(dir, file).split(path5.sep).join("/") });
332
+ }
333
+ return out;
334
+ }
318
335
  async function scanCardDirs(serverDir, clientDir) {
319
336
  if (!existsSync3(serverDir) && !existsSync3(clientDir)) return [];
320
337
  const server = /* @__PURE__ */ new Map();
@@ -330,26 +347,35 @@ async function scanCardDirs(serverDir, clientDir) {
330
347
  for (const base of [...bases].sort()) {
331
348
  const serverFile = server.get(base);
332
349
  const clientFile = client.get(base);
333
- if (!serverFile || !clientFile) {
334
- throw new AppBuildError("CARD_PAIR_MISSING", `卡片 ${base} 必须在 server/client 双端成对存在`, {
335
- file: serverFile ?? clientFile
336
- });
350
+ if (!serverFile) {
351
+ throw new AppBuildError("CARD_PAIR_MISSING", "卡片 " + base + " 只有客户端文件,缺少服务端声明", { file: clientFile });
337
352
  }
338
353
  const { expr: serverExpr } = await readExported(serverFile, "card");
354
+ const cardType = stringProperty(serverExpr, "cardType", "card (" + base + ")");
355
+ if (!/^[a-z0-9][a-z0-9._-]*$/i.test(cardType) || cardType.includes("..")) {
356
+ throw new AppBuildError("CARD_TYPE_INVALID", "卡片类型只允许字母/数字/点/下划线/中划线:" + cardType, { file: serverFile });
357
+ }
358
+ const serverRelativeFile = path5.relative(serverDir, serverFile).split(path5.sep).join("/");
359
+ if (!clientFile) {
360
+ const obj = objectFromExpression(serverExpr, "card (" + base + ")");
361
+ if (!getProperty(obj, "view")) {
362
+ throw new AppBuildError("CARD_PAIR_MISSING", "卡片 " + base + " 必须在 server/client 双端成对存在(或用 defineViewCard 声明视图卡)", { file: serverFile });
363
+ }
364
+ out.push({ cardType, serverFile, clientFile: null, clientRelativeFile: null, view: true, serverRelativeFile });
365
+ continue;
366
+ }
339
367
  const { expr: clientExpr } = await readExported(clientFile, "card");
340
- const cardType = stringProperty(serverExpr, "cardType", `card (${base})`);
341
- const clientType = stringProperty(clientExpr, "type", `card (${base})`);
368
+ const clientType = stringProperty(clientExpr, "type", "card (" + base + ")");
342
369
  if (cardType !== clientType) {
343
- throw new AppBuildError("CARD_TYPE_MISMATCH", `卡片 ${base} 双端类型不一致: ${cardType} !== ${clientType}`, {
344
- file: clientFile
345
- });
370
+ throw new AppBuildError("CARD_TYPE_MISMATCH", "卡片 " + base + " 双端类型不一致: " + cardType + " !== " + clientType, { file: clientFile });
346
371
  }
347
372
  out.push({
348
373
  cardType,
349
374
  serverFile,
350
375
  clientFile,
351
- serverRelativeFile: path5.relative(serverDir, serverFile).split(path5.sep).join("/"),
352
- clientRelativeFile: path5.relative(clientDir, clientFile).split(path5.sep).join("/")
376
+ clientRelativeFile: path5.relative(clientDir, clientFile).split(path5.sep).join("/"),
377
+ view: false,
378
+ serverRelativeFile
353
379
  });
354
380
  }
355
381
  return out;
@@ -359,14 +385,17 @@ async function scanAppPrimitives(root) {
359
385
  return {
360
386
  tools: await scanToolDir(path5.join(appDir, "server", "src", "tools")),
361
387
  skills: await scanSkillDir(path5.join(appDir, "server", "src", "skills")),
362
- cards: await scanCardDirs(path5.join(appDir, "server", "src", "cards"), path5.join(appDir, "client", "src", "cards"))
388
+ cards: await scanCardDirs(path5.join(appDir, "server", "src", "cards"), path5.join(appDir, "client", "src", "cards")),
389
+ actions: await scanActionDir(path5.join(appDir, "server", "src", "actions"))
363
390
  };
364
391
  }
365
392
  async function scanModulePrimitives(moduleDir) {
366
393
  return {
367
394
  tools: await scanToolDir(path5.join(moduleDir, "src", "server", "tools")),
368
395
  skills: await scanSkillDir(path5.join(moduleDir, "src", "server", "skills")),
369
- cards: await scanCardDirs(path5.join(moduleDir, "src", "server", "cards"), path5.join(moduleDir, "src", "client", "cards"))
396
+ cards: await scanCardDirs(path5.join(moduleDir, "src", "server", "cards"), path5.join(moduleDir, "src", "client", "cards")),
397
+ // 模块动作走 serverModule.register 里的 ctx.cardActions,不经文件约定
398
+ actions: []
370
399
  };
371
400
  }
372
401
  function assertUnique(items, code, label) {
@@ -420,7 +449,12 @@ function validateDescriptor(raw, dir) {
420
449
  const value = raw;
421
450
  if (value.schemaVersion !== 1) throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `tbox.module.json schemaVersion 必须为 1: ${dir}`);
422
451
  if (typeof value.id !== "string" || !value.id) throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `tbox.module.json 缺少 id: ${dir}`);
423
- if (typeof value.version !== "string" || !value.version) throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `tbox.module.json 缺少 version: ${dir}`);
452
+ const manifestFile = path6.join(dir, "package.json");
453
+ const manifestVersion = existsSync4(manifestFile) ? readJsonSync(manifestFile).version : void 0;
454
+ const descriptorVersion = typeof value.version === "string" && value.version ? value.version : void 0;
455
+ const version = typeof manifestVersion === "string" && manifestVersion ? manifestVersion : descriptorVersion;
456
+ if (!version) throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `模块版本未知(package.json 与 tbox.module.json 都没有 version): ${dir}`);
457
+ value.version = version;
424
458
  const dirName = path6.basename(dir);
425
459
  if (value.id !== dirName) throw new AppBuildError("MODULE_ID_MISMATCH", `模块 id "${value.id}" 必须等于目录名 "${dirName}"`, { file: path6.join(dir, "tbox.module.json") });
426
460
  if (!value.declare || typeof value.declare !== "object") throw new AppBuildError("MODULE_DESCRIPTOR_INVALID", `tbox.module.json 缺少 declare: ${dir}`);
@@ -524,7 +558,8 @@ var APPS_DIR = "apps";
524
558
  var CLIENT_DIR = "apps/client";
525
559
  var SERVER_DIR = "apps/server";
526
560
  var SHELL_FILE = "apps/client/index.html";
527
- var CARD_PREVIEW_PAGE_FILE = "apps/client/src/platform/card-preview-page.tsx";
561
+ var APP_CONFIG_FILE = "apps/client/src/app.config.ts";
562
+ var ENTRY_OVERRIDE_FILE = "apps/client/src/entry.tsx";
528
563
 
529
564
  // src/scan.ts
530
565
  async function scanApp(root) {
@@ -538,6 +573,7 @@ async function scanApp(root) {
538
573
  assertUnique(primitives.tools, "TOOL_ID_DUPLICATE", "工具 ID");
539
574
  assertUnique(primitives.skills, "SKILL_ID_DUPLICATE", "技能 ID");
540
575
  assertUnique(primitives.cards, "CARD_TYPE_DUPLICATE", "卡片类型");
576
+ assertUnique(primitives.actions, "ACTION_ID_DUPLICATE", "动作 ID");
541
577
  if (meta.appKind === "web") {
542
578
  const hasAgentSurface = primitives.tools.length > 0 || primitives.skills.length > 0 || primitives.cards.length > 0;
543
579
  if (hasAgentSurface) {
@@ -574,14 +610,16 @@ async function scanApp(root) {
574
610
  tools: primitives.tools,
575
611
  skills: primitives.skills,
576
612
  cards: primitives.cards,
613
+ actions: primitives.actions,
577
614
  modules
578
615
  };
579
616
  }
580
617
 
581
618
  // src/generate.ts
582
619
  import path8 from "path";
583
- import { existsSync as existsSync5 } from "fs";
620
+ import { existsSync as existsSync5, readdirSync } from "fs";
584
621
  import { watch as fsWatch } from "fs";
622
+ import ts2 from "typescript";
585
623
  function pageDocument(route) {
586
624
  if (route === "/") return "index.html";
587
625
  if (route === "/_tbox/card-preview") return "_tbox/card-preview.html";
@@ -592,17 +630,18 @@ function pageRank(route) {
592
630
  if (route === "/_tbox/card-preview") return 2;
593
631
  return 1;
594
632
  }
595
- function buildManifest(scan) {
633
+ var defaultEntryFor = (pageId2) => `/.tbox-gen/entries/${pageId2}.tsx`;
634
+ function buildManifest(scan, entryFor = defaultEntryFor) {
596
635
  const pages = scan.pages.map((page) => ({
597
636
  path: page.route,
598
- entry: `/.tbox-gen/entries/${page.id}.tsx`,
637
+ entry: entryFor(page.id),
599
638
  document: pageDocument(page.route),
600
639
  title: page.meta.title
601
640
  }));
602
641
  if (scan.appKind === "agent") {
603
642
  pages.push({
604
643
  path: "/_tbox/card-preview",
605
- entry: "/.tbox-gen/entries/card-preview.tsx",
644
+ entry: entryFor("card-preview"),
606
645
  document: "_tbox/card-preview.html",
607
646
  title: "卡片预览"
608
647
  });
@@ -645,6 +684,7 @@ function buildServerRegistry(genDir, scan) {
645
684
  scan.tools.forEach((tool, i) => lines.push(`import { tool as tool${i} } from '${relativePosix(file, tool.file)}';`));
646
685
  scan.skills.forEach((skill, i) => lines.push(`import { skill as skill${i} } from '${relativePosix(file, skill.file)}';`));
647
686
  scan.cards.forEach((card, i) => lines.push(`import { card as card${i} } from '${relativePosix(file, card.serverFile)}';`));
687
+ scan.actions.forEach((action, i) => lines.push(`import { action as action${i} } from '${relativePosix(file, action.file)}';`));
648
688
  serverModules.forEach((mod, i) => lines.push(`import { serverModule as module${i} } from '${relativePosix(file, path8.join(mod.dir, "src/server/index.ts"))}';`));
649
689
  lines.push("");
650
690
  lines.push("export const functions = {");
@@ -656,17 +696,85 @@ function buildServerRegistry(genDir, scan) {
656
696
  lines.push("export const cards = {");
657
697
  scan.cards.forEach((card, i) => lines.push(` '${card.cardType}': card${i},`));
658
698
  lines.push("};");
699
+ lines.push("export const actions = {");
700
+ scan.actions.forEach((action, i) => lines.push(` '${action.id}': action${i},`));
701
+ lines.push("};");
659
702
  lines.push(`export const modules = [${serverModules.map((_, i) => `module${i}`).join(", ")}];`);
660
703
  lines.push("");
661
- lines.push("export const registry = { functions, tools, skills, cards, modules };");
704
+ lines.push("export const registry = { functions, tools, skills, cards, actions, modules };");
662
705
  lines.push("");
663
706
  return lines.join("\n");
664
707
  }
708
+ async function collectObservedCardTypes(scan) {
709
+ const files = [...scan.tools.map((tool) => tool.file), ...scan.actions.map((action) => action.file)];
710
+ for (const mod of scan.modules) {
711
+ for (const sub of ["src/server", "src/client"]) {
712
+ const dir = path8.join(mod.dir, sub);
713
+ if (!existsSync5(dir)) continue;
714
+ for (const entry of readdirSync(dir, { recursive: true, withFileTypes: true })) {
715
+ if (!entry.isFile() || !/\.(ts|tsx)$/.test(entry.name)) continue;
716
+ files.push(path8.join(entry.parentPath ?? dir, entry.name));
717
+ }
718
+ }
719
+ }
720
+ const observed = /* @__PURE__ */ new Set();
721
+ for (const file of files) {
722
+ let text;
723
+ try {
724
+ text = await readText(file);
725
+ } catch {
726
+ continue;
727
+ }
728
+ const source = parseSource(file, text);
729
+ const visit = (node) => {
730
+ if (ts2.isPropertyAssignment(node) && propertyName(node.name) === "cardType") {
731
+ const init = node.initializer;
732
+ if (ts2.isStringLiteral(init) || ts2.isNoSubstitutionTemplateLiteral(init)) observed.add(init.text);
733
+ }
734
+ ts2.forEachChild(node, visit);
735
+ };
736
+ visit(source);
737
+ }
738
+ return [...observed].sort();
739
+ }
740
+ function buildAppRegistry(scan, observed) {
741
+ const declared = [...new Set(scan.cards.map((card) => card.cardType))].sort();
742
+ const union = declared.length > 0 ? declared.map((type) => `'${type}'`).join(" | ") : "string";
743
+ const lines = [
744
+ "// @generated by @tbox.cn/app-build; do not edit.",
745
+ "",
746
+ `export type AppCardType = ${union};`,
747
+ ""
748
+ ];
749
+ if (observed.length > 0) {
750
+ lines.push("// C1:源码里出现的 cardType 字面量。任何一项不在 AppCardType 里,类型检查会报错并列出合法取值。");
751
+ lines.push(`const observedCardTypes: AppCardType[] = [${observed.map((type) => `'${type}'`).join(", ")}];`);
752
+ lines.push("void observedCardTypes;");
753
+ lines.push("");
754
+ }
755
+ return lines.join("\n");
756
+ }
757
+ function buildViewCardStub(cardType) {
758
+ return [
759
+ "// @generated by @tbox.cn/app-build; do not edit.",
760
+ "import type { CardView } from '@tbox.cn/app-contracts';",
761
+ "import { ViewCard, defineCard } from '@tbox.cn/app-agent-ui-kit';",
762
+ "",
763
+ "function View(props: { data: unknown; cardId: string; isHistory: boolean; actionTokens?: Record<string, string> }) {",
764
+ " return (",
765
+ " <ViewCard view={props.data as CardView} cardId={props.cardId} isHistory={props.isHistory} actionTokens={props.actionTokens} />",
766
+ " );",
767
+ "}",
768
+ "",
769
+ "export const card = defineCard({ type: '" + cardType + "', actions: 'self' }, View);",
770
+ ""
771
+ ].join("\n");
772
+ }
665
773
  function buildClientRegistry(genDir, scan) {
666
774
  const file = path8.join(genDir, "registry.client.ts");
667
775
  const lines = ["// @generated by @tbox.cn/app-build; do not edit."];
668
776
  const clientModules = scan.modules.filter((mod) => mod.hasClient);
669
- scan.cards.forEach((card, i) => lines.push(`import { card as card${i} } from '${relativePosix(file, card.clientFile)}';`));
777
+ scan.cards.forEach((card, i) => lines.push(`import { card as card${i} } from '${relativePosix(file, card.view ? path8.join(genDir, "cards", card.cardType + ".tsx") : card.clientFile)}';`));
670
778
  clientModules.forEach((mod, i) => lines.push(`import { clientModule as module${i} } from '${relativePosix(file, path8.join(mod.dir, "src/client/index.ts"))}';`));
671
779
  lines.push("");
672
780
  lines.push("export const cards = {");
@@ -677,66 +785,112 @@ function buildClientRegistry(genDir, scan) {
677
785
  lines.push("");
678
786
  return lines.join("\n");
679
787
  }
680
- function buildEntry(genDir, scan, pageId2, pageFile, cardPreview = false) {
788
+ function buildEntry(root, genDir, scan, pageId2, pageFile, cardPreview = false) {
681
789
  const file = path8.join(genDir, "entries", `${pageId2}.tsx`);
682
- const pageImport = relativePosix(file, pageFile);
683
- const mountImport = relativePosix(file, path8.join(scan.root, "apps", "client", "src", "platform", "mount-page.tsx"));
790
+ const configImport = relativePosix(file, path8.join(root, "apps", "client", "src", "app.config.ts"));
684
791
  const registryImport = relativePosix(file, path8.join(genDir, "registry.client.ts"));
685
- const mountCall = cardPreview ? "mountPage(Page, { shell: false });" : "mountPage(Page);";
792
+ if (cardPreview) {
793
+ return [
794
+ "// @generated by @tbox.cn/app-build; do not edit.",
795
+ `import config from '${configImport}';`,
796
+ `import { modules, cards } from '${registryImport}';`,
797
+ "import { startCardPreview } from '@tbox.cn/app-agent-sdk-client/app/card-preview';",
798
+ "",
799
+ "void startCardPreview({ config, modules, cards });",
800
+ ""
801
+ ].join("\n");
802
+ }
803
+ const pageImport = relativePosix(file, pageFile);
804
+ const isAgent = scan.appKind === "agent";
805
+ const startName = isAgent ? "startAgentApp" : "startApp";
806
+ const startImport = isAgent ? "@tbox.cn/app-agent-sdk-client/app" : "@tbox.cn/app-sdk-client/app";
686
807
  return [
687
808
  "// @generated by @tbox.cn/app-build; do not edit.",
688
- "import { registerClientModules, registerClientCards } from '@tbox.cn/app-sdk-client';",
809
+ // app.config 必须第一个 import:模块顶层 auth 单例先于 registry 的 module 顶层执行。
810
+ `import config from '${configImport}';`,
689
811
  `import { modules, cards } from '${registryImport}';`,
690
- `import { mountPage } from '${mountImport}';`,
691
- "",
692
- "registerClientCards(cards);",
812
+ `import { ${startName} } from '${startImport}';`,
693
813
  "",
694
- "async function start() {",
695
- " try {",
696
- " await registerClientModules(modules);",
697
- ` const { default: Page } = await import('${pageImport}');`,
698
- ` ${mountCall}`,
699
- " } catch (error) {",
700
- " console.error('[app-build] page bootstrap failed', error);",
701
- " }",
702
- "}",
703
- "",
704
- "void start();",
814
+ `void ${startName}({`,
815
+ " config,",
816
+ " modules,",
817
+ " cards,",
818
+ ` page: () => import('${pageImport}'),`,
819
+ "});",
705
820
  ""
706
821
  ].join("\n");
707
822
  }
708
823
  async function generateCore(root, shell, scan) {
709
824
  const genDir = path8.join(root, "apps", "client", ".tbox-gen");
825
+ const manifestFile = path8.join(genDir, "manifest.json");
826
+ const appConfigFile = path8.join(root, "apps", "client", "src", "app.config.ts");
827
+ const overrideFile = path8.join(root, "apps", "client", "src", "entry.tsx");
828
+ const useOverride = existsSync5(overrideFile);
829
+ if (!useOverride && !existsSync5(appConfigFile)) {
830
+ throw new AppBuildError(
831
+ "APP_CONFIG_MISSING",
832
+ "缺少 apps/client/src/app.config.ts(客户端装配真源)",
833
+ { file: appConfigFile }
834
+ );
835
+ }
836
+ const entryFor = (pageId2) => useOverride ? "/src/entry.tsx" : `/.tbox-gen/entries/${pageId2}.tsx`;
837
+ const manifest = buildManifest(scan, entryFor);
838
+ await removeFile(manifestFile);
710
839
  const files = [];
711
840
  const write = async (file, text) => {
712
841
  await writeTextIfChanged(file, text);
713
842
  files.push(file);
714
843
  };
715
- const manifest = buildManifest(scan);
716
- await write(path8.join(genDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}
717
- `);
718
- await write(path8.join(genDir, "app-kind.ts"), `export const appKind = '${scan.appKind}' as const;
719
- `);
844
+ const observedCardTypes = await collectObservedCardTypes(scan);
845
+ await write(path8.join(genDir, "app-registry.ts"), buildAppRegistry(scan, observedCardTypes));
720
846
  await write(path8.join(genDir, "registry.server.ts"), buildServerRegistry(genDir, scan));
721
- await write(path8.join(genDir, "registry.client.ts"), buildClientRegistry(genDir, scan));
722
- for (const page of scan.pages) {
723
- await write(path8.join(genDir, "entries", `${page.id}.tsx`), buildEntry(genDir, scan, page.id, page.file));
724
- const doc = renderDocument(shell, page.meta.title, page.meta.meta, `/.tbox-gen/entries/${page.id}.tsx`);
725
- await write(path8.join(genDir, "documents", pageDocument(page.route)), doc);
847
+ const cardsDir = path8.join(genDir, "cards");
848
+ const keepStubs = new Set(scan.cards.filter((item) => item.view).map((item) => item.cardType + ".tsx"));
849
+ if (existsSync5(cardsDir)) {
850
+ for (const name of readdirSync(cardsDir)) {
851
+ if (!keepStubs.has(name)) await removeFile(path8.join(cardsDir, name));
852
+ }
726
853
  }
727
- if (scan.appKind === "agent") {
728
- const pageFile = path8.join(root, "apps", "client", "src", "platform", "card-preview-page.tsx");
729
- if (!existsSync5(pageFile)) {
730
- throw new AppBuildError("CARD_PREVIEW_PAGE_MISSING", "agent 应用缺少 apps/client/src/platform/card-preview-page.tsx", { file: pageFile });
854
+ for (const card of scan.cards.filter((item) => item.view)) {
855
+ await write(path8.join(cardsDir, card.cardType + ".tsx"), buildViewCardStub(card.cardType));
856
+ }
857
+ await write(path8.join(genDir, "registry.client.ts"), buildClientRegistry(genDir, scan));
858
+ const writeDocuments = async () => {
859
+ for (const page of scan.pages) {
860
+ await write(
861
+ path8.join(genDir, "documents", pageDocument(page.route)),
862
+ renderDocument(shell, page.meta.title, page.meta.meta, entryFor(page.id))
863
+ );
864
+ }
865
+ if (scan.appKind === "agent") {
866
+ await write(
867
+ path8.join(genDir, "documents", "_tbox/card-preview.html"),
868
+ renderDocument(shell, "卡片预览", void 0, entryFor("card-preview"))
869
+ );
870
+ }
871
+ };
872
+ if (!useOverride) {
873
+ for (const page of scan.pages) {
874
+ await write(
875
+ path8.join(genDir, "entries", `${page.id}.tsx`),
876
+ buildEntry(root, genDir, scan, page.id, page.file)
877
+ );
878
+ }
879
+ if (scan.appKind === "agent") {
880
+ await write(
881
+ path8.join(genDir, "entries", "card-preview.tsx"),
882
+ buildEntry(root, genDir, scan, "card-preview", "", true)
883
+ );
731
884
  }
732
- await write(path8.join(genDir, "entries", "card-preview.tsx"), buildEntry(genDir, scan, "card-preview", pageFile, true));
733
- const doc = renderDocument(shell, "卡片预览", void 0, "/.tbox-gen/entries/card-preview.tsx");
734
- await write(path8.join(genDir, "documents", "_tbox/card-preview.html"), doc);
735
885
  }
886
+ await writeDocuments();
736
887
  const generated = new Set(files.map((file) => path8.resolve(file)));
888
+ generated.add(path8.resolve(manifestFile));
737
889
  for (const file of await listFiles(genDir)) {
738
890
  if (!generated.has(path8.resolve(file))) await removeFile(file);
739
891
  }
892
+ await write(manifestFile, `${JSON.stringify(manifest, null, 2)}
893
+ `);
740
894
  return { files, manifest };
741
895
  }
742
896
  async function generateApp(options) {
@@ -770,7 +924,7 @@ async function generateApp(options) {
770
924
  const name = filename?.toString().split(path8.sep).join("/") ?? "";
771
925
  if (!name) return;
772
926
  if (name.startsWith("apps/client/.tbox-gen/") || name.startsWith("node_modules/") || name.startsWith(".git/")) return;
773
- const relevant = name === ".tbox/app.json" || name === "apps/client/index.html" || name.startsWith("apps/client/src/pages/") || name.startsWith("apps/server/src/") || name.startsWith("modules/");
927
+ const relevant = name === ".tbox/app.json" || name === "apps/client/index.html" || name === "apps/client/src/app.config.ts" || name === "apps/client/src/entry.tsx" || name.startsWith("apps/client/src/pages/") || name.startsWith("apps/server/src/") || name.startsWith("modules/");
774
928
  if (!relevant) return;
775
929
  if (timer) clearTimeout(timer);
776
930
  timer = setTimeout(() => void regenerate(), 50);
@@ -833,15 +987,16 @@ async function checkApp(options) {
833
987
  if (!existsSync6(path9.join(root, SHELL_FILE))) {
834
988
  issues.push({ code: "APP_INDEX_MISSING", severity: "error", file: path9.join(root, SHELL_FILE), message: `缺少 ${SHELL_FILE}` });
835
989
  }
836
- try {
837
- const meta = await readAppMeta(root);
838
- if (meta.appKind === "agent") {
839
- const preview = path9.join(root, CARD_PREVIEW_PAGE_FILE);
840
- if (!existsSync6(preview)) {
841
- issues.push({ code: "CARD_PREVIEW_PAGE_MISSING", severity: "error", file: preview, message: `agent 应用缺少 ${CARD_PREVIEW_PAGE_FILE}` });
842
- }
843
- }
844
- } catch {
990
+ const appConfig = path9.join(root, APP_CONFIG_FILE);
991
+ const entryOverride = path9.join(root, ENTRY_OVERRIDE_FILE);
992
+ if (!existsSync6(appConfig) && !existsSync6(entryOverride)) {
993
+ issues.push({
994
+ code: "APP_CONFIG_MISSING",
995
+ severity: "error",
996
+ file: appConfig,
997
+ message: `缺少 ${APP_CONFIG_FILE}(或 ${ENTRY_OVERRIDE_FILE} 全量接管入口)`,
998
+ fix: "从模板复制 app.config.ts;需要完全自定义入口时创建 src/entry.tsx"
999
+ });
845
1000
  }
846
1001
  const pagesDir = path9.join(root, CLIENT_DIR, "src", "pages");
847
1002
  for (const file of await listFiles(pagesDir)) {
@@ -865,90 +1020,71 @@ async function checkApp(options) {
865
1020
  return { ok: issues.every((issue) => issue.severity !== "error"), issues };
866
1021
  }
867
1022
 
868
- // src/agents.ts
869
- import path10 from "path";
870
- import { existsSync as existsSync7 } from "fs";
871
- import { fileURLToPath } from "url";
872
- var BLOCK_BEGIN = "<!-- tbox:agents:begin -->";
873
- var BLOCK_END = "<!-- tbox:agents:end -->";
874
- function fragmentDir() {
875
- return fileURLToPath(new URL("../agents/", import.meta.url));
876
- }
877
- async function readFragment(name) {
878
- const file = path10.join(fragmentDir(), name);
879
- if (!existsSync7(file)) throw new Error(`app-build AGENTS fragment missing: ${file}`);
880
- return (await readText(file)).trim();
881
- }
882
- async function composeAgents(options) {
883
- const kind = options.appKind;
884
- const root = [
885
- await readFragment("base.md"),
886
- await readFragment(`kind-${kind}.md`)
887
- ].join("\n\n");
888
- const app = [
889
- await readFragment("app-base.md"),
890
- await readFragment(`app-${kind}.md`)
891
- ].join("\n\n");
892
- const modules = options.hasModules ? (await readText(path10.join(fragmentDir(), "modules.md"))).trim() : void 0;
893
- return {
894
- root: wrapBlock(root),
895
- app: wrapBlock(app),
896
- ...modules ? { modules: wrapBlock(modules) } : {}
897
- };
898
- }
899
- function wrapBlock(content) {
900
- return `${BLOCK_BEGIN}
901
- ${content.trim()}
902
- ${BLOCK_END}`;
903
- }
904
- function extractOverlay(existing) {
905
- const start = existing.indexOf(BLOCK_BEGIN);
906
- const end = existing.indexOf(BLOCK_END);
907
- if (start === -1 || end === -1 || end < start) return existing.trim();
908
- return `${existing.slice(0, start)}${existing.slice(end + BLOCK_END.length)}`.trim();
909
- }
910
- function replaceBlock(existing, content) {
911
- const start = existing.indexOf(BLOCK_BEGIN);
912
- const end = existing.indexOf(BLOCK_END);
913
- if (start === -1 || end === -1 || end < start) {
914
- const overlay = existing.trim();
915
- return overlay ? `${overlay}
916
-
917
- ${content}
918
- ` : `${content}
919
- `;
920
- }
921
- const before = existing.slice(0, start).trimEnd();
922
- const after = existing.slice(end + BLOCK_END.length).trimStart();
923
- return [before, content, after].filter(Boolean).join("\n\n") + "\n";
924
- }
925
- async function syncAgents(options) {
926
- const composed = await composeAgents(options);
927
- const targets = [
928
- [path10.join(options.root, "AGENTS.md"), composed.root],
929
- [path10.join(options.root, "apps", "AGENTS.md"), composed.app]
930
- ];
931
- if (composed.modules) targets.push([path10.join(options.root, "modules", "AGENTS.md"), composed.modules]);
932
- const written = [];
933
- for (const [file, block] of targets) {
934
- const exists = existsSync7(file);
935
- const existing = exists ? await readText(file) : "";
936
- if (existing && !existing.includes(BLOCK_BEGIN) && !options.allowAppend) {
937
- throw new Error(`${file} 缺少 ${BLOCK_BEGIN}(拒绝覆盖用户内容;加 --append 或手动加 block)`);
1023
+ // src/card-samples.ts
1024
+ import { existsSync as existsSync7, readFileSync as readFileSync2 } from "fs";
1025
+ function readCardSamples(file) {
1026
+ const issues = [];
1027
+ if (!existsSync7(file)) return { samples: [], issues: [`文件不存在: ${file}`] };
1028
+ const text = readFileSync2(file, "utf8");
1029
+ const sf = parseSource(file, text);
1030
+ const exported = findExportedVariable(sf, "card");
1031
+ if (!exported) return { samples: [], issues: ["没有找到 export const card"] };
1032
+ let object;
1033
+ try {
1034
+ object = objectFromExpression(exported, file);
1035
+ } catch (error) {
1036
+ return { samples: [], issues: [`卡片声明不是静态对象字面量: ${error.message}`] };
1037
+ }
1038
+ let cardType;
1039
+ const typeNode = getProperty(object, "cardType");
1040
+ if (typeNode) {
1041
+ try {
1042
+ const value = literalToJson(typeNode, file);
1043
+ if (typeof value === "string") cardType = value;
1044
+ } catch {
1045
+ issues.push("cardType 不是静态字面量");
1046
+ }
1047
+ }
1048
+ const samples = [];
1049
+ const sampleData = getProperty(object, "sampleData");
1050
+ if (sampleData) {
1051
+ try {
1052
+ samples.push({ label: "sampleData", data: literalToJson(sampleData, file) });
1053
+ } catch (error) {
1054
+ issues.push(`sampleData 不是静态字面量: ${error.message}`);
938
1055
  }
939
- await writeText(file, replaceBlock(existing, block));
940
- written.push(file);
941
1056
  }
942
- return written;
1057
+ const extra = getProperty(object, "samples");
1058
+ if (extra) {
1059
+ try {
1060
+ const list = literalToJson(extra, file);
1061
+ if (Array.isArray(list)) {
1062
+ list.forEach((entry, index) => {
1063
+ const row = entry ?? {};
1064
+ samples.push({
1065
+ ...typeof row.label === "string" ? { label: row.label } : { label: `samples[${index}]` },
1066
+ ...typeof row.note === "string" ? { note: row.note } : {},
1067
+ data: row.data
1068
+ });
1069
+ });
1070
+ } else {
1071
+ issues.push("samples 不是数组");
1072
+ }
1073
+ } catch (error) {
1074
+ issues.push(`samples 不是静态字面量: ${error.message}`);
1075
+ }
1076
+ }
1077
+ if (samples.length === 0) issues.push("没有可用样例(补 sampleData)");
1078
+ return { cardType, samples, issues };
943
1079
  }
944
1080
 
945
1081
  // src/vite-plugin.ts
946
- import path11 from "path";
947
- import { existsSync as existsSync8, readFileSync } from "fs";
1082
+ import path10 from "path";
1083
+ import { existsSync as existsSync8, readFileSync as readFileSync3 } from "fs";
948
1084
  function readManifest(root) {
949
- const file = path11.join(root, "apps", "client", ".tbox-gen", "manifest.json");
1085
+ const file = path10.join(root, "apps", "client", ".tbox-gen", "manifest.json");
950
1086
  if (!existsSync8(file)) throw new Error(`[tbox-app] 缺少 ${file};先运行 generate`);
951
- return JSON.parse(readFileSync(file, "utf8"));
1087
+ return JSON.parse(readFileSync3(file, "utf8"));
952
1088
  }
953
1089
  function pageId(pagePath) {
954
1090
  if (pagePath === "/") return "index";
@@ -964,21 +1100,29 @@ function inject(html, title, entry) {
964
1100
  return out;
965
1101
  }
966
1102
  function tboxAppPlugin(options = {}) {
967
- let root = options.root ? path11.resolve(options.root) : "";
1103
+ let root = options.root ? path10.resolve(options.root) : "";
968
1104
  const getManifest = () => {
969
1105
  if (options.getManifest) return options.getManifest();
970
1106
  return readManifest(root);
971
1107
  };
1108
+ const getManifestSafe = () => {
1109
+ try {
1110
+ return getManifest();
1111
+ } catch {
1112
+ return null;
1113
+ }
1114
+ };
972
1115
  return {
973
1116
  name: "tbox-app",
974
1117
  enforce: "post",
975
1118
  config(config) {
976
- const viteRoot = config.root ? path11.resolve(config.root) : process.cwd();
977
- root = options.root ? path11.resolve(options.root) : path11.dirname(viteRoot);
978
- const current = getManifest();
1119
+ const viteRoot = config.root ? path10.resolve(config.root) : process.cwd();
1120
+ root = options.root ? path10.resolve(options.root) : path10.dirname(viteRoot);
1121
+ const current = getManifestSafe();
1122
+ if (!current) throw new Error("[tbox-app] 缺少 .tbox-gen/manifest.json;先运行 generate");
979
1123
  const input = {};
980
1124
  for (const page of current.pages) {
981
- input[pageId(page.path)] = path11.join(root, "apps", "client", ".tbox-gen", "documents", page.document);
1125
+ input[pageId(page.path)] = path10.join(root, "apps", "client", ".tbox-gen", "documents", page.document);
982
1126
  }
983
1127
  return {
984
1128
  build: {
@@ -994,17 +1138,20 @@ function tboxAppPlugin(options = {}) {
994
1138
  if (!ctx.server) return html;
995
1139
  const url = (ctx.originalUrl || ctx.path || "/").split("?")[0];
996
1140
  const normalized = url !== "/" && url.endsWith("/") ? url.slice(0, -1) : url;
997
- const page = getManifest().pages.find((item) => item.path === normalized);
1141
+ const current = getManifestSafe();
1142
+ if (!current) return html;
1143
+ const page = current.pages.find((item) => item.path === normalized);
998
1144
  if (!page) return html;
999
1145
  const entry = page.entry ?? `/.tbox-gen/entries/${pageId(page.path)}.tsx`;
1000
1146
  return inject(html, page.title, entry);
1001
1147
  }
1002
1148
  },
1003
1149
  generateBundle(_outputOptions, bundle) {
1004
- const current = getManifest();
1005
- const byDocument = new Map(current.pages.map((page) => [`.tbox-gen/documents/${page.document}`.split(path11.sep).join("/"), page.document]));
1150
+ const current = getManifestSafe();
1151
+ if (!current) return;
1152
+ const byDocument = new Map(current.pages.map((page) => [`.tbox-gen/documents/${page.document}`.split(path10.sep).join("/"), page.document]));
1006
1153
  for (const [fileName, asset] of Object.entries(bundle)) {
1007
- const normalized = fileName.split(path11.sep).join("/");
1154
+ const normalized = fileName.split(path10.sep).join("/");
1008
1155
  const target = byDocument.get(normalized);
1009
1156
  if (!target) continue;
1010
1157
  delete bundle[fileName];
@@ -1014,25 +1161,123 @@ function tboxAppPlugin(options = {}) {
1014
1161
  }
1015
1162
  };
1016
1163
  }
1164
+
1165
+ // src/tailwind-sources.ts
1166
+ import path12 from "path";
1167
+
1168
+ // tailwind-sources.mjs
1169
+ import { existsSync as existsSync9, readdirSync as readdirSync2, realpathSync, statSync } from "fs";
1170
+ import path11 from "path";
1171
+ var MODULE_ROOTS = [
1172
+ { dir: "modules", prefixes: ["module-"] },
1173
+ { dir: "apps/client/node_modules/@tbox.cn", prefixes: ["app-module-", "module-"] }
1174
+ ];
1175
+ function collectModuleSourceDirs(appRoot) {
1176
+ const root = path11.resolve(appRoot);
1177
+ const seen = /* @__PURE__ */ new Set();
1178
+ const out = [];
1179
+ for (const { dir, prefixes } of MODULE_ROOTS) {
1180
+ const base = path11.join(root, dir);
1181
+ if (!existsSync9(base)) continue;
1182
+ for (const name of readdirSync2(base).sort()) {
1183
+ if (!prefixes.some((prefix) => name.startsWith(prefix))) continue;
1184
+ const moduleDir = path11.join(base, name);
1185
+ const clientDir = path11.join(moduleDir, "src/client");
1186
+ let real;
1187
+ try {
1188
+ if (!statSync(moduleDir).isDirectory()) continue;
1189
+ if (!existsSync9(path11.join(clientDir, "index.ts"))) continue;
1190
+ real = realpathSync(clientDir);
1191
+ } catch {
1192
+ continue;
1193
+ }
1194
+ if (seen.has(real)) continue;
1195
+ seen.add(real);
1196
+ out.push(clientDir);
1197
+ }
1198
+ }
1199
+ return out.sort();
1200
+ }
1201
+ function renderModuleSources(dirs) {
1202
+ return dirs.map((dir) => `@source ${JSON.stringify(dir.split(path11.sep).join("/"))};`).join("\n");
1203
+ }
1204
+
1205
+ // src/tailwind-sources.ts
1206
+ var TAILWIND_ENTRY = "/apps/client/src/styles/tailwind.css";
1207
+ function isTailwindEntry(id) {
1208
+ const file = id.split("?")[0].replace(/\\/g, "/");
1209
+ return file.endsWith(TAILWIND_ENTRY) || file === "/src/styles/tailwind.css";
1210
+ }
1211
+ function tboxModuleSourcesPlugin(options) {
1212
+ const appRoot = path12.resolve(options.appRoot);
1213
+ return {
1214
+ name: "tbox-module-sources",
1215
+ enforce: "pre",
1216
+ transform(code, id) {
1217
+ if (!isTailwindEntry(id)) return null;
1218
+ const sources = renderModuleSources(collectModuleSourceDirs(appRoot));
1219
+ return sources ? `${code}
1220
+ ${sources}
1221
+ ` : null;
1222
+ }
1223
+ };
1224
+ }
1225
+
1226
+ // src/vendor-layer.ts
1227
+ var DEFAULT_MATCHERS = [
1228
+ /node_modules\/yet-another-react-lightbox\//,
1229
+ /node_modules\/\.pnpm\/yet-another-react-lightbox@/,
1230
+ /node_modules\/antd-mobile\//,
1231
+ /node_modules\/\.pnpm\/antd-mobile@/
1232
+ ];
1233
+ function wrapVendorCss(css) {
1234
+ if (!css.trim()) return css;
1235
+ if (/^\s*@layer\s+vendor\b/.test(css)) return css;
1236
+ const hoisted = [];
1237
+ let body = css;
1238
+ for (; ; ) {
1239
+ const match = /^\s*(@charset[^;]*;|@import[^;]*;)/i.exec(body);
1240
+ if (!match) break;
1241
+ hoisted.push(match[1].trim());
1242
+ body = body.slice(match[0].length);
1243
+ }
1244
+ const wrapped = `@layer vendor {
1245
+ ${body.trim()}
1246
+ }`;
1247
+ return hoisted.length > 0 ? `${hoisted.join("\n")}
1248
+ ${wrapped}` : wrapped;
1249
+ }
1250
+ function tboxVendorLayerPlugin(options = {}) {
1251
+ const matchers = options.match ?? DEFAULT_MATCHERS;
1252
+ return {
1253
+ name: "tbox-vendor-layer",
1254
+ enforce: "pre",
1255
+ transform(code, id) {
1256
+ const file = id.split("?")[0].replace(/\\/g, "/");
1257
+ if (!file.endsWith(".css")) return null;
1258
+ if (!matchers.some((matcher) => matcher.test(file))) return null;
1259
+ return { code: wrapVendorCss(code), map: null };
1260
+ }
1261
+ };
1262
+ }
1017
1263
  export {
1018
1264
  AppBuildError,
1019
1265
  FUNCTION_ID_RE,
1020
1266
  buildManifest,
1021
1267
  checkApp,
1022
- composeAgents,
1023
- extractOverlay,
1024
1268
  generateApp,
1025
1269
  listGeneratedFiles,
1026
1270
  parsePageMeta,
1027
1271
  readAppMeta,
1028
- replaceBlock,
1272
+ readCardSamples,
1029
1273
  scanApp,
1030
1274
  scanAppPrimitives,
1031
1275
  scanFunctions,
1032
1276
  scanModulePrimitives,
1033
1277
  scanModules,
1034
1278
  scanPages,
1035
- syncAgents,
1036
1279
  tboxAppPlugin,
1037
- wrapBlock
1280
+ tboxModuleSourcesPlugin,
1281
+ tboxVendorLayerPlugin,
1282
+ wrapVendorCss
1038
1283
  };