@soba-so/react 0.0.6 → 0.0.7

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.
@@ -1,4 +1,5 @@
1
1
  import { type ReactNode } from "react";
2
+ import type { CurrentPlan, Plan } from "./types.js";
2
3
  export interface SobaProviderProps {
3
4
  children: ReactNode;
4
5
  /**
@@ -26,6 +27,23 @@ export interface SobaProviderProps {
26
27
  /** Your route that starts a run with `@soba-so/sdk` and forwards the stream. */
27
28
  runEndpoint?: string;
28
29
  baseUrl?: string;
30
+ /**
31
+ * PLANS THE SERVER ALREADY FETCHED, so the first paint has prices in it.
32
+ *
33
+ * Without these the component cannot draw a price until two round trips have
34
+ * finished in sequence — mint an `est_` session, then read `/v1/plans` with
35
+ * it — and both start after mount, so every pricing page opened on a spinner.
36
+ * Neither trip can move to the server, because the session is per end user
37
+ * and the browser is the only party that has one.
38
+ *
39
+ * A server holding the app's secret key can read the same list directly
40
+ * (`soba.plans.list()`), and passing it here seeds the state rather than
41
+ * replacing the fetch: the provider still refreshes in the background, so a
42
+ * price changed since the page was rendered still corrects itself.
43
+ */
44
+ initialPlans?: Plan[];
45
+ /** What that user is on, if the server asked. Pairs with `initialPlans`. */
46
+ initialCurrentPlan?: CurrentPlan | null;
29
47
  pollMs?: number;
30
48
  /** The stylesheet injects itself once. Turn it off to ship your own. */
31
49
  injectStyles?: boolean;
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  "use client"
2
- var ee=class extends Error{status;constructor(t,n){super(t),this.name="ConnectError",this.status=n}},Q=class{session;baseUrl;doFetch;constructor(t){this.session=t.session,this.baseUrl=(t.baseUrl??"").replace(/\/+$/,""),this.doFetch=t.fetchImpl??fetch.bind(globalThis)}context(){return this.request("GET","/v1/connect")}async machines(){return(await this.request("GET","/v1/machines")).machines}lookup(t){return this.request("GET",`/v1/device/lookup?code=${encodeURIComponent(t)}`)}approve(t){return this.request("POST","/v1/device/approve",{user_code:t})}deny(t){return this.request("POST","/v1/device/deny",{user_code:t})}plans(){return this.request("GET","/v1/plans")}selectPlan(t){return this.request("POST","/v1/plans/select",{plan:t})}checkoutPlan(t,n){return this.request("POST","/v1/plans/checkout",{plan:t,...n?.successUrl?{success_url:n.successUrl}:{},...n?.cancelUrl?{cancel_url:n.cancelUrl}:{}})}leavePlan(){return this.request("DELETE","/v1/plans/select")}approveRuntime(t,n){return this.request("POST","/v1/runtimes/approve",{machine_id:t,runtime_id:n})}async request(t,n,c){let s=await this.doFetch(`${this.baseUrl}${n}`,{method:t,headers:{authorization:`Bearer ${this.session}`,...c?{"content-type":"application/json"}:{}},...c?{body:JSON.stringify(c)}:{}}),r={};try{r=await s.json()}catch{}if(!s.ok){let u=typeof r.error=="string"?r.error:`Request failed (${s.status})`;throw new ee(u,s.status)}return r}};function ce(e){return e.authenticated===!0?{tone:"ok",text:"signed in"}:e.authenticated===!1?{tone:"warn",text:e.auth_hint??"signed out on that machine"}:{tone:"unknown",text:"could not tell"}}function le(e){return e.state==="busy"?{tone:"busy",text:`serving ${e.active} of ${e.capacity}`}:e.state==="online"?{tone:"ok",text:"connected"}:{tone:"off",text:"asleep or offline"}}import{jsx as x,jsxs as V}from"react/jsx-runtime";function W({machines:e,onApproveRuntime:t}){return e.length?x("div",{children:e.map(n=>{let c=le(n);return V("div",{className:"sc-machine",children:[V("div",{className:"sc-row-between",children:[V("div",{className:"sc-row",children:[x("span",{className:`sc-dot sc-dot-${c.tone}`,"aria-hidden":"true"}),x("strong",{children:n.label??"This machine"})]}),x("span",{className:"sc-note",children:c.text})]}),x("p",{className:"sc-note",children:[n.platform,n.arch,n.version&&`worker ${n.version}`,n.always_on&&"always on"].filter(Boolean).join(" \xB7 ")}),V("ul",{className:"sc-runtimes",children:[n.runtimes.map(s=>{let r=ce(s);return s.quarantined?V("li",{className:"sc-row-between",children:[x("span",{children:s.display_name}),t?x("button",{type:"button",className:"sc-btn",onClick:()=>t(n.id,s.id),children:"New here. Let it serve"}):x("span",{className:"sc-tone-warn",children:"new, not serving yet"})]},s.id):V("li",{className:"sc-row-between",children:[x("span",{children:s.display_name}),x("span",{className:`sc-tone-${r.tone}`,children:r.text})]},s.id)}),!n.runtimes.length&&x("li",{className:"sc-note",children:"No runtime advertised. Install Claude Code, Codex or Ollama on that machine."})]})]},n.id)})}):x("p",{className:"sc-note",children:"Nothing connected yet."})}import{useCallback as te,useEffect as pe,useMemo as Fe,useRef as je,useState as $}from"react";var ue=[{id:"claude",title:"The Claude plan you already pay for",cost:"Nothing beyond the plan",prerequisite:"Claude Code installed, and signed in",hint:"Install it from claude.ai/code, then run `claude` once and sign in.",expects:["claude-code"]},{id:"chatgpt",title:"The ChatGPT plan you already pay for",cost:"Nothing beyond the plan",prerequisite:"Codex installed, and signed in",hint:"Install Codex, then run `codex` once and sign in.",expects:["codex"]},{id:"local",title:"A model on your own machine",cost:"Free. You bought the hardware",prerequisite:"Ollama running, with a model pulled",hint:"Install Ollama, then `ollama pull` a model before pairing.",expects:["ollama","openai-api"]}];import{Fragment as Ee,jsx as a,jsxs as f}from"react/jsx-runtime";var De=2e3,Be=1e4;function de({client:e,initialCode:t,onConnected:n,showStatus:c=!0}){let[s,r]=$("loading"),[u,y]=$(null),[g,h]=$([]),[b,o]=$(null),[m,v]=$(t??""),[k,D]=$(null),[A,_]=$(null),[I,R]=$(!1),q=je(null);pe(()=>{let l=!0;return Promise.all([e.context(),e.machines()]).then(([w,N])=>{l&&(y(w),h(N),q.current=new Set(N.map(T=>T.id)),t?r("code"):c&&N.length>0?r("manage"):r("choose"))}).catch(w=>{l&&(_(w.message),r("choose"))}),()=>{l=!1}},[e,t,c]),pe(()=>{if(s!=="manage")return;let l=!0,w=setInterval(async()=>{try{let N=await e.machines();l&&h(N)}catch{}},Be);return()=>{l=!1,clearInterval(w)}},[s,e]),pe(()=>{if(s!=="waiting")return;let l=!0,w=setInterval(async()=>{try{let N=await e.machines();if(!l)return;h(N);let T=N.filter(H=>!q.current?.has(H.id));(T.find(H=>H.state!=="offline")??T[0])&&(r("connected"),n?.(N))}catch{}},De);return()=>{l=!1,clearInterval(w)}},[s,e,n]);let B=te(async()=>{_(null),R(!0);try{let l=await e.lookup(m);D(l),r("confirm")}catch(l){_(l.message)}finally{R(!1)}},[e,m]),oe=te(async()=>{_(null),R(!0);try{await e.approve(m),r("waiting")}catch(l){_(l.message)}finally{R(!1)}},[e,m]),Z=te(async()=>{R(!0);try{await e.deny(m),r("denied")}catch(l){_(l.message)}finally{R(!1)}},[e,m]),G=Fe(()=>u?.connect_url??null,[u]),Y=te(async(l,w)=>{try{await e.approveRuntime(l,w),h(await e.machines())}catch(N){_(N.message)}},[e]);return s==="loading"?a("div",{className:"soba-connect",children:a("div",{className:"sc-card",children:a("p",{className:"sc-note",children:"Loading\u2026"})})}):f("div",{className:"soba-connect",children:[s==="manage"&&f("div",{className:"sc-card",children:[a("h2",{className:"sc-title",children:"Your compute"}),f("p",{className:"sc-sub",children:[u?.app.name??"This app"," runs on these machines, while they are awake."]}),a(W,{machines:g,onApproveRuntime:Y}),A&&a("p",{className:"sc-error",children:A}),a("button",{type:"button",className:"sc-btn",style:{marginTop:16},onClick:()=>r("choose"),children:"Connect another machine"})]}),s==="choose"&&f("div",{className:"sc-card",children:[a("h2",{className:"sc-title",children:"Use the AI you already pay for"}),f("p",{className:"sc-sub",children:[u?.app.name??"This app"," can run on your machine instead of selling you credits. Pick what you already have."]}),a("div",{className:"sc-choices",children:ue.map(l=>f("button",{type:"button",className:"sc-choice","aria-pressed":b?.id===l.id,onClick:()=>o(l),children:[a("span",{className:"sc-choice-title",children:l.title}),a("br",{}),f("span",{className:"sc-choice-meta",children:[l.cost," \xB7 ",l.prerequisite]})]},l.id))}),b&&f("div",{className:"sc-stack",style:{marginTop:16},children:[a("p",{className:"sc-note",children:b.hint}),G?f(Ee,{children:[a("p",{className:"sc-label",children:"Install Soba Connect on the machine you want to use"}),a("a",{className:"sc-btn sc-btn-primary",href:"https://soba.so/soba-connect",target:"_blank",rel:"noreferrer noopener",children:"Get Soba Connect"}),a("p",{className:"sc-label",children:"Then paste this link into it"}),a("code",{className:"sc-code",children:G}),a("p",{className:"sc-note",children:"It will show you a short code. Nothing is pasted back: the credential is written straight to that machine."}),a("button",{type:"button",className:"sc-btn",onClick:()=>r("code"),children:"I have a code"})]}):a("p",{className:"sc-error",children:"This app has no publishable key yet, so there is nothing to pair against."})]})]}),s==="code"&&f("div",{className:"sc-card",children:[a("h2",{className:"sc-title",children:"Enter the code from that machine"}),a("p",{className:"sc-sub",children:"Eight characters, shown by Soba Connect once you paste the link."}),f("form",{className:"sc-stack",onSubmit:l=>{l.preventDefault(),B()},children:[a("input",{className:"sc-input",value:m,onChange:l=>v(l.target.value),placeholder:"ACDE-F234",autoComplete:"off",autoFocus:!0,"aria-label":"Pairing code"}),A&&a("p",{className:"sc-error",children:A}),a("button",{type:"submit",className:"sc-btn sc-btn-primary",disabled:I||m.length<8,children:I?"Checking\u2026":"Continue"})]})]}),s==="confirm"&&k&&f("div",{className:"sc-card",children:[a("h2",{className:"sc-title",children:"Attach this machine to your account?"}),f("p",{className:"sc-sub",children:["Once you approve, ",u?.app.name??"this app"," may send your runs to it. It can never see the account or the keys on it."]}),f("ul",{className:"sc-facts",children:[a(X,{k:"Code",v:k.user_code}),a(X,{k:"Machine",v:k.hostname??"not stated"}),a(X,{k:"System",v:[k.platform,k.arch].filter(Boolean).join(" / ")||"not stated"}),a(X,{k:"Asked by",v:k.client??"not stated"}),k.labels.length>0&&a(X,{k:"Labels",v:k.labels.join(", ")})]}),a("p",{className:"sc-note",style:{marginTop:12},children:"Every line above is what that machine said about itself. If none of it looks like a computer of yours, say no."}),A&&a("p",{className:"sc-error",children:A}),f("div",{className:"sc-row",style:{marginTop:16},children:[a("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:()=>void oe(),disabled:I,children:"Approve"}),a("button",{type:"button",className:"sc-btn",onClick:()=>void Z(),disabled:I,children:"No, deny it"})]})]}),s==="waiting"&&f("div",{className:"sc-card",children:[a("h2",{className:"sc-title",children:"Approved. Waiting for it to connect\u2026"}),a("p",{className:"sc-sub",children:"The worker is starting on that machine. This page will change on its own the moment it arrives."}),a("p",{className:"sc-note",children:"If nothing happens, look at Soba Connect on that machine: it says what it is doing."})]}),s==="connected"&&f("div",{className:"sc-card",children:[a("h2",{className:"sc-title",children:"Connected"}),f("p",{className:"sc-sub",children:[u?.app.name??"This app"," will use this machine from now on, while it is awake."]}),c&&f(Ee,{children:[a(W,{machines:g,onApproveRuntime:Y}),a("button",{type:"button",className:"sc-btn",style:{marginTop:16},onClick:()=>r("manage"),children:"Done"})]})]}),s==="denied"&&f("div",{className:"sc-card",children:[a("h2",{className:"sc-title",children:"Declined"}),a("p",{className:"sc-sub",children:"That machine was not attached to your account, and the terminal has been told so."})]})]})}function X({k:e,v:t}){return f("li",{className:"sc-fact",children:[a("span",{className:"sc-fact-key",children:e}),a("span",{children:t})]})}import{createContext as Ge,useContext as He}from"react";var me=Ge(null);function M(){let e=He(me);if(!e)throw new Error("useSoba() must be used inside a <SobaProvider>.");return e}import{jsx as J}from"react/jsx-runtime";function Ve({className:e}){let{compute:t}=M(),n=e?`soba-connect ${e}`:"soba-connect";return t.loading&&!t.machines.length?J("div",{className:n,children:J("p",{className:"sc-note",children:"Loading\u2026"})}):t.error&&!t.machines.length?J("div",{className:n,children:J("p",{className:"sc-error",children:t.error.message})}):J("div",{className:n,children:J(W,{machines:t.machines})})}import{createContext as We,useContext as Je}from"react";var he=We(null);function ke(){return Je(he)}import{jsx as U}from"react/jsx-runtime";function Ye({initialCode:e,onConnected:t,className:n,showStatus:c}){let{error:s}=M(),r=ke();return s?U("div",{className:_e(n),children:U("div",{className:"sc-card",children:U("p",{className:"sc-error",children:s.message})})}):r?U("div",{className:n,children:U(de,{client:r,...e?{initialCode:e}:{},...t?{onConnected:t}:{},...c===void 0?{}:{showStatus:c}})}):U("div",{className:_e(n),children:U("div",{className:"sc-card",children:U("p",{className:"sc-note",children:"Loading\u2026"})})})}function _e(e){return e?`soba-connect ${e}`:"soba-connect"}var ze=new Set(["delta","thinking","status","done","error"]);function ne(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t,c=n.type==="event"?n.event:n;if(!c||typeof c!="object")return null;let s=c;if(typeof s.type!="string"||!ze.has(s.type))return null;let r={type:s.type};return typeof s.text=="string"&&(r.text=s.text),typeof s.message=="string"&&(r.message=s.message),typeof s.tool=="string"&&(r.tool=s.tool),typeof s.tier=="string"&&(r.tier=s.tier),s.usage&&typeof s.usage=="object"&&(r.usage=s.usage),r}async function*fe(e){let t=e.body;if(!t)throw new Error("That run response had no body to stream.");let n=(e.headers.get("content-type")??"").includes("ndjson"),c=t.getReader(),s=new TextDecoder,r="",u=[];try{for(;;){let g=await c.read();if(g.done)break;for(r+=s.decode(g.value,{stream:!0});;){let h=r.indexOf(`
3
- `);if(h===-1)break;let b=Te(r.slice(0,h));if(r=r.slice(h+1),n){let o=b.trim()?ne(b):null;o&&(yield o);continue}if(b===""){let o=u.join(`
4
- `);if(u=[],o==="[DONE]")return;let m=o?ne(o):null;m&&(yield m);continue}Re(b,u)}}!n&&r&&Re(Te(r),u);let y=n?r.trim():u.join(`
5
- `);if(y&&y!=="[DONE]"){let g=ne(y);g&&(yield g)}}finally{c.cancel().catch(()=>{})}}function Re(e,t){if(!e||e.startsWith(":"))return;let n=e.indexOf(":");if(n===-1||e.slice(0,n)!=="data")return;let c=e.slice(n+1);t.push(c.startsWith(" ")?c.slice(1):c)}function Te(e){return e.endsWith("\r")?e.slice(0,-1):e}async function Ke(e){let t="";for await(let n of e)if(n.type==="delta"&&n.text&&(t+=n.text),n.type==="error")throw new Error(n.message??"The run ended with an error.");return t}import{useState as Me}from"react";import{jsx as Ae,jsxs as Xe}from"react/jsx-runtime";function Qe({plan:e,successUrl:t,cancelUrl:n,label:c,className:s}){let{plan:r}=M(),[u,y]=Me(!1),[g,h]=Me(null);async function b(){y(!0),h(null);try{let o=await r.checkout(e.id,{...t?{successUrl:t}:{},...n?{cancelUrl:n}:{}});window.location.assign(o)}catch(o){h(o.message),y(!1)}}return Xe("div",{className:s?`soba-connect ${s}`:"soba-connect",children:[Ae("button",{type:"button",className:"sc-btn sc-btn-primary",disabled:u,onClick:()=>void b(),children:u?"Opening\u2026":c??`Subscribe \u2014 $${e.price.toLocaleString()}/${e.interval}`}),g&&Ae("p",{className:"sc-error",children:g})]})}import{useState as Ie}from"react";import{Fragment as nt,jsx as d,jsxs as S}from"react/jsx-runtime";var Ze={"user-hardware":"your own machine","user-subscription":"your own AI subscription","open-weights":"open models we host",frontier:"frontier models"},et=new Set(["user-hardware","user-subscription"]);function se(e){return e?`soba-connect ${e}`:"soba-connect"}function tt({onSelect:e,successUrl:t,cancelUrl:n,showCompute:c=!0,className:s}){let{plan:r}=M(),[u,y]=Ie(null),[g,h]=Ie(null);if(r.error)return d("div",{className:se(s),children:d("div",{className:"sc-card",children:d("p",{className:"sc-error",children:r.error.message})})});if(r.loading)return d("div",{className:se(s),children:d("div",{className:"sc-card",children:d("p",{className:"sc-note",children:"Loading plans\u2026"})})});if(r.plans.length===0)return d("div",{className:se(s),children:d("div",{className:"sc-card",children:d("p",{className:"sc-note",children:"This app has no plans yet."})})});async function b(o){y(o.id),h(null);try{if(o.selectable)await r.select(o.id);else if(e)e(o);else{let m=await r.checkout(o.id,{...t?{successUrl:t}:{},...n?{cancelUrl:n}:{}});window.location.assign(m);return}}catch(m){h(m.message)}finally{y(null)}}return S("div",{className:se(s),children:[d("div",{className:"sc-plans",children:r.plans.map(o=>{let m=r.current?.plan_id===o.id;return S("div",{className:m?"sc-plan sc-plan-current":"sc-plan",children:[S("div",{className:"sc-row-between",children:[d("span",{className:"sc-title",children:o.name}),m&&d("span",{className:"sc-plan-badge",children:"Current"})]}),o.description&&d("p",{className:"sc-sub",children:o.description}),d("p",{className:"sc-plan-price",children:o.price===0?d("span",{className:"sc-plan-amount",children:"Free"}):S(nt,{children:[S("span",{className:"sc-plan-amount",children:["$",o.price.toLocaleString()]}),S("span",{className:"sc-plan-interval",children:["/",o.interval]})]})}),S("div",{className:"sc-facts",children:[S("div",{className:"sc-fact",children:[d("span",{className:"sc-fact-key",children:"Included"}),d("span",{children:o.included_units===null?"Unlimited":`${o.included_units.toLocaleString()} ${o.unit}${o.included_units===1?"":"s"}`})]}),o.overage_per_unit>0&&S("div",{className:"sc-fact",children:[d("span",{className:"sc-fact-key",children:"Then"}),S("span",{children:["$",o.overage_per_unit," / ",o.unit]})]}),o.trial_days>0&&S("div",{className:"sc-fact",children:[d("span",{className:"sc-fact-key",children:"Trial"}),S("span",{children:[o.trial_days," days"]})]}),c&&S("div",{className:"sc-plan-compute",children:[d("span",{className:"sc-fact-key",children:"Runs on"}),o.route_allow===null||o.route_allow.length===0?d("span",{children:o.route_allow===null?"any compute":"no compute"}):d("ul",{className:"sc-compute",children:o.route_allow.map(v=>d("li",{className:et.has(v)?"sc-compute-own":void 0,children:Ze[v]??v},v))})]})]}),d("button",{type:"button",className:m?"sc-btn":"sc-btn sc-btn-primary",disabled:m||u!==null,onClick:()=>void b(o),children:m?"Your plan":u===o.id?o.selectable?"Switching\u2026":"Opening\u2026":o.selectable?"Choose":`Subscribe \u2014 $${o.price.toLocaleString()}/${o.interval}`})]},o.id)})}),g&&d("p",{className:"sc-error",children:g})]})}import{useCallback as F,useEffect as j,useMemo as ye,useRef as rt,useState as E}from"react";var re=class{#t;#s=null;#n=null;#e;#r=new Set;constructor(t){this.#e=t,this.#t=t.token??null}get token(){return this.#t}get expiresAt(){return this.#s}get canRefresh(){return!!this.#e.endpoint}get refreshAt(){return!this.canRefresh||this.#s===null?null:Math.max(Date.now()+1e4,this.#s-6e4)}subscribe(t){return this.#r.add(t),()=>this.#r.delete(t)}async ensure(){return this.#t?this.#t:this.refresh()}async refresh(){if(this.#n)return this.#n;let t=this.#e.endpoint;if(!t)throw new Error("This Soba session cannot be refreshed. Pass `sessionEndpoint` so the provider can mint a new one.");let n=this.#e.fetchImpl??fetch.bind(globalThis);this.#n=(async()=>{let c=await n(t,{method:"POST",headers:{"content-type":"application/json"},credentials:"same-origin",body:JSON.stringify(this.#e.user?{user:this.#e.user}:{})});if(!c.ok)throw new Error(`Could not start a Soba session (${c.status} from ${t}).`);let s=await c.json(),r=s.session??s.token;if(!r)throw new Error(`${t} answered without a \`session\`. See @soba-so/react's README.`);let u=s.expires_in??s.expiresIn;this.#t=r,this.#s=typeof u=="number"?Date.now()+u*1e3:null;for(let y of this.#r)y();return r})();try{return await this.#n}finally{this.#n=null}}};function Oe(e,t=fetch.bind(globalThis)){return async(n,c)=>{let s=await t(n,c);if(s.status!==401||!e.canRefresh)return s;let r;try{r=await e.refresh()}catch{return s}return t(n,st(c,r))}}function st(e,t){let n=new Headers(e?.headers);return n.set("authorization",`Bearer ${t}`),{...e,headers:n}}var Le="data-soba-react",$e=!1;function ge(){if($e||typeof document>"u"||($e=!0,document.querySelector(`style[${Le}]`)))return;let e=document.createElement("style");e.setAttribute(Le,""),e.textContent=`.soba-connect {
2
+ var te=class extends Error{status;constructor(t,n){super(t),this.name="ConnectError",this.status=n}},Q=class{session;baseUrl;doFetch;constructor(t){this.session=t.session,this.baseUrl=(t.baseUrl??"").replace(/\/+$/,""),this.doFetch=t.fetchImpl??fetch.bind(globalThis)}context(){return this.request("GET","/v1/connect")}async machines(){return(await this.request("GET","/v1/machines")).machines}lookup(t){return this.request("GET",`/v1/device/lookup?code=${encodeURIComponent(t)}`)}approve(t){return this.request("POST","/v1/device/approve",{user_code:t})}deny(t){return this.request("POST","/v1/device/deny",{user_code:t})}plans(){return this.request("GET","/v1/plans")}selectPlan(t){return this.request("POST","/v1/plans/select",{plan:t})}checkoutPlan(t,n){return this.request("POST","/v1/plans/checkout",{plan:t,...n?.successUrl?{success_url:n.successUrl}:{},...n?.cancelUrl?{cancel_url:n.cancelUrl}:{}})}leavePlan(){return this.request("DELETE","/v1/plans/select")}approveRuntime(t,n){return this.request("POST","/v1/runtimes/approve",{machine_id:t,runtime_id:n})}async request(t,n,c){let s=await this.doFetch(`${this.baseUrl}${n}`,{method:t,headers:{authorization:`Bearer ${this.session}`,...c?{"content-type":"application/json"}:{}},...c?{body:JSON.stringify(c)}:{}}),r={};try{r=await s.json()}catch{}if(!s.ok){let u=typeof r.error=="string"?r.error:`Request failed (${s.status})`;throw new te(u,s.status)}return r}};function ce(e){return e.authenticated===!0?{tone:"ok",text:"signed in"}:e.authenticated===!1?{tone:"warn",text:e.auth_hint??"signed out on that machine"}:{tone:"unknown",text:"could not tell"}}function le(e){return e.state==="busy"?{tone:"busy",text:`serving ${e.active} of ${e.capacity}`}:e.state==="online"?{tone:"ok",text:"connected"}:{tone:"off",text:"asleep or offline"}}import{jsx as E,jsxs as V}from"react/jsx-runtime";function W({machines:e,onApproveRuntime:t}){return e.length?E("div",{children:e.map(n=>{let c=le(n);return V("div",{className:"sc-machine",children:[V("div",{className:"sc-row-between",children:[V("div",{className:"sc-row",children:[E("span",{className:`sc-dot sc-dot-${c.tone}`,"aria-hidden":"true"}),E("strong",{children:n.label??"This machine"})]}),E("span",{className:"sc-note",children:c.text})]}),E("p",{className:"sc-note",children:[n.platform,n.arch,n.version&&`worker ${n.version}`,n.always_on&&"always on"].filter(Boolean).join(" \xB7 ")}),V("ul",{className:"sc-runtimes",children:[n.runtimes.map(s=>{let r=ce(s);return s.quarantined?V("li",{className:"sc-row-between",children:[E("span",{children:s.display_name}),t?E("button",{type:"button",className:"sc-btn",onClick:()=>t(n.id,s.id),children:"New here. Let it serve"}):E("span",{className:"sc-tone-warn",children:"new, not serving yet"})]},s.id):V("li",{className:"sc-row-between",children:[E("span",{children:s.display_name}),E("span",{className:`sc-tone-${r.tone}`,children:r.text})]},s.id)}),!n.runtimes.length&&E("li",{className:"sc-note",children:"No runtime advertised. Install Claude Code, Codex or Ollama on that machine."})]})]},n.id)})}):E("p",{className:"sc-note",children:"Nothing connected yet."})}import{useCallback as ne,useEffect as pe,useMemo as De,useRef as Be,useState as U}from"react";var ue=[{id:"claude",title:"The Claude plan you already pay for",cost:"Nothing beyond the plan",prerequisite:"Claude Code installed, and signed in",hint:"Install it from claude.ai/code, then run `claude` once and sign in.",expects:["claude-code"]},{id:"chatgpt",title:"The ChatGPT plan you already pay for",cost:"Nothing beyond the plan",prerequisite:"Codex installed, and signed in",hint:"Install Codex, then run `codex` once and sign in.",expects:["codex"]},{id:"local",title:"A model on your own machine",cost:"Free. You bought the hardware",prerequisite:"Ollama running, with a model pulled",hint:"Install Ollama, then `ollama pull` a model before pairing.",expects:["ollama","openai-api"]}];import{Fragment as ke,jsx as a,jsxs as h}from"react/jsx-runtime";var Ge=2e3,He=1e4;function de({client:e,initialCode:t,onConnected:n,showStatus:c=!0}){let[s,r]=U("loading"),[u,y]=U(null),[f,g]=U([]),[b,o]=U(null),[m,w]=U(t??""),[_,R]=U(null),[A,P]=U(null),[D,T]=U(!1),B=Be(null);pe(()=>{let l=!0;return Promise.all([e.context(),e.machines()]).then(([S,v])=>{l&&(y(S),g(v),B.current=new Set(v.map(I=>I.id)),t?r("code"):c&&v.length>0?r("manage"):r("choose"))}).catch(S=>{l&&(P(S.message),r("choose"))}),()=>{l=!1}},[e,t,c]),pe(()=>{if(s!=="manage")return;let l=!0,S=setInterval(async()=>{try{let v=await e.machines();l&&g(v)}catch{}},He);return()=>{l=!1,clearInterval(S)}},[s,e]),pe(()=>{if(s!=="waiting")return;let l=!0,S=setInterval(async()=>{try{let v=await e.machines();if(!l)return;g(v);let I=v.filter(O=>!B.current?.has(O.id));(I.find(O=>O.state!=="offline")??I[0])&&(r("connected"),n?.(v))}catch{}},Ge);return()=>{l=!1,clearInterval(S)}},[s,e,n]);let Z=ne(async()=>{P(null),T(!0);try{let l=await e.lookup(m);R(l),r("confirm")}catch(l){P(l.message)}finally{T(!1)}},[e,m]),G=ne(async()=>{P(null),T(!0);try{await e.approve(m),r("waiting")}catch(l){P(l.message)}finally{T(!1)}},[e,m]),H=ne(async()=>{T(!0);try{await e.deny(m),r("denied")}catch(l){P(l.message)}finally{T(!1)}},[e,m]),ee=De(()=>u?.connect_url??null,[u]),Y=ne(async(l,S)=>{try{await e.approveRuntime(l,S),g(await e.machines())}catch(v){P(v.message)}},[e]);return s==="loading"?a("div",{className:"soba-connect",children:a("div",{className:"sc-card",children:a("p",{className:"sc-note",children:"Loading\u2026"})})}):h("div",{className:"soba-connect",children:[s==="manage"&&h("div",{className:"sc-card",children:[a("h2",{className:"sc-title",children:"Your compute"}),h("p",{className:"sc-sub",children:[u?.app.name??"This app"," runs on these machines, while they are awake."]}),a(W,{machines:f,onApproveRuntime:Y}),A&&a("p",{className:"sc-error",children:A}),a("button",{type:"button",className:"sc-btn",style:{marginTop:16},onClick:()=>r("choose"),children:"Connect another machine"})]}),s==="choose"&&h("div",{className:"sc-card",children:[a("h2",{className:"sc-title",children:"Use the AI you already pay for"}),h("p",{className:"sc-sub",children:[u?.app.name??"This app"," can run on your machine instead of selling you credits. Pick what you already have."]}),a("div",{className:"sc-choices",children:ue.map(l=>h("button",{type:"button",className:"sc-choice","aria-pressed":b?.id===l.id,onClick:()=>o(l),children:[a("span",{className:"sc-choice-title",children:l.title}),a("br",{}),h("span",{className:"sc-choice-meta",children:[l.cost," \xB7 ",l.prerequisite]})]},l.id))}),b&&h("div",{className:"sc-stack",style:{marginTop:16},children:[a("p",{className:"sc-note",children:b.hint}),ee?h(ke,{children:[a("p",{className:"sc-label",children:"Install Soba Connect on the machine you want to use"}),a("a",{className:"sc-btn sc-btn-primary",href:"https://soba.so/soba-connect",target:"_blank",rel:"noreferrer noopener",children:"Get Soba Connect"}),a("p",{className:"sc-label",children:"Then paste this link into it"}),a("code",{className:"sc-code",children:ee}),a("p",{className:"sc-note",children:"It will show you a short code. Nothing is pasted back: the credential is written straight to that machine."}),a("button",{type:"button",className:"sc-btn",onClick:()=>r("code"),children:"I have a code"})]}):a("p",{className:"sc-error",children:"This app has no publishable key yet, so there is nothing to pair against."})]})]}),s==="code"&&h("div",{className:"sc-card",children:[a("h2",{className:"sc-title",children:"Enter the code from that machine"}),a("p",{className:"sc-sub",children:"Eight characters, shown by Soba Connect once you paste the link."}),h("form",{className:"sc-stack",onSubmit:l=>{l.preventDefault(),Z()},children:[a("input",{className:"sc-input",value:m,onChange:l=>w(l.target.value),placeholder:"ACDE-F234",autoComplete:"off",autoFocus:!0,"aria-label":"Pairing code"}),A&&a("p",{className:"sc-error",children:A}),a("button",{type:"submit",className:"sc-btn sc-btn-primary",disabled:D||m.length<8,children:D?"Checking\u2026":"Continue"})]})]}),s==="confirm"&&_&&h("div",{className:"sc-card",children:[a("h2",{className:"sc-title",children:"Attach this machine to your account?"}),h("p",{className:"sc-sub",children:["Once you approve, ",u?.app.name??"this app"," may send your runs to it. It can never see the account or the keys on it."]}),h("ul",{className:"sc-facts",children:[a(X,{k:"Code",v:_.user_code}),a(X,{k:"Machine",v:_.hostname??"not stated"}),a(X,{k:"System",v:[_.platform,_.arch].filter(Boolean).join(" / ")||"not stated"}),a(X,{k:"Asked by",v:_.client??"not stated"}),_.labels.length>0&&a(X,{k:"Labels",v:_.labels.join(", ")})]}),a("p",{className:"sc-note",style:{marginTop:12},children:"Every line above is what that machine said about itself. If none of it looks like a computer of yours, say no."}),A&&a("p",{className:"sc-error",children:A}),h("div",{className:"sc-row",style:{marginTop:16},children:[a("button",{type:"button",className:"sc-btn sc-btn-primary",onClick:()=>void G(),disabled:D,children:"Approve"}),a("button",{type:"button",className:"sc-btn",onClick:()=>void H(),disabled:D,children:"No, deny it"})]})]}),s==="waiting"&&h("div",{className:"sc-card",children:[a("h2",{className:"sc-title",children:"Approved. Waiting for it to connect\u2026"}),a("p",{className:"sc-sub",children:"The worker is starting on that machine. This page will change on its own the moment it arrives."}),a("p",{className:"sc-note",children:"If nothing happens, look at Soba Connect on that machine: it says what it is doing."})]}),s==="connected"&&h("div",{className:"sc-card",children:[a("h2",{className:"sc-title",children:"Connected"}),h("p",{className:"sc-sub",children:[u?.app.name??"This app"," will use this machine from now on, while it is awake."]}),c&&h(ke,{children:[a(W,{machines:f,onApproveRuntime:Y}),a("button",{type:"button",className:"sc-btn",style:{marginTop:16},onClick:()=>r("manage"),children:"Done"})]})]}),s==="denied"&&h("div",{className:"sc-card",children:[a("h2",{className:"sc-title",children:"Declined"}),a("p",{className:"sc-sub",children:"That machine was not attached to your account, and the terminal has been told so."})]})]})}function X({k:e,v:t}){return h("li",{className:"sc-fact",children:[a("span",{className:"sc-fact-key",children:e}),a("span",{children:t})]})}import{createContext as Ve,useContext as We}from"react";var me=Ve(null);function M(){let e=We(me);if(!e)throw new Error("useSoba() must be used inside a <SobaProvider>.");return e}import{jsx as J}from"react/jsx-runtime";function Je({className:e}){let{compute:t}=M(),n=e?`soba-connect ${e}`:"soba-connect";return t.loading&&!t.machines.length?J("div",{className:n,children:J("p",{className:"sc-note",children:"Loading\u2026"})}):t.error&&!t.machines.length?J("div",{className:n,children:J("p",{className:"sc-error",children:t.error.message})}):J("div",{className:n,children:J(W,{machines:t.machines})})}import{createContext as Ye,useContext as ze}from"react";var he=Ye(null);function _e(){return ze(he)}import{jsx as q}from"react/jsx-runtime";function Ke({initialCode:e,onConnected:t,className:n,showStatus:c}){let{error:s}=M(),r=_e();return s?q("div",{className:Re(n),children:q("div",{className:"sc-card",children:q("p",{className:"sc-error",children:s.message})})}):r?q("div",{className:n,children:q(de,{client:r,...e?{initialCode:e}:{},...t?{onConnected:t}:{},...c===void 0?{}:{showStatus:c}})}):q("div",{className:Re(n),children:q("div",{className:"sc-card",children:q("p",{className:"sc-note",children:"Loading\u2026"})})})}function Re(e){return e?`soba-connect ${e}`:"soba-connect"}var Qe=new Set(["delta","thinking","status","done","error"]);function se(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!="object")return null;let n=t,c=n.type==="event"?n.event:n;if(!c||typeof c!="object")return null;let s=c;if(typeof s.type!="string"||!Qe.has(s.type))return null;let r={type:s.type};return typeof s.text=="string"&&(r.text=s.text),typeof s.message=="string"&&(r.message=s.message),typeof s.tool=="string"&&(r.tool=s.tool),typeof s.tier=="string"&&(r.tier=s.tier),s.usage&&typeof s.usage=="object"&&(r.usage=s.usage),r}async function*fe(e){let t=e.body;if(!t)throw new Error("That run response had no body to stream.");let n=(e.headers.get("content-type")??"").includes("ndjson"),c=t.getReader(),s=new TextDecoder,r="",u=[];try{for(;;){let f=await c.read();if(f.done)break;for(r+=s.decode(f.value,{stream:!0});;){let g=r.indexOf(`
3
+ `);if(g===-1)break;let b=Me(r.slice(0,g));if(r=r.slice(g+1),n){let o=b.trim()?se(b):null;o&&(yield o);continue}if(b===""){let o=u.join(`
4
+ `);if(u=[],o==="[DONE]")return;let m=o?se(o):null;m&&(yield m);continue}Te(b,u)}}!n&&r&&Te(Me(r),u);let y=n?r.trim():u.join(`
5
+ `);if(y&&y!=="[DONE]"){let f=se(y);f&&(yield f)}}finally{c.cancel().catch(()=>{})}}function Te(e,t){if(!e||e.startsWith(":"))return;let n=e.indexOf(":");if(n===-1||e.slice(0,n)!=="data")return;let c=e.slice(n+1);t.push(c.startsWith(" ")?c.slice(1):c)}function Me(e){return e.endsWith("\r")?e.slice(0,-1):e}async function Xe(e){let t="";for await(let n of e)if(n.type==="delta"&&n.text&&(t+=n.text),n.type==="error")throw new Error(n.message??"The run ended with an error.");return t}import{useState as Ae}from"react";import{jsx as Ie,jsxs as et}from"react/jsx-runtime";function Ze({plan:e,successUrl:t,cancelUrl:n,label:c,className:s}){let{plan:r}=M(),[u,y]=Ae(!1),[f,g]=Ae(null);async function b(){y(!0),g(null);try{let o=await r.checkout(e.id,{...t?{successUrl:t}:{},...n?{cancelUrl:n}:{}});window.location.assign(o)}catch(o){g(o.message),y(!1)}}return et("div",{className:s?`soba-connect ${s}`:"soba-connect",children:[Ie("button",{type:"button",className:"sc-btn sc-btn-primary",disabled:u,onClick:()=>void b(),children:u?"Opening\u2026":c??`Subscribe \u2014 $${e.price.toLocaleString()}/${e.interval}`}),f&&Ie("p",{className:"sc-error",children:f})]})}import{useState as Oe}from"react";import{Fragment as rt,jsx as d,jsxs as N}from"react/jsx-runtime";var tt={"user-hardware":"your own machine","user-subscription":"your own AI subscription","open-weights":"open models we host",frontier:"frontier models"},nt=new Set(["user-hardware","user-subscription"]);function re(e){return e?`soba-connect ${e}`:"soba-connect"}function st({onSelect:e,successUrl:t,cancelUrl:n,showCompute:c=!0,className:s}){let{plan:r}=M(),[u,y]=Oe(null),[f,g]=Oe(null);if(r.error)return d("div",{className:re(s),children:d("div",{className:"sc-card",children:d("p",{className:"sc-error",children:r.error.message})})});if(r.loading)return d("div",{className:re(s),children:d("div",{className:"sc-card",children:d("p",{className:"sc-note",children:"Loading plans\u2026"})})});if(r.plans.length===0)return d("div",{className:re(s),children:d("div",{className:"sc-card",children:d("p",{className:"sc-note",children:"This app has no plans yet."})})});async function b(o){y(o.id),g(null);try{if(o.selectable)await r.select(o.id);else if(e)e(o);else{let m=await r.checkout(o.id,{...t?{successUrl:t}:{},...n?{cancelUrl:n}:{}});window.location.assign(m);return}}catch(m){g(m.message)}finally{y(null)}}return N("div",{className:re(s),children:[d("div",{className:"sc-plans",children:r.plans.map(o=>{let m=r.current?.plan_id===o.id;return N("div",{className:m?"sc-plan sc-plan-current":"sc-plan",children:[N("div",{className:"sc-row-between",children:[d("span",{className:"sc-title",children:o.name}),m&&d("span",{className:"sc-plan-badge",children:"Current"})]}),o.description&&d("p",{className:"sc-sub",children:o.description}),d("p",{className:"sc-plan-price",children:o.price===0?d("span",{className:"sc-plan-amount",children:"Free"}):N(rt,{children:[N("span",{className:"sc-plan-amount",children:["$",o.price.toLocaleString()]}),N("span",{className:"sc-plan-interval",children:["/",o.interval]})]})}),N("div",{className:"sc-facts",children:[N("div",{className:"sc-fact",children:[d("span",{className:"sc-fact-key",children:"Included"}),d("span",{children:o.included_units===null?"Unlimited":`${o.included_units.toLocaleString()} ${o.unit}${o.included_units===1?"":"s"}`})]}),o.overage_per_unit>0&&N("div",{className:"sc-fact",children:[d("span",{className:"sc-fact-key",children:"Then"}),N("span",{children:["$",o.overage_per_unit," / ",o.unit]})]}),o.trial_days>0&&N("div",{className:"sc-fact",children:[d("span",{className:"sc-fact-key",children:"Trial"}),N("span",{children:[o.trial_days," days"]})]}),c&&N("div",{className:"sc-plan-compute",children:[d("span",{className:"sc-fact-key",children:"Runs on"}),o.route_allow===null||o.route_allow.length===0?d("span",{children:o.route_allow===null?"any compute":"no compute"}):d("ul",{className:"sc-compute",children:o.route_allow.map(w=>d("li",{className:nt.has(w)?"sc-compute-own":void 0,children:tt[w]??w},w))})]})]}),d("button",{type:"button",className:m?"sc-btn":"sc-btn sc-btn-primary",disabled:m||u!==null,onClick:()=>void b(o),children:m?"Your plan":u===o.id?o.selectable?"Switching\u2026":"Opening\u2026":o.selectable?"Choose":`Subscribe \u2014 $${o.price.toLocaleString()}/${o.interval}`})]},o.id)})}),f&&d("p",{className:"sc-error",children:f})]})}import{useCallback as F,useEffect as j,useMemo as ye,useRef as at,useState as k}from"react";var oe=class{#t;#s=null;#n=null;#e;#r=new Set;constructor(t){this.#e=t,this.#t=t.token??null}get token(){return this.#t}get expiresAt(){return this.#s}get canRefresh(){return!!this.#e.endpoint}get refreshAt(){return!this.canRefresh||this.#s===null?null:Math.max(Date.now()+1e4,this.#s-6e4)}subscribe(t){return this.#r.add(t),()=>this.#r.delete(t)}async ensure(){return this.#t?this.#t:this.refresh()}async refresh(){if(this.#n)return this.#n;let t=this.#e.endpoint;if(!t)throw new Error("This Soba session cannot be refreshed. Pass `sessionEndpoint` so the provider can mint a new one.");let n=this.#e.fetchImpl??fetch.bind(globalThis);this.#n=(async()=>{let c=await n(t,{method:"POST",headers:{"content-type":"application/json"},credentials:"same-origin",body:JSON.stringify(this.#e.user?{user:this.#e.user}:{})});if(!c.ok)throw new Error(`Could not start a Soba session (${c.status} from ${t}).`);let s=await c.json(),r=s.session??s.token;if(!r)throw new Error(`${t} answered without a \`session\`. See @soba-so/react's README.`);let u=s.expires_in??s.expiresIn;this.#t=r,this.#s=typeof u=="number"?Date.now()+u*1e3:null;for(let y of this.#r)y();return r})();try{return await this.#n}finally{this.#n=null}}};function Le(e,t=fetch.bind(globalThis)){return async(n,c)=>{let s=await t(n,c);if(s.status!==401||!e.canRefresh)return s;let r;try{r=await e.refresh()}catch{return s}return t(n,ot(c,r))}}function ot(e,t){let n=new Headers(e?.headers);return n.set("authorization",`Bearer ${t}`),{...e,headers:n}}var $e="data-soba-react",Ue=!1;function ge(){if(Ue||typeof document>"u"||(Ue=!0,document.querySelector(`style[${$e}]`)))return;let e=document.createElement("style");e.setAttribute($e,""),e.textContent=`.soba-connect {
6
6
  --sc-ground: #ffffff;
7
7
  --sc-sheet: #ffffff;
8
8
  --sc-raised: #f6f6f7;
@@ -256,7 +256,7 @@ a.sc-btn {
256
256
  gap: 12px;
257
257
  align-items: stretch;
258
258
 
259
- grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
259
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
260
260
  }
261
261
 
262
262
  .sc-plan {
@@ -374,4 +374,4 @@ a.sc-btn {
374
374
  border-bottom: 1px solid var(--sc-line, #e9e9eb);
375
375
  margin-bottom: 2px;
376
376
  }
377
- `,document.head.appendChild(e)}import{jsx as Ue}from"react/jsx-runtime";var ot="https://www.soba.so",at=15e3;function it(e){let{children:t,session:n,sessionEndpoint:c,user:s,runEndpoint:r,baseUrl:u=ot,pollMs:y=at,injectStyles:g=!0,fetchImpl:h,onError:b}=e,[o,m]=E(n??null),[v,k]=E(null),[D,A]=E(null),[_,I]=E(null),[R,q]=E(!0),[B,oe]=E([]),[Z,G]=E(null),[Y,l]=E(!0),[w,N]=E([]),[T,be]=E(null),[H,ae]=E(null),[ve,Ce]=E(!0),we=rt(b);we.current=b;let z=F(i=>{k(i),we.current?.(i)},[]);j(()=>{g&&ge()},[g]);let P=ye(()=>new re({...n?{token:n}:{},...c?{endpoint:c}:{},...s?{user:s}:{},...h?{fetchImpl:h}:{}}),[n,c,s,h]);j(()=>{let i=!0,C=P.subscribe(()=>{i&&m(P.token)});return!P.token&&!P.canRefresh?z(new Error("<SobaProvider> needs a `session` or a `sessionEndpoint`. A browser cannot mint one: that takes your secret key.")):P.ensure().then(()=>i&&m(P.token),L=>i&&z(L)),()=>{i=!1,C()}},[P,z]),j(()=>{v&&(q(!1),l(!1),Ce(!1),I(i=>i??v),G(i=>i??v),ae(i=>i??v))},[v]),j(()=>{let i=P.refreshAt;if(i===null)return;let C=setTimeout(()=>{P.refresh().catch(L=>z(L))},Math.max(0,i-Date.now()));return()=>clearTimeout(C)},[P,z,o]);let p=ye(()=>o?new Q({session:o,baseUrl:u,fetchImpl:Oe(P,h??fetch.bind(globalThis))}):null,[o,u,P,h]);j(()=>{if(!p)return;let i=!0;return q(!0),p.context().then(C=>{i&&(A(C),I(null),q(!1))},C=>{i&&(I(C),q(!1))}),()=>{i=!1}},[p]);let K=F(async()=>{if(p)try{let i=await p.machines();oe(i),G(null)}catch(i){G(i)}finally{l(!1)}},[p]),O=F(async()=>{if(p)try{let i=await p.plans();N(i.plans),be(i.current),ae(null)}catch(i){ae(i)}finally{Ce(!1)}},[p]);j(()=>{p&&O()},[p,O]);let Ne=F(async i=>{if(!p)throw new Error("No session yet.");await p.selectPlan(i),await O()},[p,O]),Se=F(async(i,C)=>{if(!p)throw new Error("No session yet.");let L=await p.checkoutPlan(i,C);if(!L.url)throw new Error("Checkout could not be started.");return L.url},[p]),Pe=F(async()=>{if(!p)throw new Error("No session yet.");await p.leavePlan(),await O()},[p,O]);j(()=>{if(!p)return;let i=!0;K();let C=setInterval(()=>{typeof document<"u"&&document.hidden||i&&K()},y);return()=>{i=!1,clearInterval(C)}},[p,K,y]);let xe=F(async i=>{if(!r)throw new Error("Pass `runEndpoint` to <SobaProvider> to start runs from the browser. It is your own route: it holds your secret key, calls soba.run(), and forwards the stream.");let{signal:C,...L}=i,ie=await(h??fetch.bind(globalThis))(r,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream"},credentials:"same-origin",body:JSON.stringify(L),...C?{signal:C}:{}});if(!ie.ok)throw new Error(`${r} answered ${ie.status}.`);return fe(ie)},[r,h]),qe=ye(()=>({session:o,client:p,error:v,plan:{plans:w,current:T,plan:T?w.find(i=>i.id===T.plan_id)??null:null,loading:ve,error:H,select:Ne,checkout:Se,leave:Pe,refresh:O},compute:{machines:B,connected:B.length>0,online:B.some(i=>i.state!=="offline"),loading:Y,error:Z,refresh:K},connect:{app:D?.app??null,command:D?.command??null,publishableKey:D?.publishable_key??null,loading:R,error:_},run:xe}),[o,p,v,B,Y,Z,K,w,T,ve,H,Ne,Se,Pe,O,D,R,_,xe]);return Ue(he.Provider,{value:p,children:Ue(me.Provider,{value:qe,children:t})})}export{Ve as ComputeStatus,Ye as ConnectCompute,Qe as SobaCheckout,tt as SobaPlans,it as SobaProvider,Ke as collectText,ge as injectStyles,ne as parseEvent,fe as readEvents,M as useSoba};
377
+ `,document.head.appendChild(e)}import{jsx as qe}from"react/jsx-runtime";var it="https://www.soba.so",ct=15e3;function lt(e){let{children:t,session:n,sessionEndpoint:c,user:s,runEndpoint:r,initialPlans:u,initialCurrentPlan:y=null,baseUrl:f=it,pollMs:g=ct,injectStyles:b=!0,fetchImpl:o,onError:m}=e,[w,_]=k(n??null),[R,A]=k(null),[P,D]=k(null),[T,B]=k(null),[Z,G]=k(!0),[H,ee]=k([]),[Y,l]=k(null),[S,v]=k(!0),[I,be]=k(u??[]),[O,Fe]=k(y),[ve,ae]=k(null),[Ce,we]=k(u===void 0),Ne=at(m);Ne.current=m;let z=F(i=>{A(i),Ne.current?.(i)},[]);j(()=>{b&&ge()},[b]);let x=ye(()=>new oe({...n?{token:n}:{},...c?{endpoint:c}:{},...s?{user:s}:{},...o?{fetchImpl:o}:{}}),[n,c,s,o]);j(()=>{let i=!0,C=x.subscribe(()=>{i&&_(x.token)});return!x.token&&!x.canRefresh?z(new Error("<SobaProvider> needs a `session` or a `sessionEndpoint`. A browser cannot mint one: that takes your secret key.")):x.ensure().then(()=>i&&_(x.token),$=>i&&z($)),()=>{i=!1,C()}},[x,z]),j(()=>{R&&(G(!1),v(!1),we(!1),B(i=>i??R),l(i=>i??R),ae(i=>i??R))},[R]),j(()=>{let i=x.refreshAt;if(i===null)return;let C=setTimeout(()=>{x.refresh().catch($=>z($))},Math.max(0,i-Date.now()));return()=>clearTimeout(C)},[x,z,w]);let p=ye(()=>w?new Q({session:w,baseUrl:f,fetchImpl:Le(x,o??fetch.bind(globalThis))}):null,[w,f,x,o]);j(()=>{if(!p)return;let i=!0;return G(!0),p.context().then(C=>{i&&(D(C),B(null),G(!1))},C=>{i&&(B(C),G(!1))}),()=>{i=!1}},[p]);let K=F(async()=>{if(p)try{let i=await p.machines();ee(i),l(null)}catch(i){l(i)}finally{v(!1)}},[p]),L=F(async()=>{if(p)try{let i=await p.plans();be(i.plans),Fe(i.current),ae(null)}catch(i){ae(i)}finally{we(!1)}},[p]);j(()=>{p&&L()},[p,L]);let Pe=F(async i=>{if(!p)throw new Error("No session yet.");await p.selectPlan(i),await L()},[p,L]),Se=F(async(i,C)=>{if(!p)throw new Error("No session yet.");let $=await p.checkoutPlan(i,C);if(!$.url)throw new Error("Checkout could not be started.");return $.url},[p]),xe=F(async()=>{if(!p)throw new Error("No session yet.");await p.leavePlan(),await L()},[p,L]);j(()=>{if(!p)return;let i=!0;K();let C=setInterval(()=>{typeof document<"u"&&document.hidden||i&&K()},g);return()=>{i=!1,clearInterval(C)}},[p,K,g]);let Ee=F(async i=>{if(!r)throw new Error("Pass `runEndpoint` to <SobaProvider> to start runs from the browser. It is your own route: it holds your secret key, calls soba.run(), and forwards the stream.");let{signal:C,...$}=i,ie=await(o??fetch.bind(globalThis))(r,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream"},credentials:"same-origin",body:JSON.stringify($),...C?{signal:C}:{}});if(!ie.ok)throw new Error(`${r} answered ${ie.status}.`);return fe(ie)},[r,o]),je=ye(()=>({session:w,client:p,error:R,plan:{plans:I,current:O,plan:O?I.find(i=>i.id===O.plan_id)??null:null,loading:Ce,error:ve,select:Pe,checkout:Se,leave:xe,refresh:L},compute:{machines:H,connected:H.length>0,online:H.some(i=>i.state!=="offline"),loading:S,error:Y,refresh:K},connect:{app:P?.app??null,command:P?.command??null,publishableKey:P?.publishable_key??null,loading:Z,error:T},run:Ee}),[w,p,R,H,S,Y,K,I,O,Ce,ve,Pe,Se,xe,L,P,Z,T,Ee]);return qe(he.Provider,{value:p,children:qe(me.Provider,{value:je,children:t})})}export{Je as ComputeStatus,Ke as ConnectCompute,Ze as SobaCheckout,st as SobaPlans,lt as SobaProvider,Xe as collectText,ge as injectStyles,se as parseEvent,fe as readEvents,M as useSoba};
package/dist/styles.css CHANGED
@@ -252,7 +252,7 @@ a.sc-btn {
252
252
  gap: 12px;
253
253
  align-items: stretch;
254
254
 
255
- grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
255
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
256
256
  }
257
257
 
258
258
  .sc-plan {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soba-so/react",
3
- "version": "0.0.6",
3
+ "version": "0.0.7",
4
4
  "description": "Connect the AI your users already pay for, from your own React app.",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://soba.so/docs/components",