@aiti-ai/aiti-git-review 0.2.12 → 0.2.13

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.
@@ -13,7 +13,7 @@ import { __setCtx, apiUrl } from "./host-shim";
13
13
  // carry their own host-shim copy — hand it the same ctx so their apiUrl (basePath) and i18n
14
14
  // resolve against this extension's runtime instead of falling back to defaults.
15
15
  import { __setCtx as setAitiFolderCtx } from "../../../aiti-folder/client/src/host-shim";
16
- import { seedDockDefault } from "../../../_shared/ext-float-dock";
16
+ import { seedDockDefault } from "@aiti-ai/ext-shared/ext-float-dock";
17
17
  import { api, G, setGRCtx } from "./shared";
18
18
  import { openFromToolbar, ReviewWork, DockReviewWork, GrEyeIcon } from "./git-review-app";
19
19
 
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import { useState, useEffect } from "react";
9
9
  import { regSvc } from "./host-shim";
10
- import { useGate, DockBody, present } from "../../../_shared/ext-float-dock";
10
+ import { useGate, DockBody, present } from "@aiti-ai/ext-shared/ext-float-dock";
11
11
  import { api, jsonBody, G, lastSeg } from "./shared";
12
12
  import { TaskPicker } from "./task-picker";
13
13
  import { ReviewApp } from "./review-app";
@@ -10,7 +10,7 @@
10
10
  */
11
11
  import { useState, useEffect, useRef } from "react";
12
12
  import { t, apiUrl, extSvc } from "./host-shim";
13
- import { uiAlert } from "../../../_shared/ui-dialogs";
13
+ import { uiAlert } from "@aiti-ai/ext-shared/ui-dialogs";
14
14
  import {
15
15
  api, jsonBody, G, getCtx, lastSeg, MONO, SMALL_MQ,
16
16
  statusIcon, statusColor, sevColor, sevLabel,
@@ -6,12 +6,12 @@
6
6
  */
7
7
  import { useState, useEffect, useRef } from "react";
8
8
  import { t, apiUrl } from "./host-shim";
9
- import { uiConfirm } from "../../../_shared/ui-dialogs";
10
- import { dedupeFetch } from "../../../_shared/dedupe-fetch";
9
+ import { uiConfirm } from "@aiti-ai/ext-shared/ui-dialogs";
10
+ import { dedupeFetch } from "@aiti-ai/ext-shared/dedupe-fetch";
11
11
  import { api, jsonBody, G, lastSeg, statusIcon, statusColor, overlay, pickerCard, segBtn, segOn, btnPrimary } from "./shared";
12
12
  // aiti-folder 工作区切换器(与 session-manager 同法:构建期内联复用同一组件)
13
13
  import { WorkspaceDropdown } from "../../../aiti-folder/client/src/folder-switcher";
14
- import { isDirectoryPickerTarget } from "../../../_shared/directory-picker-dom";
14
+ import { isDirectoryPickerTarget } from "@aiti-ai/ext-shared/directory-picker-dom";
15
15
  import { displayCwd } from "../../../aiti-folder/client/src/lib";
16
16
 
17
17
  /** 版本选项(分支/tag/远程) */
@@ -159,52 +159,57 @@ const P = (d) => ({ tag: "path", attrs: { d } });
159
159
  const R = (x, y, width, height, rx = 2) => ({ tag: "rect", attrs: { x, y, width, height, rx } });
160
160
  const thin = (n) => ({ ...n, attrs: { ...n.attrs, "stroke-width": 1.5 } });
161
161
  const DOCK_ICON_NODES = {
162
- /** 浮窗:圆角框 + 标题栏 + 圆点(app-window;用户 2026-09-15 定稿 C)。 */
162
+ /** Float: rounded frame + title bar + dots (app-window; user finalized C on 2026-09-15). */
163
163
  float: [
164
164
  R(2, 4, 20, 16, 2),
165
165
  P("M10 4v4"),
166
166
  P("M2 8h20"),
167
167
  P("M6 4v4")
168
168
  ],
169
- /** 新窗口打开:方框 + 右上外斜箭头(square-arrow-out-up-right;
170
- * 用户 2026-09-15 拍板:B 图形用作「新窗口打开」,且仅支持的面板(文件/文件夹)显示)。 */
169
+ /** Open in new window: box + outward diagonal arrow at top right
170
+ * (square-arrow-out-up-right;
171
+ * user ruling 2026-09-15: glyph B serves "Open in new window", shown only for capable
172
+ * panels (files/folders)). */
171
173
  "new-window": [
172
174
  P("M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6"),
173
175
  P("m21 3-9 9"),
174
176
  P("M15 3h6v6")
175
177
  ],
176
- /** 左栏:方框 + 左缘粗边。 */
178
+ /** Left panel: box + thick left edge. */
177
179
  "panel-left": [R(3, 3, 18, 18), P("M9 3v18")],
178
- /** 右栏:方框 + 右缘粗边。 */
180
+ /** Right panel: box + thick right edge. */
179
181
  "panel-right": [R(3, 3, 18, 18), P("M15 3v18")],
180
- /** 底部(预留位):方框 + 下缘粗边。 */
182
+ /** Bottom (reserved slot): box + thick bottom edge. */
181
183
  "panel-bottom": [R(3, 3, 18, 18), P("M3 15h18")],
182
184
  "chevron-up": [P("m18 15-6-6-6 6")],
183
185
  "chevron-down": [P("m6 9 6 6 6-6")],
184
186
  "chevron-left": [P("m15 18-6-6 6-6")],
185
187
  "chevron-right": [P("m9 18 6-6-6-6")],
186
188
  "arrow-up": [P("m5 12 7-7 7 7"), P("M12 19V5")],
187
- /** 钉住:图钉(lucide pin;⋮ 区块操作「钉住」,与 aiti-folder MiPin 同形)。 */
189
+ /** Pin: pushpin (lucide pin; the ⋮ block operation "Pin", same shape as aiti-folder's MiPin). */
188
190
  pin: [
189
191
  { tag: "line", attrs: { x1: 12, y1: 17, x2: 12, y2: 22 } },
190
192
  P("M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z")
191
193
  ],
192
- /** 关闭:×(lucide x;⋮ 区块操作「关闭」)。 */
194
+ /** Close: × (lucide x; the ⋮ block operation "Close"). */
193
195
  x: [P("M18 6 6 18"), P("m6 6 12 12")],
194
- /** 取消钉住态:图钉 + 斜删除线(lucide pin-off;移动行钉住钮已钉态,与 MiPin 同语义族)。 */
196
+ /** Unpin state: pushpin + diagonal strike (lucide pin-off; the move-row pin button's
197
+ * pinned state, same semantic family as MiPin). */
195
198
  "pin-off": [
196
199
  { tag: "line", attrs: { x1: 12, y1: 17, x2: 12, y2: 22 } },
197
200
  P("M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16h14v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z"),
198
201
  { tag: "line", attrs: { x1: 2, y1: 2, x2: 22, y2: 22 } }
199
202
  ],
200
- /** 移除本实例:垃圾桶(lucide trash;多实例区块 ⋮「移除本实例」,与 aiti-folder MiTrash 同形)。 */
203
+ /** Remove this instance: trash can (lucide trash; multi-instance blocks' ⋮ "Remove
204
+ * this instance", same shape as aiti-folder's MiTrash). */
201
205
  trash: [
202
206
  { tag: "polyline", attrs: { points: "3 6 5 6 21 6" } },
203
207
  P("M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"),
204
208
  { tag: "line", attrs: { x1: 10, y1: 11, x2: 10, y2: 17 } },
205
209
  { tag: "line", attrs: { x1: 14, y1: 11, x2: 14, y2: 17 } }
206
210
  ],
207
- /** 移动:对角双箭头(lucide move-diagonal-2;⋮「移动」行首图标——左上 + 右下,用户 2026-09-15 指定)。 */
211
+ /** Move: diagonal double arrow (lucide move-diagonal-2; the ⋮ "Move" row's leading
212
+ * icon — top-left + bottom-right, specified by the user 2026-09-15). */
208
213
  "move-diagonal-2": [
209
214
  P("M5 11V5h6"),
210
215
  P("M19 13v6h-6"),
@@ -1222,8 +1227,9 @@ function DockBody(props) {
1222
1227
  {
1223
1228
  key: "label",
1224
1229
  "data-ext-dock-icon-row-label": "1",
1225
- // 行首图标(可选):带图标 = 动作行(正文字色,与其余 icon+text 行同款);
1226
- // 无图标 = 纯说明名(dim,位置菜单「停靠方位」标题原样)。
1230
+ // Leading row icon (optional): with an icon = an action row (body text color,
1231
+ // same style as the other icon+text rows); without = a pure caption name (dim,
1232
+ // e.g. the position menu's "Dock zones" title as-is).
1227
1233
  style: {
1228
1234
  display: "inline-flex",
1229
1235
  alignItems: "center",
@@ -1352,16 +1358,19 @@ function DockBody(props) {
1352
1358
  boxShadow: "0 8px 24px rgba(0,0,0,0.4)",
1353
1359
  minWidth: menu?.kind === "position" ? 190 : 150,
1354
1360
  maxWidth: "calc(100vw - 16px)",
1355
- // 长菜单滚动契约(v3):视口内可滚 + 防滚动穿透(内部滚动不触发「容器滚动即关」)
1361
+ // Long-menu scroll contract (v3): scrollable inside the viewport + scroll
1362
+ // containment (inner scroll does not trigger "container scroll closes")
1356
1363
  maxHeight: "min(70vh, calc(100vh - 16px))",
1357
1364
  overflowY: "auto",
1358
1365
  overscrollBehavior: "contain",
1359
- // 首帧离屏(布局期测量后落位,绘制前同步无闪烁)
1366
+ // First frame off-screen (positioned after layout measurement, synced before paint, no flicker)
1360
1367
  ...menuPos ? { left: menuPos.left, top: menuPos.top } : { left: -99999, top: -99999 }
1361
1368
  },
1362
- // hover 关闭仅限真 hover 设备(2026-11-15 小屏反馈「菜单经常自己关掉」):手机上手指
1363
- // 滑动浏览菜单项时浏览器合成 mouse 事件(touchmove 目标变化 → 合成 mouseleave),
1364
- // 无条件关闭等于「一滑就关」;触屏(hover:none)忽略 mouseleave,改由外点/滚动关闭。
1369
+ // Hover-close only on true hover devices (2026-11-15 small-screen feedback "the menu
1370
+ // keeps closing itself"): while a finger swipes through menu items on phones the
1371
+ // browser synthesizes mouse events (touchmove target change → synthetic mouseleave);
1372
+ // unconditional close equals "one swipe closes it". Touch (hover:none) ignores
1373
+ // mouseleave and closes via outside click/scroll instead.
1365
1374
  onMouseLeave: () => {
1366
1375
  try {
1367
1376
  if (!window.matchMedia("(hover: hover) and (pointer: fine)").matches) return;
@@ -1455,10 +1464,11 @@ function DockBody(props) {
1455
1464
  "data-ext-float-dock-body": itemKey,
1456
1465
  "data-ext-item": itemKey,
1457
1466
  "data-ext-dock-block": blockKey,
1458
- // 根上带声明属性:TabBar ⇱ 菜单在 face 挂载时可直接读(注册表兜底优先)
1467
+ // Declaration attributes on the root: the TabBar ⇱ menu reads them directly when the
1468
+ // face is mounted (registry fallback takes precedence)
1459
1469
  "data-ext-float-dock": allZones.join(" "),
1460
1470
  ...defaultZone ? { "data-ext-float-dock-default": defaultZone } : {},
1461
- // 注册按钮数(e2e/调试断言用):当前头行可见 / 溢出
1471
+ // Registered button counts (for e2e/debug assertions): currently visible in header / overflow
1462
1472
  "data-ext-dock-actions": String(shownActions.length),
1463
1473
  "data-ext-dock-actions-overflow": String(overflowActions.length),
1464
1474
  style: { display: "flex", flexDirection: "column", height: "100%", minHeight: 0, overflow: "hidden", position: "relative" }
@@ -1882,7 +1892,7 @@ function buildBody(panel2, spec, finish) {
1882
1892
  head.appendChild(icon);
1883
1893
  const titleEl = document.createElement("div");
1884
1894
  titleEl.style.cssText = "flex:1;min-width:0;font-size:15px;font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;";
1885
- titleEl.textContent = o.title || (spec.kind === "confirm" ? o.danger ? "危险操作确认" : "确认操作" : spec.kind === "prompt" ? "输入" : spec.kind === "choice" ? "请选择" : "提示");
1895
+ titleEl.textContent = o.title || (spec.kind === "confirm" ? o.danger ? "Confirm dangerous operation" : "Confirm" : spec.kind === "prompt" ? "Input" : spec.kind === "choice" ? "Choose" : "Notice");
1886
1896
  head.appendChild(titleEl);
1887
1897
  panel2.appendChild(head);
1888
1898
  if (o.message) {
@@ -1938,11 +1948,11 @@ function buildBody(panel2, spec, finish) {
1938
1948
  }
1939
1949
  if (items.length === 0) finish(o.cancelId ?? null);
1940
1950
  } else if (spec.kind === "alert") {
1941
- const ok = mk(o.confirmText || "确定", true, false, () => finish(void 0));
1951
+ const ok = mk(o.confirmText || "OK", true, false, () => finish(void 0));
1942
1952
  ok.__primary = true;
1943
1953
  } else {
1944
- mk(o.cancelText || "取消", false, false, () => finish(spec.kind === "prompt" ? null : spec.kind === "choice" ? o.cancelId ?? null : false));
1945
- const ok = mk(o.confirmText || (spec.kind === "confirm" && o.danger ? "确认执行" : "确定"), true, !!(spec.kind === "confirm" && o.danger), () => finish(spec.kind === "prompt" ? input && o.required && !input.value.trim() ? void 0 : input.value : true));
1954
+ mk(o.cancelText || "Cancel", false, false, () => finish(spec.kind === "prompt" ? null : spec.kind === "choice" ? o.cancelId ?? null : false));
1955
+ const ok = mk(o.confirmText || (spec.kind === "confirm" && o.danger ? "Confirm" : "OK"), true, !!(spec.kind === "confirm" && o.danger), () => finish(spec.kind === "prompt" ? input && o.required && !input.value.trim() ? void 0 : input.value : true));
1946
1956
  ok.__primary = true;
1947
1957
  }
1948
1958
  panel2.appendChild(foot);
@@ -2107,6 +2117,7 @@ const COMPONENT_DICT = {
2107
2117
  "git.aiMessageEmpty": "The AI answered, but the text could not be cleaned into a commit message — please retry.",
2108
2118
  "git.aiMessageOverwrite": "Message already has content. Overwrite with the generated commit message?",
2109
2119
  "git.aiMessageTitle": "Generate a commit message with AI (reads AGENTS.md and the diff of selected files)",
2120
+ "git.wiPickTitle": "Insert a work-item header at the top of the message (aiti-codehub picker)",
2110
2121
  "git.stagedBucket": "Staged",
2111
2122
  "git.unstagedBucket": "Changes",
2112
2123
  "git.stageTitle": "Stage",
@@ -2117,7 +2128,14 @@ const COMPONENT_DICT = {
2117
2128
  "git.discardUntrackedConfirm": "Move the untracked file to the trash? (restorable from the trash)",
2118
2129
  "git.diffTitle": "View diff (git-review)",
2119
2130
  "git.changesToggle": "Toggle changed-files section",
2120
- "git.planRetry": "Retry remaining groups"
2131
+ "git.planRetry": "Retry remaining groups",
2132
+ "git.nestedRepoTip": "Nested git repository (click to toggle its changes)",
2133
+ "git.nestedFallbackHint": "git-ops engine unavailable — read-only view",
2134
+ "git.moreActions": "More actions",
2135
+ "git.branchPanelEntry": "Branch panel",
2136
+ "git.refreshRepo": "Refresh this repo (git status only)",
2137
+ "git.openAsFolderTab": "Open as folder tab",
2138
+ "git.collapseChanges": "Collapse changes"
2121
2139
  },
2122
2140
  "zh-CN": {
2123
2141
  "files.cancel": "取消",
@@ -2193,6 +2211,7 @@ const COMPONENT_DICT = {
2193
2211
  "git.aiMessageEmpty": "AI 已作答,但无法整理成提交信息——请重试。",
2194
2212
  "git.aiMessageOverwrite": "输入框已有内容,生成结果将覆盖,是否继续?",
2195
2213
  "git.aiMessageTitle": "AI 生成提交信息(读取 AGENTS.md 与所选文件的 diff)",
2214
+ "git.wiPickTitle": "在消息开头插入工作项头部(aiti-codehub 选择器)",
2196
2215
  "git.stagedBucket": "已暂存",
2197
2216
  "git.unstagedBucket": "工作区",
2198
2217
  "git.stageTitle": "暂存",
@@ -2203,7 +2222,14 @@ const COMPONENT_DICT = {
2203
2222
  "git.discardUntrackedConfirm": "将未跟踪文件移入回收站?(可在回收站还原)",
2204
2223
  "git.diffTitle": "查看 diff(git-review)",
2205
2224
  "git.changesToggle": "开/合变更文件区",
2206
- "git.planRetry": "重试剩余组"
2225
+ "git.planRetry": "重试剩余组",
2226
+ "git.nestedRepoTip": "嵌套 Git 仓库(点击展开/收起其变更)",
2227
+ "git.nestedFallbackHint": "git-ops 引擎未启用——只读视图",
2228
+ "git.moreActions": "更多操作",
2229
+ "git.branchPanelEntry": "分支面板",
2230
+ "git.refreshRepo": "刷新本仓(仅 git 状态)",
2231
+ "git.openAsFolderTab": "打开为独立文件夹标签页",
2232
+ "git.collapseChanges": "收起变更区"
2207
2233
  }
2208
2234
  };
2209
2235
  function currentLocale() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiti-ai/aiti-git-review",
3
- "version": "0.2.12",
3
+ "version": "0.2.13",
4
4
  "type": "module",
5
5
  "description": "Dedicated to reviewing uncommitted changes — Monaco diff workspace (side-by-side/merged/new-only/outline) + line-level annotations (must/suggest/question) + anchor flag-line re-mapping (stays valid while editing mid-review) + summary final-review checklist + AI pre-review (aiti_review_* tools injected only into review sessions, zero tools day-to-day)",
6
6
  "displayNameI18n": {
@@ -31,7 +31,7 @@
31
31
  "@aiti-ai/ext-shared": "^0.1.12"
32
32
  },
33
33
  "license": "MIT",
34
- "contentHash": "9c71fd7b15b543a6",
34
+ "contentHash": "d0d87a4ab103f087",
35
35
  "repository": {
36
36
  "type": "git",
37
37
  "url": "git+https://github.com/aiti-ai/aiti-ai.git",
package/tools/deploy.mjs CHANGED
@@ -16,13 +16,12 @@ import { resolve } from "node:path";
16
16
  import { fileURLToPath } from "node:url";
17
17
  import { homedir } from "node:os";
18
18
  import { execSync } from "node:child_process";
19
- import { deployCommit } from "../../_shared/deploy-commit.mjs";
20
- import { copyIcons } from "../../_shared/ext-icons-deploy.mjs";
21
- import { notifyReconcile } from "../../_shared/reconcile-deps.mjs";
19
+ import { deployCommit } from "@aiti-ai/ext-shared/deploy-commit";
20
+ import { notifyReconcile } from "@aiti-ai/ext-shared/reconcile-deps";
22
21
 
23
22
  // client TS 残留检查(.mjs 里是合法 JS 语法检查不报、运行时必炸;FAIL 即部署失败)
24
23
  {
25
- const { checkClientDir } = await import("../../_shared/check-client.mjs");
24
+ const { checkClientDir } = await import("@aiti-ai/ext-shared/check-client");
26
25
  checkClientDir(fileURLToPath(new URL("../client", import.meta.url)), { log: (m) => console.log("[deploy] " + m) });
27
26
  }
28
27
 
@@ -76,7 +75,6 @@ console.log("[deploy] 完成。生效:POST /api/extensions/reload(或重启
76
75
  // 提交部署状态到扩展 git 仓库(生产目录是 git 仓库)
77
76
 
78
77
  // 图标文件拷贝(icon: "icons/<name>.svg" → 宿主加载时内嵌;库在 _shared/icons/)
79
- for (const t of targets) copyIcons(resolve(t, "icons"), ["eye"], { log: (m2) => console.log(m2) });
80
78
 
81
79
  deployCommit({ repo: extRepo, name: "aiti-git-review", paths: ["aiti-git-review"], log: (m) => console.log("[deploy] " + m) });
82
80
 
@@ -85,7 +83,7 @@ await notifyReconcile();
85
83
 
86
84
  // ── 双实例热重载(basePath 双 env 按机器设值)——允许失败:服务未启动/共享模块缺失仅提示,不影响 deploy 退出码 ──
87
85
  try {
88
- const { reloadInstances } = await import("../../_shared/reload-instances.mjs");
86
+ const { reloadInstances } = await import("@aiti-ai/ext-shared/reload-instances");
89
87
  await reloadInstances();
90
88
  } catch (e) {
91
89
  console.log("[deploy] 自动 reload 未执行(" + String((e && e.message) || e) + ")— 需手动 POST /api/extensions/reload");
@@ -93,7 +91,7 @@ try {
93
91
 
94
92
  // ── dev-pack(方案 §3.2:源码+构建工具+AGENTS.md 直达部署目录,AI 可现场直改)——允许失败,不影响 deploy 退出码 ──
95
93
  try {
96
- const { packDevPack } = await import("../../_shared/dev-pack.mjs");
94
+ const { packDevPack } = await import("@aiti-ai/ext-shared/dev-pack");
97
95
  packDevPack({ extRoot: resolve(import.meta.dirname, ".."), log: (m) => console.log("[deploy] " + m) });
98
96
  } catch (e) {
99
97
  console.log("[deploy] dev-pack 未执行(" + String((e && e.message) || e) + ")");
package/check-client.mjs DELETED
@@ -1,273 +0,0 @@
1
- /**
2
- * check-client —— 扩展 client .mjs/.js 的 TS 残留 tripwire(零依赖,纯 node)。
3
- *
4
- * 背景:aiti-plan-review 事故(docs/aiti-ext-client-hardening-plan.md §1)——
5
- * `useState<any>(null)` 解析为合法 JS 比较表达式 `useState < any > (null)`,
6
- * node --check / TS 解析器 / babel 全不报错,只有运行时才炸。纯语法检查
7
- * 原理性无效,只能启发式规则 + 渲染期错误边界兜底。
8
- *
9
- * 用法:
10
- * CLI node check-client.mjs <file|dir>... FAIL → exit 1
11
- * 自测 node check-client.mjs --selftest fixtures 全过 → exit 0
12
- * API lintClientSource(src) → violations[] { line, level, rule, text }
13
- * lintPath(path) → { files, violations }(文件或目录,递归)
14
- * checkClientDir(dir,{log}) FAIL → throw(deploy 脚本用)
15
- *
16
- * 词法:规则匹配前先剥离注释/字符串/模板字面量(${} 插值内代码保留检查)——
17
- * aiti-editor 的 Monaco TS stub 模板串、JSDoc @return 都是合法内容,不剥全误报。
18
- * 已知极限:regex 字面量含引号等 lexer 歧义允许漏报(tripwire 定位非编译器)。
19
- *
20
- * 豁免:目标行或其上一行含 `check-client:allow` 即跳过该行。
21
- * 权威源:本文件;aiti-extman 部署副本由其 tools/deploy.mjs 拷贝(改动两处同步)。
22
- */
23
- import { readdirSync, readFileSync, statSync } from "node:fs";
24
- import { join, resolve } from "node:path";
25
-
26
- // ── 规则(分级)──────────────────────────────────────────────────────────────
27
-
28
- const RULES = [
29
- // FAIL:合法 JS 但运行时必炸 / 纯 TS 语法
30
- { level: "FAIL", re: /\b(useState|useRef|useMemo|useCallback|useReducer|useImperativeHandle)\s*</, why: "React hook 泛型(运行时必炸)" },
31
- // 注:含「any/unknown/string」字样的规则用字符串构 RegExp——本文件自身也
32
- // 会被扫,正则字面量里的 (?:any 会被自己命中(词法器不处理 regex 字面量),
33
- // 字符串字面量则会被词法遮蔽。
34
- { level: "FAIL", re: new RegExp("\\bas\\s+(?:" + "any|unknown|const)\\b"), why: "as 断言" },
35
- { level: "FAIL", re: new RegExp(":\\s*(?:" + "any|unknown)\\b"), why: ": any/: unknown 注解" },
36
- { level: "FAIL", re: /\b(?:import|export)\s+type\s/, why: "import/export type" },
37
- { level: "FAIL", re: /\b(?:interface|enum)\s+[A-Za-z_$]/, why: "interface/enum 声明" },
38
- // warn:疑似残留,人工确认,不阻断
39
- { level: "warn", re: new RegExp(":\\s*(?:" + "string|number|boolean|void)\\b(?!\\s*[._\\w])"), why: "疑似类型注解" },
40
- { level: "warn", re: /\bsatisfies\s/, why: "satisfies" },
41
- { level: "warn", re: /\b(?:Record|Partial|Readonly|Omit|Pick)\s*</, why: "TS 工具类型" },
42
- ];
43
-
44
- // ── 词法剥离:注释/字符串/模板字面量 → 空格(保留换行,行号不漂移)─────────
45
- export function stripLiterals(src) {
46
- const out = src.split("");
47
- const n = src.length;
48
- const mask = (from, to) => {
49
- for (let k = from; k < to && k < n; k++) if (out[k] !== "\n") out[k] = " ";
50
- };
51
- let mode = "code";
52
- let depth = 0;
53
- const stack = []; // 模板 ${ 插值进入时的 brace 深度(支持嵌套模板)
54
- let i = 0;
55
- while (i < n) {
56
- const c = src[i];
57
- const d = i + 1 < n ? src[i + 1] : "";
58
- if (mode === "code") {
59
- if (c === "/" && d === "/") {
60
- const j = src.indexOf("\n", i);
61
- const end = j === -1 ? n : j;
62
- mask(i, end);
63
- i = end;
64
- } else if (c === "/" && d === "*") {
65
- const j = src.indexOf("*/", i + 2);
66
- const end = j === -1 ? n : j + 2;
67
- mask(i, end);
68
- i = end;
69
- } else if (c === "'" || c === '"') {
70
- let j = i + 1;
71
- while (j < n && src[j] !== c && src[j] !== "\n") j += src[j] === "\\" ? 2 : 1;
72
- if (j < n && src[j] === c) {
73
- mask(i, j + 1);
74
- i = j + 1;
75
- } else {
76
- // 未闭合到行尾 → 可能是 regex 字面量歧义,只遮开引号,按代码继续
77
- out[i] = " ";
78
- i++;
79
- }
80
- } else if (c === "`") {
81
- mode = "tpl";
82
- out[i] = " ";
83
- i++;
84
- } else if (c === "{") {
85
- depth++;
86
- i++;
87
- } else if (c === "}") {
88
- if (stack.length && depth === stack[stack.length - 1]) {
89
- stack.pop();
90
- mode = "tpl"; // 插值结束回模板
91
- out[i] = " ";
92
- } else {
93
- depth = Math.max(0, depth - 1);
94
- }
95
- i++;
96
- } else i++;
97
- } else if (mode === "tpl") {
98
- if (c === "\\") {
99
- mask(i, Math.min(i + 2, n));
100
- i += 2;
101
- } else if (c === "`") {
102
- mode = "code";
103
- out[i] = " ";
104
- i++;
105
- } else if (c === "$" && d === "{") {
106
- stack.push(depth);
107
- mode = "code";
108
- mask(i, i + 2);
109
- i += 2;
110
- } else {
111
- if (c !== "\n") out[i] = " ";
112
- i++;
113
- }
114
- } else {
115
- // 不可达:line/block/字符串均在 code 分支内联处理
116
- i++;
117
- }
118
- }
119
- return out.join("");
120
- }
121
-
122
- // ── 单源检查 ────────────────────────────────────────────────────────────────
123
- export function lintClientSource(src) {
124
- const masked = stripLiterals(src);
125
- const origLines = src.split("\n");
126
- const maskedLines = masked.split("\n");
127
- const violations = [];
128
- for (let i = 0; i < maskedLines.length; i++) {
129
- const prev = i > 0 ? origLines[i - 1] : "";
130
- if (origLines[i].includes("check-client:allow") || prev.includes("check-client:allow")) continue;
131
- for (const { level, re, why } of RULES) {
132
- if (re.test(maskedLines[i])) {
133
- violations.push({ line: i + 1, level, rule: why, text: origLines[i].trim().slice(0, 90) });
134
- }
135
- }
136
- }
137
- return violations;
138
- }
139
-
140
- // ── 文件/目录检查 ───────────────────────────────────────────────────────────
141
- const SKIP_DIR = new Set(["node_modules", ".git"]);
142
- /** 超过此体积视为 vendored bundle(如 Monaco ts.worker,合法含 interface 字样),不查。 */
143
- const MAX_BYTES = 512 * 1024;
144
- const isClientFile = (name) => /\.(mjs|js|cjs)$/.test(name) && !/\.min\./.test(name) && !/\.test\./.test(name);
145
-
146
- export function lintPath(p, out = { files: 0, violations: [] }) {
147
- const st = statSync(p);
148
- if (st.isDirectory()) {
149
- for (const name of readdirSync(p)) {
150
- if (SKIP_DIR.has(name)) continue;
151
- lintPath(join(p, name), out);
152
- }
153
- return out;
154
- }
155
- const base = p.split("/").pop();
156
- if (!isClientFile(base)) return out;
157
- if (st.size > MAX_BYTES) return out; // vendored bundle 豁免
158
- out.files++;
159
- for (const v of lintClientSource(readFileSync(p, "utf8"))) out.violations.push({ file: p, ...v });
160
- return out;
161
- }
162
-
163
- export function formatViolations(violations) {
164
- return violations
165
- .map((v) => ` ${v.level} ${v.file}:${v.line} [${v.rule}] ${v.text}`)
166
- .join("\n");
167
- }
168
-
169
- /** deploy 脚本用:检查目录,FAIL 抛错(消息含违规清单),warn 只打日志不阻断。 */
170
- export function checkClientDir(dir, { log = console.log } = {}) {
171
- const { files, violations } = lintPath(resolve(dir));
172
- const fails = violations.filter((v) => v.level === "FAIL");
173
- const warns = violations.filter((v) => v.level === "warn");
174
- if (warns.length) log(`[check-client] ${warns.length} 处疑似 TS 残留(不阻断,建议人工确认):\n${formatViolations(warns)}`);
175
- if (fails.length) {
176
- throw new Error(
177
- `client 检查未通过:${files} 个文件中 ${fails.length} 处 TS 残留(.mjs 里是合法 JS,语法检查不报,运行时必炸)。\n` +
178
- formatViolations(fails) +
179
- `\n修复或在该行加注释 // check-client:allow 豁免。详见 docs/aiti-ext-client-hardening-plan.md`,
180
- );
181
- }
182
- if (files) log(`[check-client] ${files} 个 client 文件检查通过`);
183
- return { files, fails: fails.length, warns: warns.length };
184
- }
185
-
186
- /**
187
- * extman 安装用:扫整个扩展目录(含第三方,不遵循 client/ 约定)。
188
- * 在 SKIP_DIR 之上额外跳过构建产物/vendored 目录(Monaco ts.worker、语言包等
189
- * 合法包含 TS 字样,词法器对 minified 代码不提供保证);体积上限同上。
190
- */
191
- export function lintExtensionDir(dir) {
192
- const out = { files: 0, violations: [] };
193
- const walk = (p) => {
194
- const st = statSync(p);
195
- if (st.isDirectory()) {
196
- for (const name of readdirSync(p)) {
197
- if (SKIP_DIR.has(name) || VENDORED_DIRS.has(name)) continue;
198
- walk(join(p, name));
199
- }
200
- return;
201
- }
202
- const base = p.split("/").pop();
203
- if (!isClientFile(base) || st.size > MAX_BYTES) return;
204
- out.files++;
205
- for (const v of lintClientSource(readFileSync(p, "utf8"))) out.violations.push({ file: p, ...v });
206
- };
207
- walk(resolve(dir));
208
- return out;
209
- }
210
- const VENDORED_DIRS = new Set(["vendor", "monaco", "dist", "build", "assets", "static", "bundles", "chunks"]);
211
-
212
- // ── CLI ─────────────────────────────────────────────────────────────────────
213
- function selftest() {
214
- const MUST_FAIL = [
215
- "const [st, setSt] = useState<any>(null);",
216
- "const r = useRef<number>(null);",
217
- "const x = v as any;",
218
- "function f(a: unknown) {}",
219
- 'import type { Foo } from "./x";',
220
- "interface Foo { a: string }",
221
- "enum Color { Red }",
222
- "const y = v as const;",
223
- ];
224
- const MUST_WARN = [
225
- "const opts = { mode: string };",
226
- "x satisfies Y;",
227
- "const m: Record<string, any> = {};",
228
- ];
229
- const MUST_PASS = [
230
- 'const REACT_TYPE_STUB = `\ndeclare module "react" {\n export function useState<T>(init: T): [T];\n export const Fragment: any;\n}\n`;',
231
- "/** @return {{chars1: string, chars2: string}} */",
232
- "const [s] = useState(null);",
233
- "useState<any>(null); // check-client:allow",
234
- "// check-client:allow\nuseState<never>(0);",
235
- "const cmp = a < b && c > (d);",
236
- "if (a // 注释里 as any 不算\n ) run();",
237
- ];
238
- let bad = 0;
239
- const check = (src, expect, desc) => {
240
- const v = lintClientSource(src);
241
- const fails = v.filter((x) => x.level === "FAIL");
242
- const ok = expect === "FAIL" ? fails.length > 0 : expect === "PASS" ? v.length === 0 : v.length > 0 && fails.length === 0;
243
- if (!ok) {
244
- bad++;
245
- console.log(`SELFTEST FAIL [${desc}] 期望 ${expect},实际 ${JSON.stringify(v)}`);
246
- }
247
- };
248
- MUST_FAIL.forEach((s) => check(s, "FAIL", s.slice(0, 40)));
249
- MUST_WARN.forEach((s) => check(s, "WARN", s.slice(0, 40)));
250
- MUST_PASS.forEach((s) => check(s, "PASS", s.replace(/\n/g, "⏎").slice(0, 40)));
251
- if (bad) {
252
- console.log(`selftest: ${bad} 处未过`);
253
- process.exit(1);
254
- }
255
- console.log("selftest: 全部通过(8 FAIL / 3 WARN / 7 PASS)");
256
- }
257
-
258
- if (process.argv[1] && resolve(process.argv[1]) === resolve(import.meta.filename)) {
259
- if (process.argv.includes("--selftest")) {
260
- selftest();
261
- } else if (process.argv.length > 2) {
262
- const all = { files: 0, violations: [] };
263
- for (const p of process.argv.slice(2)) lintPath(resolve(p), all);
264
- const fails = all.violations.filter((v) => v.level === "FAIL");
265
- const warns = all.violations.filter((v) => v.level === "warn");
266
- if (all.violations.length) console.log(formatViolations(all.violations));
267
- console.log(`\n${all.files} 个文件:FAIL=${fails.length} warn=${warns.length}`);
268
- process.exit(fails.length ? 1 : 0);
269
- } else {
270
- console.log("用法:node check-client.mjs <file|dir>... | --selftest");
271
- process.exit(2);
272
- }
273
- }
package/deploy-commit.mjs DELETED
@@ -1,52 +0,0 @@
1
- /**
2
- * deploy 脚本共享「部署状态 commit」助手(pi-web-ext 各扩展 tools/deploy.mjs 统一用)。
3
- *
4
- * 背景(2026-08-30 排障,session 0cc6ad47 op264):重复部署同内容时
5
- * `git add -A && git commit` 以 "nothing to commit" exit 1,而 stdio:"ignore" 吞掉
6
- * stderr,输出「提交失败(忽略):Command failed: …」假报警(msg-smart 实证);
7
- * 另有 --allow-empty 族每次部署都造空 commit 噪音。本助手统一三态语义:
8
- * committed → 有暂存变更,已提交
9
- * clean → 无变更,跳过(不算失败)
10
- * failed → git 真失败(带 stderr 首行,不阻断部署——部署本体永远优先)
11
- *
12
- * 用法:
13
- * import { deployCommit } from "../../_shared/deploy-commit.mjs";
14
- * deployCommit({ repo: extRepo, name: "aiti-msg-smart", paths: ["aiti-msg-smart"],
15
- * log: (m) => console.log("[deploy] " + m) });
16
- *
17
- * 红线:本助手永不 throw、不触碰部署产物路径之外的任何东西;只对 <repo> 做
18
- * add/diff/commit(默认 --no-verify,extRepo 无 hooks,防未来误挂)。
19
- */
20
- import { execFileSync } from "node:child_process";
21
-
22
- export function deployCommit({ repo, name, paths = null, extraMsg = "", ident = false, log = console.log }) {
23
- const git = (args) =>
24
- execFileSync("git", args, { cwd: repo, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
25
- const firstLine = (s) => String(s || "").trim().split("\n")[0];
26
- try {
27
- // 暂存:默认只收本扩展子目录(与 add <ext> 行为对齐;避免把别的扩展的
28
- // 未提交改动卷进本扩展的部署 commit);paths=null 时退回 add -A 全仓。
29
- git(["add", ...(paths && paths.length ? ["--", ...paths] : ["-A"])]);
30
- let dirty;
31
- try {
32
- git(["diff", "--cached", "--quiet"]);
33
- dirty = false; // exit 0 = 暂存区与 HEAD 一致
34
- } catch (e) {
35
- if (e.status !== 1) throw e; // 1 = 有变更;其他才是真错误
36
- dirty = true;
37
- }
38
- if (!dirty) {
39
- log("扩展仓库无变化(跳过提交)");
40
- return { status: "clean" };
41
- }
42
- const stamp = new Date().toISOString().replace("T", " ").slice(0, 19);
43
- const msg = `[deploy] ${name} · ${stamp}${extraMsg ? " · " + extraMsg : ""}`;
44
- git([...(ident ? ["-c", "user.name=deploy", "-c", "user.email=deploy@local"] : []), "commit", "--no-verify", "-m", msg]);
45
- log("扩展仓库已提交:" + msg);
46
- return { status: "committed", msg };
47
- } catch (e) {
48
- const reason = firstLine(e.stderr) || firstLine(e.message) || "git error";
49
- log("提交失败(忽略,不影响部署):" + reason);
50
- return { status: "failed", reason };
51
- }
52
- }
package/dev-pack.mjs DELETED
@@ -1,259 +0,0 @@
1
- /**
2
- * pi-web-ext · dev-pack 共享实现(方案 §3.2 / M5:扩展 dev-pack——src + 构建工具 + AGENTS.md 直达部署目录)
3
- *
4
- * 目标:用户在 AI 窗对 AI 说「帮我改一下 xxx 扩展」时,AI 能在**部署目录**直接:
5
- * 读 AGENTS.md → 改 src/ → node tools/build.mjs → curl reload → 浏览器生效,不等回开发机。
6
- *
7
- * 各扩展 tools/deploy.mjs 末尾统一追加一段(见本文件同级各 deploy.mjs 模式):
8
- * const { packDevPack } = await import("../../_shared/dev-pack.mjs");
9
- * packDevPack({ extRoot: <扩展源码根>, log: console.log });
10
- *
11
- * packDevPack 向每个已存在的部署目录(~/.pi/web{,-dev}/extensions/<extId>)写入:
12
- * AGENTS.md 源码目录有则拷,无则由模板生成(§3.4)
13
- * src/ client/src/**、根级服务端源码 *.ts/*.cjs/*.mjs、lib/(跳 vendor)、server/、sched/、worker-src/
14
- * tools/build.mjs 现场构建入口(扩展自带则拷真身,否则生成 esbuild 默认版)
15
- * tools/deploy.mjs 部署脚本本身(大改后回源码仓重部署的入口)
16
- * package.json 含 aitiConfigs 声明与 build 脚本
17
- * vite.config.ts 有则拷
18
- *
19
- * 幂等:重复部署整目录覆盖;允许失败:任何异常只 log 不影响 deploy 退出码(调用方 try/catch)。
20
- */
21
- "use strict";
22
- import { homedir } from "node:os";
23
- import { join, resolve, dirname, basename, sep as pathSep } from "node:path";
24
- import {
25
- existsSync, readdirSync, statSync, mkdirSync, cpSync, rmSync, writeFileSync, readFileSync,
26
- } from "node:fs";
27
-
28
- // 根级服务端源码文件:拷进 src/(运行时平铺文件在部署根不动,宿主 loader 路径不变)
29
- const ROOT_SRC_EXTS = new Set([".ts", ".tsx", ".cjs", ".mjs"]);
30
- const ROOT_SRC_SKIP = new Set(["dist", "node_modules"]);
31
- // 源码子目录:整目录拷(vendor 类大资产跳过——部署目录本就有运行时副本)
32
- const SRC_DIRS = ["client/src", "server", "lib", "sched", "worker-src"];
33
- const DIR_SKIP = new Set(["vendor", "__pycache__", "node_modules"]);
34
-
35
- function copyTree(src, dest, skip) {
36
- mkdirSync(dest, { recursive: true });
37
- for (const en of readdirSync(src, { withFileTypes: true })) {
38
- if (skip && skip.has(en.name)) continue;
39
- const s = join(src, en.name), d = join(dest, en.name);
40
- if (en.isDirectory()) copyTree(s, d, skip);
41
- else if (en.isFile()) cpSync(s, d);
42
- }
43
- }
44
-
45
- /** AGENTS.md 默认模板(§3.4;扩展自带 AGENTS.md 则不走到这里)。供 CLI 批量生成源码目录版复用。 */
46
- export function agentsMdTemplate(extId) {
47
- return `# ${extId} 扩展(部署目录直改指南)
48
-
49
- ## 结构
50
- - 运行时文件平铺在本目录根(index.ts / core.cjs …,宿主 loader 按相对路径加载——**禁手改运行时平铺文件**,改 src/ 再 build)
51
- - \`src/\` 源码(client/src + 服务端 ts/cjs)· \`dist/\` 构建产物(禁手改)· \`tools/\` 构建/部署脚本
52
- - npm 包形态的扩展:本目录 package.json 含 version 与 aitiConfigs 声明
53
-
54
- ## 小改现场流程(改文案/样式/小逻辑)
55
- 1. 改 \`src/\` 下对应源码
56
- 2. \`node tools/build.mjs\`(client 有构建产物的扩展;纯服务端改动跳过)
57
- 3. \`curl -X POST http://127.0.0.1:3001/api/extensions/reload\`(dev;prod 3002;外部经 nginx 带 basePath:/dev、/mac、/mdev、/win、/wdev → \`/xxx/api/extensions/reload\`)
58
- 4. 浏览器刷新页面验证
59
-
60
- ## 大改回源码仓
61
- - 源码仓:\`extensions/${extId}/\`(git 管理,deploy 同步回本目录)
62
- - 改完在源码仓跑 \`node tools/deploy.mjs\`(或仓库根 \`node scripts/deploy-all.mjs --only ${extId}\`)
63
-
64
- ## 数据目录(数据分层:config / cache)
65
- - \`ctx.configDir\` 根级 = 配置与关键小状态(aiti-configs 备份范围;小、珍贵、人可读)
66
- - \`ctx.cacheDir\`(= \`<configDir>/cache/\`)= 可删缓存:db/venv/日志/大文件;rm -rf 后扩展下次访问自动重建
67
- - \`ctx.dataDir\` 已移除(访问即抛)——新代码禁用
68
- - 本扩展白名单(永不为 cache 的配置文件)见 package.json \`aitiConfigs.configFiles\`
69
-
70
- ## 红线
71
- - 禁轮询(setInterval 拉取);需要等待用事件/回调/SSE(桥的 SSE、aiti-event-bus topics)
72
- - 禁重启生产服务(pi-web 3002 等 restart 须用户明确同意)
73
- - 禁手改 dist/ 与运行时平铺文件;跨扩展通信走 ctx.services(禁 globalThis.__ext 直穿)
74
- - 服务端:SQLite 一律 WAL + 分批小事务(批间 setImmediate 让步);禁 execFileSync 调 >1s 外部程序;>8MB 文件禁同步读
75
- `;
76
- }
77
-
78
- /** 默认 tools/build.mjs(esbuild 单包零配置;扩展自带 tools/build.mjs 则不走到这里)。 */
79
- function buildMjsTemplate(extId, extRoot, clientOut, entryRel) {
80
- // No hardcoded checkout path: candidates are resolved at run time (see repoCandidates below).
81
- return `/**
82
- * ${extId} · 现场构建入口(dev-pack 默认模板,esbuild 单包零配置)
83
- * 用法:node tools/build.mjs
84
- * 本文件由 dev-pack 生成;复杂构建(多入口/插件链)请参照 src/vite.config.ts 改写本文件或回源码仓构建。
85
- */
86
- "use strict";
87
- import { existsSync, readdirSync, constants as fsConstants, accessSync } from "node:fs";
88
- import { join, resolve, dirname, basename, sep as pathSep } from "node:path";
89
- import { fileURLToPath } from "node:url";
90
- import { spawnSync } from "node:child_process";
91
-
92
- const here = dirname(fileURLToPath(import.meta.url));
93
- const extRoot = resolve(here, "..");
94
- const clientOut = ${JSON.stringify(clientOut || "dist/client-bundle.mjs")};
95
- const entryRel = ${JSON.stringify(entryRel || "")};
96
-
97
- // esbuild 解析:部署目录 node_modules → 源码仓 node_modules(本机开发场景)→ PATH 上的 esbuild → npm exec 现拉。
98
- // 注意:node_modules/esbuild/bin/esbuild 是原生二进制(ELF/Mach-O),必须直接执行(不能当 JS 跑)。
99
- // Checkout roots are discovered by walking up from the extension dir (a root has node_modules/),
100
- // plus AITI_REPO_ROOT when set — no machine-specific absolute paths baked into generated files.
101
- function repoCandidates() {
102
- const out = [];
103
- if (process.env.AITI_REPO_ROOT) out.push(process.env.AITI_REPO_ROOT.split(pathSep).join("/") + "/node_modules/esbuild/bin/esbuild");
104
- let d = extRoot;
105
- for (let i = 0; i < 8; i++) {
106
- out.push(d.split(pathSep).join("/") + "/node_modules/esbuild/bin/esbuild");
107
- const up = dirname(d);
108
- if (up === d) break;
109
- d = up;
110
- }
111
- return out;
112
- }
113
- function findEsbuild() {
114
- const home = (process.env.HOME || process.env.USERPROFILE || "").split(pathSep).join("/");
115
- const candidates = [
116
- extRoot + "/node_modules/esbuild/bin/esbuild",
117
- ...repoCandidates(),
118
- ];
119
- for (const c of candidates) {
120
- if (!existsSync(c)) continue;
121
- try { accessSync(c, fsConstants.X_OK); return [c]; } catch (e) { /* 无执行位 → 下一个来源 */ }
122
- }
123
- const r = spawnSync("esbuild", ["--version"], { encoding: "utf8" });
124
- if (r.status === 0) return ["esbuild"];
125
- return ["npm", "exec", "--yes", "esbuild", "--"];
126
- }
127
-
128
- function pickEntry() {
129
- if (entryRel) return entryRel;
130
- const srcDir = join(extRoot, "src", "client", "src");
131
- if (!existsSync(srcDir)) throw new Error("找不到 client 源码目录 src/client/src");
132
- for (const name of ["entry.tsx", "entry.ts", "entry.jsx", "entry.js", "index.tsx", "index.ts"]) {
133
- if (existsSync(join(srcDir, name))) return "client/src/" + name;
134
- }
135
- const first = readdirSync(srcDir).find((f) => /\\.(tsx?|jsx?)$/.test(f));
136
- if (!first) throw new Error("client/src 下没有可构建入口");
137
- return "client/src/" + first;
138
- }
139
-
140
- // 服务端源码同步:src/ 根级文件(index.ts/core.cjs/package.json/vite.config.ts 等)→ 部署根
141
- // (服务端没有构建产物——jiti 直接加载部署根文件;不 sync 则「改 src → reload」永远不生效)
142
- import { readdirSync as _rd, copyFileSync as _cp, statSync as _st } from "node:fs";
143
- const srcRoot = join(extRoot, "src");
144
- if (existsSync(srcRoot)) {
145
- for (const f of _rd(srcRoot)) {
146
- const fp = join(srcRoot, f);
147
- if (!_st(fp).isFile()) continue;
148
- _cp(fp, join(extRoot, f));
149
- }
150
- console.log("[build] 服务端源码已从 src/ 同步到部署根");
151
- }
152
-
153
- const entry = pickEntry();
154
- const args = [join(extRoot, "src", entry), "--bundle", "--format=esm",
155
- "--outfile=" + join(extRoot, clientOut), "--jsx=automatic"];
156
- // pi-web host-shim 委托(react → 本地 shim;jsx-runtime 同理)——与各扩展 vite.config 同款
157
- const shim = join(extRoot, "src", "client", "src", "host-shim.ts");
158
- const jsxRuntime = ["jsx-runtime.ts", "jsx-runtime.tsx", "jsx-dev-runtime.ts"].map((f) => join(extRoot, "src", "client", "src", f)).find(existsSync);
159
- if (existsSync(shim)) args.push("--alias:react=" + shim);
160
- if (jsxRuntime) args.push("--alias:react/jsx-runtime=" + jsxRuntime);
161
- args.push("--log-level=info");
162
-
163
- const [cmd, ...pre] = findEsbuild();
164
- console.log("[build] esbuild:", cmd, ...pre);
165
- const r = spawnSync(cmd, [...pre, ...args], { stdio: "inherit", cwd: extRoot });
166
- if (r.status !== 0) { console.error("[build] 失败——可参照 src/vite.config.ts 调整本文件后重试,或回源码仓构建"); process.exit(r.status ?? 1); }
167
- console.log("[build] ✓ " + clientOut + "(reload 后浏览器刷新生效)");
168
- `;
169
- }
170
-
171
- /**
172
- * 主入口:向已存在的部署目录写 dev-pack。
173
- * @param {object} opts
174
- * @param {string} opts.extRoot 扩展源码根(pi-web-ext/<extId>)
175
- * @param {string[]} [opts.targets] 显式部署目录;缺省 = ~/.pi/web{,-dev}/extensions/<extId>(存在的才写)
176
- * @param {(m: string) => void} [opts.log]
177
- */
178
- export function packDevPack(opts) {
179
- const extRoot = resolve(opts.extRoot);
180
- const extId = basename(extRoot);
181
- const log = opts.log || (() => {});
182
- const targets = (opts.targets || [
183
- join(homedir(), ".pi", "web", "extensions", extId),
184
- join(homedir(), ".pi", "web-dev", "extensions", extId),
185
- ]).filter((t) => existsSync(t));
186
- if (!targets.length) return;
187
-
188
- // 1) 打包源码到临时区(staging)→ 逐目标 cpSync(多部署目录零重复扫描)
189
- const stage = join(extRoot, "dist", ".dev-pack-staging");
190
- rmSync(stage, { recursive: true, force: true });
191
- mkdirSync(stage, { recursive: true });
192
- try {
193
- // src/:根级源码文件 + 源码子目录
194
- const srcDir = join(stage, "src");
195
- mkdirSync(srcDir, { recursive: true });
196
- for (const en of readdirSync(extRoot, { withFileTypes: true })) {
197
- if (en.isDirectory()) continue;
198
- if (ROOT_SRC_SKIP.has(en.name)) continue;
199
- if (!ROOT_SRC_EXTS.has(en.name.slice(en.name.lastIndexOf(".") || 0)) && en.name !== "package.json") continue;
200
- cpSync(join(extRoot, en.name), join(srcDir, en.name));
201
- }
202
- for (const d of SRC_DIRS) {
203
- const s = join(extRoot, d);
204
- if (!existsSync(s)) continue;
205
- copyTree(s, join(srcDir, ...d.split("/")), DIR_SKIP);
206
- }
207
- for (const f of ["vite.config.ts", "package.json"]) {
208
- if (existsSync(join(extRoot, f))) cpSync(join(extRoot, f), join(srcDir, f));
209
- }
210
- // tools/build.mjs:扩展自带拷真身,否则生成默认 esbuild 版
211
- mkdirSync(join(stage, "tools"), { recursive: true });
212
- if (existsSync(join(extRoot, "tools", "build.mjs"))) {
213
- cpSync(join(extRoot, "tools", "build.mjs"), join(stage, "tools", "build.mjs"));
214
- } else {
215
- let clientOut = "";
216
- try {
217
- const pkg = JSON.parse(readFileSync(join(extRoot, "package.json"), "utf8"));
218
- if (pkg.client && String(pkg.client).startsWith("dist/")) clientOut = pkg.client;
219
- } catch (e) {}
220
- if (!clientOut) {
221
- // 回退:client 产物名常声明在 entry 的 client: "dist/<id>-client.mjs"(index.ts)——从 staging 的 src 里解析
222
- try {
223
- for (const f of readdirSync(srcDir)) {
224
- if (!/\.tsx?$/.test(f)) continue;
225
- const m = readFileSync(join(srcDir, f), "utf8").match(/client\s*:\s*["'`](dist\/[\w.-]+\.mjs)["'`]/);
226
- if (m) { clientOut = m[1]; break; }
227
- }
228
- } catch (e) {}
229
- }
230
- writeFileSync(join(stage, "tools", "build.mjs"), buildMjsTemplate(extId, extRoot, clientOut, ""));
231
- }
232
- // tools/deploy.mjs 本身
233
- if (existsSync(join(extRoot, "tools", "deploy.mjs"))) {
234
- cpSync(join(extRoot, "tools", "deploy.mjs"), join(stage, "tools", "deploy.mjs"));
235
- }
236
- // AGENTS.md:自带优先,否则模板生成
237
- if (existsSync(join(extRoot, "AGENTS.md"))) cpSync(join(extRoot, "AGENTS.md"), join(stage, "AGENTS.md"));
238
- else writeFileSync(join(stage, "AGENTS.md"), agentsMdTemplate(extId));
239
-
240
- // 1.5) _shared 依赖:部署 src 里的源码可能相对引用 ../../../_shared/*(源仓出仓路径)——
241
- // 部署根放一份 _shared(小体量、纯源码),让现场 build 的模块解析与源仓一致
242
- const sharedSrc = resolve(extRoot, "..", "_shared");
243
- if (existsSync(sharedSrc)) {
244
- const sharedStage = join(stage, "_shared");
245
- copyTree(sharedSrc, sharedStage, DIR_SKIP);
246
- }
247
-
248
- // 2) 落位(staging → 部署目录;package.json/vite.config.ts 双放:根级按 §3.2 结构,src 内供现场阅读)
249
- for (const t of targets) {
250
- cpSync(stage, t, { recursive: true });
251
- for (const f of ["package.json", "vite.config.ts"]) {
252
- if (existsSync(join(stage, f))) cpSync(join(stage, f), join(t, f));
253
- }
254
- }
255
- log(`dev-pack → ${targets.map((t) => t.replace(homedir(), "~")).join(", ")}(AGENTS.md + src/ + tools/)`);
256
- } finally {
257
- rmSync(stage, { recursive: true, force: true });
258
- }
259
- }
@@ -1,24 +0,0 @@
1
- /**
2
- * 扩展图标部署侧(Node only):把 `_shared/icons/<name>.svg` 拷进扩展部署目录 `icons/`。
3
- *
4
- * 契约(2026-09 拍板):扩展注册只写文件名 `icon: "icons/<name>.svg"`(扩展内部文件),
5
- * 宿主加载扩展时(pi-web lib/ext/loader.ts embedUiSvgIcons)读文件动态生成内嵌 {svg}——
6
- * 源码里不静态写 path,也没有 token 替换;图标库只有一处:`_shared/icons/*.svg`。
7
- *
8
- * deploy.mjs 在拷贝循环后调用:
9
- * for (const t of targets) copyIcons(resolve(t, "icons"), ["mic", "history"], { log });
10
- */
11
- import { copyFileSync, mkdirSync } from "node:fs";
12
- import { resolve, dirname } from "node:path";
13
- import { fileURLToPath } from "node:url";
14
-
15
- const ICONS_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "icons");
16
-
17
- export function copyIcons(destDir, names, { log } = {}) {
18
- mkdirSync(destDir, { recursive: true });
19
- for (const name of names) {
20
- const file = name.endsWith(".svg") ? name : name + ".svg";
21
- copyFileSync(resolve(ICONS_DIR, file), resolve(destDir, file));
22
- log?.(`[deploy] 图标 ${file} → ${destDir}`);
23
- }
24
- }
package/icons/eye.svg DELETED
@@ -1 +0,0 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
@@ -1,41 +0,0 @@
1
- /**
2
- * _shared/reconcile-deps.mjs · 通知 pi-web 双实例对齐扩展共享依赖(各扩展 deploy.mjs 共用)
3
- *
4
- * 背景:扩展运行时依赖统一装进共享根 <webRoot>/node_modules(jiti 从扩展目录向上解析
5
- * 自动命中;机制仿 pi 本体 npm: 包安装)。共享根的唯一写入方是 aiti-extman 的
6
- * shared-deps reconcile——deploy.mjs 拷完文件后 POST 本通知即可,不在部署脚本里跑 npm。
7
- *
8
- * 用法(与 reload-instances 同款:允许失败,永不 throw、不影响 deploy 退出码):
9
- * import { notifyReconcile } from "../../_shared/reconcile-deps.mjs";
10
- * await notifyReconcile(); // 默认 "[deploy] " 前缀;建议在 reloadInstances() 之前调
11
- *
12
- * 失败无害:extman 在下一次 install/remove/reconcile-deps 时会自愈对齐;双实例各自
13
- * reconcile 各自的 webRoot(~/.pi/web 与 ~/.pi/web-dev),互不相干。
14
- */
15
- import { buildInstances } from "./reload-instances.mjs";
16
-
17
- export async function notifyReconcile(prefix = "[deploy] ") {
18
- for (const inst of buildInstances()) {
19
- if (inst.base === null) {
20
- console.log(`${prefix}reconcile ${inst.name} 跳过:basePath 非法`);
21
- continue;
22
- }
23
- try {
24
- const r = await fetch(inst.base + "/api/extensions/aiti-extman/ops", {
25
- method: "POST",
26
- headers: { "content-type": "application/json" },
27
- body: JSON.stringify({ action: "reconcile-deps", source: "deploy" }),
28
- });
29
- const body = await r.json().catch(() => null);
30
- const err = body && body.deps && body.deps.error;
31
- if (r.ok && body && body.ok) {
32
- console.log(`${prefix}reconcile ${inst.name} → ✓(${Object.keys(body.deps?.deps || {}).length} 个共享依赖)`);
33
- } else {
34
- console.log(`${prefix}reconcile ${inst.name} → HTTP ${r.status} ⚠${err ? " " + err : "(extman 未就绪?下次安装时自动对齐)"}`);
35
- }
36
- } catch (e) {
37
- const cause = e && e.cause ? String(e.cause.code || e.cause.message || e.cause) : String((e && e.message) || e);
38
- console.log(`${prefix}reconcile ${inst.name} 不可达(${cause})— 下次安装时自动对齐`);
39
- }
40
- }
41
- }
@@ -1,60 +0,0 @@
1
- /**
2
- * _shared/reload-instances.mjs · pi-web 双实例热重载(各扩展 deploy.mjs 共用)
3
- *
4
- * dev 3001 / 生产 3002;端口可经 AITI_DEV_PORT / AITI_PROD_PORT 覆盖;
5
- * basePath 双 env(AITI_DEV_BASE_PATH / AITI_PROD_BASE_PATH)按机器设值,
6
- * 推荐值不带斜杠(48:dev 与 空;155:系统级 wdev 与 win)——git-bash 启动
7
- * 原生程序时会把 / 开头的 env 值做 MSYS 路径转换(/wdev → D:/apps/Git/wdev)
8
- * 致 URL 非法;不带斜杠则不触发转换。此处自动补 /(旧 /xxx 格式仍兼容),
9
- * 兼容不了时提示 MSYS_NO_PATHCONV=1。
10
- * 避免「server 端代码改了、实例没 reload 导致跑旧逻辑」。
11
- *
12
- * 用法(静态 import 或顶层 await import 均可):
13
- * import { reloadInstances } from "../../_shared/reload-instances.mjs";
14
- * await reloadInstances(); // 默认 "[deploy] " 前缀
15
- */
16
- const BASE_PATH_RE = /^\/[A-Za-z0-9._-]*$/;
17
-
18
- function buildInstance(name, portEnv, portDefault, pathEnv, pathDefault) {
19
- const origin = `http://127.0.0.1:${process.env[portEnv] || portDefault}`;
20
- const raw = process.env[pathEnv];
21
- if (raw === undefined || raw === null || String(raw).trim() === "") return { name, base: origin + pathDefault };
22
- // 自动补 /:wdev → /wdev(推荐无斜杠格式,MSYS 不转换);/wdev → /wdev(旧格式兼容)
23
- const p = "/" + String(raw).trim().replace(/^\/+|\/+$/g, "");
24
- if (BASE_PATH_RE.test(p)) return { name, base: origin + p };
25
- return { name, base: null, raw };
26
- }
27
-
28
- /** 双实例清单(dev/prod 各 {name, base});reload-instances 与 reconcile-deps 等共用。 */
29
- export function buildInstances() {
30
- return [
31
- buildInstance("dev", "AITI_DEV_PORT", 3001, "AITI_DEV_BASE_PATH", "/dev"),
32
- buildInstance("prod", "AITI_PROD_PORT", 3002, "AITI_PROD_BASE_PATH", ""),
33
- ];
34
- }
35
-
36
- export async function reloadInstances(prefix = "[deploy] ") {
37
- // 批次合并(deploy-all 场景):子条目部署脚本被注入 PI_WEB_DEFER_RELOAD=1 时不各自 reload,
38
- // 由 deploy-all 在全部条目完成后统一执行一轮(N 条目 × 2 实例 → 2 次 POST)。
39
- // 避免批量部署时的 reload 风暴(2026-09-15 实测:65 条目逐个 reload 把 dev 实例打满)。
40
- // 单独跑某个扩展 deploy.mjs 不带该 env → 行为不变(部署完立即 reload)。
41
- if (process.env.PI_WEB_DEFER_RELOAD === "1") {
42
- console.log(`${prefix}reload 已 defer(PI_WEB_DEFER_RELOAD=1,由 deploy-all 收尾统一执行)`);
43
- return;
44
- }
45
- // 允许失败:网络异常/非 2xx/服务未启动/env 非法一律只打提示,永不 throw——不影响 deploy 退出码
46
- for (const inst of buildInstances()) {
47
- if (inst.base === null) {
48
- const msysHint = /[\\:]/.test(inst.raw) ? "——疑似 git-bash MSYS 路径转换,用 MSYS_NO_PATHCONV=1 前缀重跑" : "";
49
- console.log(`${prefix}reload ${inst.name} 跳过:AITI_${inst.name.toUpperCase()}_BASE_PATH="${inst.raw}" 非法(须形如 /xxx 或留空)${msysHint}`);
50
- continue;
51
- }
52
- try {
53
- const r = await fetch(inst.base + "/api/extensions/reload", { method: "POST" });
54
- console.log(`${prefix}reload ${inst.name} → HTTP ${r.status} ${r.ok ? "✓" : "⚠ 失败(请手动 POST /api/extensions/reload)"}`);
55
- } catch (e) {
56
- const cause = e && e.cause ? String(e.cause.code || e.cause.message || e.cause) : String((e && e.message) || e);
57
- console.log(`${prefix}reload ${inst.name} 不可达(${cause})— 需手动 POST /api/extensions/reload`);
58
- }
59
- }
60
- }