@kibotos/sdk 0.0.0-stage → 0.2.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/dist/index.js ADDED
@@ -0,0 +1,1479 @@
1
+ // src/errors.ts
2
+ var KibotosError = class extends Error {
3
+ constructor(message, options) {
4
+ super(message, options);
5
+ this.name = new.target.name;
6
+ Object.setPrototypeOf(this, new.target.prototype);
7
+ }
8
+ };
9
+ var APIConnectionError = class extends KibotosError {
10
+ constructor(message = "Failed to connect to the Kibotos API", options) {
11
+ super(message, options);
12
+ }
13
+ };
14
+ var KibotosAPIError = class extends KibotosError {
15
+ status;
16
+ code;
17
+ requestId;
18
+ retryable;
19
+ details;
20
+ headers;
21
+ constructor(init) {
22
+ super(init.message, init.cause !== void 0 ? { cause: init.cause } : void 0);
23
+ this.status = init.status;
24
+ this.code = init.code;
25
+ this.requestId = init.requestId;
26
+ this.retryable = init.retryable;
27
+ this.details = init.details;
28
+ this.headers = init.headers;
29
+ }
30
+ };
31
+ var AuthenticationError = class extends KibotosAPIError {
32
+ };
33
+ var PermissionDeniedError = class extends KibotosAPIError {
34
+ };
35
+ var NotFoundError = class extends KibotosAPIError {
36
+ };
37
+ var WaitTimeoutError = class extends KibotosAPIError {
38
+ };
39
+ var ConflictError = class extends KibotosAPIError {
40
+ };
41
+ var UnexpectedStatusError = class extends ConflictError {
42
+ };
43
+ var RateLimitError = class extends KibotosAPIError {
44
+ /** Parsed `Retry-After` delay in milliseconds, if provided by the server. */
45
+ retryAfterMs;
46
+ constructor(init) {
47
+ super(init);
48
+ this.retryAfterMs = init.retryAfterMs;
49
+ }
50
+ };
51
+ var DEFAULT_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
52
+ function parseRetryAfterMs(headerValue, nowMs = Date.now()) {
53
+ if (!headerValue) {
54
+ return void 0;
55
+ }
56
+ const trimmed = headerValue.trim();
57
+ if (trimmed.length === 0) {
58
+ return void 0;
59
+ }
60
+ const seconds = Number(trimmed);
61
+ if (Number.isFinite(seconds) && seconds >= 0) {
62
+ return Math.round(seconds * 1e3);
63
+ }
64
+ const dateMs = Date.parse(trimmed);
65
+ if (!Number.isNaN(dateMs)) {
66
+ return Math.max(0, dateMs - nowMs);
67
+ }
68
+ return void 0;
69
+ }
70
+ function isErrorEnvelope(value) {
71
+ if (typeof value !== "object" || value === null) {
72
+ return false;
73
+ }
74
+ const err = value.error;
75
+ return typeof err === "object" && err !== null;
76
+ }
77
+ function createAPIError(status, headers, body, fallbackMessage) {
78
+ const headerRequestId = headers.get("Request-Id") ?? void 0;
79
+ let code = "http_error";
80
+ let message = fallbackMessage || `Kibotos API request failed with status ${status}`;
81
+ let requestId = headerRequestId;
82
+ let retryable = DEFAULT_RETRYABLE_STATUSES.has(status);
83
+ let details;
84
+ if (isErrorEnvelope(body)) {
85
+ const err = body.error;
86
+ if (typeof err.code === "string" && err.code.length > 0) {
87
+ code = err.code;
88
+ }
89
+ if (typeof err.message === "string" && err.message.length > 0) {
90
+ message = err.message;
91
+ }
92
+ if (typeof err.request_id === "string" && err.request_id.length > 0) {
93
+ requestId = err.request_id;
94
+ }
95
+ if (typeof err.retryable === "boolean") {
96
+ retryable = err.retryable;
97
+ }
98
+ if (typeof err.details === "object" && err.details !== null && !Array.isArray(err.details)) {
99
+ details = err.details;
100
+ }
101
+ }
102
+ const init = {
103
+ status,
104
+ code,
105
+ message,
106
+ requestId,
107
+ retryable,
108
+ details,
109
+ headers
110
+ };
111
+ if (status === 401) {
112
+ return new AuthenticationError(init);
113
+ }
114
+ if (status === 403) {
115
+ return new PermissionDeniedError(init);
116
+ }
117
+ if (status === 404) {
118
+ return new NotFoundError(init);
119
+ }
120
+ if (status === 408) {
121
+ return new WaitTimeoutError(init);
122
+ }
123
+ if (status === 409) {
124
+ if (code === "unexpected_status") {
125
+ return new UnexpectedStatusError(init);
126
+ }
127
+ return new ConflictError(init);
128
+ }
129
+ if (status === 429) {
130
+ const retryAfterMs = parseRetryAfterMs(headers.get("Retry-After"));
131
+ return new RateLimitError({ ...init, retryAfterMs });
132
+ }
133
+ return new KibotosAPIError(init);
134
+ }
135
+
136
+ // src/http.ts
137
+ var DEFAULT_BASE_URL = "https://api.kibo.to/v1";
138
+ var DEFAULT_MAX_RETRIES = 3;
139
+ var DEFAULT_TIMEOUT_MS = 3e4;
140
+ var SDK_VERSION = "0.2.0";
141
+ var INITIAL_RETRY_DELAY_MS = 500;
142
+ var MAX_RETRY_DELAY_MS = 8e3;
143
+ var RETRYABLE_HTTP_STATUSES = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
144
+ function readEnv(name) {
145
+ try {
146
+ const proc = globalThis.process;
147
+ if (proc && typeof proc === "object" && proc.env && typeof proc.env === "object") {
148
+ const val = proc.env[name];
149
+ return typeof val === "string" && val.length > 0 ? val : void 0;
150
+ }
151
+ } catch {
152
+ }
153
+ return void 0;
154
+ }
155
+ function normalizeBaseUrl(rawUrl) {
156
+ const trimmed = rawUrl.trim().replace(/\/+$/, "");
157
+ if (trimmed.length === 0) {
158
+ return DEFAULT_BASE_URL;
159
+ }
160
+ if (trimmed.endsWith("/v1")) {
161
+ return trimmed;
162
+ }
163
+ return `${trimmed}/v1`;
164
+ }
165
+ function generateUuid() {
166
+ if (typeof globalThis.crypto?.randomUUID === "function") {
167
+ return globalThis.crypto.randomUUID();
168
+ }
169
+ const bytes = new Uint8Array(16);
170
+ globalThis.crypto.getRandomValues(bytes);
171
+ bytes[6] = (bytes[6] ?? 0) & 15 | 64;
172
+ bytes[8] = (bytes[8] ?? 0) & 63 | 128;
173
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
174
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
175
+ }
176
+ function createAbortError(signal) {
177
+ if (signal.reason !== void 0) {
178
+ return signal.reason;
179
+ }
180
+ if (typeof DOMException !== "undefined") {
181
+ return new DOMException("The operation was aborted.", "AbortError");
182
+ }
183
+ const err = new Error("The operation was aborted.");
184
+ err.name = "AbortError";
185
+ return err;
186
+ }
187
+ function combineSignals(userSignal, timeoutMs) {
188
+ const hasTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0;
189
+ if (!userSignal && !hasTimeout) {
190
+ return { signal: void 0, isTimeout: () => false, cleanup: () => {
191
+ } };
192
+ }
193
+ let timedOut = false;
194
+ if (!userSignal && hasTimeout) {
195
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
196
+ timeoutSignal.addEventListener(
197
+ "abort",
198
+ () => {
199
+ timedOut = true;
200
+ },
201
+ { once: true }
202
+ );
203
+ return {
204
+ signal: timeoutSignal,
205
+ isTimeout: () => timedOut || timeoutSignal.aborted,
206
+ cleanup: () => {
207
+ }
208
+ };
209
+ }
210
+ if (userSignal && !hasTimeout) {
211
+ return {
212
+ signal: userSignal,
213
+ isTimeout: () => false,
214
+ cleanup: () => {
215
+ }
216
+ };
217
+ }
218
+ const controller = new AbortController();
219
+ const onUserAbort = () => {
220
+ controller.abort(createAbortError(userSignal));
221
+ };
222
+ if (userSignal.aborted) {
223
+ controller.abort(createAbortError(userSignal));
224
+ return {
225
+ signal: controller.signal,
226
+ isTimeout: () => false,
227
+ cleanup: () => {
228
+ }
229
+ };
230
+ }
231
+ userSignal.addEventListener("abort", onUserAbort, { once: true });
232
+ const timer = setTimeout(() => {
233
+ timedOut = true;
234
+ controller.abort(new Error(`Request timed out after ${timeoutMs}ms`));
235
+ }, timeoutMs);
236
+ return {
237
+ signal: controller.signal,
238
+ isTimeout: () => timedOut,
239
+ cleanup: () => {
240
+ clearTimeout(timer);
241
+ userSignal.removeEventListener("abort", onUserAbort);
242
+ }
243
+ };
244
+ }
245
+ function combineResponseSignals(userSignal, timeoutMs) {
246
+ const hasTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0;
247
+ if (userSignal && hasTimeout && typeof AbortSignal.any !== "function") {
248
+ const combined = combineSignals(userSignal, timeoutMs);
249
+ combined.signal?.addEventListener("abort", combined.cleanup, { once: true });
250
+ return combined;
251
+ }
252
+ const timeoutSignal = hasTimeout ? AbortSignal.timeout(timeoutMs) : void 0;
253
+ return {
254
+ signal: userSignal && timeoutSignal ? AbortSignal.any([userSignal, timeoutSignal]) : userSignal ?? timeoutSignal,
255
+ isTimeout: () => timeoutSignal?.aborted === true,
256
+ cleanup: () => {
257
+ }
258
+ };
259
+ }
260
+ function sleep(ms, signal) {
261
+ if (signal?.aborted) {
262
+ return Promise.reject(createAbortError(signal));
263
+ }
264
+ if (ms <= 0) {
265
+ return Promise.resolve();
266
+ }
267
+ return new Promise((resolve, reject) => {
268
+ const onAbort = () => {
269
+ clearTimeout(timer);
270
+ reject(createAbortError(signal));
271
+ };
272
+ const timer = setTimeout(() => {
273
+ signal?.removeEventListener("abort", onAbort);
274
+ resolve();
275
+ }, ms);
276
+ signal?.addEventListener("abort", onAbort, { once: true });
277
+ });
278
+ }
279
+ function calculateBackoffMs(attempt, retryAfterMs) {
280
+ if (retryAfterMs !== void 0 && Number.isFinite(retryAfterMs) && retryAfterMs >= 0) {
281
+ return retryAfterMs;
282
+ }
283
+ const exponential = Math.min(INITIAL_RETRY_DELAY_MS * 2 ** attempt, MAX_RETRY_DELAY_MS);
284
+ const jitter = 0.5 + Math.random() * 0.5;
285
+ return Math.round(exponential * jitter);
286
+ }
287
+ var HttpClient = class {
288
+ baseUrl;
289
+ maxRetries;
290
+ timeoutMs;
291
+ apiKey;
292
+ fetchImpl;
293
+ defaultHeaders;
294
+ constructor(options = {}) {
295
+ this.apiKey = options.apiKey ?? readEnv("KIBOTOS_API_KEY");
296
+ this.baseUrl = normalizeBaseUrl(options.baseUrl ?? readEnv("KIBOTOS_API_URL") ?? DEFAULT_BASE_URL);
297
+ this.maxRetries = Math.max(0, options.maxRetries ?? DEFAULT_MAX_RETRIES);
298
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
299
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
300
+ this.defaultHeaders = { ...options.defaultHeaders ?? {} };
301
+ if (typeof this.fetchImpl !== "function") {
302
+ throw new APIConnectionError(
303
+ "No fetch implementation found. Provide a custom `fetch` option or use a runtime with global `fetch` (Node 20+, Bun, Deno, Cloudflare Workers)."
304
+ );
305
+ }
306
+ }
307
+ buildUrl(path, query) {
308
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
309
+ const url = new URL(`${this.baseUrl}${normalizedPath}`);
310
+ if (query) {
311
+ query.forEach((value, key) => {
312
+ url.searchParams.append(key, value);
313
+ });
314
+ }
315
+ return url.toString();
316
+ }
317
+ buildHeaders(overrides) {
318
+ const headers = new Headers();
319
+ if (this.apiKey) {
320
+ headers.set("Authorization", `Bearer ${this.apiKey}`);
321
+ }
322
+ for (const [k, v] of Object.entries(this.defaultHeaders)) {
323
+ headers.set(k, v);
324
+ }
325
+ for (const [k, v] of Object.entries(overrides ?? {})) {
326
+ headers.set(k, v);
327
+ }
328
+ return headers;
329
+ }
330
+ async request(config) {
331
+ return await this.perform(config, false);
332
+ }
333
+ requestResponse(config) {
334
+ return this.perform(config, true);
335
+ }
336
+ async perform(config, rawResponse) {
337
+ const { method, path, query, body, rawBody, opts, disableWaitTimeoutRetry } = config;
338
+ const url = this.buildUrl(path, query);
339
+ const effectiveTimeoutMs = opts?.timeoutMs ?? this.timeoutMs;
340
+ const userSignal = opts?.signal;
341
+ const maxRetries = config.nonReplayable ? 0 : this.maxRetries;
342
+ const headers = this.buildHeaders(opts?.headers);
343
+ headers.set("Accept", config.accept ?? headers.get("Accept") ?? "application/json");
344
+ if (!headers.has("User-Agent")) {
345
+ headers.set("User-Agent", `@kibotos/sdk/${SDK_VERSION}`);
346
+ }
347
+ const requestBody = rawBody ?? (body === void 0 ? void 0 : JSON.stringify(body));
348
+ if (requestBody !== void 0 && !headers.has("Content-Type")) {
349
+ headers.set("Content-Type", rawBody === void 0 ? "application/json" : "application/octet-stream");
350
+ }
351
+ if (config.disableIdempotency) {
352
+ headers.delete("Idempotency-Key");
353
+ } else if (opts?.idempotencyKey) {
354
+ headers.set("Idempotency-Key", opts.idempotencyKey);
355
+ } else if (method === "POST" && !headers.has("Idempotency-Key")) {
356
+ headers.set("Idempotency-Key", generateUuid());
357
+ }
358
+ let attempt = 0;
359
+ while (true) {
360
+ if (userSignal?.aborted) {
361
+ throw createAbortError(userSignal);
362
+ }
363
+ const { signal, isTimeout, cleanup } = rawResponse ? combineResponseSignals(userSignal, effectiveTimeoutMs) : combineSignals(userSignal, effectiveTimeoutMs);
364
+ let response;
365
+ try {
366
+ const init = {
367
+ method,
368
+ headers,
369
+ body: requestBody,
370
+ signal
371
+ };
372
+ if (config.duplex) init.duplex = config.duplex;
373
+ response = await this.fetchImpl(url, init);
374
+ } catch (err) {
375
+ cleanup();
376
+ if (userSignal?.aborted) {
377
+ throw createAbortError(userSignal);
378
+ }
379
+ const connectionError = isTimeout() ? new APIConnectionError(`Request timed out after ${effectiveTimeoutMs}ms`, { cause: err }) : new APIConnectionError(
380
+ err instanceof Error && err.message ? `Network error: ${err.message}` : "Network error while contacting the Kibotos API",
381
+ { cause: err }
382
+ );
383
+ if (attempt < maxRetries) {
384
+ const delayMs = calculateBackoffMs(attempt);
385
+ attempt += 1;
386
+ await sleep(delayMs, userSignal);
387
+ continue;
388
+ }
389
+ throw connectionError;
390
+ }
391
+ if (rawResponse && (response.ok || config.successStatuses?.includes(response.status))) {
392
+ return response;
393
+ }
394
+ let parsedBody;
395
+ try {
396
+ const text = await response.text();
397
+ if (text.length > 0) {
398
+ try {
399
+ parsedBody = JSON.parse(text);
400
+ } catch {
401
+ parsedBody = text;
402
+ }
403
+ }
404
+ } catch (err) {
405
+ cleanup();
406
+ if (userSignal?.aborted) {
407
+ throw createAbortError(userSignal);
408
+ }
409
+ const readError = isTimeout() ? new APIConnectionError(`Request timed out after ${effectiveTimeoutMs}ms`, { cause: err }) : new APIConnectionError("Failed to read response body from the Kibotos API", { cause: err });
410
+ if (attempt < maxRetries) {
411
+ const delayMs = calculateBackoffMs(attempt);
412
+ attempt += 1;
413
+ await sleep(delayMs, userSignal);
414
+ continue;
415
+ }
416
+ throw readError;
417
+ } finally {
418
+ cleanup();
419
+ }
420
+ if (response.ok) {
421
+ return parsedBody;
422
+ }
423
+ const apiError = createAPIError(
424
+ response.status,
425
+ response.headers,
426
+ parsedBody,
427
+ response.statusText || void 0
428
+ );
429
+ if (this.shouldRetryAPIError(apiError, disableWaitTimeoutRetry) && attempt < maxRetries) {
430
+ const retryAfterMs = apiError instanceof RateLimitError ? apiError.retryAfterMs : parseRetryAfterMs(response.headers.get("Retry-After"));
431
+ const delayMs = calculateBackoffMs(attempt, retryAfterMs);
432
+ attempt += 1;
433
+ await sleep(delayMs, userSignal);
434
+ continue;
435
+ }
436
+ throw apiError;
437
+ }
438
+ }
439
+ shouldRetryAPIError(error, disableWaitTimeoutRetry) {
440
+ if (disableWaitTimeoutRetry && error.status === 408 && error.code === "wait_timeout") {
441
+ return false;
442
+ }
443
+ return error.retryable || RETRYABLE_HTTP_STATUSES.has(error.status);
444
+ }
445
+ };
446
+
447
+ // src/pagination.ts
448
+ async function* paginate(fetchPage, initialPageToken) {
449
+ let pageToken = initialPageToken;
450
+ const seenTokens = /* @__PURE__ */ new Set();
451
+ while (true) {
452
+ const page = await fetchPage(pageToken);
453
+ for (const item of page.data) {
454
+ yield item;
455
+ }
456
+ const next = page.next_page_token;
457
+ if (!next || seenTokens.has(next)) {
458
+ break;
459
+ }
460
+ seenTokens.add(next);
461
+ pageToken = next;
462
+ }
463
+ }
464
+ function buildQueryParams(params) {
465
+ const searchParams = new URLSearchParams();
466
+ if (!params) {
467
+ return searchParams;
468
+ }
469
+ for (const [key, value] of Object.entries(params)) {
470
+ if (value === void 0) {
471
+ continue;
472
+ }
473
+ if (key === "labels" && typeof value === "object" && !Array.isArray(value)) {
474
+ for (const [labelKey, labelValue] of Object.entries(value)) {
475
+ searchParams.set(`label.${labelKey}`, labelValue);
476
+ }
477
+ } else if (Array.isArray(value)) {
478
+ for (const item of value) {
479
+ searchParams.append(key, String(item));
480
+ }
481
+ } else if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
482
+ searchParams.set(key, String(value));
483
+ }
484
+ }
485
+ return searchParams;
486
+ }
487
+
488
+ // src/resources/exposures.ts
489
+ var ExposuresResource = class {
490
+ constructor(http) {
491
+ this.http = http;
492
+ }
493
+ http;
494
+ /**
495
+ * Creates a public HTTPS exposure for a workspace port (`201 Created`).
496
+ * `POST /v1/workspaces/{id}/exposures`
497
+ */
498
+ create(workspaceId, body, opts) {
499
+ return this.http.request({
500
+ method: "POST",
501
+ path: `/workspaces/${encodeURIComponent(workspaceId)}/exposures`,
502
+ body,
503
+ opts
504
+ });
505
+ }
506
+ /**
507
+ * Lists exposures for a workspace.
508
+ * `GET /v1/workspaces/{id}/exposures`
509
+ */
510
+ list(workspaceId, params, opts) {
511
+ return this.http.request({
512
+ method: "GET",
513
+ path: `/workspaces/${encodeURIComponent(workspaceId)}/exposures`,
514
+ query: buildQueryParams({
515
+ include_revoked: params?.include_revoked,
516
+ limit: params?.limit,
517
+ page_token: params?.page_token
518
+ }),
519
+ opts
520
+ });
521
+ }
522
+ /**
523
+ * Auto-paginates across all exposures for a workspace.
524
+ */
525
+ iterate(workspaceId, params, opts) {
526
+ return paginate(
527
+ (pageToken) => this.list(
528
+ workspaceId,
529
+ {
530
+ ...params,
531
+ page_token: pageToken
532
+ },
533
+ opts
534
+ ),
535
+ params?.page_token
536
+ );
537
+ }
538
+ /**
539
+ * Retrieves a specific exposure by ID.
540
+ * `GET /v1/workspaces/{id}/exposures/{exposure_id}`
541
+ */
542
+ get(workspaceId, exposureId, opts) {
543
+ return this.http.request({
544
+ method: "GET",
545
+ path: `/workspaces/${encodeURIComponent(workspaceId)}/exposures/${encodeURIComponent(exposureId)}`,
546
+ opts
547
+ });
548
+ }
549
+ /**
550
+ * Revokes an active exposure.
551
+ * `DELETE /v1/workspaces/{id}/exposures/{exposure_id}`
552
+ */
553
+ revoke(workspaceId, exposureId, opts) {
554
+ return this.http.request({
555
+ method: "DELETE",
556
+ path: `/workspaces/${encodeURIComponent(workspaceId)}/exposures/${encodeURIComponent(exposureId)}`,
557
+ opts
558
+ });
559
+ }
560
+ };
561
+
562
+ // src/resources/templates.ts
563
+ var TemplatesResource = class {
564
+ constructor(http) {
565
+ this.http = http;
566
+ }
567
+ http;
568
+ /**
569
+ * Lists templates across zones.
570
+ * `GET /v1/templates`
571
+ */
572
+ list(params, opts) {
573
+ return this.http.request({
574
+ method: "GET",
575
+ path: "/templates",
576
+ query: buildQueryParams({
577
+ owner: params?.owner,
578
+ zone: params?.zone,
579
+ limit: params?.limit,
580
+ page_token: params?.page_token
581
+ }),
582
+ opts
583
+ });
584
+ }
585
+ /**
586
+ * Auto-paginates across all templates matching `params`.
587
+ */
588
+ iterate(params, opts) {
589
+ return paginate(
590
+ (pageToken) => this.list(
591
+ {
592
+ ...params,
593
+ page_token: pageToken
594
+ },
595
+ opts
596
+ ),
597
+ params?.page_token
598
+ );
599
+ }
600
+ /**
601
+ * Retrieves a template by ID.
602
+ * `GET /v1/templates/{id}`
603
+ */
604
+ get(id, opts) {
605
+ return this.http.request({
606
+ method: "GET",
607
+ path: `/templates/${encodeURIComponent(id)}`,
608
+ opts
609
+ });
610
+ }
611
+ /**
612
+ * Lists revisions for a template.
613
+ * `GET /v1/templates/{id}/revisions`
614
+ */
615
+ listRevisions(id, params, opts) {
616
+ return this.http.request({
617
+ method: "GET",
618
+ path: `/templates/${encodeURIComponent(id)}/revisions`,
619
+ query: buildQueryParams({
620
+ limit: params?.limit,
621
+ page_token: params?.page_token
622
+ }),
623
+ opts
624
+ });
625
+ }
626
+ /**
627
+ * Retrieves a specific template revision.
628
+ * `GET /v1/templates/{id}/revisions/{revision_id}`
629
+ */
630
+ getRevision(id, revisionId, opts) {
631
+ return this.http.request({
632
+ method: "GET",
633
+ path: `/templates/${encodeURIComponent(id)}/revisions/${encodeURIComponent(revisionId)}`,
634
+ opts
635
+ });
636
+ }
637
+ };
638
+
639
+ // src/wait.ts
640
+ var DEFAULT_WAIT_TIMEOUT_SECONDS = 30;
641
+ var MAX_CHUNK_TIMEOUT_SECONDS = 60;
642
+ var HTTP_TIMEOUT_BUFFER_SECONDS = 15;
643
+ async function executeWaitLoop(http, params) {
644
+ const statuses = Array.isArray(params.status) ? params.status : [params.status];
645
+ if (statuses.length === 0) {
646
+ throw new KibotosError("wait() requires at least one target status");
647
+ }
648
+ const totalTimeoutSeconds = params.timeoutSeconds ?? DEFAULT_WAIT_TIMEOUT_SECONDS;
649
+ if (!Number.isFinite(totalTimeoutSeconds) || totalTimeoutSeconds <= 0) {
650
+ throw new KibotosError("wait() timeoutSeconds must be a positive number");
651
+ }
652
+ const deadlineMs = Date.now() + totalTimeoutSeconds * 1e3;
653
+ let remainingBudgetSeconds = totalTimeoutSeconds;
654
+ while (true) {
655
+ if (params.opts?.signal?.aborted) {
656
+ throw params.opts.signal.reason ?? new Error("The operation was aborted.");
657
+ }
658
+ const chunkSeconds = Math.min(
659
+ MAX_CHUNK_TIMEOUT_SECONDS,
660
+ Math.max(1, Math.ceil(remainingBudgetSeconds))
661
+ );
662
+ const query = new URLSearchParams();
663
+ for (const status of statuses) {
664
+ query.append("status", status);
665
+ }
666
+ query.set("timeout", String(chunkSeconds));
667
+ const effectiveOpts = {
668
+ ...params.opts,
669
+ timeoutMs: params.opts?.timeoutMs ?? Math.max(http.timeoutMs, (chunkSeconds + HTTP_TIMEOUT_BUFFER_SECONDS) * 1e3)
670
+ };
671
+ try {
672
+ return await http.request({
673
+ method: "GET",
674
+ path: params.path,
675
+ query,
676
+ opts: effectiveOpts,
677
+ disableWaitTimeoutRetry: true
678
+ });
679
+ } catch (err) {
680
+ if (!(err instanceof WaitTimeoutError)) {
681
+ throw err;
682
+ }
683
+ const wallRemainingSeconds = (deadlineMs - Date.now()) / 1e3;
684
+ remainingBudgetSeconds = Math.min(remainingBudgetSeconds - chunkSeconds, wallRemainingSeconds);
685
+ if (remainingBudgetSeconds <= 0) {
686
+ throw err;
687
+ }
688
+ }
689
+ }
690
+ }
691
+
692
+ // src/resources/volumes.ts
693
+ var VolumesResource = class {
694
+ constructor(http) {
695
+ this.http = http;
696
+ }
697
+ http;
698
+ /**
699
+ * Creates a new persistent volume asynchronously (`202 Accepted`).
700
+ * `POST /v1/volumes`
701
+ */
702
+ create(body, opts) {
703
+ return this.http.request({
704
+ method: "POST",
705
+ path: "/volumes",
706
+ body,
707
+ opts
708
+ });
709
+ }
710
+ /**
711
+ * Lists volumes across zones.
712
+ * `GET /v1/volumes`
713
+ */
714
+ list(params, opts) {
715
+ return this.http.request({
716
+ method: "GET",
717
+ path: "/volumes",
718
+ query: buildQueryParams({
719
+ zone: params?.zone,
720
+ attached: params?.attached,
721
+ labels: params?.labels,
722
+ limit: params?.limit,
723
+ page_token: params?.page_token
724
+ }),
725
+ opts
726
+ });
727
+ }
728
+ /**
729
+ * Auto-paginates across all volumes matching `params`.
730
+ */
731
+ iterate(params, opts) {
732
+ return paginate(
733
+ (pageToken) => this.list(
734
+ {
735
+ ...params,
736
+ page_token: pageToken
737
+ },
738
+ opts
739
+ ),
740
+ params?.page_token
741
+ );
742
+ }
743
+ /**
744
+ * Retrieves a volume by ID.
745
+ * `GET /v1/volumes/{id}`
746
+ */
747
+ get(id, opts) {
748
+ return this.http.request({
749
+ method: "GET",
750
+ path: `/volumes/${encodeURIComponent(id)}`,
751
+ opts
752
+ });
753
+ }
754
+ /**
755
+ * Updates volume metadata (`name` and/or `labels`).
756
+ * `PATCH /v1/volumes/{id}`
757
+ */
758
+ update(id, body, opts) {
759
+ return this.http.request({
760
+ method: "PATCH",
761
+ path: `/volumes/${encodeURIComponent(id)}`,
762
+ body,
763
+ opts
764
+ });
765
+ }
766
+ /**
767
+ * Resizes a volume asynchronously (`202 Accepted`).
768
+ * `POST /v1/volumes/{id}/resize`
769
+ */
770
+ resize(id, body, opts) {
771
+ return this.http.request({
772
+ method: "POST",
773
+ path: `/volumes/${encodeURIComponent(id)}/resize`,
774
+ body,
775
+ opts
776
+ });
777
+ }
778
+ /**
779
+ * Deletes a volume asynchronously (`202 Accepted`).
780
+ * `DELETE /v1/volumes/{id}`
781
+ */
782
+ delete(id, opts) {
783
+ return this.http.request({
784
+ method: "DELETE",
785
+ path: `/volumes/${encodeURIComponent(id)}`,
786
+ opts
787
+ });
788
+ }
789
+ /**
790
+ * Waits until the volume reaches one of the target statuses.
791
+ * Automatically chunks calls into `<= 60s` windows when `timeoutSeconds > 60`.
792
+ * `GET /v1/volumes/{id}/wait`
793
+ */
794
+ wait(id, params, opts) {
795
+ return executeWaitLoop(this.http, {
796
+ path: `/volumes/${encodeURIComponent(id)}/wait`,
797
+ status: params.status,
798
+ timeoutSeconds: params.timeoutSeconds,
799
+ opts
800
+ });
801
+ }
802
+ };
803
+
804
+ // src/sse.ts
805
+ var EXEC_EVENTS = /* @__PURE__ */ new Set([
806
+ "started",
807
+ "stdout",
808
+ "stderr",
809
+ "heartbeat",
810
+ "exited",
811
+ "error"
812
+ ]);
813
+ async function* parseExecEvents(response) {
814
+ if (!response.body) throw new Error("Kibotos exec stream has no response body");
815
+ const reader = response.body.getReader();
816
+ const decoder = new TextDecoder();
817
+ let pending = "";
818
+ let event = "";
819
+ let data = [];
820
+ let skipLF = false;
821
+ try {
822
+ while (true) {
823
+ const { value, done } = await reader.read();
824
+ const chunk = decoder.decode(value, { stream: !done });
825
+ if (chunk.length > 0) {
826
+ pending += skipLF && chunk.startsWith("\n") ? chunk.slice(1) : chunk;
827
+ skipLF = false;
828
+ }
829
+ let offset = 0;
830
+ const lineEnd = /\r\n|[\r\n]/g;
831
+ for (let match = lineEnd.exec(pending); match; match = lineEnd.exec(pending)) {
832
+ const line = pending.slice(offset, match.index);
833
+ offset = lineEnd.lastIndex;
834
+ skipLF = match[0] === "\r" && offset === pending.length;
835
+ if (line === "") {
836
+ const name = event;
837
+ const payload = data.join("\n");
838
+ const hasData = data.length > 0;
839
+ event = "";
840
+ data = [];
841
+ if (hasData && EXEC_EVENTS.has(name)) {
842
+ let decoded = payload;
843
+ try {
844
+ decoded = JSON.parse(payload);
845
+ } catch {
846
+ }
847
+ yield { event: name, data: decoded };
848
+ }
849
+ continue;
850
+ }
851
+ const colon = line.indexOf(":");
852
+ const field = colon === -1 ? line : line.slice(0, colon);
853
+ let fieldValue = colon === -1 ? "" : line.slice(colon + 1);
854
+ if (fieldValue.startsWith(" ")) fieldValue = fieldValue.slice(1);
855
+ if (field === "event") event = fieldValue;
856
+ if (field === "data") data.push(fieldValue);
857
+ }
858
+ pending = pending.slice(offset);
859
+ if (done) break;
860
+ }
861
+ } finally {
862
+ try {
863
+ await reader.cancel();
864
+ } catch {
865
+ } finally {
866
+ reader.releaseLock();
867
+ }
868
+ }
869
+ }
870
+
871
+ // src/websocket.ts
872
+ var FRAME_VERSION = 1;
873
+ var HEADER_BYTES = 6;
874
+ var WorkspaceChannel = {
875
+ stdin: 0,
876
+ stdout: 1,
877
+ stderr: 2,
878
+ pty: 3,
879
+ tunnel: 4
880
+ };
881
+ function encodeBinaryFrame(streamId, channel, payload) {
882
+ validateStreamId(streamId);
883
+ validateChannel(channel);
884
+ const frame = new Uint8Array(HEADER_BYTES + payload.byteLength);
885
+ const header = new DataView(frame.buffer);
886
+ header.setUint8(0, FRAME_VERSION);
887
+ header.setUint32(1, streamId, false);
888
+ header.setUint8(5, channel);
889
+ frame.set(payload, HEADER_BYTES);
890
+ return frame;
891
+ }
892
+ function decodeBinaryFrame(input) {
893
+ const bytes = input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
894
+ if (bytes.byteLength < HEADER_BYTES) throw new RangeError("Workspace frame is shorter than 6 bytes");
895
+ const header = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
896
+ if (header.getUint8(0) !== FRAME_VERSION) throw new RangeError("Unsupported workspace frame version");
897
+ const streamId = header.getUint32(1, false);
898
+ validateStreamId(streamId);
899
+ const channel = header.getUint8(5);
900
+ validateChannel(channel);
901
+ return {
902
+ stream_id: streamId,
903
+ channel,
904
+ payload: bytes.subarray(HEADER_BYTES)
905
+ };
906
+ }
907
+ function validateStreamId(streamId) {
908
+ if (!Number.isInteger(streamId) || streamId < 1 || streamId > 4294967295) {
909
+ throw new RangeError("stream_id must be a nonzero unsigned 32-bit integer");
910
+ }
911
+ }
912
+ function validateChannel(channel) {
913
+ if (!Number.isInteger(channel) || channel < 0 || channel > 4) {
914
+ throw new RangeError("Invalid workspace frame channel");
915
+ }
916
+ }
917
+ function decodeWorkspaceFrame(data) {
918
+ if (typeof data !== "string") return { type: "binary", frame: decodeBinaryFrame(data) };
919
+ const frame = JSON.parse(data);
920
+ if (!frame || typeof frame !== "object" || !("type" in frame) || typeof frame.type !== "string") {
921
+ throw new TypeError("Invalid workspace control frame");
922
+ }
923
+ return { type: "control", frame };
924
+ }
925
+ function webSocketUrl(url) {
926
+ const target = new URL(url);
927
+ if (target.protocol === "https:") target.protocol = "wss:";
928
+ if (target.protocol === "http:") target.protocol = "ws:";
929
+ if (target.protocol !== "ws:" && target.protocol !== "wss:") {
930
+ throw new TypeError("A WebSocket URL requires HTTP or HTTPS");
931
+ }
932
+ return target.toString();
933
+ }
934
+ function openWebSocket(url, headers, options) {
935
+ const handshake = { protocols: options?.protocols, headers: Object.fromEntries(headers) };
936
+ if (options?.factory) return options.factory(url, handshake);
937
+ const NativeWebSocket = globalThis.WebSocket;
938
+ if (typeof NativeWebSocket !== "function") {
939
+ throw new APIConnectionError("Global WebSocket is unavailable. Supply a WebSocket factory.");
940
+ }
941
+ if (Object.keys(handshake.headers).length === 0) {
942
+ return new NativeWebSocket(url, options?.protocols);
943
+ }
944
+ if (globalThis.process?.versions?.node) {
945
+ const NodeWebSocket = NativeWebSocket;
946
+ return new NodeWebSocket(url, handshake);
947
+ }
948
+ throw new APIConnectionError("This runtime requires a WebSocket factory to set handshake headers.");
949
+ }
950
+ var WorkspaceSocket = class {
951
+ constructor(socket) {
952
+ this.socket = socket;
953
+ socket.binaryType = "arraybuffer";
954
+ }
955
+ socket;
956
+ /** Subscribe to decoded frames. Returns an unsubscribe function. */
957
+ onFrame(listener) {
958
+ const onMessage = (event) => {
959
+ listener(decodeWorkspaceFrame(event.data));
960
+ };
961
+ this.socket.addEventListener("message", onMessage);
962
+ return () => this.socket.removeEventListener("message", onMessage);
963
+ }
964
+ sendControl(frame) {
965
+ this.socket.send(JSON.stringify(frame));
966
+ }
967
+ open(streamId, kind, params = {}) {
968
+ validateStreamId(streamId);
969
+ this.sendControl({ type: "open", stream_id: streamId, kind, params });
970
+ }
971
+ sendBinary(streamId, channel, payload) {
972
+ this.socket.send(encodeBinaryFrame(streamId, channel, payload));
973
+ }
974
+ close(code, reason) {
975
+ this.socket.close(code, reason);
976
+ }
977
+ };
978
+
979
+ // src/resources/workspaces.ts
980
+ function workspacePath(id) {
981
+ return `/workspaces/${encodeURIComponent(id)}`;
982
+ }
983
+ var WorkspacesResource = class {
984
+ constructor(http) {
985
+ this.http = http;
986
+ }
987
+ http;
988
+ /**
989
+ * Creates a new workspace asynchronously (`202 Accepted`).
990
+ * `POST /v1/workspaces`
991
+ */
992
+ create(body, opts) {
993
+ const { noTimeout, ...rest } = body;
994
+ if (noTimeout && rest.timeout !== void 0) {
995
+ return Promise.reject(new TypeError("Cannot combine noTimeout with timeout"));
996
+ }
997
+ const payload = noTimeout ? { ...rest, timeout: { seconds: 0 } } : rest;
998
+ return this.http.request({
999
+ method: "POST",
1000
+ path: "/workspaces",
1001
+ body: payload,
1002
+ opts
1003
+ });
1004
+ }
1005
+ /**
1006
+ * Lists workspaces across zones.
1007
+ * `GET /v1/workspaces`
1008
+ */
1009
+ list(params, opts) {
1010
+ return this.http.request({
1011
+ method: "GET",
1012
+ path: "/workspaces",
1013
+ query: buildQueryParams({
1014
+ status: params?.status,
1015
+ zone: params?.zone,
1016
+ labels: params?.labels,
1017
+ limit: params?.limit,
1018
+ page_token: params?.page_token
1019
+ }),
1020
+ opts
1021
+ });
1022
+ }
1023
+ /**
1024
+ * Auto-paginates across all workspaces matching `params`.
1025
+ */
1026
+ iterate(params, opts) {
1027
+ return paginate(
1028
+ (pageToken) => this.list(
1029
+ {
1030
+ ...params,
1031
+ page_token: pageToken
1032
+ },
1033
+ opts
1034
+ ),
1035
+ params?.page_token
1036
+ );
1037
+ }
1038
+ /**
1039
+ * Retrieves a workspace by ID.
1040
+ * `GET /v1/workspaces/{id}`
1041
+ */
1042
+ get(id, opts) {
1043
+ return this.http.request({
1044
+ method: "GET",
1045
+ path: `/workspaces/${encodeURIComponent(id)}`,
1046
+ opts
1047
+ });
1048
+ }
1049
+ /**
1050
+ * Updates workspace metadata and resizes eligible stopped or failed workspaces.
1051
+ * `PATCH /v1/workspaces/{id}`
1052
+ */
1053
+ update(id, body, opts) {
1054
+ return this.http.request({
1055
+ method: "PATCH",
1056
+ path: `/workspaces/${encodeURIComponent(id)}`,
1057
+ body,
1058
+ opts
1059
+ });
1060
+ }
1061
+ /**
1062
+ * Deletes a workspace asynchronously (`202 Accepted`).
1063
+ * `DELETE /v1/workspaces/{id}`
1064
+ */
1065
+ delete(id, opts) {
1066
+ return this.http.request({
1067
+ method: "DELETE",
1068
+ path: `/workspaces/${encodeURIComponent(id)}`,
1069
+ opts
1070
+ });
1071
+ }
1072
+ /**
1073
+ * Starts a stopped workspace (`202 Accepted`).
1074
+ * `POST /v1/workspaces/{id}/start`
1075
+ */
1076
+ start(id, body, opts) {
1077
+ let payload;
1078
+ if (body !== void 0) {
1079
+ const { noTimeout, ...rest } = body;
1080
+ if (noTimeout && rest.timeout !== void 0) {
1081
+ return Promise.reject(new TypeError("Cannot combine noTimeout with timeout"));
1082
+ }
1083
+ payload = noTimeout ? { ...rest, timeout: { seconds: 0 } } : rest;
1084
+ }
1085
+ return this.http.request({
1086
+ method: "POST",
1087
+ path: `/workspaces/${encodeURIComponent(id)}/start`,
1088
+ body: payload,
1089
+ opts
1090
+ });
1091
+ }
1092
+ /**
1093
+ * Stops an available workspace (`202 Accepted`).
1094
+ * `POST /v1/workspaces/{id}/stop`
1095
+ */
1096
+ stop(id, body, opts) {
1097
+ return this.http.request({
1098
+ method: "POST",
1099
+ path: `/workspaces/${encodeURIComponent(id)}/stop`,
1100
+ body,
1101
+ opts
1102
+ });
1103
+ }
1104
+ /**
1105
+ * Updates the auto-timeout policy for a workspace.
1106
+ * `POST /v1/workspaces/{id}/timeout`
1107
+ */
1108
+ setTimeout(id, body, opts) {
1109
+ return this.http.request({
1110
+ method: "POST",
1111
+ path: `/workspaces/${encodeURIComponent(id)}/timeout`,
1112
+ body,
1113
+ opts
1114
+ });
1115
+ }
1116
+ /**
1117
+ * Removes the auto-timeout policy so the workspace does not expire automatically.
1118
+ * `POST /v1/workspaces/{id}/timeout` with `{ seconds: 0 }`.
1119
+ */
1120
+ clearTimeout(id, opts) {
1121
+ return this.setTimeout(id, { seconds: 0 }, opts);
1122
+ }
1123
+ /**
1124
+ * Replaces the outbound network policy for a workspace.
1125
+ * `PUT /v1/workspaces/{id}/network`
1126
+ */
1127
+ setNetwork(id, body, opts) {
1128
+ return this.http.request({
1129
+ method: "PUT",
1130
+ path: `/workspaces/${encodeURIComponent(id)}/network`,
1131
+ body,
1132
+ opts
1133
+ });
1134
+ }
1135
+ setVolumes(id, body, opts) {
1136
+ return this.http.request({ method: "PUT", path: `${workspacePath(id)}/volumes`, body, opts });
1137
+ }
1138
+ setPacks(id, body, opts) {
1139
+ return this.http.request({ method: "PUT", path: `${workspacePath(id)}/packs`, body, opts });
1140
+ }
1141
+ getMetrics(id, params, opts) {
1142
+ return this.http.request({
1143
+ method: "GET",
1144
+ path: `${workspacePath(id)}/metrics`,
1145
+ query: buildQueryParams({
1146
+ start: params?.start instanceof Date ? params.start.toISOString() : params?.start,
1147
+ end: params?.end instanceof Date ? params.end.toISOString() : params?.end
1148
+ }),
1149
+ opts
1150
+ });
1151
+ }
1152
+ exec(id, body, opts) {
1153
+ return this.http.request({
1154
+ method: "POST",
1155
+ path: `${workspacePath(id)}/exec`,
1156
+ body,
1157
+ opts: { ...opts, timeoutMs: opts?.timeoutMs ?? ((body.timeout_seconds ?? 30) + 15) * 1e3 },
1158
+ accept: "application/json",
1159
+ nonReplayable: true,
1160
+ disableIdempotency: true
1161
+ });
1162
+ }
1163
+ async *execStream(id, body, opts) {
1164
+ const response = await this.http.requestResponse({
1165
+ method: "POST",
1166
+ path: `${workspacePath(id)}/exec`,
1167
+ body,
1168
+ opts: { ...opts, timeoutMs: opts?.timeoutMs ?? 0 },
1169
+ accept: "text/event-stream",
1170
+ nonReplayable: true,
1171
+ disableIdempotency: true
1172
+ });
1173
+ yield* parseExecEvents(response);
1174
+ }
1175
+ listFiles(id, path, opts) {
1176
+ return this.http.request({
1177
+ method: "GET",
1178
+ path: `${workspacePath(id)}/files`,
1179
+ query: buildQueryParams({ path, depth: opts?.depth, user: opts?.user }),
1180
+ opts
1181
+ });
1182
+ }
1183
+ statFile(id, path, opts) {
1184
+ return this.http.request({
1185
+ method: "GET",
1186
+ path: `${workspacePath(id)}/files/stat`,
1187
+ query: buildQueryParams({ path, user: opts?.user }),
1188
+ opts
1189
+ });
1190
+ }
1191
+ async readFile(id, path, opts) {
1192
+ const headers = new Headers(opts?.headers);
1193
+ if (opts?.range !== void 0) headers.set("Range", opts.range);
1194
+ if (opts?.ifNoneMatch !== void 0) headers.set("If-None-Match", opts.ifNoneMatch);
1195
+ const response = await this.http.requestResponse({
1196
+ method: "GET",
1197
+ path: `${workspacePath(id)}/files/content`,
1198
+ query: buildQueryParams({ path, user: opts?.user }),
1199
+ opts: { ...opts, headers: Object.fromEntries(headers), timeoutMs: opts?.timeoutMs ?? 0 },
1200
+ accept: "application/octet-stream",
1201
+ successStatuses: [304]
1202
+ });
1203
+ if (opts?.as === "bytes") return new Uint8Array(await response.arrayBuffer());
1204
+ if (opts?.as === "stream") return response.body;
1205
+ return response;
1206
+ }
1207
+ writeFile(id, path, content, opts) {
1208
+ const body = content instanceof Uint8Array ? content.buffer instanceof ArrayBuffer ? new Uint8Array(content.buffer, content.byteOffset, content.byteLength) : new Uint8Array(content) : content;
1209
+ return this.http.request({
1210
+ method: "PUT",
1211
+ path: `${workspacePath(id)}/files/content`,
1212
+ query: buildQueryParams({ path, mode: opts?.mode, create_only: opts?.createOnly, user: opts?.user }),
1213
+ opts: { ...opts, timeoutMs: opts?.timeoutMs ?? 0 },
1214
+ rawBody: body,
1215
+ duplex: body instanceof ReadableStream ? "half" : void 0,
1216
+ nonReplayable: true
1217
+ });
1218
+ }
1219
+ makeDir(id, body, opts) {
1220
+ return this.http.request({
1221
+ method: "POST",
1222
+ path: `${workspacePath(id)}/files/mkdir`,
1223
+ body,
1224
+ opts,
1225
+ nonReplayable: true,
1226
+ disableIdempotency: true
1227
+ });
1228
+ }
1229
+ moveFile(id, body, opts) {
1230
+ return this.http.request({
1231
+ method: "POST",
1232
+ path: `${workspacePath(id)}/files/move`,
1233
+ body,
1234
+ opts,
1235
+ nonReplayable: true,
1236
+ disableIdempotency: true
1237
+ });
1238
+ }
1239
+ deleteFile(id, path, opts) {
1240
+ return this.http.request({
1241
+ method: "DELETE",
1242
+ path: `${workspacePath(id)}/files`,
1243
+ query: buildQueryParams({ path, user: opts?.user }),
1244
+ opts,
1245
+ nonReplayable: true,
1246
+ disableIdempotency: true
1247
+ });
1248
+ }
1249
+ wsUrl(id) {
1250
+ return webSocketUrl(this.http.buildUrl(`${workspacePath(id)}/ws`));
1251
+ }
1252
+ tunnelWSUrl(id, target) {
1253
+ const url = this.http.buildUrl(`${workspacePath(id)}/tunnels/ws`, buildQueryParams({ ...target }));
1254
+ return webSocketUrl(url);
1255
+ }
1256
+ desktopVNCUrl(id) {
1257
+ return webSocketUrl(this.http.buildUrl(`${workspacePath(id)}/desktop/vnc`));
1258
+ }
1259
+ proxyUrl(id, port, path = "", query) {
1260
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
1261
+ throw new RangeError("port must be between 1 and 65535");
1262
+ }
1263
+ const segments = path.replace(/^\//, "").split("/");
1264
+ if (segments.some((segment) => segment === "." || segment === "..")) {
1265
+ throw new TypeError("Proxy path must not contain dot segments");
1266
+ }
1267
+ const suffix = path ? `/${segments.map(encodeURIComponent).join("/")}` : "";
1268
+ return this.http.buildUrl(`${workspacePath(id)}/proxy/${port}${suffix}`, query);
1269
+ }
1270
+ proxyWSUrl(id, port, path, query) {
1271
+ return webSocketUrl(this.proxyUrl(id, port, path, query));
1272
+ }
1273
+ /** Headers for a WebSocket upgrade or an authenticated proxy request. */
1274
+ wsHeaders(overrides) {
1275
+ return this.http.buildHeaders(overrides);
1276
+ }
1277
+ connectWS(id, opts) {
1278
+ return new WorkspaceSocket(openWebSocket(this.wsUrl(id), this.wsHeaders(opts?.headers), opts));
1279
+ }
1280
+ connectTunnel(id, target, opts) {
1281
+ return openWebSocket(this.tunnelWSUrl(id, target), this.wsHeaders(opts?.headers), opts);
1282
+ }
1283
+ connectDesktop(id, opts) {
1284
+ return openWebSocket(this.desktopVNCUrl(id), this.wsHeaders(opts?.headers), opts);
1285
+ }
1286
+ connectProxy(id, port, opts) {
1287
+ const url = this.proxyWSUrl(id, port, opts?.path, opts?.query);
1288
+ return openWebSocket(url, this.wsHeaders(opts?.headers), opts);
1289
+ }
1290
+ /**
1291
+ * Attaches a volume to a workspace.
1292
+ * `PUT /v1/workspaces/{id}/volume`
1293
+ */
1294
+ attachVolume(id, body, opts) {
1295
+ return this.http.request({
1296
+ method: "PUT",
1297
+ path: `/workspaces/${encodeURIComponent(id)}/volume`,
1298
+ body,
1299
+ opts
1300
+ });
1301
+ }
1302
+ /**
1303
+ * Detaches the attached volume from a workspace.
1304
+ * `DELETE /v1/workspaces/{id}/volume`
1305
+ */
1306
+ detachVolume(id, opts) {
1307
+ return this.http.request({
1308
+ method: "DELETE",
1309
+ path: `/workspaces/${encodeURIComponent(id)}/volume`,
1310
+ opts
1311
+ });
1312
+ }
1313
+ /**
1314
+ * Waits until the workspace reaches one of the target statuses.
1315
+ * Automatically chunks calls into `<= 60s` windows when `timeoutSeconds > 60`.
1316
+ * `GET /v1/workspaces/{id}/wait`
1317
+ */
1318
+ wait(id, params, opts) {
1319
+ return executeWaitLoop(this.http, {
1320
+ path: `/workspaces/${encodeURIComponent(id)}/wait`,
1321
+ status: params.status,
1322
+ timeoutSeconds: params.timeoutSeconds,
1323
+ opts
1324
+ });
1325
+ }
1326
+ };
1327
+
1328
+ // src/resources/zones.ts
1329
+ var ZonesResource = class {
1330
+ constructor(http) {
1331
+ this.http = http;
1332
+ }
1333
+ http;
1334
+ /**
1335
+ * Lists zones available to the authenticated organization.
1336
+ * `GET /v1/zones`
1337
+ */
1338
+ list(params, opts) {
1339
+ return this.http.request({
1340
+ method: "GET",
1341
+ path: "/zones",
1342
+ query: buildQueryParams({
1343
+ limit: params?.limit,
1344
+ page_token: params?.page_token
1345
+ }),
1346
+ opts
1347
+ });
1348
+ }
1349
+ /**
1350
+ * Auto-paginates across all zones matching `params`.
1351
+ */
1352
+ iterate(params, opts) {
1353
+ return paginate(
1354
+ (pageToken) => this.list(
1355
+ {
1356
+ ...params,
1357
+ page_token: pageToken
1358
+ },
1359
+ opts
1360
+ ),
1361
+ params?.page_token
1362
+ );
1363
+ }
1364
+ };
1365
+
1366
+ // src/resources/egresses.ts
1367
+ var EgressesResource = class {
1368
+ constructor(http) {
1369
+ this.http = http;
1370
+ }
1371
+ http;
1372
+ create(body, opts) {
1373
+ return this.http.request({ method: "POST", path: "/egresses", body, opts });
1374
+ }
1375
+ list(params, opts) {
1376
+ return this.http.request({
1377
+ method: "GET",
1378
+ path: "/egresses",
1379
+ query: buildQueryParams({ ...params }),
1380
+ opts
1381
+ });
1382
+ }
1383
+ get(id, opts) {
1384
+ return this.http.request({ method: "GET", path: `/egresses/${encodeURIComponent(id)}`, opts });
1385
+ }
1386
+ replace(id, body, opts) {
1387
+ return this.http.request({ method: "PUT", path: `/egresses/${encodeURIComponent(id)}`, body, opts });
1388
+ }
1389
+ update(id, body, opts) {
1390
+ return this.http.request({ method: "PATCH", path: `/egresses/${encodeURIComponent(id)}`, body, opts });
1391
+ }
1392
+ delete(id, opts) {
1393
+ return this.http.request({ method: "DELETE", path: `/egresses/${encodeURIComponent(id)}`, opts });
1394
+ }
1395
+ };
1396
+
1397
+ // src/resources/packs.ts
1398
+ var PacksResource = class {
1399
+ constructor(http) {
1400
+ this.http = http;
1401
+ }
1402
+ http;
1403
+ list(params, opts) {
1404
+ return this.http.request({ method: "GET", path: "/packs", query: buildQueryParams({ ...params }), opts });
1405
+ }
1406
+ get(id, opts) {
1407
+ return this.http.request({ method: "GET", path: `/packs/${encodeURIComponent(id)}`, opts });
1408
+ }
1409
+ getRevision(id, revisionId, opts) {
1410
+ return this.http.request({
1411
+ method: "GET",
1412
+ path: `/packs/${encodeURIComponent(id)}/revisions/${encodeURIComponent(revisionId)}`,
1413
+ opts
1414
+ });
1415
+ }
1416
+ };
1417
+
1418
+ // src/resources/resolvers.ts
1419
+ var ResolversResource = class {
1420
+ constructor(http) {
1421
+ this.http = http;
1422
+ }
1423
+ http;
1424
+ create(body, opts) {
1425
+ return this.http.request({ method: "POST", path: "/resolvers", body, opts });
1426
+ }
1427
+ list(params, opts) {
1428
+ return this.http.request({
1429
+ method: "GET",
1430
+ path: "/resolvers",
1431
+ query: buildQueryParams({ ...params }),
1432
+ opts
1433
+ });
1434
+ }
1435
+ get(id, opts) {
1436
+ return this.http.request({ method: "GET", path: `/resolvers/${encodeURIComponent(id)}`, opts });
1437
+ }
1438
+ replace(id, body, opts) {
1439
+ return this.http.request({ method: "PUT", path: `/resolvers/${encodeURIComponent(id)}`, body, opts });
1440
+ }
1441
+ update(id, body, opts) {
1442
+ return this.http.request({ method: "PATCH", path: `/resolvers/${encodeURIComponent(id)}`, body, opts });
1443
+ }
1444
+ delete(id, opts) {
1445
+ return this.http.request({ method: "DELETE", path: `/resolvers/${encodeURIComponent(id)}`, opts });
1446
+ }
1447
+ };
1448
+
1449
+ // src/client.ts
1450
+ var Kibotos = class {
1451
+ zones;
1452
+ templates;
1453
+ workspaces;
1454
+ volumes;
1455
+ exposures;
1456
+ egresses;
1457
+ packs;
1458
+ resolvers;
1459
+ http;
1460
+ constructor(options = {}) {
1461
+ this.http = new HttpClient(options);
1462
+ this.zones = new ZonesResource(this.http);
1463
+ this.templates = new TemplatesResource(this.http);
1464
+ this.workspaces = new WorkspacesResource(this.http);
1465
+ this.volumes = new VolumesResource(this.http);
1466
+ this.egresses = new EgressesResource(this.http);
1467
+ this.packs = new PacksResource(this.http);
1468
+ this.resolvers = new ResolversResource(this.http);
1469
+ this.exposures = new ExposuresResource(this.http);
1470
+ }
1471
+ /** Normalized base URL (always ending in `/v1`). */
1472
+ get baseUrl() {
1473
+ return this.http.baseUrl;
1474
+ }
1475
+ };
1476
+
1477
+ export { APIConnectionError, AuthenticationError, ConflictError, DEFAULT_BASE_URL, DEFAULT_MAX_RETRIES, DEFAULT_TIMEOUT_MS, EgressesResource, ExposuresResource, Kibotos, KibotosAPIError, KibotosError, NotFoundError, PacksResource, PermissionDeniedError, RateLimitError, ResolversResource, SDK_VERSION, TemplatesResource, UnexpectedStatusError, VolumesResource, WaitTimeoutError, WorkspaceChannel, WorkspaceSocket, WorkspacesResource, ZonesResource, decodeBinaryFrame, decodeWorkspaceFrame, encodeBinaryFrame };
1478
+ //# sourceMappingURL=index.js.map
1479
+ //# sourceMappingURL=index.js.map