palbase 0.77.0 → 0.78.1

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 (60) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/ai-sdk/index.js +2 -2
  3. package/dist/backend/engine.js +2 -2
  4. package/dist/backend/env.js +1 -1
  5. package/dist/backend/index.js +3 -3
  6. package/dist/backend/stack.js +1 -1
  7. package/dist/backend/test.js +2 -2
  8. package/dist/chunks/{34HGL5FX.js → 25KG2TVU.js} +1 -1
  9. package/dist/chunks/{GFBWGJW3.js → 2T3EX52E.js} +1 -1
  10. package/dist/chunks/{VOLGPAPR.js → 35KQJQ77.js} +2 -2
  11. package/dist/chunks/{ES24JS2D.js → 3TJFV35H.js} +2 -2
  12. package/dist/chunks/{FN5763FR.js → 3XF644A5.js} +2 -2
  13. package/dist/chunks/426QPZNS.js +13 -0
  14. package/dist/chunks/{U4VX7NKX.js → 4XE4HLPK.js} +2 -2
  15. package/dist/chunks/{WXT24CE5.js → 5KGMQFET.js} +1 -1
  16. package/dist/chunks/6Y4ICGZ7.js +2 -0
  17. package/dist/chunks/{G3PH5T6N.js → EUMY6SCM.js} +1 -1
  18. package/dist/chunks/{IZVBCAKH.js → FCCX2OTM.js} +2 -2
  19. package/dist/chunks/{RQJ4MX2H.js → IO5HB5B6.js} +2 -2
  20. package/dist/chunks/{AUOFL6RB.js → JY7YG3BO.js} +2 -2
  21. package/dist/chunks/{RRS7TQKX.js → L63FWRZX.js} +2 -2
  22. package/dist/chunks/{ONLXIZ6E.js → LONPNPNX.js} +2 -2
  23. package/dist/chunks/{DENZSXKJ.js → LXS7JHPJ.js} +2 -2
  24. package/dist/chunks/{QWXF6KWI.js → QWKOKJKM.js} +1 -1
  25. package/dist/chunks/{7RTPVUIH.js → RB4JQXKZ.js} +2 -2
  26. package/dist/chunks/{BDHVYVWT.js → ROV6TJZK.js} +1 -1
  27. package/dist/chunks/{KLK7HZZ7.js → TFPVJ3C3.js} +3 -3
  28. package/dist/chunks/{JOVXELK5.js → UUDOMSKW.js} +2 -2
  29. package/dist/chunks/{FE7ZBADH.js → VNUCKM7H.js} +1 -1
  30. package/dist/chunks/{ZZNNCI6A.js → WTFMJKDB.js} +2 -2
  31. package/dist/chunks/{F6OGRDZB.js → ZBTOHVML.js} +2 -2
  32. package/dist/chunks/{CYNLRAAW.js → ZIHVYOXE.js} +2 -2
  33. package/dist/cli.js +7 -3
  34. package/dist/cloud/index.js +2 -2
  35. package/dist/refuse/ai-sdk.js +1 -1
  36. package/dist/refuse/ai.js +1 -1
  37. package/dist/refuse/backend.js +1 -1
  38. package/dist/refuse/cloud.js +1 -1
  39. package/dist/refuse/server.js +1 -1
  40. package/dist/server/index.js +2 -2
  41. package/dist/server/testing.js +2 -2
  42. package/dist/web/index.js +2 -2
  43. package/dist/web/message.js +2 -2
  44. package/dist/web/palbe.js +2 -2
  45. package/dist/web/payments-ui.js +2 -2
  46. package/dist/web/paywall.js +2 -2
  47. package/dist/web/push-sw.js +1 -1
  48. package/dist/web/ssr.js +2 -2
  49. package/dist/web/vite.js +2 -2
  50. package/package.json +2 -2
  51. package/types/ai/src/chats.d.ts +7 -0
  52. package/types/backend/src/gateways.d.ts +2 -1
  53. package/types/cloud/src/generated/project.d.ts +1 -1
  54. package/types/internal/src/chat.d.ts +28 -0
  55. package/types/internal/src/modules/ai.d.ts +11 -7
  56. package/types/internal/src/modules/payments.d.ts +366 -24
  57. package/types/web/src/chat.d.ts +20 -0
  58. package/types/web/src/index.d.ts +1 -1
  59. package/dist/chunks/4M4GEXJS.js +0 -13
  60. package/dist/chunks/6WCN7VAZ.js +0 -2
@@ -1,2 +1,2 @@
1
- /*! palbase 0.77.0 — Palbase SDK License (see LICENSE) */
2
- import{b as c,f as u}from"./VOLGPAPR.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
1
+ /*! palbase 0.78.1 — Palbase SDK License (see LICENSE) */
2
+ import{b as c,f as u}from"./35KQJQ77.js";var l={attempts:3,maxWaitSeconds:30},y=new Set([429,502,503,504]);function x(e,t=l){let r=t.sleep??h;return{async send(o){let n=p(o),a=n.body,m=!a||a.kind!=="raw"||u(a.value),f=(n.method==="GET"||n.method==="HEAD"||n.idempotent===!0)&&m;for(let i=1;;i++)try{return await e.send(n)}catch(s){if(!f||i>=t.attempts||!(s instanceof c)||n.signal?.aborted)throw s;let d=b(s,i,t.maxWaitSeconds);if(d===void 0)throw s;await r(d*1e3,n.signal)}}}}function p(e){return e.idempotent?Object.entries(e.headers??{}).some(([r,o])=>r.toLowerCase()==="idempotency-key"&&o!==void 0&&o!==null&&o!=="")?e:{...e,headers:{...e.headers,"Idempotency-Key":w()}}:e}function b(e,t,r){return y.has(e.status)||e.code==="network_error"?e.retryAfter!==void 0?e.retryAfter<=r?e.retryAfter:void 0:Math.min(.5*2**(t-1),r)*(.8+Math.random()*.4):void 0}function h(e,t){return new Promise((r,o)=>{if(t?.aborted)return o(t.reason);let n=()=>{clearTimeout(a),o(t?.reason)},a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function w(){if(typeof crypto.randomUUID=="function")return crypto.randomUUID();let e=crypto.getRandomValues(new Uint8Array(16));e[6]=e[6]&15|64,e[8]=e[8]&63|128;let t=[...e].map(r=>r.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}export{l as a,x as b,b as c,w as d};
@@ -0,0 +1,13 @@
1
+ /*! palbase 0.78.1 — Palbase SDK License (see LICENSE) */
2
+ import{b as D,d as I,e as R}from"./6Y4ICGZ7.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"./25KG2TVU.js";import{d as G}from"./3XF644A5.js";import{a as E,b as Q,c as T,e as q}from"./35KQJQ77.js";var f=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 f||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function K(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??Qe(e,"request_id"),data:S(e,"data"),cause:t};if(t.code==="network_error")return new f("network",n);if(t.status===401&&t.code==="insufficient_user_authentication")return new f("stepUpRequired",n);if(t.status===401&&t.code==="app_attest_required")return new f("attestationRequired",n);if(t.status===401)return new f("unauthorized",n);if(t.status===429)return new f("rateLimited",{...n,retryAfter:ze(e)??t.retryAfter});let s=Ue(e);return t.status===400&&s?new f("validation",{...n,fields:s}):new f("server",n)}function P(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 Ue(t){let e=S(S(t,"data"),"fields");if(oe(e))return e;let n=S(t,"fields");return oe(n)?n:void 0}function ze(t){return ie(t,"retry_after")??ie(S(t,"data"),"retryAfter")}function S(t,e){if(typeof t=="object"&&t!==null)return t[e]}function ie(t,e){let n=S(t,e);return typeof n=="number"?n:void 0}function Qe(t,e){let n=S(t,e);return typeof n=="string"?n:void 0}var Ye=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ze=Object.freeze(["adoptSession","ai","analytics","anonymousTelemetry","appContext","appEvent","appVersion","auth","callOnSignOut","calls","cancelCallOnSignOut","captureOnce","chatToolCall","chatWorkspaceFile","configuration","consent","currentSession","defaults","flags","installation","keychainItem","module","moduleDirectory","notify","offerTaker","onAppEvent","onSessionChange","onSignOut","preferences","realtime","scope","send","setLanguage","setPreferredLanguages","signedInUserNow","socket","storage","storedUserId","telemetry","transport","transportFor","upload","version","watchSessions","palbe","data","stores","iap","payments","commerce","campaigns","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),Xe=new Set(Ze),et=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function O(t){return t==="then"||t==="toJSON"||et.has(t)}function de(t){return t==="call"||t==="join"||O(t)}function le(t){return typeof t=="string"&&Ye.test(t)&&!Xe.has(t)&&!O(t)}function ce(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function ue(t){q(t)}function pe(t){return q(t).origin}var $=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;execution={target:null,generation:0,workspaceSeq:0,machineId:null,machineStatus:null,failoverAt:null,lastHandoff:null,compactions:[],offloads:[]};handoffGens=new Set;compactionSeqs=new Set;offloadKeys=new Set;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 c=(a?.parts??[]).map(h=>D(h)).filter(h=>h!==void 0);if(this.olderCursor=a?.nextCursor,this.olderLeft=typeof a?.nextCursor=="string"&&a.nextCursor!=="",this.before(c),r&&this.replays&&this.next===0&&this.pagedFrom!==void 0?(this.racing=!0,this.racedPages=c):this.racing&&(this.racedPages=c.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 p=w(i);p<=0||(this.paged.add(p),(this.pagedFrom===void 0||p<this.pagedFrom)&&(this.pagedFrom=p),(this.pagedTo===void 0||p>this.pagedTo)&&(this.pagedTo=p))}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,p]of n.messages){let y=this.told.get(i)??[],b=p;if(y.length>0)for(let C of y)b=ve(b,C);else b=this.messages.get(i)??p;r.set(i,b);let _=[...n.told.get(i)??[],...y];_.length>0&&this.told.set(i,_)}for(let[i,p]of this.messages)r.has(i)||r.set(i,p);this.messages.clear();for(let[i,p]of r)this.messages.set(i,p);let o=new Map;for(let[i,p]of n.responses){let y=this.responses.get(i);o.set(i,y?nt(p,y):p)}for(let[i,p]of this.responses)o.has(i)||o.set(i,p);this.responses.clear();for(let[i,p]of o)this.responses.set(i,p);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],c=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(L(i.event)))&&!(i.type==="handoff"&&n.handoffGens.has(i.event.generation))&&!(i.type==="compaction"&&i.event.seq>0&&n.compactionSeqs.has(i.event.seq))){if(i.type==="message"&&i.began&&i.turn!==null){let p=this.responses.get(i.turn);c.has(i.turn)?a.push({...i,began:!1,at:i.arrived}):a.push({...i,at:p&&p.at<i.arrived?p.at-.5:i.arrived});continue}a.push(i)}a.sort((i,p)=>i.at-p.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));for(let i of n.handoffGens)this.handoffGens.add(i);for(let i of n.compactionSeqs)this.compactionSeqs.add(i);for(let i of n.offloadKeys)this.offloadKeys.add(i);n.execution.generation>this.execution.generation&&(this.execution={...this.execution,target:n.execution.target,generation:n.execution.generation,workspaceSeq:n.execution.workspaceSeq,lastHandoff:n.execution.lastHandoff}),this.execution.machineStatus===null&&n.execution.machineStatus!==null&&(this.execution={...this.execution,machineId:n.execution.machineId,machineStatus:n.execution.machineStatus,failoverAt:n.execution.failoverAt});let l=[];for(let i of a)i.type==="compaction"&&l.push(i.event);let u=[...n.execution.offloads,...this.execution.offloads.filter(i=>!n.offloadKeys.has(me(i)))];this.execution={...this.execution,compactions:l,offloads:u},this.turn??=n.turn;let g=new Map([...n.calls,...this.calls]);this.calls.clear();for(let[i,p]of g)this.calls.set(i,p);for(let[i,p]of n.history)this.history.has(i)||this.history.set(i,p);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=D(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=w(e);n>0&&this.pagedTo!==void 0&&n>this.pagedTo?this.sortHeld():(clearTimeout(this.heldTimer),this.heldTimer=ge(setTimeout(()=>this.quiet(),fe)));return}this.takeNow(e)}}quiet(){let e=this.held.map(w).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<tt?this.heldTimer=ge(setTimeout(()=>this.quiet(),fe)):this.sortHeld()}takeNow(e){let n=w(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(w(a))),d=o<0?-1:n.findIndex(a=>w(a)===w(e[o]));if(d>=0){let a=0;for(;a<o&&a<d&&he(e[o-1-a],n[d-1-a]);)a++;let c=0;for(;o+c<e.length&&d+c<n.length&&he(e[o+c],n[d+c]);)c++;s=e.slice(0,o-a),r=e.slice(o+c)}else{let a=e.find(h=>w(h)>0),c=a!==void 0&&this.pagedFrom!==void 0&&w(a)<this.pagedFrom;for(let h of e){let l=w(h);l>0&&!(this.pagedFrom!==void 0&&l<this.pagedFrom)&&(c=!1),(c?s:r).push(h)}}if(s.length>0){let a=Math.min(...s.map(w).filter(c=>c>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}),A(n.times,e.status,e.at),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+I(n.text),loose:n.text==="",cutAt:n.cut,thinking:{stepId:null,runId:e.run_id,text:"",startedAt:e.at??null,endedAt:e.at??null,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,...Ee(r.thinking,e.at??null,e.at??null)}:n.marks.set(s,{type:"thinking",text_offset:n.from+I(n.text),loose:n.text==="",cutAt:n.cut,thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,startedAt:e.at??null,endedAt:e.at??null,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=L(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);ot(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,R(n.text,e.offset-n.from)),n.cut=n.cut===null?e.offset:Math.min(n.cut,e.offset);break}case"tool":{let n=this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id);n.marks.set(`tool:${e.call_id}`,e),we(n,`tool:${e.call_id}`,e.status,e.at),this.calls.set(e.call_id,e);break}case"agent":{let n=this.response(e.parent_response_id),s=e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`;if(n.marks.set(s,e),we(n,s,e.status,e.at),!e.response_id)break;let r=this.response(e.response_id);r.runId=e.run_id,r.agent=e.name,r.named=!0,r.parentId??=e.parent_response_id,A(r.times,e.status,e.at);break}case"session.handed_off":{if(this.handoffGens.has(e.generation))return!1;this.handoffGens.add(e.generation),e.generation>=this.execution.generation&&(this.execution={...this.execution,target:e.to_target,generation:e.generation,workspaceSeq:e.workspace_seq,machineId:e.to_target.compute.machine_id??null,failoverAt:null,lastHandoff:e}),this.order.push({type:"handoff",event:e,at:this.at});break}case"session.machine_status":{this.execution={...this.execution,machineId:e.machine_id||this.execution.machineId,machineStatus:e.status,failoverAt:e.failover_at??null};break}case"context.offloaded":{let n=me(e);if(this.offloadKeys.has(n))return!1;this.offloadKeys.add(n),this.execution={...this.execution,offloads:[...this.execution.offloads,e]};break}case"context.compacted":{if(e.seq>0){if(this.compactionSeqs.has(e.seq))return!1;this.compactionSeqs.add(e.seq)}this.execution={...this.execution,compactions:[...this.execution.compactions,e]},this.order.push({type:"compaction",event:e,at:this.at});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=rt(e),s=this.messages.get(n);this.messages.set(n,ve(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(([c,h])=>c!==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(c=>c.type==="response"&&c.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,markTimes:new Map,times:{},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=l=>e!==void 0&&l.startedBy===e,s=new Map;for(let l of this.responses.values()){let u=l.parentId!==null?this.responses.get(l.parentId)??l:l;s.set(l.id,it(l,u.startedBy??null,n(u),l.goal??u.goal))}let r=new Map([...this.messages].map(([l,u])=>[l,e!==void 0&&u.author===e?{...u,mine:!0}:u])),o=[...this.history.entries()].sort(([l],[u])=>l-u).flatMap(([l,u])=>u.map((g,i)=>dt(g,`${l}:${i}`,e))),d=[...o];for(let l of this.order)l.type==="goal"?d.push({type:"goal",goal:l.event}):l.type==="voice"?d.push({type:"voice",voice:l.event}):l.type==="handoff"?d.push({type:"handoff",handoff:l.event}):l.type==="compaction"?d.push({type:"compaction",compaction:l.event}):l.type==="message"?d.push({type:"message",message:r.get(l.key)}):this.responses.get(l.key).parentId===null&&d.push({type:"response",response:s.get(l.key)});let a=o.flatMap(l=>l.type==="message"?[l.message]:[]),c=o.flatMap(l=>l.type==="response"?[l.response]:[]),h=[...this.calls.values()].filter(l=>s.get(l.response_id)?.mine===!0);return{items:d,messages:[...a,...r.values()],responses:[...c,...s.values()],turn:this.turn,waiting:{approvals:h.filter(l=>l.status==="awaiting_approval"),outputs:h.filter(l=>l.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?st(this.voice,e):null,execution:this.execution}}},fe=150,tt=2e3;function he(t,e){let n=w(t);return n>0||w(e)>0?n===w(e):JSON.stringify({...t,at:void 0})===JSON.stringify({...e,at:void 0})}function w(t){let e=t.seq;return typeof e=="number"&&e>0?e:0}function ge(t){return t.unref?.(),t}function L(t){return`${t.voice_id}\0${t.status}`}function me(t){return t.seq>0?`seq:${t.seq}`:`call:${t.call_id}:${t.ref??""}`}function ye(t,e,n){return n.add(L(e)),(e.status==="closed"?t===null||t.voice_id===e.voice_id:!n.has(`${e.voice_id}\0closed`))?e:t}function ve(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?xe(e.attachments):t?.attachments??[]}}function nt(t,e){let n={...t,marks:new Map(t.marks),times:ke(t.times,e.times),markTimes:new Map(t.markTimes)};for(let[r,o]of e.markTimes)n.markTimes.set(r,ke(n.markTimes.get(r)??{},o));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,R(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=I(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,...Ee(d.thinking,o.thinking.startedAt,o.thinking.endedAt)}});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 st(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 xe(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 rt(t){return`${t.author??""}\0${t.client_id}`}function ot(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,R(t.text,e-t.from))+n}function it(t,e,n,s){let r=[...t.marks].map(([l,u],g)=>({key:l,m:u,i:g,at:R(t.text,Math.max(0,(Number(u.text_offset)||0)-t.from))}));r.sort((l,u)=>l.at-u.at||l.i-u.i);let o=[],d=[],a=0;for(let{key:l,m:u,at:g}of r)if(g>a&&o.push({type:"text",text:t.text.slice(a,g)}),a=Math.max(a,g),u.type==="thinking")o.push({type:"thinking",thinking:u.thinking}),d.push(u.thinking);else{let i={...t.markTimes.get(l)};o.push(u.type==="tool"?{type:"tool",tool:u,times:i}:{type:"agent",agent:u,times:i})}a<t.text.length&&o.push({type:"text",text:t.text.slice(a)});let c=Object.values(t.times).sort(),h=at.map(l=>t.times[l]).find(l=>l!==void 0)??null;return{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,times:{...t.times},startedAt:c[0]??null,endedAt:h}}var at=["completed","failed","canceled","timed_out","budget_exceeded","denied","failed_with_uncertain_side_effect"];function A(t,e,n){if(typeof n!="string"||n==="")return;let s=t[e];(s===void 0||n<s)&&(t[e]=n)}function we(t,e,n,s){if(typeof s!="string"||s==="")return;let r=t.markTimes.get(e);r||t.markTimes.set(e,r={}),A(r,n,s)}function ke(t,e){let n={...t};for(let[s,r]of Object.entries(e))A(n,s,r);return n}function Ee(t,e,n){return{startedAt:t.startedAt===null||e!==null&&e<t.startedAt?e??t.startedAt:t.startedAt,endedAt:t.endedAt===null||n!==null&&n>t.endedAt?n??t.endedAt:t.endedAt}}function dt(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:xe(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,times:{},startedAt:null,endedAt:null}}}var be=[["ApiKeyAuth","userJWT"]];function _e(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/${T("ListChatParts","chat_id",e)}/parts`,auth:be,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/${T("GetChatToolCall","chat_id",e)}/tool-calls/${T("GetChatToolCall","call_id",n)}`,auth:be,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}}}}var M=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},Se=new WeakMap;async function Te(t,e,n,s={},r=()=>{},o){let{pattern:d,events:a,messages:c,durable:h,chat:l}=lt(e),u=ct(d,n),g=Se.get(t);g||Se.set(t,g=new Map);let i=g,p=i.get(u)??{count:0};i.set(u,p),p.count++;let y=t.channel(u,h&&s.history!==!1?{after:0}:{});if(l&&!p.chat){let m=n.chatId,x=new $(r,o,typeof m=="string"&&m!==""?m:void 0,h&&s.history!==!1);p.chat=x,p.unchat=y.on("broadcast",v=>{v.event==="chat"&&x.takePayload(v.payload)})}let b=()=>{--p.count>0||(i.delete(u),p.unchat?.(),p.chat?.end(),y.leave())};try{await y.join()}catch{let m=y.state==="refused"?Ce(y.refusal,"unavailable"):"socket closed";throw b(),new M(`gateway ${JSON.stringify(u)} was not joined: ${m}`,m)}let _=!1,C=new Set,V=()=>{if(!_){_=!0,Ve();for(let m of[...C])m();b()}},Ve=y.onClosed(V),U=m=>{if(_)return()=>{};let x=y.on("broadcast",k=>{typeof k.event=="string"&&a.has(k.event)&&m(k.event,E(k.payload))}),v=()=>{C.delete(v),x()};return C.add(v),v},z={topic:u,get seq(){return y.logSeq},on(m,x){if(typeof m=="function")return U((v,k)=>m({event:v,payload:k}));if(!a.has(m))throw new TypeError(`gateway ${JSON.stringify(d)} declares no event ${JSON.stringify(String(m))}`);if(typeof x!="function")throw new TypeError(`gateway ${JSON.stringify(d)}: on(${JSON.stringify(m)}, \u2026) takes the function the event is handed to`);return U((v,k)=>{v===m&&x(k)})},off(m){C.has(m)&&m()},async send(m,x){if(!c.has(m))throw new TypeError(`gateway ${JSON.stringify(d)} declares no message ${JSON.stringify(String(m))}`);let v=_?{status:"error",response:{reason:"not joined"}}:await y.push("broadcast",{type:"broadcast",event:m,payload:x});if(v.status==="ok")return E(v.response.reply);let k=Ce(v.response,"unavailable");throw new M(`gateway ${JSON.stringify(u)} did not take ${JSON.stringify(m)}: ${k}`,k)},leave:V};return l&&Object.defineProperty(z,"chat",{value:p.chat,enumerable:!0}),z}function lt(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 ct(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 Ce(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var ut=3600*1e3,j=new Map;function pt(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=j.get(s);if(!n&&r&&Date.now()-r.at<ut)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(c){throw new f("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:c})}try{return await re(a,e.signer,e.projectId,d)}catch(c){throw new f("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:c})}})();return j.set(s,{list:o,at:Date.now()}),o.catch(()=>{j.get(s)?.list===o&&j.delete(s)}),o}async function Re(t,e,n,s,r,o){let a=(await pt(t,e,o)).keys[0];return X(a.kid,a.key,Z(e.projectId,n,s,r))}function B(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 Ie(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 f("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 f("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:d})}})}function Pe(t){return t instanceof f&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var F=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
3
+ `);let n=[],s=this.pending.indexOf(`
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
+ `)}),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(`
6
+ `)}return n}};async function*Oe(t,e){let n=t.getReader(),s=new TextDecoder,r=new F;try{for(;;){let{done:o,value:d}=await n.read();if(o)break;for(let a of r.consume(s.decode(d,{stream:!0}))){if(a.event==="error")throw new f("network",{code:"stream_failed",message:`stream failed: ${a.payload}`});let c;try{c=JSON.parse(a.payload)}catch{throw new f("decode",{code:"invalid_frame",message:`stream frame is not valid JSON: ${a.payload.slice(0,120)}`})}yield E(c)}}}finally{e.abort();try{await n.cancel()}catch{}}}var ft={},Ae=new WeakMap;function en(t,e,n,s,r,o=()=>{}){Ae.set(t,{project:e,machine:n,storage:s,socket:r,me:o})}var Me=new Map,$e=new WeakMap;function tn(t,e,n,s,r,o){if(!le(e))throw new f("validation",{code:"reserved_namespace",message:`Cannot register backend ${JSON.stringify(String(e))}: a backend's name is an identifier the client does not keep.`});let d=pe(t);if(!ce(n))throw new TypeError(`${JSON.stringify(String(n))} is not a machine's name: a lowercase letter, then lowercase letters, digits and -`);ue(s),Ge(r);for(let a of Object.keys(r))if(de(a))throw je(a);if(o!==void 0)vt(o);else if(qe(r))throw new f("validation",{code:"invalid_namespace_tree",message:`Backend ${e}: its routes carry encrypted fields, and its module holds no project id and signing key to seal them with \u2014 generate it again with palbase apps:sync`});(Me.get(e)??ht(e)).set(d,{machine:n,url:s,tree:r,...o?{transit:{...o}}:{}})}function ht(t){let e=new Map;return Me.set(t,e),Object.defineProperty(ft,t,{configurable:!0,get(){return gt(this,t,e)}}),e}function gt(t,e,n){let s=Ae.get(t);if(!s)return;let r=n.get(s.project);if(!r)throw new TypeError(`pb.${e} is the backend of ${[...n.keys()].join(" and ")}: this client is ${s.project}'s, and its user's session never goes to another project's machine`);let o=$e.get(t);o||$e.set(t,o=new Map);let d=o.get(e);if(d?.registration===r)return d.ns;let a={machine:()=>s.machine(r.url),storage:s.storage,name:r.machine,...r.transit?{transit:{project:s.storage,config:r.transit}}:{}},c=Object.assign({call:(h,l,u)=>_t(a.machine,h,l,u),join:(h,l,u)=>Te(s.socket,h,l,u,s.me,_e(s.storage))},Ne(r.tree,a));return o.set(e,{registration:r,ns:c}),c}function je(t){return new f("validation",{code:"reserved_namespace",message:`Cannot register endpoint namespace ${JSON.stringify(t)}: the name is reserved.`})}function J(t){return typeof t.path=="string"&&typeof t.method=="string"}function mt(t,e){if(t.pathParams!==void 0){if(!Array.isArray(t.pathParams)||!t.pathParams.every(n=>typeof n=="string"))throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams must be an array of strings.`});for(let n of t.pathParams)if(!t.path.includes(`{${n}}`))throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams entry '${n}' has no '{${n}}' placeholder in the path.`})}if(t.sse!==void 0&&typeof t.sse!="boolean")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': sse must be a boolean.`});if(t.idempotent!==void 0&&typeof t.idempotent!="boolean")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': idempotent must be a boolean.`});if(t.upload!==void 0&&typeof t.upload!="boolean")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': upload must be a boolean.`});if(t.upload===!0&&(t.method!=="POST"||t.sse===!0))throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an upload endpoint is a POST, and no stream.`});if(t.sse===!0&&t.input==="query")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an sse endpoint cannot take query input.`});if(t.input!==void 0&&t.input!=="body"&&t.input!=="query"&&t.input!=="none")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': input must be 'body', 'query' or 'none'.`});if(t.encryption!==void 0&&yt(t,e),t.errors!==void 0){for(let[n,s]of Object.entries(t.errors))if(typeof s!="function")throw new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': errors['${n}'] must be a function.`})}}function yt(t,e){let n=t.encryption,s=r=>new f("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': encryption ${r}.`});if(typeof n!="object"||n===null)throw s("is { request, response }");for(let[r,o]of[["request",["/body/","/query/"]],["response",["/response"]]]){let d=n[r];if(d!==void 0&&(!Array.isArray(d)||!d.every(a=>typeof a=="string"&&o.some(c=>a===c||a.startsWith(c.endsWith("/")?c:`${c}/`)))))throw s(`${r} is a list of places under ${o.join(" or ")}`)}if(t.upload===!0)throw s("is no upload\u2019s: storage seals nothing");if(t.sse===!0&&(n.response?.length??0)>0)throw s("of a streamed answer is none")}function qe(t){return J(t)?t.encryption!==void 0:Object.values(t).some(e=>qe(e))}function vt(t){if(typeof t!="object"||t===null||typeof t.projectId!="string"||!/^[0-9a-f-]{36}$/.test(t.projectId)||typeof t.signer!="string"||!/^[A-Za-z0-9_-]{43}$/.test(t.signer))throw new f("validation",{code:"invalid_namespace_tree",message:"The backend's encryption is { projectId, signer }: the project's id and its Ed25519 signing key, base64url"})}function Ge(t){if(typeof t!="object"||t===null)throw new f("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});let e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null)throw new f("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});for(let[n,s]of Object.entries(t)){if(O(n))throw je(n);typeof s=="object"&&s!==null&&J(s)?(s.method=s.method.toUpperCase(),mt(s,s.path)):Ge(s)}}function Ne(t,e){if(J(t))return t.upload===!0?async(...s)=>xt(e,t,s):async(...s)=>Le(e.machine(),t,s,e.transit);let n={};for(let[s,r]of Object.entries(t))n[s]=Ne(r,e);return n}function H(t){if(t==null)return"";let e=Object.entries(t).filter(([,s])=>s!=null).sort(([s],[r])=>s<r?-1:s>r?1:0);return e.length===0?"":`?${e.map(([s,r])=>{if(typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")throw new f("validation",{code:"invalid_query_value",message:`Query parameter '${s}' must be a string, number, or boolean.`});return`${encodeURIComponent(s)}=${encodeURIComponent(String(r))}`}).join("&")}`}function De(t,e,n){try{return T(t.path,e,n)}catch(s){if(!P(s)||s.code!=="invalid_path_parameter")throw s;let r=String(n);throw new f("validation",{code:"invalid_path_parameter",message:`${t.path}: ${e} cannot be ${r===""?"empty":JSON.stringify(r)}`})}}function Ke(t,e){let n=t.pathParams??[],s=t.path;for(let r=0;r<n.length;r++){let o=e[r];if(typeof o!="string"&&typeof o!="number")throw new f("validation",{code:"missing_path_param",message:`${t.path}: path parameter '${n[r]}' must be a string or number`});s=s.replace(`{${n[r]}}`,De(t,`path parameter '${n[r]}'`,o))}return s}var wt=new Set(["POST","PUT","PATCH","DELETE"]);async function Le(t,e,n,s){let r=e.pathParams??[],o=Ke(e,n),d=o;if(e.input==="none"&&n.length>r.length+1)throw new f("validation",{code:"unexpected_argument",message:`${e.path}: endpoint takes no input \u2014 pass only path params and options`});let a=e.input==="none"?void 0:n[r.length],c=e.input==="none"?r.length:r.length+1,h=n[c],l;if(e.input==="query")d+=H(a);else if(e.input!=="none")if(e.method==="GET"){if(a!==void 0)throw new f("validation",{code:"unsupported_get_input",message:`${e.path}: GET endpoints take no body input`})}else l=a;let u={...h?.headers};if(wt.has(e.method)&&!Object.keys(u).some(g=>g.toLowerCase()==="idempotency-key")&&(u["Idempotency-Key"]=G()),e.encryption!==void 0){if(!s)throw new f("validation",{code:"encryption_unconfigured",message:`${e.method} ${e.path}: the route carries encrypted fields, and this backend's module holds no key to seal them with`});return kt(t,e,o,a,l,u,h?.signal,r.map((g,i)=>String(n[i])),s)}try{return e.sse===!0?await We(t,e,d,l,u,h?.signal):await Je(t,e,d,l,u,h?.signal)}catch(g){throw W(e,g)}}async function kt(t,e,n,s,r,o,d,a,c){let h=e.encryption;for(let l=0;;l++){let u=await Re(c.project,c.config,e.method,e.path,a,l>0);try{let g=e.input==="query"?n+H(await B(u,s,"/query",h.request)):n,i=await B(u,r,"/body",h.request),p={...o,[Y]:u.header};return e.sse===!0?await We(t,e,g,i,p,d):E(await Ie(u,await Je(t,e,g,i,p,d),h.response,`${e.method} ${e.path}`))}catch(g){if(l===0&&Pe(g))continue;throw W(e,g)}}}function W(t,e){return t.errors&&ae(e)&&Object.hasOwn(t.errors,e.code)?t.errors[e.code](e):e}var bt=[["ApiKeyAuth","userJWT"],["ApiKeyAuth"]];async function xt(t,e,n){let s=e.pathParams??[],r=Ke(e,n),o=e.input==="none"?s.length:s.length+1;if(n.length>o+2)throw new f("validation",{code:"unexpected_argument",message:`${e.path}: an upload takes its path params, ${e.input==="none"?"":"its input, "}the file and options`});let d=e.input==="none"?void 0:n[s.length],a=n[o],c=n[o+1];if(!(a instanceof Blob))throw new f("validation",{code:"invalid_file",message:`${e.path}: the file is a Blob (a File is one)`});let h=`/storage/upload/${t.name}/${De(e,"the route",r.slice(1))}`;e.input==="query"&&(h+=H(d));let l=Et(e.input==="query"?void 0:d,a),u=l.body.size,g=0,i=p=>{g=p;try{c?.onProgress?.({loaded:p,total:u})}catch{}};c?.onProgress&&i(0);try{let p;try{let y={op:`Upload ${e.path}`,method:"POST",path:h,auth:bt,answers:Be,body:{kind:"raw",contentType:l.type,value:l.body},signal:c?.signal,...c?.onProgress?{onUploadProgress:b=>i(b)}:{}};p=(await t.storage.send(y)).data}catch(y){throw P(y)?K(y):y}return c?.onProgress&&g<u&&i(u),await He(e,p,c?.signal)}catch(p){throw W(e,p)}}function Et(t,e){let n=`Palbase-${G()}`,s=a=>a.replaceAll('"',"_").replace(/[\r\n]/g,""),r=typeof e.name=="string"?e.name:"blob",o=(a,c)=>`--${n}\r
7
+ Content-Disposition: form-data; ${a}\r
8
+ Content-Type: ${c}\r
9
+ \r
10
+ `,d=[];return t!==void 0&&d.push(o('name="body"',"application/json"),JSON.stringify(t),`\r
11
+ `),d.push(o(`name="file"; filename="${s(r)}"`,s(e.type)||"application/octet-stream"),e,`\r
12
+ --${n}--\r
13
+ `),{body:new Blob(d),type:`multipart/form-data; boundary=${n}`}}async function _t(t,e,n,s){if(typeof e!="string"||e===""||e==="/")throw new f("validation",{code:"invalid_endpoint_name",message:'Endpoint name must be a non-empty path like "todos/create"'});let r=e.startsWith("/")?e:`/${e}`;return Le(t(),{method:"POST",path:r},[n,s])}var Be=Object.fromEntries(Array.from({length:100},(t,e)=>[200+e,"raw"])),St=[["userJWT"],[]];async function Fe(t,e,n,s,r,o){let d={op:`${e.method} ${e.path}`,method:e.method,path:n,auth:St,answers:Be,headers:r,...s===void 0?{}:{body:{kind:"json",contentType:"application/json",value:s}},idempotent:e.idempotent===!0,signal:o};try{return(await t.send(d)).data}catch(a){throw P(a)?K(a):a}}async function Je(t,e,n,s,r,o){return He(e,await Fe(t,e,n,s,r,o),o)}async function He(t,e,n){let s=e.headers.get("x-request-id")??void 0,r;try{r=await e.text()}catch(o){throw n?.aborted?o:new f("network",{code:"network_error",message:`${t.method} ${t.path}: the answer did not arrive whole`,status:e.status,requestId:s,cause:o})}if(r!=="")try{return E(JSON.parse(r))}catch(o){throw new f("decode",{code:"invalid_json",message:`${t.method} ${t.path}: the answer is not JSON`,status:e.status,requestId:s,cause:o})}}async function We(t,e,n,s,r,o){let d=new AbortController;o&&(o.aborted?d.abort():o.addEventListener("abort",()=>d.abort(),{once:!0}));let a=await Fe(t,e,n,s,{accept:"text/event-stream",...r},d.signal);if(!a.body)throw new f("network",{code:"empty_stream",message:"the server answered a streaming route with no body",status:a.status});return Oe(a.body,d)}export{f as a,ae as b,Ze as c,le as d,_e as e,M as f,ft as g,en as h,tn as i};
@@ -1,5 +1,5 @@
1
- /*! palbase 0.77.0 — Palbase SDK License (see LICENSE) */
2
- import{b as xt,c as Ke,d as Mt}from"./CYNLRAAW.js";import{e as Ct}from"./7RTPVUIH.js";import{e as _t,g as Rt,h as Pt}from"./4M4GEXJS.js";import{c as je}from"./6WCN7VAZ.js";import{h as Tt}from"./DENZSXKJ.js";import{a as kt}from"./ZZNNCI6A.js";import{r as wt,t as bt,u as St}from"./G3PH5T6N.js";import{a as Ue,b as Z,c as W,e as ft,f as gt,g as G,h as mt,i as yt,l as qe,m as H}from"./ES24JS2D.js";import{a as vt,b as ee}from"./FN5763FR.js";import{b,d as $}from"./VOLGPAPR.js";function Ms(r){let e=r,t=e?.body,s=t&&typeof t=="object"?t.reason:void 0;return s==="user_deleted"?"userDeleted":s==="user_banned"?"userBanned":e?.code==="session_expired"||e?.code==="token_expired"?"expired":"revoked"}var P=class extends Error{code="session_changed";constructor(e){super(e),this.name="SessionChangedError"}};function It(){let r=null;return{load:()=>r,save:e=>{r=e},clear:()=>{r=null},shared:!1}}function Ot(r){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let i=s()?.getItem(r);return i==null?t?null:e:JSON.parse(i)}catch{return e}},save(i){e=i;try{let n=s();if(!n)throw new Error("no storage");n.setItem(r,JSON.stringify(i)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(r)}catch{}},watch(i){let n=globalThis;if(typeof n.addEventListener!="function")return()=>{};let a=o=>{(o.key===r||o.key===null)&&i()};return n.addEventListener("storage",a),()=>n.removeEventListener?.("storage",a)}}}function At(r){try{let e=r.split(".")[1]??"",t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),s=JSON.parse(t);return typeof s=="object"&&s!==null?s:{}}catch{return{}}}function Fe(r){let{sub:e}=At(r);return typeof e=="string"?e:""}function Is(r,e){let{iat:t,exp:s}=At(r);return typeof t!="number"||typeof s!="number"||!(s>t)?e:Math.min(e,(s-t)*1e3/2)}var Os=6e4,As=15e3;function Es(r,e,t){let s=r?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var ae=class{current=null;loaded;inflight=null;endReason=null;listeners=new Set;store;refresher;isRejected;now;lockName;refreshTimeoutMs;mode;constructor(e,t,s,i={}){this.store=e,this.refresher=t,this.isRejected=s,this.now=i.now??Date.now,this.lockName=i.lockName??"palbase.session.refresh",this.refreshTimeoutMs=i.refreshTimeoutMs??As,this.mode=i.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(n=>{this.current=n}),e.watch?.(()=>{this.reconcile()})}async session(){return await this.loaded,this.current}snapshot(){return this.current}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async set(e,t,s){await this.loaded;let i=t==="TOKEN_REFRESHED"?this.current:null,n={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??i?.userId??Fe(e.access_token),user:s??i?.user};return this.current=n,await this.store.save(n),this.emit(t,n),n}async setUser(e,t){await this.loaded,!(!this.current||!t||this.current.userId!==t.userId)&&(this.current={...this.current,user:e},await this.store.save(this.current),this.emit("USER_UPDATED",this.current))}async clear(e,t){await this.loaded;let s=this.current;this.current=null,this.inflight=null;let i=await this.store.load();(!i||!s||i.userId===s.userId)&&await this.store.clear(),s&&(e==="SESSION_EXPIRED"&&(this.endReason=t??"revoked"),this.emit(e,null))}async accessToken(){await this.loaded;let e=this.current;if(!e)return;let t=e.expiresAt-this.now();if(t>Is(e.accessToken,Os))return e.accessToken;if(this.mode==="never")return t>0?e.accessToken:void 0;if(t>0&&this.mode==="behind")return this.refresh().catch(()=>{}),e.accessToken;if(t>0)try{return(await this.refresh()).accessToken}catch(s){if(this.current===e)return e.accessToken;throw s}return(await this.refresh()).accessToken}refresh(){if(this.mode==="never")return Promise.reject(new Error("this client does not renew its session (refresh: 'never'): where the session cannot be written back, the request's middleware renews it"));if(this.inflight)return this.inflight;let e=Es(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new P("no session to refresh");let s=await this.adoptStored(t);if(s)return s;try{let i=await this.withTimeout(this.refresher(t.refreshToken));if(this.current?.refreshToken!==t.refreshToken)throw new P("the session changed while it was refreshed");return await this.set(i,"TOKEN_REFRESHED")}catch(i){throw this.isRejected(i)&&this.current?.refreshToken===t.refreshToken&&await this.clear("SESSION_EXPIRED",Ms(i)),i}});return this.inflight=e,e.finally(()=>{this.inflight===e&&(this.inflight=null)}).catch(()=>{}),e}async adoptStored(e){let t=await this.store.load();if(!t)throw this.current=null,this.emit("SIGNED_OUT",null),new P("signed out in another tab");if(t.userId!==e.userId)throw this.current=t,this.emit("SIGNED_OUT",null),this.emit("SIGNED_IN",t),new P("another user signed in in another tab");if(t.refreshToken!==e.refreshToken&&t.expiresAt>=e.expiresAt)return this.current=t,this.emit("TOKEN_REFRESHED",t),t}async reconcile(){await this.loaded;let e=this.current,t=await this.store.load();if(!e){t&&(this.current=t,this.emit("SIGNED_IN",t));return}await this.adoptStored(e).catch(()=>{})}withTimeout(e){let t,s=new Promise((i,n)=>{t=setTimeout(()=>n(new Error(`the refresh did not answer within ${this.refreshTimeoutMs/1e3} s`)),this.refreshTimeoutMs)});return Promise.race([e,s]).finally(()=>clearTimeout(t))}emit(e,t){(e==="SIGNED_IN"||e==="SIGNED_OUT")&&(this.endReason=null);for(let s of this.listeners)try{s(e,t)}catch{}}};var Ve=class{state="closed";refusal;logSeq;joinRef=null;refusals=0;retry=null;asking=0;listeners=new Map;closers=new Set;joiners=new Set;joinWaiters=[];name;socket;constructor(e,t,s={}){this.name=e,this.socket=t,this.logSeq=s.after}get topic(){return`realtime:${this.name}`}join(){if(this.state==="joined")return Promise.resolve();let e=new Promise((t,s)=>this.joinWaiters.push({resolve:t,reject:s}));return this.state!=="joining"&&this.socket.join(this),e}leave(){this.socket.leave(this)}push(e,t){return this.socket.request(this,e,t)}on(e,t){let s=this.listeners.get(e);return s||this.listeners.set(e,s=new Set),s.add(t),()=>s.delete(t)}onClosed(e){return this.closers.add(e),()=>this.closers.delete(e)}onJoined(e){return this.joiners.add(e),()=>this.joiners.delete(e)}deliver(e,t){e==="broadcast"&&typeof t.seq=="number"&&(this.logSeq=t.seq);for(let s of this.listeners.get(e)??[])try{s(t)}catch{}}settled(e,t){e&&typeof t.log_seq=="number"&&(this.logSeq=t.log_seq),this.state=e?"joined":"refused",this.refusal=e?void 0:t,e&&(this.refusals=0);let s=this.joinWaiters.splice(0);for(let i of s)e?i.resolve():i.reject(new Error(`join ${this.name} refused: ${JSON.stringify(t)}`));if(e)for(let i of[...this.joiners])try{i()}catch{}}closed(e){this.state="closed",this.joinRef=null,this.retry&&clearTimeout(this.retry),this.retry=null,this.refusals=0;let t=this.joinWaiters.splice(0);for(let s of t)s.reject(new Error(`join ${this.name}: ${e}`));for(let s of[...this.closers])try{s()}catch{}}},oe=class{ws=null;opening=null;ref=0;channels=new Map;lastJoin=new Map;replies=new Map;heartbeat=null;heartbeatRef=null;reconnectTimer=null;attempts=0;closedByUs=!1;asks=0;epoch=0;wasOpen=!1;current="idle";statusListeners=new Set;reconnects=0;opts;constructor(e){this.opts=e}get status(){return this.current}onStatus(e){return this.statusListeners.add(e),()=>{this.statusListeners.delete(e)}}setStatus(e){if(this.current!==e){this.current=e;for(let t of[...this.statusListeners])try{t(e)}catch{}}}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new Ve(e,this,t)),s}disconnect(){this.closedByUs=!0,this.wasOpen=!1,this.epoch++,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.attempts=0,this.stopHeartbeat();let e=this.ws;this.ws=null,this.opening=null,e?.close(1e3);for(let[,t]of this.replies)t("error",{reason:"socket closed"});this.replies.clear();for(let t of this.channels.values())t.asking=0,t.closed("the socket was closed");this.lastJoin.clear(),this.current!=="idle"&&this.setStatus("disconnected")}async tokenChanged(){if(this.askRefusedAgain(),!this.ws||this.ws.readyState!==1)return;let e=await this.opts.accessToken();if(e)for(let t of this.channels.values())t.state==="joined"&&this.push(t.joinRef,t.topic,"access_token",{access_token:e})}askRefusedAgain(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.open().catch(()=>{}));for(let e of this.channels.values())e.state==="refused"&&(e.retry&&clearTimeout(e.retry),e.retry=null,this.askAgain(e))}join(e){if(e.state="joining",this.ws?.readyState===1){this.sendJoin(e);return}this.reconnectTimer||this.open().catch(()=>{})}settle(e,t,s){e.settled(t,s),t||this.askAgainLater(e)}askAgainLater(e){let t=this.opts.refusedBackoff??[1e3,2e3,5e3,1e4,3e4,6e4,3e5],s=t[Math.min(e.refusals,t.length-1)]*(.8+Math.random()*.4);e.refusals++,e.retry&&clearTimeout(e.retry),e.retry=B(setTimeout(()=>{e.retry=null,this.askAgain(e)},s))}askAgain(e){this.reconnectTimer||this.channels.get(e.name)!==e||e.state!=="refused"||this.join(e)}joinWanted(){for(let e of this.channels.values())e.state==="refused"&&(e.retry&&clearTimeout(e.retry),e.retry=null,e.state="joining"),e.state==="joining"&&this.sendJoin(e)}leave(e){e.retry&&clearTimeout(e.retry),e.retry=null,e.state==="joined"&&(this.ws?.readyState===1&&this.push(e.joinRef,e.topic,"phx_leave",{}),this.lastJoin.get(e.name)===e&&this.lastJoin.delete(e.name)),e.state="closed",this.channels.delete(e.name)}async request(e,t,s){let i=this.ws;if(this.channels.get(e.name)!==e||e.state!=="joined"||i?.readyState!==1)return{status:"error",response:{reason:"not joined"}};let n=this.nextRef(),a=JSON.stringify([e.joinRef,n,e.topic,t,s]),o=this.awaitReply(n);return i.send(a),o}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1,this.current!=="reconnecting"&&this.setStatus("connecting");let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((i,n)=>{let a;try{a=new e(t)}catch(o){this.setStatus("reconnecting");let d=o instanceof Error?o.message:String(o);for(let l of this.channels.values())l.state==="joining"&&this.settle(l,!1,{reason:d});n(o);return}this.ws=a,a.onopen=()=>{if(this.ws!==a){a.close(1e3),n(new Error("the socket was closed"));return}this.attempts=0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wasOpen&&this.reconnects++,this.wasOpen=!0,this.startHeartbeat(),this.setStatus("connected"),this.joinWanted(),i()},a.onmessage=o=>this.receive(String(o.data)),a.onerror=()=>n(new Error("the realtime socket could not be opened")),a.onclose=()=>this.dropped(a)});return this.opening=s,s.finally(()=>{this.opening===s&&(this.opening=null)}).catch(()=>{}),s}dropped(e){if(this.ws!==e)return;this.ws=null,e.onmessage=null,this.stopHeartbeat();for(let[,i]of this.replies)i("error",{reason:"socket closed"});this.replies.clear();for(let i of this.channels.values())i.state==="joined"&&(i.state="joining");if(this.closedByUs)return;if(![...this.channels.values()].some(i=>i.state==="joining"||i.state==="refused")){this.wasOpen=!1,this.setStatus("disconnected");return}if(this.setStatus("reconnecting"),this.reconnectTimer)return;let t=this.opts.backoff??[500,1e3,2e3,5e3,1e4,3e4],s=t[Math.min(this.attempts,t.length-1)]*(.8+Math.random()*.4);this.attempts++,this.reconnectTimer=B(setTimeout(()=>{this.reconnectTimer=null,this.open().catch(()=>{})},s))}async sendJoin(e){if(e.asking)return;let t=++this.asks;e.asking=t;try{await this.ask(e)}finally{e.asking===t&&(e.asking=0)}}async ask(e){let t=this.ws;if(t?.readyState!==1)return;let s=this.epoch,i;try{i=await this.opts.accessToken()}catch(c){s===this.epoch&&this.ws===t&&this.channels.get(e.name)===e&&e.state==="joining"&&this.settle(e,!1,{reason:c instanceof Error?c.message:String(c)});return}if(s!==this.epoch||this.channels.get(e.name)!==e||e.state!=="joining"||this.ws!==t||t.readyState!==1)return;let n=this.nextRef();e.joinRef=n;let a=this.awaitReply(n),o={broadcast:{self:!1}};e.logSeq!==void 0&&(o.log={after:e.logSeq}),this.lastJoin.set(e.name,e),this.push(n,e.topic,"phx_join",{access_token:i,config:o},n);let{status:d,response:l}=await a;if(!(d!=="ok"&&this.ws!==t)){if(this.channels.get(e.name)!==e||e.state!=="joining"){this.lastJoin.get(e.name)===e&&(this.lastJoin.delete(e.name),d==="ok"&&this.ws?.readyState===1&&this.push(n,e.topic,"phx_leave",{}));return}if(d==="timeout"){this.askOnLater(e);return}this.settle(e,d==="ok",l)}}askOnLater(e){let t=this.opts.refusedBackoff??[1e3,2e3,5e3,1e4,3e4,6e4,3e5],s=t[Math.min(e.refusals,t.length-1)]*(.8+Math.random()*.4);e.refusals++,e.retry&&clearTimeout(e.retry),e.retry=B(setTimeout(()=>{e.retry=null,this.channels.get(e.name)===e&&e.state==="joining"&&this.ws?.readyState===1&&this.sendJoin(e)},s))}awaitReply(e){return new Promise(t=>{let s=B(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(i,n)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:n})})})}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||t.length!==5||typeof t[2]!="string"||typeof t[3]!="string")return;let[s,i,n,a,o]=t,d=typeof o=="object"&&o!==null?o:{};if(a==="phx_reply"&&typeof i=="string"){if(i===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(i)?.(String(d.status),d.response??{});return}let l=[...this.channels.values()].find(c=>c.topic===n);if(l&&!((a==="phx_close"||a==="phx_error")&&typeof s=="string"&&l.joinRef!==null&&s!==l.joinRef)){if(a==="phx_close"){if(l.state!=="joined")return;l.state="refused",l.refusal={reason:"closed by the server"},this.askAgainLater(l);return}if(a==="phx_error"){l.state="joining",B(setTimeout(()=>this.channels.get(l.name)===l&&l.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(l),1e3));return}l.deliver(a,d)}}push(e,t,s,i,n=this.nextRef()){this.ws?.send(JSON.stringify([e,n,t,s,i]))}nextRef(){return String(++this.ref)}startHeartbeat(){this.stopHeartbeat(),this.heartbeat=B(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null;let e=this.ws;e?.close(4e3),e&&this.dropped(e);return}this.heartbeatRef=this.nextRef(),this.push(null,"phoenix","heartbeat",{},this.heartbeatRef)},this.opts.heartbeatMs??25e3))}stopHeartbeat(){this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null,this.heartbeatRef=null}};function B(r){return r.unref?.(),r}var O="X-Palbase-Installation-Secret",J="X-Palbase-Installation",Lt=new WeakMap;function A(r){return Lt.get(r)}var Dt=new WeakSet;function Nt(r){return Dt.has(r)}var Ls=/^[A-Za-z0-9_-]{43}$/,de=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=Et()?.getItem(t);i&&Ls.test(i)&&(s=i)}catch{}if(!s){Dt.add(this),s=Ut(crypto.getRandomValues(new Uint8Array(32)));try{Et()?.setItem(t,s)}catch{}}Lt.set(this,s),this.id=Ds(s)}};function Ds(r){return Ut(Us(new TextEncoder().encode(r)).subarray(0,16))}function Et(){try{return globalThis.localStorage}catch{return}}function Ut(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var Ns=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),L=(r,e)=>r>>>e|r<<32-e;function Us(r){let e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((r.length+9)/64)*64);t.set(r),t[r.length]=128;let s=new DataView(t.buffer);s.setUint32(t.length-8,Math.floor(r.length/536870912)),s.setUint32(t.length-4,r.length*8>>>0);let i=new Uint32Array(64);for(let o=0;o<t.length;o+=64){for(let g=0;g<16;g++)i[g]=s.getUint32(o+g*4);for(let g=16;g<64;g++){let y=L(i[g-15],7)^L(i[g-15],18)^i[g-15]>>>3,R=L(i[g-2],17)^L(i[g-2],19)^i[g-2]>>>10;i[g]=i[g-16]+y+i[g-7]+R|0}let[d,l,c,h,p,v,f,u]=e;for(let g=0;g<64;g++){let y=u+(L(p,6)^L(p,11)^L(p,25))+(p&v^~p&f)+Ns[g]+i[g]|0,R=(L(d,2)^L(d,13)^L(d,22))+(d&l^d&c^l&c)|0;u=f,f=v,v=p,p=h+y|0,h=c,c=l,l=d,d=y+R|0}e[0]+=d,e[1]+=l,e[2]+=c,e[3]+=h,e[4]+=p,e[5]+=v,e[6]+=f,e[7]+=u}let n=new Uint8Array(32),a=new DataView(n.buffer);for(let o=0;o<8;o++)a.setUint32(o*4,e[o]);return n}var qs=30*6e4,qt=1e3,js=100,Ks=60*1024,le=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function F(){try{return globalThis.localStorage}catch{return}}var ue=class{api;closingApi;perfApi;closingPerfApi;flushMs;flushAt;now;anonKey;sessionKey;onceKey;events=[];samples=[];timer;memoryAnon;memorySession;memoryOnce;appVersion;stopAuto;session;consent;identifyPending=!1;listeners=new Set;people={set:e=>this.person({set:e}),setOnce:e=>this.person({set_once:e}),unset:e=>this.person({unset:[...e]}),add:e=>this.person({add:e})};constructor(e,t,s,i,n,a,o={}){this.session=s,this.consent=i;let d={send:c=>e.send(this.granted("analytics")?{...c,headers:{...c.headers,[J]:n.id}}:c)};this.api=Z.client(d);let l={send:c=>(this.granted("analytics")?e:t).send(c)};this.perfApi=Z.client(l),this.closingApi=Z.client({send:c=>d.send({...c,keepalive:!0})}),this.closingPerfApi=Z.client({send:c=>l.send({...c,keepalive:!0})}),this.flushMs=o.flushMs??5e3,this.flushAt=o.flushAt??20,this.now=o.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${a}`,this.sessionKey=`palbase.analytics.session.${a}`,this.onceKey=`palbase.analytics.once.${a}`,s.onChange(c=>{c==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):c==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((c,h)=>{h!=="granted"&&(c==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map($e),this.reset()):c==="performance"&&(this.samples=[]))})}capture(e,t){for(let i of this.listeners)i(e,t);if(!this.granted("analytics"))return;let s=this.now();this.hold({event:e,distinct_id:this.distinctId(),properties:t,timestamp:s,session_id:this.sessionId(s),...this.appVersion?{app_version:this.appVersion}:{}})}captureOnce(e,t,s){if(!this.granted("analytics"))return;let i=this.sessionId(this.now()),n=this.readOnce(),a=n?.session===i?n.keys:[];a.includes(e)||(this.writeOnce({session:i,keys:[...a,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=F()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{F()?.setItem(this.onceKey,JSON.stringify(e))}catch{}}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}page(e={}){let t=globalThis.location,s=globalThis.document,i=e.url??(t?`${t.origin}${Q(t.pathname)}`:"");if(!i)return;let n=e.referrer??Hs(s?.referrer);this.capture("$pageview",{...e.properties,url:i,...e.title??s?.title?{title:e.title??s?.title}:{},...n?{referrer:n}:{}})}async identify(e){this.identifyPending=!1;let t=this.session.snapshot()?.userId;!t||!this.granted("analytics")||(await this.flush(),await this.sendIdentify(this.api,t,e))}async sendIdentify(e,t,s){try{await e.identify({body:{distinct_id:t,anonymous_id:this.anonymousId(),traits:s,timestamp:this.now(),sent_at:this.now()}})}catch{}}reset(){this.memoryAnon=void 0,this.memorySession=void 0,this.memoryOnce=void 0;try{F()?.removeItem(this.anonKey),F()?.removeItem(this.sessionKey),F()?.removeItem(this.onceKey)}catch{}}async flush(e=!1){this.timer&&clearTimeout(this.timer),this.timer=void 0,this.granted("analytics")||(this.events=[]),this.granted("performance")?this.granted("analytics")||(this.samples=this.samples.map($e)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,i=this.now(),n=this.session.snapshot()?.userId;for(this.identifyPending&&n&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,n));this.events.length>0;){let a=this.take(this.events,e);try{await t.batch({body:{events:a.map(o=>({...o,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let a=this.take(this.samples,e);try{await s.sendPerf({body:{items:a}})}catch{}}}start(e={}){this.stopAuto?.(),this.appVersion=e.appVersion;let t=globalThis;if(typeof t.addEventListener!="function"||typeof globalThis.document>"u")return()=>{};let s=[];e.pageViews!==!1&&s.push(this.watchPages(t)),e.webVitals!==!1&&s.push($s((a,o)=>this.sample("web_vital",a,o))),e.network!==!1&&s.push(this.watchFetch(t));let i=()=>{document.visibilityState==="hidden"&&this.flush(!0)},n=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",i),t.addEventListener("pagehide",n),s.push(()=>{document.removeEventListener("visibilitychange",i),t.removeEventListener("pagehide",n)}),this.stopAuto=()=>{for(let a of s.splice(0))a();this.stopAuto=void 0},this.stopAuto}granted(e){return this.consent.state(e)==="granted"}async person(e){if(!this.granted("analytics"))return;let t=this.session.snapshot()?.userId,s=this.now();try{await this.api.setPersonProperties({body:{...e,...t?{}:{distinct_id:this.anonymousId()},timestamp:s,sent_at:s}})}catch{}}hold(e){this.events.length>=qt&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=qt&&this.samples.shift();let n={row_id:le(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...i};this.samples.push(this.granted("analytics")?{...n,distinct_id:this.distinctId()}:$e(n)),this.soon()}soon(){if(this.events.length+this.samples.length>=this.flushAt){this.flush();return}this.timer||(this.timer=setTimeout(()=>{this.flush()},this.flushMs),this.timer.unref?.())}take(e,t){let s=e.splice(0,js);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>Ks;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=F();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${le()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${le()}`,this.memoryAnon}sessionId(e){let t=F(),s=this.memorySession;try{let n=t?.getItem(this.sessionKey);n&&(s=JSON.parse(n))}catch{}let i=s&&e-s.last<qs?{id:s.id,last:e}:{id:`ses_${le()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=!0,i,n=()=>{if(!s)return;let v=`${e.location.origin}${e.location.pathname}`;if(v===t)return;t=v;let f=`${e.location.origin}${Q(e.location.pathname)}`;i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,s&&this.page({url:f})},0)},a=e.history,o=a.pushState,d=Object.hasOwn(a,"pushState"),l=a.replaceState,c=Object.hasOwn(a,"replaceState"),h=(...v)=>{o.apply(a,v),n()},p=(...v)=>{l.apply(a,v),n()};return a.pushState=h,a.replaceState=p,e.addEventListener("popstate",n),n(),()=>{s=!1,i!==void 0&&(clearTimeout(i),i=void 0),a.pushState===h&&(d?a.pushState=o:delete a.pushState),a.replaceState===p&&(c?a.replaceState=l:delete a.replaceState),e.removeEventListener("popstate",n)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,n)=>{let a=performance.now(),o=i instanceof Request?i:void 0,d=(n?.method??o?.method??"GET").toUpperCase(),l;try{l=new URL(o?.url??String(i),e.location.href)}catch{l=void 0}let c=!!l&&l.pathname.startsWith("/analytics/")||Ws(n?.headers??o?.headers);try{let h=await t(i,n);return l&&!c&&this.sample("network",`${d} ${l.origin}${Q(l.pathname)}`,performance.now()-a,{attrs:{status:String(h.status)},...h.headers.get("x-request-id")?{request_id:h.headers.get("x-request-id")}:{}}),h}catch(h){throw l&&!c&&this.sample("network",`${d} ${l.origin}${Q(l.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),h}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function $e(r){let{distinct_id:e,request_id:t,...s}=r;return s}var Fs=r=>r.entryType==="layout-shift"&&"value"in r&&"hadRecentInput"in r,Vs=r=>r.entryType==="event"||r.entryType==="first-input";function ce(r,e){if(!(typeof PerformanceObserver>"u"))try{let t=new PerformanceObserver(s=>e(s.getEntries()));return t.observe({type:r,buffered:!0}),t}catch{return}}function $s(r){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[ce("largest-contentful-paint",l=>{for(let c of l)e=Math.max(e,c.startTime)}),ce("layout-shift",l=>{for(let c of l)Fs(c)&&!c.hadRecentInput&&(t+=c.value)}),ce("event",l=>{for(let c of l)Vs(c)&&(s=Math.max(s,c.duration))}),ce("paint",l=>{for(let c of l)c.name==="first-contentful-paint"&&r("FCP",c.startTime)})],n=performance.getEntriesByType("navigation")[0];n&&n.responseStart>0&&r("TTFB",n.responseStart);let a=!1,o=()=>{a||(a=!0,e>0&&r("LCP",e),r("CLS",t),s>0&&r("INP",s))},d=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",d),()=>{o(),document.removeEventListener("visibilitychange",d);for(let l of i)l?.disconnect()}}function Ws(r){if(!r)return!1;try{return new Headers(r).has("next-router-prefetch")}catch{return!1}}var Gs=/^[a-z][a-z0-9_-]{0,31}$/;function Q(r){return r.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return Gs.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(n=>n.length<=16)?s:":id"}).join("/")}function Hs(r){if(!r)return"";try{let e=new URL(r);return`${e.origin}${Q(e.pathname)}`}catch{return Q(r.split(/[?#]/,1)[0]??"")}}var zt=/^custom\.[a-z0-9_]{1,48}$/,Bs=/^[a-z][a-z0-9_]{0,63}$/,Kt=r=>Bs.test(r)||zt.test(r),Js=50,Ft=[5e3,3e4,12e4,6e5],Qs=100,pe=class{userApi;deviceApi;session;socket;ref;installation;start;textVersion;customKeys;storeKey;now;kept;listeners=new Set;engaged=!1;platformKeys;watch;sending;sendAgain=!1;retryTimer;retries=0;readFor;stale=!1;lastW=0;lastChosen=0;gpc=globalThis.navigator?.globalPrivacyControl===!0;constructor(e){let t=e.options??{};for(let[d,l]of Object.entries(t.start??{})){if(!Kt(d))throw new TypeError(`consent.start: ${JSON.stringify(d)} is not a consent key (a platform key, or custom.<name>)`);if(l!=="granted"&&l!=="denied")throw new TypeError(`consent.start.${d} is granted or denied`)}for(let d of t.customKeys??[])if(!zt.test(d))throw new TypeError(`consent.customKeys: ${JSON.stringify(d)} is not custom.<name> (a-z, 0-9 and _, 48 at most)`);if(t.textVersion!==void 0&&(t.textVersion===""||t.textVersion.length>64))throw new TypeError("consent.textVersion: 1 to 64 characters");this.userApi=e.userApi,this.deviceApi=e.deviceApi,this.session=e.session,this.socket=e.socket,this.ref=e.ref,this.installation=e.installation,this.start={...t.start},this.textVersion=t.textVersion,this.customKeys=[...t.customKeys??[]],this.storeKey=`palbase.consent.${e.origin}.${e.installation.id}`,this.now=e.now??Date.now;let s=this.load(),i=()=>Nt(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},n={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...n,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:i()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...n,unsent:s.unsent.filter(d=>d.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((d,l)=>{this.engaged&&(d==="SIGNED_IN"&&l?this.signedIn(l):(d==="SIGNED_OUT"||d==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",d=>{(d.key===this.storeKey||d.key===null)&&this.reload()}),a.addEventListener("online",()=>{this.engaged&&this.send()}));let o=this.kept;(e.options!==void 0||s!=="empty"&&(o.unknown?.on||o.unsent.length>0||o.link!==void 0||Object.keys(o.choices).length>0))&&this.engage()}async keys(){return this.engage(),[...(await this.platform()).map(t=>({key:t.key,category:t.category,title:{...t.title},description:{...t.description},ads:t.ads})),...this.customKeys.map(t=>({key:t,category:"custom",title:{},description:{},ads:!1}))]}state(e){if(T(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=Wt(this.kept,e);return t&&t.state!=="unset"?t.state:this.kept.unknown?.on?"denied":this.start[e]}owesRead(){return this.stale||this.kept.unknown?.on===!0||T(this.kept)!==this.holder()||Object.values(this.kept.choices).some(e=>e.provisional)}holder(){let e=this.session.snapshot()?.userId;return e?`user:${e}`:`device:${this.installation.id}`}lastDeniedAt(e){let t=this.kept.choices[e]?.last_denied_at;return t?new Date(t):void 0}set(e,t){this.setMany({[e]:t})}setMany(e){let t=Object.entries(e);for(let[a,o]of t){if(!Kt(a))throw new TypeError(`${JSON.stringify(a)} is not a consent key (a platform key, or custom.<name>)`);if(o!=="granted"&&o!=="denied")throw new TypeError(`${a}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),i=this.session.snapshot()?.userId??null,n=this.states();for(let[a,o]of t)this.queue({key:a,state:o,source:"app",chosen_at:s,user:i,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(n),this.send()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async region(){this.engage();let e=await this.subject();if(this.readFor!==e)try{await this.read(e)}catch(t){if(!this.kept.region)throw t}return this.kept.region}async needsAsking(e){this.engage();let t=await this.subject();this.readFor!==t&&await this.read(t).catch(()=>{});let s=e??(await this.keys()).map(d=>d.key),i=await this.platform().catch(()=>this.kept.keys??[]),n=new Set(i.filter(d=>d.ads).map(d=>d.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(d=>{let l=this.kept.choices[d];return a&&n.has(d)&&l?.last_denied_at!==void 0&&Date.parse(l.last_denied_at)>o.getTime()?!1:!l||l.state==="unset"?!0:this.textVersion!==void 0&&l.source==="app"&&l.text_version!==this.textVersion})}engage(){this.engaged||(this.engaged=!0,this.session.session().then(e=>{e&&!this.watch&&this.follow(e),this.send(),this.refuseByGpc()}))}async subject(){return(await this.session.session())?.userId??null}secret(){return{[O]:A(this.installation)}}platform(){return this.platformKeys??=this.deviceApi.listConsentKeys().then(e=>(this.kept={...this.kept,keys:e.data.keys},this.commit(),e.data.keys),e=>{if(this.platformKeys=void 0,this.kept.keys)return this.kept.keys;throw e}),this.platformKeys}async read(e){let s=(await(e===null?this.deviceApi:this.userApi(e)).getConsents({query:{installation_id:this.installation.id},headers:this.secret()})).data;this.adopt(s,e)}adopt(e,t,s=[]){if(this.kept={...this.kept,region:e.region},(this.session.snapshot()?.userId??null)!==t){this.commit();return}let i=this.states(),n={};for(let u of e.choices)n[u.key]={state:u.state,source:u.source,chosen_at:u.chosen_at,...u.text_version!==void 0?{text_version:u.text_version}:{},...u.last_denied_at!==void 0?{last_denied_at:u.last_denied_at}:{}};let a=s.filter(u=>n[u.key]?.state!==u.state||Date.parse(n[u.key]?.chosen_at??"")!==Date.parse(u.chosen_at)).map(u=>N(u.key,u)),d=T(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,u])=>u.provisional).map(([u,g])=>N(u,g)):[];if(a.length+d.length>0&&(this.kept={...this.kept,void:U([...this.kept.void??[],...a,...d])}),t===null&&this.kept.resetAt!==void 0)for(let[u,g]of Object.entries(n))Date.parse(g.chosen_at)<this.kept.resetAt&&delete n[u];let l=new Set(Object.entries(n).map(([u,g])=>N(u,g))),c=(this.kept.void??[]).filter(u=>l.has(u));c.length>0&&(this.kept={...this.kept,unvoid:U([...this.kept.unvoid??[],...c])});let h=Xt(this.kept),p;if(T(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))p=n;else{p={};for(let u of[...new Set([...Object.keys(this.kept.choices),...Object.keys(n)])].sort()){let g=this.kept.choices[u],y=g&&!g.provisional&&!h.has(N(u,g))?g:void 0,R=n[u],x=R&&(!y||Date.parse(R.chosen_at)>=Date.parse(y.chosen_at))?R:y;x&&(p[u]=x)}}for(let u of this.kept.unsent){if(u.user!==null&&u.user!==t||u.user===null&&u.device!==this.installation.id||u.user===null&&t!==null)continue;let g=p[u.key];g&&Date.parse(g.chosen_at)>Date.parse(u.chosen_at)||(p[u.key]=Vt(u,g))}let{install:v,...f}=this.kept;this.kept={...f,whose:t,...t===null?{install:this.installation.id}:{},choices:p,unknown:{on:!1,w:this.stamp()}},this.readFor=t,this.stale=!1,this.commit(i),this.refuseByGpc()}async refused(e,t,s){let i=t===e&&T(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),n=U([...this.kept.void??[],...s.map(d=>N(d.key,d))]);if(!i){this.kept={...this.kept,void:n},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let d of s){if(this.kept.unsent.some(c=>c.key===d.key&&(c.user===null||c.user===e)&&Date.parse(c.chosen_at)>Date.parse(d.chosen_at)))continue;let l=o[d.key];o[d.key]={state:"denied",source:"app",chosen_at:d.chosen_at,...l?.last_denied_at!==void 0?{last_denied_at:l.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:o,void:n},this.commit(a);try{await this.read(e)}catch{this.stale=!0}}queue(e){let t=e.user===null?{...e,device:this.installation.id}:e,s=T(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:Yt([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:Vt(t,this.kept.choices[t.key])}}:{}}}send(){if(this.sendAgain=!0,this.sending)return;let e=(async()=>{for(;this.sendAgain;)this.sendAgain=!1,await this.sendUnsent()||(this.sendAgain=!1)})();this.sending=e,e.finally(()=>{this.sending===e&&(this.sending=void 0)})}async sendUnsent(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=this.session.snapshot()?.userId??null;try{e=await this.subject();let t=await this.sendOf(null,e);if(e!==null&&(this.kept.link===e||t)){let s;try{s=(await this.userApi(e).linkConsents({headers:this.secret(),body:{installation_id:this.installation.id}})).data}catch(i){if(!Bt(i))throw i}if(this.kept.link===e){let{link:i,...n}=this.kept;this.kept=n,this.commit()}if(s)this.adopt(s,e);else{let i=this.states();this.kept={...this.kept,unknown:{on:!0,w:this.stamp()}},this.commit(i)}}if(e!==null&&await this.sendOf(e,e),this.owesRead()&&(await this.read(e),this.owesRead()))throw new Error("the choices are not read yet");return this.retries=0,!0}catch{return(this.session.snapshot()?.userId??null)!==e?(this.sendAgain=!0,!0):(this.retryLater(),!1)}}async sendOf(e,t){let s=!1;for(;;){let i=this.nextGroup(e);if(i.length===0)return s;let n=i[0],a=e===null?this.deviceApi:this.userApi(e),o;try{o=(await a.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...n.source==="gpc"?{source:"gpc"}:{},...n.text_version!==void 0?{text_version:n.text_version}:{},choices:i.map(d=>({key:d.key,state:d.state,chosen_at:d.chosen_at}))}})).data}catch(d){if(!Bt(d))throw d;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(l=>i.some(c=>Ht(c,l))?{...l,alone:!0}:l)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(d=>!i.some(l=>Ht(l,d))),done:U([...this.kept.done??[],...i.map(fe)])},this.commit(),o?(s=!0,e===t&&this.adopt(o,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(a=>a.user===e&&(e!==null||a.device===this.installation.id)),s=t[0];if(!s)return[];let i=[],n=new Set;if(s.alone)return[s];for(let a of t)if(!n.has(a.key)&&(n.add(a.key),!(a.alone||a.source!==s.source||a.text_version!==s.text_version)&&(i.push(a),i.length===Js)))break;return i}retryLater(){if(this.retryTimer)return;let e=Ft[Math.min(this.retries,Ft.length-1)];this.retries++,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.send()},e),this.retryTimer.unref?.()}signedIn(e){this.readFor=void 0,this.kept={...this.kept,link:e.userId},this.commit(),this.follow(e),this.send()}signedOut(){this.unfollow(),this.readFor=void 0;let e=this.states(),t=this.chosenAt(),s=new Set([...Object.entries(this.kept.choices).filter(([,o])=>o.state!=="unset").map(([o])=>o),...this.kept.unsent.filter(o=>o.user===null&&o.device===this.installation.id).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),i={};for(let[o,d]of Object.entries(this.kept.choices))i[o]={state:"unset",source:"app",chosen_at:t,...d.last_denied_at!==void 0?{last_denied_at:d.last_denied_at}:{}};let n=o=>o.user===null&&o.device===this.installation.id,a=this.kept.unsent.filter(n);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(o=>!n(o)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:U([...this.kept.done??[],...a.map(fe)]),...this.kept.region?{region:this.kept.region}:{},...this.kept.keys?{keys:this.kept.keys}:{},...this.kept.gpc?{gpc:this.kept.gpc}:{},...this.kept.unknown?{unknown:this.kept.unknown}:{}};for(let o of s)this.queue({key:o,state:"unset",source:"app",chosen_at:t,user:null});this.commit(e),this.send(),this.refuseByGpc()}follow(e){this.unfollow();let t=this.socket.channel(`consents:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},version:-1},i=[t.on("broadcast",n=>{n.event==="changed"&&this.changed(s,We(n.payload))}),t.on("state_snapshot",n=>this.held(s,We(Qt(n.entries)))),t.on("state_diff",n=>this.held(s,We(Qt(n.set))))];s.off=()=>i.forEach(n=>n()),this.watch=s,t.join().catch(()=>{})}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}held(e,t){t!==void 0&&this.changed(e,t)}changed(e,t){if(this.watch===e){if(t!==void 0){if(t<=e.version)return;e.version=t}this.read(e.userId).catch(()=>{this.watch===e&&(this.stale=!0,this.retryLater())})}}gpcRefuses(e){if(!this.gpc||!(this.kept.keys??[]).some(n=>n.key===e&&n.ads))return!1;let t=Wt(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[T(this.kept)],i=s!==void 0&&(this.kept.whose!=null||s>=(this.kept.resetAt??0));return!(t?.state==="granted"&&t.source==="app"&&i&&Date.parse(t.chosen_at)>s)}async refuseByGpc(){if(!this.gpc||T(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(T(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(a=>a.ads&&this.gpcRefuses(a.key)&&!this.kept.unsent.some(o=>o.key===a.key&&o.source==="gpc"&&o.user===t));if(s.length===0)return;let i=this.chosenAt(),n=this.states();for(let a of s)this.queue({key:a.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[T(this.kept)]:Date.parse(i)}},this.commit(n),this.send()}states(){let e=new Map;for(let t of[...Object.keys(this.start),...Object.keys(this.kept.choices)])e.set(t,this.state(t));return e}tell(e){let t=this.states();for(let s of new Set([...e.keys(),...t.keys()])){let i=t.get(s);if(e.get(s)!==i)for(let n of[...this.listeners])try{n(s,i)}catch{}}}load(){let e;try{e=Jt()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(Zs(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=$t(e,this.kept,"theirs",this.holder()),T(e)===T(this.kept)&&Gt(this.kept)!==Gt(e)&&this.write(),this.tell(t);let s=this.session.snapshot()?.userId??null;this.engaged&&this.kept.unsent.some(i=>i.user!==null&&i.user===s||i.user===null&&i.device===this.installation.id)&&this.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=$t(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{Jt()?.setItem(this.storeKey,JSON.stringify(this.kept))}catch{}}chosenAt(){return this.lastChosen=Math.max(this.now(),this.lastChosen+1),new Date(this.lastChosen).toISOString()}stamp(){let e=this.kept,t=e?Math.max(0,e.unknown?.w??0):0;return this.lastW=Math.max(this.now(),this.lastW+1,t+1),this.lastW}};function Vt(r,e){let t=r.state==="denied"?r.chosen_at:e?.last_denied_at;return{state:r.state,source:r.source,chosen_at:r.chosen_at,...r.text_version!==void 0?{text_version:r.text_version}:{},...t!==void 0?{last_denied_at:t}:{}}}function N(r,e){return`${r}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function Xt(r){let e=new Set(r.unvoid??[]);return new Set((r.void??[]).filter(t=>!e.has(t)))}var he={denied:2,unset:1,granted:0};function zs(r,e,t,s){let i=e&&!s.has(N(r,e))?e:void 0,n=t&&!s.has(N(r,t))?t:void 0;if(!i||!n)return i??n;let a=Date.parse(i.chosen_at),o=Date.parse(n.chosen_at);return a!==o?a>o?i:n:he[i.state]!==he[n.state]?he[i.state]>he[n.state]?i:n:i.provisional?n:i}function Xs(r,e){return!r||!e?r??e:e.w>r.w||e.w===r.w&&e.on?e:r}function $t(r,e,t,s){let i=U([...r.void??[],...e.void??[]]),n=U([...r.unvoid??[],...e.unvoid??[]]),a=Xt({void:i,unvoid:n}),o={},d,l={...r.gpc};for(let[y,R]of Object.entries(e.gpc??{}))l[y]=Math.max(l[y]??0,R);let c;if(T(r)===T(e)){d=e;for(let y of[...new Set([...Object.keys(r.choices),...Object.keys(e.choices)])].sort()){let R=zs(y,r.choices[y],e.choices[y],a);R&&(o[y]=R)}c=Xs(r.unknown,e.unknown)}else{d=T(e)===s?e:T(r)===s?r:t==="ours"?e:r;for(let[y,R]of Object.entries(d.choices))a.has(N(y,R))||(o[y]=R);c=d.unknown}let h=U([...r.done??[],...e.done??[]]),p=Yt([...r.unsent,...e.unsent]).filter(y=>!h.includes(fe(y))),v=t==="ours"?e:r,f=t==="ours"?r:e,u=v.region??f.region,g=v.keys??f.keys;return{whose:d.whose??null,...d.whose==null&&d.install!==void 0?{install:d.install}:{},...d.whose==null&&(r.resetAt!==void 0||e.resetAt!==void 0)&&T(r)===T(e)?{resetAt:Math.max(r.resetAt??0,e.resetAt??0)}:d.whose==null&&d.resetAt!==void 0?{resetAt:d.resetAt}:{},choices:o,unsent:p,...h.length>0?{done:h}:{},...i.length>0?{void:i}:{},...n.length>0?{unvoid:n}:{},...v.link!==void 0?{link:v.link}:{},...u?{region:u}:{},...Object.keys(l).length>0?{gpc:l}:{},...g?{keys:g}:{},...c?{unknown:c}:{}}}function fe(r){return`${r.user??`device:${r.device??""}`}|${r.key}|${r.state}|${r.source}|${r.chosen_at}`}function Wt(r,e){let t=r.choices[e];if(!t||r.whose!=null||r.resetAt===void 0||Date.parse(t.chosen_at)>=r.resetAt)return t}function T(r){return r.whose!=null?`user:${r.whose}`:`device:${r.install??""}`}function U(r){return[...new Set(r)].slice(-Qs)}function Gt(r){return JSON.stringify(r,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[i])=>s.localeCompare(i))):t)}function Yt(r){let e=new Map;for(let t of r){let s=fe(t),i=e.get(s);e.set(s,i?i.alone||!t.alone?i:{...i,alone:!0}:t)}return[...e.values()].sort((t,s)=>Date.parse(t.chosen_at)-Date.parse(s.chosen_at))}var Ys=new Set(["granted","denied","unset"]);function Zs(r){if(typeof r!="object"||r===null)return!1;let e=r;if(typeof e.choices!="object"||e.choices===null||Array.isArray(e.choices)||!Array.isArray(e.unsent))return!1;let t=(o,d)=>{if(typeof o!="object"||o===null)return!1;let l=o;return Ys.has(l.state)&&typeof l.chosen_at=="string"&&(!d||typeof l.key=="string")},s=o=>o===void 0||typeof o=="object"&&o!==null&&typeof o.on=="boolean"&&typeof o.w=="number",i=r,n=o=>o===void 0||Array.isArray(o)&&o.every(d=>typeof d=="string"),a=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(o=>t(o,!1))&&e.unsent.every(o=>t(o,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(o=>typeof o=="number"))&&s(i.unknown)&&n(i.done)&&n(i.void)&&n(i.unvoid)&&a}function Ht(r,e){return r.key===e.key&&r.user===e.user&&r.state===e.state&&r.source===e.source&&r.chosen_at===e.chosen_at}function Bt(r){return r instanceof b&&r.status>=400&&r.status<500&&r.status!==401&&r.status!==408&&r.status!==429}function Jt(){try{return globalThis.localStorage}catch{return}}function Qt(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function We(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var ei=`
1
+ /*! palbase 0.78.1 — Palbase SDK License (see LICENSE) */
2
+ import{b as xt,c as Ke,d as Mt}from"./ZIHVYOXE.js";import{e as Ct}from"./RB4JQXKZ.js";import{e as _t,g as Rt,h as Pt}from"./426QPZNS.js";import{c as je}from"./6Y4ICGZ7.js";import{h as Tt}from"./LXS7JHPJ.js";import{a as kt}from"./WTFMJKDB.js";import{r as wt,t as bt,u as St}from"./EUMY6SCM.js";import{a as Ue,b as Z,c as W,e as ft,f as gt,g as G,h as mt,i as yt,l as qe,m as H}from"./3TJFV35H.js";import{a as vt,b as ee}from"./3XF644A5.js";import{b,d as $}from"./35KQJQ77.js";function Ms(r){let e=r,t=e?.body,s=t&&typeof t=="object"?t.reason:void 0;return s==="user_deleted"?"userDeleted":s==="user_banned"?"userBanned":e?.code==="session_expired"||e?.code==="token_expired"?"expired":"revoked"}var P=class extends Error{code="session_changed";constructor(e){super(e),this.name="SessionChangedError"}};function It(){let r=null;return{load:()=>r,save:e=>{r=e},clear:()=>{r=null},shared:!1}}function Ot(r){let e=null,t=!0,s=()=>{try{return globalThis.localStorage}catch{return}};return{shared:!0,load(){try{let i=s()?.getItem(r);return i==null?t?null:e:JSON.parse(i)}catch{return e}},save(i){e=i;try{let n=s();if(!n)throw new Error("no storage");n.setItem(r,JSON.stringify(i)),t=!0}catch{t=!1}},clear(){e=null,t=!0;try{s()?.removeItem(r)}catch{}},watch(i){let n=globalThis;if(typeof n.addEventListener!="function")return()=>{};let a=o=>{(o.key===r||o.key===null)&&i()};return n.addEventListener("storage",a),()=>n.removeEventListener?.("storage",a)}}}function At(r){try{let e=r.split(".")[1]??"",t=atob(e.replace(/-/g,"+").replace(/_/g,"/").padEnd(Math.ceil(e.length/4)*4,"=")),s=JSON.parse(t);return typeof s=="object"&&s!==null?s:{}}catch{return{}}}function Fe(r){let{sub:e}=At(r);return typeof e=="string"?e:""}function Is(r,e){let{iat:t,exp:s}=At(r);return typeof t!="number"||typeof s!="number"||!(s>t)?e:Math.min(e,(s-t)*1e3/2)}var Os=6e4,As=15e3;function Es(r,e,t){let s=r?globalThis.navigator?.locks:void 0;return s?s.request(e,t):t()}var ae=class{current=null;loaded;inflight=null;endReason=null;listeners=new Set;store;refresher;isRejected;now;lockName;refreshTimeoutMs;mode;constructor(e,t,s,i={}){this.store=e,this.refresher=t,this.isRejected=s,this.now=i.now??Date.now,this.lockName=i.lockName??"palbase.session.refresh",this.refreshTimeoutMs=i.refreshTimeoutMs??As,this.mode=i.refresh??"behind",this.loaded=Promise.resolve(e.load()).then(n=>{this.current=n}),e.watch?.(()=>{this.reconcile()})}async session(){return await this.loaded,this.current}snapshot(){return this.current}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async set(e,t,s){await this.loaded;let i=t==="TOKEN_REFRESHED"?this.current:null,n={accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:this.now()+e.expires_in*1e3,userId:s?.id??i?.userId??Fe(e.access_token),user:s??i?.user};return this.current=n,await this.store.save(n),this.emit(t,n),n}async setUser(e,t){await this.loaded,!(!this.current||!t||this.current.userId!==t.userId)&&(this.current={...this.current,user:e},await this.store.save(this.current),this.emit("USER_UPDATED",this.current))}async clear(e,t){await this.loaded;let s=this.current;this.current=null,this.inflight=null;let i=await this.store.load();(!i||!s||i.userId===s.userId)&&await this.store.clear(),s&&(e==="SESSION_EXPIRED"&&(this.endReason=t??"revoked"),this.emit(e,null))}async accessToken(){await this.loaded;let e=this.current;if(!e)return;let t=e.expiresAt-this.now();if(t>Is(e.accessToken,Os))return e.accessToken;if(this.mode==="never")return t>0?e.accessToken:void 0;if(t>0&&this.mode==="behind")return this.refresh().catch(()=>{}),e.accessToken;if(t>0)try{return(await this.refresh()).accessToken}catch(s){if(this.current===e)return e.accessToken;throw s}return(await this.refresh()).accessToken}refresh(){if(this.mode==="never")return Promise.reject(new Error("this client does not renew its session (refresh: 'never'): where the session cannot be written back, the request's middleware renews it"));if(this.inflight)return this.inflight;let e=Es(this.store.shared===!0,this.lockName,async()=>{await this.loaded;let t=this.current;if(!t)throw new P("no session to refresh");let s=await this.adoptStored(t);if(s)return s;try{let i=await this.withTimeout(this.refresher(t.refreshToken));if(this.current?.refreshToken!==t.refreshToken)throw new P("the session changed while it was refreshed");return await this.set(i,"TOKEN_REFRESHED")}catch(i){throw this.isRejected(i)&&this.current?.refreshToken===t.refreshToken&&await this.clear("SESSION_EXPIRED",Ms(i)),i}});return this.inflight=e,e.finally(()=>{this.inflight===e&&(this.inflight=null)}).catch(()=>{}),e}async adoptStored(e){let t=await this.store.load();if(!t)throw this.current=null,this.emit("SIGNED_OUT",null),new P("signed out in another tab");if(t.userId!==e.userId)throw this.current=t,this.emit("SIGNED_OUT",null),this.emit("SIGNED_IN",t),new P("another user signed in in another tab");if(t.refreshToken!==e.refreshToken&&t.expiresAt>=e.expiresAt)return this.current=t,this.emit("TOKEN_REFRESHED",t),t}async reconcile(){await this.loaded;let e=this.current,t=await this.store.load();if(!e){t&&(this.current=t,this.emit("SIGNED_IN",t));return}await this.adoptStored(e).catch(()=>{})}withTimeout(e){let t,s=new Promise((i,n)=>{t=setTimeout(()=>n(new Error(`the refresh did not answer within ${this.refreshTimeoutMs/1e3} s`)),this.refreshTimeoutMs)});return Promise.race([e,s]).finally(()=>clearTimeout(t))}emit(e,t){(e==="SIGNED_IN"||e==="SIGNED_OUT")&&(this.endReason=null);for(let s of this.listeners)try{s(e,t)}catch{}}};var Ve=class{state="closed";refusal;logSeq;joinRef=null;refusals=0;retry=null;asking=0;listeners=new Map;closers=new Set;joiners=new Set;joinWaiters=[];name;socket;constructor(e,t,s={}){this.name=e,this.socket=t,this.logSeq=s.after}get topic(){return`realtime:${this.name}`}join(){if(this.state==="joined")return Promise.resolve();let e=new Promise((t,s)=>this.joinWaiters.push({resolve:t,reject:s}));return this.state!=="joining"&&this.socket.join(this),e}leave(){this.socket.leave(this)}push(e,t){return this.socket.request(this,e,t)}on(e,t){let s=this.listeners.get(e);return s||this.listeners.set(e,s=new Set),s.add(t),()=>s.delete(t)}onClosed(e){return this.closers.add(e),()=>this.closers.delete(e)}onJoined(e){return this.joiners.add(e),()=>this.joiners.delete(e)}deliver(e,t){e==="broadcast"&&typeof t.seq=="number"&&(this.logSeq=t.seq);for(let s of this.listeners.get(e)??[])try{s(t)}catch{}}settled(e,t){e&&typeof t.log_seq=="number"&&(this.logSeq=t.log_seq),this.state=e?"joined":"refused",this.refusal=e?void 0:t,e&&(this.refusals=0);let s=this.joinWaiters.splice(0);for(let i of s)e?i.resolve():i.reject(new Error(`join ${this.name} refused: ${JSON.stringify(t)}`));if(e)for(let i of[...this.joiners])try{i()}catch{}}closed(e){this.state="closed",this.joinRef=null,this.retry&&clearTimeout(this.retry),this.retry=null,this.refusals=0;let t=this.joinWaiters.splice(0);for(let s of t)s.reject(new Error(`join ${this.name}: ${e}`));for(let s of[...this.closers])try{s()}catch{}}},oe=class{ws=null;opening=null;ref=0;channels=new Map;lastJoin=new Map;replies=new Map;heartbeat=null;heartbeatRef=null;reconnectTimer=null;attempts=0;closedByUs=!1;asks=0;epoch=0;wasOpen=!1;current="idle";statusListeners=new Set;reconnects=0;opts;constructor(e){this.opts=e}get status(){return this.current}onStatus(e){return this.statusListeners.add(e),()=>{this.statusListeners.delete(e)}}setStatus(e){if(this.current!==e){this.current=e;for(let t of[...this.statusListeners])try{t(e)}catch{}}}channel(e,t){let s=this.channels.get(e);return s||this.channels.set(e,s=new Ve(e,this,t)),s}disconnect(){this.closedByUs=!0,this.wasOpen=!1,this.epoch++,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.attempts=0,this.stopHeartbeat();let e=this.ws;this.ws=null,this.opening=null,e?.close(1e3);for(let[,t]of this.replies)t("error",{reason:"socket closed"});this.replies.clear();for(let t of this.channels.values())t.asking=0,t.closed("the socket was closed");this.lastJoin.clear(),this.current!=="idle"&&this.setStatus("disconnected")}async tokenChanged(){if(this.askRefusedAgain(),!this.ws||this.ws.readyState!==1)return;let e=await this.opts.accessToken();if(e)for(let t of this.channels.values())t.state==="joined"&&this.push(t.joinRef,t.topic,"access_token",{access_token:e})}askRefusedAgain(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.open().catch(()=>{}));for(let e of this.channels.values())e.state==="refused"&&(e.retry&&clearTimeout(e.retry),e.retry=null,this.askAgain(e))}join(e){if(e.state="joining",this.ws?.readyState===1){this.sendJoin(e);return}this.reconnectTimer||this.open().catch(()=>{})}settle(e,t,s){e.settled(t,s),t||this.askAgainLater(e)}askAgainLater(e){let t=this.opts.refusedBackoff??[1e3,2e3,5e3,1e4,3e4,6e4,3e5],s=t[Math.min(e.refusals,t.length-1)]*(.8+Math.random()*.4);e.refusals++,e.retry&&clearTimeout(e.retry),e.retry=B(setTimeout(()=>{e.retry=null,this.askAgain(e)},s))}askAgain(e){this.reconnectTimer||this.channels.get(e.name)!==e||e.state!=="refused"||this.join(e)}joinWanted(){for(let e of this.channels.values())e.state==="refused"&&(e.retry&&clearTimeout(e.retry),e.retry=null,e.state="joining"),e.state==="joining"&&this.sendJoin(e)}leave(e){e.retry&&clearTimeout(e.retry),e.retry=null,e.state==="joined"&&(this.ws?.readyState===1&&this.push(e.joinRef,e.topic,"phx_leave",{}),this.lastJoin.get(e.name)===e&&this.lastJoin.delete(e.name)),e.state="closed",this.channels.delete(e.name)}async request(e,t,s){let i=this.ws;if(this.channels.get(e.name)!==e||e.state!=="joined"||i?.readyState!==1)return{status:"error",response:{reason:"not joined"}};let n=this.nextRef(),a=JSON.stringify([e.joinRef,n,e.topic,t,s]),o=this.awaitReply(n);return i.send(a),o}open(){if(this.ws?.readyState===1)return Promise.resolve();if(this.opening)return this.opening;this.closedByUs=!1,this.current!=="reconnecting"&&this.setStatus("connecting");let e=this.opts.webSocket??globalThis.WebSocket,t=`${this.opts.baseUrl.replace(/^http/,"ws")}/realtime/v1/websocket?vsn=2.0.0&apikey=${encodeURIComponent(this.opts.publishableKey)}`,s=new Promise((i,n)=>{let a;try{a=new e(t)}catch(o){this.setStatus("reconnecting");let d=o instanceof Error?o.message:String(o);for(let l of this.channels.values())l.state==="joining"&&this.settle(l,!1,{reason:d});n(o);return}this.ws=a,a.onopen=()=>{if(this.ws!==a){a.close(1e3),n(new Error("the socket was closed"));return}this.attempts=0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.wasOpen&&this.reconnects++,this.wasOpen=!0,this.startHeartbeat(),this.setStatus("connected"),this.joinWanted(),i()},a.onmessage=o=>this.receive(String(o.data)),a.onerror=()=>n(new Error("the realtime socket could not be opened")),a.onclose=()=>this.dropped(a)});return this.opening=s,s.finally(()=>{this.opening===s&&(this.opening=null)}).catch(()=>{}),s}dropped(e){if(this.ws!==e)return;this.ws=null,e.onmessage=null,this.stopHeartbeat();for(let[,i]of this.replies)i("error",{reason:"socket closed"});this.replies.clear();for(let i of this.channels.values())i.state==="joined"&&(i.state="joining");if(this.closedByUs)return;if(![...this.channels.values()].some(i=>i.state==="joining"||i.state==="refused")){this.wasOpen=!1,this.setStatus("disconnected");return}if(this.setStatus("reconnecting"),this.reconnectTimer)return;let t=this.opts.backoff??[500,1e3,2e3,5e3,1e4,3e4],s=t[Math.min(this.attempts,t.length-1)]*(.8+Math.random()*.4);this.attempts++,this.reconnectTimer=B(setTimeout(()=>{this.reconnectTimer=null,this.open().catch(()=>{})},s))}async sendJoin(e){if(e.asking)return;let t=++this.asks;e.asking=t;try{await this.ask(e)}finally{e.asking===t&&(e.asking=0)}}async ask(e){let t=this.ws;if(t?.readyState!==1)return;let s=this.epoch,i;try{i=await this.opts.accessToken()}catch(c){s===this.epoch&&this.ws===t&&this.channels.get(e.name)===e&&e.state==="joining"&&this.settle(e,!1,{reason:c instanceof Error?c.message:String(c)});return}if(s!==this.epoch||this.channels.get(e.name)!==e||e.state!=="joining"||this.ws!==t||t.readyState!==1)return;let n=this.nextRef();e.joinRef=n;let a=this.awaitReply(n),o={broadcast:{self:!1}};e.logSeq!==void 0&&(o.log={after:e.logSeq}),this.lastJoin.set(e.name,e),this.push(n,e.topic,"phx_join",{access_token:i,config:o},n);let{status:d,response:l}=await a;if(!(d!=="ok"&&this.ws!==t)){if(this.channels.get(e.name)!==e||e.state!=="joining"){this.lastJoin.get(e.name)===e&&(this.lastJoin.delete(e.name),d==="ok"&&this.ws?.readyState===1&&this.push(n,e.topic,"phx_leave",{}));return}if(d==="timeout"){this.askOnLater(e);return}this.settle(e,d==="ok",l)}}askOnLater(e){let t=this.opts.refusedBackoff??[1e3,2e3,5e3,1e4,3e4,6e4,3e5],s=t[Math.min(e.refusals,t.length-1)]*(.8+Math.random()*.4);e.refusals++,e.retry&&clearTimeout(e.retry),e.retry=B(setTimeout(()=>{e.retry=null,this.channels.get(e.name)===e&&e.state==="joining"&&this.ws?.readyState===1&&this.sendJoin(e)},s))}awaitReply(e){return new Promise(t=>{let s=B(setTimeout(()=>{this.replies.delete(e),t({status:"timeout",response:{reason:"no reply"}})},this.opts.replyTimeoutMs??1e4));this.replies.set(e,(i,n)=>{clearTimeout(s),this.replies.delete(e),t({status:i,response:n})})})}receive(e){let t;try{t=JSON.parse(e)}catch{return}if(!Array.isArray(t)||t.length!==5||typeof t[2]!="string"||typeof t[3]!="string")return;let[s,i,n,a,o]=t,d=typeof o=="object"&&o!==null?o:{};if(a==="phx_reply"&&typeof i=="string"){if(i===this.heartbeatRef){this.heartbeatRef=null;return}this.replies.get(i)?.(String(d.status),d.response??{});return}let l=[...this.channels.values()].find(c=>c.topic===n);if(l&&!((a==="phx_close"||a==="phx_error")&&typeof s=="string"&&l.joinRef!==null&&s!==l.joinRef)){if(a==="phx_close"){if(l.state!=="joined")return;l.state="refused",l.refusal={reason:"closed by the server"},this.askAgainLater(l);return}if(a==="phx_error"){l.state="joining",B(setTimeout(()=>this.channels.get(l.name)===l&&l.state==="joining"&&this.ws?.readyState===1&&void this.sendJoin(l),1e3));return}l.deliver(a,d)}}push(e,t,s,i,n=this.nextRef()){this.ws?.send(JSON.stringify([e,n,t,s,i]))}nextRef(){return String(++this.ref)}startHeartbeat(){this.stopHeartbeat(),this.heartbeat=B(setInterval(()=>{if(this.heartbeatRef!==null){this.heartbeatRef=null;let e=this.ws;e?.close(4e3),e&&this.dropped(e);return}this.heartbeatRef=this.nextRef(),this.push(null,"phoenix","heartbeat",{},this.heartbeatRef)},this.opts.heartbeatMs??25e3))}stopHeartbeat(){this.heartbeat&&clearInterval(this.heartbeat),this.heartbeat=null,this.heartbeatRef=null}};function B(r){return r.unref?.(),r}var O="X-Palbase-Installation-Secret",J="X-Palbase-Installation",Lt=new WeakMap;function A(r){return Lt.get(r)}var Dt=new WeakSet;function Nt(r){return Dt.has(r)}var Ls=/^[A-Za-z0-9_-]{43}$/,de=class{id;constructor(e){let t=`palbase.installation.secret.${e}`,s;try{let i=Et()?.getItem(t);i&&Ls.test(i)&&(s=i)}catch{}if(!s){Dt.add(this),s=Ut(crypto.getRandomValues(new Uint8Array(32)));try{Et()?.setItem(t,s)}catch{}}Lt.set(this,s),this.id=Ds(s)}};function Ds(r){return Ut(Us(new TextEncoder().encode(r)).subarray(0,16))}function Et(){try{return globalThis.localStorage}catch{return}}function Ut(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}var Ns=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),L=(r,e)=>r>>>e|r<<32-e;function Us(r){let e=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),t=new Uint8Array(Math.ceil((r.length+9)/64)*64);t.set(r),t[r.length]=128;let s=new DataView(t.buffer);s.setUint32(t.length-8,Math.floor(r.length/536870912)),s.setUint32(t.length-4,r.length*8>>>0);let i=new Uint32Array(64);for(let o=0;o<t.length;o+=64){for(let g=0;g<16;g++)i[g]=s.getUint32(o+g*4);for(let g=16;g<64;g++){let y=L(i[g-15],7)^L(i[g-15],18)^i[g-15]>>>3,R=L(i[g-2],17)^L(i[g-2],19)^i[g-2]>>>10;i[g]=i[g-16]+y+i[g-7]+R|0}let[d,l,c,h,p,v,f,u]=e;for(let g=0;g<64;g++){let y=u+(L(p,6)^L(p,11)^L(p,25))+(p&v^~p&f)+Ns[g]+i[g]|0,R=(L(d,2)^L(d,13)^L(d,22))+(d&l^d&c^l&c)|0;u=f,f=v,v=p,p=h+y|0,h=c,c=l,l=d,d=y+R|0}e[0]+=d,e[1]+=l,e[2]+=c,e[3]+=h,e[4]+=p,e[5]+=v,e[6]+=f,e[7]+=u}let n=new Uint8Array(32),a=new DataView(n.buffer);for(let o=0;o<8;o++)a.setUint32(o*4,e[o]);return n}var qs=30*6e4,qt=1e3,js=100,Ks=60*1024,le=()=>globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function F(){try{return globalThis.localStorage}catch{return}}var ue=class{api;closingApi;perfApi;closingPerfApi;flushMs;flushAt;now;anonKey;sessionKey;onceKey;events=[];samples=[];timer;memoryAnon;memorySession;memoryOnce;appVersion;stopAuto;session;consent;identifyPending=!1;listeners=new Set;people={set:e=>this.person({set:e}),setOnce:e=>this.person({set_once:e}),unset:e=>this.person({unset:[...e]}),add:e=>this.person({add:e})};constructor(e,t,s,i,n,a,o={}){this.session=s,this.consent=i;let d={send:c=>e.send(this.granted("analytics")?{...c,headers:{...c.headers,[J]:n.id}}:c)};this.api=Z.client(d);let l={send:c=>(this.granted("analytics")?e:t).send(c)};this.perfApi=Z.client(l),this.closingApi=Z.client({send:c=>d.send({...c,keepalive:!0})}),this.closingPerfApi=Z.client({send:c=>l.send({...c,keepalive:!0})}),this.flushMs=o.flushMs??5e3,this.flushAt=o.flushAt??20,this.now=o.now??Date.now,this.anonKey=`palbase.analytics.anonymous.${a}`,this.sessionKey=`palbase.analytics.session.${a}`,this.onceKey=`palbase.analytics.once.${a}`,s.onChange(c=>{c==="SIGNED_IN"?(this.identifyPending=!0,this.soon()):c==="SIGNED_OUT"&&(this.identifyPending=!1,this.reset())}),i.onChange((c,h)=>{h!=="granted"&&(c==="analytics"?(this.events=[],this.identifyPending=!1,this.samples=this.samples.map($e),this.reset()):c==="performance"&&(this.samples=[]))})}capture(e,t){for(let i of this.listeners)i(e,t);if(!this.granted("analytics"))return;let s=this.now();this.hold({event:e,distinct_id:this.distinctId(),properties:t,timestamp:s,session_id:this.sessionId(s),...this.appVersion?{app_version:this.appVersion}:{}})}captureOnce(e,t,s){if(!this.granted("analytics"))return;let i=this.sessionId(this.now()),n=this.readOnce(),a=n?.session===i?n.keys:[];a.includes(e)||(this.writeOnce({session:i,keys:[...a,e].slice(-500)}),this.capture(t,s))}readOnce(){try{let e=F()?.getItem(this.onceKey);if(e)return JSON.parse(e)}catch{}return this.memoryOnce}writeOnce(e){this.memoryOnce=e;try{F()?.setItem(this.onceKey,JSON.stringify(e))}catch{}}onEvent(e){return this.listeners.add(e),()=>this.listeners.delete(e)}page(e={}){let t=globalThis.location,s=globalThis.document,i=e.url??(t?`${t.origin}${Q(t.pathname)}`:"");if(!i)return;let n=e.referrer??Hs(s?.referrer);this.capture("$pageview",{...e.properties,url:i,...e.title??s?.title?{title:e.title??s?.title}:{},...n?{referrer:n}:{}})}async identify(e){this.identifyPending=!1;let t=this.session.snapshot()?.userId;!t||!this.granted("analytics")||(await this.flush(),await this.sendIdentify(this.api,t,e))}async sendIdentify(e,t,s){try{await e.identify({body:{distinct_id:t,anonymous_id:this.anonymousId(),traits:s,timestamp:this.now(),sent_at:this.now()}})}catch{}}reset(){this.memoryAnon=void 0,this.memorySession=void 0,this.memoryOnce=void 0;try{F()?.removeItem(this.anonKey),F()?.removeItem(this.sessionKey),F()?.removeItem(this.onceKey)}catch{}}async flush(e=!1){this.timer&&clearTimeout(this.timer),this.timer=void 0,this.granted("analytics")||(this.events=[]),this.granted("performance")?this.granted("analytics")||(this.samples=this.samples.map($e)):this.samples=[];let t=e?this.closingApi:this.api,s=e?this.closingPerfApi:this.perfApi,i=this.now(),n=this.session.snapshot()?.userId;for(this.identifyPending&&n&&this.granted("analytics")&&(this.identifyPending=!1,await this.sendIdentify(t,n));this.events.length>0;){let a=this.take(this.events,e);try{await t.batch({body:{events:a.map(o=>({...o,sent_at:i}))}})}catch{}}for(;this.samples.length>0;){let a=this.take(this.samples,e);try{await s.sendPerf({body:{items:a}})}catch{}}}start(e={}){this.stopAuto?.(),this.appVersion=e.appVersion;let t=globalThis;if(typeof t.addEventListener!="function"||typeof globalThis.document>"u")return()=>{};let s=[];e.pageViews!==!1&&s.push(this.watchPages(t)),e.webVitals!==!1&&s.push($s((a,o)=>this.sample("web_vital",a,o))),e.network!==!1&&s.push(this.watchFetch(t));let i=()=>{document.visibilityState==="hidden"&&this.flush(!0)},n=()=>{this.flush(!0)};return document.addEventListener("visibilitychange",i),t.addEventListener("pagehide",n),s.push(()=>{document.removeEventListener("visibilitychange",i),t.removeEventListener("pagehide",n)}),this.stopAuto=()=>{for(let a of s.splice(0))a();this.stopAuto=void 0},this.stopAuto}granted(e){return this.consent.state(e)==="granted"}async person(e){if(!this.granted("analytics"))return;let t=this.session.snapshot()?.userId,s=this.now();try{await this.api.setPersonProperties({body:{...e,...t?{}:{distinct_id:this.anonymousId()},timestamp:s,sent_at:s}})}catch{}}hold(e){this.events.length>=qt&&this.events.shift(),this.events.push(e),this.soon()}sample(e,t,s,i={}){if(!this.granted("performance"))return;this.samples.length>=qt&&this.samples.shift();let n={row_id:le(),trace_type:e,name:t,value:Math.max(0,s),timestamp:this.now(),...i};this.samples.push(this.granted("analytics")?{...n,distinct_id:this.distinctId()}:$e(n)),this.soon()}soon(){if(this.events.length+this.samples.length>=this.flushAt){this.flush();return}this.timer||(this.timer=setTimeout(()=>{this.flush()},this.flushMs),this.timer.unref?.())}take(e,t){let s=e.splice(0,js);if(!t)return s;for(;s.length>1&&JSON.stringify(s).length>Ks;)e.unshift(s.pop());return s}distinctId(){return this.session.snapshot()?.userId??this.anonymousId()}anonymousId(){let e=F();try{let t=e?.getItem(this.anonKey);if(t)return t;let s=`anon_${le()}`;if(e?.setItem(this.anonKey,s),e?.getItem(this.anonKey)===s)return s}catch{}return this.memoryAnon??=`anon_${le()}`,this.memoryAnon}sessionId(e){let t=F(),s=this.memorySession;try{let n=t?.getItem(this.sessionKey);n&&(s=JSON.parse(n))}catch{}let i=s&&e-s.last<qs?{id:s.id,last:e}:{id:`ses_${le()}`,last:e};this.memorySession=i;try{t?.setItem(this.sessionKey,JSON.stringify(i))}catch{}return i.id}watchPages(e){let t="",s=!0,i,n=()=>{if(!s)return;let v=`${e.location.origin}${e.location.pathname}`;if(v===t)return;t=v;let f=`${e.location.origin}${Q(e.location.pathname)}`;i!==void 0&&clearTimeout(i),i=setTimeout(()=>{i=void 0,s&&this.page({url:f})},0)},a=e.history,o=a.pushState,d=Object.hasOwn(a,"pushState"),l=a.replaceState,c=Object.hasOwn(a,"replaceState"),h=(...v)=>{o.apply(a,v),n()},p=(...v)=>{l.apply(a,v),n()};return a.pushState=h,a.replaceState=p,e.addEventListener("popstate",n),n(),()=>{s=!1,i!==void 0&&(clearTimeout(i),i=void 0),a.pushState===h&&(d?a.pushState=o:delete a.pushState),a.replaceState===p&&(c?a.replaceState=l:delete a.replaceState),e.removeEventListener("popstate",n)}}watchFetch(e){let t=e.fetch;if(typeof t!="function")return()=>{};let s=async(i,n)=>{let a=performance.now(),o=i instanceof Request?i:void 0,d=(n?.method??o?.method??"GET").toUpperCase(),l;try{l=new URL(o?.url??String(i),e.location.href)}catch{l=void 0}let c=!!l&&l.pathname.startsWith("/analytics/")||Ws(n?.headers??o?.headers);try{let h=await t(i,n);return l&&!c&&this.sample("network",`${d} ${l.origin}${Q(l.pathname)}`,performance.now()-a,{attrs:{status:String(h.status)},...h.headers.get("x-request-id")?{request_id:h.headers.get("x-request-id")}:{}}),h}catch(h){throw l&&!c&&this.sample("network",`${d} ${l.origin}${Q(l.pathname)}`,performance.now()-a,{attrs:{status:"0"}}),h}};return e.fetch=s,()=>{e.fetch===s&&(e.fetch=t)}}};function $e(r){let{distinct_id:e,request_id:t,...s}=r;return s}var Fs=r=>r.entryType==="layout-shift"&&"value"in r&&"hadRecentInput"in r,Vs=r=>r.entryType==="event"||r.entryType==="first-input";function ce(r,e){if(!(typeof PerformanceObserver>"u"))try{let t=new PerformanceObserver(s=>e(s.getEntries()));return t.observe({type:r,buffered:!0}),t}catch{return}}function $s(r){if(typeof document>"u"||typeof performance>"u"||typeof performance.getEntriesByType!="function")return()=>{};let e=0,t=0,s=0,i=[ce("largest-contentful-paint",l=>{for(let c of l)e=Math.max(e,c.startTime)}),ce("layout-shift",l=>{for(let c of l)Fs(c)&&!c.hadRecentInput&&(t+=c.value)}),ce("event",l=>{for(let c of l)Vs(c)&&(s=Math.max(s,c.duration))}),ce("paint",l=>{for(let c of l)c.name==="first-contentful-paint"&&r("FCP",c.startTime)})],n=performance.getEntriesByType("navigation")[0];n&&n.responseStart>0&&r("TTFB",n.responseStart);let a=!1,o=()=>{a||(a=!0,e>0&&r("LCP",e),r("CLS",t),s>0&&r("INP",s))},d=()=>{document.visibilityState==="hidden"&&o()};return document.addEventListener("visibilitychange",d),()=>{o(),document.removeEventListener("visibilitychange",d);for(let l of i)l?.disconnect()}}function Ws(r){if(!r)return!1;try{return new Headers(r).has("next-router-prefetch")}catch{return!1}}var Gs=/^[a-z][a-z0-9_-]{0,31}$/;function Q(r){return r.split("/").map(e=>{if(e==="")return e;let t=e.split(";",1)[0],s=t.toLowerCase();return Gs.test(s)&&(s.match(/\d/g)?.length??0)<=2&&t.slice(1)===s.slice(1)&&s.split(/[-_]/).every(n=>n.length<=16)?s:":id"}).join("/")}function Hs(r){if(!r)return"";try{let e=new URL(r);return`${e.origin}${Q(e.pathname)}`}catch{return Q(r.split(/[?#]/,1)[0]??"")}}var zt=/^custom\.[a-z0-9_]{1,48}$/,Bs=/^[a-z][a-z0-9_]{0,63}$/,Kt=r=>Bs.test(r)||zt.test(r),Js=50,Ft=[5e3,3e4,12e4,6e5],Qs=100,pe=class{userApi;deviceApi;session;socket;ref;installation;start;textVersion;customKeys;storeKey;now;kept;listeners=new Set;engaged=!1;platformKeys;watch;sending;sendAgain=!1;retryTimer;retries=0;readFor;stale=!1;lastW=0;lastChosen=0;gpc=globalThis.navigator?.globalPrivacyControl===!0;constructor(e){let t=e.options??{};for(let[d,l]of Object.entries(t.start??{})){if(!Kt(d))throw new TypeError(`consent.start: ${JSON.stringify(d)} is not a consent key (a platform key, or custom.<name>)`);if(l!=="granted"&&l!=="denied")throw new TypeError(`consent.start.${d} is granted or denied`)}for(let d of t.customKeys??[])if(!zt.test(d))throw new TypeError(`consent.customKeys: ${JSON.stringify(d)} is not custom.<name> (a-z, 0-9 and _, 48 at most)`);if(t.textVersion!==void 0&&(t.textVersion===""||t.textVersion.length>64))throw new TypeError("consent.textVersion: 1 to 64 characters");this.userApi=e.userApi,this.deviceApi=e.deviceApi,this.session=e.session,this.socket=e.socket,this.ref=e.ref,this.installation=e.installation,this.start={...t.start},this.textVersion=t.textVersion,this.customKeys=[...t.customKeys??[]],this.storeKey=`palbase.consent.${e.origin}.${e.installation.id}`,this.now=e.now??Date.now;let s=this.load(),i=()=>Nt(this.installation)?{}:{unknown:{on:!0,w:this.stamp()}},n={whose:null,install:this.installation.id,choices:{},unsent:[]};typeof s!="object"?this.kept={...n,...s==="unreadable"?{unknown:{on:!0,w:this.stamp()}}:i()}:s.whose==null&&s.install!==void 0&&s.install!==this.installation.id?this.kept={...n,unsent:s.unsent.filter(d=>d.user!==null),...s.keys?{keys:s.keys}:{},...i()}:this.kept=s,e.session.onChange((d,l)=>{this.engaged&&(d==="SIGNED_IN"&&l?this.signedIn(l):(d==="SIGNED_OUT"||d==="SESSION_EXPIRED")&&this.signedOut())});let a=globalThis;typeof a.addEventListener=="function"&&(a.addEventListener("storage",d=>{(d.key===this.storeKey||d.key===null)&&this.reload()}),a.addEventListener("online",()=>{this.engaged&&this.send()}));let o=this.kept;(e.options!==void 0||s!=="empty"&&(o.unknown?.on||o.unsent.length>0||o.link!==void 0||Object.keys(o.choices).length>0))&&this.engage()}async keys(){return this.engage(),[...(await this.platform()).map(t=>({key:t.key,category:t.category,title:{...t.title},description:{...t.description},ads:t.ads})),...this.customKeys.map(t=>({key:t,category:"custom",title:{},description:{},ads:!1}))]}state(e){if(T(this.kept)!==this.holder()||this.gpcRefuses(e))return"denied";let t=Wt(this.kept,e);return t&&t.state!=="unset"?t.state:this.kept.unknown?.on?"denied":this.start[e]}owesRead(){return this.stale||this.kept.unknown?.on===!0||T(this.kept)!==this.holder()||Object.values(this.kept.choices).some(e=>e.provisional)}holder(){let e=this.session.snapshot()?.userId;return e?`user:${e}`:`device:${this.installation.id}`}lastDeniedAt(e){let t=this.kept.choices[e]?.last_denied_at;return t?new Date(t):void 0}set(e,t){this.setMany({[e]:t})}setMany(e){let t=Object.entries(e);for(let[a,o]of t){if(!Kt(a))throw new TypeError(`${JSON.stringify(a)} is not a consent key (a platform key, or custom.<name>)`);if(o!=="granted"&&o!=="denied")throw new TypeError(`${a}: a choice is granted or denied`)}if(t.length===0)return;this.engage();let s=this.chosenAt(),i=this.session.snapshot()?.userId??null,n=this.states();for(let[a,o]of t)this.queue({key:a,state:o,source:"app",chosen_at:s,user:i,...this.textVersion!==void 0?{text_version:this.textVersion}:{}});this.commit(n),this.send()}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}async region(){this.engage();let e=await this.subject();if(this.readFor!==e)try{await this.read(e)}catch(t){if(!this.kept.region)throw t}return this.kept.region}async needsAsking(e){this.engage();let t=await this.subject();this.readFor!==t&&await this.read(t).catch(()=>{});let s=e??(await this.keys()).map(d=>d.key),i=await this.platform().catch(()=>this.kept.keys??[]),n=new Set(i.filter(d=>d.ads).map(d=>d.key)),a=this.kept.region?.jurisdiction==="us",o=new Date(this.now());return o.setUTCMonth(o.getUTCMonth()-12),s.filter(d=>{let l=this.kept.choices[d];return a&&n.has(d)&&l?.last_denied_at!==void 0&&Date.parse(l.last_denied_at)>o.getTime()?!1:!l||l.state==="unset"?!0:this.textVersion!==void 0&&l.source==="app"&&l.text_version!==this.textVersion})}engage(){this.engaged||(this.engaged=!0,this.session.session().then(e=>{e&&!this.watch&&this.follow(e),this.send(),this.refuseByGpc()}))}async subject(){return(await this.session.session())?.userId??null}secret(){return{[O]:A(this.installation)}}platform(){return this.platformKeys??=this.deviceApi.listConsentKeys().then(e=>(this.kept={...this.kept,keys:e.data.keys},this.commit(),e.data.keys),e=>{if(this.platformKeys=void 0,this.kept.keys)return this.kept.keys;throw e}),this.platformKeys}async read(e){let s=(await(e===null?this.deviceApi:this.userApi(e)).getConsents({query:{installation_id:this.installation.id},headers:this.secret()})).data;this.adopt(s,e)}adopt(e,t,s=[]){if(this.kept={...this.kept,region:e.region},(this.session.snapshot()?.userId??null)!==t){this.commit();return}let i=this.states(),n={};for(let u of e.choices)n[u.key]={state:u.state,source:u.source,chosen_at:u.chosen_at,...u.text_version!==void 0?{text_version:u.text_version}:{},...u.last_denied_at!==void 0?{last_denied_at:u.last_denied_at}:{}};let a=s.filter(u=>n[u.key]?.state!==u.state||Date.parse(n[u.key]?.chosen_at??"")!==Date.parse(u.chosen_at)).map(u=>N(u.key,u)),d=T(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`)?Object.entries(this.kept.choices).filter(([,u])=>u.provisional).map(([u,g])=>N(u,g)):[];if(a.length+d.length>0&&(this.kept={...this.kept,void:U([...this.kept.void??[],...a,...d])}),t===null&&this.kept.resetAt!==void 0)for(let[u,g]of Object.entries(n))Date.parse(g.chosen_at)<this.kept.resetAt&&delete n[u];let l=new Set(Object.entries(n).map(([u,g])=>N(u,g))),c=(this.kept.void??[]).filter(u=>l.has(u));c.length>0&&(this.kept={...this.kept,unvoid:U([...this.kept.unvoid??[],...c])});let h=Xt(this.kept),p;if(T(this.kept)!==(t===null?`device:${this.installation.id}`:`user:${t}`))p=n;else{p={};for(let u of[...new Set([...Object.keys(this.kept.choices),...Object.keys(n)])].sort()){let g=this.kept.choices[u],y=g&&!g.provisional&&!h.has(N(u,g))?g:void 0,R=n[u],x=R&&(!y||Date.parse(R.chosen_at)>=Date.parse(y.chosen_at))?R:y;x&&(p[u]=x)}}for(let u of this.kept.unsent){if(u.user!==null&&u.user!==t||u.user===null&&u.device!==this.installation.id||u.user===null&&t!==null)continue;let g=p[u.key];g&&Date.parse(g.chosen_at)>Date.parse(u.chosen_at)||(p[u.key]=Vt(u,g))}let{install:v,...f}=this.kept;this.kept={...f,whose:t,...t===null?{install:this.installation.id}:{},choices:p,unknown:{on:!1,w:this.stamp()}},this.readFor=t,this.stale=!1,this.commit(i),this.refuseByGpc()}async refused(e,t,s){let i=t===e&&T(this.kept)===(t===null?`device:${this.installation.id}`:`user:${t}`),n=U([...this.kept.void??[],...s.map(d=>N(d.key,d))]);if(!i){this.kept={...this.kept,void:n},this.commit();return}let a=this.states(),o={...this.kept.choices};for(let d of s){if(this.kept.unsent.some(c=>c.key===d.key&&(c.user===null||c.user===e)&&Date.parse(c.chosen_at)>Date.parse(d.chosen_at)))continue;let l=o[d.key];o[d.key]={state:"denied",source:"app",chosen_at:d.chosen_at,...l?.last_denied_at!==void 0?{last_denied_at:l.last_denied_at}:{},provisional:!0}}this.kept={...this.kept,choices:o,void:n},this.commit(a);try{await this.read(e)}catch{this.stale=!0}}queue(e){let t=e.user===null?{...e,device:this.installation.id}:e,s=T(this.kept)===(t.user===null?`device:${this.installation.id}`:`user:${t.user}`);this.kept={...this.kept,unsent:Yt([...this.kept.unsent,t]),...s?{choices:{...this.kept.choices,[t.key]:Vt(t,this.kept.choices[t.key])}}:{}}}send(){if(this.sendAgain=!0,this.sending)return;let e=(async()=>{for(;this.sendAgain;)this.sendAgain=!1,await this.sendUnsent()||(this.sendAgain=!1)})();this.sending=e,e.finally(()=>{this.sending===e&&(this.sending=void 0)})}async sendUnsent(){this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=void 0;let e=this.session.snapshot()?.userId??null;try{e=await this.subject();let t=await this.sendOf(null,e);if(e!==null&&(this.kept.link===e||t)){let s;try{s=(await this.userApi(e).linkConsents({headers:this.secret(),body:{installation_id:this.installation.id}})).data}catch(i){if(!Bt(i))throw i}if(this.kept.link===e){let{link:i,...n}=this.kept;this.kept=n,this.commit()}if(s)this.adopt(s,e);else{let i=this.states();this.kept={...this.kept,unknown:{on:!0,w:this.stamp()}},this.commit(i)}}if(e!==null&&await this.sendOf(e,e),this.owesRead()&&(await this.read(e),this.owesRead()))throw new Error("the choices are not read yet");return this.retries=0,!0}catch{return(this.session.snapshot()?.userId??null)!==e?(this.sendAgain=!0,!0):(this.retryLater(),!1)}}async sendOf(e,t){let s=!1;for(;;){let i=this.nextGroup(e);if(i.length===0)return s;let n=i[0],a=e===null?this.deviceApi:this.userApi(e),o;try{o=(await a.chooseConsents({headers:this.secret(),body:{installation_id:this.installation.id,...n.source==="gpc"?{source:"gpc"}:{},...n.text_version!==void 0?{text_version:n.text_version}:{},choices:i.map(d=>({key:d.key,state:d.state,chosen_at:d.chosen_at}))}})).data}catch(d){if(!Bt(d))throw d;if(i.length>1){this.kept={...this.kept,unsent:this.kept.unsent.map(l=>i.some(c=>Ht(c,l))?{...l,alone:!0}:l)},this.commit();continue}}this.kept={...this.kept,unsent:this.kept.unsent.filter(d=>!i.some(l=>Ht(l,d))),done:U([...this.kept.done??[],...i.map(fe)])},this.commit(),o?(s=!0,e===t&&this.adopt(o,e,i)):await this.refused(t,e,i)}}nextGroup(e){let t=this.kept.unsent.filter(a=>a.user===e&&(e!==null||a.device===this.installation.id)),s=t[0];if(!s)return[];let i=[],n=new Set;if(s.alone)return[s];for(let a of t)if(!n.has(a.key)&&(n.add(a.key),!(a.alone||a.source!==s.source||a.text_version!==s.text_version)&&(i.push(a),i.length===Js)))break;return i}retryLater(){if(this.retryTimer)return;let e=Ft[Math.min(this.retries,Ft.length-1)];this.retries++,this.retryTimer=setTimeout(()=>{this.retryTimer=void 0,this.send()},e),this.retryTimer.unref?.()}signedIn(e){this.readFor=void 0,this.kept={...this.kept,link:e.userId},this.commit(),this.follow(e),this.send()}signedOut(){this.unfollow(),this.readFor=void 0;let e=this.states(),t=this.chosenAt(),s=new Set([...Object.entries(this.kept.choices).filter(([,o])=>o.state!=="unset").map(([o])=>o),...this.kept.unsent.filter(o=>o.user===null&&o.device===this.installation.id).map(o=>o.key),...Object.keys(this.start),...this.customKeys,...(this.kept.keys??[]).map(o=>o.key)]),i={};for(let[o,d]of Object.entries(this.kept.choices))i[o]={state:"unset",source:"app",chosen_at:t,...d.last_denied_at!==void 0?{last_denied_at:d.last_denied_at}:{}};let n=o=>o.user===null&&o.device===this.installation.id,a=this.kept.unsent.filter(n);this.kept={whose:null,install:this.installation.id,resetAt:Date.parse(t),choices:i,unsent:this.kept.unsent.filter(o=>!n(o)),...this.kept.void?{void:this.kept.void}:{},...this.kept.unvoid?{unvoid:this.kept.unvoid}:{},done:U([...this.kept.done??[],...a.map(fe)]),...this.kept.region?{region:this.kept.region}:{},...this.kept.keys?{keys:this.kept.keys}:{},...this.kept.gpc?{gpc:this.kept.gpc}:{},...this.kept.unknown?{unknown:this.kept.unknown}:{}};for(let o of s)this.queue({key:o,state:"unset",source:"app",chosen_at:t,user:null});this.commit(e),this.send(),this.refuseByGpc()}follow(e){this.unfollow();let t=this.socket.channel(`consents:${this.ref}:${e.userId}`),s={userId:e.userId,channel:t,off:()=>{},version:-1},i=[t.on("broadcast",n=>{n.event==="changed"&&this.changed(s,We(n.payload))}),t.on("state_snapshot",n=>this.held(s,We(Qt(n.entries)))),t.on("state_diff",n=>this.held(s,We(Qt(n.set))))];s.off=()=>i.forEach(n=>n()),this.watch=s,t.join().catch(()=>{})}unfollow(){let e=this.watch;e&&(this.watch=void 0,e.off(),e.channel.leave())}held(e,t){t!==void 0&&this.changed(e,t)}changed(e,t){if(this.watch===e){if(t!==void 0){if(t<=e.version)return;e.version=t}this.read(e.userId).catch(()=>{this.watch===e&&(this.stale=!0,this.retryLater())})}}gpcRefuses(e){if(!this.gpc||!(this.kept.keys??[]).some(n=>n.key===e&&n.ads))return!1;let t=Wt(this.kept,e);if(t?.state==="denied")return!1;let s=this.kept.gpc?.[T(this.kept)],i=s!==void 0&&(this.kept.whose!=null||s>=(this.kept.resetAt??0));return!(t?.state==="granted"&&t.source==="app"&&i&&Date.parse(t.chosen_at)>s)}async refuseByGpc(){if(!this.gpc||T(this.kept)!==this.holder())return;let e;try{e=await this.platform()}catch{return}if(T(this.kept)!==this.holder())return;let t=this.session.snapshot()?.userId??null,s=e.filter(a=>a.ads&&this.gpcRefuses(a.key)&&!this.kept.unsent.some(o=>o.key===a.key&&o.source==="gpc"&&o.user===t));if(s.length===0)return;let i=this.chosenAt(),n=this.states();for(let a of s)this.queue({key:a.key,state:"denied",source:"gpc",chosen_at:i,user:t});this.kept={...this.kept,gpc:{...this.kept.gpc,[T(this.kept)]:Date.parse(i)}},this.commit(n),this.send()}states(){let e=new Map;for(let t of[...Object.keys(this.start),...Object.keys(this.kept.choices)])e.set(t,this.state(t));return e}tell(e){let t=this.states();for(let s of new Set([...e.keys(),...t.keys()])){let i=t.get(s);if(e.get(s)!==i)for(let n of[...this.listeners])try{n(s,i)}catch{}}}load(){let e;try{e=Jt()?.getItem(this.storeKey)}catch{return"unreadable"}if(e==null)return"empty";try{let t=JSON.parse(e);if(Zs(t))return t}catch{}return"unreadable"}reload(){let e=this.load();if(typeof e!="object"){this.write();return}let t=this.states();this.kept=$t(e,this.kept,"theirs",this.holder()),T(e)===T(this.kept)&&Gt(this.kept)!==Gt(e)&&this.write(),this.tell(t);let s=this.session.snapshot()?.userId??null;this.engaged&&this.kept.unsent.some(i=>i.user!==null&&i.user===s||i.user===null&&i.device===this.installation.id)&&this.retryLater(),this.engaged&&this.refuseByGpc()}commit(e=this.states()){let t=this.load();typeof t=="object"&&(this.kept=$t(t,this.kept,"ours",this.holder())),this.write(),this.tell(e)}write(){try{Jt()?.setItem(this.storeKey,JSON.stringify(this.kept))}catch{}}chosenAt(){return this.lastChosen=Math.max(this.now(),this.lastChosen+1),new Date(this.lastChosen).toISOString()}stamp(){let e=this.kept,t=e?Math.max(0,e.unknown?.w??0):0;return this.lastW=Math.max(this.now(),this.lastW+1,t+1),this.lastW}};function Vt(r,e){let t=r.state==="denied"?r.chosen_at:e?.last_denied_at;return{state:r.state,source:r.source,chosen_at:r.chosen_at,...r.text_version!==void 0?{text_version:r.text_version}:{},...t!==void 0?{last_denied_at:t}:{}}}function N(r,e){return`${r}|${e.provisional?"provisional":e.state}|${Date.parse(e.chosen_at)}`}function Xt(r){let e=new Set(r.unvoid??[]);return new Set((r.void??[]).filter(t=>!e.has(t)))}var he={denied:2,unset:1,granted:0};function zs(r,e,t,s){let i=e&&!s.has(N(r,e))?e:void 0,n=t&&!s.has(N(r,t))?t:void 0;if(!i||!n)return i??n;let a=Date.parse(i.chosen_at),o=Date.parse(n.chosen_at);return a!==o?a>o?i:n:he[i.state]!==he[n.state]?he[i.state]>he[n.state]?i:n:i.provisional?n:i}function Xs(r,e){return!r||!e?r??e:e.w>r.w||e.w===r.w&&e.on?e:r}function $t(r,e,t,s){let i=U([...r.void??[],...e.void??[]]),n=U([...r.unvoid??[],...e.unvoid??[]]),a=Xt({void:i,unvoid:n}),o={},d,l={...r.gpc};for(let[y,R]of Object.entries(e.gpc??{}))l[y]=Math.max(l[y]??0,R);let c;if(T(r)===T(e)){d=e;for(let y of[...new Set([...Object.keys(r.choices),...Object.keys(e.choices)])].sort()){let R=zs(y,r.choices[y],e.choices[y],a);R&&(o[y]=R)}c=Xs(r.unknown,e.unknown)}else{d=T(e)===s?e:T(r)===s?r:t==="ours"?e:r;for(let[y,R]of Object.entries(d.choices))a.has(N(y,R))||(o[y]=R);c=d.unknown}let h=U([...r.done??[],...e.done??[]]),p=Yt([...r.unsent,...e.unsent]).filter(y=>!h.includes(fe(y))),v=t==="ours"?e:r,f=t==="ours"?r:e,u=v.region??f.region,g=v.keys??f.keys;return{whose:d.whose??null,...d.whose==null&&d.install!==void 0?{install:d.install}:{},...d.whose==null&&(r.resetAt!==void 0||e.resetAt!==void 0)&&T(r)===T(e)?{resetAt:Math.max(r.resetAt??0,e.resetAt??0)}:d.whose==null&&d.resetAt!==void 0?{resetAt:d.resetAt}:{},choices:o,unsent:p,...h.length>0?{done:h}:{},...i.length>0?{void:i}:{},...n.length>0?{unvoid:n}:{},...v.link!==void 0?{link:v.link}:{},...u?{region:u}:{},...Object.keys(l).length>0?{gpc:l}:{},...g?{keys:g}:{},...c?{unknown:c}:{}}}function fe(r){return`${r.user??`device:${r.device??""}`}|${r.key}|${r.state}|${r.source}|${r.chosen_at}`}function Wt(r,e){let t=r.choices[e];if(!t||r.whose!=null||r.resetAt===void 0||Date.parse(t.chosen_at)>=r.resetAt)return t}function T(r){return r.whose!=null?`user:${r.whose}`:`device:${r.install??""}`}function U(r){return[...new Set(r)].slice(-Qs)}function Gt(r){return JSON.stringify(r,(e,t)=>typeof t=="object"&&t!==null&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort(([s],[i])=>s.localeCompare(i))):t)}function Yt(r){let e=new Map;for(let t of r){let s=fe(t),i=e.get(s);e.set(s,i?i.alone||!t.alone?i:{...i,alone:!0}:t)}return[...e.values()].sort((t,s)=>Date.parse(t.chosen_at)-Date.parse(s.chosen_at))}var Ys=new Set(["granted","denied","unset"]);function Zs(r){if(typeof r!="object"||r===null)return!1;let e=r;if(typeof e.choices!="object"||e.choices===null||Array.isArray(e.choices)||!Array.isArray(e.unsent))return!1;let t=(o,d)=>{if(typeof o!="object"||o===null)return!1;let l=o;return Ys.has(l.state)&&typeof l.chosen_at=="string"&&(!d||typeof l.key=="string")},s=o=>o===void 0||typeof o=="object"&&o!==null&&typeof o.on=="boolean"&&typeof o.w=="number",i=r,n=o=>o===void 0||Array.isArray(o)&&o.every(d=>typeof d=="string"),a=i.whose===void 0||i.whose===null||typeof i.whose=="string";return Object.values(e.choices).every(o=>t(o,!1))&&e.unsent.every(o=>t(o,!0))&&(i.gpc===void 0||typeof i.gpc=="object"&&i.gpc!==null&&Object.values(i.gpc).every(o=>typeof o=="number"))&&s(i.unknown)&&n(i.done)&&n(i.void)&&n(i.unvoid)&&a}function Ht(r,e){return r.key===e.key&&r.user===e.user&&r.state===e.state&&r.source===e.source&&r.chosen_at===e.chosen_at}function Bt(r){return r instanceof b&&r.status>=400&&r.status<500&&r.status!==401&&r.status!==408&&r.status!==429}function Jt(){try{return globalThis.localStorage}catch{return}}function Qt(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="object"&&e!==null?e.v:void 0}function We(r){let e=typeof r=="object"&&r!==null?r.version:void 0;return typeof e=="number"&&Number.isFinite(e)?e:void 0}var ei=`
3
3
  :host{display:block;color-scheme:light dark;font:15px/1.4 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
4
4
  .list{display:flex;flex-direction:column;gap:8px;margin:0;padding:0;list-style:none}
5
5
  .item{position:relative;display:flex;gap:12px;align-items:flex-start;padding:12px 40px 12px 12px;border-radius:12px;background:var(--bg);color:var(--fg);cursor:pointer;outline:none}
@@ -1,2 +1,2 @@
1
- /*! palbase 0.77.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.78.1 — Palbase SDK License (see LICENSE) */
2
2
  import{lstat as E,mkdir as k,readdir as b,readFile as j,rename as F,rm as J,writeFile as R}from"node:fs/promises";import{join as $}from"node:path";var o="palbase/strings",g="_meta.json",m=3,S=r=>typeof r=="object"&&r!==null&&!Array.isArray(r);function w(r){try{return Intl.getCanonicalLocales(r)[0]}catch{return}}function O(r,t){try{return JSON.parse(r)}catch(n){throw new Error(`${t} is not JSON: ${n.message}`)}}async function M(r){let t=$(r,o);try{if(!(await E(t)).isDirectory())throw new Error(`${o} is not a directory: the strings live in a directory of their own`)}catch(e){if(e.code==="ENOENT")return;throw e}let n=new Map;for(let e of await b(t,{withFileTypes:!0}))if(!(e.name.startsWith(".")||!e.name.endsWith(".json"))){if(!e.isFile())throw new Error(`${o}/${e.name} is not a regular file`);n.set(e.name,await j($(t,e.name),"utf8"))}return n.size===0?void 0:n}async function N(r){let t=await M(r);if(t===void 0)return;let n=t.get(g);if(n===void 0)throw new Error(`${o}/${g} is missing: it names the source language, and without it the language files are not a table`);let e=O(n,`${o}/${g}`);if(!S(e))throw new Error(`${o}/${g}: not a JSON object`);let c=e.version;if(c!==m)throw new Error(`${o}/${g}: version ${JSON.stringify(c)} is not one this reads (${m})`);let s=e.source;if(typeof s!="string"||w(s)!==s)throw new Error(`${o}/${g}: source ${JSON.stringify(s)} is not a language tag as it is written (${w(String(s))??"en, en-US, zh-Hans"})`);let f=new Map;for(let u of[...t.keys()].sort()){if(u===g)continue;let i=u.slice(0,-5),a=`${o}/${u}`,l=w(i);if(l===void 0)throw new Error(`${a}: ${JSON.stringify(i)} is not a language tag`);if(l!==i)throw new Error(`${a}: the language is written ${l} \u2014 name the file ${l}.json`);if(i===s)throw new Error(`${a}: ${i} is the source language \u2014 its text is the key itself, and it has no file`);if(i==="und"||i==="root"||i.startsWith("x-"))throw new Error(`${a}: ${i} is no language a request names \u2014 name the file for one (en, de, pt-BR)`);let d=O(t.get(u),a);if(!S(d))throw new Error(`${a}: not a JSON object of "sentence": "translation"`);let h=new Map;for(let[p,y]of Object.entries(d)){if(typeof y!="string")throw new Error(`${a}: the translation of ${JSON.stringify(p)} is not a string`);h.set(p,y)}f.set(i,h)}return{format:c,source:s,languages:f}}async function P(r){let t=await N(r);if(t===void 0)return;let n={};Object.setPrototypeOf(n,null);for(let[e,c]of t.languages)for(let[s,f]of c)Object.hasOwn(n,s)||(n[s]={},Object.setPrototypeOf(n[s],null)),n[s][e]=f;return{source:t.source,locales:[t.source,...t.languages.keys()],strings:n}}export{P as a};
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.78.1 — Palbase SDK License (see LICENSE) */
2
+ import{a as o,b as u}from"./35KQJQ77.js";var c={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,draft_changed:()=>"the agent's draft was saved again since its revision was read: read it again (ai.agents.get) and make the change on that one",agent_defined_in_code:()=>"this agent is the backend's code's (its build's contract names it): it is changed in the code, and has no draft, versions or delete",nothing_to_publish:()=>"the agent's draft is the version published already: save a change to it first (ai.agents.saveDraft)",agent_not_published:()=>"the agent has no version published yet: publish its draft (ai.agents.publish) before a chat or an answer names it",ai_budget_reached:()=>"the project's monthly AI budget is spent: Palbase's models serve it again when the month turns (UTC) or an owner or admin raises the budget (Studio \u203A AI \u203A Settings, or palbase ai:settings:set --monthly-budget) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",ai_payment_required:()=>"the month's free AI dollar is spent and the project has no paid rights now to pay for Palbase's models (it is on Free, at its month's limit, or its payment account has an unpaid charge): move it to Pay as you go (Studio \u203A Billing) \u2014 or connect the project's own key for the model's provider (ai.connectProvider), which its provider bills",billing_unavailable:t=>`Palbase's billing did not say whether its models serve the project${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,client_handoff_disabled:()=>"app users may not hand off chats in this project: enable allow_client_handoff in AI settings, or trigger the handoff from your server",superseded:()=>"this chat has already moved to a newer execution target generation",machine_not_found:()=>"the target machine is not enrolled in this project's runner pools",harness_unavailable:()=>"the requested ACP CLI harness is not ready on the target machine",handoff_requires_idle:()=>"a turn is currently running in this chat: pass when: 'after_turn' or when: 'now' to hand off"},g=new WeakSet;function f(t){if(!(t instanceof u)||g.has(t))return t;let e=c[t.code];if(!e)return t;let r=new u({op:t.op,status:t.status,code:t.code,message:`${e(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return g.add(r),r}function m(t){return t.catch(e=>{throw f(e)})}function h(t){if(typeof t!="object"||t===null)return;let e=t,r=e.data;if(typeof e.type!="string"||typeof r!="object"||r===null||Array.isArray(r))return;let n=o(r),i=typeof e.id=="number"&&Number.isSafeInteger(e.id)?e.id:0,s=p(e.type,n,i);return s!==void 0&&s.type!=="history"&&typeof t.at=="string"&&t.at!==""&&(s.at=t.at),s}function p(t,e,r){switch(t){case"message":return typeof e.client_id=="string"?{type:"message",seq:r,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let n={...e,type:"turn",seq:r};return n.waiting??=null,n.error??=null,n}case"text":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"text",response_id:e.response_id,offset:n,text:typeof e.text=="string"?e.text:""}}case"reset":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"reset",response_id:e.response_id,offset:n}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let n=e.omitted_bytes;return{...e,type:"tool",seq:r,omittedBytes:typeof n=="number"&&Number.isSafeInteger(n)&&n>0?n:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:r}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let n=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:r,response_id:e.response_id,run_id:n,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:r,response_id:e.response_id,run_id:n,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:n,...i}=e;return{...i,type:"goal",seq:r,...typeof n=="number"?{turn:n}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let n=e.items.filter(s=>typeof s=="object"&&s!==null&&(s.role==="user"||s.role==="assistant")&&typeof s.text=="string"),i=e.forked_from;return{type:"history",forked_from:i&&typeof i.chat_id=="string"?i:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:n}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:r,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:r,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};case"session.handed_off":return typeof e.to_target!="object"||e.to_target===null||typeof e.generation!="number"?void 0:{type:"session.handed_off",seq:r,chat_id:typeof e.chat_id=="string"?e.chat_id:"",generation:e.generation,...typeof e.from_target=="object"&&e.from_target!==null?{from_target:e.from_target}:{},to_target:e.to_target,reason:typeof e.reason=="string"?e.reason:"",workspace_seq:typeof e.workspace_seq=="number"?e.workspace_seq:0};case"session.machine_status":return typeof e.status!="string"?void 0:{type:"session.machine_status",seq:r,chat_id:typeof e.chat_id=="string"?e.chat_id:"",machine_id:typeof e.machine_id=="string"?e.machine_id:"",status:e.status,...e.failover_at===null||typeof e.failover_at=="string"?{failover_at:e.failover_at}:{}};case"context.offloaded":return{type:"context.offloaded",seq:r,call_id:typeof e.call_id=="string"?e.call_id:"",...typeof e.storage=="string"?{storage:e.storage}:{},...typeof e.ref=="string"?{ref:e.ref}:{},...typeof e.original_bytes=="number"?{original_bytes:e.original_bytes}:{},...typeof e.stub_bytes=="number"?{stub_bytes:e.stub_bytes}:{}};case"context.compacted":return{type:"context.compacted",seq:r,...typeof e.format=="string"?{format:e.format}:{},...typeof e.messages_compacted=="number"?{messages_compacted:e.messages_compacted}:{},...typeof e.tokens_before=="number"?{tokens_before:e.tokens_before}:{},...typeof e.tokens_after=="number"?{tokens_after:e.tokens_after}:{},...typeof e.preserved_attachments_count=="number"?{preserved_attachments_count:e.preserved_attachments_count}:{},...typeof e.project_directives_count=="number"?{project_directives_count:e.project_directives_count}:{},...typeof e.cache_friendly=="boolean"?{cache_friendly:e.cache_friendly}:{}};default:return}}function y(t){if(typeof t!="object"||t===null||Array.isArray(t))return;let e=o(t);if(!(typeof e.chat_id!="string"||e.chat_id===""||typeof e.run_status!="string"||typeof e.target_generation!="number")&&!(typeof e.target_summary!="object"||e.target_summary===null))return{chat_id:e.chat_id,run_status:e.run_status,...typeof e.active_run_id=="string"&&e.active_run_id!==""?{active_run_id:e.active_run_id}:{},...typeof e.workspace_id=="string"&&e.workspace_id!==""?{workspace_id:e.workspace_id}:{},target_generation:e.target_generation,target_summary:e.target_summary,updated_at:typeof e.updated_at=="string"?e.updated_at:""}}function v(t){let e=0;for(let r=0;r<t.length;r++){let n=t.charCodeAt(r);n<128?e+=1:n<2048?e+=2:n>=55296&&n<=56319&&r+1<t.length&&(t.charCodeAt(r+1)&64512)===56320?(e+=4,r++):e+=3}return e}function d(t,e){if(e<=0)return 0;let r=0;for(let n=0;n<t.length;n++){let i=t.charCodeAt(n),s=3,a=1;if(i<128?s=1:i<2048?s=2:i>=55296&&i<=56319&&n+1<t.length&&(t.charCodeAt(n+1)&64512)===56320&&(s=4,a=2),r+=s,r>=e)return n+a;n+=a-1}return t.length}function w(t,e){return t.slice(d(t,e))}export{m as a,h as b,y as c,v as d,d as e,w as f};
@@ -1,4 +1,4 @@
1
- /*! palbase 0.77.0 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.78.1 — Palbase SDK License (see LICENSE) */
2
2
  var Rt=d=>[...new Uint8Array(d)].map(t=>t.toString(16).padStart(2,"0")).join(""),_t=d=>`pw-font-${d}`;function ne(d){return(typeof d=="string"?/^asset:([0-9a-f-]{36})$/.exec(d):null)?.[1]}async function an(d,t={}){let l={},a=t.fetch??((c,p)=>globalThis.fetch(c,p));return await Promise.all(d.map(async c=>{try{if(!/^https:\/\//.test(c.url))return;let p=await a(c.url,{signal:t.signal,credentials:"omit"});if(!p.ok)return;let g=await p.arrayBuffer();if(g.byteLength!==c.bytes&&c.bytes>0||Rt(await globalThis.crypto.subtle.digest("SHA-256",g))!==c.sha256.toLowerCase())return;let b=At(c.kind,new Uint8Array(g));if(b===void 0)return;let y=await Et(c,g,b,t);y&&(l[c.id]=y)}catch{}})),l}var C=(d,t,l=0)=>d.length>=l+t.length&&t.every((a,c)=>d[l+c]===a),W=d=>[...d].map(t=>t.charCodeAt(0));function At(d,t){switch(d){case"image":return C(t,[137,80,78,71,13,10,26,10])?"image/png":C(t,[255,216,255])?"image/jpeg":C(t,W("RIFF"))&&C(t,W("WEBP"),8)?"image/webp":void 0;case"video":return C(t,W("ftyp"),4)?C(t,W("qt "),8)?"video/quicktime":"video/mp4":C(t,[26,69,223,163])?"video/webm":void 0;case"font":return C(t,W("wOF2"))?"font/woff2":C(t,W("wOFF"))?"font/woff":C(t,W("OTTO"))?"font/otf":C(t,[0,1,0,0])||C(t,W("true"))?"font/ttf":void 0;case"html":return C(t,[80,75,3,4])||C(t,[80,75,5,6])?"application/zip":void 0;default:return}}async function Et(d,t,l,a){switch(d.kind){case"image":case"video":return{kind:d.kind,url:URL.createObjectURL(new Blob([t],{type:l}))};case"font":{let c=_t(d.id),p=globalThis.FontFace,g=a.fonts??globalThis.document?.fonts;if(!p||!g)return;let h=new p(c,t,{display:"block"});return await h.load(),g.add(h),{kind:"font",url:"",family:c}}case"html":{let c=await Lt(new Uint8Array(t)),p=Ot(c);return p===void 0?void 0:{kind:"html",url:"",html:p}}}}async function Lt(d){let t=new DataView(d.buffer,d.byteOffset,d.byteLength),l=-1;for(let h=d.length-22;h>=Math.max(0,d.length-22-65535);h--)if(t.getUint32(h,!0)===101010256){l=h;break}if(l<0)throw new Error("not a zip");let a=t.getUint16(l+10,!0),c=t.getUint32(l+16,!0),p=new Map,g=0;for(let h=0;h<a;h++){if(t.getUint32(c,!0)!==33639248)throw new Error("a broken zip");let b=t.getUint16(c+10,!0),y=t.getUint32(c+20,!0),m=t.getUint32(c+24,!0),v=t.getUint16(c+28,!0),A=t.getUint16(c+30,!0),P=t.getUint16(c+32,!0),R=t.getUint32(c+42,!0),x=new TextDecoder().decode(d.subarray(c+46,c+46+v));if(c+=46+v+A+P,x.endsWith("/"))continue;if(x.startsWith("/")||x.split("/").includes(".."))throw new Error("a path leaving the zip");if(g+=m,p.size>=200||g>20971520)throw new Error("a zip too large");let T=R+30+t.getUint16(R+26,!0)+t.getUint16(R+28,!0),O=d.subarray(T,T+y);if(b===0)p.set(x,O);else if(b===8)p.set(x,await Pt(O));else throw new Error("a zip entry compressed another way")}return p}async function Pt(d){let t=new Response(new Uint8Array(d)).body.pipeThrough(new DecompressionStream("deflate-raw"));return new Uint8Array(await new Response(t).arrayBuffer())}var Tt={html:"text/html",css:"text/css",js:"text/javascript",mjs:"text/javascript",json:"application/json",png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",webp:"image/webp",gif:"image/gif",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",woff2:"font/woff2",woff:"font/woff",ttf:"font/ttf",otf:"font/otf"};function qe(d,t){let l=Tt[d.split(".").pop()?.toLowerCase()??""]??"application/octet-stream",a="";for(let c=0;c<t.length;c+=32768)a+=String.fromCharCode(...t.subarray(c,c+32768));return`data:${l};base64,${btoa(a)}`}var $t="default-src 'none'; img-src data:; media-src data:; font-src data:; style-src 'unsafe-inline' data:; script-src 'unsafe-inline' data:";function Ot(d){let t=d.get("index.html");if(!t)return;let l=new TextDecoder().decode(t),a=y=>new TextDecoder().decode(d.get(y)),c=y=>{let m=y.replace(/^\.\//,"").split(/[?#]/)[0];return d.has(m)?m:void 0},p=y=>y.replace(/url\(\s*(['"]?)([^'")]+)\1\s*\)/g,(m,v,A)=>{let P=c(A);return P?`url("${qe(P,d.get(P))}")`:m}),g=globalThis.DOMParser;if(!g)return;let h=new g().parseFromString(l,"text/html");for(let y of[...h.querySelectorAll('link[rel~="stylesheet"][href]')]){let m=c(y.getAttribute("href")),v=h.createElement("style");v.textContent=m?p(a(m)):"",y.replaceWith(v)}for(let y of[...h.querySelectorAll("style")])y.textContent=p(y.textContent??"");for(let y of[...h.querySelectorAll("[src], [href], [poster]")])for(let m of["src","href","poster"]){let v=y.getAttribute(m);if(v===null)continue;let A=c(v);A?y.setAttribute(m,qe(A,d.get(A))):/^(https?:)?\/\//i.test(v)&&y.removeAttribute(m)}for(let y of[...h.querySelectorAll("[style]")])y.setAttribute("style",p(y.getAttribute("style")??""));let b=h.createElement("meta");return b.setAttribute("http-equiv","Content-Security-Policy"),b.setAttribute("content",$t),h.head.prepend(b),`<!doctype html>${h.documentElement.outerHTML}`}var K=(d,t,l)=>`M${d-l} ${t}a${l} ${l} 0 1 0 ${2*l} 0a${l} ${l} 0 1 0 ${-2*l} 0`,de={ad_free:["M3 7h18v10H3z","M4 4l16 16"],bell:["M6 16v-5a6 6 0 0 1 12 0v5l2 2H4z","M10 21a2 2 0 0 0 4 0"],bolt:["M13 2L4 14h7l-1 8 9-12h-7z"],book:["M5 4h11a3 3 0 0 1 3 3v13H8a3 3 0 0 1-3-3z","M5 17a3 3 0 0 1 3-3h11"],chart:["M3 20h18","M6 20v-8","M11 20V5","M16 20v-6","M21 20V9"],chat:["M4 5h16v11H9l-5 4z"],check:["M5 12l5 5 9-10"],check_circle:[K(12,12,9),"M8 12l3 3 5-6"],clock:[K(12,12,9),"M12 7v5l3 2"],cloud:["M7 18a4 4 0 0 1-.5-7.97A6 6 0 0 1 18 9a4.5 4.5 0 0 1-.5 9z"],crown:["M3 8l4 4 5-7 5 7 4-4-2 11H5z"],download:["M12 4v11","M7 10l5 5 5-5","M4 20h16"],gift:["M3 9h18v4H3z","M5 13v8h14v-8","M12 9v12","M12 9C10 5 6 5 6 7.5S12 9 12 9zm0 0c2-4 6-4 6-1.5S12 9 12 9z"],globe:[K(12,12,9),"M3 12h18","M12 3a14 14 0 0 1 0 18a14 14 0 0 1 0-18z"],heart:["M12 20s-7-4.5-9-9a4.5 4.5 0 0 1 9-3 4.5 4.5 0 0 1 9 3c-2 4.5-9 9-9 9z"],infinity:["M7 9a3 3 0 1 0 0 6c3 0 7-6 10-6a3 3 0 1 1 0 6c-3 0-7-6-10-6z"],lock_open:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 7.5-2"],music:["M9 18V5l11-2v13",K(6,18,3),K(17,16,3)],people:[K(9,8,3.5),"M2 20a7 7 0 0 1 14 0","M16 4.5a3.5 3.5 0 0 1 0 7","M18 14a6 6 0 0 1 4 6"],person:[K(12,8,4),"M4 21a8 8 0 0 1 16 0"],photo:["M3 5h18v14H3z",K(8.5,9.5,1.5),"M3 17l5-5 4 4 3-3 6 6"],shield:["M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z"],sparkles:["M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z","M19 15l.8 2.2L22 18l-2.2.8L19 21l-.8-2.2L16 18l2.2-.8z"],star:["M12 3l2.8 5.7 6.2.9-4.5 4.4 1 6.2L12 17.3l-5.5 2.9 1-6.2L3 9.6l6.2-.9z"],video:["M3 6h12v12H3z","M15 10l6-3v10l-6-3z"],arrow_right:["M4 12h15","M13 6l6 6-6 6"],calendar:["M4 6h16v15H4z","M4 10h16","M8 3v5","M16 3v5"],close:["M6 6l12 12","M18 6L6 18"],lock:["M5 11h14v10H5z","M8 11V7a4 4 0 0 1 8 0v4"],play:["M7 4l13 8-13 8z"],quote:["M5 17c3 0 4-2 4-5V7H4v5h3","M15 17c3 0 4-2 4-5V7h-5v5h3"],trophy:["M7 4h10v5a5 5 0 0 1-10 0z","M7 6H4v2a3 3 0 0 0 3 3","M17 6h3v2a3 3 0 0 1-3 3","M12 14v4","M8 21h8","M9 18h6v3H9z"]};var Be="http://www.w3.org/2000/svg";function pe(d,t,l){let a=d.createElementNS(Be,"svg");a.setAttribute("viewBox","0 0 24 24"),a.setAttribute("width",String(l)),a.setAttribute("height",String(l)),a.setAttribute("fill","none"),a.setAttribute("stroke","currentColor"),a.setAttribute("stroke-width","2"),a.setAttribute("stroke-linecap","round"),a.setAttribute("stroke-linejoin","round"),a.setAttribute("aria-hidden","true"),a.setAttribute("focusable","false");for(let c of t){let p=d.createElementNS(Be,"path");p.setAttribute("d",c),a.append(p)}return a}var dn=2,pn=2,f=(d,t=!1)=>({kind:"value",value:"plain",def:d,required:t}),j=d=>({kind:"value",value:"color",def:d}),We=d=>({kind:"value",value:"spacing",def:d}),zt=d=>({kind:"value",value:"radius",def:d}),G=(d=!1)=>({kind:"text",required:d}),Me=(d,t=!1)=>({kind:"list",item:d,required:t}),se=(d,t=!1)=>({kind:"object",item:d,required:t}),Ke=(d=!1)=>({kind:"component",required:d}),Re={kind:"components"},Ge={stack:{axis:f("vertical"),spacing:We(0),align:f("center"),distribution:f("start"),scroll:f(!1),children:Re},text:{text:G(),spans:Me("span"),font:f(),size:f(),weight:f(),line_height:f(),letter_spacing:f(),color:{kind:"value",value:"textColor",def:"text"},align:f("center"),max_lines:f(),uppercase:f(!1)},image:{src:f(void 0,!0),fit:f("fit"),aspect:f(),mask:se("mask"),overlay:{kind:"value",value:"textColor"},alt:G(),decorative:f(!1)},icon:{name:f(void 0,!0),color:j("accent"),size:f(24)},video:{src:f(void 0,!0),poster:f(),autoplay:f(!0),loop:f(!0),mute:f(!0),controls:f(!1),fit:f("fill"),aspect:f(),alt:G()},button:{action:se("action",!0),content:Ke(!0)},purchase_button:{content:Ke(!0),package:f()},package:{product:f(void 0,!0),plan:f(void 0,!0),selected:f(!1),offer:f(),children:Re},tabs:{},switch:{},carousel:{pages:Re,peek:f(0),spacing:f(8),loop:f(!1),auto_advance_ms:f(),indicator:se("indicator"),height:f("")},countdown:{},timeline:{items:Me("timeline_item",!0),line_color:j("accent"),line_width:f(2),icon_color:j("on_accent"),color:j("text"),spacing:f(16)},features:{items:Me("feature",!0),icon_color:j("accent"),color:j("text"),spacing:f(12)},spacer:{size:We()},divider:{color:j("muted"),thickness:f(1)},custom_html:{src:f(void 0,!0),height:f("",!0)}},Ht={style:{padding:{kind:"edges"},margin:{kind:"edges"},width:f(""),height:f(""),max_width:f(),background:{kind:"fill"},border:se("border"),corners:{kind:"corners"},shadow:se("shadow"),opacity:f(1)},border:{width:f(),color:j("")},shadow:{color:j(""),radius:f(0),x:f(0),y:f(0)},linear:{type:f(""),angle:f(180),stops:f()},radial:{type:f(""),center_x:f(.5),center_y:f(.5),radius:f(.5),stops:f()},image_fill:{type:f(""),src:f(),fit:f("fill")},video_fill:{type:f(""),src:f(),poster:f(),loop:f(!0)},animation:{type:f(""),duration_ms:f(300),delay_ms:f(0),easing:f("ease_out")},action:{type:f(""),url:f(),sheet:f(),package:f()},mask:{shape:f(""),radius:zt(0),depth:f(16)},span:{text:G(!0),bold:f(!1),italic:f(!1),underline:f(!1),strikethrough:f(!1),color:j(""),link:f()},timeline_item:{icon:f(void 0,!0),title:G(!0),text:G(),color:j("")},feature:{icon:f(void 0,!0),text:G(!0)},indicator:{style:f("dots"),color:j("muted"),active_color:j("accent"),size:f(8),spacing:f(6)},typography:{font:f("system"),size:f(),weight:f(400),line_height:f(),letter_spacing:f(0),text_style:f("body")}},Xe=new Set(["package","purchase_button"]),Ct={action:{type:f(""),url:f(),link:f(),sheet:f(),placement:f(),name:f(),value:f(),offer:f(),code:G(),dismiss:f(!0)},presentation:{type:f(""),position:f("bottom"),auto_dismiss_seconds:f(),dismissible:f(!0),backdrop:j("#00000080")}},jt={modal:["type","dismissible","backdrop"],fullscreen:["type"],banner:["type","position","auto_dismiss_seconds","dismissible"],slide_in:["type","position","auto_dismiss_seconds","dismissible"],toast:["type","position","auto_dismiss_seconds","dismissible"],card:["type"]},Ft={linear:"linear",radial:"radial",image:"image_fill",video:"video_fill"},Nt=["top","bottom","leading","trailing"],Dt=["top_leading","top_trailing","bottom_leading","bottom_trailing"],Jt=Object.keys(Ge),un=Jt.filter(d=>!Xe.has(d)),Ye=/\{\{\s*([^{}]*?)\s*\}\}/g,Q=(d,t)=>typeof d=="object"&&d!==null&&Object.hasOwn(d,t),M=d=>typeof d=="object"&&d!==null&&!Array.isArray(d)?d:{},I=d=>Array.isArray(d)?d:[],X=(d,t)=>d??t;function It(d){let t="";for(let l of new TextEncoder().encode(d)){let a=String.fromCharCode(l);t+=/^[A-Za-z0-9._~-]$/.test(a)?a:`%${l.toString(16).toUpperCase().padStart(2,"0")}`}return t}function Vt(d){let t=Math.floor(d/86400),l=Math.floor(d%86400/3600),a=Math.floor(d%3600/60),c=d%60,p=h=>String(h).padStart(2,"0");return{countdown:t>0?`${t}d ${p(l)}:${p(a)}:${p(c)}`:l>0?`${l}:${p(a)}:${p(c)}`:`${p(a)}:${p(c)}`,days:String(t),hours:p(l),minutes:p(a),seconds:p(c)}}function fn(d){let t=[],l=c=>{if(Array.isArray(c))return c.forEach(l);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.product=="string"&&typeof p.plan=="string"){let g=`${p.product}.${p.plan}`;t.includes(g)||t.push(g)}for(let g of Object.keys(p).sort())l(p[g])},a=d;for(let c of["header","root","footer"])l(a[c]);for(let c of Object.keys(M(a.sheets)).sort())l(M(M(a.sheets)[c]).root);return t}function Ut(d){let t=new Map,l=c=>{if(Array.isArray(c))return c.forEach(l);if(typeof c!="object"||c===null)return;let p=c;if(p.type==="package"&&typeof p.offer=="string"){let g=`${p.product}.${p.plan}`;t.has(g)||t.set(g,p.offer)}for(let g of Object.keys(p).sort())l(p[g])},a=d;for(let c of["header","root","footer","sheets"])l(a[c]);return t}function gn(d,t){return Ae(d,t).tree}function Ae(d,t){return new ue("paywall",d,t).resolve()}function hn(d,t){return Ee(d,t).tree}function Ee(d,t){let{variables:l,...a}=t;return new ue("message",d,{...a,packages:{"":{...l}}}).resolve()}var ue=class{kind;d;opts;lang;texts={};palette;typography={};radii;spacing;packages;offers;selected="";tab="";paths=new WeakMap;tabsShown={};switchesOn={};countdowns={};constructor(t,l,a){this.kind=t,this.d=l,this.opts=a,this.offers=Ut(l);let c={};for(let[y,m]of Object.entries(a.packages??{})){let v={...m};this.open(y)||(m.price!==void 0?v.offer_price=m.price:delete v.offer_price),c[y]=v}this.packages=c;let p=M(this.d.locales),g=String(this.d.default_locale??""),h=a.locale;Q(p,h)||(h=h.split("-")[0]??"",Q(p,h)||(h=g)),this.lang=h;for(let y of[g,h])for(let[m,v]of Object.entries(M(p[y])))typeof v=="string"&&(this.texts[m]=v);let b=M(this.d.theme);this.palette=M(M(b.colors)[a.appearance]);for(let[y,m]of Object.entries(M(b.typography))){let v={};for(let[A,P]of Object.entries(this.objectFields("typography"))){let R=X(M(m)[A],P.def);R!=null&&(v[A]=R)}this.typography[y]=v}this.radii=M(b.radii),this.spacing=M(b.spacing)}open(t){let l=this.offers.get(t);return l!==void 0&&(this.opts.offers??[]).includes(l)}fields(t){if(!(this.kind==="message"&&Xe.has(t)))return Ge[t]}objectFields(t){return(this.kind==="message"?Ct[t]:void 0)??Ht[t]??{}}resolve(){let[t,l]=this.initialState();this.tab=t,this.selected=this.kind==="paywall"?l:"";let a={theme:{colors:this.palette,typography:this.typography,radii:this.radii,spacing:this.spacing}};this.kind==="paywall"&&(a.selected=l);let c=this.d.presentation;if(typeof c=="object"&&c!==null){let g=this.item("presentation",M(c),void 0)??{},h=jt[String(M(c).type)]??[];for(let b of Object.keys(g))h.includes(b)||delete g[b];a.presentation=g}for(let g of["header","root","footer"]){let h=this.d[g];if(typeof h=="object"&&h!==null){let b=this.component(M(h),g,"",!1);b&&(a[g]=b)}}let p={};if(typeof this.d.sheets=="object"&&this.d.sheets!==null){let g={};for(let[h,b]of Object.entries(M(this.d.sheets))){let y=this.component(M(M(b).root),`sheets.${h}.root`,"",!1);y&&(g[h]=y);let m=this.text(M(b).title,this.packages[this.selected]);m!==null&&(p[h]=m)}a.sheets=g}return{tree:a,pathOf:g=>this.paths.get(g),tabs:this.tabsShown,switches:this.switchesOn,sheetTitles:p,countdowns:this.countdowns,language:this.lang}}switchOn(t,l){return this.opts.switches&&Object.hasOwn(this.opts.switches,l)?this.opts.switches[l]:this.opts.switch?this.opts.switch==="on":t.default===!0}tabShown(t,l){let c=I(t.tabs).map(M).map(g=>String(g.id)),p=this.opts.tabs?.[l];return p!==void 0&&c.includes(p)?p:this.opts.tab?this.opts.tab:typeof t.default=="string"&&t.default!==""?t.default:c[0]??""}initialState(){let t="",l="",a="",c="",p=(h,b)=>{if(Array.isArray(h)){h.forEach((m,v)=>p(m,`${b}[${v}]`));return}if(typeof h!="object"||h===null)return;let y=h;switch(y.type){case"package":{let m=`${y.product}.${y.plan}`;a===""&&(a=m),y.selected===!0&&l===""&&(l=m);break}case"switch":{let m=this.switchOn(y,b),v=m?y.on_package:y.off_package;typeof v=="string"&&c===""&&(c=v),p(m?y.on:y.off,`${b}.${m?"on":"off"}`);return}case"tabs":{let m=this.tabShown(y,b);t===""&&(t=m),I(y.tabs).forEach((v,A)=>{let P=M(v);P.id===m&&(typeof P.package=="string"&&c===""&&(c=P.package),p(P.content,`${b}.tabs[${A}].content`))});return}}for(let m of Object.keys(y).sort())m!=="sheets"&&p(y[m],b===""?m:`${b}.${m}`)};for(let h of["header","root","footer"])p(this.d[h],h);let g=this.opts.selected||c||l||a;return[t,g]}holds(t,l){let a=l||this.selected;for(let[c,p]of Object.entries(t))switch(c){case"selected_package":if(!I(p).includes(this.selected))return!1;break;case"intro_eligible":if((this.opts.eligible??[]).includes(a)!==p)return!1;break;case"offer_open":if(this.open(a)!==p)return!1;break;case"platform":if(!I(p).includes(this.opts.platform))return!1;break;case"locale":if(!I(p).includes(this.opts.locale)&&!I(p).includes(this.lang))return!1;break;case"appearance":if(p!==this.opts.appearance)return!1;break;case"tab":if(p!==this.tab)return!1;break}return!0}component(t,l,a,c){if(typeof t.visible=="object"&&t.visible!==null&&!this.holds(M(t.visible),a))return null;let p=String(t.type),g=a,h=c;p==="package"&&(g=`${t.product}.${t.plan}`,h=g===this.selected);let b={type:p};this.paths.set(b,l),Q(t,"id")&&(b.id=t.id);let y={...M(t.style)};h&&Object.assign(y,M(M(t.states).selected)),Object.keys(y).length>0&&(b.style=this.style(y)),typeof t.animation=="object"&&t.animation!==null&&(b.animation=this.defaults(M(t.animation),this.objectFields("animation")));let m=this.packages[g||this.selected];switch(p){case"tabs":return this.tabs(t,b,l,g);case"switch":return this.switchOf(t,b,l,g,h);case"countdown":return this.countdown(t,b,l,g,h);case"purchase_button":{let v=typeof t.package=="string"?t.package:this.selected;b.package=v,this.open(v)&&(b.offer=this.offers.get(v));let A=this.component(M(t.content),`${l}.content`,v,h);return A?(b.content=A,b):null}case"package":b.product=t.product,b.plan=t.plan,b.selected=h,typeof t.offer=="string"&&(this.opts.offers??[]).includes(t.offer)&&(b.offer=t.offer)}for(let[v,A]of Object.entries(this.fields(p)??{})){if(p==="package"&&(v==="product"||v==="plan"||v==="selected"||v==="offer"))continue;let P=t[v],R=Q(t,v);switch(A.kind){case"component":{if(!R)continue;let x=this.component(M(P),`${l}.${v}`,g,h);if(!x&&A.required)return null;x&&(b[v]=x);break}case"components":{let x=[];I(P).forEach((T,O)=>{let V=this.component(M(T),`${l}.${v}[${O}]`,g,h);V&&x.push(V)}),b[v]=x;break}case"text":{let x=this.text(P,m);if(x!==null)b[v]=x;else if(A.required||p==="text"&&v==="text"&&R)return null;break}case"list":{let x=[];for(let T of I(P)){let O=this.item(A.item,M(T),m);O&&x.push(O)}if(p==="text"&&x.length===0&&R)return null;R&&(b[v]=x);break}case"object":{if(R){let x=this.object(M(P),A.item,m);if(x===null&&A.required)return null;b[v]=x}else v==="indicator"&&(b[v]=this.object({},A.item,m));break}case"value":{let x=this.value(X(P,A.def),A);x!=null&&x!==""&&(b[v]=x);break}}}return p==="text"&&this.typeStyle(b),b}typeStyle(t){if(typeof t.size!="string"){t.size!==void 0&&t.size!==null&&(t.text_style="body");return}let l=this.typography[t.size];for(let a of["font","weight","line_height","letter_spacing","text_style"])!Q(t,a)&&l?.[a]!==void 0&&l?.[a]!==null&&(t[a]=l[a]);t.size=l?.size??null}tabs(t,l,a,c){let p=this.tabShown(t,a);this.tabsShown[a]=p;let g=[];return I(t.tabs).forEach((h,b)=>{let y=M(h),m=y.id===p,v=this.component(M(y.label),`${a}.tabs[${b}].label`,c,m);if(g.push({id:y.id,selected:m,label:v}),m){let A=this.component(M(y.content),`${a}.tabs[${b}].content`,c,!1);A&&(l.content=A)}}),l.tabs=g,typeof t.bar=="object"&&t.bar!==null&&(l.bar=this.style(M(t.bar))),l}switchOf(t,l,a,c,p){let g=this.switchOn(t,a);this.switchesOn[a]=g,l.on=g;let h=this.text(t.label,this.packages[c||this.selected]);h!==null&&(l.label=h),l.tint=this.color(String(X(t.tint,"accent")));let b=g?"on":"off",y=this.component(M(t[b]),`${a}.${b}`,c,p);return y&&(l.content=y),l}countdown(t,l,a,c,p){let g=M(t.target),h=this.opts.now??Date.now(),b;if(typeof g.after_open_seconds=="number"?b=Math.trunc(g.after_open_seconds)-(this.opts.openedSecondsAgo??0):b=Math.trunc((Date.parse(String(g.at))-h)/1e3),b>0){l.state="counting",l.remaining_seconds=b,this.countdowns[a]=b;let y=this.packages,m={};for(let[A,P]of Object.entries(y))m[A]={...P,...Vt(b)};this.packages=m;let v=this.component(M(t.counting),`${a}.counting`,c,p);return v&&(l.content=v),this.packages=y,l}if(l.state="ended",l.remaining_seconds=0,typeof t.ended=="object"&&t.ended!==null){let y=this.component(M(t.ended),`${a}.ended`,c,p);y&&(l.content=y)}return l}item(t,l,a){let c={};for(let[p,g]of Object.entries(this.objectFields(t))){let h=l[p];if(g.kind==="text"){let b=this.text(h,a);if(b!==null)c[p]=b;else if(g.required)return null}else{let b=g.def,y=this.value(X(h,b),g);y!=null&&(Q(l,p)||b!=null&&b!=="")&&(c[p]=y)}}return c}object(t,l,a){if(l==="style")return this.style(t);let c=this.item(l,t,a)??{};if(l==="action")for(let p of["url","link"]){if(typeof c[p]!="string")continue;let g=qt(c[p],a);if(g===null)return null;c[p]=g}return c}defaults(t,l){let a={};for(let[c,p]of Object.entries(l)){let g=X(t[c],p.def);g!=null&&g!==""&&(a[c]=g)}return a}style(t){let l={};for(let[a,c]of Object.entries(t)){let p=this.objectFields("style")[a];if(!p){l[a]=c;continue}switch(p.kind){case"edges":l[a]=this.sides(c,Nt,this.spacing);break;case"corners":l[a]=this.sides(c,Dt,this.radii);break;case"fill":l[a]=this.fill(c);break;case"object":{let g=M(c),h={};for(let[b,y]of Object.entries(this.objectFields(p.item))){let m=X(g[b],y.def);m!=null&&m!==""&&(h[b]=this.value(m,y))}l[a]=h;break}default:l[a]=c}}return l}sides(t,l,a){let c={};for(let p of l){let g=typeof t=="object"&&t!==null?X(M(t)[p],0):t;c[p]=_e(g,a)}return c}fill(t){if(typeof t=="string")return{type:"color",color:this.color(t)};let l=M(t),a=this.defaults(l,this.objectFields(Ft[String(l.type)]??""));return Array.isArray(l.stops)&&(a.stops=l.stops.map(c=>({color:this.color(String(M(c).color)),at:M(c).at}))),a}value(t,l){if(l.kind!=="value")return t;switch(l.value){case"color":return typeof t=="string"&&t!==""?this.color(t):t;case"textColor":return typeof t=="string"?this.color(t):t==null?t:this.fill(t);case"spacing":return _e(t,this.spacing);case"radius":return _e(t,this.radii);default:return t}}color(t){let l=Object.hasOwn(this.palette,t)?this.palette[t]:void 0;return typeof l=="string"?l:t}text(t,l){let a;if(typeof t=="string")a=t;else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let p=t.t;a=typeof p=="string"&&Object.hasOwn(this.texts,p)?this.texts[p]:""}else return null;let c=!1;return a=a.replace(Ye,(p,g)=>{let h=l&&Object.hasOwn(l,g)?l[g]:void 0;return typeof h!="string"||h===""?(c=!0,""):h}),c||a.trim()===""?null:a}};function qt(d,t){let l=!1,a=d.replace(Ye,(c,p)=>{let g=t&&Object.hasOwn(t,p)?t[p]:void 0;return typeof g!="string"||g===""?(l=!0,""):It(g)});return l?null:a}function _e(d,t){return typeof d=="string"?Object.hasOwn(t,d)?t[d]:null:d}var Bt={packages:"Choose a plan",close:"Close",restore:"Restore purchases",page:(d,t)=>`${d} of ${t}`},ee={system:'-apple-system, BlinkMacSystemFont, "SF Pro Text", system-ui, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',rounded:'ui-rounded, "SF Pro Rounded", Nunito, "Varela Round", system-ui, -apple-system, sans-serif',serif:'ui-serif, "New York", "Iowan Old Style", Georgia, "Times New Roman", serif',mono:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace'},Wt=1.35,Ze=20,Kt=new Set(["button","purchase_button","package","text"]),Gt=new Set(["ar","he","fa","ur","ps","yi","dv","ug","ku","sd"]),Qe={ease_out:"cubic-bezier(0.16, 1, 0.3, 1)",ease_in_out:"cubic-bezier(0.65, 0, 0.35, 1)",spring:"cubic-bezier(0.34, 1.56, 0.64, 1)"},Xt={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"},Yt={start:"flex-start",center:"center",end:"flex-end",space_between:"space-between",space_around:"space-around",space_evenly:"space-evenly"},Zt={stack:["children"],package:["children"],button:["content"],purchase_button:["content"],tabs:["tabs","content"],switch:["content"],carousel:["pages"],countdown:["content"]},Qt={package:["selected"],purchase_button:["package"],switch:["on"],countdown:["state","remaining_seconds"]},en=`
3
3
  :host{display:block;height:100%}
4
4
  .pw2{position:relative;box-sizing:border-box;display:flex;flex-direction:column;height:100%;overflow:hidden;font-family:${ee.system};font-size:1rem;line-height:1.3;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;text-rendering:optimizeLegibility}
@@ -1,2 +1,2 @@
1
- /*! palbase 0.77.0 — Palbase SDK License (see LICENSE) */
2
- import{a as g,f as y,g as w}from"./JOVXELK5.js";import"./34HGL5FX.js";import"./FE7ZBADH.js";import{pathToFileURL as z}from"node:url";import{z as c}from"zod";async function S(r){let l=new Map,t=new Map;for(let s of r){let o=`${s.className}.${s.method}`,i=t.get(s.className);if(i!==void 0&&i!==s.file)throw new Error(`two controllers are named ${s.className} (${i}, ${s.file}): the contract tells routes apart by their class's name \u2014 rename one`);t.set(s.className,s.file),l.set(o,{returns:await x(s),throws:s.throws})}return s=>l.get(`${s.controller.name}.${s.fn}`)}async function x(r){let l=`${r.file} \u2014 ${r.className}.${r.method}`;switch(r.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let s=(await import(z(r.returns.file).href))[r.returns.exportName];if(!k(s))throw new Error(`${l}: its return type names ${r.returns.exportName}, which ${r.returns.file} exports as no schema (a zod, valibot or arktype schema)`);if(w(y(s)))throw new Error(`${l}: ${r.returns.exportName} marks an encrypted field (encrypted()) \u2014 an answer's is encrypt(value) in what the handler returns, its type Encrypted<T>, which the contract reads`);return{kind:"json",schema:s,array:r.returns.array}}case"expression":{let t=$(r.returns.expression,l);if(!k(t))throw new Error(`${l}: the schema made of its return type is not one`);return{kind:"json",schema:t,array:!1}}}}function $(r,l){let t=0,s=()=>{for(;t<r.length&&/\s/.test(r[t]);)t++},o=e=>{throw new Error(`${l}: invalid inferred return schema (${e}) at offset ${t}`)},i=e=>(s(),r.startsWith(e,t)?(t+=e.length,!0):!1),n=e=>{i(e)||o(`expected ${JSON.stringify(e)}`)},f=()=>{s(),r[t]!=='"'&&o("expected string literal");let e=t+1;for(;e<r.length;){let d=r[e];if(d==="\\"){e+=2;continue}if(d==='"'){let h=r.slice(t,e+1);return t=e+1,JSON.parse(h)}e++}return o("unterminated string literal")},p=()=>{if(s(),r[t]==='"')return f();if(r.startsWith("true",t)&&!/[A-Za-z0-9_$]/.test(r[t+4]??""))return t+=4,!0;if(r.startsWith("false",t)&&!/[A-Za-z0-9_$]/.test(r[t+5]??""))return t+=5,!1;let e=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(r.slice(t));return e?(t+=e[0].length,Number(e[0])):o("expected literal value")},u=()=>{s();let e;if(i("encrypted(")){let d=u();n(")"),e=g(d)}else if(i("z.")){let d=t;for(;t<r.length&&/[A-Za-z0-9_]/.test(r[t]);)t++;let h=r.slice(d,t);switch(n("("),h){case"string":n(")"),e=c.string();break;case"number":n(")"),e=c.number();break;case"boolean":n(")"),e=c.boolean();break;case"null":n(")"),e=c.null();break;case"undefined":n(")"),e=c.undefined();break;case"literal":{let a=p();n(")"),e=c.literal(a);break}case"array":{let a=u();n(")"),e=c.array(a);break}case"union":{n("[");let a=[];if(!i("]")){do a.push(u());while(i(","));n("]")}n(")"),a.length<2&&o("z.union requires at least two alternatives"),e=c.union(a);break}case"record":{let a=u();n(",");let m=u();n(")"),e=c.record(a,m);break}case"object":{n("{");let a={};if(!i("}")){do{let m=f();n(":"),a[m]=u()}while(i(","));n("}")}n(")"),e=c.object(a);break}default:return o(`unsupported z.${h}`)}}else return o("expected z.* or encrypted(...)");for(;i(".");){let d=t;for(;t<r.length&&/[A-Za-z0-9_]/.test(r[t]);)t++;let h=r.slice(d,t);switch(n("("),h){case"strict":n(")"),e=e.strict();break;case"nullable":n(")"),e=e.nullable();break;case"optional":n(")"),e=e.optional();break;case"length":{let a=p();if(typeof a!="number"||!Number.isInteger(a)||a<0)return o("expected non-negative integer for .length()");n(")"),e=e.length(a);break}case"regex":{n("new RegExp(");let a=f();n(")"),n(")"),e=e.regex(new RegExp(a));break}default:return o(`unsupported modifier .${h}()`)}}return e},b=u();return s(),t!==r.length&&o("unexpected trailing tokens"),b}function k(r){return typeof r=="object"&&r!==null&&typeof r["~standard"]?.validate=="function"}export{S as routeContracts};
1
+ /*! palbase 0.78.1 — Palbase SDK License (see LICENSE) */
2
+ import{a as g,f as y,g as w}from"./UUDOMSKW.js";import"./25KG2TVU.js";import"./VNUCKM7H.js";import{pathToFileURL as z}from"node:url";import{z as c}from"zod";async function S(r){let l=new Map,t=new Map;for(let s of r){let o=`${s.className}.${s.method}`,i=t.get(s.className);if(i!==void 0&&i!==s.file)throw new Error(`two controllers are named ${s.className} (${i}, ${s.file}): the contract tells routes apart by their class's name \u2014 rename one`);t.set(s.className,s.file),l.set(o,{returns:await x(s),throws:s.throws})}return s=>l.get(`${s.controller.name}.${s.fn}`)}async function x(r){let l=`${r.file} \u2014 ${r.className}.${r.method}`;switch(r.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let s=(await import(z(r.returns.file).href))[r.returns.exportName];if(!k(s))throw new Error(`${l}: its return type names ${r.returns.exportName}, which ${r.returns.file} exports as no schema (a zod, valibot or arktype schema)`);if(w(y(s)))throw new Error(`${l}: ${r.returns.exportName} marks an encrypted field (encrypted()) \u2014 an answer's is encrypt(value) in what the handler returns, its type Encrypted<T>, which the contract reads`);return{kind:"json",schema:s,array:r.returns.array}}case"expression":{let t=$(r.returns.expression,l);if(!k(t))throw new Error(`${l}: the schema made of its return type is not one`);return{kind:"json",schema:t,array:!1}}}}function $(r,l){let t=0,s=()=>{for(;t<r.length&&/\s/.test(r[t]);)t++},o=e=>{throw new Error(`${l}: invalid inferred return schema (${e}) at offset ${t}`)},i=e=>(s(),r.startsWith(e,t)?(t+=e.length,!0):!1),n=e=>{i(e)||o(`expected ${JSON.stringify(e)}`)},f=()=>{s(),r[t]!=='"'&&o("expected string literal");let e=t+1;for(;e<r.length;){let d=r[e];if(d==="\\"){e+=2;continue}if(d==='"'){let h=r.slice(t,e+1);return t=e+1,JSON.parse(h)}e++}return o("unterminated string literal")},p=()=>{if(s(),r[t]==='"')return f();if(r.startsWith("true",t)&&!/[A-Za-z0-9_$]/.test(r[t+4]??""))return t+=4,!0;if(r.startsWith("false",t)&&!/[A-Za-z0-9_$]/.test(r[t+5]??""))return t+=5,!1;let e=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(r.slice(t));return e?(t+=e[0].length,Number(e[0])):o("expected literal value")},u=()=>{s();let e;if(i("encrypted(")){let d=u();n(")"),e=g(d)}else if(i("z.")){let d=t;for(;t<r.length&&/[A-Za-z0-9_]/.test(r[t]);)t++;let h=r.slice(d,t);switch(n("("),h){case"string":n(")"),e=c.string();break;case"number":n(")"),e=c.number();break;case"boolean":n(")"),e=c.boolean();break;case"null":n(")"),e=c.null();break;case"undefined":n(")"),e=c.undefined();break;case"literal":{let a=p();n(")"),e=c.literal(a);break}case"array":{let a=u();n(")"),e=c.array(a);break}case"union":{n("[");let a=[];if(!i("]")){do a.push(u());while(i(","));n("]")}n(")"),a.length<2&&o("z.union requires at least two alternatives"),e=c.union(a);break}case"record":{let a=u();n(",");let m=u();n(")"),e=c.record(a,m);break}case"object":{n("{");let a={};if(!i("}")){do{let m=f();n(":"),a[m]=u()}while(i(","));n("}")}n(")"),e=c.object(a);break}default:return o(`unsupported z.${h}`)}}else return o("expected z.* or encrypted(...)");for(;i(".");){let d=t;for(;t<r.length&&/[A-Za-z0-9_]/.test(r[t]);)t++;let h=r.slice(d,t);switch(n("("),h){case"strict":n(")"),e=e.strict();break;case"nullable":n(")"),e=e.nullable();break;case"optional":n(")"),e=e.optional();break;case"length":{let a=p();if(typeof a!="number"||!Number.isInteger(a)||a<0)return o("expected non-negative integer for .length()");n(")"),e=e.length(a);break}case"regex":{n("new RegExp(");let a=f();n(")"),n(")"),e=e.regex(new RegExp(a));break}default:return o(`unsupported modifier .${h}()`)}}return e},b=u();return s(),t!==r.length&&o("unexpected trailing tokens"),b}function k(r){return typeof r=="object"&&r!==null&&typeof r["~standard"]?.validate=="function"}export{S as routeContracts};