sandcovery 0.5.0 → 0.5.1

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.
@@ -1,8 +1,14 @@
1
- import { Bn as toMillis, Bt as retry, Cn as ClockRef, En as currentTimeMillis$1, Kt as suspend, Ln as TaggedError, Mr as hasProperty, Rn as millis, St as flatMap, Yt as tapError, bt as fail, ht as catchTag, nn as void_, on as spaced, ot as acquireUseRelease, pt as catchDefect, qt as sync, sn as upTo, vt as die, zn as seconds } from "./Schema-fLas6rbA.mjs";
2
- import { D as CARD_FEE_TERMS, M as NO_MARKUP_TERMS, O as CREDIT_PURCHASE_MAX_MICRO_USD, _ as SandboxStatus, c as SpendLimit, j as MICRO_USD_PER_DOLLAR, k as CREDIT_PURCHASE_MIN_MICRO_USD, o as KeyKind, x as ProviderSort, y as DEFAULT_SLUG } from "./origin-5maEGWRg.mjs";
1
+ import { Bn as TaggedError, Br as isString, Ct as fail, E as decodeUnknownSync, En as ClockRef, Hn as seconds, Ir as hasProperty, Jn as isSuccess, O as fromJsonString, Qt as tapError, Tt as flatMap, Un as toMillis, Ut as retry, Vn as millis, Xt as sync, Yn as try_, Yt as suspend, _ as String$1, an as void_, ar as getOrThrowWith, cr as isSome, g as Record, gt as catchDefect, h as Number$1, kn as currentTimeMillis$1, ln as spaced, lt as acquireUseRelease, m as NullOr, n as Boolean, rr as getOrElse, sr as isNone, t as ArraySchema, u as Literals, un as upTo, ur as map, v as Struct, vt as catchTag, w as decodeUnknownOption, xt as die } from "./Schema-CoX0a2_o.mjs";
2
+ import { C as NotFound, D as Forbidden, E as SandboxStatus, F as CREDIT_PURCHASE_MIN_MICRO_USD, M as ProviderSort, N as CARD_FEE_TERMS, O as Conflict, P as CREDIT_PURCHASE_MAX_MICRO_USD, R as MICRO_USD_PER_DOLLAR, S as Unauthorized, _ as KeyKind, h as SANDCOVERY_X_HANDLE, j as DEFAULT_SLUG, l as MONTH_TEXT, t as Sandcovery, v as SpendLimit, x as Unsupported, z as NO_MARKUP_TERMS } from "./src-BoT9S6C3.mjs";
3
+ import { WebSocket } from "node:http";
4
+ import net from "node:net";
5
+ import readline from "node:readline";
6
+ import { spawn } from "node:child_process";
7
+ import crypto$1, { createHash } from "node:crypto";
8
+ import { once } from "node:events";
3
9
  import fs from "node:fs";
4
10
  import path from "node:path";
5
- import crypto from "node:crypto";
11
+ import { text } from "node:stream/consumers";
6
12
  import os from "node:os";
7
13
  // ../../node_modules/.pnpm/effect@4.1.1/node_modules/effect/dist/Clock.js
8
14
  /**
@@ -85,6 +91,328 @@ const Clock = ClockRef;
85
91
  * @since 2.0.0
86
92
  */
87
93
  const currentTimeMillis = currentTimeMillis$1;
94
+ // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/function/noop.mjs
95
+ /**
96
+ * A no-operation function that does nothing.
97
+ * This can be used as a placeholder or default function.
98
+ *
99
+ * @example
100
+ * noop(); // Does nothing
101
+ *
102
+ * @returns This function does not return anything.
103
+ */
104
+ function noop() {}
105
+ // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/math/clamp.mjs
106
+ /**
107
+ * Clamps a number within the specified bounds.
108
+ *
109
+ * This function takes a number and one or two bounds, and returns the number clamped within the specified bounds.
110
+ * If only one bound is provided, it returns the minimum of the value and the bound.
111
+ *
112
+ * @param value - The number to clamp.
113
+ * @param bound1 - The minimum bound to clamp the number, or the maximum bound if bound2 is not provided.
114
+ * @param [bound2] - The maximum bound to clamp the number. If not provided, the function will only consider bound1 as the upper limit.
115
+ * @returns The clamped number within the specified bounds.
116
+ *
117
+ * @example
118
+ * const result1 = clamp(10, 5); // result1 will be 5, as 10 is clamped to the bound 5
119
+ * const result2 = clamp(10, 5, 15); // result2 will be 10, as it is within the bounds 5 and 15
120
+ * const result3 = clamp(2, 5, 15); // result3 will be 5, as 2 is clamped to the lower bound 5
121
+ * const result4 = clamp(20, 5, 15); // result4 will be 15, as 20 is clamped to the upper bound 15
122
+ */
123
+ function clamp(value, bound1, bound2) {
124
+ if (bound2 == null) return Math.min(value, bound1);
125
+ return Math.min(Math.max(value, bound1), bound2);
126
+ }
127
+ // src/cli/detached.ts
128
+ const READY = "ready\n";
129
+ const PRIVATE_DIRECTORY_MODE = 448;
130
+ const PRIVATE_SOCKET_MODE = 384;
131
+ const TERMINAL_ERRORS = [
132
+ NotFound,
133
+ Unauthorized,
134
+ Forbidden,
135
+ Conflict,
136
+ Unsupported
137
+ ];
138
+ const decodeUnserved = decodeUnknownOption(Struct({ code: Literals([
139
+ "ECONNREFUSED",
140
+ "ECONNRESET",
141
+ "ENOENT"
142
+ ]) }));
143
+ const isTerminal = (cause) => TERMINAL_ERRORS.some((kind) => cause instanceof kind);
144
+ const socketOf = ({ name, settingsFile }) => {
145
+ const directory = path.dirname(settingsFile);
146
+ if (process.platform !== "win32") return path.join(directory, `${name}.sock`);
147
+ const digest = createHash("sha256").update(directory).digest("hex");
148
+ return String.raw`\\.\pipe\sandcovery-${name}-${digest.slice(0, 16)}`;
149
+ };
150
+ const answers = async (socketPath) => {
151
+ const socket = net.connect(socketPath);
152
+ try {
153
+ await once(socket, "connect");
154
+ return true;
155
+ } catch (error) {
156
+ if (isSome(decodeUnserved(error))) return false;
157
+ throw error;
158
+ } finally {
159
+ socket.destroy();
160
+ }
161
+ };
162
+ const listened = async (server, socketPath) => {
163
+ const { promise, resolve } = Promise.withResolvers();
164
+ server.once("error", resolve);
165
+ server.listen(socketPath, () => {
166
+ server.off("error", resolve);
167
+ resolve(void 0);
168
+ });
169
+ return await promise;
170
+ };
171
+ const servedAt = async (server, socketPath) => {
172
+ const windows = process.platform === "win32";
173
+ if (!windows) {
174
+ const directory = path.dirname(socketPath);
175
+ fs.mkdirSync(directory, {
176
+ mode: PRIVATE_DIRECTORY_MODE,
177
+ recursive: true
178
+ });
179
+ fs.chmodSync(directory, PRIVATE_DIRECTORY_MODE);
180
+ }
181
+ const failure = await listened(server, socketPath);
182
+ if (failure === void 0) {
183
+ if (!windows) fs.chmodSync(socketPath, PRIVATE_SOCKET_MODE);
184
+ return true;
185
+ }
186
+ if (failure.code !== "EADDRINUSE" || windows || await answers(socketPath)) return false;
187
+ fs.rmSync(socketPath, { force: true });
188
+ return await servedAt(server, socketPath);
189
+ };
190
+ const spawned = async ({ entry, env }) => {
191
+ const child = spawn(process.execPath, [entry], {
192
+ detached: true,
193
+ env: {
194
+ ...process.env,
195
+ ...env
196
+ },
197
+ stdio: [
198
+ "ignore",
199
+ "pipe",
200
+ "ignore"
201
+ ]
202
+ });
203
+ try {
204
+ await Promise.race([once(child.stdout, "data"), once(child, "exit")]);
205
+ } finally {
206
+ child.stdout.destroy();
207
+ child.unref();
208
+ }
209
+ };
210
+ const servedOrSpawned = async ({ attempt, entry, env }) => {
211
+ try {
212
+ return await attempt();
213
+ } catch (error) {
214
+ if (isNone(decodeUnserved(error))) throw error;
215
+ await spawned({
216
+ entry,
217
+ env
218
+ });
219
+ return await attempt();
220
+ }
221
+ };
222
+ // src/cli/kubectl-idle.ts
223
+ const IDLE_WATCHER_ENV = "__SANDCOVERY_KUBECTL_IDLE";
224
+ const IDLE_MS = 9e5;
225
+ const HEARTBEAT_MS = 6e4;
226
+ const DESTROY_TIMEOUT_MS = 3e4;
227
+ const REFUSED_STATUSES = /* @__PURE__ */ new Set([
228
+ 400,
229
+ 401,
230
+ 403,
231
+ 404,
232
+ 409,
233
+ 410,
234
+ 422
235
+ ]);
236
+ const decodeWatcher = decodeUnknownSync(fromJsonString(Struct({
237
+ idleMs: Number$1,
238
+ socketPath: String$1
239
+ })));
240
+ const decodeHold = decodeUnknownOption(fromJsonString(Struct({ origin: String$1 })));
241
+ const decodeAnswered = decodeUnknownOption(Struct({ cause: Struct({ status: Number$1 }) }));
242
+ const decodeCluster = decodeUnknownOption(fromJsonString(Struct({
243
+ expires_at: String$1,
244
+ key: String$1,
245
+ sandbox: String$1
246
+ })));
247
+ const idleSocket = (settingsFile) => socketOf({
248
+ name: "kubectl-idle",
249
+ settingsFile
250
+ });
251
+ const statusOf$1 = (failure) => getOrElse(map(decodeAnswered(failure), ({ cause }) => cause.status), () => 0);
252
+ const refused = (failure) => isTerminal(failure) || REFUSED_STATUSES.has(statusOf$1(failure));
253
+ const deadlinesOf = ({ cluster, destroying, due, holders }) => cluster === null ? [] : [cluster.expiresAt, ...holders === 0 && destroying === null ? [due] : []];
254
+ const ended = async ({ cluster, origin }) => {
255
+ try {
256
+ await new Sandcovery({
257
+ apiKey: cluster.key,
258
+ baseUrl: origin
259
+ }).sandboxes.destroy(cluster.sandbox, { signal: AbortSignal.timeout(DESTROY_TIMEOUT_MS) });
260
+ return true;
261
+ } catch (error) {
262
+ if (!(error instanceof Error)) throw error;
263
+ return refused(error);
264
+ }
265
+ };
266
+ const destroyed = async ({ entry, origin, settle }) => {
267
+ const { cluster } = entry;
268
+ if (cluster !== null && await ended({
269
+ cluster,
270
+ origin
271
+ })) {
272
+ if (entry.cluster?.sandbox === cluster.sandbox) entry.cluster = null;
273
+ } else entry.due = Date.now() + HEARTBEAT_MS;
274
+ entry.destroying = null;
275
+ settle();
276
+ };
277
+ const attached = (entry, line) => {
278
+ const cluster = decodeCluster(line);
279
+ if (isNone(cluster)) return false;
280
+ const { expires_at, key, sandbox } = cluster.value;
281
+ const expiresAt = Date.parse(expires_at);
282
+ if (Number.isNaN(expiresAt)) return false;
283
+ entry.cluster = {
284
+ expiresAt,
285
+ key,
286
+ sandbox
287
+ };
288
+ return true;
289
+ };
290
+ const watchIdle = async (config) => {
291
+ const { idleMs, socketPath } = decodeWatcher(config);
292
+ const watched = /* @__PURE__ */ new Map();
293
+ const listener = net.createServer();
294
+ const state = {
295
+ connections: 0,
296
+ timer: null
297
+ };
298
+ const check = () => {
299
+ const now = Date.now();
300
+ if (state.timer !== null) clearTimeout(state.timer);
301
+ for (const [origin, entry] of watched) {
302
+ if (entry.cluster !== null && now >= entry.cluster.expiresAt) entry.cluster = null;
303
+ if (entry.cluster !== null && entry.holders === 0 && entry.destroying === null && now >= entry.due) entry.destroying = destroyed({
304
+ entry,
305
+ origin,
306
+ settle: check
307
+ });
308
+ if (entry.cluster === null && entry.holders === 0 && entry.destroying === null) watched.delete(origin);
309
+ }
310
+ if (state.connections === 0 && watched.size === 0) {
311
+ listener.close();
312
+ return;
313
+ }
314
+ const next = Math.min(now + HEARTBEAT_MS, ...[...watched.values()].flatMap(deadlinesOf));
315
+ state.timer = setTimeout(check, clamp(next - now, 0, HEARTBEAT_MS));
316
+ };
317
+ const held = async (connection, origin) => {
318
+ const entry = watched.get(origin) ?? {
319
+ cluster: null,
320
+ destroying: null,
321
+ due: Date.now() + idleMs,
322
+ holders: 0
323
+ };
324
+ entry.holders += 1;
325
+ watched.set(origin, entry);
326
+ await entry.destroying;
327
+ connection.write(READY);
328
+ return entry;
329
+ };
330
+ listener.on("connection", (connection) => {
331
+ const hold = { entry: null };
332
+ const lines = readline.createInterface({ input: connection });
333
+ state.connections += 1;
334
+ connection.on("error", noop);
335
+ const received = async (line) => {
336
+ if (hold.entry !== null) {
337
+ if (!attached(await hold.entry, line)) connection.destroy();
338
+ return;
339
+ }
340
+ const asked = decodeHold(line);
341
+ if (isNone(asked)) {
342
+ connection.destroy();
343
+ return;
344
+ }
345
+ hold.entry = held(connection, asked.value.origin);
346
+ };
347
+ const released = async () => {
348
+ const entry = await hold.entry;
349
+ state.connections -= 1;
350
+ lines.close();
351
+ if (entry !== null) {
352
+ entry.holders -= 1;
353
+ entry.due = Date.now() + idleMs;
354
+ }
355
+ check();
356
+ };
357
+ lines.on("line", (line) => {
358
+ received(line);
359
+ });
360
+ connection.once("close", () => {
361
+ released();
362
+ });
363
+ });
364
+ const serving = await servedAt(listener, socketPath);
365
+ process.stdout.write(READY);
366
+ if (serving) state.timer = setTimeout(check, HEARTBEAT_MS);
367
+ };
368
+ const connected = async (socketPath) => {
369
+ const socket = net.connect(socketPath);
370
+ const { promise, reject, resolve } = Promise.withResolvers();
371
+ socket.once("connect", () => {
372
+ resolve(socket);
373
+ });
374
+ socket.once("error", reject);
375
+ return await promise;
376
+ };
377
+ const readied = async (socket) => {
378
+ const { promise, reject, resolve } = Promise.withResolvers();
379
+ socket.once("data", () => {
380
+ resolve(null);
381
+ });
382
+ socket.once("close", () => {
383
+ reject(/* @__PURE__ */ new Error("The idle watcher stopped before it answered."));
384
+ });
385
+ await promise;
386
+ };
387
+ const holdCluster = async ({ entry, origin, settingsFile }) => {
388
+ const socketPath = idleSocket(settingsFile);
389
+ const socket = await servedOrSpawned({
390
+ attempt: async () => await connected(socketPath),
391
+ entry,
392
+ env: { [IDLE_WATCHER_ENV]: JSON.stringify({
393
+ idleMs: IDLE_MS,
394
+ socketPath
395
+ }) }
396
+ });
397
+ socket.on("error", noop);
398
+ const ready = readied(socket);
399
+ socket.write(`${JSON.stringify({ origin })}\n`);
400
+ try {
401
+ await ready;
402
+ } catch (error) {
403
+ socket.destroy();
404
+ throw error;
405
+ }
406
+ return {
407
+ attach: (cluster) => {
408
+ socket.write(`${JSON.stringify(cluster)}\n`);
409
+ },
410
+ release: () => {
411
+ socket.end();
412
+ socket.unref();
413
+ }
414
+ };
415
+ };
88
416
  // ../cli-core/src/canceled.ts
89
417
  var Canceled = class extends TaggedError("Canceled") {};
90
418
  // ../cli-core/src/failure.ts
@@ -136,11 +464,13 @@ const reasons = {
136
464
  missing_key: "missing_input",
137
465
  missing_path: "missing_input",
138
466
  missing_port: "missing_input",
467
+ missing_process: "missing_input",
139
468
  missing_provider: "missing_input",
140
469
  missing_query: "missing_input",
141
470
  missing_run: "missing_input",
142
471
  missing_sandbox: "missing_input",
143
472
  missing_site: "missing_input",
473
+ missing_url: "missing_input",
144
474
  missing_value: "missing_input",
145
475
  mode_not_entitled: "conflict",
146
476
  network_error: "network",
@@ -190,17 +520,6 @@ const isWordCharacter = (character) => isDigit(character) || isUpper(character)
190
520
  const consistsOf = (text, allowed) => text !== "" && text.split("").every(allowed);
191
521
  const isDigits = (text) => consistsOf(text, isDigit);
192
522
  const codePoints = (text) => Array.from(text, (point) => point);
193
- // ../../node_modules/.pnpm/es-toolkit@1.53.1/node_modules/es-toolkit/dist/function/noop.mjs
194
- /**
195
- * A no-operation function that does nothing.
196
- * This can be used as a placeholder or default function.
197
- *
198
- * @example
199
- * noop(); // Does nothing
200
- *
201
- * @returns This function does not return anything.
202
- */
203
- function noop() {}
204
523
  // ../cli-core/src/sanitize.ts
205
524
  const ESC = 27;
206
525
  const BEL = 7;
@@ -752,7 +1071,7 @@ const writePrivateFile = ({ file, text }) => {
752
1071
  mode: 448,
753
1072
  recursive: true
754
1073
  });
755
- const pending = path.join(directory, `.${path.basename(file)}.${crypto.randomBytes(8).toString("hex")}.tmp`);
1074
+ const pending = path.join(directory, `.${path.basename(file)}.${crypto$1.randomBytes(8).toString("hex")}.tmp`);
756
1075
  fs.writeFileSync(pending, text, {
757
1076
  flag: "wx",
758
1077
  mode: 384
@@ -804,15 +1123,132 @@ const withFileLock = ({ bin, file, work }) => {
804
1123
  }), () => work, (own) => removeIf(lock, sameAs(own)));
805
1124
  };
806
1125
  // package.json
807
- var version = "0.5.0";
1126
+ var version = "0.5.1";
1127
+ // ../format/src/display.ts
1128
+ const LOCALE = "en-US";
1129
+ const UTC = "UTC";
1130
+ new Intl.DateTimeFormat(LOCALE, {
1131
+ day: "numeric",
1132
+ month: "short",
1133
+ timeZone: UTC,
1134
+ year: "numeric"
1135
+ });
1136
+ new Intl.DateTimeFormat(LOCALE, {
1137
+ day: "numeric",
1138
+ month: "long",
1139
+ timeZone: UTC,
1140
+ year: "numeric"
1141
+ });
1142
+ new Intl.DateTimeFormat(LOCALE, {
1143
+ hour: "numeric",
1144
+ minute: "2-digit",
1145
+ timeZone: UTC,
1146
+ timeZoneName: "short"
1147
+ });
1148
+ new Intl.DateTimeFormat(LOCALE, {
1149
+ month: "long",
1150
+ timeZone: UTC,
1151
+ year: "numeric"
1152
+ });
1153
+ new Intl.DateTimeFormat(LOCALE, {
1154
+ day: "numeric",
1155
+ month: "short",
1156
+ timeZone: UTC
1157
+ });
1158
+ const monthName = new Intl.DateTimeFormat(LOCALE, {
1159
+ month: "long",
1160
+ timeZone: UTC
1161
+ });
1162
+ Array.from({ length: 12 }, (_, month) => monthName.format(Date.UTC(2e3, month)));
1163
+ new Intl.DateTimeFormat(LOCALE, {
1164
+ day: "numeric",
1165
+ hour: "numeric",
1166
+ minute: "2-digit",
1167
+ month: "short",
1168
+ timeZone: "America/New_York",
1169
+ timeZoneName: "short",
1170
+ year: "numeric"
1171
+ });
1172
+ new Intl.DateTimeFormat(LOCALE, {
1173
+ day: "2-digit",
1174
+ hour: "2-digit",
1175
+ hourCycle: "h23",
1176
+ minute: "2-digit",
1177
+ month: "2-digit",
1178
+ timeZoneName: "short",
1179
+ year: "numeric"
1180
+ });
1181
+ const moneyFormats = {
1182
+ exact: new Intl.NumberFormat(LOCALE, {
1183
+ currency: "USD",
1184
+ maximumFractionDigits: 2,
1185
+ minimumFractionDigits: 2,
1186
+ style: "currency"
1187
+ }),
1188
+ signed: new Intl.NumberFormat(LOCALE, {
1189
+ currency: "USD",
1190
+ maximumFractionDigits: 2,
1191
+ minimumFractionDigits: 2,
1192
+ signDisplay: "exceptZero",
1193
+ style: "currency"
1194
+ }),
1195
+ subcent: new Intl.NumberFormat(LOCALE, {
1196
+ currency: "USD",
1197
+ maximumSignificantDigits: 3,
1198
+ style: "currency"
1199
+ }),
1200
+ trimmed: new Intl.NumberFormat(LOCALE, {
1201
+ currency: "USD",
1202
+ style: "currency",
1203
+ trailingZeroDisplay: "stripIfInteger"
1204
+ }),
1205
+ whole: new Intl.NumberFormat(LOCALE, {
1206
+ currency: "USD",
1207
+ maximumFractionDigits: 0,
1208
+ style: "currency"
1209
+ })
1210
+ };
1211
+ const formatMoney = ({ cents, style }) => moneyFormats[style].format(cents / 100);
1212
+ const countFormats = {
1213
+ compact: new Intl.NumberFormat(LOCALE, {
1214
+ maximumFractionDigits: 1,
1215
+ notation: "compact"
1216
+ }),
1217
+ whole: new Intl.NumberFormat(LOCALE, { maximumFractionDigits: 0 })
1218
+ };
1219
+ const formatCount = ({ count, style = "whole" }) => countFormats[style].format(count);
1220
+ const plural = new Intl.PluralRules(LOCALE);
1221
+ const counted = ({ count, one, other }) => `${formatCount({ count })} ${plural.select(count) === "one" ? one : other}`;
1222
+ const unitFormat = ({ unit }) => new Intl.NumberFormat(LOCALE, {
1223
+ style: "unit",
1224
+ unit,
1225
+ unitDisplay: "long"
1226
+ });
1227
+ unitFormat({ unit: "hour" }), unitFormat({ unit: "minute" }), unitFormat({ unit: "month" }), unitFormat({ unit: "second" });
1228
+ const percentFormats = {
1229
+ rate: new Intl.NumberFormat(LOCALE, {
1230
+ maximumFractionDigits: 2,
1231
+ minimumFractionDigits: 2,
1232
+ style: "percent"
1233
+ }),
1234
+ whole: new Intl.NumberFormat(LOCALE, {
1235
+ maximumFractionDigits: 0,
1236
+ style: "percent"
1237
+ })
1238
+ };
1239
+ const formatPercent = ({ rate, style }) => percentFormats[style].format(rate);
1240
+ // ../sandcovery-contract/src/problem-report-limits.ts
1241
+ const PROBLEM_REPORT_MAX = 2e3;
808
1242
  // src/cli/spec.ts
809
1243
  const BIN = "sandcovery";
810
1244
  const SETUP_MARK = "# added by sandcovery setup";
811
1245
  const NULLABLE_TEXT = "string | null";
812
1246
  const NULLABLE_NUMBER = "number | null";
1247
+ const NULLABLE_OBJECT = "object | null";
813
1248
  const SANDBOX = "<SANDBOX>";
814
1249
  const SPEND_LIMIT = "spend-limit";
815
1250
  const NEEDS_MANAGEMENT = "Needs a management key.";
1251
+ const NEEDS_PERSON = "Needs a management key, which acts for the owner who minted it, or a login.";
816
1252
  const CLEARABLE = {
817
1253
  "expires-at": "expires_at",
818
1254
  "max-concurrent": "max_concurrent_sandboxes",
@@ -1226,6 +1662,30 @@ const sandboxesExec = {
1226
1662
  "2>&1"
1227
1663
  ],
1228
1664
  summary: "Start a server that keeps running after the CLI exits"
1665
+ },
1666
+ {
1667
+ argv: [
1668
+ "sandboxes",
1669
+ "exec",
1670
+ SANDBOX,
1671
+ "--interactive",
1672
+ "--tty",
1673
+ "--",
1674
+ "bash"
1675
+ ],
1676
+ summary: "Open a shell in the sandbox"
1677
+ },
1678
+ {
1679
+ argv: [
1680
+ "sandboxes",
1681
+ "exec",
1682
+ SANDBOX,
1683
+ "--interactive",
1684
+ "--",
1685
+ "wc",
1686
+ "-l"
1687
+ ],
1688
+ summary: "Count the lines piped to the CLI"
1229
1689
  }
1230
1690
  ],
1231
1691
  kind: "leaf",
@@ -1234,6 +1694,7 @@ const sandboxesExec = {
1234
1694
  "The command's stdout and stderr stream to this terminal's, and the CLI exits with the command's exit code.",
1235
1695
  "With --json, the CLI waits for the command and prints its stdout, stderr, exit code, and duration as one document.",
1236
1696
  "With --detach, the CLI returns once the provider starts the command, which keeps running until it exits or the sandbox ends, and its output is not kept, so redirect it to a file to read it later. A provider with no detached commands answers unsupported.",
1697
+ "With --interactive, the CLI sends its stdin to the command until stdin ends. With --tty, the command's stdout and stderr, and its stdin with --interactive, sit on a terminal of this terminal's size, and the output reaches this terminal unchanged. Either one runs the command as a process with no timeout that survives a dropped connection; Ctrl-C reaches the command, and a second Ctrl-C without --tty leaves it running and exits the CLI.",
1237
1698
  "The CLI never retries a command, since running it twice may change the sandbox twice."
1238
1699
  ],
1239
1700
  options: [
@@ -1249,13 +1710,21 @@ const sandboxesExec = {
1249
1710
  summary: "Start the command and return at once, leaving it running in the sandbox"
1250
1711
  }),
1251
1712
  env,
1713
+ flag({
1714
+ name: "interactive",
1715
+ summary: "Send this CLI's stdin to the command"
1716
+ }),
1252
1717
  json,
1253
1718
  {
1254
1719
  hint: "<SECONDS>",
1255
1720
  kind: "value",
1256
1721
  name: "timeout",
1257
1722
  summary: "Seconds after which the provider stops the command"
1258
- }
1723
+ },
1724
+ flag({
1725
+ name: "tty",
1726
+ summary: "Run the command on a terminal, as ssh -t does"
1727
+ })
1259
1728
  ],
1260
1729
  result: [
1261
1730
  {
@@ -1349,6 +1818,47 @@ const sandboxesPortsInspect = {
1349
1818
  ],
1350
1819
  summary: "Print a port's preview URL"
1351
1820
  };
1821
+ const sandboxesProcessesInspect = {
1822
+ arguments: [sandboxArgument("show a process"), required({
1823
+ message: "Can't show a process without its ID.",
1824
+ name: "process",
1825
+ reason: "missing_process",
1826
+ summary: "Process ID, such as proc_ and a UUID"
1827
+ })],
1828
+ examples: [{
1829
+ argv: [
1830
+ "sandboxes",
1831
+ "processes",
1832
+ "inspect",
1833
+ SANDBOX,
1834
+ "<PROCESS>"
1835
+ ],
1836
+ summary: "Show a process's status and exit code"
1837
+ }],
1838
+ kind: "leaf",
1839
+ name: "inspect",
1840
+ notes: ["A process is running until its command exits, then exited, or lost when the sandbox ended before the process reported an exit."],
1841
+ options: [baseUrl, json],
1842
+ result: [
1843
+ {
1844
+ name: "process.id",
1845
+ type: "string"
1846
+ },
1847
+ {
1848
+ name: "process.status",
1849
+ type: "\"exited\" | \"lost\" | \"running\""
1850
+ },
1851
+ {
1852
+ name: "process.exit_code",
1853
+ type: NULLABLE_NUMBER
1854
+ },
1855
+ {
1856
+ name: "process.signal",
1857
+ type: NULLABLE_TEXT
1858
+ }
1859
+ ],
1860
+ summary: "Show a process"
1861
+ };
1352
1862
  const filesList = {
1353
1863
  arguments: [sandboxArgument("list files"), pathArgument("list files")],
1354
1864
  examples: [{
@@ -1496,11 +2006,13 @@ const docker = {
1496
2006
  notes: [
1497
2007
  "Runs the Docker CLI in a sandbox with every word after docker, streams its stdout and stderr to this terminal's, and exits with its exit code.",
1498
2008
  "The first command starts a sandbox on a provider that runs Docker, as Sandcovery CI runners do, and later commands reuse it until it ends at its TTL, so images, containers, and volumes carry over between commands. sandcovery sandboxes destroy ends it sooner.",
1499
- "build, buildx, builder, and image build first copy the working directory into the sandbox, up to 100 MiB packed, so their relative paths resolve as they do here. Every other path names a file in the sandbox, as with a remote Docker daemon.",
1500
- "compose first copies the Compose project into the sandbox, up to 100 MiB packed: its Compose files and env files, each build context without what .dockerignore leaves out, and each bind-mounted file or directory, under the directory that holds them all. ps, logs, down, and other commands that only read the project copy only the Compose files and env files. The copy keeps what containers wrote there, and a file deleted here stays there. Variables in Compose files come only from .env and --env-file, and absolute and ~ paths name files in the sandbox.",
1501
- "When stdin is not a terminal and docker reads it, as with -i on run or exec without -d, start -i, login --password-stdin, load, import -, build -, or cp -, the command reads stdin to its end and hands it to docker.",
2009
+ "Before docker runs, the command copies the local files it reads into the sandbox at the same absolute paths, up to 100 MiB packed, and runs docker in the same working directory there, so relative and absolute paths resolve as they do here. Those files are the build context of build and bake without what .dockerignore leaves out, the files of a build's -f, --build-context, and --secret, the bind mount sources and env files of run and create, and the file that cp, load -i, or import reads.",
2010
+ "compose copies its Compose files and env files and, for commands that build or start containers, each build context and each bind-mounted file or directory. ps, logs, down, and other commands that only read the project copy only the Compose files and env files. Variables in Compose files come only from .env and --env-file, and ~ in a Compose file names the home folder of the sandbox.",
2011
+ "Only paths under your home folder or the working directory are copied, a symlink arrives as the link itself, and a path through a symlinked folder fails. What containers wrote stays in the sandbox and never comes back here, and a file deleted here since the last copy is deleted there.",
2012
+ "When stdin is not a terminal and docker reads it, as with -i on run or exec without -d, start -i, login --password-stdin, load, import -, build -, or cp -, the command streams stdin to docker as it reads it.",
1502
2013
  "When stdout is not a terminal and docker writes an archive there, as with save or export without -o, cp to -, or build -o -, the archive arrives byte for byte. save and export without -o refuse a terminal, as docker does.",
1503
- "The command gets no terminal and stops after an hour, so docker run -it does not work.",
2014
+ "A TCP port a container publishes answers on the same address and port here, through a process the command starts in the background, until the sandbox ends. A port another program here listens on, or one only an administrator may listen on, stays in the sandbox, and the command warns once.",
2015
+ "docker gets a terminal in the sandbox wherever this command's stdin, stdout, or stderr is one, so docker run -it, docker exec -it, and docker attach work. A command runs until it exits, and the sandbox stays up past its TTL while it runs.",
1504
2016
  "sandcovery-docker takes docker arguments alone, runs them in the same sandbox, and adds nothing to docker output, so alias docker=sandcovery-docker runs docker here."
1505
2017
  ],
1506
2018
  options: [baseUrl],
@@ -1508,6 +2020,54 @@ const docker = {
1508
2020
  result: [],
1509
2021
  summary: "Run a docker command in a sandbox"
1510
2022
  };
2023
+ const kubectl = {
2024
+ arguments: [{
2025
+ name: "args",
2026
+ optional: true,
2027
+ summary: "Arguments for kubectl, every word passed on unchanged, so sandcovery options such as --base-url go before kubectl",
2028
+ variadic: true
2029
+ }],
2030
+ examples: [
2031
+ {
2032
+ argv: [
2033
+ "kubectl",
2034
+ "apply",
2035
+ "--filename",
2036
+ "deployment.yaml"
2037
+ ],
2038
+ summary: "Apply a local manifest to a cluster in a sandbox"
2039
+ },
2040
+ {
2041
+ argv: [
2042
+ "kubectl",
2043
+ "get",
2044
+ "pods"
2045
+ ],
2046
+ summary: "List the pods of that cluster"
2047
+ },
2048
+ {
2049
+ argv: [
2050
+ "kubectl",
2051
+ "port-forward",
2052
+ "deployment/app",
2053
+ "8080:80"
2054
+ ],
2055
+ summary: "Reach a pod on port 8080 of this computer"
2056
+ }
2057
+ ],
2058
+ kind: "leaf",
2059
+ name: "kubectl",
2060
+ notes: [
2061
+ "Runs your own kubectl with every word after kubectl against a one-node Kubernetes cluster in a sandbox, so the output and exit code are kubectl's, local files reach apply -f, and port-forward, exec -it, and logs -f work as they do with a local cluster. kubectl must be on PATH.",
2062
+ "The first command that reaches the cluster starts a 2x4 sandbox on Freestyle, or a 2x8 sandbox on boxd when Freestyle cannot create it, and waits a few minutes for the cluster. Later commands reuse it, so what you applied carries over between commands. It stops 15 minutes after the last command that reached it ends, or at its TTL, whichever comes first, and a command that keeps running, such as port-forward or logs -f, keeps it running. sandcovery sandboxes destroy ends it sooner.",
2063
+ "kubectl reads a kubeconfig the CLI keeps beside its settings, through KUBECONFIG, so --kubeconfig names your own clusters instead. completion, config, help, kustomize, options, plugin, version --client, and --help start no cluster.",
2064
+ "sandcovery-kubectl takes kubectl arguments alone and adds nothing to kubectl output, so alias kubectl=sandcovery-kubectl runs kubectl here."
2065
+ ],
2066
+ options: [baseUrl],
2067
+ passthrough: true,
2068
+ result: [],
2069
+ summary: "Run a kubectl command against a cluster in a sandbox"
2070
+ };
1511
2071
  const setup = {
1512
2072
  arguments: [],
1513
2073
  examples: [{
@@ -1669,6 +2229,14 @@ const sandboxes = {
1669
2229
  name: "ports",
1670
2230
  shortcuts: ["port"],
1671
2231
  summary: "Preview a sandbox's ports"
2232
+ },
2233
+ {
2234
+ children: [sandboxesProcessesInspect],
2235
+ defaultChild: "inspect",
2236
+ kind: "group",
2237
+ name: "processes",
2238
+ shortcuts: ["process"],
2239
+ summary: "Show the processes of a sandbox"
1672
2240
  }
1673
2241
  ],
1674
2242
  kind: "group",
@@ -2073,9 +2641,48 @@ const credentials = {
2073
2641
  {
2074
2642
  name: "offer.remaining_vcpu_seconds",
2075
2643
  type: "number"
2644
+ },
2645
+ {
2646
+ name: "offer.x_post_counted",
2647
+ type: "boolean"
2076
2648
  }
2077
2649
  ],
2078
2650
  summary: "Show the free vCPU-hours offer"
2651
+ },
2652
+ {
2653
+ arguments: [required({
2654
+ message: "Can't count an X post without its URL.",
2655
+ name: "url",
2656
+ reason: "missing_url",
2657
+ summary: "The post's URL on x.com or twitter.com, such as https://x.com/<handle>/status/<id>"
2658
+ })],
2659
+ examples: [{
2660
+ argv: [
2661
+ "credentials",
2662
+ "count-x-post",
2663
+ "https://x.com/you/status/1234567890123456789"
2664
+ ],
2665
+ summary: `Count your post on X that tags @${SANDCOVERY_X_HANDLE} as one key`
2666
+ }],
2667
+ kind: "leaf",
2668
+ name: "count-x-post",
2669
+ notes: [`A post on X that tags @${SANDCOVERY_X_HANDLE} counts as one key toward the free vCPU-hours when the X account linked to your organization's owner wrote it. A repost counts nothing.`, "One post counts per account, and one X account counts for one Sandcovery account only. Needs a management key."],
2670
+ options: [baseUrl, json],
2671
+ result: [
2672
+ {
2673
+ name: "offer.keys_counted",
2674
+ type: "number"
2675
+ },
2676
+ {
2677
+ name: "offer.remaining_vcpu_seconds",
2678
+ type: "number"
2679
+ },
2680
+ {
2681
+ name: "offer.x_post_counted",
2682
+ type: "boolean"
2683
+ }
2684
+ ],
2685
+ summary: "Count an X post toward the free vCPU-hours"
2079
2686
  }
2080
2687
  ],
2081
2688
  defaultChild: "list",
@@ -2295,6 +2902,182 @@ const usage = {
2295
2902
  ],
2296
2903
  summary: "Show usage totals by day, week, month, and in total"
2297
2904
  },
2905
+ {
2906
+ children: [
2907
+ {
2908
+ arguments: [],
2909
+ examples: [{
2910
+ argv: [
2911
+ "usage",
2912
+ "shares",
2913
+ "list"
2914
+ ],
2915
+ summary: "List the live usage shares"
2916
+ }],
2917
+ kind: "leaf",
2918
+ name: "list",
2919
+ notes: [NEEDS_MANAGEMENT],
2920
+ options: [baseUrl, json],
2921
+ result: [
2922
+ {
2923
+ name: "shares",
2924
+ type: "array"
2925
+ },
2926
+ {
2927
+ name: "shares[].id",
2928
+ type: "string"
2929
+ },
2930
+ {
2931
+ name: "shares[].url",
2932
+ type: "string"
2933
+ }
2934
+ ],
2935
+ shortcuts: ["ls"],
2936
+ summary: "List usage shares"
2937
+ },
2938
+ {
2939
+ arguments: [],
2940
+ examples: [{
2941
+ argv: [
2942
+ "usage",
2943
+ "shares",
2944
+ "create"
2945
+ ],
2946
+ summary: "Share this month's usage without its cost"
2947
+ }, {
2948
+ argv: [
2949
+ "usage",
2950
+ "shares",
2951
+ "create",
2952
+ "--period",
2953
+ "total",
2954
+ "--figure",
2955
+ "sandbox_count",
2956
+ "--figure",
2957
+ "vcpu_seconds"
2958
+ ],
2959
+ summary: "Share only the sandboxes and vCPU-hours of all time"
2960
+ }],
2961
+ kind: "leaf",
2962
+ name: "create",
2963
+ notes: [
2964
+ "Reads the usage total of the window now and shares the chosen figures at a new public URL. Anyone with the URL sees them and your Sandcovery username, and nothing else of the organization, until you revoke the share.",
2965
+ "With no --figure, it shares every figure but the estimated cost.",
2966
+ "Needs the saved login of an owner or admin who picked a username in the share dialog on the usage page, since a key names no person."
2967
+ ],
2968
+ options: [
2969
+ baseUrl,
2970
+ {
2971
+ hint: "<FIGURE>",
2972
+ kind: "value",
2973
+ name: "figure",
2974
+ repeat: "append",
2975
+ summary: "Figure to share, such as sandbox_count or vcpu_seconds; repeat for each one"
2976
+ },
2977
+ json,
2978
+ {
2979
+ defaultText: "month",
2980
+ hint: "<PERIOD>",
2981
+ kind: "value",
2982
+ name: "period",
2983
+ summary: "Window to share: day, week, month, or total"
2984
+ }
2985
+ ],
2986
+ result: [
2987
+ {
2988
+ name: "share.id",
2989
+ type: "string"
2990
+ },
2991
+ {
2992
+ name: "share.url",
2993
+ type: "string"
2994
+ },
2995
+ {
2996
+ name: "share.image_url",
2997
+ type: "string"
2998
+ }
2999
+ ],
3000
+ summary: "Share usage at a public URL"
3001
+ },
3002
+ {
3003
+ arguments: [required({
3004
+ message: "Can't revoke a usage share without its ID.",
3005
+ name: "share",
3006
+ reason: "missing_value",
3007
+ summary: "Share ID, such as ush_ and a UUID, as sandcovery usage shares list prints it"
3008
+ })],
3009
+ examples: [{
3010
+ argv: [
3011
+ "usage",
3012
+ "shares",
3013
+ "revoke",
3014
+ "<SHARE>"
3015
+ ],
3016
+ summary: "Revoke a share after a prompt"
3017
+ }, {
3018
+ argv: [
3019
+ "usage",
3020
+ "shares",
3021
+ "revoke",
3022
+ "<SHARE>",
3023
+ "--yes"
3024
+ ],
3025
+ summary: "Revoke it in a script, after a person approved"
3026
+ }],
3027
+ kind: "leaf",
3028
+ name: "revoke",
3029
+ notes: ["Its URL answers 404 at once for everyone who has it.", `It asks first, and needs --yes without a terminal. ${NEEDS_MANAGEMENT}`],
3030
+ options: [
3031
+ baseUrl,
3032
+ json,
3033
+ yes
3034
+ ],
3035
+ result: [{
3036
+ name: "share.id",
3037
+ type: "string"
3038
+ }, {
3039
+ name: "outcome",
3040
+ type: "\"revoked\""
3041
+ }],
3042
+ shortcuts: ["delete", "rm"],
3043
+ summary: "Revoke a usage share"
3044
+ },
3045
+ {
3046
+ arguments: [required({
3047
+ message: "Can't show shared usage without its token.",
3048
+ name: "token",
3049
+ reason: "missing_value",
3050
+ summary: "Token, the 43 characters after /share/ in a share URL"
3051
+ })],
3052
+ examples: [{
3053
+ argv: [
3054
+ "usage",
3055
+ "shares",
3056
+ "inspect",
3057
+ "<TOKEN>"
3058
+ ],
3059
+ summary: "Show what a share URL shows"
3060
+ }],
3061
+ kind: "leaf",
3062
+ name: "inspect",
3063
+ notes: ["Shows the figures a share URL shows to anyone. Needs no key."],
3064
+ options: [baseUrl, json],
3065
+ result: [{
3066
+ name: "usage.period",
3067
+ type: "string"
3068
+ }, {
3069
+ name: "usage.figures",
3070
+ type: "array"
3071
+ }],
3072
+ summary: "Show the usage a share URL shows"
3073
+ }
3074
+ ],
3075
+ defaultChild: "list",
3076
+ kind: "group",
3077
+ name: "shares",
3078
+ shortcuts: ["share"],
3079
+ summary: "Share usage at public URLs"
3080
+ },
2298
3081
  {
2299
3082
  arguments: [],
2300
3083
  examples: [{
@@ -2428,12 +3211,12 @@ const billing = {
2428
3211
  }],
2429
3212
  kind: "leaf",
2430
3213
  name: "inspect",
2431
- notes: [`Shows the plan, the credit balance, and the Pro price. It fails as not found while billing is not set up. ${NEEDS_MANAGEMENT}`],
3214
+ notes: [`Shows the plan, the credit balance, and the Pro and Enterprise prices. It fails as not found while billing is not set up. ${NEEDS_MANAGEMENT}`],
2432
3215
  options: [baseUrl, json],
2433
3216
  result: [
2434
3217
  {
2435
3218
  name: "billing.plan",
2436
- type: "\"free\" | \"pro\""
3219
+ type: "\"free\" | \"pro\" | \"enterprise\""
2437
3220
  },
2438
3221
  {
2439
3222
  name: "billing.credit_balance_micro_usd",
@@ -2445,7 +3228,15 @@ const billing = {
2445
3228
  },
2446
3229
  {
2447
3230
  name: "billing.pro_price",
2448
- type: "object | null"
3231
+ type: NULLABLE_OBJECT
3232
+ },
3233
+ {
3234
+ name: "billing.enterprise_price",
3235
+ type: NULLABLE_OBJECT
3236
+ },
3237
+ {
3238
+ name: "billing.github_enterprise",
3239
+ type: "boolean"
2449
3240
  }
2450
3241
  ],
2451
3242
  summary: "Show the plan and credits"
@@ -2490,25 +3281,134 @@ const pricing = {
2490
3281
  arguments: [],
2491
3282
  examples: [{
2492
3283
  argv: ["pricing", "inspect"],
2493
- summary: "Show the Pro price and the credit terms"
3284
+ summary: "Show the plan prices and the credit terms"
2494
3285
  }],
2495
3286
  kind: "leaf",
2496
3287
  name: "inspect",
2497
- notes: ["Shows the Pro price, the smallest and largest credit purchase, and the processing fee that comes out of each purchase. It needs no key, and the Pro price reads Not on sale while Pro is not on sale.", NO_MARKUP_TERMS],
3288
+ notes: ["Shows the Pro and Enterprise prices, the smallest and largest credit purchase, and the processing fee that comes out of each purchase. It needs no key, and each price reads Not on sale while its plan is not on sale.", NO_MARKUP_TERMS],
2498
3289
  options: [baseUrl, json],
2499
- result: [{
2500
- name: "pricing.pro_price",
2501
- type: "object | null"
2502
- }, {
2503
- name: "pricing.credits",
2504
- type: "object"
3290
+ result: [
3291
+ {
3292
+ name: "pricing.pro_price",
3293
+ type: NULLABLE_OBJECT
3294
+ },
3295
+ {
3296
+ name: "pricing.enterprise_price",
3297
+ type: NULLABLE_OBJECT
3298
+ },
3299
+ {
3300
+ name: "pricing.credits",
3301
+ type: "object"
3302
+ }
3303
+ ],
3304
+ summary: "Show the plan prices and credit terms"
3305
+ }, {
3306
+ arguments: [],
3307
+ examples: [{
3308
+ argv: [
3309
+ "pricing",
3310
+ "monthly",
3311
+ "--size",
3312
+ "4x8",
3313
+ "--hours-per-day",
3314
+ "24"
3315
+ ],
3316
+ summary: "Price a 4x8 sandbox that runs all month on each provider"
2505
3317
  }],
2506
- summary: "Show the Pro price and credit terms"
3318
+ kind: "leaf",
3319
+ name: "monthly",
3320
+ notes: [`Prices one size on each provider Sandcovery routes to, cheapest first, for a sandbox that runs --hours-per-day hours on every day of ${MONTH_TEXT}, and prints the slug that routes a create to the cheapest. It needs no key and creates nothing.`, NO_MARKUP_TERMS],
3321
+ options: [
3322
+ baseUrl,
3323
+ {
3324
+ defaultText: String(8),
3325
+ hint: "<HOURS>",
3326
+ kind: "value",
3327
+ name: "hours-per-day",
3328
+ summary: `Hours a day the sandbox runs, above 0 and at most ${String(24)}, such as 8 or 0.5`
3329
+ },
3330
+ json,
3331
+ {
3332
+ defaultText: "2x4",
3333
+ hint: "<SIZE>",
3334
+ kind: "value",
3335
+ name: "size",
3336
+ summary: "Size as <vcpu>x<memory_gib>, such as 2x4 or 2x0.5"
3337
+ }
3338
+ ],
3339
+ result: [
3340
+ {
3341
+ name: "estimates",
3342
+ type: "array"
3343
+ },
3344
+ {
3345
+ name: "estimates[].provider",
3346
+ type: "string"
3347
+ },
3348
+ {
3349
+ name: "estimates[].slug",
3350
+ type: "string"
3351
+ },
3352
+ {
3353
+ name: "estimates[].monthly_micro_usd",
3354
+ type: "number"
3355
+ },
3356
+ {
3357
+ name: "slug",
3358
+ type: "string"
3359
+ }
3360
+ ],
3361
+ summary: "Price a size for a month on each provider"
2507
3362
  }],
2508
3363
  defaultChild: "inspect",
2509
3364
  kind: "group",
2510
3365
  name: "pricing",
2511
- summary: "Show the Pro price and the credit terms"
3366
+ summary: "Show the plan prices, the credit terms, and monthly costs"
3367
+ };
3368
+ const problems = {
3369
+ children: [{
3370
+ arguments: [{
3371
+ missing: {
3372
+ message: "Can't report a problem without a message.",
3373
+ reason: "missing_value"
3374
+ },
3375
+ name: "message",
3376
+ summary: `What went wrong, up to ${formatCount({ count: PROBLEM_REPORT_MAX })} characters; its words join with spaces`,
3377
+ variadic: true
3378
+ }],
3379
+ examples: [{
3380
+ argv: [
3381
+ "problems",
3382
+ "report",
3383
+ "The pricing table is cut off on my phone.",
3384
+ "--page",
3385
+ "/pricing"
3386
+ ],
3387
+ summary: "Report a problem with a page"
3388
+ }],
3389
+ kind: "leaf",
3390
+ name: "report",
3391
+ notes: [`Sends the report to the Sandcovery team, who track it as an issue. It needs no key, and Sandcovery takes ${String(3)} reports a minute from one network address.`],
3392
+ options: [
3393
+ baseUrl,
3394
+ json,
3395
+ {
3396
+ hint: "<PATH>",
3397
+ kind: "value",
3398
+ name: "page",
3399
+ summary: "Path of the Sandcovery page the problem is on"
3400
+ }
3401
+ ],
3402
+ result: [{
3403
+ name: "outcome",
3404
+ type: "\"sent\""
3405
+ }],
3406
+ summary: "Tell the Sandcovery team about a problem"
3407
+ }],
3408
+ kind: "group",
3409
+ name: "problems",
3410
+ shortcuts: ["problem"],
3411
+ summary: "Tell the Sandcovery team about a problem"
2512
3412
  };
2513
3413
  const ci = {
2514
3414
  children: [{
@@ -2680,6 +3580,85 @@ const ci = {
2680
3580
  name: "ci",
2681
3581
  summary: "Run GitHub Actions jobs on sandboxes"
2682
3582
  };
3583
+ const xAccount = {
3584
+ children: [
3585
+ {
3586
+ arguments: [],
3587
+ examples: [{
3588
+ argv: ["x-account", "inspect"],
3589
+ summary: "Show the X account linked to you"
3590
+ }],
3591
+ kind: "leaf",
3592
+ name: "inspect",
3593
+ notes: [`Shows the handle, X ID, and link time of the X account linked to you, and whether Sandcovery links X accounts now. ${NEEDS_PERSON}`],
3594
+ options: [baseUrl, json],
3595
+ result: [
3596
+ {
3597
+ name: "x_account.linked",
3598
+ type: NULLABLE_OBJECT
3599
+ },
3600
+ {
3601
+ name: "x_account.linked.username",
3602
+ type: "string"
3603
+ },
3604
+ {
3605
+ name: "x_account.linking_open",
3606
+ type: "boolean"
3607
+ }
3608
+ ],
3609
+ summary: "Show the linked X account"
3610
+ },
3611
+ {
3612
+ arguments: [],
3613
+ examples: [{
3614
+ argv: ["x-account", "link"],
3615
+ summary: "Print the page that links an X account"
3616
+ }],
3617
+ kind: "leaf",
3618
+ name: "link",
3619
+ notes: ["Prints the dashboard page where you link an X account, since X confirms the link in the browser. Linking asks X only to read your X profile and posts. It fails as not found while Sandcovery links no X accounts, and as a conflict while one is linked to you.", NEEDS_PERSON],
3620
+ options: [baseUrl, json],
3621
+ result: [{
3622
+ name: "link.url",
3623
+ type: "string"
3624
+ }],
3625
+ summary: "Link an X account in the browser"
3626
+ },
3627
+ {
3628
+ arguments: [],
3629
+ examples: [{
3630
+ argv: ["x-account", "unlink"],
3631
+ summary: "Unlink the X account after a prompt"
3632
+ }, {
3633
+ argv: [
3634
+ "x-account",
3635
+ "unlink",
3636
+ "--yes"
3637
+ ],
3638
+ summary: "Unlink it in a script, after a person approved"
3639
+ }],
3640
+ kind: "leaf",
3641
+ name: "unlink",
3642
+ notes: ["Deletes the ID, handle, and X token of the X account linked to you. It fails as not found while none is linked.", `It asks first, and needs --yes without a terminal. ${NEEDS_PERSON}`],
3643
+ options: [
3644
+ baseUrl,
3645
+ json,
3646
+ yes
3647
+ ],
3648
+ result: [{
3649
+ name: "outcome",
3650
+ type: "\"unlinked\""
3651
+ }],
3652
+ shortcuts: ["delete", "rm"],
3653
+ summary: "Unlink the X account"
3654
+ }
3655
+ ],
3656
+ defaultChild: "inspect",
3657
+ kind: "group",
3658
+ name: "x-account",
3659
+ shortcuts: ["x"],
3660
+ summary: "Link or unlink your X account"
3661
+ };
2683
3662
  const telemetryLeaf = ({ name, summary }) => ({
2684
3663
  arguments: [],
2685
3664
  examples: [{
@@ -2790,6 +3769,7 @@ const CLI = {
2790
3769
  children: [
2791
3770
  sandboxes,
2792
3771
  docker,
3772
+ kubectl,
2793
3773
  setup,
2794
3774
  keys,
2795
3775
  credentials,
@@ -2800,6 +3780,8 @@ const CLI = {
2800
3780
  billing,
2801
3781
  pricing,
2802
3782
  ci,
3783
+ xAccount,
3784
+ problems,
2803
3785
  login,
2804
3786
  logout,
2805
3787
  help,
@@ -2846,6 +3828,7 @@ const CLI = {
2846
3828
  ["sandboxes", "destroy"],
2847
3829
  ["sandboxes", "files"],
2848
3830
  ["docker"],
3831
+ ["kubectl"],
2849
3832
  ["setup"]
2850
3833
  ],
2851
3834
  title: "Sandboxes"
@@ -2854,10 +3837,12 @@ const CLI = {
2854
3837
  paths: [
2855
3838
  ["providers", "list"],
2856
3839
  ["pricing", "inspect"],
3840
+ ["pricing", "monthly"],
2857
3841
  ["usage", "estimate"],
2858
3842
  ["usage", "inspect"],
2859
3843
  ["usage", "live"],
2860
3844
  ["usage", "totals"],
3845
+ ["usage", "shares"],
2861
3846
  ["stats", "inspect"]
2862
3847
  ],
2863
3848
  title: "Providers and Cost"
@@ -2869,7 +3854,8 @@ const CLI = {
2869
3854
  ["keys"],
2870
3855
  ["credentials"],
2871
3856
  ["activity", "list"],
2872
- ["billing"]
3857
+ ["billing"],
3858
+ ["x-account"]
2873
3859
  ],
2874
3860
  title: "Account"
2875
3861
  },
@@ -2877,10 +3863,1125 @@ const CLI = {
2877
3863
  paths: [
2878
3864
  ["help"],
2879
3865
  ["help", "search"],
3866
+ ["problems", "report"],
2880
3867
  ["cli", "telemetry"]
2881
3868
  ],
2882
3869
  title: "Help and Settings"
2883
3870
  }
2884
3871
  ]
2885
3872
  };
2886
- export { remoteCell as A, exitCodeOf as B, clearLine as C, spinnerFrame as D, plainPrefix as E, isDigit as F, usageFailure as H, isDigits as I, isUpper as L, remoteText as M, noop as N, theme as O, consistsOf as P, isWordCharacter as R, valuesOf as S, glyph as T, Canceled as U, statusOf as V, Clock as W, lastValue as _, version as a, readOptionToken as b, writePrivateFile as c, modeOf as d, productVariable as f, isOptionValue as g, isOptionToken as h, SETUP_MARK as i, remoteLine as j, escapeUnprintable as k, enabledVariable as l, flagOf as m, CLEARABLE as n, configDirectory as o, closest as p, CLI as r, withFileLock as s, BIN as t, guidanceOn as u, parseFailure as v, ellipsis as w, rerunArgv as x, parseLeaf as y, CliFailure as z };
3873
+ // src/cli/commands/setup.ts
3874
+ const DROP_INS = [{
3875
+ binary: "sandcovery-docker",
3876
+ tool: "docker"
3877
+ }, {
3878
+ binary: "sandcovery-kubectl",
3879
+ tool: "kubectl"
3880
+ }];
3881
+ const LINE_MARK = ` ${SETUP_MARK}`;
3882
+ const SHIM_HEAD = `#!/bin/sh\n${SETUP_MARK}\n`;
3883
+ const BASH_LOGIN = [
3884
+ ".bash_profile",
3885
+ ".bash_login",
3886
+ ".profile"
3887
+ ];
3888
+ const ZSH_FILES = [".zshenv", ".zshrc"];
3889
+ const FILE_TYPE_UNIT = 4096;
3890
+ const UNREACHABLE = /* @__PURE__ */ new Set([
3891
+ "EACCES",
3892
+ "EEXIST",
3893
+ "EISDIR",
3894
+ "ENOTDIR",
3895
+ "EPERM",
3896
+ "EROFS"
3897
+ ]);
3898
+ const EMPTY = {
3899
+ changes: [],
3900
+ edits: []
3901
+ };
3902
+ const joined = (plans) => ({
3903
+ changes: plans.flatMap(({ changes }) => changes),
3904
+ edits: plans.flatMap(({ edits }) => edits)
3905
+ });
3906
+ const touched = ({ file, verb, work }) => {
3907
+ const done = try_(work);
3908
+ if (isSuccess(done)) return done.success;
3909
+ const { failure } = done;
3910
+ const code = hasProperty(failure, "code") && isString(failure.code) ? failure.code : "";
3911
+ if (!UNREACHABLE.has(code)) throw failure;
3912
+ throw new CliFailure({
3913
+ message: verb === "read" ? `Can't read ${file} (${code}). Nothing was changed.` : `Can't write ${file} (${code}). Run the command again once it is writable, and it lists what is left.`,
3914
+ reason: "permission_denied"
3915
+ });
3916
+ };
3917
+ const statOf = (file) => touched({
3918
+ file,
3919
+ verb: "read",
3920
+ work: () => fs.lstatSync(file, { throwIfNoEntry: false })
3921
+ });
3922
+ const textOf = (file) => fs.existsSync(file) ? touched({
3923
+ file,
3924
+ verb: "read",
3925
+ work: () => fs.readFileSync(file, "utf-8")
3926
+ }) : void 0;
3927
+ const envValue = (name) => {
3928
+ const value = process.env[name];
3929
+ return value === void 0 || value === "" ? void 0 : value;
3930
+ };
3931
+ const fishQuoted = (text) => text.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("$", "\\$");
3932
+ const posixQuoted = (text) => fishQuoted(text).replaceAll("`", "\\`");
3933
+ const posixLine = (shims) => `export PATH="${posixQuoted(shims)}:$PATH"${LINE_MARK}`;
3934
+ const fishLine = (shims) => `set -gx PATH "${fishQuoted(shims)}" $PATH${LINE_MARK}`;
3935
+ const shimText = (binary) => `${SHIM_HEAD}exec ${binary} "$@"\n`;
3936
+ const executable = (file) => {
3937
+ const found = try_(() => {
3938
+ fs.accessSync(file, fs.constants.X_OK);
3939
+ return fs.statSync(file).isFile();
3940
+ });
3941
+ return isSuccess(found) && found.success;
3942
+ };
3943
+ const onPath = ({ name, shims }) => (process.env.PATH ?? "").split(path.delimiter).flatMap((folder) => path.isAbsolute(folder) && path.resolve(folder) !== shims ? [path.join(folder, name)] : []).find(executable) ?? null;
3944
+ const zshFolder = (home) => envValue("ZDOTDIR") ?? home;
3945
+ const fishConfig = (configHome) => path.join(configHome, "fish", "config.fish");
3946
+ const defaultConfigHome = (home) => path.join(home, ".config");
3947
+ const shellsOf = (home) => {
3948
+ const bashLogin = BASH_LOGIN.map((name) => path.join(home, name)).find((file) => fs.existsSync(file)) ?? path.join(home, ".profile");
3949
+ return [
3950
+ {
3951
+ files: [path.join(home, ".bashrc"), bashLogin],
3952
+ line: posixLine,
3953
+ name: "bash"
3954
+ },
3955
+ {
3956
+ files: ZSH_FILES.map((name) => path.join(zshFolder(home), name)),
3957
+ line: posixLine,
3958
+ name: "zsh"
3959
+ },
3960
+ {
3961
+ files: [fishConfig(envValue("XDG_CONFIG_HOME") ?? defaultConfigHome(home))],
3962
+ line: fishLine,
3963
+ name: "fish"
3964
+ }
3965
+ ];
3966
+ };
3967
+ const everyStartupFile = (home) => [.../* @__PURE__ */ new Set([
3968
+ ...[".bashrc", ...BASH_LOGIN].map((name) => path.join(home, name)),
3969
+ ...[zshFolder(home), home].flatMap((folder) => ZSH_FILES.map((name) => path.join(folder, name))),
3970
+ ...[envValue("XDG_CONFIG_HOME") ?? defaultConfigHome(home), defaultConfigHome(home)].map(fishConfig)
3971
+ ])];
3972
+ const appended = (line) => (text) => {
3973
+ if (text.split("\n").includes(line)) return text;
3974
+ return `${text}${text === "" || text.endsWith("\n") ? "" : "\n"}${line}\n`;
3975
+ };
3976
+ const withoutMarked = (text) => text.split("\n").filter((line) => !line.endsWith(LINE_MARK)).join("\n");
3977
+ const folderEntries = (folder) => statOf(folder)?.isDirectory() === true ? touched({
3978
+ file: folder,
3979
+ verb: "read",
3980
+ work: () => fs.readdirSync(folder)
3981
+ }).map((name) => path.join(folder, name)).toSorted() : [];
3982
+ const isOwnShim = (file) => statOf(file)?.isFile() === true && (textOf(file) ?? "").startsWith(SHIM_HEAD);
3983
+ const shimDeletion = (file) => ({
3984
+ changes: [{
3985
+ action: "delete",
3986
+ file,
3987
+ line: null,
3988
+ summary: "Delete this shim",
3989
+ text: null
3990
+ }],
3991
+ edits: [{
3992
+ file,
3993
+ kind: "delete"
3994
+ }]
3995
+ });
3996
+ const shimWrite = ({ binary, shims, tool }) => {
3997
+ const file = path.join(shims, tool);
3998
+ const text = shimText(binary);
3999
+ const stat = statOf(file);
4000
+ if (stat !== void 0) {
4001
+ const current = stat.isFile() ? textOf(file) : void 0;
4002
+ if (current === text) return EMPTY;
4003
+ if (current === void 0 || !current.startsWith(SHIM_HEAD)) throw new CliFailure({
4004
+ message: `Can't write the ${tool} shim. ${file} is not a file sandcovery setup wrote, so it stays as it is.`,
4005
+ reason: "conflict",
4006
+ recovery: [{ instruction: `Move ${file} out of ${shims}, then run sandcovery setup again` }]
4007
+ });
4008
+ }
4009
+ return {
4010
+ changes: [{
4011
+ action: "write",
4012
+ file,
4013
+ line: null,
4014
+ summary: `Write a shim that runs ${binary}`,
4015
+ text
4016
+ }],
4017
+ edits: [{
4018
+ file,
4019
+ kind: "shim",
4020
+ text
4021
+ }]
4022
+ };
4023
+ };
4024
+ const shimPlan = ({ dropIns, shims }) => {
4025
+ const wanted = dropIns.filter(({ installed }) => installed);
4026
+ const tools = new Set(wanted.map(({ tool }) => tool));
4027
+ return joined([...wanted.map(({ binary, tool }) => shimWrite({
4028
+ binary,
4029
+ shims,
4030
+ tool
4031
+ })), ...folderEntries(shims).flatMap((file) => tools.has(path.basename(file)) || !isOwnShim(file) ? [] : [shimDeletion(file)])]);
4032
+ };
4033
+ const lineAddition = ({ file, text }) => {
4034
+ const current = textOf(file) ?? "";
4035
+ return appended(text)(current) === current ? EMPTY : {
4036
+ changes: [{
4037
+ action: "append",
4038
+ file,
4039
+ line: null,
4040
+ summary: `Add: ${text}`,
4041
+ text
4042
+ }],
4043
+ edits: [{
4044
+ change: appended(text),
4045
+ file,
4046
+ kind: "startup"
4047
+ }]
4048
+ };
4049
+ };
4050
+ const linePlan = ({ home, shims }) => {
4051
+ const login = path.basename(envValue("SHELL") ?? "");
4052
+ return joined(shellsOf(home).flatMap(({ files, line, name }) => name === login || files.some((file) => fs.existsSync(file)) ? files.map((file) => lineAddition({
4053
+ file,
4054
+ text: line(shims)
4055
+ })) : []));
4056
+ };
4057
+ const lineRemovals = (file) => {
4058
+ const text = textOf(file);
4059
+ if (text === void 0) return EMPTY;
4060
+ const marked = text.split("\n").flatMap((line, index) => line.endsWith(LINE_MARK) ? [{
4061
+ line: index + 1,
4062
+ text: line
4063
+ }] : []);
4064
+ if (marked.length === 0) return EMPTY;
4065
+ const deletion = withoutMarked(text) === "" && statOf(file)?.isFile() === true ? [{
4066
+ action: "delete",
4067
+ file,
4068
+ line: null,
4069
+ summary: "Delete this file, which holds nothing else",
4070
+ text: null
4071
+ }] : [];
4072
+ return {
4073
+ changes: [...marked.map(({ line, text: content }) => ({
4074
+ action: "remove",
4075
+ file,
4076
+ line,
4077
+ summary: `Remove line ${String(line)}: ${content}`,
4078
+ text: content
4079
+ })), ...deletion],
4080
+ edits: [{
4081
+ change: withoutMarked,
4082
+ file,
4083
+ kind: "startup"
4084
+ }]
4085
+ };
4086
+ };
4087
+ const undoPlan = ({ home, shims }) => {
4088
+ const entries = folderEntries(shims);
4089
+ const own = entries.filter(isOwnShim);
4090
+ const folderGoes = statOf(shims)?.isDirectory() === true && own.length === entries.length;
4091
+ return joined([
4092
+ ...everyStartupFile(home).map(lineRemovals),
4093
+ ...own.map(shimDeletion),
4094
+ folderGoes ? {
4095
+ changes: [{
4096
+ action: "delete",
4097
+ file: shims,
4098
+ line: null,
4099
+ summary: "Delete this empty folder",
4100
+ text: null
4101
+ }],
4102
+ edits: [{
4103
+ file: shims,
4104
+ kind: "folder"
4105
+ }]
4106
+ } : EMPTY
4107
+ ]);
4108
+ };
4109
+ const replaceText = ({ file, mode, text }) => {
4110
+ const folder = path.dirname(file);
4111
+ fs.mkdirSync(folder, { recursive: true });
4112
+ const pending = path.join(folder, `.${path.basename(file)}.${crypto$1.randomBytes(8).toString("hex")}.tmp`);
4113
+ fs.writeFileSync(pending, text, { flag: "wx" });
4114
+ if (mode !== void 0) fs.chmodSync(pending, mode);
4115
+ fs.renameSync(pending, file);
4116
+ };
4117
+ const rewrite = ({ change, file }) => {
4118
+ const target = fs.existsSync(file) ? fs.realpathSync(file) : file;
4119
+ const before = textOf(target) ?? "";
4120
+ const after = change(before);
4121
+ if (after === before) return;
4122
+ if (after === "" && statOf(file)?.isFile() === true) {
4123
+ fs.rmSync(file);
4124
+ return;
4125
+ }
4126
+ const stat = statOf(target);
4127
+ replaceText({
4128
+ file: target,
4129
+ mode: stat === void 0 ? void 0 : stat.mode % FILE_TYPE_UNIT,
4130
+ text: after
4131
+ });
4132
+ };
4133
+ const apply = (edit) => {
4134
+ touched({
4135
+ file: edit.file,
4136
+ verb: "write",
4137
+ work: () => {
4138
+ if (edit.kind === "startup") rewrite(edit);
4139
+ else if (edit.kind === "shim") {
4140
+ fs.mkdirSync(path.dirname(edit.file), {
4141
+ mode: 448,
4142
+ recursive: true
4143
+ });
4144
+ replaceText({
4145
+ file: edit.file,
4146
+ mode: 493,
4147
+ text: edit.text
4148
+ });
4149
+ } else if (edit.kind === "delete") fs.rmSync(edit.file, { force: true });
4150
+ else if (fs.readdirSync(edit.file).length === 0) fs.rmdirSync(edit.file);
4151
+ }
4152
+ });
4153
+ };
4154
+ const resultOf = ({ changes, dropIns }) => ({
4155
+ changes: changes.map(({ action, file, line, text }) => ({
4156
+ action,
4157
+ file,
4158
+ line,
4159
+ text
4160
+ })),
4161
+ drop_ins: dropIns
4162
+ });
4163
+ const toolNotes = (dropIns) => dropIns.map(({ binary, installed, real_path: realPath, tool }) => {
4164
+ if (!installed) return `${tool} stays as it is, since ${binary} isn't installed.`;
4165
+ return realPath === null ? `${tool} runs ${binary} in each new terminal.` : `${tool} runs ${binary} in each new terminal. Your own ${tool} stays at ${realPath} and runs by that full path.`;
4166
+ });
4167
+ const confirmed = async ({ changes, context, dropIns, notes, undo }) => {
4168
+ context.io.context(changes.map(({ file, summary }) => ({
4169
+ label: file,
4170
+ value: summary
4171
+ })));
4172
+ context.io.note(notes);
4173
+ if (flagOf(context.options, "yes") === true) return;
4174
+ if (!context.mode.interactive || context.prompter === void 0) throw new CliFailure({
4175
+ data: resultOf({
4176
+ changes,
4177
+ dropIns
4178
+ }),
4179
+ message: `Can't ${undo ? "undo sandcovery setup" : "set up drop-ins"} without --yes in non-interactive mode.`,
4180
+ reason: "confirmation_required",
4181
+ recovery: [{
4182
+ instruction: "After a person approves the changes listed, run",
4183
+ next: {
4184
+ argv: [...context.rerun, "--yes"],
4185
+ when: "Only after a human approves the listed changes"
4186
+ }
4187
+ }],
4188
+ userActionRequired: true
4189
+ });
4190
+ if (!await context.prompter.confirm("Make these changes?")) throw new Canceled({
4191
+ remote: "none",
4192
+ signal: "SIGINT"
4193
+ });
4194
+ };
4195
+ const shimsOf = (context) => path.join(path.dirname(context.settingsFile), "bin");
4196
+ const shimFolder = (context) => {
4197
+ const shims = shimsOf(context);
4198
+ const characters = new Set(shims);
4199
+ if (characters.has(path.delimiter) || characters.has("\n")) throw new CliFailure({
4200
+ message: `Can't put ${shims} on PATH, since PATH can't hold a folder whose name has a colon or a line break.`,
4201
+ reason: "invalid_arguments",
4202
+ recovery: [{ instruction: "Choose another settings folder with --global-config" }]
4203
+ });
4204
+ return shims;
4205
+ };
4206
+ const setupDropIns = async (context) => {
4207
+ if (process.platform === "win32") throw new CliFailure({
4208
+ message: "Can't set up drop-ins on Windows. sandcovery setup changes the startup files of bash, zsh, and fish.",
4209
+ reason: "unsupported"
4210
+ });
4211
+ const undo = flagOf(context.options, "undo") === true;
4212
+ const home = os.homedir();
4213
+ const shims = shimFolder(context);
4214
+ const dropIns = DROP_INS.map(({ binary, tool }) => ({
4215
+ binary,
4216
+ installed: onPath({
4217
+ name: binary,
4218
+ shims
4219
+ }) !== null,
4220
+ real_path: onPath({
4221
+ name: tool,
4222
+ shims
4223
+ }),
4224
+ tool
4225
+ }));
4226
+ if (!undo && dropIns.every(({ installed }) => !installed)) throw new CliFailure({
4227
+ message: `Can't set up drop-ins. None of ${DROP_INS.map(({ binary }) => binary).join(", ")} is on PATH.`,
4228
+ notes: ["They come with the sandcovery npm package: npm install --global sandcovery."],
4229
+ reason: "not_found"
4230
+ });
4231
+ const plan = undo ? undoPlan({
4232
+ home,
4233
+ shims
4234
+ }) : joined([shimPlan({
4235
+ dropIns,
4236
+ shims
4237
+ }), linePlan({
4238
+ home,
4239
+ shims
4240
+ })]);
4241
+ const notes = undo ? [] : toolNotes(dropIns);
4242
+ if (plan.changes.length === 0) {
4243
+ context.io.note([undo ? "Nothing to undo." : "Nothing to change.", ...notes]);
4244
+ return { document: resultOf({
4245
+ changes: [],
4246
+ dropIns
4247
+ }) };
4248
+ }
4249
+ await confirmed({
4250
+ changes: plan.changes,
4251
+ context,
4252
+ dropIns,
4253
+ notes,
4254
+ undo
4255
+ });
4256
+ for (const edit of plan.edits) apply(edit);
4257
+ context.io.receipt({
4258
+ outcome: undo ? "Undone" : "Set up",
4259
+ target: shims
4260
+ });
4261
+ if (!undo) context.io.note(["Open a new terminal, so the shims come first on PATH there."]);
4262
+ return { document: resultOf({
4263
+ changes: plan.changes,
4264
+ dropIns
4265
+ }) };
4266
+ };
4267
+ // ../../node_modules/.pnpm/uuid@14.0.3/node_modules/uuid/dist-node/stringify.js
4268
+ const byteToHex = [];
4269
+ for (let i = 0; i < 256; ++i) byteToHex.push((i + 256).toString(16).slice(1));
4270
+ function unsafeStringify(arr, offset = 0) {
4271
+ return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
4272
+ }
4273
+ // ../../node_modules/.pnpm/uuid@14.0.3/node_modules/uuid/dist-node/rng.js
4274
+ const rnds8 = /* @__PURE__ */ new Uint8Array(16);
4275
+ function rng() {
4276
+ return crypto.getRandomValues(rnds8);
4277
+ }
4278
+ // ../../node_modules/.pnpm/uuid@14.0.3/node_modules/uuid/dist-node/v7.js
4279
+ const _state = {};
4280
+ function v7(options, buf, offset) {
4281
+ let bytes;
4282
+ if (options) bytes = v7Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.seq, buf, offset);
4283
+ else {
4284
+ const now = Date.now();
4285
+ const rnds = rng();
4286
+ updateV7State(_state, now, rnds);
4287
+ bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset);
4288
+ }
4289
+ return buf ?? unsafeStringify(bytes);
4290
+ }
4291
+ function updateV7State(state, now, rnds) {
4292
+ state.msecs ??= -Infinity;
4293
+ state.seq ??= 0;
4294
+ if (now > state.msecs) {
4295
+ state.seq = v7Sequence(rnds);
4296
+ state.msecs = now;
4297
+ } else {
4298
+ state.seq = state.seq + 1 | 0;
4299
+ if (state.seq === 0) state.msecs++;
4300
+ }
4301
+ return state;
4302
+ }
4303
+ function v7Bytes(rnds, msecs, seq, buf, offset = 0) {
4304
+ if (rnds.length < 16) throw new Error("Random bytes length must be >= 16");
4305
+ if (!buf) {
4306
+ buf = /* @__PURE__ */ new Uint8Array(16);
4307
+ offset = 0;
4308
+ } else if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
4309
+ msecs ??= Date.now();
4310
+ seq ??= v7Sequence(rnds);
4311
+ buf[offset++] = msecs / 1099511627776 & 255;
4312
+ buf[offset++] = msecs / 4294967296 & 255;
4313
+ buf[offset++] = msecs / 16777216 & 255;
4314
+ buf[offset++] = msecs / 65536 & 255;
4315
+ buf[offset++] = msecs / 256 & 255;
4316
+ buf[offset++] = msecs & 255;
4317
+ buf[offset++] = 112 | seq >>> 28 & 15;
4318
+ buf[offset++] = seq >>> 20 & 255;
4319
+ buf[offset++] = 128 | seq >>> 14 & 63;
4320
+ buf[offset++] = seq >>> 6 & 255;
4321
+ buf[offset++] = seq << 2 & 255 | rnds[10] & 3;
4322
+ buf[offset++] = rnds[11];
4323
+ buf[offset++] = rnds[12];
4324
+ buf[offset++] = rnds[13];
4325
+ buf[offset++] = rnds[14];
4326
+ buf[offset++] = rnds[15];
4327
+ return buf;
4328
+ }
4329
+ function v7Sequence(rnds) {
4330
+ return (rnds[6] & 127) << 24 | rnds[7] << 16 | rnds[8] << 8 | rnds[9];
4331
+ }
4332
+ // src/cli/relay.ts
4333
+ const RELAY_PORT = 9951;
4334
+ const RELAY_TOKEN_HEADER = "x-sandcovery-relay-token";
4335
+ const RELAY_SOURCE = String.raw`import base64
4336
+ import hashlib
4337
+ import hmac
4338
+ import json
4339
+ import os
4340
+ import socket
4341
+ import subprocess
4342
+ import sys
4343
+ import threading
4344
+
4345
+ GUID = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
4346
+ HEADER_LIMIT = 16384
4347
+ CHUNK = 65536
4348
+ KEEPALIVE_SECONDS = 30
4349
+ TEXT, BINARY, CLOSE, PING, PONG = 1, 2, 8, 9, 10
4350
+ EVENTS = [
4351
+ "docker", "events", "--format", "{{.Actor.ID}}",
4352
+ "--filter", "type=container",
4353
+ "--filter", "event=start",
4354
+ "--filter", "event=die",
4355
+ ]
4356
+
4357
+
4358
+ def shut(sock, how=socket.SHUT_RDWR):
4359
+ try:
4360
+ sock.shutdown(how)
4361
+ except OSError:
4362
+ pass
4363
+
4364
+
4365
+ class Peer:
4366
+ def __init__(self, conn):
4367
+ self.conn = conn
4368
+ self.buffer = b""
4369
+ self.lock = threading.Lock()
4370
+ self.done = threading.Event()
4371
+
4372
+ def fill(self):
4373
+ chunk = self.conn.recv(CHUNK)
4374
+ if not chunk:
4375
+ raise EOFError
4376
+ self.buffer += chunk
4377
+
4378
+ def take(self, size):
4379
+ while len(self.buffer) < size:
4380
+ self.fill()
4381
+ data, self.buffer = self.buffer[:size], self.buffer[size:]
4382
+ return data
4383
+
4384
+ def head(self):
4385
+ while b"\r\n\r\n" not in self.buffer:
4386
+ if len(self.buffer) > HEADER_LIMIT:
4387
+ raise EOFError
4388
+ self.fill()
4389
+ head, self.buffer = self.buffer.split(b"\r\n\r\n", 1)
4390
+ return head.decode("latin-1").split("\r\n")
4391
+
4392
+ def send(self, opcode, payload=b""):
4393
+ size = len(payload)
4394
+ if size < 126:
4395
+ head = bytes([0x80 | opcode, size])
4396
+ elif size < 65536:
4397
+ head = bytes([0x80 | opcode, 126]) + size.to_bytes(2, "big")
4398
+ else:
4399
+ head = bytes([0x80 | opcode, 127]) + size.to_bytes(8, "big")
4400
+ with self.lock:
4401
+ self.conn.sendall(head + payload)
4402
+
4403
+ def frame(self):
4404
+ first, second = self.take(2)
4405
+ size = second & 0x7F
4406
+ if size == 126:
4407
+ size = int.from_bytes(self.take(2), "big")
4408
+ elif size == 127:
4409
+ size = int.from_bytes(self.take(8), "big")
4410
+ mask = self.take(4) if second & 0x80 else b""
4411
+ payload = self.take(size)
4412
+ if mask and size:
4413
+ key = (mask * (size // 4 + 1))[:size]
4414
+ mixed = int.from_bytes(payload, "little") ^ int.from_bytes(key, "little")
4415
+ payload = mixed.to_bytes(size, "little")
4416
+ return first & 0x80, first & 0x0F, payload
4417
+
4418
+ def message(self):
4419
+ kind, parts = 0, []
4420
+ while True:
4421
+ final, opcode, payload = self.frame()
4422
+ if opcode == PING:
4423
+ self.send(PONG, payload)
4424
+ elif opcode == CLOSE:
4425
+ return CLOSE, b""
4426
+ elif opcode != PONG:
4427
+ kind = kind or opcode
4428
+ parts.append(payload)
4429
+ if final:
4430
+ return kind, b"".join(parts)
4431
+
4432
+
4433
+ def refuse(peer, status):
4434
+ peer.conn.sendall(
4435
+ ("HTTP/1.1 " + status + "\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").encode()
4436
+ )
4437
+
4438
+
4439
+ def keepalive(peer):
4440
+ while not peer.done.wait(KEEPALIVE_SECONDS):
4441
+ try:
4442
+ peer.send(PING)
4443
+ except OSError:
4444
+ return
4445
+
4446
+
4447
+ def accept(peer, key):
4448
+ digest = base64.b64encode(hashlib.sha1(key.encode() + GUID).digest()).decode()
4449
+ peer.conn.sendall(
4450
+ (
4451
+ "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\n"
4452
+ "Connection: Upgrade\r\nSec-WebSocket-Accept: " + digest + "\r\n\r\n"
4453
+ ).encode()
4454
+ )
4455
+ threading.Thread(target=keepalive, args=(peer,), daemon=True).start()
4456
+
4457
+
4458
+ def send_down(peer, upstream):
4459
+ try:
4460
+ while True:
4461
+ data = upstream.recv(CHUNK)
4462
+ peer.send(BINARY, data)
4463
+ if not data:
4464
+ return
4465
+ except OSError:
4466
+ shut(peer.conn)
4467
+
4468
+
4469
+ def pipe(peer, upstream):
4470
+ with upstream:
4471
+ threading.Thread(target=send_down, args=(peer, upstream), daemon=True).start()
4472
+ try:
4473
+ while True:
4474
+ opcode, payload = peer.message()
4475
+ if opcode == CLOSE:
4476
+ return
4477
+ if payload:
4478
+ upstream.sendall(payload)
4479
+ else:
4480
+ shut(upstream, socket.SHUT_WR)
4481
+ finally:
4482
+ shut(upstream)
4483
+ try:
4484
+ peer.send(CLOSE)
4485
+ except OSError:
4486
+ pass
4487
+
4488
+
4489
+ def ports_snapshot():
4490
+ ids = subprocess.run(
4491
+ ["docker", "ps", "--quiet", "--no-trunc"], capture_output=True, text=True
4492
+ ).stdout.split()
4493
+ if not ids:
4494
+ return "[]"
4495
+ shown = subprocess.run(
4496
+ ["docker", "inspect", "--format", "{{json .NetworkSettings.Ports}}", *ids],
4497
+ capture_output=True,
4498
+ text=True,
4499
+ ).stdout
4500
+ return "[" + ",".join(line for line in shown.splitlines() if line) + "]"
4501
+
4502
+
4503
+ def events(peer, key):
4504
+ accept(peer, key)
4505
+ lock = threading.Lock()
4506
+ watcher = subprocess.Popen(EVENTS, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
4507
+
4508
+ def snapshot(tag=None):
4509
+ with lock:
4510
+ shown = '{"ports":' + ports_snapshot() + ',"tag":' + json.dumps(tag) + "}"
4511
+ peer.send(TEXT, shown.encode())
4512
+
4513
+ def watch():
4514
+ try:
4515
+ for _ in watcher.stdout:
4516
+ snapshot()
4517
+ except OSError:
4518
+ pass
4519
+ shut(peer.conn)
4520
+
4521
+ try:
4522
+ threading.Thread(target=watch, daemon=True).start()
4523
+ snapshot()
4524
+ while True:
4525
+ opcode, payload = peer.message()
4526
+ if opcode == CLOSE:
4527
+ return
4528
+ snapshot(payload.decode("utf-8", "replace"))
4529
+ finally:
4530
+ watcher.kill()
4531
+ watcher.wait()
4532
+
4533
+
4534
+ def handle(conn, token):
4535
+ with conn:
4536
+ peer = Peer(conn)
4537
+ try:
4538
+ lines = peer.head()
4539
+ request = lines[0].split(" ")
4540
+ fields = {}
4541
+ for line in lines[1:]:
4542
+ name, _, value = line.partition(":")
4543
+ fields[name.strip().lower()] = value.strip()
4544
+ offered = fields.get("${RELAY_TOKEN_HEADER}", "").encode()
4545
+ key = fields.get("sec-websocket-key", "")
4546
+ if not hmac.compare_digest(offered, token):
4547
+ return refuse(peer, "401 Unauthorized")
4548
+ if len(request) != 3 or not key or fields.get("upgrade", "").lower() != "websocket":
4549
+ return refuse(peer, "400 Bad Request")
4550
+ target = request[1].split("?")[0]
4551
+ if target.endswith("/events"):
4552
+ return events(peer, key)
4553
+ _, found, digits = target.rpartition("/tcp/")
4554
+ number = int(digits) if found and digits.isascii() and digits.isdigit() else 0
4555
+ if not 0 < number < 65536:
4556
+ return refuse(peer, "404 Not Found")
4557
+ try:
4558
+ upstream = socket.create_connection(("127.0.0.1", number))
4559
+ except OSError:
4560
+ return refuse(peer, "502 Bad Gateway")
4561
+ accept(peer, key)
4562
+ pipe(peer, upstream)
4563
+ except (EOFError, OSError, ValueError):
4564
+ pass
4565
+ finally:
4566
+ peer.done.set()
4567
+
4568
+
4569
+ def main():
4570
+ port, token_file = int(sys.argv[1]), sys.argv[2]
4571
+ with open(token_file, "rb") as file:
4572
+ token = file.read().strip()
4573
+ os.remove(token_file)
4574
+ if not token:
4575
+ raise SystemExit("the relay token file is empty")
4576
+ try:
4577
+ server = socket.create_server(("", port), family=socket.AF_INET6, dualstack_ipv6=True)
4578
+ except (OSError, ValueError):
4579
+ server = socket.create_server(("", port))
4580
+ child = os.fork()
4581
+ if child:
4582
+ print(server.getsockname()[1], child, flush=True)
4583
+ os._exit(0)
4584
+ os.setsid()
4585
+ devnull = os.open(os.devnull, os.O_RDWR)
4586
+ for descriptor in (0, 1, 2):
4587
+ os.dup2(devnull, descriptor)
4588
+ while True:
4589
+ conn, _ = server.accept()
4590
+ threading.Thread(target=handle, args=(conn, token), daemon=True).start()
4591
+
4592
+
4593
+ main()
4594
+ `;
4595
+ // src/cli/port-forwarder.ts
4596
+ const FORWARDER_ENV = "__SANDCOVERY_PORT_FORWARDER";
4597
+ const BUFFERED_LIMIT = 4194304;
4598
+ const DRAIN_POLL_MS = 10;
4599
+ const SYNC_MS = 15e3;
4600
+ const UNATTACHED_MS = 6e4;
4601
+ const PREVIEW_MARGIN_MS = 6e4;
4602
+ const LONGEST_TIMER_MS = 2147483647;
4603
+ const RETRY_MS = [
4604
+ 1e3,
4605
+ 2e3,
4606
+ 5e3,
4607
+ 1e4,
4608
+ 3e4
4609
+ ];
4610
+ const ANY_IPV4 = "0.0.0.0";
4611
+ const HIGHEST_PORT = 65535;
4612
+ const UnforwardedSchema = Struct({
4613
+ host: String$1,
4614
+ port: Number$1,
4615
+ reason: Literals(["busy", "denied"])
4616
+ });
4617
+ const decodeRequest = decodeUnknownOption(fromJsonString(Struct({
4618
+ attachment: Struct({
4619
+ expires_at: String$1,
4620
+ key: String$1,
4621
+ origin: String$1,
4622
+ sandbox: String$1,
4623
+ token: String$1
4624
+ }),
4625
+ sync: Boolean
4626
+ })));
4627
+ const decodeReply = decodeUnknownOption(fromJsonString(Struct({ unforwarded: ArraySchema(UnforwardedSchema) })));
4628
+ const SnapshotSchema = Struct({
4629
+ ports: ArraySchema(NullOr(Record(String$1, NullOr(ArraySchema(Struct({
4630
+ HostIp: String$1,
4631
+ HostPort: String$1
4632
+ })))))),
4633
+ tag: NullOr(String$1)
4634
+ });
4635
+ const decodeSnapshot = decodeUnknownOption(fromJsonString(SnapshotSchema));
4636
+ const keyOf = ({ host, port }) => `${host} ${String(port)}`;
4637
+ const isPort = (port) => Number.isInteger(port) && port > 0 && port <= HIGHEST_PORT;
4638
+ const publishedIn = (ports) => ports.flatMap((container) => Object.entries(container ?? {}).flatMap(([target, bindings]) => target.endsWith("/tcp") ? (bindings ?? []).flatMap(({ HostIp, HostPort }) => {
4639
+ const port = Number(HostPort);
4640
+ return isPort(port) ? [{
4641
+ host: HostIp === "" ? ANY_IPV4 : HostIp,
4642
+ port
4643
+ }] : [];
4644
+ }) : []));
4645
+ const errorCode = (error) => error.code ?? "";
4646
+ const cancel = (timer) => {
4647
+ if (timer !== null) clearTimeout(timer);
4648
+ return null;
4649
+ };
4650
+ const heldUntil = async (attachment) => {
4651
+ const [read] = await Promise.allSettled([new Sandcovery({
4652
+ apiKey: attachment.key,
4653
+ baseUrl: attachment.origin
4654
+ }).sandboxes.get(attachment.sandbox)]);
4655
+ return read.status === "fulfilled" && read.value.status === "running" ? Date.parse(read.value.expires_at) : Number.NEGATIVE_INFINITY;
4656
+ };
4657
+ const resumedWhenDrained = (remote, local) => {
4658
+ const timer = setInterval(() => {
4659
+ if (remote.bufferedAmount <= BUFFERED_LIMIT || remote.readyState !== WebSocket.OPEN) {
4660
+ clearInterval(timer);
4661
+ local.resume();
4662
+ }
4663
+ }, DRAIN_POLL_MS);
4664
+ };
4665
+ const carry = (local, remote) => {
4666
+ const ended = {
4667
+ local: false,
4668
+ remote: false
4669
+ };
4670
+ const finish = () => {
4671
+ if (ended.local && ended.remote) remote.close();
4672
+ };
4673
+ remote.addEventListener("open", () => {
4674
+ local.resume();
4675
+ });
4676
+ remote.addEventListener("message", ({ data }) => {
4677
+ if (!(data instanceof ArrayBuffer)) return;
4678
+ if (data.byteLength === 0) {
4679
+ ended.remote = true;
4680
+ local.end();
4681
+ finish();
4682
+ } else local.write(new Uint8Array(data));
4683
+ });
4684
+ remote.addEventListener("close", () => {
4685
+ if (!ended.local || !ended.remote) local.destroy();
4686
+ });
4687
+ local.on("data", (chunk) => {
4688
+ remote.send(chunk);
4689
+ if (remote.bufferedAmount > BUFFERED_LIMIT) {
4690
+ local.pause();
4691
+ resumedWhenDrained(remote, local);
4692
+ }
4693
+ });
4694
+ local.once("end", () => {
4695
+ ended.local = true;
4696
+ remote.send(/* @__PURE__ */ new Uint8Array());
4697
+ finish();
4698
+ });
4699
+ local.once("error", () => {
4700
+ remote.close();
4701
+ });
4702
+ };
4703
+ const forwarderSocket = (settingsFile) => socketOf({
4704
+ name: "docker-ports",
4705
+ settingsFile
4706
+ });
4707
+ const requested = async (connection) => {
4708
+ const chunks = [];
4709
+ const { promise, resolve } = Promise.withResolvers();
4710
+ connection.on("data", (chunk) => {
4711
+ chunks.push(chunk);
4712
+ });
4713
+ connection.once("end", () => {
4714
+ resolve(Buffer.concat(chunks).toString("utf-8"));
4715
+ });
4716
+ connection.once("close", () => {
4717
+ resolve("");
4718
+ });
4719
+ return await promise;
4720
+ };
4721
+ const forwardPorts = async (socketPath) => {
4722
+ const state = {
4723
+ applying: false,
4724
+ attachment: null,
4725
+ bound: /* @__PURE__ */ new Map(),
4726
+ connecting: false,
4727
+ control: null,
4728
+ expiry: null,
4729
+ failures: 0,
4730
+ latest: null,
4731
+ notices: /* @__PURE__ */ new Map(),
4732
+ relay: null,
4733
+ retry: null,
4734
+ syncs: /* @__PURE__ */ new Map()
4735
+ };
4736
+ const listener = net.createServer({ allowHalfOpen: true });
4737
+ const release = () => {
4738
+ for (const server of state.bound.values()) server.close();
4739
+ state.bound.clear();
4740
+ state.notices.clear();
4741
+ state.latest = null;
4742
+ state.relay = null;
4743
+ state.failures = 0;
4744
+ state.retry = cancel(state.retry);
4745
+ const { control } = state;
4746
+ state.control = null;
4747
+ control?.close();
4748
+ };
4749
+ const wakeSyncs = () => {
4750
+ for (const wake of state.syncs.values()) wake();
4751
+ };
4752
+ const stop = () => {
4753
+ release();
4754
+ state.attachment = null;
4755
+ state.expiry = cancel(state.expiry);
4756
+ listener.close();
4757
+ wakeSyncs();
4758
+ };
4759
+ const expireAt = (deadline) => {
4760
+ const settle = async () => {
4761
+ const { attachment } = state;
4762
+ const later = Date.now() < deadline || attachment === null ? deadline : await heldUntil(attachment);
4763
+ if (state.attachment !== attachment) return;
4764
+ if (later > Date.now()) expireAt(later);
4765
+ else stop();
4766
+ };
4767
+ cancel(state.expiry);
4768
+ state.expiry = setTimeout(() => {
4769
+ settle();
4770
+ }, clamp(deadline - Date.now(), 0, LONGEST_TIMER_MS));
4771
+ };
4772
+ const relay = async (attachment) => {
4773
+ if (state.relay !== null && state.relay.expiresAt - Date.now() > PREVIEW_MARGIN_MS) return state.relay;
4774
+ const preview = await new Sandcovery({
4775
+ apiKey: attachment.key,
4776
+ baseUrl: attachment.origin
4777
+ }).sandboxes.portPreview(attachment.sandbox, RELAY_PORT);
4778
+ state.relay = {
4779
+ expiresAt: preview.expires_at === null ? Number.POSITIVE_INFINITY : Date.parse(preview.expires_at),
4780
+ headers: preview.headers,
4781
+ url: preview.url
4782
+ };
4783
+ return state.relay;
4784
+ };
4785
+ const attempted = async (attachment, target, listen) => {
4786
+ try {
4787
+ const current = await relay(attachment);
4788
+ const url = new URL(current.url);
4789
+ url.pathname = `${url.pathname.endsWith("/") ? url.pathname.slice(0, -1) : url.pathname}${target}`;
4790
+ const socket = new WebSocket(url, { headers: {
4791
+ ...current.headers,
4792
+ [RELAY_TOKEN_HEADER]: attachment.token
4793
+ } });
4794
+ socket.binaryType = "arraybuffer";
4795
+ listen(socket);
4796
+ return socket;
4797
+ } catch (error) {
4798
+ if (error instanceof Error) return error;
4799
+ throw error;
4800
+ }
4801
+ };
4802
+ const tunnel = async (local, port) => {
4803
+ local.on("error", noop);
4804
+ const { attachment } = state;
4805
+ const outcome = attachment === null ? null : await attempted(attachment, `/tcp/${String(port)}`, (remote) => {
4806
+ carry(local, remote);
4807
+ });
4808
+ if (outcome === null || outcome instanceof Error) local.destroy();
4809
+ };
4810
+ const bind = async (published) => {
4811
+ const { host, port } = published;
4812
+ const server = net.createServer({
4813
+ allowHalfOpen: true,
4814
+ pauseOnConnect: true
4815
+ }, (local) => {
4816
+ tunnel(local, port);
4817
+ });
4818
+ const { promise, resolve } = Promise.withResolvers();
4819
+ server.once("error", (error) => {
4820
+ const code = errorCode(error);
4821
+ if (code === "EADDRINUSE") resolve({
4822
+ host,
4823
+ port,
4824
+ reason: "busy"
4825
+ });
4826
+ else if (code === "EACCES") resolve({
4827
+ host,
4828
+ port,
4829
+ reason: "denied"
4830
+ });
4831
+ else resolve(null);
4832
+ });
4833
+ server.listen({
4834
+ host,
4835
+ ipv6Only: host.includes(":"),
4836
+ port
4837
+ }, () => {
4838
+ server.on("error", noop);
4839
+ state.bound.set(keyOf(published), server);
4840
+ resolve(null);
4841
+ });
4842
+ return await promise;
4843
+ };
4844
+ const apply = async (published) => {
4845
+ const wanted = new Map(published.map((entry) => [keyOf(entry), entry]));
4846
+ for (const [key, server] of state.bound) if (!wanted.has(key)) {
4847
+ server.close();
4848
+ state.bound.delete(key);
4849
+ }
4850
+ for (const key of state.notices.keys()) if (!wanted.has(key)) state.notices.delete(key);
4851
+ const refused = await Promise.all([...wanted.values()].flatMap((entry) => state.bound.has(keyOf(entry)) ? [] : [bind(entry)]));
4852
+ for (const key of state.bound.keys()) state.notices.delete(key);
4853
+ for (const entry of refused) if (entry !== null && !state.notices.has(keyOf(entry))) state.notices.set(keyOf(entry), {
4854
+ entry,
4855
+ reported: false
4856
+ });
4857
+ };
4858
+ const applyLatest = async () => {
4859
+ const next = state.latest;
4860
+ if (next === null || state.applying) return;
4861
+ state.latest = null;
4862
+ state.applying = true;
4863
+ try {
4864
+ await apply(next.published);
4865
+ } finally {
4866
+ state.applying = false;
4867
+ }
4868
+ for (const tag of next.tags) state.syncs.get(tag)?.();
4869
+ await applyLatest();
4870
+ };
4871
+ const received = ({ ports, tag }) => {
4872
+ state.latest = {
4873
+ published: publishedIn(ports),
4874
+ tags: [...state.latest?.tags ?? [], ...tag === null ? [] : [tag]]
4875
+ };
4876
+ applyLatest();
4877
+ };
4878
+ const requestSync = (tag) => {
4879
+ if (state.control?.readyState === WebSocket.OPEN) state.control.send(tag);
4880
+ };
4881
+ const watch = (control) => {
4882
+ state.control = control;
4883
+ control.addEventListener("open", () => {
4884
+ state.failures = 0;
4885
+ for (const tag of state.syncs.keys()) requestSync(tag);
4886
+ });
4887
+ control.addEventListener("message", ({ data }) => {
4888
+ const snapshot = decodeSnapshot(data);
4889
+ if (isSome(snapshot)) received(snapshot.value);
4890
+ });
4891
+ };
4892
+ const connect = async () => {
4893
+ const { attachment } = state;
4894
+ if (attachment === null || state.control !== null || state.connecting) return;
4895
+ state.connecting = true;
4896
+ const { promise: ended, resolve: end } = Promise.withResolvers();
4897
+ const outcome = await attempted(attachment, "/events", (control) => {
4898
+ control.addEventListener("close", () => {
4899
+ end(null);
4900
+ });
4901
+ if (state.attachment?.sandbox === attachment.sandbox) watch(control);
4902
+ else control.close();
4903
+ });
4904
+ state.connecting = false;
4905
+ if (outcome instanceof Error) {
4906
+ state.relay = null;
4907
+ if (isTerminal(outcome)) stop();
4908
+ wakeSyncs();
4909
+ } else if (state.control === outcome) {
4910
+ await ended;
4911
+ if (state.control !== outcome) return;
4912
+ state.control = null;
4913
+ state.relay = null;
4914
+ wakeSyncs();
4915
+ }
4916
+ if (state.attachment === null || state.retry !== null) return;
4917
+ const delay = RETRY_MS[Math.min(state.failures, RETRY_MS.length - 1)];
4918
+ state.failures += 1;
4919
+ state.retry = setTimeout(() => {
4920
+ state.retry = null;
4921
+ connect();
4922
+ }, delay);
4923
+ };
4924
+ const attach = (attachment) => {
4925
+ if (state.attachment?.sandbox !== attachment.sandbox) release();
4926
+ state.attachment = attachment;
4927
+ expireAt(Date.parse(attachment.expires_at));
4928
+ connect();
4929
+ };
4930
+ const synced = async () => {
4931
+ const tag = v7();
4932
+ const { promise, resolve } = Promise.withResolvers();
4933
+ const wake = () => {
4934
+ resolve(null);
4935
+ };
4936
+ const timer = setTimeout(wake, SYNC_MS);
4937
+ state.syncs.set(tag, wake);
4938
+ requestSync(tag);
4939
+ await promise;
4940
+ clearTimeout(timer);
4941
+ state.syncs.delete(tag);
4942
+ };
4943
+ const notices = () => [...state.notices.values()].flatMap((notice) => {
4944
+ if (notice.reported) return [];
4945
+ notice.reported = true;
4946
+ return [notice.entry];
4947
+ });
4948
+ const answer = async (connection) => {
4949
+ connection.on("error", noop);
4950
+ const request = decodeRequest(await requested(connection));
4951
+ if (isNone(request)) {
4952
+ connection.destroy();
4953
+ return;
4954
+ }
4955
+ attach(request.value.attachment);
4956
+ if (request.value.sync) await synced();
4957
+ connection.end(`${JSON.stringify({ unforwarded: notices() })}\n`);
4958
+ };
4959
+ listener.on("connection", (connection) => {
4960
+ answer(connection);
4961
+ });
4962
+ const serving = await servedAt(listener, socketPath);
4963
+ process.stdout.write(READY);
4964
+ if (serving) expireAt(Date.now() + UNATTACHED_MS);
4965
+ };
4966
+ const asked = async ({ line, socketPath }) => {
4967
+ const socket = net.connect(socketPath);
4968
+ const reply = text(socket);
4969
+ socket.end(line);
4970
+ return await reply;
4971
+ };
4972
+ const attachForwarder = async ({ attachment, entry, socketPath, sync }) => {
4973
+ const line = `${JSON.stringify({
4974
+ attachment,
4975
+ sync
4976
+ })}\n`;
4977
+ const reply = await servedOrSpawned({
4978
+ attempt: async () => await asked({
4979
+ line,
4980
+ socketPath
4981
+ }),
4982
+ entry,
4983
+ env: { [FORWARDER_ENV]: socketPath }
4984
+ });
4985
+ return getOrThrowWith(decodeReply(reply), () => /* @__PURE__ */ new Error("The port forwarder stopped before it answered.")).unforwarded;
4986
+ };
4987
+ export { exitCodeOf as $, isOptionValue as A, plainPrefix as B, enabledVariable as C, closest as D, productVariable as E, rerunArgv as F, remoteLine as G, theme as H, valuesOf as I, isDigit as J, remoteText as K, clearLine as L, parseFailure as M, parseLeaf as N, flagOf as O, readOptionToken as P, CliFailure as Q, ellipsis as R, writePrivateFile as S, modeOf as T, escapeUnprintable as U, spinnerFrame as V, remoteCell as W, isUpper as X, isDigits as Y, isWordCharacter as Z, formatMoney as _, RELAY_PORT as a, holdCluster as at, configDirectory as b, onPath as c, Clock as ct, BIN as d, statusOf as et, CLEARABLE as f, formatCount as g, counted as h, forwarderSocket as i, IDLE_WATCHER_ENV as it, lastValue as j, isOptionToken as k, setupDropIns as l, PROBLEM_REPORT_MAX as m, attachForwarder as n, Canceled as nt, RELAY_SOURCE as o, watchIdle as ot, CLI as p, consistsOf as q, forwardPorts as r, IDLE_MS as rt, v7 as s, noop as st, FORWARDER_ENV as t, usageFailure as tt, shimsOf as u, formatPercent as v, guidanceOn as w, withFileLock as x, version as y, glyph as z };