@wirecat/cli-core 0.668.0 → 0.670.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 +125 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/documents/catalog.js +3 -14
- package/dist/cli/documents/sync.d.ts +21 -5
- package/dist/cli/documents/sync.js +39 -8
- package/dist/cli/documents/testing/source-contract.d.ts +9 -0
- package/dist/cli/documents/testing/source-contract.js +12 -0
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/store-settings.js +5 -3
- package/dist/crm/cli/csv.d.ts +1 -1
- package/dist/crm/cli/csv.js +2 -2
- package/dist/crm/cli/index.d.ts +11 -1
- package/dist/crm/cli/index.js +11 -5
- package/dist/crm/cli/records.d.ts +94 -0
- package/dist/crm/cli/records.js +412 -0
- package/dist/crm/foreign-contacts.d.ts +34 -0
- package/dist/crm/foreign-contacts.js +104 -0
- package/dist/crm/index.d.ts +9 -3
- package/dist/crm/index.js +7 -1
- package/dist/crm/provider-call.d.ts +23 -0
- package/dist/crm/provider-call.js +49 -0
- package/dist/crm/query.d.ts +32 -0
- package/dist/crm/query.js +122 -0
- package/dist/crm/source.d.ts +41 -4
- package/dist/crm/sync.d.ts +1 -1
- package/dist/crm/sync.js +13 -7
- package/dist/crm/testing/source-contract.d.ts +5 -0
- package/dist/crm/testing/source-contract.js +39 -0
- package/dist/crm/testing/source.d.ts +9 -3
- package/dist/crm/testing/source.js +109 -10
- package/dist/crm/testing/write-contract.d.ts +2 -2
- package/dist/crm/testing/write-contract.js +41 -2
- package/dist/crm/values.d.ts +33 -0
- package/dist/crm/values.js +75 -0
- package/dist/crm/walk.d.ts +18 -0
- package/dist/crm/walk.js +23 -0
- package/dist/crm/writer.d.ts +41 -6
- package/dist/crm/writer.js +16 -10
- package/dist/crm/writes.d.ts +38 -2
- package/dist/crm/writes.js +163 -9
- package/dist/documents/model.d.ts +4 -0
- package/dist/domain/crm.d.ts +41 -5
- package/dist/entities/deal.d.ts +8 -2
- package/dist/entities/deal.js +4 -1
- package/dist/errors/reasons.js +23 -2
- package/dist/oauth/index.d.ts +1 -1
- package/dist/oauth/index.js +1 -1
- package/dist/oauth/keeper.js +4 -0
- package/dist/oauth/storage.d.ts +21 -0
- package/dist/oauth/storage.js +32 -1
- package/dist/services/documents/ingestion.d.ts +3 -0
- package/dist/services/documents/ingestion.js +9 -2
- package/dist/services/documents/plan.d.ts +16 -1
- package/dist/services/documents/plan.js +163 -103
- package/dist/services/documents/ports.d.ts +13 -0
- package/dist/services/documents/sync.d.ts +11 -0
- package/dist/services/documents/sync.js +41 -3
- package/dist/services/metadata.d.ts +1 -1
- package/dist/store/sqlite/catalog.d.ts +2 -1
- package/dist/store/sqlite/catalog.js +4 -1
- package/dist/store/sqlite/crm-contacts.d.ts +5 -4
- package/dist/store/sqlite/crm-contacts.js +8 -4
- package/dist/store/sqlite/crm-rows.d.ts +1 -0
- package/dist/store/sqlite/crm-rows.js +37 -7
- package/dist/store/sqlite/crm-settings.d.ts +2 -2
- package/dist/store/sqlite/crm-settings.js +4 -3
- package/dist/store/sqlite/crm.d.ts +5 -3
- package/dist/store/sqlite/crm.js +20 -3
- package/dist/store/sqlite/note-search.d.ts +10 -1
- package/dist/store/sqlite/note-search.js +35 -1
- package/package.json +1 -1
package/dist/entities/deal.d.ts
CHANGED
|
@@ -56,7 +56,10 @@ export declare const deal: v.StrictObjectSchema<{
|
|
|
56
56
|
readonly external_id: v.NullableSchema<v.StringSchema<undefined>, undefined>;
|
|
57
57
|
/** A CRM copy's assignee, the identity `<account>/user/<id>`. */
|
|
58
58
|
readonly assignee: v.NullableSchema<v.StringSchema<undefined>, undefined>;
|
|
59
|
-
/**
|
|
59
|
+
/**
|
|
60
|
+
* A CRM copy's own fields by code; a list field's value is its option's label, `option_id` its id. `amount_note` is
|
|
61
|
+
* WireCat's own note, not a CRM field: the CRM's amount the store could not keep, and why.
|
|
62
|
+
*/
|
|
60
63
|
readonly provider_metadata: v.RecordSchema<v.StringSchema<undefined>, v.StrictObjectSchema<{
|
|
61
64
|
readonly label: v.NullableSchema<v.StringSchema<undefined>, undefined>;
|
|
62
65
|
readonly value: v.UnknownSchema;
|
|
@@ -129,7 +132,10 @@ export declare const lead: v.StrictObjectSchema<{
|
|
|
129
132
|
readonly external_id: v.NullableSchema<v.StringSchema<undefined>, undefined>;
|
|
130
133
|
/** A CRM copy's assignee, the identity `<account>/user/<id>`. */
|
|
131
134
|
readonly assignee: v.NullableSchema<v.StringSchema<undefined>, undefined>;
|
|
132
|
-
/**
|
|
135
|
+
/**
|
|
136
|
+
* A CRM copy's own fields by code; a list field's value is its option's label, `option_id` its id. `amount_note` is
|
|
137
|
+
* WireCat's own note, not a CRM field: the CRM's amount the store could not keep, and why.
|
|
138
|
+
*/
|
|
133
139
|
readonly provider_metadata: v.RecordSchema<v.StringSchema<undefined>, v.StrictObjectSchema<{
|
|
134
140
|
readonly label: v.NullableSchema<v.StringSchema<undefined>, undefined>;
|
|
135
141
|
readonly value: v.UnknownSchema;
|
package/dist/entities/deal.js
CHANGED
|
@@ -55,7 +55,10 @@ export const deal = v.strictObject({
|
|
|
55
55
|
external_id: nullableText,
|
|
56
56
|
/** A CRM copy's assignee, the identity `<account>/user/<id>`. */
|
|
57
57
|
assignee: nullableText,
|
|
58
|
-
/**
|
|
58
|
+
/**
|
|
59
|
+
* A CRM copy's own fields by code; a list field's value is its option's label, `option_id` its id. `amount_note` is
|
|
60
|
+
* WireCat's own note, not a CRM field: the CRM's amount the store could not keep, and why.
|
|
61
|
+
*/
|
|
59
62
|
provider_metadata: v.record(v.string(), v.strictObject({
|
|
60
63
|
label: v.nullable(v.string()),
|
|
61
64
|
value: v.unknown(),
|
package/dist/errors/reasons.js
CHANGED
|
@@ -29,6 +29,11 @@ const SIGN_IN = [
|
|
|
29
29
|
["oauth.no-response", "outcome_unknown", "the token request did not finish"],
|
|
30
30
|
["oauth.unavailable", "provider_unavailable", "the provider's token endpoint is unavailable"],
|
|
31
31
|
["oauth.expired", "authentication_error", "the provider refused the saved sign-in; sign in again"],
|
|
32
|
+
[
|
|
33
|
+
"oauth.moved-rotating",
|
|
34
|
+
"authentication_error",
|
|
35
|
+
"a run with moved folders cannot refresh a sign-in whose refresh token rotates",
|
|
36
|
+
],
|
|
32
37
|
["oauth.invalid-response", "invalid_response", "the provider's token response could not be used"],
|
|
33
38
|
["oauth.failed", "authentication_error", "the provider returned no offline refresh token"],
|
|
34
39
|
["oauth.revoke-failed", "outcome_unknown", "the provider did not confirm the revoke"],
|
|
@@ -432,16 +437,32 @@ const OTHERS = [
|
|
|
432
437
|
validation("pipeline.field", "a pipeline needs a name and at least one stage, each named once"),
|
|
433
438
|
["pipeline.not-found", "not_found", "no stored pipeline has that name or reference"],
|
|
434
439
|
validation("crm.stage-unknown", "a CRM item stands in a stage the store does not hold; it was not kept"),
|
|
435
|
-
validation("crm.item-invalid", "a CRM item has a field the store refuses, such as a
|
|
440
|
+
validation("crm.item-invalid", "a CRM item has a field the store refuses, such as a status it does not know"),
|
|
441
|
+
validation("crm.amount-unkept", "a CRM deal's amount is in a currency or with decimals the store cannot hold: the deal is kept without it"),
|
|
436
442
|
validation("crm.pipeline-required", "the CRM has more than one pipeline of the kind; the command names one"),
|
|
437
443
|
validation("field.unknown", "no custom field of the kind has that code or label; `fields list` lists them"),
|
|
438
444
|
validation("field.ambiguous", "more than one custom field has that label; name one by its code"),
|
|
439
445
|
validation("field.unknown-option", "the list field has no option with that id or label"),
|
|
446
|
+
validation("crm.record-ambiguous", "more than one contact or company has that name; name one by its id"),
|
|
447
|
+
validation("field.ambiguous-option", "more than one option of the list field has that label; name one by its id"),
|
|
440
448
|
validation("field.unknown-kind", "fields are listed for deals, leads, people and organizations only"),
|
|
449
|
+
[
|
|
450
|
+
"crm.foreign-contacts-spent",
|
|
451
|
+
"permission_error",
|
|
452
|
+
"the day's views of contacts and companies that are not yours are spent",
|
|
453
|
+
],
|
|
454
|
+
[
|
|
455
|
+
"crm.client-reads-admin-only",
|
|
456
|
+
"permission_error",
|
|
457
|
+
"a raw api call that reads contacts or companies is the CRM administrator's",
|
|
458
|
+
],
|
|
459
|
+
validation("field.not-filterable", "the CRM cannot filter a list by that custom field"),
|
|
460
|
+
validation("query.bad-value", "a term's value is not the kind its field takes, such as an id or a number"),
|
|
461
|
+
validation("crm.record-field", "a contact's or company's field is not valid"),
|
|
441
462
|
validation("crm.write-unsupported", "the CRM does not take this write, or does not recognise a repeated one"),
|
|
442
463
|
validation("crm.unlisted-held", "a list of every id would mark most of a kind deleted; nothing was, until --rescan"),
|
|
443
464
|
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"),
|
|
444
|
-
validation("crm.unassigned-dropped", "the CRM does not let this sign-in
|
|
465
|
+
validation("crm.unassigned-dropped", "the CRM does not let this sign-in choose a user in unassigned; that user's deals are not copied"),
|
|
445
466
|
validation("crm.not-reported", "the CRM did not list users or departments; what they would say is unknown, nothing withdrawn"),
|
|
446
467
|
validation("crm.reference-unknown", "a CRM row names a contact, company or user the store does not hold; that link was not made"),
|
|
447
468
|
validation("crm.pending-dropped", "relationships waited too long for an end that never came; they were dropped"),
|
package/dist/oauth/index.d.ts
CHANGED
|
@@ -3,4 +3,4 @@ export { type ClientFileOptions, readClientFile } from "./client-file.js";
|
|
|
3
3
|
export { type SignInOptions, type TokenKeeper, type TokenKeeperOptions, type TokensOptions, tokenKeeper, } from "./keeper.js";
|
|
4
4
|
export { type AppSource, type ExchangeContext, googleProvider, type OAuthClient, type OAuthProvider, type RequestContext, type TokenSet, } from "./provider.js";
|
|
5
5
|
export { requestTokens, revokeToken, TOKEN_LOG_ALLOW, TOKEN_LOG_EVENT } from "./requests.js";
|
|
6
|
-
export { type CredentialStorageOptions, credentialStorage, driveSessionCodec, type EncodeInput, googleTokenCodec, oauthAccount, type StoredTokens, standardCodec, type TokenCodec, type TokenStorage, zoomTokenCodec, } from "./storage.js";
|
|
6
|
+
export { accountTokenCodec, type CredentialStorageOptions, credentialStorage, driveSessionCodec, type EncodeInput, googleTokenCodec, oauthAccount, type StoredTokens, standardCodec, type TokenCodec, type TokenStorage, zoomTokenCodec, } from "./storage.js";
|
package/dist/oauth/index.js
CHANGED
|
@@ -3,4 +3,4 @@ export { readClientFile } from "./client-file.js";
|
|
|
3
3
|
export { tokenKeeper, } from "./keeper.js";
|
|
4
4
|
export { googleProvider, } from "./provider.js";
|
|
5
5
|
export { requestTokens, revokeToken, TOKEN_LOG_ALLOW, TOKEN_LOG_EVENT } from "./requests.js";
|
|
6
|
-
export { credentialStorage, driveSessionCodec, googleTokenCodec, oauthAccount, standardCodec, zoomTokenCodec, } from "./storage.js";
|
|
6
|
+
export { accountTokenCodec, credentialStorage, driveSessionCodec, googleTokenCodec, oauthAccount, standardCodec, zoomTokenCodec, } from "./storage.js";
|
package/dist/oauth/keeper.js
CHANGED
|
@@ -120,6 +120,10 @@ export const tokenKeeper = (options) => {
|
|
|
120
120
|
if (fresh(current.tokens) || current.tokens.refreshToken !== seen.tokens.refreshToken)
|
|
121
121
|
return current.tokens;
|
|
122
122
|
}
|
|
123
|
+
if (storage.moved && storage.rotating)
|
|
124
|
+
throw new CliError("authentication_error", `the sign-in to ${provider.name} needs a refresh, which a run with moved folders never makes: the ` +
|
|
125
|
+
"provider rotates its refresh token, and the owner's own sign-in would keep a dead one; run this in " +
|
|
126
|
+
"the normal run, or sign in again there", { reason: "oauth.moved-rotating" });
|
|
123
127
|
const client = clientOf(current);
|
|
124
128
|
const refreshed = await exchange({ grant_type: "refresh_token", refresh_token: current.tokens.refreshToken }, context(client, current.tokens));
|
|
125
129
|
// A rotated refresh token is saved even so: kept only in memory, it would die with the process.
|
package/dist/oauth/storage.d.ts
CHANGED
|
@@ -4,6 +4,11 @@ export interface StoredTokens {
|
|
|
4
4
|
tokens: TokenSet;
|
|
5
5
|
/** The app the entry was signed in with, when the entry records it; refresh must use that one. */
|
|
6
6
|
client?: OAuthClient;
|
|
7
|
+
/** The account an account-bound entry (`accountTokenCodec`) was signed in to: its base URL and the user's id. */
|
|
8
|
+
account?: {
|
|
9
|
+
host: string;
|
|
10
|
+
userId: string;
|
|
11
|
+
};
|
|
7
12
|
}
|
|
8
13
|
export interface EncodeInput {
|
|
9
14
|
tokens: TokenSet;
|
|
@@ -12,11 +17,15 @@ export interface EncodeInput {
|
|
|
12
17
|
previous?: string;
|
|
13
18
|
/** Fields a CLI adds at sign-in, such as drive's `principal`. */
|
|
14
19
|
extra?: Record<string, unknown>;
|
|
20
|
+
/** A new sign-in, not a refresh: a codec takes the account's fields from `extra` only. */
|
|
21
|
+
signIn?: boolean;
|
|
15
22
|
}
|
|
16
23
|
/** Every failure throws a fixed message: a parser's message would quote the secret. */
|
|
17
24
|
export interface TokenCodec {
|
|
18
25
|
decode(raw: string): StoredTokens;
|
|
19
26
|
encode(input: EncodeInput): string;
|
|
27
|
+
/** The provider gives a new refresh token on every refresh and kills the old one (amoCRM, Kommo). */
|
|
28
|
+
readonly rotating?: boolean;
|
|
20
29
|
}
|
|
21
30
|
export interface TokenStorage {
|
|
22
31
|
/** Names the entry across processes; the lock is keyed by it. */
|
|
@@ -26,6 +35,11 @@ export interface TokenStorage {
|
|
|
26
35
|
* instead of copying the owner's sign-in there. Only a new sign-in is saved.
|
|
27
36
|
*/
|
|
28
37
|
readonly moved?: boolean;
|
|
38
|
+
/**
|
|
39
|
+
* The codec's `rotating`: a moved run then never refreshes, since the rotated token would land in its temporary
|
|
40
|
+
* entry and the owner's own entry would keep a dead one.
|
|
41
|
+
*/
|
|
42
|
+
readonly rotating?: boolean;
|
|
29
43
|
/** Throws when the entry cannot be saved, so a sign-in fails before the browser, not after consent. */
|
|
30
44
|
probe(): void;
|
|
31
45
|
read(): StoredTokens | undefined;
|
|
@@ -46,6 +60,13 @@ export declare const driveSessionCodec: TokenCodec;
|
|
|
46
60
|
* client file is read only at sign-in. A client without a secret drops the one the profile signed in with before.
|
|
47
61
|
*/
|
|
48
62
|
export declare const googleTokenCodec: TokenCodec;
|
|
63
|
+
/**
|
|
64
|
+
* An entry bound to one CRM account through the owner's own app (Bitrix24's local application, a Kommo
|
|
65
|
+
* integration): the standard entry plus the owner's client secret, which every refresh needs, the account's base URL
|
|
66
|
+
* (`host`) and the signed-in user's id. A sign-in passes `host` and `userId` as `extra`; a refresh keeps them, and
|
|
67
|
+
* saves a rotated refresh token. A moved run's writes go to its temporary entry (`credentialStorage`).
|
|
68
|
+
*/
|
|
69
|
+
export declare const accountTokenCodec: (providerId: string) => TokenCodec;
|
|
49
70
|
/** zm's entry as zoom-cli writes it today: `{accessToken, refreshToken, expiresAt, scopes}`, all four required. */
|
|
50
71
|
export declare const zoomTokenCodec: TokenCodec;
|
|
51
72
|
export interface CredentialStorageOptions {
|
package/dist/oauth/storage.js
CHANGED
|
@@ -142,6 +142,36 @@ export const googleTokenCodec = {
|
|
|
142
142
|
return JSON.stringify(entry);
|
|
143
143
|
},
|
|
144
144
|
};
|
|
145
|
+
/**
|
|
146
|
+
* An entry bound to one CRM account through the owner's own app (Bitrix24's local application, a Kommo
|
|
147
|
+
* integration): the standard entry plus the owner's client secret, which every refresh needs, the account's base URL
|
|
148
|
+
* (`host`) and the signed-in user's id. A sign-in passes `host` and `userId` as `extra`; a refresh keeps them, and
|
|
149
|
+
* saves a rotated refresh token. A moved run's writes go to its temporary entry (`credentialStorage`).
|
|
150
|
+
*/
|
|
151
|
+
export const accountTokenCodec = (providerId) => {
|
|
152
|
+
const standard = standardCodec(providerId);
|
|
153
|
+
return {
|
|
154
|
+
rotating: true,
|
|
155
|
+
decode: (raw) => {
|
|
156
|
+
const stored = standard.decode(raw);
|
|
157
|
+
const value = parse(raw);
|
|
158
|
+
const clientSecret = text(value.clientSecret);
|
|
159
|
+
const host = text(value.host);
|
|
160
|
+
const userId = text(value.userId);
|
|
161
|
+
if (!host || !userId || !clientSecret)
|
|
162
|
+
throw invalid();
|
|
163
|
+
return { ...stored, client: { ...stored.client, clientSecret }, account: { host, userId } };
|
|
164
|
+
},
|
|
165
|
+
encode: (input) => {
|
|
166
|
+
const entry = parse(standard.encode(input));
|
|
167
|
+
const from = input.signIn ? (input.extra ?? {}) : entry;
|
|
168
|
+
if (!input.client.clientSecret || typeof from.host !== "string" || typeof from.userId !== "string")
|
|
169
|
+
throw new CliError("configuration_error", "an account-bound sign-in needs the app's secret, its host and user");
|
|
170
|
+
entry.clientSecret = input.client.clientSecret;
|
|
171
|
+
return JSON.stringify(entry);
|
|
172
|
+
},
|
|
173
|
+
};
|
|
174
|
+
};
|
|
145
175
|
/** zm's entry as zoom-cli writes it today: `{accessToken, refreshToken, expiresAt, scopes}`, all four required. */
|
|
146
176
|
export const zoomTokenCodec = {
|
|
147
177
|
decode: (raw) => {
|
|
@@ -218,6 +248,7 @@ export const credentialStorage = (options) => {
|
|
|
218
248
|
return {
|
|
219
249
|
key: `${service}\u0000${account}`,
|
|
220
250
|
moved,
|
|
251
|
+
...(codec.rotating ? { rotating: true } : {}),
|
|
221
252
|
probe: () => {
|
|
222
253
|
raw(account);
|
|
223
254
|
},
|
|
@@ -225,7 +256,7 @@ export const credentialStorage = (options) => {
|
|
|
225
256
|
const value = current();
|
|
226
257
|
return value === undefined ? undefined : codec.decode(value);
|
|
227
258
|
},
|
|
228
|
-
write: (input, writeOptions) => save(codec.encode({ ...input, previous: raw(account) }), writeOptions),
|
|
259
|
+
write: (input, writeOptions) => save(codec.encode({ ...input, previous: raw(account), ...(writeOptions?.signIn ? { signIn: true } : {}) }), writeOptions),
|
|
229
260
|
remove: () => {
|
|
230
261
|
try {
|
|
231
262
|
return credentials.remove(account);
|
|
@@ -28,6 +28,9 @@ export declare const documentIngestion: <M extends SourceFile>(store: Pick<Messa
|
|
|
28
28
|
}>;
|
|
29
29
|
};
|
|
30
30
|
collection: (principal: string, create: boolean) => Promise<import("../../store/index.js").NoteFolder | undefined>;
|
|
31
|
+
settle: ({ until }: {
|
|
32
|
+
until: () => boolean;
|
|
33
|
+
}) => Promise<number>;
|
|
31
34
|
save: (principal: string, content: SourceContent<M>, hash: string) => Promise<string>;
|
|
32
35
|
remove: (principal: string, id: string) => Promise<void>;
|
|
33
36
|
};
|
|
@@ -10,6 +10,8 @@ export const documentIngestion = (store, options) => {
|
|
|
10
10
|
const found = (await store.notes.folders()).find((item) => item.name === name);
|
|
11
11
|
return found ?? (create ? await store.notes.addFolder({ name, format: "markdown" }) : undefined);
|
|
12
12
|
};
|
|
13
|
+
// The catalog answers external ids (`<id>.md`), so an id given back as it was answered is found too.
|
|
14
|
+
const both = (id) => [...new Set([options.externalId(id), id])];
|
|
13
15
|
const stale = async (ref) => {
|
|
14
16
|
for (const status of ["proposed", "confirmed"]) {
|
|
15
17
|
for (let batch = 0;; batch++) {
|
|
@@ -44,7 +46,10 @@ export const documentIngestion = (store, options) => {
|
|
|
44
46
|
},
|
|
45
47
|
get: async (principal, id) => {
|
|
46
48
|
const selected = await folder(principal, false);
|
|
47
|
-
|
|
49
|
+
if (!selected)
|
|
50
|
+
return undefined;
|
|
51
|
+
const entry = await store.catalog.get(selected.id, options.externalId(id));
|
|
52
|
+
return entry ?? (options.externalId(id) === id ? undefined : store.catalog.get(selected.id, id));
|
|
48
53
|
},
|
|
49
54
|
list: async (principal, query = {}) => {
|
|
50
55
|
const selected = await folder(principal, false);
|
|
@@ -57,12 +62,14 @@ export const documentIngestion = (store, options) => {
|
|
|
57
62
|
? store.catalog.list(selected.id, {
|
|
58
63
|
...query,
|
|
59
64
|
...(ast ? { ast } : {}),
|
|
60
|
-
...(query.parent === undefined ? {} : { parent:
|
|
65
|
+
...(query.parent === undefined ? {} : { parent: [query.parent].flat().flatMap(both) }),
|
|
61
66
|
})
|
|
62
67
|
: { items: [], hasMore: false };
|
|
63
68
|
},
|
|
64
69
|
},
|
|
65
70
|
collection: folder,
|
|
71
|
+
// A store fake that predates `indexWritten` leaves the text for the next search to index.
|
|
72
|
+
settle: async ({ until }) => store.notes.indexWritten?.({ until }),
|
|
66
73
|
save: async (principal, content, hash) => {
|
|
67
74
|
const selected = await folder(principal, true);
|
|
68
75
|
if (!selected)
|
|
@@ -7,5 +7,20 @@ interface WalkStore<M extends SourceFile> {
|
|
|
7
7
|
read: (scope: string) => SourceWalk<M> | undefined;
|
|
8
8
|
save: (walk: SourceWalk<M>) => void;
|
|
9
9
|
}
|
|
10
|
-
export
|
|
10
|
+
export type WalkStop = "entries" | "requests" | "deadline" | "cancelled";
|
|
11
|
+
/** A folder walk this call stopped before its end, saved for the next sync to go on from. */
|
|
12
|
+
export interface WalkProgress {
|
|
13
|
+
folders_left: number;
|
|
14
|
+
/** Entries the walk has found over every call so far. */
|
|
15
|
+
entries: number;
|
|
16
|
+
/** Folders this call listed: 0 means it moved nothing on. */
|
|
17
|
+
listed: number;
|
|
18
|
+
stopped: WalkStop;
|
|
19
|
+
}
|
|
20
|
+
export type Plan<M extends SourceFile> = {
|
|
21
|
+
pending: NonNullable<SourceState<M>["pending"]>;
|
|
22
|
+
} | {
|
|
23
|
+
walk: WalkProgress;
|
|
24
|
+
};
|
|
25
|
+
export declare const planDocuments: <M extends SourceFile>(options: SyncOptions<M>, source: DocumentSource<M> | undefined, state: SourceState<M>, roots: string[], limit: number, pictures: boolean, walks?: WalkStore<M>) => Promise<Plan<M>>;
|
|
11
26
|
export {};
|
|
@@ -12,134 +12,78 @@ export const changedSince = (previous, file) => previous.version !== file.versio
|
|
|
12
12
|
previous.canDownload !== file.canDownload ||
|
|
13
13
|
JSON.stringify(previous.parents) !== JSON.stringify(file.parents);
|
|
14
14
|
const SAVE_EVERY_MS = 2000;
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
15
|
+
// A round of changes is saved under its own scope: a CLI that validates the walk file keeps only the fields it knows,
|
|
16
|
+
// and these say both what the walk is and which cursor it started from.
|
|
17
|
+
const changesScope = (scope, cursor) => `${scope}:changes:${cursor}`;
|
|
18
|
+
export const planDocuments = async (options, source, state, roots, limit, pictures, walks) => {
|
|
19
|
+
const { isFolder, skipReason, retryable, maxEntries, errorOf, query, budget } = options;
|
|
18
20
|
const scope = scopeHash(roots, query, options.isDocument !== undefined);
|
|
19
21
|
if (!roots.length && query?.mode !== "include")
|
|
20
22
|
return {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
23
|
+
pending: {
|
|
24
|
+
scope,
|
|
25
|
+
cursor: state.cursor ?? "",
|
|
26
|
+
folders: {},
|
|
27
|
+
skipped: [],
|
|
28
|
+
jobs: Object.keys(state.documents).map((id) => ({ id, kind: "remove" })),
|
|
29
|
+
},
|
|
26
30
|
};
|
|
27
31
|
if (!source)
|
|
28
32
|
throw new CliError("configuration_error", "selected folders or a saved query require an authenticated source");
|
|
29
33
|
if (query?.mode === "include" && !query.list)
|
|
30
34
|
throw new CliError("configuration_error", "a query that includes files must list them");
|
|
31
|
-
// Listed before the walk: a failure here then costs no folder already walked.
|
|
32
|
-
const found = query?.mode === "include" && query.list ? await query.list() : [];
|
|
33
35
|
const initial = !state.cursor || scope !== state.scope;
|
|
34
|
-
const resumed = initial ?
|
|
35
|
-
const cursor = initial ? (resumed?.cursor ?? (await source.startToken())) : state.cursor;
|
|
36
|
+
const resumed = walks?.read(initial ? scope : changesScope(scope, state.cursor));
|
|
36
37
|
const folders = initial ? {} : structuredClone(state.folders);
|
|
37
38
|
const files = new Map(Object.values(state.documents).map((doc) => [doc.metadata.id, doc.metadata]));
|
|
38
39
|
const changed = new Set();
|
|
40
|
+
// What the walk saves: every file of a full walk, or what a round of changes touched, a removed file as trashed.
|
|
41
|
+
const delta = new Map();
|
|
39
42
|
for (const skipped of state.skipped)
|
|
40
43
|
if (skipped.file)
|
|
41
44
|
files.set(skipped.id, skipped.file);
|
|
45
|
+
if (initial)
|
|
46
|
+
files.clear();
|
|
42
47
|
const keep = (file) => {
|
|
43
48
|
files.set(file.id, file);
|
|
44
49
|
changed.add(file.id);
|
|
50
|
+
delta.set(file.id, file);
|
|
51
|
+
};
|
|
52
|
+
const drop = (id) => {
|
|
53
|
+
const known = files.get(id);
|
|
54
|
+
if (known)
|
|
55
|
+
delta.set(id, { ...known, trashed: true });
|
|
56
|
+
files.delete(id);
|
|
45
57
|
};
|
|
46
58
|
const container = (file) => {
|
|
47
59
|
if (options.isDocument?.(file))
|
|
48
60
|
keep(file);
|
|
49
61
|
};
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
const
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
folders[folder.id] = folder;
|
|
59
|
-
for (const file of await source.children(folder.id)) {
|
|
60
|
-
if (++discovered > MAX_ENTRIES)
|
|
61
|
-
throw tooManyEntries();
|
|
62
|
-
if (isFolder(file)) {
|
|
63
|
-
container(file);
|
|
64
|
-
await crawl(file, new Set([...ancestry, folder.id]));
|
|
65
|
-
}
|
|
66
|
-
else
|
|
67
|
-
keep(file);
|
|
68
|
-
}
|
|
69
|
-
};
|
|
70
|
-
let finalCursor = cursor;
|
|
71
|
-
if (initial) {
|
|
72
|
-
files.clear();
|
|
73
|
-
const walk = resumed ?? {
|
|
62
|
+
// A folder the last finished pass walked keeps its subtree: a round lists only its direct children, and the
|
|
63
|
+
// source's changes name what changed below them. A new, restored or moved-in folder is walked in full.
|
|
64
|
+
const walked = (id) => !initial && state.folders[id] !== undefined && !state.folders[id]?.trashed;
|
|
65
|
+
let walk = resumed;
|
|
66
|
+
let cursor = state.cursor ?? "";
|
|
67
|
+
if (!walk && initial) {
|
|
68
|
+
const start = await source.startToken();
|
|
69
|
+
walk = {
|
|
74
70
|
scope,
|
|
75
|
-
cursor,
|
|
71
|
+
cursor: start,
|
|
76
72
|
stack: [...roots].reverse().map((id) => ({ id, ancestry: [] })),
|
|
77
73
|
visited: [],
|
|
78
74
|
folders: {},
|
|
79
75
|
files: [],
|
|
80
76
|
discovered: 0,
|
|
81
77
|
};
|
|
82
|
-
for (const id of walk.visited)
|
|
83
|
-
visited.add(id);
|
|
84
|
-
Object.assign(folders, walk.folders);
|
|
85
|
-
for (const file of walk.files) {
|
|
86
|
-
files.set(file.id, file);
|
|
87
|
-
changed.add(file.id);
|
|
88
|
-
}
|
|
89
|
-
discovered = walk.discovered;
|
|
90
|
-
let savedAt = (options.now ?? Date.now)();
|
|
91
|
-
const record = () => {
|
|
92
|
-
walks?.save({ ...walk, visited: [...visited], folders, files: [...files.values()], discovered });
|
|
93
|
-
savedAt = (options.now ?? Date.now)();
|
|
94
|
-
};
|
|
95
|
-
try {
|
|
96
|
-
for (let step = walk.stack.at(-1); step; step = walk.stack.at(-1)) {
|
|
97
|
-
if (step.ancestry.includes(step.id))
|
|
98
|
-
throw new CliError("invalid_response", "folder traversal contains a cycle");
|
|
99
|
-
if (visited.has(step.id)) {
|
|
100
|
-
walk.stack.pop();
|
|
101
|
-
continue;
|
|
102
|
-
}
|
|
103
|
-
const folder = step.folder ?? (await source.metadata(step.id));
|
|
104
|
-
if (!step.folder && (!isFolder(folder) || folder.trashed))
|
|
105
|
-
throw new CliError("validation_error", "configured root is not an accessible folder");
|
|
106
|
-
if (!step.folder)
|
|
107
|
-
container(folder);
|
|
108
|
-
const children = await source.children(folder.id);
|
|
109
|
-
if (discovered + children.length > MAX_ENTRIES)
|
|
110
|
-
throw tooManyEntries();
|
|
111
|
-
discovered += children.length;
|
|
112
|
-
walk.stack.pop();
|
|
113
|
-
visited.add(folder.id);
|
|
114
|
-
folders[folder.id] = folder;
|
|
115
|
-
const nested = [];
|
|
116
|
-
for (const file of children)
|
|
117
|
-
if (isFolder(file)) {
|
|
118
|
-
container(file);
|
|
119
|
-
nested.push({ id: file.id, ancestry: [...step.ancestry, folder.id], folder: file });
|
|
120
|
-
}
|
|
121
|
-
else
|
|
122
|
-
keep(file);
|
|
123
|
-
for (const entry of nested.reverse())
|
|
124
|
-
walk.stack.push(entry);
|
|
125
|
-
if ((options.now ?? Date.now)() - savedAt > SAVE_EVERY_MS)
|
|
126
|
-
record();
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
catch (error) {
|
|
130
|
-
record();
|
|
131
|
-
throw error;
|
|
132
|
-
}
|
|
133
78
|
}
|
|
134
|
-
else {
|
|
79
|
+
else if (!walk) {
|
|
135
80
|
const page = await source.changes(cursor);
|
|
136
|
-
finalCursor = page.cursor;
|
|
137
81
|
const latest = new Map(page.items.map((change) => [change.id, change]));
|
|
138
82
|
const entering = [];
|
|
139
83
|
// Apply all ancestry changes before classifying document scope.
|
|
140
84
|
for (const change of latest.values()) {
|
|
141
85
|
if (change.removed || change.file?.trashed) {
|
|
142
|
-
|
|
86
|
+
drop(change.id);
|
|
143
87
|
if (folders[change.id])
|
|
144
88
|
folders[change.id] = { ...folders[change.id], trashed: true };
|
|
145
89
|
}
|
|
@@ -171,10 +115,126 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
|
|
|
171
115
|
folders[root] = { ...previous, trashed: true };
|
|
172
116
|
}
|
|
173
117
|
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
118
|
+
const stack = entering
|
|
119
|
+
.filter((folder) => within(folder, roots, folders))
|
|
120
|
+
.reverse()
|
|
121
|
+
.map((folder) => ({ id: folder.id, ancestry: [], folder }));
|
|
122
|
+
if (stack.length)
|
|
123
|
+
walk = {
|
|
124
|
+
scope: changesScope(scope, cursor),
|
|
125
|
+
cursor: page.cursor,
|
|
126
|
+
stack,
|
|
127
|
+
visited: [],
|
|
128
|
+
folders: {},
|
|
129
|
+
files: [],
|
|
130
|
+
discovered: 0,
|
|
131
|
+
};
|
|
132
|
+
else
|
|
133
|
+
cursor = page.cursor;
|
|
177
134
|
}
|
|
135
|
+
const vanished = async (id) => {
|
|
136
|
+
try {
|
|
137
|
+
return (await source.metadata(id)).trashed;
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
return errorOf(error).code === "not_found";
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
let found = [];
|
|
144
|
+
if (walk) {
|
|
145
|
+
const visited = new Set(walk.visited);
|
|
146
|
+
Object.assign(folders, walk.folders);
|
|
147
|
+
for (const file of walk.files) {
|
|
148
|
+
if (file.trashed)
|
|
149
|
+
drop(file.id);
|
|
150
|
+
else
|
|
151
|
+
keep(file);
|
|
152
|
+
}
|
|
153
|
+
cursor = walk.cursor;
|
|
154
|
+
const now = options.now ?? Date.now;
|
|
155
|
+
let savedAt = now();
|
|
156
|
+
const current = walk;
|
|
157
|
+
const record = () => {
|
|
158
|
+
walks?.save({ ...current, visited: [...visited], folders, files: [...delta.values()] });
|
|
159
|
+
savedAt = now();
|
|
160
|
+
};
|
|
161
|
+
let spent = 0;
|
|
162
|
+
let listed = 0;
|
|
163
|
+
let stopped = null;
|
|
164
|
+
try {
|
|
165
|
+
for (let step = walk.stack.at(-1); step; step = walk.stack.at(-1)) {
|
|
166
|
+
if (step.ancestry.includes(step.id))
|
|
167
|
+
throw new CliError("invalid_response", "folder traversal contains a cycle");
|
|
168
|
+
if (visited.has(step.id)) {
|
|
169
|
+
walk.stack.pop();
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
// One folder at least per call, so a folder with more children than the bound still gets listed.
|
|
173
|
+
stopped = listed > 0 && spent >= maxEntries ? "entries" : (budget?.take() ?? null);
|
|
174
|
+
if (stopped)
|
|
175
|
+
break;
|
|
176
|
+
const folder = step.folder ?? (await source.metadata(step.id));
|
|
177
|
+
if (!step.folder && (!isFolder(folder) || folder.trashed))
|
|
178
|
+
throw new CliError("validation_error", "configured root is not an accessible folder");
|
|
179
|
+
if (!step.folder)
|
|
180
|
+
container(folder);
|
|
181
|
+
let children;
|
|
182
|
+
try {
|
|
183
|
+
children = await source.children(folder.id);
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
// Deleted or unshared since the walk saved it: gone, with what is below it, instead of failing every sync.
|
|
187
|
+
// A listing's 404 alone can be passing, so the folder is read again and is gone only when that read is a
|
|
188
|
+
// 404 too or finds it trashed; on any doubt the call fails and the next sync lists it again.
|
|
189
|
+
if (errorOf(error).code !== "not_found" || !(await vanished(folder.id)))
|
|
190
|
+
throw error;
|
|
191
|
+
walk.stack.pop();
|
|
192
|
+
visited.add(folder.id);
|
|
193
|
+
folders[folder.id] = { ...folder, trashed: true };
|
|
194
|
+
drop(folder.id);
|
|
195
|
+
spent++;
|
|
196
|
+
listed++;
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
spent += 1 + children.length;
|
|
200
|
+
listed++;
|
|
201
|
+
walk.discovered += children.length;
|
|
202
|
+
walk.stack.pop();
|
|
203
|
+
visited.add(folder.id);
|
|
204
|
+
folders[folder.id] = folder;
|
|
205
|
+
const nested = [];
|
|
206
|
+
for (const file of children)
|
|
207
|
+
if (isFolder(file)) {
|
|
208
|
+
container(file);
|
|
209
|
+
if (walked(file.id))
|
|
210
|
+
folders[file.id] = file;
|
|
211
|
+
else
|
|
212
|
+
nested.push({ id: file.id, ancestry: [...step.ancestry, folder.id], folder: file });
|
|
213
|
+
}
|
|
214
|
+
else
|
|
215
|
+
keep(file);
|
|
216
|
+
for (const entry of nested.reverse())
|
|
217
|
+
walk.stack.push(entry);
|
|
218
|
+
if (now() - savedAt > SAVE_EVERY_MS)
|
|
219
|
+
record();
|
|
220
|
+
}
|
|
221
|
+
if (stopped) {
|
|
222
|
+
record();
|
|
223
|
+
return {
|
|
224
|
+
walk: { folders_left: walk.stack.length, entries: walk.discovered, listed, stopped },
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
// Listed once the walk is done: a call the walk does not finish would read it for nothing.
|
|
228
|
+
if (query?.mode === "include" && query.list)
|
|
229
|
+
found = await query.list();
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
record();
|
|
233
|
+
throw error;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
else if (query?.mode === "include" && query.list)
|
|
237
|
+
found = await query.list();
|
|
178
238
|
const matched = new Set();
|
|
179
239
|
for (const file of found) {
|
|
180
240
|
if ((isFolder(file) && !options.isDocument?.(file)) ||
|
|
@@ -182,8 +242,6 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
|
|
|
182
242
|
!query?.matches(file) ||
|
|
183
243
|
matched.has(file.id))
|
|
184
244
|
continue;
|
|
185
|
-
if (!files.has(file.id) && ++discovered > MAX_ENTRIES)
|
|
186
|
-
throw tooManyEntries();
|
|
187
245
|
// Listed again on every sync, so only a new or changed file is work; a skipped one keeps its skip.
|
|
188
246
|
const prior = state.documents[file.id]?.metadata ?? state.skipped.find((item) => item.id === file.id)?.file;
|
|
189
247
|
if (initial || !prior || changedSince(prior, file))
|
|
@@ -219,7 +277,7 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
|
|
|
219
277
|
jobs.push({ id, kind: "save", file });
|
|
220
278
|
}
|
|
221
279
|
}
|
|
222
|
-
for (const id of
|
|
280
|
+
for (const id of Object.keys(state.documents)) {
|
|
223
281
|
const file = files.get(id);
|
|
224
282
|
if (!file || !inScope(file, roots, folders, matched, query))
|
|
225
283
|
jobs.push({ id, kind: "remove" });
|
|
@@ -227,11 +285,13 @@ export const planDocuments = async (options, source, state, roots, limit, pictur
|
|
|
227
285
|
// Only retain metadata for selected ancestry; the account-wide feed includes unrelated folders.
|
|
228
286
|
const scopedFolders = Object.fromEntries(Object.entries(folders).filter(([, file]) => within(file, roots, folders) || roots.includes(file.id)));
|
|
229
287
|
return {
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
288
|
+
pending: {
|
|
289
|
+
scope,
|
|
290
|
+
cursor,
|
|
291
|
+
folders: scopedFolders,
|
|
292
|
+
jobs,
|
|
293
|
+
skipped,
|
|
294
|
+
...(query?.mode === "include" ? { matched: [...matched] } : {}),
|
|
295
|
+
},
|
|
236
296
|
};
|
|
237
297
|
};
|