@wirecat/cli-core 0.709.0 → 0.711.0

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.
@@ -0,0 +1,241 @@
1
+ import { timingSafeEqual } from "node:crypto";
2
+ import { CliError, isCliError } from "@wirecat/cli-base";
3
+ /** WebDAV class 1 only: without class 2 (LOCK) a client has nothing to lock a file it would write with. */
4
+ const ALLOW = "OPTIONS, PROPFIND, GET, HEAD";
5
+ const MOST_CACHED = 2000;
6
+ class BadPath extends Error {
7
+ }
8
+ const sameSecret = (given, secret) => {
9
+ const a = Buffer.from(given);
10
+ const b = Buffer.from(secret);
11
+ return a.length === b.length && timingSafeEqual(a, b);
12
+ };
13
+ /**
14
+ * The path under the mount, decoded one segment at a time. A segment that decodes to a separator or a dot step is
15
+ * refused: `a%2F..%2F..` survives URL parsing and would climb out of the mounted folder once the service joins it.
16
+ */
17
+ const innerPath = (segments) => {
18
+ const names = segments
19
+ .filter((segment) => segment !== "")
20
+ .map((segment) => {
21
+ let name;
22
+ try {
23
+ name = decodeURIComponent(segment);
24
+ }
25
+ catch {
26
+ throw new BadPath();
27
+ }
28
+ if (name === "." || name === ".." || /[/\\\0]/u.test(name))
29
+ throw new BadPath();
30
+ return name;
31
+ });
32
+ return `/${names.join("/")}`;
33
+ };
34
+ const parentOf = (path) => path.slice(0, path.lastIndexOf("/")) || "/";
35
+ const baseOf = (path) => path.slice(path.lastIndexOf("/") + 1);
36
+ const childOf = (path, name) => (path === "/" ? `/${name}` : `${path}/${name}`);
37
+ const xml = (text) => text.replace(/[<>&"']/gu, (c) => ({ "<": "&lt;", ">": "&gt;", "&": "&amp;", '"': "&quot;", "'": "&apos;" })[c] ?? c);
38
+ const etagOf = (entry) => {
39
+ const tag = entry.version ?? (entry.modifiedAt ? `${entry.modifiedAt}-${entry.size ?? 0}` : undefined);
40
+ return tag === undefined ? undefined : `"${tag.replace(/["\\]/gu, "")}"`;
41
+ };
42
+ const httpDate = (iso) => {
43
+ const ms = iso === undefined ? Number.NaN : Date.parse(iso);
44
+ return Number.isNaN(ms) ? undefined : new Date(ms).toUTCString();
45
+ };
46
+ const hrefOf = (secret, path, folder) => {
47
+ const encoded = path === "/" ? "" : path.split("/").map(encodeURIComponent).join("/");
48
+ return `/${secret}${encoded}${folder ? "/" : ""}`;
49
+ };
50
+ const responseXml = (href, entry) => {
51
+ const props = [
52
+ `<D:displayname>${xml(entry.name)}</D:displayname>`,
53
+ entry.folder ? "<D:resourcetype><D:collection/></D:resourcetype>" : "<D:resourcetype/>",
54
+ ...(entry.folder || entry.size === undefined ? [] : [`<D:getcontentlength>${entry.size}</D:getcontentlength>`]),
55
+ ...(entry.folder ? [] : [`<D:getcontenttype>${xml(entry.mime ?? "application/octet-stream")}</D:getcontenttype>`]),
56
+ ...[httpDate(entry.modifiedAt)].filter(Boolean).map((date) => `<D:getlastmodified>${date}</D:getlastmodified>`),
57
+ ...(entry.createdAt ? [`<D:creationdate>${xml(entry.createdAt)}</D:creationdate>`] : []),
58
+ ...[etagOf(entry)].filter(Boolean).map((tag) => `<D:getetag>${xml(tag ?? "")}</D:getetag>`),
59
+ // Windows reads this flag and opens the file read-only, so an editor says so before a save fails.
60
+ `<Z:Win32FileAttributes>${entry.folder ? "00000011" : "00000001"}</Z:Win32FileAttributes>`,
61
+ ];
62
+ return (`<D:response><D:href>${xml(href)}</D:href><D:propstat><D:prop>${props.join("")}</D:prop>` +
63
+ "<D:status>HTTP/1.1 200 OK</D:status></D:propstat></D:response>");
64
+ };
65
+ const multistatus = (responses) => new Response(`<?xml version="1.0" encoding="utf-8"?>\n<D:multistatus xmlns:D="DAV:" xmlns:Z="urn:schemas-microsoft-com:">${responses.join("")}</D:multistatus>`, {
66
+ status: 207,
67
+ headers: { "content-type": "application/xml; charset=utf-8" },
68
+ });
69
+ const plain = (status, text, headers = {}) => new Response(text, {
70
+ status,
71
+ headers: { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff", ...headers },
72
+ });
73
+ /** One `bytes=` range; anything else (several ranges, another unit) is ignored and the whole file is sent. */
74
+ const rangeOf = (header, size) => {
75
+ if (header === null || size === undefined)
76
+ return undefined;
77
+ const match = /^bytes=(\d*)-(\d*)$/u.exec(header.trim());
78
+ if (!match)
79
+ return undefined;
80
+ const [, from = "", to = ""] = match;
81
+ if (from === "" && to === "")
82
+ return undefined;
83
+ if (from === "") {
84
+ const suffix = Number(to);
85
+ if (suffix === 0)
86
+ return "unsatisfiable";
87
+ return { start: Math.max(0, size - suffix), end: size - 1 };
88
+ }
89
+ const start = Number(from);
90
+ if (start >= size)
91
+ return "unsatisfiable";
92
+ const end = to === "" ? size - 1 : Math.min(Number(to), size - 1);
93
+ return end < start ? undefined : { start, end };
94
+ };
95
+ /**
96
+ * Listings and stats answer from memory for `ms`, and a stat is answered from its parent's listing when that is
97
+ * fresh: a file manager asks for `.DS_Store`, `desktop.ini` and thumbnails in every folder, and each would otherwise be
98
+ * a request that counts against the service's rate limit.
99
+ */
100
+ const cachedSource = (source, ms, now) => {
101
+ const lists = new Map();
102
+ const stats = new Map();
103
+ const fresh = (map, key) => {
104
+ const hit = map.get(key);
105
+ if (hit && now() - hit.at < ms)
106
+ return hit.value;
107
+ map.delete(key);
108
+ return undefined;
109
+ };
110
+ const keep = (map, key, value) => {
111
+ if (map.size >= MOST_CACHED)
112
+ map.delete(map.keys().next().value);
113
+ map.set(key, { at: now(), value });
114
+ value.catch(() => map.delete(key));
115
+ return value;
116
+ };
117
+ const list = (path) => fresh(lists, path) ??
118
+ keep(lists, path, source.list(path).then((entries) => {
119
+ for (const entry of entries)
120
+ keep(stats, childOf(path, entry.name), Promise.resolve(entry));
121
+ return entries;
122
+ }));
123
+ const stat = async (path) => {
124
+ const hit = fresh(stats, path);
125
+ if (hit)
126
+ return hit;
127
+ const siblings = path === "/" ? undefined : fresh(lists, parentOf(path));
128
+ if (siblings) {
129
+ const found = (await siblings).find((entry) => entry.name === baseOf(path));
130
+ if (found)
131
+ return found;
132
+ throw notFound();
133
+ }
134
+ return keep(stats, path, source.stat(path));
135
+ };
136
+ return { list, stat };
137
+ };
138
+ const notFound = () => new CliError("not_found", "no such item");
139
+ const isNotFound = (error) => isCliError(error) && error.code === "not_found";
140
+ const failure = (error, onError) => {
141
+ if (isNotFound(error))
142
+ return plain(404, "not found");
143
+ onError?.(error);
144
+ if (isCliError(error) && error.code === "rate_limited") {
145
+ const wait = Number(error.details?.retry_after_ms ?? 60_000);
146
+ return plain(503, "the service asked to slow down", { "retry-after": String(Math.ceil(wait / 1000)) });
147
+ }
148
+ return plain(502, "the service did not answer");
149
+ };
150
+ /**
151
+ * A read-only WebDAV server over a `MountSource`, as a web-standard handler. Every request must name an allowed
152
+ * `Host` (a page on another site that rebinds its name to 127.0.0.1 cannot), carry no foreign `Origin`, and start
153
+ * with the secret; it may only read. Answers carry no CORS header, so no page can read them.
154
+ */
155
+ export const webdavHandler = (source, options) => {
156
+ const { secret, onError } = options;
157
+ const cache = cachedSource(source, options.cacheMs ?? 10_000, options.now ?? Date.now);
158
+ const propfind = async (request, path) => {
159
+ const depth = request.headers.get("depth")?.trim().toLowerCase() ?? "1";
160
+ if (depth !== "0" && depth !== "1")
161
+ return new Response('<?xml version="1.0" encoding="utf-8"?>\n<D:error xmlns:D="DAV:"><D:propfind-finite-depth/></D:error>', { status: 403, headers: { "content-type": "application/xml; charset=utf-8" } });
162
+ const entry = await cache.stat(path);
163
+ const own = responseXml(hrefOf(secret, path, entry.folder), entry);
164
+ if (depth === "0" || !entry.folder)
165
+ return multistatus([own]);
166
+ const children = await cache.list(path);
167
+ return multistatus([
168
+ own,
169
+ ...children.map((child) => responseXml(hrefOf(secret, childOf(path, child.name), child.folder), child)),
170
+ ]);
171
+ };
172
+ const get = async (request, path) => {
173
+ const entry = await cache.stat(path);
174
+ if (entry.folder) {
175
+ const names = (await cache.list(path)).map((child) => `${child.name}${child.folder ? "/" : ""}`);
176
+ return plain(200, request.method === "HEAD" ? "" : `${names.join("\n")}\n`);
177
+ }
178
+ const etag = etagOf(entry);
179
+ const lastModified = httpDate(entry.modifiedAt);
180
+ const headers = {
181
+ "content-type": entry.mime ?? "application/octet-stream",
182
+ // A file is anyone's content: an HTML or SVG file opened from the mount would run on its origin, read the secret
183
+ // from its own address and fetch the rest of the folder.
184
+ "content-security-policy": "sandbox",
185
+ "x-content-type-options": "nosniff",
186
+ "accept-ranges": "bytes",
187
+ ...(etag ? { etag } : {}),
188
+ ...(lastModified ? { "last-modified": lastModified } : {}),
189
+ };
190
+ const ifRange = request.headers.get("if-range");
191
+ const asked = ifRange !== null && ifRange !== etag && ifRange !== lastModified ? null : request.headers.get("range");
192
+ const range = rangeOf(asked, entry.size);
193
+ if (range === "unsatisfiable")
194
+ return new Response(null, { status: 416, headers: { ...headers, "content-range": `bytes */${entry.size}` } });
195
+ const whole = entry.size === undefined ? {} : { "content-length": String(entry.size) };
196
+ if (request.method === "HEAD")
197
+ return new Response(null, { status: 200, headers: { ...headers, ...whole } });
198
+ const read = await source.read(path, entry, range);
199
+ if (!range || !read.ranged)
200
+ return new Response(read.body, { status: 200, headers: { ...headers, ...whole } });
201
+ return new Response(read.body, {
202
+ status: 206,
203
+ headers: {
204
+ ...headers,
205
+ "content-length": String(range.end - range.start + 1),
206
+ "content-range": `bytes ${range.start}-${range.end}/${entry.size}`,
207
+ },
208
+ });
209
+ };
210
+ return async (request) => {
211
+ if (!options.hosts().includes(request.headers.get("host") ?? ""))
212
+ return plain(403, "this host is not served");
213
+ const origin = request.headers.get("origin");
214
+ if (origin !== null && !options.hosts().some((host) => origin === `http://${host}`))
215
+ return plain(403, "this origin is not served");
216
+ const segments = new URL(request.url).pathname.split("/").slice(1);
217
+ if (request.method === "OPTIONS")
218
+ return new Response(null, { status: 200, headers: { dav: "1", allow: ALLOW, "ms-author-via": "DAV" } });
219
+ // Windows asks about the server's top before the folder it mounts; an empty folder answers it and shows nothing.
220
+ if (request.method === "PROPFIND" && segments.every((segment) => segment === ""))
221
+ return multistatus([responseXml("/", { name: "", folder: true })]);
222
+ if (!sameSecret(segments[0] ?? "", secret))
223
+ return plain(404, "not found");
224
+ if (!["PROPFIND", "GET", "HEAD"].includes(request.method))
225
+ // A 405 to MKCOL means "it already exists" (RFC 4918, 9.3.1); 403 says creating is refused.
226
+ return plain(request.method === "MKCOL" ? 403 : 405, "this mount is read-only", { allow: ALLOW });
227
+ let path;
228
+ try {
229
+ path = innerPath(segments.slice(1));
230
+ }
231
+ catch {
232
+ return plain(400, "this path is refused");
233
+ }
234
+ try {
235
+ return await (request.method === "PROPFIND" ? propfind(request, path) : get(request, path));
236
+ }
237
+ catch (error) {
238
+ return failure(error, onError);
239
+ }
240
+ };
241
+ };
@@ -99,4 +99,11 @@ export const WIRECAT_TOOLS = [
99
99
  package: "@wirecat/wordpress-cli",
100
100
  does: "WordPress posts and pages, searchable with your other WireCat data",
101
101
  },
102
+ {
103
+ command: "linear",
104
+ appName: "linear-cli",
105
+ envPrefix: "WCLINEAR",
106
+ package: "@wirecat/linear-cli",
107
+ does: "Linear issues and projects, searchable with your other WireCat data",
108
+ },
102
109
  ];
@@ -6,6 +6,8 @@ export interface Mirror {
6
6
  id: string;
7
7
  path: string;
8
8
  folder: string;
9
+ /** Globs of paths the mirror leaves alone on both sides, as `excludedBy` reads them. */
10
+ exclude?: string[];
9
11
  }
10
12
  export declare const mirrorId: (root: string, folder: string) => string;
11
13
  /**
@@ -114,7 +114,7 @@ export declare const scanLocal: (root: string, kindOf: (path: string) => string
114
114
  size: number;
115
115
  mtimeMs: number;
116
116
  hash: string;
117
- } | undefined) => Promise<{
117
+ } | undefined, skip?: (path: string) => boolean) => Promise<{
118
118
  files: LocalDocument[];
119
119
  unsupported: number;
120
120
  links: string[];
@@ -133,7 +133,7 @@ export const replaceLocal = async (absolute, hash, content, { tag = randomUUID()
133
133
  * links' paths are returned in `links`, so a mirror does not take the files behind one as deleted. A file whose size
134
134
  * and mtime match what `known` returns keeps that hash instead of being read again.
135
135
  */
136
- export const scanLocal = async (root, kindOf, maxFiles = 10_000, known) => {
136
+ export const scanLocal = async (root, kindOf, maxFiles = 10_000, known, skip) => {
137
137
  const files = [];
138
138
  const links = [];
139
139
  let unsupported = 0;
@@ -143,6 +143,8 @@ export const scanLocal = async (root, kindOf, maxFiles = 10_000, known) => {
143
143
  if (SKIPPED.test(entry.name))
144
144
  continue;
145
145
  const path = relative ? posix.join(relative, entry.name) : entry.name;
146
+ if (skip?.(path))
147
+ continue;
146
148
  if (entry.isSymbolicLink()) {
147
149
  links.push(path);
148
150
  continue;
@@ -0,0 +1,8 @@
1
+ /** An exclusion as the mirror keeps it: trimmed, without a trailing `/`; refused when it names nothing or leaves. */
2
+ export declare const exclusionPattern: (input: string) => string;
3
+ /**
4
+ * Whether a mirror's exclusions cover `path`, or a folder on the way to it. A pattern without `/` is a name at any
5
+ * depth (`node_modules`, `*.iso`); one with `/` is a path from the mirror's root (`Photos/2019`, `/Camera`). `*` and `?`
6
+ * stay within a name; `**` crosses folders.
7
+ */
8
+ export declare const excludedBy: (patterns?: readonly string[]) => (path: string) => boolean;
@@ -0,0 +1,39 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ /** An exclusion as the mirror keeps it: trimmed, without a trailing `/`; refused when it names nothing or leaves. */
3
+ export const exclusionPattern = (input) => {
4
+ const pattern = input.trim().replace(/\/+$/u, "");
5
+ const parts = pattern.replace(/^\//u, "").split("/");
6
+ if (!pattern || pattern === "/" || parts.some((part) => !part || part === "." || part === ".."))
7
+ throw new CliError("validation_error", `${JSON.stringify(input)} is not a path pattern like Photos or /Work/*.iso`, {
8
+ reason: "mirror.bad-exclusion",
9
+ });
10
+ return pattern;
11
+ };
12
+ const globSource = (glob) => glob
13
+ .split(/(\*\*\/|\*\*|\*|\?)/u)
14
+ .map((part) => part === "**/"
15
+ ? "(?:.*/)?"
16
+ : part === "**"
17
+ ? ".*"
18
+ : part === "*"
19
+ ? "[^/]*"
20
+ : part === "?"
21
+ ? "[^/]"
22
+ : part.replace(/[.+^${}()|[\]\\]/gu, "\\$&"))
23
+ .join("");
24
+ /**
25
+ * Whether a mirror's exclusions cover `path`, or a folder on the way to it. A pattern without `/` is a name at any
26
+ * depth (`node_modules`, `*.iso`); one with `/` is a path from the mirror's root (`Photos/2019`, `/Camera`). `*` and `?`
27
+ * stay within a name; `**` crosses folders.
28
+ */
29
+ export const excludedBy = (patterns = []) => {
30
+ const test = (glob) => new RegExp(`^${globSource(glob)}$`, "u");
31
+ const names = patterns.filter((pattern) => !pattern.includes("/")).map(test);
32
+ const paths = patterns.filter((pattern) => pattern.includes("/")).map((pattern) => test(pattern.replace(/^\//u, "")));
33
+ return (path) => {
34
+ if (!names.length && !paths.length)
35
+ return false;
36
+ const parts = path.split("/");
37
+ return parts.some((name, index) => names.some((glob) => glob.test(name)) || paths.some((way) => way.test(parts.slice(0, index + 1).join("/"))));
38
+ };
39
+ };
@@ -21,8 +21,14 @@ export interface FileMirrorOptions {
21
21
  /** Settles conflicts; without it they are reported and left. */
22
22
  keep?: Keep;
23
23
  dryRun?: boolean;
24
- /** Lets a run delete this many files although the deletion guard would stop it. */
24
+ /** Lets a run delete this many files although the guard would stop it. */
25
25
  allowDeletions?: number;
26
+ /** Lets a run replace this many existing files, on either side, although the guard would stop it. */
27
+ allowReplacements?: number;
28
+ /** Globs of paths the mirror leaves alone on both sides, as `excludedBy` reads them. */
29
+ exclude?: string[];
30
+ /** The mirror's id, put for `<id>` in the hints. */
31
+ id?: string;
26
32
  /**
27
33
  * The owner confirmed that a root reported as replaced is the right folder now: its identity is recorded again and
28
34
  * the run is a first sync (identical files adopted, different ones conflicts), deleting nothing.
@@ -30,7 +36,7 @@ export interface FileMirrorOptions {
30
36
  repin?: boolean;
31
37
  /** How the app names the remote side; it ends a conflict copy's name. */
32
38
  remote: string;
33
- /** How the app's commands are named in the deletion guard's and the repin message; the defaults are flags. */
39
+ /** How the app's commands are named in the guard's, the free space and the repin message. */
34
40
  hints?: Partial<MirrorHints>;
35
41
  /** Runs one write behind the app's permission checks; `side` says which side it changes. */
36
42
  guard<T>(attempt: {
@@ -44,16 +50,29 @@ export interface FileMirrorOptions {
44
50
  /** Throws once the sync lock is lost; checked before every write. */
45
51
  assertHeld(): void | Promise<void>;
46
52
  signal?: AbortSignal;
53
+ /** Local files the mirror takes at most; more fail the run. */
47
54
  maxFiles?: number;
55
+ /** Bytes free for this process on the file system holding `path`, and its device. */
56
+ space?(path: string): Promise<{
57
+ free: number;
58
+ dev: number;
59
+ }>;
48
60
  now?(): number;
49
61
  }
62
+ /** The app's commands, as the engine's messages name them; `<id>` is the mirror's id and `<count>` a number. */
50
63
  export interface MirrorHints {
51
- /** How to preview a run: `--dry-run`. */
64
+ /** How to preview a run: `ydisk work mirrors preview <id>`. */
52
65
  preview: string;
53
- /** How to record a replaced root again: `--repin`. */
66
+ /** How to record a replaced root again: `ydisk work mirrors sync <id> --repin`. */
54
67
  repin: string;
55
- /** How to allow a run's deletions: `explicitly`, as in "allow them explicitly". */
68
+ /** The sync an approval is added to: `ydisk work mirrors sync <id>`. */
69
+ sync: string;
70
+ /** How a sync allows deletions: `--allow-deletions <count>`. */
56
71
  allowDeletions: string;
72
+ /** How a sync allows replacements: `--allow-replacements <count>`. */
73
+ allowReplacements: string;
74
+ /** How to exclude a folder: `ydisk work mirrors exclude <id> <glob>`. */
75
+ exclude: string;
57
76
  }
58
77
  export interface FileStep {
59
78
  kind: FileStepKind;
@@ -75,10 +94,12 @@ export interface FileMirrorResult {
75
94
  adopted: string[];
76
95
  unchanged: number;
77
96
  conflicts: PushConflict[];
97
+ /** A whole-run refusal (the guard, too little space) is one error at path `.` with its `reason`. */
78
98
  errors: {
79
99
  path: string;
80
100
  code: string;
81
101
  message: string;
102
+ reason?: string;
82
103
  }[];
83
104
  /**
84
105
  * Files of the last sync missing from a side that cannot prove a deletion: its listing was incomplete, or its root
@@ -91,10 +112,25 @@ export interface FileMirrorResult {
91
112
  }[];
92
113
  /** Every step but the unchanged files, on a dry run. */
93
114
  plan?: FileStep[];
94
- /** On a dry run, the deletions that would stop the real run without `allowDeletions`. */
115
+ /** The deletions that stop the run without `allowDeletions`; a dry run reports them without stopping. */
95
116
  tooManyDeletions?: number;
117
+ /** The replacements of existing files that stop the run without `allowReplacements`. */
118
+ tooManyReplacements?: number;
119
+ /** The run needs more free space than the file system at `path` has. */
120
+ noSpace?: {
121
+ path: string;
122
+ needed: number;
123
+ free: number;
124
+ };
96
125
  stopped?: true;
97
126
  }
127
+ /**
128
+ * A run that would delete more than `MAX_DELETIONS` files, or replace more than `MAX_REPLACEMENTS` existing files on
129
+ * either side, stops before writing until the owner allows the count. Replacements get the higher bar: every content
130
+ * one replaces is kept in the version store first, and bulk edits (a find-and-replace, a branch switch) are common.
131
+ */
132
+ export declare const MAX_DELETIONS = 10;
133
+ export declare const MAX_REPLACEMENTS = 50;
98
134
  /**
99
135
  * Syncs a local folder and a remote folder of plain files both ways, whole files at a time. Each path is compared
100
136
  * three ways (local now, remote now, last sync): a change on one side is copied to the other, the same content on
@@ -120,7 +156,7 @@ export declare const fileMirrorStatus: (mirrors: Mirror[], stateOf: (mirror: Mir
120
156
  * at the first poll), none when it did not, and every mirror at each poll when the target has no revision.
121
157
  */
122
158
  export declare const fileRemoteChanges: (target: FileTarget) => (signal: AbortSignal) => Promise<string[] | "all">;
123
- export interface FileMirrorSyncOptions extends Pick<FileMirrorOptions, "target" | "principal" | "keep" | "dryRun" | "allowDeletions" | "repin" | "hints" | "guard" | "operationId" | "errorOf" | "signal"> {
159
+ export interface FileMirrorSyncOptions extends Pick<FileMirrorOptions, "target" | "principal" | "keep" | "dryRun" | "allowDeletions" | "allowReplacements" | "repin" | "hints" | "guard" | "operationId" | "errorOf" | "signal" | "space"> {
124
160
  mirrors: Mirror[];
125
161
  stateOf(mirror: Mirror): FileMirrorStatePort;
126
162
  versionsOf(mirror: Mirror): FileVersions;