palbase 0.78.0 → 0.79.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) 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/{QL2UAO36.js → 6ATOAAF5.js} +1 -1
  9. package/dist/chunks/{JSRN4NOZ.js → 6OSSTYNI.js} +2 -2
  10. package/dist/chunks/{NG4OMSEK.js → 7S3FQENY.js} +2 -2
  11. package/dist/chunks/{MFWAOKLM.js → 7Y5BCID4.js} +2 -2
  12. package/dist/chunks/{SHYJVOD2.js → H54MZKCJ.js} +1 -1
  13. package/dist/chunks/{HHKRAOVG.js → H6J3ET7R.js} +1 -1
  14. package/dist/chunks/{3X3ZT72M.js → IXCF3WHZ.js} +2 -2
  15. package/dist/chunks/JU5VP7GA.js +13 -0
  16. package/dist/chunks/{5OBOVEK6.js → KXKIZ3ZM.js} +2 -2
  17. package/dist/chunks/{MA74JJUB.js → KZ2PTXAO.js} +2 -2
  18. package/dist/chunks/L3CVM7BS.js +2 -0
  19. package/dist/chunks/{EFELMJMQ.js → M5R7OBNV.js} +2 -2
  20. package/dist/chunks/{NQUAVRMC.js → M64773TP.js} +2 -2
  21. package/dist/chunks/{XVJ3CMFN.js → MLCAO5BP.js} +2 -2
  22. package/dist/chunks/{YQQKZUVS.js → NFCM74MS.js} +2 -2
  23. package/dist/chunks/{S7C7NHZI.js → OYYGUGM3.js} +2 -2
  24. package/dist/chunks/{VP3HFVV4.js → PPZGWRCM.js} +1 -1
  25. package/dist/chunks/{AKJC5WTU.js → Q5J5SAQN.js} +1 -1
  26. package/dist/chunks/{HVRVTNMI.js → R3HD47TY.js} +1 -1
  27. package/dist/chunks/{AMKY4SZU.js → RH33COMI.js} +2 -2
  28. package/dist/chunks/{B64J3E3T.js → V3FMVRBO.js} +2 -2
  29. package/dist/chunks/{5H3UYFOC.js → XKVQ4IQL.js} +2 -2
  30. package/dist/chunks/{QOETZ4FB.js → Y4V3NO2R.js} +1 -1
  31. package/dist/chunks/{FOZVJW7G.js → Z3MUYA3L.js} +2 -2
  32. package/dist/chunks/{Q3GH7I66.js → ZWTD6MI2.js} +2 -2
  33. package/dist/cli.js +6 -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/backend/src/gateways.d.ts +2 -1
  52. package/types/cloud/src/generated/project.d.ts +2 -2
  53. package/types/internal/src/chat.d.ts +17 -0
  54. package/types/internal/src/modules/ai.d.ts +53 -8
  55. package/types/internal/src/modules/commerce.d.ts +38 -12
  56. package/types/internal/src/modules/events.d.ts +2 -2
  57. package/types/internal/src/modules/iap.d.ts +112 -101
  58. package/types/internal/src/modules/payments.d.ts +1225 -73
  59. package/types/web/src/chat.d.ts +4 -2
  60. package/dist/chunks/3I5XH3A3.js +0 -13
  61. package/dist/chunks/RP2TPMXT.js +0 -2
@@ -1,8 +1,8 @@
1
- import { sessionSummary, type AgentEvent, type ChatEvent, type ContextCompactedEvent, type ContextOffloadedEvent, type GoalEvent, type SessionHandedOffEvent, type ToolEvent, type TurnEnd, type TurnEvent, type VoiceEvent } from '../../internal/src/chat.js';
1
+ import { sessionSummary, type AgentEvent, type ChatEvent, type ContextCompactedEvent, type ContextOffloadedEvent, type GoalEvent, type SessionHandedOffEvent, type ToolEvent, type StoppedBy, type TurnEnd, type TurnEvent, type VoiceEvent } from '../../internal/src/chat.js';
2
2
  import type { ai as aiModule } from '../../internal/src/modules/index.js';
3
3
  import { type Transport } from '../../internal/src/transport.js';
4
4
  export { sessionSummary };
5
- export type { AgentEvent, ChatEvent, ContextCompactedEvent, ContextOffloadedEvent, GoalEvent, HistoryEvent, HistoryItem, Publication, SessionHandedOffEvent, SessionMachineStatusEvent, SessionSummaryEvent, ThinkingEvent, ToolEvent, TranscriptEvent, TurnEnd, TurnEvent, VoiceEvent } from '../../internal/src/chat.js';
5
+ export type { AgentEvent, ChatEvent, ContextCompactedEvent, ContextOffloadedEvent, GoalEvent, HistoryEvent, HistoryItem, Publication, SessionHandedOffEvent, SessionMachineStatusEvent, SessionSummaryEvent, ThinkingEvent, StoppedBy, ToolEvent, TranscriptEvent, TurnEnd, TurnEvent, VoiceEvent } from '../../internal/src/chat.js';
6
6
  /** A picture or a file a message carries: an image the model was shown, or a file put in the chat's workspace. */
7
7
  export interface ChatAttachment {
8
8
  kind: 'image' | 'file' | (string & {});
@@ -105,6 +105,8 @@ export interface ChatResponse {
105
105
  end: TurnEnd | (string & {}) | null;
106
106
  /** Why, when it did not complete and was not stopped: its code, its words, whether asking again may go otherwise. */
107
107
  error: TurnEvent['error'];
108
+ /** Who stopped it, when it ended stopped: a member, the project's server, or Palbase with its reason (null otherwise, or a stop from before the platform kept who asked). */
109
+ stoppedBy: StoppedBy | null;
108
110
  /** The whole answer so far. */
109
111
  text: string;
110
112
  parts: ChatPart[];
@@ -1,13 +0,0 @@
1
- /*! palbase 0.78.0 — Palbase SDK License (see LICENSE) */
2
- import{b as D,d as I,e as R}from"./5OBOVEK6.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"./VP3HFVV4.js";import{d as G}from"./JSRN4NOZ.js";import{a as E,b as Q,c as T,e as q}from"./XVJ3CMFN.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};