@tbox.cn/app-build 1.0.0-alpha.7 → 1.0.0-alpha.9

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/README.md CHANGED
@@ -12,7 +12,13 @@ tbox-app 1.0 构建期叶子包。负责:
12
12
  ## API
13
13
 
14
14
  ```ts
15
- import { generateApp, checkApp, tboxAppPlugin } from '@tbox.cn/app-build';
15
+ import { generateApp, checkApp, tboxAppPlugin, tboxModuleSourcesPlugin } from '@tbox.cn/app-build';
16
+ ```
17
+
18
+ Tailwind 模块源码发现走独立子路径(Node ESM 可直接 import,供证据包使用):
19
+
20
+ ```ts
21
+ import { collectModuleSourceDirs, renderModuleSources } from '@tbox.cn/app-build/tailwind-sources';
16
22
  ```
17
23
 
18
24
  ```ts
package/dist/index.d.ts CHANGED
@@ -62,9 +62,12 @@ interface ActionModule {
62
62
  interface CardModule {
63
63
  cardType: string;
64
64
  serverFile: string;
65
- clientFile: string;
65
+ /** 视图卡没有客户端文件:客户端 stub 由 generate 派生 */
66
+ clientFile: string | null;
67
+ clientRelativeFile: string | null;
68
+ /** true = 服务端 meta 声明了 view(免成对文件) */
69
+ view: boolean;
66
70
  serverRelativeFile: string;
67
- clientRelativeFile: string;
68
71
  }
69
72
  interface ModuleDescriptor {
70
73
  schemaVersion: 1;
@@ -199,4 +202,14 @@ interface TboxAppPluginOptions {
199
202
  }
200
203
  declare function tboxAppPlugin(options?: TboxAppPluginOptions): Plugin;
201
204
 
202
- export { type ActionModule, AppBuildError, type AppKind, type AppManifest, type AppMeta, type CardModule, type CardSampleEntry, type CardSampleSet, type CheckIssue, type CheckResult, FUNCTION_ID_RE, type FunctionModule, type GenerateOptions, type GenerateResult, type GeneratedApp, type LoadedModule, type ModuleDescriptor, type PageEntry, type PageMeta, type PageModule, type ScanResult, type SkillModule, type TboxAppPluginOptions, type ToolModule, buildManifest, checkApp, generateApp, listGeneratedFiles, parsePageMeta, readAppMeta, readCardSamples, scanApp, scanAppPrimitives, scanFunctions, scanModulePrimitives, scanModules, scanPages, tboxAppPlugin };
205
+ interface TboxModuleSourcesOptions {
206
+ /** 应用根(含 apps/client 与 modules/) */
207
+ appRoot: string;
208
+ }
209
+ /**
210
+ * 在 Tailwind 入口编译前追加模块源码 @source。
211
+ * 必须排在 @tailwindcss/vite 之前(enforce: 'pre' + plugins 数组顺序)。
212
+ */
213
+ declare function tboxModuleSourcesPlugin(options: TboxModuleSourcesOptions): Plugin;
214
+
215
+ export { type ActionModule, AppBuildError, type AppKind, type AppManifest, type AppMeta, type CardModule, type CardSampleEntry, type CardSampleSet, type CheckIssue, type CheckResult, FUNCTION_ID_RE, type FunctionModule, type GenerateOptions, type GenerateResult, type GeneratedApp, type LoadedModule, type ModuleDescriptor, type PageEntry, type PageMeta, type PageModule, type ScanResult, type SkillModule, type TboxAppPluginOptions, type TboxModuleSourcesOptions, type ToolModule, buildManifest, checkApp, generateApp, listGeneratedFiles, parsePageMeta, readAppMeta, readCardSamples, scanApp, scanAppPrimitives, scanFunctions, scanModulePrimitives, scanModules, scanPages, tboxAppPlugin, tboxModuleSourcesPlugin };
package/dist/index.js CHANGED
@@ -130,8 +130,11 @@ function propertyName(node) {
130
130
  }
131
131
  function getProperty(obj, name) {
132
132
  for (const prop of obj.properties) {
133
- if (!ts.isPropertyAssignment(prop)) continue;
134
- 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;
135
138
  }
136
139
  return void 0;
137
140
  }
@@ -344,26 +347,35 @@ async function scanCardDirs(serverDir, clientDir) {
344
347
  for (const base of [...bases].sort()) {
345
348
  const serverFile = server.get(base);
346
349
  const clientFile = client.get(base);
347
- if (!serverFile || !clientFile) {
348
- throw new AppBuildError("CARD_PAIR_MISSING", `卡片 ${base} 必须在 server/client 双端成对存在`, {
349
- file: serverFile ?? clientFile
350
- });
350
+ if (!serverFile) {
351
+ throw new AppBuildError("CARD_PAIR_MISSING", "卡片 " + base + " 只有客户端文件,缺少服务端声明", { file: clientFile });
351
352
  }
352
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
+ }
353
367
  const { expr: clientExpr } = await readExported(clientFile, "card");
354
- const cardType = stringProperty(serverExpr, "cardType", `card (${base})`);
355
- const clientType = stringProperty(clientExpr, "type", `card (${base})`);
368
+ const clientType = stringProperty(clientExpr, "type", "card (" + base + ")");
356
369
  if (cardType !== clientType) {
357
- throw new AppBuildError("CARD_TYPE_MISMATCH", `卡片 ${base} 双端类型不一致: ${cardType} !== ${clientType}`, {
358
- file: clientFile
359
- });
370
+ throw new AppBuildError("CARD_TYPE_MISMATCH", "卡片 " + base + " 双端类型不一致: " + cardType + " !== " + clientType, { file: clientFile });
360
371
  }
361
372
  out.push({
362
373
  cardType,
363
374
  serverFile,
364
375
  clientFile,
365
- serverRelativeFile: path5.relative(serverDir, serverFile).split(path5.sep).join("/"),
366
- clientRelativeFile: path5.relative(clientDir, clientFile).split(path5.sep).join("/")
376
+ clientRelativeFile: path5.relative(clientDir, clientFile).split(path5.sep).join("/"),
377
+ view: false,
378
+ serverRelativeFile
367
379
  });
368
380
  }
369
381
  return out;
@@ -742,11 +754,27 @@ function buildAppRegistry(scan, observed) {
742
754
  }
743
755
  return lines.join("\n");
744
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
+ }
745
773
  function buildClientRegistry(genDir, scan) {
746
774
  const file = path8.join(genDir, "registry.client.ts");
747
775
  const lines = ["// @generated by @tbox.cn/app-build; do not edit."];
748
776
  const clientModules = scan.modules.filter((mod) => mod.hasClient);
749
- 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)}';`));
750
778
  clientModules.forEach((mod, i) => lines.push(`import { clientModule as module${i} } from '${relativePosix(file, path8.join(mod.dir, "src/client/index.ts"))}';`));
751
779
  lines.push("");
752
780
  lines.push("export const cards = {");
@@ -816,6 +844,16 @@ async function generateCore(root, shell, scan) {
816
844
  const observedCardTypes = await collectObservedCardTypes(scan);
817
845
  await write(path8.join(genDir, "app-registry.ts"), buildAppRegistry(scan, observedCardTypes));
818
846
  await write(path8.join(genDir, "registry.server.ts"), buildServerRegistry(genDir, scan));
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
+ }
853
+ }
854
+ for (const card of scan.cards.filter((item) => item.view)) {
855
+ await write(path8.join(cardsDir, card.cardType + ".tsx"), buildViewCardStub(card.cardType));
856
+ }
819
857
  await write(path8.join(genDir, "registry.client.ts"), buildClientRegistry(genDir, scan));
820
858
  const writeDocuments = async () => {
821
859
  for (const page of scan.pages) {
@@ -1123,6 +1161,67 @@ function tboxAppPlugin(options = {}) {
1123
1161
  }
1124
1162
  };
1125
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
+ }
1126
1225
  export {
1127
1226
  AppBuildError,
1128
1227
  FUNCTION_ID_RE,
@@ -1139,5 +1238,6 @@ export {
1139
1238
  scanModulePrimitives,
1140
1239
  scanModules,
1141
1240
  scanPages,
1142
- tboxAppPlugin
1241
+ tboxAppPlugin,
1242
+ tboxModuleSourcesPlugin
1143
1243
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tbox.cn/app-build",
3
- "version": "1.0.0-alpha.7",
3
+ "version": "1.0.0-alpha.9",
4
4
  "type": "module",
5
5
  "description": "tbox-app 1.0 build-time leaf: scan apps/ modules/ and generate manifest, registries, documents; Vite plugin and checks.",
6
6
  "exports": {
@@ -8,7 +8,11 @@
8
8
  "types": "./dist/index.d.ts",
9
9
  "import": "./dist/index.js"
10
10
  },
11
- "./package.json": "./package.json"
11
+ "./package.json": "./package.json",
12
+ "./tailwind-sources": {
13
+ "types": "./tailwind-sources.d.mts",
14
+ "import": "./tailwind-sources.mjs"
15
+ }
12
16
  },
13
17
  "publishConfig": {
14
18
  "access": "public"
@@ -35,6 +39,8 @@
35
39
  },
36
40
  "files": [
37
41
  "dist",
42
+ "tailwind-sources.mjs",
43
+ "tailwind-sources.d.mts",
38
44
  "README.md",
39
45
  "LICENSE"
40
46
  ],
@@ -0,0 +1,2 @@
1
+ export function collectModuleSourceDirs(appRoot: string): string[];
2
+ export function renderModuleSources(dirs: string[]): string;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Tailwind 模块源码发现:dev/build 的 Vite 插件与证据包 surface-css 共用。
3
+ *
4
+ * 只登记有 src/client/index.ts 的客户端模块,扫描其 src/client/;显式绝对路径——
5
+ * Tailwind 的 @source 不跟随通配符路径(对 pnpm 软链不生效)。
6
+ */
7
+ import { existsSync, readdirSync, realpathSync, statSync } from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ const MODULE_ROOTS = [
11
+ { dir: 'modules', prefixes: ['module-'] },
12
+ { dir: 'apps/client/node_modules/@tbox.cn', prefixes: ['app-module-', 'module-'] },
13
+ ];
14
+
15
+ /**
16
+ * @param {string} appRoot
17
+ * @returns {string[]} 模块源码目录(绝对路径,已排序/去重)
18
+ */
19
+ export function collectModuleSourceDirs(appRoot) {
20
+ const root = path.resolve(appRoot);
21
+ const seen = new Set();
22
+ const out = [];
23
+
24
+ for (const { dir, prefixes } of MODULE_ROOTS) {
25
+ const base = path.join(root, dir);
26
+ if (!existsSync(base)) continue;
27
+ for (const name of readdirSync(base).sort()) {
28
+ if (!prefixes.some((prefix) => name.startsWith(prefix))) continue;
29
+ const moduleDir = path.join(base, name);
30
+ const clientDir = path.join(moduleDir, 'src/client');
31
+ let real;
32
+ try {
33
+ if (!statSync(moduleDir).isDirectory()) continue;
34
+ if (!existsSync(path.join(clientDir, 'index.ts'))) continue;
35
+ real = realpathSync(clientDir);
36
+ } catch {
37
+ continue;
38
+ }
39
+ if (seen.has(real)) continue;
40
+ seen.add(real);
41
+ out.push(clientDir);
42
+ }
43
+ }
44
+ return out.sort();
45
+ }
46
+
47
+ /**
48
+ * @param {string[]} dirs
49
+ * @returns {string} 可拼进任意 Tailwind 入口 CSS 的 @source 行
50
+ */
51
+ export function renderModuleSources(dirs) {
52
+ return dirs
53
+ .map((dir) => `@source ${JSON.stringify(dir.split(path.sep).join('/'))};`)
54
+ .join('\n');
55
+ }