@composable-os/cli 0.1.0-beta.7 → 0.1.0-beta.9

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 (64) hide show
  1. package/dist/accounts-D6N77JGP.js +44 -0
  2. package/dist/{blocks-HVTAQ5W2.js → blocks-4CA4PP3P.js} +4 -4
  3. package/dist/{chunk-X6I2LWB3.js → chunk-2MLAPQU7.js} +1471 -359
  4. package/dist/{chunk-2S7375SC.js → chunk-3MIEYXRY.js} +3 -301
  5. package/dist/chunk-56A6RJIU.js +1040 -0
  6. package/dist/chunk-7CQGMVDO.js +63 -0
  7. package/dist/{chunk-STJZJIRA.js → chunk-7O4F3NU4.js} +1039 -1380
  8. package/dist/chunk-7U3OZLTK.js +1370 -0
  9. package/dist/{chunk-ZRWF6QZS.js → chunk-DU6OIFOU.js} +1 -0
  10. package/dist/chunk-E4WCYTCT.js +347 -0
  11. package/dist/{chunk-E5JLTLRM.js → chunk-GYTEW66E.js} +1 -1
  12. package/dist/chunk-LPD2VR5M.js +284 -0
  13. package/dist/chunk-NDKVIG23.js +2641 -0
  14. package/dist/chunk-NSSUOI3Z.js +333 -0
  15. package/dist/chunk-OV3OFYPI.js +746 -0
  16. package/dist/{chunk-2P4AZTFL.js → chunk-P6YZMS3F.js} +11 -5
  17. package/dist/{chunk-Y7PQ7NIL.js → chunk-RFJOPI42.js} +138 -14
  18. package/dist/{chunk-VL62IMBN.js → chunk-RXRD34QW.js} +10 -8
  19. package/dist/{chunk-BEKL3CA2.js → chunk-STBMGUTM.js} +7065 -4580
  20. package/dist/chunk-VTQNOQGA.js +150 -0
  21. package/dist/chunk-XSE37HK5.js +426 -0
  22. package/dist/{chunk-MINQ46RU.js → chunk-Z52IX5WL.js} +257 -844
  23. package/dist/chunk-ZSR5H4O7.js +552 -0
  24. package/dist/{cli-XHC6QBQW.js → cli-7A5XHYML.js} +16 -9
  25. package/dist/{cli-BRSACHSG.js → cli-T6MJM7TU.js} +20 -8
  26. package/dist/cli.js +4 -4
  27. package/dist/{client-repo-G55G4OLV.js → client-repo-PC4ISVEZ.js} +4 -4
  28. package/dist/create.js +4 -4
  29. package/dist/{fields-64BQJA62.js → fields-L24XAIOA.js} +13 -11
  30. package/dist/invoke-TLYT6CFI.js +33 -0
  31. package/dist/order-IKQBUFCV.js +19 -0
  32. package/dist/{person-AZFEPZOE.js → person-DXEOOH2A.js} +9 -5
  33. package/dist/plan-on-sale-LRCK5MJG.js +24 -0
  34. package/dist/platform/migrations/0510_video_and_file_media.sql +109 -0
  35. package/dist/platform/migrations/0516_order_tax.sql +63 -0
  36. package/dist/platform/migrations/0520_publish_requests.sql +20 -0
  37. package/dist/platform/migrations/0530_subscriptions.sql +173 -0
  38. package/dist/platform/migrations/0531_subscription_trials.sql +56 -0
  39. package/dist/platform/migrations/0532_subscription_offers.sql +80 -0
  40. package/dist/platform/migrations/0533_allowances.sql +262 -0
  41. package/dist/platform/migrations/0560_recurring.sql +75 -0
  42. package/dist/platform/sdk/allowance.ts +508 -0
  43. package/dist/platform/sdk/capacity.ts +89 -0
  44. package/dist/platform/sdk/contract.ts +97 -1
  45. package/dist/platform/sdk/document.ts +161 -14
  46. package/dist/platform/sdk/field-types.ts +5 -0
  47. package/dist/platform/sdk/index.ts +3 -0
  48. package/dist/platform/sdk/manifest.ts +206 -5
  49. package/dist/platform/sdk/media.ts +62 -0
  50. package/dist/platform/sdk/recurring.ts +314 -0
  51. package/dist/platform/sdk/rich-text.ts +52 -4
  52. package/dist/platform/sdk/sellable.ts +120 -0
  53. package/dist/platform/sdk/states.ts +162 -1
  54. package/dist/platform/sdk/unique.ts +81 -0
  55. package/dist/run-BMSZKTN3.js +648 -0
  56. package/dist/run-GMQBAV6H.js +309 -0
  57. package/dist/{run-4JNFLYXV.js → run-TNHMG5RI.js} +51 -390
  58. package/dist/src-7DXXGZG2.js +38 -0
  59. package/dist/{src-J27WXNLY.js → src-BDG7PERB.js} +73 -1
  60. package/dist/visibility-XSBZTO66.js +33 -0
  61. package/package.json +2 -2
  62. package/dist/chunk-MAXLUQKB.js +0 -1287
  63. package/dist/invoke-5SR5ZWW7.js +0 -26
  64. package/dist/src-SSVOBH6L.js +0 -31
@@ -1,4 +1,16 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ chunks,
4
+ importRecords,
5
+ outcomeLines,
6
+ sha256
7
+ } from "./chunk-7CQGMVDO.js";
8
+ import {
9
+ LOOPBACK_PATH,
10
+ confirmer,
11
+ sessionHost,
12
+ signInForRun
13
+ } from "./chunk-E4WCYTCT.js";
2
14
  import {
3
15
  IMAGE_SCHEMA,
4
16
  RICH_TEXT_SCHEMA,
@@ -7,209 +19,13 @@ import {
7
19
  mediaProblem,
8
20
  slugify,
9
21
  validateDocument
10
- } from "./chunk-X6I2LWB3.js";
22
+ } from "./chunk-2MLAPQU7.js";
11
23
  import "./chunk-5KSXSK7Y.js";
12
24
 
13
25
  // src/content-import/run.ts
14
- import { execFile } from "node:child_process";
15
26
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
16
- import { createServer } from "node:http";
17
- import { hostname } from "node:os";
18
27
  import { join, resolve } from "node:path";
19
28
 
20
- // ../client/src/binding.ts
21
- var SESSION_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
22
-
23
- // ../client/src/errors.ts
24
- var ApiError = class extends Error {
25
- constructor(code, message, status, details) {
26
- super(message);
27
- this.code = code;
28
- this.status = status;
29
- this.details = details;
30
- }
31
- code;
32
- status;
33
- details;
34
- name = "ApiError";
35
- };
36
- var NetworkError = class extends Error {
37
- constructor(message, cause) {
38
- super(message);
39
- this.cause = cause;
40
- }
41
- cause;
42
- name = "NetworkError";
43
- };
44
-
45
- // ../client/src/session.ts
46
- async function post(fetcher, url, body, headers = {}) {
47
- let response;
48
- try {
49
- response = await fetcher(url, {
50
- method: "POST",
51
- headers: { "content-type": "application/json", ...headers },
52
- body: JSON.stringify(body)
53
- });
54
- } catch (error) {
55
- throw new NetworkError("Could not reach the host to sign in", error);
56
- }
57
- const parsed = JSON.parse(await response.text());
58
- if (response.status === 200 && parsed.data) return parsed.data;
59
- throw new ApiError(
60
- parsed.error?.code ?? "internal",
61
- parsed.error?.message ?? `The host answered ${response.status}`,
62
- response.status,
63
- parsed.error?.details
64
- );
65
- }
66
- function tokenSession(options) {
67
- const base = options.baseUrl.replace(/\/+$/, "");
68
- const fetcher = options.fetch ?? globalThis.fetch?.bind(globalThis);
69
- const early = options.refreshEarlyMs ?? 3e4;
70
- const now = options.now ?? (() => Date.now());
71
- let refreshing = null;
72
- async function refresh(tokens) {
73
- try {
74
- const next = await post(fetcher, `${base}/api/v1/auth/refresh`, {
75
- refreshToken: tokens.refreshToken
76
- });
77
- await options.store.save(next);
78
- return next;
79
- } catch (error) {
80
- if (error instanceof ApiError) await options.store.save(null);
81
- throw error;
82
- }
83
- }
84
- return {
85
- /**
86
- * Exchanges a sign-in for tokens. `credentials` are the headers that carry it, such as the
87
- * cookie the sign-in answered with.
88
- */
89
- async exchange(deviceName, credentials) {
90
- const tokens = await post(fetcher, `${base}/api/v1/auth/token`, { deviceName }, credentials);
91
- await options.store.save(tokens);
92
- return tokens;
93
- },
94
- /**
95
- * Asks the host to email a sign-in code (ADR 0455). The answer is the same whoever the
96
- * address is; it throws only when the host refuses to send any (`rate_limited`, or sign-in
97
- * not set up).
98
- */
99
- async requestCode(email, audience = "customer") {
100
- await post(fetcher, `${base}/api/v1/auth/${audience}/code`, { email });
101
- },
102
- /**
103
- * Signs in with the emailed code and keeps the device session the host answers with. A wrong,
104
- * used or expired code throws `forbidden` (`invalid_code`). No cookie is involved.
105
- */
106
- async signInWithCode(email, code, deviceName, audience = "customer") {
107
- const signedIn = await post(fetcher, `${base}/api/v1/auth/${audience}/sign-in`, {
108
- email,
109
- code,
110
- deviceName
111
- });
112
- const { account: _account, ...tokens } = signedIn;
113
- await options.store.save(tokens);
114
- return signedIn;
115
- },
116
- /**
117
- * Finishes a staff sign-in in the system browser (`startBrowserSignIn`): checks the state it
118
- * was sent back with and exchanges the code, with the verifier, for a device session.
119
- */
120
- async finishBrowserSignIn(input) {
121
- const query = input.callbackUrl.includes("?") ? input.callbackUrl.split("?")[1] ?? "" : "";
122
- const params = new Map(
123
- query.split("&").filter(Boolean).map((pair) => {
124
- const [key = "", value = ""] = pair.split("=");
125
- return [decodeURIComponent(key), decodeURIComponent(value.replace(/\+/g, " "))];
126
- })
127
- );
128
- const code = params.get("code");
129
- if (!code || params.get("state") !== input.state) {
130
- throw new ApiError(
131
- "forbidden",
132
- "The sign-in did not come back from this app's request",
133
- 401,
134
- {
135
- reason: "invalid_code"
136
- }
137
- );
138
- }
139
- const tokens = await post(fetcher, `${base}/api/v1/auth/staff/exchange`, {
140
- code,
141
- codeVerifier: input.verifier,
142
- redirectUri: input.redirectUri,
143
- deviceName: input.deviceName
144
- });
145
- await options.store.save(tokens);
146
- return tokens;
147
- },
148
- /** The headers for a call: a current access token, refreshed first when it is about to end. */
149
- async headers() {
150
- let tokens = await options.store.load();
151
- if (!tokens) return {};
152
- if (Date.parse(tokens.accessExpiresAt) - early <= now()) {
153
- refreshing ??= refresh(tokens).finally(() => {
154
- refreshing = null;
155
- });
156
- tokens = await refreshing;
157
- if (!tokens) return {};
158
- }
159
- return { authorization: `Bearer ${tokens.accessToken}` };
160
- },
161
- /**
162
- * Ends this device's session on the host (ADR 0455) with its refresh token, which any account
163
- * may do whatever it may call, then forgets the tokens, even when the host could not be
164
- * reached.
165
- */
166
- async signOut() {
167
- const tokens = await options.store.load();
168
- try {
169
- if (tokens) {
170
- await post(fetcher, `${base}/api/v1/auth/sign-out`, {
171
- refreshToken: tokens.refreshToken
172
- });
173
- }
174
- } catch {
175
- } finally {
176
- await options.store.save(null);
177
- }
178
- }
179
- };
180
- }
181
- function base64url(bytes) {
182
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
183
- let out = "";
184
- for (let i = 0; i < bytes.length; i += 3) {
185
- const a = bytes[i] ?? 0;
186
- const b = bytes[i + 1];
187
- const c = bytes[i + 2];
188
- out += alphabet[a >> 2];
189
- out += alphabet[(a & 3) << 4 | (b ?? 0) >> 4];
190
- if (b !== void 0) out += alphabet[(b & 15) << 2 | (c ?? 0) >> 6];
191
- if (c !== void 0) out += alphabet[c & 63];
192
- }
193
- return out;
194
- }
195
- async function startBrowserSignIn(options) {
196
- const verifier = `${options.randomKey()}${options.randomKey()}`.replace(/[^A-Za-z0-9._~-]/g, "").slice(0, 128);
197
- if (verifier.length < 43) throw new Error("randomKey must give at least 22 characters");
198
- const state = options.randomKey().replace(/[^A-Za-z0-9._~-]/g, "");
199
- const challenge = base64url(await options.sha256(verifier));
200
- const query = [
201
- ["redirect_uri", options.redirectUri],
202
- ["code_challenge", challenge],
203
- ["code_challenge_method", "S256"],
204
- ["state", state]
205
- ].map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");
206
- return {
207
- url: `${options.hostUrl.replace(/\/+$/, "")}/native/staff-sign-in?${query}`,
208
- state,
209
- verifier
210
- };
211
- }
212
-
213
29
  // src/content-import/format.ts
214
30
  var POST_OBJECT = "content.post";
215
31
  var CATEGORY_OBJECT = "content.category";
@@ -400,55 +216,30 @@ function readFolder(files) {
400
216
  }
401
217
 
402
218
  // src/content-import/engine.ts
403
- var BATCH = 25;
404
- var chunks = (list, size) => Array.from(
405
- { length: Math.ceil(list.length / size) },
406
- (_, i) => list.slice(i * size, (i + 1) * size)
407
- );
408
- async function sha256(bytes) {
409
- const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
410
- return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
411
- }
412
- function resolved(post2, media, category) {
413
- const values = withPictures(post2.values, media);
414
- if (post2.category) {
415
- const id = category(post2.category);
219
+ function resolved(post, media, category) {
220
+ const values = withPictures(post.values, media);
221
+ if (post.category) {
222
+ const id = category(post.category);
416
223
  if (id) values.category = id;
417
224
  }
418
225
  return values;
419
226
  }
420
- async function importRecords(host, object, records, options) {
421
- const out = [];
422
- for (const part of chunks(records, BATCH)) {
423
- const answer = await host.call("record.import", {
424
- object,
425
- records: part.map(({ key, values }) => ({ key, values })),
426
- dryRun: options.dryRun,
427
- checkReferences: options.checkReferences
428
- });
429
- for (const result of answer.results) {
430
- const file = part.find((r) => r.key === result.key)?.file ?? null;
431
- out.push({ ...result, object, file });
432
- }
433
- }
434
- return out;
435
- }
436
- async function unpublishedNote(host, post2, result) {
227
+ async function unpublishedNote(host, post, result) {
437
228
  if (result?.id && (result.outcome === "unchanged" || result.outcome === "updated")) {
438
229
  const record = await host.call("record.get", {
439
230
  object: POST_OBJECT,
440
231
  id: result.id
441
232
  });
442
233
  const state = record.values.publishState;
443
- const same = post2.status === "published" ? state === "published" : state === "scheduled" && record.values.publishAt === post2.date;
234
+ const same = post.status === "published" ? state === "published" : state === "scheduled" && record.values.publishAt === post.date;
444
235
  if (same) {
445
- return result.outcome === "unchanged" ? null : post2.status === "published" ? "Published here already: the change is saved, not published (pass --publish to publish it)" : "Scheduled here already: the change is saved, not published (pass --publish to schedule it)";
236
+ return result.outcome === "unchanged" ? null : post.status === "published" ? "Published here already: the change is saved, not published (pass --publish to publish it)" : "Scheduled here already: the change is saved, not published (pass --publish to schedule it)";
446
237
  }
447
238
  if (state === "published" || state === "scheduled") {
448
239
  return "Already " + state + " here; left as it is (pass --publish to publish or schedule it as the source has it)";
449
240
  }
450
241
  }
451
- return post2.status === "scheduled" ? `Scheduled for ${post2.date} in the source: imported as a draft (pass --publish to schedule it)` : "Published in the source: imported as a draft (pass --publish to publish it)";
242
+ return post.status === "scheduled" ? `Scheduled for ${post.date} in the source: imported as a draft (pass --publish to schedule it)` : "Published in the source: imported as a draft (pass --publish to publish it)";
452
243
  }
453
244
  async function runImport(plan, host, options = {}) {
454
245
  const report = {
@@ -487,11 +278,11 @@ async function runImport(plan, host, options = {}) {
487
278
  const dryPosts = await importRecords(
488
279
  host,
489
280
  POST_OBJECT,
490
- plan.posts.map((post2) => ({
491
- key: post2.key,
492
- file: post2.file,
281
+ plan.posts.map((post) => ({
282
+ key: post.key,
283
+ file: post.file,
493
284
  values: resolved(
494
- post2,
285
+ post,
495
286
  (f) => placeholders.get(f) ?? placeholderMedia(0),
496
287
  (key) => dryCategoryIds.get(key) ?? "rec_importplaceholder"
497
288
  )
@@ -505,14 +296,14 @@ async function runImport(plan, host, options = {}) {
505
296
  }
506
297
  }
507
298
  }
508
- for (const post2 of plan.posts) {
509
- if (post2.status === "draft" || options.publish) continue;
299
+ for (const post of plan.posts) {
300
+ if (post.status === "draft" || options.publish) continue;
510
301
  const note = await unpublishedNote(
511
302
  host,
512
- post2,
513
- dryPosts.find((r) => r.key === post2.key)
303
+ post,
304
+ dryPosts.find((r) => r.key === post.key)
514
305
  );
515
- if (note) report.notes.push({ file: post2.file, message: note });
306
+ if (note) report.notes.push({ file: post.file, message: note });
516
307
  }
517
308
  if (report.problems.length || options.dryRun) {
518
309
  report.records = [...dryCategories, ...dryPosts];
@@ -551,11 +342,11 @@ async function runImport(plan, host, options = {}) {
551
342
  const posts = await importRecords(
552
343
  host,
553
344
  POST_OBJECT,
554
- plan.posts.map((post2) => ({
555
- key: post2.key,
556
- file: post2.file,
345
+ plan.posts.map((post) => ({
346
+ key: post.key,
347
+ file: post.file,
557
348
  values: resolved(
558
- post2,
349
+ post,
559
350
  (f) => ids.get(f),
560
351
  (key) => categoryIds.get(key) ?? null
561
352
  )
@@ -567,36 +358,36 @@ async function runImport(plan, host, options = {}) {
567
358
  report.wroteNothing = false;
568
359
  }
569
360
  if (options.publish) {
570
- for (const post2 of plan.posts) {
571
- const result = posts.find((r) => r.key === post2.key);
361
+ for (const post of plan.posts) {
362
+ const result = posts.find((r) => r.key === post.key);
572
363
  if (!result?.id || result.outcome === "conflict" || result.outcome === "invalid") continue;
573
- if (post2.status === "draft") continue;
364
+ if (post.status === "draft") continue;
574
365
  const id = result.id;
575
366
  const record = await host.call("record.get", {
576
367
  object: POST_OBJECT,
577
368
  id
578
369
  });
579
370
  const state = record.values.publishState;
580
- const due = post2.status === "scheduled" && post2.date && Date.parse(post2.date) > now.getTime();
371
+ const due = post.status === "scheduled" && post.date && Date.parse(post.date) > now.getTime();
581
372
  if (due) {
582
- if (state === "scheduled" && record.values.publishAt === post2.date) {
583
- report.published.push({ file: post2.file, id, as: "unchanged" });
373
+ if (state === "scheduled" && record.values.publishAt === post.date) {
374
+ report.published.push({ file: post.file, id, as: "unchanged" });
584
375
  continue;
585
376
  }
586
377
  await host.call("record.schedulePublish", {
587
378
  object: POST_OBJECT,
588
379
  id,
589
- at: post2.date,
380
+ at: post.date,
590
381
  note: "Imported"
591
382
  });
592
383
  report.wroteNothing = false;
593
- report.published.push({ file: post2.file, id, as: "scheduled" });
384
+ report.published.push({ file: post.file, id, as: "scheduled" });
594
385
  continue;
595
386
  }
596
- if (post2.status === "scheduled") {
387
+ if (post.status === "scheduled") {
597
388
  report.notes.push({
598
- file: post2.file,
599
- message: `Scheduled for ${post2.date}, which has passed: published`
389
+ file: post.file,
390
+ message: `Scheduled for ${post.date}, which has passed: published`
600
391
  });
601
392
  }
602
393
  if (state === "published" && typeof record.values.publishedVersion === "number") {
@@ -606,13 +397,13 @@ async function runImport(plan, host, options = {}) {
606
397
  from: record.values.publishedVersion
607
398
  });
608
399
  if (!diff.changes.length) {
609
- report.published.push({ file: post2.file, id, as: "unchanged" });
400
+ report.published.push({ file: post.file, id, as: "unchanged" });
610
401
  continue;
611
402
  }
612
403
  }
613
404
  await host.call("record.publish", { object: POST_OBJECT, id, note: "Imported" });
614
405
  report.wroteNothing = false;
615
- report.published.push({ file: post2.file, id, as: "published" });
406
+ report.published.push({ file: post.file, id, as: "published" });
616
407
  }
617
408
  }
618
409
  return report;
@@ -624,22 +415,7 @@ function reportLines(report, dryRun) {
624
415
  for (const p of report.problems) lines.push(` ${p.file}: ${p.message}`);
625
416
  return lines;
626
417
  }
627
- const by = (outcome) => report.records.filter((r) => r.outcome === outcome);
628
- const verb = dryRun ? "would be" : "were";
629
- for (const [outcome, label] of [
630
- ["created", "created"],
631
- ["updated", "updated"],
632
- ["unchanged", "unchanged"]
633
- ]) {
634
- const list = by(outcome);
635
- if (list.length)
636
- lines.push(`${list.length} record(s) ${outcome === "unchanged" ? "are" : verb} ${label}.`);
637
- }
638
- const conflicts = by("conflict");
639
- if (conflicts.length) {
640
- lines.push(`${conflicts.length} conflict(s), left as they are:`);
641
- for (const c of conflicts) lines.push(` ${c.file ?? c.key}: ${c.problems.join("; ")}`);
642
- }
418
+ lines.push(...outcomeLines(report.records, dryRun));
643
419
  if (!dryRun) {
644
420
  lines.push(
645
421
  `Pictures: ${report.pictures.uploaded} uploaded, ${report.pictures.already} already in the library.`
@@ -653,45 +429,7 @@ function reportLines(report, dryRun) {
653
429
  return lines;
654
430
  }
655
431
 
656
- // src/content-import/host.ts
657
- function sessionHost(base, headers, fetcher = fetch) {
658
- return {
659
- async call(name, input) {
660
- const response = await fetcher(`${base}/api/v1/op/${encodeURIComponent(name)}`, {
661
- method: "POST",
662
- headers: {
663
- "content-type": "application/json",
664
- "idempotency-key": crypto.randomUUID(),
665
- ...await headers()
666
- },
667
- body: JSON.stringify(input)
668
- });
669
- const body = await response.json();
670
- if (!response.ok || body.error) {
671
- throw Object.assign(new Error(body.error?.message ?? `${name}: HTTP ${response.status}`), {
672
- code: body.error?.code,
673
- details: body.error?.details
674
- });
675
- }
676
- return body.data;
677
- },
678
- async upload(bytes, name) {
679
- const response = await fetcher(`${base}/api/v1/media?${new URLSearchParams({ name })}`, {
680
- method: "POST",
681
- headers: { "content-type": "application/octet-stream", ...await headers() },
682
- body: new Uint8Array(bytes)
683
- });
684
- const body = await response.json();
685
- if (!response.ok || !body.data) {
686
- throw new Error(`pictures/${name}: ${body.error?.message ?? `HTTP ${response.status}`}`);
687
- }
688
- return body.data;
689
- }
690
- };
691
- }
692
-
693
432
  // src/content-import/run.ts
694
- var LOOPBACK_PATH = "/cos-sign-in";
695
433
  function readImportFolder(dir) {
696
434
  const root = resolve(dir);
697
435
  if (!existsSync(root) || !statSync(root).isDirectory()) {
@@ -712,44 +450,6 @@ function readImportFolder(dir) {
712
450
  }
713
451
  return { posts, pictures };
714
452
  }
715
- function memoryStore() {
716
- let saved = null;
717
- return {
718
- load: async () => saved,
719
- save: async (tokens) => {
720
- saved = tokens;
721
- }
722
- };
723
- }
724
- var hex = (bytes) => [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
725
- function openBrowser(url, io) {
726
- io.out(`Sign in in your browser: ${url}`);
727
- const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
728
- execFile(command, [url], () => {
729
- });
730
- }
731
- async function loopback() {
732
- let settle;
733
- const callback = new Promise((resolve_) => {
734
- settle = resolve_;
735
- });
736
- const server = createServer((req, res) => {
737
- const url = new URL(req.url ?? "/", "http://127.0.0.1");
738
- if (url.pathname !== LOOPBACK_PATH) {
739
- res.writeHead(404).end();
740
- return;
741
- }
742
- res.writeHead(200, { "content-type": "text/plain; charset=utf-8" }).end("Signed in. You can close this tab and go back to the terminal.");
743
- settle(`http://127.0.0.1${req.url}`);
744
- });
745
- await new Promise((done) => server.listen(0, "127.0.0.1", done));
746
- const port = server.address().port;
747
- return {
748
- redirectUri: `http://127.0.0.1:${port}${LOOPBACK_PATH}`,
749
- callback,
750
- close: () => server.close()
751
- };
752
- }
753
453
  async function contentImport(positional, flags, io) {
754
454
  const dir = positional[0];
755
455
  if (!dir) {
@@ -776,40 +476,9 @@ A post file's fields: ${Object.entries(
776
476
  io.out(
777
477
  `${plan.posts.length} post(s), ${plan.categories.length} categor${plan.categories.length === 1 ? "y" : "ies"} and ${plan.pictures.size} picture(s) in ${dir}.`
778
478
  );
779
- const store = memoryStore();
780
- const session = tokenSession({ baseUrl: host, store });
781
- const deviceName = `cos content import on ${hostname()}`.slice(0, 100);
479
+ let session;
782
480
  try {
783
- if (flags.email) {
784
- await session.requestCode(flags.email, "staff");
785
- io.out(
786
- `If ${flags.email} may sign in by code, a code is on its way. If none arrives in a minute or two, check on the host: the address is one an admin invited, or one you confirmed (your account menu, Confirm your email), and Settings \u2192 Users shows sign-in codes going out (Send sign-in codes without review). Or run without --email to sign in with the browser.`
787
- );
788
- const code = await io.ask(`The sign-in code sent to ${flags.email}`, { secret: true });
789
- await session.signInWithCode(flags.email, code.trim(), deviceName, "staff");
790
- } else {
791
- const back = await loopback();
792
- try {
793
- const random = () => hex(crypto.getRandomValues(new Uint8Array(16)));
794
- const started = await startBrowserSignIn({
795
- hostUrl: host,
796
- redirectUri: back.redirectUri,
797
- randomKey: random,
798
- sha256: async (text) => new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)))
799
- });
800
- openBrowser(started.url, io);
801
- const callbackUrl = await back.callback;
802
- await session.finishBrowserSignIn({
803
- callbackUrl,
804
- state: started.state,
805
- verifier: started.verifier,
806
- redirectUri: back.redirectUri,
807
- deviceName
808
- });
809
- } finally {
810
- back.close();
811
- }
812
- }
481
+ session = await signInForRun(host, flags.email, io, "cos content import");
813
482
  } catch (error) {
814
483
  io.err(`Could not sign in: ${error.message}`);
815
484
  return 1;
@@ -821,15 +490,7 @@ A post file's fields: ${Object.entries(
821
490
  {
822
491
  dryRun: Boolean(flags.dryRun),
823
492
  publish: Boolean(flags.publish),
824
- confirm: async (summary) => {
825
- if (flags.yes) return true;
826
- if (!io.interactive) {
827
- io.err(`${summary}. Pass --yes to confirm it when running from a script.`);
828
- return false;
829
- }
830
- const answer = await io.ask(`${summary}. Go ahead? (yes/no)`, { default: "no" });
831
- return /^y(es)?$/i.test(answer.trim());
832
- }
493
+ confirm: confirmer(io, flags.yes)
833
494
  }
834
495
  );
835
496
  for (const line of reportLines(report, Boolean(flags.dryRun))) {
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ENTRY_POINTS,
4
+ operationsFor,
5
+ productContract,
6
+ releaseContract,
7
+ renderClient,
8
+ renderEntry,
9
+ renderRoleClient,
10
+ schemaToTs
11
+ } from "./chunk-P6YZMS3F.js";
12
+ import "./chunk-STBMGUTM.js";
13
+ import "./chunk-7U3OZLTK.js";
14
+ import "./chunk-LPD2VR5M.js";
15
+ import "./chunk-Z52IX5WL.js";
16
+ import "./chunk-VTQNOQGA.js";
17
+ import "./chunk-NDKVIG23.js";
18
+ import "./chunk-NSSUOI3Z.js";
19
+ import "./chunk-56A6RJIU.js";
20
+ import "./chunk-OV3OFYPI.js";
21
+ import "./chunk-DU6OIFOU.js";
22
+ import "./chunk-KGHA67HG.js";
23
+ import "./chunk-6UWRT4VM.js";
24
+ import "./chunk-7O4F3NU4.js";
25
+ import "./chunk-3MIEYXRY.js";
26
+ import "./chunk-ZSR5H4O7.js";
27
+ import "./chunk-2MLAPQU7.js";
28
+ import "./chunk-5KSXSK7Y.js";
29
+ export {
30
+ ENTRY_POINTS,
31
+ operationsFor,
32
+ productContract,
33
+ releaseContract,
34
+ renderClient,
35
+ renderEntry,
36
+ renderRoleClient,
37
+ schemaToTs
38
+ };