@ariestools/cli 0.1.19 → 0.1.22

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,6 +1,14 @@
1
- import { chmodSync, existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
1
+ import { createRequire } from "node:module";
2
+ import { chmodSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
2
3
  import path from "node:path";
3
- import { homedir } from "node:os";
4
+ import os, { homedir } from "node:os";
5
+ import { spawn } from "node:child_process";
6
+ import HTTP from "node:http";
7
+ import HTTPS from "node:https";
8
+ import PROCESS from "node:process";
9
+ import { fileURLToPath } from "node:url";
10
+ import { createInterface } from "node:readline/promises";
11
+ import tty from "node:tty";
4
12
  //#region ../datalake-core/dist/browser/browser.mjs
5
13
  var DatalakeApiError = class extends Error {
6
14
  code;
@@ -55,18 +63,485 @@ function datalakePlaneClearPath(id) {
55
63
  function datalakePlaneUsagePath(id) {
56
64
  return `${datalakePlaneResourcePath(id)}/usage`;
57
65
  }
58
- var DATALAKE_CONTROL_OPERATIONS = [
66
+ var DATALAKE_CONTROL_OPERATIONS$1 = [
59
67
  "datalake:create",
60
68
  "datalake:describe",
61
69
  "datalake:list"
62
70
  ];
63
- var DATALAKE_DATA_OPERATIONS = [
71
+ var DATALAKE_DATA_OPERATIONS$1 = [
64
72
  "payload:append",
65
73
  "payload:read",
66
74
  "usage:read"
67
75
  ];
68
- DATALAKE_CONTROL_OPERATIONS.join(" ");
69
- DATALAKE_DATA_OPERATIONS.join(" ");
76
+ DATALAKE_CONTROL_OPERATIONS$1.join(" ");
77
+ DATALAKE_DATA_OPERATIONS$1.join(" ");
78
+ //#endregion
79
+ //#region ../../node_modules/.pnpm/@ariestools+sdk@8.3.0_@opentelemetry+api@1.9.1_zod@4.6.1/node_modules/@ariestools/sdk/dist/neutral/fetch.mjs
80
+ var fetchErrorMarker = "$$xylabs-fetch-error";
81
+ var codeTypes = {
82
+ ENOTFOUND: "dns",
83
+ EAI_AGAIN: "dns",
84
+ ECONNREFUSED: "connection-refused",
85
+ ECONNRESET: "connection-reset",
86
+ EPIPE: "connection-reset",
87
+ ETIMEDOUT: "connection-timeout",
88
+ UND_ERR_CONNECT_TIMEOUT: "connection-timeout",
89
+ UND_ERR_HEADERS_TIMEOUT: "timeout",
90
+ UND_ERR_BODY_TIMEOUT: "timeout",
91
+ EHOSTUNREACH: "unreachable",
92
+ ENETUNREACH: "unreachable",
93
+ CERT_HAS_EXPIRED: "tls",
94
+ DEPTH_ZERO_SELF_SIGNED_CERT: "tls",
95
+ UNABLE_TO_VERIFY_LEAF_SIGNATURE: "tls",
96
+ SELF_SIGNED_CERT_IN_CHAIN: "tls",
97
+ ERR_TLS_CERT_ALTNAME_INVALID: "tls"
98
+ };
99
+ function findErrorCode(error) {
100
+ let current = error;
101
+ for (let depth = 0; depth < 8 && current instanceof Error; depth++) {
102
+ const code = current.code;
103
+ if (typeof code === "string") return code;
104
+ current = current.cause;
105
+ }
106
+ }
107
+ function typeFromCode(code) {
108
+ if (Object.hasOwn(codeTypes, code)) return codeTypes[code];
109
+ if (code.startsWith("CERT_") || code.startsWith("ERR_TLS_")) return "tls";
110
+ }
111
+ function classifyFetchError(error) {
112
+ if (error instanceof Error) {
113
+ if (error.name === "TimeoutError") return { type: "timeout" };
114
+ if (error.name === "AbortError") return { type: "aborted" };
115
+ }
116
+ const code = findErrorCode(error);
117
+ if (code !== void 0) {
118
+ const type = typeFromCode(code);
119
+ if (type !== void 0) return {
120
+ type,
121
+ code
122
+ };
123
+ return {
124
+ type: "unknown",
125
+ code
126
+ };
127
+ }
128
+ if (error instanceof TypeError && /fetch failed|failed to fetch|network/i.test(error.message)) return { type: "network" };
129
+ return { type: "unknown" };
130
+ }
131
+ var FetchError = class extends Error {
132
+ /** Cross-realm marker consumed by {@link isFetchError}. */
133
+ __fetchErrorMarker = fetchErrorMarker;
134
+ /** Raw unparseable body text for `parse` failures. */
135
+ body;
136
+ /** Node, undici, or TLS system error code when available. */
137
+ code;
138
+ /** HTTP method associated with the failed request. */
139
+ method;
140
+ /** Parsed response for rejected HTTP-status requests. */
141
+ response;
142
+ /** HTTP status when a response was received. */
143
+ status;
144
+ /** HTTP reason phrase when a response was received. */
145
+ statusText;
146
+ /** Classified reason for the fetch failure. */
147
+ type;
148
+ /** Request URL associated with the failure. */
149
+ url;
150
+ /** Creates a structured fetch error from a message and request context. */
151
+ constructor(message, context = {}) {
152
+ super(message, { cause: context.cause });
153
+ this.name = "FetchError";
154
+ this.type = context.type ?? "unknown";
155
+ this.code = context.code;
156
+ this.url = context.url;
157
+ this.method = context.method;
158
+ this.status = context.status;
159
+ this.statusText = context.statusText;
160
+ this.response = context.response;
161
+ this.body = context.body;
162
+ }
163
+ /** Returns a circular-reference-free representation for logs and telemetry. */
164
+ toJSON() {
165
+ return {
166
+ name: this.name,
167
+ message: this.message,
168
+ type: this.type,
169
+ code: this.code,
170
+ url: this.url,
171
+ method: this.method,
172
+ status: this.status,
173
+ statusText: this.statusText
174
+ };
175
+ }
176
+ };
177
+ function isFetchError(value) {
178
+ return value instanceof FetchError || typeof value === "object" && value !== null && value.__fetchErrorMarker === fetchErrorMarker;
179
+ }
180
+ function toFetchError(error, context = {}) {
181
+ if (isFetchError(error)) return error;
182
+ const { type, code } = classifyFetchError(error);
183
+ return new FetchError(error instanceof Error ? error.message : String(error), {
184
+ ...context,
185
+ type,
186
+ code,
187
+ cause: error
188
+ });
189
+ }
190
+ function fetchDefault(input, init) {
191
+ return globalThis.fetch(input, init);
192
+ }
193
+ async function gzipString(body) {
194
+ const stream = new Blob([body]).stream().pipeThrough(new CompressionStream("gzip"));
195
+ return new Response(stream).arrayBuffer();
196
+ }
197
+ async function fetchCompress(url, options = {}) {
198
+ const { compressMinLength = 1024, fetcher = fetchDefault, ...init } = options;
199
+ try {
200
+ if (init.body !== void 0 && init.body !== null) {
201
+ const bodyStr = typeof init.body === "string" ? init.body : JSON.stringify(init.body);
202
+ if (bodyStr.length > compressMinLength) {
203
+ const headers = new Headers(init.headers);
204
+ headers.set("Content-Encoding", "gzip");
205
+ return await fetcher(url, {
206
+ ...init,
207
+ body: await gzipString(bodyStr),
208
+ headers
209
+ });
210
+ }
211
+ }
212
+ return await fetcher(url, init);
213
+ } catch (error) {
214
+ throw toFetchError(error, {
215
+ url: url.toString(),
216
+ method: init.method
217
+ });
218
+ }
219
+ }
220
+ function validateMaxResponseBytes(maxResponseBytes) {
221
+ if (maxResponseBytes !== void 0 && (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes <= 0)) throw new RangeError("maxResponseBytes must be a positive safe integer");
222
+ }
223
+ function abortError(signal) {
224
+ const reason = signal.reason;
225
+ let isTimeout = false;
226
+ try {
227
+ isTimeout = typeof reason === "object" && reason !== null && "name" in reason && reason.name === "TimeoutError" || classifyFetchError(reason).type === "timeout";
228
+ } catch {}
229
+ return new FetchError("Response body read was aborted", {
230
+ type: isTimeout ? "timeout" : "aborted",
231
+ cause: reason
232
+ });
233
+ }
234
+ function readChunk(reader, signal) {
235
+ if (signal == null) return reader.read();
236
+ return new Promise((resolve, reject) => {
237
+ let settled = false;
238
+ const finish = (outcome) => {
239
+ if (settled) return;
240
+ settled = true;
241
+ signal.removeEventListener("abort", onAbort);
242
+ if ("error" in outcome) reject(toFetchError(outcome.error));
243
+ else resolve(outcome.value);
244
+ };
245
+ const onAbort = () => finish({ error: abortError(signal) });
246
+ signal.addEventListener("abort", onAbort, { once: true });
247
+ if (signal.aborted) {
248
+ onAbort();
249
+ return;
250
+ }
251
+ try {
252
+ reader.read().then((value) => signal.aborted ? onAbort() : finish({ value })).catch((error) => finish({ error }));
253
+ } catch (error) {
254
+ finish({ error });
255
+ }
256
+ });
257
+ }
258
+ function cancelReader(reader, reason) {
259
+ try {
260
+ reader.cancel(reason).catch(() => {});
261
+ } catch {}
262
+ }
263
+ async function readStreamText(reader, maxResponseBytes, signal, response) {
264
+ const decoder = new TextDecoder();
265
+ const parts = [];
266
+ let bytes = 0;
267
+ let completed = false;
268
+ let failure;
269
+ try {
270
+ while (true) {
271
+ const result = await readChunk(reader, signal);
272
+ if (signal?.aborted === true) throw abortError(signal);
273
+ if (result.done) {
274
+ parts.push(decoder.decode());
275
+ completed = true;
276
+ return parts.join("");
277
+ }
278
+ const chunk = result.value;
279
+ if (!ArrayBuffer.isView(chunk) || Object.prototype.toString.call(chunk) !== "[object Uint8Array]") throw new TypeError("Response body chunks must be Uint8Array values");
280
+ if (maxResponseBytes !== void 0) {
281
+ if (chunk.byteLength > maxResponseBytes - bytes) throw new FetchError("Response body exceeds maxResponseBytes", {
282
+ type: "response-too-large",
283
+ status: response.status,
284
+ statusText: response.statusText
285
+ });
286
+ bytes += chunk.byteLength;
287
+ }
288
+ const text = decoder.decode(chunk, { stream: true });
289
+ if (text !== "") parts.push(text);
290
+ }
291
+ } catch (error) {
292
+ failure = error;
293
+ throw error;
294
+ } finally {
295
+ if (!completed) cancelReader(reader, failure);
296
+ reader.releaseLock();
297
+ }
298
+ }
299
+ async function readResponseText(response, options = {}) {
300
+ const { maxResponseBytes, signal } = options;
301
+ validateMaxResponseBytes(maxResponseBytes);
302
+ if (maxResponseBytes === void 0 && signal == null) return await response.text();
303
+ if (response.bodyUsed) throw new TypeError("Response body has already been consumed");
304
+ const body = response.body;
305
+ if (body === null) {
306
+ if (signal?.aborted === true) throw abortError(signal);
307
+ return "";
308
+ }
309
+ return await readStreamText(body.getReader(), maxResponseBytes, signal, response);
310
+ }
311
+ function contextualizeReadError(error, context, options) {
312
+ const failure = toFetchError(error, context);
313
+ if (options.maxResponseBytes === void 0 && options.signal == null) return failure;
314
+ if ((failure.url !== void 0 || context.url === void 0) && (failure.method !== void 0 || context.method === void 0)) return failure;
315
+ return new FetchError(failure.message, {
316
+ body: failure.body,
317
+ cause: failure.cause,
318
+ code: failure.code,
319
+ method: failure.method ?? context.method,
320
+ response: failure.response,
321
+ status: failure.status,
322
+ statusText: failure.statusText,
323
+ type: failure.type,
324
+ url: failure.url ?? context.url
325
+ });
326
+ }
327
+ async function parseJsonResponse(response, context = {}, options = {}) {
328
+ let text;
329
+ try {
330
+ text = await readResponseText(response, options);
331
+ } catch (error) {
332
+ throw contextualizeReadError(error, context, options);
333
+ }
334
+ if (text.trim() === "") return null;
335
+ try {
336
+ return JSON.parse(text);
337
+ } catch (error) {
338
+ throw new FetchError("Failed to parse response body as JSON", {
339
+ type: "parse",
340
+ url: context.url,
341
+ method: context.method,
342
+ status: response.status,
343
+ statusText: response.statusText,
344
+ body: text,
345
+ cause: error
346
+ });
347
+ }
348
+ }
349
+ async function tryParseJson(response, options = {}, context = {}) {
350
+ let text;
351
+ try {
352
+ text = await readResponseText(response, options);
353
+ } catch (error) {
354
+ if (options.maxResponseBytes !== void 0 || options.signal != null) throw contextualizeReadError(error, context, options);
355
+ return null;
356
+ }
357
+ try {
358
+ return text.trim() === "" ? null : JSON.parse(text);
359
+ } catch {
360
+ return null;
361
+ }
362
+ }
363
+ function noop() {}
364
+ function requestSignal(signal, timeout) {
365
+ if (timeout === void 0 || timeout === 0) return {
366
+ signal,
367
+ close: noop
368
+ };
369
+ const timeoutSignal = AbortSignal.timeout(timeout);
370
+ if (signal == null) return {
371
+ signal: timeoutSignal,
372
+ close: noop
373
+ };
374
+ const controller = new AbortController();
375
+ const close = () => {
376
+ signal.removeEventListener("abort", onCallerAbort);
377
+ timeoutSignal.removeEventListener("abort", onTimeout);
378
+ };
379
+ const abort = (source) => {
380
+ if (!controller.signal.aborted) controller.abort(source.reason);
381
+ close();
382
+ };
383
+ const onCallerAbort = () => abort(signal);
384
+ const onTimeout = () => abort(timeoutSignal);
385
+ signal.addEventListener("abort", onCallerAbort, { once: true });
386
+ timeoutSignal.addEventListener("abort", onTimeout, { once: true });
387
+ if (signal.aborted) onCallerAbort();
388
+ else if (timeoutSignal.aborted) onTimeout();
389
+ return {
390
+ signal: controller.signal,
391
+ close
392
+ };
393
+ }
394
+ var FetchClientError = class extends FetchError {
395
+ /** Effective request configuration, including the resolved request URL. */
396
+ config;
397
+ /** Creates an HTTP-status error with its response and request configuration. */
398
+ constructor(message, response, config) {
399
+ super(message, {
400
+ type: "http-status",
401
+ url: config.url,
402
+ method: config.method,
403
+ status: response.status,
404
+ statusText: response.statusText,
405
+ response
406
+ });
407
+ this.name = "FetchClientError";
408
+ this.config = config;
409
+ }
410
+ };
411
+ function buildHeaders(custom, includeContentType = false) {
412
+ const headers = new Headers();
413
+ headers.set("Accept", "application/json, text/plain, *.*");
414
+ if (includeContentType) headers.set("Content-Type", "application/json");
415
+ if (custom) {
416
+ const merged = new Headers(custom);
417
+ for (const [key, value] of merged.entries()) headers.set(key, value);
418
+ }
419
+ return headers;
420
+ }
421
+ function buildURL(config) {
422
+ const base = config.baseURL ?? "";
423
+ const path = config.url ?? "";
424
+ const url = base === "" ? new URL(path) : new URL(path, base);
425
+ if (config.params) for (const [key, value] of Object.entries(config.params)) url.searchParams.set(key, value);
426
+ return url.href;
427
+ }
428
+ var FetchClient = class _FetchClient {
429
+ /** Instance defaults shallow-merged beneath every request configuration. */
430
+ defaults;
431
+ /** Creates a client with reusable request defaults. */
432
+ constructor(defaults = {}) {
433
+ this.defaults = defaults;
434
+ }
435
+ /** Creates a client with the supplied request defaults. */
436
+ static create(config) {
437
+ return new _FetchClient(config);
438
+ }
439
+ /** Sends a `DELETE` request and parses its response as JSON. */
440
+ delete(url, config) {
441
+ return this.request({
442
+ ...config,
443
+ url,
444
+ method: "DELETE"
445
+ });
446
+ }
447
+ /** Sends a `GET` request and parses its response as JSON. */
448
+ get(url, config) {
449
+ return this.request({
450
+ ...config,
451
+ url,
452
+ method: "GET"
453
+ });
454
+ }
455
+ /** Serializes `data`, sends a `PATCH` request, and parses the JSON response. */
456
+ patch(url, data, config) {
457
+ return this.request({
458
+ ...config,
459
+ url,
460
+ data,
461
+ method: "PATCH"
462
+ });
463
+ }
464
+ /** Serializes `data`, sends a `POST` request, and parses the JSON response. */
465
+ post(url, data, config) {
466
+ return this.request({
467
+ ...config,
468
+ url,
469
+ data,
470
+ method: "POST"
471
+ });
472
+ }
473
+ /** Serializes `data`, sends a `PUT` request, and parses the JSON response. */
474
+ put(url, data, config) {
475
+ return this.request({
476
+ ...config,
477
+ url,
478
+ data,
479
+ method: "PUT"
480
+ });
481
+ }
482
+ /**
483
+ * Resolves and executes a request using native fetch semantics.
484
+ * @returns Response metadata and parsed JSON, or `null` for an empty body.
485
+ * @throws {@link FetchClientError} when `validateStatus` rejects the status.
486
+ * @throws {@link FetchError} for transport or JSON parsing failures.
487
+ */
488
+ async request(config) {
489
+ const merged = {
490
+ ...this.defaults,
491
+ ...config
492
+ };
493
+ const url = buildURL(merged);
494
+ const { baseURL: _baseURL, data: requestData, headers, maxResponseBytes, method = "GET", params: _params, signal, timeout, url: _url, validateStatus: validateStatusOption, ...requestInit } = merged;
495
+ validateMaxResponseBytes(maxResponseBytes);
496
+ const scope = requestSignal(signal, timeout);
497
+ try {
498
+ const init = {
499
+ ...requestInit,
500
+ method,
501
+ headers: buildHeaders(headers, requestData !== void 0),
502
+ signal: scope.signal
503
+ };
504
+ if (requestData !== void 0) init.body = JSON.stringify(requestData);
505
+ const response = await fetchCompress(url, init);
506
+ const readOptions = {
507
+ maxResponseBytes,
508
+ signal: scope.signal
509
+ };
510
+ const result = {
511
+ data: response.ok ? await parseJsonResponse(response, {
512
+ url,
513
+ method
514
+ }, readOptions) : await tryParseJson(response, readOptions, {
515
+ url,
516
+ method
517
+ }),
518
+ headers: response.headers,
519
+ response,
520
+ status: response.status,
521
+ statusText: response.statusText
522
+ };
523
+ const validateStatus = validateStatusOption === void 0 ? (s) => s >= 200 && s < 300 : validateStatusOption;
524
+ if (validateStatus && !validateStatus(response.status)) throw new FetchClientError(`Request failed with status ${response.status} ${response.statusText}`, result, {
525
+ ...merged,
526
+ method,
527
+ url
528
+ });
529
+ return result;
530
+ } finally {
531
+ scope.close();
532
+ }
533
+ }
534
+ };
535
+ new class _FetchJsonClient extends FetchClient {
536
+ /** Creates a JSON client with reusable request and compression defaults. */
537
+ constructor(config) {
538
+ super(config);
539
+ }
540
+ /** Creates a JSON client with the supplied defaults. */
541
+ static create(config) {
542
+ return new _FetchJsonClient(config);
543
+ }
544
+ }();
70
545
  //#endregion
71
546
  //#region ../datalake-client/dist/node/index.mjs
72
547
  function getAriesHome() {
@@ -199,10 +674,11 @@ var LocalDatalakeClient = class {
199
674
  const store = readStore();
200
675
  const datalake = requireDatalake(store, request.datalakeId);
201
676
  const existing = datalake.acl.findIndex((entry2) => entry2.principal === request.principal);
677
+ const grantedAtDate = /* @__PURE__ */ new Date();
202
678
  const entry = {
203
679
  principal: request.principal,
204
680
  role: request.role,
205
- grantedAt: (/* @__PURE__ */ new Date()).toISOString(),
681
+ grantedAt: grantedAtDate.toISOString(),
206
682
  grantedBy: LOCAL_OWNER_ID
207
683
  };
208
684
  if (existing === -1) datalake.acl.push(entry);
@@ -217,15 +693,17 @@ var LocalDatalakeClient = class {
217
693
  async mintToken(request) {
218
694
  const datalake = requireDatalake(readStore(), request.datalakeId);
219
695
  const ttl = request.ttlSeconds ?? 3600;
696
+ const issued = Buffer.from(JSON.stringify({
697
+ dl: datalake.id,
698
+ role: request.role,
699
+ exp: Math.floor(Date.now() / 1e3) + ttl
700
+ })).toString("base64url");
701
+ const expiresAtDate = new Date(Date.now() + ttl * 1e3);
220
702
  return {
221
- token: `local.${Buffer.from(JSON.stringify({
222
- dl: datalake.id,
223
- role: request.role,
224
- exp: Math.floor(Date.now() / 1e3) + ttl
225
- })).toString("base64url")}`,
703
+ token: `local.${issued}`,
226
704
  datalakeId: datalake.id,
227
705
  role: request.role,
228
- expiresAt: new Date(Date.now() + ttl * 1e3).toISOString(),
706
+ expiresAt: expiresAtDate.toISOString(),
229
707
  url: datalake.url ?? `http://localhost:8080/datalakes/${datalake.name}`
230
708
  };
231
709
  }
@@ -378,6 +856,22 @@ function extractRequestBase(urlWithPossiblePath) {
378
856
  return urlWithPossiblePath.replace(/\/$/, "");
379
857
  }
380
858
  }
859
+ function parsePayloadResponse(response, text, method) {
860
+ const payload = text.length > 0 ? JSON.parse(text) : void 0;
861
+ if (!response.ok) {
862
+ const errorBody = isApiErrorBody2(payload) ? payload : {
863
+ code: "internal",
864
+ message: "Unexpected " + response.status + " response from " + method + " data plane"
865
+ };
866
+ throw new DatalakeApiError(response.status, errorBody);
867
+ }
868
+ return payload;
869
+ }
870
+ function isApiErrorBody2(value) {
871
+ if (typeof value !== "object" || value === null) return false;
872
+ const maybe = value;
873
+ return typeof maybe.code === "string" && typeof maybe.message === "string";
874
+ }
381
875
  var RestPayloadsClient = class {
382
876
  authToken;
383
877
  datalakeId;
@@ -458,24 +952,15 @@ var RestPayloadsClient = class {
458
952
  data: void 0,
459
953
  headers: response.headers
460
954
  };
461
- const text = await response.text();
462
- const payload = text.length > 0 ? JSON.parse(text) : void 0;
463
- if (!response.ok) {
464
- const errorBody = isApiErrorBody2(payload) ? payload : {
465
- code: "internal",
466
- message: `Unexpected ${response.status} response from ${method} data plane`
467
- };
468
- throw new DatalakeApiError(response.status, errorBody);
469
- }
470
955
  return {
471
- data: payload,
956
+ data: parsePayloadResponse(response, await response.text(), method),
472
957
  headers: response.headers
473
958
  };
474
959
  }
475
960
  };
476
961
  function readInsertSummary(headers) {
477
962
  const duplicatesRaw = headers.get(DATALAKE_HEADER_DUPLICATES);
478
- const duplicates = duplicatesRaw === null ? 0 : Number.parseInt(duplicatesRaw, 10);
963
+ const duplicates = duplicatesRaw === null ? 0 : Math.trunc(Number(duplicatesRaw));
479
964
  const rejectedRaw = headers.get(DATALAKE_HEADER_REJECTED);
480
965
  const rejected = rejectedRaw === null || rejectedRaw.length === 0 ? [] : rejectedRaw.split(",").map((value) => value.trim()).filter((value) => value.length > 0);
481
966
  return {
@@ -483,10 +968,1007 @@ function readInsertSummary(headers) {
483
968
  rejected
484
969
  };
485
970
  }
486
- function isApiErrorBody2(value) {
487
- if (typeof value !== "object" || value === null) return false;
488
- const maybe = value;
489
- return typeof maybe.code === "string" && typeof maybe.message === "string";
971
+ //#endregion
972
+ //#region ../../node_modules/.pnpm/@ariestools+cli-kit-daemon@1.2.3_@ariestools+actor-model@1.3.0_@ariestools+sdk@8.3.0_@o_8cda624dab9c79c693e4473e20d01110/node_modules/@ariestools/cli-kit-daemon/dist/node/index.mjs
973
+ function isProcessAlive(pid) {
974
+ try {
975
+ PROCESS.kill(pid, 0);
976
+ return true;
977
+ } catch (error) {
978
+ return error.code === "EPERM";
979
+ }
980
+ }
981
+ var require2 = createRequire(import.meta.url);
982
+ var HEALTH_POLL_MS = 100;
983
+ var STATUS_PING_TIMEOUT_MS = 1e3;
984
+ var DEFAULT_DOWN_GRACE_MS = 2e3;
985
+ var DOWN_POLL_MS = 50;
986
+ var DEFAULT_LOG_LINES = 50;
987
+ var STATUS_LABEL_WIDTH = 10;
988
+ var DAEMON_STATUS_EXIT_CODES = {
989
+ /** Running and answering health probes. */
990
+ healthy: 0,
991
+ /** No live process for the recorded pid, or no state at all. */
992
+ notRunning: 3,
993
+ /** Process is alive but not answering health probes. */
994
+ unresponsive: 2
995
+ };
996
+ var IDENTITY = (text) => text;
997
+ function resolveStyle(style) {
998
+ return {
999
+ dim: style?.dim ?? IDENTITY,
1000
+ error: style?.error ?? IDENTITY,
1001
+ info: style?.info ?? IDENTITY,
1002
+ success: style?.success ?? IDENTITY,
1003
+ warn: style?.warn ?? IDENTITY
1004
+ };
1005
+ }
1006
+ function delay(ms) {
1007
+ return new Promise((resolve) => setTimeout(resolve, ms));
1008
+ }
1009
+ function formatUptime(startedAt, now) {
1010
+ const started = new Date(startedAt).getTime();
1011
+ if (Number.isNaN(started)) return "";
1012
+ const seconds = Math.max(0, Math.floor((now - started) / 1e3));
1013
+ if (seconds < 60) return `${seconds}s`;
1014
+ const minutes = Math.floor(seconds / 60);
1015
+ if (minutes < 60) return `${minutes}m ${seconds % 60}s`;
1016
+ return `${Math.floor(minutes / 60)}h ${minutes % 60}m`;
1017
+ }
1018
+ function createDaemonKit$1(config) {
1019
+ const displayName = config.displayName;
1020
+ const capitalizedName = displayName.charAt(0).toUpperCase() + displayName.slice(1);
1021
+ const style = resolveStyle(config.style);
1022
+ const io = config.host.io;
1023
+ const paths = {
1024
+ dir: () => path.join(config.homeDir(), config.dirName),
1025
+ logPath: () => path.join(paths.dir(), "server.log"),
1026
+ pidPath: () => path.join(paths.dir(), "pid"),
1027
+ statePath: () => path.join(paths.dir(), "state.json")
1028
+ };
1029
+ function readState() {
1030
+ const filePath = paths.statePath();
1031
+ if (!existsSync(filePath)) return void 0;
1032
+ let parsed;
1033
+ try {
1034
+ parsed = JSON.parse(readFileSync(filePath, "utf8"));
1035
+ } catch {
1036
+ return;
1037
+ }
1038
+ if (config.normalizeState === void 0) return parsed;
1039
+ const normalized = config.normalizeState(parsed);
1040
+ if (normalized === void 0) return void 0;
1041
+ if (JSON.stringify(parsed) !== JSON.stringify(normalized)) writeState(normalized);
1042
+ return normalized;
1043
+ }
1044
+ function writeState(state) {
1045
+ const dir = paths.dir();
1046
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1047
+ const statePath = paths.statePath();
1048
+ const temporaryStatePath = `${statePath}.${PROCESS.pid}.tmp`;
1049
+ writeFileSync(temporaryStatePath, JSON.stringify(state, void 0, 2), "utf8");
1050
+ renameSync(temporaryStatePath, statePath);
1051
+ writeFileSync(paths.pidPath(), String(state.pid), "utf8");
1052
+ }
1053
+ function clearState() {
1054
+ for (const filePath of [paths.statePath(), paths.pidPath()]) if (existsSync(filePath)) unlinkSync(filePath);
1055
+ }
1056
+ function resolveServerBin() {
1057
+ const { bin } = config;
1058
+ if (bin.embeddedRelPath !== void 0 && bin.embeddedRelPath.length > 0 && bin.resolveFromUrl !== void 0 && bin.resolveFromUrl.length > 0) {
1059
+ const relativeSegments = bin.embeddedRelPath.split("/");
1060
+ const binDir = path.dirname(fileURLToPath(bin.resolveFromUrl));
1061
+ const embedded = path.join(binDir, ...relativeSegments);
1062
+ if (existsSync(embedded)) return embedded;
1063
+ const searchPaths = bin.searchPaths ?? [];
1064
+ for (const searchPath of searchPaths) {
1065
+ const candidate = path.resolve(binDir, searchPath, ...relativeSegments);
1066
+ if (existsSync(candidate)) return candidate;
1067
+ }
1068
+ }
1069
+ if (bin.packageName !== void 0 && bin.binRelPath !== void 0) try {
1070
+ const packageJsonPath = require2.resolve(`${bin.packageName}/package.json`);
1071
+ const binPath = path.join(path.dirname(packageJsonPath), ...bin.binRelPath.split("/"));
1072
+ if (existsSync(binPath)) return binPath;
1073
+ } catch {}
1074
+ throw new Error(`${capitalizedName} binary not found. ${bin.installHint} (expected an embedded daemon beside the calling bin or a resolvable package bin)`);
1075
+ }
1076
+ function probeUrl(baseUrl) {
1077
+ return `${baseUrl.replace(/\/$/, "")}${config.health?.path ?? ""}`;
1078
+ }
1079
+ async function probeOnce(baseUrl, timeoutMs, tlsCa) {
1080
+ return await new Promise((resolve) => {
1081
+ const url = new URL(probeUrl(baseUrl));
1082
+ const request = (url.protocol === "https:" ? HTTPS : HTTP).get(url, { ca: tlsCa }, (response) => {
1083
+ response.resume();
1084
+ const status2 = response.statusCode ?? 0;
1085
+ resolve(config.health?.anyResponse === true || status2 >= 200 && status2 < 300);
1086
+ });
1087
+ request.on("error", () => resolve(false));
1088
+ if (timeoutMs !== void 0) request.setTimeout(timeoutMs, () => {
1089
+ request.destroy();
1090
+ resolve(false);
1091
+ });
1092
+ });
1093
+ }
1094
+ async function waitForHealth(baseUrl, timeoutMs, tlsCa) {
1095
+ const deadline = Date.now() + timeoutMs;
1096
+ while (Date.now() < deadline) {
1097
+ if (await probeOnce(baseUrl, void 0, tlsCa)) return true;
1098
+ await delay(HEALTH_POLL_MS);
1099
+ }
1100
+ return false;
1101
+ }
1102
+ async function up(buildSpec) {
1103
+ const existing = readState();
1104
+ if (existing && isProcessAlive(existing.pid)) {
1105
+ io.log(style.warn(`${displayName} already running (pid ${existing.pid}) at ${config.baseUrl(existing)}`));
1106
+ return existing;
1107
+ }
1108
+ if (existing) clearState();
1109
+ const spec = await buildSpec();
1110
+ const binPath = resolveServerBin();
1111
+ const dir = paths.dir();
1112
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
1113
+ const logFd = openSync(paths.logPath(), "a");
1114
+ const child = spawn(PROCESS.execPath, [binPath, ...spec.args ?? []], {
1115
+ detached: true,
1116
+ env: spec.env,
1117
+ stdio: [
1118
+ "ignore",
1119
+ logFd,
1120
+ logFd
1121
+ ]
1122
+ });
1123
+ child.unref();
1124
+ if (child.pid === void 0) throw new Error(`Failed to spawn ${displayName} process`);
1125
+ io.log(style.dim(`starting ${displayName} (pid ${child.pid})...`));
1126
+ if (!await waitForHealth(spec.healthUrl, spec.timeoutMs, spec.healthTlsCa)) {
1127
+ try {
1128
+ PROCESS.kill(child.pid, "SIGTERM");
1129
+ } catch {}
1130
+ throw new Error(`${capitalizedName} did not become healthy within ${spec.timeoutMs / 1e3}s. Check logs at ${paths.logPath()}`);
1131
+ }
1132
+ const state = spec.buildState(child.pid);
1133
+ writeState(state);
1134
+ spec.onReady?.(state);
1135
+ return state;
1136
+ }
1137
+ async function down(options = {}) {
1138
+ const state = readState();
1139
+ if (!state) {
1140
+ io.log(style.warn(`${displayName} is not running`));
1141
+ return;
1142
+ }
1143
+ const graceMs = options.gracePeriodMs ?? DEFAULT_DOWN_GRACE_MS;
1144
+ const stopped = state;
1145
+ function cleanup() {
1146
+ config.postDown?.(stopped);
1147
+ clearState();
1148
+ }
1149
+ if (!isProcessAlive(state.pid)) {
1150
+ cleanup();
1151
+ io.log(style.success(`${displayName} pid ${state.pid} was already stopped \u2014 cleaned up state`));
1152
+ return;
1153
+ }
1154
+ try {
1155
+ PROCESS.kill(state.pid, "SIGTERM");
1156
+ } catch (error) {
1157
+ if (error.code !== "ESRCH") throw error;
1158
+ }
1159
+ const deadline = Date.now() + graceMs;
1160
+ while (Date.now() < deadline && isProcessAlive(state.pid)) await delay(DOWN_POLL_MS);
1161
+ if (isProcessAlive(state.pid)) try {
1162
+ PROCESS.kill(state.pid, "SIGKILL");
1163
+ } catch {}
1164
+ cleanup();
1165
+ io.log(style.success(`${displayName} pid ${state.pid} stopped`));
1166
+ }
1167
+ function printField(label, value) {
1168
+ io.log(` ${style.dim(`${label}:`.padEnd(STATUS_LABEL_WIDTH))}${value}`);
1169
+ }
1170
+ function statusLabel(isAlive, isHealthy) {
1171
+ if (isAlive && isHealthy) return style.success("running + healthy");
1172
+ if (isAlive) return style.warn("running but unresponsive");
1173
+ return style.error("stale state (process gone)");
1174
+ }
1175
+ async function status() {
1176
+ const state = readState();
1177
+ if (!state) {
1178
+ io.log(style.warn(`${displayName} not running`));
1179
+ return {
1180
+ exitCode: DAEMON_STATUS_EXIT_CODES.notRunning,
1181
+ isAlive: false,
1182
+ isHealthy: false
1183
+ };
1184
+ }
1185
+ const isAlive = isProcessAlive(state.pid);
1186
+ const tlsCa = config.health?.tlsCa?.(state);
1187
+ const isHealthy = isAlive ? await probeOnce(config.baseUrl(state), STATUS_PING_TIMEOUT_MS, tlsCa) : false;
1188
+ const uptime = formatUptime(state.startedAt, Date.now());
1189
+ io.log(style.info(`${displayName} status`));
1190
+ printField("state", statusLabel(isAlive, isHealthy));
1191
+ printField("pid", String(state.pid));
1192
+ const extraFields = config.statusFields?.(state) ?? [];
1193
+ for (const [label, value] of extraFields) printField(label, value);
1194
+ printField("started", `${state.startedAt}${uptime ? ` (${uptime})` : ""}`);
1195
+ printField("log", paths.logPath());
1196
+ let exitCode = DAEMON_STATUS_EXIT_CODES.healthy;
1197
+ if (!isAlive) exitCode = DAEMON_STATUS_EXIT_CODES.notRunning;
1198
+ else if (!isHealthy) exitCode = DAEMON_STATUS_EXIT_CODES.unresponsive;
1199
+ return {
1200
+ exitCode,
1201
+ isAlive,
1202
+ isHealthy,
1203
+ state
1204
+ };
1205
+ }
1206
+ async function logs(options = {}) {
1207
+ const logPath = paths.logPath();
1208
+ if (!existsSync(logPath)) {
1209
+ io.log(style.warn(`no ${displayName} log file yet`));
1210
+ return 0;
1211
+ }
1212
+ if (options.follow === true) {
1213
+ const child = spawn("tail", [
1214
+ "-n",
1215
+ String(options.lines ?? DEFAULT_LOG_LINES),
1216
+ "-f",
1217
+ logPath
1218
+ ], { stdio: "inherit" });
1219
+ return await new Promise((resolve) => {
1220
+ child.on("exit", (code) => {
1221
+ resolve(code ?? 0);
1222
+ });
1223
+ });
1224
+ }
1225
+ const tail = readFileSync(logPath, "utf8").split("\n").slice(-(options.lines ?? DEFAULT_LOG_LINES));
1226
+ io.log(tail.join("\n"));
1227
+ return 0;
1228
+ }
1229
+ async function reset() {
1230
+ await down();
1231
+ const dir = paths.dir();
1232
+ if (!existsSync(dir)) {
1233
+ io.log(style.success("nothing to reset"));
1234
+ return;
1235
+ }
1236
+ rmSync(dir, {
1237
+ recursive: true,
1238
+ force: true
1239
+ });
1240
+ io.log(style.success(`reset ${dir}`));
1241
+ }
1242
+ return {
1243
+ clearState,
1244
+ down,
1245
+ logs,
1246
+ paths,
1247
+ readState,
1248
+ reset,
1249
+ resolveServerBin,
1250
+ status,
1251
+ up,
1252
+ writeState
1253
+ };
1254
+ }
1255
+ //#endregion
1256
+ //#region ../../node_modules/.pnpm/@ariestools+cli-kit-node@1.2.3_@ariestools+actor-model@1.3.0_@ariestools+sdk@8.3.0_@ope_7b18c786a1c8bb7b1298534a22a75fd9/node_modules/@ariestools/cli-kit-node/dist/node/index.mjs
1257
+ function resolveEnvironmentValue(key, layers) {
1258
+ for (const layer of layers) {
1259
+ if (!Object.hasOwn(layer, key)) continue;
1260
+ const value = layer[key];
1261
+ if (value !== void 0) return value;
1262
+ }
1263
+ }
1264
+ function mergeEnvironments(primary, ...fallbacks) {
1265
+ const layers = [primary, ...fallbacks];
1266
+ const keys = /* @__PURE__ */ new Set();
1267
+ for (const layer of layers) for (const key of Object.keys(layer)) keys.add(key);
1268
+ const result = {};
1269
+ for (const key of keys) result[key] = resolveEnvironmentValue(key, layers);
1270
+ return result;
1271
+ }
1272
+ var nodeProcessIO = {
1273
+ get columns() {
1274
+ return PROCESS.stdout.columns;
1275
+ },
1276
+ get isInteractive() {
1277
+ return PROCESS.stdin.isTTY && PROCESS.stdout.isTTY;
1278
+ },
1279
+ error(...values) {
1280
+ console.error(...values);
1281
+ },
1282
+ log(...values) {
1283
+ console.log(...values);
1284
+ },
1285
+ async question(prompt) {
1286
+ const readline = createInterface({
1287
+ input: PROCESS.stdin,
1288
+ output: PROCESS.stdout
1289
+ });
1290
+ try {
1291
+ return await readline.question(prompt);
1292
+ } finally {
1293
+ readline.close();
1294
+ }
1295
+ },
1296
+ warn(...values) {
1297
+ console.warn(...values);
1298
+ }
1299
+ };
1300
+ var DEFAULT_INTERRUPT_SIGNALS = ["SIGINT", "SIGTERM"];
1301
+ function createNodeProcessHost(options) {
1302
+ const signals = options?.signals ?? DEFAULT_INTERRUPT_SIGNALS;
1303
+ const environmentOverride = options?.environment;
1304
+ const environmentDefaults = options?.environmentDefaults;
1305
+ function resolveEnvironment() {
1306
+ const primary = environmentOverride ?? PROCESS.env;
1307
+ if (environmentDefaults === void 0) return primary;
1308
+ return mergeEnvironments(primary, environmentDefaults);
1309
+ }
1310
+ return {
1311
+ get argv() {
1312
+ return PROCESS.argv;
1313
+ },
1314
+ get environment() {
1315
+ return resolveEnvironment();
1316
+ },
1317
+ exit(code) {
1318
+ PROCESS.exit(code);
1319
+ },
1320
+ get io() {
1321
+ return nodeProcessIO;
1322
+ },
1323
+ get isDevelopment() {
1324
+ return resolveEnvironment().NODE_ENV === "development";
1325
+ },
1326
+ onInterrupt(listener) {
1327
+ const handleInterrupt = () => {
1328
+ listener();
1329
+ };
1330
+ for (const signal of signals) PROCESS.on(signal, handleInterrupt);
1331
+ return () => {
1332
+ for (const signal of signals) PROCESS.off(signal, handleInterrupt);
1333
+ };
1334
+ }
1335
+ };
1336
+ }
1337
+ var nodeProcessHost = createNodeProcessHost();
1338
+ //#endregion
1339
+ //#region ../../node_modules/.pnpm/chalk@6.0.0/node_modules/chalk/source/utilities.js
1340
+ function stringReplaceAll(string, substring, postfix) {
1341
+ let index = string.indexOf(substring);
1342
+ if (index === -1) return string;
1343
+ const substringLength = substring.length;
1344
+ let endIndex = 0;
1345
+ let returnValue = "";
1346
+ do {
1347
+ returnValue += string.slice(endIndex, index) + substring + postfix;
1348
+ endIndex = index + substringLength;
1349
+ index = string.indexOf(substring, endIndex);
1350
+ } while (index !== -1);
1351
+ returnValue += string.slice(endIndex);
1352
+ return returnValue;
1353
+ }
1354
+ function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) {
1355
+ let endIndex = 0;
1356
+ let returnValue = "";
1357
+ do {
1358
+ const isGotCR = string[index - 1] === "\r";
1359
+ returnValue += string.slice(endIndex, isGotCR ? index - 1 : index) + prefix + (isGotCR ? "\r\n" : "\n") + postfix;
1360
+ endIndex = index + 1;
1361
+ index = string.indexOf("\n", endIndex);
1362
+ } while (index !== -1);
1363
+ returnValue += string.slice(endIndex);
1364
+ return returnValue;
1365
+ }
1366
+ //#endregion
1367
+ //#region ../../node_modules/.pnpm/chalk@6.0.0/node_modules/chalk/source/vendor/ansi-styles/index.js
1368
+ const ANSI_BACKGROUND_OFFSET = 10;
1369
+ const ANSI_UNDERLINE_OFFSET = 20;
1370
+ const wrapAnsi16 = (offset = 0) => (code) => `\u{1B}[${code + offset}m`;
1371
+ const wrapAnsi256 = (offset = 0) => (code) => `\u{1B}[${38 + offset};5;${code}m`;
1372
+ const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u{1B}[${38 + offset};2;${red};${green};${blue}m`;
1373
+ const wrapUnderlineAnsi = (code) => `\u{1B}[58;5;${code < 90 ? code - 30 : code - 90 + 8}m`;
1374
+ const styles$1 = {
1375
+ modifier: {
1376
+ reset: [0, 0],
1377
+ bold: [1, 22],
1378
+ dim: [2, 22],
1379
+ italic: [3, 23],
1380
+ underline: [4, 24],
1381
+ underlineDouble: ["4:2", 24],
1382
+ underlineCurly: ["4:3", 24],
1383
+ underlineDotted: ["4:4", 24],
1384
+ underlineDashed: ["4:5", 24],
1385
+ overline: [53, 55],
1386
+ inverse: [7, 27],
1387
+ hidden: [8, 28],
1388
+ strikethrough: [9, 29]
1389
+ },
1390
+ color: {
1391
+ black: [30, 39],
1392
+ red: [31, 39],
1393
+ green: [32, 39],
1394
+ yellow: [33, 39],
1395
+ blue: [34, 39],
1396
+ magenta: [35, 39],
1397
+ cyan: [36, 39],
1398
+ white: [37, 39],
1399
+ blackBright: [90, 39],
1400
+ gray: [90, 39],
1401
+ grey: [90, 39],
1402
+ redBright: [91, 39],
1403
+ greenBright: [92, 39],
1404
+ yellowBright: [93, 39],
1405
+ blueBright: [94, 39],
1406
+ magentaBright: [95, 39],
1407
+ cyanBright: [96, 39],
1408
+ whiteBright: [97, 39]
1409
+ },
1410
+ bgColor: {
1411
+ bgBlack: [40, 49],
1412
+ bgRed: [41, 49],
1413
+ bgGreen: [42, 49],
1414
+ bgYellow: [43, 49],
1415
+ bgBlue: [44, 49],
1416
+ bgMagenta: [45, 49],
1417
+ bgCyan: [46, 49],
1418
+ bgWhite: [47, 49],
1419
+ bgBlackBright: [100, 49],
1420
+ bgGray: [100, 49],
1421
+ bgGrey: [100, 49],
1422
+ bgRedBright: [101, 49],
1423
+ bgGreenBright: [102, 49],
1424
+ bgYellowBright: [103, 49],
1425
+ bgBlueBright: [104, 49],
1426
+ bgMagentaBright: [105, 49],
1427
+ bgCyanBright: [106, 49],
1428
+ bgWhiteBright: [107, 49]
1429
+ },
1430
+ underlineColor: {
1431
+ underlineBlack: ["58;5;0", 59],
1432
+ underlineRed: ["58;5;1", 59],
1433
+ underlineGreen: ["58;5;2", 59],
1434
+ underlineYellow: ["58;5;3", 59],
1435
+ underlineBlue: ["58;5;4", 59],
1436
+ underlineMagenta: ["58;5;5", 59],
1437
+ underlineCyan: ["58;5;6", 59],
1438
+ underlineWhite: ["58;5;7", 59],
1439
+ underlineBlackBright: ["58;5;8", 59],
1440
+ underlineGray: ["58;5;8", 59],
1441
+ underlineGrey: ["58;5;8", 59],
1442
+ underlineRedBright: ["58;5;9", 59],
1443
+ underlineGreenBright: ["58;5;10", 59],
1444
+ underlineYellowBright: ["58;5;11", 59],
1445
+ underlineBlueBright: ["58;5;12", 59],
1446
+ underlineMagentaBright: ["58;5;13", 59],
1447
+ underlineCyanBright: ["58;5;14", 59],
1448
+ underlineWhiteBright: ["58;5;15", 59]
1449
+ }
1450
+ };
1451
+ Object.keys(styles$1.modifier);
1452
+ const foregroundColorNames = Object.keys(styles$1.color);
1453
+ const backgroundColorNames = Object.keys(styles$1.bgColor);
1454
+ Object.keys(styles$1.underlineColor);
1455
+ [...foregroundColorNames, ...backgroundColorNames];
1456
+ function assembleStyles() {
1457
+ const codes = /* @__PURE__ */ new Map();
1458
+ for (const [groupName, group] of Object.entries(styles$1)) {
1459
+ for (const [styleName, style] of Object.entries(group)) {
1460
+ styles$1[styleName] = {
1461
+ open: `\u{1B}[${style[0]}m`,
1462
+ close: `\u{1B}[${style[1]}m`
1463
+ };
1464
+ group[styleName] = styles$1[styleName];
1465
+ codes.set(Number.parseInt(style[0], 10), style[1]);
1466
+ }
1467
+ Object.defineProperty(styles$1, groupName, {
1468
+ value: group,
1469
+ enumerable: false
1470
+ });
1471
+ }
1472
+ Object.defineProperty(styles$1, "codes", {
1473
+ value: codes,
1474
+ enumerable: false
1475
+ });
1476
+ styles$1.color.close = "\x1B[39m";
1477
+ styles$1.bgColor.close = "\x1B[49m";
1478
+ styles$1.underlineColor.close = "\x1B[59m";
1479
+ styles$1.color.ansi = wrapAnsi16();
1480
+ styles$1.color.ansi256 = wrapAnsi256();
1481
+ styles$1.color.ansi16m = wrapAnsi16m();
1482
+ styles$1.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET);
1483
+ styles$1.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET);
1484
+ styles$1.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET);
1485
+ styles$1.underlineColor.ansi = wrapUnderlineAnsi;
1486
+ styles$1.underlineColor.ansi256 = wrapAnsi256(ANSI_UNDERLINE_OFFSET);
1487
+ styles$1.underlineColor.ansi16m = wrapAnsi16m(ANSI_UNDERLINE_OFFSET);
1488
+ Object.defineProperties(styles$1, {
1489
+ rgbToAnsi256: {
1490
+ value(red, green, blue) {
1491
+ if (red === green && green === blue) {
1492
+ if (red < 8) return 16;
1493
+ if (red > 248) return 231;
1494
+ return Math.round((red - 8) / 247 * 24) + 232;
1495
+ }
1496
+ return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5);
1497
+ },
1498
+ enumerable: false
1499
+ },
1500
+ hexToRgb: {
1501
+ value(hex) {
1502
+ const matches = /[\da-f]{6}|[\da-f]{3}/i.exec(hex.toString(16));
1503
+ if (!matches) return [
1504
+ 0,
1505
+ 0,
1506
+ 0
1507
+ ];
1508
+ let [colorString] = matches;
1509
+ if (colorString.length === 3) colorString = [...colorString].map((character) => character + character).join("");
1510
+ const integer = Number.parseInt(colorString, 16);
1511
+ return [
1512
+ integer >> 16 & 255,
1513
+ integer >> 8 & 255,
1514
+ integer & 255
1515
+ ];
1516
+ },
1517
+ enumerable: false
1518
+ },
1519
+ hexToAnsi256: {
1520
+ value: (hex) => styles$1.rgbToAnsi256(...styles$1.hexToRgb(hex)),
1521
+ enumerable: false
1522
+ },
1523
+ ansi256ToAnsi: {
1524
+ value(code) {
1525
+ if (code < 8) return 30 + code;
1526
+ if (code < 16) return 90 + (code - 8);
1527
+ let red;
1528
+ let green;
1529
+ let blue;
1530
+ if (code >= 232) {
1531
+ red = ((code - 232) * 10 + 8) / 255;
1532
+ green = red;
1533
+ blue = red;
1534
+ } else {
1535
+ code -= 16;
1536
+ const remainder = code % 36;
1537
+ red = Math.floor(code / 36) / 5;
1538
+ green = Math.floor(remainder / 6) / 5;
1539
+ blue = remainder % 6 / 5;
1540
+ }
1541
+ const value = Math.max(red, green, blue) * 2;
1542
+ if (value === 0) return 30;
1543
+ let result = 30 + (Math.round(blue) << 2 | Math.round(green) << 1 | Math.round(red));
1544
+ if (value === 2) result += 60;
1545
+ return result;
1546
+ },
1547
+ enumerable: false
1548
+ },
1549
+ rgbToAnsi: {
1550
+ value: (red, green, blue) => styles$1.ansi256ToAnsi(styles$1.rgbToAnsi256(red, green, blue)),
1551
+ enumerable: false
1552
+ },
1553
+ hexToAnsi: {
1554
+ value: (hex) => styles$1.ansi256ToAnsi(styles$1.hexToAnsi256(hex)),
1555
+ enumerable: false
1556
+ }
1557
+ });
1558
+ return styles$1;
1559
+ }
1560
+ const ansiStyles = assembleStyles();
1561
+ //#endregion
1562
+ //#region ../../node_modules/.pnpm/chalk@6.0.0/node_modules/chalk/source/vendor/supports-color/index.js
1563
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : PROCESS.argv) {
1564
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
1565
+ const position = argv.indexOf(prefix + flag);
1566
+ const terminatorPosition = argv.indexOf("--");
1567
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
1568
+ }
1569
+ const { env } = PROCESS;
1570
+ let flagForceColor;
1571
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) flagForceColor = 0;
1572
+ else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) flagForceColor = 1;
1573
+ function hasNumericForceColor() {
1574
+ return /^\d+$/.test(env.FORCE_COLOR);
1575
+ }
1576
+ function envForceColor() {
1577
+ if (!("FORCE_COLOR" in env)) return;
1578
+ if (env.FORCE_COLOR === "false") return 0;
1579
+ if (env.FORCE_COLOR === "true" || env.FORCE_COLOR.length === 0) return 1;
1580
+ if (!hasNumericForceColor()) return;
1581
+ return Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
1582
+ }
1583
+ function translateLevel(level) {
1584
+ if (level === 0) return false;
1585
+ return {
1586
+ level,
1587
+ hasBasic: true,
1588
+ has256: level >= 2,
1589
+ has16m: level >= 3
1590
+ };
1591
+ }
1592
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
1593
+ const noFlagForceColor = envForceColor();
1594
+ if (noFlagForceColor !== void 0) flagForceColor = noFlagForceColor;
1595
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
1596
+ if (forceColor === 0) return 0;
1597
+ if (sniffFlags) {
1598
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) return 3;
1599
+ if (hasFlag("color=256")) return 2;
1600
+ }
1601
+ if (forceColor !== void 0 && hasNumericForceColor()) return forceColor;
1602
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) return 1;
1603
+ if (haveStream && !streamIsTTY && forceColor === void 0) return 0;
1604
+ const min = forceColor || 0;
1605
+ if (env.TERM === "dumb") return min;
1606
+ if (PROCESS.platform === "win32") {
1607
+ const osRelease = os.release().split(".");
1608
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) return Number(osRelease[2]) >= 14931 ? 3 : 2;
1609
+ return 1;
1610
+ }
1611
+ if ("CI" in env) {
1612
+ if ([
1613
+ "GITHUB_ACTIONS",
1614
+ "GITEA_ACTIONS",
1615
+ "CIRCLECI"
1616
+ ].some((key) => key in env)) return 3;
1617
+ if ([
1618
+ "TRAVIS",
1619
+ "APPVEYOR",
1620
+ "GITLAB_CI",
1621
+ "BUILDKITE",
1622
+ "DRONE"
1623
+ ].some((sign) => sign in env) || env.CI_NAME === "codeship") return 1;
1624
+ return min;
1625
+ }
1626
+ if ("TEAMCITY_VERSION" in env) return /^(?:9\.0*[1-9]\d*\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
1627
+ if (env.COLORTERM === "truecolor") return 3;
1628
+ if (env.TERM === "xterm-kitty") return 3;
1629
+ if (env.TERM === "xterm-ghostty") return 3;
1630
+ if (env.TERM === "wezterm") return 3;
1631
+ if ("TERM_PROGRAM" in env) {
1632
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".", 1)[0], 10);
1633
+ switch (env.TERM_PROGRAM) {
1634
+ case "iTerm.app": return version >= 3 ? 3 : 2;
1635
+ case "Apple_Terminal": return 2;
1636
+ }
1637
+ }
1638
+ if (/-256(?:color)?$/i.test(env.TERM)) return 2;
1639
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) return 1;
1640
+ if ("COLORTERM" in env) return 1;
1641
+ return min;
1642
+ }
1643
+ function createSupportsColor(stream, options = {}) {
1644
+ return translateLevel(_supportsColor(stream, {
1645
+ streamIsTTY: stream && stream.isTTY,
1646
+ ...options
1647
+ }));
1648
+ }
1649
+ //#endregion
1650
+ //#region ../../node_modules/.pnpm/chalk@6.0.0/node_modules/chalk/source/index.js
1651
+ const { stdout: stdoutColor, stderr: stderrColor } = {
1652
+ stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
1653
+ stderr: createSupportsColor({ isTTY: tty.isatty(2) })
1654
+ };
1655
+ const GENERATOR = Symbol("GENERATOR");
1656
+ const STYLER = Symbol("STYLER");
1657
+ const IS_EMPTY = Symbol("IS_EMPTY");
1658
+ const LEVEL = Symbol("LEVEL");
1659
+ const styles = Object.create(null);
1660
+ const assertValidLevel = (level) => {
1661
+ if (!Number.isSafeInteger(level) || level < 0 || level > 3) throw new Error("The `level` should be an integer from 0 to 3");
1662
+ };
1663
+ const levelDescriptor = {
1664
+ enumerable: true,
1665
+ get() {
1666
+ return this[LEVEL];
1667
+ },
1668
+ set(level) {
1669
+ assertValidLevel(level);
1670
+ this[LEVEL] = level;
1671
+ }
1672
+ };
1673
+ const applyOptions = (object, options = {}) => {
1674
+ if (options.level !== void 0) assertValidLevel(options.level);
1675
+ const colorLevel = stdoutColor ? stdoutColor.level : 0;
1676
+ object[LEVEL] = options.level === void 0 ? colorLevel : options.level;
1677
+ };
1678
+ const chalkFactory = (options) => {
1679
+ const chalk = (...strings) => strings.join(" ");
1680
+ applyOptions(chalk, options);
1681
+ Object.setPrototypeOf(chalk, createChalk.prototype);
1682
+ return chalk;
1683
+ };
1684
+ function createChalk(options) {
1685
+ return chalkFactory(options);
1686
+ }
1687
+ Object.setPrototypeOf(createChalk.prototype, Function.prototype);
1688
+ for (const [styleName, style] of Object.entries(ansiStyles)) styles[styleName] = { get() {
1689
+ const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]);
1690
+ Object.defineProperty(this, styleName, { value: builder });
1691
+ return builder;
1692
+ } };
1693
+ styles.visible = { get() {
1694
+ const builder = createBuilder(this, this[STYLER], true);
1695
+ Object.defineProperty(this, "visible", { value: builder });
1696
+ return builder;
1697
+ } };
1698
+ const createModelConverters = (model, type) => {
1699
+ const style = ansiStyles[type];
1700
+ if (model === "rgb") {
1701
+ const ansi = (red, green, blue) => style.ansi(ansiStyles.rgbToAnsi(red, green, blue));
1702
+ const ansi256 = (red, green, blue) => style.ansi256(ansiStyles.rgbToAnsi256(red, green, blue));
1703
+ return [
1704
+ ansi,
1705
+ ansi,
1706
+ ansi256,
1707
+ style.ansi16m
1708
+ ];
1709
+ }
1710
+ if (model === "hex") {
1711
+ const ansi = (hex) => style.ansi(ansiStyles.hexToAnsi(hex));
1712
+ const ansi256 = (hex) => style.ansi256(ansiStyles.hexToAnsi256(hex));
1713
+ return [
1714
+ ansi,
1715
+ ansi,
1716
+ ansi256,
1717
+ (hex) => style.ansi16m(...ansiStyles.hexToRgb(hex))
1718
+ ];
1719
+ }
1720
+ const ansi = (code) => style.ansi(ansiStyles.ansi256ToAnsi(code));
1721
+ return [
1722
+ ansi,
1723
+ ansi,
1724
+ style.ansi256,
1725
+ style.ansi256
1726
+ ];
1727
+ };
1728
+ for (const model of [
1729
+ "rgb",
1730
+ "hex",
1731
+ "ansi256"
1732
+ ]) {
1733
+ const capitalizedModel = model[0].toUpperCase() + model.slice(1);
1734
+ for (const [styleName, type] of [
1735
+ [model, "color"],
1736
+ ["bg" + capitalizedModel, "bgColor"],
1737
+ ["underline" + capitalizedModel, "underlineColor"]
1738
+ ]) {
1739
+ const { close } = ansiStyles[type];
1740
+ const converters = createModelConverters(model, type);
1741
+ styles[styleName] = { get() {
1742
+ const styleFunction = function(first, second, third) {
1743
+ const open = converters[this.level](first, second, third);
1744
+ return createBuilder(this, createStyler(open, close, this[STYLER]), this[IS_EMPTY]);
1745
+ };
1746
+ Object.defineProperty(this, styleName, { value: styleFunction });
1747
+ return styleFunction;
1748
+ } };
1749
+ }
1750
+ }
1751
+ const proto = Object.defineProperties(() => {}, {
1752
+ ...styles,
1753
+ level: {
1754
+ enumerable: true,
1755
+ get() {
1756
+ return this[GENERATOR].level;
1757
+ },
1758
+ set(level) {
1759
+ this[GENERATOR].level = level;
1760
+ }
1761
+ }
1762
+ });
1763
+ const createStyler = (open, close, parent) => {
1764
+ let openAll;
1765
+ let closeAll;
1766
+ if (parent === void 0) {
1767
+ openAll = open;
1768
+ closeAll = close;
1769
+ } else {
1770
+ openAll = parent.openAll + open;
1771
+ closeAll = close + parent.closeAll;
1772
+ }
1773
+ return {
1774
+ open,
1775
+ close,
1776
+ openAll,
1777
+ closeAll,
1778
+ parent
1779
+ };
1780
+ };
1781
+ const createBuilder = (self, _styler, _isEmpty) => {
1782
+ const builder = (...arguments_) => {
1783
+ if (arguments_.length === 1) return applyStyle(builder, "" + arguments_[0]);
1784
+ if (arguments_.length === 2) return applyStyle(builder, arguments_[0] + " " + arguments_[1]);
1785
+ return applyStyle(builder, arguments_.join(" "));
1786
+ };
1787
+ Object.setPrototypeOf(builder, proto);
1788
+ builder[GENERATOR] = self[GENERATOR] ?? self;
1789
+ builder[STYLER] = _styler;
1790
+ builder[IS_EMPTY] = _isEmpty;
1791
+ return builder;
1792
+ };
1793
+ const applyStyle = (self, string) => {
1794
+ if (self[GENERATOR][LEVEL] <= 0 || !string) return self[IS_EMPTY] ? "" : string;
1795
+ let styler = self[STYLER];
1796
+ if (styler === void 0) return string;
1797
+ const { openAll, closeAll } = styler;
1798
+ if (string.includes("\x1B")) while (styler !== void 0) {
1799
+ string = stringReplaceAll(string, styler.close, styler.open);
1800
+ styler = styler.parent;
1801
+ }
1802
+ const lfIndex = string.indexOf("\n");
1803
+ if (lfIndex !== -1) string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
1804
+ return openAll + string + closeAll;
1805
+ };
1806
+ Object.defineProperties(createChalk.prototype, {
1807
+ ...styles,
1808
+ level: levelDescriptor
1809
+ });
1810
+ const chalk = createChalk();
1811
+ createChalk({ level: stderrColor ? stderrColor.level : 0 });
1812
+ //#endregion
1813
+ //#region ../datalake-core/dist/node/index.mjs
1814
+ var DATALAKE_CONTROL_AUDIENCE = "aries-datalake-control";
1815
+ var DATALAKE_CONTROL_OPERATIONS = [
1816
+ "datalake:create",
1817
+ "datalake:describe",
1818
+ "datalake:list"
1819
+ ];
1820
+ var DATALAKE_DATA_OPERATIONS = [
1821
+ "payload:append",
1822
+ "payload:read",
1823
+ "usage:read"
1824
+ ];
1825
+ DATALAKE_CONTROL_OPERATIONS.join(" ");
1826
+ DATALAKE_DATA_OPERATIONS.join(" ");
1827
+ //#endregion
1828
+ //#region ../cli-lib/dist/node/datalake.mjs
1829
+ var MONOREPO_BIN_SEARCH_PATHS = ["../../../cli/dist/bin", "../../../cli-internal/dist/bin"];
1830
+ function createDaemonKit(config) {
1831
+ return createDaemonKit$1({
1832
+ ...config,
1833
+ bin: {
1834
+ ...config.bin,
1835
+ resolveFromUrl: import.meta.url,
1836
+ searchPaths: MONOREPO_BIN_SEARCH_PATHS
1837
+ },
1838
+ homeDir: () => process.env.ARIES_HOME ?? path.join(homedir(), ".aries"),
1839
+ host: nodeProcessHost,
1840
+ style: {
1841
+ dim: chalk.gray,
1842
+ error: chalk.red,
1843
+ info: chalk.cyan,
1844
+ success: chalk.green,
1845
+ warn: chalk.yellow
1846
+ }
1847
+ });
1848
+ }
1849
+ function normalizeDevState(value) {
1850
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
1851
+ const state = value;
1852
+ if (typeof state.pid !== "number" || !Number.isSafeInteger(state.pid) || state.pid <= 0) return void 0;
1853
+ if (typeof state.startedAt !== "string") return void 0;
1854
+ if (typeof state.controlUrl !== "string" || typeof state.planeUrl !== "string") return void 0;
1855
+ const controlAudience = typeof state.controlAudience === "string" && state.controlAudience.length > 0 ? state.controlAudience : DATALAKE_CONTROL_AUDIENCE;
1856
+ const corsOrigins = Array.isArray(state.corsOrigins) && state.corsOrigins.every((origin) => typeof origin === "string") ? [...new Set(state.corsOrigins)] : [];
1857
+ const persistDir = typeof state.persistDir === "string" && state.persistDir.length > 0 ? state.persistDir : void 0;
1858
+ return {
1859
+ pid: state.pid,
1860
+ startedAt: state.startedAt,
1861
+ controlUrl: state.controlUrl,
1862
+ planeUrl: state.planeUrl,
1863
+ controlAudience,
1864
+ corsOrigins,
1865
+ ...persistDir && { persistDir }
1866
+ };
1867
+ }
1868
+ var devDaemon = createDaemonKit({
1869
+ dirName: "dev",
1870
+ displayName: "dev server",
1871
+ bin: {
1872
+ embeddedRelPath: "daemons/datalake-dev.mjs",
1873
+ packageName: "@ariestools/aries-datalake-plane",
1874
+ binRelPath: "dist/bin/devServer.mjs",
1875
+ installHint: "Rebuild the CLI package so dist/bin/daemons/datalake-dev.mjs is embedded."
1876
+ },
1877
+ normalizeState: normalizeDevState,
1878
+ health: { path: "/v1/health" },
1879
+ baseUrl: (state) => state.controlUrl,
1880
+ statusFields: (state) => [
1881
+ ["control", state.controlUrl],
1882
+ ["data", state.planeUrl],
1883
+ ["audience", state.controlAudience],
1884
+ ["cors", state.corsOrigins.join(", ") || "disabled"],
1885
+ ["store", state.persistDir ?? "in-memory"]
1886
+ ],
1887
+ postDown: (state) => {
1888
+ if (loadCredentials()?.baseUrl === state.controlUrl) clearCredentials();
1889
+ }
1890
+ });
1891
+ var DEFAULT_TIMEOUT_MS = 1e3;
1892
+ async function inspectDatalakeDevServer(options = {}) {
1893
+ const state = devDaemon.readState();
1894
+ if (state === void 0) return {
1895
+ schemaVersion: 1,
1896
+ status: "stopped",
1897
+ exitCode: 3,
1898
+ process: {
1899
+ running: false,
1900
+ pid: null,
1901
+ startedAt: null
1902
+ },
1903
+ endpoints: {
1904
+ control: null,
1905
+ plane: null
1906
+ }
1907
+ };
1908
+ if (!isProcessAlive(state.pid)) return {
1909
+ schemaVersion: 1,
1910
+ status: "stale",
1911
+ exitCode: 3,
1912
+ process: {
1913
+ running: false,
1914
+ pid: state.pid,
1915
+ startedAt: state.startedAt
1916
+ },
1917
+ endpoints: {
1918
+ control: {
1919
+ healthy: false,
1920
+ url: state.controlUrl
1921
+ },
1922
+ plane: {
1923
+ healthy: false,
1924
+ url: state.planeUrl
1925
+ }
1926
+ }
1927
+ };
1928
+ const timeoutMs = normalizeTimeout(options.timeoutMs);
1929
+ const [controlHealthy, planeHealthy] = await Promise.all([probeHealth(state.controlUrl, timeoutMs), probeHealth(state.planeUrl, timeoutMs)]);
1930
+ const status = resolveStatus(controlHealthy, planeHealthy);
1931
+ return {
1932
+ schemaVersion: 1,
1933
+ status,
1934
+ exitCode: status === "healthy" ? 0 : 2,
1935
+ process: {
1936
+ running: true,
1937
+ pid: state.pid,
1938
+ startedAt: state.startedAt
1939
+ },
1940
+ endpoints: {
1941
+ control: {
1942
+ healthy: controlHealthy,
1943
+ url: state.controlUrl
1944
+ },
1945
+ plane: {
1946
+ healthy: planeHealthy,
1947
+ url: state.planeUrl
1948
+ }
1949
+ }
1950
+ };
1951
+ }
1952
+ function normalizeTimeout(value) {
1953
+ if (value === void 0) return DEFAULT_TIMEOUT_MS;
1954
+ if (!Number.isFinite(value) || value <= 0) throw new Error("timeoutMs must be a positive number");
1955
+ return value;
1956
+ }
1957
+ async function probeHealth(baseUrl, timeoutMs) {
1958
+ const controller = new AbortController();
1959
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
1960
+ try {
1961
+ return (await fetch(`${baseUrl.replace(/\/$/, "")}/v1/health`, { signal: controller.signal })).ok;
1962
+ } catch {
1963
+ return false;
1964
+ } finally {
1965
+ clearTimeout(timeout);
1966
+ }
1967
+ }
1968
+ function resolveStatus(controlHealthy, planeHealthy) {
1969
+ if (controlHealthy && planeHealthy) return "healthy";
1970
+ if (controlHealthy || planeHealthy) return "degraded";
1971
+ return "unresponsive";
490
1972
  }
491
1973
  //#endregion
492
- export { LocalDatalakeClient, RestDatalakeClient, RestPayloadsClient, clearCredentials, clearDefaultDatalake, createDatalakeClient, getCredentialsLocation, getDefaultDatalake, loadCredentials, saveCredentials, setDefaultDatalake };
1974
+ export { LocalDatalakeClient, RestDatalakeClient, RestPayloadsClient, clearCredentials, clearDefaultDatalake, createDatalakeClient, getCredentialsLocation, getDefaultDatalake, inspectDatalakeDevServer, loadCredentials, saveCredentials, setDefaultDatalake };