@picked/cli 0.0.1-dev.1789541668638 → 0.0.1-dev.1793756239746

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 (39) hide show
  1. package/LICENSE +1 -0
  2. package/README.md +29 -11
  3. package/dist/.tsbuildinfo +1 -1
  4. package/dist/cjs/cli.js +7 -2
  5. package/dist/cjs/index.js +1 -1
  6. package/dist/esm/cli.js +76 -65
  7. package/dist/esm/index.js +1 -2
  8. package/dist/types/commands/docs.d.ts +65 -0
  9. package/dist/types/commands/docs.d.ts.map +1 -0
  10. package/dist/types/commands/login.d.ts +2 -1
  11. package/dist/types/commands/login.d.ts.map +1 -1
  12. package/dist/types/commands/pull.d.ts +19 -0
  13. package/dist/types/commands/pull.d.ts.map +1 -0
  14. package/dist/types/commands/whoami.d.ts +1 -0
  15. package/dist/types/commands/whoami.d.ts.map +1 -1
  16. package/dist/types/commands/workspace-export.d.ts +28 -0
  17. package/dist/types/commands/workspace-export.d.ts.map +1 -0
  18. package/dist/types/commands/workspace-import.d.ts +26 -0
  19. package/dist/types/commands/workspace-import.d.ts.map +1 -0
  20. package/dist/types/commands/workspace-list.d.ts +1 -1
  21. package/dist/types/commands/workspace-list.d.ts.map +1 -1
  22. package/dist/types/commands/workspace-use.d.ts.map +1 -1
  23. package/dist/types/index.d.ts +4 -0
  24. package/dist/types/index.d.ts.map +1 -1
  25. package/dist/types/lib/admin-client.d.ts +22 -0
  26. package/dist/types/lib/admin-client.d.ts.map +1 -0
  27. package/dist/types/lib/bundle.d.ts +79 -0
  28. package/dist/types/lib/bundle.d.ts.map +1 -0
  29. package/dist/types/lib/docs.d.ts +94 -0
  30. package/dist/types/lib/docs.d.ts.map +1 -0
  31. package/dist/types/lib/workspace-transfer.d.ts +120 -0
  32. package/dist/types/lib/workspace-transfer.d.ts.map +1 -0
  33. package/dist/types/lib/workspaces.d.ts +8 -9
  34. package/dist/types/lib/workspaces.d.ts.map +1 -1
  35. package/dist/workspace-use-BlhQXU7t.js +1043 -0
  36. package/dist/workspace-use-CBVbT-DN.cjs +53 -0
  37. package/package.json +14 -7
  38. package/dist/workspace-use-CT6_jewh.cjs +0 -48
  39. package/dist/workspace-use-Cbz1Bxse.js +0 -521
@@ -0,0 +1,1043 @@
1
+ import { existsSync as e, readFileSync as t, realpathSync as n } from "node:fs";
2
+ import { chmod as r, mkdir as i, mkdtemp as a, readFile as o, readdir as s, rename as c, rm as l, rmdir as u, writeFile as d } from "node:fs/promises";
3
+ import { basename as f, dirname as p, join as m, relative as h, resolve as g, sep as _ } from "node:path";
4
+ import { generate as ee } from "@picked/typegen";
5
+ import { SNAPSHOT_FILENAME as v, fetchSnapshot as te, loadPickedConfig as y, loadResolvedPickedConfig as b, normalizeApiUrl as x, readActiveSelection as ne, readSnapshot as re, resolveSnapshotPath as ie, serializeSnapshot as ae, writeActiveSelection as oe, writeSnapshot as se } from "@picked/config";
6
+ import { createServer as ce } from "node:http";
7
+ import { spawn as le } from "node:child_process";
8
+ import { createHash as S, randomBytes as C } from "node:crypto";
9
+ import { homedir as ue } from "node:os";
10
+ import { AdminApiResponseError as de, AssetCommitDocument as fe, AssetDeleteDocument as pe, AssetUploadInitDocument as me, ProjectLiveVersionDocument as he, WorkspaceExportDocument as ge, WorkspaceImportDocument as _e, WorkspacePublishDocument as ve, createAdminApiClient as w, graphql as T } from "@picked/admin-api-client";
11
+ import { isDeepStrictEqual as ye } from "node:util";
12
+ import { createInterface as be } from "node:readline";
13
+ //#region src/lib/docs.ts
14
+ var E = "https://docs.picked.app";
15
+ function D(e) {
16
+ let t = e.trim().replace(/^https?:\/\/[^/]+/, ""), n = t.search(/[#?]/);
17
+ return `/${((n === -1 ? t : t.slice(0, n)).split("node_modules/picked/docs/").pop() ?? "").replace(/\.mdx?$/, "").replace(/(?:^|\/)index$/, "").split("/").filter((e) => e !== "" && e !== ".").join("/")}`;
18
+ }
19
+ function O(e) {
20
+ let t = /^---\n(?<yaml>[\s\S]*?)\n---\n+/.exec(e);
21
+ if (!t) return { body: e };
22
+ let n = t.groups?.yaml && /^type:\s*(?<value>\S+)/m.exec(t.groups.yaml);
23
+ return {
24
+ type: n ? n.groups?.value : void 0,
25
+ body: e.slice(t[0].length)
26
+ };
27
+ }
28
+ function xe(e) {
29
+ let t = e.split(/\n{2,}/).map((e) => e.trim()), n = t.findIndex((e) => e.startsWith("# "));
30
+ return {
31
+ title: n === -1 ? void 0 : t[n]?.slice(2).trim(),
32
+ description: t.slice(n + 1).find((e) => e !== "" && !/^(?:#|:::|```|<|import |export |\||-|\d+\.)/.test(e))?.split("\n").map((e) => e.trim()).join(" ")
33
+ };
34
+ }
35
+ async function k(e) {
36
+ return (await s(e, {
37
+ recursive: !0,
38
+ withFileTypes: !0
39
+ })).filter((e) => e.isFile() && /\.mdx?$/.test(e.name)).map((e) => m(e.parentPath, e.name));
40
+ }
41
+ function Se(e) {
42
+ let t = async (t) => (await k(e)).find((n) => D(h(e, n).split(_).join("/")) === t);
43
+ return {
44
+ location: e,
45
+ list: async () => {
46
+ let t = await k(e);
47
+ return (await Promise.all(t.map(async (t) => {
48
+ let { type: n, body: r } = O(await o(t, "utf8")), { title: i, description: a } = xe(r), s = D(h(e, t).split(_).join("/"));
49
+ return {
50
+ path: s,
51
+ title: i ?? s,
52
+ ...n && { type: n },
53
+ ...a && { description: a },
54
+ file: t
55
+ };
56
+ }))).toSorted((e, t) => e.path.localeCompare(t.path));
57
+ },
58
+ read: async (e) => {
59
+ let n = await t(D(e));
60
+ return n ? O(await o(n, "utf8")).body : void 0;
61
+ }
62
+ };
63
+ }
64
+ function Ce(e) {
65
+ return typeof e != "object" || !e || !("pages" in e) || !Array.isArray(e.pages) ? [] : e.pages.filter((e) => typeof e == "object" && !!e && "path" in e && typeof e.path == "string" && "title" in e && typeof e.title == "string" && "body" in e && typeof e.body == "string");
66
+ }
67
+ function we(e = fetch) {
68
+ let t = `${E}/docs-index.json`, n, r = () => (n ??= e(t).then(async (e) => {
69
+ if (!e.ok) throw Error(`Could not fetch ${t}: ${String(e.status)}`);
70
+ return Ce(await e.json());
71
+ }), n);
72
+ return {
73
+ location: t,
74
+ list: async () => (await r()).map(({ path: e, title: t, type: n, description: r }) => ({
75
+ path: e,
76
+ title: t,
77
+ ...n && { type: n },
78
+ ...r && { description: r }
79
+ })),
80
+ read: async (e) => {
81
+ let t = D(e);
82
+ return (await r()).find((e) => e.path === t)?.body;
83
+ }
84
+ };
85
+ }
86
+ function Te(n) {
87
+ for (let r = n;; r = p(r)) {
88
+ let n = m(r, "package.json");
89
+ if (e(n)) {
90
+ let e = JSON.parse(t(n, "utf8")), i = typeof e == "object" && e && "name" in e && typeof e.name == "string" ? e.name : void 0;
91
+ return {
92
+ dir: r,
93
+ name: i
94
+ };
95
+ }
96
+ if (p(r) === r) return;
97
+ }
98
+ }
99
+ function Ee(t) {
100
+ return [
101
+ t.env.PICKED_DOCS_DIR,
102
+ (() => {
103
+ if (!t.bin || !e(t.bin)) return;
104
+ let r = Te(p(n(t.bin)));
105
+ return r?.name === "picked" ? m(r.dir, "docs") : void 0;
106
+ })(),
107
+ (() => {
108
+ for (let n = t.cwd;; n = p(n)) {
109
+ if (e(m(n, "node_modules", "picked", "package.json"))) return m(n, "node_modules", "picked", "docs");
110
+ if (p(n) === n) return;
111
+ }
112
+ })()
113
+ ].find((t) => typeof t == "string" && e(t));
114
+ }
115
+ function A(e) {
116
+ let t = Ee({
117
+ cwd: e?.cwd ?? process.cwd(),
118
+ bin: process.argv[1],
119
+ env: process.env
120
+ });
121
+ return t ? Se(t) : we();
122
+ }
123
+ function De(e, t) {
124
+ let n = t.toLowerCase().split(/[\s/-]+/).filter(Boolean);
125
+ return e.filter((e) => {
126
+ let t = `${e.path} ${e.title} ${e.description ?? ""}`.toLowerCase();
127
+ return n.every((e) => t.includes(e));
128
+ });
129
+ }
130
+ //#endregion
131
+ //#region src/commands/docs.ts
132
+ var Oe = "Read a page with `picked docs read <path>`.";
133
+ async function j(e) {
134
+ let t = e.source ?? A(), n = await t.list(), r = e.type ? n.filter((t) => t.type === e.type) : n, i = e.query ? De(r, e.query) : r;
135
+ if (i.length === 0) return console.error(`No documentation page matches. Run \`picked docs list\` to see all ${String(n.length)}.`), 1;
136
+ if (e.json) return console.log(JSON.stringify(i, null, 2)), 0;
137
+ for (let e of i) console.log(`${e.path}\t${e.title}`);
138
+ return console.error(`\n${String(i.length)} ${i.length === 1 ? "page" : "pages"} from ${t.location}. ${Oe}`), 0;
139
+ }
140
+ function ke(e, t) {
141
+ let n = t.toLowerCase().split(/[\s/-]+/).filter(Boolean), r = e.map((e) => {
142
+ let t = `${e.path} ${e.title}`.toLowerCase();
143
+ return {
144
+ page: e,
145
+ score: n.filter((e) => t.includes(e)).length
146
+ };
147
+ }), i = Math.max(0, ...r.map(({ score: e }) => e));
148
+ return r.filter(({ score: e }) => e > 0 && e === i).slice(0, 5).map(({ page: e }) => e);
149
+ }
150
+ async function M(e) {
151
+ if (!e.page) return console.error("Usage: picked docs read <path>, for example `picked docs read /how-to/install-the-sdk`."), 1;
152
+ let t = e.source ?? A(), n = D(e.page), r = await t.read(n);
153
+ if (r === void 0) {
154
+ let e = ke(await t.list(), n).map((e) => ` ${e.path}\t${e.title}`);
155
+ return console.error([
156
+ `No documentation page at ${n}.`,
157
+ ...e.length > 0 ? ["Closest pages:", ...e] : [],
158
+ "Run `picked docs list [words]` to find a page."
159
+ ].join("\n")), 1;
160
+ }
161
+ return console.log(`<!-- ${E}${n === "/" ? "" : n} -->\n\n${r}`), 0;
162
+ }
163
+ function N(e) {
164
+ return e === void 0 || e === "list" || e === "ls";
165
+ }
166
+ function Ae(e) {
167
+ return N(e) ? "docs list" : "docs read";
168
+ }
169
+ async function je(e) {
170
+ let [t, ...n] = e.args;
171
+ return N(t) ? j({
172
+ query: n.join(" ") || void 0,
173
+ type: e.type,
174
+ json: e.json,
175
+ source: e.source
176
+ }) : M({
177
+ page: t === "read" ? n[0] : t,
178
+ source: e.source
179
+ });
180
+ }
181
+ //#endregion
182
+ //#region src/commands/generate-types.ts
183
+ async function P(e) {
184
+ let t = e?.cwd ?? process.cwd(), n = await b(t);
185
+ if (!n) return console.error("No picked.config.{ts,js,json} found in the current directory."), 1;
186
+ try {
187
+ let t = await ee({
188
+ config: n,
189
+ check: e?.check ?? !1,
190
+ onWarn: (e) => {
191
+ console.warn(e);
192
+ }
193
+ });
194
+ return e?.check ? t.changed ? (console.error(`Types are out of date: ${t.typesOutput}`), 1) : (console.log(`Types are up to date (${t.typesOutput}).`), 0) : (console.log(`Generated types at ${t.typesOutput}`), 0);
195
+ } catch (e) {
196
+ let t = e instanceof Error ? e.message : String(e);
197
+ return console.error(t), 1;
198
+ }
199
+ }
200
+ //#endregion
201
+ //#region src/lib/browser.ts
202
+ function Me(e) {
203
+ return process.platform === "darwin" ? {
204
+ command: "open",
205
+ args: [e]
206
+ } : process.platform === "win32" ? {
207
+ command: "cmd",
208
+ args: [
209
+ "/c",
210
+ "start",
211
+ "\"\"",
212
+ e
213
+ ]
214
+ } : {
215
+ command: "xdg-open",
216
+ args: [e]
217
+ };
218
+ }
219
+ function Ne(e) {
220
+ let { command: t, args: n } = Me(e);
221
+ try {
222
+ let e = le(t, n, {
223
+ detached: !0,
224
+ stdio: "ignore"
225
+ });
226
+ e.on("error", () => void 0), e.unref();
227
+ } catch {}
228
+ return Promise.resolve();
229
+ }
230
+ //#endregion
231
+ //#region src/lib/paths.ts
232
+ var Pe = 8;
233
+ function Fe() {
234
+ return m(ue(), ".picked");
235
+ }
236
+ function Ie(e) {
237
+ let t = x(e), { hostname: n, port: r } = new URL(t);
238
+ return `${(r ? `${n}-${r}` : n).replace(/[^a-z0-9.-]/gi, "_")}-${S("sha256").update(t).digest("hex").slice(0, Pe)}`;
239
+ }
240
+ function F(e) {
241
+ return m(Fe(), "auth", `${Ie(e)}.json`);
242
+ }
243
+ //#endregion
244
+ //#region src/auth/token-store.ts
245
+ var I = 384;
246
+ function Le(e) {
247
+ return typeof e == "object" && !!e && "clientId" in e && typeof e.clientId == "string" && "redirectUri" in e && typeof e.redirectUri == "string";
248
+ }
249
+ function Re(e) {
250
+ return !(typeof e != "object" || !e || !("accessToken" in e) || typeof e.accessToken != "string" || !("refreshToken" in e) || typeof e.refreshToken != "string" || !("expiresAt" in e) || typeof e.expiresAt != "number" || "user" in e && e.user !== void 0 && (typeof e.user != "object" || e.user === null));
251
+ }
252
+ function ze(e) {
253
+ return !(typeof e != "object" || !e || !("apiUrl" in e) || typeof e.apiUrl != "string" || "client" in e && e.client !== void 0 && !Le(e.client) || "session" in e && e.session !== void 0 && !Re(e.session));
254
+ }
255
+ async function L(t) {
256
+ let n = F(t);
257
+ if (!e(n)) return null;
258
+ try {
259
+ let e = JSON.parse(await o(n, "utf8"));
260
+ return ze(e) ? e : null;
261
+ } catch {
262
+ return null;
263
+ }
264
+ }
265
+ async function Be(e) {
266
+ let t = F(e.apiUrl);
267
+ await i(p(t), { recursive: !0 });
268
+ let n = `${t}.${process.pid.toString()}.tmp`;
269
+ await d(n, `${JSON.stringify(e, null, 2)}\n`, {
270
+ encoding: "utf8",
271
+ mode: I
272
+ }), await r(n, I), await c(n, t);
273
+ }
274
+ async function R(e, t) {
275
+ let n = await L(e);
276
+ await Be({
277
+ apiUrl: x(e),
278
+ client: n?.client,
279
+ session: n?.session,
280
+ ...t
281
+ });
282
+ }
283
+ async function Ve(e, t) {
284
+ await R(e, { client: t });
285
+ }
286
+ async function He(e, t) {
287
+ await R(e, { session: t });
288
+ }
289
+ async function Ue(e) {
290
+ await l(F(e), { force: !0 });
291
+ }
292
+ //#endregion
293
+ //#region src/auth/pkce.ts
294
+ var We = 32, Ge = 16;
295
+ function z(e) {
296
+ return e.toString("base64").replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
297
+ }
298
+ function Ke() {
299
+ return z(C(We));
300
+ }
301
+ function qe(e) {
302
+ return z(S("sha256").update(e).digest());
303
+ }
304
+ function Je() {
305
+ return z(C(Ge));
306
+ }
307
+ //#endregion
308
+ //#region src/auth/oauth.ts
309
+ var B = [
310
+ 8976,
311
+ 8977,
312
+ 8988
313
+ ], Ye = 18e4, Xe = "openid profile email";
314
+ async function V(e) {
315
+ let t;
316
+ try {
317
+ t = await fetch(`${e}/.well-known/oauth-authorization-server`);
318
+ } catch (e) {
319
+ let t = e instanceof Error ? e.message : String(e);
320
+ throw Error(`Failed to reach the Picked OAuth discovery endpoint: ${t}`);
321
+ }
322
+ if (!t.ok) throw Error(`OAuth discovery request failed (${t.status.toString()}).`);
323
+ let n = await t.json();
324
+ if (typeof n != "object" || !n) throw Error("Malformed OAuth discovery document.");
325
+ if (!("authorization_endpoint" in n) || typeof n.authorization_endpoint != "string") throw Error("OAuth discovery document is missing authorization_endpoint.");
326
+ if (!("token_endpoint" in n) || typeof n.token_endpoint != "string") throw Error("OAuth discovery document is missing token_endpoint.");
327
+ let r = "registration_endpoint" in n && typeof n.registration_endpoint == "string" ? n.registration_endpoint : void 0, i = "code_challenge_methods_supported" in n && Array.isArray(n.code_challenge_methods_supported) ? n.code_challenge_methods_supported.filter((e) => typeof e == "string") : void 0;
328
+ return {
329
+ authorizationEndpoint: n.authorization_endpoint,
330
+ tokenEndpoint: n.token_endpoint,
331
+ registrationEndpoint: r,
332
+ codeChallengeMethods: i
333
+ };
334
+ }
335
+ async function Ze(e, t, n) {
336
+ if (!t.registrationEndpoint) throw Error("OAuth client registration is not available for this Picked API.");
337
+ let r = await fetch(t.registrationEndpoint, {
338
+ method: "POST",
339
+ headers: { "content-type": "application/json" },
340
+ body: JSON.stringify({
341
+ client_name: "Picked CLI",
342
+ redirect_uris: [n],
343
+ grant_types: ["authorization_code", "refresh_token"],
344
+ response_types: ["code"],
345
+ token_endpoint_auth_method: "none"
346
+ })
347
+ });
348
+ if (!r.ok) throw Error(`OAuth client registration failed (${r.status.toString()}).`);
349
+ let i = await r.json();
350
+ if (typeof i != "object" || !i || !("client_id" in i) || typeof i.client_id != "string") throw Error("OAuth client registration returned an unexpected response.");
351
+ return await Ve(e, {
352
+ clientId: i.client_id,
353
+ redirectUri: n
354
+ }), i.client_id;
355
+ }
356
+ async function Qe(e, t, n) {
357
+ let r = (await L(e))?.client;
358
+ return r?.redirectUri === n ? r.clientId : Ze(e, t, n);
359
+ }
360
+ function $e(e, t) {
361
+ return new Promise((n) => {
362
+ let r = () => {
363
+ e.removeListener("error", r), n(!1);
364
+ };
365
+ e.once("error", r), e.listen(t, "127.0.0.1", () => {
366
+ e.removeListener("error", r), n(!0);
367
+ });
368
+ });
369
+ }
370
+ async function et(e) {
371
+ for (let t of B) if (await $e(e, t)) return t;
372
+ throw Error(`No loopback port available for the OAuth callback (tried ${B.join(", ")}).`);
373
+ }
374
+ function tt(e, t, n) {
375
+ return new Promise((r, i) => {
376
+ let a = () => {
377
+ clearTimeout(o), process.removeListener("SIGINT", s), e.close();
378
+ }, o = setTimeout(() => {
379
+ a(), i(/* @__PURE__ */ Error("Timed out waiting for the browser sign-in to complete."));
380
+ }, n), s = () => {
381
+ a(), i(/* @__PURE__ */ Error("Sign-in cancelled."));
382
+ };
383
+ process.once("SIGINT", s), e.on("request", (e, n) => {
384
+ let o = new URL(e.url ?? "/", "http://127.0.0.1");
385
+ if (o.pathname !== "/callback") {
386
+ n.writeHead(404), n.end();
387
+ return;
388
+ }
389
+ let s = o.searchParams.get("error");
390
+ if (s) {
391
+ n.writeHead(200, { "content-type": "text/html" }), n.end("<html><body>Sign-in failed. You can close this tab.</body></html>"), a(), i(/* @__PURE__ */ Error(`Authorization failed: ${s}`));
392
+ return;
393
+ }
394
+ let c = o.searchParams.get("code"), l = o.searchParams.get("state");
395
+ !c || l !== t ? (n.writeHead(400, { "content-type": "text/html" }), n.end("<html><body>Invalid sign-in response. Close this tab and try again.</body></html>"), a(), i(/* @__PURE__ */ Error("Invalid OAuth callback: missing code or state mismatch."))) : (n.writeHead(200, { "content-type": "text/html" }), n.end("<html><body>Signed in. You can close this tab and return to the terminal.</body></html>"), a(), r({ code: c }));
396
+ });
397
+ });
398
+ }
399
+ async function H(e) {
400
+ let t;
401
+ try {
402
+ t = await e.json();
403
+ } catch {
404
+ return null;
405
+ }
406
+ if (typeof t != "object" || !t || !("access_token" in t) || typeof t.access_token != "string" || !("expires_in" in t) || typeof t.expires_in != "number") return null;
407
+ let n = "refresh_token" in t && typeof t.refresh_token == "string" ? t.refresh_token : void 0;
408
+ return {
409
+ accessToken: t.access_token,
410
+ refreshToken: n,
411
+ expiresIn: t.expires_in
412
+ };
413
+ }
414
+ function nt(e) {
415
+ let t = e.split("."), n = t[1];
416
+ if (t.length !== 3 || !n) return {};
417
+ try {
418
+ let e = JSON.parse(Buffer.from(n, "base64url").toString("utf8"));
419
+ return typeof e != "object" || !e ? {} : {
420
+ id: "sub" in e && typeof e.sub == "string" ? e.sub : void 0,
421
+ email: "email" in e && typeof e.email == "string" ? e.email : void 0
422
+ };
423
+ } catch {
424
+ return {};
425
+ }
426
+ }
427
+ async function rt(e) {
428
+ let t = await V(e), n = ce(), r = `http://127.0.0.1:${(await et(n)).toString()}/callback`, i = await Qe(e, t, r), a = Ke(), o = qe(a), s = Je(), c = new URL(t.authorizationEndpoint);
429
+ c.searchParams.set("response_type", "code"), c.searchParams.set("client_id", i), c.searchParams.set("redirect_uri", r), c.searchParams.set("code_challenge", o), c.searchParams.set("code_challenge_method", "S256"), c.searchParams.set("state", s), c.searchParams.set("scope", Xe), console.log(`Opening your browser to sign in...\n${c.toString()}`), await Ne(c.toString());
430
+ let { code: l } = await tt(n, s, Ye), u = new URLSearchParams({
431
+ grant_type: "authorization_code",
432
+ code: l,
433
+ redirect_uri: r,
434
+ client_id: i,
435
+ code_verifier: a
436
+ }), d = await fetch(t.tokenEndpoint, {
437
+ method: "POST",
438
+ headers: { "content-type": "application/x-www-form-urlencoded" },
439
+ body: u.toString()
440
+ });
441
+ if (!d.ok) throw Error(`Token exchange failed (${d.status.toString()}).`);
442
+ let f = await H(d);
443
+ if (!f?.refreshToken) throw Error("Token exchange did not return a refresh token.");
444
+ return {
445
+ accessToken: f.accessToken,
446
+ refreshToken: f.refreshToken,
447
+ expiresAt: Date.now() + f.expiresIn * 1e3,
448
+ user: nt(f.accessToken)
449
+ };
450
+ }
451
+ async function it(e) {
452
+ if (!e.client || !e.session) throw Error("Session expired. Run `picked login`.");
453
+ let t = await V(e.apiUrl), n = new URLSearchParams({
454
+ grant_type: "refresh_token",
455
+ refresh_token: e.session.refreshToken,
456
+ client_id: e.client.clientId
457
+ }), r;
458
+ try {
459
+ r = await fetch(t.tokenEndpoint, {
460
+ method: "POST",
461
+ headers: { "content-type": "application/x-www-form-urlencoded" },
462
+ body: n.toString()
463
+ });
464
+ } catch {
465
+ throw Error("Session expired. Run `picked login`.");
466
+ }
467
+ if (!r.ok) throw Error("Session expired. Run `picked login`.");
468
+ let i = await H(r);
469
+ if (!i) throw Error("Session expired. Run `picked login`.");
470
+ return {
471
+ accessToken: i.accessToken,
472
+ refreshToken: i.refreshToken ?? e.session.refreshToken,
473
+ expiresAt: Date.now() + i.expiresIn * 1e3,
474
+ user: e.session.user
475
+ };
476
+ }
477
+ //#endregion
478
+ //#region src/auth/session.ts
479
+ var at = 6e4;
480
+ async function U(e) {
481
+ let t = await L(e);
482
+ if (!t?.session) throw Error(`Not logged in to ${e}. Run \`picked login\`.`);
483
+ if (t.session.expiresAt - Date.now() > at) return t.session.accessToken;
484
+ let n = await it(t);
485
+ return await He(e, n), n.accessToken;
486
+ }
487
+ //#endregion
488
+ //#region src/lib/admin-client.ts
489
+ function W() {
490
+ let e = process.env.PICKED_API_KEY?.trim();
491
+ return e === "" ? void 0 : e;
492
+ }
493
+ async function G(e) {
494
+ let t = W();
495
+ return t ? w({
496
+ apiUrl: e,
497
+ apiKey: t
498
+ }) : (await U(e), w({
499
+ apiUrl: e,
500
+ token: () => U(e)
501
+ }));
502
+ }
503
+ //#endregion
504
+ //#region src/lib/api-url.ts
505
+ var ot = "https://api.picked.app";
506
+ async function K(e = process.cwd()) {
507
+ let t = process.env.PICKED_API_URL;
508
+ if (t) return x(t);
509
+ let n = await y(e);
510
+ return x(n?.apiUrl ?? ot);
511
+ }
512
+ //#endregion
513
+ //#region src/commands/login.ts
514
+ async function st(e) {
515
+ let t = await K(e?.cwd);
516
+ if (W()) return console.error(`\`picked login\` does not apply while PICKED_API_KEY is set: every command authenticates to ${t} with that API key. Unset PICKED_API_KEY to sign in as a user.`), 1;
517
+ try {
518
+ let e = await rt(t);
519
+ await He(t, e);
520
+ let n = e.user?.email ?? e.user?.id ?? "unknown user";
521
+ return console.log(`Logged in as ${n} (${t})`), 0;
522
+ } catch (e) {
523
+ let t = e instanceof Error ? e.message : String(e);
524
+ return console.error(t), 1;
525
+ }
526
+ }
527
+ //#endregion
528
+ //#region src/commands/logout.ts
529
+ async function ct(e) {
530
+ let t = await K(e?.cwd);
531
+ return await Ue(t), console.log(`Logged out of ${t}.`), 0;
532
+ }
533
+ //#endregion
534
+ //#region src/commands/pull.ts
535
+ function q(e) {
536
+ return e ? e.projectVersionId ?? "preview" : "none";
537
+ }
538
+ async function lt(e) {
539
+ try {
540
+ return await re(e);
541
+ } catch {
542
+ return null;
543
+ }
544
+ }
545
+ async function ut(t, n) {
546
+ let r = ie(t);
547
+ if (!e(r)) return console.error(`There is no ${v} to check. Run \`picked pull\` to write one.`), 1;
548
+ let i = await lt(t), a = JSON.parse(ae(n));
549
+ return ye(i, a) ? (console.log(`${v} is up to date (version ${q(n)}).`), 0) : (console.error(`${v} is out of date: it holds version ${q(i)}, and live is version ${q(n)}. Run \`picked pull\` to refresh it.`), 1);
550
+ }
551
+ async function dt(e) {
552
+ let t = await b(e?.cwd ?? process.cwd());
553
+ if (!t) return console.error("No picked.config.{ts,js,json} found in the current directory."), 1;
554
+ if (t.source === "preview" && e?.allowPreview !== !0) return console.error(`The source in force is preview, so ${v} would commit unpublished content. Select the live workspace with \`picked workspace use\`, or pass --allow-preview to pull it anyway.`), 1;
555
+ let n;
556
+ try {
557
+ n = await te({
558
+ apiUrl: t.apiUrl,
559
+ projectId: t.projectId,
560
+ source: t.source,
561
+ previewToken: t.previewToken ?? void 0
562
+ });
563
+ } catch (e) {
564
+ return console.error(e instanceof Error ? e.message : String(e)), 1;
565
+ }
566
+ if (e?.check === !0) return ut(t.projectRoot, n);
567
+ await se(t.projectRoot, n);
568
+ let r = Object.keys(n.experiences).length;
569
+ return console.log(`Wrote ${v}: project ${n.projectId}, version ${q(n)}, ${r.toString()} experience${r === 1 ? "" : "s"} with content.`), t.data !== "snapshot" && console.log(`The data mode in force is '${t.data}', so builds do not read it yet. Set \`data: 'snapshot'\` in picked.config to build from it.`), 0;
570
+ }
571
+ //#endregion
572
+ //#region src/commands/status.ts
573
+ async function ft(e) {
574
+ let t = e?.cwd ?? process.cwd(), n = await y(t);
575
+ if (!n) return console.error("No picked.config.{ts,js,json} found in the current directory."), 1;
576
+ let r = await K(t);
577
+ console.log(`API: ${r}`), console.log(`Config default: project ${n.projectId} (source: ${n.source ?? "published"})`);
578
+ let i = await ne(t, r);
579
+ if (!i) return console.log("Active selection: none (using the config default)."), 0;
580
+ if (!i.workspace) return console.log(`Active selection: live (published) in project ${i.projectId}`), 0;
581
+ let { name: a, status: o, source: s } = i.workspace;
582
+ return console.log(`Active selection: ${a} [${o}] in project ${i.projectId} (source: ${s})`), 0;
583
+ }
584
+ //#endregion
585
+ //#region src/commands/whoami.ts
586
+ async function pt(e) {
587
+ let t = await K(e?.cwd);
588
+ if (W()) return console.error(`\`picked whoami\` does not apply while PICKED_API_KEY is set: an API key authenticates to ${t} as a project or organization, not as a user.`), 1;
589
+ let n = await L(t);
590
+ if (!n?.session) return console.error(`Not logged in to ${t}. Run \`picked login\`.`), 1;
591
+ let { user: r } = n.session, i = r?.email ?? r?.id ?? "unknown user";
592
+ return console.log(`${i} (${t})`), 0;
593
+ }
594
+ //#endregion
595
+ //#region src/lib/bundle.ts
596
+ var J = "bundle.json", Y = "assets", mt = /^[0-9a-f]{64}$/;
597
+ function X(e, t, n) {
598
+ let r = g(e), i = g(r, t);
599
+ if (!i.startsWith(r.endsWith(_) ? r : r + _)) throw Error(`${n} ${t} must name a directory inside ${r}.`);
600
+ return i;
601
+ }
602
+ function Z(e) {
603
+ return typeof e == "object" && !!e && !Array.isArray(e);
604
+ }
605
+ function ht(e) {
606
+ return S("sha256").update(e).digest("hex");
607
+ }
608
+ function gt(e, t) {
609
+ return m(e, Y, t);
610
+ }
611
+ function _t(e, t) {
612
+ let n = `bundle assets[${String(t)}]`;
613
+ if (!Z(e)) throw Error(`${n} is not an object.`);
614
+ let { versionId: r, fileName: i, mimeType: a, sizeBytes: o, sha256: s, downloadUrl: c } = e;
615
+ if (typeof r != "string" || typeof i != "string" || typeof a != "string" || typeof c != "string" || typeof o != "number" || !Number.isInteger(o) || o < 0) throw Error(`${n} needs a string versionId, fileName, mimeType and downloadUrl, and an integer sizeBytes.`);
616
+ if (s === null) return {
617
+ versionId: r,
618
+ fileName: i,
619
+ mimeType: a,
620
+ sizeBytes: o,
621
+ sha256: s,
622
+ downloadUrl: c
623
+ };
624
+ let l = typeof s == "string" ? s.toLowerCase() : "";
625
+ if (!mt.test(l)) throw Error(`${n} (${i}) has a sha256 that is not a hex SHA-256 digest.`);
626
+ return {
627
+ versionId: r,
628
+ fileName: i,
629
+ mimeType: a,
630
+ sizeBytes: o,
631
+ sha256: l,
632
+ downloadUrl: c
633
+ };
634
+ }
635
+ function vt(e) {
636
+ let { assets: t } = e;
637
+ if (!Array.isArray(t)) throw Error("The bundle has no assets array.");
638
+ return t.map((e, t) => _t(e, t));
639
+ }
640
+ function yt(e, t, n) {
641
+ if (t.byteLength !== e.sizeBytes) throw Error(`${e.fileName} (${n}) has size ${String(t.byteLength)} bytes; the manifest says ${String(e.sizeBytes)}.`);
642
+ let r = ht(t);
643
+ if (e.sha256 !== null && r !== e.sha256) throw Error(`${e.fileName} (${n}) has SHA-256 ${r}; the manifest says ${e.sha256}.`);
644
+ return r;
645
+ }
646
+ function bt(e, t) {
647
+ let n = Array.isArray(e.assets) ? e.assets : [];
648
+ return {
649
+ ...e,
650
+ assets: n.map((e, n) => Z(e) ? {
651
+ ...e,
652
+ sha256: t[n]
653
+ } : e)
654
+ };
655
+ }
656
+ //#endregion
657
+ //#region src/lib/workspace-transfer.ts
658
+ var xt = 12e4, St = 3e5, Ct = class extends Error {
659
+ name = "PayloadUserErrorsError";
660
+ };
661
+ function Q(e, t) {
662
+ if (t.length !== 0) throw new Ct(`${e} failed:\n${t.map((e) => {
663
+ let t = e.field?.length ? ` (${e.field.join(".")})` : "";
664
+ return ` ${e.code}: ${e.message}${t}`;
665
+ }).join("\n")}`);
666
+ }
667
+ async function wt(e, t) {
668
+ let { project: n } = await e.request(he, { input: { id: t } });
669
+ if (!n) throw Error(`Project ${t} was not found.`);
670
+ let r = n.liveWorkspaceVersion;
671
+ if (!r) throw Error(`Project ${t} has no published version.`);
672
+ if (!r.snapshotWorkspaceId) throw Error(`The live version ${r.id} of project ${t} has no snapshot workspace to export. Publish the project again.`);
673
+ return r.snapshotWorkspaceId;
674
+ }
675
+ async function Tt(e, t) {
676
+ let { workspaceExport: n } = await e.request(ge, { input: { workspaceId: t } });
677
+ if (Q(`Export of workspace ${t}`, n.userErrors), !Z(n.bundle)) throw Error(`Export of workspace ${t} returned no bundle.`);
678
+ return n.bundle;
679
+ }
680
+ async function Et(e, t) {
681
+ let { projectId: n, fileName: r, mimeType: i, sha256: a, bytes: o } = t, { assetUploadInit: s } = await e.request(me, { input: {
682
+ projectId: n,
683
+ fileName: r,
684
+ contentType: i,
685
+ sha256: a
686
+ } });
687
+ if (s.deduplicated) return {
688
+ assetId: s.assetId,
689
+ versionId: s.versionId,
690
+ deduplicated: !0
691
+ };
692
+ if (!s.uploadUrl) throw Error(`The API returned no upload URL for ${r}.`);
693
+ let c = await fetch(s.uploadUrl, {
694
+ method: "PUT",
695
+ headers: { "Content-Type": i },
696
+ body: o,
697
+ signal: AbortSignal.timeout(xt)
698
+ });
699
+ if (!c.ok) throw Error(`Upload of ${r} failed with status ${String(c.status)}: ${await c.text()}`);
700
+ let { assetCommit: l } = await e.request(fe, { input: {
701
+ projectId: n,
702
+ assetId: s.assetId,
703
+ versionId: s.versionId,
704
+ fileName: r,
705
+ storagePath: s.storagePath,
706
+ sha256: a
707
+ } });
708
+ return Q(`Commit of ${r}`, l.userErrors), {
709
+ assetId: s.assetId,
710
+ versionId: s.versionId,
711
+ deduplicated: !1
712
+ };
713
+ }
714
+ async function Dt(e, t) {
715
+ await e.request(pe, { input: { id: t } });
716
+ }
717
+ async function Ot(e, t) {
718
+ let { workspaceImport: n } = await e.request(_e, { input: t }, { timeoutMs: St });
719
+ if (Q(`Import into project ${t.projectId}`, n.userErrors), !n.workspace) throw Error(`Import into project ${t.projectId} returned no workspace.`);
720
+ return n.workspace;
721
+ }
722
+ async function kt(e, t) {
723
+ let { workspacePublish: n } = await e.request(ve, { input: { workspaceId: t } });
724
+ Q(`Publish of workspace ${t}`, n.userErrors);
725
+ }
726
+ //#endregion
727
+ //#region src/commands/workspace-export.ts
728
+ var At = 12e4;
729
+ function jt(e, t) {
730
+ if (!e.project) throw Error("Missing --project <id>.");
731
+ if (e.workspace && e.live) throw Error("Pass --workspace <id> or --live, not both.");
732
+ if (!e.workspace && !e.live) throw Error("Pass --workspace <id> or --live.");
733
+ if (!e.out) throw Error("Missing --out <dir>.");
734
+ return {
735
+ projectId: e.project,
736
+ workspaceId: e.workspace ?? null,
737
+ outDir: X(t, e.out, "--out")
738
+ };
739
+ }
740
+ async function Mt(e) {
741
+ if ((await s(e).catch((e) => {
742
+ if (Z(e) && e.code === "ENOENT") return [];
743
+ throw e;
744
+ })).length > 0) throw Error(`${e} is not empty. Export into a new or empty directory.`);
745
+ }
746
+ async function Nt(e) {
747
+ let t = await fetch(e.downloadUrl, { signal: AbortSignal.timeout(At) });
748
+ if (!t.ok) throw Error(`Download of ${e.fileName} from ${e.downloadUrl} failed with status ${String(t.status)}.`);
749
+ let n = new Uint8Array(await t.arrayBuffer());
750
+ return {
751
+ bytes: n,
752
+ sha256: yt(e, n, e.downloadUrl)
753
+ };
754
+ }
755
+ async function Pt(e, t, n) {
756
+ await i(m(e, Y));
757
+ let r = [];
758
+ for (let t of n) {
759
+ let { bytes: n, sha256: i } = await Nt(t);
760
+ await d(gt(e, i), n), r.push(i);
761
+ }
762
+ let a = bt(t, r);
763
+ await d(m(e, J), `${JSON.stringify(a, null, 2)}\n`);
764
+ }
765
+ async function Ft(e, t, n) {
766
+ await i(p(e), { recursive: !0 });
767
+ let r = await a(m(p(e), `.${f(e)}.partial-`));
768
+ try {
769
+ await Pt(r, t, n), await u(e).catch((e) => {
770
+ if (!(Z(e) && e.code === "ENOENT")) throw e;
771
+ }), await c(r, e);
772
+ } catch (e) {
773
+ throw await l(r, {
774
+ recursive: !0,
775
+ force: !0
776
+ }), e;
777
+ }
778
+ }
779
+ async function It(e, t) {
780
+ let n = t.workspaceId ?? await wt(e, t.projectId), r = await Tt(e, n), i = Z(r.source) ? r.source.projectId : void 0;
781
+ if (i !== t.projectId) throw Error(`Workspace ${n} belongs to project ${String(i)}, not ${t.projectId}.`);
782
+ return r;
783
+ }
784
+ async function Lt(e) {
785
+ try {
786
+ let t = jt(e, e.cwd ?? process.cwd());
787
+ await Mt(t.outDir);
788
+ let n = await It(await G(await K(e.cwd)), t), r = vt(n);
789
+ await Ft(t.outDir, n, r);
790
+ let i = Z(n.workspace) ? String(n.workspace.name) : "";
791
+ return console.log(`Exported workspace "${i}" with ${String(r.length)} assets to ${t.outDir}`), 0;
792
+ } catch (e) {
793
+ let t = e instanceof Error ? e.message : String(e);
794
+ return console.error(t), 1;
795
+ }
796
+ }
797
+ //#endregion
798
+ //#region src/commands/workspace-import.ts
799
+ async function Rt(e) {
800
+ let t = m(e, J), n = await o(t, "utf8").catch((e) => {
801
+ throw Error(`Cannot read ${t}. Pass the directory \`picked workspace export\` wrote.`, { cause: e });
802
+ }), r = JSON.parse(n);
803
+ if (!Z(r)) throw Error(`${t} is not a JSON object.`);
804
+ return r;
805
+ }
806
+ async function zt(e, t) {
807
+ let n = [];
808
+ for (let r of t) {
809
+ if (r.sha256 === null) throw Error(`The manifest item for ${r.fileName} has no SHA-256. Export the bundle with \`picked workspace export\`.`);
810
+ let t = gt(e, r.sha256), i = new Uint8Array(await o(t));
811
+ n.push({
812
+ asset: r,
813
+ sha256: yt(r, i, t),
814
+ bytes: i
815
+ });
816
+ }
817
+ return n;
818
+ }
819
+ async function Bt(e, t, n, r) {
820
+ let i = [];
821
+ for (let { asset: a, sha256: o, bytes: s } of n) {
822
+ let n = await Et(e, {
823
+ projectId: t,
824
+ fileName: a.fileName,
825
+ mimeType: a.mimeType,
826
+ sha256: o,
827
+ bytes: s
828
+ });
829
+ n.deduplicated || r.push(n.assetId), i.push({
830
+ sourceVersionId: a.versionId,
831
+ assetId: n.assetId,
832
+ versionId: n.versionId
833
+ });
834
+ }
835
+ return i;
836
+ }
837
+ async function Vt(e, t) {
838
+ let n = [], r = [];
839
+ for (let i of t) try {
840
+ await Dt(e, i), n.push(i);
841
+ } catch (e) {
842
+ let t = e instanceof Error ? e.message : String(e);
843
+ r.push(`Could not delete asset ${i} (${t}); delete it from the project by hand.`);
844
+ }
845
+ return [...n.length > 0 ? [`Deleted the ${String(n.length)} asset${n.length === 1 ? "" : "s"} this run uploaded: ${n.join(", ")}.`] : [], ...r].join("\n");
846
+ }
847
+ function Ht(e, t) {
848
+ let n = e instanceof Error ? e.message : String(e);
849
+ return Error(t ? `${n}\n${t}` : n, { cause: e });
850
+ }
851
+ function Ut(e) {
852
+ let t = ["The outcome of the import is unknown: the API may have created the workspace. Check the project for it before you import again."];
853
+ return e.length > 0 && t.push(`Kept the ${String(e.length)} asset${e.length === 1 ? "" : "s"} this run uploaded: ${e.join(", ")}. If the project has no new workspace, delete them from the project.`), t.join("\n");
854
+ }
855
+ var Wt = /* @__PURE__ */ new Set([
856
+ "FORBIDDEN",
857
+ "UNAUTHENTICATED",
858
+ "BAD_USER_INPUT",
859
+ "GRAPHQL_VALIDATION_FAILED"
860
+ ]);
861
+ function Gt(e) {
862
+ return e instanceof Ct || e instanceof de && e.codes.length > 0 && e.codes.every((e) => e !== void 0 && Wt.has(e));
863
+ }
864
+ async function Kt(e, t) {
865
+ let n = [], r = await Bt(e, t.projectId, t.assets, n).catch(async (t) => {
866
+ throw Ht(t, await Vt(e, n));
867
+ });
868
+ return {
869
+ workspace: await Ot(e, {
870
+ projectId: t.projectId,
871
+ name: t.name,
872
+ bundle: t.bundle,
873
+ assetMap: r
874
+ }).catch(async (t) => {
875
+ throw Ht(t, Gt(t) ? await Vt(e, n) : Ut(n));
876
+ }),
877
+ uploaded: n.length
878
+ };
879
+ }
880
+ async function qt(e) {
881
+ try {
882
+ if (!e.project) throw Error("Missing --project <id>.");
883
+ if (!e.in) throw Error("Missing --in <dir>.");
884
+ let t = e.project, n = X(e.cwd ?? process.cwd(), e.in, "--in"), r = await Rt(n), i = await zt(n, vt(r)), a = await G(await K(e.cwd)), { workspace: o, uploaded: s } = await Kt(a, {
885
+ projectId: t,
886
+ name: e.name,
887
+ bundle: r,
888
+ assets: i
889
+ });
890
+ return console.log(`Imported workspace "${o.name}" as ${o.id} into project ${t} (assets: ${String(s)} uploaded, ${String(i.length - s)} already in the project).`), e.publish && (await kt(a, o.id).catch((e) => {
891
+ let t = e instanceof Error ? e.message : String(e);
892
+ throw Error(`Workspace ${o.id} was imported, but not published. ${t}`, { cause: e });
893
+ }), console.log(`Published workspace ${o.id}.`)), 0;
894
+ } catch (e) {
895
+ let t = e instanceof Error ? e.message : String(e);
896
+ return console.error(t), 1;
897
+ }
898
+ }
899
+ //#endregion
900
+ //#region src/lib/workspaces.ts
901
+ var Jt = T("\n query PickedWorkspaces {\n user {\n organizations(first: 50) {\n edges {\n node {\n id\n name\n slug\n projects(first: 100) {\n edges {\n node {\n id\n name\n liveWorkspace {\n id\n }\n liveWorkspaceVersion {\n id\n }\n workspaces(first: 100) {\n edges {\n node {\n id\n name\n status\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n"), Yt = T("\n query PickedPreviewToken($id: ID!, $projectId: ID!) {\n workspace(id: $id, projectId: $projectId) {\n id\n name\n status\n previewToken\n }\n }\n");
902
+ async function Xt(e) {
903
+ let t = await e.request(Jt, {});
904
+ if (!t.user) throw Error("Not signed in as a user, or no organizations are visible to this account. An API key has no organization list.");
905
+ return t.user.organizations.edges.map((e) => {
906
+ let t = e.node;
907
+ return {
908
+ id: t.id,
909
+ name: t.name,
910
+ slug: t.slug ?? "",
911
+ projects: t.projects.edges.map((e) => {
912
+ let t = e.node;
913
+ return {
914
+ id: t.id,
915
+ name: t.name,
916
+ liveWorkspaceId: t.liveWorkspace?.id ?? null,
917
+ liveVersionId: t.liveWorkspaceVersion?.id ?? null,
918
+ workspaces: t.workspaces.edges.map((e) => ({
919
+ id: e.node.id,
920
+ name: e.node.name,
921
+ status: e.node.status
922
+ }))
923
+ };
924
+ })
925
+ };
926
+ });
927
+ }
928
+ async function Zt(e, t, n) {
929
+ let r = (await e.request(Yt, {
930
+ id: n,
931
+ projectId: t
932
+ })).workspace;
933
+ if (!r) throw Error(`Workspace "${n}" was not found in project "${t}".`);
934
+ return {
935
+ status: r.status,
936
+ name: r.name,
937
+ previewToken: r.previewToken
938
+ };
939
+ }
940
+ //#endregion
941
+ //#region src/commands/workspace-list.ts
942
+ function Qt(e) {
943
+ for (let t of e) {
944
+ console.log(`${t.name} (${t.slug})`);
945
+ for (let e of t.projects) {
946
+ console.log(` ${e.name} [${e.id}]`);
947
+ for (let t of e.workspaces) {
948
+ let n = t.status === "LIVE" || t.id === e.liveWorkspaceId ? " (live)" : "";
949
+ console.log(` ${t.name} [${t.status}]${n}`);
950
+ }
951
+ }
952
+ }
953
+ }
954
+ async function $t(e) {
955
+ try {
956
+ let t = await Xt(await G(await K(e?.cwd)));
957
+ return e?.json ? (console.log(JSON.stringify(t, null, 2)), 0) : (Qt(t), 0);
958
+ } catch (e) {
959
+ let t = e instanceof Error ? e.message : String(e);
960
+ return console.error(t), 1;
961
+ }
962
+ }
963
+ //#endregion
964
+ //#region src/lib/prompt.ts
965
+ function en(e, t) {
966
+ return new Promise((n) => {
967
+ e.question(t, n);
968
+ });
969
+ }
970
+ async function tn(e, t) {
971
+ if (t.length === 0) throw Error("No choices available to select from.");
972
+ let n = be({
973
+ input: process.stdin,
974
+ output: process.stderr
975
+ });
976
+ process.stderr.write(`${e}\n`), t.forEach((e, t) => {
977
+ process.stderr.write(` ${(t + 1).toString()}. ${e.label}\n`);
978
+ });
979
+ try {
980
+ for (;;) {
981
+ let e = await en(n, `Enter a number (1-${t.length.toString()}): `), r = Number.parseInt(e, 10), i = Number.isInteger(r) ? t[r - 1] : void 0;
982
+ if (i) return i.value;
983
+ process.stderr.write("Invalid choice, try again.\n");
984
+ }
985
+ } finally {
986
+ n.close();
987
+ }
988
+ }
989
+ //#endregion
990
+ //#region src/commands/workspace-use.ts
991
+ function $(e, t, n) {
992
+ return {
993
+ projectId: e,
994
+ workspace: {
995
+ id: t,
996
+ name: n.name,
997
+ status: n.status,
998
+ source: "preview",
999
+ previewToken: n.previewToken
1000
+ }
1001
+ };
1002
+ }
1003
+ async function nn(e, t, n) {
1004
+ return n ? $(t, n, await Zt(e, t, n)) : { projectId: t };
1005
+ }
1006
+ async function rn(e) {
1007
+ let t = await tn("Select a project", (await Xt(e)).flatMap((e) => e.projects.map((t) => ({
1008
+ label: `${e.name} / ${t.name}`,
1009
+ value: t
1010
+ })))), n = t.workspaces.map((e) => ({
1011
+ label: `${e.name} [${e.status}]`,
1012
+ value: e
1013
+ }));
1014
+ t.liveVersionId && n.unshift({
1015
+ label: "Published (live version)",
1016
+ value: null
1017
+ });
1018
+ let r = await tn("Select a workspace", n);
1019
+ if (!r) return { projectId: t.id };
1020
+ r.status === "ARCHIVED" && console.error("Warning: archived workspaces may fail to load via the delivery API.");
1021
+ let i = await Zt(e, t.id, r.id);
1022
+ return $(t.id, r.id, i);
1023
+ }
1024
+ function an(e) {
1025
+ if (!e.workspace) {
1026
+ console.log(`Active workspace: live (published) in project ${e.projectId}`);
1027
+ return;
1028
+ }
1029
+ let { name: t, status: n, source: r } = e.workspace;
1030
+ console.log(`Active workspace: ${t} [${n}] in project ${e.projectId} (source: ${r})`);
1031
+ }
1032
+ async function on(e) {
1033
+ let t = e?.cwd ?? process.cwd();
1034
+ try {
1035
+ let n = await K(t), r = await G(n), i = e?.project ? await nn(r, e.project, e.workspace) : await rn(r);
1036
+ return await oe(t, n, i), an(i), e?.generate !== !1 && await P({ cwd: t }), 0;
1037
+ } catch (e) {
1038
+ let t = e instanceof Error ? e.message : String(e);
1039
+ return console.error(t), 1;
1040
+ }
1041
+ }
1042
+ //#endregion
1043
+ export { pt as a, ct as c, Ae as d, je as f, Lt as i, st as l, M as m, $t as n, ft as o, j as p, qt as r, dt as s, on as t, P as u };