@captapi/sdk 0.1.0 → 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/README.md CHANGED
Binary file
package/dist/core.d.ts CHANGED
@@ -29,5 +29,13 @@ export declare class HttpCore {
29
29
  private readonly timeoutMs;
30
30
  private readonly fetchImpl;
31
31
  constructor(options?: CaptapiOptions);
32
+ private fail;
33
+ private parseBody;
34
+ private send;
32
35
  get(path: string, params?: object): Promise<ApiEnvelope>;
36
+ /**
37
+ * POST multipart/form-data. ``file`` may be a local path (Node), Blob, or File.
38
+ * Other params become additional form fields.
39
+ */
40
+ postMultipart(path: string, params?: object): Promise<ApiEnvelope>;
33
41
  }
package/dist/core.js CHANGED
@@ -13,6 +13,21 @@ export class CaptapiError extends Error {
13
13
  this.detail = detail;
14
14
  }
15
15
  }
16
+ const RETRY_STATUSES = new Set([502, 503]);
17
+ const RETRY_DELAY_MS = 500;
18
+ function shouldRetry(status, body) {
19
+ if (!RETRY_STATUSES.has(status))
20
+ return false;
21
+ const bag = body && typeof body === "object" && "detail" in body
22
+ ? body.detail
23
+ : body;
24
+ if (bag && typeof bag === "object") {
25
+ const flags = bag;
26
+ if (flags.persistent === true || flags.replayed === true)
27
+ return false;
28
+ }
29
+ return true;
30
+ }
16
31
  export class HttpCore {
17
32
  apiKey;
18
33
  baseUrl;
@@ -29,39 +44,91 @@ export class HttpCore {
29
44
  this.timeoutMs = options.timeoutMs ?? 120_000;
30
45
  this.fetchImpl = options.fetch ?? globalThis.fetch;
31
46
  }
47
+ fail(path, status, body) {
48
+ const detail = body?.detail ?? body?.error ?? body;
49
+ const code = typeof body?.detail === "object" && body?.detail?.error
50
+ ? String(body.detail.error)
51
+ : typeof body?.error === "string"
52
+ ? body.error
53
+ : undefined;
54
+ return new CaptapiError(`Captapi ${path} returned ${status}: ${typeof detail === "string" ? detail : JSON.stringify(detail ?? "unknown error")}`, status, code, detail);
55
+ }
56
+ async parseBody(res) {
57
+ try {
58
+ return await res.json();
59
+ }
60
+ catch {
61
+ return undefined;
62
+ }
63
+ }
64
+ async send(path, init) {
65
+ let last;
66
+ for (let attempt = 0; attempt < 2; attempt++) {
67
+ let res;
68
+ try {
69
+ res = await this.fetchImpl(this.baseUrl + path, {
70
+ ...init,
71
+ headers: {
72
+ authorization: `Bearer ${this.apiKey}`,
73
+ accept: "application/json",
74
+ ...(init.headers ?? {}),
75
+ },
76
+ signal: AbortSignal.timeout(this.timeoutMs),
77
+ });
78
+ }
79
+ catch (err) {
80
+ const message = err instanceof Error ? err.message : String(err);
81
+ throw new CaptapiError(`Request to ${path} failed: ${message}`, 0, "network_error", err);
82
+ }
83
+ const body = await this.parseBody(res);
84
+ if (res.ok && body?.success !== false)
85
+ return body;
86
+ last = this.fail(path, res.status, body);
87
+ if (attempt === 0 && shouldRetry(res.status, body)) {
88
+ await new Promise((r) => setTimeout(r, RETRY_DELAY_MS));
89
+ continue;
90
+ }
91
+ throw last;
92
+ }
93
+ throw last ?? new CaptapiError(`Request to ${path} failed`, 0, "network_error");
94
+ }
32
95
  async get(path, params = {}) {
33
96
  const url = new URL(this.baseUrl + path);
34
97
  for (const [k, v] of Object.entries(params)) {
35
98
  if (v !== undefined && v !== null)
36
99
  url.searchParams.set(k, String(v));
37
100
  }
38
- let res;
39
- try {
40
- res = await this.fetchImpl(url, {
41
- headers: { authorization: `Bearer ${this.apiKey}`, accept: "application/json" },
42
- signal: AbortSignal.timeout(this.timeoutMs),
43
- });
101
+ return this.send(url.pathname + url.search, { method: "GET" });
102
+ }
103
+ /**
104
+ * POST multipart/form-data. ``file`` may be a local path (Node), Blob, or File.
105
+ * Other params become additional form fields.
106
+ */
107
+ async postMultipart(path, params = {}) {
108
+ const form = new FormData();
109
+ const entries = params;
110
+ const fileVal = entries.file;
111
+ if (fileVal == null) {
112
+ throw new CaptapiError("Missing required form field: file", 400, "missing_file");
44
113
  }
45
- catch (err) {
46
- const message = err instanceof Error ? err.message : String(err);
47
- throw new CaptapiError(`Request to ${path} failed: ${message}`, 0, "network_error", err);
114
+ if (typeof fileVal === "string") {
115
+ // Node: treat string as a filesystem path.
116
+ const fs = await import("node:fs");
117
+ const pathMod = await import("node:path");
118
+ const buf = fs.readFileSync(fileVal);
119
+ form.append("file", new Blob([buf]), pathMod.basename(fileVal));
48
120
  }
49
- let body;
50
- try {
51
- body = await res.json();
121
+ else if (typeof Blob !== "undefined" && fileVal instanceof Blob) {
122
+ form.append("file", fileVal, fileVal.name || "upload.bin");
52
123
  }
53
- catch {
54
- body = undefined;
124
+ else {
125
+ form.append("file", fileVal);
55
126
  }
56
- if (!res.ok || body?.success === false) {
57
- const detail = body?.detail ?? body?.error ?? body;
58
- const code = typeof body?.detail === "object" && body?.detail?.error
59
- ? String(body.detail.error)
60
- : typeof body?.error === "string"
61
- ? body.error
62
- : undefined;
63
- throw new CaptapiError(`Captapi ${path} returned ${res.status}: ${typeof detail === "string" ? detail : JSON.stringify(detail ?? "unknown error")}`, res.status, code, detail);
127
+ for (const [k, v] of Object.entries(entries)) {
128
+ if (k === "file" || v === undefined || v === null)
129
+ continue;
130
+ form.append(k, String(v));
64
131
  }
65
- return body;
132
+ return this.send(path, { method: "POST", body: form });
66
133
  }
67
134
  }