@wirecat/cli-core 0.714.0 → 0.716.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/dist/background/lock.d.ts +7 -0
  3. package/dist/background/lock.js +15 -0
  4. package/dist/cli/account-remove.d.ts +14 -0
  5. package/dist/cli/account-remove.js +2 -2
  6. package/dist/cli/account-rename.d.ts +15 -0
  7. package/dist/cli/account-rename.js +240 -0
  8. package/dist/cli/bot/api.js +2 -1
  9. package/dist/cli/documents/words.d.ts +1 -1
  10. package/dist/cli/index.d.ts +1 -0
  11. package/dist/cli/index.js +1 -0
  12. package/dist/cli/messenger/account-command.js +6 -0
  13. package/dist/cli/messenger/serve-command.js +16 -1
  14. package/dist/cli/messenger/server-command.js +4 -2
  15. package/dist/cli/profile-files.js +1 -0
  16. package/dist/cli/profile-store.d.ts +31 -0
  17. package/dist/cli/profile-store.js +64 -0
  18. package/dist/cli/service-api.js +31 -3
  19. package/dist/content/cli/store.d.ts +4 -0
  20. package/dist/content/cli/store.js +3 -0
  21. package/dist/content/index.d.ts +1 -0
  22. package/dist/content/index.js +1 -0
  23. package/dist/content/manifest/manifest.d.ts +34 -10
  24. package/dist/content/manifest/manifest.js +32 -15
  25. package/dist/content/manifest/source.js +44 -6
  26. package/dist/content/manifest/writer.js +64 -34
  27. package/dist/content/source.d.ts +5 -0
  28. package/dist/content/sync.js +31 -8
  29. package/dist/content/testing/manifest-fake.d.ts +6 -1
  30. package/dist/content/testing/manifest-fake.js +51 -23
  31. package/dist/content/writes.js +2 -1
  32. package/dist/crm/cli/store.d.ts +4 -30
  33. package/dist/crm/cli/store.js +3 -63
  34. package/dist/documents/html-markdown.js +2 -1
  35. package/dist/errors/reasons.js +8 -0
  36. package/dist/search/lucene/types.d.ts +2 -0
  37. package/dist/search/lucene/types.js +8 -0
  38. package/dist/store/sqlite/account-groups.js +18 -2
  39. package/dist/store/sqlite/admin-statistics.js +3 -2
  40. package/dist/store/sqlite/lucene.js +2 -2
  41. package/dist/store/sqlite/migrations.generated.js +2 -2
  42. package/dist/tracker/cli/index.js +9 -3
  43. package/dist/tracker/index.d.ts +1 -1
  44. package/dist/tracker/index.js +1 -1
  45. package/dist/tracker/sync.d.ts +8 -0
  46. package/dist/tracker/sync.js +29 -0
  47. package/dist/tracker/tasks.d.ts +24 -4
  48. package/dist/tracker/tasks.js +164 -18
  49. package/dist/tracker/testing/manifest-fake.js +13 -1
  50. package/dist/tracker/testing/source-contract.js +14 -0
  51. package/dist/tracker/testing/source.d.ts +2 -0
  52. package/dist/tracker/testing/source.js +2 -0
  53. package/package.json +1 -1
  54. package/parity.json +11 -0
@@ -0,0 +1,64 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { isCliError } from "@wirecat/cli-base";
5
+ import { readOnlyLockOf } from "../ports/app.js";
6
+ /**
7
+ * The store a command over one service account reads (a CRM's, a blog's), and the profile's account in it. A read takes
8
+ * the account an earlier run saved, so it never reads the sign-in; the first read of a profile, a store that is missing
9
+ * or needs a migration, and every sync and write open it for writing and save the account (scope work, which the owner
10
+ * may change) and the profile.
11
+ *
12
+ * Under `<PREFIX>_READ_ONLY` a read with no store or no saved profile reads an empty store in a temporary folder, so
13
+ * the lock creates no `wirecat.db`; the folder goes when the store closes. A sync still writes, as a fetch may.
14
+ */
15
+ export const openProfileStore = async (options) => {
16
+ const { app, env, profile, readOnly, open } = options;
17
+ const locked = readOnly && readOnlyLockOf(app, env) !== undefined;
18
+ if (readOnly) {
19
+ const store = await open(env, { readOnly: true }).catch((error) => {
20
+ if (locked && !(isCliError(error) && error.code === "not_found"))
21
+ throw error;
22
+ return undefined;
23
+ });
24
+ if (store) {
25
+ const saved = await store.accounts
26
+ .profiles()
27
+ .then((all) => all[app.command]?.[profile])
28
+ .catch(() => undefined);
29
+ if (saved)
30
+ return { store, account: { provider: saved.provider, account: saved.account } };
31
+ await store.close();
32
+ }
33
+ }
34
+ if (!locked)
35
+ return withProfile(options, env, options.account());
36
+ const folder = mkdtempSync(join(tmpdir(), `${app.command}-empty-`));
37
+ const removing = () => rmSync(folder, { recursive: true, force: true });
38
+ try {
39
+ const empty = await withProfile(options, { ...env, MESSAGING_STORE: join(folder, "wirecat.db") }, {
40
+ provider: options.provider,
41
+ account: profile,
42
+ });
43
+ const close = empty.store.close.bind(empty.store);
44
+ empty.store.close = () => close().finally(removing);
45
+ return empty;
46
+ }
47
+ catch (error) {
48
+ removing();
49
+ throw error;
50
+ }
51
+ };
52
+ const withProfile = async ({ app, profile, open }, env, account) => {
53
+ const store = await open(env);
54
+ try {
55
+ // An account already stored keeps the scope the owner gave it.
56
+ await store.accounts.saveAccount(account, { name: null, scope: "work" });
57
+ await store.accounts.saveProfile(app.command, profile, account);
58
+ return { store, account };
59
+ }
60
+ catch (error) {
61
+ await store.close();
62
+ throw error;
63
+ }
64
+ };
@@ -263,11 +263,36 @@ const serviceApiCore = (options) => {
263
263
  renderer.warn(`permissions name ${former}, the old key of api ${pathOf(operation)}: rename it to ${keyOf(operation)}`);
264
264
  return operation.effect === "read" && level !== "deny" && level !== "ask" ? [] : [former];
265
265
  };
266
- return { operations, left, baseUrlOf, defaults, exchange, formerKeys, operationOf, readsFreely, signed, write };
266
+ /**
267
+ * The refusal `execute` would give, before the body is read: a `deny` stops a call whatever its input, and a missing
268
+ * body must not answer `validation_error` in its place. Only the keys known without the body; the rest, and an old
269
+ * flat key (which warns), wait for `execute`.
270
+ */
271
+ const refuseBeforeBody = (command, operation) => {
272
+ const extra = permissionsOf(operation)
273
+ .filter((permission) => whenOf(permission) === undefined)
274
+ .map(({ key }) => key);
275
+ if (operation.effect === "read" && extra.length === 0)
276
+ return;
277
+ guardOf(command, extra).refuse({ chatId: null, kind: "edit", key: keyOf(operation), operationId: newOperationId() });
278
+ };
279
+ return {
280
+ operations,
281
+ left,
282
+ baseUrlOf,
283
+ defaults,
284
+ exchange,
285
+ formerKeys,
286
+ operationOf,
287
+ readsFreely,
288
+ refuseBeforeBody,
289
+ signed,
290
+ write,
291
+ };
267
292
  };
268
293
  export const serviceApiCommand = (options) => {
269
294
  const { app, configuration } = options;
270
- const { operations, baseUrlOf, exchange, formerKeys, operationOf, readsFreely, signed, write } = serviceApiCore(options);
295
+ const { operations, baseUrlOf, exchange, formerKeys, operationOf, readsFreely, refuseBeforeBody, signed, write } = serviceApiCore(options);
271
296
  const send = async (command, operation, request) => (await exchange(command, operation, request)).answer;
272
297
  let schemas;
273
298
  const loaded = () => {
@@ -331,6 +356,7 @@ export const serviceApiCommand = (options) => {
331
356
  const generated = generatedApiCommand({
332
357
  operations,
333
358
  checkParameter: (name, schema, raw) => checkApiParameter(name, schema, raw, loaded()),
359
+ before: refuseBeforeBody,
334
360
  checkBody: (operation, text) => checkApiBody(operation, text, loaded()),
335
361
  readBody: (command, body) => {
336
362
  if (body.bodyFile !== undefined)
@@ -389,7 +415,9 @@ export const serviceApiCommand = (options) => {
389
415
  const schema = operation.request?.schema ? definitions[operation.request.schema] : undefined;
390
416
  renderAnswer(this, outputFor(this), itemOf({ operation, ...options.shown, ...(schema ? { request_schema: schema } : {}) }));
391
417
  });
392
- const group = annotate(new Command("api"), { effects: NO_EFFECTS }).description(`the raw ${options.service} API, one command per operation of its OpenAPI document`);
418
+ const graphql = operations.length > 0 && operations.every((one) => one.binding.kind === "graphql");
419
+ const described = graphql ? "GraphQL schema" : "OpenAPI document";
420
+ const group = annotate(new Command("api"), { effects: NO_EFFECTS }).description(`the raw ${options.service} API, one command per operation of its ${described}`);
393
421
  group.addCommand(list).addCommand(show);
394
422
  for (const child of [...generated.commands])
395
423
  group.addCommand(child);
@@ -0,0 +1,4 @@
1
+ import { openProfileStore, type ProfileStoreOptions } from "../../cli/profile-store.js";
2
+ export type ContentStoreOptions = ProfileStoreOptions;
3
+ /** The store a content command reads, and the profile's account in it (`openProfileStore`). */
4
+ export declare const openContentStore: typeof openProfileStore;
@@ -0,0 +1,3 @@
1
+ import { openProfileStore } from "../../cli/profile-store.js";
2
+ /** The store a content command reads, and the profile's account in it (`openProfileStore`). */
3
+ export const openContentStore = openProfileStore;
@@ -1,5 +1,6 @@
1
1
  export { CHANNEL_KINDS, type ChannelKind, CONTENT_KINDS, type ContentAuthor, type ContentChannel, type ContentKind, type ContentMedia, type ContentMetric, type ContentPost, type ContentRecords, type ContentTerm, POST_STATUSES, POST_TYPES, type PostStatus, type PostType, TERM_KINDS, type TermKind, } from "../domain/content.js";
2
2
  export { addContentCommands, type ContentCommandOptions, type ContentRun } from "./cli/index.js";
3
+ export { type ContentStoreOptions, openContentStore } from "./cli/store.js";
3
4
  export * from "./manifest/index.js";
4
5
  export type { ContentCallContext, ContentChanges, ContentGap, ContentIdPage, ContentPage, ContentSource, ContentSourceTraits, } from "./source.js";
5
6
  export { GET_UNSUPPORTED } from "./source.js";
@@ -1,5 +1,6 @@
1
1
  export { CHANNEL_KINDS, CONTENT_KINDS, POST_STATUSES, POST_TYPES, TERM_KINDS, } from "../domain/content.js";
2
2
  export { addContentCommands } from "./cli/index.js";
3
+ export { openContentStore } from "./cli/store.js";
3
4
  export * from "./manifest/index.js";
4
5
  export { GET_UNSUPPORTED } from "./source.js";
5
6
  export { contentCursorName, contentGapsOf, syncContent, } from "./sync.js";
@@ -40,7 +40,9 @@ export interface ContentManifestEntity {
40
40
  * The sign-in may be refused this call (a role without the right): a gap with this text, and the rest syncs. A
41
41
  * source that leaves rows out without an error names `requires`: a read whose value at `check` is true when the
42
42
  * sign-in sees every row; false or missing is the same gap. A source that refuses the call outright to a role names
43
- * `needs`: unless its `check` is true the call is never sent, and the gap says its own `message`.
43
+ * `needs`: unless its `check` is true the call is never sent, and the gap says its own `message`. A source that
44
+ * answers a simpler form of a refused call names `fallback`: the same calls with these query values over their own
45
+ * (WordPress: `context=view` for a role that may not edit users), and the gap says its `message`.
44
46
  */
45
47
  optional?: {
46
48
  message: string;
@@ -50,27 +52,49 @@ export interface ContentManifestEntity {
50
52
  message: string;
51
53
  scope?: string;
52
54
  };
55
+ fallback?: ContentFallback;
53
56
  };
54
57
  }
58
+ /** The simpler form of a kind's calls, sent once the first was refused; it reads part of the rows, or fewer fields. */
59
+ export interface ContentFallback {
60
+ query: Readonly<Record<string, string | number | boolean>>;
61
+ message: string;
62
+ scope?: string;
63
+ }
55
64
  /** A read of the sign-in's rights, true at `check` when it has the right (WordPress: `users/me`'s capabilities). */
56
65
  export type ContentRightsCall = CrmOperationCall & {
57
66
  check: string;
58
67
  };
59
- /** A post's writes, as calls and values over the update call. `"{id}"` and `"{at}"` are filled by the engine. */
68
+ /** Where each of our fields goes in a write's body, a dotted path (`title.raw`); `terms` by the term's kind. */
69
+ export interface ContentWriteFields {
70
+ title?: string;
71
+ body?: string;
72
+ excerpt?: string;
73
+ slug?: string;
74
+ terms?: Partial<Record<(typeof TERM_KINDS)[number], string>>;
75
+ }
76
+ /** The calls that write one type of post. */
77
+ export interface ContentTypeWrites {
78
+ create: CrmOperationCall;
79
+ update: CrmOperationCall;
80
+ trash: CrmOperationCall;
81
+ /** Deleting for good, past the trash; absent, the source has no such write. */
82
+ delete?: CrmOperationCall;
83
+ /** Absent, the post's own `fields`. */
84
+ fields?: ContentWriteFields;
85
+ }
86
+ /**
87
+ * A post's writes, as calls and values over the update call. `"{id}"` and `"{at}"` are filled by the engine. A page is
88
+ * written by `page`'s calls, with the same publish, schedule and unpublish values; absent, pages are not written.
89
+ */
60
90
  export interface ContentManifestWrites {
61
91
  create: CrmOperationCall;
62
92
  update: CrmOperationCall;
63
93
  trash: CrmOperationCall;
64
94
  /** Deleting for good, past the trash; absent, the source has no such write. */
65
95
  delete?: CrmOperationCall;
66
- /** Where each of our fields goes in a write's body, a dotted path (`title.raw`); `terms` by the term's kind. */
67
- fields: {
68
- title?: string;
69
- body?: string;
70
- excerpt?: string;
71
- slug?: string;
72
- terms?: Partial<Record<(typeof TERM_KINDS)[number], string>>;
73
- };
96
+ fields: ContentWriteFields;
97
+ page?: ContentTypeWrites;
74
98
  /** Body values over `update` that publish now, schedule at `"{at}"` (ISO in UTC), and bring back to a draft. */
75
99
  publish: Readonly<Record<string, unknown>>;
76
100
  schedule: Readonly<Record<string, unknown>>;
@@ -15,6 +15,13 @@ const call = v.strictObject({
15
15
  items: v.optional(path),
16
16
  });
17
17
  const format = v.picklist(BODY_FORMATS);
18
+ const writeFields = v.strictObject({
19
+ title: v.optional(v.string()),
20
+ body: v.optional(v.string()),
21
+ excerpt: v.optional(v.string()),
22
+ slug: v.optional(v.string()),
23
+ terms: v.optional(v.record(v.picklist(TERM_KINDS), v.optional(v.string()))),
24
+ });
18
25
  const entity = v.strictObject({
19
26
  list: call,
20
27
  changes: v.optional(v.strictObject({
@@ -36,6 +43,11 @@ const entity = v.strictObject({
36
43
  message: v.pipe(v.string(), v.minLength(1)),
37
44
  scope: v.optional(v.string()),
38
45
  })),
46
+ fallback: v.optional(v.strictObject({
47
+ query: v.record(v.string(), v.union([v.string(), v.number(), v.boolean()])),
48
+ message: v.pipe(v.string(), v.minLength(1)),
49
+ scope: v.optional(v.string()),
50
+ })),
39
51
  })),
40
52
  });
41
53
  const schema = v.strictObject({
@@ -49,13 +61,14 @@ const schema = v.strictObject({
49
61
  update: call,
50
62
  trash: call,
51
63
  delete: v.optional(call),
52
- fields: v.strictObject({
53
- title: v.optional(v.string()),
54
- body: v.optional(v.string()),
55
- excerpt: v.optional(v.string()),
56
- slug: v.optional(v.string()),
57
- terms: v.optional(v.record(v.picklist(TERM_KINDS), v.optional(v.string()))),
58
- }),
64
+ fields: writeFields,
65
+ page: v.optional(v.strictObject({
66
+ create: call,
67
+ update: call,
68
+ trash: call,
69
+ delete: v.optional(call),
70
+ fields: v.optional(writeFields),
71
+ })),
59
72
  publish: v.record(v.string(), v.unknown()),
60
73
  schedule: v.record(v.string(), v.unknown()),
61
74
  unpublish: v.record(v.string(), v.unknown()),
@@ -130,14 +143,18 @@ export const parseContentManifest = (input, api) => {
130
143
  if (writes) {
131
144
  if (!manifest.entities.post?.some((one) => one.get))
132
145
  throw invalid("writes", "a write checks the post's version first, and no post entity has a get");
133
- for (const name of ["create", "update", "trash", "delete"]) {
134
- const one = writes[name];
135
- if (!one)
136
- continue;
137
- checkCall(`writes.${name}`, one, false);
138
- if (name !== "create" && !holds([one.path, one.query], "{id}"))
139
- throw invalid(`writes.${name}`, 'no "{id}" in its path or query');
140
- }
146
+ for (const [where, calls] of [
147
+ ["writes", writes],
148
+ ["writes.page", writes.page],
149
+ ])
150
+ for (const name of ["create", "update", "trash", "delete"]) {
151
+ const one = calls?.[name];
152
+ if (!one)
153
+ continue;
154
+ checkCall(`${where}.${name}`, one, false);
155
+ if (name !== "create" && !holds([one.path, one.query], "{id}"))
156
+ throw invalid(`${where}.${name}`, 'no "{id}" in its path or query');
157
+ }
141
158
  if (!holds(writes.schedule, "{at}"))
142
159
  throw invalid("writes.schedule", 'no "{at}" for the time it goes out');
143
160
  }
@@ -65,7 +65,13 @@ const pageOf = (page, now) => {
65
65
  const token = dot < 0 ? undefined : head.slice(dot + 1) || undefined;
66
66
  return Number.isSafeInteger(call) && call >= 0 ? { call, token, started } : { call: -1, token: undefined, started };
67
67
  };
68
+ /**
69
+ * A right the role lacks is a lasting gap only where each row the list leaves out can be read by its id: there a 404
70
+ * proves a row gone. A kind without that read keeps the gap a refusal, which holds its deletions.
71
+ */
72
+ const lastingOf = (entity) => (entity.get ? { lasting: true } : {});
68
73
  const gone = (error) => isCliError(error) && error.code === "not_found";
74
+ const forbidden = (error) => isCliError(error) && (error.code === "permission_error" || error.details.inner_status === 403);
69
75
  // A service may refuse a role with a 400 whose details say 403 (WordPress, for a status the role may not read).
70
76
  const refused = (error) => isCliError(error) &&
71
77
  (error.code === "permission_error" || error.code === "not_found" || error.details.inner_status === 403);
@@ -157,7 +163,12 @@ export const contentSourceFromManifest = (input, options) => {
157
163
  const checkRights = async (kind, entity, send, context) => {
158
164
  const { needs, requires } = entity.optional ?? {};
159
165
  if (needs && !(await has(needs, send))) {
160
- context?.gap({ kind, message: needs.message, ...(needs.scope ? { scope: needs.scope } : {}) });
166
+ context?.gap({
167
+ kind,
168
+ message: needs.message,
169
+ ...(needs.scope ? { scope: needs.scope } : {}),
170
+ ...lastingOf(entity),
171
+ });
161
172
  return false;
162
173
  }
163
174
  if (requires && !(await has(requires, send)))
@@ -165,9 +176,35 @@ export const contentSourceFromManifest = (input, options) => {
165
176
  kind,
166
177
  message: entity.optional?.message ?? "",
167
178
  ...(entity.optional?.scope ? { scope: entity.optional.scope } : {}),
179
+ ...lastingOf(entity),
168
180
  });
169
181
  return true;
170
182
  };
183
+ const simpler = new Set();
184
+ /** The call as this sign-in is answered: in its `fallback` form once the first form was refused. */
185
+ const formOf = (entity, call) => {
186
+ const fallback = entity.optional?.fallback;
187
+ return fallback && simpler.has(entity) ? { ...call, query: { ...call.query, ...fallback.query } } : call;
188
+ };
189
+ /** Sends a read of the entity; refused, once more in its simpler form, which is a gap of its own. */
190
+ const reading = async (kind, entity, read, context) => {
191
+ try {
192
+ return await read();
193
+ }
194
+ catch (error) {
195
+ const fallback = entity.optional?.fallback;
196
+ if (!fallback || simpler.has(entity) || !forbidden(error))
197
+ throw error;
198
+ simpler.add(entity);
199
+ context?.gap({
200
+ kind,
201
+ message: fallback.message,
202
+ ...(fallback.scope ? { scope: fallback.scope } : {}),
203
+ ...lastingOf(entity),
204
+ });
205
+ return read();
206
+ }
207
+ };
171
208
  const gapOf = (kind, entity, error, context) => {
172
209
  if (!entity.optional || !refused(error))
173
210
  return false;
@@ -205,9 +242,9 @@ export const contentSourceFromManifest = (input, options) => {
205
242
  try {
206
243
  read = !(await checkRights(kind, entity, send, context))
207
244
  ? { rows: [], next: undefined }
208
- : changes?.keyset && since !== null
209
- ? await keysetPage({ ...changes, keyset: changes.keyset }, spot.token === undefined ? since - overlap : Number(spot.token), send)
210
- : await readPage(changes ?? entity.list, changes && since !== null ? { since: SINCE[changes.since](since - overlap) } : {}, spot.token, send);
245
+ : await reading(kind, entity, () => changes?.keyset && since !== null
246
+ ? keysetPage(formOf(entity, { ...changes, keyset: changes.keyset }), spot.token === undefined ? since - overlap : Number(spot.token), send)
247
+ : readPage(formOf(entity, changes ?? entity.list), changes && since !== null ? { since: SINCE[changes.since](since - overlap) } : {}, spot.token, send), context);
211
248
  }
212
249
  catch (error) {
213
250
  if (!gapOf(kind, entity, error, context))
@@ -233,7 +270,7 @@ export const contentSourceFromManifest = (input, options) => {
233
270
  const send = metered(context);
234
271
  try {
235
272
  read = (await checkRights(kind, entity, send, context))
236
- ? await readPage(entity.ids ?? entity.list, {}, spot.token, send)
273
+ ? await reading(kind, entity, () => readPage(formOf(entity, entity.ids ?? entity.list), {}, spot.token, send), context)
237
274
  : { rows: [], next: undefined };
238
275
  }
239
276
  catch (error) {
@@ -260,8 +297,9 @@ export const contentSourceFromManifest = (input, options) => {
260
297
  if (!entity.get)
261
298
  continue;
262
299
  let answer;
300
+ const get = entity.get;
263
301
  try {
264
- answer = await send(entity.get.operation, inputOf(entity.get, { id: externalId }));
302
+ answer = await reading(kind, entity, () => send(get.operation, inputOf(formOf(entity, get), { id: externalId })), context);
265
303
  }
266
304
  catch (error) {
267
305
  // A post and a page share one id space; a 404 from one call may be the other's row.
@@ -5,8 +5,14 @@ import { contentConflict } from "../writer.js";
5
5
  import { parseContentManifest } from "./manifest.js";
6
6
  import { mapContentRecord, postBodyOf } from "./map.js";
7
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.
8
+ // A manifest without `writes.page` reads pages, and they are written in the source's own editor.
9
9
  const pagesUnwritten = () => new CliError("validation_error", "this CLI writes posts, not pages", { reason: "content.write-unsupported" });
10
+ const mapType = (entity) => {
11
+ const rule = entity.map.type;
12
+ return rule && typeof rule === "object" && "value" in rule ? rule.value : "post";
13
+ };
14
+ /** `posts.delete.force` → `delete.force`: the action, whatever route it is on. */
15
+ const actionOf = (key) => key.slice(key.indexOf(".") + 1);
10
16
  const iso = (ms) => `${new Date(ms).toISOString().slice(0, 19)}Z`;
11
17
  /**
12
18
  * A `ContentWriter` from the manifest's `writes`. Each write reads the post first: an old version is a conflict, and a
@@ -17,20 +23,36 @@ export const contentWriterFromManifest = (input, options) => {
17
23
  const writes = manifest.writes;
18
24
  if (!writes)
19
25
  throw new CliError("configuration_error", "the source manifest has no writes");
20
- const [entity] = manifest.entities.post ?? [];
21
- if (!entity)
26
+ const entities = manifest.entities.post ?? [];
27
+ const [first] = entities;
28
+ if (!first)
22
29
  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) => {
30
+ const callsOf = (type) => {
31
+ if (type === undefined || type === "post")
32
+ return writes;
33
+ if (!writes.page)
34
+ throw pagesUnwritten();
35
+ return { ...writes.page, fields: writes.page.fields ?? writes.fields };
36
+ };
37
+ const postOf = async (answer, type) => {
25
38
  const raw = crmValues.isRaw(answer) && crmValues.isRaw(answer.previous) && answer.deleted === true ? null : answer;
26
39
  if (!crmValues.isRaw(raw))
27
40
  return null;
28
- const post = mapContentRecord("post", entity.map, raw);
41
+ // Posts and pages map alike but for their type: the answer is read by the entity of the type written.
42
+ for (const entity of entities) {
43
+ const post = mapContentRecord("post", entity.map, raw);
44
+ if (post && (post.type ?? "post") === type)
45
+ return Object.assign(post, { channel: SITE_CHANNEL }, await postBodyOf(entity, raw));
46
+ }
47
+ const post = mapContentRecord("post", first.map, raw);
29
48
  if (!post)
30
49
  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));
50
+ return Object.assign(post, { channel: SITE_CHANNEL }, await postBodyOf(first, raw));
32
51
  };
33
- const bodyOf = async (fields) => {
52
+ const bodyOf = async (fields, type) => {
53
+ const to = callsOf(type).fields;
54
+ const entity = entities.find((one) => mapType(one) === type) ?? first;
55
+ const html = entity.body !== undefined && entity.body.format !== "markdown";
34
56
  const out = {};
35
57
  const put = (path, value) => {
36
58
  const keys = path.split(".");
@@ -43,7 +65,6 @@ export const contentWriterFromManifest = (input, options) => {
43
65
  }
44
66
  inner[last] = value;
45
67
  };
46
- const to = writes.fields;
47
68
  if (fields.title !== undefined && to.title)
48
69
  put(to.title, fields.title ?? "");
49
70
  if (fields.excerpt !== undefined && to.excerpt)
@@ -52,6 +73,10 @@ export const contentWriterFromManifest = (input, options) => {
52
73
  put(to.slug, fields.slug ?? "");
53
74
  if (fields.body !== undefined && to.body)
54
75
  put(to.body, html ? await markdownToHtml(fields.body) : fields.body);
76
+ if (fields.terms?.length && !to.terms)
77
+ throw new CliError("validation_error", `${manifest.provider} takes no tags or categories on a ${type}`, {
78
+ reason: "content.write-unsupported",
79
+ });
55
80
  if (fields.terms !== undefined && to.terms) {
56
81
  const kinds = new Map();
57
82
  for (const term of fields.terms) {
@@ -74,20 +99,25 @@ export const contentWriterFromManifest = (input, options) => {
74
99
  throw new CliError("not_found", `${manifest.provider} has no post ${externalId}; sync, then try again`);
75
100
  if (version != null && found.version != null && found.version !== version)
76
101
  throw contentConflict();
77
- if (found.type === "page")
78
- throw pagesUnwritten();
79
- return found;
102
+ const type = found.type ?? "post";
103
+ return { found, type, calls: callsOf(type) };
80
104
  };
81
105
  const send = async (call, slots, confirmed, body) => {
82
106
  const base = call.body === undefined ? {} : fill(call.body, slots);
83
107
  // The owner said yes to this write in the content command, so its one call is not asked about again; a key that
84
- // command did not ask about, as the publish key for a post that is published at the source now, still is.
85
- const own = options.api.operations.find((one) => one.id === call.operation)?.command;
86
- const { result } = await options.write(options.command, call.operation, inputOf(call, slots, body === undefined && call.body === undefined ? undefined : { ...base, ...body }), !confirmed?.length ? [] : [...confirmed, ...(own === undefined ? [] : [`api.${own}`])]);
108
+ // command did not ask about, as the publish key for a post that is published at the source now, still is. A page's
109
+ // call checks its own route's keys (`pages.publish`): the one for the action the owner said yes to goes with it.
110
+ const operation = options.api.operations.find((one) => one.id === call.operation);
111
+ const route = (operation?.permissions ?? [])
112
+ .map((one) => one.key)
113
+ .filter((key) => confirmed?.some((yes) => actionOf(yes) === actionOf(key)) && !confirmed.includes(key));
114
+ const { result } = await options.write(options.command, call.operation, inputOf(call, slots, body === undefined && call.body === undefined ? undefined : { ...base, ...body }), !confirmed?.length
115
+ ? []
116
+ : [...confirmed, ...route, ...(operation?.command === undefined ? [] : [`api.${operation.command}`])]);
87
117
  return result;
88
118
  };
89
- const updated = async (externalId, body, confirmed) => {
90
- const post = await postOf(await send(writes.update, { id: externalId }, confirmed, body));
119
+ const updated = async ({ type, calls }, externalId, body, confirmed) => {
120
+ const post = await postOf(await send(calls.update, { id: externalId }, confirmed, body), type);
91
121
  if (!post)
92
122
  throw new CliError("invalid_response", `${manifest.provider} answered an update with no post`);
93
123
  return post;
@@ -95,42 +125,42 @@ export const contentWriterFromManifest = (input, options) => {
95
125
  return {
96
126
  provider: manifest.provider,
97
127
  async createDraft(draft, options_) {
98
- if (draft.type === "page")
99
- throw pagesUnwritten();
100
- const post = await postOf(await send(writes.create, {}, options_.confirmed, await bodyOf(draft)));
128
+ const type = draft.type ?? "post";
129
+ const calls = callsOf(type);
130
+ const post = await postOf(await send(calls.create, {}, options_.confirmed, await bodyOf(draft, type)), type);
101
131
  if (!post)
102
132
  throw new CliError("invalid_response", `${manifest.provider} answered a create with no post`);
103
133
  return post;
104
134
  },
105
135
  async update(externalId, patch, options_) {
106
- await current(externalId, options_);
107
- return updated(externalId, await bodyOf(patch), options_.confirmed);
136
+ const now = await current(externalId, options_);
137
+ return updated(now, externalId, await bodyOf(patch, now.type), options_.confirmed);
108
138
  },
109
139
  async publish(externalId, options_) {
110
- const found = await current(externalId, options_);
111
- if (found.status === "published")
112
- return found;
113
- return updated(externalId, { ...writes.publish }, options_.confirmed);
140
+ const now = await current(externalId, options_);
141
+ if (now.found.status === "published")
142
+ return now.found;
143
+ return updated(now, externalId, { ...writes.publish }, options_.confirmed);
114
144
  },
115
145
  async schedule(externalId, when, options_) {
116
- await current(externalId, options_);
117
- return updated(externalId, fill(writes.schedule, { at: iso(when) }), options_.confirmed);
146
+ const now = await current(externalId, options_);
147
+ return updated(now, externalId, fill(writes.schedule, { at: iso(when) }), options_.confirmed);
118
148
  },
119
149
  async unpublish(externalId, options_) {
120
- await current(externalId, options_);
121
- return updated(externalId, { ...writes.unpublish }, options_.confirmed);
150
+ const now = await current(externalId, options_);
151
+ return updated(now, externalId, { ...writes.unpublish }, options_.confirmed);
122
152
  },
123
153
  async trash(externalId, options_) {
124
- await current(externalId, options_);
154
+ const { type, calls } = await current(externalId, options_);
125
155
  if (options_.force) {
126
- if (!writes.delete)
156
+ if (!calls.delete)
127
157
  throw new CliError("validation_error", `${manifest.provider} takes no deletion past the trash`, {
128
158
  reason: "content.write-unsupported",
129
159
  });
130
- await send(writes.delete, { id: externalId }, options_.confirmed);
160
+ await send(calls.delete, { id: externalId }, options_.confirmed);
131
161
  return null;
132
162
  }
133
- return postOf(await send(writes.trash, { id: externalId }, options_.confirmed));
163
+ return postOf(await send(calls.trash, { id: externalId }, options_.confirmed), type);
134
164
  },
135
165
  };
136
166
  };
@@ -26,6 +26,11 @@ export interface ContentGap {
26
26
  kind: ContentKind;
27
27
  message: string;
28
28
  scope?: string;
29
+ /**
30
+ * A right the sign-in's role lacks, the same each run: what it reads is whole for what it may see. The cursor moves
31
+ * on, and a row a complete id list lacks is read once more by its id, so only a source's "gone" deletes it.
32
+ */
33
+ lasting?: true;
29
34
  }
30
35
  export interface ContentCallContext {
31
36
  /** Takes one request from the run's budget for each request beyond the first; throws once it is spent. */