@wirecat/cli-core 0.704.0 → 0.706.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.
- package/CHANGELOG.md +116 -0
- package/dist/cli/bot/api-http.d.ts +8 -2
- package/dist/cli/bot/api-http.js +20 -4
- package/dist/cli/bot/api.d.ts +8 -0
- package/dist/cli/bot/api.js +31 -3
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/index.d.ts +4 -4
- package/dist/cli/index.js +3 -3
- package/dist/cli/messenger/lacks.js +3 -0
- package/dist/cli/messenger/messages-delete-command.js +30 -25
- package/dist/cli/messenger/messages-edit-command.js +2 -0
- package/dist/cli/messenger/messages-scheduled-command.js +110 -4
- package/dist/cli/messenger/store-maintenance-command.js +6 -2
- package/dist/cli/service-api-call.d.ts +13 -3
- package/dist/cli/service-api-call.js +19 -9
- package/dist/cli/service-api-manifest.d.ts +11 -2
- package/dist/cli/service-api-manifest.js +30 -9
- package/dist/cli/service-api.d.ts +14 -6
- package/dist/cli/service-api.js +198 -52
- package/dist/cli/token-session.d.ts +5 -2
- package/dist/cli/token-session.js +13 -4
- package/dist/content/cli/index.d.ts +33 -0
- package/dist/content/cli/index.js +368 -0
- package/dist/content/index.d.ts +8 -0
- package/dist/content/index.js +7 -0
- package/dist/content/manifest/index.d.ts +4 -0
- package/dist/content/manifest/index.js +4 -0
- package/dist/content/manifest/manifest.d.ts +92 -0
- package/dist/content/manifest/manifest.js +137 -0
- package/dist/content/manifest/map.d.ts +25 -0
- package/dist/content/manifest/map.js +94 -0
- package/dist/content/manifest/source.d.ts +41 -0
- package/dist/content/manifest/source.js +288 -0
- package/dist/content/manifest/writer.d.ts +26 -0
- package/dist/content/manifest/writer.js +133 -0
- package/dist/content/source.d.ts +64 -0
- package/dist/content/source.js +2 -0
- package/dist/content/sync.d.ts +61 -0
- package/dist/content/sync.js +387 -0
- package/dist/content/testing/index.d.ts +4 -0
- package/dist/content/testing/index.js +4 -0
- package/dist/content/testing/source-contract.d.ts +38 -0
- package/dist/content/testing/source-contract.js +274 -0
- package/dist/content/testing/source.d.ts +55 -0
- package/dist/content/testing/source.js +276 -0
- package/dist/content/testing/sync-contract.d.ts +10 -0
- package/dist/content/testing/sync-contract.js +172 -0
- package/dist/content/testing/write-contract.d.ts +14 -0
- package/dist/content/testing/write-contract.js +102 -0
- package/dist/content/writer.d.ts +64 -0
- package/dist/content/writer.js +38 -0
- package/dist/content/writes.d.ts +58 -0
- package/dist/content/writes.js +129 -0
- package/dist/documents/file-mirror-model.d.ts +3 -1
- package/dist/documents/index.d.ts +3 -3
- package/dist/documents/index.js +1 -1
- package/dist/domain/content.d.ts +102 -0
- package/dist/domain/content.js +11 -0
- package/dist/entities/index.d.ts +8 -2
- package/dist/entities/index.js +4 -2
- package/dist/entities/message-change.d.ts +240 -0
- package/dist/entities/message-change.js +6 -0
- package/dist/errors/reasons.js +14 -0
- package/dist/kit/fake.d.ts +2 -2
- package/dist/kit/fake.js +21 -0
- package/dist/manifest/index.d.ts +21 -7
- package/dist/manifest/index.js +7 -4
- package/dist/mcp/surface.js +6 -3
- package/dist/ports/messenger.d.ts +20 -1
- package/dist/sends/permissions.js +11 -1
- package/dist/services/documents/mirrors.d.ts +13 -1
- package/dist/services/documents/mirrors.js +12 -3
- package/dist/services/files/mirror.d.ts +20 -8
- package/dist/services/files/mirror.js +84 -27
- package/dist/services/files/versions.d.ts +17 -7
- package/dist/services/files/versions.js +56 -21
- package/dist/services/messages.d.ts +31 -0
- package/dist/services/messages.js +62 -0
- package/dist/store/exports.d.ts +1 -0
- package/dist/store/exports.js +1 -0
- package/dist/store/recover.js +2 -0
- package/dist/store/sqlite/account-purge.js +7 -0
- package/dist/store/sqlite/content.d.ts +100 -0
- package/dist/store/sqlite/content.js +375 -0
- package/dist/store/sqlite/entity-types.d.ts +1 -0
- package/dist/store/sqlite/entity-types.js +1 -0
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +26 -0
- package/dist/store/sqlite/schema.d.ts +1140 -0
- package/dist/store/sqlite/schema.js +100 -0
- package/dist/store/store.d.ts +3 -0
- package/dist/store/store.js +5 -0
- package/package.json +12 -4
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { crmValues } from "../../crm/index.js";
|
|
3
|
+
import { markdownToHtml } from "../../documents/html-markdown.js";
|
|
4
|
+
import { contentConflict } from "../writer.js";
|
|
5
|
+
import { parseContentManifest } from "./manifest.js";
|
|
6
|
+
import { mapContentRecord, postBodyOf } from "./map.js";
|
|
7
|
+
import { fill, inputOf, SITE_CHANNEL } from "./source.js";
|
|
8
|
+
// The manifest's writes name the post calls; a page is read, and written in the source's own editor for now.
|
|
9
|
+
const pagesUnwritten = () => new CliError("validation_error", "this CLI writes posts, not pages", { reason: "content.write-unsupported" });
|
|
10
|
+
const iso = (ms) => `${new Date(ms).toISOString().slice(0, 19)}Z`;
|
|
11
|
+
/**
|
|
12
|
+
* A `ContentWriter` from the manifest's `writes`. Each write reads the post first: an old version is a conflict, and a
|
|
13
|
+
* publish of a published post sends nothing. A body goes as the source keeps text (HTML from Markdown).
|
|
14
|
+
*/
|
|
15
|
+
export const contentWriterFromManifest = (input, options) => {
|
|
16
|
+
const manifest = parseContentManifest(input, options.api);
|
|
17
|
+
const writes = manifest.writes;
|
|
18
|
+
if (!writes)
|
|
19
|
+
throw new CliError("configuration_error", "the source manifest has no writes");
|
|
20
|
+
const [entity] = manifest.entities.post ?? [];
|
|
21
|
+
if (!entity)
|
|
22
|
+
throw new CliError("configuration_error", "the source manifest has no post entity");
|
|
23
|
+
const html = entity.body !== undefined && entity.body.format !== "markdown";
|
|
24
|
+
const postOf = async (answer) => {
|
|
25
|
+
const raw = crmValues.isRaw(answer) && crmValues.isRaw(answer.previous) && answer.deleted === true ? null : answer;
|
|
26
|
+
if (!crmValues.isRaw(raw))
|
|
27
|
+
return null;
|
|
28
|
+
const post = mapContentRecord("post", entity.map, raw);
|
|
29
|
+
if (!post)
|
|
30
|
+
throw new CliError("invalid_response", `${manifest.provider} answered a write with no post`);
|
|
31
|
+
return Object.assign(post, { channel: SITE_CHANNEL }, await postBodyOf(entity, raw));
|
|
32
|
+
};
|
|
33
|
+
const bodyOf = async (fields) => {
|
|
34
|
+
const out = {};
|
|
35
|
+
const put = (path, value) => {
|
|
36
|
+
const keys = path.split(".");
|
|
37
|
+
const last = keys.pop();
|
|
38
|
+
let inner = out;
|
|
39
|
+
for (const key of keys) {
|
|
40
|
+
if (!crmValues.isRaw(inner[key]))
|
|
41
|
+
inner[key] = {};
|
|
42
|
+
inner = inner[key];
|
|
43
|
+
}
|
|
44
|
+
inner[last] = value;
|
|
45
|
+
};
|
|
46
|
+
const to = writes.fields;
|
|
47
|
+
if (fields.title !== undefined && to.title)
|
|
48
|
+
put(to.title, fields.title ?? "");
|
|
49
|
+
if (fields.excerpt !== undefined && to.excerpt)
|
|
50
|
+
put(to.excerpt, fields.excerpt ?? "");
|
|
51
|
+
if (fields.slug !== undefined && to.slug)
|
|
52
|
+
put(to.slug, fields.slug ?? "");
|
|
53
|
+
if (fields.body !== undefined && to.body)
|
|
54
|
+
put(to.body, html ? await markdownToHtml(fields.body) : fields.body);
|
|
55
|
+
if (fields.terms !== undefined && to.terms) {
|
|
56
|
+
const kinds = new Map();
|
|
57
|
+
for (const term of fields.terms) {
|
|
58
|
+
const found = await options.source.get("term", term);
|
|
59
|
+
if (!found)
|
|
60
|
+
throw new CliError("not_found", `no tag or category ${term} at ${manifest.provider}`);
|
|
61
|
+
kinds.set(found.kind, [...(kinds.get(found.kind) ?? []), term]);
|
|
62
|
+
}
|
|
63
|
+
// A numeric id goes as a number: the API's body schema types WordPress's term lists as integers.
|
|
64
|
+
for (const [kind, name] of Object.entries(to.terms))
|
|
65
|
+
if (name)
|
|
66
|
+
put(name, (kinds.get(kind) ?? []).map((one) => (/^\d+$/.test(one) ? Number(one) : one)));
|
|
67
|
+
}
|
|
68
|
+
return out;
|
|
69
|
+
};
|
|
70
|
+
/** The post as the source holds it now, checked against the copy's version. */
|
|
71
|
+
const current = async (externalId, { version }) => {
|
|
72
|
+
const found = await options.source.get("post", externalId);
|
|
73
|
+
if (!found)
|
|
74
|
+
throw new CliError("not_found", `${manifest.provider} has no post ${externalId}; sync, then try again`);
|
|
75
|
+
if (version != null && found.version != null && found.version !== version)
|
|
76
|
+
throw contentConflict();
|
|
77
|
+
if (found.type === "page")
|
|
78
|
+
throw pagesUnwritten();
|
|
79
|
+
return found;
|
|
80
|
+
};
|
|
81
|
+
const send = async (call, slots, body) => {
|
|
82
|
+
const base = call.body === undefined ? {} : fill(call.body, slots);
|
|
83
|
+
const { result } = await options.write(options.command, call.operation, inputOf(call, slots, body === undefined && call.body === undefined ? undefined : { ...base, ...body }));
|
|
84
|
+
return result;
|
|
85
|
+
};
|
|
86
|
+
const updated = async (externalId, body) => {
|
|
87
|
+
const post = await postOf(await send(writes.update, { id: externalId }, body));
|
|
88
|
+
if (!post)
|
|
89
|
+
throw new CliError("invalid_response", `${manifest.provider} answered an update with no post`);
|
|
90
|
+
return post;
|
|
91
|
+
};
|
|
92
|
+
return {
|
|
93
|
+
provider: manifest.provider,
|
|
94
|
+
async createDraft(draft) {
|
|
95
|
+
if (draft.type === "page")
|
|
96
|
+
throw pagesUnwritten();
|
|
97
|
+
const post = await postOf(await send(writes.create, {}, await bodyOf(draft)));
|
|
98
|
+
if (!post)
|
|
99
|
+
throw new CliError("invalid_response", `${manifest.provider} answered a create with no post`);
|
|
100
|
+
return post;
|
|
101
|
+
},
|
|
102
|
+
async update(externalId, patch, options_) {
|
|
103
|
+
await current(externalId, options_);
|
|
104
|
+
return updated(externalId, await bodyOf(patch));
|
|
105
|
+
},
|
|
106
|
+
async publish(externalId, options_) {
|
|
107
|
+
const found = await current(externalId, options_);
|
|
108
|
+
if (found.status === "published")
|
|
109
|
+
return found;
|
|
110
|
+
return updated(externalId, { ...writes.publish });
|
|
111
|
+
},
|
|
112
|
+
async schedule(externalId, when, options_) {
|
|
113
|
+
await current(externalId, options_);
|
|
114
|
+
return updated(externalId, fill(writes.schedule, { at: iso(when) }));
|
|
115
|
+
},
|
|
116
|
+
async unpublish(externalId, options_) {
|
|
117
|
+
await current(externalId, options_);
|
|
118
|
+
return updated(externalId, { ...writes.unpublish });
|
|
119
|
+
},
|
|
120
|
+
async trash(externalId, options_) {
|
|
121
|
+
await current(externalId, options_);
|
|
122
|
+
if (options_.force) {
|
|
123
|
+
if (!writes.delete)
|
|
124
|
+
throw new CliError("validation_error", `${manifest.provider} takes no deletion past the trash`, {
|
|
125
|
+
reason: "content.write-unsupported",
|
|
126
|
+
});
|
|
127
|
+
await send(writes.delete, { id: externalId });
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
return postOf(await send(writes.trash, { id: externalId }));
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { ContentChannel, ContentKind, ContentMetric, ContentRecords } from "../domain/content.js";
|
|
2
|
+
export interface ContentSourceTraits {
|
|
3
|
+
/** What this source has, in `CONTENT_KINDS` order: a social account without terms leaves `term` out. */
|
|
4
|
+
kinds: readonly ContentKind[];
|
|
5
|
+
/** The source has numbers per post that `metrics` reads. */
|
|
6
|
+
metrics: boolean;
|
|
7
|
+
}
|
|
8
|
+
export interface ContentPage<T> {
|
|
9
|
+
items: T[];
|
|
10
|
+
hasMore: boolean;
|
|
11
|
+
nextCursor?: string;
|
|
12
|
+
/** On the last page: the cursor the next run reads changes after; `null` when the source keeps none. */
|
|
13
|
+
cursor?: string | null;
|
|
14
|
+
}
|
|
15
|
+
/** `reset`: the cursor is dead, and the kind must be listed in full again. */
|
|
16
|
+
export type ContentChanges<T> = ContentPage<T> | {
|
|
17
|
+
reset: true;
|
|
18
|
+
};
|
|
19
|
+
export interface ContentIdPage {
|
|
20
|
+
items: string[];
|
|
21
|
+
hasMore: boolean;
|
|
22
|
+
nextCursor?: string;
|
|
23
|
+
}
|
|
24
|
+
/** What the last sync could not read: drafts a role may not see, a kind the sign-in's scope refused. */
|
|
25
|
+
export interface ContentGap {
|
|
26
|
+
kind: ContentKind;
|
|
27
|
+
message: string;
|
|
28
|
+
scope?: string;
|
|
29
|
+
}
|
|
30
|
+
export interface ContentCallContext {
|
|
31
|
+
/** Takes one request from the run's budget for each request beyond the first; throws once it is spent. */
|
|
32
|
+
spend(): void;
|
|
33
|
+
/** Says what the call could not read without failing it. A gap holds the kind's deletions. */
|
|
34
|
+
gap(gap: ContentGap): void;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* One content account, as an adapter reads it: a blog, or a social account. A trashed post is listed with its status,
|
|
38
|
+
* as every status is: a list that leaves trash out would make a trashed post look deleted. A post deleted for good is
|
|
39
|
+
* found by `ids()`, which lists every id of every status, or by `get` answering `null`.
|
|
40
|
+
*/
|
|
41
|
+
export interface ContentSource {
|
|
42
|
+
/** The registry name: `wordpress`. */
|
|
43
|
+
readonly provider: string;
|
|
44
|
+
readonly traits: ContentSourceTraits;
|
|
45
|
+
/** The sites or accounts this sign-in publishes on; their address is how a sync tells a moved site. */
|
|
46
|
+
channels(context?: ContentCallContext): Promise<ContentChannel[]>;
|
|
47
|
+
/**
|
|
48
|
+
* What changed since `cursor`, a page at a time; `cursor: null` lists everything. A source without a change feed
|
|
49
|
+
* reads by its own modified time less an overlap, and gives back as the last page's cursor the time the round's first
|
|
50
|
+
* page was read.
|
|
51
|
+
*/
|
|
52
|
+
changes<K extends ContentKind>(kind: K, cursor: string | null, page?: string, context?: ContentCallContext): Promise<ContentChanges<ContentRecords[K]>>;
|
|
53
|
+
/** Every id the source holds of the kind, trashed ones too, a page at a time: how deletions are found. */
|
|
54
|
+
ids(kind: ContentKind, page?: string, context?: ContentCallContext): Promise<ContentIdPage>;
|
|
55
|
+
/**
|
|
56
|
+
* One record by its id; `null` only when the source said it has none, which proves it deleted. A source that cannot
|
|
57
|
+
* read the kind one by one throws with the reason `GET_UNSUPPORTED`.
|
|
58
|
+
*/
|
|
59
|
+
get<K extends ContentKind>(kind: K, externalId: string, context?: ContentCallContext): Promise<ContentRecords[K] | null>;
|
|
60
|
+
/** A reading of each post's numbers now; a source without metrics answers none. */
|
|
61
|
+
metrics?(posts: readonly string[], context?: ContentCallContext): Promise<ContentMetric[]>;
|
|
62
|
+
}
|
|
63
|
+
/** A source that cannot read one row by its id throws a CliError with this reason; it never answers null for it. */
|
|
64
|
+
export declare const GET_UNSUPPORTED = "content.get-unsupported";
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { type BudgetStop, type RunBudget } from "../background/budget.js";
|
|
2
|
+
import { type ContentKind } from "../domain/content.js";
|
|
3
|
+
import type { MessageStore } from "../store/store.js";
|
|
4
|
+
import type { AccountKey } from "../store/types.js";
|
|
5
|
+
import { type ContentGap, type ContentSource } from "./source.js";
|
|
6
|
+
export declare const contentCursorName: (kind: ContentKind) => string;
|
|
7
|
+
export interface ContentSyncOptions {
|
|
8
|
+
now?: number;
|
|
9
|
+
/** List everything again and every id, dropping a round in progress: `sync --rescan`. */
|
|
10
|
+
rescan?: boolean;
|
|
11
|
+
budget?: RunBudget;
|
|
12
|
+
signal?: AbortSignal;
|
|
13
|
+
/** How long a complete id pass holds before the next one; a day when absent. */
|
|
14
|
+
passEvery?: number;
|
|
15
|
+
}
|
|
16
|
+
export interface ContentSyncResult {
|
|
17
|
+
kind: ContentKind;
|
|
18
|
+
round: "full" | "changes";
|
|
19
|
+
reset: boolean;
|
|
20
|
+
state: "partial" | "complete";
|
|
21
|
+
saved: number;
|
|
22
|
+
/** Rows a complete id pass did not list, or a read answered gone, now marked deleted. */
|
|
23
|
+
unlisted: number;
|
|
24
|
+
/** `held`: it would mark too much deleted, the sign-in read only part, or the site moved; nothing was marked. */
|
|
25
|
+
pass?: "complete" | "partial" | "held";
|
|
26
|
+
held?: string;
|
|
27
|
+
error?: string;
|
|
28
|
+
}
|
|
29
|
+
export interface ContentSyncReport {
|
|
30
|
+
provider: string;
|
|
31
|
+
account: string;
|
|
32
|
+
channels: number;
|
|
33
|
+
/** The channel's address changed since the last sync: no deletion is marked until the owner rescans. */
|
|
34
|
+
moved?: {
|
|
35
|
+
channel: string;
|
|
36
|
+
from: string;
|
|
37
|
+
to: string;
|
|
38
|
+
}[];
|
|
39
|
+
synced: ContentSyncResult[];
|
|
40
|
+
/** Scheduled posts past their time, read again. */
|
|
41
|
+
due: number;
|
|
42
|
+
/** Readings of posts' numbers saved. */
|
|
43
|
+
metrics: number;
|
|
44
|
+
gaps: ContentGap[];
|
|
45
|
+
complete: boolean;
|
|
46
|
+
state: "partial" | "complete";
|
|
47
|
+
stopped?: BudgetStop;
|
|
48
|
+
progress: {
|
|
49
|
+
requests: number;
|
|
50
|
+
saved: number;
|
|
51
|
+
steps: number;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Brings one content account's copy up to date: its channels, each kind's changes since its cursor, the scheduled
|
|
56
|
+
* posts whose time has passed, once a day a pass over every id that marks deleted what the source no longer has, and a
|
|
57
|
+
* reading of the published posts' numbers. A run that hits its budget stops where it is, and the next goes on.
|
|
58
|
+
*/
|
|
59
|
+
export declare const syncContent: (source: ContentSource, store: MessageStore, account: AccountKey, options?: ContentSyncOptions) => Promise<ContentSyncReport>;
|
|
60
|
+
/** The gaps the account's last sync recorded; none before its first. */
|
|
61
|
+
export declare const contentGapsOf: (store: MessageStore, account: AccountKey) => Promise<ContentGap[]>;
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
2
|
+
import { runBudget } from "../background/budget.js";
|
|
3
|
+
import { CONTENT_KINDS } from "../domain/content.js";
|
|
4
|
+
import { GET_UNSUPPORTED } from "./source.js";
|
|
5
|
+
const DAY = 86_400_000;
|
|
6
|
+
/** An id pass that would mark more than this share of a kind deleted is held: a source that lost rights lists none. */
|
|
7
|
+
const MOST_UNLISTED = 0.5;
|
|
8
|
+
const GUARDED_FROM = 10;
|
|
9
|
+
/** Scheduled posts past their time read one by one per run; more wait for the next. */
|
|
10
|
+
const MOST_DUE = 50;
|
|
11
|
+
const fresh = () => ({ v: 1, token: null, round: null, passAt: 0 });
|
|
12
|
+
const parsed = (value) => {
|
|
13
|
+
try {
|
|
14
|
+
const found = JSON.parse(value ?? "null");
|
|
15
|
+
return found?.v === 1 ? found : null;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
export const contentCursorName = (kind) => `content:${kind}`;
|
|
22
|
+
const passName = (kind) => `content:${kind}:pass`;
|
|
23
|
+
const GAPS = "content:gaps";
|
|
24
|
+
const RESUME = "content:resume";
|
|
25
|
+
const MOVED = "content:moved";
|
|
26
|
+
class BudgetSpent extends Error {
|
|
27
|
+
why;
|
|
28
|
+
constructor(why) {
|
|
29
|
+
super(`the run's budget is spent: ${why}`);
|
|
30
|
+
this.why = why;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
const syncChanges = async (run, kind, result, mode) => {
|
|
34
|
+
const { source, store, account, budget } = run;
|
|
35
|
+
const name = contentCursorName(kind);
|
|
36
|
+
let cursor = parsed((await store.sync.syncState(account, name))?.value) ?? fresh();
|
|
37
|
+
let round = mode.drop
|
|
38
|
+
? { from: null, page: null }
|
|
39
|
+
: (cursor.round ?? { from: mode.full ? null : cursor.token, page: null });
|
|
40
|
+
const gapped = () => run.report.gaps.some((gap) => gap.kind === kind);
|
|
41
|
+
const save = (patch) => {
|
|
42
|
+
cursor = { ...cursor, ...patch };
|
|
43
|
+
return store.sync.setSyncState(account, name, JSON.stringify(cursor));
|
|
44
|
+
};
|
|
45
|
+
const pages = new Set();
|
|
46
|
+
for (;;) {
|
|
47
|
+
result.round = round.from === null ? "full" : "changes";
|
|
48
|
+
const why = budget.take();
|
|
49
|
+
if (why) {
|
|
50
|
+
await save({ round });
|
|
51
|
+
return why;
|
|
52
|
+
}
|
|
53
|
+
run.report.progress.requests += 1;
|
|
54
|
+
const page = await source.changes(kind, round.from, round.page ?? undefined, run.context);
|
|
55
|
+
if (gapped())
|
|
56
|
+
round = { ...round, gapped: true };
|
|
57
|
+
if (run.signal?.aborted) {
|
|
58
|
+
await save({ round });
|
|
59
|
+
return "cancelled";
|
|
60
|
+
}
|
|
61
|
+
if ("reset" in page) {
|
|
62
|
+
if (round.from === null)
|
|
63
|
+
throw new CliError("invalid_response", `${source.provider} refused a full list of ${kind}s`);
|
|
64
|
+
result.reset = true;
|
|
65
|
+
round = { from: null, page: null };
|
|
66
|
+
pages.clear();
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (page.items.length) {
|
|
70
|
+
result.saved += await store.content.save(account, kind, page.items, run.now);
|
|
71
|
+
run.report.progress.saved += page.items.length;
|
|
72
|
+
}
|
|
73
|
+
run.report.progress.steps += 1;
|
|
74
|
+
if (!page.hasMore) {
|
|
75
|
+
// Changes made while a read was refused would be past a new cursor: the next run reads from the old one again.
|
|
76
|
+
await save({ token: round.gapped ? round.from : (page.cursor ?? null), round: null });
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
if (page.nextCursor === undefined)
|
|
80
|
+
throw new CliError("invalid_response", `${source.provider} said there are more ${kind}s but gave no cursor`);
|
|
81
|
+
if (pages.has(page.nextCursor))
|
|
82
|
+
throw new CliError("invalid_response", `${source.provider} gave the same page of ${kind}s twice`);
|
|
83
|
+
pages.add(page.nextCursor);
|
|
84
|
+
round = { ...round, page: page.nextCursor };
|
|
85
|
+
await save({ round });
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Lists every id of the kind and marks deleted each stored row the list lacks. Absence alone is not a deletion: a
|
|
90
|
+
* pass is held when the list is empty, when it would mark most of the kind, when the sign-in could not read all of it,
|
|
91
|
+
* or when the site's address changed. Only a complete list of a site that is still the same one marks anything.
|
|
92
|
+
*/
|
|
93
|
+
const passIds = async (run, kind, result, mode) => {
|
|
94
|
+
const { source, store, account, budget } = run;
|
|
95
|
+
const name = passName(kind);
|
|
96
|
+
const pending = mode.drop ? null : parsed((await store.sync.syncState(account, name))?.value);
|
|
97
|
+
let pass = pending ?? { v: 1, started: run.now, page: null, ids: [] };
|
|
98
|
+
for (;;) {
|
|
99
|
+
const why = budget.take();
|
|
100
|
+
if (why) {
|
|
101
|
+
await store.sync.setSyncState(account, name, JSON.stringify(pass));
|
|
102
|
+
result.pass = "partial";
|
|
103
|
+
return why;
|
|
104
|
+
}
|
|
105
|
+
run.report.progress.requests += 1;
|
|
106
|
+
const page = await source.ids(kind, pass.page ?? undefined, run.context);
|
|
107
|
+
if (run.signal?.aborted) {
|
|
108
|
+
await store.sync.setSyncState(account, name, JSON.stringify(pass));
|
|
109
|
+
result.pass = "partial";
|
|
110
|
+
return "cancelled";
|
|
111
|
+
}
|
|
112
|
+
pass = { ...pass, ids: [...pass.ids, ...page.items] };
|
|
113
|
+
if (run.report.gaps.some((gap) => gap.kind === kind))
|
|
114
|
+
pass = { ...pass, gapped: true };
|
|
115
|
+
if (page.hasMore) {
|
|
116
|
+
if (page.nextCursor === undefined || page.nextCursor === pass.page)
|
|
117
|
+
throw new CliError("invalid_response", `${source.provider} gave no new page of ${kind} ids`);
|
|
118
|
+
pass = { ...pass, page: page.nextCursor };
|
|
119
|
+
await store.sync.setSyncState(account, name, JSON.stringify(pass));
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
const stored = await store.content.count(account, kind);
|
|
123
|
+
const missing = await store.content.unlisted(account, kind, pass.ids, pass.started);
|
|
124
|
+
const unlisted = missing.length;
|
|
125
|
+
const unread = pass.gapped === true || run.report.gaps.some((gap) => gap.kind === kind);
|
|
126
|
+
const moved = (run.report.moved?.length ?? 0) > 0;
|
|
127
|
+
const emptied = pass.ids.length === 0 && unlisted > 0;
|
|
128
|
+
const many = emptied || (stored >= GUARDED_FROM && unlisted > stored * MOST_UNLISTED);
|
|
129
|
+
if (unlisted > 0 && (unread || (moved && !mode.full) || (many && !mode.full))) {
|
|
130
|
+
result.pass = "held";
|
|
131
|
+
result.held = unread
|
|
132
|
+
? `${source.provider} could not read all ${kind}s, so the ${unlisted} it did not list stay; nothing was ` +
|
|
133
|
+
"marked deleted. Check the sign-in's rights, then run sync again"
|
|
134
|
+
: moved
|
|
135
|
+
? `the site's address changed since the last sync, so the ${unlisted} ${kind}s it did not list stay; ` +
|
|
136
|
+
"nothing was marked deleted. If the site moved, run sync --rescan"
|
|
137
|
+
: `${source.provider} listed ${pass.ids.length} ${kind} ids, so ${unlisted} of the ${stored} stored ` +
|
|
138
|
+
"would be marked deleted; nothing was. Check the sign-in's rights, then run sync --rescan to let it through";
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
const why = await confirmGone(run, kind, missing, result);
|
|
142
|
+
if (why) {
|
|
143
|
+
await store.sync.setSyncState(account, name, JSON.stringify(pass));
|
|
144
|
+
result.pass = "partial";
|
|
145
|
+
return why;
|
|
146
|
+
}
|
|
147
|
+
result.pass = "complete";
|
|
148
|
+
}
|
|
149
|
+
await store.sync.setSyncState(account, name, "null");
|
|
150
|
+
const cursor = parsed((await store.sync.syncState(account, contentCursorName(kind)))?.value) ?? fresh();
|
|
151
|
+
await store.sync.setSyncState(account, contentCursorName(kind), JSON.stringify({ ...cursor, passAt: pass.started }));
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
/**
|
|
156
|
+
* A scheduled post whose time has passed may have gone out without a change the source reports: each is read again
|
|
157
|
+
* until it is published. A read that answers no post proves it deleted.
|
|
158
|
+
*/
|
|
159
|
+
const readDue = async (run, result) => {
|
|
160
|
+
const { source, store, account, budget } = run;
|
|
161
|
+
for (const id of (await store.content.due(account, run.now)).slice(0, MOST_DUE)) {
|
|
162
|
+
const why = budget.take();
|
|
163
|
+
if (why)
|
|
164
|
+
return why;
|
|
165
|
+
run.report.progress.requests += 1;
|
|
166
|
+
let post;
|
|
167
|
+
try {
|
|
168
|
+
post = await source.get("post", id, run.context);
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
if (isCliError(error) && error.details.reason === GET_UNSUPPORTED)
|
|
172
|
+
return null;
|
|
173
|
+
throw error;
|
|
174
|
+
}
|
|
175
|
+
if (post)
|
|
176
|
+
result.saved += await store.content.save(account, "post", [post], run.now);
|
|
177
|
+
else if (await store.content.markDeleted(account, "post", id, run.now))
|
|
178
|
+
result.unlisted += 1;
|
|
179
|
+
run.report.due += 1;
|
|
180
|
+
}
|
|
181
|
+
return null;
|
|
182
|
+
};
|
|
183
|
+
const readMetrics = async (run) => {
|
|
184
|
+
const { source, store, account, budget } = run;
|
|
185
|
+
if (!source.traits.metrics || !source.metrics)
|
|
186
|
+
return null;
|
|
187
|
+
const posts = (await store.content.list(account, "post", { statuses: ["published"], limit: 500 })).items.map((one) => one.record.externalId);
|
|
188
|
+
if (!posts.length)
|
|
189
|
+
return null;
|
|
190
|
+
const why = budget.take();
|
|
191
|
+
if (why)
|
|
192
|
+
return why;
|
|
193
|
+
run.report.progress.requests += 1;
|
|
194
|
+
run.report.metrics += await store.content.saveMetrics(account, await source.metrics(posts, run.context));
|
|
195
|
+
return null;
|
|
196
|
+
};
|
|
197
|
+
/**
|
|
198
|
+
* Each id a list lacked, read once more: a list paged by number skips a row when an earlier one goes, so only a read
|
|
199
|
+
* that answers "gone" marks a row deleted. A row read back is saved; one the source cannot read alone is marked by its
|
|
200
|
+
* absence from a complete list, as before.
|
|
201
|
+
*/
|
|
202
|
+
const confirmGone = async (run, kind, missing, result) => {
|
|
203
|
+
const { source, store, account, budget } = run;
|
|
204
|
+
for (const id of missing) {
|
|
205
|
+
const why = budget.take();
|
|
206
|
+
if (why)
|
|
207
|
+
return why;
|
|
208
|
+
run.report.progress.requests += 1;
|
|
209
|
+
let found;
|
|
210
|
+
try {
|
|
211
|
+
found = await source.get(kind, id, run.context);
|
|
212
|
+
}
|
|
213
|
+
catch (error) {
|
|
214
|
+
// WordPress leaves others' drafts out of a contributor's list and refuses to read them, and a row of a status we
|
|
215
|
+
// do not know reads as nothing: neither proves it gone.
|
|
216
|
+
if (isCliError(error) && (error.code === "permission_error" || error.code === "invalid_response")) {
|
|
217
|
+
run.context.gap({
|
|
218
|
+
kind,
|
|
219
|
+
message: `${source.provider} would not give this sign-in every ${kind}: ${error.message}`,
|
|
220
|
+
});
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
if (!isCliError(error) || error.details.reason !== GET_UNSUPPORTED)
|
|
224
|
+
throw error;
|
|
225
|
+
found = null;
|
|
226
|
+
}
|
|
227
|
+
if (found)
|
|
228
|
+
result.saved += await store.content.save(account, kind, [found], run.now);
|
|
229
|
+
else if (await store.content.markDeleted(account, kind, id, run.now))
|
|
230
|
+
result.unlisted += 1;
|
|
231
|
+
}
|
|
232
|
+
return null;
|
|
233
|
+
};
|
|
234
|
+
/**
|
|
235
|
+
* Channels first: a site whose address changed holds every deletion until `sync --rescan`, whichever run comes next. A
|
|
236
|
+
* plain run would otherwise take the new address as the known one and mark the old site's posts deleted.
|
|
237
|
+
*/
|
|
238
|
+
const readChannels = async (run, rescan) => {
|
|
239
|
+
const { source, store, account } = run;
|
|
240
|
+
const before = new Map((await store.content.channels(account)).map((one) => [one.externalId, one]));
|
|
241
|
+
run.report.progress.requests += 1;
|
|
242
|
+
const channels = await source.channels(run.context);
|
|
243
|
+
const moved = channels.flatMap((one) => {
|
|
244
|
+
const was = before.get(one.externalId)?.url;
|
|
245
|
+
return was && one.url && was !== one.url ? [{ channel: one.externalId, from: was, to: one.url }] : [];
|
|
246
|
+
});
|
|
247
|
+
const held = rescan ? [] : (parsed((await store.sync.syncState(account, MOVED))?.value)?.moved ?? []);
|
|
248
|
+
const all = [...held, ...moved];
|
|
249
|
+
if (all.length)
|
|
250
|
+
run.report.moved = all;
|
|
251
|
+
const kept = { v: 1, moved: all };
|
|
252
|
+
await store.sync.setSyncState(account, MOVED, rescan || !all.length ? "null" : JSON.stringify(kept));
|
|
253
|
+
run.report.channels = await store.content.saveChannels(account, channels, run.now);
|
|
254
|
+
};
|
|
255
|
+
const stopping = async (step) => {
|
|
256
|
+
try {
|
|
257
|
+
return await step();
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
if (error instanceof BudgetSpent)
|
|
261
|
+
return error.why;
|
|
262
|
+
throw error;
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
/**
|
|
266
|
+
* Brings one content account's copy up to date: its channels, each kind's changes since its cursor, the scheduled
|
|
267
|
+
* posts whose time has passed, once a day a pass over every id that marks deleted what the source no longer has, and a
|
|
268
|
+
* reading of the published posts' numbers. A run that hits its budget stops where it is, and the next goes on.
|
|
269
|
+
*/
|
|
270
|
+
export const syncContent = async (source, store, account, options = {}) => {
|
|
271
|
+
const now = options.now ?? Date.now();
|
|
272
|
+
const budget = options.budget ?? runBudget();
|
|
273
|
+
const passEvery = options.passEvery ?? DAY;
|
|
274
|
+
const report = {
|
|
275
|
+
provider: source.provider,
|
|
276
|
+
account: account.account,
|
|
277
|
+
channels: 0,
|
|
278
|
+
synced: [],
|
|
279
|
+
due: 0,
|
|
280
|
+
metrics: 0,
|
|
281
|
+
gaps: [],
|
|
282
|
+
complete: true,
|
|
283
|
+
state: "complete",
|
|
284
|
+
progress: { requests: 0, saved: 0, steps: 0 },
|
|
285
|
+
};
|
|
286
|
+
const said = new Set();
|
|
287
|
+
const run = {
|
|
288
|
+
source,
|
|
289
|
+
store,
|
|
290
|
+
account,
|
|
291
|
+
now,
|
|
292
|
+
budget,
|
|
293
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
294
|
+
report,
|
|
295
|
+
context: {
|
|
296
|
+
spend: () => {
|
|
297
|
+
const why = budget.take();
|
|
298
|
+
if (why)
|
|
299
|
+
throw new BudgetSpent(why);
|
|
300
|
+
report.progress.requests += 1;
|
|
301
|
+
},
|
|
302
|
+
gap: (gap) => {
|
|
303
|
+
const key = `${gap.kind} ${gap.message}`;
|
|
304
|
+
if (said.has(key))
|
|
305
|
+
return;
|
|
306
|
+
said.add(key);
|
|
307
|
+
report.gaps.push(gap);
|
|
308
|
+
},
|
|
309
|
+
},
|
|
310
|
+
};
|
|
311
|
+
const fail = (why) => {
|
|
312
|
+
report.complete = false;
|
|
313
|
+
report.state = "partial";
|
|
314
|
+
return why;
|
|
315
|
+
};
|
|
316
|
+
const stop = (why) => {
|
|
317
|
+
report.stopped = why;
|
|
318
|
+
fail(why);
|
|
319
|
+
};
|
|
320
|
+
if (budget.take()) {
|
|
321
|
+
stop("requests");
|
|
322
|
+
return report;
|
|
323
|
+
}
|
|
324
|
+
const kinds = CONTENT_KINDS.filter((one) => source.traits.kinds.includes(one));
|
|
325
|
+
const resumed = options.rescan
|
|
326
|
+
? null
|
|
327
|
+
: parsed((await store.sync.syncState(account, RESUME))?.value);
|
|
328
|
+
const done = new Set(resumed?.done ?? []);
|
|
329
|
+
const mode = { drop: options.rescan === true, full: options.rescan === true || resumed?.rescan === true };
|
|
330
|
+
await readChannels(run, mode.full);
|
|
331
|
+
if (resumed)
|
|
332
|
+
for (const gap of await contentGapsOf(store, account))
|
|
333
|
+
if (done.has(gap.kind)) {
|
|
334
|
+
said.add(`${gap.kind} ${gap.message}`);
|
|
335
|
+
report.gaps.push(gap);
|
|
336
|
+
}
|
|
337
|
+
for (const kind of kinds.filter((one) => !done.has(one))) {
|
|
338
|
+
const result = { kind, round: "full", reset: false, state: "partial", saved: 0, unlisted: 0 };
|
|
339
|
+
report.synced.push(result);
|
|
340
|
+
let stopped;
|
|
341
|
+
try {
|
|
342
|
+
stopped = await stopping(() => syncChanges(run, kind, result, mode));
|
|
343
|
+
if (!stopped && kind === "post")
|
|
344
|
+
stopped = await stopping(() => readDue(run, result));
|
|
345
|
+
const cursor = parsed((await store.sync.syncState(account, contentCursorName(kind)))?.value);
|
|
346
|
+
const pending = parsed((await store.sync.syncState(account, passName(kind)))?.value);
|
|
347
|
+
const due = mode.full || pending !== null || now - (cursor?.passAt ?? 0) >= passEvery;
|
|
348
|
+
if (!stopped && due)
|
|
349
|
+
stopped = await stopping(() => passIds(run, kind, result, mode));
|
|
350
|
+
}
|
|
351
|
+
catch (error) {
|
|
352
|
+
result.error = fail(error instanceof Error ? error.message : String(error));
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
if (stopped) {
|
|
356
|
+
stop(stopped);
|
|
357
|
+
break;
|
|
358
|
+
}
|
|
359
|
+
result.state = "complete";
|
|
360
|
+
done.add(kind);
|
|
361
|
+
}
|
|
362
|
+
if (!report.stopped)
|
|
363
|
+
try {
|
|
364
|
+
const stopped = await stopping(() => readMetrics(run));
|
|
365
|
+
if (stopped)
|
|
366
|
+
stop(stopped);
|
|
367
|
+
}
|
|
368
|
+
catch (error) {
|
|
369
|
+
// Numbers are a reading, not the copy: a source that refuses them leaves the posts synced.
|
|
370
|
+
if (!isCliError(error))
|
|
371
|
+
throw error;
|
|
372
|
+
run.context.gap({ kind: "post", message: `${source.provider} gave no numbers: ${error.message}` });
|
|
373
|
+
}
|
|
374
|
+
await store.sync.setSyncState(account, RESUME, report.stopped ? JSON.stringify({ v: 1, done: [...done], ...(mode.full ? { rescan: true } : {}) }) : "null");
|
|
375
|
+
await store.sync.setSyncState(account, GAPS, JSON.stringify(report.gaps));
|
|
376
|
+
return report;
|
|
377
|
+
};
|
|
378
|
+
/** The gaps the account's last sync recorded; none before its first. */
|
|
379
|
+
export const contentGapsOf = async (store, account) => {
|
|
380
|
+
try {
|
|
381
|
+
const found = JSON.parse((await store.sync.syncState(account, GAPS))?.value ?? "[]");
|
|
382
|
+
return Array.isArray(found) ? found : [];
|
|
383
|
+
}
|
|
384
|
+
catch {
|
|
385
|
+
return [];
|
|
386
|
+
}
|
|
387
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { exampleContentRows, type FakeContentRows, type FakeContentSource, type FakeContentSourceOptions, fakeContentSource, } from "./source.js";
|
|
2
|
+
export { type ContentSourceFaults, type ContentSourceFixture, contentSourceContract, } from "./source-contract.js";
|
|
3
|
+
export { type ContentSyncFixture, contentSyncContract } from "./sync-contract.js";
|
|
4
|
+
export { type ContentWriteFixture, contentWriteContract } from "./write-contract.js";
|