@uncarved/jade 0.1.2 → 0.1.3

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.
Files changed (151) hide show
  1. package/README.md +204 -198
  2. package/bin/jade.js +23 -0
  3. package/dist/commands.d.ts +20 -0
  4. package/dist/commands.js +20 -0
  5. package/dist/commands.js.map +1 -1
  6. package/dist/distro.d.ts +43 -6
  7. package/dist/distro.js +198 -48
  8. package/dist/distro.js.map +1 -1
  9. package/dist/index.d.ts +2 -0
  10. package/dist/index.js +2 -0
  11. package/dist/index.js.map +1 -1
  12. package/dist/main.js +436 -300
  13. package/dist/main.js.map +1 -1
  14. package/dist/plugin-cli.d.ts +1 -1
  15. package/dist/plugin-cli.js +79 -36
  16. package/dist/plugin-cli.js.map +1 -1
  17. package/dist/plugins/budget.d.ts +2 -2
  18. package/dist/plugins/budget.js +2 -2
  19. package/dist/plugins/budget.js.map +1 -1
  20. package/dist/plugins/builtins.js +6 -3
  21. package/dist/plugins/builtins.js.map +1 -1
  22. package/dist/plugins/checks.d.ts +2 -1
  23. package/dist/plugins/checks.js +25 -5
  24. package/dist/plugins/checks.js.map +1 -1
  25. package/dist/plugins/compact.js +45 -1
  26. package/dist/plugins/compact.js.map +1 -1
  27. package/dist/plugins/core.d.ts +5 -0
  28. package/dist/plugins/core.js +39 -0
  29. package/dist/plugins/core.js.map +1 -1
  30. package/dist/plugins/host.d.ts +52 -0
  31. package/dist/plugins/host.js +115 -0
  32. package/dist/plugins/host.js.map +1 -0
  33. package/dist/plugins/install.d.ts +1 -1
  34. package/dist/plugins/loader.d.ts +238 -10
  35. package/dist/plugins/loader.js +175 -21
  36. package/dist/plugins/loader.js.map +1 -1
  37. package/dist/plugins/policy.d.ts +2 -0
  38. package/dist/plugins/policy.js +17 -1
  39. package/dist/plugins/policy.js.map +1 -1
  40. package/dist/plugins/prompts.d.ts +6 -1
  41. package/dist/plugins/prompts.js +103 -15
  42. package/dist/plugins/prompts.js.map +1 -1
  43. package/dist/plugins/repeats.d.ts +7 -0
  44. package/dist/plugins/repeats.js +74 -13
  45. package/dist/plugins/repeats.js.map +1 -1
  46. package/dist/plugins/review.d.ts +2 -0
  47. package/dist/plugins/review.js +41 -3
  48. package/dist/plugins/review.js.map +1 -1
  49. package/dist/plugins/sessions.d.ts +7 -0
  50. package/dist/plugins/sessions.js +110 -0
  51. package/dist/plugins/sessions.js.map +1 -0
  52. package/dist/provider.d.ts +56 -2
  53. package/dist/provider.js +73 -7
  54. package/dist/provider.js.map +1 -1
  55. package/dist/session-lifecycle.d.ts +61 -0
  56. package/dist/session-lifecycle.js +167 -0
  57. package/dist/session-lifecycle.js.map +1 -0
  58. package/dist/session-scope.d.ts +53 -0
  59. package/dist/session-scope.js +116 -0
  60. package/dist/session-scope.js.map +1 -0
  61. package/dist/sessions.d.ts +6 -0
  62. package/dist/sessions.js +20 -0
  63. package/dist/sessions.js.map +1 -1
  64. package/dist/sys.d.ts +4 -1
  65. package/dist/sys.js +18 -1
  66. package/dist/sys.js.map +1 -1
  67. package/dist/tools/ask.d.ts +11 -0
  68. package/dist/tools/ask.js +62 -0
  69. package/dist/tools/ask.js.map +1 -0
  70. package/dist/tools/fs.d.ts +4 -0
  71. package/dist/tools/fs.js +53 -12
  72. package/dist/tools/fs.js.map +1 -1
  73. package/dist/tools/grep.js +3 -2
  74. package/dist/tools/grep.js.map +1 -1
  75. package/dist/tools/shell.js +5 -1
  76. package/dist/tools/shell.js.map +1 -1
  77. package/dist/tools/task.d.ts +6 -2
  78. package/dist/tools/task.js +36 -8
  79. package/dist/tools/task.js.map +1 -1
  80. package/dist/tools/web.d.ts +33 -3
  81. package/dist/tools/web.js +351 -143
  82. package/dist/tools/web.js.map +1 -1
  83. package/dist/ui/configure.js +91 -22
  84. package/dist/ui/configure.js.map +1 -1
  85. package/dist/ui/diff.d.ts +1 -1
  86. package/dist/ui/diff.js +1 -2
  87. package/dist/ui/diff.js.map +1 -1
  88. package/dist/ui/editor.d.ts +8 -0
  89. package/dist/ui/editor.js +50 -1
  90. package/dist/ui/editor.js.map +1 -1
  91. package/dist/ui/markdown.d.ts +6 -1
  92. package/dist/ui/markdown.js +57 -19
  93. package/dist/ui/markdown.js.map +1 -1
  94. package/dist/ui/render.d.ts +9 -10
  95. package/dist/ui/render.js +35 -72
  96. package/dist/ui/render.js.map +1 -1
  97. package/dist/ui/renderers.d.ts +8 -0
  98. package/dist/ui/renderers.js +169 -0
  99. package/dist/ui/renderers.js.map +1 -0
  100. package/dist/ui/screen.d.ts +22 -2
  101. package/dist/ui/screen.js +104 -15
  102. package/dist/ui/screen.js.map +1 -1
  103. package/dist/ui/transcript.d.ts +13 -0
  104. package/dist/ui/transcript.js +105 -15
  105. package/dist/ui/transcript.js.map +1 -1
  106. package/dist/ui/tui.d.ts +2 -0
  107. package/dist/ui/tui.js +309 -58
  108. package/dist/ui/tui.js.map +1 -1
  109. package/dist/update.d.ts +53 -0
  110. package/dist/update.js +255 -0
  111. package/dist/update.js.map +1 -0
  112. package/package.json +6 -5
  113. package/src/commands.ts +24 -0
  114. package/src/distro.ts +228 -51
  115. package/src/index.ts +2 -0
  116. package/src/main.ts +413 -292
  117. package/src/plugin-cli.ts +73 -34
  118. package/src/plugins/budget.ts +4 -4
  119. package/src/plugins/builtins.ts +6 -3
  120. package/src/plugins/checks.ts +25 -6
  121. package/src/plugins/compact.ts +40 -1
  122. package/src/plugins/core.ts +40 -0
  123. package/src/plugins/host.ts +146 -0
  124. package/src/plugins/install.ts +1 -1
  125. package/src/plugins/loader.ts +379 -23
  126. package/src/plugins/policy.ts +17 -1
  127. package/src/plugins/prompts.ts +108 -15
  128. package/src/plugins/repeats.ts +75 -14
  129. package/src/plugins/review.ts +40 -3
  130. package/src/plugins/sessions.ts +109 -0
  131. package/src/provider.ts +109 -10
  132. package/src/session-lifecycle.ts +194 -0
  133. package/src/session-scope.ts +135 -0
  134. package/src/sessions.ts +17 -0
  135. package/src/sys.ts +18 -1
  136. package/src/tools/ask.ts +72 -0
  137. package/src/tools/fs.ts +53 -12
  138. package/src/tools/grep.ts +3 -2
  139. package/src/tools/shell.ts +5 -1
  140. package/src/tools/task.ts +51 -11
  141. package/src/tools/web.ts +370 -140
  142. package/src/ui/configure.ts +90 -27
  143. package/src/ui/diff.ts +1 -2
  144. package/src/ui/editor.ts +50 -1
  145. package/src/ui/markdown.ts +258 -219
  146. package/src/ui/render.ts +35 -57
  147. package/src/ui/renderers.ts +183 -0
  148. package/src/ui/screen.ts +113 -19
  149. package/src/ui/transcript.ts +109 -16
  150. package/src/ui/tui.tsx +353 -58
  151. package/src/update.ts +262 -0
package/src/update.ts ADDED
@@ -0,0 +1,262 @@
1
+ // 新版本提示和 jade update:查 npm 上的最新版本,按 jade 的安装方式(npm 或 bun 全局安装)升级。
2
+ // 启动时的检查每天最多一次,结果缓存在 $JADE_HOME/update-check.json,查不到时什么也不说
3
+
4
+ import { spawn } from "node:child_process";
5
+ import { closeSync, openSync, realpathSync } from "node:fs";
6
+ import { mkdir, open, readFile, rm, stat, writeFile } from "node:fs/promises";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { npmCommand, VERSION, which } from "./sys.ts";
10
+
11
+ export const PACKAGE = "@uncarved/jade";
12
+ const LATEST_URL = `https://registry.npmjs.org/${PACKAGE}/latest`;
13
+ const CHECK_EVERY_MS = 24 * 60 * 60 * 1000;
14
+ const TIMEOUT_MS = 5000;
15
+ /** 后台升级最多跑这么久;锁文件比这更旧就当作上次升级的进程已经不在了 */
16
+ const INSTALL_TIMEOUT_MS = 10 * 60 * 1000;
17
+ /** 同一个版本升级失败后,隔这么久才再自动试 */
18
+ const RETRY_FAILED_MS = 24 * 60 * 60 * 1000;
19
+
20
+ /** 比较 x.y.z 版本号:a 比 b 新时为 true。带预发布后缀的只比主版本号,主版本号相同时正式版算更新 */
21
+ export function isNewer(a: string, b: string): boolean {
22
+ const parse = (v: string) => {
23
+ const [core, pre] = v.trim().replace(/^v/, "").split("-", 2);
24
+ return { parts: core!.split(".").map((n) => Number.parseInt(n, 10) || 0), pre: pre !== undefined };
25
+ };
26
+ const x = parse(a);
27
+ const y = parse(b);
28
+ for (let i = 0; i < 3; i++) {
29
+ const d = (x.parts[i] ?? 0) - (y.parts[i] ?? 0);
30
+ if (d) return d > 0;
31
+ }
32
+ return !x.pre && y.pre;
33
+ }
34
+
35
+ /** 从 npm registry 读最新版本号;网络不通、超时或返回不对时 reject */
36
+ export async function fetchLatest(signal?: AbortSignal): Promise<string> {
37
+ const res = await fetch(LATEST_URL, {
38
+ headers: { accept: "application/json" },
39
+ signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(TIMEOUT_MS)]) : AbortSignal.timeout(TIMEOUT_MS),
40
+ });
41
+ if (!res.ok) throw new Error(`npm registry answered ${res.status}`);
42
+ const { version } = (await res.json()) as { version?: unknown };
43
+ if (typeof version !== "string" || !/^\d+\.\d+\.\d+/.test(version)) throw new Error("npm registry gave no version");
44
+ return version;
45
+ }
46
+
47
+ interface CheckCache {
48
+ checkedAt: number;
49
+ latest: string;
50
+ }
51
+
52
+ /**
53
+ * 启动时用:有比当前更新的版本时返回它的版本号。距上次查询不到一天时用缓存,不发请求;
54
+ * JADE_UPDATE_CHECK=off 时不查。任何错误都当作没有新版本
55
+ */
56
+ export async function newerVersion(home: string, opts: { now?: number; current?: string; latest?: () => Promise<string> } = {}): Promise<string | undefined> {
57
+ if (/^(0|off|false|no)$/i.test(process.env.JADE_UPDATE_CHECK?.trim() ?? "")) return undefined;
58
+ const now = opts.now ?? Date.now();
59
+ const current = opts.current ?? VERSION;
60
+ const file = path.join(home, "update-check.json");
61
+ let cache: CheckCache | undefined;
62
+ try {
63
+ const c = JSON.parse(await readFile(file, "utf8")) as Partial<CheckCache>;
64
+ if (typeof c.checkedAt === "number" && typeof c.latest === "string") cache = c as CheckCache;
65
+ } catch {}
66
+ if (!cache || now - cache.checkedAt >= CHECK_EVERY_MS || now < cache.checkedAt) {
67
+ try {
68
+ cache = { checkedAt: now, latest: await (opts.latest ?? fetchLatest)() };
69
+ } catch {
70
+ return undefined;
71
+ }
72
+ await mkdir(home, { recursive: true })
73
+ .then(() => writeFile(file, JSON.stringify(cache) + "\n"))
74
+ .catch(() => {});
75
+ }
76
+ return isNewer(cache.latest, current) ? cache.latest : undefined;
77
+ }
78
+
79
+ export type Install = { kind: "npm" | "bun" | "pnpm" | "yarn"; dir: string } | { kind: "dev"; dir: string };
80
+
81
+ /**
82
+ * 看 jade 的包目录(解析符号链接后)在哪:不在 node_modules 里就是仓库里的开发版或 npm link;
83
+ * 在 bun、pnpm、yarn 的全局目录里按对应工具算,其余按 npm 算
84
+ */
85
+ export function detectInstall(dir: string = packageDir()): Install {
86
+ const p = dir.replace(/\\/g, "/");
87
+ if (!/\/node_modules\//.test(p)) return { kind: "dev", dir };
88
+ if (/\/\.bun\/install\/global\//.test(p)) return { kind: "bun", dir };
89
+ if (/\/pnpm\/|\/\.pnpm\//.test(p)) return { kind: "pnpm", dir };
90
+ if (/\/yarn\/global\//i.test(p)) return { kind: "yarn", dir };
91
+ return { kind: "npm", dir };
92
+ }
93
+
94
+ /** jade 的包根目录:src/update.ts 和 dist/update.js 都在它下面一层 */
95
+ function packageDir(): string {
96
+ const dir = fileURLToPath(new URL("..", import.meta.url));
97
+ try {
98
+ return realpathSync.native(dir);
99
+ } catch {
100
+ return path.resolve(dir);
101
+ }
102
+ }
103
+
104
+ /** 给用户看的升级命令 */
105
+ export function upgradeHint(kind: Install["kind"] = detectInstall().kind): string {
106
+ const spec = `${PACKAGE}@latest`;
107
+ if (kind === "bun") return `bun add -g ${spec}`;
108
+ if (kind === "pnpm") return `pnpm add -g ${spec}`;
109
+ if (kind === "yarn") return `yarn global add ${spec}`;
110
+ return `npm install -g ${spec}`;
111
+ }
112
+
113
+ /** 实际执行的升级命令;找不到对应的程序时为 undefined */
114
+ function upgradeCommand(kind: Install["kind"]): string[] | undefined {
115
+ const spec = `${PACKAGE}@latest`;
116
+ if (kind === "npm") {
117
+ const npm = npmCommand();
118
+ return npm && [...npm, "install", "-g", spec];
119
+ }
120
+ const bin = which(process.platform === "win32" && kind !== "bun" ? `${kind}.cmd` : kind);
121
+ if (!bin) return undefined;
122
+ if (kind === "bun") return [bin, "add", "-g", spec];
123
+ if (kind === "pnpm") return [bin, "add", "-g", spec];
124
+ return [bin, "global", "add", spec];
125
+ }
126
+
127
+ /** jade update:返回退出码。输出直接写到终端,安装命令的输出也直接显示 */
128
+ export async function updateCli(args: string[]): Promise<number> {
129
+ if (args.includes("-h") || args.includes("--help")) {
130
+ console.log(`Usage: jade update [--check]\n\n Upgrade jade to the latest version on npm.\n --check only report whether a newer version exists`);
131
+ return 0;
132
+ }
133
+ const unknown = args.find((a) => a !== "--check");
134
+ if (unknown) {
135
+ console.error(`jade update: unknown option ${unknown}`);
136
+ return 2;
137
+ }
138
+ let latest: string;
139
+ try {
140
+ latest = await fetchLatest();
141
+ } catch (err) {
142
+ console.error(`jade update: could not reach the npm registry: ${err instanceof Error ? err.message : String(err)}`);
143
+ return 1;
144
+ }
145
+ if (!isNewer(latest, VERSION)) {
146
+ console.log(`jade ${VERSION} is up to date${latest !== VERSION ? ` (npm has ${latest})` : ""}.`);
147
+ return 0;
148
+ }
149
+ const install = detectInstall();
150
+ if (args.includes("--check")) {
151
+ console.log(`jade ${latest} is available (you have ${VERSION}). Run: ${install.kind === "dev" ? upgradeHint("npm") : upgradeHint(install.kind)}`);
152
+ return 0;
153
+ }
154
+ if (install.kind === "dev") {
155
+ console.error(`jade update: this jade runs from ${install.dir}, not from a global install (a checkout or npm link); update it with git, or install the package with: ${upgradeHint("npm")}`);
156
+ return 1;
157
+ }
158
+ const cmd = upgradeCommand(install.kind);
159
+ if (!cmd) {
160
+ console.error(`jade update: ${install.kind} was not found; run: ${upgradeHint(install.kind)}`);
161
+ return 1;
162
+ }
163
+ console.log(`Updating jade ${VERSION} → ${latest} with ${install.kind}…`);
164
+ const code = await new Promise<number | null>((resolve) => {
165
+ const child = spawn(cmd[0]!, cmd.slice(1), { stdio: "inherit" });
166
+ child.on("error", () => resolve(-1));
167
+ child.on("exit", (c) => resolve(c));
168
+ });
169
+ if (code !== 0) {
170
+ console.error(`jade update: ${install.kind} failed${code === -1 ? " to start" : ` (exit ${code})`}. Run it yourself: ${upgradeHint(install.kind)}`);
171
+ return 1;
172
+ }
173
+ console.log(`jade ${latest} is installed.`);
174
+ return 0;
175
+ }
176
+
177
+ const off = (v: string | undefined) => /^(0|off|false|no)$/i.test(v?.trim() ?? "");
178
+
179
+ /** 自动升级是否打开:JADE_AUTO_UPDATE=off 关闭;JADE_UPDATE_CHECK=off 时连检查都不做 */
180
+ export function autoUpdateEnabled(): boolean {
181
+ return !off(process.env.JADE_AUTO_UPDATE) && !off(process.env.JADE_UPDATE_CHECK);
182
+ }
183
+
184
+ export type AutoUpdateResult =
185
+ /** 装好了,下次启动生效 */
186
+ | { status: "installed" }
187
+ /** 别的 jade 正在升级,或者这个版本不久前刚失败过:这次不试 */
188
+ | { status: "skipped"; why: "busy" | "failed-recently" | "unsupported" }
189
+ | { status: "failed"; log: string };
190
+
191
+ interface Attempt {
192
+ version: string;
193
+ at: number;
194
+ ok: boolean;
195
+ }
196
+
197
+ /**
198
+ * 在后台把 jade 升级到 latest。安装进程和 jade 脱离:jade 先退出时它照常装完,不会留下装了一半的包。
199
+ * 多个 jade 同时启动时用 $JADE_HOME/update.lock 保证只有一个在装;输出写进 $JADE_HOME/update.log
200
+ */
201
+ export async function autoUpdate(home: string, latest: string, opts: { install?: Install; command?: string[] } = {}): Promise<AutoUpdateResult> {
202
+ const install = opts.install ?? detectInstall();
203
+ if (install.kind === "dev") return { status: "skipped", why: "unsupported" };
204
+ const cmd = opts.command ?? upgradeCommand(install.kind);
205
+ if (!cmd) return { status: "skipped", why: "unsupported" };
206
+
207
+ const attemptFile = path.join(home, "update-attempt.json");
208
+ const last = await readFile(attemptFile, "utf8")
209
+ .then((t) => JSON.parse(t) as Attempt)
210
+ .catch(() => undefined);
211
+ if (last && !last.ok && last.version === latest && Date.now() - last.at < RETRY_FAILED_MS) return { status: "skipped", why: "failed-recently" };
212
+
213
+ await mkdir(home, { recursive: true });
214
+ const lock = path.join(home, "update.lock");
215
+ if (!(await takeLock(lock))) return { status: "skipped", why: "busy" };
216
+
217
+ const log = path.join(home, "update.log");
218
+ let ok = false;
219
+ try {
220
+ const fd = openSync(log, "w");
221
+ try {
222
+ ok = await new Promise<boolean>((resolve) => {
223
+ const child = spawn(cmd[0]!, cmd.slice(1), { stdio: ["ignore", fd, fd], detached: true, windowsHide: true });
224
+ const timer = setTimeout(() => resolve(false), INSTALL_TIMEOUT_MS);
225
+ timer.unref();
226
+ child.on("error", () => resolve(false));
227
+ child.on("exit", (code) => {
228
+ clearTimeout(timer);
229
+ resolve(code === 0);
230
+ });
231
+ // jade 退出时不等它,它自己装完
232
+ child.unref();
233
+ });
234
+ } finally {
235
+ closeSync(fd);
236
+ }
237
+ } catch {
238
+ ok = false;
239
+ } finally {
240
+ await rm(lock, { force: true }).catch(() => {});
241
+ }
242
+ await writeFile(attemptFile, JSON.stringify({ version: latest, at: Date.now(), ok } satisfies Attempt) + "\n").catch(() => {});
243
+ return ok ? { status: "installed" } : { status: "failed", log };
244
+ }
245
+
246
+ /** 新建锁文件;已经有了且不算太旧时返回 false,太旧的(上次的进程不在了)删掉重来 */
247
+ async function takeLock(lock: string): Promise<boolean> {
248
+ for (let i = 0; i < 2; i++) {
249
+ try {
250
+ const h = await open(lock, "wx");
251
+ await h.writeFile(String(process.pid));
252
+ await h.close();
253
+ return true;
254
+ } catch (err) {
255
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") return false;
256
+ const age = await stat(lock).then((s) => Date.now() - s.mtimeMs, () => 0);
257
+ if (age < INSTALL_TIMEOUT_MS) return false;
258
+ await rm(lock, { force: true }).catch(() => {});
259
+ }
260
+ }
261
+ return false;
262
+ }