@wirecat/cli-core 0.702.0 → 0.704.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.
Files changed (36) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/messenger/conversation-answers.d.ts +1 -1
  4. package/dist/cli/messenger/conversation-answers.js +4 -1
  5. package/dist/cli/messenger/conversations-command.js +2 -1
  6. package/dist/crm/cli/index.js +8 -5
  7. package/dist/crm/manifest/source.js +2 -2
  8. package/dist/crm/testing/manifest-fake.js +18 -0
  9. package/dist/documents/file-mirror-model.d.ts +88 -0
  10. package/dist/documents/file-mirror-model.js +1 -0
  11. package/dist/documents/index.d.ts +5 -2
  12. package/dist/documents/index.js +2 -0
  13. package/dist/documents/push-model.d.ts +3 -0
  14. package/dist/embeddings/onnx-runtime.d.ts +1 -1
  15. package/dist/embeddings/onnx-runtime.js +42 -61
  16. package/dist/errors/reasons.js +8 -0
  17. package/dist/ports/wirecat-tools.js +7 -0
  18. package/dist/sends/upload.js +0 -1
  19. package/dist/services/documents/mirror-watch.d.ts +12 -4
  20. package/dist/services/documents/mirror-watch.js +2 -0
  21. package/dist/services/documents/mirrors.d.ts +55 -35
  22. package/dist/services/documents/mirrors.js +63 -66
  23. package/dist/services/documents/push.d.ts +56 -4
  24. package/dist/services/documents/push.js +131 -24
  25. package/dist/services/embeddings-search.js +35 -10
  26. package/dist/services/embeddings.d.ts +2 -0
  27. package/dist/services/files/mirror.d.ts +145 -0
  28. package/dist/services/files/mirror.js +603 -0
  29. package/dist/services/files/versions.d.ts +50 -0
  30. package/dist/services/files/versions.js +142 -0
  31. package/dist/services/metadata.d.ts +1 -1
  32. package/dist/store/sqlite/vectors.d.ts +1 -0
  33. package/dist/store/sqlite/vectors.js +25 -2
  34. package/dist/store/vectors.d.ts +2 -0
  35. package/dist/store/vectors.js +4 -2
  36. package/package.json +1 -1
@@ -1,3 +1,4 @@
1
+ import * as v from "valibot";
1
2
  import type { DocumentTarget, Keep, PushStatePort } from "../../documents/push-model.js";
2
3
  import { type PushConflict, type PushOptions } from "./push.js";
3
4
  /** A local folder mirrored into a remote folder, as the app's profile config keeps it. */
@@ -8,9 +9,14 @@ export interface Mirror {
8
9
  }
9
10
  export declare const mirrorId: (root: string, folder: string) => string;
10
11
  /**
11
- * A mirror's sync state in `<dir>/<id>.json`. A missing file is a first sync; an unreadable or invalid one is
12
- * refused rather than reset, since a reset would push every file again as new.
12
+ * A state file read against `schema`, saved 0600 in a 0700 folder. A missing file is `initial`, a first sync; an
13
+ * unreadable or invalid one is refused rather than reset, since a reset would treat every file as new.
13
14
  */
15
+ export declare const jsonState: <T>(path: string, schema: v.GenericSchema, initial: () => T) => {
16
+ read: () => T;
17
+ save: (state: T) => void;
18
+ };
19
+ /** A mirror's push state in `<dir>/<id>.json`. */
14
20
  export declare const fileMirrorState: <S>(dir: string, mirror: Mirror, principal: string, kinds: [string, ...string[]]) => PushStatePort<S>;
15
21
  /** What the next sync of each mirror would create or send, from local files and the state alone. */
16
22
  export declare const mirrorStatus: <S>(mirrors: Mirror[], kindOf: (path: string) => string | undefined, stateOf: (mirror: Mirror) => PushStatePort<S>) => Promise<{
@@ -27,7 +33,7 @@ export declare const mirrorStatus: <S>(mirrors: Mirror[], kindOf: (path: string)
27
33
  /** A conflict as the user reads it, with the remote side named the way the app names it (`google`). */
28
34
  export declare const conflictReport: (conflict: PushConflict, remote: string) => {
29
35
  path: string;
30
- url: string;
36
+ url?: string | undefined;
31
37
  reason: string;
32
38
  parts?: {
33
39
  [x: string]: string;
@@ -35,52 +41,64 @@ export declare const conflictReport: (conflict: PushConflict, remote: string) =>
35
41
  local: string;
36
42
  }[] | undefined;
37
43
  local_changed_at?: string | undefined;
44
+ local_size?: number | undefined;
38
45
  };
46
+ interface MirrorLock {
47
+ assertHeld(): void;
48
+ release(): Promise<void> | void;
49
+ }
50
+ /**
51
+ * Runs `sync` for each mirror under one lock. A mirror with conflicts, missing remote files or errors does not stop
52
+ * the others; it gets one `mirror.partial` issue, so the caller can answer `complete: false` and fail after printing.
53
+ */
54
+ export declare const eachMirror: <R extends {
55
+ conflicts: PushConflict[];
56
+ errors: unknown[];
57
+ missing?: unknown[];
58
+ unknown?: unknown[];
59
+ }>(mirrors: Mirror[], lock: () => Promise<MirrorLock>, remote: string, sync: (mirror: Mirror, assertHeld: () => void) => Promise<R>) => Promise<{
60
+ items: (Omit<{
61
+ id: string;
62
+ path: string;
63
+ } & R, "conflicts"> & {
64
+ conflicts: {
65
+ path: string;
66
+ url?: string | undefined;
67
+ reason: string;
68
+ parts?: {
69
+ [x: string]: string;
70
+ last_sync: string;
71
+ local: string;
72
+ }[] | undefined;
73
+ local_changed_at?: string | undefined;
74
+ local_size?: number | undefined;
75
+ }[];
76
+ })[];
77
+ issues: {
78
+ code: "provider_error";
79
+ reason: string;
80
+ source: string;
81
+ }[];
82
+ }>;
39
83
  export interface MirrorSyncOptions<S> extends Pick<PushOptions<S>, "principal" | "recreate" | "guard" | "operationId" | "errorOf" | "signal"> {
40
84
  mirrors: Mirror[];
41
85
  target: DocumentTarget<S>;
42
86
  stateOf(mirror: Mirror): PushStatePort<S>;
43
87
  keep?: Keep;
44
88
  /** Taken once for all the mirrors, so a second sync or a watcher's next cycle waits its turn. */
45
- lock(): Promise<{
46
- assertHeld(): void;
47
- release(): Promise<void> | void;
48
- }>;
89
+ lock(): Promise<MirrorLock>;
49
90
  /** How the app names the remote side in conflict reports. */
50
91
  remote: string;
51
92
  }
52
- /**
53
- * Syncs each mirror both ways. A mirror with conflicts, missing remote files or errors does not stop the others;
54
- * it gets one `mirror.partial` issue, so the caller can answer `complete: false` and fail after printing.
55
- */
93
+ /** Syncs each mirror both ways, as `eachMirror` runs them. */
56
94
  export declare const syncMirrors: <S>(options: MirrorSyncOptions<S>) => Promise<{
57
- items: {
58
- created: string[];
59
- updated: string[];
60
- pulled: string[];
61
- unchanged: number;
62
- missing: string[];
63
- orphans: {
64
- path: string;
65
- url: string;
66
- }[];
67
- errors: {
68
- path: string;
69
- code: string;
70
- message: string;
71
- }[];
72
- unsupported: number;
73
- plan?: {
74
- create: string[];
75
- update: string[];
76
- orphans: string[];
77
- };
78
- stopped?: true;
95
+ items: (Omit<{
79
96
  id: string;
80
97
  path: string;
98
+ } & import("./push.js").PushResult, "conflicts"> & {
81
99
  conflicts: {
82
100
  path: string;
83
- url: string;
101
+ url?: string | undefined;
84
102
  reason: string;
85
103
  parts?: {
86
104
  [x: string]: string;
@@ -88,11 +106,13 @@ export declare const syncMirrors: <S>(options: MirrorSyncOptions<S>) => Promise<
88
106
  local: string;
89
107
  }[] | undefined;
90
108
  local_changed_at?: string | undefined;
109
+ local_size?: number | undefined;
91
110
  }[];
92
- }[];
111
+ })[];
93
112
  issues: {
94
113
  code: "provider_error";
95
114
  reason: string;
96
115
  source: string;
97
116
  }[];
98
117
  }>;
118
+ export {};
@@ -1,6 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { mkdirSync, readFileSync } from "node:fs";
3
- import { join } from "node:path";
3
+ import { dirname, join } from "node:path";
4
4
  import { CliError, writeSecurely } from "@wirecat/cli-base";
5
5
  import * as v from "valibot";
6
6
  import { planPush, pushDocuments, scanLocal } from "./push.js";
@@ -27,46 +27,44 @@ const stateSchema = (kinds) => v.object({
27
27
  pending: v.record(v.string(), v.object({ origin: v.string(), operationId: v.string() })),
28
28
  });
29
29
  /**
30
- * A mirror's sync state in `<dir>/<id>.json`. A missing file is a first sync; an unreadable or invalid one is
31
- * refused rather than reset, since a reset would push every file again as new.
30
+ * A state file read against `schema`, saved 0600 in a 0700 folder. A missing file is `initial`, a first sync; an
31
+ * unreadable or invalid one is refused rather than reset, since a reset would treat every file as new.
32
32
  */
33
- export const fileMirrorState = (dir, mirror, principal, kinds) => {
34
- const path = join(dir, `${mirror.id}.json`);
35
- const schema = stateSchema(kinds);
36
- return {
37
- read: () => {
38
- let value;
39
- try {
40
- value = JSON.parse(readFileSync(path, "utf8"));
41
- }
42
- catch (error) {
43
- if (error.code === "ENOENT")
44
- return {
45
- version: 1,
46
- principal,
47
- root: mirror.path,
48
- target: mirror.folder,
49
- folders: {},
50
- entries: {},
51
- pending: {},
52
- };
53
- throw new CliError("configuration_error", "mirror state is unreadable; refusing to reset it", {
54
- reason: "state.invalid",
55
- });
56
- }
57
- const parsed = v.safeParse(schema, value);
58
- if (!parsed.success)
59
- throw new CliError("configuration_error", "mirror state is invalid; refusing to reset it", {
60
- reason: "state.invalid",
61
- });
62
- return parsed.output;
63
- },
64
- save: (state) => {
65
- mkdirSync(dir, { recursive: true, mode: 0o700 });
66
- writeSecurely(path, `${JSON.stringify(state)}\n`, 0o600);
67
- },
68
- };
69
- };
33
+ export const jsonState = (path, schema, initial) => ({
34
+ read: () => {
35
+ let value;
36
+ try {
37
+ value = JSON.parse(readFileSync(path, "utf8"));
38
+ }
39
+ catch (error) {
40
+ if (error.code === "ENOENT")
41
+ return initial();
42
+ throw new CliError("configuration_error", "mirror state is unreadable; refusing to reset it", {
43
+ reason: "state.invalid",
44
+ });
45
+ }
46
+ const parsed = v.safeParse(schema, value);
47
+ if (!parsed.success)
48
+ throw new CliError("configuration_error", "mirror state is invalid; refusing to reset it", {
49
+ reason: "state.invalid",
50
+ });
51
+ return parsed.output;
52
+ },
53
+ save: (state) => {
54
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
55
+ writeSecurely(path, `${JSON.stringify(state)}\n`, 0o600);
56
+ },
57
+ });
58
+ /** A mirror's push state in `<dir>/<id>.json`. */
59
+ export const fileMirrorState = (dir, mirror, principal, kinds) => jsonState(join(dir, `${mirror.id}.json`), stateSchema(kinds), () => ({
60
+ version: 1,
61
+ principal,
62
+ root: mirror.path,
63
+ target: mirror.folder,
64
+ folders: {},
65
+ entries: {},
66
+ pending: {},
67
+ }));
70
68
  /** What the next sync of each mirror would create or send, from local files and the state alone. */
71
69
  export const mirrorStatus = async (mirrors, kindOf, stateOf) => {
72
70
  const items = [];
@@ -90,7 +88,7 @@ export const mirrorStatus = async (mirrors, kindOf, stateOf) => {
90
88
  /** A conflict as the user reads it, with the remote side named the way the app names it (`google`). */
91
89
  export const conflictReport = (conflict, remote) => ({
92
90
  path: conflict.path,
93
- url: conflict.url,
91
+ ...(conflict.url ? { url: conflict.url } : {}),
94
92
  reason: conflict.reason,
95
93
  ...(conflict.parts
96
94
  ? { parts: conflict.parts.map((part) => ({ last_sync: part.base, local: part.local, [remote]: part.remote })) }
@@ -98,41 +96,25 @@ export const conflictReport = (conflict, remote) => ({
98
96
  ...(conflict.localChangedAt ? { local_changed_at: conflict.localChangedAt } : {}),
99
97
  ...(conflict.remoteChangedAt ? { [`${remote}_changed_at`]: conflict.remoteChangedAt } : {}),
100
98
  ...(conflict.remoteChangedBy ? { [`${remote}_changed_by`]: conflict.remoteChangedBy } : {}),
99
+ ...(conflict.localSize !== undefined ? { local_size: conflict.localSize } : {}),
100
+ ...(conflict.remoteSize !== undefined ? { [`${remote}_size`]: conflict.remoteSize } : {}),
101
101
  });
102
102
  /**
103
- * Syncs each mirror both ways. A mirror with conflicts, missing remote files or errors does not stop the others;
104
- * it gets one `mirror.partial` issue, so the caller can answer `complete: false` and fail after printing.
103
+ * Runs `sync` for each mirror under one lock. A mirror with conflicts, missing remote files or errors does not stop
104
+ * the others; it gets one `mirror.partial` issue, so the caller can answer `complete: false` and fail after printing.
105
105
  */
106
- export const syncMirrors = async (options) => {
107
- const { mirrors, keep, remote } = options;
108
- const lock = await options.lock();
106
+ export const eachMirror = async (mirrors, lock, remote, sync) => {
107
+ const held = await lock();
109
108
  const results = [];
110
109
  try {
111
110
  for (const mirror of mirrors)
112
- results.push({
113
- id: mirror.id,
114
- path: mirror.path,
115
- ...(await pushDocuments({
116
- root: mirror.path,
117
- folder: mirror.folder,
118
- target: options.target,
119
- state: options.stateOf(mirror),
120
- principal: options.principal,
121
- ...(keep ? { keep } : {}),
122
- recreate: options.recreate === true,
123
- guard: options.guard,
124
- operationId: options.operationId,
125
- errorOf: options.errorOf,
126
- assertHeld: () => lock.assertHeld(),
127
- ...(options.signal ? { signal: options.signal } : {}),
128
- })),
129
- });
111
+ results.push({ id: mirror.id, path: mirror.path, ...(await sync(mirror, () => held.assertHeld())) });
130
112
  }
131
113
  finally {
132
- await lock.release();
114
+ await held.release();
133
115
  }
134
116
  const issues = results
135
- .filter((result) => result.errors.length || result.conflicts.length || result.missing.length)
117
+ .filter((result) => result.errors.length || result.conflicts.length || result.missing?.length || result.unknown?.length)
136
118
  .map((result) => ({ code: "provider_error", reason: "mirror.partial", source: `mirror ${result.id}` }));
137
119
  return {
138
120
  items: results.map(({ conflicts, ...result }) => ({
@@ -142,3 +124,18 @@ export const syncMirrors = async (options) => {
142
124
  issues,
143
125
  };
144
126
  };
127
+ /** Syncs each mirror both ways, as `eachMirror` runs them. */
128
+ export const syncMirrors = (options) => eachMirror(options.mirrors, options.lock, options.remote, (mirror, assertHeld) => pushDocuments({
129
+ root: mirror.path,
130
+ folder: mirror.folder,
131
+ target: options.target,
132
+ state: options.stateOf(mirror),
133
+ principal: options.principal,
134
+ ...(options.keep ? { keep: options.keep } : {}),
135
+ recreate: options.recreate === true,
136
+ guard: options.guard,
137
+ operationId: options.operationId,
138
+ errorOf: options.errorOf,
139
+ assertHeld,
140
+ ...(options.signal ? { signal: options.signal } : {}),
141
+ }));
@@ -15,7 +15,7 @@ export interface PushOptions<S> {
15
15
  dryRun?: boolean;
16
16
  /** Runs one remote write behind the provider's permission checks and write journal. */
17
17
  guard<T>(attempt: {
18
- action: "create" | "update" | "folder";
18
+ action: MirrorAction;
19
19
  path: string;
20
20
  operationId: string;
21
21
  }, act: () => Promise<T>): Promise<T>;
@@ -26,14 +26,19 @@ export interface PushOptions<S> {
26
26
  maxFiles?: number;
27
27
  now?(): number;
28
28
  }
29
+ /** What a mirror's write does; the guard maps it to the app's permission keys. */
30
+ export type MirrorAction = "create" | "update" | "folder" | "delete" | "move";
29
31
  export interface PushConflict {
30
32
  path: string;
31
- url: string;
33
+ /** The remote file's address, when the provider has one. */
34
+ url?: string;
32
35
  reason: string;
33
36
  parts?: ConflictPart[];
34
37
  localChangedAt?: string;
35
38
  remoteChangedAt?: string;
36
39
  remoteChangedBy?: string;
40
+ localSize?: number;
41
+ remoteSize?: number;
37
42
  }
38
43
  export interface PushResult {
39
44
  created: string[];
@@ -62,10 +67,57 @@ export interface PushResult {
62
67
  }
63
68
  /** Hidden files, `node_modules` and editor leftovers: never mirrored, and never a reason to sync. */
64
69
  export declare const skippedName: (name: string) => boolean;
65
- /** Files under `root` the target pushes. Hidden files, editor leftovers and symbolic links are never followed. */
66
- export declare const scanLocal: (root: string, kindOf: (path: string) => string | undefined, maxFiles?: number) => Promise<{
70
+ /** The sha256 and md5 of a file, read as a stream: a file of any size takes the same memory. */
71
+ export declare const hashFile: (path: string) => Promise<{
72
+ sha256: string;
73
+ md5: string;
74
+ }>;
75
+ /**
76
+ * Puts `from` at `to` only while `to` is absent: a hard link, or a copy into a file this call creates exclusively
77
+ * where the file system has no hard links (exFAT, FAT, many FUSE and SMB mounts) or `to` is on another device. Fails
78
+ * with `EEXIST` when `to` exists; `from` stays for the caller to remove.
79
+ */
80
+ export declare const placeNew: (from: string, to: string) => Promise<void>;
81
+ /**
82
+ * A relative path whose every segment names one entry: none empty, `.` or `..`, none with NUL, and on Windows,
83
+ * where it separates folders, none with a backslash.
84
+ */
85
+ export declare const safePath: (path: string, platform?: NodeJS.Platform) => boolean;
86
+ /**
87
+ * Refuses a write at `path` under `root` when a folder on the way, or the file itself, is a symbolic link: a write
88
+ * would follow it out of the mirrored folder. A part that does not exist yet ends the check.
89
+ */
90
+ export declare const assertNoLink: (root: string, path: string) => Promise<void>;
91
+ /** A hidden temporary file beside `absolute`; `tag` lets a caller find a crash's leftover again. */
92
+ export declare const localTemp: (absolute: string, tag: string) => string;
93
+ /**
94
+ * Writes `absolute` through a temporary file beside it. With `hash`, the file is replaced only while it still has
95
+ * that sha256 (someone may have saved it during the sync) and keeps its mode; without, it is created only while
96
+ * absent. `content` is text, bytes, or a writer that fills the temporary file, for a stream of any size; with
97
+ * `sha256`, content with another hash is refused before it takes the file's place. `tag` names the temporary file, so
98
+ * a crash's leftover can be found. Returns the new file's hashes, or undefined, with nothing written, when the file
99
+ * was not as `hash` said.
100
+ */
101
+ export declare const replaceLocal: (absolute: string, hash: string | undefined, content: string | Uint8Array | ((temp: string) => Promise<void>), { tag, sha256 }?: {
102
+ tag?: string;
103
+ sha256?: string;
104
+ }) => Promise<{
105
+ sha256: string;
106
+ md5: string;
107
+ } | undefined>;
108
+ /**
109
+ * Files under `root` the target pushes. Hidden files, editor leftovers and symbolic links are never followed; the
110
+ * links' paths are returned in `links`, so a mirror does not take the files behind one as deleted. A file whose size
111
+ * and mtime match what `known` returns keeps that hash instead of being read again.
112
+ */
113
+ export declare const scanLocal: (root: string, kindOf: (path: string) => string | undefined, maxFiles?: number, known?: (path: string) => {
114
+ size: number;
115
+ mtimeMs: number;
116
+ hash: string;
117
+ } | undefined) => Promise<{
67
118
  files: LocalDocument[];
68
119
  unsupported: number;
120
+ links: string[];
69
121
  }>;
70
122
  /** What a push would do, from the local files and the last push alone: no remote read. */
71
123
  export declare const planPush: <S>(files: LocalDocument[], state: PushState<S>) => PushPlan;
@@ -1,49 +1,152 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { createReadStream } from "node:fs";
3
- import { chmod, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
2
+ import { createReadStream, createWriteStream } from "node:fs";
3
+ import { chmod, link, lstat, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
4
4
  import { basename, dirname, join, posix } from "node:path";
5
+ import { pipeline } from "node:stream/promises";
5
6
  import { CliError, isCliError } from "@wirecat/cli-base";
6
7
  const SKIPPED = /^(\.|node_modules$|~\$)|(~|\.swp|\.tmp)$/;
7
8
  /** Hidden files, `node_modules` and editor leftovers: never mirrored, and never a reason to sync. */
8
9
  export const skippedName = (name) => SKIPPED.test(name);
9
- const hashFile = (path) => new Promise((done, fail) => {
10
- const hash = createHash("sha256");
10
+ /** The sha256 and md5 of a file, read as a stream: a file of any size takes the same memory. */
11
+ export const hashFile = (path) => new Promise((done, fail) => {
12
+ const sha256 = createHash("sha256");
13
+ const md5 = createHash("md5");
11
14
  createReadStream(path)
12
- .on("data", (chunk) => hash.update(chunk))
15
+ .on("data", (chunk) => {
16
+ sha256.update(chunk);
17
+ md5.update(chunk);
18
+ })
13
19
  .on("error", fail)
14
- .on("end", () => done(hash.digest("hex")));
20
+ .on("end", () => done({ sha256: sha256.digest("hex"), md5: md5.digest("hex") }));
15
21
  });
16
- const hashText = (text) => createHash("sha256").update(text).digest("hex");
17
22
  /**
18
- * Replaces the file through a temporary file beside it, keeping its mode. Undefined, and nothing written, when
19
- * the file no longer has `hash`: someone saved it during the sync.
23
+ * Puts `from` at `to` only while `to` is absent: a hard link, or a copy into a file this call creates exclusively
24
+ * where the file system has no hard links (exFAT, FAT, many FUSE and SMB mounts) or `to` is on another device. Fails
25
+ * with `EEXIST` when `to` exists; `from` stays for the caller to remove.
20
26
  */
21
- const replaceLocal = async (file, content) => {
22
- const temp = join(dirname(file.absolute), `.${basename(file.absolute)}.${randomUUID().slice(0, 8)}.tmp`);
23
- const { mode } = await stat(file.absolute);
24
- await writeFile(temp, content, { flag: "wx" });
27
+ export const placeNew = async (from, to) => {
25
28
  try {
29
+ await link(from, to);
30
+ return;
31
+ }
32
+ catch (error) {
33
+ if (!["EPERM", "ENOTSUP", "EOPNOTSUPP", "EXDEV", "ENOSYS"].includes(error.code ?? ""))
34
+ throw error;
35
+ }
36
+ const { mode } = await stat(from);
37
+ let created = false;
38
+ // "wx" fails with EEXIST before anything exists, so only a file this call opened is ever removed.
39
+ const into = createWriteStream(to, { flags: "wx" }).once("open", () => {
40
+ created = true;
41
+ });
42
+ try {
43
+ await pipeline(createReadStream(from), into);
44
+ await chmod(to, mode & 0o777);
45
+ }
46
+ catch (error) {
47
+ if (created)
48
+ await rm(to, { force: true });
49
+ throw error;
50
+ }
51
+ };
52
+ /**
53
+ * A relative path whose every segment names one entry: none empty, `.` or `..`, none with NUL, and on Windows,
54
+ * where it separates folders, none with a backslash.
55
+ */
56
+ export const safePath = (path, platform = process.platform) => path
57
+ .split("/")
58
+ .every((part) => part !== "" &&
59
+ part !== "." &&
60
+ part !== ".." &&
61
+ !part.includes("\0") &&
62
+ !(platform === "win32" && part.includes("\\")));
63
+ /**
64
+ * Refuses a write at `path` under `root` when a folder on the way, or the file itself, is a symbolic link: a write
65
+ * would follow it out of the mirrored folder. A part that does not exist yet ends the check.
66
+ */
67
+ export const assertNoLink = async (root, path) => {
68
+ let at = root;
69
+ for (const part of path.split("/")) {
70
+ at = join(at, part);
71
+ try {
72
+ if ((await lstat(at)).isSymbolicLink())
73
+ throw new CliError("validation_error", `${path} is under a symbolic link; the sync does not follow links`, {
74
+ reason: "mirror.symlink",
75
+ });
76
+ }
77
+ catch (error) {
78
+ if (error.code === "ENOENT")
79
+ return;
80
+ throw error;
81
+ }
82
+ }
83
+ };
84
+ /** A hidden temporary file beside `absolute`; `tag` lets a caller find a crash's leftover again. */
85
+ export const localTemp = (absolute, tag) => join(dirname(absolute), `.${basename(absolute)}.${tag}.tmp`);
86
+ /**
87
+ * Writes `absolute` through a temporary file beside it. With `hash`, the file is replaced only while it still has
88
+ * that sha256 (someone may have saved it during the sync) and keeps its mode; without, it is created only while
89
+ * absent. `content` is text, bytes, or a writer that fills the temporary file, for a stream of any size; with
90
+ * `sha256`, content with another hash is refused before it takes the file's place. `tag` names the temporary file, so
91
+ * a crash's leftover can be found. Returns the new file's hashes, or undefined, with nothing written, when the file
92
+ * was not as `hash` said.
93
+ */
94
+ export const replaceLocal = async (absolute, hash, content, { tag = randomUUID().slice(0, 8), sha256 } = {}) => {
95
+ const temp = localTemp(absolute, tag);
96
+ const mode = hash === undefined ? undefined : (await stat(absolute)).mode;
97
+ try {
98
+ if (typeof content === "function")
99
+ await content(temp);
100
+ else
101
+ await writeFile(temp, content, { flag: "wx" });
26
102
  // A mode passed to the write goes through the umask; set it after, so a group-writable file stays one.
27
- await chmod(temp, mode & 0o777);
28
- if ((await hashFile(file.absolute)) !== file.hash)
103
+ if (mode !== undefined)
104
+ await chmod(temp, mode & 0o777);
105
+ const written = await hashFile(temp);
106
+ if (sha256 !== undefined && written.sha256 !== sha256)
107
+ throw new CliError("invalid_response", "the downloaded file has other content than the listing said", {
108
+ reason: "download.mismatch",
109
+ });
110
+ if (hash === undefined) {
111
+ // A link fails when the name exists, where a rename would replace a file created during the sync.
112
+ try {
113
+ await placeNew(temp, absolute);
114
+ }
115
+ catch (error) {
116
+ if (error.code === "EEXIST")
117
+ return undefined;
118
+ throw error;
119
+ }
120
+ return written;
121
+ }
122
+ if ((await hashFile(absolute)).sha256 !== hash)
29
123
  return undefined;
30
- await rename(temp, file.absolute);
124
+ await rename(temp, absolute);
125
+ return written;
31
126
  }
32
127
  finally {
33
128
  await rm(temp, { force: true });
34
129
  }
35
- return hashText(content);
36
130
  };
37
- /** Files under `root` the target pushes. Hidden files, editor leftovers and symbolic links are never followed. */
38
- export const scanLocal = async (root, kindOf, maxFiles = 10_000) => {
131
+ /**
132
+ * Files under `root` the target pushes. Hidden files, editor leftovers and symbolic links are never followed; the
133
+ * links' paths are returned in `links`, so a mirror does not take the files behind one as deleted. A file whose size
134
+ * and mtime match what `known` returns keeps that hash instead of being read again.
135
+ */
136
+ export const scanLocal = async (root, kindOf, maxFiles = 10_000, known) => {
39
137
  const files = [];
138
+ const links = [];
40
139
  let unsupported = 0;
41
140
  const walk = async (relative) => {
42
141
  const entries = await readdir(join(root, relative), { withFileTypes: true });
43
142
  for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
44
- if (SKIPPED.test(entry.name) || entry.isSymbolicLink())
143
+ if (SKIPPED.test(entry.name))
45
144
  continue;
46
145
  const path = relative ? posix.join(relative, entry.name) : entry.name;
146
+ if (entry.isSymbolicLink()) {
147
+ links.push(path);
148
+ continue;
149
+ }
47
150
  if (entry.isDirectory())
48
151
  await walk(path);
49
152
  else if (entry.isFile()) {
@@ -57,7 +160,10 @@ export const scanLocal = async (root, kindOf, maxFiles = 10_000) => {
57
160
  reason: "push.too-many-files",
58
161
  });
59
162
  const absolute = join(root, path);
60
- files.push({ path, absolute, kind, hash: await hashFile(absolute) });
163
+ const { size, mtimeMs } = await stat(absolute);
164
+ const before = known?.(path);
165
+ const hash = before && before.size === size && before.mtimeMs === mtimeMs ? before.hash : (await hashFile(absolute)).sha256;
166
+ files.push({ path, absolute, kind, hash, size, mtimeMs });
61
167
  }
62
168
  }
63
169
  };
@@ -69,7 +175,7 @@ export const scanLocal = async (root, kindOf, maxFiles = 10_000) => {
69
175
  throw error;
70
176
  throw new CliError("validation_error", "the folder to push could not be read", { reason: "push.unreadable" });
71
177
  }
72
- return { files, unsupported };
178
+ return { files, unsupported, links };
73
179
  };
74
180
  /** What a push would do, from the local files and the last push alone: no remote read. */
75
181
  export const planPush = (files, state) => {
@@ -232,12 +338,13 @@ export const pushDocuments = async (options) => {
232
338
  // both sides and merges it once.
233
339
  if (prepared.local !== undefined) {
234
340
  options.assertHeld();
235
- const written = await replaceLocal(file, prepared.local);
341
+ await assertNoLink(root, file.path);
342
+ const written = await replaceLocal(file.absolute, file.hash, prepared.local);
236
343
  if (!written) {
237
344
  result.conflicts.push({ path: file.path, url: entry.url, reason: "the local file changed during the sync" });
238
345
  continue;
239
346
  }
240
- hash = written;
347
+ hash = written.sha256;
241
348
  result.pulled.push(file.path);
242
349
  if (prepared.remote && prepared.afterLocal !== undefined) {
243
350
  state.entries[file.path] = { ...entry, snapshot: prepared.afterLocal, hash };