@prompt-helm/sdk 0.2.0 → 1.1.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/LICENSE +1 -1
- package/README.md +82 -152
- package/dist/cli.js +146 -0
- package/dist/index.cjs +140 -552
- package/dist/index.d.cts +47 -111
- package/dist/index.d.ts +47 -111
- package/dist/index.js +112 -545
- package/package.json +38 -54
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,579 +1,167 @@
|
|
|
1
|
-
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
2
19
|
|
|
3
|
-
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
PromptHelm: () => PromptHelm,
|
|
24
|
+
PromptHelmError: () => PromptHelmError,
|
|
25
|
+
extractVariables: () => extractVariables,
|
|
26
|
+
render: () => render
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(index_exports);
|
|
4
29
|
|
|
5
30
|
// src/errors.ts
|
|
6
31
|
var PromptHelmError = class extends Error {
|
|
7
|
-
|
|
8
|
-
statusCode;
|
|
9
|
-
/** Machine-readable error code from the API envelope, e.g. `VALIDATION_ERROR`. */
|
|
10
|
-
errorCode;
|
|
11
|
-
/** Request correlation id — quote this when contacting PromptHelm support. */
|
|
12
|
-
requestId;
|
|
13
|
-
constructor(statusCode, errorCode, requestId, message) {
|
|
32
|
+
constructor(code, message, status) {
|
|
14
33
|
super(message);
|
|
15
|
-
this.
|
|
16
|
-
this.
|
|
17
|
-
this.errorCode = errorCode;
|
|
18
|
-
this.requestId = requestId;
|
|
19
|
-
}
|
|
20
|
-
};
|
|
21
|
-
var AuthenticationError = class extends PromptHelmError {
|
|
22
|
-
constructor(statusCode, errorCode, requestId, message) {
|
|
23
|
-
super(statusCode, errorCode, requestId, message);
|
|
24
|
-
this.name = "AuthenticationError";
|
|
25
|
-
}
|
|
26
|
-
};
|
|
27
|
-
var AuthorizationError = class extends PromptHelmError {
|
|
28
|
-
constructor(statusCode, errorCode, requestId, message) {
|
|
29
|
-
super(statusCode, errorCode, requestId, message);
|
|
30
|
-
this.name = "AuthorizationError";
|
|
31
|
-
}
|
|
32
|
-
};
|
|
33
|
-
var RateLimitError = class extends PromptHelmError {
|
|
34
|
-
constructor(statusCode, errorCode, requestId, message) {
|
|
35
|
-
super(statusCode, errorCode, requestId, message);
|
|
36
|
-
this.name = "RateLimitError";
|
|
37
|
-
}
|
|
38
|
-
};
|
|
39
|
-
var NotFoundError = class extends PromptHelmError {
|
|
40
|
-
constructor(statusCode, errorCode, requestId, message) {
|
|
41
|
-
super(statusCode, errorCode, requestId, message);
|
|
42
|
-
this.name = "NotFoundError";
|
|
43
|
-
}
|
|
44
|
-
};
|
|
45
|
-
var ApiError = class extends PromptHelmError {
|
|
46
|
-
constructor(statusCode, errorCode, requestId, message) {
|
|
47
|
-
super(statusCode, errorCode, requestId, message);
|
|
48
|
-
this.name = "ApiError";
|
|
49
|
-
}
|
|
50
|
-
};
|
|
51
|
-
var TimeoutError = class extends Error {
|
|
52
|
-
timeoutMs;
|
|
53
|
-
constructor(timeoutMs, message) {
|
|
54
|
-
super(message ?? `Request timed out after ${String(timeoutMs)}ms`);
|
|
55
|
-
this.name = "TimeoutError";
|
|
56
|
-
this.timeoutMs = timeoutMs;
|
|
34
|
+
this.code = code;
|
|
35
|
+
this.status = status;
|
|
57
36
|
}
|
|
37
|
+
code;
|
|
38
|
+
status;
|
|
39
|
+
name = "PromptHelmError";
|
|
58
40
|
};
|
|
59
|
-
function fallbackMessage(status) {
|
|
60
|
-
if (status === 401) {
|
|
61
|
-
return "Authentication failed. Check that your API key is valid and not revoked.";
|
|
62
|
-
}
|
|
63
|
-
if (status === 403) {
|
|
64
|
-
return "You do not have permission to perform this action.";
|
|
65
|
-
}
|
|
66
|
-
if (status === 404) {
|
|
67
|
-
return "The requested prompt or resource was not found.";
|
|
68
|
-
}
|
|
69
|
-
if (status === 429) {
|
|
70
|
-
return "Rate limit exceeded. Slow down requests or upgrade your plan.";
|
|
71
|
-
}
|
|
72
|
-
if (status >= 500) {
|
|
73
|
-
return "PromptHelm encountered an internal error. The request can be retried.";
|
|
74
|
-
}
|
|
75
|
-
return `Request failed with status ${String(status)}.`;
|
|
76
|
-
}
|
|
77
|
-
function normalizeMessage(message) {
|
|
78
|
-
return Array.isArray(message) ? message.join("; ") : message;
|
|
79
|
-
}
|
|
80
|
-
function parseErrorResponse(status, body) {
|
|
81
|
-
const envelope = isErrorEnvelope(body) ? body : null;
|
|
82
|
-
const message = envelope ? normalizeMessage(envelope.message) : fallbackMessage(status);
|
|
83
|
-
const errorCode = envelope?.errorCode;
|
|
84
|
-
const requestId = envelope?.requestId;
|
|
85
|
-
const statusCode = envelope?.statusCode ?? status;
|
|
86
|
-
if (statusCode === 401) {
|
|
87
|
-
return new AuthenticationError(statusCode, errorCode, requestId, message);
|
|
88
|
-
}
|
|
89
|
-
if (statusCode === 403) {
|
|
90
|
-
return new AuthorizationError(statusCode, errorCode, requestId, message);
|
|
91
|
-
}
|
|
92
|
-
if (statusCode === 404) {
|
|
93
|
-
return new NotFoundError(statusCode, errorCode, requestId, message);
|
|
94
|
-
}
|
|
95
|
-
if (statusCode === 429) {
|
|
96
|
-
return new RateLimitError(statusCode, errorCode, requestId, message);
|
|
97
|
-
}
|
|
98
|
-
return new ApiError(statusCode, errorCode, requestId, message);
|
|
99
|
-
}
|
|
100
|
-
function isErrorEnvelope(value) {
|
|
101
|
-
if (typeof value !== "object" || value === null) {
|
|
102
|
-
return false;
|
|
103
|
-
}
|
|
104
|
-
const record = value;
|
|
105
|
-
const message = record["message"];
|
|
106
|
-
const messageOk = typeof message === "string" || Array.isArray(message) && message.every((item) => typeof item === "string");
|
|
107
|
-
return typeof record["statusCode"] === "number" && typeof record["errorCode"] === "string" && messageOk;
|
|
108
|
-
}
|
|
109
41
|
|
|
110
|
-
// src/
|
|
111
|
-
var
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const jitter = Math.floor(random() * 100);
|
|
119
|
-
return Math.min(exponential + jitter, maxDelayMs);
|
|
42
|
+
// src/template.ts
|
|
43
|
+
var VARIABLE = /\{\{\s*([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g;
|
|
44
|
+
function extractVariables(template) {
|
|
45
|
+
const names = /* @__PURE__ */ new Set();
|
|
46
|
+
for (const match of template.matchAll(VARIABLE)) {
|
|
47
|
+
names.add(match[1]);
|
|
48
|
+
}
|
|
49
|
+
return [...names];
|
|
120
50
|
}
|
|
121
|
-
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
const random = opts.random ?? Math.random;
|
|
126
|
-
let attempt = 0;
|
|
127
|
-
while (true) {
|
|
128
|
-
try {
|
|
129
|
-
return await fn();
|
|
130
|
-
} catch (err) {
|
|
131
|
-
if (attempt >= opts.maxRetries || !opts.isRetryable(err)) {
|
|
132
|
-
throw err;
|
|
133
|
-
}
|
|
134
|
-
const delay = computeBackoff(attempt, baseDelayMs, maxDelayMs, random);
|
|
135
|
-
await sleep(delay);
|
|
136
|
-
attempt += 1;
|
|
137
|
-
}
|
|
51
|
+
function render(template, vars = {}) {
|
|
52
|
+
const missing = extractVariables(template).filter((name) => !Object.hasOwn(vars, name));
|
|
53
|
+
if (missing.length > 0) {
|
|
54
|
+
throw new PromptHelmError("missing_variables", `Missing variables: ${missing.join(", ")}`);
|
|
138
55
|
}
|
|
56
|
+
return template.replace(VARIABLE, (_, name) => String(vars[name]));
|
|
139
57
|
}
|
|
140
58
|
|
|
141
|
-
// src/stream.ts
|
|
142
|
-
var SseParser = class {
|
|
143
|
-
buffer = "";
|
|
144
|
-
dataLines = [];
|
|
145
|
-
feed(chunk) {
|
|
146
|
-
this.buffer += chunk;
|
|
147
|
-
const frames = [];
|
|
148
|
-
let newlineIndex = this.indexOfLineEnd(this.buffer);
|
|
149
|
-
while (newlineIndex.index !== -1) {
|
|
150
|
-
const line = this.buffer.slice(0, newlineIndex.index);
|
|
151
|
-
this.buffer = this.buffer.slice(newlineIndex.index + newlineIndex.length);
|
|
152
|
-
if (line === "") {
|
|
153
|
-
if (this.dataLines.length > 0) {
|
|
154
|
-
frames.push({ data: this.dataLines.join("\n") });
|
|
155
|
-
this.dataLines = [];
|
|
156
|
-
}
|
|
157
|
-
} else if (!line.startsWith(":")) {
|
|
158
|
-
const colonIndex = line.indexOf(":");
|
|
159
|
-
let field;
|
|
160
|
-
let value;
|
|
161
|
-
if (colonIndex === -1) {
|
|
162
|
-
field = line;
|
|
163
|
-
value = "";
|
|
164
|
-
} else {
|
|
165
|
-
field = line.slice(0, colonIndex);
|
|
166
|
-
value = line.slice(colonIndex + 1);
|
|
167
|
-
if (value.startsWith(" ")) {
|
|
168
|
-
value = value.slice(1);
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
if (field === "data") {
|
|
172
|
-
this.dataLines.push(value);
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
newlineIndex = this.indexOfLineEnd(this.buffer);
|
|
176
|
-
}
|
|
177
|
-
return frames;
|
|
178
|
-
}
|
|
179
|
-
flush() {
|
|
180
|
-
if (this.dataLines.length === 0) {
|
|
181
|
-
return [];
|
|
182
|
-
}
|
|
183
|
-
const frame = { data: this.dataLines.join("\n") };
|
|
184
|
-
this.dataLines = [];
|
|
185
|
-
return [frame];
|
|
186
|
-
}
|
|
187
|
-
indexOfLineEnd(input) {
|
|
188
|
-
const crlf = input.indexOf("\r\n");
|
|
189
|
-
const lf = input.indexOf("\n");
|
|
190
|
-
const cr = input.indexOf("\r");
|
|
191
|
-
if (crlf !== -1 && (lf === -1 || crlf <= lf) && (cr === -1 || crlf <= cr)) {
|
|
192
|
-
return { index: crlf, length: 2 };
|
|
193
|
-
}
|
|
194
|
-
if (lf !== -1 && (cr === -1 || lf < cr)) {
|
|
195
|
-
return { index: lf, length: 1 };
|
|
196
|
-
}
|
|
197
|
-
if (cr !== -1) {
|
|
198
|
-
return { index: cr, length: 1 };
|
|
199
|
-
}
|
|
200
|
-
return { index: -1, length: 0 };
|
|
201
|
-
}
|
|
202
|
-
};
|
|
203
|
-
function parseStreamEvent(data) {
|
|
204
|
-
const trimmed = data.trim();
|
|
205
|
-
if (trimmed === "" || trimmed === "[DONE]") {
|
|
206
|
-
return null;
|
|
207
|
-
}
|
|
208
|
-
let parsed;
|
|
209
|
-
try {
|
|
210
|
-
parsed = JSON.parse(trimmed);
|
|
211
|
-
} catch {
|
|
212
|
-
return null;
|
|
213
|
-
}
|
|
214
|
-
if (!isStreamEvent(parsed)) {
|
|
215
|
-
return null;
|
|
216
|
-
}
|
|
217
|
-
return parsed;
|
|
218
|
-
}
|
|
219
|
-
function isStreamEvent(value) {
|
|
220
|
-
if (typeof value !== "object" || value === null) {
|
|
221
|
-
return false;
|
|
222
|
-
}
|
|
223
|
-
const record = value;
|
|
224
|
-
const type = record["type"];
|
|
225
|
-
if (type === "chunk") {
|
|
226
|
-
return typeof record["content"] === "string";
|
|
227
|
-
}
|
|
228
|
-
if (type === "done") {
|
|
229
|
-
return typeof record["inputTokens"] === "number" && typeof record["outputTokens"] === "number" && typeof record["totalTokens"] === "number" && typeof record["cost"] === "number" && typeof record["model"] === "string" && typeof record["latencyMs"] === "number";
|
|
230
|
-
}
|
|
231
|
-
if (type === "error") {
|
|
232
|
-
return typeof record["errorCode"] === "string" && typeof record["message"] === "string";
|
|
233
|
-
}
|
|
234
|
-
return false;
|
|
235
|
-
}
|
|
236
|
-
async function* readSseStream(body, signal) {
|
|
237
|
-
const reader = body.getReader();
|
|
238
|
-
const decoder = new TextDecoder("utf-8");
|
|
239
|
-
const parser = new SseParser();
|
|
240
|
-
const abortListener = () => {
|
|
241
|
-
void reader.cancel().catch(() => {
|
|
242
|
-
});
|
|
243
|
-
};
|
|
244
|
-
if (signal) {
|
|
245
|
-
if (signal.aborted) {
|
|
246
|
-
await reader.cancel().catch(() => void 0);
|
|
247
|
-
return;
|
|
248
|
-
}
|
|
249
|
-
signal.addEventListener("abort", abortListener, { once: true });
|
|
250
|
-
}
|
|
251
|
-
try {
|
|
252
|
-
while (true) {
|
|
253
|
-
const { value, done } = await reader.read();
|
|
254
|
-
if (done) {
|
|
255
|
-
const tail = parser.flush();
|
|
256
|
-
for (const frame of tail) {
|
|
257
|
-
const event = parseStreamEvent(frame.data);
|
|
258
|
-
if (event) {
|
|
259
|
-
yield event;
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
return;
|
|
263
|
-
}
|
|
264
|
-
const text = decoder.decode(value, { stream: true });
|
|
265
|
-
const frames = parser.feed(text);
|
|
266
|
-
for (const frame of frames) {
|
|
267
|
-
const event = parseStreamEvent(frame.data);
|
|
268
|
-
if (event) {
|
|
269
|
-
yield event;
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
if (signal?.aborted) {
|
|
273
|
-
return;
|
|
274
|
-
}
|
|
275
|
-
}
|
|
276
|
-
} finally {
|
|
277
|
-
if (signal) {
|
|
278
|
-
signal.removeEventListener("abort", abortListener);
|
|
279
|
-
}
|
|
280
|
-
reader.releaseLock();
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
var SDK_VERSION = "0.2.0" ;
|
|
284
|
-
var SDK_USER_AGENT = `prompt-helm-sdk-node/${SDK_VERSION}`;
|
|
285
|
-
|
|
286
59
|
// src/client.ts
|
|
287
|
-
var DEFAULT_BASE_URL = "https://
|
|
288
|
-
var DEFAULT_TIMEOUT_MS = 6e4;
|
|
289
|
-
var DEFAULT_MAX_RETRIES = 2;
|
|
290
|
-
var API_KEY_LENGTH = 36;
|
|
291
|
-
var API_KEY_PREFIX = "phk_";
|
|
292
|
-
var SDK_UA = SDK_USER_AGENT;
|
|
60
|
+
var DEFAULT_BASE_URL = "https://prompthelm.app";
|
|
293
61
|
var PromptHelm = class {
|
|
294
|
-
apiKey;
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
62
|
+
#apiKey;
|
|
63
|
+
#baseUrl;
|
|
64
|
+
#ttl;
|
|
65
|
+
#timeout;
|
|
66
|
+
#fetch;
|
|
67
|
+
#onError;
|
|
68
|
+
#cache = /* @__PURE__ */ new Map();
|
|
69
|
+
#inflight = /* @__PURE__ */ new Map();
|
|
70
|
+
constructor(options = {}) {
|
|
71
|
+
const apiKey = options.apiKey ?? env("PROMPTHELM_API_KEY");
|
|
72
|
+
if (!apiKey) throw new Error("PromptHelm: pass apiKey or set PROMPTHELM_API_KEY");
|
|
73
|
+
this.#apiKey = apiKey;
|
|
74
|
+
const baseUrl = options.baseUrl ?? env("PROMPTHELM_BASE_URL") ?? DEFAULT_BASE_URL;
|
|
75
|
+
this.#baseUrl = baseUrl.replace(/\/+$/, "");
|
|
76
|
+
this.#ttl = options.ttl ?? 6e4;
|
|
77
|
+
this.#timeout = options.timeout ?? 3e3;
|
|
78
|
+
this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
79
|
+
this.#onError = options.onError ?? ((error, slug) => console.warn(`[PromptHelm] ${slug}: ${error.message}`));
|
|
80
|
+
}
|
|
81
|
+
/** The live version of a prompt with its variables filled in. */
|
|
82
|
+
async get(slug, options = {}) {
|
|
83
|
+
const { vars, fallback } = options;
|
|
84
|
+
try {
|
|
85
|
+
const entry = await this.#entry(slug);
|
|
86
|
+
return render(entry.content, vars);
|
|
87
|
+
} catch (error) {
|
|
88
|
+
const failure = toPromptHelmError(error);
|
|
89
|
+
if (fallback === void 0) throw failure;
|
|
90
|
+
this.#onError(failure, slug);
|
|
91
|
+
return render(fallback, vars);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
#entry(slug) {
|
|
95
|
+
const cached = this.#cache.get(slug);
|
|
96
|
+
if (!cached) return this.#load(slug);
|
|
97
|
+
if (Date.now() - cached.fetchedAt >= this.#ttl) {
|
|
98
|
+
this.#load(slug).catch((error) => {
|
|
99
|
+
cached.fetchedAt = Date.now();
|
|
100
|
+
this.#onError(toPromptHelmError(error), slug);
|
|
101
|
+
});
|
|
329
102
|
}
|
|
330
|
-
|
|
331
|
-
this.baseURL = baseURL.replace(/\/+$/, "");
|
|
332
|
-
this.timeout = timeout;
|
|
333
|
-
this.maxRetries = maxRetries;
|
|
334
|
-
this.fetchFn = fetchImpl;
|
|
335
|
-
this.extraHeaders = config.headers ?? {};
|
|
336
|
-
this.userAgent = config.userAgent ? `${config.userAgent} ${SDK_UA}` : SDK_UA;
|
|
103
|
+
return Promise.resolve(cached);
|
|
337
104
|
}
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
);
|
|
105
|
+
#load(slug) {
|
|
106
|
+
let pending = this.#inflight.get(slug);
|
|
107
|
+
if (!pending) {
|
|
108
|
+
pending = this.#request(slug).finally(() => this.#inflight.delete(slug));
|
|
109
|
+
this.#inflight.set(slug, pending);
|
|
110
|
+
}
|
|
111
|
+
return pending;
|
|
346
112
|
}
|
|
347
|
-
|
|
348
|
-
const
|
|
349
|
-
const
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
const fetchFn = this.fetchFn;
|
|
353
|
-
const signal = options?.signal;
|
|
354
|
-
return {
|
|
355
|
-
[Symbol.asyncIterator]: () => {
|
|
356
|
-
const controller = new AbortController();
|
|
357
|
-
const composite = composeSignals(controller.signal, signal);
|
|
358
|
-
const timeoutHandle = setTimeout(() => {
|
|
359
|
-
controller.abort(new TimeoutError(timeout));
|
|
360
|
-
}, timeout);
|
|
361
|
-
const responsePromise = fetchFn(url, {
|
|
362
|
-
method: "POST",
|
|
363
|
-
headers,
|
|
364
|
-
body,
|
|
365
|
-
signal: composite
|
|
366
|
-
}).then(async (response) => {
|
|
367
|
-
if (!response.ok) {
|
|
368
|
-
clearTimeout(timeoutHandle);
|
|
369
|
-
const errorBody = await safeReadJson(response);
|
|
370
|
-
throw parseErrorResponse(response.status, errorBody);
|
|
371
|
-
}
|
|
372
|
-
if (!response.body) {
|
|
373
|
-
clearTimeout(timeoutHandle);
|
|
374
|
-
throw new ApiError(
|
|
375
|
-
response.status,
|
|
376
|
-
void 0,
|
|
377
|
-
void 0,
|
|
378
|
-
"Server returned an empty stream body."
|
|
379
|
-
);
|
|
380
|
-
}
|
|
381
|
-
return response.body;
|
|
382
|
-
});
|
|
383
|
-
let inner = null;
|
|
384
|
-
let finalized = false;
|
|
385
|
-
const finalize = () => {
|
|
386
|
-
if (finalized) {
|
|
387
|
-
return;
|
|
388
|
-
}
|
|
389
|
-
finalized = true;
|
|
390
|
-
clearTimeout(timeoutHandle);
|
|
391
|
-
};
|
|
392
|
-
return {
|
|
393
|
-
next: async () => {
|
|
394
|
-
try {
|
|
395
|
-
if (!inner) {
|
|
396
|
-
const body2 = await responsePromise.catch((err) => {
|
|
397
|
-
if (isAbortError(err) && controller.signal.aborted) {
|
|
398
|
-
const reason = controller.signal.reason;
|
|
399
|
-
if (reason instanceof TimeoutError) {
|
|
400
|
-
throw reason;
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
throw err;
|
|
404
|
-
});
|
|
405
|
-
inner = readSseStream(body2, signal);
|
|
406
|
-
}
|
|
407
|
-
const result = await inner.next();
|
|
408
|
-
if (result.done === true) {
|
|
409
|
-
finalize();
|
|
410
|
-
return { value: void 0, done: true };
|
|
411
|
-
}
|
|
412
|
-
const event = result.value;
|
|
413
|
-
if (event.type === "error") {
|
|
414
|
-
finalize();
|
|
415
|
-
throw new ApiError(
|
|
416
|
-
500,
|
|
417
|
-
event.errorCode,
|
|
418
|
-
event.requestId,
|
|
419
|
-
event.message
|
|
420
|
-
);
|
|
421
|
-
}
|
|
422
|
-
if (event.type === "done") {
|
|
423
|
-
finalize();
|
|
424
|
-
return { value: event, done: false };
|
|
425
|
-
}
|
|
426
|
-
return { value: event, done: false };
|
|
427
|
-
} catch (err) {
|
|
428
|
-
finalize();
|
|
429
|
-
if (isAbortError(err) && controller.signal.aborted && controller.signal.reason instanceof TimeoutError) {
|
|
430
|
-
throw controller.signal.reason;
|
|
431
|
-
}
|
|
432
|
-
throw err;
|
|
433
|
-
}
|
|
434
|
-
},
|
|
435
|
-
return: async () => {
|
|
436
|
-
finalize();
|
|
437
|
-
controller.abort();
|
|
438
|
-
if (inner) {
|
|
439
|
-
await inner.return().catch(() => void 0);
|
|
440
|
-
}
|
|
441
|
-
return { value: void 0, done: true };
|
|
442
|
-
},
|
|
443
|
-
throw: async (err) => {
|
|
444
|
-
finalize();
|
|
445
|
-
controller.abort();
|
|
446
|
-
if (inner) {
|
|
447
|
-
await inner.return().catch(() => void 0);
|
|
448
|
-
}
|
|
449
|
-
throw err;
|
|
450
|
-
}
|
|
451
|
-
};
|
|
452
|
-
}
|
|
113
|
+
async #request(slug) {
|
|
114
|
+
const cached = this.#cache.get(slug);
|
|
115
|
+
const headers = {
|
|
116
|
+
authorization: `Bearer ${this.#apiKey}`,
|
|
117
|
+
accept: "application/json"
|
|
453
118
|
};
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
const url = `${this.baseURL}/api/v1/gateway/execute`;
|
|
457
|
-
const controller = new AbortController();
|
|
458
|
-
const composite = composeSignals(controller.signal, options?.signal);
|
|
459
|
-
const timeoutHandle = setTimeout(() => {
|
|
460
|
-
controller.abort(new TimeoutError(this.timeout));
|
|
461
|
-
}, this.timeout);
|
|
119
|
+
if (cached?.etag) headers["if-none-match"] = cached.etag;
|
|
120
|
+
let response;
|
|
462
121
|
try {
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
body: JSON.stringify(request),
|
|
467
|
-
signal: composite
|
|
122
|
+
response = await this.#fetch(`${this.#baseUrl}/v1/prompts/${encodeURIComponent(slug)}`, {
|
|
123
|
+
headers,
|
|
124
|
+
signal: AbortSignal.timeout(this.#timeout)
|
|
468
125
|
});
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
throw
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (error?.name === "TimeoutError") {
|
|
128
|
+
throw new PromptHelmError("timeout", `No response within ${this.#timeout} ms`);
|
|
472
129
|
}
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
"content-type": "application/json",
|
|
487
|
-
accept: extra["accept"] ?? "application/json",
|
|
488
|
-
authorization: `Bearer ${this.apiKey}`,
|
|
489
|
-
"user-agent": this.userAgent,
|
|
490
|
-
...this.extraHeaders
|
|
130
|
+
throw new PromptHelmError("network", error instanceof Error ? error.message : String(error));
|
|
131
|
+
}
|
|
132
|
+
if (response.status === 304 && cached) {
|
|
133
|
+
const entry2 = { ...cached, fetchedAt: Date.now() };
|
|
134
|
+
this.#cache.set(slug, entry2);
|
|
135
|
+
return entry2;
|
|
136
|
+
}
|
|
137
|
+
if (!response.ok) throw await errorFromResponse(response);
|
|
138
|
+
const payload = await response.json();
|
|
139
|
+
const entry = {
|
|
140
|
+
content: payload.content,
|
|
141
|
+
etag: response.headers.get("etag"),
|
|
142
|
+
fetchedAt: Date.now()
|
|
491
143
|
};
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
if (err instanceof TimeoutError) {
|
|
495
|
-
return false;
|
|
496
|
-
}
|
|
497
|
-
if (err instanceof AuthenticationError) {
|
|
498
|
-
return false;
|
|
499
|
-
}
|
|
500
|
-
if (err instanceof AuthorizationError) {
|
|
501
|
-
return false;
|
|
502
|
-
}
|
|
503
|
-
if (err instanceof NotFoundError) {
|
|
504
|
-
return false;
|
|
505
|
-
}
|
|
506
|
-
if (err instanceof RateLimitError) {
|
|
507
|
-
return false;
|
|
508
|
-
}
|
|
509
|
-
if (err instanceof PromptHelmError) {
|
|
510
|
-
return err.statusCode >= 500 && err.statusCode <= 599;
|
|
511
|
-
}
|
|
512
|
-
if (isAbortError(err)) {
|
|
513
|
-
return false;
|
|
514
|
-
}
|
|
515
|
-
return true;
|
|
144
|
+
this.#cache.set(slug, entry);
|
|
145
|
+
return entry;
|
|
516
146
|
}
|
|
517
147
|
};
|
|
518
|
-
function
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
return external;
|
|
524
|
-
}
|
|
525
|
-
const onAbort = () => {
|
|
526
|
-
if (!primary.aborted) {
|
|
527
|
-
const reason = external.reason;
|
|
528
|
-
compositeController.abort(reason);
|
|
529
|
-
}
|
|
530
|
-
};
|
|
531
|
-
const compositeController = new AbortController();
|
|
532
|
-
external.addEventListener("abort", onAbort, { once: true });
|
|
533
|
-
primary.addEventListener(
|
|
534
|
-
"abort",
|
|
535
|
-
() => {
|
|
536
|
-
const reason = primary.reason;
|
|
537
|
-
compositeController.abort(reason);
|
|
538
|
-
},
|
|
539
|
-
{ once: true }
|
|
540
|
-
);
|
|
541
|
-
return compositeController.signal;
|
|
148
|
+
async function errorFromResponse(response) {
|
|
149
|
+
const body = await response.json().catch(() => null);
|
|
150
|
+
const message = body?.error?.message ?? `HTTP ${response.status}`;
|
|
151
|
+
const code = response.status === 401 || response.status === 403 ? "unauthorized" : response.status === 404 ? "not_found" : "server";
|
|
152
|
+
return new PromptHelmError(code, message, response.status);
|
|
542
153
|
}
|
|
543
|
-
function
|
|
544
|
-
|
|
545
|
-
return false;
|
|
546
|
-
}
|
|
547
|
-
const candidate = err;
|
|
548
|
-
return candidate.name === "AbortError";
|
|
154
|
+
function env(name) {
|
|
155
|
+
return typeof process === "undefined" ? void 0 : process.env[name] || void 0;
|
|
549
156
|
}
|
|
550
|
-
function
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
return true;
|
|
554
|
-
} catch {
|
|
555
|
-
return false;
|
|
556
|
-
}
|
|
157
|
+
function toPromptHelmError(error) {
|
|
158
|
+
if (error instanceof PromptHelmError) return error;
|
|
159
|
+
return new PromptHelmError("server", error instanceof Error ? error.message : String(error));
|
|
557
160
|
}
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
} catch {
|
|
566
|
-
return null;
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
exports.ApiError = ApiError;
|
|
571
|
-
exports.AuthenticationError = AuthenticationError;
|
|
572
|
-
exports.AuthorizationError = AuthorizationError;
|
|
573
|
-
exports.NotFoundError = NotFoundError;
|
|
574
|
-
exports.PromptHelm = PromptHelm;
|
|
575
|
-
exports.PromptHelmError = PromptHelmError;
|
|
576
|
-
exports.RateLimitError = RateLimitError;
|
|
577
|
-
exports.TimeoutError = TimeoutError;
|
|
578
|
-
//# sourceMappingURL=index.cjs.map
|
|
579
|
-
//# sourceMappingURL=index.cjs.map
|
|
161
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
162
|
+
0 && (module.exports = {
|
|
163
|
+
PromptHelm,
|
|
164
|
+
PromptHelmError,
|
|
165
|
+
extractVariables,
|
|
166
|
+
render
|
|
167
|
+
});
|