palbase 0.62.0 → 0.63.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.
Files changed (54) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +3 -3
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/{S3YODXG5.js → 5KIV2VHK.js} +2 -2
  8. package/dist/chunks/{DCWPUWZE.js → 5TXSFJYI.js} +2 -2
  9. package/dist/chunks/{LUVYYNMK.js → 7YRDXDVI.js} +2 -2
  10. package/dist/chunks/BP35TQMR.js +2 -0
  11. package/dist/chunks/{HXKBPLL2.js → BVR7H5RY.js} +1 -1
  12. package/dist/chunks/{WJXZYXL6.js → COXA3LDU.js} +2 -2
  13. package/dist/chunks/{P3QFV5EA.js → EJ7YD4YY.js} +1 -1
  14. package/dist/chunks/{SCUAN3L3.js → G4UNJNUL.js} +1 -1
  15. package/dist/chunks/{PQ627JVJ.js → IX4TWJ7J.js} +2 -2
  16. package/dist/chunks/{EEGVWOER.js → IXFSQYJA.js} +2 -2
  17. package/dist/chunks/{USL5YRDX.js → KGP3V3IA.js} +2 -2
  18. package/dist/chunks/{ECVNYWWT.js → LGGBVI33.js} +2 -2
  19. package/dist/chunks/{3KEWWFIC.js → RFRPB2IR.js} +1 -1
  20. package/dist/chunks/{ZVDYTR3S.js → SWB2U22R.js} +2 -2
  21. package/dist/chunks/{7J3HTVFX.js → T74PPGHJ.js} +2 -2
  22. package/dist/chunks/{WBKZLJ66.js → UDS4W77D.js} +1 -1
  23. package/dist/chunks/{PYL5JMWN.js → VHTT6VB5.js} +2 -2
  24. package/dist/chunks/{WEMTQPSH.js → WUQWOSEI.js} +2 -2
  25. package/dist/chunks/{IPAVEV75.js → WXOQLEUW.js} +2 -2
  26. package/dist/chunks/{M6KUVE4B.js → XHTUT6AV.js} +2 -2
  27. package/dist/chunks/{LXAR6WWQ.js → XPKA7LAF.js} +2 -2
  28. package/dist/chunks/{KUSZFTJK.js → YWG7F44Q.js} +1 -1
  29. package/dist/chunks/{LDLYOQAV.js → ZG2LQB5B.js} +1 -1
  30. package/dist/cli.js +7 -7
  31. package/dist/cloud/index.js +2 -2
  32. package/dist/refuse/ai.js +1 -1
  33. package/dist/refuse/backend.js +1 -1
  34. package/dist/refuse/cloud.js +1 -1
  35. package/dist/refuse/server.js +1 -1
  36. package/dist/server/index.js +2 -2
  37. package/dist/server/testing.js +2 -2
  38. package/dist/web/index.js +2 -2
  39. package/dist/web/message.js +2 -2
  40. package/dist/web/palbe.js +2 -2
  41. package/dist/web/paywall.js +2 -2
  42. package/dist/web/push-sw.js +1 -1
  43. package/dist/web/ssr.js +2 -2
  44. package/dist/web/vite.js +2 -2
  45. package/package.json +2 -2
  46. package/types/cloud/src/generated/studio.d.ts +67 -8
  47. package/types/internal/src/modules/ai.d.ts +1 -1
  48. package/types/internal/src/modules/analytics.d.ts +7 -7
  49. package/types/internal/src/modules/auth.d.ts +41 -30
  50. package/types/internal/src/modules/notify.d.ts +1 -1
  51. package/types/internal/src/modules/purchases.d.ts +19 -7
  52. package/types/internal/src/modules/stores.d.ts +3 -3
  53. package/types/web/src/screen/resolve.d.ts +2 -1
  54. package/dist/chunks/ZWSYEBRO.js +0 -2
@@ -1,5 +1,5 @@
1
- /*! palbase 0.62.0 — Palbase SDK License (see LICENSE) */
2
- import{b as q,c as P,d as S}from"./ZVDYTR3S.js";import{a as Y,f as Z,g as X,j as ee,k as te,l as ne,o as N,p as se,q as re}from"./WBKZLJ66.js";import{d as G}from"./USL5YRDX.js";import{a as E,b as Q,c as _,e as A}from"./ECVNYWWT.js";var p=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,n){super(n.message,n.cause===void 0?void 0:{cause:n.cause}),this.name="BackendError",this.kind=e,this.code=n.code,this.status=n.status??0,this.requestId=n.requestId,this.fields=n.fields,this.retryAfter=n.retryAfter,this.data=n.data}};function ae(t){return t instanceof p||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function D(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??We(e,"request_id"),data:x(e,"data"),cause:t};if(t.code==="network_error")return new p("network",n);if(t.status===401&&t.code==="insufficient_user_authentication")return new p("stepUpRequired",n);if(t.status===401&&t.code==="app_attest_required")return new p("attestationRequired",n);if(t.status===401)return new p("unauthorized",n);if(t.status===429)return new p("rateLimited",{...n,retryAfter:Je(e)??t.retryAfter});let s=Le(e);return t.status===400&&s?new p("validation",{...n,fields:s}):new p("server",n)}function I(t){return t instanceof Q||t instanceof Error&&t.name==="PalbaseError"}function oe(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Le(t){let e=x(x(t,"data"),"fields");if(oe(e))return e;let n=x(t,"fields");return oe(n)?n:void 0}function Je(t){return ie(t,"retry_after")??ie(x(t,"data"),"retryAfter")}function x(t,e){if(typeof t=="object"&&t!==null)return t[e]}function ie(t,e){let n=x(t,e);return typeof n=="number"?n:void 0}function We(t,e){let n=x(t,e);return typeof n=="string"?n:void 0}var He=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ve=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),Ue=new Set(Ve),ze=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function $(t){return t==="then"||t==="toJSON"||ze.has(t)}function de(t){return t==="call"||t==="join"||$(t)}function le(t){return typeof t=="string"&&He.test(t)&&!Ue.has(t)&&!$(t)}function ue(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function ce(t){A(t)}function pe(t){return A(t).origin}var O=class t{me;reader;messages=new Map;told=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;history=new Map;forkedFrom=null;calls=new Map;thoughts=new Set;at=0;next=0;lowest=0;folded=0;paged=new Set;pagedFrom;pagedTo;racing=!1;replays;held=[];racedPages=[];heldTimer;heldSince=0;oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;changing=!1;ended=!1;constructor(e=()=>{},n,s,r=!0){this.me=e,this.reader=n,this.chatId=s,this.replays=r}get hasOlder(){return this.olderLeft}loadOlder(e={}){return e.limit!==void 0&&e.turns!==void 0?Promise.reject(new TypeError("loadOlder: limit (events) or turns (turns), not both")):e.turns!==void 0&&(!Number.isSafeInteger(e.turns)||e.turns<1||e.turns>20)?Promise.reject(new TypeError(`loadOlder: turns is how many more of the chat's turns to read back to, 1 to 20 (got ${String(e.turns)})`)):(this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading)}async readOlder(e){let n=e.turns;do{if(!this.olderLeft)return!1;let s=this.olderCursor,r=this.next===0&&this.olderCursor===void 0,d={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...n!==void 0?{turns:n}:{},...e.signal?{signal:e.signal}:{}},a;if(e.load)a=await e.load(d);else{let h=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");a=await this.reader.parts(h,d)}if(this.ended)return!1;let l=(a?.parts??[]).map(h=>q(h)).filter(h=>h!==void 0);if(this.olderCursor=a?.nextCursor,this.olderLeft=typeof a?.nextCursor=="string"&&a.nextCursor!=="",this.before(l),r&&this.replays&&this.next===0&&this.pagedFrom!==void 0?(this.racing=!0,this.racedPages=l):this.racing&&(this.racedPages=l.concat(this.racedPages)),n===void 0||typeof a?.turns!="number"||s!==void 0&&this.olderCursor===s)break;n-=a.turns}while(n>0);return this.olderLeft}idFor(e,n){let s=n??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}before(e){for(let i of e){let c=v(i);c<=0||(this.paged.add(c),(this.pagedFrom===void 0||c<this.pagedFrom)&&(this.pagedFrom=c),(this.pagedTo===void 0||c>this.pagedTo)&&(this.pagedTo=c))}let n=new t(this.me);n.thoughts=this.thoughts,n.lowest=this.lowest-e.length;let s=n.lowest;for(let i of e)n.at=s++,n.fold(i);this.folded+=n.folded,this.lowest=n.lowest,this.chatId??=n.chatId;let r=new Map;for(let[i,c]of n.messages){let y=this.told.get(i)??[],f=c;if(y.length>0)for(let C of y)f=me(f,C);else f=this.messages.get(i)??c;r.set(i,f);let m=[...n.told.get(i)??[],...y];m.length>0&&this.told.set(i,m)}for(let[i,c]of this.messages)r.has(i)||r.set(i,c);this.messages.clear();for(let[i,c]of r)this.messages.set(i,c);let o=new Map;for(let[i,c]of n.responses){let y=this.responses.get(i);o.set(i,y?Ye(c,y):c)}for(let[i,c]of this.responses)o.has(i)||o.set(i,c);this.responses.clear();for(let[i,c]of o)this.responses.set(i,c);let d=new Set;for(let i of n.order)(i.type==="message"||i.type==="response")&&d.add(`${i.type}\0${i.key}`);let a=[...n.order],l=new Set([...n.messages.values()].flatMap(i=>i.responseId?[i.responseId]:[]));for(let i of this.order)if(!((i.type==="message"||i.type==="response")&&d.has(`${i.type}\0${i.key}`))&&!(i.type==="goal"&&i.event.seq>0&&n.goalWords.has(i.event.seq))&&!(i.type==="voice"&&n.voiceWords.has(F(i.event)))){if(i.type==="message"&&i.began&&i.turn!==null){let c=this.responses.get(i.turn);l.has(i.turn)?a.push({...i,began:!1,at:i.arrived}):a.push({...i,at:c&&c.at<i.arrived?c.at-.5:i.arrived});continue}a.push(i)}a.sort((i,c)=>i.at-c.at),this.order=a;for(let i of n.goalWords)this.goalWords.add(i);this.goal=null;for(let i of a)i.type==="goal"&&this.goalSaid(i.event);for(let i of n.voiceWords)this.voiceWords.add(i);let h=new Set;this.voice=null;for(let i of a)i.type==="voice"&&(this.voice=ye(this.voice,i.event,h));this.turn??=n.turn;let u=new Map([...n.calls,...this.calls]);this.calls.clear();for(let[i,c]of u)this.calls.set(i,c);for(let[i,c]of n.history)this.history.has(i)||this.history.set(i,c);this.forkedFrom??=n.forkedFrom,this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,n,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==n){n=o,yield o;continue}if(this.ended)return;await new Promise(d=>e=d)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0,clearTimeout(this.heldTimer);for(let e of[...this.enders])e()}}takePayload(e){let n=q(e);n&&this.take(n)}take(e){if(!this.ended){if(this.racing){this.held.length===0&&(this.heldSince=Date.now()),this.held.push(e);let n=v(e);n>0&&this.pagedTo!==void 0&&n>this.pagedTo?this.sortHeld():(clearTimeout(this.heldTimer),this.heldTimer=ge(setTimeout(()=>this.quiet(),he)));return}this.takeNow(e)}}quiet(){let e=this.held.map(v).filter(s=>s>0);e.length>0&&e.every(s=>!this.paged.has(s)&&this.pagedFrom!==void 0&&s<this.pagedFrom)&&Date.now()-this.heldSince<Qe?this.heldTimer=ge(setTimeout(()=>this.quiet(),he)):this.sortHeld()}takeNow(e){let n=v(e);n>0&&this.paged.has(n)||(n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.at=this.next++,this.fold(e)&&this.changed())}sortHeld(){clearTimeout(this.heldTimer),this.racing=!1;let e=this.held.splice(0),n=this.racedPages;this.racedPages=[];let s=[],r=[],o=e.findIndex(a=>this.paged.has(v(a))),d=o<0?-1:n.findIndex(a=>v(a)===v(e[o]));if(d>=0){let a=0;for(;a<o&&a<d&&fe(e[o-1-a],n[d-1-a]);)a++;let l=0;for(;o+l<e.length&&d+l<n.length&&fe(e[o+l],n[d+l]);)l++;s=e.slice(0,o-a),r=e.slice(o+l)}else{let a=e.find(h=>v(h)>0),l=a!==void 0&&this.pagedFrom!==void 0&&v(a)<this.pagedFrom;for(let h of e){let u=v(h);u>0&&!(this.pagedFrom!==void 0&&u<this.pagedFrom)&&(l=!1),(l?s:r).push(h)}}if(s.length>0){let a=Math.min(...s.map(v).filter(l=>l>0));this.before(s),Number.isFinite(a)&&(this.oldestLive=a,this.olderCursor=void 0)}for(let a of r)this.takeNow(a)}fold(e){switch(this.folded++,e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let n=this.response(e.response_id);n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(n.startedBy=e.user_id),e.goal&&(n.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let n=this.response(e.response_id);if(e.seq>0){if(this.thoughts.has(e.seq))return!1;this.thoughts.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:n.from+P(n.text),loose:n.text==="",cutAt:n.cut,thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=n.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:n.marks.set(s,{type:"thinking",text_offset:n.from+P(n.text),loose:n.text==="",cutAt:n.cut,thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e,at:this.at});break;case"voice":{let n=F(e);if(this.voiceWords.has(n))return!1;this.voice=ye(this.voice,e,this.voiceWords),this.order.push({type:"voice",event:e,at:this.at});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let n=this.response(e.response_id);et(n,e.offset,e.text),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"reset":{let n=this.response(e.response_id);e.offset<=n.from?(n.text="",n.from=Math.max(0,e.offset)):n.text=n.text.slice(0,S(n.text,e.offset-n.from)),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let n=this.response(e.response_id);n.runId=e.run_id,n.agent=e.name,n.named=!0,n.parentId??=e.parent_response_id;break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let n=this.goal;if(!n||n.id!==e.goal_id)return;let s={...n,events:[...n.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let n=Xe(e),s=this.messages.get(n);this.messages.set(n,me(s,e));let r=this.told.get(n);r?r.push(e):this.told.set(n,[e]),s||this.place(e,n),this.changed()}said(e){let n=`voice\0${e.id}`,s=this.messages.get(n);this.messages.set(n,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:n,at:this.at,arrived:this.at,turn:null,began:!1}),this.changed()}place(e,n){let s=e.response_id??null,r=s!==null&&![...this.messages.entries()].some(([l,h])=>l!==n&&h.responseId===s),o=r?this.responses.get(s):void 0,d={type:"message",key:n,at:o?o.at-.5:this.at,arrived:this.at,turn:s,began:r},a=o?this.order.findIndex(l=>l.type==="response"&&l.key===s):-1;a>=0?this.order.splice(a,0,d):this.order.push(d)}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",from:0,cut:null,marks:new Map,runId:null,agent:null,named:!1,parentId:null,startedBy:void 0,goal:null,at:this.at},this.responses.set(e,n),this.order.push({type:"response",key:e,at:this.at})),n}changed(){this.snapshot=void 0,!this.changing&&(this.changing=!0,queueMicrotask(()=>{if(this.changing=!1,this.listeners.size===0)return;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=u=>e!==void 0&&u.startedBy===e,s=new Map;for(let u of this.responses.values()){let i=u.parentId!==null?this.responses.get(u.parentId)??u:u;s.set(u.id,tt(u,i.startedBy??null,n(i),u.goal??i.goal))}let r=new Map([...this.messages].map(([u,i])=>[u,e!==void 0&&i.author===e?{...i,mine:!0}:i])),o=[...this.history.entries()].sort(([u],[i])=>u-i).flatMap(([u,i])=>i.map((c,y)=>nt(c,`${u}:${y}`,e))),d=[...o];for(let u of this.order)u.type==="goal"?d.push({type:"goal",goal:u.event}):u.type==="voice"?d.push({type:"voice",voice:u.event}):u.type==="message"?d.push({type:"message",message:r.get(u.key)}):this.responses.get(u.key).parentId===null&&d.push({type:"response",response:s.get(u.key)});let a=o.flatMap(u=>u.type==="message"?[u.message]:[]),l=o.flatMap(u=>u.type==="response"?[u.response]:[]),h=[...this.calls.values()].filter(u=>s.get(u.response_id)?.mine===!0);return{items:d,messages:[...a,...r.values()],responses:[...l,...s.values()],turn:this.turn,waiting:{approvals:h.filter(u=>u.status==="awaiting_approval"),outputs:h.filter(u=>u.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Ze(this.voice,e):null}}},he=150,Qe=2e3;function fe(t,e){let n=v(t);return n>0||v(e)>0?n===v(e):JSON.stringify(t)===JSON.stringify(e)}function v(t){let e=t.seq;return typeof e=="number"&&e>0?e:0}function ge(t){return t.unref?.(),t}function F(t){return`${t.voice_id}\0${t.status}`}function ye(t,e,n){return n.add(F(e)),(e.status==="closed"?t===null||t.voice_id===e.voice_id:!n.has(`${e.voice_id}\0closed`))?e:t}function me(t,e){let n=e.status==="delivered"||e.status==="failed"?e.status:"pending";return{clientId:e.client_id,id:e.id??t?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:t?.status==="delivered"?"delivered":n,error:e.error??null,responseId:e.response_id??t?.responseId??null,createdAt:e.created_at??t?.createdAt??"",mine:!1,metadata:e.metadata??t?.metadata??{},history:!1,truncated:!1,kind:e.kind??t?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:t?.voice??null,attachments:e.attachments?we(e.attachments):t?.attachments??[]}}function Ye(t,e){let n={...t,marks:new Map(t.marks)};e.status!==null&&(n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=e.end),e.startedBy!==void 0&&(n.startedBy=e.startedBy),e.goal&&(n.goal=e.goal),e.named&&(n.runId=e.runId,n.agent=e.agent,n.named=!0),n.parentId=t.parentId??e.parentId,e.cut!==null&&(t.text===""||e.cut<=t.from?(n.text=e.text,n.from=e.text===""?Math.max(0,e.cut):e.from):n.text=t.text.slice(0,S(t.text,e.cut-t.from))+e.text,n.cut=t.cut===null?e.cut:Math.min(t.cut,e.cut));let s=r=>{if(t.text==="")return null;if(r!==null&&r<=t.from)return r;let o=P(t.text);return t.from+(r===null?o:Math.min(o,r-t.from))};for(let[r,o]of e.marks){let d=n.marks.get(r);if(d?.type==="thinking"&&o.type==="thinking"&&r!=="thinking:unavailable")n.marks.set(r,{...d,thinking:{...d.thinking,text:d.thinking.text+o.thinking.text}});else if(o.type==="thinking"&&o.loose){let a=s(o.cutAt);n.marks.set(r,a!==null?{...o,text_offset:a,loose:!1}:{...o,cutAt:o.cutAt===null?t.cut:t.cut===null?o.cutAt:Math.min(o.cutAt,t.cut)})}else n.marks.set(r,o)}return n}function Ze(t,e){return{id:t.voice_id,userId:t.user_id,mine:e!==void 0&&t.user_id===e,delegation:t.delegation,status:t.status,seconds:typeof t.seconds=="number"?t.seconds:null,closeReason:t.close_reason??""}}function we(t){return t.map((e,n)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:n,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function Xe(t){return`${t.author??""}\0${t.client_id}`}function et(t,e,n){if(t.text===""||e<=t.from){t.from=Math.max(0,e),t.text=n;return}t.text=t.text.slice(0,S(t.text,e-t.from))+n}function tt(t,e,n,s){let r=[...t.marks.values()].map((l,h)=>({m:l,i:h,at:S(t.text,Math.max(0,(Number(l.text_offset)||0)-t.from))}));r.sort((l,h)=>l.at-h.at||l.i-h.i);let o=[],d=[],a=0;for(let{m:l,at:h}of r)h>a&&o.push({type:"text",text:t.text.slice(a,h)}),a=Math.max(a,h),l.type==="thinking"?(o.push({type:"thinking",thinking:l.thinking}),d.push(l.thinking)):o.push(l.type==="tool"?{type:"tool",tool:l}:{type:"agent",agent:l});return a<t.text.length&&o.push({type:"text",text:t.text.slice(a)}),{id:t.id,status:t.status,waiting:t.waiting,end:t.end,error:t.error,text:t.text,parts:o,runId:t.runId,agent:t.agent,parentId:t.parentId,startedBy:e,mine:n,thinking:d,goal:s,history:!1,truncated:!1}}function nt(t,e,n){let s=t.text_truncated===!0;if(t.role==="user"){let r=t.author??null;return{type:"message",message:{clientId:t.client_id??"",id:t.message_id??null,text:t.text,author:r,authorName:t.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:t.created_at??"",mine:n!==void 0&&r===n,metadata:t.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:we(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var B=[["ApiKeyAuth","userJWT"]];function ve(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.turns!==void 0&&(s.turns=n.turns),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${_("ListChatParts","chat_id",e)}/parts`,auth:B,answers:{200:"json"},query:s,signal:n.signal})).data;return{parts:r.parts,...r.next_cursor!==void 0?{nextCursor:r.next_cursor}:{},...r.turns!==void 0?{turns:r.turns}:{}}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${_("GetChatToolCall","chat_id",e)}/tool-calls/${_("GetChatToolCall","call_id",n)}`,auth:B,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let o={path:n};return s!==void 0&&(o.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:B,answers:{200:"raw"},query:o,signal:r})).data.blob()}}}var M=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},be=new WeakMap;async function Ee(t,e,n,s={},r=()=>{},o){let{pattern:d,events:a,messages:l,durable:h,chat:u}=st(e),i=rt(d,n),c=be.get(t);c||be.set(t,c=new Map);let y=c,f=y.get(i)??{count:0};y.set(i,f),f.count++;let m=t.channel(i,h&&s.history!==!1?{after:0}:{});if(u&&!f.chat){let g=n.chatId,k=new O(r,o,typeof g=="string"&&g!==""?g:void 0,h&&s.history!==!1);f.chat=k,f.unchat=m.on("broadcast",w=>{w.event==="chat"&&k.takePayload(w.payload)})}let C=()=>{--f.count>0||(y.delete(i),f.unchat?.(),f.chat?.end(),m.leave())};try{await m.join()}catch{let g=m.state==="refused"?ke(m.refusal,"unavailable"):"socket closed";throw C(),new M(`gateway ${JSON.stringify(i)} was not joined: ${g}`,g)}let T=!1,R=new Set,V=()=>{if(!T){T=!0,Ke();for(let g of[...R])g();C()}},Ke=m.onClosed(V),U=g=>{if(T)return()=>{};let k=m.on("broadcast",b=>{typeof b.event=="string"&&a.has(b.event)&&g(b.event,E(b.payload))}),w=()=>{R.delete(w),k()};return R.add(w),w},z={topic:i,get seq(){return m.logSeq},on(g,k){if(typeof g=="function")return U((w,b)=>g({event:w,payload:b}));if(!a.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no event ${JSON.stringify(String(g))}`);if(typeof k!="function")throw new TypeError(`gateway ${JSON.stringify(d)}: on(${JSON.stringify(g)}, \u2026) takes the function the event is handed to`);return U((w,b)=>{w===g&&k(b)})},off(g){R.has(g)&&g()},async send(g,k){if(!l.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no message ${JSON.stringify(String(g))}`);let w=T?{status:"error",response:{reason:"not joined"}}:await m.push("broadcast",{type:"broadcast",event:g,payload:k});if(w.status==="ok")return E(w.response.reply);let b=ke(w.response,"unavailable");throw new M(`gateway ${JSON.stringify(i)} did not take ${JSON.stringify(g)}: ${b}`,b)},leave:V};return u&&Object.defineProperty(z,"chat",{value:f.chat,enumerable:!0}),z}function st(t){let e=typeof t=="object"&&t!==null?t:{},n=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!n(e.events)||!n(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function rt(t,e){let n=typeof e=="object"&&e!==null?e:{};return t.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(n,r)?n[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(t)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(t)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function ke(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var ot=3600*1e3,j=new Map;function it(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=j.get(s);if(!n&&r&&Date.now()-r.at<ot)return r.list;let o=(async()=>{let d=se(),a;try{a=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:d},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(l){throw new p("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:l})}try{return await re(a,e.signer,e.projectId,d)}catch(l){throw new p("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:l})}})();return j.set(s,{list:o,at:Date.now()}),o.catch(()=>{j.get(s)?.list===o&&j.delete(s)}),o}async function _e(t,e,n,s,r,o){let a=(await it(t,e,o)).keys[0];return X(a.kid,a.key,Z(e.projectId,n,s,r))}function K(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):N(e,n,s,(r,o)=>ee(t.key,r,o))}function xe(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):N(e,"/response",n,async(r,o)=>{if(!te(o))throw new p("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await ne(t.key,r,o)}catch(d){throw new p("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:d})}})}function Ce(t){return t instanceof p&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var L=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
1
+ /*! palbase 0.63.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as q,c as P,d as S}from"./SWB2U22R.js";import{a as Y,f as Z,g as X,j as ee,k as te,l as ne,o as N,p as se,q as re}from"./UDS4W77D.js";import{d as G}from"./KGP3V3IA.js";import{a as E,b as Q,c as _,e as A}from"./LGGBVI33.js";var p=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,n){super(n.message,n.cause===void 0?void 0:{cause:n.cause}),this.name="BackendError",this.kind=e,this.code=n.code,this.status=n.status??0,this.requestId=n.requestId,this.fields=n.fields,this.retryAfter=n.retryAfter,this.data=n.data}};function ae(t){return t instanceof p||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function D(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??We(e,"request_id"),data:x(e,"data"),cause:t};if(t.code==="network_error")return new p("network",n);if(t.status===401&&t.code==="insufficient_user_authentication")return new p("stepUpRequired",n);if(t.status===401&&t.code==="app_attest_required")return new p("attestationRequired",n);if(t.status===401)return new p("unauthorized",n);if(t.status===429)return new p("rateLimited",{...n,retryAfter:Je(e)??t.retryAfter});let s=Le(e);return t.status===400&&s?new p("validation",{...n,fields:s}):new p("server",n)}function I(t){return t instanceof Q||t instanceof Error&&t.name==="PalbaseError"}function oe(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Le(t){let e=x(x(t,"data"),"fields");if(oe(e))return e;let n=x(t,"fields");return oe(n)?n:void 0}function Je(t){return ie(t,"retry_after")??ie(x(t,"data"),"retryAfter")}function x(t,e){if(typeof t=="object"&&t!==null)return t[e]}function ie(t,e){let n=x(t,e);return typeof n=="number"?n:void 0}function We(t,e){let n=x(t,e);return typeof n=="string"?n:void 0}var He=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ve=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),Ue=new Set(Ve),ze=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function $(t){return t==="then"||t==="toJSON"||ze.has(t)}function de(t){return t==="call"||t==="join"||$(t)}function le(t){return typeof t=="string"&&He.test(t)&&!Ue.has(t)&&!$(t)}function ue(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function ce(t){A(t)}function pe(t){return A(t).origin}var O=class t{me;reader;messages=new Map;told=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;history=new Map;forkedFrom=null;calls=new Map;thoughts=new Set;at=0;next=0;lowest=0;folded=0;paged=new Set;pagedFrom;pagedTo;racing=!1;replays;held=[];racedPages=[];heldTimer;heldSince=0;oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;changing=!1;ended=!1;constructor(e=()=>{},n,s,r=!0){this.me=e,this.reader=n,this.chatId=s,this.replays=r}get hasOlder(){return this.olderLeft}loadOlder(e={}){return e.limit!==void 0&&e.turns!==void 0?Promise.reject(new TypeError("loadOlder: limit (events) or turns (turns), not both")):e.turns!==void 0&&(!Number.isSafeInteger(e.turns)||e.turns<1||e.turns>20)?Promise.reject(new TypeError(`loadOlder: turns is how many more of the chat's turns to read back to, 1 to 20 (got ${String(e.turns)})`)):(this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading)}async readOlder(e){let n=e.turns;do{if(!this.olderLeft)return!1;let s=this.olderCursor,r=this.next===0&&this.olderCursor===void 0,d={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...n!==void 0?{turns:n}:{},...e.signal?{signal:e.signal}:{}},a;if(e.load)a=await e.load(d);else{let h=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");a=await this.reader.parts(h,d)}if(this.ended)return!1;let l=(a?.parts??[]).map(h=>q(h)).filter(h=>h!==void 0);if(this.olderCursor=a?.nextCursor,this.olderLeft=typeof a?.nextCursor=="string"&&a.nextCursor!=="",this.before(l),r&&this.replays&&this.next===0&&this.pagedFrom!==void 0?(this.racing=!0,this.racedPages=l):this.racing&&(this.racedPages=l.concat(this.racedPages)),n===void 0||typeof a?.turns!="number"||s!==void 0&&this.olderCursor===s)break;n-=a.turns}while(n>0);return this.olderLeft}idFor(e,n){let s=n??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}before(e){for(let i of e){let c=v(i);c<=0||(this.paged.add(c),(this.pagedFrom===void 0||c<this.pagedFrom)&&(this.pagedFrom=c),(this.pagedTo===void 0||c>this.pagedTo)&&(this.pagedTo=c))}let n=new t(this.me);n.thoughts=this.thoughts,n.lowest=this.lowest-e.length;let s=n.lowest;for(let i of e)n.at=s++,n.fold(i);this.folded+=n.folded,this.lowest=n.lowest,this.chatId??=n.chatId;let r=new Map;for(let[i,c]of n.messages){let y=this.told.get(i)??[],f=c;if(y.length>0)for(let C of y)f=me(f,C);else f=this.messages.get(i)??c;r.set(i,f);let m=[...n.told.get(i)??[],...y];m.length>0&&this.told.set(i,m)}for(let[i,c]of this.messages)r.has(i)||r.set(i,c);this.messages.clear();for(let[i,c]of r)this.messages.set(i,c);let o=new Map;for(let[i,c]of n.responses){let y=this.responses.get(i);o.set(i,y?Ye(c,y):c)}for(let[i,c]of this.responses)o.has(i)||o.set(i,c);this.responses.clear();for(let[i,c]of o)this.responses.set(i,c);let d=new Set;for(let i of n.order)(i.type==="message"||i.type==="response")&&d.add(`${i.type}\0${i.key}`);let a=[...n.order],l=new Set([...n.messages.values()].flatMap(i=>i.responseId?[i.responseId]:[]));for(let i of this.order)if(!((i.type==="message"||i.type==="response")&&d.has(`${i.type}\0${i.key}`))&&!(i.type==="goal"&&i.event.seq>0&&n.goalWords.has(i.event.seq))&&!(i.type==="voice"&&n.voiceWords.has(F(i.event)))){if(i.type==="message"&&i.began&&i.turn!==null){let c=this.responses.get(i.turn);l.has(i.turn)?a.push({...i,began:!1,at:i.arrived}):a.push({...i,at:c&&c.at<i.arrived?c.at-.5:i.arrived});continue}a.push(i)}a.sort((i,c)=>i.at-c.at),this.order=a;for(let i of n.goalWords)this.goalWords.add(i);this.goal=null;for(let i of a)i.type==="goal"&&this.goalSaid(i.event);for(let i of n.voiceWords)this.voiceWords.add(i);let h=new Set;this.voice=null;for(let i of a)i.type==="voice"&&(this.voice=ye(this.voice,i.event,h));this.turn??=n.turn;let u=new Map([...n.calls,...this.calls]);this.calls.clear();for(let[i,c]of u)this.calls.set(i,c);for(let[i,c]of n.history)this.history.has(i)||this.history.set(i,c);this.forkedFrom??=n.forkedFrom,this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,n,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==n){n=o,yield o;continue}if(this.ended)return;await new Promise(d=>e=d)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0,clearTimeout(this.heldTimer);for(let e of[...this.enders])e()}}takePayload(e){let n=q(e);n&&this.take(n)}take(e){if(!this.ended){if(this.racing){this.held.length===0&&(this.heldSince=Date.now()),this.held.push(e);let n=v(e);n>0&&this.pagedTo!==void 0&&n>this.pagedTo?this.sortHeld():(clearTimeout(this.heldTimer),this.heldTimer=ge(setTimeout(()=>this.quiet(),he)));return}this.takeNow(e)}}quiet(){let e=this.held.map(v).filter(s=>s>0);e.length>0&&e.every(s=>!this.paged.has(s)&&this.pagedFrom!==void 0&&s<this.pagedFrom)&&Date.now()-this.heldSince<Qe?this.heldTimer=ge(setTimeout(()=>this.quiet(),he)):this.sortHeld()}takeNow(e){let n=v(e);n>0&&this.paged.has(n)||(n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.at=this.next++,this.fold(e)&&this.changed())}sortHeld(){clearTimeout(this.heldTimer),this.racing=!1;let e=this.held.splice(0),n=this.racedPages;this.racedPages=[];let s=[],r=[],o=e.findIndex(a=>this.paged.has(v(a))),d=o<0?-1:n.findIndex(a=>v(a)===v(e[o]));if(d>=0){let a=0;for(;a<o&&a<d&&fe(e[o-1-a],n[d-1-a]);)a++;let l=0;for(;o+l<e.length&&d+l<n.length&&fe(e[o+l],n[d+l]);)l++;s=e.slice(0,o-a),r=e.slice(o+l)}else{let a=e.find(h=>v(h)>0),l=a!==void 0&&this.pagedFrom!==void 0&&v(a)<this.pagedFrom;for(let h of e){let u=v(h);u>0&&!(this.pagedFrom!==void 0&&u<this.pagedFrom)&&(l=!1),(l?s:r).push(h)}}if(s.length>0){let a=Math.min(...s.map(v).filter(l=>l>0));this.before(s),Number.isFinite(a)&&(this.oldestLive=a,this.olderCursor=void 0)}for(let a of r)this.takeNow(a)}fold(e){switch(this.folded++,e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let n=this.response(e.response_id);n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(n.startedBy=e.user_id),e.goal&&(n.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let n=this.response(e.response_id);if(e.seq>0){if(this.thoughts.has(e.seq))return!1;this.thoughts.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:n.from+P(n.text),loose:n.text==="",cutAt:n.cut,thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=n.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:n.marks.set(s,{type:"thinking",text_offset:n.from+P(n.text),loose:n.text==="",cutAt:n.cut,thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e,at:this.at});break;case"voice":{let n=F(e);if(this.voiceWords.has(n))return!1;this.voice=ye(this.voice,e,this.voiceWords),this.order.push({type:"voice",event:e,at:this.at});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let n=this.response(e.response_id);et(n,e.offset,e.text),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"reset":{let n=this.response(e.response_id);e.offset<=n.from?(n.text="",n.from=Math.max(0,e.offset)):n.text=n.text.slice(0,S(n.text,e.offset-n.from)),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let n=this.response(e.response_id);n.runId=e.run_id,n.agent=e.name,n.named=!0,n.parentId??=e.parent_response_id;break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let n=this.goal;if(!n||n.id!==e.goal_id)return;let s={...n,events:[...n.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let n=Xe(e),s=this.messages.get(n);this.messages.set(n,me(s,e));let r=this.told.get(n);r?r.push(e):this.told.set(n,[e]),s||this.place(e,n),this.changed()}said(e){let n=`voice\0${e.id}`,s=this.messages.get(n);this.messages.set(n,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:n,at:this.at,arrived:this.at,turn:null,began:!1}),this.changed()}place(e,n){let s=e.response_id??null,r=s!==null&&![...this.messages.entries()].some(([l,h])=>l!==n&&h.responseId===s),o=r?this.responses.get(s):void 0,d={type:"message",key:n,at:o?o.at-.5:this.at,arrived:this.at,turn:s,began:r},a=o?this.order.findIndex(l=>l.type==="response"&&l.key===s):-1;a>=0?this.order.splice(a,0,d):this.order.push(d)}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",from:0,cut:null,marks:new Map,runId:null,agent:null,named:!1,parentId:null,startedBy:void 0,goal:null,at:this.at},this.responses.set(e,n),this.order.push({type:"response",key:e,at:this.at})),n}changed(){this.snapshot=void 0,!this.changing&&(this.changing=!0,queueMicrotask(()=>{if(this.changing=!1,this.listeners.size===0)return;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=u=>e!==void 0&&u.startedBy===e,s=new Map;for(let u of this.responses.values()){let i=u.parentId!==null?this.responses.get(u.parentId)??u:u;s.set(u.id,tt(u,i.startedBy??null,n(i),u.goal??i.goal))}let r=new Map([...this.messages].map(([u,i])=>[u,e!==void 0&&i.author===e?{...i,mine:!0}:i])),o=[...this.history.entries()].sort(([u],[i])=>u-i).flatMap(([u,i])=>i.map((c,y)=>nt(c,`${u}:${y}`,e))),d=[...o];for(let u of this.order)u.type==="goal"?d.push({type:"goal",goal:u.event}):u.type==="voice"?d.push({type:"voice",voice:u.event}):u.type==="message"?d.push({type:"message",message:r.get(u.key)}):this.responses.get(u.key).parentId===null&&d.push({type:"response",response:s.get(u.key)});let a=o.flatMap(u=>u.type==="message"?[u.message]:[]),l=o.flatMap(u=>u.type==="response"?[u.response]:[]),h=[...this.calls.values()].filter(u=>s.get(u.response_id)?.mine===!0);return{items:d,messages:[...a,...r.values()],responses:[...l,...s.values()],turn:this.turn,waiting:{approvals:h.filter(u=>u.status==="awaiting_approval"),outputs:h.filter(u=>u.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Ze(this.voice,e):null}}},he=150,Qe=2e3;function fe(t,e){let n=v(t);return n>0||v(e)>0?n===v(e):JSON.stringify(t)===JSON.stringify(e)}function v(t){let e=t.seq;return typeof e=="number"&&e>0?e:0}function ge(t){return t.unref?.(),t}function F(t){return`${t.voice_id}\0${t.status}`}function ye(t,e,n){return n.add(F(e)),(e.status==="closed"?t===null||t.voice_id===e.voice_id:!n.has(`${e.voice_id}\0closed`))?e:t}function me(t,e){let n=e.status==="delivered"||e.status==="failed"?e.status:"pending";return{clientId:e.client_id,id:e.id??t?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:t?.status==="delivered"?"delivered":n,error:e.error??null,responseId:e.response_id??t?.responseId??null,createdAt:e.created_at??t?.createdAt??"",mine:!1,metadata:e.metadata??t?.metadata??{},history:!1,truncated:!1,kind:e.kind??t?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:t?.voice??null,attachments:e.attachments?we(e.attachments):t?.attachments??[]}}function Ye(t,e){let n={...t,marks:new Map(t.marks)};e.status!==null&&(n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=e.end),e.startedBy!==void 0&&(n.startedBy=e.startedBy),e.goal&&(n.goal=e.goal),e.named&&(n.runId=e.runId,n.agent=e.agent,n.named=!0),n.parentId=t.parentId??e.parentId,e.cut!==null&&(t.text===""||e.cut<=t.from?(n.text=e.text,n.from=e.text===""?Math.max(0,e.cut):e.from):n.text=t.text.slice(0,S(t.text,e.cut-t.from))+e.text,n.cut=t.cut===null?e.cut:Math.min(t.cut,e.cut));let s=r=>{if(t.text==="")return null;if(r!==null&&r<=t.from)return r;let o=P(t.text);return t.from+(r===null?o:Math.min(o,r-t.from))};for(let[r,o]of e.marks){let d=n.marks.get(r);if(d?.type==="thinking"&&o.type==="thinking"&&r!=="thinking:unavailable")n.marks.set(r,{...d,thinking:{...d.thinking,text:d.thinking.text+o.thinking.text}});else if(o.type==="thinking"&&o.loose){let a=s(o.cutAt);n.marks.set(r,a!==null?{...o,text_offset:a,loose:!1}:{...o,cutAt:o.cutAt===null?t.cut:t.cut===null?o.cutAt:Math.min(o.cutAt,t.cut)})}else n.marks.set(r,o)}return n}function Ze(t,e){return{id:t.voice_id,userId:t.user_id,mine:e!==void 0&&t.user_id===e,delegation:t.delegation,status:t.status,seconds:typeof t.seconds=="number"?t.seconds:null,closeReason:t.close_reason??""}}function we(t){return t.map((e,n)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:n,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function Xe(t){return`${t.author??""}\0${t.client_id}`}function et(t,e,n){if(t.text===""||e<=t.from){t.from=Math.max(0,e),t.text=n;return}t.text=t.text.slice(0,S(t.text,e-t.from))+n}function tt(t,e,n,s){let r=[...t.marks.values()].map((l,h)=>({m:l,i:h,at:S(t.text,Math.max(0,(Number(l.text_offset)||0)-t.from))}));r.sort((l,h)=>l.at-h.at||l.i-h.i);let o=[],d=[],a=0;for(let{m:l,at:h}of r)h>a&&o.push({type:"text",text:t.text.slice(a,h)}),a=Math.max(a,h),l.type==="thinking"?(o.push({type:"thinking",thinking:l.thinking}),d.push(l.thinking)):o.push(l.type==="tool"?{type:"tool",tool:l}:{type:"agent",agent:l});return a<t.text.length&&o.push({type:"text",text:t.text.slice(a)}),{id:t.id,status:t.status,waiting:t.waiting,end:t.end,error:t.error,text:t.text,parts:o,runId:t.runId,agent:t.agent,parentId:t.parentId,startedBy:e,mine:n,thinking:d,goal:s,history:!1,truncated:!1}}function nt(t,e,n){let s=t.text_truncated===!0;if(t.role==="user"){let r=t.author??null;return{type:"message",message:{clientId:t.client_id??"",id:t.message_id??null,text:t.text,author:r,authorName:t.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:t.created_at??"",mine:n!==void 0&&r===n,metadata:t.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:we(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var B=[["ApiKeyAuth","userJWT"]];function ve(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.turns!==void 0&&(s.turns=n.turns),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${_("ListChatParts","chat_id",e)}/parts`,auth:B,answers:{200:"json"},query:s,signal:n.signal})).data;return{parts:r.parts,...r.next_cursor!==void 0?{nextCursor:r.next_cursor}:{},...r.turns!==void 0?{turns:r.turns}:{}}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${_("GetChatToolCall","chat_id",e)}/tool-calls/${_("GetChatToolCall","call_id",n)}`,auth:B,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let o={path:n};return s!==void 0&&(o.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:B,answers:{200:"raw"},query:o,signal:r})).data.blob()}}}var M=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},be=new WeakMap;async function Ee(t,e,n,s={},r=()=>{},o){let{pattern:d,events:a,messages:l,durable:h,chat:u}=st(e),i=rt(d,n),c=be.get(t);c||be.set(t,c=new Map);let y=c,f=y.get(i)??{count:0};y.set(i,f),f.count++;let m=t.channel(i,h&&s.history!==!1?{after:0}:{});if(u&&!f.chat){let g=n.chatId,k=new O(r,o,typeof g=="string"&&g!==""?g:void 0,h&&s.history!==!1);f.chat=k,f.unchat=m.on("broadcast",w=>{w.event==="chat"&&k.takePayload(w.payload)})}let C=()=>{--f.count>0||(y.delete(i),f.unchat?.(),f.chat?.end(),m.leave())};try{await m.join()}catch{let g=m.state==="refused"?ke(m.refusal,"unavailable"):"socket closed";throw C(),new M(`gateway ${JSON.stringify(i)} was not joined: ${g}`,g)}let T=!1,R=new Set,V=()=>{if(!T){T=!0,Ke();for(let g of[...R])g();C()}},Ke=m.onClosed(V),U=g=>{if(T)return()=>{};let k=m.on("broadcast",b=>{typeof b.event=="string"&&a.has(b.event)&&g(b.event,E(b.payload))}),w=()=>{R.delete(w),k()};return R.add(w),w},z={topic:i,get seq(){return m.logSeq},on(g,k){if(typeof g=="function")return U((w,b)=>g({event:w,payload:b}));if(!a.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no event ${JSON.stringify(String(g))}`);if(typeof k!="function")throw new TypeError(`gateway ${JSON.stringify(d)}: on(${JSON.stringify(g)}, \u2026) takes the function the event is handed to`);return U((w,b)=>{w===g&&k(b)})},off(g){R.has(g)&&g()},async send(g,k){if(!l.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no message ${JSON.stringify(String(g))}`);let w=T?{status:"error",response:{reason:"not joined"}}:await m.push("broadcast",{type:"broadcast",event:g,payload:k});if(w.status==="ok")return E(w.response.reply);let b=ke(w.response,"unavailable");throw new M(`gateway ${JSON.stringify(i)} did not take ${JSON.stringify(g)}: ${b}`,b)},leave:V};return u&&Object.defineProperty(z,"chat",{value:f.chat,enumerable:!0}),z}function st(t){let e=typeof t=="object"&&t!==null?t:{},n=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!n(e.events)||!n(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function rt(t,e){let n=typeof e=="object"&&e!==null?e:{};return t.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(n,r)?n[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(t)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(t)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function ke(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var ot=3600*1e3,j=new Map;function it(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=j.get(s);if(!n&&r&&Date.now()-r.at<ot)return r.list;let o=(async()=>{let d=se(),a;try{a=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:d},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(l){throw new p("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:l})}try{return await re(a,e.signer,e.projectId,d)}catch(l){throw new p("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:l})}})();return j.set(s,{list:o,at:Date.now()}),o.catch(()=>{j.get(s)?.list===o&&j.delete(s)}),o}async function _e(t,e,n,s,r,o){let a=(await it(t,e,o)).keys[0];return X(a.kid,a.key,Z(e.projectId,n,s,r))}function K(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):N(e,n,s,(r,o)=>ee(t.key,r,o))}function xe(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):N(e,"/response",n,async(r,o)=>{if(!te(o))throw new p("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await ne(t.key,r,o)}catch(d){throw new p("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:d})}})}function Ce(t){return t instanceof p&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var L=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
3
3
  `);let n=[],s=this.pending.indexOf(`
4
4
  `);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let o=r.endsWith("\r")?r.slice(0,-1):r;if(o==="")this.dataLines.length>0&&n.push({event:this.eventName,payload:this.dataLines.join(`
5
5
  `)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let d=o.slice(5);this.dataLines.push(d.startsWith(" ")?d.slice(1):d)}else if(o.startsWith("event:")){let d=o.slice(6);this.eventName=d.startsWith(" ")?d.slice(1):d}}s=this.pending.indexOf(`
@@ -1,2 +1,2 @@
1
- /*! palbase 0.62.0 — Palbase SDK License (see LICENSE) */
2
- import{c as D,g as b,l as O,m as _,s as F}from"./P3QFV5EA.js";import{b as w}from"./ECVNYWWT.js";var I=20,M=2048,S=256,j=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new w({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function L(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>I)throw m(`${n.length} attributes: at most ${I}`);let t=[];for(let i of n){if(!j.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=L(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>M)throw m(`the attributes are ${a.length} bytes: at most ${M}`);return a}function x(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function R(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function $(e,n,t){let a=e/10**R(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(R(n))} ${n}`}}function X(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var K={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function B(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=K[n.split("-")[0].toLowerCase()];return a?a(t):t}function H(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function E(e,n){let t=new Map,a=new Map;for(let r of e){let s=x(r.period);if(!s)continue;let u=r.price.amount/s.months;t.set(r.key,u),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,u))}let i={};for(let r of e){let s={product_name:r.productName,price:$(r.price.amount,r.price.currency,n)},u=x(r.period);if(u){s.period=X(u,n),s.price_per_month=$(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,d=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;d>=.01&&(s.savings=H(d,n))}let l=r.intro?.mode==="free_trial"?x(r.intro.duration):null;l&&(s.trial=B(l,n)),r.offer&&(s.offer_price=$(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.62.0"};var C=`palbase-js/${V.version}`;var k=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,u={},l=[]){this.placement=n,this.source=t,this.definition=a,this.assets=u,this.offerings=i,this.offers=l,this.shown=r,this.deps=s}packages(n){return E(Y(this.offerings,O(this.definition),n,Z(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?q():void 0,r=this.packages(a),s=F(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let d=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(d,o):globalThis.location.assign(d)}catch(d){if(!t.onError)throw d;t.onError(d,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),u=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",u),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let l=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",u),l()},s}};function q(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function W(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function Y(e,n,t,a=new Map){let i=[];for(let r of n){let[s,u]=r.split("."),l=e.products.find(f=>f.key===s),o=l?.channels.web,d=o?.plans.find(f=>f.key===u);if(!l||!o||!d)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:W(o.locales,t)??l.key,price:{amount:d.price.amount,currency:d.price.currency},period:d.period,intro:d.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function Z(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var G={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function Q(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:G,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function h(){try{return globalThis.localStorage}catch{return}}function ee(e){try{let n=h()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?h()?.setItem(e,JSON.stringify(n)):h()?.removeItem(e)}catch{}}var z=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U;function te(e){let n=`palbase.installation.${e}`;try{let t=h()?.getItem(n);if(t&&/^[A-Za-z0-9._:-]{1,128}$/.test(t))return t;let a=z();if(h()?.setItem(n,a),h()?.getItem(n)===a)return a}catch{}return U??=z(),U}async function ye(e,n,t,a,i={}){let{signal:r,fetch:s}=i,u=T(i.attributes),l=`palbase.paywall.${n}.${t}`,o=te(n),p={checkout:a,expose:async c=>{if(c.shown)try{let v={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":o},body:v})}catch{}}},g=async(c,v)=>new k(t,v,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await D(c.assets??[],{signal:r,...s?{fetch:s}:{}}),c.offers??[]),f=ee(l),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":o,"X-Platform":"web","X-Palbase-SDK":C,...i.appVersion?{"X-Palbase-Client-Version":i.appVersion}:{},...i.app?{"X-Palbase-App":i.app}:{},...i.locale?{"Accept-Language":i.locale}:{},...u!==void 0?{"X-Palbase-Attributes":u}:{},...f?.etag?{"If-None-Match":f.etag}:{}},signal:r})}catch(c){if(c instanceof w&&c.status===404||c instanceof w&&c.status===400&&c.code.startsWith("invalid_"))return P(l,void 0),A(e,t,p,r);if(f&&!r?.aborted)return g(f.answer,"cache");throw c}return y.status===200?(P(l,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&f?g(f.answer,"server"):(P(l,void 0),A(e,t,p,r))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=Q(i);return r?new k(n,"default",r,i,void 0,t):null}export{T as a,x as b,$ as c,X as d,E as e,k as f,Q as g,ye as h};
1
+ /*! palbase 0.63.0 — Palbase SDK License (see LICENSE) */
2
+ import{c as D,g as b,l as O,m as _,s as F}from"./EJ7YD4YY.js";import{b as w}from"./LGGBVI33.js";var I=20,M=2048,S=256,j=/^[A-Za-z][A-Za-z0-9_.-]{0,39}$/,m=e=>new w({op:"GetPlacementPaywall",status:0,code:"invalid_attributes",message:e});function L(e){let n='"';for(let t=0;t<e.length;t++){let a=e.charCodeAt(t);a===34?n+='\\"':a===92?n+="\\\\":a>=32&&a<=126?n+=e[t]:n+=`\\u${a.toString(16).padStart(4,"0")}`}return`${n}"`}function T(e){let n=Object.keys(e??{}).sort((i,r)=>i<r?-1:i>r?1:0);if(n.length===0)return;if(n.length>I)throw m(`${n.length} attributes: at most ${I}`);let t=[];for(let i of n){if(!j.test(i))throw m(`the attribute ${JSON.stringify(i)}: a key is a letter, then letters, digits and _ . -, at most 40`);let r=e[i],s;if(typeof r=="string"){if(new TextEncoder().encode(r).length>S)throw m(`the attribute ${JSON.stringify(i)} is over ${S} bytes`);s=L(r)}else if(typeof r=="number"){if(!Number.isFinite(r))throw m(`the attribute ${JSON.stringify(i)} is no number`);s=String(Object.is(r,-0)?0:r)}else if(typeof r=="boolean")s=r?"true":"false";else throw m(`the attribute ${JSON.stringify(i)}: a value is a text, a number or a boolean`);t.push(`"${i}":${s}`)}let a=`{${t.join(",")}}`;if(a.length>M)throw m(`the attributes are ${a.length} bytes: at most ${M}`);return a}function x(e){let n=/^P(\d+)([DWMY])$/.exec(e??"");if(!n)return null;let t=Number(n[1]);if(!Number.isSafeInteger(t)||t<1)return null;switch(n[2]){case"D":return{count:t,unit:"day",months:t*12/365};case"W":return{count:t,unit:"week",months:t*12/52};case"M":return{count:t,unit:"month",months:t};default:return{count:t,unit:"year",months:t*12}}}function R(e){try{return new Intl.NumberFormat("en",{style:"currency",currency:e}).resolvedOptions().maximumFractionDigits??2}catch{return 2}}function $(e,n,t){let a=e/10**R(n);try{return new Intl.NumberFormat(t,{style:"currency",currency:n}).format(a)}catch{return`${a.toFixed(R(n))} ${n}`}}function X(e,n){try{let t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"});return e.count>1?t.format(e.count):t.formatToParts(1).filter(i=>i.type==="unit").map(i=>i.value).join("").trim()||t.format(1)}catch{return e.count>1?`${e.count} ${e.unit}s`:e.unit}}var K={en:e=>`${e} free`,tr:e=>`${e} \xFCcretsiz`,de:e=>`${e} kostenlos`,es:e=>`${e} gratis`,it:e=>`${e} gratis`,nl:e=>`${e} gratis`,pt:e=>`${e} gr\xE1tis`,sv:e=>`${e} gratis`,da:e=>`${e} gratis`,nb:e=>`${e} gratis`};function B(e,n){let t;try{t=new Intl.NumberFormat(n,{style:"unit",unit:e.unit,unitDisplay:"long"}).format(e.count)}catch{t=`${e.count} ${e.unit}${e.count>1?"s":""}`}let a=K[n.split("-")[0].toLowerCase()];return a?a(t):t}function H(e,n){try{return new Intl.NumberFormat(n,{style:"percent",maximumFractionDigits:0}).format(e)}catch{return`${Math.round(e*100)}%`}}function E(e,n){let t=new Map,a=new Map;for(let r of e){let s=x(r.period);if(!s)continue;let u=r.price.amount/s.months;t.set(r.key,u),a.set(r.price.currency,Math.max(a.get(r.price.currency)??0,u))}let i={};for(let r of e){let s={product_name:r.productName,price:$(r.price.amount,r.price.currency,n)},u=x(r.period);if(u){s.period=X(u,n),s.price_per_month=$(Math.round(t.get(r.key)),r.price.currency,n);let o=a.get(r.price.currency)??0,d=o>0?Math.floor((1-t.get(r.key)/o)*100)/100:0;d>=.01&&(s.savings=H(d,n))}let l=r.intro?.mode==="free_trial"?x(r.intro.duration):null;l&&(s.trial=B(l,n)),r.offer&&(s.offer_price=$(Math.floor((r.price.amount*(100-r.offer.percentOff)+50)/100),r.price.currency,n)),i[r.key]=s}return i}var V={version:"0.63.0"};var C=`palbase-js/${V.version}`;var k=class{placement;source;definition;assets;offerings;offers;shown;deps;exposed=!1;constructor(n,t,a,i,r,s,u={},l=[]){this.placement=n,this.source=t,this.definition=a,this.assets=u,this.offerings=i,this.offers=l,this.shown=r,this.deps=s}packages(n){return E(Y(this.offerings,O(this.definition),n,Z(this.definition,this.offers)),n)}render(n,t){let a=t.locale??globalThis.navigator?.language??this.definition.default_locale,i=t.appearance===void 0?q():void 0,r=this.packages(a),s=F(n,{definition:this.definition,locale:a,appearance:t.appearance??(i?.matches?"dark":"light"),platform:"web",packages:r,eligible:Object.entries(r).filter(([,o])=>o.trial).map(([o])=>o),offers:this.offers.filter(o=>o.web).map(o=>o.key),links:t.links,assets:this.assets},{onPurchase:async o=>{try{let d=await this.deps.checkout({product:o.product,plan:o.plan,successUrl:t.successUrl,cancelUrl:t.cancelUrl,...o.offer!==void 0?{offer:o.offer}:{}});t.onCheckout?t.onCheckout(d,o):globalThis.location.assign(d)}catch(d){if(!t.onError)throw d;t.onError(d,o)}},onClose:t.onClose,onLink:t.onLink,labels:t.labels}),u=o=>s.update({appearance:o.matches?"dark":"light"});i?.addEventListener?.("change",u),!this.exposed&&this.shown&&(this.exposed=!0,this.deps.expose(this));let l=s.destroy.bind(s);return s.destroy=()=>{i?.removeEventListener?.("change",u),l()},s}};function q(){try{return globalThis.matchMedia?.("(prefers-color-scheme: dark)")}catch{return}}function W(e,n){if(!e)return;let t=n.split("-")[0];return e[n]?.name??e[t]?.name??Object.values(e).find(a=>a.name)?.name}function Y(e,n,t,a=new Map){let i=[];for(let r of n){let[s,u]=r.split("."),l=e.products.find(f=>f.key===s),o=l?.channels.web,d=o?.plans.find(f=>f.key===u);if(!l||!o||!d)continue;let p=a.get(r),g=p?.discount?p.discount.percent:p?.trial?100:void 0;i.push({key:r,productName:W(o.locales,t)??l.key,price:{amount:d.price.amount,currency:d.price.currency},period:d.period,intro:d.intro,...g!==void 0?{offer:{percentOff:g}}:{}})}return i}function Z(e,n){let t=new Map;for(let[a,i]of _(e)){let r=n.find(s=>s.key===i);r?.web&&t.set(a,r)}return t}var G={en:{cta:"Continue",terms:"Terms",privacy:"Privacy"},tr:{cta:"Devam et",terms:"Ko\u015Fullar",privacy:"Gizlilik"},de:{cta:"Weiter",terms:"Bedingungen",privacy:"Datenschutz"},es:{cta:"Continuar",terms:"T\xE9rminos",privacy:"Privacidad"},fr:{cta:"Continuer",terms:"Conditions",privacy:"Confidentialit\xE9"},it:{cta:"Continua",terms:"Termini",privacy:"Privacy"},pt:{cta:"Continuar",terms:"Termos",privacy:"Privacidade"},nl:{cta:"Doorgaan",terms:"Voorwaarden",privacy:"Privacy"},ja:{cta:"\u7D9A\u3051\u308B",terms:"\u5229\u7528\u898F\u7D04",privacy:"\u30D7\u30E9\u30A4\u30D0\u30B7\u30FC"}},N=e=>({type:"button",action:{type:e},content:{type:"text",text:{t:e},size:"caption",color:"muted"}});function Q(e){let n=e.products.flatMap(t=>(t.channels.web?.plans??[]).map(a=>({product:t.key,plan:a.key}))).slice(0,6);return n.length===0?null:{schema:2,name:"Default",default_locale:"en",locales:G,theme:{colors:{light:{background:"#FFFFFF",surface:"#F2F2F7",text:"#111114",muted:"#6B6B70",accent:"#111114",on_accent:"#FFFFFF",stroke:"#E5E5EA"},dark:{background:"#000000",surface:"#1C1C1E",text:"#F5F5F7",muted:"#9A9AA0",accent:"#F5F5F7",on_accent:"#000000",stroke:"#2C2C2E"}},typography:{headline:{size:17,weight:600,text_style:"headline"},caption:{size:13,weight:400,text_style:"footnote"}},radii:{card:14},spacing:{sm:8,md:16,lg:24}},root:{type:"stack",spacing:"md",align:"stretch",style:{padding:"lg"},children:[{type:"stack",axis:"horizontal",children:[{type:"spacer"},{type:"button",action:{type:"close"},content:{type:"icon",name:"close",color:"muted",size:22}}]},{type:"spacer"},{type:"stack",spacing:"sm",align:"stretch",children:n.map(({product:t,plan:a})=>({type:"package",product:t,plan:a,style:{padding:"md",corners:"card",background:"surface",border:{width:1,color:"stroke"}},states:{selected:{border:{width:2,color:"accent"}}},children:[{type:"stack",axis:"horizontal",spacing:"sm",children:[{type:"stack",align:"start",spacing:2,children:[{type:"text",text:"{{product_name}}",size:"headline",align:"start"},{type:"text",text:"{{period}}",size:"caption",color:"muted",align:"start"}]},{type:"spacer"},{type:"text",text:"{{price}}",size:"headline"}]}]}))},{type:"purchase_button",style:{padding:"md",corners:"card",background:"accent"},content:{type:"text",text:{t:"cta"},size:"headline",color:"on_accent"}},{type:"stack",axis:"horizontal",spacing:"md",distribution:"center",children:[N("terms"),N("privacy")]}]}}}function h(){try{return globalThis.localStorage}catch{return}}function ee(e){try{let n=h()?.getItem(e);if(!n)return;let t=JSON.parse(n),a=t?.answer;return typeof a!="object"||a===null||typeof a.paywall_id!="string"||typeof a.version!="number"||typeof a.definition!="object"||a.definition===null||typeof a.offerings!="object"||a.definition.schema!==2?void 0:{etag:typeof t.etag=="string"?t.etag:void 0,answer:a}}catch{return}}function P(e,n){try{n?h()?.setItem(e,JSON.stringify(n)):h()?.removeItem(e)}catch{}}var z=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,U;function te(e){let n=`palbase.installation.${e}`;try{let t=h()?.getItem(n);if(t&&/^[A-Za-z0-9._:-]{1,128}$/.test(t))return t;let a=z();if(h()?.setItem(n,a),h()?.getItem(n)===a)return a}catch{}return U??=z(),U}async function ye(e,n,t,a,i={}){let{signal:r,fetch:s}=i,u=T(i.attributes),l=`palbase.paywall.${n}.${t}`,o=te(n),p={checkout:a,expose:async c=>{if(c.shown)try{let v={paywall_id:c.shown.paywallId,version:c.shown.version,...c.shown.variant!==void 0?{variant:c.shown.variant}:{},...c.shown.ruleId!==void 0?{rule_id:c.shown.ruleId}:{}};await e.recordPaywallExposure({path:{placement:t},headers:{"X-Palbase-Installation":o},body:v})}catch{}}},g=async(c,v)=>new k(t,v,c.definition,c.offerings,{paywallId:c.paywall_id,version:c.version,...c.variant!==void 0?{variant:c.variant}:{},...c.rule_id!==void 0?{ruleId:c.rule_id}:{}},p,await D(c.assets??[],{signal:r,...s?{fetch:s}:{}}),c.offers??[]),f=ee(l),y;try{y=await e.getPlacementPaywall({path:{placement:t},query:{channel:"web"},headers:{"X-Palbase-Paywall-Schema":2,"X-Palbase-Installation":o,"X-Platform":"web","X-Palbase-SDK":C,...i.appVersion?{"X-Palbase-Client-Version":i.appVersion}:{},...i.app?{"X-Palbase-App":i.app}:{},...i.locale?{"Accept-Language":i.locale}:{},...u!==void 0?{"X-Palbase-Attributes":u}:{},...f?.etag?{"If-None-Match":f.etag}:{}},signal:r})}catch(c){if(c instanceof w&&c.status===404||c instanceof w&&c.status===400&&c.code.startsWith("invalid_"))return P(l,void 0),A(e,t,p,r);if(f&&!r?.aborted)return g(f.answer,"cache");throw c}return y.status===200?(P(l,{etag:y.headers.get("etag")??void 0,answer:y.data}),g(y.data,"server")):y.status===304&&f?g(f.answer,"server"):(P(l,void 0),A(e,t,p,r))}async function A(e,n,t,a){let i=(await e.getOfferings({query:{channel:"web"},signal:a})).data,r=Q(i);return r?new k(n,"default",r,i,void 0,t):null}export{T as a,x as b,$ as c,X as d,E as e,k as f,Q as g,ye as h};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.62.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.63.0 — Palbase SDK License (see LICENSE) */
2
2
  var d=Object.defineProperty;var e=(c,a)=>{for(var b in a)d(c,b,{get:a[b],enumerable:!0})};export{e as a};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.62.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.63.0 — Palbase SDK License (see LICENSE) */
2
2
  var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};