@umituz/web-ai 1.0.2 → 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.
@@ -2555,39 +2555,811 @@ function createFalProvider(config) {
2555
2555
  return new FalProvider(config);
2556
2556
  }
2557
2557
 
2558
- // src/providers/pruna/pruna-generate.ts
2559
- var prunaCorePromise = null;
2560
- async function loadPrunaCore() {
2561
- if (!prunaCorePromise) {
2562
- const specifier = "@umituz/pruna-provider/core";
2563
- prunaCorePromise = import(specifier);
2558
+ // src/providers/pruna/client/core/constants/limits.ts
2559
+ var DEFAULT_ASPECT_RATIO = "16:9";
2560
+ var P_VIDEO_DEFAULTS = {
2561
+ duration: 5,
2562
+ resolution: "720p",
2563
+ fps: 24,
2564
+ draft: false,
2565
+ promptUpsampling: true
2566
+ };
2567
+ var POLL_DEFAULTS = {
2568
+ intervalMs: 3e3,
2569
+ maxAttempts: 120,
2570
+ maxIntervalMs: 1e4,
2571
+ backoffBase: 1.5,
2572
+ jitterPercent: 0.1
2573
+ };
2574
+ var DEFAULT_DEDUPLICATOR_TTL_MS = 3e4;
2575
+ var DEDUPLICATOR_CLEANUP_GRACE_MS = 100;
2576
+
2577
+ // src/providers/pruna/client/core/constants/network.ts
2578
+ var HTTPS_PREFIX = "https://";
2579
+ var HTTP_PREFIX = "http://";
2580
+ var BASE64_MARKER = "base64,";
2581
+ var PRUNA_BASE_URL = "https://api.pruna.ai";
2582
+ var PRUNA_PREDICTIONS_URL = `${PRUNA_BASE_URL}/v1/predictions`;
2583
+ var PRUNA_FILES_URL = `${PRUNA_BASE_URL}/v1/files`;
2584
+ var AUTH_FAILURE_STATUSES = [401, 403];
2585
+ var MIN_API_KEY_LENGTH = 1;
2586
+ var MAX_API_KEY_LENGTH = 256;
2587
+
2588
+ // src/providers/pruna/client/core/constants/mime-types.ts
2589
+ var MIME_PNG = "image/png";
2590
+ var MIME_JPEG = "image/jpeg";
2591
+ var MIME_WEBP = "image/webp";
2592
+ var DEFAULT_IMAGE_MIME = MIME_PNG;
2593
+ var MIME_FILE_EXTENSION = {
2594
+ [MIME_PNG]: "png",
2595
+ [MIME_JPEG]: "jpg",
2596
+ [MIME_WEBP]: "webp"
2597
+ };
2598
+ var IMAGE_SIGNATURES = {
2599
+ PNG: [137, 80],
2600
+ JPEG: [255, 216],
2601
+ WEBP_RIFF: [82, 73]
2602
+ };
2603
+
2604
+ // src/providers/pruna/client/core/errors/cancellation-error.ts
2605
+ var CANCELLATION_MESSAGE = "Request cancelled by user";
2606
+ var CancellationError = class extends Error {
2607
+ constructor(message = CANCELLATION_MESSAGE) {
2608
+ super(message);
2609
+ this.name = "CancellationError";
2610
+ }
2611
+ };
2612
+
2613
+ // src/providers/pruna/client/core/errors/authentication-error.ts
2614
+ var AUTHENTICATION_MESSAGE = "Authentication failed. Please check your API key.";
2615
+ var AuthenticationError = class extends Error {
2616
+ constructor(message = AUTHENTICATION_MESSAGE) {
2617
+ super(message);
2618
+ this.name = "AuthenticationError";
2619
+ }
2620
+ };
2621
+
2622
+ // src/providers/pruna/client/core/errors/timeout-error.ts
2623
+ var TIMEOUT_MESSAGE = "Generation timed out. Maximum polling attempts reached.";
2624
+ var TimeoutError = class extends Error {
2625
+ constructor(message = TIMEOUT_MESSAGE) {
2626
+ super(message);
2627
+ this.name = "TimeoutError";
2628
+ }
2629
+ };
2630
+
2631
+ // src/providers/pruna/client/core/errors/validation-error.ts
2632
+ var ValidationError = class extends Error {
2633
+ field;
2634
+ reason;
2635
+ receivedValue;
2636
+ constructor(context) {
2637
+ super(`Invalid ${context.field}: ${context.reason}`);
2638
+ this.name = "ValidationError";
2639
+ this.field = context.field;
2640
+ this.reason = context.reason;
2641
+ this.receivedValue = context.receivedValue;
2564
2642
  }
2565
- return prunaCorePromise;
2643
+ };
2644
+
2645
+ // src/providers/pruna/client/core/utils/base64.ts
2646
+ var globalScope = globalThis;
2647
+ var hasBuffer = typeof globalScope.Buffer?.from === "function";
2648
+ function base64ToBytes(raw) {
2649
+ if (hasBuffer) {
2650
+ const bufferFactory = globalScope.Buffer;
2651
+ if (!bufferFactory) {
2652
+ throw new Error("Buffer unavailable despite detection flag");
2653
+ }
2654
+ const buf = bufferFactory.from(raw, "base64");
2655
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
2656
+ }
2657
+ const decoded = atob(raw);
2658
+ return Uint8Array.from(decoded, (char) => char.charCodeAt(0));
2566
2659
  }
2567
- async function* generateWithPruna(request, apiKey, signal, onProgress) {
2568
- const prunaCore = await loadPrunaCore();
2569
- if (prunaCore.generateWithPruna) {
2570
- yield* prunaCore.generateWithPruna(request, apiKey, signal, onProgress);
2571
- return;
2572
- }
2573
- if (!prunaCore.submitPrediction || !prunaCore.pollForResult) {
2574
- throw new Error("@umituz/pruna-provider/core does not export required functions");
2575
- }
2576
- const modelId = request.model || (request.image ? "p-image-edit" : "p-image");
2577
- const prediction = await prunaCore.submitPrediction(modelId, request, apiKey, signal, onProgress);
2578
- if (prediction.output && typeof prediction.output === "object" && "url" in prediction.output) {
2579
- yield {
2580
- stage: "predicting",
2581
- result: { url: prediction.output.url, model: modelId }
2660
+
2661
+ // src/providers/pruna/client/core/utils/mime-detector.ts
2662
+ var MIN_SIGNATURE_BYTES = 2;
2663
+ function matchesSignature(bytes, signature) {
2664
+ if (bytes.length < signature.length) return false;
2665
+ return signature.every((value, index) => bytes[index] === value);
2666
+ }
2667
+ function detectImageMime(bytes) {
2668
+ if (bytes.length < MIN_SIGNATURE_BYTES) return DEFAULT_IMAGE_MIME;
2669
+ if (matchesSignature(bytes, IMAGE_SIGNATURES.PNG)) return MIME_PNG;
2670
+ if (matchesSignature(bytes, IMAGE_SIGNATURES.JPEG)) return MIME_JPEG;
2671
+ if (matchesSignature(bytes, IMAGE_SIGNATURES.WEBP_RIFF)) return MIME_WEBP;
2672
+ return DEFAULT_IMAGE_MIME;
2673
+ }
2674
+
2675
+ // src/providers/pruna/client/core/utils/api-error-parser.ts
2676
+ async function parseApiError(response, fallback) {
2677
+ const payload = await response.json().catch(() => ({ message: response.statusText }));
2678
+ const message = payload.message ?? `${fallback}: ${response.status}`;
2679
+ const error = new Error(message);
2680
+ error.statusCode = response.status;
2681
+ return error;
2682
+ }
2683
+
2684
+ // src/providers/pruna/client/core/protocol/http-status.ts
2685
+ function isAuthFailureStatus(status) {
2686
+ return AUTH_FAILURE_STATUSES.includes(status);
2687
+ }
2688
+
2689
+ // src/providers/pruna/client/core/protocol/job-status.ts
2690
+ var TERMINAL_SUCCESS_STATUSES = ["succeeded", "completed"];
2691
+ var TERMINAL_FAILURE_STATUSES = ["failed"];
2692
+ function isTerminalSuccessStatus(status) {
2693
+ if (!status) return false;
2694
+ return TERMINAL_SUCCESS_STATUSES.includes(status);
2695
+ }
2696
+ function isTerminalFailureStatus(status) {
2697
+ if (!status) return false;
2698
+ return TERMINAL_FAILURE_STATUSES.includes(status);
2699
+ }
2700
+
2701
+ // src/providers/pruna/client/core/protocol/abort-signal-classifier.ts
2702
+ function isAbortError(err) {
2703
+ if (err instanceof DOMException && err.code === DOMException.ABORT_ERR) return true;
2704
+ if (err instanceof Error && err.name === "AbortError") return true;
2705
+ return false;
2706
+ }
2707
+
2708
+ // src/providers/pruna/client/core/protocol/pruna-url-builder.ts
2709
+ function isAbsoluteHttpUrl(value) {
2710
+ return value.startsWith(HTTPS_PREFIX) || value.startsWith(HTTP_PREFIX);
2711
+ }
2712
+ function isHttpsUrl(value) {
2713
+ return value.startsWith(HTTPS_PREFIX);
2714
+ }
2715
+ function buildPrunaApiUrl(pathOrUrl) {
2716
+ if (isAbsoluteHttpUrl(pathOrUrl)) return pathOrUrl;
2717
+ return `${PRUNA_BASE_URL}${pathOrUrl}`;
2718
+ }
2719
+ function buildFileUrlById(fileId) {
2720
+ return `${PRUNA_FILES_URL}/${fileId}`;
2721
+ }
2722
+
2723
+ // src/providers/pruna/client/core/math/exponential-backoff.ts
2724
+ function calculateExponentialBackoff2(inputs) {
2725
+ const {
2726
+ attempt,
2727
+ baseIntervalMs,
2728
+ maxIntervalMs = POLL_DEFAULTS.maxIntervalMs,
2729
+ jitterPercent = POLL_DEFAULTS.jitterPercent,
2730
+ growthBase = POLL_DEFAULTS.backoffBase
2731
+ } = inputs;
2732
+ const safeAttempt = Math.max(0, attempt);
2733
+ const safeBase = Math.max(0, baseIntervalMs);
2734
+ const exponentialDelay = Math.min(safeBase * Math.pow(growthBase, safeAttempt), maxIntervalMs);
2735
+ const jitter = exponentialDelay * jitterPercent * Math.random();
2736
+ return exponentialDelay + jitter;
2737
+ }
2738
+
2739
+ // src/providers/pruna/client/core/utils/uri-resolver.ts
2740
+ var uriCache = /* @__PURE__ */ new WeakMap();
2741
+ function stripBase64Prefix(image) {
2742
+ if (isHttpsUrl(image)) return image;
2743
+ const base64Index = image.indexOf(BASE64_MARKER);
2744
+ return base64Index !== -1 ? image.slice(base64Index + BASE64_MARKER.length) : image;
2745
+ }
2746
+ function readOutput(output) {
2747
+ if (typeof output === "string") return output;
2748
+ if (Array.isArray(output) && output.length > 0) return output[0] ?? null;
2749
+ if (output !== null && typeof output === "object" && "url" in output) {
2750
+ return output.url;
2751
+ }
2752
+ return null;
2753
+ }
2754
+ function extractUri(data) {
2755
+ const cached = uriCache.get(data);
2756
+ if (cached !== void 0) return cached;
2757
+ if (!isTerminalSuccessStatus(data.status)) {
2758
+ uriCache.set(data, null);
2759
+ return null;
2760
+ }
2761
+ const result = data.generation_url ?? readOutput(data.output) ?? data.video_url ?? data.data ?? null;
2762
+ uriCache.set(data, result);
2763
+ return result;
2764
+ }
2765
+ function resolveUri(uri) {
2766
+ return uri.startsWith("/") ? `${PRUNA_BASE_URL}${uri}` : uri;
2767
+ }
2768
+
2769
+ // src/providers/pruna/client/core/services/pruna-client.service.ts
2770
+ function buildFileExtension(mime) {
2771
+ return MIME_FILE_EXTENSION[mime] ?? "bin";
2772
+ }
2773
+ async function uploadImage(base64OrUrl, apiKey, onProgress) {
2774
+ if (isHttpsUrl(base64OrUrl)) return base64OrUrl;
2775
+ if (base64OrUrl.startsWith(HTTP_PREFIX)) {
2776
+ throw new Error("Only HTTPS URLs are supported for security.");
2777
+ }
2778
+ onProgress?.("uploading");
2779
+ const raw = stripBase64Prefix(base64OrUrl);
2780
+ let bytes;
2781
+ try {
2782
+ bytes = base64ToBytes(raw);
2783
+ } catch {
2784
+ throw new Error("Invalid image format. Provide base64 or a valid HTTPS URL.");
2785
+ }
2786
+ const mime = detectImageMime(bytes);
2787
+ const buffer = bytes.buffer.slice(
2788
+ bytes.byteOffset,
2789
+ bytes.byteOffset + bytes.byteLength
2790
+ );
2791
+ const blob = new Blob([buffer], { type: mime });
2792
+ const formData = new FormData();
2793
+ formData.append("content", blob, `upload.${buildFileExtension(mime)}`);
2794
+ const res = await fetch(PRUNA_FILES_URL, {
2795
+ method: "POST",
2796
+ headers: { apikey: apiKey },
2797
+ body: formData
2798
+ });
2799
+ if (!res.ok) {
2800
+ throw await parseApiError(res, "File upload error");
2801
+ }
2802
+ const data = await res.json();
2803
+ return data.urls?.get ?? buildFileUrlById(data.id ?? "");
2804
+ }
2805
+ async function submitPrediction(model, input, apiKey, signal, onProgress) {
2806
+ onProgress?.("predicting");
2807
+ const res = await fetch(PRUNA_PREDICTIONS_URL, {
2808
+ method: "POST",
2809
+ headers: {
2810
+ apikey: apiKey,
2811
+ Model: model,
2812
+ "Try-Sync": "true",
2813
+ "Content-Type": "application/json"
2814
+ },
2815
+ body: JSON.stringify({ input }),
2816
+ signal
2817
+ });
2818
+ if (!res.ok) {
2819
+ throw await parseApiError(res, "API error");
2820
+ }
2821
+ return res.json();
2822
+ }
2823
+ var GenerationFailedError = class extends Error {
2824
+ constructor(message) {
2825
+ super(message);
2826
+ this.name = "GenerationFailedError";
2827
+ }
2828
+ };
2829
+ async function attemptPoll(fullUrl, apiKey, signal) {
2830
+ let res;
2831
+ try {
2832
+ res = await fetch(fullUrl, { headers: { apikey: apiKey }, signal });
2833
+ } catch (err) {
2834
+ if (isAbortError(err)) throw new CancellationError();
2835
+ return { outcome: "transient-failure" };
2836
+ }
2837
+ if (!res.ok) {
2838
+ if (isAuthFailureStatus(res.status)) throw new AuthenticationError();
2839
+ return { outcome: "transient-failure" };
2840
+ }
2841
+ let data;
2842
+ try {
2843
+ data = await res.json();
2844
+ } catch {
2845
+ return { outcome: "transient-failure" };
2846
+ }
2847
+ if (isTerminalSuccessStatus(data.status)) {
2848
+ const uri = extractUri(data);
2849
+ if (uri) return { outcome: "succeeded", uri: resolveUri(uri) };
2850
+ return { outcome: "transient-failure" };
2851
+ }
2852
+ if (isTerminalFailureStatus(data.status)) {
2853
+ throw new GenerationFailedError(data.error ?? "Generation failed during processing.");
2854
+ }
2855
+ return { outcome: "continue" };
2856
+ }
2857
+ async function pollForResult(pollUrl, apiKey, maxAttempts = POLL_DEFAULTS.maxAttempts, intervalMs = POLL_DEFAULTS.intervalMs, signal, onProgress) {
2858
+ const fullUrl = isAbsoluteHttpUrl(pollUrl) ? pollUrl : buildPrunaApiUrl(pollUrl);
2859
+ const controller = new AbortController();
2860
+ const onExternalAbort = () => controller.abort();
2861
+ signal?.addEventListener("abort", onExternalAbort);
2862
+ try {
2863
+ for (let i = 0; i < maxAttempts; i++) {
2864
+ if (signal?.aborted) throw new CancellationError();
2865
+ const delay = calculateExponentialBackoff2({ attempt: i, baseIntervalMs: intervalMs });
2866
+ await new Promise((resolve) => setTimeout(resolve, delay));
2867
+ if (signal?.aborted) throw new CancellationError();
2868
+ onProgress?.("polling", i + 1);
2869
+ const result = await attemptPoll(fullUrl, apiKey, controller.signal);
2870
+ if (result.outcome === "succeeded" && result.uri) {
2871
+ return result.uri;
2872
+ }
2873
+ }
2874
+ throw new TimeoutError();
2875
+ } finally {
2876
+ signal?.removeEventListener("abort", onExternalAbort);
2877
+ controller.abort();
2878
+ }
2879
+ }
2880
+
2881
+ // src/providers/pruna/client/core/math/comparison-hash.ts
2882
+ function sortKeysDeep(value) {
2883
+ if (Array.isArray(value)) {
2884
+ return value.map(sortKeysDeep);
2885
+ }
2886
+ if (value !== null && typeof value === "object") {
2887
+ const record = value;
2888
+ return Object.keys(record).sort().reduce((acc, key) => {
2889
+ acc[key] = sortKeysDeep(record[key]);
2890
+ return acc;
2891
+ }, {});
2892
+ }
2893
+ return value;
2894
+ }
2895
+ function hashValue(value) {
2896
+ if (value === null || typeof value !== "object") {
2897
+ return String(value);
2898
+ }
2899
+ try {
2900
+ return JSON.stringify(sortKeysDeep(value));
2901
+ } catch {
2902
+ return String(value);
2903
+ }
2904
+ }
2905
+ function compositeHash(...values) {
2906
+ return values.map(hashValue).join("|");
2907
+ }
2908
+
2909
+ // src/providers/pruna/client/core/math/cache-key-derivation.ts
2910
+ function deriveGenerationCacheKey(apiKey, input) {
2911
+ return `${apiKey}:${compositeHash(input)}`;
2912
+ }
2913
+
2914
+ // src/providers/pruna/client/core/validation/api-key-validator.ts
2915
+ function assertValidApiKey(apiKey) {
2916
+ if (typeof apiKey !== "string") {
2917
+ throw new ValidationError({
2918
+ field: "apiKey",
2919
+ reason: "must be a string",
2920
+ receivedValue: typeof apiKey
2921
+ });
2922
+ }
2923
+ if (apiKey.length < MIN_API_KEY_LENGTH) {
2924
+ throw new ValidationError({
2925
+ field: "apiKey",
2926
+ reason: "must not be empty",
2927
+ receivedValue: apiKey
2928
+ });
2929
+ }
2930
+ if (apiKey.length > MAX_API_KEY_LENGTH) {
2931
+ throw new ValidationError({
2932
+ field: "apiKey",
2933
+ reason: `exceeds maximum length of ${MAX_API_KEY_LENGTH}`,
2934
+ receivedValue: apiKey.length
2935
+ });
2936
+ }
2937
+ }
2938
+
2939
+ // src/providers/pruna/client/core/validation/image-source-validator.ts
2940
+ function classifyImageSource(source) {
2941
+ if (source.startsWith(HTTPS_PREFIX)) return "https-url";
2942
+ if (source.startsWith(HTTP_PREFIX)) return "http-url";
2943
+ if (source.includes(BASE64_MARKER) || /^[A-Za-z0-9+/=]+$/.test(source)) return "base64";
2944
+ return "unknown";
2945
+ }
2946
+ function assertSecureImageSource(image, fieldName = "image") {
2947
+ if (typeof image !== "string") {
2948
+ throw new ValidationError({
2949
+ field: fieldName,
2950
+ reason: "must be a string",
2951
+ receivedValue: typeof image
2952
+ });
2953
+ }
2954
+ const kind = classifyImageSource(image);
2955
+ if (kind === "http-url") {
2956
+ throw new ValidationError({
2957
+ field: fieldName,
2958
+ reason: "HTTP URLs are not supported; use HTTPS or a base64 data URI",
2959
+ receivedValue: image
2960
+ });
2961
+ }
2962
+ if (kind === "unknown") {
2963
+ throw new ValidationError({
2964
+ field: fieldName,
2965
+ reason: "must be an HTTPS URL or a base64 data URI",
2966
+ receivedValue: typeof image
2967
+ });
2968
+ }
2969
+ }
2970
+
2971
+ // src/providers/pruna/client/core/validation/aspect-ratio-validator.ts
2972
+ var SUPPORTED_ASPECT_RATIOS = [
2973
+ "16:9",
2974
+ "9:16",
2975
+ "1:1",
2976
+ "4:3",
2977
+ "3:4",
2978
+ "3:2",
2979
+ "2:3"
2980
+ ];
2981
+ function isSupportedAspectRatio(value) {
2982
+ return typeof value === "string" && SUPPORTED_ASPECT_RATIOS.includes(value);
2983
+ }
2984
+ function assertValidAspectRatio(value, fieldName = "aspect_ratio") {
2985
+ if (value === void 0 || value === null) return;
2986
+ if (!isSupportedAspectRatio(value)) {
2987
+ throw new ValidationError({
2988
+ field: fieldName,
2989
+ reason: `must be one of ${SUPPORTED_ASPECT_RATIOS.join(", ")}`,
2990
+ receivedValue: value
2991
+ });
2992
+ }
2993
+ }
2994
+
2995
+ // src/providers/pruna/client/core/validation/resolution-validator.ts
2996
+ var SUPPORTED_RESOLUTIONS = ["720p", "1080p"];
2997
+ function isSupportedResolution(value) {
2998
+ return typeof value === "string" && SUPPORTED_RESOLUTIONS.includes(value);
2999
+ }
3000
+ function assertValidResolution(value, fieldName = "resolution") {
3001
+ if (value === void 0 || value === null) return;
3002
+ if (!isSupportedResolution(value)) {
3003
+ throw new ValidationError({
3004
+ field: fieldName,
3005
+ reason: `must be one of ${SUPPORTED_RESOLUTIONS.join(", ")}`,
3006
+ receivedValue: value
3007
+ });
3008
+ }
3009
+ }
3010
+
3011
+ // src/providers/pruna/client/core/validation/duration-validator.ts
3012
+ var MIN_VIDEO_DURATION_SECONDS = 1;
3013
+ var MAX_VIDEO_DURATION_SECONDS = 30;
3014
+ function isValidDuration(value) {
3015
+ return typeof value === "number" && Number.isFinite(value) && value >= MIN_VIDEO_DURATION_SECONDS && value <= MAX_VIDEO_DURATION_SECONDS && Number.isInteger(value);
3016
+ }
3017
+ function assertValidDuration(value, fieldName = "duration") {
3018
+ if (value === void 0 || value === null) return;
3019
+ if (!isValidDuration(value)) {
3020
+ throw new ValidationError({
3021
+ field: fieldName,
3022
+ reason: `must be an integer between ${MIN_VIDEO_DURATION_SECONDS} and ${MAX_VIDEO_DURATION_SECONDS} seconds`,
3023
+ receivedValue: value
3024
+ });
3025
+ }
3026
+ }
3027
+
3028
+ // src/providers/pruna/client/core/validation/prompt-validator.ts
3029
+ var MIN_PROMPT_LENGTH = 1;
3030
+ var MAX_PROMPT_LENGTH = 4e3;
3031
+ function assertValidPrompt(value, fieldName = "prompt") {
3032
+ if (typeof value !== "string") {
3033
+ throw new ValidationError({
3034
+ field: fieldName,
3035
+ reason: "must be a string",
3036
+ receivedValue: typeof value
3037
+ });
3038
+ }
3039
+ if (value.trim().length < MIN_PROMPT_LENGTH) {
3040
+ throw new ValidationError({
3041
+ field: fieldName,
3042
+ reason: "must not be empty or whitespace-only",
3043
+ receivedValue: value
3044
+ });
3045
+ }
3046
+ if (value.length > MAX_PROMPT_LENGTH) {
3047
+ throw new ValidationError({
3048
+ field: fieldName,
3049
+ reason: `exceeds maximum length of ${MAX_PROMPT_LENGTH} characters`,
3050
+ receivedValue: value.length
3051
+ });
3052
+ }
3053
+ }
3054
+
3055
+ // src/providers/pruna/client/core/validation/seed-validator.ts
3056
+ var MIN_SEED = -2147483648;
3057
+ var MAX_SEED = 2147483647;
3058
+ function isValidSeed(value) {
3059
+ return typeof value === "number" && Number.isFinite(value) && Number.isInteger(value) && value >= MIN_SEED && value <= MAX_SEED;
3060
+ }
3061
+ function assertValidSeed(value, fieldName = "seed") {
3062
+ if (value === void 0 || value === null) return;
3063
+ if (!isValidSeed(value)) {
3064
+ throw new ValidationError({
3065
+ field: fieldName,
3066
+ reason: `must be an integer in [${MIN_SEED}, ${MAX_SEED}]`,
3067
+ receivedValue: value
3068
+ });
3069
+ }
3070
+ }
3071
+
3072
+ // src/providers/pruna/client/core/protocol/input-type-guard.ts
3073
+ function isTextToImageInput(input) {
3074
+ return input.model === "p-image";
3075
+ }
3076
+ function isImageToImageInput(input) {
3077
+ return input.model === "p-image-edit";
3078
+ }
3079
+ function isImageToVideoInput(input) {
3080
+ return input.model === "p-video";
3081
+ }
3082
+
3083
+ // src/providers/pruna/client/core/utils/request-deduplicator.ts
3084
+ var RequestDeduplicator2 = class {
3085
+ pendingRequests = /* @__PURE__ */ new Map();
3086
+ ttl;
3087
+ constructor(ttl = DEFAULT_DEDUPLICATOR_TTL_MS) {
3088
+ this.ttl = ttl;
3089
+ }
3090
+ execute(key, fn) {
3091
+ const existing = this.pendingRequests.get(key);
3092
+ if (existing) {
3093
+ if (Date.now() - existing.timestamp < this.ttl) {
3094
+ return existing.promise;
3095
+ }
3096
+ this.pendingRequests.delete(key);
3097
+ }
3098
+ const promise = fn().finally(() => {
3099
+ setTimeout(() => {
3100
+ this.pendingRequests.delete(key);
3101
+ }, DEDUPLICATOR_CLEANUP_GRACE_MS);
3102
+ });
3103
+ this.pendingRequests.set(key, { promise, timestamp: Date.now() });
3104
+ return promise;
3105
+ }
3106
+ clear() {
3107
+ this.pendingRequests.clear();
3108
+ }
3109
+ size() {
3110
+ this.purgeExpired();
3111
+ return this.pendingRequests.size;
3112
+ }
3113
+ purgeExpired() {
3114
+ const now = Date.now();
3115
+ for (const [key, value] of this.pendingRequests) {
3116
+ if (now - value.timestamp >= this.ttl) {
3117
+ this.pendingRequests.delete(key);
3118
+ }
3119
+ }
3120
+ }
3121
+ };
3122
+ var globalDeduplicator = new RequestDeduplicator2();
3123
+
3124
+ // src/providers/pruna/client/generation/builders/text-to-image.builder.ts
3125
+ var TextToImageInputBuilder = class {
3126
+ model = "p-image";
3127
+ build(input, _context) {
3128
+ const payload = {
3129
+ prompt: input.prompt,
3130
+ aspect_ratio: input.aspect_ratio ?? DEFAULT_ASPECT_RATIO
2582
3131
  };
2583
- return;
3132
+ if (input.seed !== void 0) {
3133
+ payload.seed = input.seed;
3134
+ }
3135
+ return Promise.resolve(payload);
2584
3136
  }
2585
- const pollUrl = prediction.status_url || prediction.generation_url;
3137
+ };
3138
+
3139
+ // src/providers/pruna/client/generation/builders/image-to-image.builder.ts
3140
+ var ImageToImageInputBuilder = class {
3141
+ model = "p-image-edit";
3142
+ build(input, _context) {
3143
+ const payload = {
3144
+ images: [stripBase64Prefix(input.image)],
3145
+ prompt: input.prompt,
3146
+ aspect_ratio: input.aspect_ratio ?? DEFAULT_ASPECT_RATIO
3147
+ };
3148
+ if (input.seed !== void 0) {
3149
+ payload.seed = input.seed;
3150
+ }
3151
+ return Promise.resolve(payload);
3152
+ }
3153
+ };
3154
+
3155
+ // src/providers/pruna/client/generation/builders/image-to-video.builder.ts
3156
+ var ImageToVideoInputBuilder = class {
3157
+ model = "p-video";
3158
+ async build(input, context) {
3159
+ if (context.signal?.aborted) {
3160
+ throw new CancellationError();
3161
+ }
3162
+ const fileUrl = await uploadImage(
3163
+ input.image,
3164
+ context.apiKey,
3165
+ context.onProgress
3166
+ );
3167
+ return {
3168
+ image: fileUrl,
3169
+ prompt: input.prompt,
3170
+ duration: input.duration ?? P_VIDEO_DEFAULTS.duration,
3171
+ resolution: input.resolution ?? P_VIDEO_DEFAULTS.resolution,
3172
+ fps: P_VIDEO_DEFAULTS.fps,
3173
+ draft: input.draft ?? P_VIDEO_DEFAULTS.draft,
3174
+ aspect_ratio: input.aspect_ratio ?? DEFAULT_ASPECT_RATIO,
3175
+ prompt_upsampling: P_VIDEO_DEFAULTS.promptUpsampling
3176
+ };
3177
+ }
3178
+ };
3179
+
3180
+ // src/providers/pruna/client/generation/builders/model-input-builder.ts
3181
+ var ModelInputBuilderRegistry = class {
3182
+ builders = /* @__PURE__ */ new Map();
3183
+ register(builder) {
3184
+ this.builders.set(builder.model, builder);
3185
+ return this;
3186
+ }
3187
+ resolve(model) {
3188
+ const builder = this.builders.get(model);
3189
+ if (!builder) {
3190
+ throw new Error(`No input builder registered for model: ${model}`);
3191
+ }
3192
+ return builder;
3193
+ }
3194
+ };
3195
+
3196
+ // src/providers/pruna/client/generation/builders/builder-factory.ts
3197
+ function createDefaultBuilderRegistry() {
3198
+ return new ModelInputBuilderRegistry().register(new TextToImageInputBuilder()).register(new ImageToImageInputBuilder()).register(new ImageToVideoInputBuilder());
3199
+ }
3200
+
3201
+ // src/providers/pruna/client/generation/services/generation.service.ts
3202
+ var builderRegistry = createDefaultBuilderRegistry();
3203
+ function validateGenerateInput(input) {
3204
+ assertValidPrompt(input.prompt, `${input.model}.prompt`);
3205
+ assertValidAspectRatio(input.aspect_ratio, `${input.model}.aspect_ratio`);
3206
+ if (isTextToImageInput(input)) {
3207
+ assertValidSeed(input.seed, `${input.model}.seed`);
3208
+ } else if (isImageToImageInput(input)) {
3209
+ assertSecureImageSource(input.image, `${input.model}.image`);
3210
+ assertValidSeed(input.seed, `${input.model}.seed`);
3211
+ } else if (isImageToVideoInput(input)) {
3212
+ assertSecureImageSource(input.image, `${input.model}.image`);
3213
+ assertValidDuration(input.duration, `${input.model}.duration`);
3214
+ assertValidResolution(input.resolution, `${input.model}.resolution`);
3215
+ }
3216
+ }
3217
+ async function generate(apiKey, input, options = {}) {
3218
+ assertValidApiKey(apiKey);
3219
+ validateGenerateInput(input);
3220
+ const { signal, onProgress, useCache = true } = options;
3221
+ if (useCache) {
3222
+ const cacheKey = deriveGenerationCacheKey(apiKey, input);
3223
+ return globalDeduplicator.execute(
3224
+ cacheKey,
3225
+ () => generateInternal(apiKey, input, { signal, onProgress })
3226
+ );
3227
+ }
3228
+ return generateInternal(apiKey, input, { signal, onProgress });
3229
+ }
3230
+ async function generateInternal(apiKey, input, options) {
3231
+ const { signal, onProgress } = options;
3232
+ const builder = builderRegistry.resolve(input.model);
3233
+ const modelInput = await builder.build(input, { apiKey, signal, onProgress });
3234
+ const response = await submitPrediction(input.model, modelInput, apiKey, signal, onProgress);
3235
+ const syncUri = extractUri(response);
3236
+ if (syncUri) {
3237
+ return { url: resolveUri(syncUri), model: input.model };
3238
+ }
3239
+ const pollUrl = response.get_url ?? response.status_url;
2586
3240
  if (!pollUrl) {
2587
- throw new Error("Pruna prediction response missing polling URL");
3241
+ throw new Error("Pruna API returned no result and no polling URL.");
3242
+ }
3243
+ const url = await pollForResult(
3244
+ pollUrl,
3245
+ apiKey,
3246
+ POLL_DEFAULTS.maxAttempts,
3247
+ POLL_DEFAULTS.intervalMs,
3248
+ signal,
3249
+ onProgress
3250
+ );
3251
+ return { url, model: input.model };
3252
+ }
3253
+ async function generateImageThenVideo(apiKey, input, options = {}) {
3254
+ assertValidApiKey(apiKey);
3255
+ assertValidPrompt(input.prompt, "text-to-video.prompt");
3256
+ assertValidAspectRatio(input.aspect_ratio, "text-to-video.aspect_ratio");
3257
+ assertValidDuration(input.duration, "text-to-video.duration");
3258
+ assertValidResolution(input.resolution, "text-to-video.resolution");
3259
+ const { signal, onProgress } = options;
3260
+ const aspectRatio = input.aspect_ratio ?? DEFAULT_ASPECT_RATIO;
3261
+ onProgress?.("predicting", 1);
3262
+ const imageResult = await generate(
3263
+ apiKey,
3264
+ { model: "p-image", prompt: input.prompt, aspect_ratio: aspectRatio },
3265
+ { signal }
3266
+ );
3267
+ onProgress?.("predicting", 2);
3268
+ return generate(
3269
+ apiKey,
3270
+ {
3271
+ model: "p-video",
3272
+ prompt: input.prompt,
3273
+ image: imageResult.url,
3274
+ duration: input.duration ?? P_VIDEO_DEFAULTS.duration,
3275
+ resolution: input.resolution ?? P_VIDEO_DEFAULTS.resolution,
3276
+ aspect_ratio: aspectRatio,
3277
+ draft: input.draft ?? P_VIDEO_DEFAULTS.draft
3278
+ },
3279
+ { signal, onProgress }
3280
+ );
3281
+ }
3282
+
3283
+ // src/providers/pruna/pruna-generate.ts
3284
+ async function* generateWithPruna(request, apiKey, signal, onProgress) {
3285
+ const stages = [];
3286
+ let notify = null;
3287
+ let done = false;
3288
+ const wake = () => {
3289
+ const fn = notify;
3290
+ if (fn) {
3291
+ notify = null;
3292
+ fn();
3293
+ }
3294
+ };
3295
+ const handleProgress = (stage) => {
3296
+ stages.push({ stage });
3297
+ onProgress?.(stage);
3298
+ wake();
3299
+ };
3300
+ const promise = (async () => {
3301
+ try {
3302
+ const model = request.model ?? (request.image ? "p-image-edit" : "p-image");
3303
+ if (model === "p-video" && !request.image && request.prompt) {
3304
+ const videoRes = await generateImageThenVideo(
3305
+ apiKey,
3306
+ {
3307
+ prompt: request.prompt,
3308
+ duration: request.duration ?? 5,
3309
+ aspect_ratio: request.aspectRatio ?? request.aspect_ratio ?? "16:9"
3310
+ },
3311
+ { signal, onProgress: handleProgress }
3312
+ );
3313
+ stages.push({
3314
+ stage: "polling",
3315
+ result: { url: videoRes.url, model: "p-video" }
3316
+ });
3317
+ return;
3318
+ }
3319
+ const input = {
3320
+ model,
3321
+ prompt: request.prompt ?? "",
3322
+ aspect_ratio: request.aspectRatio ?? request.aspect_ratio ?? "1:1",
3323
+ ...request.image ? { image: request.image } : {},
3324
+ ...request.duration ? { duration: request.duration } : {},
3325
+ ...request.resolution ? { resolution: request.resolution } : {},
3326
+ ...request.seed !== void 0 ? { seed: request.seed } : {}
3327
+ };
3328
+ const res = await generate(apiKey, input, {
3329
+ signal,
3330
+ onProgress: handleProgress
3331
+ });
3332
+ stages.push({
3333
+ stage: "polling",
3334
+ result: { url: res.url, model: res.model }
3335
+ });
3336
+ } catch (err) {
3337
+ stages.push({
3338
+ stage: "processing",
3339
+ error: err instanceof Error ? err : new Error(String(err))
3340
+ });
3341
+ } finally {
3342
+ done = true;
3343
+ wake();
3344
+ }
3345
+ })();
3346
+ while (!done || stages.length > 0) {
3347
+ if (stages.length === 0 && !done) {
3348
+ await new Promise((resolve) => {
3349
+ notify = resolve;
3350
+ });
3351
+ notify = null;
3352
+ }
3353
+ while (stages.length > 0) {
3354
+ const nextStage = stages.shift();
3355
+ if (!nextStage) continue;
3356
+ yield nextStage;
3357
+ if (nextStage.error) {
3358
+ throw nextStage.error;
3359
+ }
3360
+ }
2588
3361
  }
2589
- const resultUrl = await prunaCore.pollForResult(pollUrl, apiKey, 60, 2e3, signal, onProgress);
2590
- yield { stage: "polling", result: { url: resultUrl, model: modelId } };
3362
+ await promise;
2591
3363
  }
2592
3364
 
2593
3365
  // src/providers/pruna/pruna.provider.ts
@@ -3206,7 +3978,9 @@ exports.API_ENDPOINTS = API_ENDPOINTS;
3206
3978
  exports.AnthropicHttpTransport = AnthropicHttpTransport;
3207
3979
  exports.AnthropicProvider = AnthropicProvider;
3208
3980
  exports.AnthropicRequestBuilder = AnthropicRequestBuilder;
3981
+ exports.AuthenticationError = AuthenticationError;
3209
3982
  exports.BaseProvider = BaseProvider;
3983
+ exports.CancellationError = CancellationError;
3210
3984
  exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
3211
3985
  exports.DEFAULT_GENERATION_CONFIG = DEFAULT_GENERATION_CONFIG;
3212
3986
  exports.DEFAULT_MODELS = DEFAULT_MODELS;
@@ -3215,6 +3989,7 @@ exports.GEMINI_TIERS = GEMINI_TIERS;
3215
3989
  exports.GROQ_MODELS = GROQ_MODELS;
3216
3990
  exports.GROQ_TIERS = GROQ_TIERS;
3217
3991
  exports.GeminiProvider = GeminiProvider;
3992
+ exports.GenerationFailedError = GenerationFailedError;
3218
3993
  exports.GroqChatRequestBuilder = GroqChatRequestBuilder;
3219
3994
  exports.GroqConfigStore = GroqConfigStore;
3220
3995
  exports.GroqHttpClient = GroqHttpClient;
@@ -3225,6 +4000,8 @@ exports.ProviderFactory = ProviderFactory;
3225
4000
  exports.PrunaProvider = PrunaProvider;
3226
4001
  exports.TIMEOUTS = TIMEOUTS;
3227
4002
  exports.TextGenerationService = TextGenerationService;
4003
+ exports.TimeoutError = TimeoutError;
4004
+ exports.ValidationError = ValidationError;
3228
4005
  exports.configureProvider = configureProvider;
3229
4006
  exports.consumeAnthropicStream = consumeAnthropicStream;
3230
4007
  exports.consumeGroqStream = consumeGroqStream;
@@ -3240,14 +4017,19 @@ exports.defaultEffortForModel = defaultEffortForModel;
3240
4017
  exports.extractContentFromSsePayload = extractContentFromSsePayload;
3241
4018
  exports.extractTextFromMessages = extractTextFromMessages;
3242
4019
  exports.formatMessagesForDisplay = formatMessagesForDisplay;
4020
+ exports.generateImageThenVideo = generateImageThenVideo;
4021
+ exports.generatePruna = generate;
3243
4022
  exports.generateWithPruna = generateWithPruna;
3244
4023
  exports.getProvider = getProvider;
3245
4024
  exports.isMediaProvider = isMediaProvider;
3246
4025
  exports.isTextProvider = isTextProvider;
3247
4026
  exports.mapAnthropicStopReason = mapAnthropicStopReason;
4027
+ exports.pollForResult = pollForResult;
3248
4028
  exports.promptToMessages = promptToMessages;
3249
4029
  exports.requestStructuredJson = requestStructuredJson;
3250
4030
  exports.resetProvider = resetProvider;
4031
+ exports.submitPrediction = submitPrediction;
3251
4032
  exports.toGroqMessages = toGroqMessages;
4033
+ exports.uploadImage = uploadImage;
3252
4034
  //# sourceMappingURL=index.cjs.map
3253
4035
  //# sourceMappingURL=index.cjs.map