@launchpad-kit/client-core 0.0.0-bootstrap.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.mjs ADDED
@@ -0,0 +1,685 @@
1
+ import { stripVTControlCharacters as e } from "node:util";
2
+ import t from "node:os";
3
+ import n from "node:path";
4
+ import { z as r } from "zod";
5
+ import { randomBytes as i } from "node:crypto";
6
+ import { constants as a, promises as o } from "node:fs";
7
+ import { createClient as s, normalizeBaseUrl as c } from "@launchpad-kit/sdk";
8
+ import l from "picomatch";
9
+ import { Pack as u } from "tar";
10
+ // src/errors.ts
11
+ var d = class extends Error {
12
+ code;
13
+ constructor(e, t) {
14
+ super(t), this.name = "ClientCoreError", this.code = e;
15
+ }
16
+ };
17
+ // src/redact.ts
18
+ function f(e) {
19
+ return e.replace(/lp_[A-Za-z0-9_-]{8,}/g, "lp_[redacted]").replace(/\bBearer\s+(?!\[redacted\])(?:[^\s"',;\\]{8,}|[^\s"',;\\]*[\d._-][^\s"',;\\]*)/gi, "Bearer [redacted]").replace(/__(Secure|Host)-([A-Za-z0-9._-]+)=(?:\\?")?[^\s;,"'\\]+/gi, "__$1-$2=[redacted]");
20
+ }
21
+ function p(e, t) {
22
+ let n = /* @__PURE__ */ new Set();
23
+ for (let e of t) if (!(e.length < 8)) {
24
+ n.add(e), /^lp_/i.test(e) && n.add(e.slice(3)), n.add(encodeURIComponent(e)), n.add(JSON.stringify(e).slice(1, -1));
25
+ try {
26
+ n.add(decodeURIComponent(e));
27
+ } catch {}
28
+ }
29
+ let r = e;
30
+ for (let e of [...n].filter((e) => e.length >= 8).sort((e, t) => t.length - e.length)) r = r.replace(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "gi"), "[redacted]");
31
+ return r;
32
+ }
33
+ // src/output.ts
34
+ function m(t, n = []) {
35
+ let r = [...n], i = (e) => f(p(e, r));
36
+ return i(e(i(t)).replace(/[\p{Cc}\p{Cf}\u2028\u2029]/gu, (e) => e === "\n" || e === " " ? e : e === "‌" || e === "‍" ? `\\u${e.codePointAt(0).toString(16)}` : "").replace(/(\[redacted\])[A-Za-z0-9_-]+/g, "$1"));
37
+ }
38
+ // src/secure-file.ts
39
+ var h = class {
40
+ directory;
41
+ file;
42
+ name;
43
+ label;
44
+ schema;
45
+ empty;
46
+ constructor(e, t) {
47
+ this.directory = e, this.name = t.name, this.label = t.label, this.schema = t.schema, this.empty = t.empty, this.file = n.join(e, t.name);
48
+ }
49
+ async checkDirectory(e) {
50
+ let t;
51
+ try {
52
+ t = await o.lstat(this.directory);
53
+ } catch (n) {
54
+ if (n.code !== "ENOENT") throw n;
55
+ if (!e) return !1;
56
+ await o.mkdir(this.directory, {
57
+ recursive: !0,
58
+ mode: 448
59
+ }), t = await o.lstat(this.directory);
60
+ }
61
+ if (!t.isDirectory()) throw new d("insecure-store", `${this.directory} is not a real directory (a link or a file).`);
62
+ if (process.platform !== "win32") {
63
+ let n = process.getuid?.();
64
+ if (n !== void 0 && t.uid !== n) throw new d("insecure-store", `${this.directory} is owned by another user.`);
65
+ if (t.mode & 63) {
66
+ if (!e) throw new d("insecure-store", `${this.directory} is open to others. Run: chmod 700 ${this.directory}`);
67
+ await o.chmod(this.directory, 448);
68
+ }
69
+ }
70
+ return !0;
71
+ }
72
+ async guard(e) {
73
+ try {
74
+ return await e();
75
+ } catch (e) {
76
+ let t = e?.code;
77
+ throw e instanceof d || typeof t != "string" ? e : new d("store-unavailable", `Cannot use the ${this.label} at ${this.directory} (${t}).`);
78
+ }
79
+ }
80
+ load() {
81
+ return this.guard(() => this.read());
82
+ }
83
+ async read() {
84
+ if (!await this.checkDirectory(!1)) return this.empty();
85
+ let e;
86
+ try {
87
+ e = await o.open(this.file, a.O_RDONLY | (a.O_NOFOLLOW ?? 0) | (a.O_NONBLOCK ?? 0));
88
+ } catch (e) {
89
+ let t = e.code;
90
+ if (t === "ENOENT") return this.empty();
91
+ throw t === "ELOOP" ? new d("insecure-store", `${this.file} is a symbolic link.`) : e;
92
+ }
93
+ let t;
94
+ try {
95
+ let n = await e.stat();
96
+ if (!n.isFile()) throw new d("insecure-store", `${this.file} is not a regular file.`);
97
+ if (process.platform !== "win32") {
98
+ let e = process.getuid?.();
99
+ if (e !== void 0 && n.uid !== e) throw new d("insecure-store", `${this.file} is owned by another user.`);
100
+ if (n.mode & 63) throw new d("insecure-store", `${this.file} is readable by others. Run: chmod 600 ${this.file}`);
101
+ }
102
+ t = await e.readFile("utf8");
103
+ } finally {
104
+ await e.close();
105
+ }
106
+ let n;
107
+ try {
108
+ n = JSON.parse(t);
109
+ } catch {
110
+ throw new d("corrupt-store", `${this.file} is not valid JSON. Fix or remove it; it was not changed.`);
111
+ }
112
+ let r = n?.version;
113
+ if (typeof r == "number" && r !== 1) throw new d("unsupported-store", `${this.file} was written by a different version of Launchpad (format ${r}); it was not changed.`);
114
+ let i = this.schema.safeParse(n);
115
+ if (!i.success) throw new d("corrupt-store", `${this.file} does not have the expected shape. Fix or remove it; it was not changed.`);
116
+ return i.data;
117
+ }
118
+ update(e) {
119
+ return this.guard(() => this.write(e));
120
+ }
121
+ async write(e) {
122
+ await this.checkDirectory(!0);
123
+ let t = await this.lock();
124
+ try {
125
+ let t = await this.read(), r = e(t), a = n.join(this.directory, `.${this.name}.${i(6).toString("hex")}`), s = await o.open(a, "wx", 384);
126
+ try {
127
+ try {
128
+ await s.writeFile(JSON.stringify(t, null, 2) + "\n"), await s.sync();
129
+ } finally {
130
+ await s.close();
131
+ }
132
+ return await o.rename(a, this.file), r;
133
+ } finally {
134
+ await o.rm(a, { force: !0 });
135
+ }
136
+ } finally {
137
+ await t();
138
+ }
139
+ }
140
+ async lock() {
141
+ let e = `${this.file}.lock`, t = i(24).toString("hex");
142
+ for (let n = 0; n < 50; n++) {
143
+ let n;
144
+ try {
145
+ n = await o.open(e, "wx", 384);
146
+ } catch (e) {
147
+ if (e.code !== "EEXIST") throw e;
148
+ await new Promise((e) => setTimeout(e, 20));
149
+ continue;
150
+ }
151
+ try {
152
+ await n.writeFile(t);
153
+ } catch (t) {
154
+ throw await o.rm(e, { force: !0 }), t;
155
+ } finally {
156
+ await n.close();
157
+ }
158
+ return async () => {
159
+ await o.readFile(e, "utf8").catch((e) => {
160
+ if (e.code === "ENOENT") return null;
161
+ throw e;
162
+ }) === t && await o.rm(e, { force: !0 });
163
+ };
164
+ }
165
+ throw new d("store-busy", `The ${this.label} is busy. Retry after other commands finish. If a command crashed, remove ${e} only after confirming no client is writing.`);
166
+ }
167
+ }, g = r.object({
168
+ controller: r.string(),
169
+ apiKey: r.string(),
170
+ organizationId: r.string().nullable(),
171
+ savedAt: r.string()
172
+ }), _ = r.object({
173
+ version: r.literal(1),
174
+ currentProfile: r.string().nullable(),
175
+ profiles: r.record(r.string(), g)
176
+ }), v = () => ({
177
+ version: 1,
178
+ currentProfile: null,
179
+ profiles: {}
180
+ });
181
+ function y(e) {
182
+ return e.LAUNCHPAD_CONFIG_DIR ? e.LAUNCHPAD_CONFIG_DIR : e.XDG_CONFIG_HOME ? n.join(e.XDG_CONFIG_HOME, "launchpad") : n.join(t.homedir(), ".config", "launchpad");
183
+ }
184
+ var ee = "credentials.json", b = class extends h {
185
+ constructor(e) {
186
+ super(e, {
187
+ name: ee,
188
+ label: "credential store",
189
+ schema: _,
190
+ empty: v
191
+ });
192
+ }
193
+ }, x = (e) => e.trim().toLowerCase(), S = r.object({
194
+ controller: r.string(),
195
+ email: r.string(),
196
+ cookie: r.string(),
197
+ savedAt: r.string()
198
+ }), C = r.object({
199
+ version: r.literal(1),
200
+ sessions: r.record(r.string(), S)
201
+ }).refine((e) => Object.entries(e.sessions).every(([e, t]) => {
202
+ try {
203
+ return e === t.controller && c(t.controller) === e && x(t.email) === t.email;
204
+ } catch {
205
+ return !1;
206
+ }
207
+ })), te = "session.json", w = class extends h {
208
+ constructor(e) {
209
+ super(e, {
210
+ name: te,
211
+ label: "session store",
212
+ schema: C,
213
+ empty: () => ({
214
+ version: 1,
215
+ sessions: {}
216
+ })
217
+ });
218
+ }
219
+ async get(e) {
220
+ let t = c(e), n = await this.load();
221
+ return Object.hasOwn(n.sessions, t) ? n.sessions[t] : null;
222
+ }
223
+ put(e) {
224
+ let t = c(e.controller);
225
+ return this.update((n) => {
226
+ let r = Object.hasOwn(n.sessions, t) ? n.sessions[t] : null;
227
+ return n.sessions[t] = {
228
+ controller: t,
229
+ email: x(e.email),
230
+ cookie: e.cookie,
231
+ savedAt: e.savedAt ?? (/* @__PURE__ */ new Date()).toISOString()
232
+ }, r;
233
+ });
234
+ }
235
+ remove(e, t) {
236
+ let n = c(e);
237
+ return this.update((e) => {
238
+ let r = Object.hasOwn(e.sessions, n) ? e.sessions[n] : null;
239
+ return !r || t !== void 0 && r.cookie !== t ? null : (delete e.sessions[n], r);
240
+ });
241
+ }
242
+ };
243
+ // src/operations.ts
244
+ function ne(e = process.env, t = {}) {
245
+ let n = y(e);
246
+ return {
247
+ store: new b(n),
248
+ sessions: new w(n),
249
+ env: e,
250
+ secrets: /* @__PURE__ */ new Set(),
251
+ ...t
252
+ };
253
+ }
254
+ async function T(e, t) {
255
+ let { LAUNCHPAD_CONTROLLER: n, LAUNCHPAD_API_KEY: r } = e.env;
256
+ if (!t && !!n != !!r) throw new d("bad-input", "Set both LAUNCHPAD_CONTROLLER and LAUNCHPAD_API_KEY, or neither; use --profile to explicitly choose saved credentials.");
257
+ if (!t && n && r) return e.secrets?.add(r), {
258
+ profile: null,
259
+ controller: n,
260
+ apiKey: r,
261
+ organizationId: e.env.LAUNCHPAD_ORG ?? null,
262
+ fromEnvironment: !0
263
+ };
264
+ let i = await e.store.load(), a = t ?? e.env.LAUNCHPAD_PROFILE ?? i.currentProfile, o = a && Object.hasOwn(i.profiles, a) ? i.profiles[a] : void 0;
265
+ if (!a || !o) throw new d("not-logged-in", a ? `No profile named "${a}". Run: launchpad login` : "Not logged in. Run: launchpad login");
266
+ return e.secrets?.add(o.apiKey), {
267
+ profile: a,
268
+ controller: o.controller,
269
+ apiKey: o.apiKey,
270
+ organizationId: e.env.LAUNCHPAD_ORG ?? o.organizationId,
271
+ fromEnvironment: !1
272
+ };
273
+ }
274
+ function E(e, t) {
275
+ return s({
276
+ baseUrl: t.controller,
277
+ apiKey: t.apiKey,
278
+ fetch: e.fetch
279
+ });
280
+ }
281
+ var D = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,39}$/;
282
+ async function O(e, t) {
283
+ let n = t.profile ?? "default";
284
+ if (!D.test(n)) throw new d("bad-input", "A profile name is letters, digits, _ . - (40 at most).");
285
+ let r = c(t.controller);
286
+ e.secrets?.add(t.apiKey);
287
+ let i = await s({
288
+ baseUrl: r,
289
+ apiKey: t.apiKey,
290
+ fetch: e.fetch
291
+ }).key.get();
292
+ return await e.store.update((e) => {
293
+ e.profiles[n] = {
294
+ controller: r,
295
+ apiKey: t.apiKey,
296
+ organizationId: i.organizationId,
297
+ savedAt: (/* @__PURE__ */ new Date()).toISOString()
298
+ }, e.currentProfile ??= n;
299
+ }), {
300
+ profile: n,
301
+ controller: r,
302
+ key: i
303
+ };
304
+ }
305
+ async function k(e, t) {
306
+ let n = await e.store.load(), r = t ?? e.env.LAUNCHPAD_PROFILE ?? n.currentProfile;
307
+ if (!r || !Object.hasOwn(n.profiles, r)) throw new d("not-logged-in", "Nothing to log out of.");
308
+ return await e.store.update((e) => {
309
+ delete e.profiles[r], e.currentProfile === r && (e.currentProfile = Object.keys(e.profiles)[0] ?? null);
310
+ }), { profile: r };
311
+ }
312
+ async function A(e) {
313
+ let t = await e.store.load();
314
+ return {
315
+ current: t.currentProfile,
316
+ profiles: Object.entries(t.profiles).map(([e, t]) => ({
317
+ name: e,
318
+ controller: t.controller,
319
+ organizationId: t.organizationId,
320
+ savedAt: t.savedAt
321
+ }))
322
+ };
323
+ }
324
+ async function j(e, t) {
325
+ return await e.store.update((e) => {
326
+ if (!Object.hasOwn(e.profiles, t)) throw new d("not-logged-in", `No profile named "${t}".`);
327
+ e.currentProfile = t;
328
+ }), { profile: t };
329
+ }
330
+ async function re(e, t) {
331
+ let n = await T(e, t), r = await E(e, n).key.get();
332
+ return {
333
+ profile: n.profile,
334
+ controller: n.controller,
335
+ key: r
336
+ };
337
+ }
338
+ async function ie(e, t, n) {
339
+ let r = await T(e, n), i = (await E(e, r).organizations.list()).find((e) => e.id === t || e.slug === t);
340
+ if (!i) throw new d("no-organization", `This key cannot see an organization "${t}".`);
341
+ return r.profile && await e.store.update((e) => {
342
+ let t = r.profile, n = Object.hasOwn(e.profiles, t) ? e.profiles[t] : void 0;
343
+ if (!n || n.controller !== r.controller || n.apiKey !== r.apiKey) throw new d("bad-input", "The profile changed while the organization was being selected. Try again.");
344
+ n.organizationId = i.id;
345
+ }), { organization: i };
346
+ }
347
+ async function ae(e, t) {
348
+ return E(e, await T(e, t)).organizations.list();
349
+ }
350
+ async function oe(e, t) {
351
+ let n = await T(e, t), r = E(e, n), i = n.organizationId ?? (await r.key.get()).organizationId;
352
+ return r.projects.list(i);
353
+ }
354
+ // src/project.ts
355
+ var se = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
356
+ async function M(e, t, n) {
357
+ if (se.test(n)) return n.toLowerCase();
358
+ let r = (await e.projects.list(t)).find((e) => e.slug === n);
359
+ if (!r) throw new d("bad-input", `This key cannot see a project "${n}".`);
360
+ return r.id;
361
+ }
362
+ async function N(e, t, n) {
363
+ let r = await T(e, n), i = E(e, r), a = r.organizationId ?? (await i.key.get()).organizationId;
364
+ return {
365
+ organizationId: a,
366
+ projectId: await M(i, a, t)
367
+ };
368
+ }
369
+ // src/pack.ts
370
+ var P = {
371
+ maxArchiveBytes: 52428800,
372
+ maxEntries: 5e3,
373
+ maxDepth: 16
374
+ }, F = /* @__PURE__ */ new Set([
375
+ ".git",
376
+ ".svn",
377
+ ".hg",
378
+ ".ssh",
379
+ ".aws",
380
+ ".gnupg",
381
+ ".kube",
382
+ ".docker",
383
+ ".terraform"
384
+ ]), I = /* @__PURE__ */ new Set([
385
+ ".npmrc",
386
+ ".netrc",
387
+ ".htpasswd",
388
+ ".pgpass",
389
+ ".dockercfg",
390
+ ".git-credentials",
391
+ ".pypirc"
392
+ ]), L = [
393
+ /^\.env(\..*)?$/,
394
+ /^id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/,
395
+ /^service-account.*\.json$/,
396
+ /^secrets?\..*/
397
+ ], R = /* @__PURE__ */ new Set([
398
+ ".pem",
399
+ ".key",
400
+ ".p12",
401
+ ".pfx",
402
+ ".jks",
403
+ ".keystore",
404
+ ".tfstate",
405
+ ".kdbx",
406
+ ".sqlite"
407
+ ]), z = 1e5, B = (e) => JSON.stringify([...e].slice(0, 80).map((e) => /[\p{Cc}\p{Cf}]/u.test(e) ? "?" : e).join(""));
408
+ function V(e) {
409
+ throw new d("bad-input", e);
410
+ }
411
+ function H(e, t, r) {
412
+ t.length > r.maxDepth && V(`${B(e)} is nested deeper than ${r.maxDepth} levels.`);
413
+ for (let r of t) {
414
+ (/[\p{Cc}\p{Cf}\\]/u.test(r) || r.length > 255) && V(`${B(e)} has a name the controller will not accept.`);
415
+ let t = r.toLowerCase();
416
+ (F.has(t) || I.has(t) || L.some((e) => e.test(t)) || R.has(n.extname(t))) && V(`${B(e)} looks like a secret or version-control data and must not be deployed. Remove it from the directory.`);
417
+ }
418
+ }
419
+ var U = 100, W = 256;
420
+ function G(e, t) {
421
+ for (let [n, r] of [["include", e], ["exclude", t]]) {
422
+ (r.length === 0 || r.length > U) && V(`Give 1 to ${U} ${n} patterns.`);
423
+ for (let e of r) (e.length === 0 || e.length > W || /[\\\u0000-\u001f\u007f]/.test(e) || e.startsWith("/") || e.startsWith("!") || e.startsWith("#") || e.split("/").includes("..")) && V(`The ${n} pattern ${B(e)} must be a relative glob without "..", "!", backslashes or control characters.`);
424
+ }
425
+ let n = (e) => e.map((e) => e.replaceAll("[!", "[^"));
426
+ e = n(e), t = n(t);
427
+ let r = {
428
+ dot: !0,
429
+ nocomment: !0,
430
+ posixSlashes: !0
431
+ }, i = l(e, r), a = l(t, {
432
+ ...r,
433
+ nocase: !0
434
+ }), o = e.map((e) => l.scan(e).base.replace(/\/+$/, "")), s = (e) => {
435
+ let t = e.split("/");
436
+ for (let e = 1; e <= t.length; e++) {
437
+ let n = t.slice(0, e).join("/");
438
+ if (a(n) || a(`${n}/`)) return !0;
439
+ }
440
+ return !1;
441
+ };
442
+ return {
443
+ selects: (e) => i(e) && !s(e),
444
+ mayContain: (e) => !s(e) && o.some((t) => t === "" || e === t || e.startsWith(`${t}/`) || t.startsWith(`${e}/`))
445
+ };
446
+ }
447
+ async function K(e, t = P, r, i) {
448
+ let a = n.resolve(e), s = r && G(r.include, r.exclude), c = (e) => r.prefix ? `${r.prefix}/${e}` : e;
449
+ r?.prefix && H(r.prefix, r.prefix.split("/"), {
450
+ ...t,
451
+ maxDepth: 1e9
452
+ });
453
+ let l = await o.lstat(a).catch(() => void 0);
454
+ l || V(`${B(e)} does not exist.`), (l.isSymbolicLink() || !l.isDirectory()) && V(`${B(e)} is not a directory.`);
455
+ let d = [], f = 0, p = 0, m = async (e) => {
456
+ i?.throwIfAborted();
457
+ let l = await o.readdir(n.join(a, e), { withFileTypes: !0 });
458
+ l.sort((e, t) => e.name.localeCompare(t.name));
459
+ for (let i of l) {
460
+ ++p > z && V(`The directory holds more than ${z} entries to look through. Deploy a smaller directory.`);
461
+ let l = e === "" ? i.name : `${e}/${i.name}`, u = l.split("/");
462
+ if (i.isDirectory()) {
463
+ if (s && !s.mayContain(c(l))) continue;
464
+ s || H(l, u, t), (await o.lstat(n.join(a, l))).isDirectory() || V(`${B(l)} changed while it was being read.`), await m(l);
465
+ continue;
466
+ }
467
+ if (s && !s.selects(c(l))) continue;
468
+ H(l, u, t);
469
+ let h = n.join(a, l);
470
+ for (let e of r?.protectedPaths ?? []) {
471
+ let t = n.relative(e, h);
472
+ t !== ".." && !t.startsWith(`..${n.sep}`) && !n.isAbsolute(t) && V(`${B(l)} is in this client's credential store and must not be deployed.`);
473
+ }
474
+ if (i.isFile()) {
475
+ d.push(l), d.length > t.maxEntries && V(`The directory has more than ${t.maxEntries} files.`);
476
+ let e = await o.lstat(n.join(a, l));
477
+ e.isFile() || V(`${B(l)} changed while it was being read.`), f += e.size;
478
+ } else V(`${B(l)} is not a regular file (links and special files are refused).`);
479
+ }
480
+ };
481
+ await m(""), d.includes("index.html") || V(s ? "The selected files have no index.html at the top level of the directory." : "The directory has no index.html at its top level.");
482
+ let h = new u({
483
+ gzip: !0,
484
+ cwd: a,
485
+ portable: !0,
486
+ noPax: !1,
487
+ follow: !1
488
+ });
489
+ for (let e of d) h.add(e);
490
+ h.end();
491
+ let g = [], _ = 0;
492
+ for await (let e of h) i?.throwIfAborted(), _ += e.length, _ > t.maxArchiveBytes && V(`The packed archive is larger than ${Math.floor(t.maxArchiveBytes / 1048576)} MiB.`), g.push(e);
493
+ return {
494
+ archive: Buffer.concat(g),
495
+ files: d.length,
496
+ bytes: f
497
+ };
498
+ }
499
+ function ce(e, t = []) {
500
+ n.resolve(e).split(n.sep).some((e) => F.has(e.toLowerCase())) && V("That directory is inside credential or version-control data and cannot be deployed.");
501
+ for (let r of t) {
502
+ let t = n.relative(r, e);
503
+ !(t === ".." || t.startsWith(`..${n.sep}`)) && !n.isAbsolute(t) && V("That directory holds this client's credentials and cannot be deployed.");
504
+ }
505
+ }
506
+ async function le(e, t = P) {
507
+ let n = await o.lstat(e).catch(() => void 0);
508
+ n?.isFile() || V(`${B(e)} is not a file.`);
509
+ let r = () => V(`${B(e)} is larger than ${Math.floor(t.maxArchiveBytes / 1048576)} MiB.`);
510
+ n.size > t.maxArchiveBytes && r();
511
+ let i = await o.open(e, a.O_RDONLY | (a.O_NOFOLLOW ?? 0)).catch(() => V(`${B(e)} cannot be read as a plain file.`));
512
+ try {
513
+ let n = await i.stat();
514
+ n.isFile() || V(`${B(e)} is not a file.`), n.size > t.maxArchiveBytes && r();
515
+ let a = [], o = 0;
516
+ for (;;) {
517
+ let e = Buffer.allocUnsafe(65536), { bytesRead: n } = await i.read(e, 0, e.length, null);
518
+ if (n === 0) break;
519
+ o += n, o > t.maxArchiveBytes && r(), a.push(e.subarray(0, n));
520
+ }
521
+ return {
522
+ archive: Buffer.concat(a),
523
+ files: 0,
524
+ bytes: o
525
+ };
526
+ } finally {
527
+ await i.close();
528
+ }
529
+ }
530
+ // src/workspace.ts
531
+ var q = r.string().trim().min(1).max(128), ue = r.strictObject({
532
+ profile: r.string().regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,39}$/).optional(),
533
+ organization: q,
534
+ project: q
535
+ });
536
+ function de(e, t) {
537
+ return t === void 0 || e === t;
538
+ }
539
+ function J() {
540
+ throw new d("bad-input", "launchpad.json must be a regular, non-symlink JSON file (16 KiB at most) with organization, project, and optional profile.");
541
+ }
542
+ async function fe(e) {
543
+ let t = await o.lstat(e).catch((e) => e.code === "ENOENT" ? null : J());
544
+ if (!t || (t.isFile() || J(), !de(t.uid, process.getuid?.()))) return null;
545
+ let n = await o.open(e, a.O_RDONLY | (a.O_NOFOLLOW ?? 0) | (a.O_NONBLOCK ?? 0)).catch((e) => e.code === "ENOENT" ? null : J());
546
+ if (!n) return null;
547
+ try {
548
+ let e = await n.stat();
549
+ (!e.isFile() || e.size > 16384 || e.dev !== t.dev || e.ino !== t.ino) && J();
550
+ let r = Buffer.alloc(16385), i = 0;
551
+ for (; i < r.length;) {
552
+ let e = await n.read(r, i, r.length - i, null);
553
+ if (!e.bytesRead) break;
554
+ i += e.bytesRead;
555
+ }
556
+ i > 16384 && J();
557
+ let a = ue.safeParse(JSON.parse(r.subarray(0, i).toString("utf8")));
558
+ return a.success || J(), a.data;
559
+ } catch {
560
+ return J();
561
+ } finally {
562
+ await n.close();
563
+ }
564
+ }
565
+ async function Y(e) {
566
+ if (!n.isAbsolute(e)) throw new d("bad-input", "working_dir must be an absolute existing directory.");
567
+ let t = await o.realpath(e).catch(() => null);
568
+ if (!t || !(await o.stat(t)).isDirectory()) throw new d("bad-input", "working_dir must be an absolute existing directory.");
569
+ let r = t;
570
+ for (;;) {
571
+ let e = await fe(n.join(r, "launchpad.json"));
572
+ if (e) return {
573
+ directory: t,
574
+ config: e
575
+ };
576
+ let i = n.dirname(r);
577
+ if (i === r) return {
578
+ directory: t,
579
+ config: null
580
+ };
581
+ r = i;
582
+ }
583
+ }
584
+ async function X(e, t) {
585
+ let n = await Y(t.workingDir), r = t.profile ?? n.config?.profile ?? t.defaultProfile, i = t.organization ?? n.config?.organization, a = e;
586
+ if (i) {
587
+ let t = await T(e, r);
588
+ r ??= t.profile ?? void 0;
589
+ let n = (await E(e, t).organizations.list()).find((e) => e.id === i || e.slug === i);
590
+ if (!n) throw new d("no-organization", "This key cannot see the selected organization.");
591
+ a = {
592
+ ...e,
593
+ env: {
594
+ ...e.env,
595
+ LAUNCHPAD_ORG: n.id
596
+ }
597
+ };
598
+ }
599
+ return {
600
+ context: a,
601
+ profile: r,
602
+ project: t.project ?? n.config?.project,
603
+ directory: n.directory,
604
+ organization: i
605
+ };
606
+ }
607
+ // src/app-client.ts
608
+ async function pe(e, t) {
609
+ let n = await T(e, t), r = E(e, n);
610
+ return {
611
+ client: r,
612
+ organizationId: n.organizationId ?? (await r.key.get()).organizationId
613
+ };
614
+ }
615
+ function me(e) {
616
+ if (e !== !0) throw new d("bad-input", "Confirm this change explicitly before proceeding.");
617
+ }
618
+ async function he({ client: e, organizationId: t }, n, r) {
619
+ let i = await e.apps.get(t, n);
620
+ if (i.id !== n || !r.includes(i.projectId)) throw new d("bad-input", "The app is outside the configured projects.");
621
+ return i;
622
+ }
623
+ // src/fields.ts
624
+ var Z = 200, ge = 8, _e = /^([^[\]=]+)((?:\[[^[\]=]*\])*)$/, Q = (e) => new d("bad-input", e);
625
+ async function ve(e, t, n) {
626
+ let r = n.fill ?? ((e) => e);
627
+ if (!e.typed) return r(t);
628
+ if (t === "true") return !0;
629
+ if (t === "false") return !1;
630
+ if (t === "null") return null;
631
+ if (/^-?\d+$/.test(t) && Number.isSafeInteger(Number(t))) return Number(t);
632
+ if (t.startsWith("@")) {
633
+ let e = t.slice(1);
634
+ if (!e) throw Q("A field value of @ needs a file path, or @- for standard input.");
635
+ return e === "-" ? n.readStdin() : n.readFile(e);
636
+ }
637
+ return r(t);
638
+ }
639
+ async function ye(e, t) {
640
+ if (e.length > Z) throw Q(`At most ${Z} fields are accepted.`);
641
+ let n = Object.create(null);
642
+ for (let r of e) {
643
+ let e = r.text.indexOf("="), i = e === -1 ? r.text : r.text.slice(0, e), a = _e.exec(i);
644
+ if (!a) throw Q(`The field "${i.slice(0, 40)}" is not a valid parameter name.`);
645
+ let o = [a[1], ...[...a[2].matchAll(/\[([^[\]]*)\]/g)].map((e) => e[1])];
646
+ if (o.length > ge) throw Q("A field is nested too deeply.");
647
+ if (o.some((e) => e === "__proto__" || e === "constructor" || e === "prototype")) throw Q("That parameter name is not allowed.");
648
+ if (e === -1 && o[o.length - 1] !== "") throw Q(`The field "${i.slice(0, 40)}" needs a value (key=value).`);
649
+ if (o.slice(0, -1).includes("")) throw Q("An array marker [] is allowed only at the end of a field name.");
650
+ let s = e === -1 ? void 0 : await ve(r, r.text.slice(e + 1), t), c = n;
651
+ for (let e = 0; e < o.length - 1; e++) {
652
+ let t = o[e];
653
+ if (e === o.length - 2 && o[e + 1] === "") {
654
+ let e = c[t];
655
+ if (e === void 0) c[t] = [];
656
+ else if (!Array.isArray(e)) throw Q(`The field "${t}" is used twice.`);
657
+ s !== void 0 && c[t].push(s), c = n;
658
+ break;
659
+ }
660
+ let r = c[t];
661
+ if (r === void 0) c = c[t] = Object.create(null);
662
+ else if (typeof r == "object" && r && !Array.isArray(r)) c = r;
663
+ else throw Q(`The field "${t}" is used twice.`);
664
+ }
665
+ if (o.length === 1) {
666
+ if (Object.hasOwn(n, o[0]) && n[o[0]] !== void 0) throw Q(`The field "${o[0]}" is used twice.`);
667
+ n[o[0]] = s;
668
+ } else if (o[o.length - 1] !== "") {
669
+ let e = o[o.length - 1];
670
+ if (Object.hasOwn(c, e)) throw Q(`The field "${e}" is used twice.`);
671
+ c[e] = s;
672
+ }
673
+ }
674
+ return n;
675
+ }
676
+ function $(e, t = "") {
677
+ let n = [];
678
+ for (let [r, i] of Object.entries(e)) {
679
+ let e = t ? `${t}[${r}]` : r;
680
+ if (Array.isArray(i)) for (let t of i) n.push([`${e}[]`, String(t)]);
681
+ else typeof i == "object" && i ? n.push(...$(i, e)) : n.push([e, String(i)]);
682
+ }
683
+ return n;
684
+ }
685
+ export { d as ClientCoreError, b as CredentialStore, P as DEFAULT_PACK_LIMITS, w as SessionStore, pe as appClient, ce as checkLocation, he as checkedApp, E as clientFor, G as compileSelection, y as configDirectory, ne as createContext, $ as fieldsToQuery, ae as listOrganizations, A as listProfiles, oe as listProjects, O as login, k as logout, x as normalizeEmail, K as packDirectory, ye as parseFields, le as readArchive, Y as readWorkspace, f as redact, p as redactSecrets, me as requireConfirmation, T as resolve, N as resolveProject, m as safeOutput, ie as useOrganization, j as useProfile, re as whoami, X as workspaceContext };