@umituz/web-ai 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cancellation-error-CKcZRhFg.d.ts +129 -0
- package/dist/cancellation-error-DwHrDKBz.d.cts +129 -0
- package/dist/content/index.cjs +914 -37
- package/dist/content/index.cjs.map +1 -1
- package/dist/content/index.d.cts +1 -1
- package/dist/content/index.d.ts +1 -1
- package/dist/content/index.js +914 -37
- package/dist/content/index.js.map +1 -1
- package/dist/core/index.cjs +10 -0
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +13 -3
- package/dist/core/index.d.ts +13 -3
- package/dist/core/index.js +9 -1
- package/dist/core/index.js.map +1 -1
- package/dist/{create-ai-DXEoke8-.d.ts → create-ai-9PW752z8.d.ts} +11 -1
- package/dist/{create-ai-DOI9jD3v.d.cts → create-ai-CXYKPK6G.d.cts} +11 -1
- package/dist/hooks/index.cjs +1192 -39
- package/dist/hooks/index.cjs.map +1 -1
- package/dist/hooks/index.d.cts +64 -2
- package/dist/hooks/index.d.ts +64 -2
- package/dist/hooks/index.js +1188 -40
- package/dist/hooks/index.js.map +1 -1
- package/dist/index.cjs +1230 -37
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -4
- package/dist/index.d.ts +5 -4
- package/dist/index.js +1201 -38
- package/dist/index.js.map +1 -1
- package/dist/providers/index.cjs +1505 -37
- package/dist/providers/index.cjs.map +1 -1
- package/dist/providers/index.d.cts +115 -8
- package/dist/providers/index.d.ts +115 -8
- package/dist/providers/index.js +1478 -38
- package/dist/providers/index.js.map +1 -1
- package/package.json +11 -1
package/dist/content/index.cjs
CHANGED
|
@@ -198,6 +198,14 @@ var ProviderQuotaExhaustedError = class extends AIError {
|
|
|
198
198
|
}
|
|
199
199
|
};
|
|
200
200
|
|
|
201
|
+
// src/core/errors/groq-error.ts
|
|
202
|
+
var GroqError = class extends AIError {
|
|
203
|
+
constructor(type, message, cause, metadata = {}) {
|
|
204
|
+
super(type, message, cause, metadata);
|
|
205
|
+
this.name = "GroqError";
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
|
|
201
209
|
// src/core/errors/error-classifier.ts
|
|
202
210
|
var DEFAULT_RETRYABLE_TYPES = /* @__PURE__ */ new Set([
|
|
203
211
|
"NETWORK_ERROR" /* NETWORK_ERROR */,
|
|
@@ -1394,6 +1402,27 @@ var RequestDeduplicator = class {
|
|
|
1394
1402
|
}
|
|
1395
1403
|
};
|
|
1396
1404
|
|
|
1405
|
+
// src/core/utils/api-key-validator.ts
|
|
1406
|
+
var DEFAULT_API_KEY_RULE = {
|
|
1407
|
+
minLength: 10
|
|
1408
|
+
};
|
|
1409
|
+
function validateApiKey(apiKey, rule = DEFAULT_API_KEY_RULE) {
|
|
1410
|
+
if (!apiKey) {
|
|
1411
|
+
return { valid: false, reason: "API key is required" };
|
|
1412
|
+
}
|
|
1413
|
+
const trimmed = apiKey.trim();
|
|
1414
|
+
if (trimmed.length === 0) {
|
|
1415
|
+
return { valid: false, reason: "API key cannot be empty" };
|
|
1416
|
+
}
|
|
1417
|
+
if (trimmed.length < rule.minLength) {
|
|
1418
|
+
return {
|
|
1419
|
+
valid: false,
|
|
1420
|
+
reason: `API key must be at least ${rule.minLength} characters`
|
|
1421
|
+
};
|
|
1422
|
+
}
|
|
1423
|
+
return { valid: true };
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1397
1426
|
// src/providers/groq/groq.constants.ts
|
|
1398
1427
|
var GROQ_MODELS = {
|
|
1399
1428
|
LLAMA_3_1_8B_INSTANT: "llama-3.1-8b-instant",
|
|
@@ -1410,11 +1439,13 @@ var DEFAULT_GENERATION_CONFIG = {
|
|
|
1410
1439
|
topP: 1
|
|
1411
1440
|
};
|
|
1412
1441
|
var GROQ_BASE_URL = "https://api.groq.com/openai/v1";
|
|
1442
|
+
var DEFAULT_BASE_URL = GROQ_BASE_URL;
|
|
1413
1443
|
var CHAT_COMPLETIONS_PATH = "/chat/completions";
|
|
1414
1444
|
var GROQ_TIMEOUTS = {
|
|
1415
1445
|
DEFAULT: 3e4,
|
|
1416
1446
|
STREAMING: 6e4
|
|
1417
1447
|
};
|
|
1448
|
+
var TIMEOUTS = GROQ_TIMEOUTS;
|
|
1418
1449
|
var HTTP_HEADERS = {
|
|
1419
1450
|
CONTENT_TYPE: "Content-Type",
|
|
1420
1451
|
APPLICATION_JSON: "application/json",
|
|
@@ -1473,13 +1504,65 @@ var GroqChatRequestBuilder = class _GroqChatRequestBuilder {
|
|
|
1473
1504
|
}
|
|
1474
1505
|
};
|
|
1475
1506
|
|
|
1507
|
+
// src/providers/groq/groq-config-store.ts
|
|
1508
|
+
var GroqConfigStore = class {
|
|
1509
|
+
config = null;
|
|
1510
|
+
initialize(config) {
|
|
1511
|
+
const validation = validateApiKey(config.apiKey, { minLength: 1 });
|
|
1512
|
+
if (!validation.valid) {
|
|
1513
|
+
throw new GroqError("INVALID_API_KEY" /* INVALID_API_KEY */, validation.reason ?? "Invalid API key");
|
|
1514
|
+
}
|
|
1515
|
+
const normalized = {
|
|
1516
|
+
apiKey: config.apiKey.trim(),
|
|
1517
|
+
baseUrl: config.baseUrl ?? DEFAULT_BASE_URL,
|
|
1518
|
+
timeoutMs: config.timeoutMs ?? TIMEOUTS.DEFAULT,
|
|
1519
|
+
...config.models !== void 0 ? { models: config.models } : {},
|
|
1520
|
+
...config.textModel !== void 0 ? { textModel: config.textModel } : {}
|
|
1521
|
+
};
|
|
1522
|
+
this.config = normalized;
|
|
1523
|
+
return normalized;
|
|
1524
|
+
}
|
|
1525
|
+
get() {
|
|
1526
|
+
if (!this.config) {
|
|
1527
|
+
throw new GroqError(
|
|
1528
|
+
"MISSING_CONFIG" /* MISSING_CONFIG */,
|
|
1529
|
+
"Client not initialized. Call configureProvider first."
|
|
1530
|
+
);
|
|
1531
|
+
}
|
|
1532
|
+
return this.config;
|
|
1533
|
+
}
|
|
1534
|
+
getOrNull() {
|
|
1535
|
+
return this.config;
|
|
1536
|
+
}
|
|
1537
|
+
isInitialized() {
|
|
1538
|
+
return this.config !== null;
|
|
1539
|
+
}
|
|
1540
|
+
setApiKey(apiKey) {
|
|
1541
|
+
const current = this.get();
|
|
1542
|
+
const validation = validateApiKey(apiKey, { minLength: 1 });
|
|
1543
|
+
if (!validation.valid) {
|
|
1544
|
+
throw new GroqError("INVALID_API_KEY" /* INVALID_API_KEY */, validation.reason ?? "Invalid API key");
|
|
1545
|
+
}
|
|
1546
|
+
this.config = { ...current, apiKey: apiKey.trim() };
|
|
1547
|
+
}
|
|
1548
|
+
reset() {
|
|
1549
|
+
this.config = null;
|
|
1550
|
+
}
|
|
1551
|
+
};
|
|
1552
|
+
|
|
1476
1553
|
// src/providers/groq/groq-http-transport.ts
|
|
1477
1554
|
var GroqHttpTransport = class {
|
|
1478
|
-
constructor(
|
|
1479
|
-
this.
|
|
1555
|
+
constructor(configSource) {
|
|
1556
|
+
this.configSource = configSource;
|
|
1480
1557
|
}
|
|
1481
|
-
|
|
1558
|
+
configSource;
|
|
1482
1559
|
pendingAbortControllers = /* @__PURE__ */ new Set();
|
|
1560
|
+
getConfig() {
|
|
1561
|
+
if ("get" in this.configSource && typeof this.configSource.get === "function") {
|
|
1562
|
+
return this.configSource.get();
|
|
1563
|
+
}
|
|
1564
|
+
return this.configSource;
|
|
1565
|
+
}
|
|
1483
1566
|
cancelPendingRequests() {
|
|
1484
1567
|
for (const controller of this.pendingAbortControllers) {
|
|
1485
1568
|
controller.abort();
|
|
@@ -1494,7 +1577,7 @@ var GroqHttpTransport = class {
|
|
|
1494
1577
|
}
|
|
1495
1578
|
async streamChatCompletion(request, options = {}) {
|
|
1496
1579
|
const url = `${this.baseUrl()}${CHAT_COMPLETIONS_PATH}`;
|
|
1497
|
-
const timeout = this.
|
|
1580
|
+
const timeout = this.getConfig().timeoutMs ?? GROQ_TIMEOUTS.STREAMING;
|
|
1498
1581
|
const controller = new AbortController();
|
|
1499
1582
|
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
1500
1583
|
const onExternalAbort = () => controller.abort();
|
|
@@ -1521,11 +1604,11 @@ var GroqHttpTransport = class {
|
|
|
1521
1604
|
}
|
|
1522
1605
|
}
|
|
1523
1606
|
baseUrl() {
|
|
1524
|
-
return this.
|
|
1607
|
+
return this.getConfig().baseUrl ?? GROQ_BASE_URL;
|
|
1525
1608
|
}
|
|
1526
1609
|
async request(endpoint, body) {
|
|
1527
1610
|
const url = `${this.baseUrl()}${endpoint}`;
|
|
1528
|
-
const timeout = this.
|
|
1611
|
+
const timeout = this.getConfig().timeoutMs ?? GROQ_TIMEOUTS.DEFAULT;
|
|
1529
1612
|
const controller = new AbortController();
|
|
1530
1613
|
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
1531
1614
|
this.pendingAbortControllers.add(controller);
|
|
@@ -1548,7 +1631,7 @@ var GroqHttpTransport = class {
|
|
|
1548
1631
|
buildHeaders() {
|
|
1549
1632
|
return {
|
|
1550
1633
|
[HTTP_HEADERS.CONTENT_TYPE]: HTTP_HEADERS.APPLICATION_JSON,
|
|
1551
|
-
[HTTP_HEADERS.AUTHORIZATION]: `${HTTP_HEADERS.BEARER_PREFIX}${this.
|
|
1634
|
+
[HTTP_HEADERS.AUTHORIZATION]: `${HTTP_HEADERS.BEARER_PREFIX}${this.getConfig().apiKey}`
|
|
1552
1635
|
};
|
|
1553
1636
|
}
|
|
1554
1637
|
async throwFromErrorResponse(response) {
|
|
@@ -1650,21 +1733,40 @@ var CompositeExecutor = class {
|
|
|
1650
1733
|
|
|
1651
1734
|
// src/providers/groq/groq-http-client.ts
|
|
1652
1735
|
var GroqHttpClient = class {
|
|
1736
|
+
configStore;
|
|
1653
1737
|
transport;
|
|
1654
1738
|
executor;
|
|
1655
|
-
constructor(
|
|
1656
|
-
|
|
1739
|
+
constructor(configOrDeps, maybeDeps = {}) {
|
|
1740
|
+
const isConfig = typeof configOrDeps === "object" && configOrDeps !== null && "apiKey" in configOrDeps && typeof configOrDeps.apiKey === "string";
|
|
1741
|
+
const deps = isConfig ? maybeDeps : configOrDeps ?? {};
|
|
1742
|
+
this.configStore = deps.configStore ?? new GroqConfigStore();
|
|
1743
|
+
if (isConfig) {
|
|
1744
|
+
this.configStore.initialize(configOrDeps);
|
|
1745
|
+
}
|
|
1746
|
+
this.transport = deps.transport ?? new GroqHttpTransport(this.configStore);
|
|
1657
1747
|
const retryManager2 = deps.retryManager ?? new RetryManager();
|
|
1658
1748
|
const queue = deps.queue ?? new RequestQueue();
|
|
1659
1749
|
const deduplicator = deps.deduplicator ?? new RequestDeduplicator();
|
|
1660
1750
|
this.executor = new CompositeExecutor([
|
|
1661
1751
|
new DedupeExecutor(deduplicator, {
|
|
1662
|
-
generateKey: (request) => deduplicatorKey(request,
|
|
1752
|
+
generateKey: (request) => deduplicatorKey(request, this.configStore.isInitialized() ? this.configStore.get().apiKey : "")
|
|
1663
1753
|
}),
|
|
1664
1754
|
new RetryExecutor(retryManager2),
|
|
1665
1755
|
new QueueExecutor(queue, QUEUE_PRIORITY_USER_REQUEST)
|
|
1666
1756
|
]);
|
|
1667
1757
|
}
|
|
1758
|
+
initialize(config) {
|
|
1759
|
+
this.configStore.initialize(config);
|
|
1760
|
+
}
|
|
1761
|
+
isInitialized() {
|
|
1762
|
+
return this.configStore.isInitialized();
|
|
1763
|
+
}
|
|
1764
|
+
getApiKey() {
|
|
1765
|
+
return this.configStore.get().apiKey;
|
|
1766
|
+
}
|
|
1767
|
+
setApiKey(apiKey) {
|
|
1768
|
+
this.configStore.setApiKey(apiKey);
|
|
1769
|
+
}
|
|
1668
1770
|
cancelPendingRequests() {
|
|
1669
1771
|
this.transport.cancelPendingRequests();
|
|
1670
1772
|
}
|
|
@@ -1677,6 +1779,10 @@ var GroqHttpClient = class {
|
|
|
1677
1779
|
streamChatCompletion(request, options) {
|
|
1678
1780
|
return this.transport.streamChatCompletion(request, options);
|
|
1679
1781
|
}
|
|
1782
|
+
reset() {
|
|
1783
|
+
this.transport.cancelPendingRequests();
|
|
1784
|
+
this.configStore.reset();
|
|
1785
|
+
}
|
|
1680
1786
|
};
|
|
1681
1787
|
function deduplicatorKey(request, apiKey) {
|
|
1682
1788
|
const { model, messages, stream: _stream, ...rest } = request;
|
|
@@ -2562,39 +2668,810 @@ var FalProvider = class extends BaseProvider {
|
|
|
2562
2668
|
}
|
|
2563
2669
|
};
|
|
2564
2670
|
|
|
2565
|
-
// src/providers/pruna/
|
|
2566
|
-
var
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
|
|
2570
|
-
|
|
2671
|
+
// src/providers/pruna/client/core/constants/limits.ts
|
|
2672
|
+
var DEFAULT_ASPECT_RATIO = "16:9";
|
|
2673
|
+
var P_VIDEO_DEFAULTS = {
|
|
2674
|
+
duration: 5,
|
|
2675
|
+
resolution: "720p",
|
|
2676
|
+
fps: 24,
|
|
2677
|
+
draft: false,
|
|
2678
|
+
promptUpsampling: true
|
|
2679
|
+
};
|
|
2680
|
+
var POLL_DEFAULTS = {
|
|
2681
|
+
intervalMs: 3e3,
|
|
2682
|
+
maxAttempts: 120,
|
|
2683
|
+
maxIntervalMs: 1e4,
|
|
2684
|
+
backoffBase: 1.5,
|
|
2685
|
+
jitterPercent: 0.1
|
|
2686
|
+
};
|
|
2687
|
+
var DEFAULT_DEDUPLICATOR_TTL_MS = 3e4;
|
|
2688
|
+
var DEDUPLICATOR_CLEANUP_GRACE_MS = 100;
|
|
2689
|
+
|
|
2690
|
+
// src/providers/pruna/client/core/constants/network.ts
|
|
2691
|
+
var HTTPS_PREFIX = "https://";
|
|
2692
|
+
var HTTP_PREFIX = "http://";
|
|
2693
|
+
var BASE64_MARKER = "base64,";
|
|
2694
|
+
var PRUNA_BASE_URL = "https://api.pruna.ai";
|
|
2695
|
+
var PRUNA_PREDICTIONS_URL = `${PRUNA_BASE_URL}/v1/predictions`;
|
|
2696
|
+
var PRUNA_FILES_URL = `${PRUNA_BASE_URL}/v1/files`;
|
|
2697
|
+
var AUTH_FAILURE_STATUSES = [401, 403];
|
|
2698
|
+
var MIN_API_KEY_LENGTH = 1;
|
|
2699
|
+
var MAX_API_KEY_LENGTH = 256;
|
|
2700
|
+
|
|
2701
|
+
// src/providers/pruna/client/core/constants/mime-types.ts
|
|
2702
|
+
var MIME_PNG = "image/png";
|
|
2703
|
+
var MIME_JPEG = "image/jpeg";
|
|
2704
|
+
var MIME_WEBP = "image/webp";
|
|
2705
|
+
var DEFAULT_IMAGE_MIME = MIME_PNG;
|
|
2706
|
+
var MIME_FILE_EXTENSION = {
|
|
2707
|
+
[MIME_PNG]: "png",
|
|
2708
|
+
[MIME_JPEG]: "jpg",
|
|
2709
|
+
[MIME_WEBP]: "webp"
|
|
2710
|
+
};
|
|
2711
|
+
var IMAGE_SIGNATURES = {
|
|
2712
|
+
PNG: [137, 80],
|
|
2713
|
+
JPEG: [255, 216],
|
|
2714
|
+
WEBP_RIFF: [82, 73]
|
|
2715
|
+
};
|
|
2716
|
+
|
|
2717
|
+
// src/providers/pruna/client/core/errors/cancellation-error.ts
|
|
2718
|
+
var CANCELLATION_MESSAGE = "Request cancelled by user";
|
|
2719
|
+
var CancellationError = class extends Error {
|
|
2720
|
+
constructor(message = CANCELLATION_MESSAGE) {
|
|
2721
|
+
super(message);
|
|
2722
|
+
this.name = "CancellationError";
|
|
2723
|
+
}
|
|
2724
|
+
};
|
|
2725
|
+
|
|
2726
|
+
// src/providers/pruna/client/core/errors/authentication-error.ts
|
|
2727
|
+
var AUTHENTICATION_MESSAGE = "Authentication failed. Please check your API key.";
|
|
2728
|
+
var AuthenticationError = class extends Error {
|
|
2729
|
+
constructor(message = AUTHENTICATION_MESSAGE) {
|
|
2730
|
+
super(message);
|
|
2731
|
+
this.name = "AuthenticationError";
|
|
2571
2732
|
}
|
|
2572
|
-
|
|
2733
|
+
};
|
|
2734
|
+
|
|
2735
|
+
// src/providers/pruna/client/core/errors/timeout-error.ts
|
|
2736
|
+
var TIMEOUT_MESSAGE = "Generation timed out. Maximum polling attempts reached.";
|
|
2737
|
+
var TimeoutError = class extends Error {
|
|
2738
|
+
constructor(message = TIMEOUT_MESSAGE) {
|
|
2739
|
+
super(message);
|
|
2740
|
+
this.name = "TimeoutError";
|
|
2741
|
+
}
|
|
2742
|
+
};
|
|
2743
|
+
|
|
2744
|
+
// src/providers/pruna/client/core/errors/validation-error.ts
|
|
2745
|
+
var ValidationError2 = class extends Error {
|
|
2746
|
+
field;
|
|
2747
|
+
reason;
|
|
2748
|
+
receivedValue;
|
|
2749
|
+
constructor(context) {
|
|
2750
|
+
super(`Invalid ${context.field}: ${context.reason}`);
|
|
2751
|
+
this.name = "ValidationError";
|
|
2752
|
+
this.field = context.field;
|
|
2753
|
+
this.reason = context.reason;
|
|
2754
|
+
this.receivedValue = context.receivedValue;
|
|
2755
|
+
}
|
|
2756
|
+
};
|
|
2757
|
+
|
|
2758
|
+
// src/providers/pruna/client/core/utils/base64.ts
|
|
2759
|
+
var globalScope = globalThis;
|
|
2760
|
+
var hasBuffer = typeof globalScope.Buffer?.from === "function";
|
|
2761
|
+
function base64ToBytes(raw) {
|
|
2762
|
+
if (hasBuffer) {
|
|
2763
|
+
const bufferFactory = globalScope.Buffer;
|
|
2764
|
+
if (!bufferFactory) {
|
|
2765
|
+
throw new Error("Buffer unavailable despite detection flag");
|
|
2766
|
+
}
|
|
2767
|
+
const buf = bufferFactory.from(raw, "base64");
|
|
2768
|
+
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
|
2769
|
+
}
|
|
2770
|
+
const decoded = atob(raw);
|
|
2771
|
+
return Uint8Array.from(decoded, (char) => char.charCodeAt(0));
|
|
2573
2772
|
}
|
|
2574
|
-
|
|
2575
|
-
|
|
2576
|
-
|
|
2577
|
-
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
|
|
2581
|
-
|
|
2582
|
-
|
|
2583
|
-
|
|
2584
|
-
|
|
2585
|
-
if (
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2773
|
+
|
|
2774
|
+
// src/providers/pruna/client/core/utils/mime-detector.ts
|
|
2775
|
+
var MIN_SIGNATURE_BYTES = 2;
|
|
2776
|
+
function matchesSignature(bytes, signature) {
|
|
2777
|
+
if (bytes.length < signature.length) return false;
|
|
2778
|
+
return signature.every((value, index) => bytes[index] === value);
|
|
2779
|
+
}
|
|
2780
|
+
function detectImageMime(bytes) {
|
|
2781
|
+
if (bytes.length < MIN_SIGNATURE_BYTES) return DEFAULT_IMAGE_MIME;
|
|
2782
|
+
if (matchesSignature(bytes, IMAGE_SIGNATURES.PNG)) return MIME_PNG;
|
|
2783
|
+
if (matchesSignature(bytes, IMAGE_SIGNATURES.JPEG)) return MIME_JPEG;
|
|
2784
|
+
if (matchesSignature(bytes, IMAGE_SIGNATURES.WEBP_RIFF)) return MIME_WEBP;
|
|
2785
|
+
return DEFAULT_IMAGE_MIME;
|
|
2786
|
+
}
|
|
2787
|
+
|
|
2788
|
+
// src/providers/pruna/client/core/utils/api-error-parser.ts
|
|
2789
|
+
async function parseApiError(response, fallback) {
|
|
2790
|
+
const payload = await response.json().catch(() => ({ message: response.statusText }));
|
|
2791
|
+
const message = payload.message ?? `${fallback}: ${response.status}`;
|
|
2792
|
+
const error = new Error(message);
|
|
2793
|
+
error.statusCode = response.status;
|
|
2794
|
+
return error;
|
|
2795
|
+
}
|
|
2796
|
+
|
|
2797
|
+
// src/providers/pruna/client/core/protocol/http-status.ts
|
|
2798
|
+
function isAuthFailureStatus(status) {
|
|
2799
|
+
return AUTH_FAILURE_STATUSES.includes(status);
|
|
2800
|
+
}
|
|
2801
|
+
|
|
2802
|
+
// src/providers/pruna/client/core/protocol/job-status.ts
|
|
2803
|
+
var TERMINAL_SUCCESS_STATUSES = ["succeeded", "completed"];
|
|
2804
|
+
var TERMINAL_FAILURE_STATUSES = ["failed"];
|
|
2805
|
+
function isTerminalSuccessStatus(status) {
|
|
2806
|
+
if (!status) return false;
|
|
2807
|
+
return TERMINAL_SUCCESS_STATUSES.includes(status);
|
|
2808
|
+
}
|
|
2809
|
+
function isTerminalFailureStatus(status) {
|
|
2810
|
+
if (!status) return false;
|
|
2811
|
+
return TERMINAL_FAILURE_STATUSES.includes(status);
|
|
2812
|
+
}
|
|
2813
|
+
|
|
2814
|
+
// src/providers/pruna/client/core/protocol/abort-signal-classifier.ts
|
|
2815
|
+
function isAbortError(err) {
|
|
2816
|
+
if (err instanceof DOMException && err.code === DOMException.ABORT_ERR) return true;
|
|
2817
|
+
if (err instanceof Error && err.name === "AbortError") return true;
|
|
2818
|
+
return false;
|
|
2819
|
+
}
|
|
2820
|
+
|
|
2821
|
+
// src/providers/pruna/client/core/protocol/pruna-url-builder.ts
|
|
2822
|
+
function isAbsoluteHttpUrl(value) {
|
|
2823
|
+
return value.startsWith(HTTPS_PREFIX) || value.startsWith(HTTP_PREFIX);
|
|
2824
|
+
}
|
|
2825
|
+
function isHttpsUrl(value) {
|
|
2826
|
+
return value.startsWith(HTTPS_PREFIX);
|
|
2827
|
+
}
|
|
2828
|
+
function buildPrunaApiUrl(pathOrUrl) {
|
|
2829
|
+
if (isAbsoluteHttpUrl(pathOrUrl)) return pathOrUrl;
|
|
2830
|
+
return `${PRUNA_BASE_URL}${pathOrUrl}`;
|
|
2831
|
+
}
|
|
2832
|
+
function buildFileUrlById(fileId) {
|
|
2833
|
+
return `${PRUNA_FILES_URL}/${fileId}`;
|
|
2834
|
+
}
|
|
2835
|
+
|
|
2836
|
+
// src/providers/pruna/client/core/math/exponential-backoff.ts
|
|
2837
|
+
function calculateExponentialBackoff2(inputs) {
|
|
2838
|
+
const {
|
|
2839
|
+
attempt,
|
|
2840
|
+
baseIntervalMs,
|
|
2841
|
+
maxIntervalMs = POLL_DEFAULTS.maxIntervalMs,
|
|
2842
|
+
jitterPercent = POLL_DEFAULTS.jitterPercent,
|
|
2843
|
+
growthBase = POLL_DEFAULTS.backoffBase
|
|
2844
|
+
} = inputs;
|
|
2845
|
+
const safeAttempt = Math.max(0, attempt);
|
|
2846
|
+
const safeBase = Math.max(0, baseIntervalMs);
|
|
2847
|
+
const exponentialDelay = Math.min(safeBase * Math.pow(growthBase, safeAttempt), maxIntervalMs);
|
|
2848
|
+
const jitter = exponentialDelay * jitterPercent * Math.random();
|
|
2849
|
+
return exponentialDelay + jitter;
|
|
2850
|
+
}
|
|
2851
|
+
|
|
2852
|
+
// src/providers/pruna/client/core/utils/uri-resolver.ts
|
|
2853
|
+
var uriCache = /* @__PURE__ */ new WeakMap();
|
|
2854
|
+
function stripBase64Prefix(image) {
|
|
2855
|
+
if (isHttpsUrl(image)) return image;
|
|
2856
|
+
const base64Index = image.indexOf(BASE64_MARKER);
|
|
2857
|
+
return base64Index !== -1 ? image.slice(base64Index + BASE64_MARKER.length) : image;
|
|
2858
|
+
}
|
|
2859
|
+
function readOutput(output) {
|
|
2860
|
+
if (typeof output === "string") return output;
|
|
2861
|
+
if (Array.isArray(output) && output.length > 0) return output[0] ?? null;
|
|
2862
|
+
if (output !== null && typeof output === "object" && "url" in output) {
|
|
2863
|
+
return output.url;
|
|
2864
|
+
}
|
|
2865
|
+
return null;
|
|
2866
|
+
}
|
|
2867
|
+
function extractUri(data) {
|
|
2868
|
+
const cached = uriCache.get(data);
|
|
2869
|
+
if (cached !== void 0) return cached;
|
|
2870
|
+
if (!isTerminalSuccessStatus(data.status)) {
|
|
2871
|
+
uriCache.set(data, null);
|
|
2872
|
+
return null;
|
|
2873
|
+
}
|
|
2874
|
+
const result = data.generation_url ?? readOutput(data.output) ?? data.video_url ?? data.data ?? null;
|
|
2875
|
+
uriCache.set(data, result);
|
|
2876
|
+
return result;
|
|
2877
|
+
}
|
|
2878
|
+
function resolveUri(uri) {
|
|
2879
|
+
return uri.startsWith("/") ? `${PRUNA_BASE_URL}${uri}` : uri;
|
|
2880
|
+
}
|
|
2881
|
+
|
|
2882
|
+
// src/providers/pruna/client/core/services/pruna-client.service.ts
|
|
2883
|
+
function buildFileExtension(mime) {
|
|
2884
|
+
return MIME_FILE_EXTENSION[mime] ?? "bin";
|
|
2885
|
+
}
|
|
2886
|
+
async function uploadImage(base64OrUrl, apiKey, onProgress) {
|
|
2887
|
+
if (isHttpsUrl(base64OrUrl)) return base64OrUrl;
|
|
2888
|
+
if (base64OrUrl.startsWith(HTTP_PREFIX)) {
|
|
2889
|
+
throw new Error("Only HTTPS URLs are supported for security.");
|
|
2890
|
+
}
|
|
2891
|
+
onProgress?.("uploading");
|
|
2892
|
+
const raw = stripBase64Prefix(base64OrUrl);
|
|
2893
|
+
let bytes;
|
|
2894
|
+
try {
|
|
2895
|
+
bytes = base64ToBytes(raw);
|
|
2896
|
+
} catch {
|
|
2897
|
+
throw new Error("Invalid image format. Provide base64 or a valid HTTPS URL.");
|
|
2898
|
+
}
|
|
2899
|
+
const mime = detectImageMime(bytes);
|
|
2900
|
+
const buffer = bytes.buffer.slice(
|
|
2901
|
+
bytes.byteOffset,
|
|
2902
|
+
bytes.byteOffset + bytes.byteLength
|
|
2903
|
+
);
|
|
2904
|
+
const blob = new Blob([buffer], { type: mime });
|
|
2905
|
+
const formData = new FormData();
|
|
2906
|
+
formData.append("content", blob, `upload.${buildFileExtension(mime)}`);
|
|
2907
|
+
const res = await fetch(PRUNA_FILES_URL, {
|
|
2908
|
+
method: "POST",
|
|
2909
|
+
headers: { apikey: apiKey },
|
|
2910
|
+
body: formData
|
|
2911
|
+
});
|
|
2912
|
+
if (!res.ok) {
|
|
2913
|
+
throw await parseApiError(res, "File upload error");
|
|
2914
|
+
}
|
|
2915
|
+
const data = await res.json();
|
|
2916
|
+
return data.urls?.get ?? buildFileUrlById(data.id ?? "");
|
|
2917
|
+
}
|
|
2918
|
+
async function submitPrediction(model, input, apiKey, signal, onProgress) {
|
|
2919
|
+
onProgress?.("predicting");
|
|
2920
|
+
const res = await fetch(PRUNA_PREDICTIONS_URL, {
|
|
2921
|
+
method: "POST",
|
|
2922
|
+
headers: {
|
|
2923
|
+
apikey: apiKey,
|
|
2924
|
+
Model: model,
|
|
2925
|
+
"Try-Sync": "true",
|
|
2926
|
+
"Content-Type": "application/json"
|
|
2927
|
+
},
|
|
2928
|
+
body: JSON.stringify({ input }),
|
|
2929
|
+
signal
|
|
2930
|
+
});
|
|
2931
|
+
if (!res.ok) {
|
|
2932
|
+
throw await parseApiError(res, "API error");
|
|
2933
|
+
}
|
|
2934
|
+
return res.json();
|
|
2935
|
+
}
|
|
2936
|
+
var GenerationFailedError = class extends Error {
|
|
2937
|
+
constructor(message) {
|
|
2938
|
+
super(message);
|
|
2939
|
+
this.name = "GenerationFailedError";
|
|
2940
|
+
}
|
|
2941
|
+
};
|
|
2942
|
+
async function attemptPoll(fullUrl, apiKey, signal) {
|
|
2943
|
+
let res;
|
|
2944
|
+
try {
|
|
2945
|
+
res = await fetch(fullUrl, { headers: { apikey: apiKey }, signal });
|
|
2946
|
+
} catch (err) {
|
|
2947
|
+
if (isAbortError(err)) throw new CancellationError();
|
|
2948
|
+
return { outcome: "transient-failure" };
|
|
2949
|
+
}
|
|
2950
|
+
if (!res.ok) {
|
|
2951
|
+
if (isAuthFailureStatus(res.status)) throw new AuthenticationError();
|
|
2952
|
+
return { outcome: "transient-failure" };
|
|
2953
|
+
}
|
|
2954
|
+
let data;
|
|
2955
|
+
try {
|
|
2956
|
+
data = await res.json();
|
|
2957
|
+
} catch {
|
|
2958
|
+
return { outcome: "transient-failure" };
|
|
2959
|
+
}
|
|
2960
|
+
if (isTerminalSuccessStatus(data.status)) {
|
|
2961
|
+
const uri = extractUri(data);
|
|
2962
|
+
if (uri) return { outcome: "succeeded", uri: resolveUri(uri) };
|
|
2963
|
+
return { outcome: "transient-failure" };
|
|
2964
|
+
}
|
|
2965
|
+
if (isTerminalFailureStatus(data.status)) {
|
|
2966
|
+
throw new GenerationFailedError(data.error ?? "Generation failed during processing.");
|
|
2967
|
+
}
|
|
2968
|
+
return { outcome: "continue" };
|
|
2969
|
+
}
|
|
2970
|
+
async function pollForResult(pollUrl, apiKey, maxAttempts = POLL_DEFAULTS.maxAttempts, intervalMs = POLL_DEFAULTS.intervalMs, signal, onProgress) {
|
|
2971
|
+
const fullUrl = isAbsoluteHttpUrl(pollUrl) ? pollUrl : buildPrunaApiUrl(pollUrl);
|
|
2972
|
+
const controller = new AbortController();
|
|
2973
|
+
const onExternalAbort = () => controller.abort();
|
|
2974
|
+
signal?.addEventListener("abort", onExternalAbort);
|
|
2975
|
+
try {
|
|
2976
|
+
for (let i = 0; i < maxAttempts; i++) {
|
|
2977
|
+
if (signal?.aborted) throw new CancellationError();
|
|
2978
|
+
const delay = calculateExponentialBackoff2({ attempt: i, baseIntervalMs: intervalMs });
|
|
2979
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
2980
|
+
if (signal?.aborted) throw new CancellationError();
|
|
2981
|
+
onProgress?.("polling", i + 1);
|
|
2982
|
+
const result = await attemptPoll(fullUrl, apiKey, controller.signal);
|
|
2983
|
+
if (result.outcome === "succeeded" && result.uri) {
|
|
2984
|
+
return result.uri;
|
|
2985
|
+
}
|
|
2986
|
+
}
|
|
2987
|
+
throw new TimeoutError();
|
|
2988
|
+
} finally {
|
|
2989
|
+
signal?.removeEventListener("abort", onExternalAbort);
|
|
2990
|
+
controller.abort();
|
|
2991
|
+
}
|
|
2992
|
+
}
|
|
2993
|
+
|
|
2994
|
+
// src/providers/pruna/client/core/math/comparison-hash.ts
|
|
2995
|
+
function sortKeysDeep(value) {
|
|
2996
|
+
if (Array.isArray(value)) {
|
|
2997
|
+
return value.map(sortKeysDeep);
|
|
2998
|
+
}
|
|
2999
|
+
if (value !== null && typeof value === "object") {
|
|
3000
|
+
const record = value;
|
|
3001
|
+
return Object.keys(record).sort().reduce((acc, key) => {
|
|
3002
|
+
acc[key] = sortKeysDeep(record[key]);
|
|
3003
|
+
return acc;
|
|
3004
|
+
}, {});
|
|
3005
|
+
}
|
|
3006
|
+
return value;
|
|
3007
|
+
}
|
|
3008
|
+
function hashValue(value) {
|
|
3009
|
+
if (value === null || typeof value !== "object") {
|
|
3010
|
+
return String(value);
|
|
3011
|
+
}
|
|
3012
|
+
try {
|
|
3013
|
+
return JSON.stringify(sortKeysDeep(value));
|
|
3014
|
+
} catch {
|
|
3015
|
+
return String(value);
|
|
3016
|
+
}
|
|
3017
|
+
}
|
|
3018
|
+
function compositeHash(...values) {
|
|
3019
|
+
return values.map(hashValue).join("|");
|
|
3020
|
+
}
|
|
3021
|
+
|
|
3022
|
+
// src/providers/pruna/client/core/math/cache-key-derivation.ts
|
|
3023
|
+
function deriveGenerationCacheKey(apiKey, input) {
|
|
3024
|
+
return `${apiKey}:${compositeHash(input)}`;
|
|
3025
|
+
}
|
|
3026
|
+
|
|
3027
|
+
// src/providers/pruna/client/core/validation/api-key-validator.ts
|
|
3028
|
+
function assertValidApiKey(apiKey) {
|
|
3029
|
+
if (typeof apiKey !== "string") {
|
|
3030
|
+
throw new ValidationError2({
|
|
3031
|
+
field: "apiKey",
|
|
3032
|
+
reason: "must be a string",
|
|
3033
|
+
receivedValue: typeof apiKey
|
|
3034
|
+
});
|
|
3035
|
+
}
|
|
3036
|
+
if (apiKey.length < MIN_API_KEY_LENGTH) {
|
|
3037
|
+
throw new ValidationError2({
|
|
3038
|
+
field: "apiKey",
|
|
3039
|
+
reason: "must not be empty",
|
|
3040
|
+
receivedValue: apiKey
|
|
3041
|
+
});
|
|
3042
|
+
}
|
|
3043
|
+
if (apiKey.length > MAX_API_KEY_LENGTH) {
|
|
3044
|
+
throw new ValidationError2({
|
|
3045
|
+
field: "apiKey",
|
|
3046
|
+
reason: `exceeds maximum length of ${MAX_API_KEY_LENGTH}`,
|
|
3047
|
+
receivedValue: apiKey.length
|
|
3048
|
+
});
|
|
3049
|
+
}
|
|
3050
|
+
}
|
|
3051
|
+
|
|
3052
|
+
// src/providers/pruna/client/core/validation/image-source-validator.ts
|
|
3053
|
+
function classifyImageSource(source) {
|
|
3054
|
+
if (source.startsWith(HTTPS_PREFIX)) return "https-url";
|
|
3055
|
+
if (source.startsWith(HTTP_PREFIX)) return "http-url";
|
|
3056
|
+
if (source.includes(BASE64_MARKER) || /^[A-Za-z0-9+/=]+$/.test(source)) return "base64";
|
|
3057
|
+
return "unknown";
|
|
3058
|
+
}
|
|
3059
|
+
function assertSecureImageSource(image, fieldName = "image") {
|
|
3060
|
+
if (typeof image !== "string") {
|
|
3061
|
+
throw new ValidationError2({
|
|
3062
|
+
field: fieldName,
|
|
3063
|
+
reason: "must be a string",
|
|
3064
|
+
receivedValue: typeof image
|
|
3065
|
+
});
|
|
3066
|
+
}
|
|
3067
|
+
const kind = classifyImageSource(image);
|
|
3068
|
+
if (kind === "http-url") {
|
|
3069
|
+
throw new ValidationError2({
|
|
3070
|
+
field: fieldName,
|
|
3071
|
+
reason: "HTTP URLs are not supported; use HTTPS or a base64 data URI",
|
|
3072
|
+
receivedValue: image
|
|
3073
|
+
});
|
|
3074
|
+
}
|
|
3075
|
+
if (kind === "unknown") {
|
|
3076
|
+
throw new ValidationError2({
|
|
3077
|
+
field: fieldName,
|
|
3078
|
+
reason: "must be an HTTPS URL or a base64 data URI",
|
|
3079
|
+
receivedValue: typeof image
|
|
3080
|
+
});
|
|
3081
|
+
}
|
|
3082
|
+
}
|
|
3083
|
+
|
|
3084
|
+
// src/providers/pruna/client/core/validation/aspect-ratio-validator.ts
|
|
3085
|
+
var SUPPORTED_ASPECT_RATIOS = [
|
|
3086
|
+
"16:9",
|
|
3087
|
+
"9:16",
|
|
3088
|
+
"1:1",
|
|
3089
|
+
"4:3",
|
|
3090
|
+
"3:4",
|
|
3091
|
+
"3:2",
|
|
3092
|
+
"2:3"
|
|
3093
|
+
];
|
|
3094
|
+
function isSupportedAspectRatio(value) {
|
|
3095
|
+
return typeof value === "string" && SUPPORTED_ASPECT_RATIOS.includes(value);
|
|
3096
|
+
}
|
|
3097
|
+
function assertValidAspectRatio(value, fieldName = "aspect_ratio") {
|
|
3098
|
+
if (value === void 0 || value === null) return;
|
|
3099
|
+
if (!isSupportedAspectRatio(value)) {
|
|
3100
|
+
throw new ValidationError2({
|
|
3101
|
+
field: fieldName,
|
|
3102
|
+
reason: `must be one of ${SUPPORTED_ASPECT_RATIOS.join(", ")}`,
|
|
3103
|
+
receivedValue: value
|
|
3104
|
+
});
|
|
3105
|
+
}
|
|
3106
|
+
}
|
|
3107
|
+
|
|
3108
|
+
// src/providers/pruna/client/core/validation/resolution-validator.ts
|
|
3109
|
+
var SUPPORTED_RESOLUTIONS = ["720p", "1080p"];
|
|
3110
|
+
function isSupportedResolution(value) {
|
|
3111
|
+
return typeof value === "string" && SUPPORTED_RESOLUTIONS.includes(value);
|
|
3112
|
+
}
|
|
3113
|
+
function assertValidResolution(value, fieldName = "resolution") {
|
|
3114
|
+
if (value === void 0 || value === null) return;
|
|
3115
|
+
if (!isSupportedResolution(value)) {
|
|
3116
|
+
throw new ValidationError2({
|
|
3117
|
+
field: fieldName,
|
|
3118
|
+
reason: `must be one of ${SUPPORTED_RESOLUTIONS.join(", ")}`,
|
|
3119
|
+
receivedValue: value
|
|
3120
|
+
});
|
|
3121
|
+
}
|
|
3122
|
+
}
|
|
3123
|
+
|
|
3124
|
+
// src/providers/pruna/client/core/validation/duration-validator.ts
|
|
3125
|
+
var MIN_VIDEO_DURATION_SECONDS = 1;
|
|
3126
|
+
var MAX_VIDEO_DURATION_SECONDS = 30;
|
|
3127
|
+
function isValidDuration(value) {
|
|
3128
|
+
return typeof value === "number" && Number.isFinite(value) && value >= MIN_VIDEO_DURATION_SECONDS && value <= MAX_VIDEO_DURATION_SECONDS && Number.isInteger(value);
|
|
3129
|
+
}
|
|
3130
|
+
function assertValidDuration(value, fieldName = "duration") {
|
|
3131
|
+
if (value === void 0 || value === null) return;
|
|
3132
|
+
if (!isValidDuration(value)) {
|
|
3133
|
+
throw new ValidationError2({
|
|
3134
|
+
field: fieldName,
|
|
3135
|
+
reason: `must be an integer between ${MIN_VIDEO_DURATION_SECONDS} and ${MAX_VIDEO_DURATION_SECONDS} seconds`,
|
|
3136
|
+
receivedValue: value
|
|
3137
|
+
});
|
|
3138
|
+
}
|
|
3139
|
+
}
|
|
3140
|
+
|
|
3141
|
+
// src/providers/pruna/client/core/validation/prompt-validator.ts
|
|
3142
|
+
var MIN_PROMPT_LENGTH = 1;
|
|
3143
|
+
var MAX_PROMPT_LENGTH = 4e3;
|
|
3144
|
+
function assertValidPrompt(value, fieldName = "prompt") {
|
|
3145
|
+
if (typeof value !== "string") {
|
|
3146
|
+
throw new ValidationError2({
|
|
3147
|
+
field: fieldName,
|
|
3148
|
+
reason: "must be a string",
|
|
3149
|
+
receivedValue: typeof value
|
|
3150
|
+
});
|
|
3151
|
+
}
|
|
3152
|
+
if (value.trim().length < MIN_PROMPT_LENGTH) {
|
|
3153
|
+
throw new ValidationError2({
|
|
3154
|
+
field: fieldName,
|
|
3155
|
+
reason: "must not be empty or whitespace-only",
|
|
3156
|
+
receivedValue: value
|
|
3157
|
+
});
|
|
3158
|
+
}
|
|
3159
|
+
if (value.length > MAX_PROMPT_LENGTH) {
|
|
3160
|
+
throw new ValidationError2({
|
|
3161
|
+
field: fieldName,
|
|
3162
|
+
reason: `exceeds maximum length of ${MAX_PROMPT_LENGTH} characters`,
|
|
3163
|
+
receivedValue: value.length
|
|
3164
|
+
});
|
|
3165
|
+
}
|
|
3166
|
+
}
|
|
3167
|
+
|
|
3168
|
+
// src/providers/pruna/client/core/validation/seed-validator.ts
|
|
3169
|
+
var MIN_SEED = -2147483648;
|
|
3170
|
+
var MAX_SEED = 2147483647;
|
|
3171
|
+
function isValidSeed(value) {
|
|
3172
|
+
return typeof value === "number" && Number.isFinite(value) && Number.isInteger(value) && value >= MIN_SEED && value <= MAX_SEED;
|
|
3173
|
+
}
|
|
3174
|
+
function assertValidSeed(value, fieldName = "seed") {
|
|
3175
|
+
if (value === void 0 || value === null) return;
|
|
3176
|
+
if (!isValidSeed(value)) {
|
|
3177
|
+
throw new ValidationError2({
|
|
3178
|
+
field: fieldName,
|
|
3179
|
+
reason: `must be an integer in [${MIN_SEED}, ${MAX_SEED}]`,
|
|
3180
|
+
receivedValue: value
|
|
3181
|
+
});
|
|
3182
|
+
}
|
|
3183
|
+
}
|
|
3184
|
+
|
|
3185
|
+
// src/providers/pruna/client/core/protocol/input-type-guard.ts
|
|
3186
|
+
function isTextToImageInput(input) {
|
|
3187
|
+
return input.model === "p-image";
|
|
3188
|
+
}
|
|
3189
|
+
function isImageToImageInput(input) {
|
|
3190
|
+
return input.model === "p-image-edit";
|
|
3191
|
+
}
|
|
3192
|
+
function isImageToVideoInput(input) {
|
|
3193
|
+
return input.model === "p-video";
|
|
3194
|
+
}
|
|
3195
|
+
|
|
3196
|
+
// src/providers/pruna/client/core/utils/request-deduplicator.ts
|
|
3197
|
+
var RequestDeduplicator2 = class {
|
|
3198
|
+
pendingRequests = /* @__PURE__ */ new Map();
|
|
3199
|
+
ttl;
|
|
3200
|
+
constructor(ttl = DEFAULT_DEDUPLICATOR_TTL_MS) {
|
|
3201
|
+
this.ttl = ttl;
|
|
3202
|
+
}
|
|
3203
|
+
execute(key, fn) {
|
|
3204
|
+
const existing = this.pendingRequests.get(key);
|
|
3205
|
+
if (existing) {
|
|
3206
|
+
if (Date.now() - existing.timestamp < this.ttl) {
|
|
3207
|
+
return existing.promise;
|
|
3208
|
+
}
|
|
3209
|
+
this.pendingRequests.delete(key);
|
|
3210
|
+
}
|
|
3211
|
+
const promise = fn().finally(() => {
|
|
3212
|
+
setTimeout(() => {
|
|
3213
|
+
this.pendingRequests.delete(key);
|
|
3214
|
+
}, DEDUPLICATOR_CLEANUP_GRACE_MS);
|
|
3215
|
+
});
|
|
3216
|
+
this.pendingRequests.set(key, { promise, timestamp: Date.now() });
|
|
3217
|
+
return promise;
|
|
3218
|
+
}
|
|
3219
|
+
clear() {
|
|
3220
|
+
this.pendingRequests.clear();
|
|
3221
|
+
}
|
|
3222
|
+
size() {
|
|
3223
|
+
this.purgeExpired();
|
|
3224
|
+
return this.pendingRequests.size;
|
|
3225
|
+
}
|
|
3226
|
+
purgeExpired() {
|
|
3227
|
+
const now = Date.now();
|
|
3228
|
+
for (const [key, value] of this.pendingRequests) {
|
|
3229
|
+
if (now - value.timestamp >= this.ttl) {
|
|
3230
|
+
this.pendingRequests.delete(key);
|
|
3231
|
+
}
|
|
3232
|
+
}
|
|
3233
|
+
}
|
|
3234
|
+
};
|
|
3235
|
+
var globalDeduplicator = new RequestDeduplicator2();
|
|
3236
|
+
|
|
3237
|
+
// src/providers/pruna/client/generation/builders/text-to-image.builder.ts
|
|
3238
|
+
var TextToImageInputBuilder = class {
|
|
3239
|
+
model = "p-image";
|
|
3240
|
+
build(input, _context) {
|
|
3241
|
+
const payload = {
|
|
3242
|
+
prompt: input.prompt,
|
|
3243
|
+
aspect_ratio: input.aspect_ratio ?? DEFAULT_ASPECT_RATIO
|
|
3244
|
+
};
|
|
3245
|
+
if (input.seed !== void 0) {
|
|
3246
|
+
payload.seed = input.seed;
|
|
3247
|
+
}
|
|
3248
|
+
return Promise.resolve(payload);
|
|
3249
|
+
}
|
|
3250
|
+
};
|
|
3251
|
+
|
|
3252
|
+
// src/providers/pruna/client/generation/builders/image-to-image.builder.ts
|
|
3253
|
+
var ImageToImageInputBuilder = class {
|
|
3254
|
+
model = "p-image-edit";
|
|
3255
|
+
build(input, _context) {
|
|
3256
|
+
const payload = {
|
|
3257
|
+
images: [stripBase64Prefix(input.image)],
|
|
3258
|
+
prompt: input.prompt,
|
|
3259
|
+
aspect_ratio: input.aspect_ratio ?? DEFAULT_ASPECT_RATIO
|
|
2589
3260
|
};
|
|
2590
|
-
|
|
3261
|
+
if (input.seed !== void 0) {
|
|
3262
|
+
payload.seed = input.seed;
|
|
3263
|
+
}
|
|
3264
|
+
return Promise.resolve(payload);
|
|
3265
|
+
}
|
|
3266
|
+
};
|
|
3267
|
+
|
|
3268
|
+
// src/providers/pruna/client/generation/builders/image-to-video.builder.ts
|
|
3269
|
+
var ImageToVideoInputBuilder = class {
|
|
3270
|
+
model = "p-video";
|
|
3271
|
+
async build(input, context) {
|
|
3272
|
+
if (context.signal?.aborted) {
|
|
3273
|
+
throw new CancellationError();
|
|
3274
|
+
}
|
|
3275
|
+
const fileUrl = await uploadImage(
|
|
3276
|
+
input.image,
|
|
3277
|
+
context.apiKey,
|
|
3278
|
+
context.onProgress
|
|
3279
|
+
);
|
|
3280
|
+
return {
|
|
3281
|
+
image: fileUrl,
|
|
3282
|
+
prompt: input.prompt,
|
|
3283
|
+
duration: input.duration ?? P_VIDEO_DEFAULTS.duration,
|
|
3284
|
+
resolution: input.resolution ?? P_VIDEO_DEFAULTS.resolution,
|
|
3285
|
+
fps: P_VIDEO_DEFAULTS.fps,
|
|
3286
|
+
draft: input.draft ?? P_VIDEO_DEFAULTS.draft,
|
|
3287
|
+
aspect_ratio: input.aspect_ratio ?? DEFAULT_ASPECT_RATIO,
|
|
3288
|
+
prompt_upsampling: P_VIDEO_DEFAULTS.promptUpsampling
|
|
3289
|
+
};
|
|
3290
|
+
}
|
|
3291
|
+
};
|
|
3292
|
+
|
|
3293
|
+
// src/providers/pruna/client/generation/builders/model-input-builder.ts
|
|
3294
|
+
var ModelInputBuilderRegistry = class {
|
|
3295
|
+
builders = /* @__PURE__ */ new Map();
|
|
3296
|
+
register(builder) {
|
|
3297
|
+
this.builders.set(builder.model, builder);
|
|
3298
|
+
return this;
|
|
3299
|
+
}
|
|
3300
|
+
resolve(model) {
|
|
3301
|
+
const builder = this.builders.get(model);
|
|
3302
|
+
if (!builder) {
|
|
3303
|
+
throw new Error(`No input builder registered for model: ${model}`);
|
|
3304
|
+
}
|
|
3305
|
+
return builder;
|
|
3306
|
+
}
|
|
3307
|
+
};
|
|
3308
|
+
|
|
3309
|
+
// src/providers/pruna/client/generation/builders/builder-factory.ts
|
|
3310
|
+
function createDefaultBuilderRegistry() {
|
|
3311
|
+
return new ModelInputBuilderRegistry().register(new TextToImageInputBuilder()).register(new ImageToImageInputBuilder()).register(new ImageToVideoInputBuilder());
|
|
3312
|
+
}
|
|
3313
|
+
|
|
3314
|
+
// src/providers/pruna/client/generation/services/generation.service.ts
|
|
3315
|
+
var builderRegistry = createDefaultBuilderRegistry();
|
|
3316
|
+
function validateGenerateInput(input) {
|
|
3317
|
+
assertValidPrompt(input.prompt, `${input.model}.prompt`);
|
|
3318
|
+
assertValidAspectRatio(input.aspect_ratio, `${input.model}.aspect_ratio`);
|
|
3319
|
+
if (isTextToImageInput(input)) {
|
|
3320
|
+
assertValidSeed(input.seed, `${input.model}.seed`);
|
|
3321
|
+
} else if (isImageToImageInput(input)) {
|
|
3322
|
+
assertSecureImageSource(input.image, `${input.model}.image`);
|
|
3323
|
+
assertValidSeed(input.seed, `${input.model}.seed`);
|
|
3324
|
+
} else if (isImageToVideoInput(input)) {
|
|
3325
|
+
assertSecureImageSource(input.image, `${input.model}.image`);
|
|
3326
|
+
assertValidDuration(input.duration, `${input.model}.duration`);
|
|
3327
|
+
assertValidResolution(input.resolution, `${input.model}.resolution`);
|
|
3328
|
+
}
|
|
3329
|
+
}
|
|
3330
|
+
async function generate(apiKey, input, options = {}) {
|
|
3331
|
+
assertValidApiKey(apiKey);
|
|
3332
|
+
validateGenerateInput(input);
|
|
3333
|
+
const { signal, onProgress, useCache = true } = options;
|
|
3334
|
+
if (useCache) {
|
|
3335
|
+
const cacheKey = deriveGenerationCacheKey(apiKey, input);
|
|
3336
|
+
return globalDeduplicator.execute(
|
|
3337
|
+
cacheKey,
|
|
3338
|
+
() => generateInternal(apiKey, input, { signal, onProgress })
|
|
3339
|
+
);
|
|
2591
3340
|
}
|
|
2592
|
-
|
|
3341
|
+
return generateInternal(apiKey, input, { signal, onProgress });
|
|
3342
|
+
}
|
|
3343
|
+
async function generateInternal(apiKey, input, options) {
|
|
3344
|
+
const { signal, onProgress } = options;
|
|
3345
|
+
const builder = builderRegistry.resolve(input.model);
|
|
3346
|
+
const modelInput = await builder.build(input, { apiKey, signal, onProgress });
|
|
3347
|
+
const response = await submitPrediction(input.model, modelInput, apiKey, signal, onProgress);
|
|
3348
|
+
const syncUri = extractUri(response);
|
|
3349
|
+
if (syncUri) {
|
|
3350
|
+
return { url: resolveUri(syncUri), model: input.model };
|
|
3351
|
+
}
|
|
3352
|
+
const pollUrl = response.get_url ?? response.status_url;
|
|
2593
3353
|
if (!pollUrl) {
|
|
2594
|
-
throw new Error("Pruna
|
|
3354
|
+
throw new Error("Pruna API returned no result and no polling URL.");
|
|
3355
|
+
}
|
|
3356
|
+
const url = await pollForResult(
|
|
3357
|
+
pollUrl,
|
|
3358
|
+
apiKey,
|
|
3359
|
+
POLL_DEFAULTS.maxAttempts,
|
|
3360
|
+
POLL_DEFAULTS.intervalMs,
|
|
3361
|
+
signal,
|
|
3362
|
+
onProgress
|
|
3363
|
+
);
|
|
3364
|
+
return { url, model: input.model };
|
|
3365
|
+
}
|
|
3366
|
+
async function generateImageThenVideo(apiKey, input, options = {}) {
|
|
3367
|
+
assertValidApiKey(apiKey);
|
|
3368
|
+
assertValidPrompt(input.prompt, "text-to-video.prompt");
|
|
3369
|
+
assertValidAspectRatio(input.aspect_ratio, "text-to-video.aspect_ratio");
|
|
3370
|
+
assertValidDuration(input.duration, "text-to-video.duration");
|
|
3371
|
+
assertValidResolution(input.resolution, "text-to-video.resolution");
|
|
3372
|
+
const { signal, onProgress } = options;
|
|
3373
|
+
const aspectRatio = input.aspect_ratio ?? DEFAULT_ASPECT_RATIO;
|
|
3374
|
+
onProgress?.("predicting", 1);
|
|
3375
|
+
const imageResult = await generate(
|
|
3376
|
+
apiKey,
|
|
3377
|
+
{ model: "p-image", prompt: input.prompt, aspect_ratio: aspectRatio },
|
|
3378
|
+
{ signal }
|
|
3379
|
+
);
|
|
3380
|
+
onProgress?.("predicting", 2);
|
|
3381
|
+
return generate(
|
|
3382
|
+
apiKey,
|
|
3383
|
+
{
|
|
3384
|
+
model: "p-video",
|
|
3385
|
+
prompt: input.prompt,
|
|
3386
|
+
image: imageResult.url,
|
|
3387
|
+
duration: input.duration ?? P_VIDEO_DEFAULTS.duration,
|
|
3388
|
+
resolution: input.resolution ?? P_VIDEO_DEFAULTS.resolution,
|
|
3389
|
+
aspect_ratio: aspectRatio,
|
|
3390
|
+
draft: input.draft ?? P_VIDEO_DEFAULTS.draft
|
|
3391
|
+
},
|
|
3392
|
+
{ signal, onProgress }
|
|
3393
|
+
);
|
|
3394
|
+
}
|
|
3395
|
+
|
|
3396
|
+
// src/providers/pruna/pruna-generate.ts
|
|
3397
|
+
async function* generateWithPruna(request, apiKey, signal, onProgress) {
|
|
3398
|
+
const stages = [];
|
|
3399
|
+
let notify = null;
|
|
3400
|
+
let done = false;
|
|
3401
|
+
const wake = () => {
|
|
3402
|
+
const fn = notify;
|
|
3403
|
+
if (fn) {
|
|
3404
|
+
notify = null;
|
|
3405
|
+
fn();
|
|
3406
|
+
}
|
|
3407
|
+
};
|
|
3408
|
+
const handleProgress = (stage) => {
|
|
3409
|
+
stages.push({ stage });
|
|
3410
|
+
wake();
|
|
3411
|
+
};
|
|
3412
|
+
const promise = (async () => {
|
|
3413
|
+
try {
|
|
3414
|
+
const model = request.model ?? (request.image ? "p-image-edit" : "p-image");
|
|
3415
|
+
if (model === "p-video" && !request.image && request.prompt) {
|
|
3416
|
+
const videoRes = await generateImageThenVideo(
|
|
3417
|
+
apiKey,
|
|
3418
|
+
{
|
|
3419
|
+
prompt: request.prompt,
|
|
3420
|
+
duration: request.duration ?? 5,
|
|
3421
|
+
aspect_ratio: request.aspectRatio ?? request.aspect_ratio ?? "16:9"
|
|
3422
|
+
},
|
|
3423
|
+
{ signal, onProgress: handleProgress }
|
|
3424
|
+
);
|
|
3425
|
+
stages.push({
|
|
3426
|
+
stage: "polling",
|
|
3427
|
+
result: { url: videoRes.url, model: "p-video" }
|
|
3428
|
+
});
|
|
3429
|
+
return;
|
|
3430
|
+
}
|
|
3431
|
+
const input = {
|
|
3432
|
+
model,
|
|
3433
|
+
prompt: request.prompt ?? "",
|
|
3434
|
+
aspect_ratio: request.aspectRatio ?? request.aspect_ratio ?? "1:1",
|
|
3435
|
+
...request.image ? { image: request.image } : {},
|
|
3436
|
+
...request.duration ? { duration: request.duration } : {},
|
|
3437
|
+
...request.resolution ? { resolution: request.resolution } : {},
|
|
3438
|
+
...request.seed !== void 0 ? { seed: request.seed } : {}
|
|
3439
|
+
};
|
|
3440
|
+
const res = await generate(apiKey, input, {
|
|
3441
|
+
signal,
|
|
3442
|
+
onProgress: handleProgress
|
|
3443
|
+
});
|
|
3444
|
+
stages.push({
|
|
3445
|
+
stage: "polling",
|
|
3446
|
+
result: { url: res.url, model: res.model }
|
|
3447
|
+
});
|
|
3448
|
+
} catch (err) {
|
|
3449
|
+
stages.push({
|
|
3450
|
+
stage: "processing",
|
|
3451
|
+
error: err instanceof Error ? err : new Error(String(err))
|
|
3452
|
+
});
|
|
3453
|
+
} finally {
|
|
3454
|
+
done = true;
|
|
3455
|
+
wake();
|
|
3456
|
+
}
|
|
3457
|
+
})();
|
|
3458
|
+
while (!done || stages.length > 0) {
|
|
3459
|
+
if (stages.length === 0 && !done) {
|
|
3460
|
+
await new Promise((resolve) => {
|
|
3461
|
+
notify = resolve;
|
|
3462
|
+
});
|
|
3463
|
+
notify = null;
|
|
3464
|
+
}
|
|
3465
|
+
while (stages.length > 0) {
|
|
3466
|
+
const nextStage = stages.shift();
|
|
3467
|
+
if (!nextStage) continue;
|
|
3468
|
+
yield nextStage;
|
|
3469
|
+
if (nextStage.error) {
|
|
3470
|
+
throw nextStage.error;
|
|
3471
|
+
}
|
|
3472
|
+
}
|
|
2595
3473
|
}
|
|
2596
|
-
|
|
2597
|
-
yield { stage: "polling", result: { url: resultUrl, model: modelId } };
|
|
3474
|
+
await promise;
|
|
2598
3475
|
}
|
|
2599
3476
|
|
|
2600
3477
|
// src/providers/pruna/pruna.provider.ts
|