@wirecat/cli-core 0.704.0 → 0.705.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 (76) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/dist/cli/bot/api-http.d.ts +8 -2
  3. package/dist/cli/bot/api-http.js +20 -4
  4. package/dist/cli/documents/words.d.ts +1 -1
  5. package/dist/cli/index.d.ts +3 -3
  6. package/dist/cli/index.js +3 -3
  7. package/dist/cli/messenger/store-maintenance-command.js +6 -2
  8. package/dist/cli/service-api-call.d.ts +13 -3
  9. package/dist/cli/service-api-call.js +19 -9
  10. package/dist/cli/service-api-manifest.d.ts +11 -2
  11. package/dist/cli/service-api-manifest.js +30 -9
  12. package/dist/cli/service-api.d.ts +14 -6
  13. package/dist/cli/service-api.js +137 -29
  14. package/dist/cli/token-session.d.ts +5 -2
  15. package/dist/cli/token-session.js +13 -4
  16. package/dist/content/cli/index.d.ts +33 -0
  17. package/dist/content/cli/index.js +368 -0
  18. package/dist/content/index.d.ts +8 -0
  19. package/dist/content/index.js +7 -0
  20. package/dist/content/manifest/index.d.ts +4 -0
  21. package/dist/content/manifest/index.js +4 -0
  22. package/dist/content/manifest/manifest.d.ts +92 -0
  23. package/dist/content/manifest/manifest.js +137 -0
  24. package/dist/content/manifest/map.d.ts +25 -0
  25. package/dist/content/manifest/map.js +94 -0
  26. package/dist/content/manifest/source.d.ts +41 -0
  27. package/dist/content/manifest/source.js +288 -0
  28. package/dist/content/manifest/writer.d.ts +26 -0
  29. package/dist/content/manifest/writer.js +133 -0
  30. package/dist/content/source.d.ts +64 -0
  31. package/dist/content/source.js +2 -0
  32. package/dist/content/sync.d.ts +61 -0
  33. package/dist/content/sync.js +387 -0
  34. package/dist/content/testing/index.d.ts +4 -0
  35. package/dist/content/testing/index.js +4 -0
  36. package/dist/content/testing/source-contract.d.ts +38 -0
  37. package/dist/content/testing/source-contract.js +274 -0
  38. package/dist/content/testing/source.d.ts +55 -0
  39. package/dist/content/testing/source.js +276 -0
  40. package/dist/content/testing/sync-contract.d.ts +10 -0
  41. package/dist/content/testing/sync-contract.js +172 -0
  42. package/dist/content/testing/write-contract.d.ts +14 -0
  43. package/dist/content/testing/write-contract.js +102 -0
  44. package/dist/content/writer.d.ts +64 -0
  45. package/dist/content/writer.js +38 -0
  46. package/dist/content/writes.d.ts +58 -0
  47. package/dist/content/writes.js +129 -0
  48. package/dist/documents/file-mirror-model.d.ts +3 -1
  49. package/dist/documents/index.d.ts +3 -3
  50. package/dist/documents/index.js +1 -1
  51. package/dist/domain/content.d.ts +102 -0
  52. package/dist/domain/content.js +11 -0
  53. package/dist/errors/reasons.js +14 -0
  54. package/dist/manifest/index.d.ts +21 -7
  55. package/dist/manifest/index.js +7 -4
  56. package/dist/services/documents/mirrors.d.ts +13 -1
  57. package/dist/services/documents/mirrors.js +12 -3
  58. package/dist/services/files/mirror.d.ts +20 -8
  59. package/dist/services/files/mirror.js +84 -27
  60. package/dist/services/files/versions.d.ts +17 -7
  61. package/dist/services/files/versions.js +56 -21
  62. package/dist/store/exports.d.ts +1 -0
  63. package/dist/store/exports.js +1 -0
  64. package/dist/store/recover.js +2 -0
  65. package/dist/store/sqlite/account-purge.js +7 -0
  66. package/dist/store/sqlite/content.d.ts +100 -0
  67. package/dist/store/sqlite/content.js +375 -0
  68. package/dist/store/sqlite/entity-types.d.ts +1 -0
  69. package/dist/store/sqlite/entity-types.js +1 -0
  70. package/dist/store/sqlite/manifest.js +2 -0
  71. package/dist/store/sqlite/migrations.generated.js +26 -0
  72. package/dist/store/sqlite/schema.d.ts +1140 -0
  73. package/dist/store/sqlite/schema.js +100 -0
  74. package/dist/store/store.d.ts +3 -0
  75. package/dist/store/store.js +5 -0
  76. package/package.json +12 -4
@@ -0,0 +1,102 @@
1
+ /**
2
+ * What a blog or a social account publishes, as the store copies it (WordPress first, then Ghost and social posts):
3
+ * the authors, the tags and categories, and the posts and pages. Authors and terms come before the posts that name
4
+ * them. The channel a post is published on (a site, a social account) is read on its own, not as a changes kind.
5
+ */
6
+ export declare const CONTENT_KINDS: readonly ["author", "term", "post"];
7
+ export type ContentKind = (typeof CONTENT_KINDS)[number];
8
+ /** Where a post stands. A trashed post still exists at the source: only a post gone from every list is deleted. */
9
+ export declare const POST_STATUSES: readonly ["draft", "pending", "scheduled", "published", "private", "trashed"];
10
+ export type PostStatus = (typeof POST_STATUSES)[number];
11
+ export declare const POST_TYPES: readonly ["post", "page"];
12
+ export type PostType = (typeof POST_TYPES)[number];
13
+ export declare const CHANNEL_KINDS: readonly ["blog", "social", "newsletter"];
14
+ export type ChannelKind = (typeof CHANNEL_KINDS)[number];
15
+ export declare const TERM_KINDS: readonly ["tag", "category"];
16
+ export type TermKind = (typeof TERM_KINDS)[number];
17
+ /**
18
+ * Every record has the source's id. A field left out means the source did not say, and the store keeps what it
19
+ * held; `null` means the source said there is none. Times are epoch milliseconds.
20
+ */
21
+ interface ContentRecord {
22
+ externalId: string;
23
+ createdAt?: number | null;
24
+ updatedAt?: number | null;
25
+ }
26
+ /** A site or a social account. Two profiles on one site read one channel. */
27
+ export interface ContentChannel {
28
+ externalId: string;
29
+ kind: ChannelKind;
30
+ /** `wordpress`, `ghost`, `linkedin`, `linkedin-page`, `x`. */
31
+ network: string;
32
+ name: string;
33
+ /** The site's address: a sync holds its deletions when it changes, as a moved root would empty the copy. */
34
+ url?: string | null;
35
+ handle?: string | null;
36
+ }
37
+ export interface ContentAuthor extends ContentRecord {
38
+ name: string;
39
+ /** How the store joins the author to a person it already knows: by this exact address, when read. */
40
+ email?: string | null;
41
+ slug?: string | null;
42
+ }
43
+ /** A tag or a category of the source; the store tags a post with the shared tag of the same name. */
44
+ export interface ContentTerm extends ContentRecord {
45
+ kind: TermKind;
46
+ name: string;
47
+ slug?: string | null;
48
+ parent?: string | null;
49
+ }
50
+ export interface ContentMedia {
51
+ externalId?: string | null;
52
+ url: string;
53
+ mime?: string | null;
54
+ alt?: string | null;
55
+ }
56
+ export interface ContentPost extends ContentRecord {
57
+ /** The channel's id; left out, the account's only channel. */
58
+ channel?: string | null;
59
+ type?: PostType;
60
+ /** A social post has none. */
61
+ title?: string | null;
62
+ /** Markdown. */
63
+ body?: string | null;
64
+ /**
65
+ * The source's text holds markup Markdown cannot keep (blocks, embeds, frames): writing the body back would flatten
66
+ * it, so a write of the body needs the owner's `--replace-body`.
67
+ */
68
+ lossy?: boolean | null;
69
+ excerpt?: string | null;
70
+ status: PostStatus;
71
+ url?: string | null;
72
+ slug?: string | null;
73
+ publishedAt?: number | null;
74
+ /** When a scheduled post goes out. */
75
+ scheduledFor?: number | null;
76
+ /** Authors' ids. */
77
+ authors?: string[];
78
+ /** Terms' ids. */
79
+ terms?: string[];
80
+ media?: ContentMedia[];
81
+ /** The post this one is a part of: one text sent to several social channels. */
82
+ parent?: string | null;
83
+ /** The source's own mark of this version, sent back with a write so a change made elsewhere is not overwritten. */
84
+ version?: string | null;
85
+ }
86
+ export interface ContentRecords {
87
+ author: ContentAuthor;
88
+ term: ContentTerm;
89
+ post: ContentPost;
90
+ }
91
+ /** One reading of a post's numbers; each reading is kept, never overwritten. A number the source lacks is absent. */
92
+ export interface ContentMetric {
93
+ post: string;
94
+ at: number;
95
+ views?: number | null;
96
+ reactions?: number | null;
97
+ comments?: number | null;
98
+ shares?: number | null;
99
+ clicks?: number | null;
100
+ raw?: Record<string, unknown>;
101
+ }
102
+ export {};
@@ -0,0 +1,11 @@
1
+ /**
2
+ * What a blog or a social account publishes, as the store copies it (WordPress first, then Ghost and social posts):
3
+ * the authors, the tags and categories, and the posts and pages. Authors and terms come before the posts that name
4
+ * them. The channel a post is published on (a site, a social account) is read on its own, not as a changes kind.
5
+ */
6
+ export const CONTENT_KINDS = ["author", "term", "post"];
7
+ /** Where a post stands. A trashed post still exists at the source: only a post gone from every list is deleted. */
8
+ export const POST_STATUSES = ["draft", "pending", "scheduled", "published", "private", "trashed"];
9
+ export const POST_TYPES = ["post", "page"];
10
+ export const CHANNEL_KINDS = ["blog", "social", "newsletter"];
11
+ export const TERM_KINDS = ["tag", "category"];
@@ -226,6 +226,12 @@ const OTHERS = [
226
226
  "confirmation_required",
227
227
  "the sync would delete more files than the guard allows; check them with --dry-run and allow them explicitly",
228
228
  ],
229
+ [
230
+ "mirror.version-not-kept",
231
+ "provider_error",
232
+ "the earlier content could not be kept in the version store, so the sync did not replace it",
233
+ ],
234
+ ["mirror.remote-changed", "conflict", "the remote file changed since the listing; the next sync settles it"],
229
235
  ["upload.mismatch", "conflict", "the uploaded file reads back with other content; the local file changed meanwhile"],
230
236
  ["download.mismatch", "invalid_response", "the downloaded file has other content than the listing said"],
231
237
  ["catalog.unavailable", "configuration_error", "the store has no shared catalog for this account"],
@@ -497,6 +503,14 @@ const OTHERS = [
497
503
  validation("crm.write-unsupported", "the CRM does not take this write, or does not recognise a repeated one"),
498
504
  validation("crm.unlisted-held", "a list of every id would mark most of a kind deleted; nothing was, until --rescan"),
499
505
  validation("tracker.unlisted-held", "a tracker's id list would mark too much deleted, or the sign-in read only part; nothing was, until --rescan"),
506
+ validation("content.unlisted-held", "a content id list would mark too much deleted, the sign-in read only part, or the site moved; nothing was"),
507
+ validation("content.conflict", "the post changed at the source since the last sync; sync, then write again"),
508
+ validation("content.lossy-body", "the post's text holds blocks or embeds Markdown does not keep; --replace-body"),
509
+ validation("content.schedule-past", "a post is scheduled for a time to come, not one that passed"),
510
+ validation("content.already-published", "a published post cannot be scheduled; unpublish it first"),
511
+ validation("content.empty", "a write names no field to set"),
512
+ ["content.get-unsupported", "configuration_error", "the source cannot read one post, author or term by its id"],
513
+ validation("content.write-unsupported", "the source does not take this write, such as a deletion past the trash"),
500
514
  validation("crm.narrowing-held", "the default scope mine would mark most of a kind's stored rows deleted; none is, until the owner sets the scope"),
501
515
  validation("crm.unassigned-dropped", "the CRM does not let this sign-in choose a user in unassigned; that user's deals are not copied"),
502
516
  validation("crm.not-reported", "the CRM did not list users or departments; what they would say is unknown, nothing withdrawn"),
@@ -1,3 +1,4 @@
1
+ import type { ContentManifest } from "../content/manifest/manifest.js";
1
2
  import type { CrmManifest } from "../crm/manifest/manifest.js";
2
3
  import type { OAuthProvider } from "../oauth/provider.js";
3
4
  import type { TrackerManifest } from "../tracker/manifest/manifest.js";
@@ -26,6 +27,14 @@ export type CliAuth = {
26
27
  preset: "token";
27
28
  verify?: CliVerify;
28
29
  }
30
+ /**
31
+ * A WordPress application password: the profile's own site (`--site host/blog`), a user name and the password, sent
32
+ * by Basic to that site alone.
33
+ */
34
+ | {
35
+ preset: "app-password";
36
+ verify?: CliVerify;
37
+ }
29
38
  /** The browser sign-in the spec's authorization code flow declares; the redirect is what the app registered. */
30
39
  | {
31
40
  preset: "oauth2-pkce";
@@ -38,7 +47,7 @@ export type CliAuth = {
38
47
  /** The provider sends a new refresh token on each refresh; the spec cannot say so. */
39
48
  rotating?: boolean;
40
49
  };
41
- export declare const CLI_CATEGORIES: readonly ["messenger", "mail", "notes", "files", "meetings", "calendar", "crm", "tracker", "other"];
50
+ export declare const CLI_CATEGORIES: readonly ["messenger", "mail", "notes", "files", "meetings", "calendar", "crm", "tracker", "content", "other"];
42
51
  export type CliCategory = (typeof CLI_CATEGORIES)[number];
43
52
  /** One file, `wirecat.config.ts`, that `new --from-config` builds a CLI from. */
44
53
  export interface CliConfig {
@@ -54,26 +63,31 @@ export interface CliConfig {
54
63
  /** The GitHub owner of the repository. */
55
64
  owner: string;
56
65
  };
57
- /** `from`: the https URL the description is published at. */
66
+ /**
67
+ * `from`: the https URL the description is published at. For `wp-json`, a WordPress site's REST index
68
+ * (`https://wp.example/wp-json/`), from a plain WordPress the CLI is made against, as it serves every site.
69
+ */
58
70
  spec: {
59
- kind: "openapi" | "swagger" | "graphql";
71
+ kind: "openapi" | "swagger" | "graphql" | "wp-json";
60
72
  from: string;
73
+ /** The WordPress version `from` runs, for the snapshot's provenance: the index does not say it. */
74
+ version?: string;
61
75
  };
62
76
  auth: CliAuth;
63
77
  /** cli-template's `--category`; `other` is any API outside them. */
64
78
  category: CliCategory;
65
79
  /**
66
- * A crm or tracker CLI's source; checked against the generated API by `parseCrmManifest` or `parseTrackerManifest`
67
- * once the api group exists.
80
+ * A crm, tracker or content CLI's source; checked against the generated API by `parseCrmManifest`,
81
+ * `parseTrackerManifest` or `parseContentManifest` once the api group exists.
68
82
  */
69
- source?: CrmManifest | TrackerManifest;
83
+ source?: CrmManifest | TrackerManifest | ContentManifest;
70
84
  /** The module of named hooks, relative to the config: `./src/hooks.ts`. */
71
85
  hooks?: string;
72
86
  }
73
87
  /** Types the config in the editor; it returns what it is given. */
74
88
  export declare const defineCli: (config: CliConfig) => CliConfig;
75
89
  /**
76
- * The config checked against its shape; every error names where it is. A crm or tracker CLI needs its source. `source` comes back
90
+ * The config checked against its shape; every error names where it is. A crm, tracker or content CLI needs its source. `source` comes back
77
91
  * unchecked: `parseCrmManifest` checks it against the generated API.
78
92
  */
79
93
  export declare const parseCliConfig: (input: unknown) => CliConfig;
@@ -11,6 +11,7 @@ export const CLI_CATEGORIES = [
11
11
  "calendar",
12
12
  "crm",
13
13
  "tracker",
14
+ "content",
14
15
  "other",
15
16
  ];
16
17
  /** Types the config in the editor; it returns what it is given. */
@@ -64,12 +65,14 @@ const schema = v.strictObject({
64
65
  owner: v.pipe(v.string(), v.regex(/^[A-Za-z0-9](?:-?[A-Za-z0-9]){0,38}$/, "a GitHub owner")),
65
66
  }),
66
67
  spec: v.strictObject({
67
- kind: v.picklist(["openapi", "swagger", "graphql"]),
68
+ kind: v.picklist(["openapi", "swagger", "graphql", "wp-json"]),
68
69
  from: httpsUrl,
70
+ version: v.optional(v.pipe(v.string(), v.regex(/^\d+\.\d+(\.\d+)?$/, "a version such as 6.9.4"))),
69
71
  }),
70
72
  auth: v.variant("preset", [
71
73
  v.strictObject({ preset: v.literal("none") }),
72
74
  v.strictObject({ preset: v.literal("token"), verify }),
75
+ v.strictObject({ preset: v.literal("app-password"), verify }),
73
76
  v.strictObject({
74
77
  preset: v.literal("oauth2-pkce"),
75
78
  verify,
@@ -89,7 +92,7 @@ const schema = v.strictObject({
89
92
  hooks: v.optional(v.pipe(v.string(), v.regex(/^\.\/([^\s]*\/)?[^/\s.][^/\s]*\.[cm]?[jt]s$/, "a module in the project, such as ./src/hooks.ts"), v.check((text) => !/\.d\.[cm]?ts$/.test(text), "a module, not a .d.ts declaration file"), v.check((text) => !text.split(/[\\/]/).includes(".."), "a module in the project, without .."))),
90
93
  });
91
94
  /**
92
- * The config checked against its shape; every error names where it is. A crm or tracker CLI needs its source. `source` comes back
95
+ * The config checked against its shape; every error names where it is. A crm, tracker or content CLI needs its source. `source` comes back
93
96
  * unchecked: `parseCrmManifest` checks it against the generated API.
94
97
  */
95
98
  export const parseCliConfig = (input) => {
@@ -111,9 +114,9 @@ export const parseCliConfig = (input) => {
111
114
  // Typed, not cast: a field CliConfig needs that the schema lacks or types otherwise fails to compile (not the reverse).
112
115
  const output = parsed.output;
113
116
  const config = output;
114
- const sourced = config.category === "crm" || config.category === "tracker";
117
+ const sourced = config.category === "crm" || config.category === "tracker" || config.category === "content";
115
118
  if (!sourced && config.source)
116
- throw new CliError("configuration_error", "wirecat.config: source: only a crm or tracker CLI reads a source yet", {
119
+ throw new CliError("configuration_error", "wirecat.config: source: only a crm, tracker or content CLI reads a source yet", {
117
120
  reason: "manifest.invalid",
118
121
  });
119
122
  if (sourced && !config.source)
@@ -47,6 +47,16 @@ interface MirrorLock {
47
47
  assertHeld(): void;
48
48
  release(): Promise<void> | void;
49
49
  }
50
+ /** A sync lock: one as `acquireLock` returns it (`held()`), or one with a synchronous `assertHeld`. */
51
+ export type HeldLock = {
52
+ release(): Promise<void> | void;
53
+ } & ({
54
+ assertHeld(): void;
55
+ } | {
56
+ held(): Promise<boolean>;
57
+ });
58
+ /** The check a write runs first: it throws once the lock is no longer this process's. */
59
+ export declare const heldCheck: (lock: HeldLock) => () => Promise<void>;
50
60
  /**
51
61
  * Runs `sync` for each mirror under one lock. A mirror with conflicts, missing remote files or errors does not stop
52
62
  * the others; it gets one `mirror.partial` issue, so the caller can answer `complete: false` and fail after printing.
@@ -56,7 +66,9 @@ export declare const eachMirror: <R extends {
56
66
  errors: unknown[];
57
67
  missing?: unknown[];
58
68
  unknown?: unknown[];
59
- }>(mirrors: Mirror[], lock: () => Promise<MirrorLock>, remote: string, sync: (mirror: Mirror, assertHeld: () => void) => Promise<R>) => Promise<{
69
+ }, L extends {
70
+ release(): Promise<void> | void;
71
+ }>(mirrors: Mirror[], lock: () => Promise<L>, remote: string, sync: (mirror: Mirror, held: L) => Promise<R>) => Promise<{
60
72
  items: (Omit<{
61
73
  id: string;
62
74
  path: string;
@@ -99,6 +99,15 @@ export const conflictReport = (conflict, remote) => ({
99
99
  ...(conflict.localSize !== undefined ? { local_size: conflict.localSize } : {}),
100
100
  ...(conflict.remoteSize !== undefined ? { [`${remote}_size`]: conflict.remoteSize } : {}),
101
101
  });
102
+ /** The check a write runs first: it throws once the lock is no longer this process's. */
103
+ export const heldCheck = (lock) => async () => {
104
+ if ("assertHeld" in lock)
105
+ return lock.assertHeld();
106
+ if (!(await lock.held()))
107
+ throw new CliError("provider_unavailable", "the mirrors' sync lock was lost; sync again", {
108
+ reason: "profile.busy",
109
+ });
110
+ };
102
111
  /**
103
112
  * Runs `sync` for each mirror under one lock. A mirror with conflicts, missing remote files or errors does not stop
104
113
  * the others; it gets one `mirror.partial` issue, so the caller can answer `complete: false` and fail after printing.
@@ -108,7 +117,7 @@ export const eachMirror = async (mirrors, lock, remote, sync) => {
108
117
  const results = [];
109
118
  try {
110
119
  for (const mirror of mirrors)
111
- results.push({ id: mirror.id, path: mirror.path, ...(await sync(mirror, () => held.assertHeld())) });
120
+ results.push({ id: mirror.id, path: mirror.path, ...(await sync(mirror, held)) });
112
121
  }
113
122
  finally {
114
123
  await held.release();
@@ -125,7 +134,7 @@ export const eachMirror = async (mirrors, lock, remote, sync) => {
125
134
  };
126
135
  };
127
136
  /** Syncs each mirror both ways, as `eachMirror` runs them. */
128
- export const syncMirrors = (options) => eachMirror(options.mirrors, options.lock, options.remote, (mirror, assertHeld) => pushDocuments({
137
+ export const syncMirrors = (options) => eachMirror(options.mirrors, options.lock, options.remote, (mirror, held) => pushDocuments({
129
138
  root: mirror.path,
130
139
  folder: mirror.folder,
131
140
  target: options.target,
@@ -136,6 +145,6 @@ export const syncMirrors = (options) => eachMirror(options.mirrors, options.lock
136
145
  guard: options.guard,
137
146
  operationId: options.operationId,
138
147
  errorOf: options.errorOf,
139
- assertHeld,
148
+ assertHeld: () => held.assertHeld(),
140
149
  ...(options.signal ? { signal: options.signal } : {}),
141
150
  }));
@@ -1,7 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import type { FileMirrorStatePort, FileStepKind, FileTarget } from "../../documents/file-mirror-model.js";
3
3
  import type { Keep } from "../../documents/push-model.js";
4
- import { type Mirror } from "../documents/mirrors.js";
4
+ import { type HeldLock, type Mirror } from "../documents/mirrors.js";
5
5
  import { type MirrorAction, type PushConflict } from "../documents/push.js";
6
6
  import type { FileVersions } from "./versions.js";
7
7
  type Side = "local" | "remote";
@@ -12,7 +12,10 @@ export interface FileMirrorOptions {
12
12
  folder: string;
13
13
  target: FileTarget;
14
14
  state: FileMirrorStatePort;
15
- /** Keeps every local file's content before the sync overwrites or deletes it, and logs each change. */
15
+ /**
16
+ * Keeps every content before the sync overwrites or deletes it (a remote one an upload replaces is downloaded first
17
+ * unless the store has it; a remote deletion leaves it in the provider's trash), and logs each change.
18
+ */
16
19
  versions: FileVersions;
17
20
  principal: string;
18
21
  /** Settles conflicts; without it they are reported and left. */
@@ -27,6 +30,8 @@ export interface FileMirrorOptions {
27
30
  repin?: boolean;
28
31
  /** How the app names the remote side; it ends a conflict copy's name. */
29
32
  remote: string;
33
+ /** How the app's commands are named in the deletion guard's and the repin message; the defaults are flags. */
34
+ hints?: Partial<MirrorHints>;
30
35
  /** Runs one write behind the app's permission checks; `side` says which side it changes. */
31
36
  guard<T>(attempt: {
32
37
  action: MirrorAction;
@@ -36,11 +41,20 @@ export interface FileMirrorOptions {
36
41
  }, act: () => Promise<T>): Promise<T>;
37
42
  operationId(): string;
38
43
  errorOf(error: unknown): CliError;
39
- assertHeld(): void;
44
+ /** Throws once the sync lock is lost; checked before every write. */
45
+ assertHeld(): void | Promise<void>;
40
46
  signal?: AbortSignal;
41
47
  maxFiles?: number;
42
48
  now?(): number;
43
49
  }
50
+ export interface MirrorHints {
51
+ /** How to preview a run: `--dry-run`. */
52
+ preview: string;
53
+ /** How to record a replaced root again: `--repin`. */
54
+ repin: string;
55
+ /** How to allow a run's deletions: `explicitly`, as in "allow them explicitly". */
56
+ allowDeletions: string;
57
+ }
44
58
  export interface FileStep {
45
59
  kind: FileStepKind;
46
60
  path: string;
@@ -106,14 +120,12 @@ export declare const fileMirrorStatus: (mirrors: Mirror[], stateOf: (mirror: Mir
106
120
  * at the first poll), none when it did not, and every mirror at each poll when the target has no revision.
107
121
  */
108
122
  export declare const fileRemoteChanges: (target: FileTarget) => (signal: AbortSignal) => Promise<string[] | "all">;
109
- export interface FileMirrorSyncOptions extends Pick<FileMirrorOptions, "target" | "principal" | "keep" | "dryRun" | "allowDeletions" | "repin" | "guard" | "operationId" | "errorOf" | "signal"> {
123
+ export interface FileMirrorSyncOptions extends Pick<FileMirrorOptions, "target" | "principal" | "keep" | "dryRun" | "allowDeletions" | "repin" | "hints" | "guard" | "operationId" | "errorOf" | "signal"> {
110
124
  mirrors: Mirror[];
111
125
  stateOf(mirror: Mirror): FileMirrorStatePort;
112
126
  versionsOf(mirror: Mirror): FileVersions;
113
- lock(): Promise<{
114
- assertHeld(): void;
115
- release(): Promise<void> | void;
116
- }>;
127
+ /** The sync lock, as `acquireLock` returns it or with a synchronous `assertHeld`. */
128
+ lock(): Promise<HeldLock>;
117
129
  /** How the app names the remote side in reports and conflict copies. */
118
130
  remote: string;
119
131
  }
@@ -1,10 +1,11 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { mkdir, rm, stat, unlink } from "node:fs/promises";
3
3
  import { dirname, join, posix } from "node:path";
4
- import { CliError } from "@wirecat/cli-base";
4
+ import { CliError, isCliError } from "@wirecat/cli-base";
5
5
  import * as v from "valibot";
6
- import { eachMirror, jsonState } from "../documents/mirrors.js";
6
+ import { eachMirror, heldCheck, jsonState } from "../documents/mirrors.js";
7
7
  import { assertNoLink, hashFile, localTemp, placeNew, replaceLocal, safePath, scanLocal, skippedName, } from "../documents/push.js";
8
+ const HINTS = { preview: "--dry-run", repin: "--repin", allowDeletions: "explicitly" };
8
9
  /**
9
10
  * A run that would delete more than `ALWAYS_DELETED` files and more than `MAX_DELETIONS` files or `MAX_DELETED_SHARE`
10
11
  * of the mirror stops before writing.
@@ -128,6 +129,21 @@ const scan = async (root, entries, maxFiles) => {
128
129
  };
129
130
  /** Remote files the mirror covers: hidden files and editor leftovers are skipped, as they are locally. */
130
131
  const mirrored = (files) => files.filter((file) => !file.path.split("/").some(skippedName));
132
+ /** False when `path` or a folder on the way to it is a symbolic link, so nothing under it is touched. */
133
+ const linkFree = (root, path) => assertNoLink(root, path).then(() => true, (error) => {
134
+ if (isCliError(error) && error.details?.reason === "mirror.symlink")
135
+ return false;
136
+ throw error;
137
+ });
138
+ /** True when the file at `absolute` is missing or has one of `hashes`: no partial copy is left there. */
139
+ const whole = async (absolute, hashes) => {
140
+ try {
141
+ return hashes.includes((await hashFile(absolute)).sha256);
142
+ }
143
+ catch (error) {
144
+ return error.code === "ENOENT";
145
+ }
146
+ };
131
147
  /** True when `path` is `link` or lies under it. */
132
148
  const under = (path, link) => path === link || path.startsWith(`${link}/`);
133
149
  /**
@@ -139,6 +155,7 @@ const under = (path, link) => path === link || path.startsWith(`${link}/`);
139
155
  */
140
156
  export const syncFileMirror = async (options) => {
141
157
  const { root, folder, target, principal, keep, signal, versions } = options;
158
+ const hints = { ...HINTS, ...options.hints };
142
159
  const now = options.now ?? Date.now;
143
160
  if (signal?.aborted)
144
161
  throw new CliError("cancelled", "sync was cancelled");
@@ -172,7 +189,8 @@ export const syncFileMirror = async (options) => {
172
189
  : localReplaced && !repin
173
190
  ? problem("local", "confirmation_required", "the local folder was replaced by another one", true)
174
191
  : Object.keys(state.entries).length > 0 && !local.size
175
- ? problem("local", "validation_error", "the local folder is empty; it may be an unmounted drive")
192
+ ? problem("local", "validation_error", "the local folder is empty; it may be an unmounted drive. Mount it, or if the files were really " +
193
+ "deleted, add a file to the folder or remove the mirror's state to start over")
176
194
  : undefined;
177
195
  const refused = rootProblem ? [] : (listed?.files ?? []).filter((file) => !safePath(file.path));
178
196
  const refusedIds = new Set(refused.map((file) => file.id));
@@ -218,7 +236,8 @@ export const syncFileMirror = async (options) => {
218
236
  path: ".",
219
237
  code,
220
238
  message: repinnable
221
- ? `${reason}; if it is the right folder now, sync again with --repin to record it (that run deletes nothing)`
239
+ ? `${reason}; if it is the right folder now, sync again with ${hints.repin} to record it ` +
240
+ "(that run deletes nothing)"
222
241
  : reason,
223
242
  });
224
243
  return result;
@@ -253,7 +272,10 @@ export const syncFileMirror = async (options) => {
253
272
  const here = local.get(path);
254
273
  // Where links fail, a download is copied into place; a crash midway leaves a partial file under the real name,
255
274
  // which must be neither sent nor overwritten.
256
- if (state.pending[path]?.op === "download" && here && here.hash !== file?.sha256 && here.hash !== entry?.sha256) {
275
+ const pending = state.pending[path];
276
+ // A replaced file is renamed into place whole; only a new file may be a partial copy.
277
+ const created = pending?.op === "download" && pending.created !== false;
278
+ if (created && here && here.hash !== file?.sha256 && here.hash !== entry?.sha256) {
257
279
  cutOff.add(path);
258
280
  steps.push({
259
281
  kind: "conflict",
@@ -301,7 +323,8 @@ export const syncFileMirror = async (options) => {
301
323
  return result;
302
324
  }
303
325
  if (tooMany && (options.allowDeletions ?? 0) < deletions)
304
- throw new CliError("confirmation_required", `this sync would delete ${deletions} files; check them with --dry-run and allow them explicitly`, { reason: "mirror.too-many-deletions", deletions });
326
+ throw new CliError("confirmation_required", `this sync would delete ${deletions} files; ` +
327
+ `check them with ${hints.preview} and allow them ${hints.allowDeletions}`, { reason: "mirror.too-many-deletions", deletions });
305
328
  if (repin) {
306
329
  state.entries = {};
307
330
  state.rootId = listed?.rootId;
@@ -314,7 +337,8 @@ export const syncFileMirror = async (options) => {
314
337
  state.localRoot ??= { dev: localRoot.dev, ino: localRoot.ino };
315
338
  }
316
339
  for (const [path, pending] of Object.entries(state.pending)) {
317
- if (pending.op === "download")
340
+ const parent = posix.dirname(path);
341
+ if (pending.op === "download" && (parent === "." || (await linkFree(root, parent))))
318
342
  await rm(localTemp(join(root, path), tagOf(pending.operationId)), { force: true });
319
343
  if (!cutOff.has(path))
320
344
  delete state.pending[path];
@@ -340,8 +364,8 @@ export const syncFileMirror = async (options) => {
340
364
  for (let up = path; up !== "."; up = posix.dirname(up))
341
365
  folders.add(up);
342
366
  let lastOperation = "";
343
- const write = (action, side, path, act, operationId) => {
344
- options.assertHeld();
367
+ const write = async (action, side, path, act, operationId) => {
368
+ await options.assertHeld();
345
369
  lastOperation = operationId ?? options.operationId();
346
370
  return options.guard({ action, side, path, operationId: lastOperation }, act);
347
371
  };
@@ -358,7 +382,23 @@ export const syncFileMirror = async (options) => {
358
382
  };
359
383
  save();
360
384
  };
361
- const upload = async (path, from, expect, created) => {
385
+ /**
386
+ * Keeps the remote content an upload will replace, downloaded through the store unless it holds it already.
387
+ * Refused as `mirror.remote-changed` when the remote no longer has the listed content.
388
+ */
389
+ const keepRemote = async (path, file) => {
390
+ const listed = file.sha256;
391
+ if (versions.has(listed))
392
+ return;
393
+ const kept = await versions.keep((temp) => target.download(remotePath(path), temp, signal));
394
+ if (kept !== listed)
395
+ throw new CliError("conflict", `the ${options.remote} file changed since the listing`, {
396
+ reason: "mirror.remote-changed",
397
+ });
398
+ };
399
+ const upload = async (path, from, expect, created, replaced) => {
400
+ if (replaced)
401
+ await keepRemote(path, replaced);
362
402
  for (const up of ancestors(path))
363
403
  if (!folders.has(up)) {
364
404
  await write("folder", "remote", up, () => target.ensureFolder(remotePath(up), signal));
@@ -372,7 +412,7 @@ export const syncFileMirror = async (options) => {
372
412
  path,
373
413
  event: created ? "created" : "changed",
374
414
  direction: "local-to-remote",
375
- ...("sha256" in expect ? { old: expect.sha256 } : {}),
415
+ ...("sha256" in expect ? { old: expect.sha256, from: "remote" } : {}),
376
416
  new: from.hash,
377
417
  size: from.size,
378
418
  });
@@ -384,16 +424,27 @@ export const syncFileMirror = async (options) => {
384
424
  */
385
425
  const download = async (path, file, over, recorded = true) => {
386
426
  const operationId = options.operationId();
387
- state.pending[path] = { op: "download", operationId };
427
+ state.pending[path] = { op: "download", operationId, created: !over };
388
428
  save(true);
389
429
  const absolute = join(root, path);
390
- await assertNoLink(root, path);
391
- await mkdir(dirname(absolute), { recursive: true });
392
- const old = over ? await versions.keep(absolute) : undefined;
393
- const written = await write(over ? "update" : "create", "local", path, () => replaceLocal(absolute, over?.hash, (temp) => target.download(remotePath(file.path), temp, signal), {
394
- tag: tagOf(operationId),
395
- sha256: file.sha256,
396
- }), operationId);
430
+ let written;
431
+ let old;
432
+ try {
433
+ await assertNoLink(root, path);
434
+ await mkdir(dirname(absolute), { recursive: true });
435
+ old = over ? await versions.keep(absolute) : undefined;
436
+ written = await write(over ? "update" : "create", "local", path, () => replaceLocal(absolute, over?.hash, (temp) => target.download(remotePath(file.path), temp, signal), {
437
+ tag: tagOf(operationId),
438
+ sha256: file.sha256,
439
+ }), operationId);
440
+ }
441
+ catch (error) {
442
+ // A failed copy into place removes what it wrote; should that removal fail too, the marker keeps the partial
443
+ // file from being sent or overwritten.
444
+ if (await whole(absolute, [file.sha256, over?.hash]))
445
+ delete state.pending[path];
446
+ throw error;
447
+ }
397
448
  delete state.pending[path];
398
449
  if (!written)
399
450
  return false;
@@ -403,7 +454,7 @@ export const syncFileMirror = async (options) => {
403
454
  path,
404
455
  event: old ? "changed" : "created",
405
456
  direction: "remote-to-local",
406
- ...(old ? { old } : {}),
457
+ ...(old ? { old, from: "local" } : {}),
407
458
  new: written.sha256,
408
459
  size: file.size,
409
460
  });
@@ -428,7 +479,7 @@ export const syncFileMirror = async (options) => {
428
479
  return;
429
480
  case "upload":
430
481
  if (here)
431
- await upload(path, here, expectOf(there), !there);
482
+ await upload(path, here, expectOf(there), !there, there);
432
483
  return;
433
484
  case "download":
434
485
  if (there && !(await download(path, there, here)))
@@ -445,6 +496,9 @@ export const syncFileMirror = async (options) => {
445
496
  event: "deleted",
446
497
  direction: "local-to-remote",
447
498
  old: there.sha256,
499
+ from: "remote",
500
+ // Not downloaded to be kept: the provider's trash holds it, and a deleted folder may be large.
501
+ ...(versions.has(there.sha256) ? {} : { oldIn: "remote-trash" }),
448
502
  size: there.size,
449
503
  });
450
504
  result.trashed.push({ path, side: "remote" });
@@ -457,7 +511,7 @@ export const syncFileMirror = async (options) => {
457
511
  return changedHere(step);
458
512
  delete state.entries[path];
459
513
  save();
460
- versions.log({ path, event: "deleted", direction: "remote-to-local", old, size: here.size });
514
+ versions.log({ path, event: "deleted", direction: "remote-to-local", old, from: "local", size: here.size });
461
515
  result.trashed.push({ path, side: "local" });
462
516
  return;
463
517
  }
@@ -481,6 +535,8 @@ export const syncFileMirror = async (options) => {
481
535
  const copy = copyName(path, options.remote, date, (name) => local.has(name) || remote.has(name));
482
536
  if (!(await download(copy, there, undefined, false)))
483
537
  return changedHere(step);
538
+ if ((await versions.keep(join(root, copy))) !== there.sha256)
539
+ await keepRemote(path, there);
484
540
  await upload(path, here, expectOf(there), false);
485
541
  const { size, mtimeMs } = await stat(join(root, copy));
486
542
  const copied = { ...here, path: copy, absolute: join(root, copy), hash: there.sha256, size, mtimeMs };
@@ -511,7 +567,8 @@ export const syncFileMirror = async (options) => {
511
567
  else
512
568
  result.errors.push({ path: step.path, code: failure.code, message: failure.message });
513
569
  // Not retried: the next listing shows whether it landed, and adopts it when it did.
514
- if (failure.code === "outcome_unknown")
570
+ // A download's outcome is known: its temporary file is gone and the file is in place or not.
571
+ if (failure.code === "outcome_unknown" && step.kind !== "download")
515
572
  state.pending[step.path] = { op: step.kind, operationId: lastOperation };
516
573
  }
517
574
  }
@@ -519,7 +576,7 @@ export const syncFileMirror = async (options) => {
519
576
  finally {
520
577
  save(true);
521
578
  }
522
- options.assertHeld();
579
+ await options.assertHeld();
523
580
  await versions.prune();
524
581
  return result;
525
582
  };
@@ -547,7 +604,7 @@ const stateSchema = v.object({
547
604
  rootId: v.optional(v.string()),
548
605
  localRoot: v.optional(v.object({ dev: v.number(), ino: v.number() })),
549
606
  entries: v.record(v.string(), entrySchema),
550
- pending: v.record(v.string(), v.object({ op: v.string(), operationId: v.string() })),
607
+ pending: v.record(v.string(), v.object({ op: v.string(), operationId: v.string(), created: v.optional(v.boolean()) })),
551
608
  });
552
609
  /** A file mirror's state in `<dir>/<id>.json`, refused rather than reset when invalid. */
553
610
  export const fileSyncState = (dir, mirror, principal) => jsonState(join(dir, `${mirror.id}.json`), stateSchema, () => ({
@@ -593,11 +650,11 @@ export const fileRemoteChanges = (target) => {
593
650
  };
594
651
  };
595
652
  /** Syncs each file mirror under one lock, with one `mirror.partial` issue per mirror left with conflicts or errors. */
596
- export const syncFileMirrors = (options) => eachMirror(options.mirrors, options.lock, options.remote, (mirror, assertHeld) => syncFileMirror({
653
+ export const syncFileMirrors = (options) => eachMirror(options.mirrors, options.lock, options.remote, (mirror, held) => syncFileMirror({
597
654
  ...options,
598
655
  root: mirror.path,
599
656
  folder: mirror.folder,
600
657
  state: options.stateOf(mirror),
601
658
  versions: options.versionsOf(mirror),
602
- assertHeld,
659
+ assertHeld: heldCheck(held),
603
660
  }));