@runappsai/sdk 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -7
- package/dist/client.d.ts +6 -6
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +9 -3
- package/dist/client.js.map +1 -1
- package/dist/sdk.umd.js +2 -2
- package/dist/sdk.umd.js.map +1 -1
- package/package.json +1 -1
- package/src/client.ts +15 -8
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
There are two ways to use it:
|
|
6
6
|
|
|
7
|
-
- **In an app you publish on RunApps.** Users sign in with their RunApps account and pay for their own usage. You never hold a key
|
|
7
|
+
- **In an app you publish on RunApps.** Users sign in with their RunApps account and pay for their own usage. You never hold a key: create the client without one, `new RunApps()`, and it signs the user in.
|
|
8
8
|
- **From your own code.** A server, script or CLI uses a personal API key (`rk_…`), billed to you.
|
|
9
9
|
|
|
10
10
|
Both use the base URL `https://www.runapps.ai` and the same OpenAI-compatible API under `/v1`.
|
|
@@ -24,7 +24,7 @@ Or load it with a script tag, which defines the global `RunApps`:
|
|
|
24
24
|
```html
|
|
25
25
|
<script src="https://cdn.jsdelivr.net/npm/@runappsai/sdk/dist/sdk.umd.js"></script>
|
|
26
26
|
<script>
|
|
27
|
-
const client = new RunApps(
|
|
27
|
+
const client = new RunApps(); // no key: users sign in with RunApps
|
|
28
28
|
</script>
|
|
29
29
|
```
|
|
30
30
|
|
|
@@ -40,8 +40,7 @@ Create the app on the dashboard, under **Creator → Publish**. It gets its slug
|
|
|
40
40
|
import { RunApps } from "@runappsai/sdk";
|
|
41
41
|
|
|
42
42
|
const client = new RunApps({
|
|
43
|
-
|
|
44
|
-
project: "my-tool", // the draft's slug; it stays the same after you upload
|
|
43
|
+
project: "my-tool", // the draft's slug; it stays the same after you upload
|
|
45
44
|
});
|
|
46
45
|
|
|
47
46
|
const resp = await client.chat.create({
|
|
@@ -71,7 +70,7 @@ client.auth?.hasFreshToken(); // avoid showing a "sign in" button needles
|
|
|
71
70
|
|
|
72
71
|
The SDK holds one token per user per app. It draws a small activity badge while it works; turn it off with `showIdentityBadge: false`, or move it with `badgePosition`.
|
|
73
72
|
|
|
74
|
-
`project` is optional on `*.runapps.dev`, where the address already says which app it is. It is required on localhost and when the client runs on a personal key. Sign-in only works on the app's own `*.runapps.dev` address and on `http://localhost`.
|
|
73
|
+
`project` is optional on `*.runapps.dev`, where the address already says which app it is. It is required on localhost and when the client runs on a personal key. Sign-in only works on the app's own `*.runapps.dev` address and on `http://localhost`. With no key, a browser client signs the user in on its own; outside a browser there is no one to sign in, so pass `apiKey`.
|
|
75
74
|
|
|
76
75
|
### 3. Private prompts
|
|
77
76
|
|
|
@@ -160,7 +159,7 @@ curl https://www.runapps.ai/v1/chat/completions \
|
|
|
160
159
|
-d '{"model": "Claude Sonnet 4.6", "messages": [{"role": "user", "content": "Hello!"}]}'
|
|
161
160
|
```
|
|
162
161
|
|
|
163
|
-
Never put an `rk_…` key in a frontend; an app on RunApps
|
|
162
|
+
Never put an `rk_…` key in a frontend; an app on RunApps creates its client without a key. `baseURL` overrides the base URL in either mode.
|
|
164
163
|
|
|
165
164
|
## Chat
|
|
166
165
|
|
|
@@ -399,7 +398,7 @@ Helpers: `hasCapabilityTag`, `acceptsModality`, `getOptionsSchema`, `acceptsFiel
|
|
|
399
398
|
|
|
400
399
|
### Upgrading from `@runjobsai/sdk`
|
|
401
400
|
|
|
402
|
-
The package was renamed. Install `@runappsai/sdk` and change your imports; the API is the same. Users signed in with 0.2.1 or later stay signed in after the upgrade. `
|
|
401
|
+
The package was renamed. Install `@runappsai/sdk` and change your imports; the API is the same. Users signed in with 0.2.1 or later stay signed in after the upgrade. `authProvider` no longer needs to be set: a browser client without a key signs the user in. `RunJobs` still works as a deprecated alias of `RunApps`, and so does `authProvider: "runjobs"`.
|
|
403
402
|
|
|
404
403
|
## License
|
|
405
404
|
|
package/dist/client.d.ts
CHANGED
|
@@ -22,8 +22,8 @@ import { SDKEvents } from "./events.js";
|
|
|
22
22
|
*/
|
|
23
23
|
export type AuthProvider = "static" | "runapps" | "runjobs";
|
|
24
24
|
export interface ClientOptions {
|
|
25
|
-
/**
|
|
26
|
-
*
|
|
25
|
+
/** A personal API key (`rk_…`) or another static key. Leave it out in an
|
|
26
|
+
* app published on RunApps: the browser client then signs the user in. */
|
|
27
27
|
apiKey?: string;
|
|
28
28
|
/**
|
|
29
29
|
* Dynamic API key resolver. See `AuthProvider` for the typical
|
|
@@ -33,9 +33,9 @@ export interface ClientOptions {
|
|
|
33
33
|
*/
|
|
34
34
|
apiKeyResolver?: () => string | Promise<string>;
|
|
35
35
|
/**
|
|
36
|
-
* Auth strategy
|
|
37
|
-
*
|
|
38
|
-
*
|
|
36
|
+
* Auth strategy. Rarely needed: in a browser with no `apiKey` /
|
|
37
|
+
* `apiKeyResolver` the client uses `"runapps"` (the platform sign-in),
|
|
38
|
+
* otherwise `"static"` (the key you pass).
|
|
39
39
|
*/
|
|
40
40
|
authProvider?: AuthProvider;
|
|
41
41
|
/**
|
|
@@ -93,7 +93,7 @@ export interface ClientOptions {
|
|
|
93
93
|
* ```html
|
|
94
94
|
* <script src="https://cdn.jsdelivr.net/npm/@runappsai/sdk/dist/sdk.umd.js"></script>
|
|
95
95
|
* <script>
|
|
96
|
-
* const client = new RunApps
|
|
96
|
+
* const client = new RunApps();
|
|
97
97
|
* const res = await client.chat.create({
|
|
98
98
|
* model: "gpt-4o-mini",
|
|
99
99
|
* messages: [{ role: "user", content: "hello" }],
|
package/dist/client.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AACxC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAC5C,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC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IAAI,WAAW,GAAG,IAAI,CAE7B;CACF"}
|
package/dist/client.js
CHANGED
|
@@ -21,7 +21,7 @@ const DEFAULT_BASE_URL = "https://www.runapps.ai";
|
|
|
21
21
|
* ```html
|
|
22
22
|
* <script src="https://cdn.jsdelivr.net/npm/@runappsai/sdk/dist/sdk.umd.js"></script>
|
|
23
23
|
* <script>
|
|
24
|
-
* const client = new RunApps
|
|
24
|
+
* const client = new RunApps();
|
|
25
25
|
* const res = await client.chat.create({
|
|
26
26
|
* model: "gpt-4o-mini",
|
|
27
27
|
* messages: [{ role: "user", content: "hello" }],
|
|
@@ -66,7 +66,13 @@ export class RunApps {
|
|
|
66
66
|
*/
|
|
67
67
|
events = new SDKEvents();
|
|
68
68
|
constructor(options = {}) {
|
|
69
|
-
|
|
69
|
+
// With no key and no explicit authProvider, a browser client uses the
|
|
70
|
+
// platform sign-in: `new RunApps()` is all an app needs. Elsewhere
|
|
71
|
+
// (Node, workers without a window) there is no one to sign in.
|
|
72
|
+
const provider = options.authProvider ??
|
|
73
|
+
(!options.apiKey && !options.apiKeyResolver && typeof window !== "undefined"
|
|
74
|
+
? "runapps"
|
|
75
|
+
: "static");
|
|
70
76
|
let apiKeyResolver = options.apiKeyResolver;
|
|
71
77
|
let baseURL = options.baseURL;
|
|
72
78
|
let onUnauthorized;
|
|
@@ -107,7 +113,7 @@ export class RunApps {
|
|
|
107
113
|
onUnauthorized = () => auth.invalidate();
|
|
108
114
|
}
|
|
109
115
|
if (!options.apiKey && !apiKeyResolver) {
|
|
110
|
-
throw new Error("runapps: pass
|
|
116
|
+
throw new Error("runapps: pass `apiKey` (or `apiKeyResolver`); outside a browser there is no sign-in to fall back to");
|
|
111
117
|
}
|
|
112
118
|
const transport = new Transport({
|
|
113
119
|
baseURL: baseURL ?? DEFAULT_BASE_URL,
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":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AAC,UAAU,GAAG,IAAI,iBAAiB,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IAClE,CAAC;IAED;gCAC4B;IAC5B,MAAM;QACJ,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC;IACtB,CAAC;IAED;;;;;;OAMG;IACH,OAAO;QACL,IAAI,CAAC,IAAI,EAAE,OAAO,EAAE,CAAC;IACvB,CAAC;IAED,iEAAiE;IACjE,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,IAAI,EAAE,IAAI,IAAI,IAAI,CAAC;IACjC,CAAC;CACF"}
|
package/dist/sdk.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var RunApps=(()=>{var J=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var gt=Object.prototype.hasOwnProperty;var mt=(r,e,t)=>e in r?J(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var ht=(r,e)=>{for(var t in e)J(r,t,{get:e[t],enumerable:!0})},ft=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of dt(e))!gt.call(r,s)&&s!==t&&J(r,s,{get:()=>e[s],enumerable:!(n=pt(e,s))||n.enumerable});return r};var bt=r=>ft(J({},"__esModule",{value:!0}),r);var l=(r,e,t)=>mt(r,typeof e!="symbol"?e+"":e,t);var Yt={};ht(Yt,{APIError:()=>x,ActivityTracker:()=>C,BrowserAuth:()=>A,Client:()=>T,RunApps:()=>T,RunJobs:()=>T,SDKEvents:()=>k,ServerTools:()=>Ce,acceptsField:()=>nt,acceptsModality:()=>De,allowedValuesFor:()=>st,assistantMessage:()=>Te,audioPart:()=>Ue,decodeMediaUrl:()=>B,defaultVoice:()=>Le,encodeImageUrl:()=>Ne,getOptionsSchema:()=>L,hasCapabilityTag:()=>je,imagePart:()=>Me,newRequestId:()=>D,requiresField:()=>rt,supportsInstructText:()=>$e,supportsVoiceClone:()=>Fe,systemMessage:()=>Ae,textPart:()=>Ie,toolResultMessage:()=>Re,userMessage:()=>Ee,userMessageParts:()=>Pe,validateRequest:()=>at,videoPart:()=>Oe});var x=class extends Error{constructor(t,n,s){super(`runapps: ${t} ${n}: ${s}`);l(this,"statusCode");l(this,"type");this.name="APIError",this.statusCode=t,this.type=n}};var V=class{constructor(e){l(this,"baseURL");l(this,"apiKey");l(this,"apiKeyResolver");l(this,"onUnauthorized");l(this,"fetchImpl");if(!e.apiKey&&!e.apiKeyResolver)throw new Error("RunApps: pass either `apiKey` or `apiKeyResolver` when constructing the client");this.baseURL=e.baseURL.replace(/\/+$/,""),this.apiKey=e.apiKey,this.apiKeyResolver=e.apiKeyResolver,this.onUnauthorized=e.onUnauthorized,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis)}async resolveToken(){return this.apiKeyResolver?await this.apiKeyResolver():this.apiKey??""}async fetchWithAuthRetry(e,t){let n=this.baseURL+e,s=await this.fetchImpl(n,await this.buildInit(t));if(s.status!==401||!this.onUnauthorized)return s;try{await this.onUnauthorized()}catch{return s}return s=await this.fetchImpl(n,await this.buildInit(t)),s}async buildInit(e){let t=await e();return t.cache?t:{...t,cache:"no-store"}}async postJSON(e,t,n){let s=await this.fetchWithAuthRetry(e,async()=>({method:"POST",headers:await this.jsonHeaders(),body:JSON.stringify(t),signal:n?.signal}));if(!s.ok)throw await this.parseError(s);return await s.json()}async getJSON(e,t){let n=await this.fetchWithAuthRetry(e,async()=>({method:"GET",headers:await this.authHeaders(),signal:t?.signal}));if(!n.ok)throw await this.parseError(n);return await n.json()}async getRaw(e,t){let n=await this.fetchWithAuthRetry(e,async()=>({method:"GET",headers:await this.authHeaders(),signal:t?.signal}));if(!n.ok)throw await this.parseError(n);let s=new Uint8Array(await n.arrayBuffer()),
|
|
2
|
-
`))!==-1;){let a=n.slice(0,i).replace(/\r$/,"");if(n=n.slice(i+1),!a.startsWith("data: "))continue;let u=a.slice(6).trim();if(u==="[DONE]")return;if(!u)continue;let c;try{c=JSON.parse(u)}catch(g){throw new Error(`runapps: decode stream chunk: ${g.message}`)}let d=c.error;if(d)throw new x(d.code??0,d.type??"upstream_error",d.message??u);yield c}}}finally{t.releaseLock()}}var je=(r,e)=>Array.isArray(r.capability_tags)&&r.capability_tags.some(t=>t.id===e),De=(r,e)=>Array.isArray(r.input_modalities)&&r.input_modalities.includes(e);function Be(r,e){let t=r.options?.[e];return typeof t=="boolean"?t:typeof t=="number"?t!==0:!1}var Fe=r=>Be(r,"supports_voice_clone"),$e=r=>Be(r,"supports_instruct_text"),Le=r=>{let e=r.options?.default_voice;return typeof e=="string"?e:null},W=class{constructor(e){l(this,"transport",e)}async list(e={},t){let n="/v1/models";return e.capability&&(n+=`?capability=${encodeURIComponent(e.capability)}`),(await this.transport.getJSON(n,t)).data}};var Y=class{constructor(e,t){l(this,"transport",e);l(this,"events",t)}async generate(e,t,n){return h(this.events,{model:e,capability:"image_generation"},()=>this.transport.postJSON("/v1/images/generations",{model:e,...t},n),s=>({costUSD:s.usage?.total_cost}))}async generateAsync(e,t,n){let s=n?.pollIntervalMs??2e3,o=n?.signal;return h(this.events,{model:e,capability:"image_generation"},async()=>{let a=await this.transport.postJSON("/v1/async/images/generations",{model:e,...t},{signal:o});for(;a.status!=="succeeded"&&a.status!=="failed";)await vt(s,o),a=await this.getAsyncStatus(a.id,{signal:o});if(a.status==="failed")throw new Error(a.error??"image generation failed");return{created:a.created_at??Math.floor(Date.now()/1e3),data:a.data??[],usage:a.usage??{total_cost:0}}},i=>({costUSD:i.usage?.total_cost}))}async submitGenerate(e,t,n){return h(this.events,{model:e,capability:"image_generation"},()=>this.transport.postJSON("/v1/async/images/generations",{model:e,...t},n))}async getAsyncStatus(e,t){return this.transport.getJSON(`/v1/async/images/generations/${encodeURIComponent(e)}`,t)}async edit(e,t,n){let s=xt(e,t);return h(this.events,{model:e,capability:"image_edit"},()=>this.transport.postMultipart("/v1/images/edits",s,n),o=>({costUSD:o.usage?.total_cost}))}};function vt(r,e){return new Promise((t,n)=>{if(e?.aborted){n(e.reason??new Error("aborted"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},r),o=()=>{clearTimeout(s),n(e.reason??new Error("aborted"))};e?.addEventListener("abort",o,{once:!0})})}function xt(r,e){let t=new FormData;return t.set("model",r),t.set("prompt",e.prompt),e.size&&t.set("size",e.size),e.n!==void 0&&t.set("n",String(e.n)),e.user&&t.set("user",e.user),t.set("image",Ke(e.image),e.image.filename),e.mask&&t.set("mask",Ke(e.mask),e.mask.filename),t}function Ke(r){let e=r.contentType??St(r.filename);return r.data instanceof Blob?r.data.type===e?r.data:new Blob([r.data],{type:e}):typeof r.data=="string"?new Blob([r.data],{type:e}):new Blob([r.data],{type:e})}function St(r){switch(r.toLowerCase().split(".").pop()??""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"webp":return"image/webp";case"gif":return"image/gif";default:return"application/octet-stream"}}function Ne(r){if(r instanceof Blob)throw new Error("encodeImageUrl: Blob input requires async; await blob.arrayBuffer() and pass the result instead");let e=r instanceof Uint8Array?r:new Uint8Array(r),t=kt(e),n=32768,s="";for(let i=0;i<e.length;i+=n)s+=String.fromCharCode.apply(null,Array.from(e.subarray(i,i+n)));let o=globalThis.btoa?globalThis.btoa(s):Buffer.from(s,"binary").toString("base64");return`data:${t};base64,${o}`}async function B(r){if(r.startsWith("data:")){let e=r.slice(5),t=e.indexOf(";"),n=e.indexOf(",");if(t===-1||n===-1||n<t)throw new Error("decodeMediaUrl: malformed data URI");let s=e.slice(0,t),o=e.slice(n+1);return{bytes:_t(o),contentType:s}}if(r.startsWith("http://")||r.startsWith("https://")){let e=await fetch(r);if(!e.ok)throw new Error(`decodeMediaUrl: upstream ${e.status}`);let t=await e.arrayBuffer();return{bytes:new Uint8Array(t),contentType:e.headers.get("Content-Type")??""}}throw new Error(`decodeMediaUrl: unsupported url scheme: ${r.slice(0,32)}`)}function _t(r){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function kt(r){return r.length>=8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71?"image/png":r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255?"image/jpeg":r.length>=6&&r[0]===71&&r[1]===73&&r[2]===70&&r[3]===56?"image/gif":r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===87&&r[9]===69&&r[10]===66&&r[11]===80?"image/webp":"application/octet-stream"}var X=class{constructor(e,t){l(this,"transport",e);l(this,"events",t)}async speech(e,t,n){return h(this.events,{model:e,capability:"text_to_speech"},async()=>{let s=await this.transport.postJSON("/v1/audio/speech",qe(e,t),n),{bytes:o,contentType:i}=await B(s.audio_url);return{data:o,contentType:i,usage:s.usage}},s=>({costUSD:s.usage?.total_cost}))}async speechAsync(e,t,n){return h(this.events,{model:e,capability:"text_to_speech"},async()=>{let s=await this.transport.postJSON("/v1/async/audio/speech",qe(e,t),n);if(!s.id)throw new Error("runapps: speech submit response missing job id");return Ct(this.transport,s.id,n)},s=>({costUSD:s.usage?.total_cost}))}async transcribe(e,t,n){let s=Ge(e,t);return h(this.events,{model:e,capability:"speech_to_text"},()=>this.transport.postMultipart("/v1/audio/transcriptions",s,n),o=>({costUSD:o.usage?.total_cost}))}async transcribeAsync(e,t,n){return h(this.events,{model:e,capability:"speech_to_text"},async()=>{let s=Ge(e,t),o=await this.transport.postMultipart("/v1/async/audio/transcriptions",s,n);if(!o.id)throw new Error("runapps: transcribe submit response missing job id");return Et(this.transport,o.id,n)},s=>({costUSD:s.usage?.total_cost}))}};async function Ct(r,e,t){let n=`/v1/async/audio/speech/${encodeURIComponent(e)}`,s=t?.pollIntervalMs??3e3;await Q(2e3,t?.signal);let i=Date.now()+600*1e3;for(;;){if(t?.signal?.aborted)throw new DOMException("speech poll aborted","AbortError");if(!t?.signal&&Date.now()>i)throw new Error("runapps: speech job timed out (10 min internal cap)");let a=await r.getJSON(n,t);if(a.status==="succeeded"){if(!a.audio_url)throw new Error("runapps: speech job succeeded but no audio_url returned");let{bytes:u,contentType:c}=await B(a.audio_url);return{data:u,contentType:c,usage:a.usage??{total_cost:0}}}if(a.status==="failed")throw new Error(a.error||"runapps: speech job failed");await Q(s,t?.signal)}}async function Et(r,e,t){let n=`/v1/async/audio/transcriptions/${encodeURIComponent(e)}`,s=t?.pollIntervalMs??3e3;await Q(2e3,t?.signal);let o=Date.now()+600*1e3;for(;;){if(t?.signal?.aborted)throw new DOMException("transcribe poll aborted","AbortError");if(!t?.signal&&Date.now()>o)throw new Error("runapps: transcribe job timed out (10 min internal cap)");let i=await r.getJSON(n,t);switch(i.status){case"succeeded":return At(i);case"failed":throw new Error(i.error||"runapps: transcribe job failed");case"queued":case"running":await Q(s,t?.signal);break;default:throw new Error(`runapps: unknown transcribe job status ${JSON.stringify(i.status)}`)}}}function At(r){let e={text:r.text??"",usage:r.usage??{total_cost:0}},t={};for(let[n,s]of Object.entries(r))n==="text"||n==="usage"||n==="id"||n==="status"||(t[n]=s);return Object.keys(t).length>0&&(e.raw=t),e}function Q(r,e){return new Promise((t,n)=>{if(e?.aborted){n(new DOMException("aborted","AbortError"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},r),o=()=>{clearTimeout(s),n(new DOMException("aborted","AbortError"))};e?.addEventListener("abort",o,{once:!0})})}function qe(r,e){let{extra:t,...n}=e,s={model:r,...n};if(t)for(let[o,i]of Object.entries(t))o in s||(s[o]=i);return s}function Ge(r,e){let t=new FormData;if(t.set("model",r),e.language&&t.set("language",e.language),e.prompt&&t.set("prompt",e.prompt),e.response_format&&t.set("response_format",e.response_format),e.timestamp_granularities)for(let o of e.timestamp_granularities)t.append("timestamp_granularities[]",o);e.user&&t.set("user",e.user);let n=e.file.contentType??Tt(e.file.filename),s=e.file.data instanceof Blob?e.file.data:new Blob([e.file.data],{type:n});return t.set("file",s,e.file.filename),t}function Tt(r){switch(r.toLowerCase().split(".").pop()??""){case"mp3":return"audio/mpeg";case"wav":return"audio/wav";case"m4a":return"audio/mp4";case"flac":return"audio/flac";case"ogg":return"audio/ogg";case"webm":return"audio/webm";default:return"application/octet-stream"}}var Z=class{constructor(e,t){l(this,"transport",e);l(this,"events",t)}async generate(e,t,n){return h(this.events,{model:e,capability:"video_generation"},()=>this.transport.postJSON("/v1/videos/generations",{model:e,...t},n))}async getStatus(e,t){return this.transport.getJSON(`/v1/videos/generations/${encodeURIComponent(e)}`,t)}async wait(e,t={}){let n=t.pollIntervalMs??5e3;for(;;){let s=await this.getStatus(e,{signal:t.signal});if(s.status==="succeeded"||s.status==="failed")return s;await Rt(n,t.signal)}}async getContent(e,t){return this.transport.getRaw(`/v1/videos/${encodeURIComponent(e)}/content`,t)}};function Rt(r,e){return new Promise((t,n)=>{if(e?.aborted){n(e.reason??new Error("aborted"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",o),t()},r),o=()=>{clearTimeout(s),n(e.reason??new Error("aborted"))};e?.addEventListener("abort",o,{once:!0})})}var ee=class{constructor(e,t){l(this,"transport",e);l(this,"events",t)}async step(e,t,n){return h(this.events,{model:e,capability:"computer_use"},()=>this.transport.postJSON("/v1/computer/step",{model:e,...t},n),s=>({totalTokens:s.usage?.completion_tokens,costUSD:s.usage?.total_cost}))}};function F(r,e){let t=e.replace(/^\/+/,"");return r+"/"+t.split("/").map(encodeURIComponent).join("/")}var te=class{constructor(e,t){l(this,"transport",e);l(this,"base");this.base=t?"/v1/p/"+encodeURIComponent(t)+"/files":"/v1/files"}async put(e,t,n){let s={};return n?.ifNoneMatch&&(s["If-None-Match"]="*"),n?.ifMatch&&(s["If-Match"]=`"${n.ifMatch.replace(/"/g,"")}"`),this.transport.putBytes(F(this.base,e),t,{contentType:n?.contentType,headers:Object.keys(s).length?s:void 0,signal:n?.signal})}async putString(e,t,n){return this.put(e,t,{...n,contentType:n?.contentType??"text/plain; charset=utf-8"})}async get(e,t){return(await this.read(e,t)).blob}async read(e,t){let{data:n,contentType:s,etag:o}=await this.transport.getRaw(F(this.base,e),t);return{blob:new Blob([new Uint8Array(n)],{type:s||"application/octet-stream"}),contentType:s,etag:o}}async readJSON(e,t){let n;try{n=await this.read(e,t)}catch(s){if(s?.statusCode===404||s?.status===404)return{value:void 0,etag:void 0};throw s}return{value:JSON.parse(await n.blob.text()),etag:n.etag}}async stat(e,t){let{status:n,headers:s}=await this.transport.head(F(this.base,e),t);if(n===404)throw Object.assign(new Error("not found"),{status:404});if(n>=400)throw Object.assign(new Error("stat failed"),{status:n});let o=parseInt(s.get("content-length")??"0",10);return{path:s.get("x-file-path")??e,size:o,content_type:s.get("content-type")??void 0,etag:(s.get("etag")??"").replace(/"/g,"")||void 0,url:s.get("x-file-url")??""}}async exists(e,t){let{status:n}=await this.transport.head(F(this.base,e),t);return n>=200&&n<400}async del(e,t){await this.transport.deletePath(F(this.base,e),t)}async list(e){let t=new URLSearchParams;e?.prefix&&t.set("prefix",e.prefix),e?.cursor&&t.set("cursor",e.cursor),e?.limit&&t.set("limit",String(e.limit)),e?.glob&&t.set("glob",e.glob);let n=t.toString();return this.transport.getJSON(this.base+(n?"?"+n:""),e?.signal?{signal:e.signal}:void 0)}async deleteMany(e,t){return this.transport.postJSON(this.base+"/delete",{prefix:e.prefix??"",glob:e.glob??""},t)}async move(e,t,n){return this.transport.postJSON(this.base+"/move",{from:e,to:t},n)}async copy(e,t,n){return this.transport.postJSON(this.base+"/copy",{from:e,to:t},n)}async putFromURL(e,t,n){return this.transport.postJSON(this.base+"/put-url",{path:e,src_url:t,content_type:n?.contentType,if_none_match:n?.ifNoneMatch,if_match:n?.ifMatch},n?.signal?{signal:n.signal}:void 0)}async batch(e,t){if(e.length===0)return[];let n=30;if(e.length<=n)return(await this.transport.postJSON(this.base+"/batch",{ops:e},t)).results;let s=[];for(let o=0;o<e.length;o+=n){let i=e.slice(o,o+n),a=await this.transport.postJSON(this.base+"/batch",{ops:i},t);s.push(...a.results)}return s}};var ne=class{constructor(e,t){l(this,"transport",e);l(this,"events",t)}async create(e,t,n){return h(this.events,{model:e,capability:"embedding"},()=>this.transport.postJSON("/v1/embeddings",{model:e,...t},n),s=>({totalTokens:s.usage?.total_tokens,costUSD:s.usage?.total_cost}))}};var C=class{constructor(){l(this,"active",new Map);l(this,"recent",[]);l(this,"session",{totalCalls:0,totalCostUSD:0,errorCount:0,startedAt:Date.now()});l(this,"lastErrorAt",0);l(this,"changeListeners",new Set)}attach(e){let t=[e.on("request:start",n=>{this.onStart(n),this.notify()}),e.on("request:streamDelta",n=>{this.onDelta(n),this.notify()}),e.on("request:end",n=>{this.onEnd(n),this.notify()}),e.on("request:error",n=>{this.onError(n),this.notify()})];return()=>{for(let n of t)n()}}onChange(e){return this.changeListeners.add(e),()=>this.changeListeners.delete(e)}notify(){for(let e of this.changeListeners)try{e()}catch(t){console.error("[runapps sdk] ActivityTracker onChange listener threw:",t)}}snapshot(){let e=Date.now();return{active:Array.from(this.active.values()),recent:this.recent.slice(),session:{...this.session},status:e-this.lastErrorAt<3e4?"error":this.active.size>0?"active":"idle"}}onStart(e){this.active.set(e.id,{id:e.id,model:e.model,capability:e.capability,startedAt:e.startedAt,streaming:e.streaming,tokensSoFar:0,tokensPerSec:0,rateSamples:[]})}onDelta(e){let t=this.active.get(e.id);if(!t)return;t.tokensSoFar=e.totalTokens;let n=Date.now();t.rateSamples.push({t:n,tokens:e.deltaTokens});let s=n-1500;for(;t.rateSamples.length>0&&t.rateSamples[0].t<s;)t.rateSamples.shift();if(t.rateSamples.length>=2){let o=t.rateSamples.reduce((a,u)=>a+u.tokens,0),i=n-t.rateSamples[0].t;t.tokensPerSec=i>0?o*1e3/i:0}}onEnd(e){let t=this.active.get(e.id);this.active.delete(e.id),this.pushRecent({id:e.id,model:e.model,capability:e.capability,latencyMs:e.latencyMs,totalTokens:e.totalTokens||t?.tokensSoFar||0,...e.costUSD!==void 0&&{costUSD:e.costUSD},...e.finishReason!==void 0&&{finishReason:e.finishReason},ok:!0,endedAt:Date.now()}),this.session.totalCalls+=1,e.costUSD!==void 0&&(this.session.totalCostUSD+=e.costUSD)}onError(e){let t=this.active.get(e.id);this.active.delete(e.id),this.pushRecent({id:e.id,model:e.model,capability:e.capability,latencyMs:e.latencyMs,totalTokens:t?.tokensSoFar||0,ok:!1,errorMessage:e.error.message,endedAt:Date.now()}),this.session.totalCalls+=1,this.session.errorCount+=1,this.lastErrorAt=Date.now()}pushRecent(e){this.recent.unshift(e),this.recent.length>20&&(this.recent.length=20)}};var He=60,Je="__runapps_auth_v1__",Ve="__runjobs_auth_v1__",ze="__runapps_signed_out_v1__",We="__runjobs_signed_out_v1__";function $(r){return r?`${Je}:${r}`:Je}function re(r){return r?`${ze}:${r}`:ze}function de(r){return r?`${Ve}:${r}`:Ve}function Ye(r){return r?`${We}:${r}`:We}var A=class{constructor(e={}){l(this,"origin");l(this,"hideBadge");l(this,"project");l(this,"events");l(this,"tracker");l(this,"badgePosition");l(this,"token",null);l(this,"expiresAt",0);l(this,"userInfo",null);l(this,"listeners",[]);l(this,"parentHandshake",null);l(this,"signingIn",!1);l(this,"getToken",async()=>{if(this.tokenIsFresh())return this.token;if(this.isSignedOut())throw new Error("RunApps: signed out \u2014 call client.signIn() to authenticate");if(this.inIframe()){try{this.parentHandshake&&(await this.parentHandshake,this.parentHandshake=null),this.tokenIsFresh()||await this.requestTokenFromParent()}catch{}if(this.tokenIsFresh())return this.token;throw new Error("RunApps: could not obtain a token from the dashboard")}return this.parentHandshake&&(await this.parentHandshake,this.tokenIsFresh())?this.token:(this.signIn(),new Promise(()=>{}))});this.origin=(e.origin??"https://www.runapps.ai").replace(/\/$/,""),this.hideBadge=!!e.hideBadge,this.project=e.project??null,this.events=e.events??null,this.badgePosition=e.badgePosition??"bottom-right",this.events&&!this.hideBadge?(this.tracker=new C,this.tracker.attach(this.events)):this.tracker=null,!(typeof window>"u")&&(this.loadPersisted(),this.consumeFragment()&&this.clearSignedOut(),this.isSignedOut()||(this.inIframe()&&!this.tokenIsFresh()?this.parentHandshake=this.requestTokenFromParent().catch(()=>{}):this.tokenIsFresh()&&this.userInfo&&!this.hideBadge&&this.renderBadge()))}onTokenChange(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}}get user(){return this.userInfo}hasFreshToken(){return this.tokenIsFresh()}signOut(){this.token=null,this.expiresAt=0,this.userInfo=null,this.parentHandshake=null,this.signingIn=!1,this.clearPersisted(),this.markSignedOut(),this.removeBadge()}invalidate(){this.token=null,this.expiresAt=0,this.userInfo=null,this.parentHandshake=null,this.signingIn=!1,this.clearPersisted()}signIn(){if(typeof window>"u"||this.signingIn)return;this.clearSignedOut(),this.signingIn=!0;let e=location.href.split("#")[0]??location.href,t=window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light";location.href=this.buildGrantUrl({pageOrigin:location.origin,app:location.host,redirectTo:e,scheme:t})}_buildGrantUrlForTest(e){return this.buildGrantUrl(e)}_storageKeysForTest(){return{auth:$(this.project),signedOut:re(this.project)}}buildGrantUrl(e){let t=new URLSearchParams;return t.set("origin",e.pageOrigin),t.set("app",e.app),t.set("redirect_to",e.redirectTo),t.set("scheme",e.scheme),this.project&&t.set("project_id",this.project),t.set("token_name","runapps_token"),this.origin+"/api/sdk/grant?"+t.toString()}nowSec(){return Math.floor(Date.now()/1e3)}tokenIsFresh(){return!!this.token&&this.nowSec()<this.expiresAt-He}inIframe(){try{return window.self!==window.top}catch{return!0}}setToken(e,t,n){this.token=e,this.expiresAt=t||this.nowSec()+3600,n&&(this.userInfo=n,this.hideBadge||this.renderBadge()),this.savePersisted();for(let s of this.listeners)try{s(e)}catch(o){console.warn("[runapps] onTokenChange handler threw",o)}}savePersisted(){if(!(typeof localStorage>"u"||!this.token))try{let e={token:this.token,expiresAt:this.expiresAt,origin:this.origin,...this.userInfo?{user:this.userInfo}:{}};localStorage.setItem($(this.project),JSON.stringify(e))}catch{}}loadPersisted(){if(!(typeof localStorage>"u"))try{let e=localStorage.getItem($(this.project));if(!e){if(e=localStorage.getItem(de(this.project)),!e)return;localStorage.setItem($(this.project),e),localStorage.removeItem(de(this.project))}let t=JSON.parse(e);if(!t.token||!t.origin||t.origin!==this.origin)return;if(typeof t.expiresAt=="number"&&t.expiresAt>0&&this.nowSec()>=t.expiresAt-He){this.clearPersisted();return}this.token=t.token,this.expiresAt=t.expiresAt??0,t.user&&(this.userInfo=t.user)}catch{this.clearPersisted()}}clearPersisted(){if(!(typeof localStorage>"u"))try{localStorage.removeItem($(this.project)),localStorage.removeItem(de(this.project))}catch{}}isSignedOut(){if(typeof localStorage>"u")return!1;try{return localStorage.getItem(re(this.project))==="1"||localStorage.getItem(Ye(this.project))==="1"}catch{return!1}}markSignedOut(){if(!(typeof localStorage>"u"))try{localStorage.setItem(re(this.project),"1")}catch{}}clearSignedOut(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(re(this.project)),localStorage.removeItem(Ye(this.project))}catch{}}removeBadge(){typeof document>"u"||document.getElementById("__runapps_identity__")?.remove()}consumeFragment(){if(!location.hash||!/(^#|&)run(apps|jobs)_token=/.test(location.hash))return!1;let e={};location.hash.replace(/^#/,"").split("&").forEach(s=>{let o=s.indexOf("=");o>=0&&(e[decodeURIComponent(s.slice(0,o))]=decodeURIComponent(s.slice(o+1)))});let t=e.runapps_token||e.runjobs_token;if(!t)return!1;let n;if(e.user)try{n=JSON.parse(e.user)}catch{}this.setToken(t,parseInt(e.expires_at??"",10)||0,n);try{history.replaceState(null,"",location.pathname+location.search)}catch{}return!0}requestTokenFromParent(){return new Promise((e,t)=>{let n=!1,s=[],o=()=>{n=!0,window.removeEventListener("message",i);for(let u of s)clearTimeout(u)},i=u=>{if(u.origin!==this.origin)return;let c=u.data;c&&(c.type==="runapps:token"||c.type==="runjobs:token")&&c.token&&(this.setToken(c.token,c.expires_at??0,c.user),o(),e())};window.addEventListener("message",i);let a=()=>{if(!n)try{window.parent.postMessage({type:"runapps:request-token"},this.origin),window.parent.postMessage({type:"runjobs:request-token"},this.origin)}catch(u){o(),t(u)}};a();for(let u of[250,750,1500,3e3])s.push(setTimeout(a,u));s.push(setTimeout(()=>{n||(o(),t(new Error("runapps: parent handshake timeout")))},5e3))})}renderBadge(){if(typeof document>"u"||!this.userInfo)return;let e="__runapps_identity__",t=`${this.origin}/dashboard`;(s=>document.body?s():document.addEventListener("DOMContentLoaded",s))(()=>{document.getElementById(e)?.remove();let s=Dt({id:e,user:this.userInfo,dashboardUrl:t,tracker:this.tracker,position:this.badgePosition,onSignOut:()=>{this.signOut(),typeof window<"u"&&window.location.reload()}});document.body.appendChild(s)})}};function Pt(){if(typeof document>"u"||document.getElementById("__runapps_kf__"))return;let r=document.createElement("style");r.id="__runapps_kf__",r.textContent="@keyframes __runapps_led_pulse__ { 0% { box-shadow: 0 0 0 0 rgba(59,130,246,0.7); } 70% { box-shadow: 0 0 0 6px rgba(59,130,246,0); } 100% { box-shadow: 0 0 0 0 rgba(59,130,246,0); }}",(document.head??document.documentElement).appendChild(r)}function It(r){let e=r.startsWith("top")?"top":"bottom",t=r.endsWith("right")?"right":"left",n=e==="bottom"?"bottom:calc(100% + 8px);top:auto":"top:calc(100% + 8px);bottom:auto",s=t==="right"?"right:0;left:auto":"left:0;right:auto";return{badge:`${e}:16px;${t}:16px`,popover:`${n};${s}`}}var Ze="__runapps_badge_pos__",Mt="__runjobs_badge_pos__",Xe=5,E=8;function Ot(){if(typeof document>"u")return null;let r=document.cookie.split(";").map(c=>c.trim()),e=Ze,t=r.find(c=>c.startsWith(e+"="));if(t||(e=Mt,t=r.find(c=>c.startsWith(e+"="))),!t)return null;let s=decodeURIComponent(t.slice(e.length+1)).split(","),o=s[0],i=s[1];if(s.length!==2||o===void 0||i===void 0)return null;let a=Number.parseInt(o,10),u=Number.parseInt(i,10);return!Number.isFinite(a)||!Number.isFinite(u)?null:{x:a,y:u}}function Ut(r,e){if(typeof document>"u")return;let t=3600*24*365,n=typeof window<"u"&&window.location?.protocol==="https:"?";Secure":"";document.cookie=`${Ze}=${encodeURIComponent(`${Math.round(r)},${Math.round(e)}`)};path=/;max-age=${t};SameSite=Lax${n}`}function Qe(r,e,t,n){let s=typeof window<"u"?window.innerWidth:1024,o=typeof window<"u"?window.innerHeight:768,i=Math.max(E,s-t-E),a=Math.max(E,o-n-E);return{x:Math.min(Math.max(E,r),i),y:Math.min(Math.max(E,e),a)}}function jt(r){let e=typeof window<"u"?window.innerWidth:1024,t=typeof window<"u"?window.innerHeight:768,n=r.left+r.width/2,o=r.top+r.height/2<t/2?"top:calc(100% + 8px);bottom:auto":"bottom:calc(100% + 8px);top:auto",i=n<e/2?"left:0;right:auto":"right:0;left:auto";return`${o};${i}`}function Dt(r){let{id:e,user:t,dashboardUrl:n,tracker:s,position:o,onSignOut:i}=r,a=It(o),u=a.popover;Pt();let c=document.createElement("button");c.id=e,c.type="button",c.title="RunApps activity",c.setAttribute("aria-label","RunApps activity status"),c.style.cssText=["position:fixed",a.badge,"z-index:2147483647","display:flex","align-items:center","gap:8px","padding:6px 12px 6px 6px","border-radius:999px","font:500 12px/1 -apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif","color:#fff","background:rgba(15,15,20,0.55)","backdrop-filter:blur(10px) saturate(1.2)","-webkit-backdrop-filter:blur(10px) saturate(1.2)","border:1px solid rgba(255,255,255,0.12)","box-shadow:0 4px 16px rgba(0,0,0,0.15)","user-select:none","max-width:220px","overflow:visible","cursor:pointer","appearance:none","-webkit-appearance:none","transition:background-color 120ms ease-out, box-shadow 120ms ease-out"].join(";"),c.addEventListener("mouseenter",()=>{c.style.backgroundColor="rgba(30,30,40,0.7)",c.style.boxShadow="0 6px 20px rgba(0,0,0,0.22)"}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="rgba(15,15,20,0.55)",c.style.boxShadow="0 4px 16px rgba(0,0,0,0.15)"});let d=document.createElement("span");d.style.cssText=["position:relative","width:26px;height:26px","flex-shrink:0","display:inline-flex;align-items:center;justify-content:center"].join(";");let g="http://www.w3.org/2000/svg",b=document.createElementNS(g,"svg");b.setAttribute("viewBox","0 0 26 26"),b.setAttribute("width","26"),b.setAttribute("height","26"),b.style.cssText=["position:absolute;inset:0","pointer-events:none","opacity:0","transition:opacity 200ms ease-out"].join(";");let S=document.createElementNS(g,"circle");S.setAttribute("cx","13"),S.setAttribute("cy","13"),S.setAttribute("r","12"),S.setAttribute("fill","none"),S.setAttribute("stroke","rgba(255,255,255,0.08)"),S.setAttribute("stroke-width","1.5");let y=document.createElementNS(g,"circle");y.setAttribute("cx","13"),y.setAttribute("cy","13"),y.setAttribute("r","12"),y.setAttribute("fill","none"),y.setAttribute("stroke","#3b82f6"),y.setAttribute("stroke-width","2"),y.setAttribute("stroke-linecap","round"),y.setAttribute("transform","rotate(-90 13 13)");let oe=2*Math.PI*12;y.setAttribute("stroke-dasharray",String(oe)),y.setAttribute("stroke-dashoffset",String(oe)),b.appendChild(S),b.appendChild(y);let ie=document.createElement("div");ie.textContent=(t.name||"?").charAt(0).toUpperCase(),ie.style.cssText=["width:22px;height:22px;border-radius:50%;flex-shrink:0","display:flex;align-items:center;justify-content:center","background:linear-gradient(135deg,#3b82f6,#8b5cf6)","font-size:11px;font-weight:600;color:#fff","position:relative"].join(";");let K=document.createElement("span");K.style.cssText=["position:absolute","bottom:-2px;right:-2px","width:8px;height:8px;border-radius:50%","background:rgba(255,255,255,0.2)","border:2px solid rgba(15,15,20,1)","box-shadow:0 0 0 0 transparent","transition:background-color 150ms ease-out, box-shadow 200ms ease-out","pointer-events:none"].join(";"),d.appendChild(b),d.appendChild(ie),d.appendChild(K);let ae=document.createElement("span");ae.textContent=t.name||"Signed in",ae.style.cssText="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;pointer-events:none",c.appendChild(d),c.appendChild(ae);let f=null,w=!1,_=null,N=null,q=null,le=()=>{N!==null&&(window.clearTimeout(N),N=null)},R=()=>{q!==null&&(window.clearTimeout(q),q=null)},me=()=>{R(),q=window.setTimeout(()=>{_==="hover"&&P()},300)},he=p=>{if(le(),R(),w){p==="click"&&(_="click");return}f||(f=$t(n,u,()=>{P(),i()}),f.addEventListener("mouseenter",R),f.addEventListener("mouseleave",()=>{_==="hover"&&me()})),c.appendChild(f),w=!0,_=p,H()},P=()=>{R(),w&&(f?.remove(),w=!1,_=null)};c.addEventListener("click",p=>{p.stopPropagation(),w?P():he("click")}),c.addEventListener("mouseenter",()=>{R(),le(),N=window.setTimeout(()=>{w||he("hover")},400)}),c.addEventListener("mouseleave",()=>{le(),_==="hover"&&me()}),document.addEventListener("click",p=>{w&&!c.contains(p.target)&&P()});let fe=0,be=0,ye=0,we=0,G=!1,I=!1,ce=!1,ue=(p,m)=>{c.style.left=`${p}px`,c.style.top=`${m}px`,c.style.right="auto",c.style.bottom="auto"},ve=()=>{let p=c.getBoundingClientRect();if(u=jt({left:p.left,top:p.top,width:p.width,height:p.height}),f){f.style.top="",f.style.bottom="",f.style.left="",f.style.right="";for(let m of u.split(";")){let[U,j]=m.split(":");U&&j&&f.style.setProperty(U.trim(),j.trim())}}};c.addEventListener("pointerdown",p=>{if(p.button!==0)return;G=!0,I=!1,fe=p.clientX,be=p.clientY;let m=c.getBoundingClientRect();ye=m.left,we=m.top}),c.addEventListener("pointermove",p=>{if(!G)return;let m=p.clientX-fe,U=p.clientY-be;if(!I){if(Math.abs(m)<Xe&&Math.abs(U)<Xe)return;I=!0,c.setPointerCapture(p.pointerId),c.style.cursor="grabbing",w&&P()}let j=c.getBoundingClientRect(),_e=Qe(ye+m,we+U,j.width,j.height);ue(_e.x,_e.y)});let xe=p=>{if(!G||(G=!1,!I))return;I=!1,c.style.cursor="pointer",c.hasPointerCapture(p.pointerId)&&c.releasePointerCapture(p.pointerId);let m=c.getBoundingClientRect();Ut(m.left,m.top),ve(),ce=!0};c.addEventListener("pointerup",xe),c.addEventListener("pointercancel",xe),c.addEventListener("click",p=>{ce&&(ce=!1,p.stopPropagation(),p.preventDefault())},!0);let M=Ot();M&&(ue(M.x,M.y),requestAnimationFrame(()=>{let p=c.getBoundingClientRect(),m=Qe(M.x,M.y,p.width,p.height);ue(m.x,m.y),ve()}));let pe=!1,O=null,Se=()=>{if(pe=!1,!s){b.style.opacity="0",K.style.background="rgba(255,255,255,0.2)";return}let p=s.snapshot();Bt(b,y,oe,p),Ft(K,p),w&&f&&Lt(f,p);let m=p.status!=="idle"||w;m&&O===null?O=window.setInterval(H,160):!m&&O!==null&&(window.clearInterval(O),O=null)};function H(){pe||(pe=!0,typeof requestAnimationFrame=="function"?requestAnimationFrame(Se):setTimeout(Se,0))}return s&&s.onChange(H),H(),c}function Bt(r,e,t,n){if(n.active.length===0){r.style.opacity="0";return}r.style.opacity="1";let s=n.active.reduce((o,i)=>i.tokensPerSec>o.tokensPerSec?i:o,n.active[0]);if(s.streaming&&s.tokensPerSec>0){let o=Math.min(s.tokensPerSec/60,1);e.setAttribute("stroke-dashoffset",String(t*(1-o))),e.setAttribute("stroke","#3b82f6")}else n.status==="error"?(e.setAttribute("stroke-dashoffset","0"),e.setAttribute("stroke","#ef4444")):(e.setAttribute("stroke-dashoffset",String(t*.75)),e.setAttribute("stroke","#a78bfa"))}function Ft(r,e){switch(e.status){case"idle":r.style.background="rgba(255,255,255,0.2)",r.style.boxShadow="0 0 0 0 transparent";break;case"active":r.style.background="#3b82f6",r.style.boxShadow="0 0 0 0 rgba(59,130,246,0.7)",r.style.animation="__runapps_led_pulse__ 1.2s ease-out infinite";break;case"error":r.style.background="#ef4444",r.style.boxShadow="0 0 0 2px rgba(239,68,68,0.3)",r.style.animation="";break}}function $t(r,e,t){let n=document.createElement("div");n.style.cssText=["position:absolute",e,"min-width:280px;max-width:340px","padding:10px 12px","border-radius:10px","background:rgba(15,15,20,0.92)","backdrop-filter:blur(20px) saturate(1.3)","-webkit-backdrop-filter:blur(20px) saturate(1.3)","border:1px solid rgba(255,255,255,0.12)","box-shadow:0 10px 30px rgba(0,0,0,0.4)","color:#fff","font:400 11px/1.4 -apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif","cursor:default","text-align:left"].join(";"),n.setAttribute("data-runapps-popover","1"),n.addEventListener("click",u=>u.stopPropagation());let s=document.createElement("div");s.setAttribute("data-runapps-popover-content","1"),n.appendChild(s);let o=document.createElement("div");o.style.cssText=["margin-top:10px;padding-top:8px","border-top:1px solid rgba(255,255,255,0.08)","display:flex;justify-content:space-between;align-items:center","font-size:10px;color:rgba(255,255,255,0.6)"].join(";");let i=document.createElement("a");i.textContent="Open dashboard \u2192",i.href=r,i.target="_blank",i.rel="noopener noreferrer",i.style.cssText="color:#a78bfa;text-decoration:none",o.appendChild(i);let a=document.createElement("button");return a.type="button",a.textContent="Sign out",a.style.cssText=["background:none;border:0;padding:0;margin:0","font:inherit;cursor:pointer","color:rgba(255,255,255,0.55)","transition:color 120ms ease"].join(";"),a.addEventListener("mouseenter",()=>{a.style.color="#f87171"}),a.addEventListener("mouseleave",()=>{a.style.color="rgba(255,255,255,0.55)"}),a.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),t()}),o.appendChild(a),n.appendChild(o),n}function Lt(r,e){let t=r.querySelector("[data-runapps-popover-content]");if(!t)return;t.innerHTML="";let n=Date.now();t.appendChild(Kt(e,n)),t.appendChild(Nt(e,n)),t.appendChild(qt(e.session,n))}function Kt(r,e){let t=document.createElement("div");if(t.style.marginBottom="10px",t.appendChild(ge("Active",r.active.length>0?`${r.active.length} in flight`:"\u2014")),r.active.length===0){let n=document.createElement("div");return n.style.cssText="color:rgba(255,255,255,0.4);font-size:10px;padding:2px 0",n.textContent="No calls in flight.",t.appendChild(n),t}for(let n of r.active){let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0";let o=document.createElement("span");o.style.cssText="color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px",o.textContent=n.model;let i=document.createElement("span");i.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums;font-size:10px";let a=((e-n.startedAt)/1e3).toFixed(1),u=n.tokensPerSec>0?` \xB7 ${Math.round(n.tokensPerSec)} tok/s`:"";i.textContent=`${a}s${u}`,s.appendChild(o),s.appendChild(i),t.appendChild(s)}return t}function Nt(r,e){let t=document.createElement("div");if(t.style.marginBottom="10px",t.appendChild(ge("Recent",r.recent.length>0?`last ${Math.min(r.recent.length,5)}`:"\u2014")),r.recent.length===0){let n=document.createElement("div");return n.style.cssText="color:rgba(255,255,255,0.4);font-size:10px;padding:2px 0",n.textContent="Nothing yet this session.",t.appendChild(n),t}for(let n of r.recent.slice(0,5)){let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0";let o=document.createElement("span");o.style.cssText="color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px";let i=document.createElement("span");i.textContent=n.ok?"\u2713 ":"\u2717 ",i.style.color=n.ok?"#10b981":"#ef4444",o.appendChild(i),o.appendChild(document.createTextNode(n.model));let a=document.createElement("span");a.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums;font-size:10px";let u=`${(n.latencyMs/1e3).toFixed(1)}s`,c=n.costUSD!==void 0?` \xB7 $${n.costUSD.toFixed(4)}`:"",d=` \xB7 ${et(e-n.endedAt)}`;a.textContent=`${u}${c}${d}`,s.appendChild(o),s.appendChild(a),t.appendChild(s)}return t}function qt(r,e){let t=document.createElement("div");t.appendChild(ge("Session",et(e-r.startedAt)));let n=document.createElement("div");n.style.cssText="display:flex;justify-content:space-between;gap:12px;color:rgba(255,255,255,0.85);font-size:10px";let s=document.createElement("span");s.textContent=`${r.totalCalls} call${r.totalCalls===1?"":"s"}`;let o=document.createElement("span");o.textContent=`$${r.totalCostUSD.toFixed(4)}`;let i=document.createElement("span");return i.textContent=r.errorCount>0?`${r.errorCount} error${r.errorCount===1?"":"s"}`:"0 errors",r.errorCount>0&&(i.style.color="#ef4444"),n.appendChild(s),n.appendChild(o),n.appendChild(i),t.appendChild(n),t}function ge(r,e){let t=document.createElement("div");t.style.cssText=["display:flex;justify-content:space-between;align-items:baseline","margin-bottom:4px","color:rgba(255,255,255,0.55)","font-size:10px;text-transform:uppercase;letter-spacing:0.05em"].join(";");let n=document.createElement("span");n.textContent=r;let s=document.createElement("span");return s.textContent=e,s.style.cssText="font-size:9px;letter-spacing:0",t.appendChild(n),t.appendChild(s),t}function et(r){return r<1500?"just now":r<6e4?`${Math.round(r/1e3)}s ago`:r<36e5?`${Math.round(r/6e4)}m ago`:`${Math.round(r/36e5)}h ago`}var Gt="https://www.runapps.ai",T=class{constructor(e={}){l(this,"chat");l(this,"models");l(this,"image");l(this,"audio");l(this,"video");l(this,"computer");l(this,"files");l(this,"embeddings");l(this,"auth",null);l(this,"events",new k);let t=e.authProvider??"static",n=e.apiKeyResolver,s=e.baseURL,o;if(t==="runapps"||t==="runjobs"){s=s??"https://www.runapps.ai";let a=e.showIdentityBadge!==void 0?e.showIdentityBadge:e.hideIdentityBadge!==void 0?!e.hideIdentityBadge:!0,u=new A({origin:s,hideBadge:!a,events:this.events,...e.badgePosition!==void 0&&{badgePosition:e.badgePosition},...e.project!==void 0&&{project:e.project}});this.auth=u,n=u.getToken,o=()=>u.invalidate()}if(!e.apiKey&&!n)throw new Error('runapps: pass either `apiKey`, `apiKeyResolver`, or `authProvider: "runapps"`');let i=new V({baseURL:s??Gt,...e.apiKey!==void 0&&{apiKey:e.apiKey},...n!==void 0&&{apiKeyResolver:n},...o!==void 0&&{onUnauthorized:o},...e.fetch?{fetchImpl:e.fetch}:{}});this.chat=new z(i,this.events),this.models=new W(i),this.image=new Y(i,this.events),this.audio=new X(i,this.events),this.video=new Z(i,this.events),this.computer=new ee(i,this.events),this.files=new te(i,e.project),this.embeddings=new ne(i,this.events)}signIn(){this.auth?.signIn()}signOut(){this.auth?.signOut()}get user(){return this.auth?.user??null}};function tt(r){return r?r.map(e=>Array.isArray(e)?{fields:e}:e):[]}function L(r){let e=r.options;return!e||typeof e!="object"?null:e}function nt(r,e){let n=L(r)?.inputs?.[e];return n?n.presence!=="forbidden":!1}function rt(r,e){return L(r)?.inputs?.[e]?.presence==="required"}function st(r,e){return L(r)?.inputs?.[e]?.enum??null}function at(r,e={}){if(!r)return[];let t=[];if(r.inputs)for(let[n,s]of Object.entries(r.inputs)){let o=n in e,i=e[n];o&&!v(i)?t.push(...lt(n,s,i)):o&&s.min_items!==void 0&&Array.isArray(i)&&i.length<s.min_items&&t.push({field:n,reason:`at least ${s.min_items} items`}),t.push(...ct(n,s,i,o))}for(let n of r.constraints??[])t.push(...Ht(n,e));return t}function lt(r,e,t){let n=[];if(!Jt(e.type,t))return n.push({field:r,reason:`expected type ${e.type}, got ${se(t)}`}),n;if(e.enum&&e.enum.length>0&&!Vt(t,e.enum)&&n.push({field:r,reason:`must be one of ${JSON.stringify(e.enum)}`}),e.type==="int"||e.type==="float"){let s=ut(t);s!==null&&(e.min!==void 0&&s<e.min&&n.push({field:r,reason:`must be >= ${e.min}`}),e.max!==void 0&&s>e.max&&n.push({field:r,reason:`must be <= ${e.max}`}))}return Array.isArray(t)&&(e.max_items!==void 0&&t.length>e.max_items&&n.push({field:r,reason:`at most ${e.max_items} items`}),e.min_items!==void 0&&t.length<e.min_items&&n.push({field:r,reason:`at least ${e.min_items} items`})),e.fields&&(e.repeatable?Array.isArray(t)?t.forEach((s,o)=>{if(typeof s!="object"||s===null||Array.isArray(s)){n.push({field:`${r}[${o}]`,reason:`expected object, got ${se(s)}`});return}n.push(...ot(`${r}[${o}]`,e.fields,s))}):n.push({field:r,reason:`expected array of objects, got ${se(t)}`}):typeof t!="object"||t===null||Array.isArray(t)?n.push({field:r,reason:`expected object, got ${se(t)}`}):n.push(...ot(r,e.fields,t))),n}function ot(r,e,t){let n=[];for(let[s,o]of Object.entries(e)){let i=`${r}.${s}`,a=t[s],u=s in t;u&&!v(a)&&n.push(...lt(i,o,a)),n.push(...ct(i,o,a,u))}return n}function ct(r,e,t,n){let s=e.presence??"optional";return s==="required"&&(!n||v(t))?[{field:r,reason:"required"}]:s==="forbidden"&&n&&!v(t)?[{field:r,reason:"must not be set for this model"}]:[]}function Ht(r,e){switch(r.kind){case"any_of_required":{let t=r.fields??[];return t.some(s=>s in e&&!v(e[s]))?[]:[{field:t.join("/"),reason:`at least one of ${t.join(", ")} is required`}]}case"mutually_exclusive":{let t=r.fields??[],n=t.filter(s=>s in e&&!v(e[s]));return n.length>1?[{field:n.join("/"),reason:`at most one of ${t.join(", ")} may be set (got: ${n.join(", ")})`}]:[]}case"group_mutex":{let t=tt(r.groups),n=[],s=[];for(let o of t){let i=o.fields.filter(a=>a in e&&!v(e[a]));i.length>0&&(n.push(o),s.push(...i))}if(n.length>1){let o=t.map(i=>`[${i.fields.join("+")}]`).join(" or ");return[{field:s.join("/"),reason:`at most one of ${o} may be used (got: ${s.join(", ")})`}]}return[]}case"requires_all":{let t=r.when;if(!t)return[];if(!(t in e&&!v(e[t])))return[];let s=(r.then??[]).filter(o=>!(o in e)||v(e[o]));return s.length===0?[]:[{field:s.join("/"),reason:`required when ${t} is set`}]}case"pixel_bounds":{let t=r.fields?.[0];if(!t)return[];let n=e[t];if(typeof n!="string"||n==="")return[];let s=Wt(n);if(!s)return[{field:t,reason:`expected WxH dimensions, got "${n}"`}];let[o,i]=s,a=o*i,u=[];return r.min!==void 0&&a<r.min&&u.push({field:t,reason:`image too small: ${o}x${i} = ${a} pixels, minimum ${r.min}`}),r.max!==void 0&&a>r.max&&u.push({field:t,reason:`image too large: ${o}x${i} = ${a} pixels, maximum ${r.max}`}),u}}return[]}function Jt(r,e){switch(r){case"string":return typeof e=="string";case"int":case"float":return ut(e)!==null;case"bool":return typeof e=="boolean";case"url":return typeof e=="string"&&it(e);case"url[]":return Array.isArray(e)&&e.every(t=>typeof t=="string"&&it(t));case"string[]":return Array.isArray(e)&&e.every(t=>typeof t=="string");case"file":return!0;default:return!0}}function se(r){return r===null?"null":Array.isArray(r)?"array":typeof r}function ut(r){return typeof r=="number"&&Number.isFinite(r)?r:null}function it(r){return r.startsWith("http://")||r.startsWith("https://")||r.startsWith("data:")}function v(r){return r==null?!0:typeof r=="string"?r==="":Array.isArray(r)?r.length===0:!1}function Vt(r,e){for(let t of e)if(zt(r,t))return!0;return!1}function zt(r,e){return r===e}function Wt(r){for(let e of["x","X","*","\xD7"]){let t=r.indexOf(e);if(t<=0)continue;let n=parseInt(r.slice(0,t).trim(),10),s=parseInt(r.slice(t+e.length).trim(),10);if(Number.isFinite(n)&&Number.isFinite(s)&&n>0&&s>0)return[n,s]}return null}return bt(Yt);})();
|
|
1
|
+
"use strict";var RunApps=(()=>{var J=Object.defineProperty;var pt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var gt=Object.prototype.hasOwnProperty;var mt=(r,e,t)=>e in r?J(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var ht=(r,e)=>{for(var t in e)J(r,t,{get:e[t],enumerable:!0})},ft=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of dt(e))!gt.call(r,s)&&s!==t&&J(r,s,{get:()=>e[s],enumerable:!(n=pt(e,s))||n.enumerable});return r};var bt=r=>ft(J({},"__esModule",{value:!0}),r);var l=(r,e,t)=>mt(r,typeof e!="symbol"?e+"":e,t);var Yt={};ht(Yt,{APIError:()=>x,ActivityTracker:()=>C,BrowserAuth:()=>A,Client:()=>T,RunApps:()=>T,RunJobs:()=>T,SDKEvents:()=>k,ServerTools:()=>Ce,acceptsField:()=>nt,acceptsModality:()=>De,allowedValuesFor:()=>st,assistantMessage:()=>Te,audioPart:()=>Ue,decodeMediaUrl:()=>B,defaultVoice:()=>Le,encodeImageUrl:()=>Ne,getOptionsSchema:()=>L,hasCapabilityTag:()=>je,imagePart:()=>Me,newRequestId:()=>D,requiresField:()=>rt,supportsInstructText:()=>$e,supportsVoiceClone:()=>Fe,systemMessage:()=>Ae,textPart:()=>Ie,toolResultMessage:()=>Re,userMessage:()=>Ee,userMessageParts:()=>Pe,validateRequest:()=>at,videoPart:()=>Oe});var x=class extends Error{constructor(t,n,s){super(`runapps: ${t} ${n}: ${s}`);l(this,"statusCode");l(this,"type");this.name="APIError",this.statusCode=t,this.type=n}};var V=class{constructor(e){l(this,"baseURL");l(this,"apiKey");l(this,"apiKeyResolver");l(this,"onUnauthorized");l(this,"fetchImpl");if(!e.apiKey&&!e.apiKeyResolver)throw new Error("RunApps: pass either `apiKey` or `apiKeyResolver` when constructing the client");this.baseURL=e.baseURL.replace(/\/+$/,""),this.apiKey=e.apiKey,this.apiKeyResolver=e.apiKeyResolver,this.onUnauthorized=e.onUnauthorized,this.fetchImpl=e.fetchImpl??fetch.bind(globalThis)}async resolveToken(){return this.apiKeyResolver?await this.apiKeyResolver():this.apiKey??""}async fetchWithAuthRetry(e,t){let n=this.baseURL+e,s=await this.fetchImpl(n,await this.buildInit(t));if(s.status!==401||!this.onUnauthorized)return s;try{await this.onUnauthorized()}catch{return s}return s=await this.fetchImpl(n,await this.buildInit(t)),s}async buildInit(e){let t=await e();return t.cache?t:{...t,cache:"no-store"}}async postJSON(e,t,n){let s=await this.fetchWithAuthRetry(e,async()=>({method:"POST",headers:await this.jsonHeaders(),body:JSON.stringify(t),signal:n?.signal}));if(!s.ok)throw await this.parseError(s);return await s.json()}async getJSON(e,t){let n=await this.fetchWithAuthRetry(e,async()=>({method:"GET",headers:await this.authHeaders(),signal:t?.signal}));if(!n.ok)throw await this.parseError(n);return await n.json()}async getRaw(e,t){let n=await this.fetchWithAuthRetry(e,async()=>({method:"GET",headers:await this.authHeaders(),signal:t?.signal}));if(!n.ok)throw await this.parseError(n);let s=new Uint8Array(await n.arrayBuffer()),i=n.headers.get("content-type")??"",o=(n.headers.get("etag")??"").replace(/"/g,"")||void 0;return{data:s,contentType:i,etag:o}}async postMultipart(e,t,n){let s=await this.fetchWithAuthRetry(e,async()=>({method:"POST",headers:await this.authHeaders(),body:t,signal:n?.signal}));if(!s.ok)throw await this.parseError(s);return await s.json()}async postJSONStream(e,t,n){let s=await this.fetchWithAuthRetry(e,async()=>({method:"POST",headers:{...await this.jsonHeaders(),"Accept-Encoding":"identity"},body:JSON.stringify(t),signal:n?.signal}));if(!s.ok)throw await this.parseError(s);return s}async putBytes(e,t,n){let s=await this.fetchWithAuthRetry(e,async()=>{let i={...await this.authHeaders(),"Content-Type":n?.contentType??"application/octet-stream"};return n?.headers&&Object.assign(i,n.headers),{method:"PUT",headers:i,body:t,signal:n?.signal}});if(!s.ok)throw await this.parseError(s);if(n?.parse!=="none")return await s.json()}async deletePath(e,t){let n=await this.fetchWithAuthRetry(e,async()=>({method:"DELETE",headers:await this.authHeaders(),signal:t?.signal}));if(!n.ok)throw await this.parseError(n);if(t?.parse!=="none")return await n.json()}async head(e,t){let n=await this.fetchWithAuthRetry(e,async()=>({method:"HEAD",headers:await this.authHeaders(),signal:t?.signal}));return{status:n.status,headers:n.headers}}async jsonHeaders(){return{"Content-Type":"application/json",Authorization:`Bearer ${await this.resolveToken()}`}}async authHeaders(){return{Authorization:`Bearer ${await this.resolveToken()}`}}async parseError(e){let t=await e.text(),n="error",s=t||e.statusText;try{let i=JSON.parse(t);i.type&&(n=i.type),i.message&&(s=i.message)}catch{}return new x(e.status,n,s)}};var k=class{constructor(){l(this,"handlers",new Map)}on(e,t){let n=this.handlers.get(e);n||(n=new Set,this.handlers.set(e,n));let s=t;return n.add(s),()=>{this.handlers.get(e)?.delete(s)}}emit(e,t){let n=this.handlers.get(e);if(!(!n||n.size===0))for(let s of n)try{s(t)}catch(i){console.error("[runapps sdk] event listener for",e,"threw:",i)}}clear(){this.handlers.clear()}};function D(){return"req_"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,8)}async function h(r,e,t,n){let s=D(),i=Date.now();r.emit("request:start",{id:s,model:e.model,capability:e.capability,startedAt:i,streaming:!1});try{let o=await t(),a=n?n(o):{};return r.emit("request:end",{id:s,model:e.model,capability:e.capability,latencyMs:Date.now()-i,totalTokens:a.totalTokens??0,...a.costUSD!==void 0&&{costUSD:a.costUSD},...a.finishReason!==void 0&&{finishReason:a.finishReason}}),o}catch(o){let a=o;throw r.emit("request:error",{id:s,model:e.model,capability:e.capability,latencyMs:Date.now()-i,error:a,...typeof a.statusCode=="number"&&{statusCode:a.statusCode}}),o}}function yt(r){return r?Math.max(1,Math.round(r.length/4)):0}async function*ke(r,e,t,n){let s=D(),i=Date.now();r.emit("request:start",{id:s,model:e.model,capability:e.capability,startedAt:i,streaming:!0});let o=0,a,u,c;try{for await(let d of t()){let g=n(d);if(g.deltaText){let b=yt(g.deltaText);o+=b,r.emit("request:streamDelta",{id:s,deltaTokens:b,totalTokens:o})}g.completionTokens!==void 0&&(a=g.completionTokens),g.costUSD!==void 0&&(u=g.costUSD),g.finishReason!==void 0&&(c=g.finishReason),yield d}r.emit("request:end",{id:s,model:e.model,capability:e.capability,latencyMs:Date.now()-i,totalTokens:a??o,...u!==void 0&&{costUSD:u},...c!==void 0&&{finishReason:c}})}catch(d){let g=d;throw r.emit("request:error",{id:s,model:e.model,capability:e.capability,latencyMs:Date.now()-i,error:g,...typeof g.statusCode=="number"&&{statusCode:g.statusCode}}),d}}var Ce={WebSearch:"web_search",WebFetch:"web_fetch",TwitterSearch:"twitter_search"},Ee=r=>({role:"user",content:r}),Ae=r=>({role:"system",content:r}),Te=r=>({role:"assistant",content:r}),Re=(r,e)=>({role:"tool",tool_call_id:r,content:e}),Pe=(...r)=>({role:"user",content:r}),Ie=r=>({type:"text",text:r}),Me=(r,e)=>({type:"image_url",image_url:e?{url:r,detail:e}:{url:r}}),Oe=r=>({type:"video_url",video_url:{url:r}}),Ue=r=>({type:"audio_url",audio_url:{url:r}}),z=class{constructor(e,t){l(this,"transport",e);l(this,"events",t)}async create(e,t){let n={...e,stream:!1};return h(this.events,{model:e.model,capability:"text"},()=>this.transport.postJSON("/v1/chat/completions",n,t),s=>({totalTokens:s.usage?.completion_tokens,costUSD:s.usage?.total_cost,finishReason:s.choices?.[0]?.finish_reason}))}async*stream(e,t){let n={...e,stream:!0,stream_options:e.stream_options??{include_usage:!0}},s=async function*(){let i=await this.transport.postJSONStream("/v1/chat/completions",n,t);if(!i.body)throw new Error("runapps: streaming response had no body");yield*wt(i.body)}.bind(this);yield*ke(this.events,{model:e.model,capability:"text"},s,i=>({deltaText:i.choices?.[0]?.delta?.content??"",completionTokens:i.usage?.completion_tokens,costUSD:i.usage?.total_cost,finishReason:i.choices?.[0]?.finish_reason??void 0}))}};async function*wt(r){let e=new TextDecoder,t=r.getReader(),n="";try{for(;;){let{value:s,done:i}=await t.read();if(i)break;n+=e.decode(s,{stream:!0});let o;for(;(o=n.indexOf(`
|
|
2
|
+
`))!==-1;){let a=n.slice(0,o).replace(/\r$/,"");if(n=n.slice(o+1),!a.startsWith("data: "))continue;let u=a.slice(6).trim();if(u==="[DONE]")return;if(!u)continue;let c;try{c=JSON.parse(u)}catch(g){throw new Error(`runapps: decode stream chunk: ${g.message}`)}let d=c.error;if(d)throw new x(d.code??0,d.type??"upstream_error",d.message??u);yield c}}}finally{t.releaseLock()}}var je=(r,e)=>Array.isArray(r.capability_tags)&&r.capability_tags.some(t=>t.id===e),De=(r,e)=>Array.isArray(r.input_modalities)&&r.input_modalities.includes(e);function Be(r,e){let t=r.options?.[e];return typeof t=="boolean"?t:typeof t=="number"?t!==0:!1}var Fe=r=>Be(r,"supports_voice_clone"),$e=r=>Be(r,"supports_instruct_text"),Le=r=>{let e=r.options?.default_voice;return typeof e=="string"?e:null},W=class{constructor(e){l(this,"transport",e)}async list(e={},t){let n="/v1/models";return e.capability&&(n+=`?capability=${encodeURIComponent(e.capability)}`),(await this.transport.getJSON(n,t)).data}};var Y=class{constructor(e,t){l(this,"transport",e);l(this,"events",t)}async generate(e,t,n){return h(this.events,{model:e,capability:"image_generation"},()=>this.transport.postJSON("/v1/images/generations",{model:e,...t},n),s=>({costUSD:s.usage?.total_cost}))}async generateAsync(e,t,n){let s=n?.pollIntervalMs??2e3,i=n?.signal;return h(this.events,{model:e,capability:"image_generation"},async()=>{let a=await this.transport.postJSON("/v1/async/images/generations",{model:e,...t},{signal:i});for(;a.status!=="succeeded"&&a.status!=="failed";)await vt(s,i),a=await this.getAsyncStatus(a.id,{signal:i});if(a.status==="failed")throw new Error(a.error??"image generation failed");return{created:a.created_at??Math.floor(Date.now()/1e3),data:a.data??[],usage:a.usage??{total_cost:0}}},o=>({costUSD:o.usage?.total_cost}))}async submitGenerate(e,t,n){return h(this.events,{model:e,capability:"image_generation"},()=>this.transport.postJSON("/v1/async/images/generations",{model:e,...t},n))}async getAsyncStatus(e,t){return this.transport.getJSON(`/v1/async/images/generations/${encodeURIComponent(e)}`,t)}async edit(e,t,n){let s=xt(e,t);return h(this.events,{model:e,capability:"image_edit"},()=>this.transport.postMultipart("/v1/images/edits",s,n),i=>({costUSD:i.usage?.total_cost}))}};function vt(r,e){return new Promise((t,n)=>{if(e?.aborted){n(e.reason??new Error("aborted"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r),i=()=>{clearTimeout(s),n(e.reason??new Error("aborted"))};e?.addEventListener("abort",i,{once:!0})})}function xt(r,e){let t=new FormData;return t.set("model",r),t.set("prompt",e.prompt),e.size&&t.set("size",e.size),e.n!==void 0&&t.set("n",String(e.n)),e.user&&t.set("user",e.user),t.set("image",Ke(e.image),e.image.filename),e.mask&&t.set("mask",Ke(e.mask),e.mask.filename),t}function Ke(r){let e=r.contentType??St(r.filename);return r.data instanceof Blob?r.data.type===e?r.data:new Blob([r.data],{type:e}):typeof r.data=="string"?new Blob([r.data],{type:e}):new Blob([r.data],{type:e})}function St(r){switch(r.toLowerCase().split(".").pop()??""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"webp":return"image/webp";case"gif":return"image/gif";default:return"application/octet-stream"}}function Ne(r){if(r instanceof Blob)throw new Error("encodeImageUrl: Blob input requires async; await blob.arrayBuffer() and pass the result instead");let e=r instanceof Uint8Array?r:new Uint8Array(r),t=kt(e),n=32768,s="";for(let o=0;o<e.length;o+=n)s+=String.fromCharCode.apply(null,Array.from(e.subarray(o,o+n)));let i=globalThis.btoa?globalThis.btoa(s):Buffer.from(s,"binary").toString("base64");return`data:${t};base64,${i}`}async function B(r){if(r.startsWith("data:")){let e=r.slice(5),t=e.indexOf(";"),n=e.indexOf(",");if(t===-1||n===-1||n<t)throw new Error("decodeMediaUrl: malformed data URI");let s=e.slice(0,t),i=e.slice(n+1);return{bytes:_t(i),contentType:s}}if(r.startsWith("http://")||r.startsWith("https://")){let e=await fetch(r);if(!e.ok)throw new Error(`decodeMediaUrl: upstream ${e.status}`);let t=await e.arrayBuffer();return{bytes:new Uint8Array(t),contentType:e.headers.get("Content-Type")??""}}throw new Error(`decodeMediaUrl: unsupported url scheme: ${r.slice(0,32)}`)}function _t(r){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function kt(r){return r.length>=8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71?"image/png":r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255?"image/jpeg":r.length>=6&&r[0]===71&&r[1]===73&&r[2]===70&&r[3]===56?"image/gif":r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===87&&r[9]===69&&r[10]===66&&r[11]===80?"image/webp":"application/octet-stream"}var X=class{constructor(e,t){l(this,"transport",e);l(this,"events",t)}async speech(e,t,n){return h(this.events,{model:e,capability:"text_to_speech"},async()=>{let s=await this.transport.postJSON("/v1/audio/speech",qe(e,t),n),{bytes:i,contentType:o}=await B(s.audio_url);return{data:i,contentType:o,usage:s.usage}},s=>({costUSD:s.usage?.total_cost}))}async speechAsync(e,t,n){return h(this.events,{model:e,capability:"text_to_speech"},async()=>{let s=await this.transport.postJSON("/v1/async/audio/speech",qe(e,t),n);if(!s.id)throw new Error("runapps: speech submit response missing job id");return Ct(this.transport,s.id,n)},s=>({costUSD:s.usage?.total_cost}))}async transcribe(e,t,n){let s=Ge(e,t);return h(this.events,{model:e,capability:"speech_to_text"},()=>this.transport.postMultipart("/v1/audio/transcriptions",s,n),i=>({costUSD:i.usage?.total_cost}))}async transcribeAsync(e,t,n){return h(this.events,{model:e,capability:"speech_to_text"},async()=>{let s=Ge(e,t),i=await this.transport.postMultipart("/v1/async/audio/transcriptions",s,n);if(!i.id)throw new Error("runapps: transcribe submit response missing job id");return Et(this.transport,i.id,n)},s=>({costUSD:s.usage?.total_cost}))}};async function Ct(r,e,t){let n=`/v1/async/audio/speech/${encodeURIComponent(e)}`,s=t?.pollIntervalMs??3e3;await Q(2e3,t?.signal);let o=Date.now()+600*1e3;for(;;){if(t?.signal?.aborted)throw new DOMException("speech poll aborted","AbortError");if(!t?.signal&&Date.now()>o)throw new Error("runapps: speech job timed out (10 min internal cap)");let a=await r.getJSON(n,t);if(a.status==="succeeded"){if(!a.audio_url)throw new Error("runapps: speech job succeeded but no audio_url returned");let{bytes:u,contentType:c}=await B(a.audio_url);return{data:u,contentType:c,usage:a.usage??{total_cost:0}}}if(a.status==="failed")throw new Error(a.error||"runapps: speech job failed");await Q(s,t?.signal)}}async function Et(r,e,t){let n=`/v1/async/audio/transcriptions/${encodeURIComponent(e)}`,s=t?.pollIntervalMs??3e3;await Q(2e3,t?.signal);let i=Date.now()+600*1e3;for(;;){if(t?.signal?.aborted)throw new DOMException("transcribe poll aborted","AbortError");if(!t?.signal&&Date.now()>i)throw new Error("runapps: transcribe job timed out (10 min internal cap)");let o=await r.getJSON(n,t);switch(o.status){case"succeeded":return At(o);case"failed":throw new Error(o.error||"runapps: transcribe job failed");case"queued":case"running":await Q(s,t?.signal);break;default:throw new Error(`runapps: unknown transcribe job status ${JSON.stringify(o.status)}`)}}}function At(r){let e={text:r.text??"",usage:r.usage??{total_cost:0}},t={};for(let[n,s]of Object.entries(r))n==="text"||n==="usage"||n==="id"||n==="status"||(t[n]=s);return Object.keys(t).length>0&&(e.raw=t),e}function Q(r,e){return new Promise((t,n)=>{if(e?.aborted){n(new DOMException("aborted","AbortError"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r),i=()=>{clearTimeout(s),n(new DOMException("aborted","AbortError"))};e?.addEventListener("abort",i,{once:!0})})}function qe(r,e){let{extra:t,...n}=e,s={model:r,...n};if(t)for(let[i,o]of Object.entries(t))i in s||(s[i]=o);return s}function Ge(r,e){let t=new FormData;if(t.set("model",r),e.language&&t.set("language",e.language),e.prompt&&t.set("prompt",e.prompt),e.response_format&&t.set("response_format",e.response_format),e.timestamp_granularities)for(let i of e.timestamp_granularities)t.append("timestamp_granularities[]",i);e.user&&t.set("user",e.user);let n=e.file.contentType??Tt(e.file.filename),s=e.file.data instanceof Blob?e.file.data:new Blob([e.file.data],{type:n});return t.set("file",s,e.file.filename),t}function Tt(r){switch(r.toLowerCase().split(".").pop()??""){case"mp3":return"audio/mpeg";case"wav":return"audio/wav";case"m4a":return"audio/mp4";case"flac":return"audio/flac";case"ogg":return"audio/ogg";case"webm":return"audio/webm";default:return"application/octet-stream"}}var Z=class{constructor(e,t){l(this,"transport",e);l(this,"events",t)}async generate(e,t,n){return h(this.events,{model:e,capability:"video_generation"},()=>this.transport.postJSON("/v1/videos/generations",{model:e,...t},n))}async getStatus(e,t){return this.transport.getJSON(`/v1/videos/generations/${encodeURIComponent(e)}`,t)}async wait(e,t={}){let n=t.pollIntervalMs??5e3;for(;;){let s=await this.getStatus(e,{signal:t.signal});if(s.status==="succeeded"||s.status==="failed")return s;await Rt(n,t.signal)}}async getContent(e,t){return this.transport.getRaw(`/v1/videos/${encodeURIComponent(e)}/content`,t)}};function Rt(r,e){return new Promise((t,n)=>{if(e?.aborted){n(e.reason??new Error("aborted"));return}let s=setTimeout(()=>{e?.removeEventListener("abort",i),t()},r),i=()=>{clearTimeout(s),n(e.reason??new Error("aborted"))};e?.addEventListener("abort",i,{once:!0})})}var ee=class{constructor(e,t){l(this,"transport",e);l(this,"events",t)}async step(e,t,n){return h(this.events,{model:e,capability:"computer_use"},()=>this.transport.postJSON("/v1/computer/step",{model:e,...t},n),s=>({totalTokens:s.usage?.completion_tokens,costUSD:s.usage?.total_cost}))}};function F(r,e){let t=e.replace(/^\/+/,"");return r+"/"+t.split("/").map(encodeURIComponent).join("/")}var te=class{constructor(e,t){l(this,"transport",e);l(this,"base");this.base=t?"/v1/p/"+encodeURIComponent(t)+"/files":"/v1/files"}async put(e,t,n){let s={};return n?.ifNoneMatch&&(s["If-None-Match"]="*"),n?.ifMatch&&(s["If-Match"]=`"${n.ifMatch.replace(/"/g,"")}"`),this.transport.putBytes(F(this.base,e),t,{contentType:n?.contentType,headers:Object.keys(s).length?s:void 0,signal:n?.signal})}async putString(e,t,n){return this.put(e,t,{...n,contentType:n?.contentType??"text/plain; charset=utf-8"})}async get(e,t){return(await this.read(e,t)).blob}async read(e,t){let{data:n,contentType:s,etag:i}=await this.transport.getRaw(F(this.base,e),t);return{blob:new Blob([new Uint8Array(n)],{type:s||"application/octet-stream"}),contentType:s,etag:i}}async readJSON(e,t){let n;try{n=await this.read(e,t)}catch(s){if(s?.statusCode===404||s?.status===404)return{value:void 0,etag:void 0};throw s}return{value:JSON.parse(await n.blob.text()),etag:n.etag}}async stat(e,t){let{status:n,headers:s}=await this.transport.head(F(this.base,e),t);if(n===404)throw Object.assign(new Error("not found"),{status:404});if(n>=400)throw Object.assign(new Error("stat failed"),{status:n});let i=parseInt(s.get("content-length")??"0",10);return{path:s.get("x-file-path")??e,size:i,content_type:s.get("content-type")??void 0,etag:(s.get("etag")??"").replace(/"/g,"")||void 0,url:s.get("x-file-url")??""}}async exists(e,t){let{status:n}=await this.transport.head(F(this.base,e),t);return n>=200&&n<400}async del(e,t){await this.transport.deletePath(F(this.base,e),t)}async list(e){let t=new URLSearchParams;e?.prefix&&t.set("prefix",e.prefix),e?.cursor&&t.set("cursor",e.cursor),e?.limit&&t.set("limit",String(e.limit)),e?.glob&&t.set("glob",e.glob);let n=t.toString();return this.transport.getJSON(this.base+(n?"?"+n:""),e?.signal?{signal:e.signal}:void 0)}async deleteMany(e,t){return this.transport.postJSON(this.base+"/delete",{prefix:e.prefix??"",glob:e.glob??""},t)}async move(e,t,n){return this.transport.postJSON(this.base+"/move",{from:e,to:t},n)}async copy(e,t,n){return this.transport.postJSON(this.base+"/copy",{from:e,to:t},n)}async putFromURL(e,t,n){return this.transport.postJSON(this.base+"/put-url",{path:e,src_url:t,content_type:n?.contentType,if_none_match:n?.ifNoneMatch,if_match:n?.ifMatch},n?.signal?{signal:n.signal}:void 0)}async batch(e,t){if(e.length===0)return[];let n=30;if(e.length<=n)return(await this.transport.postJSON(this.base+"/batch",{ops:e},t)).results;let s=[];for(let i=0;i<e.length;i+=n){let o=e.slice(i,i+n),a=await this.transport.postJSON(this.base+"/batch",{ops:o},t);s.push(...a.results)}return s}};var ne=class{constructor(e,t){l(this,"transport",e);l(this,"events",t)}async create(e,t,n){return h(this.events,{model:e,capability:"embedding"},()=>this.transport.postJSON("/v1/embeddings",{model:e,...t},n),s=>({totalTokens:s.usage?.total_tokens,costUSD:s.usage?.total_cost}))}};var C=class{constructor(){l(this,"active",new Map);l(this,"recent",[]);l(this,"session",{totalCalls:0,totalCostUSD:0,errorCount:0,startedAt:Date.now()});l(this,"lastErrorAt",0);l(this,"changeListeners",new Set)}attach(e){let t=[e.on("request:start",n=>{this.onStart(n),this.notify()}),e.on("request:streamDelta",n=>{this.onDelta(n),this.notify()}),e.on("request:end",n=>{this.onEnd(n),this.notify()}),e.on("request:error",n=>{this.onError(n),this.notify()})];return()=>{for(let n of t)n()}}onChange(e){return this.changeListeners.add(e),()=>this.changeListeners.delete(e)}notify(){for(let e of this.changeListeners)try{e()}catch(t){console.error("[runapps sdk] ActivityTracker onChange listener threw:",t)}}snapshot(){let e=Date.now();return{active:Array.from(this.active.values()),recent:this.recent.slice(),session:{...this.session},status:e-this.lastErrorAt<3e4?"error":this.active.size>0?"active":"idle"}}onStart(e){this.active.set(e.id,{id:e.id,model:e.model,capability:e.capability,startedAt:e.startedAt,streaming:e.streaming,tokensSoFar:0,tokensPerSec:0,rateSamples:[]})}onDelta(e){let t=this.active.get(e.id);if(!t)return;t.tokensSoFar=e.totalTokens;let n=Date.now();t.rateSamples.push({t:n,tokens:e.deltaTokens});let s=n-1500;for(;t.rateSamples.length>0&&t.rateSamples[0].t<s;)t.rateSamples.shift();if(t.rateSamples.length>=2){let i=t.rateSamples.reduce((a,u)=>a+u.tokens,0),o=n-t.rateSamples[0].t;t.tokensPerSec=o>0?i*1e3/o:0}}onEnd(e){let t=this.active.get(e.id);this.active.delete(e.id),this.pushRecent({id:e.id,model:e.model,capability:e.capability,latencyMs:e.latencyMs,totalTokens:e.totalTokens||t?.tokensSoFar||0,...e.costUSD!==void 0&&{costUSD:e.costUSD},...e.finishReason!==void 0&&{finishReason:e.finishReason},ok:!0,endedAt:Date.now()}),this.session.totalCalls+=1,e.costUSD!==void 0&&(this.session.totalCostUSD+=e.costUSD)}onError(e){let t=this.active.get(e.id);this.active.delete(e.id),this.pushRecent({id:e.id,model:e.model,capability:e.capability,latencyMs:e.latencyMs,totalTokens:t?.tokensSoFar||0,ok:!1,errorMessage:e.error.message,endedAt:Date.now()}),this.session.totalCalls+=1,this.session.errorCount+=1,this.lastErrorAt=Date.now()}pushRecent(e){this.recent.unshift(e),this.recent.length>20&&(this.recent.length=20)}};var He=60,Je="__runapps_auth_v1__",Ve="__runjobs_auth_v1__",ze="__runapps_signed_out_v1__",We="__runjobs_signed_out_v1__";function $(r){return r?`${Je}:${r}`:Je}function re(r){return r?`${ze}:${r}`:ze}function de(r){return r?`${Ve}:${r}`:Ve}function Ye(r){return r?`${We}:${r}`:We}var A=class{constructor(e={}){l(this,"origin");l(this,"hideBadge");l(this,"project");l(this,"events");l(this,"tracker");l(this,"badgePosition");l(this,"token",null);l(this,"expiresAt",0);l(this,"userInfo",null);l(this,"listeners",[]);l(this,"parentHandshake",null);l(this,"signingIn",!1);l(this,"getToken",async()=>{if(this.tokenIsFresh())return this.token;if(this.isSignedOut())throw new Error("RunApps: signed out \u2014 call client.signIn() to authenticate");if(this.inIframe()){try{this.parentHandshake&&(await this.parentHandshake,this.parentHandshake=null),this.tokenIsFresh()||await this.requestTokenFromParent()}catch{}if(this.tokenIsFresh())return this.token;throw new Error("RunApps: could not obtain a token from the dashboard")}return this.parentHandshake&&(await this.parentHandshake,this.tokenIsFresh())?this.token:(this.signIn(),new Promise(()=>{}))});this.origin=(e.origin??"https://www.runapps.ai").replace(/\/$/,""),this.hideBadge=!!e.hideBadge,this.project=e.project??null,this.events=e.events??null,this.badgePosition=e.badgePosition??"bottom-right",this.events&&!this.hideBadge?(this.tracker=new C,this.tracker.attach(this.events)):this.tracker=null,!(typeof window>"u")&&(this.loadPersisted(),this.consumeFragment()&&this.clearSignedOut(),this.isSignedOut()||(this.inIframe()&&!this.tokenIsFresh()?this.parentHandshake=this.requestTokenFromParent().catch(()=>{}):this.tokenIsFresh()&&this.userInfo&&!this.hideBadge&&this.renderBadge()))}onTokenChange(e){return this.listeners.push(e),()=>{let t=this.listeners.indexOf(e);t>=0&&this.listeners.splice(t,1)}}get user(){return this.userInfo}hasFreshToken(){return this.tokenIsFresh()}signOut(){this.token=null,this.expiresAt=0,this.userInfo=null,this.parentHandshake=null,this.signingIn=!1,this.clearPersisted(),this.markSignedOut(),this.removeBadge()}invalidate(){this.token=null,this.expiresAt=0,this.userInfo=null,this.parentHandshake=null,this.signingIn=!1,this.clearPersisted()}signIn(){if(typeof window>"u"||this.signingIn)return;this.clearSignedOut(),this.signingIn=!0;let e=location.href.split("#")[0]??location.href,t=window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light";location.href=this.buildGrantUrl({pageOrigin:location.origin,app:location.host,redirectTo:e,scheme:t})}_buildGrantUrlForTest(e){return this.buildGrantUrl(e)}_storageKeysForTest(){return{auth:$(this.project),signedOut:re(this.project)}}buildGrantUrl(e){let t=new URLSearchParams;return t.set("origin",e.pageOrigin),t.set("app",e.app),t.set("redirect_to",e.redirectTo),t.set("scheme",e.scheme),this.project&&t.set("project_id",this.project),t.set("token_name","runapps_token"),this.origin+"/api/sdk/grant?"+t.toString()}nowSec(){return Math.floor(Date.now()/1e3)}tokenIsFresh(){return!!this.token&&this.nowSec()<this.expiresAt-He}inIframe(){try{return window.self!==window.top}catch{return!0}}setToken(e,t,n){this.token=e,this.expiresAt=t||this.nowSec()+3600,n&&(this.userInfo=n,this.hideBadge||this.renderBadge()),this.savePersisted();for(let s of this.listeners)try{s(e)}catch(i){console.warn("[runapps] onTokenChange handler threw",i)}}savePersisted(){if(!(typeof localStorage>"u"||!this.token))try{let e={token:this.token,expiresAt:this.expiresAt,origin:this.origin,...this.userInfo?{user:this.userInfo}:{}};localStorage.setItem($(this.project),JSON.stringify(e))}catch{}}loadPersisted(){if(!(typeof localStorage>"u"))try{let e=localStorage.getItem($(this.project));if(!e){if(e=localStorage.getItem(de(this.project)),!e)return;localStorage.setItem($(this.project),e),localStorage.removeItem(de(this.project))}let t=JSON.parse(e);if(!t.token||!t.origin||t.origin!==this.origin)return;if(typeof t.expiresAt=="number"&&t.expiresAt>0&&this.nowSec()>=t.expiresAt-He){this.clearPersisted();return}this.token=t.token,this.expiresAt=t.expiresAt??0,t.user&&(this.userInfo=t.user)}catch{this.clearPersisted()}}clearPersisted(){if(!(typeof localStorage>"u"))try{localStorage.removeItem($(this.project)),localStorage.removeItem(de(this.project))}catch{}}isSignedOut(){if(typeof localStorage>"u")return!1;try{return localStorage.getItem(re(this.project))==="1"||localStorage.getItem(Ye(this.project))==="1"}catch{return!1}}markSignedOut(){if(!(typeof localStorage>"u"))try{localStorage.setItem(re(this.project),"1")}catch{}}clearSignedOut(){if(!(typeof localStorage>"u"))try{localStorage.removeItem(re(this.project)),localStorage.removeItem(Ye(this.project))}catch{}}removeBadge(){typeof document>"u"||document.getElementById("__runapps_identity__")?.remove()}consumeFragment(){if(!location.hash||!/(^#|&)run(apps|jobs)_token=/.test(location.hash))return!1;let e={};location.hash.replace(/^#/,"").split("&").forEach(s=>{let i=s.indexOf("=");i>=0&&(e[decodeURIComponent(s.slice(0,i))]=decodeURIComponent(s.slice(i+1)))});let t=e.runapps_token||e.runjobs_token;if(!t)return!1;let n;if(e.user)try{n=JSON.parse(e.user)}catch{}this.setToken(t,parseInt(e.expires_at??"",10)||0,n);try{history.replaceState(null,"",location.pathname+location.search)}catch{}return!0}requestTokenFromParent(){return new Promise((e,t)=>{let n=!1,s=[],i=()=>{n=!0,window.removeEventListener("message",o);for(let u of s)clearTimeout(u)},o=u=>{if(u.origin!==this.origin)return;let c=u.data;c&&(c.type==="runapps:token"||c.type==="runjobs:token")&&c.token&&(this.setToken(c.token,c.expires_at??0,c.user),i(),e())};window.addEventListener("message",o);let a=()=>{if(!n)try{window.parent.postMessage({type:"runapps:request-token"},this.origin),window.parent.postMessage({type:"runjobs:request-token"},this.origin)}catch(u){i(),t(u)}};a();for(let u of[250,750,1500,3e3])s.push(setTimeout(a,u));s.push(setTimeout(()=>{n||(i(),t(new Error("runapps: parent handshake timeout")))},5e3))})}renderBadge(){if(typeof document>"u"||!this.userInfo)return;let e="__runapps_identity__",t=`${this.origin}/dashboard`;(s=>document.body?s():document.addEventListener("DOMContentLoaded",s))(()=>{document.getElementById(e)?.remove();let s=Dt({id:e,user:this.userInfo,dashboardUrl:t,tracker:this.tracker,position:this.badgePosition,onSignOut:()=>{this.signOut(),typeof window<"u"&&window.location.reload()}});document.body.appendChild(s)})}};function Pt(){if(typeof document>"u"||document.getElementById("__runapps_kf__"))return;let r=document.createElement("style");r.id="__runapps_kf__",r.textContent="@keyframes __runapps_led_pulse__ { 0% { box-shadow: 0 0 0 0 rgba(59,130,246,0.7); } 70% { box-shadow: 0 0 0 6px rgba(59,130,246,0); } 100% { box-shadow: 0 0 0 0 rgba(59,130,246,0); }}",(document.head??document.documentElement).appendChild(r)}function It(r){let e=r.startsWith("top")?"top":"bottom",t=r.endsWith("right")?"right":"left",n=e==="bottom"?"bottom:calc(100% + 8px);top:auto":"top:calc(100% + 8px);bottom:auto",s=t==="right"?"right:0;left:auto":"left:0;right:auto";return{badge:`${e}:16px;${t}:16px`,popover:`${n};${s}`}}var Ze="__runapps_badge_pos__",Mt="__runjobs_badge_pos__",Xe=5,E=8;function Ot(){if(typeof document>"u")return null;let r=document.cookie.split(";").map(c=>c.trim()),e=Ze,t=r.find(c=>c.startsWith(e+"="));if(t||(e=Mt,t=r.find(c=>c.startsWith(e+"="))),!t)return null;let s=decodeURIComponent(t.slice(e.length+1)).split(","),i=s[0],o=s[1];if(s.length!==2||i===void 0||o===void 0)return null;let a=Number.parseInt(i,10),u=Number.parseInt(o,10);return!Number.isFinite(a)||!Number.isFinite(u)?null:{x:a,y:u}}function Ut(r,e){if(typeof document>"u")return;let t=3600*24*365,n=typeof window<"u"&&window.location?.protocol==="https:"?";Secure":"";document.cookie=`${Ze}=${encodeURIComponent(`${Math.round(r)},${Math.round(e)}`)};path=/;max-age=${t};SameSite=Lax${n}`}function Qe(r,e,t,n){let s=typeof window<"u"?window.innerWidth:1024,i=typeof window<"u"?window.innerHeight:768,o=Math.max(E,s-t-E),a=Math.max(E,i-n-E);return{x:Math.min(Math.max(E,r),o),y:Math.min(Math.max(E,e),a)}}function jt(r){let e=typeof window<"u"?window.innerWidth:1024,t=typeof window<"u"?window.innerHeight:768,n=r.left+r.width/2,i=r.top+r.height/2<t/2?"top:calc(100% + 8px);bottom:auto":"bottom:calc(100% + 8px);top:auto",o=n<e/2?"left:0;right:auto":"right:0;left:auto";return`${i};${o}`}function Dt(r){let{id:e,user:t,dashboardUrl:n,tracker:s,position:i,onSignOut:o}=r,a=It(i),u=a.popover;Pt();let c=document.createElement("button");c.id=e,c.type="button",c.title="RunApps activity",c.setAttribute("aria-label","RunApps activity status"),c.style.cssText=["position:fixed",a.badge,"z-index:2147483647","display:flex","align-items:center","gap:8px","padding:6px 12px 6px 6px","border-radius:999px","font:500 12px/1 -apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif","color:#fff","background:rgba(15,15,20,0.55)","backdrop-filter:blur(10px) saturate(1.2)","-webkit-backdrop-filter:blur(10px) saturate(1.2)","border:1px solid rgba(255,255,255,0.12)","box-shadow:0 4px 16px rgba(0,0,0,0.15)","user-select:none","max-width:220px","overflow:visible","cursor:pointer","appearance:none","-webkit-appearance:none","transition:background-color 120ms ease-out, box-shadow 120ms ease-out"].join(";"),c.addEventListener("mouseenter",()=>{c.style.backgroundColor="rgba(30,30,40,0.7)",c.style.boxShadow="0 6px 20px rgba(0,0,0,0.22)"}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="rgba(15,15,20,0.55)",c.style.boxShadow="0 4px 16px rgba(0,0,0,0.15)"});let d=document.createElement("span");d.style.cssText=["position:relative","width:26px;height:26px","flex-shrink:0","display:inline-flex;align-items:center;justify-content:center"].join(";");let g="http://www.w3.org/2000/svg",b=document.createElementNS(g,"svg");b.setAttribute("viewBox","0 0 26 26"),b.setAttribute("width","26"),b.setAttribute("height","26"),b.style.cssText=["position:absolute;inset:0","pointer-events:none","opacity:0","transition:opacity 200ms ease-out"].join(";");let S=document.createElementNS(g,"circle");S.setAttribute("cx","13"),S.setAttribute("cy","13"),S.setAttribute("r","12"),S.setAttribute("fill","none"),S.setAttribute("stroke","rgba(255,255,255,0.08)"),S.setAttribute("stroke-width","1.5");let y=document.createElementNS(g,"circle");y.setAttribute("cx","13"),y.setAttribute("cy","13"),y.setAttribute("r","12"),y.setAttribute("fill","none"),y.setAttribute("stroke","#3b82f6"),y.setAttribute("stroke-width","2"),y.setAttribute("stroke-linecap","round"),y.setAttribute("transform","rotate(-90 13 13)");let ie=2*Math.PI*12;y.setAttribute("stroke-dasharray",String(ie)),y.setAttribute("stroke-dashoffset",String(ie)),b.appendChild(S),b.appendChild(y);let oe=document.createElement("div");oe.textContent=(t.name||"?").charAt(0).toUpperCase(),oe.style.cssText=["width:22px;height:22px;border-radius:50%;flex-shrink:0","display:flex;align-items:center;justify-content:center","background:linear-gradient(135deg,#3b82f6,#8b5cf6)","font-size:11px;font-weight:600;color:#fff","position:relative"].join(";");let K=document.createElement("span");K.style.cssText=["position:absolute","bottom:-2px;right:-2px","width:8px;height:8px;border-radius:50%","background:rgba(255,255,255,0.2)","border:2px solid rgba(15,15,20,1)","box-shadow:0 0 0 0 transparent","transition:background-color 150ms ease-out, box-shadow 200ms ease-out","pointer-events:none"].join(";"),d.appendChild(b),d.appendChild(oe),d.appendChild(K);let ae=document.createElement("span");ae.textContent=t.name||"Signed in",ae.style.cssText="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;pointer-events:none",c.appendChild(d),c.appendChild(ae);let f=null,w=!1,_=null,N=null,q=null,le=()=>{N!==null&&(window.clearTimeout(N),N=null)},R=()=>{q!==null&&(window.clearTimeout(q),q=null)},me=()=>{R(),q=window.setTimeout(()=>{_==="hover"&&P()},300)},he=p=>{if(le(),R(),w){p==="click"&&(_="click");return}f||(f=$t(n,u,()=>{P(),o()}),f.addEventListener("mouseenter",R),f.addEventListener("mouseleave",()=>{_==="hover"&&me()})),c.appendChild(f),w=!0,_=p,H()},P=()=>{R(),w&&(f?.remove(),w=!1,_=null)};c.addEventListener("click",p=>{p.stopPropagation(),w?P():he("click")}),c.addEventListener("mouseenter",()=>{R(),le(),N=window.setTimeout(()=>{w||he("hover")},400)}),c.addEventListener("mouseleave",()=>{le(),_==="hover"&&me()}),document.addEventListener("click",p=>{w&&!c.contains(p.target)&&P()});let fe=0,be=0,ye=0,we=0,G=!1,I=!1,ce=!1,ue=(p,m)=>{c.style.left=`${p}px`,c.style.top=`${m}px`,c.style.right="auto",c.style.bottom="auto"},ve=()=>{let p=c.getBoundingClientRect();if(u=jt({left:p.left,top:p.top,width:p.width,height:p.height}),f){f.style.top="",f.style.bottom="",f.style.left="",f.style.right="";for(let m of u.split(";")){let[U,j]=m.split(":");U&&j&&f.style.setProperty(U.trim(),j.trim())}}};c.addEventListener("pointerdown",p=>{if(p.button!==0)return;G=!0,I=!1,fe=p.clientX,be=p.clientY;let m=c.getBoundingClientRect();ye=m.left,we=m.top}),c.addEventListener("pointermove",p=>{if(!G)return;let m=p.clientX-fe,U=p.clientY-be;if(!I){if(Math.abs(m)<Xe&&Math.abs(U)<Xe)return;I=!0,c.setPointerCapture(p.pointerId),c.style.cursor="grabbing",w&&P()}let j=c.getBoundingClientRect(),_e=Qe(ye+m,we+U,j.width,j.height);ue(_e.x,_e.y)});let xe=p=>{if(!G||(G=!1,!I))return;I=!1,c.style.cursor="pointer",c.hasPointerCapture(p.pointerId)&&c.releasePointerCapture(p.pointerId);let m=c.getBoundingClientRect();Ut(m.left,m.top),ve(),ce=!0};c.addEventListener("pointerup",xe),c.addEventListener("pointercancel",xe),c.addEventListener("click",p=>{ce&&(ce=!1,p.stopPropagation(),p.preventDefault())},!0);let M=Ot();M&&(ue(M.x,M.y),requestAnimationFrame(()=>{let p=c.getBoundingClientRect(),m=Qe(M.x,M.y,p.width,p.height);ue(m.x,m.y),ve()}));let pe=!1,O=null,Se=()=>{if(pe=!1,!s){b.style.opacity="0",K.style.background="rgba(255,255,255,0.2)";return}let p=s.snapshot();Bt(b,y,ie,p),Ft(K,p),w&&f&&Lt(f,p);let m=p.status!=="idle"||w;m&&O===null?O=window.setInterval(H,160):!m&&O!==null&&(window.clearInterval(O),O=null)};function H(){pe||(pe=!0,typeof requestAnimationFrame=="function"?requestAnimationFrame(Se):setTimeout(Se,0))}return s&&s.onChange(H),H(),c}function Bt(r,e,t,n){if(n.active.length===0){r.style.opacity="0";return}r.style.opacity="1";let s=n.active.reduce((i,o)=>o.tokensPerSec>i.tokensPerSec?o:i,n.active[0]);if(s.streaming&&s.tokensPerSec>0){let i=Math.min(s.tokensPerSec/60,1);e.setAttribute("stroke-dashoffset",String(t*(1-i))),e.setAttribute("stroke","#3b82f6")}else n.status==="error"?(e.setAttribute("stroke-dashoffset","0"),e.setAttribute("stroke","#ef4444")):(e.setAttribute("stroke-dashoffset",String(t*.75)),e.setAttribute("stroke","#a78bfa"))}function Ft(r,e){switch(e.status){case"idle":r.style.background="rgba(255,255,255,0.2)",r.style.boxShadow="0 0 0 0 transparent";break;case"active":r.style.background="#3b82f6",r.style.boxShadow="0 0 0 0 rgba(59,130,246,0.7)",r.style.animation="__runapps_led_pulse__ 1.2s ease-out infinite";break;case"error":r.style.background="#ef4444",r.style.boxShadow="0 0 0 2px rgba(239,68,68,0.3)",r.style.animation="";break}}function $t(r,e,t){let n=document.createElement("div");n.style.cssText=["position:absolute",e,"min-width:280px;max-width:340px","padding:10px 12px","border-radius:10px","background:rgba(15,15,20,0.92)","backdrop-filter:blur(20px) saturate(1.3)","-webkit-backdrop-filter:blur(20px) saturate(1.3)","border:1px solid rgba(255,255,255,0.12)","box-shadow:0 10px 30px rgba(0,0,0,0.4)","color:#fff","font:400 11px/1.4 -apple-system,BlinkMacSystemFont,'Segoe UI',system-ui,sans-serif","cursor:default","text-align:left"].join(";"),n.setAttribute("data-runapps-popover","1"),n.addEventListener("click",u=>u.stopPropagation());let s=document.createElement("div");s.setAttribute("data-runapps-popover-content","1"),n.appendChild(s);let i=document.createElement("div");i.style.cssText=["margin-top:10px;padding-top:8px","border-top:1px solid rgba(255,255,255,0.08)","display:flex;justify-content:space-between;align-items:center","font-size:10px;color:rgba(255,255,255,0.6)"].join(";");let o=document.createElement("a");o.textContent="Open dashboard \u2192",o.href=r,o.target="_blank",o.rel="noopener noreferrer",o.style.cssText="color:#a78bfa;text-decoration:none",i.appendChild(o);let a=document.createElement("button");return a.type="button",a.textContent="Sign out",a.style.cssText=["background:none;border:0;padding:0;margin:0","font:inherit;cursor:pointer","color:rgba(255,255,255,0.55)","transition:color 120ms ease"].join(";"),a.addEventListener("mouseenter",()=>{a.style.color="#f87171"}),a.addEventListener("mouseleave",()=>{a.style.color="rgba(255,255,255,0.55)"}),a.addEventListener("click",u=>{u.preventDefault(),u.stopPropagation(),t()}),i.appendChild(a),n.appendChild(i),n}function Lt(r,e){let t=r.querySelector("[data-runapps-popover-content]");if(!t)return;t.innerHTML="";let n=Date.now();t.appendChild(Kt(e,n)),t.appendChild(Nt(e,n)),t.appendChild(qt(e.session,n))}function Kt(r,e){let t=document.createElement("div");if(t.style.marginBottom="10px",t.appendChild(ge("Active",r.active.length>0?`${r.active.length} in flight`:"\u2014")),r.active.length===0){let n=document.createElement("div");return n.style.cssText="color:rgba(255,255,255,0.4);font-size:10px;padding:2px 0",n.textContent="No calls in flight.",t.appendChild(n),t}for(let n of r.active){let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0";let i=document.createElement("span");i.style.cssText="color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px",i.textContent=n.model;let o=document.createElement("span");o.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums;font-size:10px";let a=((e-n.startedAt)/1e3).toFixed(1),u=n.tokensPerSec>0?` \xB7 ${Math.round(n.tokensPerSec)} tok/s`:"";o.textContent=`${a}s${u}`,s.appendChild(i),s.appendChild(o),t.appendChild(s)}return t}function Nt(r,e){let t=document.createElement("div");if(t.style.marginBottom="10px",t.appendChild(ge("Recent",r.recent.length>0?`last ${Math.min(r.recent.length,5)}`:"\u2014")),r.recent.length===0){let n=document.createElement("div");return n.style.cssText="color:rgba(255,255,255,0.4);font-size:10px;padding:2px 0",n.textContent="Nothing yet this session.",t.appendChild(n),t}for(let n of r.recent.slice(0,5)){let s=document.createElement("div");s.style.cssText="display:flex;justify-content:space-between;gap:8px;padding:3px 0";let i=document.createElement("span");i.style.cssText="color:#fff;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:180px";let o=document.createElement("span");o.textContent=n.ok?"\u2713 ":"\u2717 ",o.style.color=n.ok?"#10b981":"#ef4444",i.appendChild(o),i.appendChild(document.createTextNode(n.model));let a=document.createElement("span");a.style.cssText="color:rgba(255,255,255,0.7);font-variant-numeric:tabular-nums;font-size:10px";let u=`${(n.latencyMs/1e3).toFixed(1)}s`,c=n.costUSD!==void 0?` \xB7 $${n.costUSD.toFixed(4)}`:"",d=` \xB7 ${et(e-n.endedAt)}`;a.textContent=`${u}${c}${d}`,s.appendChild(i),s.appendChild(a),t.appendChild(s)}return t}function qt(r,e){let t=document.createElement("div");t.appendChild(ge("Session",et(e-r.startedAt)));let n=document.createElement("div");n.style.cssText="display:flex;justify-content:space-between;gap:12px;color:rgba(255,255,255,0.85);font-size:10px";let s=document.createElement("span");s.textContent=`${r.totalCalls} call${r.totalCalls===1?"":"s"}`;let i=document.createElement("span");i.textContent=`$${r.totalCostUSD.toFixed(4)}`;let o=document.createElement("span");return o.textContent=r.errorCount>0?`${r.errorCount} error${r.errorCount===1?"":"s"}`:"0 errors",r.errorCount>0&&(o.style.color="#ef4444"),n.appendChild(s),n.appendChild(i),n.appendChild(o),t.appendChild(n),t}function ge(r,e){let t=document.createElement("div");t.style.cssText=["display:flex;justify-content:space-between;align-items:baseline","margin-bottom:4px","color:rgba(255,255,255,0.55)","font-size:10px;text-transform:uppercase;letter-spacing:0.05em"].join(";");let n=document.createElement("span");n.textContent=r;let s=document.createElement("span");return s.textContent=e,s.style.cssText="font-size:9px;letter-spacing:0",t.appendChild(n),t.appendChild(s),t}function et(r){return r<1500?"just now":r<6e4?`${Math.round(r/1e3)}s ago`:r<36e5?`${Math.round(r/6e4)}m ago`:`${Math.round(r/36e5)}h ago`}var Gt="https://www.runapps.ai",T=class{constructor(e={}){l(this,"chat");l(this,"models");l(this,"image");l(this,"audio");l(this,"video");l(this,"computer");l(this,"files");l(this,"embeddings");l(this,"auth",null);l(this,"events",new k);let t=e.authProvider??(!e.apiKey&&!e.apiKeyResolver&&typeof window<"u"?"runapps":"static"),n=e.apiKeyResolver,s=e.baseURL,i;if(t==="runapps"||t==="runjobs"){s=s??"https://www.runapps.ai";let a=e.showIdentityBadge!==void 0?e.showIdentityBadge:e.hideIdentityBadge!==void 0?!e.hideIdentityBadge:!0,u=new A({origin:s,hideBadge:!a,events:this.events,...e.badgePosition!==void 0&&{badgePosition:e.badgePosition},...e.project!==void 0&&{project:e.project}});this.auth=u,n=u.getToken,i=()=>u.invalidate()}if(!e.apiKey&&!n)throw new Error("runapps: pass `apiKey` (or `apiKeyResolver`); outside a browser there is no sign-in to fall back to");let o=new V({baseURL:s??Gt,...e.apiKey!==void 0&&{apiKey:e.apiKey},...n!==void 0&&{apiKeyResolver:n},...i!==void 0&&{onUnauthorized:i},...e.fetch?{fetchImpl:e.fetch}:{}});this.chat=new z(o,this.events),this.models=new W(o),this.image=new Y(o,this.events),this.audio=new X(o,this.events),this.video=new Z(o,this.events),this.computer=new ee(o,this.events),this.files=new te(o,e.project),this.embeddings=new ne(o,this.events)}signIn(){this.auth?.signIn()}signOut(){this.auth?.signOut()}get user(){return this.auth?.user??null}};function tt(r){return r?r.map(e=>Array.isArray(e)?{fields:e}:e):[]}function L(r){let e=r.options;return!e||typeof e!="object"?null:e}function nt(r,e){let n=L(r)?.inputs?.[e];return n?n.presence!=="forbidden":!1}function rt(r,e){return L(r)?.inputs?.[e]?.presence==="required"}function st(r,e){return L(r)?.inputs?.[e]?.enum??null}function at(r,e={}){if(!r)return[];let t=[];if(r.inputs)for(let[n,s]of Object.entries(r.inputs)){let i=n in e,o=e[n];i&&!v(o)?t.push(...lt(n,s,o)):i&&s.min_items!==void 0&&Array.isArray(o)&&o.length<s.min_items&&t.push({field:n,reason:`at least ${s.min_items} items`}),t.push(...ct(n,s,o,i))}for(let n of r.constraints??[])t.push(...Ht(n,e));return t}function lt(r,e,t){let n=[];if(!Jt(e.type,t))return n.push({field:r,reason:`expected type ${e.type}, got ${se(t)}`}),n;if(e.enum&&e.enum.length>0&&!Vt(t,e.enum)&&n.push({field:r,reason:`must be one of ${JSON.stringify(e.enum)}`}),e.type==="int"||e.type==="float"){let s=ut(t);s!==null&&(e.min!==void 0&&s<e.min&&n.push({field:r,reason:`must be >= ${e.min}`}),e.max!==void 0&&s>e.max&&n.push({field:r,reason:`must be <= ${e.max}`}))}return Array.isArray(t)&&(e.max_items!==void 0&&t.length>e.max_items&&n.push({field:r,reason:`at most ${e.max_items} items`}),e.min_items!==void 0&&t.length<e.min_items&&n.push({field:r,reason:`at least ${e.min_items} items`})),e.fields&&(e.repeatable?Array.isArray(t)?t.forEach((s,i)=>{if(typeof s!="object"||s===null||Array.isArray(s)){n.push({field:`${r}[${i}]`,reason:`expected object, got ${se(s)}`});return}n.push(...it(`${r}[${i}]`,e.fields,s))}):n.push({field:r,reason:`expected array of objects, got ${se(t)}`}):typeof t!="object"||t===null||Array.isArray(t)?n.push({field:r,reason:`expected object, got ${se(t)}`}):n.push(...it(r,e.fields,t))),n}function it(r,e,t){let n=[];for(let[s,i]of Object.entries(e)){let o=`${r}.${s}`,a=t[s],u=s in t;u&&!v(a)&&n.push(...lt(o,i,a)),n.push(...ct(o,i,a,u))}return n}function ct(r,e,t,n){let s=e.presence??"optional";return s==="required"&&(!n||v(t))?[{field:r,reason:"required"}]:s==="forbidden"&&n&&!v(t)?[{field:r,reason:"must not be set for this model"}]:[]}function Ht(r,e){switch(r.kind){case"any_of_required":{let t=r.fields??[];return t.some(s=>s in e&&!v(e[s]))?[]:[{field:t.join("/"),reason:`at least one of ${t.join(", ")} is required`}]}case"mutually_exclusive":{let t=r.fields??[],n=t.filter(s=>s in e&&!v(e[s]));return n.length>1?[{field:n.join("/"),reason:`at most one of ${t.join(", ")} may be set (got: ${n.join(", ")})`}]:[]}case"group_mutex":{let t=tt(r.groups),n=[],s=[];for(let i of t){let o=i.fields.filter(a=>a in e&&!v(e[a]));o.length>0&&(n.push(i),s.push(...o))}if(n.length>1){let i=t.map(o=>`[${o.fields.join("+")}]`).join(" or ");return[{field:s.join("/"),reason:`at most one of ${i} may be used (got: ${s.join(", ")})`}]}return[]}case"requires_all":{let t=r.when;if(!t)return[];if(!(t in e&&!v(e[t])))return[];let s=(r.then??[]).filter(i=>!(i in e)||v(e[i]));return s.length===0?[]:[{field:s.join("/"),reason:`required when ${t} is set`}]}case"pixel_bounds":{let t=r.fields?.[0];if(!t)return[];let n=e[t];if(typeof n!="string"||n==="")return[];let s=Wt(n);if(!s)return[{field:t,reason:`expected WxH dimensions, got "${n}"`}];let[i,o]=s,a=i*o,u=[];return r.min!==void 0&&a<r.min&&u.push({field:t,reason:`image too small: ${i}x${o} = ${a} pixels, minimum ${r.min}`}),r.max!==void 0&&a>r.max&&u.push({field:t,reason:`image too large: ${i}x${o} = ${a} pixels, maximum ${r.max}`}),u}}return[]}function Jt(r,e){switch(r){case"string":return typeof e=="string";case"int":case"float":return ut(e)!==null;case"bool":return typeof e=="boolean";case"url":return typeof e=="string"&&ot(e);case"url[]":return Array.isArray(e)&&e.every(t=>typeof t=="string"&&ot(t));case"string[]":return Array.isArray(e)&&e.every(t=>typeof t=="string");case"file":return!0;default:return!0}}function se(r){return r===null?"null":Array.isArray(r)?"array":typeof r}function ut(r){return typeof r=="number"&&Number.isFinite(r)?r:null}function ot(r){return r.startsWith("http://")||r.startsWith("https://")||r.startsWith("data:")}function v(r){return r==null?!0:typeof r=="string"?r==="":Array.isArray(r)?r.length===0:!1}function Vt(r,e){for(let t of e)if(zt(r,t))return!0;return!1}function zt(r,e){return r===e}function Wt(r){for(let e of["x","X","*","\xD7"]){let t=r.indexOf(e);if(t<=0)continue;let n=parseInt(r.slice(0,t).trim(),10),s=parseInt(r.slice(t+e.length).trim(),10);if(Number.isFinite(n)&&Number.isFinite(s)&&n>0&&s>0)return[n,s]}return null}return bt(Yt);})();
|
|
3
3
|
RunApps = Object.assign(RunApps.Client, RunApps); var RunJobs = RunApps;
|
|
4
4
|
//# sourceMappingURL=sdk.umd.js.map
|