@insmind/cli 2.1.1 → 2.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 (46) hide show
  1. package/README.md +30 -0
  2. package/dist/bin/sync-skill.js +33 -0
  3. package/dist/src/bootstrap/create-runtime.js +5 -1
  4. package/dist/src/bootstrap/validators.js +88 -152
  5. package/dist/src/cli/agent-commands.js +2 -2
  6. package/dist/src/cli/editor-commands.js +9 -7
  7. package/dist/src/cli/errors.js +4 -5
  8. package/dist/src/cli/host-input.js +3 -5
  9. package/dist/src/cli/observed-errors.js +7 -3
  10. package/dist/src/cli/presenter.js +4 -5
  11. package/dist/src/contracts/creation-input.js +20 -17
  12. package/dist/src/features/auth/credential-store.js +1 -0
  13. package/dist/src/features/dam/object-storage.js +2 -1
  14. package/dist/src/features/dam/use-cases.js +2 -2
  15. package/dist/src/features/editor/bridge-process.js +3 -2
  16. package/dist/src/features/editor/session-state.js +1 -0
  17. package/dist/src/features/task/creation-refusal.js +3 -1
  18. package/dist/src/features/task/store.js +65 -22
  19. package/dist/src/features/task/task-background.js +3 -2
  20. package/dist/src/features/tool/canvas-media.js +2 -3
  21. package/dist/src/features/tool/canvas-results.js +13 -6
  22. package/dist/src/features/tool/catalog.js +2 -23
  23. package/dist/src/features/tool/dynamic-schema.js +3 -6
  24. package/dist/src/features/tool/tool-definitions.js +23 -0
  25. package/dist/src/features/update/package-manager.js +124 -0
  26. package/dist/src/features/update/update-service.js +133 -67
  27. package/dist/src/platform/detached-spawn.js +9 -0
  28. package/dist/src/platform/file-lock.js +12 -4
  29. package/dist/src/platform/input-uri.js +23 -1
  30. package/dist/src/platform/local-json-file.js +97 -15
  31. package/dist/src/platform/open-browser.js +5 -2
  32. package/dist/src/platform/safe-upload-file.js +2 -3
  33. package/dist/src/platform/schema-compiler.js +16 -0
  34. package/dist/src/platform/windows-acl/LICENSE-mingw-w64 +43 -0
  35. package/dist/src/platform/windows-acl/arm64.node +0 -0
  36. package/dist/src/platform/windows-acl/ia32.node +0 -0
  37. package/dist/src/platform/windows-acl/x64.node +0 -0
  38. package/dist/src/platform/windows-host-job/arm64.exe +0 -0
  39. package/dist/src/platform/windows-host-job/ia32.exe +0 -0
  40. package/dist/src/platform/windows-host-job/sha256.json +7 -0
  41. package/dist/src/platform/windows-host-job/x64.exe +0 -0
  42. package/dist/src/platform/windows-private-state.js +72 -0
  43. package/dist/src/product/config.js +1 -1
  44. package/dist/src/telemetry/failure-summary.js +2 -2
  45. package/dist/src/telemetry/sls-sink.js +48 -29
  46. package/package.json +4 -4
@@ -1,5 +1,5 @@
1
1
  import { isInterruption } from "../../platform/interruption.js";
2
- import { spawn } from "node:child_process";
2
+ import { PackageManagerTerminationError, spawnPackageManager, windowsShimTarget } from "./package-manager.js";
3
3
  import { lstatSync, readFileSync, readlinkSync, realpathSync } from "node:fs";
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, isAbsolute, join, resolve } from "node:path";
@@ -31,15 +31,13 @@ export function detectInstallSource(input) {
31
31
  const userAgent = input.env.npm_config_user_agent ?? "";
32
32
  const npmExecPath = normalizePath(input.env.npm_execpath ?? "");
33
33
  const packageName = input.packageName ?? "@gaoding/cli";
34
- const encodedPackage = packageName.replace("/", "+").replace("@", "@");
35
34
  if (userAgent.startsWith("yarn/") || npmExecPath.includes("/yarn/")) {
36
35
  return unsupported("Yarn 安装不支持自动更新");
37
36
  }
38
37
  if (containsTemporaryRunner(binaryPath) || containsTemporaryRunner(packageRoot)) {
39
38
  return unsupported("临时运行方式不支持自动更新");
40
39
  }
41
- if (binaryPath.includes("/node_modules/.bin/")
42
- || packageRoot.startsWith(`${cwd}/node_modules/`)) {
40
+ if (binaryPath.includes("/node_modules/.bin/")) {
43
41
  return unsupported("项目依赖不支持自动更新");
44
42
  }
45
43
  if (!isWithin(realBinaryPath, packageRoot)) {
@@ -48,23 +46,45 @@ export function detectInstallSource(input) {
48
46
  // pnpm 12 can link global and project installs to the same store. The hash
49
47
  // alone is not ownership evidence: match the actual invocation to its global launcher.
50
48
  const command = input.binaryName ?? "gd-cli";
51
- if (realBinaryPath === `${packageRoot}/dist/bin/${command}.js`
52
- && pnpmSnapshotDirectory(binaryPath, packageName, command)
53
- && pnpmLauncherTargets(input.env, command).some(target => target === resolve(input.binaryPath))
54
- && safeRealpath(input.binaryPath) === input.realBinaryPath) {
55
- return { kind: "global", manager: "pnpm", packageRoot: input.packageRoot };
49
+ const platform = input.platform ?? process.platform;
50
+ const pnpmDirectory = pnpmSnapshotDirectory(binaryPath, packageName, command);
51
+ const pnpmLauncher = pnpmLaunchers(input.env, command).find(entry => entry.target === resolve(input.binaryPath));
52
+ if (realBinaryPath === `${packageRoot}/dist/bin/${command}.js` && pnpmDirectory && pnpmLauncher
53
+ && safeRealpath(input.binaryPath) === input.realBinaryPath
54
+ && packageManifestMatches(input.packageRoot, packageName)
55
+ && (!binaryPath.includes("/5/.pnpm/") || legacyManifestMatches(pnpmDirectory, packageName))) {
56
+ return { kind: "global", manager: "pnpm", packageRoot: input.packageRoot, directory: pnpmDirectory, launcher: pnpmLauncher.launcher };
56
57
  }
57
- if (packageRoot.includes(`/global/`) && packageRoot.includes(`/.pnpm/${encodedPackage}@`)
58
- || packageRoot.includes(`/node_modules/${packageName}`)
59
- && /\/v\d+\/[0-9a-f]+-[0-9a-f]+-[0-9a-f]{16}\//u.test(packageRoot)
60
- || binaryPath.includes(`/node_modules/${packageName}/dist/bin/${input.binaryName ?? "gd-cli"}.js`)
61
- && /\/v\d+\/[0-9a-f]+-[0-9a-f]+-[0-9a-f]{16}\//u.test(binaryPath)) {
62
- return { kind: "global", manager: "pnpm", packageRoot: input.packageRoot };
58
+ // Windows npm places packages directly under <prefix>/node_modules. Require
59
+ // the matching npm-generated launcher before treating that layout as global.
60
+ if (platform === "win32" && packageRoot.endsWith(`/node_modules/${packageName}`)
61
+ && realBinaryPath === `${packageRoot}/dist/bin/${command}.js` && packageManifestMatches(input.packageRoot, packageName)) {
62
+ const prefix = dirname(dirname(dirname(input.packageRoot)));
63
+ const launcher = join(prefix, `${command}.cmd`);
64
+ try {
65
+ const shim = readFileSync(launcher, "utf8");
66
+ const target = windowsShimTarget(shim);
67
+ if (target && realpathSync(resolve(prefix, target)) === input.realBinaryPath
68
+ && safeRealpath(input.binaryPath) === input.realBinaryPath) {
69
+ return { kind: "global", manager: "npm", packageRoot: input.packageRoot, directory: prefix, launcher };
70
+ }
71
+ }
72
+ catch { /* no matching launcher */ }
63
73
  }
64
- if (packageRoot.endsWith(`/lib/node_modules/${packageName}`)
65
- || packageRoot.endsWith(`/npm/node_modules/${packageName}`)) {
66
- return { kind: "global", manager: "npm", packageRoot: input.packageRoot };
74
+ if (platform !== "win32" && packageRoot.endsWith(`/lib/node_modules/${packageName}`)
75
+ && realBinaryPath === `${packageRoot}/dist/bin/${command}.js` && packageManifestMatches(input.packageRoot, packageName)) {
76
+ const prefix = dirname(dirname(dirname(dirname(input.packageRoot))));
77
+ try {
78
+ const launcher = join(prefix, "bin", command);
79
+ if (lstatSync(launcher).isSymbolicLink() && realpathSync(launcher) === input.realBinaryPath
80
+ && safeRealpath(input.binaryPath) === input.realBinaryPath) {
81
+ return { kind: "global", manager: "npm", packageRoot: input.packageRoot, directory: prefix, launcher };
82
+ }
83
+ }
84
+ catch { /* no matching global launcher */ }
67
85
  }
86
+ if (packageRoot.startsWith(`${cwd}/node_modules/`))
87
+ return unsupported("项目依赖不支持自动更新");
68
88
  return unsupported("无法确认 npm 或 pnpm 全局安装");
69
89
  }
70
90
  function pnpmSnapshotDirectory(binaryPath, name, command) {
@@ -75,38 +95,74 @@ function pnpmSnapshotDirectory(binaryPath, name, command) {
75
95
  const snapshot = normalized.slice(0, -suffix.length);
76
96
  if (/\/v\d+\/(?:[a-f0-9]{64}|[0-9a-f]+-[0-9a-f]+-[0-9a-f]{16})$/u.test(snapshot))
77
97
  return dirname(dirname(snapshot));
98
+ const marker = `/5/.pnpm/${name.replace("/", "+")}@`;
99
+ const index = snapshot.lastIndexOf(marker);
100
+ if (index > 0 && !snapshot.slice(index + marker.length).includes("/"))
101
+ return resolve(snapshot.slice(0, index));
102
+ }
103
+ function packageManifestMatches(root, name) {
104
+ try {
105
+ return JSON.parse(readFileSync(join(root, "package.json"), "utf8")).name === name;
106
+ }
107
+ catch {
108
+ return false;
109
+ }
110
+ }
111
+ function legacyManifestMatches(directory, name) {
112
+ try {
113
+ return typeof JSON.parse(readFileSync(join(directory, "5", "package.json"), "utf8")).dependencies?.[name] === "string";
114
+ }
115
+ catch {
116
+ return false;
117
+ }
118
+ }
119
+ function launcherTarget(launcher) {
120
+ try {
121
+ const stat = lstatSync(launcher);
122
+ const text = stat.isFile() && stat.size < 131072 ? readFileSync(launcher, "utf8") : undefined;
123
+ // pnpm also emits sh and PowerShell siblings. Identify the forwarded
124
+ // entry from their command, never from a comment naming a different file.
125
+ const shellEntry = text?.startsWith("#!") ? /^\s*exec\s+[^\r\n]*?\s+"([^"\r\n]+\.js)"\s+"\$@"\s*$/mu.exec(text)?.[1]
126
+ ?? /^\s*&\s+[^\r\n]*?\s+"([^"\r\n]+\.js)"\s+\$args\s*$/mu.exec(text)?.[1] : undefined;
127
+ const marker = text && /^#\s*cmd-shim-target=(.+)$/mu.exec(text)?.[1]?.trim();
128
+ const shellTarget = shellEntry?.match(/^\$basedir(?:_win)?\/(.+)$/u)?.[1]
129
+ ?? (marker && shellEntry && resolve(dirname(launcher), marker) === resolve(dirname(launcher), shellEntry) ? shellEntry : undefined);
130
+ const target = stat.isSymbolicLink() ? readlinkSync(launcher) : text
131
+ ? windowsShimTarget(text) ?? shellTarget : undefined;
132
+ if (!target)
133
+ return;
134
+ const entry = resolve(dirname(launcher), target);
135
+ realpathSync(entry);
136
+ return entry;
137
+ }
138
+ catch {
139
+ return;
140
+ }
78
141
  }
79
- function pnpmLauncherTargets(env, command) {
142
+ function pnpmLaunchers(env, command) {
80
143
  const home = env.HOME || env.USERPROFILE || homedir();
81
144
  const pnpmHome = env.PNPM_HOME || (process.platform === "darwin" ? join(home, "Library", "pnpm")
82
145
  : process.platform === "win32" ? join(env.LOCALAPPDATA || join(home, "AppData", "Local"), "pnpm")
83
146
  : join(env.XDG_DATA_HOME || join(home, ".local", "share"), "pnpm"));
84
147
  if (!isAbsolute(pnpmHome))
85
148
  return [];
86
- const targets = [];
149
+ const result = [];
87
150
  for (const dir of [join(pnpmHome, "bin"), pnpmHome]) {
88
151
  for (const ext of process.platform === "win32" ? [".cmd", ".ps1", ""] : [""]) {
89
152
  const launcher = join(dir, command + ext);
90
- try {
91
- const stat = lstatSync(launcher);
92
- const target = stat.isSymbolicLink() ? readlinkSync(launcher)
93
- : stat.isFile() && stat.size < 131072
94
- ? /^(?:#|::|@?REM)\s+cmd-shim-target=(.+)$/imu.exec(readFileSync(launcher, "utf8"))?.[1]?.trim()
95
- : undefined;
96
- if (target) {
97
- const entry = resolve(dirname(launcher), target);
98
- realpathSync(entry);
99
- targets.push(entry);
100
- }
101
- }
102
- catch { /* Another launcher location may exist; ambiguous ownership is never writable. */ }
153
+ const target = launcherTarget(launcher);
154
+ if (target)
155
+ result.push({ launcher, target });
103
156
  }
104
157
  }
105
- return targets;
158
+ return result;
159
+ }
160
+ export function pnpmLauncherTargets(env, command) {
161
+ return pnpmLaunchers(env, command).map(entry => entry.target);
106
162
  }
107
163
  export function createUpdateService(options) {
108
164
  const fetchPackage = options.fetch ?? globalThis.fetch;
109
- const runProcess = options.runProcess ?? spawnProcess;
165
+ const runProcess = options.runProcess ?? spawnPackageManager;
110
166
  const syncSkills = options.syncSkills ?? syncBundledSkills;
111
167
  const verifySkills = options.verifySkills ?? verifyBundledSkills;
112
168
  const env = options.env ?? process.env;
@@ -192,17 +248,14 @@ export function createUpdateService(options) {
192
248
  return { version: options.currentVersion, updated: false };
193
249
  }
194
250
  const command = source.manager;
195
- const globalDirectory = command === "pnpm" && pnpmLauncherTargets(env, commandName).includes(resolve(binaryPath))
196
- ? pnpmSnapshotDirectory(binaryPath, packageName, commandName) : undefined;
197
- const modulesParent = dirname(dirname(dirname(source.packageRoot)));
198
- // npm puts global modules under <prefix>/lib/node_modules on POSIX and
199
- // <prefix>/node_modules on Windows. Never let today's config redirect a prior one-off install.
200
- const npmPrefix = normalizePath(source.packageRoot).endsWith(`/lib/node_modules/${packageName}`)
201
- ? dirname(modulesParent) : modulesParent;
251
+ const globalDirectory = source.manager === "pnpm" ? source.directory : undefined;
202
252
  const args = source.manager === "npm"
203
- ? ["install", "--global", "--prefix", npmPrefix, `--allow-scripts=${packageName}`, `${packageName}@${latest}`]
204
- : ["add", "--global", ...(globalDirectory ? ["--global-dir", globalDirectory] : []),
205
- `--allow-build=${packageName}`, `${packageName}@${latest}`];
253
+ ? ["install", "--global", "--prefix", source.directory, `--allow-scripts=${packageName}`, `${packageName}@${latest}`]
254
+ : ["add", "--global", "--global-dir", source.directory, `--allow-build=${packageName}`, `${packageName}@${latest}`];
255
+ const installNextSteps = [
256
+ insmind ? `Original installation directory: ${source.directory}` : `原安装目录:${source.directory}`,
257
+ insmind ? "Use the original package manager and directory if a manual retry is needed." : "如需手动重试,请使用原包管理器和该目录。"
258
+ ];
206
259
  await options.telemetry.stage("install", async () => {
207
260
  try {
208
261
  await runProcess(command, args, signal);
@@ -210,12 +263,25 @@ export function createUpdateService(options) {
210
263
  catch (error) {
211
264
  if (isInterruption(error, signal))
212
265
  throw signal.reason;
266
+ if (error instanceof PackageManagerTerminationError) {
267
+ throw new UpdateError("UPDATE_FAILED", insmind
268
+ ? "Unable to confirm that the interrupted package manager stopped; it may still be running."
269
+ : "无法确认已中断的包管理器已停止;安装进程可能仍在运行。", [installNextSteps[0], insmind ? "Check the package manager process and original installation before retrying." : "请先检查包管理器进程及原安装状态,再决定是否重试。"], error);
270
+ }
213
271
  throw new UpdateError("UPDATE_FAILED", insmind
214
272
  ? `Failed to update ${commandName} to ${latest}.`
215
- : `gd-cli 更新到 ${latest} 失败。`, nextSteps, error);
273
+ : `gd-cli 更新到 ${latest} 失败。`, installNextSteps, error);
216
274
  }
217
275
  });
218
276
  signal.throwIfAborted();
277
+ try {
278
+ (options.verifyInstallation ?? verifyInstalledVersion)(source, latest, globalDirectory, env, packageName, commandName);
279
+ }
280
+ catch (error) {
281
+ throw new UpdateError("UPDATE_FAILED", insmind
282
+ ? `The package manager finished, but the ${latest} installation could not be confirmed; the installation may have changed.`
283
+ : `包管理器已结束,但无法确认原安装目录已更新到 ${latest};安装状态可能已改变。`, [installNextSteps[0], insmind ? `Check the original installation and run ${commandName} --version.` : "请检查原安装目录并执行 gd-cli --version。"], error);
284
+ }
219
285
  const targetSkills = options.bundledSkills.map((skill) => ({
220
286
  ...skill,
221
287
  version: latest
@@ -230,8 +296,9 @@ export function createUpdateService(options) {
230
296
  throw verificationError;
231
297
  // A pnpm store cache hit may skip postinstall. Only use new Skill bytes
232
298
  // from the verified replacement launcher in the same global installation.
233
- const target = pnpmLauncherTargets(env, commandName)
234
- .find(entry => pnpmSnapshotDirectory(entry, packageName, commandName) === globalDirectory);
299
+ const target = launcherTarget(source.launcher);
300
+ if (target && pnpmSnapshotDirectory(target, packageName, commandName) !== globalDirectory)
301
+ throw verificationError;
235
302
  if (!target)
236
303
  throw verificationError;
237
304
  const actual = loadBundledSkills(realpathSync(target));
@@ -256,25 +323,24 @@ export function createUpdateService(options) {
256
323
  }
257
324
  };
258
325
  }
259
- function spawnProcess(command, args, signal) {
260
- return new Promise((resolvePromise, reject) => {
261
- const child = spawn(command, args, {
262
- stdio: [0, 2, 2],
263
- shell: false,
264
- signal
265
- });
266
- child.once("error", reject);
267
- child.once("exit", (code, exitSignal) => {
268
- if (code === 0) {
269
- resolvePromise();
270
- }
271
- else {
272
- reject(new Error(code === null
273
- ? `package manager terminated by ${exitSignal ?? "unknown signal"}`
274
- : `package manager exited with ${code}`));
275
- }
276
- });
277
- });
326
+ function verifyInstalledVersion(source, version, globalDirectory, env, packageName, command) {
327
+ let root = source.packageRoot;
328
+ if (source.manager === "pnpm") {
329
+ if (!globalDirectory)
330
+ throw new Error("Cannot verify the original pnpm global directory");
331
+ const target = launcherTarget(source.launcher);
332
+ if (!target || pnpmSnapshotDirectory(target, packageName, command) !== globalDirectory)
333
+ throw new Error("Cannot find the replacement launcher in the original global directory");
334
+ root = dirname(dirname(dirname(realpathSync(target))));
335
+ }
336
+ const entry = launcherTarget(source.launcher);
337
+ const expectedEntry = realpathSync(join(root, "dist", "bin", `${command}.js`));
338
+ if (!entry || realpathSync(entry) !== expectedEntry)
339
+ throw new Error("The original launcher no longer reaches the updated installation");
340
+ const manifest = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
341
+ if (manifest.name !== packageName || manifest.version !== version || readInstallationOwner(root) !== "user") {
342
+ throw new Error("The original installation does not contain the requested package version");
343
+ }
278
344
  }
279
345
  function manualCommands(version, packageName = "@gaoding/cli") {
280
346
  return [
@@ -0,0 +1,9 @@
1
+ import { createRequire } from "node:module";
2
+ const require = createRequire(import.meta.url);
3
+ let windowsSpawn;
4
+ export function startDetached(spawn) {
5
+ if (process.platform !== "win32")
6
+ return spawn();
7
+ windowsSpawn ??= require(`./windows-acl/${process.arch}.node`).withDetachedPipes;
8
+ return windowsSpawn(spawn);
9
+ }
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import * as nodeFileSystem from "node:fs/promises";
3
3
  import { join, resolve } from "node:path";
4
4
  import { setTimeout as delay } from "node:timers/promises";
5
+ export const fileLockDirectory = (lockPath) => `${lockPath}.d`;
5
6
  const localTurns = new Map();
6
7
  const actions = new Set(["task_write", "task_update", "sls_queue", "analytics_device"]);
7
8
  const localOwners = new Map();
@@ -70,7 +71,7 @@ async function acquireFileLock(path, run, options, identity) {
70
71
  const deadline = Math.min(options.deadline ?? Infinity, Date.now() + 2_000);
71
72
  if (Date.now() >= deadline)
72
73
  throw lockTimeout(identity.startedAt, identity.contenderId, "owner_files", [], options.action);
73
- const directory = `${path}.d`;
74
+ const directory = fileLockDirectory(path);
74
75
  await mkdir(directory, { recursive: true, mode: 0o700 });
75
76
  await chmod(directory, 0o700);
76
77
  const name = `${process.pid}-${identity.contenderId}.json`;
@@ -96,7 +97,8 @@ async function acquireFileLock(path, run, options, identity) {
96
97
  }
97
98
  }
98
99
  try {
99
- const text = await readFile(join(directory, entry), "utf8");
100
+ const ownerPath = join(directory, entry);
101
+ const text = options.readOwner ? await options.readOwner(ownerPath) : await readFile(ownerPath, "utf8");
100
102
  let ticket = null;
101
103
  let action;
102
104
  let startedAtMs;
@@ -115,8 +117,14 @@ async function acquireFileLock(path, run, options, identity) {
115
117
  ...(action ? { action } : {}), ...(startedAtMs === undefined ? {} : { startedAtMs }) });
116
118
  }
117
119
  catch (error) {
118
- if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
119
- throw error;
120
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
121
+ continue;
122
+ // Windows can return ACCESS_DENIED when the previous owner unlinks its
123
+ // ticket between readdir and open. A UUID ticket is never reused.
124
+ if (error instanceof Error && "win32Code" in error && error.win32Code === 5
125
+ && !(await readdir(directory)).includes(entry))
126
+ continue;
127
+ throw error;
120
128
  }
121
129
  }
122
130
  return found;
@@ -1,3 +1,4 @@
1
+ import { fileURLToPath, pathToFileURL } from "node:url";
1
2
  /** Structural evidence for an already rejected URI; never include its value. */
2
3
  export function uriIssue(value) {
3
4
  if (/[\u0000-\u001f\u007f-\u009f]/u.test(value))
@@ -50,6 +51,27 @@ export function uriShape(value) {
50
51
  uriWindowsDrive: windowsDrive
51
52
  };
52
53
  }
54
+ // WHATWG file URLs drop an explicit "localhost" authority. On Windows it can
55
+ // identify an SMB share, so preserve it until the native filesystem boundary.
56
+ const localhostAuthority = /^file:\/\/localhost(?=\/)/iu;
57
+ export function fileUriFromLocalPath(path) {
58
+ const url = pathToFileURL(path);
59
+ return process.platform === "win32" && /^\\\\localhost\\/iu.test(path)
60
+ ? "file://localhost" + url.pathname : url.href;
61
+ }
62
+ export function localPathFromFileUri(uri) {
63
+ try {
64
+ return fileURLToPath(uri);
65
+ }
66
+ catch (cause) {
67
+ if (process.platform !== "win32" || !/^file:\/\/localhost\/[^/]/iu.test(uri))
68
+ throw cause;
69
+ // A trailing DNS dot keeps the authority intact for Node's UNC decoding,
70
+ // including its encoded-separator checks. Only the original name reaches fs.
71
+ const unc = fileURLToPath(uri.replace(localhostAuthority, "file://localhost."));
72
+ return "\\\\localhost" + unc.slice("\\\\localhost.".length);
73
+ }
74
+ }
53
75
  /** Canonicalize explicit file URIs, without repairing paths or losing filename spaces. */
54
76
  export function canonicalFileUri(value) {
55
77
  if (!/^file:\//iu.test(value) || /[\\\u0000-\u001f\u007f-\u009f]/u.test(value)
@@ -61,7 +83,7 @@ export function canonicalFileUri(value) {
61
83
  return undefined;
62
84
  // URL accepts malformed escapes, whereas fileURLToPath cannot read them.
63
85
  decodeURIComponent(url.pathname);
64
- return url.href;
86
+ return process.platform === "win32" && localhostAuthority.test(value) ? "file://localhost" + url.pathname : url.href;
65
87
  }
66
88
  catch {
67
89
  return undefined;
@@ -1,6 +1,31 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { closeSync } from "node:fs";
2
3
  import * as nodeFileSystem from "node:fs/promises";
3
- import { join } from "node:path";
4
+ import { dirname, join } from "node:path";
5
+ import { openWindowsState, openWindowsStateReader, retryWindowsStateRename } from "./windows-private-state.js";
6
+ // Windows can report ENOENT when an ancestor is a regular file. Walk only
7
+ // on the missing path, so normal reads incur no additional filesystem calls.
8
+ export async function confirmMissingPath(directory, cause) {
9
+ if (process.platform !== "win32" || !isMissing(cause))
10
+ return;
11
+ let current = directory;
12
+ for (;;) {
13
+ try {
14
+ const stat = await nodeFileSystem.stat(current);
15
+ if (!stat.isDirectory())
16
+ throw Object.assign(new Error("A local state parent is not a directory."), { code: "ENOTDIR", cause });
17
+ return;
18
+ }
19
+ catch (error) {
20
+ if (!isMissing(error))
21
+ throw error;
22
+ const parent = dirname(current);
23
+ if (parent === current)
24
+ throw error;
25
+ current = parent;
26
+ }
27
+ }
28
+ }
4
29
  export class LocalFileError extends Error {
5
30
  file;
6
31
  reason;
@@ -19,6 +44,7 @@ export class LocalFileError extends Error {
19
44
  export function createLocalJsonFile(options) {
20
45
  const fileSystem = options.fileSystem ?? nodeFileSystem;
21
46
  const path = join(options.directory, options.filename);
47
+ const windowsAcl = process.platform === "win32" && options.protectWindowsAcl;
22
48
  return {
23
49
  async readText() {
24
50
  let handle;
@@ -26,17 +52,37 @@ export function createLocalJsonFile(options) {
26
52
  let primaryError;
27
53
  let step = "directory_permissions";
28
54
  try {
29
- await fileSystem.chmod(options.directory, 0o700);
30
- step = "open";
31
- handle = await fileSystem.open(path, "r");
32
- step = "file_permissions";
33
- await handle.chmod(0o600);
55
+ if (windowsAcl) {
56
+ const directoryFd = openWindowsState(options.directory, "directory");
57
+ try {
58
+ step = "file_permissions";
59
+ handle = openWindowsStateReader(path);
60
+ }
61
+ finally {
62
+ closeSync(directoryFd);
63
+ }
64
+ }
65
+ else {
66
+ await fileSystem.chmod(options.directory, 0o700);
67
+ step = "open";
68
+ const opened = await fileSystem.open(path, "r");
69
+ handle = opened;
70
+ step = "file_permissions";
71
+ await opened.chmod(0o600);
72
+ }
34
73
  step = "read";
35
74
  return await handle.readFile("utf8");
36
75
  }
37
76
  catch (cause) {
38
- if (!handle && isMissing(cause))
39
- return null;
77
+ if (!handle && isMissing(cause)) {
78
+ try {
79
+ await confirmMissingPath(options.directory, cause);
80
+ return null;
81
+ }
82
+ catch (error) {
83
+ cause = error;
84
+ }
85
+ }
40
86
  failed = true;
41
87
  primaryError = cause;
42
88
  throw new LocalFileError(cause, options.filename, "io", { operation: "read", step, ...(options.role ? { role: options.role } : {}) });
@@ -54,14 +100,24 @@ export function createLocalJsonFile(options) {
54
100
  },
55
101
  async writeTextAtomically(value) {
56
102
  const temporaryPath = join(options.directory, `${options.filename}.tmp-${randomUUID()}`);
103
+ let directoryFd;
57
104
  let handle;
105
+ let createdTemporary = false;
58
106
  let step = "directory_create";
59
107
  try {
60
- await fileSystem.mkdir(options.directory, { mode: 0o700, recursive: true });
61
- step = "directory_permissions";
62
- await fileSystem.chmod(options.directory, 0o700);
108
+ if (windowsAcl) {
109
+ await fileSystem.mkdir(dirname(options.directory), { recursive: true });
110
+ step = "directory_permissions";
111
+ directoryFd = openWindowsState(options.directory, "create");
112
+ }
113
+ else {
114
+ await fileSystem.mkdir(options.directory, { mode: 0o700, recursive: true });
115
+ step = "directory_permissions";
116
+ await fileSystem.chmod(options.directory, 0o700);
117
+ }
63
118
  step = "open";
64
119
  handle = await fileSystem.open(temporaryPath, "wx", 0o600);
120
+ createdTemporary = true;
65
121
  step = "file_permissions";
66
122
  await handle.chmod(0o600);
67
123
  step = "write";
@@ -72,21 +128,47 @@ export function createLocalJsonFile(options) {
72
128
  await handle.close();
73
129
  handle = undefined;
74
130
  step = "rename";
75
- await fileSystem.rename(temporaryPath, path);
131
+ const rename = () => fileSystem.rename(temporaryPath, path);
132
+ if (windowsAcl)
133
+ await retryWindowsStateRename(rename);
134
+ else
135
+ await rename();
76
136
  }
77
137
  catch (cause) {
78
138
  await handle?.close().catch(() => undefined);
79
- await fileSystem.unlink(temporaryPath).catch(() => undefined);
139
+ if (createdTemporary)
140
+ await fileSystem.unlink(temporaryPath).catch(() => undefined);
80
141
  throw new LocalFileError(cause, options.filename, "io", { operation: "write", step, ...(options.role ? { role: options.role } : {}) });
81
142
  }
143
+ finally {
144
+ if (directoryFd !== undefined)
145
+ closeSync(directoryFd);
146
+ }
82
147
  },
83
148
  async remove() {
149
+ let directoryFd;
150
+ let step = "directory_permissions";
84
151
  try {
152
+ if (windowsAcl)
153
+ directoryFd = openWindowsState(options.directory, "directory");
154
+ step = "unlink";
85
155
  await fileSystem.unlink(path);
86
156
  }
87
157
  catch (cause) {
88
- if (!isMissing(cause))
89
- throw new LocalFileError(cause, options.filename, "io", { operation: "remove", step: "unlink", ...(options.role ? { role: options.role } : {}) });
158
+ if (isMissing(cause)) {
159
+ try {
160
+ await confirmMissingPath(options.directory, cause);
161
+ return;
162
+ }
163
+ catch (error) {
164
+ cause = error;
165
+ }
166
+ }
167
+ throw new LocalFileError(cause, options.filename, "io", { operation: "remove", step, ...(options.role ? { role: options.role } : {}) });
168
+ }
169
+ finally {
170
+ if (directoryFd !== undefined)
171
+ closeSync(directoryFd);
90
172
  }
91
173
  }
92
174
  };
@@ -1,5 +1,8 @@
1
- import open from "open";
2
- export function createBrowserOpener(openUrl = open) {
1
+ async function launchBrowser(url) {
2
+ const { default: open } = await import("open");
3
+ return open(url);
4
+ }
5
+ export function createBrowserOpener(openUrl = launchBrowser) {
3
6
  return {
4
7
  async open(url) {
5
8
  await openUrl(url.href);
@@ -4,8 +4,7 @@ import { hasWebmDocType } from "./webm-header.js";
4
4
  import { isInterruption } from "./interruption.js";
5
5
  import { open, realpath, stat } from "node:fs/promises";
6
6
  import { basename, extname, sep } from "node:path";
7
- import { fileURLToPath } from "node:url";
8
- import { canonicalFileUri, uriShape } from "./input-uri.js";
7
+ import { canonicalFileUri, localPathFromFileUri, uriShape } from "./input-uri.js";
9
8
  export class LocalFileInputError extends Error {
10
9
  reason;
11
10
  diagnosticSummary;
@@ -117,7 +116,7 @@ export async function inspectUploadFile(input) {
117
116
  const url = canonicalFileUri(input.url);
118
117
  if (url === undefined)
119
118
  throw new TypeError("Invalid local file URI.");
120
- requestedPath = fileURLToPath(url);
119
+ requestedPath = localPathFromFileUri(url);
121
120
  }
122
121
  catch (cause) {
123
122
  throw new LocalFileInputError(cause, "invalid_file_uri");
@@ -0,0 +1,16 @@
1
+ import { createRequire } from "node:module";
2
+ const require = createRequire(import.meta.url);
3
+ // The command graph is shared. A probe that does not validate a document
4
+ // should not pay for loading Ajv, its formats and their dependencies.
5
+ export function lazySchemaCompiler(options) {
6
+ let compiler;
7
+ return () => {
8
+ if (!compiler) {
9
+ const { Ajv2020 } = require("ajv/dist/2020.js");
10
+ const engine = new Ajv2020(options);
11
+ require("ajv-formats")(engine);
12
+ compiler = engine;
13
+ }
14
+ return compiler;
15
+ };
16
+ }
@@ -0,0 +1,43 @@
1
+ With exception of certain parts that are prominently marked as being
2
+ in the Public Domain, BSD, or LGPL this Software is provided under the
3
+ Zope Public License (ZPL) Version 2.1.
4
+
5
+ Copyright (c) 2009 - 2013 by the mingw-w64 project
6
+
7
+ See the AUTHORS file for the list of contributors to the mingw-w64 project.
8
+
9
+ This license has been certified as open source. It has also been designated
10
+ as GPL compatible by the Free Software Foundation (FSF).
11
+
12
+ Redistribution and use in source and binary forms, with or without
13
+ modification, are permitted provided that the following conditions are met:
14
+
15
+ 1. Redistributions in source code must retain the accompanying copyright
16
+ notice, this list of conditions, and the following disclaimer.
17
+ 2. Redistributions in binary form must reproduce the accompanying
18
+ copyright notice, this list of conditions, and the following disclaimer
19
+ in the documentation and/or other materials provided with the
20
+ distribution.
21
+ 3. Names of the copyright holders must not be used to endorse or promote
22
+ products derived from this software without prior written permission
23
+ from the copyright holders.
24
+ 4. The right to distribute this software or to use it for any purpose does
25
+ not give you the right to use Servicemarks (sm) or Trademarks (tm) of
26
+ the copyright holders. Use of them is covered by separate agreement
27
+ with the copyright holders.
28
+ 5. If any files are modified, you must cause the modified files to carry
29
+ prominent notices stating that you changed the files and the date of
30
+ any change.
31
+
32
+ Disclaimer
33
+
34
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED
35
+ OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
36
+ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
37
+ EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT,
38
+ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
39
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
40
+ OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
41
+ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
42
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
43
+ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.