@theobourgeois/ytdb 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.next/BUILD_ID +1 -1
- package/.next/app-path-routes-manifest.json +6 -6
- package/.next/build-manifest.json +3 -3
- package/.next/prerender-manifest.json +5 -5
- package/.next/server/app/[connectionId]/[schema]/[table]/page.js +1 -1
- package/.next/server/app/[connectionId]/[schema]/[table]/page.js.nft.json +1 -1
- package/.next/server/app/[connectionId]/[schema]/[table]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/[connectionId]/diff/page.js +1 -1
- package/.next/server/app/[connectionId]/diff/page.js.nft.json +1 -1
- package/.next/server/app/[connectionId]/diff/page_client-reference-manifest.js +1 -1
- package/.next/server/app/[connectionId]/migrations/(index)/page.js +1 -1
- package/.next/server/app/[connectionId]/migrations/(index)/page.js.nft.json +1 -1
- package/.next/server/app/[connectionId]/migrations/(index)/page_client-reference-manifest.js +1 -1
- package/.next/server/app/[connectionId]/migrations/(index)/release/page.js +1 -1
- package/.next/server/app/[connectionId]/migrations/(index)/release/page.js.nft.json +1 -1
- package/.next/server/app/[connectionId]/migrations/(index)/release/page_client-reference-manifest.js +1 -1
- package/.next/server/app/[connectionId]/migrations/(index)/timeline/page.js +1 -1
- package/.next/server/app/[connectionId]/migrations/(index)/timeline/page.js.nft.json +1 -1
- package/.next/server/app/[connectionId]/migrations/(index)/timeline/page_client-reference-manifest.js +1 -1
- package/.next/server/app/[connectionId]/migrations/[setId]/diagram/page.js +1 -1
- package/.next/server/app/[connectionId]/migrations/[setId]/diagram/page.js.nft.json +1 -1
- package/.next/server/app/[connectionId]/migrations/[setId]/diagram/page_client-reference-manifest.js +1 -1
- package/.next/server/app/[connectionId]/migrations/[setId]/page.js +1 -1
- package/.next/server/app/[connectionId]/migrations/[setId]/page.js.nft.json +1 -1
- package/.next/server/app/[connectionId]/migrations/[setId]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/[connectionId]/migrations/[setId]/schema/page.js +1 -1
- package/.next/server/app/[connectionId]/migrations/[setId]/schema/page.js.nft.json +1 -1
- package/.next/server/app/[connectionId]/migrations/[setId]/schema/page_client-reference-manifest.js +1 -1
- package/.next/server/app/[connectionId]/migrations/[setId]/timeline/page.js +1 -1
- package/.next/server/app/[connectionId]/migrations/[setId]/timeline/page.js.nft.json +1 -1
- package/.next/server/app/[connectionId]/migrations/[setId]/timeline/page_client-reference-manifest.js +1 -1
- package/.next/server/app/[connectionId]/page.js +1 -1
- package/.next/server/app/[connectionId]/page.js.nft.json +1 -1
- package/.next/server/app/[connectionId]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/[connectionId]/query/page.js +1 -1
- package/.next/server/app/[connectionId]/query/page.js.nft.json +1 -1
- package/.next/server/app/[connectionId]/query/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page.js +1 -1
- package/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/_not-found.html +1 -1
- package/.next/server/app/_not-found.rsc +7 -7
- package/.next/server/app/_not-found.segments/_full.segment.rsc +7 -7
- package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +7 -7
- package/.next/server/app/_not-found.segments/_tree.segment.rsc +3 -3
- package/.next/server/app/api/note/route.js +1 -1
- package/.next/server/app/api/note/route.js.nft.json +1 -1
- package/.next/server/app/api/release/label/route.js +1 -1
- package/.next/server/app/api/release/label/route.js.nft.json +1 -1
- package/.next/server/app/api/release/merge/route.js +1 -1
- package/.next/server/app/api/release/merge/route.js.nft.json +1 -1
- package/.next/server/app/api/release/route.js +1 -1
- package/.next/server/app/api/release/route.js.nft.json +1 -1
- package/.next/server/app/api/release/sync/route.js +1 -1
- package/.next/server/app/api/release/sync/route.js.nft.json +1 -1
- package/.next/server/app/api/repo/route.js +1 -1
- package/.next/server/app/api/repo/route.js.nft.json +1 -1
- package/.next/server/app/index.html +1 -1
- package/.next/server/app/index.rsc +8 -8
- package/.next/server/app/index.segments/__PAGE__.segment.rsc +8 -8
- package/.next/server/app/index.segments/_full.segment.rsc +8 -8
- package/.next/server/app/index.segments/_tree.segment.rsc +3 -3
- package/.next/server/app/page.js +1 -1
- package/.next/server/app/page.js.nft.json +1 -1
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app-paths-manifest.json +6 -6
- package/.next/server/chunks/3128.js +1 -1
- package/.next/server/chunks/4809.js +1 -1
- package/.next/server/chunks/{7928.js → 4829.js} +2 -2
- package/.next/server/chunks/535.js +1 -1
- package/.next/server/chunks/5529.js +1 -1
- package/.next/server/chunks/6326.js +1 -1
- package/.next/server/chunks/6729.js +1 -1
- package/.next/server/chunks/9955.js +2 -0
- package/.next/server/chunks/9975.js +1 -0
- package/.next/server/middleware-build-manifest.js +1 -1
- package/.next/server/pages/404.html +1 -1
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/544-4b9895b378c705d5.js +1 -0
- package/.next/static/chunks/5882-93a86897269a2357.js +1 -0
- package/.next/static/chunks/{6090-6747af370e06526b.js → 6090-da786d958e55f4a0.js} +1 -1
- package/.next/static/chunks/{223-ae41c085e76173d8.js → 6204-83d5772d4de805ed.js} +1 -1
- package/.next/static/chunks/app/[connectionId]/layout-7003c682ec8f6509.js +1 -0
- package/.next/static/chunks/app/[connectionId]/migrations/(index)/layout-600db79333f35616.js +1 -0
- package/.next/static/chunks/app/[connectionId]/migrations/[setId]/layout-0301fd5781bab720.js +1 -0
- package/.next/static/chunks/app/[connectionId]/page-1a00b3257a09dd92.js +1 -0
- package/.next/static/chunks/app/{layout-2ed8b1f837adb32a.js → layout-99d6b2a5165968f9.js} +1 -1
- package/.next/static/chunks/{webpack-469ae59d9719e191.js → webpack-a9d4b191c6c579a9.js} +1 -1
- package/.next/static/css/15730e9f7c5c55ef.css +1 -0
- package/.next/static/css/7990d32d787a4f50.css +1 -0
- package/package.json +1 -1
- package/.next/server/chunks/1421.js +0 -1
- package/.next/server/chunks/2783.js +0 -2
- package/.next/static/chunks/544-624e05bf7e7a38d4.js +0 -1
- package/.next/static/chunks/5882-80bb4c4b772c9896.js +0 -1
- package/.next/static/chunks/app/[connectionId]/layout-b8ad40b3da6824ed.js +0 -1
- package/.next/static/chunks/app/[connectionId]/migrations/(index)/layout-4156ea75d3316171.js +0 -1
- package/.next/static/chunks/app/[connectionId]/migrations/[setId]/layout-a4421cb4d144bdb0.js +0 -1
- package/.next/static/chunks/app/[connectionId]/page-33495fc674565a49.js +0 -1
- package/.next/static/css/3f63e021c3018af1.css +0 -1
- package/.next/static/css/5df9ea52964d1443.css +0 -1
- /package/.next/static/{o6yjJlz_K9qa2rPdFBH6P → Kaj0NPa3KimVM4bTHOpOs}/_buildManifest.js +0 -0
- /package/.next/static/{o6yjJlz_K9qa2rPdFBH6P → Kaj0NPa3KimVM4bTHOpOs}/_ssgManifest.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
exports.id=4809,exports.ids=[4809],exports.modules={10117:(a,b)=>{"use strict";function c(a){return a.split("/").map(a=>encodeURIComponent(a)).join("/")}Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"encodeURIPath",{enumerable:!0,get:function(){return c}})},10410:(a,b,c)=>{Promise.resolve().then(c.bind(c,53253))},10937:(a,b,c)=>{"use strict";c.r(b),c.d(b,{default:()=>f});var d=c(5735),e=c(97182);async function f({children:a,params:b}){let{setId:c}=await b;return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(e.MigrationDetail,{setId:decodeURIComponent(c)}),a]})}},12229:(a,b,c)=>{"use strict";c.d(b,{En:()=>k,Pc:()=>j,jl:()=>i});var d=c(31417),e=c(300),f=c(14490),g=c(15445);let h="ytdb:queries";(0,g.q)("db-studio:queries",h);let i=144,j=800,k=(0,d.v)()((0,e.Zr)(a=>({drafts:{},editorHeight:224,history:[],setDraft:(b,c)=>a(a=>({drafts:{...a.drafts,[b]:c}})),setEditorHeight:b=>a({editorHeight:Math.min(j,Math.max(i,Math.round(b)))}),record:(b,c)=>a(a=>{let d=c.trim();if(!d)return a;let e=a.history.find(a=>a.connectionId===b&&a.sql===d),g={id:e?.id??(0,f.z)(),connectionId:b,sql:d,executedAt:Date.now()},h=0,i=0;return{history:[g,...a.history.filter(a=>a.id!==g.id)].filter(a=>!(h>=200)&&!(i+a.sql.length>1e6)&&(h+=1,i+=a.sql.length,!0))}}),remove:b=>a(a=>({history:a.history.filter(a=>a.id!==b)}))}),{name:h}))},39973:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"default",{enumerable:!0,get:function(){return e}});let d=c(40399)._(c(80061));function e(a,b){let c={};"function"==typeof a&&(c.loader=a);let e={...c,...b};return(0,d.default)({...e,modules:e.loadableGenerated?.modules})}("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},53253:(a,b,c)=>{"use strict";c.d(b,{MigrationDetail:()=>W});var d=c(48249),e=c(39973),f=c.n(e),g=c(2116),h=c.n(g),i=c(19099),j=c(67484),k=c(23171),l=c(44231),m=c(60671),n=c(86229),o=c(25297),p=c(82244),q=c(53286),r=c(20886),s=c(21883),t=c(67657),u=c(78931),v=c(72428),w=c(86408),x=c(453),y=c(12356),z=c(66280),A=c(12229),B=c(14490),C=c(30770),D=c(64759);function E({environments:a,targetId:b,onSelect:c}){let e=a.find(a=>a.connection.id===b);return e?(0,d.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,d.jsx)("span",{className:"text-xs text-muted-foreground",children:"Running against"}),(0,d.jsxs)(p.rI,{children:[(0,d.jsxs)(p.ty,{disabled:a.length<2,className:"flex h-7 cursor-pointer items-center gap-1.5 rounded-lg border bg-background px-2 text-xs font-medium outline-none hover:bg-muted/60 focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-default data-open:bg-muted/60",children:[(0,d.jsx)(C.F,{connection:e.connection}),(0,d.jsx)("span",{className:"max-w-32 truncate",children:e.connection.name})]}),(0,d.jsx)(p.SQ,{align:"start",className:"min-w-52",children:a.map(a=>(0,d.jsxs)(p._2,{onClick:()=>c(a.connection.id),className:a.connection.id===b?"font-medium":void 0,children:[(0,d.jsx)(C.F,{connection:a.connection}),(0,d.jsx)("span",{className:"min-w-0 flex-1 truncate",children:a.connection.name}),(0,d.jsxs)("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:[a.summary.applied,"/",a.summary.total]})]},a.connection.id))})]})]}):null}function F({environments:a,targetId:b,caption:c,loading:e,selection:f,onSelect:g,onCompare:h}){return(0,d.jsxs)("div",{className:"flex h-11 shrink-0 items-center border-b bg-muted/20",children:[(0,d.jsx)("span",{className:"flex h-11 shrink-0 items-center pl-3",children:(0,d.jsx)(D.aL,{checked:f.checked,label:f.checked?"Clear selection":"Select all",onToggle:()=>f.onToggle()})}),(0,d.jsx)("span",{className:"min-w-0 flex-1 truncate px-2 text-xs text-muted-foreground",children:c}),a.map(a=>{let{connection:c,summary:f,ledger:h,error:i}=a,j=c.id===b;return(0,d.jsxs)("button",{type:"button",disabled:j,"aria-current":j?"true":void 0,title:j?`${c.name} is what Apply and Revert run against`:`Run against ${c.name} instead`,onClick:()=>g(c.id),className:(0,B.cn)("flex h-11 shrink-0 flex-col items-center justify-center gap-0.5 border-l text-[11px] outline-none",D.Z_,j?"cursor-default bg-foreground/[0.04] font-medium":"cursor-pointer text-muted-foreground hover:bg-muted/60 hover:text-foreground",e&&"opacity-60"),children:[(0,d.jsxs)("span",{className:"flex max-w-full items-center gap-1",children:[(0,d.jsx)(C.F,{connection:c,className:"size-1.5"}),(0,d.jsx)("span",{className:"truncate",children:c.name})]}),i?(0,d.jsx)("span",{className:"text-destructive",children:"unreachable"}):h?(0,d.jsxs)("span",{className:"tabular-nums text-muted-foreground/80",children:[f.applied,"/",f.total,f.drifted>0&&(0,d.jsx)("span",{className:"text-amber-600 dark:text-amber-400",children:" !"})]}):(0,d.jsx)("span",{className:"text-muted-foreground/70",children:"reading…"})]},c.id)}),(0,d.jsx)("div",{className:(0,B.cn)("flex shrink-0 items-center justify-end border-l pr-2 pl-1",D.yr),children:a.length>1&&(0,d.jsx)(o.$,{size:"icon-xs",variant:"ghost",title:"Compare the two schemas","aria-label":"Compare schemas",onClick:()=>{let c=a.find(a=>a.connection.id!==b);c&&h(c.connection.id)},children:(0,d.jsx)(k.R4X,{})})})]})}var G=c(38393),H=c(88877),I=c(90863);function J({schema:a,found:b,onOpenChange:c,onSave:e}){let[f,g]=(0,j.useState)(a),h=f.trim(),i=(0,v.hD)(h),k=b.filter(a=>a.schema!==h);function l(){i&&(e(h),c(!1))}return(0,d.jsx)(G.lG,{open:!0,onOpenChange:c,children:(0,d.jsxs)(G.Cf,{className:"sm:max-w-md",children:[(0,d.jsxs)(G.c7,{children:[(0,d.jsx)(G.L3,{children:"Ledger schema"}),(0,d.jsx)(G.rr,{children:"Where each database keeps its record of what has run. Created on the first apply."})]}),(0,d.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,d.jsx)(I.J,{htmlFor:"ledger-schema",children:"Schema"}),(0,d.jsx)(H.p,{id:"ledger-schema",value:f,spellCheck:!1,autoComplete:"off","aria-invalid":h.length>0&&!i,onChange:a=>g(a.target.value),onKeyDown:a=>"Enter"===a.key&&l()}),(0,d.jsx)("p",{className:"font-mono text-xs text-muted-foreground",children:i?`${h}.${v.R9}`:"\xa0"}),h.length>0&&!i&&(0,d.jsx)("p",{className:"text-xs text-destructive",children:"Letters, digits and underscores only, starting with a letter or underscore."})]}),k.length>0&&(0,d.jsxs)("p",{className:"rounded-md border border-amber-600/25 bg-amber-500/8 px-3 py-2 text-xs",children:[k.map(a=>`${a.name} keeps its ledger in ${a.schema}`).join("; "),". That one stays where it is."]}),(0,d.jsxs)(G.Es,{children:[h!==v.aC&&(0,d.jsx)(o.$,{variant:"ghost",onClick:()=>g(v.aC),children:"Reset"}),(0,d.jsx)(o.$,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),(0,d.jsx)(o.$,{disabled:!i,onClick:l,children:"Save"})]})]})})}var K=c(60101),L=c(76829),M=c(13449),N=c(65292),O=c(29613),P=c(86871);function Q({initial:a,file:b,onOpenChange:c,onSave:e}){let[f,g]=(0,j.useState)(a),[h,i]=(0,j.useState)(!1),[k,l]=(0,j.useState)(null),m=f.trim()!==a.trim();async function n(a){if(a?.preventDefault(),m&&!h){i(!0),l(null);try{await e(f.trim()),c(!1)}catch(a){l(a instanceof Error?a.message:String(a))}finally{i(!1)}}}return(0,d.jsx)(G.lG,{open:!0,onOpenChange:a=>!h&&c(a),children:(0,d.jsx)(G.Cf,{className:"sm:max-w-lg",showCloseButton:!1,children:(0,d.jsxs)("form",{onSubmit:a=>void n(a),className:"flex flex-col gap-4",children:[(0,d.jsx)(G.c7,{children:(0,d.jsxs)("div",{className:"flex items-baseline gap-3",children:[(0,d.jsx)(G.L3,{children:"Note"}),b&&(0,d.jsx)("span",{className:"ml-auto truncate font-mono text-[11px] text-muted-foreground",title:"Written into the migration's folder, to commit with the SQL",children:b})]})}),(0,d.jsx)(P.T,{autoFocus:!0,"aria-label":"Note",value:f,maxLength:v.XG,placeholder:"Apply 0001–0007, deploy the app, then apply 0008.",className:"max-h-[50vh] min-h-32",onChange:a=>g(a.target.value),onKeyDown:a=>{"Enter"===a.key&&(a.metaKey||a.ctrlKey)&&n()}}),k&&(0,d.jsx)("p",{className:"text-xs text-destructive",children:k}),(0,d.jsxs)(G.Es,{children:[(0,d.jsx)(o.$,{type:"button",variant:"ghost",disabled:h,onClick:()=>c(!1),children:"Cancel"}),(0,d.jsx)(o.$,{type:"submit",disabled:!m||h,children:h?"Saving…":"Save"})]})]})})})}var R=c(76349),S=c(78394),T=c(17463),U=c(30904);let V=f()(async()=>{},{loadableGenerated:{modules:["components/migrations/migration-detail.tsx -> ./schema-diagram"]},ssr:!1});function W({setId:a}){let b=(0,i.useRouter)(),{connection:c,tables:e}=(0,l.k)(),f=(0,z.jV)(a=>a.addFiles),g=(0,z.jV)(a=>a.renameSet),n=(0,z.jV)(a=>a.setNote),C=(0,z.jV)(a=>a.removeSet),G=(0,z.jV)(a=>a.removeStep),H=(0,z.jV)(a=>a.record),I=(0,z.jV)(a=>a.ledgerSchema),P=(0,z.jV)(a=>a.setLedgerSchema),R=(0,z.Ss)(a),{root:_,checkout:aa}=(0,z.ox)(c.id),ab=(0,U.y)((0,v.km)(a)?_:null,aa),ac=(0,v.km)(a)?ab.data?.sets.find(b=>b.id===a)??null:R,ad=!!ac?.source,ae=(0,w.gz)(c.id),af=(0,A.En)(a=>a.setDraft),ag=(0,m.$C)(),ah=(0,M.ZG)((0,i.usePathname)()),ai=(0,L.hX)("migration"===ah.kind?ah.view:void 0),aj=(0,j.useCallback)(d=>{d!==ai&&b.push((0,M.Jn)({kind:"migration",connectionId:c.id,setId:a,view:(0,L.z2)(d)}),{scroll:!1})},[ai,b,c.id,a]),ak=(0,j.useRef)(null),[al,am]=(0,j.useState)([]);(0,j.useRef)(null),ac?.steps.map(a=>a.version).join(",");let[an,ao]=(0,j.useState)([]),ap=(0,j.useRef)(null),[aq,ar]=(0,j.useState)(null),[as,at]=(0,j.useState)(null),[au,av]=(0,j.useState)(!1),[aw,ax]=(0,j.useState)(!1),[ay,az]=(0,j.useState)(!1),[aA,aB]=(0,j.useState)(null),[aC,aD]=(0,j.useState)(null),[aE,aF]=(0,j.useState)(!1),[aG,aH]=(0,j.useState)(!1),[aI,aJ]=(0,j.useState)(!1),aK=(0,j.useRef)(null),aL=(0,j.useRef)(!1),aM=(0,j.useMemo)(()=>[c,...ae],[c,ae]),aN=aM.map(a=>a.url).join("|"),aO=(0,r.Y)(`ledgers:${I}:${aN}`,async a=>Object.fromEntries(await Promise.all(aM.map(async b=>{try{return[b.id,{ledger:await s.F.ledger(b.url,I,a),error:null}]}catch(c){if(a.aborted)throw c;return[b.id,{ledger:null,error:c instanceof Error?c.message:String(c)}]}})))),aP=aO.data?.[c.id]??null,aQ=ac?.name??"",aR=(0,j.useMemo)(()=>(0,u.Gf)(aP?.ledger,aQ),[aP?.ledger,aQ]),aS=(0,j.useMemo)(()=>aM.map(a=>{let b=aO.data?.[a.id]??null,c=(0,u.Gf)(b?.ledger,aQ);return{connection:a,ledger:c,error:b?.error??null,summary:(0,u.eh)(ac,c)}}),[aM,aO.data,ac,aQ]),aT=(0,j.useMemo)(()=>{let a=new Set;for(let b of ac?.steps??[])if(al.includes(b.version))for(let c of aS)"drifted"===(0,u.FY)(b,c.ledger)&&a.add(c.connection.id);return aM.filter(b=>a.has(b.id))},[ac,al,aS,aM]),aU=(0,r.Y)(`stored:${I}:${aT.map(a=>a.url).join("|")}`,async a=>Object.fromEntries(await Promise.all(aT.map(async b=>{try{return[b.id,{ledger:await s.F.ledger(b.url,I,a,!0),error:null}]}catch(c){if(a.aborted)throw c;return[b.id,{ledger:null,error:c instanceof Error?c.message:String(c)}]}})))),aV=`/${encodeURIComponent(c.id)}/migrations`,aW=(0,z.jV)(a=>a.history),aX=(0,j.useMemo)(()=>(0,x.x)(aS.map(a=>({connection:a.connection,ledger:a.ledger})),aW).filter(a=>a.setName===aQ),[aS,aW,aQ]),aY=(0,j.useMemo)(()=>"schema"===ai&&ac?(0,y.DT)(ac.steps.map(a=>({version:a.version,sql:a.applySql}))):null,[ai,ac]),[aZ,a$]=(0,j.useState)(null),a_=(0,j.useCallback)(a=>{a$(a),aj("diagram")},[aj]),a0=(0,j.useCallback)(a=>{ak.current=a,am(b=>b.includes(a)?b:[...b,a]),aj("migrations")},[aj]),a1=(0,u.eh)(ac,aR),a2=(0,j.useMemo)(()=>(0,u.nb)(ac,aR),[ac,aR]),a3=(0,u.kB)(ac,aR),a4=(0,j.useCallback)(a=>{aj("migrations"),at(null),ax(!1),ar({steps:[a],blockedBy:null,direction:"apply"})},[aj]),a5=(0,j.useCallback)((a,b)=>ac&&ac.name===a?ac.steps.find(a=>a.version===b)??null:null,[ac]),a6=(0,j.useCallback)(b=>{aB(f(a,b.files)),aj("migrations")},[f,a,aj]),a7=(0,N.$)(a6);function a8(a,b,c=!1){(0!==b.steps.length||b.blockedBy)&&(at(null),ax(!1),ar({...b,direction:a,recordOnly:c}))}function a9(a,b){return"apply"===b?a.applySql:a.revertSql}async function ba(){if(!aq||!ac)return;ax(!0),av(!0);let a=aq.steps.map(a=>({version:a.version,name:a.name,status:"running"}));at(a);try{let b=await s.F.rehearse(c.url,{steps:aq.steps.map(a=>({version:a.version,name:a.name,sql:a9(a,aq.direction)??""}))}),d=new Map(b.steps.map(a=>[a.version,a]));a=a.map(a=>{let c=d.get(a.version);return c?{...a,status:"ok",durationMs:c.durationMs}:b.failed?.version===a.version?{...a,status:"failed",error:b.failed.error}:{...a,status:"skipped"}})}catch(c){let b=c instanceof Error?c.message:String(c);a=a.map((a,c)=>0===c?{...a,status:"failed",error:b}:{...a,status:"skipped"})}at(a),av(!1)}function bb(a){return{steps:a,blockedBy:null}}async function bc(){if(!aq||!ac)return;aL.current=!1,ax(!1),av(!0);let a=aq.steps.map(a=>({version:a.version,name:a.name,status:"waiting"}));at(a);let b=(b,c)=>{at(a=a.map((a,d)=>d===b?{...a,...c}:a))},d=b=>{at(a=a.map((a,c)=>c>=b&&"waiting"===a.status?{...a,status:"skipped"}:a))};for(let[a,e]of aq.steps.entries()){if(aL.current){d(a);break}let f="apply"===aq.direction?e.applySql:e.revertSql;if(!f&&!aq.recordOnly){b(a,{status:"failed",error:"No revert file for this migration."}),d(a+1);break}b(a,{status:"running"});let g=crypto.randomUUID();try{let d=await s.F.migrate(c.url,{runId:g,direction:aq.direction,version:e.version,name:e.name,checksum:e.checksum,setName:ac.name,sql:f??"",revertSql:"apply"===aq.direction?e.revertSql:void 0,ledgerSchema:I,recordOnly:aq.recordOnly});b(a,{status:"ok",durationMs:d.durationMs}),H({runId:d.runId??g,setId:ac.id,setName:ac.name,connectionId:c.id,connectionName:c.name,direction:aq.direction,version:e.version,name:e.name,status:"ok",recorded:aq.recordOnly,durationMs:d.durationMs})}catch(h){let f=h instanceof Error?h.message:String(h);b(a,{status:"failed",error:f}),d(a+1),H({runId:g,setId:ac.id,setName:ac.name,connectionId:c.id,connectionName:c.name,direction:aq.direction,version:e.version,name:e.name,status:"failed",durationMs:0,error:f});break}}av(!1),aO.reload(),aU.reload(),e.reload(),a.every(a=>"ok"===a.status)&&ao([])}function bd(a){af(c.id,a),b.push(`/${encodeURIComponent(c.id)}/query`)}function be(a){ag(a)}async function bf(a){ac&&(ac.source?(await s.F.note(ac.source.root,ac.source.path,a),ab.reload()):n(ac.id,a))}async function bg(a){let b=a?.[0];aD(null),b&&aC&&ac&&aB(f(ac.id,[{path:`revert/${aC}_${b.name}`,text:await b.text()}]))}if(!ac){let b=(0,v.km)(a)&&ab.loading;return(0,d.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col",children:[(0,d.jsx)(X,{name:b?"Reading…":"Not found"}),(0,d.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center gap-2 text-muted-foreground",children:b?(0,d.jsx)("p",{className:"text-sm",children:"Reading the folder…"}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("p",{className:"text-sm",children:ab.error?ab.error:(0,v.km)(a)?"That migration is not in the folder on the branch you have checked out.":"That migration is no longer here."}),(0,d.jsx)(h(),{href:aV,className:"text-foreground underline underline-offset-4",children:"All migrations"})]})})]})}let bh=new Set(an),bi=ac.steps.filter(a=>bh.has(a.version)).length,bj=bi>0,bk=bj?(0,u.DM)(ac,aR,bh):(0,u.gj)(ac,aR),bl=bj?(0,u.n9)(ac,aR,bh):(0,u.e)(ac,aR),bm=au||aO.loading||ab.loading;return(0,d.jsxs)("div",{className:"relative flex min-h-0 flex-1 flex-col",onDragOver:a=>{!ad&&a.dataTransfer.types.includes("Files")&&(a.preventDefault(),az(!0))},children:[(0,d.jsxs)(X,{name:ac?.name??"",indexHref:aV,children:[ac.source&&(0,d.jsxs)("span",{className:"flex min-w-0 items-center gap-1 text-[11px] text-muted-foreground",title:`Read from ${ac.source.path}`,children:[(0,d.jsx)(k.WzY,{className:"size-3.5 shrink-0"}),(0,d.jsx)("span",{className:"max-w-48 truncate font-mono",children:ac.source.path}),ab.data?.git&&(0,d.jsxs)("span",{className:"shrink-0 rounded border px-1.5 font-mono text-[10px]",children:[ab.data.git.branch,ab.data.git.dirty&&"*"]})]}),(0,d.jsx)(E,{environments:aS,targetId:c.id,onSelect:be}),(0,d.jsxs)("div",{className:"ml-auto flex items-center gap-2",children:[(0,d.jsx)(o.$,{size:"icon-sm",variant:"ghost",disabled:aO.loading||ab.loading,"aria-label":"Refresh",title:ad?"Re-read the files and every environment's ledger":"Re-read every environment's ledger",onClick:function(){aO.reload(),aU.reload(),ad&&ab.reload()},children:(0,d.jsx)(k.oS8,{className:(0,B.cn)((aO.loading||ab.loading)&&"animate-spin")})}),!ad&&(0,d.jsxs)(o.$,{size:"sm",variant:"ghost",onClick:()=>az(!0),children:[(0,d.jsx)(k.FeY,{"data-icon":"inline-start"}),"Import"]}),(0,d.jsxs)(p.rI,{children:[(0,d.jsx)(p.ty,{render:(0,d.jsx)(o.$,{size:"icon-sm",variant:"ghost","aria-label":"More migration actions"}),className:"cursor-pointer",children:(0,d.jsx)(k.YKd,{})}),(0,d.jsxs)(p.SQ,{align:"end",className:"min-w-64",children:[(0,d.jsxs)(p._2,{disabled:bm||0===bk.steps.length,onClick:()=>a8("apply",bb(bk.steps),!0),children:[(0,d.jsx)(k.nXx,{}),"Mark ",bk.steps.length," as already applied"]}),(0,d.jsx)(p.mB,{}),(0,d.jsxs)(p._2,{disabled:bm||0===bl.steps.length,onClick:()=>a8("revert",bl),children:[(0,d.jsx)(k.ij9,{}),bj?`Revert ${bl.steps.length} selected on ${c.name}`:`Revert everything on ${c.name}`]}),(0,d.jsx)(p.mB,{}),(0,d.jsxs)(p._2,{onClick:()=>aJ(!0),children:[(0,d.jsx)(k.UA_,{}),ac.note?"Edit note":"Add note"]}),!ad&&(0,d.jsxs)(p._2,{onClick:()=>aH(!0),children:[(0,d.jsx)(k.NOV,{}),"Rename"]}),(0,d.jsxs)(p._2,{onClick:()=>aF(!0),children:[(0,d.jsx)(k.ooN,{}),"Ledger table",(0,d.jsxs)("span",{className:"ml-auto pl-3 font-mono text-[11px] text-muted-foreground",children:[I,".",v.R9]})]}),!ad&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(p.mB,{}),(0,d.jsx)(p._2,{variant:"destructive",onClick:function(){ac&&(C(ac.id),b.push(aV))},children:"Forget this migration"})]})]})]}),(0,d.jsxs)(o.$,{size:"sm",disabled:bm||0===bk.steps.length,onClick:()=>a8("apply",bk),children:[(0,d.jsx)(k.eGB,{"data-icon":"inline-start"}),0===bk.steps.length?bj?"Nothing selected to apply":"Up to date":`Apply ${bk.steps.length}${bj?" selected":""} to ${c.name}`]})]})]}),aA&&(0,d.jsx)(Z,{report:aA,onDismiss:()=>aB(null)}),a7.error&&(0,d.jsx)("p",{className:"border-b bg-destructive/5 px-4 py-1.5 text-xs text-destructive",children:a7.error}),"migrations"===ai&&ac.note&&(0,d.jsx)(Y,{note:ac.note,notePath:ac.source?.notePath??null,onEdit:()=>aJ(!0)}),(0,d.jsxs)("div",{className:"relative flex min-h-0 flex-1 flex-col",children:["history"===ai?(0,d.jsx)(q.F,{className:"min-h-0 flex-1",children:(0,d.jsx)(K.H,{events:aX,connections:aM,loading:aO.loading,ledgerSchema:I,setName:aQ,findStep:a5,onLedgerChange:aO.reload,onRetry:a4})}):"schema"===ai&&aY?(0,d.jsx)(q.F,{className:"min-h-0 flex-1",children:(0,d.jsx)(T.ku,{changes:aY,onVersion:a0,className:"py-2"})}):"diagram"===ai?(0,d.jsx)(V,{steps:ac.steps,live:e.data??null,at:aZ,onAt:a$,onVersion:a0}):aP?.error?(0,d.jsx)("p",{className:"flex-1 px-4 py-6 font-mono text-xs text-destructive",children:aP.error}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(F,{environments:aS,targetId:c.id,caption:bj?`${bi} selected`:function(a,b){if(b&&0===a.total)return"Reading…";let c=`${a.total} migration${1===a.total?"":"s"}`;return a.foreign>0?`${c} \xb7 ${a.foreign} not in this folder`:c}(a1,aO.loading),loading:aO.loading,selection:{checked:0!==bi&&(bi===ac.steps.length||"mixed"),onToggle:function(){if(!ac)return;let a=ac.steps.map(a=>a.version);ao(b=>b.some(b=>a.includes(b))?[]:a)}},onSelect:be,onCompare:function(a){w.lz.getState().setCompareTarget(c.id,a),b.push(`/${encodeURIComponent(c.id)}/diff`)}}),(0,d.jsxs)(q.F,{className:(0,B.cn)("min-h-0 flex-1",aO.loading&&"opacity-70"),children:[(ac?.steps.length??0)===0&&!ad&&(0,d.jsx)("div",{className:"p-6",children:(0,d.jsx)(N.k,{onFiles:a6,compact:!0})}),ac.skipped.length>0&&ad&&(0,d.jsxs)("div",{className:"border-b bg-muted/20 px-4 py-2 text-xs text-muted-foreground",children:[(0,d.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,d.jsx)(k.e5t,{className:"size-3.5 shrink-0 text-amber-600 dark:text-amber-400"}),"Skipped ",ac.skipped.length," file",1===ac.skipped.length?"":"s"]}),(0,d.jsx)("ul",{className:"mt-1 space-y-0.5 pl-5 font-mono text-[11px]",children:ac.skipped.map(a=>(0,d.jsx)("li",{children:a},a))})]}),(ac?.steps??[]).map(a=>(0,d.jsx)(D.Tj,{step:a,targetId:c.id,status:(0,u.FY)(a,aR),environments:aS.map(b=>({connection:b.connection,status:(0,u.FY)(a,b.ledger),entry:(0,u.ay)(a,b.ledger),error:b.error})),isNewestApplied:a3?.version===a.version,expanded:al.includes(a.version),busy:bm,editable:!ad,drift:function(a){let b=aS.filter(b=>"drifted"===(0,u.FY)(a,b.ledger)),d=b.find(a=>a.connection.id===c.id)??b[0];if(!d)return null;let e=aU.data?.[d.connection.id],f=e?.ledger?.entries.find(b=>b.setName===aQ&&b.version===a.version);return{connectionName:d.connection.name,appliedSql:e?.ledger?f?.applySql??null:void 0,error:e?.error??null}}(a),selected:bh.has(a.version),onSelect:b=>(function(a,b){if(!ac)return;let c=ac.steps.map(a=>a.version),d=ap.current;ap.current=a,ao(e=>{let f=!e.includes(a),g=[a];if(b&&d&&d!==a&&c.includes(d)){let[b,e]=[c.indexOf(d),c.indexOf(a)].sort((a,b)=>a-b);g=c.slice(b,e+1)}let h=new Set(e);for(let a of g)f?h.add(a):h.delete(a);return c.filter(a=>h.has(a))})})(a.version,b),onToggle:()=>{var b;return b=a.version,void am(a=>a.includes(b)?a.filter(a=>a!==b):[...a,b])},actions:{onApplyThrough:()=>a8("apply",(0,u.gj)(ac,aR,a.version)),onApplyOne:()=>a8("apply",{steps:[a],blockedBy:null}),onRevertThrough:()=>a8("revert",(0,u.e)(ac,aR,a.version)),onMarkApplied:()=>a8("apply",bb([a]),!0),onMarkPending:()=>a8("revert",bb([a]),!0),onAttachRevert:()=>{aD(a.version),window.requestAnimationFrame(()=>aK.current?.click())},onRemove:()=>ac&&G(ac.id,a.version),onOpenInEditor:bd,onShowDiagram:()=>a_(a.version)}},a.version)),a2.length>0&&(0,d.jsx)($,{entries:a2,connectionName:c.name})]})]}),ay&&!ad&&(0,d.jsx)("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-background/85 p-6",onDragOver:a=>a.preventDefault(),onDragLeave:()=>az(!1),onDrop:a=>{a.preventDefault(),az(!1),a7.importFrom(a.dataTransfer)},children:(0,d.jsx)(N.k,{onFiles:a6,className:"w-full max-w-xl bg-background"})})]}),(0,d.jsx)(L.lj,{pane:ai,onPaneChange:aj,historyCount:aX.length,migrationsLabel:"Files",showSchema:!0,caption:aY?(0,T.Zg)(aY):function({connectionName:a,summary:b,initialized:c,loading:d,foundIn:e,configuredSchema:f}){if(d&&null===c)return"Reading ledgers…";let g=[];return!1===c||b.pending>0?g.push(`${b.pending} of ${b.total} pending on ${a}`):g.push(`${a} is up to date`),b.drifted>0&&g.push(`${b.drifted} changed since applied`),e&&e!==f&&g.push(`ledger in ${e}`),g.join(" \xb7 ")}({connectionName:c.name,summary:a1,initialized:aR?.initialized??null,loading:aO.loading,foundIn:aR?.initialized?aR.schema:null,configuredSchema:I})}),(0,d.jsx)("input",{ref:aK,type:"file",accept:".sql",className:"sr-only",onChange:a=>{bg(a.target.files),a.target.value=""}}),(0,d.jsx)(O.K,{open:aG,title:"Rename migration",initial:ac.name,submitLabel:"Rename",onOpenChange:aH,onSubmit:function(a){ac&&g(ac.id,a)}}),aI&&(0,d.jsx)(Q,{initial:ac.note??"",file:ac.source?ac.source.notePath?.split(/[\\/]/).at(-1)??"README.md":null,onOpenChange:aJ,onSave:bf}),aE&&(0,d.jsx)(J,{schema:I,found:aS.filter(a=>a.ledger?.initialized).map(a=>({name:a.connection.name,schema:a.ledger?.schema??I})),onOpenChange:aF,onSave:a=>{P(a),aO.reload()}}),aq&&(0,d.jsx)(S.I,{open:!0,direction:aq.direction,connection:c,steps:aq.steps,blockedBy:aq.blockedBy,progress:as,running:au,recordOnly:aq.recordOnly??!1,note:ac.note,outOfOrder:"apply"!==aq.direction||aq.recordOnly?null:(0,u.nj)(aR,aq.steps),rehearsal:aw,onRun:()=>void bc(),onRehearse:!aq.recordOnly&&0!==aq.steps.length&&aq.steps.every(a=>{let b=a9(a,aq.direction);return!!b&&(0,t.Ol)(b).atomic})?()=>void ba():null,onStop:()=>{aL.current=!0},onClose:function(){au||(ar(null),at(null),ax(!1))}})]})}function X({name:a,indexHref:b,children:c}){let e=(0,d.jsx)(k.olY,{className:"size-4 shrink-0 text-muted-foreground"});return(0,d.jsxs)(n.X,{children:[b?(0,d.jsx)(h(),{href:b,title:"All migrations","aria-label":"All migrations",className:"flex size-6 shrink-0 items-center justify-center rounded-md outline-none hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring/60",children:e}):e,(0,d.jsx)("span",{className:"min-w-0 truncate font-medium",children:a}),c]})}function Y({note:a,notePath:b,onEdit:c}){return(0,d.jsxs)("div",{title:b?`${b} \xb7 click to edit`:"Click to edit",onClick:a=>{a.target.closest("a")||c()},className:"group flex w-full cursor-pointer items-start gap-2 border-b px-4 py-2.5 text-left text-xs hover:bg-muted/30",children:[(0,d.jsx)(k.UA_,{className:"mt-px size-3.5 shrink-0 text-muted-foreground"}),(0,d.jsx)(R.o,{text:a,className:"max-h-40 min-w-0 flex-1 overflow-y-auto"}),(0,d.jsx)("button",{type:"button","aria-label":"Edit note",onClick:a=>{a.stopPropagation(),c()},className:"mt-px shrink-0 rounded-sm text-muted-foreground opacity-0 outline-none group-hover:opacity-100 focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring",children:(0,d.jsx)(k.NOV,{className:"size-3.5"})})]})}function Z({report:a,onDismiss:b}){let c=[];return a.added>0&&c.push(`added ${a.added}`),a.updated>0&&c.push(`updated ${a.updated}`),a.reverts>0&&c.push(`${a.reverts} revert file${1===a.reverts?"":"s"}`),(0,d.jsxs)("div",{className:"flex items-start gap-2 border-b bg-muted/30 px-4 py-1.5 text-xs",children:[(0,d.jsxs)("span",{className:"min-w-0 flex-1",children:[c.length>0?`Imported: ${c.join(", ")}`:"Nothing new in those files",a.skipped.length>0&&(0,d.jsxs)("span",{className:"text-muted-foreground",children:[" ","\xb7 skipped ",a.skipped.slice(0,2).join(", "),a.skipped.length>2&&` and ${a.skipped.length-2} more`]})]}),(0,d.jsx)(o.$,{size:"xs",variant:"ghost",onClick:b,children:"Dismiss"})]})}function $({entries:a,connectionName:b}){return(0,d.jsxs)("div",{className:"border-t bg-muted/20",children:[(0,d.jsxs)("p",{className:"flex items-center gap-2 px-4 py-2 text-xs text-muted-foreground",children:[(0,d.jsx)(k.e5t,{className:"size-3.5 shrink-0 text-amber-600 dark:text-amber-400"}),"Applied on ",b,", not in this folder"]}),a.map(a=>(0,d.jsxs)("div",{className:"flex items-center gap-2 px-4 py-1.5 text-xs opacity-70",children:[(0,d.jsx)(D.oy,{status:"applied"}),(0,d.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:a.version}),(0,d.jsx)("span",{className:"min-w-0 flex-1 truncate",children:a.name||"—"}),(0,d.jsx)("span",{className:"shrink-0 text-muted-foreground/70",children:new Date(a.appliedAt).toLocaleString()})]},a.version))]})}},66958:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"BailoutToCSR",{enumerable:!0,get:function(){return e}});let d=c(49306);function e({reason:a,children:b}){throw Object.defineProperty(new d.BailoutToCSRError(a),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0})}},80061:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"default",{enumerable:!0,get:function(){return j}});let d=c(48249),e=c(67484),f=c(66958),g=c(85264);function h(a){return{default:a&&"default"in a?a.default:a}}let i={loader:()=>Promise.resolve(h(()=>null)),loading:null,ssr:!0},j=function(a){let b={...i,...a},c=(0,e.lazy)(()=>b.loader().then(h)),j=b.loading;function k(a){let h=j?(0,d.jsx)(j,{isLoading:!0,pastDelay:!0,error:null}):null,i=!b.ssr||!!b.loading,k=i?e.Suspense:e.Fragment,l=b.ssr?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(g.PreloadChunks,{moduleIds:b.modules}),(0,d.jsx)(c,{...a})]}):(0,d.jsx)(f.BailoutToCSR,{reason:"next/dynamic",children:(0,d.jsx)(c,{...a})});return(0,d.jsx)(k,{...i?{fallback:h}:{},children:l})}return k.displayName="LoadableComponent",k}},85264:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"PreloadChunks",{enumerable:!0,get:function(){return i}});let d=c(48249),e=c(74429),f=c(29294),g=c(10117),h=c(44217);function i({moduleIds:a}){let b=f.workAsyncStorage.getStore();if(void 0===b)return null;let c=[];if(b.reactLoadableManifest&&a){let d=b.reactLoadableManifest;for(let b of a){if(!d[b])continue;let a=d[b].files;c.push(...a)}}if(0===c.length)return null;let j=(0,h.getAssetTokenQuery)();return(0,d.jsx)(d.Fragment,{children:c.map(a=>{let c=`${b.assetPrefix}/_next/${(0,g.encodeURIPath)(a)}${j}`;return a.endsWith(".css")?(0,d.jsx)("link",{precedence:"dynamic",href:c,rel:"stylesheet",as:"style",nonce:b.nonce},a):((0,e.preload)(c,{as:"script",fetchPriority:"low",nonce:b.nonce}),null)})})}},92258:(a,b,c)=>{Promise.resolve().then(c.bind(c,97182))},97182:(a,b,c)=>{"use strict";c.d(b,{MigrationDetail:()=>d});let d=(0,c(77943).registerClientReference)(function(){throw Error("Attempted to call MigrationDetail() from the server but MigrationDetail is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"/Users/theobourgeois/code/db-studio/src/components/migrations/migration-detail.tsx","MigrationDetail")}};
|
|
1
|
+
exports.id=4809,exports.ids=[4809],exports.modules={10117:(a,b)=>{"use strict";function c(a){return a.split("/").map(a=>encodeURIComponent(a)).join("/")}Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"encodeURIPath",{enumerable:!0,get:function(){return c}})},10410:(a,b,c)=>{Promise.resolve().then(c.bind(c,53253))},10937:(a,b,c)=>{"use strict";c.r(b),c.d(b,{default:()=>f});var d=c(5735),e=c(97182);async function f({children:a,params:b}){let{setId:c}=await b;return(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(e.MigrationDetail,{setId:decodeURIComponent(c)}),a]})}},12229:(a,b,c)=>{"use strict";c.d(b,{En:()=>k,Pc:()=>j,jl:()=>i});var d=c(31417),e=c(300),f=c(14490),g=c(15445);let h="ytdb:queries";(0,g.q)("db-studio:queries",h);let i=144,j=800,k=(0,d.v)()((0,e.Zr)(a=>({drafts:{},editorHeight:224,history:[],setDraft:(b,c)=>a(a=>({drafts:{...a.drafts,[b]:c}})),setEditorHeight:b=>a({editorHeight:Math.min(j,Math.max(i,Math.round(b)))}),record:(b,c)=>a(a=>{let d=c.trim();if(!d)return a;let e=a.history.find(a=>a.connectionId===b&&a.sql===d),g={id:e?.id??(0,f.z)(),connectionId:b,sql:d,executedAt:Date.now()},h=0,i=0;return{history:[g,...a.history.filter(a=>a.id!==g.id)].filter(a=>!(h>=200)&&!(i+a.sql.length>1e6)&&(h+=1,i+=a.sql.length,!0))}}),remove:b=>a(a=>({history:a.history.filter(a=>a.id!==b)}))}),{name:h}))},39973:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"default",{enumerable:!0,get:function(){return e}});let d=c(40399)._(c(80061));function e(a,b){let c={};"function"==typeof a&&(c.loader=a);let e={...c,...b};return(0,d.default)({...e,modules:e.loadableGenerated?.modules})}("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},53253:(a,b,c)=>{"use strict";c.d(b,{MigrationDetail:()=>X});var d=c(48249),e=c(39973),f=c.n(e),g=c(2116),h=c.n(g),i=c(19099),j=c(67484),k=c(23171),l=c(44231),m=c(60671),n=c(86229),o=c(25297),p=c(82244),q=c(53286),r=c(20886),s=c(21883),t=c(67657),u=c(78931),v=c(72428),w=c(86408),x=c(453),y=c(12356),z=c(66280),A=c(12229),B=c(14490),C=c(30770),D=c(64759);function E({environments:a,targetId:b,onSelect:c}){let e=a.find(a=>a.connection.id===b);return e?(0,d.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,d.jsx)("span",{className:"text-xs text-muted-foreground",children:"Running against"}),(0,d.jsxs)(p.rI,{children:[(0,d.jsxs)(p.ty,{disabled:a.length<2,className:"flex h-7 cursor-pointer items-center gap-1.5 rounded-lg border bg-background px-2 text-xs font-medium outline-none hover:bg-muted/60 focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-default data-open:bg-muted/60",children:[(0,d.jsx)(C.F,{connection:e.connection}),(0,d.jsx)("span",{className:"max-w-32 truncate",children:e.connection.name})]}),(0,d.jsx)(p.SQ,{align:"start",className:"min-w-52",children:a.map(a=>(0,d.jsxs)(p._2,{onClick:()=>c(a.connection.id),className:a.connection.id===b?"font-medium":void 0,children:[(0,d.jsx)(C.F,{connection:a.connection}),(0,d.jsx)("span",{className:"min-w-0 flex-1 truncate",children:a.connection.name}),(0,d.jsxs)("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:[a.summary.applied,"/",a.summary.total]})]},a.connection.id))})]})]}):null}function F({environments:a,targetId:b,caption:c,loading:e,selection:f,onSelect:g,onCompare:h}){return(0,d.jsxs)("div",{className:"flex h-11 shrink-0 items-center border-b bg-muted/20",children:[(0,d.jsx)("span",{className:"flex h-11 shrink-0 items-center pl-3",children:(0,d.jsx)(D.aL,{checked:f.checked,label:f.checked?"Clear selection":"Select all",onToggle:()=>f.onToggle()})}),(0,d.jsx)("span",{className:"min-w-0 flex-1 truncate px-2 text-xs text-muted-foreground",children:c}),a.map(a=>{let{connection:c,summary:f,ledger:h,error:i}=a,j=c.id===b;return(0,d.jsxs)("button",{type:"button",disabled:j,"aria-current":j?"true":void 0,title:j?`${c.name} is what Apply and Revert run against`:`Run against ${c.name} instead`,onClick:()=>g(c.id),className:(0,B.cn)("flex h-11 shrink-0 flex-col items-center justify-center gap-0.5 border-l text-[11px] outline-none",D.Z_,j?"cursor-default bg-foreground/[0.04] font-medium":"cursor-pointer text-muted-foreground hover:bg-muted/60 hover:text-foreground",e&&"opacity-60"),children:[(0,d.jsxs)("span",{className:"flex max-w-full items-center gap-1",children:[(0,d.jsx)(C.F,{connection:c,className:"size-1.5"}),(0,d.jsx)("span",{className:"truncate",children:c.name})]}),i?(0,d.jsx)("span",{className:"text-destructive",children:"unreachable"}):h?(0,d.jsxs)("span",{className:"tabular-nums text-muted-foreground/80",children:[f.applied,"/",f.total,f.drifted>0&&(0,d.jsx)("span",{className:"text-amber-600 dark:text-amber-400",children:" !"})]}):(0,d.jsx)("span",{className:"text-muted-foreground/70",children:"reading…"})]},c.id)}),(0,d.jsx)("div",{className:(0,B.cn)("flex shrink-0 items-center justify-end border-l pr-2 pl-1",D.yr),children:a.length>1&&(0,d.jsx)(o.$,{size:"icon-xs",variant:"ghost",title:"Compare the two schemas","aria-label":"Compare schemas",onClick:()=>{let c=a.find(a=>a.connection.id!==b);c&&h(c.connection.id)},children:(0,d.jsx)(k.R4X,{})})})]})}var G=c(9230),H=c(38393),I=c(88877),J=c(90863);function K({schema:a,found:b,onOpenChange:c,onSave:e}){let[f,g]=(0,j.useState)(a),h=f.trim(),i=(0,v.hD)(h),k=b.filter(a=>a.schema!==h);function l(){i&&(e(h),c(!1))}return(0,d.jsx)(H.lG,{open:!0,onOpenChange:c,children:(0,d.jsxs)(H.Cf,{className:"sm:max-w-md",children:[(0,d.jsxs)(H.c7,{children:[(0,d.jsx)(H.L3,{children:"Ledger schema"}),(0,d.jsx)(H.rr,{children:"Where each database keeps its record of what has run. Created on the first apply."})]}),(0,d.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,d.jsx)(J.J,{htmlFor:"ledger-schema",children:"Schema"}),(0,d.jsx)(I.p,{id:"ledger-schema",value:f,spellCheck:!1,autoComplete:"off","aria-invalid":h.length>0&&!i,onChange:a=>g(a.target.value),onKeyDown:a=>"Enter"===a.key&&l()}),(0,d.jsx)("p",{className:"font-mono text-xs text-muted-foreground",children:i?`${h}.${v.R9}`:"\xa0"}),h.length>0&&!i&&(0,d.jsx)("p",{className:"text-xs text-destructive",children:"Letters, digits and underscores only, starting with a letter or underscore."})]}),k.length>0&&(0,d.jsxs)("p",{className:"rounded-md border border-amber-600/25 bg-amber-500/8 px-3 py-2 text-xs",children:[k.map(a=>`${a.name} keeps its ledger in ${a.schema}`).join("; "),". That one stays where it is."]}),(0,d.jsxs)(H.Es,{children:[h!==v.aC&&(0,d.jsx)(o.$,{variant:"ghost",onClick:()=>g(v.aC),children:"Reset"}),(0,d.jsx)(o.$,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),(0,d.jsx)(o.$,{disabled:!i,onClick:l,children:"Save"})]})]})})}var L=c(60101),M=c(76829),N=c(13449),O=c(65292),P=c(29613),Q=c(86871);function R({initial:a,file:b,onOpenChange:c,onSave:e}){let[f,g]=(0,j.useState)(a),[h,i]=(0,j.useState)(!1),[k,l]=(0,j.useState)(null),m=f.trim()!==a.trim();async function n(a){if(a?.preventDefault(),m&&!h){i(!0),l(null);try{await e(f.trim()),c(!1)}catch(a){l(a instanceof Error?a.message:String(a))}finally{i(!1)}}}return(0,d.jsx)(H.lG,{open:!0,onOpenChange:a=>!h&&c(a),children:(0,d.jsx)(H.Cf,{className:"sm:max-w-lg",showCloseButton:!1,children:(0,d.jsxs)("form",{onSubmit:a=>void n(a),className:"flex flex-col gap-4",children:[(0,d.jsx)(H.c7,{children:(0,d.jsxs)("div",{className:"flex items-baseline gap-3",children:[(0,d.jsx)(H.L3,{children:"Note"}),b&&(0,d.jsx)("span",{className:"ml-auto truncate font-mono text-[11px] text-muted-foreground",title:"Written into the migration's folder, to commit with the SQL",children:b})]})}),(0,d.jsx)(Q.T,{autoFocus:!0,"aria-label":"Note",value:f,maxLength:v.XG,placeholder:"Apply 0001–0007, deploy the app, then apply 0008.",className:"max-h-[50vh] min-h-32",onChange:a=>g(a.target.value),onKeyDown:a=>{"Enter"===a.key&&(a.metaKey||a.ctrlKey)&&n()}}),k&&(0,d.jsx)("p",{className:"text-xs text-destructive",children:k}),(0,d.jsxs)(H.Es,{children:[(0,d.jsx)(o.$,{type:"button",variant:"ghost",disabled:h,onClick:()=>c(!1),children:"Cancel"}),(0,d.jsx)(o.$,{type:"submit",disabled:!m||h,children:h?"Saving…":"Save"})]})]})})})}var S=c(76349),T=c(78394),U=c(17463),V=c(30904);let W=f()(async()=>{},{loadableGenerated:{modules:["components/migrations/migration-detail.tsx -> ./schema-diagram"]},ssr:!1});function X({setId:a}){let b=(0,i.useRouter)(),{connection:c,tables:e}=(0,l.k)(),f=(0,z.jV)(a=>a.addFiles),g=(0,z.jV)(a=>a.renameSet),n=(0,z.jV)(a=>a.setNote),C=(0,z.jV)(a=>a.removeSet),H=(0,z.jV)(a=>a.removeStep),I=(0,z.jV)(a=>a.record),J=(0,z.jV)(a=>a.ledgerSchema),Q=(0,z.jV)(a=>a.setLedgerSchema),S=(0,z.Ss)(a),{scope:aa,root:ab,checkout:ac}=(0,z.ox)(c.id),ad=(0,z.jV)(a=>a.setRepoCheckout),ae=(0,V.y)((0,v.km)(a)?ab:null,ac),af=(0,v.km)(a)?ae.data?.sets.find(b=>b.id===a)??null:S,ag=!!af?.source,ah=(0,w.gz)(c.id),ai=(0,A.En)(a=>a.setDraft),aj=(0,m.$C)(),ak=(0,N.ZG)((0,i.usePathname)()),al=(0,M.hX)("migration"===ak.kind?ak.view:void 0),am=(0,j.useCallback)(d=>{d!==al&&b.push((0,N.Jn)({kind:"migration",connectionId:c.id,setId:a,view:(0,M.z2)(d)}),{scroll:!1})},[al,b,c.id,a]),an=(0,j.useRef)(null),[ao,ap]=(0,j.useState)([]);(0,j.useRef)(null),af?.steps.map(a=>a.version).join(",");let[aq,ar]=(0,j.useState)([]),as=(0,j.useRef)(null),[at,au]=(0,j.useState)(null),[av,aw]=(0,j.useState)(null),[ax,ay]=(0,j.useState)(!1),[az,aA]=(0,j.useState)(!1),[aB,aC]=(0,j.useState)(!1),[aD,aE]=(0,j.useState)(null),[aF,aG]=(0,j.useState)(null),[aH,aI]=(0,j.useState)(!1),[aJ,aK]=(0,j.useState)(!1),[aL,aM]=(0,j.useState)(!1),aN=(0,j.useRef)(null),aO=(0,j.useRef)(!1),aP=(0,j.useMemo)(()=>[c,...ah],[c,ah]),aQ=aP.map(a=>a.url).join("|"),aR=(0,r.Y)(`ledgers:${J}:${aQ}`,async a=>Object.fromEntries(await Promise.all(aP.map(async b=>{try{return[b.id,{ledger:await s.F.ledger(b.url,J,a),error:null}]}catch(c){if(a.aborted)throw c;return[b.id,{ledger:null,error:c instanceof Error?c.message:String(c)}]}})))),aS=aR.data?.[c.id]??null,aT=af?.name??"",aU=(0,j.useMemo)(()=>(0,u.Gf)(aS?.ledger,aT),[aS?.ledger,aT]),aV=(0,j.useMemo)(()=>aP.map(a=>{let b=aR.data?.[a.id]??null,c=(0,u.Gf)(b?.ledger,aT);return{connection:a,ledger:c,error:b?.error??null,summary:(0,u.eh)(af,c)}}),[aP,aR.data,af,aT]),aW=(0,j.useMemo)(()=>{let a=new Set;for(let b of af?.steps??[])if(ao.includes(b.version))for(let c of aV)"drifted"===(0,u.FY)(b,c.ledger)&&a.add(c.connection.id);return aP.filter(b=>a.has(b.id))},[af,ao,aV,aP]),aX=(0,r.Y)(`stored:${J}:${aW.map(a=>a.url).join("|")}`,async a=>Object.fromEntries(await Promise.all(aW.map(async b=>{try{return[b.id,{ledger:await s.F.ledger(b.url,J,a,!0),error:null}]}catch(c){if(a.aborted)throw c;return[b.id,{ledger:null,error:c instanceof Error?c.message:String(c)}]}})))),aY=`/${encodeURIComponent(c.id)}/migrations`,aZ=(0,z.jV)(a=>a.history),a$=(0,j.useMemo)(()=>(0,x.x)(aV.map(a=>({connection:a.connection,ledger:a.ledger})),aZ).filter(a=>a.setName===aT),[aV,aZ,aT]),a_=(0,j.useMemo)(()=>"schema"===al&&af?(0,y.DT)(af.steps.map(a=>({version:a.version,sql:a.applySql}))):null,[al,af]),[a0,a1]=(0,j.useState)(null),a2=(0,j.useCallback)(a=>{a1(a),am("diagram")},[am]),a3=(0,j.useCallback)(a=>{an.current=a,ap(b=>b.includes(a)?b:[...b,a]),am("migrations")},[am]),a4=(0,u.eh)(af,aU),a5=(0,j.useMemo)(()=>(0,u.nb)(af,aU),[af,aU]),a6=(0,u.kB)(af,aU),a7=(0,j.useCallback)(a=>{am("migrations"),aw(null),aA(!1),au({steps:[a],blockedBy:null,direction:"apply"})},[am]),a8=(0,j.useCallback)((a,b)=>af&&af.name===a?af.steps.find(a=>a.version===b)??null:null,[af]),a9=(0,j.useCallback)(b=>{aE(f(a,b.files)),am("migrations")},[f,a,am]),ba=(0,O.$)(a9);function bb(a,b,c=!1){(0!==b.steps.length||b.blockedBy)&&(aw(null),aA(!1),au({...b,direction:a,recordOnly:c}))}function bc(a,b){return"apply"===b?a.applySql:a.revertSql}async function bd(){if(!at||!af)return;aA(!0),ay(!0);let a=at.steps.map(a=>({version:a.version,name:a.name,status:"running"}));aw(a);try{let b=await s.F.rehearse(c.url,{steps:at.steps.map(a=>({version:a.version,name:a.name,sql:bc(a,at.direction)??""}))}),d=new Map(b.steps.map(a=>[a.version,a]));a=a.map(a=>{let c=d.get(a.version);return c?{...a,status:"ok",durationMs:c.durationMs}:b.failed?.version===a.version?{...a,status:"failed",error:b.failed.error}:{...a,status:"skipped"}})}catch(c){let b=c instanceof Error?c.message:String(c);a=a.map((a,c)=>0===c?{...a,status:"failed",error:b}:{...a,status:"skipped"})}aw(a),ay(!1)}function be(a){return{steps:a,blockedBy:null}}async function bf(){if(!at||!af)return;aO.current=!1,aA(!1),ay(!0);let a=at.steps.map(a=>({version:a.version,name:a.name,status:"waiting"}));aw(a);let b=(b,c)=>{aw(a=a.map((a,d)=>d===b?{...a,...c}:a))},d=b=>{aw(a=a.map((a,c)=>c>=b&&"waiting"===a.status?{...a,status:"skipped"}:a))};for(let[a,e]of at.steps.entries()){if(aO.current){d(a);break}let f="apply"===at.direction?e.applySql:e.revertSql;if(!f&&!at.recordOnly){b(a,{status:"failed",error:"No revert file for this migration."}),d(a+1);break}b(a,{status:"running"});let g=crypto.randomUUID();try{let d=await s.F.migrate(c.url,{runId:g,direction:at.direction,version:e.version,name:e.name,checksum:e.checksum,setName:af.name,sql:f??"",revertSql:"apply"===at.direction?e.revertSql:void 0,ledgerSchema:J,recordOnly:at.recordOnly});b(a,{status:"ok",durationMs:d.durationMs}),I({runId:d.runId??g,setId:af.id,setName:af.name,connectionId:c.id,connectionName:c.name,direction:at.direction,version:e.version,name:e.name,status:"ok",recorded:at.recordOnly,durationMs:d.durationMs})}catch(h){let f=h instanceof Error?h.message:String(h);b(a,{status:"failed",error:f}),d(a+1),I({runId:g,setId:af.id,setName:af.name,connectionId:c.id,connectionName:c.name,direction:at.direction,version:e.version,name:e.name,status:"failed",durationMs:0,error:f});break}}ay(!1),aR.reload(),aX.reload(),e.reload(),a.every(a=>"ok"===a.status)&&ar([])}function bg(a){ai(c.id,a),b.push(`/${encodeURIComponent(c.id)}/query`)}function bh(a){aj(a)}async function bi(a){af&&(af.source?(await s.F.note(af.source.root,af.source.path,a),ae.reload()):n(af.id,a))}async function bj(a){let b=a?.[0];aG(null),b&&aF&&af&&aE(f(af.id,[{path:`revert/${aF}_${b.name}`,text:await b.text()}]))}if(!af){let b=(0,v.km)(a)&&ae.loading;return(0,d.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col",children:[(0,d.jsx)(Y,{name:b?"Reading…":"Not found"}),(0,d.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center gap-2 text-muted-foreground",children:b?(0,d.jsx)("p",{className:"text-sm",children:"Reading the folder…"}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)("p",{className:"text-sm",children:ae.error?ae.error:(0,v.km)(a)?ac?"That migration is not in the folder in the worktree you picked.":"That migration is not in the folder in any worktree.":"That migration is no longer here."}),(0,d.jsx)(h(),{href:aY,className:"text-foreground underline underline-offset-4",children:"All migrations"})]})})]})}let bk=new Set(aq),bl=af.steps.filter(a=>bk.has(a.version)).length,bm=bl>0,bn=bm?(0,u.DM)(af,aU,bk):(0,u.gj)(af,aU),bo=bm?(0,u.n9)(af,aU,bk):(0,u.e)(af,aU),bp=ax||aR.loading||ae.loading;return(0,d.jsxs)("div",{className:"relative flex min-h-0 flex-1 flex-col",onDragOver:a=>{!ag&&a.dataTransfer.types.includes("Files")&&(a.preventDefault(),aC(!0))},children:[(0,d.jsxs)(Y,{name:af?.name??"",indexHref:aY,children:[af.source&&(0,d.jsxs)("span",{className:"flex min-w-0 items-center gap-1 text-[11px] text-muted-foreground",title:`Read from ${af.source.path}`,children:[(0,d.jsx)(k.WzY,{className:"size-3.5 shrink-0"}),(0,d.jsx)("span",{className:"max-w-48 truncate font-mono",children:af.source.path}),af.origins?(0,d.jsx)(G.c,{origins:af.origins,limit:3}):ae.data?.git&&(0,d.jsxs)("span",{className:"shrink-0 rounded border px-1.5 font-mono text-[10px]",children:[ae.data.git.branch,ae.data.git.dirty&&"*"]})]}),(0,d.jsx)(E,{environments:aV,targetId:c.id,onSelect:bh}),(0,d.jsxs)("div",{className:"ml-auto flex items-center gap-2",children:[(0,d.jsx)(o.$,{size:"icon-sm",variant:"ghost",disabled:aR.loading||ae.loading,"aria-label":"Refresh",title:ag?"Re-read the files and every environment's ledger":"Re-read every environment's ledger",onClick:function(){aR.reload(),aX.reload(),ag&&ae.reload()},children:(0,d.jsx)(k.oS8,{className:(0,B.cn)((aR.loading||ae.loading)&&"animate-spin")})}),!ag&&(0,d.jsxs)(o.$,{size:"sm",variant:"ghost",onClick:()=>aC(!0),children:[(0,d.jsx)(k.FeY,{"data-icon":"inline-start"}),"Import"]}),(0,d.jsxs)(p.rI,{children:[(0,d.jsx)(p.ty,{render:(0,d.jsx)(o.$,{size:"icon-sm",variant:"ghost","aria-label":"More migration actions"}),className:"cursor-pointer",children:(0,d.jsx)(k.YKd,{})}),(0,d.jsxs)(p.SQ,{align:"end",className:"min-w-64",children:[(0,d.jsxs)(p._2,{disabled:bp||0===bn.steps.length,onClick:()=>bb("apply",be(bn.steps),!0),children:[(0,d.jsx)(k.nXx,{}),"Mark ",bn.steps.length," as already applied"]}),(0,d.jsx)(p.mB,{}),(0,d.jsxs)(p._2,{disabled:bp||0===bo.steps.length,onClick:()=>bb("revert",bo),children:[(0,d.jsx)(k.ij9,{}),bm?`Revert ${bo.steps.length} selected on ${c.name}`:`Revert everything on ${c.name}`]}),(0,d.jsx)(p.mB,{}),(0,d.jsxs)(p._2,{onClick:()=>aM(!0),children:[(0,d.jsx)(k.UA_,{}),af.note?"Edit note":"Add note"]}),!ag&&(0,d.jsxs)(p._2,{onClick:()=>aK(!0),children:[(0,d.jsx)(k.NOV,{}),"Rename"]}),(0,d.jsxs)(p._2,{onClick:()=>aI(!0),children:[(0,d.jsx)(k.ooN,{}),"Ledger table",(0,d.jsxs)("span",{className:"ml-auto pl-3 font-mono text-[11px] text-muted-foreground",children:[J,".",v.R9]})]}),!ag&&(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(p.mB,{}),(0,d.jsx)(p._2,{variant:"destructive",onClick:function(){af&&(C(af.id),b.push(aY))},children:"Forget this migration"})]})]})]}),(0,d.jsxs)(o.$,{size:"sm",disabled:bp||0===bn.steps.length,onClick:()=>bb("apply",bn),children:[(0,d.jsx)(k.eGB,{"data-icon":"inline-start"}),0===bn.steps.length?bm?"Nothing selected to apply":"Up to date":`Apply ${bn.steps.length}${bm?" selected":""} to ${c.name}`]})]})]}),aD&&(0,d.jsx)($,{report:aD,onDismiss:()=>aE(null)}),ba.error&&(0,d.jsx)("p",{className:"border-b bg-destructive/5 px-4 py-1.5 text-xs text-destructive",children:ba.error}),"migrations"===al&&af.note&&(0,d.jsx)(Z,{note:af.note,notePath:af.source?.notePath??null,onEdit:()=>aM(!0)}),(0,d.jsxs)("div",{className:"relative flex min-h-0 flex-1 flex-col",children:["history"===al?(0,d.jsx)(q.F,{className:"min-h-0 flex-1",children:(0,d.jsx)(L.H,{events:a$,connections:aP,loading:aR.loading,ledgerSchema:J,setName:aT,findStep:a8,onLedgerChange:aR.reload,onRetry:a7})}):"schema"===al&&a_?(0,d.jsx)(q.F,{className:"min-h-0 flex-1",children:(0,d.jsx)(U.ku,{changes:a_,onVersion:a3,className:"py-2"})}):"diagram"===al?(0,d.jsx)(W,{steps:af.steps,live:e.data??null,at:a0,onAt:a1,onVersion:a3}):aS?.error?(0,d.jsx)("p",{className:"flex-1 px-4 py-6 font-mono text-xs text-destructive",children:aS.error}):(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(F,{environments:aV,targetId:c.id,caption:bm?`${bl} selected`:function(a,b){if(b&&0===a.total)return"Reading…";let c=`${a.total} migration${1===a.total?"":"s"}`;return a.foreign>0?`${c} \xb7 ${a.foreign} not in this folder`:c}(a4,aR.loading),loading:aR.loading,selection:{checked:0!==bl&&(bl===af.steps.length||"mixed"),onToggle:function(){if(!af)return;let a=af.steps.map(a=>a.version);ar(b=>b.some(b=>a.includes(b))?[]:a)}},onSelect:bh,onCompare:function(a){w.lz.getState().setCompareTarget(c.id,a),b.push(`/${encodeURIComponent(c.id)}/diff`)}}),(0,d.jsxs)(q.F,{className:(0,B.cn)("min-h-0 flex-1",aR.loading&&"opacity-70"),children:[(af?.steps.length??0)===0&&!ag&&(0,d.jsx)("div",{className:"p-6",children:(0,d.jsx)(O.k,{onFiles:a9,compact:!0})}),af.conflicts&&(0,d.jsxs)("div",{className:"border-b bg-muted/20 px-4 py-2 text-xs text-muted-foreground",children:[(0,d.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,d.jsx)(k.e5t,{className:"size-3.5 shrink-0 text-amber-600 dark:text-amber-400"}),"Worktrees disagree on ",1===af.conflicts.length?"one file":`${af.conflicts.length} files`,". Runs use the copy named first; read another worktree alone to run its copy."]}),(0,d.jsx)("ul",{className:"mt-1 space-y-1 pl-5",children:af.conflicts.map(a=>(0,d.jsxs)("li",{className:"flex flex-wrap items-center gap-1.5",children:[(0,d.jsx)("span",{className:"font-mono text-[11px]",children:a.version}),(0,d.jsx)("span",{className:"rounded border px-1.5 font-mono text-[10px] text-foreground",children:a.used.branch}),a.others.map(a=>(0,d.jsx)(o.$,{size:"xs",variant:"ghost",title:`Read only ${a.path}`,onClick:()=>ad(aa,a.path),children:(0,d.jsx)("span",{className:"font-mono text-[10px]",children:a.branch})},a.path))]},a.version))})]}),af.skipped.length>0&&ag&&(0,d.jsxs)("div",{className:"border-b bg-muted/20 px-4 py-2 text-xs text-muted-foreground",children:[(0,d.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,d.jsx)(k.e5t,{className:"size-3.5 shrink-0 text-amber-600 dark:text-amber-400"}),"Skipped ",af.skipped.length," file",1===af.skipped.length?"":"s"]}),(0,d.jsx)("ul",{className:"mt-1 space-y-0.5 pl-5 font-mono text-[11px]",children:af.skipped.map(a=>(0,d.jsx)("li",{children:a},a))})]}),(af?.steps??[]).map(a=>(0,d.jsx)(D.Tj,{step:a,targetId:c.id,status:(0,u.FY)(a,aU),environments:aV.map(b=>({connection:b.connection,status:(0,u.FY)(a,b.ledger),entry:(0,u.ay)(a,b.ledger),error:b.error})),isNewestApplied:a6?.version===a.version,expanded:ao.includes(a.version),busy:bp,editable:!ag,drift:function(a){let b=aV.filter(b=>"drifted"===(0,u.FY)(a,b.ledger)),d=b.find(a=>a.connection.id===c.id)??b[0];if(!d)return null;let e=aX.data?.[d.connection.id],f=e?.ledger?.entries.find(b=>b.setName===aT&&b.version===a.version);return{connectionName:d.connection.name,appliedSql:e?.ledger?f?.applySql??null:void 0,error:e?.error??null}}(a),selected:bk.has(a.version),onSelect:b=>(function(a,b){if(!af)return;let c=af.steps.map(a=>a.version),d=as.current;as.current=a,ar(e=>{let f=!e.includes(a),g=[a];if(b&&d&&d!==a&&c.includes(d)){let[b,e]=[c.indexOf(d),c.indexOf(a)].sort((a,b)=>a-b);g=c.slice(b,e+1)}let h=new Set(e);for(let a of g)f?h.add(a):h.delete(a);return c.filter(a=>h.has(a))})})(a.version,b),onToggle:()=>{var b;return b=a.version,void ap(a=>a.includes(b)?a.filter(a=>a!==b):[...a,b])},actions:{onApplyThrough:()=>bb("apply",(0,u.gj)(af,aU,a.version)),onApplyOne:()=>bb("apply",{steps:[a],blockedBy:null}),onRevertThrough:()=>bb("revert",(0,u.e)(af,aU,a.version)),onMarkApplied:()=>bb("apply",be([a]),!0),onMarkPending:()=>bb("revert",be([a]),!0),onAttachRevert:()=>{aG(a.version),window.requestAnimationFrame(()=>aN.current?.click())},onRemove:()=>af&&H(af.id,a.version),onOpenInEditor:bg,onShowDiagram:()=>a2(a.version)}},a.version)),a5.length>0&&(0,d.jsx)(_,{entries:a5,connectionName:c.name})]})]}),aB&&!ag&&(0,d.jsx)("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-background/85 p-6",onDragOver:a=>a.preventDefault(),onDragLeave:()=>aC(!1),onDrop:a=>{a.preventDefault(),aC(!1),ba.importFrom(a.dataTransfer)},children:(0,d.jsx)(O.k,{onFiles:a9,className:"w-full max-w-xl bg-background"})})]}),(0,d.jsx)(M.lj,{pane:al,onPaneChange:am,historyCount:a$.length,migrationsLabel:"Files",showSchema:!0,caption:a_?(0,U.Zg)(a_):function({connectionName:a,summary:b,initialized:c,loading:d,foundIn:e,configuredSchema:f}){if(d&&null===c)return"Reading ledgers…";let g=[];return!1===c||b.pending>0?g.push(`${b.pending} of ${b.total} pending on ${a}`):g.push(`${a} is up to date`),b.drifted>0&&g.push(`${b.drifted} changed since applied`),e&&e!==f&&g.push(`ledger in ${e}`),g.join(" \xb7 ")}({connectionName:c.name,summary:a4,initialized:aU?.initialized??null,loading:aR.loading,foundIn:aU?.initialized?aU.schema:null,configuredSchema:J})}),(0,d.jsx)("input",{ref:aN,type:"file",accept:".sql",className:"sr-only",onChange:a=>{bj(a.target.files),a.target.value=""}}),(0,d.jsx)(P.K,{open:aJ,title:"Rename migration",initial:af.name,submitLabel:"Rename",onOpenChange:aK,onSubmit:function(a){af&&g(af.id,a)}}),aL&&(0,d.jsx)(R,{initial:af.note??"",file:af.source?af.source.notePath?.split(/[\\/]/).at(-1)??"README.md":null,onOpenChange:aM,onSave:bi}),aH&&(0,d.jsx)(K,{schema:J,found:aV.filter(a=>a.ledger?.initialized).map(a=>({name:a.connection.name,schema:a.ledger?.schema??J})),onOpenChange:aI,onSave:a=>{Q(a),aR.reload()}}),at&&(0,d.jsx)(T.I,{open:!0,direction:at.direction,connection:c,steps:at.steps,blockedBy:at.blockedBy,progress:av,running:ax,recordOnly:at.recordOnly??!1,note:af.note,outOfOrder:"apply"!==at.direction||at.recordOnly?null:(0,u.nj)(aU,at.steps),rehearsal:az,onRun:()=>void bf(),onRehearse:!at.recordOnly&&0!==at.steps.length&&at.steps.every(a=>{let b=bc(a,at.direction);return!!b&&(0,t.Ol)(b).atomic})?()=>void bd():null,onStop:()=>{aO.current=!0},onClose:function(){ax||(au(null),aw(null),aA(!1))}})]})}function Y({name:a,indexHref:b,children:c}){let e=(0,d.jsx)(k.olY,{className:"size-4 shrink-0 text-muted-foreground"});return(0,d.jsxs)(n.X,{children:[b?(0,d.jsx)(h(),{href:b,title:"All migrations","aria-label":"All migrations",className:"flex size-6 shrink-0 items-center justify-center rounded-md outline-none hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring/60",children:e}):e,(0,d.jsx)("span",{className:"min-w-0 truncate font-medium",children:a}),c]})}function Z({note:a,notePath:b,onEdit:c}){return(0,d.jsxs)("div",{title:b?`${b} \xb7 click to edit`:"Click to edit",onClick:a=>{a.target.closest("a")||c()},className:"group flex w-full cursor-pointer items-start gap-2 border-b px-4 py-2.5 text-left text-xs hover:bg-muted/30",children:[(0,d.jsx)(k.UA_,{className:"mt-px size-3.5 shrink-0 text-muted-foreground"}),(0,d.jsx)(S.o,{text:a,className:"max-h-40 min-w-0 flex-1 overflow-y-auto"}),(0,d.jsx)("button",{type:"button","aria-label":"Edit note",onClick:a=>{a.stopPropagation(),c()},className:"mt-px shrink-0 rounded-sm text-muted-foreground opacity-0 outline-none group-hover:opacity-100 focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring",children:(0,d.jsx)(k.NOV,{className:"size-3.5"})})]})}function $({report:a,onDismiss:b}){let c=[];return a.added>0&&c.push(`added ${a.added}`),a.updated>0&&c.push(`updated ${a.updated}`),a.reverts>0&&c.push(`${a.reverts} revert file${1===a.reverts?"":"s"}`),(0,d.jsxs)("div",{className:"flex items-start gap-2 border-b bg-muted/30 px-4 py-1.5 text-xs",children:[(0,d.jsxs)("span",{className:"min-w-0 flex-1",children:[c.length>0?`Imported: ${c.join(", ")}`:"Nothing new in those files",a.skipped.length>0&&(0,d.jsxs)("span",{className:"text-muted-foreground",children:[" ","\xb7 skipped ",a.skipped.slice(0,2).join(", "),a.skipped.length>2&&` and ${a.skipped.length-2} more`]})]}),(0,d.jsx)(o.$,{size:"xs",variant:"ghost",onClick:b,children:"Dismiss"})]})}function _({entries:a,connectionName:b}){return(0,d.jsxs)("div",{className:"border-t bg-muted/20",children:[(0,d.jsxs)("p",{className:"flex items-center gap-2 px-4 py-2 text-xs text-muted-foreground",children:[(0,d.jsx)(k.e5t,{className:"size-3.5 shrink-0 text-amber-600 dark:text-amber-400"}),"Applied on ",b,", not in this folder"]}),a.map(a=>(0,d.jsxs)("div",{className:"flex items-center gap-2 px-4 py-1.5 text-xs opacity-70",children:[(0,d.jsx)(D.oy,{status:"applied"}),(0,d.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:a.version}),(0,d.jsx)("span",{className:"min-w-0 flex-1 truncate",children:a.name||"—"}),(0,d.jsx)("span",{className:"shrink-0 text-muted-foreground/70",children:new Date(a.appliedAt).toLocaleString()})]},a.version))]})}},66958:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"BailoutToCSR",{enumerable:!0,get:function(){return e}});let d=c(49306);function e({reason:a,children:b}){throw Object.defineProperty(new d.BailoutToCSRError(a),"__NEXT_ERROR_CODE",{value:"E394",enumerable:!1,configurable:!0})}},80061:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"default",{enumerable:!0,get:function(){return j}});let d=c(48249),e=c(67484),f=c(66958),g=c(85264);function h(a){return{default:a&&"default"in a?a.default:a}}let i={loader:()=>Promise.resolve(h(()=>null)),loading:null,ssr:!0},j=function(a){let b={...i,...a},c=(0,e.lazy)(()=>b.loader().then(h)),j=b.loading;function k(a){let h=j?(0,d.jsx)(j,{isLoading:!0,pastDelay:!0,error:null}):null,i=!b.ssr||!!b.loading,k=i?e.Suspense:e.Fragment,l=b.ssr?(0,d.jsxs)(d.Fragment,{children:[(0,d.jsx)(g.PreloadChunks,{moduleIds:b.modules}),(0,d.jsx)(c,{...a})]}):(0,d.jsx)(f.BailoutToCSR,{reason:"next/dynamic",children:(0,d.jsx)(c,{...a})});return(0,d.jsx)(k,{...i?{fallback:h}:{},children:l})}return k.displayName="LoadableComponent",k}},85264:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"PreloadChunks",{enumerable:!0,get:function(){return i}});let d=c(48249),e=c(74429),f=c(29294),g=c(10117),h=c(44217);function i({moduleIds:a}){let b=f.workAsyncStorage.getStore();if(void 0===b)return null;let c=[];if(b.reactLoadableManifest&&a){let d=b.reactLoadableManifest;for(let b of a){if(!d[b])continue;let a=d[b].files;c.push(...a)}}if(0===c.length)return null;let j=(0,h.getAssetTokenQuery)();return(0,d.jsx)(d.Fragment,{children:c.map(a=>{let c=`${b.assetPrefix}/_next/${(0,g.encodeURIPath)(a)}${j}`;return a.endsWith(".css")?(0,d.jsx)("link",{precedence:"dynamic",href:c,rel:"stylesheet",as:"style",nonce:b.nonce},a):((0,e.preload)(c,{as:"script",fetchPriority:"low",nonce:b.nonce}),null)})})}},92258:(a,b,c)=>{Promise.resolve().then(c.bind(c,97182))},97182:(a,b,c)=>{"use strict";c.d(b,{MigrationDetail:()=>d});let d=(0,c(77943).registerClientReference)(function(){throw Error("Attempted to call MigrationDetail() from the server but MigrationDetail is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.")},"/Users/theobourgeois/code/db-studio/src/components/migrations/migration-detail.tsx","MigrationDetail")}};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
exports.id=7928,exports.ids=[7928],exports.modules={300:(a,b,c)=>{"use strict";function d(a,b){let c;try{c=a()}catch(a){return}return{getItem:a=>{var d;let e=a=>null===a?null:JSON.parse(a,null==b?void 0:b.reviver),f=null!=(d=c.getItem(a))?d:null;return f instanceof Promise?f.then(e):e(f)},setItem:(a,d)=>c.setItem(a,JSON.stringify(d,null==b?void 0:b.replacer)),removeItem:a=>c.removeItem(a)}}c.d(b,{KU:()=>d,Zr:()=>f});let e=a=>b=>{try{let c=a(b);if(c instanceof Promise)return c;return{then:a=>e(a)(c),catch(a){return this}}}catch(a){return{then(a){return this},catch:b=>e(b)(a)}}},f=(a,b)=>(c,f,g)=>{let h,i={storage:d(()=>window.localStorage),partialize:a=>a,version:0,merge:(a,b)=>({...b,...a}),...b},j=!1,k=0,l=new Set,m=new Set,n=i.storage;if(!n)return a((...a)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),c(...a)},f,g);let o=()=>{let a=i.partialize({...f()});return n.setItem(i.name,{state:a,version:i.version})},p=g.setState;g.setState=(a,b)=>(p(a,b),o());let q=a((...a)=>(c(...a),o()),f,g);g.getInitialState=()=>q;let r=()=>{var a,b;if(!n)return;let d=++k;j=!1,l.forEach(a=>{var b;return a(null!=(b=f())?b:q)});let g=(null==(b=i.onRehydrateStorage)?void 0:b.call(i,null!=(a=f())?a:q))||void 0;return e(n.getItem.bind(n))(i.name).then(a=>{if(a)if("number"!=typeof a.version||a.version===i.version)return[!1,a.state];else{if(i.migrate){let b=i.migrate(a.state,a.version);return b instanceof Promise?b.then(a=>[!0,a]):[!0,b]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}return[!1,void 0]}).then(a=>{var b;if(d!==k)return;let[e,g]=a;if(c(h=i.merge(g,null!=(b=f())?b:q),!0),e)return o()}).then(()=>{d===k&&(null==g||g(f(),void 0),h=f(),j=!0,m.forEach(a=>a(h)))}).catch(a=>{d===k&&(null==g||g(void 0,a))})};return g.persist={setOptions:a=>{i={...i,...a},a.storage&&(n=a.storage)},clearStorage:()=>{++k,null==n||n.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>r(),hasHydrated:()=>j,onHydrate:a=>(l.add(a),()=>{l.delete(a)}),onFinishHydration:a=>(m.add(a),()=>{m.delete(a)})},i.skipHydration||r(),h||q}},17708:a=>{a.exports={style:{fontFamily:"'Geist Mono', 'Geist Mono Fallback'",fontStyle:"normal"},className:"__className_8c25df",variable:"__variable_8c25df"}},19099:(a,b,c)=>{"use strict";var d=c(54839);c.o(d,"useParams")&&c.d(b,{useParams:function(){return d.useParams}}),c.o(d,"usePathname")&&c.d(b,{usePathname:function(){return d.usePathname}}),c.o(d,"useRouter")&&c.d(b,{useRouter:function(){return d.useRouter}})},31417:(a,b,c)=>{"use strict";c.d(b,{v:()=>g});var d=c(67484);let e=a=>{let b,c=new Set,d=(a,d)=>{let e="function"==typeof a?a(b):a;if(!Object.is(e,b)){let a=b;b=(null!=d?d:"object"!=typeof e||null===e)?e:Object.assign({},b,e),c.forEach(c=>c(b,a))}},e=()=>b,f={setState:d,getState:e,getInitialState:()=>g,subscribe:a=>(c.add(a),()=>c.delete(a))},g=b=a(d,e,f);return f},f=a=>{let b=a?e(a):e,c=a=>(function(a,b=a=>a){let c=d.useSyncExternalStore(a.subscribe,d.useCallback(()=>b(a.getState()),[a,b]),d.useCallback(()=>b(a.getInitialState()),[a,b]));return d.useDebugValue(c),c})(b,a);return Object.assign(c,b),c},g=a=>a?f(a):f},35159:a=>{a.exports={style:{fontFamily:"'Geist', 'Geist Fallback'",fontStyle:"normal"},className:"__className_8eaea4",variable:"__variable_8eaea4"}},55091:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"default",{enumerable:!0,get:function(){return f}});let d=c(5735),e=c(22675);function f(){return(0,d.jsx)(e.HTTPAccessErrorFallback,{status:404,message:"This page could not be found."})}("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},55414:(a,b,c)=>{"use strict";let d;c.d(b,{hD:()=>aT,eH:()=>aR});for(var e,f,g=c(67484),h=[],i=[],j=Uint8Array,k="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=0,m=k.length;l<m;++l)h[l]=k[l],i[k.charCodeAt(l)]=l;function n(a){var b,c,d=function(a){var b=a.length;if(b%4>0)throw Error("Invalid string. Length must be a multiple of 4");var c=a.indexOf("=");-1===c&&(c=b);var d=c===b?0:4-c%4;return[c,d]}(a),e=d[0],f=d[1],g=new j((e+f)*3/4-f),h=0,k=f>0?e-4:e;for(c=0;c<k;c+=4)b=i[a.charCodeAt(c)]<<18|i[a.charCodeAt(c+1)]<<12|i[a.charCodeAt(c+2)]<<6|i[a.charCodeAt(c+3)],g[h++]=b>>16&255,g[h++]=b>>8&255,g[h++]=255&b;return 2===f&&(b=i[a.charCodeAt(c)]<<2|i[a.charCodeAt(c+1)]>>4,g[h++]=255&b),1===f&&(b=i[a.charCodeAt(c)]<<10|i[a.charCodeAt(c+1)]<<4|i[a.charCodeAt(c+2)]>>2,g[h++]=b>>8&255,g[h++]=255&b),g}function o(a){for(var b,c=a.length,d=c%3,e=[],f=0,g=c-d;f<g;f+=16383)e.push(function(a,b,c){for(var d,e=[],f=b;f<c;f+=3)d=(a[f]<<16&0xff0000)+(a[f+1]<<8&65280)+(255&a[f+2]),e.push(h[d>>18&63]+h[d>>12&63]+h[d>>6&63]+h[63&d]);return e.join("")}(a,f,f+16383>g?g:f+16383));return 1===d?e.push(h[(b=a[c-1])>>2]+h[b<<4&63]+"=="):2===d&&e.push(h[(b=(a[c-2]<<8)+a[c-1])>>10]+h[b>>4&63]+h[b<<2&63]+"="),e.join("")}function p(a){if(void 0===a)return{};if(!q(a))throw Error(`The arguments to a Convex function must be an object. Received: ${a}`);return a}function q(a){let b="object"==typeof a,c=Object.getPrototypeOf(a),d=null===c||c===Object.prototype||c?.constructor?.name==="Object";return b&&d}i[45]=62,i[95]=63;let r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),t=BigInt("0"),u=BigInt("8"),v=BigInt("256"),w="This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.";class x{[Symbol.toPrimitive](a){if("string"===a)return this.toString();throw Error(w)}valueOf(){throw Error(w)}toJSON(){throw Error(w)}toString(){return"[unresolved commit timestamp]"}}let y=new x;function z(a){return Number.isNaN(a)||!Number.isFinite(a)||Object.is(a,-0)}let A=DataView.prototype.setBigInt64?function(a){if(a<r||s<a)throw Error(`BigInt ${a} does not fit into a 64-bit signed integer.`);let b=new ArrayBuffer(8);return new DataView(b).setBigInt64(0,a,!0),o(new Uint8Array(b))}:function(a){a<t&&(a-=r+r);let b=a.toString(16);b.length%2==1&&(b="0"+b);let c=new Uint8Array(new ArrayBuffer(8)),d=0;for(let e of b.match(/.{2}/g).reverse())c.set([parseInt(e,16)],d++),a>>=u;return o(c)},B=DataView.prototype.getBigInt64?function(a){let b=n(a);if(8!==b.byteLength)throw Error(`Received ${b.byteLength} bytes, expected 8 for $integer`);return new DataView(b.buffer).getBigInt64(0,!0)}:function(a){let b=n(a);if(8!==b.byteLength)throw Error(`Received ${b.byteLength} bytes, expected 8 for $integer`);let c=t,d=t;for(let a of b)c+=BigInt(a)*v**d,d++;return c>s&&(c+=r+r),c};function C(a){if(a.length>1024)throw Error(`Field name ${a} exceeds maximum field name length 1024.`);if(a.startsWith("$"))throw Error(`Field name ${a} starts with a '$', which is reserved.`);for(let b=0;b<a.length;b+=1){let c=a.charCodeAt(b);if(c<32||c>=127)throw Error(`Field name ${a} has invalid character '${a[b]}': Field names can only contain non-control ASCII characters`)}}function D(a){if(null===a||"boolean"==typeof a||"number"==typeof a||"string"==typeof a)return a;if(Array.isArray(a))return a.map(a=>D(a));if("object"!=typeof a)throw Error(`Unexpected type of ${a}`);let b=Object.entries(a);if(1===b.length){let c=b[0][0];if("$bytes"===c){if("string"!=typeof a.$bytes)throw Error(`Malformed $bytes field on ${a}`);return n(a.$bytes).buffer}if("$integer"===c){if("string"!=typeof a.$integer)throw Error(`Malformed $integer field on ${a}`);return B(a.$integer)}if("$float"===c){if("string"!=typeof a.$float)throw Error(`Malformed $float field on ${a}`);let b=n(a.$float);if(8!==b.byteLength)throw Error(`Received ${b.byteLength} bytes, expected 8 for $float`);let c=new DataView(b.buffer).getFloat64(0,!0);if(!z(c))throw Error(`Float ${c} should be encoded as a number`);return c}if("$commitTs"===c){if(null!==a.$commitTs)throw Error(`Malformed $commitTs field on ${a}`);return y}if("$set"===c)throw Error("Received a Set which is no longer supported as a Convex type.");if("$map"===c)throw Error("Received a Map which is no longer supported as a Convex type.")}let c={};for(let[b,d]of Object.entries(a))C(b),c[b]=D(d);return c}function E(a){let b=JSON.stringify(a,(a,b)=>void 0===b?"undefined":"bigint"==typeof b?`${b.toString()}n`:b);if(b.length>16384){let a="[...truncated]",c=16384-a.length,d=b.codePointAt(c-1);return void 0!==d&&d>65535&&(c-=1),b.substring(0,c)+a}return b}function F(a,b,c,d){return a?`${b}${E(c)} is not a supported Convex type (present at path ${a} in original object ${E(d)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${b}${E(c)} is not a supported Convex type.`}function G(a){return function a(b,c,d,e){if(void 0===b){let a=d&&` (present at path ${d} in original object ${E(c)})`;throw Error(`undefined is not a valid Convex value${a}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(null===b)return b;if("bigint"==typeof b){if(b<r||s<b)throw Error(`BigInt ${b} does not fit into a 64-bit signed integer.`);return{$integer:A(b)}}if("number"==typeof b)if(!z(b))return b;else{let a=new ArrayBuffer(8);return new DataView(a).setFloat64(0,b,!0),{$float:o(new Uint8Array(a))}}if("boolean"==typeof b||"string"==typeof b)return b;if(b instanceof ArrayBuffer)return{$bytes:o(new Uint8Array(b))};if(b instanceof x)return{$commitTs:null};if(Array.isArray(b))return b.map((b,e)=>a(b,c,d+`[${e}]`,!1));if(b instanceof Set)throw Error(F(d,"Set",[...b],c));if(b instanceof Map)throw Error(F(d,"Map",[...b],c));if(!q(b)){let a=b?.constructor?.name;throw Error(F(d,a?`${a} `:"",b,c))}let f={},g=Object.entries(b);for(let[b,h]of(g.sort(([a,b],[c,d])=>a===c?0:a<c?-1:1),g))void 0!==h?(C(b),f[b]=a(h,c,d+`.${b}`,!1)):e&&(C(b),f[b]=function(b,c,d){if(void 0===b)return{$undefined:null};if(void 0===c)throw Error(`Programming error. Current value is ${E(b)} but original value is undefined`);return a(b,c,d,!1)}(h,c,d+`.${b}`));return f}(a,a,"",!1)}var H=Object.defineProperty,I=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?H(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};let J=Symbol.for("ConvexError");class K extends(f=Error,e=J,f){constructor(a){super("string"==typeof a?a:E(a)),I(this,"name","ConvexError"),I(this,"data"),I(this,e,!0),this.data=a}}let L=()=>Array.from({length:4},()=>0);L(),L();let M="1.45.0";var N=Object.defineProperty,O=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?N(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};function P(a){switch(a){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class Q{constructor(a){O(this,"_onLogLineFuncs"),O(this,"_verbose"),this._onLogLineFuncs={},this._verbose=a.verbose}addLogLineListener(a){let b=Math.random().toString(36).substring(2,15);for(let a=0;a<10&&void 0!==this._onLogLineFuncs[b];a++)b=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[b]=a,()=>{delete this._onLogLineFuncs[b]}}logVerbose(...a){if(this._verbose)for(let b of Object.values(this._onLogLineFuncs))b("debug",`${new Date().toISOString()}`,...a)}log(...a){for(let b of Object.values(this._onLogLineFuncs))b("info",...a)}warn(...a){for(let b of Object.values(this._onLogLineFuncs))b("warn",...a)}error(...a){for(let b of Object.values(this._onLogLineFuncs))b("error",...a)}}function R(a){let b=new Q(a);return b.addLogLineListener((a,...b)=>{switch(a){case"debug":console.debug(...b);break;case"info":default:console.log(...b);break;case"warn":console.warn(...b);break;case"error":console.error(...b)}}),b}function S(a,b,c,d,e){let f=P(c);if("object"==typeof e&&(e=`ConvexError ${JSON.stringify(e.errorData,null,2)}`),"info"===b){let b=e.match(/^\[.*?\] /);if(null===b)return void a.error(`[CONVEX ${f}(${d})] Could not parse console.log`);let c=e.slice(1,b[0].length-2),g=e.slice(b[0].length);a.log(`%c[CONVEX ${f}(${d})] [${c}]`,"color:rgb(0, 145, 255)",g)}else a.error(`[CONVEX ${f}(${d})] ${e}`)}function T(a,b,c){let d=P(a);return`[CONVEX ${d}(${b})] ${c.errorMessage}
|
|
2
|
-
Called by client`}function U(a,b){return b.data=a.errorData,b}function V(a){let b,c,d=a.split(":");return 1===d.length?(b=d[0],c="default"):(b=d.slice(0,d.length-1).join(":"),c=d[d.length-1]),b.endsWith(".js")&&(b=b.slice(0,-3)),`${b}:${c}`}function W(a,b){return JSON.stringify({udfPath:V(a),args:G(b)})}function X(a,b,c){let{initialNumItems:d,id:e}=c;return JSON.stringify({type:"paginated",udfPath:V(a),args:G(b),options:G({initialNumItems:d,id:e})})}var Y=Object.defineProperty,Z=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?Y(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class ${constructor(){Z(this,"nextQueryId"),Z(this,"querySetVersion"),Z(this,"querySet"),Z(this,"queryIdToToken"),Z(this,"identityVersion"),Z(this,"auth"),Z(this,"outstandingQueriesOlderThanRestart"),Z(this,"outstandingAuthOlderThanRestart"),Z(this,"paused"),Z(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return 0===this.outstandingQueriesOlderThanRestart.size&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(a,b,c,d){let e=V(a),f=W(e,b),g=this.querySet.get(f);if(void 0!==g)return g.numSubscribers+=1,{queryToken:f,modification:null,unsubscribe:()=>this.removeSubscriber(f)};{let a=this.nextQueryId++;this.querySet.set(f,{id:a,canonicalizedUdfPath:e,args:b,numSubscribers:1,journal:c,componentPath:d}),this.queryIdToToken.set(a,f);let g=this.querySetVersion,h=this.querySetVersion+1,i={type:"Add",queryId:a,udfPath:e,args:[G(b)],journal:c,componentPath:d};return this.paused?this.pendingQuerySetModifications.set(a,i):this.querySetVersion=h,{queryToken:f,modification:{type:"ModifyQuerySet",baseVersion:g,newVersion:h,modifications:[i]},unsubscribe:()=>this.removeSubscriber(f)}}}transition(a){for(let b of a.modifications)switch(b.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(b.queryId);let a=b.journal;if(void 0!==a){let c=this.queryIdToToken.get(b.queryId);void 0!==c&&(this.querySet.get(c).journal=a)}break}case"QueryRemoved":this.outstandingQueriesOlderThanRestart.delete(b.queryId);break;default:throw Error(`Invalid modification ${b.type}`)}}queryId(a,b){let c=W(V(a),b),d=this.querySet.get(c);return void 0!==d?d.id:null}isCurrentOrNewerAuthVersion(a){return a>=this.identityVersion}getAuth(){return this.auth}setAuth(a){this.auth={tokenType:"User",value:a};let b=this.identityVersion;return this.paused||(this.identityVersion=b+1),{type:"Authenticate",baseVersion:b,...this.auth}}setAdminAuth(a,b){let c={tokenType:"Admin",value:a,impersonating:b};this.auth=c;let d=this.identityVersion;return this.paused||(this.identityVersion=d+1),{type:"Authenticate",baseVersion:d,...c}}clearAuth(){this.auth=void 0,this.markAuthCompletion();let a=this.identityVersion;return this.paused||(this.identityVersion=a+1),{type:"Authenticate",tokenType:"None",baseVersion:a}}hasAuth(){return!!this.auth}isNewAuth(a){return this.auth?.value!==a}queryPath(a){let b=this.queryIdToToken.get(a);return b?this.querySet.get(b).canonicalizedUdfPath:null}queryArgs(a){let b=this.queryIdToToken.get(a);return b?this.querySet.get(b).args:null}queryToken(a){return this.queryIdToToken.get(a)??null}queryJournal(a){return this.querySet.get(a)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let a=[];for(let b of this.querySet.values()){let c={type:"Add",queryId:b.id,udfPath:b.canonicalizedUdfPath,args:[G(b.args)],journal:b.journal,componentPath:b.componentPath};a.push(c),this.outstandingQueriesOlderThanRestart.add(b.id)}this.querySetVersion=1;let b={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:a};if(!this.auth)return this.identityVersion=0,[b,void 0];this.outstandingAuthOlderThanRestart=!0;let c={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[b,c]}pause(){this.paused=!0}resume(){let a=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,b=void 0!==this.auth?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[a,b]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(a){let b=this.querySet.get(a);if(b.numSubscribers>1)return b.numSubscribers-=1,null;{this.querySet.delete(a),this.queryIdToToken.delete(b.id),this.outstandingQueriesOlderThanRestart.delete(b.id);let c=this.querySetVersion,d=this.querySetVersion+1,e={type:"Remove",queryId:b.id};return this.paused?this.pendingQuerySetModifications.has(b.id)?this.pendingQuerySetModifications.delete(b.id):this.pendingQuerySetModifications.set(b.id,e):this.querySetVersion=d,{type:"ModifyQuerySet",baseVersion:c,newVersion:d,modifications:[e]}}}}var _=Object.defineProperty,aa=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?_(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class ab{constructor(a,b){this.logger=a,this.markConnectionStateDirty=b,aa(this,"inflightRequests"),aa(this,"requestsOlderThanRestart"),aa(this,"inflightMutationsCount",0),aa(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(a,b){let c=new Promise(c=>{this.inflightRequests.set(a.requestId,{message:a,status:{status:b?"Requested":"NotSent",requestedAt:new Date,onResult:c}}),"Mutation"===a.type?this.inflightMutationsCount++:"Action"===a.type&&this.inflightActionsCount++});return this.markConnectionStateDirty(),c}onResponse(a){let b,c,d=this.inflightRequests.get(a.requestId);if(void 0===d||"Completed"===d.status.status)return null;let e="Mutation"===d.message.type?"mutation":"action",f=d.message.udfPath;for(let b of a.logLines)S(this.logger,"info",e,f,b);let g=d.status;if(a.success)b={success:!0,logLines:a.logLines,value:D(a.result)},c=()=>g.onResult(b);else{let d=a.result,{errorData:h}=a;S(this.logger,"error",e,f,d),b={success:!1,errorMessage:d,errorData:void 0!==h?D(h):void 0,logLines:a.logLines},c=()=>g.onResult(b)}return"ActionResponse"!==a.type&&a.success?(d.status={status:"Completed",result:b,ts:a.ts,onResolve:c},null):(c(),this.inflightRequests.delete(a.requestId),this.requestsOlderThanRestart.delete(a.requestId),"Action"===d.message.type?this.inflightActionsCount--:"Mutation"===d.message.type&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:a.requestId,result:b})}removeCompleted(a){let b=new Map;for(let[c,d]of this.inflightRequests.entries()){let e=d.status;"Completed"===e.status&&e.ts.lessThanOrEqual(a)&&(e.onResolve(),b.set(c,e.result),"Mutation"===d.message.type?this.inflightMutationsCount--:"Action"===d.message.type&&this.inflightActionsCount--,this.inflightRequests.delete(c),this.requestsOlderThanRestart.delete(c))}return b.size>0&&this.markConnectionStateDirty(),b}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let a=[];for(let[b,c]of this.inflightRequests){if("NotSent"===c.status.status){c.status.status="Requested",a.push(c.message);continue}if("Mutation"===c.message.type)a.push(c.message);else if("Action"===c.message.type){if(this.inflightRequests.delete(b),this.requestsOlderThanRestart.delete(b),this.inflightActionsCount--,"Completed"===c.status.status)throw Error("Action should never be in 'Completed' state");c.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),a}resume(){let a=[];for(let[,b]of this.inflightRequests)if("NotSent"===b.status.status){b.status.status="Requested",a.push(b.message);continue}return a}hasIncompleteRequests(){for(let a of this.inflightRequests.values())if("Requested"===a.status.status)return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return 0===this.requestsOlderThanRestart.size}timeOfOldestInflightRequest(){if(0===this.inflightRequests.size)return null;let a=Date.now();for(let b of this.inflightRequests.values())"Completed"!==b.status.status&&b.status.requestedAt.getTime()<a&&(a=b.status.requestedAt.getTime());return new Date(a)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}let ac=Symbol.for("functionName"),ad=Symbol.for("toReferencePath");function ae(a){let b=function(a){let b;if("string"==typeof a)b=a.startsWith("function://")?{functionHandle:a}:{name:a};else if(a[ac])b={name:a[ac]};else{let c=a[ad]??null;if(!c)throw Error(`${a} is not a functionReference`);b={reference:c}}return b}(a);if(void 0===b.name){if(void 0!==b.functionHandle)throw Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${b.functionHandle}`);if(void 0!==b.reference)throw Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${b.reference}`);throw Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(b)}`)}if("string"==typeof a)return a;let c=a[ac];if(!c)throw Error(`${a} is not a functionReference`);return c}!function a(b=[]){return new Proxy({},{get(c,d){if("string"==typeof d)return a([...b,d]);if(d===ac){if(b.length<2){let a=["api",...b].join(".");throw Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${a}\``)}let a=b.slice(0,-1).join("/"),c=b[b.length-1];return"default"===c?a:a+":"+c}return d===Symbol.toStringTag?"FunctionReference":void 0}})}();var af=Object.defineProperty,ag=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?af(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class ah{constructor(a){ag(this,"queryResults"),ag(this,"modifiedQueries"),this.queryResults=a,this.modifiedQueries=[]}getQuery(a,...b){let c=p(b[0]),d=ae(a),e=this.queryResults.get(W(d,c));if(void 0!==e)return ah.queryValue(e.result)}getAllQueries(a){let b=[],c=ae(a);for(let a of this.queryResults.values())a.udfPath===V(c)&&b.push({args:a.args,value:ah.queryValue(a.result)});return b}setQuery(a,b,c){let d=p(b),e=ae(a),f=W(e,d);this.queryResults.set(f,{udfPath:e,args:d,result:void 0===c?void 0:{success:!0,value:c,logLines:[]}}),this.modifiedQueries.push(f)}static queryValue(a){return void 0===a?void 0:a.success?a.value:void 0}}class ai{constructor(){ag(this,"queryResults"),ag(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(a,b){this.optimisticUpdates=this.optimisticUpdates.filter(a=>!b.has(a.mutationId));let c=this.queryResults;this.queryResults=new Map(a);let d=new ah(this.queryResults);for(let a of this.optimisticUpdates)a.update(d);let e=[];for(let[a,b]of this.queryResults){let d=c.get(a);(void 0===d||d.result!==b.result)&&e.push(a)}return e}applyOptimisticUpdate(a,b){this.optimisticUpdates.push({update:a,mutationId:b});let c=new ah(this.queryResults);return a(c),c.modifiedQueries}rawQueryResult(a){let b=this.queryResults.get(a);if(void 0!==b)return b.result}queryResult(a){let b=this.queryResults.get(a);if(void 0===b)return;let c=b.result;if(void 0!==c){if(c.success)return c.value;if(void 0!==c.errorData)throw U(c,new K(T("query",b.udfPath,c)));throw Error(T("query",b.udfPath,c))}}hasQueryResult(a){return void 0!==this.queryResults.get(a)}queryLogs(a){let b=this.queryResults.get(a);return b?.result?.logLines}}var aj=Object.defineProperty,ak=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?aj(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class al{constructor(a,b){ak(this,"low"),ak(this,"high"),ak(this,"__isUnsignedLong__"),this.low=0|a,this.high=0|b,this.__isUnsignedLong__=!0}static isLong(a){return!0===(a&&a.__isUnsignedLong__)}static fromBytesLE(a){return new al(a[0]|a[1]<<8|a[2]<<16|a[3]<<24,a[4]|a[5]<<8|a[6]<<16|a[7]<<24)}toBytesLE(){let a=this.high,b=this.low;return[255&b,b>>>8&255,b>>>16&255,b>>>24,255&a,a>>>8&255,a>>>16&255,a>>>24]}static fromNumber(a){return isNaN(a)||a<0?am:a>=ao?ap:new al(a%an|0,a/an|0)}toString(){return(BigInt(this.high)*BigInt(an)+BigInt(this.low)).toString()}equals(a){return al.isLong(a)||(a=al.fromValue(a)),(this.high>>>31!=1||a.high>>>31!=1)&&this.high===a.high&&this.low===a.low}notEquals(a){return!this.equals(a)}comp(a){return(al.isLong(a)||(a=al.fromValue(a)),this.equals(a))?0:a.high>>>0>this.high>>>0||a.high===this.high&&a.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(a){return 0>=this.comp(a)}static fromValue(a){return"number"==typeof a?al.fromNumber(a):new al(a.low,a.high)}}let am=new al(0,0),an=0x100000000,ao=0xffffffffffffffff,ap=new al(-1,-1);var aq=Object.defineProperty,ar=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?aq(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class as{constructor(a,b){ar(this,"version"),ar(this,"remoteQuerySet"),ar(this,"queryPath"),ar(this,"logger"),this.version={querySet:0,ts:al.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=a,this.logger=b}transition(a){let b=a.startVersion;if(this.version.querySet!==b.querySet||this.version.ts.notEquals(b.ts)||this.version.identity!==b.identity)throw Error(`Invalid start version: ${b.ts.toString()}:${b.querySet}:${b.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(let b of a.modifications)switch(b.type){case"QueryUpdated":{let a=this.queryPath(b.queryId);if(a)for(let c of b.logLines)S(this.logger,"info","query",a,c);let c=D(b.value??null);this.remoteQuerySet.set(b.queryId,{success:!0,value:c,logLines:b.logLines});break}case"QueryFailed":{let a=this.queryPath(b.queryId);if(a)for(let c of b.logLines)S(this.logger,"info","query",a,c);let{errorData:c}=b;this.remoteQuerySet.set(b.queryId,{success:!1,errorMessage:b.errorMessage,errorData:void 0!==c?D(c):void 0,logLines:b.logLines});break}case"QueryRemoved":this.remoteQuerySet.delete(b.queryId);break;default:throw Error(`Invalid modification ${b.type}`)}this.version=a.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}function at(a){let b=n(a);return al.fromBytesLE(Array.from(b))}function au(a){switch(a.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...a};case"MutationResponse":if(a.success)return{...a,ts:at(a.ts)};return{...a};case"Transition":return{...a,startVersion:{...a.startVersion,ts:at(a.startVersion.ts)},endVersion:{...a.endVersion,ts:at(a.endVersion.ts)}}}}var av=Object.defineProperty,aw=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?av(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};function ax(){return(void 0===d&&(d=Date.now()),"u"<typeof performance||!performance.now)?Date.now():Math.round(d+performance.now())}function ay(){return`t=${Math.round((ax()-d)/100)/10}s`}let az={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};class aA{constructor(a,b,c,d,e,f){this.markConnectionStateDirty=e,this.debug=f,aw(this,"socket"),aw(this,"connectionCount"),aw(this,"_hasEverConnected",!1),aw(this,"lastCloseReason"),aw(this,"transitionChunkBuffer",null),aw(this,"defaultInitialBackoff"),aw(this,"maxBackoff"),aw(this,"retries"),aw(this,"serverInactivityThreshold"),aw(this,"reconnectDueToServerInactivityTimeout"),aw(this,"scheduledReconnect",null),aw(this,"networkOnlineHandler",null),aw(this,"pendingNetworkRecoveryInfo",null),aw(this,"uri"),aw(this,"onOpen"),aw(this,"onResume"),aw(this,"onMessage"),aw(this,"webSocketConstructor"),aw(this,"logger"),aw(this,"onServerDisconnectError"),this.webSocketConstructor=c,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=a,this.onOpen=b.onOpen,this.onResume=b.onResume,this.onMessage=b.onMessage,this.onServerDisconnectError=b.onServerDisconnectError,this.logger=d,this.setupNetworkListener(),this.connect()}setSocketState(a){this.socket=a,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}setupNetworkListener(){"u"<typeof window||"function"!=typeof window.addEventListener||null===this.networkOnlineHandler&&(this.networkOnlineHandler=()=>{this._logVerbose("network online event detected"),this.tryReconnectImmediately()},window.addEventListener("online",this.networkOnlineHandler),this._logVerbose("network online event listener registered"))}cleanupNetworkListener(){this.networkOnlineHandler&&"u">typeof window&&"function"==typeof window.removeEventListener&&(window.removeEventListener("online",this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose("network online event listener removed"))}assembleTransition(a){if(a.partNumber<0||a.partNumber>=a.totalParts||0===a.totalParts||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==a.totalParts||this.transitionChunkBuffer.transitionId!==a.transitionId))throw this.transitionChunkBuffer=null,Error("Invalid TransitionChunk");if(null===this.transitionChunkBuffer&&(this.transitionChunkBuffer={chunks:[],totalParts:a.totalParts,transitionId:a.transitionId}),a.partNumber!==this.transitionChunkBuffer.chunks.length){let b=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,Error(`TransitionChunk received out of order: expected part ${b}, got ${a.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(a.chunk),this.transitionChunkBuffer.chunks.length===a.totalParts){let a=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;let b=au(JSON.parse(a));if("Transition"!==b.type)throw Error(`Expected Transition, got ${b.type} after assembling chunks`);return b}return null}connect(){if("terminated"===this.socket.state)return;if("disconnected"!==this.socket.state&&"stopped"!==this.socket.state)throw Error("Didn't start connection from disconnected state: "+this.socket.state);let a=new this.webSocketConstructor(this.uri);this._logVerbose("constructed WebSocket"),this.setSocketState({state:"connecting",ws:a,paused:"no"}),this.resetServerInactivityTimeout(),a.onopen=()=>{if(this.logger.logVerbose("begin ws.onopen"),"connecting"!==this.socket.state)throw Error("onopen called with socket not in connecting state");if(this.setSocketState({state:"ready",ws:a,paused:"yes"===this.socket.paused?"uninitialized":"no"}),this.resetServerInactivityTimeout(),"no"===this.socket.paused&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:ax()})),"InitialConnect"!==this.lastCloseReason&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",ay(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",ay())),this.connectionCount+=1,this.lastCloseReason=null,null!==this.pendingNetworkRecoveryInfo){let{timeSavedMs:a}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:"Event",eventType:"NetworkRecoveryReconnect",event:{timeSavedMs:a}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(a/1e3)}s of waiting`)}},a.onerror=a=>{this.transitionChunkBuffer=null;let b=a.message;b&&this.logger.log(`WebSocket error message: ${b}`)},a.onmessage=a=>{this.resetServerInactivityTimeout();let b=a.data.length,c=au(JSON.parse(a.data));if(this._logVerbose(`received ws message with type ${c.type}`),"Ping"!==c.type){if("TransitionChunk"===c.type){let a=this.assembleTransition(c);if(!a)return;c=a,this._logVerbose(`assembled full ws message of type ${c.type}`)}null!==this.transitionChunkBuffer&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${c.type} while buffering TransitionChunks`)),"Transition"===c.type&&this.reportLargeTransition({messageLength:b,transition:c}),this.onMessage(c).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())}},a.onclose=a=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,null===this.lastCloseReason&&(this.lastCloseReason=a.reason||`closed with code ${a.code}`),1e3!==a.code&&1001!==a.code&&1005!==a.code&&4040!==a.code){let b=`WebSocket closed with code ${a.code}`;a.reason&&(b+=`: ${a.reason}`),this.logger.log(b),this.onServerDisconnectError&&a.reason&&this.onServerDisconnectError(b)}let b=function(a){if(void 0===a)return"Unknown";for(let b of Object.keys(az))if(a.startsWith(b))return b;return"Unknown"}(a.reason);this.scheduleReconnect(b)}}socketState(){return this.socket.state}sendMessage(a){let b={type:a.type,..."Authenticate"===a.type&&"User"===a.tokenType?{value:`...${a.value.slice(-7)}`}:{}};if("ready"===this.socket.state&&"no"===this.socket.paused){let c=JSON.stringify(function(a){switch(a.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...a};case"Connect":if(void 0===a.maxObservedTimestamp)return{...a,maxObservedTimestamp:void 0};return{...a,maxObservedTimestamp:o(new Uint8Array(a.maxObservedTimestamp.toBytesLE()))}}}(a)),d=!1;try{this.socket.ws.send(c),d=!0}catch(a){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${a}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${d?"sent":"failed to send"} message with type ${a.type}: ${JSON.stringify(b)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(b)}`),!1}resetServerInactivityTimeout(){"terminated"!==this.socket.state&&(null!==this.reconnectDueToServerInactivityTimeout&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(a){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};let b=this.nextBackoff(a);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(b)}ms`);let c=ax(),d=setTimeout(()=>{this.scheduledReconnect?.timeout===d&&(this.scheduledReconnect=null,this.connect())},b);this.scheduledReconnect={timeout:d,scheduledAt:c,backoffMs:b}}closeAndReconnect(a){switch(this._logVerbose(`begin closeAndReconnect with reason ${a}`),this.socket.state){case"disconnected":case"terminated":case"stopped":return;case"connecting":case"ready":this.lastCloseReason=a,this.close(),this.scheduleReconnect("client");return;default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{let a=this.socket.ws;return a.onmessage=a=>{this._logVerbose("Ignoring message received after close")},new Promise(b=>{a.onclose=()=>{this._logVerbose("Closed after connecting"),b()},a.onopen=()=>{this._logVerbose("Opened after connecting"),a.close()}})}case"ready":{this._logVerbose("ws.close called");let a=this.socket.ws;a.onmessage=a=>{this._logVerbose("Ignoring message received after close")};let b=new Promise(b=>{a.onclose=()=>{b()}});return a.close(),b}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.cleanupNetworkListener(),this.socket.state){case"terminated":case"stopped":case"disconnected":case"connecting":case"ready":{let a=this.close();return this.setSocketState({state:"terminated"}),a}default:throw this.socket,Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case"terminated":return Promise.resolve();case"connecting":case"stopped":case"disconnected":case"ready":{this.cleanupNetworkListener();let a=this.close();return this.socket={state:"stopped"},a}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case"stopped":break;case"terminated":case"connecting":case"ready":case"disconnected":this.logger.logVerbose("Restart called without stopping first");return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":this.socket={...this.socket,paused:"yes"};return;default:return void this.socket}}tryReconnectImmediately(){if(this._logVerbose("tryReconnectImmediately called"),"disconnected"!==this.socket.state)return void this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);let a=null;if(this.scheduledReconnect){let b=ax()-this.scheduledReconnect.scheduledAt;a=Math.max(0,this.scheduledReconnect.backoffMs-b),this._logVerbose(`would have waited ${Math.round(a)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(b)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose("canceled scheduled reconnect")}this.logger.log("Network recovery detected, reconnecting immediately"),this.pendingNetworkRecoveryInfo=null!==a?{timeSavedMs:a}:null,this.connect()}resume(){switch(this.socket.state){case"connecting":this.socket={...this.socket,paused:"no"};return;case"ready":"uninitialized"===this.socket.paused?(this.socket={...this.socket,paused:"no"},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:ax()})):"yes"===this.socket.paused&&(this.socket={...this.socket,paused:"no"},this.onResume());return;case"terminated":case"stopped":case"disconnected":return;default:this.socket}this.connect()}connectionState(){return{isConnected:"ready"===this.socket.state,hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(a){this.logger.logVerbose(a)}nextBackoff(a){let b=("client"===a?100:"Unknown"===a?this.defaultInitialBackoff:az[a].timeout)*Math.pow(2,this.retries);this.retries+=1;let c=Math.min(b,this.maxBackoff),d=c*(Math.random()-.5);return c+d}reportLargeTransition({transition:a,messageLength:b}){if(void 0===a.clientClockSkew||void 0===a.serverTs)return;let c=ax()-a.clientClockSkew-a.serverTs/1e6,d=`${Math.round(c)}ms`,e=`${Math.round(b/1e4)/100}MB`,f=b/(c/1e3),g=`${Math.round(f/1e4)/100}MB per second`;this._logVerbose(`received ${e} transition in ${d} at ${g}`),b>2e7?this.logger.log(`received query results totaling more that 20MB (${e}) which will take a long time to download on slower connections`):c>2e4&&this.logger.log(`received query results totaling ${e} which took more than 20s to arrive (${d})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:c,messageLength:b}})}}class aB extends Error{}function aC(a,b){let c;if("string"!=typeof a)throw new aB("Invalid token specified: must be a string");b||(b={});let d=+(!0!==b.header),e=a.split(".")[d];if("string"!=typeof e)throw new aB(`Invalid token specified: missing part #${d+1}`);try{c=function(a){let b=a.replace(/-/g,"+").replace(/_/g,"/");switch(b.length%4){case 0:break;case 2:b+="==";break;case 3:b+="=";break;default:throw Error("base64 string is not of the correct length")}try{var c;return c=b,decodeURIComponent(atob(c).replace(/(.)/g,(a,b)=>{let c=b.charCodeAt(0).toString(16).toUpperCase();return c.length<2&&(c="0"+c),"%"+c}))}catch{return atob(b)}}(e)}catch(a){throw new aB(`Invalid token specified: invalid base64 for part #${d+1} (${a.message})`)}try{return JSON.parse(c)}catch(a){throw new aB(`Invalid token specified: invalid json for part #${d+1} (${a.message})`)}}aB.prototype.name="InvalidTokenError";var aD=Object.defineProperty,aE=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?aD(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class aF{constructor(a,b,c){aE(this,"authState",{state:"noAuth"}),aE(this,"configVersion",0),aE(this,"syncState"),aE(this,"authenticate"),aE(this,"stopSocket"),aE(this,"tryRestartSocket"),aE(this,"pauseSocket"),aE(this,"resumeSocket"),aE(this,"clearAuth"),aE(this,"logger"),aE(this,"refreshTokenLeewaySeconds"),aE(this,"initialAuthTokenReuse"),aE(this,"lastRefreshChange"),aE(this,"tokenConfirmationAttempts",0),this.syncState=a,this.authenticate=b.authenticate,this.stopSocket=b.stopSocket,this.tryRestartSocket=b.tryRestartSocket,this.pauseSocket=b.pauseSocket,this.resumeSocket=b.resumeSocket,this.clearAuth=b.clearAuth,this.logger=c.logger,this.refreshTokenLeewaySeconds=c.refreshTokenLeewaySeconds,this.initialAuthTokenReuse=c.initialAuthTokenReuse,this.lastRefreshChange=!1}notifyRefreshChange(a){"noAuth"!==this.authState.state&&"initialRefetch"!==this.authState.state&&this.authState.config.onRefreshChange&&this.lastRefreshChange!==a&&(this.lastRefreshChange=a,this.authState.config.onRefreshChange(a))}async setConfig(a,b,c){this.resetAuthState(),this._logVerbose("pausing WS for auth token fetch"),this.pauseSocket();let d=await this.fetchTokenAndGuardAgainstRace(a,{forceRefreshToken:!1});if(d.isFromOutdatedConfig)return;let e={fetchToken:a,onAuthChange:b,onRefreshChange:c};d.value?(this.setAuthState({state:"waitingForServerConfirmationOfCachedToken",config:e,hasRetried:!1}),this.authenticate(d.value)):(this.setAuthState({state:"initialRefetch",config:e}),await this.refetchToken()),this._logVerbose("resuming WS after auth token fetch"),this.resumeSocket()}onTransition(a){if(this.syncState.isCurrentOrNewerAuthVersion(a.endVersion.identity)&&!(a.endVersion.identity<=a.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),"waitingForServerConfirmationOfCachedToken"===this.authState.state){this._logVerbose("server confirmed auth token is valid");let b=this.syncState.getAuth()?.value;this.initialAuthTokenReuse&&b?this.scheduleTokenRefetch(b,a.clientClockSkew):this.refetchToken(),this.authState.config.onAuthChange(!0);return}"waitingForServerConfirmationOfFreshToken"===this.authState.state&&(this._logVerbose("server confirmed new auth token is valid"),this.notifyRefreshChange(!1),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(a){if(!1===a.authUpdateAttempted&&("waitingForServerConfirmationOfFreshToken"===this.authState.state||"waitingForServerConfirmationOfCachedToken"===this.authState.state))return void this._logVerbose("ignoring non-auth token expired error");let{baseVersion:b}=a;this.syncState.isCurrentOrNewerAuthVersion(b+1)?this.tryToReauthenticate(a):this._logVerbose("ignoring auth error for previous auth attempt")}async tryToReauthenticate(a){if(this._logVerbose(`attempting to reauthenticate: ${a.error}`),"noAuth"===this.authState.state||"waitingForServerConfirmationOfFreshToken"===this.authState.state&&this.tokenConfirmationAttempts>=2){this.logger.error(`Failed to authenticate: "${a.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),"noAuth"!==this.authState.state&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}if("waitingForServerConfirmationOfFreshToken"===this.authState.state&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${2-this.tokenConfirmationAttempts} attempts remaining`)),this.notifyRefreshChange(!0),await this.stopSocket(),"noAuth"===this.authState.state)return;let b=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});b.isFromOutdatedConfig||(b.value&&this.syncState.isNewAuth(b.value)?(this.authenticate(b.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:b.value,hadAuth:"notRefetching"===this.authState.state||"waitingForScheduledRefetch"===this.authState.state})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if("noAuth"===this.authState.state)return;this._logVerbose("refetching auth token");let a=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});a.isFromOutdatedConfig||(a.value?this.syncState.isNewAuth(a.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:a.value,config:this.authState.config}),this.authenticate(a.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(a,b){let c;if("noAuth"===this.authState.state)return;let d=this.decodeToken(a);if(!d)return void this.logger.error("Auth token is not a valid JWT, cannot refetch the token");let{iat:e,exp:f}=d;if(!e||!f)return void this.logger.error("Auth token does not have required fields, cannot refetch the token");let g=f-e;if(g<=2)return void this.logger.error("Auth token does not live long enough, cannot refetch the token");void 0!==b?(c=f-(Date.now()-b)/1e3)<=0&&(c=0):c=g;let h=Math.min(1728e6,(c-this.refreshTokenLeewaySeconds)*1e3);h<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${c}s`),h=0);let i=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},h);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:i,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${h}ms`)}async fetchTokenAndGuardAgainstRace(a,b){let c=++this.configVersion;this._logVerbose(`fetching token with config version ${c}`);let d=await a(b);return this.configVersion!==c?(this._logVerbose(`stale config version, expected ${c}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:d}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(a){a(!1),this.resetAuthState()}resetAuthState(){this.notifyRefreshChange(!1),this.setAuthState({state:"noAuth"})}setAuthState(a){let b="waitingForServerConfirmationOfFreshToken"===a.state?{hadAuth:a.hadAuth,state:a.state,token:`...${a.token.slice(-7)}`}:{state:a.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(b)}`),a.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0}"waitingForScheduledRefetch"===this.authState.state&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=a}decodeToken(a){try{return aC(a)}catch(a){return this._logVerbose(`Error decoding token: ${a instanceof Error?a.message:"Unknown error"}`),null}}_logVerbose(a){this.logger.logVerbose(`${a} [v${this.configVersion}]`)}}let aG=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function aH(a){let b=a.name.slice(6);return{name:b=b.charAt(0).toLowerCase()+b.slice(1),startTime:a.startTime}}var aI=Object.defineProperty,aJ=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?aI(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class aK{constructor(a,b,c){let d;if(aJ(this,"address"),aJ(this,"state"),aJ(this,"requestManager"),aJ(this,"webSocketManager"),aJ(this,"authenticationManager"),aJ(this,"remoteQuerySet"),aJ(this,"optimisticQueryResults"),aJ(this,"_transitionHandlerCounter",0),aJ(this,"_nextRequestId"),aJ(this,"_onTransitionFns",new Map),aJ(this,"_sessionId"),aJ(this,"firstMessageReceived",!1),aJ(this,"debug"),aJ(this,"logger"),aJ(this,"maxObservedTimestamp"),aJ(this,"connectionStateSubscribers",new Map),aJ(this,"nextConnectionStateSubscriberId",0),aJ(this,"_lastPublishedConnectionState"),aJ(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{let a=this.connectionState();if(JSON.stringify(a)!==JSON.stringify(this._lastPublishedConnectionState))for(let b of(this._lastPublishedConnectionState=a,this.connectionStateSubscribers.values()))b(a)})}),aJ(this,"mark",a=>{var b;this.debug&&(b=this.sessionId,"u">typeof performance&&performance.mark&&performance.mark(a,{detail:{sessionId:b}}))}),"object"==typeof a)throw Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");c?.skipConvexDeploymentUrlCheck!==!0&&function(a){if(void 0===a)throw Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if("string"!=typeof a)throw Error(`Invalid deployment address: found ${a}".`);if(!(a.startsWith("http:")||a.startsWith("https:")))throw Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${a}".`);try{new URL(a)}catch{throw Error(`Invalid deployment address: "${a}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(a.endsWith(".convex.site"))throw Error(`Invalid deployment address: "${a}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}(a);const e=(c={...c}).authRefreshTokenLeewaySeconds??10;let f=c.webSocketConstructor;if(!f&&"u"<typeof WebSocket)throw Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");f=f||WebSocket,this.debug=c.reportDebugInfoToConvex??!1,this.address=a,this.logger=!1===c.logger?function(a){return new Q(a)}({verbose:c.verbose??!1}):!0!==c.logger&&c.logger?c.logger:R({verbose:c.verbose??!1});const g=a.search("://");if(-1===g)throw Error("Provided address was not an absolute URL.");const h=a.substring(g+3),i=a.substring(0,g);if("http"===i)d="ws";else if("https"===i)d="wss";else throw Error(`Unknown parent protocol ${i}`);const j=`${d}://${h}/api/${M}/sync`;this.state=new $,this.remoteQuerySet=new as(a=>this.state.queryPath(a),this.logger),this.requestManager=new ab(this.logger,this.markConnectionStateDirty);const k=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new aF(this.state,{authenticate:a=>{let b=this.state.setAuth(a);return this.webSocketManager.sendMessage(b),b.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:k,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:e,initialAuthTokenReuse:c.initialAuthTokenReuse??!1}),this.optimisticQueryResults=new ai,this.addOnTransitionHandler(a=>{b(a.queries.map(a=>a.token))}),this._nextRequestId=0,this._sessionId="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{let b=16*Math.random()|0;return("x"===a?b:3&b|8).toString(16)});const{unsavedChangesWarning:l}=c;if("u"<typeof window||void 0===window.addEventListener){if(!0===l)throw Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else!1!==l&&window.addEventListener("beforeunload",a=>{if(this.requestManager.hasIncompleteRequests()){a.preventDefault();let b="Are you sure you want to leave? Your changes may not be saved.";return(a||window.event).returnValue=b,b}});this.webSocketManager=new aA(j,{onOpen:a=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...a,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new as(a=>this.state.queryPath(a),this.logger);let[b,c]=this.state.restart();for(let a of(c&&this.webSocketManager.sendMessage(c),this.webSocketManager.sendMessage(b),this.requestManager.restart()))this.webSocketManager.sendMessage(a)},onResume:()=>{let[a,b]=this.state.resume();for(let c of(b&&this.webSocketManager.sendMessage(b),a&&this.webSocketManager.sendMessage(a),this.requestManager.resume()))this.webSocketManager.sendMessage(c)},onMessage:a=>{switch(!this.firstMessageReceived&&(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),a.type){case"Transition":{this.observedTimestamp(a.endVersion.ts),this.authenticationManager.onTransition(a),this.remoteQuerySet.transition(a),this.state.transition(a);let b=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(b);break}case"MutationResponse":{a.success&&this.observedTimestamp(a.ts);let b=this.requestManager.onResponse(a);null!==b&&this.notifyOnQueryResultChanges(new Map([[b.requestId,b.result]]));break}case"ActionResponse":this.requestManager.onResponse(a);break;case"AuthError":this.authenticationManager.onAuthError(a);break;case"FatalError":{var b,c;let d,e=(b=this.logger,c=a.error,d=`[CONVEX FATAL ERROR] ${c}`,b.error(d),Error(d));throw this.webSocketManager.terminate(),e}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:c.onServerDisconnectError},f,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),c.expectAuth&&k()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(a){(void 0===this.maxObservedTimestamp||this.maxObservedTimestamp.lessThanOrEqual(a))&&(this.maxObservedTimestamp=a)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(a){let b=this.remoteQuerySet.remoteQueryResults(),c=new Map;for(let[a,d]of b){let b=this.state.queryToken(a);if(null!==b){let e={result:d,udfPath:this.state.queryPath(a),args:this.state.queryArgs(a)};c.set(b,e)}}let d=this.optimisticQueryResults.ingestQueryResultsFromServer(c,new Set(a.keys()));this.handleTransition({queries:d.map(a=>{let b=this.optimisticQueryResults.rawQueryResult(a);return{token:a,modification:{kind:"Updated",result:b}}}),reflectedMutations:Array.from(a).map(([a,b])=>({requestId:a,result:b})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(a){for(let b of this._onTransitionFns.values())b(a)}addOnTransitionHandler(a){let b=this._transitionHandlerCounter++;return this._onTransitionFns.set(b,a),()=>this._onTransitionFns.delete(b)}getCurrentAuthClaims(){let a=this.state.getAuth(),b={};if(a&&"User"===a.tokenType){try{b=a?aC(a.value):{}}catch{b={}}return{token:a.value,decoded:b}}}setAuth(a,b,c){this.authenticationManager.setConfig(a,b,c)}hasAuth(){return this.state.hasAuth()}setAdminAuth(a,b){let c=this.state.setAdminAuth(a,b);this.webSocketManager.sendMessage(c)}clearAuth(){let a=this.state.clearAuth();this.webSocketManager.sendMessage(a)}subscribe(a,b,c){let d=p(b),{modification:e,queryToken:f,unsubscribe:g}=this.state.subscribe(a,d,c?.journal,c?.componentPath);return null!==e&&this.webSocketManager.sendMessage(e),{queryToken:f,unsubscribe:()=>{let a=g();a&&this.webSocketManager.sendMessage(a)}}}localQueryResult(a,b){let c=W(a,p(b));return this.optimisticQueryResults.queryResult(c)}localQueryResultByToken(a){return this.optimisticQueryResults.queryResult(a)}hasLocalQueryResultByToken(a){return this.optimisticQueryResults.hasQueryResult(a)}localQueryLogs(a,b){let c=W(a,p(b));return this.optimisticQueryResults.queryLogs(c)}queryJournal(a,b){let c=W(a,p(b));return this.state.queryJournal(c)}connectionState(){let a=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:a.isConnected,hasEverConnected:a.hasEverConnected,connectionCount:a.connectionCount,connectionRetries:a.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(a){let b=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(b,a),()=>{this.connectionStateSubscribers.delete(b)}}async mutation(a,b,c){let d=await this.mutationInternal(a,b,c);if(!d.success){if(void 0!==d.errorData)throw U(d,new K(T("mutation",a,d)));throw Error(T("mutation",a,d))}return d.value}async mutationInternal(a,b,c,d){let{mutationPromise:e}=this.enqueueMutation(a,b,c,d);return e}enqueueMutation(a,b,c,d){let e=p(b);this.tryReportLongDisconnect();let f=this.nextRequestId;if(this._nextRequestId++,void 0!==c){let a=c.optimisticUpdate;if(void 0!==a){let b=b=>{a(b,e)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},c=this.optimisticQueryResults.applyOptimisticUpdate(b,f).map(a=>{let b=this.localQueryResultByToken(a);return{token:a,modification:{kind:"Updated",result:void 0===b?void 0:{success:!0,value:b,logLines:[]}}}});this.handleTransition({queries:c,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let g={type:"Mutation",requestId:f,udfPath:a,componentPath:d,args:[G(e)]},h=this.webSocketManager.sendMessage(g);return{requestId:f,mutationPromise:this.requestManager.request(g,h)}}async action(a,b){let c=await this.actionInternal(a,b);if(!c.success){if(void 0!==c.errorData)throw U(c,new K(T("action",a,c)));throw Error(T("action",a,c))}return c.value}async actionInternal(a,b,c){let d=p(b),e=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let f={type:"Action",requestId:e,udfPath:a,componentPath:c,args:[G(d)]},g=this.webSocketManager.sendMessage(f);return this.requestManager.request(f,g)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){let a=function(a){if("u"<typeof performance||!performance.getEntriesByName)return[];let b=[];for(let c of aG){let d=performance.getEntriesByName(c).filter(a=>"mark"===a.entryType).filter(b=>b.detail.sessionId===a);b.push(...d)}return b.map(aH)}(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:a})}}tryReportLongDisconnect(){if(!this.debug)return;let a=this.connectionState().timeOfOldestInflightRequest;null===a||Date.now()-a.getTime()<=6e4||fetch(`${this.address}/api/debug_event`,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${M}`},body:JSON.stringify({event:"LongWebsocketDisconnect"})}).then(a=>{a.ok||this.logger.warn("Analytics request failed with response:",a.body)}).catch(a=>{this.logger.warn("Analytics response failed with error:",a)})}}function aL(a){if("object"!=typeof a||null===a||!Array.isArray(a.page)||"boolean"!=typeof a.isDone||"string"!=typeof a.continueCursor)throw Error(`Not a valid paginated query result: ${a?.toString()}`);return a}var aM=Object.defineProperty,aN=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?aM(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class aO{constructor(a,b){this.client=a,this.onTransition=b,aN(this,"paginatedQuerySet",new Map),aN(this,"lastTransitionTs"),this.lastTransitionTs=al.fromNumber(0),this.client.addOnTransitionHandler(a=>this.onBaseTransition(a))}subscribe(a,b,c){let d=V(a),e=X(d,b,c),f=()=>this.removePaginatedQuerySubscriber(e),g=this.paginatedQuerySet.get(e);return g?g.numSubscribers+=1:(this.paginatedQuerySet.set(e,{token:e,canonicalizedUdfPath:d,args:b,numSubscribers:1,options:{initialNumItems:c.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:c.id}),this.addPageToPaginatedQuery(e,null,c.initialNumItems)),{paginatedQueryToken:e,unsubscribe:f}}localQueryResult(a,b,c){let d=X(V(a),b,c);return this.localQueryResultByToken(d)}localQueryResultByToken(a){let b,c=this.paginatedQuerySet.get(a);if(!c)return;let d=this.activePageQueryTokens(c);if(0===d.length)return{results:[],status:"LoadingFirstPage",loadMore:b=>this.loadMoreOfPaginatedQuery(a,b)};let e=[],f=!1,g=!1;for(let a of d){let b=this.client.localQueryResultByToken(a);if(void 0===b){f=!0,g=!1;continue}let c=aL(b);e=e.concat(c.page),g=!!c.isDone}return b=f?0===e.length?"LoadingFirstPage":"LoadingMore":g?"Exhausted":"CanLoadMore",{results:e,status:b,loadMore:b=>this.loadMoreOfPaginatedQuery(a,b)}}onBaseTransition(a){let b=a.queries.map(a=>a.token),c=this.queriesContainingTokens(b),d=[];c.length>0&&(this.processPaginatedQuerySplits(c,a=>this.client.localQueryResultByToken(a)),d=c.map(a=>({token:a,modification:{kind:"Updated",result:this.localQueryResultByToken(a)}})));let e={...a,paginatedQueries:d};this.onTransition(e)}loadMoreOfPaginatedQuery(a,b){this.mustGetPaginatedQuery(a);let c=this.queryTokenForLastPageOfPaginatedQuery(a),d=this.client.localQueryResultByToken(c);if(!d)return!1;let e=aL(d);if(e.isDone)return!1;this.addPageToPaginatedQuery(a,e.continueCursor,b);let f={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:a,modification:{kind:"Updated",result:this.localQueryResultByToken(a)}}]};return this.onTransition(f),!0}queriesContainingTokens(a){if(0===a.length)return[];let b=[],c=new Set(a);for(let[a,d]of this.paginatedQuerySet)for(let e of this.allQueryTokens(d))if(c.has(e)){b.push(a);break}return b}processPaginatedQuerySplits(a,b){for(let c of a){let a=this.mustGetPaginatedQuery(c),{ongoingSplits:d,pageKeyToQuery:e,pageKeys:f}=a;for(let[c,[f,g]]of d)void 0!==b(e.get(f).queryToken)&&void 0!==b(e.get(g).queryToken)&&this.completePaginatedQuerySplit(a,c,f,g);for(let c of f){if(d.has(c))continue;let f=e.get(c);if(!f)throw Error(`No page query for active pageKey ${c}`);let g=b(f.queryToken);if(!g)continue;let h=aL(g);h.splitCursor&&("SplitRecommended"===h.pageStatus||"SplitRequired"===h.pageStatus||h.page.length>2*a.options.initialNumItems)&&this.splitPaginatedQueryPage(a,c,f.cursor,h.splitCursor,h.continueCursor)}}}splitPaginatedQueryPage(a,b,c,d,e){let f=a.nextPageKey++,g=a.nextPageKey++,h={numItems:a.options.initialNumItems,id:a.id},i=this.client.subscribe(a.canonicalizedUdfPath,{...a.args,paginationOpts:{...h,cursor:c,endCursor:d}});a.pageKeyToQuery.set(f,{...i,cursor:c});let j=this.client.subscribe(a.canonicalizedUdfPath,{...a.args,paginationOpts:{...h,cursor:d,endCursor:e}});a.pageKeyToQuery.set(g,{...j,cursor:d}),a.ongoingSplits.set(b,[f,g])}addPageToPaginatedQuery(a,b,c){let d=this.mustGetPaginatedQuery(a),e=d.nextPageKey++,f={cursor:b,numItems:c,id:d.id},g={...d.args,paginationOpts:f},h=this.client.subscribe(d.canonicalizedUdfPath,g);return d.pageKeys.push(e),d.pageKeyToQuery.set(e,{...h,cursor:b}),h}removePaginatedQuerySubscriber(a){let b=this.paginatedQuerySet.get(a);if(b&&(b.numSubscribers-=1,!(b.numSubscribers>0))){for(let a of b.pageKeyToQuery.values())a.unsubscribe();this.paginatedQuerySet.delete(a)}}completePaginatedQuerySplit(a,b,c,d){let e=a.pageKeyToQuery.get(b);a.pageKeyToQuery.delete(b);let f=a.pageKeys.indexOf(b);a.pageKeys.splice(f,1,c,d),a.ongoingSplits.delete(b),e.unsubscribe()}activePageQueryTokens(a){return a.pageKeys.map(b=>a.pageKeyToQuery.get(b).queryToken)}allQueryTokens(a){return Array.from(a.pageKeyToQuery.values()).map(a=>a.queryToken)}queryTokenForLastPageOfPaginatedQuery(a){let b=this.mustGetPaginatedQuery(a),c=b.pageKeys[b.pageKeys.length-1];if(void 0===c)throw Error(`No pages for paginated query ${a}`);return b.pageKeyToQuery.get(c).queryToken}mustGetPaginatedQuery(a){let b=this.paginatedQuerySet.get(a);if(!b)throw Error("paginated query no longer exists for token "+a);return b}}var aP=Object.defineProperty,aQ=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?aP(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};if(void 0===g)throw Error("Required dependency 'react' not found");class aR{constructor(a,b){if(aQ(this,"address"),aQ(this,"cachedSync"),aQ(this,"cachedPaginatedQueryClient"),aQ(this,"listeners"),aQ(this,"options"),aQ(this,"closed",!1),aQ(this,"_logger"),aQ(this,"adminAuth"),aQ(this,"fakeUserIdentity"),void 0===a)throw Error("No address provided to ConvexReactClient.\nIf trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\nIf running locally, make sure to run `convex dev` and ensure the .env.local file is populated.");if("string"!=typeof a)throw Error(`ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof a} instead.`);if(!a.includes("://"))throw Error("Provided address was not an absolute URL.");this.address=a,this.listeners=new Map,this._logger=b?.logger===!1?function(a){return new Q(a)}({verbose:b?.verbose??!1}):b?.logger!==!0&&b?.logger?b.logger:R({verbose:b?.verbose??!1}),this.options={...b,logger:this._logger}}get url(){return this.address}get sync(){if(this.closed)throw Error("ConvexReactClient has already been closed.");return this.cachedSync||(this.cachedSync=this.options.baseClient??new aK(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new aO(this.cachedSync,a=>this.handleTransition(a))),this.cachedSync}get paginatedQueryClient(){if(this.sync,this.cachedPaginatedQueryClient)return this.cachedPaginatedQueryClient;throw Error("Should already be instantiated")}setAuth(a,b,c){if("string"==typeof a)throw Error("Passing a string to ConvexReactClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication.");this.sync.setAuth(a,b??(()=>{}),c)}clearAuth(){this.sync.clearAuth()}setAdminAuth(a,b){if(this.adminAuth=a,this.fakeUserIdentity=b,this.closed)throw Error("ConvexReactClient has already been closed.");this.cachedSync&&this.sync.setAdminAuth(a,b)}watchQuery(a,...b){let[c,d]=b,e=ae(a);return{onUpdate:a=>{let{queryToken:b,unsubscribe:f}=this.sync.subscribe(e,c,d),g=this.listeners.get(b);return void 0!==g?g.add(a):this.listeners.set(b,new Set([a])),()=>{if(this.closed)return;let c=this.listeners.get(b);c.delete(a),0===c.size&&this.listeners.delete(b),f()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(e,c)},localQueryLogs:()=>{if(this.cachedSync)return this.cachedSync.localQueryLogs(e,c)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(e,c)}}}prewarmQuery(a){let b=a.extendSubscriptionFor??5e3;setTimeout(this.watchQuery(a.query,a.args||{}).onUpdate(()=>{}),b)}watchPaginatedQuery(a,b,c){let d=ae(a);return{onUpdate:a=>{let{paginatedQueryToken:e,unsubscribe:f}=this.paginatedQueryClient.subscribe(d,b||{},c),g=this.listeners.get(e);return void 0!==g?g.add(a):this.listeners.set(e,new Set([a])),()=>{if(this.closed)return;let b=this.listeners.get(e);b.delete(a),0===b.size&&this.listeners.delete(e),f()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(d,b,c)}}mutation(a,...b){let[c,d]=b,e=ae(a);return this.sync.mutation(e,c,d)}action(a,...b){let c=ae(a);return this.sync.action(c,...b)}query(a,...b){let c=this.watchQuery(a,...b),d=c.localQueryResult();return void 0!==d?Promise.resolve(d):new Promise((a,b)=>{let d=c.onUpdate(()=>{d();try{a(c.localQueryResult())}catch(a){b(a)}})})}connectionState(){return this.sync.connectionState()}subscribeToConnectionState(a){return this.sync.subscribeToConnectionState(a)}get logger(){return this._logger}async close(){if(this.closed=!0,this.listeners=new Map,this.cachedPaginatedQueryClient&&(this.cachedPaginatedQueryClient=void 0),this.cachedSync){let a=this.cachedSync;this.cachedSync=void 0,await a.close()}}handleTransition(a){let b=a.queries.map(a=>a.token),c=a.paginatedQueries.map(a=>a.token);this.transition([...b,...c])}transition(a){for(let b of a){let a=this.listeners.get(b);if(a)for(let b of a)b()}}}let aS=g.createContext(void 0),aT=({client:a,children:b})=>g.createElement(aS.Provider,{value:a},b);Symbol("includePageKeys"),Symbol("page"),(0,g.createContext)(void 0)}};
|
|
1
|
+
exports.id=4829,exports.ids=[4829],exports.modules={300:(a,b,c)=>{"use strict";function d(a,b){let c;try{c=a()}catch(a){return}return{getItem:a=>{var d;let e=a=>null===a?null:JSON.parse(a,null==b?void 0:b.reviver),f=null!=(d=c.getItem(a))?d:null;return f instanceof Promise?f.then(e):e(f)},setItem:(a,d)=>c.setItem(a,JSON.stringify(d,null==b?void 0:b.replacer)),removeItem:a=>c.removeItem(a)}}c.d(b,{KU:()=>d,Zr:()=>f});let e=a=>b=>{try{let c=a(b);if(c instanceof Promise)return c;return{then:a=>e(a)(c),catch(a){return this}}}catch(a){return{then(a){return this},catch:b=>e(b)(a)}}},f=(a,b)=>(c,f,g)=>{let h,i={storage:d(()=>window.localStorage),partialize:a=>a,version:0,merge:(a,b)=>({...b,...a}),...b},j=!1,k=0,l=new Set,m=new Set,n=i.storage;if(!n)return a((...a)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),c(...a)},f,g);let o=()=>{let a=i.partialize({...f()});return n.setItem(i.name,{state:a,version:i.version})},p=g.setState;g.setState=(a,b)=>(p(a,b),o());let q=a((...a)=>(c(...a),o()),f,g);g.getInitialState=()=>q;let r=()=>{var a,b;if(!n)return;let d=++k;j=!1,l.forEach(a=>{var b;return a(null!=(b=f())?b:q)});let g=(null==(b=i.onRehydrateStorage)?void 0:b.call(i,null!=(a=f())?a:q))||void 0;return e(n.getItem.bind(n))(i.name).then(a=>{if(a)if("number"!=typeof a.version||a.version===i.version)return[!1,a.state];else{if(i.migrate){let b=i.migrate(a.state,a.version);return b instanceof Promise?b.then(a=>[!0,a]):[!0,b]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}return[!1,void 0]}).then(a=>{var b;if(d!==k)return;let[e,g]=a;if(c(h=i.merge(g,null!=(b=f())?b:q),!0),e)return o()}).then(()=>{d===k&&(null==g||g(f(),void 0),h=f(),j=!0,m.forEach(a=>a(h)))}).catch(a=>{d===k&&(null==g||g(void 0,a))})};return g.persist={setOptions:a=>{i={...i,...a},a.storage&&(n=a.storage)},clearStorage:()=>{++k,null==n||n.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>r(),hasHydrated:()=>j,onHydrate:a=>(l.add(a),()=>{l.delete(a)}),onFinishHydration:a=>(m.add(a),()=>{m.delete(a)})},i.skipHydration||r(),h||q}},17708:a=>{a.exports={style:{fontFamily:"'Geist Mono', 'Geist Mono Fallback'",fontStyle:"normal"},className:"__className_8c25df",variable:"__variable_8c25df"}},19099:(a,b,c)=>{"use strict";var d=c(54839);c.o(d,"useParams")&&c.d(b,{useParams:function(){return d.useParams}}),c.o(d,"usePathname")&&c.d(b,{usePathname:function(){return d.usePathname}}),c.o(d,"useRouter")&&c.d(b,{useRouter:function(){return d.useRouter}})},31417:(a,b,c)=>{"use strict";c.d(b,{v:()=>g});var d=c(67484);let e=a=>{let b,c=new Set,d=(a,d)=>{let e="function"==typeof a?a(b):a;if(!Object.is(e,b)){let a=b;b=(null!=d?d:"object"!=typeof e||null===e)?e:Object.assign({},b,e),c.forEach(c=>c(b,a))}},e=()=>b,f={setState:d,getState:e,getInitialState:()=>g,subscribe:a=>(c.add(a),()=>c.delete(a))},g=b=a(d,e,f);return f},f=a=>{let b=a?e(a):e,c=a=>(function(a,b=a=>a){let c=d.useSyncExternalStore(a.subscribe,d.useCallback(()=>b(a.getState()),[a,b]),d.useCallback(()=>b(a.getInitialState()),[a,b]));return d.useDebugValue(c),c})(b,a);return Object.assign(c,b),c},g=a=>a?f(a):f},55091:(a,b,c)=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0}),Object.defineProperty(b,"default",{enumerable:!0,get:function(){return f}});let d=c(5735),e=c(22675);function f(){return(0,d.jsx)(e.HTTPAccessErrorFallback,{status:404,message:"This page could not be found."})}("function"==typeof b.default||"object"==typeof b.default&&null!==b.default)&&void 0===b.default.__esModule&&(Object.defineProperty(b.default,"__esModule",{value:!0}),Object.assign(b.default,b),a.exports=b.default)},55414:(a,b,c)=>{"use strict";let d;c.d(b,{hD:()=>aT,eH:()=>aR});for(var e,f,g=c(67484),h=[],i=[],j=Uint8Array,k="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",l=0,m=k.length;l<m;++l)h[l]=k[l],i[k.charCodeAt(l)]=l;function n(a){var b,c,d=function(a){var b=a.length;if(b%4>0)throw Error("Invalid string. Length must be a multiple of 4");var c=a.indexOf("=");-1===c&&(c=b);var d=c===b?0:4-c%4;return[c,d]}(a),e=d[0],f=d[1],g=new j((e+f)*3/4-f),h=0,k=f>0?e-4:e;for(c=0;c<k;c+=4)b=i[a.charCodeAt(c)]<<18|i[a.charCodeAt(c+1)]<<12|i[a.charCodeAt(c+2)]<<6|i[a.charCodeAt(c+3)],g[h++]=b>>16&255,g[h++]=b>>8&255,g[h++]=255&b;return 2===f&&(b=i[a.charCodeAt(c)]<<2|i[a.charCodeAt(c+1)]>>4,g[h++]=255&b),1===f&&(b=i[a.charCodeAt(c)]<<10|i[a.charCodeAt(c+1)]<<4|i[a.charCodeAt(c+2)]>>2,g[h++]=b>>8&255,g[h++]=255&b),g}function o(a){for(var b,c=a.length,d=c%3,e=[],f=0,g=c-d;f<g;f+=16383)e.push(function(a,b,c){for(var d,e=[],f=b;f<c;f+=3)d=(a[f]<<16&0xff0000)+(a[f+1]<<8&65280)+(255&a[f+2]),e.push(h[d>>18&63]+h[d>>12&63]+h[d>>6&63]+h[63&d]);return e.join("")}(a,f,f+16383>g?g:f+16383));return 1===d?e.push(h[(b=a[c-1])>>2]+h[b<<4&63]+"=="):2===d&&e.push(h[(b=(a[c-2]<<8)+a[c-1])>>10]+h[b>>4&63]+h[b<<2&63]+"="),e.join("")}function p(a){if(void 0===a)return{};if(!q(a))throw Error(`The arguments to a Convex function must be an object. Received: ${a}`);return a}function q(a){let b="object"==typeof a,c=Object.getPrototypeOf(a),d=null===c||c===Object.prototype||c?.constructor?.name==="Object";return b&&d}i[45]=62,i[95]=63;let r=BigInt("-9223372036854775808"),s=BigInt("9223372036854775807"),t=BigInt("0"),u=BigInt("8"),v=BigInt("256"),w="This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.";class x{[Symbol.toPrimitive](a){if("string"===a)return this.toString();throw Error(w)}valueOf(){throw Error(w)}toJSON(){throw Error(w)}toString(){return"[unresolved commit timestamp]"}}let y=new x;function z(a){return Number.isNaN(a)||!Number.isFinite(a)||Object.is(a,-0)}let A=DataView.prototype.setBigInt64?function(a){if(a<r||s<a)throw Error(`BigInt ${a} does not fit into a 64-bit signed integer.`);let b=new ArrayBuffer(8);return new DataView(b).setBigInt64(0,a,!0),o(new Uint8Array(b))}:function(a){a<t&&(a-=r+r);let b=a.toString(16);b.length%2==1&&(b="0"+b);let c=new Uint8Array(new ArrayBuffer(8)),d=0;for(let e of b.match(/.{2}/g).reverse())c.set([parseInt(e,16)],d++),a>>=u;return o(c)},B=DataView.prototype.getBigInt64?function(a){let b=n(a);if(8!==b.byteLength)throw Error(`Received ${b.byteLength} bytes, expected 8 for $integer`);return new DataView(b.buffer).getBigInt64(0,!0)}:function(a){let b=n(a);if(8!==b.byteLength)throw Error(`Received ${b.byteLength} bytes, expected 8 for $integer`);let c=t,d=t;for(let a of b)c+=BigInt(a)*v**d,d++;return c>s&&(c+=r+r),c};function C(a){if(a.length>1024)throw Error(`Field name ${a} exceeds maximum field name length 1024.`);if(a.startsWith("$"))throw Error(`Field name ${a} starts with a '$', which is reserved.`);for(let b=0;b<a.length;b+=1){let c=a.charCodeAt(b);if(c<32||c>=127)throw Error(`Field name ${a} has invalid character '${a[b]}': Field names can only contain non-control ASCII characters`)}}function D(a){if(null===a||"boolean"==typeof a||"number"==typeof a||"string"==typeof a)return a;if(Array.isArray(a))return a.map(a=>D(a));if("object"!=typeof a)throw Error(`Unexpected type of ${a}`);let b=Object.entries(a);if(1===b.length){let c=b[0][0];if("$bytes"===c){if("string"!=typeof a.$bytes)throw Error(`Malformed $bytes field on ${a}`);return n(a.$bytes).buffer}if("$integer"===c){if("string"!=typeof a.$integer)throw Error(`Malformed $integer field on ${a}`);return B(a.$integer)}if("$float"===c){if("string"!=typeof a.$float)throw Error(`Malformed $float field on ${a}`);let b=n(a.$float);if(8!==b.byteLength)throw Error(`Received ${b.byteLength} bytes, expected 8 for $float`);let c=new DataView(b.buffer).getFloat64(0,!0);if(!z(c))throw Error(`Float ${c} should be encoded as a number`);return c}if("$commitTs"===c){if(null!==a.$commitTs)throw Error(`Malformed $commitTs field on ${a}`);return y}if("$set"===c)throw Error("Received a Set which is no longer supported as a Convex type.");if("$map"===c)throw Error("Received a Map which is no longer supported as a Convex type.")}let c={};for(let[b,d]of Object.entries(a))C(b),c[b]=D(d);return c}function E(a){let b=JSON.stringify(a,(a,b)=>void 0===b?"undefined":"bigint"==typeof b?`${b.toString()}n`:b);if(b.length>16384){let a="[...truncated]",c=16384-a.length,d=b.codePointAt(c-1);return void 0!==d&&d>65535&&(c-=1),b.substring(0,c)+a}return b}function F(a,b,c,d){return a?`${b}${E(c)} is not a supported Convex type (present at path ${a} in original object ${E(d)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${b}${E(c)} is not a supported Convex type.`}function G(a){return function a(b,c,d,e){if(void 0===b){let a=d&&` (present at path ${d} in original object ${E(c)})`;throw Error(`undefined is not a valid Convex value${a}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(null===b)return b;if("bigint"==typeof b){if(b<r||s<b)throw Error(`BigInt ${b} does not fit into a 64-bit signed integer.`);return{$integer:A(b)}}if("number"==typeof b)if(!z(b))return b;else{let a=new ArrayBuffer(8);return new DataView(a).setFloat64(0,b,!0),{$float:o(new Uint8Array(a))}}if("boolean"==typeof b||"string"==typeof b)return b;if(b instanceof ArrayBuffer)return{$bytes:o(new Uint8Array(b))};if(b instanceof x)return{$commitTs:null};if(Array.isArray(b))return b.map((b,e)=>a(b,c,d+`[${e}]`,!1));if(b instanceof Set)throw Error(F(d,"Set",[...b],c));if(b instanceof Map)throw Error(F(d,"Map",[...b],c));if(!q(b)){let a=b?.constructor?.name;throw Error(F(d,a?`${a} `:"",b,c))}let f={},g=Object.entries(b);for(let[b,h]of(g.sort(([a,b],[c,d])=>a===c?0:a<c?-1:1),g))void 0!==h?(C(b),f[b]=a(h,c,d+`.${b}`,!1)):e&&(C(b),f[b]=function(b,c,d){if(void 0===b)return{$undefined:null};if(void 0===c)throw Error(`Programming error. Current value is ${E(b)} but original value is undefined`);return a(b,c,d,!1)}(h,c,d+`.${b}`));return f}(a,a,"",!1)}var H=Object.defineProperty,I=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?H(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};let J=Symbol.for("ConvexError");class K extends(f=Error,e=J,f){constructor(a){super("string"==typeof a?a:E(a)),I(this,"name","ConvexError"),I(this,"data"),I(this,e,!0),this.data=a}}let L=()=>Array.from({length:4},()=>0);L(),L();let M="1.45.0";var N=Object.defineProperty,O=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?N(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};function P(a){switch(a){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class Q{constructor(a){O(this,"_onLogLineFuncs"),O(this,"_verbose"),this._onLogLineFuncs={},this._verbose=a.verbose}addLogLineListener(a){let b=Math.random().toString(36).substring(2,15);for(let a=0;a<10&&void 0!==this._onLogLineFuncs[b];a++)b=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[b]=a,()=>{delete this._onLogLineFuncs[b]}}logVerbose(...a){if(this._verbose)for(let b of Object.values(this._onLogLineFuncs))b("debug",`${new Date().toISOString()}`,...a)}log(...a){for(let b of Object.values(this._onLogLineFuncs))b("info",...a)}warn(...a){for(let b of Object.values(this._onLogLineFuncs))b("warn",...a)}error(...a){for(let b of Object.values(this._onLogLineFuncs))b("error",...a)}}function R(a){let b=new Q(a);return b.addLogLineListener((a,...b)=>{switch(a){case"debug":console.debug(...b);break;case"info":default:console.log(...b);break;case"warn":console.warn(...b);break;case"error":console.error(...b)}}),b}function S(a,b,c,d,e){let f=P(c);if("object"==typeof e&&(e=`ConvexError ${JSON.stringify(e.errorData,null,2)}`),"info"===b){let b=e.match(/^\[.*?\] /);if(null===b)return void a.error(`[CONVEX ${f}(${d})] Could not parse console.log`);let c=e.slice(1,b[0].length-2),g=e.slice(b[0].length);a.log(`%c[CONVEX ${f}(${d})] [${c}]`,"color:rgb(0, 145, 255)",g)}else a.error(`[CONVEX ${f}(${d})] ${e}`)}function T(a,b,c){let d=P(a);return`[CONVEX ${d}(${b})] ${c.errorMessage}
|
|
2
|
+
Called by client`}function U(a,b){return b.data=a.errorData,b}function V(a){let b,c,d=a.split(":");return 1===d.length?(b=d[0],c="default"):(b=d.slice(0,d.length-1).join(":"),c=d[d.length-1]),b.endsWith(".js")&&(b=b.slice(0,-3)),`${b}:${c}`}function W(a,b){return JSON.stringify({udfPath:V(a),args:G(b)})}function X(a,b,c){let{initialNumItems:d,id:e}=c;return JSON.stringify({type:"paginated",udfPath:V(a),args:G(b),options:G({initialNumItems:d,id:e})})}var Y=Object.defineProperty,Z=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?Y(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class ${constructor(){Z(this,"nextQueryId"),Z(this,"querySetVersion"),Z(this,"querySet"),Z(this,"queryIdToToken"),Z(this,"identityVersion"),Z(this,"auth"),Z(this,"outstandingQueriesOlderThanRestart"),Z(this,"outstandingAuthOlderThanRestart"),Z(this,"paused"),Z(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return 0===this.outstandingQueriesOlderThanRestart.size&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(a,b,c,d){let e=V(a),f=W(e,b),g=this.querySet.get(f);if(void 0!==g)return g.numSubscribers+=1,{queryToken:f,modification:null,unsubscribe:()=>this.removeSubscriber(f)};{let a=this.nextQueryId++;this.querySet.set(f,{id:a,canonicalizedUdfPath:e,args:b,numSubscribers:1,journal:c,componentPath:d}),this.queryIdToToken.set(a,f);let g=this.querySetVersion,h=this.querySetVersion+1,i={type:"Add",queryId:a,udfPath:e,args:[G(b)],journal:c,componentPath:d};return this.paused?this.pendingQuerySetModifications.set(a,i):this.querySetVersion=h,{queryToken:f,modification:{type:"ModifyQuerySet",baseVersion:g,newVersion:h,modifications:[i]},unsubscribe:()=>this.removeSubscriber(f)}}}transition(a){for(let b of a.modifications)switch(b.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(b.queryId);let a=b.journal;if(void 0!==a){let c=this.queryIdToToken.get(b.queryId);void 0!==c&&(this.querySet.get(c).journal=a)}break}case"QueryRemoved":this.outstandingQueriesOlderThanRestart.delete(b.queryId);break;default:throw Error(`Invalid modification ${b.type}`)}}queryId(a,b){let c=W(V(a),b),d=this.querySet.get(c);return void 0!==d?d.id:null}isCurrentOrNewerAuthVersion(a){return a>=this.identityVersion}getAuth(){return this.auth}setAuth(a){this.auth={tokenType:"User",value:a};let b=this.identityVersion;return this.paused||(this.identityVersion=b+1),{type:"Authenticate",baseVersion:b,...this.auth}}setAdminAuth(a,b){let c={tokenType:"Admin",value:a,impersonating:b};this.auth=c;let d=this.identityVersion;return this.paused||(this.identityVersion=d+1),{type:"Authenticate",baseVersion:d,...c}}clearAuth(){this.auth=void 0,this.markAuthCompletion();let a=this.identityVersion;return this.paused||(this.identityVersion=a+1),{type:"Authenticate",tokenType:"None",baseVersion:a}}hasAuth(){return!!this.auth}isNewAuth(a){return this.auth?.value!==a}queryPath(a){let b=this.queryIdToToken.get(a);return b?this.querySet.get(b).canonicalizedUdfPath:null}queryArgs(a){let b=this.queryIdToToken.get(a);return b?this.querySet.get(b).args:null}queryToken(a){return this.queryIdToToken.get(a)??null}queryJournal(a){return this.querySet.get(a)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let a=[];for(let b of this.querySet.values()){let c={type:"Add",queryId:b.id,udfPath:b.canonicalizedUdfPath,args:[G(b.args)],journal:b.journal,componentPath:b.componentPath};a.push(c),this.outstandingQueriesOlderThanRestart.add(b.id)}this.querySetVersion=1;let b={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:a};if(!this.auth)return this.identityVersion=0,[b,void 0];this.outstandingAuthOlderThanRestart=!0;let c={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[b,c]}pause(){this.paused=!0}resume(){let a=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,b=void 0!==this.auth?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[a,b]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(a){let b=this.querySet.get(a);if(b.numSubscribers>1)return b.numSubscribers-=1,null;{this.querySet.delete(a),this.queryIdToToken.delete(b.id),this.outstandingQueriesOlderThanRestart.delete(b.id);let c=this.querySetVersion,d=this.querySetVersion+1,e={type:"Remove",queryId:b.id};return this.paused?this.pendingQuerySetModifications.has(b.id)?this.pendingQuerySetModifications.delete(b.id):this.pendingQuerySetModifications.set(b.id,e):this.querySetVersion=d,{type:"ModifyQuerySet",baseVersion:c,newVersion:d,modifications:[e]}}}}var _=Object.defineProperty,aa=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?_(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class ab{constructor(a,b){this.logger=a,this.markConnectionStateDirty=b,aa(this,"inflightRequests"),aa(this,"requestsOlderThanRestart"),aa(this,"inflightMutationsCount",0),aa(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(a,b){let c=new Promise(c=>{this.inflightRequests.set(a.requestId,{message:a,status:{status:b?"Requested":"NotSent",requestedAt:new Date,onResult:c}}),"Mutation"===a.type?this.inflightMutationsCount++:"Action"===a.type&&this.inflightActionsCount++});return this.markConnectionStateDirty(),c}onResponse(a){let b,c,d=this.inflightRequests.get(a.requestId);if(void 0===d||"Completed"===d.status.status)return null;let e="Mutation"===d.message.type?"mutation":"action",f=d.message.udfPath;for(let b of a.logLines)S(this.logger,"info",e,f,b);let g=d.status;if(a.success)b={success:!0,logLines:a.logLines,value:D(a.result)},c=()=>g.onResult(b);else{let d=a.result,{errorData:h}=a;S(this.logger,"error",e,f,d),b={success:!1,errorMessage:d,errorData:void 0!==h?D(h):void 0,logLines:a.logLines},c=()=>g.onResult(b)}return"ActionResponse"!==a.type&&a.success?(d.status={status:"Completed",result:b,ts:a.ts,onResolve:c},null):(c(),this.inflightRequests.delete(a.requestId),this.requestsOlderThanRestart.delete(a.requestId),"Action"===d.message.type?this.inflightActionsCount--:"Mutation"===d.message.type&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:a.requestId,result:b})}removeCompleted(a){let b=new Map;for(let[c,d]of this.inflightRequests.entries()){let e=d.status;"Completed"===e.status&&e.ts.lessThanOrEqual(a)&&(e.onResolve(),b.set(c,e.result),"Mutation"===d.message.type?this.inflightMutationsCount--:"Action"===d.message.type&&this.inflightActionsCount--,this.inflightRequests.delete(c),this.requestsOlderThanRestart.delete(c))}return b.size>0&&this.markConnectionStateDirty(),b}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let a=[];for(let[b,c]of this.inflightRequests){if("NotSent"===c.status.status){c.status.status="Requested",a.push(c.message);continue}if("Mutation"===c.message.type)a.push(c.message);else if("Action"===c.message.type){if(this.inflightRequests.delete(b),this.requestsOlderThanRestart.delete(b),this.inflightActionsCount--,"Completed"===c.status.status)throw Error("Action should never be in 'Completed' state");c.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),a}resume(){let a=[];for(let[,b]of this.inflightRequests)if("NotSent"===b.status.status){b.status.status="Requested",a.push(b.message);continue}return a}hasIncompleteRequests(){for(let a of this.inflightRequests.values())if("Requested"===a.status.status)return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return 0===this.requestsOlderThanRestart.size}timeOfOldestInflightRequest(){if(0===this.inflightRequests.size)return null;let a=Date.now();for(let b of this.inflightRequests.values())"Completed"!==b.status.status&&b.status.requestedAt.getTime()<a&&(a=b.status.requestedAt.getTime());return new Date(a)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}let ac=Symbol.for("functionName"),ad=Symbol.for("toReferencePath");function ae(a){let b=function(a){let b;if("string"==typeof a)b=a.startsWith("function://")?{functionHandle:a}:{name:a};else if(a[ac])b={name:a[ac]};else{let c=a[ad]??null;if(!c)throw Error(`${a} is not a functionReference`);b={reference:c}}return b}(a);if(void 0===b.name){if(void 0!==b.functionHandle)throw Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${b.functionHandle}`);if(void 0!==b.reference)throw Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${b.reference}`);throw Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(b)}`)}if("string"==typeof a)return a;let c=a[ac];if(!c)throw Error(`${a} is not a functionReference`);return c}!function a(b=[]){return new Proxy({},{get(c,d){if("string"==typeof d)return a([...b,d]);if(d===ac){if(b.length<2){let a=["api",...b].join(".");throw Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${a}\``)}let a=b.slice(0,-1).join("/"),c=b[b.length-1];return"default"===c?a:a+":"+c}return d===Symbol.toStringTag?"FunctionReference":void 0}})}();var af=Object.defineProperty,ag=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?af(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class ah{constructor(a){ag(this,"queryResults"),ag(this,"modifiedQueries"),this.queryResults=a,this.modifiedQueries=[]}getQuery(a,...b){let c=p(b[0]),d=ae(a),e=this.queryResults.get(W(d,c));if(void 0!==e)return ah.queryValue(e.result)}getAllQueries(a){let b=[],c=ae(a);for(let a of this.queryResults.values())a.udfPath===V(c)&&b.push({args:a.args,value:ah.queryValue(a.result)});return b}setQuery(a,b,c){let d=p(b),e=ae(a),f=W(e,d);this.queryResults.set(f,{udfPath:e,args:d,result:void 0===c?void 0:{success:!0,value:c,logLines:[]}}),this.modifiedQueries.push(f)}static queryValue(a){return void 0===a?void 0:a.success?a.value:void 0}}class ai{constructor(){ag(this,"queryResults"),ag(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(a,b){this.optimisticUpdates=this.optimisticUpdates.filter(a=>!b.has(a.mutationId));let c=this.queryResults;this.queryResults=new Map(a);let d=new ah(this.queryResults);for(let a of this.optimisticUpdates)a.update(d);let e=[];for(let[a,b]of this.queryResults){let d=c.get(a);(void 0===d||d.result!==b.result)&&e.push(a)}return e}applyOptimisticUpdate(a,b){this.optimisticUpdates.push({update:a,mutationId:b});let c=new ah(this.queryResults);return a(c),c.modifiedQueries}rawQueryResult(a){let b=this.queryResults.get(a);if(void 0!==b)return b.result}queryResult(a){let b=this.queryResults.get(a);if(void 0===b)return;let c=b.result;if(void 0!==c){if(c.success)return c.value;if(void 0!==c.errorData)throw U(c,new K(T("query",b.udfPath,c)));throw Error(T("query",b.udfPath,c))}}hasQueryResult(a){return void 0!==this.queryResults.get(a)}queryLogs(a){let b=this.queryResults.get(a);return b?.result?.logLines}}var aj=Object.defineProperty,ak=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?aj(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class al{constructor(a,b){ak(this,"low"),ak(this,"high"),ak(this,"__isUnsignedLong__"),this.low=0|a,this.high=0|b,this.__isUnsignedLong__=!0}static isLong(a){return!0===(a&&a.__isUnsignedLong__)}static fromBytesLE(a){return new al(a[0]|a[1]<<8|a[2]<<16|a[3]<<24,a[4]|a[5]<<8|a[6]<<16|a[7]<<24)}toBytesLE(){let a=this.high,b=this.low;return[255&b,b>>>8&255,b>>>16&255,b>>>24,255&a,a>>>8&255,a>>>16&255,a>>>24]}static fromNumber(a){return isNaN(a)||a<0?am:a>=ao?ap:new al(a%an|0,a/an|0)}toString(){return(BigInt(this.high)*BigInt(an)+BigInt(this.low)).toString()}equals(a){return al.isLong(a)||(a=al.fromValue(a)),(this.high>>>31!=1||a.high>>>31!=1)&&this.high===a.high&&this.low===a.low}notEquals(a){return!this.equals(a)}comp(a){return(al.isLong(a)||(a=al.fromValue(a)),this.equals(a))?0:a.high>>>0>this.high>>>0||a.high===this.high&&a.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(a){return 0>=this.comp(a)}static fromValue(a){return"number"==typeof a?al.fromNumber(a):new al(a.low,a.high)}}let am=new al(0,0),an=0x100000000,ao=0xffffffffffffffff,ap=new al(-1,-1);var aq=Object.defineProperty,ar=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?aq(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class as{constructor(a,b){ar(this,"version"),ar(this,"remoteQuerySet"),ar(this,"queryPath"),ar(this,"logger"),this.version={querySet:0,ts:al.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=a,this.logger=b}transition(a){let b=a.startVersion;if(this.version.querySet!==b.querySet||this.version.ts.notEquals(b.ts)||this.version.identity!==b.identity)throw Error(`Invalid start version: ${b.ts.toString()}:${b.querySet}:${b.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(let b of a.modifications)switch(b.type){case"QueryUpdated":{let a=this.queryPath(b.queryId);if(a)for(let c of b.logLines)S(this.logger,"info","query",a,c);let c=D(b.value??null);this.remoteQuerySet.set(b.queryId,{success:!0,value:c,logLines:b.logLines});break}case"QueryFailed":{let a=this.queryPath(b.queryId);if(a)for(let c of b.logLines)S(this.logger,"info","query",a,c);let{errorData:c}=b;this.remoteQuerySet.set(b.queryId,{success:!1,errorMessage:b.errorMessage,errorData:void 0!==c?D(c):void 0,logLines:b.logLines});break}case"QueryRemoved":this.remoteQuerySet.delete(b.queryId);break;default:throw Error(`Invalid modification ${b.type}`)}this.version=a.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}function at(a){let b=n(a);return al.fromBytesLE(Array.from(b))}function au(a){switch(a.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...a};case"MutationResponse":if(a.success)return{...a,ts:at(a.ts)};return{...a};case"Transition":return{...a,startVersion:{...a.startVersion,ts:at(a.startVersion.ts)},endVersion:{...a.endVersion,ts:at(a.endVersion.ts)}}}}var av=Object.defineProperty,aw=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?av(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};function ax(){return(void 0===d&&(d=Date.now()),"u"<typeof performance||!performance.now)?Date.now():Math.round(d+performance.now())}function ay(){return`t=${Math.round((ax()-d)/100)/10}s`}let az={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};class aA{constructor(a,b,c,d,e,f){this.markConnectionStateDirty=e,this.debug=f,aw(this,"socket"),aw(this,"connectionCount"),aw(this,"_hasEverConnected",!1),aw(this,"lastCloseReason"),aw(this,"transitionChunkBuffer",null),aw(this,"defaultInitialBackoff"),aw(this,"maxBackoff"),aw(this,"retries"),aw(this,"serverInactivityThreshold"),aw(this,"reconnectDueToServerInactivityTimeout"),aw(this,"scheduledReconnect",null),aw(this,"networkOnlineHandler",null),aw(this,"pendingNetworkRecoveryInfo",null),aw(this,"uri"),aw(this,"onOpen"),aw(this,"onResume"),aw(this,"onMessage"),aw(this,"webSocketConstructor"),aw(this,"logger"),aw(this,"onServerDisconnectError"),this.webSocketConstructor=c,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=a,this.onOpen=b.onOpen,this.onResume=b.onResume,this.onMessage=b.onMessage,this.onServerDisconnectError=b.onServerDisconnectError,this.logger=d,this.setupNetworkListener(),this.connect()}setSocketState(a){this.socket=a,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}setupNetworkListener(){"u"<typeof window||"function"!=typeof window.addEventListener||null===this.networkOnlineHandler&&(this.networkOnlineHandler=()=>{this._logVerbose("network online event detected"),this.tryReconnectImmediately()},window.addEventListener("online",this.networkOnlineHandler),this._logVerbose("network online event listener registered"))}cleanupNetworkListener(){this.networkOnlineHandler&&"u">typeof window&&"function"==typeof window.removeEventListener&&(window.removeEventListener("online",this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose("network online event listener removed"))}assembleTransition(a){if(a.partNumber<0||a.partNumber>=a.totalParts||0===a.totalParts||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==a.totalParts||this.transitionChunkBuffer.transitionId!==a.transitionId))throw this.transitionChunkBuffer=null,Error("Invalid TransitionChunk");if(null===this.transitionChunkBuffer&&(this.transitionChunkBuffer={chunks:[],totalParts:a.totalParts,transitionId:a.transitionId}),a.partNumber!==this.transitionChunkBuffer.chunks.length){let b=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,Error(`TransitionChunk received out of order: expected part ${b}, got ${a.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(a.chunk),this.transitionChunkBuffer.chunks.length===a.totalParts){let a=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;let b=au(JSON.parse(a));if("Transition"!==b.type)throw Error(`Expected Transition, got ${b.type} after assembling chunks`);return b}return null}connect(){if("terminated"===this.socket.state)return;if("disconnected"!==this.socket.state&&"stopped"!==this.socket.state)throw Error("Didn't start connection from disconnected state: "+this.socket.state);let a=new this.webSocketConstructor(this.uri);this._logVerbose("constructed WebSocket"),this.setSocketState({state:"connecting",ws:a,paused:"no"}),this.resetServerInactivityTimeout(),a.onopen=()=>{if(this.logger.logVerbose("begin ws.onopen"),"connecting"!==this.socket.state)throw Error("onopen called with socket not in connecting state");if(this.setSocketState({state:"ready",ws:a,paused:"yes"===this.socket.paused?"uninitialized":"no"}),this.resetServerInactivityTimeout(),"no"===this.socket.paused&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:ax()})),"InitialConnect"!==this.lastCloseReason&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",ay(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",ay())),this.connectionCount+=1,this.lastCloseReason=null,null!==this.pendingNetworkRecoveryInfo){let{timeSavedMs:a}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:"Event",eventType:"NetworkRecoveryReconnect",event:{timeSavedMs:a}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(a/1e3)}s of waiting`)}},a.onerror=a=>{this.transitionChunkBuffer=null;let b=a.message;b&&this.logger.log(`WebSocket error message: ${b}`)},a.onmessage=a=>{this.resetServerInactivityTimeout();let b=a.data.length,c=au(JSON.parse(a.data));if(this._logVerbose(`received ws message with type ${c.type}`),"Ping"!==c.type){if("TransitionChunk"===c.type){let a=this.assembleTransition(c);if(!a)return;c=a,this._logVerbose(`assembled full ws message of type ${c.type}`)}null!==this.transitionChunkBuffer&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${c.type} while buffering TransitionChunks`)),"Transition"===c.type&&this.reportLargeTransition({messageLength:b,transition:c}),this.onMessage(c).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())}},a.onclose=a=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,null===this.lastCloseReason&&(this.lastCloseReason=a.reason||`closed with code ${a.code}`),1e3!==a.code&&1001!==a.code&&1005!==a.code&&4040!==a.code){let b=`WebSocket closed with code ${a.code}`;a.reason&&(b+=`: ${a.reason}`),this.logger.log(b),this.onServerDisconnectError&&a.reason&&this.onServerDisconnectError(b)}let b=function(a){if(void 0===a)return"Unknown";for(let b of Object.keys(az))if(a.startsWith(b))return b;return"Unknown"}(a.reason);this.scheduleReconnect(b)}}socketState(){return this.socket.state}sendMessage(a){let b={type:a.type,..."Authenticate"===a.type&&"User"===a.tokenType?{value:`...${a.value.slice(-7)}`}:{}};if("ready"===this.socket.state&&"no"===this.socket.paused){let c=JSON.stringify(function(a){switch(a.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...a};case"Connect":if(void 0===a.maxObservedTimestamp)return{...a,maxObservedTimestamp:void 0};return{...a,maxObservedTimestamp:o(new Uint8Array(a.maxObservedTimestamp.toBytesLE()))}}}(a)),d=!1;try{this.socket.ws.send(c),d=!0}catch(a){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${a}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${d?"sent":"failed to send"} message with type ${a.type}: ${JSON.stringify(b)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(b)}`),!1}resetServerInactivityTimeout(){"terminated"!==this.socket.state&&(null!==this.reconnectDueToServerInactivityTimeout&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(a){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};let b=this.nextBackoff(a);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(b)}ms`);let c=ax(),d=setTimeout(()=>{this.scheduledReconnect?.timeout===d&&(this.scheduledReconnect=null,this.connect())},b);this.scheduledReconnect={timeout:d,scheduledAt:c,backoffMs:b}}closeAndReconnect(a){switch(this._logVerbose(`begin closeAndReconnect with reason ${a}`),this.socket.state){case"disconnected":case"terminated":case"stopped":return;case"connecting":case"ready":this.lastCloseReason=a,this.close(),this.scheduleReconnect("client");return;default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{let a=this.socket.ws;return a.onmessage=a=>{this._logVerbose("Ignoring message received after close")},new Promise(b=>{a.onclose=()=>{this._logVerbose("Closed after connecting"),b()},a.onopen=()=>{this._logVerbose("Opened after connecting"),a.close()}})}case"ready":{this._logVerbose("ws.close called");let a=this.socket.ws;a.onmessage=a=>{this._logVerbose("Ignoring message received after close")};let b=new Promise(b=>{a.onclose=()=>{b()}});return a.close(),b}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.cleanupNetworkListener(),this.socket.state){case"terminated":case"stopped":case"disconnected":case"connecting":case"ready":{let a=this.close();return this.setSocketState({state:"terminated"}),a}default:throw this.socket,Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case"terminated":return Promise.resolve();case"connecting":case"stopped":case"disconnected":case"ready":{this.cleanupNetworkListener();let a=this.close();return this.socket={state:"stopped"},a}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case"stopped":break;case"terminated":case"connecting":case"ready":case"disconnected":this.logger.logVerbose("Restart called without stopping first");return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":this.socket={...this.socket,paused:"yes"};return;default:return void this.socket}}tryReconnectImmediately(){if(this._logVerbose("tryReconnectImmediately called"),"disconnected"!==this.socket.state)return void this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);let a=null;if(this.scheduledReconnect){let b=ax()-this.scheduledReconnect.scheduledAt;a=Math.max(0,this.scheduledReconnect.backoffMs-b),this._logVerbose(`would have waited ${Math.round(a)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(b)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose("canceled scheduled reconnect")}this.logger.log("Network recovery detected, reconnecting immediately"),this.pendingNetworkRecoveryInfo=null!==a?{timeSavedMs:a}:null,this.connect()}resume(){switch(this.socket.state){case"connecting":this.socket={...this.socket,paused:"no"};return;case"ready":"uninitialized"===this.socket.paused?(this.socket={...this.socket,paused:"no"},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:ax()})):"yes"===this.socket.paused&&(this.socket={...this.socket,paused:"no"},this.onResume());return;case"terminated":case"stopped":case"disconnected":return;default:this.socket}this.connect()}connectionState(){return{isConnected:"ready"===this.socket.state,hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(a){this.logger.logVerbose(a)}nextBackoff(a){let b=("client"===a?100:"Unknown"===a?this.defaultInitialBackoff:az[a].timeout)*Math.pow(2,this.retries);this.retries+=1;let c=Math.min(b,this.maxBackoff),d=c*(Math.random()-.5);return c+d}reportLargeTransition({transition:a,messageLength:b}){if(void 0===a.clientClockSkew||void 0===a.serverTs)return;let c=ax()-a.clientClockSkew-a.serverTs/1e6,d=`${Math.round(c)}ms`,e=`${Math.round(b/1e4)/100}MB`,f=b/(c/1e3),g=`${Math.round(f/1e4)/100}MB per second`;this._logVerbose(`received ${e} transition in ${d} at ${g}`),b>2e7?this.logger.log(`received query results totaling more that 20MB (${e}) which will take a long time to download on slower connections`):c>2e4&&this.logger.log(`received query results totaling ${e} which took more than 20s to arrive (${d})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:c,messageLength:b}})}}class aB extends Error{}function aC(a,b){let c;if("string"!=typeof a)throw new aB("Invalid token specified: must be a string");b||(b={});let d=+(!0!==b.header),e=a.split(".")[d];if("string"!=typeof e)throw new aB(`Invalid token specified: missing part #${d+1}`);try{c=function(a){let b=a.replace(/-/g,"+").replace(/_/g,"/");switch(b.length%4){case 0:break;case 2:b+="==";break;case 3:b+="=";break;default:throw Error("base64 string is not of the correct length")}try{var c;return c=b,decodeURIComponent(atob(c).replace(/(.)/g,(a,b)=>{let c=b.charCodeAt(0).toString(16).toUpperCase();return c.length<2&&(c="0"+c),"%"+c}))}catch{return atob(b)}}(e)}catch(a){throw new aB(`Invalid token specified: invalid base64 for part #${d+1} (${a.message})`)}try{return JSON.parse(c)}catch(a){throw new aB(`Invalid token specified: invalid json for part #${d+1} (${a.message})`)}}aB.prototype.name="InvalidTokenError";var aD=Object.defineProperty,aE=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?aD(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class aF{constructor(a,b,c){aE(this,"authState",{state:"noAuth"}),aE(this,"configVersion",0),aE(this,"syncState"),aE(this,"authenticate"),aE(this,"stopSocket"),aE(this,"tryRestartSocket"),aE(this,"pauseSocket"),aE(this,"resumeSocket"),aE(this,"clearAuth"),aE(this,"logger"),aE(this,"refreshTokenLeewaySeconds"),aE(this,"initialAuthTokenReuse"),aE(this,"lastRefreshChange"),aE(this,"tokenConfirmationAttempts",0),this.syncState=a,this.authenticate=b.authenticate,this.stopSocket=b.stopSocket,this.tryRestartSocket=b.tryRestartSocket,this.pauseSocket=b.pauseSocket,this.resumeSocket=b.resumeSocket,this.clearAuth=b.clearAuth,this.logger=c.logger,this.refreshTokenLeewaySeconds=c.refreshTokenLeewaySeconds,this.initialAuthTokenReuse=c.initialAuthTokenReuse,this.lastRefreshChange=!1}notifyRefreshChange(a){"noAuth"!==this.authState.state&&"initialRefetch"!==this.authState.state&&this.authState.config.onRefreshChange&&this.lastRefreshChange!==a&&(this.lastRefreshChange=a,this.authState.config.onRefreshChange(a))}async setConfig(a,b,c){this.resetAuthState(),this._logVerbose("pausing WS for auth token fetch"),this.pauseSocket();let d=await this.fetchTokenAndGuardAgainstRace(a,{forceRefreshToken:!1});if(d.isFromOutdatedConfig)return;let e={fetchToken:a,onAuthChange:b,onRefreshChange:c};d.value?(this.setAuthState({state:"waitingForServerConfirmationOfCachedToken",config:e,hasRetried:!1}),this.authenticate(d.value)):(this.setAuthState({state:"initialRefetch",config:e}),await this.refetchToken()),this._logVerbose("resuming WS after auth token fetch"),this.resumeSocket()}onTransition(a){if(this.syncState.isCurrentOrNewerAuthVersion(a.endVersion.identity)&&!(a.endVersion.identity<=a.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),"waitingForServerConfirmationOfCachedToken"===this.authState.state){this._logVerbose("server confirmed auth token is valid");let b=this.syncState.getAuth()?.value;this.initialAuthTokenReuse&&b?this.scheduleTokenRefetch(b,a.clientClockSkew):this.refetchToken(),this.authState.config.onAuthChange(!0);return}"waitingForServerConfirmationOfFreshToken"===this.authState.state&&(this._logVerbose("server confirmed new auth token is valid"),this.notifyRefreshChange(!1),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(a){if(!1===a.authUpdateAttempted&&("waitingForServerConfirmationOfFreshToken"===this.authState.state||"waitingForServerConfirmationOfCachedToken"===this.authState.state))return void this._logVerbose("ignoring non-auth token expired error");let{baseVersion:b}=a;this.syncState.isCurrentOrNewerAuthVersion(b+1)?this.tryToReauthenticate(a):this._logVerbose("ignoring auth error for previous auth attempt")}async tryToReauthenticate(a){if(this._logVerbose(`attempting to reauthenticate: ${a.error}`),"noAuth"===this.authState.state||"waitingForServerConfirmationOfFreshToken"===this.authState.state&&this.tokenConfirmationAttempts>=2){this.logger.error(`Failed to authenticate: "${a.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),"noAuth"!==this.authState.state&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}if("waitingForServerConfirmationOfFreshToken"===this.authState.state&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${2-this.tokenConfirmationAttempts} attempts remaining`)),this.notifyRefreshChange(!0),await this.stopSocket(),"noAuth"===this.authState.state)return;let b=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});b.isFromOutdatedConfig||(b.value&&this.syncState.isNewAuth(b.value)?(this.authenticate(b.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:b.value,hadAuth:"notRefetching"===this.authState.state||"waitingForScheduledRefetch"===this.authState.state})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if("noAuth"===this.authState.state)return;this._logVerbose("refetching auth token");let a=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});a.isFromOutdatedConfig||(a.value?this.syncState.isNewAuth(a.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:a.value,config:this.authState.config}),this.authenticate(a.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(a,b){let c;if("noAuth"===this.authState.state)return;let d=this.decodeToken(a);if(!d)return void this.logger.error("Auth token is not a valid JWT, cannot refetch the token");let{iat:e,exp:f}=d;if(!e||!f)return void this.logger.error("Auth token does not have required fields, cannot refetch the token");let g=f-e;if(g<=2)return void this.logger.error("Auth token does not live long enough, cannot refetch the token");void 0!==b?(c=f-(Date.now()-b)/1e3)<=0&&(c=0):c=g;let h=Math.min(1728e6,(c-this.refreshTokenLeewaySeconds)*1e3);h<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${c}s`),h=0);let i=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},h);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:i,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${h}ms`)}async fetchTokenAndGuardAgainstRace(a,b){let c=++this.configVersion;this._logVerbose(`fetching token with config version ${c}`);let d=await a(b);return this.configVersion!==c?(this._logVerbose(`stale config version, expected ${c}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:d}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(a){a(!1),this.resetAuthState()}resetAuthState(){this.notifyRefreshChange(!1),this.setAuthState({state:"noAuth"})}setAuthState(a){let b="waitingForServerConfirmationOfFreshToken"===a.state?{hadAuth:a.hadAuth,state:a.state,token:`...${a.token.slice(-7)}`}:{state:a.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(b)}`),a.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0}"waitingForScheduledRefetch"===this.authState.state&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=a}decodeToken(a){try{return aC(a)}catch(a){return this._logVerbose(`Error decoding token: ${a instanceof Error?a.message:"Unknown error"}`),null}}_logVerbose(a){this.logger.logVerbose(`${a} [v${this.configVersion}]`)}}let aG=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function aH(a){let b=a.name.slice(6);return{name:b=b.charAt(0).toLowerCase()+b.slice(1),startTime:a.startTime}}var aI=Object.defineProperty,aJ=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?aI(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class aK{constructor(a,b,c){let d;if(aJ(this,"address"),aJ(this,"state"),aJ(this,"requestManager"),aJ(this,"webSocketManager"),aJ(this,"authenticationManager"),aJ(this,"remoteQuerySet"),aJ(this,"optimisticQueryResults"),aJ(this,"_transitionHandlerCounter",0),aJ(this,"_nextRequestId"),aJ(this,"_onTransitionFns",new Map),aJ(this,"_sessionId"),aJ(this,"firstMessageReceived",!1),aJ(this,"debug"),aJ(this,"logger"),aJ(this,"maxObservedTimestamp"),aJ(this,"connectionStateSubscribers",new Map),aJ(this,"nextConnectionStateSubscriberId",0),aJ(this,"_lastPublishedConnectionState"),aJ(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{let a=this.connectionState();if(JSON.stringify(a)!==JSON.stringify(this._lastPublishedConnectionState))for(let b of(this._lastPublishedConnectionState=a,this.connectionStateSubscribers.values()))b(a)})}),aJ(this,"mark",a=>{var b;this.debug&&(b=this.sessionId,"u">typeof performance&&performance.mark&&performance.mark(a,{detail:{sessionId:b}}))}),"object"==typeof a)throw Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");c?.skipConvexDeploymentUrlCheck!==!0&&function(a){if(void 0===a)throw Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if("string"!=typeof a)throw Error(`Invalid deployment address: found ${a}".`);if(!(a.startsWith("http:")||a.startsWith("https:")))throw Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${a}".`);try{new URL(a)}catch{throw Error(`Invalid deployment address: "${a}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(a.endsWith(".convex.site"))throw Error(`Invalid deployment address: "${a}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}(a);const e=(c={...c}).authRefreshTokenLeewaySeconds??10;let f=c.webSocketConstructor;if(!f&&"u"<typeof WebSocket)throw Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");f=f||WebSocket,this.debug=c.reportDebugInfoToConvex??!1,this.address=a,this.logger=!1===c.logger?function(a){return new Q(a)}({verbose:c.verbose??!1}):!0!==c.logger&&c.logger?c.logger:R({verbose:c.verbose??!1});const g=a.search("://");if(-1===g)throw Error("Provided address was not an absolute URL.");const h=a.substring(g+3),i=a.substring(0,g);if("http"===i)d="ws";else if("https"===i)d="wss";else throw Error(`Unknown parent protocol ${i}`);const j=`${d}://${h}/api/${M}/sync`;this.state=new $,this.remoteQuerySet=new as(a=>this.state.queryPath(a),this.logger),this.requestManager=new ab(this.logger,this.markConnectionStateDirty);const k=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new aF(this.state,{authenticate:a=>{let b=this.state.setAuth(a);return this.webSocketManager.sendMessage(b),b.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:k,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:e,initialAuthTokenReuse:c.initialAuthTokenReuse??!1}),this.optimisticQueryResults=new ai,this.addOnTransitionHandler(a=>{b(a.queries.map(a=>a.token))}),this._nextRequestId=0,this._sessionId="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{let b=16*Math.random()|0;return("x"===a?b:3&b|8).toString(16)});const{unsavedChangesWarning:l}=c;if("u"<typeof window||void 0===window.addEventListener){if(!0===l)throw Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else!1!==l&&window.addEventListener("beforeunload",a=>{if(this.requestManager.hasIncompleteRequests()){a.preventDefault();let b="Are you sure you want to leave? Your changes may not be saved.";return(a||window.event).returnValue=b,b}});this.webSocketManager=new aA(j,{onOpen:a=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...a,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new as(a=>this.state.queryPath(a),this.logger);let[b,c]=this.state.restart();for(let a of(c&&this.webSocketManager.sendMessage(c),this.webSocketManager.sendMessage(b),this.requestManager.restart()))this.webSocketManager.sendMessage(a)},onResume:()=>{let[a,b]=this.state.resume();for(let c of(b&&this.webSocketManager.sendMessage(b),a&&this.webSocketManager.sendMessage(a),this.requestManager.resume()))this.webSocketManager.sendMessage(c)},onMessage:a=>{switch(!this.firstMessageReceived&&(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),a.type){case"Transition":{this.observedTimestamp(a.endVersion.ts),this.authenticationManager.onTransition(a),this.remoteQuerySet.transition(a),this.state.transition(a);let b=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(b);break}case"MutationResponse":{a.success&&this.observedTimestamp(a.ts);let b=this.requestManager.onResponse(a);null!==b&&this.notifyOnQueryResultChanges(new Map([[b.requestId,b.result]]));break}case"ActionResponse":this.requestManager.onResponse(a);break;case"AuthError":this.authenticationManager.onAuthError(a);break;case"FatalError":{var b,c;let d,e=(b=this.logger,c=a.error,d=`[CONVEX FATAL ERROR] ${c}`,b.error(d),Error(d));throw this.webSocketManager.terminate(),e}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:c.onServerDisconnectError},f,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),c.expectAuth&&k()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(a){(void 0===this.maxObservedTimestamp||this.maxObservedTimestamp.lessThanOrEqual(a))&&(this.maxObservedTimestamp=a)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(a){let b=this.remoteQuerySet.remoteQueryResults(),c=new Map;for(let[a,d]of b){let b=this.state.queryToken(a);if(null!==b){let e={result:d,udfPath:this.state.queryPath(a),args:this.state.queryArgs(a)};c.set(b,e)}}let d=this.optimisticQueryResults.ingestQueryResultsFromServer(c,new Set(a.keys()));this.handleTransition({queries:d.map(a=>{let b=this.optimisticQueryResults.rawQueryResult(a);return{token:a,modification:{kind:"Updated",result:b}}}),reflectedMutations:Array.from(a).map(([a,b])=>({requestId:a,result:b})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(a){for(let b of this._onTransitionFns.values())b(a)}addOnTransitionHandler(a){let b=this._transitionHandlerCounter++;return this._onTransitionFns.set(b,a),()=>this._onTransitionFns.delete(b)}getCurrentAuthClaims(){let a=this.state.getAuth(),b={};if(a&&"User"===a.tokenType){try{b=a?aC(a.value):{}}catch{b={}}return{token:a.value,decoded:b}}}setAuth(a,b,c){this.authenticationManager.setConfig(a,b,c)}hasAuth(){return this.state.hasAuth()}setAdminAuth(a,b){let c=this.state.setAdminAuth(a,b);this.webSocketManager.sendMessage(c)}clearAuth(){let a=this.state.clearAuth();this.webSocketManager.sendMessage(a)}subscribe(a,b,c){let d=p(b),{modification:e,queryToken:f,unsubscribe:g}=this.state.subscribe(a,d,c?.journal,c?.componentPath);return null!==e&&this.webSocketManager.sendMessage(e),{queryToken:f,unsubscribe:()=>{let a=g();a&&this.webSocketManager.sendMessage(a)}}}localQueryResult(a,b){let c=W(a,p(b));return this.optimisticQueryResults.queryResult(c)}localQueryResultByToken(a){return this.optimisticQueryResults.queryResult(a)}hasLocalQueryResultByToken(a){return this.optimisticQueryResults.hasQueryResult(a)}localQueryLogs(a,b){let c=W(a,p(b));return this.optimisticQueryResults.queryLogs(c)}queryJournal(a,b){let c=W(a,p(b));return this.state.queryJournal(c)}connectionState(){let a=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:a.isConnected,hasEverConnected:a.hasEverConnected,connectionCount:a.connectionCount,connectionRetries:a.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(a){let b=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(b,a),()=>{this.connectionStateSubscribers.delete(b)}}async mutation(a,b,c){let d=await this.mutationInternal(a,b,c);if(!d.success){if(void 0!==d.errorData)throw U(d,new K(T("mutation",a,d)));throw Error(T("mutation",a,d))}return d.value}async mutationInternal(a,b,c,d){let{mutationPromise:e}=this.enqueueMutation(a,b,c,d);return e}enqueueMutation(a,b,c,d){let e=p(b);this.tryReportLongDisconnect();let f=this.nextRequestId;if(this._nextRequestId++,void 0!==c){let a=c.optimisticUpdate;if(void 0!==a){let b=b=>{a(b,e)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},c=this.optimisticQueryResults.applyOptimisticUpdate(b,f).map(a=>{let b=this.localQueryResultByToken(a);return{token:a,modification:{kind:"Updated",result:void 0===b?void 0:{success:!0,value:b,logLines:[]}}}});this.handleTransition({queries:c,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let g={type:"Mutation",requestId:f,udfPath:a,componentPath:d,args:[G(e)]},h=this.webSocketManager.sendMessage(g);return{requestId:f,mutationPromise:this.requestManager.request(g,h)}}async action(a,b){let c=await this.actionInternal(a,b);if(!c.success){if(void 0!==c.errorData)throw U(c,new K(T("action",a,c)));throw Error(T("action",a,c))}return c.value}async actionInternal(a,b,c){let d=p(b),e=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let f={type:"Action",requestId:e,udfPath:a,componentPath:c,args:[G(d)]},g=this.webSocketManager.sendMessage(f);return this.requestManager.request(f,g)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){let a=function(a){if("u"<typeof performance||!performance.getEntriesByName)return[];let b=[];for(let c of aG){let d=performance.getEntriesByName(c).filter(a=>"mark"===a.entryType).filter(b=>b.detail.sessionId===a);b.push(...d)}return b.map(aH)}(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:a})}}tryReportLongDisconnect(){if(!this.debug)return;let a=this.connectionState().timeOfOldestInflightRequest;null===a||Date.now()-a.getTime()<=6e4||fetch(`${this.address}/api/debug_event`,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${M}`},body:JSON.stringify({event:"LongWebsocketDisconnect"})}).then(a=>{a.ok||this.logger.warn("Analytics request failed with response:",a.body)}).catch(a=>{this.logger.warn("Analytics response failed with error:",a)})}}function aL(a){if("object"!=typeof a||null===a||!Array.isArray(a.page)||"boolean"!=typeof a.isDone||"string"!=typeof a.continueCursor)throw Error(`Not a valid paginated query result: ${a?.toString()}`);return a}var aM=Object.defineProperty,aN=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?aM(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};class aO{constructor(a,b){this.client=a,this.onTransition=b,aN(this,"paginatedQuerySet",new Map),aN(this,"lastTransitionTs"),this.lastTransitionTs=al.fromNumber(0),this.client.addOnTransitionHandler(a=>this.onBaseTransition(a))}subscribe(a,b,c){let d=V(a),e=X(d,b,c),f=()=>this.removePaginatedQuerySubscriber(e),g=this.paginatedQuerySet.get(e);return g?g.numSubscribers+=1:(this.paginatedQuerySet.set(e,{token:e,canonicalizedUdfPath:d,args:b,numSubscribers:1,options:{initialNumItems:c.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:c.id}),this.addPageToPaginatedQuery(e,null,c.initialNumItems)),{paginatedQueryToken:e,unsubscribe:f}}localQueryResult(a,b,c){let d=X(V(a),b,c);return this.localQueryResultByToken(d)}localQueryResultByToken(a){let b,c=this.paginatedQuerySet.get(a);if(!c)return;let d=this.activePageQueryTokens(c);if(0===d.length)return{results:[],status:"LoadingFirstPage",loadMore:b=>this.loadMoreOfPaginatedQuery(a,b)};let e=[],f=!1,g=!1;for(let a of d){let b=this.client.localQueryResultByToken(a);if(void 0===b){f=!0,g=!1;continue}let c=aL(b);e=e.concat(c.page),g=!!c.isDone}return b=f?0===e.length?"LoadingFirstPage":"LoadingMore":g?"Exhausted":"CanLoadMore",{results:e,status:b,loadMore:b=>this.loadMoreOfPaginatedQuery(a,b)}}onBaseTransition(a){let b=a.queries.map(a=>a.token),c=this.queriesContainingTokens(b),d=[];c.length>0&&(this.processPaginatedQuerySplits(c,a=>this.client.localQueryResultByToken(a)),d=c.map(a=>({token:a,modification:{kind:"Updated",result:this.localQueryResultByToken(a)}})));let e={...a,paginatedQueries:d};this.onTransition(e)}loadMoreOfPaginatedQuery(a,b){this.mustGetPaginatedQuery(a);let c=this.queryTokenForLastPageOfPaginatedQuery(a),d=this.client.localQueryResultByToken(c);if(!d)return!1;let e=aL(d);if(e.isDone)return!1;this.addPageToPaginatedQuery(a,e.continueCursor,b);let f={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:a,modification:{kind:"Updated",result:this.localQueryResultByToken(a)}}]};return this.onTransition(f),!0}queriesContainingTokens(a){if(0===a.length)return[];let b=[],c=new Set(a);for(let[a,d]of this.paginatedQuerySet)for(let e of this.allQueryTokens(d))if(c.has(e)){b.push(a);break}return b}processPaginatedQuerySplits(a,b){for(let c of a){let a=this.mustGetPaginatedQuery(c),{ongoingSplits:d,pageKeyToQuery:e,pageKeys:f}=a;for(let[c,[f,g]]of d)void 0!==b(e.get(f).queryToken)&&void 0!==b(e.get(g).queryToken)&&this.completePaginatedQuerySplit(a,c,f,g);for(let c of f){if(d.has(c))continue;let f=e.get(c);if(!f)throw Error(`No page query for active pageKey ${c}`);let g=b(f.queryToken);if(!g)continue;let h=aL(g);h.splitCursor&&("SplitRecommended"===h.pageStatus||"SplitRequired"===h.pageStatus||h.page.length>2*a.options.initialNumItems)&&this.splitPaginatedQueryPage(a,c,f.cursor,h.splitCursor,h.continueCursor)}}}splitPaginatedQueryPage(a,b,c,d,e){let f=a.nextPageKey++,g=a.nextPageKey++,h={numItems:a.options.initialNumItems,id:a.id},i=this.client.subscribe(a.canonicalizedUdfPath,{...a.args,paginationOpts:{...h,cursor:c,endCursor:d}});a.pageKeyToQuery.set(f,{...i,cursor:c});let j=this.client.subscribe(a.canonicalizedUdfPath,{...a.args,paginationOpts:{...h,cursor:d,endCursor:e}});a.pageKeyToQuery.set(g,{...j,cursor:d}),a.ongoingSplits.set(b,[f,g])}addPageToPaginatedQuery(a,b,c){let d=this.mustGetPaginatedQuery(a),e=d.nextPageKey++,f={cursor:b,numItems:c,id:d.id},g={...d.args,paginationOpts:f},h=this.client.subscribe(d.canonicalizedUdfPath,g);return d.pageKeys.push(e),d.pageKeyToQuery.set(e,{...h,cursor:b}),h}removePaginatedQuerySubscriber(a){let b=this.paginatedQuerySet.get(a);if(b&&(b.numSubscribers-=1,!(b.numSubscribers>0))){for(let a of b.pageKeyToQuery.values())a.unsubscribe();this.paginatedQuerySet.delete(a)}}completePaginatedQuerySplit(a,b,c,d){let e=a.pageKeyToQuery.get(b);a.pageKeyToQuery.delete(b);let f=a.pageKeys.indexOf(b);a.pageKeys.splice(f,1,c,d),a.ongoingSplits.delete(b),e.unsubscribe()}activePageQueryTokens(a){return a.pageKeys.map(b=>a.pageKeyToQuery.get(b).queryToken)}allQueryTokens(a){return Array.from(a.pageKeyToQuery.values()).map(a=>a.queryToken)}queryTokenForLastPageOfPaginatedQuery(a){let b=this.mustGetPaginatedQuery(a),c=b.pageKeys[b.pageKeys.length-1];if(void 0===c)throw Error(`No pages for paginated query ${a}`);return b.pageKeyToQuery.get(c).queryToken}mustGetPaginatedQuery(a){let b=this.paginatedQuerySet.get(a);if(!b)throw Error("paginated query no longer exists for token "+a);return b}}var aP=Object.defineProperty,aQ=(a,b,c)=>{let d;return(d="symbol"!=typeof b?b+"":b)in a?aP(a,d,{enumerable:!0,configurable:!0,writable:!0,value:c}):a[d]=c};if(void 0===g)throw Error("Required dependency 'react' not found");class aR{constructor(a,b){if(aQ(this,"address"),aQ(this,"cachedSync"),aQ(this,"cachedPaginatedQueryClient"),aQ(this,"listeners"),aQ(this,"options"),aQ(this,"closed",!1),aQ(this,"_logger"),aQ(this,"adminAuth"),aQ(this,"fakeUserIdentity"),void 0===a)throw Error("No address provided to ConvexReactClient.\nIf trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\nIf running locally, make sure to run `convex dev` and ensure the .env.local file is populated.");if("string"!=typeof a)throw Error(`ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof a} instead.`);if(!a.includes("://"))throw Error("Provided address was not an absolute URL.");this.address=a,this.listeners=new Map,this._logger=b?.logger===!1?function(a){return new Q(a)}({verbose:b?.verbose??!1}):b?.logger!==!0&&b?.logger?b.logger:R({verbose:b?.verbose??!1}),this.options={...b,logger:this._logger}}get url(){return this.address}get sync(){if(this.closed)throw Error("ConvexReactClient has already been closed.");return this.cachedSync||(this.cachedSync=this.options.baseClient??new aK(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new aO(this.cachedSync,a=>this.handleTransition(a))),this.cachedSync}get paginatedQueryClient(){if(this.sync,this.cachedPaginatedQueryClient)return this.cachedPaginatedQueryClient;throw Error("Should already be instantiated")}setAuth(a,b,c){if("string"==typeof a)throw Error("Passing a string to ConvexReactClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication.");this.sync.setAuth(a,b??(()=>{}),c)}clearAuth(){this.sync.clearAuth()}setAdminAuth(a,b){if(this.adminAuth=a,this.fakeUserIdentity=b,this.closed)throw Error("ConvexReactClient has already been closed.");this.cachedSync&&this.sync.setAdminAuth(a,b)}watchQuery(a,...b){let[c,d]=b,e=ae(a);return{onUpdate:a=>{let{queryToken:b,unsubscribe:f}=this.sync.subscribe(e,c,d),g=this.listeners.get(b);return void 0!==g?g.add(a):this.listeners.set(b,new Set([a])),()=>{if(this.closed)return;let c=this.listeners.get(b);c.delete(a),0===c.size&&this.listeners.delete(b),f()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(e,c)},localQueryLogs:()=>{if(this.cachedSync)return this.cachedSync.localQueryLogs(e,c)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(e,c)}}}prewarmQuery(a){let b=a.extendSubscriptionFor??5e3;setTimeout(this.watchQuery(a.query,a.args||{}).onUpdate(()=>{}),b)}watchPaginatedQuery(a,b,c){let d=ae(a);return{onUpdate:a=>{let{paginatedQueryToken:e,unsubscribe:f}=this.paginatedQueryClient.subscribe(d,b||{},c),g=this.listeners.get(e);return void 0!==g?g.add(a):this.listeners.set(e,new Set([a])),()=>{if(this.closed)return;let b=this.listeners.get(e);b.delete(a),0===b.size&&this.listeners.delete(e),f()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(d,b,c)}}mutation(a,...b){let[c,d]=b,e=ae(a);return this.sync.mutation(e,c,d)}action(a,...b){let c=ae(a);return this.sync.action(c,...b)}query(a,...b){let c=this.watchQuery(a,...b),d=c.localQueryResult();return void 0!==d?Promise.resolve(d):new Promise((a,b)=>{let d=c.onUpdate(()=>{d();try{a(c.localQueryResult())}catch(a){b(a)}})})}connectionState(){return this.sync.connectionState()}subscribeToConnectionState(a){return this.sync.subscribeToConnectionState(a)}get logger(){return this._logger}async close(){if(this.closed=!0,this.listeners=new Map,this.cachedPaginatedQueryClient&&(this.cachedPaginatedQueryClient=void 0),this.cachedSync){let a=this.cachedSync;this.cachedSync=void 0,await a.close()}}handleTransition(a){let b=a.queries.map(a=>a.token),c=a.paginatedQueries.map(a=>a.token);this.transition([...b,...c])}transition(a){for(let b of a){let a=this.listeners.get(b);if(a)for(let b of a)b()}}}let aS=g.createContext(void 0),aT=({client:a,children:b})=>g.createElement(aS.Provider,{value:a},b);Symbol("includePageKeys"),Symbol("page"),(0,g.createContext)(void 0)},69334:a=>{a.exports={style:{fontFamily:"'Geist', 'Geist Fallback'",fontStyle:"normal"},className:"__className_8eaea4",variable:"__variable_8eaea4"}}};
|