@wirecat/cli-core 0.691.0 → 0.692.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 +8 -0
- package/README.md +142 -204
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/documents/folders.js +1 -1
- package/dist/cli/documents/search.js +3 -3
- package/dist/cli/documents/words.d.ts +3 -1
- package/dist/cli/documents/words.js +1 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +1 -0
- package/dist/cli/service-api-call.d.ts +26 -0
- package/dist/cli/service-api-call.js +34 -0
- package/dist/cli/service-api-manifest.d.ts +4 -0
- package/dist/cli/service-api-manifest.js +1 -1
- package/dist/crm/index.d.ts +2 -0
- package/dist/crm/index.js +2 -0
- package/dist/crm/manifest/manifest.d.ts +176 -0
- package/dist/crm/manifest/manifest.js +156 -0
- package/dist/crm/manifest/map.d.ts +53 -0
- package/dist/crm/manifest/map.js +234 -0
- package/dist/crm/manifest/source.d.ts +18 -0
- package/dist/crm/manifest/source.js +314 -0
- package/dist/errors/reasons.js +1 -0
- package/dist/services/metadata.d.ts +1 -1
- package/package.json +2 -1
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
2
|
+
import { nextPage, parameterValue, withValue } from "../../cli/service-api-manifest.js";
|
|
3
|
+
import { id, isRaw, number, rawsOf, text } from "../values.js";
|
|
4
|
+
import { parseCrmManifest, } from "./manifest.js";
|
|
5
|
+
import { at, convert, evaluate, MISSING, mapFields, mapRecord, selectedOf } from "./map.js";
|
|
6
|
+
const OVERLAP_MS = 10 * 60_000;
|
|
7
|
+
/** How far one read of every page goes: a service that never stops paging must not hold a sync forever. */
|
|
8
|
+
const MOST_PAGES = 500;
|
|
9
|
+
const DROP = Symbol("drop");
|
|
10
|
+
/** Fills `"{since}"`, `"{select}"` and `"{id}"`; an empty select drops the parameter it stands for. */
|
|
11
|
+
const fill = (value, slots) => {
|
|
12
|
+
if (value === "{since}")
|
|
13
|
+
return slots.since ?? DROP;
|
|
14
|
+
if (value === "{select}")
|
|
15
|
+
return slots.select?.length ? [...slots.select] : DROP;
|
|
16
|
+
if (value === "{id}")
|
|
17
|
+
return slots.id ?? DROP;
|
|
18
|
+
if (Array.isArray(value))
|
|
19
|
+
return value.map((one) => fill(one, slots)).filter((one) => one !== DROP);
|
|
20
|
+
if (isRaw(value))
|
|
21
|
+
return Object.fromEntries(Object.entries(value).flatMap(([key, one]) => {
|
|
22
|
+
const filled = fill(one, slots);
|
|
23
|
+
return filled === DROP ? [] : [[key, filled]];
|
|
24
|
+
}));
|
|
25
|
+
return value;
|
|
26
|
+
};
|
|
27
|
+
const inputOf = (call, slots) => {
|
|
28
|
+
const path = fill(call.path ?? {}, slots);
|
|
29
|
+
const query = fill(call.query ?? {}, slots);
|
|
30
|
+
const body = call.body === undefined ? undefined : fill(call.body, slots);
|
|
31
|
+
return {
|
|
32
|
+
path: Object.fromEntries(Object.entries(path).map(([key, one]) => [key, String(one)])),
|
|
33
|
+
query: Object.fromEntries(Object.entries(query).map(([key, one]) => [key, Array.isArray(one) ? one.join(",") : String(one)])),
|
|
34
|
+
headers: {},
|
|
35
|
+
fields: {},
|
|
36
|
+
...(body === undefined || body === DROP ? {} : { body: JSON.stringify(body) }),
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
const SINCE = {
|
|
40
|
+
ms: (ms) => String(ms),
|
|
41
|
+
seconds: (ms) => String(Math.floor(ms / 1000)),
|
|
42
|
+
iso: (ms) => new Date(ms).toISOString(),
|
|
43
|
+
datetime: (ms) => new Date(ms).toISOString().slice(0, 19).replace("T", " "),
|
|
44
|
+
};
|
|
45
|
+
const pageParameter = (pagination) => pagination.style === "cursor"
|
|
46
|
+
? pagination.cursor
|
|
47
|
+
: pagination.style === "offset"
|
|
48
|
+
? pagination.offset
|
|
49
|
+
: pagination.style === "page"
|
|
50
|
+
? pagination.page
|
|
51
|
+
: undefined;
|
|
52
|
+
/** `<the service's page token>@<when the round started>`: a round spread over runs ends with its first page's time. */
|
|
53
|
+
const pageOf = (page, now) => {
|
|
54
|
+
const cut = page?.lastIndexOf("@") ?? -1;
|
|
55
|
+
const started = Number(page?.slice(cut + 1));
|
|
56
|
+
if (page === undefined || cut < 0 || !Number.isSafeInteger(started))
|
|
57
|
+
return { token: undefined, started: now };
|
|
58
|
+
return { token: page.slice(0, cut) || undefined, started };
|
|
59
|
+
};
|
|
60
|
+
const unseen = (error) => isCliError(error) && (error.code === "not_found" || error.code === "permission_error");
|
|
61
|
+
/**
|
|
62
|
+
* A `CrmSource` read from a manifest: every kind listed and read for changes by the operations it names, paged by each
|
|
63
|
+
* operation's own `pagination`, each row mapped onto the shared schema. Deletions are found by a pass over every id.
|
|
64
|
+
* What the manifest cannot say comes from `hooks`.
|
|
65
|
+
*/
|
|
66
|
+
export const crmSourceFromManifest = (input, options) => {
|
|
67
|
+
const manifest = parseCrmManifest(input, options.api);
|
|
68
|
+
const now = options.now ?? Date.now;
|
|
69
|
+
const hooks = options.hooks ?? {};
|
|
70
|
+
const overlap = manifest.overlapMs ?? OVERLAP_MS;
|
|
71
|
+
const operations = new Map(options.api.operations.map((one) => [one.id, one]));
|
|
72
|
+
/** The engine paid for a call's first request; each further one is spent from the run's budget. */
|
|
73
|
+
const metered = (context) => {
|
|
74
|
+
let paid = false;
|
|
75
|
+
return (operation, request) => {
|
|
76
|
+
if (paid)
|
|
77
|
+
context?.spend();
|
|
78
|
+
paid = true;
|
|
79
|
+
return options.call(operation, request);
|
|
80
|
+
};
|
|
81
|
+
};
|
|
82
|
+
/** One page: its rows, and the service's token for the next one, absent on the last. */
|
|
83
|
+
const readPage = async (call, slots, token, send) => {
|
|
84
|
+
const pagination = operations.get(call.operation)?.pagination;
|
|
85
|
+
const parameter = pagination && pageParameter(pagination);
|
|
86
|
+
let request = inputOf(call, slots);
|
|
87
|
+
if (token !== undefined && parameter)
|
|
88
|
+
request = withValue(request, parameter, pagination.style === "cursor" ? token : Number(token));
|
|
89
|
+
const answer = await send(call.operation, request);
|
|
90
|
+
if (!pagination || !parameter) {
|
|
91
|
+
const listed = call.items === undefined ? answer : at(answer, call.items);
|
|
92
|
+
return { rows: rawsOf(listed), next: undefined };
|
|
93
|
+
}
|
|
94
|
+
const step = nextPage(pagination, request, answer);
|
|
95
|
+
const rows = rawsOf(call.items === undefined ? step.items : at(answer, call.items));
|
|
96
|
+
const value = step.next && "input" in step.next ? parameterValue(step.next.input, parameter) : undefined;
|
|
97
|
+
return { rows, next: value === undefined || value === null ? undefined : String(value) };
|
|
98
|
+
};
|
|
99
|
+
const readAll = async (call, send) => {
|
|
100
|
+
const rows = [];
|
|
101
|
+
let token;
|
|
102
|
+
for (let read = 0; read < MOST_PAGES; read += 1) {
|
|
103
|
+
const page = await readPage(call, {}, token, send);
|
|
104
|
+
for (const row of page.rows)
|
|
105
|
+
rows.push(row);
|
|
106
|
+
if (page.next === undefined)
|
|
107
|
+
return rows;
|
|
108
|
+
token = page.next;
|
|
109
|
+
}
|
|
110
|
+
throw new CliError("provider_error", `${call.operation} gave more than ${MOST_PAGES} pages`);
|
|
111
|
+
};
|
|
112
|
+
const entityOf = (kind) => {
|
|
113
|
+
const found = manifest.entities[kind];
|
|
114
|
+
if (!found)
|
|
115
|
+
throw new CliError("configuration_error", `the source manifest has no ${kind}`);
|
|
116
|
+
return found;
|
|
117
|
+
};
|
|
118
|
+
const loaded = new Map();
|
|
119
|
+
/** A sign-in without the right to read field definitions still syncs its records, with no custom values. */
|
|
120
|
+
const fieldsOf = (kind, send, context) => {
|
|
121
|
+
const spec = manifest.fields?.[kind];
|
|
122
|
+
if (!spec)
|
|
123
|
+
return Promise.resolve([]);
|
|
124
|
+
let found = loaded.get(kind);
|
|
125
|
+
if (!found) {
|
|
126
|
+
found = readAll(spec.call, send)
|
|
127
|
+
.then((rows) => rows.flatMap((raw) => toField(spec, raw) ?? []))
|
|
128
|
+
.catch((error) => {
|
|
129
|
+
if (isCliError(error) && error.code === "permission_error") {
|
|
130
|
+
context?.gap({
|
|
131
|
+
kind,
|
|
132
|
+
message: `the service refused the ${kind} field definitions: no custom values are read`,
|
|
133
|
+
});
|
|
134
|
+
return [];
|
|
135
|
+
}
|
|
136
|
+
loaded.delete(kind);
|
|
137
|
+
throw error;
|
|
138
|
+
});
|
|
139
|
+
loaded.set(kind, found);
|
|
140
|
+
}
|
|
141
|
+
return found;
|
|
142
|
+
};
|
|
143
|
+
const selectOf = (kind, defined) => {
|
|
144
|
+
const entity = entityOf(kind);
|
|
145
|
+
if (!entity.select)
|
|
146
|
+
return [];
|
|
147
|
+
const custom = entity.custom?.from === entity.select.from ? defined.map(({ code }) => code) : [];
|
|
148
|
+
return [...new Set([...selectedOf(entity.map, entity.select.from), ...custom, ...(entity.select.also ?? [])])];
|
|
149
|
+
};
|
|
150
|
+
const mapped = async (kind, rows, defined, send) => {
|
|
151
|
+
const entity = entityOf(kind);
|
|
152
|
+
const after = hooks.after?.[kind];
|
|
153
|
+
const records = [];
|
|
154
|
+
for (const raw of rows) {
|
|
155
|
+
const record = mapRecord(kind, entity, raw, defined);
|
|
156
|
+
if (record !== null)
|
|
157
|
+
records.push(after ? await after(record, raw, { call: send }) : record);
|
|
158
|
+
}
|
|
159
|
+
return records;
|
|
160
|
+
};
|
|
161
|
+
/**
|
|
162
|
+
* One page of a change read sorted by modified time: the next page starts at the last row's time, or further along
|
|
163
|
+
* the same time when the whole page shares it. A service's own page token is an offset into a list that moves when
|
|
164
|
+
* a row changes mid-round, and would skip the row behind it. Past `cap`, only a full list reads them all.
|
|
165
|
+
*/
|
|
166
|
+
const keysetPage = async (changes, slots, since, token, send) => {
|
|
167
|
+
const [fromText, offsetText] = (token ?? "").split(".");
|
|
168
|
+
const from = token === undefined ? since : Number(fromText);
|
|
169
|
+
const offset = token === undefined ? 0 : Number(offsetText);
|
|
170
|
+
if (!Number.isSafeInteger(from) || !Number.isSafeInteger(offset))
|
|
171
|
+
return { reset: true };
|
|
172
|
+
const { rows, next } = await readPage(changes, { ...slots, since: SINCE[changes.since](from) }, offset ? String(offset) : undefined, send);
|
|
173
|
+
if (next === undefined)
|
|
174
|
+
return { rows, next: undefined };
|
|
175
|
+
const last = convert("epoch", at(rows.at(-1), changes.keyset.field));
|
|
176
|
+
const spot = typeof last === "number" && last > from ? { from: last, offset: 0 } : { from, offset: offset + rows.length };
|
|
177
|
+
if (changes.keyset.cap !== undefined && spot.offset + rows.length > changes.keyset.cap)
|
|
178
|
+
return { reset: true };
|
|
179
|
+
return { rows, next: `${spot.from}.${spot.offset}` };
|
|
180
|
+
};
|
|
181
|
+
const base = {
|
|
182
|
+
provider: manifest.provider,
|
|
183
|
+
traits: { kinds: manifest.kinds, removedInChanges: false },
|
|
184
|
+
async pipelines(kind, context) {
|
|
185
|
+
const spec = manifest.pipelines?.[kind];
|
|
186
|
+
if (!spec)
|
|
187
|
+
return [];
|
|
188
|
+
const rows = await readAll(spec.call, metered(context));
|
|
189
|
+
return rows.flatMap((raw) => toPipeline(spec, raw) ?? []);
|
|
190
|
+
},
|
|
191
|
+
async changes(kind, cursor, page, context) {
|
|
192
|
+
const entity = entityOf(kind);
|
|
193
|
+
const since = cursor === null ? null : Date.parse(cursor);
|
|
194
|
+
if (since !== null && Number.isNaN(since))
|
|
195
|
+
return { reset: true };
|
|
196
|
+
const { token, started } = pageOf(page, now());
|
|
197
|
+
const send = metered(context);
|
|
198
|
+
const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
|
|
199
|
+
const changes = since !== null ? entity.changes : undefined;
|
|
200
|
+
const slots = { select: selectOf(kind, defined) };
|
|
201
|
+
const read = changes?.keyset && since !== null
|
|
202
|
+
? await keysetPage({ ...changes, keyset: changes.keyset }, slots, since - overlap, token, send)
|
|
203
|
+
: await readPage(changes ?? entity.list, changes && since !== null ? { ...slots, since: SINCE[changes.since](since - overlap) } : slots, token, send);
|
|
204
|
+
if ("reset" in read)
|
|
205
|
+
return { reset: true };
|
|
206
|
+
const { rows, next } = read;
|
|
207
|
+
const items = await mapped(kind, rows, defined, send);
|
|
208
|
+
return next === undefined
|
|
209
|
+
? { items, hasMore: false, cursor: new Date(started).toISOString() }
|
|
210
|
+
: { items, hasMore: true, nextCursor: `${next}@${started}` };
|
|
211
|
+
},
|
|
212
|
+
async ids(kind, page, context) {
|
|
213
|
+
const entity = entityOf(kind);
|
|
214
|
+
const { rows, next } = await readPage(entity.ids ?? entity.list, {}, page, metered(context));
|
|
215
|
+
const items = rows.flatMap((raw) => {
|
|
216
|
+
const found = evaluate(entity.map.externalId, raw);
|
|
217
|
+
const externalId = found === MISSING ? null : id(found);
|
|
218
|
+
return externalId === null ? [] : [externalId];
|
|
219
|
+
});
|
|
220
|
+
return next === undefined ? { items, hasMore: false } : { items, hasMore: true, nextCursor: next };
|
|
221
|
+
},
|
|
222
|
+
async get(kind, externalId, context) {
|
|
223
|
+
const entity = entityOf(kind);
|
|
224
|
+
if (!entity.get)
|
|
225
|
+
return null;
|
|
226
|
+
const send = metered(context);
|
|
227
|
+
const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
|
|
228
|
+
let answer;
|
|
229
|
+
try {
|
|
230
|
+
answer = await send(entity.get.operation, inputOf(entity.get, { id: externalId, select: selectOf(kind, defined) }));
|
|
231
|
+
}
|
|
232
|
+
catch (error) {
|
|
233
|
+
if (unseen(error))
|
|
234
|
+
return null;
|
|
235
|
+
throw error;
|
|
236
|
+
}
|
|
237
|
+
const raw = entity.get.items === undefined ? answer : at(answer, entity.get.items);
|
|
238
|
+
return isRaw(raw) ? ((await mapped(kind, [raw], defined, send))[0] ?? null) : null;
|
|
239
|
+
},
|
|
240
|
+
...(manifest.fields
|
|
241
|
+
? { fields: (kind, context) => fieldsOf(kind, metered(context), context) }
|
|
242
|
+
: {}),
|
|
243
|
+
...(manifest.users
|
|
244
|
+
? {
|
|
245
|
+
async users(context) {
|
|
246
|
+
const spec = manifest.users;
|
|
247
|
+
const rows = await readAll(spec.call, metered(context));
|
|
248
|
+
const users = rows.flatMap((raw) => {
|
|
249
|
+
const user = mapFields(spec.map, { externalId: "id", name: "text", email: "text", position: "text", active: "bool" }, raw);
|
|
250
|
+
return typeof user.externalId === "string" ? [user] : [];
|
|
251
|
+
});
|
|
252
|
+
return [...new Map(users.map((user) => [user.externalId, user])).values()];
|
|
253
|
+
},
|
|
254
|
+
}
|
|
255
|
+
: {}),
|
|
256
|
+
};
|
|
257
|
+
return { ...base, ...hooks.extend?.(base) };
|
|
258
|
+
};
|
|
259
|
+
const outcomeOf = (spec, stage, pipeline) => {
|
|
260
|
+
if (typeof spec === "function")
|
|
261
|
+
return spec(stage, pipeline);
|
|
262
|
+
if ("value" in spec)
|
|
263
|
+
return spec.value;
|
|
264
|
+
const found = text(at(stage, spec.path)) ?? "";
|
|
265
|
+
if (spec.won?.includes(found))
|
|
266
|
+
return "won";
|
|
267
|
+
return spec.lost?.includes(found) ? "lost" : "open";
|
|
268
|
+
};
|
|
269
|
+
const toPipeline = (spec, raw) => {
|
|
270
|
+
const { externalId, name } = mapFields(spec.map, { externalId: "id", name: "text" }, raw);
|
|
271
|
+
if (typeof externalId !== "string")
|
|
272
|
+
return null;
|
|
273
|
+
return {
|
|
274
|
+
externalId,
|
|
275
|
+
name: typeof name === "string" ? name : externalId,
|
|
276
|
+
stages: rawsOf(at(raw, spec.stages.each)).flatMap((stage, place) => {
|
|
277
|
+
const found = mapFields(spec.stages.map, { externalId: "id", name: "text", position: "text" }, stage);
|
|
278
|
+
if (typeof found.externalId !== "string")
|
|
279
|
+
return [];
|
|
280
|
+
return [
|
|
281
|
+
{
|
|
282
|
+
externalId: found.externalId,
|
|
283
|
+
name: typeof found.name === "string" ? found.name : found.externalId,
|
|
284
|
+
position: number(found.position) ?? place,
|
|
285
|
+
outcome: outcomeOf(spec.stages.outcome, stage, raw),
|
|
286
|
+
},
|
|
287
|
+
];
|
|
288
|
+
}),
|
|
289
|
+
};
|
|
290
|
+
};
|
|
291
|
+
const toField = (spec, raw) => {
|
|
292
|
+
if (spec.keep && !spec.keep(raw))
|
|
293
|
+
return null;
|
|
294
|
+
const { options: optionsRule, ...rules } = spec.map;
|
|
295
|
+
const found = mapFields(rules, { code: "text", label: "text", type: "text", multiple: "bool", filterable: "bool" }, raw);
|
|
296
|
+
if (typeof found.code !== "string")
|
|
297
|
+
return null;
|
|
298
|
+
const options = typeof optionsRule === "function"
|
|
299
|
+
? optionsRule(raw)
|
|
300
|
+
: optionsRule === undefined
|
|
301
|
+
? undefined
|
|
302
|
+
: rawsOf(at(raw, optionsRule.each)).flatMap((one) => {
|
|
303
|
+
const option = convert("text", at(one, optionsRule.id));
|
|
304
|
+
return typeof option === "string" ? [{ id: option, label: text(at(one, optionsRule.label)) ?? option }] : [];
|
|
305
|
+
});
|
|
306
|
+
return {
|
|
307
|
+
code: found.code,
|
|
308
|
+
label: typeof found.label === "string" ? found.label : null,
|
|
309
|
+
type: typeof found.type === "string" ? found.type : "string",
|
|
310
|
+
multiple: found.multiple === true,
|
|
311
|
+
filterable: found.filterable !== false,
|
|
312
|
+
...(options?.length ? { options: [...new Map(options.map((one) => [one.id, one])).values()] } : {}),
|
|
313
|
+
};
|
|
314
|
+
};
|
package/dist/errors/reasons.js
CHANGED
|
@@ -62,6 +62,7 @@ const PROVIDER_API = [
|
|
|
62
62
|
["offline.refused", "permission_error", "this command needs the provider; --offline was given"],
|
|
63
63
|
validation("api.unknown-method", "the provider has no method by this name"),
|
|
64
64
|
["api.disabled", "configuration_error", "the provider's API is turned off for this OAuth project"],
|
|
65
|
+
["manifest.invalid", "configuration_error", "the source manifest does not match its shape or the generated API"],
|
|
65
66
|
["provider.usage-limit", "rate_limited", "the account's usage limit at the provider is reached; wait, do not retry"],
|
|
66
67
|
["access.denied", "permission_error", "the provider refused this account access to the item"],
|
|
67
68
|
["item.not-found", "not_found", "the provider has no item by this id, or this account cannot see it"],
|
|
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
|
|
|
14
14
|
dryRun?: boolean;
|
|
15
15
|
}) => Promise<{
|
|
16
16
|
items: ({
|
|
17
|
-
error?: undefined;
|
|
18
17
|
chatId: string;
|
|
19
18
|
tags: import("../domain/channel-tags.js").ChannelTagMatch[];
|
|
20
19
|
algorithm: string;
|
|
21
20
|
fetchedAt: string | null;
|
|
22
21
|
source: string;
|
|
22
|
+
error?: undefined;
|
|
23
23
|
} | {
|
|
24
24
|
tags?: undefined;
|
|
25
25
|
algorithm?: undefined;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.692.0",
|
|
4
4
|
"description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Viacheslav Ptsarev",
|
|
@@ -239,6 +239,7 @@
|
|
|
239
239
|
"search:docs": "pnpm build && node scripts/search-docs.ts",
|
|
240
240
|
"check:agent-process": "pnpm build && node --experimental-strip-types scripts/check-agent-process.ts",
|
|
241
241
|
"standards:check": "node config/wirecat/check.mjs",
|
|
242
|
+
"docs:images": "node docs/images/src/render.ts",
|
|
242
243
|
"docs:lint": "markdownlint-cli2",
|
|
243
244
|
"docs:spell": "cspell lint --config cspell.json --no-progress README.md",
|
|
244
245
|
"ci:quick": "pnpm typecheck && vitest run src/cli/command-lint.test.ts",
|