@curviate/cli 0.32.0 → 0.34.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +264 -1
  2. package/README.md +13 -1
  3. package/dist/{account-JDSZC633.js → account-463D5EVY.js} +90 -47
  4. package/dist/{chunk-JRKM4OV2.js → chunk-6W7364S3.js} +1 -1
  5. package/dist/{chunk-KQXYEQAD.js → chunk-7JU4IXXG.js} +172 -8
  6. package/dist/{chunk-5EJDQ47B.js → chunk-BN7L7WSY.js} +16 -16
  7. package/dist/chunk-DCZR4M7G.js +327 -0
  8. package/dist/{chunk-V3PB4HSF.js → chunk-MNDXMGPX.js} +68 -24
  9. package/dist/chunk-TCUYH5GO.js +34 -0
  10. package/dist/{chunk-SKJNLN37.js → chunk-XDQHNUEU.js} +86 -2
  11. package/dist/{chunk-LJR4LJG6.js → chunk-XP2LN6F6.js} +53 -0
  12. package/dist/{chunk-EIEF2KFH.js → chunk-XZJQQJBE.js} +6 -4
  13. package/dist/{chunk-6P52Q2GK.js → chunk-ZJ7D3NFS.js} +5 -4
  14. package/dist/cli.js +104 -37
  15. package/dist/{comment-YOFNFQUE.js → comment-G6RB2PBZ.js} +32 -26
  16. package/dist/{company-6PKHDK6L.js → company-OWND3W3L.js} +53 -35
  17. package/dist/{config-FUHT23SX.js → config-RUBXWFQ3.js} +74 -29
  18. package/dist/{connect-DG2AVGVL.js → connect-3E7EC5ZM.js} +35 -32
  19. package/dist/{doctor-FK7B6754.js → doctor-Z6OSCGKT.js} +22 -16
  20. package/dist/{exit-codes-AAFTOAXF.js → exit-codes-YSFFFWMS.js} +1 -1
  21. package/dist/{feed-HXBKXKAQ.js → feed-VDTFIMKN.js} +18 -17
  22. package/dist/{group-UYX3KTX3.js → group-KDJHY2IM.js} +21 -18
  23. package/dist/{inbox-EVE2ZTHC.js → inbox-DQLX2LR7.js} +39 -23
  24. package/dist/{inboxes-JBB34WMQ.js → inboxes-WMNHOPY7.js} +18 -17
  25. package/dist/{job-GXUZANYN.js → job-ESKS2LDJ.js} +44 -30
  26. package/dist/{login-3OAUY7TG.js → login-YTVPIN27.js} +15 -3
  27. package/dist/{message-34AGROW2.js → message-5W2R3YHS.js} +7 -9
  28. package/dist/{notification-SKKZS2C5.js → notification-IGNUH2GR.js} +20 -19
  29. package/dist/{post-FIW522Q6.js → post-NLI76K74.js} +34 -26
  30. package/dist/{profile-SX6JOYMD.js → profile-TBKKIICM.js} +71 -90
  31. package/dist/{recruiter-H7ROBEVC.js → recruiter-AEJRHIX5.js} +42 -29
  32. package/dist/{sales-nav-7KCK562X.js → sales-nav-SW6WJVMD.js} +43 -29
  33. package/dist/{search-PASMDQEH.js → search-CS6VN5AG.js} +58 -44
  34. package/dist/{setup-YV5PVIU5.js → setup-ANHJZJ2S.js} +12 -8
  35. package/dist/{webhook-GPLFPC6N.js → webhook-NGMRJMQ5.js} +25 -22
  36. package/package.json +2 -2
  37. package/dist/chunk-LKF5MZIP.js +0 -90
  38. package/dist/chunk-PKSKQ3LN.js +0 -68
  39. package/dist/chunk-R3VLWLVV.js +0 -23
  40. package/dist/chunk-TD2ZIXFR.js +0 -67
  41. package/dist/chunk-TQJ77SL4.js +0 -147
@@ -1,4 +1,9 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ isPlainObject,
4
+ profileValue,
5
+ readConfigFile
6
+ } from "./chunk-DCZR4M7G.js";
2
7
 
3
8
  // src/lib/output.ts
4
9
  function isJsonMode(opts) {
@@ -45,6 +50,7 @@ function applyProjection(data, fields) {
45
50
  }
46
51
  return data;
47
52
  }
53
+ var parseFields = (raw) => raw ? raw.split(",").map((f) => f.trim()).filter(Boolean) : [];
48
54
  var isPlain = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
49
55
  function withPreservedNotices(original, rendered) {
50
56
  if (!isPlain(original) || !isPlain(rendered)) return rendered;
@@ -53,6 +59,8 @@ function withPreservedNotices(original, rendered) {
53
59
  if (Array.isArray(notices) && notices.length > 0 && rendered["notices"] !== notices) {
54
60
  out = { ...out, notices };
55
61
  }
62
+ const safetyWarning = original["safety_warning"];
63
+ if (isPlain(safetyWarning)) out = { ...out, safety_warning: safetyWarning };
56
64
  return withPreservedProvenance(original, out);
57
65
  }
58
66
  var PROVENANCE_KEYS = ["source", "observed_at", "withdrawn", "withdrawn_at"];
@@ -84,14 +92,14 @@ function renderProvenanceNote(data) {
84
92
  return line + "\n";
85
93
  }
86
94
  function firstProjectableItem(data) {
87
- const isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
95
+ const isPlainObject2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
88
96
  if (Array.isArray(data)) {
89
- return data.length > 0 && isPlainObject(data[0]) ? data[0] : null;
97
+ return data.length > 0 && isPlainObject2(data[0]) ? data[0] : null;
90
98
  }
91
- if (isPlainObject(data)) {
99
+ if (isPlainObject2(data)) {
92
100
  const items = data["items"];
93
101
  if (Array.isArray(items)) {
94
- return items.length > 0 && isPlainObject(items[0]) ? items[0] : null;
102
+ return items.length > 0 && isPlainObject2(items[0]) ? items[0] : null;
95
103
  }
96
104
  return data;
97
105
  }
@@ -110,7 +118,7 @@ function detectUnknownFields(data, fields) {
110
118
  }
111
119
  function renderSuccess(data, opts, out) {
112
120
  const json = isJsonMode(opts);
113
- const fields = opts.fields ? opts.fields.split(",").map((f) => f.trim()).filter(Boolean) : [];
121
+ const fields = parseFields(opts.fields);
114
122
  const slimmed = !opts.verbose && opts.slim ? opts.slim(data) : data;
115
123
  const unknownFields = detectUnknownFields(withPreservedNotices(data, slimmed), fields);
116
124
  if (unknownFields) {
@@ -128,6 +136,11 @@ function renderSuccess(data, opts, out) {
128
136
  out.stdout.write(renderHuman(projected) + "\n");
129
137
  }
130
138
  }
139
+ function writeNdjsonItem(out, item, fields, original = item) {
140
+ const list = parseFields(fields);
141
+ const projected = list.length > 0 ? withPreservedNotices(original, applyProjection(item, list)) : item;
142
+ out.stdout.write(JSON.stringify(projected) + "\n");
143
+ }
131
144
  function formatNotice(notice) {
132
145
  if (typeof notice !== "object" || notice === null) return null;
133
146
  const n = notice;
@@ -152,7 +165,11 @@ function renderHuman(data) {
152
165
  const notices = renderNotices(obj["notices"]);
153
166
  if (Array.isArray(obj["items"])) {
154
167
  const items = obj["items"];
155
- const body = items.length === 0 ? "(no items)" : items.map(renderHuman).join("\n");
168
+ let body = items.length === 0 ? "(no items)" : items.map(renderHuman).join("\n");
169
+ if (isPlain(obj["safety_warning"])) {
170
+ body = `safety_warning: ${JSON.stringify(obj["safety_warning"])}
171
+ ${body}`;
172
+ }
156
173
  return notices ? `${notices}
157
174
  ${body}` : body;
158
175
  }
@@ -222,10 +239,157 @@ function renderUnexpectedError(err, out) {
222
239
  `);
223
240
  }
224
241
 
242
+ // src/lib/paginate.ts
243
+ import { CurviateError } from "@curviate/sdk";
244
+ function readablePage(page) {
245
+ const list = isPlainObject(page) ? page["items"] === void 0 ? page["data"] : page["items"] : void 0;
246
+ if (!Array.isArray(list)) throw unreadable("list page");
247
+ return { ...page, items: list };
248
+ }
249
+ function readableId(entity) {
250
+ const id = isPlainObject(entity) ? entity["id"] : void 0;
251
+ if ((typeof id !== "string" || id === "") && !(typeof id === "number" && Number.isFinite(id))) throw unreadable("id");
252
+ return String(id);
253
+ }
254
+ function rejectPaginationModifiersWithoutAll(flags, out) {
255
+ if (flags.all) return;
256
+ const offender = flags["max-pages"] !== void 0 ? "--max-pages" : flags["page-delay"] !== void 0 ? "--page-delay" : null;
257
+ if (!offender) return;
258
+ out.stderr.write(`error: ${offender} requires --all; without it, streaming never engages so the flag does nothing.
259
+ `);
260
+ process.exit(2);
261
+ }
262
+ function unreadable(what) {
263
+ return new CurviateError({
264
+ code: "PLATFORM_ERROR",
265
+ message: `The API answered without a readable ${what}.`,
266
+ // The status the client gives every synthesized unreadable-2xx fault.
267
+ httpStatus: 502,
268
+ userFixable: false,
269
+ retryLikelyToSucceed: true
270
+ });
271
+ }
272
+ function truncationProseNote(pagesFetched) {
273
+ return `Streaming truncated at ${pagesFetched} page(s). Use --all --max-pages or --cursor for manual paging.
274
+ `;
275
+ }
276
+ function ndjsonModeNotice() {
277
+ return "--all streams NDJSON: one object per line; the {items,cursor} envelope is not used\n";
278
+ }
279
+ var DEFAULT_PAGE_DELAY_MS = 400;
280
+ function pageDelayFrom(raw) {
281
+ if (raw === void 0 || raw === "") return void 0;
282
+ const n = Number(raw);
283
+ if (!Number.isInteger(n) || n < 0) return void 0;
284
+ return n;
285
+ }
286
+ function pageDelayFromFlags(flags) {
287
+ return pageDelayFrom(flags["page-delay"]);
288
+ }
289
+ var realSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
290
+ function truncationSentinelLine(pagesFetched, hasMore) {
291
+ return JSON.stringify({ object: "stream_truncated", pages_fetched: pagesFetched, has_more: hasMore }) + "\n";
292
+ }
293
+ async function* streamAll(fn, params, opts = {}) {
294
+ const maxPages = opts.maxPages ?? 100;
295
+ const pageDelayMs = opts.pageDelayMs ?? DEFAULT_PAGE_DELAY_MS;
296
+ const sleep = opts.sleep ?? realSleep;
297
+ let cursor = void 0;
298
+ let pageCount = 0;
299
+ let firstPage = true;
300
+ while (true) {
301
+ const pageParams = cursor !== void 0 && cursor !== null ? { ...params, cursor } : params;
302
+ const page = readablePage(await fn(pageParams));
303
+ pageCount++;
304
+ const items = page.items;
305
+ if (firstPage) {
306
+ if (opts.out) opts.out.stderr.write(ndjsonModeNotice());
307
+ firstPage = false;
308
+ }
309
+ if (opts.out) {
310
+ const pageNotices = renderNotices(page.notices);
311
+ if (pageNotices) opts.out.stderr.write(pageNotices + "\n");
312
+ const pageWarning = page.safety_warning;
313
+ if (typeof pageWarning === "object" && pageWarning !== null && !Array.isArray(pageWarning)) {
314
+ opts.out.stderr.write(`safety_warning: ${JSON.stringify(pageWarning)}
315
+ `);
316
+ }
317
+ const pageProvenance = renderProvenanceNote(page);
318
+ if (pageProvenance) opts.out.stderr.write(pageProvenance);
319
+ }
320
+ if (Array.isArray(items)) {
321
+ for (const item of items) {
322
+ yield item;
323
+ }
324
+ }
325
+ cursor = page.cursor;
326
+ if (!cursor) break;
327
+ if (pageCount >= maxPages) {
328
+ const hasMore = cursor !== null && cursor !== void 0;
329
+ if (opts.out) {
330
+ opts.out.stdout.write(truncationSentinelLine(pageCount, hasMore));
331
+ opts.out.stderr.write(truncationProseNote(pageCount));
332
+ }
333
+ if (opts.onTruncated) {
334
+ opts.onTruncated(pageCount, hasMore);
335
+ }
336
+ break;
337
+ }
338
+ if (pageDelayMs > 0) await sleep(pageDelayMs);
339
+ }
340
+ }
341
+
342
+ // src/lib/resolve.ts
343
+ var DEFAULT_BASE_URL = "https://api.curviate.com";
344
+ var DEFAULT_TIMEOUT_MS = 3e4;
345
+ async function resolveEffectiveConfig(flags) {
346
+ const file = await readConfigFile();
347
+ const fromProfile = (field) => profileValue(file, flags.profile, field);
348
+ const profileKey = flags.apiKey === void 0 && process.env["CURVIATE_API_KEY"] === void 0 ? fromProfile("apiKey") : void 0;
349
+ const apiKey = flags.apiKey ?? process.env["CURVIATE_API_KEY"] ?? profileKey;
350
+ const apiKeySource = flags.apiKey !== void 0 ? "flag" : process.env["CURVIATE_API_KEY"] !== void 0 ? "env" : profileKey !== void 0 ? "profile" : "none";
351
+ const baseUrl = flags.baseUrl ?? process.env["CURVIATE_BASE_URL"] ?? fromProfile("baseUrl") ?? DEFAULT_BASE_URL;
352
+ const timeoutFlag = flags.timeout === void 0 ? void 0 : /^[1-9]\d*$/.test(flags.timeout) ? Number(flags.timeout) : NaN;
353
+ const keyAndUrlBypassProfile = apiKeySource !== "profile" && apiKeySource !== "none" && (flags.baseUrl ?? process.env["CURVIATE_BASE_URL"]) !== void 0;
354
+ const profileTimeout = () => {
355
+ try {
356
+ return fromProfile("timeout");
357
+ } catch (err) {
358
+ if (keyAndUrlBypassProfile) return void 0;
359
+ throw err;
360
+ }
361
+ };
362
+ const timeout = timeoutFlag ?? profileTimeout() ?? DEFAULT_TIMEOUT_MS;
363
+ return {
364
+ apiKey,
365
+ baseUrl,
366
+ timeout,
367
+ apiKeySource,
368
+ // Account: flag > env > profile. Read on access: a root-scoped command never
369
+ // takes it, so a broken profile account must not refuse that command.
370
+ get account() {
371
+ return flags.account ?? process.env["CURVIATE_ACCOUNT"] ?? fromProfile("account");
372
+ },
373
+ // Tenant: only meaningful when the key itself came from the profile.
374
+ get tenant() {
375
+ return apiKeySource === "profile" ? fromProfile("tenant") : void 0;
376
+ }
377
+ };
378
+ }
379
+
225
380
  export {
226
- renderProvenanceNote,
381
+ isJsonMode,
227
382
  renderSuccess,
383
+ writeNdjsonItem,
228
384
  renderNotices,
229
385
  renderError,
230
- renderUnexpectedError
386
+ renderUnexpectedError,
387
+ readablePage,
388
+ readableId,
389
+ rejectPaginationModifiersWithoutAll,
390
+ ndjsonModeNotice,
391
+ DEFAULT_PAGE_DELAY_MS,
392
+ pageDelayFromFlags,
393
+ streamAll,
394
+ resolveEffectiveConfig
231
395
  };
@@ -16,26 +16,28 @@ import {
16
16
  normalizeChatId,
17
17
  resolveIdentifier
18
18
  } from "./chunk-UEAX6KUB.js";
19
- import {
20
- buildPreviewOutput
21
- } from "./chunk-R3VLWLVV.js";
22
19
  import {
23
20
  requireAccount
24
- } from "./chunk-V3PB4HSF.js";
21
+ } from "./chunk-MNDXMGPX.js";
22
+ import {
23
+ buildPreviewOutput
24
+ } from "./chunk-TCUYH5GO.js";
25
25
  import {
26
+ readableId,
26
27
  renderError,
27
28
  renderSuccess,
28
- renderUnexpectedError
29
- } from "./chunk-KQXYEQAD.js";
29
+ renderUnexpectedError,
30
+ resolveEffectiveConfig
31
+ } from "./chunk-7JU4IXXG.js";
30
32
  import {
31
33
  createClient,
32
- resolveEffectiveConfig
33
- } from "./chunk-TD2ZIXFR.js";
34
+ downloadBinary
35
+ } from "./chunk-DCZR4M7G.js";
34
36
  import {
35
37
  READ_SINGLE_FLAGS,
36
38
  WRITE_FLAGS,
37
39
  resolveTextOrStdin
38
- } from "./chunk-SKJNLN37.js";
40
+ } from "./chunk-XDQHNUEU.js";
39
41
 
40
42
  // src/commands/message.ts
41
43
  import { defineCommand } from "citty";
@@ -73,9 +75,9 @@ var MEMBER_PROVIDER_ID_RE = /^A[CDE][A-Za-z0-9_-]{4,}$/;
73
75
  async function handleSdkError(err, outOpts, out) {
74
76
  const { CurviateError } = await import("@curviate/sdk");
75
77
  if (err instanceof CurviateError) {
76
- const { getExitCode } = await import("./exit-codes-AAFTOAXF.js");
78
+ const { getExitCode } = await import("./exit-codes-YSFFFWMS.js");
77
79
  renderError(err, outOpts, out);
78
- process.exit(getExitCode(err.code));
80
+ process.exit(getExitCode(err));
79
81
  }
80
82
  renderUnexpectedError(err, out);
81
83
  process.exit(1);
@@ -115,8 +117,7 @@ async function runMessageNew(client, flags, out, _readStdin) {
115
117
  providerId = resolvedSlugOrId;
116
118
  } else {
117
119
  try {
118
- const profileData = await ns.users.get(resolvedSlugOrId, {});
119
- providerId = profileData.id;
120
+ providerId = readableId(await ns.users.get(resolvedSlugOrId, {}));
120
121
  } catch (err) {
121
122
  await handleSdkError(err, outOpts, out);
122
123
  return;
@@ -298,7 +299,7 @@ async function runMessageAttachment(client, flags, out, isTTY) {
298
299
  const attachmentId = flags.attachmentId ?? "";
299
300
  const ns = client.account(accountId);
300
301
  try {
301
- const data = await ns.messaging.getAttachment(chatId, messageId, attachmentId);
302
+ const data = await downloadBinary(() => ns.messaging.getAttachment(chatId, messageId, attachmentId));
302
303
  await writeBinaryOutput(data, {
303
304
  outputPath: flags.output,
304
305
  isTTY,
@@ -334,8 +335,7 @@ async function runMessageInMail(client, flags, out, _readStdin) {
334
335
  recipientUrn = resolvedSlugOrId;
335
336
  } else {
336
337
  try {
337
- const profileData = await ns.users.get(resolvedSlugOrId, {});
338
- recipientUrn = profileData.id;
338
+ recipientUrn = readableId(await ns.users.get(resolvedSlugOrId, {}));
339
339
  } catch (err) {
340
340
  await handleSdkError(err, outOpts, out);
341
341
  return;
@@ -0,0 +1,327 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ assertNoStdinPlaceholder,
4
+ betaOverrideHeader
5
+ } from "./chunk-XDQHNUEU.js";
6
+
7
+ // src/lib/config.ts
8
+ import {
9
+ readFile,
10
+ writeFile,
11
+ mkdir,
12
+ rename,
13
+ chmod,
14
+ unlink
15
+ } from "fs/promises";
16
+ import { join, dirname } from "path";
17
+ import { homedir, tmpdir } from "os";
18
+ import { randomBytes } from "crypto";
19
+ import { CurviateError } from "@curviate/sdk";
20
+ function nullProtoProfiles(profiles) {
21
+ return Object.assign(/* @__PURE__ */ Object.create(null), profiles);
22
+ }
23
+ var PROFILE_FIELD_TYPES = {
24
+ apiKey: "string",
25
+ account: "string",
26
+ baseUrl: "string",
27
+ tenant: "string",
28
+ timeout: "number"
29
+ };
30
+ function isPlainObject(value) {
31
+ return typeof value === "object" && value !== null && !Array.isArray(value);
32
+ }
33
+ function malformed(message) {
34
+ return new CurviateError({ code: "INVALID_REQUEST", message, userFixable: true, retryLikelyToSucceed: false });
35
+ }
36
+ function fileProblem(what) {
37
+ return malformed(`${getConfigPath()} is invalid: ${what}. Edit the file, or run \`curviate config reset\` to start over.`);
38
+ }
39
+ function assertStructure(file, takesActive) {
40
+ if (file.unparseable) throw fileProblem("it is not valid JSON");
41
+ const { root } = file;
42
+ if (!isPlainObject(root)) throw fileProblem("the top level must be an object");
43
+ if (takesActive && root["active"] != null && typeof root["active"] !== "string") throw fileProblem('"active" must be a string');
44
+ if (root["profiles"] != null && !isPlainObject(root["profiles"])) throw fileProblem('"profiles" must be an object');
45
+ }
46
+ function profileRepair(name) {
47
+ return `Run \`curviate config reset --profile ${name}\`, or edit the file.`;
48
+ }
49
+ async function readConfigFile() {
50
+ let raw;
51
+ try {
52
+ raw = await readFile(getConfigPath(), "utf8");
53
+ } catch (err) {
54
+ if (err.code === "ENOENT") return null;
55
+ throw err;
56
+ }
57
+ try {
58
+ return { root: JSON.parse(raw.replace(/^\uFEFF/, "")) };
59
+ } catch {
60
+ return { root: void 0, unparseable: true };
61
+ }
62
+ }
63
+ function profileValue(file, selected, field) {
64
+ if (file === null) return void 0;
65
+ assertStructure(file, selected === void 0);
66
+ const { root } = file;
67
+ const name = selected ?? root["active"] ?? "default";
68
+ const profiles = root["profiles"];
69
+ if (profiles == null) return void 0;
70
+ const profile = Object.prototype.hasOwnProperty.call(profiles, name) ? profiles[name] : void 0;
71
+ if (profile == null) return void 0;
72
+ const where = `Profile ${JSON.stringify(name)} in ${getConfigPath()}`;
73
+ if (!isPlainObject(profile)) throw malformed(`${where} is not an object. ${profileRepair(name)}`);
74
+ const value = profile[field];
75
+ if (value == null) return void 0;
76
+ const want = PROFILE_FIELD_TYPES[field];
77
+ if (typeof value !== want) throw malformed(`${where} is invalid: ${field} must be a ${want}. ${profileRepair(name)}`);
78
+ return value;
79
+ }
80
+ function getConfigPath() {
81
+ const xdg = process.env["XDG_CONFIG_HOME"] ?? (process.env["APPDATA"] ?? join(homedir(), ".config"));
82
+ return join(xdg, "curviate", "config.json");
83
+ }
84
+ async function readConfig() {
85
+ const file = await readConfigFile();
86
+ if (file === null) return null;
87
+ assertStructure(file, true);
88
+ const { root } = file;
89
+ const profiles = root["profiles"] ?? {};
90
+ const active = root["active"] ?? "default";
91
+ return { ...root, active, profiles: nullProtoProfiles(profiles) };
92
+ }
93
+ async function writeConfig(cfg) {
94
+ const cfgPath = getConfigPath();
95
+ const cfgDir = dirname(cfgPath);
96
+ await mkdir(cfgDir, { recursive: true, mode: 448 });
97
+ try {
98
+ await chmod(cfgDir, 448);
99
+ } catch {
100
+ }
101
+ const content = JSON.stringify(cfg, null, 2) + "\n";
102
+ assertNoStdinPlaceholder("the configuration about to be written", [content]);
103
+ const tmpPath = join(
104
+ tmpdir(),
105
+ `curviate-cfg-${randomBytes(6).toString("hex")}.tmp`
106
+ );
107
+ try {
108
+ await writeFile(tmpPath, content, { encoding: "utf8", mode: 384 });
109
+ try {
110
+ await chmod(tmpPath, 384);
111
+ } catch {
112
+ }
113
+ await rename(tmpPath, cfgPath);
114
+ try {
115
+ await chmod(cfgPath, 384);
116
+ } catch {
117
+ }
118
+ } catch (err) {
119
+ try {
120
+ await unlink(tmpPath);
121
+ } catch {
122
+ }
123
+ throw err;
124
+ }
125
+ }
126
+ async function writeProfile(profileName, entry) {
127
+ const existing = await readConfig() ?? {
128
+ active: profileName,
129
+ profiles: nullProtoProfiles({})
130
+ };
131
+ const stored = existing.profiles[profileName];
132
+ const current = isPlainObject(stored) ? stored : {};
133
+ existing.profiles[profileName] = { ...current, ...entry };
134
+ if (!existing.active) {
135
+ existing.active = profileName;
136
+ }
137
+ await writeConfig(existing);
138
+ }
139
+ async function setActiveProfile(profileName) {
140
+ const cfg = await readConfig();
141
+ if (!cfg || !cfg.profiles[profileName]) {
142
+ throw new Error(`Profile "${profileName}" not found.`);
143
+ }
144
+ cfg.active = profileName;
145
+ await writeConfig(cfg);
146
+ }
147
+ async function renameProfile(oldName, newName) {
148
+ const cfg = await readConfig();
149
+ if (!cfg || !cfg.profiles[oldName]) {
150
+ throw new Error(`Profile "${oldName}" not found.`);
151
+ }
152
+ if (cfg.profiles[newName]) {
153
+ throw new Error(
154
+ `Profile "${newName}" already exists. Remove it first or choose another name.`
155
+ );
156
+ }
157
+ cfg.profiles[newName] = cfg.profiles[oldName];
158
+ delete cfg.profiles[oldName];
159
+ if (cfg.active === oldName) {
160
+ cfg.active = newName;
161
+ }
162
+ await writeConfig(cfg);
163
+ }
164
+ async function removeProfile(profileName) {
165
+ const cfg = await readConfig();
166
+ if (!cfg) return;
167
+ delete cfg.profiles[profileName];
168
+ if (cfg.active === profileName) {
169
+ cfg.active = "default";
170
+ }
171
+ await writeConfig(cfg);
172
+ }
173
+ async function updateProfileField(profileName, field, value) {
174
+ const cfg = await readConfig();
175
+ const stored = cfg?.profiles[profileName];
176
+ if (!cfg || stored == null) {
177
+ throw new Error(`Profile "${profileName}" not found.`);
178
+ }
179
+ const profile = isPlainObject(stored) ? stored : {};
180
+ cfg.profiles[profileName] = profile;
181
+ if (field === "timeout") {
182
+ profile.timeout = typeof value === "number" ? value : value !== void 0 ? Number(value) : void 0;
183
+ } else if (field === "apiKey") {
184
+ profile.apiKey = value !== void 0 ? String(value) : void 0;
185
+ } else if (field === "account") {
186
+ profile.account = value !== void 0 ? String(value) : void 0;
187
+ } else if (field === "baseUrl") {
188
+ profile.baseUrl = value !== void 0 ? String(value) : void 0;
189
+ } else if (field === "tenant") {
190
+ profile.tenant = value !== void 0 ? String(value) : void 0;
191
+ }
192
+ await writeConfig(cfg);
193
+ }
194
+
195
+ // src/lib/client.ts
196
+ import { AsyncLocalStorage } from "async_hooks";
197
+ import { Curviate, CurviateError as CurviateError2 } from "@curviate/sdk";
198
+ function headerStrings(headers) {
199
+ if (!headers) return [];
200
+ if (headers instanceof Headers) {
201
+ const out = [];
202
+ headers.forEach((value, key) => out.push(key, value));
203
+ return out;
204
+ }
205
+ if (Array.isArray(headers)) return headers.flat().map(String);
206
+ return Object.entries(headers).flat().map(String);
207
+ }
208
+ var guardedFetch = async (input, init) => {
209
+ const beta = betaOverrideHeader();
210
+ let merged = init;
211
+ if (Object.keys(beta).length > 0) {
212
+ const headers = new Headers(init?.headers);
213
+ for (const [name, value] of Object.entries(beta)) headers.set(name, value);
214
+ merged = { ...init, headers };
215
+ }
216
+ assertNoStdinPlaceholder("the request about to be sent", [
217
+ String(input instanceof Request ? input.url : input),
218
+ ...headerStrings(merged?.headers),
219
+ typeof merged?.body === "string" ? merged.body : void 0
220
+ ]);
221
+ const res = await fetch(input, merged);
222
+ return downloading.getStore() && res.ok ? asOpaqueBytes(res) : platformFaultIfUnreadable(res);
223
+ };
224
+ var downloading = new AsyncLocalStorage();
225
+ function downloadBinary(call) {
226
+ return downloading.run(true, call);
227
+ }
228
+ function asOpaqueBytes(res) {
229
+ const headers = new Headers(res.headers);
230
+ headers.set("content-type", "application/octet-stream");
231
+ return new Response(res.body, { status: res.status, statusText: res.statusText, headers });
232
+ }
233
+ async function platformFaultIfUnreadable(res) {
234
+ const text = res.status === 204 ? "" : await res.clone().text();
235
+ let parsed = true;
236
+ let env = null;
237
+ try {
238
+ env = JSON.parse(text);
239
+ } catch {
240
+ parsed = false;
241
+ }
242
+ if (res.status >= 500) {
243
+ if (typeof env?.code === "string") return res;
244
+ } else if (!res.ok || parsed) {
245
+ return res;
246
+ } else if (text === "") {
247
+ const headers2 = new Headers(res.headers);
248
+ headers2.delete("content-type");
249
+ return new Response(null, { status: res.status, statusText: res.statusText, headers: headers2 });
250
+ }
251
+ const headers = new Headers(res.headers);
252
+ headers.set("content-type", "application/json");
253
+ headers.delete("content-length");
254
+ headers.delete("content-encoding");
255
+ return new Response(
256
+ JSON.stringify({
257
+ code: "PLATFORM_ERROR",
258
+ message: `The API answered ${res.status} without a readable body.`,
259
+ user_fixable: false,
260
+ retry_likely_to_succeed: true
261
+ }),
262
+ // A 2xx has to become an error status for the SDK to decode it as one.
263
+ { status: res.status >= 500 ? res.status : 502, statusText: res.statusText, headers }
264
+ );
265
+ }
266
+ function usage(message) {
267
+ return new CurviateError2({ code: "INVALID_REQUEST", message, userFixable: true, retryLikelyToSucceed: false });
268
+ }
269
+ function baseUrlProblem(baseUrl) {
270
+ let url;
271
+ try {
272
+ url = new URL(baseUrl);
273
+ } catch {
274
+ url = void 0;
275
+ }
276
+ if (url && (url.username !== "" || url.password !== "")) {
277
+ return "Invalid base URL: it must not carry a user name or password (`user:pass@`). Check --base-url, CURVIATE_BASE_URL, or the profile's baseUrl.";
278
+ }
279
+ return url?.protocol === "http:" || url?.protocol === "https:" ? null : "Invalid base URL: expected an absolute http:// or https:// URL. Check --base-url, CURVIATE_BASE_URL, or the profile's baseUrl.";
280
+ }
281
+ function withoutUserinfo(baseUrl) {
282
+ try {
283
+ const url = new URL(baseUrl);
284
+ if (url.username === "" && url.password === "") return baseUrl;
285
+ url.username = "";
286
+ url.password = "";
287
+ return url.href;
288
+ } catch {
289
+ return baseUrl;
290
+ }
291
+ }
292
+ var MAX_TIMEOUT_MS = 2147483647;
293
+ function createClient(config) {
294
+ const badUrl = config.baseUrl === void 0 ? null : baseUrlProblem(config.baseUrl);
295
+ if (badUrl) throw usage(badUrl);
296
+ const t = config.timeout;
297
+ if (t !== void 0 && !(Number.isInteger(t) && t > 0 && t <= MAX_TIMEOUT_MS)) {
298
+ throw usage(
299
+ `Invalid timeout: expected a whole number of milliseconds from 1 to ${MAX_TIMEOUT_MS}. Check --timeout or the profile's timeout.`
300
+ );
301
+ }
302
+ return new Curviate({
303
+ apiKey: config.apiKey.trim(),
304
+ fetch: guardedFetch,
305
+ ...config.baseUrl !== void 0 ? { baseUrl: config.baseUrl } : {},
306
+ ...config.timeout !== void 0 ? { timeout: config.timeout } : {}
307
+ });
308
+ }
309
+
310
+ export {
311
+ PROFILE_FIELD_TYPES,
312
+ isPlainObject,
313
+ assertStructure,
314
+ readConfigFile,
315
+ profileValue,
316
+ getConfigPath,
317
+ readConfig,
318
+ writeProfile,
319
+ setActiveProfile,
320
+ renameProfile,
321
+ removeProfile,
322
+ updateProfileField,
323
+ downloadBinary,
324
+ baseUrlProblem,
325
+ withoutUserinfo,
326
+ createClient
327
+ };