@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
@@ -1,3 +1,4 @@
1
+ import { type HeldLock } from "../documents/mirrors.js";
1
2
  /** Which way a sync moved a change. */
2
3
  export type VersionDirection = "local-to-remote" | "remote-to-local" | "restored";
3
4
  /** One line of a mirror's version log: what a sync did to a path, with the content's hash before and after. */
@@ -8,6 +9,10 @@ export interface VersionEvent {
8
9
  direction: VersionDirection;
9
10
  /** The content the change replaced: the local file kept before a pull or deletion, the remote version an upload replaced. */
10
11
  old?: string;
12
+ /** The side `old` was kept from. */
13
+ from?: "local" | "remote";
14
+ /** Where `old` is when the store does not hold it: a remote deletion leaves it in the provider's trash. */
15
+ oldIn?: "remote-trash";
11
16
  new?: string;
12
17
  size?: number;
13
18
  /** A rename's new path. */
@@ -18,8 +23,15 @@ export interface FileVersion extends VersionEvent {
18
23
  available: boolean;
19
24
  }
20
25
  export interface FileVersions {
21
- /** Copies the file into the store before the sync overwrites or deletes it; returns the hash of what it copied. */
22
- keep(absolute: string): Promise<string>;
26
+ /**
27
+ * Copies a content into the store before the sync overwrites or deletes it; returns the hash of what it copied. The
28
+ * source is a local file, or a writer that creates the temporary file it is given, such as a target's `download`.
29
+ * A failure of the store itself, the writer's local file-system errors (a full disk) included, is
30
+ * `mirror.version-not-kept`; the writer's other errors pass through.
31
+ */
32
+ keep(source: string | ((temp: string) => Promise<void>)): Promise<string>;
33
+ /** Whether the store holds this content. */
34
+ has(sha256: string): boolean;
23
35
  log(event: Omit<VersionEvent, "at">): void;
24
36
  /** Every event of `path`, oldest first, including renames to or from it. */
25
37
  list(path: string): FileVersion[];
@@ -42,9 +54,7 @@ export declare const fileVersions: (dir: string, now?: () => number) => FileVers
42
54
  /**
43
55
  * Puts a kept version of `path` back into the mirrored folder; the file there now is kept first. The next sync sends
44
56
  * it like any local change. False when the store no longer has the version or the file changed meanwhile. Runs under
45
- * the mirrors' sync lock, so a sync never reads the folder halfway through.
57
+ * the mirrors' sync lock (as `acquireLock` returns it, or any `assertHeld`), so a sync never reads the folder halfway
58
+ * through.
46
59
  */
47
- export declare const restoreFileVersion: (root: string, path: string, sha256: string, versions: FileVersions, lock: () => Promise<{
48
- assertHeld(): void;
49
- release(): Promise<void> | void;
50
- }>) => Promise<boolean>;
60
+ export declare const restoreFileVersion: (root: string, path: string, sha256: string, versions: FileVersions, lock: () => Promise<HeldLock>) => Promise<boolean>;
@@ -1,12 +1,41 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { appendFileSync, createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync } from "node:fs";
3
- import { readdir, rename, rm, stat, utimes } from "node:fs/promises";
3
+ import { mkdir, readdir, rename, rm, stat, utimes } from "node:fs/promises";
4
4
  import { join } from "node:path";
5
5
  import { Transform } from "node:stream";
6
6
  import { pipeline } from "node:stream/promises";
7
7
  import { CliError } from "@wirecat/cli-base";
8
- import { assertNoLink, replaceLocal, safePath } from "../documents/push.js";
8
+ import { heldCheck } from "../documents/mirrors.js";
9
+ import { assertNoLink, hashFile, replaceLocal, safePath } from "../documents/push.js";
9
10
  const RETAIN_MS = 30 * 24 * 60 * 60 * 1000;
11
+ /** Errors of the local file system: a writer that fails with one could not write the store, whatever it was reading. */
12
+ const LOCAL_FAILURES = new Set(["ENOSPC", "EDQUOT", "EROFS", "EACCES", "EPERM", "EIO", "EFBIG", "EMFILE", "ENFILE"]);
13
+ const notKept = (error) => {
14
+ const why = error.code ?? String(error);
15
+ return new CliError("provider_error", `the earlier content could not be kept (${why}); nothing was replaced`, {
16
+ reason: "mirror.version-not-kept",
17
+ });
18
+ };
19
+ const stored = async (act) => {
20
+ try {
21
+ return await act();
22
+ }
23
+ catch (error) {
24
+ throw notKept(error);
25
+ }
26
+ };
27
+ /** Copies `from` into the new file `into` and returns the sha256 of the bytes it copied. */
28
+ const copyHashed = async (from, into) => {
29
+ const hash = createHash("sha256");
30
+ // Hashed while copied: the file may change under the sync, and the store is keyed by what it really holds.
31
+ await pipeline(createReadStream(from), new Transform({
32
+ transform(chunk, _encoding, done) {
33
+ hash.update(chunk);
34
+ done(null, chunk);
35
+ },
36
+ }), createWriteStream(into, { flags: "wx", mode: 0o600 }));
37
+ return hash.digest("hex");
38
+ };
10
39
  /**
11
40
  * A mirror's local version store: `<dir>/objects/<sha256>` holds each kept content once, `<dir>/log.jsonl` is
12
41
  * append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention, one
@@ -32,30 +61,35 @@ export const fileVersions = (dir, now = Date.now) => {
32
61
  };
33
62
  const has = (sha256) => existsSync(join(objects, sha256));
34
63
  return {
35
- keep: async (absolute) => {
36
- mkdirSync(objects, { recursive: true, mode: 0o700 });
64
+ keep: async (source) => {
65
+ await stored(() => mkdir(objects, { recursive: true, mode: 0o700 }));
37
66
  const temp = join(objects, `.${randomUUID()}.tmp`);
38
- const hash = createHash("sha256");
39
67
  try {
40
- // Hashed while copied: the file may change under the sync, and the store is keyed by what it really holds.
41
- await pipeline(createReadStream(absolute), new Transform({
42
- transform(chunk, _encoding, done) {
43
- hash.update(chunk);
44
- done(null, chunk);
45
- },
46
- }), createWriteStream(temp, { flags: "wx", mode: 0o600 }));
47
- const sha256 = hash.digest("hex");
48
- const object = join(objects, sha256);
49
- if (!has(sha256))
50
- await rename(temp, object);
51
- const at = now() / 1000;
52
- await utimes(object, at, at);
68
+ let sha256;
69
+ if (typeof source === "function") {
70
+ await source(temp).catch((error) => {
71
+ if (LOCAL_FAILURES.has(error.code ?? ""))
72
+ throw notKept(error);
73
+ throw error;
74
+ });
75
+ sha256 = await stored(async () => (await hashFile(temp)).sha256);
76
+ }
77
+ else
78
+ sha256 = await stored(() => copyHashed(source, temp));
79
+ await stored(async () => {
80
+ const object = join(objects, sha256);
81
+ if (!has(sha256))
82
+ await rename(temp, object);
83
+ const at = now() / 1000;
84
+ await utimes(object, at, at);
85
+ });
53
86
  return sha256;
54
87
  }
55
88
  finally {
56
89
  await rm(temp, { force: true });
57
90
  }
58
91
  },
92
+ has,
59
93
  log: (event) => {
60
94
  mkdirSync(dir, { recursive: true, mode: 0o700 });
61
95
  appendFileSync(logPath, `${JSON.stringify({ at: new Date(now()).toISOString(), ...event })}\n`, { mode: 0o600 });
@@ -112,7 +146,8 @@ export const fileVersions = (dir, now = Date.now) => {
112
146
  /**
113
147
  * Puts a kept version of `path` back into the mirrored folder; the file there now is kept first. The next sync sends
114
148
  * it like any local change. False when the store no longer has the version or the file changed meanwhile. Runs under
115
- * the mirrors' sync lock, so a sync never reads the folder halfway through.
149
+ * the mirrors' sync lock (as `acquireLock` returns it, or any `assertHeld`), so a sync never reads the folder halfway
150
+ * through.
116
151
  */
117
152
  export const restoreFileVersion = async (root, path, sha256, versions, lock) => {
118
153
  if (!safePath(path))
@@ -124,14 +159,14 @@ export const restoreFileVersion = async (root, path, sha256, versions, lock) =>
124
159
  const current = existsSync(absolute) ? await versions.keep(absolute) : undefined;
125
160
  if (current === sha256)
126
161
  return true;
127
- held.assertHeld();
162
+ await heldCheck(held)();
128
163
  if (!(await versions.write(sha256, absolute, current)))
129
164
  return false;
130
165
  versions.log({
131
166
  path,
132
167
  event: current ? "changed" : "created",
133
168
  direction: "restored",
134
- ...(current ? { old: current } : {}),
169
+ ...(current ? { old: current, from: "local" } : {}),
135
170
  new: sha256,
136
171
  });
137
172
  return true;
@@ -25,6 +25,7 @@ export type { ChatRekey, ChatRekeys } from "./sqlite/chat-rekey.js";
25
25
  export { CHAT_COLUMNS, TRACKED_CHAT_COLUMNS, titlePart } from "./sqlite/chats.js";
26
26
  export { storeClients } from "./sqlite/clients.js";
27
27
  export { CHAT_LIST_KEY, type ChatCompleteness, type ChatCoverage, fetchedKey, historyStartKey, } from "./sqlite/completeness.js";
28
+ export { type ContentFilter, type ContentHit, type ContentItem, type ContentPerson, type ContentRevision, type ContentSearch, type ContentStore, contentHashOf, type RevisionReason, resetContentPostWords, } from "./sqlite/content.js";
28
29
  export { CONVERSATION_COLUMNS } from "./sqlite/conversations.js";
29
30
  export { type CopyViewer, seenBy } from "./sqlite/copy-viewer.js";
30
31
  export type { CounterTarget } from "./sqlite/counters.js";
@@ -7,6 +7,7 @@ export { BUSINESS_FIND_MAX, } from "./sqlite/business-search.js";
7
7
  export { CHAT_COLUMNS, TRACKED_CHAT_COLUMNS, titlePart } from "./sqlite/chats.js";
8
8
  export { storeClients } from "./sqlite/clients.js";
9
9
  export { CHAT_LIST_KEY, fetchedKey, historyStartKey, } from "./sqlite/completeness.js";
10
+ export { contentHashOf, resetContentPostWords, } from "./sqlite/content.js";
10
11
  export { CONVERSATION_COLUMNS } from "./sqlite/conversations.js";
11
12
  export { seenBy } from "./sqlite/copy-viewer.js";
12
13
  export { resetCrmFileWords, } from "./sqlite/crm-files.js";
@@ -11,6 +11,7 @@ import { readHealthMark, recordDeepCheck } from "./marks.js";
11
11
  import { migrate } from "./migrations.js";
12
12
  import { forgetCoverageSince, REFILL_MARGIN_MS } from "./refill.js";
13
13
  import { resetAttachmentWords } from "./sqlite/attachment-texts.js";
14
+ import { resetContentPostWords } from "./sqlite/content.js";
14
15
  import { resetCrmFileWords } from "./sqlite/crm-files.js";
15
16
  import { involvementStoreOver } from "./sqlite/involvements.js";
16
17
  import { drainMeetingIndex } from "./sqlite/meetings.js";
@@ -385,6 +386,7 @@ const FILLERS = {
385
386
  attachment_words: (database) => void resetAttachmentWords(database),
386
387
  crm_file_words: (database) => void resetCrmFileWords(database),
387
388
  tracker_item_words: (database) => void resetTrackerItemWords(database),
389
+ content_post_words: (database) => void resetContentPostWords(database),
388
390
  attachment_name_words: (database) =>
389
391
  // As migration 20 filled it: й and ё fold as the triggers fold them.
390
392
  database.exec("INSERT INTO attachment_name_words (rowid, name) SELECT id, " +
@@ -98,6 +98,13 @@ export const purgeAccount = (context, accountKey) => {
98
98
  orm.run(sql `DELETE FROM crm_fields WHERE account_id = ${accountKey}`);
99
99
  orm.run(sql `DELETE FROM crm_files WHERE account_id = ${accountKey}`);
100
100
  orm.run(sql `DELETE FROM tracker_items WHERE account_id = ${accountKey}`);
101
+ const postsOf = sql `(SELECT id FROM content_posts WHERE account_id = ${accountKey})`;
102
+ orm.run(sql `DELETE FROM content_post_revisions WHERE post_id IN ${postsOf}`);
103
+ orm.run(sql `DELETE FROM content_metrics WHERE post_id IN ${postsOf}`);
104
+ orm.run(sql `DELETE FROM content_posts WHERE account_id = ${accountKey}`);
105
+ orm.run(sql `DELETE FROM content_terms WHERE account_id = ${accountKey}`);
106
+ orm.run(sql `DELETE FROM content_authors WHERE account_id = ${accountKey}`);
107
+ orm.run(sql `DELETE FROM content_channels WHERE account_id = ${accountKey}`);
101
108
  // An entity made from a record is the owner's and stays; only what the source said goes.
102
109
  const recordsOf = sql `(SELECT id FROM records WHERE account_id = ${accountKey})`;
103
110
  orm.run(sql `DELETE FROM record_relations WHERE record_id IN ${recordsOf} OR target_id IN ${recordsOf}`);
@@ -0,0 +1,100 @@
1
+ import type { ContentChannel, ContentKind, ContentMetric, ContentPost, ContentRecords, PostStatus, PostType } from "../../domain/content.js";
2
+ import type { CacheDatabase } from "../driver.js";
3
+ import type { AccountKey } from "../types.js";
4
+ import type { StoreContext } from "./open.js";
5
+ /** One stored record with what the store keeps beside it. */
6
+ export interface ContentItem<K extends ContentKind = ContentKind> {
7
+ kind: K;
8
+ record: ContentRecords[K];
9
+ /** Gone from a complete list of the source's ids. A trashed post is not deleted: its status says so. */
10
+ deletedAt: number | null;
11
+ syncedAt: number;
12
+ }
13
+ /** What replaced a stored post's text or status: a sync, a write of the owner's, or the source deleting it. */
14
+ export type RevisionReason = "sync" | "write" | "deleted";
15
+ /** A post as it stood before a change; the newest first. */
16
+ export interface ContentRevision {
17
+ title: string | null;
18
+ body: string | null;
19
+ status: PostStatus;
20
+ contentHash: string;
21
+ version: string | null;
22
+ reason: RevisionReason;
23
+ createdAt: number;
24
+ }
25
+ export interface ContentFilter {
26
+ channel?: string;
27
+ statuses?: readonly PostStatus[];
28
+ type?: PostType;
29
+ /** A term's id at the source. */
30
+ term?: string;
31
+ /** An author's id at the source. */
32
+ author?: string;
33
+ /** Published at or after; epoch ms. */
34
+ since?: number;
35
+ /** Published before; epoch ms. */
36
+ until?: number;
37
+ limit?: number;
38
+ offset?: number;
39
+ }
40
+ export interface ContentHit {
41
+ account: AccountKey;
42
+ item: ContentItem<"post">;
43
+ excerpt: string;
44
+ }
45
+ export interface ContentSearch {
46
+ words: string[];
47
+ anyWord?: boolean;
48
+ exact?: boolean;
49
+ /** Absent: every content account's. */
50
+ accounts?: AccountKey[];
51
+ limit?: number;
52
+ offset?: number;
53
+ }
54
+ /** An author joined to the one person the store knows by the same e-mail. */
55
+ export interface ContentPerson {
56
+ author: string;
57
+ person: string;
58
+ name: string | null;
59
+ }
60
+ export interface ContentStore {
61
+ saveChannels(key: AccountKey, channels: readonly ContentChannel[], now: number): Promise<number>;
62
+ channels(key: AccountKey): Promise<ContentChannel[]>;
63
+ /**
64
+ * Upserts records of one kind; a field a record leaves out keeps its stored value, and a record listed again after
65
+ * it was marked deleted comes back. A post whose title, text or status changes keeps what it had as a revision.
66
+ */
67
+ save<K extends ContentKind>(key: AccountKey, kind: K, records: readonly ContentRecords[K][], now: number, options?: {
68
+ reason?: Exclude<RevisionReason, "deleted">;
69
+ }): Promise<number>;
70
+ /**
71
+ * After a complete list of the kind's ids: the stored ones the list lacks that were not synced since `before`. Absence
72
+ * alone is no deletion: the sync reads each again, and `markDeleted` marks the ones the source says are gone.
73
+ */
74
+ unlisted(key: AccountKey, kind: ContentKind, listed: readonly string[], before: number): Promise<string[]>;
75
+ /** Marks one record deleted, as a read that answered "no such post" proves. */
76
+ markDeleted(key: AccountKey, kind: ContentKind, externalId: string, now: number): Promise<boolean>;
77
+ get<K extends ContentKind>(key: AccountKey, kind: K, externalId: string): Promise<ContentItem<K> | undefined>;
78
+ /** Live rows, newest change first; deleted ones never. Post filters apply to posts only. */
79
+ list<K extends ContentKind>(key: AccountKey, kind: K, filter?: ContentFilter): Promise<{
80
+ items: ContentItem<K>[];
81
+ hasMore: boolean;
82
+ }>;
83
+ find(search: ContentSearch): Promise<{
84
+ items: ContentHit[];
85
+ hasMore: boolean;
86
+ }>;
87
+ count(key: AccountKey, kind: ContentKind): Promise<number>;
88
+ /** Scheduled posts whose time has passed, the longest unread first: the source may have published them unmarked. */
89
+ due(key: AccountKey, now: number): Promise<string[]>;
90
+ revisions(key: AccountKey, post: string): Promise<ContentRevision[]>;
91
+ saveMetrics(key: AccountKey, metrics: readonly ContentMetric[]): Promise<number>;
92
+ /** Every reading of a post's numbers, the newest first. */
93
+ metrics(key: AccountKey, post: string, limit?: number): Promise<ContentMetric[]>;
94
+ people(key: AccountKey, authors: readonly string[]): Promise<ContentPerson[]>;
95
+ }
96
+ /** The hash a post's text keeps: a change of either part is a new version. */
97
+ export declare const contentHashOf: (post: Pick<ContentPost, "title" | "body">) => string;
98
+ /** `store rebuild`: the normalized copies follow the current normalizer, then the word index is filled again. */
99
+ export declare const resetContentPostWords: (database: CacheDatabase) => number;
100
+ export declare const contentStoreOver: (context: StoreContext) => ContentStore;