@retab/react 0.0.1 → 0.0.3

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/dist/index.mjs CHANGED
@@ -1,24 +1,25 @@
1
- import*as kt from'react';import kt__default,{createContext,useContext,useMemo,useRef,useCallback,useEffect,useState,Component}from'react';import {useQuery,useQueryClient,QueryClient,QueryClientProvider,useMutation}from'@tanstack/react-query';import {toast}from'sonner';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {createSlot,Slot}from'@radix-ui/react-slot';import {cva}from'class-variance-authority';import {clsx}from'clsx';import {twMerge}from'tailwind-merge';import {CalendarIcon,Trash,Plus,Loader2,Search,X,ChevronLeftIcon,ChevronRightIcon,ChevronDownIcon,CheckIcon,Atom,Info,Pencil,AlertCircle,Sparkles,ChevronDown,ChevronRight,EllipsisVertical,Trash2,MessageCircleOff,Download,CloudUpload,Copy,GripVertical,EyeIcon,Type,Hash,ToggleLeft,List,Braces,Brackets,Calendar,Clock,CalendarClock,Link,PlusIcon,Shapes,ChevronUpIcon,Blend,XIcon,ArrowDown,ArrowRight,TriangleAlert,ChevronUp,Mail,CalendarDays,Building2,User,DollarSign,MapPin,ChevronLeft,Box,Table,CheckSquare,Table2,Blocks,Code,Eye,Edit,CircleX,RotateCcw,FileX,Settings2,ArrowUpWideNarrowIcon,Database,ArrowDownWideNarrowIcon,FileSearch,MousePointerClick,SlidersHorizontal,Upload,MoreVertical,ShieldCheck,ShieldUser,RefreshCw,KeyRound,WifiOff,Paperclip,ListFilter,CircleCheck,Tag,CircleIcon,FileText,FileSpreadsheet,FileJson,ChevronsLeft,FileIcon,Play,UploadCloud,ImageIcon}from'lucide-react';import {set,isUndefined,isEqual,debounce,noop}from'lodash';import {format,isValid,parseISO}from'date-fns';import {create,createStore,useStore}from'zustand';import'decimal.js';import {useForm,Controller,useFormContext,useFormState,FormProvider}from'react-hook-form';import Xl from'lodash/set';import*as _S from'@radix-ui/react-label';import*as tp from'@radix-ui/react-checkbox';import*as Nt from'@radix-ui/react-select';import*as Bo from'@radix-ui/react-accordion';import*as On from'@radix-ui/react-tooltip';import {TooltipArrow}from'@radix-ui/react-tooltip';import {getDefaultClassNames,DayPicker}from'react-day-picker';import*as pa from'@radix-ui/react-popover';import*as zS from'react-dom';import zS__default from'react-dom';import*as bt from'@radix-ui/react-dropdown-menu';import*as Sp from'@radix-ui/react-switch';import {Editor}from'@monaco-editor/react';import {zodResolver}from'@hookform/resolvers/zod';import*as Cr from'@radix-ui/react-alert-dialog';import*as sE from'@radix-ui/react-separator';import {flexRender,useReactTable,getCoreRowModel}from'@tanstack/react-table';import {ajvResolver}from'@hookform/resolvers/ajv';import*as wi from'@radix-ui/react-tabs';import*as lh from'xlsx';import {PrismAsync}from'react-syntax-highlighter';import {oneDark}from'react-syntax-highlighter/dist/esm/styles/prism';import {lookup}from'mime-types';var EO=Object.create;var Fh=Object.defineProperty;var PO=Object.getOwnPropertyDescriptor;var TO=Object.getOwnPropertyNames;var kO=Object.getPrototypeOf,RO=Object.prototype.hasOwnProperty;var sa=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var M=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),OO=(e,t)=>{for(var r in t)Fh(e,r,{get:t[r],enumerable:true});},DO=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of TO(t))!RO.call(e,o)&&o!==r&&Fh(e,o,{get:()=>t[o],enumerable:!(n=PO(t,o))||n.enumerable});return e};var Hc=(e,t,r)=>(r=e!=null?EO(kO(e)):{},DO(!e||!e.__esModule?Fh(r,"default",{value:e,enumerable:true}):r,e));var Gs=M(ut=>{Object.defineProperty(ut,"__esModule",{value:true});ut.regexpCode=ut.getEsmExportName=ut.getProperty=ut.safeStringify=ut.stringify=ut.strConcat=ut.addCodeArg=ut.str=ut._=ut.nil=ut._Code=ut.Name=ut.IDENTIFIER=ut._CodeOrName=void 0;var Wc=class{};ut._CodeOrName=Wc;ut.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var qi=class extends Wc{constructor(t){if(super(),!ut.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t;}toString(){return this.str}emptyStr(){return false}get names(){return {[this.str]:1}}};ut.Name=qi;var Nn=class extends Wc{constructor(t){super(),this._items=typeof t=="string"?[t]:t;}toString(){return this.str}emptyStr(){if(this._items.length>1)return false;let t=this._items[0];return t===""||t==='""'}get str(){var t;return (t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return (t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof qi&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ut._Code=Nn;ut.nil=new Nn("");function lw(e,...t){let r=[e[0]],n=0;for(;n<t.length;)Vh(r,t[n]),r.push(e[++n]);return new Nn(r)}ut._=lw;var qh=new Nn("+");function cw(e,...t){let r=[Kc(e[0])],n=0;for(;n<t.length;)r.push(qh),Vh(r,t[n]),r.push(qh,Kc(e[++n]));return cD(r),new Nn(r)}ut.str=cw;function Vh(e,t){t instanceof Nn?e.push(...t._items):t instanceof qi?e.push(t):e.push(fD(t));}ut.addCodeArg=Vh;function cD(e){let t=1;for(;t<e.length-1;){if(e[t]===qh){let r=uD(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+";}t++;}}function uD(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof qi||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof qi))return `"${e}${t.slice(1)}`}function dD(e,t){return t.emptyStr()?e:e.emptyStr()?t:cw`${e}${t}`}ut.strConcat=dD;function fD(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Kc(Array.isArray(e)?e.join(","):e)}function pD(e){return new Nn(Kc(e))}ut.stringify=pD;function Kc(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ut.safeStringify=Kc;function mD(e){return typeof e=="string"&&ut.IDENTIFIER.test(e)?new Nn(`.${e}`):lw`[${e}]`}ut.getProperty=mD;function hD(e){if(typeof e=="string"&&ut.IDENTIFIER.test(e))return new Nn(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}ut.getEsmExportName=hD;function gD(e){return new Nn(e.toString())}ut.regexpCode=gD;});var Wh=M(en=>{Object.defineProperty(en,"__esModule",{value:true});en.ValueScope=en.ValueScopeName=en.Scope=en.varKinds=en.UsedValueState=void 0;var Yr=Gs(),Hh=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value;}},nf;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed";})(nf||(en.UsedValueState=nf={}));en.varKinds={const:new Yr.Name("const"),let:new Yr.Name("let"),var:new Yr.Name("var")};var of=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r;}toName(t){return t instanceof Yr.Name?t:this.name(t)}name(t){return new Yr.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return `${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};en.Scope=of;var af=class extends Yr.Name{constructor(t,r){super(r),this.prefix=t;}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0, Yr._)`.${new Yr.Name(r)}[${n}]`;}};en.ValueScopeName=af;var yD=(0, Yr._)`\n`,Jh=class extends of{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?yD:Yr.nil};}get(){return this._scope}name(t){return new af(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(t),{prefix:a}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,s=this._values[a];if(s){let u=s.get(i);if(u)return u}else s=this._values[a]=new Map;s.set(i,o);let l=this._scope[a]||(this._scope[a]=[]),c=l.length;return l[c]=r.ref,o.setValue(r,{property:a,itemIndex:c}),o}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return (0, Yr._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(t,r,n={},o){let a=Yr.nil;for(let i in t){let s=t[i];if(!s)continue;let l=n[i]=n[i]||new Map;s.forEach(c=>{if(l.has(c))return;l.set(c,nf.Started);let u=r(c);if(u){let d=this.opts.es5?en.varKinds.var:en.varKinds.const;a=(0, Yr._)`${a}${d} ${c} = ${u};${this.opts._n}`;}else if(u=o?.(c))a=(0, Yr._)`${a}${u}${this.opts._n}`;else throw new Hh(c);l.set(c,nf.Completed);});}return a}};en.ValueScope=Jh;});var Ve=M(Ge=>{Object.defineProperty(Ge,"__esModule",{value:true});Ge.or=Ge.and=Ge.not=Ge.CodeGen=Ge.operators=Ge.varKinds=Ge.ValueScopeName=Ge.ValueScope=Ge.Scope=Ge.Name=Ge.regexpCode=Ge.stringify=Ge.getProperty=Ge.nil=Ge.strConcat=Ge.str=Ge._=void 0;var rt=Gs(),Yn=Wh(),Va=Gs();Object.defineProperty(Ge,"_",{enumerable:true,get:function(){return Va._}});Object.defineProperty(Ge,"str",{enumerable:true,get:function(){return Va.str}});Object.defineProperty(Ge,"strConcat",{enumerable:true,get:function(){return Va.strConcat}});Object.defineProperty(Ge,"nil",{enumerable:true,get:function(){return Va.nil}});Object.defineProperty(Ge,"getProperty",{enumerable:true,get:function(){return Va.getProperty}});Object.defineProperty(Ge,"stringify",{enumerable:true,get:function(){return Va.stringify}});Object.defineProperty(Ge,"regexpCode",{enumerable:true,get:function(){return Va.regexpCode}});Object.defineProperty(Ge,"Name",{enumerable:true,get:function(){return Va.Name}});var uf=Wh();Object.defineProperty(Ge,"Scope",{enumerable:true,get:function(){return uf.Scope}});Object.defineProperty(Ge,"ValueScope",{enumerable:true,get:function(){return uf.ValueScope}});Object.defineProperty(Ge,"ValueScopeName",{enumerable:true,get:function(){return uf.ValueScopeName}});Object.defineProperty(Ge,"varKinds",{enumerable:true,get:function(){return uf.varKinds}});Ge.operators={GT:new rt._Code(">"),GTE:new rt._Code(">="),LT:new rt._Code("<"),LTE:new rt._Code("<="),EQ:new rt._Code("==="),NEQ:new rt._Code("!=="),NOT:new rt._Code("!"),OR:new rt._Code("||"),AND:new rt._Code("&&"),ADD:new rt._Code("+")};var la=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},Kh=class extends la{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n;}render({es5:t,_n:r}){let n=t?Yn.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return `${n} ${this.name}${o};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Xs(this.rhs,t,r)),this}get names(){return this.rhs instanceof rt._CodeOrName?this.rhs.names:{}}},sf=class extends la{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n;}render({_n:t}){return `${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof rt.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Xs(this.rhs,t,r),this}get names(){let t=this.lhs instanceof rt.Name?{}:{...this.lhs.names};return cf(t,this.rhs)}},Gh=class extends sf{constructor(t,r,n,o){super(t,n,o),this.op=r;}render({_n:t}){return `${this.lhs} ${this.op}= ${this.rhs};`+t}},Zh=class extends la{constructor(t){super(),this.label=t,this.names={};}render({_n:t}){return `${this.label}:`+t}},Xh=class extends la{constructor(t){super(),this.label=t,this.names={};}render({_n:t}){return `break${this.label?` ${this.label}`:""};`+t}},Qh=class extends la{constructor(t){super(),this.error=t;}render({_n:t}){return `throw ${this.error};`+t}get names(){return this.error.names}},Yh=class extends la{constructor(t){super(),this.code=t;}render({_n:t}){return `${this.code};`+t}optimizeNodes(){return `${this.code}`?this:void 0}optimizeNames(t,r){return this.code=Xs(this.code,t,r),this}get names(){return this.code instanceof rt._CodeOrName?this.code.names:{}}},Gc=class extends la{constructor(t=[]){super(),this.nodes=t;}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1);}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,o=n.length;for(;o--;){let a=n[o];a.optimizeNames(t,r)||(vD(t,a.names),n.splice(o,1));}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Ji(t,r.names),{})}},ca=class extends Gc{render(t){return "{"+t._n+super.render(t)+"}"+t._n}},eg=class extends Gc{},Zs=class extends ca{};Zs.kind="else";var Vi=class e extends ca{constructor(t,r){super(r),this.condition=t;}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===true)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Zs(n):n;}if(r)return t===false?r instanceof e?r:r.nodes:this.nodes.length?this:new e(uw(t),r instanceof e?[r]:r.nodes);if(!(t===false||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=Xs(this.condition,t,r),this}get names(){let t=super.names;return cf(t,this.condition),this.else&&Ji(t,this.else.names),t}};Vi.kind="if";var Hi=class extends ca{};Hi.kind="for";var tg=class extends Hi{constructor(t){super(),this.iteration=t;}render(t){return `for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=Xs(this.iteration,t,r),this}get names(){return Ji(super.names,this.iteration.names)}},rg=class extends Hi{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o;}render(t){let r=t.es5?Yn.varKinds.var:this.varKind,{name:n,from:o,to:a}=this;return `for(${r} ${n}=${o}; ${n}<${a}; ${n}++)`+super.render(t)}get names(){let t=cf(super.names,this.from);return cf(t,this.to)}},lf=class extends Hi{constructor(t,r,n,o){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=o;}render(t){return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=Xs(this.iterable,t,r),this}get names(){return Ji(super.names,this.iterable.names)}},Zc=class extends ca{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n;}render(t){return `${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};Zc.kind="func";var Xc=class extends Gc{render(t){return "return "+super.render(t)}};Xc.kind="return";var ng=class extends ca{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,o;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(o=this.finally)===null||o===void 0||o.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Ji(t,this.catch.names),this.finally&&Ji(t,this.finally.names),t}},Qc=class extends ca{constructor(t){super(),this.error=t;}render(t){return `catch(${this.error})`+super.render(t)}};Qc.kind="catch";var Yc=class extends ca{render(t){return "finally"+super.render(t)}};Yc.kind="finally";var og=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2
- `:""},this._extScope=t,this._scope=new Yn.Scope({parent:t}),this._nodes=[new eg];}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return (this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,o){let a=this._scope.toName(r);return n!==void 0&&o&&(this._constants[a.str]=n),this._leafNode(new Kh(t,a,n)),a}const(t,r,n){return this._def(Yn.varKinds.const,t,r,n)}let(t,r,n){return this._def(Yn.varKinds.let,t,r,n)}var(t,r,n){return this._def(Yn.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new sf(t,r,n))}add(t,r){return this._leafNode(new Gh(t,Ge.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==rt.nil&&this._leafNode(new Yh(t)),this}object(...t){let r=["{"];for(let[n,o]of t)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0, rt.addCodeArg)(r,o));return r.push("}"),new rt._Code(r)}if(t,r,n){if(this._blockNode(new Vi(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new Vi(t))}else(){return this._elseNode(new Zs)}endIf(){return this._endBlockNode(Vi,Zs)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new tg(t),r)}forRange(t,r,n,o,a=this.opts.es5?Yn.varKinds.var:Yn.varKinds.let){let i=this._scope.toName(t);return this._for(new rg(a,i,r,n),()=>o(i))}forOf(t,r,n,o=Yn.varKinds.const){let a=this._scope.toName(t);if(this.opts.es5){let i=r instanceof rt.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0, rt._)`${i}.length`,s=>{this.var(a,(0, rt._)`${i}[${s}]`),n(a);})}return this._for(new lf("of",o,a,r),()=>n(a))}forIn(t,r,n,o=this.opts.es5?Yn.varKinds.var:Yn.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0, rt._)`Object.keys(${r})`,n);let a=this._scope.toName(t);return this._for(new lf("in",o,a,r),()=>n(a))}endFor(){return this._endBlockNode(Hi)}label(t){return this._leafNode(new Zh(t))}break(t){return this._leafNode(new Xh(t))}return(t){let r=new Xc;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Xc)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new ng;if(this._blockNode(o),this.code(t),r){let a=this.name("e");this._currNode=o.catch=new Qc(a),r(a);}return n&&(this._currNode=o.finally=new Yc,this.code(n)),this._endBlockNode(Qc,Yc)}throw(t){return this._leafNode(new Qh(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=rt.nil,n,o){return this._blockNode(new Zc(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Zc)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants);}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t);}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof Vi))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t;}};Ge.CodeGen=og;function Ji(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function cf(e,t){return t instanceof rt._CodeOrName?Ji(e,t.names):e}function Xs(e,t,r){if(e instanceof rt.Name)return n(e);if(!o(e))return e;return new rt._Code(e._items.reduce((a,i)=>(i instanceof rt.Name&&(i=n(i)),i instanceof rt._Code?a.push(...i._items):a.push(i),a),[]));function n(a){let i=r[a.str];return i===void 0||t[a.str]!==1?a:(delete t[a.str],i)}function o(a){return a instanceof rt._Code&&a._items.some(i=>i instanceof rt.Name&&t[i.str]===1&&r[i.str]!==void 0)}}function vD(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0);}function uw(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0, rt._)`!${ag(e)}`}Ge.not=uw;var bD=dw(Ge.operators.AND);function xD(...e){return e.reduce(bD)}Ge.and=xD;var wD=dw(Ge.operators.OR);function _D(...e){return e.reduce(wD)}Ge.or=_D;function dw(e){return (t,r)=>t===rt.nil?r:r===rt.nil?t:(0, rt._)`${ag(t)} ${e} ${ag(r)}`}function ag(e){return e instanceof rt.Name?e:(0, rt._)`(${e})`}});var dt=M(Ze=>{Object.defineProperty(Ze,"__esModule",{value:true});Ze.checkStrictMode=Ze.getErrorPath=Ze.Type=Ze.useFunc=Ze.setEvaluated=Ze.evaluatedPropsToName=Ze.mergeEvaluated=Ze.eachItem=Ze.unescapeJsonPointer=Ze.escapeJsonPointer=Ze.escapeFragment=Ze.unescapeFragment=Ze.schemaRefOrVal=Ze.schemaHasRulesButRef=Ze.schemaHasRules=Ze.checkUnknownRules=Ze.alwaysValidSchema=Ze.toHash=void 0;var St=Ve(),SD=Gs();function ND(e){let t={};for(let r of e)t[r]=true;return t}Ze.toHash=ND;function CD(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?true:(mw(e,t),!hw(t,e.self.RULES.all))}Ze.alwaysValidSchema=CD;function mw(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let a in t)o[a]||vw(e,`unknown keyword: "${a}"`);}Ze.checkUnknownRules=mw;function hw(e,t){if(typeof e=="boolean")return !e;for(let r in e)if(t[r])return true;return false}Ze.schemaHasRules=hw;function ED(e,t){if(typeof e=="boolean")return !e;for(let r in e)if(r!=="$ref"&&t.all[r])return true;return false}Ze.schemaHasRulesButRef=ED;function PD({topSchemaRef:e,schemaPath:t},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return (0, St._)`${r}`}return (0, St._)`${e}${t}${(0, St.getProperty)(n)}`}Ze.schemaRefOrVal=PD;function TD(e){return gw(decodeURIComponent(e))}Ze.unescapeFragment=TD;function kD(e){return encodeURIComponent(sg(e))}Ze.escapeFragment=kD;function sg(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}Ze.escapeJsonPointer=sg;function gw(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}Ze.unescapeJsonPointer=gw;function RD(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e);}Ze.eachItem=RD;function fw({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return (o,a,i,s)=>{let l=i===void 0?a:i instanceof St.Name?(a instanceof St.Name?e(o,a,i):t(o,a,i),i):a instanceof St.Name?(t(o,i,a),a):r(a,i);return s===St.Name&&!(l instanceof St.Name)?n(o,l):l}}Ze.mergeEvaluated={props:fw({mergeNames:(e,t,r)=>e.if((0, St._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0, St._)`${t} === true`,()=>e.assign(r,true),()=>e.assign(r,(0, St._)`${r} || {}`).code((0, St._)`Object.assign(${r}, ${t})`));}),mergeToName:(e,t,r)=>e.if((0, St._)`${r} !== true`,()=>{t===true?e.assign(r,true):(e.assign(r,(0, St._)`${r} || {}`),lg(e,r,t));}),mergeValues:(e,t)=>e===true?true:{...e,...t},resultToName:yw}),items:fw({mergeNames:(e,t,r)=>e.if((0, St._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0, St._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0, St._)`${r} !== true`,()=>e.assign(r,t===true?true:(0, St._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===true?true:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function yw(e,t){if(t===true)return e.var("props",true);let r=e.var("props",(0, St._)`{}`);return t!==void 0&&lg(e,r,t),r}Ze.evaluatedPropsToName=yw;function lg(e,t,r){Object.keys(r).forEach(n=>e.assign((0, St._)`${t}${(0, St.getProperty)(n)}`,true));}Ze.setEvaluated=lg;var pw={};function OD(e,t){return e.scopeValue("func",{ref:t,code:pw[t.code]||(pw[t.code]=new SD._Code(t.code))})}Ze.useFunc=OD;var ig;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str";})(ig||(Ze.Type=ig={}));function DD(e,t,r){if(e instanceof St.Name){let n=t===ig.Num;return r?n?(0, St._)`"[" + ${e} + "]"`:(0, St._)`"['" + ${e} + "']"`:n?(0, St._)`"/" + ${e}`:(0, St._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0, St.getProperty)(e).toString():"/"+sg(e)}Ze.getErrorPath=DD;function vw(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===true)throw new Error(t);e.self.logger.warn(t);}}Ze.checkStrictMode=vw;});var Do=M(cg=>{Object.defineProperty(cg,"__esModule",{value:true});var Dr=Ve(),AD={data:new Dr.Name("data"),valCxt:new Dr.Name("valCxt"),instancePath:new Dr.Name("instancePath"),parentData:new Dr.Name("parentData"),parentDataProperty:new Dr.Name("parentDataProperty"),rootData:new Dr.Name("rootData"),dynamicAnchors:new Dr.Name("dynamicAnchors"),vErrors:new Dr.Name("vErrors"),errors:new Dr.Name("errors"),this:new Dr.Name("this"),self:new Dr.Name("self"),scope:new Dr.Name("scope"),json:new Dr.Name("json"),jsonPos:new Dr.Name("jsonPos"),jsonLen:new Dr.Name("jsonLen"),jsonPart:new Dr.Name("jsonPart")};cg.default=AD;});var Qs=M(Ar=>{Object.defineProperty(Ar,"__esModule",{value:true});Ar.extendErrors=Ar.resetErrorsCount=Ar.reportExtraError=Ar.reportError=Ar.keyword$DataError=Ar.keywordError=void 0;var lt=Ve(),df=dt(),Ur=Do();Ar.keywordError={message:({keyword:e})=>(0, lt.str)`must pass "${e}" keyword validation`};Ar.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0, lt.str)`"${e}" keyword must be ${t} ($data)`:(0, lt.str)`"${e}" keyword is invalid ($data)`};function $D(e,t=Ar.keywordError,r,n){let{it:o}=e,{gen:a,compositeRule:i,allErrors:s}=o,l=ww(e,t,r);n??(i||s)?bw(a,l):xw(o,(0, lt._)`[${l}]`);}Ar.reportError=$D;function ID(e,t=Ar.keywordError,r){let{it:n}=e,{gen:o,compositeRule:a,allErrors:i}=n,s=ww(e,t,r);bw(o,s),a||i||xw(n,Ur.default.vErrors);}Ar.reportExtraError=ID;function FD(e,t){e.assign(Ur.default.errors,t),e.if((0, lt._)`${Ur.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0, lt._)`${Ur.default.vErrors}.length`,t),()=>e.assign(Ur.default.vErrors,null)));}Ar.resetErrorsCount=FD;function MD({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:a}){if(o===void 0)throw new Error("ajv implementation error");let i=e.name("err");e.forRange("i",o,Ur.default.errors,s=>{e.const(i,(0, lt._)`${Ur.default.vErrors}[${s}]`),e.if((0, lt._)`${i}.instancePath === undefined`,()=>e.assign((0, lt._)`${i}.instancePath`,(0, lt.strConcat)(Ur.default.instancePath,a.errorPath))),e.assign((0, lt._)`${i}.schemaPath`,(0, lt.str)`${a.errSchemaPath}/${t}`),a.opts.verbose&&(e.assign((0, lt._)`${i}.schema`,r),e.assign((0, lt._)`${i}.data`,n));});}Ar.extendErrors=MD;function bw(e,t){let r=e.const("err",t);e.if((0, lt._)`${Ur.default.vErrors} === null`,()=>e.assign(Ur.default.vErrors,(0, lt._)`[${r}]`),(0, lt._)`${Ur.default.vErrors}.push(${r})`),e.code((0, lt._)`${Ur.default.errors}++`);}function xw(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0, lt._)`new ${e.ValidationError}(${t})`):(r.assign((0, lt._)`${n}.errors`,t),r.return(false));}var Wi={keyword:new lt.Name("keyword"),schemaPath:new lt.Name("schemaPath"),params:new lt.Name("params"),propertyName:new lt.Name("propertyName"),message:new lt.Name("message"),schema:new lt.Name("schema"),parentSchema:new lt.Name("parentSchema")};function ww(e,t,r){let{createErrors:n}=e.it;return n===false?(0, lt._)`{}`:jD(e,t,r)}function jD(e,t,r={}){let{gen:n,it:o}=e,a=[LD(o,r),BD(e,r)];return zD(e,t,a),n.object(...a)}function LD({errorPath:e},{instancePath:t}){let r=t?(0, lt.str)`${e}${(0, df.getErrorPath)(t,df.Type.Str)}`:e;return [Ur.default.instancePath,(0, lt.strConcat)(Ur.default.instancePath,r)]}function BD({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0, lt.str)`${t}/${e}`;return r&&(o=(0, lt.str)`${o}${(0, df.getErrorPath)(r,df.Type.Str)}`),[Wi.schemaPath,o]}function zD(e,{params:t,message:r},n){let{keyword:o,data:a,schemaValue:i,it:s}=e,{opts:l,propertyName:c,topSchemaRef:u,schemaPath:d}=s;n.push([Wi.keyword,o],[Wi.params,typeof t=="function"?t(e):t||(0, lt._)`{}`]),l.messages&&n.push([Wi.message,typeof r=="function"?r(e):r]),l.verbose&&n.push([Wi.schema,i],[Wi.parentSchema,(0, lt._)`${u}${d}`],[Ur.default.data,a]),c&&n.push([Wi.propertyName,c]);}});var Sw=M(Ys=>{Object.defineProperty(Ys,"__esModule",{value:true});Ys.boolOrEmptySchema=Ys.topBoolOrEmptySchema=void 0;var UD=Qs(),qD=Ve(),VD=Do(),HD={message:"boolean schema is false"};function JD(e){let{gen:t,schema:r,validateName:n}=e;r===false?_w(e,false):typeof r=="object"&&r.$async===true?t.return(VD.default.data):(t.assign((0, qD._)`${n}.errors`,null),t.return(true));}Ys.topBoolOrEmptySchema=JD;function WD(e,t){let{gen:r,schema:n}=e;n===false?(r.var(t,false),_w(e)):r.var(t,true);}Ys.boolOrEmptySchema=WD;function _w(e,t){let{gen:r,data:n}=e,o={gen:r,keyword:"false schema",data:n,schema:false,schemaCode:false,schemaValue:false,params:{},it:e};(0, UD.reportError)(o,HD,void 0,t);}});var ug=M(el=>{Object.defineProperty(el,"__esModule",{value:true});el.getRules=el.isJSONType=void 0;var KD=["string","number","integer","boolean","null","object","array"],GD=new Set(KD);function ZD(e){return typeof e=="string"&&GD.has(e)}el.isJSONType=ZD;function XD(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return {types:{...e,integer:true,boolean:true,null:true},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}el.getRules=XD;});var dg=M(Ha=>{Object.defineProperty(Ha,"__esModule",{value:true});Ha.shouldUseRule=Ha.shouldUseGroup=Ha.schemaHasRulesForType=void 0;function QD({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==true&&Nw(e,n)}Ha.schemaHasRulesForType=QD;function Nw(e,t){return t.rules.some(r=>Cw(e,r))}Ha.shouldUseGroup=Nw;function Cw(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}Ha.shouldUseRule=Cw;});var eu=M($r=>{Object.defineProperty($r,"__esModule",{value:true});$r.reportTypeError=$r.checkDataTypes=$r.checkDataType=$r.coerceAndCheckDataType=$r.getJSONTypes=$r.getSchemaTypes=$r.DataType=void 0;var YD=ug(),eA=dg(),tA=Qs(),He=Ve(),Ew=dt(),tl;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong";})(tl||($r.DataType=tl={}));function rA(e){let t=Pw(e.type);if(t.includes("null")){if(e.nullable===false)throw new Error("type: null contradicts nullable: false")}else {if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===true&&t.push("null");}return t}$r.getSchemaTypes=rA;function Pw(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(YD.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}$r.getJSONTypes=Pw;function nA(e,t){let{gen:r,data:n,opts:o}=e,a=oA(t,o.coerceTypes),i=t.length>0&&!(a.length===0&&t.length===1&&(0, eA.schemaHasRulesForType)(e,t[0]));if(i){let s=pg(t,n,o.strictNumbers,tl.Wrong);r.if(s,()=>{a.length?aA(e,t,a):mg(e);});}return i}$r.coerceAndCheckDataType=nA;var Tw=new Set(["string","number","integer","boolean","null"]);function oA(e,t){return t?e.filter(r=>Tw.has(r)||t==="array"&&r==="array"):[]}function aA(e,t,r){let{gen:n,data:o,opts:a}=e,i=n.let("dataType",(0, He._)`typeof ${o}`),s=n.let("coerced",(0, He._)`undefined`);a.coerceTypes==="array"&&n.if((0, He._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0, He._)`${o}[0]`).assign(i,(0, He._)`typeof ${o}`).if(pg(t,o,a.strictNumbers),()=>n.assign(s,o))),n.if((0, He._)`${s} !== undefined`);for(let c of r)(Tw.has(c)||c==="array"&&a.coerceTypes==="array")&&l(c);n.else(),mg(e),n.endIf(),n.if((0, He._)`${s} !== undefined`,()=>{n.assign(o,s),iA(e,s);});function l(c){switch(c){case "string":n.elseIf((0, He._)`${i} == "number" || ${i} == "boolean"`).assign(s,(0, He._)`"" + ${o}`).elseIf((0, He._)`${o} === null`).assign(s,(0, He._)`""`);return;case "number":n.elseIf((0, He._)`${i} == "boolean" || ${o} === null
3
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(s,(0, He._)`+${o}`);return;case "integer":n.elseIf((0, He._)`${i} === "boolean" || ${o} === null
4
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(s,(0, He._)`+${o}`);return;case "boolean":n.elseIf((0, He._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(s,false).elseIf((0, He._)`${o} === "true" || ${o} === 1`).assign(s,true);return;case "null":n.elseIf((0, He._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(s,null);return;case "array":n.elseIf((0, He._)`${i} === "string" || ${i} === "number"
5
- || ${i} === "boolean" || ${o} === null`).assign(s,(0, He._)`[${o}]`);}}}function iA({gen:e,parentData:t,parentDataProperty:r},n){e.if((0, He._)`${t} !== undefined`,()=>e.assign((0, He._)`${t}[${r}]`,n));}function fg(e,t,r,n=tl.Correct){let o=n===tl.Correct?He.operators.EQ:He.operators.NEQ,a;switch(e){case "null":return (0, He._)`${t} ${o} null`;case "array":a=(0, He._)`Array.isArray(${t})`;break;case "object":a=(0, He._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case "integer":a=i((0, He._)`!(${t} % 1) && !isNaN(${t})`);break;case "number":a=i();break;default:return (0, He._)`typeof ${t} ${o} ${e}`}return n===tl.Correct?a:(0, He.not)(a);function i(s=He.nil){return (0, He.and)((0, He._)`typeof ${t} == "number"`,s,r?(0, He._)`isFinite(${t})`:He.nil)}}$r.checkDataType=fg;function pg(e,t,r,n){if(e.length===1)return fg(e[0],t,r,n);let o,a=(0, Ew.toHash)(e);if(a.array&&a.object){let i=(0, He._)`typeof ${t} != "object"`;o=a.null?i:(0, He._)`!${t} || ${i}`,delete a.null,delete a.array,delete a.object;}else o=He.nil;a.number&&delete a.integer;for(let i in a)o=(0, He.and)(o,fg(i,t,r,n));return o}$r.checkDataTypes=pg;var sA={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0, He._)`{type: ${e}}`:(0, He._)`{type: ${t}}`};function mg(e){let t=lA(e);(0, tA.reportError)(t,sA);}$r.reportTypeError=mg;function lA(e){let{gen:t,data:r,schema:n}=e,o=(0, Ew.schemaRefOrVal)(e,n,"type");return {gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var Rw=M(ff=>{Object.defineProperty(ff,"__esModule",{value:true});ff.assignDefaults=void 0;var rl=Ve(),cA=dt();function uA(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)kw(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,a)=>kw(e,a,o.default));}ff.assignDefaults=uA;function kw(e,t,r){let{gen:n,compositeRule:o,data:a,opts:i}=e;if(r===void 0)return;let s=(0, rl._)`${a}${(0, rl.getProperty)(t)}`;if(o){(0, cA.checkStrictMode)(e,`default is ignored for: ${s}`);return}let l=(0, rl._)`${s} === undefined`;i.useDefaults==="empty"&&(l=(0, rl._)`${l} || ${s} === null || ${s} === ""`),n.if(l,(0, rl._)`${s} = ${(0, rl.stringify)(r)}`);}});var Cn=M(vt=>{Object.defineProperty(vt,"__esModule",{value:true});vt.validateUnion=vt.validateArray=vt.usePattern=vt.callValidateCode=vt.schemaProperties=vt.allSchemaProperties=vt.noPropertyInData=vt.propertyInData=vt.isOwnProperty=vt.hasPropFunc=vt.reportMissingProp=vt.checkMissingProp=vt.checkReportMissingProp=void 0;var Dt=Ve(),hg=dt(),Ja=Do(),dA=dt();function fA(e,t){let{gen:r,data:n,it:o}=e;r.if(yg(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0, Dt._)`${t}`},true),e.error();});}vt.checkReportMissingProp=fA;function pA({gen:e,data:t,it:{opts:r}},n,o){return (0, Dt.or)(...n.map(a=>(0, Dt.and)(yg(e,t,a,r.ownProperties),(0, Dt._)`${o} = ${a}`)))}vt.checkMissingProp=pA;function mA(e,t){e.setParams({missingProperty:t},true),e.error();}vt.reportMissingProp=mA;function Ow(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0, Dt._)`Object.prototype.hasOwnProperty`})}vt.hasPropFunc=Ow;function gg(e,t,r){return (0, Dt._)`${Ow(e)}.call(${t}, ${r})`}vt.isOwnProperty=gg;function hA(e,t,r,n){let o=(0, Dt._)`${t}${(0, Dt.getProperty)(r)} !== undefined`;return n?(0, Dt._)`${o} && ${gg(e,t,r)}`:o}vt.propertyInData=hA;function yg(e,t,r,n){let o=(0, Dt._)`${t}${(0, Dt.getProperty)(r)} === undefined`;return n?(0, Dt.or)(o,(0, Dt.not)(gg(e,t,r))):o}vt.noPropertyInData=yg;function Dw(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}vt.allSchemaProperties=Dw;function gA(e,t){return Dw(t).filter(r=>!(0, hg.alwaysValidSchema)(e,t[r]))}vt.schemaProperties=gA;function yA({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:a},it:i},s,l,c){let u=c?(0, Dt._)`${e}, ${t}, ${n}${o}`:t,d=[[Ja.default.instancePath,(0, Dt.strConcat)(Ja.default.instancePath,a)],[Ja.default.parentData,i.parentData],[Ja.default.parentDataProperty,i.parentDataProperty],[Ja.default.rootData,Ja.default.rootData]];i.opts.dynamicRef&&d.push([Ja.default.dynamicAnchors,Ja.default.dynamicAnchors]);let m=(0, Dt._)`${u}, ${r.object(...d)}`;return l!==Dt.nil?(0, Dt._)`${s}.call(${l}, ${m})`:(0, Dt._)`${s}(${m})`}vt.callValidateCode=yA;var vA=(0, Dt._)`new RegExp`;function bA({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,a=o(r,n);return e.scopeValue("pattern",{key:a.toString(),ref:a,code:(0, Dt._)`${o.code==="new RegExp"?vA:(0, dA.useFunc)(e,o)}(${r}, ${n})`})}vt.usePattern=bA;function xA(e){let{gen:t,data:r,keyword:n,it:o}=e,a=t.name("valid");if(o.allErrors){let s=t.let("valid",true);return i(()=>t.assign(s,false)),s}return t.var(a,true),i(()=>t.break()),a;function i(s){let l=t.const("len",(0, Dt._)`${r}.length`);t.forRange("i",0,l,c=>{e.subschema({keyword:n,dataProp:c,dataPropType:hg.Type.Num},a),t.if((0, Dt.not)(a),s);});}}vt.validateArray=xA;function wA(e){let{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0, hg.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;let i=t.let("valid",false),s=t.name("_valid");t.block(()=>r.forEach((l,c)=>{let u=e.subschema({keyword:n,schemaProp:c,compositeRule:true},s);t.assign(i,(0, Dt._)`${i} || ${s}`),e.mergeValidEvaluated(u,s)||t.if((0, Dt.not)(i));})),e.result(i,()=>e.reset(),()=>e.error(true));}vt.validateUnion=wA;});var Iw=M(Ao=>{Object.defineProperty(Ao,"__esModule",{value:true});Ao.validateKeywordUsage=Ao.validSchemaType=Ao.funcKeywordCode=Ao.macroKeywordCode=void 0;var qr=Ve(),Ki=Do(),_A=Cn(),SA=Qs();function NA(e,t){let{gen:r,keyword:n,schema:o,parentSchema:a,it:i}=e,s=t.macro.call(i.self,o,a,i),l=$w(r,n,s);i.opts.validateSchema!==false&&i.self.validateSchema(s,true);let c=r.name("valid");e.subschema({schema:s,schemaPath:qr.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:true},c),e.pass(c,()=>e.error(true));}Ao.macroKeywordCode=NA;function CA(e,t){var r;let{gen:n,keyword:o,schema:a,parentSchema:i,$data:s,it:l}=e;PA(l,t);let c=!s&&t.compile?t.compile.call(l.self,a,i,l):t.validate,u=$w(n,o,c),d=n.let("valid");e.block$data(d,m),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function m(){if(t.errors===false)p(),t.modifying&&Aw(e),f(()=>e.error());else {let x=t.async?h():y();t.modifying&&Aw(e),f(()=>EA(e,x));}}function h(){let x=n.let("ruleErrs",null);return n.try(()=>p((0, qr._)`await `),g=>n.assign(d,false).if((0, qr._)`${g} instanceof ${l.ValidationError}`,()=>n.assign(x,(0, qr._)`${g}.errors`),()=>n.throw(g))),x}function y(){let x=(0, qr._)`${u}.errors`;return n.assign(x,null),p(qr.nil),x}function p(x=t.async?(0, qr._)`await `:qr.nil){let g=l.opts.passContext?Ki.default.this:Ki.default.self,v=!("compile"in t&&!s||t.schema===false);n.assign(d,(0, qr._)`${x}${(0, _A.callValidateCode)(e,u,g,v)}`,t.modifying);}function f(x){var g;n.if((0, qr.not)((g=t.valid)!==null&&g!==void 0?g:d),x);}}Ao.funcKeywordCode=CA;function Aw(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0, qr._)`${n.parentData}[${n.parentDataProperty}]`));}function EA(e,t){let{gen:r}=e;r.if((0, qr._)`Array.isArray(${t})`,()=>{r.assign(Ki.default.vErrors,(0, qr._)`${Ki.default.vErrors} === null ? ${t} : ${Ki.default.vErrors}.concat(${t})`).assign(Ki.default.errors,(0, qr._)`${Ki.default.vErrors}.length`),(0, SA.extendErrors)(e);},()=>e.error());}function PA({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function $w(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0, qr.stringify)(r)})}function TA(e,t,r=false){return !t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}Ao.validSchemaType=TA;function kA({schema:e,opts:t,self:r,errSchemaPath:n},o,a){if(Array.isArray(o.keyword)?!o.keyword.includes(a):o.keyword!==a)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(s=>!Object.prototype.hasOwnProperty.call(e,s)))throw new Error(`parent schema must have dependencies of ${a}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[a])){let l=`keyword "${a}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Ao.validateKeywordUsage=kA;});var Mw=M(Wa=>{Object.defineProperty(Wa,"__esModule",{value:true});Wa.extendSubschemaMode=Wa.extendSubschemaData=Wa.getSubschema=void 0;var $o=Ve(),Fw=dt();function RA(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:a,topSchemaRef:i}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let s=e.schema[t];return r===void 0?{schema:s,schemaPath:(0, $o._)`${e.schemaPath}${(0, $o.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:s[r],schemaPath:(0, $o._)`${e.schemaPath}${(0, $o.getProperty)(t)}${(0, $o.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0, Fw.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||a===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return {schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:a}}throw new Error('either "keyword" or "schema" must be passed')}Wa.getSubschema=RA;function OA(e,t,{dataProp:r,dataPropType:n,data:o,dataTypes:a,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:s}=t;if(r!==void 0){let{errorPath:c,dataPathArr:u,opts:d}=t,m=s.let("data",(0, $o._)`${t.data}${(0, $o.getProperty)(r)}`,true);l(m),e.errorPath=(0, $o.str)`${c}${(0, Fw.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0, $o._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty];}if(o!==void 0){let c=o instanceof $o.Name?o:s.let("data",o,true);l(c),i!==void 0&&(e.propertyName=i);}a&&(e.dataTypes=a);function l(c){e.data=c,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,c];}}Wa.extendSubschemaData=OA;function DA(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:a}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=r;}Wa.extendSubschemaMode=DA;});var vg=M((TJ,jw)=>{jw.exports=function e(t,r){if(t===r)return true;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return false;var n,o,a;if(Array.isArray(t)){if(n=t.length,n!=r.length)return false;for(o=n;o--!==0;)if(!e(t[o],r[o]))return false;return true}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(a=Object.keys(t),n=a.length,n!==Object.keys(r).length)return false;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,a[o]))return false;for(o=n;o--!==0;){var i=a[o];if(!e(t[i],r[i]))return false}return true}return t!==t&&r!==r};});var Bw=M((kJ,Lw)=>{var Ka=Lw.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};pf(t,n,o,e,"",e);};Ka.keywords={additionalItems:true,items:true,contains:true,additionalProperties:true,propertyNames:true,not:true,if:true,then:true,else:true};Ka.arrayKeywords={items:true,allOf:true,anyOf:true,oneOf:true};Ka.propsKeywords={$defs:true,definitions:true,properties:true,patternProperties:true,dependencies:true};Ka.skipKeywords={default:true,enum:true,const:true,required:true,maximum:true,minimum:true,exclusiveMaximum:true,exclusiveMinimum:true,multipleOf:true,maxLength:true,minLength:true,pattern:true,format:true,maxItems:true,minItems:true,uniqueItems:true,maxProperties:true,minProperties:true};function pf(e,t,r,n,o,a,i,s,l,c){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,a,i,s,l,c);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in Ka.arrayKeywords)for(var m=0;m<d.length;m++)pf(e,t,r,d[m],o+"/"+u+"/"+m,a,o,u,n,m);}else if(u in Ka.propsKeywords){if(d&&typeof d=="object")for(var h in d)pf(e,t,r,d[h],o+"/"+u+"/"+AA(h),a,o,u,n,h);}else (u in Ka.keywords||e.allKeys&&!(u in Ka.skipKeywords))&&pf(e,t,r,d,o+"/"+u,a,o,u,n);}r(n,o,a,i,s,l,c);}}function AA(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var tu=M(tn=>{Object.defineProperty(tn,"__esModule",{value:true});tn.getSchemaRefs=tn.resolveUrl=tn.normalizeId=tn._getFullPath=tn.getFullPath=tn.inlineRef=void 0;var $A=dt(),IA=vg(),FA=Bw(),MA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function jA(e,t=true){return typeof e=="boolean"?true:t===true?!bg(e):t?zw(e)<=t:false}tn.inlineRef=jA;var LA=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function bg(e){for(let t in e){if(LA.has(t))return true;let r=e[t];if(Array.isArray(r)&&r.some(bg)||typeof r=="object"&&bg(r))return true}return false}function zw(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!MA.has(r)&&(typeof e[r]=="object"&&(0, $A.eachItem)(e[r],n=>t+=zw(n)),t===1/0))return 1/0}return t}function Uw(e,t="",r){r!==false&&(t=nl(t));let n=e.parse(t);return qw(e,n)}tn.getFullPath=Uw;function qw(e,t){return e.serialize(t).split("#")[0]+"#"}tn._getFullPath=qw;var BA=/#\/?$/;function nl(e){return e?e.replace(BA,""):""}tn.normalizeId=nl;function zA(e,t,r){return r=nl(r),e.resolve(t,r)}tn.resolveUrl=zA;var UA=/^[a-z_][-a-z0-9._]*$/i;function qA(e,t){if(typeof e=="boolean")return {};let{schemaId:r,uriResolver:n}=this.opts,o=nl(e[r]||t),a={"":o},i=Uw(n,o,false),s={},l=new Set;return FA(e,{allKeys:true},(d,m,h,y)=>{if(y===void 0)return;let p=i+m,f=a[y];typeof d[r]=="string"&&(f=x.call(this,d[r])),g.call(this,d.$anchor),g.call(this,d.$dynamicAnchor),a[m]=f;function x(v){let w=this.opts.uriResolver.resolve;if(v=nl(f?w(f,v):v),l.has(v))throw u(v);l.add(v);let N=this.refs[v];return typeof N=="string"&&(N=this.refs[N]),typeof N=="object"?c(d,N.schema,v):v!==nl(p)&&(v[0]==="#"?(c(d,s[v],v),s[v]=d):this.refs[v]=p),v}function g(v){if(typeof v=="string"){if(!UA.test(v))throw new Error(`invalid anchor "${v}"`);x.call(this,`#${v}`);}}}),s;function c(d,m,h){if(m!==void 0&&!IA(d,m))throw u(h)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}tn.getSchemaRefs=qA;});var ol=M(Ga=>{Object.defineProperty(Ga,"__esModule",{value:true});Ga.getData=Ga.KeywordCxt=Ga.validateFunctionCode=void 0;var Kw=Sw(),Vw=eu(),wg=dg(),mf=eu(),VA=Rw(),nu=Iw(),xg=Mw(),ve=Ve(),Ae=Do(),HA=tu(),ua=dt(),ru=Qs();function JA(e){if(Xw(e)&&(Qw(e),Zw(e))){GA(e);return}Gw(e,()=>(0, Kw.topBoolOrEmptySchema)(e));}Ga.validateFunctionCode=JA;function Gw({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},a){o.code.es5?e.func(t,(0, ve._)`${Ae.default.data}, ${Ae.default.valCxt}`,n.$async,()=>{e.code((0, ve._)`"use strict"; ${Hw(r,o)}`),KA(e,o),e.code(a);}):e.func(t,(0, ve._)`${Ae.default.data}, ${WA(o)}`,n.$async,()=>e.code(Hw(r,o)).code(a));}function WA(e){return (0, ve._)`{${Ae.default.instancePath}="", ${Ae.default.parentData}, ${Ae.default.parentDataProperty}, ${Ae.default.rootData}=${Ae.default.data}${e.dynamicRef?(0, ve._)`, ${Ae.default.dynamicAnchors}={}`:ve.nil}}={}`}function KA(e,t){e.if(Ae.default.valCxt,()=>{e.var(Ae.default.instancePath,(0, ve._)`${Ae.default.valCxt}.${Ae.default.instancePath}`),e.var(Ae.default.parentData,(0, ve._)`${Ae.default.valCxt}.${Ae.default.parentData}`),e.var(Ae.default.parentDataProperty,(0, ve._)`${Ae.default.valCxt}.${Ae.default.parentDataProperty}`),e.var(Ae.default.rootData,(0, ve._)`${Ae.default.valCxt}.${Ae.default.rootData}`),t.dynamicRef&&e.var(Ae.default.dynamicAnchors,(0, ve._)`${Ae.default.valCxt}.${Ae.default.dynamicAnchors}`);},()=>{e.var(Ae.default.instancePath,(0, ve._)`""`),e.var(Ae.default.parentData,(0, ve._)`undefined`),e.var(Ae.default.parentDataProperty,(0, ve._)`undefined`),e.var(Ae.default.rootData,Ae.default.data),t.dynamicRef&&e.var(Ae.default.dynamicAnchors,(0, ve._)`{}`);});}function GA(e){let{schema:t,opts:r,gen:n}=e;Gw(e,()=>{r.$comment&&t.$comment&&e1(e),e$(e),n.let(Ae.default.vErrors,null),n.let(Ae.default.errors,0),r.unevaluated&&ZA(e),Yw(e),n$(e);});}function ZA(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0, ve._)`${r}.evaluated`),t.if((0, ve._)`${e.evaluated}.dynamicProps`,()=>t.assign((0, ve._)`${e.evaluated}.props`,(0, ve._)`undefined`)),t.if((0, ve._)`${e.evaluated}.dynamicItems`,()=>t.assign((0, ve._)`${e.evaluated}.items`,(0, ve._)`undefined`));}function Hw(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0, ve._)`/*# sourceURL=${r} */`:ve.nil}function XA(e,t){if(Xw(e)&&(Qw(e),Zw(e))){QA(e,t);return}(0, Kw.boolOrEmptySchema)(e,t);}function Zw({schema:e,self:t}){if(typeof e=="boolean")return !e;for(let r in e)if(t.RULES.all[r])return true;return false}function Xw(e){return typeof e.schema!="boolean"}function QA(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&e1(e),t$(e),r$(e);let a=n.const("_errs",Ae.default.errors);Yw(e,a),n.var(t,(0, ve._)`${a} === ${Ae.default.errors}`);}function Qw(e){(0, ua.checkUnknownRules)(e),YA(e);}function Yw(e,t){if(e.opts.jtd)return Jw(e,[],false,t);let r=(0, Vw.getSchemaTypes)(e.schema),n=(0, Vw.coerceAndCheckDataType)(e,r);Jw(e,r,!n,t);}function YA(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0, ua.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`);}function e$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0, ua.checkStrictMode)(e,"default is ignored in the schema root");}function t$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0, HA.resolveUrl)(e.opts.uriResolver,e.baseId,t));}function r$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function e1({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let a=r.$comment;if(o.$comment===true)e.code((0, ve._)`${Ae.default.self}.logger.log(${a})`);else if(typeof o.$comment=="function"){let i=(0, ve.str)`${n}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code((0, ve._)`${Ae.default.self}.opts.$comment(${a}, ${i}, ${s}.schema)`);}}function n$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:a}=e;r.$async?t.if((0, ve._)`${Ae.default.errors} === 0`,()=>t.return(Ae.default.data),()=>t.throw((0, ve._)`new ${o}(${Ae.default.vErrors})`)):(t.assign((0, ve._)`${n}.errors`,Ae.default.vErrors),a.unevaluated&&o$(e),t.return((0, ve._)`${Ae.default.errors} === 0`));}function o$({gen:e,evaluated:t,props:r,items:n}){r instanceof ve.Name&&e.assign((0, ve._)`${t}.props`,r),n instanceof ve.Name&&e.assign((0, ve._)`${t}.items`,n);}function Jw(e,t,r,n){let{gen:o,schema:a,data:i,allErrors:s,opts:l,self:c}=e,{RULES:u}=c;if(a.$ref&&(l.ignoreKeywordsWithRef||!(0, ua.schemaHasRulesButRef)(a,u))){o.block(()=>r1(e,"$ref",u.all.$ref.definition));return}l.jtd||a$(e,t),o.block(()=>{for(let m of u.rules)d(m);d(u.post);});function d(m){(0, wg.shouldUseGroup)(a,m)&&(m.type?(o.if((0, mf.checkDataType)(m.type,i,l.strictNumbers)),Ww(e,m),t.length===1&&t[0]===m.type&&r&&(o.else(),(0, mf.reportTypeError)(e)),o.endIf()):Ww(e,m),s||o.if((0, ve._)`${Ae.default.errors} === ${n||0}`));}}function Ww(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0, VA.assignDefaults)(e,t.type),r.block(()=>{for(let a of t.rules)(0, wg.shouldUseRule)(n,a)&&r1(e,a.keyword,a.definition,t.type);});}function a$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(i$(e,t),e.opts.allowUnionTypes||s$(e,t),l$(e,e.dataTypes));}function i$(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{t1(e.dataTypes,r)||_g(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`);}),u$(e,t);}}function s$(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&_g(e,"use allowUnionTypes to allow union type keyword");}function l$(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0, wg.shouldUseRule)(e.schema,o)){let{type:a}=o.definition;a.length&&!a.some(i=>c$(t,i))&&_g(e,`missing type "${a.join(",")}" for keyword "${n}"`);}}}function c$(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function t1(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function u$(e,t){let r=[];for(let n of e.dataTypes)t1(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r;}function _g(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0, ua.checkStrictMode)(e,t,e.opts.strictTypes);}var hf=class{constructor(t,r,n){if((0, nu.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0, ua.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",n1(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0, nu.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==false)&&(this.errsCount=t.gen.const("_errs",Ae.default.errors));}result(t,r,n){this.failResult((0, ve.not)(t),r,n);}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else();}pass(t,r){this.failResult((0, ve.not)(t),void 0,r);}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(false);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else();}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0, ve._)`${r} !== undefined && (${(0, ve.or)(this.invalid$data(),t)})`);}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n);}_error(t,r){(t?ru.reportExtraError:ru.reportError)(this,this.def.error,r);}$dataError(){(0, ru.reportError)(this,this.def.$dataError||ru.keyword$DataError);}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0, ru.resetErrorsCount)(this.gen,this.errsCount);}ok(t){this.allErrors||this.gen.if(t);}setParams(t,r){r?Object.assign(this.params,t):this.params=t;}block$data(t,r,n=ve.nil){this.gen.block(()=>{this.check$data(t,n),r();});}check$data(t=ve.nil,r=ve.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:a,def:i}=this;n.if((0, ve.or)((0, ve._)`${o} === undefined`,r)),t!==ve.nil&&n.assign(t,true),(a.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==ve.nil&&n.assign(t,false)),n.else();}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:o,it:a}=this;return (0, ve.or)(i(),s());function i(){if(n.length){if(!(r instanceof ve.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return (0, ve._)`${(0, mf.checkDataTypes)(l,r,a.opts.strictNumbers,mf.DataType.Wrong)}`}return ve.nil}function s(){if(o.validateSchema){let l=t.scopeValue("validate$data",{ref:o.validateSchema});return (0, ve._)`!${l}(${r})`}return ve.nil}}subschema(t,r){let n=(0, xg.getSubschema)(this.it,t);(0, xg.extendSubschemaData)(n,this.it,t),(0, xg.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return XA(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==true&&t.props!==void 0&&(n.props=ua.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==true&&t.items!==void 0&&(n.items=ua.mergeEvaluated.items(o,t.items,n.items,r)));}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==true||n.items!==true))return o.if(r,()=>this.mergeEvaluated(t,ve.Name)),true}};Ga.KeywordCxt=hf;function r1(e,t,r,n){let o=new hf(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0, nu.funcKeywordCode)(o,r):"macro"in r?(0, nu.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0, nu.funcKeywordCode)(o,r);}var d$=/^\/(?:[^~]|~0|~1)*$/,f$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function n1(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,a;if(e==="")return Ae.default.rootData;if(e[0]==="/"){if(!d$.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,a=Ae.default.rootData;}else {let c=f$.exec(e);if(!c)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+c[1];if(o=c[2],o==="#"){if(u>=t)throw new Error(l("property/index",u));return n[t-u]}if(u>t)throw new Error(l("data",u));if(a=r[t-u],!o)return a}let i=a,s=o.split("/");for(let c of s)c&&(a=(0, ve._)`${a}${(0, ve.getProperty)((0, ua.unescapeJsonPointer)(c))}`,i=(0, ve._)`${i} && ${a}`);return i;function l(c,u){return `Cannot access ${c} ${u} levels up, current level is ${t}`}}Ga.getData=n1;});var gf=M(Ng=>{Object.defineProperty(Ng,"__esModule",{value:true});var Sg=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=true;}};Ng.default=Sg;});var ou=M(Pg=>{Object.defineProperty(Pg,"__esModule",{value:true});var Cg=tu(),Eg=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0, Cg.resolveUrl)(t,r,n),this.missingSchema=(0, Cg.normalizeId)((0, Cg.getFullPath)(t,this.missingRef));}};Pg.default=Eg;});var vf=M(En=>{Object.defineProperty(En,"__esModule",{value:true});En.resolveSchema=En.getCompilingSchema=En.resolveRef=En.compileSchema=En.SchemaEnv=void 0;var eo=Ve(),p$=gf(),Gi=Do(),to=tu(),o1=dt(),m$=ol(),al=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0, to.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={};}};En.SchemaEnv=al;function kg(e){let t=a1.call(this,e);if(t)return t;let r=(0, to.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:a}=this.opts,i=new eo.CodeGen(this.scope,{es5:n,lines:o,ownProperties:a}),s;e.$async&&(s=i.scopeValue("Error",{ref:p$.default,code:(0, eo._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");e.validateName=l;let c={gen:i,allErrors:this.opts.allErrors,data:Gi.default.data,parentData:Gi.default.parentData,parentDataProperty:Gi.default.parentDataProperty,dataNames:[Gi.default.data],dataPathArr:[eo.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===true?{ref:e.schema,code:(0, eo.stringify)(e.schema)}:{ref:e.schema}),validateName:l,ValidationError:s,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:eo.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0, eo._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,m$.validateFunctionCode)(c),i.optimize(this.opts.code.optimize);let d=i.toString();u=`${i.scopeRefs(Gi.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let h=new Function(`${Gi.default.self}`,`${Gi.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:h}),h.errors=null,h.schema=e.schema,h.schemaEnv=e,e.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:l,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:y,items:p}=c;h.evaluated={props:y instanceof eo.Name?void 0:y,items:p instanceof eo.Name?void 0:p,dynamicProps:y instanceof eo.Name,dynamicItems:p instanceof eo.Name},h.source&&(h.source.evaluated=(0,eo.stringify)(h.evaluated));}return e.validate=h,e}catch(d){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(e);}}En.compileSchema=kg;function h$(e,t,r){var n;r=(0, to.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let a=v$.call(this,e,r);if(a===void 0){let i=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:s}=this.opts;i&&(a=new al({schema:i,schemaId:s,root:e,baseId:t}));}if(a!==void 0)return e.refs[r]=g$.call(this,a)}En.resolveRef=h$;function g$(e){return (0, to.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:kg.call(this,e)}function a1(e){for(let t of this._compilations)if(y$(t,e))return t}En.getCompilingSchema=a1;function y$(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function v$(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||yf.call(this,e,t)}function yf(e,t){let r=this.opts.uriResolver.parse(t),n=(0, to._getFullPath)(this.opts.uriResolver,r),o=(0, to.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Tg.call(this,r,e);let a=(0, to.normalizeId)(n),i=this.refs[a]||this.schemas[a];if(typeof i=="string"){let s=yf.call(this,e,i);return typeof s?.schema!="object"?void 0:Tg.call(this,r,s)}if(typeof i?.schema=="object"){if(i.validate||kg.call(this,i),a===(0, to.normalizeId)(t)){let{schema:s}=i,{schemaId:l}=this.opts,c=s[l];return c&&(o=(0, to.resolveUrl)(this.opts.uriResolver,o,c)),new al({schema:s,schemaId:l,root:e,baseId:o})}return Tg.call(this,r,i)}}En.resolveSchema=yf;var b$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Tg(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let s of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0, o1.unescapeFragment)(s)];if(l===void 0)return;r=l;let c=typeof r=="object"&&r[this.opts.schemaId];!b$.has(s)&&c&&(t=(0, to.resolveUrl)(this.opts.uriResolver,t,c));}let a;if(typeof r!="boolean"&&r.$ref&&!(0, o1.schemaHasRulesButRef)(r,this.RULES)){let s=(0, to.resolveUrl)(this.opts.uriResolver,t,r.$ref);a=yf.call(this,n,s);}let{schemaId:i}=this.opts;if(a=a||new al({schema:r,schemaId:i,root:n,baseId:t}),a.schema!==a.root.schema)return a}});var i1=M((IJ,x$)=>{x$.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:false};});var Og=M((FJ,u1)=>{var w$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),l1=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Rg(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return "";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return "";t+=e[n];}return t}var _$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function s1(e){return e.length=0,true}function S$(e,t,r){if(e.length){let n=Rg(e);if(n!=="")t.push(n);else return r.error=true,false;e.length=0;}return true}function N$(e){let t=0,r={error:false,address:"",zone:""},n=[],o=[],a=false,i=false,s=S$;for(let l=0;l<e.length;l++){let c=e[l];if(!(c==="["||c==="]"))if(c===":"){if(a===true&&(i=true),!s(o,n,r))break;if(++t>7){r.error=true;break}l>0&&e[l-1]===":"&&(a=true),n.push(":");continue}else if(c==="%"){if(!s(o,n,r))break;s=s1;}else {o.push(c);continue}}return o.length&&(s===s1?r.zone=o.join(""):i?n.push(o.join("")):n.push(Rg(o))),r.address=n.join(""),r}function c1(e){if(C$(e,":")<2)return {host:e,isIPV6:false};let t=N$(e);if(t.error)return {host:e,isIPV6:false};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,isIPV6:true,escapedHost:n}}}function C$(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function E$(e){let t=e,r=[],n=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){r.push("/");break}else {r.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(o===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n);}return r.join("")}function P$(e,t){let r=t!==true?escape:unescape;return e.scheme!==void 0&&(e.scheme=r(e.scheme)),e.userinfo!==void 0&&(e.userinfo=r(e.userinfo)),e.host!==void 0&&(e.host=r(e.host)),e.path!==void 0&&(e.path=r(e.path)),e.query!==void 0&&(e.query=r(e.query)),e.fragment!==void 0&&(e.fragment=r(e.fragment)),e}function T$(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!l1(r)){let n=c1(r);n.isIPV6===true?r=`[${n.escapedHost}]`:r=e.host;}t.push(r);}return (typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}u1.exports={nonSimpleDomain:_$,recomposeAuthority:T$,normalizeComponentEncoding:P$,removeDotSegments:E$,isIPv4:l1,isUUID:w$,normalizeIPv6:c1,stringArrayToHexStripped:Rg};});var h1=M((MJ,m1)=>{var{isUUID:k$}=Og(),R$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,O$=["http","https","ws","wss","urn","urn:uuid"];function D$(e){return O$.indexOf(e)!==-1}function Dg(e){return e.secure===true?true:e.secure===false?false:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):false}function d1(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function f1(e){let t=String(e.scheme).toLowerCase()==="https";return (e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function A$(e){return e.secure=Dg(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function $$(e){if((e.port===(Dg(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0;}return e.fragment=void 0,e}function I$(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(R$);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let o=`${n}:${t.nid||e.nid}`,a=Ag(o);e.path=void 0,a&&(e=a.parse(e,t));}else e.error=e.error||"URN can not be parsed.";return e}function F$(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),o=`${r}:${t.nid||n}`,a=Ag(o);a&&(e=a.serialize(e,t));let i=e,s=e.nss;return i.path=`${n||t.nid}:${s}`,t.skipEscape=true,i}function M$(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!k$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function j$(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var p1={scheme:"http",domainHost:true,parse:d1,serialize:f1},L$={scheme:"https",domainHost:p1.domainHost,parse:d1,serialize:f1},bf={scheme:"ws",domainHost:true,parse:A$,serialize:$$},B$={scheme:"wss",domainHost:bf.domainHost,parse:bf.parse,serialize:bf.serialize},z$={scheme:"urn",parse:I$,serialize:F$,skipNormalize:true},U$={scheme:"urn:uuid",parse:M$,serialize:j$,skipNormalize:true},xf={http:p1,https:L$,ws:bf,wss:B$,urn:z$,"urn:uuid":U$};Object.setPrototypeOf(xf,null);function Ag(e){return e&&(xf[e]||xf[e.toLowerCase()])||void 0}m1.exports={wsIsSecure:Dg,SCHEMES:xf,isValidSchemeName:D$,getSchemeHandler:Ag};});var v1=M((jJ,_f)=>{var{normalizeIPv6:q$,removeDotSegments:au,recomposeAuthority:V$,normalizeComponentEncoding:wf,isIPv4:H$,nonSimpleDomain:J$}=Og(),{SCHEMES:W$,getSchemeHandler:g1}=h1();function K$(e,t){return typeof e=="string"?e=Io(da(e,t),t):typeof e=="object"&&(e=da(Io(e,t),t)),e}function G$(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=y1(da(e,n),da(t,n),n,true);return n.skipEscape=true,Io(o,n)}function y1(e,t,r,n){let o={};return n||(e=da(Io(e,r),r),t=da(Io(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=au(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=au(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=au(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=au(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function Z$(e,t,r){return typeof e=="string"?(e=unescape(e),e=Io(wf(da(e,r),true),{...r,skipEscape:true})):typeof e=="object"&&(e=Io(wf(e,true),{...r,skipEscape:true})),typeof t=="string"?(t=unescape(t),t=Io(wf(da(t,r),true),{...r,skipEscape:true})):typeof t=="object"&&(t=Io(wf(t,true),{...r,skipEscape:true})),e.toLowerCase()===t.toLowerCase()}function Io(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),o=[],a=g1(n.scheme||r.scheme);a&&a.serialize&&a.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=V$(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let s=r.path;!n.absolutePath&&(!a||!a.absolutePath)&&(s=au(s)),i===void 0&&s[0]==="/"&&s[1]==="/"&&(s="/%2F"+s.slice(2)),o.push(s);}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var X$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function da(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=false;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let a=e.match(X$);if(a){if(n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]),n.host)if(H$(n.host)===false){let l=q$(n.host);n.host=l.host.toLowerCase(),o=l.isIPV6;}else o=true;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=g1(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===false&&J$(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase());}catch(s){n.error=n.error||"Host's domain name can not be converted to ASCII: "+s;}(!i||i&&!i.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r);}else n.error=n.error||"URI can not be parsed.";return n}var $g={SCHEMES:W$,normalize:K$,resolve:G$,resolveComponent:y1,equal:Z$,serialize:Io,parse:da};_f.exports=$g;_f.exports.default=$g;_f.exports.fastUri=$g;});var x1=M(Ig=>{Object.defineProperty(Ig,"__esModule",{value:true});var b1=v1();b1.code='require("ajv/dist/runtime/uri").default';Ig.default=b1;});var T1=M(wr=>{Object.defineProperty(wr,"__esModule",{value:true});wr.CodeGen=wr.Name=wr.nil=wr.stringify=wr.str=wr._=wr.KeywordCxt=void 0;var Q$=ol();Object.defineProperty(wr,"KeywordCxt",{enumerable:true,get:function(){return Q$.KeywordCxt}});var il=Ve();Object.defineProperty(wr,"_",{enumerable:true,get:function(){return il._}});Object.defineProperty(wr,"str",{enumerable:true,get:function(){return il.str}});Object.defineProperty(wr,"stringify",{enumerable:true,get:function(){return il.stringify}});Object.defineProperty(wr,"nil",{enumerable:true,get:function(){return il.nil}});Object.defineProperty(wr,"Name",{enumerable:true,get:function(){return il.Name}});Object.defineProperty(wr,"CodeGen",{enumerable:true,get:function(){return il.CodeGen}});var Y$=gf(),C1=ou(),e4=ug(),iu=vf(),t4=Ve(),su=tu(),Sf=eu(),Mg=dt(),w1=i1(),r4=x1(),E1=(e,t)=>new RegExp(e,t);E1.code="new RegExp";var n4=["removeAdditional","useDefaults","coerceTypes"],o4=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),a4={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},i4={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},_1=200;function s4(e){var t,r,n,o,a,i,s,l,c,u,d,m,h,y,p,f,x,g,v,w,N,S,_,P,R;let E=e.strict,C=(t=e.code)===null||t===void 0?void 0:t.optimize,b=C===true||C===void 0?1:C||0,O=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:E1,D=(o=e.uriResolver)!==null&&o!==void 0?o:r4.default;return {strictSchema:(i=(a=e.strictSchema)!==null&&a!==void 0?a:E)!==null&&i!==void 0?i:true,strictNumbers:(l=(s=e.strictNumbers)!==null&&s!==void 0?s:E)!==null&&l!==void 0?l:true,strictTypes:(u=(c=e.strictTypes)!==null&&c!==void 0?c:E)!==null&&u!==void 0?u:"log",strictTuples:(m=(d=e.strictTuples)!==null&&d!==void 0?d:E)!==null&&m!==void 0?m:"log",strictRequired:(y=(h=e.strictRequired)!==null&&h!==void 0?h:E)!==null&&y!==void 0?y:false,code:e.code?{...e.code,optimize:b,regExp:O}:{optimize:b,regExp:O},loopRequired:(p=e.loopRequired)!==null&&p!==void 0?p:_1,loopEnum:(f=e.loopEnum)!==null&&f!==void 0?f:_1,meta:(x=e.meta)!==null&&x!==void 0?x:true,messages:(g=e.messages)!==null&&g!==void 0?g:true,inlineRefs:(v=e.inlineRefs)!==null&&v!==void 0?v:true,schemaId:(w=e.schemaId)!==null&&w!==void 0?w:"$id",addUsedSchema:(N=e.addUsedSchema)!==null&&N!==void 0?N:true,validateSchema:(S=e.validateSchema)!==null&&S!==void 0?S:true,validateFormats:(_=e.validateFormats)!==null&&_!==void 0?_:true,unicodeRegExp:(P=e.unicodeRegExp)!==null&&P!==void 0?P:true,int32range:(R=e.int32range)!==null&&R!==void 0?R:true,uriResolver:D}}var lu=class{constructor(t={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...s4(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new t4.ValueScope({scope:{},prefixes:o4,es5:r,lines:n}),this.logger=p4(t.logger);let o=t.validateFormats;t.validateFormats=false,this.RULES=(0, e4.getRules)(),S1.call(this,a4,t,"NOT SUPPORTED"),S1.call(this,i4,t,"DEPRECATED","warn"),this._metaOpts=d4.call(this),t.formats&&c4.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&u4.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),l4.call(this),t.validateFormats=o;}_addVocabularies(){this.addKeyword("$async");}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=w1;n==="id"&&(o={...w1},o.id=o.$id,delete o.$id),r&&t&&this.addMetaSchema(o,o[n],false);}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let o=n(r);return "$async"in n||(this.errors=n.errors),o}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,t,r);async function o(u,d){await a.call(this,u.$schema);let m=this._addSchema(u,d);return m.validate||i.call(this,m)}async function a(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},true);}async function i(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof C1.default))throw d;return s.call(this,d),await l.call(this,d.missingSchema),i.call(this,u)}}function s({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function l(u){let d=await c.call(this,u);this.refs[u]||await a.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r);}async function c(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u];}}}addSchema(t,r,n,o=this.opts.validateSchema){if(Array.isArray(t)){for(let i of t)this.addSchema(i,void 0,n,o);return this}let a;if(typeof t=="object"){let{schemaId:i}=this.opts;if(a=t[i],a!==void 0&&typeof a!="string")throw new Error(`schema ${i} must be string`)}return r=(0, su.normalizeId)(r||a),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,o,true),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,true,n),this}validateSchema(t,r){if(typeof t=="boolean")return true;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,true;let o=this.validate(n,t);if(!o&&r){let a="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(a);else throw new Error(a)}return o}getSchema(t){let r;for(;typeof(r=N1.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new iu.SchemaEnv({schema:{},schemaId:n});if(r=iu.resolveSchema.call(this,o,t),!r)return;this.refs[t]=r;}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case "undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case "string":{let r=N1.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case "object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0, su.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(h4.call(this,n,r),!r)return (0, Mg.eachItem)(n,a=>Fg.call(this,a)),this;y4.call(this,r);let o={...r,type:(0, Sf.getJSONTypes)(r.type),schemaType:(0, Sf.getJSONTypes)(r.schemaType)};return (0, Mg.eachItem)(n,o.type.length===0?a=>Fg.call(this,a,o):a=>o.type.forEach(i=>Fg.call(this,a,o,i))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let o=n.rules.findIndex(a=>a.keyword===t);o>=0&&n.rules.splice(o,1);}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return !t||t.length===0?"No errors":t.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,a)=>o+r+a)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let a=o.split("/").slice(1),i=t;for(let s of a)i=i[s];for(let s in n){let l=n[s];if(typeof l!="object")continue;let{$data:c}=l.definition,u=i[s];c&&u&&(i[s]=P1(u));}}return t}_removeAllSchemas(t,r){for(let n in t){let o=t[n];(!r||r.test(n))&&(typeof o=="string"?delete t[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete t[n]));}}_addSchema(t,r,n,o=this.opts.validateSchema,a=this.opts.addUsedSchema){let i,{schemaId:s}=this.opts;if(typeof t=="object")i=t[s];else {if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(t);if(l!==void 0)return l;n=(0, su.normalizeId)(i||n);let c=su.getSchemaRefs.call(this,t,n);return l=new iu.SchemaEnv({schema:t,schemaId:s,meta:r,baseId:n,localRefs:c}),this._cache.set(l.schema,l),a&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),o&&this.validateSchema(t,true),l}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):iu.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{iu.compileSchema.call(this,t);}finally{this.opts=r;}}};lu.ValidationError=Y$.default;lu.MissingRefError=C1.default;wr.default=lu;function S1(e,t,r,n="error"){for(let o in e){let a=o;a in t&&this.logger[n](`${r}: option ${o}. ${e[a]}`);}}function N1(e){return e=(0, su.normalizeId)(e),this.schemas[e]||this.refs[e]}function l4(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t);}function c4(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t);}}function u4(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r);}}function d4(){let e={...this.opts};for(let t of n4)delete e[t];return e}var f4={log(){},warn(){},error(){}};function p4(e){if(e===false)return f4;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var m4=/^[a-z_$][a-z0-9_$:-]*$/i;function h4(e,t){let{RULES:r}=this;if((0, Mg.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!m4.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function Fg(e,t,r){var n;let o=t?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:a}=this,i=o?a.post:a.rules.find(({type:l})=>l===r);if(i||(i={type:r,rules:[]},a.rules.push(i)),a.keywords[e]=true,!t)return;let s={keyword:e,definition:{...t,type:(0, Sf.getJSONTypes)(t.type),schemaType:(0, Sf.getJSONTypes)(t.schemaType)}};t.before?g4.call(this,i,s,t.before):i.rules.push(s),a.all[e]=s,(n=t.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l));}function g4(e,t,r){let n=e.rules.findIndex(o=>o.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`));}function y4(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=P1(t)),e.validateSchema=this.compile(t,true));}var v4={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function P1(e){return {anyOf:[e,v4]}}});var k1=M(jg=>{Object.defineProperty(jg,"__esModule",{value:true});var b4={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};jg.default=b4;});var A1=M(Zi=>{Object.defineProperty(Zi,"__esModule",{value:true});Zi.callRef=Zi.getValidate=void 0;var x4=ou(),R1=Cn(),rn=Ve(),sl=Do(),O1=vf(),Nf=dt(),w4={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:a,validateName:i,opts:s,self:l}=n,{root:c}=a;if((r==="#"||r==="#/")&&o===c.baseId)return d();let u=O1.resolveRef.call(l,c,o,r);if(u===void 0)throw new x4.default(n.opts.uriResolver,o,r);if(u instanceof O1.SchemaEnv)return m(u);return h(u);function d(){if(a===c)return Cf(e,i,a,a.$async);let y=t.scopeValue("root",{ref:c});return Cf(e,(0, rn._)`${y}.validate`,c,c.$async)}function m(y){let p=D1(e,y);Cf(e,p,y,y.$async);}function h(y){let p=t.scopeValue("schema",s.code.source===true?{ref:y,code:(0, rn.stringify)(y)}:{ref:y}),f=t.name("valid"),x=e.subschema({schema:y,dataTypes:[],schemaPath:rn.nil,topSchemaRef:p,errSchemaPath:r},f);e.mergeEvaluated(x),e.ok(f);}}};function D1(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0, rn._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Zi.getValidate=D1;function Cf(e,t,r,n){let{gen:o,it:a}=e,{allErrors:i,schemaEnv:s,opts:l}=a,c=l.passContext?sl.default.this:rn.nil;n?u():d();function u(){if(!s.$async)throw new Error("async schema referenced by sync schema");let y=o.let("valid");o.try(()=>{o.code((0, rn._)`await ${(0, R1.callValidateCode)(e,t,c)}`),h(t),i||o.assign(y,true);},p=>{o.if((0, rn._)`!(${p} instanceof ${a.ValidationError})`,()=>o.throw(p)),m(p),i||o.assign(y,false);}),e.ok(y);}function d(){e.result((0, R1.callValidateCode)(e,t,c),()=>h(t),()=>m(t));}function m(y){let p=(0, rn._)`${y}.errors`;o.assign(sl.default.vErrors,(0, rn._)`${sl.default.vErrors} === null ? ${p} : ${sl.default.vErrors}.concat(${p})`),o.assign(sl.default.errors,(0, rn._)`${sl.default.vErrors}.length`);}function h(y){var p;if(!a.opts.unevaluated)return;let f=(p=r?.validate)===null||p===void 0?void 0:p.evaluated;if(a.props!==true)if(f&&!f.dynamicProps)f.props!==void 0&&(a.props=Nf.mergeEvaluated.props(o,f.props,a.props));else {let x=o.var("props",(0, rn._)`${y}.evaluated.props`);a.props=Nf.mergeEvaluated.props(o,x,a.props,rn.Name);}if(a.items!==true)if(f&&!f.dynamicItems)f.items!==void 0&&(a.items=Nf.mergeEvaluated.items(o,f.items,a.items));else {let x=o.var("items",(0, rn._)`${y}.evaluated.items`);a.items=Nf.mergeEvaluated.items(o,x,a.items,rn.Name);}}}Zi.callRef=Cf;Zi.default=w4;});var $1=M(Lg=>{Object.defineProperty(Lg,"__esModule",{value:true});var _4=k1(),S4=A1(),N4=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",_4.default,S4.default];Lg.default=N4;});var I1=M(Bg=>{Object.defineProperty(Bg,"__esModule",{value:true});var Ef=Ve(),Za=Ef.operators,Pf={maximum:{okStr:"<=",ok:Za.LTE,fail:Za.GT},minimum:{okStr:">=",ok:Za.GTE,fail:Za.LT},exclusiveMaximum:{okStr:"<",ok:Za.LT,fail:Za.GTE},exclusiveMinimum:{okStr:">",ok:Za.GT,fail:Za.LTE}},C4={message:({keyword:e,schemaCode:t})=>(0, Ef.str)`must be ${Pf[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0, Ef._)`{comparison: ${Pf[e].okStr}, limit: ${t}}`},E4={keyword:Object.keys(Pf),type:"number",schemaType:"number",$data:true,error:C4,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0, Ef._)`${r} ${Pf[t].fail} ${n} || isNaN(${r})`);}};Bg.default=E4;});var F1=M(zg=>{Object.defineProperty(zg,"__esModule",{value:true});var cu=Ve(),P4={message:({schemaCode:e})=>(0, cu.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0, cu._)`{multipleOf: ${e}}`},T4={keyword:"multipleOf",type:"number",schemaType:"number",$data:true,error:P4,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,a=o.opts.multipleOfPrecision,i=t.let("res"),s=a?(0, cu._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${a}`:(0, cu._)`${i} !== parseInt(${i})`;e.fail$data((0, cu._)`(${n} === 0 || (${i} = ${r}/${n}, ${s}))`);}};zg.default=T4;});var j1=M(Ug=>{Object.defineProperty(Ug,"__esModule",{value:true});function M1(e){let t=e.length,r=0,n=0,o;for(;n<t;)r++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<t&&(o=e.charCodeAt(n),(o&64512)===56320&&n++);return r}Ug.default=M1;M1.code='require("ajv/dist/runtime/ucs2length").default';});var L1=M(qg=>{Object.defineProperty(qg,"__esModule",{value:true});var Xi=Ve(),k4=dt(),R4=j1(),O4={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return (0, Xi.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0, Xi._)`{limit: ${e}}`},D4={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:true,error:O4,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,a=t==="maxLength"?Xi.operators.GT:Xi.operators.LT,i=o.opts.unicode===false?(0, Xi._)`${r}.length`:(0, Xi._)`${(0, k4.useFunc)(e.gen,R4.default)}(${r})`;e.fail$data((0, Xi._)`${i} ${a} ${n}`);}};qg.default=D4;});var B1=M(Vg=>{Object.defineProperty(Vg,"__esModule",{value:true});var A4=Cn(),Tf=Ve(),$4={message:({schemaCode:e})=>(0, Tf.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0, Tf._)`{pattern: ${e}}`},I4={keyword:"pattern",type:"string",schemaType:"string",$data:true,error:$4,code(e){let{data:t,$data:r,schema:n,schemaCode:o,it:a}=e,i=a.opts.unicodeRegExp?"u":"",s=r?(0, Tf._)`(new RegExp(${o}, ${i}))`:(0, A4.usePattern)(e,n);e.fail$data((0, Tf._)`!${s}.test(${t})`);}};Vg.default=I4;});var z1=M(Hg=>{Object.defineProperty(Hg,"__esModule",{value:true});var uu=Ve(),F4={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return (0, uu.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0, uu._)`{limit: ${e}}`},M4={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:true,error:F4,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?uu.operators.GT:uu.operators.LT;e.fail$data((0, uu._)`Object.keys(${r}).length ${o} ${n}`);}};Hg.default=M4;});var U1=M(Jg=>{Object.defineProperty(Jg,"__esModule",{value:true});var du=Cn(),fu=Ve(),j4=dt(),L4={message:({params:{missingProperty:e}})=>(0, fu.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0, fu._)`{missingProperty: ${e}}`},B4={keyword:"required",type:"object",schemaType:"array",$data:true,error:L4,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:a,it:i}=e,{opts:s}=i;if(!a&&r.length===0)return;let l=r.length>=s.loopRequired;if(i.allErrors?c():u(),s.strictRequired){let h=e.parentSchema.properties,{definedProperties:y}=e.it;for(let p of r)if(h?.[p]===void 0&&!y.has(p)){let f=i.schemaEnv.baseId+i.errSchemaPath,x=`required property "${p}" is not defined at "${f}" (strictRequired)`;(0, j4.checkStrictMode)(i,x,i.opts.strictRequired);}}function c(){if(l||a)e.block$data(fu.nil,d);else for(let h of r)(0, du.checkReportMissingProp)(e,h);}function u(){let h=t.let("missing");if(l||a){let y=t.let("valid",true);e.block$data(y,()=>m(h,y)),e.ok(y);}else t.if((0, du.checkMissingProp)(e,r,h)),(0, du.reportMissingProp)(e,h),t.else();}function d(){t.forOf("prop",n,h=>{e.setParams({missingProperty:h}),t.if((0, du.noPropertyInData)(t,o,h,s.ownProperties),()=>e.error());});}function m(h,y){e.setParams({missingProperty:h}),t.forOf(h,n,()=>{t.assign(y,(0, du.propertyInData)(t,o,h,s.ownProperties)),t.if((0, fu.not)(y),()=>{e.error(),t.break();});},fu.nil);}}};Jg.default=B4;});var q1=M(Wg=>{Object.defineProperty(Wg,"__esModule",{value:true});var pu=Ve(),z4={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return (0, pu.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0, pu._)`{limit: ${e}}`},U4={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:true,error:z4,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?pu.operators.GT:pu.operators.LT;e.fail$data((0, pu._)`${r}.length ${o} ${n}`);}};Wg.default=U4;});var kf=M(Kg=>{Object.defineProperty(Kg,"__esModule",{value:true});var V1=vg();V1.code='require("ajv/dist/runtime/equal").default';Kg.default=V1;});var H1=M(Zg=>{Object.defineProperty(Zg,"__esModule",{value:true});var Gg=eu(),_r=Ve(),q4=dt(),V4=kf(),H4={message:({params:{i:e,j:t}})=>(0, _r.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0, _r._)`{i: ${e}, j: ${t}}`},J4={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:true,error:H4,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:a,schemaCode:i,it:s}=e;if(!n&&!o)return;let l=t.let("valid"),c=a.items?(0, Gg.getSchemaTypes)(a.items):[];e.block$data(l,u,(0, _r._)`${i} === false`),e.ok(l);function u(){let y=t.let("i",(0, _r._)`${r}.length`),p=t.let("j");e.setParams({i:y,j:p}),t.assign(l,true),t.if((0, _r._)`${y} > 1`,()=>(d()?m:h)(y,p));}function d(){return c.length>0&&!c.some(y=>y==="object"||y==="array")}function m(y,p){let f=t.name("item"),x=(0, Gg.checkDataTypes)(c,f,s.opts.strictNumbers,Gg.DataType.Wrong),g=t.const("indices",(0, _r._)`{}`);t.for((0, _r._)`;${y}--;`,()=>{t.let(f,(0, _r._)`${r}[${y}]`),t.if(x,(0, _r._)`continue`),c.length>1&&t.if((0, _r._)`typeof ${f} == "string"`,(0, _r._)`${f} += "_"`),t.if((0, _r._)`typeof ${g}[${f}] == "number"`,()=>{t.assign(p,(0, _r._)`${g}[${f}]`),e.error(),t.assign(l,false).break();}).code((0, _r._)`${g}[${f}] = ${y}`);});}function h(y,p){let f=(0, q4.useFunc)(t,V4.default),x=t.name("outer");t.label(x).for((0, _r._)`;${y}--;`,()=>t.for((0, _r._)`${p} = ${y}; ${p}--;`,()=>t.if((0, _r._)`${f}(${r}[${y}], ${r}[${p}])`,()=>{e.error(),t.assign(l,false).break(x);})));}}};Zg.default=J4;});var J1=M(Qg=>{Object.defineProperty(Qg,"__esModule",{value:true});var Xg=Ve(),W4=dt(),K4=kf(),G4={message:"must be equal to constant",params:({schemaCode:e})=>(0, Xg._)`{allowedValue: ${e}}`},Z4={keyword:"const",$data:true,error:G4,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:a}=e;n||a&&typeof a=="object"?e.fail$data((0, Xg._)`!${(0, W4.useFunc)(t,K4.default)}(${r}, ${o})`):e.fail((0, Xg._)`${a} !== ${r}`);}};Qg.default=Z4;});var W1=M(Yg=>{Object.defineProperty(Yg,"__esModule",{value:true});var mu=Ve(),X4=dt(),Q4=kf(),Y4={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0, mu._)`{allowedValues: ${e}}`},e5={keyword:"enum",schemaType:"array",$data:true,error:Y4,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:a,it:i}=e;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let s=o.length>=i.opts.loopEnum,l,c=()=>l??(l=(0, X4.useFunc)(t,Q4.default)),u;if(s||n)u=t.let("valid"),e.block$data(u,d);else {if(!Array.isArray(o))throw new Error("ajv implementation error");let h=t.const("vSchema",a);u=(0, mu.or)(...o.map((y,p)=>m(h,p)));}e.pass(u);function d(){t.assign(u,false),t.forOf("v",a,h=>t.if((0, mu._)`${c()}(${r}, ${h})`,()=>t.assign(u,true).break()));}function m(h,y){let p=o[y];return typeof p=="object"&&p!==null?(0, mu._)`${c()}(${r}, ${h}[${y}])`:(0, mu._)`${r} === ${p}`}}};Yg.default=e5;});var K1=M(ey=>{Object.defineProperty(ey,"__esModule",{value:true});var t5=I1(),r5=F1(),n5=L1(),o5=B1(),a5=z1(),i5=U1(),s5=q1(),l5=H1(),c5=J1(),u5=W1(),d5=[t5.default,r5.default,n5.default,o5.default,a5.default,i5.default,s5.default,l5.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},c5.default,u5.default];ey.default=d5;});var ry=M(hu=>{Object.defineProperty(hu,"__esModule",{value:true});hu.validateAdditionalItems=void 0;var Qi=Ve(),ty=dt(),f5={message:({params:{len:e}})=>(0, Qi.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0, Qi._)`{limit: ${e}}`},p5={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:f5,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0, ty.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}G1(e,n);}};function G1(e,t){let{gen:r,schema:n,data:o,keyword:a,it:i}=e;i.items=true;let s=r.const("len",(0, Qi._)`${o}.length`);if(n===false)e.setParams({len:t.length}),e.pass((0, Qi._)`${s} <= ${t.length}`);else if(typeof n=="object"&&!(0, ty.alwaysValidSchema)(i,n)){let c=r.var("valid",(0, Qi._)`${s} <= ${t.length}`);r.if((0, Qi.not)(c),()=>l(c)),e.ok(c);}function l(c){r.forRange("i",t.length,s,u=>{e.subschema({keyword:a,dataProp:u,dataPropType:ty.Type.Num},c),i.allErrors||r.if((0, Qi.not)(c),()=>r.break());});}}hu.validateAdditionalItems=G1;hu.default=p5;});var ny=M(gu=>{Object.defineProperty(gu,"__esModule",{value:true});gu.validateTuple=void 0;var Z1=Ve(),Rf=dt(),m5=Cn(),h5={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return X1(e,"additionalItems",t);r.items=true,!(0, Rf.alwaysValidSchema)(r,t)&&e.ok((0, m5.validateArray)(e));}};function X1(e,t,r=e.schema){let{gen:n,parentSchema:o,data:a,keyword:i,it:s}=e;u(o),s.opts.unevaluated&&r.length&&s.items!==true&&(s.items=Rf.mergeEvaluated.items(n,r.length,s.items));let l=n.name("valid"),c=n.const("len",(0, Z1._)`${a}.length`);r.forEach((d,m)=>{(0, Rf.alwaysValidSchema)(s,d)||(n.if((0, Z1._)`${c} > ${m}`,()=>e.subschema({keyword:i,schemaProp:m,dataProp:m},l)),e.ok(l));});function u(d){let{opts:m,errSchemaPath:h}=s,y=r.length,p=y===d.minItems&&(y===d.maxItems||d[t]===false);if(m.strictTuples&&!p){let f=`"${i}" is ${y}-tuple, but minItems or maxItems/${t} are not specified or different at path "${h}"`;(0, Rf.checkStrictMode)(s,f,m.strictTuples);}}}gu.validateTuple=X1;gu.default=h5;});var Q1=M(oy=>{Object.defineProperty(oy,"__esModule",{value:true});var g5=ny(),y5={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0, g5.validateTuple)(e,"items")};oy.default=y5;});var e_=M(ay=>{Object.defineProperty(ay,"__esModule",{value:true});var Y1=Ve(),v5=dt(),b5=Cn(),x5=ry(),w5={message:({params:{len:e}})=>(0, Y1.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0, Y1._)`{limit: ${e}}`},_5={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:w5,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=true,!(0, v5.alwaysValidSchema)(n,t)&&(o?(0, x5.validateAdditionalItems)(e,o):e.ok((0, b5.validateArray)(e)));}};ay.default=_5;});var t_=M(iy=>{Object.defineProperty(iy,"__esModule",{value:true});var Pn=Ve(),Of=dt(),S5={message:({params:{min:e,max:t}})=>t===void 0?(0, Pn.str)`must contain at least ${e} valid item(s)`:(0, Pn.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0, Pn._)`{minContains: ${e}}`:(0, Pn._)`{minContains: ${e}, maxContains: ${t}}`},N5={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:true,error:S5,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:a}=e,i,s,{minContains:l,maxContains:c}=n;a.opts.next?(i=l===void 0?1:l,s=c):i=1;let u=t.const("len",(0, Pn._)`${o}.length`);if(e.setParams({min:i,max:s}),s===void 0&&i===0){(0, Of.checkStrictMode)(a,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(s!==void 0&&i>s){(0, Of.checkStrictMode)(a,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0, Of.alwaysValidSchema)(a,r)){let p=(0, Pn._)`${u} >= ${i}`;s!==void 0&&(p=(0, Pn._)`${p} && ${u} <= ${s}`),e.pass(p);return}a.items=true;let d=t.name("valid");s===void 0&&i===1?h(d,()=>t.if(d,()=>t.break())):i===0?(t.let(d,true),s!==void 0&&t.if((0, Pn._)`${o}.length > 0`,m)):(t.let(d,false),m()),e.result(d,()=>e.reset());function m(){let p=t.name("_valid"),f=t.let("count",0);h(p,()=>t.if(p,()=>y(f)));}function h(p,f){t.forRange("i",0,u,x=>{e.subschema({keyword:"contains",dataProp:x,dataPropType:Of.Type.Num,compositeRule:true},p),f();});}function y(p){t.code((0, Pn._)`${p}++`),s===void 0?t.if((0, Pn._)`${p} >= ${i}`,()=>t.assign(d,true).break()):(t.if((0, Pn._)`${p} > ${s}`,()=>t.assign(d,false).break()),i===1?t.assign(d,true):t.if((0, Pn._)`${p} >= ${i}`,()=>t.assign(d,true)));}}};iy.default=N5;});var o_=M(Fo=>{Object.defineProperty(Fo,"__esModule",{value:true});Fo.validateSchemaDeps=Fo.validatePropertyDeps=Fo.error=void 0;var sy=Ve(),C5=dt(),yu=Cn();Fo.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return (0, sy.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0, sy._)`{property: ${e},
1
+ import*as Rt from'react';import Rt__default,{createContext,useContext,useMemo,useRef,useCallback,useEffect,useState,Component}from'react';import {useQuery,useQueryClient,QueryClient,QueryClientProvider,useMutation}from'@tanstack/react-query';import {toast}from'sonner';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {createSlot,Slot}from'@radix-ui/react-slot';import {cva}from'class-variance-authority';import {clsx}from'clsx';import {twMerge}from'tailwind-merge';import {CalendarIcon,Trash,Plus,Loader2,Search,X,ChevronLeftIcon,ChevronRightIcon,ChevronDownIcon,CheckIcon,Atom,Info,SquarePen,AppWindowIcon,Ruler,Blend,MousePointerClick,AlertCircle,Sparkles,ChevronDown,ChevronRight,EllipsisVertical,Trash2,MessageCircleOff,Download,CloudUpload,Copy,Pencil,GripVertical,EyeIcon,Type,Hash,ToggleLeft,List,Braces,Brackets,Calendar,Clock,CalendarClock,Link,PlusIcon,Shapes,ChevronUpIcon,XIcon,ArrowDown,ArrowRight,TriangleAlert,ChevronUp,Mail,CalendarDays,Building2,User,DollarSign,MapPin,ChevronLeft,Box,Table,CheckSquare,Table2,Blocks,Code,Eye,Edit,CircleX,FileX,Settings2,ArrowUpWideNarrowIcon,Database,ArrowDownWideNarrowIcon,FileSearch,SlidersHorizontal,Upload,MoreVertical,ShieldCheck,ShieldUser,RefreshCw,KeyRound,WifiOff,Paperclip,ListFilter,CircleCheck,Tag,CircleIcon,FileText,FileSpreadsheet,FileJson,ChevronsLeft,FileIcon,Play,UploadCloud,ImageIcon}from'lucide-react';import {set,isUndefined,isEqual,debounce,noop}from'lodash';import {format,isValid,parseISO}from'date-fns';import {create,createStore,useStore}from'zustand';import Ge from'decimal.js';import {useForm,Controller,useFormContext,useFormState,FormProvider}from'react-hook-form';import Tc from'lodash/set';import*as sN from'@radix-ui/react-label';import*as Tp from'@radix-ui/react-checkbox';import*as Tt from'@radix-ui/react-select';import*as Xa from'@radix-ui/react-accordion';import*as Kn from'@radix-ui/react-tooltip';import {TooltipArrow}from'@radix-ui/react-tooltip';import {getDefaultClassNames,DayPicker}from'react-day-picker';import*as Eo from'@radix-ui/react-popover';import*as PN from'react-dom';import PN__default from'react-dom';import*as St from'@radix-ui/react-dropdown-menu';import*as Kp from'@radix-ui/react-switch';import {Editor}from'@monaco-editor/react';import {zodResolver}from'@hookform/resolvers/zod';import*as Rr from'@radix-ui/react-alert-dialog';import*as ZE from'@radix-ui/react-separator';import {flexRender,useReactTable,getCoreRowModel}from'@tanstack/react-table';import {ajvResolver}from'@hookform/resolvers/ajv';import*as Mm from'@radix-ui/react-progress';import*as Ui from'@radix-ui/react-tabs';import*as Fh from'xlsx';import {PrismAsync}from'react-syntax-highlighter';import {oneDark}from'react-syntax-highlighter/dist/esm/styles/prism';import {lookup}from'mime-types';var xD=Object.create;var og=Object.defineProperty;var wD=Object.getOwnPropertyDescriptor;var _D=Object.getOwnPropertyNames;var SD=Object.getPrototypeOf,ND=Object.prototype.hasOwnProperty;var yo=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var B=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),CD=(e,t)=>{for(var r in t)og(e,r,{get:t[r],enumerable:true});},ED=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of _D(t))!ND.call(e,a)&&a!==r&&og(e,a,{get:()=>t[a],enumerable:!(n=wD(t,a))||n.enumerable});return e};var os=(e,t,r)=>(r=e!=null?xD(SD(e)):{},ED(!e||!e.__esModule?og(r,"default",{value:e,enumerable:true}):r,e));var _l=B(ft=>{Object.defineProperty(ft,"__esModule",{value:true});ft.regexpCode=ft.getEsmExportName=ft.getProperty=ft.safeStringify=ft.stringify=ft.strConcat=ft.addCodeArg=ft.str=ft._=ft.nil=ft._Code=ft.Name=ft.IDENTIFIER=ft._CodeOrName=void 0;var _u=class{};ft._CodeOrName=_u;ft.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ds=class extends _u{constructor(t){if(super(),!ft.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t;}toString(){return this.str}emptyStr(){return false}get names(){return {[this.str]:1}}};ft.Name=ds;var Bn=class extends _u{constructor(t){super(),this._items=typeof t=="string"?[t]:t;}toString(){return this.str}emptyStr(){if(this._items.length>1)return false;let t=this._items[0];return t===""||t==='""'}get str(){var t;return (t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return (t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof ds&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ft._Code=Bn;ft.nil=new Bn("");function Bw(e,...t){let r=[e[0]],n=0;for(;n<t.length;)pg(r,t[n]),r.push(e[++n]);return new Bn(r)}ft._=Bw;var fg=new Bn("+");function zw(e,...t){let r=[Su(e[0])],n=0;for(;n<t.length;)r.push(fg),pg(r,t[n]),r.push(fg,Su(e[++n]));return nA(r),new Bn(r)}ft.str=zw;function pg(e,t){t instanceof Bn?e.push(...t._items):t instanceof ds?e.push(t):e.push(iA(t));}ft.addCodeArg=pg;function nA(e){let t=1;for(;t<e.length-1;){if(e[t]===fg){let r=aA(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+";}t++;}}function aA(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof ds||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof ds))return `"${e}${t.slice(1)}`}function oA(e,t){return t.emptyStr()?e:e.emptyStr()?t:zw`${e}${t}`}ft.strConcat=oA;function iA(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:Su(Array.isArray(e)?e.join(","):e)}function sA(e){return new Bn(Su(e))}ft.stringify=sA;function Su(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}ft.safeStringify=Su;function lA(e){return typeof e=="string"&&ft.IDENTIFIER.test(e)?new Bn(`.${e}`):Bw`[${e}]`}ft.getProperty=lA;function cA(e){if(typeof e=="string"&&ft.IDENTIFIER.test(e))return new Bn(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}ft.getEsmExportName=cA;function uA(e){return new Bn(e.toString())}ft.regexpCode=uA;});var gg=B(cn=>{Object.defineProperty(cn,"__esModule",{value:true});cn.ValueScope=cn.ValueScopeName=cn.Scope=cn.varKinds=cn.UsedValueState=void 0;var ln=_l(),mg=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value;}},Of;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed";})(Of||(cn.UsedValueState=Of={}));cn.varKinds={const:new ln.Name("const"),let:new ln.Name("let"),var:new ln.Name("var")};var Df=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r;}toName(t){return t instanceof ln.Name?t:this.name(t)}name(t){return new ln.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return `${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};cn.Scope=Df;var Af=class extends ln.Name{constructor(t,r){super(r),this.prefix=t;}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0, ln._)`.${new ln.Name(r)}[${n}]`;}};cn.ValueScopeName=Af;var dA=(0, ln._)`\n`,hg=class extends Df{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?dA:ln.nil};}get(){return this._scope}name(t){return new Af(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let a=this.toName(t),{prefix:o}=a,i=(n=r.key)!==null&&n!==void 0?n:r.ref,s=this._values[o];if(s){let u=s.get(i);if(u)return u}else s=this._values[o]=new Map;s.set(i,a);let l=this._scope[o]||(this._scope[o]=[]),c=l.length;return l[c]=r.ref,a.setValue(r,{property:o,itemIndex:c}),a}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return (0, ln._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,a=>{if(a.value===void 0)throw new Error(`CodeGen: name "${a}" has no value`);return a.value.code},r,n)}_reduceValues(t,r,n={},a){let o=ln.nil;for(let i in t){let s=t[i];if(!s)continue;let l=n[i]=n[i]||new Map;s.forEach(c=>{if(l.has(c))return;l.set(c,Of.Started);let u=r(c);if(u){let d=this.opts.es5?cn.varKinds.var:cn.varKinds.const;o=(0, ln._)`${o}${d} ${c} = ${u};${this.opts._n}`;}else if(u=a?.(c))o=(0, ln._)`${o}${u}${this.opts._n}`;else throw new mg(c);l.set(c,Of.Completed);});}return o}};cn.ValueScope=hg;});var Ye=B(at=>{Object.defineProperty(at,"__esModule",{value:true});at.or=at.and=at.not=at.CodeGen=at.operators=at.varKinds=at.ValueScopeName=at.ValueScope=at.Scope=at.Name=at.regexpCode=at.stringify=at.getProperty=at.nil=at.strConcat=at.str=at._=void 0;var st=_l(),ha=gg(),ii=_l();Object.defineProperty(at,"_",{enumerable:true,get:function(){return ii._}});Object.defineProperty(at,"str",{enumerable:true,get:function(){return ii.str}});Object.defineProperty(at,"strConcat",{enumerable:true,get:function(){return ii.strConcat}});Object.defineProperty(at,"nil",{enumerable:true,get:function(){return ii.nil}});Object.defineProperty(at,"getProperty",{enumerable:true,get:function(){return ii.getProperty}});Object.defineProperty(at,"stringify",{enumerable:true,get:function(){return ii.stringify}});Object.defineProperty(at,"regexpCode",{enumerable:true,get:function(){return ii.regexpCode}});Object.defineProperty(at,"Name",{enumerable:true,get:function(){return ii.Name}});var Mf=gg();Object.defineProperty(at,"Scope",{enumerable:true,get:function(){return Mf.Scope}});Object.defineProperty(at,"ValueScope",{enumerable:true,get:function(){return Mf.ValueScope}});Object.defineProperty(at,"ValueScopeName",{enumerable:true,get:function(){return Mf.ValueScopeName}});Object.defineProperty(at,"varKinds",{enumerable:true,get:function(){return Mf.varKinds}});at.operators={GT:new st._Code(">"),GTE:new st._Code(">="),LT:new st._Code("<"),LTE:new st._Code("<="),EQ:new st._Code("==="),NEQ:new st._Code("!=="),NOT:new st._Code("!"),OR:new st._Code("||"),AND:new st._Code("&&"),ADD:new st._Code("+")};var vo=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},yg=class extends vo{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n;}render({es5:t,_n:r}){let n=t?ha.varKinds.var:this.varKind,a=this.rhs===void 0?"":` = ${this.rhs}`;return `${n} ${this.name}${a};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=Nl(this.rhs,t,r)),this}get names(){return this.rhs instanceof st._CodeOrName?this.rhs.names:{}}},$f=class extends vo{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n;}render({_n:t}){return `${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof st.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Nl(this.rhs,t,r),this}get names(){let t=this.lhs instanceof st.Name?{}:{...this.lhs.names};return Ff(t,this.rhs)}},vg=class extends $f{constructor(t,r,n,a){super(t,n,a),this.op=r;}render({_n:t}){return `${this.lhs} ${this.op}= ${this.rhs};`+t}},bg=class extends vo{constructor(t){super(),this.label=t,this.names={};}render({_n:t}){return `${this.label}:`+t}},xg=class extends vo{constructor(t){super(),this.label=t,this.names={};}render({_n:t}){return `break${this.label?` ${this.label}`:""};`+t}},wg=class extends vo{constructor(t){super(),this.error=t;}render({_n:t}){return `throw ${this.error};`+t}get names(){return this.error.names}},_g=class extends vo{constructor(t){super(),this.code=t;}render({_n:t}){return `${this.code};`+t}optimizeNodes(){return `${this.code}`?this:void 0}optimizeNames(t,r){return this.code=Nl(this.code,t,r),this}get names(){return this.code instanceof st._CodeOrName?this.code.names:{}}},Nu=class extends vo{constructor(t=[]){super(),this.nodes=t;}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1);}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,a=n.length;for(;a--;){let o=n[a];o.optimizeNames(t,r)||(fA(t,o.names),n.splice(a,1));}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>ms(t,r.names),{})}},bo=class extends Nu{render(t){return "{"+t._n+super.render(t)+"}"+t._n}},Sg=class extends Nu{},Sl=class extends bo{};Sl.kind="else";var fs=class e extends bo{constructor(t,r){super(r),this.condition=t;}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===true)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Sl(n):n;}if(r)return t===false?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Uw(t),r instanceof e?[r]:r.nodes);if(!(t===false||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=Nl(this.condition,t,r),this}get names(){let t=super.names;return Ff(t,this.condition),this.else&&ms(t,this.else.names),t}};fs.kind="if";var ps=class extends bo{};ps.kind="for";var Ng=class extends ps{constructor(t){super(),this.iteration=t;}render(t){return `for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=Nl(this.iteration,t,r),this}get names(){return ms(super.names,this.iteration.names)}},Cg=class extends ps{constructor(t,r,n,a){super(),this.varKind=t,this.name=r,this.from=n,this.to=a;}render(t){let r=t.es5?ha.varKinds.var:this.varKind,{name:n,from:a,to:o}=this;return `for(${r} ${n}=${a}; ${n}<${o}; ${n}++)`+super.render(t)}get names(){let t=Ff(super.names,this.from);return Ff(t,this.to)}},If=class extends ps{constructor(t,r,n,a){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=a;}render(t){return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=Nl(this.iterable,t,r),this}get names(){return ms(super.names,this.iterable.names)}},Cu=class extends bo{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n;}render(t){return `${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};Cu.kind="func";var Eu=class extends Nu{render(t){return "return "+super.render(t)}};Eu.kind="return";var Eg=class extends bo{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,a;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(a=this.finally)===null||a===void 0||a.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&ms(t,this.catch.names),this.finally&&ms(t,this.finally.names),t}},Pu=class extends bo{constructor(t){super(),this.error=t;}render(t){return `catch(${this.error})`+super.render(t)}};Pu.kind="catch";var Tu=class extends bo{render(t){return "finally"+super.render(t)}};Tu.kind="finally";var Pg=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2
+ `:""},this._extScope=t,this._scope=new ha.Scope({parent:t}),this._nodes=[new Sg];}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return (this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,a){let o=this._scope.toName(r);return n!==void 0&&a&&(this._constants[o.str]=n),this._leafNode(new yg(t,o,n)),o}const(t,r,n){return this._def(ha.varKinds.const,t,r,n)}let(t,r,n){return this._def(ha.varKinds.let,t,r,n)}var(t,r,n){return this._def(ha.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new $f(t,r,n))}add(t,r){return this._leafNode(new vg(t,at.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==st.nil&&this._leafNode(new _g(t)),this}object(...t){let r=["{"];for(let[n,a]of t)r.length>1&&r.push(","),r.push(n),(n!==a||this.opts.es5)&&(r.push(":"),(0, st.addCodeArg)(r,a));return r.push("}"),new st._Code(r)}if(t,r,n){if(this._blockNode(new fs(t)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(t){return this._elseNode(new fs(t))}else(){return this._elseNode(new Sl)}endIf(){return this._endBlockNode(fs,Sl)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Ng(t),r)}forRange(t,r,n,a,o=this.opts.es5?ha.varKinds.var:ha.varKinds.let){let i=this._scope.toName(t);return this._for(new Cg(o,i,r,n),()=>a(i))}forOf(t,r,n,a=ha.varKinds.const){let o=this._scope.toName(t);if(this.opts.es5){let i=r instanceof st.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0, st._)`${i}.length`,s=>{this.var(o,(0, st._)`${i}[${s}]`),n(o);})}return this._for(new If("of",a,o,r),()=>n(o))}forIn(t,r,n,a=this.opts.es5?ha.varKinds.var:ha.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0, st._)`Object.keys(${r})`,n);let o=this._scope.toName(t);return this._for(new If("in",a,o,r),()=>n(o))}endFor(){return this._endBlockNode(ps)}label(t){return this._leafNode(new bg(t))}break(t){return this._leafNode(new xg(t))}return(t){let r=new Eu;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Eu)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let a=new Eg;if(this._blockNode(a),this.code(t),r){let o=this.name("e");this._currNode=a.catch=new Pu(o),r(o);}return n&&(this._currNode=a.finally=new Tu,this.code(n)),this._endBlockNode(Pu,Tu)}throw(t){return this._leafNode(new wg(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=st.nil,n,a){return this._blockNode(new Cu(t,r,n)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(Cu)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants);}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t);}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof fs))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t;}};at.CodeGen=Pg;function ms(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function Ff(e,t){return t instanceof st._CodeOrName?ms(e,t.names):e}function Nl(e,t,r){if(e instanceof st.Name)return n(e);if(!a(e))return e;return new st._Code(e._items.reduce((o,i)=>(i instanceof st.Name&&(i=n(i)),i instanceof st._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[o.str];return i===void 0||t[o.str]!==1?o:(delete t[o.str],i)}function a(o){return o instanceof st._Code&&o._items.some(i=>i instanceof st.Name&&t[i.str]===1&&r[i.str]!==void 0)}}function fA(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0);}function Uw(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0, st._)`!${Tg(e)}`}at.not=Uw;var pA=qw(at.operators.AND);function mA(...e){return e.reduce(pA)}at.and=mA;var hA=qw(at.operators.OR);function gA(...e){return e.reduce(hA)}at.or=gA;function qw(e){return (t,r)=>t===st.nil?r:r===st.nil?t:(0, st._)`${Tg(t)} ${e} ${Tg(r)}`}function Tg(e){return e instanceof st.Name?e:(0, st._)`(${e})`}});var pt=B(ot=>{Object.defineProperty(ot,"__esModule",{value:true});ot.checkStrictMode=ot.getErrorPath=ot.Type=ot.useFunc=ot.setEvaluated=ot.evaluatedPropsToName=ot.mergeEvaluated=ot.eachItem=ot.unescapeJsonPointer=ot.escapeJsonPointer=ot.escapeFragment=ot.unescapeFragment=ot.schemaRefOrVal=ot.schemaHasRulesButRef=ot.schemaHasRules=ot.checkUnknownRules=ot.alwaysValidSchema=ot.toHash=void 0;var Pt=Ye(),yA=_l();function vA(e){let t={};for(let r of e)t[r]=true;return t}ot.toHash=vA;function bA(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?true:(Jw(e,t),!Ww(t,e.self.RULES.all))}ot.alwaysValidSchema=bA;function Jw(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let a=n.RULES.keywords;for(let o in t)a[o]||Zw(e,`unknown keyword: "${o}"`);}ot.checkUnknownRules=Jw;function Ww(e,t){if(typeof e=="boolean")return !e;for(let r in e)if(t[r])return true;return false}ot.schemaHasRules=Ww;function xA(e,t){if(typeof e=="boolean")return !e;for(let r in e)if(r!=="$ref"&&t.all[r])return true;return false}ot.schemaHasRulesButRef=xA;function wA({topSchemaRef:e,schemaPath:t},r,n,a){if(!a){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return (0, Pt._)`${r}`}return (0, Pt._)`${e}${t}${(0, Pt.getProperty)(n)}`}ot.schemaRefOrVal=wA;function _A(e){return Kw(decodeURIComponent(e))}ot.unescapeFragment=_A;function SA(e){return encodeURIComponent(Rg(e))}ot.escapeFragment=SA;function Rg(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}ot.escapeJsonPointer=Rg;function Kw(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}ot.unescapeJsonPointer=Kw;function NA(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e);}ot.eachItem=NA;function Vw({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return (a,o,i,s)=>{let l=i===void 0?o:i instanceof Pt.Name?(o instanceof Pt.Name?e(a,o,i):t(a,o,i),i):o instanceof Pt.Name?(t(a,i,o),o):r(o,i);return s===Pt.Name&&!(l instanceof Pt.Name)?n(a,l):l}}ot.mergeEvaluated={props:Vw({mergeNames:(e,t,r)=>e.if((0, Pt._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0, Pt._)`${t} === true`,()=>e.assign(r,true),()=>e.assign(r,(0, Pt._)`${r} || {}`).code((0, Pt._)`Object.assign(${r}, ${t})`));}),mergeToName:(e,t,r)=>e.if((0, Pt._)`${r} !== true`,()=>{t===true?e.assign(r,true):(e.assign(r,(0, Pt._)`${r} || {}`),Og(e,r,t));}),mergeValues:(e,t)=>e===true?true:{...e,...t},resultToName:Gw}),items:Vw({mergeNames:(e,t,r)=>e.if((0, Pt._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0, Pt._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0, Pt._)`${r} !== true`,()=>e.assign(r,t===true?true:(0, Pt._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===true?true:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Gw(e,t){if(t===true)return e.var("props",true);let r=e.var("props",(0, Pt._)`{}`);return t!==void 0&&Og(e,r,t),r}ot.evaluatedPropsToName=Gw;function Og(e,t,r){Object.keys(r).forEach(n=>e.assign((0, Pt._)`${t}${(0, Pt.getProperty)(n)}`,true));}ot.setEvaluated=Og;var Hw={};function CA(e,t){return e.scopeValue("func",{ref:t,code:Hw[t.code]||(Hw[t.code]=new yA._Code(t.code))})}ot.useFunc=CA;var kg;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str";})(kg||(ot.Type=kg={}));function EA(e,t,r){if(e instanceof Pt.Name){let n=t===kg.Num;return r?n?(0, Pt._)`"[" + ${e} + "]"`:(0, Pt._)`"['" + ${e} + "']"`:n?(0, Pt._)`"/" + ${e}`:(0, Pt._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0, Pt.getProperty)(e).toString():"/"+Rg(e)}ot.getErrorPath=EA;function Zw(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===true)throw new Error(t);e.self.logger.warn(t);}}ot.checkStrictMode=Zw;});var Ua=B(Dg=>{Object.defineProperty(Dg,"__esModule",{value:true});var Mr=Ye(),PA={data:new Mr.Name("data"),valCxt:new Mr.Name("valCxt"),instancePath:new Mr.Name("instancePath"),parentData:new Mr.Name("parentData"),parentDataProperty:new Mr.Name("parentDataProperty"),rootData:new Mr.Name("rootData"),dynamicAnchors:new Mr.Name("dynamicAnchors"),vErrors:new Mr.Name("vErrors"),errors:new Mr.Name("errors"),this:new Mr.Name("this"),self:new Mr.Name("self"),scope:new Mr.Name("scope"),json:new Mr.Name("json"),jsonPos:new Mr.Name("jsonPos"),jsonLen:new Mr.Name("jsonLen"),jsonPart:new Mr.Name("jsonPart")};Dg.default=PA;});var Cl=B(jr=>{Object.defineProperty(jr,"__esModule",{value:true});jr.extendErrors=jr.resetErrorsCount=jr.reportExtraError=jr.reportError=jr.keyword$DataError=jr.keywordError=void 0;var dt=Ye(),jf=pt(),Kr=Ua();jr.keywordError={message:({keyword:e})=>(0, dt.str)`must pass "${e}" keyword validation`};jr.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0, dt.str)`"${e}" keyword must be ${t} ($data)`:(0, dt.str)`"${e}" keyword is invalid ($data)`};function TA(e,t=jr.keywordError,r,n){let{it:a}=e,{gen:o,compositeRule:i,allErrors:s}=a,l=Yw(e,t,r);n??(i||s)?Xw(o,l):Qw(a,(0, dt._)`[${l}]`);}jr.reportError=TA;function kA(e,t=jr.keywordError,r){let{it:n}=e,{gen:a,compositeRule:o,allErrors:i}=n,s=Yw(e,t,r);Xw(a,s),o||i||Qw(n,Kr.default.vErrors);}jr.reportExtraError=kA;function RA(e,t){e.assign(Kr.default.errors,t),e.if((0, dt._)`${Kr.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0, dt._)`${Kr.default.vErrors}.length`,t),()=>e.assign(Kr.default.vErrors,null)));}jr.resetErrorsCount=RA;function OA({gen:e,keyword:t,schemaValue:r,data:n,errsCount:a,it:o}){if(a===void 0)throw new Error("ajv implementation error");let i=e.name("err");e.forRange("i",a,Kr.default.errors,s=>{e.const(i,(0, dt._)`${Kr.default.vErrors}[${s}]`),e.if((0, dt._)`${i}.instancePath === undefined`,()=>e.assign((0, dt._)`${i}.instancePath`,(0, dt.strConcat)(Kr.default.instancePath,o.errorPath))),e.assign((0, dt._)`${i}.schemaPath`,(0, dt.str)`${o.errSchemaPath}/${t}`),o.opts.verbose&&(e.assign((0, dt._)`${i}.schema`,r),e.assign((0, dt._)`${i}.data`,n));});}jr.extendErrors=OA;function Xw(e,t){let r=e.const("err",t);e.if((0, dt._)`${Kr.default.vErrors} === null`,()=>e.assign(Kr.default.vErrors,(0, dt._)`[${r}]`),(0, dt._)`${Kr.default.vErrors}.push(${r})`),e.code((0, dt._)`${Kr.default.errors}++`);}function Qw(e,t){let{gen:r,validateName:n,schemaEnv:a}=e;a.$async?r.throw((0, dt._)`new ${e.ValidationError}(${t})`):(r.assign((0, dt._)`${n}.errors`,t),r.return(false));}var hs={keyword:new dt.Name("keyword"),schemaPath:new dt.Name("schemaPath"),params:new dt.Name("params"),propertyName:new dt.Name("propertyName"),message:new dt.Name("message"),schema:new dt.Name("schema"),parentSchema:new dt.Name("parentSchema")};function Yw(e,t,r){let{createErrors:n}=e.it;return n===false?(0, dt._)`{}`:DA(e,t,r)}function DA(e,t,r={}){let{gen:n,it:a}=e,o=[AA(a,r),$A(e,r)];return IA(e,t,o),n.object(...o)}function AA({errorPath:e},{instancePath:t}){let r=t?(0, dt.str)`${e}${(0, jf.getErrorPath)(t,jf.Type.Str)}`:e;return [Kr.default.instancePath,(0, dt.strConcat)(Kr.default.instancePath,r)]}function $A({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let a=n?t:(0, dt.str)`${t}/${e}`;return r&&(a=(0, dt.str)`${a}${(0, jf.getErrorPath)(r,jf.Type.Str)}`),[hs.schemaPath,a]}function IA(e,{params:t,message:r},n){let{keyword:a,data:o,schemaValue:i,it:s}=e,{opts:l,propertyName:c,topSchemaRef:u,schemaPath:d}=s;n.push([hs.keyword,a],[hs.params,typeof t=="function"?t(e):t||(0, dt._)`{}`]),l.messages&&n.push([hs.message,typeof r=="function"?r(e):r]),l.verbose&&n.push([hs.schema,i],[hs.parentSchema,(0, dt._)`${u}${d}`],[Kr.default.data,o]),c&&n.push([hs.propertyName,c]);}});var t1=B(El=>{Object.defineProperty(El,"__esModule",{value:true});El.boolOrEmptySchema=El.topBoolOrEmptySchema=void 0;var FA=Cl(),MA=Ye(),jA=Ua(),LA={message:"boolean schema is false"};function BA(e){let{gen:t,schema:r,validateName:n}=e;r===false?e1(e,false):typeof r=="object"&&r.$async===true?t.return(jA.default.data):(t.assign((0, MA._)`${n}.errors`,null),t.return(true));}El.topBoolOrEmptySchema=BA;function zA(e,t){let{gen:r,schema:n}=e;n===false?(r.var(t,false),e1(e)):r.var(t,true);}El.boolOrEmptySchema=zA;function e1(e,t){let{gen:r,data:n}=e,a={gen:r,keyword:"false schema",data:n,schema:false,schemaCode:false,schemaValue:false,params:{},it:e};(0, FA.reportError)(a,LA,void 0,t);}});var Ag=B(Pl=>{Object.defineProperty(Pl,"__esModule",{value:true});Pl.getRules=Pl.isJSONType=void 0;var UA=["string","number","integer","boolean","null","object","array"],qA=new Set(UA);function VA(e){return typeof e=="string"&&qA.has(e)}Pl.isJSONType=VA;function HA(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return {types:{...e,integer:true,boolean:true,null:true},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Pl.getRules=HA;});var $g=B(si=>{Object.defineProperty(si,"__esModule",{value:true});si.shouldUseRule=si.shouldUseGroup=si.schemaHasRulesForType=void 0;function JA({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==true&&r1(e,n)}si.schemaHasRulesForType=JA;function r1(e,t){return t.rules.some(r=>n1(e,r))}si.shouldUseGroup=r1;function n1(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}si.shouldUseRule=n1;});var ku=B(Lr=>{Object.defineProperty(Lr,"__esModule",{value:true});Lr.reportTypeError=Lr.checkDataTypes=Lr.checkDataType=Lr.coerceAndCheckDataType=Lr.getJSONTypes=Lr.getSchemaTypes=Lr.DataType=void 0;var WA=Ag(),KA=$g(),GA=Cl(),et=Ye(),a1=pt(),Tl;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong";})(Tl||(Lr.DataType=Tl={}));function ZA(e){let t=o1(e.type);if(t.includes("null")){if(e.nullable===false)throw new Error("type: null contradicts nullable: false")}else {if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===true&&t.push("null");}return t}Lr.getSchemaTypes=ZA;function o1(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(WA.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Lr.getJSONTypes=o1;function XA(e,t){let{gen:r,data:n,opts:a}=e,o=QA(t,a.coerceTypes),i=t.length>0&&!(o.length===0&&t.length===1&&(0, KA.schemaHasRulesForType)(e,t[0]));if(i){let s=Fg(t,n,a.strictNumbers,Tl.Wrong);r.if(s,()=>{o.length?YA(e,t,o):Mg(e);});}return i}Lr.coerceAndCheckDataType=XA;var i1=new Set(["string","number","integer","boolean","null"]);function QA(e,t){return t?e.filter(r=>i1.has(r)||t==="array"&&r==="array"):[]}function YA(e,t,r){let{gen:n,data:a,opts:o}=e,i=n.let("dataType",(0, et._)`typeof ${a}`),s=n.let("coerced",(0, et._)`undefined`);o.coerceTypes==="array"&&n.if((0, et._)`${i} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>n.assign(a,(0, et._)`${a}[0]`).assign(i,(0, et._)`typeof ${a}`).if(Fg(t,a,o.strictNumbers),()=>n.assign(s,a))),n.if((0, et._)`${s} !== undefined`);for(let c of r)(i1.has(c)||c==="array"&&o.coerceTypes==="array")&&l(c);n.else(),Mg(e),n.endIf(),n.if((0, et._)`${s} !== undefined`,()=>{n.assign(a,s),e$(e,s);});function l(c){switch(c){case "string":n.elseIf((0, et._)`${i} == "number" || ${i} == "boolean"`).assign(s,(0, et._)`"" + ${a}`).elseIf((0, et._)`${a} === null`).assign(s,(0, et._)`""`);return;case "number":n.elseIf((0, et._)`${i} == "boolean" || ${a} === null
3
+ || (${i} == "string" && ${a} && ${a} == +${a})`).assign(s,(0, et._)`+${a}`);return;case "integer":n.elseIf((0, et._)`${i} === "boolean" || ${a} === null
4
+ || (${i} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(s,(0, et._)`+${a}`);return;case "boolean":n.elseIf((0, et._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(s,false).elseIf((0, et._)`${a} === "true" || ${a} === 1`).assign(s,true);return;case "null":n.elseIf((0, et._)`${a} === "" || ${a} === 0 || ${a} === false`),n.assign(s,null);return;case "array":n.elseIf((0, et._)`${i} === "string" || ${i} === "number"
5
+ || ${i} === "boolean" || ${a} === null`).assign(s,(0, et._)`[${a}]`);}}}function e$({gen:e,parentData:t,parentDataProperty:r},n){e.if((0, et._)`${t} !== undefined`,()=>e.assign((0, et._)`${t}[${r}]`,n));}function Ig(e,t,r,n=Tl.Correct){let a=n===Tl.Correct?et.operators.EQ:et.operators.NEQ,o;switch(e){case "null":return (0, et._)`${t} ${a} null`;case "array":o=(0, et._)`Array.isArray(${t})`;break;case "object":o=(0, et._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case "integer":o=i((0, et._)`!(${t} % 1) && !isNaN(${t})`);break;case "number":o=i();break;default:return (0, et._)`typeof ${t} ${a} ${e}`}return n===Tl.Correct?o:(0, et.not)(o);function i(s=et.nil){return (0, et.and)((0, et._)`typeof ${t} == "number"`,s,r?(0, et._)`isFinite(${t})`:et.nil)}}Lr.checkDataType=Ig;function Fg(e,t,r,n){if(e.length===1)return Ig(e[0],t,r,n);let a,o=(0, a1.toHash)(e);if(o.array&&o.object){let i=(0, et._)`typeof ${t} != "object"`;a=o.null?i:(0, et._)`!${t} || ${i}`,delete o.null,delete o.array,delete o.object;}else a=et.nil;o.number&&delete o.integer;for(let i in o)a=(0, et.and)(a,Ig(i,t,r,n));return a}Lr.checkDataTypes=Fg;var t$={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0, et._)`{type: ${e}}`:(0, et._)`{type: ${t}}`};function Mg(e){let t=r$(e);(0, GA.reportError)(t,t$);}Lr.reportTypeError=Mg;function r$(e){let{gen:t,data:r,schema:n}=e,a=(0, a1.schemaRefOrVal)(e,n,"type");return {gen:t,keyword:"type",data:r,schema:n.type,schemaCode:a,schemaValue:a,parentSchema:n,params:{},it:e}}});var l1=B(Lf=>{Object.defineProperty(Lf,"__esModule",{value:true});Lf.assignDefaults=void 0;var kl=Ye(),n$=pt();function a$(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let a in r)s1(e,a,r[a].default);else t==="array"&&Array.isArray(n)&&n.forEach((a,o)=>s1(e,o,a.default));}Lf.assignDefaults=a$;function s1(e,t,r){let{gen:n,compositeRule:a,data:o,opts:i}=e;if(r===void 0)return;let s=(0, kl._)`${o}${(0, kl.getProperty)(t)}`;if(a){(0, n$.checkStrictMode)(e,`default is ignored for: ${s}`);return}let l=(0, kl._)`${s} === undefined`;i.useDefaults==="empty"&&(l=(0, kl._)`${l} || ${s} === null || ${s} === ""`),n.if(l,(0, kl._)`${s} = ${(0, kl.stringify)(r)}`);}});var zn=B(_t=>{Object.defineProperty(_t,"__esModule",{value:true});_t.validateUnion=_t.validateArray=_t.usePattern=_t.callValidateCode=_t.schemaProperties=_t.allSchemaProperties=_t.noPropertyInData=_t.propertyInData=_t.isOwnProperty=_t.hasPropFunc=_t.reportMissingProp=_t.checkMissingProp=_t.checkReportMissingProp=void 0;var $t=Ye(),jg=pt(),li=Ua(),o$=pt();function i$(e,t){let{gen:r,data:n,it:a}=e;r.if(Bg(r,n,t,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0, $t._)`${t}`},true),e.error();});}_t.checkReportMissingProp=i$;function s$({gen:e,data:t,it:{opts:r}},n,a){return (0, $t.or)(...n.map(o=>(0, $t.and)(Bg(e,t,o,r.ownProperties),(0, $t._)`${a} = ${o}`)))}_t.checkMissingProp=s$;function l$(e,t){e.setParams({missingProperty:t},true),e.error();}_t.reportMissingProp=l$;function c1(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0, $t._)`Object.prototype.hasOwnProperty`})}_t.hasPropFunc=c1;function Lg(e,t,r){return (0, $t._)`${c1(e)}.call(${t}, ${r})`}_t.isOwnProperty=Lg;function c$(e,t,r,n){let a=(0, $t._)`${t}${(0, $t.getProperty)(r)} !== undefined`;return n?(0, $t._)`${a} && ${Lg(e,t,r)}`:a}_t.propertyInData=c$;function Bg(e,t,r,n){let a=(0, $t._)`${t}${(0, $t.getProperty)(r)} === undefined`;return n?(0, $t.or)(a,(0, $t.not)(Lg(e,t,r))):a}_t.noPropertyInData=Bg;function u1(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}_t.allSchemaProperties=u1;function u$(e,t){return u1(t).filter(r=>!(0, jg.alwaysValidSchema)(e,t[r]))}_t.schemaProperties=u$;function d$({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:a,errorPath:o},it:i},s,l,c){let u=c?(0, $t._)`${e}, ${t}, ${n}${a}`:t,d=[[li.default.instancePath,(0, $t.strConcat)(li.default.instancePath,o)],[li.default.parentData,i.parentData],[li.default.parentDataProperty,i.parentDataProperty],[li.default.rootData,li.default.rootData]];i.opts.dynamicRef&&d.push([li.default.dynamicAnchors,li.default.dynamicAnchors]);let g=(0, $t._)`${u}, ${r.object(...d)}`;return l!==$t.nil?(0, $t._)`${s}.call(${l}, ${g})`:(0, $t._)`${s}(${g})`}_t.callValidateCode=d$;var f$=(0, $t._)`new RegExp`;function p$({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:a}=t.code,o=a(r,n);return e.scopeValue("pattern",{key:o.toString(),ref:o,code:(0, $t._)`${a.code==="new RegExp"?f$:(0, o$.useFunc)(e,a)}(${r}, ${n})`})}_t.usePattern=p$;function m$(e){let{gen:t,data:r,keyword:n,it:a}=e,o=t.name("valid");if(a.allErrors){let s=t.let("valid",true);return i(()=>t.assign(s,false)),s}return t.var(o,true),i(()=>t.break()),o;function i(s){let l=t.const("len",(0, $t._)`${r}.length`);t.forRange("i",0,l,c=>{e.subschema({keyword:n,dataProp:c,dataPropType:jg.Type.Num},o),t.if((0, $t.not)(o),s);});}}_t.validateArray=m$;function h$(e){let{gen:t,schema:r,keyword:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0, jg.alwaysValidSchema)(a,l))&&!a.opts.unevaluated)return;let i=t.let("valid",false),s=t.name("_valid");t.block(()=>r.forEach((l,c)=>{let u=e.subschema({keyword:n,schemaProp:c,compositeRule:true},s);t.assign(i,(0, $t._)`${i} || ${s}`),e.mergeValidEvaluated(u,s)||t.if((0, $t.not)(i));})),e.result(i,()=>e.reset(),()=>e.error(true));}_t.validateUnion=h$;});var p1=B(qa=>{Object.defineProperty(qa,"__esModule",{value:true});qa.validateKeywordUsage=qa.validSchemaType=qa.funcKeywordCode=qa.macroKeywordCode=void 0;var Gr=Ye(),gs=Ua(),g$=zn(),y$=Cl();function v$(e,t){let{gen:r,keyword:n,schema:a,parentSchema:o,it:i}=e,s=t.macro.call(i.self,a,o,i),l=f1(r,n,s);i.opts.validateSchema!==false&&i.self.validateSchema(s,true);let c=r.name("valid");e.subschema({schema:s,schemaPath:Gr.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:true},c),e.pass(c,()=>e.error(true));}qa.macroKeywordCode=v$;function b$(e,t){var r;let{gen:n,keyword:a,schema:o,parentSchema:i,$data:s,it:l}=e;w$(l,t);let c=!s&&t.compile?t.compile.call(l.self,o,i,l):t.validate,u=f1(n,a,c),d=n.let("valid");e.block$data(d,g),e.ok((r=t.valid)!==null&&r!==void 0?r:d);function g(){if(t.errors===false)m(),t.modifying&&d1(e),p(()=>e.error());else {let v=t.async?f():h();t.modifying&&d1(e),p(()=>x$(e,v));}}function f(){let v=n.let("ruleErrs",null);return n.try(()=>m((0, Gr._)`await `),y=>n.assign(d,false).if((0, Gr._)`${y} instanceof ${l.ValidationError}`,()=>n.assign(v,(0, Gr._)`${y}.errors`),()=>n.throw(y))),v}function h(){let v=(0, Gr._)`${u}.errors`;return n.assign(v,null),m(Gr.nil),v}function m(v=t.async?(0, Gr._)`await `:Gr.nil){let y=l.opts.passContext?gs.default.this:gs.default.self,x=!("compile"in t&&!s||t.schema===false);n.assign(d,(0, Gr._)`${v}${(0, g$.callValidateCode)(e,u,y,x)}`,t.modifying);}function p(v){var y;n.if((0, Gr.not)((y=t.valid)!==null&&y!==void 0?y:d),v);}}qa.funcKeywordCode=b$;function d1(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0, Gr._)`${n.parentData}[${n.parentDataProperty}]`));}function x$(e,t){let{gen:r}=e;r.if((0, Gr._)`Array.isArray(${t})`,()=>{r.assign(gs.default.vErrors,(0, Gr._)`${gs.default.vErrors} === null ? ${t} : ${gs.default.vErrors}.concat(${t})`).assign(gs.default.errors,(0, Gr._)`${gs.default.vErrors}.length`),(0, y$.extendErrors)(e);},()=>e.error());}function w$({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function f1(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0, Gr.stringify)(r)})}function _$(e,t,r=false){return !t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}qa.validSchemaType=_$;function S$({schema:e,opts:t,self:r,errSchemaPath:n},a,o){if(Array.isArray(a.keyword)?!a.keyword.includes(o):a.keyword!==o)throw new Error("ajv implementation error");let i=a.dependencies;if(i?.some(s=>!Object.prototype.hasOwnProperty.call(e,s)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(a.validateSchema&&!a.validateSchema(e[o])){let l=`keyword "${o}" value is invalid at path "${n}": `+r.errorsText(a.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}qa.validateKeywordUsage=S$;});var h1=B(ci=>{Object.defineProperty(ci,"__esModule",{value:true});ci.extendSubschemaMode=ci.extendSubschemaData=ci.getSubschema=void 0;var Va=Ye(),m1=pt();function N$(e,{keyword:t,schemaProp:r,schema:n,schemaPath:a,errSchemaPath:o,topSchemaRef:i}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let s=e.schema[t];return r===void 0?{schema:s,schemaPath:(0, Va._)`${e.schemaPath}${(0, Va.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:s[r],schemaPath:(0, Va._)`${e.schemaPath}${(0, Va.getProperty)(t)}${(0, Va.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0, m1.escapeFragment)(r)}`}}if(n!==void 0){if(a===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return {schema:n,schemaPath:a,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}ci.getSubschema=N$;function C$(e,t,{dataProp:r,dataPropType:n,data:a,dataTypes:o,propertyName:i}){if(a!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:s}=t;if(r!==void 0){let{errorPath:c,dataPathArr:u,opts:d}=t,g=s.let("data",(0, Va._)`${t.data}${(0, Va.getProperty)(r)}`,true);l(g),e.errorPath=(0, Va.str)`${c}${(0, m1.getErrorPath)(r,n,d.jsPropertySyntax)}`,e.parentDataProperty=(0, Va._)`${r}`,e.dataPathArr=[...u,e.parentDataProperty];}if(a!==void 0){let c=a instanceof Va.Name?a:s.let("data",a,true);l(c),i!==void 0&&(e.propertyName=i);}o&&(e.dataTypes=o);function l(c){e.data=c,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,c];}}ci.extendSubschemaData=C$;function E$(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:a,allErrors:o}){n!==void 0&&(e.compositeRule=n),a!==void 0&&(e.createErrors=a),o!==void 0&&(e.allErrors=o),e.jtdDiscriminator=t,e.jtdMetadata=r;}ci.extendSubschemaMode=E$;});var zg=B((PW,g1)=>{g1.exports=function e(t,r){if(t===r)return true;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return false;var n,a,o;if(Array.isArray(t)){if(n=t.length,n!=r.length)return false;for(a=n;a--!==0;)if(!e(t[a],r[a]))return false;return true}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(o=Object.keys(t),n=o.length,n!==Object.keys(r).length)return false;for(a=n;a--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[a]))return false;for(a=n;a--!==0;){var i=o[a];if(!e(t[i],r[i]))return false}return true}return t!==t&&r!==r};});var v1=B((TW,y1)=>{var ui=y1.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},a=r.post||function(){};Bf(t,n,a,e,"",e);};ui.keywords={additionalItems:true,items:true,contains:true,additionalProperties:true,propertyNames:true,not:true,if:true,then:true,else:true};ui.arrayKeywords={items:true,allOf:true,anyOf:true,oneOf:true};ui.propsKeywords={$defs:true,definitions:true,properties:true,patternProperties:true,dependencies:true};ui.skipKeywords={default:true,enum:true,const:true,required:true,maximum:true,minimum:true,exclusiveMaximum:true,exclusiveMinimum:true,multipleOf:true,maxLength:true,minLength:true,pattern:true,format:true,maxItems:true,minItems:true,uniqueItems:true,maxProperties:true,minProperties:true};function Bf(e,t,r,n,a,o,i,s,l,c){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,a,o,i,s,l,c);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in ui.arrayKeywords)for(var g=0;g<d.length;g++)Bf(e,t,r,d[g],a+"/"+u+"/"+g,o,a,u,n,g);}else if(u in ui.propsKeywords){if(d&&typeof d=="object")for(var f in d)Bf(e,t,r,d[f],a+"/"+u+"/"+P$(f),o,a,u,n,f);}else (u in ui.keywords||e.allKeys&&!(u in ui.skipKeywords))&&Bf(e,t,r,d,a+"/"+u,o,a,u,n);}r(n,a,o,i,s,l,c);}}function P$(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ru=B(un=>{Object.defineProperty(un,"__esModule",{value:true});un.getSchemaRefs=un.resolveUrl=un.normalizeId=un._getFullPath=un.getFullPath=un.inlineRef=void 0;var T$=pt(),k$=zg(),R$=v1(),O$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function D$(e,t=true){return typeof e=="boolean"?true:t===true?!Ug(e):t?b1(e)<=t:false}un.inlineRef=D$;var A$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ug(e){for(let t in e){if(A$.has(t))return true;let r=e[t];if(Array.isArray(r)&&r.some(Ug)||typeof r=="object"&&Ug(r))return true}return false}function b1(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!O$.has(r)&&(typeof e[r]=="object"&&(0, T$.eachItem)(e[r],n=>t+=b1(n)),t===1/0))return 1/0}return t}function x1(e,t="",r){r!==false&&(t=Rl(t));let n=e.parse(t);return w1(e,n)}un.getFullPath=x1;function w1(e,t){return e.serialize(t).split("#")[0]+"#"}un._getFullPath=w1;var $$=/#\/?$/;function Rl(e){return e?e.replace($$,""):""}un.normalizeId=Rl;function I$(e,t,r){return r=Rl(r),e.resolve(t,r)}un.resolveUrl=I$;var F$=/^[a-z_][-a-z0-9._]*$/i;function M$(e,t){if(typeof e=="boolean")return {};let{schemaId:r,uriResolver:n}=this.opts,a=Rl(e[r]||t),o={"":a},i=x1(n,a,false),s={},l=new Set;return R$(e,{allKeys:true},(d,g,f,h)=>{if(h===void 0)return;let m=i+g,p=o[h];typeof d[r]=="string"&&(p=v.call(this,d[r])),y.call(this,d.$anchor),y.call(this,d.$dynamicAnchor),o[g]=p;function v(x){let w=this.opts.uriResolver.resolve;if(x=Rl(p?w(p,x):x),l.has(x))throw u(x);l.add(x);let _=this.refs[x];return typeof _=="string"&&(_=this.refs[_]),typeof _=="object"?c(d,_.schema,x):x!==Rl(m)&&(x[0]==="#"?(c(d,s[x],x),s[x]=d):this.refs[x]=m),x}function y(x){if(typeof x=="string"){if(!F$.test(x))throw new Error(`invalid anchor "${x}"`);v.call(this,`#${x}`);}}}),s;function c(d,g,f){if(g!==void 0&&!k$(d,g))throw u(f)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}un.getSchemaRefs=M$;});var Ol=B(di=>{Object.defineProperty(di,"__esModule",{value:true});di.getData=di.KeywordCxt=di.validateFunctionCode=void 0;var E1=t1(),_1=ku(),Vg=$g(),zf=ku(),j$=l1(),Du=p1(),qg=h1(),Se=Ye(),qe=Ua(),L$=Ru(),xo=pt(),Ou=Cl();function B$(e){if(k1(e)&&(R1(e),T1(e))){q$(e);return}P1(e,()=>(0, E1.topBoolOrEmptySchema)(e));}di.validateFunctionCode=B$;function P1({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},o){a.code.es5?e.func(t,(0, Se._)`${qe.default.data}, ${qe.default.valCxt}`,n.$async,()=>{e.code((0, Se._)`"use strict"; ${S1(r,a)}`),U$(e,a),e.code(o);}):e.func(t,(0, Se._)`${qe.default.data}, ${z$(a)}`,n.$async,()=>e.code(S1(r,a)).code(o));}function z$(e){return (0, Se._)`{${qe.default.instancePath}="", ${qe.default.parentData}, ${qe.default.parentDataProperty}, ${qe.default.rootData}=${qe.default.data}${e.dynamicRef?(0, Se._)`, ${qe.default.dynamicAnchors}={}`:Se.nil}}={}`}function U$(e,t){e.if(qe.default.valCxt,()=>{e.var(qe.default.instancePath,(0, Se._)`${qe.default.valCxt}.${qe.default.instancePath}`),e.var(qe.default.parentData,(0, Se._)`${qe.default.valCxt}.${qe.default.parentData}`),e.var(qe.default.parentDataProperty,(0, Se._)`${qe.default.valCxt}.${qe.default.parentDataProperty}`),e.var(qe.default.rootData,(0, Se._)`${qe.default.valCxt}.${qe.default.rootData}`),t.dynamicRef&&e.var(qe.default.dynamicAnchors,(0, Se._)`${qe.default.valCxt}.${qe.default.dynamicAnchors}`);},()=>{e.var(qe.default.instancePath,(0, Se._)`""`),e.var(qe.default.parentData,(0, Se._)`undefined`),e.var(qe.default.parentDataProperty,(0, Se._)`undefined`),e.var(qe.default.rootData,qe.default.data),t.dynamicRef&&e.var(qe.default.dynamicAnchors,(0, Se._)`{}`);});}function q$(e){let{schema:t,opts:r,gen:n}=e;P1(e,()=>{r.$comment&&t.$comment&&D1(e),K$(e),n.let(qe.default.vErrors,null),n.let(qe.default.errors,0),r.unevaluated&&V$(e),O1(e),X$(e);});}function V$(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0, Se._)`${r}.evaluated`),t.if((0, Se._)`${e.evaluated}.dynamicProps`,()=>t.assign((0, Se._)`${e.evaluated}.props`,(0, Se._)`undefined`)),t.if((0, Se._)`${e.evaluated}.dynamicItems`,()=>t.assign((0, Se._)`${e.evaluated}.items`,(0, Se._)`undefined`));}function S1(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0, Se._)`/*# sourceURL=${r} */`:Se.nil}function H$(e,t){if(k1(e)&&(R1(e),T1(e))){J$(e,t);return}(0, E1.boolOrEmptySchema)(e,t);}function T1({schema:e,self:t}){if(typeof e=="boolean")return !e;for(let r in e)if(t.RULES.all[r])return true;return false}function k1(e){return typeof e.schema!="boolean"}function J$(e,t){let{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&D1(e),G$(e),Z$(e);let o=n.const("_errs",qe.default.errors);O1(e,o),n.var(t,(0, Se._)`${o} === ${qe.default.errors}`);}function R1(e){(0, xo.checkUnknownRules)(e),W$(e);}function O1(e,t){if(e.opts.jtd)return N1(e,[],false,t);let r=(0, _1.getSchemaTypes)(e.schema),n=(0, _1.coerceAndCheckDataType)(e,r);N1(e,r,!n,t);}function W$(e){let{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0, xo.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`);}function K$(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0, xo.checkStrictMode)(e,"default is ignored in the schema root");}function G$(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0, L$.resolveUrl)(e.opts.uriResolver,e.baseId,t));}function Z$(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function D1({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){let o=r.$comment;if(a.$comment===true)e.code((0, Se._)`${qe.default.self}.logger.log(${o})`);else if(typeof a.$comment=="function"){let i=(0, Se.str)`${n}/$comment`,s=e.scopeValue("root",{ref:t.root});e.code((0, Se._)`${qe.default.self}.opts.$comment(${o}, ${i}, ${s}.schema)`);}}function X$(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:o}=e;r.$async?t.if((0, Se._)`${qe.default.errors} === 0`,()=>t.return(qe.default.data),()=>t.throw((0, Se._)`new ${a}(${qe.default.vErrors})`)):(t.assign((0, Se._)`${n}.errors`,qe.default.vErrors),o.unevaluated&&Q$(e),t.return((0, Se._)`${qe.default.errors} === 0`));}function Q$({gen:e,evaluated:t,props:r,items:n}){r instanceof Se.Name&&e.assign((0, Se._)`${t}.props`,r),n instanceof Se.Name&&e.assign((0, Se._)`${t}.items`,n);}function N1(e,t,r,n){let{gen:a,schema:o,data:i,allErrors:s,opts:l,self:c}=e,{RULES:u}=c;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0, xo.schemaHasRulesButRef)(o,u))){a.block(()=>$1(e,"$ref",u.all.$ref.definition));return}l.jtd||Y$(e,t),a.block(()=>{for(let g of u.rules)d(g);d(u.post);});function d(g){(0, Vg.shouldUseGroup)(o,g)&&(g.type?(a.if((0, zf.checkDataType)(g.type,i,l.strictNumbers)),C1(e,g),t.length===1&&t[0]===g.type&&r&&(a.else(),(0, zf.reportTypeError)(e)),a.endIf()):C1(e,g),s||a.if((0, Se._)`${qe.default.errors} === ${n||0}`));}}function C1(e,t){let{gen:r,schema:n,opts:{useDefaults:a}}=e;a&&(0, j$.assignDefaults)(e,t.type),r.block(()=>{for(let o of t.rules)(0, Vg.shouldUseRule)(n,o)&&$1(e,o.keyword,o.definition,t.type);});}function Y$(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(e4(e,t),e.opts.allowUnionTypes||t4(e,t),r4(e,e.dataTypes));}function e4(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{A1(e.dataTypes,r)||Hg(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`);}),a4(e,t);}}function t4(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Hg(e,"use allowUnionTypes to allow union type keyword");}function r4(e,t){let r=e.self.RULES.all;for(let n in r){let a=r[n];if(typeof a=="object"&&(0, Vg.shouldUseRule)(e.schema,a)){let{type:o}=a.definition;o.length&&!o.some(i=>n4(t,i))&&Hg(e,`missing type "${o.join(",")}" for keyword "${n}"`);}}}function n4(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function A1(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function a4(e,t){let r=[];for(let n of e.dataTypes)A1(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r;}function Hg(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0, xo.checkStrictMode)(e,t,e.opts.strictTypes);}var Uf=class{constructor(t,r,n){if((0, Du.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0, xo.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",I1(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0, Du.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==false)&&(this.errsCount=t.gen.const("_errs",qe.default.errors));}result(t,r,n){this.failResult((0, Se.not)(t),r,n);}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else();}pass(t,r){this.failResult((0, Se.not)(t),void 0,r);}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(false);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else();}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0, Se._)`${r} !== undefined && (${(0, Se.or)(this.invalid$data(),t)})`);}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n);}_error(t,r){(t?Ou.reportExtraError:Ou.reportError)(this,this.def.error,r);}$dataError(){(0, Ou.reportError)(this,this.def.$dataError||Ou.keyword$DataError);}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0, Ou.resetErrorsCount)(this.gen,this.errsCount);}ok(t){this.allErrors||this.gen.if(t);}setParams(t,r){r?Object.assign(this.params,t):this.params=t;}block$data(t,r,n=Se.nil){this.gen.block(()=>{this.check$data(t,n),r();});}check$data(t=Se.nil,r=Se.nil){if(!this.$data)return;let{gen:n,schemaCode:a,schemaType:o,def:i}=this;n.if((0, Se.or)((0, Se._)`${a} === undefined`,r)),t!==Se.nil&&n.assign(t,true),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==Se.nil&&n.assign(t,false)),n.else();}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:a,it:o}=this;return (0, Se.or)(i(),s());function i(){if(n.length){if(!(r instanceof Se.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return (0, Se._)`${(0, zf.checkDataTypes)(l,r,o.opts.strictNumbers,zf.DataType.Wrong)}`}return Se.nil}function s(){if(a.validateSchema){let l=t.scopeValue("validate$data",{ref:a.validateSchema});return (0, Se._)`!${l}(${r})`}return Se.nil}}subschema(t,r){let n=(0, qg.getSubschema)(this.it,t);(0, qg.extendSubschemaData)(n,this.it,t),(0, qg.extendSubschemaMode)(n,t);let a={...this.it,...n,items:void 0,props:void 0};return H$(a,r),a}mergeEvaluated(t,r){let{it:n,gen:a}=this;n.opts.unevaluated&&(n.props!==true&&t.props!==void 0&&(n.props=xo.mergeEvaluated.props(a,t.props,n.props,r)),n.items!==true&&t.items!==void 0&&(n.items=xo.mergeEvaluated.items(a,t.items,n.items,r)));}mergeValidEvaluated(t,r){let{it:n,gen:a}=this;if(n.opts.unevaluated&&(n.props!==true||n.items!==true))return a.if(r,()=>this.mergeEvaluated(t,Se.Name)),true}};di.KeywordCxt=Uf;function $1(e,t,r,n){let a=new Uf(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0, Du.funcKeywordCode)(a,r):"macro"in r?(0, Du.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0, Du.funcKeywordCode)(a,r);}var o4=/^\/(?:[^~]|~0|~1)*$/,i4=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function I1(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,o;if(e==="")return qe.default.rootData;if(e[0]==="/"){if(!o4.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,o=qe.default.rootData;}else {let c=i4.exec(e);if(!c)throw new Error(`Invalid JSON-pointer: ${e}`);let u=+c[1];if(a=c[2],a==="#"){if(u>=t)throw new Error(l("property/index",u));return n[t-u]}if(u>t)throw new Error(l("data",u));if(o=r[t-u],!a)return o}let i=o,s=a.split("/");for(let c of s)c&&(o=(0, Se._)`${o}${(0, Se.getProperty)((0, xo.unescapeJsonPointer)(c))}`,i=(0, Se._)`${i} && ${o}`);return i;function l(c,u){return `Cannot access ${c} ${u} levels up, current level is ${t}`}}di.getData=I1;});var qf=B(Wg=>{Object.defineProperty(Wg,"__esModule",{value:true});var Jg=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=true;}};Wg.default=Jg;});var Au=B(Zg=>{Object.defineProperty(Zg,"__esModule",{value:true});var Kg=Ru(),Gg=class extends Error{constructor(t,r,n,a){super(a||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0, Kg.resolveUrl)(t,r,n),this.missingSchema=(0, Kg.normalizeId)((0, Kg.getFullPath)(t,this.missingRef));}};Zg.default=Gg;});var Hf=B(Un=>{Object.defineProperty(Un,"__esModule",{value:true});Un.resolveSchema=Un.getCompilingSchema=Un.resolveRef=Un.compileSchema=Un.SchemaEnv=void 0;var ga=Ye(),s4=qf(),ys=Ua(),ya=Ru(),F1=pt(),l4=Ol(),Dl=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0, ya.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={};}};Un.SchemaEnv=Dl;function Qg(e){let t=M1.call(this,e);if(t)return t;let r=(0, ya.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:a}=this.opts.code,{ownProperties:o}=this.opts,i=new ga.CodeGen(this.scope,{es5:n,lines:a,ownProperties:o}),s;e.$async&&(s=i.scopeValue("Error",{ref:s4.default,code:(0, ga._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");e.validateName=l;let c={gen:i,allErrors:this.opts.allErrors,data:ys.default.data,parentData:ys.default.parentData,parentDataProperty:ys.default.parentDataProperty,dataNames:[ys.default.data],dataPathArr:[ga.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===true?{ref:e.schema,code:(0, ga.stringify)(e.schema)}:{ref:e.schema}),validateName:l,ValidationError:s,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:ga.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0, ga._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(e),(0,l4.validateFunctionCode)(c),i.optimize(this.opts.code.optimize);let d=i.toString();u=`${i.scopeRefs(ys.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,e));let f=new Function(`${ys.default.self}`,`${ys.default.scope}`,u)(this,this.scope.get());if(this.scope.value(l,{ref:f}),f.errors=null,f.schema=e.schema,f.schemaEnv=e,e.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:l,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:m}=c;f.evaluated={props:h instanceof ga.Name?void 0:h,items:m instanceof ga.Name?void 0:m,dynamicProps:h instanceof ga.Name,dynamicItems:m instanceof ga.Name},f.source&&(f.source.evaluated=(0,ga.stringify)(f.evaluated));}return e.validate=f,e}catch(d){throw delete e.validate,delete e.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(e);}}Un.compileSchema=Qg;function c4(e,t,r){var n;r=(0, ya.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let o=f4.call(this,e,r);if(o===void 0){let i=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:s}=this.opts;i&&(o=new Dl({schema:i,schemaId:s,root:e,baseId:t}));}if(o!==void 0)return e.refs[r]=u4.call(this,o)}Un.resolveRef=c4;function u4(e){return (0, ya.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Qg.call(this,e)}function M1(e){for(let t of this._compilations)if(d4(t,e))return t}Un.getCompilingSchema=M1;function d4(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function f4(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||Vf.call(this,e,t)}function Vf(e,t){let r=this.opts.uriResolver.parse(t),n=(0, ya._getFullPath)(this.opts.uriResolver,r),a=(0, ya.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===a)return Xg.call(this,r,e);let o=(0, ya.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let s=Vf.call(this,e,i);return typeof s?.schema!="object"?void 0:Xg.call(this,r,s)}if(typeof i?.schema=="object"){if(i.validate||Qg.call(this,i),o===(0, ya.normalizeId)(t)){let{schema:s}=i,{schemaId:l}=this.opts,c=s[l];return c&&(a=(0, ya.resolveUrl)(this.opts.uriResolver,a,c)),new Dl({schema:s,schemaId:l,root:e,baseId:a})}return Xg.call(this,r,i)}}Un.resolveSchema=Vf;var p4=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Xg(e,{baseId:t,schema:r,root:n}){var a;if(((a=e.fragment)===null||a===void 0?void 0:a[0])!=="/")return;for(let s of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0, F1.unescapeFragment)(s)];if(l===void 0)return;r=l;let c=typeof r=="object"&&r[this.opts.schemaId];!p4.has(s)&&c&&(t=(0, ya.resolveUrl)(this.opts.uriResolver,t,c));}let o;if(typeof r!="boolean"&&r.$ref&&!(0, F1.schemaHasRulesButRef)(r,this.RULES)){let s=(0, ya.resolveUrl)(this.opts.uriResolver,t,r.$ref);o=Vf.call(this,n,s);}let{schemaId:i}=this.opts;if(o=o||new Dl({schema:r,schemaId:i,root:n,baseId:t}),o.schema!==o.root.schema)return o}});var j1=B(($W,m4)=>{m4.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:false};});var B1=B((IW,L1)=>{var h4={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};L1.exports={HEX:h4};});var K1=B((FW,W1)=>{var{HEX:g4}=B1(),y4=/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u;function V1(e){if(J1(e,".")<3)return {host:e,isIPV4:false};let t=e.match(y4)||[],[r]=t;return r?{host:b4(r,"."),isIPV4:true}:{host:e,isIPV4:false}}function Yg(e,t=false){let r="",n=true;for(let a of e){if(g4[a]===void 0)return;a!=="0"&&n===true&&(n=false),n||(r+=a);}return t&&r.length===0&&(r="0"),r}function v4(e){let t=0,r={error:false,address:"",zone:""},n=[],a=[],o=false,i=false,s=false;function l(){if(a.length){if(o===false){let c=Yg(a);if(c!==void 0)n.push(c);else return r.error=true,false}a.length=0;}return true}for(let c=0;c<e.length;c++){let u=e[c];if(!(u==="["||u==="]"))if(u===":"){if(i===true&&(s=true),!l())break;if(t++,n.push(":"),t>7){r.error=true;break}c-1>=0&&e[c-1]===":"&&(i=true);continue}else if(u==="%"){if(!l())break;o=true;}else {a.push(u);continue}}return a.length&&(o?r.zone=a.join(""):s?n.push(a.join("")):n.push(Yg(a))),r.address=n.join(""),r}function H1(e){if(J1(e,":")<2)return {host:e,isIPV6:false};let t=v4(e);if(t.error)return {host:e,isIPV6:false};{let r=t.address,n=t.address;return t.zone&&(r+="%"+t.zone,n+="%25"+t.zone),{host:r,escapedHost:n,isIPV6:true}}}function b4(e,t){let r="",n=true,a=e.length;for(let o=0;o<a;o++){let i=e[o];i==="0"&&n?(o+1<=a&&e[o+1]===t||o+1===a)&&(r+=i,n=false):(i===t?n=true:n=false,r+=i);}return r}function J1(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}var z1=/^\.\.?\//u,U1=/^\/\.(?:\/|$)/u,q1=/^\/\.\.(?:\/|$)/u,x4=/^\/?(?:.|\n)*?(?=\/|$)/u;function w4(e){let t=[];for(;e.length;)if(e.match(z1))e=e.replace(z1,"");else if(e.match(U1))e=e.replace(U1,"/");else if(e.match(q1))e=e.replace(q1,"/"),t.pop();else if(e==="."||e==="..")e="";else {let r=e.match(x4);if(r){let n=r[0];e=e.slice(n.length),t.push(n);}else throw new Error("Unexpected dot segment condition")}return t.join("")}function _4(e,t){let r=t!==true?escape:unescape;return e.scheme!==void 0&&(e.scheme=r(e.scheme)),e.userinfo!==void 0&&(e.userinfo=r(e.userinfo)),e.host!==void 0&&(e.host=r(e.host)),e.path!==void 0&&(e.path=r(e.path)),e.query!==void 0&&(e.query=r(e.query)),e.fragment!==void 0&&(e.fragment=r(e.fragment)),e}function S4(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host),n=V1(r);if(n.isIPV4)r=n.host;else {let a=H1(n.host);a.isIPV6===true?r=`[${a.escapedHost}]`:r=e.host;}t.push(r);}return (typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}W1.exports={recomposeAuthority:S4,normalizeComponentEncoding:_4,removeDotSegments:w4,normalizeIPv4:V1,normalizeIPv6:H1,stringArrayToHexStripped:Yg};});var e_=B((MW,Y1)=>{var N4=/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu,C4=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function G1(e){return typeof e.secure=="boolean"?e.secure:String(e.scheme).toLowerCase()==="wss"}function Z1(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function X1(e){let t=String(e.scheme).toLowerCase()==="https";return (e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function E4(e){return e.secure=G1(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function P4(e){if((e.port===(G1(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0;}return e.fragment=void 0,e}function T4(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(C4);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let a=`${n}:${t.nid||e.nid}`,o=ey[a];e.path=void 0,o&&(e=o.parse(e,t));}else e.error=e.error||"URN can not be parsed.";return e}function k4(e,t){let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),a=`${r}:${t.nid||n}`,o=ey[a];o&&(e=o.serialize(e,t));let i=e,s=e.nss;return i.path=`${n||t.nid}:${s}`,t.skipEscape=true,i}function R4(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!N4.test(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function O4(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var Q1={scheme:"http",domainHost:true,parse:Z1,serialize:X1},D4={scheme:"https",domainHost:Q1.domainHost,parse:Z1,serialize:X1},Jf={scheme:"ws",domainHost:true,parse:E4,serialize:P4},A4={scheme:"wss",domainHost:Jf.domainHost,parse:Jf.parse,serialize:Jf.serialize},$4={scheme:"urn",parse:T4,serialize:k4,skipNormalize:true},I4={scheme:"urn:uuid",parse:R4,serialize:O4,skipNormalize:true},ey={http:Q1,https:D4,ws:Jf,wss:A4,urn:$4,"urn:uuid":I4};Y1.exports=ey;});var r_=B((jW,Kf)=>{var{normalizeIPv6:F4,normalizeIPv4:M4,removeDotSegments:$u,recomposeAuthority:j4,normalizeComponentEncoding:Wf}=K1(),ty=e_();function L4(e,t){return typeof e=="string"?e=Ha(wo(e,t),t):typeof e=="object"&&(e=wo(Ha(e,t),t)),e}function B4(e,t,r){let n=Object.assign({scheme:"null"},r),a=t_(wo(e,n),wo(t,n),n,true);return Ha(a,{...n,skipEscape:true})}function t_(e,t,r,n){let a={};return n||(e=wo(Ha(e,r),r),t=wo(Ha(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=$u(t.path||""),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=$u(t.path||""),a.query=t.query):(t.path?(t.path.charAt(0)==="/"?a.path=$u(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path="/"+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path,a.path=$u(a.path)),a.query=t.query):(a.path=e.path,t.query!==void 0?a.query=t.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function z4(e,t,r){return typeof e=="string"?(e=unescape(e),e=Ha(Wf(wo(e,r),true),{...r,skipEscape:true})):typeof e=="object"&&(e=Ha(Wf(e,true),{...r,skipEscape:true})),typeof t=="string"?(t=unescape(t),t=Ha(Wf(wo(t,r),true),{...r,skipEscape:true})):typeof t=="object"&&(t=Ha(Wf(t,true),{...r,skipEscape:true})),e.toLowerCase()===t.toLowerCase()}function Ha(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),a=[],o=ty[(n.scheme||r.scheme||"").toLowerCase()];o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&a.push(r.scheme,":");let i=j4(r);if(i!==void 0&&(n.reference!=="suffix"&&a.push("//"),a.push(i),r.path&&r.path.charAt(0)!=="/"&&a.push("/")),r.path!==void 0){let s=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(s=$u(s)),i===void 0&&(s=s.replace(/^\/\//u,"/%2F")),a.push(s);}return r.query!==void 0&&a.push("?",r.query),r.fragment!==void 0&&a.push("#",r.fragment),a.join("")}var U4=Array.from({length:127},(e,t)=>/[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(t)));function q4(e){let t=0;for(let r=0,n=e.length;r<n;++r)if(t=e.charCodeAt(r),t>126||U4[t])return true;return false}var V4=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function wo(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},a=e.indexOf("%")!==-1,o=false;r.reference==="suffix"&&(e=(r.scheme?r.scheme+":":"")+"//"+e);let i=e.match(V4);if(i){if(n.scheme=i[1],n.userinfo=i[3],n.host=i[4],n.port=parseInt(i[5],10),n.path=i[6]||"",n.query=i[7],n.fragment=i[8],isNaN(n.port)&&(n.port=i[5]),n.host){let l=M4(n.host);if(l.isIPV4===false){let c=F4(l.host);n.host=c.host.toLowerCase(),o=c.isIPV6;}else n.host=l.host,o=true;}n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let s=ty[(r.scheme||n.scheme||"").toLowerCase()];if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&o===false&&q4(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase());}catch(l){n.error=n.error||"Host's domain name can not be converted to ASCII: "+l;}(!s||s&&!s.skipNormalize)&&(a&&n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),a&&n.host!==void 0&&(n.host=unescape(n.host)),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s&&s.parse&&s.parse(n,r);}else n.error=n.error||"URI can not be parsed.";return n}var ry={SCHEMES:ty,normalize:L4,resolve:B4,resolveComponents:t_,equal:z4,serialize:Ha,parse:wo};Kf.exports=ry;Kf.exports.default=ry;Kf.exports.fastUri=ry;});var a_=B(ny=>{Object.defineProperty(ny,"__esModule",{value:true});var n_=r_();n_.code='require("ajv/dist/runtime/uri").default';ny.default=n_;});var f_=B(Cr=>{Object.defineProperty(Cr,"__esModule",{value:true});Cr.CodeGen=Cr.Name=Cr.nil=Cr.stringify=Cr.str=Cr._=Cr.KeywordCxt=void 0;var H4=Ol();Object.defineProperty(Cr,"KeywordCxt",{enumerable:true,get:function(){return H4.KeywordCxt}});var Al=Ye();Object.defineProperty(Cr,"_",{enumerable:true,get:function(){return Al._}});Object.defineProperty(Cr,"str",{enumerable:true,get:function(){return Al.str}});Object.defineProperty(Cr,"stringify",{enumerable:true,get:function(){return Al.stringify}});Object.defineProperty(Cr,"nil",{enumerable:true,get:function(){return Al.nil}});Object.defineProperty(Cr,"Name",{enumerable:true,get:function(){return Al.Name}});Object.defineProperty(Cr,"CodeGen",{enumerable:true,get:function(){return Al.CodeGen}});var J4=qf(),c_=Au(),W4=Ag(),Iu=Hf(),K4=Ye(),Fu=Ru(),Gf=ku(),oy=pt(),o_=j1(),G4=a_(),u_=(e,t)=>new RegExp(e,t);u_.code="new RegExp";var Z4=["removeAdditional","useDefaults","coerceTypes"],X4=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Q4={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},Y4={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},i_=200;function e5(e){var t,r,n,a,o,i,s,l,c,u,d,g,f,h,m,p,v,y,x,w,_,E,C,P,T;let N=e.strict,S=(t=e.code)===null||t===void 0?void 0:t.optimize,b=S===true||S===void 0?1:S||0,k=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:u_,D=(a=e.uriResolver)!==null&&a!==void 0?a:G4.default;return {strictSchema:(i=(o=e.strictSchema)!==null&&o!==void 0?o:N)!==null&&i!==void 0?i:true,strictNumbers:(l=(s=e.strictNumbers)!==null&&s!==void 0?s:N)!==null&&l!==void 0?l:true,strictTypes:(u=(c=e.strictTypes)!==null&&c!==void 0?c:N)!==null&&u!==void 0?u:"log",strictTuples:(g=(d=e.strictTuples)!==null&&d!==void 0?d:N)!==null&&g!==void 0?g:"log",strictRequired:(h=(f=e.strictRequired)!==null&&f!==void 0?f:N)!==null&&h!==void 0?h:false,code:e.code?{...e.code,optimize:b,regExp:k}:{optimize:b,regExp:k},loopRequired:(m=e.loopRequired)!==null&&m!==void 0?m:i_,loopEnum:(p=e.loopEnum)!==null&&p!==void 0?p:i_,meta:(v=e.meta)!==null&&v!==void 0?v:true,messages:(y=e.messages)!==null&&y!==void 0?y:true,inlineRefs:(x=e.inlineRefs)!==null&&x!==void 0?x:true,schemaId:(w=e.schemaId)!==null&&w!==void 0?w:"$id",addUsedSchema:(_=e.addUsedSchema)!==null&&_!==void 0?_:true,validateSchema:(E=e.validateSchema)!==null&&E!==void 0?E:true,validateFormats:(C=e.validateFormats)!==null&&C!==void 0?C:true,unicodeRegExp:(P=e.unicodeRegExp)!==null&&P!==void 0?P:true,int32range:(T=e.int32range)!==null&&T!==void 0?T:true,uriResolver:D}}var Mu=class{constructor(t={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...e5(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new K4.ValueScope({scope:{},prefixes:X4,es5:r,lines:n}),this.logger=i5(t.logger);let a=t.validateFormats;t.validateFormats=false,this.RULES=(0, W4.getRules)(),s_.call(this,Q4,t,"NOT SUPPORTED"),s_.call(this,Y4,t,"DEPRECATED","warn"),this._metaOpts=a5.call(this),t.formats&&r5.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&n5.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),t5.call(this),t.validateFormats=a;}_addVocabularies(){this.addKeyword("$async");}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,a=o_;n==="id"&&(a={...o_},a.id=a.$id,delete a.$id),r&&t&&this.addMetaSchema(a,a[n],false);}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let a=n(r);return "$async"in n||(this.errors=n.errors),a}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return a.call(this,t,r);async function a(u,d){await o.call(this,u.$schema);let g=this._addSchema(u,d);return g.validate||i.call(this,g)}async function o(u){u&&!this.getSchema(u)&&await a.call(this,{$ref:u},true);}async function i(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof c_.default))throw d;return s.call(this,d),await l.call(this,d.missingSchema),i.call(this,u)}}function s({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function l(u){let d=await c.call(this,u);this.refs[u]||await o.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,r);}async function c(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u];}}}addSchema(t,r,n,a=this.opts.validateSchema){if(Array.isArray(t)){for(let i of t)this.addSchema(i,void 0,n,a);return this}let o;if(typeof t=="object"){let{schemaId:i}=this.opts;if(o=t[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return r=(0, Fu.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,a,true),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,true,n),this}validateSchema(t,r){if(typeof t=="boolean")return true;let n;if(n=t.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,true;let a=this.validate(n,t);if(!a&&r){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return a}getSchema(t){let r;for(;typeof(r=l_.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,a=new Iu.SchemaEnv({schema:{},schemaId:n});if(r=Iu.resolveSchema.call(this,a,t),!r)return;this.refs[t]=r;}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case "undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case "string":{let r=l_.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case "object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0, Fu.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(l5.call(this,n,r),!r)return (0, oy.eachItem)(n,o=>ay.call(this,o)),this;u5.call(this,r);let a={...r,type:(0, Gf.getJSONTypes)(r.type),schemaType:(0, Gf.getJSONTypes)(r.schemaType)};return (0, oy.eachItem)(n,a.type.length===0?o=>ay.call(this,o,a):o=>a.type.forEach(i=>ay.call(this,o,a,i))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let a=n.rules.findIndex(o=>o.keyword===t);a>=0&&n.rules.splice(a,1);}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return !t||t.length===0?"No errors":t.map(a=>`${n}${a.instancePath} ${a.message}`).reduce((a,o)=>a+r+o)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let a of r){let o=a.split("/").slice(1),i=t;for(let s of o)i=i[s];for(let s in n){let l=n[s];if(typeof l!="object")continue;let{$data:c}=l.definition,u=i[s];c&&u&&(i[s]=d_(u));}}return t}_removeAllSchemas(t,r){for(let n in t){let a=t[n];(!r||r.test(n))&&(typeof a=="string"?delete t[n]:a&&!a.meta&&(this._cache.delete(a.schema),delete t[n]));}}_addSchema(t,r,n,a=this.opts.validateSchema,o=this.opts.addUsedSchema){let i,{schemaId:s}=this.opts;if(typeof t=="object")i=t[s];else {if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(t);if(l!==void 0)return l;n=(0, Fu.normalizeId)(i||n);let c=Fu.getSchemaRefs.call(this,t,n);return l=new Iu.SchemaEnv({schema:t,schemaId:s,meta:r,baseId:n,localRefs:c}),this._cache.set(l.schema,l),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),a&&this.validateSchema(t,true),l}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):Iu.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{Iu.compileSchema.call(this,t);}finally{this.opts=r;}}};Mu.ValidationError=J4.default;Mu.MissingRefError=c_.default;Cr.default=Mu;function s_(e,t,r,n="error"){for(let a in e){let o=a;o in t&&this.logger[n](`${r}: option ${a}. ${e[o]}`);}}function l_(e){return e=(0, Fu.normalizeId)(e),this.schemas[e]||this.refs[e]}function t5(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t);}function r5(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t);}}function n5(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r);}}function a5(){let e={...this.opts};for(let t of Z4)delete e[t];return e}var o5={log(){},warn(){},error(){}};function i5(e){if(e===false)return o5;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var s5=/^[a-z_$][a-z0-9_$:-]*$/i;function l5(e,t){let{RULES:r}=this;if((0, oy.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!s5.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function ay(e,t,r){var n;let a=t?.post;if(r&&a)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=a?o.post:o.rules.find(({type:l})=>l===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[e]=true,!t)return;let s={keyword:e,definition:{...t,type:(0, Gf.getJSONTypes)(t.type),schemaType:(0, Gf.getJSONTypes)(t.schemaType)}};t.before?c5.call(this,i,s,t.before):i.rules.push(s),o.all[e]=s,(n=t.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l));}function c5(e,t,r){let n=e.rules.findIndex(a=>a.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`));}function u5(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=d_(t)),e.validateSchema=this.compile(t,true));}var d5={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function d_(e){return {anyOf:[e,d5]}}});var p_=B(iy=>{Object.defineProperty(iy,"__esModule",{value:true});var f5={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};iy.default=f5;});var y_=B(vs=>{Object.defineProperty(vs,"__esModule",{value:true});vs.callRef=vs.getValidate=void 0;var p5=Au(),m_=zn(),dn=Ye(),$l=Ua(),h_=Hf(),Zf=pt(),m5={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:a,schemaEnv:o,validateName:i,opts:s,self:l}=n,{root:c}=o;if((r==="#"||r==="#/")&&a===c.baseId)return d();let u=h_.resolveRef.call(l,c,a,r);if(u===void 0)throw new p5.default(n.opts.uriResolver,a,r);if(u instanceof h_.SchemaEnv)return g(u);return f(u);function d(){if(o===c)return Xf(e,i,o,o.$async);let h=t.scopeValue("root",{ref:c});return Xf(e,(0, dn._)`${h}.validate`,c,c.$async)}function g(h){let m=g_(e,h);Xf(e,m,h,h.$async);}function f(h){let m=t.scopeValue("schema",s.code.source===true?{ref:h,code:(0, dn.stringify)(h)}:{ref:h}),p=t.name("valid"),v=e.subschema({schema:h,dataTypes:[],schemaPath:dn.nil,topSchemaRef:m,errSchemaPath:r},p);e.mergeEvaluated(v),e.ok(p);}}};function g_(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0, dn._)`${r.scopeValue("wrapper",{ref:t})}.validate`}vs.getValidate=g_;function Xf(e,t,r,n){let{gen:a,it:o}=e,{allErrors:i,schemaEnv:s,opts:l}=o,c=l.passContext?$l.default.this:dn.nil;n?u():d();function u(){if(!s.$async)throw new Error("async schema referenced by sync schema");let h=a.let("valid");a.try(()=>{a.code((0, dn._)`await ${(0, m_.callValidateCode)(e,t,c)}`),f(t),i||a.assign(h,true);},m=>{a.if((0, dn._)`!(${m} instanceof ${o.ValidationError})`,()=>a.throw(m)),g(m),i||a.assign(h,false);}),e.ok(h);}function d(){e.result((0, m_.callValidateCode)(e,t,c),()=>f(t),()=>g(t));}function g(h){let m=(0, dn._)`${h}.errors`;a.assign($l.default.vErrors,(0, dn._)`${$l.default.vErrors} === null ? ${m} : ${$l.default.vErrors}.concat(${m})`),a.assign($l.default.errors,(0, dn._)`${$l.default.vErrors}.length`);}function f(h){var m;if(!o.opts.unevaluated)return;let p=(m=r?.validate)===null||m===void 0?void 0:m.evaluated;if(o.props!==true)if(p&&!p.dynamicProps)p.props!==void 0&&(o.props=Zf.mergeEvaluated.props(a,p.props,o.props));else {let v=a.var("props",(0, dn._)`${h}.evaluated.props`);o.props=Zf.mergeEvaluated.props(a,v,o.props,dn.Name);}if(o.items!==true)if(p&&!p.dynamicItems)p.items!==void 0&&(o.items=Zf.mergeEvaluated.items(a,p.items,o.items));else {let v=a.var("items",(0, dn._)`${h}.evaluated.items`);o.items=Zf.mergeEvaluated.items(a,v,o.items,dn.Name);}}}vs.callRef=Xf;vs.default=m5;});var v_=B(sy=>{Object.defineProperty(sy,"__esModule",{value:true});var h5=p_(),g5=y_(),y5=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",h5.default,g5.default];sy.default=y5;});var b_=B(ly=>{Object.defineProperty(ly,"__esModule",{value:true});var Qf=Ye(),fi=Qf.operators,Yf={maximum:{okStr:"<=",ok:fi.LTE,fail:fi.GT},minimum:{okStr:">=",ok:fi.GTE,fail:fi.LT},exclusiveMaximum:{okStr:"<",ok:fi.LT,fail:fi.GTE},exclusiveMinimum:{okStr:">",ok:fi.GT,fail:fi.LTE}},v5={message:({keyword:e,schemaCode:t})=>(0, Qf.str)`must be ${Yf[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0, Qf._)`{comparison: ${Yf[e].okStr}, limit: ${t}}`},b5={keyword:Object.keys(Yf),type:"number",schemaType:"number",$data:true,error:v5,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0, Qf._)`${r} ${Yf[t].fail} ${n} || isNaN(${r})`);}};ly.default=b5;});var x_=B(cy=>{Object.defineProperty(cy,"__esModule",{value:true});var ju=Ye(),x5={message:({schemaCode:e})=>(0, ju.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0, ju._)`{multipleOf: ${e}}`},w5={keyword:"multipleOf",type:"number",schemaType:"number",$data:true,error:x5,code(e){let{gen:t,data:r,schemaCode:n,it:a}=e,o=a.opts.multipleOfPrecision,i=t.let("res"),s=o?(0, ju._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0, ju._)`${i} !== parseInt(${i})`;e.fail$data((0, ju._)`(${n} === 0 || (${i} = ${r}/${n}, ${s}))`);}};cy.default=w5;});var __=B(uy=>{Object.defineProperty(uy,"__esModule",{value:true});function w_(e){let t=e.length,r=0,n=0,a;for(;n<t;)r++,a=e.charCodeAt(n++),a>=55296&&a<=56319&&n<t&&(a=e.charCodeAt(n),(a&64512)===56320&&n++);return r}uy.default=w_;w_.code='require("ajv/dist/runtime/ucs2length").default';});var S_=B(dy=>{Object.defineProperty(dy,"__esModule",{value:true});var bs=Ye(),_5=pt(),S5=__(),N5={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return (0, bs.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0, bs._)`{limit: ${e}}`},C5={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:true,error:N5,code(e){let{keyword:t,data:r,schemaCode:n,it:a}=e,o=t==="maxLength"?bs.operators.GT:bs.operators.LT,i=a.opts.unicode===false?(0, bs._)`${r}.length`:(0, bs._)`${(0, _5.useFunc)(e.gen,S5.default)}(${r})`;e.fail$data((0, bs._)`${i} ${o} ${n}`);}};dy.default=C5;});var N_=B(fy=>{Object.defineProperty(fy,"__esModule",{value:true});var E5=zn(),ep=Ye(),P5={message:({schemaCode:e})=>(0, ep.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0, ep._)`{pattern: ${e}}`},T5={keyword:"pattern",type:"string",schemaType:"string",$data:true,error:P5,code(e){let{data:t,$data:r,schema:n,schemaCode:a,it:o}=e,i=o.opts.unicodeRegExp?"u":"",s=r?(0, ep._)`(new RegExp(${a}, ${i}))`:(0, E5.usePattern)(e,n);e.fail$data((0, ep._)`!${s}.test(${t})`);}};fy.default=T5;});var C_=B(py=>{Object.defineProperty(py,"__esModule",{value:true});var Lu=Ye(),k5={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return (0, Lu.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0, Lu._)`{limit: ${e}}`},R5={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:true,error:k5,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxProperties"?Lu.operators.GT:Lu.operators.LT;e.fail$data((0, Lu._)`Object.keys(${r}).length ${a} ${n}`);}};py.default=R5;});var E_=B(my=>{Object.defineProperty(my,"__esModule",{value:true});var Bu=zn(),zu=Ye(),O5=pt(),D5={message:({params:{missingProperty:e}})=>(0, zu.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0, zu._)`{missingProperty: ${e}}`},A5={keyword:"required",type:"object",schemaType:"array",$data:true,error:D5,code(e){let{gen:t,schema:r,schemaCode:n,data:a,$data:o,it:i}=e,{opts:s}=i;if(!o&&r.length===0)return;let l=r.length>=s.loopRequired;if(i.allErrors?c():u(),s.strictRequired){let f=e.parentSchema.properties,{definedProperties:h}=e.it;for(let m of r)if(f?.[m]===void 0&&!h.has(m)){let p=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${m}" is not defined at "${p}" (strictRequired)`;(0, O5.checkStrictMode)(i,v,i.opts.strictRequired);}}function c(){if(l||o)e.block$data(zu.nil,d);else for(let f of r)(0, Bu.checkReportMissingProp)(e,f);}function u(){let f=t.let("missing");if(l||o){let h=t.let("valid",true);e.block$data(h,()=>g(f,h)),e.ok(h);}else t.if((0, Bu.checkMissingProp)(e,r,f)),(0, Bu.reportMissingProp)(e,f),t.else();}function d(){t.forOf("prop",n,f=>{e.setParams({missingProperty:f}),t.if((0, Bu.noPropertyInData)(t,a,f,s.ownProperties),()=>e.error());});}function g(f,h){e.setParams({missingProperty:f}),t.forOf(f,n,()=>{t.assign(h,(0, Bu.propertyInData)(t,a,f,s.ownProperties)),t.if((0, zu.not)(h),()=>{e.error(),t.break();});},zu.nil);}}};my.default=A5;});var P_=B(hy=>{Object.defineProperty(hy,"__esModule",{value:true});var Uu=Ye(),$5={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return (0, Uu.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0, Uu._)`{limit: ${e}}`},I5={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:true,error:$5,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxItems"?Uu.operators.GT:Uu.operators.LT;e.fail$data((0, Uu._)`${r}.length ${a} ${n}`);}};hy.default=I5;});var tp=B(gy=>{Object.defineProperty(gy,"__esModule",{value:true});var T_=zg();T_.code='require("ajv/dist/runtime/equal").default';gy.default=T_;});var k_=B(vy=>{Object.defineProperty(vy,"__esModule",{value:true});var yy=ku(),Er=Ye(),F5=pt(),M5=tp(),j5={message:({params:{i:e,j:t}})=>(0, Er.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0, Er._)`{i: ${e}, j: ${t}}`},L5={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:true,error:j5,code(e){let{gen:t,data:r,$data:n,schema:a,parentSchema:o,schemaCode:i,it:s}=e;if(!n&&!a)return;let l=t.let("valid"),c=o.items?(0, yy.getSchemaTypes)(o.items):[];e.block$data(l,u,(0, Er._)`${i} === false`),e.ok(l);function u(){let h=t.let("i",(0, Er._)`${r}.length`),m=t.let("j");e.setParams({i:h,j:m}),t.assign(l,true),t.if((0, Er._)`${h} > 1`,()=>(d()?g:f)(h,m));}function d(){return c.length>0&&!c.some(h=>h==="object"||h==="array")}function g(h,m){let p=t.name("item"),v=(0, yy.checkDataTypes)(c,p,s.opts.strictNumbers,yy.DataType.Wrong),y=t.const("indices",(0, Er._)`{}`);t.for((0, Er._)`;${h}--;`,()=>{t.let(p,(0, Er._)`${r}[${h}]`),t.if(v,(0, Er._)`continue`),c.length>1&&t.if((0, Er._)`typeof ${p} == "string"`,(0, Er._)`${p} += "_"`),t.if((0, Er._)`typeof ${y}[${p}] == "number"`,()=>{t.assign(m,(0, Er._)`${y}[${p}]`),e.error(),t.assign(l,false).break();}).code((0, Er._)`${y}[${p}] = ${h}`);});}function f(h,m){let p=(0, F5.useFunc)(t,M5.default),v=t.name("outer");t.label(v).for((0, Er._)`;${h}--;`,()=>t.for((0, Er._)`${m} = ${h}; ${m}--;`,()=>t.if((0, Er._)`${p}(${r}[${h}], ${r}[${m}])`,()=>{e.error(),t.assign(l,false).break(v);})));}}};vy.default=L5;});var R_=B(xy=>{Object.defineProperty(xy,"__esModule",{value:true});var by=Ye(),B5=pt(),z5=tp(),U5={message:"must be equal to constant",params:({schemaCode:e})=>(0, by._)`{allowedValue: ${e}}`},q5={keyword:"const",$data:true,error:U5,code(e){let{gen:t,data:r,$data:n,schemaCode:a,schema:o}=e;n||o&&typeof o=="object"?e.fail$data((0, by._)`!${(0, B5.useFunc)(t,z5.default)}(${r}, ${a})`):e.fail((0, by._)`${o} !== ${r}`);}};xy.default=q5;});var O_=B(wy=>{Object.defineProperty(wy,"__esModule",{value:true});var qu=Ye(),V5=pt(),H5=tp(),J5={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0, qu._)`{allowedValues: ${e}}`},W5={keyword:"enum",schemaType:"array",$data:true,error:J5,code(e){let{gen:t,data:r,$data:n,schema:a,schemaCode:o,it:i}=e;if(!n&&a.length===0)throw new Error("enum must have non-empty array");let s=a.length>=i.opts.loopEnum,l,c=()=>l??(l=(0, V5.useFunc)(t,H5.default)),u;if(s||n)u=t.let("valid"),e.block$data(u,d);else {if(!Array.isArray(a))throw new Error("ajv implementation error");let f=t.const("vSchema",o);u=(0, qu.or)(...a.map((h,m)=>g(f,m)));}e.pass(u);function d(){t.assign(u,false),t.forOf("v",o,f=>t.if((0, qu._)`${c()}(${r}, ${f})`,()=>t.assign(u,true).break()));}function g(f,h){let m=a[h];return typeof m=="object"&&m!==null?(0, qu._)`${c()}(${r}, ${f}[${h}])`:(0, qu._)`${r} === ${m}`}}};wy.default=W5;});var D_=B(_y=>{Object.defineProperty(_y,"__esModule",{value:true});var K5=b_(),G5=x_(),Z5=S_(),X5=N_(),Q5=C_(),Y5=E_(),eI=P_(),tI=k_(),rI=R_(),nI=O_(),aI=[K5.default,G5.default,Z5.default,X5.default,Q5.default,Y5.default,eI.default,tI.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},rI.default,nI.default];_y.default=aI;});var Ny=B(Vu=>{Object.defineProperty(Vu,"__esModule",{value:true});Vu.validateAdditionalItems=void 0;var xs=Ye(),Sy=pt(),oI={message:({params:{len:e}})=>(0, xs.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0, xs._)`{limit: ${e}}`},iI={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:oI,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0, Sy.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}A_(e,n);}};function A_(e,t){let{gen:r,schema:n,data:a,keyword:o,it:i}=e;i.items=true;let s=r.const("len",(0, xs._)`${a}.length`);if(n===false)e.setParams({len:t.length}),e.pass((0, xs._)`${s} <= ${t.length}`);else if(typeof n=="object"&&!(0, Sy.alwaysValidSchema)(i,n)){let c=r.var("valid",(0, xs._)`${s} <= ${t.length}`);r.if((0, xs.not)(c),()=>l(c)),e.ok(c);}function l(c){r.forRange("i",t.length,s,u=>{e.subschema({keyword:o,dataProp:u,dataPropType:Sy.Type.Num},c),i.allErrors||r.if((0, xs.not)(c),()=>r.break());});}}Vu.validateAdditionalItems=A_;Vu.default=iI;});var Cy=B(Hu=>{Object.defineProperty(Hu,"__esModule",{value:true});Hu.validateTuple=void 0;var $_=Ye(),rp=pt(),sI=zn(),lI={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return I_(e,"additionalItems",t);r.items=true,!(0, rp.alwaysValidSchema)(r,t)&&e.ok((0, sI.validateArray)(e));}};function I_(e,t,r=e.schema){let{gen:n,parentSchema:a,data:o,keyword:i,it:s}=e;u(a),s.opts.unevaluated&&r.length&&s.items!==true&&(s.items=rp.mergeEvaluated.items(n,r.length,s.items));let l=n.name("valid"),c=n.const("len",(0, $_._)`${o}.length`);r.forEach((d,g)=>{(0, rp.alwaysValidSchema)(s,d)||(n.if((0, $_._)`${c} > ${g}`,()=>e.subschema({keyword:i,schemaProp:g,dataProp:g},l)),e.ok(l));});function u(d){let{opts:g,errSchemaPath:f}=s,h=r.length,m=h===d.minItems&&(h===d.maxItems||d[t]===false);if(g.strictTuples&&!m){let p=`"${i}" is ${h}-tuple, but minItems or maxItems/${t} are not specified or different at path "${f}"`;(0, rp.checkStrictMode)(s,p,g.strictTuples);}}}Hu.validateTuple=I_;Hu.default=lI;});var F_=B(Ey=>{Object.defineProperty(Ey,"__esModule",{value:true});var cI=Cy(),uI={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0, cI.validateTuple)(e,"items")};Ey.default=uI;});var j_=B(Py=>{Object.defineProperty(Py,"__esModule",{value:true});var M_=Ye(),dI=pt(),fI=zn(),pI=Ny(),mI={message:({params:{len:e}})=>(0, M_.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0, M_._)`{limit: ${e}}`},hI={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:mI,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:a}=r;n.items=true,!(0, dI.alwaysValidSchema)(n,t)&&(a?(0, pI.validateAdditionalItems)(e,a):e.ok((0, fI.validateArray)(e)));}};Py.default=hI;});var L_=B(Ty=>{Object.defineProperty(Ty,"__esModule",{value:true});var qn=Ye(),np=pt(),gI={message:({params:{min:e,max:t}})=>t===void 0?(0, qn.str)`must contain at least ${e} valid item(s)`:(0, qn.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0, qn._)`{minContains: ${e}}`:(0, qn._)`{minContains: ${e}, maxContains: ${t}}`},yI={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:true,error:gI,code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:o}=e,i,s,{minContains:l,maxContains:c}=n;o.opts.next?(i=l===void 0?1:l,s=c):i=1;let u=t.const("len",(0, qn._)`${a}.length`);if(e.setParams({min:i,max:s}),s===void 0&&i===0){(0, np.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(s!==void 0&&i>s){(0, np.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0, np.alwaysValidSchema)(o,r)){let m=(0, qn._)`${u} >= ${i}`;s!==void 0&&(m=(0, qn._)`${m} && ${u} <= ${s}`),e.pass(m);return}o.items=true;let d=t.name("valid");s===void 0&&i===1?f(d,()=>t.if(d,()=>t.break())):i===0?(t.let(d,true),s!==void 0&&t.if((0, qn._)`${a}.length > 0`,g)):(t.let(d,false),g()),e.result(d,()=>e.reset());function g(){let m=t.name("_valid"),p=t.let("count",0);f(m,()=>t.if(m,()=>h(p)));}function f(m,p){t.forRange("i",0,u,v=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:np.Type.Num,compositeRule:true},m),p();});}function h(m){t.code((0, qn._)`${m}++`),s===void 0?t.if((0, qn._)`${m} >= ${i}`,()=>t.assign(d,true).break()):(t.if((0, qn._)`${m} > ${s}`,()=>t.assign(d,false).break()),i===1?t.assign(d,true):t.if((0, qn._)`${m} >= ${i}`,()=>t.assign(d,true)));}}};Ty.default=yI;});var U_=B(Ja=>{Object.defineProperty(Ja,"__esModule",{value:true});Ja.validateSchemaDeps=Ja.validatePropertyDeps=Ja.error=void 0;var ky=Ye(),vI=pt(),Ju=zn();Ja.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return (0, ky.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0, ky._)`{property: ${e},
6
6
  missingProperty: ${n},
7
7
  depsCount: ${t},
8
- deps: ${r}}`};var E5={keyword:"dependencies",type:"object",schemaType:"object",error:Fo.error,code(e){let[t,r]=P5(e);r_(e,t),n_(e,r);}};function P5({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let o=Array.isArray(e[n])?t:r;o[n]=e[n];}return [t,r]}function r_(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let a=r.let("missing");for(let i in t){let s=t[i];if(s.length===0)continue;let l=(0, yu.propertyInData)(r,n,i,o.opts.ownProperties);e.setParams({property:i,depsCount:s.length,deps:s.join(", ")}),o.allErrors?r.if(l,()=>{for(let c of s)(0, yu.checkReportMissingProp)(e,c);}):(r.if((0, sy._)`${l} && (${(0, yu.checkMissingProp)(e,s,a)})`),(0, yu.reportMissingProp)(e,a),r.else());}}Fo.validatePropertyDeps=r_;function n_(e,t=e.schema){let{gen:r,data:n,keyword:o,it:a}=e,i=r.name("valid");for(let s in t)(0, C5.alwaysValidSchema)(a,t[s])||(r.if((0, yu.propertyInData)(r,n,s,a.opts.ownProperties),()=>{let l=e.subschema({keyword:o,schemaProp:s},i);e.mergeValidEvaluated(l,i);},()=>r.var(i,true)),e.ok(i));}Fo.validateSchemaDeps=n_;Fo.default=E5;});var i_=M(ly=>{Object.defineProperty(ly,"__esModule",{value:true});var a_=Ve(),T5=dt(),k5={message:"property name must be valid",params:({params:e})=>(0, a_._)`{propertyName: ${e.propertyName}}`},R5={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:k5,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0, T5.alwaysValidSchema)(o,r))return;let a=t.name("valid");t.forIn("key",n,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:true},a),t.if((0, a_.not)(a),()=>{e.error(true),o.allErrors||t.break();});}),e.ok(a);}};ly.default=R5;});var uy=M(cy=>{Object.defineProperty(cy,"__esModule",{value:true});var Df=Cn(),ro=Ve(),O5=Do(),Af=dt(),D5={message:"must NOT have additional properties",params:({params:e})=>(0, ro._)`{additionalProperty: ${e.additionalProperty}}`},A5={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:true,trackErrors:true,error:D5,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:a,it:i}=e;if(!a)throw new Error("ajv implementation error");let{allErrors:s,opts:l}=i;if(i.props=true,l.removeAdditional!=="all"&&(0, Af.alwaysValidSchema)(i,r))return;let c=(0, Df.allSchemaProperties)(n.properties),u=(0, Df.allSchemaProperties)(n.patternProperties);d(),e.ok((0, ro._)`${a} === ${O5.default.errors}`);function d(){t.forIn("key",o,f=>{!c.length&&!u.length?y(f):t.if(m(f),()=>y(f));});}function m(f){let x;if(c.length>8){let g=(0, Af.schemaRefOrVal)(i,n.properties,"properties");x=(0, Df.isOwnProperty)(t,g,f);}else c.length?x=(0, ro.or)(...c.map(g=>(0, ro._)`${f} === ${g}`)):x=ro.nil;return u.length&&(x=(0, ro.or)(x,...u.map(g=>(0, ro._)`${(0, Df.usePattern)(e,g)}.test(${f})`))),(0, ro.not)(x)}function h(f){t.code((0, ro._)`delete ${o}[${f}]`);}function y(f){if(l.removeAdditional==="all"||l.removeAdditional&&r===false){h(f);return}if(r===false){e.setParams({additionalProperty:f}),e.error(),s||t.break();return}if(typeof r=="object"&&!(0, Af.alwaysValidSchema)(i,r)){let x=t.name("valid");l.removeAdditional==="failing"?(p(f,x,false),t.if((0, ro.not)(x),()=>{e.reset(),h(f);})):(p(f,x),s||t.if((0, ro.not)(x),()=>t.break()));}}function p(f,x,g){let v={keyword:"additionalProperties",dataProp:f,dataPropType:Af.Type.Str};g===false&&Object.assign(v,{compositeRule:true,createErrors:false,allErrors:false}),e.subschema(v,x);}}};cy.default=A5;});var c_=M(fy=>{Object.defineProperty(fy,"__esModule",{value:true});var $5=ol(),s_=Cn(),dy=dt(),l_=uy(),I5={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:a}=e;a.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&l_.default.code(new $5.KeywordCxt(a,l_.default,"additionalProperties"));let i=(0, s_.allSchemaProperties)(r);for(let d of i)a.definedProperties.add(d);a.opts.unevaluated&&i.length&&a.props!==true&&(a.props=dy.mergeEvaluated.props(t,(0, dy.toHash)(i),a.props));let s=i.filter(d=>!(0, dy.alwaysValidSchema)(a,r[d]));if(s.length===0)return;let l=t.name("valid");for(let d of s)c(d)?u(d):(t.if((0, s_.propertyInData)(t,o,d,a.opts.ownProperties)),u(d),a.allErrors||t.else().var(l,true),t.endIf()),e.it.definedProperties.add(d),e.ok(l);function c(d){return a.opts.useDefaults&&!a.compositeRule&&r[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},l);}}};fy.default=I5;});var p_=M(py=>{Object.defineProperty(py,"__esModule",{value:true});var u_=Cn(),$f=Ve(),d_=dt(),f_=dt(),F5={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:a}=e,{opts:i}=a,s=(0, u_.allSchemaProperties)(r),l=s.filter(p=>(0, d_.alwaysValidSchema)(a,r[p]));if(s.length===0||l.length===s.length&&(!a.opts.unevaluated||a.props===true))return;let c=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=t.name("valid");a.props!==true&&!(a.props instanceof $f.Name)&&(a.props=(0, f_.evaluatedPropsToName)(t,a.props));let{props:d}=a;m();function m(){for(let p of s)c&&h(p),a.allErrors?y(p):(t.var(u,true),y(p),t.if(u));}function h(p){for(let f in c)new RegExp(p).test(f)&&(0, d_.checkStrictMode)(a,`property ${f} matches pattern ${p} (use allowMatchingProperties)`);}function y(p){t.forIn("key",n,f=>{t.if((0, $f._)`${(0, u_.usePattern)(e,p)}.test(${f})`,()=>{let x=l.includes(p);x||e.subschema({keyword:"patternProperties",schemaProp:p,dataProp:f,dataPropType:f_.Type.Str},u),a.opts.unevaluated&&d!==true?t.assign((0, $f._)`${d}[${f}]`,true):!x&&!a.allErrors&&t.if((0, $f.not)(u),()=>t.break());});});}}};py.default=F5;});var m_=M(my=>{Object.defineProperty(my,"__esModule",{value:true});var M5=dt(),j5={keyword:"not",schemaType:["object","boolean"],trackErrors:true,code(e){let{gen:t,schema:r,it:n}=e;if((0, M5.alwaysValidSchema)(n,r)){e.fail();return}let o=t.name("valid");e.subschema({keyword:"not",compositeRule:true,createErrors:false,allErrors:false},o),e.failResult(o,()=>e.reset(),()=>e.error());},error:{message:"must NOT be valid"}};my.default=j5;});var h_=M(hy=>{Object.defineProperty(hy,"__esModule",{value:true});var L5=Cn(),B5={keyword:"anyOf",schemaType:"array",trackErrors:true,code:L5.validateUnion,error:{message:"must match a schema in anyOf"}};hy.default=B5;});var g_=M(gy=>{Object.defineProperty(gy,"__esModule",{value:true});var If=Ve(),z5=dt(),U5={message:"must match exactly one schema in oneOf",params:({params:e})=>(0, If._)`{passingSchemas: ${e.passing}}`},q5={keyword:"oneOf",schemaType:"array",trackErrors:true,error:U5,code(e){let{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let a=r,i=t.let("valid",false),s=t.let("passing",null),l=t.name("_valid");e.setParams({passing:s}),t.block(c),e.result(i,()=>e.reset(),()=>e.error(true));function c(){a.forEach((u,d)=>{let m;(0, z5.alwaysValidSchema)(o,u)?t.var(l,true):m=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:true},l),d>0&&t.if((0, If._)`${l} && ${i}`).assign(i,false).assign(s,(0, If._)`[${s}, ${d}]`).else(),t.if(l,()=>{t.assign(i,true),t.assign(s,d),m&&e.mergeEvaluated(m,If.Name);});});}}};gy.default=q5;});var y_=M(yy=>{Object.defineProperty(yy,"__esModule",{value:true});var V5=dt(),H5={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=t.name("valid");r.forEach((a,i)=>{if((0, V5.alwaysValidSchema)(n,a))return;let s=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(s);});}};yy.default=H5;});var x_=M(vy=>{Object.defineProperty(vy,"__esModule",{value:true});var Ff=Ve(),b_=dt(),J5={message:({params:e})=>(0, Ff.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0, Ff._)`{failingKeyword: ${e.ifClause}}`},W5={keyword:"if",schemaType:["object","boolean"],trackErrors:true,error:J5,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0, b_.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=v_(n,"then"),a=v_(n,"else");if(!o&&!a)return;let i=t.let("valid",true),s=t.name("_valid");if(l(),e.reset(),o&&a){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(s,c("then",u),c("else",u));}else o?t.if(s,c("then")):t.if((0, Ff.not)(s),c("else"));e.pass(i,()=>e.error(true));function l(){let u=e.subschema({keyword:"if",compositeRule:true,createErrors:false,allErrors:false},s);e.mergeEvaluated(u);}function c(u,d){return ()=>{let m=e.subschema({keyword:u},s);t.assign(i,s),e.mergeValidEvaluated(m,i),d?t.assign(d,(0, Ff._)`${u}`):e.setParams({ifClause:u});}}}};function v_(e,t){let r=e.schema[t];return r!==void 0&&!(0, b_.alwaysValidSchema)(e,r)}vy.default=W5;});var w_=M(by=>{Object.defineProperty(by,"__esModule",{value:true});var K5=dt(),G5={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0, K5.checkStrictMode)(r,`"${e}" without "if" is ignored`);}};by.default=G5;});var __=M(xy=>{Object.defineProperty(xy,"__esModule",{value:true});var Z5=ry(),X5=Q1(),Q5=ny(),Y5=e_(),eI=t_(),tI=o_(),rI=i_(),nI=uy(),oI=c_(),aI=p_(),iI=m_(),sI=h_(),lI=g_(),cI=y_(),uI=x_(),dI=w_();function fI(e=false){let t=[iI.default,sI.default,lI.default,cI.default,uI.default,dI.default,rI.default,nI.default,tI.default,oI.default,aI.default];return e?t.push(X5.default,Y5.default):t.push(Z5.default,Q5.default),t.push(eI.default),t}xy.default=fI;});var S_=M(wy=>{Object.defineProperty(wy,"__esModule",{value:true});var Qt=Ve(),pI={message:({schemaCode:e})=>(0, Qt.str)`must match format "${e}"`,params:({schemaCode:e})=>(0, Qt._)`{format: ${e}}`},mI={keyword:"format",type:["number","string"],schemaType:"string",$data:true,error:pI,code(e,t){let{gen:r,data:n,$data:o,schema:a,schemaCode:i,it:s}=e,{opts:l,errSchemaPath:c,schemaEnv:u,self:d}=s;if(!l.validateFormats)return;o?m():h();function m(){let y=r.scopeValue("formats",{ref:d.formats,code:l.code.formats}),p=r.const("fDef",(0, Qt._)`${y}[${i}]`),f=r.let("fType"),x=r.let("format");r.if((0, Qt._)`typeof ${p} == "object" && !(${p} instanceof RegExp)`,()=>r.assign(f,(0, Qt._)`${p}.type || "string"`).assign(x,(0, Qt._)`${p}.validate`),()=>r.assign(f,(0, Qt._)`"string"`).assign(x,p)),e.fail$data((0, Qt.or)(g(),v()));function g(){return l.strictSchema===false?Qt.nil:(0, Qt._)`${i} && !${x}`}function v(){let w=u.$async?(0, Qt._)`(${p}.async ? await ${x}(${n}) : ${x}(${n}))`:(0, Qt._)`${x}(${n})`,N=(0, Qt._)`(typeof ${x} == "function" ? ${w} : ${x}.test(${n}))`;return (0, Qt._)`${x} && ${x} !== true && ${f} === ${t} && !${N}`}}function h(){let y=d.formats[a];if(!y){g();return}if(y===true)return;let[p,f,x]=v(y);p===t&&e.pass(w());function g(){if(l.strictSchema===false){d.logger.warn(N());return}throw new Error(N());function N(){return `unknown format "${a}" ignored in schema at path "${c}"`}}function v(N){let S=N instanceof RegExp?(0, Qt.regexpCode)(N):l.code.formats?(0, Qt._)`${l.code.formats}${(0, Qt.getProperty)(a)}`:void 0,_=r.scopeValue("formats",{key:a,ref:N,code:S});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0, Qt._)`${_}.validate`]:["string",N,_]}function w(){if(typeof y=="object"&&!(y instanceof RegExp)&&y.async){if(!u.$async)throw new Error("async format in sync schema");return (0, Qt._)`await ${x}(${n})`}return typeof f=="function"?(0, Qt._)`${x}(${n})`:(0, Qt._)`${x}.test(${n})`}}}};wy.default=mI;});var N_=M(_y=>{Object.defineProperty(_y,"__esModule",{value:true});var hI=S_(),gI=[hI.default];_y.default=gI;});var C_=M(ll=>{Object.defineProperty(ll,"__esModule",{value:true});ll.contentVocabulary=ll.metadataVocabulary=void 0;ll.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ll.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];});var P_=M(Sy=>{Object.defineProperty(Sy,"__esModule",{value:true});var yI=$1(),vI=K1(),bI=__(),xI=N_(),E_=C_(),wI=[yI.default,vI.default,(0, bI.default)(),xI.default,E_.metadataVocabulary,E_.contentVocabulary];Sy.default=wI;});var k_=M(Mf=>{Object.defineProperty(Mf,"__esModule",{value:true});Mf.DiscrError=void 0;var T_;(function(e){e.Tag="tag",e.Mapping="mapping";})(T_||(Mf.DiscrError=T_={}));});var O_=M(Cy=>{Object.defineProperty(Cy,"__esModule",{value:true});var cl=Ve(),Ny=k_(),R_=vf(),_I=ou(),SI=dt(),NI={message:({params:{discrError:e,tagName:t}})=>e===Ny.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0, cl._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},CI={keyword:"discriminator",type:"object",schemaType:"object",error:NI,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:a}=e,{oneOf:i}=o;if(!a.opts.discriminator)throw new Error("discriminator: requires discriminator option");let s=n.propertyName;if(typeof s!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let l=t.let("valid",false),c=t.const("tag",(0, cl._)`${r}${(0, cl.getProperty)(s)}`);t.if((0, cl._)`typeof ${c} == "string"`,()=>u(),()=>e.error(false,{discrError:Ny.DiscrError.Tag,tag:c,tagName:s})),e.ok(l);function u(){let h=m();t.if(false);for(let y in h)t.elseIf((0, cl._)`${c} === ${y}`),t.assign(l,d(h[y]));t.else(),e.error(false,{discrError:Ny.DiscrError.Mapping,tag:c,tagName:s}),t.endIf();}function d(h){let y=t.name("valid"),p=e.subschema({keyword:"oneOf",schemaProp:h},y);return e.mergeEvaluated(p,cl.Name),y}function m(){var h;let y={},p=x(o),f=true;for(let w=0;w<i.length;w++){let N=i[w];if(N?.$ref&&!(0, SI.schemaHasRulesButRef)(N,a.self.RULES)){let _=N.$ref;if(N=R_.resolveRef.call(a.self,a.schemaEnv.root,a.baseId,_),N instanceof R_.SchemaEnv&&(N=N.schema),N===void 0)throw new _I.default(a.opts.uriResolver,a.baseId,_)}let S=(h=N?.properties)===null||h===void 0?void 0:h[s];if(typeof S!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);f=f&&(p||x(N)),g(S,w);}if(!f)throw new Error(`discriminator: "${s}" must be required`);return y;function x({required:w}){return Array.isArray(w)&&w.includes(s)}function g(w,N){if(w.const)v(w.const,N);else if(w.enum)for(let S of w.enum)v(S,N);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function v(w,N){if(typeof w!="string"||w in y)throw new Error(`discriminator: "${s}" values must be unique strings`);y[w]=N;}}}};Cy.default=CI;});var Ey=M((EW,EI)=>{EI.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:true,readOnly:{type:"boolean",default:false},examples:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:true},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:true,enum:{type:"array",items:true,minItems:1,uniqueItems:true},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:true}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:true};});var Lf=M((At,Py)=>{Object.defineProperty(At,"__esModule",{value:true});At.MissingRefError=At.ValidationError=At.CodeGen=At.Name=At.nil=At.stringify=At.str=At._=At.KeywordCxt=At.Ajv=void 0;var PI=T1(),TI=P_(),kI=O_(),D_=Ey(),RI=["/properties"],jf="http://json-schema.org/draft-07/schema",ul=class extends PI.default{_addVocabularies(){super._addVocabularies(),TI.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(kI.default);}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(D_,RI):D_;this.addMetaSchema(t,jf,false),this.refs["http://json-schema.org/schema"]=jf;}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(jf)?jf:void 0)}};At.Ajv=ul;Py.exports=At=ul;Py.exports.Ajv=ul;Object.defineProperty(At,"__esModule",{value:true});At.default=ul;var OI=ol();Object.defineProperty(At,"KeywordCxt",{enumerable:true,get:function(){return OI.KeywordCxt}});var dl=Ve();Object.defineProperty(At,"_",{enumerable:true,get:function(){return dl._}});Object.defineProperty(At,"str",{enumerable:true,get:function(){return dl.str}});Object.defineProperty(At,"stringify",{enumerable:true,get:function(){return dl.stringify}});Object.defineProperty(At,"nil",{enumerable:true,get:function(){return dl.nil}});Object.defineProperty(At,"Name",{enumerable:true,get:function(){return dl.Name}});Object.defineProperty(At,"CodeGen",{enumerable:true,get:function(){return dl.CodeGen}});var DI=gf();Object.defineProperty(At,"ValidationError",{enumerable:true,get:function(){return DI.default}});var AI=ou();Object.defineProperty(At,"MissingRefError",{enumerable:true,get:function(){return AI.default}});});var j_=M(Mo=>{Object.defineProperty(Mo,"__esModule",{value:true});Mo.formatNames=Mo.fastFormats=Mo.fullFormats=void 0;function fl(e,t){return {validate:e,compare:t}}Mo.fullFormats={date:fl(I_,Ry),time:fl(F_,Oy),"date-time":fl(MI,M_),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:BI,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:WI,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:zI,int32:{type:"number",validate:VI},int64:{type:"number",validate:HI},float:{type:"number",validate:$_},double:{type:"number",validate:$_},password:true,binary:true};Mo.fastFormats={...Mo.fullFormats,date:fl(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Ry),time:fl(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Oy),"date-time":fl(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,M_),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Mo.formatNames=Object.keys(Mo.fullFormats);function $I(e){return e%4===0&&(e%100!==0||e%400===0)}var II=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,FI=[0,31,28,31,30,31,30,31,31,30,31,30,31];function I_(e){let t=II.exec(e);if(!t)return false;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&$I(r)?29:FI[n])}function Ry(e,t){if(e&&t)return e>t?1:e<t?-1:0}var Ty=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;function F_(e,t){let r=Ty.exec(e);if(!r)return false;let n=+r[1],o=+r[2],a=+r[3],i=r[5];return (n<=23&&o<=59&&a<=59||n===23&&o===59&&a===60)&&(!t||i!=="")}function Oy(e,t){if(!(e&&t))return;let r=Ty.exec(e),n=Ty.exec(t);if(r&&n)return e=r[1]+r[2]+r[3]+(r[4]||""),t=n[1]+n[2]+n[3]+(n[4]||""),e>t?1:e<t?-1:0}var ky=/t|\s/i;function MI(e){let t=e.split(ky);return t.length===2&&I_(t[0])&&F_(t[1],true)}function M_(e,t){if(!(e&&t))return;let[r,n]=e.split(ky),[o,a]=t.split(ky),i=Ry(r,o);if(i!==void 0)return i||Oy(n,a)}var jI=/\/|:/,LI=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function BI(e){return jI.test(e)&&LI.test(e)}var A_=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function zI(e){return A_.lastIndex=0,A_.test(e)}var UI=-2147483648,qI=2**31-1;function VI(e){return Number.isInteger(e)&&e<=qI&&e>=UI}function HI(e){return Number.isInteger(e)}function $_(){return true}var JI=/[^\\]\\Z/;function WI(e){if(JI.test(e))return false;try{return new RegExp(e),!0}catch{return false}}});var L_=M(pl=>{Object.defineProperty(pl,"__esModule",{value:true});pl.formatLimitDefinition=void 0;var KI=Lf(),no=Ve(),Xa=no.operators,Bf={formatMaximum:{okStr:"<=",ok:Xa.LTE,fail:Xa.GT},formatMinimum:{okStr:">=",ok:Xa.GTE,fail:Xa.LT},formatExclusiveMaximum:{okStr:"<",ok:Xa.LT,fail:Xa.GTE},formatExclusiveMinimum:{okStr:">",ok:Xa.GT,fail:Xa.LTE}},GI={message:({keyword:e,schemaCode:t})=>no.str`should be ${Bf[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>no._`{comparison: ${Bf[e].okStr}, limit: ${t}}`};pl.formatLimitDefinition={keyword:Object.keys(Bf),type:"string",schemaType:"string",$data:true,error:GI,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:a}=e,{opts:i,self:s}=a;if(!i.validateFormats)return;let l=new KI.KeywordCxt(a,s.RULES.all.format.definition,"format");l.$data?c():u();function c(){let m=t.scopeValue("formats",{ref:s.formats,code:i.code.formats}),h=t.const("fmt",no._`${m}[${l.schemaCode}]`);e.fail$data(no.or(no._`typeof ${h} != "object"`,no._`${h} instanceof RegExp`,no._`typeof ${h}.compare != "function"`,d(h)));}function u(){let m=l.schema,h=s.formats[m];if(!h||h===true)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let y=t.scopeValue("formats",{key:m,ref:h,code:i.code.formats?no._`${i.code.formats}${no.getProperty(m)}`:void 0});e.fail$data(d(y));}function d(m){return no._`${m}.compare(${r}, ${n}) ${Bf[o].fail} 0`}},dependencies:["format"]};var ZI=e=>(e.addKeyword(pl.formatLimitDefinition),e);pl.default=ZI;});var q_=M((vu,U_)=>{Object.defineProperty(vu,"__esModule",{value:true});var ml=j_(),XI=L_(),Dy=Ve(),B_=new Dy.Name("fullFormats"),QI=new Dy.Name("fastFormats"),Ay=(e,t={keywords:true})=>{if(Array.isArray(t))return z_(e,t,ml.fullFormats,B_),e;let[r,n]=t.mode==="fast"?[ml.fastFormats,QI]:[ml.fullFormats,B_],o=t.formats||ml.formatNames;return z_(e,o,r,n),t.keywords&&XI.default(e),e};Ay.get=(e,t="full")=>{let n=(t==="fast"?ml.fastFormats:ml.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function z_(e,t,r,n){var o,a;(o=(a=e.opts.code).formats)!==null&&o!==void 0||(a.formats=Dy._`require("ajv-formats/dist/formats").${n}`);for(let i of t)e.addFormat(i,r[i]);}U_.exports=vu=Ay;Object.defineProperty(vu,"__esModule",{value:true});vu.default=Ay;});var W_=M((Iy,Fy)=>{Object.defineProperty(Iy,"__esModule",{value:true});var te=Lf(),Qa=Ve(),V_=Gs(),YI=ol(),bu=Qs(),oo=Do(),zf="errorMessage",Ya=new te.Name("emUsed"),H_={required:"missingProperty",dependencies:"property",dependentRequired:"property"},J_=/\$\{[^}]+\}/,eF=/\$\{([^}]+)\}/g,tF=/^""\s*\+\s*|\s*\+\s*""$/g;function rF(e){return {keyword:zf,schemaType:["string","object"],post:true,code(t){let{gen:r,data:n,schema:o,schemaValue:a,it:i}=t;if(i.createErrors===false)return;let s=o,l=Qa.strConcat(oo.default.instancePath,i.errorPath);r.if(te._`${oo.default.errors} > 0`,()=>{if(typeof s=="object"){let[_,P]=u(s);P&&d(P),_&&m(_),h(c(s));}let S=typeof s=="string"?s:s._;S&&y(S),e.keepErrors||p();});function c({properties:S,items:_}){let P={};if(S){P.props={};for(let R in S)P.props[R]=[];}if(_){P.items={};for(let R=0;R<_.length;R++)P.items[R]=[];}return P}function u(S){let _,P;for(let R in S){if(R==="properties"||R==="items")continue;let E=S[R];if(typeof E=="object"){_||(_={});let C=_[R]={};for(let b in E)C[b]=[];}else P||(P={}),P[R]=[];}return [_,P]}function d(S){let _=r.const("emErrors",te.stringify(S)),P=r.const("templates",v(S,o));r.forOf("err",oo.default.vErrors,b=>r.if(f(b,_),()=>r.code(te._`${_}[${b}.keyword].push(${b})`).assign(te._`${b}.${Ya}`,true)));let{singleError:R}=e;if(R){let b=r.let("message",te._`""`),O=r.let("paramsErrors",te._`[]`);E(D=>{r.if(b,()=>r.code(te._`${b} += ${typeof R=="string"?R:";"}`)),r.code(te._`${b} += ${C(D)}`),r.assign(O,te._`${O}.concat(${_}[${D}])`);}),bu.reportError(t,{message:b,params:te._`{errors: ${O}}`});}else E(b=>bu.reportError(t,{message:C(b),params:te._`{errors: ${_}[${b}]}`}));function E(b){r.forIn("key",_,O=>r.if(te._`${_}[${O}].length`,()=>b(O)));}function C(b){return te._`${b} in ${P} ? ${P}[${b}]() : ${a}[${b}]`}}function m(S){let _=r.const("emErrors",te.stringify(S)),P=[];for(let O in S)P.push([O,v(S[O],o[O])]);let R=r.const("templates",r.object(...P)),E=r.scopeValue("obj",{ref:H_,code:te.stringify(H_)}),C=r.let("emPropParams"),b=r.let("emParamsErrors");r.forOf("err",oo.default.vErrors,O=>r.if(f(O,_),()=>{r.assign(C,te._`${E}[${O}.keyword]`),r.assign(b,te._`${_}[${O}.keyword][${O}.params[${C}]]`),r.if(b,()=>r.code(te._`${b}.push(${O})`).assign(te._`${O}.${Ya}`,true));})),r.forIn("key",_,O=>r.forIn("keyProp",te._`${_}[${O}]`,D=>{r.assign(b,te._`${_}[${O}][${D}]`),r.if(te._`${b}.length`,()=>{let k=r.const("tmpl",te._`${R}[${O}] && ${R}[${O}][${D}]`);bu.reportError(t,{message:te._`${k} ? ${k}() : ${a}[${O}][${D}]`,params:te._`{errors: ${b}}`});});}));}function h(S){let{props:_,items:P}=S;if(!_&&!P)return;let R=te._`typeof ${n} == "object"`,E=te._`Array.isArray(${n})`,C=r.let("emErrors"),b,O,D=r.let("templates");_&&P?(b=r.let("emChildKwd"),r.if(R),r.if(E,()=>{k(P,o.items),r.assign(b,te.str`items`);},()=>{k(_,o.properties),r.assign(b,te.str`properties`);}),O=te._`[${b}]`):P?(r.if(E),k(P,o.items),O=te._`.items`):_&&(r.if(Qa.and(R,Qa.not(E))),k(_,o.properties),O=te._`.properties`),r.forOf("err",oo.default.vErrors,I=>x(I,C,F=>r.code(te._`${C}[${F}].push(${I})`).assign(te._`${I}.${Ya}`,true))),r.forIn("key",C,I=>r.if(te._`${C}[${I}].length`,()=>{bu.reportError(t,{message:te._`${I} in ${D} ? ${D}[${I}]() : ${a}${O}[${I}]`,params:te._`{errors: ${C}[${I}]}`}),r.assign(te._`${oo.default.vErrors}[${oo.default.errors}-1].instancePath`,te._`${l} + "/" + ${I}.replace(/~/g, "~0").replace(/\\//g, "~1")`);})),r.endIf();function k(I,F){r.assign(C,te.stringify(I)),r.assign(D,v(I,F));}}function y(S){let _=r.const("emErrs",te._`[]`);r.forOf("err",oo.default.vErrors,P=>r.if(g(P),()=>r.code(te._`${_}.push(${P})`).assign(te._`${P}.${Ya}`,true))),r.if(te._`${_}.length`,()=>bu.reportError(t,{message:w(S),params:te._`{errors: ${_}}`}));}function p(){let S=r.const("emErrs",te._`[]`);r.forOf("err",oo.default.vErrors,_=>r.if(te._`!${_}.${Ya}`,()=>r.code(te._`${S}.push(${_})`))),r.assign(oo.default.vErrors,S).assign(oo.default.errors,te._`${S}.length`);}function f(S,_){return Qa.and(te._`${S}.keyword !== ${zf}`,te._`!${S}.${Ya}`,te._`${S}.instancePath === ${l}`,te._`${S}.keyword in ${_}`,te._`${S}.schemaPath.indexOf(${i.errSchemaPath}) === 0`,te._`/^\\/[^\\/]*$/.test(${S}.schemaPath.slice(${i.errSchemaPath.length}))`)}function x(S,_,P){r.if(Qa.and(te._`${S}.keyword !== ${zf}`,te._`!${S}.${Ya}`,te._`${S}.instancePath.indexOf(${l}) === 0`),()=>{let R=r.scopeValue("pattern",{ref:/^\/([^/]*)(?:\/|$)/,code:te._`new RegExp("^\\\/([^/]*)(?:\\\/|$)")`}),E=r.const("emMatches",te._`${R}.exec(${S}.instancePath.slice(${l}.length))`),C=r.const("emChild",te._`${E} && ${E}[1].replace(/~1/g, "/").replace(/~0/g, "~")`);r.if(te._`${C} !== undefined && ${C} in ${_}`,()=>P(C));});}function g(S){return Qa.and(te._`${S}.keyword !== ${zf}`,te._`!${S}.${Ya}`,Qa.or(te._`${S}.instancePath === ${l}`,Qa.and(te._`${S}.instancePath.indexOf(${l}) === 0`,te._`${S}.instancePath[${l}.length] === "/"`)),te._`${S}.schemaPath.indexOf(${i.errSchemaPath}) === 0`,te._`${S}.schemaPath[${i.errSchemaPath}.length] === "/"`)}function v(S,_){let P=[];for(let R in S){let E=_[R];J_.test(E)&&P.push([R,N(E)]);}return r.object(...P)}function w(S){return J_.test(S)?new V_._Code(V_.safeStringify(S).replace(eF,(_,P)=>`" + JSON.stringify(${YI.getData(P,i)}) + "`).replace(tF,"")):te.stringify(S)}function N(S){return te._`function(){return ${w(S)}}`}},metaSchema:{anyOf:[{type:"string"},{type:"object",properties:{properties:{$ref:"#/$defs/stringMap"},items:{$ref:"#/$defs/stringList"},required:{$ref:"#/$defs/stringOrMap"},dependencies:{$ref:"#/$defs/stringOrMap"}},additionalProperties:{type:"string"}}],$defs:{stringMap:{type:"object",additionalProperties:{type:"string"}},stringOrMap:{anyOf:[{type:"string"},{$ref:"#/$defs/stringMap"}]},stringList:{type:"array",items:{type:"string"}}}}}}var $y=(e,t={})=>{if(!e.opts.allErrors)throw new Error("ajv-errors: Ajv option allErrors must be true");if(e.opts.jsPropertySyntax)throw new Error("ajv-errors: ajv option jsPropertySyntax is not supported");return e.addKeyword(rF(t))};Iy.default=$y;Fy.exports=$y;Fy.exports.default=$y;});var Yu=M((zae,Sv)=>{typeof process>"u"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0?Sv.exports={nextTick:H6}:Sv.exports=process;function H6(e,t,r,n){if(typeof e!="function")throw new TypeError('"callback" argument must be a function');var o=arguments.length,a,i;switch(o){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick(function(){e.call(null,t);});case 3:return process.nextTick(function(){e.call(null,t,r);});case 4:return process.nextTick(function(){e.call(null,t,r,n);});default:for(a=new Array(o-1),i=0;i<a.length;)a[i++]=arguments[i];return process.nextTick(function(){e.apply(null,a);})}}});var VE=M((Uae,qE)=>{var J6={}.toString;qE.exports=Array.isArray||function(e){return J6.call(e)=="[object Array]"};});var Nv=M((qae,HE)=>{HE.exports=sa("stream");});var ed=M((Cv,WE)=>{var gm=sa("buffer"),Ea=gm.Buffer;function JE(e,t){for(var r in e)t[r]=e[r];}Ea.from&&Ea.alloc&&Ea.allocUnsafe&&Ea.allocUnsafeSlow?WE.exports=gm:(JE(gm,Cv),Cv.Buffer=lc);function lc(e,t,r){return Ea(e,t,r)}JE(Ea,lc);lc.from=function(e,t,r){if(typeof e=="number")throw new TypeError("Argument must not be a number");return Ea(e,t,r)};lc.alloc=function(e,t,r){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=Ea(e);return t!==void 0?typeof r=="string"?n.fill(t,r):n.fill(t):n.fill(0),n};lc.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return Ea(e)};lc.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return gm.SlowBuffer(e)};});var cc=M(Br=>{function W6(e){return Array.isArray?Array.isArray(e):ym(e)==="[object Array]"}Br.isArray=W6;function K6(e){return typeof e=="boolean"}Br.isBoolean=K6;function G6(e){return e===null}Br.isNull=G6;function Z6(e){return e==null}Br.isNullOrUndefined=Z6;function X6(e){return typeof e=="number"}Br.isNumber=X6;function Q6(e){return typeof e=="string"}Br.isString=Q6;function Y6(e){return typeof e=="symbol"}Br.isSymbol=Y6;function e7(e){return e===void 0}Br.isUndefined=e7;function t7(e){return ym(e)==="[object RegExp]"}Br.isRegExp=t7;function r7(e){return typeof e=="object"&&e!==null}Br.isObject=r7;function n7(e){return ym(e)==="[object Date]"}Br.isDate=n7;function o7(e){return ym(e)==="[object Error]"||e instanceof Error}Br.isError=o7;function a7(e){return typeof e=="function"}Br.isFunction=a7;function i7(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"||typeof e=="symbol"||typeof e>"u"}Br.isPrimitive=i7;Br.isBuffer=sa("buffer").Buffer.isBuffer;function ym(e){return Object.prototype.toString.call(e)}});var KE=M((Hae,Ev)=>{typeof Object.create=="function"?Ev.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:false,writable:true,configurable:true}}));}:Ev.exports=function(t,r){if(r){t.super_=r;var n=function(){};n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t;}};});var uc=M((Jae,Tv)=>{try{if(Pv=sa("util"),typeof Pv.inherits!="function")throw "";Tv.exports=Pv.inherits;}catch{Tv.exports=KE();}var Pv;});var ZE=M((Wae,kv)=>{function s7(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var GE=ed().Buffer,td=sa("util");function l7(e,t,r){e.copy(t,r);}kv.exports=(function(){function e(){s7(this,e),this.head=null,this.tail=null,this.length=0;}return e.prototype.push=function(r){var n={data:r,next:null};this.length>0?this.tail.next=n:this.head=n,this.tail=n,++this.length;},e.prototype.unshift=function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length;},e.prototype.shift=function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0;},e.prototype.join=function(r){if(this.length===0)return "";for(var n=this.head,o=""+n.data;n=n.next;)o+=r+n.data;return o},e.prototype.concat=function(r){if(this.length===0)return GE.alloc(0);for(var n=GE.allocUnsafe(r>>>0),o=this.head,a=0;o;)l7(o.data,n,a),a+=o.data.length,o=o.next;return n},e})();td&&td.inspect&&td.inspect.custom&&(kv.exports.prototype[td.inspect.custom]=function(){var e=td.inspect({length:this.length});return this.constructor.name+" "+e});});var Rv=M((Kae,XE)=>{var vm=Yu();function c7(e,t){var r=this,n=this._readableState&&this._readableState.destroyed,o=this._writableState&&this._writableState.destroyed;return n||o?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=true,vm.nextTick(bm,this,e)):vm.nextTick(bm,this,e)),this):(this._readableState&&(this._readableState.destroyed=true),this._writableState&&(this._writableState.destroyed=true),this._destroy(e||null,function(a){!t&&a?r._writableState?r._writableState.errorEmitted||(r._writableState.errorEmitted=true,vm.nextTick(bm,r,a)):vm.nextTick(bm,r,a):t&&t(a);}),this)}function u7(){this._readableState&&(this._readableState.destroyed=false,this._readableState.reading=false,this._readableState.ended=false,this._readableState.endEmitted=false),this._writableState&&(this._writableState.destroyed=false,this._writableState.ended=false,this._writableState.ending=false,this._writableState.finalCalled=false,this._writableState.prefinished=false,this._writableState.finished=false,this._writableState.errorEmitted=false);}function bm(e,t){e.emit("error",t);}XE.exports={destroy:c7,undestroy:u7};});var YE=M((Gae,QE)=>{QE.exports=sa("util").deprecate;});var Dv=M((Zae,sP)=>{var ks=Yu();sP.exports=ir;function tP(e){var t=this;this.next=null,this.entry=null,this.finish=function(){T7(t,e);};}var d7=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:ks.nextTick,dc;ir.WritableState=nd;var rP=Object.create(cc());rP.inherits=uc();var f7={deprecate:YE()},nP=Nv(),wm=ed().Buffer,p7=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function m7(e){return wm.from(e)}function h7(e){return wm.isBuffer(e)||e instanceof p7}var oP=Rv();rP.inherits(ir,nP);function g7(){}function nd(e,t){dc=dc||Rs(),e=e||{};var r=t instanceof dc;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var n=e.highWaterMark,o=e.writableHighWaterMark,a=this.objectMode?16:16*1024;n||n===0?this.highWaterMark=n:r&&(o||o===0)?this.highWaterMark=o:this.highWaterMark=a,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=false,this.needDrain=false,this.ending=false,this.ended=false,this.finished=false,this.destroyed=false;var i=e.decodeStrings===false;this.decodeStrings=!i,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=false,this.corked=0,this.sync=true,this.bufferProcessing=false,this.onwrite=function(s){S7(t,s);},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=false,this.errorEmitted=false,this.bufferedRequestCount=0,this.corkedRequestsFree=new tP(this);}nd.prototype.getBuffer=function(){for(var t=this.bufferedRequest,r=[];t;)r.push(t),t=t.next;return r};(function(){try{Object.defineProperty(nd.prototype,"buffer",{get:f7.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")});}catch{}})();var xm;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(xm=Function.prototype[Symbol.hasInstance],Object.defineProperty(ir,Symbol.hasInstance,{value:function(e){return xm.call(this,e)?true:this!==ir?false:e&&e._writableState instanceof nd}})):xm=function(e){return e instanceof this};function ir(e){if(dc=dc||Rs(),!xm.call(ir,this)&&!(this instanceof dc))return new ir(e);this._writableState=new nd(e,this),this.writable=true,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),nP.call(this);}ir.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"));};function y7(e,t){var r=new Error("write after end");e.emit("error",r),ks.nextTick(t,r);}function v7(e,t,r,n){var o=true,a=false;return r===null?a=new TypeError("May not write null values to stream"):typeof r!="string"&&r!==void 0&&!t.objectMode&&(a=new TypeError("Invalid non-string/buffer chunk")),a&&(e.emit("error",a),ks.nextTick(n,a),o=false),o}ir.prototype.write=function(e,t,r){var n=this._writableState,o=false,a=!n.objectMode&&h7(e);return a&&!wm.isBuffer(e)&&(e=m7(e)),typeof t=="function"&&(r=t,t=null),a?t="buffer":t||(t=n.defaultEncoding),typeof r!="function"&&(r=g7),n.ended?y7(this,r):(a||v7(this,n,e,r))&&(n.pendingcb++,o=x7(this,n,a,e,t,r)),o};ir.prototype.cork=function(){var e=this._writableState;e.corked++;};ir.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&aP(this,e));};ir.prototype.setDefaultEncoding=function(t){if(typeof t=="string"&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this};function b7(e,t,r){return !e.objectMode&&e.decodeStrings!==false&&typeof t=="string"&&(t=wm.from(t,r)),t}Object.defineProperty(ir.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function x7(e,t,r,n,o,a){if(!r){var i=b7(t,n,o);n!==i&&(r=true,o="buffer",n=i);}var s=t.objectMode?1:n.length;t.length+=s;var l=t.length<t.highWaterMark;if(l||(t.needDrain=true),t.writing||t.corked){var c=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:o,isBuf:r,callback:a,next:null},c?c.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1;}else Ov(e,t,false,s,n,o,a);return l}function Ov(e,t,r,n,o,a,i){t.writelen=n,t.writecb=i,t.writing=true,t.sync=true,r?e._writev(o,t.onwrite):e._write(o,a,t.onwrite),t.sync=false;}function w7(e,t,r,n,o){--t.pendingcb,r?(ks.nextTick(o,n),ks.nextTick(rd,e,t),e._writableState.errorEmitted=true,e.emit("error",n)):(o(n),e._writableState.errorEmitted=true,e.emit("error",n),rd(e,t));}function _7(e){e.writing=false,e.writecb=null,e.length-=e.writelen,e.writelen=0;}function S7(e,t){var r=e._writableState,n=r.sync,o=r.writecb;if(_7(r),t)w7(e,r,n,t,o);else {var a=iP(r);!a&&!r.corked&&!r.bufferProcessing&&r.bufferedRequest&&aP(e,r),n?d7(eP,e,r,a,o):eP(e,r,a,o);}}function eP(e,t,r,n){r||N7(e,t),t.pendingcb--,n(),rd(e,t);}function N7(e,t){t.length===0&&t.needDrain&&(t.needDrain=false,e.emit("drain"));}function aP(e,t){t.bufferProcessing=true;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,o=new Array(n),a=t.corkedRequestsFree;a.entry=r;for(var i=0,s=true;r;)o[i]=r,r.isBuf||(s=false),r=r.next,i+=1;o.allBuffers=s,Ov(e,t,true,t.length,o,"",a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new tP(t),t.bufferedRequestCount=0;}else {for(;r;){var l=r.chunk,c=r.encoding,u=r.callback,d=t.objectMode?1:l.length;if(Ov(e,t,false,d,l,c,u),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null);}t.bufferedRequest=r,t.bufferProcessing=false;}ir.prototype._write=function(e,t,r){r(new Error("_write() is not implemented"));};ir.prototype._writev=null;ir.prototype.end=function(e,t,r){var n=this._writableState;typeof e=="function"?(r=e,e=null,t=null):typeof t=="function"&&(r=t,t=null),e!=null&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||P7(this,n,r);};function iP(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function C7(e,t){e._final(function(r){t.pendingcb--,r&&e.emit("error",r),t.prefinished=true,e.emit("prefinish"),rd(e,t);});}function E7(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final=="function"?(t.pendingcb++,t.finalCalled=true,ks.nextTick(C7,e,t)):(t.prefinished=true,e.emit("prefinish")));}function rd(e,t){var r=iP(t);return r&&(E7(e,t),t.pendingcb===0&&(t.finished=true,e.emit("finish"))),r}function P7(e,t,r){t.ending=true,rd(e,t),r&&(t.finished?ks.nextTick(r):e.once("finish",r)),t.ended=true,e.writable=false;}function T7(e,t,r){var n=e.entry;for(e.entry=null;n;){var o=n.callback;t.pendingcb--,o(r),n=n.next;}t.corkedRequestsFree.next=e;}Object.defineProperty(ir.prototype,"destroyed",{get:function(){return this._writableState===void 0?false:this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e);}});ir.prototype.destroy=oP.destroy;ir.prototype._undestroy=oP.undestroy;ir.prototype._destroy=function(e,t){this.end(),t(e);};});var Rs=M((Xae,dP)=>{var lP=Yu(),k7=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};dP.exports=Pa;var cP=Object.create(cc());cP.inherits=uc();var uP=Iv(),$v=Dv();cP.inherits(Pa,uP);for(Av=k7($v.prototype),_m=0;_m<Av.length;_m++)Sm=Av[_m],Pa.prototype[Sm]||(Pa.prototype[Sm]=$v.prototype[Sm]);var Av,Sm,_m;function Pa(e){if(!(this instanceof Pa))return new Pa(e);uP.call(this,e),$v.call(this,e),e&&e.readable===false&&(this.readable=false),e&&e.writable===false&&(this.writable=false),this.allowHalfOpen=true,e&&e.allowHalfOpen===false&&(this.allowHalfOpen=false),this.once("end",R7);}Object.defineProperty(Pa.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function R7(){this.allowHalfOpen||this._writableState.ended||lP.nextTick(O7,this);}function O7(e){e.end();}Object.defineProperty(Pa.prototype,"destroyed",{get:function(){return this._readableState===void 0||this._writableState===void 0?false:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=e,this._writableState.destroyed=e);}});Pa.prototype._destroy=function(e,t){this.push(null),this.end(),lP.nextTick(t,e);};});var jv=M(pP=>{var Mv=ed().Buffer,fP=Mv.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case "hex":case "utf8":case "utf-8":case "ascii":case "binary":case "base64":case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":case "raw":return true;default:return false}};function D7(e){if(!e)return "utf8";for(var t;;)switch(e){case "utf8":case "utf-8":return "utf8";case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return "utf16le";case "latin1":case "binary":return "latin1";case "base64":case "ascii":case "hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=true;}}function A7(e){var t=D7(e);if(typeof t!="string"&&(Mv.isEncoding===fP||!fP(e)))throw new Error("Unknown encoding: "+e);return t||e}pP.StringDecoder=od;function od(e){this.encoding=A7(e);var t;switch(this.encoding){case "utf16le":this.text=L7,this.end=B7,t=4;break;case "utf8":this.fillLast=F7,t=4;break;case "base64":this.text=z7,this.end=U7,t=3;break;default:this.write=q7,this.end=V7;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Mv.allocUnsafe(t);}od.prototype.write=function(e){if(e.length===0)return "";var t,r;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return "";r=this.lastNeed,this.lastNeed=0;}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""};od.prototype.end=j7;od.prototype.text=M7;od.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length;};function Fv(e){return e<=127?0:e>>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}function $7(e,t,r){var n=t.length-1;if(n<r)return 0;var o=Fv(t[n]);return o>=0?(o>0&&(e.lastNeed=o-1),o):--n<r||o===-2?0:(o=Fv(t[n]),o>=0?(o>0&&(e.lastNeed=o-2),o):--n<r||o===-2?0:(o=Fv(t[n]),o>=0?(o>0&&(o===2?o=0:e.lastNeed=o-3),o):0))}function I7(e,t,r){if((t[0]&192)!==128)return e.lastNeed=0,"\uFFFD";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"\uFFFD";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"\uFFFD"}}function F7(e){var t=this.lastTotal-this.lastNeed,r=I7(this,e);if(r!==void 0)return r;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length;}function M7(e,t){var r=$7(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}function j7(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"\uFFFD":t}function L7(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function B7(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function z7(e,t){var r=(e.length-t)%3;return r===0?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function U7(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function q7(e){return e.toString(this.encoding)}function V7(e){return e&&e.length?this.write(e):""}});var Iv=M((eie,CP)=>{var pc=Yu();CP.exports=Mt;var H7=VE(),ad;Mt.ReadableState=xP;sa("events").EventEmitter;var yP=function(e,t){return e.listeners(t).length},qv=Nv(),id=ed().Buffer,J7=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function W7(e){return id.from(e)}function K7(e){return id.isBuffer(e)||e instanceof J7}var vP=Object.create(cc());vP.inherits=uc();var Lv=sa("util"),gt=void 0;Lv&&Lv.debuglog?gt=Lv.debuglog("stream"):gt=function(){};var G7=ZE(),bP=Rv(),fc;vP.inherits(Mt,qv);var Bv=["error","close","destroy","pause","resume"];function Z7(e,t,r){if(typeof e.prependListener=="function")return e.prependListener(t,r);!e._events||!e._events[t]?e.on(t,r):H7(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]];}function xP(e,t){ad=ad||Rs(),e=e||{};var r=t instanceof ad;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var n=e.highWaterMark,o=e.readableHighWaterMark,a=this.objectMode?16:16*1024;n||n===0?this.highWaterMark=n:r&&(o||o===0)?this.highWaterMark=o:this.highWaterMark=a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new G7,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=false,this.endEmitted=false,this.reading=false,this.sync=true,this.needReadable=false,this.emittedReadable=false,this.readableListening=false,this.resumeScheduled=false,this.destroyed=false,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=false,this.decoder=null,this.encoding=null,e.encoding&&(fc||(fc=jv().StringDecoder),this.decoder=new fc(e.encoding),this.encoding=e.encoding);}function Mt(e){if(ad=ad||Rs(),!(this instanceof Mt))return new Mt(e);this._readableState=new xP(e,this),this.readable=true,e&&(typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)),qv.call(this);}Object.defineProperty(Mt.prototype,"destroyed",{get:function(){return this._readableState===void 0?false:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e);}});Mt.prototype.destroy=bP.destroy;Mt.prototype._undestroy=bP.undestroy;Mt.prototype._destroy=function(e,t){this.push(null),t(e);};Mt.prototype.push=function(e,t){var r=this._readableState,n;return r.objectMode?n=true:typeof e=="string"&&(t=t||r.defaultEncoding,t!==r.encoding&&(e=id.from(e,t),t=""),n=true),wP(this,e,t,false,n)};Mt.prototype.unshift=function(e){return wP(this,e,null,true,false)};function wP(e,t,r,n,o){var a=e._readableState;if(t===null)a.reading=false,e8(e,a);else {var i;o||(i=X7(a,t)),i?e.emit("error",i):a.objectMode||t&&t.length>0?(typeof t!="string"&&!a.objectMode&&Object.getPrototypeOf(t)!==id.prototype&&(t=W7(t)),n?a.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):zv(e,a,t,true):a.ended?e.emit("error",new Error("stream.push() after EOF")):(a.reading=false,a.decoder&&!r?(t=a.decoder.write(t),a.objectMode||t.length!==0?zv(e,a,t,false):_P(e,a)):zv(e,a,t,false))):n||(a.reading=false);}return Q7(a)}function zv(e,t,r,n){t.flowing&&t.length===0&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&Nm(e)),_P(e,t);}function X7(e,t){var r;return !K7(t)&&typeof t!="string"&&t!==void 0&&!e.objectMode&&(r=new TypeError("Invalid non-string/buffer chunk")),r}function Q7(e){return !e.ended&&(e.needReadable||e.length<e.highWaterMark||e.length===0)}Mt.prototype.isPaused=function(){return this._readableState.flowing===false};Mt.prototype.setEncoding=function(e){return fc||(fc=jv().StringDecoder),this._readableState.decoder=new fc(e),this._readableState.encoding=e,this};var mP=8388608;function Y7(e){return e>=mP?e=mP:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function hP(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=Y7(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=true,0))}Mt.prototype.read=function(e){gt("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(e!==0&&(t.emittedReadable=false),e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return gt("read: emitReadable",t.length,t.ended),t.length===0&&t.ended?Uv(this):Nm(this),null;if(e=hP(e,t),e===0&&t.ended)return t.length===0&&Uv(this),null;var n=t.needReadable;gt("need readable",n),(t.length===0||t.length-e<t.highWaterMark)&&(n=true,gt("length less than watermark",n)),t.ended||t.reading?(n=false,gt("reading or ended",n)):n&&(gt("do read"),t.reading=true,t.sync=true,t.length===0&&(t.needReadable=true),this._read(t.highWaterMark),t.sync=false,t.reading||(e=hP(r,t)));var o;return e>0?o=SP(e,t):o=null,o===null?(t.needReadable=true,e=0):t.length-=e,t.length===0&&(t.ended||(t.needReadable=true),r!==e&&t.ended&&Uv(this)),o!==null&&this.emit("data",o),o};function e8(e,t){if(!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length);}t.ended=true,Nm(e);}}function Nm(e){var t=e._readableState;t.needReadable=false,t.emittedReadable||(gt("emitReadable",t.flowing),t.emittedReadable=true,t.sync?pc.nextTick(gP,e):gP(e));}function gP(e){gt("emit readable"),e.emit("readable"),Vv(e);}function _P(e,t){t.readingMore||(t.readingMore=true,pc.nextTick(t8,e,t));}function t8(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(gt("maybeReadMore read 0"),e.read(0),r!==t.length);)r=t.length;t.readingMore=false;}Mt.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"));};Mt.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e);break}n.pipesCount+=1,gt("pipe count=%d opts=%j",n.pipesCount,t);var o=(!t||t.end!==false)&&e!==process.stdout&&e!==process.stderr,a=o?s:f;n.endEmitted?pc.nextTick(a):r.once("end",a),e.on("unpipe",i);function i(x,g){gt("onunpipe"),x===r&&g&&g.hasUnpiped===false&&(g.hasUnpiped=true,u());}function s(){gt("onend"),e.end();}var l=r8(r);e.on("drain",l);var c=false;function u(){gt("cleanup"),e.removeListener("close",y),e.removeListener("finish",p),e.removeListener("drain",l),e.removeListener("error",h),e.removeListener("unpipe",i),r.removeListener("end",s),r.removeListener("end",f),r.removeListener("data",m),c=true,n.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&l();}var d=false;r.on("data",m);function m(x){gt("ondata"),d=false;var g=e.write(x);g===false&&!d&&((n.pipesCount===1&&n.pipes===e||n.pipesCount>1&&NP(n.pipes,e)!==-1)&&!c&&(gt("false write response, pause",n.awaitDrain),n.awaitDrain++,d=true),r.pause());}function h(x){gt("onerror",x),f(),e.removeListener("error",h),yP(e,"error")===0&&e.emit("error",x);}Z7(e,"error",h);function y(){e.removeListener("finish",p),f();}e.once("close",y);function p(){gt("onfinish"),e.removeListener("close",y),f();}e.once("finish",p);function f(){gt("unpipe"),r.unpipe(e);}return e.emit("pipe",r),n.flowing||(gt("pipe resume"),r.resume()),e};function r8(e){return function(){var t=e._readableState;gt("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&yP(e,"data")&&(t.flowing=true,Vv(e));}}Mt.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:false};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=false,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,o=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=false;for(var a=0;a<o;a++)n[a].emit("unpipe",this,{hasUnpiped:false});return this}var i=NP(t.pipes,e);return i===-1?this:(t.pipes.splice(i,1),t.pipesCount-=1,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,r),this)};Mt.prototype.on=function(e,t){var r=qv.prototype.on.call(this,e,t);if(e==="data")this._readableState.flowing!==false&&this.resume();else if(e==="readable"){var n=this._readableState;!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=true,n.emittedReadable=false,n.reading?n.length&&Nm(this):pc.nextTick(n8,this));}return r};Mt.prototype.addListener=Mt.prototype.on;function n8(e){gt("readable nexttick read 0"),e.read(0);}Mt.prototype.resume=function(){var e=this._readableState;return e.flowing||(gt("resume"),e.flowing=true,o8(this,e)),this};function o8(e,t){t.resumeScheduled||(t.resumeScheduled=true,pc.nextTick(a8,e,t));}function a8(e,t){t.reading||(gt("resume read 0"),e.read(0)),t.resumeScheduled=false,t.awaitDrain=0,e.emit("resume"),Vv(e),t.flowing&&!t.reading&&e.read(0);}Mt.prototype.pause=function(){return gt("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==false&&(gt("pause"),this._readableState.flowing=false,this.emit("pause")),this};function Vv(e){var t=e._readableState;for(gt("flow",t.flowing);t.flowing&&e.read()!==null;);}Mt.prototype.wrap=function(e){var t=this,r=this._readableState,n=false;e.on("end",function(){if(gt("wrapped end"),r.decoder&&!r.ended){var i=r.decoder.end();i&&i.length&&t.push(i);}t.push(null);}),e.on("data",function(i){if(gt("wrapped data"),r.decoder&&(i=r.decoder.write(i)),!(r.objectMode&&i==null)&&!(!r.objectMode&&(!i||!i.length))){var s=t.push(i);s||(n=true,e.pause());}});for(var o in e)this[o]===void 0&&typeof e[o]=="function"&&(this[o]=(function(i){return function(){return e[i].apply(e,arguments)}})(o));for(var a=0;a<Bv.length;a++)e.on(Bv[a],this.emit.bind(this,Bv[a]));return this._read=function(i){gt("wrapped _read",i),n&&(n=false,e.resume());},this};Object.defineProperty(Mt.prototype,"readableHighWaterMark",{enumerable:false,get:function(){return this._readableState.highWaterMark}});Mt._fromList=SP;function SP(e,t){if(t.length===0)return null;var r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(t.decoder?r=t.buffer.join(""):t.buffer.length===1?r=t.buffer.head.data:r=t.buffer.concat(t.length),t.buffer.clear()):r=i8(e,t.buffer,t.decoder),r}function i8(e,t,r){var n;return e<t.head.data.length?(n=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):e===t.head.data.length?n=t.shift():n=r?s8(e,t):l8(e,t),n}function s8(e,t){var r=t.head,n=1,o=r.data;for(e-=o.length;r=r.next;){var a=r.data,i=e>a.length?a.length:e;if(i===a.length?o+=a:o+=a.slice(0,e),e-=i,e===0){i===a.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=a.slice(i));break}++n;}return t.length-=n,o}function l8(e,t){var r=id.allocUnsafe(e),n=t.head,o=1;for(n.data.copy(r),e-=n.data.length;n=n.next;){var a=n.data,i=e>a.length?a.length:e;if(a.copy(r,r.length-e,0,i),e-=i,e===0){i===a.length?(++o,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=a.slice(i));break}++o;}return t.length-=o,r}function Uv(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=true,pc.nextTick(c8,t,e));}function c8(e,t){!e.endEmitted&&e.length===0&&(e.endEmitted=true,t.readable=false,t.emit("end"));}function NP(e,t){for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return -1}});var Hv=M((tie,TP)=>{TP.exports=Ta;var Cm=Rs(),PP=Object.create(cc());PP.inherits=uc();PP.inherits(Ta,Cm);function u8(e,t){var r=this._transformState;r.transforming=false;var n=r.writecb;if(!n)return this.emit("error",new Error("write callback called multiple times"));r.writechunk=null,r.writecb=null,t!=null&&this.push(t),n(e);var o=this._readableState;o.reading=false,(o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark);}function Ta(e){if(!(this instanceof Ta))return new Ta(e);Cm.call(this,e),this._transformState={afterTransform:u8.bind(this),needTransform:false,transforming:false,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=true,this._readableState.sync=false,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.on("prefinish",d8);}function d8(){var e=this;typeof this._flush=="function"?this._flush(function(t,r){EP(e,t,r);}):EP(this,null,null);}Ta.prototype.push=function(e,t){return this._transformState.needTransform=false,Cm.prototype.push.call(this,e,t)};Ta.prototype._transform=function(e,t,r){throw new Error("_transform() is not implemented")};Ta.prototype._write=function(e,t,r){var n=this._transformState;if(n.writecb=r,n.writechunk=e,n.writeencoding=t,!n.transforming){var o=this._readableState;(n.needTransform||o.needReadable||o.length<o.highWaterMark)&&this._read(o.highWaterMark);}};Ta.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&t.writecb&&!t.transforming?(t.transforming=true,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=true;};Ta.prototype._destroy=function(e,t){var r=this;Cm.prototype._destroy.call(this,e,function(n){t(n),r.emit("close");});};function EP(e,t,r){if(t)return e.emit("error",t);if(r!=null&&e.push(r),e._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(e._transformState.transforming)throw new Error("Calling transform done when still transforming");return e.push(null)}});var DP=M((rie,OP)=>{OP.exports=sd;var kP=Hv(),RP=Object.create(cc());RP.inherits=uc();RP.inherits(sd,kP);function sd(e){if(!(this instanceof sd))return new sd(e);kP.call(this,e);}sd.prototype._transform=function(e,t,r){r(null,e);};});var Jv=M((Er,Em)=>{var Qo=sa("stream");process.env.READABLE_STREAM==="disable"&&Qo?(Em.exports=Qo,Er=Em.exports=Qo.Readable,Er.Readable=Qo.Readable,Er.Writable=Qo.Writable,Er.Duplex=Qo.Duplex,Er.Transform=Qo.Transform,Er.PassThrough=Qo.PassThrough,Er.Stream=Qo):(Er=Em.exports=Iv(),Er.Stream=Qo||Er,Er.Readable=Er,Er.Writable=Dv(),Er.Duplex=Rs(),Er.Transform=Hv(),Er.PassThrough=DP());});var ka=M(vn=>{vn.base64=true;vn.array=true;vn.string=true;vn.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u";vn.nodebuffer=typeof Buffer<"u";vn.uint8array=typeof Uint8Array<"u";if(typeof ArrayBuffer>"u")vn.blob=false;else {Wv=new ArrayBuffer(0);try{vn.blob=new Blob([Wv],{type:"application/zip"}).size===0;}catch{try{AP=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,Kv=new AP,Kv.append(Wv),vn.blob=Kv.getBlob("application/zip").size===0;}catch{vn.blob=false;}}}var Wv,AP,Kv;try{vn.nodestream=!!Jv().Readable;}catch{vn.nodestream=false;}});var Zv=M(Gv=>{var f8=Wt(),p8=ka(),Yo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";Gv.encode=function(e){for(var t=[],r,n,o,a,i,s,l,c=0,u=e.length,d=u,m=f8.getTypeOf(e)!=="string";c<e.length;)d=u-c,m?(r=e[c++],n=c<u?e[c++]:0,o=c<u?e[c++]:0):(r=e.charCodeAt(c++),n=c<u?e.charCodeAt(c++):0,o=c<u?e.charCodeAt(c++):0),a=r>>2,i=(r&3)<<4|n>>4,s=d>1?(n&15)<<2|o>>6:64,l=d>2?o&63:64,t.push(Yo.charAt(a)+Yo.charAt(i)+Yo.charAt(s)+Yo.charAt(l));return t.join("")};Gv.decode=function(e){var t,r,n,o,a,i,s,l=0,c=0,u="data:";if(e.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");e=e.replace(/[^A-Za-z0-9+/=]/g,"");var d=e.length*3/4;if(e.charAt(e.length-1)===Yo.charAt(64)&&d--,e.charAt(e.length-2)===Yo.charAt(64)&&d--,d%1!==0)throw new Error("Invalid base64 input, bad content length.");var m;for(p8.uint8array?m=new Uint8Array(d|0):m=new Array(d|0);l<e.length;)o=Yo.indexOf(e.charAt(l++)),a=Yo.indexOf(e.charAt(l++)),i=Yo.indexOf(e.charAt(l++)),s=Yo.indexOf(e.charAt(l++)),t=o<<2|a>>4,r=(a&15)<<4|i>>2,n=(i&3)<<6|s,m[c++]=t,i!==64&&(m[c++]=r),s!==64&&(m[c++]=n);return m};});var ld=M((aie,$P)=>{$P.exports={isNode:typeof Buffer<"u",newBufferFrom:function(e,t){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,t);if(typeof e=="number")throw new Error('The "data" argument must not be a number');return new Buffer(e,t)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&typeof e.on=="function"&&typeof e.pause=="function"&&typeof e.resume=="function"}};});var jP=M((iie,MP)=>{var IP=global.MutationObserver||global.WebKitMutationObserver,mc;process.browser?IP?(Xv=0,FP=new IP(cd),Qv=global.document.createTextNode(""),FP.observe(Qv,{characterData:true}),mc=function(){Qv.data=Xv=++Xv%2;}):!global.setImmediate&&typeof global.MessageChannel<"u"?(Yv=new global.MessageChannel,Yv.port1.onmessage=cd,mc=function(){Yv.port2.postMessage(0);}):"document"in global&&"onreadystatechange"in global.document.createElement("script")?mc=function(){var e=global.document.createElement("script");e.onreadystatechange=function(){cd(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null;},global.document.documentElement.appendChild(e);}:mc=function(){setTimeout(cd,0);}:mc=function(){process.nextTick(cd);};var Xv,FP,Qv,Yv,eb,ud=[];function cd(){eb=true;for(var e,t,r=ud.length;r;){for(t=ud,ud=[],e=-1;++e<r;)t[e]();r=ud.length;}eb=false;}MP.exports=m8;function m8(e){ud.push(e)===1&&!eb&&mc();}});var HP=M((sie,VP)=>{var LP=jP();function hc(){}var zr={},BP=["REJECTED"],tb=["FULFILLED"],zP=["PENDING"];process.browser||(dd=["UNHANDLED"]);var dd;VP.exports=Ni;function Ni(e){if(typeof e!="function")throw new TypeError("resolver must be a function");this.state=zP,this.queue=[],this.outcome=void 0,process.browser||(this.handled=dd),e!==hc&&UP(this,e);}Ni.prototype.finally=function(e){if(typeof e!="function")return this;var t=this.constructor;return this.then(r,n);function r(o){function a(){return o}return t.resolve(e()).then(a)}function n(o){function a(){throw o}return t.resolve(e()).then(a)}};Ni.prototype.catch=function(e){return this.then(null,e)};Ni.prototype.then=function(e,t){if(typeof e!="function"&&this.state===tb||typeof t!="function"&&this.state===BP)return this;var r=new this.constructor(hc);if(process.browser||this.handled===dd&&(this.handled=null),this.state!==zP){var n=this.state===tb?e:t;rb(r,n,this.outcome);}else this.queue.push(new fd(r,e,t));return r};function fd(e,t,r){this.promise=e,typeof t=="function"&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),typeof r=="function"&&(this.onRejected=r,this.callRejected=this.otherCallRejected);}fd.prototype.callFulfilled=function(e){zr.resolve(this.promise,e);};fd.prototype.otherCallFulfilled=function(e){rb(this.promise,this.onFulfilled,e);};fd.prototype.callRejected=function(e){zr.reject(this.promise,e);};fd.prototype.otherCallRejected=function(e){rb(this.promise,this.onRejected,e);};function rb(e,t,r){LP(function(){var n;try{n=t(r);}catch(o){return zr.reject(e,o)}n===e?zr.reject(e,new TypeError("Cannot resolve promise with itself")):zr.resolve(e,n);});}zr.resolve=function(e,t){var r=qP(h8,t);if(r.status==="error")return zr.reject(e,r.value);var n=r.value;if(n)UP(e,n);else {e.state=tb,e.outcome=t;for(var o=-1,a=e.queue.length;++o<a;)e.queue[o].callFulfilled(t);}return e};zr.reject=function(e,t){e.state=BP,e.outcome=t,process.browser||e.handled===dd&&LP(function(){e.handled===dd&&process.emit("unhandledRejection",t,e);});for(var r=-1,n=e.queue.length;++r<n;)e.queue[r].callRejected(t);return e};function h8(e){var t=e&&e.then;if(e&&(typeof e=="object"||typeof e=="function")&&typeof t=="function")return function(){t.apply(e,arguments);}}function UP(e,t){var r=false;function n(s){r||(r=true,zr.reject(e,s));}function o(s){r||(r=true,zr.resolve(e,s));}function a(){t(o,n);}var i=qP(a);i.status==="error"&&n(i.value);}function qP(e,t){var r={};try{r.value=e(t),r.status="success";}catch(n){r.status="error",r.value=n;}return r}Ni.resolve=g8;function g8(e){return e instanceof this?e:zr.resolve(new this(hc),e)}Ni.reject=y8;function y8(e){var t=new this(hc);return zr.reject(t,e)}Ni.all=v8;function v8(e){var t=this;if(Object.prototype.toString.call(e)!=="[object Array]")return this.reject(new TypeError("must be an array"));var r=e.length,n=false;if(!r)return this.resolve([]);for(var o=new Array(r),a=0,i=-1,s=new this(hc);++i<r;)l(e[i],i);return s;function l(c,u){t.resolve(c).then(d,function(m){n||(n=true,zr.reject(s,m));});function d(m){o[u]=m,++a===r&&!n&&(n=true,zr.resolve(s,o));}}}Ni.race=b8;function b8(e){var t=this;if(Object.prototype.toString.call(e)!=="[object Array]")return this.reject(new TypeError("must be an array"));var r=e.length,n=false;if(!r)return this.resolve([]);for(var o=-1,a=new this(hc);++o<r;)i(e[o]);return a;function i(s){t.resolve(s).then(function(l){n||(n=true,zr.resolve(a,l));},function(l){n||(n=true,zr.reject(a,l));});}}});var gc=M((lie,JP)=>{var nb=null;typeof Promise<"u"?nb=Promise:nb=HP();JP.exports={Promise:nb};});var KP=M(WP=>{(function(e,t){if(e.setImmediate)return;var r=1,n={},o=false,a=e.document,i;function s(g){typeof g!="function"&&(g=new Function(""+g));for(var v=new Array(arguments.length-1),w=0;w<v.length;w++)v[w]=arguments[w+1];var N={callback:g,args:v};return n[r]=N,i(r),r++}function l(g){delete n[g];}function c(g){var v=g.callback,w=g.args;switch(w.length){case 0:v();break;case 1:v(w[0]);break;case 2:v(w[0],w[1]);break;case 3:v(w[0],w[1],w[2]);break;default:v.apply(t,w);break}}function u(g){if(o)setTimeout(u,0,g);else {var v=n[g];if(v){o=true;try{c(v);}finally{l(g),o=false;}}}}function d(){i=function(g){process.nextTick(function(){u(g);});};}function m(){if(e.postMessage&&!e.importScripts){var g=true,v=e.onmessage;return e.onmessage=function(){g=false;},e.postMessage("","*"),e.onmessage=v,g}}function h(){var g="setImmediate$"+Math.random()+"$",v=function(w){w.source===e&&typeof w.data=="string"&&w.data.indexOf(g)===0&&u(+w.data.slice(g.length));};e.addEventListener?e.addEventListener("message",v,false):e.attachEvent("onmessage",v),i=function(w){e.postMessage(g+w,"*");};}function y(){var g=new MessageChannel;g.port1.onmessage=function(v){var w=v.data;u(w);},i=function(v){g.port2.postMessage(v);};}function p(){var g=a.documentElement;i=function(v){var w=a.createElement("script");w.onreadystatechange=function(){u(v),w.onreadystatechange=null,g.removeChild(w),w=null;},g.appendChild(w);};}function f(){i=function(g){setTimeout(u,0,g);};}var x=Object.getPrototypeOf&&Object.getPrototypeOf(e);x=x&&x.setTimeout?x:e,{}.toString.call(e.process)==="[object process]"?d():m()?h():e.MessageChannel?y():a&&"onreadystatechange"in a.createElement("script")?p():f(),x.setImmediate=s,x.clearImmediate=l;})(typeof self>"u"?typeof global>"u"?WP:global:self);});var Wt=M(sr=>{var Ci=ka(),x8=Zv(),yc=ld(),ob=gc();KP();function w8(e){var t=null;return Ci.uint8array?t=new Uint8Array(e.length):t=new Array(e.length),Tm(e,t)}sr.newBlob=function(e,t){sr.checkSupport("blob");try{return new Blob([e],{type:t})}catch{try{var r=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,n=new r;return n.append(e),n.getBlob(t)}catch{throw new Error("Bug : can't construct the Blob.")}}};function pd(e){return e}function Tm(e,t){for(var r=0;r<e.length;++r)t[r]=e.charCodeAt(r)&255;return t}var Pm={stringifyByChunk:function(e,t,r){var n=[],o=0,a=e.length;if(a<=r)return String.fromCharCode.apply(null,e);for(;o<a;)t==="array"||t==="nodebuffer"?n.push(String.fromCharCode.apply(null,e.slice(o,Math.min(o+r,a)))):n.push(String.fromCharCode.apply(null,e.subarray(o,Math.min(o+r,a)))),o+=r;return n.join("")},stringifyByChar:function(e){for(var t="",r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},applyCanBeUsed:{uint8array:(function(){try{return Ci.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return false}})(),nodebuffer:(function(){try{return Ci.nodebuffer&&String.fromCharCode.apply(null,yc.allocBuffer(1)).length===1}catch{return false}})()}};function md(e){var t=65536,r=sr.getTypeOf(e),n=true;if(r==="uint8array"?n=Pm.applyCanBeUsed.uint8array:r==="nodebuffer"&&(n=Pm.applyCanBeUsed.nodebuffer),n)for(;t>1;)try{return Pm.stringifyByChunk(e,r,t)}catch{t=Math.floor(t/2);}return Pm.stringifyByChar(e)}sr.applyFromCharCode=md;function km(e,t){for(var r=0;r<e.length;r++)t[r]=e[r];return t}var Ei={};Ei.string={string:pd,array:function(e){return Tm(e,new Array(e.length))},arraybuffer:function(e){return Ei.string.uint8array(e).buffer},uint8array:function(e){return Tm(e,new Uint8Array(e.length))},nodebuffer:function(e){return Tm(e,yc.allocBuffer(e.length))}};Ei.array={string:md,array:pd,arraybuffer:function(e){return new Uint8Array(e).buffer},uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return yc.newBufferFrom(e)}};Ei.arraybuffer={string:function(e){return md(new Uint8Array(e))},array:function(e){return km(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:pd,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return yc.newBufferFrom(new Uint8Array(e))}};Ei.uint8array={string:md,array:function(e){return km(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:pd,nodebuffer:function(e){return yc.newBufferFrom(e)}};Ei.nodebuffer={string:md,array:function(e){return km(e,new Array(e.length))},arraybuffer:function(e){return Ei.nodebuffer.uint8array(e).buffer},uint8array:function(e){return km(e,new Uint8Array(e.length))},nodebuffer:pd};sr.transformTo=function(e,t){if(t||(t=""),!e)return t;sr.checkSupport(e);var r=sr.getTypeOf(t),n=Ei[r][e](t);return n};sr.resolve=function(e){for(var t=e.split("/"),r=[],n=0;n<t.length;n++){var o=t[n];o==="."||o===""&&n!==0&&n!==t.length-1||(o===".."?r.pop():r.push(o));}return r.join("/")};sr.getTypeOf=function(e){if(typeof e=="string")return "string";if(Object.prototype.toString.call(e)==="[object Array]")return "array";if(Ci.nodebuffer&&yc.isBuffer(e))return "nodebuffer";if(Ci.uint8array&&e instanceof Uint8Array)return "uint8array";if(Ci.arraybuffer&&e instanceof ArrayBuffer)return "arraybuffer"};sr.checkSupport=function(e){var t=Ci[e.toLowerCase()];if(!t)throw new Error(e+" is not supported by this platform")};sr.MAX_VALUE_16BITS=65535;sr.MAX_VALUE_32BITS=-1;sr.pretty=function(e){var t="",r,n;for(n=0;n<(e||"").length;n++)r=e.charCodeAt(n),t+="\\x"+(r<16?"0":"")+r.toString(16).toUpperCase();return t};sr.delay=function(e,t,r){setImmediate(function(){e.apply(r||null,t||[]);});};sr.inherits=function(e,t){var r=function(){};r.prototype=t.prototype,e.prototype=new r;};sr.extend=function(){var e={},t,r;for(t=0;t<arguments.length;t++)for(r in arguments[t])Object.prototype.hasOwnProperty.call(arguments[t],r)&&typeof e[r]>"u"&&(e[r]=arguments[t][r]);return e};sr.prepareContent=function(e,t,r,n,o){var a=ob.Promise.resolve(t).then(function(i){var s=Ci.blob&&(i instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(i))!==-1);return s&&typeof FileReader<"u"?new ob.Promise(function(l,c){var u=new FileReader;u.onload=function(d){l(d.target.result);},u.onerror=function(d){c(d.target.error);},u.readAsArrayBuffer(i);}):i});return a.then(function(i){var s=sr.getTypeOf(i);return s?(s==="arraybuffer"?i=sr.transformTo("uint8array",i):s==="string"&&(o?i=x8.decode(i):r&&n!==true&&(i=w8(i))),i):ob.Promise.reject(new Error("Can't read the data of '"+e+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})};});var bn=M((die,ZP)=>{function GP(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=true,this.isFinished=false,this.isLocked=false,this._listeners={data:[],end:[],error:[]},this.previous=null;}GP.prototype={push:function(e){this.emit("data",e);},end:function(){if(this.isFinished)return false;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0;}catch(e){this.emit("error",e);}return true},error:function(e){return this.isFinished?false:(this.isPaused?this.generatedError=e:(this.isFinished=true,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),true)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[];},emit:function(e,t){if(this._listeners[e])for(var r=0;r<this._listeners[e].length;r++)this._listeners[e][r].call(this,t);},pipe:function(e){return e.registerPrevious(this)},registerPrevious:function(e){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=e.streamInfo,this.mergeStreamInfo(),this.previous=e;var t=this;return e.on("data",function(r){t.processChunk(r);}),e.on("end",function(){t.end();}),e.on("error",function(r){t.error(r);}),this},pause:function(){return this.isPaused||this.isFinished?false:(this.isPaused=true,this.previous&&this.previous.pause(),true)},resume:function(){if(!this.isPaused||this.isFinished)return false;this.isPaused=false;var e=false;return this.generatedError&&(this.error(this.generatedError),e=true),this.previous&&this.previous.resume(),!e},flush:function(){},processChunk:function(e){this.push(e);},withStreamInfo:function(e,t){return this.extraStreamInfo[e]=t,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var e in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,e)&&(this.streamInfo[e]=this.extraStreamInfo[e]);},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=true,this.previous&&this.previous.lock();},toString:function(){var e="Worker "+this.name;return this.previous?this.previous+" -> "+e:e}};ZP.exports=GP;});var bc=M(Pi=>{var vc=Wt(),Os=ka(),_8=ld(),Rm=bn(),hd=new Array(256);for(Ra=0;Ra<256;Ra++)hd[Ra]=Ra>=252?6:Ra>=248?5:Ra>=240?4:Ra>=224?3:Ra>=192?2:1;var Ra;hd[254]=hd[254]=1;var S8=function(e){var t,r,n,o,a,i=e.length,s=0;for(o=0;o<i;o++)r=e.charCodeAt(o),(r&64512)===55296&&o+1<i&&(n=e.charCodeAt(o+1),(n&64512)===56320&&(r=65536+(r-55296<<10)+(n-56320),o++)),s+=r<128?1:r<2048?2:r<65536?3:4;for(Os.uint8array?t=new Uint8Array(s):t=new Array(s),a=0,o=0;a<s;o++)r=e.charCodeAt(o),(r&64512)===55296&&o+1<i&&(n=e.charCodeAt(o+1),(n&64512)===56320&&(r=65536+(r-55296<<10)+(n-56320),o++)),r<128?t[a++]=r:r<2048?(t[a++]=192|r>>>6,t[a++]=128|r&63):r<65536?(t[a++]=224|r>>>12,t[a++]=128|r>>>6&63,t[a++]=128|r&63):(t[a++]=240|r>>>18,t[a++]=128|r>>>12&63,t[a++]=128|r>>>6&63,t[a++]=128|r&63);return t},N8=function(e,t){var r;for(t=t||e.length,t>e.length&&(t=e.length),r=t-1;r>=0&&(e[r]&192)===128;)r--;return r<0||r===0?t:r+hd[e[r]]>t?r:t},C8=function(e){var t,r,n,o,a=e.length,i=new Array(a*2);for(r=0,t=0;t<a;){if(n=e[t++],n<128){i[r++]=n;continue}if(o=hd[n],o>4){i[r++]=65533,t+=o-1;continue}for(n&=o===2?31:o===3?15:7;o>1&&t<a;)n=n<<6|e[t++]&63,o--;if(o>1){i[r++]=65533;continue}n<65536?i[r++]=n:(n-=65536,i[r++]=55296|n>>10&1023,i[r++]=56320|n&1023);}return i.length!==r&&(i.subarray?i=i.subarray(0,r):i.length=r),vc.applyFromCharCode(i)};Pi.utf8encode=function(t){return Os.nodebuffer?_8.newBufferFrom(t,"utf-8"):S8(t)};Pi.utf8decode=function(t){return Os.nodebuffer?vc.transformTo("nodebuffer",t).toString("utf-8"):(t=vc.transformTo(Os.uint8array?"uint8array":"array",t),C8(t))};function Om(){Rm.call(this,"utf-8 decode"),this.leftOver=null;}vc.inherits(Om,Rm);Om.prototype.processChunk=function(e){var t=vc.transformTo(Os.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(Os.uint8array){var r=t;t=new Uint8Array(r.length+this.leftOver.length),t.set(this.leftOver,0),t.set(r,this.leftOver.length);}else t=this.leftOver.concat(t);this.leftOver=null;}var n=N8(t),o=t;n!==t.length&&(Os.uint8array?(o=t.subarray(0,n),this.leftOver=t.subarray(n,t.length)):(o=t.slice(0,n),this.leftOver=t.slice(n,t.length))),this.push({data:Pi.utf8decode(o),meta:e.meta});};Om.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:Pi.utf8decode(this.leftOver),meta:{}}),this.leftOver=null);};Pi.Utf8DecodeWorker=Om;function ab(){Rm.call(this,"utf-8 encode");}vc.inherits(ab,Rm);ab.prototype.processChunk=function(e){this.push({data:Pi.utf8encode(e.data),meta:e.meta});};Pi.Utf8EncodeWorker=ab;});var e2=M((pie,YP)=>{var XP=bn(),QP=Wt();function ib(e){XP.call(this,"ConvertWorker to "+e),this.destType=e;}QP.inherits(ib,XP);ib.prototype.processChunk=function(e){this.push({data:QP.transformTo(this.destType,e.data),meta:e.meta});};YP.exports=ib;});var n2=M((mie,r2)=>{var t2=Jv().Readable,E8=Wt();E8.inherits(sb,t2);function sb(e,t,r){t2.call(this,t),this._helper=e;var n=this;e.on("data",function(o,a){n.push(o)||n._helper.pause(),r&&r(a);}).on("error",function(o){n.emit("error",o);}).on("end",function(){n.push(null);});}sb.prototype._read=function(){this._helper.resume();};r2.exports=sb;});var lb=M((hie,i2)=>{var Ds=Wt(),P8=e2(),T8=bn(),k8=Zv(),R8=ka(),O8=gc(),o2=null;if(R8.nodestream)try{o2=n2();}catch{}function D8(e,t,r){switch(e){case "blob":return Ds.newBlob(Ds.transformTo("arraybuffer",t),r);case "base64":return k8.encode(t);default:return Ds.transformTo(e,t)}}function A8(e,t){var r,n=0,o=null,a=0;for(r=0;r<t.length;r++)a+=t[r].length;switch(e){case "string":return t.join("");case "array":return Array.prototype.concat.apply([],t);case "uint8array":for(o=new Uint8Array(a),r=0;r<t.length;r++)o.set(t[r],n),n+=t[r].length;return o;case "nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}function $8(e,t){return new O8.Promise(function(r,n){var o=[],a=e._internalType,i=e._outputType,s=e._mimeType;e.on("data",function(l,c){o.push(l),t&&t(c);}).on("error",function(l){o=[],n(l);}).on("end",function(){try{var l=D8(i,A8(a,o),s);r(l);}catch(c){n(c);}o=[];}).resume();})}function a2(e,t,r){var n=t;switch(t){case "blob":case "arraybuffer":n="uint8array";break;case "base64":n="string";break}try{this._internalType=n,this._outputType=t,this._mimeType=r,Ds.checkSupport(n),this._worker=e.pipe(new P8(n)),e.lock();}catch(o){this._worker=new T8("error"),this._worker.error(o);}}a2.prototype={accumulate:function(e){return $8(this,e)},on:function(e,t){var r=this;return e==="data"?this._worker.on(e,function(n){t.call(r,n.data,n.meta);}):this._worker.on(e,function(){Ds.delay(t,arguments,r);}),this},resume:function(){return Ds.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(e){if(Ds.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new o2(this,{objectMode:this._outputType!=="nodebuffer"},e)}};i2.exports=a2;});var cb=M(Eo=>{Eo.base64=false;Eo.binary=false;Eo.dir=false;Eo.createFolders=true;Eo.date=null;Eo.compression=null;Eo.compressionOptions=null;Eo.comment=null;Eo.unixPermissions=null;Eo.dosPermissions=null;});var ub=M((yie,s2)=>{var Dm=Wt(),Am=bn(),I8=16*1024;function xc(e){Am.call(this,"DataWorker");var t=this;this.dataIsReady=false,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=false,e.then(function(r){t.dataIsReady=true,t.data=r,t.max=r&&r.length||0,t.type=Dm.getTypeOf(r),t.isPaused||t._tickAndRepeat();},function(r){t.error(r);});}Dm.inherits(xc,Am);xc.prototype.cleanUp=function(){Am.prototype.cleanUp.call(this),this.data=null;};xc.prototype.resume=function(){return Am.prototype.resume.call(this)?(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=true,Dm.delay(this._tickAndRepeat,[],this)),true):false};xc.prototype._tickAndRepeat=function(){this._tickScheduled=false,!(this.isPaused||this.isFinished)&&(this._tick(),this.isFinished||(Dm.delay(this._tickAndRepeat,[],this),this._tickScheduled=true));};xc.prototype._tick=function(){if(this.isPaused||this.isFinished)return false;var e=I8,t=null,r=Math.min(this.max,this.index+e);if(this.index>=this.max)return this.end();switch(this.type){case "string":t=this.data.substring(this.index,r);break;case "uint8array":t=this.data.subarray(this.index,r);break;case "array":case "nodebuffer":t=this.data.slice(this.index,r);break}return this.index=r,this.push({data:t,meta:{percent:this.max?this.index/this.max*100:0}})};s2.exports=xc;});var $m=M((vie,c2)=>{var F8=Wt();function M8(){for(var e,t=[],r=0;r<256;r++){e=r;for(var n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;t[r]=e;}return t}var l2=M8();function j8(e,t,r,n){var o=l2,a=n+r;e=e^-1;for(var i=n;i<a;i++)e=e>>>8^o[(e^t[i])&255];return e^-1}function L8(e,t,r,n){var o=l2,a=n+r;e=e^-1;for(var i=n;i<a;i++)e=e>>>8^o[(e^t.charCodeAt(i))&255];return e^-1}c2.exports=function(t,r){if(typeof t>"u"||!t.length)return 0;var n=F8.getTypeOf(t)!=="string";return n?j8(r|0,t,t.length,0):L8(r|0,t,t.length,0)};});var fb=M((bie,d2)=>{var u2=bn(),B8=$m(),z8=Wt();function db(){u2.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0);}z8.inherits(db,u2);db.prototype.processChunk=function(e){this.streamInfo.crc32=B8(e.data,this.streamInfo.crc32||0),this.push(e);};d2.exports=db;});var p2=M((xie,f2)=>{var U8=Wt(),pb=bn();function mb(e){pb.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0);}U8.inherits(mb,pb);mb.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length;}pb.prototype.processChunk.call(this,e);};f2.exports=mb;});var Im=M((wie,g2)=>{var m2=gc(),h2=ub(),q8=fb(),hb=p2();function gb(e,t,r,n,o){this.compressedSize=e,this.uncompressedSize=t,this.crc32=r,this.compression=n,this.compressedContent=o;}gb.prototype={getContentWorker:function(){var e=new h2(m2.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new hb("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new h2(m2.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}};gb.createWorkerFrom=function(e,t,r){return e.pipe(new q8).pipe(new hb("uncompressedSize")).pipe(t.compressWorker(r)).pipe(new hb("compressedSize")).withStreamInfo("compression",t)};g2.exports=gb;});var x2=M((_ie,b2)=>{var V8=lb(),H8=ub(),yb=bc(),vb=Im(),y2=bn(),bb=function(e,t,r){this.name=e,this.dir=r.dir,this.date=r.date,this.comment=r.comment,this.unixPermissions=r.unixPermissions,this.dosPermissions=r.dosPermissions,this._data=t,this._dataBinary=r.binary,this.options={compression:r.compression,compressionOptions:r.compressionOptions};};bb.prototype={internalStream:function(e){var t=null,r="string";try{if(!e)throw new Error("No output type specified.");r=e.toLowerCase();var n=r==="string"||r==="text";(r==="binarystring"||r==="text")&&(r="string"),t=this._decompressWorker();var o=!this._dataBinary;o&&!n&&(t=t.pipe(new yb.Utf8EncodeWorker)),!o&&n&&(t=t.pipe(new yb.Utf8DecodeWorker));}catch(a){t=new y2("error"),t.error(a);}return new V8(t,r,"")},async:function(e,t){return this.internalStream(e).accumulate(t)},nodeStream:function(e,t){return this.internalStream(e||"nodebuffer").toNodejsStream(t)},_compressWorker:function(e,t){if(this._data instanceof vb&&this._data.compression.magic===e.magic)return this._data.getCompressedWorker();var r=this._decompressWorker();return this._dataBinary||(r=r.pipe(new yb.Utf8EncodeWorker)),vb.createWorkerFrom(r,e,t)},_decompressWorker:function(){return this._data instanceof vb?this._data.getContentWorker():this._data instanceof y2?this._data:new H8(this._data)}};var v2=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],J8=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")};for(Fm=0;Fm<v2.length;Fm++)bb.prototype[v2[Fm]]=J8;var Fm;b2.exports=bb;});var Oa=M(Wr=>{var W8=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function K8(e,t){return Object.prototype.hasOwnProperty.call(e,t)}Wr.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var r=t.shift();if(r){if(typeof r!="object")throw new TypeError(r+"must be non-object");for(var n in r)K8(r,n)&&(e[n]=r[n]);}}return e};Wr.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var G8={arraySet:function(e,t,r,n,o){if(t.subarray&&e.subarray){e.set(t.subarray(r,r+n),o);return}for(var a=0;a<n;a++)e[o+a]=t[r+a];},flattenChunks:function(e){var t,r,n,o,a,i;for(n=0,t=0,r=e.length;t<r;t++)n+=e[t].length;for(i=new Uint8Array(n),o=0,t=0,r=e.length;t<r;t++)a=e[t],i.set(a,o),o+=a.length;return i}},Z8={arraySet:function(e,t,r,n,o){for(var a=0;a<n;a++)e[o+a]=t[r+a];},flattenChunks:function(e){return [].concat.apply([],e)}};Wr.setTyped=function(e){e?(Wr.Buf8=Uint8Array,Wr.Buf16=Uint16Array,Wr.Buf32=Int32Array,Wr.assign(Wr,G8)):(Wr.Buf8=Array,Wr.Buf16=Array,Wr.Buf32=Array,Wr.assign(Wr,Z8));};Wr.setTyped(W8);});var q2=M(Sc=>{var X8=Oa(),Q8=4,w2=0,_2=1,Y8=2;function _c(e){for(var t=e.length;--t>=0;)e[t]=0;}var eB=0,T2=1,tB=2,rB=3,nB=258,Eb=29,wd=256,yd=wd+1+Eb,wc=30,Pb=19,k2=2*yd+1,As=15,xb=16,oB=7,Tb=256,R2=16,O2=17,D2=18,Nb=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],Mm=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],aB=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],A2=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],iB=512,Da=new Array((yd+2)*2);_c(Da);var gd=new Array(wc*2);_c(gd);var vd=new Array(iB);_c(vd);var bd=new Array(nB-rB+1);_c(bd);var kb=new Array(Eb);_c(kb);var jm=new Array(wc);_c(jm);function wb(e,t,r,n,o){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=n,this.max_length=o,this.has_stree=e&&e.length;}var $2,I2,F2;function _b(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t;}function M2(e){return e<256?vd[e]:vd[256+(e>>>7)]}function xd(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255;}function fn(e,t,r){e.bi_valid>xb-r?(e.bi_buf|=t<<e.bi_valid&65535,xd(e,e.bi_buf),e.bi_buf=t>>xb-e.bi_valid,e.bi_valid+=r-xb):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=r);}function ea(e,t,r){fn(e,r[t*2],r[t*2+1]);}function j2(e,t){var r=0;do r|=e&1,e>>>=1,r<<=1;while(--t>0);return r>>>1}function sB(e){e.bi_valid===16?(xd(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8);}function lB(e,t){var r=t.dyn_tree,n=t.max_code,o=t.stat_desc.static_tree,a=t.stat_desc.has_stree,i=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,l=t.stat_desc.max_length,c,u,d,m,h,y,p=0;for(m=0;m<=As;m++)e.bl_count[m]=0;for(r[e.heap[e.heap_max]*2+1]=0,c=e.heap_max+1;c<k2;c++)u=e.heap[c],m=r[r[u*2+1]*2+1]+1,m>l&&(m=l,p++),r[u*2+1]=m,!(u>n)&&(e.bl_count[m]++,h=0,u>=s&&(h=i[u-s]),y=r[u*2],e.opt_len+=y*(m+h),a&&(e.static_len+=y*(o[u*2+1]+h)));if(p!==0){do{for(m=l-1;e.bl_count[m]===0;)m--;e.bl_count[m]--,e.bl_count[m+1]+=2,e.bl_count[l]--,p-=2;}while(p>0);for(m=l;m!==0;m--)for(u=e.bl_count[m];u!==0;)d=e.heap[--c],!(d>n)&&(r[d*2+1]!==m&&(e.opt_len+=(m-r[d*2+1])*r[d*2],r[d*2+1]=m),u--);}}function L2(e,t,r){var n=new Array(As+1),o=0,a,i;for(a=1;a<=As;a++)n[a]=o=o+r[a-1]<<1;for(i=0;i<=t;i++){var s=e[i*2+1];s!==0&&(e[i*2]=j2(n[s]++,s));}}function cB(){var e,t,r,n,o,a=new Array(As+1);for(r=0,n=0;n<Eb-1;n++)for(kb[n]=r,e=0;e<1<<Nb[n];e++)bd[r++]=n;for(bd[r-1]=n,o=0,n=0;n<16;n++)for(jm[n]=o,e=0;e<1<<Mm[n];e++)vd[o++]=n;for(o>>=7;n<wc;n++)for(jm[n]=o<<7,e=0;e<1<<Mm[n]-7;e++)vd[256+o++]=n;for(t=0;t<=As;t++)a[t]=0;for(e=0;e<=143;)Da[e*2+1]=8,e++,a[8]++;for(;e<=255;)Da[e*2+1]=9,e++,a[9]++;for(;e<=279;)Da[e*2+1]=7,e++,a[7]++;for(;e<=287;)Da[e*2+1]=8,e++,a[8]++;for(L2(Da,yd+1,a),e=0;e<wc;e++)gd[e*2+1]=5,gd[e*2]=j2(e,5);$2=new wb(Da,Nb,wd+1,yd,As),I2=new wb(gd,Mm,0,wc,As),F2=new wb(new Array(0),aB,0,Pb,oB);}function B2(e){var t;for(t=0;t<yd;t++)e.dyn_ltree[t*2]=0;for(t=0;t<wc;t++)e.dyn_dtree[t*2]=0;for(t=0;t<Pb;t++)e.bl_tree[t*2]=0;e.dyn_ltree[Tb*2]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0;}function z2(e){e.bi_valid>8?xd(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0;}function uB(e,t,r,n){z2(e),(xd(e,r),xd(e,~r)),X8.arraySet(e.pending_buf,e.window,t,r,e.pending),e.pending+=r;}function S2(e,t,r,n){var o=t*2,a=r*2;return e[o]<e[a]||e[o]===e[a]&&n[t]<=n[r]}function Sb(e,t,r){for(var n=e.heap[r],o=r<<1;o<=e.heap_len&&(o<e.heap_len&&S2(t,e.heap[o+1],e.heap[o],e.depth)&&o++,!S2(t,n,e.heap[o],e.depth));)e.heap[r]=e.heap[o],r=o,o<<=1;e.heap[r]=n;}function N2(e,t,r){var n,o,a=0,i,s;if(e.last_lit!==0)do n=e.pending_buf[e.d_buf+a*2]<<8|e.pending_buf[e.d_buf+a*2+1],o=e.pending_buf[e.l_buf+a],a++,n===0?ea(e,o,t):(i=bd[o],ea(e,i+wd+1,t),s=Nb[i],s!==0&&(o-=kb[i],fn(e,o,s)),n--,i=M2(n),ea(e,i,r),s=Mm[i],s!==0&&(n-=jm[i],fn(e,n,s)));while(a<e.last_lit);ea(e,Tb,t);}function Cb(e,t){var r=t.dyn_tree,n=t.stat_desc.static_tree,o=t.stat_desc.has_stree,a=t.stat_desc.elems,i,s,l=-1,c;for(e.heap_len=0,e.heap_max=k2,i=0;i<a;i++)r[i*2]!==0?(e.heap[++e.heap_len]=l=i,e.depth[i]=0):r[i*2+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=l<2?++l:0,r[c*2]=1,e.depth[c]=0,e.opt_len--,o&&(e.static_len-=n[c*2+1]);for(t.max_code=l,i=e.heap_len>>1;i>=1;i--)Sb(e,r,i);c=a;do i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Sb(e,r,1),s=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=s,r[c*2]=r[i*2]+r[s*2],e.depth[c]=(e.depth[i]>=e.depth[s]?e.depth[i]:e.depth[s])+1,r[i*2+1]=r[s*2+1]=c,e.heap[1]=c++,Sb(e,r,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],lB(e,t),L2(r,l,e.bl_count);}function C2(e,t,r){var n,o=-1,a,i=t[1],s=0,l=7,c=4;for(i===0&&(l=138,c=3),t[(r+1)*2+1]=65535,n=0;n<=r;n++)a=i,i=t[(n+1)*2+1],!(++s<l&&a===i)&&(s<c?e.bl_tree[a*2]+=s:a!==0?(a!==o&&e.bl_tree[a*2]++,e.bl_tree[R2*2]++):s<=10?e.bl_tree[O2*2]++:e.bl_tree[D2*2]++,s=0,o=a,i===0?(l=138,c=3):a===i?(l=6,c=3):(l=7,c=4));}function E2(e,t,r){var n,o=-1,a,i=t[1],s=0,l=7,c=4;for(i===0&&(l=138,c=3),n=0;n<=r;n++)if(a=i,i=t[(n+1)*2+1],!(++s<l&&a===i)){if(s<c)do ea(e,a,e.bl_tree);while(--s!==0);else a!==0?(a!==o&&(ea(e,a,e.bl_tree),s--),ea(e,R2,e.bl_tree),fn(e,s-3,2)):s<=10?(ea(e,O2,e.bl_tree),fn(e,s-3,3)):(ea(e,D2,e.bl_tree),fn(e,s-11,7));s=0,o=a,i===0?(l=138,c=3):a===i?(l=6,c=3):(l=7,c=4);}}function dB(e){var t;for(C2(e,e.dyn_ltree,e.l_desc.max_code),C2(e,e.dyn_dtree,e.d_desc.max_code),Cb(e,e.bl_desc),t=Pb-1;t>=3&&e.bl_tree[A2[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function fB(e,t,r,n){var o;for(fn(e,t-257,5),fn(e,r-1,5),fn(e,n-4,4),o=0;o<n;o++)fn(e,e.bl_tree[A2[o]*2+1],3);E2(e,e.dyn_ltree,t-1),E2(e,e.dyn_dtree,r-1);}function pB(e){var t=4093624447,r;for(r=0;r<=31;r++,t>>>=1)if(t&1&&e.dyn_ltree[r*2]!==0)return w2;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return _2;for(r=32;r<wd;r++)if(e.dyn_ltree[r*2]!==0)return _2;return w2}var P2=false;function mB(e){P2||(cB(),P2=true),e.l_desc=new _b(e.dyn_ltree,$2),e.d_desc=new _b(e.dyn_dtree,I2),e.bl_desc=new _b(e.bl_tree,F2),e.bi_buf=0,e.bi_valid=0,B2(e);}function U2(e,t,r,n){fn(e,(eB<<1)+(n?1:0),3),uB(e,t,r);}function hB(e){fn(e,T2<<1,3),ea(e,Tb,Da),sB(e);}function gB(e,t,r,n){var o,a,i=0;e.level>0?(e.strm.data_type===Y8&&(e.strm.data_type=pB(e)),Cb(e,e.l_desc),Cb(e,e.d_desc),i=dB(e),o=e.opt_len+3+7>>>3,a=e.static_len+3+7>>>3,a<=o&&(o=a)):o=a=r+5,r+4<=o&&t!==-1?U2(e,t,r,n):e.strategy===Q8||a===o?(fn(e,(T2<<1)+(n?1:0),3),N2(e,Da,gd)):(fn(e,(tB<<1)+(n?1:0),3),fB(e,e.l_desc.max_code+1,e.d_desc.max_code+1,i+1),N2(e,e.dyn_ltree,e.dyn_dtree)),B2(e),n&&z2(e);}function yB(e,t,r){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=r&255,e.last_lit++,t===0?e.dyn_ltree[r*2]++:(e.matches++,t--,e.dyn_ltree[(bd[r]+wd+1)*2]++,e.dyn_dtree[M2(t)*2]++),e.last_lit===e.lit_bufsize-1}Sc._tr_init=mB;Sc._tr_stored_block=U2;Sc._tr_flush_block=gB;Sc._tr_tally=yB;Sc._tr_align=hB;});var Rb=M((Cie,V2)=>{function vB(e,t,r,n){for(var o=e&65535|0,a=e>>>16&65535|0,i=0;r!==0;){i=r>2e3?2e3:r,r-=i;do o=o+t[n++]|0,a=a+o|0;while(--i);o%=65521,a%=65521;}return o|a<<16|0}V2.exports=vB;});var Ob=M((Eie,H2)=>{function bB(){for(var e,t=[],r=0;r<256;r++){e=r;for(var n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;t[r]=e;}return t}var xB=bB();function wB(e,t,r,n){var o=xB,a=n+r;e^=-1;for(var i=n;i<a;i++)e=e>>>8^o[(e^t[i])&255];return e^-1}H2.exports=wB;});var Lm=M((Pie,J2)=>{J2.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};});var tT=M(na=>{var Kr=Oa(),Vn=q2(),Z2=Rb(),Ti=Ob(),_B=Lm(),Ms=0,SB=1,NB=3,Ai=4,W2=5,ra=0,K2=1,Hn=-2,CB=-3,Db=-5,EB=-1,PB=1,Bm=2,TB=3,kB=4,RB=0,OB=2,Vm=8,DB=9,AB=15,$B=8,IB=29,FB=256,$b=FB+1+IB,MB=30,jB=19,LB=2*$b+1,BB=15,at=3,Oi=258,Po=Oi+at+1,zB=32,Hm=42,Ib=69,zm=73,Um=91,qm=103,$s=113,Sd=666,yr=1,Nd=2,Is=3,Ec=4,UB=3;function Di(e,t){return e.msg=_B[t],t}function G2(e){return (e<<1)-(e>4?9:0)}function Ri(e){for(var t=e.length;--t>=0;)e[t]=0;}function ki(e){var t=e.state,r=t.pending;r>e.avail_out&&(r=e.avail_out),r!==0&&(Kr.arraySet(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,t.pending===0&&(t.pending_out=0));}function Pr(e,t){Vn._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,ki(e.strm);}function ht(e,t){e.pending_buf[e.pending++]=t;}function _d(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255;}function qB(e,t,r,n){var o=e.avail_in;return o>n&&(o=n),o===0?0:(e.avail_in-=o,Kr.arraySet(t,e.input,e.next_in,o,r),e.state.wrap===1?e.adler=Z2(e.adler,t,o,r):e.state.wrap===2&&(e.adler=Ti(e.adler,t,o,r)),e.next_in+=o,e.total_in+=o,o)}function X2(e,t){var r=e.max_chain_length,n=e.strstart,o,a,i=e.prev_length,s=e.nice_match,l=e.strstart>e.w_size-Po?e.strstart-(e.w_size-Po):0,c=e.window,u=e.w_mask,d=e.prev,m=e.strstart+Oi,h=c[n+i-1],y=c[n+i];e.prev_length>=e.good_match&&(r>>=2),s>e.lookahead&&(s=e.lookahead);do if(o=t,!(c[o+i]!==y||c[o+i-1]!==h||c[o]!==c[n]||c[++o]!==c[n+1])){n+=2,o++;do;while(c[++n]===c[++o]&&c[++n]===c[++o]&&c[++n]===c[++o]&&c[++n]===c[++o]&&c[++n]===c[++o]&&c[++n]===c[++o]&&c[++n]===c[++o]&&c[++n]===c[++o]&&n<m);if(a=Oi-(m-n),n=m-Oi,a>i){if(e.match_start=t,i=a,a>=s)break;h=c[n+i-1],y=c[n+i];}}while((t=d[t&u])>l&&--r!==0);return i<=e.lookahead?i:e.lookahead}function Fs(e){var t=e.w_size,r,n,o,a,i;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Po)){Kr.arraySet(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,n=e.hash_size,r=n;do o=e.head[--r],e.head[r]=o>=t?o-t:0;while(--n);n=t,r=n;do o=e.prev[--r],e.prev[r]=o>=t?o-t:0;while(--n);a+=t;}if(e.strm.avail_in===0)break;if(n=qB(e.strm,e.window,e.strstart+e.lookahead,a),e.lookahead+=n,e.lookahead+e.insert>=at)for(i=e.strstart-e.insert,e.ins_h=e.window[i],e.ins_h=(e.ins_h<<e.hash_shift^e.window[i+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[i+at-1])&e.hash_mask,e.prev[i&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=i,i++,e.insert--,!(e.lookahead+e.insert<at)););}while(e.lookahead<Po&&e.strm.avail_in!==0)}function VB(e,t){var r=65535;for(r>e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Fs(e),e.lookahead===0&&t===Ms)return yr;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+r;if((e.strstart===0||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,Pr(e,false),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-Po&&(Pr(e,false),e.strm.avail_out===0))return yr}return e.insert=0,t===Ai?(Pr(e,true),e.strm.avail_out===0?Is:Ec):(e.strstart>e.block_start&&(Pr(e,false),e.strm.avail_out===0),yr)}function Ab(e,t){for(var r,n;;){if(e.lookahead<Po){if(Fs(e),e.lookahead<Po&&t===Ms)return yr;if(e.lookahead===0)break}if(r=0,e.lookahead>=at&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+at-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),r!==0&&e.strstart-r<=e.w_size-Po&&(e.match_length=X2(e,r)),e.match_length>=at)if(n=Vn._tr_tally(e,e.strstart-e.match_start,e.match_length-at),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=at){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+at-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++;}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else n=Vn._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(Pr(e,false),e.strm.avail_out===0))return yr}return e.insert=e.strstart<at-1?e.strstart:at-1,t===Ai?(Pr(e,true),e.strm.avail_out===0?Is:Ec):e.last_lit&&(Pr(e,false),e.strm.avail_out===0)?yr:Nd}function Nc(e,t){for(var r,n,o;;){if(e.lookahead<Po){if(Fs(e),e.lookahead<Po&&t===Ms)return yr;if(e.lookahead===0)break}if(r=0,e.lookahead>=at&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+at-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=at-1,r!==0&&e.prev_length<e.max_lazy_match&&e.strstart-r<=e.w_size-Po&&(e.match_length=X2(e,r),e.match_length<=5&&(e.strategy===PB||e.match_length===at&&e.strstart-e.match_start>4096)&&(e.match_length=at-1)),e.prev_length>=at&&e.match_length<=e.prev_length){o=e.strstart+e.lookahead-at,n=Vn._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-at),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=o&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+at-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=at-1,e.strstart++,n&&(Pr(e,false),e.strm.avail_out===0))return yr}else if(e.match_available){if(n=Vn._tr_tally(e,0,e.window[e.strstart-1]),n&&Pr(e,false),e.strstart++,e.lookahead--,e.strm.avail_out===0)return yr}else e.match_available=1,e.strstart++,e.lookahead--;}return e.match_available&&(n=Vn._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<at-1?e.strstart:at-1,t===Ai?(Pr(e,true),e.strm.avail_out===0?Is:Ec):e.last_lit&&(Pr(e,false),e.strm.avail_out===0)?yr:Nd}function HB(e,t){for(var r,n,o,a,i=e.window;;){if(e.lookahead<=Oi){if(Fs(e),e.lookahead<=Oi&&t===Ms)return yr;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=at&&e.strstart>0&&(o=e.strstart-1,n=i[o],n===i[++o]&&n===i[++o]&&n===i[++o])){a=e.strstart+Oi;do;while(n===i[++o]&&n===i[++o]&&n===i[++o]&&n===i[++o]&&n===i[++o]&&n===i[++o]&&n===i[++o]&&n===i[++o]&&o<a);e.match_length=Oi-(a-o),e.match_length>e.lookahead&&(e.match_length=e.lookahead);}if(e.match_length>=at?(r=Vn._tr_tally(e,1,e.match_length-at),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=Vn._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(Pr(e,false),e.strm.avail_out===0))return yr}return e.insert=0,t===Ai?(Pr(e,true),e.strm.avail_out===0?Is:Ec):e.last_lit&&(Pr(e,false),e.strm.avail_out===0)?yr:Nd}function JB(e,t){for(var r;;){if(e.lookahead===0&&(Fs(e),e.lookahead===0)){if(t===Ms)return yr;break}if(e.match_length=0,r=Vn._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(Pr(e,false),e.strm.avail_out===0))return yr}return e.insert=0,t===Ai?(Pr(e,true),e.strm.avail_out===0?Is:Ec):e.last_lit&&(Pr(e,false),e.strm.avail_out===0)?yr:Nd}function ta(e,t,r,n,o){this.good_length=e,this.max_lazy=t,this.nice_length=r,this.max_chain=n,this.func=o;}var Cc;Cc=[new ta(0,0,0,0,VB),new ta(4,4,8,4,Ab),new ta(4,5,16,8,Ab),new ta(4,6,32,32,Ab),new ta(4,4,16,16,Nc),new ta(8,16,32,32,Nc),new ta(8,16,128,128,Nc),new ta(8,32,128,256,Nc),new ta(32,128,258,1024,Nc),new ta(32,258,258,4096,Nc)];function WB(e){e.window_size=2*e.w_size,Ri(e.head),e.max_lazy_match=Cc[e.level].max_lazy,e.good_match=Cc[e.level].good_length,e.nice_match=Cc[e.level].nice_length,e.max_chain_length=Cc[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=at-1,e.match_available=0,e.ins_h=0;}function KB(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Vm,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Kr.Buf16(LB*2),this.dyn_dtree=new Kr.Buf16((2*MB+1)*2),this.bl_tree=new Kr.Buf16((2*jB+1)*2),Ri(this.dyn_ltree),Ri(this.dyn_dtree),Ri(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Kr.Buf16(BB+1),this.heap=new Kr.Buf16(2*$b+1),Ri(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Kr.Buf16(2*$b+1),Ri(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0;}function Q2(e){var t;return !e||!e.state?Di(e,Hn):(e.total_in=e.total_out=0,e.data_type=OB,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?Hm:$s,e.adler=t.wrap===2?0:1,t.last_flush=Ms,Vn._tr_init(t),ra)}function Y2(e){var t=Q2(e);return t===ra&&WB(e.state),t}function GB(e,t){return !e||!e.state||e.state.wrap!==2?Hn:(e.state.gzhead=t,ra)}function eT(e,t,r,n,o,a){if(!e)return Hn;var i=1;if(t===EB&&(t=6),n<0?(i=0,n=-n):n>15&&(i=2,n-=16),o<1||o>DB||r!==Vm||n<8||n>15||t<0||t>9||a<0||a>kB)return Di(e,Hn);n===8&&(n=9);var s=new KB;return e.state=s,s.strm=e,s.wrap=i,s.gzhead=null,s.w_bits=n,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=o+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+at-1)/at),s.window=new Kr.Buf8(s.w_size*2),s.head=new Kr.Buf16(s.hash_size),s.prev=new Kr.Buf16(s.w_size),s.lit_bufsize=1<<o+6,s.pending_buf_size=s.lit_bufsize*4,s.pending_buf=new Kr.Buf8(s.pending_buf_size),s.d_buf=1*s.lit_bufsize,s.l_buf=3*s.lit_bufsize,s.level=t,s.strategy=a,s.method=r,Y2(e)}function ZB(e,t){return eT(e,t,Vm,AB,$B,RB)}function XB(e,t){var r,n,o,a;if(!e||!e.state||t>W2||t<0)return e?Di(e,Hn):Hn;if(n=e.state,!e.output||!e.input&&e.avail_in!==0||n.status===Sd&&t!==Ai)return Di(e,e.avail_out===0?Db:Hn);if(n.strm=e,r=n.last_flush,n.last_flush=t,n.status===Hm)if(n.wrap===2)e.adler=0,ht(n,31),ht(n,139),ht(n,8),n.gzhead?(ht(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),ht(n,n.gzhead.time&255),ht(n,n.gzhead.time>>8&255),ht(n,n.gzhead.time>>16&255),ht(n,n.gzhead.time>>24&255),ht(n,n.level===9?2:n.strategy>=Bm||n.level<2?4:0),ht(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(ht(n,n.gzhead.extra.length&255),ht(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=Ti(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=Ib):(ht(n,0),ht(n,0),ht(n,0),ht(n,0),ht(n,0),ht(n,n.level===9?2:n.strategy>=Bm||n.level<2?4:0),ht(n,UB),n.status=$s);else {var i=Vm+(n.w_bits-8<<4)<<8,s=-1;n.strategy>=Bm||n.level<2?s=0:n.level<6?s=1:n.level===6?s=2:s=3,i|=s<<6,n.strstart!==0&&(i|=zB),i+=31-i%31,n.status=$s,_d(n,i),n.strstart!==0&&(_d(n,e.adler>>>16),_d(n,e.adler&65535)),e.adler=1;}if(n.status===Ib)if(n.gzhead.extra){for(o=n.pending;n.gzindex<(n.gzhead.extra.length&65535)&&!(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(e.adler=Ti(e.adler,n.pending_buf,n.pending-o,o)),ki(e),o=n.pending,n.pending===n.pending_buf_size));)ht(n,n.gzhead.extra[n.gzindex]&255),n.gzindex++;n.gzhead.hcrc&&n.pending>o&&(e.adler=Ti(e.adler,n.pending_buf,n.pending-o,o)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=zm);}else n.status=zm;if(n.status===zm)if(n.gzhead.name){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(e.adler=Ti(e.adler,n.pending_buf,n.pending-o,o)),ki(e),o=n.pending,n.pending===n.pending_buf_size)){a=1;break}n.gzindex<n.gzhead.name.length?a=n.gzhead.name.charCodeAt(n.gzindex++)&255:a=0,ht(n,a);}while(a!==0);n.gzhead.hcrc&&n.pending>o&&(e.adler=Ti(e.adler,n.pending_buf,n.pending-o,o)),a===0&&(n.gzindex=0,n.status=Um);}else n.status=Um;if(n.status===Um)if(n.gzhead.comment){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(e.adler=Ti(e.adler,n.pending_buf,n.pending-o,o)),ki(e),o=n.pending,n.pending===n.pending_buf_size)){a=1;break}n.gzindex<n.gzhead.comment.length?a=n.gzhead.comment.charCodeAt(n.gzindex++)&255:a=0,ht(n,a);}while(a!==0);n.gzhead.hcrc&&n.pending>o&&(e.adler=Ti(e.adler,n.pending_buf,n.pending-o,o)),a===0&&(n.status=qm);}else n.status=qm;if(n.status===qm&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&ki(e),n.pending+2<=n.pending_buf_size&&(ht(n,e.adler&255),ht(n,e.adler>>8&255),e.adler=0,n.status=$s)):n.status=$s),n.pending!==0){if(ki(e),e.avail_out===0)return n.last_flush=-1,ra}else if(e.avail_in===0&&G2(t)<=G2(r)&&t!==Ai)return Di(e,Db);if(n.status===Sd&&e.avail_in!==0)return Di(e,Db);if(e.avail_in!==0||n.lookahead!==0||t!==Ms&&n.status!==Sd){var l=n.strategy===Bm?JB(n,t):n.strategy===TB?HB(n,t):Cc[n.level].func(n,t);if((l===Is||l===Ec)&&(n.status=Sd),l===yr||l===Is)return e.avail_out===0&&(n.last_flush=-1),ra;if(l===Nd&&(t===SB?Vn._tr_align(n):t!==W2&&(Vn._tr_stored_block(n,0,0,false),t===NB&&(Ri(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),ki(e),e.avail_out===0))return n.last_flush=-1,ra}return t!==Ai?ra:n.wrap<=0?K2:(n.wrap===2?(ht(n,e.adler&255),ht(n,e.adler>>8&255),ht(n,e.adler>>16&255),ht(n,e.adler>>24&255),ht(n,e.total_in&255),ht(n,e.total_in>>8&255),ht(n,e.total_in>>16&255),ht(n,e.total_in>>24&255)):(_d(n,e.adler>>>16),_d(n,e.adler&65535)),ki(e),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?ra:K2)}function QB(e){var t;return !e||!e.state?Hn:(t=e.state.status,t!==Hm&&t!==Ib&&t!==zm&&t!==Um&&t!==qm&&t!==$s&&t!==Sd?Di(e,Hn):(e.state=null,t===$s?Di(e,CB):ra))}function YB(e,t){var r=t.length,n,o,a,i,s,l,c,u;if(!e||!e.state||(n=e.state,i=n.wrap,i===2||i===1&&n.status!==Hm||n.lookahead))return Hn;for(i===1&&(e.adler=Z2(e.adler,t,r,0)),n.wrap=0,r>=n.w_size&&(i===0&&(Ri(n.head),n.strstart=0,n.block_start=0,n.insert=0),u=new Kr.Buf8(n.w_size),Kr.arraySet(u,t,r-n.w_size,n.w_size,0),t=u,r=n.w_size),s=e.avail_in,l=e.next_in,c=e.input,e.avail_in=r,e.next_in=0,e.input=t,Fs(n);n.lookahead>=at;){o=n.strstart,a=n.lookahead-(at-1);do n.ins_h=(n.ins_h<<n.hash_shift^n.window[o+at-1])&n.hash_mask,n.prev[o&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=o,o++;while(--a);n.strstart=o,n.lookahead=at-1,Fs(n);}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=at-1,n.match_available=0,e.next_in=l,e.input=c,e.avail_in=s,n.wrap=i,ra}na.deflateInit=ZB;na.deflateInit2=eT;na.deflateReset=Y2;na.deflateResetKeep=Q2;na.deflateSetHeader=GB;na.deflate=XB;na.deflateEnd=QB;na.deflateSetDictionary=YB;na.deflateInfo="pako deflate (from Nodeca project)";});var Fb=M(Pc=>{var Jm=Oa(),rT=true,nT=true;try{String.fromCharCode.apply(null,[0]);}catch{rT=false;}try{String.fromCharCode.apply(null,new Uint8Array(1));}catch{nT=false;}var Cd=new Jm.Buf8(256);for(Aa=0;Aa<256;Aa++)Cd[Aa]=Aa>=252?6:Aa>=248?5:Aa>=240?4:Aa>=224?3:Aa>=192?2:1;var Aa;Cd[254]=Cd[254]=1;Pc.string2buf=function(e){var t,r,n,o,a,i=e.length,s=0;for(o=0;o<i;o++)r=e.charCodeAt(o),(r&64512)===55296&&o+1<i&&(n=e.charCodeAt(o+1),(n&64512)===56320&&(r=65536+(r-55296<<10)+(n-56320),o++)),s+=r<128?1:r<2048?2:r<65536?3:4;for(t=new Jm.Buf8(s),a=0,o=0;a<s;o++)r=e.charCodeAt(o),(r&64512)===55296&&o+1<i&&(n=e.charCodeAt(o+1),(n&64512)===56320&&(r=65536+(r-55296<<10)+(n-56320),o++)),r<128?t[a++]=r:r<2048?(t[a++]=192|r>>>6,t[a++]=128|r&63):r<65536?(t[a++]=224|r>>>12,t[a++]=128|r>>>6&63,t[a++]=128|r&63):(t[a++]=240|r>>>18,t[a++]=128|r>>>12&63,t[a++]=128|r>>>6&63,t[a++]=128|r&63);return t};function oT(e,t){if(t<65534&&(e.subarray&&nT||!e.subarray&&rT))return String.fromCharCode.apply(null,Jm.shrinkBuf(e,t));for(var r="",n=0;n<t;n++)r+=String.fromCharCode(e[n]);return r}Pc.buf2binstring=function(e){return oT(e,e.length)};Pc.binstring2buf=function(e){for(var t=new Jm.Buf8(e.length),r=0,n=t.length;r<n;r++)t[r]=e.charCodeAt(r);return t};Pc.buf2string=function(e,t){var r,n,o,a,i=t||e.length,s=new Array(i*2);for(n=0,r=0;r<i;){if(o=e[r++],o<128){s[n++]=o;continue}if(a=Cd[o],a>4){s[n++]=65533,r+=a-1;continue}for(o&=a===2?31:a===3?15:7;a>1&&r<i;)o=o<<6|e[r++]&63,a--;if(a>1){s[n++]=65533;continue}o<65536?s[n++]=o:(o-=65536,s[n++]=55296|o>>10&1023,s[n++]=56320|o&1023);}return oT(s,n)};Pc.utf8border=function(e,t){var r;for(t=t||e.length,t>e.length&&(t=e.length),r=t-1;r>=0&&(e[r]&192)===128;)r--;return r<0||r===0?t:r+Cd[e[r]]>t?r:t};});var Mb=M((Rie,aT)=>{function ez(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0;}aT.exports=ez;});var cT=M(Td=>{var Ed=tT(),Pd=Oa(),Lb=Fb(),Bb=Lm(),tz=Mb(),lT=Object.prototype.toString,rz=0,jb=4,Tc=0,iT=1,sT=2,nz=-1,oz=0,az=8;function js(e){if(!(this instanceof js))return new js(e);this.options=Pd.assign({level:nz,method:az,chunkSize:16384,windowBits:15,memLevel:8,strategy:oz,to:""},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=false,this.chunks=[],this.strm=new tz,this.strm.avail_out=0;var r=Ed.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(r!==Tc)throw new Error(Bb[r]);if(t.header&&Ed.deflateSetHeader(this.strm,t.header),t.dictionary){var n;if(typeof t.dictionary=="string"?n=Lb.string2buf(t.dictionary):lT.call(t.dictionary)==="[object ArrayBuffer]"?n=new Uint8Array(t.dictionary):n=t.dictionary,r=Ed.deflateSetDictionary(this.strm,n),r!==Tc)throw new Error(Bb[r]);this._dict_set=true;}}js.prototype.push=function(e,t){var r=this.strm,n=this.options.chunkSize,o,a;if(this.ended)return false;a=t===~~t?t:t===true?jb:rz,typeof e=="string"?r.input=Lb.string2buf(e):lT.call(e)==="[object ArrayBuffer]"?r.input=new Uint8Array(e):r.input=e,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new Pd.Buf8(n),r.next_out=0,r.avail_out=n),o=Ed.deflate(r,a),o!==iT&&o!==Tc)return this.onEnd(o),this.ended=true,false;(r.avail_out===0||r.avail_in===0&&(a===jb||a===sT))&&(this.options.to==="string"?this.onData(Lb.buf2binstring(Pd.shrinkBuf(r.output,r.next_out))):this.onData(Pd.shrinkBuf(r.output,r.next_out)));}while((r.avail_in>0||r.avail_out===0)&&o!==iT);return a===jb?(o=Ed.deflateEnd(this.strm),this.onEnd(o),this.ended=true,o===Tc):(a===sT&&(this.onEnd(Tc),r.avail_out=0),true)};js.prototype.onData=function(e){this.chunks.push(e);};js.prototype.onEnd=function(e){e===Tc&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Pd.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg;};function zb(e,t){var r=new js(t);if(r.push(e,true),r.err)throw r.msg||Bb[r.err];return r.result}function iz(e,t){return t=t||{},t.raw=true,zb(e,t)}function sz(e,t){return t=t||{},t.gzip=true,zb(e,t)}Td.Deflate=js;Td.deflate=zb;Td.deflateRaw=iz;Td.gzip=sz;});var dT=M((Die,uT)=>{var Wm=30,lz=12;uT.exports=function(t,r){var n,o,a,i,s,l,c,u,d,m,h,y,p,f,x,g,v,w,N,S,_,P,R,E,C;n=t.state,o=t.next_in,E=t.input,a=o+(t.avail_in-5),i=t.next_out,C=t.output,s=i-(r-t.avail_out),l=i+(t.avail_out-257),c=n.dmax,u=n.wsize,d=n.whave,m=n.wnext,h=n.window,y=n.hold,p=n.bits,f=n.lencode,x=n.distcode,g=(1<<n.lenbits)-1,v=(1<<n.distbits)-1;e:do{p<15&&(y+=E[o++]<<p,p+=8,y+=E[o++]<<p,p+=8),w=f[y&g];t:for(;;){if(N=w>>>24,y>>>=N,p-=N,N=w>>>16&255,N===0)C[i++]=w&65535;else if(N&16){S=w&65535,N&=15,N&&(p<N&&(y+=E[o++]<<p,p+=8),S+=y&(1<<N)-1,y>>>=N,p-=N),p<15&&(y+=E[o++]<<p,p+=8,y+=E[o++]<<p,p+=8),w=x[y&v];r:for(;;){if(N=w>>>24,y>>>=N,p-=N,N=w>>>16&255,N&16){if(_=w&65535,N&=15,p<N&&(y+=E[o++]<<p,p+=8,p<N&&(y+=E[o++]<<p,p+=8)),_+=y&(1<<N)-1,_>c){t.msg="invalid distance too far back",n.mode=Wm;break e}if(y>>>=N,p-=N,N=i-s,_>N){if(N=_-N,N>d&&n.sane){t.msg="invalid distance too far back",n.mode=Wm;break e}if(P=0,R=h,m===0){if(P+=u-N,N<S){S-=N;do C[i++]=h[P++];while(--N);P=i-_,R=C;}}else if(m<N){if(P+=u+m-N,N-=m,N<S){S-=N;do C[i++]=h[P++];while(--N);if(P=0,m<S){N=m,S-=N;do C[i++]=h[P++];while(--N);P=i-_,R=C;}}}else if(P+=m-N,N<S){S-=N;do C[i++]=h[P++];while(--N);P=i-_,R=C;}for(;S>2;)C[i++]=R[P++],C[i++]=R[P++],C[i++]=R[P++],S-=3;S&&(C[i++]=R[P++],S>1&&(C[i++]=R[P++]));}else {P=i-_;do C[i++]=C[P++],C[i++]=C[P++],C[i++]=C[P++],S-=3;while(S>2);S&&(C[i++]=C[P++],S>1&&(C[i++]=C[P++]));}}else if((N&64)===0){w=x[(w&65535)+(y&(1<<N)-1)];continue r}else {t.msg="invalid distance code",n.mode=Wm;break e}break}}else if((N&64)===0){w=f[(w&65535)+(y&(1<<N)-1)];continue t}else if(N&32){n.mode=lz;break e}else {t.msg="invalid literal/length code",n.mode=Wm;break e}break}}while(o<a&&i<l);S=p>>3,o-=S,p-=S<<3,y&=(1<<p)-1,t.next_in=o,t.next_out=i,t.avail_in=o<a?5+(a-o):5-(o-a),t.avail_out=i<l?257+(l-i):257-(i-l),n.hold=y,n.bits=p;};});var vT=M((Aie,yT)=>{var fT=Oa(),kc=15,pT=852,mT=592,hT=0,Ub=1,gT=2,cz=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],uz=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],dz=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],fz=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];yT.exports=function(t,r,n,o,a,i,s,l){var c=l.bits,u=0,d=0,m=0,h=0,y=0,p=0,f=0,x=0,g=0,v=0,w,N,S,_,P,R=null,E=0,C,b=new fT.Buf16(kc+1),O=new fT.Buf16(kc+1),D=null,k=0,I,F,Z;for(u=0;u<=kc;u++)b[u]=0;for(d=0;d<o;d++)b[r[n+d]]++;for(y=c,h=kc;h>=1&&b[h]===0;h--);if(y>h&&(y=h),h===0)return a[i++]=1<<24|64<<16|0,a[i++]=1<<24|64<<16|0,l.bits=1,0;for(m=1;m<h&&b[m]===0;m++);for(y<m&&(y=m),x=1,u=1;u<=kc;u++)if(x<<=1,x-=b[u],x<0)return -1;if(x>0&&(t===hT||h!==1))return -1;for(O[1]=0,u=1;u<kc;u++)O[u+1]=O[u]+b[u];for(d=0;d<o;d++)r[n+d]!==0&&(s[O[r[n+d]]++]=d);if(t===hT?(R=D=s,C=19):t===Ub?(R=cz,E-=257,D=uz,k-=257,C=256):(R=dz,D=fz,C=-1),v=0,d=0,u=m,P=i,p=y,f=0,S=-1,g=1<<y,_=g-1,t===Ub&&g>pT||t===gT&&g>mT)return 1;for(;;){I=u-f,s[d]<C?(F=0,Z=s[d]):s[d]>C?(F=D[k+s[d]],Z=R[E+s[d]]):(F=96,Z=0),w=1<<u-f,N=1<<p,m=N;do N-=w,a[P+(v>>f)+N]=I<<24|F<<16|Z|0;while(N!==0);for(w=1<<u-1;v&w;)w>>=1;if(w!==0?(v&=w-1,v+=w):v=0,d++,--b[u]===0){if(u===h)break;u=r[n+s[d]];}if(u>y&&(v&_)!==S){for(f===0&&(f=y),P+=m,p=u-f,x=1<<p;p+f<h&&(x-=b[p+f],!(x<=0));)p++,x<<=1;if(g+=1<<p,t===Ub&&g>pT||t===gT&&g>mT)return 1;S=v&_,a[S]=y<<24|p<<16|P-i|0;}}return v!==0&&(a[P+v]=u-f<<24|64<<16|0),l.bits=y,0};});var YT=M(To=>{var xn=Oa(),Kb=Rb(),oa=Ob(),pz=dT(),kd=vT(),mz=0,VT=1,HT=2,bT=4,hz=5,Km=6,Ls=0,gz=1,yz=2,Jn=-2,JT=-3,Gb=-4,vz=-5,xT=8,WT=1,wT=2,_T=3,ST=4,NT=5,CT=6,ET=7,PT=8,TT=9,kT=10,Xm=11,$a=12,qb=13,RT=14,Vb=15,OT=16,DT=17,AT=18,$T=19,Gm=20,Zm=21,IT=22,FT=23,MT=24,jT=25,LT=26,Hb=27,BT=28,zT=29,Lt=30,Zb=31,bz=32,xz=852,wz=592,_z=15,Sz=_z;function UT(e){return (e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function Nz(){this.mode=0,this.last=false,this.wrap=0,this.havedict=false,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new xn.Buf16(320),this.work=new xn.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0;}function KT(e){var t;return !e||!e.state?Jn:(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=WT,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new xn.Buf32(xz),t.distcode=t.distdyn=new xn.Buf32(wz),t.sane=1,t.back=-1,Ls)}function GT(e){var t;return !e||!e.state?Jn:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,KT(e))}function ZT(e,t){var r,n;return !e||!e.state||(n=e.state,t<0?(r=0,t=-t):(r=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?Jn:(n.window!==null&&n.wbits!==t&&(n.window=null),n.wrap=r,n.wbits=t,GT(e))}function XT(e,t){var r,n;return e?(n=new Nz,e.state=n,n.window=null,r=ZT(e,t),r!==Ls&&(e.state=null),r):Jn}function Cz(e){return XT(e,Sz)}var qT=true,Jb,Wb;function Ez(e){if(qT){var t;for(Jb=new xn.Buf32(512),Wb=new xn.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(kd(VT,e.lens,0,288,Jb,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;kd(HT,e.lens,0,32,Wb,0,e.work,{bits:5}),qT=false;}e.lencode=Jb,e.lenbits=9,e.distcode=Wb,e.distbits=5;}function QT(e,t,r,n){var o,a=e.state;return a.window===null&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new xn.Buf8(a.wsize)),n>=a.wsize?(xn.arraySet(a.window,t,r-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):(o=a.wsize-a.wnext,o>n&&(o=n),xn.arraySet(a.window,t,r-n,o,a.wnext),n-=o,n?(xn.arraySet(a.window,t,r-n,n,0),a.wnext=n,a.whave=a.wsize):(a.wnext+=o,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=o))),0}function Pz(e,t){var r,n,o,a,i,s,l,c,u,d,m,h,y,p,f=0,x,g,v,w,N,S,_,P,R=new xn.Buf8(4),E,C,b=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&e.avail_in!==0)return Jn;r=e.state,r.mode===$a&&(r.mode=qb),i=e.next_out,o=e.output,l=e.avail_out,a=e.next_in,n=e.input,s=e.avail_in,c=r.hold,u=r.bits,d=s,m=l,P=Ls;e:for(;;)switch(r.mode){case WT:if(r.wrap===0){r.mode=qb;break}for(;u<16;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}if(r.wrap&2&&c===35615){r.check=0,R[0]=c&255,R[1]=c>>>8&255,r.check=oa(r.check,R,2,0),c=0,u=0,r.mode=wT;break}if(r.flags=0,r.head&&(r.head.done=false),!(r.wrap&1)||(((c&255)<<8)+(c>>8))%31){e.msg="incorrect header check",r.mode=Lt;break}if((c&15)!==xT){e.msg="unknown compression method",r.mode=Lt;break}if(c>>>=4,u-=4,_=(c&15)+8,r.wbits===0)r.wbits=_;else if(_>r.wbits){e.msg="invalid window size",r.mode=Lt;break}r.dmax=1<<_,e.adler=r.check=1,r.mode=c&512?kT:$a,c=0,u=0;break;case wT:for(;u<16;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}if(r.flags=c,(r.flags&255)!==xT){e.msg="unknown compression method",r.mode=Lt;break}if(r.flags&57344){e.msg="unknown header flags set",r.mode=Lt;break}r.head&&(r.head.text=c>>8&1),r.flags&512&&(R[0]=c&255,R[1]=c>>>8&255,r.check=oa(r.check,R,2,0)),c=0,u=0,r.mode=_T;case _T:for(;u<32;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}r.head&&(r.head.time=c),r.flags&512&&(R[0]=c&255,R[1]=c>>>8&255,R[2]=c>>>16&255,R[3]=c>>>24&255,r.check=oa(r.check,R,4,0)),c=0,u=0,r.mode=ST;case ST:for(;u<16;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}r.head&&(r.head.xflags=c&255,r.head.os=c>>8),r.flags&512&&(R[0]=c&255,R[1]=c>>>8&255,r.check=oa(r.check,R,2,0)),c=0,u=0,r.mode=NT;case NT:if(r.flags&1024){for(;u<16;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}r.length=c,r.head&&(r.head.extra_len=c),r.flags&512&&(R[0]=c&255,R[1]=c>>>8&255,r.check=oa(r.check,R,2,0)),c=0,u=0;}else r.head&&(r.head.extra=null);r.mode=CT;case CT:if(r.flags&1024&&(h=r.length,h>s&&(h=s),h&&(r.head&&(_=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),xn.arraySet(r.head.extra,n,a,h,_)),r.flags&512&&(r.check=oa(r.check,n,h,a)),s-=h,a+=h,r.length-=h),r.length))break e;r.length=0,r.mode=ET;case ET:if(r.flags&2048){if(s===0)break e;h=0;do _=n[a+h++],r.head&&_&&r.length<65536&&(r.head.name+=String.fromCharCode(_));while(_&&h<s);if(r.flags&512&&(r.check=oa(r.check,n,h,a)),s-=h,a+=h,_)break e}else r.head&&(r.head.name=null);r.length=0,r.mode=PT;case PT:if(r.flags&4096){if(s===0)break e;h=0;do _=n[a+h++],r.head&&_&&r.length<65536&&(r.head.comment+=String.fromCharCode(_));while(_&&h<s);if(r.flags&512&&(r.check=oa(r.check,n,h,a)),s-=h,a+=h,_)break e}else r.head&&(r.head.comment=null);r.mode=TT;case TT:if(r.flags&512){for(;u<16;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}if(c!==(r.check&65535)){e.msg="header crc mismatch",r.mode=Lt;break}c=0,u=0;}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=true),e.adler=r.check=0,r.mode=$a;break;case kT:for(;u<32;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}e.adler=r.check=UT(c),c=0,u=0,r.mode=Xm;case Xm:if(r.havedict===0)return e.next_out=i,e.avail_out=l,e.next_in=a,e.avail_in=s,r.hold=c,r.bits=u,yz;e.adler=r.check=1,r.mode=$a;case $a:if(t===hz||t===Km)break e;case qb:if(r.last){c>>>=u&7,u-=u&7,r.mode=Hb;break}for(;u<3;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}switch(r.last=c&1,c>>>=1,u-=1,c&3){case 0:r.mode=RT;break;case 1:if(Ez(r),r.mode=Gm,t===Km){c>>>=2,u-=2;break e}break;case 2:r.mode=DT;break;case 3:e.msg="invalid block type",r.mode=Lt;}c>>>=2,u-=2;break;case RT:for(c>>>=u&7,u-=u&7;u<32;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}if((c&65535)!==(c>>>16^65535)){e.msg="invalid stored block lengths",r.mode=Lt;break}if(r.length=c&65535,c=0,u=0,r.mode=Vb,t===Km)break e;case Vb:r.mode=OT;case OT:if(h=r.length,h){if(h>s&&(h=s),h>l&&(h=l),h===0)break e;xn.arraySet(o,n,a,h,i),s-=h,a+=h,l-=h,i+=h,r.length-=h;break}r.mode=$a;break;case DT:for(;u<14;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}if(r.nlen=(c&31)+257,c>>>=5,u-=5,r.ndist=(c&31)+1,c>>>=5,u-=5,r.ncode=(c&15)+4,c>>>=4,u-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=Lt;break}r.have=0,r.mode=AT;case AT:for(;r.have<r.ncode;){for(;u<3;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}r.lens[b[r.have++]]=c&7,c>>>=3,u-=3;}for(;r.have<19;)r.lens[b[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,E={bits:r.lenbits},P=kd(mz,r.lens,0,19,r.lencode,0,r.work,E),r.lenbits=E.bits,P){e.msg="invalid code lengths set",r.mode=Lt;break}r.have=0,r.mode=$T;case $T:for(;r.have<r.nlen+r.ndist;){for(;f=r.lencode[c&(1<<r.lenbits)-1],x=f>>>24,g=f>>>16&255,v=f&65535,!(x<=u);){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}if(v<16)c>>>=x,u-=x,r.lens[r.have++]=v;else {if(v===16){for(C=x+2;u<C;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}if(c>>>=x,u-=x,r.have===0){e.msg="invalid bit length repeat",r.mode=Lt;break}_=r.lens[r.have-1],h=3+(c&3),c>>>=2,u-=2;}else if(v===17){for(C=x+3;u<C;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}c>>>=x,u-=x,_=0,h=3+(c&7),c>>>=3,u-=3;}else {for(C=x+7;u<C;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}c>>>=x,u-=x,_=0,h=11+(c&127),c>>>=7,u-=7;}if(r.have+h>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=Lt;break}for(;h--;)r.lens[r.have++]=_;}}if(r.mode===Lt)break;if(r.lens[256]===0){e.msg="invalid code -- missing end-of-block",r.mode=Lt;break}if(r.lenbits=9,E={bits:r.lenbits},P=kd(VT,r.lens,0,r.nlen,r.lencode,0,r.work,E),r.lenbits=E.bits,P){e.msg="invalid literal/lengths set",r.mode=Lt;break}if(r.distbits=6,r.distcode=r.distdyn,E={bits:r.distbits},P=kd(HT,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,E),r.distbits=E.bits,P){e.msg="invalid distances set",r.mode=Lt;break}if(r.mode=Gm,t===Km)break e;case Gm:r.mode=Zm;case Zm:if(s>=6&&l>=258){e.next_out=i,e.avail_out=l,e.next_in=a,e.avail_in=s,r.hold=c,r.bits=u,pz(e,m),i=e.next_out,o=e.output,l=e.avail_out,a=e.next_in,n=e.input,s=e.avail_in,c=r.hold,u=r.bits,r.mode===$a&&(r.back=-1);break}for(r.back=0;f=r.lencode[c&(1<<r.lenbits)-1],x=f>>>24,g=f>>>16&255,v=f&65535,!(x<=u);){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}if(g&&(g&240)===0){for(w=x,N=g,S=v;f=r.lencode[S+((c&(1<<w+N)-1)>>w)],x=f>>>24,g=f>>>16&255,v=f&65535,!(w+x<=u);){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}c>>>=w,u-=w,r.back+=w;}if(c>>>=x,u-=x,r.back+=x,r.length=v,g===0){r.mode=LT;break}if(g&32){r.back=-1,r.mode=$a;break}if(g&64){e.msg="invalid literal/length code",r.mode=Lt;break}r.extra=g&15,r.mode=IT;case IT:if(r.extra){for(C=r.extra;u<C;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}r.length+=c&(1<<r.extra)-1,c>>>=r.extra,u-=r.extra,r.back+=r.extra;}r.was=r.length,r.mode=FT;case FT:for(;f=r.distcode[c&(1<<r.distbits)-1],x=f>>>24,g=f>>>16&255,v=f&65535,!(x<=u);){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}if((g&240)===0){for(w=x,N=g,S=v;f=r.distcode[S+((c&(1<<w+N)-1)>>w)],x=f>>>24,g=f>>>16&255,v=f&65535,!(w+x<=u);){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}c>>>=w,u-=w,r.back+=w;}if(c>>>=x,u-=x,r.back+=x,g&64){e.msg="invalid distance code",r.mode=Lt;break}r.offset=v,r.extra=g&15,r.mode=MT;case MT:if(r.extra){for(C=r.extra;u<C;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}r.offset+=c&(1<<r.extra)-1,c>>>=r.extra,u-=r.extra,r.back+=r.extra;}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=Lt;break}r.mode=jT;case jT:if(l===0)break e;if(h=m-l,r.offset>h){if(h=r.offset-h,h>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=Lt;break}h>r.wnext?(h-=r.wnext,y=r.wsize-h):y=r.wnext-h,h>r.length&&(h=r.length),p=r.window;}else p=o,y=i-r.offset,h=r.length;h>l&&(h=l),l-=h,r.length-=h;do o[i++]=p[y++];while(--h);r.length===0&&(r.mode=Zm);break;case LT:if(l===0)break e;o[i++]=r.length,l--,r.mode=Zm;break;case Hb:if(r.wrap){for(;u<32;){if(s===0)break e;s--,c|=n[a++]<<u,u+=8;}if(m-=l,e.total_out+=m,r.total+=m,m&&(e.adler=r.check=r.flags?oa(r.check,o,m,i-m):Kb(r.check,o,m,i-m)),m=l,(r.flags?c:UT(c))!==r.check){e.msg="incorrect data check",r.mode=Lt;break}c=0,u=0;}r.mode=BT;case BT:if(r.wrap&&r.flags){for(;u<32;){if(s===0)break e;s--,c+=n[a++]<<u,u+=8;}if(c!==(r.total&4294967295)){e.msg="incorrect length check",r.mode=Lt;break}c=0,u=0;}r.mode=zT;case zT:P=gz;break e;case Lt:P=JT;break e;case Zb:return Gb;case bz:default:return Jn}return e.next_out=i,e.avail_out=l,e.next_in=a,e.avail_in=s,r.hold=c,r.bits=u,(r.wsize||m!==e.avail_out&&r.mode<Lt&&(r.mode<Hb||t!==bT))&&QT(e,e.output,e.next_out,m-e.avail_out)?(r.mode=Zb,Gb):(d-=e.avail_in,m-=e.avail_out,e.total_in+=d,e.total_out+=m,r.total+=m,r.wrap&&m&&(e.adler=r.check=r.flags?oa(r.check,o,m,e.next_out-m):Kb(r.check,o,m,e.next_out-m)),e.data_type=r.bits+(r.last?64:0)+(r.mode===$a?128:0)+(r.mode===Gm||r.mode===Vb?256:0),(d===0&&m===0||t===bT)&&P===Ls&&(P=vz),P)}function Tz(e){if(!e||!e.state)return Jn;var t=e.state;return t.window&&(t.window=null),e.state=null,Ls}function kz(e,t){var r;return !e||!e.state||(r=e.state,(r.wrap&2)===0)?Jn:(r.head=t,t.done=false,Ls)}function Rz(e,t){var r=t.length,n,o,a;return !e||!e.state||(n=e.state,n.wrap!==0&&n.mode!==Xm)?Jn:n.mode===Xm&&(o=1,o=Kb(o,t,r,0),o!==n.check)?JT:(a=QT(e,t,r,r),a?(n.mode=Zb,Gb):(n.havedict=1,Ls))}To.inflateReset=GT;To.inflateReset2=ZT;To.inflateResetKeep=KT;To.inflateInit=Cz;To.inflateInit2=XT;To.inflate=Pz;To.inflateEnd=Tz;To.inflateGetHeader=kz;To.inflateSetDictionary=Rz;To.inflateInfo="pako inflate (from Nodeca project)";});var Xb=M((Iie,ek)=>{ek.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};});var rk=M((Fie,tk)=>{function Oz(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=false;}tk.exports=Oz;});var ok=M(Od=>{var Rc=YT(),Rd=Oa(),Qm=Fb(),tr=Xb(),Qb=Lm(),Dz=Mb(),Az=rk(),nk=Object.prototype.toString;function Bs(e){if(!(this instanceof Bs))return new Bs(e);this.options=Rd.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(e&&e.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15)===0&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=false,this.chunks=[],this.strm=new Dz,this.strm.avail_out=0;var r=Rc.inflateInit2(this.strm,t.windowBits);if(r!==tr.Z_OK)throw new Error(Qb[r]);if(this.header=new Az,Rc.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=Qm.string2buf(t.dictionary):nk.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(r=Rc.inflateSetDictionary(this.strm,t.dictionary),r!==tr.Z_OK)))throw new Error(Qb[r])}Bs.prototype.push=function(e,t){var r=this.strm,n=this.options.chunkSize,o=this.options.dictionary,a,i,s,l,c,u=false;if(this.ended)return false;i=t===~~t?t:t===true?tr.Z_FINISH:tr.Z_NO_FLUSH,typeof e=="string"?r.input=Qm.binstring2buf(e):nk.call(e)==="[object ArrayBuffer]"?r.input=new Uint8Array(e):r.input=e,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new Rd.Buf8(n),r.next_out=0,r.avail_out=n),a=Rc.inflate(r,tr.Z_NO_FLUSH),a===tr.Z_NEED_DICT&&o&&(a=Rc.inflateSetDictionary(this.strm,o)),a===tr.Z_BUF_ERROR&&u===true&&(a=tr.Z_OK,u=false),a!==tr.Z_STREAM_END&&a!==tr.Z_OK)return this.onEnd(a),this.ended=true,false;r.next_out&&(r.avail_out===0||a===tr.Z_STREAM_END||r.avail_in===0&&(i===tr.Z_FINISH||i===tr.Z_SYNC_FLUSH))&&(this.options.to==="string"?(s=Qm.utf8border(r.output,r.next_out),l=r.next_out-s,c=Qm.buf2string(r.output,s),r.next_out=l,r.avail_out=n-l,l&&Rd.arraySet(r.output,r.output,s,l,0),this.onData(c)):this.onData(Rd.shrinkBuf(r.output,r.next_out))),r.avail_in===0&&r.avail_out===0&&(u=true);}while((r.avail_in>0||r.avail_out===0)&&a!==tr.Z_STREAM_END);return a===tr.Z_STREAM_END&&(i=tr.Z_FINISH),i===tr.Z_FINISH?(a=Rc.inflateEnd(this.strm),this.onEnd(a),this.ended=true,a===tr.Z_OK):(i===tr.Z_SYNC_FLUSH&&(this.onEnd(tr.Z_OK),r.avail_out=0),true)};Bs.prototype.onData=function(e){this.chunks.push(e);};Bs.prototype.onEnd=function(e){e===tr.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Rd.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg;};function Yb(e,t){var r=new Bs(t);if(r.push(e,true),r.err)throw r.msg||Qb[r.err];return r.result}function $z(e,t){return t=t||{},t.raw=true,Yb(e,t)}Od.Inflate=Bs;Od.inflate=Yb;Od.inflateRaw=$z;Od.ungzip=Yb;});var sk=M((jie,ik)=>{var Iz=Oa().assign,Fz=cT(),Mz=ok(),jz=Xb(),ak={};Iz(ak,Fz,Mz,jz);ik.exports=ak;});var ck=M(eh=>{var Lz=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",Bz=sk(),lk=Wt(),Ym=bn(),zz=Lz?"uint8array":"array";eh.magic="\b\0";function zs(e,t){Ym.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={};}lk.inherits(zs,Ym);zs.prototype.processChunk=function(e){this.meta=e.meta,this._pako===null&&this._createPako(),this._pako.push(lk.transformTo(zz,e.data),false);};zs.prototype.flush=function(){Ym.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],true);};zs.prototype.cleanUp=function(){Ym.prototype.cleanUp.call(this),this._pako=null;};zs.prototype._createPako=function(){this._pako=new Bz[this._pakoAction]({raw:true,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta});};};eh.compressWorker=function(e){return new zs("Deflate",e)};eh.uncompressWorker=function(){return new zs("Inflate",{})};});var tx=M(ex=>{var uk=bn();ex.STORE={magic:"\0\0",compressWorker:function(){return new uk("STORE compression")},uncompressWorker:function(){return new uk("STORE decompression")}};ex.DEFLATE=ck();});var rx=M(Us=>{Us.LOCAL_FILE_HEADER="PK";Us.CENTRAL_FILE_HEADER="PK";Us.CENTRAL_DIRECTORY_END="PK";Us.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07";Us.ZIP64_CENTRAL_DIRECTORY_END="PK";Us.DATA_DESCRIPTOR="PK\x07\b";});var mk=M((Uie,pk)=>{var Oc=Wt(),Dc=bn(),nx=bc(),dk=$m(),th=rx(),Rt=function(e,t){var r="",n;for(n=0;n<t;n++)r+=String.fromCharCode(e&255),e=e>>>8;return r},Uz=function(e,t){var r=e;return e||(r=t?16893:33204),(r&65535)<<16},qz=function(e){return (e||0)&63},fk=function(e,t,r,n,o,a){var i=e.file,s=e.compression,l=a!==nx.utf8encode,c=Oc.transformTo("string",a(i.name)),u=Oc.transformTo("string",nx.utf8encode(i.name)),d=i.comment,m=Oc.transformTo("string",a(d)),h=Oc.transformTo("string",nx.utf8encode(d)),y=u.length!==i.name.length,p=h.length!==d.length,f,x,g="",v="",w="",N=i.dir,S=i.date,_={crc32:0,compressedSize:0,uncompressedSize:0};(!t||r)&&(_.crc32=e.crc32,_.compressedSize=e.compressedSize,_.uncompressedSize=e.uncompressedSize);var P=0;t&&(P|=8),!l&&(y||p)&&(P|=2048);var R=0,E=0;N&&(R|=16),o==="UNIX"?(E=798,R|=Uz(i.unixPermissions,N)):(E=20,R|=qz(i.dosPermissions)),f=S.getUTCHours(),f=f<<6,f=f|S.getUTCMinutes(),f=f<<5,f=f|S.getUTCSeconds()/2,x=S.getUTCFullYear()-1980,x=x<<4,x=x|S.getUTCMonth()+1,x=x<<5,x=x|S.getUTCDate(),y&&(v=Rt(1,1)+Rt(dk(c),4)+u,g+="up"+Rt(v.length,2)+v),p&&(w=Rt(1,1)+Rt(dk(m),4)+h,g+="uc"+Rt(w.length,2)+w);var C="";C+=`
9
- \0`,C+=Rt(P,2),C+=s.magic,C+=Rt(f,2),C+=Rt(x,2),C+=Rt(_.crc32,4),C+=Rt(_.compressedSize,4),C+=Rt(_.uncompressedSize,4),C+=Rt(c.length,2),C+=Rt(g.length,2);var b=th.LOCAL_FILE_HEADER+C+c+g,O=th.CENTRAL_FILE_HEADER+Rt(E,2)+C+Rt(m.length,2)+"\0\0\0\0"+Rt(R,4)+Rt(n,4)+c+g+m;return {fileRecord:b,dirRecord:O}},Vz=function(e,t,r,n,o){var a="",i=Oc.transformTo("string",o(n));return a=th.CENTRAL_DIRECTORY_END+"\0\0\0\0"+Rt(e,2)+Rt(e,2)+Rt(t,4)+Rt(r,4)+Rt(i.length,2)+i,a},Hz=function(e){var t="";return t=th.DATA_DESCRIPTOR+Rt(e.crc32,4)+Rt(e.compressedSize,4)+Rt(e.uncompressedSize,4),t};function ko(e,t,r,n){Dc.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=r,this.encodeFileName=n,this.streamFiles=e,this.accumulate=false,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[];}Oc.inherits(ko,Dc);ko.prototype.push=function(e){var t=e.meta.percent||0,r=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,Dc.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:r?(t+100*(r-n-1))/r:100}}));};ko.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var r=fk(e,t,false,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:r.fileRecord,meta:{percent:0}});}else this.accumulate=true;};ko.prototype.closedSource=function(e){this.accumulate=false;var t=this.streamFiles&&!e.file.dir,r=fk(e,t,true,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),t)this.push({data:Hz(e),meta:{percent:100}});else for(this.push({data:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null;};ko.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var r=this.bytesWritten-e,n=Vz(this.dirRecords.length,r,e,this.zipComment,this.encodeFileName);this.push({data:n,meta:{percent:100}});};ko.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume();};ko.prototype.registerPrevious=function(e){this._sources.push(e);var t=this;return e.on("data",function(r){t.processChunk(r);}),e.on("end",function(){t.closedSource(t.previous.streamInfo),t._sources.length?t.prepareNextSource():t.end();}),e.on("error",function(r){t.error(r);}),this};ko.prototype.resume=function(){if(!Dc.prototype.resume.call(this))return false;if(!this.previous&&this._sources.length)return this.prepareNextSource(),true;if(!this.previous&&!this._sources.length&&!this.generatedError)return this.end(),true};ko.prototype.error=function(e){var t=this._sources;if(!Dc.prototype.error.call(this,e))return false;for(var r=0;r<t.length;r++)try{t[r].error(e);}catch{}return true};ko.prototype.lock=function(){Dc.prototype.lock.call(this);for(var e=this._sources,t=0;t<e.length;t++)e[t].lock();};pk.exports=ko;});var gk=M(hk=>{var Jz=tx(),Wz=mk(),Kz=function(e,t){var r=e||t,n=Jz[r];if(!n)throw new Error(r+" is not a valid compression method !");return n};hk.generateWorker=function(e,t,r){var n=new Wz(t.streamFiles,r,t.platform,t.encodeFileName),o=0;try{e.forEach(function(a,i){o++;var s=Kz(i.options.compression,t.compression),l=i.options.compressionOptions||t.compressionOptions||{},c=i.dir,u=i.date;i._compressWorker(s,l).withStreamInfo("file",{name:a,dir:c,date:u,comment:i.comment||"",unixPermissions:i.unixPermissions,dosPermissions:i.dosPermissions}).pipe(n);}),n.entriesCount=o;}catch(a){n.error(a);}return n};});var vk=M((Vie,yk)=>{var Gz=Wt(),rh=bn();function Dd(e,t){rh.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=false,this._bindStream(t);}Gz.inherits(Dd,rh);Dd.prototype._bindStream=function(e){var t=this;this._stream=e,e.pause(),e.on("data",function(r){t.push({data:r,meta:{percent:0}});}).on("error",function(r){t.isPaused?this.generatedError=r:t.error(r);}).on("end",function(){t.isPaused?t._upstreamEnded=true:t.end();});};Dd.prototype.pause=function(){return rh.prototype.pause.call(this)?(this._stream.pause(),true):false};Dd.prototype.resume=function(){return rh.prototype.resume.call(this)?(this._upstreamEnded?this.end():this._stream.resume(),true):false};yk.exports=Dd;});var Tk=M((Hie,Pk)=>{var Zz=bc(),Ad=Wt(),_k=bn(),Xz=lb(),Sk=cb(),bk=Im(),Qz=x2(),Yz=gk(),xk=ld(),eU=vk(),Nk=function(e,t,r){var n=Ad.getTypeOf(t),o,a=Ad.extend(r||{},Sk);a.date=a.date||new Date,a.compression!==null&&(a.compression=a.compression.toUpperCase()),typeof a.unixPermissions=="string"&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&a.unixPermissions&16384&&(a.dir=true),a.dosPermissions&&a.dosPermissions&16&&(a.dir=true),a.dir&&(e=Ck(e)),a.createFolders&&(o=tU(e))&&Ek.call(this,o,true);var i=n==="string"&&a.binary===false&&a.base64===false;(!r||typeof r.binary>"u")&&(a.binary=!i);var s=t instanceof bk&&t.uncompressedSize===0;(s||a.dir||!t||t.length===0)&&(a.base64=false,a.binary=true,t="",a.compression="STORE",n="string");var l=null;t instanceof bk||t instanceof _k?l=t:xk.isNode&&xk.isStream(t)?l=new eU(e,t):l=Ad.prepareContent(e,t,a.binary,a.optimizedBinaryString,a.base64);var c=new Qz(e,l,a);this.files[e]=c;},tU=function(e){e.slice(-1)==="/"&&(e=e.substring(0,e.length-1));var t=e.lastIndexOf("/");return t>0?e.substring(0,t):""},Ck=function(e){return e.slice(-1)!=="/"&&(e+="/"),e},Ek=function(e,t){return t=typeof t<"u"?t:Sk.createFolders,e=Ck(e),this.files[e]||Nk.call(this,e,null,{dir:true,createFolders:t}),this.files[e]};function wk(e){return Object.prototype.toString.call(e)==="[object RegExp]"}var rU={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(e){var t,r,n;for(t in this.files)n=this.files[t],r=t.slice(this.root.length,t.length),r&&t.slice(0,this.root.length)===this.root&&e(r,n);},filter:function(e){var t=[];return this.forEach(function(r,n){e(r,n)&&t.push(n);}),t},file:function(e,t,r){if(arguments.length===1)if(wk(e)){var n=e;return this.filter(function(a,i){return !i.dir&&n.test(a)})}else {var o=this.files[this.root+e];return o&&!o.dir?o:null}else e=this.root+e,Nk.call(this,e,t,r);return this},folder:function(e){if(!e)return this;if(wk(e))return this.filter(function(o,a){return a.dir&&e.test(o)});var t=this.root+e,r=Ek.call(this,t),n=this.clone();return n.root=r.name,n},remove:function(e){e=this.root+e;var t=this.files[e];if(t||(e.slice(-1)!=="/"&&(e+="/"),t=this.files[e]),t&&!t.dir)delete this.files[e];else for(var r=this.filter(function(o,a){return a.name.slice(0,e.length)===e}),n=0;n<r.length;n++)delete this.files[r[n].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(e){var t,r={};try{if(r=Ad.extend(e||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:Zz.utf8encode}),r.type=r.type.toLowerCase(),r.compression=r.compression.toUpperCase(),r.type==="binarystring"&&(r.type="string"),!r.type)throw new Error("No output type specified.");Ad.checkSupport(r.type),(r.platform==="darwin"||r.platform==="freebsd"||r.platform==="linux"||r.platform==="sunos")&&(r.platform="UNIX"),r.platform==="win32"&&(r.platform="DOS");var n=r.comment||this.comment||"";t=Yz.generateWorker(this,r,n);}catch(o){t=new _k("error"),t.error(o);}return new Xz(t,r.type||"string",r.mimeType)},generateAsync:function(e,t){return this.generateInternalStream(e).accumulate(t)},generateNodeStream:function(e,t){return e=e||{},e.type||(e.type="nodebuffer"),this.generateInternalStream(e).toNodejsStream(t)}};Pk.exports=rU;});var ox=M((Jie,Rk)=>{var nU=Wt();function kk(e){this.data=e,this.length=e.length,this.index=0,this.zero=0;}kk.prototype={checkOffset:function(e){this.checkIndex(this.index+e);},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e;},skip:function(e){this.setIndex(this.index+e);},byteAt:function(){},readInt:function(e){var t=0,r;for(this.checkOffset(e),r=this.index+e-1;r>=this.index;r--)t=(t<<8)+this.byteAt(r);return this.index+=e,t},readString:function(e){return nU.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC((e>>25&127)+1980,(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(e&31)<<1))}};Rk.exports=kk;});var ax=M((Wie,Dk)=>{var Ok=ox(),oU=Wt();function Ac(e){Ok.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=e[t]&255;}oU.inherits(Ac,Ok);Ac.prototype.byteAt=function(e){return this.data[this.zero+e]};Ac.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),r=e.charCodeAt(1),n=e.charCodeAt(2),o=e.charCodeAt(3),a=this.length-4;a>=0;--a)if(this.data[a]===t&&this.data[a+1]===r&&this.data[a+2]===n&&this.data[a+3]===o)return a-this.zero;return -1};Ac.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),r=e.charCodeAt(1),n=e.charCodeAt(2),o=e.charCodeAt(3),a=this.readData(4);return t===a[0]&&r===a[1]&&n===a[2]&&o===a[3]};Ac.prototype.readData=function(e){if(this.checkOffset(e),e===0)return [];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};Dk.exports=Ac;});var Ik=M((Kie,$k)=>{var Ak=ox(),aU=Wt();function $c(e){Ak.call(this,e);}aU.inherits($c,Ak);$c.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)};$c.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero};$c.prototype.readAndCheckSignature=function(e){var t=this.readData(4);return e===t};$c.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};$k.exports=$c;});var sx=M((Gie,Mk)=>{var Fk=ax(),iU=Wt();function ix(e){Fk.call(this,e);}iU.inherits(ix,Fk);ix.prototype.readData=function(e){if(this.checkOffset(e),e===0)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};Mk.exports=ix;});var Bk=M((Zie,Lk)=>{var jk=sx(),sU=Wt();function lx(e){jk.call(this,e);}sU.inherits(lx,jk);lx.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};Lk.exports=lx;});var cx=M((Xie,Uk)=>{var nh=Wt(),zk=ka(),lU=ax(),cU=Ik(),uU=Bk(),dU=sx();Uk.exports=function(e){var t=nh.getTypeOf(e);return nh.checkSupport(t),t==="string"&&!zk.uint8array?new cU(e):t==="nodebuffer"?new uU(e):zk.uint8array?new dU(nh.transformTo("uint8array",e)):new lU(nh.transformTo("array",e))};});var Jk=M((Qie,Hk)=>{var ux=cx(),$i=Wt(),fU=Im(),qk=$m(),oh=bc(),ah=tx(),pU=ka(),mU=0,hU=3,gU=function(e){for(var t in ah)if(Object.prototype.hasOwnProperty.call(ah,t)&&ah[t].magic===e)return ah[t];return null};function Vk(e,t){this.options=e,this.loadOptions=t;}Vk.prototype={isEncrypted:function(){return (this.bitFlag&1)===1},useUTF8:function(){return (this.bitFlag&2048)===2048},readLocalPart:function(e){var t,r;if(e.skip(22),this.fileNameLength=e.readInt(2),r=e.readInt(2),this.fileName=e.readData(this.fileNameLength),e.skip(r),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(t=gU(this.compressionMethod),t===null)throw new Error("Corrupted zip : compression "+$i.pretty(this.compressionMethod)+" unknown (inner file : "+$i.transformTo("string",this.fileName)+")");this.decompressed=new fU(this.compressedSize,this.uncompressedSize,this.crc32,t,e.readData(this.compressedSize));},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength);},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(this.externalFileAttributes&16),e===mU&&(this.dosPermissions=this.externalFileAttributes&63),e===hU&&(this.unixPermissions=this.externalFileAttributes>>16&65535),!this.dir&&this.fileNameStr.slice(-1)==="/"&&(this.dir=true);},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=ux(this.extraFields[1].value);this.uncompressedSize===$i.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===$i.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===$i.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===$i.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4));}},readExtraFields:function(e){var t=e.index+this.extraFieldsLength,r,n,o;for(this.extraFields||(this.extraFields={});e.index+4<t;)r=e.readInt(2),n=e.readInt(2),o=e.readData(n),this.extraFields[r]={id:r,length:n,value:o};e.setIndex(t);},handleUTF8:function(){var e=pU.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=oh.utf8decode(this.fileName),this.fileCommentStr=oh.utf8decode(this.fileComment);else {var t=this.findExtraFieldUnicodePath();if(t!==null)this.fileNameStr=t;else {var r=$i.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(r);}var n=this.findExtraFieldUnicodeComment();if(n!==null)this.fileCommentStr=n;else {var o=$i.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(o);}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=ux(e.value);return t.readInt(1)!==1||qk(this.fileName)!==t.readInt(4)?null:oh.utf8decode(t.readData(e.length-5))}return null},findExtraFieldUnicodeComment:function(){var e=this.extraFields[25461];if(e){var t=ux(e.value);return t.readInt(1)!==1||qk(this.fileComment)!==t.readInt(4)?null:oh.utf8decode(t.readData(e.length-5))}return null}};Hk.exports=Vk;});var Gk=M((Yie,Kk)=>{var yU=cx(),Ia=Wt(),Ro=rx(),vU=Jk(),bU=ka();function Wk(e){this.files=[],this.loadOptions=e;}Wk.prototype={checkSignature:function(e){if(!this.reader.readAndCheckSignature(e)){this.reader.index-=4;var t=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+Ia.pretty(t)+", expected "+Ia.pretty(e)+")")}},isSignature:function(e,t){var r=this.reader.index;this.reader.setIndex(e);var n=this.reader.readString(4),o=n===t;return this.reader.setIndex(r),o},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var e=this.reader.readData(this.zipCommentLength),t=bU.uint8array?"uint8array":"array",r=Ia.transformTo(t,e);this.zipComment=this.loadOptions.decodeFileName(r);},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var e=this.zip64EndOfCentralSize-44,t=0,r,n,o;t<e;)r=this.reader.readInt(2),n=this.reader.readInt(4),o=this.reader.readData(n),this.zip64ExtensibleData[r]={id:r,length:n,value:o};},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var e,t;for(e=0;e<this.files.length;e++)t=this.files[e],this.reader.setIndex(t.localHeaderOffset),this.checkSignature(Ro.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes();},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(Ro.CENTRAL_FILE_HEADER);)e=new vU({zip64:this.zip64},this.loadOptions),e.readCentralPart(this.reader),this.files.push(e);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var e=this.reader.lastIndexOfSignature(Ro.CENTRAL_DIRECTORY_END);if(e<0){var t=!this.isSignature(0,Ro.LOCAL_FILE_HEADER);throw t?new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"):new Error("Corrupted zip: can't find end of central directory")}this.reader.setIndex(e);var r=e;if(this.checkSignature(Ro.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===Ia.MAX_VALUE_16BITS||this.diskWithCentralDirStart===Ia.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===Ia.MAX_VALUE_16BITS||this.centralDirRecords===Ia.MAX_VALUE_16BITS||this.centralDirSize===Ia.MAX_VALUE_32BITS||this.centralDirOffset===Ia.MAX_VALUE_32BITS){if(this.zip64=true,e=this.reader.lastIndexOfSignature(Ro.ZIP64_CENTRAL_DIRECTORY_LOCATOR),e<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(e),this.checkSignature(Ro.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,Ro.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(Ro.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(Ro.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral();}var n=this.centralDirOffset+this.centralDirSize;this.zip64&&(n+=20,n+=12+this.zip64EndOfCentralSize);var o=r-n;if(o>0)this.isSignature(r,Ro.CENTRAL_FILE_HEADER)||(this.reader.zero=o);else if(o<0)throw new Error("Corrupted zip: missing "+Math.abs(o)+" bytes.")},prepareReader:function(e){this.reader=yU(e);},load:function(e){this.prepareReader(e),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles();}};Kk.exports=Wk;});var Qk=M((ese,Xk)=>{var dx=Wt(),ih=gc(),xU=bc(),wU=Gk(),_U=fb(),Zk=ld();function SU(e){return new ih.Promise(function(t,r){var n=e.decompressed.getContentWorker().pipe(new _U);n.on("error",function(o){r(o);}).on("end",function(){n.streamInfo.crc32!==e.decompressed.crc32?r(new Error("Corrupted zip : CRC32 mismatch")):t();}).resume();})}Xk.exports=function(e,t){var r=this;return t=dx.extend(t||{},{base64:false,checkCRC32:false,optimizedBinaryString:false,createFolders:false,decodeFileName:xU.utf8decode}),Zk.isNode&&Zk.isStream(e)?ih.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):dx.prepareContent("the loaded zip file",e,true,t.optimizedBinaryString,t.base64).then(function(n){var o=new wU(t);return o.load(n),o}).then(function(o){var a=[ih.Promise.resolve(o)],i=o.files;if(t.checkCRC32)for(var s=0;s<i.length;s++)a.push(SU(i[s]));return ih.Promise.all(a)}).then(function(o){for(var a=o.shift(),i=a.files,s=0;s<i.length;s++){var l=i[s],c=l.fileNameStr,u=dx.resolve(l.fileNameStr);r.file(u,l.decompressed,{binary:true,optimizedBinaryString:true,date:l.date,dir:l.dir,comment:l.fileCommentStr.length?l.fileCommentStr:null,unixPermissions:l.unixPermissions,dosPermissions:l.dosPermissions,createFolders:t.createFolders}),l.dir||(r.file(u).unsafeOriginalName=c);}return a.zipComment.length&&(r.comment=a.zipComment),r})};});var eR=M((tse,Yk)=>{function Wn(){if(!(this instanceof Wn))return new Wn;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var e=new Wn;for(var t in this)typeof this[t]!="function"&&(e[t]=this[t]);return e};}Wn.prototype=Tk();Wn.prototype.loadAsync=Qk();Wn.support=ka();Wn.defaults=cb();Wn.version="3.10.1";Wn.loadAsync=function(e,t){return new Wn().loadAsync(e,t)};Wn.external=gc();Yk.exports=Wn;});var Zr=class extends Error{constructor(t,r,n,o){super(t,n),this.name=new.target.name,this.code=r,this.extras=o||{},Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.technicalMessage=`${this.name}[${this.code}] - Extras: ${JSON.stringify(this.extras,null,2)}`;}};var ji=class extends Zr{constructor(t){super("ConflictError","FIELD_CONFLICT",void 0,t);}};var Li=class extends Zr{constructor(t){super("Plan limit exceeded, redirecting to billing page...","PLAN_LIMIT_EXCEEDED",void 0,t);}},Bi=class extends Zr{constructor(t){super("Credit limit exceeded. Please increase your limit to continue.","CREDIT_LIMIT_EXCEEDED",void 0,t);}};var Ua=class extends Error{constructor(t,r,n){super(t),this.name=new.target.name,this.statusCode=r,n&&(this.code=n),this.toString=()=>`HTTP ${this.statusCode} error: ${this.code} - ${this.message}`;}};var Zd=class extends Zr{constructor(r="The requested resource was not found",n){super(r,"NOT_FOUND");this.resource=n;this.statusCode=404;this.name="NotFoundError";}toString(){let r=this.resource?` (${this.resource})`:"";return `${this.name}: ${this.message}${r}`}};var Js=class extends Zr{constructor(t){super("Too many pages","TOO_MANY_PAGES",void 0,t);}},Ws=class extends Zr{constructor(t){super("File is too large","FILE_TOO_LARGE",void 0,t);}};function Xr(e){if(e instanceof Zr)return e instanceof ji?{type:"client_error",isRetryable:false,userMessage:"There was a conflict with recent changes. Please refresh and try again.",technicalMessage:`Conflict error: ${e.message}`}:e instanceof Li?{type:"client_error",isRetryable:false,userMessage:"You have reached your plan limit.",technicalMessage:`Plan limit error: ${e.message}`}:e instanceof Bi?{type:"client_error",isRetryable:false,userMessage:"You have reached your credit limit. Increase your limit in settings or contact support.",technicalMessage:`Credit limit error: ${e.message}`}:e instanceof Zd?{type:"client_error",isRetryable:false,userMessage:"The page you are looking for does not exist.",technicalMessage:`Not found error: ${e.message}`}:e instanceof Ua?{type:"client_error",isRetryable:false,userMessage:"Request failed. Please try again.",technicalMessage:`HTTP error: ${e.message}`}:e instanceof Ws?{type:"client_error",isRetryable:false,userMessage:"File is too large",technicalMessage:`File too large error: ${e.message}`}:e instanceof Js?{type:"client_error",isRetryable:false,userMessage:"File has too many pages",technicalMessage:`Too many pages error: ${e.message}`}:{type:"client_error",isRetryable:false,userMessage:"An error occurred. Please try again.",technicalMessage:`Retab error: ${e.message}`};if(e.name==="TypeError"&&e.message.includes("Failed to fetch")){let t=typeof navigator<"u"&&navigator.onLine===false;return {type:"network_error",isRetryable:true,userMessage:t?"You appear to be offline. Please check your internet connection.":"Cannot reach the server. Retrying...",technicalMessage:t?"Browser reports offline status":"Network fetch failed \u2013 server unreachable"}}if(e.message?.includes("CORS")||e.message?.includes("Access-Control-Allow-Origin"))return {type:"cors_error",isRetryable:true,userMessage:"Connection issue. Retrying...",technicalMessage:"CORS error \u2013 likely offline or network connectivity issue"};if(e.name==="AbortError"||e.message?.includes("timeout"))return {type:"timeout_error",isRetryable:true,userMessage:"Request timed out. Retrying...",technicalMessage:"Request timeout or abort signal"};if(e.code||e instanceof Ua&&e.code){let t=e.code||(e instanceof Ua?e.code:void 0);if(t==="OPENAI_STREAMING_ERROR")return {type:"server_error",isRetryable:true,userMessage:"AI service temporarily unavailable. Retrying...",technicalMessage:`OpenAI streaming error: ${e.message||"Unknown streaming issue"}`};if(t==="OPENAI_RATE_LIMIT_ERROR")return {type:"server_error",isRetryable:true,userMessage:"AI service rate limited. Retrying...",technicalMessage:`OpenAI rate limit: ${e.message||"Rate limit exceeded"}`}}if(e.status||e.response?.status||e.statusCode){let t=e.statusCode??e.status??e.response.status;if(t===401||t===403)return {type:"auth_error",isRetryable:false,userMessage:"Authentication required. Please sign in again.",technicalMessage:`Authentication error: ${t}`};if(t===409)return {type:"client_error",isRetryable:false,userMessage:e.message||"Request conflict. Please check and try again.",technicalMessage:`Client conflict: ${t}`};if(t>=500)return {type:"server_error",isRetryable:true,userMessage:"Server temporarily unavailable. Retrying...",technicalMessage:`Server error: ${t}`};if(t>=400)return {type:"client_error",isRetryable:false,userMessage:"Request error. Please check your input.",technicalMessage:`Client error: ${t}`}}return {type:"unknown_error",isRetryable:false,userMessage:"An unexpected error occurred.",technicalMessage:e.message||"Unknown error"}}var IO=new Map;function Jc(e){let t=Xr(e);e instanceof Li||e instanceof Bi||e instanceof ji?console.warn(`[${t.type.toUpperCase()}] ${t.technicalMessage}:`,e):console.error(`[${t.type.toUpperCase()}] ${t.technicalMessage}:`,e);let r=false;if(e instanceof Error)for(let[n,o]of IO)e instanceof n&&(o.forEach(a=>{try{a(e,t);}catch(i){console.error("[ErrorManager] Handler threw:",i);}}),r=true);if(r||t.isRetryable||toast.error(t.userMessage),t.type==="auth_error"&&typeof window<"u")try{window.dispatchEvent(new CustomEvent("auth-required",{detail:{source:"error-manager"}}));}catch{}return t}kt__default.createContext(null);async function Tt(e,t){if(e.ok)throw new Error("Response is OK, but an error was expected");let n=(await e.json().catch(()=>({}))).detail,o=n?.code;switch(o){case "FIELD_CONFLICT":return new ji(n.details);case "PLAN_LIMIT_EXCEEDED":return new Li(n.details);case "CREDIT_LIMIT_EXCEEDED":return new Bi(n.details);case "FILE_TOO_LARGE":return new Ws(n.details);case "TOO_MANY_PAGES":return new Js(n.details);default:return new Ua(n?.message||t||e.statusText||"Unknown error",e.status,o)}}var Wx=createContext(null);function De(){let e=useContext(Wx);if(!e)throw new Error("useAuth must be used within a AuthProvider");return e}var BO="https://api.retab.com",zO=6e4,UO=3,qO=1e3;function Lh(e){if(e instanceof TypeError&&e.message.includes("fetch"))return true;if(e instanceof Error){let t=e.message.toLowerCase();return t.includes("network")||t.includes("failed to fetch")||t.includes("net::")||t.includes("offline")||t.includes("connection")||t.includes("timeout")}return false}function VO(e){return Lh(e)?"NETWORK_ERROR":e instanceof Error&&e.message.includes("token")?"TOKEN_FETCH_FAILED":"UNKNOWN"}function HO(e){return new Promise(t=>setTimeout(t,e))}function Kx({children:e,config:t,queryClient:r}){let n=useRef(null),o=useRef(null),a=useRef(false),i=useRef(0),[s,l]=useState(null),[c,u]=useState(typeof navigator<"u"?navigator.onLine:true),[d,m]=useState(false),h=t.maxRetries??UO,y=t.retryBaseDelay??qO;useEffect(()=>{let P=()=>{console.log("[AuthProvider] Network connection restored"),u(true),l(E=>E?.code==="NETWORK_ERROR"?null:E),i.current=0;},R=()=>{console.log("[AuthProvider] Network connection lost"),u(false);};return typeof window<"u"&&(window.addEventListener("online",P),window.addEventListener("offline",R)),()=>{typeof window<"u"&&(window.removeEventListener("online",P),window.removeEventListener("offline",R));}},[]),useEffect(()=>{if(c&&s?.code==="NETWORK_ERROR"){console.log("[AuthProvider] Online again, retrying token fetch...");let P=setTimeout(()=>{n.current=null,i.current=0,l(null);},500);return ()=>clearTimeout(P)}},[c,s]);let p=useMemo(()=>r??new QueryClient({defaultOptions:{queries:{staleTime:1e3*60*5,refetchOnWindowFocus:false,retry:(P,R)=>R instanceof Error&&R.message.includes("401")?false:Lh(R)?P<5:P<3,retryDelay:P=>Math.min(1e3*2**P,3e4)}}}),[r]),f=t.baseUrl??BO,x=useCallback(async()=>{let P;for(let C=0;C<=h;C++)try{if(typeof navigator<"u"&&!navigator.onLine)throw new Error("Network offline");let b=await t.getToken();l(null),i.current=0;let D=Date.now()+3300*1e3;try{let k=b.split(".");if(k.length===3){let I=JSON.parse(atob(k[1]));typeof I.exp=="number"&&(D=I.exp*1e3-zO);}}catch{}return n.current={token:b,expiresAt:D},b}catch(b){if(P=b,i.current=C+1,console.warn(`[AuthProvider] Token fetch attempt ${C+1}/${h+1} failed:`,b instanceof Error?b.message:b),typeof navigator<"u"&&!navigator.onLine)break;if(C<h){let O=y*Math.pow(2,C),D=Math.random()*500;console.log(`[AuthProvider] Retrying in ${O+D}ms...`),await HO(O+D);}}let R=VO(P),E={message:P instanceof Error?P.message:"Token fetch failed",code:R,timestamp:Date.now(),retryCount:i.current};throw l(E),console.error("[AuthProvider] Token fetch failed after all retries:",E),P},[t.getToken,h,y]),g=useCallback(async()=>{let P=Date.now();return n.current&&P<n.current.expiresAt?n.current.token:(o.current||(m(true),o.current=x().finally(()=>{o.current=null,m(false);})),o.current)},[x]),v=useCallback(async()=>({Authorization:`Bearer ${await g()}`}),[g]),w=useCallback(async(P,R={})=>{let E=P.startsWith("http")?P:`${f}${P}`;try{let C=await v(),b=new Headers(R.headers);Object.entries(C).forEach(([D,k])=>{b.set(D,k);});let O=await fetch(E,{...R,headers:b});if(O.status===401){console.log("[AuthProvider] Received 401, refreshing token..."),n.current=null,i.current=0;try{let D=await v(),k=new Headers(R.headers);return Object.entries(D).forEach(([I,F])=>{k.set(I,F);}),fetch(E,{...R,headers:k})}catch(D){throw l({message:"Session expired. Please refresh the page.",code:"AUTH_EXPIRED",timestamp:Date.now(),retryCount:i.current}),D}}return O}catch(C){throw Lh(C)&&(console.error("[AuthProvider] Network error during fetch:",C),l({message:"Network error. Check your connection.",code:"NETWORK_ERROR",timestamp:Date.now(),retryCount:i.current})),C}},[f,v]),N=useCallback(async()=>{n.current=null,i.current=0,l(null),await g();},[g]),S=useCallback(async()=>{console.log("[AuthProvider] Manual retry initiated"),n.current=null,i.current=0,l(null);try{await g(),p.invalidateQueries();}catch(P){console.error("[AuthProvider] Manual retry failed:",P);}},[g,p]);useEffect(()=>{let P=async()=>{if(!a.current){a.current=true;try{n.current=null,await g(),p.invalidateQueries();}catch(R){console.error("[AuthProvider] Failed to refresh token:",R);}finally{a.current=false;}}};return typeof window<"u"&&window.addEventListener("auth-required",P),()=>{typeof window<"u"&&window.removeEventListener("auth-required",P);}},[g,p]);let _=useMemo(()=>({baseUrl:f,getAuthHeaders:v,fetchWithAuth:w,refreshToken:N,authError:s,isOnline:c,isAuthenticating:d,retryAuth:S}),[f,v,w,N,s,c,d,S]);return jsx(QueryClientProvider,{client:p,children:jsx(Wx.Provider,{value:_,children:e})})}var Gt={all:["projects"],lists:()=>[...Gt.all,"list"],list:e=>[...Gt.lists(),{filters:e}],details:()=>[...Gt.all,"detail"],detail:e=>[...Gt.details(),e],builderDocuments:e=>[...Gt.detail(e),"builder-documents"],builderDocument:(e,t)=>[...Gt.builderDocuments(e),t]};var Gx=e=>{let{fetchWithAuth:t}=De();return useQuery({queryKey:Gt.detail(e),queryFn:async()=>{let r=await t(`/v1/projects/${e}`);if(!r.ok)throw await Tt(r,"Failed to fetch project");return r.json()},enabled:!!e,refetchInterval:300*1e3,refetchIntervalInBackground:false,structuralSharing:false,throwOnError:r=>Xr(r).type!=="auth_error"})};var Zx=()=>{let e=useQueryClient(),{fetchWithAuth:t}=De();return useMutation({mutationFn:async r=>{let{projectId:n,request:o}=r;if(!n)throw new Error("Project ID is required");let a=await t(`/v1/projects/${n}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!a.ok)throw await Tt(a,`Failed to update project ${n}`);return a.json()},onSuccess:(r,{projectId:n})=>{e.setQueryData(Gt.detail(n),r),e.invalidateQueries({queryKey:Gt.lists()});},onError:r=>{Jc(r);}})},Xx=()=>{let e=useQueryClient(),{fetchWithAuth:t}=De();return useMutation({mutationFn:async r=>{let n=await t(`/v1/projects/${r}`,{method:"DELETE"});if(!n.ok)throw await Tt(n,"Failed to delete project")},onSuccess:(r,n)=>{e.removeQueries({queryKey:Gt.detail(n)}),e.invalidateQueries({queryKey:Gt.lists()});},onError:r=>{Jc(r);}})},Qx=()=>{let e=useQueryClient(),{fetchWithAuth:t}=De();return useMutation({mutationFn:async r=>{let{projectId:n,request:o}=r,a=await t(`/v1/projects/${n}/duplicate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o??{})});if(!a.ok)throw await Tt(a,"Failed to duplicate project");return a.json()},onSuccess:r=>{e.setQueryData(Gt.detail(r.id),r),e.invalidateQueries({queryKey:Gt.lists()});},onError:r=>Jc(r)})},Yx=()=>{let e=useQueryClient(),{fetchWithAuth:t}=De();return useMutation({mutationFn:async r=>{let{projectId:n,request:o}=r,a=await t(`/v1/projects/${n}/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!a.ok)throw await Tt(a,"Failed to rename project");return a.json()},onSuccess:r=>{e.setQueryData(Gt.detail(r.id),r),e.invalidateQueries({queryKey:Gt.lists()});},onError:r=>Jc(r)})};function T(...e){return twMerge(clsx(e))}var zi=cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",destructive:"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9",iconSm:"size-8",iconXs:"size-6"}},defaultVariants:{variant:"default",size:"default"}});function V({className:e,variant:t,size:r,asChild:n=false,...o}){return jsx(n?Slot:"button",{"data-slot":"button",className:T(zi({variant:t,size:r,className:e})),...o})}var rw=createContext(void 0),tw=e=>JSON.stringify(e);function nw({children:e}){let{fetchWithAuth:t}=De(),[r,n]=useState({}),o=useRef({}),[a,i]=useState(()=>{if(typeof window>"u")return {};try{let C=sessionStorage.getItem("ocrFileUrls");return C?JSON.parse(C):{}}catch{return {}}}),s=useRef(new Set),l=useRef({}),[c,u]=useState(0),d=useRef(new Set),m=useQueryClient(),h=async(C,b,O,D,k)=>{try{let I=await t("/v1/documents/compute_field_locations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file_id:k,data:D,method:"bm25"})});if(!I.ok)throw new Error(`Failed to compute ${O} field locations`);let F=await I.json();if(F.status==="success"){let pe=b==="ground_truth"||O==="dataset"||O==="playground"?`${C}_ground_truth`:`${C}_extraction_${O}`;return n(ie=>{let J={...ie};return delete J[pe],J}),F.field_locations}}catch(I){console.error(`[computeFieldLocations] FAILED for ${O}:`,I);let F=b==="ground_truth"||O==="dataset"||O==="playground",Z=F?`${C}_ground_truth`:`${C}_extraction_${O}`;n(pe=>({...pe,[Z]:`Failed to compute ${F?"ground truth":O} sources. ${I.message||"Please try again."}`}));}return null},y=(C,b)=>{let O=`${C}_${b}`;return r[O]||null},p=(C,b,O)=>{let k=b==="ground_truth"||O==="dataset"||O==="playground"?`${C}_ground_truth`:`${C}_extraction_${O}`;return r[k]||null},f=(C,b)=>{let O=`${C}_${b}`;n(D=>{let k={...D};return delete k[O],k});},x=(C,b,O)=>{let k=b==="ground_truth"||O==="dataset"||O==="playground"?`${C}_ground_truth`:`${C}_extraction_${O}`;n(I=>{let F={...I};return delete F[k],F});},g=useCallback(async(C,b=true)=>{if(!o.current[C]){o.current[C]=true;try{let O=await t("/v1/documents/perform_ocr",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file_id:C})});if(!O.ok)throw new Error(`OCR request failed: ${O.statusText}`);let k=(await O.json()).ocr_file_url;k&&i(I=>({...I,[C]:k})),b&&toast.success("OCR completed successfully");}catch(O){console.error("[performOCR] OCR request failed:",O),b&&toast.error(O.message||"Failed to perform OCR processing");}finally{o.current[C]=false;}}},[m]),v=useCallback(C=>o.current[C]||false,[]),w=useCallback((C,b)=>{if(b.includes("dataset")||b.includes("builder")||b.includes("playground")){let k=`${C}_ground_truth`,I=l.current[k];return I?I.fieldLocations:null}let O=`${C}_extraction_${b}`,D=l.current[O];return D?D.fieldLocations:null},[c]),N=useCallback((C,b,O)=>{if(b==="ground_truth"){let I=`${C}_ground_truth`,F=l.current[I];return F?F.fieldLocations:null}if(O.includes("dataset")||O.includes("builder")||O.includes("playground")){let I=`${C}_ground_truth`,F=l.current[I];return F?F.fieldLocations:null}let D=`${C}_extraction_${O}`,k=l.current[D];return k?k.fieldLocations:null},[c]),S=useCallback((C,b)=>{if(b.includes("dataset")||b.includes("builder")||b.includes("playground")){let D=`${C}_ground_truth`;return !l.current[D]}else {let D=`${C}_extraction_${b}`;return !l.current[D]}},[c]),_=useCallback(async C=>{C&&(a[C]||s.current.has(C)||(s.current.add(C),g(C,false).finally(()=>{s.current.delete(C);})));},[g,a]),P=useCallback(async C=>{try{i(b=>{let O={...b};return delete O[C],O}),await g(C,!1);}catch(b){console.error("[refreshOCRUrl] Failed to refresh OCR URL for",C,b);}},[g]);useEffect(()=>{if(!(typeof window>"u"))try{sessionStorage.setItem("ocrFileUrls",JSON.stringify(a));}catch{}},[a]);let R=useCallback(async(C,b,O,D)=>{if(!C)return;let k=b&&Object.keys(b).length>0,F=D.includes("dataset")||D.includes("builder")||D.includes("playground")?`${C}_ground_truth`:`${C}_extraction_${D}`,Z=tw(b),pe=l.current[F],ie=d.current.has(F),J=!pe||pe.dataHash!==Z;k&&J&&!ie&&(d.current.add(F),h(C,"ground_truth",D,b,O).then(re=>{re&&(l.current[F]={fieldLocations:re,dataHash:Z},u(X=>X+1));}).catch(re=>{console.error("[autoComputeFieldLocations] Error during computation:",re);}).finally(()=>{d.current.delete(F);}));},[h,tw]),E=useMemo(()=>({computeFieldLocations:h,getFieldLocationsError:y,clearFieldLocationsError:f,getFieldLocationsErrorByType:p,clearFieldLocationsErrorByType:x,isPerformingOCR:v,performOCR:g,ocrFileUrls:a,getInMemoryFieldLocations:w,getInMemoryFieldLocationsByType:N,inMemoryFieldLocationsRef:l,counterFieldLocationUpdated:c,setCounterFieldLocationUpdated:u,isInitializingFieldLocations:S,autoPerformOCR:_,autoComputeFieldLocations:R,refreshOCRUrl:P}),[h,y,f,p,x,v,g,a,w,N,l,c,u,S,_,R,P]);return jsx(rw.Provider,{value:E,children:e})}function Ui(){let e=useContext(rw);if(!e)throw console.error("[useOCR] Context is undefined! useOCR must be used within an OCRProvider"),new Error("useOCR must be used within an OCRProvider");return e}var tf=e=>!!(e.startsWith("image/")||e==="application/pdf"||e==="application/octet-stream"||["application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.oasis.opendocument.spreadsheet","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.oasis.opendocument.text","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.oasis.opendocument.presentation"].includes(e)||e.startsWith("text/")||e==="text/html"||e==="message/rfc822"||e==="application/json"||e==="application/xml"||e==="application/yaml"||e.startsWith("audio/"));var iw=createContext(void 0),lD={id:"default_project",name:"Project",is_schema_generated:true,updated_at:new Date().toISOString(),published_config:{inference_settings:{model:"auto-small",temperature:.5,reasoning_effort:"minimal",image_resolution_dpi:192,n_consensus:1},computation_spec:{computations:{}},json_schema:{},human_in_the_loop_criteria:[{path:"",agentic_fix:false}],origin:"manual"},draft_config:{inference_settings:{model:"auto-small",temperature:.5,reasoning_effort:"minimal",image_resolution_dpi:192,n_consensus:1},json_schema:{},human_in_the_loop_criteria:[],computation_spec:{computations:{}}},is_published:false},aw=e=>JSON.stringify(e);function sw({children:e,projectId:t}){let r=useQueryClient(),{fetchWithAuth:n}=De(),o=Gx(t),a=Zx(),i=Xx(),s=Qx(),l=Yx(),{computeFieldLocations:c,inMemoryFieldLocationsRef:u,setCounterFieldLocationUpdated:d}=Ui(),m=useRef(new Set),h=useRef(new Set),y=kt.useMemo(()=>o.data!==void 0&&!o.isLoading?o.data:{...lD,id:t},[o.data,o.isLoading,t]),p=useCallback(async(b,O)=>{if(O?.optimistic??false){let I=r.getQueryData(Gt.detail(t));if(I){let F={...I,...b,draft_config:b.draft_config?{...I.draft_config,...b.draft_config,json_schema:b.draft_config.json_schema||I.draft_config?.json_schema}:I.draft_config};r.setQueryData(Gt.detail(t),F);}}return await a.mutateAsync({projectId:t,request:b})},[t,a,r]),f=useCallback(async b=>{await i.mutateAsync(b);},[i]),x=useCallback(async b=>await s.mutateAsync({projectId:t,request:b}),[t,s]),g=useCallback(async b=>await l.mutateAsync({projectId:t,request:{name:b}}),[t,l]),v=useCallback(async b=>{let O=b?`?origin=${encodeURIComponent(b)}`:"",D=await n(`/v1/projects/${t}/publish${O}`,{method:"POST"});if(!D.ok)throw await Tt(D,"Failed to publish project");let k=await D.json();return r.setQueryData(Gt.detail(t),k),r.invalidateQueries({queryKey:Gt.lists()}),k},[t,r]),w=useCallback(async()=>{let b=await n(`/v1/projects/${t}/unpublish`,{method:"POST"});if(!b.ok)throw await Tt(b,"Failed to unpublish project");let O=await b.json();return r.setQueryData(Gt.detail(t),O),r.invalidateQueries({queryKey:Gt.lists()}),O},[t,r]),N=useCallback(()=>{o.refetch();},[o]),S=useCallback(async()=>{},[]),_=useCallback(async(b,O)=>{if(!b.id)return;let D=b.prediction_data.prediction&&Object.keys(b.prediction_data.prediction).length>0,k=`${b.id}_ground_truth`,I=aw(b.prediction_data.prediction),F=u.current[k],Z=m.current.has(k),pe=!F||F.dataHash!==I;D&&pe&&!Z&&(m.current.add(k),c(b.id,"ground_truth",O,b.prediction_data.prediction,b.mime_data.id).then(J=>{J&&(u.current[k]={fieldLocations:J,dataHash:I},d(ue=>ue+1));}).catch(console.error).finally(()=>{m.current.delete(k);}));},[c,u,d]),P=useCallback(async(b,O)=>{let D=b.prediction_data.prediction&&Object.keys(b.prediction_data.prediction).length>0,k=`${b.id}_extraction_${O}`,I=aw(b.prediction_data.prediction),F=u.current[k],Z=h.current.has(k),pe=!F||F.dataHash!==I;D&&!Z&&pe&&(h.current.add(k),c(b.id,"extraction",O,b.prediction_data.prediction,b.mime_data.id).then(J=>{J&&(u.current[k]={fieldLocations:J,dataHash:I},d(ue=>ue+1));}).catch(console.error).finally(()=>{h.current.delete(k);}));},[c,u,d]),R=useCallback(async b=>{if(!b||Object.keys(b).length===0)return b;let O=await n(`/v1/projects/${t}/apply-computations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:b})});if(!O.ok)throw await Tt(O,"Failed to apply computations");return (await O.json())?.data??b},[t]),E=kt.useMemo(()=>{if(o.error){let b=Xr(o.error);if(!b.isRetryable&&b.type!=="auth_error")throw o.error}return {project:y,isLoading:o.isLoading,isError:!!o.error,error:o.error,updateProject:p,deleteProject:f,duplicateProject:x,renameProject:g,publishProject:v,unpublishProject:w,refreshProject:N,batchPerformOCR:S,autoComputeNonIterationFieldLocations:_,autoComputeIterationFieldLocations:P,applyComputations:R}},[y,o.isLoading,o.error,p,f,x,g,v,N,S,_,P,R]),C=o.error?Xr(o.error):null;return jsxs(iw.Provider,{value:E,children:[C&&C.isRetryable&&C.type!=="auth_error"&&jsxs("div",{className:"bg-amber-50 border-b border-amber-200 p-2 text-amber-800 text-sm flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("span",{children:typeof navigator<"u"&&navigator.onLine===false?"You are offline.":"Connection issue."}),jsx("span",{className:"opacity-80",children:"Retrying\u2026"})]}),jsxs(V,{variant:"outline",size:"sm",onClick:()=>o.refetch(),disabled:o.isRefetching,className:"h-7 px-2",children:[jsx(RefreshCw,{className:`h-3.5 w-3.5 mr-1 ${o.isRefetching?"animate-spin":""}`}),"Retry now"]})]}),e]})}function Qr(){let e=useContext(iw);if(e===void 0)throw new Error("useProject must be used within a ProjectProvider");return e}var Z_=Hc(Lf()),X_=Hc(q_()),Q_=Hc(W_()),Y_=Hc(Ey());var Hf=structuredClone(Y_.default);Hf.$id="http://retab-json-schema.org/draft-07/enriched-schema#";function eS(e){if(e&&typeof e=="object"){e.type==="object"&&(e.propertyNames={type:"string",pattern:"^(?![-+]?(\\d+(\\.\\d*)?|\\.\\d+)$).+"});for(let t of Object.keys(e))typeof e[t]=="object"&&eS(e[t]);}}eS(Hf);set(Hf,"properties.additionalProperties",{const:false});var tS=createContext(void 0),Jf=new Z_.default({allErrors:true});(0, X_.default)(Jf);(0, Q_.default)(Jf);var G_=Jf.compile(Hf);function rS({jsonSchema:e,setJsonSchema:t,computedSchema:r,layoutSchema:n,persistJsonSchemaCallback:o,children:a}){let i=e,s=r??e,[l,c]=useState(),[u,d]=useState(true),[m,h]=useState(0),y=useRef(i);useEffect(()=>{y.current=i;},[i]);let p=useCallback((w,N)=>{if(!w||!N||typeof w!="object"||typeof N!="object")return false;if(w.properties&&N.properties){let S=Object.keys(w.properties),_=Object.keys(N.properties);if(S.length===_.length){for(let P=0;P<S.length;P++)if(S[P]!==_[P])return true}for(let P of S)if(N.properties[P]&&p(w.properties[P],N.properties[P]))return true}if(w.$defs&&N.$defs){let S=Object.keys(w.$defs);for(let _ of S)if(N.$defs[_]&&p(w.$defs[_],N.$defs[_]))return true}return false},[]),f=useCallback(async(w,N)=>{process.env.NODE_ENV;let S=typeof w=="function"?w(y.current):w,_=p(y.current,S);if(!!isEqual(y.current,S)&&!_){(N??true)&&o&&await o(S);return}t&&t(S),(N??true)&&o&&await o(S);},[t,o,p]),x=useCallback(w=>{if(!w||typeof w!="object")return 0;let N=(_,P="")=>{if(!_||typeof _!="object")return 0;let R=0;if(_["X-ReasoningPrompt"]!==void 0&&_["X-ReasoningPrompt"]!==null&&_["X-ReasoningPrompt"]!==""&&(R+=1),_.$ref&&typeof _.$ref=="string"&&_.$ref.startsWith("#/")){let E=_.$ref.substring(2).split("/"),C=w;for(let b of E)if(C&&typeof C=="object")C=C[b];else {C=void 0;break}C&&(R+=N(C,`${P}>${_.$ref}`));}return _.properties&&typeof _.properties=="object"&&(R+=Object.keys(_.properties).length,Object.entries(_.properties).forEach(([E,C])=>{R+=N(C,`${P}/properties/${E}`);})),_.type==="array"&&_.items&&(Array.isArray(_.items)?_.items.forEach((E,C)=>{R+=N(E,`${P}/items/${C}`);}):R+=N(_.items,`${P}/items`)),["allOf","anyOf","oneOf"].forEach(E=>{let C=_[E];Array.isArray(C)&&C.forEach((b,O)=>{R+=N(b,`${P}/${E}/${O}`);});}),R};return N(w)},[]),g=useCallback(w=>{if(!w||w.length===0)return [];let N=[],S=new Set;for(let _ of w)if(_.keyword==="pattern"&&_.schemaPath?.includes("/propertyNames/pattern")&&_.data&&typeof _.data=="string"){let P=_.data;S.has(P)||(N.push({keyword:"propertyNames",instancePath:_.instancePath,schemaPath:_.schemaPath,params:{propertyName:P},message:`Property name "${P}" must not be purely numeric`,data:_.data,schema:_.schema}),S.add(P));}else if(_.keyword==="propertyNames"&&_.params?.propertyName){let P=_.params.propertyName;S.has(P)||(N.push({keyword:"propertyNames",instancePath:_.instancePath,schemaPath:_.schemaPath,params:{propertyName:P},message:`Property name "${P}" must not be purely numeric`,data:_.data,schema:_.schema}),S.add(P));}else _.keyword==="const"&&_.schemaPath?.includes("/additionalProperties/const")?N.push({keyword:"additionalProperties",instancePath:_.instancePath,schemaPath:_.schemaPath,params:_.params,message:"`additionalProperties` are forbidden, if present they MUST be false.",data:_.data,schema:_.schema}):_.keyword!=="propertyNames"&&!(_.keyword==="pattern"&&_.schemaPath?.includes("/propertyNames/pattern"))&&!(_.keyword==="const"&&_.schemaPath?.includes("/additionalProperties/const"))&&N.push(_);return N},[]);useEffect(()=>{let w=x(i);h(w);let N=w>100,S=G_(i)&&!N;c(S?void 0:N?`Schema has too many properties: ${w}. Maximum accepted by OpenAI is 100. Please reduce the number of properties.`:Jf.errorsText(g(G_.errors),{separator:`
8
+ deps: ${r}}`};var bI={keyword:"dependencies",type:"object",schemaType:"object",error:Ja.error,code(e){let[t,r]=xI(e);B_(e,t),z_(e,r);}};function xI({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let a=Array.isArray(e[n])?t:r;a[n]=e[n];}return [t,r]}function B_(e,t=e.schema){let{gen:r,data:n,it:a}=e;if(Object.keys(t).length===0)return;let o=r.let("missing");for(let i in t){let s=t[i];if(s.length===0)continue;let l=(0, Ju.propertyInData)(r,n,i,a.opts.ownProperties);e.setParams({property:i,depsCount:s.length,deps:s.join(", ")}),a.allErrors?r.if(l,()=>{for(let c of s)(0, Ju.checkReportMissingProp)(e,c);}):(r.if((0, ky._)`${l} && (${(0, Ju.checkMissingProp)(e,s,o)})`),(0, Ju.reportMissingProp)(e,o),r.else());}}Ja.validatePropertyDeps=B_;function z_(e,t=e.schema){let{gen:r,data:n,keyword:a,it:o}=e,i=r.name("valid");for(let s in t)(0, vI.alwaysValidSchema)(o,t[s])||(r.if((0, Ju.propertyInData)(r,n,s,o.opts.ownProperties),()=>{let l=e.subschema({keyword:a,schemaProp:s},i);e.mergeValidEvaluated(l,i);},()=>r.var(i,true)),e.ok(i));}Ja.validateSchemaDeps=z_;Ja.default=bI;});var V_=B(Ry=>{Object.defineProperty(Ry,"__esModule",{value:true});var q_=Ye(),wI=pt(),_I={message:"property name must be valid",params:({params:e})=>(0, q_._)`{propertyName: ${e.propertyName}}`},SI={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:_I,code(e){let{gen:t,schema:r,data:n,it:a}=e;if((0, wI.alwaysValidSchema)(a,r))return;let o=t.name("valid");t.forIn("key",n,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:true},o),t.if((0, q_.not)(o),()=>{e.error(true),a.allErrors||t.break();});}),e.ok(o);}};Ry.default=SI;});var Dy=B(Oy=>{Object.defineProperty(Oy,"__esModule",{value:true});var ap=zn(),va=Ye(),NI=Ua(),op=pt(),CI={message:"must NOT have additional properties",params:({params:e})=>(0, va._)`{additionalProperty: ${e.additionalProperty}}`},EI={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:true,trackErrors:true,error:CI,code(e){let{gen:t,schema:r,parentSchema:n,data:a,errsCount:o,it:i}=e;if(!o)throw new Error("ajv implementation error");let{allErrors:s,opts:l}=i;if(i.props=true,l.removeAdditional!=="all"&&(0, op.alwaysValidSchema)(i,r))return;let c=(0, ap.allSchemaProperties)(n.properties),u=(0, ap.allSchemaProperties)(n.patternProperties);d(),e.ok((0, va._)`${o} === ${NI.default.errors}`);function d(){t.forIn("key",a,p=>{!c.length&&!u.length?h(p):t.if(g(p),()=>h(p));});}function g(p){let v;if(c.length>8){let y=(0, op.schemaRefOrVal)(i,n.properties,"properties");v=(0, ap.isOwnProperty)(t,y,p);}else c.length?v=(0, va.or)(...c.map(y=>(0, va._)`${p} === ${y}`)):v=va.nil;return u.length&&(v=(0, va.or)(v,...u.map(y=>(0, va._)`${(0, ap.usePattern)(e,y)}.test(${p})`))),(0, va.not)(v)}function f(p){t.code((0, va._)`delete ${a}[${p}]`);}function h(p){if(l.removeAdditional==="all"||l.removeAdditional&&r===false){f(p);return}if(r===false){e.setParams({additionalProperty:p}),e.error(),s||t.break();return}if(typeof r=="object"&&!(0, op.alwaysValidSchema)(i,r)){let v=t.name("valid");l.removeAdditional==="failing"?(m(p,v,false),t.if((0, va.not)(v),()=>{e.reset(),f(p);})):(m(p,v),s||t.if((0, va.not)(v),()=>t.break()));}}function m(p,v,y){let x={keyword:"additionalProperties",dataProp:p,dataPropType:op.Type.Str};y===false&&Object.assign(x,{compositeRule:true,createErrors:false,allErrors:false}),e.subschema(x,v);}}};Oy.default=EI;});var W_=B($y=>{Object.defineProperty($y,"__esModule",{value:true});var PI=Ol(),H_=zn(),Ay=pt(),J_=Dy(),TI={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:o}=e;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&J_.default.code(new PI.KeywordCxt(o,J_.default,"additionalProperties"));let i=(0, H_.allSchemaProperties)(r);for(let d of i)o.definedProperties.add(d);o.opts.unevaluated&&i.length&&o.props!==true&&(o.props=Ay.mergeEvaluated.props(t,(0, Ay.toHash)(i),o.props));let s=i.filter(d=>!(0, Ay.alwaysValidSchema)(o,r[d]));if(s.length===0)return;let l=t.name("valid");for(let d of s)c(d)?u(d):(t.if((0, H_.propertyInData)(t,a,d,o.opts.ownProperties)),u(d),o.allErrors||t.else().var(l,true),t.endIf()),e.it.definedProperties.add(d),e.ok(l);function c(d){return o.opts.useDefaults&&!o.compositeRule&&r[d].default!==void 0}function u(d){e.subschema({keyword:"properties",schemaProp:d,dataProp:d},l);}}};$y.default=TI;});var X_=B(Iy=>{Object.defineProperty(Iy,"__esModule",{value:true});var K_=zn(),ip=Ye(),G_=pt(),Z_=pt(),kI={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:a,it:o}=e,{opts:i}=o,s=(0, K_.allSchemaProperties)(r),l=s.filter(m=>(0, G_.alwaysValidSchema)(o,r[m]));if(s.length===0||l.length===s.length&&(!o.opts.unevaluated||o.props===true))return;let c=i.strictSchema&&!i.allowMatchingProperties&&a.properties,u=t.name("valid");o.props!==true&&!(o.props instanceof ip.Name)&&(o.props=(0, Z_.evaluatedPropsToName)(t,o.props));let{props:d}=o;g();function g(){for(let m of s)c&&f(m),o.allErrors?h(m):(t.var(u,true),h(m),t.if(u));}function f(m){for(let p in c)new RegExp(m).test(p)&&(0, G_.checkStrictMode)(o,`property ${p} matches pattern ${m} (use allowMatchingProperties)`);}function h(m){t.forIn("key",n,p=>{t.if((0, ip._)`${(0, K_.usePattern)(e,m)}.test(${p})`,()=>{let v=l.includes(m);v||e.subschema({keyword:"patternProperties",schemaProp:m,dataProp:p,dataPropType:Z_.Type.Str},u),o.opts.unevaluated&&d!==true?t.assign((0, ip._)`${d}[${p}]`,true):!v&&!o.allErrors&&t.if((0, ip.not)(u),()=>t.break());});});}}};Iy.default=kI;});var Q_=B(Fy=>{Object.defineProperty(Fy,"__esModule",{value:true});var RI=pt(),OI={keyword:"not",schemaType:["object","boolean"],trackErrors:true,code(e){let{gen:t,schema:r,it:n}=e;if((0, RI.alwaysValidSchema)(n,r)){e.fail();return}let a=t.name("valid");e.subschema({keyword:"not",compositeRule:true,createErrors:false,allErrors:false},a),e.failResult(a,()=>e.reset(),()=>e.error());},error:{message:"must NOT be valid"}};Fy.default=OI;});var Y_=B(My=>{Object.defineProperty(My,"__esModule",{value:true});var DI=zn(),AI={keyword:"anyOf",schemaType:"array",trackErrors:true,code:DI.validateUnion,error:{message:"must match a schema in anyOf"}};My.default=AI;});var eS=B(jy=>{Object.defineProperty(jy,"__esModule",{value:true});var sp=Ye(),$I=pt(),II={message:"must match exactly one schema in oneOf",params:({params:e})=>(0, sp._)`{passingSchemas: ${e.passing}}`},FI={keyword:"oneOf",schemaType:"array",trackErrors:true,error:II,code(e){let{gen:t,schema:r,parentSchema:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(a.opts.discriminator&&n.discriminator)return;let o=r,i=t.let("valid",false),s=t.let("passing",null),l=t.name("_valid");e.setParams({passing:s}),t.block(c),e.result(i,()=>e.reset(),()=>e.error(true));function c(){o.forEach((u,d)=>{let g;(0, $I.alwaysValidSchema)(a,u)?t.var(l,true):g=e.subschema({keyword:"oneOf",schemaProp:d,compositeRule:true},l),d>0&&t.if((0, sp._)`${l} && ${i}`).assign(i,false).assign(s,(0, sp._)`[${s}, ${d}]`).else(),t.if(l,()=>{t.assign(i,true),t.assign(s,d),g&&e.mergeEvaluated(g,sp.Name);});});}}};jy.default=FI;});var tS=B(Ly=>{Object.defineProperty(Ly,"__esModule",{value:true});var MI=pt(),jI={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let a=t.name("valid");r.forEach((o,i)=>{if((0, MI.alwaysValidSchema)(n,o))return;let s=e.subschema({keyword:"allOf",schemaProp:i},a);e.ok(a),e.mergeEvaluated(s);});}};Ly.default=jI;});var aS=B(By=>{Object.defineProperty(By,"__esModule",{value:true});var lp=Ye(),nS=pt(),LI={message:({params:e})=>(0, lp.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0, lp._)`{failingKeyword: ${e.ifClause}}`},BI={keyword:"if",schemaType:["object","boolean"],trackErrors:true,error:LI,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0, nS.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let a=rS(n,"then"),o=rS(n,"else");if(!a&&!o)return;let i=t.let("valid",true),s=t.name("_valid");if(l(),e.reset(),a&&o){let u=t.let("ifClause");e.setParams({ifClause:u}),t.if(s,c("then",u),c("else",u));}else a?t.if(s,c("then")):t.if((0, lp.not)(s),c("else"));e.pass(i,()=>e.error(true));function l(){let u=e.subschema({keyword:"if",compositeRule:true,createErrors:false,allErrors:false},s);e.mergeEvaluated(u);}function c(u,d){return ()=>{let g=e.subschema({keyword:u},s);t.assign(i,s),e.mergeValidEvaluated(g,i),d?t.assign(d,(0, lp._)`${u}`):e.setParams({ifClause:u});}}}};function rS(e,t){let r=e.schema[t];return r!==void 0&&!(0, nS.alwaysValidSchema)(e,r)}By.default=BI;});var oS=B(zy=>{Object.defineProperty(zy,"__esModule",{value:true});var zI=pt(),UI={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0, zI.checkStrictMode)(r,`"${e}" without "if" is ignored`);}};zy.default=UI;});var iS=B(Uy=>{Object.defineProperty(Uy,"__esModule",{value:true});var qI=Ny(),VI=F_(),HI=Cy(),JI=j_(),WI=L_(),KI=U_(),GI=V_(),ZI=Dy(),XI=W_(),QI=X_(),YI=Q_(),e3=Y_(),t3=eS(),r3=tS(),n3=aS(),a3=oS();function o3(e=false){let t=[YI.default,e3.default,t3.default,r3.default,n3.default,a3.default,GI.default,ZI.default,KI.default,XI.default,QI.default];return e?t.push(VI.default,JI.default):t.push(qI.default,HI.default),t.push(WI.default),t}Uy.default=o3;});var sS=B(qy=>{Object.defineProperty(qy,"__esModule",{value:true});var rr=Ye(),i3={message:({schemaCode:e})=>(0, rr.str)`must match format "${e}"`,params:({schemaCode:e})=>(0, rr._)`{format: ${e}}`},s3={keyword:"format",type:["number","string"],schemaType:"string",$data:true,error:i3,code(e,t){let{gen:r,data:n,$data:a,schema:o,schemaCode:i,it:s}=e,{opts:l,errSchemaPath:c,schemaEnv:u,self:d}=s;if(!l.validateFormats)return;a?g():f();function g(){let h=r.scopeValue("formats",{ref:d.formats,code:l.code.formats}),m=r.const("fDef",(0, rr._)`${h}[${i}]`),p=r.let("fType"),v=r.let("format");r.if((0, rr._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>r.assign(p,(0, rr._)`${m}.type || "string"`).assign(v,(0, rr._)`${m}.validate`),()=>r.assign(p,(0, rr._)`"string"`).assign(v,m)),e.fail$data((0, rr.or)(y(),x()));function y(){return l.strictSchema===false?rr.nil:(0, rr._)`${i} && !${v}`}function x(){let w=u.$async?(0, rr._)`(${m}.async ? await ${v}(${n}) : ${v}(${n}))`:(0, rr._)`${v}(${n})`,_=(0, rr._)`(typeof ${v} == "function" ? ${w} : ${v}.test(${n}))`;return (0, rr._)`${v} && ${v} !== true && ${p} === ${t} && !${_}`}}function f(){let h=d.formats[o];if(!h){y();return}if(h===true)return;let[m,p,v]=x(h);m===t&&e.pass(w());function y(){if(l.strictSchema===false){d.logger.warn(_());return}throw new Error(_());function _(){return `unknown format "${o}" ignored in schema at path "${c}"`}}function x(_){let E=_ instanceof RegExp?(0, rr.regexpCode)(_):l.code.formats?(0, rr._)`${l.code.formats}${(0, rr.getProperty)(o)}`:void 0,C=r.scopeValue("formats",{key:o,ref:_,code:E});return typeof _=="object"&&!(_ instanceof RegExp)?[_.type||"string",_.validate,(0, rr._)`${C}.validate`]:["string",_,C]}function w(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return (0, rr._)`await ${v}(${n})`}return typeof p=="function"?(0, rr._)`${v}(${n})`:(0, rr._)`${v}.test(${n})`}}}};qy.default=s3;});var lS=B(Vy=>{Object.defineProperty(Vy,"__esModule",{value:true});var l3=sS(),c3=[l3.default];Vy.default=c3;});var cS=B(Il=>{Object.defineProperty(Il,"__esModule",{value:true});Il.contentVocabulary=Il.metadataVocabulary=void 0;Il.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Il.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];});var dS=B(Hy=>{Object.defineProperty(Hy,"__esModule",{value:true});var u3=v_(),d3=D_(),f3=iS(),p3=lS(),uS=cS(),m3=[u3.default,d3.default,(0, f3.default)(),p3.default,uS.metadataVocabulary,uS.contentVocabulary];Hy.default=m3;});var pS=B(cp=>{Object.defineProperty(cp,"__esModule",{value:true});cp.DiscrError=void 0;var fS;(function(e){e.Tag="tag",e.Mapping="mapping";})(fS||(cp.DiscrError=fS={}));});var hS=B(Wy=>{Object.defineProperty(Wy,"__esModule",{value:true});var Fl=Ye(),Jy=pS(),mS=Hf(),h3=Au(),g3=pt(),y3={message:({params:{discrError:e,tagName:t}})=>e===Jy.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0, Fl._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},v3={keyword:"discriminator",type:"object",schemaType:"object",error:y3,code(e){let{gen:t,data:r,schema:n,parentSchema:a,it:o}=e,{oneOf:i}=a;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let s=n.propertyName;if(typeof s!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let l=t.let("valid",false),c=t.const("tag",(0, Fl._)`${r}${(0, Fl.getProperty)(s)}`);t.if((0, Fl._)`typeof ${c} == "string"`,()=>u(),()=>e.error(false,{discrError:Jy.DiscrError.Tag,tag:c,tagName:s})),e.ok(l);function u(){let f=g();t.if(false);for(let h in f)t.elseIf((0, Fl._)`${c} === ${h}`),t.assign(l,d(f[h]));t.else(),e.error(false,{discrError:Jy.DiscrError.Mapping,tag:c,tagName:s}),t.endIf();}function d(f){let h=t.name("valid"),m=e.subschema({keyword:"oneOf",schemaProp:f},h);return e.mergeEvaluated(m,Fl.Name),h}function g(){var f;let h={},m=v(a),p=true;for(let w=0;w<i.length;w++){let _=i[w];if(_?.$ref&&!(0, g3.schemaHasRulesButRef)(_,o.self.RULES)){let C=_.$ref;if(_=mS.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,C),_ instanceof mS.SchemaEnv&&(_=_.schema),_===void 0)throw new h3.default(o.opts.uriResolver,o.baseId,C)}let E=(f=_?.properties)===null||f===void 0?void 0:f[s];if(typeof E!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${s}"`);p=p&&(m||v(_)),y(E,w);}if(!p)throw new Error(`discriminator: "${s}" must be required`);return h;function v({required:w}){return Array.isArray(w)&&w.includes(s)}function y(w,_){if(w.const)x(w.const,_);else if(w.enum)for(let E of w.enum)x(E,_);else throw new Error(`discriminator: "properties/${s}" must have "const" or "enum"`)}function x(w,_){if(typeof w!="string"||w in h)throw new Error(`discriminator: "${s}" values must be unique strings`);h[w]=_;}}}};Wy.default=v3;});var Ky=B((EK,b3)=>{b3.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:true,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:true,readOnly:{type:"boolean",default:false},examples:{type:"array",items:true},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:true},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:false},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:true,enum:{type:"array",items:true,minItems:1,uniqueItems:true},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:true}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:true};});var Wu=B((It,Gy)=>{Object.defineProperty(It,"__esModule",{value:true});It.MissingRefError=It.ValidationError=It.CodeGen=It.Name=It.nil=It.stringify=It.str=It._=It.KeywordCxt=It.Ajv=void 0;var x3=f_(),w3=dS(),_3=hS(),gS=Ky(),S3=["/properties"],up="http://json-schema.org/draft-07/schema",Ml=class extends x3.default{_addVocabularies(){super._addVocabularies(),w3.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(_3.default);}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(gS,S3):gS;this.addMetaSchema(t,up,false),this.refs["http://json-schema.org/schema"]=up;}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(up)?up:void 0)}};It.Ajv=Ml;Gy.exports=It=Ml;Gy.exports.Ajv=Ml;Object.defineProperty(It,"__esModule",{value:true});It.default=Ml;var N3=Ol();Object.defineProperty(It,"KeywordCxt",{enumerable:true,get:function(){return N3.KeywordCxt}});var jl=Ye();Object.defineProperty(It,"_",{enumerable:true,get:function(){return jl._}});Object.defineProperty(It,"str",{enumerable:true,get:function(){return jl.str}});Object.defineProperty(It,"stringify",{enumerable:true,get:function(){return jl.stringify}});Object.defineProperty(It,"nil",{enumerable:true,get:function(){return jl.nil}});Object.defineProperty(It,"Name",{enumerable:true,get:function(){return jl.Name}});Object.defineProperty(It,"CodeGen",{enumerable:true,get:function(){return jl.CodeGen}});var C3=qf();Object.defineProperty(It,"ValidationError",{enumerable:true,get:function(){return C3.default}});var E3=Au();Object.defineProperty(It,"MissingRefError",{enumerable:true,get:function(){return E3.default}});});var _S=B(Wa=>{Object.defineProperty(Wa,"__esModule",{value:true});Wa.formatNames=Wa.fastFormats=Wa.fullFormats=void 0;function Ll(e,t){return {validate:e,compare:t}}Wa.fullFormats={date:Ll(bS,Qy),time:Ll(xS,Yy),"date-time":Ll(R3,wS),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:A3,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:B3,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:$3,int32:{type:"number",validate:M3},int64:{type:"number",validate:j3},float:{type:"number",validate:vS},double:{type:"number",validate:vS},password:true,binary:true};Wa.fastFormats={...Wa.fullFormats,date:Ll(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Qy),time:Ll(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Yy),"date-time":Ll(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,wS),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Wa.formatNames=Object.keys(Wa.fullFormats);function P3(e){return e%4===0&&(e%100!==0||e%400===0)}var T3=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,k3=[0,31,28,31,30,31,30,31,31,30,31,30,31];function bS(e){let t=T3.exec(e);if(!t)return false;let r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(n===2&&P3(r)?29:k3[n])}function Qy(e,t){if(e&&t)return e>t?1:e<t?-1:0}var Zy=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;function xS(e,t){let r=Zy.exec(e);if(!r)return false;let n=+r[1],a=+r[2],o=+r[3],i=r[5];return (n<=23&&a<=59&&o<=59||n===23&&a===59&&o===60)&&(!t||i!=="")}function Yy(e,t){if(!(e&&t))return;let r=Zy.exec(e),n=Zy.exec(t);if(r&&n)return e=r[1]+r[2]+r[3]+(r[4]||""),t=n[1]+n[2]+n[3]+(n[4]||""),e>t?1:e<t?-1:0}var Xy=/t|\s/i;function R3(e){let t=e.split(Xy);return t.length===2&&bS(t[0])&&xS(t[1],true)}function wS(e,t){if(!(e&&t))return;let[r,n]=e.split(Xy),[a,o]=t.split(Xy),i=Qy(r,a);if(i!==void 0)return i||Yy(n,o)}var O3=/\/|:/,D3=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function A3(e){return O3.test(e)&&D3.test(e)}var yS=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function $3(e){return yS.lastIndex=0,yS.test(e)}var I3=-2147483648,F3=2**31-1;function M3(e){return Number.isInteger(e)&&e<=F3&&e>=I3}function j3(e){return Number.isInteger(e)}function vS(){return true}var L3=/[^\\]\\Z/;function B3(e){if(L3.test(e))return false;try{return new RegExp(e),!0}catch{return false}}});var SS=B(Bl=>{Object.defineProperty(Bl,"__esModule",{value:true});Bl.formatLimitDefinition=void 0;var z3=Wu(),ba=Ye(),pi=ba.operators,dp={formatMaximum:{okStr:"<=",ok:pi.LTE,fail:pi.GT},formatMinimum:{okStr:">=",ok:pi.GTE,fail:pi.LT},formatExclusiveMaximum:{okStr:"<",ok:pi.LT,fail:pi.GTE},formatExclusiveMinimum:{okStr:">",ok:pi.GT,fail:pi.LTE}},U3={message:({keyword:e,schemaCode:t})=>ba.str`should be ${dp[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>ba._`{comparison: ${dp[e].okStr}, limit: ${t}}`};Bl.formatLimitDefinition={keyword:Object.keys(dp),type:"string",schemaType:"string",$data:true,error:U3,code(e){let{gen:t,data:r,schemaCode:n,keyword:a,it:o}=e,{opts:i,self:s}=o;if(!i.validateFormats)return;let l=new z3.KeywordCxt(o,s.RULES.all.format.definition,"format");l.$data?c():u();function c(){let g=t.scopeValue("formats",{ref:s.formats,code:i.code.formats}),f=t.const("fmt",ba._`${g}[${l.schemaCode}]`);e.fail$data(ba.or(ba._`typeof ${f} != "object"`,ba._`${f} instanceof RegExp`,ba._`typeof ${f}.compare != "function"`,d(f)));}function u(){let g=l.schema,f=s.formats[g];if(!f||f===true)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${a}": format "${g}" does not define "compare" function`);let h=t.scopeValue("formats",{key:g,ref:f,code:i.code.formats?ba._`${i.code.formats}${ba.getProperty(g)}`:void 0});e.fail$data(d(h));}function d(g){return ba._`${g}.compare(${r}, ${n}) ${dp[a].fail} 0`}},dependencies:["format"]};var q3=e=>(e.addKeyword(Bl.formatLimitDefinition),e);Bl.default=q3;});var r0=B((Ku,ES)=>{Object.defineProperty(Ku,"__esModule",{value:true});var zl=_S(),V3=SS(),e0=Ye(),NS=new e0.Name("fullFormats"),H3=new e0.Name("fastFormats"),t0=(e,t={keywords:true})=>{if(Array.isArray(t))return CS(e,t,zl.fullFormats,NS),e;let[r,n]=t.mode==="fast"?[zl.fastFormats,H3]:[zl.fullFormats,NS],a=t.formats||zl.formatNames;return CS(e,a,r,n),t.keywords&&V3.default(e),e};t0.get=(e,t="full")=>{let n=(t==="fast"?zl.fastFormats:zl.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function CS(e,t,r,n){var a,o;(a=(o=e.opts.code).formats)!==null&&a!==void 0||(o.formats=e0._`require("ajv-formats/dist/formats").${n}`);for(let i of t)e.addFormat(i,r[i]);}ES.exports=Ku=t0;Object.defineProperty(Ku,"__esModule",{value:true});Ku.default=t0;});var RS=B((a0,o0)=>{Object.defineProperty(a0,"__esModule",{value:true});var de=Wu(),mi=Ye(),PS=_l(),J3=Ol(),Gu=Cl(),xa=Ua(),fp="errorMessage",hi=new de.Name("emUsed"),TS={required:"missingProperty",dependencies:"property",dependentRequired:"property"},kS=/\$\{[^}]+\}/,W3=/\$\{([^}]+)\}/g,K3=/^""\s*\+\s*|\s*\+\s*""$/g;function G3(e){return {keyword:fp,schemaType:["string","object"],post:true,code(t){let{gen:r,data:n,schema:a,schemaValue:o,it:i}=t;if(i.createErrors===false)return;let s=a,l=mi.strConcat(xa.default.instancePath,i.errorPath);r.if(de._`${xa.default.errors} > 0`,()=>{if(typeof s=="object"){let[C,P]=u(s);P&&d(P),C&&g(C),f(c(s));}let E=typeof s=="string"?s:s._;E&&h(E),e.keepErrors||m();});function c({properties:E,items:C}){let P={};if(E){P.props={};for(let T in E)P.props[T]=[];}if(C){P.items={};for(let T=0;T<C.length;T++)P.items[T]=[];}return P}function u(E){let C,P;for(let T in E){if(T==="properties"||T==="items")continue;let N=E[T];if(typeof N=="object"){C||(C={});let S=C[T]={};for(let b in N)S[b]=[];}else P||(P={}),P[T]=[];}return [C,P]}function d(E){let C=r.const("emErrors",de.stringify(E)),P=r.const("templates",x(E,a));r.forOf("err",xa.default.vErrors,b=>r.if(p(b,C),()=>r.code(de._`${C}[${b}.keyword].push(${b})`).assign(de._`${b}.${hi}`,true)));let{singleError:T}=e;if(T){let b=r.let("message",de._`""`),k=r.let("paramsErrors",de._`[]`);N(D=>{r.if(b,()=>r.code(de._`${b} += ${typeof T=="string"?T:";"}`)),r.code(de._`${b} += ${S(D)}`),r.assign(k,de._`${k}.concat(${C}[${D}])`);}),Gu.reportError(t,{message:b,params:de._`{errors: ${k}}`});}else N(b=>Gu.reportError(t,{message:S(b),params:de._`{errors: ${C}[${b}]}`}));function N(b){r.forIn("key",C,k=>r.if(de._`${C}[${k}].length`,()=>b(k)));}function S(b){return de._`${b} in ${P} ? ${P}[${b}]() : ${o}[${b}]`}}function g(E){let C=r.const("emErrors",de.stringify(E)),P=[];for(let k in E)P.push([k,x(E[k],a[k])]);let T=r.const("templates",r.object(...P)),N=r.scopeValue("obj",{ref:TS,code:de.stringify(TS)}),S=r.let("emPropParams"),b=r.let("emParamsErrors");r.forOf("err",xa.default.vErrors,k=>r.if(p(k,C),()=>{r.assign(S,de._`${N}[${k}.keyword]`),r.assign(b,de._`${C}[${k}.keyword][${k}.params[${S}]]`),r.if(b,()=>r.code(de._`${b}.push(${k})`).assign(de._`${k}.${hi}`,true));})),r.forIn("key",C,k=>r.forIn("keyProp",de._`${C}[${k}]`,D=>{r.assign(b,de._`${C}[${k}][${D}]`),r.if(de._`${b}.length`,()=>{let O=r.const("tmpl",de._`${T}[${k}] && ${T}[${k}][${D}]`);Gu.reportError(t,{message:de._`${O} ? ${O}() : ${o}[${k}][${D}]`,params:de._`{errors: ${b}}`});});}));}function f(E){let{props:C,items:P}=E;if(!C&&!P)return;let T=de._`typeof ${n} == "object"`,N=de._`Array.isArray(${n})`,S=r.let("emErrors"),b,k,D=r.let("templates");C&&P?(b=r.let("emChildKwd"),r.if(T),r.if(N,()=>{O(P,a.items),r.assign(b,de.str`items`);},()=>{O(C,a.properties),r.assign(b,de.str`properties`);}),k=de._`[${b}]`):P?(r.if(N),O(P,a.items),k=de._`.items`):C&&(r.if(mi.and(T,mi.not(N))),O(C,a.properties),k=de._`.properties`),r.forOf("err",xa.default.vErrors,$=>v($,S,A=>r.code(de._`${S}[${A}].push(${$})`).assign(de._`${$}.${hi}`,true))),r.forIn("key",S,$=>r.if(de._`${S}[${$}].length`,()=>{Gu.reportError(t,{message:de._`${$} in ${D} ? ${D}[${$}]() : ${o}${k}[${$}]`,params:de._`{errors: ${S}[${$}]}`}),r.assign(de._`${xa.default.vErrors}[${xa.default.errors}-1].instancePath`,de._`${l} + "/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`);})),r.endIf();function O($,A){r.assign(S,de.stringify($)),r.assign(D,x($,A));}}function h(E){let C=r.const("emErrs",de._`[]`);r.forOf("err",xa.default.vErrors,P=>r.if(y(P),()=>r.code(de._`${C}.push(${P})`).assign(de._`${P}.${hi}`,true))),r.if(de._`${C}.length`,()=>Gu.reportError(t,{message:w(E),params:de._`{errors: ${C}}`}));}function m(){let E=r.const("emErrs",de._`[]`);r.forOf("err",xa.default.vErrors,C=>r.if(de._`!${C}.${hi}`,()=>r.code(de._`${E}.push(${C})`))),r.assign(xa.default.vErrors,E).assign(xa.default.errors,de._`${E}.length`);}function p(E,C){return mi.and(de._`${E}.keyword !== ${fp}`,de._`!${E}.${hi}`,de._`${E}.instancePath === ${l}`,de._`${E}.keyword in ${C}`,de._`${E}.schemaPath.indexOf(${i.errSchemaPath}) === 0`,de._`/^\\/[^\\/]*$/.test(${E}.schemaPath.slice(${i.errSchemaPath.length}))`)}function v(E,C,P){r.if(mi.and(de._`${E}.keyword !== ${fp}`,de._`!${E}.${hi}`,de._`${E}.instancePath.indexOf(${l}) === 0`),()=>{let T=r.scopeValue("pattern",{ref:/^\/([^/]*)(?:\/|$)/,code:de._`new RegExp("^\\\/([^/]*)(?:\\\/|$)")`}),N=r.const("emMatches",de._`${T}.exec(${E}.instancePath.slice(${l}.length))`),S=r.const("emChild",de._`${N} && ${N}[1].replace(/~1/g, "/").replace(/~0/g, "~")`);r.if(de._`${S} !== undefined && ${S} in ${C}`,()=>P(S));});}function y(E){return mi.and(de._`${E}.keyword !== ${fp}`,de._`!${E}.${hi}`,mi.or(de._`${E}.instancePath === ${l}`,mi.and(de._`${E}.instancePath.indexOf(${l}) === 0`,de._`${E}.instancePath[${l}.length] === "/"`)),de._`${E}.schemaPath.indexOf(${i.errSchemaPath}) === 0`,de._`${E}.schemaPath[${i.errSchemaPath}.length] === "/"`)}function x(E,C){let P=[];for(let T in E){let N=C[T];kS.test(N)&&P.push([T,_(N)]);}return r.object(...P)}function w(E){return kS.test(E)?new PS._Code(PS.safeStringify(E).replace(W3,(C,P)=>`" + JSON.stringify(${J3.getData(P,i)}) + "`).replace(K3,"")):de.stringify(E)}function _(E){return de._`function(){return ${w(E)}}`}},metaSchema:{anyOf:[{type:"string"},{type:"object",properties:{properties:{$ref:"#/$defs/stringMap"},items:{$ref:"#/$defs/stringList"},required:{$ref:"#/$defs/stringOrMap"},dependencies:{$ref:"#/$defs/stringOrMap"}},additionalProperties:{type:"string"}}],$defs:{stringMap:{type:"object",additionalProperties:{type:"string"}},stringOrMap:{anyOf:[{type:"string"},{$ref:"#/$defs/stringMap"}]},stringList:{type:"array",items:{type:"string"}}}}}}var n0=(e,t={})=>{if(!e.opts.allErrors)throw new Error("ajv-errors: Ajv option allErrors must be true");if(e.opts.jsPropertySyntax)throw new Error("ajv-errors: ajv option jsPropertySyntax is not supported");return e.addKeyword(G3(t))};a0.default=n0;o0.exports=n0;o0.exports.default=n0;});var kd=B((qse,rb)=>{typeof process>"u"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0?rb.exports={nextTick:W7}:rb.exports=process;function W7(e,t,r,n){if(typeof e!="function")throw new TypeError('"callback" argument must be a function');var a=arguments.length,o,i;switch(a){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick(function(){e.call(null,t);});case 3:return process.nextTick(function(){e.call(null,t,r);});case 4:return process.nextTick(function(){e.call(null,t,r,n);});default:for(o=new Array(a-1),i=0;i<o.length;)o[i++]=arguments[i];return process.nextTick(function(){e.apply(null,o);})}}});var LP=B((Vse,jP)=>{var K7={}.toString;jP.exports=Array.isArray||function(e){return K7.call(e)=="[object Array]"};});var nb=B((Hse,BP)=>{BP.exports=yo("stream");});var Rd=B((ab,UP)=>{var Vm=yo("buffer"),Uo=Vm.Buffer;function zP(e,t){for(var r in e)t[r]=e[r];}Uo.from&&Uo.alloc&&Uo.allocUnsafe&&Uo.allocUnsafeSlow?UP.exports=Vm:(zP(Vm,ab),ab.Buffer=jc);function jc(e,t,r){return Uo(e,t,r)}zP(Uo,jc);jc.from=function(e,t,r){if(typeof e=="number")throw new TypeError("Argument must not be a number");return Uo(e,t,r)};jc.alloc=function(e,t,r){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=Uo(e);return t!==void 0?typeof r=="string"?n.fill(t,r):n.fill(t):n.fill(0),n};jc.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return Uo(e)};jc.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return Vm.SlowBuffer(e)};});var Lc=B(Jr=>{function G7(e){return Array.isArray?Array.isArray(e):Hm(e)==="[object Array]"}Jr.isArray=G7;function Z7(e){return typeof e=="boolean"}Jr.isBoolean=Z7;function X7(e){return e===null}Jr.isNull=X7;function Q7(e){return e==null}Jr.isNullOrUndefined=Q7;function Y7(e){return typeof e=="number"}Jr.isNumber=Y7;function e8(e){return typeof e=="string"}Jr.isString=e8;function t8(e){return typeof e=="symbol"}Jr.isSymbol=t8;function r8(e){return e===void 0}Jr.isUndefined=r8;function n8(e){return Hm(e)==="[object RegExp]"}Jr.isRegExp=n8;function a8(e){return typeof e=="object"&&e!==null}Jr.isObject=a8;function o8(e){return Hm(e)==="[object Date]"}Jr.isDate=o8;function i8(e){return Hm(e)==="[object Error]"||e instanceof Error}Jr.isError=i8;function s8(e){return typeof e=="function"}Jr.isFunction=s8;function l8(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"||typeof e=="symbol"||typeof e>"u"}Jr.isPrimitive=l8;Jr.isBuffer=yo("buffer").Buffer.isBuffer;function Hm(e){return Object.prototype.toString.call(e)}});var qP=B((Wse,ob)=>{typeof Object.create=="function"?ob.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:false,writable:true,configurable:true}}));}:ob.exports=function(t,r){if(r){t.super_=r;var n=function(){};n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t;}};});var Bc=B((Kse,sb)=>{try{if(ib=yo("util"),typeof ib.inherits!="function")throw "";sb.exports=ib.inherits;}catch{sb.exports=qP();}var ib;});var HP=B((Gse,lb)=>{function c8(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var VP=Rd().Buffer,Od=yo("util");function u8(e,t,r){e.copy(t,r);}lb.exports=(function(){function e(){c8(this,e),this.head=null,this.tail=null,this.length=0;}return e.prototype.push=function(r){var n={data:r,next:null};this.length>0?this.tail.next=n:this.head=n,this.tail=n,++this.length;},e.prototype.unshift=function(r){var n={data:r,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length;},e.prototype.shift=function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0;},e.prototype.join=function(r){if(this.length===0)return "";for(var n=this.head,a=""+n.data;n=n.next;)a+=r+n.data;return a},e.prototype.concat=function(r){if(this.length===0)return VP.alloc(0);for(var n=VP.allocUnsafe(r>>>0),a=this.head,o=0;a;)u8(a.data,n,o),o+=a.data.length,a=a.next;return n},e})();Od&&Od.inspect&&Od.inspect.custom&&(lb.exports.prototype[Od.inspect.custom]=function(){var e=Od.inspect({length:this.length});return this.constructor.name+" "+e});});var cb=B((Zse,JP)=>{var Jm=kd();function d8(e,t){var r=this,n=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return n||a?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=true,Jm.nextTick(Wm,this,e)):Jm.nextTick(Wm,this,e)),this):(this._readableState&&(this._readableState.destroyed=true),this._writableState&&(this._writableState.destroyed=true),this._destroy(e||null,function(o){!t&&o?r._writableState?r._writableState.errorEmitted||(r._writableState.errorEmitted=true,Jm.nextTick(Wm,r,o)):Jm.nextTick(Wm,r,o):t&&t(o);}),this)}function f8(){this._readableState&&(this._readableState.destroyed=false,this._readableState.reading=false,this._readableState.ended=false,this._readableState.endEmitted=false),this._writableState&&(this._writableState.destroyed=false,this._writableState.ended=false,this._writableState.ending=false,this._writableState.finalCalled=false,this._writableState.prefinished=false,this._writableState.finished=false,this._writableState.errorEmitted=false);}function Wm(e,t){e.emit("error",t);}JP.exports={destroy:d8,undestroy:f8};});var KP=B((Xse,WP)=>{WP.exports=yo("util").deprecate;});var db=B((Qse,r2)=>{var rl=kd();r2.exports=sr;function ZP(e){var t=this;this.next=null,this.entry=null,this.finish=function(){R8(t,e);};}var p8=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:rl.nextTick,zc;sr.WritableState=Ad;var XP=Object.create(Lc());XP.inherits=Bc();var m8={deprecate:KP()},QP=nb(),Gm=Rd().Buffer,h8=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function g8(e){return Gm.from(e)}function y8(e){return Gm.isBuffer(e)||e instanceof h8}var YP=cb();XP.inherits(sr,QP);function v8(){}function Ad(e,t){zc=zc||nl(),e=e||{};var r=t instanceof zc;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var n=e.highWaterMark,a=e.writableHighWaterMark,o=this.objectMode?16:16*1024;n||n===0?this.highWaterMark=n:r&&(a||a===0)?this.highWaterMark=a:this.highWaterMark=o,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=false,this.needDrain=false,this.ending=false,this.ended=false,this.finished=false,this.destroyed=false;var i=e.decodeStrings===false;this.decodeStrings=!i,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=false,this.corked=0,this.sync=true,this.bufferProcessing=false,this.onwrite=function(s){C8(t,s);},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=false,this.errorEmitted=false,this.bufferedRequestCount=0,this.corkedRequestsFree=new ZP(this);}Ad.prototype.getBuffer=function(){for(var t=this.bufferedRequest,r=[];t;)r.push(t),t=t.next;return r};(function(){try{Object.defineProperty(Ad.prototype,"buffer",{get:m8.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")});}catch{}})();var Km;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(Km=Function.prototype[Symbol.hasInstance],Object.defineProperty(sr,Symbol.hasInstance,{value:function(e){return Km.call(this,e)?true:this!==sr?false:e&&e._writableState instanceof Ad}})):Km=function(e){return e instanceof this};function sr(e){if(zc=zc||nl(),!Km.call(sr,this)&&!(this instanceof zc))return new sr(e);this._writableState=new Ad(e,this),this.writable=true,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),QP.call(this);}sr.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"));};function b8(e,t){var r=new Error("write after end");e.emit("error",r),rl.nextTick(t,r);}function x8(e,t,r,n){var a=true,o=false;return r===null?o=new TypeError("May not write null values to stream"):typeof r!="string"&&r!==void 0&&!t.objectMode&&(o=new TypeError("Invalid non-string/buffer chunk")),o&&(e.emit("error",o),rl.nextTick(n,o),a=false),a}sr.prototype.write=function(e,t,r){var n=this._writableState,a=false,o=!n.objectMode&&y8(e);return o&&!Gm.isBuffer(e)&&(e=g8(e)),typeof t=="function"&&(r=t,t=null),o?t="buffer":t||(t=n.defaultEncoding),typeof r!="function"&&(r=v8),n.ended?b8(this,r):(o||x8(this,n,e,r))&&(n.pendingcb++,a=_8(this,n,o,e,t,r)),a};sr.prototype.cork=function(){var e=this._writableState;e.corked++;};sr.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&e2(this,e));};sr.prototype.setDefaultEncoding=function(t){if(typeof t=="string"&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this};function w8(e,t,r){return !e.objectMode&&e.decodeStrings!==false&&typeof t=="string"&&(t=Gm.from(t,r)),t}Object.defineProperty(sr.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function _8(e,t,r,n,a,o){if(!r){var i=w8(t,n,a);n!==i&&(r=true,a="buffer",n=i);}var s=t.objectMode?1:n.length;t.length+=s;var l=t.length<t.highWaterMark;if(l||(t.needDrain=true),t.writing||t.corked){var c=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:a,isBuf:r,callback:o,next:null},c?c.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1;}else ub(e,t,false,s,n,a,o);return l}function ub(e,t,r,n,a,o,i){t.writelen=n,t.writecb=i,t.writing=true,t.sync=true,r?e._writev(a,t.onwrite):e._write(a,o,t.onwrite),t.sync=false;}function S8(e,t,r,n,a){--t.pendingcb,r?(rl.nextTick(a,n),rl.nextTick(Dd,e,t),e._writableState.errorEmitted=true,e.emit("error",n)):(a(n),e._writableState.errorEmitted=true,e.emit("error",n),Dd(e,t));}function N8(e){e.writing=false,e.writecb=null,e.length-=e.writelen,e.writelen=0;}function C8(e,t){var r=e._writableState,n=r.sync,a=r.writecb;if(N8(r),t)S8(e,r,n,t,a);else {var o=t2(r);!o&&!r.corked&&!r.bufferProcessing&&r.bufferedRequest&&e2(e,r),n?p8(GP,e,r,o,a):GP(e,r,o,a);}}function GP(e,t,r,n){r||E8(e,t),t.pendingcb--,n(),Dd(e,t);}function E8(e,t){t.length===0&&t.needDrain&&(t.needDrain=false,e.emit("drain"));}function e2(e,t){t.bufferProcessing=true;var r=t.bufferedRequest;if(e._writev&&r&&r.next){var n=t.bufferedRequestCount,a=new Array(n),o=t.corkedRequestsFree;o.entry=r;for(var i=0,s=true;r;)a[i]=r,r.isBuf||(s=false),r=r.next,i+=1;a.allBuffers=s,ub(e,t,true,t.length,a,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new ZP(t),t.bufferedRequestCount=0;}else {for(;r;){var l=r.chunk,c=r.encoding,u=r.callback,d=t.objectMode?1:l.length;if(ub(e,t,false,d,l,c,u),r=r.next,t.bufferedRequestCount--,t.writing)break}r===null&&(t.lastBufferedRequest=null);}t.bufferedRequest=r,t.bufferProcessing=false;}sr.prototype._write=function(e,t,r){r(new Error("_write() is not implemented"));};sr.prototype._writev=null;sr.prototype.end=function(e,t,r){var n=this._writableState;typeof e=="function"?(r=e,e=null,t=null):typeof t=="function"&&(r=t,t=null),e!=null&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||k8(this,n,r);};function t2(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function P8(e,t){e._final(function(r){t.pendingcb--,r&&e.emit("error",r),t.prefinished=true,e.emit("prefinish"),Dd(e,t);});}function T8(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final=="function"?(t.pendingcb++,t.finalCalled=true,rl.nextTick(P8,e,t)):(t.prefinished=true,e.emit("prefinish")));}function Dd(e,t){var r=t2(t);return r&&(T8(e,t),t.pendingcb===0&&(t.finished=true,e.emit("finish"))),r}function k8(e,t,r){t.ending=true,Dd(e,t),r&&(t.finished?rl.nextTick(r):e.once("finish",r)),t.ended=true,e.writable=false;}function R8(e,t,r){var n=e.entry;for(e.entry=null;n;){var a=n.callback;t.pendingcb--,a(r),n=n.next;}t.corkedRequestsFree.next=e;}Object.defineProperty(sr.prototype,"destroyed",{get:function(){return this._writableState===void 0?false:this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e);}});sr.prototype.destroy=YP.destroy;sr.prototype._undestroy=YP.undestroy;sr.prototype._destroy=function(e,t){this.end(),t(e);};});var nl=B((Yse,i2)=>{var n2=kd(),O8=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};i2.exports=qo;var a2=Object.create(Lc());a2.inherits=Bc();var o2=mb(),pb=db();a2.inherits(qo,o2);for(fb=O8(pb.prototype),Zm=0;Zm<fb.length;Zm++)Xm=fb[Zm],qo.prototype[Xm]||(qo.prototype[Xm]=pb.prototype[Xm]);var fb,Xm,Zm;function qo(e){if(!(this instanceof qo))return new qo(e);o2.call(this,e),pb.call(this,e),e&&e.readable===false&&(this.readable=false),e&&e.writable===false&&(this.writable=false),this.allowHalfOpen=true,e&&e.allowHalfOpen===false&&(this.allowHalfOpen=false),this.once("end",D8);}Object.defineProperty(qo.prototype,"writableHighWaterMark",{enumerable:false,get:function(){return this._writableState.highWaterMark}});function D8(){this.allowHalfOpen||this._writableState.ended||n2.nextTick(A8,this);}function A8(e){e.end();}Object.defineProperty(qo.prototype,"destroyed",{get:function(){return this._readableState===void 0||this._writableState===void 0?false:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=e,this._writableState.destroyed=e);}});qo.prototype._destroy=function(e,t){this.push(null),this.end(),n2.nextTick(t,e);};});var yb=B(l2=>{var gb=Rd().Buffer,s2=gb.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case "hex":case "utf8":case "utf-8":case "ascii":case "binary":case "base64":case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":case "raw":return true;default:return false}};function $8(e){if(!e)return "utf8";for(var t;;)switch(e){case "utf8":case "utf-8":return "utf8";case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return "utf16le";case "latin1":case "binary":return "latin1";case "base64":case "ascii":case "hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=true;}}function I8(e){var t=$8(e);if(typeof t!="string"&&(gb.isEncoding===s2||!s2(e)))throw new Error("Unknown encoding: "+e);return t||e}l2.StringDecoder=$d;function $d(e){this.encoding=I8(e);var t;switch(this.encoding){case "utf16le":this.text=z8,this.end=U8,t=4;break;case "utf8":this.fillLast=j8,t=4;break;case "base64":this.text=q8,this.end=V8,t=3;break;default:this.write=H8,this.end=J8;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=gb.allocUnsafe(t);}$d.prototype.write=function(e){if(e.length===0)return "";var t,r;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return "";r=this.lastNeed,this.lastNeed=0;}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""};$d.prototype.end=B8;$d.prototype.text=L8;$d.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length;};function hb(e){return e<=127?0:e>>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}function F8(e,t,r){var n=t.length-1;if(n<r)return 0;var a=hb(t[n]);return a>=0?(a>0&&(e.lastNeed=a-1),a):--n<r||a===-2?0:(a=hb(t[n]),a>=0?(a>0&&(e.lastNeed=a-2),a):--n<r||a===-2?0:(a=hb(t[n]),a>=0?(a>0&&(a===2?a=0:e.lastNeed=a-3),a):0))}function M8(e,t,r){if((t[0]&192)!==128)return e.lastNeed=0,"\uFFFD";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"\uFFFD";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"\uFFFD"}}function j8(e){var t=this.lastTotal-this.lastNeed,r=M8(this,e);if(r!==void 0)return r;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length;}function L8(e,t){var r=F8(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}function B8(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"\uFFFD":t}function z8(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function U8(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function q8(e,t){var r=(e.length-t)%3;return r===0?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function V8(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function H8(e){return e.toString(this.encoding)}function J8(e){return e&&e.length?this.write(e):""}});var mb=B((rle,x2)=>{var qc=kd();x2.exports=Mt;var W8=LP(),Id;Mt.ReadableState=h2;yo("events").EventEmitter;var f2=function(e,t){return e.listeners(t).length},_b=nb(),Fd=Rd().Buffer,K8=(typeof global<"u"?global:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function G8(e){return Fd.from(e)}function Z8(e){return Fd.isBuffer(e)||e instanceof K8}var p2=Object.create(Lc());p2.inherits=Bc();var vb=yo("util"),yt=void 0;vb&&vb.debuglog?yt=vb.debuglog("stream"):yt=function(){};var X8=HP(),m2=cb(),Uc;p2.inherits(Mt,_b);var bb=["error","close","destroy","pause","resume"];function Q8(e,t,r){if(typeof e.prependListener=="function")return e.prependListener(t,r);!e._events||!e._events[t]?e.on(t,r):W8(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]];}function h2(e,t){Id=Id||nl(),e=e||{};var r=t instanceof Id;this.objectMode=!!e.objectMode,r&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var n=e.highWaterMark,a=e.readableHighWaterMark,o=this.objectMode?16:16*1024;n||n===0?this.highWaterMark=n:r&&(a||a===0)?this.highWaterMark=a:this.highWaterMark=o,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new X8,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=false,this.endEmitted=false,this.reading=false,this.sync=true,this.needReadable=false,this.emittedReadable=false,this.readableListening=false,this.resumeScheduled=false,this.destroyed=false,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=false,this.decoder=null,this.encoding=null,e.encoding&&(Uc||(Uc=yb().StringDecoder),this.decoder=new Uc(e.encoding),this.encoding=e.encoding);}function Mt(e){if(Id=Id||nl(),!(this instanceof Mt))return new Mt(e);this._readableState=new h2(e,this),this.readable=true,e&&(typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)),_b.call(this);}Object.defineProperty(Mt.prototype,"destroyed",{get:function(){return this._readableState===void 0?false:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e);}});Mt.prototype.destroy=m2.destroy;Mt.prototype._undestroy=m2.undestroy;Mt.prototype._destroy=function(e,t){this.push(null),t(e);};Mt.prototype.push=function(e,t){var r=this._readableState,n;return r.objectMode?n=true:typeof e=="string"&&(t=t||r.defaultEncoding,t!==r.encoding&&(e=Fd.from(e,t),t=""),n=true),g2(this,e,t,false,n)};Mt.prototype.unshift=function(e){return g2(this,e,null,true,false)};function g2(e,t,r,n,a){var o=e._readableState;if(t===null)o.reading=false,rB(e,o);else {var i;a||(i=Y8(o,t)),i?e.emit("error",i):o.objectMode||t&&t.length>0?(typeof t!="string"&&!o.objectMode&&Object.getPrototypeOf(t)!==Fd.prototype&&(t=G8(t)),n?o.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):xb(e,o,t,true):o.ended?e.emit("error",new Error("stream.push() after EOF")):(o.reading=false,o.decoder&&!r?(t=o.decoder.write(t),o.objectMode||t.length!==0?xb(e,o,t,false):y2(e,o)):xb(e,o,t,false))):n||(o.reading=false);}return eB(o)}function xb(e,t,r,n){t.flowing&&t.length===0&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,n?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&Qm(e)),y2(e,t);}function Y8(e,t){var r;return !Z8(t)&&typeof t!="string"&&t!==void 0&&!e.objectMode&&(r=new TypeError("Invalid non-string/buffer chunk")),r}function eB(e){return !e.ended&&(e.needReadable||e.length<e.highWaterMark||e.length===0)}Mt.prototype.isPaused=function(){return this._readableState.flowing===false};Mt.prototype.setEncoding=function(e){return Uc||(Uc=yb().StringDecoder),this._readableState.decoder=new Uc(e),this._readableState.encoding=e,this};var c2=8388608;function tB(e){return e>=c2?e=c2:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function u2(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=tB(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=true,0))}Mt.prototype.read=function(e){yt("read",e),e=parseInt(e,10);var t=this._readableState,r=e;if(e!==0&&(t.emittedReadable=false),e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return yt("read: emitReadable",t.length,t.ended),t.length===0&&t.ended?wb(this):Qm(this),null;if(e=u2(e,t),e===0&&t.ended)return t.length===0&&wb(this),null;var n=t.needReadable;yt("need readable",n),(t.length===0||t.length-e<t.highWaterMark)&&(n=true,yt("length less than watermark",n)),t.ended||t.reading?(n=false,yt("reading or ended",n)):n&&(yt("do read"),t.reading=true,t.sync=true,t.length===0&&(t.needReadable=true),this._read(t.highWaterMark),t.sync=false,t.reading||(e=u2(r,t)));var a;return e>0?a=v2(e,t):a=null,a===null?(t.needReadable=true,e=0):t.length-=e,t.length===0&&(t.ended||(t.needReadable=true),r!==e&&t.ended&&wb(this)),a!==null&&this.emit("data",a),a};function rB(e,t){if(!t.ended){if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length);}t.ended=true,Qm(e);}}function Qm(e){var t=e._readableState;t.needReadable=false,t.emittedReadable||(yt("emitReadable",t.flowing),t.emittedReadable=true,t.sync?qc.nextTick(d2,e):d2(e));}function d2(e){yt("emit readable"),e.emit("readable"),Sb(e);}function y2(e,t){t.readingMore||(t.readingMore=true,qc.nextTick(nB,e,t));}function nB(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(yt("maybeReadMore read 0"),e.read(0),r!==t.length);)r=t.length;t.readingMore=false;}Mt.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"));};Mt.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e);break}n.pipesCount+=1,yt("pipe count=%d opts=%j",n.pipesCount,t);var a=(!t||t.end!==false)&&e!==process.stdout&&e!==process.stderr,o=a?s:p;n.endEmitted?qc.nextTick(o):r.once("end",o),e.on("unpipe",i);function i(v,y){yt("onunpipe"),v===r&&y&&y.hasUnpiped===false&&(y.hasUnpiped=true,u());}function s(){yt("onend"),e.end();}var l=aB(r);e.on("drain",l);var c=false;function u(){yt("cleanup"),e.removeListener("close",h),e.removeListener("finish",m),e.removeListener("drain",l),e.removeListener("error",f),e.removeListener("unpipe",i),r.removeListener("end",s),r.removeListener("end",p),r.removeListener("data",g),c=true,n.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&l();}var d=false;r.on("data",g);function g(v){yt("ondata"),d=false;var y=e.write(v);y===false&&!d&&((n.pipesCount===1&&n.pipes===e||n.pipesCount>1&&b2(n.pipes,e)!==-1)&&!c&&(yt("false write response, pause",n.awaitDrain),n.awaitDrain++,d=true),r.pause());}function f(v){yt("onerror",v),p(),e.removeListener("error",f),f2(e,"error")===0&&e.emit("error",v);}Q8(e,"error",f);function h(){e.removeListener("finish",m),p();}e.once("close",h);function m(){yt("onfinish"),e.removeListener("close",h),p();}e.once("finish",m);function p(){yt("unpipe"),r.unpipe(e);}return e.emit("pipe",r),n.flowing||(yt("pipe resume"),r.resume()),e};function aB(e){return function(){var t=e._readableState;yt("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&f2(e,"data")&&(t.flowing=true,Sb(e));}}Mt.prototype.unpipe=function(e){var t=this._readableState,r={hasUnpiped:false};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=false,e&&e.emit("unpipe",this,r),this);if(!e){var n=t.pipes,a=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=false;for(var o=0;o<a;o++)n[o].emit("unpipe",this,{hasUnpiped:false});return this}var i=b2(t.pipes,e);return i===-1?this:(t.pipes.splice(i,1),t.pipesCount-=1,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,r),this)};Mt.prototype.on=function(e,t){var r=_b.prototype.on.call(this,e,t);if(e==="data")this._readableState.flowing!==false&&this.resume();else if(e==="readable"){var n=this._readableState;!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=true,n.emittedReadable=false,n.reading?n.length&&Qm(this):qc.nextTick(oB,this));}return r};Mt.prototype.addListener=Mt.prototype.on;function oB(e){yt("readable nexttick read 0"),e.read(0);}Mt.prototype.resume=function(){var e=this._readableState;return e.flowing||(yt("resume"),e.flowing=true,iB(this,e)),this};function iB(e,t){t.resumeScheduled||(t.resumeScheduled=true,qc.nextTick(sB,e,t));}function sB(e,t){t.reading||(yt("resume read 0"),e.read(0)),t.resumeScheduled=false,t.awaitDrain=0,e.emit("resume"),Sb(e),t.flowing&&!t.reading&&e.read(0);}Mt.prototype.pause=function(){return yt("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==false&&(yt("pause"),this._readableState.flowing=false,this.emit("pause")),this};function Sb(e){var t=e._readableState;for(yt("flow",t.flowing);t.flowing&&e.read()!==null;);}Mt.prototype.wrap=function(e){var t=this,r=this._readableState,n=false;e.on("end",function(){if(yt("wrapped end"),r.decoder&&!r.ended){var i=r.decoder.end();i&&i.length&&t.push(i);}t.push(null);}),e.on("data",function(i){if(yt("wrapped data"),r.decoder&&(i=r.decoder.write(i)),!(r.objectMode&&i==null)&&!(!r.objectMode&&(!i||!i.length))){var s=t.push(i);s||(n=true,e.pause());}});for(var a in e)this[a]===void 0&&typeof e[a]=="function"&&(this[a]=(function(i){return function(){return e[i].apply(e,arguments)}})(a));for(var o=0;o<bb.length;o++)e.on(bb[o],this.emit.bind(this,bb[o]));return this._read=function(i){yt("wrapped _read",i),n&&(n=false,e.resume());},this};Object.defineProperty(Mt.prototype,"readableHighWaterMark",{enumerable:false,get:function(){return this._readableState.highWaterMark}});Mt._fromList=v2;function v2(e,t){if(t.length===0)return null;var r;return t.objectMode?r=t.buffer.shift():!e||e>=t.length?(t.decoder?r=t.buffer.join(""):t.buffer.length===1?r=t.buffer.head.data:r=t.buffer.concat(t.length),t.buffer.clear()):r=lB(e,t.buffer,t.decoder),r}function lB(e,t,r){var n;return e<t.head.data.length?(n=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):e===t.head.data.length?n=t.shift():n=r?cB(e,t):uB(e,t),n}function cB(e,t){var r=t.head,n=1,a=r.data;for(e-=a.length;r=r.next;){var o=r.data,i=e>o.length?o.length:e;if(i===o.length?a+=o:a+=o.slice(0,e),e-=i,e===0){i===o.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(i));break}++n;}return t.length-=n,a}function uB(e,t){var r=Fd.allocUnsafe(e),n=t.head,a=1;for(n.data.copy(r),e-=n.data.length;n=n.next;){var o=n.data,i=e>o.length?o.length:e;if(o.copy(r,r.length-e,0,i),e-=i,e===0){i===o.length?(++a,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(i));break}++a;}return t.length-=a,r}function wb(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=true,qc.nextTick(dB,t,e));}function dB(e,t){!e.endEmitted&&e.length===0&&(e.endEmitted=true,t.readable=false,t.emit("end"));}function b2(e,t){for(var r=0,n=e.length;r<n;r++)if(e[r]===t)return r;return -1}});var Nb=B((nle,S2)=>{S2.exports=Vo;var Ym=nl(),_2=Object.create(Lc());_2.inherits=Bc();_2.inherits(Vo,Ym);function fB(e,t){var r=this._transformState;r.transforming=false;var n=r.writecb;if(!n)return this.emit("error",new Error("write callback called multiple times"));r.writechunk=null,r.writecb=null,t!=null&&this.push(t),n(e);var a=this._readableState;a.reading=false,(a.needReadable||a.length<a.highWaterMark)&&this._read(a.highWaterMark);}function Vo(e){if(!(this instanceof Vo))return new Vo(e);Ym.call(this,e),this._transformState={afterTransform:fB.bind(this),needTransform:false,transforming:false,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=true,this._readableState.sync=false,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.on("prefinish",pB);}function pB(){var e=this;typeof this._flush=="function"?this._flush(function(t,r){w2(e,t,r);}):w2(this,null,null);}Vo.prototype.push=function(e,t){return this._transformState.needTransform=false,Ym.prototype.push.call(this,e,t)};Vo.prototype._transform=function(e,t,r){throw new Error("_transform() is not implemented")};Vo.prototype._write=function(e,t,r){var n=this._transformState;if(n.writecb=r,n.writechunk=e,n.writeencoding=t,!n.transforming){var a=this._readableState;(n.needTransform||a.needReadable||a.length<a.highWaterMark)&&this._read(a.highWaterMark);}};Vo.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&t.writecb&&!t.transforming?(t.transforming=true,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=true;};Vo.prototype._destroy=function(e,t){var r=this;Ym.prototype._destroy.call(this,e,function(n){t(n),r.emit("close");});};function w2(e,t,r){if(t)return e.emit("error",t);if(r!=null&&e.push(r),e._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(e._transformState.transforming)throw new Error("Calling transform done when still transforming");return e.push(null)}});var P2=B((ale,E2)=>{E2.exports=Md;var N2=Nb(),C2=Object.create(Lc());C2.inherits=Bc();C2.inherits(Md,N2);function Md(e){if(!(this instanceof Md))return new Md(e);N2.call(this,e);}Md.prototype._transform=function(e,t,r){r(null,e);};});var Cb=B((Or,eh)=>{var so=yo("stream");process.env.READABLE_STREAM==="disable"&&so?(eh.exports=so,Or=eh.exports=so.Readable,Or.Readable=so.Readable,Or.Writable=so.Writable,Or.Duplex=so.Duplex,Or.Transform=so.Transform,Or.PassThrough=so.PassThrough,Or.Stream=so):(Or=eh.exports=mb(),Or.Stream=so||Or,Or.Readable=Or,Or.Writable=db(),Or.Duplex=nl(),Or.Transform=Nb(),Or.PassThrough=P2());});var Ho=B($n=>{$n.base64=true;$n.array=true;$n.string=true;$n.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u";$n.nodebuffer=typeof Buffer<"u";$n.uint8array=typeof Uint8Array<"u";if(typeof ArrayBuffer>"u")$n.blob=false;else {Eb=new ArrayBuffer(0);try{$n.blob=new Blob([Eb],{type:"application/zip"}).size===0;}catch{try{T2=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,Pb=new T2,Pb.append(Eb),$n.blob=Pb.getBlob("application/zip").size===0;}catch{$n.blob=false;}}}var Eb,T2,Pb;try{$n.nodestream=!!Cb().Readable;}catch{$n.nodestream=false;}});var kb=B(Tb=>{var mB=Xt(),hB=Ho(),lo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";Tb.encode=function(e){for(var t=[],r,n,a,o,i,s,l,c=0,u=e.length,d=u,g=mB.getTypeOf(e)!=="string";c<e.length;)d=u-c,g?(r=e[c++],n=c<u?e[c++]:0,a=c<u?e[c++]:0):(r=e.charCodeAt(c++),n=c<u?e.charCodeAt(c++):0,a=c<u?e.charCodeAt(c++):0),o=r>>2,i=(r&3)<<4|n>>4,s=d>1?(n&15)<<2|a>>6:64,l=d>2?a&63:64,t.push(lo.charAt(o)+lo.charAt(i)+lo.charAt(s)+lo.charAt(l));return t.join("")};Tb.decode=function(e){var t,r,n,a,o,i,s,l=0,c=0,u="data:";if(e.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");e=e.replace(/[^A-Za-z0-9+/=]/g,"");var d=e.length*3/4;if(e.charAt(e.length-1)===lo.charAt(64)&&d--,e.charAt(e.length-2)===lo.charAt(64)&&d--,d%1!==0)throw new Error("Invalid base64 input, bad content length.");var g;for(hB.uint8array?g=new Uint8Array(d|0):g=new Array(d|0);l<e.length;)a=lo.indexOf(e.charAt(l++)),o=lo.indexOf(e.charAt(l++)),i=lo.indexOf(e.charAt(l++)),s=lo.indexOf(e.charAt(l++)),t=a<<2|o>>4,r=(o&15)<<4|i>>2,n=(i&3)<<6|s,g[c++]=t,i!==64&&(g[c++]=r),s!==64&&(g[c++]=n);return g};});var jd=B((sle,k2)=>{k2.exports={isNode:typeof Buffer<"u",newBufferFrom:function(e,t){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,t);if(typeof e=="number")throw new Error('The "data" argument must not be a number');return new Buffer(e,t)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&typeof e.on=="function"&&typeof e.pause=="function"&&typeof e.resume=="function"}};});var A2=B((lle,D2)=>{var R2=global.MutationObserver||global.WebKitMutationObserver,Vc;process.browser?R2?(Rb=0,O2=new R2(Ld),Ob=global.document.createTextNode(""),O2.observe(Ob,{characterData:true}),Vc=function(){Ob.data=Rb=++Rb%2;}):!global.setImmediate&&typeof global.MessageChannel<"u"?(Db=new global.MessageChannel,Db.port1.onmessage=Ld,Vc=function(){Db.port2.postMessage(0);}):"document"in global&&"onreadystatechange"in global.document.createElement("script")?Vc=function(){var e=global.document.createElement("script");e.onreadystatechange=function(){Ld(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null;},global.document.documentElement.appendChild(e);}:Vc=function(){setTimeout(Ld,0);}:Vc=function(){process.nextTick(Ld);};var Rb,O2,Ob,Db,Ab,Bd=[];function Ld(){Ab=true;for(var e,t,r=Bd.length;r;){for(t=Bd,Bd=[],e=-1;++e<r;)t[e]();r=Bd.length;}Ab=false;}D2.exports=gB;function gB(e){Bd.push(e)===1&&!Ab&&Vc();}});var B2=B((cle,L2)=>{var $2=A2();function Hc(){}var Wr={},I2=["REJECTED"],$b=["FULFILLED"],F2=["PENDING"];process.browser||(zd=["UNHANDLED"]);var zd;L2.exports=Hi;function Hi(e){if(typeof e!="function")throw new TypeError("resolver must be a function");this.state=F2,this.queue=[],this.outcome=void 0,process.browser||(this.handled=zd),e!==Hc&&M2(this,e);}Hi.prototype.finally=function(e){if(typeof e!="function")return this;var t=this.constructor;return this.then(r,n);function r(a){function o(){return a}return t.resolve(e()).then(o)}function n(a){function o(){throw a}return t.resolve(e()).then(o)}};Hi.prototype.catch=function(e){return this.then(null,e)};Hi.prototype.then=function(e,t){if(typeof e!="function"&&this.state===$b||typeof t!="function"&&this.state===I2)return this;var r=new this.constructor(Hc);if(process.browser||this.handled===zd&&(this.handled=null),this.state!==F2){var n=this.state===$b?e:t;Ib(r,n,this.outcome);}else this.queue.push(new Ud(r,e,t));return r};function Ud(e,t,r){this.promise=e,typeof t=="function"&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),typeof r=="function"&&(this.onRejected=r,this.callRejected=this.otherCallRejected);}Ud.prototype.callFulfilled=function(e){Wr.resolve(this.promise,e);};Ud.prototype.otherCallFulfilled=function(e){Ib(this.promise,this.onFulfilled,e);};Ud.prototype.callRejected=function(e){Wr.reject(this.promise,e);};Ud.prototype.otherCallRejected=function(e){Ib(this.promise,this.onRejected,e);};function Ib(e,t,r){$2(function(){var n;try{n=t(r);}catch(a){return Wr.reject(e,a)}n===e?Wr.reject(e,new TypeError("Cannot resolve promise with itself")):Wr.resolve(e,n);});}Wr.resolve=function(e,t){var r=j2(yB,t);if(r.status==="error")return Wr.reject(e,r.value);var n=r.value;if(n)M2(e,n);else {e.state=$b,e.outcome=t;for(var a=-1,o=e.queue.length;++a<o;)e.queue[a].callFulfilled(t);}return e};Wr.reject=function(e,t){e.state=I2,e.outcome=t,process.browser||e.handled===zd&&$2(function(){e.handled===zd&&process.emit("unhandledRejection",t,e);});for(var r=-1,n=e.queue.length;++r<n;)e.queue[r].callRejected(t);return e};function yB(e){var t=e&&e.then;if(e&&(typeof e=="object"||typeof e=="function")&&typeof t=="function")return function(){t.apply(e,arguments);}}function M2(e,t){var r=false;function n(s){r||(r=true,Wr.reject(e,s));}function a(s){r||(r=true,Wr.resolve(e,s));}function o(){t(a,n);}var i=j2(o);i.status==="error"&&n(i.value);}function j2(e,t){var r={};try{r.value=e(t),r.status="success";}catch(n){r.status="error",r.value=n;}return r}Hi.resolve=vB;function vB(e){return e instanceof this?e:Wr.resolve(new this(Hc),e)}Hi.reject=bB;function bB(e){var t=new this(Hc);return Wr.reject(t,e)}Hi.all=xB;function xB(e){var t=this;if(Object.prototype.toString.call(e)!=="[object Array]")return this.reject(new TypeError("must be an array"));var r=e.length,n=false;if(!r)return this.resolve([]);for(var a=new Array(r),o=0,i=-1,s=new this(Hc);++i<r;)l(e[i],i);return s;function l(c,u){t.resolve(c).then(d,function(g){n||(n=true,Wr.reject(s,g));});function d(g){a[u]=g,++o===r&&!n&&(n=true,Wr.resolve(s,a));}}}Hi.race=wB;function wB(e){var t=this;if(Object.prototype.toString.call(e)!=="[object Array]")return this.reject(new TypeError("must be an array"));var r=e.length,n=false;if(!r)return this.resolve([]);for(var a=-1,o=new this(Hc);++a<r;)i(e[a]);return o;function i(s){t.resolve(s).then(function(l){n||(n=true,Wr.resolve(o,l));},function(l){n||(n=true,Wr.reject(o,l));});}}});var Jc=B((ule,z2)=>{var Fb=null;typeof Promise<"u"?Fb=Promise:Fb=B2();z2.exports={Promise:Fb};});var q2=B(U2=>{(function(e,t){if(e.setImmediate)return;var r=1,n={},a=false,o=e.document,i;function s(y){typeof y!="function"&&(y=new Function(""+y));for(var x=new Array(arguments.length-1),w=0;w<x.length;w++)x[w]=arguments[w+1];var _={callback:y,args:x};return n[r]=_,i(r),r++}function l(y){delete n[y];}function c(y){var x=y.callback,w=y.args;switch(w.length){case 0:x();break;case 1:x(w[0]);break;case 2:x(w[0],w[1]);break;case 3:x(w[0],w[1],w[2]);break;default:x.apply(t,w);break}}function u(y){if(a)setTimeout(u,0,y);else {var x=n[y];if(x){a=true;try{c(x);}finally{l(y),a=false;}}}}function d(){i=function(y){process.nextTick(function(){u(y);});};}function g(){if(e.postMessage&&!e.importScripts){var y=true,x=e.onmessage;return e.onmessage=function(){y=false;},e.postMessage("","*"),e.onmessage=x,y}}function f(){var y="setImmediate$"+Math.random()+"$",x=function(w){w.source===e&&typeof w.data=="string"&&w.data.indexOf(y)===0&&u(+w.data.slice(y.length));};e.addEventListener?e.addEventListener("message",x,false):e.attachEvent("onmessage",x),i=function(w){e.postMessage(y+w,"*");};}function h(){var y=new MessageChannel;y.port1.onmessage=function(x){var w=x.data;u(w);},i=function(x){y.port2.postMessage(x);};}function m(){var y=o.documentElement;i=function(x){var w=o.createElement("script");w.onreadystatechange=function(){u(x),w.onreadystatechange=null,y.removeChild(w),w=null;},y.appendChild(w);};}function p(){i=function(y){setTimeout(u,0,y);};}var v=Object.getPrototypeOf&&Object.getPrototypeOf(e);v=v&&v.setTimeout?v:e,{}.toString.call(e.process)==="[object process]"?d():g()?f():e.MessageChannel?h():o&&"onreadystatechange"in o.createElement("script")?m():p(),v.setImmediate=s,v.clearImmediate=l;})(typeof self>"u"?typeof global>"u"?U2:global:self);});var Xt=B(lr=>{var Ji=Ho(),_B=kb(),Wc=jd(),Mb=Jc();q2();function SB(e){var t=null;return Ji.uint8array?t=new Uint8Array(e.length):t=new Array(e.length),rh(e,t)}lr.newBlob=function(e,t){lr.checkSupport("blob");try{return new Blob([e],{type:t})}catch{try{var r=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,n=new r;return n.append(e),n.getBlob(t)}catch{throw new Error("Bug : can't construct the Blob.")}}};function qd(e){return e}function rh(e,t){for(var r=0;r<e.length;++r)t[r]=e.charCodeAt(r)&255;return t}var th={stringifyByChunk:function(e,t,r){var n=[],a=0,o=e.length;if(o<=r)return String.fromCharCode.apply(null,e);for(;a<o;)t==="array"||t==="nodebuffer"?n.push(String.fromCharCode.apply(null,e.slice(a,Math.min(a+r,o)))):n.push(String.fromCharCode.apply(null,e.subarray(a,Math.min(a+r,o)))),a+=r;return n.join("")},stringifyByChar:function(e){for(var t="",r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t},applyCanBeUsed:{uint8array:(function(){try{return Ji.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return false}})(),nodebuffer:(function(){try{return Ji.nodebuffer&&String.fromCharCode.apply(null,Wc.allocBuffer(1)).length===1}catch{return false}})()}};function Vd(e){var t=65536,r=lr.getTypeOf(e),n=true;if(r==="uint8array"?n=th.applyCanBeUsed.uint8array:r==="nodebuffer"&&(n=th.applyCanBeUsed.nodebuffer),n)for(;t>1;)try{return th.stringifyByChunk(e,r,t)}catch{t=Math.floor(t/2);}return th.stringifyByChar(e)}lr.applyFromCharCode=Vd;function nh(e,t){for(var r=0;r<e.length;r++)t[r]=e[r];return t}var Wi={};Wi.string={string:qd,array:function(e){return rh(e,new Array(e.length))},arraybuffer:function(e){return Wi.string.uint8array(e).buffer},uint8array:function(e){return rh(e,new Uint8Array(e.length))},nodebuffer:function(e){return rh(e,Wc.allocBuffer(e.length))}};Wi.array={string:Vd,array:qd,arraybuffer:function(e){return new Uint8Array(e).buffer},uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return Wc.newBufferFrom(e)}};Wi.arraybuffer={string:function(e){return Vd(new Uint8Array(e))},array:function(e){return nh(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:qd,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return Wc.newBufferFrom(new Uint8Array(e))}};Wi.uint8array={string:Vd,array:function(e){return nh(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:qd,nodebuffer:function(e){return Wc.newBufferFrom(e)}};Wi.nodebuffer={string:Vd,array:function(e){return nh(e,new Array(e.length))},arraybuffer:function(e){return Wi.nodebuffer.uint8array(e).buffer},uint8array:function(e){return nh(e,new Uint8Array(e.length))},nodebuffer:qd};lr.transformTo=function(e,t){if(t||(t=""),!e)return t;lr.checkSupport(e);var r=lr.getTypeOf(t),n=Wi[r][e](t);return n};lr.resolve=function(e){for(var t=e.split("/"),r=[],n=0;n<t.length;n++){var a=t[n];a==="."||a===""&&n!==0&&n!==t.length-1||(a===".."?r.pop():r.push(a));}return r.join("/")};lr.getTypeOf=function(e){if(typeof e=="string")return "string";if(Object.prototype.toString.call(e)==="[object Array]")return "array";if(Ji.nodebuffer&&Wc.isBuffer(e))return "nodebuffer";if(Ji.uint8array&&e instanceof Uint8Array)return "uint8array";if(Ji.arraybuffer&&e instanceof ArrayBuffer)return "arraybuffer"};lr.checkSupport=function(e){var t=Ji[e.toLowerCase()];if(!t)throw new Error(e+" is not supported by this platform")};lr.MAX_VALUE_16BITS=65535;lr.MAX_VALUE_32BITS=-1;lr.pretty=function(e){var t="",r,n;for(n=0;n<(e||"").length;n++)r=e.charCodeAt(n),t+="\\x"+(r<16?"0":"")+r.toString(16).toUpperCase();return t};lr.delay=function(e,t,r){setImmediate(function(){e.apply(r||null,t||[]);});};lr.inherits=function(e,t){var r=function(){};r.prototype=t.prototype,e.prototype=new r;};lr.extend=function(){var e={},t,r;for(t=0;t<arguments.length;t++)for(r in arguments[t])Object.prototype.hasOwnProperty.call(arguments[t],r)&&typeof e[r]>"u"&&(e[r]=arguments[t][r]);return e};lr.prepareContent=function(e,t,r,n,a){var o=Mb.Promise.resolve(t).then(function(i){var s=Ji.blob&&(i instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(i))!==-1);return s&&typeof FileReader<"u"?new Mb.Promise(function(l,c){var u=new FileReader;u.onload=function(d){l(d.target.result);},u.onerror=function(d){c(d.target.error);},u.readAsArrayBuffer(i);}):i});return o.then(function(i){var s=lr.getTypeOf(i);return s?(s==="arraybuffer"?i=lr.transformTo("uint8array",i):s==="string"&&(a?i=_B.decode(i):r&&n!==true&&(i=SB(i))),i):Mb.Promise.reject(new Error("Can't read the data of '"+e+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})};});var In=B((ple,H2)=>{function V2(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=true,this.isFinished=false,this.isLocked=false,this._listeners={data:[],end:[],error:[]},this.previous=null;}V2.prototype={push:function(e){this.emit("data",e);},end:function(){if(this.isFinished)return false;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0;}catch(e){this.emit("error",e);}return true},error:function(e){return this.isFinished?false:(this.isPaused?this.generatedError=e:(this.isFinished=true,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),true)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[];},emit:function(e,t){if(this._listeners[e])for(var r=0;r<this._listeners[e].length;r++)this._listeners[e][r].call(this,t);},pipe:function(e){return e.registerPrevious(this)},registerPrevious:function(e){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=e.streamInfo,this.mergeStreamInfo(),this.previous=e;var t=this;return e.on("data",function(r){t.processChunk(r);}),e.on("end",function(){t.end();}),e.on("error",function(r){t.error(r);}),this},pause:function(){return this.isPaused||this.isFinished?false:(this.isPaused=true,this.previous&&this.previous.pause(),true)},resume:function(){if(!this.isPaused||this.isFinished)return false;this.isPaused=false;var e=false;return this.generatedError&&(this.error(this.generatedError),e=true),this.previous&&this.previous.resume(),!e},flush:function(){},processChunk:function(e){this.push(e);},withStreamInfo:function(e,t){return this.extraStreamInfo[e]=t,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var e in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,e)&&(this.streamInfo[e]=this.extraStreamInfo[e]);},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=true,this.previous&&this.previous.lock();},toString:function(){var e="Worker "+this.name;return this.previous?this.previous+" -> "+e:e}};H2.exports=V2;});var Gc=B(Ki=>{var Kc=Xt(),al=Ho(),NB=jd(),ah=In(),Hd=new Array(256);for(Jo=0;Jo<256;Jo++)Hd[Jo]=Jo>=252?6:Jo>=248?5:Jo>=240?4:Jo>=224?3:Jo>=192?2:1;var Jo;Hd[254]=Hd[254]=1;var CB=function(e){var t,r,n,a,o,i=e.length,s=0;for(a=0;a<i;a++)r=e.charCodeAt(a),(r&64512)===55296&&a+1<i&&(n=e.charCodeAt(a+1),(n&64512)===56320&&(r=65536+(r-55296<<10)+(n-56320),a++)),s+=r<128?1:r<2048?2:r<65536?3:4;for(al.uint8array?t=new Uint8Array(s):t=new Array(s),o=0,a=0;o<s;a++)r=e.charCodeAt(a),(r&64512)===55296&&a+1<i&&(n=e.charCodeAt(a+1),(n&64512)===56320&&(r=65536+(r-55296<<10)+(n-56320),a++)),r<128?t[o++]=r:r<2048?(t[o++]=192|r>>>6,t[o++]=128|r&63):r<65536?(t[o++]=224|r>>>12,t[o++]=128|r>>>6&63,t[o++]=128|r&63):(t[o++]=240|r>>>18,t[o++]=128|r>>>12&63,t[o++]=128|r>>>6&63,t[o++]=128|r&63);return t},EB=function(e,t){var r;for(t=t||e.length,t>e.length&&(t=e.length),r=t-1;r>=0&&(e[r]&192)===128;)r--;return r<0||r===0?t:r+Hd[e[r]]>t?r:t},PB=function(e){var t,r,n,a,o=e.length,i=new Array(o*2);for(r=0,t=0;t<o;){if(n=e[t++],n<128){i[r++]=n;continue}if(a=Hd[n],a>4){i[r++]=65533,t+=a-1;continue}for(n&=a===2?31:a===3?15:7;a>1&&t<o;)n=n<<6|e[t++]&63,a--;if(a>1){i[r++]=65533;continue}n<65536?i[r++]=n:(n-=65536,i[r++]=55296|n>>10&1023,i[r++]=56320|n&1023);}return i.length!==r&&(i.subarray?i=i.subarray(0,r):i.length=r),Kc.applyFromCharCode(i)};Ki.utf8encode=function(t){return al.nodebuffer?NB.newBufferFrom(t,"utf-8"):CB(t)};Ki.utf8decode=function(t){return al.nodebuffer?Kc.transformTo("nodebuffer",t).toString("utf-8"):(t=Kc.transformTo(al.uint8array?"uint8array":"array",t),PB(t))};function oh(){ah.call(this,"utf-8 decode"),this.leftOver=null;}Kc.inherits(oh,ah);oh.prototype.processChunk=function(e){var t=Kc.transformTo(al.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(al.uint8array){var r=t;t=new Uint8Array(r.length+this.leftOver.length),t.set(this.leftOver,0),t.set(r,this.leftOver.length);}else t=this.leftOver.concat(t);this.leftOver=null;}var n=EB(t),a=t;n!==t.length&&(al.uint8array?(a=t.subarray(0,n),this.leftOver=t.subarray(n,t.length)):(a=t.slice(0,n),this.leftOver=t.slice(n,t.length))),this.push({data:Ki.utf8decode(a),meta:e.meta});};oh.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:Ki.utf8decode(this.leftOver),meta:{}}),this.leftOver=null);};Ki.Utf8DecodeWorker=oh;function jb(){ah.call(this,"utf-8 encode");}Kc.inherits(jb,ah);jb.prototype.processChunk=function(e){this.push({data:Ki.utf8encode(e.data),meta:e.meta});};Ki.Utf8EncodeWorker=jb;});var G2=B((hle,K2)=>{var J2=In(),W2=Xt();function Lb(e){J2.call(this,"ConvertWorker to "+e),this.destType=e;}W2.inherits(Lb,J2);Lb.prototype.processChunk=function(e){this.push({data:W2.transformTo(this.destType,e.data),meta:e.meta});};K2.exports=Lb;});var Q2=B((gle,X2)=>{var Z2=Cb().Readable,TB=Xt();TB.inherits(Bb,Z2);function Bb(e,t,r){Z2.call(this,t),this._helper=e;var n=this;e.on("data",function(a,o){n.push(a)||n._helper.pause(),r&&r(o);}).on("error",function(a){n.emit("error",a);}).on("end",function(){n.push(null);});}Bb.prototype._read=function(){this._helper.resume();};X2.exports=Bb;});var zb=B((yle,tT)=>{var ol=Xt(),kB=G2(),RB=In(),OB=kb(),DB=Ho(),AB=Jc(),Y2=null;if(DB.nodestream)try{Y2=Q2();}catch{}function $B(e,t,r){switch(e){case "blob":return ol.newBlob(ol.transformTo("arraybuffer",t),r);case "base64":return OB.encode(t);default:return ol.transformTo(e,t)}}function IB(e,t){var r,n=0,a=null,o=0;for(r=0;r<t.length;r++)o+=t[r].length;switch(e){case "string":return t.join("");case "array":return Array.prototype.concat.apply([],t);case "uint8array":for(a=new Uint8Array(o),r=0;r<t.length;r++)a.set(t[r],n),n+=t[r].length;return a;case "nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}function FB(e,t){return new AB.Promise(function(r,n){var a=[],o=e._internalType,i=e._outputType,s=e._mimeType;e.on("data",function(l,c){a.push(l),t&&t(c);}).on("error",function(l){a=[],n(l);}).on("end",function(){try{var l=$B(i,IB(o,a),s);r(l);}catch(c){n(c);}a=[];}).resume();})}function eT(e,t,r){var n=t;switch(t){case "blob":case "arraybuffer":n="uint8array";break;case "base64":n="string";break}try{this._internalType=n,this._outputType=t,this._mimeType=r,ol.checkSupport(n),this._worker=e.pipe(new kB(n)),e.lock();}catch(a){this._worker=new RB("error"),this._worker.error(a);}}eT.prototype={accumulate:function(e){return FB(this,e)},on:function(e,t){var r=this;return e==="data"?this._worker.on(e,function(n){t.call(r,n.data,n.meta);}):this._worker.on(e,function(){ol.delay(t,arguments,r);}),this},resume:function(){return ol.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(e){if(ol.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new Y2(this,{objectMode:this._outputType!=="nodebuffer"},e)}};tT.exports=eT;});var Ub=B(Fa=>{Fa.base64=false;Fa.binary=false;Fa.dir=false;Fa.createFolders=true;Fa.date=null;Fa.compression=null;Fa.compressionOptions=null;Fa.comment=null;Fa.unixPermissions=null;Fa.dosPermissions=null;});var qb=B((ble,rT)=>{var ih=Xt(),sh=In(),MB=16*1024;function Zc(e){sh.call(this,"DataWorker");var t=this;this.dataIsReady=false,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=false,e.then(function(r){t.dataIsReady=true,t.data=r,t.max=r&&r.length||0,t.type=ih.getTypeOf(r),t.isPaused||t._tickAndRepeat();},function(r){t.error(r);});}ih.inherits(Zc,sh);Zc.prototype.cleanUp=function(){sh.prototype.cleanUp.call(this),this.data=null;};Zc.prototype.resume=function(){return sh.prototype.resume.call(this)?(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=true,ih.delay(this._tickAndRepeat,[],this)),true):false};Zc.prototype._tickAndRepeat=function(){this._tickScheduled=false,!(this.isPaused||this.isFinished)&&(this._tick(),this.isFinished||(ih.delay(this._tickAndRepeat,[],this),this._tickScheduled=true));};Zc.prototype._tick=function(){if(this.isPaused||this.isFinished)return false;var e=MB,t=null,r=Math.min(this.max,this.index+e);if(this.index>=this.max)return this.end();switch(this.type){case "string":t=this.data.substring(this.index,r);break;case "uint8array":t=this.data.subarray(this.index,r);break;case "array":case "nodebuffer":t=this.data.slice(this.index,r);break}return this.index=r,this.push({data:t,meta:{percent:this.max?this.index/this.max*100:0}})};rT.exports=Zc;});var lh=B((xle,aT)=>{var jB=Xt();function LB(){for(var e,t=[],r=0;r<256;r++){e=r;for(var n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;t[r]=e;}return t}var nT=LB();function BB(e,t,r,n){var a=nT,o=n+r;e=e^-1;for(var i=n;i<o;i++)e=e>>>8^a[(e^t[i])&255];return e^-1}function zB(e,t,r,n){var a=nT,o=n+r;e=e^-1;for(var i=n;i<o;i++)e=e>>>8^a[(e^t.charCodeAt(i))&255];return e^-1}aT.exports=function(t,r){if(typeof t>"u"||!t.length)return 0;var n=jB.getTypeOf(t)!=="string";return n?BB(r|0,t,t.length,0):zB(r|0,t,t.length,0)};});var Hb=B((wle,iT)=>{var oT=In(),UB=lh(),qB=Xt();function Vb(){oT.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0);}qB.inherits(Vb,oT);Vb.prototype.processChunk=function(e){this.streamInfo.crc32=UB(e.data,this.streamInfo.crc32||0),this.push(e);};iT.exports=Vb;});var lT=B((_le,sT)=>{var VB=Xt(),Jb=In();function Wb(e){Jb.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0);}VB.inherits(Wb,Jb);Wb.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length;}Jb.prototype.processChunk.call(this,e);};sT.exports=Wb;});var ch=B((Sle,dT)=>{var cT=Jc(),uT=qb(),HB=Hb(),Kb=lT();function Gb(e,t,r,n,a){this.compressedSize=e,this.uncompressedSize=t,this.crc32=r,this.compression=n,this.compressedContent=a;}Gb.prototype={getContentWorker:function(){var e=new uT(cT.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new Kb("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new uT(cT.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}};Gb.createWorkerFrom=function(e,t,r){return e.pipe(new HB).pipe(new Kb("uncompressedSize")).pipe(t.compressWorker(r)).pipe(new Kb("compressedSize")).withStreamInfo("compression",t)};dT.exports=Gb;});var hT=B((Nle,mT)=>{var JB=zb(),WB=qb(),Zb=Gc(),Xb=ch(),fT=In(),Qb=function(e,t,r){this.name=e,this.dir=r.dir,this.date=r.date,this.comment=r.comment,this.unixPermissions=r.unixPermissions,this.dosPermissions=r.dosPermissions,this._data=t,this._dataBinary=r.binary,this.options={compression:r.compression,compressionOptions:r.compressionOptions};};Qb.prototype={internalStream:function(e){var t=null,r="string";try{if(!e)throw new Error("No output type specified.");r=e.toLowerCase();var n=r==="string"||r==="text";(r==="binarystring"||r==="text")&&(r="string"),t=this._decompressWorker();var a=!this._dataBinary;a&&!n&&(t=t.pipe(new Zb.Utf8EncodeWorker)),!a&&n&&(t=t.pipe(new Zb.Utf8DecodeWorker));}catch(o){t=new fT("error"),t.error(o);}return new JB(t,r,"")},async:function(e,t){return this.internalStream(e).accumulate(t)},nodeStream:function(e,t){return this.internalStream(e||"nodebuffer").toNodejsStream(t)},_compressWorker:function(e,t){if(this._data instanceof Xb&&this._data.compression.magic===e.magic)return this._data.getCompressedWorker();var r=this._decompressWorker();return this._dataBinary||(r=r.pipe(new Zb.Utf8EncodeWorker)),Xb.createWorkerFrom(r,e,t)},_decompressWorker:function(){return this._data instanceof Xb?this._data.getContentWorker():this._data instanceof fT?this._data:new WB(this._data)}};var pT=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],KB=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")};for(uh=0;uh<pT.length;uh++)Qb.prototype[pT[uh]]=KB;var uh;mT.exports=Qb;});var Wo=B(en=>{var GB=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";function ZB(e,t){return Object.prototype.hasOwnProperty.call(e,t)}en.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var r=t.shift();if(r){if(typeof r!="object")throw new TypeError(r+"must be non-object");for(var n in r)ZB(r,n)&&(e[n]=r[n]);}}return e};en.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var XB={arraySet:function(e,t,r,n,a){if(t.subarray&&e.subarray){e.set(t.subarray(r,r+n),a);return}for(var o=0;o<n;o++)e[a+o]=t[r+o];},flattenChunks:function(e){var t,r,n,a,o,i;for(n=0,t=0,r=e.length;t<r;t++)n+=e[t].length;for(i=new Uint8Array(n),a=0,t=0,r=e.length;t<r;t++)o=e[t],i.set(o,a),a+=o.length;return i}},QB={arraySet:function(e,t,r,n,a){for(var o=0;o<n;o++)e[a+o]=t[r+o];},flattenChunks:function(e){return [].concat.apply([],e)}};en.setTyped=function(e){e?(en.Buf8=Uint8Array,en.Buf16=Uint16Array,en.Buf32=Int32Array,en.assign(en,XB)):(en.Buf8=Array,en.Buf16=Array,en.Buf32=Array,en.assign(en,QB));};en.setTyped(GB);});var jT=B(Yc=>{var YB=Wo(),ez=4,gT=0,yT=1,tz=2;function Qc(e){for(var t=e.length;--t>=0;)e[t]=0;}var rz=0,ST=1,nz=2,az=3,oz=258,ox=29,Xd=256,Wd=Xd+1+ox,Xc=30,ix=19,NT=2*Wd+1,il=15,Yb=16,iz=7,sx=256,CT=16,ET=17,PT=18,nx=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],dh=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],sz=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],TT=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],lz=512,Ko=new Array((Wd+2)*2);Qc(Ko);var Jd=new Array(Xc*2);Qc(Jd);var Kd=new Array(lz);Qc(Kd);var Gd=new Array(oz-az+1);Qc(Gd);var lx=new Array(ox);Qc(lx);var fh=new Array(Xc);Qc(fh);function ex(e,t,r,n,a){this.static_tree=e,this.extra_bits=t,this.extra_base=r,this.elems=n,this.max_length=a,this.has_stree=e&&e.length;}var kT,RT,OT;function tx(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t;}function DT(e){return e<256?Kd[e]:Kd[256+(e>>>7)]}function Zd(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255;}function Sn(e,t,r){e.bi_valid>Yb-r?(e.bi_buf|=t<<e.bi_valid&65535,Zd(e,e.bi_buf),e.bi_buf=t>>Yb-e.bi_valid,e.bi_valid+=r-Yb):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=r);}function co(e,t,r){Sn(e,r[t*2],r[t*2+1]);}function AT(e,t){var r=0;do r|=e&1,e>>>=1,r<<=1;while(--t>0);return r>>>1}function cz(e){e.bi_valid===16?(Zd(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8);}function uz(e,t){var r=t.dyn_tree,n=t.max_code,a=t.stat_desc.static_tree,o=t.stat_desc.has_stree,i=t.stat_desc.extra_bits,s=t.stat_desc.extra_base,l=t.stat_desc.max_length,c,u,d,g,f,h,m=0;for(g=0;g<=il;g++)e.bl_count[g]=0;for(r[e.heap[e.heap_max]*2+1]=0,c=e.heap_max+1;c<NT;c++)u=e.heap[c],g=r[r[u*2+1]*2+1]+1,g>l&&(g=l,m++),r[u*2+1]=g,!(u>n)&&(e.bl_count[g]++,f=0,u>=s&&(f=i[u-s]),h=r[u*2],e.opt_len+=h*(g+f),o&&(e.static_len+=h*(a[u*2+1]+f)));if(m!==0){do{for(g=l-1;e.bl_count[g]===0;)g--;e.bl_count[g]--,e.bl_count[g+1]+=2,e.bl_count[l]--,m-=2;}while(m>0);for(g=l;g!==0;g--)for(u=e.bl_count[g];u!==0;)d=e.heap[--c],!(d>n)&&(r[d*2+1]!==g&&(e.opt_len+=(g-r[d*2+1])*r[d*2],r[d*2+1]=g),u--);}}function $T(e,t,r){var n=new Array(il+1),a=0,o,i;for(o=1;o<=il;o++)n[o]=a=a+r[o-1]<<1;for(i=0;i<=t;i++){var s=e[i*2+1];s!==0&&(e[i*2]=AT(n[s]++,s));}}function dz(){var e,t,r,n,a,o=new Array(il+1);for(r=0,n=0;n<ox-1;n++)for(lx[n]=r,e=0;e<1<<nx[n];e++)Gd[r++]=n;for(Gd[r-1]=n,a=0,n=0;n<16;n++)for(fh[n]=a,e=0;e<1<<dh[n];e++)Kd[a++]=n;for(a>>=7;n<Xc;n++)for(fh[n]=a<<7,e=0;e<1<<dh[n]-7;e++)Kd[256+a++]=n;for(t=0;t<=il;t++)o[t]=0;for(e=0;e<=143;)Ko[e*2+1]=8,e++,o[8]++;for(;e<=255;)Ko[e*2+1]=9,e++,o[9]++;for(;e<=279;)Ko[e*2+1]=7,e++,o[7]++;for(;e<=287;)Ko[e*2+1]=8,e++,o[8]++;for($T(Ko,Wd+1,o),e=0;e<Xc;e++)Jd[e*2+1]=5,Jd[e*2]=AT(e,5);kT=new ex(Ko,nx,Xd+1,Wd,il),RT=new ex(Jd,dh,0,Xc,il),OT=new ex(new Array(0),sz,0,ix,iz);}function IT(e){var t;for(t=0;t<Wd;t++)e.dyn_ltree[t*2]=0;for(t=0;t<Xc;t++)e.dyn_dtree[t*2]=0;for(t=0;t<ix;t++)e.bl_tree[t*2]=0;e.dyn_ltree[sx*2]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0;}function FT(e){e.bi_valid>8?Zd(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0;}function fz(e,t,r,n){FT(e),(Zd(e,r),Zd(e,~r)),YB.arraySet(e.pending_buf,e.window,t,r,e.pending),e.pending+=r;}function vT(e,t,r,n){var a=t*2,o=r*2;return e[a]<e[o]||e[a]===e[o]&&n[t]<=n[r]}function rx(e,t,r){for(var n=e.heap[r],a=r<<1;a<=e.heap_len&&(a<e.heap_len&&vT(t,e.heap[a+1],e.heap[a],e.depth)&&a++,!vT(t,n,e.heap[a],e.depth));)e.heap[r]=e.heap[a],r=a,a<<=1;e.heap[r]=n;}function bT(e,t,r){var n,a,o=0,i,s;if(e.last_lit!==0)do n=e.pending_buf[e.d_buf+o*2]<<8|e.pending_buf[e.d_buf+o*2+1],a=e.pending_buf[e.l_buf+o],o++,n===0?co(e,a,t):(i=Gd[a],co(e,i+Xd+1,t),s=nx[i],s!==0&&(a-=lx[i],Sn(e,a,s)),n--,i=DT(n),co(e,i,r),s=dh[i],s!==0&&(n-=fh[i],Sn(e,n,s)));while(o<e.last_lit);co(e,sx,t);}function ax(e,t){var r=t.dyn_tree,n=t.stat_desc.static_tree,a=t.stat_desc.has_stree,o=t.stat_desc.elems,i,s,l=-1,c;for(e.heap_len=0,e.heap_max=NT,i=0;i<o;i++)r[i*2]!==0?(e.heap[++e.heap_len]=l=i,e.depth[i]=0):r[i*2+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=l<2?++l:0,r[c*2]=1,e.depth[c]=0,e.opt_len--,a&&(e.static_len-=n[c*2+1]);for(t.max_code=l,i=e.heap_len>>1;i>=1;i--)rx(e,r,i);c=o;do i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],rx(e,r,1),s=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=s,r[c*2]=r[i*2]+r[s*2],e.depth[c]=(e.depth[i]>=e.depth[s]?e.depth[i]:e.depth[s])+1,r[i*2+1]=r[s*2+1]=c,e.heap[1]=c++,rx(e,r,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],uz(e,t),$T(r,l,e.bl_count);}function xT(e,t,r){var n,a=-1,o,i=t[1],s=0,l=7,c=4;for(i===0&&(l=138,c=3),t[(r+1)*2+1]=65535,n=0;n<=r;n++)o=i,i=t[(n+1)*2+1],!(++s<l&&o===i)&&(s<c?e.bl_tree[o*2]+=s:o!==0?(o!==a&&e.bl_tree[o*2]++,e.bl_tree[CT*2]++):s<=10?e.bl_tree[ET*2]++:e.bl_tree[PT*2]++,s=0,a=o,i===0?(l=138,c=3):o===i?(l=6,c=3):(l=7,c=4));}function wT(e,t,r){var n,a=-1,o,i=t[1],s=0,l=7,c=4;for(i===0&&(l=138,c=3),n=0;n<=r;n++)if(o=i,i=t[(n+1)*2+1],!(++s<l&&o===i)){if(s<c)do co(e,o,e.bl_tree);while(--s!==0);else o!==0?(o!==a&&(co(e,o,e.bl_tree),s--),co(e,CT,e.bl_tree),Sn(e,s-3,2)):s<=10?(co(e,ET,e.bl_tree),Sn(e,s-3,3)):(co(e,PT,e.bl_tree),Sn(e,s-11,7));s=0,a=o,i===0?(l=138,c=3):o===i?(l=6,c=3):(l=7,c=4);}}function pz(e){var t;for(xT(e,e.dyn_ltree,e.l_desc.max_code),xT(e,e.dyn_dtree,e.d_desc.max_code),ax(e,e.bl_desc),t=ix-1;t>=3&&e.bl_tree[TT[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function mz(e,t,r,n){var a;for(Sn(e,t-257,5),Sn(e,r-1,5),Sn(e,n-4,4),a=0;a<n;a++)Sn(e,e.bl_tree[TT[a]*2+1],3);wT(e,e.dyn_ltree,t-1),wT(e,e.dyn_dtree,r-1);}function hz(e){var t=4093624447,r;for(r=0;r<=31;r++,t>>>=1)if(t&1&&e.dyn_ltree[r*2]!==0)return gT;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return yT;for(r=32;r<Xd;r++)if(e.dyn_ltree[r*2]!==0)return yT;return gT}var _T=false;function gz(e){_T||(dz(),_T=true),e.l_desc=new tx(e.dyn_ltree,kT),e.d_desc=new tx(e.dyn_dtree,RT),e.bl_desc=new tx(e.bl_tree,OT),e.bi_buf=0,e.bi_valid=0,IT(e);}function MT(e,t,r,n){Sn(e,(rz<<1)+(n?1:0),3),fz(e,t,r);}function yz(e){Sn(e,ST<<1,3),co(e,sx,Ko),cz(e);}function vz(e,t,r,n){var a,o,i=0;e.level>0?(e.strm.data_type===tz&&(e.strm.data_type=hz(e)),ax(e,e.l_desc),ax(e,e.d_desc),i=pz(e),a=e.opt_len+3+7>>>3,o=e.static_len+3+7>>>3,o<=a&&(a=o)):a=o=r+5,r+4<=a&&t!==-1?MT(e,t,r,n):e.strategy===ez||o===a?(Sn(e,(ST<<1)+(n?1:0),3),bT(e,Ko,Jd)):(Sn(e,(nz<<1)+(n?1:0),3),mz(e,e.l_desc.max_code+1,e.d_desc.max_code+1,i+1),bT(e,e.dyn_ltree,e.dyn_dtree)),IT(e),n&&FT(e);}function bz(e,t,r){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=r&255,e.last_lit++,t===0?e.dyn_ltree[r*2]++:(e.matches++,t--,e.dyn_ltree[(Gd[r]+Xd+1)*2]++,e.dyn_dtree[DT(t)*2]++),e.last_lit===e.lit_bufsize-1}Yc._tr_init=gz;Yc._tr_stored_block=MT;Yc._tr_flush_block=vz;Yc._tr_tally=bz;Yc._tr_align=yz;});var cx=B((Ple,LT)=>{function xz(e,t,r,n){for(var a=e&65535|0,o=e>>>16&65535|0,i=0;r!==0;){i=r>2e3?2e3:r,r-=i;do a=a+t[n++]|0,o=o+a|0;while(--i);a%=65521,o%=65521;}return a|o<<16|0}LT.exports=xz;});var ux=B((Tle,BT)=>{function wz(){for(var e,t=[],r=0;r<256;r++){e=r;for(var n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;t[r]=e;}return t}var _z=wz();function Sz(e,t,r,n){var a=_z,o=n+r;e^=-1;for(var i=n;i<o;i++)e=e>>>8^a[(e^t[i])&255];return e^-1}BT.exports=Sz;});var ph=B((kle,zT)=>{zT.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"};});var ZT=B(po=>{var tn=Wo(),ia=jT(),HT=cx(),Gi=ux(),Nz=ph(),ul=0,Cz=1,Ez=3,es=4,UT=5,fo=0,qT=1,sa=-2,Pz=-3,dx=-5,Tz=-1,kz=1,mh=2,Rz=3,Oz=4,Dz=0,Az=2,vh=8,$z=9,Iz=15,Fz=8,Mz=29,jz=256,px=jz+1+Mz,Lz=30,Bz=19,zz=2*px+1,Uz=15,ct=3,Qi=258,Ma=Qi+ct+1,qz=32,bh=42,mx=69,hh=73,gh=91,yh=103,sl=113,Yd=666,wr=1,ef=2,ll=3,ru=4,Vz=3;function Yi(e,t){return e.msg=Nz[t],t}function VT(e){return (e<<1)-(e>4?9:0)}function Xi(e){for(var t=e.length;--t>=0;)e[t]=0;}function Zi(e){var t=e.state,r=t.pending;r>e.avail_out&&(r=e.avail_out),r!==0&&(tn.arraySet(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,t.pending===0&&(t.pending_out=0));}function Dr(e,t){ia._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,Zi(e.strm);}function ht(e,t){e.pending_buf[e.pending++]=t;}function Qd(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255;}function Hz(e,t,r,n){var a=e.avail_in;return a>n&&(a=n),a===0?0:(e.avail_in-=a,tn.arraySet(t,e.input,e.next_in,a,r),e.state.wrap===1?e.adler=HT(e.adler,t,a,r):e.state.wrap===2&&(e.adler=Gi(e.adler,t,a,r)),e.next_in+=a,e.total_in+=a,a)}function JT(e,t){var r=e.max_chain_length,n=e.strstart,a,o,i=e.prev_length,s=e.nice_match,l=e.strstart>e.w_size-Ma?e.strstart-(e.w_size-Ma):0,c=e.window,u=e.w_mask,d=e.prev,g=e.strstart+Qi,f=c[n+i-1],h=c[n+i];e.prev_length>=e.good_match&&(r>>=2),s>e.lookahead&&(s=e.lookahead);do if(a=t,!(c[a+i]!==h||c[a+i-1]!==f||c[a]!==c[n]||c[++a]!==c[n+1])){n+=2,a++;do;while(c[++n]===c[++a]&&c[++n]===c[++a]&&c[++n]===c[++a]&&c[++n]===c[++a]&&c[++n]===c[++a]&&c[++n]===c[++a]&&c[++n]===c[++a]&&c[++n]===c[++a]&&n<g);if(o=Qi-(g-n),n=g-Qi,o>i){if(e.match_start=t,i=o,o>=s)break;f=c[n+i-1],h=c[n+i];}}while((t=d[t&u])>l&&--r!==0);return i<=e.lookahead?i:e.lookahead}function cl(e){var t=e.w_size,r,n,a,o,i;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Ma)){tn.arraySet(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,n=e.hash_size,r=n;do a=e.head[--r],e.head[r]=a>=t?a-t:0;while(--n);n=t,r=n;do a=e.prev[--r],e.prev[r]=a>=t?a-t:0;while(--n);o+=t;}if(e.strm.avail_in===0)break;if(n=Hz(e.strm,e.window,e.strstart+e.lookahead,o),e.lookahead+=n,e.lookahead+e.insert>=ct)for(i=e.strstart-e.insert,e.ins_h=e.window[i],e.ins_h=(e.ins_h<<e.hash_shift^e.window[i+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[i+ct-1])&e.hash_mask,e.prev[i&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=i,i++,e.insert--,!(e.lookahead+e.insert<ct)););}while(e.lookahead<Ma&&e.strm.avail_in!==0)}function Jz(e,t){var r=65535;for(r>e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(cl(e),e.lookahead===0&&t===ul)return wr;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+r;if((e.strstart===0||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,Dr(e,false),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-Ma&&(Dr(e,false),e.strm.avail_out===0))return wr}return e.insert=0,t===es?(Dr(e,true),e.strm.avail_out===0?ll:ru):(e.strstart>e.block_start&&(Dr(e,false),e.strm.avail_out===0),wr)}function fx(e,t){for(var r,n;;){if(e.lookahead<Ma){if(cl(e),e.lookahead<Ma&&t===ul)return wr;if(e.lookahead===0)break}if(r=0,e.lookahead>=ct&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+ct-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),r!==0&&e.strstart-r<=e.w_size-Ma&&(e.match_length=JT(e,r)),e.match_length>=ct)if(n=ia._tr_tally(e,e.strstart-e.match_start,e.match_length-ct),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=ct){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+ct-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++;}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else n=ia._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(Dr(e,false),e.strm.avail_out===0))return wr}return e.insert=e.strstart<ct-1?e.strstart:ct-1,t===es?(Dr(e,true),e.strm.avail_out===0?ll:ru):e.last_lit&&(Dr(e,false),e.strm.avail_out===0)?wr:ef}function eu(e,t){for(var r,n,a;;){if(e.lookahead<Ma){if(cl(e),e.lookahead<Ma&&t===ul)return wr;if(e.lookahead===0)break}if(r=0,e.lookahead>=ct&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+ct-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=ct-1,r!==0&&e.prev_length<e.max_lazy_match&&e.strstart-r<=e.w_size-Ma&&(e.match_length=JT(e,r),e.match_length<=5&&(e.strategy===kz||e.match_length===ct&&e.strstart-e.match_start>4096)&&(e.match_length=ct-1)),e.prev_length>=ct&&e.match_length<=e.prev_length){a=e.strstart+e.lookahead-ct,n=ia._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-ct),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=a&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+ct-1])&e.hash_mask,r=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=ct-1,e.strstart++,n&&(Dr(e,false),e.strm.avail_out===0))return wr}else if(e.match_available){if(n=ia._tr_tally(e,0,e.window[e.strstart-1]),n&&Dr(e,false),e.strstart++,e.lookahead--,e.strm.avail_out===0)return wr}else e.match_available=1,e.strstart++,e.lookahead--;}return e.match_available&&(n=ia._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<ct-1?e.strstart:ct-1,t===es?(Dr(e,true),e.strm.avail_out===0?ll:ru):e.last_lit&&(Dr(e,false),e.strm.avail_out===0)?wr:ef}function Wz(e,t){for(var r,n,a,o,i=e.window;;){if(e.lookahead<=Qi){if(cl(e),e.lookahead<=Qi&&t===ul)return wr;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=ct&&e.strstart>0&&(a=e.strstart-1,n=i[a],n===i[++a]&&n===i[++a]&&n===i[++a])){o=e.strstart+Qi;do;while(n===i[++a]&&n===i[++a]&&n===i[++a]&&n===i[++a]&&n===i[++a]&&n===i[++a]&&n===i[++a]&&n===i[++a]&&a<o);e.match_length=Qi-(o-a),e.match_length>e.lookahead&&(e.match_length=e.lookahead);}if(e.match_length>=ct?(r=ia._tr_tally(e,1,e.match_length-ct),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=ia._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(Dr(e,false),e.strm.avail_out===0))return wr}return e.insert=0,t===es?(Dr(e,true),e.strm.avail_out===0?ll:ru):e.last_lit&&(Dr(e,false),e.strm.avail_out===0)?wr:ef}function Kz(e,t){for(var r;;){if(e.lookahead===0&&(cl(e),e.lookahead===0)){if(t===ul)return wr;break}if(e.match_length=0,r=ia._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(Dr(e,false),e.strm.avail_out===0))return wr}return e.insert=0,t===es?(Dr(e,true),e.strm.avail_out===0?ll:ru):e.last_lit&&(Dr(e,false),e.strm.avail_out===0)?wr:ef}function uo(e,t,r,n,a){this.good_length=e,this.max_lazy=t,this.nice_length=r,this.max_chain=n,this.func=a;}var tu;tu=[new uo(0,0,0,0,Jz),new uo(4,4,8,4,fx),new uo(4,5,16,8,fx),new uo(4,6,32,32,fx),new uo(4,4,16,16,eu),new uo(8,16,32,32,eu),new uo(8,16,128,128,eu),new uo(8,32,128,256,eu),new uo(32,128,258,1024,eu),new uo(32,258,258,4096,eu)];function Gz(e){e.window_size=2*e.w_size,Xi(e.head),e.max_lazy_match=tu[e.level].max_lazy,e.good_match=tu[e.level].good_length,e.nice_match=tu[e.level].nice_length,e.max_chain_length=tu[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=ct-1,e.match_available=0,e.ins_h=0;}function Zz(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=vh,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new tn.Buf16(zz*2),this.dyn_dtree=new tn.Buf16((2*Lz+1)*2),this.bl_tree=new tn.Buf16((2*Bz+1)*2),Xi(this.dyn_ltree),Xi(this.dyn_dtree),Xi(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new tn.Buf16(Uz+1),this.heap=new tn.Buf16(2*px+1),Xi(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new tn.Buf16(2*px+1),Xi(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0;}function WT(e){var t;return !e||!e.state?Yi(e,sa):(e.total_in=e.total_out=0,e.data_type=Az,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?bh:sl,e.adler=t.wrap===2?0:1,t.last_flush=ul,ia._tr_init(t),fo)}function KT(e){var t=WT(e);return t===fo&&Gz(e.state),t}function Xz(e,t){return !e||!e.state||e.state.wrap!==2?sa:(e.state.gzhead=t,fo)}function GT(e,t,r,n,a,o){if(!e)return sa;var i=1;if(t===Tz&&(t=6),n<0?(i=0,n=-n):n>15&&(i=2,n-=16),a<1||a>$z||r!==vh||n<8||n>15||t<0||t>9||o<0||o>Oz)return Yi(e,sa);n===8&&(n=9);var s=new Zz;return e.state=s,s.strm=e,s.wrap=i,s.gzhead=null,s.w_bits=n,s.w_size=1<<s.w_bits,s.w_mask=s.w_size-1,s.hash_bits=a+7,s.hash_size=1<<s.hash_bits,s.hash_mask=s.hash_size-1,s.hash_shift=~~((s.hash_bits+ct-1)/ct),s.window=new tn.Buf8(s.w_size*2),s.head=new tn.Buf16(s.hash_size),s.prev=new tn.Buf16(s.w_size),s.lit_bufsize=1<<a+6,s.pending_buf_size=s.lit_bufsize*4,s.pending_buf=new tn.Buf8(s.pending_buf_size),s.d_buf=1*s.lit_bufsize,s.l_buf=3*s.lit_bufsize,s.level=t,s.strategy=o,s.method=r,KT(e)}function Qz(e,t){return GT(e,t,vh,Iz,Fz,Dz)}function Yz(e,t){var r,n,a,o;if(!e||!e.state||t>UT||t<0)return e?Yi(e,sa):sa;if(n=e.state,!e.output||!e.input&&e.avail_in!==0||n.status===Yd&&t!==es)return Yi(e,e.avail_out===0?dx:sa);if(n.strm=e,r=n.last_flush,n.last_flush=t,n.status===bh)if(n.wrap===2)e.adler=0,ht(n,31),ht(n,139),ht(n,8),n.gzhead?(ht(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),ht(n,n.gzhead.time&255),ht(n,n.gzhead.time>>8&255),ht(n,n.gzhead.time>>16&255),ht(n,n.gzhead.time>>24&255),ht(n,n.level===9?2:n.strategy>=mh||n.level<2?4:0),ht(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(ht(n,n.gzhead.extra.length&255),ht(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=Gi(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=mx):(ht(n,0),ht(n,0),ht(n,0),ht(n,0),ht(n,0),ht(n,n.level===9?2:n.strategy>=mh||n.level<2?4:0),ht(n,Vz),n.status=sl);else {var i=vh+(n.w_bits-8<<4)<<8,s=-1;n.strategy>=mh||n.level<2?s=0:n.level<6?s=1:n.level===6?s=2:s=3,i|=s<<6,n.strstart!==0&&(i|=qz),i+=31-i%31,n.status=sl,Qd(n,i),n.strstart!==0&&(Qd(n,e.adler>>>16),Qd(n,e.adler&65535)),e.adler=1;}if(n.status===mx)if(n.gzhead.extra){for(a=n.pending;n.gzindex<(n.gzhead.extra.length&65535)&&!(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>a&&(e.adler=Gi(e.adler,n.pending_buf,n.pending-a,a)),Zi(e),a=n.pending,n.pending===n.pending_buf_size));)ht(n,n.gzhead.extra[n.gzindex]&255),n.gzindex++;n.gzhead.hcrc&&n.pending>a&&(e.adler=Gi(e.adler,n.pending_buf,n.pending-a,a)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=hh);}else n.status=hh;if(n.status===hh)if(n.gzhead.name){a=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>a&&(e.adler=Gi(e.adler,n.pending_buf,n.pending-a,a)),Zi(e),a=n.pending,n.pending===n.pending_buf_size)){o=1;break}n.gzindex<n.gzhead.name.length?o=n.gzhead.name.charCodeAt(n.gzindex++)&255:o=0,ht(n,o);}while(o!==0);n.gzhead.hcrc&&n.pending>a&&(e.adler=Gi(e.adler,n.pending_buf,n.pending-a,a)),o===0&&(n.gzindex=0,n.status=gh);}else n.status=gh;if(n.status===gh)if(n.gzhead.comment){a=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>a&&(e.adler=Gi(e.adler,n.pending_buf,n.pending-a,a)),Zi(e),a=n.pending,n.pending===n.pending_buf_size)){o=1;break}n.gzindex<n.gzhead.comment.length?o=n.gzhead.comment.charCodeAt(n.gzindex++)&255:o=0,ht(n,o);}while(o!==0);n.gzhead.hcrc&&n.pending>a&&(e.adler=Gi(e.adler,n.pending_buf,n.pending-a,a)),o===0&&(n.status=yh);}else n.status=yh;if(n.status===yh&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&Zi(e),n.pending+2<=n.pending_buf_size&&(ht(n,e.adler&255),ht(n,e.adler>>8&255),e.adler=0,n.status=sl)):n.status=sl),n.pending!==0){if(Zi(e),e.avail_out===0)return n.last_flush=-1,fo}else if(e.avail_in===0&&VT(t)<=VT(r)&&t!==es)return Yi(e,dx);if(n.status===Yd&&e.avail_in!==0)return Yi(e,dx);if(e.avail_in!==0||n.lookahead!==0||t!==ul&&n.status!==Yd){var l=n.strategy===mh?Kz(n,t):n.strategy===Rz?Wz(n,t):tu[n.level].func(n,t);if((l===ll||l===ru)&&(n.status=Yd),l===wr||l===ll)return e.avail_out===0&&(n.last_flush=-1),fo;if(l===ef&&(t===Cz?ia._tr_align(n):t!==UT&&(ia._tr_stored_block(n,0,0,false),t===Ez&&(Xi(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),Zi(e),e.avail_out===0))return n.last_flush=-1,fo}return t!==es?fo:n.wrap<=0?qT:(n.wrap===2?(ht(n,e.adler&255),ht(n,e.adler>>8&255),ht(n,e.adler>>16&255),ht(n,e.adler>>24&255),ht(n,e.total_in&255),ht(n,e.total_in>>8&255),ht(n,e.total_in>>16&255),ht(n,e.total_in>>24&255)):(Qd(n,e.adler>>>16),Qd(n,e.adler&65535)),Zi(e),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?fo:qT)}function eU(e){var t;return !e||!e.state?sa:(t=e.state.status,t!==bh&&t!==mx&&t!==hh&&t!==gh&&t!==yh&&t!==sl&&t!==Yd?Yi(e,sa):(e.state=null,t===sl?Yi(e,Pz):fo))}function tU(e,t){var r=t.length,n,a,o,i,s,l,c,u;if(!e||!e.state||(n=e.state,i=n.wrap,i===2||i===1&&n.status!==bh||n.lookahead))return sa;for(i===1&&(e.adler=HT(e.adler,t,r,0)),n.wrap=0,r>=n.w_size&&(i===0&&(Xi(n.head),n.strstart=0,n.block_start=0,n.insert=0),u=new tn.Buf8(n.w_size),tn.arraySet(u,t,r-n.w_size,n.w_size,0),t=u,r=n.w_size),s=e.avail_in,l=e.next_in,c=e.input,e.avail_in=r,e.next_in=0,e.input=t,cl(n);n.lookahead>=ct;){a=n.strstart,o=n.lookahead-(ct-1);do n.ins_h=(n.ins_h<<n.hash_shift^n.window[a+ct-1])&n.hash_mask,n.prev[a&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=a,a++;while(--o);n.strstart=a,n.lookahead=ct-1,cl(n);}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=ct-1,n.match_available=0,e.next_in=l,e.input=c,e.avail_in=s,n.wrap=i,fo}po.deflateInit=Qz;po.deflateInit2=GT;po.deflateReset=KT;po.deflateResetKeep=WT;po.deflateSetHeader=Xz;po.deflate=Yz;po.deflateEnd=eU;po.deflateSetDictionary=tU;po.deflateInfo="pako deflate (from Nodeca project)";});var hx=B(nu=>{var xh=Wo(),XT=true,QT=true;try{String.fromCharCode.apply(null,[0]);}catch{XT=false;}try{String.fromCharCode.apply(null,new Uint8Array(1));}catch{QT=false;}var tf=new xh.Buf8(256);for(Go=0;Go<256;Go++)tf[Go]=Go>=252?6:Go>=248?5:Go>=240?4:Go>=224?3:Go>=192?2:1;var Go;tf[254]=tf[254]=1;nu.string2buf=function(e){var t,r,n,a,o,i=e.length,s=0;for(a=0;a<i;a++)r=e.charCodeAt(a),(r&64512)===55296&&a+1<i&&(n=e.charCodeAt(a+1),(n&64512)===56320&&(r=65536+(r-55296<<10)+(n-56320),a++)),s+=r<128?1:r<2048?2:r<65536?3:4;for(t=new xh.Buf8(s),o=0,a=0;o<s;a++)r=e.charCodeAt(a),(r&64512)===55296&&a+1<i&&(n=e.charCodeAt(a+1),(n&64512)===56320&&(r=65536+(r-55296<<10)+(n-56320),a++)),r<128?t[o++]=r:r<2048?(t[o++]=192|r>>>6,t[o++]=128|r&63):r<65536?(t[o++]=224|r>>>12,t[o++]=128|r>>>6&63,t[o++]=128|r&63):(t[o++]=240|r>>>18,t[o++]=128|r>>>12&63,t[o++]=128|r>>>6&63,t[o++]=128|r&63);return t};function YT(e,t){if(t<65534&&(e.subarray&&QT||!e.subarray&&XT))return String.fromCharCode.apply(null,xh.shrinkBuf(e,t));for(var r="",n=0;n<t;n++)r+=String.fromCharCode(e[n]);return r}nu.buf2binstring=function(e){return YT(e,e.length)};nu.binstring2buf=function(e){for(var t=new xh.Buf8(e.length),r=0,n=t.length;r<n;r++)t[r]=e.charCodeAt(r);return t};nu.buf2string=function(e,t){var r,n,a,o,i=t||e.length,s=new Array(i*2);for(n=0,r=0;r<i;){if(a=e[r++],a<128){s[n++]=a;continue}if(o=tf[a],o>4){s[n++]=65533,r+=o-1;continue}for(a&=o===2?31:o===3?15:7;o>1&&r<i;)a=a<<6|e[r++]&63,o--;if(o>1){s[n++]=65533;continue}a<65536?s[n++]=a:(a-=65536,s[n++]=55296|a>>10&1023,s[n++]=56320|a&1023);}return YT(s,n)};nu.utf8border=function(e,t){var r;for(t=t||e.length,t>e.length&&(t=e.length),r=t-1;r>=0&&(e[r]&192)===128;)r--;return r<0||r===0?t:r+tf[e[r]]>t?r:t};});var gx=B((Dle,ek)=>{function rU(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0;}ek.exports=rU;});var ak=B(af=>{var rf=ZT(),nf=Wo(),vx=hx(),bx=ph(),nU=gx(),nk=Object.prototype.toString,aU=0,yx=4,au=0,tk=1,rk=2,oU=-1,iU=0,sU=8;function dl(e){if(!(this instanceof dl))return new dl(e);this.options=nf.assign({level:oU,method:sU,chunkSize:16384,windowBits:15,memLevel:8,strategy:iU,to:""},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=false,this.chunks=[],this.strm=new nU,this.strm.avail_out=0;var r=rf.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(r!==au)throw new Error(bx[r]);if(t.header&&rf.deflateSetHeader(this.strm,t.header),t.dictionary){var n;if(typeof t.dictionary=="string"?n=vx.string2buf(t.dictionary):nk.call(t.dictionary)==="[object ArrayBuffer]"?n=new Uint8Array(t.dictionary):n=t.dictionary,r=rf.deflateSetDictionary(this.strm,n),r!==au)throw new Error(bx[r]);this._dict_set=true;}}dl.prototype.push=function(e,t){var r=this.strm,n=this.options.chunkSize,a,o;if(this.ended)return false;o=t===~~t?t:t===true?yx:aU,typeof e=="string"?r.input=vx.string2buf(e):nk.call(e)==="[object ArrayBuffer]"?r.input=new Uint8Array(e):r.input=e,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new nf.Buf8(n),r.next_out=0,r.avail_out=n),a=rf.deflate(r,o),a!==tk&&a!==au)return this.onEnd(a),this.ended=true,false;(r.avail_out===0||r.avail_in===0&&(o===yx||o===rk))&&(this.options.to==="string"?this.onData(vx.buf2binstring(nf.shrinkBuf(r.output,r.next_out))):this.onData(nf.shrinkBuf(r.output,r.next_out)));}while((r.avail_in>0||r.avail_out===0)&&a!==tk);return o===yx?(a=rf.deflateEnd(this.strm),this.onEnd(a),this.ended=true,a===au):(o===rk&&(this.onEnd(au),r.avail_out=0),true)};dl.prototype.onData=function(e){this.chunks.push(e);};dl.prototype.onEnd=function(e){e===au&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=nf.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg;};function xx(e,t){var r=new dl(t);if(r.push(e,true),r.err)throw r.msg||bx[r.err];return r.result}function lU(e,t){return t=t||{},t.raw=true,xx(e,t)}function cU(e,t){return t=t||{},t.gzip=true,xx(e,t)}af.Deflate=dl;af.deflate=xx;af.deflateRaw=lU;af.gzip=cU;});var ik=B(($le,ok)=>{var wh=30,uU=12;ok.exports=function(t,r){var n,a,o,i,s,l,c,u,d,g,f,h,m,p,v,y,x,w,_,E,C,P,T,N,S;n=t.state,a=t.next_in,N=t.input,o=a+(t.avail_in-5),i=t.next_out,S=t.output,s=i-(r-t.avail_out),l=i+(t.avail_out-257),c=n.dmax,u=n.wsize,d=n.whave,g=n.wnext,f=n.window,h=n.hold,m=n.bits,p=n.lencode,v=n.distcode,y=(1<<n.lenbits)-1,x=(1<<n.distbits)-1;e:do{m<15&&(h+=N[a++]<<m,m+=8,h+=N[a++]<<m,m+=8),w=p[h&y];t:for(;;){if(_=w>>>24,h>>>=_,m-=_,_=w>>>16&255,_===0)S[i++]=w&65535;else if(_&16){E=w&65535,_&=15,_&&(m<_&&(h+=N[a++]<<m,m+=8),E+=h&(1<<_)-1,h>>>=_,m-=_),m<15&&(h+=N[a++]<<m,m+=8,h+=N[a++]<<m,m+=8),w=v[h&x];r:for(;;){if(_=w>>>24,h>>>=_,m-=_,_=w>>>16&255,_&16){if(C=w&65535,_&=15,m<_&&(h+=N[a++]<<m,m+=8,m<_&&(h+=N[a++]<<m,m+=8)),C+=h&(1<<_)-1,C>c){t.msg="invalid distance too far back",n.mode=wh;break e}if(h>>>=_,m-=_,_=i-s,C>_){if(_=C-_,_>d&&n.sane){t.msg="invalid distance too far back",n.mode=wh;break e}if(P=0,T=f,g===0){if(P+=u-_,_<E){E-=_;do S[i++]=f[P++];while(--_);P=i-C,T=S;}}else if(g<_){if(P+=u+g-_,_-=g,_<E){E-=_;do S[i++]=f[P++];while(--_);if(P=0,g<E){_=g,E-=_;do S[i++]=f[P++];while(--_);P=i-C,T=S;}}}else if(P+=g-_,_<E){E-=_;do S[i++]=f[P++];while(--_);P=i-C,T=S;}for(;E>2;)S[i++]=T[P++],S[i++]=T[P++],S[i++]=T[P++],E-=3;E&&(S[i++]=T[P++],E>1&&(S[i++]=T[P++]));}else {P=i-C;do S[i++]=S[P++],S[i++]=S[P++],S[i++]=S[P++],E-=3;while(E>2);E&&(S[i++]=S[P++],E>1&&(S[i++]=S[P++]));}}else if((_&64)===0){w=v[(w&65535)+(h&(1<<_)-1)];continue r}else {t.msg="invalid distance code",n.mode=wh;break e}break}}else if((_&64)===0){w=p[(w&65535)+(h&(1<<_)-1)];continue t}else if(_&32){n.mode=uU;break e}else {t.msg="invalid literal/length code",n.mode=wh;break e}break}}while(a<o&&i<l);E=m>>3,a-=E,m-=E<<3,h&=(1<<m)-1,t.next_in=a,t.next_out=i,t.avail_in=a<o?5+(o-a):5-(a-o),t.avail_out=i<l?257+(l-i):257-(i-l),n.hold=h,n.bits=m;};});var pk=B((Ile,fk)=>{var sk=Wo(),ou=15,lk=852,ck=592,uk=0,wx=1,dk=2,dU=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],fU=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],pU=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],mU=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];fk.exports=function(t,r,n,a,o,i,s,l){var c=l.bits,u=0,d=0,g=0,f=0,h=0,m=0,p=0,v=0,y=0,x=0,w,_,E,C,P,T=null,N=0,S,b=new sk.Buf16(ou+1),k=new sk.Buf16(ou+1),D=null,O=0,$,A,F;for(u=0;u<=ou;u++)b[u]=0;for(d=0;d<a;d++)b[r[n+d]]++;for(h=c,f=ou;f>=1&&b[f]===0;f--);if(h>f&&(h=f),f===0)return o[i++]=1<<24|64<<16|0,o[i++]=1<<24|64<<16|0,l.bits=1,0;for(g=1;g<f&&b[g]===0;g++);for(h<g&&(h=g),v=1,u=1;u<=ou;u++)if(v<<=1,v-=b[u],v<0)return -1;if(v>0&&(t===uk||f!==1))return -1;for(k[1]=0,u=1;u<ou;u++)k[u+1]=k[u]+b[u];for(d=0;d<a;d++)r[n+d]!==0&&(s[k[r[n+d]]++]=d);if(t===uk?(T=D=s,S=19):t===wx?(T=dU,N-=257,D=fU,O-=257,S=256):(T=pU,D=mU,S=-1),x=0,d=0,u=g,P=i,m=h,p=0,E=-1,y=1<<h,C=y-1,t===wx&&y>lk||t===dk&&y>ck)return 1;for(;;){$=u-p,s[d]<S?(A=0,F=s[d]):s[d]>S?(A=D[O+s[d]],F=T[N+s[d]]):(A=96,F=0),w=1<<u-p,_=1<<m,g=_;do _-=w,o[P+(x>>p)+_]=$<<24|A<<16|F|0;while(_!==0);for(w=1<<u-1;x&w;)w>>=1;if(w!==0?(x&=w-1,x+=w):x=0,d++,--b[u]===0){if(u===f)break;u=r[n+s[d]];}if(u>h&&(x&C)!==E){for(p===0&&(p=h),P+=g,m=u-p,v=1<<m;m+p<f&&(v-=b[m+p],!(v<=0));)m++,v<<=1;if(y+=1<<m,t===wx&&y>lk||t===dk&&y>ck)return 1;E=x&C,o[E]=h<<24|m<<16|P-i|0;}}return x!==0&&(o[P+x]=u-p<<24|64<<16|0),l.bits=h,0};});var Kk=B(ja=>{var Fn=Wo(),Px=cx(),mo=ux(),hU=ik(),of=pk(),gU=0,Lk=1,Bk=2,mk=4,yU=5,_h=6,fl=0,vU=1,bU=2,la=-2,zk=-3,Tx=-4,xU=-5,hk=8,Uk=1,gk=2,yk=3,vk=4,bk=5,xk=6,wk=7,_k=8,Sk=9,Nk=10,Ch=11,Zo=12,_x=13,Ck=14,Sx=15,Ek=16,Pk=17,Tk=18,kk=19,Sh=20,Nh=21,Rk=22,Ok=23,Dk=24,Ak=25,$k=26,Nx=27,Ik=28,Fk=29,Ut=30,kx=31,wU=32,_U=852,SU=592,NU=15,CU=NU;function Mk(e){return (e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function EU(){this.mode=0,this.last=false,this.wrap=0,this.havedict=false,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Fn.Buf16(320),this.work=new Fn.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0;}function qk(e){var t;return !e||!e.state?la:(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=Uk,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Fn.Buf32(_U),t.distcode=t.distdyn=new Fn.Buf32(SU),t.sane=1,t.back=-1,fl)}function Vk(e){var t;return !e||!e.state?la:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,qk(e))}function Hk(e,t){var r,n;return !e||!e.state||(n=e.state,t<0?(r=0,t=-t):(r=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?la:(n.window!==null&&n.wbits!==t&&(n.window=null),n.wrap=r,n.wbits=t,Vk(e))}function Jk(e,t){var r,n;return e?(n=new EU,e.state=n,n.window=null,r=Hk(e,t),r!==fl&&(e.state=null),r):la}function PU(e){return Jk(e,CU)}var jk=true,Cx,Ex;function TU(e){if(jk){var t;for(Cx=new Fn.Buf32(512),Ex=new Fn.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(of(Lk,e.lens,0,288,Cx,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;of(Bk,e.lens,0,32,Ex,0,e.work,{bits:5}),jk=false;}e.lencode=Cx,e.lenbits=9,e.distcode=Ex,e.distbits=5;}function Wk(e,t,r,n){var a,o=e.state;return o.window===null&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new Fn.Buf8(o.wsize)),n>=o.wsize?(Fn.arraySet(o.window,t,r-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(a=o.wsize-o.wnext,a>n&&(a=n),Fn.arraySet(o.window,t,r-n,a,o.wnext),n-=a,n?(Fn.arraySet(o.window,t,r-n,n,0),o.wnext=n,o.whave=o.wsize):(o.wnext+=a,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=a))),0}function kU(e,t){var r,n,a,o,i,s,l,c,u,d,g,f,h,m,p=0,v,y,x,w,_,E,C,P,T=new Fn.Buf8(4),N,S,b=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&e.avail_in!==0)return la;r=e.state,r.mode===Zo&&(r.mode=_x),i=e.next_out,a=e.output,l=e.avail_out,o=e.next_in,n=e.input,s=e.avail_in,c=r.hold,u=r.bits,d=s,g=l,P=fl;e:for(;;)switch(r.mode){case Uk:if(r.wrap===0){r.mode=_x;break}for(;u<16;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}if(r.wrap&2&&c===35615){r.check=0,T[0]=c&255,T[1]=c>>>8&255,r.check=mo(r.check,T,2,0),c=0,u=0,r.mode=gk;break}if(r.flags=0,r.head&&(r.head.done=false),!(r.wrap&1)||(((c&255)<<8)+(c>>8))%31){e.msg="incorrect header check",r.mode=Ut;break}if((c&15)!==hk){e.msg="unknown compression method",r.mode=Ut;break}if(c>>>=4,u-=4,C=(c&15)+8,r.wbits===0)r.wbits=C;else if(C>r.wbits){e.msg="invalid window size",r.mode=Ut;break}r.dmax=1<<C,e.adler=r.check=1,r.mode=c&512?Nk:Zo,c=0,u=0;break;case gk:for(;u<16;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}if(r.flags=c,(r.flags&255)!==hk){e.msg="unknown compression method",r.mode=Ut;break}if(r.flags&57344){e.msg="unknown header flags set",r.mode=Ut;break}r.head&&(r.head.text=c>>8&1),r.flags&512&&(T[0]=c&255,T[1]=c>>>8&255,r.check=mo(r.check,T,2,0)),c=0,u=0,r.mode=yk;case yk:for(;u<32;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}r.head&&(r.head.time=c),r.flags&512&&(T[0]=c&255,T[1]=c>>>8&255,T[2]=c>>>16&255,T[3]=c>>>24&255,r.check=mo(r.check,T,4,0)),c=0,u=0,r.mode=vk;case vk:for(;u<16;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}r.head&&(r.head.xflags=c&255,r.head.os=c>>8),r.flags&512&&(T[0]=c&255,T[1]=c>>>8&255,r.check=mo(r.check,T,2,0)),c=0,u=0,r.mode=bk;case bk:if(r.flags&1024){for(;u<16;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}r.length=c,r.head&&(r.head.extra_len=c),r.flags&512&&(T[0]=c&255,T[1]=c>>>8&255,r.check=mo(r.check,T,2,0)),c=0,u=0;}else r.head&&(r.head.extra=null);r.mode=xk;case xk:if(r.flags&1024&&(f=r.length,f>s&&(f=s),f&&(r.head&&(C=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),Fn.arraySet(r.head.extra,n,o,f,C)),r.flags&512&&(r.check=mo(r.check,n,f,o)),s-=f,o+=f,r.length-=f),r.length))break e;r.length=0,r.mode=wk;case wk:if(r.flags&2048){if(s===0)break e;f=0;do C=n[o+f++],r.head&&C&&r.length<65536&&(r.head.name+=String.fromCharCode(C));while(C&&f<s);if(r.flags&512&&(r.check=mo(r.check,n,f,o)),s-=f,o+=f,C)break e}else r.head&&(r.head.name=null);r.length=0,r.mode=_k;case _k:if(r.flags&4096){if(s===0)break e;f=0;do C=n[o+f++],r.head&&C&&r.length<65536&&(r.head.comment+=String.fromCharCode(C));while(C&&f<s);if(r.flags&512&&(r.check=mo(r.check,n,f,o)),s-=f,o+=f,C)break e}else r.head&&(r.head.comment=null);r.mode=Sk;case Sk:if(r.flags&512){for(;u<16;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}if(c!==(r.check&65535)){e.msg="header crc mismatch",r.mode=Ut;break}c=0,u=0;}r.head&&(r.head.hcrc=r.flags>>9&1,r.head.done=true),e.adler=r.check=0,r.mode=Zo;break;case Nk:for(;u<32;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}e.adler=r.check=Mk(c),c=0,u=0,r.mode=Ch;case Ch:if(r.havedict===0)return e.next_out=i,e.avail_out=l,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=u,bU;e.adler=r.check=1,r.mode=Zo;case Zo:if(t===yU||t===_h)break e;case _x:if(r.last){c>>>=u&7,u-=u&7,r.mode=Nx;break}for(;u<3;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}switch(r.last=c&1,c>>>=1,u-=1,c&3){case 0:r.mode=Ck;break;case 1:if(TU(r),r.mode=Sh,t===_h){c>>>=2,u-=2;break e}break;case 2:r.mode=Pk;break;case 3:e.msg="invalid block type",r.mode=Ut;}c>>>=2,u-=2;break;case Ck:for(c>>>=u&7,u-=u&7;u<32;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}if((c&65535)!==(c>>>16^65535)){e.msg="invalid stored block lengths",r.mode=Ut;break}if(r.length=c&65535,c=0,u=0,r.mode=Sx,t===_h)break e;case Sx:r.mode=Ek;case Ek:if(f=r.length,f){if(f>s&&(f=s),f>l&&(f=l),f===0)break e;Fn.arraySet(a,n,o,f,i),s-=f,o+=f,l-=f,i+=f,r.length-=f;break}r.mode=Zo;break;case Pk:for(;u<14;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}if(r.nlen=(c&31)+257,c>>>=5,u-=5,r.ndist=(c&31)+1,c>>>=5,u-=5,r.ncode=(c&15)+4,c>>>=4,u-=4,r.nlen>286||r.ndist>30){e.msg="too many length or distance symbols",r.mode=Ut;break}r.have=0,r.mode=Tk;case Tk:for(;r.have<r.ncode;){for(;u<3;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}r.lens[b[r.have++]]=c&7,c>>>=3,u-=3;}for(;r.have<19;)r.lens[b[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,N={bits:r.lenbits},P=of(gU,r.lens,0,19,r.lencode,0,r.work,N),r.lenbits=N.bits,P){e.msg="invalid code lengths set",r.mode=Ut;break}r.have=0,r.mode=kk;case kk:for(;r.have<r.nlen+r.ndist;){for(;p=r.lencode[c&(1<<r.lenbits)-1],v=p>>>24,y=p>>>16&255,x=p&65535,!(v<=u);){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}if(x<16)c>>>=v,u-=v,r.lens[r.have++]=x;else {if(x===16){for(S=v+2;u<S;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}if(c>>>=v,u-=v,r.have===0){e.msg="invalid bit length repeat",r.mode=Ut;break}C=r.lens[r.have-1],f=3+(c&3),c>>>=2,u-=2;}else if(x===17){for(S=v+3;u<S;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}c>>>=v,u-=v,C=0,f=3+(c&7),c>>>=3,u-=3;}else {for(S=v+7;u<S;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}c>>>=v,u-=v,C=0,f=11+(c&127),c>>>=7,u-=7;}if(r.have+f>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=Ut;break}for(;f--;)r.lens[r.have++]=C;}}if(r.mode===Ut)break;if(r.lens[256]===0){e.msg="invalid code -- missing end-of-block",r.mode=Ut;break}if(r.lenbits=9,N={bits:r.lenbits},P=of(Lk,r.lens,0,r.nlen,r.lencode,0,r.work,N),r.lenbits=N.bits,P){e.msg="invalid literal/lengths set",r.mode=Ut;break}if(r.distbits=6,r.distcode=r.distdyn,N={bits:r.distbits},P=of(Bk,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,N),r.distbits=N.bits,P){e.msg="invalid distances set",r.mode=Ut;break}if(r.mode=Sh,t===_h)break e;case Sh:r.mode=Nh;case Nh:if(s>=6&&l>=258){e.next_out=i,e.avail_out=l,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=u,hU(e,g),i=e.next_out,a=e.output,l=e.avail_out,o=e.next_in,n=e.input,s=e.avail_in,c=r.hold,u=r.bits,r.mode===Zo&&(r.back=-1);break}for(r.back=0;p=r.lencode[c&(1<<r.lenbits)-1],v=p>>>24,y=p>>>16&255,x=p&65535,!(v<=u);){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}if(y&&(y&240)===0){for(w=v,_=y,E=x;p=r.lencode[E+((c&(1<<w+_)-1)>>w)],v=p>>>24,y=p>>>16&255,x=p&65535,!(w+v<=u);){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}c>>>=w,u-=w,r.back+=w;}if(c>>>=v,u-=v,r.back+=v,r.length=x,y===0){r.mode=$k;break}if(y&32){r.back=-1,r.mode=Zo;break}if(y&64){e.msg="invalid literal/length code",r.mode=Ut;break}r.extra=y&15,r.mode=Rk;case Rk:if(r.extra){for(S=r.extra;u<S;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}r.length+=c&(1<<r.extra)-1,c>>>=r.extra,u-=r.extra,r.back+=r.extra;}r.was=r.length,r.mode=Ok;case Ok:for(;p=r.distcode[c&(1<<r.distbits)-1],v=p>>>24,y=p>>>16&255,x=p&65535,!(v<=u);){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}if((y&240)===0){for(w=v,_=y,E=x;p=r.distcode[E+((c&(1<<w+_)-1)>>w)],v=p>>>24,y=p>>>16&255,x=p&65535,!(w+v<=u);){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}c>>>=w,u-=w,r.back+=w;}if(c>>>=v,u-=v,r.back+=v,y&64){e.msg="invalid distance code",r.mode=Ut;break}r.offset=x,r.extra=y&15,r.mode=Dk;case Dk:if(r.extra){for(S=r.extra;u<S;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}r.offset+=c&(1<<r.extra)-1,c>>>=r.extra,u-=r.extra,r.back+=r.extra;}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=Ut;break}r.mode=Ak;case Ak:if(l===0)break e;if(f=g-l,r.offset>f){if(f=r.offset-f,f>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=Ut;break}f>r.wnext?(f-=r.wnext,h=r.wsize-f):h=r.wnext-f,f>r.length&&(f=r.length),m=r.window;}else m=a,h=i-r.offset,f=r.length;f>l&&(f=l),l-=f,r.length-=f;do a[i++]=m[h++];while(--f);r.length===0&&(r.mode=Nh);break;case $k:if(l===0)break e;a[i++]=r.length,l--,r.mode=Nh;break;case Nx:if(r.wrap){for(;u<32;){if(s===0)break e;s--,c|=n[o++]<<u,u+=8;}if(g-=l,e.total_out+=g,r.total+=g,g&&(e.adler=r.check=r.flags?mo(r.check,a,g,i-g):Px(r.check,a,g,i-g)),g=l,(r.flags?c:Mk(c))!==r.check){e.msg="incorrect data check",r.mode=Ut;break}c=0,u=0;}r.mode=Ik;case Ik:if(r.wrap&&r.flags){for(;u<32;){if(s===0)break e;s--,c+=n[o++]<<u,u+=8;}if(c!==(r.total&4294967295)){e.msg="incorrect length check",r.mode=Ut;break}c=0,u=0;}r.mode=Fk;case Fk:P=vU;break e;case Ut:P=zk;break e;case kx:return Tx;case wU:default:return la}return e.next_out=i,e.avail_out=l,e.next_in=o,e.avail_in=s,r.hold=c,r.bits=u,(r.wsize||g!==e.avail_out&&r.mode<Ut&&(r.mode<Nx||t!==mk))&&Wk(e,e.output,e.next_out,g-e.avail_out)?(r.mode=kx,Tx):(d-=e.avail_in,g-=e.avail_out,e.total_in+=d,e.total_out+=g,r.total+=g,r.wrap&&g&&(e.adler=r.check=r.flags?mo(r.check,a,g,e.next_out-g):Px(r.check,a,g,e.next_out-g)),e.data_type=r.bits+(r.last?64:0)+(r.mode===Zo?128:0)+(r.mode===Sh||r.mode===Sx?256:0),(d===0&&g===0||t===mk)&&P===fl&&(P=xU),P)}function RU(e){if(!e||!e.state)return la;var t=e.state;return t.window&&(t.window=null),e.state=null,fl}function OU(e,t){var r;return !e||!e.state||(r=e.state,(r.wrap&2)===0)?la:(r.head=t,t.done=false,fl)}function DU(e,t){var r=t.length,n,a,o;return !e||!e.state||(n=e.state,n.wrap!==0&&n.mode!==Ch)?la:n.mode===Ch&&(a=1,a=Px(a,t,r,0),a!==n.check)?zk:(o=Wk(e,t,r,r),o?(n.mode=kx,Tx):(n.havedict=1,fl))}ja.inflateReset=Vk;ja.inflateReset2=Hk;ja.inflateResetKeep=qk;ja.inflateInit=PU;ja.inflateInit2=Jk;ja.inflate=kU;ja.inflateEnd=RU;ja.inflateGetHeader=OU;ja.inflateSetDictionary=DU;ja.inflateInfo="pako inflate (from Nodeca project)";});var Rx=B((Mle,Gk)=>{Gk.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};});var Xk=B((jle,Zk)=>{function AU(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=false;}Zk.exports=AU;});var Yk=B(lf=>{var iu=Kk(),sf=Wo(),Eh=hx(),or=Rx(),Ox=ph(),$U=gx(),IU=Xk(),Qk=Object.prototype.toString;function pl(e){if(!(this instanceof pl))return new pl(e);this.options=sf.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(e&&e.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15)===0&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=false,this.chunks=[],this.strm=new $U,this.strm.avail_out=0;var r=iu.inflateInit2(this.strm,t.windowBits);if(r!==or.Z_OK)throw new Error(Ox[r]);if(this.header=new IU,iu.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=Eh.string2buf(t.dictionary):Qk.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(r=iu.inflateSetDictionary(this.strm,t.dictionary),r!==or.Z_OK)))throw new Error(Ox[r])}pl.prototype.push=function(e,t){var r=this.strm,n=this.options.chunkSize,a=this.options.dictionary,o,i,s,l,c,u=false;if(this.ended)return false;i=t===~~t?t:t===true?or.Z_FINISH:or.Z_NO_FLUSH,typeof e=="string"?r.input=Eh.binstring2buf(e):Qk.call(e)==="[object ArrayBuffer]"?r.input=new Uint8Array(e):r.input=e,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new sf.Buf8(n),r.next_out=0,r.avail_out=n),o=iu.inflate(r,or.Z_NO_FLUSH),o===or.Z_NEED_DICT&&a&&(o=iu.inflateSetDictionary(this.strm,a)),o===or.Z_BUF_ERROR&&u===true&&(o=or.Z_OK,u=false),o!==or.Z_STREAM_END&&o!==or.Z_OK)return this.onEnd(o),this.ended=true,false;r.next_out&&(r.avail_out===0||o===or.Z_STREAM_END||r.avail_in===0&&(i===or.Z_FINISH||i===or.Z_SYNC_FLUSH))&&(this.options.to==="string"?(s=Eh.utf8border(r.output,r.next_out),l=r.next_out-s,c=Eh.buf2string(r.output,s),r.next_out=l,r.avail_out=n-l,l&&sf.arraySet(r.output,r.output,s,l,0),this.onData(c)):this.onData(sf.shrinkBuf(r.output,r.next_out))),r.avail_in===0&&r.avail_out===0&&(u=true);}while((r.avail_in>0||r.avail_out===0)&&o!==or.Z_STREAM_END);return o===or.Z_STREAM_END&&(i=or.Z_FINISH),i===or.Z_FINISH?(o=iu.inflateEnd(this.strm),this.onEnd(o),this.ended=true,o===or.Z_OK):(i===or.Z_SYNC_FLUSH&&(this.onEnd(or.Z_OK),r.avail_out=0),true)};pl.prototype.onData=function(e){this.chunks.push(e);};pl.prototype.onEnd=function(e){e===or.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=sf.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg;};function Dx(e,t){var r=new pl(t);if(r.push(e,true),r.err)throw r.msg||Ox[r.err];return r.result}function FU(e,t){return t=t||{},t.raw=true,Dx(e,t)}lf.Inflate=pl;lf.inflate=Dx;lf.inflateRaw=FU;lf.ungzip=Dx;});var rR=B((Ble,tR)=>{var MU=Wo().assign,jU=ak(),LU=Yk(),BU=Rx(),eR={};MU(eR,jU,LU,BU);tR.exports=eR;});var aR=B(Th=>{var zU=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",UU=rR(),nR=Xt(),Ph=In(),qU=zU?"uint8array":"array";Th.magic="\b\0";function ml(e,t){Ph.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={};}nR.inherits(ml,Ph);ml.prototype.processChunk=function(e){this.meta=e.meta,this._pako===null&&this._createPako(),this._pako.push(nR.transformTo(qU,e.data),false);};ml.prototype.flush=function(){Ph.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],true);};ml.prototype.cleanUp=function(){Ph.prototype.cleanUp.call(this),this._pako=null;};ml.prototype._createPako=function(){this._pako=new UU[this._pakoAction]({raw:true,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta});};};Th.compressWorker=function(e){return new ml("Deflate",e)};Th.uncompressWorker=function(){return new ml("Inflate",{})};});var $x=B(Ax=>{var oR=In();Ax.STORE={magic:"\0\0",compressWorker:function(){return new oR("STORE compression")},uncompressWorker:function(){return new oR("STORE decompression")}};Ax.DEFLATE=aR();});var Ix=B(hl=>{hl.LOCAL_FILE_HEADER="PK";hl.CENTRAL_FILE_HEADER="PK";hl.CENTRAL_DIRECTORY_END="PK";hl.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07";hl.ZIP64_CENTRAL_DIRECTORY_END="PK";hl.DATA_DESCRIPTOR="PK\x07\b";});var cR=B((Vle,lR)=>{var su=Xt(),lu=In(),Fx=Gc(),iR=lh(),kh=Ix(),Dt=function(e,t){var r="",n;for(n=0;n<t;n++)r+=String.fromCharCode(e&255),e=e>>>8;return r},VU=function(e,t){var r=e;return e||(r=t?16893:33204),(r&65535)<<16},HU=function(e){return (e||0)&63},sR=function(e,t,r,n,a,o){var i=e.file,s=e.compression,l=o!==Fx.utf8encode,c=su.transformTo("string",o(i.name)),u=su.transformTo("string",Fx.utf8encode(i.name)),d=i.comment,g=su.transformTo("string",o(d)),f=su.transformTo("string",Fx.utf8encode(d)),h=u.length!==i.name.length,m=f.length!==d.length,p,v,y="",x="",w="",_=i.dir,E=i.date,C={crc32:0,compressedSize:0,uncompressedSize:0};(!t||r)&&(C.crc32=e.crc32,C.compressedSize=e.compressedSize,C.uncompressedSize=e.uncompressedSize);var P=0;t&&(P|=8),!l&&(h||m)&&(P|=2048);var T=0,N=0;_&&(T|=16),a==="UNIX"?(N=798,T|=VU(i.unixPermissions,_)):(N=20,T|=HU(i.dosPermissions)),p=E.getUTCHours(),p=p<<6,p=p|E.getUTCMinutes(),p=p<<5,p=p|E.getUTCSeconds()/2,v=E.getUTCFullYear()-1980,v=v<<4,v=v|E.getUTCMonth()+1,v=v<<5,v=v|E.getUTCDate(),h&&(x=Dt(1,1)+Dt(iR(c),4)+u,y+="up"+Dt(x.length,2)+x),m&&(w=Dt(1,1)+Dt(iR(g),4)+f,y+="uc"+Dt(w.length,2)+w);var S="";S+=`
9
+ \0`,S+=Dt(P,2),S+=s.magic,S+=Dt(p,2),S+=Dt(v,2),S+=Dt(C.crc32,4),S+=Dt(C.compressedSize,4),S+=Dt(C.uncompressedSize,4),S+=Dt(c.length,2),S+=Dt(y.length,2);var b=kh.LOCAL_FILE_HEADER+S+c+y,k=kh.CENTRAL_FILE_HEADER+Dt(N,2)+S+Dt(g.length,2)+"\0\0\0\0"+Dt(T,4)+Dt(n,4)+c+y+g;return {fileRecord:b,dirRecord:k}},JU=function(e,t,r,n,a){var o="",i=su.transformTo("string",a(n));return o=kh.CENTRAL_DIRECTORY_END+"\0\0\0\0"+Dt(e,2)+Dt(e,2)+Dt(t,4)+Dt(r,4)+Dt(i.length,2)+i,o},WU=function(e){var t="";return t=kh.DATA_DESCRIPTOR+Dt(e.crc32,4)+Dt(e.compressedSize,4)+Dt(e.uncompressedSize,4),t};function La(e,t,r,n){lu.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=r,this.encodeFileName=n,this.streamFiles=e,this.accumulate=false,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[];}su.inherits(La,lu);La.prototype.push=function(e){var t=e.meta.percent||0,r=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,lu.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:r?(t+100*(r-n-1))/r:100}}));};La.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var r=sR(e,t,false,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:r.fileRecord,meta:{percent:0}});}else this.accumulate=true;};La.prototype.closedSource=function(e){this.accumulate=false;var t=this.streamFiles&&!e.file.dir,r=sR(e,t,true,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),t)this.push({data:WU(e),meta:{percent:100}});else for(this.push({data:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null;};La.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var r=this.bytesWritten-e,n=JU(this.dirRecords.length,r,e,this.zipComment,this.encodeFileName);this.push({data:n,meta:{percent:100}});};La.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume();};La.prototype.registerPrevious=function(e){this._sources.push(e);var t=this;return e.on("data",function(r){t.processChunk(r);}),e.on("end",function(){t.closedSource(t.previous.streamInfo),t._sources.length?t.prepareNextSource():t.end();}),e.on("error",function(r){t.error(r);}),this};La.prototype.resume=function(){if(!lu.prototype.resume.call(this))return false;if(!this.previous&&this._sources.length)return this.prepareNextSource(),true;if(!this.previous&&!this._sources.length&&!this.generatedError)return this.end(),true};La.prototype.error=function(e){var t=this._sources;if(!lu.prototype.error.call(this,e))return false;for(var r=0;r<t.length;r++)try{t[r].error(e);}catch{}return true};La.prototype.lock=function(){lu.prototype.lock.call(this);for(var e=this._sources,t=0;t<e.length;t++)e[t].lock();};lR.exports=La;});var dR=B(uR=>{var KU=$x(),GU=cR(),ZU=function(e,t){var r=e||t,n=KU[r];if(!n)throw new Error(r+" is not a valid compression method !");return n};uR.generateWorker=function(e,t,r){var n=new GU(t.streamFiles,r,t.platform,t.encodeFileName),a=0;try{e.forEach(function(o,i){a++;var s=ZU(i.options.compression,t.compression),l=i.options.compressionOptions||t.compressionOptions||{},c=i.dir,u=i.date;i._compressWorker(s,l).withStreamInfo("file",{name:o,dir:c,date:u,comment:i.comment||"",unixPermissions:i.unixPermissions,dosPermissions:i.dosPermissions}).pipe(n);}),n.entriesCount=a;}catch(o){n.error(o);}return n};});var pR=B((Jle,fR)=>{var XU=Xt(),Rh=In();function cf(e,t){Rh.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=false,this._bindStream(t);}XU.inherits(cf,Rh);cf.prototype._bindStream=function(e){var t=this;this._stream=e,e.pause(),e.on("data",function(r){t.push({data:r,meta:{percent:0}});}).on("error",function(r){t.isPaused?this.generatedError=r:t.error(r);}).on("end",function(){t.isPaused?t._upstreamEnded=true:t.end();});};cf.prototype.pause=function(){return Rh.prototype.pause.call(this)?(this._stream.pause(),true):false};cf.prototype.resume=function(){return Rh.prototype.resume.call(this)?(this._upstreamEnded?this.end():this._stream.resume(),true):false};fR.exports=cf;});var SR=B((Wle,_R)=>{var QU=Gc(),uf=Xt(),yR=In(),YU=zb(),vR=Ub(),mR=ch(),eq=hT(),tq=dR(),hR=jd(),rq=pR(),bR=function(e,t,r){var n=uf.getTypeOf(t),a,o=uf.extend(r||{},vR);o.date=o.date||new Date,o.compression!==null&&(o.compression=o.compression.toUpperCase()),typeof o.unixPermissions=="string"&&(o.unixPermissions=parseInt(o.unixPermissions,8)),o.unixPermissions&&o.unixPermissions&16384&&(o.dir=true),o.dosPermissions&&o.dosPermissions&16&&(o.dir=true),o.dir&&(e=xR(e)),o.createFolders&&(a=nq(e))&&wR.call(this,a,true);var i=n==="string"&&o.binary===false&&o.base64===false;(!r||typeof r.binary>"u")&&(o.binary=!i);var s=t instanceof mR&&t.uncompressedSize===0;(s||o.dir||!t||t.length===0)&&(o.base64=false,o.binary=true,t="",o.compression="STORE",n="string");var l=null;t instanceof mR||t instanceof yR?l=t:hR.isNode&&hR.isStream(t)?l=new rq(e,t):l=uf.prepareContent(e,t,o.binary,o.optimizedBinaryString,o.base64);var c=new eq(e,l,o);this.files[e]=c;},nq=function(e){e.slice(-1)==="/"&&(e=e.substring(0,e.length-1));var t=e.lastIndexOf("/");return t>0?e.substring(0,t):""},xR=function(e){return e.slice(-1)!=="/"&&(e+="/"),e},wR=function(e,t){return t=typeof t<"u"?t:vR.createFolders,e=xR(e),this.files[e]||bR.call(this,e,null,{dir:true,createFolders:t}),this.files[e]};function gR(e){return Object.prototype.toString.call(e)==="[object RegExp]"}var aq={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(e){var t,r,n;for(t in this.files)n=this.files[t],r=t.slice(this.root.length,t.length),r&&t.slice(0,this.root.length)===this.root&&e(r,n);},filter:function(e){var t=[];return this.forEach(function(r,n){e(r,n)&&t.push(n);}),t},file:function(e,t,r){if(arguments.length===1)if(gR(e)){var n=e;return this.filter(function(o,i){return !i.dir&&n.test(o)})}else {var a=this.files[this.root+e];return a&&!a.dir?a:null}else e=this.root+e,bR.call(this,e,t,r);return this},folder:function(e){if(!e)return this;if(gR(e))return this.filter(function(a,o){return o.dir&&e.test(a)});var t=this.root+e,r=wR.call(this,t),n=this.clone();return n.root=r.name,n},remove:function(e){e=this.root+e;var t=this.files[e];if(t||(e.slice(-1)!=="/"&&(e+="/"),t=this.files[e]),t&&!t.dir)delete this.files[e];else for(var r=this.filter(function(a,o){return o.name.slice(0,e.length)===e}),n=0;n<r.length;n++)delete this.files[r[n].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(e){var t,r={};try{if(r=uf.extend(e||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:QU.utf8encode}),r.type=r.type.toLowerCase(),r.compression=r.compression.toUpperCase(),r.type==="binarystring"&&(r.type="string"),!r.type)throw new Error("No output type specified.");uf.checkSupport(r.type),(r.platform==="darwin"||r.platform==="freebsd"||r.platform==="linux"||r.platform==="sunos")&&(r.platform="UNIX"),r.platform==="win32"&&(r.platform="DOS");var n=r.comment||this.comment||"";t=tq.generateWorker(this,r,n);}catch(a){t=new yR("error"),t.error(a);}return new YU(t,r.type||"string",r.mimeType)},generateAsync:function(e,t){return this.generateInternalStream(e).accumulate(t)},generateNodeStream:function(e,t){return e=e||{},e.type||(e.type="nodebuffer"),this.generateInternalStream(e).toNodejsStream(t)}};_R.exports=aq;});var Mx=B((Kle,CR)=>{var oq=Xt();function NR(e){this.data=e,this.length=e.length,this.index=0,this.zero=0;}NR.prototype={checkOffset:function(e){this.checkIndex(this.index+e);},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e;},skip:function(e){this.setIndex(this.index+e);},byteAt:function(){},readInt:function(e){var t=0,r;for(this.checkOffset(e),r=this.index+e-1;r>=this.index;r--)t=(t<<8)+this.byteAt(r);return this.index+=e,t},readString:function(e){return oq.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC((e>>25&127)+1980,(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(e&31)<<1))}};CR.exports=NR;});var jx=B((Gle,PR)=>{var ER=Mx(),iq=Xt();function cu(e){ER.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=e[t]&255;}iq.inherits(cu,ER);cu.prototype.byteAt=function(e){return this.data[this.zero+e]};cu.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),r=e.charCodeAt(1),n=e.charCodeAt(2),a=e.charCodeAt(3),o=this.length-4;o>=0;--o)if(this.data[o]===t&&this.data[o+1]===r&&this.data[o+2]===n&&this.data[o+3]===a)return o-this.zero;return -1};cu.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),r=e.charCodeAt(1),n=e.charCodeAt(2),a=e.charCodeAt(3),o=this.readData(4);return t===o[0]&&r===o[1]&&n===o[2]&&a===o[3]};cu.prototype.readData=function(e){if(this.checkOffset(e),e===0)return [];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};PR.exports=cu;});var RR=B((Zle,kR)=>{var TR=Mx(),sq=Xt();function uu(e){TR.call(this,e);}sq.inherits(uu,TR);uu.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)};uu.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero};uu.prototype.readAndCheckSignature=function(e){var t=this.readData(4);return e===t};uu.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};kR.exports=uu;});var Bx=B((Xle,DR)=>{var OR=jx(),lq=Xt();function Lx(e){OR.call(this,e);}lq.inherits(Lx,OR);Lx.prototype.readData=function(e){if(this.checkOffset(e),e===0)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};DR.exports=Lx;});var IR=B((Qle,$R)=>{var AR=Bx(),cq=Xt();function zx(e){AR.call(this,e);}cq.inherits(zx,AR);zx.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};$R.exports=zx;});var Ux=B((Yle,MR)=>{var Oh=Xt(),FR=Ho(),uq=jx(),dq=RR(),fq=IR(),pq=Bx();MR.exports=function(e){var t=Oh.getTypeOf(e);return Oh.checkSupport(t),t==="string"&&!FR.uint8array?new dq(e):t==="nodebuffer"?new fq(e):FR.uint8array?new pq(Oh.transformTo("uint8array",e)):new uq(Oh.transformTo("array",e))};});var zR=B((ece,BR)=>{var qx=Ux(),ts=Xt(),mq=ch(),jR=lh(),Dh=Gc(),Ah=$x(),hq=Ho(),gq=0,yq=3,vq=function(e){for(var t in Ah)if(Object.prototype.hasOwnProperty.call(Ah,t)&&Ah[t].magic===e)return Ah[t];return null};function LR(e,t){this.options=e,this.loadOptions=t;}LR.prototype={isEncrypted:function(){return (this.bitFlag&1)===1},useUTF8:function(){return (this.bitFlag&2048)===2048},readLocalPart:function(e){var t,r;if(e.skip(22),this.fileNameLength=e.readInt(2),r=e.readInt(2),this.fileName=e.readData(this.fileNameLength),e.skip(r),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(t=vq(this.compressionMethod),t===null)throw new Error("Corrupted zip : compression "+ts.pretty(this.compressionMethod)+" unknown (inner file : "+ts.transformTo("string",this.fileName)+")");this.decompressed=new mq(this.compressedSize,this.uncompressedSize,this.crc32,t,e.readData(this.compressedSize));},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength);},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(this.externalFileAttributes&16),e===gq&&(this.dosPermissions=this.externalFileAttributes&63),e===yq&&(this.unixPermissions=this.externalFileAttributes>>16&65535),!this.dir&&this.fileNameStr.slice(-1)==="/"&&(this.dir=true);},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=qx(this.extraFields[1].value);this.uncompressedSize===ts.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===ts.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===ts.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===ts.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4));}},readExtraFields:function(e){var t=e.index+this.extraFieldsLength,r,n,a;for(this.extraFields||(this.extraFields={});e.index+4<t;)r=e.readInt(2),n=e.readInt(2),a=e.readData(n),this.extraFields[r]={id:r,length:n,value:a};e.setIndex(t);},handleUTF8:function(){var e=hq.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=Dh.utf8decode(this.fileName),this.fileCommentStr=Dh.utf8decode(this.fileComment);else {var t=this.findExtraFieldUnicodePath();if(t!==null)this.fileNameStr=t;else {var r=ts.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(r);}var n=this.findExtraFieldUnicodeComment();if(n!==null)this.fileCommentStr=n;else {var a=ts.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(a);}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=qx(e.value);return t.readInt(1)!==1||jR(this.fileName)!==t.readInt(4)?null:Dh.utf8decode(t.readData(e.length-5))}return null},findExtraFieldUnicodeComment:function(){var e=this.extraFields[25461];if(e){var t=qx(e.value);return t.readInt(1)!==1||jR(this.fileComment)!==t.readInt(4)?null:Dh.utf8decode(t.readData(e.length-5))}return null}};BR.exports=LR;});var VR=B((tce,qR)=>{var bq=Ux(),Xo=Xt(),Ba=Ix(),xq=zR(),wq=Ho();function UR(e){this.files=[],this.loadOptions=e;}UR.prototype={checkSignature:function(e){if(!this.reader.readAndCheckSignature(e)){this.reader.index-=4;var t=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+Xo.pretty(t)+", expected "+Xo.pretty(e)+")")}},isSignature:function(e,t){var r=this.reader.index;this.reader.setIndex(e);var n=this.reader.readString(4),a=n===t;return this.reader.setIndex(r),a},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var e=this.reader.readData(this.zipCommentLength),t=wq.uint8array?"uint8array":"array",r=Xo.transformTo(t,e);this.zipComment=this.loadOptions.decodeFileName(r);},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var e=this.zip64EndOfCentralSize-44,t=0,r,n,a;t<e;)r=this.reader.readInt(2),n=this.reader.readInt(4),a=this.reader.readData(n),this.zip64ExtensibleData[r]={id:r,length:n,value:a};},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var e,t;for(e=0;e<this.files.length;e++)t=this.files[e],this.reader.setIndex(t.localHeaderOffset),this.checkSignature(Ba.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes();},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(Ba.CENTRAL_FILE_HEADER);)e=new xq({zip64:this.zip64},this.loadOptions),e.readCentralPart(this.reader),this.files.push(e);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var e=this.reader.lastIndexOfSignature(Ba.CENTRAL_DIRECTORY_END);if(e<0){var t=!this.isSignature(0,Ba.LOCAL_FILE_HEADER);throw t?new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"):new Error("Corrupted zip: can't find end of central directory")}this.reader.setIndex(e);var r=e;if(this.checkSignature(Ba.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===Xo.MAX_VALUE_16BITS||this.diskWithCentralDirStart===Xo.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===Xo.MAX_VALUE_16BITS||this.centralDirRecords===Xo.MAX_VALUE_16BITS||this.centralDirSize===Xo.MAX_VALUE_32BITS||this.centralDirOffset===Xo.MAX_VALUE_32BITS){if(this.zip64=true,e=this.reader.lastIndexOfSignature(Ba.ZIP64_CENTRAL_DIRECTORY_LOCATOR),e<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(e),this.checkSignature(Ba.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,Ba.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(Ba.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(Ba.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral();}var n=this.centralDirOffset+this.centralDirSize;this.zip64&&(n+=20,n+=12+this.zip64EndOfCentralSize);var a=r-n;if(a>0)this.isSignature(r,Ba.CENTRAL_FILE_HEADER)||(this.reader.zero=a);else if(a<0)throw new Error("Corrupted zip: missing "+Math.abs(a)+" bytes.")},prepareReader:function(e){this.reader=bq(e);},load:function(e){this.prepareReader(e),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles();}};qR.exports=UR;});var WR=B((rce,JR)=>{var Vx=Xt(),$h=Jc(),_q=Gc(),Sq=VR(),Nq=Hb(),HR=jd();function Cq(e){return new $h.Promise(function(t,r){var n=e.decompressed.getContentWorker().pipe(new Nq);n.on("error",function(a){r(a);}).on("end",function(){n.streamInfo.crc32!==e.decompressed.crc32?r(new Error("Corrupted zip : CRC32 mismatch")):t();}).resume();})}JR.exports=function(e,t){var r=this;return t=Vx.extend(t||{},{base64:false,checkCRC32:false,optimizedBinaryString:false,createFolders:false,decodeFileName:_q.utf8decode}),HR.isNode&&HR.isStream(e)?$h.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):Vx.prepareContent("the loaded zip file",e,true,t.optimizedBinaryString,t.base64).then(function(n){var a=new Sq(t);return a.load(n),a}).then(function(a){var o=[$h.Promise.resolve(a)],i=a.files;if(t.checkCRC32)for(var s=0;s<i.length;s++)o.push(Cq(i[s]));return $h.Promise.all(o)}).then(function(a){for(var o=a.shift(),i=o.files,s=0;s<i.length;s++){var l=i[s],c=l.fileNameStr,u=Vx.resolve(l.fileNameStr);r.file(u,l.decompressed,{binary:true,optimizedBinaryString:true,date:l.date,dir:l.dir,comment:l.fileCommentStr.length?l.fileCommentStr:null,unixPermissions:l.unixPermissions,dosPermissions:l.dosPermissions,createFolders:t.createFolders}),l.dir||(r.file(u).unsafeOriginalName=c);}return o.zipComment.length&&(r.comment=o.zipComment),r})};});var GR=B((nce,KR)=>{function ca(){if(!(this instanceof ca))return new ca;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var e=new ca;for(var t in this)typeof this[t]!="function"&&(e[t]=this[t]);return e};}ca.prototype=SR();ca.prototype.loadAsync=WR();ca.support=Ho();ca.defaults=Ub();ca.version="3.10.1";ca.loadAsync=function(e,t){return new ca().loadAsync(e,t)};ca.external=Jc();KR.exports=ca;});var on=class extends Error{constructor(t,r,n,a){super(t,n),this.name=new.target.name,this.code=r,this.extras=a||{},Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.technicalMessage=`${this.name}[${this.code}] - Extras: ${JSON.stringify(this.extras,null,2)}`;}};var is=class extends on{constructor(t){super("ConflictError","FIELD_CONFLICT",void 0,t);}};var ss=class extends on{constructor(t){super("Plan limit exceeded, redirecting to billing page...","PLAN_LIMIT_EXCEEDED",void 0,t);}},ls=class extends on{constructor(t){super("Credit limit exceeded. Please increase your limit to continue.","CREDIT_LIMIT_EXCEEDED",void 0,t);}};var ai=class extends Error{constructor(t,r,n){super(t),this.name=new.target.name,this.statusCode=r,n&&(this.code=n),this.toString=()=>`HTTP ${this.statusCode} error: ${this.code} - ${this.message}`;}};var Nf=class extends on{constructor(r="The requested resource was not found",n){super(r,"NOT_FOUND");this.resource=n;this.statusCode=404;this.name="NotFoundError";}toString(){let r=this.resource?` (${this.resource})`:"";return `${this.name}: ${this.message}${r}`}};var bl=class extends on{constructor(t){super("Too many pages","TOO_MANY_PAGES",void 0,t);}},xl=class extends on{constructor(t){super("File is too large","FILE_TOO_LARGE",void 0,t);}};function sn(e){if(e instanceof on)return e instanceof is?{type:"client_error",isRetryable:false,userMessage:"There was a conflict with recent changes. Please refresh and try again.",technicalMessage:`Conflict error: ${e.message}`}:e instanceof ss?{type:"client_error",isRetryable:false,userMessage:"You have reached your plan limit.",technicalMessage:`Plan limit error: ${e.message}`}:e instanceof ls?{type:"client_error",isRetryable:false,userMessage:"You have reached your credit limit. Increase your limit in settings or contact support.",technicalMessage:`Credit limit error: ${e.message}`}:e instanceof Nf?{type:"client_error",isRetryable:false,userMessage:"The page you are looking for does not exist.",technicalMessage:`Not found error: ${e.message}`}:e instanceof ai?{type:"client_error",isRetryable:false,userMessage:"Request failed. Please try again.",technicalMessage:`HTTP error: ${e.message}`}:e instanceof xl?{type:"client_error",isRetryable:false,userMessage:"File is too large",technicalMessage:`File too large error: ${e.message}`}:e instanceof bl?{type:"client_error",isRetryable:false,userMessage:"File has too many pages",technicalMessage:`Too many pages error: ${e.message}`}:{type:"client_error",isRetryable:false,userMessage:"An error occurred. Please try again.",technicalMessage:`Retab error: ${e.message}`};if(e.name==="TypeError"&&e.message.includes("Failed to fetch")){let t=typeof navigator<"u"&&navigator.onLine===false;return {type:"network_error",isRetryable:true,userMessage:t?"You appear to be offline. Please check your internet connection.":"Cannot reach the server. Retrying...",technicalMessage:t?"Browser reports offline status":"Network fetch failed \u2013 server unreachable"}}if(e.message?.includes("CORS")||e.message?.includes("Access-Control-Allow-Origin"))return {type:"cors_error",isRetryable:true,userMessage:"Connection issue. Retrying...",technicalMessage:"CORS error \u2013 likely offline or network connectivity issue"};if(e.name==="AbortError"||e.message?.includes("timeout"))return {type:"timeout_error",isRetryable:true,userMessage:"Request timed out. Retrying...",technicalMessage:"Request timeout or abort signal"};if(e.code||e instanceof ai&&e.code){let t=e.code||(e instanceof ai?e.code:void 0);if(t==="OPENAI_STREAMING_ERROR")return {type:"server_error",isRetryable:true,userMessage:"AI service temporarily unavailable. Retrying...",technicalMessage:`OpenAI streaming error: ${e.message||"Unknown streaming issue"}`};if(t==="OPENAI_RATE_LIMIT_ERROR")return {type:"server_error",isRetryable:true,userMessage:"AI service rate limited. Retrying...",technicalMessage:`OpenAI rate limit: ${e.message||"Rate limit exceeded"}`}}if(e.status||e.response?.status||e.statusCode){let t=e.statusCode??e.status??e.response.status;if(t===401||t===403)return {type:"auth_error",isRetryable:false,userMessage:"Authentication required. Please sign in again.",technicalMessage:`Authentication error: ${t}`};if(t===409)return {type:"client_error",isRetryable:false,userMessage:e.message||"Request conflict. Please check and try again.",technicalMessage:`Client conflict: ${t}`};if(t>=500)return {type:"server_error",isRetryable:true,userMessage:"Server temporarily unavailable. Retrying...",technicalMessage:`Server error: ${t}`};if(t>=400)return {type:"client_error",isRetryable:false,userMessage:"Request error. Please check your input.",technicalMessage:`Client error: ${t}`}}return {type:"unknown_error",isRetryable:false,userMessage:"An unexpected error occurred.",technicalMessage:e.message||"Unknown error"}}var kD=new Map;function wu(e){let t=sn(e);e instanceof ss||e instanceof ls||e instanceof is?console.warn(`[${t.type.toUpperCase()}] ${t.technicalMessage}:`,e):console.error(`[${t.type.toUpperCase()}] ${t.technicalMessage}:`,e);let r=false;if(e instanceof Error)for(let[n,a]of kD)e instanceof n&&(a.forEach(o=>{try{o(e,t);}catch(i){console.error("[ErrorManager] Handler threw:",i);}}),r=true);if(r||t.isRetryable||toast.error(t.userMessage),t.type==="auth_error"&&typeof window<"u")try{window.dispatchEvent(new CustomEvent("auth-required",{detail:{source:"error-manager"}}));}catch{}return t}Rt__default.createContext(null);async function Et(e,t){if(e.ok)throw new Error("Response is OK, but an error was expected");let n=(await e.json().catch(()=>({}))).detail,a=n?.code;switch(a){case "FIELD_CONFLICT":return new is(n.details);case "PLAN_LIMIT_EXCEEDED":return new ss(n.details);case "CREDIT_LIMIT_EXCEEDED":return new ls(n.details);case "FILE_TOO_LARGE":return new xl(n.details);case "TOO_MANY_PAGES":return new bl(n.details);default:return new ai(n?.message||t||e.statusText||"Unknown error",e.status,a)}}var Cw=createContext(null);function Ve(){let e=useContext(Cw);if(!e)throw new Error("useAuth must be used within a AuthProvider");return e}var $D="https://api.retab.com",ID=6e4,FD=3,MD=1e3;function lg(e){if(e instanceof TypeError&&e.message.includes("fetch"))return true;if(e instanceof Error){let t=e.message.toLowerCase();return t.includes("network")||t.includes("failed to fetch")||t.includes("net::")||t.includes("offline")||t.includes("connection")||t.includes("timeout")}return false}function jD(e){return lg(e)?"NETWORK_ERROR":e instanceof Error&&e.message.includes("token")?"TOKEN_FETCH_FAILED":"UNKNOWN"}function LD(e){return new Promise(t=>setTimeout(t,e))}function Ew({children:e,config:t,queryClient:r}){let n=useRef(null),a=useRef(null),o=useRef(false),i=useRef(0),[s,l]=useState(null),[c,u]=useState(typeof navigator<"u"?navigator.onLine:true),[d,g]=useState(false),f=t.maxRetries??FD,h=t.retryBaseDelay??MD;useEffect(()=>{let P=()=>{console.log("[AuthProvider] Network connection restored"),u(true),l(N=>N?.code==="NETWORK_ERROR"?null:N),i.current=0;},T=()=>{console.log("[AuthProvider] Network connection lost"),u(false);};return typeof window<"u"&&(window.addEventListener("online",P),window.addEventListener("offline",T)),()=>{typeof window<"u"&&(window.removeEventListener("online",P),window.removeEventListener("offline",T));}},[]),useEffect(()=>{if(c&&s?.code==="NETWORK_ERROR"){console.log("[AuthProvider] Online again, retrying token fetch...");let P=setTimeout(()=>{n.current=null,i.current=0,l(null);},500);return ()=>clearTimeout(P)}},[c,s]);let m=useMemo(()=>r??new QueryClient({defaultOptions:{queries:{staleTime:1e3*60*5,refetchOnWindowFocus:false,retry:(P,T)=>T instanceof Error&&T.message.includes("401")?false:lg(T)?P<5:P<3,retryDelay:P=>Math.min(1e3*2**P,3e4)}}}),[r]),p=t.baseUrl??$D,v=useCallback(async()=>{let P;for(let S=0;S<=f;S++)try{if(typeof navigator<"u"&&!navigator.onLine)throw new Error("Network offline");let b=await t.getToken();l(null),i.current=0;let D=Date.now()+3300*1e3;try{let O=b.split(".");if(O.length===3){let $=JSON.parse(atob(O[1]));typeof $.exp=="number"&&(D=$.exp*1e3-ID);}}catch{}return n.current={token:b,expiresAt:D},b}catch(b){if(P=b,i.current=S+1,console.warn(`[AuthProvider] Token fetch attempt ${S+1}/${f+1} failed:`,b instanceof Error?b.message:b),typeof navigator<"u"&&!navigator.onLine)break;if(S<f){let k=h*Math.pow(2,S),D=Math.random()*500;console.log(`[AuthProvider] Retrying in ${k+D}ms...`),await LD(k+D);}}let T=jD(P),N={message:P instanceof Error?P.message:"Token fetch failed",code:T,timestamp:Date.now(),retryCount:i.current};throw l(N),console.error("[AuthProvider] Token fetch failed after all retries:",N),P},[t.getToken,f,h]),y=useCallback(async()=>{let P=Date.now();return n.current&&P<n.current.expiresAt?n.current.token:(a.current||(g(true),a.current=v().finally(()=>{a.current=null,g(false);})),a.current)},[v]),x=useCallback(async()=>({Authorization:`Bearer ${await y()}`}),[y]),w=useCallback(async(P,T={})=>{let N=P.startsWith("http")?P:`${p}${P}`;try{let S=await x(),b=new Headers(T.headers);Object.entries(S).forEach(([D,O])=>{b.set(D,O);});let k=await fetch(N,{...T,headers:b});if(k.status===401){console.log("[AuthProvider] Received 401, refreshing token..."),n.current=null,i.current=0;try{let D=await x(),O=new Headers(T.headers);return Object.entries(D).forEach(([$,A])=>{O.set($,A);}),fetch(N,{...T,headers:O})}catch(D){throw l({message:"Session expired. Please refresh the page.",code:"AUTH_EXPIRED",timestamp:Date.now(),retryCount:i.current}),D}}return k}catch(S){throw lg(S)&&(console.error("[AuthProvider] Network error during fetch:",S),l({message:"Network error. Check your connection.",code:"NETWORK_ERROR",timestamp:Date.now(),retryCount:i.current})),S}},[p,x]),_=useCallback(async()=>{n.current=null,i.current=0,l(null),await y();},[y]),E=useCallback(async()=>{console.log("[AuthProvider] Manual retry initiated"),n.current=null,i.current=0,l(null);try{await y(),m.invalidateQueries();}catch(P){console.error("[AuthProvider] Manual retry failed:",P);}},[y,m]);useEffect(()=>{let P=async()=>{if(!o.current){o.current=true;try{n.current=null,await y(),m.invalidateQueries();}catch(T){console.error("[AuthProvider] Failed to refresh token:",T);}finally{o.current=false;}}};return typeof window<"u"&&window.addEventListener("auth-required",P),()=>{typeof window<"u"&&window.removeEventListener("auth-required",P);}},[y,m]);let C=useMemo(()=>({baseUrl:p,getAuthHeaders:x,fetchWithAuth:w,refreshToken:_,authError:s,isOnline:c,isAuthenticating:d,retryAuth:E}),[p,x,w,_,s,c,d,E]);return jsx(QueryClientProvider,{client:m,children:jsx(Cw.Provider,{value:C,children:e})})}var Yt={all:["projects"],lists:()=>[...Yt.all,"list"],list:e=>[...Yt.lists(),{filters:e}],details:()=>[...Yt.all,"detail"],detail:e=>[...Yt.details(),e],builderDocuments:e=>[...Yt.detail(e),"builder-documents"],builderDocument:(e,t)=>[...Yt.builderDocuments(e),t]};var Pw=e=>{let{fetchWithAuth:t}=Ve();return useQuery({queryKey:Yt.detail(e),queryFn:async()=>{let r=await t(`/v1/projects/${e}`);if(!r.ok)throw await Et(r,"Failed to fetch project");return r.json()},enabled:!!e,refetchInterval:300*1e3,refetchIntervalInBackground:false,structuralSharing:false,throwOnError:r=>sn(r).type!=="auth_error"})};var Tw=()=>{let e=useQueryClient(),{fetchWithAuth:t}=Ve();return useMutation({mutationFn:async r=>{let{projectId:n,request:a}=r;if(!n)throw new Error("Project ID is required");let o=await t(`/v1/projects/${n}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!o.ok)throw await Et(o,`Failed to update project ${n}`);return o.json()},onSuccess:(r,{projectId:n})=>{e.setQueryData(Yt.detail(n),r),e.invalidateQueries({queryKey:Yt.lists()});},onError:r=>{wu(r);}})},kw=()=>{let e=useQueryClient(),{fetchWithAuth:t}=Ve();return useMutation({mutationFn:async r=>{let n=await t(`/v1/projects/${r}`,{method:"DELETE"});if(!n.ok)throw await Et(n,"Failed to delete project")},onSuccess:(r,n)=>{e.removeQueries({queryKey:Yt.detail(n)}),e.invalidateQueries({queryKey:Yt.lists()});},onError:r=>{wu(r);}})},Rw=()=>{let e=useQueryClient(),{fetchWithAuth:t}=Ve();return useMutation({mutationFn:async r=>{let{projectId:n,request:a}=r,o=await t(`/v1/projects/${n}/duplicate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a??{})});if(!o.ok)throw await Et(o,"Failed to duplicate project");return o.json()},onSuccess:r=>{e.setQueryData(Yt.detail(r.id),r),e.invalidateQueries({queryKey:Yt.lists()});},onError:r=>wu(r)})},Ow=()=>{let e=useQueryClient(),{fetchWithAuth:t}=Ve();return useMutation({mutationFn:async r=>{let{projectId:n,request:a}=r,o=await t(`/v1/projects/${n}/rename`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!o.ok)throw await Et(o,"Failed to rename project");return o.json()},onSuccess:r=>{e.setQueryData(Yt.detail(r.id),r),e.invalidateQueries({queryKey:Yt.lists()});},onError:r=>wu(r)})};function R(...e){return twMerge(clsx(e))}var cs=cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",destructive:"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9",iconSm:"size-8",iconXs:"size-6"}},defaultVariants:{variant:"default",size:"default"}});function K({className:e,variant:t,size:r,asChild:n=false,...a}){return jsx(n?Slot:"button",{"data-slot":"button",className:R(cs({variant:t,size:r,className:e})),...a})}var $w=createContext(void 0),Aw=e=>JSON.stringify(e);function Iw({children:e}){let{fetchWithAuth:t}=Ve(),[r,n]=useState({}),a=useRef({}),[o,i]=useState(()=>{if(typeof window>"u")return {};try{let S=sessionStorage.getItem("ocrFileUrls");return S?JSON.parse(S):{}}catch{return {}}}),s=useRef(new Set),l=useRef({}),[c,u]=useState(0),d=useRef(new Set),g=useQueryClient(),f=async(S,b,k,D,O,$)=>{try{let A=await t("/v1/documents/compute_field_locations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file_id:O,data:D,method:"bm25",extraction_id:$})});if(!A.ok)throw new Error(`Failed to compute ${k} field locations`);let F=await A.json();if(F.status==="success"){let H=b==="ground_truth"||k==="dataset"||k==="playground"?`${S}_ground_truth`:`${S}_extraction_${k}`;return n(L=>{let Q={...L};return delete Q[H],Q}),F.field_locations}}catch(A){console.error(`[computeFieldLocations] FAILED for ${k}:`,A);let F=b==="ground_truth"||k==="dataset"||k==="playground",X=F?`${S}_ground_truth`:`${S}_extraction_${k}`;n(H=>({...H,[X]:`Failed to compute ${F?"ground truth":k} sources. ${A.message||"Please try again."}`}));}return null},h=(S,b)=>{let k=`${S}_${b}`;return r[k]||null},m=(S,b,k)=>{let O=b==="ground_truth"||k==="dataset"||k==="playground"?`${S}_ground_truth`:`${S}_extraction_${k}`;return r[O]||null},p=(S,b)=>{let k=`${S}_${b}`;n(D=>{let O={...D};return delete O[k],O});},v=(S,b,k)=>{let O=b==="ground_truth"||k==="dataset"||k==="playground"?`${S}_ground_truth`:`${S}_extraction_${k}`;n($=>{let A={...$};return delete A[O],A});},y=useCallback(async(S,b=true)=>{if(!a.current[S]){a.current[S]=true;try{let k=await t("/v1/documents/perform_ocr",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({file_id:S})});if(!k.ok)throw new Error(`OCR request failed: ${k.statusText}`);let O=(await k.json()).ocr_file_url;O&&i($=>({...$,[S]:O})),b&&toast.success("OCR completed successfully");}catch(k){console.error("[performOCR] OCR request failed:",k),b&&toast.error(k.message||"Failed to perform OCR processing");}finally{a.current[S]=false;}}},[g]),x=useCallback(S=>a.current[S]||false,[]),w=useCallback((S,b)=>{if(b.includes("dataset")||b.includes("builder")||b.includes("playground")){let O=`${S}_ground_truth`,$=l.current[O];return $?$.fieldLocations:null}let k=`${S}_extraction_${b}`,D=l.current[k];return D?D.fieldLocations:null},[c]),_=useCallback((S,b,k)=>{if(b==="ground_truth"){let $=`${S}_ground_truth`,A=l.current[$];return A?A.fieldLocations:null}if(k.includes("dataset")||k.includes("builder")||k.includes("playground")){let $=`${S}_ground_truth`,A=l.current[$];return A?A.fieldLocations:null}let D=`${S}_extraction_${k}`,O=l.current[D];return O?O.fieldLocations:null},[c]),E=useCallback((S,b)=>{if(b.includes("dataset")||b.includes("builder")||b.includes("playground")){let D=`${S}_ground_truth`;return !l.current[D]}else {let D=`${S}_extraction_${b}`;return !l.current[D]}},[c]),C=useCallback(async S=>{S&&(o[S]||s.current.has(S)||(s.current.add(S),y(S,false).finally(()=>{s.current.delete(S);})));},[y,o]),P=useCallback(async S=>{try{i(b=>{let k={...b};return delete k[S],k}),await y(S,!1);}catch(b){console.error("[refreshOCRUrl] Failed to refresh OCR URL for",S,b);}},[y]);useEffect(()=>{if(!(typeof window>"u"))try{sessionStorage.setItem("ocrFileUrls",JSON.stringify(o));}catch{}},[o]);let T=useCallback(async(S,b,k,D,O)=>{if(!S)return;let $=b&&Object.keys(b).length>0,F=D.includes("dataset")||D.includes("builder")||D.includes("playground")?`${S}_ground_truth`:`${S}_extraction_${D}`,X=Aw(b),H=l.current[F],L=d.current.has(F),Q=!H||H.dataHash!==X;$&&Q&&!L&&(d.current.add(F),f(S,"ground_truth",D,b,k,O).then(ae=>{ae&&(l.current[F]={fieldLocations:ae,dataHash:X},u(M=>M+1));}).catch(ae=>{console.error("[autoComputeFieldLocations] Error during computation:",ae);}).finally(()=>{d.current.delete(F);}));},[f,Aw]),N=useMemo(()=>({computeFieldLocations:f,getFieldLocationsError:h,clearFieldLocationsError:p,getFieldLocationsErrorByType:m,clearFieldLocationsErrorByType:v,isPerformingOCR:x,performOCR:y,ocrFileUrls:o,getInMemoryFieldLocations:w,getInMemoryFieldLocationsByType:_,inMemoryFieldLocationsRef:l,counterFieldLocationUpdated:c,setCounterFieldLocationUpdated:u,isInitializingFieldLocations:E,autoPerformOCR:C,autoComputeFieldLocations:T,refreshOCRUrl:P}),[f,h,p,m,v,x,y,o,w,_,l,c,u,E,C,T,P]);return jsx($w.Provider,{value:N,children:e})}function us(){let e=useContext($w);if(!e)throw console.error("[useOCR] Context is undefined! useOCR must be used within an OCRProvider"),new Error("useOCR must be used within an OCRProvider");return e}var kf=e=>!!(e.startsWith("image/")||e==="application/pdf"||e==="application/octet-stream"||["application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.oasis.opendocument.spreadsheet","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.oasis.opendocument.text","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.oasis.opendocument.presentation"].includes(e)||e.startsWith("text/")||e==="text/html"||e==="message/rfc822"||e==="application/json"||e==="application/xml"||e==="application/yaml"||e.startsWith("audio/"));var jw=createContext(void 0),rA={id:"default_project",name:"Project",is_schema_generated:true,updated_at:new Date().toISOString(),published_config:{inference_settings:{model:"auto-small",temperature:.5,reasoning_effort:"minimal",image_resolution_dpi:192,n_consensus:1},computation_spec:{computations:{}},json_schema:{},human_in_the_loop_criteria:[{path:"",agentic_fix:false}],origin:"manual"},draft_config:{inference_settings:{model:"auto-small",temperature:.5,reasoning_effort:"minimal",image_resolution_dpi:192,n_consensus:1},json_schema:{},human_in_the_loop_criteria:[],computation_spec:{computations:{}}},is_published:false},Mw=e=>JSON.stringify(e);function Lw({children:e,projectId:t}){let r=useQueryClient(),{fetchWithAuth:n}=Ve(),a=Pw(t),o=Tw(),i=kw(),s=Rw(),l=Ow(),{computeFieldLocations:c,inMemoryFieldLocationsRef:u,setCounterFieldLocationUpdated:d}=us(),g=useRef(new Set),f=useRef(new Set),h=Rt.useMemo(()=>a.data!==void 0&&!a.isLoading?a.data:{...rA,id:t},[a.data,a.isLoading,t]),m=useCallback(async(b,k)=>{if(k?.optimistic??false){let $=r.getQueryData(Yt.detail(t));if($){let A={...$,...b,draft_config:b.draft_config?{...$.draft_config,...b.draft_config,json_schema:b.draft_config.json_schema||$.draft_config?.json_schema}:$.draft_config};r.setQueryData(Yt.detail(t),A);}}return await o.mutateAsync({projectId:t,request:b})},[t,o,r]),p=useCallback(async b=>{await i.mutateAsync(b);},[i]),v=useCallback(async b=>await s.mutateAsync({projectId:t,request:b}),[t,s]),y=useCallback(async b=>await l.mutateAsync({projectId:t,request:{name:b}}),[t,l]),x=useCallback(async b=>{let k=b?`?origin=${encodeURIComponent(b)}`:"",D=await n(`/v1/projects/${t}/publish${k}`,{method:"POST"});if(!D.ok)throw await Et(D,"Failed to publish project");let O=await D.json();return r.setQueryData(Yt.detail(t),O),r.invalidateQueries({queryKey:Yt.lists()}),O},[t,r]),w=useCallback(async()=>{let b=await n(`/v1/projects/${t}/unpublish`,{method:"POST"});if(!b.ok)throw await Et(b,"Failed to unpublish project");let k=await b.json();return r.setQueryData(Yt.detail(t),k),r.invalidateQueries({queryKey:Yt.lists()}),k},[t,r]),_=useCallback(()=>{a.refetch();},[a]),E=useCallback(async()=>{},[]),C=useCallback(async(b,k)=>{if(!b.id)return;let D=b.prediction_data.prediction&&Object.keys(b.prediction_data.prediction).length>0,O=`${b.id}_ground_truth`,$=Mw(b.prediction_data.prediction),A=u.current[O],F=g.current.has(O),X=!A||A.dataHash!==$;D&&X&&!F&&(g.current.add(O),c(b.id,"ground_truth",k,b.prediction_data.prediction,b.mime_data.id).then(L=>{L&&(u.current[O]={fieldLocations:L,dataHash:$},d(Q=>Q+1));}).catch(console.error).finally(()=>{g.current.delete(O);}));},[c,u,d]),P=useCallback(async(b,k)=>{let D=b.prediction_data.prediction&&Object.keys(b.prediction_data.prediction).length>0,O=`${b.id}_extraction_${k}`,$=Mw(b.prediction_data.prediction),A=u.current[O],F=f.current.has(O),X=!A||A.dataHash!==$;D&&!F&&X&&(f.current.add(O),c(b.id,"extraction",k,b.prediction_data.prediction,b.mime_data.id).then(L=>{L&&(u.current[O]={fieldLocations:L,dataHash:$},d(Q=>Q+1));}).catch(console.error).finally(()=>{f.current.delete(O);}));},[c,u,d]),T=useCallback(async b=>{if(!b||Object.keys(b).length===0)return b;let k=await n(`/v1/projects/${t}/apply-computations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({data:b})});if(!k.ok)throw await Et(k,"Failed to apply computations");return (await k.json())?.data??b},[t]),N=Rt.useMemo(()=>{if(a.error){let b=sn(a.error);if(!b.isRetryable&&b.type!=="auth_error")throw a.error}return {project:h,isLoading:a.isLoading,isError:!!a.error,error:a.error,updateProject:m,deleteProject:p,duplicateProject:v,renameProject:y,publishProject:x,unpublishProject:w,refreshProject:_,batchPerformOCR:E,autoComputeNonIterationFieldLocations:C,autoComputeIterationFieldLocations:P,applyComputations:T}},[h,a.isLoading,a.error,m,p,v,y,x,_,E,C,P,T]),S=a.error?sn(a.error):null;return jsxs(jw.Provider,{value:N,children:[S&&S.isRetryable&&S.type!=="auth_error"&&jsxs("div",{className:"bg-amber-50 border-b border-amber-200 p-2 text-amber-800 text-sm flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("span",{children:typeof navigator<"u"&&navigator.onLine===false?"You are offline.":"Connection issue."}),jsx("span",{className:"opacity-80",children:"Retrying\u2026"})]}),jsxs(K,{variant:"outline",size:"sm",onClick:()=>a.refetch(),disabled:a.isRefetching,className:"h-7 px-2",children:[jsx(RefreshCw,{className:`h-3.5 w-3.5 mr-1 ${a.isRefetching?"animate-spin":""}`}),"Retry now"]})]}),e]})}function Fr(){let e=useContext(jw);if(e===void 0)throw new Error("useProject must be used within a ProjectProvider");return e}var AS=os(Wu()),$S=os(r0()),IS=os(RS()),FS=os(Ky());var gp=structuredClone(FS.default);gp.$id="http://retab-json-schema.org/draft-07/enriched-schema#";function MS(e){if(e&&typeof e=="object"){e.type==="object"&&(e.propertyNames={type:"string",pattern:"^(?![-+]?(\\d+(\\.\\d*)?|\\.\\d+)$).+"});for(let t of Object.keys(e))typeof e[t]=="object"&&MS(e[t]);}}MS(gp);set(gp,"properties.additionalProperties",{const:false});var jS=createContext(void 0),yp=new AS.default({allErrors:true});(0, $S.default)(yp);(0, IS.default)(yp);var DS=yp.compile(gp);function LS({jsonSchema:e,setJsonSchema:t,computedSchema:r,layoutSchema:n,persistJsonSchemaCallback:a,children:o}){let i=e,s=r??e,[l,c]=useState(),[u,d]=useState(true),[g,f]=useState(0),h=useRef(i);useEffect(()=>{h.current=i;},[i]);let m=useCallback((w,_)=>{if(!w||!_||typeof w!="object"||typeof _!="object")return false;if(w.properties&&_.properties){let E=Object.keys(w.properties),C=Object.keys(_.properties);if(E.length===C.length){for(let P=0;P<E.length;P++)if(E[P]!==C[P])return true}for(let P of E)if(_.properties[P]&&m(w.properties[P],_.properties[P]))return true}if(w.$defs&&_.$defs){let E=Object.keys(w.$defs);for(let C of E)if(_.$defs[C]&&m(w.$defs[C],_.$defs[C]))return true}return false},[]),p=useCallback(async(w,_)=>{process.env.NODE_ENV;let E=typeof w=="function"?w(h.current):w,C=m(h.current,E);if(!!isEqual(h.current,E)&&!C){(_??true)&&a&&await a(E);return}t&&t(E),(_??true)&&a&&await a(E);},[t,a,m]),v=useCallback(w=>{if(!w||typeof w!="object")return 0;let _=(C,P="")=>{if(!C||typeof C!="object")return 0;let T=0;if(C["X-ReasoningPrompt"]!==void 0&&C["X-ReasoningPrompt"]!==null&&C["X-ReasoningPrompt"]!==""&&(T+=1),C.$ref&&typeof C.$ref=="string"&&C.$ref.startsWith("#/")){let N=C.$ref.substring(2).split("/"),S=w;for(let b of N)if(S&&typeof S=="object")S=S[b];else {S=void 0;break}S&&(T+=_(S,`${P}>${C.$ref}`));}return C.properties&&typeof C.properties=="object"&&(T+=Object.keys(C.properties).length,Object.entries(C.properties).forEach(([N,S])=>{T+=_(S,`${P}/properties/${N}`);})),C.type==="array"&&C.items&&(Array.isArray(C.items)?C.items.forEach((N,S)=>{T+=_(N,`${P}/items/${S}`);}):T+=_(C.items,`${P}/items`)),["allOf","anyOf","oneOf"].forEach(N=>{let S=C[N];Array.isArray(S)&&S.forEach((b,k)=>{T+=_(b,`${P}/${N}/${k}`);});}),T};return _(w)},[]),y=useCallback(w=>{if(!w||w.length===0)return [];let _=[],E=new Set;for(let C of w)if(C.keyword==="pattern"&&C.schemaPath?.includes("/propertyNames/pattern")&&C.data&&typeof C.data=="string"){let P=C.data;E.has(P)||(_.push({keyword:"propertyNames",instancePath:C.instancePath,schemaPath:C.schemaPath,params:{propertyName:P},message:`Property name "${P}" must not be purely numeric`,data:C.data,schema:C.schema}),E.add(P));}else if(C.keyword==="propertyNames"&&C.params?.propertyName){let P=C.params.propertyName;E.has(P)||(_.push({keyword:"propertyNames",instancePath:C.instancePath,schemaPath:C.schemaPath,params:{propertyName:P},message:`Property name "${P}" must not be purely numeric`,data:C.data,schema:C.schema}),E.add(P));}else C.keyword==="const"&&C.schemaPath?.includes("/additionalProperties/const")?_.push({keyword:"additionalProperties",instancePath:C.instancePath,schemaPath:C.schemaPath,params:C.params,message:"`additionalProperties` are forbidden, if present they MUST be false.",data:C.data,schema:C.schema}):C.keyword!=="propertyNames"&&!(C.keyword==="pattern"&&C.schemaPath?.includes("/propertyNames/pattern"))&&!(C.keyword==="const"&&C.schemaPath?.includes("/additionalProperties/const"))&&_.push(C);return _},[]);useEffect(()=>{let w=v(i);f(w);let _=w>100,E=DS(i)&&!_;c(E?void 0:_?`Schema has too many properties: ${w}. Maximum accepted by OpenAI is 100. Please reduce the number of properties.`:yp.errorsText(y(DS.errors),{separator:`
10
10
 
11
- `})),d(S);},[i]);let v=useMemo(()=>({jsonSchema:i,setJsonSchema:f,computedSchema:s,isValidSchema:u,validationErrors:l}),[i,f,s,u,l]);return jsx(tS.Provider,{value:v,children:a})}function jo(){let e=useContext(tS);if(e===void 0)throw new Error("useJsonSchema must be used within a JsonSchemaProvider");return e}function uF({children:e}){let t={title:"",description:"",type:"object",properties:{},required:[]},[r,n]=useState(t);return jsx(rS,{jsonSchema:r,setJsonSchema:n,computedSchema:r,children:e})}var nS=kt__default.memo(function({jsonSchema:t,setJsonSchema:r,computedSchema:n,layoutSchema:o,persistJsonSchemaCallback:a,children:i}){return !t&&!n?jsx(uF,{children:i}):jsx(rS,{jsonSchema:t,setJsonSchema:r,computedSchema:n,layoutSchema:o,persistJsonSchemaCallback:a,children:i})});var $t={all:["extractions"],lists:()=>[...$t.all,"list"],list:e=>[...$t.lists(),{filters:e}],details:()=>[...$t.all,"detail"],detail:e=>[...$t.details(),e]};var Lo=(e={},t={})=>{let{enabled:r=true}=t,{fetchWithAuth:n}=De();return useQuery({queryKey:$t.list(e),queryFn:async()=>{let o=new URLSearchParams;e.before&&o.append("before",e.before),e.after&&o.append("after",e.after),e.limit!==void 0&&o.append("limit",String(e.limit)),e.order&&o.append("order",e.order),e.origin_dot_id&&o.append("origin_dot_id",e.origin_dot_id),e.metadata&&Object.keys(e.metadata).length>0&&o.append("metadata",JSON.stringify(e.metadata)),e.filename&&o.append("filename",e.filename),e.from_date&&o.append("from_date",e.from_date),e.to_date&&o.append("to_date",e.to_date),e.human_review_status&&o.append("human_review_status",e.human_review_status);let a=`/v1/extractions${o.toString()?`?${o.toString()}`:""}`,i=await n(a);if(!i.ok)throw await Tt(i,"Failed to fetch extractions");return i.json()},throwOnError:o=>Xr(o).type!=="auth_error",enabled:r})};var My=e=>{let{fetchWithAuth:t}=De();return useQuery({queryKey:$t.detail(e||"null"),queryFn:async()=>{if(!e)throw new Error("Extraction ID is required");let r=await t(`/v1/extractions/${e}`);if(r.status===404)return null;if(!r.ok)throw await Tt(r,"Failed to fetch extraction");return r.json()},enabled:!!e,retry:(r,n)=>n.message?.includes("404")||Xr(n).type==="auth_error"?false:r<3,throwOnError:r=>Xr(r).type!=="auth_error"})},hl=()=>{let e=useQueryClient(),{fetchWithAuth:t}=De();return useMutation({mutationFn:async r=>{let{extractionId:n,...o}=r,a=await t(`/v1/extractions/${n}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!a.ok)throw await Tt(a,"Failed to update extraction");return a.json()},onSuccess:r=>{e.setQueryData($t.detail(r.id),r);let n=e.getQueriesData({queryKey:$t.lists()});for(let[o,a]of n)a&&e.setQueryData(o,{...a,data:a.data.map(i=>i.id===r.id?r:i)});}})},Wf=()=>{let e=useQueryClient(),{fetchWithAuth:t}=De();return useMutation({mutationFn:async r=>{let n=await t(`/v1/extractions/${r}`,{method:"DELETE"});if(!n.ok)throw await Tt(n,"Failed to delete extraction")},onSuccess:()=>{e.invalidateQueries({queryKey:$t.all});}})};var sS=e=>createStore()(t=>({limit:e?.limit??50,order:e?.order??"desc",originId:e?.originId??void 0,dateRange:{},humanReviewStatus:e?.humanReviewStatus??"review_required",cursors:{before:null,after:null},normalizedCursors:{before:null,after:null},hasNormalizedSingleOnce:false,selectedExtractionId:null,setLimit:r=>t({limit:r,cursors:{before:null,after:null}}),setOrder:r=>t({order:r}),setOriginId:r=>t({originId:r}),setDateRange:r=>t({dateRange:r,cursors:{before:null,after:null}}),setHumanReviewStatus:r=>t({humanReviewStatus:r,cursors:{before:null,after:null}}),setCursors:r=>t({cursors:r}),setNormalizedCursors:r=>t({normalizedCursors:r}),setHasNormalizedSingleOnce:r=>t({hasNormalizedSingleOnce:r}),setSelectedExtractionId:r=>t({selectedExtractionId:r}),resetCursors:()=>t({cursors:{before:null,after:null},normalizedCursors:{before:null,after:null},hasNormalizedSingleOnce:false}),resetFilters:r=>t({limit:r?.limit??50,order:r?.order??"desc",humanReviewStatus:r?.humanReviewStatus??"review_required",originId:r?.originId??void 0,dateRange:{},cursors:{before:null,after:null},normalizedCursors:{before:null,after:null},hasNormalizedSingleOnce:false,selectedExtractionId:null})}));var Ly=createContext(void 0),hF=createContext(null);function fS({children:e,initialLimit:t=50,initialOrder:r="desc",initialHumanStatus:n="review_required",originId:o,mode:a="full"}){let i=useQueryClient(),{fetchWithAuth:s}=De(),l=useRef(null);l.current||(l.current=sS({limit:t,order:r,humanReviewStatus:n,originId:o}));let c=l.current,u=useStore(c,$=>$.limit),d=useStore(c,$=>$.order),m=useStore(c,$=>$.originId),h=useStore(c,$=>$.dateRange),y=useStore(c,$=>$.humanReviewStatus),p=useStore(c,$=>$.cursors),f=useStore(c,$=>$.normalizedCursors),x=useStore(c,$=>$.hasNormalizedSingleOnce),g=useStore(c,$=>$.selectedExtractionId),v=useStore(c,$=>$.setLimit),w=useStore(c,$=>$.setOrder),N=useStore(c,$=>$.setOriginId),S=useStore(c,$=>$.setDateRange),_=useStore(c,$=>$.setHumanReviewStatus),P=useStore(c,$=>$.setCursors),R=useStore(c,$=>$.setNormalizedCursors),E=useStore(c,$=>$.setHasNormalizedSingleOnce),C=useStore(c,$=>$.setSelectedExtractionId),b=useStore(c,$=>$.resetCursors);useEffect(()=>{let $=false,L=u===1,le=!!p.before&&!p.after;async function ae(){if(L&&le){if(x){R({before:p.before,after:null});return}let Oe=new URLSearchParams;Oe.append("before",p.before),Oe.append("limit","1"),d&&Oe.append("order",d),m&&Oe.append("origin_dot_id",m),h.from&&Oe.append("from_date",format(h.from,"yyyy-MM-dd")),h.to&&Oe.append("to_date",format(h.to,"yyyy-MM-dd")),y&&y!=="all"&&Oe.append("human_review_status",y);try{let ye=`/v1/extractions${Oe.toString()?`?${Oe.toString()}`:""}`,ft=await s(ye);if(!ft.ok)throw await Tt(ft,"Failed to normalize cursors");let Et={before:null,after:(await ft.json())?.data?.[0]?.id??null};$||(R(Et),E(!0));}catch{$||R({before:null,after:null});}return}R({before:p.before,after:p.after});}return ae(),()=>{$=true;}},[u,p.before,p.after,d,m,h.from,h.to,y,s,R,E,x]),useEffect(()=>{!p.before&&!p.after&&E(false);},[p.before,p.after,u,d,m,y,h.from,h.to,E]);let{project:O}=Qr(),D=useMemo(()=>{let $={limit:u,order:d};y&&y!=="all"&&($.human_review_status=y),m&&($.origin_dot_id=m),h.from&&($.from_date=format(h.from,"yyyy-MM-dd")),h.to&&($.to_date=format(h.to,"yyyy-MM-dd"));let L=f.before,le=f.after;return L&&($.before=L),le&&($.after=le),$},[u,d,y,m,h,f.before,f.after]),k=Lo(D,{enabled:a==="full"}),I=k.data?.data??[],F=k.data?.list_metadata??{before:null,after:null};useEffect(()=>{k.error&&toast.error("Failed to fetch extractions");},[k.error]);let Z=useCallback(()=>{F.before&&P({before:F.before,after:null});},[F.before,P]),pe=useCallback(()=>{F.after&&P({before:null,after:F.after});},[F.after,P]),ie=useCallback(()=>{b(),i.invalidateQueries({queryKey:["extractions"]});},[i,b]),J=useCallback($=>{P({before:$.before??null,after:$.after??null});},[P]),ue=useCallback(async $=>{if($)try{let L=await s(`/v1/extractions/${$}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({human_review_status:"reviewed"})});if(!L.ok)throw await Tt(L,"Failed to validate extraction");let le=await L.json();if(console.log("responseData",le),L.ok){let ae=[...$t.all,"count",{origin_dot_id:m,human_review_status:"review_required"}];i.setQueryData(ae,ye=>ye&&{count:Math.max(0,(ye.count??0)-1)});let Oe=[...$t.all,"count",{origin_dot_id:m,human_review_status:"reviewed"}];i.setQueryData(Oe,ye=>ye&&{count:(ye.count??0)+1}),i.invalidateQueries({queryKey:["extractions"]});}return le}catch(L){throw console.error("validateExtraction failed",L),L}},[m,i,s]),re=useCallback(async $=>{if($)try{let L=await s(`/v1/extractions/${$}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({human_review_status:"review_required"})});if(!L.ok)throw await Tt(L,"Failed to invalidate human review");let le=await L.json();if(console.log("responseData",le),L.ok){let ae=[...$t.all,"count",{origin_dot_id:m,human_review_status:"review_required"}];i.setQueryData(ae,ye=>ye&&{count:(ye.count??0)+1});let Oe=[...$t.all,"count",{origin_dot_id:m,human_review_status:"reviewed"}];i.setQueryData(Oe,ye=>ye&&{count:Math.max(0,(ye.count??0)-1)}),i.invalidateQueries({queryKey:["extractions"]});}return le}catch(L){throw console.error("invalidateHumanReview failed",L),L}},[m,i,s]),X=useMemo(()=>({extractions:I,cursors:p,meta:F,isLoading:k.isLoading||k.isRefetching,isError:!!k.error,error:k.error??null,limit:u,setLimit:v,order:d,setOrder:w,originId:m,setOriginId:N,dateRange:h,setDateRange:S,humanReviewStatus:y,setHumanReviewStatus:_,selectedExtractionId:g,setSelectedExtractionId:C,fetchNextPage:Z,fetchPrevPage:pe,refresh:ie,setCursorsFromUrl:J,transientUpdateExtraction:($,L)=>{i.setQueryData($t.list(D),le=>le&&{...le,data:le.data.map(ae=>ae.id===$?{...ae,...L}:ae)});},validateExtraction:ue,invalidateHumanReview:re}),[I,p,F,k.isLoading,k.isRefetching,k.error,u,v,d,w,m,N,h,S,y,_,g,C,Z,pe,ie,J,D,i,ue,re]);return jsx(hF.Provider,{value:c,children:jsx(Ly.Provider,{value:X,children:e})})}function pS(){let e=useContext(Ly);if(e===void 0)throw new Error("useExtractions must be used within an ExtractionsProvider");return e}function ei(){return useContext(Ly)}function xu(e){return e.operation?e.operation:null}function Ut(e,t){if(e&&e.$ref){let r=e.$ref;if(r.startsWith("#/")){let n=r.substring(2).split("/"),o=t;for(let a of n)if(o&&typeof o=="object"&&a in o)o=o[a];else return e;return o}}return e}function Yi(e,t,r){if(!e)return t;let n=e.split("."),o=t;for(let a of n)if(a==="*")if(o.type==="array"){let i=o.items||{};o=Ut(i,t);}else return {};else if(o.type==="object"){let i=o.properties||{};if(a in i){let s=i[a];o=Ut(s,t);}else throw new Error(`Field '${a}' not found in schema at path '${e}'`)}else throw o.type==="array"?new Error(`Cannot access field '${a}' on array type at path '${e}'`):new Error(`Path '${e}' does not exist in schema`);return o}function Zf(e,t,r){try{let n=Yi(e,t,r);return Object.keys(n).length>0}catch{return false}}function zy(e,t,r){if(!e)return t.type||null;try{return Yi(e,t,r).type||null}catch{return null}}function Xf(e,t){switch(e.operation){case "$concat":return {type:"string"};case "$eq":case "$gt":case "$gte":case "$lt":case "$lte":case "$and":case "$or":case "$not":return {type:"boolean"};case "$count":case "$match":return {type:"integer"};case "$filter":return {type:"array",items:{}};case "$add":case "$subtract":case "$multiply":case "$divide":case "$abs":case "$sqrt":case "$log":case "$pow":return t&&t.some(r=>qF(r))?{type:"array",items:{type:"number"}}:{type:"number"};case "$sum":case "$average":case "$min":case "$max":return {type:"number"};case "$lookup":return {};case "$if":if(t&&t.length>=3){let r=t[1],n=t[2];if(r?.type&&n?.type&&r.type===n.type)return {type:r.type};if(r?.type)return {type:r.type};if(n?.type)return {type:n.type}}return {type:"string"};default:return {type:"number"}}}function qF(e){if(!e||typeof e!="object")return false;if(e.type==="array")return true;let t=e.anyOf||e.oneOf||e.allOf;return Array.isArray(t)?t.some(r=>r&&typeof r=="object"&&r.type==="array"):false}function Qf(e){let t={};for(let n in e){let o={expression:e[n].expression};t[n]=o;}return {computations:t}}function wu(e){let t=parseFloat(e);return isNaN(t)?[...e].every(r=>/\w|\.|\*/.test(r))&&!e.includes("..")&&!e.endsWith("."):false}function qy(e,t,r){let n=e.split(".");if(!n.includes("*")){let o=n.length>1?n.slice(0,-1).join("."):null;if(o){let a=zy(o,t,r);if(a&&a!=="object")throw new Error(`Cannot add field to non-object parent at '${o}' (type: ${a})`)}}}var es=class{constructor(t){this.position=0;this.current="";this.input=t.trim(),this.current=this.input[0]||"";}advance(){this.position++,this.current=this.position<this.input.length?this.input[this.position]:"";}peek(t=1){let r=this.position+t;return r<this.input.length?this.input[r]:""}skipWhitespace(){for(;this.current&&/\s/.test(this.current);)this.advance();}readNumber(){let t=this.position,r="";for(;this.current&&/[0-9.]/.test(this.current);)r+=this.current,this.advance();return {type:"NUMBER",value:r,position:t}}readString(t){let r=this.position,n="";for(this.advance();this.current&&this.current!==t;)this.current==="\\"?(this.advance(),this.current&&(n+=this.current,this.advance())):(n+=this.current,this.advance());return this.current===t&&this.advance(),{type:"STRING",value:n,position:r}}readIdentifier(){let t=this.position,r="";for(;this.current&&/[a-zA-Z0-9_.*]/.test(this.current);)r+=this.current,this.advance();let n=r.toLowerCase();if(n==="true"||n==="false")return {type:"BOOLEAN",value:n,position:t};if(n==="null")return {type:"NULL",value:n,position:t};if(this.skipWhitespace(),this.current==="("){let o=r.toUpperCase();if(["SUM","AVERAGE","MIN","MAX","COUNT","LOOKUP","MATCH","FILTER","FLATTEN","CONCAT","ABS","SQRT","LOG","POW","EQ","AND","OR","IF","NOT","GT","GTE","LT","LTE"].includes(o))return {type:"FUNCTION",value:o,position:t}}return {type:"IDENTIFIER",value:r,position:t}}tokenize(){let t=[];for(;this.position<this.input.length&&(this.skipWhitespace(),!!this.current);){if(/[0-9]/.test(this.current)){t.push(this.readNumber());continue}if(this.current==='"'||this.current==="'"){t.push(this.readString(this.current));continue}if(/[a-zA-Z_]/.test(this.current)){t.push(this.readIdentifier());continue}let r=this.current,n=this.position;if(r==="<"||r===">"){this.advance(),this.current==="="?(this.advance(),r==="<"?t.push({type:"LTE",value:"<=",position:n}):t.push({type:"GTE",value:">=",position:n})):r==="<"?t.push({type:"LT",value:"<",position:n}):t.push({type:"GT",value:">",position:n});continue}if(r==="="){this.advance(),this.current==="="?(this.advance(),t.push({type:"EQ",value:"==",position:n})):t.push({type:"EQ",value:"=",position:n});continue}switch(this.advance(),r){case "+":t.push({type:"PLUS",value:"+",position:n});break;case "-":t.push({type:"MINUS",value:"-",position:n});break;case "*":t.push({type:"MULTIPLY",value:"*",position:n});break;case "/":t.push({type:"DIVIDE",value:"/",position:n});break;case "!":t.push({type:"NOT",value:"!",position:n});break;case "(":t.push({type:"LPAREN",value:"(",position:n});break;case ")":t.push({type:"RPAREN",value:")",position:n});break;case ",":t.push({type:"COMMA",value:",",position:n});break;default:throw new Error(`Unexpected character '${r}' at position ${n}`)}}return t.push({type:"EOF",value:"",position:this.position}),t}};var Yf=class{constructor(t){this.position=0;this.tokens=t,this.current=t[0];}advance(){this.position++,this.current=this.position<this.tokens.length?this.tokens[this.position]:this.tokens[this.tokens.length-1];}expect(t){if(this.current.type!==t)throw new Error(`Expected ${t} but got ${this.current.type} at position ${this.current.position}`);let r=this.current;return this.advance(),r}parseUnary(){if(this.current.type==="PLUS"||this.current.type==="MINUS"||this.current.type==="NOT"){let t;this.current.type==="MINUS"?t="-":this.current.type==="PLUS"?t="+":t="!",this.advance();let r=this.parseUnary();return {type:"UnaryOp",operator:t,operand:r}}return this.parsePrimary()}parsePrimary(){if(this.current.type==="NUMBER"){let t=parseFloat(this.current.value);return this.advance(),{type:"Number",value:t}}if(this.current.type==="STRING"){let t=this.current.value;return this.advance(),{type:"String",value:t}}if(this.current.type==="BOOLEAN"){let t=this.current.value==="true";return this.advance(),{type:"Boolean",value:t}}if(this.current.type==="NULL")return this.advance(),{type:"Null",value:null};if(this.current.type==="FUNCTION")return this.parseFunctionCall();if(this.current.type==="IDENTIFIER"){let t=this.current.value;return this.advance(),{type:"Identifier",name:t}}if(this.current.type==="LPAREN"){this.advance();let t=this.parseExpression();return this.expect("RPAREN"),t}throw new Error(`Unexpected token ${this.current.type} at position ${this.current.position}`)}parseFunctionCall(){let t=this.current.value;this.advance(),this.expect("LPAREN");let r=[];if(this.current.type!=="RPAREN")for(r.push(this.parseExpression());this.current.type==="COMMA";)this.advance(),r.push(this.parseExpression());return this.expect("RPAREN"),{type:"FunctionCall",name:t,args:r}}parseMultiplicative(){let t=this.parseUnary();for(;this.current.type==="MULTIPLY"||this.current.type==="DIVIDE";){let r=this.current.type==="MULTIPLY"?"*":"/";this.advance();let n=this.parseUnary();t={type:"BinaryOp",operator:r,left:t,right:n};}return t}parseAdditive(){let t=this.parseMultiplicative();for(;this.current.type==="PLUS"||this.current.type==="MINUS";){let r=this.current.type==="PLUS"?"+":"-";this.advance();let n=this.parseMultiplicative();t={type:"BinaryOp",operator:r,left:t,right:n};}return t}parseComparison(){let t=this.parseAdditive();for(;this.current.type==="GT"||this.current.type==="GTE"||this.current.type==="LT"||this.current.type==="LTE"||this.current.type==="EQ";){let r;switch(this.current.type){case "GT":r=">";break;case "GTE":r=">=";break;case "LT":r="<";break;case "LTE":r="<=";break;case "EQ":r=this.current.value;break;default:throw new Error(`Unexpected comparison operator ${this.current.type}`)}this.advance();let n=this.parseAdditive();t={type:"BinaryOp",operator:r,left:t,right:n};}return t}parseExpression(){return this.parseComparison()}parse(){let t=this.parseExpression();return this.expect("EOF"),t}};function ti(e){let r=new es(e).tokenize();return new Yf(r).parse()}function yl(e){try{switch(e.type){case "Number":return {value:e.value,literal:!0};case "String":return {value:e.value,literal:!0};case "Boolean":return {value:e.value,literal:!0};case "Null":return {value:e.value,literal:!0};case "Identifier":return {value:null,path:e.name};case "BinaryOp":{let t=e,r=yl(t.left),n=yl(t.right);if(r===null||n===null)return null;let o;switch(t.operator){case "+":o="$add";break;case "-":o="$subtract";break;case "*":o="$multiply";break;case "/":o="$divide";break;case ">":o="$gt";break;case ">=":o="$gte";break;case "<":o="$lt";break;case "<=":o="$lte";break;case "=":case "==":o="$eq";break;default:return null}return {value:null,operation:o,operands:[r,n]}}case "UnaryOp":{let t=e,r=yl(t.operand);if(r===null)return null;if(t.operator==="+")return r;if(t.operator==="-"){let n={value:0,literal:!0};return {value:null,operation:"$subtract",operands:[n,r]}}else return {value:null,operation:"$not",operands:[r]}}case "FunctionCall":{let t=e,r=t.args.map(o=>yl(o));if(r.some(o=>o===null))return null;let n;switch(t.name){case "SUM":n="$sum";break;case "AVERAGE":n="$average";break;case "MIN":n="$min";break;case "MAX":n="$max";break;case "COUNT":n="$count";break;case "LOOKUP":n="$lookup";break;case "MATCH":n="$match";break;case "FILTER":n="$filter";break;case "FLATTEN":n="$flatten";break;case "CONCAT":n="$concat";break;case "ABS":n="$abs";break;case "SQRT":n="$sqrt";break;case "LOG":n="$log";break;case "POW":n="$pow";break;case "EQ":n="$eq";break;case "AND":n="$and";break;case "OR":n="$or";break;case "IF":n="$if";break;case "NOT":n="$not";break;case "GT":n="$gt";break;case "GTE":n="$gte";break;case "LT":n="$lt";break;case "LTE":n="$lte";break;default:return null}return {value:null,operation:n,operands:r}}default:return null}}catch{return null}}function Tn(e){try{let t=ti(e);return yl(t)}catch{return null}}function hS(e){let t=[];if(!e||e.trim()==="")return t.push("Expression cannot be empty"),{isValid:false,errors:t};try{return ti(e),{isValid:!0,errors:[]}}catch(r){return r instanceof Error?t.push(r.message):t.push("Unknown syntax error"),{isValid:false,errors:t}}}function Hy(e,t,r){let n=[],o=[],a=hS(e);if(!a.isValid)return a;let i;try{i=ti(e);}catch(s){return n.push(s instanceof Error?s.message:"Parse error"),{isValid:false,errors:n,warnings:o}}if(t){let s=_u(i);for(let l of s)if(!l.startsWith("__temp_")&&!(r&&r.has(l)))try{Yi(l,t,r||new Set);}catch{n.push(`Path '${l}' does not exist in schema`);}}return {isValid:n.length===0,errors:n,warnings:o}}function _u(e){let t=[];switch(e.type){case "Identifier":t.push(e.name);break;case "BinaryOp":t.push(..._u(e.left)),t.push(..._u(e.right));break;case "UnaryOp":t.push(..._u(e.operand));break;case "FunctionCall":let r=e.name;for(let n=0;n<e.args.length;n++){let o=e.args[n],a=false;r==="SUM"||r==="AVERAGE"||r==="MIN"||r==="MAX"||r==="FLATTEN"?a=n===1:r==="LOOKUP"?a=n===1||n===2||n===4||n===5:(r==="MATCH"||r==="FILTER")&&(a=n===1||n===2||r==="MATCH"&&n===4),a||t.push(..._u(o));}break}return t}function Jy(e){try{let t=ti(e);return ep(t)}catch{return []}}function ep(e){let t=[];if(!e)return t;switch(e.type){case "Identifier":t.push(e.name);break;case "BinaryOp":t.push(...ep(e.left)),t.push(...ep(e.right));break;case "FunctionCall":for(let r of e.args||[])t.push(...ep(r));break}return t.filter(r=>wu(r))}function ri(e){let t={},r={};for(let a in e)t[a]=0,r[a]=[];for(let a in e){let i=Jy(e[a].expression);for(let s of i)s in e&&(r[s].push(a),t[a]++);}let n=[];for(let a in t)t[a]===0&&n.push(a);let o=[];for(;n.length>0;){let a=n.shift();o.push(a);for(let i of r[a])t[i]--,t[i]===0&&n.push(i);}if(o.length!==Object.keys(e).length)throw new Error("Cycle detected in computation dependencies");return o}function Su(e){let t={},r={},n={};for(let s in e)t[s]={dependencies:[],dependents:[],depth:0},r[s]=[],n[s]=[];for(let s in e){let l=Jy(e[s].expression);for(let c of l)c in e&&(r[s].push(c),n[c].push(s));}for(let s in e)t[s].dependencies=r[s],t[s].dependents=n[s];let o={};for(let s in e)o[s]=r[s].length;let a=[];for(let s in o)o[s]===0&&a.push(s);let i={};for(let s in e)i[s]=0;for(;a.length>0;){let s=a.shift();for(let l of n[s])i[l]=Math.max(i[l],i[s]+1),o[l]--,o[l]===0&&a.push(l);}if(Object.values(o).some(s=>s>0))throw new Error("Cycle detected in computation dependencies");for(let s in t)t[s].depth=i[s];return t}function Wy(e,t,r){if(!e[t])throw new Error(`Cannot rename computation: Field '${t}' does not exist in the current computation spec`);if(t===r)return {affectedComputations:[],updatedSpec:e};if(e[r])throw new Error(`Cannot rename to '${r}': A computed field with this name already exists`);let n=[],o={};Su(e)[t]?.dependents||[];for(let s in e){let l=e[s];if(s===t)o[r]={...l},n.push(t);else {let c=l.expression;if(Jy(l.expression).includes(t)){let d=new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"g");c=c.replace(d,r),n.push(s);}o[s]={expression:c};}}return {affectedComputations:[...new Set(n)],updatedSpec:o}}function vS(e){if(!e)return [];let t=[];if(e.path&&!e.operation)return t.push(e.path),t;if(e.operation&&e.operands){let r=e.operation;for(let n=0;n<e.operands.length;n++){let o=e.operands[n],a=false;r==="$sum"||r==="$average"||r==="$min"||r==="$max"||r==="$flatten"?a=n===1:r==="$lookup"?a=n===1||n===2||n===4||n===5:(r==="$match"||r==="$filter")&&(a=n===1||n===2||r==="$match"&&n===4),a||t.push(...vS(o));}}return t}function Ky(e,t){let r;t.computations?r=t:r=Qf(t);let n;try{n=ri(r.computations);}catch(a){let i=a instanceof Error?a.message:String(a);throw console.error(`[compileSpec] Failed to compute execution order: ${i}`),a}let o=new Set;for(let a of n){let i=r.computations[a];try{qy(a,e,o);}catch(s){let l=s instanceof Error?s.message:String(s);throw console.error(`[compileSpec] Target path validation failed for '${a}': ${l}`),s}try{let s=Tn(i.expression),l=vS(s);for(let c of l)if(!c.startsWith("__temp_")&&!o.has(c)&&!Zf(c,e,o))throw new Error(`Operand path '${c}' does not exist in schema for target '${a}'`)}catch(s){let l=s instanceof Error?s.message:String(s);throw console.error(`[compileSpec] Validation failed for '${a}' (expression: ${i.expression}): ${l}`),s}o.add(a);}return r}function bS(e,t){let r=e,n=e;for(let o of t)if(o==="*"){r.type!=="array"&&(r.type="array"),(!r.items||typeof r.items!="object")&&(r.items={});let a=r.items;if(a.$ref){let i=a.$ref;if(i.startsWith("#/$defs/")){let s=i.substring(8);n.$defs&&n.$defs[s]?r=n.$defs[s]:r=a;}else r=a;}else r=a;}else {r.type!=="object"&&(r.type="object"),(!r.properties||typeof r.properties!="object")&&(r.properties={});let a=r.properties;if((!(o in a)||typeof a[o]!="object")&&(a[o]={}),r=a[o],r.$ref){let i=r.$ref;if(i.startsWith("#/$defs/")){let s=i.substring(8);n.$defs&&n.$defs[s]&&(r=n.$defs[s]);}}}return r}function Gy(e,t){let r=Ky(e,t),n=ri(r.computations),o=JSON.parse(JSON.stringify(e));for(let a of n){let i=r.computations[a],s=a.split("."),l;if(s.includes("*")){let d=s.lastIndexOf("*");l=[...s.slice(0,d+1),...s.slice(d+1,-1)];}else l=s.slice(0,-1);let c=s[s.length-1],u=bS(o,l);if(u.type!=="object"&&(u.type="object"),(!u.properties||typeof u.properties!="object")&&(u.properties={}),!(c in u.properties)){let d=Tn(i.expression);if(!d){u.properties[c]={type:"string","X-ComputedField":true};continue}let m=xu(d);if(m){let h;d.operands&&(h=d.operands.map(p=>{if(p.literal){let f=p.value;return typeof f=="string"?{type:"string"}:typeof f=="boolean"?{type:"boolean"}:typeof f=="number"?Number.isInteger(f)?{type:"integer"}:{type:"number"}:{type:"string"}}return {}}));let y=Xf({operation:m},h);!y.type&&Object.keys(y).length===0&&(y.type="string"),u.properties[c]={...y,"X-ComputedField":true};}}}return o}function n3({projectId:e,authConfig:t,extractionsConfig:r={},jsonSchemaConfig:n={},children:o}){return e?jsx(Kx,{config:t,children:jsx(nw,{children:jsx(sw,{projectId:e,children:jsx(o3,{config:n,children:jsx(fS,{originId:e,initialLimit:r.initialLimit??50,initialOrder:r.initialOrder??"desc",initialHumanStatus:r.initialHumanStatus??"review_required",mode:r.mode??"full",children:o})})})})}):jsx("div",{className:"flex items-center justify-center h-screen",children:jsxs("div",{className:"text-center",children:[jsx("h2",{className:"text-2xl font-semibold text-gray-700",children:"Invalid Project ID"}),jsx("p",{className:"text-gray-500 mt-2",children:"No project ID was provided."})]})})}function o3({config:e,children:t}){let{project:r}=Qr(),n=useMemo(()=>{let a=r.published_config.json_schema;return e.includeComputedFields??true?(()=>{try{let s=a;return s=Gy(s,r.published_config.computation_spec),s}catch(s){return console.warn("Skipping computed fields in schema due to error:",s instanceof Error?s.message:s),a}})():a},[r.published_config.json_schema,r.published_config.computation_spec,e.includeComputedFields]),o=useCallback(async a=>{e.enableSchemaUpdates&&e.persistJsonSchemaCallback?await e.persistJsonSchemaCallback(a):e.enableSchemaUpdates?console.warn("Schema updates are enabled but no persistJsonSchemaCallback was provided. Updates will not be persisted."):console.log("Schema update requested but updates are disabled (read-only mode):",a);},[e.enableSchemaUpdates,e.persistJsonSchemaCallback]);return jsx(nS,{computedSchema:n,jsonSchema:r.published_config.json_schema,persistJsonSchemaCallback:o,children:t})}function nt({className:e,type:t,...r}){return jsx("input",{type:t,"data-slot":"input",className:T("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",e),...r})}function xS({className:e,...t}){return jsx("textarea",{"data-slot":"input",className:T(e),...t})}function Yt({className:e,...t}){return jsx(_S.Root,{"data-slot":"label",className:T("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}var vl=FormProvider,SS=kt.createContext({}),ao=({...e})=>jsx(SS.Provider,{value:{name:e.name},children:jsx(Controller,{...e})}),Zy=()=>{let e=kt.useContext(SS),t=kt.useContext(NS),{getFieldState:r}=useFormContext(),n=useFormState({name:e.name}),o=r(e.name,n);if(!e)throw new Error("useFormField should be used within <FormField>");let{id:a}=t;return {id:a,name:e.name,formItemId:`${a}-form-item`,formDescriptionId:`${a}-form-item-description`,formMessageId:`${a}-form-item-message`,...o}},NS=kt.createContext({});function kn({className:e,...t}){let r=kt.useId();return jsx(NS.Provider,{value:{id:r},children:jsx("div",{"data-slot":"form-item",className:T("grid gap-2",e),...t})})}function oi({className:e,...t}){let{error:r,formItemId:n}=Zy();return jsx(Yt,{"data-slot":"form-label","data-error":!!r,className:T("data-[error=true]:text-destructive",e),htmlFor:n,...t})}function Rn({...e}){let{error:t,formItemId:r,formDescriptionId:n,formMessageId:o}=Zy();return jsx(Slot,{"data-slot":"form-control",id:r,"aria-describedby":t?`${n} ${o}`:`${n}`,"aria-invalid":!!t,...e})}function Nu({className:e,...t}){let{error:r,formMessageId:n}=Zy(),o=r?String(r?.message??""):t.children;return o?jsx("p",{"data-slot":"form-message",id:n,className:T("text-destructive text-sm",e),...t,children:o}):null}function bl({className:e,...t}){return jsx(tp.Root,{"data-slot":"checkbox",className:T("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:jsx(tp.Indicator,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:jsx(CheckIcon,{className:"size-3.5"})})})}function rp({...e}){return jsx(Nt.Root,{"data-slot":"select",...e})}function np({...e}){return jsx(Nt.Value,{"data-slot":"select-value",...e})}function op({className:e,size:t="default",children:r,...n}){return jsxs(Nt.Trigger,{"data-slot":"select-trigger","data-size":t,className:T("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[r,jsx(Nt.Icon,{asChild:true,children:jsx(ChevronDownIcon,{className:"size-4 opacity-50"})})]})}function ap({className:e,children:t,position:r="popper",...n}){return jsx(Nt.Portal,{children:jsxs(Nt.Content,{"data-slot":"select-content",className:T("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:r,...n,children:[jsx(h3,{}),jsx(Nt.Viewport,{className:T("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),jsx(g3,{})]})})}function rs({className:e,children:t,...r}){return jsxs(Nt.Item,{"data-slot":"select-item",className:T("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...r,children:[jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:jsx(Nt.ItemIndicator,{children:jsx(CheckIcon,{className:"size-4"})})}),jsx(Nt.ItemText,{children:t})]})}function h3({className:e,...t}){return jsx(Nt.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:T("flex cursor-default items-center justify-center py-1",e),...t,children:jsx(ChevronUpIcon,{className:"size-4"})})}function g3({className:e,...t}){return jsx(Nt.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:T("flex cursor-default items-center justify-center py-1",e),...t,children:jsx(ChevronDownIcon,{className:"size-4"})})}function Cu({...e}){return jsx(Bo.Root,{"data-slot":"accordion",...e})}function Eu({className:e,...t}){return jsx(Bo.Item,{"data-slot":"accordion-item",className:T("border-b last:border-b-0",e),...t})}function Pu({className:e,children:t,hideChevron:r,...n}){return jsx(Bo.Header,{className:"flex",children:jsxs(Bo.Trigger,{"data-slot":"accordion-trigger",className:T("focus-visible:border-ring group focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,jsx(ChevronDownIcon,{className:T("text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200 ",r&&"opacity-0 group-hover:opacity-100 transition-opacity duration-200")})]})})}function Tu({className:e,children:t,...r}){return jsx(Bo.Content,{"data-slot":"accordion-content",className:"data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm",...r,children:jsx("div",{className:T("pt-0 pb-4",e),children:t})})}function io({delayDuration:e=0,...t}){return jsx(On.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Xe({...e}){return jsx(io,{children:jsx(On.Root,{"data-slot":"tooltip",...e})})}function Qe({...e}){return jsx(On.Trigger,{"data-slot":"tooltip-trigger",...e})}function et({className:e,sideOffset:t=0,children:r,...n}){return jsx(On.Portal,{children:jsxs(On.Content,{"data-slot":"tooltip-content",sideOffset:t,className:T("bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...n,children:[r,jsx(On.Arrow,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function Re({className:e,...t}){return jsx("div",{"data-slot":"skeleton",className:T("bg-accent animate-pulse rounded-md",e),...t})}function ns({className:e,classNames:t,showOutsideDays:r=true,captionLayout:n="label",buttonVariant:o="ghost",formatters:a,components:i,...s}){let l=getDefaultClassNames();return jsx(DayPicker,{showOutsideDays:r,className:T("bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,e),captionLayout:n,formatters:{formatMonthDropdown:c=>c.toLocaleString("default",{month:"short"}),...a},classNames:{root:T("w-fit",l.root),months:T("flex gap-4 flex-col md:flex-row relative",l.months),month:T("flex flex-col w-full gap-4",l.month),nav:T("flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",l.nav),button_previous:T(zi({variant:o}),"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",l.button_previous),button_next:T(zi({variant:o}),"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",l.button_next),month_caption:T("flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",l.month_caption),dropdowns:T("w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",l.dropdowns),dropdown_root:T("relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",l.dropdown_root),dropdown:T("absolute inset-0 opacity-0",l.dropdown),caption_label:T("select-none font-medium",n==="label"?"text-sm":"rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",l.caption_label),table:"w-full border-collapse",weekdays:T("flex",l.weekdays),weekday:T("text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",l.weekday),week:T("flex w-full mt-2",l.week),week_number_header:T("select-none w-(--cell-size)",l.week_number_header),week_number:T("text-[0.8rem] select-none text-muted-foreground",l.week_number),day:T("relative w-full h-full p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",l.day),range_start:T("rounded-l-md bg-accent",l.range_start),range_middle:T("rounded-none",l.range_middle),range_end:T("rounded-r-md bg-accent",l.range_end),today:T("bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",l.today),outside:T("text-muted-foreground aria-selected:text-muted-foreground",l.outside),disabled:T("text-muted-foreground opacity-50",l.disabled),hidden:T("invisible",l.hidden),...t},components:{Root:({className:c,rootRef:u,...d})=>jsx("div",{"data-slot":"calendar",ref:u,className:T(c),...d}),Chevron:({className:c,orientation:u,...d})=>u==="left"?jsx(ChevronLeftIcon,{className:T("size-4",c),...d}):u==="right"?jsx(ChevronRightIcon,{className:T("size-4",c),...d}):jsx(ChevronDownIcon,{className:T("size-4",c),...d}),DayButton:C3,WeekNumber:({children:c,...u})=>jsx("td",{...u,children:jsx("div",{className:"flex size-(--cell-size) items-center justify-center text-center",children:c})}),...i},...s})}function C3({className:e,day:t,modifiers:r,...n}){let o=getDefaultClassNames(),a=kt.useRef(null);return kt.useEffect(()=>{r.focused&&a.current?.focus();},[r.focused]),jsx(V,{ref:a,variant:"ghost",size:"icon","data-day":t.date.toLocaleDateString(),"data-selected-single":r.selected&&!r.range_start&&!r.range_end&&!r.range_middle,"data-range-start":r.range_start,"data-range-end":r.range_end,"data-range-middle":r.range_middle,className:T("data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",o.day,e),...n})}function nr({...e}){return jsx(pa.Root,{"data-slot":"popover",...e})}function or({...e}){return jsx(pa.Trigger,{"data-slot":"popover-trigger",...e})}function ar({className:e,align:t="center",sideOffset:r=4,...n}){return jsx(pa.Portal,{children:jsx(pa.Content,{"data-slot":"popover-content",align:t,sideOffset:r,className:T("rounded-xl shadow-[0_1px_2px_rgba(25,28,33,.06),0_0_2px_theme(colors.gray.black/.08)] bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) border shadow-md outline-hidden",e),...n})})}function nn({className:e,...t}){return jsx("textarea",{"data-slot":"textarea",className:T("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}var TS={retab_rdylbu:[{pos:0,color:[250,110,110]},{pos:.5,color:[250,195,0]},{pos:1,color:[80,100,240]}],retab_rdylgn:[{pos:0,color:[250,110,110]},{pos:.5,color:[250,195,0]},{pos:1,color:[80,240,135]}],Reds:[{pos:0,color:[255,245,240]},{pos:.1,color:[254,229,216]},{pos:.2,color:[253,202,181]},{pos:.3,color:[252,171,143]},{pos:.4,color:[252,138,106]},{pos:.5,color:[251,105,74]},{pos:.6,color:[241,68,50]},{pos:.7,color:[217,37,35]},{pos:.8,color:[188,20,26]},{pos:.9,color:[152,12,19]},{pos:1,color:[103,0,13]}],hot:[{pos:0,color:[11,0,0]},{pos:.1,color:[76,0,0]},{pos:.2,color:[144,0,0]},{pos:.3,color:[210,0,0]},{pos:.4,color:[255,23,0]},{pos:.5,color:[255,92,0]},{pos:.6,color:[255,157,0]},{pos:.7,color:[255,225,0]},{pos:.8,color:[255,255,54]},{pos:.9,color:[255,255,157]},{pos:1,color:[255,255,255]}],afmhot:[{pos:0,color:[0,0,0]},{pos:.1,color:[50,0,0]},{pos:.2,color:[102,0,0]},{pos:.3,color:[152,24,0]},{pos:.4,color:[204,77,0]},{pos:.5,color:[255,128,1]},{pos:.6,color:[255,178,51]},{pos:.7,color:[255,230,103]},{pos:.8,color:[255,255,153]},{pos:.9,color:[255,255,205]},{pos:1,color:[255,255,255]}],gist_heat:[{pos:0,color:[0,0,0]},{pos:.1,color:[38,0,0]},{pos:.2,color:[77,0,0]},{pos:.3,color:[114,0,0]},{pos:.4,color:[153,0,0]},{pos:.5,color:[192,1,0]},{pos:.6,color:[229,51,0]},{pos:.7,color:[255,103,0]},{pos:.8,color:[255,153,51]},{pos:.9,color:[255,205,155]},{pos:1,color:[255,255,255]}],YlOrRd:[{pos:0,color:[255,255,204]},{pos:.1,color:[255,241,169]},{pos:.2,color:[254,225,135]},{pos:.3,color:[254,202,102]},{pos:.4,color:[254,171,73]},{pos:.5,color:[253,140,60]},{pos:.6,color:[252,91,46]},{pos:.7,color:[237,46,33]},{pos:.8,color:[212,16,32]},{pos:.9,color:[176,0,38]},{pos:1,color:[128,0,38]}],retab_YlOrRd:[{pos:0,color:[255,255,255]},{pos:.1,color:[255,241,169]},{pos:.2,color:[254,225,135]},{pos:.3,color:[254,202,102]},{pos:.4,color:[254,171,73]},{pos:.5,color:[253,140,60]},{pos:.6,color:[252,91,46]},{pos:.7,color:[237,46,33]},{pos:.8,color:[212,16,32]},{pos:.9,color:[176,0,38]},{pos:1,color:[128,0,38]}],OrRd:[{pos:0,color:[255,247,236]},{pos:.1,color:[254,235,208]},{pos:.2,color:[253,220,175]},{pos:.3,color:[253,202,148]},{pos:.4,color:[253,178,123]},{pos:.5,color:[252,140,89]},{pos:.6,color:[242,109,75]},{pos:.7,color:[224,68,47]},{pos:.8,color:[201,29,19]},{pos:.9,color:[168,0,0]},{pos:1,color:[127,0,0]}],bone:[{pos:0,color:[0,0,0]},{pos:.1,color:[22,22,30]},{pos:.2,color:[45,45,62]},{pos:.3,color:[66,66,93]},{pos:.4,color:[89,92,121]},{pos:.5,color:[112,123,144]},{pos:.6,color:[134,154,166]},{pos:.7,color:[157,185,188]},{pos:.8,color:[185,210,210]},{pos:.9,color:[221,233,233]},{pos:1,color:[255,255,255]}],RdBu:[{pos:0,color:[165,0,38]},{pos:.2,color:[215,48,39]},{pos:.4,color:[244,109,67]},{pos:.5,color:[253,174,97]},{pos:.6,color:[254,224,144]},{pos:.8,color:[171,217,233]},{pos:1,color:[49,54,149]}],RdGn:[{pos:0,color:[165,0,38]},{pos:.2,color:[215,48,39]},{pos:.4,color:[244,109,67]},{pos:.5,color:[253,174,97]},{pos:.6,color:[254,224,144]},{pos:.8,color:[166,217,106]},{pos:1,color:[26,152,80]}],jet:[{pos:0,color:[0,0,128]},{pos:.1,color:[0,0,241]},{pos:.2,color:[0,76,255]},{pos:.3,color:[0,176,255]},{pos:.4,color:[41,255,206]},{pos:.5,color:[125,255,122]},{pos:.6,color:[206,255,41]},{pos:.7,color:[255,196,0]},{pos:.8,color:[255,104,0]},{pos:.9,color:[241,8,0]},{pos:1,color:[128,0,0]}],pink:[{pos:0,color:[30,0,0]},{pos:.1,color:[104,65,65]},{pos:.2,color:[145,93,93]},{pos:.3,color:[175,114,114]},{pos:.4,color:[198,139,132]},{pos:.5,color:[208,172,148]},{pos:.6,color:[218,198,161]},{pos:.7,color:[228,223,174]},{pos:.8,color:[237,237,198]},{pos:.9,color:[247,247,229]},{pos:1,color:[255,255,255]}],coolwarm:[{pos:0,color:[59,76,192]},{pos:.25,color:[141,176,254]},{pos:.5,color:[221,220,220]},{pos:.75,color:[244,152,122]},{pos:1,color:[180,4,38]}],summer:[{pos:0,color:[0,128,102]},{pos:.25,color:[64,159,102]},{pos:.5,color:[128,191,102]},{pos:.75,color:[191,223,102]},{pos:1,color:[255,255,102]}],wistia:[{pos:0,color:[0,0,0]},{pos:.25,color:[128,92,28]},{pos:.5,color:[255,192,64]},{pos:.75,color:[255,224,128]},{pos:1,color:[255,255,191]}],RdYlBu:[{pos:0,color:[165,0,38]},{pos:.2,color:[215,48,39]},{pos:.4,color:[244,109,67]},{pos:.5,color:[253,174,97]},{pos:.6,color:[254,224,144]},{pos:.8,color:[171,217,233]},{pos:1,color:[49,54,149]}],RdYlGn:[{pos:0,color:[165,0,38]},{pos:.2,color:[215,48,39]},{pos:.4,color:[244,109,67]},{pos:.5,color:[253,174,97]},{pos:.6,color:[254,224,139]},{pos:.8,color:[166,217,106]},{pos:1,color:[26,152,80]}]},kS=(e,t=0,r=1)=>Math.min(Math.max(e,t),r),Yy=(e,t,r)=>e+(t-e)*r,RS=(e,t,r)=>[Math.round(Yy(e[0],t[0],r)),Math.round(Yy(e[1],t[1],r)),Math.round(Yy(e[2],t[2],r))],OS=([e,t,r])=>"#"+[e,t,r].map(n=>n.toString(16).padStart(2,"0")).join("").toUpperCase();function DS(e,t,r=false,n){let o=TS[e],a=kS(t);r&&(a=1-a);let i;for(let s=0;s<o.length-1;s++){let l=o[s],c=o[s+1];if(a>=l.pos&&a<=c.pos){let u=(a-l.pos)/(c.pos-l.pos);i=RS(l.color,c.color,u);break}}if(i||(i=o[o.length-1].color),n!==void 0){let s=Math.min(Math.max(n,0),1),l=[255,255,255];i=[Math.round(i[0]*s+l[0]*(1-s)),Math.round(i[1]*s+l[1]*(1-s)),Math.round(i[2]*s+l[2]*(1-s))];}return OS(i)}var PS={};function ku(e,t,r=false,n){let o=`${e}|${r?"1":"0"}`,a=PS[o];if(!a){let c=TS[e];a=new Array(11);for(let u=0;u<=10;u++){let d=u/10,m=Math.round(d*10)/10;r&&(m=1-m);let h=c[c.length-1].color;for(let y=0;y<c.length-1;y++){let p=c[y],f=c[y+1];if(m>=p.pos&&m<=f.pos){let x=(m-p.pos)/(f.pos-p.pos);h=RS(p.color,f.color,x);break}}a[u]=h;}PS[o]=a;}let i=kS(t),s=Math.max(0,Math.min(10,Math.floor(i*10))),l=a[s];{let c=Math.min(Math.max(n,0),1),u=[255,255,255];l=[Math.round(l[0]*c+u[0]*(1-c)),Math.round(l[1]*c+u[1]*(1-c)),Math.round(l[2]*c+u[2]*(1-c))];}return OS(l)}var Ru="retab_rdylgn",Ou="retab_YlOrRd",Du=true,Au=false,e0=.2,t0=.2;var P3=[{pattern:/(\d{1,2})\s+(\d{1,2})\s+(\d{4})/,dayIndex:1,monthIndex:2,yearIndex:3},{pattern:/(\d{1,2})\/(\d{1,2})\/(\d{4})/,dayIndex:1,monthIndex:2,yearIndex:3},{pattern:/(\d{1,2})-(\d{1,2})-(\d{4})/,dayIndex:1,monthIndex:2,yearIndex:3},{pattern:/(\d{1,2})\.(\d{1,2})\.(\d{4})/,dayIndex:1,monthIndex:2,yearIndex:3},{pattern:/(\d{4})-(\d{1,2})-(\d{1,2})/,yearIndex:1,monthIndex:2,dayIndex:3}],T3=/(\d{1,2}):(\d{1,2})(:(\d{1,2}))?(\s*(AM|PM))?/i,k3=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{3})?Z?$/,R3=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})Z?$/,O3=/^(\d{4})-(\d{2})-(\d{2})$/;function D3(e){if(typeof e!="string")return null;let t={},r=e.trim();if(!r)return null;let n=r.match(k3);if(n)return t.year=parseInt(n[1],10),t.month=parseInt(n[2],10)-1,t.day=parseInt(n[3],10),t.hours=parseInt(n[4],10),t.minutes=parseInt(n[5],10),t.seconds=parseInt(n[6],10),t;let o=r.match(R3);if(o)return t.year=parseInt(o[1],10),t.month=parseInt(o[2],10)-1,t.day=parseInt(o[3],10),t.hours=parseInt(o[4],10),t.minutes=parseInt(o[5],10),t;let a=r.match(O3);if(a)return t.year=parseInt(a[1],10),t.month=parseInt(a[2],10)-1,t.day=parseInt(a[3],10),t;let i=new Date(r);if(!isNaN(i.getTime()))return t.year=i.getFullYear(),t.month=i.getMonth(),t.day=i.getDate(),t.hours=i.getHours(),t.minutes=i.getMinutes(),t.seconds=i.getSeconds(),t;for(let l of P3){let c=r.match(l.pattern);if(c){t.year=parseInt(c[l.yearIndex],10),t.month=parseInt(c[l.monthIndex],10)-1,t.day=parseInt(c[l.dayIndex],10),r=r.slice(c[0].length).trim();break}}let s=r.match(T3);if(s){let l=parseInt(s[1],10),c=parseInt(s[2],10),u=s[4]?parseInt(s[4],10):void 0,d=s[6]?s[6].toUpperCase():null;if(d){d==="PM"&&l!==12?l+=12:d==="AM"&&l===12&&(l=0);}t.hours=l,t.minutes=c,u!==void 0&&(t.seconds=u);}return t.year===void 0&&t.month===void 0&&t.day===void 0&&t.hours===void 0&&t.minutes===void 0&&t.seconds===void 0?null:t}function zo(e,t){let r=D3(e);if(!r)return "";let n=d=>d!==void 0?String(d).padStart(2,"0"):"00",o=r.year!==void 0?String(r.year).padStart(4,"0"):"0000",a=n((r.month??0)+1),i=n(r.day??1),s=n(r.hours??0),l=n(r.minutes??0),c=n(r.seconds??0),u;return t.includes("T")?u=`${o}-${a}-${i}T${s}:${l}`:t.includes("-")?u=`${o}-${a}-${i}`:t.includes(":")?r.seconds!==void 0?u=`${s}:${l}:${c}`:u=`${s}:${l}`:u=`${o}-${a}-${i}`,u}function r0(e){return zo(e,"2000-01-01T00:00")||"2000-01-01T00:00"}function n0(e){return zo(e,"00:00")||"00:00"}function o0(e){let t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return `${t}-${r}-${n}`}function Dn(e,t,r=""){if(!e||!t)return e;let n=Dn._SCHEMA_CACHE||new WeakMap;Dn._SCHEMA_CACHE=n;let o=a=>{if(!a||typeof a!="object")return false;if(n.has(a))return n.get(a);let i=false;try{if(a.format&&(a.format==="date"||a.format==="date-time"||a.format==="iso-time"))i=!0;else if(a.type==="object"&&a.properties){for(let s of Object.keys(a.properties))if(o(a.properties[s])){i=!0;break}}else if(a.type==="array"&&a.items)i=o(a.items);else if(a.anyOf||a.oneOf||a.allOf){let s=a.anyOf||a.oneOf||a.allOf;for(let l of s)if(o(l)){i=!0;break}}}finally{n.set(a,i);}return i};if(Array.isArray(e))return !t.items||!o(t.items)?e:e.map((a,i)=>Dn(a,t.items,`${r}[${i}]`));if(typeof e=="object"&&e!==null){let a={...e};return t.properties&&Object.keys(t.properties).forEach(i=>{if(i in a){let s=t.properties[i],l=r?`${r}.${i}`:i;if(s.format&&typeof a[i]=="string"){let c=a[i],u=null;try{switch(s.format){case "date":u=zo(c,"2000-01-01");break;case "iso-time":u=zo(c,"00:00");break;case "date-time":u=zo(c,"2000-01-01T00:00:00");break}u&&u!==c&&(a[i]=u);}catch(d){console.warn(`autoFormatDateTimeFields: Failed to format ${l}:`,d);}}else (s.type==="object"||s.type==="array")&&o(s)&&(a[i]=Dn(a[i],s,l));}}),a}return e}function Uo(e,t,{checkForDefaultPrevented:r=true}={}){return function(o){if(e?.(o),r===false||!o.defaultPrevented)return t?.(o)}}function AS(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t);}function A3(...e){return t=>{let r=false,n=e.map(o=>{let a=AS(o,t);return !r&&typeof a=="function"&&(r=true),a});if(r)return ()=>{for(let o=0;o<n.length;o++){let a=n[o];typeof a=="function"?a():AS(e[o],null);}}}}function so(...e){return kt.useCallback(A3(...e),e)}function FS(e,t){let r=kt.createContext(t),n=a=>{let{children:i,...s}=a,l=kt.useMemo(()=>s,Object.values(s));return jsx(r.Provider,{value:l,children:i})};n.displayName=e+"Provider";function o(a){let i=kt.useContext(r);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${a}\` must be used within \`${e}\``)}return [n,o]}function MS(e,t=[]){let r=[];function n(a,i){let s=kt.createContext(i),l=r.length;r=[...r,i];let c=d=>{let{scope:m,children:h,...y}=d,p=m?.[e]?.[l]||s,f=kt.useMemo(()=>y,Object.values(y));return jsx(p.Provider,{value:f,children:h})};c.displayName=a+"Provider";function u(d,m){let h=m?.[e]?.[l]||s,y=kt.useContext(h);if(y)return y;if(i!==void 0)return i;throw new Error(`\`${d}\` must be used within \`${a}\``)}return [c,u]}let o=()=>{let a=r.map(i=>kt.createContext(i));return function(s){let l=s?.[e]||a;return kt.useMemo(()=>({[`__scope${e}`]:{...s,[e]:l}}),[s,l])}};return o.scopeName=e,[n,$3(o,...t)]}function $3(...e){let t=e[0];if(e.length===1)return t;let r=()=>{let n=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(a){let i=n.reduce((s,{useScope:l,scopeName:c})=>{let d=l(a)[`__scope${c}`];return {...s,...d}},{});return kt.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return r.scopeName=t.scopeName,r}var ma=globalThis?.document?kt.useLayoutEffect:()=>{};var I3=kt[" useId ".trim().toString()]||(()=>{}),F3=0;function lp(e){let[t,r]=kt.useState(I3());return ma(()=>{r(n=>n??String(F3++));},[e]),e||(t?`radix-${t}`:"")}var M3=kt[" useInsertionEffect ".trim().toString()]||ma;function LS({prop:e,defaultProp:t,onChange:r=()=>{},caller:n}){let[o,a,i]=j3({defaultProp:t,onChange:r}),s=e!==void 0,l=s?e:o;{let u=kt.useRef(e!==void 0);kt.useEffect(()=>{let d=u.current;d!==s&&console.warn(`${n} is changing from ${d?"controlled":"uncontrolled"} to ${s?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=s;},[s,n]);}let c=kt.useCallback(u=>{if(s){let d=L3(u)?u(e):u;d!==e&&i.current?.(d);}else a(u);},[s,e,a,i]);return [l,c]}function j3({defaultProp:e,onChange:t}){let[r,n]=kt.useState(e),o=kt.useRef(r),a=kt.useRef(t);return M3(()=>{a.current=t;},[t]),kt.useEffect(()=>{o.current!==r&&(a.current?.(r),o.current=r);},[r,o]),[r,n,a]}function L3(e){return typeof e=="function"}var U3=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],mn=U3.reduce((e,t)=>{let r=createSlot(`Primitive.${t}`),n=kt.forwardRef((o,a)=>{let{asChild:i,...s}=o,l=i?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(l,{...s,ref:a})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function US(e,t){e&&zS.flushSync(()=>e.dispatchEvent(t));}function ii(e){let t=kt.useRef(e);return kt.useEffect(()=>{t.current=e;}),kt.useMemo(()=>(...r)=>t.current?.(...r),[])}function VS(e,t=globalThis?.document){let r=ii(e);kt.useEffect(()=>{let n=o=>{o.key==="Escape"&&r(o);};return t.addEventListener("keydown",n,{capture:true}),()=>t.removeEventListener("keydown",n,{capture:true})},[r,t]);}var q3="DismissableLayer",i0="dismissableLayer.update",V3="dismissableLayer.pointerDownOutside",H3="dismissableLayer.focusOutside",HS,KS=kt.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),s0=kt.forwardRef((e,t)=>{let{disableOutsidePointerEvents:r=false,onEscapeKeyDown:n,onPointerDownOutside:o,onFocusOutside:a,onInteractOutside:i,onDismiss:s,...l}=e,c=kt.useContext(KS),[u,d]=kt.useState(null),m=u?.ownerDocument??globalThis?.document,[,h]=kt.useState({}),y=so(t,_=>d(_)),p=Array.from(c.layers),[f]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),x=p.indexOf(f),g=u?p.indexOf(u):-1,v=c.layersWithOutsidePointerEventsDisabled.size>0,w=g>=x,N=K3(_=>{let P=_.target,R=[...c.branches].some(E=>E.contains(P));!w||R||(o?.(_),i?.(_),_.defaultPrevented||s?.());},m),S=G3(_=>{let P=_.target;[...c.branches].some(E=>E.contains(P))||(a?.(_),i?.(_),_.defaultPrevented||s?.());},m);return VS(_=>{g===c.layers.size-1&&(n?.(_),!_.defaultPrevented&&s&&(_.preventDefault(),s()));},m),kt.useEffect(()=>{if(u)return r&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(HS=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(u)),c.layers.add(u),JS(),()=>{r&&c.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=HS);}},[u,m,r,c]),kt.useEffect(()=>()=>{u&&(c.layers.delete(u),c.layersWithOutsidePointerEventsDisabled.delete(u),JS());},[u,c]),kt.useEffect(()=>{let _=()=>h({});return document.addEventListener(i0,_),()=>document.removeEventListener(i0,_)},[]),jsx(mn.div,{...l,ref:y,style:{pointerEvents:v?w?"auto":"none":void 0,...e.style},onFocusCapture:Uo(e.onFocusCapture,S.onFocusCapture),onBlurCapture:Uo(e.onBlurCapture,S.onBlurCapture),onPointerDownCapture:Uo(e.onPointerDownCapture,N.onPointerDownCapture)})});s0.displayName=q3;var J3="DismissableLayerBranch",W3=kt.forwardRef((e,t)=>{let r=kt.useContext(KS),n=kt.useRef(null),o=so(t,n);return kt.useEffect(()=>{let a=n.current;if(a)return r.branches.add(a),()=>{r.branches.delete(a);}},[r.branches]),jsx(mn.div,{...e,ref:o})});W3.displayName=J3;function K3(e,t=globalThis?.document){let r=ii(e),n=kt.useRef(false),o=kt.useRef(()=>{});return kt.useEffect(()=>{let a=s=>{if(s.target&&!n.current){let c=function(){GS(V3,r,u,{discrete:true});};let u={originalEvent:s};s.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=c,t.addEventListener("click",o.current,{once:true})):c();}else t.removeEventListener("click",o.current);n.current=false;},i=window.setTimeout(()=>{t.addEventListener("pointerdown",a);},0);return ()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",a),t.removeEventListener("click",o.current);}},[t,r]),{onPointerDownCapture:()=>n.current=true}}function G3(e,t=globalThis?.document){let r=ii(e),n=kt.useRef(false);return kt.useEffect(()=>{let o=a=>{a.target&&!n.current&&GS(H3,r,{originalEvent:a},{discrete:false});};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,r]),{onFocusCapture:()=>n.current=true,onBlurCapture:()=>n.current=false}}function JS(){let e=new CustomEvent(i0);document.dispatchEvent(e);}function GS(e,t,r,{discrete:n}){let o=r.originalEvent.target,a=new CustomEvent(e,{bubbles:false,cancelable:true,detail:r});t&&o.addEventListener(e,t,{once:true}),n?US(o,a):o.dispatchEvent(a);}var l0="focusScope.autoFocusOnMount",c0="focusScope.autoFocusOnUnmount",ZS={bubbles:false,cancelable:true},X3="FocusScope",u0=kt.forwardRef((e,t)=>{let{loop:r=false,trapped:n=false,onMountAutoFocus:o,onUnmountAutoFocus:a,...i}=e,[s,l]=kt.useState(null),c=ii(o),u=ii(a),d=kt.useRef(null),m=so(t,p=>l(p)),h=kt.useRef({paused:false,pause(){this.paused=true;},resume(){this.paused=false;}}).current;kt.useEffect(()=>{if(n){let g=function(S){if(h.paused||!s)return;let _=S.target;s.contains(_)?d.current=_:si(d.current,{select:true});},v=function(S){if(h.paused||!s)return;let _=S.relatedTarget;_!==null&&(s.contains(_)||si(d.current,{select:true}));},w=function(S){if(document.activeElement===document.body)for(let P of S)P.removedNodes.length>0&&si(s);};document.addEventListener("focusin",g),document.addEventListener("focusout",v);let N=new MutationObserver(w);return s&&N.observe(s,{childList:true,subtree:true}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",v),N.disconnect();}}},[n,s,h.paused]),kt.useEffect(()=>{if(s){QS.add(h);let p=document.activeElement;if(!s.contains(p)){let x=new CustomEvent(l0,ZS);s.addEventListener(l0,c),s.dispatchEvent(x),x.defaultPrevented||(Q3(nM(eN(s)),{select:true}),document.activeElement===p&&si(s));}return ()=>{s.removeEventListener(l0,c),setTimeout(()=>{let x=new CustomEvent(c0,ZS);s.addEventListener(c0,u),s.dispatchEvent(x),x.defaultPrevented||si(p??document.body,{select:true}),s.removeEventListener(c0,u),QS.remove(h);},0);}}},[s,c,u,h]);let y=kt.useCallback(p=>{if(!r&&!n||h.paused)return;let f=p.key==="Tab"&&!p.altKey&&!p.ctrlKey&&!p.metaKey,x=document.activeElement;if(f&&x){let g=p.currentTarget,[v,w]=Y3(g);v&&w?!p.shiftKey&&x===w?(p.preventDefault(),r&&si(v,{select:true})):p.shiftKey&&x===v&&(p.preventDefault(),r&&si(w,{select:true})):x===g&&p.preventDefault();}},[r,n,h.paused]);return jsx(mn.div,{tabIndex:-1,...i,ref:m,onKeyDown:y})});u0.displayName=X3;function Q3(e,{select:t=false}={}){let r=document.activeElement;for(let n of e)if(si(n,{select:t}),document.activeElement!==r)return}function Y3(e){let t=eN(e),r=XS(t,e),n=XS(t.reverse(),e);return [r,n]}function eN(e){let t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{let o=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||o?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function XS(e,t){for(let r of e)if(!eM(r,{upTo:t}))return r}function eM(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return true;for(;e;){if(t!==void 0&&e===t)return false;if(getComputedStyle(e).display==="none")return true;e=e.parentElement;}return false}function tM(e){return e instanceof HTMLInputElement&&"select"in e}function si(e,{select:t=false}={}){if(e&&e.focus){let r=document.activeElement;e.focus({preventScroll:true}),e!==r&&tM(e)&&t&&e.select();}}var QS=rM();function rM(){let e=[];return {add(t){let r=e[0];t!==r&&r?.pause(),e=YS(e,t),e.unshift(t);},remove(t){e=YS(e,t),e[0]?.resume();}}}function YS(e,t){let r=[...e],n=r.indexOf(t);return n!==-1&&r.splice(n,1),r}function nM(e){return e.filter(t=>t.tagName!=="A")}var iM="Portal",d0=kt.forwardRef((e,t)=>{let{container:r,...n}=e,[o,a]=kt.useState(false);ma(()=>a(true),[]);let i=r||o&&globalThis?.document?.body;return i?zS__default.createPortal(jsx(mn.div,{...n,ref:t}),i):null});d0.displayName=iM;function sM(e,t){return kt.useReducer((r,n)=>t[r][n]??r,e)}var $u=e=>{let{present:t,children:r}=e,n=lM(t),o=typeof r=="function"?r({present:n.isPresent}):kt.Children.only(r),a=so(n.ref,cM(o));return typeof r=="function"||n.isPresent?kt.cloneElement(o,{ref:a}):null};$u.displayName="Presence";function lM(e){let[t,r]=kt.useState(),n=kt.useRef(null),o=kt.useRef(e),a=kt.useRef("none"),i=e?"mounted":"unmounted",[s,l]=sM(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return kt.useEffect(()=>{let c=dp(n.current);a.current=s==="mounted"?c:"none";},[s]),ma(()=>{let c=n.current,u=o.current;if(u!==e){let m=a.current,h=dp(c);e?l("MOUNT"):h==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&m!==h?"ANIMATION_OUT":"UNMOUNT"),o.current=e;}},[e,l]),ma(()=>{if(t){let c,u=t.ownerDocument.defaultView??window,d=h=>{let p=dp(n.current).includes(CSS.escape(h.animationName));if(h.target===t&&p&&(l("ANIMATION_END"),!o.current)){let f=t.style.animationFillMode;t.style.animationFillMode="forwards",c=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=f);});}},m=h=>{h.target===t&&(a.current=dp(n.current));};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{u.clearTimeout(c),t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d);}}else l("ANIMATION_END");},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:kt.useCallback(c=>{n.current=c?getComputedStyle(c):null,r(c);},[])}}function dp(e){return e?.animationName||"none"}function cM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var f0=0;function oN(){kt.useEffect(()=>{let e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??rN()),document.body.insertAdjacentElement("beforeend",e[1]??rN()),f0++,()=>{f0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),f0--;}},[]);}function rN(){let e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var an=function(){return an=Object.assign||function(t){for(var r,n=1,o=arguments.length;n<o;n++){r=arguments[n];for(var a in r)Object.prototype.hasOwnProperty.call(r,a)&&(t[a]=r[a]);}return t},an.apply(this,arguments)};function fp(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,n=Object.getOwnPropertySymbols(e);o<n.length;o++)t.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(e,n[o])&&(r[n[o]]=e[n[o]]);return r}function aN(e,t,r){for(var n=0,o=t.length,a;n<o;n++)(a||!(n in t))&&(a||(a=Array.prototype.slice.call(t,0,n)),a[n]=t[n]);return e.concat(a||Array.prototype.slice.call(t))}var os="right-scroll-bar-position",as="width-before-scroll-bar",p0="with-scroll-bars-hidden",m0="--removed-body-scroll-bar-size";function pp(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function iN(e,t){var r=useState(function(){return {value:e,callback:t,facade:{get current(){return r.value},set current(n){var o=r.value;o!==n&&(r.value=n,r.callback(n,o));}}}})[0];return r.callback=t,r.facade}var dM=typeof window<"u"?kt.useLayoutEffect:kt.useEffect,sN=new WeakMap;function h0(e,t){var r=iN(null,function(n){return e.forEach(function(o){return pp(o,n)})});return dM(function(){var n=sN.get(r);if(n){var o=new Set(n),a=new Set(e),i=r.current;o.forEach(function(s){a.has(s)||pp(s,null);}),a.forEach(function(s){o.has(s)||pp(s,i);});}sN.set(r,e);},[e]),r}function fM(e){return e}function pM(e,t){t===void 0&&(t=fM);var r=[],n=false,o={read:function(){if(n)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:e},useMedium:function(a){var i=t(a,n);return r.push(i),function(){r=r.filter(function(s){return s!==i});}},assignSyncMedium:function(a){for(n=true;r.length;){var i=r;r=[],i.forEach(a);}r={push:function(s){return a(s)},filter:function(){return r}};},assignMedium:function(a){n=true;var i=[];if(r.length){var s=r;r=[],s.forEach(a),i=r;}var l=function(){var u=i;i=[],u.forEach(a);},c=function(){return Promise.resolve().then(l)};c(),r={push:function(u){i.push(u),c();},filter:function(u){return i=i.filter(u),r}};}};return o}function g0(e){e===void 0&&(e={});var t=pM(null);return t.options=an({async:true,ssr:false},e),t}var cN=function(e){var t=e.sideCar,r=fp(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=t.read();if(!n)throw new Error("Sidecar medium not found");return kt.createElement(n,an({},r))};cN.isSideCarExport=true;function y0(e,t){return e.useMedium(t),cN}var hp=g0();var v0=function(){},Iu=kt.forwardRef(function(e,t){var r=kt.useRef(null),n=kt.useState({onScrollCapture:v0,onWheelCapture:v0,onTouchMoveCapture:v0}),o=n[0],a=n[1],i=e.forwardProps,s=e.children,l=e.className,c=e.removeScrollBar,u=e.enabled,d=e.shards,m=e.sideCar,h=e.noRelative,y=e.noIsolation,p=e.inert,f=e.allowPinchZoom,x=e.as,g=x===void 0?"div":x,v=e.gapMode,w=fp(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),N=m,S=h0([r,t]),_=an(an({},w),o);return kt.createElement(kt.Fragment,null,u&&kt.createElement(N,{sideCar:hp,removeScrollBar:c,shards:d,noRelative:h,noIsolation:y,inert:p,setCallbacks:a,allowPinchZoom:!!f,lockRef:r,gapMode:v}),i?kt.cloneElement(kt.Children.only(s),an(an({},_),{ref:S})):kt.createElement(g,an({},_,{className:l,ref:S}),s))});Iu.defaultProps={enabled:true,removeScrollBar:true,inert:false};Iu.classNames={fullWidth:as,zeroRight:os};var dN=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function mM(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=dN();return t&&e.setAttribute("nonce",t),e}function hM(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t));}function gM(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e);}var b0=function(){var e=0,t=null;return {add:function(r){e==0&&(t=mM())&&(hM(t,r),gM(t)),e++;},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null);}}};var x0=function(){var e=b0();return function(t,r){kt.useEffect(function(){return e.add(t),function(){e.remove();}},[t&&r]);}};var Fu=function(){var e=x0(),t=function(r){var n=r.styles,o=r.dynamic;return e(n,o),null};return t};var yM={left:0,top:0,right:0,gap:0},w0=function(e){return parseInt(e||"",10)||0},vM=function(e){var t=window.getComputedStyle(document.body),r=t[e==="padding"?"paddingLeft":"marginLeft"],n=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return [w0(r),w0(n),w0(o)]},_0=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return yM;var t=vM(e),r=document.documentElement.clientWidth,n=window.innerWidth;return {left:t[0],top:t[1],right:t[2],gap:Math.max(0,n-r+t[2]-t[0])}};var bM=Fu(),Sl="data-scroll-locked",xM=function(e,t,r,n){var o=e.left,a=e.top,i=e.right,s=e.gap;return r===void 0&&(r="margin"),`
12
- .`.concat(p0,` {
11
+ `})),d(E);},[i]);let x=useMemo(()=>({jsonSchema:i,setJsonSchema:p,computedSchema:s,isValidSchema:u,validationErrors:l}),[i,p,s,u,l]);return jsx(jS.Provider,{value:x,children:o})}function Ka(){let e=useContext(jS);if(e===void 0)throw new Error("useJsonSchema must be used within a JsonSchemaProvider");return e}function nF({children:e}){let t={title:"",description:"",type:"object",properties:{},required:[]},[r,n]=useState(t);return jsx(LS,{jsonSchema:r,setJsonSchema:n,computedSchema:r,children:e})}var BS=Rt__default.memo(function({jsonSchema:t,setJsonSchema:r,computedSchema:n,layoutSchema:a,persistJsonSchemaCallback:o,children:i}){return !t&&!n?jsx(nF,{children:i}):jsx(LS,{jsonSchema:t,setJsonSchema:r,computedSchema:n,layoutSchema:a,persistJsonSchemaCallback:o,children:i})});function Ul(...e){return twMerge(clsx(e))}function Zu(e,t){if(!e||!t)return;let r=t.split("."),n=e;for(let a of r){if(n==null)return;n=n[a];}return n}function i0(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>i0(n));let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=i0(e[n]));let r=Object.keys(t);if(r.length>0&&r.every(a=>{let o=Number(a);return !isNaN(o)&&Number.isInteger(o)&&o>=0&&o<=Number.MAX_SAFE_INTEGER&&String(o)===a})){let a=r.map(o=>Number(o)).sort((o,i)=>o-i);if(a[0]===0&&a[a.length-1]===a.length-1)return a.map(o=>t[o])}return t}function zS(e){if(!e||Object.keys(e).length===0)return e;let t={...e},r={};for(let n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let o=n.split(".").filter(s=>s!=="");if(o.length===0){r[n]=t[n];continue}let i=r;for(let s=0;s<o.length;s++){let l=o[s],u=!isNaN(Number(l))&&Number.isInteger(Number(l))&&Number(l)>=0&&String(Number(l))===l?Number(l):l;s===o.length-1?i[u]=t[n]:(i[u]===void 0?i[u]={}:(typeof i[u]!="object"||Array.isArray(i[u]))&&(i[u]={}),i=i[u]);}}return i0(r)}var Bt={all:["extractions"],lists:()=>[...Bt.all,"list"],list:e=>[...Bt.lists(),{filters:e}],details:()=>[...Bt.all,"detail"],detail:e=>[...Bt.details(),e]};var Ga=(e={},t={})=>{let{enabled:r=true}=t,{fetchWithAuth:n}=Ve();return useQuery({queryKey:Bt.list(e),queryFn:async()=>{let a=new URLSearchParams;e.before&&a.append("before",e.before),e.after&&a.append("after",e.after),e.limit!==void 0&&a.append("limit",String(e.limit)),e.order&&a.append("order",e.order),e.origin_dot_id&&a.append("origin_dot_id",e.origin_dot_id),e.metadata&&Object.keys(e.metadata).length>0&&a.append("metadata",JSON.stringify(e.metadata)),e.filename&&a.append("filename",e.filename),e.from_date&&a.append("from_date",e.from_date),e.to_date&&a.append("to_date",e.to_date),e.human_review_status&&a.append("human_review_status",e.human_review_status);let o=`/v1/extractions${a.toString()?`?${a.toString()}`:""}`,i=await n(o);if(!i.ok)throw await Et(i,"Failed to fetch extractions");return i.json()},throwOnError:a=>sn(a).type!=="auth_error",enabled:r})};var c0=e=>{let{fetchWithAuth:t}=Ve();return useQuery({queryKey:Bt.detail(e||"null"),queryFn:async()=>{if(!e)throw new Error("Extraction ID is required");let r=await t(`/v1/extractions/${e}`);if(r.status===404)return null;if(!r.ok)throw await Et(r,"Failed to fetch extraction");return r.json()},enabled:!!e,retry:(r,n)=>n.message?.includes("404")||sn(n).type==="auth_error"?false:r<3,throwOnError:r=>sn(r).type!=="auth_error"})},ql=()=>{let e=useQueryClient(),{fetchWithAuth:t}=Ve();return useMutation({mutationFn:async r=>{let{extractionId:n,...a}=r,o=await t(`/v1/extractions/${n}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!o.ok)throw await Et(o,"Failed to update extraction");return o.json()},onSuccess:r=>{e.setQueryData(Bt.detail(r.id),r);let n=e.getQueriesData({queryKey:Bt.lists()});for(let[a,o]of n)o&&e.setQueryData(a,{...o,data:o.data.map(i=>i.id===r.id?r:i)});}})},vp=()=>{let e=useQueryClient(),{fetchWithAuth:t}=Ve();return useMutation({mutationFn:async r=>{let n=await t(`/v1/extractions/${r}`,{method:"DELETE"});if(!n.ok)throw await Et(n,"Failed to delete extraction")},onSuccess:()=>{e.invalidateQueries({queryKey:Bt.all});}})},qS=()=>{let e=useQueryClient(),{fetchWithAuth:t}=Ve();return useMutation({mutationFn:async r=>{let{projectId:n,extractionId:a,file:o,onStreamStart:i,onStreamEnd:s,onPredictionUpdate:l}=r,c={},u=new FormData;u.append("document",o),u.append("extraction_id",a),u.append("store","true");let d=await t(`/v1/projects/extract/${n}/stream`,{method:"POST",body:u});if(!d.ok)throw await Et(d,`Extraction failed with status ${d.status}`);if(!d.body)throw new Error("Browser doesn't support streaming responses.");i?.();let g=d.body.getReader(),f=new TextDecoder("utf-8"),h="";try{for(;;){let{value:m,done:p}=await g.read();if(p)break;if(m){let v=f.decode(m,{stream:!0});h+=v;let y=h.split(`
12
+ `);h=y.pop()||"";for(let x of y)if(x.trim())try{let _=JSON.parse(x)?.choices?.[0],E=_?.delta;if(E&&(E.flat_deleted_keys&&E.flat_deleted_keys.forEach(P=>{delete c[P];}),E.flat_parsed)){c={...c,...E.flat_parsed};let P=zS(c);l?.(P);}let C=_?.message?.parsed;C&&typeof C=="object"&&l?.(C);}catch(w){console.error("[useExtractionProcess] Error parsing chunk:",w);}}}}finally{s?.();}},onSuccess:(r,{extractionId:n})=>{e.invalidateQueries({queryKey:Bt.lists()}),e.invalidateQueries({queryKey:Bt.detail(n)});},onError:r=>{console.error("[useExtractionProcess] Extraction error:",r);},retry:2,retryDelay:r=>Math.min(1e3*Math.pow(2,r),3e4)})};var VS=e=>createStore()(t=>({limit:e?.limit??50,order:e?.order??"desc",originId:e?.originId??void 0,dateRange:{},humanReviewStatus:e?.humanReviewStatus??"review_required",cursors:{before:null,after:null},normalizedCursors:{before:null,after:null},hasNormalizedSingleOnce:false,selectedExtractionId:null,setLimit:r=>t({limit:r,cursors:{before:null,after:null}}),setOrder:r=>t({order:r}),setOriginId:r=>t({originId:r}),setDateRange:r=>t({dateRange:r,cursors:{before:null,after:null}}),setHumanReviewStatus:r=>t({humanReviewStatus:r,cursors:{before:null,after:null}}),setCursors:r=>t({cursors:r}),setNormalizedCursors:r=>t({normalizedCursors:r}),setHasNormalizedSingleOnce:r=>t({hasNormalizedSingleOnce:r}),setSelectedExtractionId:r=>t({selectedExtractionId:r}),resetCursors:()=>t({cursors:{before:null,after:null},normalizedCursors:{before:null,after:null},hasNormalizedSingleOnce:false}),resetFilters:r=>t({limit:r?.limit??50,order:r?.order??"desc",humanReviewStatus:r?.humanReviewStatus??"review_required",originId:r?.originId??void 0,dateRange:{},cursors:{before:null,after:null},normalizedCursors:{before:null,after:null},hasNormalizedSingleOnce:false,selectedExtractionId:null})}));var d0=createContext(void 0),uF=createContext(null);function GS({children:e,initialLimit:t=50,initialOrder:r="desc",initialHumanStatus:n="review_required",originId:a,mode:o="full"}){let i=useQueryClient(),{fetchWithAuth:s}=Ve(),l=useRef(null);l.current||(l.current=VS({limit:t,order:r,humanReviewStatus:n,originId:a}));let c=l.current,u=useStore(c,M=>M.limit),d=useStore(c,M=>M.order),g=useStore(c,M=>M.originId),f=useStore(c,M=>M.dateRange),h=useStore(c,M=>M.humanReviewStatus),m=useStore(c,M=>M.cursors),p=useStore(c,M=>M.normalizedCursors),v=useStore(c,M=>M.hasNormalizedSingleOnce),y=useStore(c,M=>M.selectedExtractionId),x=useStore(c,M=>M.setLimit),w=useStore(c,M=>M.setOrder),_=useStore(c,M=>M.setOriginId),E=useStore(c,M=>M.setDateRange),C=useStore(c,M=>M.setHumanReviewStatus),P=useStore(c,M=>M.setCursors),T=useStore(c,M=>M.setNormalizedCursors),N=useStore(c,M=>M.setHasNormalizedSingleOnce),S=useStore(c,M=>M.setSelectedExtractionId),b=useStore(c,M=>M.resetCursors);useEffect(()=>{let M=false,j=u===1,ue=!!m.before&&!m.after;async function ie(){if(j&&ue){if(v){T({before:m.before,after:null});return}let Ce=new URLSearchParams;Ce.append("before",m.before),Ce.append("limit","1"),d&&Ce.append("order",d),g&&Ce.append("origin_dot_id",g),f.from&&Ce.append("from_date",format(f.from,"yyyy-MM-dd")),f.to&&Ce.append("to_date",format(f.to,"yyyy-MM-dd")),h&&h!=="all"&&Ce.append("human_review_status",h);try{let Te=`/v1/extractions${Ce.toString()?`?${Ce.toString()}`:""}`,Je=await s(Te);if(!Je.ok)throw await Et(Je,"Failed to normalize cursors");let bt={before:null,after:(await Je.json())?.data?.[0]?.id??null};M||(T(bt),N(!0));}catch{M||T({before:null,after:null});}return}T({before:m.before,after:m.after});}return ie(),()=>{M=true;}},[u,m.before,m.after,d,g,f.from,f.to,h,s,T,N,v]),useEffect(()=>{!m.before&&!m.after&&N(false);},[m.before,m.after,u,d,g,h,f.from,f.to,N]);let{project:k}=Fr(),D=useMemo(()=>{let M={limit:u,order:d};h&&h!=="all"&&(M.human_review_status=h),g&&(M.origin_dot_id=g),f.from&&(M.from_date=format(f.from,"yyyy-MM-dd")),f.to&&(M.to_date=format(f.to,"yyyy-MM-dd"));let j=p.before,ue=p.after;return j&&(M.before=j),ue&&(M.after=ue),M},[u,d,h,g,f,p.before,p.after]),O=Ga(D,{enabled:o==="full"}),$=O.data?.data??[],A=O.data?.list_metadata??{before:null,after:null};useEffect(()=>{O.error&&toast.error("Failed to fetch extractions");},[O.error]);let F=useCallback(()=>{A.before&&P({before:A.before,after:null});},[A.before,P]),X=useCallback(()=>{A.after&&P({before:null,after:A.after});},[A.after,P]),H=useCallback(()=>{b(),i.invalidateQueries({queryKey:["extractions"]});},[i,b]),L=useCallback(M=>{P({before:M.before??null,after:M.after??null});},[P]),Q=useCallback(async M=>{if(M)try{let j=await s(`/v1/extractions/${M}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({human_review_status:"reviewed"})});if(!j.ok)throw await Et(j,"Failed to validate extraction");let ue=await j.json();if(console.log("responseData",ue),j.ok){let ie=[...Bt.all,"count",{origin_dot_id:g,human_review_status:"review_required"}];i.setQueryData(ie,Te=>Te&&{count:Math.max(0,(Te.count??0)-1)});let Ce=[...Bt.all,"count",{origin_dot_id:g,human_review_status:"reviewed"}];i.setQueryData(Ce,Te=>Te&&{count:(Te.count??0)+1}),i.invalidateQueries({queryKey:["extractions"]});}return ue}catch(j){throw console.error("validateExtraction failed",j),j}},[g,i,s]),z=useCallback(async M=>{if(M)try{let j=await s(`/v1/extractions/${M}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({human_review_status:"review_required"})});if(!j.ok)throw await Et(j,"Failed to invalidate human review");let ue=await j.json();if(console.log("responseData",ue),j.ok){let ie=[...Bt.all,"count",{origin_dot_id:g,human_review_status:"review_required"}];i.setQueryData(ie,Te=>Te&&{count:(Te.count??0)+1});let Ce=[...Bt.all,"count",{origin_dot_id:g,human_review_status:"reviewed"}];i.setQueryData(Ce,Te=>Te&&{count:Math.max(0,(Te.count??0)-1)}),i.invalidateQueries({queryKey:["extractions"]});}return ue}catch(j){throw console.error("invalidateHumanReview failed",j),j}},[g,i,s]),ae=useMemo(()=>({extractions:$,cursors:m,meta:A,isLoading:O.isLoading||O.isRefetching,isError:!!O.error,error:O.error??null,limit:u,setLimit:x,order:d,setOrder:w,originId:g,setOriginId:_,dateRange:f,setDateRange:E,humanReviewStatus:h,setHumanReviewStatus:C,selectedExtractionId:y,setSelectedExtractionId:S,fetchNextPage:F,fetchPrevPage:X,refresh:H,setCursorsFromUrl:L,transientUpdateExtraction:(M,j)=>{i.setQueryData(Bt.list(D),ue=>ue&&{...ue,data:ue.data.map(ie=>ie.id===M?{...ie,...j}:ie)});},validateExtraction:Q,invalidateHumanReview:z}),[$,m,A,O.isLoading,O.isRefetching,O.error,u,x,d,w,g,_,f,E,h,C,y,S,F,X,H,L,D,i,Q,z]);return jsx(uF.Provider,{value:c,children:jsx(d0.Provider,{value:ae,children:e})})}function ZS(){let e=useContext(d0);if(e===void 0)throw new Error("useExtractions must be used within an ExtractionsProvider");return e}function Za(){return useContext(d0)}function dF(e){try{if(e.some(r=>Array.isArray(r))){let r=e.filter(i=>Array.isArray(i)),n=e.filter(i=>!Array.isArray(i));if(r.length===1&&n.length>0){let i=n.reduce((s,l)=>s.plus(l===null?0:l),new Ge(0));return r[0].map(s=>new Ge(s===null?0:s).plus(i).toNumber())}let a=Math.max(...e.map(i=>Array.isArray(i)?i.length:1)),o=[];for(let i=0;i<a;i++){let s=new Ge(0);for(let l of e){let c=Array.isArray(l)?l[i]??0:l===null?0:l;s=s.plus(c);}o.push(s.toNumber());}return o}return e.reduce((r,n)=>r.plus(n===null?0:n),new Ge(0)).toNumber()}catch{return null}}function fF(e){if(e.length!==2)return null;try{let t=Array.isArray(e[0]),r=Array.isArray(e[1]);if(t||r)if(t&&!r){let o=new Ge(e[1]===null?0:e[1]);return e[0].map(i=>new Ge(i===null?0:i).minus(o).toNumber())}else if(!t&&r){let o=new Ge(e[0]===null?0:e[0]);return e[1].map(i=>o.minus(i===null?0:i).toNumber())}else {let o=e[0],i=e[1],s=Math.max(o.length,i.length),l=[];for(let c=0;c<s;c++){let u=c<o.length?o[c]===null?0:o[c]:0,d=c<i.length?i[c]===null?0:i[c]:0;l.push(new Ge(u).minus(d).toNumber());}return l}let n=e[0]===null?0:e[0],a=e[1]===null?0:e[1];return new Ge(n).minus(a).toNumber()}catch{return null}}function pF(e){if(e.length===0)return 1;try{if(e.some(r=>Array.isArray(r))){let r=e.filter(i=>Array.isArray(i)),n=e.filter(i=>!Array.isArray(i));if(r.length===1&&n.length>0){let i=n.reduce((s,l)=>s.times(l===null?0:l),new Ge(1));return r[0].map(s=>new Ge(s===null?0:s).times(i).toNumber())}let a=Math.max(...e.map(i=>Array.isArray(i)?i.length:1)),o=[];for(let i=0;i<a;i++){let s=new Ge(1);for(let l of e){let c=Array.isArray(l)?l[i]===null?0:l[i]??1:l===null?0:l;s=s.times(c);}o.push(s.toNumber());}return o}return e.reduce((r,n)=>r.times(n===null?0:n),new Ge(1)).toNumber()}catch{return null}}function mF(e){if(e.length!==2)return null;try{let t=Array.isArray(e[0]),r=Array.isArray(e[1]);if(t||r)if(t&&!r){let o=new Ge(e[1]===null?1:e[1]);return e[0].map(i=>new Ge(i===null?0:i).div(o).toNumber())}else if(!t&&r){let o=new Ge(e[0]===null?0:e[0]);return e[1].map(i=>o.div(i===null?1:i).toNumber())}else {let o=e[0],i=e[1],s=Math.max(o.length,i.length),l=[];for(let c=0;c<s;c++){let u=c<o.length?o[c]===null?0:o[c]:0,d=c<i.length?i[c]===null?1:i[c]:1;l.push(new Ge(u).div(d).toNumber());}return l}let n=e[0]===null?0:e[0],a=e[1]===null?1:e[1];return new Ge(n).div(a).toNumber()}catch{return null}}function hF(e){if(e.length!==1)return null;try{let t=e[0];if(Array.isArray(t))return t.map(n=>{let a=n===null?0:n;return new Ge(a).abs().toNumber()});let r=t===null?0:t;return new Ge(r).abs().toNumber()}catch{return null}}function gF(e){if(e.length!==1)return null;try{let t=e[0];if(Array.isArray(t))return t.map(n=>{let a=n===null?0:n;return new Ge(a).sqrt().toNumber()});let r=t===null?0:t;return new Ge(r).sqrt().toNumber()}catch{return null}}function yF(e){if(e.length<1||e.length>2)return null;try{let t=e[0],r=e.length===2?e[1]:null;if(Array.isArray(t))return t.map(a=>{let o=a===null?1:a;if(r===null)return new Ge(o).ln().toNumber();{let i=r===null?Math.E:r;return new Ge(o).ln().div(new Ge(i).ln()).toNumber()}});let n=t===null?1:t;if(r===null)return new Ge(n).ln().toNumber();{let a=r===null?Math.E:r;return new Ge(n).ln().div(new Ge(a).ln()).toNumber()}}catch{return null}}function vF(e){if(e.length!==2)return null;try{let t=e[0],r=e[1],n=Array.isArray(t),a=Array.isArray(r);if(n||a)if(n&&!a){let s=new Ge(r===null?1:r);return t.map(l=>new Ge(l===null?0:l).pow(s).toNumber())}else if(!n&&a){let s=new Ge(t===null?0:t);return r.map(l=>s.pow(l===null?1:l).toNumber())}else {let s=t,l=r,c=Math.max(s.length,l.length),u=[];for(let d=0;d<c;d++){let g=d<s.length?s[d]===null?0:s[d]:0,f=d<l.length?l[d]===null?1:l[d]:1;u.push(new Ge(g).pow(f).toNumber());}return u}let o=t===null?0:t,i=r===null?1:r;return new Ge(o).pow(i).toNumber()}catch{return null}}function bF(e){if(e.length===0)return null;try{if(!Array.isArray(e[0]))return null;let t=e[0];if(t.length===0)return 0;let r=t;if(e.length>1&&typeof e[1]=="string"&&e[1]!==""){let i=e[1].split(".");r=t.map(s=>{if(s==null||typeof s!="object")return null;let l=s;for(let c of i){if(l==null||typeof l!="object")return null;l=l[c];}return l});}let n=new Ge(0),a=!1;for(let o of r)if(o!=null)if(typeof o=="number")n=n.plus(o);else if(typeof o=="string"){let i=Number(o);if(!isNaN(i))n=n.plus(i);else {a=!0;break}}else if(typeof o=="object"){a=!0;break}else {a=!0;break}return a?null:n.toNumber()}catch{return null}}function xF(e){if(e.length===0)return null;try{if(!Array.isArray(e[0]))return null;let t=e[0];if(t.length===0)return null;let r=t;if(e.length>1&&typeof e[1]=="string"&&e[1]!==""){let s=e[1].split(".");r=t.map(l=>{if(l==null||typeof l!="object")return null;let c=l;for(let u of s){if(c==null||typeof c!="object")return null;c=c[u];}return c});}let n=new Ge(0),a=0,o=!1;for(let i of r)if(i!=null)if(typeof i=="number")n=n.plus(i),a++;else if(typeof i=="string"){let s=Number(i);if(!isNaN(s))n=n.plus(s),a++;else {o=!0;break}}else if(typeof i=="object"){o=!0;break}else {o=!0;break}return o||a===0?null:n.div(a).toNumber()}catch{return null}}function wF(e){if(e.length===0)return null;try{if(Array.isArray(e[0])){let t=e[0];if(t.length===0)return null;let r=t;if(e.length>1&&typeof e[1]=="string"&&e[1]!==""){let i=e[1].split(".");r=t.map(s=>{if(s==null||typeof s!="object")return null;let l=s;for(let c of i){if(l==null||typeof l!="object")return null;l=l[c];}return l});}let n=null,a=!1;for(let o of r)if(o!=null)if(typeof o=="number"){let i=new Ge(o);(n===null||i.lessThan(n))&&(n=i);}else if(typeof o=="string"){let i=Number(o);if(isNaN(i)){a=!0;break}else {let s=new Ge(i);(n===null||s.lessThan(n))&&(n=s);}}else if(typeof o=="object"){a=!0;break}else {a=!0;break}return a||n===null?null:n.toNumber()}else {let t=null,r=!1;for(let n of e)if(n!=null)if(typeof n=="number"){let a=new Ge(n);(t===null||a.lessThan(t))&&(t=a);}else if(typeof n=="string"){let a=Number(n);if(isNaN(a)){r=!0;break}else {let o=new Ge(a);(t===null||o.lessThan(t))&&(t=o);}}else if(typeof n=="object"||Array.isArray(n)){r=!0;break}else {r=!0;break}return r||t===null?null:t.toNumber()}}catch{return null}}function _F(e){if(e.length===0)return null;try{if(Array.isArray(e[0])){let t=e[0];if(t.length===0)return null;let r=t;if(e.length>1&&typeof e[1]=="string"&&e[1]!==""){let i=e[1].split(".");r=t.map(s=>{if(s==null||typeof s!="object")return null;let l=s;for(let c of i){if(l==null||typeof l!="object")return null;l=l[c];}return l});}let n=null,a=!1;for(let o of r)if(o!=null)if(typeof o=="number"){let i=new Ge(o);(n===null||i.greaterThan(n))&&(n=i);}else if(typeof o=="string"){let i=Number(o);if(isNaN(i)){a=!0;break}else {let s=new Ge(i);(n===null||s.greaterThan(n))&&(n=s);}}else if(typeof o=="object"){a=!0;break}else {a=!0;break}return a||n===null?null:n.toNumber()}else {let t=null,r=!1;for(let n of e)if(n!=null)if(typeof n=="number"){let a=new Ge(n);(t===null||a.greaterThan(t))&&(t=a);}else if(typeof n=="string"){let a=Number(n);if(isNaN(a)){r=!0;break}else {let o=new Ge(a);(t===null||o.greaterThan(t))&&(t=o);}}else if(typeof n=="object"||Array.isArray(n)){r=!0;break}else {r=!0;break}return r||t===null?null:t.toNumber()}}catch{return null}}function SF(e){try{return e.map(t=>t===null?"":String(t)).join("")}catch{return null}}function NF(e){if(e.length!==2)return null;let t=e[0],r=e[1];if(!Array.isArray(t))return null;try{return t.reduce((n,a)=>n+(a===r?1:0),0)}catch{return null}}function f0(e,t,r){switch(t){case "=":case "==":return e===r;case "!=":return e!==r;case ">":return e>r;case ">=":return e>=r;case "<":return e<r;case "<=":return e<=r;case "contains":let n=String(e).toLowerCase(),a=String(r).toLowerCase();return n.includes(a);default:return false}}function CF(e){if(e.length<4)return null;try{let t=e[0];if(!Array.isArray(t)||t.length===0)return null;let r=e[1],n=e[2],a=e[3],o=e.length>4?e[4]:"",i=e.length>5?e[5]:"exact";if(typeof r!="string"||typeof n!="string")return null;let s=o&&typeof o=="string"&&o!==""?o.split("."):[];if(i==="approx"){if(typeof a!="number")return null;let l=0,c=t.length-1,u=null;for(;l<=c;){let d=Math.floor((l+c)/2),g=t[d],f=g;if(r!==""){let h=r.split(".");for(let m of h){if(f==null||typeof f!="object"){f=null;break}f=f[m];}}if(typeof f!="number")return null;f<=a?(u=g,l=d+1):c=d-1;}if(u===null)return null;if(s.length>0){let d=u;for(let g of s){if(d==null||typeof d!="object")return null;d=d[g];}return d}return u}for(let l of t){let c=l;if(r!==""){let u=r.split(".");for(let d of u){if(c==null||typeof c!="object"){c=null;break}c=c[d];}c===void 0&&(c=null);}if(f0(c,n,a)){if(s.length>0){let u=l;for(let d of s){if(u==null||typeof u!="object")return null;u=u[d];}return u}return l}}return null}catch{return null}}function EF(e){if(e.length<4)return -1;try{let t=e[0];if(!Array.isArray(t)||t.length===0)return -1;let r=e[1],n=e[2],a=e[3],o=e.length>4?e[4]:"exact";if(typeof r!="string"||typeof n!="string")return -1;if(o==="approx"){if(typeof a!="number")return -1;let i=0,s=t.length-1,l=-1;for(;i<=s;){let c=Math.floor((i+s)/2),d=t[c];if(r!==""){let g=r.split(".");for(let f of g){if(d==null||typeof d!="object"){d=null;break}d=d[f];}}if(typeof d!="number")return -1;d<=a?(l=c,i=c+1):s=c-1;}return l}for(let i=0;i<t.length;i++){let l=t[i];if(r!==""){let c=r.split(".");for(let u of c){if(l==null||typeof l!="object"){l=null;break}l=l[u];}l===void 0&&(l=null);}if(f0(l,n,a))return i}return -1}catch{return -1}}function PF(e){if(e.length<4)return [];try{let t=e[0];if(!Array.isArray(t))return [];if(t.length===0)return [];let r=e[1],n=e[2],a=e[3];if(typeof r!="string"||typeof n!="string")return [];let o=[];for(let i of t){let s=i;if(r!==""){let l=r.split(".");for(let c of l){if(s==null||typeof s!="object"){s=null;break}s=s[c];}s===void 0&&(s=null);}f0(s,n,a)&&o.push(i);}return o}catch{return []}}function TF(e){if(e.length===0)return [];try{let t=e[0];if(!Array.isArray(t))return [];if(t.length===0)return [];if(e.length>1&&typeof e[1]=="string"&&e[1]!==""){let n=e[1].split(".");return t.map(o=>{if(o==null||typeof o!="object")return null;let i=o;for(let s of n){if(i==null||typeof i!="object")return null;i=i[s];}return i}).filter(o=>o!=null).flat(1)}return t.flat(1)}catch{return []}}function kF(e){if(e.length!==2)return null;try{return e[0]===e[1]}catch{return null}}function RF(e){if(e.length<2)return null;try{return e.every(t=>!!t)}catch{return null}}function OF(e){if(e.length<2)return null;try{return e.some(t=>!!t)}catch{return null}}function DF(e){if(e.length!==3)return null;try{let t=e[0],r=e[1],n=e[2];if(Array.isArray(t)){let a=Array.isArray(r)?r:null,o=Array.isArray(n)?n:null;return t.map((i,s)=>{let l=a?a[s]??r:r,c=o?o[s]??n:n;return i?l:c})}return t?r:n}catch{return null}}function AF(e){if(e.length!==1)return null;try{let t=e[0];return Array.isArray(t)?t.map(r=>!r):!t}catch{return null}}function $F(e){if(e.length!==2)return null;try{let t=e[0],r=e[1],n=Array.isArray(t),a=Array.isArray(r);if(n||a){if(n&&!a)return t.map(o=>o>r);if(!n&&a)return r.map(o=>t>o);{let o=t,i=r,s=Math.max(o.length,i.length),l=[];for(let c=0;c<s;c++){let u=c<o.length?o[c]:null,d=c<i.length?i[c]:null;l.push(u>d);}return l}}return t>r}catch{return null}}function IF(e){if(e.length!==2)return null;try{let t=e[0],r=e[1],n=Array.isArray(t),a=Array.isArray(r);if(n||a){if(n&&!a)return t.map(o=>o>=r);if(!n&&a)return r.map(o=>t>=o);{let o=t,i=r,s=Math.max(o.length,i.length),l=[];for(let c=0;c<s;c++){let u=c<o.length?o[c]:null,d=c<i.length?i[c]:null;l.push(u>=d);}return l}}return t>=r}catch{return null}}function FF(e){if(e.length!==2)return null;try{let t=e[0],r=e[1],n=Array.isArray(t),a=Array.isArray(r);if(n||a){if(n&&!a)return t.map(o=>o<r);if(!n&&a)return r.map(o=>t<o);{let o=t,i=r,s=Math.max(o.length,i.length),l=[];for(let c=0;c<s;c++){let u=c<o.length?o[c]:null,d=c<i.length?i[c]:null;l.push(u<d);}return l}}return t<r}catch{return null}}function MF(e){if(e.length!==2)return null;try{let t=e[0],r=e[1],n=Array.isArray(t),a=Array.isArray(r);if(n||a){if(n&&!a)return t.map(o=>o<=r);if(!n&&a)return r.map(o=>t<=o);{let o=t,i=r,s=Math.max(o.length,i.length),l=[];for(let c=0;c<s;c++){let u=c<o.length?o[c]:null,d=c<i.length?i[c]:null;l.push(u<=d);}return l}}return t<=r}catch{return null}}var Hl={$add:dF,$subtract:fF,$multiply:pF,$divide:mF,$abs:hF,$sqrt:gF,$log:yF,$pow:vF,$sum:bF,$average:xF,$min:wF,$max:_F,$concat:SF,$count:NF,$lookup:CF,$match:EF,$filter:PF,$flatten:TF,$eq:kF,$and:RF,$or:OF,$if:DF,$not:AF,$gt:$F,$gte:IF,$lt:FF,$lte:MF};function Xu(e){return e.operation?e.operation:null}function Vt(e,t){if(e&&e.$ref){let r=e.$ref;if(r.startsWith("#/")){let n=r.substring(2).split("/"),a=t;for(let o of n)if(a&&typeof a=="object"&&o in a)a=a[o];else return e;return a}}return e}function ws(e,t,r){if(!e)return t;let n=e.split("."),a=t;for(let o of n)if(o==="*")if(a.type==="array"){let i=a.items||{};a=Vt(i,t);}else return {};else if(a.type==="object"){let i=a.properties||{};if(o in i){let s=i[o];a=Vt(s,t);}else throw new Error(`Field '${o}' not found in schema at path '${e}'`)}else throw a.type==="array"?new Error(`Cannot access field '${o}' on array type at path '${e}'`):new Error(`Path '${e}' does not exist in schema`);return a}function xp(e,t,r){try{let n=ws(e,t,r);return Object.keys(n).length>0}catch{return false}}function p0(e,t,r){if(!e)return t.type||null;try{return ws(e,t,r).type||null}catch{return null}}function wp(e,t){switch(e.operation){case "$concat":return {type:"string"};case "$eq":case "$gt":case "$gte":case "$lt":case "$lte":case "$and":case "$or":case "$not":return {type:"boolean"};case "$count":case "$match":return {type:"integer"};case "$filter":return {type:"array",items:{}};case "$add":case "$subtract":case "$multiply":case "$divide":case "$abs":case "$sqrt":case "$log":case "$pow":return t&&t.some(r=>jF(r))?{type:"array",items:{type:"number"}}:{type:"number"};case "$sum":case "$average":case "$min":case "$max":return {type:"number"};case "$lookup":return {};case "$if":if(t&&t.length>=3){let r=t[1],n=t[2];if(r?.type&&n?.type&&r.type===n.type)return {type:r.type};if(r?.type)return {type:r.type};if(n?.type)return {type:n.type}}return {type:"string"};default:return {type:"number"}}}function jF(e){if(!e||typeof e!="object")return false;if(e.type==="array")return true;let t=e.anyOf||e.oneOf||e.allOf;return Array.isArray(t)?t.some(r=>r&&typeof r=="object"&&r.type==="array"):false}function Vn(e,t){try{if(t.length===0)return e;let r=t[0],n=t.slice(1);if(r==="*"){if(!Array.isArray(e))return null;let a=[];for(let o of e)if(n.length===0)typeof o=="object"&&o!==null&&"$original_value"in o?a.push(o.$original_value):Array.isArray(o)?a.push(...o):a.push(o);else {let i=Vn(o,n);i===null?a.push(null):Array.isArray(i)?a.push(...i):a.push(i);}return a}else {if(typeof e!="object"||e===null||!(r in e))return null;let a=e[r];return Vn(a,n)}}catch{return null}}function _p(e){return typeof e=="object"&&e!==null&&"$original_value"in e?e.$original_value:e}function Sp(e,t,r,n=true){try{let a=-1;for(let l=0;l<t.length;l++)if(t[l]==="*"&&!(l in r)){a=l;break}if(a===-1)return wa(e,t,r,n);let o=t.slice(0,a),i=t.slice(a),s=e;return o.length>0&&(s=wa(e,o,r,!1),s===null)?null:Vn(s,i)}catch{return null}}function wa(e,t,r,n=true){let a=e;for(let o=0;o<t.length;o++){let i=t[o];if(i==="*"){if(!(o in r))throw new Error(`No binding for wildcard at position ${o}`);let s=r[o];if(!Array.isArray(a))throw new Error(`Expected list at position ${o} but got ${typeof a}`);if(s>=a.length)throw new Error(`Index ${s} out of range for array of length ${a.length}`);a=a[s],o===t.length-1&&n&&(a=_p(a));}else {if(typeof a!="object"||a===null||!(i in a))return null;a=a[i];}}return a}function Np(e){let t={};for(let n in e){let a={expression:e[n].expression};t[n]=a;}return {computations:t}}function Qu(e){let t=parseFloat(e);return isNaN(t)?[...e].every(r=>/\w|\.|\*/.test(r))&&!e.includes("..")&&!e.endsWith("."):false}function Cp(e,t,r){try{if(t.length===0)return;let n=e;for(let a=0;a<t.length-1;a++){let o=t[a];(!(o in n)||typeof n[o]!="object"||n[o]===null)&&(n[o]={}),n=n[o];}n[t[t.length-1]]=r;}catch{return}}function m0(e,t,r){let n=e.split(".");if(!n.includes("*")){let a=n.length>1?n.slice(0,-1).join("."):null;if(a){let o=p0(a,t,r);if(o&&o!=="object")throw new Error(`Cannot add field to non-object parent at '${a}' (type: ${o})`)}}}var _s=class{constructor(t){this.position=0;this.current="";this.input=t.trim(),this.current=this.input[0]||"";}advance(){this.position++,this.current=this.position<this.input.length?this.input[this.position]:"";}peek(t=1){let r=this.position+t;return r<this.input.length?this.input[r]:""}skipWhitespace(){for(;this.current&&/\s/.test(this.current);)this.advance();}readNumber(){let t=this.position,r="";for(;this.current&&/[0-9.]/.test(this.current);)r+=this.current,this.advance();return {type:"NUMBER",value:r,position:t}}readString(t){let r=this.position,n="";for(this.advance();this.current&&this.current!==t;)this.current==="\\"?(this.advance(),this.current&&(n+=this.current,this.advance())):(n+=this.current,this.advance());return this.current===t&&this.advance(),{type:"STRING",value:n,position:r}}readIdentifier(){let t=this.position,r="";for(;this.current&&/[a-zA-Z0-9_.*]/.test(this.current);)r+=this.current,this.advance();let n=r.toLowerCase();if(n==="true"||n==="false")return {type:"BOOLEAN",value:n,position:t};if(n==="null")return {type:"NULL",value:n,position:t};if(this.skipWhitespace(),this.current==="("){let a=r.toUpperCase();if(["SUM","AVERAGE","MIN","MAX","COUNT","LOOKUP","MATCH","FILTER","FLATTEN","CONCAT","ABS","SQRT","LOG","POW","EQ","AND","OR","IF","NOT","GT","GTE","LT","LTE"].includes(a))return {type:"FUNCTION",value:a,position:t}}return {type:"IDENTIFIER",value:r,position:t}}tokenize(){let t=[];for(;this.position<this.input.length&&(this.skipWhitespace(),!!this.current);){if(/[0-9]/.test(this.current)){t.push(this.readNumber());continue}if(this.current==='"'||this.current==="'"){t.push(this.readString(this.current));continue}if(/[a-zA-Z_]/.test(this.current)){t.push(this.readIdentifier());continue}let r=this.current,n=this.position;if(r==="<"||r===">"){this.advance(),this.current==="="?(this.advance(),r==="<"?t.push({type:"LTE",value:"<=",position:n}):t.push({type:"GTE",value:">=",position:n})):r==="<"?t.push({type:"LT",value:"<",position:n}):t.push({type:"GT",value:">",position:n});continue}if(r==="="){this.advance(),this.current==="="?(this.advance(),t.push({type:"EQ",value:"==",position:n})):t.push({type:"EQ",value:"=",position:n});continue}switch(this.advance(),r){case "+":t.push({type:"PLUS",value:"+",position:n});break;case "-":t.push({type:"MINUS",value:"-",position:n});break;case "*":t.push({type:"MULTIPLY",value:"*",position:n});break;case "/":t.push({type:"DIVIDE",value:"/",position:n});break;case "!":t.push({type:"NOT",value:"!",position:n});break;case "(":t.push({type:"LPAREN",value:"(",position:n});break;case ")":t.push({type:"RPAREN",value:")",position:n});break;case ",":t.push({type:"COMMA",value:",",position:n});break;default:throw new Error(`Unexpected character '${r}' at position ${n}`)}}return t.push({type:"EOF",value:"",position:this.position}),t}};var Ep=class{constructor(t){this.position=0;this.tokens=t,this.current=t[0];}advance(){this.position++,this.current=this.position<this.tokens.length?this.tokens[this.position]:this.tokens[this.tokens.length-1];}expect(t){if(this.current.type!==t)throw new Error(`Expected ${t} but got ${this.current.type} at position ${this.current.position}`);let r=this.current;return this.advance(),r}parseUnary(){if(this.current.type==="PLUS"||this.current.type==="MINUS"||this.current.type==="NOT"){let t;this.current.type==="MINUS"?t="-":this.current.type==="PLUS"?t="+":t="!",this.advance();let r=this.parseUnary();return {type:"UnaryOp",operator:t,operand:r}}return this.parsePrimary()}parsePrimary(){if(this.current.type==="NUMBER"){let t=parseFloat(this.current.value);return this.advance(),{type:"Number",value:t}}if(this.current.type==="STRING"){let t=this.current.value;return this.advance(),{type:"String",value:t}}if(this.current.type==="BOOLEAN"){let t=this.current.value==="true";return this.advance(),{type:"Boolean",value:t}}if(this.current.type==="NULL")return this.advance(),{type:"Null",value:null};if(this.current.type==="FUNCTION")return this.parseFunctionCall();if(this.current.type==="IDENTIFIER"){let t=this.current.value;return this.advance(),{type:"Identifier",name:t}}if(this.current.type==="LPAREN"){this.advance();let t=this.parseExpression();return this.expect("RPAREN"),t}throw new Error(`Unexpected token ${this.current.type} at position ${this.current.position}`)}parseFunctionCall(){let t=this.current.value;this.advance(),this.expect("LPAREN");let r=[];if(this.current.type!=="RPAREN")for(r.push(this.parseExpression());this.current.type==="COMMA";)this.advance(),r.push(this.parseExpression());return this.expect("RPAREN"),{type:"FunctionCall",name:t,args:r}}parseMultiplicative(){let t=this.parseUnary();for(;this.current.type==="MULTIPLY"||this.current.type==="DIVIDE";){let r=this.current.type==="MULTIPLY"?"*":"/";this.advance();let n=this.parseUnary();t={type:"BinaryOp",operator:r,left:t,right:n};}return t}parseAdditive(){let t=this.parseMultiplicative();for(;this.current.type==="PLUS"||this.current.type==="MINUS";){let r=this.current.type==="PLUS"?"+":"-";this.advance();let n=this.parseMultiplicative();t={type:"BinaryOp",operator:r,left:t,right:n};}return t}parseComparison(){let t=this.parseAdditive();for(;this.current.type==="GT"||this.current.type==="GTE"||this.current.type==="LT"||this.current.type==="LTE"||this.current.type==="EQ";){let r;switch(this.current.type){case "GT":r=">";break;case "GTE":r=">=";break;case "LT":r="<";break;case "LTE":r="<=";break;case "EQ":r=this.current.value;break;default:throw new Error(`Unexpected comparison operator ${this.current.type}`)}this.advance();let n=this.parseAdditive();t={type:"BinaryOp",operator:r,left:t,right:n};}return t}parseExpression(){return this.parseComparison()}parse(){let t=this.parseExpression();return this.expect("EOF"),t}};function gi(e){let r=new _s(e).tokenize();return new Ep(r).parse()}function Jl(e){try{switch(e.type){case "Number":return {value:e.value,literal:!0};case "String":return {value:e.value,literal:!0};case "Boolean":return {value:e.value,literal:!0};case "Null":return {value:e.value,literal:!0};case "Identifier":return {value:null,path:e.name};case "BinaryOp":{let t=e,r=Jl(t.left),n=Jl(t.right);if(r===null||n===null)return null;let a;switch(t.operator){case "+":a="$add";break;case "-":a="$subtract";break;case "*":a="$multiply";break;case "/":a="$divide";break;case ">":a="$gt";break;case ">=":a="$gte";break;case "<":a="$lt";break;case "<=":a="$lte";break;case "=":case "==":a="$eq";break;default:return null}return {value:null,operation:a,operands:[r,n]}}case "UnaryOp":{let t=e,r=Jl(t.operand);if(r===null)return null;if(t.operator==="+")return r;if(t.operator==="-"){let n={value:0,literal:!0};return {value:null,operation:"$subtract",operands:[n,r]}}else return {value:null,operation:"$not",operands:[r]}}case "FunctionCall":{let t=e,r=t.args.map(a=>Jl(a));if(r.some(a=>a===null))return null;let n;switch(t.name){case "SUM":n="$sum";break;case "AVERAGE":n="$average";break;case "MIN":n="$min";break;case "MAX":n="$max";break;case "COUNT":n="$count";break;case "LOOKUP":n="$lookup";break;case "MATCH":n="$match";break;case "FILTER":n="$filter";break;case "FLATTEN":n="$flatten";break;case "CONCAT":n="$concat";break;case "ABS":n="$abs";break;case "SQRT":n="$sqrt";break;case "LOG":n="$log";break;case "POW":n="$pow";break;case "EQ":n="$eq";break;case "AND":n="$and";break;case "OR":n="$or";break;case "IF":n="$if";break;case "NOT":n="$not";break;case "GT":n="$gt";break;case "GTE":n="$gte";break;case "LT":n="$lt";break;case "LTE":n="$lte";break;default:return null}return {value:null,operation:n,operands:r}}default:return null}}catch{return null}}function fn(e){try{let t=gi(e);return Jl(t)}catch{return null}}function QS(e){let t=[];if(!e||e.trim()==="")return t.push("Expression cannot be empty"),{isValid:false,errors:t};try{return gi(e),{isValid:!0,errors:[]}}catch(r){return r instanceof Error?t.push(r.message):t.push("Unknown syntax error"),{isValid:false,errors:t}}}function g0(e,t,r){let n=[],a=[],o=QS(e);if(!o.isValid)return o;let i;try{i=gi(e);}catch(s){return n.push(s instanceof Error?s.message:"Parse error"),{isValid:false,errors:n,warnings:a}}if(t){let s=Yu(i);for(let l of s)if(!l.startsWith("__temp_")&&!(r&&r.has(l)))try{ws(l,t,r||new Set);}catch{n.push(`Path '${l}' does not exist in schema`);}}return {isValid:n.length===0,errors:n,warnings:a}}function Yu(e){let t=[];switch(e.type){case "Identifier":t.push(e.name);break;case "BinaryOp":t.push(...Yu(e.left)),t.push(...Yu(e.right));break;case "UnaryOp":t.push(...Yu(e.operand));break;case "FunctionCall":let r=e.name;for(let n=0;n<e.args.length;n++){let a=e.args[n],o=false;r==="SUM"||r==="AVERAGE"||r==="MIN"||r==="MAX"||r==="FLATTEN"?o=n===1:r==="LOOKUP"?o=n===1||n===2||n===4||n===5:(r==="MATCH"||r==="FILTER")&&(o=n===1||n===2||r==="MATCH"&&n===4),o||t.push(...Yu(a));}break}return t}function y0(e){try{let t=gi(e);return Pp(t)}catch{return []}}function Pp(e){let t=[];if(!e)return t;switch(e.type){case "Identifier":t.push(e.name);break;case "BinaryOp":t.push(...Pp(e.left)),t.push(...Pp(e.right));break;case "FunctionCall":for(let r of e.args||[])t.push(...Pp(r));break}return t.filter(r=>Qu(r))}function _o(e){let t={},r={};for(let o in e)t[o]=0,r[o]=[];for(let o in e){let i=y0(e[o].expression);for(let s of i)s in e&&(r[s].push(o),t[o]++);}let n=[];for(let o in t)t[o]===0&&n.push(o);let a=[];for(;n.length>0;){let o=n.shift();a.push(o);for(let i of r[o])t[i]--,t[i]===0&&n.push(i);}if(a.length!==Object.keys(e).length)throw new Error("Cycle detected in computation dependencies");return a}function ed(e){let t={},r={},n={};for(let s in e)t[s]={dependencies:[],dependents:[],depth:0},r[s]=[],n[s]=[];for(let s in e){let l=y0(e[s].expression);for(let c of l)c in e&&(r[s].push(c),n[c].push(s));}for(let s in e)t[s].dependencies=r[s],t[s].dependents=n[s];let a={};for(let s in e)a[s]=r[s].length;let o=[];for(let s in a)a[s]===0&&o.push(s);let i={};for(let s in e)i[s]=0;for(;o.length>0;){let s=o.shift();for(let l of n[s])i[l]=Math.max(i[l],i[s]+1),a[l]--,a[l]===0&&o.push(l);}if(Object.values(a).some(s=>s>0))throw new Error("Cycle detected in computation dependencies");for(let s in t)t[s].depth=i[s];return t}function v0(e,t,r){if(!e[t])throw new Error(`Cannot rename computation: Field '${t}' does not exist in the current computation spec`);if(t===r)return {affectedComputations:[],updatedSpec:e};if(e[r])throw new Error(`Cannot rename to '${r}': A computed field with this name already exists`);let n=[],a={};ed(e)[t]?.dependents||[];for(let s in e){let l=e[s];if(s===t)a[r]={...l},n.push(t);else {let c=l.expression;if(y0(l.expression).includes(t)){let d=new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"g");c=c.replace(d,r),n.push(s);}a[s]={expression:c};}}return {affectedComputations:[...new Set(n)],updatedSpec:a}}function Ss(e,t,r={},n=null){try{if(e.literal)return e.value;if(e.path){let a=e.path.split(".");if(a.includes("*"))return Object.keys(r).length>0?Sp(t,a,r):Vn(t,a);if(n!==null){let o=Vn(n,a);if(o!==null)return o}return Vn(t,a)}if(e.operation&&e.operands){let a=Hl[e.operation];if(!a)return null;let o=e.operation==="$sum"||e.operation==="$average"||e.operation==="$min"||e.operation==="$max"||e.operation==="$lookup"||e.operation==="$match"||e.operation==="$filter"||e.operation==="$flatten",i=e.operands.map((s,l)=>{if(!o)return Ss(s,t,r,n);let c=!1;if(e.operation==="$sum"||e.operation==="$average"||e.operation==="$min"||e.operation==="$max"||e.operation==="$flatten"?c=l===1:e.operation==="$lookup"?c=l===1||l===2||l===4||l===5:(e.operation==="$match"||e.operation==="$filter")&&(c=l===1||l===2||e.operation==="$match"&&l===4),c&&s.path&&!s.path.includes("*")){let u=Ss(s,t,r,n);return u??s.path}return Ss(s,t,r,n)});return a(i)}return null}catch{return null}}function eN(e,t,r,n,a=0,o={}){try{if(a>=n.length){let c=n[n.length-1],u=t.slice(c+1);if(u.length===0)return;let d=wa(e,t.slice(0,c+1),o,!1),g=d;if(typeof g!="object"||g===null){let h={$original_value:g},m=t.slice(0,c),p=wa(e,m,o,!1),v=o[c];p[v]=h,g=h;}let f=Ss(r,e,o,d);f!==null&&Cp(g,u,f);return}let i=n[a],s=t.slice(0,i),l=wa(e,s,o,!1);if(!Array.isArray(l))return;for(let c=0;c<l.length;c++){let u={...o,[i]:c};eN(e,t,r,n,a+1,u);}}catch{return}}function b0(e,t,r){try{let n=fn(r.expression);if(n===null)return;let a=t.split(".");if(a.includes("*")){let o=a.map((i,s)=>i==="*"?s:-1).filter(i=>i!==-1);eN(e,a,n,o);}else {let o=Ss(n,e,{},null);o!==null&&Cp(e,a,o);}}catch{return}}function tN(e){if(!e)return [];let t=[];if(e.path&&!e.operation)return t.push(e.path),t;if(e.operation&&e.operands){let r=e.operation;for(let n=0;n<e.operands.length;n++){let a=e.operands[n],o=false;r==="$sum"||r==="$average"||r==="$min"||r==="$max"||r==="$flatten"?o=n===1:r==="$lookup"?o=n===1||n===2||n===4||n===5:(r==="$match"||r==="$filter")&&(o=n===1||n===2||r==="$match"&&n===4),o||t.push(...tN(a));}}return t}function x0(e,t){let r;t.computations?r=t:r=Np(t);let n;try{n=_o(r.computations);}catch(o){let i=o instanceof Error?o.message:String(o);throw console.error(`[compileSpec] Failed to compute execution order: ${i}`),o}let a=new Set;for(let o of n){let i=r.computations[o];try{m0(o,e,a);}catch(s){let l=s instanceof Error?s.message:String(s);throw console.error(`[compileSpec] Target path validation failed for '${o}': ${l}`),s}try{let s=fn(i.expression),l=tN(s);for(let c of l)if(!c.startsWith("__temp_")&&!a.has(c)&&!xp(c,e,a))throw new Error(`Operand path '${c}' does not exist in schema for target '${o}'`)}catch(s){let l=s instanceof Error?s.message:String(s);throw console.error(`[compileSpec] Validation failed for '${o}' (expression: ${i.expression}): ${l}`),s}a.add(o);}return r}function nN(e,t){let r=[];for(let n=0;n<e.length;n++){let a=e[n];if(a==="*"){let o=t[n];o!==void 0?r.length>0?r[r.length-1]=`${r[r.length-1]}[${o}]`:r.push(`[${o}]`):r.length>0?r[r.length-1]=`${r[r.length-1]}[*]`:r.push("[*]");}else r.push(a);}return r.join(".")}function _a(e,t,r=0,n=[],a,o){let i=[];if(o&&Object.keys(o).length>0&&r===0){let u=-1;for(let d=0;d<t.length;d++)if(t[d]==="*"&&!(d in o)){u=d;break}if(u>0){let d=t.slice(0,u),g=wa(e,d,o,false);if(g===null)return i;let f=[];for(let h=0;h<d.length;h++){let m=d[h];if(m==="*"){let p=o[h];f.length>0?f[f.length-1]=`${f[f.length-1]}[${p}]`:f.push(`[${p}]`);}else f.push(m);}return _a(e,t,u,f,g)}}let s=a===void 0?e:a;for(let u=r;u<t.length;u++){let d=t[u];if(d==="*"){if(!Array.isArray(s))return i;if(o&&u in o){let g=o[u];if(g>=0&&g<s.length){let f=n.slice();f.length>0?f[f.length-1]=`${f[f.length-1]}[${g}]`:f.push(`[${g}]`);let h=s[g],m=_a(e,t,u+1,f,h,o);i.push(...m);}return i}for(let g=0;g<s.length;g++){let f=n.slice();f.length>0?f[f.length-1]=`${f[f.length-1]}[${g}]`:f.push(`[${g}]`);let h=s[g],m=_a(e,t,u+1,f,h,o);i.push(...m);}return i}else {if(typeof s!="object"||s===null||!(d in s))return i;n.push(d),s=s[d];}}let l=n.join("."),c=_p(s);if(Array.isArray(c)&&o&&Object.keys(o).length>0)for(let u=0;u<c.length;u++)i.push({displayPath:`${l}[${u}]`,value:c[u]});else i.push({displayPath:l,value:c});return i}function w0(e,t){let r;if(t.computations)r=t.computations;else {r={};for(let i in t){let l={expression:t[i].expression};r[i]=l;}}let n=_o(r),a=JSON.parse(JSON.stringify(e)),o=[];for(let i of n){let s=r[i],l=fn(s.expression),c=i.split("."),u={targetPath:i,items:[]},d=(f,h,m=false,p={},v,y)=>{let x=null;if(Object.keys(p).length>0&&y)try{let w=Object.keys(p).map(Number).sort((_,E)=>E-_);if(w.length>0){let _=w[0],E=y.slice(0,_+1);x=wa(h,E,p,!1);}}catch{}if(f.literal)return {tokens:[{type:"number",value:f.value}],value:f.value};if(f.path){let w=f.path.split(".");if(w.includes("*"))if(Object.keys(p).length>0){let _=Sp(h,w,p);if(Array.isArray(_)){let E=_a(h,w,0,[],void 0,p),C=E.map(T=>T.value),P=E.map(T=>T.displayPath);return {tokens:[],value:C,operandInfos:[{value:C,sources:P}]}}else {let E=nN(w,p);return {tokens:[{type:"number",value:_,sourcePath:E}],value:_}}}else {let _=_a(h,w),E=_.map(P=>P.value),C=_.map(P=>P.displayPath);return {tokens:[],value:E,operandInfos:[{value:E,sources:C}]}}else {let _=null;return x!==null&&(_=Vn(x,w)),_===null&&(_=Vn(h,w)),{tokens:[{type:"number",value:_,sourcePath:f.path}],value:_}}}if(f.operation&&f.operands){let w=null;(f.operation==="$sum"||f.operation==="$average"||f.operation==="$min"||f.operation==="$max")&&f.operands.length>0&&(w=d(f.operands[0],h,false,p,void 0,y));let _=f.operands.map((N,S)=>{if(S===0&&w!==null)return w;let b=false;if(f.operation==="$sum"||f.operation==="$average"||f.operation==="$min"||f.operation==="$max"){let k=w&&Array.isArray(w.value),D=N.path&&!N.operation&&(!N.path.includes(".")||!N.path.split(".")[0].includes("["));b=S===1&&k&&D;}else f.operation==="$flatten"?b=S===1:f.operation==="$lookup"?b=S===1||S===2||S===4||S===5:(f.operation==="$match"||f.operation==="$filter")&&(b=S===1||S===2||f.operation==="$match"&&S===4);return b&&N.path&&!N.path.includes("*")?{tokens:[],value:N.path}:d(N,h,false,p,void 0,y)}),E=_.map(N=>N.value),C=Hl[f.operation],P=C(E),T=[];if(T.push({type:"text",value:"("}),f.operation==="$sum"||f.operation==="$average"){let N=Array.isArray(_[0]?.value)?_[0].value:[],S=_[0].operandInfos?.[0]?.sources||[];if(_.length>1&&_[1].operandInfos?.[0]?.sources)N=_[1].operandInfos[0].value||_[1].value,S=_[1].operandInfos[0].sources||[];else if(_.length>1&&typeof _[1]?.value=="string"&&_[1].value!==""){let b=_[1].value,k=b.split("."),D=[],O=k.includes("*");if(N.forEach(($,A)=>{if(Array.isArray($))$.forEach((F,X)=>{if(!(F==null||typeof F!="object"))if(O){let H=S[A]?`${S[A]}[${X}]`:void 0;_a(F,k,0,H?[H]:[]).forEach(({displayPath:Q,value:z})=>{z!=null&&D.push({value:z,sourcePath:Q});});}else {let H=F;for(let L of k){if(H==null||typeof H!="object")return;H=H[L];}if(H!=null){let L=S[A]?`${S[A]}[${X}].${b}`:void 0;D.push({value:H,sourcePath:L});}}});else {if($==null||typeof $!="object")return;if(O){let F=S[A]||void 0;_a($,k,0,F?[F]:[]).forEach(({displayPath:H,value:L})=>{L!=null&&D.push({value:L,sourcePath:H});});}else {let F=$;for(let X of k){if(F==null||typeof F!="object")return;F=F[X];}if(F!=null){let X=S[A]?`${S[A]}.${b}`:void 0;D.push({value:F,sourcePath:X});}}}}),N=D.map($=>$.value),S=D.map($=>$.sourcePath),f.operation==="$sum")P=N.reduce(($,A)=>$.plus(A===null?0:A),new Ge(0)).toNumber();else if(f.operation==="$average"){let $=N.reduce((A,F)=>A.plus(F===null?0:F),new Ge(0));P=N.length>0?$.div(N.length).toNumber():0;}}if(f.operation==="$average"&&T.push({type:"text",value:"("}),N.forEach((b,k)=>{k>0&&T.push({type:"text",value:"+"}),T.push({type:"number",value:b,sourcePath:S[k]});}),f.operation==="$average"){T.push({type:"text",value:")"});let b=N.length||1;T.push({type:"text",value:"/"}),T.push({type:"number",value:b});}}else if(f.operation==="$min")if(Array.isArray(_[0]?.value)){let N=_[0].value,S=_[0].operandInfos?.[0]?.sources||[];if(_.length>1&&typeof _[1]?.value=="string"&&_[1].value!==""){let b=_[1].value,k=b.split("."),D=[],O=k.includes("*");N.forEach(($,A)=>{if(Array.isArray($))$.forEach((F,X)=>{if(!(F==null||typeof F!="object"))if(O){let H=S[A]?`${S[A]}[${X}]`:void 0;_a(F,k,0,H?[H]:[]).forEach(({displayPath:Q,value:z})=>{z!=null&&D.push({value:z,sourcePath:Q});});}else {let H=F;for(let L of k){if(H==null||typeof H!="object")return;H=H[L];}if(H!=null){let L=S[A]?`${S[A]}[${X}].${b}`:void 0;D.push({value:H,sourcePath:L});}}});else {if($==null||typeof $!="object")return;if(O){let F=S[A]||void 0;_a($,k,0,F?[F]:[]).forEach(({displayPath:H,value:L})=>{L!=null&&D.push({value:L,sourcePath:H});});}else {let F=$;for(let X of k){if(F==null||typeof F!="object")return;F=F[X];}if(F!=null){let X=S[A]?`${S[A]}.${b}`:void 0;D.push({value:F,sourcePath:X});}}}}),N=D.map($=>$.value),S=D.map($=>$.sourcePath),P=N.length>0?Math.min(...N):0;}T.push({type:"text",value:"MIN(["}),N.forEach((b,k)=>{k>0&&T.push({type:"text",value:","}),T.push({type:"number",value:b,sourcePath:S[k]});}),T.push({type:"text",value:"]"});}else T.push({type:"text",value:"MIN("}),_.forEach((N,S)=>{S>0&&T.push({type:"text",value:","}),T.push(...N.tokens);}),T.push({type:"text",value:")"});else if(f.operation==="$max")if(Array.isArray(_[0]?.value)){let N=_[0].value,S=_[0].operandInfos?.[0]?.sources||[];if(_.length>1&&typeof _[1]?.value=="string"&&_[1].value!==""){let b=_[1].value,k=b.split("."),D=[],O=k.includes("*");N.forEach(($,A)=>{if(Array.isArray($))$.forEach((F,X)=>{if(!(F==null||typeof F!="object"))if(O){let H=S[A]?`${S[A]}[${X}]`:void 0;_a(F,k,0,H?[H]:[]).forEach(({displayPath:Q,value:z})=>{z!=null&&D.push({value:z,sourcePath:Q});});}else {let H=F;for(let L of k){if(H==null||typeof H!="object")return;H=H[L];}if(H!=null){let L=S[A]?`${S[A]}[${X}].${b}`:void 0;D.push({value:H,sourcePath:L});}}});else {if($==null||typeof $!="object")return;if(O){let F=S[A]||void 0;_a($,k,0,F?[F]:[]).forEach(({displayPath:H,value:L})=>{L!=null&&D.push({value:L,sourcePath:H});});}else {let F=$;for(let X of k){if(F==null||typeof F!="object")return;F=F[X];}if(F!=null){let X=S[A]?`${S[A]}.${b}`:void 0;D.push({value:F,sourcePath:X});}}}}),N=D.map($=>$.value),S=D.map($=>$.sourcePath),P=N.length>0?Math.max(...N):0;}T.push({type:"text",value:"MAX(["}),N.forEach((b,k)=>{k>0&&T.push({type:"text",value:","}),T.push({type:"number",value:b,sourcePath:S[k]});}),T.push({type:"text",value:"]"});}else T.push({type:"text",value:"MAX("}),_.forEach((N,S)=>{S>0&&T.push({type:"text",value:","}),T.push(...N.tokens);}),T.push({type:"text",value:")"});else if(f.operation==="$filter"){let N=_[0],S=_[1]?.value||"",b=_[2]?.value||"=",k=_[3]?.value,D=[],O=[];if(Array.isArray(N?.value)&&(D=N.value,O=N.operandInfos?.[0]?.sources||[],O.length===0||O.every(X=>X===void 0))){let X=f.operands[0];X?.path&&(O=D.map((H,L)=>`${X.path}[${L}]`));}let $=[];D.forEach((X,H)=>{let L=X;if(S!==""){let z=String(S).split(".");for(let ae of z){if(L==null||typeof L!="object"){L=null;break}L=L[ae];}L===void 0&&(L=null);}let Q=false;switch(b){case "=":case "==":Q=L===k;break;case "!=":Q=L!==k;break;case ">":Q=L>k;break;case ">=":Q=L>=k;break;case "<":Q=L<k;break;case "<=":Q=L<=k;break;case "contains":let z=String(L).toLowerCase(),ae=String(k).toLowerCase();Q=z.includes(ae);break}Q&&$.push({value:X,sourcePath:O[H]});});let A=$.map(X=>X.value),F=$.map(X=>X.sourcePath);return {tokens:[],value:A,operandInfos:[{value:A,sources:F}]}}else if(f.operation==="$flatten"){let N=_[0],S=_.length>1?_[1]?.value:"",b=[],k=[];if(Array.isArray(N?.value)&&(b=N.value,k=N.operandInfos?.[0]?.sources||[],k.length===0||k.every(A=>A===void 0))){let A=f.operands[0];A?.path&&(k=b.map((F,X)=>`${A.path}[${X}]`));}let D=[];S&&typeof S=="string"&&S!==""?b.forEach((A,F)=>{if(A==null||typeof A!="object")return;let X=String(S).split("."),H=A;for(let L of X){if(H==null||typeof H!="object"){H=null;break}H=H[L];}Array.isArray(H)&&H.forEach((L,Q)=>{let z=k[F]?`${k[F]}.${S}[${Q}]`:void 0;D.push({value:L,sourcePath:z});});}):b.forEach((A,F)=>{Array.isArray(A)?A.forEach((X,H)=>{let L=k[F]?`${k[F]}[${H}]`:void 0;D.push({value:X,sourcePath:L});}):D.push({value:A,sourcePath:k[F]});});let O=D.map(A=>A.value),$=D.map(A=>A.sourcePath);return {tokens:[],value:O,operandInfos:[{value:O,sources:$}]}}else if(f.operation==="$lookup"){let N=_[0],S=_[1]?.value||"",b=_[2]?.value||"=",k=_[3]?.value,D=_.length>4?_[4]?.value:"";_.length>5?_[5]?.value:"exact";let $=[],A=[];if(Array.isArray(N?.value)&&($=N.value,A=N.operandInfos?.[0]?.sources||[],A.length===0||A.every(H=>H===void 0))){let H=f.operands[0];H?.path&&(A=$.map((L,Q)=>`${H.path}[${Q}]`));}let F=-1;for(let H=0;H<$.length;H++){let Q=$[H];if(S!==""){let ae=String(S).split(".");for(let M of ae){if(Q==null||typeof Q!="object"){Q=null;break}Q=Q[M];}Q===void 0&&(Q=null);}let z=false;switch(b){case "=":case "==":z=Q===k;break;case "!=":z=Q!==k;break;case ">":z=Q>k;break;case ">=":z=Q>=k;break;case "<":z=Q<k;break;case "<=":z=Q<=k;break;case "contains":let ae=String(Q).toLowerCase(),M=String(k).toLowerCase();z=ae.includes(M);break}if(z){F=H;break}}let X=v;return F>=0&&A[F]&&(D&&D!==""?X=`${A[F]}.${D}`:X=A[F]),{tokens:[{type:"text",value:"("},{type:"text",value:"="},{type:"number",value:P,sourcePath:X},{type:"text",value:")"}],value:P}}else {if(f.operation==="$match")return {tokens:[{type:"text",value:"("},{type:"text",value:"="},{type:"number",value:P,sourcePath:v},{type:"text",value:")"}],value:P};if(f.operation==="$count"){let N=Array.isArray(_[0]?.value)?_[0].value:[];_[1]?.value;T.push({type:"text",value:"count("}),T.push(..._[1].tokens),T.push({type:"text",value:" in ["}),N.forEach((b,k)=>{k>0&&T.push({type:"text",value:","}),T.push({type:"number",value:b});}),T.push({type:"text",value:"]"});}else if(f.operation==="$abs")T.push({type:"text",value:"ABS("}),T.push(..._[0].tokens),T.push({type:"text",value:")"});else if(f.operation==="$sqrt")T.push({type:"text",value:"SQRT("}),T.push(..._[0].tokens),T.push({type:"text",value:")"});else if(f.operation==="$log")T.push({type:"text",value:"LOG("}),T.push(..._[0].tokens),_.length>1&&(T.push({type:"text",value:", "}),T.push(..._[1].tokens)),T.push({type:"text",value:")"});else if(f.operation==="$pow")T.push({type:"text",value:"POW("}),T.push(..._[0].tokens),T.push({type:"text",value:", "}),T.push(..._[1].tokens),T.push({type:"text",value:")"});else if(f.operation==="$add"||f.operation==="$subtract"||f.operation==="$multiply"||f.operation==="$divide"){let N={$add:"+",$subtract:"-",$multiply:"*",$divide:"/"};_.forEach((S,b)=>{if(b>0&&T.push({type:"text",value:N[f.operation]}),S.tokens.length>1){let k=f.operands[b].operation&&(f.operation==="$multiply"||f.operation==="$divide")&&(f.operands[b].operation==="$add"||f.operands[b].operation==="$subtract");k&&T.push({type:"text",value:"("}),T.push(...S.tokens),k&&T.push({type:"text",value:")"});}else T.push(...S.tokens);});}else f.operation==="$concat"?_.forEach((N,S)=>{S>0&&T.push({type:"text",value:"+"}),T.push(...N.tokens);}):f.operation==="$eq"?_.forEach((N,S)=>{S>0&&T.push({type:"text",value:"=="}),T.push(...N.tokens);}):f.operation==="$gt"?_.forEach((N,S)=>{S>0&&T.push({type:"text",value:">"}),T.push(...N.tokens);}):f.operation==="$gte"?_.forEach((N,S)=>{S>0&&T.push({type:"text",value:">="}),T.push(...N.tokens);}):f.operation==="$lt"?_.forEach((N,S)=>{S>0&&T.push({type:"text",value:"<"}),T.push(...N.tokens);}):f.operation==="$lte"?_.forEach((N,S)=>{S>0&&T.push({type:"text",value:"<="}),T.push(...N.tokens);}):f.operation==="$and"?_.forEach((N,S)=>{S>0&&T.push({type:"text",value:" AND "}),T.push(...N.tokens);}):f.operation==="$or"?_.forEach((N,S)=>{S>0&&T.push({type:"text",value:" OR "}),T.push(...N.tokens);}):f.operation==="$if"?(T.push({type:"text",value:"IF("}),T.push(..._[0].tokens),T.push({type:"text",value:", "}),T.push(..._[1].tokens),T.push({type:"text",value:", "}),T.push(..._[2].tokens),T.push({type:"text",value:")"})):f.operation==="$not"&&(T.push({type:"text",value:"NOT("}),T.push(..._[0].tokens),T.push({type:"text",value:")"}));}return m&&(T.push({type:"text",value:"="}),T.push({type:"number",value:P,sourcePath:v})),T.push({type:"text",value:")"}),{tokens:T,value:P}}throw new Error("Unknown evaluation result type")};if(c.includes("*")){let f=c.map((m,p)=>m==="*"?p:-1).filter(m=>m!==-1),h=(m,p)=>{if(m>=f.length){let w=nN(c,p),_=d(l,a,true,p,w,c);u.items.push({displayPath:w,tokens:_.tokens});return}let v=f[m],y=c.slice(0,v),x=wa(a,y,p,false);if(Array.isArray(x))for(let w=0;w<x.length;w++){let _={...p,[v]:w};h(m+1,_);}};h(0,{});}else {let f=d(l,a,true,{},i,c);u.items.push({displayPath:i,tokens:f.tokens});}o.push(u),b0(a,i,s);}return o}function aN(e,t){let r=e,n=e;for(let a of t)if(a==="*"){r.type!=="array"&&(r.type="array"),(!r.items||typeof r.items!="object")&&(r.items={});let o=r.items;if(o.$ref){let i=o.$ref;if(i.startsWith("#/$defs/")){let s=i.substring(8);n.$defs&&n.$defs[s]?r=n.$defs[s]:r=o;}else r=o;}else r=o;}else {r.type!=="object"&&(r.type="object"),(!r.properties||typeof r.properties!="object")&&(r.properties={});let o=r.properties;if((!(a in o)||typeof o[a]!="object")&&(o[a]={}),r=o[a],r.$ref){let i=r.$ref;if(i.startsWith("#/$defs/")){let s=i.substring(8);n.$defs&&n.$defs[s]&&(r=n.$defs[s]);}}}return r}function _0(e,t){let r=x0(e,t),n=_o(r.computations),a=JSON.parse(JSON.stringify(e));for(let o of n){let i=r.computations[o],s=o.split("."),l;if(s.includes("*")){let d=s.lastIndexOf("*");l=[...s.slice(0,d+1),...s.slice(d+1,-1)];}else l=s.slice(0,-1);let c=s[s.length-1],u=aN(a,l);if(u.type!=="object"&&(u.type="object"),(!u.properties||typeof u.properties!="object")&&(u.properties={}),!(c in u.properties)){let d=fn(i.expression);if(!d){u.properties[c]={type:"string","X-ComputedField":true};continue}let g=Xu(d);if(g){let f;d.operands&&(f=d.operands.map(m=>{if(m.literal){let p=m.value;return typeof p=="string"?{type:"string"}:typeof p=="boolean"?{type:"boolean"}:typeof p=="number"?Number.isInteger(p)?{type:"integer"}:{type:"number"}:{type:"string"}}return {}}));let h=wp({operation:g},f);!h.type&&Object.keys(h).length===0&&(h.type="string"),u.properties[c]={...h,"X-ComputedField":true};}}}return a}function WF({projectId:e,authConfig:t,extractionsConfig:r={},jsonSchemaConfig:n={},children:a}){return e?jsx(Ew,{config:t,children:jsx(Iw,{children:jsx(Lw,{projectId:e,children:jsx(KF,{config:n,children:jsx(GS,{originId:e,initialLimit:r.initialLimit??50,initialOrder:r.initialOrder??"desc",initialHumanStatus:r.initialHumanStatus??"review_required",mode:r.mode??"full",children:a})})})})}):jsx("div",{className:"flex items-center justify-center h-screen",children:jsxs("div",{className:"text-center",children:[jsx("h2",{className:"text-2xl font-semibold text-gray-700",children:"Invalid Project ID"}),jsx("p",{className:"text-gray-500 mt-2",children:"No project ID was provided."})]})})}function KF({config:e,children:t}){let{project:r}=Fr(),n=useMemo(()=>{let o=r.published_config.json_schema;return e.includeComputedFields??true?(()=>{try{let s=o;return s=_0(s,r.published_config.computation_spec),s}catch(s){return console.warn("Skipping computed fields in schema due to error:",s instanceof Error?s.message:s),o}})():o},[r.published_config.json_schema,r.published_config.computation_spec,e.includeComputedFields]),a=useCallback(async o=>{e.enableSchemaUpdates&&e.persistJsonSchemaCallback?await e.persistJsonSchemaCallback(o):e.enableSchemaUpdates?console.warn("Schema updates are enabled but no persistJsonSchemaCallback was provided. Updates will not be persisted."):console.log("Schema update requested but updates are disabled (read-only mode):",o);},[e.enableSchemaUpdates,e.persistJsonSchemaCallback]);return jsx(BS,{computedSchema:n,jsonSchema:r.published_config.json_schema,persistJsonSchemaCallback:a,children:t})}function Ze({className:e,type:t,...r}){return jsx("input",{type:t,"data-slot":"input",className:R("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input flex h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",e),...r})}function oN({className:e,...t}){return jsx("textarea",{"data-slot":"input",className:R(e),...t})}function nr({className:e,...t}){return jsx(sN.Root,{"data-slot":"label",className:R("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}var Wl=FormProvider,lN=Rt.createContext({}),Sa=({...e})=>jsx(lN.Provider,{value:{name:e.name},children:jsx(Controller,{...e})}),S0=()=>{let e=Rt.useContext(lN),t=Rt.useContext(cN),{getFieldState:r}=useFormContext(),n=useFormState({name:e.name}),a=r(e.name,n);if(!e)throw new Error("useFormField should be used within <FormField>");let{id:o}=t;return {id:o,name:e.name,formItemId:`${o}-form-item`,formDescriptionId:`${o}-form-item-description`,formMessageId:`${o}-form-item-message`,...a}},cN=Rt.createContext({});function Hn({className:e,...t}){let r=Rt.useId();return jsx(cN.Provider,{value:{id:r},children:jsx("div",{"data-slot":"form-item",className:R("grid gap-2",e),...t})})}function vi({className:e,...t}){let{error:r,formItemId:n}=S0();return jsx(nr,{"data-slot":"form-label","data-error":!!r,className:R("data-[error=true]:text-destructive",e),htmlFor:n,...t})}function Jn({...e}){let{error:t,formItemId:r,formDescriptionId:n,formMessageId:a}=S0();return jsx(Slot,{"data-slot":"form-control",id:r,"aria-describedby":t?`${n} ${a}`:`${n}`,"aria-invalid":!!t,...e})}function td({className:e,...t}){let{error:r,formMessageId:n}=S0(),a=r?String(r?.message??""):t.children;return a?jsx("p",{"data-slot":"form-message",id:n,className:R("text-destructive text-sm",e),...t,children:a}):null}function No({className:e,...t}){return jsx(Tp.Root,{"data-slot":"checkbox",className:R("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:jsx(Tp.Indicator,{"data-slot":"checkbox-indicator",className:"flex items-center justify-center text-current transition-none",children:jsx(CheckIcon,{className:"size-3.5"})})})}function Cs({...e}){return jsx(Tt.Root,{"data-slot":"select",...e})}function Es({...e}){return jsx(Tt.Value,{"data-slot":"select-value",...e})}function Ps({className:e,size:t="default",children:r,...n}){return jsxs(Tt.Trigger,{"data-slot":"select-trigger","data-size":t,className:R("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[r,jsx(Tt.Icon,{asChild:true,children:jsx(ChevronDownIcon,{className:"size-4 opacity-50"})})]})}function Ts({className:e,children:t,position:r="popper",...n}){return jsx(Tt.Portal,{children:jsxs(Tt.Content,{"data-slot":"select-content",className:R("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:r,...n,children:[jsx(oM,{}),jsx(Tt.Viewport,{className:R("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),jsx(iM,{})]})})}function Wn({className:e,children:t,...r}){return jsxs(Tt.Item,{"data-slot":"select-item",className:R("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...r,children:[jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:jsx(Tt.ItemIndicator,{children:jsx(CheckIcon,{className:"size-4"})})}),jsx(Tt.ItemText,{children:t})]})}function oM({className:e,...t}){return jsx(Tt.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:R("flex cursor-default items-center justify-center py-1",e),...t,children:jsx(ChevronUpIcon,{className:"size-4"})})}function iM({className:e,...t}){return jsx(Tt.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:R("flex cursor-default items-center justify-center py-1",e),...t,children:jsx(ChevronDownIcon,{className:"size-4"})})}function rd({...e}){return jsx(Xa.Root,{"data-slot":"accordion",...e})}function nd({className:e,...t}){return jsx(Xa.Item,{"data-slot":"accordion-item",className:R("border-b last:border-b-0",e),...t})}function ad({className:e,children:t,hideChevron:r,...n}){return jsx(Xa.Header,{className:"flex",children:jsxs(Xa.Trigger,{"data-slot":"accordion-trigger",className:R("focus-visible:border-ring group focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",e),...n,children:[t,jsx(ChevronDownIcon,{className:R("text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200 ",r&&"opacity-0 group-hover:opacity-100 transition-opacity duration-200")})]})})}function od({className:e,children:t,...r}){return jsx(Xa.Content,{"data-slot":"accordion-content",className:"data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm",...r,children:jsx("div",{className:R("pt-0 pb-4",e),children:t})})}function fr({delayDuration:e=0,...t}){return jsx(Kn.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Me({...e}){return jsx(fr,{children:jsx(Kn.Root,{"data-slot":"tooltip",...e})})}function je({...e}){return jsx(Kn.Trigger,{"data-slot":"tooltip-trigger",...e})}function ze({className:e,sideOffset:t=0,children:r,...n}){return jsx(Kn.Portal,{children:jsxs(Kn.Content,{"data-slot":"tooltip-content",sideOffset:t,className:R("bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...n,children:[r,jsx(Kn.Arrow,{className:"bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}function Ue({className:e,...t}){return jsx("div",{"data-slot":"skeleton",className:R("bg-accent animate-pulse rounded-md",e),...t})}function Co({className:e,classNames:t,showOutsideDays:r=true,captionLayout:n="label",buttonVariant:a="ghost",formatters:o,components:i,...s}){let l=getDefaultClassNames();return jsx(DayPicker,{showOutsideDays:r,className:R("bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,e),captionLayout:n,formatters:{formatMonthDropdown:c=>c.toLocaleString("default",{month:"short"}),...o},classNames:{root:R("w-fit",l.root),months:R("flex gap-4 flex-col md:flex-row relative",l.months),month:R("flex flex-col w-full gap-4",l.month),nav:R("flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between",l.nav),button_previous:R(cs({variant:a}),"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",l.button_previous),button_next:R(cs({variant:a}),"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",l.button_next),month_caption:R("flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)",l.month_caption),dropdowns:R("w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5",l.dropdowns),dropdown_root:R("relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",l.dropdown_root),dropdown:R("absolute inset-0 opacity-0",l.dropdown),caption_label:R("select-none font-medium",n==="label"?"text-sm":"rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",l.caption_label),table:"w-full border-collapse",weekdays:R("flex",l.weekdays),weekday:R("text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none",l.weekday),week:R("flex w-full mt-2",l.week),week_number_header:R("select-none w-(--cell-size)",l.week_number_header),week_number:R("text-[0.8rem] select-none text-muted-foreground",l.week_number),day:R("relative w-full h-full p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",l.day),range_start:R("rounded-l-md bg-accent",l.range_start),range_middle:R("rounded-none",l.range_middle),range_end:R("rounded-r-md bg-accent",l.range_end),today:R("bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none",l.today),outside:R("text-muted-foreground aria-selected:text-muted-foreground",l.outside),disabled:R("text-muted-foreground opacity-50",l.disabled),hidden:R("invisible",l.hidden),...t},components:{Root:({className:c,rootRef:u,...d})=>jsx("div",{"data-slot":"calendar",ref:u,className:R(c),...d}),Chevron:({className:c,orientation:u,...d})=>u==="left"?jsx(ChevronLeftIcon,{className:R("size-4",c),...d}):u==="right"?jsx(ChevronRightIcon,{className:R("size-4",c),...d}):jsx(ChevronDownIcon,{className:R("size-4",c),...d}),DayButton:hM,WeekNumber:({children:c,...u})=>jsx("td",{...u,children:jsx("div",{className:"flex size-(--cell-size) items-center justify-center text-center",children:c})}),...i},...s})}function hM({className:e,day:t,modifiers:r,...n}){let a=getDefaultClassNames(),o=Rt.useRef(null);return Rt.useEffect(()=>{r.focused&&o.current?.focus();},[r.focused]),jsx(K,{ref:o,variant:"ghost",size:"icon","data-day":t.date.toLocaleDateString(),"data-selected-single":r.selected&&!r.range_start&&!r.range_end&&!r.range_middle,"data-range-start":r.range_start,"data-range-end":r.range_end,"data-range-middle":r.range_middle,className:R("data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",a.day,e),...n})}function Ht({...e}){return jsx(Eo.Root,{"data-slot":"popover",...e})}function Jt({...e}){return jsx(Eo.Trigger,{"data-slot":"popover-trigger",...e})}function Wt({className:e,align:t="center",sideOffset:r=4,...n}){return jsx(Eo.Portal,{children:jsx(Eo.Content,{"data-slot":"popover-content",align:t,sideOffset:r,className:R("rounded-xl shadow-[0_1px_2px_rgba(25,28,33,.06),0_0_2px_theme(colors.gray.black/.08)] bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) border shadow-md outline-hidden",e),...n})})}function pr({className:e,...t}){return jsx("textarea",{"data-slot":"textarea",className:R("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}var pN={retab_rdylbu:[{pos:0,color:[250,110,110]},{pos:.5,color:[250,195,0]},{pos:1,color:[80,100,240]}],retab_rdylgn:[{pos:0,color:[250,110,110]},{pos:.5,color:[250,195,0]},{pos:1,color:[80,240,135]}],Reds:[{pos:0,color:[255,245,240]},{pos:.1,color:[254,229,216]},{pos:.2,color:[253,202,181]},{pos:.3,color:[252,171,143]},{pos:.4,color:[252,138,106]},{pos:.5,color:[251,105,74]},{pos:.6,color:[241,68,50]},{pos:.7,color:[217,37,35]},{pos:.8,color:[188,20,26]},{pos:.9,color:[152,12,19]},{pos:1,color:[103,0,13]}],hot:[{pos:0,color:[11,0,0]},{pos:.1,color:[76,0,0]},{pos:.2,color:[144,0,0]},{pos:.3,color:[210,0,0]},{pos:.4,color:[255,23,0]},{pos:.5,color:[255,92,0]},{pos:.6,color:[255,157,0]},{pos:.7,color:[255,225,0]},{pos:.8,color:[255,255,54]},{pos:.9,color:[255,255,157]},{pos:1,color:[255,255,255]}],afmhot:[{pos:0,color:[0,0,0]},{pos:.1,color:[50,0,0]},{pos:.2,color:[102,0,0]},{pos:.3,color:[152,24,0]},{pos:.4,color:[204,77,0]},{pos:.5,color:[255,128,1]},{pos:.6,color:[255,178,51]},{pos:.7,color:[255,230,103]},{pos:.8,color:[255,255,153]},{pos:.9,color:[255,255,205]},{pos:1,color:[255,255,255]}],gist_heat:[{pos:0,color:[0,0,0]},{pos:.1,color:[38,0,0]},{pos:.2,color:[77,0,0]},{pos:.3,color:[114,0,0]},{pos:.4,color:[153,0,0]},{pos:.5,color:[192,1,0]},{pos:.6,color:[229,51,0]},{pos:.7,color:[255,103,0]},{pos:.8,color:[255,153,51]},{pos:.9,color:[255,205,155]},{pos:1,color:[255,255,255]}],YlOrRd:[{pos:0,color:[255,255,204]},{pos:.1,color:[255,241,169]},{pos:.2,color:[254,225,135]},{pos:.3,color:[254,202,102]},{pos:.4,color:[254,171,73]},{pos:.5,color:[253,140,60]},{pos:.6,color:[252,91,46]},{pos:.7,color:[237,46,33]},{pos:.8,color:[212,16,32]},{pos:.9,color:[176,0,38]},{pos:1,color:[128,0,38]}],retab_YlOrRd:[{pos:0,color:[255,255,255]},{pos:.1,color:[255,241,169]},{pos:.2,color:[254,225,135]},{pos:.3,color:[254,202,102]},{pos:.4,color:[254,171,73]},{pos:.5,color:[253,140,60]},{pos:.6,color:[252,91,46]},{pos:.7,color:[237,46,33]},{pos:.8,color:[212,16,32]},{pos:.9,color:[176,0,38]},{pos:1,color:[128,0,38]}],OrRd:[{pos:0,color:[255,247,236]},{pos:.1,color:[254,235,208]},{pos:.2,color:[253,220,175]},{pos:.3,color:[253,202,148]},{pos:.4,color:[253,178,123]},{pos:.5,color:[252,140,89]},{pos:.6,color:[242,109,75]},{pos:.7,color:[224,68,47]},{pos:.8,color:[201,29,19]},{pos:.9,color:[168,0,0]},{pos:1,color:[127,0,0]}],bone:[{pos:0,color:[0,0,0]},{pos:.1,color:[22,22,30]},{pos:.2,color:[45,45,62]},{pos:.3,color:[66,66,93]},{pos:.4,color:[89,92,121]},{pos:.5,color:[112,123,144]},{pos:.6,color:[134,154,166]},{pos:.7,color:[157,185,188]},{pos:.8,color:[185,210,210]},{pos:.9,color:[221,233,233]},{pos:1,color:[255,255,255]}],RdBu:[{pos:0,color:[165,0,38]},{pos:.2,color:[215,48,39]},{pos:.4,color:[244,109,67]},{pos:.5,color:[253,174,97]},{pos:.6,color:[254,224,144]},{pos:.8,color:[171,217,233]},{pos:1,color:[49,54,149]}],RdGn:[{pos:0,color:[165,0,38]},{pos:.2,color:[215,48,39]},{pos:.4,color:[244,109,67]},{pos:.5,color:[253,174,97]},{pos:.6,color:[254,224,144]},{pos:.8,color:[166,217,106]},{pos:1,color:[26,152,80]}],jet:[{pos:0,color:[0,0,128]},{pos:.1,color:[0,0,241]},{pos:.2,color:[0,76,255]},{pos:.3,color:[0,176,255]},{pos:.4,color:[41,255,206]},{pos:.5,color:[125,255,122]},{pos:.6,color:[206,255,41]},{pos:.7,color:[255,196,0]},{pos:.8,color:[255,104,0]},{pos:.9,color:[241,8,0]},{pos:1,color:[128,0,0]}],pink:[{pos:0,color:[30,0,0]},{pos:.1,color:[104,65,65]},{pos:.2,color:[145,93,93]},{pos:.3,color:[175,114,114]},{pos:.4,color:[198,139,132]},{pos:.5,color:[208,172,148]},{pos:.6,color:[218,198,161]},{pos:.7,color:[228,223,174]},{pos:.8,color:[237,237,198]},{pos:.9,color:[247,247,229]},{pos:1,color:[255,255,255]}],coolwarm:[{pos:0,color:[59,76,192]},{pos:.25,color:[141,176,254]},{pos:.5,color:[221,220,220]},{pos:.75,color:[244,152,122]},{pos:1,color:[180,4,38]}],summer:[{pos:0,color:[0,128,102]},{pos:.25,color:[64,159,102]},{pos:.5,color:[128,191,102]},{pos:.75,color:[191,223,102]},{pos:1,color:[255,255,102]}],wistia:[{pos:0,color:[0,0,0]},{pos:.25,color:[128,92,28]},{pos:.5,color:[255,192,64]},{pos:.75,color:[255,224,128]},{pos:1,color:[255,255,191]}],RdYlBu:[{pos:0,color:[165,0,38]},{pos:.2,color:[215,48,39]},{pos:.4,color:[244,109,67]},{pos:.5,color:[253,174,97]},{pos:.6,color:[254,224,144]},{pos:.8,color:[171,217,233]},{pos:1,color:[49,54,149]}],RdYlGn:[{pos:0,color:[165,0,38]},{pos:.2,color:[215,48,39]},{pos:.4,color:[244,109,67]},{pos:.5,color:[253,174,97]},{pos:.6,color:[254,224,139]},{pos:.8,color:[166,217,106]},{pos:1,color:[26,152,80]}]},mN=(e,t=0,r=1)=>Math.min(Math.max(e,t),r),E0=(e,t,r)=>e+(t-e)*r,hN=(e,t,r)=>[Math.round(E0(e[0],t[0],r)),Math.round(E0(e[1],t[1],r)),Math.round(E0(e[2],t[2],r))],gN=([e,t,r])=>"#"+[e,t,r].map(n=>n.toString(16).padStart(2,"0")).join("").toUpperCase();function Na(e,t,r=false,n){let a=pN[e],o=mN(t);r&&(o=1-o);let i;for(let s=0;s<a.length-1;s++){let l=a[s],c=a[s+1];if(o>=l.pos&&o<=c.pos){let u=(o-l.pos)/(c.pos-l.pos);i=hN(l.color,c.color,u);break}}if(i||(i=a[a.length-1].color),n!==void 0){let s=Math.min(Math.max(n,0),1),l=[255,255,255];i=[Math.round(i[0]*s+l[0]*(1-s)),Math.round(i[1]*s+l[1]*(1-s)),Math.round(i[2]*s+l[2]*(1-s))];}return gN(i)}var fN={};function P0(e,t,r=false,n){let a=`${e}|${r?"1":"0"}`,o=fN[a];if(!o){let c=pN[e];o=new Array(11);for(let u=0;u<=10;u++){let d=u/10,g=Math.round(d*10)/10;r&&(g=1-g);let f=c[c.length-1].color;for(let h=0;h<c.length-1;h++){let m=c[h],p=c[h+1];if(g>=m.pos&&g<=p.pos){let v=(g-m.pos)/(p.pos-m.pos);f=hN(m.color,p.color,v);break}}o[u]=f;}fN[a]=o;}let i=mN(t),s=Math.max(0,Math.min(10,Math.floor(i*10))),l=o[s];{let c=Math.min(Math.max(n,0),1),u=[255,255,255];l=[Math.round(l[0]*c+u[0]*(1-c)),Math.round(l[1]*c+u[1]*(1-c)),Math.round(l[2]*c+u[2]*(1-c))];}return gN(l)}var Po="retab_rdylgn",Zl="retab_YlOrRd";var Xl=true,To=false;var yN=.2,vN=.2;function Op(e){if(e===void 0||e===1)return "transparent";let t=[245,158,11],r=.4,n=[255,255,255];return "#"+[Math.round(t[0]*r+n[0]*(1-r)),Math.round(t[1]*r+n[1]*(1-r)),Math.round(t[2]*r+n[2]*(1-r))].map(o=>o.toString(16).padStart(2,"0")).join("").toUpperCase()}var yM=[{pattern:/(\d{1,2})\s+(\d{1,2})\s+(\d{4})/,dayIndex:1,monthIndex:2,yearIndex:3},{pattern:/(\d{1,2})\/(\d{1,2})\/(\d{4})/,dayIndex:1,monthIndex:2,yearIndex:3},{pattern:/(\d{1,2})-(\d{1,2})-(\d{4})/,dayIndex:1,monthIndex:2,yearIndex:3},{pattern:/(\d{1,2})\.(\d{1,2})\.(\d{4})/,dayIndex:1,monthIndex:2,yearIndex:3},{pattern:/(\d{4})-(\d{1,2})-(\d{1,2})/,yearIndex:1,monthIndex:2,dayIndex:3}],vM=/(\d{1,2}):(\d{1,2})(:(\d{1,2}))?(\s*(AM|PM))?/i,bM=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(\.\d{3})?Z?$/,xM=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})Z?$/,wM=/^(\d{4})-(\d{2})-(\d{2})$/;function _M(e){if(typeof e!="string")return null;let t={},r=e.trim();if(!r)return null;let n=r.match(bM);if(n)return t.year=parseInt(n[1],10),t.month=parseInt(n[2],10)-1,t.day=parseInt(n[3],10),t.hours=parseInt(n[4],10),t.minutes=parseInt(n[5],10),t.seconds=parseInt(n[6],10),t;let a=r.match(xM);if(a)return t.year=parseInt(a[1],10),t.month=parseInt(a[2],10)-1,t.day=parseInt(a[3],10),t.hours=parseInt(a[4],10),t.minutes=parseInt(a[5],10),t;let o=r.match(wM);if(o)return t.year=parseInt(o[1],10),t.month=parseInt(o[2],10)-1,t.day=parseInt(o[3],10),t;let i=new Date(r);if(!isNaN(i.getTime()))return t.year=i.getFullYear(),t.month=i.getMonth(),t.day=i.getDate(),t.hours=i.getHours(),t.minutes=i.getMinutes(),t.seconds=i.getSeconds(),t;for(let l of yM){let c=r.match(l.pattern);if(c){t.year=parseInt(c[l.yearIndex],10),t.month=parseInt(c[l.monthIndex],10)-1,t.day=parseInt(c[l.dayIndex],10),r=r.slice(c[0].length).trim();break}}let s=r.match(vM);if(s){let l=parseInt(s[1],10),c=parseInt(s[2],10),u=s[4]?parseInt(s[4],10):void 0,d=s[6]?s[6].toUpperCase():null;if(d){d==="PM"&&l!==12?l+=12:d==="AM"&&l===12&&(l=0);}t.hours=l,t.minutes=c,u!==void 0&&(t.seconds=u);}return t.year===void 0&&t.month===void 0&&t.day===void 0&&t.hours===void 0&&t.minutes===void 0&&t.seconds===void 0?null:t}function Zr(e,t){let r=_M(e);if(!r)return "";let n=d=>d!==void 0?String(d).padStart(2,"0"):"00",a=r.year!==void 0?String(r.year).padStart(4,"0"):"0000",o=n((r.month??0)+1),i=n(r.day??1),s=n(r.hours??0),l=n(r.minutes??0),c=n(r.seconds??0),u;return t.includes("T")?u=`${a}-${o}-${i}T${s}:${l}`:t.includes("-")?u=`${a}-${o}-${i}`:t.includes(":")?r.seconds!==void 0?u=`${s}:${l}:${c}`:u=`${s}:${l}`:u=`${a}-${o}-${i}`,u}function id(e){return Zr(e,"2000-01-01T00:00")||"2000-01-01T00:00"}function Dp(e){return Zr(e,"2000-01-01")||"2000-01-01"}function sd(e){return Zr(e,"00:00")||"00:00"}function ld(e){let t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return `${t}-${r}-${n}`}function pn(e,t,r=""){if(!e||!t)return e;let n=pn._SCHEMA_CACHE||new WeakMap;pn._SCHEMA_CACHE=n;let a=o=>{if(!o||typeof o!="object")return false;if(n.has(o))return n.get(o);let i=false;try{if(o.format&&(o.format==="date"||o.format==="date-time"||o.format==="iso-time"))i=!0;else if(o.type==="object"&&o.properties){for(let s of Object.keys(o.properties))if(a(o.properties[s])){i=!0;break}}else if(o.type==="array"&&o.items)i=a(o.items);else if(o.anyOf||o.oneOf||o.allOf){let s=o.anyOf||o.oneOf||o.allOf;for(let l of s)if(a(l)){i=!0;break}}}finally{n.set(o,i);}return i};if(Array.isArray(e))return !t.items||!a(t.items)?e:e.map((o,i)=>pn(o,t.items,`${r}[${i}]`));if(typeof e=="object"&&e!==null){let o={...e};return t.properties&&Object.keys(t.properties).forEach(i=>{if(i in o){let s=t.properties[i],l=r?`${r}.${i}`:i;if(s.format&&typeof o[i]=="string"){let c=o[i],u=null;try{switch(s.format){case "date":u=Zr(c,"2000-01-01");break;case "iso-time":u=Zr(c,"00:00");break;case "date-time":u=Zr(c,"2000-01-01T00:00:00");break}u&&u!==c&&(o[i]=u);}catch(d){console.warn(`autoFormatDateTimeFields: Failed to format ${l}:`,d);}}else (s.type==="object"||s.type==="array")&&a(s)&&(o[i]=pn(o[i],s,l));}}),o}return e}function Qa(e,t,{checkForDefaultPrevented:r=true}={}){return function(a){if(e?.(a),r===false||!a.defaultPrevented)return t?.(a)}}function bN(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t);}function SM(...e){return t=>{let r=false,n=e.map(a=>{let o=bN(a,t);return !r&&typeof o=="function"&&(r=true),o});if(r)return ()=>{for(let a=0;a<n.length;a++){let o=n[a];typeof o=="function"?o():bN(e[a],null);}}}}function Ca(...e){return Rt.useCallback(SM(...e),e)}function _N(e,t){let r=Rt.createContext(t),n=o=>{let{children:i,...s}=o,l=Rt.useMemo(()=>s,Object.values(s));return jsx(r.Provider,{value:l,children:i})};n.displayName=e+"Provider";function a(o){let i=Rt.useContext(r);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${o}\` must be used within \`${e}\``)}return [n,a]}function SN(e,t=[]){let r=[];function n(o,i){let s=Rt.createContext(i),l=r.length;r=[...r,i];let c=d=>{let{scope:g,children:f,...h}=d,m=g?.[e]?.[l]||s,p=Rt.useMemo(()=>h,Object.values(h));return jsx(m.Provider,{value:p,children:f})};c.displayName=o+"Provider";function u(d,g){let f=g?.[e]?.[l]||s,h=Rt.useContext(f);if(h)return h;if(i!==void 0)return i;throw new Error(`\`${d}\` must be used within \`${o}\``)}return [c,u]}let a=()=>{let o=r.map(i=>Rt.createContext(i));return function(s){let l=s?.[e]||o;return Rt.useMemo(()=>({[`__scope${e}`]:{...s,[e]:l}}),[s,l])}};return a.scopeName=e,[n,NM(a,...t)]}function NM(...e){let t=e[0];if(e.length===1)return t;let r=()=>{let n=e.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(o){let i=n.reduce((s,{useScope:l,scopeName:c})=>{let d=l(o)[`__scope${c}`];return {...s,...d}},{});return Rt.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return r.scopeName=t.scopeName,r}var ko=globalThis?.document?Rt.useLayoutEffect:()=>{};var CM=Rt[" useId ".trim().toString()]||(()=>{}),EM=0;function Ap(e){let[t,r]=Rt.useState(CM());return ko(()=>{r(n=>n??String(EM++));},[e]),e||(t?`radix-${t}`:"")}var PM=Rt[" useInsertionEffect ".trim().toString()]||ko;function CN({prop:e,defaultProp:t,onChange:r=()=>{},caller:n}){let[a,o,i]=TM({defaultProp:t,onChange:r}),s=e!==void 0,l=s?e:a;{let u=Rt.useRef(e!==void 0);Rt.useEffect(()=>{let d=u.current;d!==s&&console.warn(`${n} is changing from ${d?"controlled":"uncontrolled"} to ${s?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=s;},[s,n]);}let c=Rt.useCallback(u=>{if(s){let d=kM(u)?u(e):u;d!==e&&i.current?.(d);}else o(u);},[s,e,o,i]);return [l,c]}function TM({defaultProp:e,onChange:t}){let[r,n]=Rt.useState(e),a=Rt.useRef(r),o=Rt.useRef(t);return PM(()=>{o.current=t;},[t]),Rt.useEffect(()=>{a.current!==r&&(o.current?.(r),a.current=r);},[r,a]),[r,n,o]}function kM(e){return typeof e=="function"}var DM=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Cn=DM.reduce((e,t)=>{let r=createSlot(`Primitive.${t}`),n=Rt.forwardRef((a,o)=>{let{asChild:i,...s}=a,l=i?r:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=true),jsx(l,{...s,ref:o})});return n.displayName=`Primitive.${t}`,{...e,[t]:n}},{});function TN(e,t){e&&PN.flushSync(()=>e.dispatchEvent(t));}function xi(e){let t=Rt.useRef(e);return Rt.useEffect(()=>{t.current=e;}),Rt.useMemo(()=>(...r)=>t.current?.(...r),[])}function RN(e,t=globalThis?.document){let r=xi(e);Rt.useEffect(()=>{let n=a=>{a.key==="Escape"&&r(a);};return t.addEventListener("keydown",n,{capture:true}),()=>t.removeEventListener("keydown",n,{capture:true})},[r,t]);}var AM="DismissableLayer",k0="dismissableLayer.update",$M="dismissableLayer.pointerDownOutside",IM="dismissableLayer.focusOutside",ON,$N=Rt.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),R0=Rt.forwardRef((e,t)=>{let{disableOutsidePointerEvents:r=false,onEscapeKeyDown:n,onPointerDownOutside:a,onFocusOutside:o,onInteractOutside:i,onDismiss:s,...l}=e,c=Rt.useContext($N),[u,d]=Rt.useState(null),g=u?.ownerDocument??globalThis?.document,[,f]=Rt.useState({}),h=Ca(t,C=>d(C)),m=Array.from(c.layers),[p]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),v=m.indexOf(p),y=u?m.indexOf(u):-1,x=c.layersWithOutsidePointerEventsDisabled.size>0,w=y>=v,_=jM(C=>{let P=C.target,T=[...c.branches].some(N=>N.contains(P));!w||T||(a?.(C),i?.(C),C.defaultPrevented||s?.());},g),E=LM(C=>{let P=C.target;[...c.branches].some(N=>N.contains(P))||(o?.(C),i?.(C),C.defaultPrevented||s?.());},g);return RN(C=>{y===c.layers.size-1&&(n?.(C),!C.defaultPrevented&&s&&(C.preventDefault(),s()));},g),Rt.useEffect(()=>{if(u)return r&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(ON=g.body.style.pointerEvents,g.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(u)),c.layers.add(u),DN(),()=>{r&&c.layersWithOutsidePointerEventsDisabled.size===1&&(g.body.style.pointerEvents=ON);}},[u,g,r,c]),Rt.useEffect(()=>()=>{u&&(c.layers.delete(u),c.layersWithOutsidePointerEventsDisabled.delete(u),DN());},[u,c]),Rt.useEffect(()=>{let C=()=>f({});return document.addEventListener(k0,C),()=>document.removeEventListener(k0,C)},[]),jsx(Cn.div,{...l,ref:h,style:{pointerEvents:x?w?"auto":"none":void 0,...e.style},onFocusCapture:Qa(e.onFocusCapture,E.onFocusCapture),onBlurCapture:Qa(e.onBlurCapture,E.onBlurCapture),onPointerDownCapture:Qa(e.onPointerDownCapture,_.onPointerDownCapture)})});R0.displayName=AM;var FM="DismissableLayerBranch",MM=Rt.forwardRef((e,t)=>{let r=Rt.useContext($N),n=Rt.useRef(null),a=Ca(t,n);return Rt.useEffect(()=>{let o=n.current;if(o)return r.branches.add(o),()=>{r.branches.delete(o);}},[r.branches]),jsx(Cn.div,{...e,ref:a})});MM.displayName=FM;function jM(e,t=globalThis?.document){let r=xi(e),n=Rt.useRef(false),a=Rt.useRef(()=>{});return Rt.useEffect(()=>{let o=s=>{if(s.target&&!n.current){let c=function(){IN($M,r,u,{discrete:true});};let u={originalEvent:s};s.pointerType==="touch"?(t.removeEventListener("click",a.current),a.current=c,t.addEventListener("click",a.current,{once:true})):c();}else t.removeEventListener("click",a.current);n.current=false;},i=window.setTimeout(()=>{t.addEventListener("pointerdown",o);},0);return ()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",o),t.removeEventListener("click",a.current);}},[t,r]),{onPointerDownCapture:()=>n.current=true}}function LM(e,t=globalThis?.document){let r=xi(e),n=Rt.useRef(false);return Rt.useEffect(()=>{let a=o=>{o.target&&!n.current&&IN(IM,r,{originalEvent:o},{discrete:false});};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,r]),{onFocusCapture:()=>n.current=true,onBlurCapture:()=>n.current=false}}function DN(){let e=new CustomEvent(k0);document.dispatchEvent(e);}function IN(e,t,r,{discrete:n}){let a=r.originalEvent.target,o=new CustomEvent(e,{bubbles:false,cancelable:true,detail:r});t&&a.addEventListener(e,t,{once:true}),n?TN(a,o):a.dispatchEvent(o);}var O0="focusScope.autoFocusOnMount",D0="focusScope.autoFocusOnUnmount",FN={bubbles:false,cancelable:true},zM="FocusScope",A0=Rt.forwardRef((e,t)=>{let{loop:r=false,trapped:n=false,onMountAutoFocus:a,onUnmountAutoFocus:o,...i}=e,[s,l]=Rt.useState(null),c=xi(a),u=xi(o),d=Rt.useRef(null),g=Ca(t,m=>l(m)),f=Rt.useRef({paused:false,pause(){this.paused=true;},resume(){this.paused=false;}}).current;Rt.useEffect(()=>{if(n){let y=function(E){if(f.paused||!s)return;let C=E.target;s.contains(C)?d.current=C:wi(d.current,{select:true});},x=function(E){if(f.paused||!s)return;let C=E.relatedTarget;C!==null&&(s.contains(C)||wi(d.current,{select:true}));},w=function(E){if(document.activeElement===document.body)for(let P of E)P.removedNodes.length>0&&wi(s);};document.addEventListener("focusin",y),document.addEventListener("focusout",x);let _=new MutationObserver(w);return s&&_.observe(s,{childList:true,subtree:true}),()=>{document.removeEventListener("focusin",y),document.removeEventListener("focusout",x),_.disconnect();}}},[n,s,f.paused]),Rt.useEffect(()=>{if(s){jN.add(f);let m=document.activeElement;if(!s.contains(m)){let v=new CustomEvent(O0,FN);s.addEventListener(O0,c),s.dispatchEvent(v),v.defaultPrevented||(UM(WM(BN(s)),{select:true}),document.activeElement===m&&wi(s));}return ()=>{s.removeEventListener(O0,c),setTimeout(()=>{let v=new CustomEvent(D0,FN);s.addEventListener(D0,u),s.dispatchEvent(v),v.defaultPrevented||wi(m??document.body,{select:true}),s.removeEventListener(D0,u),jN.remove(f);},0);}}},[s,c,u,f]);let h=Rt.useCallback(m=>{if(!r&&!n||f.paused)return;let p=m.key==="Tab"&&!m.altKey&&!m.ctrlKey&&!m.metaKey,v=document.activeElement;if(p&&v){let y=m.currentTarget,[x,w]=qM(y);x&&w?!m.shiftKey&&v===w?(m.preventDefault(),r&&wi(x,{select:true})):m.shiftKey&&v===x&&(m.preventDefault(),r&&wi(w,{select:true})):v===y&&m.preventDefault();}},[r,n,f.paused]);return jsx(Cn.div,{tabIndex:-1,...i,ref:g,onKeyDown:h})});A0.displayName=zM;function UM(e,{select:t=false}={}){let r=document.activeElement;for(let n of e)if(wi(n,{select:t}),document.activeElement!==r)return}function qM(e){let t=BN(e),r=MN(t,e),n=MN(t.reverse(),e);return [r,n]}function BN(e){let t=[],r=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:n=>{let a=n.tagName==="INPUT"&&n.type==="hidden";return n.disabled||n.hidden||a?NodeFilter.FILTER_SKIP:n.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;r.nextNode();)t.push(r.currentNode);return t}function MN(e,t){for(let r of e)if(!VM(r,{upTo:t}))return r}function VM(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return true;for(;e;){if(t!==void 0&&e===t)return false;if(getComputedStyle(e).display==="none")return true;e=e.parentElement;}return false}function HM(e){return e instanceof HTMLInputElement&&"select"in e}function wi(e,{select:t=false}={}){if(e&&e.focus){let r=document.activeElement;e.focus({preventScroll:true}),e!==r&&HM(e)&&t&&e.select();}}var jN=JM();function JM(){let e=[];return {add(t){let r=e[0];t!==r&&r?.pause(),e=LN(e,t),e.unshift(t);},remove(t){e=LN(e,t),e[0]?.resume();}}}function LN(e,t){let r=[...e],n=r.indexOf(t);return n!==-1&&r.splice(n,1),r}function WM(e){return e.filter(t=>t.tagName!=="A")}var ZM="Portal",$0=Rt.forwardRef((e,t)=>{let{container:r,...n}=e,[a,o]=Rt.useState(false);ko(()=>o(true),[]);let i=r||a&&globalThis?.document?.body;return i?PN__default.createPortal(jsx(Cn.div,{...n,ref:t}),i):null});$0.displayName=ZM;function XM(e,t){return Rt.useReducer((r,n)=>t[r][n]??r,e)}var cd=e=>{let{present:t,children:r}=e,n=QM(t),a=typeof r=="function"?r({present:n.isPresent}):Rt.Children.only(r),o=Ca(n.ref,YM(a));return typeof r=="function"||n.isPresent?Rt.cloneElement(a,{ref:o}):null};cd.displayName="Presence";function QM(e){let[t,r]=Rt.useState(),n=Rt.useRef(null),a=Rt.useRef(e),o=Rt.useRef("none"),i=e?"mounted":"unmounted",[s,l]=XM(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return Rt.useEffect(()=>{let c=Fp(n.current);o.current=s==="mounted"?c:"none";},[s]),ko(()=>{let c=n.current,u=a.current;if(u!==e){let g=o.current,f=Fp(c);e?l("MOUNT"):f==="none"||c?.display==="none"?l("UNMOUNT"):l(u&&g!==f?"ANIMATION_OUT":"UNMOUNT"),a.current=e;}},[e,l]),ko(()=>{if(t){let c,u=t.ownerDocument.defaultView??window,d=f=>{let m=Fp(n.current).includes(CSS.escape(f.animationName));if(f.target===t&&m&&(l("ANIMATION_END"),!a.current)){let p=t.style.animationFillMode;t.style.animationFillMode="forwards",c=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=p);});}},g=f=>{f.target===t&&(o.current=Fp(n.current));};return t.addEventListener("animationstart",g),t.addEventListener("animationcancel",d),t.addEventListener("animationend",d),()=>{u.clearTimeout(c),t.removeEventListener("animationstart",g),t.removeEventListener("animationcancel",d),t.removeEventListener("animationend",d);}}else l("ANIMATION_END");},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(s),ref:Rt.useCallback(c=>{n.current=c?getComputedStyle(c):null,r(c);},[])}}function Fp(e){return e?.animationName||"none"}function YM(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning;return r?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,r=t&&"isReactWarning"in t&&t.isReactWarning,r?e.props.ref:e.props.ref||e.ref)}var I0=0;function VN(){Rt.useEffect(()=>{let e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??UN()),document.body.insertAdjacentElement("beforeend",e[1]??UN()),I0++,()=>{I0===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),I0--;}},[]);}function UN(){let e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var hn=function(){return hn=Object.assign||function(t){for(var r,n=1,a=arguments.length;n<a;n++){r=arguments[n];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(t[o]=r[o]);}return t},hn.apply(this,arguments)};function Mp(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,n=Object.getOwnPropertySymbols(e);a<n.length;a++)t.indexOf(n[a])<0&&Object.prototype.propertyIsEnumerable.call(e,n[a])&&(r[n[a]]=e[n[a]]);return r}function HN(e,t,r){for(var n=0,a=t.length,o;n<a;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return e.concat(o||Array.prototype.slice.call(t))}var ks="right-scroll-bar-position",Rs="width-before-scroll-bar",F0="with-scroll-bars-hidden",M0="--removed-body-scroll-bar-size";function jp(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function JN(e,t){var r=useState(function(){return {value:e,callback:t,facade:{get current(){return r.value},set current(n){var a=r.value;a!==n&&(r.value=n,r.callback(n,a));}}}})[0];return r.callback=t,r.facade}var tj=typeof window<"u"?Rt.useLayoutEffect:Rt.useEffect,WN=new WeakMap;function j0(e,t){var r=JN(null,function(n){return e.forEach(function(a){return jp(a,n)})});return tj(function(){var n=WN.get(r);if(n){var a=new Set(n),o=new Set(e),i=r.current;a.forEach(function(s){o.has(s)||jp(s,null);}),o.forEach(function(s){a.has(s)||jp(s,i);});}WN.set(r,e);},[e]),r}function rj(e){return e}function nj(e,t){t===void 0&&(t=rj);var r=[],n=false,a={read:function(){if(n)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return r.length?r[r.length-1]:e},useMedium:function(o){var i=t(o,n);return r.push(i),function(){r=r.filter(function(s){return s!==i});}},assignSyncMedium:function(o){for(n=true;r.length;){var i=r;r=[],i.forEach(o);}r={push:function(s){return o(s)},filter:function(){return r}};},assignMedium:function(o){n=true;var i=[];if(r.length){var s=r;r=[],s.forEach(o),i=r;}var l=function(){var u=i;i=[],u.forEach(o);},c=function(){return Promise.resolve().then(l)};c(),r={push:function(u){i.push(u),c();},filter:function(u){return i=i.filter(u),r}};}};return a}function L0(e){e===void 0&&(e={});var t=nj(null);return t.options=hn({async:true,ssr:false},e),t}var GN=function(e){var t=e.sideCar,r=Mp(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var n=t.read();if(!n)throw new Error("Sidecar medium not found");return Rt.createElement(n,hn({},r))};GN.isSideCarExport=true;function B0(e,t){return e.useMedium(t),GN}var Bp=L0();var z0=function(){},ud=Rt.forwardRef(function(e,t){var r=Rt.useRef(null),n=Rt.useState({onScrollCapture:z0,onWheelCapture:z0,onTouchMoveCapture:z0}),a=n[0],o=n[1],i=e.forwardProps,s=e.children,l=e.className,c=e.removeScrollBar,u=e.enabled,d=e.shards,g=e.sideCar,f=e.noRelative,h=e.noIsolation,m=e.inert,p=e.allowPinchZoom,v=e.as,y=v===void 0?"div":v,x=e.gapMode,w=Mp(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),_=g,E=j0([r,t]),C=hn(hn({},w),a);return Rt.createElement(Rt.Fragment,null,u&&Rt.createElement(_,{sideCar:Bp,removeScrollBar:c,shards:d,noRelative:f,noIsolation:h,inert:m,setCallbacks:o,allowPinchZoom:!!p,lockRef:r,gapMode:x}),i?Rt.cloneElement(Rt.Children.only(s),hn(hn({},C),{ref:E})):Rt.createElement(y,hn({},C,{className:l,ref:E}),s))});ud.defaultProps={enabled:true,removeScrollBar:true,inert:false};ud.classNames={fullWidth:Rs,zeroRight:ks};var XN=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function aj(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=XN();return t&&e.setAttribute("nonce",t),e}function oj(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t));}function ij(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e);}var U0=function(){var e=0,t=null;return {add:function(r){e==0&&(t=aj())&&(oj(t,r),ij(t)),e++;},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null);}}};var q0=function(){var e=U0();return function(t,r){Rt.useEffect(function(){return e.add(t),function(){e.remove();}},[t&&r]);}};var dd=function(){var e=q0(),t=function(r){var n=r.styles,a=r.dynamic;return e(n,a),null};return t};var sj={left:0,top:0,right:0,gap:0},V0=function(e){return parseInt(e||"",10)||0},lj=function(e){var t=window.getComputedStyle(document.body),r=t[e==="padding"?"paddingLeft":"marginLeft"],n=t[e==="padding"?"paddingTop":"marginTop"],a=t[e==="padding"?"paddingRight":"marginRight"];return [V0(r),V0(n),V0(a)]},H0=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return sj;var t=lj(e),r=document.documentElement.clientWidth,n=window.innerWidth;return {left:t[0],top:t[1],right:t[2],gap:Math.max(0,n-r+t[2]-t[0])}};var cj=dd(),Yl="data-scroll-locked",uj=function(e,t,r,n){var a=e.left,o=e.top,i=e.right,s=e.gap;return r===void 0&&(r="margin"),`
13
+ .`.concat(F0,` {
13
14
  overflow: hidden `).concat(n,`;
14
15
  padding-right: `).concat(s,"px ").concat(n,`;
15
16
  }
16
- body[`).concat(Sl,`] {
17
+ body[`).concat(Yl,`] {
17
18
  overflow: hidden `).concat(n,`;
18
19
  overscroll-behavior: contain;
19
20
  `).concat([t&&"position: relative ".concat(n,";"),r==="margin"&&`
20
- padding-left: `.concat(o,`px;
21
- padding-top: `).concat(a,`px;
21
+ padding-left: `.concat(a,`px;
22
+ padding-top: `).concat(o,`px;
22
23
  padding-right: `).concat(i,`px;
23
24
  margin-left:0;
24
25
  margin-top:0;
@@ -26,53 +27,60 @@ import*as kt from'react';import kt__default,{createContext,useContext,useMemo,us
26
27
  `),r==="padding"&&"padding-right: ".concat(s,"px ").concat(n,";")].filter(Boolean).join(""),`
27
28
  }
28
29
 
29
- .`).concat(os,` {
30
+ .`).concat(ks,` {
30
31
  right: `).concat(s,"px ").concat(n,`;
31
32
  }
32
33
 
33
- .`).concat(as,` {
34
+ .`).concat(Rs,` {
34
35
  margin-right: `).concat(s,"px ").concat(n,`;
35
36
  }
36
37
 
37
- .`).concat(os," .").concat(os,` {
38
+ .`).concat(ks," .").concat(ks,` {
38
39
  right: 0 `).concat(n,`;
39
40
  }
40
41
 
41
- .`).concat(as," .").concat(as,` {
42
+ .`).concat(Rs," .").concat(Rs,` {
42
43
  margin-right: 0 `).concat(n,`;
43
44
  }
44
45
 
45
- body[`).concat(Sl,`] {
46
- `).concat(m0,": ").concat(s,`px;
46
+ body[`).concat(Yl,`] {
47
+ `).concat(M0,": ").concat(s,`px;
47
48
  }
48
- `)},pN=function(){var e=parseInt(document.body.getAttribute(Sl)||"0",10);return isFinite(e)?e:0},wM=function(){kt.useEffect(function(){return document.body.setAttribute(Sl,(pN()+1).toString()),function(){var e=pN()-1;e<=0?document.body.removeAttribute(Sl):document.body.setAttribute(Sl,e.toString());}},[]);},S0=function(e){var t=e.noRelative,r=e.noImportant,n=e.gapMode,o=n===void 0?"margin":n;wM();var a=kt.useMemo(function(){return _0(o)},[o]);return kt.createElement(bM,{styles:xM(a,!t,o,r?"":"!important")})};var N0=false;if(typeof window<"u")try{Mu=Object.defineProperty({},"passive",{get:function(){return N0=!0,!0}}),window.addEventListener("test",Mu,Mu),window.removeEventListener("test",Mu,Mu);}catch{N0=false;}var Mu,is=N0?{passive:false}:false;var _M=function(e){return e.tagName==="TEXTAREA"},mN=function(e,t){if(!(e instanceof Element))return false;var r=window.getComputedStyle(e);return r[t]!=="hidden"&&!(r.overflowY===r.overflowX&&!_M(e)&&r[t]==="visible")},SM=function(e){return mN(e,"overflowY")},NM=function(e){return mN(e,"overflowX")},C0=function(e,t){var r=t.ownerDocument,n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var o=hN(e,n);if(o){var a=gN(e,n),i=a[1],s=a[2];if(i>s)return true}n=n.parentNode;}while(n&&n!==r.body);return false},CM=function(e){var t=e.scrollTop,r=e.scrollHeight,n=e.clientHeight;return [t,r,n]},EM=function(e){var t=e.scrollLeft,r=e.scrollWidth,n=e.clientWidth;return [t,r,n]},hN=function(e,t){return e==="v"?SM(t):NM(t)},gN=function(e,t){return e==="v"?CM(t):EM(t)},PM=function(e,t){return e==="h"&&t==="rtl"?-1:1},yN=function(e,t,r,n,o){var a=PM(e,window.getComputedStyle(t).direction),i=a*n,s=r.target,l=t.contains(s),c=false,u=i>0,d=0,m=0;do{if(!s)break;var h=gN(e,s),y=h[0],p=h[1],f=h[2],x=p-f-a*y;(y||x)&&hN(e,s)&&(d+=x,m+=y);var g=s.parentNode;s=g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE?g.host:g;}while(!l&&s!==document.body||l&&(t.contains(s)||t===s));return (u&&(Math.abs(d)<1||false)||!u&&(Math.abs(m)<1||false))&&(c=true),c};var gp=function(e){return "changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},vN=function(e){return [e.deltaX,e.deltaY]},bN=function(e){return e&&"current"in e?e.current:e},TM=function(e,t){return e[0]===t[0]&&e[1]===t[1]},kM=function(e){return `
49
+ `)},YN=function(){var e=parseInt(document.body.getAttribute(Yl)||"0",10);return isFinite(e)?e:0},dj=function(){Rt.useEffect(function(){return document.body.setAttribute(Yl,(YN()+1).toString()),function(){var e=YN()-1;e<=0?document.body.removeAttribute(Yl):document.body.setAttribute(Yl,e.toString());}},[]);},J0=function(e){var t=e.noRelative,r=e.noImportant,n=e.gapMode,a=n===void 0?"margin":n;dj();var o=Rt.useMemo(function(){return H0(a)},[a]);return Rt.createElement(cj,{styles:uj(o,!t,a,r?"":"!important")})};var W0=false;if(typeof window<"u")try{fd=Object.defineProperty({},"passive",{get:function(){return W0=!0,!0}}),window.addEventListener("test",fd,fd),window.removeEventListener("test",fd,fd);}catch{W0=false;}var fd,Os=W0?{passive:false}:false;var fj=function(e){return e.tagName==="TEXTAREA"},eC=function(e,t){if(!(e instanceof Element))return false;var r=window.getComputedStyle(e);return r[t]!=="hidden"&&!(r.overflowY===r.overflowX&&!fj(e)&&r[t]==="visible")},pj=function(e){return eC(e,"overflowY")},mj=function(e){return eC(e,"overflowX")},K0=function(e,t){var r=t.ownerDocument,n=t;do{typeof ShadowRoot<"u"&&n instanceof ShadowRoot&&(n=n.host);var a=tC(e,n);if(a){var o=rC(e,n),i=o[1],s=o[2];if(i>s)return true}n=n.parentNode;}while(n&&n!==r.body);return false},hj=function(e){var t=e.scrollTop,r=e.scrollHeight,n=e.clientHeight;return [t,r,n]},gj=function(e){var t=e.scrollLeft,r=e.scrollWidth,n=e.clientWidth;return [t,r,n]},tC=function(e,t){return e==="v"?pj(t):mj(t)},rC=function(e,t){return e==="v"?hj(t):gj(t)},yj=function(e,t){return e==="h"&&t==="rtl"?-1:1},nC=function(e,t,r,n,a){var o=yj(e,window.getComputedStyle(t).direction),i=o*n,s=r.target,l=t.contains(s),c=false,u=i>0,d=0,g=0;do{if(!s)break;var f=rC(e,s),h=f[0],m=f[1],p=f[2],v=m-p-o*h;(h||v)&&tC(e,s)&&(d+=v,g+=h);var y=s.parentNode;s=y&&y.nodeType===Node.DOCUMENT_FRAGMENT_NODE?y.host:y;}while(!l&&s!==document.body||l&&(t.contains(s)||t===s));return (u&&(Math.abs(d)<1||false)||!u&&(Math.abs(g)<1||false))&&(c=true),c};var zp=function(e){return "changedTouches"in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},aC=function(e){return [e.deltaX,e.deltaY]},oC=function(e){return e&&"current"in e?e.current:e},vj=function(e,t){return e[0]===t[0]&&e[1]===t[1]},bj=function(e){return `
49
50
  .block-interactivity-`.concat(e,` {pointer-events: none;}
50
51
  .allow-interactivity-`).concat(e,` {pointer-events: all;}
51
- `)},RM=0,Cl=[];function xN(e){var t=kt.useRef([]),r=kt.useRef([0,0]),n=kt.useRef(),o=kt.useState(RM++)[0],a=kt.useState(Fu)[0],i=kt.useRef(e);kt.useEffect(function(){i.current=e;},[e]),kt.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(o));var p=aN([e.lockRef.current],(e.shards||[]).map(bN)).filter(Boolean);return p.forEach(function(f){return f.classList.add("allow-interactivity-".concat(o))}),function(){document.body.classList.remove("block-interactivity-".concat(o)),p.forEach(function(f){return f.classList.remove("allow-interactivity-".concat(o))});}}},[e.inert,e.lockRef.current,e.shards]);var s=kt.useCallback(function(p,f){if("touches"in p&&p.touches.length===2||p.type==="wheel"&&p.ctrlKey)return !i.current.allowPinchZoom;var x=gp(p),g=r.current,v="deltaX"in p?p.deltaX:g[0]-x[0],w="deltaY"in p?p.deltaY:g[1]-x[1],N,S=p.target,_=Math.abs(v)>Math.abs(w)?"h":"v";if("touches"in p&&_==="h"&&S.type==="range")return false;var P=window.getSelection(),R=P&&P.anchorNode,E=R?R===S||R.contains(S):false;if(E)return false;var C=C0(_,S);if(!C)return true;if(C?N=_:(N=_==="v"?"h":"v",C=C0(_,S)),!C)return false;if(!n.current&&"changedTouches"in p&&(v||w)&&(n.current=N),!N)return true;var b=n.current||N;return yN(b,f,p,b==="h"?v:w)},[]),l=kt.useCallback(function(p){var f=p;if(!(!Cl.length||Cl[Cl.length-1]!==a)){var x="deltaY"in f?vN(f):gp(f),g=t.current.filter(function(N){return N.name===f.type&&(N.target===f.target||f.target===N.shadowParent)&&TM(N.delta,x)})[0];if(g&&g.should){f.cancelable&&f.preventDefault();return}if(!g){var v=(i.current.shards||[]).map(bN).filter(Boolean).filter(function(N){return N.contains(f.target)}),w=v.length>0?s(f,v[0]):!i.current.noIsolation;w&&f.cancelable&&f.preventDefault();}}},[]),c=kt.useCallback(function(p,f,x,g){var v={name:p,delta:f,target:x,should:g,shadowParent:OM(x)};t.current.push(v),setTimeout(function(){t.current=t.current.filter(function(w){return w!==v});},1);},[]),u=kt.useCallback(function(p){r.current=gp(p),n.current=void 0;},[]),d=kt.useCallback(function(p){c(p.type,vN(p),p.target,s(p,e.lockRef.current));},[]),m=kt.useCallback(function(p){c(p.type,gp(p),p.target,s(p,e.lockRef.current));},[]);kt.useEffect(function(){return Cl.push(a),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:m}),document.addEventListener("wheel",l,is),document.addEventListener("touchmove",l,is),document.addEventListener("touchstart",u,is),function(){Cl=Cl.filter(function(p){return p!==a}),document.removeEventListener("wheel",l,is),document.removeEventListener("touchmove",l,is),document.removeEventListener("touchstart",u,is);}},[]);var h=e.removeScrollBar,y=e.inert;return kt.createElement(kt.Fragment,null,y?kt.createElement(a,{styles:kM(o)}):null,h?kt.createElement(S0,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function OM(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var wN=y0(hp,xN);var _N=kt.forwardRef(function(e,t){return kt.createElement(Iu,an({},e,{ref:t,sideCar:wN}))});_N.classNames=Iu.classNames;var E0=_N;var DM=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},El=new WeakMap,vp=new WeakMap,bp={},P0=0,SN=function(e){return e&&(e.host||SN(e.parentNode))},AM=function(e,t){return t.map(function(r){if(e.contains(r))return r;var n=SN(r);return n&&e.contains(n)?n:(console.error("aria-hidden",r,"in not contained inside",e,". Doing nothing"),null)}).filter(function(r){return !!r})},$M=function(e,t,r,n){var o=AM(t,Array.isArray(e)?e:[e]);bp[r]||(bp[r]=new WeakMap);var a=bp[r],i=[],s=new Set,l=new Set(o),c=function(d){!d||s.has(d)||(s.add(d),c(d.parentNode));};o.forEach(c);var u=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(m){if(s.has(m))u(m);else try{var h=m.getAttribute(n),y=h!==null&&h!=="false",p=(El.get(m)||0)+1,f=(a.get(m)||0)+1;El.set(m,p),a.set(m,f),i.push(m),p===1&&y&&vp.set(m,!0),f===1&&m.setAttribute(r,"true"),y||m.setAttribute(n,"true");}catch(x){console.error("aria-hidden: cannot operate on ",m,x);}});};return u(t),s.clear(),P0++,function(){i.forEach(function(d){var m=El.get(d)-1,h=a.get(d)-1;El.set(d,m),a.set(d,h),m||(vp.has(d)||d.removeAttribute(n),vp.delete(d)),h||d.removeAttribute(r);}),P0--,P0||(El=new WeakMap,El=new WeakMap,vp=new WeakMap,bp={});}},NN=function(e,t,r){r===void 0&&(r="data-aria-hidden");var n=Array.from(Array.isArray(e)?e:[e]),o=DM(e);return o?(n.push.apply(n,Array.from(o.querySelectorAll("[aria-live], script"))),$M(n,o,r,"aria-hidden")):function(){return null}};var wp="Dialog",[PN]=MS(wp),[FM,lo]=PN(wp),TN=e=>{let{__scopeDialog:t,children:r,open:n,defaultOpen:o,onOpenChange:a,modal:i=true}=e,s=kt.useRef(null),l=kt.useRef(null),[c,u]=LS({prop:n,defaultProp:o??false,onChange:a,caller:wp});return jsx(FM,{scope:t,triggerRef:s,contentRef:l,contentId:lp(),titleId:lp(),descriptionId:lp(),open:c,onOpenChange:u,onOpenToggle:kt.useCallback(()=>u(d=>!d),[u]),modal:i,children:r})};TN.displayName=wp;var kN="DialogTrigger",RN=kt.forwardRef((e,t)=>{let{__scopeDialog:r,...n}=e,o=lo(kN,r),a=so(t,o.triggerRef);return jsx(mn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":o.open,"aria-controls":o.contentId,"data-state":R0(o.open),...n,ref:a,onClick:Uo(e.onClick,o.onOpenToggle)})});RN.displayName=kN;var T0="DialogPortal",[MM,ON]=PN(T0,{forceMount:void 0}),DN=e=>{let{__scopeDialog:t,forceMount:r,children:n,container:o}=e,a=lo(T0,t);return jsx(MM,{scope:t,forceMount:r,children:kt.Children.map(n,i=>jsx($u,{present:r||a.open,children:jsx(d0,{asChild:true,container:o,children:i})}))})};DN.displayName=T0;var xp="DialogOverlay",AN=kt.forwardRef((e,t)=>{let r=ON(xp,e.__scopeDialog),{forceMount:n=r.forceMount,...o}=e,a=lo(xp,e.__scopeDialog);return a.modal?jsx($u,{present:n||a.open,children:jsx(LM,{...o,ref:t})}):null});AN.displayName=xp;var jM=createSlot("DialogOverlay.RemoveScroll"),LM=kt.forwardRef((e,t)=>{let{__scopeDialog:r,...n}=e,o=lo(xp,r);return jsx(E0,{as:jM,allowPinchZoom:true,shards:[o.contentRef],children:jsx(mn.div,{"data-state":R0(o.open),...n,ref:t,style:{pointerEvents:"auto",...n.style}})})}),ss="DialogContent",$N=kt.forwardRef((e,t)=>{let r=ON(ss,e.__scopeDialog),{forceMount:n=r.forceMount,...o}=e,a=lo(ss,e.__scopeDialog);return jsx($u,{present:n||a.open,children:a.modal?jsx(BM,{...o,ref:t}):jsx(zM,{...o,ref:t})})});$N.displayName=ss;var BM=kt.forwardRef((e,t)=>{let r=lo(ss,e.__scopeDialog),n=kt.useRef(null),o=so(t,r.contentRef,n);return kt.useEffect(()=>{let a=n.current;if(a)return NN(a)},[]),jsx(IN,{...e,ref:o,trapFocus:r.open,disableOutsidePointerEvents:true,onCloseAutoFocus:Uo(e.onCloseAutoFocus,a=>{a.preventDefault(),r.triggerRef.current?.focus();}),onPointerDownOutside:Uo(e.onPointerDownOutside,a=>{let i=a.detail.originalEvent,s=i.button===0&&i.ctrlKey===true;(i.button===2||s)&&a.preventDefault();}),onFocusOutside:Uo(e.onFocusOutside,a=>a.preventDefault())})}),zM=kt.forwardRef((e,t)=>{let r=lo(ss,e.__scopeDialog),n=kt.useRef(false),o=kt.useRef(false);return jsx(IN,{...e,ref:t,trapFocus:false,disableOutsidePointerEvents:false,onCloseAutoFocus:a=>{e.onCloseAutoFocus?.(a),a.defaultPrevented||(n.current||r.triggerRef.current?.focus(),a.preventDefault()),n.current=false,o.current=false;},onInteractOutside:a=>{e.onInteractOutside?.(a),a.defaultPrevented||(n.current=true,a.detail.originalEvent.type==="pointerdown"&&(o.current=true));let i=a.target;r.triggerRef.current?.contains(i)&&a.preventDefault(),a.detail.originalEvent.type==="focusin"&&o.current&&a.preventDefault();}})}),IN=kt.forwardRef((e,t)=>{let{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:o,onCloseAutoFocus:a,...i}=e,s=lo(ss,r),l=kt.useRef(null),c=so(t,l);return oN(),jsxs(Fragment,{children:[jsx(u0,{asChild:true,loop:true,trapped:n,onMountAutoFocus:o,onUnmountAutoFocus:a,children:jsx(s0,{role:"dialog",id:s.contentId,"aria-describedby":s.descriptionId,"aria-labelledby":s.titleId,"data-state":R0(s.open),...i,ref:c,onDismiss:()=>s.onOpenChange(false)})}),jsxs(Fragment,{children:[jsx(UM,{titleId:s.titleId}),jsx(VM,{contentRef:l,descriptionId:s.descriptionId})]})]})}),k0="DialogTitle",FN=kt.forwardRef((e,t)=>{let{__scopeDialog:r,...n}=e,o=lo(k0,r);return jsx(mn.h2,{id:o.titleId,...n,ref:t})});FN.displayName=k0;var MN="DialogDescription",jN=kt.forwardRef((e,t)=>{let{__scopeDialog:r,...n}=e,o=lo(MN,r);return jsx(mn.p,{id:o.descriptionId,...n,ref:t})});jN.displayName=MN;var LN="DialogClose",BN=kt.forwardRef((e,t)=>{let{__scopeDialog:r,...n}=e,o=lo(LN,r);return jsx(mn.button,{type:"button",...n,ref:t,onClick:Uo(e.onClick,()=>o.onOpenChange(false))})});BN.displayName=LN;function R0(e){return e?"open":"closed"}var zN="DialogTitleWarning",[NY,UN]=FS(zN,{contentName:ss,titleName:k0,docsSlug:"dialog"}),UM=({titleId:e})=>{let t=UN(zN),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
52
+ `)},xj=0,tc=[];function iC(e){var t=Rt.useRef([]),r=Rt.useRef([0,0]),n=Rt.useRef(),a=Rt.useState(xj++)[0],o=Rt.useState(dd)[0],i=Rt.useRef(e);Rt.useEffect(function(){i.current=e;},[e]),Rt.useEffect(function(){if(e.inert){document.body.classList.add("block-interactivity-".concat(a));var m=HN([e.lockRef.current],(e.shards||[]).map(oC)).filter(Boolean);return m.forEach(function(p){return p.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),m.forEach(function(p){return p.classList.remove("allow-interactivity-".concat(a))});}}},[e.inert,e.lockRef.current,e.shards]);var s=Rt.useCallback(function(m,p){if("touches"in m&&m.touches.length===2||m.type==="wheel"&&m.ctrlKey)return !i.current.allowPinchZoom;var v=zp(m),y=r.current,x="deltaX"in m?m.deltaX:y[0]-v[0],w="deltaY"in m?m.deltaY:y[1]-v[1],_,E=m.target,C=Math.abs(x)>Math.abs(w)?"h":"v";if("touches"in m&&C==="h"&&E.type==="range")return false;var P=window.getSelection(),T=P&&P.anchorNode,N=T?T===E||T.contains(E):false;if(N)return false;var S=K0(C,E);if(!S)return true;if(S?_=C:(_=C==="v"?"h":"v",S=K0(C,E)),!S)return false;if(!n.current&&"changedTouches"in m&&(x||w)&&(n.current=_),!_)return true;var b=n.current||_;return nC(b,p,m,b==="h"?x:w)},[]),l=Rt.useCallback(function(m){var p=m;if(!(!tc.length||tc[tc.length-1]!==o)){var v="deltaY"in p?aC(p):zp(p),y=t.current.filter(function(_){return _.name===p.type&&(_.target===p.target||p.target===_.shadowParent)&&vj(_.delta,v)})[0];if(y&&y.should){p.cancelable&&p.preventDefault();return}if(!y){var x=(i.current.shards||[]).map(oC).filter(Boolean).filter(function(_){return _.contains(p.target)}),w=x.length>0?s(p,x[0]):!i.current.noIsolation;w&&p.cancelable&&p.preventDefault();}}},[]),c=Rt.useCallback(function(m,p,v,y){var x={name:m,delta:p,target:v,should:y,shadowParent:wj(v)};t.current.push(x),setTimeout(function(){t.current=t.current.filter(function(w){return w!==x});},1);},[]),u=Rt.useCallback(function(m){r.current=zp(m),n.current=void 0;},[]),d=Rt.useCallback(function(m){c(m.type,aC(m),m.target,s(m,e.lockRef.current));},[]),g=Rt.useCallback(function(m){c(m.type,zp(m),m.target,s(m,e.lockRef.current));},[]);Rt.useEffect(function(){return tc.push(o),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:g}),document.addEventListener("wheel",l,Os),document.addEventListener("touchmove",l,Os),document.addEventListener("touchstart",u,Os),function(){tc=tc.filter(function(m){return m!==o}),document.removeEventListener("wheel",l,Os),document.removeEventListener("touchmove",l,Os),document.removeEventListener("touchstart",u,Os);}},[]);var f=e.removeScrollBar,h=e.inert;return Rt.createElement(Rt.Fragment,null,h?Rt.createElement(o,{styles:bj(a)}):null,f?Rt.createElement(J0,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function wj(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var sC=B0(Bp,iC);var lC=Rt.forwardRef(function(e,t){return Rt.createElement(ud,hn({},e,{ref:t,sideCar:sC}))});lC.classNames=ud.classNames;var G0=lC;var _j=function(e){if(typeof document>"u")return null;var t=Array.isArray(e)?e[0]:e;return t.ownerDocument.body},rc=new WeakMap,qp=new WeakMap,Vp={},Z0=0,cC=function(e){return e&&(e.host||cC(e.parentNode))},Sj=function(e,t){return t.map(function(r){if(e.contains(r))return r;var n=cC(r);return n&&e.contains(n)?n:(console.error("aria-hidden",r,"in not contained inside",e,". Doing nothing"),null)}).filter(function(r){return !!r})},Nj=function(e,t,r,n){var a=Sj(t,Array.isArray(e)?e:[e]);Vp[r]||(Vp[r]=new WeakMap);var o=Vp[r],i=[],s=new Set,l=new Set(a),c=function(d){!d||s.has(d)||(s.add(d),c(d.parentNode));};a.forEach(c);var u=function(d){!d||l.has(d)||Array.prototype.forEach.call(d.children,function(g){if(s.has(g))u(g);else try{var f=g.getAttribute(n),h=f!==null&&f!=="false",m=(rc.get(g)||0)+1,p=(o.get(g)||0)+1;rc.set(g,m),o.set(g,p),i.push(g),m===1&&h&&qp.set(g,!0),p===1&&g.setAttribute(r,"true"),h||g.setAttribute(n,"true");}catch(v){console.error("aria-hidden: cannot operate on ",g,v);}});};return u(t),s.clear(),Z0++,function(){i.forEach(function(d){var g=rc.get(d)-1,f=o.get(d)-1;rc.set(d,g),o.set(d,f),g||(qp.has(d)||d.removeAttribute(n),qp.delete(d)),f||d.removeAttribute(r);}),Z0--,Z0||(rc=new WeakMap,rc=new WeakMap,qp=new WeakMap,Vp={});}},uC=function(e,t,r){r===void 0&&(r="data-aria-hidden");var n=Array.from(Array.isArray(e)?e:[e]),a=_j(e);return a?(n.push.apply(n,Array.from(a.querySelectorAll("[aria-live], script"))),Nj(n,a,r,"aria-hidden")):function(){return null}};var Jp="Dialog",[pC]=SN(Jp),[Ej,Ea]=pC(Jp),mC=e=>{let{__scopeDialog:t,children:r,open:n,defaultOpen:a,onOpenChange:o,modal:i=true}=e,s=Rt.useRef(null),l=Rt.useRef(null),[c,u]=CN({prop:n,defaultProp:a??false,onChange:o,caller:Jp});return jsx(Ej,{scope:t,triggerRef:s,contentRef:l,contentId:Ap(),titleId:Ap(),descriptionId:Ap(),open:c,onOpenChange:u,onOpenToggle:Rt.useCallback(()=>u(d=>!d),[u]),modal:i,children:r})};mC.displayName=Jp;var hC="DialogTrigger",gC=Rt.forwardRef((e,t)=>{let{__scopeDialog:r,...n}=e,a=Ea(hC,r),o=Ca(t,a.triggerRef);return jsx(Cn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":Y0(a.open),...n,ref:o,onClick:Qa(e.onClick,a.onOpenToggle)})});gC.displayName=hC;var X0="DialogPortal",[Pj,yC]=pC(X0,{forceMount:void 0}),vC=e=>{let{__scopeDialog:t,forceMount:r,children:n,container:a}=e,o=Ea(X0,t);return jsx(Pj,{scope:t,forceMount:r,children:Rt.Children.map(n,i=>jsx(cd,{present:r||o.open,children:jsx($0,{asChild:true,container:a,children:i})}))})};vC.displayName=X0;var Hp="DialogOverlay",bC=Rt.forwardRef((e,t)=>{let r=yC(Hp,e.__scopeDialog),{forceMount:n=r.forceMount,...a}=e,o=Ea(Hp,e.__scopeDialog);return o.modal?jsx(cd,{present:n||o.open,children:jsx(kj,{...a,ref:t})}):null});bC.displayName=Hp;var Tj=createSlot("DialogOverlay.RemoveScroll"),kj=Rt.forwardRef((e,t)=>{let{__scopeDialog:r,...n}=e,a=Ea(Hp,r);return jsx(G0,{as:Tj,allowPinchZoom:true,shards:[a.contentRef],children:jsx(Cn.div,{"data-state":Y0(a.open),...n,ref:t,style:{pointerEvents:"auto",...n.style}})})}),Ds="DialogContent",xC=Rt.forwardRef((e,t)=>{let r=yC(Ds,e.__scopeDialog),{forceMount:n=r.forceMount,...a}=e,o=Ea(Ds,e.__scopeDialog);return jsx(cd,{present:n||o.open,children:o.modal?jsx(Rj,{...a,ref:t}):jsx(Oj,{...a,ref:t})})});xC.displayName=Ds;var Rj=Rt.forwardRef((e,t)=>{let r=Ea(Ds,e.__scopeDialog),n=Rt.useRef(null),a=Ca(t,r.contentRef,n);return Rt.useEffect(()=>{let o=n.current;if(o)return uC(o)},[]),jsx(wC,{...e,ref:a,trapFocus:r.open,disableOutsidePointerEvents:true,onCloseAutoFocus:Qa(e.onCloseAutoFocus,o=>{o.preventDefault(),r.triggerRef.current?.focus();}),onPointerDownOutside:Qa(e.onPointerDownOutside,o=>{let i=o.detail.originalEvent,s=i.button===0&&i.ctrlKey===true;(i.button===2||s)&&o.preventDefault();}),onFocusOutside:Qa(e.onFocusOutside,o=>o.preventDefault())})}),Oj=Rt.forwardRef((e,t)=>{let r=Ea(Ds,e.__scopeDialog),n=Rt.useRef(false),a=Rt.useRef(false);return jsx(wC,{...e,ref:t,trapFocus:false,disableOutsidePointerEvents:false,onCloseAutoFocus:o=>{e.onCloseAutoFocus?.(o),o.defaultPrevented||(n.current||r.triggerRef.current?.focus(),o.preventDefault()),n.current=false,a.current=false;},onInteractOutside:o=>{e.onInteractOutside?.(o),o.defaultPrevented||(n.current=true,o.detail.originalEvent.type==="pointerdown"&&(a.current=true));let i=o.target;r.triggerRef.current?.contains(i)&&o.preventDefault(),o.detail.originalEvent.type==="focusin"&&a.current&&o.preventDefault();}})}),wC=Rt.forwardRef((e,t)=>{let{__scopeDialog:r,trapFocus:n,onOpenAutoFocus:a,onCloseAutoFocus:o,...i}=e,s=Ea(Ds,r),l=Rt.useRef(null),c=Ca(t,l);return VN(),jsxs(Fragment,{children:[jsx(A0,{asChild:true,loop:true,trapped:n,onMountAutoFocus:a,onUnmountAutoFocus:o,children:jsx(R0,{role:"dialog",id:s.contentId,"aria-describedby":s.descriptionId,"aria-labelledby":s.titleId,"data-state":Y0(s.open),...i,ref:c,onDismiss:()=>s.onOpenChange(false)})}),jsxs(Fragment,{children:[jsx(Dj,{titleId:s.titleId}),jsx($j,{contentRef:l,descriptionId:s.descriptionId})]})]})}),Q0="DialogTitle",_C=Rt.forwardRef((e,t)=>{let{__scopeDialog:r,...n}=e,a=Ea(Q0,r);return jsx(Cn.h2,{id:a.titleId,...n,ref:t})});_C.displayName=Q0;var SC="DialogDescription",NC=Rt.forwardRef((e,t)=>{let{__scopeDialog:r,...n}=e,a=Ea(SC,r);return jsx(Cn.p,{id:a.descriptionId,...n,ref:t})});NC.displayName=SC;var CC="DialogClose",EC=Rt.forwardRef((e,t)=>{let{__scopeDialog:r,...n}=e,a=Ea(CC,r);return jsx(Cn.button,{type:"button",...n,ref:t,onClick:Qa(e.onClick,()=>a.onOpenChange(false))})});EC.displayName=CC;function Y0(e){return e?"open":"closed"}var PC="DialogTitleWarning",[Eee,TC]=_N(PC,{contentName:Ds,titleName:Q0,docsSlug:"dialog"}),Dj=({titleId:e})=>{let t=TC(PC),r=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users.
52
53
 
53
54
  If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
54
55
 
55
- For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return kt.useEffect(()=>{e&&(document.getElementById(e)||console.error(r));},[r,e]),null},qM="DialogDescriptionWarning",VM=({contentRef:e,descriptionId:t})=>{let n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${UN(qM).contentName}}.`;return kt.useEffect(()=>{let o=e.current?.getAttribute("aria-describedby");t&&o&&(document.getElementById(t)||console.warn(n));},[n,e,t]),null},qN=TN,VN=RN,O0=DN,D0=AN,A0=$N,HN=FN,JN=jN,$0=BN;var WN=kt.createContext(false);function WM(){return kt.useContext(WN)}function hn({...e}){return jsx(WN.Provider,{value:true,children:jsx(qN,{"data-slot":"dialog",...e})})}function ju({...e}){return jsx(VN,{"data-slot":"dialog-trigger",...e})}function KM({...e}){return jsx(O0,{"data-slot":"dialog-portal",...e})}function I0({children:e,asChild:t,...r}){return WM()?jsx($0,{"data-slot":"dialog-close",asChild:t,...r,children:e}):jsx(Fragment,{children:e})}function GM({className:e,...t}){return jsx(D0,{"data-slot":"dialog-overlay",className:T("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function co({className:e,children:t,showCloseButton:r=true,...n}){return jsxs(KM,{"data-slot":"dialog-portal",children:[jsx(GM,{}),jsxs(A0,{"data-slot":"dialog-content",className:T("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...n,children:[t,r&&jsxs($0,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[jsx(XIcon,{}),jsx("span",{className:"sr-only",children:"Close"})]})]})]})}var F0=kt.forwardRef(({className:e,children:t,...r},n)=>jsxs(O0,{children:[jsx(D0,{className:"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"}),jsx(A0,{ref:n,className:T("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-xl translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200",e),...r,children:t})]}));F0.displayName="DialogContentWithoutClose";function li({className:e,...t}){return jsx("div",{"data-slot":"dialog-header",className:T("flex flex-col gap-2 text-center sm:text-left",e),...t})}function Tl({className:e,...t}){return jsx("div",{"data-slot":"dialog-footer",className:T("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function gn({className:e,...t}){return jsx(HN,{"data-slot":"dialog-title",className:T("text-lg leading-none font-semibold",e),...t})}function ci({className:e,...t}){return jsx(JN,{"data-slot":"dialog-description",className:T("text-muted-foreground text-sm",e),...t})}function dr({...e}){return jsx(bt.Root,{"data-slot":"dropdown-menu",...e})}function uo({...e}){return jsx(bt.Portal,{"data-slot":"dropdown-menu-portal",...e})}function fr({...e}){return jsx(bt.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}function pr({className:e,sideOffset:t=4,...r}){return jsx(bt.Portal,{children:jsx(bt.Content,{"data-slot":"dropdown-menu-content",sideOffset:t,className:T("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",e),...r})})}function ge({className:e,inset:t,variant:r="default",...n}){return jsx(bt.Item,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":r,className:T("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n})}function kl({...e}){return jsx(bt.RadioGroup,{"data-slot":"dropdown-menu-radio-group",...e})}function Rl({className:e,children:t,...r}){return jsxs(bt.RadioItem,{"data-slot":"dropdown-menu-radio-item",className:T("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...r,children:[jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:jsx(bt.ItemIndicator,{children:jsx(CircleIcon,{className:"size-2 fill-current"})})}),t]})}function fo({className:e,...t}){return jsx(bt.Separator,{"data-slot":"dropdown-menu-separator",className:T("bg-border -mx-1 my-1 h-px",e),...t})}function Vr({...e}){return jsx(bt.Sub,{"data-slot":"dropdown-menu-sub",...e})}function Hr({className:e,inset:t,children:r,...n}){return jsxs(bt.SubTrigger,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:T("focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",e),...n,children:[r,jsx(ChevronRightIcon,{className:"ml-auto size-4"})]})}function Jr({className:e,...t}){return jsx(bt.SubContent,{"data-slot":"dropdown-menu-sub-content",className:T("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",e),...t})}function Np({className:e,...t}){return jsx(Sp.Root,{"data-slot":"switch",className:T("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:jsx(Sp.Thumb,{"data-slot":"switch-thumb",className:T("bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}function XN({isOpen:e,onClose:t,path:r,propertyName:n,setPropertyName:o,metadataValues:a,setMetadataValues:i,nameError:s,setNameError:l,showReasoningPromptField:c,setShowReasoningPromptField:u,validateName:d,onChange:m,onNameChange:h,onDelete:y,node:p,name:f,localType:x,editMode:g}){let[v,w]=useState(p),[N,S]=useState(n),[_,P]=useState({type:"object",properties:{},$defs:{}});return useEffect(()=>{e&&(w({...p}),S(n));},[e,p,n]),jsx(hn,{open:e,onOpenChange:t,children:jsxs(co,{className:"sm:max-w-xl max-h-[90vh] overflow-y-auto p-0 gap-2",children:[jsxs(li,{className:"px-4 pt-4",children:[jsx(gn,{className:"text-xl font-bold",children:"Edit Property"}),jsx(ci,{className:"text-sm text-muted-foreground",children:"Modify property name, type, description, and other characteristics."})]}),jsx(j0,{editedProperty:v,setEditedProperty:w,setJsonSchema:()=>{},editedJsonSchema:_,setEditedJsonSchema:P,editedName:N,setEditedName:S,onSubmit:()=>{let b=d(N);if(b){l(b);return}let O={...a,title:N?qo(N):"",description:v.description||"","X-ReasoningPrompt":v["X-ReasoningPrompt"]||"",maxLength:v.maxLength};i(O),N!==f?(o(N),h(N)):m(v),t();},onCancel:()=>{t();},onDelete:y,submitLabel:"Save",onNameError:b=>{l(b);},editMode:g,wrapCancelInDialogClose:true})]})})}function QN({isOpen:e,onClose:t,path:r,schemaTitle:n,setSchemaTitle:o,metadataValues:a,setMetadataValues:i,showReasoningPromptField:s,setShowReasoningPromptField:l,onChange:c,node:u,editMode:d="editable"}){let m=()=>{l(!s);};return jsx(hn,{open:e,onOpenChange:t,children:jsxs(co,{className:"p-0 gap-0 bg-gray-50 rounded-2xl max-h-[90vh] flex flex-col",children:[jsxs("div",{className:"bg-white shadow-xs rounded-2xl m-0 mb-0 flex-1 overflow-y-auto",children:[jsxs(li,{className:"p-4 pb-2 flex-shrink-0",children:[jsx(gn,{className:"text-xl font-bold",children:"Edit Schema"}),jsx(ci,{className:"text-sm text-gray-600",children:"Modify schema title, description, and reasoning."})]}),jsxs("div",{className:"space-y-4 p-4 pt-2",children:[jsxs("div",{children:[jsxs("div",{className:"flex flex-row items-center gap-2",children:[jsx(Yt,{htmlFor:`${r}-title`,className:"block text-sm font-medium text-gray-700",children:"Schema Title"}),jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(Info,{className:"w-4 h-4"})}),jsx(et,{children:"This title will be used by the AI to understand what we are extracting."})]})]}),jsx(nt,{id:`${r}-title`,value:n,onChange:h=>o(h.target.value),className:"mt-1",placeholder:"Enter schema title",disabled:d==="readOnly"||d==="promptOnly"})]}),jsxs("div",{children:[jsx(Yt,{htmlFor:`${r}-description`,className:"block text-sm font-medium text-gray-700",children:"Description"}),jsx(nn,{id:`${r}-description`,value:a.description,onChange:h=>i({...a,description:h.target.value}),className:"mt-1",placeholder:"Add a description to your schema",disabled:d==="readOnly"})]}),s?jsxs("div",{children:[jsx("div",{className:"flex justify-between items-center",children:jsx(V,{type:"button",variant:"ghost",size:"sm",onClick:()=>{m(),i({...a,"X-ReasoningPrompt":""});},className:"h-6 w-6 p-0",disabled:d==="readOnly",children:jsx(X,{className:"h-4 w-4"})})}),jsx(nn,{id:`${r}-reasoningPrompt`,value:a["X-ReasoningPrompt"],onChange:h=>i({...a,"X-ReasoningPrompt":h.target.value}),className:"w-full bg-purple-100 text-[#736982] h-24 mt-1 rounded-md border border-input px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",placeholder:"Add a reasoning prompt for the entire schema",disabled:d==="readOnly"})]}):jsx("div",{className:"flex mt-2 flex-row space-x-2 items-center",children:jsxs(V,{type:"button",variant:"outline",size:"sm",onClick:m,className:"bg-purple-100 hover:text-purple-900 hover:bg-[#EEDFFF] text-[#736982]",disabled:d==="readOnly",children:[jsx(PlusIcon,{className:"w-4 h-4 mr-1"}),"Add reasoning"]})})]})]}),jsxs(Tl,{className:"p-4 flex-shrink-0",children:[jsx(V,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),jsx(V,{type:"button",onClick:()=>{let h={...a,title:n};c(Ep(u,h)),t();},disabled:d==="readOnly",className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay ring-1 bg-gray-900 hover:bg-gray-900 hover:opacity-80 text-white ring-gray-900",children:"Save"})]})]})})}function eC({isOpen:e,onClose:t,onConfirm:r,onCancel:n}){let[o,a]=useState([]),[i,s]=useState("");useEffect(()=>{e&&(a([]),s(""));},[e]);let l=()=>{i.trim()&&(a(p=>[...p,i.trim()]),s(""));},c=()=>{a(p=>[...p,""]);},u=p=>{a(f=>f.filter((x,g)=>g!==p));},d=(p,f)=>{a(x=>x.map((g,v)=>v===p?f:g));},m=()=>{let p=o.filter(f=>f.trim()!=="");p.length>0&&(r(p),t());},h=()=>{n(),t();},y=o.filter(p=>p.trim()!=="").length;return jsx(hn,{open:e,onOpenChange:h,children:jsxs(co,{className:"p-6 max-h-[90vh] flex flex-col max-w-lg",children:[jsxs(li,{className:"flex-shrink-0",children:[jsx(gn,{className:"text-xl font-bold",children:"Update Field"}),jsx(ci,{className:"text-sm text-gray-600",children:"Define the allowed values for this field."})]}),jsx("div",{className:"space-y-4 mt-4 flex-1 overflow-y-auto pr-2",children:jsxs("div",{children:[jsx(Yt,{className:"text-sm font-medium text-gray-700 block mb-2",children:"Enabled Options"}),o.length>0&&jsx("div",{className:"space-y-2 mb-4",children:o.map((p,f)=>jsxs("div",{className:"flex items-center gap-2",children:[jsx(nt,{value:p,onChange:x=>d(f,x.target.value),onKeyDown:x=>{x.key==="Enter"&&p.trim()&&(f===o.length-1?c():document.querySelector(`input[data-enum-index="${f+1}"]`)?.focus());},className:"flex-1",placeholder:`Value ${f+1}`,"data-enum-index":f}),jsx(V,{type:"button",variant:"ghost",size:"sm",className:"p-1 h-8 w-8",onClick:()=>u(f),disabled:o.length===1,children:jsx(X,{className:"h-4 w-4"})})]},f))}),jsxs("div",{className:"flex items-center gap-2",children:[jsx(nt,{value:i,onChange:p=>s(p.target.value),onKeyDown:p=>{p.key==="Enter"&&i.trim()&&l();},className:"flex-1",placeholder:"Add another value"}),jsxs(V,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:!i.trim(),children:[jsx(PlusIcon,{className:"h-4 w-4 mr-1"}),"Add"]})]}),jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[y," value",y!==1?"s":""," defined."]})]})}),jsxs(Tl,{className:"mt-6 flex-shrink-0",children:[jsx(V,{type:"button",variant:"outline",onClick:h,children:"Cancel"}),jsxs(V,{type:"button",variant:"default",onClick:m,disabled:y===0,children:["Update Field (",y," value",y!==1?"s":"",")"]})]})]})})}var Ol={Address:{description:"A normalized postal address (Schema.org / UBL / FHIR compatible).",properties:{street_address:{description:"Full address line: house number, street name, apt/suite, building, floor, company, ...",examples:["221B Baker Street, Flat B, 10th Floor, Acme Inc."],title:"Street Address",type:"string"},city:{examples:["London"],title:"City",type:"string"},region:{anyOf:[{type:"string"},{type:"null"}],default:null,description:"State / province / region.",examples:["Greater London"],title:"Region"},postal_code:{anyOf:[{type:"string"},{type:"null"}],default:null,description:"ZIP / postal code.",examples:["NW1 6XE"],title:"Postal Code"},country:{examples:["GB"],maxLength:2,minLength:2,pattern:"^[A-Z]{2}$",title:"Country",type:"string"}},required:["street_address","city","country"],title:"Address",type:"object"},Price:{description:"Monetary value tied to a specific ISO-4217 currency.\n\n`amount` is stored in the major unit of the currency (e.g. dollars, euros).",properties:{amount:{anyOf:[{type:"number"},{type:"string"}],examples:["19.99"],title:"Amount"},currency:{examples:["USD"],maxLength:3,minLength:3,pattern:"^[A-Z]{3}$",title:"Currency",type:"string"}},required:["amount","currency"],title:"Price",type:"object"},Person:{description:"A natural person with contact information.",properties:{first_name:{examples:["Ada"],title:"First Name",type:"string"},last_name:{examples:["Lovelace"],title:"Last Name",type:"string"},middle_name:{anyOf:[{type:"string"},{type:"null"}],default:null,examples:["King"],title:"Middle Name"},email:{anyOf:[{pattern:"^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",type:"string"},{type:"null"}],default:null,examples:["ada@example.com"],title:"Email"},phone:{anyOf:[{pattern:"^\\+?[0-9 .\\-()]{7,25}$",type:"string"},{type:"null"}],default:null,examples:["+1-555-0100"],title:"Phone"}},required:["first_name","last_name"],title:"Person",type:"object"},Company:{$defs:{Address:{description:"A normalized postal address (Schema.org / UBL / FHIR compatible).",properties:{street_address:{description:"Full address line: house number, street name, apt/suite, building, floor, company, ...",examples:["221B Baker Street, Flat B, 10th Floor, Acme Inc."],title:"Street Address",type:"string"},city:{examples:["London"],title:"City",type:"string"},region:{anyOf:[{type:"string"},{type:"null"}],default:null,description:"State / province / region.",examples:["Greater London"],title:"Region"},postal_code:{anyOf:[{type:"string"},{type:"null"}],default:null,description:"ZIP / postal code.",examples:["NW1 6XE"],title:"Postal Code"},country:{examples:["GB"],maxLength:2,minLength:2,pattern:"^[A-Z]{2}$",title:"Country",type:"string"}},required:["street_address","city","country"],title:"Address",type:"object"}},description:"A legal entity or organization.",properties:{name:{description:"Registered legal name.",examples:["Example Corp."],title:"Name",type:"string"},address:{$ref:"#/$defs/Address"},phone:{anyOf:[{pattern:"^\\+?[0-9 .\\-()]{7,25}$",type:"string"},{type:"null"}],default:null,examples:["+1 415 555 0199"],title:"Phone"},email:{anyOf:[{pattern:"^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",type:"string"},{type:"null"}],default:null,examples:["info@example.com"],title:"Email"},website:{anyOf:[{type:"string"},{type:"null"}],default:null,description:"Company website URL.",examples:["https://example.com"],title:"Website"}},required:["name","address"],title:"Company",type:"object",deps:["Address"]},Event:{description:"An occurrence at a certain date and place, lasting from a start time to an end time.",properties:{title:{examples:["Board Meeting"],title:"Title",type:"string"},date:{examples:["2025-08-15"],format:"date",title:"Date",type:"string"},start_time:{examples:["09:00"],format:"iso-time",title:"Start Time",type:"string"},end_time:{examples:["11:30"],format:"iso-time",title:"End Time",type:"string"},description:{examples:["Quarterly results call for the company"],title:"Description",type:"string"}},required:["title","date","start_time","end_time","description"],title:"Event",type:"object"}};function Pp(e){return typeof e=="object"&&e!==null&&("type"in e||"$ref"in e||"anyOf"in e||"oneOf"in e||"allOf"in e)}function tC(e,t){if(typeof e!="object"||e===null||!("$ref"in e))throw new Error("Schema is not a valid reference schema.");let r=e.$ref;if(!r||!r.startsWith("#/"))throw new Error("Only internal references are supported.");let n=r.substring(2).split("/"),o=t;for(let a of n)if(o=o[a],o===void 0)throw new Error(`Unable to resolve schema reference: ${r}`);return o}function L0(e,t){if(typeof e!="object"||e===null)return false;if(e.type==="object"||e.properties&&Object.keys(e.properties).length>0)return true;if("$ref"in e){let r=tC(e,t);return L0(r,t)}return false}function rC(e,t){let r=s=>typeof s=="number",n=s=>r(s)?[s]:s==null?[]:Array.isArray(s)?s.flatMap(n):typeof s=="object"?Object.values(s).flatMap(n):[];if(!t||t.trim()===""){let s=n(e);return s.length?s.reduce((l,c)=>l+c,0)/s.length:0}let o=t.split("."),a=(s,l)=>{if(l===o.length)return n(s);if(s==null)return [];let c=o[l];if(c==="*")return Array.isArray(s)?s.flatMap(d=>a(d,l+1)):typeof s=="object"?Object.values(s).flatMap(d=>a(d,l+1)):[];let u=Array.isArray(s)&&!Number.isNaN(Number(c))?s[Number(c)]:s[c];return a(u,l+1)},i=a(e,0);return i.length?i.reduce((s,l)=>s+l,0)/i.length:0}function Tp(e,t){if(!t||t.trim()==="")return e;let r=t.split("."),n=(o,a)=>{if(a===r.length)return o;if(o==null)return;let i=r[a];if(i==="*"){if(Array.isArray(o)&&o.length>0){for(let l of o){let c=n(l,a+1);if(c!==void 0)return c}return}if(typeof o=="object"){for(let l of Object.values(o)){let c=n(l,a+1);if(c!==void 0)return c}return}return}let s=Array.isArray(o)&&!Number.isNaN(Number(i))?o[Number(i)]:o[i];return n(s,a+1)};return n(e,0)}function ls(e){if(e.anyOf&&Array.isArray(e.anyOf)){let t=e.anyOf.find(r=>typeof r=="object"&&(r.type!=="null"||r.$ref));return t&&typeof t=="object"?t:e}return e}function sC({validationErrors:e,className:t,variant:r="full",showFixButton:n=true,onSchemaFixWithAI:o,fixButtonText:a="Fix with AI",fixButtonIcon:i}){let[s,l]=useState(false),[c,u]=useState(false),d=n&&o;if(!e)return null;let m=async()=>{if(o){l(true);try{await o(e);}catch(g){console.error("Error in fix handler:",g);}finally{l(false);}}},h=e.split(`
56
+ For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return Rt.useEffect(()=>{e&&(document.getElementById(e)||console.error(r));},[r,e]),null},Aj="DialogDescriptionWarning",$j=({contentRef:e,descriptionId:t})=>{let n=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${TC(Aj).contentName}}.`;return Rt.useEffect(()=>{let a=e.current?.getAttribute("aria-describedby");t&&a&&(document.getElementById(t)||console.warn(n));},[n,e,t]),null},kC=mC,RC=gC,ev=vC,tv=bC,rv=xC,OC=_C,DC=NC,nv=EC;var AC=Rt.createContext(false);function Mj(){return Rt.useContext(AC)}function En({...e}){return jsx(AC.Provider,{value:true,children:jsx(kC,{"data-slot":"dialog",...e})})}function pd({...e}){return jsx(RC,{"data-slot":"dialog-trigger",...e})}function jj({...e}){return jsx(ev,{"data-slot":"dialog-portal",...e})}function av({children:e,asChild:t,...r}){return Mj()?jsx(nv,{"data-slot":"dialog-close",asChild:t,...r,children:e}):jsx(Fragment,{children:e})}function Lj({className:e,...t}){return jsx(tv,{"data-slot":"dialog-overlay",className:R("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function Pa({className:e,children:t,showCloseButton:r=true,...n}){return jsxs(jj,{"data-slot":"dialog-portal",children:[jsx(Lj,{}),jsxs(rv,{"data-slot":"dialog-content",className:R("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...n,children:[t,r&&jsxs(nv,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[jsx(XIcon,{}),jsx("span",{className:"sr-only",children:"Close"})]})]})]})}var ov=Rt.forwardRef(({className:e,children:t,...r},n)=>jsxs(ev,{children:[jsx(tv,{className:"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"}),jsx(rv,{ref:n,className:R("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-xl translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200",e),...r,children:t})]}));ov.displayName="DialogContentWithoutClose";function _i({className:e,...t}){return jsx("div",{"data-slot":"dialog-header",className:R("flex flex-col gap-2 text-center sm:text-left",e),...t})}function ac({className:e,...t}){return jsx("div",{"data-slot":"dialog-footer",className:R("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function Pn({className:e,...t}){return jsx(OC,{"data-slot":"dialog-title",className:R("text-lg leading-none font-semibold",e),...t})}function Si({className:e,...t}){return jsx(DC,{"data-slot":"dialog-description",className:R("text-muted-foreground text-sm",e),...t})}function mr({...e}){return jsx(St.Root,{"data-slot":"dropdown-menu",...e})}function Ta({...e}){return jsx(St.Portal,{"data-slot":"dropdown-menu-portal",...e})}function hr({...e}){return jsx(St.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}function gr({className:e,sideOffset:t=4,...r}){return jsx(St.Portal,{children:jsx(St.Content,{"data-slot":"dropdown-menu-content",sideOffset:t,className:R("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",e),...r})})}function we({className:e,inset:t,variant:r="default",...n}){return jsx(St.Item,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":r,className:R("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n})}function oc({...e}){return jsx(St.RadioGroup,{"data-slot":"dropdown-menu-radio-group",...e})}function ic({className:e,children:t,...r}){return jsxs(St.RadioItem,{"data-slot":"dropdown-menu-radio-item",className:R("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...r,children:[jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:jsx(St.ItemIndicator,{children:jsx(CircleIcon,{className:"size-2 fill-current"})})}),t]})}function ka({className:e,...t}){return jsx(St.Separator,{"data-slot":"dropdown-menu-separator",className:R("bg-border -mx-1 my-1 h-px",e),...t})}function Xr({...e}){return jsx(St.Sub,{"data-slot":"dropdown-menu-sub",...e})}function Qr({className:e,inset:t,children:r,...n}){return jsxs(St.SubTrigger,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:R("focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",e),...n,children:[r,jsx(ChevronRightIcon,{className:"ml-auto size-4"})]})}function Yr({className:e,...t}){return jsx(St.SubContent,{"data-slot":"dropdown-menu-sub-content",className:R("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",e),...t})}function md({className:e,...t}){return jsx(Kp.Root,{"data-slot":"switch",className:R("peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:jsx(Kp.Thumb,{"data-slot":"switch-thumb",className:R("bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0")})})}function MC({isOpen:e,onClose:t,path:r,propertyName:n,setPropertyName:a,metadataValues:o,setMetadataValues:i,nameError:s,setNameError:l,showReasoningPromptField:c,setShowReasoningPromptField:u,validateName:d,onChange:g,onNameChange:f,onDelete:h,node:m,name:p,localType:v,editMode:y}){let[x,w]=useState(m),[_,E]=useState(n),[C,P]=useState({type:"object",properties:{},$defs:{}});return useEffect(()=>{e&&(w({...m}),E(n));},[e,m,n]),jsx(En,{open:e,onOpenChange:t,children:jsxs(Pa,{className:"sm:max-w-xl max-h-[90vh] overflow-y-auto p-0 gap-2",children:[jsxs(_i,{className:"px-4 pt-4",children:[jsx(Pn,{className:"text-xl font-bold",children:"Edit Property"}),jsx(Si,{className:"text-sm text-muted-foreground",children:"Modify property name, type, description, and other characteristics."})]}),jsx(sv,{editedProperty:x,setEditedProperty:w,setJsonSchema:()=>{},editedJsonSchema:C,setEditedJsonSchema:P,editedName:_,setEditedName:E,onSubmit:()=>{let b=d(_);if(b){l(b);return}let k={...o,title:_?Ya(_):"",description:x.description||"","X-ReasoningPrompt":x["X-ReasoningPrompt"]||"",maxLength:x.maxLength};i(k),_!==p?(a(_),f(_)):g(x),t();},onCancel:()=>{t();},onDelete:h,submitLabel:"Save",onNameError:b=>{l(b);},editMode:y,wrapCancelInDialogClose:true})]})})}function jC({isOpen:e,onClose:t,path:r,schemaTitle:n,setSchemaTitle:a,metadataValues:o,setMetadataValues:i,showReasoningPromptField:s,setShowReasoningPromptField:l,onChange:c,node:u,editMode:d="editable"}){let g=()=>{l(!s);};return jsx(En,{open:e,onOpenChange:t,children:jsxs(Pa,{className:"p-0 gap-0 bg-gray-50 rounded-2xl max-h-[90vh] flex flex-col",children:[jsxs("div",{className:"bg-white shadow-xs rounded-2xl m-0 mb-0 flex-1 overflow-y-auto",children:[jsxs(_i,{className:"p-4 pb-2 flex-shrink-0",children:[jsx(Pn,{className:"text-xl font-bold",children:"Edit Schema"}),jsx(Si,{className:"text-sm text-gray-600",children:"Modify schema title, description, and reasoning."})]}),jsxs("div",{className:"space-y-4 p-4 pt-2",children:[jsxs("div",{children:[jsxs("div",{className:"flex flex-row items-center gap-2",children:[jsx(nr,{htmlFor:`${r}-title`,className:"block text-sm font-medium text-gray-700",children:"Schema Title"}),jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(Info,{className:"w-4 h-4"})}),jsx(ze,{children:"This title will be used by the AI to understand what we are extracting."})]})]}),jsx(Ze,{id:`${r}-title`,value:n,onChange:f=>a(f.target.value),className:"mt-1",placeholder:"Enter schema title",disabled:d==="readOnly"||d==="promptOnly"})]}),jsxs("div",{children:[jsx(nr,{htmlFor:`${r}-description`,className:"block text-sm font-medium text-gray-700",children:"Description"}),jsx(pr,{id:`${r}-description`,value:o.description,onChange:f=>i({...o,description:f.target.value}),className:"mt-1",placeholder:"Add a description to your schema",disabled:d==="readOnly"})]}),s?jsxs("div",{children:[jsx("div",{className:"flex justify-between items-center",children:jsx(K,{type:"button",variant:"ghost",size:"sm",onClick:()=>{g(),i({...o,"X-ReasoningPrompt":""});},className:"h-6 w-6 p-0",disabled:d==="readOnly",children:jsx(X,{className:"h-4 w-4"})})}),jsx(pr,{id:`${r}-reasoningPrompt`,value:o["X-ReasoningPrompt"],onChange:f=>i({...o,"X-ReasoningPrompt":f.target.value}),className:"w-full bg-purple-100 text-[#736982] h-24 mt-1 rounded-md border border-input px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",placeholder:"Add a reasoning prompt for the entire schema",disabled:d==="readOnly"})]}):jsx("div",{className:"flex mt-2 flex-row space-x-2 items-center",children:jsxs(K,{type:"button",variant:"outline",size:"sm",onClick:g,className:"bg-purple-100 hover:text-purple-900 hover:bg-[#EEDFFF] text-[#736982]",disabled:d==="readOnly",children:[jsx(PlusIcon,{className:"w-4 h-4 mr-1"}),"Add reasoning"]})})]})]}),jsxs(ac,{className:"p-4 flex-shrink-0",children:[jsx(K,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),jsx(K,{type:"button",onClick:()=>{let f={...o,title:n};c(Zp(u,f)),t();},disabled:d==="readOnly",className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay ring-1 bg-gray-900 hover:bg-gray-900 hover:opacity-80 text-white ring-gray-900",children:"Save"})]})]})})}function BC({isOpen:e,onClose:t,onConfirm:r,onCancel:n}){let[a,o]=useState([]),[i,s]=useState("");useEffect(()=>{e&&(o([]),s(""));},[e]);let l=()=>{i.trim()&&(o(m=>[...m,i.trim()]),s(""));},c=()=>{o(m=>[...m,""]);},u=m=>{o(p=>p.filter((v,y)=>y!==m));},d=(m,p)=>{o(v=>v.map((y,x)=>x===m?p:y));},g=()=>{let m=a.filter(p=>p.trim()!=="");m.length>0&&(r(m),t());},f=()=>{n(),t();},h=a.filter(m=>m.trim()!=="").length;return jsx(En,{open:e,onOpenChange:f,children:jsxs(Pa,{className:"p-6 max-h-[90vh] flex flex-col max-w-lg",children:[jsxs(_i,{className:"flex-shrink-0",children:[jsx(Pn,{className:"text-xl font-bold",children:"Update Field"}),jsx(Si,{className:"text-sm text-gray-600",children:"Define the allowed values for this field."})]}),jsx("div",{className:"space-y-4 mt-4 flex-1 overflow-y-auto pr-2",children:jsxs("div",{children:[jsx(nr,{className:"text-sm font-medium text-gray-700 block mb-2",children:"Enabled Options"}),a.length>0&&jsx("div",{className:"space-y-2 mb-4",children:a.map((m,p)=>jsxs("div",{className:"flex items-center gap-2",children:[jsx(Ze,{value:m,onChange:v=>d(p,v.target.value),onKeyDown:v=>{v.key==="Enter"&&m.trim()&&(p===a.length-1?c():document.querySelector(`input[data-enum-index="${p+1}"]`)?.focus());},className:"flex-1",placeholder:`Value ${p+1}`,"data-enum-index":p}),jsx(K,{type:"button",variant:"ghost",size:"sm",className:"p-1 h-8 w-8",onClick:()=>u(p),disabled:a.length===1,children:jsx(X,{className:"h-4 w-4"})})]},p))}),jsxs("div",{className:"flex items-center gap-2",children:[jsx(Ze,{value:i,onChange:m=>s(m.target.value),onKeyDown:m=>{m.key==="Enter"&&i.trim()&&l();},className:"flex-1",placeholder:"Add another value"}),jsxs(K,{type:"button",variant:"outline",size:"sm",onClick:l,disabled:!i.trim(),children:[jsx(PlusIcon,{className:"h-4 w-4 mr-1"}),"Add"]})]}),jsxs("p",{className:"text-xs text-gray-500 mt-2",children:[h," value",h!==1?"s":""," defined."]})]})}),jsxs(ac,{className:"mt-6 flex-shrink-0",children:[jsx(K,{type:"button",variant:"outline",onClick:f,children:"Cancel"}),jsxs(K,{type:"button",variant:"default",onClick:g,disabled:h===0,children:["Update Field (",h," value",h!==1?"s":"",")"]})]})]})})}var sc={Address:{description:"A normalized postal address (Schema.org / UBL / FHIR compatible).",properties:{street_address:{description:"Full address line: house number, street name, apt/suite, building, floor, company, ...",examples:["221B Baker Street, Flat B, 10th Floor, Acme Inc."],title:"Street Address",type:"string"},city:{examples:["London"],title:"City",type:"string"},region:{anyOf:[{type:"string"},{type:"null"}],default:null,description:"State / province / region.",examples:["Greater London"],title:"Region"},postal_code:{anyOf:[{type:"string"},{type:"null"}],default:null,description:"ZIP / postal code.",examples:["NW1 6XE"],title:"Postal Code"},country:{examples:["GB"],maxLength:2,minLength:2,pattern:"^[A-Z]{2}$",title:"Country",type:"string"}},required:["street_address","city","country"],title:"Address",type:"object"},Price:{description:"Monetary value tied to a specific ISO-4217 currency.\n\n`amount` is stored in the major unit of the currency (e.g. dollars, euros).",properties:{amount:{anyOf:[{type:"number"},{type:"string"}],examples:["19.99"],title:"Amount"},currency:{examples:["USD"],maxLength:3,minLength:3,pattern:"^[A-Z]{3}$",title:"Currency",type:"string"}},required:["amount","currency"],title:"Price",type:"object"},Person:{description:"A natural person with contact information.",properties:{first_name:{examples:["Ada"],title:"First Name",type:"string"},last_name:{examples:["Lovelace"],title:"Last Name",type:"string"},middle_name:{anyOf:[{type:"string"},{type:"null"}],default:null,examples:["King"],title:"Middle Name"},email:{anyOf:[{pattern:"^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",type:"string"},{type:"null"}],default:null,examples:["ada@example.com"],title:"Email"},phone:{anyOf:[{pattern:"^\\+?[0-9 .\\-()]{7,25}$",type:"string"},{type:"null"}],default:null,examples:["+1-555-0100"],title:"Phone"}},required:["first_name","last_name"],title:"Person",type:"object"},Company:{$defs:{Address:{description:"A normalized postal address (Schema.org / UBL / FHIR compatible).",properties:{street_address:{description:"Full address line: house number, street name, apt/suite, building, floor, company, ...",examples:["221B Baker Street, Flat B, 10th Floor, Acme Inc."],title:"Street Address",type:"string"},city:{examples:["London"],title:"City",type:"string"},region:{anyOf:[{type:"string"},{type:"null"}],default:null,description:"State / province / region.",examples:["Greater London"],title:"Region"},postal_code:{anyOf:[{type:"string"},{type:"null"}],default:null,description:"ZIP / postal code.",examples:["NW1 6XE"],title:"Postal Code"},country:{examples:["GB"],maxLength:2,minLength:2,pattern:"^[A-Z]{2}$",title:"Country",type:"string"}},required:["street_address","city","country"],title:"Address",type:"object"}},description:"A legal entity or organization.",properties:{name:{description:"Registered legal name.",examples:["Example Corp."],title:"Name",type:"string"},address:{$ref:"#/$defs/Address"},phone:{anyOf:[{pattern:"^\\+?[0-9 .\\-()]{7,25}$",type:"string"},{type:"null"}],default:null,examples:["+1 415 555 0199"],title:"Phone"},email:{anyOf:[{pattern:"^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",type:"string"},{type:"null"}],default:null,examples:["info@example.com"],title:"Email"},website:{anyOf:[{type:"string"},{type:"null"}],default:null,description:"Company website URL.",examples:["https://example.com"],title:"Website"}},required:["name","address"],title:"Company",type:"object",deps:["Address"]},Event:{description:"An occurrence at a certain date and place, lasting from a start time to an end time.",properties:{title:{examples:["Board Meeting"],title:"Title",type:"string"},date:{examples:["2025-08-15"],format:"date",title:"Date",type:"string"},start_time:{examples:["09:00"],format:"iso-time",title:"Start Time",type:"string"},end_time:{examples:["11:30"],format:"iso-time",title:"End Time",type:"string"},description:{examples:["Quarterly results call for the company"],title:"Description",type:"string"}},required:["title","date","start_time","end_time","description"],title:"Event",type:"object"}};var zC=os(Wu()),UC=os(r0()),Zj=new zC.default({allErrors:true,strict:false});(0, UC.default)(Zj);function Xp(e){return typeof e=="object"&&e!==null&&("type"in e||"$ref"in e||"anyOf"in e||"oneOf"in e||"allOf"in e)}function qC(e,t){if(typeof e!="object"||e===null||!("$ref"in e))throw new Error("Schema is not a valid reference schema.");let r=e.$ref;if(!r||!r.startsWith("#/"))throw new Error("Only internal references are supported.");let n=r.substring(2).split("/"),a=t;for(let o of n)if(a=a[o],a===void 0)throw new Error(`Unable to resolve schema reference: ${r}`);return a}function lv(e,t){if(typeof e!="object"||e===null)return false;if(e.type==="object"||e.properties&&Object.keys(e.properties).length>0)return true;if("$ref"in e){let r=qC(e,t);return lv(r,t)}return false}function VC(e,t){let r=s=>typeof s=="number",n=s=>r(s)?[s]:s==null?[]:Array.isArray(s)?s.flatMap(n):typeof s=="object"?Object.values(s).flatMap(n):[];if(!t||t.trim()===""){let s=n(e);return s.length?s.reduce((l,c)=>l+c,0)/s.length:0}let a=t.split("."),o=(s,l)=>{if(l===a.length)return n(s);if(s==null)return [];let c=a[l];if(c==="*")return Array.isArray(s)?s.flatMap(d=>o(d,l+1)):typeof s=="object"?Object.values(s).flatMap(d=>o(d,l+1)):[];let u=Array.isArray(s)&&!Number.isNaN(Number(c))?s[Number(c)]:s[c];return o(u,l+1)},i=o(e,0);return i.length?i.reduce((s,l)=>s+l,0)/i.length:0}function Pr(e,t){if(!t||t.trim()==="")return e;let r=t.split("."),n=(a,o)=>{if(o===r.length)return a;if(a==null)return;let i=r[o];if(i==="*"){if(Array.isArray(a)&&a.length>0){for(let l of a){let c=n(l,o+1);if(c!==void 0)return c}return}if(typeof a=="object"){for(let l of Object.values(a)){let c=n(l,o+1);if(c!==void 0)return c}return}return}let s=Array.isArray(a)&&!Number.isNaN(Number(i))?a[Number(i)]:a[i];return n(s,o+1)};return n(e,0)}function HC(e,t){return e?.map(r=>{let n=r?.key_mapping?.[t];if(!n)return;let a=n&&n.split(".").length>1?n.split(".").slice(0,-1).join(".")+".reasoning___"+n.split(".").slice(-1)[0]:"reasoning___"+n;return {data:Pr(r.data,n),field_locations:r.field_locations?.[n]||[],reasoning:Pr(r.data,a)}}).filter(r=>r)}function As(e){if(e.anyOf&&Array.isArray(e.anyOf)){let t=e.anyOf.find(r=>typeof r=="object"&&(r.type!=="null"||r.$ref));return t&&typeof t=="object"?t:e}return e}function ZC({validationErrors:e,className:t,variant:r="full",showFixButton:n=true,onSchemaFixWithAI:a,fixButtonText:o="Fix with AI",fixButtonIcon:i}){let[s,l]=useState(false),[c,u]=useState(false),d=n&&a;if(!e)return null;let g=async()=>{if(a){l(true);try{await a(e);}catch(y){console.error("Error in fix handler:",y);}finally{l(false);}}},f=e.split(`
56
57
 
57
- `).filter(Boolean),p=i||jsx(Sparkles,{className:"h-3 w-3"}),f=i||jsx(Sparkles,{className:"h-3 w-3"});i||jsx(Sparkles,{className:"h-4 w-4"});return r==="compact"?jsxs("div",{className:T("border-l-2 border-red-400 w-full max-w-full overflow-hidden box-border",t),children:[jsxs("div",{className:"flex items-center justify-between px-3 py-2 w-full min-w-0 box-border",children:[jsxs("button",{onClick:()=>u(!c),className:"flex items-center gap-2 hover:bg-white/5 rounded px-1 py-1 transition-colors text-left flex-1 min-w-0 overflow-hidden",title:c?"Click to collapse error details":"Click to expand error details",children:[c?jsx(ChevronDown,{className:"h-3 w-3 text-red-400 flex-shrink-0"}):jsx(ChevronRight,{className:"h-3 w-3 text-red-400 flex-shrink-0"}),jsx(AlertCircle,{className:"h-3 w-3 text-red-400 flex-shrink-0"}),jsxs("span",{className:"text-xs font-medium text-red-300 truncate",children:[h.length," validation error",h.length!==1?"s":""]})]}),d&&jsxs(V,{variant:"ghost",size:"sm",onClick:m,disabled:s,className:"h-6 px-2 text-xs text-red-400 hover:text-red-300 hover:bg-white/5 flex-shrink-0",children:[jsx("span",{className:"mr-1",children:f}),s?"Processing...":a]})]}),c&&jsx("div",{className:"border-t border-red-400/30 bg-red-950/20 px-3 py-2 w-full overflow-hidden box-border",children:jsx("div",{className:"space-y-1 w-full max-w-full",children:h.map((g,v)=>jsx("div",{className:"text-xs text-red-200 font-mono leading-relaxed w-full max-w-full break-all overflow-hidden box-border",children:g},v))})})]}):jsxs("div",{className:T("bg-red-50 border border-red-200 rounded-none w-full max-w-full overflow-hidden box-border",t),children:[jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2 w-full min-w-0 box-border",children:[jsxs("button",{onClick:()=>u(!c),className:"flex items-center gap-2 text-red-600 min-w-0 flex-1 rounded px-1 py-1 transition-colors text-left hover:bg-red-100 overflow-hidden",title:c?"Click to collapse error details":"Click to expand error details",children:[c?jsx(ChevronDown,{className:"h-4 w-4 flex-shrink-0"}):jsx(ChevronRight,{className:"h-4 w-4 flex-shrink-0"}),jsx(AlertCircle,{className:"h-4 w-4 flex-shrink-0"}),jsxs("span",{className:"text-sm font-medium",children:["Schema validation errors (",h.length,")"]})]}),d&&jsxs(V,{variant:"ghost",size:"sm",onClick:m,disabled:s,className:"h-7 px-2 text-xs flex-shrink-0 text-red-700 hover:text-red-900 hover:bg-red-100",children:[jsx("span",{className:"mr-1",children:p}),s?"Processing...":a]})]}),c&&jsx("div",{className:"border-t border-red-200 px-3 py-2 space-y-3 w-full overflow-hidden box-border",children:jsx("div",{className:"space-y-3 w-full max-w-full",children:h.map((g,v)=>jsx("div",{className:"text-sm text-red-700 leading-relaxed w-full max-w-full break-all overflow-hidden box-border",style:{overflowWrap:"anywhere",whiteSpace:"pre-wrap"},children:g},v))})})]})}var lC=({className:e})=>jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",className:e,children:[jsx("path",{d:"M4.50684 4.50684L4.50586 4.50879C4.22439 4.78888 4.02809 5.23199 4.00684 5.90918C3.98543 6.59363 4.14785 7.45733 4.52539 8.45508C5.27958 10.4479 6.8234 12.7994 9.00586 14.9922L9.41895 15.3936C11.4922 17.3656 13.6768 18.7683 15.5459 19.4756C16.5435 19.853 17.4075 20.0156 18.0918 19.9941C18.7685 19.9728 19.2112 19.7764 19.4912 19.4951L19.4932 19.4932L20.9062 20.9062C20.1717 21.6433 19.1882 21.9606 18.1543 21.9932C17.1269 22.0254 15.9933 21.7828 14.8379 21.3457C12.5243 20.4702 9.94078 18.7448 7.59473 16.4092L7.5918 16.4062C5.25616 14.0603 3.53088 11.4767 2.65527 9.16309C2.21804 8.00764 1.97568 6.87412 2.00781 5.84668C2.04028 4.81247 2.35546 3.8275 3.09277 3.09277L4.50684 4.50684Z"}),jsx("path",{d:"M13.4141 13.4141C13.0521 13.776 12.5523 14 12 14C10.8955 13.9999 10 13.1045 10 12C10.0001 11.4478 10.2241 10.9478 10.5859 10.5859L13.4141 13.4141Z"}),jsx("path",{d:"M9.00684 9.00684L9.00586 9.00879C6.82328 11.2018 5.2795 13.5531 4.52539 15.5459C4.14787 16.5437 3.98535 17.4074 4.00684 18.0918C4.02551 18.6841 4.17791 19.0974 4.4043 19.3789L4.50586 19.4912L4.50879 19.4951C4.7889 19.7764 5.23232 19.9729 5.90918 19.9941C6.5936 20.0155 7.45741 19.8531 8.45508 19.4756C10.4483 18.7213 12.7999 17.1764 14.9932 14.9932L16.4072 16.4072L16.4062 16.4092C14.0602 18.7449 11.4767 20.4701 9.16309 21.3457C8.00768 21.7829 6.87409 22.0253 5.84668 21.9932C4.81319 21.9607 3.82929 21.6444 3.09473 20.9082V20.9092C2.3564 20.1744 2.04037 19.1891 2.00781 18.1543C1.97558 17.1268 2.21803 15.9935 2.65527 14.8379C3.53081 12.5242 5.25597 9.94089 7.5918 7.59473L7.59277 7.59277L9.00684 9.00684Z"}),jsx("path",{d:"M8.36976 4.12659C7.61309 3.36993 8.16226 2.27655 9.16309 2.65527V2.65527C11.332 3.47613 13.7377 5.04397 15.9629 7.16113L16.4062 7.5918L16.4092 7.59473C18.7448 9.94079 20.4702 12.5243 21.3457 14.8379V14.8379C21.724 15.8378 20.63 16.3869 19.8741 15.6309L19.4459 15.2027C19.3203 15.0772 19.2204 14.929 19.1463 14.7676C18.315 12.9566 16.8991 10.922 14.9951 9.00879L14.582 8.60742C12.7896 6.90239 10.9136 5.624 9.23054 4.85171C9.06908 4.77763 8.92086 4.67769 8.79524 4.55208L8.36976 4.12659Z"}),jsx("path",{d:"M8.36975 4.1272C7.61354 3.37098 8.16285 2.27641 9.16309 2.65491V2.65491C11.3321 3.47574 13.7376 5.04354 15.9629 7.16077L16.4062 7.59143L16.4092 7.59436C18.7449 9.94048 20.4702 12.5238 21.3457 14.8375V14.8375C21.7244 15.8384 20.6302 16.3877 19.8735 15.631L19.448 15.2054C19.3223 15.0798 19.2224 14.9315 19.1483 14.77C18.3171 12.9582 16.9002 10.9226 14.9951 9.00842L14.582 8.60706C12.7892 6.90162 10.9127 5.62344 9.22941 4.85125C9.06805 4.77723 8.91992 4.67737 8.79439 4.55184L8.36975 4.1272Z"}),jsx("line",{x1:"2.10074",y1:"2.10059",x2:"21.8997",y2:"21.8996",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),jsx("path",{d:"M18.1543 2.00696C19.1888 2.03955 20.1735 2.35592 20.9082 3.09387L21.041 3.2345C21.6826 3.95158 21.9627 4.87693 21.9932 5.84583C22.0253 6.8732 21.7829 8.00686 21.3457 9.16223C20.9378 10.2402 20.3427 11.375 19.5898 12.5187L18.1436 11.0724C18.7151 10.1625 19.1638 9.2782 19.4756 8.45422C19.853 7.45658 20.0156 6.5927 19.9941 5.90833C19.9728 5.23157 19.7764 4.78799 19.4951 4.50793C19.4925 4.50598 19.4896 4.50339 19.4873 4.5011C19.2071 4.22177 18.7655 4.02727 18.0918 4.00598C17.4075 3.9845 16.5435 4.14714 15.5459 4.52454C14.7218 4.83638 13.8358 5.28301 12.9258 5.85461L11.4795 4.4093C12.6235 3.65643 13.7597 3.06241 14.8379 2.65442C15.9933 2.21728 17.1269 1.97473 18.1543 2.00696Z"})]});var Lu=create((e,t)=>({tabValue:"playground",setTabValue:r=>e({tabValue:r}),activeView:"table",activeEvaluationTab:"timeline",showInfoPanel:true,docId:null,hoverFieldPath:null,selectedFieldPath:null,metricsSelection:null,metricsSelectedDocumentId:null,metricsViewedDocumentId:null,metricsAlignmentKeyPath:null,documentExtractionStatus:{},isGeneratingSchema:false,isExtracting:{},isProcessingGroundTruth:false,processingIterations:new Set,showSchemaEditor:false,consensusEnabled:false,cellColorState:"none",setConsensusEnabled:r=>e({consensusEnabled:r}),setCellColorState:r=>e({cellColorState:r}),setShowInfoPanel:r=>e({showInfoPanel:r}),setShowSchemaEditor:r=>e({showSchemaEditor:r}),getDocumentStatus:(r,n)=>{let o=n?`${n}-${r}`:`${r}`;return t().documentExtractionStatus[o]||"completed"},setActiveView:r=>{e({activeView:r});},setActiveEvaluationTab:r=>{e({activeEvaluationTab:r});},setDocumentExtractionStatus:(r,n,o)=>{let a=n?`${n}-${r}`:`dataset-${r}`,i=t().documentExtractionStatus,s,l=new Set(t().processingIterations);if(o==="completed"){let{[a]:u,...d}=i;s=d,n&&(Object.keys(s).some(h=>h.includes(n))||l.delete(n));}else s={...i,[a]:o},n&&l.add(n),setTimeout(()=>{t().documentExtractionStatus[a]===o&&(console.log(`${r} under iteration=${n} is still ${o}. Setting to completed.`),t().setDocumentExtractionStatus(r,n,"completed"));},6e5);let c={};l.forEach(u=>{c[u]=true;}),e({processingIterations:l,documentExtractionStatus:s,isExtracting:c,isProcessingGroundTruth:Object.keys(s).some(u=>u.includes("dataset"))});},setIsGeneratingSchema:r=>{e({isGeneratingSchema:r});},setDocId:r=>e({docId:r}),setHoverFieldPath:r=>e({hoverFieldPath:r}),setSelectedFieldPath:r=>e({selectedFieldPath:r,hoverFieldPath:r}),setMetricsSelection:r=>e({metricsSelection:r}),setMetricsSelectedDocumentId:r=>e({metricsSelectedDocumentId:r}),setMetricsViewedDocumentId:r=>e({metricsViewedDocumentId:r}),setMetricsAlignmentKeyPath:r=>e({metricsAlignmentKeyPath:r}),resetForProjectChange:()=>{e({documentExtractionStatus:{},processingIterations:new Set,isExtracting:{},isProcessingGroundTruth:false,isGeneratingSchema:false});}}));function ui(e,t=[],r,n="name"){return /^[a-z_][a-z0-9_]{0,63}$/.test(e)?Sj.includes(e)?`"${e}" is a Python reserved keyword`:Nj.includes(e)?`"${e}" is a Pydantic reserved name`:(r?t.filter(a=>a.toLowerCase()!==r.toLowerCase()):t).some(a=>a.toLowerCase()===e.toLowerCase())?`A ${n} with the name "${e}" already exists (names are case-insensitive)`:null:"Name must start with a lowercase letter or underscore, contain only lowercase letters, numbers, or underscores, and be at most 64 characters long"}var Sj=["false","none","true","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield"],Nj=["__root__","config","schema_extra","model_config","model_fields","model_post_init","model_validate","model_dump"];function qo(e){return e.replace(/([a-z\d])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").split(" ").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function ln(e){if(e.anyOf&&Array.isArray(e.anyOf)){let t=e.anyOf.find(n=>typeof n=="object"&&(n.type!=="null"||n.$ref||n.enum)),r=e.anyOf.some(n=>typeof n=="object"&&n.type==="null");return t&&typeof t=="object"?t.$ref?{type:"$ref",isNullable:r}:t.enum?{type:"enum",isNullable:r}:t.type==="string"&&t.format==="date"?{type:"date",isNullable:r}:t.type==="string"&&t.format==="iso-time"?{type:"time",isNullable:r}:t.type==="string"&&t.format==="date-time"?{type:"datetime",isNullable:r}:{type:t.type?.toString()||"string",isNullable:r}:{type:"string",isNullable:r}}return e.enum?{type:"enum",isNullable:false}:e.$ref?{type:"$ref",isNullable:false}:e.type==="string"&&e.format==="date"?{type:"date",isNullable:false}:e.type==="string"&&e.format==="iso-time"?{type:"time",isNullable:false}:e.type==="string"&&e.format==="date-time"?{type:"datetime",isNullable:false}:{type:e.type?.toString()||"string",isNullable:false}}var U0=e=>{switch(e){case "Address":return jsx(MapPin,{className:"w-4 h-4"});case "Price":return jsx(DollarSign,{className:"w-4 h-4"});case "Person":return jsx(User,{className:"w-4 h-4"});case "Company":return jsx(Building2,{className:"w-4 h-4"});case "Event":return jsx(CalendarDays,{className:"w-4 h-4"});default:return jsx(Link,{className:"w-4 h-4"})}};function Al(e){switch(e){case "string":return {type:"string"};case "number":return {type:"number"};case "integer":return {type:"integer"};case "boolean":return {type:"boolean"};case "object":return {type:"object",properties:{},required:[]};case "array":return {type:"array",items:{type:"string"}};case "$ref":return {};case "enum":return {enum:[],type:"string"};case "date":return {type:"string",format:"date"};case "time":return {type:"string",format:"iso-time"};case "datetime":return {type:"string",format:"date-time"};default:return {type:"string"}}}function Mn(e,t,r){let n={};r.title&&(n.title=r.title),r.description&&(n.description=r.description),r["X-ReasoningPrompt"]&&(n["X-ReasoningPrompt"]=r["X-ReasoningPrompt"]);let o=Al(e);return e==="array"?o={type:"array",items:r.type==="object"?r:{type:"string"}}:e==="enum"&&(o={type:"string",enum:r.enum||[]}),t?{anyOf:[o,{type:"null"}],...n}:{...o,...n}}function Op(e,t){let{title:r,description:n,"X-ReasoningPrompt":o,...a}=e;if(t)if(e.anyOf&&Array.isArray(e.anyOf)){let i=e.anyOf.find(l=>typeof l=="object"&&(l.type!=="null"||l.$ref));return {anyOf:[{...typeof i=="object"?i:{}},{type:"null"}],...r?{title:r}:{},...n?{description:n}:{},...o?{"X-ReasoningPrompt":o}:{}}}else return {anyOf:[{...a},{type:"null"}],...r?{title:r}:{},...n?{description:n}:{},...o?{"X-ReasoningPrompt":o}:{}};else {if(e.anyOf&&Array.isArray(e.anyOf)){let i=e.anyOf.find(l=>typeof l=="object"&&(l.type!=="null"||l.$ref));return {...typeof i=="object"?i:{},...r?{title:r}:{},...n?{description:n}:{},...o?{"X-ReasoningPrompt":o}:{}}}return e}}function Ct(e,t){if(e.anyOf&&Array.isArray(e.anyOf)){let r=e.anyOf.map(n=>typeof n=="object"&&n.type==="null"?n:t);return {...e,anyOf:r}}return t}function Ep(e,t){if(e.anyOf&&Array.isArray(e.anyOf)){let r=e.anyOf.findIndex(n=>typeof n=="object"&&(n.type!=="null"||n.$ref));if(r!==-1){let n=e.anyOf[r];if(typeof n=="object"){let o=Al(typeof n.type=="string"?n.type:"string"),a=e.anyOf.find(i=>typeof i=="object"&&i.type==="null")||{type:"null"};return {...e,anyOf:[o,a],...t}}}}return {...e,...t}}function q0(e,t,r,n){let o=ls(n),a={...o,title:qo(r),...Array.isArray(o.enum)&&{type:"string"}},i=Ct(n,a),s=e.properties||{},l={},c=false;if(Object.keys(s).forEach(u=>{u===t&&r!==t?(l[r]=i,c=true):kp(s[u])&&(l[u]=s[u]);}),!c&&r!==t&&(l[r]=i,delete l[t]),r!==t){let u=Array.isArray(e.required)?e.required.map(d=>d===t?r:d):[];return {...e,properties:l,required:u}}else return {...e,properties:{...l,[t]:i}}}function SC(e,t){if(e.anyOf&&Array.isArray(e.anyOf))return SC(ls(e),t);if(e.type==="object"&&e.properties)return e.properties[t];if(e.type==="array"&&e.items){if(Array.isArray(e.items))return e.items[parseInt(t)];if(t==="*")return e.items}throw new Error(`Invalid path segment "${t}"`)}function NC(e,t,r){if(e.anyOf&&Array.isArray(e.anyOf)){let n=NC(ls(e),t,r);return Ct(e,n)}if(e.type==="object"&&e.properties)return {...e,properties:{...e.properties,[t]:r}};if(e.type==="array"&&e.items){if(Array.isArray(e.items))return {...e,items:e.items.map((n,o)=>o===parseInt(t)?r:n)};if(t==="*")return {...e,items:r}}throw new Error(`Invalid path segment "${t}"`)}function Cj(e,t){let r=[],n=[],o=e;for(let a of t.split(".")){for(;o.$ref;){let i=o.$ref.split("/");if(i.shift()!=="#")throw new Error(`Invalid $ref "${o.$ref}"`);r=i,n=[],o=i.reduce((s,l)=>s[l],e);}if(o.anyOf&&Array.isArray(o.anyOf)&&(o=ls(o)),o.type==="object"&&o.properties)n.push(a),o=o.properties[a];else if(o.type==="array"&&o.items)if(Array.isArray(o.items))n.push(a),o=o.items[parseInt(a)];else if(a==="*"||a===parseInt(a).toString())n.push("*"),o=o.items;else throw new Error(`Invalid path segment "${a}" for array type`)}return [r,n]}function CC(e,t,r,n){let[o,a]=Cj(e,t);function i(l,c){if(c.length===0)return l;let[u,...d]=c;if(d.length===0){let m=(l.properties||{})[u];return q0(l,u,r,n??m)}return NC(l,u,i(SC(l,u),d))}function s(l,c){if(c.length===0){let h=o.reduce((y,p)=>y[p],e);return i(h,a)}let[u,...d]=c;return {...l,[u]:s(l[u],d)}}return s(e,o)}function Ej({onChange:e,setDisplayEvanescentButtons:t,node:r,editMode:n,setOpenLayoutDialog:o}){let[a,i]=useState(false),[s,l]=useState({title:r.title||"",description:r.description||"","X-ReasoningPrompt":r["X-ReasoningPrompt"]||"",maxLength:r.maxLength||void 0}),[c,u]=useState(r.title||""),[d,m]=useState(s.description),[h,y]=useState(!!r["X-ReasoningPrompt"]),[p,f]=useState(r.title||"");useEffect(()=>{u(r.title||""),l({title:r.title||"",description:r.description||"","X-ReasoningPrompt":r["X-ReasoningPrompt"]||"",maxLength:r.maxLength||void 0}),y(!!r["X-ReasoningPrompt"]);},[r]),useEffect(()=>{m(s.description||"");},[s.description]);let x=()=>{if(c!==(r.title||"")){let E={...s,title:c||""};e(Ep(r,E));}},g=()=>{if(d!==s.description){let E={...s,description:d};e(Ep(r,E));}},v=async()=>{window.confirm("Are you sure you want to erase the current schema? This action cannot be undone.")&&await e({title:"",type:"object",properties:{}});},w=(E,C)=>{if(typeof E!="object"||E===null)return E;let b={...E};if(C in b&&delete b[C],b.properties&&typeof b.properties=="object"){let D={};for(let k of Object.keys(b.properties))D[k]=w(b.properties[k],C);b.properties=D;}if(b.patternProperties&&typeof b.patternProperties=="object"){let D={};for(let k of Object.keys(b.patternProperties))D[k]=w(b.patternProperties[k],C);b.patternProperties=D;}if("additionalProperties"in b){let D=b.additionalProperties;typeof D=="object"&&D!==null&&(b.additionalProperties=w(D,C));}"items"in b&&b.items&&(Array.isArray(b.items)?b.items=b.items.map(D=>w(D,C)):typeof b.items=="object"&&(b.items=w(b.items,C)));let O=["anyOf","oneOf","allOf"];for(let D of O)Array.isArray(b[D])&&(b[D]=b[D].map(k=>w(k,C)));if(b.not&&typeof b.not=="object"&&(b.not=w(b.not,C)),b.if&&typeof b.if=="object"&&(b.if=w(b.if,C)),b.then&&typeof b.then=="object"&&(b.then=w(b.then,C)),b.else&&typeof b.else=="object"&&(b.else=w(b.else,C)),b.propertyNames&&typeof b.propertyNames=="object"&&(b.propertyNames=w(b.propertyNames,C)),b.contains&&typeof b.contains=="object"&&(b.contains=w(b.contains,C)),b.dependentSchemas&&typeof b.dependentSchemas=="object"){let D={};for(let k of Object.keys(b.dependentSchemas))D[k]=w(b.dependentSchemas[k],C);b.dependentSchemas=D;}if(b.$defs&&typeof b.$defs=="object"){let D={};for(let k of Object.keys(b.$defs))D[k]=w(b.$defs[k],C);b.$defs=D;}if(b.definitions&&typeof b.definitions=="object"){let D={};for(let k of Object.keys(b.definitions))D[k]=w(b.definitions[k],C);b.definitions=D;}return b},N=async()=>{if(window.confirm("Are you sure you want to delete all descriptions in this schema? This cannot be undone.")){let E=w(r,"description");await e(E);}},S=async()=>{if(window.confirm("Are you sure you want to delete all reasoning prompts in this schema? This cannot be undone.")){let E=w(r,"X-ReasoningPrompt");await e(E);}},_=()=>{try{let E=new Blob([JSON.stringify(r,null,2)],{type:"application/json"}),C=URL.createObjectURL(E),b=document.createElement("a");b.href=C;let O=r?.title?`${r.title.toLowerCase().replace(/\s+/g,"-")}.json`:"schema.json";b.download=O,document.body.appendChild(b),b.click(),document.body.removeChild(b),URL.revokeObjectURL(C),typeof toast<"u"&&toast.success("Download Started",{description:"Your schema has been downloaded successfully."});}catch(E){console.error("Error downloading schema:",E),typeof toast<"u"&&toast.error("Download Failed",{description:"There was an error downloading your schema."});}},P=()=>{try{let E=document.createElement("input");E.type="file",E.accept=".json",E.style.display="none",E.addEventListener("change",C=>{let b=C.target;if(b.files&&b.files.length>0){let O=b.files[0],D=new FileReader;D.onload=async k=>{try{let I=k.target?.result,F=JSON.parse(I);await e(F),typeof toast<"u"&&toast.success("Schema Uploaded",{description:"Your schema has been uploaded and applied successfully."});}catch(I){console.error("Error parsing uploaded schema:",I),typeof toast<"u"&&toast.error("Upload Failed",{description:"The uploaded file is not a valid JSON schema."});}},D.readAsText(O);}document.body.removeChild(E);}),document.body.appendChild(E),E.click();}catch(E){console.error("Error uploading schema:",E),typeof toast<"u"&&toast.error("Upload Failed",{description:"There was an error uploading your schema."});}},R=()=>{try{let E=JSON.stringify(r,null,2);navigator.clipboard.writeText(E).then(()=>{typeof toast<"u"&&toast.success("Copied to Clipboard",{description:"Your schema has been copied to the clipboard."});}).catch(C=>{console.error("Error copying to clipboard:",C);let b=document.createElement("textarea");b.value=E,b.style.position="fixed",b.style.left="-999999px",b.style.top="-999999px",document.body.appendChild(b),b.focus(),b.select();try{document.execCommand("copy"),b.remove(),typeof toast<"u"&&toast.success("Copied to Clipboard",{description:"Your schema has been copied to the clipboard."});}catch(O){console.error("Fallback: Oops, unable to copy",O),typeof toast<"u"&&toast.error("Copy Failed",{description:"There was an error copying your schema to the clipboard."}),b.remove();}});}catch(E){console.error("Error preparing schema for copy:",E),typeof toast<"u"&&toast.error("Copy Failed",{description:"There was an error preparing your schema for copying."});}};return jsxs("div",{className:"pb-4",children:[jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between group pl-0",children:[jsxs("div",{className:"flex items-center space-x-2 flex-1 min-w-0",children:[jsx(nt,{className:"md:text-lg text-lg text-gray-900 font-medium border-none rounded-none p-0 m-0 shadow-none outline-none focus-visible:ring-0 h-5",value:c,placeholder:"Add a title to your schema",onChange:E=>u(E.target.value),onBlur:x,onKeyDown:E=>{E.key==="Enter"&&x();},onMouseEnter:()=>t?.(true),onMouseLeave:()=>t?.(false),autoFocus:true,disabled:n==="readOnly"||n==="promptOnly"}),s["X-ReasoningPrompt"]&&jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(Atom,{className:"w-4 h-4 text-purple-300"})}),jsxs(et,{className:"max-w-xs",children:[jsx("div",{className:"text-xs text-purple-300 mb-1",children:"Reasoning Prompt:"}),jsx("div",{className:"",children:s["X-ReasoningPrompt"]})]})]})]}),jsx("div",{className:"flex items-center gap-2",children:jsxs(dr,{children:[jsx(fr,{asChild:true,children:jsx(V,{type:"button",variant:"ghost",size:"iconSm",className:"flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity",children:jsx(EllipsisVertical,{className:"h-4 w-4"})})}),jsxs(pr,{align:"end",children:[n==="editable"&&jsxs(ge,{onClick:v,children:[jsx(Trash2,{className:"h-4 w-4 mr-2"}),"Delete Schema"]}),(n==="editable"||n==="promptOnly")&&jsxs(ge,{onClick:N,children:[jsx(MessageCircleOff,{className:"h-4 w-4 mr-2"}),"Delete all descriptions"]}),(n==="editable"||n==="promptOnly")&&jsxs(ge,{onClick:S,children:[jsx(lC,{className:"h-4 w-4 mr-2 text-muted-foreground"}),"Delete all reasoning prompts"]}),jsxs(ge,{onClick:_,children:[jsx(Download,{className:"h-4 w-4 mr-2"}),"Download"]}),jsxs(ge,{onClick:P,children:[jsx(CloudUpload,{className:"h-4 w-4 mr-2"}),"Upload"]}),jsxs(ge,{onClick:R,children:[jsx(Copy,{className:"h-4 w-4 mr-2"}),"Copy to clipboard"]})]})]})})]}),jsx("div",{className:"pb-2",children:jsxs("div",{className:"flex items-start justify-between",children:[jsx(nn,{className:"min-h-6 md:text-sm max-h-64 text-sm text-gray-600 font-normal rounded-none border-none p-0 m-0 shadow-none outline-none focus-visible:ring-0 resize-none",value:d,placeholder:"Add a description to your schema",onChange:E=>m(E.target.value),onBlur:g,onKeyDown:E=>{E.key==="Enter"&&(E.ctrlKey||E.metaKey)&&g();},onMouseEnter:()=>t?.(true),onMouseLeave:()=>t?.(false),autoFocus:true,disabled:n==="readOnly"}),jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(V,{type:"button",variant:"ghost",size:"icon",className:"p-0 m-0",onClick:()=>{f(r.title||""),i(true);},children:jsx(Pencil,{className:"w-1 h-1 group-hover:opacity-100 opacity-0 text-gray-500"})})}),jsx(et,{className:"max-w-xs",children:jsx("p",{children:"Edit schema properties"})})]})]})}),jsx(QN,{isOpen:a,onClose:()=>i(false),path:"#",schemaTitle:p,setSchemaTitle:f,metadataValues:s,setMetadataValues:l,showReasoningPromptField:h,setShowReasoningPromptField:y,onChange:e,node:r,editMode:n})]})}function kp(e){return typeof e=="object"&&e!==null}function ga({name:e,node:t,onChange:r,jsonSchema:n,setJsonSchema:o,path:a,defs:i,canDelete:s=false,onDelete:l,onNameChange:c,setDefsAccordionOpen:u,draggedParentRef:d,draggedPropertyRef:m,editMode:h="editable",setDisplayEvanescentButtons:y,hidePencilButton:p=false}){let f=a,{type:x,isNullable:g}=ln(t),[v,w]=useState(x),[N,S]=useState(g),_=h==="editable",[R,E]=useState(false),[C,b]=useState(false),[O,D]=useState(""),[k,I]=useState({title:t.title||"",description:t.description||"","X-ReasoningPrompt":t["X-ReasoningPrompt"]||"",maxLength:t.maxLength||void 0}),[F,Z]=useState(void 0);useEffect(()=>{F&&(r(Ct(t,{$ref:`#/$defs/${F}`})),Z(void 0));},[F]);let[pe,ie]=useState(e),[J,ue]=useState(null),re=B=>{if(U.properties){let se=Object.keys(U.properties);return ui(B,se,e,"property")}return ui(B,[],e,"name")},[X$1,$]=useState(e),[L,le]=useState(""),[ae,Oe]=useState(null),[ye,ft]=useState(true),[zt,st]=useState(false),[Et,tt]=useState(e),[xe,me]=useState(null),[_e,pt]=useState(""),Fe=kt.useRef(null),Me=kt.useRef(null),[ce,G]=useState(!!t["X-ReasoningPrompt"]),U=ls(t);useEffect(()=>{let{type:B,isNullable:se}=ln(t);w(B),S(se),$(e),I({title:t.title||"",description:t.description||"","X-ReasoningPrompt":t["X-ReasoningPrompt"]||"",maxLength:t.maxLength||void 0}),G(!!t["X-ReasoningPrompt"]);},[t,e]);let H=B=>{if(B==="enum")if(v!=="enum"){D(v),b(true);return}else return;w(B);let se=Mn(B,N,t);r(se);},je=B=>{let Q=Mn("enum",N,{enum:B,type:"string"});w("enum"),r(Q);},Ue=()=>{},Le=B=>{S(B);let se=Op(t,B);r(se);},W=()=>{let B=qx(Et);if(B){me(B);return}me(null),Et&&Et!==e&&c&&c(Et),st(false);},Pe=()=>{if(!_e.trim())return;let B=U.enum||[],se={...U,enum:[...B,_e.trim()]};r(Ct(t,se)),pt("");let Q=document.querySelector('input[placeholder="New enum value"]');Q&&Q.focus();},Pt=B=>{let se=(U.enum||[]).filter((qe,mt)=>mt!==B),Q={...U,enum:se};r(Ct(t,Q));},Hs=(B,se)=>{let Q=(U.enum||[]).map((mt,Or)=>Or===B?se:mt),qe={...U,enum:Q};r(Ct(t,qe));},_t=(B,se)=>{let Q=U.properties||{},qe=Object.keys(Q),mt=qe.indexOf(B),Or=qe.indexOf(se);if(mt===-1||Or===-1||mt===Or){console.warn("[DRAG] Drag and drop reorder failed: Invalid keys or indices. sourceIndex:",mt,"targetIndex:",Or);return}let Ah=qe;mt<Or?Ah=[...qe.slice(0,mt),...qe.slice(mt+1,Or+1),B,...qe.slice(Or+1)]:Ah=[...qe.slice(0,Or),B,...qe.slice(Or,mt),...qe.slice(mt+1)];let Vx={};Ah.forEach($h=>{if(Object.prototype.hasOwnProperty.call(Q,$h)){let Ih=Q[$h];typeof Ih=="object"&&Ih!==null&&(Vx[$h]=Ih);}});let NO={...U,properties:Vx},CO=Ct(t,NO);r(CO);},Ot=(B,se)=>{B.stopPropagation(),B.dataTransfer.setData("text/plain",se),B.dataTransfer.effectAllowed="move",d.current=f,m.current=se;let Q=document.createElement("div"),qe=B.currentTarget.getBoundingClientRect();Q.style.width=`${qe.width}px`,Q.style.padding="8px",Q.style.border="1px solid #90cdf4",Q.style.borderRadius="4px",Q.style.backgroundColor="rgba(255, 255, 255, 0.7)",Q.style.boxShadow="0 2px 5px rgba(0,0,0,0.1)",Q.style.opacity="0.8",Q.style.position="fixed",Q.style.zIndex="9999",Q.style.pointerEvents="none",Q.innerHTML=`<span style="font-weight: medium">${se}</span>`,document.body.appendChild(Q),B.dataTransfer.setDragImage(Q,10,10),setTimeout(()=>{document.body.removeChild(Q);},0);},Rr=(B,se)=>{B.preventDefault();let Q=U.properties||{},qe=Object.keys(Q),mt=qe.indexOf(m.current),Or=qe.indexOf(se);B.dataTransfer.dropEffect="move",d.current===f&&se!==m.current&&(B.currentTarget.classList.add(mt>Or?"border-t-2":"border-b-2"),B.currentTarget.classList.add("border-grey-700"),B.currentTarget.classList.add("border-dashed"));},Kd=B=>{B.stopPropagation(),B.currentTarget.classList.remove("border-t-2"),B.currentTarget.classList.remove("border-b-2"),B.currentTarget.classList.remove("border-grey-700"),B.currentTarget.classList.remove("border-dashed");},Gd=(B,se)=>{B.stopPropagation(),B.preventDefault();let Q=B.dataTransfer.getData("text/plain");B.currentTarget.classList.remove("border-t-2"),B.currentTarget.classList.remove("border-b-2"),B.currentTarget.classList.remove("border-grey-700"),B.currentTarget.classList.remove("border-dashed"),Q&&Q!==se&&d.current===f&&_t(Q,se);},Vc=B=>{},qx=B=>ui(B,Object.keys(U.properties||[]),e,"property"),SO=(B,se)=>{switch(B){case "string":return jsx(Type,{className:"w-4 h-4"});case "number":case "integer":return jsx(Hash,{className:"w-4 h-4"});case "boolean":return jsx(ToggleLeft,{className:"w-4 h-4"});case "enum":return jsx(List,{className:"w-4 h-4"});case "object":return jsx(Braces,{className:"w-4 h-4"});case "array":return jsx(Brackets,{className:"w-4 h-4"});case "date":return jsx(Calendar,{className:"w-4 h-4"});case "time":return jsx(Clock,{className:"w-4 h-4"});case "datetime":return jsx(CalendarClock,{className:"w-4 h-4"});case "$ref":return U0(se||"");default:return jsx(Shapes,{className:"w-4 h-4"})}};return jsxs("div",{children:[a!=="#"&&jsxs("div",{id:`schema-field-${a.replace(/^#\.?/,"").split(".").join("-")}`,className:"flex flex-col sm:flex-row items-start sm:items-center justify-between group pl-0 hover:bg-gray-100 py-0",children:[_?jsx(Xe,{children:jsx(Qe,{asChild:true,children:jsx(GripVertical,{className:"w-6 h-12 py-4 px-1 group-hover:text-gray-500 text-white cursor-pointer"})})}):jsx("div",{className:"w-6 h-12 py-4 px-1"}),jsxs("div",{className:"flex items-center space-x-2 flex-1 min-w-0",children:[zt&&_?jsx(nt,{className:`w-40 h-6 px-1 border-none p-0 m-0 shadow-none
58
+ `).filter(Boolean),m=i||jsx(Sparkles,{className:"h-3 w-3"}),p=i||jsx(Sparkles,{className:"h-3 w-3"});i||jsx(Sparkles,{className:"h-4 w-4"});return r==="compact"?jsxs("div",{className:R("border-l-2 border-red-400 w-full max-w-full overflow-hidden box-border",t),children:[jsxs("div",{className:"flex items-center justify-between px-3 py-2 w-full min-w-0 box-border",children:[jsxs("button",{onClick:()=>u(!c),className:"flex items-center gap-2 hover:bg-white/5 rounded px-1 py-1 transition-colors text-left flex-1 min-w-0 overflow-hidden",title:c?"Click to collapse error details":"Click to expand error details",children:[c?jsx(ChevronDown,{className:"h-3 w-3 text-red-400 flex-shrink-0"}):jsx(ChevronRight,{className:"h-3 w-3 text-red-400 flex-shrink-0"}),jsx(AlertCircle,{className:"h-3 w-3 text-red-400 flex-shrink-0"}),jsxs("span",{className:"text-xs font-medium text-red-300 truncate",children:[f.length," validation error",f.length!==1?"s":""]})]}),d&&jsxs(K,{variant:"ghost",size:"sm",onClick:g,disabled:s,className:"h-6 px-2 text-xs text-red-400 hover:text-red-300 hover:bg-white/5 flex-shrink-0",children:[jsx("span",{className:"mr-1",children:p}),s?"Processing...":o]})]}),c&&jsx("div",{className:"border-t border-red-400/30 bg-red-950/20 px-3 py-2 w-full overflow-hidden box-border",children:jsx("div",{className:"space-y-1 w-full max-w-full",children:f.map((y,x)=>jsx("div",{className:"text-xs text-red-200 font-mono leading-relaxed w-full max-w-full break-all overflow-hidden box-border",children:y},x))})})]}):jsxs("div",{className:R("bg-red-50 border border-red-200 rounded-none w-full max-w-full overflow-hidden box-border",t),children:[jsxs("div",{className:"flex items-center justify-between gap-3 px-3 py-2 w-full min-w-0 box-border",children:[jsxs("button",{onClick:()=>u(!c),className:"flex items-center gap-2 text-red-600 min-w-0 flex-1 rounded px-1 py-1 transition-colors text-left hover:bg-red-100 overflow-hidden",title:c?"Click to collapse error details":"Click to expand error details",children:[c?jsx(ChevronDown,{className:"h-4 w-4 flex-shrink-0"}):jsx(ChevronRight,{className:"h-4 w-4 flex-shrink-0"}),jsx(AlertCircle,{className:"h-4 w-4 flex-shrink-0"}),jsxs("span",{className:"text-sm font-medium",children:["Schema validation errors (",f.length,")"]})]}),d&&jsxs(K,{variant:"ghost",size:"sm",onClick:g,disabled:s,className:"h-7 px-2 text-xs flex-shrink-0 text-red-700 hover:text-red-900 hover:bg-red-100",children:[jsx("span",{className:"mr-1",children:m}),s?"Processing...":o]})]}),c&&jsx("div",{className:"border-t border-red-200 px-3 py-2 space-y-3 w-full overflow-hidden box-border",children:jsx("div",{className:"space-y-3 w-full max-w-full",children:f.map((y,x)=>jsx("div",{className:"text-sm text-red-700 leading-relaxed w-full max-w-full break-all overflow-hidden box-border",style:{overflowWrap:"anywhere",whiteSpace:"pre-wrap"},children:y},x))})})]})}var XC=({className:e})=>jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",className:e,children:[jsx("path",{d:"M4.50684 4.50684L4.50586 4.50879C4.22439 4.78888 4.02809 5.23199 4.00684 5.90918C3.98543 6.59363 4.14785 7.45733 4.52539 8.45508C5.27958 10.4479 6.8234 12.7994 9.00586 14.9922L9.41895 15.3936C11.4922 17.3656 13.6768 18.7683 15.5459 19.4756C16.5435 19.853 17.4075 20.0156 18.0918 19.9941C18.7685 19.9728 19.2112 19.7764 19.4912 19.4951L19.4932 19.4932L20.9062 20.9062C20.1717 21.6433 19.1882 21.9606 18.1543 21.9932C17.1269 22.0254 15.9933 21.7828 14.8379 21.3457C12.5243 20.4702 9.94078 18.7448 7.59473 16.4092L7.5918 16.4062C5.25616 14.0603 3.53088 11.4767 2.65527 9.16309C2.21804 8.00764 1.97568 6.87412 2.00781 5.84668C2.04028 4.81247 2.35546 3.8275 3.09277 3.09277L4.50684 4.50684Z"}),jsx("path",{d:"M13.4141 13.4141C13.0521 13.776 12.5523 14 12 14C10.8955 13.9999 10 13.1045 10 12C10.0001 11.4478 10.2241 10.9478 10.5859 10.5859L13.4141 13.4141Z"}),jsx("path",{d:"M9.00684 9.00684L9.00586 9.00879C6.82328 11.2018 5.2795 13.5531 4.52539 15.5459C4.14787 16.5437 3.98535 17.4074 4.00684 18.0918C4.02551 18.6841 4.17791 19.0974 4.4043 19.3789L4.50586 19.4912L4.50879 19.4951C4.7889 19.7764 5.23232 19.9729 5.90918 19.9941C6.5936 20.0155 7.45741 19.8531 8.45508 19.4756C10.4483 18.7213 12.7999 17.1764 14.9932 14.9932L16.4072 16.4072L16.4062 16.4092C14.0602 18.7449 11.4767 20.4701 9.16309 21.3457C8.00768 21.7829 6.87409 22.0253 5.84668 21.9932C4.81319 21.9607 3.82929 21.6444 3.09473 20.9082V20.9092C2.3564 20.1744 2.04037 19.1891 2.00781 18.1543C1.97558 17.1268 2.21803 15.9935 2.65527 14.8379C3.53081 12.5242 5.25597 9.94089 7.5918 7.59473L7.59277 7.59277L9.00684 9.00684Z"}),jsx("path",{d:"M8.36976 4.12659C7.61309 3.36993 8.16226 2.27655 9.16309 2.65527V2.65527C11.332 3.47613 13.7377 5.04397 15.9629 7.16113L16.4062 7.5918L16.4092 7.59473C18.7448 9.94079 20.4702 12.5243 21.3457 14.8379V14.8379C21.724 15.8378 20.63 16.3869 19.8741 15.6309L19.4459 15.2027C19.3203 15.0772 19.2204 14.929 19.1463 14.7676C18.315 12.9566 16.8991 10.922 14.9951 9.00879L14.582 8.60742C12.7896 6.90239 10.9136 5.624 9.23054 4.85171C9.06908 4.77763 8.92086 4.67769 8.79524 4.55208L8.36976 4.12659Z"}),jsx("path",{d:"M8.36975 4.1272C7.61354 3.37098 8.16285 2.27641 9.16309 2.65491V2.65491C11.3321 3.47574 13.7376 5.04354 15.9629 7.16077L16.4062 7.59143L16.4092 7.59436C18.7449 9.94048 20.4702 12.5238 21.3457 14.8375V14.8375C21.7244 15.8384 20.6302 16.3877 19.8735 15.631L19.448 15.2054C19.3223 15.0798 19.2224 14.9315 19.1483 14.77C18.3171 12.9582 16.9002 10.9226 14.9951 9.00842L14.582 8.60706C12.7892 6.90162 10.9127 5.62344 9.22941 4.85125C9.06805 4.77723 8.91992 4.67737 8.79439 4.55184L8.36975 4.1272Z"}),jsx("line",{x1:"2.10074",y1:"2.10059",x2:"21.8997",y2:"21.8996",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),jsx("path",{d:"M18.1543 2.00696C19.1888 2.03955 20.1735 2.35592 20.9082 3.09387L21.041 3.2345C21.6826 3.95158 21.9627 4.87693 21.9932 5.84583C22.0253 6.8732 21.7829 8.00686 21.3457 9.16223C20.9378 10.2402 20.3427 11.375 19.5898 12.5187L18.1436 11.0724C18.7151 10.1625 19.1638 9.2782 19.4756 8.45422C19.853 7.45658 20.0156 6.5927 19.9941 5.90833C19.9728 5.23157 19.7764 4.78799 19.4951 4.50793C19.4925 4.50598 19.4896 4.50339 19.4873 4.5011C19.2071 4.22177 18.7655 4.02727 18.0918 4.00598C17.4075 3.9845 16.5435 4.14714 15.5459 4.52454C14.7218 4.83638 13.8358 5.28301 12.9258 5.85461L11.4795 4.4093C12.6235 3.65643 13.7597 3.06241 14.8379 2.65442C15.9933 2.21728 17.1269 1.97473 18.1543 2.00696Z"})]});var Ni=create((e,t)=>({tabValue:"playground",setTabValue:r=>e({tabValue:r}),activeView:"table",activeEvaluationTab:"timeline",showInfoPanel:true,docId:null,hoverFieldPath:null,selectedFieldPath:null,metricsSelection:null,metricsSelectedDocumentId:null,metricsViewedDocumentId:null,metricsAlignmentKeyPath:null,documentExtractionStatus:{},isGeneratingSchema:false,isExtracting:{},isProcessingGroundTruth:false,processingIterations:new Set,showSchemaEditor:false,consensusEnabled:false,cellColorState:"none",setConsensusEnabled:r=>e({consensusEnabled:r}),setCellColorState:r=>e({cellColorState:r}),setShowInfoPanel:r=>e({showInfoPanel:r}),setShowSchemaEditor:r=>e({showSchemaEditor:r}),getDocumentStatus:(r,n)=>{let a=n?`${n}-${r}`:`${r}`;return t().documentExtractionStatus[a]||"completed"},setActiveView:r=>{e({activeView:r});},setActiveEvaluationTab:r=>{e({activeEvaluationTab:r});},setDocumentExtractionStatus:(r,n,a)=>{let o=n?`${n}-${r}`:`dataset-${r}`,i=t().documentExtractionStatus,s,l=new Set(t().processingIterations);if(a==="completed"){let{[o]:u,...d}=i;s=d,n&&(Object.keys(s).some(f=>f.includes(n))||l.delete(n));}else s={...i,[o]:a},n&&l.add(n),setTimeout(()=>{t().documentExtractionStatus[o]===a&&(console.log(`${r} under iteration=${n} is still ${a}. Setting to completed.`),t().setDocumentExtractionStatus(r,n,"completed"));},6e5);let c={};l.forEach(u=>{c[u]=true;}),e({processingIterations:l,documentExtractionStatus:s,isExtracting:c,isProcessingGroundTruth:Object.keys(s).some(u=>u.includes("dataset"))});},setIsGeneratingSchema:r=>{e({isGeneratingSchema:r});},setDocId:r=>e({docId:r}),setHoverFieldPath:r=>e({hoverFieldPath:r}),setSelectedFieldPath:r=>e({selectedFieldPath:r,hoverFieldPath:r}),setMetricsSelection:r=>e({metricsSelection:r}),setMetricsSelectedDocumentId:r=>e({metricsSelectedDocumentId:r}),setMetricsViewedDocumentId:r=>e({metricsViewedDocumentId:r}),setMetricsAlignmentKeyPath:r=>e({metricsAlignmentKeyPath:r}),resetForProjectChange:()=>{e({documentExtractionStatus:{},processingIterations:new Set,isExtracting:{},isProcessingGroundTruth:false,isGeneratingSchema:false});}}));function Ci(e,t=[],r,n="name"){return /^[a-z_][a-z0-9_]{0,63}$/.test(e)?mL.includes(e)?`"${e}" is a Python reserved keyword`:hL.includes(e)?`"${e}" is a Pydantic reserved name`:(r?t.filter(o=>o.toLowerCase()!==r.toLowerCase()):t).some(o=>o.toLowerCase()===e.toLowerCase())?`A ${n} with the name "${e}" already exists (names are case-insensitive)`:null:"Name must start with a lowercase letter or underscore, contain only lowercase letters, numbers, or underscores, and be at most 64 characters long"}var mL=["false","none","true","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield"],hL=["__root__","config","schema_extra","model_config","model_fields","model_post_init","model_validate","model_dump"];function Ya(e){return e.replace(/([a-z\d])([A-Z])/g,"$1 $2").replace(/[^a-zA-Z0-9]+/g," ").split(" ").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function yn(e){if(e.anyOf&&Array.isArray(e.anyOf)){let t=e.anyOf.find(n=>typeof n=="object"&&(n.type!=="null"||n.$ref||n.enum)),r=e.anyOf.some(n=>typeof n=="object"&&n.type==="null");return t&&typeof t=="object"?t.$ref?{type:"$ref",isNullable:r}:t.enum?{type:"enum",isNullable:r}:t.type==="string"&&t.format==="date"?{type:"date",isNullable:r}:t.type==="string"&&t.format==="iso-time"?{type:"time",isNullable:r}:t.type==="string"&&t.format==="date-time"?{type:"datetime",isNullable:r}:{type:t.type?.toString()||"string",isNullable:r}:{type:"string",isNullable:r}}return e.enum?{type:"enum",isNullable:false}:e.$ref?{type:"$ref",isNullable:false}:e.type==="string"&&e.format==="date"?{type:"date",isNullable:false}:e.type==="string"&&e.format==="iso-time"?{type:"time",isNullable:false}:e.type==="string"&&e.format==="date-time"?{type:"datetime",isNullable:false}:{type:e.type?.toString()||"string",isNullable:false}}var dv=e=>{switch(e){case "Address":return jsx(MapPin,{className:"w-4 h-4"});case "Price":return jsx(DollarSign,{className:"w-4 h-4"});case "Person":return jsx(User,{className:"w-4 h-4"});case "Company":return jsx(Building2,{className:"w-4 h-4"});case "Event":return jsx(CalendarDays,{className:"w-4 h-4"});default:return jsx(Link,{className:"w-4 h-4"})}};function cc(e){switch(e){case "string":return {type:"string"};case "number":return {type:"number"};case "integer":return {type:"integer"};case "boolean":return {type:"boolean"};case "object":return {type:"object",properties:{},required:[]};case "array":return {type:"array",items:{type:"string"}};case "$ref":return {};case "enum":return {enum:[],type:"string"};case "date":return {type:"string",format:"date"};case "time":return {type:"string",format:"iso-time"};case "datetime":return {type:"string",format:"date-time"};default:return {type:"string"}}}function Yn(e,t,r){let n={};r.title&&(n.title=r.title),r.description&&(n.description=r.description),r["X-ReasoningPrompt"]&&(n["X-ReasoningPrompt"]=r["X-ReasoningPrompt"]);let a=cc(e);return e==="array"?a={type:"array",items:r.type==="object"?r:{type:"string"}}:e==="enum"&&(a={type:"string",enum:r.enum||[]}),t?{anyOf:[a,{type:"null"}],...n}:{...a,...n}}function em(e,t){let{title:r,description:n,"X-ReasoningPrompt":a,...o}=e;if(t)if(e.anyOf&&Array.isArray(e.anyOf)){let i=e.anyOf.find(l=>typeof l=="object"&&(l.type!=="null"||l.$ref));return {anyOf:[{...typeof i=="object"?i:{}},{type:"null"}],...r?{title:r}:{},...n?{description:n}:{},...a?{"X-ReasoningPrompt":a}:{}}}else return {anyOf:[{...o},{type:"null"}],...r?{title:r}:{},...n?{description:n}:{},...a?{"X-ReasoningPrompt":a}:{}};else {if(e.anyOf&&Array.isArray(e.anyOf)){let i=e.anyOf.find(l=>typeof l=="object"&&(l.type!=="null"||l.$ref));return {...typeof i=="object"?i:{},...r?{title:r}:{},...n?{description:n}:{},...a?{"X-ReasoningPrompt":a}:{}}}return e}}function kt(e,t){if(e.anyOf&&Array.isArray(e.anyOf)){let r=e.anyOf.map(n=>typeof n=="object"&&n.type==="null"?n:t);return {...e,anyOf:r}}return t}function Zp(e,t){if(e.anyOf&&Array.isArray(e.anyOf)){let r=e.anyOf.findIndex(n=>typeof n=="object"&&(n.type!=="null"||n.$ref));if(r!==-1){let n=e.anyOf[r];if(typeof n=="object"){let a=cc(typeof n.type=="string"?n.type:"string"),o=e.anyOf.find(i=>typeof i=="object"&&i.type==="null")||{type:"null"};return {...e,anyOf:[a,o],...t}}}}return {...e,...t}}function fv(e,t,r,n){let a=As(n),o={...a,title:Ya(r),...Array.isArray(a.enum)&&{type:"string"}},i=kt(n,o),s=e.properties||{},l={},c=false;if(Object.keys(s).forEach(u=>{u===t&&r!==t?(l[r]=i,c=true):Qp(s[u])&&(l[u]=s[u]);}),!c&&r!==t&&(l[r]=i,delete l[t]),r!==t){let u=Array.isArray(e.required)?e.required.map(d=>d===t?r:d):[];return {...e,properties:l,required:u}}else return {...e,properties:{...l,[t]:i}}}function fE(e,t){if(e.anyOf&&Array.isArray(e.anyOf))return fE(As(e),t);if(e.type==="object"&&e.properties)return e.properties[t];if(e.type==="array"&&e.items){if(Array.isArray(e.items))return e.items[parseInt(t)];if(t==="*")return e.items}throw new Error(`Invalid path segment "${t}"`)}function pE(e,t,r){if(e.anyOf&&Array.isArray(e.anyOf)){let n=pE(As(e),t,r);return kt(e,n)}if(e.type==="object"&&e.properties)return {...e,properties:{...e.properties,[t]:r}};if(e.type==="array"&&e.items){if(Array.isArray(e.items))return {...e,items:e.items.map((n,a)=>a===parseInt(t)?r:n)};if(t==="*")return {...e,items:r}}throw new Error(`Invalid path segment "${t}"`)}function gL(e,t){let r=[],n=[],a=e;for(let o of t.split(".")){for(;a.$ref;){let i=a.$ref.split("/");if(i.shift()!=="#")throw new Error(`Invalid $ref "${a.$ref}"`);r=i,n=[],a=i.reduce((s,l)=>s[l],e);}if(a.anyOf&&Array.isArray(a.anyOf)&&(a=As(a)),a.type==="object"&&a.properties)n.push(o),a=a.properties[o];else if(a.type==="array"&&a.items)if(Array.isArray(a.items))n.push(o),a=a.items[parseInt(o)];else if(o==="*"||o===parseInt(o).toString())n.push("*"),a=a.items;else throw new Error(`Invalid path segment "${o}" for array type`)}return [r,n]}function mE(e,t,r,n){let[a,o]=gL(e,t);function i(l,c){if(c.length===0)return l;let[u,...d]=c;if(d.length===0){let g=(l.properties||{})[u];return fv(l,u,r,n??g)}return pE(l,u,i(fE(l,u),d))}function s(l,c){if(c.length===0){let f=a.reduce((h,m)=>h[m],e);return i(f,o)}let[u,...d]=c;return {...l,[u]:s(l[u],d)}}return s(e,a)}function yL({onChange:e,setDisplayEvanescentButtons:t,node:r,editMode:n,setOpenLayoutDialog:a}){let[o,i]=useState(false),[s,l]=useState({title:r.title||"",description:r.description||"","X-ReasoningPrompt":r["X-ReasoningPrompt"]||"",maxLength:r.maxLength||void 0}),[c,u]=useState(r.title||""),[d,g]=useState(s.description),[f,h]=useState(!!r["X-ReasoningPrompt"]),[m,p]=useState(r.title||"");useEffect(()=>{u(r.title||""),l({title:r.title||"",description:r.description||"","X-ReasoningPrompt":r["X-ReasoningPrompt"]||"",maxLength:r.maxLength||void 0}),h(!!r["X-ReasoningPrompt"]);},[r]),useEffect(()=>{g(s.description||"");},[s.description]);let v=()=>{if(c!==(r.title||"")){let N={...s,title:c||""};e(Zp(r,N));}},y=()=>{if(d!==s.description){let N={...s,description:d};e(Zp(r,N));}},x=async()=>{window.confirm("Are you sure you want to erase the current schema? This action cannot be undone.")&&await e({title:"",type:"object",properties:{}});},w=(N,S)=>{if(typeof N!="object"||N===null)return N;let b={...N};if(S in b&&delete b[S],b.properties&&typeof b.properties=="object"){let D={};for(let O of Object.keys(b.properties))D[O]=w(b.properties[O],S);b.properties=D;}if(b.patternProperties&&typeof b.patternProperties=="object"){let D={};for(let O of Object.keys(b.patternProperties))D[O]=w(b.patternProperties[O],S);b.patternProperties=D;}if("additionalProperties"in b){let D=b.additionalProperties;typeof D=="object"&&D!==null&&(b.additionalProperties=w(D,S));}"items"in b&&b.items&&(Array.isArray(b.items)?b.items=b.items.map(D=>w(D,S)):typeof b.items=="object"&&(b.items=w(b.items,S)));let k=["anyOf","oneOf","allOf"];for(let D of k)Array.isArray(b[D])&&(b[D]=b[D].map(O=>w(O,S)));if(b.not&&typeof b.not=="object"&&(b.not=w(b.not,S)),b.if&&typeof b.if=="object"&&(b.if=w(b.if,S)),b.then&&typeof b.then=="object"&&(b.then=w(b.then,S)),b.else&&typeof b.else=="object"&&(b.else=w(b.else,S)),b.propertyNames&&typeof b.propertyNames=="object"&&(b.propertyNames=w(b.propertyNames,S)),b.contains&&typeof b.contains=="object"&&(b.contains=w(b.contains,S)),b.dependentSchemas&&typeof b.dependentSchemas=="object"){let D={};for(let O of Object.keys(b.dependentSchemas))D[O]=w(b.dependentSchemas[O],S);b.dependentSchemas=D;}if(b.$defs&&typeof b.$defs=="object"){let D={};for(let O of Object.keys(b.$defs))D[O]=w(b.$defs[O],S);b.$defs=D;}if(b.definitions&&typeof b.definitions=="object"){let D={};for(let O of Object.keys(b.definitions))D[O]=w(b.definitions[O],S);b.definitions=D;}return b},_=async()=>{if(window.confirm("Are you sure you want to delete all descriptions in this schema? This cannot be undone.")){let N=w(r,"description");await e(N);}},E=async()=>{if(window.confirm("Are you sure you want to delete all reasoning prompts in this schema? This cannot be undone.")){let N=w(r,"X-ReasoningPrompt");await e(N);}},C=()=>{try{let N=new Blob([JSON.stringify(r,null,2)],{type:"application/json"}),S=URL.createObjectURL(N),b=document.createElement("a");b.href=S;let k=r?.title?`${r.title.toLowerCase().replace(/\s+/g,"-")}.json`:"schema.json";b.download=k,document.body.appendChild(b),b.click(),document.body.removeChild(b),URL.revokeObjectURL(S),typeof toast<"u"&&toast.success("Download Started",{description:"Your schema has been downloaded successfully."});}catch(N){console.error("Error downloading schema:",N),typeof toast<"u"&&toast.error("Download Failed",{description:"There was an error downloading your schema."});}},P=()=>{try{let N=document.createElement("input");N.type="file",N.accept=".json",N.style.display="none",N.addEventListener("change",S=>{let b=S.target;if(b.files&&b.files.length>0){let k=b.files[0],D=new FileReader;D.onload=async O=>{try{let $=O.target?.result,A=JSON.parse($);await e(A),typeof toast<"u"&&toast.success("Schema Uploaded",{description:"Your schema has been uploaded and applied successfully."});}catch($){console.error("Error parsing uploaded schema:",$),typeof toast<"u"&&toast.error("Upload Failed",{description:"The uploaded file is not a valid JSON schema."});}},D.readAsText(k);}document.body.removeChild(N);}),document.body.appendChild(N),N.click();}catch(N){console.error("Error uploading schema:",N),typeof toast<"u"&&toast.error("Upload Failed",{description:"There was an error uploading your schema."});}},T=()=>{try{let N=JSON.stringify(r,null,2);navigator.clipboard.writeText(N).then(()=>{typeof toast<"u"&&toast.success("Copied to Clipboard",{description:"Your schema has been copied to the clipboard."});}).catch(S=>{console.error("Error copying to clipboard:",S);let b=document.createElement("textarea");b.value=N,b.style.position="fixed",b.style.left="-999999px",b.style.top="-999999px",document.body.appendChild(b),b.focus(),b.select();try{document.execCommand("copy"),b.remove(),typeof toast<"u"&&toast.success("Copied to Clipboard",{description:"Your schema has been copied to the clipboard."});}catch(k){console.error("Fallback: Oops, unable to copy",k),typeof toast<"u"&&toast.error("Copy Failed",{description:"There was an error copying your schema to the clipboard."}),b.remove();}});}catch(N){console.error("Error preparing schema for copy:",N),typeof toast<"u"&&toast.error("Copy Failed",{description:"There was an error preparing your schema for copying."});}};return jsxs("div",{className:"pb-4",children:[jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between group pl-0",children:[jsxs("div",{className:"flex items-center space-x-2 flex-1 min-w-0",children:[jsx(Ze,{className:"md:text-lg text-lg text-gray-900 font-medium border-none rounded-none p-0 m-0 shadow-none outline-none focus-visible:ring-0 h-5",value:c,placeholder:"Add a title to your schema",onChange:N=>u(N.target.value),onBlur:v,onKeyDown:N=>{N.key==="Enter"&&v();},onMouseEnter:()=>t?.(true),onMouseLeave:()=>t?.(false),autoFocus:true,disabled:n==="readOnly"||n==="promptOnly"}),s["X-ReasoningPrompt"]&&jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(Atom,{className:"w-4 h-4 text-purple-300"})}),jsxs(ze,{className:"max-w-xs",children:[jsx("div",{className:"text-xs text-purple-300 mb-1",children:"Reasoning Prompt:"}),jsx("div",{className:"",children:s["X-ReasoningPrompt"]})]})]})]}),jsx("div",{className:"flex items-center gap-2",children:jsxs(mr,{children:[jsx(hr,{asChild:true,children:jsx(K,{type:"button",variant:"ghost",size:"iconSm",className:"flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity",children:jsx(EllipsisVertical,{className:"h-4 w-4"})})}),jsxs(gr,{align:"end",children:[n==="editable"&&jsxs(we,{onClick:x,children:[jsx(Trash2,{className:"h-4 w-4 mr-2"}),"Delete Schema"]}),(n==="editable"||n==="promptOnly")&&jsxs(we,{onClick:_,children:[jsx(MessageCircleOff,{className:"h-4 w-4 mr-2"}),"Delete all descriptions"]}),(n==="editable"||n==="promptOnly")&&jsxs(we,{onClick:E,children:[jsx(XC,{className:"h-4 w-4 mr-2 text-muted-foreground"}),"Delete all reasoning prompts"]}),jsxs(we,{onClick:C,children:[jsx(Download,{className:"h-4 w-4 mr-2"}),"Download"]}),jsxs(we,{onClick:P,children:[jsx(CloudUpload,{className:"h-4 w-4 mr-2"}),"Upload"]}),jsxs(we,{onClick:T,children:[jsx(Copy,{className:"h-4 w-4 mr-2"}),"Copy to clipboard"]})]})]})})]}),jsx("div",{className:"pb-2",children:jsxs("div",{className:"flex items-start justify-between",children:[jsx(pr,{className:"min-h-6 md:text-sm max-h-64 text-sm text-gray-600 font-normal rounded-none border-none p-0 m-0 shadow-none outline-none focus-visible:ring-0 resize-none",value:d,placeholder:"Add a description to your schema",onChange:N=>g(N.target.value),onBlur:y,onKeyDown:N=>{N.key==="Enter"&&(N.ctrlKey||N.metaKey)&&y();},onMouseEnter:()=>t?.(true),onMouseLeave:()=>t?.(false),autoFocus:true,disabled:n==="readOnly"}),jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(K,{type:"button",variant:"ghost",size:"icon",className:"p-0 m-0",onClick:()=>{p(r.title||""),i(true);},children:jsx(Pencil,{className:"w-1 h-1 group-hover:opacity-100 opacity-0 text-gray-500"})})}),jsx(ze,{className:"max-w-xs",children:jsx("p",{children:"Edit schema properties"})})]})]})}),jsx(jC,{isOpen:o,onClose:()=>i(false),path:"#",schemaTitle:m,setSchemaTitle:p,metadataValues:s,setMetadataValues:l,showReasoningPromptField:f,setShowReasoningPromptField:h,onChange:e,node:r,editMode:n})]})}function Qp(e){return typeof e=="object"&&e!==null}function Oo({name:e,node:t,onChange:r,jsonSchema:n,setJsonSchema:a,path:o,defs:i,canDelete:s=false,onDelete:l,onNameChange:c,setDefsAccordionOpen:u,draggedParentRef:d,draggedPropertyRef:g,editMode:f="editable",setDisplayEvanescentButtons:h,hidePencilButton:m=false}){let p=o,{type:v,isNullable:y}=yn(t),[x,w]=useState(v),[_,E]=useState(y),C=f==="editable",[T,N]=useState(false),[S,b]=useState(false),[k,D]=useState(""),[O,$]=useState({title:t.title||"",description:t.description||"","X-ReasoningPrompt":t["X-ReasoningPrompt"]||"",maxLength:t.maxLength||void 0}),[A,F]=useState(void 0);useEffect(()=>{A&&(r(kt(t,{$ref:`#/$defs/${A}`})),F(void 0));},[A]);let[X$1,H]=useState(e),[L,Q]=useState(null),z=q=>{if(ee.properties){let he=Object.keys(ee.properties);return Ci(q,he,e,"property")}return Ci(q,[],e,"name")},[ae,M]=useState(e),[j,ue]=useState(""),[ie,Ce]=useState(null),[Te,Je]=useState(true),[vt,gt]=useState(false),[bt,We]=useState(e),[ke,be]=useState(null),[re,me]=useState(""),ye=Rt.useRef(null),ge=Rt.useRef(null),[Z,W]=useState(!!t["X-ReasoningPrompt"]),ee=As(t);useEffect(()=>{let{type:q,isNullable:he}=yn(t);w(q),E(he),M(e),$({title:t.title||"",description:t.description||"","X-ReasoningPrompt":t["X-ReasoningPrompt"]||"",maxLength:t.maxLength||void 0}),W(!!t["X-ReasoningPrompt"]);},[t,e]);let V=q=>{if(q==="enum")if(x!=="enum"){D(x),b(true);return}else return;w(q);let he=Yn(q,_,t);r(he);},Re=q=>{let se=Yn("enum",_,{enum:q,type:"string"});w("enum"),r(se);},Ee=()=>{},$e=q=>{E(q);let he=em(t,q);r(he);},Ln=()=>{let q=ww(bt);if(q){be(q);return}be(null),bt&&bt!==e&&c&&c(bt),gt(false);},an=()=>{if(!re.trim())return;let q=ee.enum||[],he={...ee,enum:[...q,re.trim()]};r(kt(t,he)),me("");let se=document.querySelector('input[placeholder="New enum value"]');se&&se.focus();},te=q=>{let he=(ee.enum||[]).filter((Qe,mt)=>mt!==q),se={...ee,enum:he};r(kt(t,se));},Be=(q,he)=>{let se=(ee.enum||[]).map((mt,Ir)=>Ir===q?he:mt),Qe={...ee,enum:se};r(kt(t,Qe));},wt=(q,he)=>{let se=ee.properties||{},Qe=Object.keys(se),mt=Qe.indexOf(q),Ir=Qe.indexOf(he);if(mt===-1||Ir===-1||mt===Ir){console.warn("[DRAG] Drag and drop reorder failed: Invalid keys or indices. sourceIndex:",mt,"targetIndex:",Ir);return}let rg=Qe;mt<Ir?rg=[...Qe.slice(0,mt),...Qe.slice(mt+1,Ir+1),q,...Qe.slice(Ir+1)]:rg=[...Qe.slice(0,Ir),q,...Qe.slice(Ir,mt),...Qe.slice(mt+1)];let _w={};rg.forEach(ng=>{if(Object.prototype.hasOwnProperty.call(se,ng)){let ag=se[ng];typeof ag=="object"&&ag!==null&&(_w[ng]=ag);}});let vD={...ee,properties:_w},bD=kt(t,vD);r(bD);},Lt=(q,he)=>{q.stopPropagation(),q.dataTransfer.setData("text/plain",he),q.dataTransfer.effectAllowed="move",d.current=p,g.current=he;let se=document.createElement("div"),Qe=q.currentTarget.getBoundingClientRect();se.style.width=`${Qe.width}px`,se.style.padding="8px",se.style.border="1px solid #90cdf4",se.style.borderRadius="4px",se.style.backgroundColor="rgba(255, 255, 255, 0.7)",se.style.boxShadow="0 2px 5px rgba(0,0,0,0.1)",se.style.opacity="0.8",se.style.position="fixed",se.style.zIndex="9999",se.style.pointerEvents="none",se.innerHTML=`<span style="font-weight: medium">${he}</span>`,document.body.appendChild(se),q.dataTransfer.setDragImage(se,10,10),setTimeout(()=>{document.body.removeChild(se);},0);},At=(q,he)=>{q.preventDefault();let se=ee.properties||{},Qe=Object.keys(se),mt=Qe.indexOf(g.current),Ir=Qe.indexOf(he);q.dataTransfer.dropEffect="move",d.current===p&&he!==g.current&&(q.currentTarget.classList.add(mt>Ir?"border-t-2":"border-b-2"),q.currentTarget.classList.add("border-grey-700"),q.currentTarget.classList.add("border-dashed"));},bu=q=>{q.stopPropagation(),q.currentTarget.classList.remove("border-t-2"),q.currentTarget.classList.remove("border-b-2"),q.currentTarget.classList.remove("border-grey-700"),q.currentTarget.classList.remove("border-dashed");},vl=(q,he)=>{q.stopPropagation(),q.preventDefault();let se=q.dataTransfer.getData("text/plain");q.currentTarget.classList.remove("border-t-2"),q.currentTarget.classList.remove("border-b-2"),q.currentTarget.classList.remove("border-grey-700"),q.currentTarget.classList.remove("border-dashed"),se&&se!==he&&d.current===p&&wt(se,he);},xu=q=>{},ww=q=>Ci(q,Object.keys(ee.properties||[]),e,"property"),yD=(q,he)=>{switch(q){case "string":return jsx(Type,{className:"w-4 h-4"});case "number":case "integer":return jsx(Hash,{className:"w-4 h-4"});case "boolean":return jsx(ToggleLeft,{className:"w-4 h-4"});case "enum":return jsx(List,{className:"w-4 h-4"});case "object":return jsx(Braces,{className:"w-4 h-4"});case "array":return jsx(Brackets,{className:"w-4 h-4"});case "date":return jsx(Calendar,{className:"w-4 h-4"});case "time":return jsx(Clock,{className:"w-4 h-4"});case "datetime":return jsx(CalendarClock,{className:"w-4 h-4"});case "$ref":return dv(he||"");default:return jsx(Shapes,{className:"w-4 h-4"})}};return jsxs("div",{children:[o!=="#"&&jsxs("div",{id:`schema-field-${o.replace(/^#\.?/,"").split(".").join("-")}`,className:"flex flex-col sm:flex-row items-start sm:items-center justify-between group pl-0 hover:bg-gray-100 py-0",children:[C?jsx(Me,{children:jsx(je,{asChild:true,children:jsx(GripVertical,{className:"w-6 h-12 py-4 px-1 group-hover:text-gray-500 text-white cursor-pointer"})})}):jsx("div",{className:"w-6 h-12 py-4 px-1"}),jsxs("div",{className:"flex items-center space-x-2 flex-1 min-w-0",children:[vt&&C?jsx(Ze,{className:`w-40 h-6 px-1 border-none p-0 m-0 shadow-none
58
59
  outline-none focus-visible:ring-0
59
- ${xe?"border-red-500":""}`,value:Et,onChange:B=>{let se=B.target.value;tt(se),me(se?qx(se):null);},onBlur:W,onKeyDown:B=>{B.key==="Enter"&&W();},autoFocus:true}):jsxs("div",{className:"flex items-center",children:[jsx("span",{className:"font-medium text-gray-800 mr-1 cursor-pointer whitespace-nowrap",onClick:()=>{c&&st(true);},children:e}),v==="$ref"&&U.$ref&&jsx(V,{type:"button",variant:"ghost",size:"icon",className:"p-0 h-4 w-4",onClick:()=>{let B=U.$ref?.replace("#/$defs/","");u&&u(true),setTimeout(()=>{let se=document.getElementById(`def-${B}`);se&&(se.scrollIntoView({behavior:"smooth"}),se.classList.add("bg-blue-100"),setTimeout(()=>se.classList.remove("bg-blue-100"),2500));},600);},children:jsx(EyeIcon,{className:"w-4 h-4 text-gray-400"})})]}),zt&&xe&&jsxs("p",{className:"text-xs text-red-500 flex items-center gap-1 mt-1 ml-1",children:[jsx(AlertCircle,{className:"w-3 h-3"})," ",xe]}),k["X-ReasoningPrompt"]&&jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(Atom,{className:"w-4 h-4 text-purple-300"})}),jsxs(et,{className:"max-w-xs",children:[jsx("div",{className:"text-xs text-purple-300 mb-1",children:"Reasoning Prompt:"}),jsx("div",{className:"",children:k["X-ReasoningPrompt"]})]})]}),k.description&&jsx("div",{className:"flex items-center gap-1 flex-1 min-w-0",children:jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx("div",{className:"truncate text-xs text-muted-foreground cursor-pointer hover:text-gray-600",onClick:()=>{ie(e),ue(null),E(true);},children:k.description})}),jsxs(et,{className:"max-w-xs",children:[jsx("div",{className:"text-xs text-blue-300 mb-1",children:"Description:"}),jsx("div",{className:"text-xs",children:k.description})]})]})})]}),jsxs("div",{className:"flex items-center gap-2",children:[_&&s&&jsx(V,{type:"button",variant:"ghost",size:"sm",className:"p-0 m-0 w-3 h-3",onClick:l,children:jsx(Trash2,{className:"w-1 h-1 text-white group-hover:text-muted-foreground"})}),!p&&jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(V,{type:"button",variant:"ghost",size:"icon",className:"p-0 m-0",onClick:()=>{ie(e),ue(null),E(true);},children:jsx(Pencil,{className:"w-1 h-1 group-hover:opacity-100 opacity-0 text-gray-500"})})}),jsx(et,{className:"max-w-xs",children:jsx("p",{children:"Edit field properties"})})]}),_&&jsx("div",{className:"flex items-center mt-2 sm:mt-0 opacity-0 group-hover:opacity-100",children:jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(bl,{id:`${a}-nullable`,checked:!N,onCheckedChange:B=>Le(!B)})}),jsx(et,{children:jsx("p",{children:"Required"})})]})}),_?jsxs(dr,{children:[jsx(fr,{asChild:true,children:jsxs(V,{variant:"ghost",className:"w-40 text-xs justify-between font-normal text-gray-500 pr-0",children:[jsxs("div",{className:"flex items-center gap-1",children:[SO(v,v==="$ref"&&U.$ref?U.$ref.replace("#/$defs/",""):void 0),jsx("span",{className:"",children:v==="$ref"&&U.$ref?U.$ref.replace("#/$defs/",""):v==="date"?"date":v==="time"?"time":v==="datetime"?"datetime":v==="boolean"?"true/false":v==="enum"?"multiple choice":v==="array"?"list":v||"Select type"})]}),jsx(ChevronDown,{className:"w-4 h-4 mx-2 group-hover:opacity-100 opacity-0 text-gray-500"})]})}),jsxs(pr,{children:[jsxs(ge,{onSelect:()=>H("string"),children:[jsx(Type,{className:"w-4 h-4 mr-2"}),"string"]}),jsxs(ge,{onSelect:()=>H("number"),children:[jsx(Hash,{className:"w-4 h-4 mr-2"}),"number"]}),jsxs(ge,{onSelect:()=>H("integer"),children:[jsx(Hash,{className:"w-4 h-4 mr-2"}),"integer"]}),jsxs(ge,{onSelect:()=>H("boolean"),children:[jsx(ToggleLeft,{className:"w-4 h-4 mr-2"}),"true/false"]}),jsxs(ge,{onSelect:()=>H("enum"),children:[jsx(List,{className:"w-4 h-4 mr-2"}),"multiple choice"]}),jsxs(ge,{onSelect:()=>H("object"),children:[jsx(Braces,{className:"w-4 h-4 mr-2"}),"object"]}),jsxs(ge,{onSelect:()=>H("array"),children:[jsx(Brackets,{className:"w-4 h-4 mr-2"}),"list"]}),jsxs(ge,{onSelect:()=>H("date"),children:[jsx(Calendar,{className:"w-4 h-4 mr-2"}),"date"]}),jsxs(ge,{onSelect:()=>H("time"),children:[jsx(Clock,{className:"w-4 h-4 mr-2"}),"time"]}),jsxs(ge,{onSelect:()=>H("datetime"),children:[jsx(CalendarClock,{className:"w-4 h-4 mr-2"}),"datetime"]}),jsxs(Vr,{children:[jsxs(Hr,{children:[jsx(Link,{className:"w-4 h-4 mr-4"}),"definition"]}),jsx(uo,{children:jsx(Jr,{children:!i||Object.keys(i).length===0?jsxs(ge,{onSelect:()=>{u&&(u(true),setTimeout(()=>{let B=document.getElementById("definitions-section");B&&(B.scrollIntoView({behavior:"smooth"}),B.style.backgroundColor="#dbeafe",setTimeout(()=>{B.style.backgroundColor="";},2500));},600));},children:[jsx(PlusIcon,{className:"w-4 h-4 mr-2"}),"Create a new definition to get started"]}):Object.keys(i).map(B=>jsxs(ge,{onSelect:()=>{r(Ct(t,{$ref:`#/$defs/${B}`}));},children:[U0(B),B]},B))})})]}),jsxs(Vr,{children:[jsxs(Hr,{children:[jsx(Shapes,{className:"w-4 h-4 mr-4"}),"object template"]}),jsx(uo,{children:jsx(Jr,{children:Object.entries(Ol).map(([B,se])=>jsxs(ge,{className:"flex items-center gap-2",onSelect:()=>{let Q=[B];se.deps&&Q.push(...se.deps);let qe={...n.$defs||{}};for(let mt of Q)qe[mt]||(qe[mt]=Ol[mt]);o({...n,$defs:qe}),Z(B);},children:[U0(B),B]},B))})})]})]})]}):jsx("div",{className:"w-40 text-xs ml-4",children:v==="$ref"&&U.$ref?U.$ref.replace("#/$defs/",""):v==="date"?"date":v==="time"?"time":v==="datetime"?"datetime":v==="boolean"?"true/false":v==="enum"?"multiple choice":v==="array"?"list":v||"string"})]})]}),v==="object"&&jsx("div",{className:a==="#"?"px-0":"pl-2",children:a==="#"?jsx(Cu,{defaultValue:"properties",type:"single",collapsible:true,className:"w-full rounded-lg border border-gray-200 shadow-sm px-4 pb-0",children:jsxs(Eu,{value:"properties",className:"border-none",children:[jsxs(Pu,{className:"font-medium text-gray-400 text-sm",children:["Properties (",Object.keys(U.properties||{}).length,")"]}),jsx(Tu,{className:"",children:jsxs("div",{className:"",children:[U.properties&&Object.keys(U.properties||{}).length>0&&Object.keys(U.properties||{}).map(B=>{let se=(U.properties||{})[B];return jsx("div",{className:"",draggable:_,onDragStart:Q=>Ot(Q,B),onDragOver:Q=>Rr(Q,B),onDragLeave:Kd,onDrop:Q=>Gd(Q,B),onDragEnd:Vc,"data-prop-key":B,children:kp(se)&&jsx(ga,{draggedParentRef:d,draggedPropertyRef:m,editMode:h,name:B,node:se,jsonSchema:n,setJsonSchema:o,onChange:Q=>{let qe={...U.properties||{},[B]:Q},mt={...U,properties:qe};r(Ct(t,mt));},onNameChange:Q=>{if(Q!==B){let qe=q0(t,B,Q,U.properties?.[B]);r(Ct(t,qe));}},path:`${a}.${B}`,defs:i,canDelete:true,onDelete:()=>{let Q={...U.properties};delete Q[B];let qe=Array.isArray(U.required)?U.required.filter(Or=>Or!==B):[],mt={...U,properties:Q,required:qe};r(Ct(t,mt));},setDefsAccordionOpen:u})},B)}),_&&jsxs("div",{className:"flex flex-col gap-1 mt-3 ml-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx(nt,{placeholder:"New property name",className:`w-40 ${ae?"border-red-500":""}`,value:L,onChange:B=>{let se=B.target.value;le(se),Oe(se?ui(se,Object.keys(U.properties||[]),void 0,"property"):null);},onKeyDown:B=>{if(B.key==="Enter"&&L.trim()){let se=Al("string");se.title=qo(L);let Q={...U.properties||{},[L]:se},qe=Array.isArray(U.required)?[...U.required,L]:[L],mt={...U,properties:Q,required:qe};r(Ct(t,mt)),le("");}}}),jsxs(V,{type:"button",variant:"outline",size:"sm",disabled:!!ae||!L.trim(),className:ae||!L.trim()?"cursor-not-allowed":"",onClick:()=>{let B=ui(L,Object.keys(U.properties||[]),void 0,"property");if(B){Oe(B);return}let se=Al("string");se.title=qo(L);let Q={...U.properties||{},[L]:se},qe=Array.isArray(U.required)?[...U.required,L]:[L],mt={...U,properties:Q,required:qe};r(Ct(t,mt)),le("");},children:[jsx(PlusIcon,{className:"w-4 h-4"}),jsx("span",{children:"Add"})]})]}),ae&&jsxs("p",{className:"text-xs text-red-500 flex items-center gap-1",children:[jsx(AlertCircle,{className:"w-3 h-3"})," ",ae]})]})]})})]})}):jsxs("div",{className:"",children:[U.properties&&Object.keys(U.properties||{}).length>0&&Object.keys(U.properties||{}).map(B=>{let se=(U.properties||{})[B];return jsx("div",{className:"ml-4 border-l border-gray-200",draggable:_,onDragStart:Q=>Ot(Q,B),onDragOver:Q=>Rr(Q,B),onDragLeave:Kd,onDrop:Q=>Gd(Q,B),onDragEnd:Vc,"data-prop-key":B,children:kp(se)&&jsx(ga,{draggedParentRef:d,name:B,draggedPropertyRef:m,editMode:h,node:se,onChange:Q=>{let qe={...U.properties||{},[B]:Q},mt={...U,properties:qe};r(Ct(t,mt));},jsonSchema:n,setJsonSchema:o,onNameChange:Q=>{if(Q!==B){let qe=q0(t,B,Q,U.properties?.[B]);r(Ct(t,qe));}},path:`${a}.${B}`,defs:i,canDelete:true,onDelete:()=>{let Q={...U.properties};delete Q[B];let qe=Array.isArray(U.required)?U.required.filter(Or=>Or!==B):[],mt={...U,properties:Q,required:qe};r(Ct(t,mt));},setDefsAccordionOpen:u})},B)}),_&&jsxs("div",{className:"flex items-center gap-3 mt-2 ml-4 pl-4 border-l border-gray-200",children:[jsx(nt,{placeholder:"New property name",className:"w-40",value:L,onChange:B=>le(B.target.value),onKeyDown:B=>{if(B.key==="Enter"&&L.trim()){let se=Al("string");se.title=qo(L);let Q={...U.properties||{},[L]:se},qe=Array.isArray(U.required)?[...U.required,L]:[L],mt={...U,properties:Q,required:qe};r(Ct(t,mt)),le("");}}}),jsxs(V,{type:"button",variant:"outline",size:"sm",onClick:()=>{if(!L.trim())return;let B=Al("string");B.title=qo(L);let se={...U.properties||{},[L]:B},Q=Array.isArray(U.required)?[...U.required,L]:[L],qe={...U,properties:se,required:Q};r(Ct(t,qe)),le("");},children:[jsx(PlusIcon,{className:"w-4 h-4"}),jsx("span",{children:"Add"})]})]})]})}),v==="array"&&jsx("div",{className:"ml-4",children:jsx("div",{className:"ml-4 border-l border-gray-200",children:(()=>{let B=ls(t).items;return B!==void 0&&!Array.isArray(B)&&kp(B)&&jsx(ga,{draggedParentRef:d,draggedPropertyRef:m,editMode:h,name:"items",node:B,onChange:Q=>r(Ct(t,{...U,items:Q})),jsonSchema:n,setJsonSchema:o,path:`${a}.items`,defs:i,canDelete:false,hidePencilButton:true,setDefsAccordionOpen:u})})()})}),v==="enum"&&jsxs("div",{className:"ml-6",children:[jsx(Yt,{className:"text-gray-400 font-normal",children:"Possible values"}),U.enum&&U.enum.length>0?jsx("ul",{className:"mb-2 flex flex-wrap gap-2 mt-1",children:U.enum.map((B,se)=>jsxs("li",{className:"flex items-center space-x-2 border-gray-200 border rounded-md px-2 py-1 bg-slate-50",children:[jsx(nt,{value:B,ref:se===0?Fe:void 0,onChange:Q=>{Hs(se,Q.target.value);},className:"h-6 w-24 px-1 shadow-none bg-transparent border-0 focus-visible:ring-0 focus-visible:ring-offset-0"}),jsx(V,{type:"button",variant:"ghost",className:"p-1 m-0 w-3 h-3",size:"icon",onClick:()=>Pt(se),children:jsx(X,{className:"w-2 h-2"})})]},se))}):jsx("div",{className:"mb-2 text-sm text-gray-500",children:"No enum values defined."}),jsxs("div",{className:"flex items-center gap-3",children:[jsx(nt,{ref:Me,placeholder:"New enum value",className:"w-40",value:_e,onChange:B=>pt(B.target.value),onKeyDown:B=>{B.key==="Enter"&&_e.trim()&&Pe();}}),jsxs(V,{type:"button",variant:"outline",size:"sm",onClick:Pe,children:[jsx(PlusIcon,{className:"w-4 h-4"}),jsx("span",{children:"Add"})]})]})]}),a!=="#"&&jsx(XN,{isOpen:R,onClose:()=>E(false),path:a,propertyName:pe,setPropertyName:ie,metadataValues:k,setMetadataValues:I,nameError:J,setNameError:ue,showReasoningPromptField:ce,setShowReasoningPromptField:G,validateName:re,onChange:r,onNameChange:c||(()=>{}),onDelete:_&&s?()=>{l&&(l(),E(false));}:void 0,node:t,name:e,localType:v,editMode:h}),jsx(eC,{isOpen:C,onClose:()=>b(false),onConfirm:je,onCancel:Ue})]})}function Pj({schema:e,onChange:t,accordionOpen:r,setAccordionOpen:n,draggedParentRef:o,draggedPropertyRef:a,editMode:i="editable"}){let s=e.$defs||{},[l,c]=useState(""),[u,d]=useState(false),m=i==="editable",h=()=>{if(!l.trim())return;let f={...s,[l]:{type:"object",properties:{},required:[]}};t({...e,$defs:f}),c("");},y=f=>{let x=`#/$defs/${f}`,g=v=>{if(v===null||typeof v!="object")return false;if(Array.isArray(v)){for(let w of v)if(g(w))return true;return false}if(v.$ref===x)return true;if(v===e&&e.$defs&&typeof e.$defs=="object"){for(let[S,_]of Object.entries(e.$defs))if(S!==f&&g(_))return true;let{$defs:w,...N}=e;return g(N)}for(let w of Object.keys(v))if(w!=="$defs"&&g(v[w]))return true;return false};return g(e)},p=f=>{if(y(f)){toast.error(`Cannot delete "${f}" because it is referenced by one or more $ref properties. Remove or update those references first.`);return}let x={...s};delete x[f],t({...e,$defs:x}),Object.keys(x).length===0&&d(false);};return Object.keys(s).length===0&&!u?i==="promptOnly"?null:jsx("div",{className:"mt-6 flex pb-4",children:jsx("div",{className:"rounded-md",id:"definitions-section",children:jsxs(V,{type:"button",variant:"outline",onClick:()=>{d(true),n(true);},className:"bg-transparent rounded-md transition-colors duration-300",children:[jsx(PlusIcon,{className:"w-4 h-4 mr-2"}),"Add definition"]})})}):jsx(Cu,{className:"w-full mt-6 rounded-lg border border-gray-200 shadow-sm px-4 pb-0",type:"single",collapsible:false,value:"defs",children:jsxs(Eu,{value:"defs",className:"bg-transparent border-none",children:[jsx(Pu,{className:"text-gray-400 font-medium bg-transparent",children:jsxs("div",{className:"flex items-center",children:["Definitions (",Object.keys(s).length,")"]})}),jsx(Tu,{className:"pt-2 bg-transparent",children:jsxs("div",{className:"space-y-4",children:[Object.keys(s).length===0&&jsx("p",{className:"text-sm text-muted-foreground",children:"Create reusable schema components to avoid duplication with a new definition."}),Object.entries(s).map(([f,x])=>jsx("div",{className:" py-2",id:`def-${f}`,children:jsx(ga,{draggedParentRef:o,draggedPropertyRef:a,editMode:i,name:f,node:x,onChange:g=>{let v={...s,[f]:g};t({...e,$defs:v});},onNameChange:g=>{if(g!==f){let v={...s};v[g]=x,delete v[f];let w=S=>{if(typeof S!="object"||S===null)return S;if(Array.isArray(S))return S.map(w);let _={...S};return _.$ref===`#/$defs/${f}`&&(_.$ref=`#/$defs/${g}`),Object.keys(_).forEach(P=>{P!=="$ref"&&(_[P]=w(_[P]));}),_},N=w({...e,$defs:v});t(N);}},jsonSchema:e,setJsonSchema:t,path:`#/$defs/${f}`,defs:s,canDelete:!y(f),onDelete:()=>p(f),setDefsAccordionOpen:n})},f)),m&&jsxs("div",{className:"flex items-center gap-3",children:[jsx(nt,{placeholder:"New definition name",className:"w-40",value:l,onChange:f=>c(f.target.value)}),jsxs(V,{type:"button",variant:"outline",size:"sm",onClick:h,className:"p-1!",children:[jsx(PlusIcon,{className:"w-4 h-4"}),jsx("span",{className:"ml-1",children:"Add Definition"})]})]})]})})]})})}function Tj({fullCodeModeState:e,editMode:t="editable",setDisplayEvanescentButtons:r,onSchemaFixWithAI:n}){let[o,a]=useState(false),[i,s]=e||[o,a],{jsonSchema:l,setJsonSchema:c,validationErrors:u}=jo(),[d,m]=useState(false),[h,y]=kt.useState(false),p=kt.useRef(null),f=kt.useRef(null),{selectedFieldPath:x}=Lu();kt.useEffect(()=>{if(x)try{let v=E=>{if(E&&Array.isArray(E.anyOf)){let C=E.anyOf.find(b=>typeof b=="object"&&(b.type!=="null"||b.$ref||b.enum));return C&&typeof C=="object"?C:E}return E},N=x.split(".")[0],_=v(l)?.properties?.[N],P=v(_),R=!1;if(P&&typeof P=="object"){if(P.$ref)R=!0;else if(P.type==="array"){let E=Array.isArray(P.items)?P.items[0]:P.items,C=v(E||{});C&&C.$ref&&(R=!0);}}R&&!d&&m(!0);}catch{}},[x,l,d]);let g=v=>{m(v);};return jsxs("div",{className:"flex-1 min-h-0 flex flex-col w-full overflow-y-auto",children:[jsxs("div",{className:`group flex flex-col w-full ${i?"h-full":""}`,children:[jsx(sC,{validationErrors:u,variant:"full",showFixButton:!!n,onSchemaFixWithAI:n}),i?jsx(Editor,{language:"json",theme:"vs-dark",className:"flex-1 min-h-0 h-full rounded-lg overflow-hidden",value:JSON.stringify(l,null,2),options:{automaticLayout:true},onChange:async v=>{try{let w=JSON.parse(v||"");await c(w);}catch{}}}):jsx(Ej,{onChange:c,setDisplayEvanescentButtons:r,node:l,editMode:t,setOpenLayoutDialog:y})]}),!i&&jsxs("div",{className:"pb-20 flex-1 min-h-0 flex flex-col",children:[jsx(ga,{name:"root",node:l,onChange:c,jsonSchema:l,setJsonSchema:c,path:"#",defs:l.$defs||{},editMode:t,canDelete:false,setDefsAccordionOpen:g,draggedParentRef:p,draggedPropertyRef:f,setDisplayEvanescentButtons:r}),jsx(Pj,{editMode:t,schema:l,onChange:c,accordionOpen:d,setAccordionOpen:g,draggedParentRef:p,draggedPropertyRef:f})]})]})}kt.memo(Tj);var ql={};OO(ql,{BRAND:()=>eL,DIRTY:()=>us,EMPTY_PATH:()=>Dj,INVALID:()=>Se,NEVER:()=>ML,OK:()=>jr,ParseStatus:()=>Nr,Schema:()=>Je,ZodAny:()=>pi,ZodArray:()=>xa,ZodBigInt:()=>fs,ZodBoolean:()=>ps,ZodBranded:()=>zu,ZodCatch:()=>Ns,ZodDate:()=>ms,ZodDefault:()=>Ss,ZodDiscriminatedUnion:()=>$p,ZodEffects:()=>Bn,ZodEnum:()=>ws,ZodError:()=>cn,ZodFirstPartyTypeKind:()=>Ce,ZodFunction:()=>Fp,ZodIntersection:()=>vs,ZodIssueCode:()=>K,ZodLazy:()=>bs,ZodLiteral:()=>xs,ZodMap:()=>Ll,ZodNaN:()=>zl,ZodNativeEnum:()=>_s,ZodNever:()=>ho,ZodNull:()=>gs,ZodNullable:()=>Wo,ZodNumber:()=>ds,ZodObject:()=>un,ZodOptional:()=>jn,ZodParsedType:()=>oe,ZodPipeline:()=>Uu,ZodPromise:()=>mi,ZodReadonly:()=>Cs,ZodRecord:()=>Ip,ZodSchema:()=>Je,ZodSet:()=>Bl,ZodString:()=>fi,ZodSymbol:()=>Ml,ZodTransformer:()=>Bn,ZodTuple:()=>Jo,ZodType:()=>Je,ZodUndefined:()=>hs,ZodUnion:()=>ys,ZodUnknown:()=>ba,ZodVoid:()=>jl,addIssueToContext:()=>Y,any:()=>cL,array:()=>pL,bigint:()=>oL,boolean:()=>Mp,coerce:()=>FL,custom:()=>AC,date:()=>aL,datetimeRegex:()=>OC,defaultErrorMap:()=>ya,discriminatedUnion:()=>gL,effect:()=>TL,enum:()=>CL,function:()=>_L,getErrorMap:()=>$l,getParsedType:()=>Ho,instanceof:()=>rL,intersection:()=>yL,isAborted:()=>Dp,isAsync:()=>Il,isDirty:()=>Ap,isValid:()=>di,late:()=>tL,lazy:()=>SL,literal:()=>NL,makeIssue:()=>Bu,map:()=>xL,nan:()=>nL,nativeEnum:()=>EL,never:()=>dL,null:()=>lL,nullable:()=>RL,number:()=>$C,object:()=>W0,objectUtil:()=>V0,oboolean:()=>IL,onumber:()=>$L,optional:()=>kL,ostring:()=>AL,pipeline:()=>DL,preprocess:()=>OL,promise:()=>PL,quotelessJson:()=>kj,record:()=>bL,set:()=>wL,setErrorMap:()=>Oj,strictObject:()=>mL,string:()=>Ul,symbol:()=>iL,transformer:()=>TL,tuple:()=>vL,undefined:()=>sL,union:()=>hL,unknown:()=>uL,util:()=>Ye,void:()=>fL});var Ye;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,e.arrayToEnum=o=>{let a={};for(let i of o)a[i]=i;return a},e.getValidEnumValues=o=>{let a=e.objectKeys(o).filter(s=>typeof o[o[s]]!="number"),i={};for(let s of a)i[s]=o[s];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(a){return o[a]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let a=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&a.push(i);return a},e.find=(o,a)=>{for(let i of o)if(a(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,a=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}e.joinValues=n,e.jsonStringifyReplacer=(o,a)=>typeof a=="bigint"?a.toString():a;})(Ye||(Ye={}));var V0;(function(e){e.mergeShapes=(t,r)=>({...t,...r});})(V0||(V0={}));var oe=Ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ho=e=>{switch(typeof e){case "undefined":return oe.undefined;case "string":return oe.string;case "number":return Number.isNaN(e)?oe.nan:oe.number;case "boolean":return oe.boolean;case "function":return oe.function;case "bigint":return oe.bigint;case "symbol":return oe.symbol;case "object":return Array.isArray(e)?oe.array:e===null?oe.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?oe.promise:typeof Map<"u"&&e instanceof Map?oe.map:typeof Set<"u"&&e instanceof Set?oe.set:typeof Date<"u"&&e instanceof Date?oe.date:oe.object;default:return oe.unknown}};var K=Ye.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),kj=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),cn=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n];},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n];};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t;}format(t){let r=t||function(a){return a.message},n={_errors:[]},o=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else {let s=n,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(r(i))):s[c]=s[c]||{_errors:[]},s=s[c],l++;}}};return o(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Ye.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let a=o.path[0];r[a]=r[a]||[],r[a].push(t(o));}else n.push(t(o));return {formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};cn.create=e=>new cn(e);var Rj=(e,t)=>{let r;switch(e.code){case K.invalid_type:e.received===oe.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case K.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Ye.jsonStringifyReplacer)}`;break;case K.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ye.joinValues(e.keys,", ")}`;break;case K.invalid_union:r="Invalid input";break;case K.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ye.joinValues(e.options)}`;break;case K.invalid_enum_value:r=`Invalid enum value. Expected ${Ye.joinValues(e.options)}, received '${e.received}'`;break;case K.invalid_arguments:r="Invalid function arguments";break;case K.invalid_return_type:r="Invalid function return type";break;case K.invalid_date:r="Invalid date";break;case K.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Ye.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case K.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case K.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case K.custom:r="Invalid input";break;case K.invalid_intersection_types:r="Intersection results could not be merged";break;case K.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case K.not_finite:r="Number must be finite";break;default:r=t.defaultError,Ye.assertNever(e);}return {message:r}},ya=Rj;var EC=ya;function Oj(e){EC=e;}function $l(){return EC}var Bu=e=>{let{data:t,path:r,errorMaps:n,issueData:o}=e,a=[...r,...o.path||[]],i={...o,path:a};if(o.message!==void 0)return {...o,path:a,message:o.message};let s="",l=n.filter(c=>!!c).slice().reverse();for(let c of l)s=c(i,{data:t,defaultError:s}).message;return {...o,path:a,message:s}},Dj=[];function Y(e,t){let r=$l(),n=Bu({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===ya?void 0:ya].filter(o=>!!o)});e.common.issues.push(n);}var Nr=class e{constructor(){this.value="valid";}dirty(){this.value==="valid"&&(this.value="dirty");}abort(){this.value!=="aborted"&&(this.value="aborted");}static mergeArray(t,r){let n=[];for(let o of r){if(o.status==="aborted")return Se;o.status==="dirty"&&t.dirty(),n.push(o.value);}return {status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let o of r){let a=await o.key,i=await o.value;n.push({key:a,value:i});}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let o of r){let{key:a,value:i}=o;if(a.status==="aborted"||i.status==="aborted")return Se;a.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[a.value]=i.value);}return {status:t.value,value:n}}},Se=Object.freeze({status:"aborted"}),us=e=>({status:"dirty",value:e}),jr=e=>({status:"valid",value:e}),Dp=e=>e.status==="aborted",Ap=e=>e.status==="dirty",di=e=>e.status==="valid",Il=e=>typeof Promise<"u"&&e instanceof Promise;var fe;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message;})(fe||(fe={}));var Ln=class{constructor(t,r,n,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=o;}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},PC=(e,t)=>{if(di(t))return {success:true,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return {success:false,get error(){if(this._error)return this._error;let r=new cn(e.common.issues);return this._error=r,this._error}}};function ze(e){if(!e)return {};let{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,s)=>{let{message:l}=e;return i.code==="invalid_enum_value"?{message:l??s.defaultError}:typeof s.data>"u"?{message:l??n??s.defaultError}:i.code!=="invalid_type"?{message:s.defaultError}:{message:l??r??s.defaultError}},description:o}}var Je=class{get description(){return this._def.description}_getType(t){return Ho(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Ho(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return {status:new Nr,ctx:{common:t.parent.common,data:t.data,parsedType:Ho(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(Il(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??false,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ho(t)},o=this._parseSync({data:t,path:n.path,parent:n});return PC(n,o)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ho(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return di(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=true),r.common={issues:[],async:true};}return this._parseAsync({data:t,path:[],parent:r}).then(n=>di(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:true},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Ho(t)},o=this._parse({data:t,path:n.path,parent:n}),a=await(Il(o)?o:Promise.resolve(o));return PC(n,a)}refine(t,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,a)=>{let i=t(o),s=()=>a.addIssue({code:K.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?true:(s(),false)):i?true:(s(),false)})}refinement(t,r){return this._refinement((n,o)=>t(n)?true:(o.addIssue(typeof r=="function"?r(n,o):r),false))}_refinement(t){return new Bn({schema:this,typeName:Ce.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)};}optional(){return jn.create(this,this._def)}nullable(){return Wo.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return xa.create(this)}promise(){return mi.create(this,this._def)}or(t){return ys.create([this,t],this._def)}and(t){return vs.create(this,t,this._def)}transform(t){return new Bn({...ze(this._def),schema:this,typeName:Ce.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new Ss({...ze(this._def),innerType:this,defaultValue:r,typeName:Ce.ZodDefault})}brand(){return new zu({typeName:Ce.ZodBranded,type:this,...ze(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new Ns({...ze(this._def),innerType:this,catchValue:r,typeName:Ce.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return Uu.create(this,t)}readonly(){return Cs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Aj=/^c[^\s-]{8,}$/i,$j=/^[0-9a-z]+$/,Ij=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Fj=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Mj=/^[a-z0-9_-]{21}$/i,jj=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Lj=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Bj=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,zj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",H0,Uj=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,qj=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Vj=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Hj=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Jj=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Wj=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,kC="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Kj=new RegExp(`^${kC}$`);function RC(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return `([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function Gj(e){return new RegExp(`^${RC(e)}$`)}function OC(e){let t=`${kC}T${RC(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Zj(e,t){return !!((t==="v4"||!t)&&Uj.test(e)||(t==="v6"||!t)&&Vj.test(e))}function Xj(e,t){if(!jj.test(e))return false;try{let[r]=e.split(".");if(!r)return !1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return !(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return false}}function Qj(e,t){return !!((t==="v4"||!t)&&qj.test(e)||(t==="v6"||!t)&&Hj.test(e))}var fi=class e extends Je{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==oe.string){let a=this._getOrReturnCtx(t);return Y(a,{code:K.invalid_type,expected:oe.string,received:a.parsedType}),Se}let n=new Nr,o;for(let a of this._def.checks)if(a.kind==="min")t.data.length<a.value&&(o=this._getOrReturnCtx(t,o),Y(o,{code:K.too_small,minimum:a.value,type:"string",inclusive:true,exact:false,message:a.message}),n.dirty());else if(a.kind==="max")t.data.length>a.value&&(o=this._getOrReturnCtx(t,o),Y(o,{code:K.too_big,maximum:a.value,type:"string",inclusive:true,exact:false,message:a.message}),n.dirty());else if(a.kind==="length"){let i=t.data.length>a.value,s=t.data.length<a.value;(i||s)&&(o=this._getOrReturnCtx(t,o),i?Y(o,{code:K.too_big,maximum:a.value,type:"string",inclusive:true,exact:true,message:a.message}):s&&Y(o,{code:K.too_small,minimum:a.value,type:"string",inclusive:true,exact:true,message:a.message}),n.dirty());}else if(a.kind==="email")Bj.test(t.data)||(o=this._getOrReturnCtx(t,o),Y(o,{validation:"email",code:K.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")H0||(H0=new RegExp(zj,"u")),H0.test(t.data)||(o=this._getOrReturnCtx(t,o),Y(o,{validation:"emoji",code:K.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")Fj.test(t.data)||(o=this._getOrReturnCtx(t,o),Y(o,{validation:"uuid",code:K.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")Mj.test(t.data)||(o=this._getOrReturnCtx(t,o),Y(o,{validation:"nanoid",code:K.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")Aj.test(t.data)||(o=this._getOrReturnCtx(t,o),Y(o,{validation:"cuid",code:K.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")$j.test(t.data)||(o=this._getOrReturnCtx(t,o),Y(o,{validation:"cuid2",code:K.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")Ij.test(t.data)||(o=this._getOrReturnCtx(t,o),Y(o,{validation:"ulid",code:K.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(t.data);}catch{o=this._getOrReturnCtx(t,o),Y(o,{validation:"url",code:K.invalid_string,message:a.message}),n.dirty();}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),Y(o,{validation:"regex",code:K.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?t.data=t.data.trim():a.kind==="includes"?t.data.includes(a.value,a.position)||(o=this._getOrReturnCtx(t,o),Y(o,{code:K.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?t.data=t.data.toLowerCase():a.kind==="toUpperCase"?t.data=t.data.toUpperCase():a.kind==="startsWith"?t.data.startsWith(a.value)||(o=this._getOrReturnCtx(t,o),Y(o,{code:K.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?t.data.endsWith(a.value)||(o=this._getOrReturnCtx(t,o),Y(o,{code:K.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?OC(a).test(t.data)||(o=this._getOrReturnCtx(t,o),Y(o,{code:K.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?Kj.test(t.data)||(o=this._getOrReturnCtx(t,o),Y(o,{code:K.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?Gj(a).test(t.data)||(o=this._getOrReturnCtx(t,o),Y(o,{code:K.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?Lj.test(t.data)||(o=this._getOrReturnCtx(t,o),Y(o,{validation:"duration",code:K.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?Zj(t.data,a.version)||(o=this._getOrReturnCtx(t,o),Y(o,{validation:"ip",code:K.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?Xj(t.data,a.alg)||(o=this._getOrReturnCtx(t,o),Y(o,{validation:"jwt",code:K.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?Qj(t.data,a.version)||(o=this._getOrReturnCtx(t,o),Y(o,{validation:"cidr",code:K.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?Jj.test(t.data)||(o=this._getOrReturnCtx(t,o),Y(o,{validation:"base64",code:K.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?Wj.test(t.data)||(o=this._getOrReturnCtx(t,o),Y(o,{validation:"base64url",code:K.invalid_string,message:a.message}),n.dirty()):Ye.assertNever(a);return {status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:K.invalid_string,...fe.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...fe.errToObj(t)})}url(t){return this._addCheck({kind:"url",...fe.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...fe.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...fe.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...fe.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...fe.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...fe.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...fe.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...fe.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...fe.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...fe.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...fe.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...fe.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:false,local:false,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??false,local:t?.local??false,...fe.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...fe.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...fe.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...fe.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...fe.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...fe.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...fe.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...fe.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...fe.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...fe.errToObj(r)})}nonempty(t){return this.min(1,fe.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return !!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return !!this._def.checks.find(t=>t.kind==="date")}get isTime(){return !!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return !!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return !!this._def.checks.find(t=>t.kind==="email")}get isURL(){return !!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return !!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return !!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return !!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return !!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return !!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return !!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return !!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return !!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return !!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return !!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};fi.create=e=>new fi({checks:[],typeName:Ce.ZodString,coerce:e?.coerce??false,...ze(e)});function Yj(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,a=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return a%i/10**o}var ds=class e extends Je{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf;}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==oe.number){let a=this._getOrReturnCtx(t);return Y(a,{code:K.invalid_type,expected:oe.number,received:a.parsedType}),Se}let n,o=new Nr;for(let a of this._def.checks)a.kind==="int"?Ye.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Y(n,{code:K.invalid_type,expected:"integer",received:"float",message:a.message}),o.dirty()):a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(n=this._getOrReturnCtx(t,n),Y(n,{code:K.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:false,message:a.message}),o.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(n=this._getOrReturnCtx(t,n),Y(n,{code:K.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:false,message:a.message}),o.dirty()):a.kind==="multipleOf"?Yj(t.data,a.value)!==0&&(n=this._getOrReturnCtx(t,n),Y(n,{code:K.not_multiple_of,multipleOf:a.value,message:a.message}),o.dirty()):a.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),Y(n,{code:K.not_finite,message:a.message}),o.dirty()):Ye.assertNever(a);return {status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,true,fe.toString(r))}gt(t,r){return this.setLimit("min",t,false,fe.toString(r))}lte(t,r){return this.setLimit("max",t,true,fe.toString(r))}lt(t,r){return this.setLimit("max",t,false,fe.toString(r))}setLimit(t,r,n,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:fe.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:fe.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:false,message:fe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:false,message:fe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:true,message:fe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:true,message:fe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:fe.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:fe.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:true,value:Number.MIN_SAFE_INTEGER,message:fe.toString(t)})._addCheck({kind:"max",inclusive:true,value:Number.MAX_SAFE_INTEGER,message:fe.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return !!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Ye.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return true;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);}return Number.isFinite(r)&&Number.isFinite(t)}};ds.create=e=>new ds({checks:[],typeName:Ce.ZodNumber,coerce:e?.coerce||false,...ze(e)});var fs=class e extends Je{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte;}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data);}catch{return this._getInvalidInput(t)}if(this._getType(t)!==oe.bigint)return this._getInvalidInput(t);let n,o=new Nr;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(n=this._getOrReturnCtx(t,n),Y(n,{code:K.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),o.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(n=this._getOrReturnCtx(t,n),Y(n,{code:K.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),o.dirty()):a.kind==="multipleOf"?t.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),Y(n,{code:K.not_multiple_of,multipleOf:a.value,message:a.message}),o.dirty()):Ye.assertNever(a);return {status:o.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Y(r,{code:K.invalid_type,expected:oe.bigint,received:r.parsedType}),Se}gte(t,r){return this.setLimit("min",t,true,fe.toString(r))}gt(t,r){return this.setLimit("min",t,false,fe.toString(r))}lte(t,r){return this.setLimit("max",t,true,fe.toString(r))}lt(t,r){return this.setLimit("max",t,false,fe.toString(r))}setLimit(t,r,n,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:fe.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:false,message:fe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:false,message:fe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:true,message:fe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:true,message:fe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:fe.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};fs.create=e=>new fs({checks:[],typeName:Ce.ZodBigInt,coerce:e?.coerce??false,...ze(e)});var ps=class extends Je{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==oe.boolean){let n=this._getOrReturnCtx(t);return Y(n,{code:K.invalid_type,expected:oe.boolean,received:n.parsedType}),Se}return jr(t.data)}};ps.create=e=>new ps({typeName:Ce.ZodBoolean,coerce:e?.coerce||false,...ze(e)});var ms=class e extends Je{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==oe.date){let a=this._getOrReturnCtx(t);return Y(a,{code:K.invalid_type,expected:oe.date,received:a.parsedType}),Se}if(Number.isNaN(t.data.getTime())){let a=this._getOrReturnCtx(t);return Y(a,{code:K.invalid_date}),Se}let n=new Nr,o;for(let a of this._def.checks)a.kind==="min"?t.data.getTime()<a.value&&(o=this._getOrReturnCtx(t,o),Y(o,{code:K.too_small,message:a.message,inclusive:true,exact:false,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?t.data.getTime()>a.value&&(o=this._getOrReturnCtx(t,o),Y(o,{code:K.too_big,message:a.message,inclusive:true,exact:false,maximum:a.value,type:"date"}),n.dirty()):Ye.assertNever(a);return {status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:fe.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:fe.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};ms.create=e=>new ms({checks:[],coerce:e?.coerce||false,typeName:Ce.ZodDate,...ze(e)});var Ml=class extends Je{_parse(t){if(this._getType(t)!==oe.symbol){let n=this._getOrReturnCtx(t);return Y(n,{code:K.invalid_type,expected:oe.symbol,received:n.parsedType}),Se}return jr(t.data)}};Ml.create=e=>new Ml({typeName:Ce.ZodSymbol,...ze(e)});var hs=class extends Je{_parse(t){if(this._getType(t)!==oe.undefined){let n=this._getOrReturnCtx(t);return Y(n,{code:K.invalid_type,expected:oe.undefined,received:n.parsedType}),Se}return jr(t.data)}};hs.create=e=>new hs({typeName:Ce.ZodUndefined,...ze(e)});var gs=class extends Je{_parse(t){if(this._getType(t)!==oe.null){let n=this._getOrReturnCtx(t);return Y(n,{code:K.invalid_type,expected:oe.null,received:n.parsedType}),Se}return jr(t.data)}};gs.create=e=>new gs({typeName:Ce.ZodNull,...ze(e)});var pi=class extends Je{constructor(){super(...arguments),this._any=true;}_parse(t){return jr(t.data)}};pi.create=e=>new pi({typeName:Ce.ZodAny,...ze(e)});var ba=class extends Je{constructor(){super(...arguments),this._unknown=true;}_parse(t){return jr(t.data)}};ba.create=e=>new ba({typeName:Ce.ZodUnknown,...ze(e)});var ho=class extends Je{_parse(t){let r=this._getOrReturnCtx(t);return Y(r,{code:K.invalid_type,expected:oe.never,received:r.parsedType}),Se}};ho.create=e=>new ho({typeName:Ce.ZodNever,...ze(e)});var jl=class extends Je{_parse(t){if(this._getType(t)!==oe.undefined){let n=this._getOrReturnCtx(t);return Y(n,{code:K.invalid_type,expected:oe.void,received:n.parsedType}),Se}return jr(t.data)}};jl.create=e=>new jl({typeName:Ce.ZodVoid,...ze(e)});var xa=class e extends Je{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==oe.array)return Y(r,{code:K.invalid_type,expected:oe.array,received:r.parsedType}),Se;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,s=r.data.length<o.exactLength.value;(i||s)&&(Y(r,{code:i?K.too_big:K.too_small,minimum:s?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:true,exact:true,message:o.exactLength.message}),n.dirty());}if(o.minLength!==null&&r.data.length<o.minLength.value&&(Y(r,{code:K.too_small,minimum:o.minLength.value,type:"array",inclusive:true,exact:false,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(Y(r,{code:K.too_big,maximum:o.maxLength.value,type:"array",inclusive:true,exact:false,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,s)=>o.type._parseAsync(new Ln(r,i,r.path,s)))).then(i=>Nr.mergeArray(n,i));let a=[...r.data].map((i,s)=>o.type._parseSync(new Ln(r,i,r.path,s)));return Nr.mergeArray(n,a)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:fe.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:fe.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:fe.toString(r)}})}nonempty(t){return this.min(1,t)}};xa.create=(e,t)=>new xa({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ce.ZodArray,...ze(t)});function Fl(e){if(e instanceof un){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=jn.create(Fl(n));}return new un({...e._def,shape:()=>t})}else return e instanceof xa?new xa({...e._def,type:Fl(e.element)}):e instanceof jn?jn.create(Fl(e.unwrap())):e instanceof Wo?Wo.create(Fl(e.unwrap())):e instanceof Jo?Jo.create(e.items.map(t=>Fl(t))):e}var un=class e extends Je{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend;}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=Ye.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==oe.object){let c=this._getOrReturnCtx(t);return Y(c,{code:K.invalid_type,expected:oe.object,received:c.parsedType}),Se}let{status:n,ctx:o}=this._processInputParams(t),{shape:a,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof ho&&this._def.unknownKeys==="strip"))for(let c in o.data)i.includes(c)||s.push(c);let l=[];for(let c of i){let u=a[c],d=o.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Ln(o,d,o.path,c)),alwaysSet:c in o.data});}if(this._def.catchall instanceof ho){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of s)l.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")s.length>0&&(Y(o,{code:K.unrecognized_keys,keys:s}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else {let c=this._def.catchall;for(let u of s){let d=o.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Ln(o,d,o.path,u)),alwaysSet:u in o.data});}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,m=await u.value;c.push({key:d,value:m,alwaysSet:u.alwaysSet});}return c}).then(c=>Nr.mergeObjectSync(n,c)):Nr.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return fe.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:fe.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Ce.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of Ye.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of Ye.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return Fl(this)}partial(t){let r={};for(let n of Ye.objectKeys(this.shape)){let o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional();}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of Ye.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else {let a=this.shape[n];for(;a instanceof jn;)a=a._def.innerType;r[n]=a;}return new e({...this._def,shape:()=>r})}keyof(){return DC(Ye.objectKeys(this.shape))}};un.create=(e,t)=>new un({shape:()=>e,unknownKeys:"strip",catchall:ho.create(),typeName:Ce.ZodObject,...ze(t)});un.strictCreate=(e,t)=>new un({shape:()=>e,unknownKeys:"strict",catchall:ho.create(),typeName:Ce.ZodObject,...ze(t)});un.lazycreate=(e,t)=>new un({shape:e,unknownKeys:"strip",catchall:ho.create(),typeName:Ce.ZodObject,...ze(t)});var ys=class extends Je{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function o(a){for(let s of a)if(s.result.status==="valid")return s.result;for(let s of a)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;let i=a.map(s=>new cn(s.ctx.common.issues));return Y(r,{code:K.invalid_union,unionErrors:i}),Se}if(r.common.async)return Promise.all(n.map(async a=>{let i={...r,common:{...r.common,issues:[]},parent:null};return {result:await a._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let a,i=[];for(let l of n){let c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!a&&(a={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues);}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(l=>new cn(l));return Y(r,{code:K.invalid_union,unionErrors:s}),Se}}get options(){return this._def.options}};ys.create=(e,t)=>new ys({options:e,typeName:Ce.ZodUnion,...ze(t)});var va=e=>e instanceof bs?va(e.schema):e instanceof Bn?va(e.innerType()):e instanceof xs?[e.value]:e instanceof ws?e.options:e instanceof _s?Ye.objectValues(e.enum):e instanceof Ss?va(e._def.innerType):e instanceof hs?[void 0]:e instanceof gs?[null]:e instanceof jn?[void 0,...va(e.unwrap())]:e instanceof Wo?[null,...va(e.unwrap())]:e instanceof zu||e instanceof Cs?va(e.unwrap()):e instanceof Ns?va(e._def.innerType):[],$p=class e extends Je{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==oe.object)return Y(r,{code:K.invalid_type,expected:oe.object,received:r.parsedType}),Se;let n=this.discriminator,o=r.data[n],a=this.optionsMap.get(o);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(Y(r,{code:K.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Se)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let o=new Map;for(let a of r){let i=va(a.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let s of i){if(o.has(s))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(s)}`);o.set(s,a);}}return new e({typeName:Ce.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...ze(n)})}};function J0(e,t){let r=Ho(e),n=Ho(t);if(e===t)return {valid:true,data:e};if(r===oe.object&&n===oe.object){let o=Ye.objectKeys(t),a=Ye.objectKeys(e).filter(s=>o.indexOf(s)!==-1),i={...e,...t};for(let s of a){let l=J0(e[s],t[s]);if(!l.valid)return {valid:false};i[s]=l.data;}return {valid:true,data:i}}else if(r===oe.array&&n===oe.array){if(e.length!==t.length)return {valid:false};let o=[];for(let a=0;a<e.length;a++){let i=e[a],s=t[a],l=J0(i,s);if(!l.valid)return {valid:false};o.push(l.data);}return {valid:true,data:o}}else return r===oe.date&&n===oe.date&&+e==+t?{valid:true,data:e}:{valid:false}}var vs=class extends Je{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),o=(a,i)=>{if(Dp(a)||Dp(i))return Se;let s=J0(a.value,i.value);return s.valid?((Ap(a)||Ap(i))&&r.dirty(),{status:r.value,value:s.data}):(Y(n,{code:K.invalid_intersection_types}),Se)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,i])=>o(a,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};vs.create=(e,t,r)=>new vs({left:e,right:t,typeName:Ce.ZodIntersection,...ze(r)});var Jo=class e extends Je{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==oe.array)return Y(n,{code:K.invalid_type,expected:oe.array,received:n.parsedType}),Se;if(n.data.length<this._def.items.length)return Y(n,{code:K.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"}),Se;!this._def.rest&&n.data.length>this._def.items.length&&(Y(n,{code:K.too_big,maximum:this._def.items.length,inclusive:true,exact:false,type:"array"}),r.dirty());let a=[...n.data].map((i,s)=>{let l=this._def.items[s]||this._def.rest;return l?l._parse(new Ln(n,i,n.path,s)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>Nr.mergeArray(r,i)):Nr.mergeArray(r,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Jo.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Jo({items:e,typeName:Ce.ZodTuple,rest:null,...ze(t)})};var Ip=class e extends Je{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==oe.object)return Y(n,{code:K.invalid_type,expected:oe.object,received:n.parsedType}),Se;let o=[],a=this._def.keyType,i=this._def.valueType;for(let s in n.data)o.push({key:a._parse(new Ln(n,s,n.path,s)),value:i._parse(new Ln(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?Nr.mergeObjectAsync(r,o):Nr.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Je?new e({keyType:t,valueType:r,typeName:Ce.ZodRecord,...ze(n)}):new e({keyType:fi.create(),valueType:t,typeName:Ce.ZodRecord,...ze(r)})}},Ll=class extends Je{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==oe.map)return Y(n,{code:K.invalid_type,expected:oe.map,received:n.parsedType}),Se;let o=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([s,l],c)=>({key:o._parse(new Ln(n,s,n.path,[c,"key"])),value:a._parse(new Ln(n,l,n.path,[c,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return Se;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(c.value,u.value);}return {status:r.value,value:s}})}else {let s=new Map;for(let l of i){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return Se;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(c.value,u.value);}return {status:r.value,value:s}}}};Ll.create=(e,t,r)=>new Ll({valueType:t,keyType:e,typeName:Ce.ZodMap,...ze(r)});var Bl=class e extends Je{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==oe.set)return Y(n,{code:K.invalid_type,expected:oe.set,received:n.parsedType}),Se;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(Y(n,{code:K.too_small,minimum:o.minSize.value,type:"set",inclusive:true,exact:false,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(Y(n,{code:K.too_big,maximum:o.maxSize.value,type:"set",inclusive:true,exact:false,message:o.maxSize.message}),r.dirty());let a=this._def.valueType;function i(l){let c=new Set;for(let u of l){if(u.status==="aborted")return Se;u.status==="dirty"&&r.dirty(),c.add(u.value);}return {status:r.value,value:c}}let s=[...n.data.values()].map((l,c)=>a._parse(new Ln(n,l,n.path,c)));return n.common.async?Promise.all(s).then(l=>i(l)):i(s)}min(t,r){return new e({...this._def,minSize:{value:t,message:fe.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:fe.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};Bl.create=(e,t)=>new Bl({valueType:e,minSize:null,maxSize:null,typeName:Ce.ZodSet,...ze(t)});var Fp=class e extends Je{constructor(){super(...arguments),this.validate=this.implement;}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==oe.function)return Y(r,{code:K.invalid_type,expected:oe.function,received:r.parsedType}),Se;function n(s,l){return Bu({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,$l(),ya].filter(c=>!!c),issueData:{code:K.invalid_arguments,argumentsError:l}})}function o(s,l){return Bu({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,$l(),ya].filter(c=>!!c),issueData:{code:K.invalid_return_type,returnTypeError:l}})}let a={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof mi){let s=this;return jr(async function(...l){let c=new cn([]),u=await s._def.args.parseAsync(l,a).catch(h=>{throw c.addIssue(n(l,h)),c}),d=await Reflect.apply(i,this,u);return await s._def.returns._def.type.parseAsync(d,a).catch(h=>{throw c.addIssue(o(d,h)),c})})}else {let s=this;return jr(function(...l){let c=s._def.args.safeParse(l,a);if(!c.success)throw new cn([n(l,c.error)]);let u=Reflect.apply(i,this,c.data),d=s._def.returns.safeParse(u,a);if(!d.success)throw new cn([o(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Jo.create(t).rest(ba.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||Jo.create([]).rest(ba.create()),returns:r||ba.create(),typeName:Ce.ZodFunction,...ze(n)})}},bs=class extends Je{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};bs.create=(e,t)=>new bs({getter:e,typeName:Ce.ZodLazy,...ze(t)});var xs=class extends Je{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Y(r,{received:r.data,code:K.invalid_literal,expected:this._def.value}),Se}return {status:"valid",value:t.data}}get value(){return this._def.value}};xs.create=(e,t)=>new xs({value:e,typeName:Ce.ZodLiteral,...ze(t)});function DC(e,t){return new ws({values:e,typeName:Ce.ZodEnum,...ze(t)})}var ws=class e extends Je{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Y(r,{expected:Ye.joinValues(n),received:r.parsedType,code:K.invalid_type}),Se}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return Y(r,{received:r.data,code:K.invalid_enum_value,options:n}),Se}return jr(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};ws.create=DC;var _s=class extends Je{_parse(t){let r=Ye.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==oe.string&&n.parsedType!==oe.number){let o=Ye.objectValues(r);return Y(n,{expected:Ye.joinValues(o),received:n.parsedType,code:K.invalid_type}),Se}if(this._cache||(this._cache=new Set(Ye.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=Ye.objectValues(r);return Y(n,{received:n.data,code:K.invalid_enum_value,options:o}),Se}return jr(t.data)}get enum(){return this._def.values}};_s.create=(e,t)=>new _s({values:e,typeName:Ce.ZodNativeEnum,...ze(t)});var mi=class extends Je{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==oe.promise&&r.common.async===false)return Y(r,{code:K.invalid_type,expected:oe.promise,received:r.parsedType}),Se;let n=r.parsedType===oe.promise?r.data:Promise.resolve(r.data);return jr(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};mi.create=(e,t)=>new mi({type:e,typeName:Ce.ZodPromise,...ze(t)});var Bn=class extends Je{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ce.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,a={addIssue:i=>{Y(n,i),i.fatal?r.abort():r.dirty();},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),o.type==="preprocess"){let i=o.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async s=>{if(r.value==="aborted")return Se;let l=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return l.status==="aborted"?Se:l.status==="dirty"?us(l.value):r.value==="dirty"?us(l.value):l});{if(r.value==="aborted")return Se;let s=this._def.schema._parseSync({data:i,path:n.path,parent:n});return s.status==="aborted"?Se:s.status==="dirty"?us(s.value):r.value==="dirty"?us(s.value):s}}if(o.type==="refinement"){let i=s=>{let l=o.refinement(s,a);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===false){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Se:(s.status==="dirty"&&r.dirty(),i(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?Se:(s.status==="dirty"&&r.dirty(),i(s.value).then(()=>({status:r.value,value:s.value}))))}if(o.type==="transform")if(n.common.async===false){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!di(i))return Se;let s=o.transform(i.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return {status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>di(i)?Promise.resolve(o.transform(i.value,a)).then(s=>({status:r.value,value:s})):Se);Ye.assertNever(o);}};Bn.create=(e,t,r)=>new Bn({schema:e,typeName:Ce.ZodEffects,effect:t,...ze(r)});Bn.createWithPreprocess=(e,t,r)=>new Bn({schema:t,effect:{type:"preprocess",transform:e},typeName:Ce.ZodEffects,...ze(r)});var jn=class extends Je{_parse(t){return this._getType(t)===oe.undefined?jr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};jn.create=(e,t)=>new jn({innerType:e,typeName:Ce.ZodOptional,...ze(t)});var Wo=class extends Je{_parse(t){return this._getType(t)===oe.null?jr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Wo.create=(e,t)=>new Wo({innerType:e,typeName:Ce.ZodNullable,...ze(t)});var Ss=class extends Je{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===oe.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Ss.create=(e,t)=>new Ss({innerType:e,typeName:Ce.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...ze(t)});var Ns=class extends Je{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Il(o)?o.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new cn(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new cn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ns.create=(e,t)=>new Ns({innerType:e,typeName:Ce.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...ze(t)});var zl=class extends Je{_parse(t){if(this._getType(t)!==oe.nan){let n=this._getOrReturnCtx(t);return Y(n,{code:K.invalid_type,expected:oe.nan,received:n.parsedType}),Se}return {status:"valid",value:t.data}}};zl.create=e=>new zl({typeName:Ce.ZodNaN,...ze(e)});var eL=Symbol("zod_brand"),zu=class extends Je{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Uu=class e extends Je{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return (async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Se:a.status==="dirty"?(r.dirty(),us(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Se:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:Ce.ZodPipeline})}},Cs=class extends Je{_parse(t){let r=this._def.innerType._parse(t),n=o=>(di(o)&&(o.value=Object.freeze(o.value)),o);return Il(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Cs.create=(e,t)=>new Cs({innerType:e,typeName:Ce.ZodReadonly,...ze(t)});function TC(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function AC(e,t={},r){return e?pi.create().superRefine((n,o)=>{let a=e(n);if(a instanceof Promise)return a.then(i=>{if(!i){let s=TC(t,n),l=s.fatal??r??true;o.addIssue({code:"custom",...s,fatal:l});}});if(!a){let i=TC(t,n),s=i.fatal??r??true;o.addIssue({code:"custom",...i,fatal:s});}}):pi.create()}var tL={object:un.lazycreate},Ce;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly";})(Ce||(Ce={}));var rL=(e,t={message:`Input not instance of ${e.name}`})=>AC(r=>r instanceof e,t),Ul=fi.create,$C=ds.create,nL=zl.create,oL=fs.create,Mp=ps.create,aL=ms.create,iL=Ml.create,sL=hs.create,lL=gs.create,cL=pi.create,uL=ba.create,dL=ho.create,fL=jl.create,pL=xa.create,W0=un.create,mL=un.strictCreate,hL=ys.create,gL=$p.create,yL=vs.create,vL=Jo.create,bL=Ip.create,xL=Ll.create,wL=Bl.create,_L=Fp.create,SL=bs.create,NL=xs.create,CL=ws.create,EL=_s.create,PL=mi.create,TL=Bn.create,kL=jn.create,RL=Wo.create,OL=Bn.createWithPreprocess,DL=Uu.create,AL=()=>Ul().optional(),$L=()=>$C().optional(),IL=()=>Mp().optional(),FL={string:(e=>fi.create({...e,coerce:true})),number:(e=>ds.create({...e,coerce:true})),boolean:(e=>ps.create({...e,coerce:true})),bigint:(e=>fs.create({...e,coerce:true})),date:(e=>ms.create({...e,coerce:true}))};var ML=Se;var IC=({className:e})=>jsxs("svg",{width:"419",height:"351",viewBox:"0 0 419 351",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",className:e,children:[jsx("path",{d:"M101.497 174.575C101.362 171.333 101.902 168.098 103.083 165.075C104.263 162.052 106.058 159.307 108.353 157.014C110.649 154.72 113.396 152.928 116.42 151.751C119.444 150.574 122.68 150.037 125.922 150.175C130.746 150.18 135.462 151.615 139.471 154.299C143.48 156.983 146.604 160.796 148.447 165.255C150.289 169.714 150.769 174.619 149.825 179.35C148.88 184.082 146.555 188.427 143.141 191.837C139.728 195.247 135.38 197.568 130.648 198.508C125.915 199.447 121.01 198.963 116.553 197.115C112.096 195.268 108.287 192.14 105.607 188.128C102.927 184.116 101.497 179.4 101.497 174.575Z"}),jsx("path",{d:"M185.778 174.575C185.644 171.333 186.184 168.098 187.364 165.075C188.544 162.052 190.339 159.307 192.635 157.014C194.93 154.72 197.677 152.928 200.701 151.751C203.725 150.574 206.961 150.037 210.203 150.175C215.028 150.18 219.743 151.615 223.752 154.299C227.761 156.983 230.885 160.796 232.728 165.255C234.571 169.714 235.05 174.619 234.106 179.35C233.162 184.082 230.836 188.427 227.423 191.837C224.009 195.247 219.661 197.568 214.929 198.508C210.196 199.447 205.292 198.963 200.835 197.115C196.378 195.268 192.568 192.14 189.888 188.128C187.208 184.116 185.778 179.4 185.778 174.575Z"}),jsx("path",{d:"M269.997 174.575C269.862 171.333 270.402 168.098 271.583 165.075C272.763 162.052 274.558 159.307 276.853 157.014C279.149 154.72 281.896 152.928 284.92 151.751C287.944 150.574 291.18 150.037 294.422 150.175C299.247 150.18 303.962 151.615 307.971 154.299C311.98 156.983 315.104 160.796 316.946 165.255C318.789 169.714 319.269 174.619 318.325 179.35C317.38 184.082 315.055 188.427 311.641 191.837C308.228 195.247 303.88 197.568 299.148 198.508C294.415 199.447 289.51 198.963 285.053 197.115C280.596 195.268 276.787 192.14 274.107 188.128C271.427 184.116 269.997 179.4 269.997 174.575Z"}),jsx("path",{d:"M0.476562 197.25V153.55C7.95998 153.541 15.3944 152.343 22.5016 150C27.1229 147.429 30.9265 143.608 33.4766 138.975C36.8421 132.986 38.9996 126.395 39.8266 119.575C40.9644 109.484 41.4237 99.3276 41.2016 89.1749C40.6848 72.6982 41.7143 56.2094 44.2766 39.9249C45.8434 31.5389 49.7028 23.7509 55.4266 17.4249C60.6952 10.9582 67.731 6.16347 75.6766 3.62491C86.4389 1.01665 97.5112 -0.0855449 108.577 0.349899H117.652V36.2749C109.441 35.7638 101.201 36.5313 93.2266 38.5499C89.8504 39.8715 87.0336 42.3175 85.2516 45.4749C83.3166 53.1601 82.475 61.0797 82.7516 68.9999C82.7516 76.6499 82.2349 91.1582 81.2016 112.525C80.9709 122.417 79.4755 132.238 76.7516 141.75C74.7665 148.385 71.6636 154.633 67.5766 160.225C62.7049 166.078 56.9529 171.139 50.5266 175.225C56.8771 179.004 62.4854 183.909 67.0766 189.7C71.5922 195.685 74.9344 202.472 76.9266 209.7C79.5735 220.062 81.0659 230.685 81.3766 241.375C82.1766 261.525 82.5766 274.392 82.5766 279.975C82.2792 287.837 83.207 295.698 85.3266 303.275C87.2466 306.515 90.1687 309.042 93.6516 310.475C101.482 312.639 109.618 313.484 117.727 312.975V350.125H108.652C97.6899 350.38 86.7655 348.756 76.3516 345.325C68.4029 342.94 61.2154 338.518 55.5016 332.5C49.7172 326.182 45.7744 318.401 44.1016 310C41.7647 296.078 40.7851 281.961 41.1766 267.85C41.7704 253.285 40.8488 238.699 38.4266 224.325C36.8991 216.354 32.9123 209.063 27.0266 203.475C18.8768 199.104 9.71968 196.957 0.476562 197.25Z"}),jsx("path",{d:"M392.123 203.575C386.238 209.163 382.251 216.454 380.723 224.425C378.301 238.799 377.38 253.386 377.973 267.95C378.342 282.03 377.346 296.112 374.998 310C373.326 318.401 369.383 326.182 363.598 332.5C357.915 338.588 350.735 343.079 342.773 345.525C332.36 348.956 321.435 350.58 310.473 350.325H301.398V313.25C309.507 313.759 317.643 312.914 325.473 310.75C328.956 309.317 331.878 306.79 333.798 303.55C335.918 295.973 336.846 288.112 336.548 280.25C336.548 274.667 336.948 261.8 337.748 241.65C338.077 230.966 339.587 220.352 342.248 210C344.241 202.772 347.583 195.986 352.098 190C356.69 184.209 362.298 179.304 368.648 175.525C362.222 171.439 356.47 166.378 351.598 160.525C347.511 154.933 344.409 148.685 342.423 142.05C339.7 132.538 338.204 122.717 337.973 112.825C336.94 91.4583 336.423 76.95 336.423 69.3C336.7 61.3798 335.858 53.4601 333.923 45.775C332.141 42.6175 329.325 40.1716 325.948 38.85C317.974 36.8313 309.734 36.0638 301.523 36.575V0.399948H310.598C321.664 -0.035496 332.736 1.0667 343.498 3.67496C351.444 6.21351 358.48 11.0082 363.748 17.475C369.472 23.8009 373.332 31.5889 374.898 39.975C377.461 56.2594 378.49 72.7483 377.973 89.225C377.751 99.3776 378.211 109.534 379.348 119.625C380.175 126.445 382.333 133.036 385.698 139.025C388.249 143.658 392.052 147.479 396.673 150.05C403.794 152.415 411.246 153.631 418.748 153.65V197.25C409.471 196.975 400.286 199.157 392.123 203.575Z"})]});function l9({open:e,onOpenChange:t,onDefinitionCreated:r}){let{jsonSchema:n,setJsonSchema:o}=jo(),[a,i]=useState(""),[s,l]=useState({type:"object",properties:{},required:[]}),[c,u]=useState(null);useEffect(()=>{e&&(i(""),l({type:"object",properties:{},required:[]}),u(null));},[e]);let d=y=>{let p=Object.keys(n.$defs||{});return ui(y,p,void 0,"definition")},m=y=>{i(y),u(d(y));},h=()=>{if(!a.trim())return;let y=d(a);if(y){u(y);return}let p={...n};p.$defs||(p.$defs={}),p.$defs[a]=s,o(p),r(a),t(false);};return jsx(hn,{open:e,onOpenChange:t,children:jsxs(co,{className:"sm:max-w-[700px] max-h-[80vh] overflow-y-auto",children:[jsxs(li,{children:[jsx(gn,{children:"Create New Definition"}),jsx(ci,{children:"Create a reusable definition that can be referenced in multiple places."})]}),jsxs("div",{className:"mb-4",children:[jsxs(Yt,{htmlFor:"defName",className:"block text-sm font-medium text-gray-700",children:["Definition Name",jsx("span",{className:"text-red-500 ml-[2px]",children:"*"})]}),jsx(nt,{id:"defName",value:a,onChange:y=>m(y.target.value),className:`mt-1 ${c?"border-red-500":""}`,placeholder:"e.g. person_address"}),c&&jsxs("p",{className:"text-sm font-medium text-red-500 mt-1 flex items-center gap-1",children:[jsx(AlertCircle,{className:"h-3 w-3"}),c]}),jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Must start with a lowercase letter or underscore, contain only lowercase letters, digits, or underscores, and be at most 64 characters. Cannot be a Python reserved keyword."})]}),jsx(ga,{name:a||"Click to set definition name",node:s,onChange:l,jsonSchema:n,setJsonSchema:o,path:"#/definition",defs:n.$defs||{},canDelete:false,setDefsAccordionOpen:()=>{},onNameChange:y=>m(y),draggedParentRef:kt__default.useRef(null),draggedPropertyRef:kt__default.useRef(null)}),jsxs(Tl,{children:[jsx(V,{variant:"outline",onClick:()=>t(false),children:"Cancel"}),jsxs(V,{onClick:h,disabled:!a.trim()||!!c,children:[jsx(PlusIcon,{className:"w-4 h-4 mr-2"}),"Create Definition"]})]})]})})}var go=e=>{switch(e){case "string":return jsx(Type,{className:"w-4 h-4"});case "number":case "integer":return jsx(Hash,{className:"w-4 h-4"});case "boolean":return jsx(ToggleLeft,{className:"w-4 h-4"});case "enum":return jsx(List,{className:"w-4 h-4"});case "object":return jsx(Braces,{className:"w-4 h-4"});case "array":return jsx(Brackets,{className:"w-4 h-4"});case "date":return jsx(Calendar,{className:"w-4 h-4"});case "time":return jsx(Clock,{className:"w-4 h-4"});case "datetime":return jsx(CalendarClock,{className:"w-4 h-4"});case "$ref":return jsx(Link,{className:"w-4 h-4"});default:return jsx(Shapes,{className:"w-4 h-4"})}},MC=e=>{switch(e){case "Address":return jsx(MapPin,{className:"w-4 h-4"});case "Price":return jsx(DollarSign,{className:"w-4 h-4"});case "Person":return jsx(User,{className:"w-4 h-4"});case "Company":return jsx(Building2,{className:"w-4 h-4"});case "Event":return jsx(CalendarDays,{className:"w-4 h-4"});default:return jsx(Link,{className:"w-4 h-4"})}};function c9({name:e,value:t,onChange:r,setJsonSchema:n,label:o="Type",isRoot:a=false,setDialogMode:i,disabled:s=false,focusPath:l}){let{jsonSchema:c}=jo(),[u,d]=useState(false),[m,h]=useState(null),y=ln(t);return jsxs("div",{className:a?"":"bg-slate-50 p-3 rounded-md mt-3",children:[jsx(l9,{open:u,onOpenChange:d,onDefinitionCreated:f=>{r(Ct(t,{$ref:`#/$defs/${f}`}));}}),!a&&jsx(Yt,{className:"text-sm font-medium text-gray-700 mb-2 block",children:o}),jsxs(dr,{children:[jsx(fr,{asChild:true,children:jsxs(V,{disabled:s,variant:"outline",className:`w-full mt-2 justify-between ${s?"disabled:opacity-100":""}`,children:[jsxs("div",{className:"flex items-center gap-2",children:[go(y.type),jsx("span",{children:(()=>{if(y.type==="$ref"){let f=t.$ref,x=Array.isArray(t.anyOf)?t.anyOf.find(v=>typeof v=="object"&&v.$ref)?.$ref:void 0,g=f||x;return g?g.replace("#/$defs/",""):"$ref"}return y.type==="date"?"date":y.type==="time"?"time":y.type==="datetime"?"timestamp":y.type==="boolean"?"true/false":y.type==="enum"?"multiple choice":y.type==="array"?"list":y.type})()})]}),jsx(ChevronDown,{className:"w-4 h-4 ml-2"})]})}),jsxs(pr,{className:"w-full",children:[jsx(ge,{disabled:s,onSelect:()=>r(Mn("string",y.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[go("string"),jsx("span",{children:"string"})]})}),jsx(ge,{disabled:s,onSelect:()=>r(Mn("number",y.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[go("number"),jsx("span",{children:"number"})]})}),jsx(ge,{disabled:s,onSelect:()=>r(Mn("boolean",y.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[go("boolean"),jsx("span",{children:"true/false"})]})}),jsx(ge,{disabled:s,onSelect:()=>{let f=Mn("enum",y.isNullable,t);r({...f,enum:t.enum||[]});},children:jsxs("div",{className:"flex items-center gap-2",children:[go("enum"),jsx("span",{children:"multiple choice"})]})}),jsx(ge,{disabled:s,onSelect:()=>r(Mn("date",y.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[go("date"),jsx("span",{children:"date"})]})}),jsx(ge,{disabled:s,onSelect:()=>r(Mn("time",y.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[go("time"),jsx("span",{children:"time"})]})}),jsx(ge,{disabled:s,onSelect:()=>r(Mn("datetime",y.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[go("datetime"),jsx("span",{children:"timestamp"})]})}),jsx(ge,{disabled:s,onSelect:()=>r(Mn("array",y.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[go("array"),jsx("span",{children:"list"})]})}),jsx(ge,{disabled:s,onSelect:()=>r(Mn("object",y.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[go("object"),jsx("span",{children:"object"})]})}),jsxs(Vr,{children:[jsx(Hr,{children:jsxs("div",{className:"flex items-center gap-2",children:[go("$ref"),jsx("span",{children:"definition"})]})}),jsx(uo,{children:jsxs(Jr,{children:[Object.keys(c.$defs||{}).length>0?jsxs(Fragment,{children:[Object.keys(c.$defs||{}).map(f=>jsx(ge,{onSelect:()=>{r(Ct(t,{$ref:`#/$defs/${f}`}));},children:jsxs("div",{className:"flex items-center gap-2",children:[MC(f),jsx("span",{children:f})]})},f)),jsx(fo,{})]}):null,jsx(ge,{disabled:s,onSelect:()=>{setTimeout(()=>{d(true);},100);},children:jsxs("div",{className:"flex items-center gap-2",children:[jsx(PlusIcon,{className:"h-4 w-4"}),jsx("span",{children:"Create new definition"})]})})]})})]}),jsxs(Vr,{children:[jsx(Hr,{children:jsxs("div",{className:"flex items-center gap-2",children:[jsx(Shapes,{className:"w-4 h-4"}),jsx("span",{children:"object template"})]})}),jsx(uo,{children:jsx(Jr,{children:Object.entries(Ol).map(([f,x])=>jsx(ge,{onSelect:()=>{let g=[f];x.deps&&g.push(...x.deps);let v={...c.$defs||{}};for(let w of g)v[w]||(v[w]=Ol[w]);n({...c,$defs:v}),r(Ct(t,{$ref:`#/$defs/${f}`}));},children:jsxs("div",{className:"flex items-center gap-2",children:[MC(f),jsx("span",{children:f})]})},f))})})]})]})]}),y.type==="object"&&!t.$ref&&jsx("div",{className:"text-sm mt-3",children:jsx(V,{disabled:s,variant:"secondary",className:"w-full",onClick:()=>{i("object-editor");},children:"Edit Object Properties"})}),y.type==="array"&&jsx("div",{className:"text-sm mt-3",children:jsx(V,{disabled:s,variant:"secondary",className:"w-full",onClick:()=>{h(t.items||{type:"string"}),i("array-editor");},children:"Edit List Items"})}),(()=>{let f=t.anyOf&&Array.isArray(t.anyOf)&&t.anyOf.find(x=>typeof x=="object"&&(x.type!=="null"||x.$ref||x.enum))||t;return Array.isArray(f.enum)})()&&jsxs("div",{className:"mt-3",children:[jsx(Yt,{className:"text-sm font-medium text-gray-700 block mb-2",children:"Enabled options"}),jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:(t.anyOf&&Array.isArray(t.anyOf)?t.anyOf.find(f=>typeof f=="object"&&(f.type!=="null"||f.$ref||f.enum))?.enum||[]:t.enum||[]).map((f,x)=>jsxs("div",{className:"flex items-center space-x-2 border-gray-200 border rounded-md px-2 py-1 bg-slate-50",children:[jsx(nt,{disabled:s,value:typeof f=="string"?f:String(f),onChange:g=>{let v=t.anyOf&&Array.isArray(t.anyOf)?t.anyOf.find(_=>typeof _=="object"&&(_.type!=="null"||_.$ref||_.enum))||{}:t,w=[...v.enum||[]];w[x]=g.target.value;let N={...v,enum:w.filter(_=>_&&_!=="")},S=Ct(t,N);r(S);},className:"h-6 w-24 shadow-none px-1 bg-transparent border-0 focus-visible:ring-0 focus-visible:ring-offset-0"}),jsx(V,{type:"button",disabled:s,variant:"ghost",size:"icon",className:"h-4 w-4 p-0",onClick:()=>{let g=t.anyOf&&Array.isArray(t.anyOf)?t.anyOf.find(S=>typeof S=="object"&&(S.type!=="null"||S.$ref||S.enum))||{}:t,v=[...g.enum||[]];v.splice(x,1);let w={...g,enum:v},N=Ct(t,w);r(N);},children:jsx(X,{className:"h-3 w-3"})})]},x))}),jsxs("div",{className:"flex items-center gap-2",children:[jsx(nt,{disabled:s,placeholder:"Add new value",onKeyDown:f=>{if(f.key==="Enter"&&f.currentTarget.value){let x=t.anyOf&&Array.isArray(t.anyOf)?t.anyOf.find(w=>typeof w=="object"&&(w.type!=="null"||w.$ref||w.enum))||{}:t,g={...x,enum:[...x.enum||[],f.currentTarget.value]},v=Ct(t,g);r(v),f.currentTarget.value="";}},className:"w-40"}),jsxs(V,{disabled:s,type:"button",variant:"outline",size:"sm",onClick:f=>{let x=f.currentTarget.previousElementSibling;if(x.value){let g=t.anyOf&&Array.isArray(t.anyOf)?t.anyOf.find(N=>typeof N=="object"&&(N.type!=="null"||N.$ref||N.enum))||{}:t,v={...g,enum:[...g.enum||[],x.value]},w=Ct(t,v);r(w),x.value="";}},children:[jsx(PlusIcon,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})}var u9=W0({name:Ul().min(1,{message:"Name is required"}).regex(/^[a-z_][a-z0-9_]{0,63}$/,{message:"Name must start with a lowercase letter or underscore, contain only lowercase letters, numbers, or underscores, and be at most 64 characters long"}),description:Ul().optional(),reasoningPrompt:Ul().optional(),required:Mp()});function j0({editedProperty:e,setEditedProperty:t,setJsonSchema:r,editedJsonSchema:n,setEditedJsonSchema:o,editedName:a,setEditedName:i,onSubmit:s,onCancel:l,onDelete:c,submitLabel:u="Save Changes",onNameError:d,editMode:m="editable",wrapCancelInDialogClose:h,wrapSubmitInDialogClose:y,fieldPathOverride:p}){let[f,x]=useState("main"),{jsonSchema:g}=jo(),{setShowSchemaEditor:v,setSelectedFieldPath:w}=Lu(),N=kt__default.useRef(null),S=kt__default.useRef(null),[_,P]=useState(null),R=useCallback($=>{let L=Object.keys(g.properties||{});return ui($,L,a,"property")},[g,a]);useEffect(()=>{d&&d(_);},[_,d]);let E=useForm({resolver:zodResolver(u9),defaultValues:{name:a,description:e.description||"",reasoningPrompt:e["X-ReasoningPrompt"]||"",required:!ln(e).isNullable},mode:"onBlur"}),[C,b]=useState(!!e["X-ReasoningPrompt"]),O=useRef({name:a,description:e.description||"",reasoningPrompt:e["X-ReasoningPrompt"]||"",required:!ln(e).isNullable}),D=E.handleSubmit($=>{let L=R($.name);if(L){P(L);return}i($.name);let le={...e,title:qo($.name),description:$.description,"X-ReasoningPrompt":$.reasoningPrompt},ae=Op(le,!$.required);t(ae),s&&s(),u==="Save Changes"&&toast.success("Changes saved successfully");}),k=$=>{if($.key==="Enter"&&!$.shiftKey){if(_){$.preventDefault();return}$.target instanceof HTMLTextAreaElement?($.ctrlKey||$.metaKey)&&($.preventDefault(),D()):($.preventDefault(),D());}},I=$=>{let L=$.target.value;i(L),P(null),E.setValue("name",L,{shouldValidate:true});},F=()=>{let $=E.getValues("name");if($&&!E.formState.errors.name){let L=R($);P(L);}else E.formState.errors.name&&P(null);},Z=$=>{let L=$.target.value,le={...e,description:L};t(le),E.setValue("description",L);},pe=$=>{let L=$.target.value,le={...e,"X-ReasoningPrompt":L};t(le),E.setValue("reasoningPrompt",L);},ie=$=>{if(typeof $=="boolean"){let L=Op(e,!$);t(L),E.setValue("required",$);}},J=()=>{b($=>!$);};useEffect(()=>{let $=O.current;if(a!==$.name&&(E.setValue("name",a,{shouldValidate:true}),$.name=a,a)){let le=R(a);P(le);}e.description!==$.description&&(E.setValue("description",e.description||""),$.description=e.description||""),e["X-ReasoningPrompt"]!==$.reasoningPrompt&&(E.setValue("reasoningPrompt",e["X-ReasoningPrompt"]||""),$.reasoningPrompt=e["X-ReasoningPrompt"]||"",e["X-ReasoningPrompt"]&&b(true));let L=!ln(e).isNullable;L!==$.required&&(E.setValue("required",L),$.required=L);},[a,e,E,R]),useEffect(()=>{if(a){let $=R(a);P($);}},[a,R]);let X$1=ln(e).type==="enum"&&(()=>{if(Array.isArray(e.enum))return e.enum;if(Array.isArray(e.anyOf)){let $=e.anyOf.find(L=>typeof L=="object"&&(L.type!=="null"||L.$ref||L.enum));if($&&Array.isArray($.enum))return $.enum}return []})().length===0;return m==="editable"&&f==="array-editor"&&ln(e).type==="array"?jsxs("div",{className:"space-y-4 max-h-[80vh] overflow-y-auto p-4",children:[jsxs("div",{className:"flex items-center mb-4",children:[jsx(V,{variant:"ghost",size:"sm",onClick:()=>x("main"),children:jsx(ChevronLeft,{className:"w-4 h-4 mr-2"})}),jsx("h2",{className:"text-lg font-medium ml-2",children:"Edit list items"})]}),jsx("div",{className:"bg-gray-50 p-4 rounded-md",children:jsx(ga,{name:"items",node:e.items||{type:"string"},onChange:$=>{t({...e,items:$});},jsonSchema:n,setJsonSchema:o,path:"#/array-item",defs:g.$defs||{},canDelete:false,setDefsAccordionOpen:()=>{},draggedParentRef:N,draggedPropertyRef:S,hidePencilButton:true})}),jsx("div",{className:"flex justify-end space-x-2 mt-4",children:jsx(V,{onClick:()=>x("main"),children:"Done"})})]}):m==="editable"&&f==="object-editor"&&ln(e).type==="object"?jsxs("div",{className:"space-y-4 max-h-[80vh] overflow-y-auto p-4",children:[jsxs("div",{className:"flex items-center mb-4",children:[jsx(V,{variant:"ghost",size:"sm",onClick:()=>x("main"),children:jsx(ChevronLeft,{className:"w-4 h-4 mr-2"})}),jsx("h2",{className:"text-lg font-medium ml-2",children:"Edit Object Properties"})]}),jsx(ga,{name:a,node:e,onChange:t,jsonSchema:n,setJsonSchema:o,path:"#/object",defs:g.$defs||{},canDelete:false,setDefsAccordionOpen:()=>{},draggedParentRef:N,draggedPropertyRef:S}),jsx("div",{className:"flex justify-end space-x-2 mt-4",children:jsx(V,{onClick:()=>x("main"),children:"Done"})})]}):jsx(vl,{...E,children:jsxs("form",{onSubmit:D,onKeyDown:k,className:"flex flex-col h-full z-10 bg-gray-50 rounded-2xl",children:[jsxs("div",{className:"bg-white shadow-xs flex-1 overflow-y-auto z-20 max-h-[60vh] rounded-2xl",children:[jsxs("div",{className:"p-4 space-y-4 border-b border-gray-200",children:[jsx(ao,{control:E.control,name:"name",render:({field:$,fieldState:L})=>jsxs(kn,{children:[jsx("div",{className:"flex flex-row items-center gap-2",children:jsx(Yt,{htmlFor:"name",className:"block text-sm font-medium text-gray-700",children:"Name"})}),jsx(Rn,{children:jsx(nt,{id:"name",disabled:m!=="editable",value:a,onChange:I,onBlur:F,className:`${L.error||_?"border-red-500":""} ${m!=="editable"?"disabled:opacity-100":""}`,placeholder:"e.g. first_name",required:true})}),L.error&&jsxs("p",{className:"text-sm font-medium text-red-500 mt-1 flex items-center gap-1",children:[jsx(AlertCircle,{className:"h-3 w-3"}),L.error.message]}),!L.error&&_&&jsxs("p",{className:"text-sm font-medium text-red-500 mt-1 flex items-center gap-1",children:[jsx(AlertCircle,{className:"h-3 w-3"}),_]})]})}),jsxs("div",{children:[jsx(Yt,{htmlFor:"type",className:"block text-sm font-medium text-gray-700",children:"Data type"}),jsx(c9,{name:a,disabled:m!=="editable",value:e,onChange:t,setJsonSchema:o,setDialogMode:x,isRoot:true,focusPath:p??a})]}),jsxs("div",{className:"flex flex-row items-center justify-between",children:[jsx(ao,{control:E.control,name:"required",render:({field:$})=>jsxs(kn,{className:"flex flex-row items-center space-x-2 space-y-0",children:[jsx(Rn,{children:jsx(Np,{id:"required",disabled:m!=="editable",checked:!ln(e).isNullable,onCheckedChange:ie,className:m!=="editable"?"disabled:opacity-100":""})}),jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(Yt,{htmlFor:"required",className:"text-sm font-medium text-gray-700 cursor-pointer",children:"Required"})}),jsxs(et,{className:"max-w-xs",children:[jsx("p",{children:"When a field is required, it must have a value and cannot be null or undefined."}),jsx("p",{children:"Required fields must be provided when submitting data for this schema."})]})]})]})}),m!=="readOnly"&&jsx("div",{className:"text-sm",children:jsxs(V,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{let $=p??a;$&&w($),v(true);},children:[jsx(IC,{})," Edit in Schema Editor"]})})]})]}),jsxs("div",{className:"p-4 space-y-4",children:[jsx(ao,{control:E.control,name:"description",render:({field:$})=>jsxs(kn,{className:"group",children:[jsx("div",{className:"flex flex-row items-center justify-between gap-2",children:jsx(Yt,{htmlFor:"description",className:"block text-sm font-medium text-gray-700",children:"Description"})}),jsx(Rn,{children:jsx(nn,{id:"description",value:e.description||"",onChange:Z,onBlur:$.onBlur,disabled:m==="readOnly",className:m==="readOnly"?"disabled:opacity-100":""})})]})}),!C&&m!=="readOnly"?jsxs("div",{className:"flex flex-row space-x-2 mt-2 items-center",children:[jsxs(V,{type:"button",onClick:J,className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay text-sm h-[1.875rem] px-3 ring-1 bg-purple-500 hover:bg-purple-500 hover:opacity-80 text-white ring-purple-500",children:[jsx(PlusIcon,{className:"size-3.5"}),"Add reasoning"]}),jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(Info,{className:"size-4 text-[#736982]"})}),jsxs(et,{className:"max-w-xs flex flex-col",children:[jsx("p",{children:"A reasoning prompt adds an additional field during inference to give the LLM time to think."}),jsx("p",{children:"This is useful for challenging fields that require additional reasoning, such as unit conversions, intermediate computations, or complex logic."}),jsxs("a",{href:"https://docs.retab.com/core-concepts/Reasoning",className:"text-blue-300 mt-1 self-end flex flex-row items-center gap-1",children:["Learn more about reasoning"," ",jsx(ArrowRight,{className:"w-3 h-3"})]})]})]})]}):C?jsx(ao,{control:E.control,name:"reasoningPrompt",render:({field:$})=>jsxs(kn,{className:"group",children:[jsxs("div",{className:"flex justify-between items-center ",children:[jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(Yt,{htmlFor:"reasoningPrompt",className:"text-sm font-medium text-gray-700 flex flex-row items-center cursor-pointer",children:"Reasoning Prompt"})}),jsxs(et,{className:"max-w-xs",children:[jsx("p",{children:"A reasoning prompt adds an additional field during inference to give the LLM time to think."}),jsx("p",{children:"This is useful for challenging fields that require additional reasoning, such as unit conversions, intermediate computations, or complex logic."})]})]}),jsx("div",{className:"flex flex-row items-center gap-2 group-hover:opacity-100 transition-opacity duration-300 opacity-0",children:!e["X-ReasoningPrompt"]&&jsx(V,{type:"button",variant:"ghost",size:"sm",disabled:m==="readOnly",onClick:()=>{J();let L={...e,"X-ReasoningPrompt":""};t(L),E.setValue("reasoningPrompt","");},className:"h-6 w-6 p-0",children:jsx(X,{className:"h-4 w-4"})})})]}),jsx(Rn,{children:jsx(nn,{id:"reasoningPrompt",value:e["X-ReasoningPrompt"]||"",onChange:pe,onBlur:$.onBlur,className:`before:bg-gradient-to-b before:from-white/20 ring ring-purple-300 w-full bg-purple-100 after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay h-24 rounded-md border px-3 py-2 text-sm file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-purple-200 disabled:cursor-not-allowed ${m==="readOnly"?"disabled:opacity-100":"disabled:opacity-50"}`,placeholder:"Add a reasoning prompt for this field",disabled:m==="readOnly"})})]})}):null]})]}),m!=="readOnly"&&jsxs("div",{className:"p-4 flex justify-between rounded-b-2xl",children:[jsx("div",{children:c&&m==="editable"&&jsx(V,{type:"button",variant:"outline",size:"sm",disabled:false,onClick:c,className:"text-red-600 hover:text-red-800 border-red-200 hover:border-red-300",children:"Delete Property"})}),jsxs("div",{className:"flex space-x-2",children:[l&&(h?jsx(I0,{asChild:true,children:jsx(V,{type:"button",variant:"outline",size:"sm",onClick:l,children:"Cancel"})}):jsx(V,{type:"button",variant:"outline",size:"sm",onClick:l,children:"Cancel"})),y?jsx(I0,{asChild:true,children:jsx(V,{type:"submit",size:"sm",className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay text-sm h-[1.875rem] px-3 ring-1 bg-gray-900 hover:bg-gray-900 hover:opacity-80 text-white ring-gray-900",disabled:X$1||!!_||!!E.formState.errors.name,children:u})}):jsx(V,{type:"submit",size:"sm",className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay text-sm h-[1.875rem] px-3 ring-1 bg-gray-900 hover:bg-gray-900 hover:opacity-80 text-white ring-gray-900",disabled:X$1||!!_||!!E.formState.errors.name,children:u})]})]})]})})}function Vl({property:e,propertyKey:t,setDropdownOpen:r,jsonSchema:n,setJsonSchema:o,editMode:a="editable"}){let[i,s]=useState(()=>t.split(".")?.pop()||t),[l,c]=useState(e||d9),[u,d]=useState({...n}),[m,h]=useState(null);return useEffect(()=>{d({...n});},[n]),jsx(j0,{editedProperty:l,setEditedProperty:c,setJsonSchema:o,editedJsonSchema:u,setEditedJsonSchema:d,editedName:i,setEditedName:s,onSubmit:()=>{if(m)return;let f={...l,title:qo(i)},x=CC(u,t,i,f);o(x),r(false);},onCancel:()=>{r(false);},submitLabel:"Save Changes",onNameError:h,editMode:a,fieldPathOverride:t,wrapCancelInDialogClose:true,wrapSubmitInDialogClose:true})}var d9={type:"string",description:""};var h9=cva("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function dn({className:e,variant:t,asChild:r=false,...n}){return jsx(r?Slot:"span",{"data-slot":"badge",className:T(h9({variant:t}),e),...n})}function vo({...e}){return jsx(Cr.Root,{"data-slot":"alert-dialog",...e})}function y9({...e}){return jsx(Cr.Portal,{"data-slot":"alert-dialog-portal",...e})}function v9({className:e,...t}){return jsx(Cr.Overlay,{"data-slot":"alert-dialog-overlay",className:T("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function bo({className:e,...t}){return jsxs(y9,{children:[jsx(v9,{}),jsx(Cr.Content,{"data-slot":"alert-dialog-content",className:T("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...t})]})}function xo({className:e,...t}){return jsx("div",{"data-slot":"alert-dialog-header",className:T("flex flex-col gap-2 text-center sm:text-left",e),...t})}function wo({className:e,...t}){return jsx("div",{"data-slot":"alert-dialog-footer",className:T("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function _o({className:e,...t}){return jsx(Cr.Title,{"data-slot":"alert-dialog-title",className:T("text-lg font-semibold",e),...t})}function So({className:e,...t}){return jsx(Cr.Description,{"data-slot":"alert-dialog-description",className:T("text-muted-foreground text-sm",e),...t})}function No({className:e,...t}){return jsx(Cr.Action,{className:T(zi(),e),...t})}function wa({className:e,...t}){return jsx(Cr.Cancel,{className:T(zi({variant:"outline"}),e),...t})}function Bp(e){let t=e.match(/\.\*/g),r=t?t.length:0;return {path:e,level:r,hasArray:r>0}}function G0(e,t){let r=Bp(e),n=Bp(t);return r.level<=n.level}function x9(e,t){let r=Bp(e),n=Bp(t);return r.level-n.level===1}function _a(e,t){console.log("[CONTEXT DEBUG] Finding cursor context:",{formula:e,cursorPosition:t});let r={isInsideAggregation:false,aggregationDepth:0},n=e.substring(0,t),o=["SUM","AVERAGE","MIN","MAX","COUNT","FILTER","LOOKUP","MATCH","FLATTEN"],a=null,i=-1;for(let s of o){let l=0;for(;l<n.length;){let c=n.indexOf(s+"(",l);if(c===-1)break;console.log(`[CONTEXT DEBUG] Found ${s} at funcIndex:`,c);let u=e.substring(c+s.length),d=0,m=false,h=0,y="",p=c+s.length+1;for(let f=0;f<u.length;f++){let x=c+s.length+f;if(u[f]==="(")d++;else if(u[f]===")"){if(d--,d===0){console.log(`[CONTEXT DEBUG] Found closing paren at absolutePos ${x}, cursor at ${t}`),x>=t&&(console.log("[CONTEXT DEBUG] Cursor is before/at closing paren, setting isInside=true"),m=true);break}}else u[f]===","&&d===1&&x<t&&(h===0&&(y=e.substring(p,x).trim()),h++,p=x+1,console.log(`[CONTEXT DEBUG] Found comma at ${x}, now at argument ${h}`));if(x===t&&d>0){console.log(`[CONTEXT DEBUG] Cursor at absolutePos ${x}, parenCount ${d}, setting isInside=true`),m=true;break}if(x>t&&d>0){console.log(`[CONTEXT DEBUG] Passed cursor at absolutePos ${x}, parenCount ${d}, setting isInside=true`),m=true;break}}if(d>0&&t>c+s.length&&(m=true),m){if(h===0&&y===""){let x=e.substring(p,t).trim();x&&!x.match(/[+\-*/()]/)&&(y=x);}let f={isInsideAggregation:true,aggregationDepth:1,functionName:s,argumentIndex:h,firstArgument:y||void 0};c>i&&(i=c,a=f,console.log("[CONTEXT DEBUG] New best context at funcIndex",c,":",f));}l=c+1;}}return a?(console.log("[CONTEXT DEBUG] Returning best (innermost) context:",a),a):(console.log("[CONTEXT DEBUG] Returning default context (not inside aggregation)"),r)}function w9(e,t,r){return t.isInsideAggregation?e.filter(n=>x9(n,r)):e.filter(n=>G0(n,r))}function Z0(e,t,r,n){let o=_a(e,t);return w9(r,o,n||"")}var S9={SUM:2,AVERAGE:2,MIN:2,MAX:2,COUNT:2,LOOKUP:6,MATCH:5,FILTER:4,FLATTEN:2,CONCAT:-1,ABS:1,SQRT:1,LOG:2,POW:2,IF:3,NOT:1,GT:2,GTE:2,LT:2,LTE:2};function Hl(e,t="",r="",n){let o=[];if(!e)return o;let a=n||e;if(e.type==="object"&&e.properties)for(let[i,s]of Object.entries(e.properties)){let l=t?`${t}.${i}`:i,c=Ut(s,a);if(c.type!=="object"&&c.type!=="array")o.push(l);else if(c.type==="object")o.push(...Hl(c,l,r,a));else if(c.type==="array"&&c.items){o.push(l);let u=Ut(c.items,a);if(u.type==="object"){let d=Hl(u,`${l}.*`,r,a);o.push(...d);}else o.push(`${l}.*`);}}return o}function N9(e){return {SUM:{arguments:[{name:"array"},{name:"field",optional:true}],description:"Sum array values",example:"SUM(items, price)"},AVERAGE:{arguments:[{name:"array"},{name:"field",optional:true}],description:"Calculate average of array values",example:"AVERAGE(items, score)"},MIN:{arguments:[{name:"array or values"},{name:"field",optional:true}],description:"Find minimum value in array or among multiple values",example:"MIN(items, price) or MIN(10, 20, 30)"},MAX:{arguments:[{name:"array or values"},{name:"field",optional:true}],description:"Find maximum value in array or among multiple values",example:"MAX(items, price) or MAX(10, 20, 30)"},FILTER:{arguments:[{name:"array"},{name:"field"},{name:"operator"},{name:"value"}],description:"Filter array by condition, returning matching elements",example:'FILTER(items, price, ">", 100)'},FLATTEN:{arguments:[{name:"array"},{name:"field",optional:true}],description:"Flatten nested arrays or extract and flatten field from array elements",example:'FLATTEN(nested_arrays) or FLATTEN(groups, "items")'},LOOKUP:{arguments:[{name:"array"},{name:"field"},{name:"operator"},{name:"value"},{name:"projection",optional:true},{name:"mode",optional:true}],description:"Find first matching element in array",example:'LOOKUP(items, id, "=", 5, name)'},MATCH:{arguments:[{name:"array"},{name:"field"},{name:"operator"},{name:"value"},{name:"mode",optional:true}],description:"Find index of first matching element (0-based)",example:'MATCH(items, status, "=", "active")'},COUNT:{arguments:[{name:"array"},{name:"value"}],description:"Count occurrences of a value in an array",example:'COUNT(items, "completed")'},IF:{arguments:[{name:"condition"},{name:"value_if_true"},{name:"value_if_false"}],description:"Conditional - returns value based on condition",example:'IF(price > 100, "expensive", "affordable")'},CONCAT:{arguments:[{name:"values..."}],description:"Concatenate multiple values as strings",example:'CONCAT("Hello ", name, "!")'},ABS:{arguments:[{name:"value"}],description:"Return absolute value",example:"ABS(-10)"},SQRT:{arguments:[{name:"value"}],description:"Return square root",example:"SQRT(25)"},LOG:{arguments:[{name:"value"},{name:"base",optional:true}],description:"Return logarithm (natural log or custom base)",example:"LOG(100, 10)"},POW:{arguments:[{name:"base"},{name:"exponent"}],description:"Raise base to exponent power",example:"POW(2, 3)"},NOT:{arguments:[{name:"value"}],description:"Logical NOT operation",example:"NOT(condition)"},GT:{arguments:[{name:"left"},{name:"right"}],description:"Greater than comparison",example:"GT(price, 100)"},GTE:{arguments:[{name:"left"},{name:"right"}],description:"Greater than or equal comparison",example:"GTE(quantity, 10)"},LT:{arguments:[{name:"left"},{name:"right"}],description:"Less than comparison",example:"LT(age, 18)"},LTE:{arguments:[{name:"left"},{name:"right"}],description:"Less than or equal comparison",example:"LTE(score, 100)"}}[e]||null}function zp(e,t){let r=t,n=t;for(;r>0;){let o=e[r-1];if(/[a-zA-Z0-9_.]/.test(o))r--;else if(o==="*"&&r>=2&&e[r-2]===".")r--;else break}for(;n<e.length;){let o=e[n];if(/[a-zA-Z0-9_]/.test(o))n++;else if(o==="."&&n+1<e.length)n++,e[n]==="*"&&n++;else break}return {word:e.substring(r,n),start:r,end:n}}function Up(e,t,r,n,o="",a=0){let i=[],s=e.toLowerCase();function l(g,v){let w=Ut(g,g);if(!w)return null;let N=v.split(".");for(let S of N){if(!w)return null;let _=Ut(w,g);if(S==="*")if(_&&_.type==="array"&&_.items)w=Ut(_.items,g);else return null;else if(_&&_.type==="object"&&_.properties&&_.properties[S])w=Ut(_.properties[S],g);else return null}return w}function c(g,v){if(!g)return null;let w=Ut(g,v),N=w?.type,S=P=>{let R=Ut(P,v),E=R?.type;if(Array.isArray(E)&&E.length>0)return E.join("|");if(E==="array"){let C=R?.items;return `array<${(C?S(C):null)??"any"}>`}return E==="object"?"object":E==="string"?typeof R?.format=="string"&&R.format.length>0?R.format:Array.isArray(R?.enum)?"enum":"string":E==="number"||E==="integer"||E==="boolean"||E==="null"?E:Array.isArray(R?.enum)?"enum":null},_=w?.anyOf||w?.oneOf;if(Array.isArray(_)&&_.length>0){let P=Array.from(new Set(_.map(R=>S(R)).filter(Boolean)));if(P.length>0)return P.join("|")}if(Array.isArray(N)&&N.length>0)return N.join("|");if(N==="array"){let P=w?.items;return `array<${(P?S(P):null)??"any"}>`}return typeof N=="string"&&N.length>0?N==="string"&&typeof w?.format=="string"&&w.format.length>0?w.format:N:w?.enum?"enum":null}let u=_a(o,a);console.log("[AUTOCOMPLETE DEBUG] Context:",{formula:o,cursorPosition:a,functionName:u.functionName,argumentIndex:u.argumentIndex,isInsideAggregation:u.isInsideAggregation,firstArgument:u.firstArgument});let d=u.functionName&&(u.functionName==="SUM"||u.functionName==="AVERAGE"||u.functionName==="FILTER"||u.functionName==="LOOKUP"||u.functionName==="MATCH"||u.functionName==="FLATTEN")&&u.argumentIndex===0,m=u.functionName&&(u.functionName==="FILTER"&&u.argumentIndex===2||u.functionName==="MATCH"&&u.argumentIndex===2||u.functionName==="LOOKUP"&&u.argumentIndex===2),h=u.functionName&&(u.functionName==="FILTER"&&u.argumentIndex===3||u.functionName==="MATCH"&&u.argumentIndex===3||u.functionName==="LOOKUP"&&u.argumentIndex===3),y=u.functionName&&((u.functionName==="SUM"||u.functionName==="AVERAGE"||u.functionName==="MIN"||u.functionName==="MAX")&&u.argumentIndex===1||u.functionName==="FLATTEN"&&u.argumentIndex===1||u.functionName==="LOOKUP"&&u.argumentIndex===4||(u.functionName==="FILTER"||u.functionName==="MATCH")&&u.argumentIndex===1);if(m){let g=[{value:'"="',display:"=",description:"Equal to"},{value:'"!="',display:"!=",description:"Not equal to"},{value:'">"',display:">",description:"Greater than"},{value:'">="',display:">=",description:"Greater than or equal to"},{value:'"<"',display:"<",description:"Less than"},{value:'"<="',display:"<=",description:"Less than or equal to"},{value:'"contains"',display:"contains",description:"Contains substring (case-insensitive)"}];for(let v of g)(v.display.toLowerCase().includes(s)||v.value.toLowerCase().includes(s))&&i.push({value:v.value,display:v.display,category:"operator",description:v.description});return i}if(h&&u.firstArgument){let g=u.firstArgument.replace(/['"]/g,"").trim(),v=new RegExp(`${u.functionName}\\s*\\(\\s*[^,]+,\\s*([^,]+)`,"i"),w=o.match(v);if(w&&w[1]){let N=w[1].replace(/['"]/g,"").trim();console.log("[AUTOCOMPLETE DEBUG] Value arg - checking for enum:",{arrayPath:g,keyField:N});let S=l(t,g);if(S&&S.type==="array"&&S.items){let _=Ut(S.items,t);if(_&&_.type==="object"&&_.properties){let P=l(_,N);if(P){let R=Ut(P,t),E=[];if(Array.isArray(R?.enum))E=R.enum;else if(Array.isArray(R?.anyOf))for(let C of R.anyOf){let b=Ut(C,t);Array.isArray(b?.enum)&&E.push(...b.enum);}else if(Array.isArray(R?.oneOf))for(let C of R.oneOf){let b=Ut(C,t);Array.isArray(b?.enum)&&E.push(...b.enum);}if(E=Array.from(new Set(E.filter(C=>C!=null))),console.log("[AUTOCOMPLETE DEBUG] Found enum values:",E),E.length>0){for(let C of E){let b=String(C);b.toLowerCase().includes(s)&&i.push({value:`"${b}"`,display:b,category:"field",description:"Enum value",typeBadge:"enum"});}return i}}}}}return []}if(!d&&!m&&!h&&!y){let g=[{value:"SUM",display:"SUM()",description:"Sum array values: SUM(arrayPath, [fieldPath])"},{value:"AVERAGE",display:"AVERAGE()",description:"Calculate average of array values: AVERAGE(arrayPath, [fieldPath])"},{value:"MIN",display:"MIN()",description:"Find the minimum value in an array: MIN(arrayPath, [fieldPath])"},{value:"MAX",display:"MAX()",description:"Find the maximum value in an array: MAX(arrayPath, [fieldPath])"},{value:"COUNT",display:"COUNT",description:"Count occurrences of a value in an array"},{value:"LOOKUP",display:"LOOKUP()",description:"Find first matching element: LOOKUP(arrayPath, keyField, comparator, value, [projection], [mode])"},{value:"MATCH",display:"MATCH()",description:"Find index of first matching element: MATCH(arrayPath, keyField, comparator, value, [mode])"},{value:"FILTER",display:"FILTER()",description:"Filter array by condition: FILTER(arrayPath, keyField, comparator, value)"},{value:"FLATTEN",display:"FLATTEN()",description:"Flatten nested arrays: FLATTEN(arrayPath) or FLATTEN(arrayPath, fieldPath)"},{value:"CONCAT",display:"CONCAT()",description:"Concatenate multiple values"},{value:"ABS",display:"ABS()",description:"Return the absolute value of a number or array"},{value:"SQRT",display:"SQRT()",description:"Return the square root of a number or array"},{value:"LOG",display:"LOG()",description:"Return the natural logarithm (or logarithm with custom base) of a number or array"},{value:"POW",display:"POW()",description:"Raise base to exponent (base^exponent)"},{value:"IF",display:"IF()",description:"Conditional - returns value_if_true if condition is truthy, otherwise value_if_false"},{value:"NOT",display:"NOT()",description:"Logical NOT - returns true if operand is falsy, false if truthy"},{value:"GT",display:"GT()",description:"Compare two values - returns true if first is greater than second"},{value:"GTE",display:"GTE()",description:"Compare two values - returns true if first is greater than or equal to second"},{value:"LT",display:"LT()",description:"Compare two values - returns true if first is less than second"},{value:"LTE",display:"LTE()",description:"Compare two values - returns true if first is less than or equal to second"}];for(let v of g)v.value.toLowerCase().includes(s)&&i.push({value:v.value,display:v.display,category:"function",description:v.description});}let p=Hl(t,"",n,t),f=[];if(d){console.log("[AUTOCOMPLETE DEBUG] First array arg filtering:"),console.log(" Target path:",n);let g=n.split(".*").length-1;console.log(" Target path level:",g),console.log(" All field paths count:",p.length),f=p.filter(v=>{let w=l(t,v),N=w&&w.type==="array",S=v.split(".*").length-1,_=S<=g;return console.log(` Path: ${v}, level: ${S}, isArray: ${N}, nodeType: ${w?.type}, isAtSameLevelOrHigher: ${_}`),N&&_}),console.log(" Final paths to suggest:",f);}else u.functionName==="MIN"||u.functionName==="MAX"?(console.log("[AUTOCOMPLETE DEBUG] MIN/MAX filtering - showing all paths at same level or higher"),f=p.filter(g=>G0(g,n))):f=Z0(o,a,p,n);let x=null;if(y)if(console.log("[AUTOCOMPLETE DEBUG] Projection/KeyField arg filtering:"),console.log(" isProjectionArg:",y),console.log(" functionName:",u.functionName),console.log(" detailedContext.firstArgument:",u.firstArgument),console.log(" detailedContext.argumentIndex:",u.argumentIndex),u.firstArgument){let g=u.firstArgument.replace(/['"]/g,"").trim();if(g.startsWith("FLATTEN")&&g.includes("(")){let v=g.indexOf("("),w=0,N=-1;for(let S=v;S<g.length&&(g[S]==="("?w++:g[S]===")"?w--:g[S]===","&&w===1&&N===-1&&(N=S),w!==0);S++);if(N>-1){let S=g.substring(v+1,N).trim(),_=g.length-1;w=0;for(let b=v;b<g.length;b++)if(g[b]==="(")w++;else if(g[b]===")"&&(w--,w===0)){_=b;break}let P=g.substring(N+1,_).trim(),R=S,E=S.match(/^(FILTER|LOOKUP|MATCH)\s*\(\s*([^,]+)/i);E&&E[2]&&(R=E[2].trim()),console.log(" Detected FLATTEN with field:",P,"from array:",R);let C=l(t,R);if(C&&C.type==="array"&&C.items){let b=Ut(C.items,t),O=l(b,P);if(O&&O.type==="array"&&O.items){let D=Ut(O.items,t);if(D&&D.type==="object"&&D.properties){let k=[];for(let[I,F]of Object.entries(D.properties)){let Z=Ut(F,t);if(Z.type!=="object"&&Z.type!=="array")k.push(I);else if(Z.type==="object"){let pe=Hl(Z,I,"",t);k.push(...pe);}}console.log(" FLATTEN result field paths:",k),f=k,x=D,g="";}}}}}if(g&&g!==""){let v=g.match(/^(FILTER|LOOKUP|MATCH)\s*\(\s*([^,]+)/i);v&&v[2]&&(g=v[2].trim(),console.log(" Extracted array path from function call:",g));}if(console.log(" arrayPath:",g),g&&g!==""){let v=l(t,g);if(console.log(" arraySchema type:",v?.type),v&&v.type==="array"&&v.items){let w=Ut(v.items,t);if(console.log(" itemsSchema type:",w?.type),w&&w.type==="object"&&w.properties){let N=[],S=u.functionName==="FLATTEN"&&u.argumentIndex===1;for(let[_,P]of Object.entries(w.properties)){let R=Ut(P,t);if(S)R.type==="array"&&N.push(_);else if(R.type!=="object"&&R.type!=="array")N.push(_);else if(R.type==="object"){let E=Hl(R,_,"",t);N.push(...E);}}console.log(" itemFieldPaths:",N),f=N,x=w;}}}}else console.log(" No firstArgument captured!");console.log("[AUTOCOMPLETE DEBUG] Final pathsToSuggest before building suggestions:",f),console.log("[AUTOCOMPLETE DEBUG] isProjectionArg:",y,"isFirstArrayArg:",d);for(let g of f)if(g.toLowerCase().includes(s)){let v=x||t,w=l(v,g),N=c(w,v)||void 0;i.push({value:g,display:g,category:"field",description:"Schema field",typeBadge:N});}if(!d&&!m&&!h&&!y){let g=r.filter(w=>w!==n),v=Z0(o,a,g,n);for(let w of v)w.toLowerCase().includes(s)&&i.push({value:w,display:w,category:"computed",description:"Computed field"});}return i.sort((g,v)=>{let w={field:1,computed:2,function:3,operator:4},N=w[g.category]||999,S=w[v.category]||999;if(N!==S)return N-S;let _=g.value.toLowerCase(),P=v.value.toLowerCase();if(_===s)return -1;if(P===s)return 1;let R=_.startsWith(s),E=P.startsWith(s);return R&&!E?-1:!R&&E?1:g.value.localeCompare(v.value)}),i.slice(0,10)}function C9(e,t,r,n){if(!e)return [];let o=Hl(t,"",n,t),a=new Set([...o,...r.filter(i=>i!==n)]);try{let s=new es(e).tokenize(),l=[],c=0,u=[],d=0;for(let m=0;m<s.length;m++){let h=s[m];if(h.type==="EOF")break;h.type==="FUNCTION"?u.push({name:h.value,depth:d+1,argumentIndex:0}):h.type==="LPAREN"?d++:h.type==="RPAREN"?(d--,u.length>0&&u[u.length-1].depth>d&&u.pop()):h.type==="COMMA"&&u.length>0&&u[u.length-1].depth===d&&u[u.length-1].argumentIndex++;let y="",p=c;if(h.type==="STRING"){for(;p<e.length&&e[p]!=='"'&&e[p]!=="'";)p++;let x=e[p],g=p+1;for(;g<e.length;)if(e[g]==="\\")g+=2;else if(e[g]===x){g++;break}else g++;y=e.substring(p,g);}else {let x=h.value;p=e.indexOf(x,c),p===-1&&(p=c),y=e.substring(p,p+x.length);}if(p>c){let x=e.substring(c,p);l.push(jsx("span",{className:"text-xs text-gray-900 dark:text-gray-100",children:x},`ws-${m}`));}let f="text-xs text-gray-900 dark:text-gray-100";switch(h.type){case "NUMBER":f="text-xs text-amber-600 dark:text-amber-400";break;case "STRING":f="text-xs text-emerald-600 dark:text-emerald-400";break;case "BOOLEAN":f="text-xs text-green-600 dark:text-green-400";break;case "NULL":f="text-xs text-gray-500 dark:text-gray-500";break;case "FUNCTION":f="text-xs text-purple-600 dark:text-purple-400 font-semibold";break;case "IDENTIFIER":let x=!1;if(u.length>0){let g=u[u.length-1],v=g.name,w=g.argumentIndex;v==="SUM"||v==="AVERAGE"||v==="MIN"||v==="MAX"||v==="FLATTEN"?x=w===1:v==="LOOKUP"?x=w===1||w===2||w===4||w===5:(v==="MATCH"||v==="FILTER")&&(x=w===1||w===2||v==="MATCH"&&w===4);}a.has(h.value)?f="text-xs text-blue-600 dark:text-blue-400":x?f="text-xs text-cyan-600 dark:text-cyan-400":f="text-xs text-red-600 dark:text-red-400";break;case "PLUS":case "MINUS":case "MULTIPLY":case "DIVIDE":f="text-xs text-gray-600 dark:text-gray-400";break;case "LPAREN":case "RPAREN":case "COMMA":f="text-xs text-gray-500 dark:text-gray-500";break}l.push(jsx("span",{className:f,children:y},`token-${m}`)),c=p+y.length;}if(c<e.length){let m=e.substring(c);l.push(jsx("span",{className:"text-xs text-gray-900 dark:text-gray-100",children:m},"remaining"));}return l}catch{return [jsx("span",{className:"text-xs text-gray-900 dark:text-gray-100",children:e},"error")]}}function zC({value:e,onChange:t,onBlur:r,schema:n,computedFields:o,targetPath:a,placeholder:i,disabled:s=false}){let l=kt.useRef(null),c=kt.useRef(null),[u,d]=kt.useState(false),[m,h]=kt.useState([]),[y,p]=kt.useState(0),[f,x]=kt.useState(0),[g,v]=kt.useState({word:"",start:0,end:0}),[w,N]=kt.useState(false),[S,_]=kt.useState(_a("",0)),[P,R]=kt.useState(false);kt.useEffect(()=>{if(!l.current)return;let k=l.current.selectionStart||0;x(k);let I=zp(e,k);v(I);let F=_a(e,k);_(F);let Z=Up(I.word,n,o,a,e,k);h(Z),w&&Z.length>0?(d(true),p(0)):w&&Z.length===0&&d(false);},[e,n,o,a,w]);let E=k=>{if(!(k.key==="Enter"&&k.shiftKey)&&!(!u||m.length===0))switch(k.key){case "ArrowDown":k.preventDefault(),p(I=>Math.min(I+1,m.length-1));break;case "ArrowUp":k.preventDefault(),p(I=>Math.max(I-1,0));break;case "Tab":u&&m[y]&&(k.preventDefault(),C(m[y]));break;case "Enter":u&&m[y]&&(k.preventDefault(),C(m[y]));break;case "Escape":k.preventDefault(),d(false);break}},C=k=>{let I=e.substring(0,g.start),F=e.substring(g.end),Z=k.value,pe=false,ie=false;if(k.category==="function")k.value==="COUNT"?Z=`${k.value}(, "")`:Z=`${k.value}()`;else {let re=_a(e,f);if(re.functionName){let X=S9[re.functionName],$=re.argumentIndex??0,L=F.trimStart(),le=L.startsWith(")"),ae=L.startsWith(",");!le&&!ae&&(X===-1||$<X-1?ie=true:pe=true);}}let J=ie?", ":pe?")":"",ue=I+Z+J+F;t(ue),d(false),setTimeout(()=>{if(l.current)if(l.current.focus(),k.category==="function"){let re=I.length+Z.length-1;l.current.setSelectionRange(re,re);}else {let re=I.length+Z.length+J.length;l.current.setSelectionRange(re,re);}},0);},b=k=>{N(true),t(k.target.value);};kt.useEffect(()=>{let k=I=>{c.current&&!c.current.contains(I.target)&&l.current&&!l.current.contains(I.target)&&d(false);};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[]),kt.useEffect(()=>{if(u&&c.current){let k=c.current.children[y];k&&k.scrollIntoView({block:"nearest",behavior:"smooth"});}},[y,u]);let O=k=>{switch(k){case "function":return "text-blue-600 dark:text-blue-400";case "field":return "text-green-600 dark:text-green-400";case "computed":return "text-purple-600 dark:text-purple-400";default:return "text-gray-600 dark:text-gray-400"}},D=k=>{switch(k){case "function":return "fn";case "field":return "field";case "computed":return "calc";default:return ""}};return jsxs("div",{className:"relative",children:[jsx("div",{className:"absolute inset-0 pointer-events-none overflow-hidden rounded-md px-[13px] py-[9px]",style:{whiteSpace:"pre-wrap",wordWrap:"break-word"},children:jsx("div",{className:"text-xs font-mono leading-[1.0rem]",children:C9(e,n,o,a)})}),jsx(nn,{ref:l,value:e,onChange:b,onKeyDown:E,disabled:s,onKeyUp:k=>{if(["ArrowLeft","ArrowRight","Home","End"].includes(k.key)){let I=l.current?.selectionStart||0;x(I);let F=zp(e,I);v(F);let Z=_a(e,I);_(Z);let pe=Up(F.word,n,o,a,e,I);h(pe),w&&pe.length>0&&(d(true),p(0));}else if(["ArrowUp","ArrowDown"].includes(k.key)&&!u){let I=l.current?.selectionStart||0;x(I);let F=zp(e,I);v(F);let Z=_a(e,I);_(Z);let pe=Up(F.word,n,o,a,e,I);h(pe),w&&pe.length>0&&(d(true),p(0));}},onClick:()=>{N(true);let k=l.current?.selectionStart||0;x(k);let I=zp(e,k);v(I);let F=_a(e,k);_(F);let Z=Up(I.word,n,o,a,e,k);Z.length>0&&(h(Z),d(true),p(0));},onBlur:()=>{setTimeout(()=>{d(false),N(false),r?.();},200);},placeholder:i,className:T("min-h-[80px] border-none rounded-none leading-[1.0rem] resize-y relative font-mono !text-xs caret-gray-900 dark:caret-gray-100","text-transparent"),spellCheck:false}),u&&m.length>0&&jsxs("div",{ref:c,className:"absolute z-50 w-full -px-4 mt-1 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg max-h-60 overflow-y-auto",children:[S.functionName&&(()=>{let k=N9(S.functionName);if(!k)return null;let I=S.argumentIndex||0;return jsxs("div",{className:"sticky top-0 bg-gray-50 dark:bg-gray-900/20 border-b border-gray-200 dark:border-gray-800",children:[jsxs("button",{type:"button",onMouseDown:F=>{F.preventDefault();},onClick:F=>{F.preventDefault(),F.stopPropagation(),R(!P);},className:"w-full px-3 py-2 text-left hover:bg-blue-100 dark:hover:bg-blue-900/30 transition-colors flex items-start gap-2",children:[jsx(ChevronDown,{className:T("w-4 h-4 text-gray-500 dark:text-gray-400 mt-0.5 transition-transform flex-shrink-0",P&&"transform rotate-180")}),jsx("div",{className:"flex-1 min-w-0",children:jsxs("div",{className:"font-mono text-xs flex flex-wrap items-center gap-1",children:[jsx("span",{className:"font-semibold text-purple-700 dark:text-purple-300",children:S.functionName}),jsx("span",{className:"text-gray-500",children:"("}),k.arguments.map((F,Z)=>jsxs(kt.Fragment,{children:[Z>0&&jsx("span",{className:"text-gray-500",children:","}),jsxs("span",{className:T("px-1 rounded",Z===I?"bg-gray-200 dark:bg-gray-700 font-bold text-gray-900 dark:text-gray-100":"text-gray-700 dark:text-gray-300"),children:[F.name,F.optional&&jsx("span",{className:"text-gray-400",children:"?"})]})]},Z)),jsx("span",{className:"text-gray-500",children:")"})]})})]}),P&&jsx("div",{className:"px-3 py-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-900/10",children:jsxs("div",{className:"text-xs space-y-2",children:[jsxs("div",{children:[jsx("span",{className:"font-semibold text-gray-700 dark:text-gray-300",children:"Description:"}),jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-0.5",children:k.description})]}),jsxs("div",{children:[jsx("span",{className:"font-semibold text-gray-700 dark:text-gray-300",children:"Example:"}),jsx("code",{className:"block mt-0.5 text-gray-600 dark:text-gray-400 bg-white dark:bg-gray-800 px-2 py-1 rounded",children:k.example})]})]})})]})})(),m.map((k,I)=>jsxs("div",{className:`
60
+ ${ke?"border-red-500":""}`,value:bt,onChange:q=>{let he=q.target.value;We(he),be(he?ww(he):null);},onBlur:Ln,onKeyDown:q=>{q.key==="Enter"&&Ln();},autoFocus:true}):jsxs("div",{className:"flex items-center",children:[jsx("span",{className:"font-medium text-gray-800 mr-1 cursor-pointer whitespace-nowrap",onClick:()=>{c&&gt(true);},children:e}),x==="$ref"&&ee.$ref&&jsx(K,{type:"button",variant:"ghost",size:"icon",className:"p-0 h-4 w-4",onClick:()=>{let q=ee.$ref?.replace("#/$defs/","");u&&u(true),setTimeout(()=>{let he=document.getElementById(`def-${q}`);he&&(he.scrollIntoView({behavior:"smooth"}),he.classList.add("bg-blue-100"),setTimeout(()=>he.classList.remove("bg-blue-100"),2500));},600);},children:jsx(EyeIcon,{className:"w-4 h-4 text-gray-400"})})]}),vt&&ke&&jsxs("p",{className:"text-xs text-red-500 flex items-center gap-1 mt-1 ml-1",children:[jsx(AlertCircle,{className:"w-3 h-3"})," ",ke]}),O["X-ReasoningPrompt"]&&jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(Atom,{className:"w-4 h-4 text-purple-300"})}),jsxs(ze,{className:"max-w-xs",children:[jsx("div",{className:"text-xs text-purple-300 mb-1",children:"Reasoning Prompt:"}),jsx("div",{className:"",children:O["X-ReasoningPrompt"]})]})]}),O.description&&jsx("div",{className:"flex items-center gap-1 flex-1 min-w-0",children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("div",{className:"truncate text-xs text-muted-foreground cursor-pointer hover:text-gray-600",onClick:()=>{H(e),Q(null),N(true);},children:O.description})}),jsxs(ze,{className:"max-w-xs",children:[jsx("div",{className:"text-xs text-blue-300 mb-1",children:"Description:"}),jsx("div",{className:"text-xs",children:O.description})]})]})})]}),jsxs("div",{className:"flex items-center gap-2",children:[C&&s&&jsx(K,{type:"button",variant:"ghost",size:"sm",className:"p-0 m-0 w-3 h-3",onClick:l,children:jsx(Trash2,{className:"w-1 h-1 text-white group-hover:text-muted-foreground"})}),!m&&jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(K,{type:"button",variant:"ghost",size:"icon",className:"p-0 m-0",onClick:()=>{H(e),Q(null),N(true);},children:jsx(Pencil,{className:"w-1 h-1 group-hover:opacity-100 opacity-0 text-gray-500"})})}),jsx(ze,{className:"max-w-xs",children:jsx("p",{children:"Edit field properties"})})]}),C&&jsx("div",{className:"flex items-center mt-2 sm:mt-0 opacity-0 group-hover:opacity-100",children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(No,{id:`${o}-nullable`,checked:!_,onCheckedChange:q=>$e(!q)})}),jsx(ze,{children:jsx("p",{children:"Required"})})]})}),C?jsxs(mr,{children:[jsx(hr,{asChild:true,children:jsxs(K,{variant:"ghost",className:"w-40 text-xs justify-between font-normal text-gray-500 pr-0",children:[jsxs("div",{className:"flex items-center gap-1",children:[yD(x,x==="$ref"&&ee.$ref?ee.$ref.replace("#/$defs/",""):void 0),jsx("span",{className:"",children:x==="$ref"&&ee.$ref?ee.$ref.replace("#/$defs/",""):x==="date"?"date":x==="time"?"time":x==="datetime"?"datetime":x==="boolean"?"true/false":x==="enum"?"multiple choice":x==="array"?"list":x||"Select type"})]}),jsx(ChevronDown,{className:"w-4 h-4 mx-2 group-hover:opacity-100 opacity-0 text-gray-500"})]})}),jsxs(gr,{children:[jsxs(we,{onSelect:()=>V("string"),children:[jsx(Type,{className:"w-4 h-4 mr-2"}),"string"]}),jsxs(we,{onSelect:()=>V("number"),children:[jsx(Hash,{className:"w-4 h-4 mr-2"}),"number"]}),jsxs(we,{onSelect:()=>V("integer"),children:[jsx(Hash,{className:"w-4 h-4 mr-2"}),"integer"]}),jsxs(we,{onSelect:()=>V("boolean"),children:[jsx(ToggleLeft,{className:"w-4 h-4 mr-2"}),"true/false"]}),jsxs(we,{onSelect:()=>V("enum"),children:[jsx(List,{className:"w-4 h-4 mr-2"}),"multiple choice"]}),jsxs(we,{onSelect:()=>V("object"),children:[jsx(Braces,{className:"w-4 h-4 mr-2"}),"object"]}),jsxs(we,{onSelect:()=>V("array"),children:[jsx(Brackets,{className:"w-4 h-4 mr-2"}),"list"]}),jsxs(we,{onSelect:()=>V("date"),children:[jsx(Calendar,{className:"w-4 h-4 mr-2"}),"date"]}),jsxs(we,{onSelect:()=>V("time"),children:[jsx(Clock,{className:"w-4 h-4 mr-2"}),"time"]}),jsxs(we,{onSelect:()=>V("datetime"),children:[jsx(CalendarClock,{className:"w-4 h-4 mr-2"}),"datetime"]}),jsxs(Xr,{children:[jsxs(Qr,{children:[jsx(Link,{className:"w-4 h-4 mr-4"}),"definition"]}),jsx(Ta,{children:jsx(Yr,{children:!i||Object.keys(i).length===0?jsxs(we,{onSelect:()=>{u&&(u(true),setTimeout(()=>{let q=document.getElementById("definitions-section");q&&(q.scrollIntoView({behavior:"smooth"}),q.style.backgroundColor="#dbeafe",setTimeout(()=>{q.style.backgroundColor="";},2500));},600));},children:[jsx(PlusIcon,{className:"w-4 h-4 mr-2"}),"Create a new definition to get started"]}):Object.keys(i).map(q=>jsxs(we,{onSelect:()=>{r(kt(t,{$ref:`#/$defs/${q}`}));},children:[dv(q),q]},q))})})]}),jsxs(Xr,{children:[jsxs(Qr,{children:[jsx(Shapes,{className:"w-4 h-4 mr-4"}),"object template"]}),jsx(Ta,{children:jsx(Yr,{children:Object.entries(sc).map(([q,he])=>jsxs(we,{className:"flex items-center gap-2",onSelect:()=>{let se=[q];he.deps&&se.push(...he.deps);let Qe={...n.$defs||{}};for(let mt of se)Qe[mt]||(Qe[mt]=sc[mt]);a({...n,$defs:Qe}),F(q);},children:[dv(q),q]},q))})})]})]})]}):jsx("div",{className:"w-40 text-xs ml-4",children:x==="$ref"&&ee.$ref?ee.$ref.replace("#/$defs/",""):x==="date"?"date":x==="time"?"time":x==="datetime"?"datetime":x==="boolean"?"true/false":x==="enum"?"multiple choice":x==="array"?"list":x||"string"})]})]}),x==="object"&&jsx("div",{className:o==="#"?"px-0":"pl-2",children:o==="#"?jsx(rd,{defaultValue:"properties",type:"single",collapsible:true,className:"w-full rounded-lg border border-gray-200 shadow-sm px-4 pb-0",children:jsxs(nd,{value:"properties",className:"border-none",children:[jsxs(ad,{className:"font-medium text-gray-400 text-sm",children:["Properties (",Object.keys(ee.properties||{}).length,")"]}),jsx(od,{className:"",children:jsxs("div",{className:"",children:[ee.properties&&Object.keys(ee.properties||{}).length>0&&Object.keys(ee.properties||{}).map(q=>{let he=(ee.properties||{})[q];return jsx("div",{className:"",draggable:C,onDragStart:se=>Lt(se,q),onDragOver:se=>At(se,q),onDragLeave:bu,onDrop:se=>vl(se,q),onDragEnd:xu,"data-prop-key":q,children:Qp(he)&&jsx(Oo,{draggedParentRef:d,draggedPropertyRef:g,editMode:f,name:q,node:he,jsonSchema:n,setJsonSchema:a,onChange:se=>{let Qe={...ee.properties||{},[q]:se},mt={...ee,properties:Qe};r(kt(t,mt));},onNameChange:se=>{if(se!==q){let Qe=fv(t,q,se,ee.properties?.[q]);r(kt(t,Qe));}},path:`${o}.${q}`,defs:i,canDelete:true,onDelete:()=>{let se={...ee.properties};delete se[q];let Qe=Array.isArray(ee.required)?ee.required.filter(Ir=>Ir!==q):[],mt={...ee,properties:se,required:Qe};r(kt(t,mt));},setDefsAccordionOpen:u})},q)}),C&&jsxs("div",{className:"flex flex-col gap-1 mt-3 ml-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx(Ze,{placeholder:"New property name",className:`w-40 ${ie?"border-red-500":""}`,value:j,onChange:q=>{let he=q.target.value;ue(he),Ce(he?Ci(he,Object.keys(ee.properties||[]),void 0,"property"):null);},onKeyDown:q=>{if(q.key==="Enter"&&j.trim()){let he=cc("string");he.title=Ya(j);let se={...ee.properties||{},[j]:he},Qe=Array.isArray(ee.required)?[...ee.required,j]:[j],mt={...ee,properties:se,required:Qe};r(kt(t,mt)),ue("");}}}),jsxs(K,{type:"button",variant:"outline",size:"sm",disabled:!!ie||!j.trim(),className:ie||!j.trim()?"cursor-not-allowed":"",onClick:()=>{let q=Ci(j,Object.keys(ee.properties||[]),void 0,"property");if(q){Ce(q);return}let he=cc("string");he.title=Ya(j);let se={...ee.properties||{},[j]:he},Qe=Array.isArray(ee.required)?[...ee.required,j]:[j],mt={...ee,properties:se,required:Qe};r(kt(t,mt)),ue("");},children:[jsx(PlusIcon,{className:"w-4 h-4"}),jsx("span",{children:"Add"})]})]}),ie&&jsxs("p",{className:"text-xs text-red-500 flex items-center gap-1",children:[jsx(AlertCircle,{className:"w-3 h-3"})," ",ie]})]})]})})]})}):jsxs("div",{className:"",children:[ee.properties&&Object.keys(ee.properties||{}).length>0&&Object.keys(ee.properties||{}).map(q=>{let he=(ee.properties||{})[q];return jsx("div",{className:"ml-4 border-l border-gray-200",draggable:C,onDragStart:se=>Lt(se,q),onDragOver:se=>At(se,q),onDragLeave:bu,onDrop:se=>vl(se,q),onDragEnd:xu,"data-prop-key":q,children:Qp(he)&&jsx(Oo,{draggedParentRef:d,name:q,draggedPropertyRef:g,editMode:f,node:he,onChange:se=>{let Qe={...ee.properties||{},[q]:se},mt={...ee,properties:Qe};r(kt(t,mt));},jsonSchema:n,setJsonSchema:a,onNameChange:se=>{if(se!==q){let Qe=fv(t,q,se,ee.properties?.[q]);r(kt(t,Qe));}},path:`${o}.${q}`,defs:i,canDelete:true,onDelete:()=>{let se={...ee.properties};delete se[q];let Qe=Array.isArray(ee.required)?ee.required.filter(Ir=>Ir!==q):[],mt={...ee,properties:se,required:Qe};r(kt(t,mt));},setDefsAccordionOpen:u})},q)}),C&&jsxs("div",{className:"flex items-center gap-3 mt-2 ml-4 pl-4 border-l border-gray-200",children:[jsx(Ze,{placeholder:"New property name",className:"w-40",value:j,onChange:q=>ue(q.target.value),onKeyDown:q=>{if(q.key==="Enter"&&j.trim()){let he=cc("string");he.title=Ya(j);let se={...ee.properties||{},[j]:he},Qe=Array.isArray(ee.required)?[...ee.required,j]:[j],mt={...ee,properties:se,required:Qe};r(kt(t,mt)),ue("");}}}),jsxs(K,{type:"button",variant:"outline",size:"sm",onClick:()=>{if(!j.trim())return;let q=cc("string");q.title=Ya(j);let he={...ee.properties||{},[j]:q},se=Array.isArray(ee.required)?[...ee.required,j]:[j],Qe={...ee,properties:he,required:se};r(kt(t,Qe)),ue("");},children:[jsx(PlusIcon,{className:"w-4 h-4"}),jsx("span",{children:"Add"})]})]})]})}),x==="array"&&jsx("div",{className:"ml-4",children:jsx("div",{className:"ml-4 border-l border-gray-200",children:(()=>{let q=As(t).items;return q!==void 0&&!Array.isArray(q)&&Qp(q)&&jsx(Oo,{draggedParentRef:d,draggedPropertyRef:g,editMode:f,name:"items",node:q,onChange:se=>r(kt(t,{...ee,items:se})),jsonSchema:n,setJsonSchema:a,path:`${o}.items`,defs:i,canDelete:false,hidePencilButton:true,setDefsAccordionOpen:u})})()})}),x==="enum"&&jsxs("div",{className:"ml-6",children:[jsx(nr,{className:"text-gray-400 font-normal",children:"Possible values"}),ee.enum&&ee.enum.length>0?jsx("ul",{className:"mb-2 flex flex-wrap gap-2 mt-1",children:ee.enum.map((q,he)=>jsxs("li",{className:"flex items-center space-x-2 border-gray-200 border rounded-md px-2 py-1 bg-slate-50",children:[jsx(Ze,{value:q,ref:he===0?ye:void 0,onChange:se=>{Be(he,se.target.value);},className:"h-6 w-24 px-1 shadow-none bg-transparent border-0 focus-visible:ring-0 focus-visible:ring-offset-0"}),jsx(K,{type:"button",variant:"ghost",className:"p-1 m-0 w-3 h-3",size:"icon",onClick:()=>te(he),children:jsx(X,{className:"w-2 h-2"})})]},he))}):jsx("div",{className:"mb-2 text-sm text-gray-500",children:"No enum values defined."}),jsxs("div",{className:"flex items-center gap-3",children:[jsx(Ze,{ref:ge,placeholder:"New enum value",className:"w-40",value:re,onChange:q=>me(q.target.value),onKeyDown:q=>{q.key==="Enter"&&re.trim()&&an();}}),jsxs(K,{type:"button",variant:"outline",size:"sm",onClick:an,children:[jsx(PlusIcon,{className:"w-4 h-4"}),jsx("span",{children:"Add"})]})]})]}),o!=="#"&&jsx(MC,{isOpen:T,onClose:()=>N(false),path:o,propertyName:X$1,setPropertyName:H,metadataValues:O,setMetadataValues:$,nameError:L,setNameError:Q,showReasoningPromptField:Z,setShowReasoningPromptField:W,validateName:z,onChange:r,onNameChange:c||(()=>{}),onDelete:C&&s?()=>{l&&(l(),N(false));}:void 0,node:t,name:e,localType:x,editMode:f}),jsx(BC,{isOpen:S,onClose:()=>b(false),onConfirm:Re,onCancel:Ee})]})}function vL({schema:e,onChange:t,accordionOpen:r,setAccordionOpen:n,draggedParentRef:a,draggedPropertyRef:o,editMode:i="editable"}){let s=e.$defs||{},[l,c]=useState(""),[u,d]=useState(false),g=i==="editable",f=()=>{if(!l.trim())return;let p={...s,[l]:{type:"object",properties:{},required:[]}};t({...e,$defs:p}),c("");},h=p=>{let v=`#/$defs/${p}`,y=x=>{if(x===null||typeof x!="object")return false;if(Array.isArray(x)){for(let w of x)if(y(w))return true;return false}if(x.$ref===v)return true;if(x===e&&e.$defs&&typeof e.$defs=="object"){for(let[E,C]of Object.entries(e.$defs))if(E!==p&&y(C))return true;let{$defs:w,..._}=e;return y(_)}for(let w of Object.keys(x))if(w!=="$defs"&&y(x[w]))return true;return false};return y(e)},m=p=>{if(h(p)){toast.error(`Cannot delete "${p}" because it is referenced by one or more $ref properties. Remove or update those references first.`);return}let v={...s};delete v[p],t({...e,$defs:v}),Object.keys(v).length===0&&d(false);};return Object.keys(s).length===0&&!u?i==="promptOnly"?null:jsx("div",{className:"mt-6 flex pb-4",children:jsx("div",{className:"rounded-md",id:"definitions-section",children:jsxs(K,{type:"button",variant:"outline",onClick:()=>{d(true),n(true);},className:"bg-transparent rounded-md transition-colors duration-300",children:[jsx(PlusIcon,{className:"w-4 h-4 mr-2"}),"Add definition"]})})}):jsx(rd,{className:"w-full mt-6 rounded-lg border border-gray-200 shadow-sm px-4 pb-0",type:"single",collapsible:false,value:"defs",children:jsxs(nd,{value:"defs",className:"bg-transparent border-none",children:[jsx(ad,{className:"text-gray-400 font-medium bg-transparent",children:jsxs("div",{className:"flex items-center",children:["Definitions (",Object.keys(s).length,")"]})}),jsx(od,{className:"pt-2 bg-transparent",children:jsxs("div",{className:"space-y-4",children:[Object.keys(s).length===0&&jsx("p",{className:"text-sm text-muted-foreground",children:"Create reusable schema components to avoid duplication with a new definition."}),Object.entries(s).map(([p,v])=>jsx("div",{className:" py-2",id:`def-${p}`,children:jsx(Oo,{draggedParentRef:a,draggedPropertyRef:o,editMode:i,name:p,node:v,onChange:y=>{let x={...s,[p]:y};t({...e,$defs:x});},onNameChange:y=>{if(y!==p){let x={...s};x[y]=v,delete x[p];let w=E=>{if(typeof E!="object"||E===null)return E;if(Array.isArray(E))return E.map(w);let C={...E};return C.$ref===`#/$defs/${p}`&&(C.$ref=`#/$defs/${y}`),Object.keys(C).forEach(P=>{P!=="$ref"&&(C[P]=w(C[P]));}),C},_=w({...e,$defs:x});t(_);}},jsonSchema:e,setJsonSchema:t,path:`#/$defs/${p}`,defs:s,canDelete:!h(p),onDelete:()=>m(p),setDefsAccordionOpen:n})},p)),g&&jsxs("div",{className:"flex items-center gap-3",children:[jsx(Ze,{placeholder:"New definition name",className:"w-40",value:l,onChange:p=>c(p.target.value)}),jsxs(K,{type:"button",variant:"outline",size:"sm",onClick:f,className:"p-1!",children:[jsx(PlusIcon,{className:"w-4 h-4"}),jsx("span",{className:"ml-1",children:"Add Definition"})]})]})]})})]})})}function bL({fullCodeModeState:e,editMode:t="editable",setDisplayEvanescentButtons:r,onSchemaFixWithAI:n}){let[a,o]=useState(false),[i,s]=e||[a,o],{jsonSchema:l,setJsonSchema:c,validationErrors:u}=Ka(),[d,g]=useState(false),[f,h]=Rt.useState(false),m=Rt.useRef(null),p=Rt.useRef(null),{selectedFieldPath:v}=Ni();Rt.useEffect(()=>{if(v)try{let x=N=>{if(N&&Array.isArray(N.anyOf)){let S=N.anyOf.find(b=>typeof b=="object"&&(b.type!=="null"||b.$ref||b.enum));return S&&typeof S=="object"?S:N}return N},_=v.split(".")[0],C=x(l)?.properties?.[_],P=x(C),T=!1;if(P&&typeof P=="object"){if(P.$ref)T=!0;else if(P.type==="array"){let N=Array.isArray(P.items)?P.items[0]:P.items,S=x(N||{});S&&S.$ref&&(T=!0);}}T&&!d&&g(!0);}catch{}},[v,l,d]);let y=x=>{g(x);};return jsxs("div",{className:"flex-1 min-h-0 flex flex-col w-full overflow-y-auto",children:[jsxs("div",{className:`group flex flex-col w-full ${i?"h-full":""}`,children:[jsx(ZC,{validationErrors:u,variant:"full",showFixButton:!!n,onSchemaFixWithAI:n}),i?jsx(Editor,{language:"json",theme:"vs-dark",className:"flex-1 min-h-0 h-full rounded-lg overflow-hidden",value:JSON.stringify(l,null,2),options:{automaticLayout:true},onChange:async x=>{try{let w=JSON.parse(x||"");await c(w);}catch{}}}):jsx(yL,{onChange:c,setDisplayEvanescentButtons:r,node:l,editMode:t,setOpenLayoutDialog:h})]}),!i&&jsxs("div",{className:"pb-20 flex-1 min-h-0 flex flex-col",children:[jsx(Oo,{name:"root",node:l,onChange:c,jsonSchema:l,setJsonSchema:c,path:"#",defs:l.$defs||{},editMode:t,canDelete:false,setDefsAccordionOpen:y,draggedParentRef:m,draggedPropertyRef:p,setDisplayEvanescentButtons:r}),jsx(vL,{editMode:t,schema:l,onChange:c,accordionOpen:d,setAccordionOpen:y,draggedParentRef:m,draggedPropertyRef:p})]})]})}Rt.memo(bL);var bc={};CD(bc,{BRAND:()=>HL,DIRTY:()=>Is,EMPTY_PATH:()=>SL,INVALID:()=>Oe,NEVER:()=>T9,OK:()=>qr,ParseStatus:()=>kr,Schema:()=>tt,ZodAny:()=>Ti,ZodArray:()=>Io,ZodBigInt:()=>Ms,ZodBoolean:()=>js,ZodBranded:()=>gd,ZodCatch:()=>Gs,ZodDate:()=>Ls,ZodDefault:()=>Ks,ZodDiscriminatedUnion:()=>nm,ZodEffects:()=>ra,ZodEnum:()=>Js,ZodError:()=>vn,ZodFirstPartyTypeKind:()=>Ie,ZodFunction:()=>om,ZodIntersection:()=>qs,ZodIssueCode:()=>ne,ZodLazy:()=>Vs,ZodLiteral:()=>Hs,ZodMap:()=>hc,ZodNaN:()=>yc,ZodNativeEnum:()=>Ws,ZodNever:()=>Da,ZodNull:()=>zs,ZodNullable:()=>no,ZodNumber:()=>Fs,ZodObject:()=>bn,ZodOptional:()=>ea,ZodParsedType:()=>pe,ZodPipeline:()=>yd,ZodPromise:()=>ki,ZodReadonly:()=>Zs,ZodRecord:()=>am,ZodSchema:()=>tt,ZodSet:()=>gc,ZodString:()=>Pi,ZodSymbol:()=>pc,ZodTransformer:()=>ra,ZodTuple:()=>ro,ZodType:()=>tt,ZodUndefined:()=>Bs,ZodUnion:()=>Us,ZodUnknown:()=>$o,ZodVoid:()=>mc,addIssueToContext:()=>le,any:()=>e9,array:()=>a9,bigint:()=>GL,boolean:()=>im,coerce:()=>P9,custom:()=>_E,date:()=>ZL,datetimeRegex:()=>xE,defaultErrorMap:()=>Do,discriminatedUnion:()=>s9,effect:()=>b9,enum:()=>g9,function:()=>p9,getErrorMap:()=>uc,getParsedType:()=>to,instanceof:()=>WL,intersection:()=>l9,isAborted:()=>tm,isAsync:()=>dc,isDirty:()=>rm,isValid:()=>Ei,late:()=>JL,lazy:()=>m9,literal:()=>h9,makeIssue:()=>hd,map:()=>d9,nan:()=>KL,nativeEnum:()=>y9,never:()=>r9,null:()=>YL,nullable:()=>w9,number:()=>SE,object:()=>gv,objectUtil:()=>pv,oboolean:()=>E9,onumber:()=>C9,optional:()=>x9,ostring:()=>N9,pipeline:()=>S9,preprocess:()=>_9,promise:()=>v9,quotelessJson:()=>xL,record:()=>u9,set:()=>f9,setErrorMap:()=>_L,strictObject:()=>o9,string:()=>vc,symbol:()=>XL,transformer:()=>b9,tuple:()=>c9,undefined:()=>QL,union:()=>i9,unknown:()=>t9,util:()=>it,void:()=>n9});var it;(function(e){e.assertEqual=a=>{};function t(a){}e.assertIs=t;function r(a){throw new Error}e.assertNever=r,e.arrayToEnum=a=>{let o={};for(let i of a)o[i]=i;return o},e.getValidEnumValues=a=>{let o=e.objectKeys(a).filter(s=>typeof a[a[s]]!="number"),i={};for(let s of o)i[s]=a[s];return e.objectValues(i)},e.objectValues=a=>e.objectKeys(a).map(function(o){return a[o]}),e.objectKeys=typeof Object.keys=="function"?a=>Object.keys(a):a=>{let o=[];for(let i in a)Object.prototype.hasOwnProperty.call(a,i)&&o.push(i);return o},e.find=(a,o)=>{for(let i of a)if(o(i))return i},e.isInteger=typeof Number.isInteger=="function"?a=>Number.isInteger(a):a=>typeof a=="number"&&Number.isFinite(a)&&Math.floor(a)===a;function n(a,o=" | "){return a.map(i=>typeof i=="string"?`'${i}'`:i).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(a,o)=>typeof o=="bigint"?o.toString():o;})(it||(it={}));var pv;(function(e){e.mergeShapes=(t,r)=>({...t,...r});})(pv||(pv={}));var pe=it.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),to=e=>{switch(typeof e){case "undefined":return pe.undefined;case "string":return pe.string;case "number":return Number.isNaN(e)?pe.nan:pe.number;case "boolean":return pe.boolean;case "function":return pe.function;case "bigint":return pe.bigint;case "symbol":return pe.symbol;case "object":return Array.isArray(e)?pe.array:e===null?pe.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?pe.promise:typeof Map<"u"&&e instanceof Map?pe.map:typeof Set<"u"&&e instanceof Set?pe.set:typeof Date<"u"&&e instanceof Date?pe.date:pe.object;default:return pe.unknown}};var ne=it.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),xL=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),vn=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n];},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n];};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t;}format(t){let r=t||function(o){return o.message},n={_errors:[]},a=o=>{for(let i of o.issues)if(i.code==="invalid_union")i.unionErrors.map(a);else if(i.code==="invalid_return_type")a(i.returnTypeError);else if(i.code==="invalid_arguments")a(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else {let s=n,l=0;for(;l<i.path.length;){let c=i.path[l];l===i.path.length-1?(s[c]=s[c]||{_errors:[]},s[c]._errors.push(r(i))):s[c]=s[c]||{_errors:[]},s=s[c],l++;}}};return a(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,it.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let a of this.issues)if(a.path.length>0){let o=a.path[0];r[o]=r[o]||[],r[o].push(t(a));}else n.push(t(a));return {formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};vn.create=e=>new vn(e);var wL=(e,t)=>{let r;switch(e.code){case ne.invalid_type:e.received===pe.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ne.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,it.jsonStringifyReplacer)}`;break;case ne.unrecognized_keys:r=`Unrecognized key(s) in object: ${it.joinValues(e.keys,", ")}`;break;case ne.invalid_union:r="Invalid input";break;case ne.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${it.joinValues(e.options)}`;break;case ne.invalid_enum_value:r=`Invalid enum value. Expected ${it.joinValues(e.options)}, received '${e.received}'`;break;case ne.invalid_arguments:r="Invalid function arguments";break;case ne.invalid_return_type:r="Invalid function return type";break;case ne.invalid_date:r="Invalid date";break;case ne.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:it.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case ne.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case ne.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case ne.custom:r="Invalid input";break;case ne.invalid_intersection_types:r="Intersection results could not be merged";break;case ne.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ne.not_finite:r="Number must be finite";break;default:r=t.defaultError,it.assertNever(e);}return {message:r}},Do=wL;var hE=Do;function _L(e){hE=e;}function uc(){return hE}var hd=e=>{let{data:t,path:r,errorMaps:n,issueData:a}=e,o=[...r,...a.path||[]],i={...a,path:o};if(a.message!==void 0)return {...a,path:o,message:a.message};let s="",l=n.filter(c=>!!c).slice().reverse();for(let c of l)s=c(i,{data:t,defaultError:s}).message;return {...a,path:o,message:s}},SL=[];function le(e,t){let r=uc(),n=hd({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Do?void 0:Do].filter(a=>!!a)});e.common.issues.push(n);}var kr=class e{constructor(){this.value="valid";}dirty(){this.value==="valid"&&(this.value="dirty");}abort(){this.value!=="aborted"&&(this.value="aborted");}static mergeArray(t,r){let n=[];for(let a of r){if(a.status==="aborted")return Oe;a.status==="dirty"&&t.dirty(),n.push(a.value);}return {status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let a of r){let o=await a.key,i=await a.value;n.push({key:o,value:i});}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let a of r){let{key:o,value:i}=a;if(o.status==="aborted"||i.status==="aborted")return Oe;o.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||a.alwaysSet)&&(n[o.value]=i.value);}return {status:t.value,value:n}}},Oe=Object.freeze({status:"aborted"}),Is=e=>({status:"dirty",value:e}),qr=e=>({status:"valid",value:e}),tm=e=>e.status==="aborted",rm=e=>e.status==="dirty",Ei=e=>e.status==="valid",dc=e=>typeof Promise<"u"&&e instanceof Promise;var xe;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message;})(xe||(xe={}));var ta=class{constructor(t,r,n,a){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=a;}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},gE=(e,t)=>{if(Ei(t))return {success:true,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return {success:false,get error(){if(this._error)return this._error;let r=new vn(e.common.issues);return this._error=r,this._error}}};function Xe(e){if(!e)return {};let{errorMap:t,invalid_type_error:r,required_error:n,description:a}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:a}:{errorMap:(i,s)=>{let{message:l}=e;return i.code==="invalid_enum_value"?{message:l??s.defaultError}:typeof s.data>"u"?{message:l??n??s.defaultError}:i.code!=="invalid_type"?{message:s.defaultError}:{message:l??r??s.defaultError}},description:a}}var tt=class{get description(){return this._def.description}_getType(t){return to(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:to(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return {status:new kr,ctx:{common:t.parent.common,data:t.data,parsedType:to(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(dc(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??false,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:to(t)},a=this._parseSync({data:t,path:n.path,parent:n});return gE(n,a)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:to(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return Ei(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=true),r.common={issues:[],async:true};}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Ei(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:true},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:to(t)},a=this._parse({data:t,path:n.path,parent:n}),o=await(dc(a)?a:Promise.resolve(a));return gE(n,o)}refine(t,r){let n=a=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(a):r;return this._refinement((a,o)=>{let i=t(a),s=()=>o.addIssue({code:ne.custom,...n(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(l=>l?true:(s(),false)):i?true:(s(),false)})}refinement(t,r){return this._refinement((n,a)=>t(n)?true:(a.addIssue(typeof r=="function"?r(n,a):r),false))}_refinement(t){return new ra({schema:this,typeName:Ie.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)};}optional(){return ea.create(this,this._def)}nullable(){return no.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Io.create(this)}promise(){return ki.create(this,this._def)}or(t){return Us.create([this,t],this._def)}and(t){return qs.create(this,t,this._def)}transform(t){return new ra({...Xe(this._def),schema:this,typeName:Ie.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new Ks({...Xe(this._def),innerType:this,defaultValue:r,typeName:Ie.ZodDefault})}brand(){return new gd({typeName:Ie.ZodBranded,type:this,...Xe(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new Gs({...Xe(this._def),innerType:this,catchValue:r,typeName:Ie.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return yd.create(this,t)}readonly(){return Zs.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},NL=/^c[^\s-]{8,}$/i,CL=/^[0-9a-z]+$/,EL=/^[0-9A-HJKMNP-TV-Z]{26}$/i,PL=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,TL=/^[a-z0-9_-]{21}$/i,kL=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,RL=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,OL=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,DL="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",mv,AL=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,$L=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,IL=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,FL=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ML=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jL=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,vE="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",LL=new RegExp(`^${vE}$`);function bE(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return `([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function BL(e){return new RegExp(`^${bE(e)}$`)}function xE(e){let t=`${vE}T${bE(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function zL(e,t){return !!((t==="v4"||!t)&&AL.test(e)||(t==="v6"||!t)&&IL.test(e))}function UL(e,t){if(!kL.test(e))return false;try{let[r]=e.split(".");if(!r)return !1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),a=JSON.parse(atob(n));return !(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||t&&a.alg!==t)}catch{return false}}function qL(e,t){return !!((t==="v4"||!t)&&$L.test(e)||(t==="v6"||!t)&&FL.test(e))}var Pi=class e extends tt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==pe.string){let o=this._getOrReturnCtx(t);return le(o,{code:ne.invalid_type,expected:pe.string,received:o.parsedType}),Oe}let n=new kr,a;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(a=this._getOrReturnCtx(t,a),le(a,{code:ne.too_small,minimum:o.value,type:"string",inclusive:true,exact:false,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(a=this._getOrReturnCtx(t,a),le(a,{code:ne.too_big,maximum:o.value,type:"string",inclusive:true,exact:false,message:o.message}),n.dirty());else if(o.kind==="length"){let i=t.data.length>o.value,s=t.data.length<o.value;(i||s)&&(a=this._getOrReturnCtx(t,a),i?le(a,{code:ne.too_big,maximum:o.value,type:"string",inclusive:true,exact:true,message:o.message}):s&&le(a,{code:ne.too_small,minimum:o.value,type:"string",inclusive:true,exact:true,message:o.message}),n.dirty());}else if(o.kind==="email")OL.test(t.data)||(a=this._getOrReturnCtx(t,a),le(a,{validation:"email",code:ne.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")mv||(mv=new RegExp(DL,"u")),mv.test(t.data)||(a=this._getOrReturnCtx(t,a),le(a,{validation:"emoji",code:ne.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")PL.test(t.data)||(a=this._getOrReturnCtx(t,a),le(a,{validation:"uuid",code:ne.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")TL.test(t.data)||(a=this._getOrReturnCtx(t,a),le(a,{validation:"nanoid",code:ne.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")NL.test(t.data)||(a=this._getOrReturnCtx(t,a),le(a,{validation:"cuid",code:ne.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")CL.test(t.data)||(a=this._getOrReturnCtx(t,a),le(a,{validation:"cuid2",code:ne.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")EL.test(t.data)||(a=this._getOrReturnCtx(t,a),le(a,{validation:"ulid",code:ne.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data);}catch{a=this._getOrReturnCtx(t,a),le(a,{validation:"url",code:ne.invalid_string,message:o.message}),n.dirty();}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(a=this._getOrReturnCtx(t,a),le(a,{validation:"regex",code:ne.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(a=this._getOrReturnCtx(t,a),le(a,{code:ne.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(a=this._getOrReturnCtx(t,a),le(a,{code:ne.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(a=this._getOrReturnCtx(t,a),le(a,{code:ne.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?xE(o).test(t.data)||(a=this._getOrReturnCtx(t,a),le(a,{code:ne.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?LL.test(t.data)||(a=this._getOrReturnCtx(t,a),le(a,{code:ne.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?BL(o).test(t.data)||(a=this._getOrReturnCtx(t,a),le(a,{code:ne.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?RL.test(t.data)||(a=this._getOrReturnCtx(t,a),le(a,{validation:"duration",code:ne.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?zL(t.data,o.version)||(a=this._getOrReturnCtx(t,a),le(a,{validation:"ip",code:ne.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?UL(t.data,o.alg)||(a=this._getOrReturnCtx(t,a),le(a,{validation:"jwt",code:ne.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?qL(t.data,o.version)||(a=this._getOrReturnCtx(t,a),le(a,{validation:"cidr",code:ne.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?ML.test(t.data)||(a=this._getOrReturnCtx(t,a),le(a,{validation:"base64",code:ne.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?jL.test(t.data)||(a=this._getOrReturnCtx(t,a),le(a,{validation:"base64url",code:ne.invalid_string,message:o.message}),n.dirty()):it.assertNever(o);return {status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(a=>t.test(a),{validation:r,code:ne.invalid_string,...xe.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...xe.errToObj(t)})}url(t){return this._addCheck({kind:"url",...xe.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...xe.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...xe.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...xe.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...xe.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...xe.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...xe.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...xe.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...xe.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...xe.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...xe.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...xe.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:false,local:false,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??false,local:t?.local??false,...xe.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...xe.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...xe.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...xe.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...xe.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...xe.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...xe.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...xe.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...xe.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...xe.errToObj(r)})}nonempty(t){return this.min(1,xe.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return !!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return !!this._def.checks.find(t=>t.kind==="date")}get isTime(){return !!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return !!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return !!this._def.checks.find(t=>t.kind==="email")}get isURL(){return !!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return !!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return !!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return !!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return !!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return !!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return !!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return !!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return !!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return !!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return !!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Pi.create=e=>new Pi({checks:[],typeName:Ie.ZodString,coerce:e?.coerce??false,...Xe(e)});function VL(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,a=r>n?r:n,o=Number.parseInt(e.toFixed(a).replace(".","")),i=Number.parseInt(t.toFixed(a).replace(".",""));return o%i/10**a}var Fs=class e extends tt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf;}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==pe.number){let o=this._getOrReturnCtx(t);return le(o,{code:ne.invalid_type,expected:pe.number,received:o.parsedType}),Oe}let n,a=new kr;for(let o of this._def.checks)o.kind==="int"?it.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),le(n,{code:ne.invalid_type,expected:"integer",received:"float",message:o.message}),a.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),le(n,{code:ne.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:false,message:o.message}),a.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),le(n,{code:ne.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:false,message:o.message}),a.dirty()):o.kind==="multipleOf"?VL(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),le(n,{code:ne.not_multiple_of,multipleOf:o.value,message:o.message}),a.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),le(n,{code:ne.not_finite,message:o.message}),a.dirty()):it.assertNever(o);return {status:a.value,value:t.data}}gte(t,r){return this.setLimit("min",t,true,xe.toString(r))}gt(t,r){return this.setLimit("min",t,false,xe.toString(r))}lte(t,r){return this.setLimit("max",t,true,xe.toString(r))}lt(t,r){return this.setLimit("max",t,false,xe.toString(r))}setLimit(t,r,n,a){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:xe.toString(a)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:xe.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:false,message:xe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:false,message:xe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:true,message:xe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:true,message:xe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:xe.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:xe.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:true,value:Number.MIN_SAFE_INTEGER,message:xe.toString(t)})._addCheck({kind:"max",inclusive:true,value:Number.MAX_SAFE_INTEGER,message:xe.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return !!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&it.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return true;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);}return Number.isFinite(r)&&Number.isFinite(t)}};Fs.create=e=>new Fs({checks:[],typeName:Ie.ZodNumber,coerce:e?.coerce||false,...Xe(e)});var Ms=class e extends tt{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte;}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data);}catch{return this._getInvalidInput(t)}if(this._getType(t)!==pe.bigint)return this._getInvalidInput(t);let n,a=new kr;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),le(n,{code:ne.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),a.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(n=this._getOrReturnCtx(t,n),le(n,{code:ne.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),a.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),le(n,{code:ne.not_multiple_of,multipleOf:o.value,message:o.message}),a.dirty()):it.assertNever(o);return {status:a.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return le(r,{code:ne.invalid_type,expected:pe.bigint,received:r.parsedType}),Oe}gte(t,r){return this.setLimit("min",t,true,xe.toString(r))}gt(t,r){return this.setLimit("min",t,false,xe.toString(r))}lte(t,r){return this.setLimit("max",t,true,xe.toString(r))}lt(t,r){return this.setLimit("max",t,false,xe.toString(r))}setLimit(t,r,n,a){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:xe.toString(a)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:false,message:xe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:false,message:xe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:true,message:xe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:true,message:xe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:xe.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Ms.create=e=>new Ms({checks:[],typeName:Ie.ZodBigInt,coerce:e?.coerce??false,...Xe(e)});var js=class extends tt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==pe.boolean){let n=this._getOrReturnCtx(t);return le(n,{code:ne.invalid_type,expected:pe.boolean,received:n.parsedType}),Oe}return qr(t.data)}};js.create=e=>new js({typeName:Ie.ZodBoolean,coerce:e?.coerce||false,...Xe(e)});var Ls=class e extends tt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==pe.date){let o=this._getOrReturnCtx(t);return le(o,{code:ne.invalid_type,expected:pe.date,received:o.parsedType}),Oe}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return le(o,{code:ne.invalid_date}),Oe}let n=new kr,a;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(a=this._getOrReturnCtx(t,a),le(a,{code:ne.too_small,message:o.message,inclusive:true,exact:false,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(a=this._getOrReturnCtx(t,a),le(a,{code:ne.too_big,message:o.message,inclusive:true,exact:false,maximum:o.value,type:"date"}),n.dirty()):it.assertNever(o);return {status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:xe.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:xe.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};Ls.create=e=>new Ls({checks:[],coerce:e?.coerce||false,typeName:Ie.ZodDate,...Xe(e)});var pc=class extends tt{_parse(t){if(this._getType(t)!==pe.symbol){let n=this._getOrReturnCtx(t);return le(n,{code:ne.invalid_type,expected:pe.symbol,received:n.parsedType}),Oe}return qr(t.data)}};pc.create=e=>new pc({typeName:Ie.ZodSymbol,...Xe(e)});var Bs=class extends tt{_parse(t){if(this._getType(t)!==pe.undefined){let n=this._getOrReturnCtx(t);return le(n,{code:ne.invalid_type,expected:pe.undefined,received:n.parsedType}),Oe}return qr(t.data)}};Bs.create=e=>new Bs({typeName:Ie.ZodUndefined,...Xe(e)});var zs=class extends tt{_parse(t){if(this._getType(t)!==pe.null){let n=this._getOrReturnCtx(t);return le(n,{code:ne.invalid_type,expected:pe.null,received:n.parsedType}),Oe}return qr(t.data)}};zs.create=e=>new zs({typeName:Ie.ZodNull,...Xe(e)});var Ti=class extends tt{constructor(){super(...arguments),this._any=true;}_parse(t){return qr(t.data)}};Ti.create=e=>new Ti({typeName:Ie.ZodAny,...Xe(e)});var $o=class extends tt{constructor(){super(...arguments),this._unknown=true;}_parse(t){return qr(t.data)}};$o.create=e=>new $o({typeName:Ie.ZodUnknown,...Xe(e)});var Da=class extends tt{_parse(t){let r=this._getOrReturnCtx(t);return le(r,{code:ne.invalid_type,expected:pe.never,received:r.parsedType}),Oe}};Da.create=e=>new Da({typeName:Ie.ZodNever,...Xe(e)});var mc=class extends tt{_parse(t){if(this._getType(t)!==pe.undefined){let n=this._getOrReturnCtx(t);return le(n,{code:ne.invalid_type,expected:pe.void,received:n.parsedType}),Oe}return qr(t.data)}};mc.create=e=>new mc({typeName:Ie.ZodVoid,...Xe(e)});var Io=class e extends tt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),a=this._def;if(r.parsedType!==pe.array)return le(r,{code:ne.invalid_type,expected:pe.array,received:r.parsedType}),Oe;if(a.exactLength!==null){let i=r.data.length>a.exactLength.value,s=r.data.length<a.exactLength.value;(i||s)&&(le(r,{code:i?ne.too_big:ne.too_small,minimum:s?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:true,exact:true,message:a.exactLength.message}),n.dirty());}if(a.minLength!==null&&r.data.length<a.minLength.value&&(le(r,{code:ne.too_small,minimum:a.minLength.value,type:"array",inclusive:true,exact:false,message:a.minLength.message}),n.dirty()),a.maxLength!==null&&r.data.length>a.maxLength.value&&(le(r,{code:ne.too_big,maximum:a.maxLength.value,type:"array",inclusive:true,exact:false,message:a.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,s)=>a.type._parseAsync(new ta(r,i,r.path,s)))).then(i=>kr.mergeArray(n,i));let o=[...r.data].map((i,s)=>a.type._parseSync(new ta(r,i,r.path,s)));return kr.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:xe.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:xe.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:xe.toString(r)}})}nonempty(t){return this.min(1,t)}};Io.create=(e,t)=>new Io({type:e,minLength:null,maxLength:null,exactLength:null,typeName:Ie.ZodArray,...Xe(t)});function fc(e){if(e instanceof bn){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=ea.create(fc(n));}return new bn({...e._def,shape:()=>t})}else return e instanceof Io?new Io({...e._def,type:fc(e.element)}):e instanceof ea?ea.create(fc(e.unwrap())):e instanceof no?no.create(fc(e.unwrap())):e instanceof ro?ro.create(e.items.map(t=>fc(t))):e}var bn=class e extends tt{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend;}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=it.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==pe.object){let c=this._getOrReturnCtx(t);return le(c,{code:ne.invalid_type,expected:pe.object,received:c.parsedType}),Oe}let{status:n,ctx:a}=this._processInputParams(t),{shape:o,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof Da&&this._def.unknownKeys==="strip"))for(let c in a.data)i.includes(c)||s.push(c);let l=[];for(let c of i){let u=o[c],d=a.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new ta(a,d,a.path,c)),alwaysSet:c in a.data});}if(this._def.catchall instanceof Da){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of s)l.push({key:{status:"valid",value:u},value:{status:"valid",value:a.data[u]}});else if(c==="strict")s.length>0&&(le(a,{code:ne.unrecognized_keys,keys:s}),n.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else {let c=this._def.catchall;for(let u of s){let d=a.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new ta(a,d,a.path,u)),alwaysSet:u in a.data});}}return a.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of l){let d=await u.key,g=await u.value;c.push({key:d,value:g,alwaysSet:u.alwaysSet});}return c}).then(c=>kr.mergeObjectSync(n,c)):kr.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(t){return xe.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let a=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:xe.errToObj(t).message??a}:{message:a}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:Ie.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of it.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of it.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return fc(this)}partial(t){let r={};for(let n of it.objectKeys(this.shape)){let a=this.shape[n];t&&!t[n]?r[n]=a:r[n]=a.optional();}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of it.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else {let o=this.shape[n];for(;o instanceof ea;)o=o._def.innerType;r[n]=o;}return new e({...this._def,shape:()=>r})}keyof(){return wE(it.objectKeys(this.shape))}};bn.create=(e,t)=>new bn({shape:()=>e,unknownKeys:"strip",catchall:Da.create(),typeName:Ie.ZodObject,...Xe(t)});bn.strictCreate=(e,t)=>new bn({shape:()=>e,unknownKeys:"strict",catchall:Da.create(),typeName:Ie.ZodObject,...Xe(t)});bn.lazycreate=(e,t)=>new bn({shape:e,unknownKeys:"strip",catchall:Da.create(),typeName:Ie.ZodObject,...Xe(t)});var Us=class extends tt{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function a(o){for(let s of o)if(s.result.status==="valid")return s.result;for(let s of o)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;let i=o.map(s=>new vn(s.ctx.common.issues));return le(r,{code:ne.invalid_union,unionErrors:i}),Oe}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return {result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(a);{let o,i=[];for(let l of n){let c={...r,common:{...r.common,issues:[]},parent:null},u=l._parseSync({data:r.data,path:r.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues);}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let s=i.map(l=>new vn(l));return le(r,{code:ne.invalid_union,unionErrors:s}),Oe}}get options(){return this._def.options}};Us.create=(e,t)=>new Us({options:e,typeName:Ie.ZodUnion,...Xe(t)});var Ao=e=>e instanceof Vs?Ao(e.schema):e instanceof ra?Ao(e.innerType()):e instanceof Hs?[e.value]:e instanceof Js?e.options:e instanceof Ws?it.objectValues(e.enum):e instanceof Ks?Ao(e._def.innerType):e instanceof Bs?[void 0]:e instanceof zs?[null]:e instanceof ea?[void 0,...Ao(e.unwrap())]:e instanceof no?[null,...Ao(e.unwrap())]:e instanceof gd||e instanceof Zs?Ao(e.unwrap()):e instanceof Gs?Ao(e._def.innerType):[],nm=class e extends tt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==pe.object)return le(r,{code:ne.invalid_type,expected:pe.object,received:r.parsedType}),Oe;let n=this.discriminator,a=r.data[n],o=this.optionsMap.get(a);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(le(r,{code:ne.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Oe)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let a=new Map;for(let o of r){let i=Ao(o.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let s of i){if(a.has(s))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(s)}`);a.set(s,o);}}return new e({typeName:Ie.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:a,...Xe(n)})}};function hv(e,t){let r=to(e),n=to(t);if(e===t)return {valid:true,data:e};if(r===pe.object&&n===pe.object){let a=it.objectKeys(t),o=it.objectKeys(e).filter(s=>a.indexOf(s)!==-1),i={...e,...t};for(let s of o){let l=hv(e[s],t[s]);if(!l.valid)return {valid:false};i[s]=l.data;}return {valid:true,data:i}}else if(r===pe.array&&n===pe.array){if(e.length!==t.length)return {valid:false};let a=[];for(let o=0;o<e.length;o++){let i=e[o],s=t[o],l=hv(i,s);if(!l.valid)return {valid:false};a.push(l.data);}return {valid:true,data:a}}else return r===pe.date&&n===pe.date&&+e==+t?{valid:true,data:e}:{valid:false}}var qs=class extends tt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),a=(o,i)=>{if(tm(o)||tm(i))return Oe;let s=hv(o.value,i.value);return s.valid?((rm(o)||rm(i))&&r.dirty(),{status:r.value,value:s.data}):(le(n,{code:ne.invalid_intersection_types}),Oe)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,i])=>a(o,i)):a(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};qs.create=(e,t,r)=>new qs({left:e,right:t,typeName:Ie.ZodIntersection,...Xe(r)});var ro=class e extends tt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==pe.array)return le(n,{code:ne.invalid_type,expected:pe.array,received:n.parsedType}),Oe;if(n.data.length<this._def.items.length)return le(n,{code:ne.too_small,minimum:this._def.items.length,inclusive:true,exact:false,type:"array"}),Oe;!this._def.rest&&n.data.length>this._def.items.length&&(le(n,{code:ne.too_big,maximum:this._def.items.length,inclusive:true,exact:false,type:"array"}),r.dirty());let o=[...n.data].map((i,s)=>{let l=this._def.items[s]||this._def.rest;return l?l._parse(new ta(n,i,n.path,s)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>kr.mergeArray(r,i)):kr.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ro.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ro({items:e,typeName:Ie.ZodTuple,rest:null,...Xe(t)})};var am=class e extends tt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==pe.object)return le(n,{code:ne.invalid_type,expected:pe.object,received:n.parsedType}),Oe;let a=[],o=this._def.keyType,i=this._def.valueType;for(let s in n.data)a.push({key:o._parse(new ta(n,s,n.path,s)),value:i._parse(new ta(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?kr.mergeObjectAsync(r,a):kr.mergeObjectSync(r,a)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof tt?new e({keyType:t,valueType:r,typeName:Ie.ZodRecord,...Xe(n)}):new e({keyType:Pi.create(),valueType:t,typeName:Ie.ZodRecord,...Xe(r)})}},hc=class extends tt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==pe.map)return le(n,{code:ne.invalid_type,expected:pe.map,received:n.parsedType}),Oe;let a=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([s,l],c)=>({key:a._parse(new ta(n,s,n.path,[c,"key"])),value:o._parse(new ta(n,l,n.path,[c,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let l of i){let c=await l.key,u=await l.value;if(c.status==="aborted"||u.status==="aborted")return Oe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(c.value,u.value);}return {status:r.value,value:s}})}else {let s=new Map;for(let l of i){let c=l.key,u=l.value;if(c.status==="aborted"||u.status==="aborted")return Oe;(c.status==="dirty"||u.status==="dirty")&&r.dirty(),s.set(c.value,u.value);}return {status:r.value,value:s}}}};hc.create=(e,t,r)=>new hc({valueType:t,keyType:e,typeName:Ie.ZodMap,...Xe(r)});var gc=class e extends tt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==pe.set)return le(n,{code:ne.invalid_type,expected:pe.set,received:n.parsedType}),Oe;let a=this._def;a.minSize!==null&&n.data.size<a.minSize.value&&(le(n,{code:ne.too_small,minimum:a.minSize.value,type:"set",inclusive:true,exact:false,message:a.minSize.message}),r.dirty()),a.maxSize!==null&&n.data.size>a.maxSize.value&&(le(n,{code:ne.too_big,maximum:a.maxSize.value,type:"set",inclusive:true,exact:false,message:a.maxSize.message}),r.dirty());let o=this._def.valueType;function i(l){let c=new Set;for(let u of l){if(u.status==="aborted")return Oe;u.status==="dirty"&&r.dirty(),c.add(u.value);}return {status:r.value,value:c}}let s=[...n.data.values()].map((l,c)=>o._parse(new ta(n,l,n.path,c)));return n.common.async?Promise.all(s).then(l=>i(l)):i(s)}min(t,r){return new e({...this._def,minSize:{value:t,message:xe.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:xe.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};gc.create=(e,t)=>new gc({valueType:e,minSize:null,maxSize:null,typeName:Ie.ZodSet,...Xe(t)});var om=class e extends tt{constructor(){super(...arguments),this.validate=this.implement;}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==pe.function)return le(r,{code:ne.invalid_type,expected:pe.function,received:r.parsedType}),Oe;function n(s,l){return hd({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,uc(),Do].filter(c=>!!c),issueData:{code:ne.invalid_arguments,argumentsError:l}})}function a(s,l){return hd({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,uc(),Do].filter(c=>!!c),issueData:{code:ne.invalid_return_type,returnTypeError:l}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof ki){let s=this;return qr(async function(...l){let c=new vn([]),u=await s._def.args.parseAsync(l,o).catch(f=>{throw c.addIssue(n(l,f)),c}),d=await Reflect.apply(i,this,u);return await s._def.returns._def.type.parseAsync(d,o).catch(f=>{throw c.addIssue(a(d,f)),c})})}else {let s=this;return qr(function(...l){let c=s._def.args.safeParse(l,o);if(!c.success)throw new vn([n(l,c.error)]);let u=Reflect.apply(i,this,c.data),d=s._def.returns.safeParse(u,o);if(!d.success)throw new vn([a(u,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ro.create(t).rest($o.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||ro.create([]).rest($o.create()),returns:r||$o.create(),typeName:Ie.ZodFunction,...Xe(n)})}},Vs=class extends tt{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Vs.create=(e,t)=>new Vs({getter:e,typeName:Ie.ZodLazy,...Xe(t)});var Hs=class extends tt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return le(r,{received:r.data,code:ne.invalid_literal,expected:this._def.value}),Oe}return {status:"valid",value:t.data}}get value(){return this._def.value}};Hs.create=(e,t)=>new Hs({value:e,typeName:Ie.ZodLiteral,...Xe(t)});function wE(e,t){return new Js({values:e,typeName:Ie.ZodEnum,...Xe(t)})}var Js=class e extends tt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return le(r,{expected:it.joinValues(n),received:r.parsedType,code:ne.invalid_type}),Oe}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return le(r,{received:r.data,code:ne.invalid_enum_value,options:n}),Oe}return qr(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};Js.create=wE;var Ws=class extends tt{_parse(t){let r=it.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==pe.string&&n.parsedType!==pe.number){let a=it.objectValues(r);return le(n,{expected:it.joinValues(a),received:n.parsedType,code:ne.invalid_type}),Oe}if(this._cache||(this._cache=new Set(it.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let a=it.objectValues(r);return le(n,{received:n.data,code:ne.invalid_enum_value,options:a}),Oe}return qr(t.data)}get enum(){return this._def.values}};Ws.create=(e,t)=>new Ws({values:e,typeName:Ie.ZodNativeEnum,...Xe(t)});var ki=class extends tt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==pe.promise&&r.common.async===false)return le(r,{code:ne.invalid_type,expected:pe.promise,received:r.parsedType}),Oe;let n=r.parsedType===pe.promise?r.data:Promise.resolve(r.data);return qr(n.then(a=>this._def.type.parseAsync(a,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ki.create=(e,t)=>new ki({type:e,typeName:Ie.ZodPromise,...Xe(t)});var ra=class extends tt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ie.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),a=this._def.effect||null,o={addIssue:i=>{le(n,i),i.fatal?r.abort():r.dirty();},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),a.type==="preprocess"){let i=a.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async s=>{if(r.value==="aborted")return Oe;let l=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return l.status==="aborted"?Oe:l.status==="dirty"?Is(l.value):r.value==="dirty"?Is(l.value):l});{if(r.value==="aborted")return Oe;let s=this._def.schema._parseSync({data:i,path:n.path,parent:n});return s.status==="aborted"?Oe:s.status==="dirty"?Is(s.value):r.value==="dirty"?Is(s.value):s}}if(a.type==="refinement"){let i=s=>{let l=a.refinement(s,o);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===false){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Oe:(s.status==="dirty"&&r.dirty(),i(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?Oe:(s.status==="dirty"&&r.dirty(),i(s.value).then(()=>({status:r.value,value:s.value}))))}if(a.type==="transform")if(n.common.async===false){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Ei(i))return Oe;let s=a.transform(i.value,o);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return {status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Ei(i)?Promise.resolve(a.transform(i.value,o)).then(s=>({status:r.value,value:s})):Oe);it.assertNever(a);}};ra.create=(e,t,r)=>new ra({schema:e,typeName:Ie.ZodEffects,effect:t,...Xe(r)});ra.createWithPreprocess=(e,t,r)=>new ra({schema:t,effect:{type:"preprocess",transform:e},typeName:Ie.ZodEffects,...Xe(r)});var ea=class extends tt{_parse(t){return this._getType(t)===pe.undefined?qr(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ea.create=(e,t)=>new ea({innerType:e,typeName:Ie.ZodOptional,...Xe(t)});var no=class extends tt{_parse(t){return this._getType(t)===pe.null?qr(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};no.create=(e,t)=>new no({innerType:e,typeName:Ie.ZodNullable,...Xe(t)});var Ks=class extends tt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===pe.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Ks.create=(e,t)=>new Ks({innerType:e,typeName:Ie.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Xe(t)});var Gs=class extends tt{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},a=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return dc(a)?a.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new vn(n.common.issues)},input:n.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new vn(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Gs.create=(e,t)=>new Gs({innerType:e,typeName:Ie.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Xe(t)});var yc=class extends tt{_parse(t){if(this._getType(t)!==pe.nan){let n=this._getOrReturnCtx(t);return le(n,{code:ne.invalid_type,expected:pe.nan,received:n.parsedType}),Oe}return {status:"valid",value:t.data}}};yc.create=e=>new yc({typeName:Ie.ZodNaN,...Xe(e)});var HL=Symbol("zod_brand"),gd=class extends tt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},yd=class e extends tt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return (async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Oe:o.status==="dirty"?(r.dirty(),Is(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let a=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?Oe:a.status==="dirty"?(r.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:Ie.ZodPipeline})}},Zs=class extends tt{_parse(t){let r=this._def.innerType._parse(t),n=a=>(Ei(a)&&(a.value=Object.freeze(a.value)),a);return dc(r)?r.then(a=>n(a)):n(r)}unwrap(){return this._def.innerType}};Zs.create=(e,t)=>new Zs({innerType:e,typeName:Ie.ZodReadonly,...Xe(t)});function yE(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function _E(e,t={},r){return e?Ti.create().superRefine((n,a)=>{let o=e(n);if(o instanceof Promise)return o.then(i=>{if(!i){let s=yE(t,n),l=s.fatal??r??true;a.addIssue({code:"custom",...s,fatal:l});}});if(!o){let i=yE(t,n),s=i.fatal??r??true;a.addIssue({code:"custom",...i,fatal:s});}}):Ti.create()}var JL={object:bn.lazycreate},Ie;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly";})(Ie||(Ie={}));var WL=(e,t={message:`Input not instance of ${e.name}`})=>_E(r=>r instanceof e,t),vc=Pi.create,SE=Fs.create,KL=yc.create,GL=Ms.create,im=js.create,ZL=Ls.create,XL=pc.create,QL=Bs.create,YL=zs.create,e9=Ti.create,t9=$o.create,r9=Da.create,n9=mc.create,a9=Io.create,gv=bn.create,o9=bn.strictCreate,i9=Us.create,s9=nm.create,l9=qs.create,c9=ro.create,u9=am.create,d9=hc.create,f9=gc.create,p9=om.create,m9=Vs.create,h9=Hs.create,g9=Js.create,y9=Ws.create,v9=ki.create,b9=ra.create,x9=ea.create,w9=no.create,_9=ra.createWithPreprocess,S9=yd.create,N9=()=>vc().optional(),C9=()=>SE().optional(),E9=()=>im().optional(),P9={string:(e=>Pi.create({...e,coerce:true})),number:(e=>Fs.create({...e,coerce:true})),boolean:(e=>js.create({...e,coerce:true})),bigint:(e=>Ms.create({...e,coerce:true})),date:(e=>Ls.create({...e,coerce:true}))};var T9=Oe;var NE=({className:e})=>jsxs("svg",{width:"419",height:"351",viewBox:"0 0 419 351",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",className:e,children:[jsx("path",{d:"M101.497 174.575C101.362 171.333 101.902 168.098 103.083 165.075C104.263 162.052 106.058 159.307 108.353 157.014C110.649 154.72 113.396 152.928 116.42 151.751C119.444 150.574 122.68 150.037 125.922 150.175C130.746 150.18 135.462 151.615 139.471 154.299C143.48 156.983 146.604 160.796 148.447 165.255C150.289 169.714 150.769 174.619 149.825 179.35C148.88 184.082 146.555 188.427 143.141 191.837C139.728 195.247 135.38 197.568 130.648 198.508C125.915 199.447 121.01 198.963 116.553 197.115C112.096 195.268 108.287 192.14 105.607 188.128C102.927 184.116 101.497 179.4 101.497 174.575Z"}),jsx("path",{d:"M185.778 174.575C185.644 171.333 186.184 168.098 187.364 165.075C188.544 162.052 190.339 159.307 192.635 157.014C194.93 154.72 197.677 152.928 200.701 151.751C203.725 150.574 206.961 150.037 210.203 150.175C215.028 150.18 219.743 151.615 223.752 154.299C227.761 156.983 230.885 160.796 232.728 165.255C234.571 169.714 235.05 174.619 234.106 179.35C233.162 184.082 230.836 188.427 227.423 191.837C224.009 195.247 219.661 197.568 214.929 198.508C210.196 199.447 205.292 198.963 200.835 197.115C196.378 195.268 192.568 192.14 189.888 188.128C187.208 184.116 185.778 179.4 185.778 174.575Z"}),jsx("path",{d:"M269.997 174.575C269.862 171.333 270.402 168.098 271.583 165.075C272.763 162.052 274.558 159.307 276.853 157.014C279.149 154.72 281.896 152.928 284.92 151.751C287.944 150.574 291.18 150.037 294.422 150.175C299.247 150.18 303.962 151.615 307.971 154.299C311.98 156.983 315.104 160.796 316.946 165.255C318.789 169.714 319.269 174.619 318.325 179.35C317.38 184.082 315.055 188.427 311.641 191.837C308.228 195.247 303.88 197.568 299.148 198.508C294.415 199.447 289.51 198.963 285.053 197.115C280.596 195.268 276.787 192.14 274.107 188.128C271.427 184.116 269.997 179.4 269.997 174.575Z"}),jsx("path",{d:"M0.476562 197.25V153.55C7.95998 153.541 15.3944 152.343 22.5016 150C27.1229 147.429 30.9265 143.608 33.4766 138.975C36.8421 132.986 38.9996 126.395 39.8266 119.575C40.9644 109.484 41.4237 99.3276 41.2016 89.1749C40.6848 72.6982 41.7143 56.2094 44.2766 39.9249C45.8434 31.5389 49.7028 23.7509 55.4266 17.4249C60.6952 10.9582 67.731 6.16347 75.6766 3.62491C86.4389 1.01665 97.5112 -0.0855449 108.577 0.349899H117.652V36.2749C109.441 35.7638 101.201 36.5313 93.2266 38.5499C89.8504 39.8715 87.0336 42.3175 85.2516 45.4749C83.3166 53.1601 82.475 61.0797 82.7516 68.9999C82.7516 76.6499 82.2349 91.1582 81.2016 112.525C80.9709 122.417 79.4755 132.238 76.7516 141.75C74.7665 148.385 71.6636 154.633 67.5766 160.225C62.7049 166.078 56.9529 171.139 50.5266 175.225C56.8771 179.004 62.4854 183.909 67.0766 189.7C71.5922 195.685 74.9344 202.472 76.9266 209.7C79.5735 220.062 81.0659 230.685 81.3766 241.375C82.1766 261.525 82.5766 274.392 82.5766 279.975C82.2792 287.837 83.207 295.698 85.3266 303.275C87.2466 306.515 90.1687 309.042 93.6516 310.475C101.482 312.639 109.618 313.484 117.727 312.975V350.125H108.652C97.6899 350.38 86.7655 348.756 76.3516 345.325C68.4029 342.94 61.2154 338.518 55.5016 332.5C49.7172 326.182 45.7744 318.401 44.1016 310C41.7647 296.078 40.7851 281.961 41.1766 267.85C41.7704 253.285 40.8488 238.699 38.4266 224.325C36.8991 216.354 32.9123 209.063 27.0266 203.475C18.8768 199.104 9.71968 196.957 0.476562 197.25Z"}),jsx("path",{d:"M392.123 203.575C386.238 209.163 382.251 216.454 380.723 224.425C378.301 238.799 377.38 253.386 377.973 267.95C378.342 282.03 377.346 296.112 374.998 310C373.326 318.401 369.383 326.182 363.598 332.5C357.915 338.588 350.735 343.079 342.773 345.525C332.36 348.956 321.435 350.58 310.473 350.325H301.398V313.25C309.507 313.759 317.643 312.914 325.473 310.75C328.956 309.317 331.878 306.79 333.798 303.55C335.918 295.973 336.846 288.112 336.548 280.25C336.548 274.667 336.948 261.8 337.748 241.65C338.077 230.966 339.587 220.352 342.248 210C344.241 202.772 347.583 195.986 352.098 190C356.69 184.209 362.298 179.304 368.648 175.525C362.222 171.439 356.47 166.378 351.598 160.525C347.511 154.933 344.409 148.685 342.423 142.05C339.7 132.538 338.204 122.717 337.973 112.825C336.94 91.4583 336.423 76.95 336.423 69.3C336.7 61.3798 335.858 53.4601 333.923 45.775C332.141 42.6175 329.325 40.1716 325.948 38.85C317.974 36.8313 309.734 36.0638 301.523 36.575V0.399948H310.598C321.664 -0.035496 332.736 1.0667 343.498 3.67496C351.444 6.21351 358.48 11.0082 363.748 17.475C369.472 23.8009 373.332 31.5889 374.898 39.975C377.461 56.2594 378.49 72.7483 377.973 89.225C377.751 99.3776 378.211 109.534 379.348 119.625C380.175 126.445 382.333 133.036 385.698 139.025C388.249 143.658 392.052 147.479 396.673 150.05C403.794 152.415 411.246 153.631 418.748 153.65V197.25C409.471 196.975 400.286 199.157 392.123 203.575Z"})]});function Y9({open:e,onOpenChange:t,onDefinitionCreated:r}){let{jsonSchema:n,setJsonSchema:a}=Ka(),[o,i]=useState(""),[s,l]=useState({type:"object",properties:{},required:[]}),[c,u]=useState(null);useEffect(()=>{e&&(i(""),l({type:"object",properties:{},required:[]}),u(null));},[e]);let d=h=>{let m=Object.keys(n.$defs||{});return Ci(h,m,void 0,"definition")},g=h=>{i(h),u(d(h));},f=()=>{if(!o.trim())return;let h=d(o);if(h){u(h);return}let m={...n};m.$defs||(m.$defs={}),m.$defs[o]=s,a(m),r(o),t(false);};return jsx(En,{open:e,onOpenChange:t,children:jsxs(Pa,{className:"sm:max-w-[700px] max-h-[80vh] overflow-y-auto",children:[jsxs(_i,{children:[jsx(Pn,{children:"Create New Definition"}),jsx(Si,{children:"Create a reusable definition that can be referenced in multiple places."})]}),jsxs("div",{className:"mb-4",children:[jsxs(nr,{htmlFor:"defName",className:"block text-sm font-medium text-gray-700",children:["Definition Name",jsx("span",{className:"text-red-500 ml-[2px]",children:"*"})]}),jsx(Ze,{id:"defName",value:o,onChange:h=>g(h.target.value),className:`mt-1 ${c?"border-red-500":""}`,placeholder:"e.g. person_address"}),c&&jsxs("p",{className:"text-sm font-medium text-red-500 mt-1 flex items-center gap-1",children:[jsx(AlertCircle,{className:"h-3 w-3"}),c]}),jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Must start with a lowercase letter or underscore, contain only lowercase letters, digits, or underscores, and be at most 64 characters. Cannot be a Python reserved keyword."})]}),jsx(Oo,{name:o||"Click to set definition name",node:s,onChange:l,jsonSchema:n,setJsonSchema:a,path:"#/definition",defs:n.$defs||{},canDelete:false,setDefsAccordionOpen:()=>{},onNameChange:h=>g(h),draggedParentRef:Rt__default.useRef(null),draggedPropertyRef:Rt__default.useRef(null)}),jsxs(ac,{children:[jsx(K,{variant:"outline",onClick:()=>t(false),children:"Cancel"}),jsxs(K,{onClick:f,disabled:!o.trim()||!!c,children:[jsx(PlusIcon,{className:"w-4 h-4 mr-2"}),"Create Definition"]})]})]})})}var Aa=e=>{switch(e){case "string":return jsx(Type,{className:"w-4 h-4"});case "number":case "integer":return jsx(Hash,{className:"w-4 h-4"});case "boolean":return jsx(ToggleLeft,{className:"w-4 h-4"});case "enum":return jsx(List,{className:"w-4 h-4"});case "object":return jsx(Braces,{className:"w-4 h-4"});case "array":return jsx(Brackets,{className:"w-4 h-4"});case "date":return jsx(Calendar,{className:"w-4 h-4"});case "time":return jsx(Clock,{className:"w-4 h-4"});case "datetime":return jsx(CalendarClock,{className:"w-4 h-4"});case "$ref":return jsx(Link,{className:"w-4 h-4"});default:return jsx(Shapes,{className:"w-4 h-4"})}},EE=e=>{switch(e){case "Address":return jsx(MapPin,{className:"w-4 h-4"});case "Price":return jsx(DollarSign,{className:"w-4 h-4"});case "Person":return jsx(User,{className:"w-4 h-4"});case "Company":return jsx(Building2,{className:"w-4 h-4"});case "Event":return jsx(CalendarDays,{className:"w-4 h-4"});default:return jsx(Link,{className:"w-4 h-4"})}};function e6({name:e,value:t,onChange:r,setJsonSchema:n,label:a="Type",isRoot:o=false,setDialogMode:i,disabled:s=false,focusPath:l}){let{jsonSchema:c}=Ka(),[u,d]=useState(false),[g,f]=useState(null),h=yn(t);return jsxs("div",{className:o?"":"bg-slate-50 p-3 rounded-md mt-3",children:[jsx(Y9,{open:u,onOpenChange:d,onDefinitionCreated:p=>{r(kt(t,{$ref:`#/$defs/${p}`}));}}),!o&&jsx(nr,{className:"text-sm font-medium text-gray-700 mb-2 block",children:a}),jsxs(mr,{children:[jsx(hr,{asChild:true,children:jsxs(K,{disabled:s,variant:"outline",className:`w-full mt-2 justify-between ${s?"disabled:opacity-100":""}`,children:[jsxs("div",{className:"flex items-center gap-2",children:[Aa(h.type),jsx("span",{children:(()=>{if(h.type==="$ref"){let p=t.$ref,v=Array.isArray(t.anyOf)?t.anyOf.find(x=>typeof x=="object"&&x.$ref)?.$ref:void 0,y=p||v;return y?y.replace("#/$defs/",""):"$ref"}return h.type==="date"?"date":h.type==="time"?"time":h.type==="datetime"?"timestamp":h.type==="boolean"?"true/false":h.type==="enum"?"multiple choice":h.type==="array"?"list":h.type})()})]}),jsx(ChevronDown,{className:"w-4 h-4 ml-2"})]})}),jsxs(gr,{className:"w-full",children:[jsx(we,{disabled:s,onSelect:()=>r(Yn("string",h.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[Aa("string"),jsx("span",{children:"string"})]})}),jsx(we,{disabled:s,onSelect:()=>r(Yn("number",h.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[Aa("number"),jsx("span",{children:"number"})]})}),jsx(we,{disabled:s,onSelect:()=>r(Yn("boolean",h.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[Aa("boolean"),jsx("span",{children:"true/false"})]})}),jsx(we,{disabled:s,onSelect:()=>{let p=Yn("enum",h.isNullable,t);r({...p,enum:t.enum||[]});},children:jsxs("div",{className:"flex items-center gap-2",children:[Aa("enum"),jsx("span",{children:"multiple choice"})]})}),jsx(we,{disabled:s,onSelect:()=>r(Yn("date",h.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[Aa("date"),jsx("span",{children:"date"})]})}),jsx(we,{disabled:s,onSelect:()=>r(Yn("time",h.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[Aa("time"),jsx("span",{children:"time"})]})}),jsx(we,{disabled:s,onSelect:()=>r(Yn("datetime",h.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[Aa("datetime"),jsx("span",{children:"timestamp"})]})}),jsx(we,{disabled:s,onSelect:()=>r(Yn("array",h.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[Aa("array"),jsx("span",{children:"list"})]})}),jsx(we,{disabled:s,onSelect:()=>r(Yn("object",h.isNullable,t)),children:jsxs("div",{className:"flex items-center gap-2",children:[Aa("object"),jsx("span",{children:"object"})]})}),jsxs(Xr,{children:[jsx(Qr,{children:jsxs("div",{className:"flex items-center gap-2",children:[Aa("$ref"),jsx("span",{children:"definition"})]})}),jsx(Ta,{children:jsxs(Yr,{children:[Object.keys(c.$defs||{}).length>0?jsxs(Fragment,{children:[Object.keys(c.$defs||{}).map(p=>jsx(we,{onSelect:()=>{r(kt(t,{$ref:`#/$defs/${p}`}));},children:jsxs("div",{className:"flex items-center gap-2",children:[EE(p),jsx("span",{children:p})]})},p)),jsx(ka,{})]}):null,jsx(we,{disabled:s,onSelect:()=>{setTimeout(()=>{d(true);},100);},children:jsxs("div",{className:"flex items-center gap-2",children:[jsx(PlusIcon,{className:"h-4 w-4"}),jsx("span",{children:"Create new definition"})]})})]})})]}),jsxs(Xr,{children:[jsx(Qr,{children:jsxs("div",{className:"flex items-center gap-2",children:[jsx(Shapes,{className:"w-4 h-4"}),jsx("span",{children:"object template"})]})}),jsx(Ta,{children:jsx(Yr,{children:Object.entries(sc).map(([p,v])=>jsx(we,{onSelect:()=>{let y=[p];v.deps&&y.push(...v.deps);let x={...c.$defs||{}};for(let w of y)x[w]||(x[w]=sc[w]);n({...c,$defs:x}),r(kt(t,{$ref:`#/$defs/${p}`}));},children:jsxs("div",{className:"flex items-center gap-2",children:[EE(p),jsx("span",{children:p})]})},p))})})]})]})]}),h.type==="object"&&!t.$ref&&jsx("div",{className:"text-sm mt-3",children:jsx(K,{disabled:s,variant:"secondary",className:"w-full",onClick:()=>{i("object-editor");},children:"Edit Object Properties"})}),h.type==="array"&&jsx("div",{className:"text-sm mt-3",children:jsx(K,{disabled:s,variant:"secondary",className:"w-full",onClick:()=>{f(t.items||{type:"string"}),i("array-editor");},children:"Edit List Items"})}),(()=>{let p=t.anyOf&&Array.isArray(t.anyOf)&&t.anyOf.find(v=>typeof v=="object"&&(v.type!=="null"||v.$ref||v.enum))||t;return Array.isArray(p.enum)})()&&jsxs("div",{className:"mt-3",children:[jsx(nr,{className:"text-sm font-medium text-gray-700 block mb-2",children:"Enabled options"}),jsx("div",{className:"mb-2 flex flex-wrap gap-2",children:(t.anyOf&&Array.isArray(t.anyOf)?t.anyOf.find(p=>typeof p=="object"&&(p.type!=="null"||p.$ref||p.enum))?.enum||[]:t.enum||[]).map((p,v)=>jsxs("div",{className:"flex items-center space-x-2 border-gray-200 border rounded-md px-2 py-1 bg-slate-50",children:[jsx(Ze,{disabled:s,value:typeof p=="string"?p:String(p),onChange:y=>{let x=t.anyOf&&Array.isArray(t.anyOf)?t.anyOf.find(C=>typeof C=="object"&&(C.type!=="null"||C.$ref||C.enum))||{}:t,w=[...x.enum||[]];w[v]=y.target.value;let _={...x,enum:w.filter(C=>C&&C!=="")},E=kt(t,_);r(E);},className:"h-6 w-24 shadow-none px-1 bg-transparent border-0 focus-visible:ring-0 focus-visible:ring-offset-0"}),jsx(K,{type:"button",disabled:s,variant:"ghost",size:"icon",className:"h-4 w-4 p-0",onClick:()=>{let y=t.anyOf&&Array.isArray(t.anyOf)?t.anyOf.find(E=>typeof E=="object"&&(E.type!=="null"||E.$ref||E.enum))||{}:t,x=[...y.enum||[]];x.splice(v,1);let w={...y,enum:x},_=kt(t,w);r(_);},children:jsx(X,{className:"h-3 w-3"})})]},v))}),jsxs("div",{className:"flex items-center gap-2",children:[jsx(Ze,{disabled:s,placeholder:"Add new value",onKeyDown:p=>{if(p.key==="Enter"&&p.currentTarget.value){let v=t.anyOf&&Array.isArray(t.anyOf)?t.anyOf.find(w=>typeof w=="object"&&(w.type!=="null"||w.$ref||w.enum))||{}:t,y={...v,enum:[...v.enum||[],p.currentTarget.value]},x=kt(t,y);r(x),p.currentTarget.value="";}},className:"w-40"}),jsxs(K,{disabled:s,type:"button",variant:"outline",size:"sm",onClick:p=>{let v=p.currentTarget.previousElementSibling;if(v.value){let y=t.anyOf&&Array.isArray(t.anyOf)?t.anyOf.find(_=>typeof _=="object"&&(_.type!=="null"||_.$ref||_.enum))||{}:t,x={...y,enum:[...y.enum||[],v.value]},w=kt(t,x);r(w),v.value="";}},children:[jsx(PlusIcon,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})}var t6=gv({name:vc().min(1,{message:"Name is required"}).regex(/^[a-z_][a-z0-9_]{0,63}$/,{message:"Name must start with a lowercase letter or underscore, contain only lowercase letters, numbers, or underscores, and be at most 64 characters long"}),description:vc().optional(),reasoningPrompt:vc().optional(),required:im()});function sv({editedProperty:e,setEditedProperty:t,setJsonSchema:r,editedJsonSchema:n,setEditedJsonSchema:a,editedName:o,setEditedName:i,onSubmit:s,onCancel:l,onDelete:c,submitLabel:u="Save Changes",onNameError:d,editMode:g="editable",wrapCancelInDialogClose:f,wrapSubmitInDialogClose:h,fieldPathOverride:m}){let[p,v]=useState("main"),{jsonSchema:y}=Ka(),{setShowSchemaEditor:x,setSelectedFieldPath:w}=Ni(),_=Rt__default.useRef(null),E=Rt__default.useRef(null),[C,P]=useState(null),T=useCallback(M=>{let j=Object.keys(y.properties||{});return Ci(M,j,o,"property")},[y,o]);useEffect(()=>{d&&d(C);},[C,d]);let N=useForm({resolver:zodResolver(t6),defaultValues:{name:o,description:e.description||"",reasoningPrompt:e["X-ReasoningPrompt"]||"",required:!yn(e).isNullable},mode:"onBlur"}),[S,b]=useState(!!e["X-ReasoningPrompt"]),k=useRef({name:o,description:e.description||"",reasoningPrompt:e["X-ReasoningPrompt"]||"",required:!yn(e).isNullable}),D=N.handleSubmit(M=>{let j=T(M.name);if(j){P(j);return}i(M.name);let ue={...e,title:Ya(M.name),description:M.description,"X-ReasoningPrompt":M.reasoningPrompt},ie=em(ue,!M.required);t(ie),s&&s(),u==="Save Changes"&&toast.success("Changes saved successfully");}),O=M=>{if(M.key==="Enter"&&!M.shiftKey){if(C){M.preventDefault();return}M.target instanceof HTMLTextAreaElement?(M.ctrlKey||M.metaKey)&&(M.preventDefault(),D()):(M.preventDefault(),D());}},$=M=>{let j=M.target.value;i(j),P(null),N.setValue("name",j,{shouldValidate:true});},A=()=>{let M=N.getValues("name");if(M&&!N.formState.errors.name){let j=T(M);P(j);}else N.formState.errors.name&&P(null);},F=M=>{let j=M.target.value,ue={...e,description:j};t(ue),N.setValue("description",j);},X$1=M=>{let j=M.target.value,ue={...e,"X-ReasoningPrompt":j};t(ue),N.setValue("reasoningPrompt",j);},H=M=>{if(typeof M=="boolean"){let j=em(e,!M);t(j),N.setValue("required",M);}},L=()=>{b(M=>!M);};useEffect(()=>{let M=k.current;if(o!==M.name&&(N.setValue("name",o,{shouldValidate:true}),M.name=o,o)){let ue=T(o);P(ue);}e.description!==M.description&&(N.setValue("description",e.description||""),M.description=e.description||""),e["X-ReasoningPrompt"]!==M.reasoningPrompt&&(N.setValue("reasoningPrompt",e["X-ReasoningPrompt"]||""),M.reasoningPrompt=e["X-ReasoningPrompt"]||"",e["X-ReasoningPrompt"]&&b(true));let j=!yn(e).isNullable;j!==M.required&&(N.setValue("required",j),M.required=j);},[o,e,N,T]),useEffect(()=>{if(o){let M=T(o);P(M);}},[o,T]);let ae=yn(e).type==="enum"&&(()=>{if(Array.isArray(e.enum))return e.enum;if(Array.isArray(e.anyOf)){let M=e.anyOf.find(j=>typeof j=="object"&&(j.type!=="null"||j.$ref||j.enum));if(M&&Array.isArray(M.enum))return M.enum}return []})().length===0;return g==="editable"&&p==="array-editor"&&yn(e).type==="array"?jsxs("div",{className:"space-y-4 max-h-[80vh] overflow-y-auto p-4",children:[jsxs("div",{className:"flex items-center mb-4",children:[jsx(K,{variant:"ghost",size:"sm",onClick:()=>v("main"),children:jsx(ChevronLeft,{className:"w-4 h-4 mr-2"})}),jsx("h2",{className:"text-lg font-medium ml-2",children:"Edit list items"})]}),jsx("div",{className:"bg-gray-50 p-4 rounded-md",children:jsx(Oo,{name:"items",node:e.items||{type:"string"},onChange:M=>{t({...e,items:M});},jsonSchema:n,setJsonSchema:a,path:"#/array-item",defs:y.$defs||{},canDelete:false,setDefsAccordionOpen:()=>{},draggedParentRef:_,draggedPropertyRef:E,hidePencilButton:true})}),jsx("div",{className:"flex justify-end space-x-2 mt-4",children:jsx(K,{onClick:()=>v("main"),children:"Done"})})]}):g==="editable"&&p==="object-editor"&&yn(e).type==="object"?jsxs("div",{className:"space-y-4 max-h-[80vh] overflow-y-auto p-4",children:[jsxs("div",{className:"flex items-center mb-4",children:[jsx(K,{variant:"ghost",size:"sm",onClick:()=>v("main"),children:jsx(ChevronLeft,{className:"w-4 h-4 mr-2"})}),jsx("h2",{className:"text-lg font-medium ml-2",children:"Edit Object Properties"})]}),jsx(Oo,{name:o,node:e,onChange:t,jsonSchema:n,setJsonSchema:a,path:"#/object",defs:y.$defs||{},canDelete:false,setDefsAccordionOpen:()=>{},draggedParentRef:_,draggedPropertyRef:E}),jsx("div",{className:"flex justify-end space-x-2 mt-4",children:jsx(K,{onClick:()=>v("main"),children:"Done"})})]}):jsx(Wl,{...N,children:jsxs("form",{onSubmit:D,onKeyDown:O,className:"flex flex-col h-full z-10 bg-gray-50 rounded-2xl",children:[jsxs("div",{className:"bg-white shadow-xs flex-1 overflow-y-auto z-20 max-h-[60vh] rounded-2xl",children:[jsxs("div",{className:"p-4 space-y-4 border-b border-gray-200",children:[jsx(Sa,{control:N.control,name:"name",render:({field:M,fieldState:j})=>jsxs(Hn,{children:[jsx("div",{className:"flex flex-row items-center gap-2",children:jsx(nr,{htmlFor:"name",className:"block text-sm font-medium text-gray-700",children:"Name"})}),jsx(Jn,{children:jsx(Ze,{id:"name",disabled:g!=="editable",value:o,onChange:$,onBlur:A,className:`${j.error||C?"border-red-500":""} ${g!=="editable"?"disabled:opacity-100":""}`,placeholder:"e.g. first_name",required:true})}),j.error&&jsxs("p",{className:"text-sm font-medium text-red-500 mt-1 flex items-center gap-1",children:[jsx(AlertCircle,{className:"h-3 w-3"}),j.error.message]}),!j.error&&C&&jsxs("p",{className:"text-sm font-medium text-red-500 mt-1 flex items-center gap-1",children:[jsx(AlertCircle,{className:"h-3 w-3"}),C]})]})}),jsxs("div",{children:[jsx(nr,{htmlFor:"type",className:"block text-sm font-medium text-gray-700",children:"Data type"}),jsx(e6,{name:o,disabled:g!=="editable",value:e,onChange:t,setJsonSchema:a,setDialogMode:v,isRoot:true,focusPath:m??o})]}),jsxs("div",{className:"flex flex-row items-center justify-between",children:[jsx(Sa,{control:N.control,name:"required",render:({field:M})=>jsxs(Hn,{className:"flex flex-row items-center space-x-2 space-y-0",children:[jsx(Jn,{children:jsx(md,{id:"required",disabled:g!=="editable",checked:!yn(e).isNullable,onCheckedChange:H,className:g!=="editable"?"disabled:opacity-100":""})}),jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(nr,{htmlFor:"required",className:"text-sm font-medium text-gray-700 cursor-pointer",children:"Required"})}),jsxs(ze,{className:"max-w-xs",children:[jsx("p",{children:"When a field is required, it must have a value and cannot be null or undefined."}),jsx("p",{children:"Required fields must be provided when submitting data for this schema."})]})]})]})}),g!=="readOnly"&&jsx("div",{className:"text-sm",children:jsxs(K,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{let M=m??o;M&&w(M),x(true);},children:[jsx(NE,{})," Edit in Schema Editor"]})})]})]}),jsxs("div",{className:"p-4 space-y-4",children:[jsx(Sa,{control:N.control,name:"description",render:({field:M})=>jsxs(Hn,{className:"group",children:[jsx("div",{className:"flex flex-row items-center justify-between gap-2",children:jsx(nr,{htmlFor:"description",className:"block text-sm font-medium text-gray-700",children:"Description"})}),jsx(Jn,{children:jsx(pr,{id:"description",value:e.description||"",onChange:F,onBlur:M.onBlur,disabled:g==="readOnly",className:g==="readOnly"?"disabled:opacity-100":""})})]})}),!S&&g!=="readOnly"?jsxs("div",{className:"flex flex-row space-x-2 mt-2 items-center",children:[jsxs(K,{type:"button",onClick:L,className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay text-sm h-[1.875rem] px-3 ring-1 bg-purple-500 hover:bg-purple-500 hover:opacity-80 text-white ring-purple-500",children:[jsx(PlusIcon,{className:"size-3.5"}),"Add reasoning"]}),jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(Info,{className:"size-4 text-[#736982]"})}),jsxs(ze,{className:"max-w-xs flex flex-col",children:[jsx("p",{children:"A reasoning prompt adds an additional field during inference to give the LLM time to think."}),jsx("p",{children:"This is useful for challenging fields that require additional reasoning, such as unit conversions, intermediate computations, or complex logic."}),jsxs("a",{href:"https://docs.retab.com/core-concepts/Reasoning",className:"text-blue-300 mt-1 self-end flex flex-row items-center gap-1",children:["Learn more about reasoning"," ",jsx(ArrowRight,{className:"w-3 h-3"})]})]})]})]}):S?jsx(Sa,{control:N.control,name:"reasoningPrompt",render:({field:M})=>jsxs(Hn,{className:"group",children:[jsxs("div",{className:"flex justify-between items-center ",children:[jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(nr,{htmlFor:"reasoningPrompt",className:"text-sm font-medium text-gray-700 flex flex-row items-center cursor-pointer",children:"Reasoning Prompt"})}),jsxs(ze,{className:"max-w-xs",children:[jsx("p",{children:"A reasoning prompt adds an additional field during inference to give the LLM time to think."}),jsx("p",{children:"This is useful for challenging fields that require additional reasoning, such as unit conversions, intermediate computations, or complex logic."})]})]}),jsx("div",{className:"flex flex-row items-center gap-2 group-hover:opacity-100 transition-opacity duration-300 opacity-0",children:!e["X-ReasoningPrompt"]&&jsx(K,{type:"button",variant:"ghost",size:"sm",disabled:g==="readOnly",onClick:()=>{L();let j={...e,"X-ReasoningPrompt":""};t(j),N.setValue("reasoningPrompt","");},className:"h-6 w-6 p-0",children:jsx(X,{className:"h-4 w-4"})})})]}),jsx(Jn,{children:jsx(pr,{id:"reasoningPrompt",value:e["X-ReasoningPrompt"]||"",onChange:X$1,onBlur:M.onBlur,className:`before:bg-gradient-to-b before:from-white/20 ring ring-purple-300 w-full bg-purple-100 after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay h-24 rounded-md border px-3 py-2 text-sm file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-purple-200 disabled:cursor-not-allowed ${g==="readOnly"?"disabled:opacity-100":"disabled:opacity-50"}`,placeholder:"Add a reasoning prompt for this field",disabled:g==="readOnly"})})]})}):null]})]}),g!=="readOnly"&&jsxs("div",{className:"p-4 flex justify-between rounded-b-2xl",children:[jsx("div",{children:c&&g==="editable"&&jsx(K,{type:"button",variant:"outline",size:"sm",disabled:false,onClick:c,className:"text-red-600 hover:text-red-800 border-red-200 hover:border-red-300",children:"Delete Property"})}),jsxs("div",{className:"flex space-x-2",children:[l&&(f?jsx(av,{asChild:true,children:jsx(K,{type:"button",variant:"outline",size:"sm",onClick:l,children:"Cancel"})}):jsx(K,{type:"button",variant:"outline",size:"sm",onClick:l,children:"Cancel"})),h?jsx(av,{asChild:true,children:jsx(K,{type:"submit",size:"sm",className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay text-sm h-[1.875rem] px-3 ring-1 bg-gray-900 hover:bg-gray-900 hover:opacity-80 text-white ring-gray-900",disabled:ae||!!C||!!N.formState.errors.name,children:u})}):jsx(K,{type:"submit",size:"sm",className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay text-sm h-[1.875rem] px-3 ring-1 bg-gray-900 hover:bg-gray-900 hover:opacity-80 text-white ring-gray-900",disabled:ae||!!C||!!N.formState.errors.name,children:u})]})]})]})})}function xc({property:e,propertyKey:t,setDropdownOpen:r,jsonSchema:n,setJsonSchema:a,editMode:o="editable"}){let[i,s]=useState(()=>t.split(".")?.pop()||t),[l,c]=useState(e||r6),[u,d]=useState({...n}),[g,f]=useState(null);return useEffect(()=>{d({...n});},[n]),jsx(sv,{editedProperty:l,setEditedProperty:c,setJsonSchema:a,editedJsonSchema:u,setEditedJsonSchema:d,editedName:i,setEditedName:s,onSubmit:()=>{if(g)return;let p={...l,title:Ya(i)},v=mE(u,t,i,p);a(v),r(false);},onCancel:()=>{r(false);},submitLabel:"Save Changes",onNameError:f,editMode:o,fieldPathOverride:t,wrapCancelInDialogClose:true,wrapSubmitInDialogClose:true})}var r6={type:"string",description:""};var i6=cva("inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function xn({className:e,variant:t,asChild:r=false,...n}){return jsx(r?Slot:"span",{"data-slot":"badge",className:R(i6({variant:t}),e),...n})}function Ri({...e}){return jsx(Rr.Root,{"data-slot":"alert-dialog",...e})}function l6({...e}){return jsx(Rr.Portal,{"data-slot":"alert-dialog-portal",...e})}function c6({className:e,...t}){return jsx(Rr.Overlay,{"data-slot":"alert-dialog-overlay",className:R("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function Oi({className:e,...t}){return jsxs(l6,{children:[jsx(c6,{}),jsx(Rr.Content,{"data-slot":"alert-dialog-content",className:R("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...t})]})}function Di({className:e,...t}){return jsx("div",{"data-slot":"alert-dialog-header",className:R("flex flex-col gap-2 text-center sm:text-left",e),...t})}function Ai({className:e,...t}){return jsx("div",{"data-slot":"alert-dialog-footer",className:R("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function $i({className:e,...t}){return jsx(Rr.Title,{"data-slot":"alert-dialog-title",className:R("text-lg font-semibold",e),...t})}function Ii({className:e,...t}){return jsx(Rr.Description,{"data-slot":"alert-dialog-description",className:R("text-muted-foreground text-sm",e),...t})}function Fi({className:e,...t}){return jsx(Rr.Action,{className:R(cs(),e),...t})}function wc({className:e,...t}){return jsx(Rr.Cancel,{className:R(cs({variant:"outline"}),e),...t})}function cm(e){let t=e.match(/\.\*/g),r=t?t.length:0;return {path:e,level:r,hasArray:r>0}}function vv(e,t){let r=cm(e),n=cm(t);return r.level<=n.level}function d6(e,t){let r=cm(e),n=cm(t);return r.level-n.level===1}function Fo(e,t){console.log("[CONTEXT DEBUG] Finding cursor context:",{formula:e,cursorPosition:t});let r={isInsideAggregation:false,aggregationDepth:0},n=e.substring(0,t),a=["SUM","AVERAGE","MIN","MAX","COUNT","FILTER","LOOKUP","MATCH","FLATTEN"],o=null,i=-1;for(let s of a){let l=0;for(;l<n.length;){let c=n.indexOf(s+"(",l);if(c===-1)break;console.log(`[CONTEXT DEBUG] Found ${s} at funcIndex:`,c);let u=e.substring(c+s.length),d=0,g=false,f=0,h="",m=c+s.length+1;for(let p=0;p<u.length;p++){let v=c+s.length+p;if(u[p]==="(")d++;else if(u[p]===")"){if(d--,d===0){console.log(`[CONTEXT DEBUG] Found closing paren at absolutePos ${v}, cursor at ${t}`),v>=t&&(console.log("[CONTEXT DEBUG] Cursor is before/at closing paren, setting isInside=true"),g=true);break}}else u[p]===","&&d===1&&v<t&&(f===0&&(h=e.substring(m,v).trim()),f++,m=v+1,console.log(`[CONTEXT DEBUG] Found comma at ${v}, now at argument ${f}`));if(v===t&&d>0){console.log(`[CONTEXT DEBUG] Cursor at absolutePos ${v}, parenCount ${d}, setting isInside=true`),g=true;break}if(v>t&&d>0){console.log(`[CONTEXT DEBUG] Passed cursor at absolutePos ${v}, parenCount ${d}, setting isInside=true`),g=true;break}}if(d>0&&t>c+s.length&&(g=true),g){if(f===0&&h===""){let v=e.substring(m,t).trim();v&&!v.match(/[+\-*/()]/)&&(h=v);}let p={isInsideAggregation:true,aggregationDepth:1,functionName:s,argumentIndex:f,firstArgument:h||void 0};c>i&&(i=c,o=p,console.log("[CONTEXT DEBUG] New best context at funcIndex",c,":",p));}l=c+1;}}return o?(console.log("[CONTEXT DEBUG] Returning best (innermost) context:",o),o):(console.log("[CONTEXT DEBUG] Returning default context (not inside aggregation)"),r)}function f6(e,t,r){return t.isInsideAggregation?e.filter(n=>d6(n,r)):e.filter(n=>vv(n,r))}function bv(e,t,r,n){let a=Fo(e,t);return f6(r,a,n||"")}var m6={SUM:2,AVERAGE:2,MIN:2,MAX:2,COUNT:2,LOOKUP:6,MATCH:5,FILTER:4,FLATTEN:2,CONCAT:-1,ABS:1,SQRT:1,LOG:2,POW:2,IF:3,NOT:1,GT:2,GTE:2,LT:2,LTE:2};function _c(e,t="",r="",n){let a=[];if(!e)return a;let o=n||e;if(e.type==="object"&&e.properties)for(let[i,s]of Object.entries(e.properties)){let l=t?`${t}.${i}`:i,c=Vt(s,o);if(c.type!=="object"&&c.type!=="array")a.push(l);else if(c.type==="object")a.push(..._c(c,l,r,o));else if(c.type==="array"&&c.items){a.push(l);let u=Vt(c.items,o);if(u.type==="object"){let d=_c(u,`${l}.*`,r,o);a.push(...d);}else a.push(`${l}.*`);}}return a}function h6(e){return {SUM:{arguments:[{name:"array"},{name:"field",optional:true}],description:"Sum array values",example:"SUM(items, price)"},AVERAGE:{arguments:[{name:"array"},{name:"field",optional:true}],description:"Calculate average of array values",example:"AVERAGE(items, score)"},MIN:{arguments:[{name:"array or values"},{name:"field",optional:true}],description:"Find minimum value in array or among multiple values",example:"MIN(items, price) or MIN(10, 20, 30)"},MAX:{arguments:[{name:"array or values"},{name:"field",optional:true}],description:"Find maximum value in array or among multiple values",example:"MAX(items, price) or MAX(10, 20, 30)"},FILTER:{arguments:[{name:"array"},{name:"field"},{name:"operator"},{name:"value"}],description:"Filter array by condition, returning matching elements",example:'FILTER(items, price, ">", 100)'},FLATTEN:{arguments:[{name:"array"},{name:"field",optional:true}],description:"Flatten nested arrays or extract and flatten field from array elements",example:'FLATTEN(nested_arrays) or FLATTEN(groups, "items")'},LOOKUP:{arguments:[{name:"array"},{name:"field"},{name:"operator"},{name:"value"},{name:"projection",optional:true},{name:"mode",optional:true}],description:"Find first matching element in array",example:'LOOKUP(items, id, "=", 5, name)'},MATCH:{arguments:[{name:"array"},{name:"field"},{name:"operator"},{name:"value"},{name:"mode",optional:true}],description:"Find index of first matching element (0-based)",example:'MATCH(items, status, "=", "active")'},COUNT:{arguments:[{name:"array"},{name:"value"}],description:"Count occurrences of a value in an array",example:'COUNT(items, "completed")'},IF:{arguments:[{name:"condition"},{name:"value_if_true"},{name:"value_if_false"}],description:"Conditional - returns value based on condition",example:'IF(price > 100, "expensive", "affordable")'},CONCAT:{arguments:[{name:"values..."}],description:"Concatenate multiple values as strings",example:'CONCAT("Hello ", name, "!")'},ABS:{arguments:[{name:"value"}],description:"Return absolute value",example:"ABS(-10)"},SQRT:{arguments:[{name:"value"}],description:"Return square root",example:"SQRT(25)"},LOG:{arguments:[{name:"value"},{name:"base",optional:true}],description:"Return logarithm (natural log or custom base)",example:"LOG(100, 10)"},POW:{arguments:[{name:"base"},{name:"exponent"}],description:"Raise base to exponent power",example:"POW(2, 3)"},NOT:{arguments:[{name:"value"}],description:"Logical NOT operation",example:"NOT(condition)"},GT:{arguments:[{name:"left"},{name:"right"}],description:"Greater than comparison",example:"GT(price, 100)"},GTE:{arguments:[{name:"left"},{name:"right"}],description:"Greater than or equal comparison",example:"GTE(quantity, 10)"},LT:{arguments:[{name:"left"},{name:"right"}],description:"Less than comparison",example:"LT(age, 18)"},LTE:{arguments:[{name:"left"},{name:"right"}],description:"Less than or equal comparison",example:"LTE(score, 100)"}}[e]||null}function um(e,t){let r=t,n=t;for(;r>0;){let a=e[r-1];if(/[a-zA-Z0-9_.]/.test(a))r--;else if(a==="*"&&r>=2&&e[r-2]===".")r--;else break}for(;n<e.length;){let a=e[n];if(/[a-zA-Z0-9_]/.test(a))n++;else if(a==="."&&n+1<e.length)n++,e[n]==="*"&&n++;else break}return {word:e.substring(r,n),start:r,end:n}}function dm(e,t,r,n,a="",o=0){let i=[],s=e.toLowerCase();function l(y,x){let w=Vt(y,y);if(!w)return null;let _=x.split(".");for(let E of _){if(!w)return null;let C=Vt(w,y);if(E==="*")if(C&&C.type==="array"&&C.items)w=Vt(C.items,y);else return null;else if(C&&C.type==="object"&&C.properties&&C.properties[E])w=Vt(C.properties[E],y);else return null}return w}function c(y,x){if(!y)return null;let w=Vt(y,x),_=w?.type,E=P=>{let T=Vt(P,x),N=T?.type;if(Array.isArray(N)&&N.length>0)return N.join("|");if(N==="array"){let S=T?.items;return `array<${(S?E(S):null)??"any"}>`}return N==="object"?"object":N==="string"?typeof T?.format=="string"&&T.format.length>0?T.format:Array.isArray(T?.enum)?"enum":"string":N==="number"||N==="integer"||N==="boolean"||N==="null"?N:Array.isArray(T?.enum)?"enum":null},C=w?.anyOf||w?.oneOf;if(Array.isArray(C)&&C.length>0){let P=Array.from(new Set(C.map(T=>E(T)).filter(Boolean)));if(P.length>0)return P.join("|")}if(Array.isArray(_)&&_.length>0)return _.join("|");if(_==="array"){let P=w?.items;return `array<${(P?E(P):null)??"any"}>`}return typeof _=="string"&&_.length>0?_==="string"&&typeof w?.format=="string"&&w.format.length>0?w.format:_:w?.enum?"enum":null}let u=Fo(a,o);console.log("[AUTOCOMPLETE DEBUG] Context:",{formula:a,cursorPosition:o,functionName:u.functionName,argumentIndex:u.argumentIndex,isInsideAggregation:u.isInsideAggregation,firstArgument:u.firstArgument});let d=u.functionName&&(u.functionName==="SUM"||u.functionName==="AVERAGE"||u.functionName==="FILTER"||u.functionName==="LOOKUP"||u.functionName==="MATCH"||u.functionName==="FLATTEN")&&u.argumentIndex===0,g=u.functionName&&(u.functionName==="FILTER"&&u.argumentIndex===2||u.functionName==="MATCH"&&u.argumentIndex===2||u.functionName==="LOOKUP"&&u.argumentIndex===2),f=u.functionName&&(u.functionName==="FILTER"&&u.argumentIndex===3||u.functionName==="MATCH"&&u.argumentIndex===3||u.functionName==="LOOKUP"&&u.argumentIndex===3),h=u.functionName&&((u.functionName==="SUM"||u.functionName==="AVERAGE"||u.functionName==="MIN"||u.functionName==="MAX")&&u.argumentIndex===1||u.functionName==="FLATTEN"&&u.argumentIndex===1||u.functionName==="LOOKUP"&&u.argumentIndex===4||(u.functionName==="FILTER"||u.functionName==="MATCH")&&u.argumentIndex===1);if(g){let y=[{value:'"="',display:"=",description:"Equal to"},{value:'"!="',display:"!=",description:"Not equal to"},{value:'">"',display:">",description:"Greater than"},{value:'">="',display:">=",description:"Greater than or equal to"},{value:'"<"',display:"<",description:"Less than"},{value:'"<="',display:"<=",description:"Less than or equal to"},{value:'"contains"',display:"contains",description:"Contains substring (case-insensitive)"}];for(let x of y)(x.display.toLowerCase().includes(s)||x.value.toLowerCase().includes(s))&&i.push({value:x.value,display:x.display,category:"operator",description:x.description});return i}if(f&&u.firstArgument){let y=u.firstArgument.replace(/['"]/g,"").trim(),x=new RegExp(`${u.functionName}\\s*\\(\\s*[^,]+,\\s*([^,]+)`,"i"),w=a.match(x);if(w&&w[1]){let _=w[1].replace(/['"]/g,"").trim();console.log("[AUTOCOMPLETE DEBUG] Value arg - checking for enum:",{arrayPath:y,keyField:_});let E=l(t,y);if(E&&E.type==="array"&&E.items){let C=Vt(E.items,t);if(C&&C.type==="object"&&C.properties){let P=l(C,_);if(P){let T=Vt(P,t),N=[];if(Array.isArray(T?.enum))N=T.enum;else if(Array.isArray(T?.anyOf))for(let S of T.anyOf){let b=Vt(S,t);Array.isArray(b?.enum)&&N.push(...b.enum);}else if(Array.isArray(T?.oneOf))for(let S of T.oneOf){let b=Vt(S,t);Array.isArray(b?.enum)&&N.push(...b.enum);}if(N=Array.from(new Set(N.filter(S=>S!=null))),console.log("[AUTOCOMPLETE DEBUG] Found enum values:",N),N.length>0){for(let S of N){let b=String(S);b.toLowerCase().includes(s)&&i.push({value:`"${b}"`,display:b,category:"field",description:"Enum value",typeBadge:"enum"});}return i}}}}}return []}if(!d&&!g&&!f&&!h){let y=[{value:"SUM",display:"SUM()",description:"Sum array values: SUM(arrayPath, [fieldPath])"},{value:"AVERAGE",display:"AVERAGE()",description:"Calculate average of array values: AVERAGE(arrayPath, [fieldPath])"},{value:"MIN",display:"MIN()",description:"Find the minimum value in an array: MIN(arrayPath, [fieldPath])"},{value:"MAX",display:"MAX()",description:"Find the maximum value in an array: MAX(arrayPath, [fieldPath])"},{value:"COUNT",display:"COUNT",description:"Count occurrences of a value in an array"},{value:"LOOKUP",display:"LOOKUP()",description:"Find first matching element: LOOKUP(arrayPath, keyField, comparator, value, [projection], [mode])"},{value:"MATCH",display:"MATCH()",description:"Find index of first matching element: MATCH(arrayPath, keyField, comparator, value, [mode])"},{value:"FILTER",display:"FILTER()",description:"Filter array by condition: FILTER(arrayPath, keyField, comparator, value)"},{value:"FLATTEN",display:"FLATTEN()",description:"Flatten nested arrays: FLATTEN(arrayPath) or FLATTEN(arrayPath, fieldPath)"},{value:"CONCAT",display:"CONCAT()",description:"Concatenate multiple values"},{value:"ABS",display:"ABS()",description:"Return the absolute value of a number or array"},{value:"SQRT",display:"SQRT()",description:"Return the square root of a number or array"},{value:"LOG",display:"LOG()",description:"Return the natural logarithm (or logarithm with custom base) of a number or array"},{value:"POW",display:"POW()",description:"Raise base to exponent (base^exponent)"},{value:"IF",display:"IF()",description:"Conditional - returns value_if_true if condition is truthy, otherwise value_if_false"},{value:"NOT",display:"NOT()",description:"Logical NOT - returns true if operand is falsy, false if truthy"},{value:"GT",display:"GT()",description:"Compare two values - returns true if first is greater than second"},{value:"GTE",display:"GTE()",description:"Compare two values - returns true if first is greater than or equal to second"},{value:"LT",display:"LT()",description:"Compare two values - returns true if first is less than second"},{value:"LTE",display:"LTE()",description:"Compare two values - returns true if first is less than or equal to second"}];for(let x of y)x.value.toLowerCase().includes(s)&&i.push({value:x.value,display:x.display,category:"function",description:x.description});}let m=_c(t,"",n,t),p=[];if(d){console.log("[AUTOCOMPLETE DEBUG] First array arg filtering:"),console.log(" Target path:",n);let y=n.split(".*").length-1;console.log(" Target path level:",y),console.log(" All field paths count:",m.length),p=m.filter(x=>{let w=l(t,x),_=w&&w.type==="array",E=x.split(".*").length-1,C=E<=y;return console.log(` Path: ${x}, level: ${E}, isArray: ${_}, nodeType: ${w?.type}, isAtSameLevelOrHigher: ${C}`),_&&C}),console.log(" Final paths to suggest:",p);}else u.functionName==="MIN"||u.functionName==="MAX"?(console.log("[AUTOCOMPLETE DEBUG] MIN/MAX filtering - showing all paths at same level or higher"),p=m.filter(y=>vv(y,n))):p=bv(a,o,m,n);let v=null;if(h)if(console.log("[AUTOCOMPLETE DEBUG] Projection/KeyField arg filtering:"),console.log(" isProjectionArg:",h),console.log(" functionName:",u.functionName),console.log(" detailedContext.firstArgument:",u.firstArgument),console.log(" detailedContext.argumentIndex:",u.argumentIndex),u.firstArgument){let y=u.firstArgument.replace(/['"]/g,"").trim();if(y.startsWith("FLATTEN")&&y.includes("(")){let x=y.indexOf("("),w=0,_=-1;for(let E=x;E<y.length&&(y[E]==="("?w++:y[E]===")"?w--:y[E]===","&&w===1&&_===-1&&(_=E),w!==0);E++);if(_>-1){let E=y.substring(x+1,_).trim(),C=y.length-1;w=0;for(let b=x;b<y.length;b++)if(y[b]==="(")w++;else if(y[b]===")"&&(w--,w===0)){C=b;break}let P=y.substring(_+1,C).trim(),T=E,N=E.match(/^(FILTER|LOOKUP|MATCH)\s*\(\s*([^,]+)/i);N&&N[2]&&(T=N[2].trim()),console.log(" Detected FLATTEN with field:",P,"from array:",T);let S=l(t,T);if(S&&S.type==="array"&&S.items){let b=Vt(S.items,t),k=l(b,P);if(k&&k.type==="array"&&k.items){let D=Vt(k.items,t);if(D&&D.type==="object"&&D.properties){let O=[];for(let[$,A]of Object.entries(D.properties)){let F=Vt(A,t);if(F.type!=="object"&&F.type!=="array")O.push($);else if(F.type==="object"){let X=_c(F,$,"",t);O.push(...X);}}console.log(" FLATTEN result field paths:",O),p=O,v=D,y="";}}}}}if(y&&y!==""){let x=y.match(/^(FILTER|LOOKUP|MATCH)\s*\(\s*([^,]+)/i);x&&x[2]&&(y=x[2].trim(),console.log(" Extracted array path from function call:",y));}if(console.log(" arrayPath:",y),y&&y!==""){let x=l(t,y);if(console.log(" arraySchema type:",x?.type),x&&x.type==="array"&&x.items){let w=Vt(x.items,t);if(console.log(" itemsSchema type:",w?.type),w&&w.type==="object"&&w.properties){let _=[],E=u.functionName==="FLATTEN"&&u.argumentIndex===1;for(let[C,P]of Object.entries(w.properties)){let T=Vt(P,t);if(E)T.type==="array"&&_.push(C);else if(T.type!=="object"&&T.type!=="array")_.push(C);else if(T.type==="object"){let N=_c(T,C,"",t);_.push(...N);}}console.log(" itemFieldPaths:",_),p=_,v=w;}}}}else console.log(" No firstArgument captured!");console.log("[AUTOCOMPLETE DEBUG] Final pathsToSuggest before building suggestions:",p),console.log("[AUTOCOMPLETE DEBUG] isProjectionArg:",h,"isFirstArrayArg:",d);for(let y of p)if(y.toLowerCase().includes(s)){let x=v||t,w=l(x,y),_=c(w,x)||void 0;i.push({value:y,display:y,category:"field",description:"Schema field",typeBadge:_});}if(!d&&!g&&!f&&!h){let y=r.filter(w=>w!==n),x=bv(a,o,y,n);for(let w of x)w.toLowerCase().includes(s)&&i.push({value:w,display:w,category:"computed",description:"Computed field"});}return i.sort((y,x)=>{let w={field:1,computed:2,function:3,operator:4},_=w[y.category]||999,E=w[x.category]||999;if(_!==E)return _-E;let C=y.value.toLowerCase(),P=x.value.toLowerCase();if(C===s)return -1;if(P===s)return 1;let T=C.startsWith(s),N=P.startsWith(s);return T&&!N?-1:!T&&N?1:y.value.localeCompare(x.value)}),i.slice(0,10)}function g6(e,t,r,n){if(!e)return [];let a=_c(t,"",n,t),o=new Set([...a,...r.filter(i=>i!==n)]);try{let s=new _s(e).tokenize(),l=[],c=0,u=[],d=0;for(let g=0;g<s.length;g++){let f=s[g];if(f.type==="EOF")break;f.type==="FUNCTION"?u.push({name:f.value,depth:d+1,argumentIndex:0}):f.type==="LPAREN"?d++:f.type==="RPAREN"?(d--,u.length>0&&u[u.length-1].depth>d&&u.pop()):f.type==="COMMA"&&u.length>0&&u[u.length-1].depth===d&&u[u.length-1].argumentIndex++;let h="",m=c;if(f.type==="STRING"){for(;m<e.length&&e[m]!=='"'&&e[m]!=="'";)m++;let v=e[m],y=m+1;for(;y<e.length;)if(e[y]==="\\")y+=2;else if(e[y]===v){y++;break}else y++;h=e.substring(m,y);}else {let v=f.value;m=e.indexOf(v,c),m===-1&&(m=c),h=e.substring(m,m+v.length);}if(m>c){let v=e.substring(c,m);l.push(jsx("span",{className:"text-xs text-gray-900 dark:text-gray-100",children:v},`ws-${g}`));}let p="text-xs text-gray-900 dark:text-gray-100";switch(f.type){case "NUMBER":p="text-xs text-amber-600 dark:text-amber-400";break;case "STRING":p="text-xs text-emerald-600 dark:text-emerald-400";break;case "BOOLEAN":p="text-xs text-green-600 dark:text-green-400";break;case "NULL":p="text-xs text-gray-500 dark:text-gray-500";break;case "FUNCTION":p="text-xs text-purple-600 dark:text-purple-400 font-semibold";break;case "IDENTIFIER":let v=!1;if(u.length>0){let y=u[u.length-1],x=y.name,w=y.argumentIndex;x==="SUM"||x==="AVERAGE"||x==="MIN"||x==="MAX"||x==="FLATTEN"?v=w===1:x==="LOOKUP"?v=w===1||w===2||w===4||w===5:(x==="MATCH"||x==="FILTER")&&(v=w===1||w===2||x==="MATCH"&&w===4);}o.has(f.value)?p="text-xs text-blue-600 dark:text-blue-400":v?p="text-xs text-cyan-600 dark:text-cyan-400":p="text-xs text-red-600 dark:text-red-400";break;case "PLUS":case "MINUS":case "MULTIPLY":case "DIVIDE":p="text-xs text-gray-600 dark:text-gray-400";break;case "LPAREN":case "RPAREN":case "COMMA":p="text-xs text-gray-500 dark:text-gray-500";break}l.push(jsx("span",{className:p,children:h},`token-${g}`)),c=m+h.length;}if(c<e.length){let g=e.substring(c);l.push(jsx("span",{className:"text-xs text-gray-900 dark:text-gray-100",children:g},"remaining"));}return l}catch{return [jsx("span",{className:"text-xs text-gray-900 dark:text-gray-100",children:e},"error")]}}function RE({value:e,onChange:t,onBlur:r,schema:n,computedFields:a,targetPath:o,placeholder:i,disabled:s=false}){let l=Rt.useRef(null),c=Rt.useRef(null),[u,d]=Rt.useState(false),[g,f]=Rt.useState([]),[h,m]=Rt.useState(0),[p,v]=Rt.useState(0),[y,x]=Rt.useState({word:"",start:0,end:0}),[w,_]=Rt.useState(false),[E,C]=Rt.useState(Fo("",0)),[P,T]=Rt.useState(false);Rt.useEffect(()=>{if(!l.current)return;let O=l.current.selectionStart||0;v(O);let $=um(e,O);x($);let A=Fo(e,O);C(A);let F=dm($.word,n,a,o,e,O);f(F),w&&F.length>0?(d(true),m(0)):w&&F.length===0&&d(false);},[e,n,a,o,w]);let N=O=>{if(!(O.key==="Enter"&&O.shiftKey)&&!(!u||g.length===0))switch(O.key){case "ArrowDown":O.preventDefault(),m($=>Math.min($+1,g.length-1));break;case "ArrowUp":O.preventDefault(),m($=>Math.max($-1,0));break;case "Tab":u&&g[h]&&(O.preventDefault(),S(g[h]));break;case "Enter":u&&g[h]&&(O.preventDefault(),S(g[h]));break;case "Escape":O.preventDefault(),d(false);break}},S=O=>{let $=e.substring(0,y.start),A=e.substring(y.end),F=O.value,X=false,H=false;if(O.category==="function")O.value==="COUNT"?F=`${O.value}(, "")`:F=`${O.value}()`;else {let z=Fo(e,p);if(z.functionName){let ae=m6[z.functionName],M=z.argumentIndex??0,j=A.trimStart(),ue=j.startsWith(")"),ie=j.startsWith(",");!ue&&!ie&&(ae===-1||M<ae-1?H=true:X=true);}}let L=H?", ":X?")":"",Q=$+F+L+A;t(Q),d(false),setTimeout(()=>{if(l.current)if(l.current.focus(),O.category==="function"){let z=$.length+F.length-1;l.current.setSelectionRange(z,z);}else {let z=$.length+F.length+L.length;l.current.setSelectionRange(z,z);}},0);},b=O=>{_(true),t(O.target.value);};Rt.useEffect(()=>{let O=$=>{c.current&&!c.current.contains($.target)&&l.current&&!l.current.contains($.target)&&d(false);};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[]),Rt.useEffect(()=>{if(u&&c.current){let O=c.current.children[h];O&&O.scrollIntoView({block:"nearest",behavior:"smooth"});}},[h,u]);let k=O=>{switch(O){case "function":return "text-blue-600 dark:text-blue-400";case "field":return "text-green-600 dark:text-green-400";case "computed":return "text-purple-600 dark:text-purple-400";default:return "text-gray-600 dark:text-gray-400"}},D=O=>{switch(O){case "function":return "fn";case "field":return "field";case "computed":return "calc";default:return ""}};return jsxs("div",{className:"relative",children:[jsx("div",{className:"absolute inset-0 pointer-events-none overflow-hidden rounded-md px-[13px] py-[9px]",style:{whiteSpace:"pre-wrap",wordWrap:"break-word"},children:jsx("div",{className:"text-xs font-mono leading-[1.0rem]",children:g6(e,n,a,o)})}),jsx(pr,{ref:l,value:e,onChange:b,onKeyDown:N,disabled:s,onKeyUp:O=>{if(["ArrowLeft","ArrowRight","Home","End"].includes(O.key)){let $=l.current?.selectionStart||0;v($);let A=um(e,$);x(A);let F=Fo(e,$);C(F);let X=dm(A.word,n,a,o,e,$);f(X),w&&X.length>0&&(d(true),m(0));}else if(["ArrowUp","ArrowDown"].includes(O.key)&&!u){let $=l.current?.selectionStart||0;v($);let A=um(e,$);x(A);let F=Fo(e,$);C(F);let X=dm(A.word,n,a,o,e,$);f(X),w&&X.length>0&&(d(true),m(0));}},onClick:()=>{_(true);let O=l.current?.selectionStart||0;v(O);let $=um(e,O);x($);let A=Fo(e,O);C(A);let F=dm($.word,n,a,o,e,O);F.length>0&&(f(F),d(true),m(0));},onBlur:()=>{setTimeout(()=>{d(false),_(false),r?.();},200);},placeholder:i,className:R("min-h-[80px] border-none rounded-none leading-[1.0rem] resize-y relative font-mono !text-xs caret-gray-900 dark:caret-gray-100","text-transparent"),spellCheck:false}),u&&g.length>0&&jsxs("div",{ref:c,className:"absolute z-50 w-full -px-4 mt-1 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg max-h-60 overflow-y-auto",children:[E.functionName&&(()=>{let O=h6(E.functionName);if(!O)return null;let $=E.argumentIndex||0;return jsxs("div",{className:"sticky top-0 bg-gray-50 dark:bg-gray-900/20 border-b border-gray-200 dark:border-gray-800",children:[jsxs("button",{type:"button",onMouseDown:A=>{A.preventDefault();},onClick:A=>{A.preventDefault(),A.stopPropagation(),T(!P);},className:"w-full px-3 py-2 text-left hover:bg-blue-100 dark:hover:bg-blue-900/30 transition-colors flex items-start gap-2",children:[jsx(ChevronDown,{className:R("w-4 h-4 text-gray-500 dark:text-gray-400 mt-0.5 transition-transform flex-shrink-0",P&&"transform rotate-180")}),jsx("div",{className:"flex-1 min-w-0",children:jsxs("div",{className:"font-mono text-xs flex flex-wrap items-center gap-1",children:[jsx("span",{className:"font-semibold text-purple-700 dark:text-purple-300",children:E.functionName}),jsx("span",{className:"text-gray-500",children:"("}),O.arguments.map((A,F)=>jsxs(Rt.Fragment,{children:[F>0&&jsx("span",{className:"text-gray-500",children:","}),jsxs("span",{className:R("px-1 rounded",F===$?"bg-gray-200 dark:bg-gray-700 font-bold text-gray-900 dark:text-gray-100":"text-gray-700 dark:text-gray-300"),children:[A.name,A.optional&&jsx("span",{className:"text-gray-400",children:"?"})]})]},F)),jsx("span",{className:"text-gray-500",children:")"})]})})]}),P&&jsx("div",{className:"px-3 py-2 border-t border-gray-200 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-900/10",children:jsxs("div",{className:"text-xs space-y-2",children:[jsxs("div",{children:[jsx("span",{className:"font-semibold text-gray-700 dark:text-gray-300",children:"Description:"}),jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-0.5",children:O.description})]}),jsxs("div",{children:[jsx("span",{className:"font-semibold text-gray-700 dark:text-gray-300",children:"Example:"}),jsx("code",{className:"block mt-0.5 text-gray-600 dark:text-gray-400 bg-white dark:bg-gray-800 px-2 py-1 rounded",children:O.example})]})]})})]})})(),g.map((O,$)=>jsxs("div",{className:`
60
61
  px-3 py-2 cursor-pointer flex items-center gap-2
61
- ${I===y?"bg-blue-50 dark:bg-blue-900/20":"hover:bg-gray-50 dark:hover:bg-gray-800"}
62
- `,onClick:()=>C(k),children:[jsx("span",{className:`
62
+ ${$===h?"bg-blue-50 dark:bg-blue-900/20":"hover:bg-gray-50 dark:hover:bg-gray-800"}
63
+ `,onClick:()=>S(O),children:[jsx("span",{className:`
63
64
  text-xs font-mono px-1.5 py-0.5 rounded
64
65
  bg-gray-100 dark:bg-gray-800 flex-shrink-0
65
- ${O(k.category)}
66
- `,children:D(k.category)}),jsx("div",{className:"flex-1 min-w-0",children:jsx("div",{className:"text-xs text-gray-900 dark:text-gray-100",children:k.display})}),k.category==="field"&&k.typeBadge&&jsx("span",{className:"ml-auto text-[10px] px-1.5 py-0.5 rounded bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-gray-700 flex-shrink-0",children:k.typeBadge})]},`${k.category}-${k.value}-${I}`))]})]})}function Wl({fieldPath:e,jsonSchema:t,computationSpec:r,setComputationSpec:n,onDelete:o,onClose:a,readOnly:i=false}){let s=r.computations[e];console.log("Rendering Computed Field Card"),console.log("Current Computation",s);let{prefix:l,suffix:c}=useMemo(()=>{let b=e.lastIndexOf(".");return b===-1?{prefix:"",suffix:e}:{prefix:e.substring(0,b),suffix:e.substring(b+1)}},[e]),[u,d]=useState(c),[m,h]=useState(s?.expression||""),[y,p]=useState(null),[f,x]=useState(null),g=useMemo(()=>l?`${l}.${u}`:u,[l,u]),v=kt.useRef(l);kt.useEffect(()=>{v.current!==l&&(h(""),v.current=l);},[l]),kt.useEffect(()=>{try{if(Object.keys(r.computations).length>0){let b=Su(r.computations);p(b);}else p(null);}catch{p(null);}},[r]);let w=useMemo(()=>y&&e?y[e]:null,[y,e]),N=useMemo(()=>Object.keys(r.computations).filter(b=>b!==e),[r.computations,e]);useMemo(()=>{let b={computations:{...r.computations}};if(m&&m.trim()!=="")try{let O=Tn(m);b.computations[g]={expression:m};}catch{}return b},[r,g,m,t]);let _=useMemo(()=>{let b=[];if(!u||u.trim()===""?b.push("Field name is required"):(u.includes(".")&&b.push("Field name cannot contain '.'"),(u.startsWith("_")||u.endsWith("_"))&&b.push("Field name should not start or end with '_'"),Object.keys(r.computations).filter(D=>D!==e).includes(g)&&b.push("This field path already has a computation")),!m||m.trim()==="")b.push("Expression is required");else {let O=new Set(Object.keys(r.computations).filter(k=>k!==e)),D=Hy(m,t,O);D.isValid||b.push(...D.errors);}return {isValid:b.length===0,errors:b}},[m,u,g,e,r,t]),P=()=>{if(f)try{let b={...r.computations};if(b[f.oldPath]){let O=Wy(b,f.oldPath,f.newPath);if(m&&m.trim()!==""){let D=Tn(m);O.updatedSpec[f.newPath]={expression:m};}else delete O.updatedSpec[f.newPath];n({computations:O.updatedSpec});}else {let O={...b};if(m&&m.trim()!==""){let D=Tn(m);O[f.newPath]={expression:m};}else delete O[f.newPath];n({computations:O});}x(null),a&&a();}catch(b){console.error(`Rename failed: ${b.message}`),x(null);}},R=()=>{f&&d(c),x(null);},E=()=>{if(!_.isValid)return;if(g!==e&&r.computations[e])try{let D=(y||Su(r.computations))[e]?.dependents||[];if(D.length>0){x({show:!0,oldPath:e,newPath:g,affectedComputations:[e,...D]});return}}catch(O){console.warn("Error checking dependencies for rename:",O);}let b={...r.computations};g!==e&&b[e]&&delete b[e],m&&m.trim()!==""?b[g]={expression:m}:delete b[g],n({computations:b}),a&&a();},C=()=>{let b={...r.computations};delete b[e],n({computations:b}),a&&a(),o&&o();};return jsxs("div",{className:"flex flex-col h-full bg-gray-50 rounded-2xl",children:[jsx("div",{className:"bg-white shadow-xs flex-1 overflow-y-auto max-h-[60vh] rounded-2xl",children:jsxs("div",{className:"p-4 space-y-4",children:[w&&w.depth>1&&jsxs("div",{className:"relative flex max-w-6xl justify-center items-center ring-1 ring-inset bg-blue-50 text-blue-600 ring-blue-600/20 gap-2 rounded-md p-2",children:[jsx(AlertCircle,{className:"size-3.5 stroke-2"}),jsxs("div",{className:"flex flex-1 flex-wrap items-center justify-between gap-x-3 gap-y-2",children:[jsx("div",{className:"text-xs font-normal",children:"This field is computed based on other fields"}),w&&jsxs(dn,{variant:"default",className:"text-xs",children:["Level ",w.depth]})]})]}),w&&(w.dependencies.length>0||w.dependents.length>0)&&jsxs("div",{className:"space-y-1.5 text-xs bg-muted/50 p-3 rounded-md border border-muted",children:[w.dependencies.length>0&&jsxs("div",{className:"flex items-start gap-1.5",children:[jsx(ArrowDown,{className:"h-3 w-3 mt-0.5 text-muted-foreground flex-shrink-0"}),jsxs("div",{className:"flex-1",children:[jsx("span",{className:"text-muted-foreground font-medium",children:"Depends on: "}),jsx("span",{className:"text-foreground",children:w.dependencies.join(", ")})]})]}),w.dependents.length>0&&jsxs("div",{className:"flex items-start gap-1.5",children:[jsx(ArrowRight,{className:"h-3 w-3 mt-0.5 text-muted-foreground flex-shrink-0"}),jsxs("div",{className:"flex-1",children:[jsx("span",{className:"text-muted-foreground font-medium",children:"Used by: "}),jsx("span",{className:"text-foreground",children:w.dependents.join(", ")})]})]})]}),jsxs("div",{children:[jsx(Yt,{className:"text-sm font-medium text-gray-700 mb-2 block",children:"Name"}),jsx("div",{className:"flex items-center gap-1",children:jsx(nt,{value:u,onChange:b=>{let O=b.target.value.replace(/[^a-zA-Z0-9_]/g,"");d(O);},placeholder:"field_name",className:"font-normal text-xs flex-1",disabled:i})})]}),jsxs("div",{className:"space-y-1.5",children:[jsx(Yt,{className:"text-sm font-medium text-gray-700",children:"Formula Expression"}),jsx("div",{className:"h-64 overflow-y-auto",children:jsx(zC,{value:m,onChange:h,schema:t,computedFields:N,targetPath:g,placeholder:"e.g., SUM(items.*.price) * 1.1 or (a + b) / c",disabled:i})}),!i&&jsxs("p",{className:"text-xs text-muted-foreground",children:["Start typing to see suggestions. Use ",jsx("kbd",{className:"px-1 py-0.5 text-[10px] font-mono bg-muted rounded",children:"\u2191"})," ",jsx("kbd",{className:"px-1 py-0.5 text-[10px] font-mono bg-muted rounded",children:"\u2193"})," to navigate, ",jsx("kbd",{className:"px-1 py-0.5 text-[10px] font-mono bg-muted rounded",children:"Enter"})," or ",jsx("kbd",{className:"px-1 py-0.5 text-[10px] font-mono bg-muted rounded",children:"Tab"})," to select"]})]}),!_.isValid&&jsxs("div",{className:"bg-destructive/10 border border-destructive/20 rounded p-2",children:[jsx("p",{className:"text-xs font-medium text-destructive mb-1",children:"Errors:"}),jsx("ul",{className:"text-xs text-destructive space-y-0.5",children:_.errors.map((b,O)=>jsxs("li",{children:["\u2022 ",b]},O))})]})]})}),!i&&jsxs("div",{className:"p-4 flex justify-between rounded-b-2xl",children:[jsx("div",{children:jsx(V,{type:"button",size:"sm",onClick:C,className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay ring-1 bg-destructive hover:bg-destructive hover:opacity-80 text-white ring-destructive gap-2",children:"Delete Computation"})}),jsx("div",{className:"flex items-center gap-2",children:jsx(V,{onClick:E,disabled:!_.isValid,size:"sm",className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay text-sm h-[1.875rem] px-3 ring-1 bg-gray-900 hover:bg-gray-900 hover:opacity-80 text-white ring-gray-900",children:"Save Changes"})})]}),jsx(vo,{open:f?.show,onOpenChange:b=>!b&&R(),children:jsxs(bo,{children:[jsxs(xo,{children:[jsx(_o,{children:"Cascade Rename Detected"}),jsxs(So,{children:["Renaming ",jsx("code",{className:"bg-muted px-1.5 py-0.5 rounded text-foreground font-medium",children:f?.oldPath})," to"," ",jsx("code",{className:"bg-muted px-1.5 py-0.5 rounded text-foreground font-medium",children:f?.newPath})," will affect"," ",jsxs("strong",{children:[(f?.affectedComputations.length||0)-1," other computation(s)"]}),"."]})]}),f&&f.affectedComputations.length>1&&jsxs("div",{className:"space-y-2 my-4",children:[jsx("p",{className:"text-sm font-medium",children:"The following computations will be updated:"}),jsx("div",{className:"bg-muted rounded-lg p-3 space-y-1.5 max-h-48 overflow-y-auto",children:f.affectedComputations.slice(1).map(b=>jsxs("div",{className:"flex items-start gap-2 text-xs",children:[jsx(ArrowRight,{className:"h-3 w-3 mt-0.5 text-muted-foreground flex-shrink-0"}),jsx("code",{className:"text-foreground",children:b})]},b))})]}),jsxs(wo,{children:[jsx(wa,{onClick:R,children:"Cancel"}),jsx(No,{onClick:P,children:"Confirm Rename"})]})]})})]})}var Kp=e=>{let t=e.split("."),r=t.pop()||"",n=t.join(".");return n?`${n}.reasoning___${r}`:`reasoning___${r}`},ev="__none__",Wu="__empty__",Hp=e=>{if(e==null)return ev;if(e==="")return Wu;let t=String(e);return t===""?Wu:t},JC=e=>e===ev?null:e===Wu?"":e,tv=kt__default.forwardRef(({className:e,variant:t,uncertainty:r,value:n,onValueChange:o,disabled:a,placeholder:i="Pick a date",size:s,scalarValueType:l},c)=>{let[u,d]=kt__default.useState(false),{setIsEditing:m}=yn();return jsx("div",{className:(()=>{switch(t){case "underline-close":return "border-b-2 pb-0";case "underline-distant":return "border-b-2 pb-2";case "left-border-close":return "border-l-4 pl-0";case "left-border-distant":return "border-l-4 pl-2";default:return ""}})(),style:(()=>{switch(t){case "underline-close":case "underline-distant":case "left-border-close":case "left-border-distant":return {borderColor:be(r,l)};default:return {}}})(),children:jsxs(nr,{open:u,onOpenChange:h=>{d(h),m(h);},children:[jsx(or,{asChild:true,children:jsxs(V,{ref:c,variant:"outline",disabled:a,className:T(e,s==="sm"?"h-[32px] text-sm":"h-[42px] text-sm","w-full justify-start text-left font-normal",!n&&"text-muted-foreground"),style:(()=>{switch(t){case "blur-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 2px 1px ${be(r,l)}`};case "blur-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 4px 2px ${be(r,l)}`};case "blur-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 6px 3px ${be(r,l)}`};case "outline-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 1px ${be(r,l)}`};case "outline-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 2px ${be(r,l)}`};case "outline-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 3px ${be(r,l)}`};default:return {}}})(),children:[n&&isValid(n)?format(n,"PPP"):i,jsx(CalendarIcon,{className:"ml-auto h-4 w-4 opacity-50"})]})}),jsx(ar,{className:"w-auto p-0",align:"start",children:jsx(ns,{mode:"single",selected:n&&isValid(n)?n:void 0,defaultMonth:n&&isValid(n)?n:void 0,onSelect:h=>{o?.(h||null),d(false),m(false);},captionLayout:"dropdown"})})]})})});tv.displayName="StyledDatePicker";var M9=kt__default.forwardRef(({className:e,variant:t,uncertainty:r,value:n,onValueChange:o,disabled:a,size:i,scalarValueType:s},l)=>{let{setIsEditing:c}=yn();return jsx("div",{className:(()=>{switch(t){case "underline-close":return "border-b-2 pb-0";case "underline-distant":return "border-b-2 pb-2";case "left-border-close":return "border-l-4 pl-0";case "left-border-distant":return "border-l-4 pl-2";default:return ""}})(),style:(()=>{switch(t){case "underline-close":case "underline-distant":case "left-border-close":case "left-border-distant":return {borderColor:be(r,s)};default:return {}}})(),children:jsx(nt,{ref:l,type:"time",disabled:a,value:n||"",onClick:()=>{c(true);},onChange:u=>{c(true),o?.(u.target.value);},onBlur:()=>{c(false);},className:T(e,i==="sm"?"h-[32px] text-sm":"h-[42px] text-sm","bg-background appearance-none [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-calendar-picker-indicator]:appearance-none"),style:(()=>{switch(t){case "blur-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 2px 1px ${be(r,s)}`};case "blur-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 4px 2px ${be(r,s)}`};case "blur-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 6px 3px ${be(r,s)}`};case "outline-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 1px ${be(r,s)}`};case "outline-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 2px ${be(r,s)}`};case "outline-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 3px ${be(r,s)}`};default:return {}}})()})})});M9.displayName="StyledTimePicker";var WC=kt__default.forwardRef(({className:e,variant:t,uncertainty:r,value:n,onValueChange:o,disabled:a,size:i,scalarValueType:s},l)=>{let{setIsEditing:c}=yn(),u=tE(n),d=u&&isValid(u)?new Date(u.getFullYear(),u.getMonth(),u.getDate()):null,m=u&&isValid(u)?`${u.getHours().toString().padStart(2,"0")}:${u.getMinutes().toString().padStart(2,"0")}`:"",[h,y]=kt__default.useState(m);kt__default.useEffect(()=>{y(m);},[m]);let p=x=>{if(!x){o?.(null);return}let g=m||"00:00:00",[v,w,N]=g.split(":").map(Number),S=new Date(x);S.setHours(v,w,N||0);let _=S.getFullYear(),P=(S.getMonth()+1).toString().padStart(2,"0"),R=S.getDate().toString().padStart(2,"0"),E=S.getHours().toString().padStart(2,"0"),C=S.getMinutes().toString().padStart(2,"0"),b=S.getSeconds().toString().padStart(2,"0");o?.(`${_}-${P}-${R}T${E}:${C}:${b}`);},f=x=>{if(!d&&!x){o?.(null);return}let g=d||new Date,[v,w,N]=x.split(":").map(Number),S=new Date(g);S.setHours(v,w,N||0);let _=S.getFullYear(),P=(S.getMonth()+1).toString().padStart(2,"0"),R=S.getDate().toString().padStart(2,"0"),E=S.getHours().toString().padStart(2,"0"),C=S.getMinutes().toString().padStart(2,"0"),b=S.getSeconds().toString().padStart(2,"0");o?.(`${_}-${P}-${R}T${E}:${C}:${b}`);};return jsxs("div",{ref:l,className:"flex gap-2",children:[jsx(tv,{variant:t,uncertainty:r,value:d,onValueChange:p,disabled:a,className:e,size:i,placeholder:"Select date",scalarValueType:s}),jsx("div",{className:(()=>{switch(t){case "underline-close":return "border-b-2 pb-0";case "underline-distant":return "border-b-2 pb-2";case "left-border-close":return "border-l-4 pl-0";case "left-border-distant":return "border-l-4 pl-2";default:return ""}})(),style:(()=>{switch(t){case "underline-close":case "underline-distant":case "left-border-close":case "left-border-distant":return {borderColor:be(r,s)};default:return {}}})(),children:jsx(Jp,{type:"time",disabled:a,value:h||"",onChange:x=>{y(x.target.value);},onBlur:x=>{let g=h;x.target.value&&/^\d{1,2}:\d{2}$/.test(x.target.value)&&(g=x.target.value+":00",y(g)),f(g);},className:T(e,i==="sm"?"h-[32px] text-sm":"h-[42px] text-sm","bg-background"),style:(()=>{switch(t){case "blur-small":return {boxShadow:`0 0 2px 1px ${be(r,s)}`};case "blur-large":return {boxShadow:`0 0 4px 2px ${be(r,s)}`};case "blur-xlarge":return {boxShadow:`0 0 6px 3px ${be(r,s)}`};case "outline-small":return {boxShadow:`0 0 0 1px ${be(r,s)}`};case "outline-large":return {boxShadow:`0 0 0 2px ${be(r,s)}`};case "outline-xlarge":return {boxShadow:`0 0 0 3px ${be(r,s)}`};default:return {}}})(),variant:t,uncertainty:r,scalarValueType:s})})]})});WC.displayName="StyledDateTimePicker";var KC=(e,t,r={})=>async(n,o,a)=>({values:n,errors:{}});function GC(e,t){let r=JSON.parse(JSON.stringify(t));return "description"in e&&(r.description=e.description),"X-ReasoningPrompt"in e?r["X-ReasoningPrompt"]=e["X-ReasoningPrompt"]:"X-ReasoningPrompt"in t&&(r["X-ReasoningPrompt"]=t["X-ReasoningPrompt"]),"X-EnumTranslation"in e?r["X-EnumTranslation"]=e["X-EnumTranslation"]:"X-EnumTranslation"in t&&(r["X-EnumTranslation"]=t["X-EnumTranslation"]),"X-FieldTranslation"in e?r["X-FieldTranslation"]=e["X-FieldTranslation"]:"X-FieldTranslation"in t&&(r["X-FieldTranslation"]=t["X-FieldTranslation"]),r}function hi(e,t=null){if(typeof e!="object"||e===null)return e;if(t||(t=e.$defs?{...e.$defs}:{}),!t||typeof t!="object")throw new Error("Definitions must be an object");if("allOf"in e){if(e.allOf.length!==1)throw new Error(`Property schema must have a single element in 'allOf'. Found: ${e.allOf}`);let n=e.allOf[0];delete e.allOf,Object.assign(e,n);}if("$ref"in e){let n=e.$ref;if(n.startsWith("#/$defs/")){let o=n.replace("#/$defs/","");if(!(o in t))return e;let a=t[o],i=GC(e,a);return delete i.$ref,hi(i,t)}else throw new Error(`Unsupported reference format: ${n}`)}let r={};for(let[n,o]of Object.entries(e))if(n==="properties"||n==="$defs")if(typeof o=="object"&&o!==null){let a={};for(let[i,s]of Object.entries(o))a[i]=hi(s,t);r[n]=a;}else r[n]=o;else n==="items"?Array.isArray(o)?r[n]=o.map(a=>hi(a,t)):r[n]=hi(o,t):typeof o=="object"&&o!==null?Array.isArray(o)?r[n]=o.map(a=>typeof a=="object"&&a!==null?hi(a,t):a):r[n]=hi(o,t):r[n]=o;return r}var Gl=(e,t)=>{let r=e,n=i=>{if(i&&i.$ref){let s=String(i.$ref).replace("#/$defs/",""),l=t?.$defs?.[s];if(l){let u={...GC(i,l)};return delete u.$ref,u}}return i};r=n(r);let o=false;Array.isArray(r?.type)&&r.type.includes("null")&&(o=true,r={...r,type:r.type.find(i=>i!=="null")});let a=r?.anyOf||r?.oneOf||r?.allOf;if(a){a.some(s=>s?.type==="null")&&(o=true);let i=a.find(s=>s?.type&&s.type!=="null"||s?.properties||s?.items||s?.$ref||s?.enum);i&&(r=n(i),r=hi(r,t?.$defs??{}));}return {schema:r,nullable:o}},be=(e,t)=>e===void 0||t==="none"?"transparent":DS(t==="similarity"?Ru:Ou,e,t==="similarity"?Au:Du,.3),Es=(e,t,r="border",n=false,o)=>t&&n?L9(o):r==="ring"?T(e&&"bg-green-50 ring-green-500 ring-2 data-[state=checked]:!bg-green-200 data-[state=checked]:!border-green-600 data-[state=checked]:!text-green-700",t&&"bg-blue-50 ring-blue-500 ring-2 data-[state=checked]:!bg-blue-200 data-[state=checked]:!border-blue-600 data-[state=checked]:!text-blue-700"):T(e&&"bg-green-50 border border-green-500 data-[state=checked]:!bg-green-200 data-[state=checked]:!border-green-600 data-[state=checked]:!text-green-700",t&&"bg-blue-50 border border-blue-500 data-[state=checked]:!bg-blue-200 data-[state=checked]:!border-blue-600 data-[state=checked]:!text-blue-700"),j9=e=>e===true?"border-green-500 border bg-green-50 data-[state=checked]:!bg-green-200 data-[state=checked]:!border-green-600 data-[state=checked]:!text-green-700":e===false?"border-red-500 border bg-red-50 data-[state=checked]:!bg-red-200 data-[state=checked]:!border-red-600 data-[state=checked]:!text-red-700":e==null?"border-yellow-500 border bg-yellow-50 data-[state=checked]:!bg-yellow-200 data-[state=checked]:!border-yellow-600 data-[state=checked]:!text-yellow-700":"border-green-500 border bg-green-50 data-[state=checked]:!bg-green-200 data-[state=checked]:!border-green-600 data-[state=checked]:!text-green-700",L9=e=>e===true?"border-green-500 border bg-green-50 data-[state=checked]:!bg-green-200 data-[state=checked]:!border-green-600 data-[state=checked]:!text-green-700":e===false?"border-red-500 border bg-red-50 data-[state=checked]:!bg-red-200 data-[state=checked]:!border-red-600 data-[state=checked]:!text-red-700":e==null?"border-yellow-500 border bg-yellow-50 data-[state=checked]:!bg-yellow-200 data-[state=checked]:!border-yellow-600 data-[state=checked]:!text-yellow-700":"border-green-500 border bg-green-50 data-[state=checked]:!bg-green-200 data-[state=checked]:!border-green-600 data-[state=checked]:!text-green-700",Jp=kt__default.forwardRef(({className:e,variant:t,size:r,type:n,uncertainty:o,multiline:a,scalarValueType:i,...s},l)=>{let{setIsEditing:c}=yn(),u=s.onKeyDown,d=f=>{f.key==="Enter"||f.key==="Escape"?f.currentTarget.blur():u?.(f);};s.onKeyDown=d;let m=s.onClick,h=f=>{c(true),m?.(f);},y=s.onBlur,p=f=>{c(false),y?.(f);};return s.onClick=h,s.onBlur=p,jsx("div",{className:(()=>{switch(t){case "underline-close":return "border-b-2 pb-0";case "underline-distant":return "border-b-2 pb-2";case "left-border-close":return "border-l-4 pl-0";case "left-border-distant":return "border-l-4 pl-2";default:return ""}})(),style:(()=>{switch(t){case "underline-close":case "underline-distant":case "left-border-close":case "left-border-distant":return {borderColor:be(o,i)};default:return {}}})(),children:a?jsx(nn,{rows:3,className:T(e,"text-opacity-90"),ref:l,...s,style:(()=>{switch(t){case "blur-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 2px 1px ${be(o,i)}`};case "blur-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 4px 2px ${be(o,i)}`};case "blur-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 6px 3px ${be(o,i)}`};case "outline-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 1px ${be(o,i)}`};case "outline-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 2px ${be(o,i)}`};case "outline-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 3px ${be(o,i)}`};default:return {}}})()}):jsx(nt,{type:n,className:T(e,"text-opacity-90"),ref:l,...s,style:(()=>{switch(t){case "blur-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 2px 1px ${be(o,i)}`};case "blur-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 4px 2px ${be(o,i)}`};case "blur-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 6px 3px ${be(o,i)}`};case "outline-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 1px ${be(o,i)}`};case "outline-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 2px ${be(o,i)}`};case "outline-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 3px ${be(o,i)}`};default:return {}}})()})})});Jp.displayName="StyledInput";var ZC=kt__default.forwardRef(({className:e,variant:t,uncertainty:r,scalarValueType:n,value:o,onChange:a,...i},s)=>{let{setIsEditing:l}=yn(),c=kt__default.useRef(null),u=i.onKeyDown,d=f=>{f.key==="Enter"||f.key==="Escape"?f.currentTarget.blur():u?.(f);};i.onKeyDown=d;let m=i.onClick,h=f=>{l(true),m?.(f);},y=i.onBlur,p=f=>{l(false),y?.(f);};return i.onClick=h,i.onBlur=p,jsx("div",{className:T((()=>{switch(t){case "underline-close":return "border-b-2 pb-0";case "underline-distant":return "border-b-2 pb-2";case "left-border-close":return "border-l-4 pl-0";case "left-border-distant":return "border-l-4 pl-2";default:return ""}})(),"flex flex-1 min-h-0"),style:(()=>{switch(t){case "underline-close":case "underline-distant":case "left-border-close":case "left-border-distant":return {borderColor:be(r,n)};default:return {}}})(),children:jsx(nn,{ref:c,rows:1,className:T(e,"text-opacity-90","whitespace-pre-wrap resize-none max-h-64 h-auto min-h-8","scrollbar-thin scrollbar-thumb-gray-400 scrollbar-track-gray-100"),value:o,onChange:a,...i,style:{...(()=>{switch(t){case "blur-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 2px 1px ${be(r,n)}`};case "blur-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 4px 2px ${be(r,n)}`};case "blur-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 6px 3px ${be(r,n)}`};case "outline-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 1px ${be(r,n)}`};case "outline-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 2px ${be(r,n)}`};case "outline-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 3px ${be(r,n)}`};default:return {}}})(),overflowY:"auto"}})})});ZC.displayName="StyledTextAreaInput";var XC=kt__default.forwardRef(({className:e,variant:t,uncertainty:r,size:n,scalarValueType:o,...a},i)=>{let s=n==="sm"?24:30,l={flexShrink:0,padding:0,margin:0,height:t==="underline-close"?`${s+2}px`:t==="underline-distant"?`${s+10}px`:`${s}px`,width:t==="left-border-close"?`${s+4}px`:t==="left-border-distant"?`${s+12}px`:`${s}px`,minWidth:t==="left-border-close"?`${s+4}px`:t==="left-border-distant"?`${s+12}px`:`${s}px`,minHeight:t==="underline-close"?`${s+2}px`:t==="underline-distant"?`${s+10}px`:`${s}px`};t==="underline-close"||t==="underline-distant"?(l.borderBottom="2px solid",l.borderColor=be(r,o),l.paddingBottom=t==="underline-close"?0:"0.5rem"):(t==="left-border-close"||t==="left-border-distant")&&(l.borderLeft="4px solid",l.borderColor=be(r,o),l.paddingLeft=t==="left-border-close"?0:"0.5rem");let c={};return t==="blur-small"?c.boxShadow=`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 2px 1px ${be(r,o)}`:t==="blur-large"?c.boxShadow=`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 4px 2px ${be(r,o)}`:t==="blur-xlarge"?c.boxShadow=`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 6px 3px ${be(r,o)}`:t==="outline-small"?c.boxShadow=`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 1px ${be(r,o)}`:t==="outline-large"?c.boxShadow=`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 2px ${be(r,o)}`:t==="outline-xlarge"&&(c.boxShadow=`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 3px ${be(r,o)}`),jsx("div",{className:"shrink-0 p-0 m-0",style:l,children:jsx(bl,{ref:i,className:T(e,"w-full h-full shrink-0",n==="sm"?"min-w-[24px] min-h-[24px]":"min-w-[30px] min-h-[30px]"),...a,style:c})})});XC.displayName="StyledCheckbox";var rv=kt__default.forwardRef(({className:e,variant:t,uncertainty:r,value:n,onValueChange:o,disabled:a,placeholder:i,size:s,children:l,scalarValueType:c},u)=>{let{setIsEditing:d}=yn(),m=h=>{d(true),o?.(h),setTimeout(()=>d(false),0);};return jsx("div",{className:(()=>{switch(t){case "underline-close":return "border-b-2 pb-0";case "underline-distant":return "border-b-2 pb-2";case "left-border-close":return "border-l-4 pl-0";case "left-border-distant":return "border-l-4 pl-2";default:return ""}})(),style:(()=>{switch(t){case "underline-close":case "underline-distant":case "left-border-close":case "left-border-distant":return {borderColor:be(r,c)};default:return {}}})(),children:jsxs(rp,{value:n,onValueChange:m,disabled:a,children:[jsx(op,{ref:u,className:T(e,s==="sm"?"!h-[32px] text-sm":"!h-[42px] text-sm","text-opacity-90"),style:(()=>{switch(t){case "blur-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 2px 1px ${be(r,c)}`};case "blur-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 4px 2px ${be(r,c)}`};case "blur-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 6px 3px ${be(r,c)}`};case "outline-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 1px ${be(r,c)}`};case "outline-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 2px ${be(r,c)}`};case "outline-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 3px ${be(r,c)}`};default:return {}}})(),children:jsx(np,{placeholder:i})}),jsx(ap,{className:T(e),children:l})]})})});rv.displayName="StyledSelect";function Gp(e,t,r=e){return B9(e,t,r)}function B9(e,t,r=e){if(!r||typeof r!="object")return null;let n=t.split(".").filter(o=>o.length>0);for(let o=0;o<n.length;){let a=n[o];if(r&&typeof r=="object"&&r.$ref){let i=e?.$defs??{},s=String(r.$ref).replace("#/$defs/","");r=i[s]??r;}if(r&&typeof r=="object"&&Array.isArray(r.anyOf)){for(let i of r.anyOf){let s=Gp(e,n.slice(o).join("."),i);if(s)return s}return null}if(r&&r.type==="array")r=r.items??{},o+1<n.length&&(n[o+1]==="*"||!isNaN(parseInt(n[o+1])))&&(o+=1);else if(r&&(r.type==="object"||r.properties)){let i=r.properties;if(i&&typeof i=="object"&&a in i)r=i[a]??{},o+=1;else if(a==="*"||!isNaN(parseInt(a)))o+=1;else return null}else if(a==="*"||!isNaN(parseInt(a)))o+=1;else return null}if(r&&typeof r=="object"&&r.$ref){let o=e?.$defs??{},a=String(r.$ref).replace("#/$defs/","");r=o[a]??r;}return r??null}var Wp=e=>{if(!e)return {};if(e.type==="string")return "";if(e.type==="number"||e.type==="integer")return 0;if(e.type==="boolean")return false;let t={};return e.properties&&Object.keys(e.properties).forEach(r=>{let n=e.properties[r],o=n.type,a;!o&&(n.anyOf||n.oneOf||n.allOf)&&(o=(n.anyOf||n.oneOf||n.allOf).find(l=>l.type!=="null")?.type||"object"),n.default!==void 0?a=n.default:o==="string"?a="":o==="number"||o==="integer"?a=null:o==="boolean"?a=false:o==="object"?a=Wp(n):o==="array"?a=n.items?[Wp(n.items)]:[]:a=null,t[r]=a;}),t};function Zp(e,t){if(!e||typeof t!="string")return false;let r=t.split("."),n=e;for(let o of r){if(n==null)return false;let a=o.match(/^(\d+)$/);if(a){let i=parseInt(a[1],10);if(!Array.isArray(n)||!(i in n))return false;n=n[i];}else {if(typeof n!="object"||!(o in n))return false;n=n[o];}}return true}var Jt=(e,t)=>t.split(".").reduce((r,n)=>{if(r&&typeof r=="object"&&n in r)return r[n]},e),Xp=(e,t)=>{if(!e||e.length<=1)return null;let r=X0(e[0].data,t),n=e.slice(1).map((s,l)=>{let c=Kp(t),u=X0(s.data,t),d=X0(s.data,c);return {value:u,index:l+2,reasoning:d}}).filter(s=>s.value!==void 0),o=s=>JSON.stringify(Array.isArray(s)?s:s??""),a=[...new Set(n.map(s=>o(s.value)))],i=n.length>0?n.filter(s=>o(s.value)===o(r)).length/n.length:1;return {consolidated_value:r,alternatives:n,count:n.length,agreement:i,hasVariation:a.length>1}};var z9=e=>e.split(".").map(t=>/^\d+$/.test(t)?"*":t).join("."),Ps=({show:e,content:t,id:r})=>!e||!t?null:jsx(io,{children:jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx("div",{className:"flex items-center",children:jsx(Atom,{className:"w-4 h-4 text-purple-300"})})}),jsxs(et,{className:"max-w-xs",children:[jsx("div",{className:"text-xs text-purple-300 mb-1",children:"Reasoning:"}),typeof t=="string"?jsx("div",{className:"whitespace-pre-wrap break-words",children:t}):jsx("pre",{className:"text-xs rounded border whitespace-pre-wrap text-gray-700 font-medium leading-snug p-1 bg-gray-50 max-h-64 overflow-auto",children:JSON.stringify(t,null,2)})]})]})},r),Zl=({show:e,content:t,id:r})=>{if(!e||!t||!t.alternatives)return null;let n=t.alternatives.filter(o=>!!o.reasoning);return n.length===0?null:jsx(io,{delayDuration:300,children:jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx("div",{className:"flex items-center cursor-pointer",children:jsx(Atom,{className:"w-4 h-4 text-purple-300"})})}),jsxs(et,{className:"max-w-xs break-words",children:[jsx("div",{className:"text-xs text-purple-300 mb-1 font-medium",children:"Model reasonings"}),jsx("div",{className:"space-y-2",children:n.map((o,a)=>jsxs("div",{className:"space-y-1",children:[jsxs("div",{children:["Model ",o.index-1]}),jsx("div",{className:"text-xs rounded border whitespace-pre-wrap text-gray-700 font-medium leading-snug p-1 bg-gray-50",children:o.reasoning})]},a))})]})]})},r)};var U9=({show:e,content:t,id:r,consolidated_value:n})=>!e||!t?null:jsx(io,{children:jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx("div",{className:"flex items-center",children:jsx(Blend,{className:"w-4 h-4 text-blue-300"})})}),jsxs(et,{className:"max-w-xs",children:[jsx("div",{className:"text-xs text-blue-300 mb-1",children:"Consensus:"}),t&&t.alternatives?jsxs("div",{className:"space-y-2",children:[jsxs("div",{className:"text-xs",children:["Agreement: ",(t.agreement*100).toFixed(0),"% (",t.count," choices)",t.hasVariation&&jsx("span",{className:"text-yellow-400 ml-1",children:"\u2022 Variation detected"})]}),jsx("div",{className:"text-xs font-medium",children:"Consensus:"}),jsx("div",{className:"space-y-1 max-h-32 overflow-y-auto",children:jsx("div",{className:"flex items-center justify-between gap-2",children:jsx("div",{className:"text-xs p-1 rounded border bg-gray-50",children:jsx("div",{className:"font-medium truncate text-gray-700",children:typeof n=="object"?JSON.stringify(n):String(n||"null")})})},"zero")}),jsx("div",{className:"text-xs font-medium",children:"Alternatives:"}),jsx("div",{className:"space-y-1 max-h-32 overflow-y-auto",children:t.alternatives.map((o,a)=>jsxs("div",{className:"flex items-center gap-2",children:["Model ",o.index-1,":",jsx("div",{className:"text-xs p-1 rounded border bg-gray-50",children:jsx("div",{className:"font-medium truncate text-gray-700",children:typeof o.value=="object"?JSON.stringify(o.value):String(o.value||"null")})})]},a))})]}):jsx("div",{className:"",children:t?String(t):""})]})]})},r),Q0=kt__default.memo(({item:e,innerIdx:t,arrayBaseName:r,enumOptions:n,itemsSchema:o,labelItem:a,elementKey:i,currentPath:s,className:l,disabled:c,isStreaming:u,size:d,handleRemoveItem:m,setLikelihoods:h,setSourcesFieldPath:y})=>{let{consensusDetails:p,form:f,config:x,scalarValueType:g,disabled:v}=yn(),w=`${r}.${t}.reasoning___item`,N=Zp(f.getValues(),w)?Jt(f.getValues(),w):null,S=`${r}.${t}`,_=kt__default.useMemo(()=>Xp(p,S),[p,S]),P=`${i}-item-${t}`;return n?jsxs("div",{className:T("flex flex-row items-center gap-2 mt-2",l,"bg-transparent shadow-none outline-transparent outline-none text-xs"),children:[jsx(ao,{control:f.control,name:`${s}.${t}`,render:({field:E})=>jsx(kn,{className:"flex-1",children:jsx(Rn,{children:jsx(rv,{size:d,disabled:c,value:Hp(E.value),onValueChange:C=>{E.onChange(JC(C)),h(b=>{let O={...b};return Xl(O,`${s}.${t}`,1),O});},className:l,scalarValueType:g,children:n.map(C=>{let b=Hp(C),O=b===Wu?"(Empty)":b.charAt(0).toUpperCase()+b.slice(1);return jsx(rs,{value:b,className:T(l,"rounded-none border-none outline-transparent"),children:O},b)})})})})}),jsx(Ps,{show:x?.showReasoning??false,content:N,id:`${i}-reasoning-enum-${t}`}),jsx(Zl,{show:x?.showReasoning??false,content:_,id:`${i}-consensus-reasoning-enum-${t}`}),!v&&jsx(V,{size:d==="sm"?"sm":"icon",type:"button",variant:"outline",onClick:()=>m(t),className:T(l,"py-1 px-2 shrink-0"),disabled:c||u,"aria-label":"Delete",children:jsx(Trash,{className:"h-3 w-3"})})]},P):(o.type??"")!=="object"&&!o.$ref&&!o.anyOf?.some(E=>E.type==="object"||E.$ref)?jsxs("div",{className:"flex items-end flex-row gap-1 w-full",children:[jsx("div",{className:"flex-1 min-w-0",children:jsx(QC,{path:s+"."+t,className:l})}),jsx(Ps,{show:x?.showReasoning??false,content:N,id:`${i}-reasoning-prim-${t}`}),jsx(Zl,{show:x?.showReasoning??false,content:_,id:`${i}-consensus-reasoning-prim-${t}`}),!v&&jsx(V,{size:d==="sm"?"sm":"icon",type:"button",variant:"outline",onClick:()=>m(t),className:T(l,"py-1 px-2 shrink-0",d==="sm"?"mr-1":"mr-2"),disabled:c||u,"aria-label":"Delete",children:jsx(Trash,{className:"h-3 w-3"})})]},P):jsxs(Eu,{value:`${i}-idx-${t}-0`,className:T(l,"border-b last:border-b-0 shadow-none border-x-0 border-t-0 rounded-none"),children:[jsxs("div",{className:T(l,"flex flex-row items-center shadow-none rounded-none border-none",d==="sm"?"h-[40px]":"h-[54px]"),children:[jsx("div",{className:"flex-1",children:jsx(Pu,{className:"pl-2 pr-2",children:jsxs("div",{className:"flex items-center flex-row gap-2 text-xs",children:[a+` #${t+1}`,jsx(Ps,{show:x?.showReasoning??false,content:N,id:`${i}-reasoning-tooltip-${t}`}),jsx(Zl,{show:x?.showReasoning??false,content:_,id:`${i}-consensus-reasoning-tooltip-${t}`})]})})}),!v&&jsx(V,{size:d==="sm"?"iconSm":"icon",type:"button",variant:"ghost",onClick:()=>m(t),className:T(l,d==="sm"?"mr-1":"mr-2"),disabled:c||u,"aria-label":"Delete",children:jsx(Trash,{className:"h-3 w-3"})})]}),jsx(Tu,{className:T(l,"border-x-0 rounded-none pb-0 pt-0 px-3 border-b-0 border-t"),children:jsx(nv,{path:s+"."+t,className:l,isArrayItem:true,isLoneObject:true})})]},`${i}-idx-${t}`)});Q0.displayName="ArrayRendererItem";var q9=({path:e,className:t})=>{let{schema:r,setSchema:n,form:o,isStreaming:a,disabled:i,size:s,setLikelihoods:l,setSourcesFieldPath:c,consensusDetails:u,config:d,propertyEditorMode:m,showPropertyEditorPencil:h,computationSpec:y,setComputationSpec:p}=yn(),{projectId:f}=yn(),x=Gp(r,e),{schema:g}=Gl(x,r),v=kt__default.useMemo(()=>Xp(u,e),[u,e]);if(!x)return null;let w=e,N=null,S=null;if((g?.type==="array"||Array.isArray(g?.type)&&g.type.includes("array"))&&g?.items)N=Gl(g.items,r).schema;else if(g?.anyOf||g?.oneOf||g?.allOf){let I=(g.anyOf||g.oneOf||g.allOf).find(F=>F?.type==="array"||F?.items);I&&(N=Gl(I.items??I,r).schema);}N?.enum&&(S=N.enum);let _=Kp(e),P=Zp(o.getValues(),_)?Jt(o.getValues(),_):null,R=e.split(".").pop(),E=N?.title||"Item",C=!!x?.["X-ComputedField"],b=Jt(o.getValues(),w);Array.isArray(b)||(b=[],o.setValue(w,b));let O=()=>{if(S){let ue=S.find(L=>L!=="")??"",re=Jt(o.getValues(),w)||[],X=[...re,ue];o.setValue(w,X,{shouldValidate:true,shouldDirty:true,shouldTouch:true});let $=`${w}.${re.length}`;l(L=>{let le={...L};return Xl(le,$,1),le});return}if(!N){console.error("Could not find items schema for",e);return}let k=Wp(N),I=Jt(o.getValues(),w)||[],F=I.length,Z=[...I,k];o.setValue(w,Z,{shouldValidate:true,shouldDirty:true,shouldTouch:true});let pe=(J,ue)=>{Object.keys(J).forEach(re=>{let X=ue?`${ue}.${re}`:re;J[re]!==null&&typeof J[re]=="object"?pe(J[re],X):l($=>{let L={...$};return Xl(L,X,1),L});});},ie=`${w}.${F}`;pe(k,ie);},D=k=>{let F=[...Jt(o.getValues(),w)||[]];F.splice(k,1),o.setValue(w,F,{shouldValidate:true,shouldDirty:true,shouldTouch:true});};return jsxs("div",{className:T("flex flex-col"),children:[jsxs("div",{className:"flex flex-row gap-2 group pt-4",children:[jsx(oi,{className:T(t,"items-center border-none outline-transparent shadow-none bg-transparent justify-center flex hover:bg-transparent mb-0"),children:R}),jsx(Ps,{show:d?.showReasoning??false,content:P,id:`${e}-reasoning-root`}),!!d?.showReasoning&&!!d?.showConsensus&&!!v&&jsx(Zl,{show:!!d?.showReasoning,content:v,id:`${e}-consensus-reasoning-root`}),n&&h!==false&&jsxs(hn,{modal:true,children:[jsx(ju,{asChild:true,children:jsx("button",{className:"cursor-pointer relative ml-auto opacity-0 group-hover:opacity-100 transition-opacity duration-300",type:"button","aria-label":"Edit field",children:jsx(Pencil,{className:"absolute top-0 right-0 size-[14px]"})})}),jsxs(co,{className:"p-0 gap-0 max-h-[80vh] overflow-y-auto",onOpenAutoFocus:k=>{k.preventDefault();},onPointerDownOutside:k=>{k.preventDefault();},onInteractOutside:k=>{k.preventDefault();},onEscapeKeyDown:k=>{k.preventDefault();},children:[jsx(gn,{className:"text-lg font-semibold px-4 pt-3 pb-0",children:"Edit field"}),C?jsx("div",{className:"p-0",children:f&&y&&p&&jsx(Wl,{fieldPath:e,jsonSchema:r,computationSpec:y,setComputationSpec:p,readOnly:m==="readOnly"})}):jsx(Vl,{property:x,propertyKey:e,setDropdownOpen:()=>{},jsonSchema:r,setJsonSchema:n,editMode:m??"editable"})]})]})]},`${e}-header`),Array.isArray(b)&&N&&(N.type==="object"||N.$ref||N.anyOf?.some(k=>k.type==="object"||k.$ref))?jsx(Cu,{type:"single",collapsible:true,defaultValue:Array.isArray(b)&&b.length>0?`${e}-idx-0-0`:void 0,className:T("outline-transparent rounded-md",t,"mt-2 bg-transparent outline overflow-hidden"),children:b.map((k,I)=>jsx(Q0,{item:k,innerIdx:I,arrayBaseName:e,enumOptions:null,itemsSchema:N,labelItem:E,elementKey:e,currentPath:w,className:t,disabled:i??false,isStreaming:a??false,size:s,handleRemoveItem:D,setLikelihoods:l,setSourcesFieldPath:c},`${e}-item-${I}`))}):Array.isArray(b)?b.map((k,I)=>jsx(Q0,{item:k,innerIdx:I,arrayBaseName:e,enumOptions:S,itemsSchema:N,labelItem:E,elementKey:e,currentPath:w,className:t,disabled:i??false,isStreaming:a??false,size:s,handleRemoveItem:D,setLikelihoods:l,setSourcesFieldPath:c},`${e}-item-${I}`)):null,jsx("div",{className:"flex mt-2",children:jsx("div",{children:jsxs(V,{size:s,className:T(t,"px-2"),type:"button",variant:"outline",onClick:O,disabled:i||a,children:[jsx(Plus,{className:"size-5 mr-2"}),jsx("span",{className:"",children:R})]})})},`${e}-add-button`)]},e)},QC=({path:e,className:t})=>{let{form:r,formFieldIdPrefix:n,size:o,likelihoods:a,scalarValueDisplay:i,scalarValueType:s,isProcessing:l,isStreaming:c,disabled:u,titlePosition:d,setLikelihoods:m,setSourcesFieldPath:h,config:y,consensusDetails:p,isEditing:f,setIsEditing:x,propertyEditorMode:g,showPropertyEditorPencil:v,schema:w,setSchema:N,validationFlags:S,setValidationFlags:_,showVerifiedProperty:P,projectId:R,computationSpec:E,setComputationSpec:C}=yn(),b=r.getValues(),O=y?.descriptions??false,[D,k]=kt__default.useState(void 0),I=Gp(w,e),F=r.getValues(e);kt__default.useEffect(()=>{k(F!=null?String(F):"");},[e,F]);let Z=Kp(e),pe=Zp(b,Z)?Jt(b,Z):null,ie=kt__default.useMemo(()=>Xp(p,e),[p,e]),{schema:J,nullable:ue}=Gl(I,w),re=!ue,X=!!(J?.["X-ComputedField"]||I?.["X-ComputedField"]),$=!!(J?.["X-FunctionField"]||I?.["X-FunctionField"]),L,le;J.enum?(L="enum",le=J.enum):L=J.format==="date"?"date":J.format==="iso-time"?"time":J.format==="date-time"?"datetime":J.type==="number"?"number":J.type==="integer"?"integer":J.type==="boolean"?"boolean":"text";let ae=L==="boolean"?"checkbox":L==="date"?"date":L==="time"?"time":L==="datetime"?"datetime-local":L==="number"||L==="integer"?"number":"text",Oe=Me=>{m(ce=>{let G={...ce};return Xl(G,Me,1),G});},ye=kt__default.useCallback((Me,ce)=>{let G=ce;if(typeof ce=="string")if(L==="number"){let H=parseFloat(ce);G=isNaN(H)?null:H;}else if(L==="integer"){let H=parseInt(ce);G=isNaN(H)?null:H;}else ae==="time"&&/^\d{1,2}:\d{2}$/.test(ce)||ae==="datetime-local"&&/^\d{4}-\d{2}-\d{2}T\d{1,2}:\d{2}$/.test(ce)?G=ce+":00":ce===""&&(G=null);let U=G;if(J&&J.format&&typeof G=="string")try{let H={type:"object",properties:{[e.split(".").pop()]:J}};U=Dn({[e.split(".").pop()]:G},H)[e.split(".").pop()];}catch(H){console.warn(`autoFormatDateTimeFields validation failed for ${e}:`,H);}Me.onChange(U),Oe(e);},[e,J,L,ae,Oe]);if(!I)return jsxs("i",{children:["Bad schema path: ",e]});let ft=J?.title||e.split(".").pop()||"",zt=(()=>{if(!(J.type==="string"||J.anyOf?.some(G=>G.type==="string")||J.oneOf?.some(G=>G.type==="string")||J.allOf?.some(G=>G.type==="string")))return false;let ce=[];return J.maxLength!==void 0&&ce.push(J.maxLength),J.anyOf&&J.anyOf.forEach(G=>{G.type==="string"&&G.maxLength!==void 0&&ce.push(G.maxLength);}),J.oneOf&&J.oneOf.forEach(G=>{G.type==="string"&&G.maxLength!==void 0&&ce.push(G.maxLength);}),J.allOf&&J.allOf.forEach(G=>{G.type==="string"&&G.maxLength!==void 0&&ce.push(G.maxLength);}),ce.length>0?Math.min(...ce)>500:false})(),st=()=>{let Me=h&&!f?()=>{h(e);}:void 0,ce=Me?G=>{let U=G.target;!U.closest("[data-radix-popper-content-wrapper]")&&!U.closest('[role="button"]')&&Me();}:void 0;return jsxs("div",{className:"flex flex-row flex-wrap gap-1 break-all min-w-0 w-full",onClick:G=>G.stopPropagation(),children:[jsxs(oi,{className:T("flex items-center gap-1 cursor-pointer","text-xs",X&&"text-blue-900 opacity-90"),onMouseEnter:ce,children:[ft,re&&!X&&jsx("span",{className:"text-red-500",children:"*"})]}),J.description&&O&&jsx("div",{className:"relative inline-block",children:jsx(io,{children:jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(Info,{className:T(t,"h-[14px] w-[14px] cursor-pointer bg-transparent shadow-none outline-none border-none outline-transparent")})}),jsxs(et,{side:"top",className:"w-[200px] p-0 max-w-[80vw]",children:[jsx(TooltipArrow,{}),jsx("div",{className:T("border border-black",t,"text-xs p-3 max-h-[60vh] overflow-y-auto break-words whitespace-normal flex shadow-none outline-none rounded-md focus-ring-0 outline-transparent"),children:J.description})]})]})})}),false,y?.showPrompts&&J["X-ReasoningPrompt"]&&jsx(io,{children:jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsxs("div",{className:"flex items-center rounded-full px-1 border border-black text-xs font-light",children:[jsx(Atom,{className:T(t,"h-[14px] w-[14px] text-muted-foreground cursor-pointer bg-transparent shadow-none outline-none border-none outline-transparent")}),"Reasoning"]})}),jsxs(et,{side:"right",className:"w-[200px] p-0",sideOffset:2,children:[jsx(TooltipArrow,{}),jsx("div",{className:T("border border-black",t,"text-xs p-3 shadow-none outline-none rounded-md focus-ring-0 outline-transparent"),children:J["X-ReasoningPrompt"]})]})]})}),h&&!f&&y?.showSources&&jsx(Search,{className:T(t,"h-[14px] w-[14px] text-muted-foreground cursor-pointer bg-transparent shadow-none outline-none border-none outline-transparent"),onMouseEnter:ce}),jsx(Ps,{show:y?.showReasoning??false,content:pe,id:`${e}-reasoning`}),jsx(U9,{show:y?.showConsensus??false,consolidated_value:F,content:ie,id:`${e}-consensus`}),y?.showReasoning&&y?.showConsensus&&ie&&jsx(Zl,{show:y?.showReasoning,content:ie,id:`${e}-consensus-reasoning`}),N&&v!==false&&jsxs(hn,{modal:true,children:[jsx(ju,{asChild:true,children:jsx("button",{className:"cursor-pointer relative ml-auto opacity-0 group-hover:opacity-100 transition-opacity duration-300",type:"button",children:jsx(Pencil,{className:"absolute top-0 right-0 size-[14px]"})})}),jsxs(co,{className:"p-0 gap-0 max-h-[80vh] overflow-y-auto",onOpenAutoFocus:G=>{G.preventDefault();},onPointerDownOutside:G=>{G.preventDefault();},onInteractOutside:G=>{G.preventDefault();},onEscapeKeyDown:G=>{X&&G.preventDefault();},children:[jsx(gn,{className:"text-lg font-semibold px-4 pt-3 pb-0",children:"Edit field"}),X?jsx("div",{className:"p-0",children:R&&E&&C&&jsx(Wl,{fieldPath:z9(e),jsonSchema:w,computationSpec:E,setComputationSpec:C,readOnly:g==="readOnly"})}):jsx(Vl,{property:I,propertyKey:e,setDropdownOpen:()=>{},jsonSchema:w,setJsonSchema:N,editMode:g??"editable"})]})]}),X&&jsx("div",{className:"flex items-center ml-auto",onClick:G=>G.stopPropagation(),children:jsx("span",{className:"text-xs font-normal text-blue-900 opacity-70",children:"computed value"})}),P===true&&!X&&jsxs("div",{className:"flex items-center gap-2 ml-auto",onClick:G=>G.stopPropagation(),children:[jsx("span",{className:"text-xs font-normal text-muted-foreground",children:"verified"}),jsx(Np,{checked:!!Jt(S,e),onCheckedChange:G=>{let U={...S};Xl(U,e,G),_(U);}})]})]})},tt=u||l||X||$||c&&(F==="Undefined"||F===void 0),xe=()=>{x(true),h&&h(e);},me=Me=>{if(h){let ce=Me.target;!ce.closest("[data-radix-popper-content-wrapper]")&&!ce.closest('[role="button"]')&&h(e);}},_e=n??"form-field",pt=!!Jt(S,e),Fe=$&&!pt?j9(F):"";return jsx("div",{id:`${_e}-${e.split(".").join("-")}`,className:T("space-y-2 group"),children:jsx(ao,{control:r.control,name:e,render:({field:Me})=>ae==="checkbox"?jsxs(kn,{className:"flex items-center space-y-0 my-2",children:[jsx(Rn,{children:jsx(XC,{size:o,uncertainty:Jt(a,e),variant:i,scalarValueType:s,className:T(t,Es(pt,X,"ring",L==="boolean",D?.toLowerCase()==="true"),Fe),onCheckedChange:ce=>{k(ce?"true":"false"),ye(Me,ce);},checked:D?.toLowerCase()==="true",disabled:tt})}),d!="none"&&jsx("div",{className:T(t,"border-none outline- shadow-none bg-transparent text-left ml-2 text-xs flex flex-1 min-h-0"),children:jsx(st,{})})]}):jsxs(kn,{className:"flex flex-1 min-h-0 flex-col",children:[c&&isUndefined(Jt(b,e))?d!="none"&&jsx(oi,{className:T(t,"border-none outline-transparent shadow-none bg-transparent text-left flex mt-4 hover:bg-transparent"),children:jsx(Re,{className:"h-4 w-[30%] bg-gray-200 animate-pulse rounded-md border-none outline-none outline-transparent"})}):d!="none"&&jsx("div",{className:T(t,"border-none outline-transparent shadow-none bg-transparent text-left flex mt-4 hover:bg-transparent"),children:jsx(st,{})}),jsx(Rn,{className:"flex flex-1 min-h-0",onMouseEnter:me,onMouseOver:me,onClick:xe,children:l&&!c?jsx(Re,{className:T(o==="sm"?"h-[32px]":"h-[42px]","flex animate-pulse rounded-md border-none outline-none bg-gray-200")}):L==="enum"&&le?c&&isUndefined(Jt(b,e))?jsx(Re,{className:T(o==="sm"?"h-[32px]":"h-[42px]","flex animate-pulse rounded-md border-none outline-none bg-gray-200")}):jsxs(rv,{size:o,disabled:tt,value:Hp(D??Me.value),onValueChange:ce=>{let G=JC(ce);k(G),ye(Me,G);},className:T(t,Es(pt,X,"border",false),Fe),uncertainty:Jt(a,e),variant:i,scalarValueType:s,children:[!re&&jsx(rs,{value:ev,children:"None"}),le.map(ce=>{let G=Hp(ce),U=G===Wu?"(Empty)":G.charAt(0).toUpperCase()+G.slice(1);return jsx(rs,{value:G,className:T(t,"rounded-none border-none outline-transparent"),children:U},G)})]}):ae=="number"?c&&isUndefined(Jt(b,e))?jsx(Re,{className:T(o==="sm"?"h-[32px]":"h-[42px]","flex animate-pulse rounded-md border-none outline-none bg-gray-200")}):jsx(Jp,{uncertainty:Jt(a,e),variant:i,scalarValueType:s,inputMode:"numeric",value:D??Me.value??"",type:ae,disabled:tt,onChange:ce=>{k(ce.target.value);},onBlur:()=>{D!==void 0&&ye(Me,D);},className:T(t,o==="sm"?"h-[32px] text-sm":"h-[42px] text-sm","text-opacity-90",Es(pt,X,"border",false),Fe)}):c&&isUndefined(Jt(b,e))?jsx(Re,{className:T(o==="sm"?"h-[32px]":"h-[42px]","flex animate-pulse rounded-md border-none outline-none bg-gray-200 text-red-200")}):L==="date"?c&&isUndefined(Jt(b,e))?jsx(Re,{className:T(o==="sm"?"h-[32px]":"h-[42px]","flex animate-pulse rounded-md border-none outline-none bg-gray-200")}):jsx(tv,{size:o,disabled:tt,value:tE(D??Me.value),onValueChange:ce=>{let G=null;if(ce){let U=ce.getFullYear(),H=(ce.getMonth()+1).toString().padStart(2,"0"),je=ce.getDate().toString().padStart(2,"0");G=`${U}-${H}-${je}`;}k(G??void 0),ye(Me,G);},className:T(t,Es(pt,X,"border",false),Fe),uncertainty:Jt(a,e),variant:i,scalarValueType:s,placeholder:"Pick a date"}):L==="datetime"?c&&isUndefined(Jt(b,e))?jsx(Re,{className:T(o==="sm"?"h-[32px]":"h-[42px]","flex animate-pulse rounded-md border-none outline-none bg-gray-200")}):jsx(WC,{size:o,scalarValueType:s,disabled:tt,value:D??Me.value,onValueChange:ce=>{k(ce??void 0),ye(Me,ce);},className:T(t,Es(pt,X,"border",false),Fe),uncertainty:Jt(a,e),variant:i}):L==="time"?jsx("div",{className:"flex items-center",children:jsx(Jp,{scalarValueType:s,uncertainty:Jt(a,e),variant:i,type:ae,disabled:tt,value:D??Me.value??"",onChange:ce=>{k(ce.target.value);},onBlur:()=>{D!==void 0&&ye(Me,D);},className:T(t,o==="sm"?"h-[32px] text-sm":"h-[42px] text-sm","text-opacity-90",Es(pt,X,"border",false),Fe),style:{WebkitAppearance:"none"},multiline:zt})}):jsx(ZC,{scalarValueType:s,uncertainty:Jt(a,e),variant:i,disabled:tt,value:D??Me.value??"",onChange:ce=>{k(ce.target.value);},onBlur:()=>{D!==void 0&&ye(Me,D);},className:T(t,o==="sm"?"h-[32px] text-sm":"h-[42px] text-sm","text-opacity-90",Es(pt,X,"border",false),Fe),style:{WebkitAppearance:"none"}})}),jsx(Nu,{className:T(t,"border-none shadow-none bg-transparent text-left flex mt-4 hover:bg-transparent text-xs text-red-600")})]})})},e)},nv=({path:e,className:t,isLoneObject:r=false,isArrayItem:n=false})=>{let{schema:o,form:a,setLikelihoods:i,size:s,disabled:l,isStreaming:c,config:u}=yn(),d=Gp(o,e),{schema:m,nullable:h}=Gl(d,o),y=e.split(".").pop()||"",p=!!y&&!n&&e!=="",f=Kp(e),x=Zp(a.getValues(),f)?Jt(a.getValues(),f):null,g=a.getValues(e),v=()=>{let S=Wp(m);a.setValue(e,S);let _=(P,R)=>{Object.keys(P).forEach(E=>{let C=R?`${R}.${E}`:E;P[E]!==null&&typeof P[E]=="object"?_(P[E],C):i(b=>{let O={...b};return Xl(O,C,1),O});});};_(S,e);},w=()=>{a.setValue(e,null);};if(h&&g===null)return jsx("div",{className:"flex mt-2",children:jsxs(V,{size:s,className:T(t,"px-2"),type:"button",variant:"outline",onClick:v,disabled:l||c,children:[jsx(Plus,{className:"size-5 mr-2"}),jsx("span",{className:"",children:y})]})});let N=m.properties||{};return jsxs("div",{className:T("space-y-4",n||r?"pb-3 pt-1 bg-background/3 border-none outline-transparent shadow-none rounded-md":""),children:[p&&jsxs("div",{className:"flex items-center gap-2 mx-auto justify-center pt-1",children:[jsx(oi,{className:T(t,"border-none outline-transparent shadow-none bg-transparent justify-center flex hover:bg-transparent mb-0 text-base font-medium"),children:y}),jsx(Ps,{show:u?.showReasoning??false,content:x,id:`${e}-reasoning-object`})]}),Object.keys(N).map(S=>{let _=N[S],{schema:P}=Gl(_,o),R=P?.type||(P?.enum?"enum":P?.properties?"object":P?.items?"array":"string");return R==="object"||P?.properties?jsx(nv,{path:e?`${e}.${S}`:S,className:t,isLoneObject:true},S):R==="array"||P?.items?jsx(q9,{path:e?`${e}.${S}`:S,className:t},S):jsx(QC,{path:e?`${e}.${S}`:S,className:t},S)}),h&&!l&&jsxs(V,{size:s,variant:"outline",type:"button",onClick:w,className:T(t," mt-12 mx-auto flex justify-center "),disabled:l||c,children:[jsx(Trash,{className:"h-4 w-4"}),"Delete"]})]},e)};function YC(e,t=[]){return e.message?[{path:t,error:e}]:Object.entries(e).flatMap(([r,n])=>YC(n,[...t,r]))}var V9=({className:e})=>{let {showSubmit:t,schema:r,setSchema:n,config:o,onSubmit:a,form:i,likelihoods:s,setLikelihoods:l,setSourcesFieldPath:c,scalarValueDisplay:u,scalarValueType:d,isProcessing:m,isStreaming:h,size:y,disabled:p,titlePosition:f,consensusDetails:x}=yn(),g=i.getValues(),v=g?.reasoning___root||g?.reasoning__root,w=Xp(x,"");hi(r);return jsx(vl,{...i,children:jsxs("form",{className:"w-full flex flex-col h-full",onSubmit:i.handleSubmit(a),children:[jsxs("div",{className:"flex flex-row items-center gap-2 mx-auto ",children:[jsx(Ps,{show:o?.showReasoning??false,content:v,id:"root-reasoning"}),v&&w&&o?.showReasoning&&o?.showConsensus&&jsx(Zl,{show:o?.showReasoning,content:w,id:"root-consensus-reasoning"})]}),jsx(nv,{className:e,path:""}),Object.keys(i.formState.errors).length>0&&o?.showErrors===true&&jsxs("div",{className:"mt-6 font-light",children:[jsx("p",{className:"text-sm font-medium text-red-500 mb-2",children:"Please fix the following errors:"}),YC(i.formState.errors).map(({path:S,error:_})=>{let R=_.message;return jsxs("div",{className:"text-xs items-end justify-end",children:[jsx(TriangleAlert,{size:16,className:"inline-block mr-1 text-red-500"}),jsx("span",{className:"",children:S.join(" > ")}),jsx("span",{className:"ml-1 text-red-500",children:R})]},S.join("."))})]}),t&&!p&&r.properties&&Object.keys(r.properties).length>0&&jsx(V,{variant:"default",className:T(e," mt-12 min-w-[200px] mx-auto flex justify-center bg-primary text-primary-foreground"),type:"submit",size:y,disabled:h||m||Object.keys(i.formState.errors).length>0,children:o?.submitText||"Submit"}),!(r.properties&&Object.keys(r.properties).length>0)&&jsx("div",{className:"min-w-[200px] mx-auto flex justify-center",children:jsx("span",{className:"text-sm text-gray-500",children:"Create a schema to get started"})})]})})},H9=({className:e,numberOfFields:t=10})=>jsx("div",{className:T("space-y-4"),children:Array.from({length:t}).map((r,n)=>jsxs("div",{className:"space-y-2",children:[jsx(Re,{className:T(e,"h-4 w-[30%] bg-gray-200 animate-pulse rounded-md border-none outline-none outline-transparent")}),jsx(Re,{className:T(e,"h-10 w-full bg-gray-200 animate-pulse rounded-md border-none outline-none outline-transparent")})]},n))}),eE=createContext(void 0),yn=()=>{let e=useContext(eE);if(!e)throw new Error("useUiFormContext must be used within a UiFormContextProvider");return e},J9=({containerProps:e,children:t})=>{let[r,n]=useState(false),{schema:o,setSchema:a,onSubmit:i,form:s,config:l,variant:c,isStreaming:u,size:d,isProcessing:m,setSourcesFieldPath:h,likelihoods:y,setLikelihoods:p,scalarValueDisplay:f,scalarValueType:x,disabled:g,titlePosition:v,showSubmit:w,consensusDetails:N,propertyEditorMode:S,showPropertyEditorPencil:_,validationFlags:P,setValidationFlags:R,showVerifiedProperty:E,projectId:C,computationSpec:b,setComputationSpec:O}=e,D={showSubmit:w??true,schema:o,setSchema:a,form:s,isStreaming:u,isProcessing:m,onSubmit:i,config:l,variant:c,size:d,likelihoods:y,setLikelihoods:p,scalarValueDisplay:f,scalarValueType:x,disabled:g,titlePosition:v,setSourcesFieldPath:h,consensusDetails:N,isEditing:r,setIsEditing:n,propertyEditorMode:S,showPropertyEditorPencil:_,validationFlags:P,setValidationFlags:R,showVerifiedProperty:E,projectId:C,computationSpec:b,setComputationSpec:O};return jsx(eE.Provider,{value:D,children:t})},W9=kt__default.memo(J9),Ql=({className:e})=>{let{isProcessing:t,isStreaming:r,form:n}=yn();return t&&!r?jsx(H9,{}):jsx(V9,{className:e})},Yl=e=>{let{className:t,children:r}=e;return jsx(W9,{containerProps:e,children:jsx("div",{className:T("gap-4",t),children:r})})},tE=e=>{if(!e||e==="Undefined")return null;let t=Date.parse(e);return Number.isNaN(t)?null:new Date(t)},X0=(e,t)=>t.split(".").reduce((r,n)=>{if(r!=null)return n==="*"?r:/^\d+$/.test(n)?r[Number(n)]:r[n]},e);var K9={headerBg:"bg-zinc-100 hover:bg-zinc-200",headerText:"text-zinc-800 hover:text-zinc-800",subHeaderBg:"bg-zinc-200",subHeaderHoverBg:"hover:bg-zinc-300",border:"border-zinc-200",verticalLine:"bg-zinc-200",tableContainerBg:"bg-white",tableRowBg:"bg-transparent hover:bg-zinc-100",tableCellBg:"bg-transparent hover:bg-zinc-50",forbiddenCellBg:"bg-zinc-100",selectedBg:"bg-zinc-300",selectedHoverBg:"hover:bg-zinc-400",tooltipBg:"bg-gray-100",tooltipText:"text-gray-800",disabledOpacity:"disabled:opacity-100 text-inherit",plusButtonIcon:"text-gray-600"};var rE={headerBg:"bg-gray-100 hover:bg-gray-200",headerText:"text-gray-800 hover:text-gray-800",subHeaderBg:"bg-gray-200",subHeaderHoverBg:"hover:bg-gray-300",border:"border-gray-200",verticalLine:"bg-gray-200",tableContainerBg:"bg-white",tableRowBg:"bg-transparent hover:bg-gray-100",tableCellBg:"bg-transparent hover:bg-gray-50",forbiddenCellBg:"bg-gray-100",selectedBg:"bg-gray-300",selectedHoverBg:"hover:bg-gray-400",tooltipBg:"bg-gray-100",tooltipText:"text-gray-800",disabledOpacity:"disabled:opacity-100 text-inherit",plusButtonIcon:"text-gray-600"},G9={headerBg:"bg-neutral-100 hover:bg-neutral-200",headerText:"text-neutral-800 hover:text-neutral-800",subHeaderBg:"bg-neutral-200",subHeaderHoverBg:"hover:bg-neutral-300",border:"border-neutral-200",verticalLine:"bg-neutral-200",tableContainerBg:"bg-white",tableRowBg:"bg-transparent hover:bg-neutral-100",tableCellBg:"bg-transparent hover:bg-neutral-50",forbiddenCellBg:"bg-neutral-100",selectedBg:"bg-neutral-300",selectedHoverBg:"hover:bg-neutral-400",tooltipBg:"bg-neutral-100",tooltipText:"text-neutral-800",disabledOpacity:"disabled:opacity-100 text-inherit",plusButtonIcon:"text-neutral-600"},Z9={headerBg:"bg-slate-100 hover:bg-slate-200",headerText:"text-slate-800 hover:text-slate-800",subHeaderBg:"bg-slate-200",subHeaderHoverBg:"hover:bg-slate-300",border:"border-slate-200",verticalLine:"bg-slate-200",tableContainerBg:"bg-white",tableRowBg:"bg-transparent hover:bg-slate-100",tableCellBg:"bg-transparent hover:bg-slate-50",forbiddenCellBg:"bg-slate-100",selectedBg:"bg-slate-300",selectedHoverBg:"hover:bg-slate-400",tooltipBg:"bg-gray-100",tooltipText:"text-gray-800",disabledOpacity:"disabled:opacity-100 text-inherit",plusButtonIcon:"text-gray-600"};function gr(e){return e.includes("dataset")?Z9:e.includes("builder")?K9:e==="hil"?G9:rE}var oE=({itemIndex:e,iterationIndex:t,schema:r,setSchema:n,extractionData:o,similarities:a,scalarValueType:i,isStreamingIteration:s,isRunningIteration:l,onFieldPathChange:c,consensusDetails:u,showSources:d=false,themeOverride:m=null,groundTruthData:h,editMode:y,showPropertyEditorPencil:p=true,allowEditing:f=false,onPredictionChange:x,computationSpec:g,setComputationSpec:v,projectId:w,showReasoning:N=true})=>{let S=useForm({mode:"all",defaultValues:o||{},resolver:void 0,shouldUnregister:false});useEffect(()=>{S.reset(o||{},{keepDirty:false,keepErrors:false,keepTouched:false,keepIsSubmitted:false,keepSubmitCount:false,keepValues:false,keepDirtyValues:false,keepDefaultValues:false});},[o,r,S,e,t,s]),useEffect(()=>{if(!f||!x||s)return;let O=S.watch((D,{type:k})=>{(k==="change"||k===void 0)&&x(e,D);});return ()=>{O.unsubscribe();}},[S,f,x,e,s]);let _=useMemo(()=>({readOnly:!f,showReasoning:N,showConsensus:true,showConfidenceTablets:true,groundTruthData:h,predictionData:o}),[h,o,f,N]),P=useCallback(O=>{O&&c?.(O);},[c]),R=useCallback(()=>{},[]),E=useMemo(()=>a||{},[a]),C=gr(m||"dark"),b=useMemo(()=>!o||Object.keys(o).length===0,[o]);return jsx(Yl,{showSubmit:false,form:S,schema:r,setSchema:n,onSubmit:()=>{},variant:"normal",config:_,size:"sm",className:"w-full p-1 pb-8",disabled:!f,titlePosition:"row",likelihoods:E,setLikelihoods:R,isStreaming:s&&Object.keys(o||{}).length>0,isProcessing:l&&!s,scalarValueDisplay:"outline-large",scalarValueType:i,setSourcesFieldPath:P,consensusDetails:u||[],propertyEditorMode:y,showPropertyEditorPencil:p,formFieldIdPrefix:"extraction-form-field",validationFlags:{},setValidationFlags:R,computationSpec:g,setComputationSpec:v,projectId:w,children:jsx(Ql,{className:`border ${C.border} rounded-sm !text-xs ${C.tableContainerBg} ${C.headerText} disabled:opacity-100`})},`pfw-${e}-${t}-${b?"empty":"data"}`)};var Q9=kt__default.memo(({itemIndex:e,schema:t,setSchema:r,groundTruth:n,similarities:o,readOnly:a=true,onGroundTruthChange:i,onFieldPathChange:s,scalarValueType:l,consensusDetails:c,isStreaming:u=false,isProcessing:d=false,validationFlags:m,setValidationFlags:h,showVerifiedProperty:y=true,showPropertyEditorPencil:p=true,editMode:f,computationSpec:x,setComputationSpec:g,projectId:v})=>{let w=process.env.NODE_ENV!=="production",N=useMemo(()=>t?KC():void 0,[t]),S=useForm({mode:"all",defaultValues:n||{},resolver:a?void 0:N}),_=useRef(n),P=useRef(t),R=useRef(e),E=useCallback(async F=>{S.reset(F||{},{keepDefaultValues:true}),await S.trigger();},[S]);useEffect(()=>{let F=_.current!==n,Z=P.current!==t,pe=R.current!==e;!a&&t&&n!==void 0&&(F||Z||pe)&&(E(n),_.current=n,P.current=t,R.current=e);},[n,t,e,E,w,a]),useEffect(()=>{if(a||!i||u)return;let F=S.watch((Z,{type:pe})=>{(pe==="change"||pe===void 0)&&i(e,Z);});return ()=>{F.unsubscribe();}},[S,a,i,e,u]);let C=useMemo(()=>({readOnly:a,showReasoning:true,showConsensus:true,showConfidenceTablets:true}),[a]),b=useCallback(F=>{F&&s?.(F);},[s]),O=useCallback(()=>{},[]),D=useMemo(()=>o||{},[o]),k=gr("dataset"),I=useCallback(()=>{},[]);return jsx(Yl,{showSubmit:false,form:S,schema:t,setSchema:r,onSubmit:()=>{},variant:"normal",likelihoods:D,config:C,size:"sm",className:"w-full p-1 pb-8",disabled:a||u,titlePosition:"row",setLikelihoods:O,isStreaming:u,isProcessing:d,scalarValueDisplay:"outline-large",scalarValueType:l,setSourcesFieldPath:b,consensusDetails:c,propertyEditorMode:f,showPropertyEditorPencil:p,formFieldIdPrefix:"ground-truth-form-field",validationFlags:m||{},setValidationFlags:h||I,showVerifiedProperty:y,computationSpec:x,setComputationSpec:g,projectId:v,children:jsx(Ql,{className:`border ${k.border} rounded-sm !text-xs ${k.tableContainerBg} ${k.headerText} disabled:opacity-100`})})});Q9.displayName="GroundTruthFormWrapper";function aE(e,t){for(let r of t)e.includes("*")&&(e=e.replace("*",r.toString()));return e}function t6(e){return e.filter(Boolean).join(".")}function iE(e,t=[]){let r=[],n=[];function o(i,s,l,c,u,d,m){let h=0,y=0;if(s=s.filter(f=>f.length!==c?true:(r[u]||(r[u]=[]),n[u]||(n[u]=[]),r[u][d+y]=i,n[u][d+y]={value:i,tpl:t6(f),idx:l,plusPathIdx:m},y++,h=1,false)),s.length===0)return [h,y];let p=new Set(s.filter(f=>f.length>c).map(f=>f[c]));if(p.has("*")&&p.size===1){let f=Array.isArray(i)?i:[];for(let v=0;v<f.length;v++){let w=f[v],[N,S]=o(w,s,[...l,v],c+1,u+h,d,m);h+=N,y=Math.max(y,S);}let[x,g]=o(void 0,s,[...l,f.length],c+1,u+h,d,m??l.length);return [h+x,Math.max(y,g)]}if(p.has("*"))throw new Error("Wildcard '*' used along with other properties");for(let f of p){let x=s.filter(N=>N[c]===f),g=i?.[f],[v,w]=o(g,x,l,c+1,u,d+y,m);h=Math.max(h,v),y+=w;}return [h,y]}let a=e&&typeof e=="object"&&"prediction_data"in e?e.prediction_data?.prediction??{}:{};if(t.includes("sum_amounts")&&"sum_amounts"in a&&console.log("[PATH-UTILS] sum_amounts found in root:",a.sum_amounts,"tplOrder:",t),o(a,t.map(i=>i.split(".")),[],0,0,0,void 0),t.includes("sum_amounts")){let i=n[0]?.find(s=>s?.tpl==="sum_amounts");console.log("[PATH-UTILS] sum_amounts pathInfo:",i);}return {table:r,paths:n}}function tm(e){let t=useRef(e);return t.current=e,useCallback((...r)=>t.current(...r),[])}function av(e,t,r,n=""){if(e===t)return true;if(typeof e!=typeof t||typeof e!="object"||e==null||t==null||Array.isArray(e)!==Array.isArray(t))return false;if(r?.shallow?.includes(n)||!r?.shallow?.length&&r?.deep?.length&&!r?.deep?.find(i=>i.startsWith(n)))return Object.is(e,t);let o=Object.keys(e),a=Object.keys(t);if(o.length!==a.length)return false;for(let i of o)if(!av(e[i],t[i],n?n+"."+i:i))return false;return true}function em(e,t,r){if(t.length===0)return typeof r=="function"?r(e):r;let[n,...o]=t,a=/^\d+$/.test(n),i=a?parseInt(n,10):n,s=e??(a?[]:{});if(a){let u=Array.isArray(s)?s:[],d=Array.isArray(s)?s[i]:void 0,m=em(d,o,r),h=u.slice();return h[i]=m,h}let l=s&&typeof s=="object"&&!Array.isArray(s)?s:{},c=l?.[i];return {...l,[i]:em(c,o,r)}}function iv({className:e,orientation:t="horizontal",decorative:r=true,...n}){return jsx(sE.Root,{"data-slot":"separator",decorative:r,orientation:t,className:T("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...n})}var rc=create(e=>({rowHeight:"medium",columnWidth:"large",setRowHeight:t=>e({rowHeight:t}),setColumnWidth:t=>e({columnWidth:t})}));var Sa=e=>{switch(e){case "small":return 48;case "medium":return 64;case "large":return 96;case "xl":return 128;case "xxl":return 160;default:return 64}},Ts=e=>{switch(e){case "small":return 24;case "medium":return 32;case "large":return 40;case "xl":return 48;case "xxl":return 64;default:return 32}};var lm=kt__default.createContext(false),fE=({isDialog:e,...t})=>{let[r,n]=useState(typeof window<"u"?window.innerHeight>=900:false);useEffect(()=>{let a=null,i=0,s=()=>{let c=window.innerHeight>=900;n(u=>u!==c?c:u);},l=()=>{let c=Date.now(),u=1e3-(c-i);u<=0?(i=c,a&&(clearTimeout(a),a=null),s()):(a&&clearTimeout(a),a=setTimeout(()=>{i=Date.now(),s(),a=null;},u));};return s(),window.addEventListener("resize",l),()=>{window.removeEventListener("resize",l),a&&clearTimeout(a);}},[]);let o=e===void 0?!r:e;return jsx(lm.Provider,{value:o,children:o?jsx(hn,{...t}):jsx(nr,{...t})})},pE=({...e})=>useContext(lm)?jsx(ju,{...e}):jsx(or,{...e}),mE=({...e})=>useContext(lm)?jsx(F0,{...e}):jsx(ar,{...e}),hE=({className:e,children:t,...r})=>useContext(lm)?jsx(gn,{className:e,...r,children:t}):jsx("h4",{className:e,...r,children:t}),gE=e=>{if(!e)return null;let t=e.match(/^(\d{1,2})\s+(\d{1,2})\s+(\d{4})$/);if(t){let[,s,l,c]=t;return new Date(parseInt(c),parseInt(l)-1,parseInt(s))}let r=e.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);if(r){let[,s,l,c]=r;return new Date(parseInt(c),parseInt(l)-1,parseInt(s))}let n=e.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/);if(n){let[,s,l,c]=n;return new Date(parseInt(c),parseInt(l)-1,parseInt(s))}let o=e.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})$/);if(o){let[,s,l,c]=o;return new Date(parseInt(c),parseInt(l)-1,parseInt(s))}if(e.match(/^\d{4}-\d{2}-\d{2}$/))return new Date(e);let i=new Date(e);return isNaN(i.getTime())?null:i},yE=e=>{switch(e){case "string":return Type;case "boolean":return CheckSquare;case "number":case "integer":return Hash;case "object":return Box;case "array":return Table;case "date":return Calendar;case "time":return Clock;case "datetime":return CalendarClock;case "enum":return List;case "$ref":return Box;default:return Type}},rm=e=>{if(!e||typeof e!="object")return false;if(e["X-ReasoningPrompt"]&&e["X-ReasoningPrompt"]!==""&&e["X-ReasoningPrompt"]!==null&&e["X-ReasoningPrompt"]!==void 0)return true;for(let t in e)if((t==="X-Reasoning"||t==="X-ReasoningSteps"||t.startsWith("X-Reasoning"))&&e[t]!==""&&e[t]!==null&&e[t]!==void 0)return true;return false},vE=e=>e.includes("reasoning___")||e.includes("reasoning__"),nm=e=>!e||typeof e!="object"?false:e["X-ComputedField"]===true,om=e=>!e||typeof e!="object"?false:e["X-FunctionField"]===true,am=e=>!e||typeof e!="object"?false:e["X-HumanInTheLoopCriterion"]===true;function qn(e,t){if(e==null||typeof e!="object")return t;let r=e;for(;r.$ref&&typeof r.$ref=="string";){let n=r.$ref.split("/");if(n[0]!=="#")throw new Error("Only internal references are supported");let o=t;for(let a=1;a<n.length;a++)o=o?.[n[a]];if(o==null||typeof o!="object")return {type:"object"};r=o;}return r}function gi(e,t){let r=qn(e,t),n=false;Array.isArray(r?.type)&&r.type.includes("null")&&(n=true,r={...r,type:r.type.find(a=>a!=="null")});let o=r.anyOf||r.oneOf||r.allOf;if(Array.isArray(o)&&o.length){o.some(i=>i?.type==="null")&&(n=true);let a=o.find(i=>{let s=qn(i,t),l=Array.isArray(s?.type)?s.type.find(c=>c!=="null"):s?.type;return l!=="null"&&(l||s.properties||s.items||s.enum)});if(a){let i=qn(a,t),{anyOf:s,oneOf:l,allOf:c,...u}=i;r=u;}}return {schema:r,nullable:n}}function im(e,t,r,n){let o=n?.seen??new WeakSet,a=n?.depth??0,i=n?.maxDepth??64,s=qn(e,r);if(s=gi(s,r).schema,a>i)return console.warn("[getSchemaFlatProperties] Max depth reached while flattening schema at path:",t.join(".")),[{key:t.join("."),type:s}];if(s&&typeof s=="object"){if(o.has(s))return console.warn("[getSchemaFlatProperties] Circular schema reference detected at path:",t.join(".")),[{key:t.join("."),type:{...s||{},type:s.type??"object",title:s.title||"(circular)"}}];o.add(s);}if(s.type==="array"){if(s.items){if(Array.isArray(s.items))return s.items.flatMap((l,c)=>im(l,[...t,String(c)],r,{seen:o,depth:a+1,maxDepth:i}));if(typeof s.items=="object"){let l=gi(s.items,r).schema;return im(l,[...t,"*"],r,{seen:o,depth:a+1,maxDepth:i})}}}else if(s.type==="object"&&s.properties)return Object.entries(s.properties).flatMap(([l,c])=>im(c,[...t,l],r,{seen:o,depth:a+1,maxDepth:i}));return [{key:t.join("."),type:s}]}function nc(e,t){let r=e;if(t==="")return e;let n=t.split(".");for(let o=0;o<n.length;o++){let a=qn(e,r),i=gi(a,r).schema;i.type==="object"&&i.properties?e=i.properties[n[o]]:i.type==="array"&&i.items&&(Array.isArray(i.items)?e=i.items[parseInt(n[o])]:typeof i.items=="object"&&(n[o]==="*"||!isNaN(parseInt(n[o])))&&(e=i.items));}return e=qn(e,r),e}function p6(e,t){let r=e;if(t==="")return e;let n=t.split(".");for(let o=0;o<n.length;o++){let a=qn(e,r),i=gi(a,r).schema;i.type==="object"&&i.properties?e=i.properties[n[o]]:i.type==="array"&&i.items&&(Array.isArray(i.items)?e=i.items[parseInt(n[o])]:typeof i.items=="object"&&(n[o]==="*"||!isNaN(parseInt(n[o])))&&(e=i.items));}return e}var sv=e=>e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ");function cv(e){return e.reduce((t,r)=>"columns"in r&&Array.isArray(r.columns)?t.concat(cv(r.columns)):t.concat([r]),[])}function bE(e,t){let r=t.reduce((n,{key:o})=>{let a=o.split(".")[e];return a&&!n.includes(a)&&n.push(a),n},[]);if(r.includes("*")&&r.length!==1)throw new Error("Invalid schema for array");return r}function m6(e,t,r,n,o){let a=JSON.parse(JSON.stringify(e)),i,s;if(!t)i=a,i.type==="object"&&i.properties&&(s=i.properties);else {let p=t.split("."),f=a;for(let g of p){let v=qn(f,a);if(!v||typeof v!="object"){console.error(`Could not resolve current node at segment: ${g} in ${t}`);return}if(f=v,g==="$defs"&&f.$defs){console.warn("Navigating through $defs, ensure path is correct."),f=f.$defs;continue}if(f.type==="object"&&f.properties&&f.properties[g])f=f.properties[g];else if(f.type==="array"&&g==="*"&&f.items&&typeof f.items=="object")f=f.items;else if(f[g]&&typeof f[g]=="object")f=f[g];else {console.error(`Could not find path: ${t} in schema. Segment: ${g}, Current Node:`,JSON.parse(JSON.stringify(f)));return}}let x=f;if(f&&typeof f=="object"&&f.$ref){let v=f.$ref.split("/");if(v[0]==="#"){let w=a;for(let N=1;N<v.length;N++)w=w?.[v[N]];w&&typeof w=="object"&&(x=w);}}i=x,i&&i.type==="object"&&(i.properties||(i.properties={}),s=i.properties);}if(!i||!s){console.error("Node for reordering is not an object with properties or path is invalid. Path:",t,"Parent Node:",i);return}let l=s,c=Object.keys(l),u=c.indexOf(r),d=c.indexOf(n);if(u===-1||d===-1||u===d){console.warn("Reorder failed: Invalid property names or indices.",{sourcePropName:r,targetPropName:n,keys:c});return}let m=Array.from(c),[h]=m.splice(u,1);m.splice(d,0,h);let y={};m.forEach(p=>{y[p]=l[p];}),i.properties=y;}function wE(e,t,r,n,o,a,i,s,l,c,u,d){var m=0;if(!e.properties||Object.keys(e.properties).length===0)return [[],0];let h=gr(l);function y(p,f){function x(P,R){return P.split(".")[f]===R}if(p.length===0)return [];let g=bE(f,p);if(g.length===1&&g[0]==="*"){let P=f+1;m=Math.max(m,P);let R=p.map(C=>({key:C.key})),E=bE(P,R);if(!(E.length===1&&E[0]==="*"))return y(R,P)}let v=(P,R,E)=>{if((E?nc(e,E):e).type==="object"){P.dataTransfer.setData("text/plain",R),P.dataTransfer.effectAllowed="move",i.current=R,s.current=E;let b=document.createElement("div");b.textContent=sv(R),b.style.position="absolute",b.style.top="-1000px",b.style.left="-1000px",b.style.padding="4px 8px",b.style.backgroundColor="rgba(200, 200, 200, 0.7)",b.style.border="1px solid #ccc",b.style.borderRadius="4px",b.style.fontSize="12px",b.style.fontFamily="sans-serif",document.body.appendChild(b),P.dataTransfer.setDragImage(b,10,10),setTimeout(()=>{document.body.removeChild(b);},0);}else P.preventDefault();},w=(P,R,E)=>{P.preventDefault();let C=i.current;if(s.current===E&&C&&C!==R){P.dataTransfer.dropEffect="move",P.currentTarget.classList.remove("border-l-2","border-r-2");let b;if(E===""?b=qn(e,e):b=qn(nc(e,E),e),b&&b.type==="object"&&b.properties){let O=Object.keys(b.properties),D=O.indexOf(C),k=O.indexOf(R);D!==-1&&k!==-1&&(D<k?P.currentTarget.classList.add("border-r-2","border-r-black"):P.currentTarget.classList.add("border-l-2","border-l-black"));}}},N=P=>{P.currentTarget.classList.remove("border-l-2","border-r-2","border-r-black","border-l-black");},S=(P,R,E)=>{P.preventDefault(),P.currentTarget.classList.remove("border-l-2","border-r-2","border-r-black","border-l-black");let C=i.current,b=s.current;C&&b===E&&C!==R&&m6(e,E,C,R),i.current=null,s.current=null;},_=P=>{i.current=null,s.current=null;};return g.flatMap(P=>{let R=p.filter(({key:J})=>x(J,P)),E=R[0].key.split(".").slice(0,f+1).join("."),C=p6(e,E),{schema:b}=gi(C,e),D=ln(b),k=L0(b,e),I=yE(D.type),F=y(R,f+1);if(D.type==="array"){let J=!r.some(X=>E.startsWith(X)),ue=J?F.length>0?[...F]:[{accessorKey:E+".*",header:({column:X})=>{let $=Sa(o)-20,L=Type;try{if(b&&b.type==="array"){let le=b.items;if(le){let ae=gi(le,e).schema,Oe=ln(ae);L=yE(Oe.type);}}}catch{L=Type;}return jsx(V,{variant:"ghost",size:"icon",className:"grow rounded-none justify-start px-1",children:jsxs("div",{className:"items-center truncate text-3xs overflow-hidden flex-row gap-2 flex",style:{maxWidth:`${$}px`,minWidth:`${$}px`},children:[jsx(L,{className:"h-3! w-3!"}),"Value"]})})}}]:[],re=F.length>0;return {accessorKey:E,foldable:re,...ue.length>0?{columns:ue}:{},header:({column:X})=>jsx(()=>{let[L,le]=useState(false),[ae,Oe]=useState(false),ye=E.toString().split(".")?.pop()||E.toString(),ft=ye,zt=E.toString().split(".");zt.pop();let st=zt.join("."),Et=sv(ye),tt=X.getLeafColumns().length||1,xe=Sa(o)*(J?tt:1)-(re?44:20),me=st?nc(e,st):e,_e=me&&me.type==="object",pt=rm(C)||rm(b)||vE(E),Fe=nm(C)||nm(b),Me=om(C)||om(b),ce=am(C)||am(b);return jsxs("div",{className:"w-full h-full flex group",draggable:_e,onDragStart:G=>_e&&v(G,ft,st),onDragOver:G=>_e&&w(G,ft,st),onDragLeave:G=>_e&&N(G),onDrop:G=>_e&&S(G,ft,st),onDragEnd:G=>_e&&_(),children:[jsxs(fE,{open:L,onOpenChange:G=>{!G&&!ae?le(false):G&&le(true);},children:[jsx(pE,{asChild:true,children:jsx(V,{variant:"ghost",size:"sm",className:`grow rounded-none h-full justify-start px-1 ${ce?"bg-emerald-50 hover:bg-emerald-100 text-emerald-900 hover:text-emerald-950":Fe?"bg-[#E0F2FE] hover:bg-blue-100 text-[#1E3A8A] hover:text-blue-900":pt?"bg-[#F6EEFF] hover:bg-purple-100 text-[#3E274A] hover:text-purple-900":`${h.headerText} ${h.headerBg}`}`,children:jsxs("div",{className:"items-center truncate text-3xs overflow-hidden flex-row gap-2 flex",style:{maxWidth:`${xe}px`,minWidth:`${xe}px`},children:[jsx(I,{className:"h-3! w-3!"})," ",Et]})})}),jsxs(mE,{className:"flex flex-col p-0 w-[400px] max-h-[80vh] overflow-y-auto",align:"start",children:[jsxs("div",{className:"flex items-center justify-between px-4 py-3",children:[jsx("div",{className:"flex items-center gap-1",children:jsx(hE,{className:"font-medium leading-none",children:Et})}),false]}),jsx(iv,{className:"my-0 "}),Fe?jsx(Wl,{fieldPath:E,jsonSchema:e,computationSpec:c,setComputationSpec:u,onClose:()=>le(false),readOnly:d==="readOnly"}):jsx(Vl,{property:C,propertyKey:E,setDropdownOpen:le,jsonSchema:e,setJsonSchema:t,editMode:ce||Me?"readOnly":d})]})]}),re&&jsx(V,{variant:"ghost",size:"icon",className:`w-9 items-center justify-center flex h-full rounded-none ${ce?"bg-emerald-50 hover:bg-emerald-100 text-emerald-900 hover:text-emerald-950":Fe?"bg-[#E0F2FE] hover:bg-blue-100 text-[#1E3A8A] hover:text-blue-900":Me?"bg-emerald-50 hover:bg-emerald-100 text-emerald-900 hover:text-emerald-950":pt?"bg-[#F6EEFF] hover:bg-purple-100 text-[#3E274A] hover:text-purple-900":`${h.headerText} ${h.headerBg}`}`,onClick:()=>{r.includes(E)?n(r.filter(G=>G!==E)):n([...r,E]);},children:r.includes(E)?jsx(ChevronDown,{className:"h-3 w-3"}):jsx(ChevronUp,{className:"h-3 w-3"})})]})},{}),cell:({row:X})=>{let $=X.getValue(E);return jsx("div",{className:"text-3xs text-muted-foreground px-1 truncate",children:Array.isArray($)?`[${$.length} items]`:"[Array]"})}}}let Z=!r.some(J=>E.startsWith(J)),pe=Z?F:[],ie=k&&F.length>0;return {accessorKey:E,foldable:ie,...pe.length>0?{columns:pe}:void 0,header:({column:J})=>jsx(()=>{let[re,X]=useState(false),[$,L]=useState(false),le=E.toString().split(".")?.pop()||E.toString(),ae=le,Oe=E.toString().split(".");Oe.pop();let ye=Oe.join("."),ft=sv(le),zt=J.getLeafColumns().length||1,st=Sa(o)*(Z?zt:1)-(ie?44:20),Et=ye?nc(e,ye):e,tt=Et&&Et.type==="object",xe=rm(C)||rm(b)||vE(E),me=nm(C)||nm(b),_e=om(C)||om(b),pt=am(C)||am(b);return jsxs("div",{className:"w-full h-full flex group",draggable:tt,onDragStart:Fe=>tt&&v(Fe,ae,ye),onDragOver:Fe=>tt&&w(Fe,ae,ye),onDragLeave:Fe=>tt&&N(Fe),onDrop:Fe=>tt&&S(Fe,ae,ye),onDragEnd:Fe=>tt&&_(),children:[jsxs(fE,{open:re,onOpenChange:Fe=>{!Fe&&!$?X(false):Fe&&X(true);},children:[jsx(pE,{asChild:true,children:jsx(V,{variant:"ghost",size:"sm",className:`grow rounded-none justify-start h-full px-1 ${pt?"bg-emerald-50 hover:bg-emerald-100 text-emerald-900 hover:text-emerald-950":me?"bg-[#E0F2FE] hover:bg-blue-100 text-[#1E3A8A] hover:text-blue-900":xe?"bg-[#F6EEFF] hover:bg-purple-100 text-[#3E274A] hover:text-purple-900":_e?"bg-emerald-50 hover:bg-emerald-100 text-emerald-900 hover:text-emerald-950":`${h.headerText} ${h.headerBg}`}`,children:jsxs("div",{className:"items-center truncate text-3xs overflow-hidden flex-row gap-2 flex",style:{maxWidth:`${st}px`,minWidth:`${st}px`},children:[jsx(I,{className:"h-3! w-3!"}),ft]})})}),jsxs(mE,{className:"flex flex-col w-[400px] p-0 gap-0 max-h-[80vh] overflow-y-auto",align:"start",children:[jsxs("div",{className:"flex items-center justify-between px-4 py-3",children:[jsx("div",{className:"flex items-center",children:jsx(hE,{className:"flex font-medium leading-none justify-center items-center",children:ft})}),jsx("div",{className:"flex items-center gap-2",children:false})]}),jsx(iv,{}),me?jsx(Wl,{fieldPath:E,jsonSchema:e,computationSpec:c,setComputationSpec:u,onClose:()=>X(false),readOnly:d==="readOnly"}):jsx(Vl,{property:C,propertyKey:E,setDropdownOpen:X,jsonSchema:e,setJsonSchema:t,editMode:pt||_e?"readOnly":d})]})]}),ie&&jsx(V,{variant:"ghost",size:"icon",className:`w-6 h-full rounded-none ${pt?"bg-emerald-50 hover:bg-emerald-100 text-emerald-900 hover:text-emerald-950":me?"bg-[#E0F2FE] hover:bg-blue-100 text-[#1E3A8A] hover:text-blue-900":_e?"bg-emerald-50 hover:bg-emerald-100 text-emerald-900 hover:text-emerald-950":xe?"bg-[#F6EEFF] hover:bg-purple-100 text-[#3E274A] hover:text-purple-900":`${h.headerText} ${h.headerBg}`}`,onClick:()=>{r.includes(E)?n(r.filter(Fe=>Fe!==E)):n([...r,E]);},children:r.includes(E)?jsx(ChevronDown,{className:"h-3 w-3"}):jsx(ChevronUp,{className:"h-3 w-3"})})]})},{}),cell:({row:J})=>{let ue=J.getValue(E),re=e.properties?.[E];if(!Pp(re))return jsx("div",{children:String(ue)});if(k)return jsx("div",{className:"text-3xs text-muted-foreground",children:ue?jsxs("div",{className:"truncate max-w-[80px]",children:[JSON.stringify(ue).substring(0,15),JSON.stringify(ue).length>15?"...":""]}):jsx("span",{children:"[Object]"})});if(re.type==="string"&&re.format){if(re.format==="date"&&ue){let X=gE(ue);return jsx("div",{children:X?X.toLocaleDateString():ue})}if(re.format==="iso-time"&&ue)return jsx("div",{children:ue});if(re.format==="date-time"&&ue){let X=gE(ue);return jsx("div",{children:X?X.toLocaleString():ue})}}return re.type==="number"?jsx("div",{className:"text-right",children:ue}):re.type==="boolean"?jsx("div",{children:ue?"Yes":"No"}):re.enum?jsx("div",{className:"capitalize",children:ue}):jsx("div",{children:String(ue)})}}})}return [(()=>{try{let p=im(e,[],e);return y(p,0)}catch(p){return console.error("[ColumnsFromSchema] Failed to flatten schema:",p),[]}})(),m]}var Ko=kt.forwardRef(({className:e,...t},r)=>jsx("table",{ref:r,className:T(" caption-bottom text-sm",e),...t}));Ko.displayName="Table";var yi=kt.forwardRef(({className:e,...t},r)=>jsx("thead",{ref:r,className:T("[&_tr]:border-b",e),...t}));yi.displayName="TableHeader";var Go=kt.forwardRef(({className:e,...t},r)=>jsx("tbody",{ref:r,className:T("[&_tr:last-child]:border-0",e),...t}));Go.displayName="TableBody";var h6=kt.forwardRef(({className:e,...t},r)=>jsx("tfoot",{ref:r,className:T("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));h6.displayName="TableFooter";var Lr=kt.forwardRef(({className:e,...t},r)=>jsx("tr",{ref:r,className:T("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),...t}));Lr.displayName="TableRow";var xr=kt.forwardRef(({className:e,...t},r)=>jsx("th",{ref:r,className:T("h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t}));xr.displayName="TableHead";var wt=kt.forwardRef(({className:e,...t},r)=>jsx("td",{ref:r,className:T("p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t}));wt.displayName="TableCell";var g6=kt.forwardRef(({className:e,...t},r)=>jsx("caption",{ref:r,className:T("mt-4 text-sm text-muted-foreground",e),...t}));g6.displayName="TableCaption";function NE({property:e,currentValue:t,onSubmit:r,likelihoods:n={},scalarValueType:o,setSourcesFieldPath:a,currentIterationId:i,disabled:s=false}){let l=useForm({defaultValues:t,resolver:ajvResolver(e,{strictSchema:false,allErrors:true})}),c=i!=="dataset"&&i!=="playground"?"promptOnly":"editable",u=gr("gray");return jsx("div",{className:"flex flex-col space-y-4 max-h-[60vh] overflow-y-auto",children:jsx(Yl,{form:l,schema:e,variant:"normal",config:{showReasoning:true},size:"sm",className:"w-full",disabled:s,isStreaming:false,isProcessing:false,scalarValueDisplay:"outline-large",scalarValueType:o,likelihoods:n,setLikelihoods:()=>{},onSubmit:r,titlePosition:"object",setSourcesFieldPath:a,propertyEditorMode:c,showPropertyEditorPencil:i==="dataset"||i==="playground",validationFlags:{},setValidationFlags:()=>{},children:jsx(Ql,{className:`border ${u.border} rounded-sm !text-xs ${u.tableContainerBg} ${u.headerText} disabled:opacity-100`})})})}function CE({name:e,property:t,currentValue:r,onSubmit:n,likelihoods:o={},scalarValueType:a,setSourcesFieldPath:i,currentIterationId:s,disabled:l=false}){let{$defs:c,...u}=t,d={type:"object",$defs:c,properties:{[e]:u},required:[e]},m=useForm({defaultValues:{[e]:Array.isArray(r)?r:[]},resolver:ajvResolver(d,{strictSchema:false,allErrors:true})}),h=f=>{n(f[e]);},y=s!=="dataset"&&s!=="playground"?"promptOnly":"editable",p=gr("gray");return jsx("div",{className:"flex flex-col space-y-4 max-h-[60vh] overflow-y-auto",children:jsx(Yl,{form:m,schema:d,variant:"normal",config:{showReasoning:true},size:"sm",className:"w-full",disabled:l,isStreaming:false,isProcessing:false,scalarValueDisplay:"outline-large",scalarValueType:a,likelihoods:o,setLikelihoods:()=>{},onSubmit:h,titlePosition:"object",setSourcesFieldPath:i,propertyEditorMode:y,showPropertyEditorPencil:s==="dataset"||s==="playground",validationFlags:{},setValidationFlags:()=>{},children:jsx(Ql,{className:`border ${p.border} rounded-sm !text-xs ${p.tableContainerBg} ${p.headerText} disabled:opacity-100`})})})}var EE=(e,t)=>{if(!e||!t)return;let r=t.split(".").map(o=>{let a=Number(o);return Number.isFinite(a)&&String(a)===o?a:o}),n=e;for(let o of r){if(n==null)return;n=Array.isArray(n)||typeof n=="object"?n[o]:void 0;}return typeof n=="boolean"?n:void 0};var uv=kt.createContext(null);function PE(){let e=kt.useContext(uv);if(!e)throw new Error("useHoverInfo must be used within a HoverInfoContext.Provider");return e}var b6=e=>{if(e)try{let t=parseISO(e);return isValid(t)?t:void 0}catch{return}},kE=new WeakMap;function x6(e,t){if(!e||!t)return;let r=kE.get(e);r||(r=new Map,kE.set(e,r));let n=r.get(t);if(n)return n;let o=nc(e,t);if(!o)return;let a=!!(o&&Pp(o)),i=gi(o,e),s=!!i.nullable,l=i.schema,c={rawProperty:o,nullable:s,isValidProp:a,isObject:l?.type==="object",isArray:l?.type==="array",isText:l?.type==="string",isEnum:!!l?.enum,isNumber:l?.type==="number",isFloat:l?.type==="float",isInteger:l?.type==="integer",isDate:l?.format==="date",isDateTime:l?.format==="date-time",isIsoTime:l?.format==="iso-time",isBoolean:l?.type==="boolean",propertyEnumVals:l?.enum??[]};return r.set(t,c),c}function dv({className:e,disabled:t=false,isReferenceSheet:r=false,...n}){let o=useRef(null),a=l=>{},i=()=>{t||o.current?.focus();},s=l=>{(l.key==="Enter"||l.key==="Escape")&&(o.current?.blur(),l.preventDefault());};return jsx(nt,{...n,className:T("cursor-default focus:cursor-text border-0 disabled:opacity-100 disabled:text-inherit",e),onKeyDown:s,onSubmit:()=>o.current?.blur(),ref:o,onMouseDown:a,onClick:l=>{document.activeElement===o.current&&l.stopPropagation(),n.onClick?.(l);},onDoubleClick:i,disabled:t})}function w6({className:e,disabled:t=false,isReferenceSheet:r=false,...n}){let o=useRef(null),[a,i]=useState(false),s=m=>{},l=()=>{t||o.current?.focus();},c=m=>{(m.key==="Enter"||m.key==="Escape")&&(o.current?.blur(),m.preventDefault());};return jsx(xS,{...n,className:T("cursor-default focus:cursor-text",e),onKeyDown:c,onSubmit:()=>o.current?.blur(),ref:o,onMouseDown:s,onClick:m=>{document.activeElement===o.current&&m.stopPropagation(),n.onClick?.(m);},onDoubleClick:l,readOnly:t})}function _6(e){let{docId:t,filename:r,fileType:n,lastModified:o,_flat_similarities:a,_full_similarities:i,_similarity:s,_aligned_flat_similarities:l,_aligned_full_similarities:c,_aligned_similarity:u,_flat_reference_elements:d,_aligned_flat_reference_elements:m,...h}=e;return h}function RE(e,t){let r=t?.$defs||{},n=e?.$defs||{};return {...e,$defs:{...r,...n}}}function fv(e){let {row:t,rowDistanceData:r,...n}=e,{pathInfo:o,similarityType:a,keyValue:i,cellColorState:s}=e,l=o?.idx?aE(i,o?.idx):void 0,c=0;if(s==="consensus"){let d=t.original?.prediction_data?.metadata?.likelihoods;d&&l&&(c=rC(d,l));}else if(s==="similarity"&&l&&r)if(a==="aligned"){let d=Tp(r.aligned_per_element_similarity||{},l);c=typeof d=="number"?d:d&&typeof d=="object"?d.aligned_similarity:0,r.aligned_flat_reference_elements?.[l];}else {let d=Tp(r.per_element_similarity||{},l);c=typeof d=="number"?d:d&&typeof d=="object"?d._similarity:0,r.flat_reference_elements?.[l];}return {...n,actualKey:l,row:t,cellScore:c}}var pv=kt.memo(e=>{let{hoverInfo:t,setHoverInfo:r}=PE(),{actualKey:n,schema:o,docId:a,cellColorState:i,setOpenPopover:s,openPopover:l,onGroundTruthDataChange:c,currentIterationId:u,cellScore:d,row:m}=fv(e),h=gr(u),[y,p]=useState(null),[f,x]=useState(false),[g,v]=useState(false),[w,N]=useState(false),S=e.pathInfo?.value;n==="sum_amounts"&&console.log("[DATA CELL] sum_amounts debug:",{actualKey:n,value:S,pathInfo:e.pathInfo,docId:a,rawRowData:m.original});let[_,P]=useState(void 0),R=kt.useCallback(W=>{try{return JSON.stringify(W)}catch{return String(W)}},[]),E=kt.useCallback(W=>W==null||W===""?null:W,[]),C=_!==void 0?_:S;useEffect(()=>{let W=Pe=>{let Pt=Pe?.detail;Pt&&Pt.docId===a&&Pt.fieldPath===n&&P(Pt.value);};return window.addEventListener("retab:optimistic-update",W),()=>{window.removeEventListener("retab:optimistic-update",W);}},[a,n]);let[b,O]=useState(S!=null?String(S):""),D=Sa(e.columnWidth);e.keyValue.endsWith("__delete")&&(D=50);let k=t?.docId===e.docId&&t?.fieldPath===n,I=tm(function(W){if(!n||!X)return;let Pe=m.original.prediction_data?.prediction??{},Pt=Tp(Pe,n),Hs=E(Pt),he=E(W),_t=E(S);if(Pt===W||R(Hs)===R(he)||R(_t)===R(he))return;let Rr=em(Pe,n.split("."),W);c(a,Rr),P(W);}),F=tm(function(W){if(n){let Pe=W;if(J&&J.format&&typeof W=="string")try{let Pt={type:"object",properties:{[n.split(".").pop()]:J}};Pe=Dn({[n.split(".").pop()]:W},Pt)[n.split(".").pop()];}catch(Pt){console.warn(`autoFormatDateTimeFields validation failed for ${n}:`,Pt);}I(Pe);}}),Z=tm(W=>{if(n){let Pe=W.currentTarget.getBoundingClientRect();e.onCellHoverStart?.({docId:a,fieldPath:n,rect:Pe});}}),pe={width:`${D}px`,minWidth:`${D}px`,backgroundColorHover:d?e.cellColorState==="consensus"?ku(Ou,d,Du,e0):ku(Ru,d,Au,t0):"transparent",backgroundColor:d?e.cellColorState==="consensus"?ku(Ou,d,Du,e0):ku(Ru,d,Au,t0):"transparent",userSelect:"none"};useEffect(()=>{O(S!=null?String(S):"");},[S]),useEffect(()=>{if(_!==void 0){let W=E(S),Pe=E(_);R(W)===R(Pe)&&P(void 0);}},[S,_,E,R]);let ie=n?x6(o,n):void 0,J=ie?.rawProperty,ue=!!(J&&J["X-ComputedField"]),re=!!(J&&J["X-FunctionField"]),X=(e.allowEditing||u.includes("dataset")||u.includes("hil"))&&!ue&&!re,$=!!ie?.nullable,L=!!ie?.isValidProp,le=!!ie?.isObject,ae=!!ie?.isArray,Oe=!!ie?.isEnum,ye=!!ie?.isNumber,ft=!!ie?.isText,zt=!!ie?.isFloat,st=!!ie?.isInteger,Et=!!ie?.isDate,tt=!!ie?.isDateTime,xe=!!ie?.isIsoTime,me=!!ie?.isBoolean,_e=W=>{if(n){let Pe=W;if(J&&J.type==="object"&&J.properties)try{Pe=Dn(W,J);}catch(Pt){console.warn(`autoFormatDateTimeFields validation failed for object ${n}:`,Pt);}I(Pe),s(null);}},pt=W=>{if(n){let Pe=W;if(J&&J.type==="array"&&J.items)try{Pe=Dn(W,J);}catch(Pt){console.warn(`autoFormatDateTimeFields validation failed for array ${n}:`,Pt);}I(Pe),s(null);}},Fe=i==="similarity"?"similarity":i==="consensus"?"consensus":"none",[Me,ce]=useState(void 0),G=(k||f||g||w)&&X,U=n?EE(e.validationFlags,n):void 0,H=u.includes("dataset")&&!!U,je=ue,Ue=re,Le=()=>re?C===true?"border-green-500 border bg-green-50":C===false?"border-red-500 border bg-red-50":C==null?"border-yellow-500 border bg-yellow-50":"border-green-500 border bg-green-50":"",Sn=()=>ue?me?C===true?"border-green-500 border bg-green-50":C===false?"border-red-500 border bg-red-50":C==null?"border-yellow-500 border bg-yellow-50":"border-green-500 border bg-green-50":"bg-blue-50":"";return useEffect(()=>{ce(b6(b));},[b]),L?jsx(wt,{className:` ${h.border} relative border-b border-r border-t-0 border-l-0 p-0 m-0 select-none`,onMouseLeave:()=>{g||w||f||e.onCellHoverEnd?.();},onMouseEnter:W=>{Z(W);},style:pe,children:jsx("div",{className:`focus-within:overflow-visible ${H?"border-green-500 border bg-green-50":Ue?Le():je?Sn():""} ${k?"border-blue-500 border w-full h-full":"w-full h-full"} `,children:le?jsxs(nr,{open:l===n,onOpenChange:W=>{console.log("[Object Popover] onOpenChange:",{open:W,actualKey:n,isEditableReference:X}),W?n&&s(n):s(null);},children:[jsx(or,{asChild:true,children:jsx("button",{className:"h-full w-full px-1 overflow-hidden justify-start text-3xs select-none text-inherit",children:C?jsx("div",{className:"truncate max-w-[80px] text-left ",children:JSON.stringify(_6(C))}):jsx("div",{className:"truncate max-w-[80px] text-left text-muted-foreground",children:`Edit ${J?.title||n}`})})}),jsx(ar,{className:"w-96 p-4 m-0 rounded-none",align:"start",side:"top",sideOffset:0,alignOffset:-1,children:l===n&&J&&jsx(NE,{disabled:!X,isOpen:l===n,property:{...RE(J,o),additionalProperties:true},currentValue:C,onSubmit:_e,likelihoods:{},scalarValueType:Fe,setSourcesFieldPath:W=>{if(!W){r(null);return}if(n){let Pe=W===n||W.startsWith(n+".")?W:`${n}.${W}`;r({docId:e.docId,fieldPath:Pe,rect:new DOMRect});}else r({docId:e.docId,fieldPath:W,rect:new DOMRect});},currentIterationId:u})})]}):ae?jsxs(nr,{open:l===n,onOpenChange:W=>{W?n&&s(n):s(null);},children:[jsx(or,{asChild:true,children:jsx("button",{className:"h-full w-full px-1 overflow-hidden justify-start text-3xs select-none text-inherit",children:C?jsx("div",{className:"truncate max-w-[80px] text-left ",children:Array.isArray(C)?`[${C.length} items]`:JSON.stringify(C)}):jsx("div",{className:"truncate max-w-[80px] text-left text-muted-foreground",children:`${J?.title||n}`})})}),jsx(ar,{className:"w-96 p-4 m-0 rounded-none",align:"start",side:"top",sideOffset:0,alignOffset:-1,children:l===n&&J&&jsx(CE,{name:n,disabled:!X,property:RE(J,o),currentValue:C,onSubmit:pt,likelihoods:{},scalarValueType:Fe,setSourcesFieldPath:W=>{if(!W){r(null);return}r({docId:e.docId,fieldPath:W,rect:new DOMRect});},currentIterationId:u})})]}):me?jsx("div",{className:"h-full flex items-center justify-center py-1",children:jsx(bl,{checked:!!C,disabled:!X,onCheckedChange:W=>{X&&F(W);},onFocus:()=>{p(`${a}:${n}`),x(true);},onBlur:()=>{p(null),x(false);},className:"disabled:opacity-100 rounded-[4px]"})}):Oe?G?jsxs(rp,{onOpenChange:W=>{v(W),W?(p(`${a}:${n}`),x(true)):(p(null),x(false));},value:C==null?"__null__":String(C),disabled:!X,onValueChange:W=>{if(W==="__null__"&&$)F(null);else if(st){let Pe=parseInt(W,10);F(Number.isNaN(Pe)?null:Pe);}else if(zt){let Pe=parseFloat(W);F(Number.isNaN(Pe)?null:Pe);}else F(W);},children:[jsx(op,{className:T("h-6 px-2 rounded-none shadow-none text-3xs text-inherit w-full border-none theme.headerText","disabled:opacity-100"),onFocus:()=>{p(`${a}:${n}`),x(true);},onBlur:()=>{g||(p(null),x(false));},children:jsx(np,{placeholder:$?"Select...":void 0})}),jsxs(ap,{position:"popper",className:"z-[60]",children:[$&&jsx(rs,{value:"__null__",className:"text-3xs text-muted-foreground",children:jsx("em",{children:"No selection"})},"__null__"),(ie?.propertyEnumVals??[]).filter(W=>W!=null&&!(typeof W=="string"&&W==="")).map(W=>jsx(rs,{value:String(W),className:"text-3xs",children:String(W)},String(W)))]})]},`${n}-${S}`):jsx("div",{className:"h-full w-full px-2 py-2 text-3xs flex items-start truncate",children:C==null||C==="__null__"?"\u2014":String(C)}):Et?G?jsxs(nr,{open:w,onOpenChange:W=>{N(W),W?(p(`${a}:${n}`),x(true)):(p(null),x(false));},children:[jsx(or,{asChild:true,children:jsxs(V,{variant:"ghost",disabled:!X,className:T("h-full hover:bg-transparent w-full justify-start text-left font-normal px-2 py-0 rounded-none shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 !text-3xs border-0 text-inherit",!C&&"text-muted-foreground","disabled:opacity-100",y===`${a}:${n}`?"absolute top-0 left-0 z-10 shadow-md":""),onClick:()=>{p(`${a}:${n}`),x(true);},children:[Me?format(Me,"PP"):jsx("span",{className:"text-muted-foreground",children:"Pick a date"}),jsx(CalendarIcon,{className:"ml-auto h-4 w-4 opacity-50"})]})}),jsx(ar,{className:"z-50 w-auto p-0",align:"start",side:"bottom",sideOffset:0,avoidCollisions:false,updatePositionStrategy:"always",children:jsx(ns,{className:"",mode:"single",selected:Me,defaultMonth:Me,onSelect:W=>{if(ce(W),W){let Pe=o0(W),Pt=zo(Pe,"2000-01-01");F(Pt||null);}else F(null);},onDayClick:W=>{if(!W)return;ce(W);let Pe=o0(W),Pt=zo(Pe,"2000-01-01");F(Pt||null),N(false),p(null),x(false);}})})]}):jsx("div",{className:"h-full w-full px-2 py-2 text-3xs flex items-center truncate",children:(()=>{try{let W=parseISO(b||""),Pe=new Date(W);return isNaN(Pe.getTime())?jsx("span",{className:"text-gray-300",children:"Pick a date"}):format(Pe,"PP")}catch{return "Invalid date"}})()}):xe?G?jsx(dv,{type:"time",value:n0(b||""),onChange:W=>{O(W.target.value);},onBlur:W=>{let Pe=b;b&&/^\d{1,2}:\d{2}$/.test(b)&&(Pe=b+":00",O(Pe));let Pt=zo(Pe,"00:00");F(Pt||null),O(Pt||""),p(null),x(false);},onFocus:()=>{p(`${a}:${n}`),x(true);},disabled:!X,className:T("h-full px-2 py-0 rounded-none shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 !text-3xs",!C&&"text-muted-foreground",y===`${a}:${n}`?"absolute top-0 left-0 z-10 ":"")}):jsx("div",{className:"h-full w-full px-2 py-2 text-3xs flex items-center truncate",children:n0(b||"")}):tt?G?jsx(dv,{type:"datetime-local",value:r0(b||""),onChange:W=>{O(W.target.value);},onFocus:()=>{p(`${a}:${n}`),x(true);},onBlur:()=>{let W=zo(b,"2000-01-01T00:00:00");F(W||null),p(null),x(false);},disabled:!X,className:`h-full px-2 py-0 rounded-none shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 !text-3xs ${y===`${a}:${n}`?"absolute top-0 left-0 z-10 bg-white ":""}`}):jsx("div",{className:"h-full w-full px-2 py-0 text-3xs flex items-center truncate",children:r0(b||"")}):ye||st?G?jsx(dv,{type:"number",value:b??null,onChange:W=>{let Pe=st?parseInt(W.target.value):parseFloat(W.target.value);O(isNaN(Pe)?"":Pe.toString());},onFocus:()=>{p(`${a}:${n}`),x(true);},onBlur:()=>{let W=st?parseInt(b):parseFloat(b);F(isNaN(W)?null:W),p(null),x(false);},disabled:!X,className:`h-full px-2 py-0 rounded-none shadow-none focus-visible:ring-0 !text-3xs ${y===`${a}:${n}`?"absolute top-0 left-0 z-10":""}`}):jsx("div",{className:"h-full w-full px-2 py-2 text-3xs flex items-center truncate",children:b??"\u2014"}):ft?jsx(w6,{type:"text",value:b??null,onChange:W=>{O(W.target.value);},onBlur:W=>{F(b||null),p(null),x(false);},onFocus:()=>{p(`${a}:${n}`),x(true);},disabled:!X,className:T("h-full px-2 py-2 rounded-none shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 !text-3xs w-full",!C&&"text-muted-foreground",y===`${a}:${n}`?"absolute top-[1px] left-[1px] z-10 bg-white shadow-md outline-1 outline-blue-500 h-64 min-w-[200px]":""),style:{resize:"none"}}):jsx("div",{className:`h-full w-full px-2 py-2 text-3xs flex items-start truncate ${h.verticalLine}`,children:C!=null?String(C):""})})},n):jsx(wt,{className:`relative ${h.verticalLine} cursor-not-allowed`,style:{width:`${D}px`,minWidth:`${D}px`}},n)},(e,t)=>{let r=fv(e),n=fv(t);return av(r,n,{deep:["pathInfo.idx"]})});pv.displayName="DataCell";var hv=kt__default.memo(({row:e,columns:t,schema:r,tableAndPaths:n,visibleKeys:o,rowCount:a,onUpdateDocument:i,editMode:s,allowEditing:l=true,onCellHoverStart:c})=>{let u=kt__default.useRef(null);if(u.current){let v=[];u.current.row!==e&&v.push("row"),u.current.columns!==t&&v.push("columns"),u.current.schema!==r&&v.push("schema"),u.current.tableAndPaths!==n&&v.push("tableAndPaths"),u.current.visibleKeys!==o&&v.push("visibleKeys"),u.current.rowCount!==a&&v.push("rowCount"),u.current.onUpdateDocument!==i&&v.push("onUpdateDocument"),u.current.editMode!==s&&v.push("editMode"),console.log("[SingleFileFormRow] Rendering - Props that changed:",v,{documentId:e.original.id,rowCount:a});}else console.log("[SingleFileFormRow] Rendering - Initial render",{documentId:e.original.id,rowCount:a});u.current={row:e,columns:t,schema:r,tableAndPaths:n,visibleKeys:o,rowCount:a,onUpdateDocument:i,editMode:s},console.log("[SingleFileFormRow] Rendering",{documentId:e.original.id,rowCount:a});let{rowHeight:d,columnWidth:m}=rc(),h=gr("single-file"),{table:y,paths:p}=n,f=e.original.id;useEffect(()=>{console.log("[SingleFileFormRow] Effect triggered - props changed",{documentId:f,rowCount:a,visibleKeys:o,visibleKeysRef:o,visibleKeysCount:o.length,rowRef:e,columnsRef:t,schemaRef:r,tableAndPathsRef:n,onUpdateDocumentRef:i});},[f,a,o,e,t,r,n,i]);let x=async(v,w)=>{console.log("[SingleFileFormRow] handleDataChange called",{docId:v,value:w}),i&&(console.log("[SingleFileFormRow] Calling onUpdateDocument"),await i({prediction_data:{prediction:w}}));};useMemo(()=>({width:"50px",minWidth:"50px",height:`${Ts(d)}px`,minHeight:`${Ts(d)}px`}),[d]);return jsx(Fragment,{children:Array(a).fill(0).map((v,w)=>jsx(Lr,{className:`flex border-b-0 ${h.border} ${h.tableRowBg} w-full`,style:{height:`${Ts(d)}px`,minHeight:`${Ts(d)}px`,minWidth:"100%"},children:o.map((N,S)=>{let _=p[w]?.[S];return jsx(pv,{keyValue:N,rowIdx:w,colIdx:S,pathInfo:_,schema:r,row:e,index:0,docId:f,cellColorState:"none",columnWidth:m,setOpenPopover:()=>{},openPopover:null,onGroundTruthDataChange:x,currentIterationId:"single-file",similarityType:"aligned",validationFlags:{},allowEditing:l,onCellHoverStart:c},`${N}-${w}`)})},`row-${w}`))})});hv.displayName="SingleFileFormRow";var $E=kt__default.memo(({table:e,columnWidth:t,stopAt:r,setStopAt:n,columns:o,foldAllSignal:a,setFoldAllSignal:i})=>{console.log("[SingleFileTableHeader] Rendering");let s=gr("single-extraction"),l=new Set;return jsx(yi,{className:`sticky top-0 z-10 ${s.headerBg}`,children:e.getHeaderGroups().map((c,u)=>jsx(Lr,{className:`flex w-max min-w-full ${s.subHeaderBg} border-b ${s.border}`,children:c.headers.map((d,m)=>{let h=l.has(d.column.id);l.add(d.column.id);function y(f){return f.columns&&f.columns.length>0?f.columns.map(y).reduce((x,g)=>x+g,0):Sa(t)}let p=y(d.column);return h?jsx("th",{className:`shrink-0 ${s.subHeaderBg} text-3xs ${s.headerText} border-r last:border-r-0 ${s.border}`,style:{width:`${p}px`,minWidth:`${p}px`}},m):jsx(xr,{className:`shrink-0 ${s.headerBg} ${s.headerText} border-r last:border-r-0 p-0 m-0 ${s.border}`,style:{width:`${p}px`,minWidth:`${p}px`,height:"38px"},colSpan:d.colSpan,children:flexRender(d.column.columnDef.header,d.getContext())},m)})},u))})});$E.displayName="SingleFileTableHeader";var gv=kt__default.memo(({stopAt:e,setStopAt:t,foldAllSignal:r,setFoldAllSignal:n,columns:o,document:a,schema:i,tableAndPaths:s,visibleKeys:l,rowCount:c,onUpdateDocument:u,editMode:d,allowEditing:m=true,onCellHoverStart:h})=>{let y=kt__default.useRef(0),p=kt__default.useRef(null);if(y.current++,p.current){let P=[];p.current.stopAt!==e&&P.push("stopAt"),p.current.setStopAt!==t&&P.push("setStopAt"),p.current.foldAllSignal!==r&&P.push("foldAllSignal"),p.current.setFoldAllSignal!==n&&P.push("setFoldAllSignal"),p.current.columns!==o&&P.push("columns"),p.current.document!==a&&P.push("document"),p.current.schema!==i&&P.push("schema"),p.current.tableAndPaths!==s&&P.push("tableAndPaths"),p.current.visibleKeys!==l&&P.push("visibleKeys"),p.current.rowCount!==c&&P.push("rowCount"),p.current.onUpdateDocument!==u&&P.push("onUpdateDocument"),p.current.editMode!==d&&P.push("editMode"),console.log(`[SingleFileVirtualizedTable] Rendering #${y.current} - Props that changed:`,P);}else console.log(`[SingleFileVirtualizedTable] Rendering #${y.current} - Initial render`);p.current={stopAt:e,setStopAt:t,foldAllSignal:r,setFoldAllSignal:n,columns:o,document:a,schema:i,tableAndPaths:s,visibleKeys:l,rowCount:c,onUpdateDocument:u,editMode:d},console.log(`[SingleFileVirtualizedTable] Rendering #${y.current}`,{columnsRef:o,columnsLength:o.length,documentRef:a,tableAndPathsRef:s,visibleKeysRef:l,visibleKeysLength:l.length});let{rowHeight:f,columnWidth:x}=rc(),g=gr("single-file"),[v,w]=useState(null);useEffect(()=>{console.log("[SingleFileVirtualizedTable] Effect triggered - props changed",{rowCount:c,visibleKeys:l,visibleKeysRef:l,visibleKeysCount:l.length,documentId:a.id,documentRef:a,columnsRef:o,tableAndPathsRef:s,schemaRef:i,onUpdateDocumentRef:u});},[c,l,a,o,s,i,u]);let N=useReactTable({data:useMemo(()=>(console.log("[SingleFileVirtualizedTable] data array recomputing",{documentRef:a}),[a]),[a]),columns:o,getCoreRowModel:getCoreRowModel()}),S=c*Ts(f),_=l.length*Sa(x);return jsx(uv.Provider,{value:{hoverInfo:v,setHoverInfo:w},children:jsx("div",{className:`flex flex-1 min-h-0 min-w-0 relative ${g.tableContainerBg}`,children:jsx("div",{className:"h-full overflow-auto w-full",children:jsxs(Ko,{className:`relative w-full rounded-none flex flex-col ${g.tableContainerBg}`,style:{minWidth:`${_}px`,height:`${S}px`},children:[jsx($E,{table:N,columnWidth:x,stopAt:e,setStopAt:t,columns:o,foldAllSignal:r,setFoldAllSignal:n}),jsx(Go,{className:"flex flex-col h-full relative w-full",children:N.getRowModel().rows.map((P,R)=>jsx(hv,{row:P,tableAndPaths:s,columns:o,schema:i,visibleKeys:l,rowCount:c,onUpdateDocument:u,editMode:d,allowEditing:m,onCellHoverStart:h},P.id))})]})})})})});gv.displayName="SingleFileVirtualizedTable";var bv=kt__default.memo(({document:e,schema:t,columnWidth:r,onUpdateDocument:n,editMode:o="editable",allowEditing:a=true,computationSpec:i,setComputationSpec:s,onCellHoverStart:l})=>{let c=kt__default.useRef(0),u=kt__default.useRef(null);if(c.current++,u.current){let _=[];u.current.document!==e&&_.push("document"),u.current.schema!==t&&_.push("schema"),u.current.columnWidth!==r&&_.push("columnWidth"),u.current.onUpdateDocument!==n&&_.push("onUpdateDocument"),u.current.editMode!==o&&_.push("editMode"),u.current.allowEditing!==a&&_.push("allowEditing"),console.log(`[SingleFileTableView] Rendering #${c.current} - Props that changed:`,_);}else console.log(`[SingleFileTableView] Rendering #${c.current} - Initial render`);u.current={document:e,schema:t,columnWidth:r,onUpdateDocument:n,editMode:o,allowEditing:a},console.log(`[SingleFileTableView] Rendering #${c.current}`,{documentId:e.id,documentRef:e,schemaRef:t});let{columnWidth:d}=rc(),m=r??d,[h,y]=useState([]),[p,f]=useState(0);useEffect(()=>{console.log("[SingleFileTableView] Effect triggered - props changed",{documentId:e.id,documentRef:e,schemaRef:t,schemaProperties:Object.keys(t.properties||{}),stopAt:h,columnWidth:m,editMode:o,allowEditing:a,onUpdateDocumentRef:n});},[e,t,h,m,o,a,n]);let x=kt__default.useRef(null),g=kt__default.useRef(null),[v]=useMemo(()=>(console.log("[SingleFileTableView] columns memo recomputing",{schemaRef:t,stopAt:h,columnWidth:m,editMode:o}),wE(t,()=>{},h,y,m,true,x,g,"single-file",i,_=>{s(_);},o)),[t,h,m,o]),w=useMemo(()=>(console.log("[SingleFileTableView] visibleKeys memo recomputing",{columnsRef:v}),cv(v).map(_=>"accessorKey"in _?_.accessorKey:void 0).filter(Boolean)),[v]),N=useMemo(()=>(console.log("[SingleFileTableView] tableAndPaths memo recomputing",{documentRef:e,visibleKeysRef:w}),e?iE(e,w):{table:[],paths:[]}),[e,w]),S=Math.max(N.paths.length,1);return jsx("div",{className:"flex flex-col flex-1 min-h-0 w-full relative",children:jsx("div",{className:"absolute inset-0 origin-top-left flex flex-col",children:jsx(gv,{stopAt:h,setStopAt:y,foldAllSignal:p,setFoldAllSignal:f,columns:v,document:e,schema:t,tableAndPaths:N,visibleKeys:w,rowCount:S,onUpdateDocument:n,editMode:o,allowEditing:a,onCellHoverStart:l})})})});bv.displayName="SingleFileTableView";function Zu({className:e,...t}){return jsx(wi.Root,{"data-slot":"tabs",className:T("flex flex-col gap-2",e),...t})}function Xu({className:e,...t}){return jsx(wi.List,{"data-slot":"tabs-list",className:T("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",e),...t})}function Ca({className:e,...t}){return jsx(wi.Trigger,{"data-slot":"tabs-trigger",className:T("data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function xv({className:e,...t}){return jsx(wi.Content,{"data-slot":"tabs-content",className:T("flex-1 outline-none",e),...t})}var mm=e=>{if(Array.isArray(e))return e.map(t=>mm(t));if(e!==null&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))r.startsWith("reasoning___")||(t[r]=mm(n));return t}return e},LE=(e,t)=>{let r=e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),n=[],o=false,a=false,i=null,s="",l=false,c=[],u=[];for(let m=0;m<r.length;m++){let h=r[m];if(a){l&&(s+=h),a=false;continue}if(h==="\\"){a=true,l&&(s+=h);continue}if(o){h==='"'?(o=false,l&&(i=s,l=false)):l&&(s+=h);continue}if(h==='"'){if(o=true,c[c.length-1]==="object"||c.length===0){let p=r.substring(m+1),f=p.match(/^([^"\\]|\\.)*"/);if(f){let x=p.substring(f[0].length).trimStart();(x.startsWith(":")||x===""||/^:/.test(p.substring(f[0].length).trim()))&&(l=true,s="");}}continue}h==="{"?(i!==null?(n.push(i),i=null):c[c.length-1]==="array"&&n.push(u[u.length-1]),c.push("object")):h==="["?(i!==null&&(n.push(i),i=null),c.push("array"),u.push(0)):h==="}"?(c.pop(),n.length>0&&n.pop(),i=null):h==="]"?(c.pop(),u.pop(),n.length>0&&n.pop(),i=null):h===":"||h===","&&(c[c.length-1]==="array"&&u[u.length-1]++,i=null);}let d=[...n];if(i!==null&&d.push(i),d.length===0||i===null){let h=e.getLineContent(t.lineNumber).match(/"([^"]+)"\s*:/);if(h){let y=h[1];d[d.length-1]!==y&&d.push(y);}}return d.length>0?d.join("."):null},q6=e=>({id:e.id,file_id:e.file.id,project_id:e.id,mime_data:{id:e.file.id,filename:e.file.filename,mime_type:e.file.mime_type},prediction_data:{prediction:e.predictions,metadata:{extraction_id:e.id}},extraction_id:e.id});function _v({extraction:e,onFieldPathChange:t,extractionDisplayOptions:r,continueButtonOptions:n,extractionStreamingOptions:o}){let a=r?.view??"form",i=r?.allowEditing??false,s=r?.showReasoning??false,l=r?.showTabs??false,c=n?.onClick,u=n?.label,d=o?.isActive??false,m=o?.data,h=o?.filename,{project:y,applyComputations:p}=Qr(),{computedSchema:f}=jo(),x=useQueryClient(),[g,v]=useState(a),[w,N]=useState(i),S=l?g:a,_=l?w:i,P=hl(),[R,E]=useState(""),[C,b]=useState(false),[O,D]=useState(false),[k,I]=useState(null),[F,Z]=useState(null),pe=useRef(null),ie=useRef([]),[J,ue]=useState(false),[re,X]=useState(false),$=useMemo(()=>!e||!e.predictions_draft||Object.keys(e.predictions_draft).length===0?false:JSON.stringify(e.predictions_draft)!==JSON.stringify(e.predictions),[e]),L=useMemo(()=>{if(!e)return {};let U=_?e.predictions_draft||e.predictions||{}:e.predictions||{};return f?Dn(U,f):U},[e,f,_]),[le,ae]=useState(null);useEffect(()=>{if(!e)return;let U=y?.published_config?.computation_spec?.computations||{};if(!(Object.keys(U).length>0)){ae(null);return}let je=false;return (async()=>{try{let Ue=await p(L);je||ae(Ue);}catch(Ue){console.error("Failed to apply computations to extraction:",Ue),je||ae(null);}})(),()=>{je=true;}},[e,L,y?.published_config?.computation_spec?.computations,p]);let Oe=le??L,ye=d?m:Oe,ft=useMemo(()=>{if(!e)return {id:"temp",project_id:"",mime_data:{id:"temp",filename:h||"Uploading...",mime_type:"application/octet-stream"},prediction_data:{prediction:ye||{},metadata:{}},extraction_id:null,dataset_id:"",iteration_id:"",dataset_document_id:""};let U=q6(e);return U.prediction_data.prediction=Oe,U},[e,Oe,h,ye]);useEffect(()=>{if(!C&&S==="code"){let U=mm(ye||{});E(JSON.stringify(U,null,2));}},[ye,C,S]);let zt=useMemo(()=>debounce(async U=>{if(!U){Z("Empty input."),D(false);return}let H;try{H=JSON.parse(U);}catch{Z("Invalid JSON."),D(false);return}Z(null),I(H),D(true);},300),[]);useEffect(()=>()=>zt.cancel(),[zt]);let st=useCallback(async()=>{if(!(!e||!k||!O||!_))try{await P.mutateAsync({extractionId:e.id,predictions_draft:k}),E(JSON.stringify(k,null,2)),b(!1),D(!1),I(null),toast.success("Draft updated successfully");}catch(U){console.error("Failed to update extraction draft:",U),toast.error("Failed to update draft");}},[e,k,O,_,P]);useEffect(()=>{if(S!=="code")return;let U=H=>{(typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(navigator.userAgentData?.platform||navigator.userAgent||"")?H.metaKey&&H.key==="s":H.ctrlKey&&H.key==="s")&&O&&(H.preventDefault(),st());};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[S,O,st]);let Et=useCallback(U=>{t?.(U);},[t]),tt=useCallback(U=>{t?.(U.fieldPath);},[t]),xe=useMemo(()=>debounce(U=>{t?.(U);},50),[t]);useEffect(()=>()=>xe.cancel(),[xe]);let me=useCallback((U,H)=>{pe.current=U,ie.current.forEach(Le=>Le.dispose()),ie.current=[];let je=U.onDidChangeCursorPosition(Le=>{let Sn=U.getModel();if(!Sn||!t)return;let W=LE(Sn,Le.position);W&&xe(W);}),Ue=U.onMouseMove(Le=>{if(!Le.target.position)return;let Sn=U.getModel();if(!Sn||!t)return;let W=LE(Sn,Le.target.position);W&&xe(W);});ie.current.push(je,Ue);},[t,xe]);useEffect(()=>()=>{ie.current.forEach(U=>U.dispose()),ie.current=[];},[]);let _e=useCallback(async U=>{if(!(!e||!_))try{let H=U?.prediction_data?.prediction??{};await P.mutateAsync({extractionId:e.id,predictions_draft:H});}catch(H){console.error("Failed to update extraction draft:",H),toast.error("Failed to update draft");}},[e,_,P]),pt=useCallback(async(U,H)=>{if(!(!e||!_))try{await P.mutateAsync({extractionId:e.id,predictions_draft:H});}catch(je){console.error("Failed to update extraction draft:",je),toast.error("Failed to update draft");}},[e,_,P]),Fe=useCallback(async()=>{if(e)try{await P.mutateAsync({extractionId:e.id,predictions_draft:e.predictions||{}}),b(!1),D(!1),I(null),Z(null),toast.success("Draft reset to original predictions"),ue(!1);}catch(U){console.error("Failed to reset draft:",U),toast.error("Failed to reset draft");}},[e,P]),Me=useCallback(async()=>{if(e)try{let U={extractionId:e.id,human_review_status:"reviewed"};$&&_&&(U.predictions=e.predictions_draft||e.predictions),await P.mutateAsync(U),x.invalidateQueries({queryKey:["extractions"]}),b(!1),D(!1),I(null),Z(null),toast.success("Marked as reviewed"),X(!1),c&&c();}catch(U){console.error("Failed to continue:",U),toast.error("Failed to mark as reviewed");}},[e,$,_,P,c,x]),ce=useMemo(()=>u||(e?.human_review_status==="review_required"?"Mark as Reviewed":_?"Update Value":"Continue"),[u,e?.human_review_status,_]),G=!d&&(e?.human_review_status==="review_required"||_);return jsxs("div",{className:"flex-1 relative min-h-0 flex flex-col overflow-hidden bg-white",children:[d&&jsxs("div",{className:"flex items-center gap-2 h-[39px] px-4 py-2 border-b border-zinc-200 top-0 left-0 right-0 bg-white",children:[jsx(Loader2,{className:"h-4 w-4 animate-spin text-indigo-600"}),jsxs("span",{className:"text-xs font-medium text-gray-700",children:["Extracting: ",h||"file"]})]}),l&&!d&&jsx("div",{className:"h-[39px] flex items-center px-2 border-b border-zinc-200 bg-white",children:jsxs("div",{className:"flex items-center justify-between w-full",children:[jsx(Zu,{value:g,onValueChange:U=>v(U),children:jsxs(Xu,{className:"flex p-0 h-7 bg-gray-50 gap-[1px] rounded-full",children:[jsxs(Ca,{value:"table",className:"text-2xs h-7 border-none hover:bg-gray-100 data-[state=active]:bg-gray-200 data-[state=active]:shadow-none shadow-none rounded-full bg-gray-50 px-3",children:[jsx(Table2,{className:"h-4 w-4 mr-1"})," Table"]}),jsxs(Ca,{value:"form",className:"text-2xs h-7 border-none hover:bg-gray-100 data-[state=active]:bg-gray-200 data-[state=active]:shadow-none shadow-none rounded-full bg-gray-50 px-3",children:[jsx(Blocks,{className:"h-4 w-4 mr-1"})," Form"]}),jsxs(Ca,{value:"code",className:"text-2xs h-7 border-none hover:bg-gray-100 data-[state=active]:bg-gray-200 data-[state=active]:shadow-none shadow-none rounded-full bg-gray-50 px-3",children:[jsx(Code,{className:"h-4 w-4 mr-1"})," Code"]})]})}),jsx(Zu,{value:w?"edit":"view",onValueChange:U=>N(U==="edit"),children:jsxs(Xu,{className:"flex p-0 h-7 bg-gray-50 gap-[1px] rounded-full",children:[jsxs(Ca,{value:"view",className:"text-2xs h-7 border-none hover:bg-gray-100 data-[state=active]:bg-gray-200 data-[state=active]:shadow-none shadow-none rounded-full bg-gray-50 px-3",children:[jsx(Eye,{className:"h-4 w-4 mr-1"})," View"]}),jsxs(Ca,{value:"edit",className:"text-2xs h-7 border-none hover:bg-gray-100 data-[state=active]:bg-gray-200 data-[state=active]:shadow-none shadow-none rounded-full bg-gray-50 px-3",children:[jsx(Edit,{className:"h-4 w-4 mr-1"})," Edit"]})]})})]})}),jsxs("div",{className:"flex-1 overflow-hidden flex flex-col min-h-0",children:[S==="form"&&jsx("div",{className:"flex-1 overflow-auto px-4 py-0 bg-white",children:jsx(oE,{itemIndex:0,iterationIndex:-1,schema:f,setSchema:noop,extractionData:ye||{},similarities:void 0,isStreamingIteration:d,isRunningIteration:d,onFieldPathChange:Et,scalarValueType:"none",consensusDetails:[],editMode:"readOnly",allowEditing:d?false:_,onPredictionChange:d?noop:pt,showPropertyEditorPencil:false,showReasoning:s})}),S==="table"&&jsx(bv,{document:ft,schema:f,editMode:"readOnly",allowEditing:d?false:_,computationSpec:y?.published_config?.computation_spec,setComputationSpec:noop,onUpdateDocument:d?async()=>{}:_e,onCellHoverStart:tt}),S==="code"&&jsxs("div",{className:"relative flex-1 min-h-0 bg-[#1E1E1E]",children:[F&&!d&&jsxs("div",{className:"absolute left-2 top-2 z-50 max-w-[75%] border border-amber-300 bg-amber-100 px-3 py-2 text-xs text-amber-900 shadow flex flex-row gap-2 rounded",children:[jsx(CircleX,{className:"w-4 h-4 text-red-800"}),F]}),C&&O&&_&&!d&&jsx("div",{className:"absolute right-2 top-2 z-50 flex items-center gap-2",children:jsxs(V,{size:"sm",onClick:st,className:"text-xs bg-teal-500 hover:bg-teal-600 h-10 px-2",children:[jsxs("span",{className:"flex items-center gap-1 mr-1",children:[jsx("span",{className:"text-xs opacity-100 font-light border border-white rounded-sm px-1.5 py-1",children:typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(navigator.userAgentData?.platform||navigator.userAgent||"")?"\u2318":"CTRL"}),jsx("span",{className:"text-xs opacity-100 font-light border border-white rounded-sm px-1.5 py-1",children:"S"})]}),"Apply Changes"]})}),jsx("div",{className:"absolute inset-0",children:jsx(Editor,{language:"json",theme:"light",value:d?JSON.stringify(mm(ye||{}),null,2):R,onChange:U=>{!_||d||(E(U||""),b(true),zt(U));},onMount:me,options:{padding:{top:10,bottom:10},automaticLayout:true,readOnly:!_||d,minimap:{enabled:false},scrollBeyondLastLine:false,fontSize:11,lineNumbers:"off",folding:false,wordWrap:"on"}})})]}),G&&jsxs("div",{className:"border-t border-zinc-200 bg-white p-2 flex items-center justify-between",children:[$&&_&&jsxs(V,{variant:"outline",size:"sm",onClick:()=>ue(true),className:"gap-2 text-xs group",children:[jsx(RotateCcw,{className:"h-4 w-4 opacity-60 group-hover:-rotate-[360deg] group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),jsx(RotateCcw,{className:"h-4 w-4 -ml-6 rotate-180 opacity-0 group-hover:rotate-0 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),"Reset Draft"]}),jsxs("button",{onClick:()=>{$&&_?X(true):Me();},className:T("h-8 ml-auto text-xs group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay px-3 ring-1 bg-gray-900 hover:bg-gray-900 hover:opacity-100 text-white ring-gray-900"),children:[ce,jsx("svg",{viewBox:"0 0 10 10","aria-hidden":"true",className:"ml-2 h-2.5 w-2.5 flex-none opacity-60 group-hover:translate-x-6 group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity",children:jsx("path",{fill:"currentColor",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"m7.25 5-3.5-2.25v4.5L7.25 5Z"})}),jsx("svg",{viewBox:"0 0 10 10","aria-hidden":"true",className:"-ml-2.5 h-2.5 w-2.5 flex-none -translate-x-2 opacity-0 group-hover:translate-x-0 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity",children:jsx("path",{fill:"currentColor",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"m7.25 5-3.5-2.25v4.5L7.25 5Z"})})]})]})]}),jsx(vo,{open:J,onOpenChange:ue,children:jsxs(bo,{children:[jsxs(xo,{children:[jsx(_o,{children:"Reset Draft?"}),jsx(So,{children:"This will discard all draft changes and revert to the original predictions. This action cannot be undone."})]}),jsxs(wo,{children:[jsx(wa,{children:"Cancel"}),jsx(No,{onClick:Fe,className:"bg-red-600 hover:bg-red-700",children:"Reset Draft"})]})]})}),jsx(vo,{open:re,onOpenChange:X,children:jsxs(bo,{children:[jsxs(xo,{children:[jsx(_o,{children:"Save Draft as Final?"}),jsx(So,{children:"This will save the draft as the final predictions, replacing the previous version."})]}),jsxs(wo,{children:[jsx(wa,{children:"Cancel"}),jsx(No,{onClick:Me,className:"bg-blue-600 hover:bg-blue-700",children:"Save & Continue"})]})]})})]})}var hm=({pageNumber:e,width:t,renderAnnotationLayer:r=true,renderTextLayer:n=true,onRenderSuccess:o,className:a,PageComponent:i})=>{let[s,l]=useState(null),[c,u]=useState(true);return useEffect(()=>{l(null),u(true);},[e]),s?jsxs("div",{className:"p-4 text-xs text-gray-500 text-center border border-gray-200 rounded bg-gray-50",children:["Page ",e," could not be loaded"]}):i?jsx(i,{pageNumber:e,width:t,renderAnnotationLayer:r,renderTextLayer:n,className:a,onLoadSuccess:()=>{u(false);},onRenderSuccess:d=>{u(false),o?.(d);},onLoadError:d=>{console.error(`Error loading page ${e}:`,d),l(d),u(false);},error:jsxs("div",{className:"p-4 text-xs text-red-500 text-center border border-red-200 rounded bg-red-50",children:["Failed to load page ",e]}),loading:jsx("div",{className:"flex items-center justify-center py-8",children:jsx(Loader2,{className:"h-6 w-6 animate-spin text-gray-400"})})}):jsx("div",{className:"flex items-center justify-center py-8",children:jsx(Loader2,{className:"h-6 w-6 animate-spin text-gray-400"})})};var Fa=Hc(eR()),fx=null,px=null,mx=null,hx=null,$d=async()=>fx&&px&&mx?{pdfjs:fx,Document:px,Page:mx}:(hx||(hx=(async()=>{let{Document:e,Page:t,pdfjs:r}=await import('react-pdf');return typeof window<"u"&&(r.GlobalWorkerOptions.workerSrc="/pdf.worker.min.mjs"),fx=r,px=e,mx=t,{pdfjs:r,Document:e,Page:t}})()),hx),nR=async()=>{let{pdfjs:e}=await $d();return e},gx=30,oR=e=>e.type==="application/pdf"||e.name.toLowerCase().endsWith(".pdf"),yx=e=>e.type==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||e.name.toLowerCase().endsWith(".docx"),vx=e=>e.type==="application/vnd.oasis.opendocument.text"||e.name.toLowerCase().endsWith(".odt"),tR=e=>yx(e)||vx(e)||e.type==="application/msword"||e.name.toLowerCase().endsWith(".doc"),bx=e=>e.type==="application/vnd.openxmlformats-officedocument.presentationml.presentation"||e.name.toLowerCase().endsWith(".pptx"),xx=e=>e.type==="application/vnd.oasis.opendocument.presentation"||e.name.toLowerCase().endsWith(".odp"),rR=e=>bx(e)||xx(e)||e.type==="application/vnd.ms-powerpoint"||e.name.toLowerCase().endsWith(".ppt"),NU=async e=>{try{let t=e.slice(0,16),r=new Uint8Array(await t.arrayBuffer()),n=Array.from(r).map(o=>o.toString(16).padStart(2,"0")).join(" ");return r.length>=4&&r[0]===37&&r[1]===80&&r[2]===68&&r[3]===70?"application/pdf":r.length>=8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71&&r[4]===13&&r[5]===10&&r[6]===26&&r[7]===10?"image/png":r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255?"image/jpeg":r.length>=6&&r[0]===71&&r[1]===73&&r[2]===70&&r[3]===56&&(r[4]===55||r[4]===57)&&r[5]===97?"image/gif":r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===87&&r[9]===69&&r[10]===66&&r[11]===80?"image/webp":(r.length>=4&&r[0]===80&&r[1]===75&&(r[2]===3||r[2]===5||r[2]===7)&&(r[3]===4||r[3]===6||r[3]===8),null)}catch{return null}},CU=async e=>{let t=await NU(e);if(t&&t!==e.type){let r=await e.arrayBuffer();return new File([r],e.name,{type:t})}return e},EU=async e=>{try{if(!e||e.size===0)return {corrupted:!0,reason:"File is empty (0 bytes)"};if(oR(e))try{let t=await nR(),r=await e.arrayBuffer(),n=new Uint8Array(r),a=await t.getDocument({data:n,stopAtErrors:!0}).promise;try{await a.cleanup?.();}catch{}try{a.destroy?.();}catch{}return {corrupted:!1}}catch(t){let r=t instanceof Error?t.message:"Unknown error";return r.includes("worker")||r.includes("Worker")||r.includes("module specifier")||r.includes("network")||r.includes("fetch")?(console.warn(`PDF validation skipped due to infrastructure error: ${r}`),{corrupted:!1}):{corrupted:!0,reason:`Invalid PDF structure: ${r}`}}if(yx(e))try{let t=await e.arrayBuffer(),r=await Fa.default.loadAsync(t);return r.file("[Content_Types].xml")||r.file("word/document.xml")?{corrupted:!1}:{corrupted:!0,reason:"Invalid DOCX: missing required document structure (Content_Types.xml or word/document.xml)"}}catch(t){return {corrupted:!0,reason:`Invalid DOCX archive: ${t instanceof Error?t.message:"Unknown error"}`}}if(bx(e))try{let t=await e.arrayBuffer(),r=await Fa.default.loadAsync(t);return r.file("[Content_Types].xml")||r.file("ppt/presentation.xml")?{corrupted:!1}:{corrupted:!0,reason:"Invalid PPTX: missing required presentation structure (Content_Types.xml or ppt/presentation.xml)"}}catch(t){return {corrupted:!0,reason:`Invalid PPTX archive: ${t instanceof Error?t.message:"Unknown error"}`}}if(vx(e))try{let t=await e.arrayBuffer();return (await Fa.default.loadAsync(t)).file("content.xml")?{corrupted:!1}:{corrupted:!0,reason:"Invalid ODT: missing content.xml"}}catch(t){return {corrupted:!0,reason:`Invalid ODT archive: ${t instanceof Error?t.message:"Unknown error"}`}}if(xx(e))try{let t=await e.arrayBuffer();return (await Fa.default.loadAsync(t)).file("content.xml")?{corrupted:!1}:{corrupted:!0,reason:"Invalid ODP: missing content.xml"}}catch(t){return {corrupted:!0,reason:`Invalid ODP archive: ${t instanceof Error?t.message:"Unknown error"}`}}return {corrupted:!1}}catch(t){return {corrupted:true,reason:`Failed to read file: ${t instanceof Error?t.message:"Unknown error"}`}}},PU=async e=>{let t=await nR(),r=await e.arrayBuffer(),n=new Uint8Array(r),a=await t.getDocument({data:n}).promise,i=a.numPages;try{await a.cleanup?.();}catch{}try{a.destroy?.();}catch{}return i},TU=async e=>{let t=await e.arrayBuffer(),n=(await Fa.default.loadAsync(t)).file("docProps/app.xml");if(!n)throw new Error("docProps/app.xml not found");let o=await n.async("text"),s=new DOMParser().parseFromString(o,"application/xml").getElementsByTagName("Pages")[0];if(!s||!s.textContent)throw new Error("Pages metadata not found");let l=parseInt(s.textContent,10);if(!Number.isFinite(l)||l<=0)throw new Error("Invalid Pages value");return l},kU=async e=>{let t=await e.arrayBuffer(),n=(await Fa.default.loadAsync(t)).file("meta.xml");if(!n)throw new Error("meta.xml not found");let o=await n.async("text"),i=new DOMParser().parseFromString(o,"application/xml"),s=i.getElementsByTagName("meta:document-statistic")[0]||i.getElementsByTagName("document-statistic")[0];if(!s)throw new Error("document-statistic not found");let l=s.getAttribute("meta:page-count")||s.getAttribute("page-count");if(!l)throw new Error("page-count not found");let c=parseInt(l,10);if(!Number.isFinite(c)||c<=0)throw new Error("Invalid page-count value");return c},RU=async e=>{let t=await e.arrayBuffer(),n=(await Fa.default.loadAsync(t)).file("docProps/app.xml");if(!n)throw new Error("docProps/app.xml not found");let o=await n.async("text"),s=new DOMParser().parseFromString(o,"application/xml").getElementsByTagName("Slides")[0];if(!s||!s.textContent)throw new Error("Slides metadata not found");let l=parseInt(s.textContent,10);if(!Number.isFinite(l)||l<=0)throw new Error("Invalid Slides value");return l},OU=async e=>{let t=await e.arrayBuffer(),n=(await Fa.default.loadAsync(t)).file("meta.xml");if(!n)throw new Error("meta.xml not found");let o=await n.async("text"),i=new DOMParser().parseFromString(o,"application/xml"),s=i.getElementsByTagName("meta:document-statistic")[0]||i.getElementsByTagName("document-statistic")[0];if(!s)throw new Error("document-statistic not found");let l=s.getAttribute("meta:slide-count")||s.getAttribute("slide-count");if(!l)throw new Error("slide-count not found");let c=parseInt(l,10);if(!Number.isFinite(c)||c<=0)throw new Error("Invalid slide-count value");return c},DU=async e=>{if(oR(e))return PU(e);if(yx(e))return TU(e);if(vx(e))return kU(e);if(bx(e))return RU(e);if(xx(e))return OU(e);throw new Error("Unsupported file type for page counting")},aR=async e=>{let t=gx,r=[],n=[],o=[];for(let a of e){let i=await CU(a);if(i.type==="application/pdf"||tR(i)||rR(i)||i.size===0)try{let l=await EU(i);if(l.corrupted){o.push({name:i.name,reason:l.reason});continue}}catch(l){let c=l instanceof Error?l.message:"Unknown validation error";o.push({name:i.name,reason:c});continue}if(i.type==="application/pdf"||tR(i)||rR(i))try{let l=await DU(i);if(l>t){n.push({name:i.name,pages:l});continue}}catch{}r.push(i);}return {accepted:r,rejected:n,corrupted:o}};var FU={cMapUrl:"https://unpkg.com/pdfjs-dist@4.4.168/cmaps/",cMapPacked:true},MU=(e,t)=>{let r=new Uint8Array(e),n=r.length;if(n===0)return `${t}-0`;let a=[0,Math.floor(n/2),n-1].map(i=>r[i]?.toString(16)??"0");return [t,n.toString(),...a].join("-")},jU=({content:e})=>{let[t,r]=useState(null),[n,o]=useState(null),[a,i]=useState(true),[s,l]=useState(null),[c,u]=useState(null),d=useRef(true),{fetchWithAuth:m}=De();useEffect(()=>(d.current=true,()=>{d.current=false;}),[]),useEffect(()=>{e.byteLength>0&&(async()=>{let p=new FormData,f=new Blob([e],{type:"message/rfc822"});p.append("file",f,"email.eml");let x=new Uint8Array(e);d.current&&u(x);try{let g=await m("/v1/processors/automations/outlook/convert_to_email_data_and_upload_file?return_inline_body=true",{method:"POST",body:p});if(!d.current)return;if(g.ok){let v=await g.json();r(v);}else throw new Error("Failed to convert EML to email model")}catch(g){d.current&&(console.error("Error converting EML:",g),o(g.message));}finally{d.current&&i(false);}})();},[e]);return n?jsx("div",{className:"text-red-500 text-center",children:n}):!t||a?jsx("div",{className:"text-center",children:"Processing email..."}):jsxs("div",{className:"flex flex-col h-full space-y-0",children:[jsx("div",{className:"w-full overflow-clip bg-background border-b border-gray-200",children:jsx("div",{className:"flex flex-row items-center space-x-2 px-2 py-2 justify-between h-10",children:jsxs("div",{className:"flex flex-row items-center space-x-2 min-w-0 grow overflow-hidden text-xs",children:[jsx(Mail,{className:"h-4 w-4 shrink-0 text-gray-600 cursor-pointer"}),jsxs("div",{className:"ml-2 text-gray-500 truncate overflow-hidden flex-1 w-full flex justify-between",children:[jsx("div",{children:jsx("span",{className:"font-semibold w-20 text-gray-600",children:t.subject})}),jsxs("div",{children:[jsx("span",{className:"pl-2 font-semibold w-20 text-gray-700",children:"From:"}),jsx("span",{className:"underline flex-1 text-gray-500",children:t.sender.email}),jsx("span",{className:"ml-2 font-semibold w-20 text-gray-700",children:"To:"}),jsx("span",{className:"underline flex-1 text-gray-500",children:t.recipients_to[0]?.email})]})]})]})})}),jsx("div",{className:"grid grid-cols-2 gap-4 text-xs",children:t.attachments.filter(y=>!y.metadata?.is_inline).length>0&&jsx("div",{className:"col-span-2",children:jsxs("div",{className:"grid grid-cols-3 gap-0",children:[jsx("li",{onClick:()=>l(null),className:`py-1 px-2 flex flex-row space-x-2 border justify-between cursor-pointer ${s===null?"bg-purple-100 border-purple-300 text-purple-700":"bg-gray-100 border-gray-200 text-gray-600 hover:bg-gray-100"}`,children:jsx("div",{className:"w-64 truncate",children:"Mail Body"})}),t.attachments.filter(y=>!y.metadata?.is_inline).map((y,p)=>jsx("li",{onClick:()=>l(y.url),className:`py-1 px-2 flex flex-row space-x-2 border justify-between cursor-pointer ${s===y.url?"bg-purple-100 border-purple-300 text-purple-700":"bg-gray-100 border-gray-200 text-gray-600 hover:bg-gray-100"}`,children:jsx("div",{className:"w-64 truncate",children:y.filename})},p))]})})}),jsx("div",{className:"overflow-auto grow",children:t&&(t.attachments.filter(y=>!y.metadata?.is_inline).find(y=>y.url===s)?(()=>{let p=t.attachments.find(f=>f.url===s).url.split(";base64,");if(p.length===2){let f=p[0].replace("data:",""),x=p[1],g=atob(x),v=new Uint8Array(g.length);for(let w=0;w<g.length;w++)v[w]=g.charCodeAt(w);return jsx(lR,{content:v.buffer,mimeType:f},s)}else return jsx("div",{children:"Malformed data URL"})})():c&&jsx(LU,{emailData:t}))})]})},LU=({emailData:e})=>{let t=kt__default.useRef(null),r=kt__default.useRef(null);return kt__default.useEffect(()=>{if(t.current&&e.body_html){let n=()=>{let o=t.current,a=r.current;if(o&&a){let i=a.querySelector(".email-header")?.clientHeight||0,s=a.clientHeight-i;o.style.height=`${s}px`;}};return t.current.onload=n,window.addEventListener("resize",n),setTimeout(n,100),()=>window.removeEventListener("resize",n)}},[e.body_html]),jsxs("div",{ref:r,className:"h-full flex flex-col overflow-hidden",children:[jsxs("div",{className:"email-header bg-muted/20 p-4",children:[jsx("h2",{className:"text-xl font-bold mb-2",children:e.subject}),jsxs("p",{className:"text-sm text-muted-foreground mb-1",children:[jsx("strong",{children:"From:"})," ",e.sender.display_name||e.sender.email," <",e.sender.email,">"]}),jsxs("p",{className:"text-sm text-muted-foreground mb-1",children:[jsx("strong",{children:"To:"})," ",e.recipients_to.map(n=>`${n.display_name||n.email} <${n.email}>`).join(", ")]}),e.recipients_cc?.length>0&&jsxs("p",{className:"text-sm text-muted-foreground mb-1",children:[jsx("strong",{children:"CC:"})," ",e.recipients_cc.map(n=>`${n.display_name||n.email} <${n.email}>`).join(", ")]}),jsxs("p",{className:"text-sm text-muted-foreground",children:[jsx("strong",{children:"Date:"})," ",new Date(e.sent_at).toLocaleString()]})]}),jsx("div",{className:"flex-1 overflow-hidden",children:e.body_html?jsx("iframe",{ref:t,srcDoc:String(e.body_html),title:"Email content",className:"w-full h-full border-none",sandbox:"allow-same-origin allow-scripts"}):jsx("div",{className:"p-4 h-full overflow-auto",children:jsx("pre",{className:"whitespace-pre-wrap",children:e.body_plain||"No content"})})})]})},BU=({content:e})=>{let t=useRef(null),[r,n]=useState(true),[o,a]=useState(null);return useEffect(()=>{(async()=>{if(t.current){n(true),a(null),t.current.innerHTML="";try{let{renderAsync:s}=await import('docx-preview');await s(e,t.current,void 0,{className:"docx-wrapper",inWrapper:!0,ignoreWidth:!1,ignoreHeight:!0,ignoreFonts:!1,breakPages:!0,ignoreLastRenderedPageBreak:!0,experimental:!1,trimXmlDeclaration:!0,useBase64URL:!0,renderHeaders:!0,renderFooters:!0,renderFootnotes:!0,renderEndnotes:!0});}catch(s){console.error("Error rendering DOCX:",s),a("Failed to render document");}finally{n(false);}}})();},[e]),jsxs("div",{className:"w-full h-full overflow-hidden flex flex-col",children:[r&&jsx("div",{className:"flex items-center justify-center h-full",children:jsx(Loader2,{className:"h-8 w-8 animate-spin text-gray-400"})}),o&&jsx("div",{className:"flex items-center justify-center h-full text-red-500 text-sm",children:o}),jsx("div",{ref:t,className:"w-full h-full overflow-auto",style:{display:r||o?"none":"block"}}),jsx("style",{jsx:true,global:true,children:`
66
+ ${k(O.category)}
67
+ `,children:D(O.category)}),jsx("div",{className:"flex-1 min-w-0",children:jsx("div",{className:"text-xs text-gray-900 dark:text-gray-100",children:O.display})}),O.category==="field"&&O.typeBadge&&jsx("span",{className:"ml-auto text-[10px] px-1.5 py-0.5 rounded bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-200 dark:border-gray-700 flex-shrink-0",children:O.typeBadge})]},`${O.category}-${O.value}-${$}`))]})]})}function Nc({fieldPath:e,jsonSchema:t,computationSpec:r,setComputationSpec:n,onDelete:a,onClose:o,readOnly:i=false}){let s=r.computations[e];console.log("Rendering Computed Field Card"),console.log("Current Computation",s);let{prefix:l,suffix:c}=useMemo(()=>{let b=e.lastIndexOf(".");return b===-1?{prefix:"",suffix:e}:{prefix:e.substring(0,b),suffix:e.substring(b+1)}},[e]),[u,d]=useState(c),[g,f]=useState(s?.expression||""),[h,m]=useState(null),[p,v]=useState(null),y=useMemo(()=>l?`${l}.${u}`:u,[l,u]),x=Rt.useRef(l);Rt.useEffect(()=>{x.current!==l&&(f(""),x.current=l);},[l]),Rt.useEffect(()=>{try{if(Object.keys(r.computations).length>0){let b=ed(r.computations);m(b);}else m(null);}catch{m(null);}},[r]);let w=useMemo(()=>h&&e?h[e]:null,[h,e]),_=useMemo(()=>Object.keys(r.computations).filter(b=>b!==e),[r.computations,e]);useMemo(()=>{let b={computations:{...r.computations}};if(g&&g.trim()!=="")try{let k=fn(g);b.computations[y]={expression:g};}catch{}return b},[r,y,g,t]);let C=useMemo(()=>{let b=[];if(!u||u.trim()===""?b.push("Field name is required"):(u.includes(".")&&b.push("Field name cannot contain '.'"),(u.startsWith("_")||u.endsWith("_"))&&b.push("Field name should not start or end with '_'"),Object.keys(r.computations).filter(D=>D!==e).includes(y)&&b.push("This field path already has a computation")),!g||g.trim()==="")b.push("Expression is required");else {let k=new Set(Object.keys(r.computations).filter(O=>O!==e)),D=g0(g,t,k);D.isValid||b.push(...D.errors);}return {isValid:b.length===0,errors:b}},[g,u,y,e,r,t]),P=()=>{if(p)try{let b={...r.computations};if(b[p.oldPath]){let k=v0(b,p.oldPath,p.newPath);if(g&&g.trim()!==""){let D=fn(g);k.updatedSpec[p.newPath]={expression:g};}else delete k.updatedSpec[p.newPath];n({computations:k.updatedSpec});}else {let k={...b};if(g&&g.trim()!==""){let D=fn(g);k[p.newPath]={expression:g};}else delete k[p.newPath];n({computations:k});}v(null),o&&o();}catch(b){console.error(`Rename failed: ${b.message}`),v(null);}},T=()=>{p&&d(c),v(null);},N=()=>{if(!C.isValid)return;if(y!==e&&r.computations[e])try{let D=(h||ed(r.computations))[e]?.dependents||[];if(D.length>0){v({show:!0,oldPath:e,newPath:y,affectedComputations:[e,...D]});return}}catch(k){console.warn("Error checking dependencies for rename:",k);}let b={...r.computations};y!==e&&b[e]&&delete b[e],g&&g.trim()!==""?b[y]={expression:g}:delete b[y],n({computations:b}),o&&o();},S=()=>{let b={...r.computations};delete b[e],n({computations:b}),o&&o(),a&&a();};return jsxs("div",{className:"flex flex-col h-full bg-gray-50 rounded-2xl",children:[jsx("div",{className:"bg-white shadow-xs flex-1 overflow-y-auto max-h-[60vh] rounded-2xl",children:jsxs("div",{className:"p-4 space-y-4",children:[w&&w.depth>1&&jsxs("div",{className:"relative flex max-w-6xl justify-center items-center ring-1 ring-inset bg-blue-50 text-blue-600 ring-blue-600/20 gap-2 rounded-md p-2",children:[jsx(AlertCircle,{className:"size-3.5 stroke-2"}),jsxs("div",{className:"flex flex-1 flex-wrap items-center justify-between gap-x-3 gap-y-2",children:[jsx("div",{className:"text-xs font-normal",children:"This field is computed based on other fields"}),w&&jsxs(xn,{variant:"default",className:"text-xs",children:["Level ",w.depth]})]})]}),w&&(w.dependencies.length>0||w.dependents.length>0)&&jsxs("div",{className:"space-y-1.5 text-xs bg-muted/50 p-3 rounded-md border border-muted",children:[w.dependencies.length>0&&jsxs("div",{className:"flex items-start gap-1.5",children:[jsx(ArrowDown,{className:"h-3 w-3 mt-0.5 text-muted-foreground flex-shrink-0"}),jsxs("div",{className:"flex-1",children:[jsx("span",{className:"text-muted-foreground font-medium",children:"Depends on: "}),jsx("span",{className:"text-foreground",children:w.dependencies.join(", ")})]})]}),w.dependents.length>0&&jsxs("div",{className:"flex items-start gap-1.5",children:[jsx(ArrowRight,{className:"h-3 w-3 mt-0.5 text-muted-foreground flex-shrink-0"}),jsxs("div",{className:"flex-1",children:[jsx("span",{className:"text-muted-foreground font-medium",children:"Used by: "}),jsx("span",{className:"text-foreground",children:w.dependents.join(", ")})]})]})]}),jsxs("div",{children:[jsx(nr,{className:"text-sm font-medium text-gray-700 mb-2 block",children:"Name"}),jsx("div",{className:"flex items-center gap-1",children:jsx(Ze,{value:u,onChange:b=>{let k=b.target.value.replace(/[^a-zA-Z0-9_]/g,"");d(k);},placeholder:"field_name",className:"font-normal text-xs flex-1",disabled:i})})]}),jsxs("div",{className:"space-y-1.5",children:[jsx(nr,{className:"text-sm font-medium text-gray-700",children:"Formula Expression"}),jsx("div",{className:"h-64 overflow-y-auto",children:jsx(RE,{value:g,onChange:f,schema:t,computedFields:_,targetPath:y,placeholder:"e.g., SUM(items.*.price) * 1.1 or (a + b) / c",disabled:i})}),!i&&jsxs("p",{className:"text-xs text-muted-foreground",children:["Start typing to see suggestions. Use ",jsx("kbd",{className:"px-1 py-0.5 text-[10px] font-mono bg-muted rounded",children:"\u2191"})," ",jsx("kbd",{className:"px-1 py-0.5 text-[10px] font-mono bg-muted rounded",children:"\u2193"})," to navigate, ",jsx("kbd",{className:"px-1 py-0.5 text-[10px] font-mono bg-muted rounded",children:"Enter"})," or ",jsx("kbd",{className:"px-1 py-0.5 text-[10px] font-mono bg-muted rounded",children:"Tab"})," to select"]})]}),!C.isValid&&jsxs("div",{className:"bg-destructive/10 border border-destructive/20 rounded p-2",children:[jsx("p",{className:"text-xs font-medium text-destructive mb-1",children:"Errors:"}),jsx("ul",{className:"text-xs text-destructive space-y-0.5",children:C.errors.map((b,k)=>jsxs("li",{children:["\u2022 ",b]},k))})]})]})}),!i&&jsxs("div",{className:"p-4 flex justify-between rounded-b-2xl",children:[jsx("div",{children:jsx(K,{type:"button",size:"sm",onClick:S,className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay ring-1 bg-destructive hover:bg-destructive hover:opacity-80 text-white ring-destructive gap-2",children:"Delete Computation"})}),jsx("div",{className:"flex items-center gap-2",children:jsx(K,{onClick:N,disabled:!C.isValid,size:"sm",className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay text-sm h-[1.875rem] px-3 ring-1 bg-gray-900 hover:bg-gray-900 hover:opacity-80 text-white ring-gray-900",children:"Save Changes"})})]}),jsx(Ri,{open:p?.show,onOpenChange:b=>!b&&T(),children:jsxs(Oi,{children:[jsxs(Di,{children:[jsx($i,{children:"Cascade Rename Detected"}),jsxs(Ii,{children:["Renaming ",jsx("code",{className:"bg-muted px-1.5 py-0.5 rounded text-foreground font-medium",children:p?.oldPath})," to"," ",jsx("code",{className:"bg-muted px-1.5 py-0.5 rounded text-foreground font-medium",children:p?.newPath})," will affect"," ",jsxs("strong",{children:[(p?.affectedComputations.length||0)-1," other computation(s)"]}),"."]})]}),p&&p.affectedComputations.length>1&&jsxs("div",{className:"space-y-2 my-4",children:[jsx("p",{className:"text-sm font-medium",children:"The following computations will be updated:"}),jsx("div",{className:"bg-muted rounded-lg p-3 space-y-1.5 max-h-48 overflow-y-auto",children:p.affectedComputations.slice(1).map(b=>jsxs("div",{className:"flex items-start gap-2 text-xs",children:[jsx(ArrowRight,{className:"h-3 w-3 mt-0.5 text-muted-foreground flex-shrink-0"}),jsx("code",{className:"text-foreground",children:b})]},b))})]}),jsxs(Ai,{children:[jsx(wc,{onClick:T,children:"Cancel"}),jsx(Fi,{onClick:P,children:"Confirm Rename"})]})]})})]})}var vm=e=>{let t=e.split("."),r=t.pop()||"",n=t.join(".");return n?`${n}.reasoning___${r}`:`reasoning___${r}`},Sv="__none__",_d="__empty__",hm=e=>{if(e==null)return Sv;if(e==="")return _d;let t=String(e);return t===""?_d:t},IE=e=>e===Sv?null:e===_d?"":e,Nv=Rt__default.forwardRef(({className:e,variant:t,uncertainty:r,value:n,onValueChange:a,disabled:o,placeholder:i="Pick a date",size:s,scalarValueType:l},c)=>{let[u,d]=Rt__default.useState(false),{setIsEditing:g}=Tn();return jsx("div",{className:(()=>{switch(t){case "underline-close":return "border-b-2 pb-0";case "underline-distant":return "border-b-2 pb-2";case "left-border-close":return "border-l-4 pl-0";case "left-border-distant":return "border-l-4 pl-2";default:return ""}})(),style:(()=>{switch(t){case "underline-close":case "underline-distant":case "left-border-close":case "left-border-distant":return {borderColor:Ne(r,l)};default:return {}}})(),children:jsxs(Ht,{open:u,onOpenChange:f=>{d(f),g(f);},children:[jsx(Jt,{asChild:true,children:jsxs(K,{ref:c,variant:"outline",disabled:o,className:R(e,s==="sm"?"h-[32px] text-sm":"h-[42px] text-sm","w-full justify-start text-left font-normal",!n&&"text-muted-foreground"),style:(()=>{switch(t){case "blur-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 2px 1px ${Ne(r,l)}`};case "blur-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 4px 2px ${Ne(r,l)}`};case "blur-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 6px 3px ${Ne(r,l)}`};case "outline-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 1px ${Ne(r,l)}`};case "outline-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 2px ${Ne(r,l)}`};case "outline-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 3px ${Ne(r,l)}`};default:return {}}})(),children:[n&&isValid(n)?format(n,"PPP"):i,jsx(CalendarIcon,{className:"ml-auto h-4 w-4 opacity-50"})]})}),jsx(Wt,{className:"w-auto p-0",align:"start",children:jsx(Co,{mode:"single",selected:n&&isValid(n)?n:void 0,defaultMonth:n&&isValid(n)?n:void 0,onSelect:f=>{a?.(f||null),d(false),g(false);},captionLayout:"dropdown"})})]})})});Nv.displayName="StyledDatePicker";var T6=Rt__default.forwardRef(({className:e,variant:t,uncertainty:r,value:n,onValueChange:a,disabled:o,size:i,scalarValueType:s},l)=>{let{setIsEditing:c}=Tn();return jsx("div",{className:(()=>{switch(t){case "underline-close":return "border-b-2 pb-0";case "underline-distant":return "border-b-2 pb-2";case "left-border-close":return "border-l-4 pl-0";case "left-border-distant":return "border-l-4 pl-2";default:return ""}})(),style:(()=>{switch(t){case "underline-close":case "underline-distant":case "left-border-close":case "left-border-distant":return {borderColor:Ne(r,s)};default:return {}}})(),children:jsx(Ze,{ref:l,type:"time",disabled:o,value:n||"",onClick:()=>{c(true);},onChange:u=>{c(true),a?.(u.target.value);},onBlur:()=>{c(false);},className:R(e,i==="sm"?"h-[32px] text-sm":"h-[42px] text-sm","bg-background appearance-none [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-calendar-picker-indicator]:appearance-none"),style:(()=>{switch(t){case "blur-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 2px 1px ${Ne(r,s)}`};case "blur-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 4px 2px ${Ne(r,s)}`};case "blur-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 6px 3px ${Ne(r,s)}`};case "outline-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 1px ${Ne(r,s)}`};case "outline-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 2px ${Ne(r,s)}`};case "outline-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 3px ${Ne(r,s)}`};default:return {}}})()})})});T6.displayName="StyledTimePicker";var FE=Rt__default.forwardRef(({className:e,variant:t,uncertainty:r,value:n,onValueChange:a,disabled:o,size:i,scalarValueType:s},l)=>{let{setIsEditing:c}=Tn(),u=VE(n),d=u&&isValid(u)?new Date(u.getFullYear(),u.getMonth(),u.getDate()):null,g=u&&isValid(u)?`${u.getHours().toString().padStart(2,"0")}:${u.getMinutes().toString().padStart(2,"0")}`:"",[f,h]=Rt__default.useState(g);Rt__default.useEffect(()=>{h(g);},[g]);let m=v=>{if(!v){a?.(null);return}let y=g||"00:00:00",[x,w,_]=y.split(":").map(Number),E=new Date(v);E.setHours(x,w,_||0);let C=E.getFullYear(),P=(E.getMonth()+1).toString().padStart(2,"0"),T=E.getDate().toString().padStart(2,"0"),N=E.getHours().toString().padStart(2,"0"),S=E.getMinutes().toString().padStart(2,"0"),b=E.getSeconds().toString().padStart(2,"0");a?.(`${C}-${P}-${T}T${N}:${S}:${b}`);},p=v=>{if(!d&&!v){a?.(null);return}let y=d||new Date,[x,w,_]=v.split(":").map(Number),E=new Date(y);E.setHours(x,w,_||0);let C=E.getFullYear(),P=(E.getMonth()+1).toString().padStart(2,"0"),T=E.getDate().toString().padStart(2,"0"),N=E.getHours().toString().padStart(2,"0"),S=E.getMinutes().toString().padStart(2,"0"),b=E.getSeconds().toString().padStart(2,"0");a?.(`${C}-${P}-${T}T${N}:${S}:${b}`);};return jsxs("div",{ref:l,className:"flex gap-2",children:[jsx(Nv,{variant:t,uncertainty:r,value:d,onValueChange:m,disabled:o,className:e,size:i,placeholder:"Select date",scalarValueType:s}),jsx("div",{className:(()=>{switch(t){case "underline-close":return "border-b-2 pb-0";case "underline-distant":return "border-b-2 pb-2";case "left-border-close":return "border-l-4 pl-0";case "left-border-distant":return "border-l-4 pl-2";default:return ""}})(),style:(()=>{switch(t){case "underline-close":case "underline-distant":case "left-border-close":case "left-border-distant":return {borderColor:Ne(r,s)};default:return {}}})(),children:jsx(gm,{type:"time",disabled:o,value:f||"",onChange:v=>{h(v.target.value);},onBlur:v=>{let y=f;v.target.value&&/^\d{1,2}:\d{2}$/.test(v.target.value)&&(y=v.target.value+":00",h(y)),p(y);},className:R(e,i==="sm"?"h-[32px] text-sm":"h-[42px] text-sm","bg-background"),style:(()=>{switch(t){case "blur-small":return {boxShadow:`0 0 2px 1px ${Ne(r,s)}`};case "blur-large":return {boxShadow:`0 0 4px 2px ${Ne(r,s)}`};case "blur-xlarge":return {boxShadow:`0 0 6px 3px ${Ne(r,s)}`};case "outline-small":return {boxShadow:`0 0 0 1px ${Ne(r,s)}`};case "outline-large":return {boxShadow:`0 0 0 2px ${Ne(r,s)}`};case "outline-xlarge":return {boxShadow:`0 0 0 3px ${Ne(r,s)}`};default:return {}}})(),variant:t,uncertainty:r,scalarValueType:s})})]})});FE.displayName="StyledDateTimePicker";var ME=(e,t,r={})=>async(n,a,o)=>({values:n,errors:{}});function jE(e,t){let r=JSON.parse(JSON.stringify(t));return "description"in e&&(r.description=e.description),"X-ReasoningPrompt"in e?r["X-ReasoningPrompt"]=e["X-ReasoningPrompt"]:"X-ReasoningPrompt"in t&&(r["X-ReasoningPrompt"]=t["X-ReasoningPrompt"]),"X-EnumTranslation"in e?r["X-EnumTranslation"]=e["X-EnumTranslation"]:"X-EnumTranslation"in t&&(r["X-EnumTranslation"]=t["X-EnumTranslation"]),"X-FieldTranslation"in e?r["X-FieldTranslation"]=e["X-FieldTranslation"]:"X-FieldTranslation"in t&&(r["X-FieldTranslation"]=t["X-FieldTranslation"]),r}function Mi(e,t=null){if(typeof e!="object"||e===null)return e;if(t||(t=e.$defs?{...e.$defs}:{}),!t||typeof t!="object")throw new Error("Definitions must be an object");if("allOf"in e){if(e.allOf.length!==1)throw new Error(`Property schema must have a single element in 'allOf'. Found: ${e.allOf}`);let n=e.allOf[0];delete e.allOf,Object.assign(e,n);}if("$ref"in e){let n=e.$ref;if(n.startsWith("#/$defs/")){let a=n.replace("#/$defs/","");if(!(a in t))return e;let o=t[a],i=jE(e,o);return delete i.$ref,Mi(i,t)}else throw new Error(`Unsupported reference format: ${n}`)}let r={};for(let[n,a]of Object.entries(e))if(n==="properties"||n==="$defs")if(typeof a=="object"&&a!==null){let o={};for(let[i,s]of Object.entries(a))o[i]=Mi(s,t);r[n]=o;}else r[n]=a;else n==="items"?Array.isArray(a)?r[n]=a.map(o=>Mi(o,t)):r[n]=Mi(a,t):typeof a=="object"&&a!==null?Array.isArray(a)?r[n]=a.map(o=>typeof o=="object"&&o!==null?Mi(o,t):o):r[n]=Mi(a,t):r[n]=a;return r}var Ec=(e,t)=>{let r=e,n=i=>{if(i&&i.$ref){let s=String(i.$ref).replace("#/$defs/",""),l=t?.$defs?.[s];if(l){let u={...jE(i,l)};return delete u.$ref,u}}return i};r=n(r);let a=false;Array.isArray(r?.type)&&r.type.includes("null")&&(a=true,r={...r,type:r.type.find(i=>i!=="null")});let o=r?.anyOf||r?.oneOf||r?.allOf;if(o){o.some(s=>s?.type==="null")&&(a=true);let i=o.find(s=>s?.type&&s.type!=="null"||s?.properties||s?.items||s?.$ref||s?.enum);i&&(r=n(i),r=Mi(r,t?.$defs??{}));}return {schema:r,nullable:a}},Ne=(e,t)=>e===void 0||t==="none"?"transparent":t==="mismatch"?Op(e):Na(t==="similarity"?Po:Zl,e,t==="similarity"?To:Xl,.3),Xs=(e,t,r="border",n=false,a)=>t&&n?R6(a):r==="ring"?R(e&&"bg-green-50 ring-green-500 ring-2 data-[state=checked]:!bg-green-200 data-[state=checked]:!border-green-600 data-[state=checked]:!text-green-700",t&&"bg-blue-50 ring-blue-500 ring-2 data-[state=checked]:!bg-blue-200 data-[state=checked]:!border-blue-600 data-[state=checked]:!text-blue-700"):R(e&&"bg-green-50 border border-green-500 data-[state=checked]:!bg-green-200 data-[state=checked]:!border-green-600 data-[state=checked]:!text-green-700",t&&"bg-blue-50 border border-blue-500 data-[state=checked]:!bg-blue-200 data-[state=checked]:!border-blue-600 data-[state=checked]:!text-blue-700"),k6=e=>e===true?"border-green-500 border bg-green-50 data-[state=checked]:!bg-green-200 data-[state=checked]:!border-green-600 data-[state=checked]:!text-green-700":e===false?"border-red-500 border bg-red-50 data-[state=checked]:!bg-red-200 data-[state=checked]:!border-red-600 data-[state=checked]:!text-red-700":e==null?"border-yellow-500 border bg-yellow-50 data-[state=checked]:!bg-yellow-200 data-[state=checked]:!border-yellow-600 data-[state=checked]:!text-yellow-700":"border-green-500 border bg-green-50 data-[state=checked]:!bg-green-200 data-[state=checked]:!border-green-600 data-[state=checked]:!text-green-700",R6=e=>e===true?"border-green-500 border bg-green-50 data-[state=checked]:!bg-green-200 data-[state=checked]:!border-green-600 data-[state=checked]:!text-green-700":e===false?"border-red-500 border bg-red-50 data-[state=checked]:!bg-red-200 data-[state=checked]:!border-red-600 data-[state=checked]:!text-red-700":e==null?"border-yellow-500 border bg-yellow-50 data-[state=checked]:!bg-yellow-200 data-[state=checked]:!border-yellow-600 data-[state=checked]:!text-yellow-700":"border-green-500 border bg-green-50 data-[state=checked]:!bg-green-200 data-[state=checked]:!border-green-600 data-[state=checked]:!text-green-700",gm=Rt__default.forwardRef(({className:e,variant:t,size:r,type:n,uncertainty:a,multiline:o,scalarValueType:i,...s},l)=>{let{setIsEditing:c}=Tn(),u=s.onKeyDown,d=p=>{p.key==="Enter"||p.key==="Escape"?p.currentTarget.blur():u?.(p);};s.onKeyDown=d;let g=s.onClick,f=p=>{c(true),g?.(p);},h=s.onBlur,m=p=>{c(false),h?.(p);};return s.onClick=f,s.onBlur=m,jsx("div",{className:(()=>{switch(t){case "underline-close":return "border-b-2 pb-0";case "underline-distant":return "border-b-2 pb-2";case "left-border-close":return "border-l-4 pl-0";case "left-border-distant":return "border-l-4 pl-2";default:return ""}})(),style:(()=>{switch(t){case "underline-close":case "underline-distant":case "left-border-close":case "left-border-distant":return {borderColor:Ne(a,i)};default:return {}}})(),children:o?jsx(pr,{rows:3,className:R(e,"text-opacity-90"),ref:l,...s,style:(()=>{switch(t){case "blur-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 2px 1px ${Ne(a,i)}`};case "blur-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 4px 2px ${Ne(a,i)}`};case "blur-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 6px 3px ${Ne(a,i)}`};case "outline-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 1px ${Ne(a,i)}`};case "outline-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 2px ${Ne(a,i)}`};case "outline-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 3px ${Ne(a,i)}`};default:return {}}})()}):jsx(Ze,{type:n,className:R(e,"text-opacity-90"),ref:l,...s,style:(()=>{switch(t){case "blur-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 2px 1px ${Ne(a,i)}`};case "blur-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 4px 2px ${Ne(a,i)}`};case "blur-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 6px 3px ${Ne(a,i)}`};case "outline-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 1px ${Ne(a,i)}`};case "outline-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 2px ${Ne(a,i)}`};case "outline-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 3px ${Ne(a,i)}`};default:return {}}})()})})});gm.displayName="StyledInput";var LE=Rt__default.forwardRef(({className:e,variant:t,uncertainty:r,scalarValueType:n,value:a,onChange:o,...i},s)=>{let{setIsEditing:l}=Tn(),c=Rt__default.useRef(null),u=i.onKeyDown,d=p=>{p.key==="Enter"||p.key==="Escape"?p.currentTarget.blur():u?.(p);};i.onKeyDown=d;let g=i.onClick,f=p=>{l(true),g?.(p);},h=i.onBlur,m=p=>{l(false),h?.(p);};return i.onClick=f,i.onBlur=m,jsx("div",{className:R((()=>{switch(t){case "underline-close":return "border-b-2 pb-0";case "underline-distant":return "border-b-2 pb-2";case "left-border-close":return "border-l-4 pl-0";case "left-border-distant":return "border-l-4 pl-2";default:return ""}})(),"flex flex-1 min-h-0"),style:(()=>{switch(t){case "underline-close":case "underline-distant":case "left-border-close":case "left-border-distant":return {borderColor:Ne(r,n)};default:return {}}})(),children:jsx(pr,{ref:c,rows:1,className:R(e,"text-opacity-90","whitespace-pre-wrap resize-none max-h-64 h-auto min-h-8","scrollbar-thin scrollbar-thumb-gray-400 scrollbar-track-gray-100"),value:a,onChange:o,...i,style:{...(()=>{switch(t){case "blur-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 2px 1px ${Ne(r,n)}`};case "blur-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 4px 2px ${Ne(r,n)}`};case "blur-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 6px 3px ${Ne(r,n)}`};case "outline-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 1px ${Ne(r,n)}`};case "outline-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 2px ${Ne(r,n)}`};case "outline-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 3px ${Ne(r,n)}`};default:return {}}})(),overflowY:"auto"}})})});LE.displayName="StyledTextAreaInput";var BE=Rt__default.forwardRef(({className:e,variant:t,uncertainty:r,size:n,scalarValueType:a,...o},i)=>{let s=n==="sm"?24:30,l={flexShrink:0,padding:0,margin:0,height:t==="underline-close"?`${s+2}px`:t==="underline-distant"?`${s+10}px`:`${s}px`,width:t==="left-border-close"?`${s+4}px`:t==="left-border-distant"?`${s+12}px`:`${s}px`,minWidth:t==="left-border-close"?`${s+4}px`:t==="left-border-distant"?`${s+12}px`:`${s}px`,minHeight:t==="underline-close"?`${s+2}px`:t==="underline-distant"?`${s+10}px`:`${s}px`};t==="underline-close"||t==="underline-distant"?(l.borderBottom="2px solid",l.borderColor=Ne(r,a),l.paddingBottom=t==="underline-close"?0:"0.5rem"):(t==="left-border-close"||t==="left-border-distant")&&(l.borderLeft="4px solid",l.borderColor=Ne(r,a),l.paddingLeft=t==="left-border-close"?0:"0.5rem");let c={};return t==="blur-small"?c.boxShadow=`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 2px 1px ${Ne(r,a)}`:t==="blur-large"?c.boxShadow=`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 4px 2px ${Ne(r,a)}`:t==="blur-xlarge"?c.boxShadow=`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 6px 3px ${Ne(r,a)}`:t==="outline-small"?c.boxShadow=`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 1px ${Ne(r,a)}`:t==="outline-large"?c.boxShadow=`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 2px ${Ne(r,a)}`:t==="outline-xlarge"&&(c.boxShadow=`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 3px ${Ne(r,a)}`),jsx("div",{className:"shrink-0 p-0 m-0",style:l,children:jsx(No,{ref:i,className:R(e,"w-full h-full shrink-0",n==="sm"?"min-w-[24px] min-h-[24px]":"min-w-[30px] min-h-[30px]"),...o,style:c})})});BE.displayName="StyledCheckbox";var Cv=Rt__default.forwardRef(({className:e,variant:t,uncertainty:r,value:n,onValueChange:a,disabled:o,placeholder:i,size:s,children:l,scalarValueType:c},u)=>{let{setIsEditing:d}=Tn(),g=f=>{d(true),a?.(f),setTimeout(()=>d(false),0);};return jsx("div",{className:(()=>{switch(t){case "underline-close":return "border-b-2 pb-0";case "underline-distant":return "border-b-2 pb-2";case "left-border-close":return "border-l-4 pl-0";case "left-border-distant":return "border-l-4 pl-2";default:return ""}})(),style:(()=>{switch(t){case "underline-close":case "underline-distant":case "left-border-close":case "left-border-distant":return {borderColor:Ne(r,c)};default:return {}}})(),children:jsxs(Cs,{value:n,onValueChange:g,disabled:o,children:[jsx(Ps,{ref:u,className:R(e,s==="sm"?"!h-[32px] text-sm":"!h-[42px] text-sm","text-opacity-90"),style:(()=>{switch(t){case "blur-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 2px 1px ${Ne(r,c)}`};case "blur-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 4px 2px ${Ne(r,c)}`};case "blur-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 6px 3px ${Ne(r,c)}`};case "outline-small":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 1px ${Ne(r,c)}`};case "outline-large":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 2px ${Ne(r,c)}`};case "outline-xlarge":return {boxShadow:`var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow), 0 0 0 3px ${Ne(r,c)}`};default:return {}}})(),children:jsx(Es,{placeholder:i})}),jsx(Ts,{className:R(e),children:l})]})})});Cv.displayName="StyledSelect";function bm(e,t,r=e){return O6(e,t,r)}function O6(e,t,r=e){if(!r||typeof r!="object")return null;let n=t.split(".").filter(a=>a.length>0);for(let a=0;a<n.length;){let o=n[a];if(r&&typeof r=="object"&&r.$ref){let i=e?.$defs??{},s=String(r.$ref).replace("#/$defs/","");r=i[s]??r;}if(r&&typeof r=="object"&&Array.isArray(r.anyOf)){for(let i of r.anyOf){let s=bm(e,n.slice(a).join("."),i);if(s)return s}return null}if(r&&r.type==="array")r=r.items??{},a+1<n.length&&(n[a+1]==="*"||!isNaN(parseInt(n[a+1])))&&(a+=1);else if(r&&(r.type==="object"||r.properties)){let i=r.properties;if(i&&typeof i=="object"&&o in i)r=i[o]??{},a+=1;else if(o==="*"||!isNaN(parseInt(o)))a+=1;else return null}else if(o==="*"||!isNaN(parseInt(o)))a+=1;else return null}if(r&&typeof r=="object"&&r.$ref){let a=e?.$defs??{},o=String(r.$ref).replace("#/$defs/","");r=a[o]??r;}return r??null}var ym=e=>{if(!e)return {};if(e.type==="string")return "";if(e.type==="number"||e.type==="integer")return 0;if(e.type==="boolean")return false;let t={};return e.properties&&Object.keys(e.properties).forEach(r=>{let n=e.properties[r],a=n.type,o;!a&&(n.anyOf||n.oneOf||n.allOf)&&(a=(n.anyOf||n.oneOf||n.allOf).find(l=>l.type!=="null")?.type||"object"),n.default!==void 0?o=n.default:a==="string"?o="":a==="number"||a==="integer"?o=null:a==="boolean"?o=false:a==="object"?o=ym(n):a==="array"?o=n.items?[ym(n.items)]:[]:o=null,t[r]=o;}),t};function xm(e,t){if(!e||typeof t!="string")return false;let r=t.split("."),n=e;for(let a of r){if(n==null)return false;let o=a.match(/^(\d+)$/);if(o){let i=parseInt(o[1],10);if(!Array.isArray(n)||!(i in n))return false;n=n[i];}else {if(typeof n!="object"||!(a in n))return false;n=n[a];}}return true}var Ot=(e,t)=>t.split(".").reduce((r,n)=>{if(r&&typeof r=="object"&&n in r)return r[n]},e),wm=(e,t)=>{if(!e||e.length<=1)return null;let r=xv(e[0].data,t),n=e.slice(1).map((s,l)=>{let c=vm(t),u=xv(s.data,t),d=xv(s.data,c);return {value:u,index:l+2,reasoning:d}}).filter(s=>s.value!==void 0),a=s=>JSON.stringify(Array.isArray(s)?s:s??""),o=[...new Set(n.map(s=>a(s.value)))],i=n.length>0?n.filter(s=>a(s.value)===a(r)).length/n.length:1;return {consolidated_value:r,alternatives:n,count:n.length,agreement:i,hasVariation:o.length>1}};var D6=e=>e.split(".").map(t=>/^\d+$/.test(t)?"*":t).join("."),Qs=({show:e,content:t,id:r})=>!e||!t?null:jsx(fr,{children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("div",{className:"flex items-center",children:jsx(Atom,{className:"w-4 h-4 text-purple-300"})})}),jsxs(ze,{className:"max-w-xs",children:[jsx("div",{className:"text-xs text-purple-300 mb-1",children:"Reasoning:"}),typeof t=="string"?jsx("div",{className:"whitespace-pre-wrap break-words",children:t}):jsx("pre",{className:"text-xs rounded border whitespace-pre-wrap text-gray-700 font-medium leading-snug p-1 bg-gray-50 max-h-64 overflow-auto",children:JSON.stringify(t,null,2)})]})]})},r),Pc=({show:e,content:t,id:r})=>{if(!e||!t||!t.alternatives)return null;let n=t.alternatives.filter(a=>!!a.reasoning);return n.length===0?null:jsx(fr,{delayDuration:300,children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("div",{className:"flex items-center cursor-pointer",children:jsx(Atom,{className:"w-4 h-4 text-purple-300"})})}),jsxs(ze,{className:"max-w-xs break-words",children:[jsx("div",{className:"text-xs text-purple-300 mb-1 font-medium",children:"Model reasonings"}),jsx("div",{className:"space-y-2",children:n.map((a,o)=>jsxs("div",{className:"space-y-1",children:[jsxs("div",{children:["Model ",a.index-1]}),jsx("div",{className:"text-xs rounded border whitespace-pre-wrap text-gray-700 font-medium leading-snug p-1 bg-gray-50",children:a.reasoning})]},o))})]})]})},r)};var A6=({show:e,content:t,id:r,consolidated_value:n})=>!e||!t?null:jsx(fr,{children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("div",{className:"flex items-center",children:jsx(Blend,{className:"w-4 h-4 text-blue-300"})})}),jsxs(ze,{className:"max-w-xs",children:[jsx("div",{className:"text-xs text-blue-300 mb-1",children:"Consensus:"}),t&&t.alternatives?jsxs("div",{className:"space-y-2",children:[jsxs("div",{className:"text-xs",children:["Agreement: ",(t.agreement*100).toFixed(0),"% (",t.count," choices)",t.hasVariation&&jsx("span",{className:"text-yellow-400 ml-1",children:"\u2022 Variation detected"})]}),jsx("div",{className:"text-xs font-medium",children:"Consensus:"}),jsx("div",{className:"space-y-1 max-h-32 overflow-y-auto",children:jsx("div",{className:"flex items-center justify-between gap-2",children:jsx("div",{className:"text-xs p-1 rounded border bg-gray-50",children:jsx("div",{className:"font-medium truncate text-gray-700",children:typeof n=="object"?JSON.stringify(n):String(n||"null")})})},"zero")}),jsx("div",{className:"text-xs font-medium",children:"Alternatives:"}),jsx("div",{className:"space-y-1 max-h-32 overflow-y-auto",children:t.alternatives.map((a,o)=>jsxs("div",{className:"flex items-center gap-2",children:["Model ",a.index-1,":",jsx("div",{className:"text-xs p-1 rounded border bg-gray-50",children:jsx("div",{className:"font-medium truncate text-gray-700",children:typeof a.value=="object"?JSON.stringify(a.value):String(a.value||"null")})})]},o))})]}):jsx("div",{className:"",children:t?String(t):""})]})]})},r),$6=e=>{if(e==null)return "\u2014";if(typeof e=="boolean")return e?"Yes":"No";if(typeof e=="object")return Array.isArray(e)?e.length===0?"[]":`[${e.length} items]`:JSON.stringify(e);let t=String(e);return t.length>50?t.slice(0,47)+"...":t},I6=({schema:e,rootSchema:t,value:r,onChange:n,disabled:a})=>{let o=e,i=o?.type,s=o?.format,l=Array.isArray(o?.enum)&&(o?.enum).length>0,c=Array.isArray(o?.type)?o.type:null,u=!!(c&&c.includes("null"));if(i==="boolean")return jsx("div",{className:"h-full flex items-center",children:jsx(No,{checked:!!r,onCheckedChange:d=>n(!!d),className:"disabled:opacity-100",disabled:a})});if(l){let d=o.enum.filter(f=>f!==""),g=r==null?"__null__":String(r);return jsxs(Cs,{value:g,onValueChange:f=>{n(f==="__null__"&&u?null:f);},disabled:a,children:[jsx(Ps,{className:"h-8 px-2 text-xs w-full border",children:jsx(Es,{placeholder:u?"Select...":void 0})}),jsxs(Ts,{children:[u&&jsx(Wn,{value:"__null__",className:"text-xs text-muted-foreground",children:jsx("em",{children:"No selection"})},"__null__"),d.map(f=>jsx(Wn,{value:String(f),className:"text-xs",children:String(f)},String(f)))]})]})}if(i==="string"&&s==="date")return jsx(Ze,{type:"date",value:typeof r=="string"?r:"",onChange:g=>n(g.target.value||null),disabled:a,className:"w-full px-2 py-1 text-xs"});if(i==="string"&&s==="date-time")return jsx(Ze,{type:"datetime-local",value:typeof r=="string"?r:"",onChange:g=>n(g.target.value||null),disabled:a,className:"w-full px-2 py-1 text-xs"});if(i==="number"||i==="integer"){let d=i==="integer",g=r==null?"":String(r);return jsx(Ze,{type:"number",value:g,onChange:f=>{let h=d?parseInt(f.target.value):parseFloat(f.target.value);n(isNaN(h)?null:h);},disabled:a,className:"w-full px-2 py-1 text-xs"})}if(i==="object"||i==="array"){let d=(()=>{try{return typeof r=="string"?r:JSON.stringify(r??null,null,2)}catch{return String(r??"")}})();return jsx(pr,{className:"w-full h-32 p-2 text-xs border rounded-md resize-none bg-gray-50",value:d,onChange:g=>{let f=g.target.value;try{let h=JSON.parse(f);n(h);}catch{n(f);}},disabled:a})}return jsx(pr,{className:"w-full h-20 p-2 text-xs border rounded-md resize-none bg-gray-50",value:r??"",onChange:d=>n(d.target.value),disabled:a})},F6=(e,t)=>{let r=e.replace("#",""),n=parseInt(r.substring(0,2),16),a=parseInt(r.substring(2,4),16),o=parseInt(r.substring(4,6),16),i=Math.max(0,Math.min(1,t)),s=Math.round(n*i),l=Math.round(a*i),c=Math.round(o*i);return `#${s.toString(16).padStart(2,"0")}${l.toString(16).padStart(2,"0")}${c.toString(16).padStart(2,"0")}`.toUpperCase()},M6=(e,t="similarity")=>{if(e===void 0||isNaN(e))return {bg:"#f1f5f9",text:"#334155",border:"#e2e8f0"};if(t==="mismatch")return e===1?{bg:"#f1f5f9",text:"#334155",border:"#e2e8f0"}:{bg:"#FEF3C7",text:"#92400E",border:"#F59E0B"};let r=Na(Po,e,To,.15),n=Na(Po,e,To,1),a=F6(n,.5),o=Na(Po,e,To,.4);return {bg:r,text:a,border:o}},j6=({groundTruthData:e,predictionData:t,onGroundTruthChange:r,onToggleMismatch:n,fieldPath:a,fieldSchema:o,rootSchema:i,similarity:s,isInMismatches:l=false,id:c,scalarValueType:u="similarity"})=>{let[d,g]=useState(false),[f,h]=useState(null),[m,p]=useState(false);if(!e)return null;let v=Ot(e,a);if(v===void 0)return null;let y=t?Ot(t,a):void 0,x=$6(v),w=!!r,_=!!n,E=M6(s,u),C=k=>{g(k),k&&h(v);},P=()=>{if(console.log("[GroundTruthBadge:handleSave] Called for fieldPath:",a),console.log("[GroundTruthBadge:handleSave] editValue:",f),console.log("[GroundTruthBadge:handleSave] onGroundTruthChange exists:",!!r),!r){console.log("[GroundTruthBadge:handleSave] No onGroundTruthChange callback, returning");return}let k=f;console.log("[GroundTruthBadge:handleSave] Captured valueToSave:",k),g(false),console.log("[GroundTruthBadge:handleSave] Popover closed, invoking callback..."),r(a,k),console.log("[GroundTruthBadge:handleSave] Callback invoked");},T=()=>{n&&(n(a),g(false));},N=()=>{y!==void 0&&h(y);},S=()=>{h(v),g(false);};if(!w)return jsx(fr,{children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] font-medium rounded max-w-[150px] truncate cursor-context-menu",style:{backgroundColor:E.bg,color:E.text,borderWidth:"1px",borderStyle:"solid",borderColor:E.border},children:jsx("span",{className:"truncate",children:x})})}),jsxs(ze,{side:"top",className:"max-w-xs",children:[jsx("div",{className:"text-xs text-slate-500 mb-1",children:"Ground Truth:"}),typeof v=="object"?jsx("pre",{className:"text-xs rounded border whitespace-pre-wrap text-gray-700 font-medium leading-snug p-1 bg-gray-50 max-h-64 overflow-auto",children:JSON.stringify(v,null,2)}):jsx("div",{className:"whitespace-pre-wrap break-words font-medium",children:String(v)})]})]})},c);y!==void 0&&JSON.stringify(y)!==JSON.stringify(v);return jsxs("div",{className:"inline-flex items-center gap-1",children:[jsxs(Ht,{open:d,onOpenChange:C,children:[jsx(Jt,{asChild:true,children:jsxs("button",{type:"button",className:"inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] font-medium rounded max-w-[150px] truncate cursor-pointer transition-opacity hover:opacity-80",style:{backgroundColor:E.bg,color:E.text,borderWidth:"1px",borderStyle:"solid",borderColor:E.border},onClick:k=>k.stopPropagation(),children:[jsx("span",{className:"truncate",children:x}),jsx(Pencil,{className:"h-2.5 w-2.5 shrink-0 opacity-60"})]})}),jsx(Wt,{className:"w-72 p-3",align:"start",onClick:k=>k.stopPropagation(),onPointerDown:k=>k.stopPropagation(),children:jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("div",{className:"text-2xs font-medium text-slate-700",children:"Ground Truth"}),jsx(K,{variant:"outline",size:"sm",onClick:N,disabled:m,className:"h-7 text-2xs",children:"Replace by prediction"})]}),jsx(I6,{schema:o,rootSchema:i,value:f,onChange:h,disabled:m}),jsxs("div",{className:"flex items-center justify-end gap-2",children:[jsx(K,{variant:"outline",size:"sm",onClick:S,disabled:m,className:"h-7 text-xs",children:"Cancel"}),jsx(K,{size:"sm",onClick:P,disabled:m,className:"h-7 text-xs",children:m?"Saving...":"Save"})]})]})})]}),_&&u==="mismatch"&&jsxs("div",{className:"inline-flex items-center gap-1",onClick:k=>k.stopPropagation(),children:[jsx(md,{checked:!l,onCheckedChange:()=>T(),className:R("h-3.5 w-6 data-[state=checked]:bg-emerald-400 data-[state=unchecked]:bg-orange-400","[&_span]:h-2.5 [&_span]:w-2.5 [&_span]:data-[state=checked]:translate-x-[10px] [&_span]:data-[state=unchecked]:translate-x-[2px]"),title:l?"Mark as OK":"Mark as mismatch"}),jsx("span",{className:R("text-[10px] font-medium",l?"text-orange-600":"text-emerald-600"),children:l?"Mismatch":"\u2713 OK"})]})]})},wv=Rt__default.memo(({item:e,innerIdx:t,arrayBaseName:r,enumOptions:n,itemsSchema:a,labelItem:o,elementKey:i,currentPath:s,className:l,disabled:c,isStreaming:u,size:d,handleRemoveItem:g,setLikelihoods:f,setSourcesFieldPath:h})=>{let{consensusDetails:m,form:p,config:v,scalarValueType:y,disabled:x}=Tn(),w=`${r}.${t}.reasoning___item`,_=xm(p.getValues(),w)?Ot(p.getValues(),w):null,E=`${r}.${t}`,C=Rt__default.useMemo(()=>wm(m,E),[m,E]),P=`${i}-item-${t}`;return n?jsxs("div",{className:R("flex flex-row items-center gap-2 mt-2",l,"bg-transparent shadow-none outline-transparent outline-none text-xs"),children:[jsx(Sa,{control:p.control,name:`${s}.${t}`,render:({field:N})=>jsx(Hn,{className:"flex-1",children:jsx(Jn,{children:jsx(Cv,{size:d,disabled:c,value:hm(N.value),onValueChange:S=>{N.onChange(IE(S)),f(b=>{let k={...b};return Tc(k,`${s}.${t}`,1),k});},className:l,scalarValueType:y,children:n.map(S=>{let b=hm(S),k=b===_d?"(Empty)":b.charAt(0).toUpperCase()+b.slice(1);return jsx(Wn,{value:b,className:R(l,"rounded-none border-none outline-transparent"),children:k},b)})})})})}),jsx(Qs,{show:v?.showReasoning??false,content:_,id:`${i}-reasoning-enum-${t}`}),jsx(Pc,{show:v?.showReasoning??false,content:C,id:`${i}-consensus-reasoning-enum-${t}`}),!x&&jsx(K,{size:d==="sm"?"sm":"icon",type:"button",variant:"outline",onClick:()=>g(t),className:R(l,"py-1 px-2 shrink-0"),disabled:c||u,"aria-label":"Delete",children:jsx(Trash,{className:"h-3 w-3"})})]},P):(a.type??"")!=="object"&&!a.$ref&&!a.anyOf?.some(N=>N.type==="object"||N.$ref)?jsxs("div",{className:"flex items-end flex-row gap-1 w-full",children:[jsx("div",{className:"flex-1 min-w-0",children:jsx(zE,{path:s+"."+t,className:l})}),jsx(Qs,{show:v?.showReasoning??false,content:_,id:`${i}-reasoning-prim-${t}`}),jsx(Pc,{show:v?.showReasoning??false,content:C,id:`${i}-consensus-reasoning-prim-${t}`}),!x&&jsx(K,{size:d==="sm"?"sm":"icon",type:"button",variant:"outline",onClick:()=>g(t),className:R(l,"py-1 px-2 shrink-0",d==="sm"?"mr-1":"mr-2"),disabled:c||u,"aria-label":"Delete",children:jsx(Trash,{className:"h-3 w-3"})})]},P):jsxs(nd,{value:`${i}-idx-${t}-0`,className:R(l,"border-b last:border-b-0 shadow-none border-x-0 border-t-0 rounded-none"),children:[jsxs("div",{className:R(l,"flex flex-row items-center shadow-none rounded-none border-none",d==="sm"?"h-[40px]":"h-[54px]"),children:[jsx("div",{className:"flex-1",children:jsx(ad,{className:"pl-2 pr-2",children:jsxs("div",{className:"flex items-center flex-row gap-2 text-xs",children:[o+` #${t+1}`,jsx(Qs,{show:v?.showReasoning??false,content:_,id:`${i}-reasoning-tooltip-${t}`}),jsx(Pc,{show:v?.showReasoning??false,content:C,id:`${i}-consensus-reasoning-tooltip-${t}`})]})})}),!x&&jsx(K,{size:d==="sm"?"iconSm":"icon",type:"button",variant:"ghost",onClick:()=>g(t),className:R(l,d==="sm"?"mr-1":"mr-2"),disabled:c||u,"aria-label":"Delete",children:jsx(Trash,{className:"h-3 w-3"})})]}),jsx(od,{className:R(l,"border-x-0 rounded-none pb-0 pt-0 px-3 border-b-0 border-t"),children:jsx(Ev,{path:s+"."+t,className:l,isArrayItem:true,isLoneObject:true})})]},`${i}-idx-${t}`)});wv.displayName="ArrayRendererItem";var L6=({path:e,className:t})=>{let{schema:r,setSchema:n,form:a,isStreaming:o,disabled:i,size:s,setLikelihoods:l,setSourcesFieldPath:c,consensusDetails:u,config:d,propertyEditorMode:g,showPropertyEditorPencil:f,computationSpec:h,setComputationSpec:m}=Tn(),{projectId:p}=Tn(),v=bm(r,e),{schema:y}=Ec(v,r),x=Rt__default.useMemo(()=>wm(u,e),[u,e]);if(!v)return null;let w=e,_=null,E=null;if((y?.type==="array"||Array.isArray(y?.type)&&y.type.includes("array"))&&y?.items)_=Ec(y.items,r).schema;else if(y?.anyOf||y?.oneOf||y?.allOf){let $=(y.anyOf||y.oneOf||y.allOf).find(A=>A?.type==="array"||A?.items);$&&(_=Ec($.items??$,r).schema);}_?.enum&&(E=_.enum);let C=vm(e),P=xm(a.getValues(),C)?Ot(a.getValues(),C):null,T=e.split(".").pop(),N=_?.title||"Item",S=!!v?.["X-ComputedField"],b=Ot(a.getValues(),w);Array.isArray(b)||(b=[],a.setValue(w,b));let k=()=>{if(E){let Q=E.find(j=>j!=="")??"",z=Ot(a.getValues(),w)||[],ae=[...z,Q];a.setValue(w,ae,{shouldValidate:true,shouldDirty:true,shouldTouch:true});let M=`${w}.${z.length}`;l(j=>{let ue={...j};return Tc(ue,M,1),ue});return}if(!_){console.error("Could not find items schema for",e);return}let O=ym(_),$=Ot(a.getValues(),w)||[],A=$.length,F=[...$,O];a.setValue(w,F,{shouldValidate:true,shouldDirty:true,shouldTouch:true});let X=(L,Q)=>{Object.keys(L).forEach(z=>{let ae=Q?`${Q}.${z}`:z;L[z]!==null&&typeof L[z]=="object"?X(L[z],ae):l(M=>{let j={...M};return Tc(j,ae,1),j});});},H=`${w}.${A}`;X(O,H);},D=O=>{let A=[...Ot(a.getValues(),w)||[]];A.splice(O,1),a.setValue(w,A,{shouldValidate:true,shouldDirty:true,shouldTouch:true});};return jsxs("div",{className:R("flex flex-col"),children:[jsxs("div",{className:"flex flex-row gap-2 group pt-4",children:[jsx(vi,{className:R(t,"items-center border-none outline-transparent shadow-none bg-transparent justify-center flex hover:bg-transparent mb-0"),children:T}),jsx(Qs,{show:d?.showReasoning??false,content:P,id:`${e}-reasoning-root`}),!!d?.showReasoning&&!!d?.showConsensus&&!!x&&jsx(Pc,{show:!!d?.showReasoning,content:x,id:`${e}-consensus-reasoning-root`}),n&&f!==false&&jsxs(En,{modal:true,children:[jsx(pd,{asChild:true,children:jsx("button",{className:"cursor-pointer relative ml-auto opacity-0 group-hover:opacity-100 transition-opacity duration-300",type:"button","aria-label":"Edit field",children:jsx(SquarePen,{className:"absolute top-0 right-0 size-[14px]"})})}),jsxs(Pa,{className:"p-0 gap-0 max-h-[80vh] overflow-y-auto",onOpenAutoFocus:O=>{O.preventDefault();},onPointerDownOutside:O=>{O.preventDefault();},onInteractOutside:O=>{O.preventDefault();},onEscapeKeyDown:O=>{O.preventDefault();},children:[jsx(Pn,{className:"text-lg font-semibold px-4 pt-3 pb-0",children:"Edit field"}),S?jsx("div",{className:"p-0",children:p&&h&&m&&jsx(Nc,{fieldPath:e,jsonSchema:r,computationSpec:h,setComputationSpec:m,readOnly:g==="readOnly"})}):jsx(xc,{property:v,propertyKey:e,setDropdownOpen:()=>{},jsonSchema:r,setJsonSchema:n,editMode:g??"editable"})]})]})]},`${e}-header`),Array.isArray(b)&&_&&(_.type==="object"||_.$ref||_.anyOf?.some(O=>O.type==="object"||O.$ref))?jsx(rd,{type:"single",collapsible:true,defaultValue:Array.isArray(b)&&b.length>0?`${e}-idx-0-0`:void 0,className:R("outline-transparent rounded-md",t,"mt-2 bg-transparent outline overflow-hidden"),children:b.map((O,$)=>jsx(wv,{item:O,innerIdx:$,arrayBaseName:e,enumOptions:null,itemsSchema:_,labelItem:N,elementKey:e,currentPath:w,className:t,disabled:i??false,isStreaming:o??false,size:s,handleRemoveItem:D,setLikelihoods:l,setSourcesFieldPath:c},`${e}-item-${$}`))}):Array.isArray(b)?b.map((O,$)=>jsx(wv,{item:O,innerIdx:$,arrayBaseName:e,enumOptions:E,itemsSchema:_,labelItem:N,elementKey:e,currentPath:w,className:t,disabled:i??false,isStreaming:o??false,size:s,handleRemoveItem:D,setLikelihoods:l,setSourcesFieldPath:c},`${e}-item-${$}`)):null,jsx("div",{className:"flex mt-2",children:jsx("div",{children:jsxs(K,{size:s,className:R(t,"px-2"),type:"button",variant:"outline",onClick:k,disabled:i||o,children:[jsx(Plus,{className:"size-5 mr-2"}),jsx("span",{className:"",children:T})]})})},`${e}-add-button`)]},e)},zE=({path:e,className:t})=>{let{form:r,formFieldIdPrefix:n,size:a,likelihoods:o,scalarValueDisplay:i,scalarValueType:s,isProcessing:l,isStreaming:c,disabled:u,titlePosition:d,setLikelihoods:g,setSourcesFieldPath:f,config:h,consensusDetails:m,isEditing:p,setIsEditing:v,propertyEditorMode:y,showPropertyEditorPencil:x,schema:w,setSchema:_,validationFlags:E,setValidationFlags:C,showVerifiedProperty:P,projectId:T,computationSpec:N,setComputationSpec:S}=Tn(),b=r.getValues(),k=h?.descriptions??false,[D,O]=Rt__default.useState(void 0),$=bm(w,e),A=r.getValues(e);Rt__default.useEffect(()=>{O(A!=null?String(A):"");},[e,A]);let F=vm(e),X=xm(b,F)?Ot(b,F):null,H=Rt__default.useMemo(()=>wm(m,e),[m,e]),{schema:L,nullable:Q}=Ec($,w),z=!Q,ae=!!(L?.["X-ComputedField"]||$?.["X-ComputedField"]),M=!!(L?.["X-FunctionField"]||$?.["X-FunctionField"]),j,ue;L.enum?(j="enum",ue=L.enum):j=L.format==="date"?"date":L.format==="iso-time"?"time":L.format==="date-time"?"datetime":L.type==="number"?"number":L.type==="integer"?"integer":L.type==="boolean"?"boolean":"text";let ie=j==="boolean"?"checkbox":j==="date"?"date":j==="time"?"time":j==="datetime"?"datetime-local":j==="number"||j==="integer"?"number":"text",Ce=ge=>{g(Z=>{let W={...Z};return Tc(W,ge,1),W});},Te=Rt__default.useCallback((ge,Z)=>{let W=Z;if(typeof Z=="string")if(j==="number"){let V=parseFloat(Z);W=isNaN(V)?null:V;}else if(j==="integer"){let V=parseInt(Z);W=isNaN(V)?null:V;}else ie==="time"&&/^\d{1,2}:\d{2}$/.test(Z)||ie==="datetime-local"&&/^\d{4}-\d{2}-\d{2}T\d{1,2}:\d{2}$/.test(Z)?W=Z+":00":Z===""&&(W=null);let ee=W;if(L&&L.format&&typeof W=="string")try{let V={type:"object",properties:{[e.split(".").pop()]:L}};ee=pn({[e.split(".").pop()]:W},V)[e.split(".").pop()];}catch(V){console.warn(`autoFormatDateTimeFields validation failed for ${e}:`,V);}ge.onChange(ee),Ce(e);},[e,L,j,ie,Ce]);if(!$)return jsxs("i",{children:["Bad schema path: ",e]});let Je=L?.title||e.split(".").pop()||"",vt=(()=>{if(!(L.type==="string"||L.anyOf?.some(W=>W.type==="string")||L.oneOf?.some(W=>W.type==="string")||L.allOf?.some(W=>W.type==="string")))return false;let Z=[];return L.maxLength!==void 0&&Z.push(L.maxLength),L.anyOf&&L.anyOf.forEach(W=>{W.type==="string"&&W.maxLength!==void 0&&Z.push(W.maxLength);}),L.oneOf&&L.oneOf.forEach(W=>{W.type==="string"&&W.maxLength!==void 0&&Z.push(W.maxLength);}),L.allOf&&L.allOf.forEach(W=>{W.type==="string"&&W.maxLength!==void 0&&Z.push(W.maxLength);}),Z.length>0?Math.min(...Z)>500:false})(),gt=()=>{let ge=f&&!p?()=>{f(e);}:void 0,Z=ge?W=>{let ee=W.target;!ee.closest("[data-radix-popper-content-wrapper]")&&!ee.closest('[role="button"]')&&ge();}:void 0;return jsxs("div",{className:"flex flex-row flex-wrap gap-1 break-all min-w-0 w-full",onClick:W=>W.stopPropagation(),children:[jsxs(vi,{className:R("flex items-center gap-1 cursor-pointer","text-xs",ae&&"text-blue-900 opacity-90"),onMouseEnter:Z,children:[Je,z&&!ae&&jsx("span",{className:"text-red-500",children:"*"})]}),jsx(j6,{groundTruthData:h?.groundTruthData,predictionData:h?.predictionData,onGroundTruthChange:h?.onGroundTruthChange,onToggleMismatch:h?.onToggleMismatch,fieldPath:e,fieldSchema:L,rootSchema:w,similarity:Ot(o,e),isInMismatches:h?.mismatches?.includes(e)??false,id:`${e}-ground-truth`,scalarValueType:s}),L.description&&k&&jsx("div",{className:"relative inline-block",children:jsx(fr,{children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(Info,{className:R(t,"h-[14px] w-[14px] cursor-pointer bg-transparent shadow-none outline-none border-none outline-transparent")})}),jsxs(ze,{side:"top",className:"w-[200px] p-0 max-w-[80vw]",children:[jsx(TooltipArrow,{}),jsx("div",{className:R("border border-black",t,"text-xs p-3 max-h-[60vh] overflow-y-auto break-words whitespace-normal flex shadow-none outline-none rounded-md focus-ring-0 outline-transparent"),children:L.description})]})]})})}),false,h?.showPrompts&&L["X-ReasoningPrompt"]&&jsx(fr,{children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsxs("div",{className:"flex items-center rounded-full px-1 border border-black text-xs font-light",children:[jsx(Atom,{className:R(t,"h-[14px] w-[14px] text-muted-foreground cursor-pointer bg-transparent shadow-none outline-none border-none outline-transparent")}),"Reasoning"]})}),jsxs(ze,{side:"right",className:"w-[200px] p-0",sideOffset:2,children:[jsx(TooltipArrow,{}),jsx("div",{className:R("border border-black",t,"text-xs p-3 shadow-none outline-none rounded-md focus-ring-0 outline-transparent"),children:L["X-ReasoningPrompt"]})]})]})}),f&&!p&&h?.showSources&&jsx(Search,{className:R(t,"h-[14px] w-[14px] text-muted-foreground cursor-pointer bg-transparent shadow-none outline-none border-none outline-transparent"),onMouseEnter:Z}),jsx(Qs,{show:h?.showReasoning??false,content:X,id:`${e}-reasoning`}),jsx(A6,{show:h?.showConsensus??false,consolidated_value:A,content:H,id:`${e}-consensus`}),h?.showReasoning&&h?.showConsensus&&H&&jsx(Pc,{show:h?.showReasoning,content:H,id:`${e}-consensus-reasoning`}),_&&x!==false&&jsxs(En,{modal:true,children:[jsx(pd,{asChild:true,children:jsx("button",{className:"cursor-pointer relative ml-auto opacity-0 group-hover:opacity-100 transition-opacity duration-300",type:"button",children:jsx(SquarePen,{className:"absolute top-0 right-0 size-[14px]"})})}),jsxs(Pa,{className:"p-0 gap-0 max-h-[80vh] overflow-y-auto",onOpenAutoFocus:W=>{W.preventDefault();},onPointerDownOutside:W=>{W.preventDefault();},onInteractOutside:W=>{W.preventDefault();},onEscapeKeyDown:W=>{ae&&W.preventDefault();},children:[jsx(Pn,{className:"text-lg font-semibold px-4 pt-3 pb-0",children:"Edit field"}),ae?jsx("div",{className:"p-0",children:T&&N&&S&&jsx(Nc,{fieldPath:D6(e),jsonSchema:w,computationSpec:N,setComputationSpec:S,readOnly:y==="readOnly"})}):jsx(xc,{property:$,propertyKey:e,setDropdownOpen:()=>{},jsonSchema:w,setJsonSchema:_,editMode:y??"editable"})]})]}),ae&&jsx("div",{className:"flex items-center ml-auto",onClick:W=>W.stopPropagation(),children:jsx("span",{className:"text-xs font-normal text-blue-900 opacity-70",children:"computed value"})}),P===true&&!ae&&jsxs("div",{className:"flex items-center gap-2 ml-auto",onClick:W=>W.stopPropagation(),children:[jsx("span",{className:"text-xs font-normal text-muted-foreground",children:"verified"}),jsx(md,{checked:!!Ot(E,e),onCheckedChange:W=>{let ee={...E};Tc(ee,e,W),C(ee);}})]})]})},We=u||l||ae||M||c&&(A==="Undefined"||A===void 0),ke=()=>{v(true),f&&f(e);},be=ge=>{if(f){let Z=ge.target;!Z.closest("[data-radix-popper-content-wrapper]")&&!Z.closest('[role="button"]')&&f(e);}},re=n??"form-field",me=!!Ot(E,e),ye=M&&!me?k6(A):"";return jsx("div",{id:`${re}-${e.split(".").join("-")}`,className:R("space-y-2 group"),children:jsx(Sa,{control:r.control,name:e,render:({field:ge})=>ie==="checkbox"?jsxs(Hn,{className:"flex items-center space-y-0 my-2",children:[jsx(Jn,{children:jsx(BE,{size:a,uncertainty:Ot(o,e),variant:i,scalarValueType:s,className:R(t,Xs(me,ae,"ring",j==="boolean",D?.toLowerCase()==="true"),ye),onCheckedChange:Z=>{O(Z?"true":"false"),Te(ge,Z);},checked:D?.toLowerCase()==="true",disabled:We})}),d!="none"&&jsx("div",{className:R(t,"border-none outline- shadow-none bg-transparent text-left ml-2 text-xs flex flex-1 min-h-0"),children:jsx(gt,{})})]}):jsxs(Hn,{className:"flex flex-1 min-h-0 flex-col",children:[c&&isUndefined(Ot(b,e))?d!="none"&&jsx(vi,{className:R(t,"border-none outline-transparent shadow-none bg-transparent text-left flex mt-4 hover:bg-transparent"),children:jsx(Ue,{className:"h-4 w-[30%] bg-gray-200 animate-pulse rounded-md border-none outline-none outline-transparent"})}):d!="none"&&jsx("div",{className:R(t,"border-none outline-transparent shadow-none bg-transparent text-left flex mt-4 hover:bg-transparent"),children:jsx(gt,{})}),jsx(Jn,{className:"flex flex-1 min-h-0",onMouseEnter:be,onMouseOver:be,onClick:ke,children:l&&!c?jsx(Ue,{className:R(a==="sm"?"h-[32px]":"h-[42px]","flex animate-pulse rounded-md border-none outline-none bg-gray-200")}):j==="enum"&&ue?c&&isUndefined(Ot(b,e))?jsx(Ue,{className:R(a==="sm"?"h-[32px]":"h-[42px]","flex animate-pulse rounded-md border-none outline-none bg-gray-200")}):jsxs(Cv,{size:a,disabled:We,value:hm(D??ge.value),onValueChange:Z=>{let W=IE(Z);O(W),Te(ge,W);},className:R(t,Xs(me,ae,"border",false),ye),uncertainty:Ot(o,e),variant:i,scalarValueType:s,children:[!z&&jsx(Wn,{value:Sv,children:"None"}),ue.map(Z=>{let W=hm(Z),ee=W===_d?"(Empty)":W.charAt(0).toUpperCase()+W.slice(1);return jsx(Wn,{value:W,className:R(t,"rounded-none border-none outline-transparent"),children:ee},W)})]}):ie=="number"?c&&isUndefined(Ot(b,e))?jsx(Ue,{className:R(a==="sm"?"h-[32px]":"h-[42px]","flex animate-pulse rounded-md border-none outline-none bg-gray-200")}):jsx(gm,{uncertainty:Ot(o,e),variant:i,scalarValueType:s,inputMode:"numeric",value:D??ge.value??"",type:ie,disabled:We,onChange:Z=>{O(Z.target.value);},onBlur:()=>{D!==void 0&&Te(ge,D);},className:R(t,a==="sm"?"h-[32px] text-sm":"h-[42px] text-sm","text-opacity-90",Xs(me,ae,"border",false),ye)}):c&&isUndefined(Ot(b,e))?jsx(Ue,{className:R(a==="sm"?"h-[32px]":"h-[42px]","flex animate-pulse rounded-md border-none outline-none bg-gray-200 text-red-200")}):j==="date"?c&&isUndefined(Ot(b,e))?jsx(Ue,{className:R(a==="sm"?"h-[32px]":"h-[42px]","flex animate-pulse rounded-md border-none outline-none bg-gray-200")}):jsx(Nv,{size:a,disabled:We,value:VE(D??ge.value),onValueChange:Z=>{let W=null;if(Z){let ee=Z.getFullYear(),V=(Z.getMonth()+1).toString().padStart(2,"0"),Re=Z.getDate().toString().padStart(2,"0");W=`${ee}-${V}-${Re}`;}O(W??void 0),Te(ge,W);},className:R(t,Xs(me,ae,"border",false),ye),uncertainty:Ot(o,e),variant:i,scalarValueType:s,placeholder:"Pick a date"}):j==="datetime"?c&&isUndefined(Ot(b,e))?jsx(Ue,{className:R(a==="sm"?"h-[32px]":"h-[42px]","flex animate-pulse rounded-md border-none outline-none bg-gray-200")}):jsx(FE,{size:a,scalarValueType:s,disabled:We,value:D??ge.value,onValueChange:Z=>{O(Z??void 0),Te(ge,Z);},className:R(t,Xs(me,ae,"border",false),ye),uncertainty:Ot(o,e),variant:i}):j==="time"?jsx("div",{className:"flex items-center",children:jsx(gm,{scalarValueType:s,uncertainty:Ot(o,e),variant:i,type:ie,disabled:We,value:D??ge.value??"",onChange:Z=>{O(Z.target.value);},onBlur:()=>{D!==void 0&&Te(ge,D);},className:R(t,a==="sm"?"h-[32px] text-sm":"h-[42px] text-sm","text-opacity-90",Xs(me,ae,"border",false),ye),style:{WebkitAppearance:"none"},multiline:vt})}):jsx(LE,{scalarValueType:s,uncertainty:Ot(o,e),variant:i,disabled:We,value:D??ge.value??"",onChange:Z=>{O(Z.target.value);},onBlur:()=>{D!==void 0&&Te(ge,D);},className:R(t,a==="sm"?"h-[32px] text-sm":"h-[42px] text-sm","text-opacity-90",Xs(me,ae,"border",false),ye),style:{WebkitAppearance:"none"}})}),jsx(td,{className:R(t,"border-none shadow-none bg-transparent text-left flex mt-4 hover:bg-transparent text-xs text-red-600")})]})})},e)},Ev=({path:e,className:t,isLoneObject:r=false,isArrayItem:n=false})=>{let{schema:a,form:o,setLikelihoods:i,size:s,disabled:l,isStreaming:c,config:u}=Tn(),d=bm(a,e),{schema:g,nullable:f}=Ec(d,a),h=e.split(".").pop()||"",m=!!h&&!n&&e!=="",p=vm(e),v=xm(o.getValues(),p)?Ot(o.getValues(),p):null,y=o.getValues(e),x=()=>{let E=ym(g);o.setValue(e,E);let C=(P,T)=>{Object.keys(P).forEach(N=>{let S=T?`${T}.${N}`:N;P[N]!==null&&typeof P[N]=="object"?C(P[N],S):i(b=>{let k={...b};return Tc(k,S,1),k});});};C(E,e);},w=()=>{o.setValue(e,null);};if(f&&y===null)return jsx("div",{className:"flex mt-2",children:jsxs(K,{size:s,className:R(t,"px-2"),type:"button",variant:"outline",onClick:x,disabled:l||c,children:[jsx(Plus,{className:"size-5 mr-2"}),jsx("span",{className:"",children:h})]})});let _=g.properties||{};return jsxs("div",{className:R("space-y-4",n||r?"pb-3 pt-1 bg-background/3 border-none outline-transparent shadow-none rounded-md":""),children:[m&&jsxs("div",{className:"flex items-center gap-2 mx-auto justify-center pt-1",children:[jsx(vi,{className:R(t,"border-none outline-transparent shadow-none bg-transparent justify-center flex hover:bg-transparent mb-0 text-base font-medium"),children:h}),jsx(Qs,{show:u?.showReasoning??false,content:v,id:`${e}-reasoning-object`})]}),Object.keys(_).map(E=>{let C=_[E],{schema:P}=Ec(C,a),T=P?.type||(P?.enum?"enum":P?.properties?"object":P?.items?"array":"string");return T==="object"||P?.properties?jsx(Ev,{path:e?`${e}.${E}`:E,className:t,isLoneObject:true},E):T==="array"||P?.items?jsx(L6,{path:e?`${e}.${E}`:E,className:t},E):jsx(zE,{path:e?`${e}.${E}`:E,className:t},E)}),f&&!l&&jsxs(K,{size:s,variant:"outline",type:"button",onClick:w,className:R(t," mt-12 mx-auto flex justify-center "),disabled:l||c,children:[jsx(Trash,{className:"h-4 w-4"}),"Delete"]})]},e)};function UE(e,t=[]){return e.message?[{path:t,error:e}]:Object.entries(e).flatMap(([r,n])=>UE(n,[...t,r]))}var B6=({className:e})=>{let {showSubmit:t,schema:r,setSchema:n,config:a,onSubmit:o,form:i,likelihoods:s,setLikelihoods:l,setSourcesFieldPath:c,scalarValueDisplay:u,scalarValueType:d,isProcessing:g,isStreaming:f,size:h,disabled:m,titlePosition:p,consensusDetails:v}=Tn(),y=i.getValues(),x=y?.reasoning___root||y?.reasoning__root,w=wm(v,"");Mi(r);return jsx(Wl,{...i,children:jsxs("form",{className:"w-full flex flex-col h-full",onSubmit:i.handleSubmit(o),children:[jsxs("div",{className:"flex flex-row items-center gap-2 mx-auto ",children:[jsx(Qs,{show:a?.showReasoning??false,content:x,id:"root-reasoning"}),x&&w&&a?.showReasoning&&a?.showConsensus&&jsx(Pc,{show:a?.showReasoning,content:w,id:"root-consensus-reasoning"})]}),jsx(Ev,{className:e,path:""}),Object.keys(i.formState.errors).length>0&&a?.showErrors===true&&jsxs("div",{className:"mt-6 font-light",children:[jsx("p",{className:"text-sm font-medium text-red-500 mb-2",children:"Please fix the following errors:"}),UE(i.formState.errors).map(({path:E,error:C})=>{let T=C.message;return jsxs("div",{className:"text-xs items-end justify-end",children:[jsx(TriangleAlert,{size:16,className:"inline-block mr-1 text-red-500"}),jsx("span",{className:"",children:E.join(" > ")}),jsx("span",{className:"ml-1 text-red-500",children:T})]},E.join("."))})]}),t&&!m&&r.properties&&Object.keys(r.properties).length>0&&jsx(K,{variant:"default",className:R(e," mt-12 min-w-[200px] mx-auto flex justify-center bg-primary text-primary-foreground"),type:"submit",size:h,disabled:f||g||Object.keys(i.formState.errors).length>0,children:a?.submitText||"Submit"}),!(r.properties&&Object.keys(r.properties).length>0)&&jsx("div",{className:"min-w-[200px] mx-auto flex justify-center",children:jsx("span",{className:"text-sm text-gray-500",children:"Create a schema to get started"})})]})})},z6=({className:e,numberOfFields:t=10})=>jsx("div",{className:R("space-y-4"),children:Array.from({length:t}).map((r,n)=>jsxs("div",{className:"space-y-2",children:[jsx(Ue,{className:R(e,"h-4 w-[30%] bg-gray-200 animate-pulse rounded-md border-none outline-none outline-transparent")}),jsx(Ue,{className:R(e,"h-10 w-full bg-gray-200 animate-pulse rounded-md border-none outline-none outline-transparent")})]},n))}),qE=createContext(void 0),Tn=()=>{let e=useContext(qE);if(!e)throw new Error("useUiFormContext must be used within a UiFormContextProvider");return e},U6=({containerProps:e,children:t})=>{let[r,n]=useState(false),{schema:a,setSchema:o,onSubmit:i,form:s,config:l,variant:c,isStreaming:u,size:d,isProcessing:g,setSourcesFieldPath:f,likelihoods:h,setLikelihoods:m,scalarValueDisplay:p,scalarValueType:v,disabled:y,titlePosition:x,showSubmit:w,consensusDetails:_,propertyEditorMode:E,showPropertyEditorPencil:C,validationFlags:P,setValidationFlags:T,showVerifiedProperty:N,projectId:S,computationSpec:b,setComputationSpec:k,formFieldIdPrefix:D}=e,O={showSubmit:w??true,schema:a,setSchema:o,form:s,isStreaming:u,isProcessing:g,onSubmit:i,config:l,variant:c,size:d,likelihoods:h,setLikelihoods:m,scalarValueDisplay:p,scalarValueType:v,disabled:y,titlePosition:x,setSourcesFieldPath:f,consensusDetails:_,isEditing:r,setIsEditing:n,propertyEditorMode:E,showPropertyEditorPencil:C,validationFlags:P,setValidationFlags:T,showVerifiedProperty:N,projectId:S,computationSpec:b,setComputationSpec:k,formFieldIdPrefix:D};return jsx(qE.Provider,{value:O,children:t})},q6=Rt__default.memo(U6),kc=({className:e})=>{let{isProcessing:t,isStreaming:r,form:n}=Tn();return t&&!r?jsx(z6,{}):jsx(B6,{className:e})},Rc=e=>{let{className:t,children:r}=e;return jsx(q6,{containerProps:e,children:jsx("div",{className:R("gap-4",t),children:r})})},VE=e=>{if(!e||e==="Undefined")return null;let t=Date.parse(e);return Number.isNaN(t)?null:new Date(t)},xv=(e,t)=>t.split(".").reduce((r,n)=>{if(r!=null)return n==="*"?r:/^\d+$/.test(n)?r[Number(n)]:r[n]},e);var V6={headerBg:"bg-zinc-100 hover:bg-zinc-200",headerText:"text-zinc-800 hover:text-zinc-800",subHeaderBg:"bg-zinc-200",subHeaderHoverBg:"hover:bg-zinc-300",border:"border-zinc-200",verticalLine:"bg-zinc-200",tableContainerBg:"bg-white",tableRowBg:"bg-transparent hover:bg-zinc-100",tableCellBg:"bg-transparent hover:bg-zinc-50",forbiddenCellBg:"bg-zinc-100",selectedBg:"bg-zinc-300",selectedHoverBg:"hover:bg-zinc-400",tooltipBg:"bg-gray-100",tooltipText:"text-gray-800",disabledOpacity:"disabled:opacity-100 text-inherit",plusButtonIcon:"text-gray-600"};var HE={headerBg:"bg-gray-100 hover:bg-gray-200",headerText:"text-gray-800 hover:text-gray-800",subHeaderBg:"bg-gray-200",subHeaderHoverBg:"hover:bg-gray-300",border:"border-gray-200",verticalLine:"bg-gray-200",tableContainerBg:"bg-white",tableRowBg:"bg-transparent hover:bg-gray-100",tableCellBg:"bg-transparent hover:bg-gray-50",forbiddenCellBg:"bg-gray-100",selectedBg:"bg-gray-300",selectedHoverBg:"hover:bg-gray-400",tooltipBg:"bg-gray-100",tooltipText:"text-gray-800",disabledOpacity:"disabled:opacity-100 text-inherit",plusButtonIcon:"text-gray-600"},H6={headerBg:"bg-neutral-100 hover:bg-neutral-200",headerText:"text-neutral-800 hover:text-neutral-800",subHeaderBg:"bg-neutral-200",subHeaderHoverBg:"hover:bg-neutral-300",border:"border-neutral-200",verticalLine:"bg-neutral-200",tableContainerBg:"bg-white",tableRowBg:"bg-transparent hover:bg-neutral-100",tableCellBg:"bg-transparent hover:bg-neutral-50",forbiddenCellBg:"bg-neutral-100",selectedBg:"bg-neutral-300",selectedHoverBg:"hover:bg-neutral-400",tooltipBg:"bg-neutral-100",tooltipText:"text-neutral-800",disabledOpacity:"disabled:opacity-100 text-inherit",plusButtonIcon:"text-neutral-600"},J6={headerBg:"bg-slate-100 hover:bg-slate-200",headerText:"text-slate-800 hover:text-slate-800",subHeaderBg:"bg-slate-200",subHeaderHoverBg:"hover:bg-slate-300",border:"border-slate-200",verticalLine:"bg-slate-200",tableContainerBg:"bg-white",tableRowBg:"bg-transparent hover:bg-slate-100",tableCellBg:"bg-transparent hover:bg-slate-50",forbiddenCellBg:"bg-slate-100",selectedBg:"bg-slate-300",selectedHoverBg:"hover:bg-slate-400",tooltipBg:"bg-gray-100",tooltipText:"text-gray-800",disabledOpacity:"disabled:opacity-100 text-inherit",plusButtonIcon:"text-gray-600"};function br(e){return e.includes("dataset")?J6:e.includes("builder")?V6:e==="hil"?H6:HE}var WE=({itemIndex:e,iterationIndex:t,schema:r,setSchema:n,extractionData:a,similarities:o,scalarValueType:i,isStreamingIteration:s,isRunningIteration:l,onFieldPathChange:c,consensusDetails:u,showSources:d=false,themeOverride:g=null,groundTruthData:f,onGroundTruthChange:h,onToggleMismatch:m,mismatches:p,editMode:v,showPropertyEditorPencil:y=true,allowEditing:x=false,onPredictionChange:w,computationSpec:_,setComputationSpec:E,projectId:C,showReasoning:P=true})=>{let T=useForm({mode:"all",defaultValues:a||{},resolver:void 0,shouldUnregister:false});useEffect(()=>{T.reset(a||{},{keepDirty:false,keepErrors:false,keepTouched:false,keepIsSubmitted:false,keepSubmitCount:false,keepValues:false,keepDirtyValues:false,keepDefaultValues:false});},[a,r,T,e,t,s]),useEffect(()=>{if(!x||!w||s)return;let $=T.watch((A,{type:F})=>{(F==="change"||F===void 0)&&w(e,A);});return ()=>{$.unsubscribe();}},[T,x,w,e,s]);let N=useMemo(()=>({readOnly:!x,showReasoning:P,showConsensus:true,showConfidenceTablets:true,groundTruthData:f,onGroundTruthChange:h,onToggleMismatch:m,mismatches:p,predictionData:a}),[f,h,m,p,a,x,P]),S=useCallback($=>{$&&c?.($);},[c]),b=useCallback(()=>{},[]),k=useMemo(()=>o||{},[o]),D=br(g||"dark"),O=useMemo(()=>!a||Object.keys(a).length===0,[a]);return jsx(Rc,{showSubmit:false,form:T,schema:r,setSchema:n,onSubmit:()=>{},variant:"normal",config:N,size:"sm",className:"w-full p-1 pb-8",disabled:!x,titlePosition:"row",likelihoods:k,setLikelihoods:b,isStreaming:s&&Object.keys(a||{}).length>0,isProcessing:l&&!s,scalarValueDisplay:"outline-large",scalarValueType:i,setSourcesFieldPath:S,consensusDetails:u||[],propertyEditorMode:v,showPropertyEditorPencil:y,formFieldIdPrefix:"extraction-form-field",validationFlags:{},setValidationFlags:b,computationSpec:_,setComputationSpec:E,projectId:C,children:jsx(kc,{className:`border ${D.border} rounded-sm !text-xs ${D.tableContainerBg} ${D.headerText} disabled:opacity-100`})},`pfw-${e}-${t}-${O?"empty":"data"}`)};var K6=Rt__default.memo(({itemIndex:e,schema:t,setSchema:r,groundTruth:n,similarities:a,readOnly:o=true,onGroundTruthChange:i,onFieldPathChange:s,scalarValueType:l,consensusDetails:c,isStreaming:u=false,isProcessing:d=false,validationFlags:g,setValidationFlags:f,showVerifiedProperty:h=true,showPropertyEditorPencil:m=true,editMode:p,computationSpec:v,setComputationSpec:y,projectId:x})=>{let w=process.env.NODE_ENV!=="production",_=useMemo(()=>t?ME():void 0,[t]),E=useForm({mode:"all",defaultValues:n||{},resolver:o?void 0:_}),C=useRef(n),P=useRef(t),T=useRef(e),N=useCallback(async A=>{E.reset(A||{},{keepDefaultValues:true}),await E.trigger();},[E]);useEffect(()=>{let A=C.current!==n,F=P.current!==t,X=T.current!==e;!o&&t&&n!==void 0&&(A||F||X)&&(N(n),C.current=n,P.current=t,T.current=e);},[n,t,e,N,w,o]),useEffect(()=>{if(o||!i||u)return;let A=E.watch((F,{type:X})=>{(X==="change"||X===void 0)&&i(e,F);});return ()=>{A.unsubscribe();}},[E,o,i,e,u]);let S=useMemo(()=>({readOnly:o,showReasoning:true,showConsensus:true,showConfidenceTablets:true}),[o]),b=useCallback(A=>{A&&s?.(A);},[s]),k=useCallback(()=>{},[]),D=useMemo(()=>a||{},[a]),O=br("dataset"),$=useCallback(()=>{},[]);return jsx(Rc,{showSubmit:false,form:E,schema:t,setSchema:r,onSubmit:()=>{},variant:"normal",likelihoods:D,config:S,size:"sm",className:"w-full p-1 pb-8",disabled:o||u,titlePosition:"row",setLikelihoods:k,isStreaming:u,isProcessing:d,scalarValueDisplay:"outline-large",scalarValueType:l,setSourcesFieldPath:b,consensusDetails:c,propertyEditorMode:p,showPropertyEditorPencil:m,formFieldIdPrefix:"ground-truth-form-field",validationFlags:g||{},setValidationFlags:f||$,showVerifiedProperty:h,computationSpec:v,setComputationSpec:y,projectId:x,children:jsx(kc,{className:`border ${O.border} rounded-sm !text-xs ${O.tableContainerBg} ${O.headerText} disabled:opacity-100`})})});K6.displayName="GroundTruthFormWrapper";function KE(e,t){for(let r of t)e.includes("*")&&(e=e.replace("*",r.toString()));return e}function X6(e){return e.filter(Boolean).join(".")}function GE(e,t=[]){let r=[],n=[];function a(i,s,l,c,u,d,g){let f=0,h=0;if(s=s.filter(p=>p.length!==c?true:(r[u]||(r[u]=[]),n[u]||(n[u]=[]),r[u][d+h]=i,n[u][d+h]={value:i,tpl:X6(p),idx:l,plusPathIdx:g},h++,f=1,false)),s.length===0)return [f,h];let m=new Set(s.filter(p=>p.length>c).map(p=>p[c]));if(m.has("*")&&m.size===1){let p=Array.isArray(i)?i:[];for(let x=0;x<p.length;x++){let w=p[x],[_,E]=a(w,s,[...l,x],c+1,u+f,d,g);f+=_,h=Math.max(h,E);}let[v,y]=a(void 0,s,[...l,p.length],c+1,u+f,d,g??l.length);return [f+v,Math.max(h,y)]}if(m.has("*"))throw new Error("Wildcard '*' used along with other properties");for(let p of m){let v=s.filter(_=>_[c]===p),y=i?.[p],[x,w]=a(y,v,l,c+1,u,d+h,g);f=Math.max(f,x),h+=w;}return [f,h]}let o=e&&typeof e=="object"&&"prediction_data"in e?e.prediction_data?.prediction??{}:{};if(t.includes("sum_amounts")&&"sum_amounts"in o&&console.log("[PATH-UTILS] sum_amounts found in root:",o.sum_amounts,"tplOrder:",t),a(o,t.map(i=>i.split(".")),[],0,0,0,void 0),t.includes("sum_amounts")){let i=n[0]?.find(s=>s?.tpl==="sum_amounts");console.log("[PATH-UTILS] sum_amounts pathInfo:",i);}return {table:r,paths:n}}function Nm(e){let t=useRef(e);return t.current=e,useCallback((...r)=>t.current(...r),[])}function Tv(e,t,r,n=""){if(e===t)return true;if(typeof e!=typeof t||typeof e!="object"||e==null||t==null||Array.isArray(e)!==Array.isArray(t))return false;if(r?.shallow?.includes(n)||!r?.shallow?.length&&r?.deep?.length&&!r?.deep?.find(i=>i.startsWith(n)))return Object.is(e,t);let a=Object.keys(e),o=Object.keys(t);if(a.length!==o.length)return false;for(let i of a)if(!Tv(e[i],t[i],n?n+"."+i:i))return false;return true}function Ys(e,t,r){if(t.length===0)return typeof r=="function"?r(e):r;let[n,...a]=t,o=/^\d+$/.test(n),i=o?parseInt(n,10):n,s=e??(o?[]:{});if(o){let u=Array.isArray(s)?s:[],d=Array.isArray(s)?s[i]:void 0,g=Ys(d,a,r),f=u.slice();return f[i]=g,f}let l=s&&typeof s=="object"&&!Array.isArray(s)?s:{},c=l?.[i];return {...l,[i]:Ys(c,a,r)}}function kv({className:e,orientation:t="horizontal",decorative:r=true,...n}){return jsx(ZE.Root,{"data-slot":"separator",decorative:r,orientation:t,className:R("bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",e),...n})}var Ac=create(e=>({rowHeight:"medium",columnWidth:"large",setRowHeight:t=>e({rowHeight:t}),setColumnWidth:t=>e({columnWidth:t})}));var Mo=e=>{switch(e){case "small":return 48;case "medium":return 64;case "large":return 96;case "xl":return 128;case "xxl":return 160;default:return 64}},el=e=>{switch(e){case "small":return 24;case "medium":return 32;case "large":return 40;case "xl":return 48;case "xxl":return 64;default:return 32}};var Om=Rt__default.createContext(false),tP=({isDialog:e,...t})=>{let[r,n]=useState(typeof window<"u"?window.innerHeight>=900:false);useEffect(()=>{let o=null,i=0,s=()=>{let c=window.innerHeight>=900;n(u=>u!==c?c:u);},l=()=>{let c=Date.now(),u=1e3-(c-i);u<=0?(i=c,o&&(clearTimeout(o),o=null),s()):(o&&clearTimeout(o),o=setTimeout(()=>{i=Date.now(),s(),o=null;},u));};return s(),window.addEventListener("resize",l),()=>{window.removeEventListener("resize",l),o&&clearTimeout(o);}},[]);let a=e===void 0?!r:e;return jsx(Om.Provider,{value:a,children:a?jsx(En,{...t}):jsx(Ht,{...t})})},rP=({...e})=>useContext(Om)?jsx(pd,{...e}):jsx(Jt,{...e}),nP=({...e})=>useContext(Om)?jsx(ov,{...e}):jsx(Wt,{...e}),aP=({className:e,children:t,...r})=>useContext(Om)?jsx(Pn,{className:e,...r,children:t}):jsx("h4",{className:e,...r,children:t}),oP=e=>{if(!e)return null;let t=e.match(/^(\d{1,2})\s+(\d{1,2})\s+(\d{4})$/);if(t){let[,s,l,c]=t;return new Date(parseInt(c),parseInt(l)-1,parseInt(s))}let r=e.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);if(r){let[,s,l,c]=r;return new Date(parseInt(c),parseInt(l)-1,parseInt(s))}let n=e.match(/^(\d{1,2})-(\d{1,2})-(\d{4})$/);if(n){let[,s,l,c]=n;return new Date(parseInt(c),parseInt(l)-1,parseInt(s))}let a=e.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})$/);if(a){let[,s,l,c]=a;return new Date(parseInt(c),parseInt(l)-1,parseInt(s))}if(e.match(/^\d{4}-\d{2}-\d{2}$/))return new Date(e);let i=new Date(e);return isNaN(i.getTime())?null:i},iP=e=>{switch(e){case "string":return Type;case "boolean":return CheckSquare;case "number":case "integer":return Hash;case "object":return Box;case "array":return Table;case "date":return Calendar;case "time":return Clock;case "datetime":return CalendarClock;case "enum":return List;case "$ref":return Box;default:return Type}},Cm=e=>{if(!e||typeof e!="object")return false;if(e["X-ReasoningPrompt"]&&e["X-ReasoningPrompt"]!==""&&e["X-ReasoningPrompt"]!==null&&e["X-ReasoningPrompt"]!==void 0)return true;for(let t in e)if((t==="X-Reasoning"||t==="X-ReasoningSteps"||t.startsWith("X-Reasoning"))&&e[t]!==""&&e[t]!==null&&e[t]!==void 0)return true;return false},sP=e=>e.includes("reasoning___")||e.includes("reasoning__"),Em=e=>!e||typeof e!="object"?false:e["X-ComputedField"]===true,Pm=e=>!e||typeof e!="object"?false:e["X-FunctionField"]===true,Tm=e=>!e||typeof e!="object"?false:e["X-HumanInTheLoopCriterion"]===true;function oa(e,t){if(e==null||typeof e!="object")return t;let r=e;for(;r.$ref&&typeof r.$ref=="string";){let n=r.$ref.split("/");if(n[0]!=="#")throw new Error("Only internal references are supported");let a=t;for(let o=1;o<n.length;o++)a=a?.[n[o]];if(a==null||typeof a!="object")return {type:"object"};r=a;}return r}function ao(e,t){let r=oa(e,t),n=false;Array.isArray(r?.type)&&r.type.includes("null")&&(n=true,r={...r,type:r.type.find(o=>o!=="null")});let a=r.anyOf||r.oneOf||r.allOf;if(Array.isArray(a)&&a.length){a.some(i=>i?.type==="null")&&(n=true);let o=a.find(i=>{let s=oa(i,t),l=Array.isArray(s?.type)?s.type.find(c=>c!=="null"):s?.type;return l!=="null"&&(l||s.properties||s.items||s.enum)});if(o){let i=oa(o,t),{anyOf:s,oneOf:l,allOf:c,...u}=i;r=u;}}return {schema:r,nullable:n}}function km(e,t,r,n){let a=n?.seen??new WeakSet,o=n?.depth??0,i=n?.maxDepth??64,s=oa(e,r);if(s=ao(s,r).schema,o>i)return console.warn("[getSchemaFlatProperties] Max depth reached while flattening schema at path:",t.join(".")),[{key:t.join("."),type:s}];if(s&&typeof s=="object"){if(a.has(s))return console.warn("[getSchemaFlatProperties] Circular schema reference detected at path:",t.join(".")),[{key:t.join("."),type:{...s||{},type:s.type??"object",title:s.title||"(circular)"}}];a.add(s);}if(s.type==="array"){if(s.items){if(Array.isArray(s.items))return s.items.flatMap((l,c)=>km(l,[...t,String(c)],r,{seen:a,depth:o+1,maxDepth:i}));if(typeof s.items=="object"){let l=ao(s.items,r).schema;return km(l,[...t,"*"],r,{seen:a,depth:o+1,maxDepth:i})}}}else if(s.type==="object"&&s.properties)return Object.entries(s.properties).flatMap(([l,c])=>km(c,[...t,l],r,{seen:a,depth:o+1,maxDepth:i}));return [{key:t.join("."),type:s}]}function $c(e,t){let r=e;if(t==="")return e;let n=t.split(".");for(let a=0;a<n.length;a++){let o=oa(e,r),i=ao(o,r).schema;i.type==="object"&&i.properties?e=i.properties[n[a]]:i.type==="array"&&i.items&&(Array.isArray(i.items)?e=i.items[parseInt(n[a])]:typeof i.items=="object"&&(n[a]==="*"||!isNaN(parseInt(n[a])))&&(e=i.items));}return e=oa(e,r),e}function c7(e,t){let r=e;if(t==="")return e;let n=t.split(".");for(let a=0;a<n.length;a++){let o=oa(e,r),i=ao(o,r).schema;i.type==="object"&&i.properties?e=i.properties[n[a]]:i.type==="array"&&i.items&&(Array.isArray(i.items)?e=i.items[parseInt(n[a])]:typeof i.items=="object"&&(n[a]==="*"||!isNaN(parseInt(n[a])))&&(e=i.items));}return e}var Rv=e=>e.split("_").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ");function Dv(e){return e.reduce((t,r)=>"columns"in r&&Array.isArray(r.columns)?t.concat(Dv(r.columns)):t.concat([r]),[])}function lP(e,t){let r=t.reduce((n,{key:a})=>{let o=a.split(".")[e];return o&&!n.includes(o)&&n.push(o),n},[]);if(r.includes("*")&&r.length!==1)throw new Error("Invalid schema for array");return r}function u7(e,t,r,n,a){let o=JSON.parse(JSON.stringify(e)),i,s;if(!t)i=o,i.type==="object"&&i.properties&&(s=i.properties);else {let m=t.split("."),p=o;for(let y of m){let x=oa(p,o);if(!x||typeof x!="object"){console.error(`Could not resolve current node at segment: ${y} in ${t}`);return}if(p=x,y==="$defs"&&p.$defs){console.warn("Navigating through $defs, ensure path is correct."),p=p.$defs;continue}if(p.type==="object"&&p.properties&&p.properties[y])p=p.properties[y];else if(p.type==="array"&&y==="*"&&p.items&&typeof p.items=="object")p=p.items;else if(p[y]&&typeof p[y]=="object")p=p[y];else {console.error(`Could not find path: ${t} in schema. Segment: ${y}, Current Node:`,JSON.parse(JSON.stringify(p)));return}}let v=p;if(p&&typeof p=="object"&&p.$ref){let x=p.$ref.split("/");if(x[0]==="#"){let w=o;for(let _=1;_<x.length;_++)w=w?.[x[_]];w&&typeof w=="object"&&(v=w);}}i=v,i&&i.type==="object"&&(i.properties||(i.properties={}),s=i.properties);}if(!i||!s){console.error("Node for reordering is not an object with properties or path is invalid. Path:",t,"Parent Node:",i);return}let l=s,c=Object.keys(l),u=c.indexOf(r),d=c.indexOf(n);if(u===-1||d===-1||u===d){console.warn("Reorder failed: Invalid property names or indices.",{sourcePropName:r,targetPropName:n,keys:c});return}let g=Array.from(c),[f]=g.splice(u,1);g.splice(d,0,f);let h={};g.forEach(m=>{h[m]=l[m];}),i.properties=h;}function uP(e,t,r,n,a,o,i,s,l,c,u,d){var g=0;if(!e.properties||Object.keys(e.properties).length===0)return [[],0];let f=br(l);function h(m,p){function v(P,T){return P.split(".")[p]===T}if(m.length===0)return [];let y=lP(p,m);if(y.length===1&&y[0]==="*"){let P=p+1;g=Math.max(g,P);let T=m.map(S=>({key:S.key})),N=lP(P,T);if(!(N.length===1&&N[0]==="*"))return h(T,P)}let x=(P,T,N)=>{if((N?$c(e,N):e).type==="object"){P.dataTransfer.setData("text/plain",T),P.dataTransfer.effectAllowed="move",i.current=T,s.current=N;let b=document.createElement("div");b.textContent=Rv(T),b.style.position="absolute",b.style.top="-1000px",b.style.left="-1000px",b.style.padding="4px 8px",b.style.backgroundColor="rgba(200, 200, 200, 0.7)",b.style.border="1px solid #ccc",b.style.borderRadius="4px",b.style.fontSize="12px",b.style.fontFamily="sans-serif",document.body.appendChild(b),P.dataTransfer.setDragImage(b,10,10),setTimeout(()=>{document.body.removeChild(b);},0);}else P.preventDefault();},w=(P,T,N)=>{P.preventDefault();let S=i.current;if(s.current===N&&S&&S!==T){P.dataTransfer.dropEffect="move",P.currentTarget.classList.remove("border-l-2","border-r-2");let b;if(N===""?b=oa(e,e):b=oa($c(e,N),e),b&&b.type==="object"&&b.properties){let k=Object.keys(b.properties),D=k.indexOf(S),O=k.indexOf(T);D!==-1&&O!==-1&&(D<O?P.currentTarget.classList.add("border-r-2","border-r-black"):P.currentTarget.classList.add("border-l-2","border-l-black"));}}},_=P=>{P.currentTarget.classList.remove("border-l-2","border-r-2","border-r-black","border-l-black");},E=(P,T,N)=>{P.preventDefault(),P.currentTarget.classList.remove("border-l-2","border-r-2","border-r-black","border-l-black");let S=i.current,b=s.current;S&&b===N&&S!==T&&u7(e,N,S,T),i.current=null,s.current=null;},C=P=>{i.current=null,s.current=null;};return y.flatMap(P=>{let T=m.filter(({key:L})=>v(L,P)),N=T[0].key.split(".").slice(0,p+1).join("."),S=c7(e,N),{schema:b}=ao(S,e),D=yn(b),O=lv(b,e),$=iP(D.type),A=h(T,p+1);if(D.type==="array"){let L=!r.some(ae=>N.startsWith(ae)),Q=L?A.length>0?[...A]:[{accessorKey:N+".*",header:({column:ae})=>{let M=Mo(a)-20,j=Type;try{if(b&&b.type==="array"){let ue=b.items;if(ue){let ie=ao(ue,e).schema,Ce=yn(ie);j=iP(Ce.type);}}}catch{j=Type;}return jsx(K,{variant:"ghost",size:"icon",className:"grow rounded-none justify-start px-1",children:jsxs("div",{className:"items-center truncate text-3xs overflow-hidden flex-row gap-2 flex",style:{maxWidth:`${M}px`,minWidth:`${M}px`},children:[jsx(j,{className:"h-3! w-3!"}),"Value"]})})}}]:[],z=A.length>0;return {accessorKey:N,foldable:z,...Q.length>0?{columns:Q}:{},header:({column:ae})=>jsx(()=>{let[j,ue]=useState(false),[ie,Ce]=useState(false),Te=N.toString().split(".")?.pop()||N.toString(),Je=Te,vt=N.toString().split(".");vt.pop();let gt=vt.join("."),bt=Rv(Te),We=ae.getLeafColumns().length||1,ke=Mo(a)*(L?We:1)-(z?44:20),be=gt?$c(e,gt):e,re=be&&be.type==="object",me=Cm(S)||Cm(b)||sP(N),ye=Em(S)||Em(b),ge=Pm(S)||Pm(b),Z=Tm(S)||Tm(b);return jsxs("div",{className:"w-full h-full flex group",draggable:re,onDragStart:W=>re&&x(W,Je,gt),onDragOver:W=>re&&w(W,Je,gt),onDragLeave:W=>re&&_(W),onDrop:W=>re&&E(W,Je,gt),onDragEnd:W=>re&&C(),children:[jsxs(tP,{open:j,onOpenChange:W=>{!W&&!ie?ue(false):W&&ue(true);},children:[jsx(rP,{asChild:true,children:jsx(K,{variant:"ghost",size:"sm",className:`grow rounded-none h-full justify-start px-1 ${Z?"bg-emerald-50 hover:bg-emerald-100 text-emerald-900 hover:text-emerald-950":ye?"bg-[#E0F2FE] hover:bg-blue-100 text-[#1E3A8A] hover:text-blue-900":me?"bg-[#F6EEFF] hover:bg-purple-100 text-[#3E274A] hover:text-purple-900":`${f.headerText} ${f.headerBg}`}`,children:jsxs("div",{className:"items-center truncate text-3xs overflow-hidden flex-row gap-2 flex",style:{maxWidth:`${ke}px`,minWidth:`${ke}px`},children:[jsx($,{className:"h-3! w-3!"})," ",bt]})})}),jsxs(nP,{className:"flex flex-col p-0 w-[400px] max-h-[80vh] overflow-y-auto",align:"start",children:[jsxs("div",{className:"flex items-center justify-between px-4 py-3",children:[jsx("div",{className:"flex items-center gap-1",children:jsx(aP,{className:"font-medium leading-none",children:bt})}),false]}),jsx(kv,{className:"my-0 "}),ye?jsx(Nc,{fieldPath:N,jsonSchema:e,computationSpec:c,setComputationSpec:u,onClose:()=>ue(false),readOnly:d==="readOnly"}):jsx(xc,{property:S,propertyKey:N,setDropdownOpen:ue,jsonSchema:e,setJsonSchema:t,editMode:Z||ge?"readOnly":d})]})]}),z&&jsx(K,{variant:"ghost",size:"icon",className:`w-9 items-center justify-center flex h-full rounded-none ${Z?"bg-emerald-50 hover:bg-emerald-100 text-emerald-900 hover:text-emerald-950":ye?"bg-[#E0F2FE] hover:bg-blue-100 text-[#1E3A8A] hover:text-blue-900":ge?"bg-emerald-50 hover:bg-emerald-100 text-emerald-900 hover:text-emerald-950":me?"bg-[#F6EEFF] hover:bg-purple-100 text-[#3E274A] hover:text-purple-900":`${f.headerText} ${f.headerBg}`}`,onClick:()=>{r.includes(N)?n(r.filter(W=>W!==N)):n([...r,N]);},children:r.includes(N)?jsx(ChevronDown,{className:"h-3 w-3"}):jsx(ChevronUp,{className:"h-3 w-3"})})]})},{}),cell:({row:ae})=>{let M=ae.getValue(N);return jsx("div",{className:"text-3xs text-muted-foreground px-1 truncate",children:Array.isArray(M)?`[${M.length} items]`:"[Array]"})}}}let F=!r.some(L=>N.startsWith(L)),X=F?A:[],H=O&&A.length>0;return {accessorKey:N,foldable:H,...X.length>0?{columns:X}:void 0,header:({column:L})=>jsx(()=>{let[z,ae]=useState(false),[M,j]=useState(false),ue=N.toString().split(".")?.pop()||N.toString(),ie=ue,Ce=N.toString().split(".");Ce.pop();let Te=Ce.join("."),Je=Rv(ue),vt=L.getLeafColumns().length||1,gt=Mo(a)*(F?vt:1)-(H?44:20),bt=Te?$c(e,Te):e,We=bt&&bt.type==="object",ke=Cm(S)||Cm(b)||sP(N),be=Em(S)||Em(b),re=Pm(S)||Pm(b),me=Tm(S)||Tm(b);return jsxs("div",{className:"w-full h-full flex group",draggable:We,onDragStart:ye=>We&&x(ye,ie,Te),onDragOver:ye=>We&&w(ye,ie,Te),onDragLeave:ye=>We&&_(ye),onDrop:ye=>We&&E(ye,ie,Te),onDragEnd:ye=>We&&C(),children:[jsxs(tP,{open:z,onOpenChange:ye=>{!ye&&!M?ae(false):ye&&ae(true);},children:[jsx(rP,{asChild:true,children:jsx(K,{variant:"ghost",size:"sm",className:`grow rounded-none justify-start h-full px-1 ${me?"bg-emerald-50 hover:bg-emerald-100 text-emerald-900 hover:text-emerald-950":be?"bg-[#E0F2FE] hover:bg-blue-100 text-[#1E3A8A] hover:text-blue-900":ke?"bg-[#F6EEFF] hover:bg-purple-100 text-[#3E274A] hover:text-purple-900":re?"bg-emerald-50 hover:bg-emerald-100 text-emerald-900 hover:text-emerald-950":`${f.headerText} ${f.headerBg}`}`,children:jsxs("div",{className:"items-center truncate text-3xs overflow-hidden flex-row gap-2 flex",style:{maxWidth:`${gt}px`,minWidth:`${gt}px`},children:[jsx($,{className:"h-3! w-3!"}),Je]})})}),jsxs(nP,{className:"flex flex-col w-[400px] p-0 gap-0 max-h-[80vh] overflow-y-auto",align:"start",children:[jsxs("div",{className:"flex items-center justify-between px-4 py-3",children:[jsx("div",{className:"flex items-center",children:jsx(aP,{className:"flex font-medium leading-none justify-center items-center",children:Je})}),jsx("div",{className:"flex items-center gap-2",children:false})]}),jsx(kv,{}),be?jsx(Nc,{fieldPath:N,jsonSchema:e,computationSpec:c,setComputationSpec:u,onClose:()=>ae(false),readOnly:d==="readOnly"}):jsx(xc,{property:S,propertyKey:N,setDropdownOpen:ae,jsonSchema:e,setJsonSchema:t,editMode:me||re?"readOnly":d})]})]}),H&&jsx(K,{variant:"ghost",size:"icon",className:`w-6 h-full rounded-none ${me?"bg-emerald-50 hover:bg-emerald-100 text-emerald-900 hover:text-emerald-950":be?"bg-[#E0F2FE] hover:bg-blue-100 text-[#1E3A8A] hover:text-blue-900":re?"bg-emerald-50 hover:bg-emerald-100 text-emerald-900 hover:text-emerald-950":ke?"bg-[#F6EEFF] hover:bg-purple-100 text-[#3E274A] hover:text-purple-900":`${f.headerText} ${f.headerBg}`}`,onClick:()=>{r.includes(N)?n(r.filter(ye=>ye!==N)):n([...r,N]);},children:r.includes(N)?jsx(ChevronDown,{className:"h-3 w-3"}):jsx(ChevronUp,{className:"h-3 w-3"})})]})},{}),cell:({row:L})=>{let Q=L.getValue(N),z=e.properties?.[N];if(!Xp(z))return jsx("div",{children:String(Q)});if(O)return jsx("div",{className:"text-3xs text-muted-foreground",children:Q?jsxs("div",{className:"truncate max-w-[80px]",children:[JSON.stringify(Q).substring(0,15),JSON.stringify(Q).length>15?"...":""]}):jsx("span",{children:"[Object]"})});if(z.type==="string"&&z.format){if(z.format==="date"&&Q){let ae=oP(Q);return jsx("div",{children:ae?ae.toLocaleDateString():Q})}if(z.format==="iso-time"&&Q)return jsx("div",{children:Q});if(z.format==="date-time"&&Q){let ae=oP(Q);return jsx("div",{children:ae?ae.toLocaleString():Q})}}return z.type==="number"?jsx("div",{className:"text-right",children:Q}):z.type==="boolean"?jsx("div",{children:Q?"Yes":"No"}):z.enum?jsx("div",{className:"capitalize",children:Q}):jsx("div",{children:String(Q)})}}})}return [(()=>{try{let m=km(e,[],e);return h(m,0)}catch(m){return console.error("[ColumnsFromSchema] Failed to flatten schema:",m),[]}})(),g]}var oo=Rt.forwardRef(({className:e,...t},r)=>jsx("table",{ref:r,className:R(" caption-bottom text-sm",e),...t}));oo.displayName="Table";var ji=Rt.forwardRef(({className:e,...t},r)=>jsx("thead",{ref:r,className:R("[&_tr]:border-b",e),...t}));ji.displayName="TableHeader";var io=Rt.forwardRef(({className:e,...t},r)=>jsx("tbody",{ref:r,className:R("[&_tr:last-child]:border-0",e),...t}));io.displayName="TableBody";var d7=Rt.forwardRef(({className:e,...t},r)=>jsx("tfoot",{ref:r,className:R("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",e),...t}));d7.displayName="TableFooter";var Vr=Rt.forwardRef(({className:e,...t},r)=>jsx("tr",{ref:r,className:R("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),...t}));Vr.displayName="TableRow";var Nr=Rt.forwardRef(({className:e,...t},r)=>jsx("th",{ref:r,className:R("h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t}));Nr.displayName="TableHead";var Ct=Rt.forwardRef(({className:e,...t},r)=>jsx("td",{ref:r,className:R("p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t}));Ct.displayName="TableCell";var f7=Rt.forwardRef(({className:e,...t},r)=>jsx("caption",{ref:r,className:R("mt-4 text-sm text-muted-foreground",e),...t}));f7.displayName="TableCaption";function pP({property:e,currentValue:t,onSubmit:r,likelihoods:n={},scalarValueType:a,setSourcesFieldPath:o,currentIterationId:i,disabled:s=false}){let l=useForm({defaultValues:t,resolver:ajvResolver(e,{strictSchema:false,allErrors:true})}),c=i!=="dataset"&&i!=="playground"?"promptOnly":"editable",u=br("gray");return jsx("div",{className:"flex flex-col space-y-4 max-h-[60vh] overflow-y-auto",children:jsx(Rc,{form:l,schema:e,variant:"normal",config:{showReasoning:true},size:"sm",className:"w-full",disabled:s,isStreaming:false,isProcessing:false,scalarValueDisplay:"outline-large",scalarValueType:a,likelihoods:n,setLikelihoods:()=>{},onSubmit:r,titlePosition:"object",setSourcesFieldPath:o,propertyEditorMode:c,showPropertyEditorPencil:i==="dataset"||i==="playground",validationFlags:{},setValidationFlags:()=>{},children:jsx(kc,{className:`border ${u.border} rounded-sm !text-xs ${u.tableContainerBg} ${u.headerText} disabled:opacity-100`})})})}function mP({name:e,property:t,currentValue:r,onSubmit:n,likelihoods:a={},scalarValueType:o,setSourcesFieldPath:i,currentIterationId:s,disabled:l=false}){let{$defs:c,...u}=t,d={type:"object",$defs:c,properties:{[e]:u},required:[e]},g=useForm({defaultValues:{[e]:Array.isArray(r)?r:[]},resolver:ajvResolver(d,{strictSchema:false,allErrors:true})}),f=p=>{n(p[e]);},h=s!=="dataset"&&s!=="playground"?"promptOnly":"editable",m=br("gray");return jsx("div",{className:"flex flex-col space-y-4 max-h-[60vh] overflow-y-auto",children:jsx(Rc,{form:g,schema:d,variant:"normal",config:{showReasoning:true},size:"sm",className:"w-full",disabled:l,isStreaming:false,isProcessing:false,scalarValueDisplay:"outline-large",scalarValueType:o,likelihoods:a,setLikelihoods:()=>{},onSubmit:f,titlePosition:"object",setSourcesFieldPath:i,propertyEditorMode:h,showPropertyEditorPencil:s==="dataset"||s==="playground",validationFlags:{},setValidationFlags:()=>{},children:jsx(kc,{className:`border ${m.border} rounded-sm !text-xs ${m.tableContainerBg} ${m.headerText} disabled:opacity-100`})})})}var Nd=(e,t)=>{if(!e||!t)return;let r=t.split(".").map(a=>{let o=Number(a);return Number.isFinite(o)&&String(o)===a?o:a}),n=e;for(let a of r){if(n==null)return;n=Array.isArray(n)||typeof n=="object"?n[a]:void 0;}return typeof n=="boolean"?n:void 0},p7=(e,t,r)=>{if(!t)return e;let n=t.split(".").map(o=>{let i=Number(o);return Number.isFinite(i)&&String(i)===o?i:o}),a=(o,i)=>{if(i.length===0)return r;let[s,...l]=i;if(typeof s=="number"){let u=Array.isArray(o)?[...o]:[];return u[s]=a(u[s],l),u}let c=o&&typeof o=="object"&&!Array.isArray(o)?{...o}:{};return c[s]=a(c[s],l),c};return a(e||{},n)},Av=async(e,t,r)=>{if(!e||!t)return;let a=!Nd(e.validation_flags,t),o=p7(e.validation_flags,t,a);await r(e.id,{validation_flags:o});};var $v=Rt.createContext(null);function hP(){let e=Rt.useContext($v);if(!e)throw new Error("useHoverInfo must be used within a HoverInfoContext.Provider");return e}var g7=e=>{if(e)try{let t=parseISO(e);return isValid(t)?t:void 0}catch{return}},yP=new WeakMap;function y7(e,t){if(!e||!t)return;let r=yP.get(e);r||(r=new Map,yP.set(e,r));let n=r.get(t);if(n)return n;let a=$c(e,t);if(!a)return;let o=!!(a&&Xp(a)),i=ao(a,e),s=!!i.nullable,l=i.schema,c={rawProperty:a,nullable:s,isValidProp:o,isObject:l?.type==="object",isArray:l?.type==="array",isText:l?.type==="string",isEnum:!!l?.enum,isNumber:l?.type==="number",isFloat:l?.type==="float",isInteger:l?.type==="integer",isDate:l?.format==="date",isDateTime:l?.format==="date-time",isIsoTime:l?.format==="iso-time",isBoolean:l?.type==="boolean",propertyEnumVals:l?.enum??[]};return r.set(t,c),c}function Iv({className:e,disabled:t=false,isReferenceSheet:r=false,...n}){let a=useRef(null),o=l=>{},i=()=>{t||a.current?.focus();},s=l=>{(l.key==="Enter"||l.key==="Escape")&&(a.current?.blur(),l.preventDefault());};return jsx(Ze,{...n,className:R("cursor-default focus:cursor-text border-0 disabled:opacity-100 disabled:text-inherit",e),onKeyDown:s,onSubmit:()=>a.current?.blur(),ref:a,onMouseDown:o,onClick:l=>{document.activeElement===a.current&&l.stopPropagation(),n.onClick?.(l);},onDoubleClick:i,disabled:t})}function v7({className:e,disabled:t=false,isReferenceSheet:r=false,...n}){let a=useRef(null),[o,i]=useState(false),s=g=>{},l=()=>{t||a.current?.focus();},c=g=>{(g.key==="Enter"||g.key==="Escape")&&(a.current?.blur(),g.preventDefault());};return jsx(oN,{...n,className:R("cursor-default focus:cursor-text",e),onKeyDown:c,onSubmit:()=>a.current?.blur(),ref:a,onMouseDown:s,onClick:g=>{document.activeElement===a.current&&g.stopPropagation(),n.onClick?.(g);},onDoubleClick:l,readOnly:t})}function b7(e){let{docId:t,filename:r,fileType:n,lastModified:a,_flat_similarities:o,_full_similarities:i,_similarity:s,_aligned_flat_similarities:l,_aligned_full_similarities:c,_aligned_similarity:u,_flat_reference_elements:d,_aligned_flat_reference_elements:g,...f}=e;return f}function vP(e,t){let r=t?.$defs||{},n=e?.$defs||{};return {...e,$defs:{...r,...n}}}function Fv(e){let {row:t,rowDistanceData:r,...n}=e,{pathInfo:a,similarityType:o,keyValue:i,cellColorState:s}=e,l=a?.idx?KE(i,a?.idx):void 0,c;if(s==="consensus"){let d=t.original?.prediction_data?.metadata?.likelihoods;if(d&&l){let g=VC(d,l);Pr(d,l)!==void 0&&(c=g);}}else if((s==="similarity"||s==="mismatch")&&l&&r)if(o==="aligned"){let d=Pr(r.aligned_per_element_similarity||{},l);c=typeof d=="number"?d:d&&typeof d=="object"?d.aligned_similarity:void 0,r.aligned_flat_reference_elements?.[l];}else {let d=Pr(r.per_element_similarity||{},l);c=typeof d=="number"?d:d&&typeof d=="object"?d._similarity:void 0,r.flat_reference_elements?.[l];}return {...n,actualKey:l,row:t,cellScore:c}}var Mv=Rt.memo(e=>{let{hoverInfo:t,setHoverInfo:r}=hP(),{actualKey:n,schema:a,docId:o,cellColorState:i,setOpenPopover:s,openPopover:l,onGroundTruthDataChange:c,currentIterationId:u,cellScore:d,row:g}=Fv(e),f=br(u),[h,m]=useState(null),[p,v]=useState(false),[y,x]=useState(false),[w,_]=useState(false),E=e.pathInfo?.value;n==="sum_amounts"&&console.log("[DATA CELL] sum_amounts debug:",{actualKey:n,value:E,pathInfo:e.pathInfo,docId:o,rawRowData:g.original});let[C,P]=useState(void 0),T=Rt.useCallback(te=>{try{return JSON.stringify(te)}catch{return String(te)}},[]),N=Rt.useCallback(te=>te==null||te===""?null:te,[]),S=C!==void 0?C:E;useEffect(()=>{let te=Be=>{let oe=Be?.detail;oe&&oe.docId===o&&oe.fieldPath===n&&P(oe.value);};return window.addEventListener("retab:optimistic-update",te),()=>{window.removeEventListener("retab:optimistic-update",te);}},[o,n]);let[b,k]=useState(E!=null?String(E):""),D=Mo(e.columnWidth);e.keyValue.endsWith("__delete")&&(D=50);let O=t?.docId===e.docId&&t?.fieldPath===n,$=Nm(function(te){if(!n||!j)return;let Be=g.original.prediction_data?.prediction??{},oe=Pr(Be,n),wt=N(oe),Lt=N(te),At=N(E);if(oe===te||T(wt)===T(Lt)||T(At)===T(Lt))return;let vl=Ys(Be,n.split("."),te);c(o,vl),P(te);}),A=Nm(function(te){if(n){let Be=te;if(z&&z.format&&typeof te=="string")try{let oe={type:"object",properties:{[n.split(".").pop()]:z}};Be=pn({[n.split(".").pop()]:te},oe)[n.split(".").pop()];}catch(oe){console.warn(`autoFormatDateTimeFields validation failed for ${n}:`,oe);}$(Be);}}),F=Nm(te=>{if(n){let Be=te.currentTarget.getBoundingClientRect();e.onCellHoverStart?.({docId:o,fieldPath:n,rect:Be});}}),H=e.cellColorState==="none"||!e.cellColorState||d===void 0?"transparent":e.cellColorState==="consensus"?P0(Zl,d,Xl,yN):e.cellColorState==="mismatch"?Op(d):P0(Po,d,To,vN),L={width:`${D}px`,minWidth:`${D}px`,backgroundColorHover:H,backgroundColor:H,userSelect:"none"};useEffect(()=>{k(E!=null?String(E):"");},[E]),useEffect(()=>{if(C!==void 0){let te=N(E),Be=N(C);T(te)===T(Be)&&P(void 0);}},[E,C,N,T]);let Q=n?y7(a,n):void 0,z=Q?.rawProperty,ae=!!(z&&z["X-ComputedField"]),M=!!(z&&z["X-FunctionField"]),j=(e.allowEditing||u.includes("dataset")||u.includes("hil"))&&!ae&&!M,ue=!!Q?.nullable,ie=!!Q?.isValidProp,Ce=!!Q?.isObject,Te=!!Q?.isArray,Je=!!Q?.isEnum,vt=!!Q?.isNumber,gt=!!Q?.isText,bt=!!Q?.isFloat,We=!!Q?.isInteger,ke=!!Q?.isDate,be=!!Q?.isDateTime,re=!!Q?.isIsoTime,me=!!Q?.isBoolean,ye=te=>{if(n){let Be=te;if(z&&z.type==="object"&&z.properties)try{Be=pn(te,z);}catch(oe){console.warn(`autoFormatDateTimeFields validation failed for object ${n}:`,oe);}$(Be),s(null);}},ge=te=>{if(n){let Be=te;if(z&&z.type==="array"&&z.items)try{Be=pn(te,z);}catch(oe){console.warn(`autoFormatDateTimeFields validation failed for array ${n}:`,oe);}$(Be),s(null);}},Z=i==="similarity"?"similarity":i==="consensus"?"consensus":i==="mismatch"?"mismatch":"none",[W,ee]=useState(void 0),V=(O||p||y||w)&&j,Re=n?Nd(e.validationFlags,n):void 0,Ee=u.includes("dataset")&&!!Re,$e=ae,nn=M,Ln=()=>M?S===true?"border-green-500 border bg-green-50":S===false?"border-red-500 border bg-red-50":S==null?"border-yellow-500 border bg-yellow-50":"border-green-500 border bg-green-50":"",an=()=>ae?me?S===true?"border-green-500 border bg-green-50":S===false?"border-red-500 border bg-red-50":S==null?"border-yellow-500 border bg-yellow-50":"border-green-500 border bg-green-50":"bg-blue-50":"";return useEffect(()=>{ee(g7(b));},[b]),ie?jsx(Ct,{"data-field-path":n,className:` ${f.border} relative border-b border-r border-t-0 border-l-0 p-0 m-0 select-none`,onMouseLeave:()=>{y||w||p||e.onCellHoverEnd?.();},onMouseEnter:te=>{F(te);},style:L,children:jsx("div",{className:`focus-within:overflow-visible ${Ee?"border-green-500 border bg-green-50":nn?Ln():$e?an():""} ${O?"border-blue-500 border w-full h-full":"w-full h-full"} `,children:Ce?jsxs(Ht,{open:l===n,onOpenChange:te=>{console.log("[Object Popover] onOpenChange:",{open:te,actualKey:n,isEditableReference:j}),te?n&&s(n):s(null);},children:[jsx(Jt,{asChild:true,children:jsx("button",{className:"h-full w-full px-1 overflow-hidden justify-start text-3xs select-none text-inherit",children:S?jsx("div",{className:"truncate max-w-[80px] text-left ",children:JSON.stringify(b7(S))}):jsx("div",{className:"truncate max-w-[80px] text-left text-muted-foreground",children:`Edit ${z?.title||n}`})})}),jsx(Wt,{className:"w-96 p-4 m-0 rounded-none",align:"start",side:"top",sideOffset:0,alignOffset:-1,children:l===n&&z&&jsx(pP,{disabled:!j,isOpen:l===n,property:{...vP(z,a),additionalProperties:true},currentValue:S,onSubmit:ye,likelihoods:{},scalarValueType:Z,setSourcesFieldPath:te=>{if(!te){r(null);return}if(n){let Be=te===n||te.startsWith(n+".")?te:`${n}.${te}`;r({docId:e.docId,fieldPath:Be,rect:new DOMRect});}else r({docId:e.docId,fieldPath:te,rect:new DOMRect});},currentIterationId:u})})]}):Te?jsxs(Ht,{open:l===n,onOpenChange:te=>{te?n&&s(n):s(null);},children:[jsx(Jt,{asChild:true,children:jsx("button",{className:"h-full w-full px-1 overflow-hidden justify-start text-3xs select-none text-inherit",children:S?jsx("div",{className:"truncate max-w-[80px] text-left ",children:Array.isArray(S)?`[${S.length} items]`:JSON.stringify(S)}):jsx("div",{className:"truncate max-w-[80px] text-left text-muted-foreground",children:`${z?.title||n}`})})}),jsx(Wt,{className:"w-96 p-4 m-0 rounded-none",align:"start",side:"top",sideOffset:0,alignOffset:-1,children:l===n&&z&&jsx(mP,{name:n,disabled:!j,property:vP(z,a),currentValue:S,onSubmit:ge,likelihoods:{},scalarValueType:Z,setSourcesFieldPath:te=>{if(!te){r(null);return}r({docId:e.docId,fieldPath:te,rect:new DOMRect});},currentIterationId:u})})]}):me?jsx("div",{className:"h-full flex items-center justify-center py-1",children:jsx(No,{checked:!!S,disabled:!j,onCheckedChange:te=>{j&&A(te);},onFocus:()=>{m(`${o}:${n}`),v(true);},onBlur:()=>{m(null),v(false);},className:"disabled:opacity-100 rounded-[4px]"})}):Je?V?jsxs(Cs,{onOpenChange:te=>{x(te),te?(m(`${o}:${n}`),v(true)):(m(null),v(false));},value:S==null?"__null__":String(S),disabled:!j,onValueChange:te=>{if(te==="__null__"&&ue)A(null);else if(We){let Be=parseInt(te,10);A(Number.isNaN(Be)?null:Be);}else if(bt){let Be=parseFloat(te);A(Number.isNaN(Be)?null:Be);}else A(te);},children:[jsx(Ps,{className:R("h-6 px-2 rounded-none shadow-none text-3xs text-inherit w-full border-none theme.headerText","disabled:opacity-100"),onFocus:()=>{m(`${o}:${n}`),v(true);},onBlur:()=>{y||(m(null),v(false));},children:jsx(Es,{placeholder:ue?"Select...":void 0})}),jsxs(Ts,{position:"popper",className:"z-[60]",children:[ue&&jsx(Wn,{value:"__null__",className:"text-3xs text-muted-foreground",children:jsx("em",{children:"No selection"})},"__null__"),(Q?.propertyEnumVals??[]).filter(te=>te!=null&&!(typeof te=="string"&&te==="")).map(te=>jsx(Wn,{value:String(te),className:"text-3xs",children:String(te)},String(te)))]})]},`${n}-${E}`):jsx("div",{className:"h-full w-full px-2 py-2 text-3xs flex items-start truncate",children:S==null||S==="__null__"?"\u2014":String(S)}):ke?V?jsxs(Ht,{open:w,onOpenChange:te=>{_(te),te?(m(`${o}:${n}`),v(true)):(m(null),v(false));},children:[jsx(Jt,{asChild:true,children:jsxs(K,{variant:"ghost",disabled:!j,className:R("h-full hover:bg-transparent w-full justify-start text-left font-normal px-2 py-0 rounded-none shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 !text-3xs border-0 text-inherit",!S&&"text-muted-foreground","disabled:opacity-100",h===`${o}:${n}`?"absolute top-0 left-0 z-10 shadow-md":""),onClick:()=>{m(`${o}:${n}`),v(true);},children:[W?format(W,"PP"):jsx("span",{className:"text-muted-foreground",children:"Pick a date"}),jsx(CalendarIcon,{className:"ml-auto h-4 w-4 opacity-50"})]})}),jsx(Wt,{className:"z-50 w-auto p-0",align:"start",side:"bottom",sideOffset:0,avoidCollisions:false,updatePositionStrategy:"always",children:jsx(Co,{className:"",mode:"single",selected:W,defaultMonth:W,onSelect:te=>{if(ee(te),te){let Be=ld(te),oe=Zr(Be,"2000-01-01");A(oe||null);}else A(null);},onDayClick:te=>{if(!te)return;ee(te);let Be=ld(te),oe=Zr(Be,"2000-01-01");A(oe||null),_(false),m(null),v(false);}})})]}):jsx("div",{className:"h-full w-full px-2 py-2 text-3xs flex items-center truncate",children:(()=>{try{let te=parseISO(b||""),Be=new Date(te);return isNaN(Be.getTime())?jsx("span",{className:"text-gray-300",children:"Pick a date"}):format(Be,"PP")}catch{return "Invalid date"}})()}):re?V?jsx(Iv,{type:"time",value:sd(b||""),onChange:te=>{k(te.target.value);},onBlur:te=>{let Be=b;b&&/^\d{1,2}:\d{2}$/.test(b)&&(Be=b+":00",k(Be));let oe=Zr(Be,"00:00");A(oe||null),k(oe||""),m(null),v(false);},onFocus:()=>{m(`${o}:${n}`),v(true);},disabled:!j,className:R("h-full px-2 py-0 rounded-none shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 !text-3xs",!S&&"text-muted-foreground",h===`${o}:${n}`?"absolute top-0 left-0 z-10 ":"")}):jsx("div",{className:"h-full w-full px-2 py-2 text-3xs flex items-center truncate",children:sd(b||"")}):be?V?jsx(Iv,{type:"datetime-local",value:id(b||""),onChange:te=>{k(te.target.value);},onFocus:()=>{m(`${o}:${n}`),v(true);},onBlur:()=>{let te=Zr(b,"2000-01-01T00:00:00");A(te||null),m(null),v(false);},disabled:!j,className:`h-full px-2 py-0 rounded-none shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 !text-3xs ${h===`${o}:${n}`?"absolute top-0 left-0 z-10 bg-white ":""}`}):jsx("div",{className:"h-full w-full px-2 py-0 text-3xs flex items-center truncate",children:id(b||"")}):vt||We?V?jsx(Iv,{type:"number",value:b??null,onChange:te=>{let Be=We?parseInt(te.target.value):parseFloat(te.target.value);k(isNaN(Be)?"":Be.toString());},onFocus:()=>{m(`${o}:${n}`),v(true);},onBlur:()=>{let te=We?parseInt(b):parseFloat(b);A(isNaN(te)?null:te),m(null),v(false);},disabled:!j,className:`h-full px-2 py-0 rounded-none shadow-none focus-visible:ring-0 !text-3xs ${h===`${o}:${n}`?"absolute top-0 left-0 z-10":""}`}):jsx("div",{className:"h-full w-full px-2 py-2 text-3xs flex items-center truncate",children:b??"\u2014"}):gt?jsx(v7,{type:"text",value:b??null,onChange:te=>{k(te.target.value);},onBlur:te=>{A(b||null),m(null),v(false);},onFocus:()=>{m(`${o}:${n}`),v(true);},disabled:!j,className:R("h-full px-2 py-2 rounded-none shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 !text-3xs w-full",!S&&"text-muted-foreground",h===`${o}:${n}`?"absolute top-[1px] left-[1px] z-10 bg-white shadow-md outline-1 outline-blue-500 h-64 min-w-[200px]":""),style:{resize:"none"}}):jsx("div",{className:`h-full w-full px-2 py-2 text-3xs flex items-start truncate ${f.verticalLine}`,children:S!=null?String(S):""})})},n):jsx(Ct,{"data-field-path":n,className:`relative ${f.verticalLine} cursor-not-allowed`,style:{width:`${D}px`,minWidth:`${D}px`}},n)},(e,t)=>{let r=Fv(e),n=Fv(t);return Tv(r,n,{deep:["pathInfo.idx"]})});Mv.displayName="DataCell";var Lv=Rt__default.memo(({row:e,columns:t,schema:r,tableAndPaths:n,visibleKeys:a,rowCount:o,onUpdateDocument:i,editMode:s,allowEditing:l=true,onCellHoverStart:c,onCellHoverEnd:u,cellColorState:d="none",distanceData:g})=>{let f=Rt__default.useRef(null);if(f.current){let E=[];f.current.row!==e&&E.push("row"),f.current.columns!==t&&E.push("columns"),f.current.schema!==r&&E.push("schema"),f.current.tableAndPaths!==n&&E.push("tableAndPaths"),f.current.visibleKeys!==a&&E.push("visibleKeys"),f.current.rowCount!==o&&E.push("rowCount"),f.current.onUpdateDocument!==i&&E.push("onUpdateDocument"),f.current.editMode!==s&&E.push("editMode"),console.log("[SingleFileFormRow] Rendering - Props that changed:",E,{documentId:e.original.id,rowCount:o});}else console.log("[SingleFileFormRow] Rendering - Initial render",{documentId:e.original.id,rowCount:o});f.current={row:e,columns:t,schema:r,tableAndPaths:n,visibleKeys:a,rowCount:o,onUpdateDocument:i,editMode:s},console.log("[SingleFileFormRow] Rendering",{documentId:e.original.id,rowCount:o});let{rowHeight:h,columnWidth:m}=Ac(),p=br("single-file"),{table:v,paths:y}=n,x=e.original.id;useEffect(()=>{console.log("[SingleFileFormRow] Effect triggered - props changed",{documentId:x,rowCount:o,visibleKeys:a,visibleKeysRef:a,visibleKeysCount:a.length,rowRef:e,columnsRef:t,schemaRef:r,tableAndPathsRef:n,onUpdateDocumentRef:i});},[x,o,a,e,t,r,n,i]);let w=async(E,C)=>{console.log("[SingleFileFormRow] handleDataChange called",{docId:E,value:C}),i&&(console.log("[SingleFileFormRow] Calling onUpdateDocument"),await i({prediction_data:{prediction:C}}));};useMemo(()=>({width:"50px",minWidth:"50px",height:`${el(h)}px`,minHeight:`${el(h)}px`}),[h]);return jsx(Fragment,{children:Array(o).fill(0).map((E,C)=>jsx(Vr,{className:`flex border-b-0 ${p.border} ${p.tableRowBg} w-full`,style:{height:`${el(h)}px`,minHeight:`${el(h)}px`,minWidth:"100%"},children:a.map((P,T)=>{let N=y[C]?.[T];return jsx(Mv,{keyValue:P,rowIdx:C,colIdx:T,pathInfo:N,schema:r,row:e,index:0,docId:x,cellColorState:d,columnWidth:m,setOpenPopover:()=>{},openPopover:null,onGroundTruthDataChange:w,currentIterationId:"single-file",similarityType:"aligned",validationFlags:{},allowEditing:l,onCellHoverStart:c,onCellHoverEnd:u,rowDistanceData:g},`${P}-${C}`)})},`row-${C}`))})});Lv.displayName="SingleFileFormRow";var Bv=Rt.createContext(null);function _P(){return Rt.useContext(Bv)}var Lo={sm:{bar:"h-1",tick:"h-1 w-1",text:"text-[10px]",gap:"gap-1",knob:"h-3 w-3"},md:{bar:"h-2",tick:"h-2 w-2",text:"text-xs",gap:"gap-1.5",knob:"h-4 w-4"},lg:{bar:"h-3",tick:"h-3 w-3",text:"text-sm",gap:"gap-2",knob:"h-5 w-5"}};cva("relative w-full rounded-full overflow-hidden",{variants:{size:{sm:Lo.sm.bar,md:Lo.md.bar,lg:Lo.lg.bar}},defaultVariants:{size:"md"}});function N7(e,t,r=1,n=120){let a=Array.from({length:n},(s,l)=>{let c=l/(n-1),u=Na(e,c*r,t),d=c*r*100;return `${u} ${d}%`}).join(", "),o=Na(e,r,t),i=`${o} ${r*100}%, ${o} 100%`;return `linear-gradient(to right, ${a}, ${i})`}var C7=({colorState:e,className:t,size:r="md",value:n})=>{let a=e==="consensus",o=a?Zl:Po,i=a?Xl:To,s=120;`linear-gradient(to right, ${Array.from({length:s},(v,y)=>Na(o,y/(s-1),i)).map((v,y)=>`${v} ${y*100/(s-1)}%`).join(", ")})`;let u=.4,g=`linear-gradient(to right, ${Array.from({length:s},(v,y)=>Na(o,y/(s-1),i,u)).map((v,y)=>`${v} ${y*100/(s-1)}%`).join(", ")})`,f={low:"Low",high:"High"},h=n!==void 0?Math.min(Math.max(n,0),1):1,m=h.toFixed(2),p=N7(o,i,h);return jsxs("div",{className:R("flex flex-col",Lo[r].gap,t),children:[jsxs("div",{className:"flex w-full items-center justify-between",children:[jsx("span",{className:R("text-black font-medium",Lo[r].text),children:"Score"}),jsx("span",{className:R("text-muted-foreground font-medium p-1 border rounded-md ring ring-gray-100",Lo[r].text),style:{borderColor:Na(o,n||0,i)},children:m})]}),jsx("div",{className:"w-full relative",children:jsxs(Mm.Root,{"data-slot":"progress",className:R("h-2 w-full overflow-hidden rounded-full",t),style:{backgroundImage:g},value:h!==void 0?h*100:void 0,max:100,children:[jsx(Mm.Indicator,{"data-slot":"progress-indicator",className:"h-full transition-all relative",style:{width:`${h*100}%`,backgroundImage:p}}),n!==void 0&&jsx("div",{"aria-hidden":true,className:R("pointer-events-none absolute top-1/2 -translate-y-1/2 -translate-x-1/2 z-10 rounded-full border bg-background ring-1 ring-border shadow-sm",Lo[r].knob),style:{left:`${h*100}%`}})]})}),jsxs("div",{className:"flex w-full items-center justify-between",children:[jsx("span",{className:R("text-muted-foreground font-normal",Lo[r].text),children:f.low}),jsx("span",{className:R("text-muted-foreground font-normal",Lo[r].text),children:f.high})]})]})},zv=C7;function kn({className:e,...t}){return jsx("div",{"data-slot":"card",className:R("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Rn({className:e,...t}){return jsx("div",{"data-slot":"card-header",className:R("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function On({className:e,...t}){return jsx("div",{"data-slot":"card-title",className:R("leading-none font-semibold",e),...t})}function Dn({className:e,...t}){return jsx("div",{"data-slot":"card-content",className:R("px-6",e),...t})}var Uv=({items:e,title:t})=>jsxs(kn,{className:"border-none shadow-none p-0 gap-0",children:[jsx(Rn,{className:"p-0",children:jsx(On,{children:jsx("div",{className:"flex items-center gap-2 text-gray-700",children:jsx("div",{className:"text-xs font-medium uppercase tracking-wide",children:t||"Computation Breakdown"})})})}),jsx(Dn,{className:"p-0",children:e.length>0?jsx("ul",{className:"text-xs list-disc pl-5",children:e.map((r,n)=>jsx("li",{className:"mb-1",children:jsx("div",{className:"flex flex-wrap items-center gap-x-1",children:jsx("code",{className:"text-[10px] break-all",children:jsx(fr,{children:r.tokens.map((a,o)=>{if(a.type==="number"){let i=String(a.value);return jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("span",{className:"px-[1px] text-xs cursor-pointer select-text underline text-blue-800 break-all",children:i})}),jsx(ze,{side:"top",className:"max-w-xs break-words",children:jsx("p",{className:"text-xs",children:a.sourcePath||"literal"})})]},o)}return jsx("span",{className:"break-all",children:String(a.value)},o)})})})})},n))}):jsx("div",{className:"text-xs text-muted-foreground",children:"No breakdown available for this field."})})]});Uv.displayName="ComputationBreakdown";function O7(e,t){if(!e)return {s:void 0,nullable:false};try{if(t){let{schema:n,nullable:a}=ao(e,t);return {s:n,nullable:a}}}catch{}let r=Array.isArray(e.type)&&e.type.includes("null");return {s:e,nullable:r}}var PP=({schema:e,rootSchema:t,value:r,onChange:n,disabled:a,className:o})=>{let {s:i,nullable:s}=O7(e||void 0,t),l=_P(),[c,u]=Rt.useState(false);i?.type;let g=i?.format,f=Array.isArray(i?.enum)&&(i?.enum).length>0;if(i?.type==="boolean")return jsx("div",{className:"h-full flex items-center",children:jsx(No,{checked:!!r,onCheckedChange:h=>n(!!h),className:R("disabled:opacity-100",o),disabled:a})});if(f){let h=i.enum.filter(p=>p!==""),m=r==null?"__null__":String(r);return jsxs(Cs,{value:m,onValueChange:p=>{n(p==="__null__"&&s?null:p);},disabled:a,onOpenChange:p=>{l?.setPortalOpen(p);},children:[jsx(Ps,{className:R("h-8 px-2 rounded-none shadow-none text-xs w-full border",o),children:jsx(Es,{placeholder:s?"Select...":void 0})}),jsxs(Ts,{children:[s&&jsx(Wn,{value:"__null__",className:"text-xs text-muted-foreground",children:jsx("em",{children:"No selection"})},"__null__"),h.map(p=>jsx(Wn,{value:String(p),className:"text-xs",children:String(p)},String(p)))]})]})}if(i?.type==="string"&&g==="date"){let h=typeof r=="string"?r:"";return jsx("div",{className:R("w-full",o),children:jsxs(Ht,{open:c,onOpenChange:m=>{u(m),l?.setPortalOpen(m);},children:[jsx(Jt,{asChild:true,children:jsxs(K,{variant:"outline",disabled:a,"data-empty":!h,className:R("data-[empty=true]:text-muted-foreground w-full justify-start text-left font-normal px-2 py-1 rounded-none shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 !text-xs"),children:[jsx(CalendarIcon,{className:"mr-2 h-4 w-4"}),(()=>{try{let m=Dp(h||""),p=new Date(m);return isNaN(p.getTime())?jsx("span",{children:"Pick a date"}):p.toLocaleDateString()}catch{return jsx("span",{children:"Pick a date"})}})()]})}),jsx(Wt,{className:"w-auto p-0",align:"start",children:jsx(Co,{mode:"single",defaultMonth:(()=>{try{let m=Dp(h||""),p=new Date(m);return isNaN(p.getTime())?void 0:p}catch{return}})(),selected:(()=>{try{let m=Dp(h||""),p=new Date(m);return isNaN(p.getTime())?void 0:p}catch{return}})(),onSelect:m=>{if(m){let p=ld(m),v=Zr(p,"2000-01-01");n(v||null);}else n(null);u(false),l?.setPortalOpen(false);}})})]})})}if(i?.type==="string"&&g==="iso-time")return jsx(Ze,{type:"time",value:sd((typeof r=="string"?r:"")||""),onChange:m=>{let p=m.target.value;p&&/^\d{1,2}:\d{2}$/.test(p)&&(p=p+":00");let v=Zr(p,"00:00");n(v||null);},disabled:a,className:R("w-full px-2 py-1 rounded-none shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 !text-xs",o)});if(i?.type==="string"&&g==="date-time")return jsx(Ze,{type:"datetime-local",value:id((typeof r=="string"?r:"")||""),onChange:m=>{let p=Zr(m.target.value,"2000-01-01T00:00:00");n(p||null);},disabled:a,className:R("w-full px-2 py-1 rounded-none shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 !text-xs",o)});if(i?.type==="number"||i?.type==="integer"){let h=i?.type==="integer",m=r==null?"":String(r);return jsx(Ze,{type:"number",value:m,onChange:p=>{let v=h?parseInt(p.target.value):parseFloat(p.target.value);n(isNaN(v)?null:v);},disabled:a,className:R("w-full px-2 py-1 rounded-none shadow-none focus-visible:ring-0 focus-visible:ring-offset-0 !text-xs",o)})}if(i?.type==="object"||i?.type==="array"){let h=(()=>{try{return typeof r=="string"?r:JSON.stringify(r??null,null,2)}catch{return String(r??"")}})();return jsx(pr,{className:R("w-full h-40 p-2 !text-xs border rounded-md resize-none bg-gray-50",o),value:h,onChange:m=>{let p=m.target.value;try{let v=JSON.parse(p),y=pn(v,i);n(y);}catch{n(p);}},disabled:a})}return jsx(pr,{className:R("w-full h-24 p-2 !text-xs border rounded-md resize-none bg-gray-50",o),value:r??"",onChange:h=>n(h.target.value),disabled:a})};PP.displayName="TypeAdaptedInput";function TP(e,t,r=e){let n=t.split(".");for(let a=0;a<n.length;){let o=n[a];if(r.$ref&&(r=e.$defs[r.$ref.replace("#/$defs/","")]),"anyOf"in r){for(let i of r.anyOf){let s=TP(e,n.slice(a).join("."),i);if(s)return s}return null}if(r.type==="array")r=r.items,a+1<n.length&&(n[a+1]==="*"||!isNaN(parseInt(n[a+1])))&&(a+=1);else if(r.type==="object"&&o in r.properties)r=r.properties[o],a+=1;else if(o==="*"||!isNaN(parseInt(o)))a+=1;else return console.log("ERROR",{schema:e,path:t,currentSchema:r,segment:o}),null}return r.$ref&&(r=e.$defs[r.$ref.replace("#/$defs/","")]),r}var CP=e=>e.replace(/\.\d+\./g,".*.").replace(/\.\d+$/,".*"),qv=({similarityType:e,document:t,selectedFieldPath:r,currentIterationId:n,updateDocument:a,jsonSchema:o,rowDistanceData:i,datasetContext:s,onGroundTruthChange:l})=>{let{setActiveView:c,setMetricsSelection:u}=Ni(),d=Rt.useCallback(async re=>{if(l){l(r,re);return}if(!s){console.error("Dataset context not available"),toast.error("Dataset context not available");return}if(!s.updateDatasetDocument||!s.datasetDocuments){console.error("Dataset context not available"),toast.error("Dataset context not available");return}try{let me=i?.key_mappings?.[r]??r;console.log("mappedDatasetPath",me);let ge=t.dataset_document_id;if(!ge){console.error("No dataset_document_id found on iteration document"),toast.error("Cannot update dataset value");return}let Z=s.datasetDocuments.find(V=>V.id===ge);if(!Z){console.error("Dataset document not found"),toast.error("Dataset document not found");return}let W=Z.prediction_data?.prediction||{},ee=Ys(W,me.split("."),re);console.log("currentAnnotation",W),console.log("updatedAnnotation",ee),await s.updateDatasetDocument(ge,{prediction_data:{prediction:ee,metadata:Z.prediction_data?.metadata||{}}}),s.invalidateDistances&&t?.id&&s.invalidateDistances(t?.id),toast.success("Dataset value updated");}catch(me){console.error("Failed to update dataset value:",me),toast.error("Failed to update dataset value");}},[r,t?.id,s,l]),[g,f]=Rt.useState(false),[h,m]=Rt.useState(""),[p,v]=Rt.useState(false),[y,x]=Rt.useState(null),{project:w}=Fr(),{showInfoPanel:_,setShowInfoPanel:E}=Ni();Rt.useEffect(()=>{f(false),m(""),v(false),x(null);},[t?.id,r]);let C=(re,me)=>{let ye=me.split("."),ge=-1;for(let V=0;V<ye.length;V++)isNaN(parseInt(ye[V]))||(ge=V);if(ge===-1)return re;let Z=ye.slice(0,ge),W=parseInt(ye[ge]),ee=(V,Re,Ee)=>{if(Re.length===0){if(!Array.isArray(V)||Ee<0||Ee>=V.length)return V;let te=V.slice();return te.splice(Ee,1),te}let[$e,...nn]=Re;if(!isNaN(parseInt($e))){let te=Number($e),Be=Array.isArray(V)?V:[],oe=Be.slice();return oe[te]=ee(Be[te],nn,Ee),oe}let an=V&&typeof V=="object"&&!Array.isArray(V)?V:{};return {...an,[$e]:ee(an[$e],nn,Ee)}};return ee(re,Z,W)},P=Rt.useCallback(()=>{if(!t)return;let re=t.prediction_data?.prediction||{},me=C(re,r),ye=t.id??t.id;a(ye,{annotation:me},{annotation:re}).then(()=>{toast.success("Row deleted");}).catch(ge=>{console.error("Failed to delete row:",ge),toast.error("Failed to delete row");});},[r,t?.id,a]),T=n.includes("dataset"),N=n.includes("single-file"),S=!!r&&r.split(".").some(re=>re==="*"||!isNaN(parseInt(re))),b=t?.prediction_data?.metadata?.likelihoods||{},k=r?Pr(t?.prediction_data.prediction,r):void 0,D=JSON.stringify(k),O=typeof r=="string"?Pr(b,r):void 0,$=false,F=0,X,H=t?.validation_flags||{},L=r?Nd(H,r):void 0;Rt.useEffect(()=>{let re=async me=>{let ye=typeof navigator<"u"&&navigator.platform?.toLowerCase?.().includes("mac"),ge=(me.key||"").toLowerCase(),Z=ye?me.metaKey&&ge==="e":me.ctrlKey&&ge==="e",W=(ye?me.metaKey:me.ctrlKey)&&(ge==="delete"||ge==="del"||ge==="backspace");if(r&&t){if(W){if(!n.includes("dataset")||!S)return;me.preventDefault(),me.stopPropagation(),P();return}if(Z){if(me.preventDefault(),me.stopPropagation(),n.includes("dataset"))Av(t,r??"",a);else if(n.includes("iteration")){if(!s){console.error("Dataset context not available"),toast.error("Dataset context not available");return}if(!s.updateDatasetDocument||!s.datasetDocuments){console.error("Dataset context not available"),toast.error("Dataset context not available");return}try{let ee=r?Pr(t?.prediction_data.prediction,r):void 0,Re=t.dataset_document_id;if(!Re){console.error("No dataset_document_id found on iteration document"),toast.error("Cannot update dataset value");return}let Ee=s.datasetDocuments.find(an=>an.id===Re);if(!Ee){console.error("Dataset document not found"),toast.error("Dataset document not found");return}let $e=Ee.prediction_data?.prediction||{},nn=i?.key_mappings?.[r]??r,Ln=Ys($e,nn.split("."),ee);console.log("Reference value before",i?.aligned_flat_reference_elements?.[r]),await s.updateDatasetDocument(Re,{prediction_data:{prediction:Ln,metadata:Ee.prediction_data?.metadata||{}}}),s.invalidateDistances&&t.id&&s.invalidateDistances(t.id),console.log("mappedDatasetPath for {selectedFieldPath}",{selectedFieldPath:r,mappedDatasetPath:nn}),console.log("Current annotation value",Pr($e,nn)),console.log("Updated annotation value",Pr(Ln,nn)),console.log("Reference value after",i?.aligned_flat_reference_elements?.[r]),toast.success("Replaced with extracted value");}catch(ee){console.error("Failed to replace dataset value",ee),toast.error("Failed to replace dataset value");}}}}};return window.addEventListener("keydown",re,true),()=>window.removeEventListener("keydown",re,true)},[n,r,t?.id,t,a,s,P,S]),typeof r=="string"&&n.includes("iteration")&&i&&(e==="aligned"?(F=Pr(i?.aligned_per_element_similarity||{},r),X=i?.aligned_flat_reference_elements?.[r]):(F=Pr(i?.per_element_similarity||{},r),X=i?.flat_reference_elements?.[r]),$=!isNaN(F)&&F!==void 0,X!=null);let Q=JSON.stringify(X),z=t?.prediction_data?.metadata?.consensus_details||[],ae=typeof r=="string"&&r.includes(".")?r.replace(/\.([^.]+)$/,".reasoning___$1"):typeof r=="string"?`reasoning___${r}`:void 0,M=typeof ae=="string"?Pr(t?.prediction_data.prediction,ae):void 0,j=typeof M=="string"?M:void 0,ue=typeof r=="string"?HC(z,r)||[]:[],ie=ue.length>1,Ce=typeof r=="string"&&o?TP(o,i?.key_mappings?.[r]??r):null,Te=(()=>{if(!Ce)return false;let re=Array.isArray(Ce?.type)?Ce.type:null,me=Ce?.anyOf||Ce?.oneOf||Ce?.allOf,ye=!!(re&&re.includes("null")),ge=Array.isArray(me)&&me.some(Z=>Z?.type==="null");return ye||ge})(),Je=!!(Ce&&Ce["X-ComputedField"]===true),vt=n==="builder"?w.draft_config.computation_spec:w.published_config.computation_spec,gt=Rt.useMemo(()=>{if(!Je||typeof r!="string")return [];try{let me=w0(t?.prediction_data.prediction||{},vt).find(W=>W.targetPath===CP(r)),ge=typeof r=="string"?(W=>{let ee=W.split("."),V=[];for(let Re of ee){let Ee=Number(Re);Number.isFinite(Ee)&&String(Ee)===Re?V.length>0?V[V.length-1]=`${V[V.length-1]}[${Ee}]`:V.push(`[${Ee}]`):V.push(Re);}return V.join(".")})(r):void 0,Z=me?.items||[];return ge?Z.filter(W=>W.displayPath===ge):Z}catch(re){return console.error("Failed to compute breakdowns",re),[]}},[Je,t,vt,r]),bt=[];typeof r=="string"&&z&&z.length>0&&z.forEach(re=>{if(re.data&&typeof re.data=="object"){let me=r.split("."),ye;if(me.length===1)ye=`reasoning___${r}`;else {let Z=me.slice(0,-1).join("."),W=me[me.length-1];ye=`${Z}.reasoning___${W}`;}let ge=Pr(re.data,ye);ge&&typeof ge=="string"&&bt.push(ge);}});let We=ie&&bt.length>0,be=[ie,$&&!T,j].filter(Boolean).length+(T?1:0);return !_||!Je&&be===0?null:jsxs("div",{className:"w-[240px]",children:[jsx("div",{className:"bg-gray-100 w-full p-2 border-b border-gray-200 ",children:jsx("div",{className:"flex-1 min-w-0 ",children:jsx("div",{className:"flex items-start justify-between gap-2 w-full flex-col group",children:jsxs("div",{className:"flex items-start justify-between gap-2 w-full",children:[jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("h2",{className:"text-xs font-medium text-gray-900 truncate min-w-0 max-w-full",children:r||"Field"})}),jsx(ze,{side:"top",className:"max-w-xs break-words",children:jsx("p",{className:"text-xs",children:r})})]}),jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("div",{className:"bg-[#969696] opacity-0 group-hover:opacity-100 transition-opacity duration-300 shrink-0 rounded-full w-3 h-3 flex items-center justify-center group",onClick:()=>E(!_),children:jsx("div",{className:"h-[2px] w-[6px] group-hover:bg-[#4D4D4D]"})})}),jsx(ze,{side:"top",className:"max-w-xs break-words",children:jsxs("p",{className:"text-xs",children:["Hide info panel. Reopen with ",typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(navigator.userAgentData?.platform||navigator.userAgent||"")?"\u2318 I":"Ctrl+I"," or click the ",jsx(AppWindowIcon,{className:"inline-block h-3 w-3 -translate-y-[1px]"})," icon in the top right corner."]})})]})]})})})}),(Je||be>0)&&jsxs("div",{className:"max-h-[317px] overflow-y-auto px-2 pt-2 gap-4 flex flex-col pb-3",children:[Je&&jsx(Uv,{items:gt}),!Je&&!ie&&!$&&j&&jsxs(kn,{className:"border-none shadow-none p-0 gap-0",children:[jsx(Rn,{className:"p-0",children:jsx(On,{children:jsxs("div",{className:"flex items-center gap-2 text-gray-700",children:[jsx("div",{className:"text-xs font-medium uppercase tracking-wide",children:"Reasoning"}),jsx(Atom,{className:"h-4 w-4"})]})})}),jsx(Dn,{className:"p-0",children:jsx("div",{className:"text-xs p-1 bg-gray-50 rounded border cursor-pointer",children:jsx("textarea",{className:"font-medium text-gray-700 w-full flex min-h-32 resize-none",value:j,readOnly:true})})})]}),!Je&&!T&&$&&jsxs(Fragment,{children:[jsxs(kn,{className:"border-none shadow-none p-0 gap-0",children:[jsx(Rn,{className:"p-0",children:jsx(On,{children:jsx("div",{children:jsxs("div",{className:"flex items-center justify-between text-gray-800",children:[jsx("div",{className:"flex items-center gap-2",children:jsx("div",{className:"text-xs flex font-medium uppercase tracking-wide",children:"Ground Truth"})}),g&&k!==void 0&&JSON.stringify(k)!==JSON.stringify(y)&&jsx("button",{type:"button",disabled:p,className:"px-2 py-1 text-[10px] rounded-md border hover:bg-gray-50",onClick:()=>{x(k);},children:"Replace by prediction"})]})})})}),jsxs(Dn,{className:"p-0",children:[g?jsxs("div",{className:"space-y-2",onMouseDown:re=>re.stopPropagation(),onPointerDown:re=>re.stopPropagation(),children:[jsx(PP,{schema:Ce,rootSchema:o,value:y,onChange:x,disabled:p}),jsxs("div",{className:"flex items-center justify-between mb-1",children:[Te&&jsx("button",{type:"button",disabled:p,className:"px-2 py-1 text-xs rounded-md border",onClick:()=>{x(null);},children:"Clear"}),jsxs("div",{className:"ml-auto flex items-center gap-2",children:[jsx("button",{disabled:p,className:"px-2 py-1 text-xs rounded-md bg-slate-900 text-white disabled:opacity-50",onClick:async()=>{v(true);try{await d(y),f(!1);}catch(re){console.error("Failed to update dataset value",re);}finally{v(false);}},children:"Save"}),jsx("button",{disabled:p,className:"px-2 py-1 text-xs rounded-md border",onClick:()=>{f(false),m(""),x(X);},children:"Cancel"})]})]})]}):jsx(fr,{children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("div",{className:"text-xs flex flex-col p-1 rounded border transition-colors bg-gray-50 cursor-pointer hover:bg-gray-100",role:"button",tabIndex:0,onClick:re=>{re.preventDefault(),re.stopPropagation(),f(true),x(X);},onMouseDown:re=>re.stopPropagation(),onPointerDown:re=>re.stopPropagation(),onKeyDown:re=>{if(re.key==="Enter"||re.key===" "){re.preventDefault(),f(true);try{let me=typeof X=="string"?X:JSON.stringify(X,null,2);m(me||"");}catch{m(Q);}}},children:jsx("div",{className:"font-medium text-gray-700 max-w-32 truncate flex items-center gap-1 pb-4",children:jsx("span",{className:"truncate",children:Q})})})}),jsx(ze,{children:jsx("p",{children:"Click to edit ground truth value"})})]})}),!N&&jsxs("div",{className:"flex text-[10px] mt-auto ml-auto pt-1 items-center justify-end gap-1 text-xs !text-gray-600",children:[jsxs("span",{className:"flex items-center gap-0.5",children:[jsx("span",{className:"opacity-100 font-light border border-gray-300 rounded-sm px-1 py-0.5",children:typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(navigator.userAgentData?.platform||navigator.userAgent||"")?"\u2318":"CTRL"}),jsx("span",{className:"opacity-100 font-light border border-gray-300 rounded-sm px-1 py-0.5",children:"E"})]}),"Replace with extracted value"]})]})]}),jsxs(kn,{className:"border-none shadow-none p-0 gap-0",children:[jsx(Rn,{className:"p-0 -mb-2",children:jsx(On,{children:jsx("div",{children:jsx("div",{className:"flex items-center gap-2",children:jsx(fr,{children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("div",{className:"",children:jsxs("div",{className:R("flex pt-1 items-center gap-2 text-gray-800",!N&&"cursor-pointer"),children:[jsx("div",{className:"text-xs font-medium uppercase tracking-wide",onClick:()=>{N||(r&&u(CP(r)),c("metrics"));},children:"Similarity"}),jsx(Ruler,{className:"w-4 h-4"})]})})}),jsx(ze,{children:jsx("p",{children:"The ground truth value and the prediction are compared to compute the similarity score."})})]})})})})})}),jsxs(Dn,{className:"p-0",children:[jsx(zv,{colorState:"similarity",size:"sm",value:F,className:"justify-center"}),!N&&jsxs("div",{className:"flex text-[10px] mt-2 items-center justify-end gap-1 text-xs !text-gray-600",children:[jsxs("span",{className:"flex items-center gap-0.5",children:[jsx("span",{className:"opacity-100 font-light border border-gray-300 rounded-sm px-1 py-0.5",children:typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(navigator.userAgentData?.platform||navigator.userAgent||"")?"\u2318":"CTRL"}),jsx("span",{className:"opacity-100 font-light border border-gray-300 rounded-sm px-1 py-0.5",children:"G"})]}),"Open metrics"]})]})]})]}),!Je&&ie&&jsxs(Fragment,{children:[jsxs(kn,{className:"border-none shadow-none p-0 gap-0",children:[jsx(Rn,{className:"p-0",children:jsx(On,{children:jsxs("div",{className:"flex items-center gap-2 text-gray-800",children:[jsx("div",{className:"text-xs flex font-medium uppercase tracking-wide",children:"Consensus"}),jsx(Blend,{className:"w-4 h-4"})]})})}),jsxs(Dn,{className:"p-0",children:[jsx("div",{className:"mb-3",children:jsx(zv,{colorState:"consensus",size:"sm",value:O,className:"justify-center"})}),jsx("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Consensus value:"}),jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("div",{className:"text-xs p-1 bg-gray-50 rounded border cursor-pointer",children:jsx("div",{className:"font-medium text-gray-700 max-w-32 truncate",children:D})})}),jsx(ze,{side:"left",className:"max-w-xs break-words",children:jsxs("p",{className:"text-xs",children:[" ",D," "]})})]})]})]}),jsxs(kn,{className:"border-none shadow-none p-0 gap-0",children:[jsx(Rn,{className:"p-0",children:jsx(On,{children:jsx("div",{className:"text-xs font-normal uppercase tracking-wide text-muted-foreground",children:"Candidates"})})}),jsx(Dn,{className:"p-0",children:jsx(fr,{children:jsx("div",{className:"space-y-1",children:ue.map((re,me)=>{let ye=JSON.stringify(re.data);return jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxs(Me,{children:[jsx(je,{asChild:true,children:jsxs("div",{className:"flex text-xs items-center gap-2 text-muted-foreground",children:[`${me+1}.`,jsx("div",{className:"text-xs p-1 bg-gray-50 rounded border cursor-pointer",children:jsx("div",{className:"font-medium text-gray-700 max-w-24 grow truncate",children:ye})})]})}),jsx(ze,{side:"left",className:"max-w-xs break-words",children:jsxs("p",{className:"text-xs",children:[" ",ye," "]})})]},me),We&&jsx(fr,{children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(Atom,{className:"w-3 h-3 text-muted-foreground cursor-pointer"})}),jsx(ze,{side:"left",className:"max-w-xs break-words",children:jsxs("p",{className:"text-xs",children:[" ",bt[me]," "]})})]})})]},me)})})})})]})]}),!Je&&T&&jsxs(kn,{className:"border-none shadow-none p-0 gap-0",children:[jsx(Rn,{className:"p-0",children:jsx(On,{children:jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[jsx("div",{className:"text-xs font-normal uppercase tracking-wide",children:"Actions"}),jsx(MousePointerClick,{className:"h-4 w-4"})]})})}),jsxs(Dn,{className:"p-0 grid grid-cols-1 gap-1",children:[S&&jsxs(K,{variant:"ghost",className:"font-normal text-xs justify-start w-full",onClick:()=>{P();},children:["Delete row",jsx("div",{className:"flex text-[10px] mt-auto ml-auto items-center justify-end gap-1 text-xs !text-gray-600",children:jsxs("span",{className:"flex items-center gap-0.5",children:[jsx("span",{className:"opacity-100 font-light border border-gray-300 rounded-sm px-1 py-0.5",children:typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(navigator.userAgentData?.platform||navigator.userAgent||"")?"\u2318":"CTRL"}),jsx("span",{className:"opacity-100 font-light border border-gray-300 rounded-sm px-1 py-0.5",children:"Del"})]})})]}),jsxs(K,{variant:"ghost",className:"font-normal text-xs justify-start w-full",children:["Edit cell",jsx("div",{className:"flex text-[10px] ml-auto items-center gap-1 text-xs !text-gray-600 font-light",children:jsx("span",{className:"opacity-100 font-light border border-gray-300 rounded-sm px-1 py-0.5",children:"Click"})})]}),jsxs(K,{variant:"ghost",className:"font-normal text-xs justify-start w-full",onClick:re=>{re.preventDefault(),re.stopPropagation(),Av(t,r,a);},children:[L?"Mark as unverified":"Mark as verified",jsx("div",{className:"flex text-[10px] mt-auto ml-auto items-center justify-end gap-1 text-xs !text-gray-600",children:jsxs("span",{className:"flex items-center gap-0.5",children:[jsx("span",{className:"opacity-100 font-light border border-gray-300 rounded-sm px-1 py-0.5",children:typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(navigator.userAgentData?.platform||navigator.userAgent||"")?"\u2318":"CTRL"}),jsx("span",{className:"opacity-100 font-light border border-gray-300 rounded-sm px-1 py-0.5",children:"E"})]})})]}),jsxs(K,{variant:"ghost",className:"font-normal text-xs justify-start w-full",onClick:re=>{re.preventDefault(),re.stopPropagation(),E(false);},children:["Hide Info Panel",jsx("div",{className:"flex text-[10px] mt-auto ml-auto items-center justify-end gap-1 text-xs !text-gray-600",children:jsxs("span",{className:"flex items-center gap-0.5",children:[jsx("span",{className:"opacity-100 font-light border border-gray-300 rounded-sm px-1 py-0.5",children:typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(navigator.userAgentData?.platform||navigator.userAgent||"")?"\u2318":"CTRL"}),jsx("span",{className:"opacity-100 font-light border border-gray-300 rounded-sm px-1 py-0.5",children:"I"})]})})]})]})]})]})]})};qv.displayName="DataCellPopoverCardContent";var OP=Rt__default.memo(({table:e,columnWidth:t,stopAt:r,setStopAt:n,columns:a,foldAllSignal:o,setFoldAllSignal:i})=>{console.log("[SingleFileTableHeader] Rendering");let s=br("single-extraction"),l=new Set;return jsx(ji,{className:`sticky top-0 z-10 ${s.headerBg}`,children:e.getHeaderGroups().map((c,u)=>jsx(Vr,{className:`flex w-max min-w-full ${s.subHeaderBg} border-b ${s.border}`,children:c.headers.map((d,g)=>{let f=l.has(d.column.id);l.add(d.column.id);function h(p){return p.columns&&p.columns.length>0?p.columns.map(h).reduce((v,y)=>v+y,0):Mo(t)}let m=h(d.column);return f?jsx("th",{className:`shrink-0 ${s.subHeaderBg} text-3xs ${s.headerText} border-r last:border-r-0 ${s.border}`,style:{width:`${m}px`,minWidth:`${m}px`}},g):jsx(Nr,{className:`shrink-0 ${s.headerBg} ${s.headerText} border-r last:border-r-0 p-0 m-0 ${s.border}`,style:{width:`${m}px`,minWidth:`${m}px`,height:"38px"},colSpan:d.colSpan,children:flexRender(d.column.columnDef.header,d.getContext())},g)})},u))})});OP.displayName="SingleFileTableHeader";var Wv=Rt__default.memo(({stopAt:e,setStopAt:t,foldAllSignal:r,setFoldAllSignal:n,columns:a,document:o,schema:i,tableAndPaths:s,visibleKeys:l,rowCount:c,onUpdateDocument:u,editMode:d,allowEditing:g=true,onCellHoverStart:f,cellColorState:h="none",distanceData:m,showHoverCard:p=false,similarityType:v="aligned",onGroundTruthChange:y})=>{let x=Rt__default.useRef(0),w=Rt__default.useRef(null);if(x.current++,w.current){let z=[];w.current.stopAt!==e&&z.push("stopAt"),w.current.setStopAt!==t&&z.push("setStopAt"),w.current.foldAllSignal!==r&&z.push("foldAllSignal"),w.current.setFoldAllSignal!==n&&z.push("setFoldAllSignal"),w.current.columns!==a&&z.push("columns"),w.current.document!==o&&z.push("document"),w.current.schema!==i&&z.push("schema"),w.current.tableAndPaths!==s&&z.push("tableAndPaths"),w.current.visibleKeys!==l&&z.push("visibleKeys"),w.current.rowCount!==c&&z.push("rowCount"),w.current.onUpdateDocument!==u&&z.push("onUpdateDocument"),w.current.editMode!==d&&z.push("editMode"),console.log(`[SingleFileVirtualizedTable] Rendering #${x.current} - Props that changed:`,z);}else console.log(`[SingleFileVirtualizedTable] Rendering #${x.current} - Initial render`);w.current={stopAt:e,setStopAt:t,foldAllSignal:r,setFoldAllSignal:n,columns:a,document:o,schema:i,tableAndPaths:s,visibleKeys:l,rowCount:c,onUpdateDocument:u,editMode:d},console.log(`[SingleFileVirtualizedTable] Rendering #${x.current}`,{columnsRef:a,columnsLength:a.length,documentRef:o,tableAndPathsRef:s,visibleKeysRef:l,visibleKeysLength:l.length});let{rowHeight:_,columnWidth:E}=Ac(),C=br("single-file"),[P,T]=useState(null),N=useRef(null),[S,b]=useState({left:0,top:0}),k=useRef(null),D=useRef(false),[O,$]=useState(false),A=useCallback(z=>{k.current&&(clearTimeout(k.current),k.current=null),!D.current&&(T(z),f?.(z));},[f]),F=useCallback(()=>{k.current&&clearTimeout(k.current),!(D.current||O)&&(k.current=window.setTimeout(()=>{T(null),k.current=null;},10));},[O]);useEffect(()=>{if(!P||!p)return;let z=0,ae=8,M=34,ue=requestAnimationFrame(()=>{let ie=N.current,Ce=ie?.offsetWidth??240,Te=ie?.offsetHeight??200,Je=P.rect.left-z-Ce,vt=P.rect.top-M;vt=Math.max(ae,Math.min(vt,window.innerHeight-Te-ae)),Je<ae&&(Je=P.rect.right+z),b({left:Je,top:vt});});return ()=>cancelAnimationFrame(ue)},[P,p]);let X=useCallback(async()=>{},[]);useEffect(()=>{console.log("[SingleFileVirtualizedTable] Effect triggered - props changed",{rowCount:c,visibleKeys:l,visibleKeysRef:l,visibleKeysCount:l.length,documentId:o.id,documentRef:o,columnsRef:a,tableAndPathsRef:s,schemaRef:i,onUpdateDocumentRef:u});},[c,l,o,a,s,i,u]);let H=useReactTable({data:useMemo(()=>(console.log("[SingleFileVirtualizedTable] data array recomputing",{documentRef:o}),[o]),[o]),columns:a,getCoreRowModel:getCoreRowModel()}),L=c*el(_),Q=l.length*Mo(E);return jsx($v.Provider,{value:{hoverInfo:P,setHoverInfo:T},children:jsx("div",{className:`flex flex-1 min-h-0 min-w-0 relative ${C.tableContainerBg}`,children:jsxs("div",{className:"h-full overflow-auto w-full",children:[p&&P&&jsx("div",{className:"absolute z-40 transition-transform duration-150 ease-out will-change-transform",style:{position:"fixed",left:0,top:0,transform:`translate3d(${S.left}px, ${S.top}px, 0)`},onMouseEnter:()=>{D.current=true,k.current&&(clearTimeout(k.current),k.current=null);},onMouseLeave:()=>{D.current=false,!k.current&&!O&&(k.current=window.setTimeout(()=>{T(null),k.current=null;},120));},children:jsx(Bv.Provider,{value:{setPortalOpen:$},children:jsx("div",{ref:N,className:"p-0 bg-white border border-gray-200 shadow-md rounded-md overflow-hidden",children:jsx(qv,{similarityType:v,document:o,selectedFieldPath:P.fieldPath,currentIterationId:h==="similarity"?"iteration-single-file":"single-file",updateDocument:X,jsonSchema:i,rowDistanceData:m,onGroundTruthChange:y})})})}),jsxs(oo,{className:`relative w-full rounded-none flex flex-col ${C.tableContainerBg}`,style:{minWidth:`${Q}px`,height:`${L}px`},children:[jsx(OP,{table:H,columnWidth:E,stopAt:e,setStopAt:t,columns:a,foldAllSignal:r,setFoldAllSignal:n}),jsx(io,{className:"flex flex-col h-full relative w-full",children:H.getRowModel().rows.map((z,ae)=>jsx(Lv,{row:z,tableAndPaths:s,columns:a,schema:i,visibleKeys:l,rowCount:c,onUpdateDocument:u,editMode:d,allowEditing:g,onCellHoverStart:p?A:f,onCellHoverEnd:p?F:void 0,cellColorState:h,distanceData:m},z.id))})]})]})})})});Wv.displayName="SingleFileVirtualizedTable";var Zv=Rt__default.memo(({document:e,schema:t,columnWidth:r,onUpdateDocument:n,editMode:a="editable",allowEditing:o=true,computationSpec:i,setComputationSpec:s,onCellHoverStart:l,cellColorState:c="none",distanceData:u,showHoverCard:d=false,similarityType:g="aligned",onGroundTruthChange:f})=>{let h=Rt__default.useRef(0),m=Rt__default.useRef(null);if(h.current++,m.current){let b=[];m.current.document!==e&&b.push("document"),m.current.schema!==t&&b.push("schema"),m.current.columnWidth!==r&&b.push("columnWidth"),m.current.onUpdateDocument!==n&&b.push("onUpdateDocument"),m.current.editMode!==a&&b.push("editMode"),m.current.allowEditing!==o&&b.push("allowEditing"),console.log(`[SingleFileTableView] Rendering #${h.current} - Props that changed:`,b);}else console.log(`[SingleFileTableView] Rendering #${h.current} - Initial render`);m.current={document:e,schema:t,columnWidth:r,onUpdateDocument:n,editMode:a,allowEditing:o},console.log(`[SingleFileTableView] Rendering #${h.current}`,{documentId:e.id,documentRef:e,schemaRef:t});let{columnWidth:p}=Ac(),v=r??p,[y,x]=useState([]),[w,_]=useState(0);useEffect(()=>{console.log("[SingleFileTableView] Effect triggered - props changed",{documentId:e.id,documentRef:e,schemaRef:t,schemaProperties:Object.keys(t.properties||{}),stopAt:y,columnWidth:v,editMode:a,allowEditing:o,onUpdateDocumentRef:n});},[e,t,y,v,a,o,n]);let E=Rt__default.useRef(null),C=Rt__default.useRef(null),[P]=useMemo(()=>(console.log("[SingleFileTableView] columns memo recomputing",{schemaRef:t,stopAt:y,columnWidth:v,editMode:a}),uP(t,()=>{},y,x,v,true,E,C,"single-file",i??{computations:{}},b=>{s?.(b);},a)),[t,y,v,a]),T=useMemo(()=>(console.log("[SingleFileTableView] visibleKeys memo recomputing",{columnsRef:P}),Dv(P).map(b=>"accessorKey"in b?b.accessorKey:void 0).filter(Boolean)),[P]),N=useMemo(()=>(console.log("[SingleFileTableView] tableAndPaths memo recomputing",{documentRef:e,visibleKeysRef:T}),e?GE(e,T):{table:[],paths:[]}),[e,T]),S=Math.max(N.paths.length,1);return jsx("div",{className:"flex flex-col flex-1 min-h-0 w-full relative",children:jsx("div",{className:"absolute inset-0 origin-top-left flex flex-col",children:jsx(Wv,{stopAt:y,setStopAt:x,foldAllSignal:w,setFoldAllSignal:_,columns:P,document:e,schema:t,tableAndPaths:N,visibleKeys:T,rowCount:S,onUpdateDocument:n,editMode:a,allowEditing:o,onCellHoverStart:l,cellColorState:c,distanceData:u,showHoverCard:d,similarityType:g,onGroundTruthChange:f})})})});Zv.displayName="SingleFileTableView";function Ed({className:e,...t}){return jsx(Ui.Root,{"data-slot":"tabs",className:R("flex flex-col gap-2",e),...t})}function Pd({className:e,...t}){return jsx(Ui.List,{"data-slot":"tabs-list",className:R("bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",e),...t})}function Bo({className:e,...t}){return jsx(Ui.Trigger,{"data-slot":"tabs-trigger",className:R("data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function Xv({className:e,...t}){return jsx(Ui.Content,{"data-slot":"tabs-content",className:R("flex-1 outline-none",e),...t})}var Um=e=>{if(Array.isArray(e))return e.map(t=>Um(t));if(e!==null&&typeof e=="object"){let t={};for(let[r,n]of Object.entries(e))r.startsWith("reasoning___")||(t[r]=Um(n));return t}return e},$P=(e,t)=>{let r=e.getValueInRange({startLineNumber:1,startColumn:1,endLineNumber:t.lineNumber,endColumn:t.column}),n=[],a=false,o=false,i=null,s="",l=false,c=[],u=[];for(let g=0;g<r.length;g++){let f=r[g];if(o){l&&(s+=f),o=false;continue}if(f==="\\"){o=true,l&&(s+=f);continue}if(a){f==='"'?(a=false,l&&(i=s,l=false)):l&&(s+=f);continue}if(f==='"'){if(a=true,c[c.length-1]==="object"||c.length===0){let m=r.substring(g+1),p=m.match(/^([^"\\]|\\.)*"/);if(p){let v=m.substring(p[0].length).trimStart();(v.startsWith(":")||v===""||/^:/.test(m.substring(p[0].length).trim()))&&(l=true,s="");}}continue}f==="{"?(i!==null?(n.push(i),i=null):c[c.length-1]==="array"&&n.push(u[u.length-1]),c.push("object")):f==="["?(i!==null&&(n.push(i),i=null),c.push("array"),u.push(0)):f==="}"?(c.pop(),n.length>0&&n.pop(),i=null):f==="]"?(c.pop(),u.pop(),n.length>0&&n.pop(),i=null):f===":"||f===","&&(c[c.length-1]==="array"&&u[u.length-1]++,i=null);}let d=[...n];if(i!==null&&d.push(i),d.length===0||i===null){let f=e.getLineContent(t.lineNumber).match(/"([^"]+)"\s*:/);if(f){let h=f[1];d[d.length-1]!==h&&d.push(h);}}return d.length>0?d.join("."):null},H7=e=>({id:e.id,file_id:e.file.id,project_id:e.id,mime_data:{id:e.file.id,filename:e.file.filename,mime_type:e.file.mime_type},prediction_data:{prediction:e.predictions,metadata:{extraction_id:e.id}},extraction_id:e.id});function tb({extraction:e,onFieldPathChange:t,extractionDisplayOptions:r,continueButtonOptions:n,extractionStreamingOptions:a}){let o=r?.view??"form",i=r?.allowEditing??false,s=r?.showReasoning??false,l=r?.showTabs??false,c=n?.onClick,u=n?.label,d=a?.isActive??false,g=a?.data,f=a?.filename,{project:h,applyComputations:m}=Fr(),{computedSchema:p}=Ka(),v=useQueryClient(),[y,x]=useState(o),[w,_]=useState(i),E=l?y:o,C=l?w:i,P=ql(),[T,N]=useState(""),[S,b]=useState(false),[k,D]=useState(false),[O,$]=useState(null),[A,F]=useState(null),X=useRef(null),H=useRef([]),L=useRef(C),Q=useRef(null);useEffect(()=>{L.current=C;},[C]);let z=useMemo(()=>{if(!e)return {};let Z=e.predictions||{};return p?pn(Z,p):Z},[e,p]),[ae,M]=useState(null);useEffect(()=>{if(!e)return;let Z=h?.published_config?.computation_spec?.computations||{};if(!(Object.keys(Z).length>0)){M(null);return}let ee=false;return (async()=>{try{let V=await m(z);ee||M(V);}catch(V){console.error("Failed to apply computations to extraction:",V),ee||M(null);}})(),()=>{ee=true;}},[e,z,h?.published_config?.computation_spec?.computations,m]);let j=ae??z;useEffect(()=>{Q.current=j;},[j]);let ue=useCallback((Z,W)=>JSON.stringify(Z)===JSON.stringify(W),[]),ie=useMemo(()=>debounce(async Z=>{if(e)try{await P.mutateAsync({extractionId:e.id,predictions:Z});}catch(W){console.error("[debouncedSave] Failed to save:",W),toast.error("Failed to save changes");}},500),[e,P]);useEffect(()=>()=>ie.cancel(),[ie]);let Ce=d?g:j,Te=useMemo(()=>{if(!e)return {id:"temp",project_id:"",mime_data:{id:"temp",filename:f||"Uploading...",mime_type:"application/octet-stream"},prediction_data:{prediction:Ce||{},metadata:{}},extraction_id:null,dataset_id:"",iteration_id:"",dataset_document_id:""};let Z=H7(e);return Z.prediction_data.prediction=j,Z},[e,j,f,Ce]);useEffect(()=>{if(!S&&E==="code"){let Z=Um(Ce||{});N(JSON.stringify(Z,null,2));}},[Ce,S,E]);let Je=useMemo(()=>debounce(async Z=>{if(!Z){F("Empty input."),D(false);return}let W;try{W=JSON.parse(Z);}catch{F("Invalid JSON."),D(false);return}F(null),$(W),D(true);},300),[]);useEffect(()=>()=>Je.cancel(),[Je]);let vt=useCallback(()=>{!O||!k||!C||(ie(O),N(JSON.stringify(O,null,2)),b(false),D(false),$(null));},[O,k,C,ie]);useEffect(()=>{if(E!=="code")return;let Z=W=>{(typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(navigator.userAgentData?.platform||navigator.userAgent||"")?W.metaKey&&W.key==="s":W.ctrlKey&&W.key==="s")&&k&&(W.preventDefault(),vt());};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[E,k,vt]);let gt=useCallback(Z=>{t?.(Z);},[t]),bt=useCallback(Z=>{t?.(Z.fieldPath);},[t]),We=useMemo(()=>debounce(Z=>{t?.(Z);},50),[t]);useEffect(()=>()=>We.cancel(),[We]);let ke=useCallback((Z,W)=>{X.current=Z,H.current.forEach(Re=>Re.dispose()),H.current=[];let ee=Z.onDidChangeCursorPosition(Re=>{let Ee=Z.getModel();if(!Ee||!t)return;let $e=$P(Ee,Re.position);$e&&We($e);}),V=Z.onMouseMove(Re=>{if(!Re.target.position)return;let Ee=Z.getModel();if(!Ee||!t)return;let $e=$P(Ee,Re.target.position);$e&&We($e);});H.current.push(ee,V);},[t,We]);useEffect(()=>()=>{H.current.forEach(Z=>Z.dispose()),H.current=[];},[]);let be=useCallback(async Z=>{if(!L.current)return;let W=Z?.prediction_data?.prediction??{},ee=Q.current;ue(ee,W)||ie(W);},[ue,ie]),re=useCallback((Z,W)=>{if(!L.current)return;let ee=Q.current;ue(ee,W)||ie(W);},[ue,ie]),me=useCallback(async()=>{if(e)try{ie.cancel(),await P.mutateAsync({extractionId:e.id,human_review_status:"reviewed"}),v.invalidateQueries({queryKey:["extractions"]}),b(!1),D(!1),$(null),F(null),toast.success("Marked as reviewed"),c&&c();}catch(Z){console.error("Failed to continue:",Z),toast.error("Failed to mark as reviewed");}},[e,ie,P,c,v]),ye=useMemo(()=>u||(e?.human_review_status==="review_required"?"Mark as Reviewed":"Continue"),[u,e?.human_review_status]),ge=!d&&(e?.human_review_status==="review_required"||!!c);return jsxs("div",{className:"flex-1 relative min-h-0 flex flex-col overflow-hidden bg-white",children:[d&&jsxs("div",{className:"flex items-center gap-2 h-[39px] px-4 py-2 border-b border-zinc-200 top-0 left-0 right-0 bg-white",children:[jsx(Loader2,{className:"h-4 w-4 animate-spin text-indigo-600"}),jsxs("span",{className:"text-xs font-medium text-gray-700",children:["Extracting: ",f||"file"]})]}),l&&!d&&jsx("div",{className:"h-[39px] flex items-center px-2 border-b border-zinc-200 bg-white",children:jsxs("div",{className:"flex items-center justify-between w-full",children:[jsx(Ed,{value:y,onValueChange:Z=>x(Z),children:jsxs(Pd,{className:"flex p-0 h-7 bg-gray-50 gap-[1px] rounded-full",children:[jsxs(Bo,{value:"table",className:"text-2xs h-7 border-none hover:bg-gray-100 data-[state=active]:bg-gray-200 data-[state=active]:shadow-none shadow-none rounded-full bg-gray-50 px-3",children:[jsx(Table2,{className:"h-4 w-4 mr-1"})," Table"]}),jsxs(Bo,{value:"form",className:"text-2xs h-7 border-none hover:bg-gray-100 data-[state=active]:bg-gray-200 data-[state=active]:shadow-none shadow-none rounded-full bg-gray-50 px-3",children:[jsx(Blocks,{className:"h-4 w-4 mr-1"})," Form"]}),jsxs(Bo,{value:"code",className:"text-2xs h-7 border-none hover:bg-gray-100 data-[state=active]:bg-gray-200 data-[state=active]:shadow-none shadow-none rounded-full bg-gray-50 px-3",children:[jsx(Code,{className:"h-4 w-4 mr-1"})," Code"]})]})}),jsx(Ed,{value:w?"edit":"view",onValueChange:Z=>_(Z==="edit"),children:jsxs(Pd,{className:"flex p-0 h-7 bg-gray-50 gap-[1px] rounded-full",children:[jsxs(Bo,{value:"view",className:"text-2xs h-7 border-none hover:bg-gray-100 data-[state=active]:bg-gray-200 data-[state=active]:shadow-none shadow-none rounded-full bg-gray-50 px-3",children:[jsx(Eye,{className:"h-4 w-4 mr-1"})," View"]}),jsxs(Bo,{value:"edit",className:"text-2xs h-7 border-none hover:bg-gray-100 data-[state=active]:bg-gray-200 data-[state=active]:shadow-none shadow-none rounded-full bg-gray-50 px-3",children:[jsx(Edit,{className:"h-4 w-4 mr-1"})," Edit"]})]})})]})}),jsxs("div",{className:"flex-1 overflow-hidden flex flex-col min-h-0",children:[E==="form"&&jsx("div",{className:"flex-1 overflow-auto px-4 py-0 bg-white",children:jsx(WE,{itemIndex:0,iterationIndex:-1,schema:p,setSchema:noop,extractionData:Ce||{},similarities:void 0,isStreamingIteration:d,isRunningIteration:d,onFieldPathChange:gt,scalarValueType:"none",consensusDetails:[],editMode:"readOnly",allowEditing:d?false:C,onPredictionChange:d?noop:re,showPropertyEditorPencil:false,showReasoning:s})}),E==="table"&&jsx(Zv,{document:Te,schema:p,editMode:"readOnly",allowEditing:d?false:C,computationSpec:h?.published_config?.computation_spec,setComputationSpec:noop,onUpdateDocument:d?async()=>{}:be,onCellHoverStart:bt,cellColorState:"none",distanceData:void 0,showHoverCard:true,similarityType:"aligned"}),E==="code"&&jsxs("div",{className:"relative flex-1 min-h-0 bg-[#1E1E1E]",children:[A&&!d&&jsxs("div",{className:"absolute left-2 top-2 z-50 max-w-[75%] border border-amber-300 bg-amber-100 px-3 py-2 text-xs text-amber-900 shadow flex flex-row gap-2 rounded",children:[jsx(CircleX,{className:"w-4 h-4 text-red-800"}),A]}),S&&k&&C&&!d&&jsx("div",{className:"absolute right-2 top-2 z-50 flex items-center gap-2",children:jsxs(K,{size:"sm",onClick:vt,className:"text-xs bg-teal-500 hover:bg-teal-600 h-10 px-2",children:[jsxs("span",{className:"flex items-center gap-1 mr-1",children:[jsx("span",{className:"text-xs opacity-100 font-light border border-white rounded-sm px-1.5 py-1",children:typeof navigator<"u"&&/mac|iphone|ipad|ipod/i.test(navigator.userAgentData?.platform||navigator.userAgent||"")?"\u2318":"CTRL"}),jsx("span",{className:"text-xs opacity-100 font-light border border-white rounded-sm px-1.5 py-1",children:"S"})]}),"Apply Changes"]})}),jsx("div",{className:"absolute inset-0",children:jsx(Editor,{language:"json",theme:"light",value:d?JSON.stringify(Um(Ce||{}),null,2):T,onChange:Z=>{!C||d||(N(Z||""),b(true),Je(Z));},onMount:ke,options:{padding:{top:10,bottom:10},automaticLayout:true,readOnly:!C||d,minimap:{enabled:false},scrollBeyondLastLine:false,fontSize:11,lineNumbers:"off",folding:false,wordWrap:"on"}})})]}),ge&&jsxs("div",{className:"border-t border-zinc-200 bg-white p-2 flex items-center justify-end",children:[P.isPending&&jsxs("div",{className:"flex items-center gap-2 mr-auto",children:[jsx(Loader2,{className:"h-4 w-4 animate-spin text-muted-foreground"}),jsx("span",{className:"text-xs text-muted-foreground",children:"Saving..."})]}),jsxs("button",{onClick:me,className:R("h-8 text-xs group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay px-3 ring-1 bg-gray-900 hover:bg-gray-900 hover:opacity-100 text-white ring-gray-900"),children:[ye,jsx("svg",{viewBox:"0 0 10 10","aria-hidden":"true",className:"ml-2 h-2.5 w-2.5 flex-none opacity-60 group-hover:translate-x-6 group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity",children:jsx("path",{fill:"currentColor",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"m7.25 5-3.5-2.25v4.5L7.25 5Z"})}),jsx("svg",{viewBox:"0 0 10 10","aria-hidden":"true",className:"-ml-2.5 h-2.5 w-2.5 flex-none -translate-x-2 opacity-0 group-hover:translate-x-0 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity",children:jsx("path",{fill:"currentColor",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.5",d:"m7.25 5-3.5-2.25v4.5L7.25 5Z"})})]})]})]})]})}var qm=({pageNumber:e,width:t,renderAnnotationLayer:r=true,renderTextLayer:n=true,onRenderSuccess:a,className:o,PageComponent:i})=>{let[s,l]=useState(null),[c,u]=useState(true);return useEffect(()=>{l(null),u(true);},[e]),s?jsxs("div",{className:"p-4 text-xs text-gray-500 text-center border border-gray-200 rounded bg-gray-50",children:["Page ",e," could not be loaded"]}):i?jsx(i,{pageNumber:e,width:t,renderAnnotationLayer:r,renderTextLayer:n,className:o,onLoadSuccess:()=>{u(false);},onRenderSuccess:d=>{u(false),a?.(d);},onLoadError:d=>{console.error(`Error loading page ${e}:`,d),l(d),u(false);},error:jsxs("div",{className:"p-4 text-xs text-red-500 text-center border border-red-200 rounded bg-red-50",children:["Failed to load page ",e]}),loading:jsx("div",{className:"flex items-center justify-center py-8",children:jsx(Loader2,{className:"h-6 w-6 animate-spin text-gray-400"})})}):jsx("div",{className:"flex items-center justify-center py-8",children:jsx(Loader2,{className:"h-6 w-6 animate-spin text-gray-400"})})};var Qo=os(GR()),Hx=null,Jx=null,Wx=null,Kx=null,df=async()=>Hx&&Jx&&Wx?{pdfjs:Hx,Document:Jx,Page:Wx}:(Kx||(Kx=(async()=>{let{Document:e,Page:t,pdfjs:r}=await import('react-pdf');return typeof window<"u"&&(r.GlobalWorkerOptions.workerSrc="/pdf.worker.min.mjs"),Hx=r,Jx=e,Wx=t,{pdfjs:r,Document:e,Page:t}})()),Kx),QR=async()=>{let{pdfjs:e}=await df();return e},Gx=30,YR=e=>e.type==="application/pdf"||e.name.toLowerCase().endsWith(".pdf"),Zx=e=>e.type==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||e.name.toLowerCase().endsWith(".docx"),Xx=e=>e.type==="application/vnd.oasis.opendocument.text"||e.name.toLowerCase().endsWith(".odt"),ZR=e=>Zx(e)||Xx(e)||e.type==="application/msword"||e.name.toLowerCase().endsWith(".doc"),Qx=e=>e.type==="application/vnd.openxmlformats-officedocument.presentationml.presentation"||e.name.toLowerCase().endsWith(".pptx"),Yx=e=>e.type==="application/vnd.oasis.opendocument.presentation"||e.name.toLowerCase().endsWith(".odp"),XR=e=>Qx(e)||Yx(e)||e.type==="application/vnd.ms-powerpoint"||e.name.toLowerCase().endsWith(".ppt"),Eq=async e=>{try{let t=e.slice(0,16),r=new Uint8Array(await t.arrayBuffer()),n=Array.from(r).map(a=>a.toString(16).padStart(2,"0")).join(" ");return r.length>=4&&r[0]===37&&r[1]===80&&r[2]===68&&r[3]===70?"application/pdf":r.length>=8&&r[0]===137&&r[1]===80&&r[2]===78&&r[3]===71&&r[4]===13&&r[5]===10&&r[6]===26&&r[7]===10?"image/png":r.length>=3&&r[0]===255&&r[1]===216&&r[2]===255?"image/jpeg":r.length>=6&&r[0]===71&&r[1]===73&&r[2]===70&&r[3]===56&&(r[4]===55||r[4]===57)&&r[5]===97?"image/gif":r.length>=12&&r[0]===82&&r[1]===73&&r[2]===70&&r[3]===70&&r[8]===87&&r[9]===69&&r[10]===66&&r[11]===80?"image/webp":(r.length>=4&&r[0]===80&&r[1]===75&&(r[2]===3||r[2]===5||r[2]===7)&&(r[3]===4||r[3]===6||r[3]===8),null)}catch{return null}},Pq=async e=>{let t=await Eq(e);if(t&&t!==e.type){let r=await e.arrayBuffer();return new File([r],e.name,{type:t})}return e},Tq=async e=>{try{if(!e||e.size===0)return {corrupted:!0,reason:"File is empty (0 bytes)"};if(YR(e))try{let t=await QR(),r=await e.arrayBuffer(),n=new Uint8Array(r),o=await t.getDocument({data:n,stopAtErrors:!0}).promise;try{await o.cleanup?.();}catch{}try{o.destroy?.();}catch{}return {corrupted:!1}}catch(t){let r=t instanceof Error?t.message:"Unknown error";return r.includes("worker")||r.includes("Worker")||r.includes("module specifier")||r.includes("network")||r.includes("fetch")?(console.warn(`PDF validation skipped due to infrastructure error: ${r}`),{corrupted:!1}):{corrupted:!0,reason:`Invalid PDF structure: ${r}`}}if(Zx(e))try{let t=await e.arrayBuffer(),r=await Qo.default.loadAsync(t);return r.file("[Content_Types].xml")||r.file("word/document.xml")?{corrupted:!1}:{corrupted:!0,reason:"Invalid DOCX: missing required document structure (Content_Types.xml or word/document.xml)"}}catch(t){return {corrupted:!0,reason:`Invalid DOCX archive: ${t instanceof Error?t.message:"Unknown error"}`}}if(Qx(e))try{let t=await e.arrayBuffer(),r=await Qo.default.loadAsync(t);return r.file("[Content_Types].xml")||r.file("ppt/presentation.xml")?{corrupted:!1}:{corrupted:!0,reason:"Invalid PPTX: missing required presentation structure (Content_Types.xml or ppt/presentation.xml)"}}catch(t){return {corrupted:!0,reason:`Invalid PPTX archive: ${t instanceof Error?t.message:"Unknown error"}`}}if(Xx(e))try{let t=await e.arrayBuffer();return (await Qo.default.loadAsync(t)).file("content.xml")?{corrupted:!1}:{corrupted:!0,reason:"Invalid ODT: missing content.xml"}}catch(t){return {corrupted:!0,reason:`Invalid ODT archive: ${t instanceof Error?t.message:"Unknown error"}`}}if(Yx(e))try{let t=await e.arrayBuffer();return (await Qo.default.loadAsync(t)).file("content.xml")?{corrupted:!1}:{corrupted:!0,reason:"Invalid ODP: missing content.xml"}}catch(t){return {corrupted:!0,reason:`Invalid ODP archive: ${t instanceof Error?t.message:"Unknown error"}`}}return {corrupted:!1}}catch(t){return {corrupted:true,reason:`Failed to read file: ${t instanceof Error?t.message:"Unknown error"}`}}},kq=async e=>{let t=await QR(),r=await e.arrayBuffer(),n=new Uint8Array(r),o=await t.getDocument({data:n}).promise,i=o.numPages;try{await o.cleanup?.();}catch{}try{o.destroy?.();}catch{}return i},Rq=async e=>{let t=await e.arrayBuffer(),n=(await Qo.default.loadAsync(t)).file("docProps/app.xml");if(!n)throw new Error("docProps/app.xml not found");let a=await n.async("text"),s=new DOMParser().parseFromString(a,"application/xml").getElementsByTagName("Pages")[0];if(!s||!s.textContent)throw new Error("Pages metadata not found");let l=parseInt(s.textContent,10);if(!Number.isFinite(l)||l<=0)throw new Error("Invalid Pages value");return l},Oq=async e=>{let t=await e.arrayBuffer(),n=(await Qo.default.loadAsync(t)).file("meta.xml");if(!n)throw new Error("meta.xml not found");let a=await n.async("text"),i=new DOMParser().parseFromString(a,"application/xml"),s=i.getElementsByTagName("meta:document-statistic")[0]||i.getElementsByTagName("document-statistic")[0];if(!s)throw new Error("document-statistic not found");let l=s.getAttribute("meta:page-count")||s.getAttribute("page-count");if(!l)throw new Error("page-count not found");let c=parseInt(l,10);if(!Number.isFinite(c)||c<=0)throw new Error("Invalid page-count value");return c},Dq=async e=>{let t=await e.arrayBuffer(),n=(await Qo.default.loadAsync(t)).file("docProps/app.xml");if(!n)throw new Error("docProps/app.xml not found");let a=await n.async("text"),s=new DOMParser().parseFromString(a,"application/xml").getElementsByTagName("Slides")[0];if(!s||!s.textContent)throw new Error("Slides metadata not found");let l=parseInt(s.textContent,10);if(!Number.isFinite(l)||l<=0)throw new Error("Invalid Slides value");return l},Aq=async e=>{let t=await e.arrayBuffer(),n=(await Qo.default.loadAsync(t)).file("meta.xml");if(!n)throw new Error("meta.xml not found");let a=await n.async("text"),i=new DOMParser().parseFromString(a,"application/xml"),s=i.getElementsByTagName("meta:document-statistic")[0]||i.getElementsByTagName("document-statistic")[0];if(!s)throw new Error("document-statistic not found");let l=s.getAttribute("meta:slide-count")||s.getAttribute("slide-count");if(!l)throw new Error("slide-count not found");let c=parseInt(l,10);if(!Number.isFinite(c)||c<=0)throw new Error("Invalid slide-count value");return c},$q=async e=>{if(YR(e))return kq(e);if(Zx(e))return Rq(e);if(Xx(e))return Oq(e);if(Qx(e))return Dq(e);if(Yx(e))return Aq(e);throw new Error("Unsupported file type for page counting")},eO=async e=>{let t=Gx,r=[],n=[],a=[];for(let o of e){let i=await Pq(o);if(i.type==="application/pdf"||ZR(i)||XR(i)||i.size===0)try{let l=await Tq(i);if(l.corrupted){a.push({name:i.name,reason:l.reason});continue}}catch(l){let c=l instanceof Error?l.message:"Unknown validation error";a.push({name:i.name,reason:c});continue}if(i.type==="application/pdf"||ZR(i)||XR(i))try{let l=await $q(i);if(l>t){n.push({name:i.name,pages:l});continue}}catch{}r.push(i);}return {accepted:r,rejected:n,corrupted:a}};var jq={cMapUrl:"https://unpkg.com/pdfjs-dist@4.4.168/cmaps/",cMapPacked:true},Lq=(e,t)=>{let r=new Uint8Array(e),n=r.length;if(n===0)return `${t}-0`;let o=[0,Math.floor(n/2),n-1].map(i=>r[i]?.toString(16)??"0");return [t,n.toString(),...o].join("-")},Bq=({content:e})=>{let[t,r]=useState(null),[n,a]=useState(null),[o,i]=useState(true),[s,l]=useState(null),[c,u]=useState(null),d=useRef(true),{fetchWithAuth:g}=Ve();useEffect(()=>(d.current=true,()=>{d.current=false;}),[]),useEffect(()=>{e.byteLength>0&&(async()=>{let m=new FormData,p=new Blob([e],{type:"message/rfc822"});m.append("file",p,"email.eml");let v=new Uint8Array(e);d.current&&u(v);try{let y=await g("/v1/processors/automations/outlook/convert_to_email_data_and_upload_file?return_inline_body=true",{method:"POST",body:m});if(!d.current)return;if(y.ok){let x=await y.json();r(x);}else throw new Error("Failed to convert EML to email model")}catch(y){d.current&&(console.error("Error converting EML:",y),a(y.message));}finally{d.current&&i(false);}})();},[e]);return n?jsx("div",{className:"text-red-500 text-center",children:n}):!t||o?jsx("div",{className:"text-center",children:"Processing email..."}):jsxs("div",{className:"flex flex-col h-full space-y-0",children:[jsx("div",{className:"w-full overflow-clip bg-background border-b border-gray-200",children:jsx("div",{className:"flex flex-row items-center space-x-2 px-2 py-2 justify-between h-10",children:jsxs("div",{className:"flex flex-row items-center space-x-2 min-w-0 grow overflow-hidden text-xs",children:[jsx(Mail,{className:"h-4 w-4 shrink-0 text-gray-600 cursor-pointer"}),jsxs("div",{className:"ml-2 text-gray-500 truncate overflow-hidden flex-1 w-full flex justify-between",children:[jsx("div",{children:jsx("span",{className:"font-semibold w-20 text-gray-600",children:t.subject})}),jsxs("div",{children:[jsx("span",{className:"pl-2 font-semibold w-20 text-gray-700",children:"From:"}),jsx("span",{className:"underline flex-1 text-gray-500",children:t.sender.email}),jsx("span",{className:"ml-2 font-semibold w-20 text-gray-700",children:"To:"}),jsx("span",{className:"underline flex-1 text-gray-500",children:t.recipients_to[0]?.email})]})]})]})})}),jsx("div",{className:"grid grid-cols-2 gap-4 text-xs",children:t.attachments.filter(h=>!h.metadata?.is_inline).length>0&&jsx("div",{className:"col-span-2",children:jsxs("div",{className:"grid grid-cols-3 gap-0",children:[jsx("li",{onClick:()=>l(null),className:`py-1 px-2 flex flex-row space-x-2 border justify-between cursor-pointer ${s===null?"bg-purple-100 border-purple-300 text-purple-700":"bg-gray-100 border-gray-200 text-gray-600 hover:bg-gray-100"}`,children:jsx("div",{className:"w-64 truncate",children:"Mail Body"})}),t.attachments.filter(h=>!h.metadata?.is_inline).map((h,m)=>jsx("li",{onClick:()=>l(h.url),className:`py-1 px-2 flex flex-row space-x-2 border justify-between cursor-pointer ${s===h.url?"bg-purple-100 border-purple-300 text-purple-700":"bg-gray-100 border-gray-200 text-gray-600 hover:bg-gray-100"}`,children:jsx("div",{className:"w-64 truncate",children:h.filename})},m))]})})}),jsx("div",{className:"overflow-auto grow",children:t&&(t.attachments.filter(h=>!h.metadata?.is_inline).find(h=>h.url===s)?(()=>{let m=t.attachments.find(p=>p.url===s).url.split(";base64,");if(m.length===2){let p=m[0].replace("data:",""),v=m[1],y=atob(v),x=new Uint8Array(y.length);for(let w=0;w<y.length;w++)x[w]=y.charCodeAt(w);return jsx(nO,{content:x.buffer,mimeType:p},s)}else return jsx("div",{children:"Malformed data URL"})})():c&&jsx(zq,{emailData:t}))})]})},zq=({emailData:e})=>{let t=Rt__default.useRef(null),r=Rt__default.useRef(null);return Rt__default.useEffect(()=>{if(t.current&&e.body_html){let n=()=>{let a=t.current,o=r.current;if(a&&o){let i=o.querySelector(".email-header")?.clientHeight||0,s=o.clientHeight-i;a.style.height=`${s}px`;}};return t.current.onload=n,window.addEventListener("resize",n),setTimeout(n,100),()=>window.removeEventListener("resize",n)}},[e.body_html]),jsxs("div",{ref:r,className:"h-full flex flex-col overflow-hidden",children:[jsxs("div",{className:"email-header bg-muted/20 p-4",children:[jsx("h2",{className:"text-xl font-bold mb-2",children:e.subject}),jsxs("p",{className:"text-sm text-muted-foreground mb-1",children:[jsx("strong",{children:"From:"})," ",e.sender.display_name||e.sender.email," <",e.sender.email,">"]}),jsxs("p",{className:"text-sm text-muted-foreground mb-1",children:[jsx("strong",{children:"To:"})," ",e.recipients_to.map(n=>`${n.display_name||n.email} <${n.email}>`).join(", ")]}),e.recipients_cc?.length>0&&jsxs("p",{className:"text-sm text-muted-foreground mb-1",children:[jsx("strong",{children:"CC:"})," ",e.recipients_cc.map(n=>`${n.display_name||n.email} <${n.email}>`).join(", ")]}),jsxs("p",{className:"text-sm text-muted-foreground",children:[jsx("strong",{children:"Date:"})," ",new Date(e.sent_at).toLocaleString()]})]}),jsx("div",{className:"flex-1 overflow-hidden",children:e.body_html?jsx("iframe",{ref:t,srcDoc:String(e.body_html),title:"Email content",className:"w-full h-full border-none",sandbox:"allow-same-origin allow-scripts"}):jsx("div",{className:"p-4 h-full overflow-auto",children:jsx("pre",{className:"whitespace-pre-wrap",children:e.body_plain||"No content"})})})]})},Uq=({content:e})=>{let t=useRef(null),[r,n]=useState(true),[a,o]=useState(null);return useEffect(()=>{(async()=>{if(t.current){n(true),o(null),t.current.innerHTML="";try{let{renderAsync:s}=await import('docx-preview');await s(e,t.current,void 0,{className:"docx-wrapper",inWrapper:!0,ignoreWidth:!1,ignoreHeight:!0,ignoreFonts:!1,breakPages:!0,ignoreLastRenderedPageBreak:!0,experimental:!1,trimXmlDeclaration:!0,useBase64URL:!0,renderHeaders:!0,renderFooters:!0,renderFootnotes:!0,renderEndnotes:!0});}catch(s){console.error("Error rendering DOCX:",s),o("Failed to render document");}finally{n(false);}}})();},[e]),jsxs("div",{className:"w-full h-full overflow-hidden flex flex-col",children:[r&&jsx("div",{className:"flex items-center justify-center h-full",children:jsx(Loader2,{className:"h-8 w-8 animate-spin text-gray-400"})}),a&&jsx("div",{className:"flex items-center justify-center h-full text-red-500 text-sm",children:a}),jsx("div",{ref:t,className:"docx-container w-full h-full overflow-auto !shadow-none !p-0 !bg-white !m-0",style:{display:r||a?"none":"block"}}),jsx("style",{jsx:true,global:true,children:`
68
+ .docx-container > * {
69
+ background: white !important;
70
+ margin: 0 !important;
71
+ box-shadow: none !important;
72
+ padding: 16px !important;
73
+ }
67
74
  .docx-wrapper {
68
75
  background: white;
69
- padding: 0;
76
+ padding: 0 !important;
70
77
  max-width: 100%;
78
+ box-shadow: none !important;
71
79
  }
72
80
  .docx-wrapper > section.docx {
73
81
  width: 100% !important;
74
82
  min-height: auto !important;
75
- padding: 16px !important;
83
+ padding: 0px !important;
76
84
  margin: 0 !important;
77
85
  box-shadow: none !important;
78
86
  max-width: 100%;
@@ -92,21 +100,20 @@ For more information, see https://radix-ui.com/primitives/docs/components/${t.do
92
100
  max-width: 100%;
93
101
  height: auto;
94
102
  }
95
- `})]})},zU=({content:e})=>{let[t,r]=useState(""),n=useMemo(()=>lh.read(new Uint8Array(e),{type:"array"}),[e]);useEffect(()=>{n.SheetNames.length>0&&!t&&r(n.SheetNames[0]);},[n.SheetNames,t]);let o=useMemo(()=>{if(!t||!n.Sheets[t])return [];let c=n.Sheets[t];return lh.utils.sheet_to_json(c,{header:1,defval:""})},[n,t]),a=useMemo(()=>o.reduce((c,u)=>Math.max(c,u.length),0),[o]),i=c=>{let u="",d=c;for(;d>=0;)u=String.fromCharCode(d%26+65)+u,d=Math.floor(d/26)-1;return u},s=c=>c==null?"":typeof c=="number"?Number.isInteger(c)?c.toLocaleString():c.toLocaleString(void 0,{maximumFractionDigits:4}):String(c),l=c=>typeof c=="number"?"text-right":typeof c=="boolean"?"text-center":"text-left";return n.SheetNames.length===0?jsx("div",{className:"w-full h-full flex items-center justify-center bg-white text-gray-500",children:jsx("div",{className:"text-center",children:jsx("div",{children:"No sheets found in this workbook"})})}):jsxs("div",{className:"w-full h-full flex flex-col bg-white overflow-hidden",children:[n.SheetNames.length>1&&jsx("div",{className:"flex-shrink-0 border-b border-gray-200 bg-gray-100",children:jsx("div",{className:"flex overflow-x-auto scrollbar-thin scrollbar-thumb-gray-300",children:n.SheetNames.map((c,u)=>jsx("button",{onClick:()=>r(c),className:`
103
+ `})]})},qq=({content:e})=>{let[t,r]=useState(""),n=useMemo(()=>Fh.read(new Uint8Array(e),{type:"array"}),[e]);useEffect(()=>{n.SheetNames.length>0&&!t&&r(n.SheetNames[0]);},[n.SheetNames,t]);let a=useMemo(()=>{if(!t||!n.Sheets[t])return [];let c=n.Sheets[t];return Fh.utils.sheet_to_json(c,{header:1,defval:""})},[n,t]),o=useMemo(()=>a.reduce((c,u)=>Math.max(c,u.length),0),[a]),i=c=>{let u="",d=c;for(;d>=0;)u=String.fromCharCode(d%26+65)+u,d=Math.floor(d/26)-1;return u},s=c=>c==null?"":typeof c=="number"?Number.isInteger(c)?c.toLocaleString():c.toLocaleString(void 0,{maximumFractionDigits:4}):String(c),l=c=>typeof c=="number"?"text-right":typeof c=="boolean"?"text-center":"text-left";return n.SheetNames.length===0?jsx("div",{className:"w-full h-full flex items-center justify-center bg-white text-gray-500",children:jsx("div",{className:"text-center",children:jsx("div",{children:"No sheets found in this workbook"})})}):jsxs("div",{className:"w-full h-full flex flex-col bg-white overflow-hidden",children:[n.SheetNames.length>1&&jsx("div",{className:"flex-shrink-0 border-b border-gray-200 bg-gray-100",children:jsx("div",{className:"flex overflow-x-auto scrollbar-thin scrollbar-thumb-gray-300",children:n.SheetNames.map((c,u)=>jsx("button",{onClick:()=>r(c),className:`
96
104
  px-4 py-2 text-xs font-medium whitespace-nowrap transition-all
97
105
  border-r border-gray-200 first:border-l
98
106
  ${t===c?"bg-white text-emerald-700 border-b-2 border-b-emerald-500 -mb-[1px]":"bg-gray-50 text-gray-600 hover:bg-gray-100 hover:text-gray-800"}
99
- `,children:jsxs("span",{className:"inline-flex items-center gap-1.5",children:[jsxs("span",{className:"opacity-50",children:["#",u+1]}),c]})},c))})}),jsx("div",{className:"flex-1 overflow-auto",children:o.length===0?jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-400",children:jsx("div",{className:"text-center",children:jsx("div",{children:"This sheet is empty"})})}):jsxs("table",{className:"w-full border-collapse text-xs",children:[jsx("thead",{className:"sticky top-0 z-20",children:jsxs("tr",{className:"bg-white",children:[jsx("th",{className:"sticky -mb-[1px] left-0 z-30 w-12 min-w-12 px-2 py-1.5 text-center text-gray-500 font-semibold bg-white border-b border-r border-gray-300"}),Array.from({length:a},(c,u)=>jsx("th",{className:"px-3 py-1.5 text-center text-gray-600 font-semibold bg-white border-b border-r border-gray-300 min-w-[80px]",children:i(u)},u))]})}),jsx("tbody",{children:o.map((c,u)=>jsxs("tr",{className:`
107
+ `,children:jsxs("span",{className:"inline-flex items-center gap-1.5",children:[jsxs("span",{className:"opacity-50",children:["#",u+1]}),c]})},c))})}),jsx("div",{className:"flex-1 overflow-auto",children:a.length===0?jsx("div",{className:"w-full h-full flex items-center justify-center text-gray-400",children:jsx("div",{className:"text-center",children:jsx("div",{children:"This sheet is empty"})})}):jsxs("table",{className:"w-full border-collapse text-xs",children:[jsx("thead",{className:"sticky top-0 z-20",children:jsxs("tr",{className:"bg-white",children:[jsx("th",{className:"sticky -mb-[1px] left-0 z-30 w-12 min-w-12 px-2 py-1.5 text-center text-gray-500 font-semibold bg-white border-b border-r border-gray-300"}),Array.from({length:o},(c,u)=>jsx("th",{className:"px-3 py-1.5 text-center text-gray-600 font-semibold bg-white border-b border-r border-gray-300 min-w-[80px]",children:i(u)},u))]})}),jsx("tbody",{children:a.map((c,u)=>jsxs("tr",{className:`
100
108
  ${u===0&&"font-medium"}
101
109
  hover:bg-gray-50 transition-colors -mt-[1px]
102
- `,children:[jsx("td",{className:"sticky left-0 z-10 w-12 h-[28px] min-w-12 py-0 text-center text-gray-400 font-medium bg-white select-none",children:jsx("div",{className:"h-full items-center justify-center flex w-full min-w-12",children:jsx("div",{className:"border-b border-r border-gray-200 h-full w-full flex items-center justify-center py-1 px-2",children:u+1})})}),Array.from({length:a},(d,m)=>{let h=c[m],y=s(h),p=u===0;return jsx("td",{className:`
110
+ `,children:[jsx("td",{className:"sticky left-0 z-10 w-12 h-[28px] min-w-12 py-0 text-center text-gray-400 font-medium bg-white select-none",children:jsx("div",{className:"h-full items-center justify-center flex w-full min-w-12",children:jsx("div",{className:"border-b border-r border-gray-200 h-full w-full flex items-center justify-center py-1 px-2",children:u+1})})}),Array.from({length:o},(d,g)=>{let f=c[g],h=s(f),m=u===0;return jsx("td",{className:`
103
111
  px-3 py-1.5 border-b border-r border-gray-200
104
- ${l(h)}
105
- ${p?"text-gray-700":"text-gray-600"}
106
- ${y?"":"text-gray-300"}
112
+ ${l(f)}
113
+ ${m?"text-gray-700":"text-gray-600"}
114
+ ${h?"":"text-gray-300"}
107
115
  max-w-[200px] truncate
108
- `,title:y.length>30?y:void 0,children:y||""},m)})]},u))})]})}),jsxs("div",{className:"flex-shrink-0 px-3 py-1.5 bg-gray-100 border-t border-gray-200 text-xs text-gray-500 flex items-center justify-between",children:[jsx("span",{children:o.length>0?`${o.length} rows \xD7 ${a} columns`:"Empty sheet"}),jsxs("span",{className:"text-gray-400",children:["Sheet ",n.SheetNames.indexOf(t)+1," of ",n.SheetNames.length]})]})]})},UU=({content:e,signature:t})=>{let[r,n]=useState(null),o=useRef(null),[a,i]=useState(0),s=useRef(null),[l,c]=useState(false),[u,d]=useState(null),[m,h]=useState(null),[y,p]=useState(true);useEffect(()=>{let v=false;return $d().then(({Document:w,Page:N})=>{v||(d(()=>w),h(()=>N),p(false));}),()=>{v=true;}},[]);let f=kt__default.useMemo(()=>{try{return new Blob([e],{type:"application/pdf"})}catch{try{let w=e.slice(0);return new Blob([w],{type:"application/pdf"})}catch{return null}}},[t]);useEffect(()=>{if(y||!u)return;let v=()=>{o.current&&i(o.current.clientWidth);};requestAnimationFrame(v);let w=null;return typeof window<"u"&&window.ResizeObserver&&o.current&&(w=new window.ResizeObserver(v),w.observe(o.current)),window.addEventListener("resize",v),()=>{window.removeEventListener("resize",v),w&&o.current&&w.unobserve(o.current);}},[y,u]),useEffect(()=>()=>{if(s.current){try{s.current.destroy();}catch(v){console.debug("PDF document cleanup error (can be safely ignored):",v);}s.current=null;}},[]),useEffect(()=>{c(false);},[t]);let x=useCallback(v=>{s.current=v,n(v.numPages),c(true);},[]),g=useCallback(v=>{console.error("PDF loading error:",v),s.current=null;},[]);return y||!u?jsx("div",{className:"relative w-full h-full flex items-center justify-center",children:jsx(Loader2,{className:"h-8 w-8 animate-spin text-gray-400"})}):jsxs("div",{ref:o,className:"relative w-full h-full overflow-auto",children:[!l&&jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-white/80 text-xs text-gray-700",children:"Loading PDF\u2026"}),jsx(u,{file:f,onLoadSuccess:x,onLoadError:g,options:FU,loading:null,error:jsxs("div",{className:"p-4 text-red-500 text-sm border border-red-200 rounded-lg bg-red-50",children:[jsx("div",{className:"font-medium",children:"Could not load PDF"}),jsx("div",{className:"text-xs mt-1",children:"Please check if the file is valid."})]}),children:!!r&&a>0&&f&&m&&Array.from({length:r},(v,w)=>jsx("div",{className:"mb-0 flex justify-center",children:jsx(hm,{pageNumber:w+1,width:Math.min(a,1200),PageComponent:m})},w))})]})},qU=({content:e,mimeType:t})=>{let r=new TextDecoder().decode(e),o=((a,i)=>{switch(i){case "application/javascript":case "text/javascript":return "javascript";case "application/typescript":case "text/typescript":return "typescript";case "text/html":return "html";case "text/css":return "css";case "application/json":return "json";case "text/x-python":case "application/x-python-code":return "python";case "text/x-java":case "text/java":return "java";case "text/x-c":case "text/x-c++":case "text/x-csrc":case "text/x-c++src":return "cpp";case "text/x-csharp":return "csharp";case "text/x-go":return "go";case "text/x-rust":return "rust";case "text/x-swift":return "swift";case "text/x-php":case "application/x-httpd-php":return "php";case "text/x-ruby":return "ruby";case "text/xml":case "application/xml":return "xml";case "text/x-markdown":case "text/markdown":return "markdown";case "text/yaml":case "application/yaml":case "application/x-yaml":return "yaml";case "text/x-toml":return "toml";case "application/x-sh":case "text/x-sh":return "bash";case "application/x-powershell":return "powershell";case "text/x-sql":return "sql";case "text/x-dockerfile":return "dockerfile";case "text/x-properties":case "application/x-properties":return "properties"}let s=a.trim().split(`
109
- `)[0].toLowerCase();if(a.trim().startsWith("{")||a.trim().startsWith("["))try{return JSON.parse(a),"json"}catch{}return s.includes("<?xml")?"xml":s.includes("<!doctype html")||a.includes("<html")?"html":s.includes("#!/usr/bin/python")?"python":s.includes("#!/usr/bin/node")?"javascript":s.includes("#!/bin/bash")?"bash":a.includes("function")&&a.includes("=>")?"javascript":a.includes("import ")&&a.includes(" from ")?"typescript":a.includes("def ")&&a.includes(":")?"python":"text"})(r,t);return jsx("div",{className:"w-full h-full bg-white border-2 border-gray-100 overflow-auto",children:jsx("div",{className:"w-full h-full overflow-auto",children:jsx(PrismAsync,{language:o,style:oneDark,customStyle:{margin:0,borderRadius:"0.75rem",height:"100%",fontSize:"11px",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:r})})})},VU=({content:e,mimeType:t})=>{let[r,n]=useState(null),o=useRef(null),a=useRef(null),i=useRef(null),s=useRef(null),l=useRef(e),c=useRef(t);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{c.current=t;},[t]);let u=useMemo(()=>MU(e,t),[e,t]);useEffect(()=>{let m=c.current,h=l.current;if(m==="message/rfc822"||m==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||m==="application/msword"||m==="application/vnd.oasis.opendocument.text"||m==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"||m==="application/vnd.ms-excel"||m==="application/vnd.oasis.opendocument.spreadsheet"||m==="application/pdf"||m==="text/plain"||m==="text/csv"||m==="text/html"||m==="application/json")return;s.current&&(URL.revokeObjectURL(s.current),s.current=null),o.current&&(o.current.style.display="flex"),a.current&&(a.current.style.display="none"),i.current&&(i.current.style.display="none");let p=false;return (async()=>{try{let x;if(m==="image/heic"||m==="image/heif")try{let g=new Blob([h],{type:m}),{default:v}=await import('heic2any'),w=await v({blob:g,toType:"image/jpeg",quality:.9}),N=Array.isArray(w)?w[0]:w;x=URL.createObjectURL(N);}catch(g){console.warn("HEIC/HEIF conversion failed or library unavailable, falling back to raw blob preview",g);let v=new Blob([h],{type:m});x=URL.createObjectURL(v);}else {let g=new Blob([h],{type:m});x=URL.createObjectURL(g);}if(p){URL.revokeObjectURL(x);return}s.current=x,n(x),o.current&&(o.current.style.display="none"),i.current&&(i.current.style.display="flex"),d(x,m);}catch(x){console.error("Failed to create preview:",x),o.current&&(o.current.style.display="none"),a.current&&(a.current.style.display="flex");}})(),()=>{p=true;}},[u]),useEffect(()=>()=>{s.current&&(URL.revokeObjectURL(s.current),s.current=null);},[]);let d=(m,h)=>{if(i.current){for(;i.current.firstChild;)i.current.removeChild(i.current.firstChild);if(h.startsWith("image/")){let y=document.createElement("img");y.src=m,y.alt="File preview",y.className="max-w-full max-h-full object-contain",y.style.maxHeight="100%",y.style.maxWidth="100%";let p=document.createElement("div");p.className="flex items-center justify-center w-full h-full",p.appendChild(y),i.current.appendChild(p);}else if(h==="application/pdf"){let y=document.createElement("iframe");y.src=m,y.className="w-full h-full border-none max-h-full",y.title="PDF preview",i.current.appendChild(y);}else if(h.startsWith("text/")){let y=document.createElement("iframe");y.src=m,y.className="w-full h-full border-none text-xs max-h-full",y.title="Text preview",i.current.appendChild(y);}else {let y=document.createElement("div");y.className="flex flex-col items-center justify-center h-full text-center";let p=document.createElement("p");p.textContent=`Preview not available for this file type: ${h}`;let f=document.createElement("a");f.href=m,f.download="file",f.className="text-primary hover:underline",f.textContent="Download file",y.appendChild(p),y.appendChild(f),i.current.appendChild(y);}}};return t==="message/rfc822"?jsx(jU,{content:e}):t==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||t==="application/msword"||t==="application/vnd.oasis.opendocument.text"?jsx(BU,{content:e}):t==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"||t==="application/vnd.ms-excel"||t==="application/vnd.oasis.opendocument.spreadsheet"?jsx(zU,{content:e}):t==="text/plain"||t==="text/csv"||t==="text/html"||t==="application/json"?jsx(qU,{content:e,mimeType:t}):t==="application/pdf"?jsx(UU,{content:e,signature:u}):t.startsWith("image/")&&r?jsx("div",{className:"relative w-full h-full",children:jsx("img",{src:r,alt:"File preview",className:"w-full h-full object-contain max-w-full max-h-full"})}):jsxs("div",{className:"relative w-full h-full overflow-auto min-w-0",children:[jsx("div",{ref:a,className:"flex items-center justify-center h-full bg-background",style:{display:"none"},children:jsx("p",{children:"Error loading file preview"})}),jsx("div",{ref:i,className:"w-full h-full relative",style:{display:"none"}})]})},lR=kt__default.memo(VU),cR=lR;function ch({className:e="h-full",showPadding:t=false}){return jsx("div",{className:`flex flex-col items-center overflow-auto ${t?"py-24":e}`,children:jsx("div",{className:"flex flex-col gap-6 w-full max-w-3xl px-4 py-4 ",children:jsxs("div",{className:"bg-white p-0 space-y-4",children:[jsxs("div",{className:"space-y-2",children:[jsx(Re,{className:"h-6 w-2/3"}),jsx(Re,{className:"h-4 w-1/2"})]}),jsxs("div",{className:"space-y-3 pt-4",children:[jsx(Re,{className:"h-3 w-full"}),jsx(Re,{className:"h-3 w-full"}),jsx(Re,{className:"h-3 w-5/6"}),jsx(Re,{className:"h-3 w-full"}),jsx(Re,{className:"h-3 w-4/5"})]}),jsxs("div",{className:"space-y-3 pt-4",children:[jsx(Re,{className:"h-4 w-1/3"}),jsx(Re,{className:"h-3 w-full"}),jsx(Re,{className:"h-3 w-full"}),jsx(Re,{className:"h-3 w-3/4"})]}),jsx(Re,{className:"h-32 w-full rounded"}),jsxs("div",{className:"space-y-3 pt-2",children:[jsx(Re,{className:"h-3 w-full"}),jsx(Re,{className:"h-3 w-full"}),jsx(Re,{className:"h-3 w-2/3"})]})]})})})}function _x(){return jsxs("div",{className:"overflow-y-auto flex flex-col col-span-2 relative",children:[jsx("div",{className:"bg-white z-10 flex flex-col top-0 left-0 p-2 sticky",children:jsx("div",{className:"flex justify-between items-center w-full",children:jsxs("div",{className:"text-xs flex items-center gap-1",children:[jsx(Loader2,{className:"h-3 w-3 animate-spin mr-1"}),jsx("div",{className:"italic text-xs text-gray-500",children:"OCR in progress..."})]})})}),jsxs("div",{className:"flex flex-col gap-4",children:[jsx(Re,{className:"w-full h-[500px] rounded-lg"}),jsx(Re,{className:"w-full h-[500px] rounded-lg"}),jsx(Re,{className:"w-full h-[300px] rounded-lg"})]})]})}var uh=class extends Component{constructor(t){super(t),this.state={hasError:false};}static getDerivedStateFromError(t){return {hasError:true,error:t}}componentDidCatch(t,r){console.error("PDF Error Boundary caught an error:",t,r);}render(){return this.state.hasError?this.props.fallback?this.props.fallback:jsxs("div",{className:"flex flex-col items-center justify-center h-full p-6 text-center",children:[jsx(AlertCircle,{className:"h-12 w-12 text-red-500 mb-4"}),jsx("h3",{className:"text-lg font-semibold mb-2",children:"Unable to Display PDF"}),jsx("p",{className:"text-sm text-muted-foreground max-w-md",children:"An error occurred while rendering the PDF. This might be due to a temporary issue. Try refreshing the page or selecting a different document."}),this.state.error&&jsxs("details",{className:"mt-4 text-xs text-left max-w-md",children:[jsx("summary",{className:"cursor-pointer text-muted-foreground hover:text-foreground",children:"Technical details"}),jsx("pre",{className:"mt-2 p-2 bg-gray-100 dark:bg-gray-800 rounded overflow-auto",children:this.state.error.message})]})]}):this.props.children}};var ZU=kt__default.memo(function({fileUrl:t,fileId:r,numPages:n,zoomFactor:o,pageWidth:a,onLoadSuccess:i,onLoadError:s,onPageRender:l,pageRefs:c,DocumentComponent:u,PageComponent:d}){let m=Math.min(a*o,1200),h=kt__default.useRef(null);kt__default.useEffect(()=>()=>{if(h.current){try{h.current.destroy();}catch(f){console.debug("PDF document cleanup error (can be safely ignored):",f);}h.current=null;}},[r]);let y=kt__default.useCallback(f=>{h.current=f,i(f);},[i]),p=kt__default.useCallback(f=>{console.error("PDF loading error:",f),h.current=null,s(f);},[s]);return jsx(u,{file:t,onLoadSuccess:y,onLoadError:p,loading:jsx("div",{className:"flex items-center justify-center h-full min-h-[400px]",children:jsx(Loader2,{className:"h-8 w-8 animate-spin"})}),error:jsxs("div",{className:"p-4 text-red-500 text-sm border border-red-200 rounded-lg bg-red-50",children:[jsx("div",{className:"font-medium",children:"Could not load PDF"}),jsx("div",{className:"text-xs mt-1",children:"Please check if the file exists and is accessible."})]}),children:n>0&&Array.from({length:n},(f,x)=>{let g=x+1;return jsx("div",{ref:v=>{c.current[g]=v;},"data-page-number":g,style:{position:"relative",marginBottom:"20px",scrollMarginBlock:"20px"},children:jsx(hm,{pageNumber:g,width:m,PageComponent:d,onRenderSuccess:v=>{try{let w=v.getViewport({scale:1}),N=m/w.width;l(g,w,N);}catch(w){console.debug(`Page ${g} render callback error (can be safely ignored):`,w);}}})},g)})},r)},(e,t)=>e.fileUrl===t.fileUrl&&e.fileId===t.fileId&&e.numPages===t.numPages&&e.zoomFactor===t.zoomFactor&&e.pageWidth===t.pageWidth&&e.DocumentComponent===t.DocumentComponent&&e.PageComponent===t.PageComponent),XU=kt__default.memo(function({fileId:t,numPages:r,currentBoxes:n,pageDims:o}){if(n.length===0)return null;let a=[],i=0;for(let s=1;s<=r;s++){a[s]=i;let l=o[t]?.[s];l&&(i+=l.h+20);}return jsx("div",{style:{position:"absolute",top:0,left:0,pointerEvents:"none",width:"100%",height:"100%"},children:Array.from({length:r},(s,l)=>{let c=l+1,u=o[t]?.[c];if(!u)return null;let d=n.filter(h=>h.page===c);if(d.length===0)return null;let m=a[c]||0;return jsx("div",{style:{position:"absolute",top:m,left:0,width:u.w,height:u.h},children:d.map((h,y)=>{let p={left:h.xmin*u.w,top:h.ymin*u.h,width:(h.xmax-h.xmin)*u.w,height:(h.ymax-h.ymin)*u.h};return jsx("div",{id:`bbox-${t}-${y}`,style:{position:"absolute",left:p.left,top:p.top,width:p.width,height:p.height,background:"rgba(114,191,227,.3)",outline:"2px solid rgba(120,162,231,1.0)",pointerEvents:"none",boxSizing:"border-box"}},`${t}-${c}-${y}`)})},c)})})}),fR=kt__default.memo(function({currentItem:t,fieldPath:r,activeFormType:n,isPerformingOCR:o,isInitializingFieldLocations:a,ocrFileUrls:i,getInMemoryFieldLocations:s,getInMemoryFieldLocationsByType:l,autoPerformOCR:c,refreshOCRUrl:u,getFieldLocationsError:d,className:m="",isFileSelectorCollapsed:h=true}){let{fetchWithAuth:y}=De(),[p,f]=useState({}),[x,g]=useState({}),[v,w]=useState(h?1:.75),[N,S]=useState(null),[_,P]=useState(0),[R,E]=useState(null),[C,b]=useState(false),O=useRef(void 0),D=useRef({}),k=useRef(null),[I,F]=useState(null),[Z,pe]=useState(null);useEffect(()=>{let xe=false;return $d().then(({Document:me,Page:_e})=>{xe||(F(()=>me),pe(()=>_e));}),()=>{xe=true;}},[]),useEffect(()=>{w(h?1:.75);},[h]),useEffect(()=>{(async()=>{if(!t?.id||t.fileMimeType!=="application/pdf"){E(null);return}b(true);try{let me=await y(`/internal/db/files/${t.id}/download-link`);if(!me.ok)throw new Error(`Failed to get download link: ${me.status} ${me.statusText}`);let _e=await me.json();E(_e.download_url);}catch(me){console.error("Error fetching direct PDF URL:",me),E(null);}finally{b(false);}})();},[t?.id,t?.fileMimeType]);let ie=useRef(null);useEffect(()=>{P(0);},[t?.id]);let J=useCallback(xe=>{if(ie.current&&ie.current.disconnect(),ie.current=null,k.current=xe,!xe)return;let me=()=>{if(k.current){let _e=k.current.clientWidth;_e>0&&P(_e);}};if(me(),typeof window<"u"&&window.ResizeObserver){let _e=new window.ResizeObserver(()=>{me();});ie.current=_e,_e.observe(xe);}},[]);useEffect(()=>{let xe=()=>{if(k.current){let me=k.current.clientWidth;me>0&&P(me);}};return window.addEventListener("resize",xe),()=>{window.removeEventListener("resize",xe);}},[]);let ue=useRef({}),re=useRef(null);useCallback(()=>{w(xe=>Math.min(xe+.25,3));},[]);useCallback(()=>{w(xe=>Math.max(xe-.25,.5));},[]);let L=useCallback(xe=>({numPages:me})=>{f(_e=>({..._e,[xe]:me})),S(null),D.current[xe]=false;},[]),le=useCallback(xe=>{console.error("PDF loading error:",xe),S(xe.message);let me=xe?.status,_e=t?.id;if(!_e)return;let pt=!!D.current[_e];(me===400||me===403)&&u&&!pt&&(D.current[_e]=true,u(_e));},[u,t?.id]),ae=useMemo(()=>{if(!r||!t?.id)return [];let xe=n?l?.(t.id,n)??null:s(t.id);if(!xe)return [];let me=xe[r];return !me?.bbox_normalized||!me.page?[]:[{page:me.page,xmin:me.bbox_normalized[0],ymin:me.bbox_normalized[1],xmax:me.bbox_normalized[2],ymax:me.bbox_normalized[3]}]},[r,t.id,s]),Oe=ae.length>0&&t&&!!x[t.id]?.[ae[0].page];useEffect(()=>{if(!Oe||!re.current)return;let xe=re.current.querySelector(`#bbox-${t.id}-0`);if(xe){let me=re.current.getBoundingClientRect(),_e=xe.getBoundingClientRect(),pt=re.current.clientHeight,Me=_e.top-me.top+re.current.scrollTop-pt/2+_e.height/2;re.current.scrollTo({top:Math.max(0,Me),behavior:"smooth"});}},[Oe,t?.id,r]),useEffect(()=>{ue.current={};},[t?.id]);let ye=i[t.id];useEffect(()=>{ye&&ye!==O.current&&(O.current=ye,S(null),D.current[t.id]=false);},[ye,t.id]);let ft=o(t.id),zt=a(t.id);useEffect(()=>{t?.id&&!i[t.id]&&!o(t.id)&&c?.(t.id);},[t?.id,i,o,c]);let st=d&&(d(t.id,"ground_truth")||d(t.id,"extraction")),Et=t.fileMimeType==="application/pdf";if(ft&&!st&&!Et)return jsx(_x,{});let tt=i[t.id]||R;return tt?jsx(uh,{children:jsxs("div",{className:T("h-full w-full flex flex-col relative",m),children:[jsx("div",{className:" z-10 flex justify-between items-center absolute top-2 right-2 left-2",children:jsx("div",{className:"text-sm text-gray-700 bg-white/50 px-2 rounded-lg items-center h-8 flex",children:zt?jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[jsx(Loader2,{className:"size-4 animate-spin"}),"Computing field locations..."]}):r?jsxs("span",{className:`text-xs flex items-center gap-2 ${ae.length===0?"text-red-600":"text-blue-600"}`,children:[ae.length>0?jsx(Search,{className:"size-4"}):jsx(X,{className:"size-4"}),jsxs("span",{children:[n==="ground_truth"?"Ground Truth":"Extraction"," - ",r]}),ae.length===0&&jsx("span",{className:"text-red-600",children:": No source available."})]}):jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[jsx(Search,{className:"size-4"}),"Select a field to view its location"]})})}),jsx("div",{ref:re,className:"flex-1 overflow-y-auto",children:N?jsxs("div",{className:"p-4 text-red-500 text-sm border border-red-200 rounded-lg bg-red-50",children:[jsx("div",{className:"font-medium",children:"Could not load PDF"}),jsx("div",{className:"text-xs mt-1",children:N})]}):jsx("div",{ref:J,style:{position:"relative",minHeight:"400px"},children:_===0||!I||!Z?jsx("div",{className:"flex items-center justify-center h-full min-h-[400px]",children:jsx(Loader2,{className:"h-8 w-8 animate-spin"})}):jsxs(Fragment,{children:[jsx(ZU,{fileUrl:tt,fileId:t.id,numPages:p[t.id]||0,zoomFactor:v,pageWidth:_,onLoadSuccess:L(t.id),onLoadError:le,onPageRender:(xe,me,_e)=>{let pt={w:me.width*_e,h:me.height*_e};g(Fe=>({...Fe,[t.id]:{...Fe[t.id],[xe]:pt}}));},pageRefs:ue,DocumentComponent:I,PageComponent:Z}),jsx(XU,{fileId:t.id,numPages:p[t.id]||0,currentBoxes:ae,pageDims:x})]})})})]})}):jsxs("div",{className:T("flex flex-col items-center justify-center h-full text-muted-foreground",m),children:[jsx(Loader2,{className:"h-8 w-8 animate-spin mb-2"}),jsx("span",{children:C?"Loading document...":"Loading OCR result..."})]})});function mR({className:e="h-12 w-12 text-gray-400",strokeWidth:t=2}){return jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:t,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 0 1 -2 -2V5a2 2 0 0 1 2 -2h5.586a1 1 0 0 1 .707 .293l5.414 5.414a1 1 0 0 1 .293 .707V19a2 2 0 0 1 -2 2z"})})}function nq(e){return lookup(e)||"application/octet-stream"}function oq({filename:e}){let t=e.lastIndexOf(".");if(t<=0||t===e.length-1)return jsx("span",{className:"text-xs truncate block",children:e});let r=e.substring(0,t),n=e.substring(t);return jsxs("span",{className:"text-2xs justify-start flex items-center min-w-0 max-w-full",children:[jsx("span",{className:"truncate flex-shrink min-w-0",children:r}),jsx("span",{className:"flex-shrink-0",children:n})]})}function gR({currentDocument:e,currentFileData:t,getFileData:r,fieldPath:n,currentIterationId:o,activeFormType:a,onClearFileData:i,showButtons:s=true,isStreaming:l=false}){let c=gr(o),[u,d]=useState("preview"),{getFieldLocationsError:m,clearFieldLocationsError:h}=Ui(),{isPerformingOCR:y,isInitializingFieldLocations:p,ocrFileUrls:f,getInMemoryFieldLocations:x,getInMemoryFieldLocationsByType:g,autoPerformOCR:v,refreshOCRUrl:w,autoComputeFieldLocations:N}=Ui(),S=e?.mime_data.id,[_,P]=useState(void 0),[R,E]=useState(false),C=kt__default.useRef(0),b=kt__default.useRef(r);useEffect(()=>{b.current=r;},[r]),useEffect(()=>{let k=e?.mime_data?.id;C.current+=1;let I=C.current;if(P(void 0),E(!!k),i?.(),!k){E(false);return}let F=b.current;if(!F){E(false);return}let Z=false;return (async()=>{try{let pe=await F(k);if(Z||I!==C.current)return;pe&&pe.buffer&&P(pe);}finally{!Z&&I===C.current&&E(false);}})(),()=>{Z=true;}},[e?.mime_data?.id]),useEffect(()=>{let k=e?.mime_data?.id;k&&(!t||t.id!==k||!t.buffer||(P(t),E(false)));},[t,e?.mime_data?.id]);let O=_?.file?.type==="application/octet-stream"?nq(_?.file?.name):_?.file?.type||"application/octet-stream";useEffect(()=>{if(u!=="sources"||!e?.id||!e?.mime_data.id)return;v(e.mime_data.id);let k=e?.prediction_data?.prediction||{};!k||Object.keys(k).length===0||(N(e.id,k,e.mime_data.id,o),o.includes("iteration")&&N(e.id,k,e.mime_data.id,e.dataset_id));},[u,e?.id,e?.mime_data.id,e?.prediction_data?.prediction,o,N,v]);let D=async()=>{if(!e||!_||!_.buffer){toast.error("File data not available");return}try{let k=e.mime_data.filename||"download",I=new Blob([_.buffer]),F=URL.createObjectURL(I),Z=document.createElement("a");Z.href=F,Z.download=k,document.body.appendChild(Z),Z.click(),document.body.removeChild(Z),URL.revokeObjectURL(F),toast.success("File downloaded");}catch(k){console.error("Download error:",k),toast.error("Failed to download file");}};return e?jsx("div",{className:"h-full w-full bg-white overflow-hidden shadow-sm flex flex-col relative",children:jsxs(Zu,{value:u,onValueChange:k=>d(k),className:"h-full flex flex-col gap-0",children:[jsxs("div",{className:`flex items-center justify-between pl-3 h-[39px] border-b ${c.border} ${c.forbiddenCellBg}`,children:[jsxs("div",{className:"flex flex-row gap-1 items-center min-w-0 flex-1 mr-2",children:[jsx(mR,{className:"h-3.5 w-3.5 flex-shrink-0"}),jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:jsx(oq,{filename:e?.mime_data?.filename||"Unknown"})})]}),jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:s&&jsxs(Xu,{className:"flex flex-row gap-0 h-[34px] items-center justify-center mr-[2px]",children:[jsx(io,{children:jsxs(Xe,{children:[jsx(Ca,{asChild:true,className:"text-xs data-[state=active]:text-gray-800 text-muted-foreground",value:"sources",disabled:!e||!tf(O)||l,children:jsx(Qe,{children:jsx(Search,{className:"h-4 w-4"})})}),jsx(et,{children:jsx("p",{children:l?"Sources not available during extraction":!e||!tf(O)?"OCR not supported for this file type":"View OCR sources and field locations"})})]})}),jsx(io,{children:jsxs(Xe,{children:[jsx(Ca,{asChild:true,value:"preview",className:"text-xs data-[state=active]:text-gray-800 text-muted-foreground",children:jsx(Qe,{children:jsx(Paperclip,{className:"h-4 w-4"})})}),jsx(et,{children:jsx("p",{children:"Preview the original file content"})})]})}),jsx(io,{children:jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(V,{size:"sm",variant:"ghost",onClick:D,disabled:!e||!_?.buffer,className:"h-8 w-8 p-0 opacity-100 duration-300",children:jsx(Download,{className:"h-4 w-4"})})}),jsx(et,{children:jsx("p",{children:"Download File"})})]})})]})})]}),jsxs("div",{className:"flex flex-1 w-full min-h-0",children:[jsx(xv,{value:"preview",className:"flex-1 min-h-0 overflow-auto mt-0 min-w-0",children:e?!_?.buffer||R?jsx(ch,{}):jsx(cR,{content:_.buffer,mimeType:O}):jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"Select an item"})}),jsx(xv,{value:"sources",className:"flex-1 min-h-0 overflow-auto mt-0 min-w-0",children:e?!_?.buffer||R?jsx(ch,{}):tf(O)?jsxs("div",{className:"flex flex-col h-full",children:[S&&m(S,a||"ground_truth")&&jsx("div",{className:"m-3 p-3 bg-red-50 border border-red-200 rounded-md",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center",children:[jsx("svg",{className:"h-4 w-4 text-red-500 mr-2 flex-shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z",clipRule:"evenodd"})}),jsx("span",{className:"text-sm text-red-700",children:S?m(S,a||"ground_truth"):null})]}),jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[jsx("button",{onClick:()=>{S&&h(S,a||"ground_truth");},className:"text-red-600 hover:text-red-800 text-sm underline font-medium",children:"Retry"}),jsx("button",{onClick:()=>S&&h(S,a||"ground_truth"),className:"text-red-500 hover:text-red-700 text-sm underline",children:"Dismiss"})]})]})}),jsx("div",{className:"flex-1 min-h-0",children:S&&O&&jsx(fR,{currentItem:{id:S,fileMimeType:O},fieldPath:n||void 0,activeFormType:a,isPerformingOCR:y,isInitializingFieldLocations:k=>p(e.id,o),ocrFileUrls:f,getInMemoryFieldLocations:k=>x(e.id,o),getInMemoryFieldLocationsByType:(k,I)=>g(e.id,I,o),autoPerformOCR:v,refreshOCRUrl:w})})]}):jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"OCR not supported for this file type"}):jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"Select an item"})})]})]})}):jsx("div",{className:"flex items-center justify-center h-full w-full bg-white border-t",children:jsx("div",{className:"text-sm text-muted-foreground",children:"No document selected"})})}function vR(e,t){let[r,n]=useState(void 0),[o,a]=useState(false),i=useRef(0);return useEffect(()=>{i.current+=1;let l=i.current,c=false;return n(void 0),a(!!e),!e||!t?(a(false),()=>{c=true;}):((async()=>{try{let u=await t(e);if(c||l!==i.current)return;u&&n(u);}catch{}finally{!c&&l===i.current&&a(false);}})(),()=>{c=true;})},[e,t]),{fileData:r,isLoading:o,reset:()=>{i.current+=1,n(void 0),a(false);}}}function uq(e){return lookup(e)||"application/octet-stream"}var dq=e=>({id:e.id,file_id:e.file.id,project_id:e.id,mime_data:{id:e.file.id,filename:e.file.filename,mime_type:e.file.mime_type},prediction_data:{prediction:e.predictions,metadata:{extraction_id:e.id}},extraction_id:e.id});function Cx({extraction:e,fieldPath:t=null,extractionStreamingOptions:r}){let n=r?.isActive??false,o=r?.data,a=r?.filename,{fetchWithAuth:i}=De(),s=useCallback(async h=>{try{let y=await i(`/internal/db/files/${h}`);if(!y.ok)throw new Error("Failed to fetch file details");let f=(await y.json())?.filename||"download",x=await i(`/internal/db/files/${h}/download-link`);if(!x.ok)throw new Error("Failed to fetch file URL");let v=(await x.json()).download_url,w=await fetch(v);if(!w.ok)throw new Error("Failed to fetch file content");let N=await w.arrayBuffer(),S=new Uint8Array(N),_=uq(f),P=new File([S],f,{type:_});return {id:h,file:P,buffer:N}}catch(y){console.error("Error fetching file data:",y),toast.error("Failed to load file");return}},[]),{fileData:l,reset:u}=vR(e?.file?.id,s),d=useMemo(()=>{if(n)return o||void 0;if(l)return l;if(e?.file?.id&&o?.buffer)return {...o,id:e.file.id}},[n,o,l,e]),m=useMemo(()=>e?dq(e):{id:"temp",project_id:"",mime_data:{id:"temp",filename:a||"Uploading...",mime_type:o?.file?.type||"application/octet-stream"},prediction_data:{prediction:{},metadata:{}},extraction_id:null,dataset_id:"",iteration_id:"",dataset_document_id:""},[e,a,o]);return jsx("div",{className:"flex-1 relative min-h-0 flex flex-col overflow-hidden bg-white",children:jsx(gR,{currentIterationId:n?"streaming-extraction":"single-extraction",currentDocument:m,currentFileData:d,getFileData:n?async()=>o||void 0:s,fieldPath:t,onClearFileData:()=>{n||u();},activeFormType:"extraction",isStreaming:n})})}function NR({leftPanel:e,rightPanel:t,defaultLeftWidth:r=25,minLeftWidth:n=15,maxLeftWidth:o=60,resizeHandleClassName:a}){let[i,s]=useState(r),[l,c]=useState(false),u=useRef(null),d=useRef(0),m=useRef(0),h=useRef(0);useEffect(()=>{let v=Math.min(Math.max(r,n),o);s(v);},[r,n,o]);let y=useCallback(g=>{u.current&&(c(true),m.current=g,h.current=i,document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.body.style.touchAction="none");},[i]),p=useCallback(g=>{if(!l||!u.current)return;let v=g-m.current,w=u.current.clientWidth,N=v/w*100,S=h.current+N,_=Math.min(Math.max(S,n),o);s(_);},[l,n,o]),f=useCallback(g=>{g.preventDefault(),y(g.clientX);},[y]),x=()=>{c(false),document.body.style.cursor="",document.body.style.userSelect="",document.body.style.touchAction="";};return useEffect(()=>{if(!l)return;let g=w=>{w.preventDefault(),cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>p(w.clientX));},v=()=>{cancelAnimationFrame(d.current),x();};return document.addEventListener("pointermove",g,{passive:false}),document.addEventListener("pointerup",v),document.addEventListener("pointercancel",v),()=>{document.removeEventListener("pointermove",g),document.removeEventListener("pointerup",v),document.removeEventListener("pointercancel",v);}},[l,p]),jsxs("div",{ref:u,className:T("flex flex-1 min-h-0 min-w-0"),children:[jsx("div",{style:{flex:`0 0 ${i}%`},className:"flex overflow-auto",children:e}),jsxs("div",{onPointerDown:f,className:T("group relative w-[1px] flex-shrink-0 bg-border hover:bg-indigo-400 cursor-col-resize transition-colors group",l&&"bg-indigo-500",a),children:[jsx("div",{className:"absolute top-0 bottom-0 left-1/2 -translate-x-1/2 w-[12px] cursor-col-resize z-20",onPointerDown:f}),jsx("div",{className:"absolute top-0 bottom-0 left-1/2 -translate-x-1/2 w-[4px] bg-indigo-500 opacity-0 transition-opacity duration-300 group-hover:opacity-100 cursor-col-resize z-20"})]}),jsx("div",{className:"flex flex-1 min-w-0 overflow-hidden",children:t})]})}function Fc(...e){return twMerge(clsx(e))}function Ld(e,t){if(!e||!t)return;let r=t.split("."),n=e;for(let o of r){if(n==null)return;n=n[o];}return n}function Px(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>Px(n));let t={};for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=Px(e[n]));let r=Object.keys(t);if(r.length>0&&r.every(o=>{let a=Number(o);return !isNaN(a)&&Number.isInteger(a)&&a>=0&&a<=Number.MAX_SAFE_INTEGER&&String(a)===o})){let o=r.map(a=>Number(a)).sort((a,i)=>a-i);if(o[0]===0&&o[o.length-1]===o.length-1)return o.map(a=>t[a])}return t}function CR(e){if(!e||Object.keys(e).length===0)return e;let t={...e},r={};for(let n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let a=n.split(".").filter(s=>s!=="");if(a.length===0){r[n]=t[n];continue}let i=r;for(let s=0;s<a.length;s++){let l=a[s],u=!isNaN(Number(l))&&Number.isInteger(Number(l))&&Number(l)>=0&&String(Number(l))===l?Number(l):l;s===a.length-1?i[u]=t[n]:(i[u]===void 0?i[u]={}:(typeof i[u]!="object"||Array.isArray(i[u]))&&(i[u]={}),i=i[u]);}}return Px(r)}var gh=({onFileUploaded:e,multiple:t=false,className:r})=>{let[n,o]=useState(false),[a,i]=useState(false),s=useRef(null),l=async y=>{try{o(!0);let p=await y.arrayBuffer();e(y,p),toast.success("File loaded successfully");}catch(p){console.error("Error loading file:",p),toast.error("Failed to load file");}finally{o(false);}},c=y=>{let p=y.target.files;if(!(!p||p.length===0))for(let f=0;f<p.length;f++){let x=p[f];l(x);}},u=y=>{y.preventDefault(),y.stopPropagation(),i(true);},d=y=>{y.preventDefault(),y.stopPropagation(),i(false);},m=y=>{y.preventDefault(),y.stopPropagation();},h=y=>{y.preventDefault(),y.stopPropagation(),i(false);let p=y.dataTransfer.files;if(!(!p||p.length===0))for(let f=0;f<p.length;f++){let x=p[f];l(x);}};return jsxs("div",{className:Fc(`flex flex-col items-center justify-center w-full h-full cursor-pointer bg-gray-100 transition-colors ${a?"bg-blue-50":""}`,r),onDragEnter:u,onDragLeave:d,onDragOver:m,onDrop:h,onClick:()=>s.current?.click(),children:[jsx(CloudUpload,{className:`h-12 w-12 ${a?"text-blue-400":"text-slate-600"} transition-colors`}),jsx("h3",{className:"text-slate-800 font-normal text-2xl mb-2 mt-4",children:"Upload a file"}),jsx("p",{className:"text-sm text-slate-700 text-center",children:"Drag and drop or click to select a file"}),jsx("input",{multiple:t,type:"file","aria-label":"Upload a file",ref:s,onChange:c,disabled:n,className:"hidden",id:"file-upload"})]})};function kx({extractionId:e,projectId:t,isNewExtraction:r=false,extractionDisplayOptions:{view:n="form",allowEditing:o=false,showReasoning:a=false,showTabs:i=false}={},continueButtonOptions:{onClick:s,label:l="Continue"}={}}){let[c,u]=useState(false),{data:d,isLoading:m}=My(r&&!c?null:e),[h,y]=useState(null),[p,f]=useState(false),[x,g]=useState(null),[v,w]=useState(null),[N,S]=useState(null),_=useQueryClient(),{fetchWithAuth:P}=De();useEffect(()=>{f(false),g(null),w(null),S(null),u(false);},[e]);let R=useCallback(async(D,k)=>{if(!t||!e){toast.error("Missing project or extraction ID");return}g(D),w({id:`temp-${Date.now()}`,file:D,buffer:k}),f(true),S({});try{let I=new FormData;I.append("document",D),I.append("extraction_id",e),I.append("store","true");let F=await P(`/v1/projects/extract/${t}/stream`,{method:"POST",body:I});if(!F.ok)throw new Error(`HTTP error! status: ${F.status}`);if(!F.body)throw new Error("Browser doesn't support streaming responses.");let Z=F.body.getReader(),pe=new TextDecoder("utf-8"),ie="",J={};for(;;){let{value:ue,done:re}=await Z.read();if(re){await _.invalidateQueries({queryKey:$t.lists()}),await _.invalidateQueries({queryKey:$t.detail(e)}),u(!0),toast.success("Extraction completed");break}if(ue){let X=pe.decode(ue,{stream:!0});ie+=X;let $=ie.split(`
110
- `);ie=$.pop()||"";for(let L of $)if(L.trim())try{let ae=JSON.parse(L)?.choices?.[0],Oe=ae?.delta;if(Oe&&(Oe.flat_deleted_keys&&Oe.flat_deleted_keys.forEach(ft=>{delete J[ft];}),Oe.flat_parsed)){J={...J,...Oe.flat_parsed};let ft=CR(J);S(ft);}let ye=ae?.message?.parsed;ye&&typeof ye=="object"&&S(ye);}catch(le){console.error("[ExtractionComponent] Error parsing chunk:",le);}}}}catch(I){console.error("[ExtractionComponent] Extraction error:",I),toast.error("Extraction failed"),f(false),S(null),w(null),g(null);}},[t,e,_,P]),E=useCallback(D=>{y(D);},[]);useEffect(()=>{d&&p&&f(false);},[d,p]);let C=p&&!d,b=e&&!r&&!d&&!p&&m,O=e&&!r&&d===null&&!p&&!m;return b?jsx("div",{className:"flex-1 relative min-h-0 flex flex-col overflow-hidden",children:jsx("div",{className:"flex-1 flex items-center justify-center p-0",children:jsxs("div",{className:"flex flex-col items-center gap-3 text-muted-foreground",children:[jsx(Loader2,{className:"h-8 w-8 animate-spin"}),jsx("span",{className:"text-sm",children:"Loading extraction..."})]})})}):O?jsx("div",{className:"flex-1 relative min-h-0 flex flex-col overflow-hidden",children:jsx("div",{className:"flex-1 flex items-center justify-center p-0",children:jsxs("div",{className:"flex flex-col items-center gap-4 text-muted-foreground max-w-md text-center px-4",children:[jsx("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-zinc-100",children:jsx(FileX,{className:"h-8 w-8 text-zinc-400"})}),jsxs("div",{className:"space-y-2",children:[jsx("h3",{className:"text-lg font-medium text-zinc-900",children:"Extraction not found"}),jsx("p",{className:"text-sm text-zinc-500",children:"The extraction you're looking for doesn't exist or may have been deleted."})]}),jsxs("p",{className:"text-xs text-zinc-400 font-mono",children:["ID: ",e]})]})})}):!d&&!p?jsx("div",{className:"flex-1 relative min-h-0 flex flex-col overflow-hidden",children:jsx("div",{className:"flex-1 flex items-center justify-center p-0",children:jsx(gh,{onFileUploaded:R,className:"flex flex-1 min-h-0 bg-white hover:bg-zinc-50 transition-colors"})})}):jsx("div",{className:"flex-1 relative min-h-0 flex flex-col overflow-hidden",children:jsx(NR,{resizeHandleClassName:"bg-zinc-200",defaultLeftWidth:40,minLeftWidth:30,maxLeftWidth:90,leftPanel:jsx(Cx,{extraction:d??null,fieldPath:h,extractionStreamingOptions:{isActive:C,data:v,filename:x?.name}}),rightPanel:jsx(_v,{extraction:d??null,onFieldPathChange:E,extractionDisplayOptions:{view:n,allowEditing:o,showReasoning:a,showTabs:i},continueButtonOptions:{onClick:s,label:l},extractionStreamingOptions:{isActive:C,data:N,filename:x?.name}})})})}var Nq=ql.object({startDate:ql.date({required_error:"Start date is required."}),endDate:ql.date({required_error:"End date is required."})}).refine(e=>e.endDate>=e.startDate,{message:"End date cannot be before start date.",path:["endDate"]});function Bd({className:e,initialStartDate:t,initialEndDate:r,onSubmit:n,onChange:o,onClose:a,submitLabel:i="Submit",autoApply:s=false}){let l=useForm({resolver:zodResolver(Nq),defaultValues:{startDate:t,endDate:r}});function c(g){n?n(g):toast("You submitted the following values",{description:jsx("pre",{className:"mt-2 w-[320px] rounded-md bg-neutral-950 p-4",children:jsx("code",{className:"text-white",children:JSON.stringify(g,null,2)})})}),a?.();}let u=l.watch("startDate"),d=l.watch("endDate"),[m,h]=useState(false),[y,p]=useState(false),f=useRef(t),x=useRef(r);return useEffect(()=>{if(s&&o&&u&&d){let g=f.current?.getTime()!==u.getTime(),v=x.current?.getTime()!==d.getTime();(g||v)&&(f.current=u,x.current=d,o({startDate:u,endDate:d}));}},[u,d,s,o]),jsx(vl,{...l,children:jsxs("form",{onSubmit:l.handleSubmit(c),className:T("bg-gray-50 rounded-2xl shadow-2xl",e),children:[jsx("div",{className:T("bg-white shadow-xs rounded-2xl",e),children:jsxs("div",{className:"text-xs grid grid-cols-2 items-center gap-4 p-4",children:[jsx(ao,{control:l.control,name:"startDate",render:({field:g})=>jsxs(kn,{className:"flex flex-col",children:[jsx(oi,{className:"text-xs font-semibold",children:"From"}),jsxs(nr,{modal:true,open:m,onOpenChange:h,children:[jsx(or,{asChild:true,children:jsx(Rn,{children:jsxs(V,{variant:"outline",className:T("text-left font-normal text-xs",!g.value&&"text-muted-foreground"),children:[g.value?g.value.toLocaleDateString():jsx("span",{children:"Pick a date"}),jsx(CalendarIcon,{className:"ml-auto h-4 w-4 opacity-50"})]})})}),jsx(ar,{className:"w-auto p-0",align:"start",children:jsx(ns,{mode:"single",selected:g.value,onSelect:v=>{g.onChange(v),h(false);},disabled:v=>{let w=v>new Date,N=v<new Date("1900-01-01"),S=d?v>d:false;return w||N||S},captionLayout:"dropdown"})})]}),jsx(Nu,{})]})}),jsx(ao,{control:l.control,name:"endDate",render:({field:g})=>jsxs(kn,{className:"flex flex-col",children:[jsx(oi,{className:"text-xs font-semibold",children:"To"}),jsxs(nr,{modal:true,open:y,onOpenChange:p,children:[jsx(or,{asChild:true,children:jsx(Rn,{children:jsxs(V,{variant:"outline",className:T("text-left font-normal text-xs",!g.value&&"text-muted-foreground"),children:[g.value?g.value.toLocaleDateString():jsx("span",{children:"Pick a date"}),jsx(CalendarIcon,{className:"ml-auto h-4 w-4 opacity-50"})]})})}),jsx(ar,{className:"w-auto p-0",align:"start",children:jsx(ns,{mode:"single",selected:g.value,onSelect:v=>{g.onChange(v),p(false);},disabled:v=>{let w=v>new Date,N=v<new Date("1900-01-01"),S=u?v<u:false;return w||N||S},captionLayout:"dropdown"})})]}),jsx(Nu,{})]})})]})}),!s&&jsx("div",{className:e?"p-2":"p-4",children:jsx(V,{type:"submit",className:"text-xs w-full group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay ring-1 bg-gray-900 hover:bg-gray-900 hover:opacity-80 text-white ring-gray-900 gap-2",children:i})})]})})}var jc=({className:e})=>jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",className:e,children:jsx("path",{d:"M12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2ZM16.6914 7.30859C16.2804 6.89801 15.6141 6.89784 15.2031 7.30859L12 10.5117L8.79785 7.30957C8.3868 6.89852 7.72062 6.89852 7.30957 7.30957C6.8988 7.72064 6.89861 8.3869 7.30957 8.79785L10.5117 12L7.30859 15.2031C6.89797 15.6141 6.89805 16.2804 7.30859 16.6914C7.71959 17.1019 8.38595 17.102 8.79688 16.6914L12 13.4883L15.2041 16.6924C15.6151 17.1024 16.2816 17.1028 16.6924 16.6924C17.1031 16.2816 17.1025 15.6152 16.6924 15.2041L13.4883 12L16.6914 8.79688C17.1021 8.38596 17.1019 7.71963 16.6914 7.30859Z"})});var Ba=({className:e})=>jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",className:e,children:jsx("path",{d:"M11.9995 1.99951C17.5223 1.99958 21.9994 6.47673 21.9995 11.9995C21.9994 17.5223 17.5223 21.9994 11.9995 21.9995C6.47676 21.9994 1.99963 17.5223 1.99951 11.9995C1.99963 6.47676 6.47676 1.99963 11.9995 1.99951ZM17.3716 8.18408C16.9205 7.70276 16.1654 7.67831 15.6841 8.12939L9.98389 13.4692L7.88135 11.1753C7.43559 10.689 6.67916 10.6553 6.19287 11.1011C5.70661 11.5468 5.67387 12.3033 6.11963 12.7896L9.03955 15.9741C9.25502 16.2089 9.55608 16.3486 9.87451 16.3608C10.1932 16.3728 10.5041 16.2566 10.7368 16.0386L17.3169 9.87158C17.798 9.42063 17.8222 8.66544 17.3716 8.18408Z",fill:"currentColor"})});var kq={sm:{container:"!text-2xs",fieldPadding:"px-2 py-1",buttonPadding:"px-2 py-1",removePadding:"px-1.5 py-[5px]",iconSize:"h-3 w-3",statusIconSize:"h-3.5 w-3.5",dropdownItemText:"!text-xs",inputHeight:"h-8",buttonHeight:"h-8"},md:{container:"!text-xs",fieldPadding:"px-2.5 py-[5px]",buttonPadding:"px-2.5 py-[5px]",removePadding:"px-2 py-[5px]",iconSize:"h-4 w-4",statusIconSize:"h-4 w-4",dropdownItemText:"!text-sm",inputHeight:"h-9",buttonHeight:"h-9"}},IR=({filter:e,onUpdate:t,onRemove:r,formatDateValue:n,size:o="sm"})=>{let[a,i]=useState(false),[s,l]=useState(e.metadataKey||""),[c,u]=useState(e.field==="metadata"?String(e.value):""),d=kq[o],m=()=>e.field==="status"?jsx(CircleCheck,{className:T(d.iconSize,"text-gray-500")}):e.field==="created_date"?jsx(Calendar,{className:T(d.iconSize,"text-gray-500")}):e.field==="metadata"?jsx(Tag,{className:T(d.iconSize,"text-gray-500")}):null,h=()=>{if(e.field==="created_date"&&e.value instanceof Date)return n(e.value);if(e.field==="status"){if(e.value==="success")return "Success";if(e.value==="review_required")return "Requires review";if(e.value==="reviewed")return "Reviewed"}return String(e.value)},y=()=>e.field==="created_date"?"Created date":e.field==="status"?"Status":e.field==="metadata"?e.metadataKey||"metadata":e.field,p=g=>{t(e.id,g);},f=()=>{r(e.id);},x=()=>{s.trim()&&c.trim()&&(p({metadataKey:s.trim(),value:c.trim()}),i(false));};return jsxs("div",{className:T("inline-flex items-center gap-0.5 bg-gray-100 border border-gray-300 rounded-md overflow-hidden",d.container),children:[jsxs("div",{className:T("flex items-center gap-1",d.fieldPadding),children:[m(),jsx("span",{className:"font-medium text-gray-700",children:y()})]}),jsxs(dr,{children:[jsx(fr,{asChild:true,children:jsx("button",{className:T("hover:bg-gray-200 transition-colors text-gray-600 font-normal",d.buttonPadding),children:e.operator==="is_not"?"is not":e.operator})}),jsx(pr,{align:"start",className:"min-w-[100px]",children:e.field==="created_date"?jsxs(Fragment,{children:[jsx(ge,{className:d.dropdownItemText,onClick:()=>p({operator:"within"}),children:"within"}),jsx(ge,{className:d.dropdownItemText,onClick:()=>p({operator:"before"}),children:"before"}),jsx(ge,{className:d.dropdownItemText,onClick:()=>p({operator:"after"}),children:"after"})]}):e.field==="metadata"?jsxs(Fragment,{children:[jsx(ge,{className:d.dropdownItemText,onClick:()=>p({operator:"is"}),children:"is"}),jsx(ge,{className:d.dropdownItemText,onClick:()=>p({operator:"contains"}),children:"contains"})]}):jsxs(Fragment,{children:[jsx(ge,{className:d.dropdownItemText,onClick:()=>p({operator:"is"}),children:"is"}),jsx(ge,{className:d.dropdownItemText,onClick:()=>p({operator:"is_not"}),children:"is not"})]})})]}),e.field==="status"&&jsxs(dr,{children:[jsx(fr,{asChild:true,children:jsx("button",{className:T("hover:bg-gray-200 transition-colors text-gray-900 font-medium",d.buttonPadding),children:h()})}),jsxs(pr,{align:"start",className:"min-w-[120px]",children:[jsxs(ge,{className:d.dropdownItemText,onClick:()=>p({value:"review_required"}),children:[jsx(jc,{className:T(d.statusIconSize,"mr-2 text-[#D25F5F]")}),"Requires review"]}),jsxs(ge,{className:d.dropdownItemText,onClick:()=>p({value:"reviewed"}),children:[jsx(Ba,{className:T(d.statusIconSize,"mr-2 text-[#5F6AD2]")}),"Reviewed"]}),jsxs(ge,{className:d.dropdownItemText,onClick:()=>p({value:"success"}),children:[jsx(Ba,{className:T(d.statusIconSize,"mr-2 text-[#50CE89]")}),"Success"]})]})]}),e.field==="created_date"&&e.operator==="within"&&jsxs(nr,{children:[jsx(or,{asChild:true,children:jsxs("button",{className:T("hover:bg-gray-200 transition-colors text-gray-900 font-medium",d.buttonPadding),children:[e.value instanceof Date?n(e.value):"start"," \u2192 ",e.endValue instanceof Date?n(e.endValue):"end"]})}),jsx(ar,{className:"w-auto p-0",align:"start",children:jsx(Bd,{initialStartDate:e.value instanceof Date?e.value:new Date,initialEndDate:e.endValue instanceof Date?e.endValue:new Date,submitLabel:"Apply",onSubmit:({startDate:g,endDate:v})=>p({value:g,endValue:v})})})]}),e.field==="created_date"&&e.operator!=="within"&&jsxs(dr,{children:[jsx(fr,{asChild:true,children:jsx("button",{className:T("hover:bg-gray-200 transition-colors text-gray-900 font-medium",d.buttonPadding),children:h()})}),jsxs(pr,{align:"start",className:"min-w-[160px]",children:[[{label:"1 day ago",days:1},{label:"3 days ago",days:3},{label:"1 week ago",days:7},{label:"1 month ago",days:30},{label:"3 months ago",days:90},{label:"6 months ago",days:180},{label:"1 year ago",days:365}].map(({label:g,days:v})=>jsx(ge,{className:d.dropdownItemText,onClick:()=>{let w=new Date;w.setDate(w.getDate()-v),p({value:w});},children:g},g)),jsx(fo,{}),jsxs(nr,{children:[jsx(or,{asChild:true,children:jsx("button",{className:T("relative flex w-full cursor-default select-none items-center rounded-sm px-2 py-1.5 outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground",d.container),children:"Custom date..."})}),jsx(ar,{className:"w-auto p-0",align:"start",side:"right",children:jsx(Bd,{initialStartDate:e.value instanceof Date?e.value:new Date,initialEndDate:e.value instanceof Date?e.value:new Date,submitLabel:"Apply",onSubmit:({startDate:g})=>p({value:g})})})]})]})]}),e.field==="metadata"&&jsxs(nr,{open:a,onOpenChange:i,children:[jsx(or,{asChild:true,children:jsx("button",{className:T("hover:bg-gray-200 transition-colors text-gray-900 font-medium",d.buttonPadding),onClick:()=>{l(e.metadataKey||""),u(String(e.value));},children:h()})}),jsx(ar,{align:"start",className:"w-64 p-3",children:jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"space-y-1.5",children:[jsx("label",{className:T("font-medium text-gray-700",d.dropdownItemText),children:"Key"}),jsx(nt,{value:s,onChange:g=>l(g.target.value),placeholder:"e.g. customer_id",className:T(d.inputHeight,d.dropdownItemText)})]}),jsxs("div",{className:"space-y-1.5",children:[jsx("label",{className:T("font-medium text-gray-700",d.dropdownItemText),children:"Value"}),jsx(nt,{value:c,onChange:g=>u(g.target.value),placeholder:"e.g. 12345",className:T(d.inputHeight,d.dropdownItemText),onKeyDown:g=>{g.key==="Enter"&&x();}})]}),jsx(V,{size:"sm",className:T("w-full",d.dropdownItemText,d.buttonHeight),onClick:x,disabled:!s.trim()||!c.trim(),children:"Apply"})]})})]}),jsx("button",{onClick:f,className:T("hover:bg-gray-200 transition-colors h-full flex items-center justify-center text-gray-400 hover:text-gray-600",d.removePadding),children:jsx(X,{className:d.iconSize})})]})};var Fq={sm:{buttonClass:"!text-2xs h-7 py-0.25 px-0.5",iconSize:"size-3.5",dropdownWidth:"w-48",dropdownItemText:"!text-xs",menuIconSize:"h-3.5 w-3.5",inputHeight:"h-8",labelText:"!text-xs"},md:{buttonClass:"!text-xs h-8 py-0.5 px-1",iconSize:"size-4",dropdownWidth:"w-52",dropdownItemText:"!text-sm",menuIconSize:"h-4 w-4",inputHeight:"h-9",labelText:"!text-sm"}},Mq=()=>Math.random().toString(36).substr(2,9),jq=e=>{if(typeof e=="string")return e;let t=new Date,r=new Date(e),n=t.getTime()-r.getTime(),o=Math.floor(n/(1e3*60*60*24));return o===0?"today":o===1?"1 day ago":o===3?"3 days ago":o>=6&&o<=8?"1 week ago":o>=29&&o<=31?"1 month ago":o>=89&&o<=91?"3 months ago":o>=179&&o<=181?"6 months ago":o>=364&&o<=366?"1 year ago":format(r,"MMM d, yyyy")};function vh({filters:e,onFiltersChange:t,size:r="sm",showMetadataFilter:n=true}){let[o,a]=useState(""),[i,s]=useState(""),[l,c]=useState(false),u=Fq[r],d=(f,x)=>{t(e.map(g=>g.id===f?{...g,...x}:g));},m=f=>{t(e.filter(x=>x.id!==f));},h=f=>{t([...e,{...f,id:Mq()}]);},y=()=>{t([]);},p=()=>{o.trim()&&i.trim()&&(h({field:"metadata",operator:"is",value:i.trim(),metadataKey:o.trim()}),a(""),s(""));};return jsxs("div",{className:"flex items-center gap-2 flex-1 flex-wrap",children:[e.map(f=>jsx(IR,{filter:f,onUpdate:d,onRemove:m,formatDateValue:jq,size:r},f.id)),jsxs(dr,{open:l,onOpenChange:c,children:[jsx(fr,{asChild:true,children:jsxs(V,{variant:"outline",size:"sm",className:u.buttonClass,children:[jsx(ListFilter,{className:T(u.iconSize,"mr-1")}),jsx("span",{children:"Filter"})]})}),jsxs(pr,{align:"start",className:T(u.dropdownWidth,u.dropdownItemText),children:[e.length>0&&jsxs(Fragment,{children:[jsxs(ge,{onClick:y,className:T("text-red-600",u.dropdownItemText),children:[jsx(X,{className:T(u.menuIconSize,"mr-2")}),jsx("span",{children:"Clear all filters"})]}),jsx(fo,{})]}),jsxs(Vr,{children:[jsxs(Hr,{className:u.dropdownItemText,children:[jsx(CircleCheck,{className:T(u.menuIconSize,"mr-2 text-gray-500")}),jsx("span",{children:"Status"})]}),jsx(uo,{children:jsxs(Jr,{sideOffset:2,children:[jsxs(ge,{onClick:()=>h({field:"status",operator:"is",value:"review_required"}),className:u.dropdownItemText,children:[jsx(jc,{className:T(u.menuIconSize,"mr-2 text-[#D25F5F]")}),jsx("span",{children:"Requires review"})]}),jsxs(ge,{onClick:()=>h({field:"status",operator:"is",value:"reviewed"}),className:u.dropdownItemText,children:[jsx(Ba,{className:T(u.menuIconSize,"mr-2 text-[#5F6AD2]")}),jsx("span",{children:"Reviewed"})]}),jsxs(ge,{onClick:()=>h({field:"status",operator:"is",value:"success"}),className:u.dropdownItemText,children:[jsx(Ba,{className:T(u.menuIconSize,"mr-2 text-[#50CE89]")}),jsx("span",{children:"Success"})]})]})})]}),jsxs(Vr,{children:[jsxs(Hr,{className:u.dropdownItemText,children:[jsx(Calendar,{className:T(u.menuIconSize,"mr-2 text-gray-500")}),jsx("span",{children:"Created date"})]}),jsx(uo,{children:jsxs(Jr,{className:"max-h-[400px] overflow-y-auto",children:[[{label:"1 day ago",days:1},{label:"3 days ago",days:3},{label:"1 week ago",days:7},{label:"1 month ago",days:30},{label:"3 months ago",days:90},{label:"6 months ago",days:180},{label:"1 year ago",days:365}].map(({label:f,days:x})=>jsx(ge,{className:u.dropdownItemText,onClick:()=>{let g=new Date;g.setDate(g.getDate()-x),h({field:"created_date",operator:"after",value:g});},children:f},f)),jsx(fo,{}),jsxs(Vr,{children:[jsx(Hr,{className:u.dropdownItemText,children:"Custom date range..."}),jsx(uo,{children:jsx(Jr,{className:"p-0",sideOffset:2,children:jsx(Bd,{initialStartDate:new Date,initialEndDate:new Date,submitLabel:"Apply",className:u.dropdownItemText,onSubmit:({startDate:f,endDate:x})=>{h({field:"created_date",operator:"within",value:f,endValue:x});},onClose:()=>c(false)})})})]})]})})]}),n&&jsxs(Vr,{children:[jsxs(Hr,{className:u.dropdownItemText,children:[jsx(Tag,{className:T(u.menuIconSize,"mr-2 text-gray-500")}),jsx("span",{children:"Metadata"})]}),jsx(uo,{children:jsxs(Jr,{className:"p-0 w-64 bg-gray-50 rounded-2xl border-none shadow-2xl",onInteractOutside:f=>f.preventDefault(),children:[jsx("div",{className:"bg-white shadow-xs rounded-2xl",children:jsxs("div",{className:"space-y-3 p-3",onClick:f=>f.stopPropagation(),children:[jsxs("div",{className:"space-y-1.5",children:[jsx("label",{className:T("font-medium text-gray-700",u.labelText),children:"Key"}),jsx(nt,{value:o,onChange:f=>a(f.target.value),placeholder:"e.g. customer_id",className:T(u.inputHeight,u.dropdownItemText),onClick:f=>f.stopPropagation(),onKeyDown:f=>f.stopPropagation()})]}),jsxs("div",{className:"space-y-1.5",children:[jsx("label",{className:T("font-medium text-gray-700",u.labelText),children:"Value"}),jsx(nt,{value:i,onChange:f=>s(f.target.value),placeholder:"e.g. 12345",className:T(u.inputHeight,u.dropdownItemText),onClick:f=>f.stopPropagation(),onKeyDown:f=>{f.stopPropagation(),f.key==="Enter"&&p();}})]})]})}),jsx("div",{className:"p-3",children:jsx(V,{size:"sm",className:T("w-full group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay ring-1 bg-gray-900 hover:bg-gray-900 hover:opacity-80 text-white ring-gray-900 gap-2",u.dropdownItemText,u.inputHeight),onClick:f=>{f.stopPropagation(),p();},disabled:!o.trim()||!i.trim(),children:"Add filter"})})]})})]})]})]})]})}function FR({projectId:e,metadata:t,dateRange:r,statusFilter:n,searchQuery:o}){let{fetchWithAuth:a}=De(),i=useCallback(async s=>{let l=toast.loading(`Preparing ${s.toUpperCase()} export...`);try{let c=new URL("/v1/extractions/download");if(c.searchParams.append("format",s),c.searchParams.append("origin_dot_id",e),t){let h=Object.fromEntries(Object.entries(t).filter(([y,p])=>p&&p.trim()!==""));Object.keys(h).length>0&&c.searchParams.append("metadata",JSON.stringify(h));}r?.from&&c.searchParams.append("from_date",format(r.from,"yyyy-MM-dd")),r?.to&&c.searchParams.append("to_date",format(r.to,"yyyy-MM-dd")),n&&c.searchParams.append("human_review_status",n),o&&c.searchParams.append("filename",o);let u=await a(c.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!u.ok){if(u.status===404){let h=await u.json().catch(()=>({}));if((h?.details?.error||h?.detail||"No extractions found").includes("No extractions found")){let p=r?.from&&r?.to?`between ${format(r.from,"MMM d, yyyy")} and ${format(r.to,"MMM d, yyyy")}`:r?.from?`after ${format(r.from,"MMM d, yyyy")}`:r?.to?`before ${format(r.to,"MMM d, yyyy")}`:"for the selected criteria";toast.dismiss(l),toast.warning(`No extractions found ${p}. Try adjusting your filters.`,{duration:5e3});return}}throw toast.dismiss(l),new Error(`Export failed: ${u.statusText}`)}let m=(await u.json()).download_url;window.open(m,"_blank"),toast.dismiss(l),toast.success("Export ready! Download started.");}catch(c){console.error("Export error:",c),toast.dismiss(l),toast.error("Failed to generate export");}},[e,t,r,n,o]);return jsxs(dr,{children:[jsx(fr,{asChild:true,children:jsxs(V,{variant:"outline",size:"sm",className:"text-2xs h-7 py-0 px-0.5",children:[jsx(Download,{className:"size-3.5 mr-1"}),jsx("span",{children:"Export"})]})}),jsxs(pr,{align:"end",className:"min-w-44",children:[jsxs(ge,{onClick:()=>i("csv"),children:[jsx(FileText,{className:"h-3.5 w-3.5 mr-2"})," CSV"]}),jsxs(ge,{onClick:()=>i("xlsx"),children:[jsx(FileSpreadsheet,{className:"h-3.5 w-3.5 mr-2"})," Excel"]}),jsxs(ge,{onClick:()=>i("jsonl"),children:[jsx(FileJson,{className:"h-3.5 w-3.5 mr-2"})," JSONL"]})]})]})}function xh({extractionId:e,filename:t,className:r}){let[n,o]=useState(null),[a,i]=useState(false),[s,l]=useState(true),[c,u]=useState(null),{fetchWithAuth:d}=De();return useEffect(()=>{let m=true,h=null;return (async()=>{try{l(!0),u(null);let p=await d(`/v1/extractions/${e}/thumbnail`,{headers:{Accept:"image/png,image/jpeg,*/*"}});if(!p.ok)throw new Error(`Failed to load thumbnail: ${p.status}`);let f=await p.blob();if(!m)return;(f.type||p.headers.get("content-type")||"application/octet-stream").startsWith("image/")?(h=URL.createObjectURL(f),o(h),i(!0)):(o(null),i(!1));}catch(p){if(!m)return;console.error(`Failed to load thumbnail for extraction ${e}`,p),u("Failed to load thumbnail"),o(null),i(false);}finally{m&&l(false);}})(),()=>{m=false,h&&URL.revokeObjectURL(h);}},[e]),s?jsx(Re,{className:T("h-6 w-6 rounded-xs",r)}):!n||!a||c?jsxs("div",{className:T("h-6 w-6 rounded-xs border bg-muted flex items-center justify-center text-muted-foreground",r),children:[jsx(FileIcon,{className:"h-4 w-4","aria-hidden":"true"}),jsx("span",{className:"sr-only",children:t})]}):jsx("div",{className:T("h-6 w-6 overflow-hidden rounded-xs border bg-muted/30",r),children:jsx("img",{src:n,alt:`Preview of ${t}`,className:"h-full w-full object-cover",loading:"lazy"})})}function wh({humanReviewStatus:e,style:t="icon"}){return e==="review_required"?t==="badge"?jsx(dn,{variant:"outline",className:"bg-orange-50 text-orange-800 border-orange-200 text-xs",children:"Review required"}):jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(jc,{className:"size-4 text-[#D25F5F] border-none"})}),jsx(et,{children:"Review required"})]}):e==="reviewed"?t==="badge"?jsx(dn,{variant:"outline",className:"bg-blue-50 text-blue-800 border-blue-200 text-xs",children:"Reviewed"}):jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(Ba,{className:"size-4 text-[#5F6AD2] border-none"})}),jsx(et,{children:"Reviewed by human"})]}):t==="badge"?jsx(dn,{variant:"outline",className:"bg-emerald-50 text-emerald-800 border-emerald-200 text-xs",children:"Success"}):jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(Ba,{className:"size-4 text-[#50CE89] border-none"})}),jsx(et,{children:"Validated automatically"})]})}function BR({extractions:e,isLoading:t,paginationMetadata:r,onPrevPage:n,onNextPage:o,onExtractionClick:a,onDeleteClick:i,onStatusChange:s,isCollapsed:l,onCollapseToggle:c,deletingId:u,updatingId:d,showUploadButton:m,onNewExtraction:h}){let y=ei(),p=y?.selectedExtractionId??null;return jsx("div",{className:`flex flex-shrink-0 ${l?"w-[194px]":"w-[330px]"} overflow-auto pt-0`,children:jsx("div",{className:"rounded-none bg-card flex flex-col flex-1 min-h-0 overflow-hidden border-t border-gray-200 border-r",children:!t&&e.length===0?jsxs("div",{className:"flex flex-col items-center justify-center p-8 gap-4 flex-1",children:[jsxs("div",{className:"text-center space-y-2",children:[jsx("p",{className:"text-sm text-muted-foreground",children:"No extractions yet."}),jsx("p",{className:"text-2xs text-muted-foreground",children:"Upload and process files to see results here."})]}),m&&jsxs(V,{variant:"outline",size:"sm",onClick:()=>{if(h){let f=h();y?.setSelectedExtractionId(f);}},className:"gap-2 rounded-none",children:[jsx(Upload,{className:"h-4 w-4"}),"Upload file"]})]}):jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[jsx("div",{className:"border-b bg-background",children:jsxs("div",{className:"flex justify-between items-center h-[38px] gap-2 pl-2 pr-1",children:[jsxs("div",{className:"flex items-center gap-2 cursor-pointer",onClick:c,children:[jsx(ChevronsLeft,{className:`h-4 w-4 transition-transform duration-300 ease-in-out ${l?"rotate-180":""}`}),jsx("span",{className:"text-2xs text-muted-foreground",children:l?"Expand":"Collapse"})]}),jsxs("div",{className:"flex items-center gap-0",children:[jsxs(V,{variant:"ghost",size:l?"iconSm":"sm",className:"text-2xs group px-2",onClick:n,disabled:!r?.before||t,children:[jsx(ChevronLeft,{className:"h-4 w-4 opacity-60 -translate-x-0.5 group-hover:-translate-x-3 group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),jsx(ChevronLeft,{className:"h-4 w-4 -ml-6 translate-x-2.5 opacity-0 group-hover:-translate-x-0 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),l?"":"Prev"]}),jsxs(V,{variant:"ghost",size:l?"iconSm":"sm",className:"text-2xs group px-2",onClick:o,disabled:!r?.after||t,children:[l?"":"Next",jsx(ChevronRight,{className:"h-4 w-4 opacity-60 group-hover:translate-x-3 group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),jsx(ChevronRight,{className:"h-4 w-4 -ml-6 -translate-x-2.5 opacity-0 group-hover:translate-x-0.5 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"})]})]})]})}),jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:jsxs(Ko,{className:"table-fixed w-full relative",children:[jsxs("colgroup",{children:[jsx("col",{style:{width:"136px"}}),!l&&jsx("col",{style:{width:"136px"}}),jsx("col",{style:{width:"24px"}}),jsx("col",{style:{width:"32px"}})]}),jsx(Go,{className:" border-blue-200",children:t?[...Array(5)].map((f,x)=>jsxs(Lr,{className:"!h-8",children:[jsx(wt,{className:"whitespace-nowrap text-2xs !h-8",children:jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[jsx(Re,{className:"h-4 w-4 shrink-0"}),jsx(Re,{className:"h-3 w-20"})]})}),!l&&jsx(wt,{className:"whitespace-nowrap text-2xs px-2 !h-8 p-0",children:jsx(Re,{className:"h-3 w-24"})}),jsx(wt,{className:"!h-8 p-0 justify-center items-center",children:jsx(Re,{className:"h-3.5 w-3.5 rounded-full"})}),jsx(wt,{className:"!h-8 p-0 justify-center items-center",children:jsx(Re,{className:"h-6 w-6"})})]},x)):e.map(f=>{let x=p===f.id;return jsxs(Lr,{className:`!h-8 p-0 cursor-pointer group last:border-b-0 first:border-t-0 ${x?"bg-muted/80 hover:bg-muted":"hover:bg-muted/30"}`,onClick:()=>{y?.setSelectedExtractionId(f.id),a(f);},children:[jsx(wt,{className:"whitespace-nowrap text-2xs !h-8 flex items-center justify-between gap-2",children:jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[jsx(xh,{extractionId:f.id,filename:f.file.filename||"Unknown",className:"shrink-0 h-4 w-4"}),jsx("div",{className:"min-w-0 flex-1",children:jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx("span",{className:"inline-block w-fit max-w-full truncate font-medium align-middle",children:f.file.filename||"Unknown"})}),jsx(et,{children:f.file.filename||"Unknown"})]})})]})}),!l&&jsx(wt,{className:"whitespace-nowrap text-2xs px-2 text-muted-foreground !h-8 p-0",children:new Date(f.created_at).toLocaleString()}),jsx(wt,{className:" !h-8 p-0 justify-center items-center gap-2",children:jsx(wh,{humanReviewStatus:f.human_review_status})}),jsx(wt,{className:" !h-8 p-0 justify-center items-center gap-2",children:jsxs(dr,{children:[jsx(fr,{asChild:true,children:jsx(V,{size:"iconSm",variant:"ghost",className:"h-6 w-6",onClick:g=>g.stopPropagation(),disabled:u===f.id||d===f.id,children:u===f.id||d===f.id?jsx(Loader2,{className:"h-3.5 w-3.5 animate-spin"}):jsx(MoreVertical,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),jsxs(pr,{align:"end",className:"w-52",children:[f.human_review_status==="review_required"&&jsxs(ge,{onClick:g=>{s(g,f.id,"reviewed");},children:[jsx(ShieldCheck,{className:"h-3.5 w-3.5 mr-2"}),jsx("span",{children:"Mark as reviewed"})]}),(f.human_review_status==="success"||f.human_review_status==="reviewed")&&jsxs(ge,{className:"text-xs",onClick:g=>{s(g,f.id,"review_required");},children:[jsx(ShieldUser,{className:"h-3.5 w-3.5 mr-2 "}),jsx("span",{className:"text-xs",children:"Mark as requiring review"})]}),jsxs(ge,{className:"text-destructive focus:text-destructive focus:bg-destructive/10 text-xs",onClick:g=>{i(g,f.id);},children:[jsx(Trash2,{className:"h-3.5 w-3.5 mr-2 text-destructive"}),jsx("span",{children:"Delete extraction"})]})]})]})})]},f.id)})})]})}),m&&jsx("div",{className:"border-t bg-background items-center justify-center flex",children:jsxs(V,{variant:"ghost",size:"sm",className:"text-xs rounded-none text-muted-foreground hover:text-foreground py-4 w-full h-full",onClick:()=>{if(h){let f=h();y?.setSelectedExtractionId(f);}},children:[jsx(Upload,{className:"h-4 w-4 mr-2"}),"Upload file"]})})]})})})}function eV(e){return useMemo(()=>{let t=[{label:"Created At",value:"created_at"},{label:"Review Status",value:"human_review_status"}],r=[],n=["string","number","integer","boolean"],o=(a,i,s)=>{Object.keys(a).forEach(l=>{let c=a[l],u=i?`${i}.${l}`:l,d=c.title||l.charAt(0).toUpperCase()+l.slice(1).replace(/_/g," "),m=s?`${s} \u203A ${d}`:d;if(c.type!=="array"){if(c.type==="object"&&c.properties){o(c.properties,u,m);return}n.includes(c.type)&&r.push({label:m,value:`completion.${u}`});}});};return e[0]?.json_schema?.properties&&o(e[0].json_schema.properties,"",""),{builtInFields:t,propertyFields:r}},[e])}function tV(e){return useMemo(()=>[...e.builtInFields,...e.propertyFields],[e])}function rV(e){return useMemo(()=>{let t=new Map;for(let r of e){let n=r.predictions;n&&typeof n=="object"&&t.set(r.id,n);}return t},[e])}function nV(e,t){return useMemo(()=>{if(!e.startsWith("completion."))return null;let r=e.replace("completion.",""),n=t.find(a=>a.value===e),o=r.split(".").pop()||r;return {key:r,label:n?.label||o.charAt(0).toUpperCase()+o.slice(1).replace(/_/g," ")}},[e,t])}function zR(e){if(typeof e=="string"&&/^[-+]?\d+(?:\.\d+)?$/.test(e.trim())){let t=Number(e);return Number.isFinite(t)?t:e}return e}var UR={review_required:0,reviewed:1,success:2};function oV(e,t,r,n){return useMemo(()=>{if(!t||e.length===0)return e;let o=[...e].sort((a,i)=>{let s,l;if(t==="created_at")s=new Date(a.created_at).getTime(),l=new Date(i.created_at).getTime();else if(t==="human_review_status")s=UR[a.human_review_status]??3,l=UR[i.human_review_status]??3;else if(t.startsWith("completion.")){let d=t.replace("completion.",""),m=n.get(a.id),h=n.get(i.id);s=Ld(m,d),l=Ld(h,d);}if(s==null&&l==null)return 0;if(s==null)return 1;if(l==null)return -1;s=zR(s),l=zR(l);let c=typeof s,u=typeof l;return c==="boolean"&&u==="boolean"?s===l?0:s?-1:1:c==="number"&&u==="number"?s-l:c==="string"&&u==="string"?s.toLowerCase().localeCompare(l.toLowerCase()):String(s).localeCompare(String(l))});return r==="desc"?o.reverse():o},[e,t,r,n])}function _h(e,t,r){let n=eV(e),o=tV(n),a=rV(e),i=oV(e,t,r,a),s=nV(t,o);return {sortFields:n,allSortFields:o,parsedPredictions:a,sortedExtractions:i,sortFieldInfo:s}}var yV=()=>{let e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",t="extr_";for(let r=0;r<21;r++)t+=e.charAt(Math.floor(Math.random()*e.length));return t};function vV({projectId:e,extractionId:t,onNavigate:r,initialFilters:n=[],visibility:{search:o=false,metadataFilter:a=false,filterMenu:i=true,displayMenu:s=true,exportMenu:l=true,uploadButton:c=true,extractionDisplayOptions:{allowEditing:u=false,showReasoning:d=false,showTabs:m=true}={}}={},defaultView:h="form"}){let y=useQueryClient(),{fetchWithAuth:p}=De(),f=ei(),[x,g]=useState(true),v=useRef(null),[w,N]=useState(null),S=useCallback(()=>{let he=yV();return v.current=he,N(he),r({extractionId:he}),he},[r]);useEffect(()=>{v.current&&t!==v.current&&(v.current=null,N(null));},[t]),useEffect(()=>{t&&f?.selectedExtractionId!==t&&f?.setSelectedExtractionId(t);},[t,f]);let _=t===v.current||t===w,{data:P}=Lo({origin_dot_id:e,human_review_status:"review_required",limit:10,order:"desc"}),R=useMemo(()=>{if(!t||t==="null"||!P?.data||P.data.length===0)return null;let he=P.data,_t=he.findIndex(Ot=>Ot.id===t);if(_t!==-1){let Ot=(_t+1)%he.length;return he[Ot].id}return he.length>0?he[0].id:null},[t,P]),E=useCallback(()=>{R?r({extractionId:R}):toast.info("No more items to review");},[R,r]),{data:C}=useQuery({queryKey:$t.detail(t||"null"),queryFn:async()=>{if(!t)return null;let he=await p(`/v1/extractions/${t}`);if(he.status===404)return null;if(!he.ok){let _t=await he.text();throw new Error(`Failed to fetch extraction: ${he.status} ${_t}`)}return he.json()},enabled:!!t&&!_,retry:(he,_t)=>_t.message?.includes("404")?false:he<3}),[b,O]=useState(null),[D,k]=useState(null),[I,F]=useState(false),[Z,pe]=useState(20),[ie,J]=useState("created_at"),[ue,re]=useState("desc"),[X,$]=useState(n),L=useMemo(()=>{let he=X.find(Ot=>Ot.field==="created_date"&&Ot.operator==="after"),_t=X.find(Ot=>Ot.field==="created_date"&&Ot.operator==="before");return {from:he?.value?new Date(he.value):void 0,to:_t?.value?new Date(_t.value):void 0}},[X]),le=useMemo(()=>{let he=X.find(_t=>_t.field==="status");if(he&&he.operator!=="is_not")return he?.value},[X]),ae=useMemo(()=>{let he=X.filter(Ot=>Ot.field==="metadata"&&Ot.operator==="is"&&Ot.metadataKey);if(he.length===0)return;let _t={};for(let Ot of he)Ot.metadataKey&&(_t[Ot.metadataKey]=String(Ot.value));return _t},[X]),[Oe,ye]=useState(""),[ft,zt]=useState("");useEffect(()=>{let he=setTimeout(()=>{zt(Oe),O(null),k(null);},500);return ()=>clearTimeout(he)},[Oe]);let st=Lo({before:b||void 0,after:D||void 0,limit:Z,order:ie==="created_at"?ue:"desc",origin_dot_id:e,filename:ft||void 0,human_review_status:le,from_date:L.from?format(L.from,"yyyy-MM-dd"):void 0,to_date:L.to?format(L.to,"yyyy-MM-dd"):void 0,metadata:ae}),Et=st.data?.data||[],tt=st.data?.list_metadata,xe=useMemo(()=>{let he=Et,_t=X.find(Rr=>Rr.field==="status");_t&&_t.operator==="is_not"&&(he=he.filter(Rr=>Rr.human_review_status!==_t.value));let Ot=X.filter(Rr=>Rr.field==="metadata"&&Rr.operator==="contains"&&Rr.metadataKey);for(let Rr of Ot)if(Rr.metadataKey){let Kd=String(Rr.value).toLowerCase();he=he.filter(Gd=>{let Vc=Gd.metadata?.[Rr.metadataKey];return Vc===void 0?false:Vc.toLowerCase().includes(Kd)});}return he},[Et,X]),{sortFields:me,allSortFields:_e,sortedExtractions:pt}=_h(xe,ie,ue),{mutateAsync:Fe}=Wf(),{mutateAsync:Me}=hl(),[ce,G]=useState(null),[U,H]=useState(null),[je,Ue]=useState(null),Le=(he,_t)=>{he.stopPropagation(),Ue(_t);},Sn=async()=>{if(je){G(je);try{await Fe(je),Ue(null);}finally{G(null);}}},W=async(he,_t,Ot)=>{he.stopPropagation(),H(_t);try{await Me({extractionId:_t,human_review_status:Ot}),y.invalidateQueries({queryKey:[...$t.all,"count"]}),y.invalidateQueries({queryKey:$t.lists()});}finally{H(null);}},Pe=useCallback(()=>{tt?.after&&(k(tt.after),O(null));},[tt]),Pt=useCallback(()=>{tt?.before&&(O(tt.before),k(null));},[tt]),Hs=useCallback(he=>{r({extractionId:he.id});},[r]);return jsxs("div",{className:"flex-1 flex flex-col min-h-0 gap-0 overflow-hidden",children:[jsxs("div",{className:"flex items-center justify-between gap-2 p-2",children:[i&&jsx(vh,{filters:X,onFiltersChange:$,showMetadataFilter:a}),jsxs("div",{className:"flex items-center gap-2",children:[o&&jsxs("div",{className:"relative w-40",children:[jsx(Search,{className:"absolute left-2 top-1.75 h-3.5 w-3.5 text-muted-foreground"}),jsx(nt,{placeholder:"Search file...",value:Oe,onChange:he=>ye(he.target.value),className:"pl-7 h-7 !text-2xs"})]}),s&&jsxs(nr,{open:I,onOpenChange:F,children:[jsx(or,{asChild:true,children:jsxs(V,{variant:"outline",size:"sm",className:"text-2xs h-7 py-0 px-0.5",children:[jsx(Settings2,{className:"size-3.5 mr-1"}),jsx("span",{children:"Display"})]})}),jsx(ar,{className:"w-72 p-3",align:"end",children:jsx("div",{className:"space-y-3",children:jsxs("div",{className:"flex flex-col gap-2",children:[jsxs("label",{className:"text-xs font-semibold text-gray-900 flex items-center gap-1.5",children:[jsx(ArrowUpWideNarrowIcon,{className:"h-3.5 w-3.5"}),"Ordering"]}),jsxs("div",{className:"flex items-center gap-2",children:[jsxs(dr,{children:[jsx(fr,{asChild:true,children:jsxs(V,{variant:"outline",className:"flex-1 min-w-0 justify-between text-xs h-8",children:[jsx("span",{className:"truncate",children:_e.find(he=>he.value===ie)?.label||"Select field"}),jsx(ChevronRight,{className:"h-3.5 w-3.5 ml-2 shrink-0 opacity-50 rotate-90"})]})}),jsxs(pr,{align:"start",className:"w-56",children:[jsx(kl,{value:ie,onValueChange:J,children:me.builtInFields.map(he=>jsx(Rl,{value:he.value,className:"text-xs",children:he.label},he.value))}),me.propertyFields.length>0&&jsxs(Fragment,{children:[jsx(fo,{}),jsxs(Vr,{children:[jsxs(Hr,{className:"text-xs",children:[jsx(Database,{className:"h-3.5 w-3.5 mr-2"}),"Extracted Properties"]}),jsx(Jr,{className:"max-h-64 max-w-56 overflow-y-auto",children:jsx(kl,{value:ie,onValueChange:J,children:me.propertyFields.map(he=>jsx(Rl,{value:he.value,className:"text-xs",children:jsx("span",{className:"truncate",children:he.label})},he.value))})})]})]})]})]}),jsxs("div",{className:"flex gap-2 shrink-0",children:[jsx("button",{onClick:()=>re("asc"),className:`flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs rounded transition-colors ${ue==="asc"?"bg-indigo-50 text-indigo-700 font-medium":"bg-gray-50 text-gray-600 hover:bg-gray-100"}`,children:jsx(ArrowUpWideNarrowIcon,{className:"h-4 w-4"})}),jsx("button",{onClick:()=>re("desc"),className:`flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs rounded transition-colors ${ue==="desc"?"bg-indigo-50 text-indigo-700 font-medium":"bg-gray-50 text-gray-600 hover:bg-gray-100"}`,children:jsx(ArrowDownWideNarrowIcon,{className:"h-4 w-4"})})]})]})]})})})]}),l&&jsx(FR,{projectId:e,metadata:ae,dateRange:L,statusFilter:le,searchQuery:ft})]})]}),jsxs("div",{className:"flex flex-row gap-0 flex-1 min-h-0 overflow-hidden",children:[jsx(BR,{extractions:pt,isLoading:st.isLoading,paginationMetadata:tt,onPrevPage:Pt,onNextPage:Pe,onExtractionClick:Hs,onDeleteClick:Le,onStatusChange:W,isCollapsed:x,onCollapseToggle:()=>g(!x),deletingId:ce,updatingId:U,onNewExtraction:S,showUploadButton:c}),jsx("div",{className:"flex-col min-w-0 flex flex-1 min-h-0",children:t?jsx("div",{className:"bg-white flex flex-col flex-1 min-h-0 gap-3",children:jsx("div",{className:"flex-1 flex flex-col min-h-0 border-y border-gray-200",children:jsx(kx,{extractionId:t,projectId:e,isNewExtraction:_,extractionDisplayOptions:{view:h,allowEditing:u,showReasoning:d,showTabs:m},continueButtonOptions:{onClick:E,label:C?.human_review_status==="review_required"?"Mark as reviewed":"Save draft"}})})}):jsx("div",{className:"flex-1 flex items-center justify-center border-t border-gray-200",children:jsxs("div",{className:"flex flex-col items-center justify-center max-w-md text-center p-8 space-y-6",children:[jsxs("div",{className:"relative",children:[jsx("div",{className:"absolute inset-0 bg-indigo-100/60 rounded-full blur-xl animate-pulse"}),jsx("div",{className:"relative flex items-center justify-center w-20 h-20 rounded-full bg-gradient-to-br from-indigo-50 to-slate-100 border border-indigo-100/50 shadow-sm",children:jsx(FileSearch,{className:"w-9 h-9 text-indigo-400",strokeWidth:1.5})})]}),jsxs("div",{className:"space-y-2",children:[jsx("h3",{className:"text-lg font-semibold text-slate-800 tracking-tight",children:"Select an extraction"}),jsx("p",{className:"text-sm text-slate-500 leading-relaxed",children:"Choose an extraction from the list to view and review its details"})]}),jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 rounded-full bg-slate-100/80 border border-slate-200/60",children:[jsx(MousePointerClick,{className:"w-4 h-4 text-slate-400"}),jsx("span",{className:"text-xs text-slate-500 font-medium",children:"Click on any item in the list"})]})]})})})]}),jsx(vo,{open:je!==null,onOpenChange:he=>!he&&Ue(null),children:jsxs(bo,{className:"p-0 gap-0 bg-gray-50 rounded-2xl border-none shadow-2xl",children:[jsx("div",{className:"bg-white shadow-xs rounded-2xl",children:jsxs(xo,{className:"p-6 pb-4",children:[jsx(_o,{className:"text-lg font-medium text-slate-900",children:"Delete extraction"}),jsx(So,{children:"Are you sure you want to delete this extraction? This action cannot be undone."})]})}),jsxs(wo,{className:"p-4",children:[jsx(wa,{disabled:ce!==null,children:"Cancel"}),jsx(No,{onClick:Sn,disabled:ce!==null,className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay ring-1 bg-destructive hover:bg-destructive hover:opacity-80 text-white ring-destructive gap-2",children:ce!==null?jsxs(Fragment,{children:[jsx(Loader2,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})}function Sh({className:e,...t}){return jsx("div",{"data-slot":"card",className:T("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Nh({className:e,...t}){return jsx("div",{"data-slot":"card-header",className:T("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function Ch({className:e,...t}){return jsx("div",{"data-slot":"card-title",className:T("leading-none font-semibold",e),...t})}function Eh({className:e,...t}){return jsx("div",{"data-slot":"card-content",className:T("px-6",e),...t})}function TV({title:e,onSelectExtraction:t,onNewExtractionClick:r,visibility:{displayPopover:n=true,statusColumn:o=false,dateColumn:a=true,search:i=true,filters:s=false,metadataFilter:l=false}={},initialFilters:c=[]}={}){let{project:u}=Qr(),d=useQueryClient(),m=ei(),h=m?.selectedExtractionId??null,[y,p]=useState(null),[f,x]=useState(null),[g,v]=useState(c),w=useMemo(()=>{let H=g.find(Le=>Le.field==="created_date"&&Le.operator==="after"),je=g.find(Le=>Le.field==="created_date"&&Le.operator==="before"),Ue=g.find(Le=>Le.field==="created_date"&&Le.operator==="within");return Ue?{from:Ue.value instanceof Date?Ue.value:new Date(Ue.value),to:Ue.endValue}:{from:H?.value?H.value instanceof Date?H.value:new Date(H.value):void 0,to:je?.value?je.value instanceof Date?je.value:new Date(je.value):void 0}},[g]),N=useMemo(()=>{let H=g.find(je=>je.field==="status");if(H&&H.operator!=="is_not")return H?.value},[g]),S=useMemo(()=>{let H=g.filter(Ue=>Ue.field==="metadata"&&Ue.operator==="is"&&Ue.metadataKey);if(H.length===0)return;let je={};for(let Ue of H)Ue.metadataKey&&(je[Ue.metadataKey]=String(Ue.value));return je},[g]),[_,P]=useState(false),[R,E]=useState(20),[C,b]=useState("created_at"),[O,D]=useState("desc"),[k,I]=useState(""),[F,Z]=useState("");useEffect(()=>{let H=setTimeout(()=>{Z(k),p(null),x(null);},500);return ()=>clearTimeout(H)},[k]);let pe=Lo({before:y||void 0,after:f||void 0,limit:R,order:C==="created_at"?O:"desc",origin_dot_id:u.id,filename:F||void 0,human_review_status:N,from_date:w.from?format(w.from,"yyyy-MM-dd"):void 0,to_date:w.to?format(w.to,"yyyy-MM-dd"):void 0,metadata:S}),ie=pe.data?.data||[],J=pe.data?.list_metadata,ue=useMemo(()=>{let H=ie,je=g.find(Le=>Le.field==="status");je&&je.operator==="is_not"&&(H=H.filter(Le=>Le.human_review_status!==je.value));let Ue=g.filter(Le=>Le.field==="metadata"&&Le.operator==="contains"&&Le.metadataKey);for(let Le of Ue)if(Le.metadataKey){let Sn=String(Le.value).toLowerCase();H=H.filter(W=>{let Pe=W.metadata?.[Le.metadataKey];return Pe===void 0?false:Pe.toLowerCase().includes(Sn)});}return H},[ie,g]),{sortFields:re,allSortFields:X,sortedExtractions:$,sortFieldInfo:L,parsedPredictions:le}=_h(ue,C,O),ae=L!==null,{mutateAsync:Oe}=Wf(),{mutateAsync:ye}=hl(),[ft,zt]=useState(null),[st,Et]=useState(null),[tt,xe]=useState(null),[me,_e]=useState(null),pt=(H,je)=>{H.stopPropagation(),_e(je),xe(null);},Fe=async()=>{if(me){zt(me);try{await Oe(me),_e(null);}finally{zt(null);}}},Me=async(H,je,Ue)=>{H.stopPropagation(),Et(je),xe(null);try{await ye({extractionId:je,human_review_status:Ue}),d.invalidateQueries({queryKey:[...$t.all,"count"]}),d.invalidateQueries({queryKey:$t.lists()});}finally{Et(null);}},ce=useCallback(()=>{J?.after&&(x(J.after),p(null));},[J]),G=useCallback(()=>{J?.before&&(p(J.before),x(null));},[J]),U=useCallback(H=>{m?.setSelectedExtractionId(H.id),t&&t(H);},[t,m]);return jsxs(Sh,{className:"shadow-none gap-3 border-none py-0 flex flex-1 min-h-0",children:[jsx(Nh,{className:"px-0 pb-0 gap-0",children:jsxs("div",{className:"flex items-center justify-between gap-2",children:[e&&jsx(Ch,{children:e}),s&&jsx(vh,{size:"md",filters:g,onFiltersChange:v,showMetadataFilter:l}),jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[i&&jsxs("div",{className:"relative w-40",children:[jsx(Search,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),jsx(nt,{placeholder:"Search file...",value:k,onChange:H=>I(H.target.value),className:"pl-8 h-8 !text-xs"})]}),n&&jsxs(nr,{open:_,onOpenChange:P,children:[jsx(or,{asChild:true,children:jsxs(V,{variant:"outline",size:"sm",className:"text-xs",children:[jsx(SlidersHorizontal,{className:"h-3.5 w-3.5 mr-1.5"}),jsx("span",{children:"Display"})]})}),jsx(ar,{className:"w-80 p-4",align:"end",children:jsxs("div",{className:"space-y-4",children:[jsxs("div",{children:[jsx("label",{className:"text-xs font-semibold text-gray-900 mb-2 block",children:"Items per page"}),jsx("div",{className:"grid grid-cols-5 gap-2",children:[1,10,25,50,100].map(H=>jsx("button",{onClick:()=>E(H),className:`px-3 py-2 text-xs rounded border transition-all ${R===H?"bg-indigo-50 border-indigo-500 text-indigo-700 font-semibold":"border-gray-200 text-gray-700 hover:bg-gray-50 hover:border-gray-300"}`,children:H},H))})]}),jsx("div",{className:"border-t border-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("label",{className:"text-xs font-semibold text-gray-900 block",children:"Sort by"}),jsxs("div",{className:"flex items-center gap-2",children:[jsxs(dr,{children:[jsx(fr,{asChild:true,children:jsxs(V,{variant:"outline",className:"flex-1 min-w-0 justify-between text-xs h-9",children:[jsx("span",{className:"truncate",children:X.find(H=>H.value===C)?.label||"Select field"}),jsx(ChevronRight,{className:"h-3.5 w-3.5 ml-2 shrink-0 opacity-50 rotate-90"})]})}),jsxs(pr,{align:"start",className:"w-56",children:[jsx(kl,{value:C,onValueChange:b,children:re.builtInFields.map(H=>jsx(Rl,{value:H.value,className:"text-xs",children:H.label},H.value))}),re.propertyFields.length>0&&jsxs(Fragment,{children:[jsx(fo,{}),jsxs(Vr,{children:[jsxs(Hr,{className:"text-xs",children:[jsx(Database,{className:"h-3.5 w-3.5 mr-2"}),"Extracted Properties"]}),jsx(Jr,{className:"max-h-64 max-w-56 overflow-y-auto",children:jsx(kl,{value:C,onValueChange:b,children:re.propertyFields.map(H=>jsx(Rl,{value:H.value,className:"text-xs",children:jsx("span",{className:"truncate",children:H.label})},H.value))})})]})]})]})]}),jsxs("div",{className:"flex gap-2 shrink-0",children:[jsx("button",{onClick:()=>D("asc"),className:`flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs rounded transition-colors ${O==="asc"?"bg-indigo-50 text-indigo-700 font-medium":"bg-gray-50 text-gray-600 hover:bg-gray-100"}`,children:jsx(ArrowUpWideNarrowIcon,{className:"h-4 w-4"})}),jsx("button",{onClick:()=>D("desc"),className:`flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs rounded transition-colors ${O==="desc"?"bg-indigo-50 text-indigo-700 font-medium":"bg-gray-50 text-gray-600 hover:bg-gray-100"}`,children:jsx(ArrowDownWideNarrowIcon,{className:"h-4 w-4"})})]})]})]})]})})]})]})]})}),jsx(Eh,{className:"flex flex-col flex-1 min-h-0 p-0 border border-gray-200 rounded-md",children:jsx("div",{className:"rounded-md bg-card flex flex-col flex-1 min-h-0 overflow-hidden",children:pe.isLoading?jsx("div",{className:"flex flex-col flex-1 min-h-0",children:jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:jsxs(Ko,{className:"table-fixed w-full relative",children:[jsxs("colgroup",{children:[jsx("col",{style:{width:ae?"35%":a&&o?"40%":a||o?"50%":"90%"}}),ae&&jsx("col",{style:{width:"25%"}}),a&&jsx("col",{style:{width:ae?"20%":o?"30%":"40%"}}),o&&jsx("col",{style:{width:ae?"12%":a?"20%":"40%"}}),jsx("col",{style:{width:ae?"8%":"10%"}})]}),jsx(yi,{className:"sticky top-0 left-0 right-0 z-10 bg-white border-green-200",children:jsxs(Lr,{className:"border-none p-0 h-4",children:[jsx(xr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"File"})}),ae&&jsx(xr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:L?.label})}),a&&jsx(xr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"Date"})}),o&&jsx(xr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"Status"})}),jsx(xr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full"})})]})}),jsx(Go,{children:[...Array(5)].map((H,je)=>jsxs(Lr,{className:"h-12.5",children:[jsx(wt,{children:jsxs("div",{className:"flex items-center gap-3",children:[jsx(Re,{className:"h-10 w-10 shrink-0"}),jsx(Re,{className:"h-4 w-3/4"})]})}),ae&&jsx(wt,{children:jsx(Re,{className:"h-4 w-24"})}),a&&jsx(wt,{children:jsx(Re,{className:"h-4 w-32"})}),o&&jsx(wt,{children:jsx(Re,{className:"h-6 w-24"})}),jsx(wt,{children:jsx(Re,{className:"h-6 w-6"})})]},je))})]})})}):$.length===0?jsxs("div",{className:"flex flex-col items-center justify-center p-8 gap-4 flex-1",children:[jsxs("div",{className:"text-center space-y-2",children:[jsx("p",{className:"text-sm text-muted-foreground",children:"No extractions yet."}),jsx("p",{className:"text-xs text-muted-foreground",children:"Upload and process files to see results here."})]}),r&&jsxs(V,{variant:"outline",size:"sm",onClick:r,className:"gap-2",children:[jsx(Upload,{className:"h-4 w-4"}),"Upload file"]})]}):jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:jsxs(Ko,{className:"table-fixed w-full relative",children:[jsxs("colgroup",{children:[jsx("col",{style:{width:ae?"35%":a&&o?"40%":a||o?"50%":"90%"}}),ae&&jsx("col",{style:{width:"25%"}}),a&&jsx("col",{style:{width:ae?"20%":o?"30%":"40%"}}),o&&jsx("col",{style:{width:ae?"12%":a?"20%":"40%"}}),jsx("col",{style:{width:ae?"8%":"10%"}})]}),jsx(yi,{className:"sticky top-0 left-0 right-0 z-10 bg-white border-green-200",children:jsxs(Lr,{className:"border-none p-0 h-4",children:[jsx(xr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"File"})}),ae&&jsx(xr,{className:"text-xs text-black p-0",children:jsxs("button",{className:"border-b px-3 py-2 items-center flex w-full h-full gap-1 hover:bg-muted/50 transition-colors cursor-pointer",onClick:()=>D(O==="asc"?"desc":"asc"),children:[jsx("span",{className:"truncate",children:L?.label}),O==="asc"?jsx(ArrowUpWideNarrowIcon,{className:"h-3 w-3 text-muted-foreground shrink-0"}):jsx(ArrowDownWideNarrowIcon,{className:"h-3 w-3 text-muted-foreground shrink-0"})]})}),a&&jsx(xr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"Date"})}),o&&jsx(xr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"Status"})}),jsx(xr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full"})})]})}),jsx(Go,{className:" border-blue-200",children:$.map(H=>{let je=h===H.id,Ue=L?Ld(le.get(H.id),L.key):null;return jsxs(Lr,{className:`h-12.5 cursor-pointer group last:border-b-0 first:border-t-0 ${je?"bg-muted/80 hover:bg-muted":"hover:bg-muted/30"}`,onClick:()=>U(H),children:[jsx(wt,{className:"whitespace-nowrap text-xs",children:jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[jsx(xh,{extractionId:H.id,filename:H.file.filename||"Unknown",className:"shrink-0 h-6 w-6"}),jsx("div",{className:"min-w-0 flex-1",children:jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx("span",{className:"inline-block w-fit max-w-full truncate font-medium align-middle",children:H.file.filename||"Unknown"})}),jsx(et,{children:H.file.filename||"Unknown"})]})})]})}),ae&&jsx(wt,{className:"text-xs text-muted-foreground",children:jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx("span",{className:"inline-block max-w-full truncate",children:Ue!=null?typeof Ue=="boolean"?Ue?"Yes":"No":String(Ue):jsx("span",{className:"text-muted-foreground/50 italic",children:"\u2014"})})}),jsx(et,{children:Ue!=null?String(Ue):"No value"})]})}),a&&jsx(wt,{className:"whitespace-nowrap text-xs text-muted-foreground",children:new Date(H.created_at).toLocaleString()}),o&&jsx(wt,{children:jsx(wh,{style:"badge",humanReviewStatus:H.human_review_status})}),jsx(wt,{className:"text-right pr-4",children:jsxs(nr,{open:tt===H.id,onOpenChange:Le=>xe(Le?H.id:null),children:[jsx(or,{asChild:true,children:jsx(V,{size:"iconSm",variant:"ghost",className:"opacity-0 group-hover:opacity-100 transition-opacity h-6 w-6",onClick:Le=>Le.stopPropagation(),disabled:ft===H.id||st===H.id,children:ft===H.id||st===H.id?jsx(Loader2,{className:"h-3.5 w-3.5 animate-spin"}):jsx(MoreVertical,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),jsxs(ar,{align:"end",className:"flex flex-col gap-1 p-2 w-52",children:[H.human_review_status==="review_required"&&jsxs("button",{className:"text-left px-3 py-2 flex items-center gap-2 text-xs rounded hover:bg-gray-50",onClick:Le=>{Me(Le,H.id,"reviewed");},children:[jsx(ShieldCheck,{className:"h-3.5 w-3.5"}),jsx("span",{children:"Mark as reviewed"})]}),(H.human_review_status==="success"||H.human_review_status==="reviewed")&&jsxs("button",{className:"text-left px-3 py-2 flex items-center gap-2 text-xs rounded hover:bg-gray-50",onClick:Le=>{Me(Le,H.id,"review_required");},children:[jsx(ShieldUser,{className:"h-3.5 w-3.5"}),jsx("span",{children:"Mark as requiring review"})]}),jsxs("button",{className:"text-left px-3 py-2 flex items-center gap-2 text-xs rounded hover:bg-destructive/10 text-destructive",onClick:Le=>pt(Le,H.id),children:[jsx(Trash2,{className:"h-3.5 w-3.5"}),jsx("span",{children:"Delete extraction"})]})]})]})})]},H.id)})})]})}),jsx("div",{className:"border-t bg-background",children:jsxs("div",{className:"flex justify-between items-center p-2 gap-2",children:[jsx("div",{children:r&&jsxs(V,{variant:"ghost",size:"sm",className:"text-xs text-muted-foreground hover:text-foreground",onClick:()=>{r();},children:[jsx(Upload,{className:"h-4 w-4 mr-2"}),"Upload file"]})}),jsxs("div",{className:"flex items-center gap-2",children:[jsxs(V,{variant:"outline",size:"sm",className:"text-xs group px-2",onClick:G,disabled:!J?.before||pe.isLoading,children:[jsx(ChevronLeft,{className:"h-4 w-4 opacity-60 -translate-x-0.5 group-hover:-translate-x-3 group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),jsx(ChevronLeft,{className:"h-4 w-4 -ml-6 translate-x-2.5 opacity-0 group-hover:-translate-x-0 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),"Prev"]}),jsxs(V,{variant:"outline",size:"sm",className:"text-xs group px-2",onClick:ce,disabled:!J?.after||pe.isLoading,children:["Next",jsx(ChevronRight,{className:"h-4 w-4 opacity-60 group-hover:translate-x-3 group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),jsx(ChevronRight,{className:"h-4 w-4 -ml-6 -translate-x-2.5 opacity-0 group-hover:translate-x-0.5 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"})]})]})]})})]})})}),jsx(vo,{open:me!==null,onOpenChange:H=>!H&&_e(null),children:jsxs(bo,{className:"p-0 gap-0 bg-gray-50 rounded-2xl border-none shadow-2xl",children:[jsx("div",{className:"bg-white shadow-xs rounded-2xl",children:jsxs(xo,{className:"p-6 pb-4",children:[jsx(_o,{className:"text-lg font-medium text-slate-900",children:"Delete extraction"}),jsx(So,{children:"Are you sure you want to delete this extraction? This action cannot be undone."})]})}),jsxs(wo,{className:"p-4",children:[jsx(wa,{disabled:ft!==null,children:"Cancel"}),jsx(No,{onClick:Fe,disabled:ft!==null,className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay ring-1 bg-destructive hover:bg-destructive hover:opacity-80 text-white ring-destructive gap-2",children:ft!==null?jsxs(Fragment,{children:[jsx(Loader2,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})}function eO({className:e="h-12 w-12 text-gray-400",strokeWidth:t=2}){return jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:t,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 0 1 -2 -2V5a2 2 0 0 1 2 -2h5.586a1 1 0 0 1 .707 .293l5.414 5.414a1 1 0 0 1 .293 .707V19a2 2 0 0 1 -2 2z"})})}function tO({open:e,onOpenChange:t,files:r}){let n=gx,o=gr("gray");return jsx(vo,{open:e,onOpenChange:t,children:jsxs(bo,{children:[jsxs(xo,{children:[jsx(_o,{children:"PDF too long"}),jsxs(So,{children:["The following PDF file",r.length>1?"s are":" is"," over ",n," pages and cannot be uploaded. Please split ",r.length>1?"them":"it"," into smaller documents (\u2264 ",n," pages) and try again.",jsx("br",{})]})]}),r.length>0&&jsx("ul",{className:"mt-2 text-sm space-y-1",children:r.map(a=>jsxs("li",{className:"flex items-center justify-between gap-4",children:[jsx("div",{className:"flex",children:jsxs("div",{className:`flex items-center w-full justify-start ${o.headerText} border ${o.border} px-1 py-1 rounded-sm ${o.headerBg}`,children:[jsx(eO,{className:"h-4 w-4 mr-1"}),jsx("span",{className:"truncate",children:(()=>{let i=a.name,s=i.lastIndexOf(".");if(s>0){let l=i.substring(0,s);return l.length>10?`${l.substring(0,10)}...`:l}return i.length>15?`${i.substring(0,15)}...`:i})()}),a.name&&a.name.lastIndexOf(".")>0&&jsx("span",{className:"ml-0",children:a.name.substring(a.name.lastIndexOf("."))})]})}),jsxs(dn,{variant:"outline",className:"shrink-0 py-1 text-sm",children:[a.pages," pages"]})]},a.name))}),jsxs(wo,{className:"flex flex-row gap-2 justify-between items-center",children:[jsxs("span",{className:"text-xs text-muted-foreground mr-auto",children:["Need help with a complex case? Email us at ",jsx("a",{href:"mailto:support@retab.com",className:"text-gray-800",children:"support@retab.com"})]}),jsx(No,{onClick:()=>t(false),children:"OK"})]})]})})}var Mx=e=>(e/(1024*1024)).toFixed(1),nO=({children:e,handleFileUpload:t,multiple:r=false,className:n,accept:o,maxFileSize:a=10*1024*1024,exposeOpenDialog:i})=>{let[s,l]=useState(false),[c,u]=useState(false),d=useRef(0),m=useRef(null),[h,y]=useState(false),[p,f]=useState([]),x=E=>{if(!o)return true;let C=o.split(",").map(D=>D.trim().toLowerCase()),{type:b,name:O}=E;return C.some(D=>D.startsWith(".")?O.toLowerCase().endsWith(D):D.endsWith("/*")?b.startsWith(D.slice(0,-2)):b===D)},g=E=>x(E)?E.size>a?(toast.error(`Maximum size is ${Mx(a)}\xA0MB, but ${E.name} is ${Mx(E.size)}\xA0MB`),false):true:(toast.error(`The file ${E.name} is not an accepted type.`),false),v=async E=>{if(!r&&E.length>1){toast.error("Only one file allowed. Drop a single file or enable multiple uploads.");return}let C=Array.from(E).filter(g);C.length,E.length;let{accepted:b,rejected:O,corrupted:D}=await aR(C);if(O.length>0&&(f(O),y(true)),D.length>0){let F=D.map(Z=>Z.reason?`${Z.name} (${Z.reason})`:Z.name).join(", ");toast.error(`Skipped corrupted file${D.length>1?"s":""}: ${F}`);}if(b.length===0)return;l(true);let k=new DataTransfer;for(let F of b)k.items.add(F);let I=()=>{l(false);};t(Array.from(k.files),I).catch(F=>{console.error(F),toast.error(F?.message||"Something went wrong"),l(false);});},w=useCallback(E=>{E.preventDefault(),d.current+=1,E.dataTransfer.items&&E.dataTransfer.items[0]&&E.dataTransfer.items[0].kind==="file"&&u(true);},[]),N=useCallback(E=>{E.preventDefault(),d.current-=1,d.current<=0&&(d.current=0,u(false));},[]),S=useCallback(E=>{E.preventDefault();},[]),_=useCallback(async E=>{E.preventDefault(),d.current=0,u(false);let C=E.dataTransfer?.files;C&&C.length&&await v(C);},[]),P=()=>{m.current?.click();};kt__default.useEffect(()=>{typeof i=="function"&&i(P);},[i]);let R=async E=>{E.target.files&&(await v(E.target.files),E.target.value="");};return jsxs("div",{className:T("relative",n),onDragEnter:w,onDragLeave:N,onDragOver:S,onDrop:_,children:[e,c&&jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm",children:jsxs("div",{className:"p-12 max-w-md mx-4 text-center animate-in fade-in duration-200",children:[jsx("div",{className:"text-gray-100 mb-6",children:jsx(ImageIcon,{className:"h-16 w-16 mx-auto"})}),jsx("h3",{className:"text-2xl font-semibold text-white mb-3",children:"Drop Files Here"}),jsx("p",{className:"text-gray-100 text-base mb-4",children:"Release to upload documents to your project"}),o&&jsxs("p",{className:"text-sm text-gray-200 mt-3",children:["Supported: ",o]}),jsxs("p",{className:"text-sm text-gray-200 mt-2",children:["Maximum file size: ",Mx(a)," MB"]})]})}),jsx("input",{"aria-label":"File input",ref:m,type:"file",accept:o,multiple:r,onChange:R,className:"hidden"}),s&&jsx("div",{className:"absolute inset-0 z-50 grid place-items-center bg-white/70 backdrop-blur-sm",children:jsx("span",{className:"text-sm text-gray-700 animate-pulse",children:"Uploading\u2026"})}),jsx(tO,{open:h,onOpenChange:y,files:p})]})};var Zn={all:["upload-jobs"],lists:()=>[...Zn.all,"list"],list:e=>[...Zn.lists(),{filters:e}],details:()=>[...Zn.all,"detail"],detail:e=>[...Zn.details(),e]};var aO=(e={},t={})=>{let{enabled:r=true,refetchInterval:n}=t,{fetchWithAuth:o}=De();return useQuery({queryKey:Zn.list(e),queryFn:async()=>{let a=new URLSearchParams;e.before&&a.append("before",e.before),e.after&&a.append("after",e.after),e.limit!==void 0&&a.append("limit",String(e.limit)),e.order&&a.append("order",e.order),e.sort_path&&a.append("sort_path",e.sort_path),e.status&&a.append("status",e.status),e.pipeline_status&&a.append("pipeline_status",e.pipeline_status),e.exclude_pipeline_status&&a.append("exclude_pipeline_status",e.exclude_pipeline_status),e.file_id&&a.append("file_id",e.file_id),e.extraction_id&&a.append("extraction_id",e.extraction_id),e.project_id&&a.append("project_id",e.project_id),e.metadata&&Object.keys(e.metadata).length>0&&a.append("metadata",JSON.stringify(e.metadata));let i=`/internal/upload-jobs${a.toString()?`?${a.toString()}`:""}`,s=await o(i);if(!s.ok)throw await Tt(s,"Failed to fetch upload jobs");return s.json()},throwOnError:a=>Xr(a).type!=="auth_error",enabled:r,refetchInterval:n})},iO=(e={},t={})=>{let{enabled:r=true,refetchInterval:n}=t,{fetchWithAuth:o}=De();return useQuery({queryKey:[...Zn.list(e),"reconciled"],queryFn:async()=>{let a=new URLSearchParams;e.before&&a.append("before",e.before),e.after&&a.append("after",e.after),e.limit!==void 0&&a.append("limit",String(e.limit)),e.order&&a.append("order",e.order),e.sort_path&&a.append("sort_path",e.sort_path),e.status&&a.append("status",e.status),e.pipeline_status&&a.append("pipeline_status",e.pipeline_status),e.exclude_pipeline_status&&a.append("exclude_pipeline_status",e.exclude_pipeline_status),e.file_id&&a.append("file_id",e.file_id),e.extraction_id&&a.append("extraction_id",e.extraction_id),e.project_id&&a.append("project_id",e.project_id),e.metadata&&Object.keys(e.metadata).length>0&&a.append("metadata",JSON.stringify(e.metadata));let i=`/internal/upload-jobs/reconciled${a.toString()?`?${a.toString()}`:""}`,s=await o(i);if(!s.ok)throw await Tt(s,"Failed to fetch upload jobs");return s.json()},throwOnError:a=>Xr(a).type!=="auth_error",enabled:r,refetchInterval:n})},sO=()=>{let e=useQueryClient(),{fetchWithAuth:t}=De();return useMutation({mutationFn:async r=>{let n=new FormData;Array.from(r.files).forEach(s=>n.append("files",s));let o=new URLSearchParams;o.append("project_id",r.projectId),r.metadata&&Object.keys(r.metadata).length>0&&o.append("metadata",JSON.stringify(r.metadata));let a=`/internal/upload-jobs/batch?${o.toString()}`,i=await t(a,{method:"POST",body:n});if(!i.ok)throw await Tt(i,"Failed to upload files");return i.json()},onSuccess:()=>{e.invalidateQueries({queryKey:Zn.all});}})},lO=()=>{let e=useQueryClient(),{fetchWithAuth:t}=De();return useMutation({mutationFn:async r=>{let n=`/internal/upload-jobs/${encodeURIComponent(r.jobId)}/process`,o=await t(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:r.projectId})});if(!o.ok)throw await Tt(o,"Failed to process job");return o.json()},onSuccess:()=>{e.invalidateQueries({queryKey:Zn.all});}})},cO=()=>{let e=useQueryClient(),{fetchWithAuth:t}=De();return useMutation({mutationFn:async r=>{let n=`/internal/upload-jobs/${encodeURIComponent(r.jobId)}`,o=await t(n,{method:"DELETE"});if(!o.ok)throw await Tt(o,"Failed to delete job")},onSuccess:()=>{e.invalidateQueries({queryKey:Zn.all});}})},uO=()=>{let e=useQueryClient(),{fetchWithAuth:t}=De();return useMutation({mutationFn:async r=>{for(let a=0;a<r.jobIds.length;a+=100){let i=r.jobIds.slice(a,a+100);await Promise.allSettled(i.map(s=>t(`/internal/upload-jobs/${encodeURIComponent(s)}/process`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:r.projectId})}))),a+100<r.jobIds.length&&await new Promise(s=>setTimeout(s,50));}},onSuccess:()=>{e.invalidateQueries({queryKey:Zn.all});}})},dO=()=>{let e=useQueryClient(),{fetchWithAuth:t}=De();return useMutation({mutationFn:async r=>{let n=new URLSearchParams;n.append("project_id",r.projectId),r.metadata&&Object.keys(r.metadata).length>0&&n.append("metadata",JSON.stringify(r.metadata));let o=await t(`/internal/upload-jobs/process-all?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!o.ok)throw await Tt(o,"Failed to process all jobs");return o.json()},onSuccess:()=>{e.invalidateQueries({queryKey:Zn.all});}})},fO=()=>{let e=useQueryClient(),{fetchWithAuth:t}=De();return useMutation({mutationFn:async r=>{for(let o=0;o<r.jobIds.length;o+=50){let a=r.jobIds.slice(o,o+50);await Promise.allSettled(a.map(i=>t(`/internal/upload-jobs/${encodeURIComponent(i)}`,{method:"DELETE"})));}},onSuccess:()=>{e.invalidateQueries({queryKey:Zn.all});}})};var pO=createContext(void 0);function mO({children:e,metadata:t}){let{project:r}=Qr(),n=15,o=15,[a,i]=kt.useState({before:null,after:null}),[s,l]=kt.useState({before:null,after:null}),c=useMemo(()=>({limit:n,order:"desc",sort_path:"updated_at",exclude_pipeline_status:"completed",project_id:r.id,metadata:t&&Object.keys(t).length>0?t:void 0,...a}),[a,r.id,t]),u=aO(c,{refetchInterval:4e3}),d=u.data?.data??[],m=u.data?.list_metadata??{before:null,after:null},h=useMemo(()=>({limit:o,order:"desc",sort_path:"updated_at",pipeline_status:"completed",project_id:r.id,metadata:t&&Object.keys(t).length>0?t:void 0,...s}),[s,r.id,t]),y=iO(h,{refetchInterval:4e3}),p=y.data?.data??[],f=y.data?.list_metadata??{before:null,after:null},x=sO(),g=lO(),v=cO(),w=uO(),N=fO(),S=dO(),_=useCallback(async O=>{if(!(!O||O.length===0))try{let D=await x.mutateAsync({files:O,projectId:r.id,metadata:t&&Object.keys(t).length>0?t:void 0});toast.success(`Uploaded ${D.jobs.length} file${D.jobs.length>1?"s":""}`);}catch(D){throw toast.error(D?.message??"Upload failed"),D}},[x,r.id,t]),P=useCallback(async O=>{try{await g.mutateAsync({jobId:O,projectId:r.id}),toast.success("Processing started");}catch(D){throw toast.error(D?.message??"Processing failed"),D}},[g,r.id]),R=useCallback(async O=>{try{await v.mutateAsync({jobId:O}),toast.success("Upload removed");}catch(D){throw toast.error(D?.message??"Delete failed"),D}},[v]),E=useCallback(async()=>{try{let O=await S.mutateAsync({projectId:r.id,metadata:t&&Object.keys(t).length>0?t:void 0});if(O.queued_count===0){toast.error("No jobs eligible for processing");return}let D=t&&Object.keys(t).length>0;toast.success(`${O.queued_count} document${O.queued_count>1?"s":""} queued for processing${D?" with filters":""}`);}catch(O){throw toast.error(O?.message??"Process all failed"),O}},[r.id,t,S]),C=useCallback(async()=>{let O=d.filter(D=>!["queued","processing","completed"].includes(D.pipeline_status||"none"));if(O.length===0){toast.error("No jobs available to delete");return}if(window.confirm(`Delete ${O.length} upload job${O.length>1?"s":""}?`))try{await N.mutateAsync({jobIds:O.map(D=>D.id)}),toast.success(`Deleted ${O.length} upload job${O.length>1?"s":""}`);}catch(D){throw toast.error(D?.message??"Delete all failed"),D}},[d,N]),b=useMemo(()=>({pendingJobs:d,pendingLoading:u.isLoading||u.isRefetching,pendingCursors:m,pendingRefetch:()=>u.refetch(),pendingNextPage:()=>{m.after&&i({before:null,after:m.after});},pendingPrevPage:()=>{m.before&&i({before:m.before,after:null});},completedJobs:p,completedLoading:y.isLoading||y.isRefetching,completedCursors:f,completedRefetch:()=>y.refetch(),completedNextPage:()=>{f.after&&l({before:null,after:f.after});},completedPrevPage:()=>{f.before&&l({before:f.before,after:null});},uploadFiles:_,processJob:P,deleteJob:R,processAll:E,deleteAll:C,isUploading:x.isPending,isProcessing:g.isPending||w.isPending||S.isPending,isDeleting:v.isPending||N.isPending}),[d,u.isLoading,u.isRefetching,u.refetch,m,p,y.isLoading,y.isRefetching,y.refetch,f,_,P,R,E,C,x.isPending,g.isPending,w.isPending,S.isPending,v.isPending,N.isPending]);return jsx(pO.Provider,{value:b,children:e})}function hO(){let e=useContext(pO);if(e===void 0)throw new Error("useUploadJobs must be used within an UploadJobsProvider");return e}function gO({job:e,className:t}){let[r,n]=useState(null),[o,a]=useState(false),[i,s]=useState(true),[l,c]=useState(null),{fetchWithAuth:u}=De();return useEffect(()=>{let d=true,m=null,h=async()=>{try{s(!0),c(null);let y=await u(`/internal/upload-jobs/${e.id}/thumbnail`,{headers:{Accept:"image/png,image/jpeg,*/*"}});if(!y.ok)throw new Error(`Failed to load thumbnail: ${y.status}`);let p=await y.blob();if(!d)return;(p.type||y.headers.get("content-type")||"application/octet-stream").startsWith("image/")?(m=URL.createObjectURL(p),n(m),a(!0)):(n(null),a(!1));}catch{if(!d)return;c("Failed to load thumbnail"),n(null),a(false);}finally{d&&s(false);}};return e.id?h():s(false),()=>{d=false,m&&URL.revokeObjectURL(m);}},[e.id]),i?jsx(Re,{className:Fc("h-9 w-9 rounded-md",t)}):!r||!o||l?jsxs("div",{className:Fc("h-6 w-6 rounded-xs border bg-muted flex items-center justify-center text-muted-foreground",t),children:[jsx(FileIcon,{className:"h-4 w-4","aria-hidden":"true"}),jsx("span",{className:"sr-only",children:e.filename})]}):jsx("div",{className:Fc("h-6 w-6 overflow-hidden rounded-xs border bg-muted/30",t),children:jsx("img",{src:r,alt:`Preview of ${e.filename}`,className:"h-full w-full object-cover",loading:"lazy"})})}function UV({status:e}){let t=e||"none";return t==="completed"?jsx(dn,{variant:"outline",className:"bg-emerald-50 text-emerald-800 border-emerald-200 text-xs",children:"Completed"}):t==="failed"?jsx(dn,{variant:"outline",className:"bg-red-50 text-red-800 border-red-200 text-xs",children:"Retry"}):t==="processing"?jsx(dn,{variant:"outline",className:"bg-blue-50 text-blue-800 border-blue-200 text-xs",children:"Processing"}):t==="queued"?jsx(dn,{variant:"outline",className:"bg-gray-50 text-gray-800 border-gray-200 text-xs",children:"Queued"}):jsx(dn,{variant:"outline",className:"bg-gray-50 text-gray-600 border-gray-200 text-xs",children:"None"})}function qV({metadata:e}){let{project:t}=Qr(),r=useRef(null),{pendingJobs:n,pendingLoading:o,pendingCursors:a,pendingNextPage:i,pendingPrevPage:s,uploadFiles:l,processJob:c,deleteJob:u,processAll:d,isUploading:m,isProcessing:h}=hO(),y=Lo({limit:20,order:"desc",origin_dot_id:t.id,metadata:e&&Object.keys(e).length>0?e:void 0}),p=useRef([]);useEffect(()=>{let g=p.current,v=n,w=v.some(S=>{let _=g.find(P=>P.id===S.id);return _&&_.pipeline_status!=="completed"&&S.pipeline_status==="completed"}),N=g.length>v.length;(w||N)&&y.refetch(),p.current=v;},[n,y]);let f=useCallback(async(g,v)=>{if(!g||g.length===0){v?.();return}await l(g),v?.();},[l]),x=useMemo(()=>n.filter(g=>g.status==="completed"&&g.file_id&&!g.extraction_id&&!["queued","processing","completed"].includes(g.pipeline_status||"none")),[n]);return jsx(nO,{handleFileUpload:f,multiple:true,accept:".pdf, application/pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, image/*, text/plain",className:"flex-1 min-h-0 flex",children:jsxs(Sh,{className:"shadow-none gap-3 border-none py-0 flex flex-1 min-h-0",children:[jsx(Nh,{className:"px-0 pb-0 gap-0",children:jsxs("div",{className:"flex items-center justify-between",children:[jsx(Ch,{children:"Upload files"}),jsxs(V,{size:"sm",variant:"ghost",className:"rounded-full border border-gray-200 text-xs text-muted-foreground",onClick:()=>{d();},disabled:h||x.length===0,children:[`Process all${x.length>0?` (${x.length})`:""}`,h?jsx(Loader2,{className:"h-4 w-4 animate-spin mr-1"}):jsx(Play,{className:"h-4 w-4 mr-1"})]})]})}),jsx(Eh,{className:"flex flex-col flex-1 min-h-0 p-0 border border-gray-200 rounded-md",children:jsx("div",{className:"rounded-md bg-card flex flex-col flex-1 min-h-0 overflow-hidden",children:n.length===0?jsx("div",{className:"flex-1 min-h-0 flex min-w-0",children:jsx(gh,{className:"bg-white hover:bg-white",onFileUploaded:(g,v)=>f([g])})}):jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:jsxs(Ko,{className:"table-fixed w-full relative",children:[jsxs("colgroup",{children:[jsx("col",{style:{width:"50%"}}),jsx("col",{style:{width:"30%"}}),jsx("col",{style:{width:"20%"}})]}),jsx(yi,{className:"sticky top-0 left-0 right-0 z-10 bg-white border-green-200",children:jsxs(Lr,{className:"border-none p-0 h-4",children:[jsx(xr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"File"})}),jsx(xr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"Status"})}),jsx(xr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full"})})]})}),jsx(Go,{className:" border-blue-200",children:n.map(g=>{let v=g.pipeline_status==="queued"||g.pipeline_status==="processing",w=g.pipeline_status==="failed",N=!["queued","processing","completed"].includes(g.pipeline_status||"none");return jsxs(Lr,{className:"h-12.5 group last:border-b-0 first:border-t-0",children:[jsx(wt,{className:"whitespace-nowrap text-xs",children:jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[jsx(gO,{job:g,className:"shrink-0 h-6 w-6"}),jsx("div",{className:"min-w-0 flex-1",children:jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx("span",{className:"inline-block w-fit max-w-full truncate font-medium align-middle",children:g.filename})}),jsx(et,{children:g.filename})]})})]})}),jsx(wt,{className:"whitespace-nowrap text-xs",children:jsx(UV,{status:g.pipeline_status})}),jsx(wt,{className:"text-right pr-4",children:jsxs("div",{className:"inline-flex items-center gap-2 justify-end",children:[jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(V,{className:`group-hover:opacity-100 transition-opacity duration-300 ${w?"opacity-100":"opacity-0"}`,size:"iconSm",variant:w?"destructive":"ghost",onClick:()=>{c(g.id);},disabled:g.status!=="completed"||v,children:v?jsx(Loader2,{className:"h-4 w-4 animate-spin"}):jsx(Play,{})})}),jsx(et,{children:"Run the extraction for this file"})]}),N&&jsxs(Xe,{children:[jsx(Qe,{asChild:true,children:jsx(V,{size:"iconSm",variant:"ghost",onClick:()=>{u(g.id);},className:"group-hover:opacity-100 opacity-0 transition-opacity duration-300",children:jsx(Trash2,{className:"h-4 w-4"})})}),jsx(et,{children:"Delete this queued file"})]})]})})]},g.id)})})]})}),jsx("div",{className:"border-t bg-background",children:jsxs("div",{className:"flex justify-between items-center p-2 gap-2",children:[jsxs("div",{children:[jsx("input",{ref:r,type:"file",accept:".pdf, application/pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, image/*, text/plain",multiple:true,className:"hidden",onChange:g=>{let v=g.target.files;v&&v.length>0&&(f(Array.from(v)),g.target.value="");}}),jsx(V,{variant:"ghost",size:"sm",className:"text-xs text-muted-foreground hover:text-foreground",disabled:m,onClick:()=>r.current?.click(),children:m?jsxs(Fragment,{children:[jsx(Loader2,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):jsxs(Fragment,{children:[jsx(UploadCloud,{className:"h-4 w-4 mr-2"}),"Add file"]})})]}),jsxs("div",{className:"flex items-center gap-2",children:[jsxs(V,{variant:"outline",size:"sm",className:"text-xs group px-2",onClick:s,disabled:!a.before||o,children:[jsx(ChevronLeft,{className:"h-4 w-4 opacity-60 -translate-x-0.5 group-hover:-translate-x-3 group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),jsx(ChevronLeft,{className:"h-4 w-4 -ml-6 translate-x-2.5 opacity-0 group-hover:-translate-x-0 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),"Prev"]}),jsxs(V,{variant:"outline",size:"sm",className:"text-xs group px-2",onClick:i,disabled:!a.after||o,children:["Next",jsx(ChevronRight,{className:"h-4 w-4 opacity-60 group-hover:translate-x-3 group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),jsx(ChevronRight,{className:"h-4 w-4 -ml-6 -translate-x-2.5 opacity-0 group-hover:translate-x-0.5 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"})]})]})]})})]})})})]})})}function VV({metadata:e}={}){return jsx(mO,{metadata:e,children:jsx(qV,{metadata:e})})}function WV({className:e,variant:t="banner",renderError:r,children:n}){let{authError:o,isOnline:a,isAuthenticating:i,retryAuth:s}=De();if(o&&r)return jsx(Fragment,{children:r(o,s,a)});if(!o)return jsx(Fragment,{children:n});let l=()=>{switch(o.code){case "NETWORK_ERROR":return {icon:jsx(WifiOff,{className:"h-5 w-5"}),title:"Connection Issue",message:a?"Having trouble connecting. Please try again.":"You appear to be offline. Check your connection.",buttonText:a?"Retry Connection":"Waiting for connection..."};case "AUTH_EXPIRED":return {icon:jsx(KeyRound,{className:"h-5 w-5"}),title:"Session Expired",message:"Your session has expired. Please refresh to continue.",buttonText:"Refresh Session"};case "TOKEN_FETCH_FAILED":return {icon:jsx(AlertCircle,{className:"h-5 w-5"}),title:"Authentication Failed",message:"Unable to authenticate. Please try again.",buttonText:"Retry Authentication"};default:return {icon:jsx(AlertCircle,{className:"h-5 w-5"}),title:"Something Went Wrong",message:o.message||"An unexpected error occurred.",buttonText:"Try Again"}}},{icon:c,title:u,message:d,buttonText:m}=l();return t==="banner"?jsxs(Fragment,{children:[jsx("div",{className:T("bg-amber-50 border-l-4 border-amber-400 p-4 mb-4",e),role:"alert",children:jsxs("div",{className:"flex items-start",children:[jsx("div",{className:"flex-shrink-0 text-amber-500",children:c}),jsxs("div",{className:"ml-3 flex-1",children:[jsx("p",{className:"text-sm font-medium text-amber-800",children:u}),jsx("p",{className:"text-sm text-amber-700 mt-1",children:d}),o.retryCount>0&&jsxs("p",{className:"text-xs text-amber-600 mt-1",children:["Attempted ",o.retryCount," time",o.retryCount>1?"s":""]})]}),jsx("div",{className:"ml-4",children:jsxs(V,{onClick:s,disabled:i||!a&&o.code==="NETWORK_ERROR",size:"sm",variant:"outline",className:"border-amber-400 text-amber-700 hover:bg-amber-100",children:[jsx(RefreshCw,{className:T("h-4 w-4 mr-2",i&&"animate-spin")}),i?"Retrying...":m]})})]})}),n]}):t==="inline"?jsxs("div",{className:T("flex flex-col items-center justify-center p-6 text-center",e),children:[jsx("div",{className:"text-amber-500 mb-3",children:c}),jsx("h3",{className:"text-lg font-medium text-gray-900 mb-1",children:u}),jsx("p",{className:"text-sm text-gray-600 mb-4",children:d}),jsxs(V,{onClick:s,disabled:i||!a&&o.code==="NETWORK_ERROR",size:"sm",children:[jsx(RefreshCw,{className:T("h-4 w-4 mr-2",i&&"animate-spin")}),i?"Retrying...":m]}),o.retryCount>0&&jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Attempted ",o.retryCount," time",o.retryCount>1?"s":""]})]}):jsx("div",{className:T("fixed inset-0 bg-white/80 backdrop-blur-sm flex items-center justify-center z-50",e),children:jsxs("div",{className:"bg-white rounded-lg shadow-lg p-6 max-w-md w-full mx-4 text-center border border-gray-200",children:[jsx("div",{className:"text-amber-500 mb-4 flex justify-center",children:c}),jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:u}),jsx("p",{className:"text-gray-600 mb-6",children:d}),jsxs(V,{onClick:s,disabled:i||!a&&o.code==="NETWORK_ERROR",className:"w-full",children:[jsx(RefreshCw,{className:T("h-4 w-4 mr-2",i&&"animate-spin")}),i?"Retrying...":m]}),o.retryCount>0&&jsxs("p",{className:"text-xs text-gray-500 mt-3",children:["Attempted ",o.retryCount," time",o.retryCount>1?"s":""]})]})})}
111
- export{WV as AuthErrorDisplay,_v as DataComponent,kx as ExtractionComponent,vV as ExtractionReviewer,TV as ExtractionsList,Cx as FileComponent,n3 as RetabProvider,VV as UploadJobsList,T as cn,De as useAuth,My as useExtraction,Lo as useExtractionList,pS as useExtractions,jo as useJsonSchema,Ui as useOCR,ei as useOptionalExtractions,Qr as useProject};//# sourceMappingURL=index.mjs.map
116
+ `,title:h.length>30?h:void 0,children:h||""},g)})]},u))})]})}),jsxs("div",{className:"flex-shrink-0 px-3 py-1.5 bg-gray-100 border-t border-gray-200 text-xs text-gray-500 flex items-center justify-between",children:[jsx("span",{children:a.length>0?`${a.length} rows \xD7 ${o} columns`:"Empty sheet"}),jsxs("span",{className:"text-gray-400",children:["Sheet ",n.SheetNames.indexOf(t)+1," of ",n.SheetNames.length]})]})]})},Vq=({content:e,signature:t})=>{let[r,n]=useState(null),a=useRef(null),[o,i]=useState(0),s=useRef(null),[l,c]=useState(false),[u,d]=useState(null),[g,f]=useState(null),[h,m]=useState(true);useEffect(()=>{let x=false;return df().then(({Document:w,Page:_})=>{x||(d(()=>w),f(()=>_),m(false));}),()=>{x=true;}},[]);let p=Rt__default.useMemo(()=>{try{return new Blob([e],{type:"application/pdf"})}catch{try{let w=e.slice(0);return new Blob([w],{type:"application/pdf"})}catch{return null}}},[t]);useEffect(()=>{if(h||!u)return;let x=()=>{a.current&&i(a.current.clientWidth);};requestAnimationFrame(x);let w=null;return typeof window<"u"&&window.ResizeObserver&&a.current&&(w=new window.ResizeObserver(x),w.observe(a.current)),window.addEventListener("resize",x),()=>{window.removeEventListener("resize",x),w&&a.current&&w.unobserve(a.current);}},[h,u]),useEffect(()=>()=>{if(s.current){try{s.current.destroy();}catch(x){console.debug("PDF document cleanup error (can be safely ignored):",x);}s.current=null;}},[]),useEffect(()=>{c(false);},[t]);let v=useCallback(x=>{s.current=x,n(x.numPages),c(true);},[]),y=useCallback(x=>{console.error("PDF loading error:",x),s.current=null;},[]);return h||!u?jsx("div",{className:"relative w-full h-full flex items-center justify-center",children:jsx(Loader2,{className:"h-8 w-8 animate-spin text-gray-400"})}):jsxs("div",{ref:a,className:"relative w-full h-full overflow-auto",children:[!l&&jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-white/80 text-xs text-gray-700",children:"Loading PDF\u2026"}),jsx(u,{file:p,onLoadSuccess:v,onLoadError:y,options:jq,loading:null,error:jsxs("div",{className:"p-4 text-red-500 text-sm border border-red-200 rounded-lg bg-red-50",children:[jsx("div",{className:"font-medium",children:"Could not load PDF"}),jsx("div",{className:"text-xs mt-1",children:"Please check if the file is valid."})]}),children:!!r&&o>0&&p&&g&&Array.from({length:r},(x,w)=>jsx("div",{id:`pdf-page-${w+1}`,className:"mb-0 flex justify-center",children:jsx(qm,{pageNumber:w+1,width:Math.min(o,1200),PageComponent:g})},w))})]})},Hq=({content:e,mimeType:t})=>{let r=new TextDecoder().decode(e),a=((o,i)=>{switch(i){case "application/javascript":case "text/javascript":return "javascript";case "application/typescript":case "text/typescript":return "typescript";case "text/html":return "html";case "text/css":return "css";case "application/json":return "json";case "text/x-python":case "application/x-python-code":return "python";case "text/x-java":case "text/java":return "java";case "text/x-c":case "text/x-c++":case "text/x-csrc":case "text/x-c++src":return "cpp";case "text/x-csharp":return "csharp";case "text/x-go":return "go";case "text/x-rust":return "rust";case "text/x-swift":return "swift";case "text/x-php":case "application/x-httpd-php":return "php";case "text/x-ruby":return "ruby";case "text/xml":case "application/xml":return "xml";case "text/x-markdown":case "text/markdown":return "markdown";case "text/yaml":case "application/yaml":case "application/x-yaml":return "yaml";case "text/x-toml":return "toml";case "application/x-sh":case "text/x-sh":return "bash";case "application/x-powershell":return "powershell";case "text/x-sql":return "sql";case "text/x-dockerfile":return "dockerfile";case "text/x-properties":case "application/x-properties":return "properties"}let s=o.trim().split(`
117
+ `)[0].toLowerCase();if(o.trim().startsWith("{")||o.trim().startsWith("["))try{return JSON.parse(o),"json"}catch{}return s.includes("<?xml")?"xml":s.includes("<!doctype html")||o.includes("<html")?"html":s.includes("#!/usr/bin/python")?"python":s.includes("#!/usr/bin/node")?"javascript":s.includes("#!/bin/bash")?"bash":o.includes("function")&&o.includes("=>")?"javascript":o.includes("import ")&&o.includes(" from ")?"typescript":o.includes("def ")&&o.includes(":")?"python":"text"})(r,t);return jsx("div",{className:"w-full h-full bg-white border-2 border-gray-100 overflow-auto",children:jsx("div",{className:"w-full h-full overflow-auto",children:jsx(PrismAsync,{language:a,style:oneDark,customStyle:{margin:0,borderRadius:"0.75rem",height:"100%",fontSize:"11px",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:r})})})},Jq=({content:e,mimeType:t})=>{let[r,n]=useState(null),a=useRef(null),o=useRef(null),i=useRef(null),s=useRef(null),l=useRef(e),c=useRef(t);useEffect(()=>{l.current=e;},[e]),useEffect(()=>{c.current=t;},[t]);let u=useMemo(()=>Lq(e,t),[e,t]);useEffect(()=>{let g=c.current,f=l.current;if(g==="message/rfc822"||g==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||g==="application/msword"||g==="application/vnd.oasis.opendocument.text"||g==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"||g==="application/vnd.ms-excel"||g==="application/vnd.oasis.opendocument.spreadsheet"||g==="application/pdf"||g==="text/plain"||g==="text/csv"||g==="text/html"||g==="application/json")return;s.current&&(URL.revokeObjectURL(s.current),s.current=null),a.current&&(a.current.style.display="flex"),o.current&&(o.current.style.display="none"),i.current&&(i.current.style.display="none");let m=false;return (async()=>{try{let v;if(g==="image/heic"||g==="image/heif")try{let y=new Blob([f],{type:g}),{default:x}=await import('heic2any'),w=await x({blob:y,toType:"image/jpeg",quality:.9}),_=Array.isArray(w)?w[0]:w;v=URL.createObjectURL(_);}catch(y){console.warn("HEIC/HEIF conversion failed or library unavailable, falling back to raw blob preview",y);let x=new Blob([f],{type:g});v=URL.createObjectURL(x);}else {let y=new Blob([f],{type:g});v=URL.createObjectURL(y);}if(m){URL.revokeObjectURL(v);return}s.current=v,n(v),a.current&&(a.current.style.display="none"),i.current&&(i.current.style.display="flex"),d(v,g);}catch(v){console.error("Failed to create preview:",v),a.current&&(a.current.style.display="none"),o.current&&(o.current.style.display="flex");}})(),()=>{m=true;}},[u]),useEffect(()=>()=>{s.current&&(URL.revokeObjectURL(s.current),s.current=null);},[]);let d=(g,f)=>{if(i.current){for(;i.current.firstChild;)i.current.removeChild(i.current.firstChild);if(f.startsWith("image/")){let h=document.createElement("img");h.src=g,h.alt="File preview",h.className="max-w-full max-h-full object-contain",h.style.maxHeight="100%",h.style.maxWidth="100%";let m=document.createElement("div");m.className="flex items-center justify-center w-full h-full",m.appendChild(h),i.current.appendChild(m);}else if(f==="application/pdf"){let h=document.createElement("iframe");h.src=g,h.className="w-full h-full border-none max-h-full",h.title="PDF preview",i.current.appendChild(h);}else if(f.startsWith("text/")){let h=document.createElement("iframe");h.src=g,h.className="w-full h-full border-none text-xs max-h-full",h.title="Text preview",i.current.appendChild(h);}else {let h=document.createElement("div");h.className="flex flex-col items-center justify-center h-full text-center";let m=document.createElement("p");m.textContent=`Preview not available for this file type: ${f}`;let p=document.createElement("a");p.href=g,p.download="file",p.className="text-primary hover:underline",p.textContent="Download file",h.appendChild(m),h.appendChild(p),i.current.appendChild(h);}}};return t==="message/rfc822"?jsx(Bq,{content:e}):t==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||t==="application/msword"||t==="application/vnd.oasis.opendocument.text"?jsx(Uq,{content:e}):t==="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"||t==="application/vnd.ms-excel"||t==="application/vnd.oasis.opendocument.spreadsheet"?jsx(qq,{content:e}):t==="text/plain"||t==="text/csv"||t==="text/html"||t==="application/json"?jsx(Hq,{content:e,mimeType:t}):t==="application/pdf"?jsx(Vq,{content:e,signature:u}):t.startsWith("image/")&&r?jsx("div",{className:"relative w-full h-full",children:jsx("img",{src:r,alt:"File preview",className:"w-full h-full object-contain max-w-full max-h-full"})}):jsxs("div",{className:"relative w-full h-full overflow-auto min-w-0",children:[jsx("div",{ref:o,className:"flex items-center justify-center h-full bg-background",style:{display:"none"},children:jsx("p",{children:"Error loading file preview"})}),jsx("div",{ref:i,className:"w-full h-full relative",style:{display:"none"}})]})},nO=Rt__default.memo(Jq),aO=nO;function Mh({className:e="h-full",showPadding:t=false}){return jsx("div",{className:`flex flex-col items-center overflow-auto ${t?"py-24":e}`,children:jsx("div",{className:"flex flex-col gap-6 w-full max-w-3xl px-4 py-4 ",children:jsxs("div",{className:"bg-white p-0 space-y-4",children:[jsxs("div",{className:"space-y-2",children:[jsx(Ue,{className:"h-6 w-2/3"}),jsx(Ue,{className:"h-4 w-1/2"})]}),jsxs("div",{className:"space-y-3 pt-4",children:[jsx(Ue,{className:"h-3 w-full"}),jsx(Ue,{className:"h-3 w-full"}),jsx(Ue,{className:"h-3 w-5/6"}),jsx(Ue,{className:"h-3 w-full"}),jsx(Ue,{className:"h-3 w-4/5"})]}),jsxs("div",{className:"space-y-3 pt-4",children:[jsx(Ue,{className:"h-4 w-1/3"}),jsx(Ue,{className:"h-3 w-full"}),jsx(Ue,{className:"h-3 w-full"}),jsx(Ue,{className:"h-3 w-3/4"})]}),jsx(Ue,{className:"h-32 w-full rounded"}),jsxs("div",{className:"space-y-3 pt-2",children:[jsx(Ue,{className:"h-3 w-full"}),jsx(Ue,{className:"h-3 w-full"}),jsx(Ue,{className:"h-3 w-2/3"})]})]})})})}function tw(){return jsxs("div",{className:"overflow-y-auto flex flex-col col-span-2 relative",children:[jsx("div",{className:"bg-white z-10 flex flex-col top-0 left-0 p-2 sticky",children:jsx("div",{className:"flex justify-between items-center w-full",children:jsxs("div",{className:"text-xs flex items-center gap-1",children:[jsx(Loader2,{className:"h-3 w-3 animate-spin mr-1"}),jsx("div",{className:"italic text-xs text-gray-500",children:"OCR in progress..."})]})})}),jsxs("div",{className:"flex flex-col gap-4",children:[jsx(Ue,{className:"w-full h-[500px] rounded-lg"}),jsx(Ue,{className:"w-full h-[500px] rounded-lg"}),jsx(Ue,{className:"w-full h-[300px] rounded-lg"})]})]})}var jh=class extends Component{constructor(t){super(t),this.state={hasError:false};}static getDerivedStateFromError(t){return {hasError:true,error:t}}componentDidCatch(t,r){console.error("PDF Error Boundary caught an error:",t,r);}render(){return this.state.hasError?this.props.fallback?this.props.fallback:jsxs("div",{className:"flex flex-col items-center justify-center h-full p-6 text-center",children:[jsx(AlertCircle,{className:"h-12 w-12 text-red-500 mb-4"}),jsx("h3",{className:"text-lg font-semibold mb-2",children:"Unable to Display PDF"}),jsx("p",{className:"text-sm text-muted-foreground max-w-md",children:"An error occurred while rendering the PDF. This might be due to a temporary issue. Try refreshing the page or selecting a different document."}),this.state.error&&jsxs("details",{className:"mt-4 text-xs text-left max-w-md",children:[jsx("summary",{className:"cursor-pointer text-muted-foreground hover:text-foreground",children:"Technical details"}),jsx("pre",{className:"mt-2 p-2 bg-gray-100 dark:bg-gray-800 rounded overflow-auto",children:this.state.error.message})]})]}):this.props.children}};var Qq=Rt__default.memo(function({fileUrl:t,fileId:r,numPages:n,zoomFactor:a,pageWidth:o,onLoadSuccess:i,onLoadError:s,onPageRender:l,pageRefs:c,DocumentComponent:u,PageComponent:d}){let g=Math.min(o*a,1200),f=Rt__default.useRef(null);Rt__default.useEffect(()=>()=>{if(f.current){try{f.current.destroy();}catch(p){console.debug("PDF document cleanup error (can be safely ignored):",p);}f.current=null;}},[r]);let h=Rt__default.useCallback(p=>{f.current=p,i(p);},[i]),m=Rt__default.useCallback(p=>{console.error("PDF loading error:",p),f.current=null,s(p);},[s]);return jsx(u,{file:t,onLoadSuccess:h,onLoadError:m,loading:jsx("div",{className:"flex items-center justify-center h-full min-h-[400px]",children:jsx(Loader2,{className:"h-8 w-8 animate-spin"})}),error:jsxs("div",{className:"p-4 text-red-500 text-sm border border-red-200 rounded-lg bg-red-50",children:[jsx("div",{className:"font-medium",children:"Could not load PDF"}),jsx("div",{className:"text-xs mt-1",children:"Please check if the file exists and is accessible."})]}),children:n>0&&Array.from({length:n},(p,v)=>{let y=v+1;return jsx("div",{ref:x=>{c.current[y]=x;},"data-page-number":y,style:{position:"relative",marginBottom:"20px",scrollMarginBlock:"20px"},children:jsx(qm,{pageNumber:y,width:g,PageComponent:d,onRenderSuccess:x=>{try{let w=x.getViewport({scale:1}),_=g/w.width,E=c.current[y];E?requestAnimationFrame(()=>{let C=E.offsetWidth,P=E.offsetHeight;l(y,{width:C/_,height:P/_},_);}):l(y,w,_);}catch(w){console.debug(`Page ${y} render callback error (can be safely ignored):`,w);}}})},y)})},r)},(e,t)=>e.fileUrl===t.fileUrl&&e.fileId===t.fileId&&e.numPages===t.numPages&&e.zoomFactor===t.zoomFactor&&e.pageWidth===t.pageWidth&&e.DocumentComponent===t.DocumentComponent&&e.PageComponent===t.PageComponent),Yq=Rt__default.memo(function({fileId:t,numPages:r,currentBoxes:n,pageDims:a}){if(n.length===0)return null;let o=[],i=0;for(let s=1;s<=r;s++){o[s]=i;let l=a[t]?.[s];l&&(i+=l.h+20);}return jsx("div",{style:{position:"absolute",top:0,left:0,pointerEvents:"none",width:"100%",height:"100%"},children:Array.from({length:r},(s,l)=>{let c=l+1,u=a[t]?.[c];if(!u)return null;let d=n.filter(f=>f.page===c);if(d.length===0)return null;let g=o[c]||0;return jsx("div",{style:{position:"absolute",top:g,left:0,width:u.w,height:u.h},children:d.map((f,h)=>{let m={left:f.xmin*u.w,top:f.ymin*u.h,width:(f.xmax-f.xmin)*u.w,height:(f.ymax-f.ymin)*u.h};return jsx("div",{id:`bbox-${t}-${h}`,style:{position:"absolute",left:m.left,top:m.top,width:m.width,height:m.height,background:"rgba(114,191,227,.3)",outline:"2px solid rgba(120,162,231,1.0)",pointerEvents:"none",boxSizing:"border-box"}},`${t}-${c}-${h}`)})},c)})})}),sO=Rt__default.memo(function({currentItem:t,fieldPath:r,activeFormType:n,isPerformingOCR:a,isInitializingFieldLocations:o,ocrFileUrls:i,getInMemoryFieldLocations:s,getInMemoryFieldLocationsByType:l,autoPerformOCR:c,refreshOCRUrl:u,getFieldLocationsError:d,className:g="",isFileSelectorCollapsed:f=true}){let{fetchWithAuth:h}=Ve(),[m,p]=useState({}),[v,y]=useState({}),[x,w]=useState(f?1:.75),[_,E]=useState(null),[C,P]=useState(0),[T,N]=useState(null),[S,b]=useState(false),k=useRef(void 0),D=useRef({}),O=useRef(null),[$,A]=useState(null),[F,X$1]=useState(null);useEffect(()=>{let ke=false;return df().then(({Document:be,Page:re})=>{ke||(A(()=>be),X$1(()=>re));}),()=>{ke=true;}},[]),useEffect(()=>{w(f?1:.75);},[f]),useEffect(()=>{(async()=>{if(!t?.id||t.fileMimeType!=="application/pdf"){N(null);return}b(true);try{let be=await h(`/internal/db/files/${t.id}/download-link`);if(!be.ok)throw new Error(`Failed to get download link: ${be.status} ${be.statusText}`);let re=await be.json();N(re.download_url);}catch(be){console.error("Error fetching direct PDF URL:",be),N(null);}finally{b(false);}})();},[t?.id,t?.fileMimeType]);let H=useRef(null);useEffect(()=>{P(0);},[t?.id]);let L=useCallback(ke=>{if(H.current&&H.current.disconnect(),H.current=null,O.current=ke,!ke)return;let be=()=>{if(O.current){let re=O.current.clientWidth;re>0&&P(re);}};if(be(),typeof window<"u"&&window.ResizeObserver){let re=new window.ResizeObserver(()=>{be();});H.current=re,re.observe(ke);}},[]);useEffect(()=>{let ke=()=>{if(O.current){let be=O.current.clientWidth;be>0&&P(be);}};return window.addEventListener("resize",ke),()=>{window.removeEventListener("resize",ke);}},[]);let Q=useRef({}),z=useRef(null);useCallback(()=>{w(ke=>Math.min(ke+.25,3));},[]);useCallback(()=>{w(ke=>Math.max(ke-.25,.5));},[]);let j=useCallback(ke=>({numPages:be})=>{p(re=>({...re,[ke]:be})),E(null),D.current[ke]=false;},[]),ue=useCallback(ke=>{console.error("PDF loading error:",ke),E(ke.message);let be=ke?.status,re=t?.id;if(!re)return;let me=!!D.current[re];(be===400||be===403)&&u&&!me&&(D.current[re]=true,u(re));},[u,t?.id]),ie=useMemo(()=>{if(!r||!t?.id)return [];let ke=n?l?.(t.id,n)??null:s(t.id);if(!ke)return [];let be=ke[r];return !be?.bbox_normalized||!be.page?[]:[{page:be.page,xmin:be.bbox_normalized[0],ymin:be.bbox_normalized[1],xmax:be.bbox_normalized[2],ymax:be.bbox_normalized[3]}]},[r,t.id,s]),Ce=ie.length>0&&t&&!!v[t.id]?.[ie[0].page];useEffect(()=>{if(!Ce||!z.current)return;let ke=z.current.querySelector(`#bbox-${t.id}-0`);if(ke){let be=z.current.getBoundingClientRect(),re=ke.getBoundingClientRect(),me=z.current.clientHeight,ge=re.top-be.top+z.current.scrollTop-me/2+re.height/2;z.current.scrollTo({top:Math.max(0,ge),behavior:"smooth"});}},[Ce,t?.id,r]),useEffect(()=>{Q.current={};},[t?.id]);let Te=i[t.id];useEffect(()=>{Te&&Te!==k.current&&(k.current=Te,E(null),D.current[t.id]=false);},[Te,t.id]);let Je=a(t.id),vt=o(t.id);useEffect(()=>{t?.id&&!i[t.id]&&!a(t.id)&&c?.(t.id);},[t?.id,i,a,c]);let gt=d&&(d(t.id,"ground_truth")||d(t.id,"extraction")),bt=t.fileMimeType==="application/pdf";if(Je&&!gt&&!bt)return jsx(tw,{});let We=i[t.id]||T;return We?jsx(jh,{children:jsxs("div",{className:R("h-full w-full flex flex-col relative",g),children:[jsx("div",{className:" z-10 flex justify-between items-center absolute top-2 right-2 left-2",children:jsx("div",{className:"text-sm text-gray-700 bg-white/50 px-2 rounded-lg items-center h-8 flex",children:vt?jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[jsx(Loader2,{className:"size-4 animate-spin"}),"Computing field locations..."]}):r?jsxs("span",{className:`text-xs flex items-center gap-2 ${ie.length===0?"text-red-600":"text-blue-600"}`,children:[ie.length>0?jsx(Search,{className:"size-4"}):jsx(X,{className:"size-4"}),jsxs("span",{children:[n==="ground_truth"?"Ground Truth":"Extraction"," - ",r]}),ie.length===0&&jsx("span",{className:"text-red-600",children:": No source available."})]}):jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-2",children:[jsx(Search,{className:"size-4"}),"Select a field to view its location"]})})}),jsx("div",{ref:z,className:"flex-1 overflow-y-auto",children:_?jsxs("div",{className:"p-4 text-red-500 text-sm border border-red-200 rounded-lg bg-red-50",children:[jsx("div",{className:"font-medium",children:"Could not load PDF"}),jsx("div",{className:"text-xs mt-1",children:_})]}):jsx("div",{ref:L,style:{position:"relative",minHeight:"400px"},children:C===0||!$||!F?jsx("div",{className:"flex items-center justify-center h-full min-h-[400px]",children:jsx(Loader2,{className:"h-8 w-8 animate-spin"})}):jsxs(Fragment,{children:[jsx(Qq,{fileUrl:We,fileId:t.id,numPages:m[t.id]||0,zoomFactor:x,pageWidth:C,onLoadSuccess:j(t.id),onLoadError:ue,onPageRender:(ke,be,re)=>{let me={w:be.width*re,h:be.height*re};y(ye=>({...ye,[t.id]:{...ye[t.id],[ke]:me}}));},pageRefs:Q,DocumentComponent:$,PageComponent:F}),jsx(Yq,{fileId:t.id,numPages:m[t.id]||0,currentBoxes:ie,pageDims:v})]})})})]})}):jsxs("div",{className:R("flex flex-col items-center justify-center h-full text-muted-foreground",g),children:[jsx(Loader2,{className:"h-8 w-8 animate-spin mb-2"}),jsx("span",{children:S?"Loading document...":"Loading OCR result..."})]})});function cO({className:e="h-12 w-12 text-gray-400",strokeWidth:t=2}){return jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:t,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 0 1 -2 -2V5a2 2 0 0 1 2 -2h5.586a1 1 0 0 1 .707 .293l5.414 5.414a1 1 0 0 1 .293 .707V19a2 2 0 0 1 -2 2z"})})}function oV(e){return lookup(e)||"application/octet-stream"}function iV({filename:e}){let t=e.lastIndexOf(".");if(t<=0||t===e.length-1)return jsx("span",{className:"text-xs truncate block",children:e});let r=e.substring(0,t),n=e.substring(t);return jsxs("span",{className:"text-2xs justify-start flex items-center min-w-0 max-w-full",children:[jsx("span",{className:"truncate flex-shrink min-w-0",children:r}),jsx("span",{className:"flex-shrink-0",children:n})]})}function dO({currentDocument:e,currentFileData:t,getFileData:r,fieldPath:n,currentIterationId:a,activeFormType:o,onClearFileData:i,showButtons:s=true,isStreaming:l=false}){let c=br(a),[u,d]=useState("preview"),f=Za()?.selectedExtractionId,{getFieldLocationsError:h,clearFieldLocationsError:m}=us(),{isPerformingOCR:p,isInitializingFieldLocations:v,ocrFileUrls:y,getInMemoryFieldLocations:x,getInMemoryFieldLocationsByType:w,autoPerformOCR:_,refreshOCRUrl:E,autoComputeFieldLocations:C}=us(),P=e?.mime_data.id,[T,N]=useState(void 0),[S,b]=useState(false),k=Rt__default.useRef(0),D=Rt__default.useRef(r);useEffect(()=>{D.current=r;},[r]),useEffect(()=>{let A=e?.mime_data?.id;k.current+=1;let F=k.current;if(N(void 0),b(!!A),i?.(),!A){b(false);return}let X=D.current;if(!X){b(false);return}let H=false;return (async()=>{try{let L=await X(A);if(H||F!==k.current)return;L&&L.buffer&&N(L);}finally{!H&&F===k.current&&b(false);}})(),()=>{H=true;}},[e?.mime_data?.id]),useEffect(()=>{let A=e?.mime_data?.id;A&&(!t||t.id!==A||!t.buffer||(N(t),b(false)));},[t,e?.mime_data?.id]);let O=T?.file?.type==="application/octet-stream"?oV(T?.file?.name):T?.file?.type||"application/octet-stream";useEffect(()=>{if(u!=="sources"||!e?.id||!e?.mime_data.id)return;_(e.mime_data.id);let A=e?.prediction_data?.prediction||{};!A||Object.keys(A).length===0||(C(e.id,A,e.mime_data.id,a,f),a.includes("iteration")&&C(e.id,A,e.mime_data.id,e.dataset_id,f));},[u,e?.id,e?.mime_data.id,e?.prediction_data?.prediction,a,C,_,f]);let $=async()=>{if(!e||!T||!T.buffer){toast.error("File data not available");return}try{let A=e.mime_data.filename||"download",F=new Blob([T.buffer]),X=URL.createObjectURL(F),H=document.createElement("a");H.href=X,H.download=A,document.body.appendChild(H),H.click(),document.body.removeChild(H),URL.revokeObjectURL(X),toast.success("File downloaded");}catch(A){console.error("Download error:",A),toast.error("Failed to download file");}};return e?jsx("div",{className:"h-full w-full bg-white overflow-hidden shadow-sm flex flex-col relative",children:jsxs(Ed,{value:u,onValueChange:A=>d(A),className:"h-full flex flex-col gap-0",children:[jsxs("div",{className:`flex items-center justify-between pl-3 h-[39px] border-b ${c.border} ${c.forbiddenCellBg}`,children:[jsxs("div",{className:"flex flex-row gap-1 items-center min-w-0 flex-1 mr-2",children:[jsx(cO,{className:"h-3.5 w-3.5 flex-shrink-0"}),jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:jsx(iV,{filename:e?.mime_data?.filename||"Unknown"})})]}),jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:s&&jsxs(Pd,{className:"flex flex-row gap-0 h-[34px] items-center justify-center mr-[2px]",children:[jsx(fr,{children:jsxs(Me,{children:[jsx(Bo,{asChild:true,className:"text-xs data-[state=active]:text-gray-800 text-muted-foreground",value:"sources",disabled:!e||!kf(O)||l,children:jsx(je,{children:jsx(Search,{className:"h-4 w-4"})})}),jsx(ze,{children:jsx("p",{children:l?"Sources not available during extraction":!e||!kf(O)?"OCR not supported for this file type":"View OCR sources and field locations"})})]})}),jsx(fr,{children:jsxs(Me,{children:[jsx(Bo,{asChild:true,value:"preview",className:"text-xs data-[state=active]:text-gray-800 text-muted-foreground",children:jsx(je,{children:jsx(Paperclip,{className:"h-4 w-4"})})}),jsx(ze,{children:jsx("p",{children:"Preview the original file content"})})]})}),jsx(fr,{children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(K,{size:"sm",variant:"ghost",onClick:$,disabled:!e||!T?.buffer,className:"h-8 w-8 p-0 opacity-100 duration-300",children:jsx(Download,{className:"h-4 w-4"})})}),jsx(ze,{children:jsx("p",{children:"Download File"})})]})})]})})]}),jsxs("div",{className:"flex flex-1 w-full min-h-0",children:[jsx(Xv,{value:"preview",className:"flex-1 min-h-0 overflow-auto mt-0 min-w-0",children:e?!T?.buffer||S?jsx(Mh,{}):jsx(aO,{content:T.buffer,mimeType:O}):jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"Select an item"})}),jsx(Xv,{value:"sources",className:"flex-1 min-h-0 overflow-auto mt-0 min-w-0",children:e?!T?.buffer||S?jsx(Mh,{}):kf(O)?jsxs("div",{className:"flex flex-col h-full",children:[P&&h(P,o||"ground_truth")&&jsx("div",{className:"m-3 p-3 bg-red-50 border border-red-200 rounded-md",children:jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center",children:[jsx("svg",{className:"h-4 w-4 text-red-500 mr-2 flex-shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:jsx("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z",clipRule:"evenodd"})}),jsx("span",{className:"text-sm text-red-700",children:P?h(P,o||"ground_truth"):null})]}),jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[jsx("button",{onClick:()=>{P&&m(P,o||"ground_truth");},className:"text-red-600 hover:text-red-800 text-sm underline font-medium",children:"Retry"}),jsx("button",{onClick:()=>P&&m(P,o||"ground_truth"),className:"text-red-500 hover:text-red-700 text-sm underline",children:"Dismiss"})]})]})}),jsx("div",{className:"flex-1 min-h-0",children:P&&O&&jsx(sO,{currentItem:{id:P,fileMimeType:O},fieldPath:n||void 0,activeFormType:o,isPerformingOCR:p,isInitializingFieldLocations:A=>v(e.id,a),ocrFileUrls:y,getInMemoryFieldLocations:A=>x(e.id,a),getInMemoryFieldLocationsByType:(A,F)=>w(e.id,F,a),autoPerformOCR:_,refreshOCRUrl:E})})]}):jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"OCR not supported for this file type"}):jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"Select an item"})})]})]})}):jsx("div",{className:"flex items-center justify-center h-full w-full bg-white border-t",children:jsx("div",{className:"text-sm text-muted-foreground",children:"No document selected"})})}function pO(e,t){let[r,n]=useState(void 0),[a,o]=useState(false),i=useRef(0);return useEffect(()=>{i.current+=1;let l=i.current,c=false;return n(void 0),o(!!e),!e||!t?(o(false),()=>{c=true;}):((async()=>{try{let u=await t(e);if(c||l!==i.current)return;u&&n(u);}catch{}finally{!c&&l===i.current&&o(false);}})(),()=>{c=true;})},[e,t]),{fileData:r,isLoading:a,reset:()=>{i.current+=1,n(void 0),o(false);}}}function fV(e){return lookup(e)||"application/octet-stream"}var pV=e=>({id:e.id,file_id:e.file.id,project_id:e.id,mime_data:{id:e.file.id,filename:e.file.filename,mime_type:e.file.mime_type},prediction_data:{prediction:e.predictions,metadata:{extraction_id:e.id}},extraction_id:e.id});function aw({extraction:e,fieldPath:t=null,extractionStreamingOptions:r}){let n=r?.isActive??false,a=r?.data,o=r?.filename,{fetchWithAuth:i}=Ve(),s=useCallback(async f=>{try{let h=await i(`/internal/db/files/${f}`);if(!h.ok)throw new Error("Failed to fetch file details");let p=(await h.json())?.filename||"download",v=await i(`/internal/db/files/${f}/download-link`);if(!v.ok)throw new Error("Failed to fetch file URL");let x=(await v.json()).download_url,w=await fetch(x);if(!w.ok)throw new Error("Failed to fetch file content");let _=await w.arrayBuffer(),E=new Uint8Array(_),C=fV(p),P=new File([E],p,{type:C});return {id:f,file:P,buffer:_}}catch(h){console.error("Error fetching file data:",h),toast.error("Failed to load file");return}},[]),{fileData:l,reset:u}=pO(e?.file?.id,s),d=useMemo(()=>{if(n)return a||void 0;if(l)return l;if(e?.file?.id&&a?.buffer)return {...a,id:e.file.id}},[n,a,l,e]),g=useMemo(()=>e?pV(e):{id:"temp",project_id:"",mime_data:{id:"temp",filename:o||"Uploading...",mime_type:a?.file?.type||"application/octet-stream"},prediction_data:{prediction:{},metadata:{}},extraction_id:null,dataset_id:"",iteration_id:"",dataset_document_id:""},[e,o,a]);return jsx("div",{className:"flex-1 relative min-h-0 flex flex-col overflow-hidden bg-white",children:jsx(dO,{currentIterationId:n?"streaming-extraction":"single-extraction",currentDocument:g,currentFileData:d,getFileData:n?async()=>a||void 0:s,fieldPath:t,onClearFileData:()=>{n||u();},activeFormType:"extraction",isStreaming:n})})}function bO({leftPanel:e,rightPanel:t,defaultLeftWidth:r=25,minLeftWidth:n=15,maxLeftWidth:a=60,resizeHandleClassName:o}){let[i,s]=useState(r),[l,c]=useState(false),u=useRef(null),d=useRef(0),g=useRef(0),f=useRef(0);useEffect(()=>{let x=Math.min(Math.max(r,n),a);s(x);},[r,n,a]);let h=useCallback(y=>{u.current&&(c(true),g.current=y,f.current=i,document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.body.style.touchAction="none");},[i]),m=useCallback(y=>{if(!l||!u.current)return;let x=y-g.current,w=u.current.clientWidth,_=x/w*100,E=f.current+_,C=Math.min(Math.max(E,n),a);s(C);},[l,n,a]),p=useCallback(y=>{y.preventDefault(),h(y.clientX);},[h]),v=()=>{c(false),document.body.style.cursor="",document.body.style.userSelect="",document.body.style.touchAction="";};return useEffect(()=>{if(!l)return;let y=w=>{w.preventDefault(),cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>m(w.clientX));},x=()=>{cancelAnimationFrame(d.current),v();};return document.addEventListener("pointermove",y,{passive:false}),document.addEventListener("pointerup",x),document.addEventListener("pointercancel",x),()=>{document.removeEventListener("pointermove",y),document.removeEventListener("pointerup",x),document.removeEventListener("pointercancel",x);}},[l,m]),jsxs("div",{ref:u,className:R("flex flex-1 min-h-0 min-w-0"),children:[jsx("div",{style:{flex:`0 0 ${i}%`},className:"flex overflow-auto",children:e}),jsxs("div",{onPointerDown:p,className:R("group relative w-[1px] flex-shrink-0 bg-border hover:bg-indigo-400 cursor-col-resize transition-colors group",l&&"bg-indigo-500",o),children:[jsx("div",{className:"absolute top-0 bottom-0 left-1/2 -translate-x-1/2 w-[12px] cursor-col-resize z-20",onPointerDown:p}),jsx("div",{className:"absolute top-0 bottom-0 left-1/2 -translate-x-1/2 w-[4px] bg-indigo-500 opacity-0 transition-opacity duration-300 group-hover:opacity-100 cursor-col-resize z-20"})]}),jsx("div",{className:"flex flex-1 min-w-0 overflow-hidden",children:t})]})}var Vh=({onFileUploaded:e,multiple:t=false,className:r})=>{let[n,a]=useState(false),[o,i]=useState(false),s=useRef(null),l=async h=>{try{a(!0);let m=await h.arrayBuffer();e(h,m),toast.success("File loaded successfully");}catch(m){console.error("Error loading file:",m),toast.error("Failed to load file");}finally{a(false);}},c=h=>{let m=h.target.files;if(!(!m||m.length===0))for(let p=0;p<m.length;p++){let v=m[p];l(v);}},u=h=>{h.preventDefault(),h.stopPropagation(),i(true);},d=h=>{h.preventDefault(),h.stopPropagation(),i(false);},g=h=>{h.preventDefault(),h.stopPropagation();},f=h=>{h.preventDefault(),h.stopPropagation(),i(false);let m=h.dataTransfer.files;if(!(!m||m.length===0))for(let p=0;p<m.length;p++){let v=m[p];l(v);}};return jsxs("div",{className:Ul(`flex flex-col items-center justify-center w-full h-full cursor-pointer bg-gray-100 transition-colors ${o?"bg-blue-50":""}`,r),onDragEnter:u,onDragLeave:d,onDragOver:g,onDrop:f,onClick:()=>s.current?.click(),children:[jsx(CloudUpload,{className:`h-12 w-12 ${o?"text-blue-400":"text-slate-600"} transition-colors`}),jsx("h3",{className:"text-slate-800 font-normal text-2xl mb-2 mt-4",children:"Upload a file"}),jsx("p",{className:"text-sm text-slate-700 text-center",children:"Drag and drop or click to select a file"}),jsx("input",{multiple:t,type:"file","aria-label":"Upload a file",ref:s,onChange:c,disabled:n,className:"hidden",id:"file-upload"})]})};function sw({extractionId:e,projectId:t,isNewExtraction:r=false,extractionDisplayOptions:{view:n="form",allowEditing:a=false,showReasoning:o=false,showTabs:i=false}={},continueButtonOptions:{onClick:s,label:l="Continue"}={}}){let[c,u]=useState(false),{data:d,isLoading:g}=c0(r&&!c?null:e),[f,h]=useState(null),[m,p]=useState(false),[v,y]=useState(null),[x,w]=useState(null),[_,E]=useState(null),C=qS();useEffect(()=>{p(false),y(null),w(null),E(null),u(false);},[e]);let P=useCallback(async(k,D)=>{if(!t||!e){toast.error("Missing project or extraction ID");return}y(k),w({id:`temp-${Date.now()}`,file:k,buffer:D}),p(true),E({});try{await C.mutateAsync({projectId:t,extractionId:e,file:k,onStreamStart:()=>{},onStreamEnd:()=>{u(!0),toast.success("Extraction completed");},onPredictionUpdate:O=>{E(O);}});}catch(O){console.error("[ExtractionComponent] Extraction error:",O),toast.error("Extraction failed"),p(false),E(null),w(null),y(null);}},[t,e,C]),T=useCallback(k=>{h(k);},[]);useEffect(()=>{d&&m&&p(false);},[d,m]);let N=m&&!d,S=e&&!r&&!d&&!m&&g,b=e&&!r&&d===null&&!m&&!g;return S?jsx("div",{className:"flex-1 relative min-h-0 flex flex-col overflow-hidden",children:jsx("div",{className:"flex-1 flex items-center justify-center p-0",children:jsxs("div",{className:"flex flex-col items-center gap-3 text-muted-foreground",children:[jsx(Loader2,{className:"h-8 w-8 animate-spin"}),jsx("span",{className:"text-sm",children:"Loading extraction..."})]})})}):b?jsx("div",{className:"flex-1 relative min-h-0 flex flex-col overflow-hidden",children:jsx("div",{className:"flex-1 flex items-center justify-center p-0",children:jsxs("div",{className:"flex flex-col items-center gap-4 text-muted-foreground max-w-md text-center px-4",children:[jsx("div",{className:"flex items-center justify-center w-16 h-16 rounded-full bg-zinc-100",children:jsx(FileX,{className:"h-8 w-8 text-zinc-400"})}),jsxs("div",{className:"space-y-2",children:[jsx("h3",{className:"text-lg font-medium text-zinc-900",children:"Extraction not found"}),jsx("p",{className:"text-sm text-zinc-500",children:"The extraction you're looking for doesn't exist or may have been deleted."})]}),jsxs("p",{className:"text-xs text-zinc-400 font-mono",children:["ID: ",e]})]})})}):!d&&!m?jsx("div",{className:"flex-1 relative min-h-0 flex flex-col overflow-hidden",children:jsx("div",{className:"flex-1 flex items-center justify-center p-0",children:jsx(Vh,{onFileUploaded:P,className:"flex flex-1 min-h-0 bg-white hover:bg-zinc-50 transition-colors"})})}):jsx("div",{className:"flex-1 relative min-h-0 flex flex-col overflow-hidden",children:jsx(bO,{resizeHandleClassName:"bg-zinc-200",defaultLeftWidth:40,minLeftWidth:30,maxLeftWidth:90,leftPanel:jsx(aw,{extraction:d??null,fieldPath:f,extractionStreamingOptions:{isActive:N,data:x,filename:v?.name}}),rightPanel:jsx(tb,{extraction:d??null,onFieldPathChange:T,extractionDisplayOptions:{view:n,allowEditing:a,showReasoning:o,showTabs:i},continueButtonOptions:{onClick:s,label:l},extractionStreamingOptions:{isActive:N,data:_,filename:v?.name}})})})}var SV=bc.object({startDate:bc.date({required_error:"Start date is required."}),endDate:bc.date({required_error:"End date is required."})}).refine(e=>e.endDate>=e.startDate,{message:"End date cannot be before start date.",path:["endDate"]});function gf({className:e,initialStartDate:t,initialEndDate:r,onSubmit:n,onChange:a,onClose:o,submitLabel:i="Submit",autoApply:s=false}){let l=useForm({resolver:zodResolver(SV),defaultValues:{startDate:t,endDate:r}});function c(y){n?n(y):toast("You submitted the following values",{description:jsx("pre",{className:"mt-2 w-[320px] rounded-md bg-neutral-950 p-4",children:jsx("code",{className:"text-white",children:JSON.stringify(y,null,2)})})}),o?.();}let u=l.watch("startDate"),d=l.watch("endDate"),[g,f]=useState(false),[h,m]=useState(false),p=useRef(t),v=useRef(r);return useEffect(()=>{if(s&&a&&u&&d){let y=p.current?.getTime()!==u.getTime(),x=v.current?.getTime()!==d.getTime();(y||x)&&(p.current=u,v.current=d,a({startDate:u,endDate:d}));}},[u,d,s,a]),jsx(Wl,{...l,children:jsxs("form",{onSubmit:l.handleSubmit(c),className:R("bg-gray-50 rounded-2xl shadow-2xl",e),children:[jsx("div",{className:R("bg-white shadow-xs rounded-2xl",e),children:jsxs("div",{className:"text-xs grid grid-cols-2 items-center gap-4 p-4",children:[jsx(Sa,{control:l.control,name:"startDate",render:({field:y})=>jsxs(Hn,{className:"flex flex-col",children:[jsx(vi,{className:"text-xs font-semibold",children:"From"}),jsxs(Ht,{modal:true,open:g,onOpenChange:f,children:[jsx(Jt,{asChild:true,children:jsx(Jn,{children:jsxs(K,{variant:"outline",className:R("text-left font-normal text-xs",!y.value&&"text-muted-foreground"),children:[y.value?y.value.toLocaleDateString():jsx("span",{children:"Pick a date"}),jsx(CalendarIcon,{className:"ml-auto h-4 w-4 opacity-50"})]})})}),jsx(Wt,{className:"w-auto p-0",align:"start",children:jsx(Co,{mode:"single",selected:y.value,onSelect:x=>{y.onChange(x),f(false);},disabled:x=>{let w=x>new Date,_=x<new Date("1900-01-01"),E=d?x>d:false;return w||_||E},captionLayout:"dropdown"})})]}),jsx(td,{})]})}),jsx(Sa,{control:l.control,name:"endDate",render:({field:y})=>jsxs(Hn,{className:"flex flex-col",children:[jsx(vi,{className:"text-xs font-semibold",children:"To"}),jsxs(Ht,{modal:true,open:h,onOpenChange:m,children:[jsx(Jt,{asChild:true,children:jsx(Jn,{children:jsxs(K,{variant:"outline",className:R("text-left font-normal text-xs",!y.value&&"text-muted-foreground"),children:[y.value?y.value.toLocaleDateString():jsx("span",{children:"Pick a date"}),jsx(CalendarIcon,{className:"ml-auto h-4 w-4 opacity-50"})]})})}),jsx(Wt,{className:"w-auto p-0",align:"start",children:jsx(Co,{mode:"single",selected:y.value,onSelect:x=>{y.onChange(x),m(false);},disabled:x=>{let w=x>new Date,_=x<new Date("1900-01-01"),E=u?x<u:false;return w||_||E},captionLayout:"dropdown"})})]}),jsx(td,{})]})})]})}),!s&&jsx("div",{className:e?"p-2":"p-4",children:jsx(K,{type:"submit",className:"text-xs w-full group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay ring-1 bg-gray-900 hover:bg-gray-900 hover:opacity-80 text-white ring-gray-900 gap-2",children:i})})]})})}var pu=({className:e})=>jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",className:e,children:jsx("path",{d:"M12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2ZM16.6914 7.30859C16.2804 6.89801 15.6141 6.89784 15.2031 7.30859L12 10.5117L8.79785 7.30957C8.3868 6.89852 7.72062 6.89852 7.30957 7.30957C6.8988 7.72064 6.89861 8.3869 7.30957 8.79785L10.5117 12L7.30859 15.2031C6.89797 15.6141 6.89805 16.2804 7.30859 16.6914C7.71959 17.1019 8.38595 17.102 8.79688 16.6914L12 13.4883L15.2041 16.6924C15.6151 17.1024 16.2816 17.1028 16.6924 16.6924C17.1031 16.2816 17.1025 15.6152 16.6924 15.2041L13.4883 12L16.6914 8.79688C17.1021 8.38596 17.1019 7.71963 16.6914 7.30859Z"})});var ri=({className:e})=>jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"currentColor",xmlns:"http://www.w3.org/2000/svg",className:e,children:jsx("path",{d:"M11.9995 1.99951C17.5223 1.99958 21.9994 6.47673 21.9995 11.9995C21.9994 17.5223 17.5223 21.9994 11.9995 21.9995C6.47676 21.9994 1.99963 17.5223 1.99951 11.9995C1.99963 6.47676 6.47676 1.99963 11.9995 1.99951ZM17.3716 8.18408C16.9205 7.70276 16.1654 7.67831 15.6841 8.12939L9.98389 13.4692L7.88135 11.1753C7.43559 10.689 6.67916 10.6553 6.19287 11.1011C5.70661 11.5468 5.67387 12.3033 6.11963 12.7896L9.03955 15.9741C9.25502 16.2089 9.55608 16.3486 9.87451 16.3608C10.1932 16.3728 10.5041 16.2566 10.7368 16.0386L17.3169 9.87158C17.798 9.42063 17.8222 8.66544 17.3716 8.18408Z",fill:"currentColor"})});var TV={sm:{container:"!text-2xs",fieldPadding:"px-2 py-1",buttonPadding:"px-2 py-1",removePadding:"px-1.5 py-[5px]",iconSize:"h-3 w-3",statusIconSize:"h-3.5 w-3.5",dropdownItemText:"!text-xs",inputHeight:"h-8",buttonHeight:"h-8"},md:{container:"!text-xs",fieldPadding:"px-2.5 py-[5px]",buttonPadding:"px-2.5 py-[5px]",removePadding:"px-2 py-[5px]",iconSize:"h-4 w-4",statusIconSize:"h-4 w-4",dropdownItemText:"!text-sm",inputHeight:"h-9",buttonHeight:"h-9"}},kO=({filter:e,onUpdate:t,onRemove:r,formatDateValue:n,size:a="sm"})=>{let[o,i]=useState(false),[s,l]=useState(e.metadataKey||""),[c,u]=useState(e.field==="metadata"?String(e.value):""),d=TV[a],g=()=>e.field==="status"?jsx(CircleCheck,{className:R(d.iconSize,"text-gray-500")}):e.field==="created_date"?jsx(Calendar,{className:R(d.iconSize,"text-gray-500")}):e.field==="metadata"?jsx(Tag,{className:R(d.iconSize,"text-gray-500")}):null,f=()=>{if(e.field==="created_date"&&e.value instanceof Date)return n(e.value);if(e.field==="status"){if(e.value==="success")return "Success";if(e.value==="review_required")return "Requires review";if(e.value==="reviewed")return "Reviewed"}return String(e.value)},h=()=>e.field==="created_date"?"Created date":e.field==="status"?"Status":e.field==="metadata"?e.metadataKey||"metadata":e.field,m=y=>{t(e.id,y);},p=()=>{r(e.id);},v=()=>{s.trim()&&c.trim()&&(m({metadataKey:s.trim(),value:c.trim()}),i(false));};return jsxs("div",{className:R("inline-flex items-center gap-0.5 bg-gray-100 border border-gray-300 rounded-md overflow-hidden",d.container),children:[jsxs("div",{className:R("flex items-center gap-1",d.fieldPadding),children:[g(),jsx("span",{className:"font-medium text-gray-700",children:h()})]}),jsxs(mr,{children:[jsx(hr,{asChild:true,children:jsx("button",{className:R("hover:bg-gray-200 transition-colors text-gray-600 font-normal",d.buttonPadding),children:e.operator==="is_not"?"is not":e.operator})}),jsx(gr,{align:"start",className:"min-w-[100px]",children:e.field==="created_date"?jsxs(Fragment,{children:[jsx(we,{className:d.dropdownItemText,onClick:()=>m({operator:"within"}),children:"within"}),jsx(we,{className:d.dropdownItemText,onClick:()=>m({operator:"before"}),children:"before"}),jsx(we,{className:d.dropdownItemText,onClick:()=>m({operator:"after"}),children:"after"})]}):e.field==="metadata"?jsxs(Fragment,{children:[jsx(we,{className:d.dropdownItemText,onClick:()=>m({operator:"is"}),children:"is"}),jsx(we,{className:d.dropdownItemText,onClick:()=>m({operator:"contains"}),children:"contains"})]}):jsxs(Fragment,{children:[jsx(we,{className:d.dropdownItemText,onClick:()=>m({operator:"is"}),children:"is"}),jsx(we,{className:d.dropdownItemText,onClick:()=>m({operator:"is_not"}),children:"is not"})]})})]}),e.field==="status"&&jsxs(mr,{children:[jsx(hr,{asChild:true,children:jsx("button",{className:R("hover:bg-gray-200 transition-colors text-gray-900 font-medium",d.buttonPadding),children:f()})}),jsxs(gr,{align:"start",className:"min-w-[120px]",children:[jsxs(we,{className:d.dropdownItemText,onClick:()=>m({value:"review_required"}),children:[jsx(pu,{className:R(d.statusIconSize,"mr-2 text-[#D25F5F]")}),"Requires review"]}),jsxs(we,{className:d.dropdownItemText,onClick:()=>m({value:"reviewed"}),children:[jsx(ri,{className:R(d.statusIconSize,"mr-2 text-[#5F6AD2]")}),"Reviewed"]}),jsxs(we,{className:d.dropdownItemText,onClick:()=>m({value:"success"}),children:[jsx(ri,{className:R(d.statusIconSize,"mr-2 text-[#50CE89]")}),"Success"]})]})]}),e.field==="created_date"&&e.operator==="within"&&jsxs(Ht,{children:[jsx(Jt,{asChild:true,children:jsxs("button",{className:R("hover:bg-gray-200 transition-colors text-gray-900 font-medium",d.buttonPadding),children:[e.value instanceof Date?n(e.value):"start"," \u2192 ",e.endValue instanceof Date?n(e.endValue):"end"]})}),jsx(Wt,{className:"w-auto p-0",align:"start",children:jsx(gf,{initialStartDate:e.value instanceof Date?e.value:new Date,initialEndDate:e.endValue instanceof Date?e.endValue:new Date,submitLabel:"Apply",onSubmit:({startDate:y,endDate:x})=>m({value:y,endValue:x})})})]}),e.field==="created_date"&&e.operator!=="within"&&jsxs(mr,{children:[jsx(hr,{asChild:true,children:jsx("button",{className:R("hover:bg-gray-200 transition-colors text-gray-900 font-medium",d.buttonPadding),children:f()})}),jsxs(gr,{align:"start",className:"min-w-[160px]",children:[[{label:"1 day ago",days:1},{label:"3 days ago",days:3},{label:"1 week ago",days:7},{label:"1 month ago",days:30},{label:"3 months ago",days:90},{label:"6 months ago",days:180},{label:"1 year ago",days:365}].map(({label:y,days:x})=>jsx(we,{className:d.dropdownItemText,onClick:()=>{let w=new Date;w.setDate(w.getDate()-x),m({value:w});},children:y},y)),jsx(ka,{}),jsxs(Ht,{children:[jsx(Jt,{asChild:true,children:jsx("button",{className:R("relative flex w-full cursor-default select-none items-center rounded-sm px-2 py-1.5 outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground",d.container),children:"Custom date..."})}),jsx(Wt,{className:"w-auto p-0",align:"start",side:"right",children:jsx(gf,{initialStartDate:e.value instanceof Date?e.value:new Date,initialEndDate:e.value instanceof Date?e.value:new Date,submitLabel:"Apply",onSubmit:({startDate:y})=>m({value:y})})})]})]})]}),e.field==="metadata"&&jsxs(Ht,{open:o,onOpenChange:i,children:[jsx(Jt,{asChild:true,children:jsx("button",{className:R("hover:bg-gray-200 transition-colors text-gray-900 font-medium",d.buttonPadding),onClick:()=>{l(e.metadataKey||""),u(String(e.value));},children:f()})}),jsx(Wt,{align:"start",className:"w-64 p-3",children:jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"space-y-1.5",children:[jsx("label",{className:R("font-medium text-gray-700",d.dropdownItemText),children:"Key"}),jsx(Ze,{value:s,onChange:y=>l(y.target.value),placeholder:"e.g. customer_id",className:R(d.inputHeight,d.dropdownItemText)})]}),jsxs("div",{className:"space-y-1.5",children:[jsx("label",{className:R("font-medium text-gray-700",d.dropdownItemText),children:"Value"}),jsx(Ze,{value:c,onChange:y=>u(y.target.value),placeholder:"e.g. 12345",className:R(d.inputHeight,d.dropdownItemText),onKeyDown:y=>{y.key==="Enter"&&v();}})]}),jsx(K,{size:"sm",className:R("w-full",d.dropdownItemText,d.buttonHeight),onClick:v,disabled:!s.trim()||!c.trim(),children:"Apply"})]})})]}),jsx("button",{onClick:p,className:R("hover:bg-gray-200 transition-colors h-full flex items-center justify-center text-gray-400 hover:text-gray-600",d.removePadding),children:jsx(X,{className:d.iconSize})})]})};var IV={sm:{buttonClass:"!text-2xs h-7 py-0.25 px-0.5",iconSize:"size-3.5",dropdownWidth:"w-48",dropdownItemText:"!text-xs",menuIconSize:"h-3.5 w-3.5",inputHeight:"h-8",labelText:"!text-xs"},md:{buttonClass:"!text-xs h-8 py-0.5 px-1",iconSize:"size-4",dropdownWidth:"w-52",dropdownItemText:"!text-sm",menuIconSize:"h-4 w-4",inputHeight:"h-9",labelText:"!text-sm"}},FV=()=>Math.random().toString(36).substr(2,9),MV=e=>{if(typeof e=="string")return e;let t=new Date,r=new Date(e),n=t.getTime()-r.getTime(),a=Math.floor(n/(1e3*60*60*24));return a===0?"today":a===1?"1 day ago":a===3?"3 days ago":a>=6&&a<=8?"1 week ago":a>=29&&a<=31?"1 month ago":a>=89&&a<=91?"3 months ago":a>=179&&a<=181?"6 months ago":a>=364&&a<=366?"1 year ago":format(r,"MMM d, yyyy")};function Jh({filters:e,onFiltersChange:t,size:r="sm",showMetadataFilter:n=true}){let[a,o]=useState(""),[i,s]=useState(""),[l,c]=useState(false),u=IV[r],d=(p,v)=>{t(e.map(y=>y.id===p?{...y,...v}:y));},g=p=>{t(e.filter(v=>v.id!==p));},f=p=>{t([...e,{...p,id:FV()}]);},h=()=>{t([]);},m=()=>{a.trim()&&i.trim()&&(f({field:"metadata",operator:"is",value:i.trim(),metadataKey:a.trim()}),o(""),s(""));};return jsxs("div",{className:"flex items-center gap-2 flex-1 flex-wrap",children:[e.map(p=>jsx(kO,{filter:p,onUpdate:d,onRemove:g,formatDateValue:MV,size:r},p.id)),jsxs(mr,{open:l,onOpenChange:c,children:[jsx(hr,{asChild:true,children:jsxs(K,{variant:"outline",size:"sm",className:u.buttonClass,children:[jsx(ListFilter,{className:R(u.iconSize,"mr-1")}),jsx("span",{children:"Filter"})]})}),jsxs(gr,{align:"start",className:R(u.dropdownWidth,u.dropdownItemText),children:[e.length>0&&jsxs(Fragment,{children:[jsxs(we,{onClick:h,className:R("text-red-600",u.dropdownItemText),children:[jsx(X,{className:R(u.menuIconSize,"mr-2")}),jsx("span",{children:"Clear all filters"})]}),jsx(ka,{})]}),jsxs(Xr,{children:[jsxs(Qr,{className:u.dropdownItemText,children:[jsx(CircleCheck,{className:R(u.menuIconSize,"mr-2 text-gray-500")}),jsx("span",{children:"Status"})]}),jsx(Ta,{children:jsxs(Yr,{sideOffset:2,children:[jsxs(we,{onClick:()=>f({field:"status",operator:"is",value:"review_required"}),className:u.dropdownItemText,children:[jsx(pu,{className:R(u.menuIconSize,"mr-2 text-[#D25F5F]")}),jsx("span",{children:"Requires review"})]}),jsxs(we,{onClick:()=>f({field:"status",operator:"is",value:"reviewed"}),className:u.dropdownItemText,children:[jsx(ri,{className:R(u.menuIconSize,"mr-2 text-[#5F6AD2]")}),jsx("span",{children:"Reviewed"})]}),jsxs(we,{onClick:()=>f({field:"status",operator:"is",value:"success"}),className:u.dropdownItemText,children:[jsx(ri,{className:R(u.menuIconSize,"mr-2 text-[#50CE89]")}),jsx("span",{children:"Success"})]})]})})]}),jsxs(Xr,{children:[jsxs(Qr,{className:u.dropdownItemText,children:[jsx(Calendar,{className:R(u.menuIconSize,"mr-2 text-gray-500")}),jsx("span",{children:"Created date"})]}),jsx(Ta,{children:jsxs(Yr,{className:"max-h-[400px] overflow-y-auto",children:[[{label:"1 day ago",days:1},{label:"3 days ago",days:3},{label:"1 week ago",days:7},{label:"1 month ago",days:30},{label:"3 months ago",days:90},{label:"6 months ago",days:180},{label:"1 year ago",days:365}].map(({label:p,days:v})=>jsx(we,{className:u.dropdownItemText,onClick:()=>{let y=new Date;y.setDate(y.getDate()-v),f({field:"created_date",operator:"after",value:y});},children:p},p)),jsx(ka,{}),jsxs(Xr,{children:[jsx(Qr,{className:u.dropdownItemText,children:"Custom date range..."}),jsx(Ta,{children:jsx(Yr,{className:"p-0",sideOffset:2,children:jsx(gf,{initialStartDate:new Date,initialEndDate:new Date,submitLabel:"Apply",className:u.dropdownItemText,onSubmit:({startDate:p,endDate:v})=>{f({field:"created_date",operator:"within",value:p,endValue:v});},onClose:()=>c(false)})})})]})]})})]}),n&&jsxs(Xr,{children:[jsxs(Qr,{className:u.dropdownItemText,children:[jsx(Tag,{className:R(u.menuIconSize,"mr-2 text-gray-500")}),jsx("span",{children:"Metadata"})]}),jsx(Ta,{children:jsxs(Yr,{className:"p-0 w-64 bg-gray-50 rounded-2xl border-none shadow-2xl",onInteractOutside:p=>p.preventDefault(),children:[jsx("div",{className:"bg-white shadow-xs rounded-2xl",children:jsxs("div",{className:"space-y-3 p-3",onClick:p=>p.stopPropagation(),children:[jsxs("div",{className:"space-y-1.5",children:[jsx("label",{className:R("font-medium text-gray-700",u.labelText),children:"Key"}),jsx(Ze,{value:a,onChange:p=>o(p.target.value),placeholder:"e.g. customer_id",className:R(u.inputHeight,u.dropdownItemText),onClick:p=>p.stopPropagation(),onKeyDown:p=>p.stopPropagation()})]}),jsxs("div",{className:"space-y-1.5",children:[jsx("label",{className:R("font-medium text-gray-700",u.labelText),children:"Value"}),jsx(Ze,{value:i,onChange:p=>s(p.target.value),placeholder:"e.g. 12345",className:R(u.inputHeight,u.dropdownItemText),onClick:p=>p.stopPropagation(),onKeyDown:p=>{p.stopPropagation(),p.key==="Enter"&&m();}})]})]})}),jsx("div",{className:"p-3",children:jsx(K,{size:"sm",className:R("w-full group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay ring-1 bg-gray-900 hover:bg-gray-900 hover:opacity-80 text-white ring-gray-900 gap-2",u.dropdownItemText,u.inputHeight),onClick:p=>{p.stopPropagation(),m();},disabled:!a.trim()||!i.trim(),children:"Add filter"})})]})})]})]})]})]})}function RO({projectId:e,metadata:t,dateRange:r,statusFilter:n,searchQuery:a}){let{fetchWithAuth:o}=Ve(),i=useCallback(async s=>{let l=toast.loading(`Preparing ${s.toUpperCase()} export...`);try{let c=new URL("/v1/extractions/download");if(c.searchParams.append("format",s),c.searchParams.append("origin_dot_id",e),t){let f=Object.fromEntries(Object.entries(t).filter(([h,m])=>m&&m.trim()!==""));Object.keys(f).length>0&&c.searchParams.append("metadata",JSON.stringify(f));}r?.from&&c.searchParams.append("from_date",format(r.from,"yyyy-MM-dd")),r?.to&&c.searchParams.append("to_date",format(r.to,"yyyy-MM-dd")),n&&c.searchParams.append("human_review_status",n),a&&c.searchParams.append("filename",a);let u=await o(c.toString(),{method:"GET",headers:{"Content-Type":"application/json"}});if(!u.ok){if(u.status===404){let f=await u.json().catch(()=>({}));if((f?.details?.error||f?.detail||"No extractions found").includes("No extractions found")){let m=r?.from&&r?.to?`between ${format(r.from,"MMM d, yyyy")} and ${format(r.to,"MMM d, yyyy")}`:r?.from?`after ${format(r.from,"MMM d, yyyy")}`:r?.to?`before ${format(r.to,"MMM d, yyyy")}`:"for the selected criteria";toast.dismiss(l),toast.warning(`No extractions found ${m}. Try adjusting your filters.`,{duration:5e3});return}}throw toast.dismiss(l),new Error(`Export failed: ${u.statusText}`)}let g=(await u.json()).download_url;window.open(g,"_blank"),toast.dismiss(l),toast.success("Export ready! Download started.");}catch(c){console.error("Export error:",c),toast.dismiss(l),toast.error("Failed to generate export");}},[e,t,r,n,a]);return jsxs(mr,{children:[jsx(hr,{asChild:true,children:jsxs(K,{variant:"outline",size:"sm",className:"text-2xs h-7 py-0 px-0.5",children:[jsx(Download,{className:"size-3.5 mr-1"}),jsx("span",{children:"Export"})]})}),jsxs(gr,{align:"end",className:"min-w-44",children:[jsxs(we,{onClick:()=>i("csv"),children:[jsx(FileText,{className:"h-3.5 w-3.5 mr-2"})," CSV"]}),jsxs(we,{onClick:()=>i("xlsx"),children:[jsx(FileSpreadsheet,{className:"h-3.5 w-3.5 mr-2"})," Excel"]}),jsxs(we,{onClick:()=>i("jsonl"),children:[jsx(FileJson,{className:"h-3.5 w-3.5 mr-2"})," JSONL"]})]})]})}function Kh({extractionId:e,filename:t,className:r}){let[n,a]=useState(null),[o,i]=useState(false),[s,l]=useState(true),[c,u]=useState(null),{fetchWithAuth:d}=Ve();return useEffect(()=>{let g=true,f=null;return (async()=>{try{l(!0),u(null);let m=await d(`/v1/extractions/${e}/thumbnail`,{headers:{Accept:"image/png,image/jpeg,*/*"}});if(!m.ok)throw new Error(`Failed to load thumbnail: ${m.status}`);let p=await m.blob();if(!g)return;(p.type||m.headers.get("content-type")||"application/octet-stream").startsWith("image/")?(f=URL.createObjectURL(p),a(f),i(!0)):(a(null),i(!1));}catch(m){if(!g)return;console.error(`Failed to load thumbnail for extraction ${e}`,m),u("Failed to load thumbnail"),a(null),i(false);}finally{g&&l(false);}})(),()=>{g=false,f&&URL.revokeObjectURL(f);}},[e]),s?jsx(Ue,{className:R("h-6 w-6 rounded-xs",r)}):!n||!o||c?jsxs("div",{className:R("h-6 w-6 rounded-xs border bg-muted flex items-center justify-center text-muted-foreground",r),children:[jsx(FileIcon,{className:"h-4 w-4","aria-hidden":"true"}),jsx("span",{className:"sr-only",children:t})]}):jsx("div",{className:R("h-6 w-6 overflow-hidden rounded-xs border bg-muted/30",r),children:jsx("img",{src:n,alt:`Preview of ${t}`,className:"h-full w-full object-cover",loading:"lazy"})})}function Gh({humanReviewStatus:e,style:t="icon"}){return e==="review_required"?t==="badge"?jsx(xn,{variant:"outline",className:"bg-orange-50 text-orange-800 border-orange-200 text-xs",children:"Review required"}):jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(pu,{className:"size-4 text-[#D25F5F] border-none"})}),jsx(ze,{children:"Review required"})]}):e==="reviewed"?t==="badge"?jsx(xn,{variant:"outline",className:"bg-blue-50 text-blue-800 border-blue-200 text-xs",children:"Reviewed"}):jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(ri,{className:"size-4 text-[#5F6AD2] border-none"})}),jsx(ze,{children:"Reviewed by human"})]}):t==="badge"?jsx(xn,{variant:"outline",className:"bg-emerald-50 text-emerald-800 border-emerald-200 text-xs",children:"Success"}):jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(ri,{className:"size-4 text-[#50CE89] border-none"})}),jsx(ze,{children:"Validated automatically"})]})}function $O({extractions:e,isLoading:t,paginationMetadata:r,onPrevPage:n,onNextPage:a,onExtractionClick:o,onDeleteClick:i,onStatusChange:s,isCollapsed:l,onCollapseToggle:c,deletingId:u,updatingId:d,showUploadButton:g,onNewExtraction:f}){let h=Za(),m=h?.selectedExtractionId??null;return jsx("div",{className:`flex flex-shrink-0 ${l?"w-[194px]":"w-[330px]"} overflow-auto pt-0`,children:jsx("div",{className:"rounded-none bg-card flex flex-col flex-1 min-h-0 overflow-hidden border-t border-gray-200 border-r",children:!t&&e.length===0?jsxs("div",{className:"flex flex-col items-center justify-center p-8 gap-4 flex-1",children:[jsxs("div",{className:"text-center space-y-2",children:[jsx("p",{className:"text-sm text-muted-foreground",children:"No extractions yet."}),jsx("p",{className:"text-2xs text-muted-foreground",children:"Upload and process files to see results here."})]}),g&&jsxs(K,{variant:"outline",size:"sm",onClick:()=>{if(f){let p=f();h?.setSelectedExtractionId(p);}},className:"gap-2 rounded-none",children:[jsx(Upload,{className:"h-4 w-4"}),"Upload file"]})]}):jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[jsx("div",{className:"border-b bg-background",children:jsxs("div",{className:"flex justify-between items-center h-[38px] gap-2 pl-2 pr-1",children:[jsxs("div",{className:"flex items-center gap-2 cursor-pointer",onClick:c,children:[jsx(ChevronsLeft,{className:`h-4 w-4 transition-transform duration-300 ease-in-out ${l?"rotate-180":""}`}),jsx("span",{className:"text-2xs text-muted-foreground",children:l?"Expand":"Collapse"})]}),jsxs("div",{className:"flex items-center gap-0",children:[jsxs(K,{variant:"ghost",size:l?"iconSm":"sm",className:"text-2xs group px-2",onClick:n,disabled:!r?.before||t,children:[jsx(ChevronLeft,{className:"h-4 w-4 opacity-60 -translate-x-0.5 group-hover:-translate-x-3 group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),jsx(ChevronLeft,{className:"h-4 w-4 -ml-6 translate-x-2.5 opacity-0 group-hover:-translate-x-0 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),l?"":"Prev"]}),jsxs(K,{variant:"ghost",size:l?"iconSm":"sm",className:"text-2xs group px-2",onClick:a,disabled:!r?.after||t,children:[l?"":"Next",jsx(ChevronRight,{className:"h-4 w-4 opacity-60 group-hover:translate-x-3 group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),jsx(ChevronRight,{className:"h-4 w-4 -ml-6 -translate-x-2.5 opacity-0 group-hover:translate-x-0.5 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"})]})]})]})}),jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:jsxs(oo,{className:"table-fixed w-full relative",children:[jsxs("colgroup",{children:[jsx("col",{style:{width:"136px"}}),!l&&jsx("col",{style:{width:"136px"}}),jsx("col",{style:{width:"24px"}}),jsx("col",{style:{width:"32px"}})]}),jsx(io,{className:" border-blue-200",children:t?[...Array(5)].map((p,v)=>jsxs(Vr,{className:"!h-8",children:[jsx(Ct,{className:"whitespace-nowrap text-2xs !h-8",children:jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[jsx(Ue,{className:"h-4 w-4 shrink-0"}),jsx(Ue,{className:"h-3 w-20"})]})}),!l&&jsx(Ct,{className:"whitespace-nowrap text-2xs px-2 !h-8 p-0",children:jsx(Ue,{className:"h-3 w-24"})}),jsx(Ct,{className:"!h-8 p-0 justify-center items-center",children:jsx(Ue,{className:"h-3.5 w-3.5 rounded-full"})}),jsx(Ct,{className:"!h-8 p-0 justify-center items-center",children:jsx(Ue,{className:"h-6 w-6"})})]},v)):e.map(p=>{let v=m===p.id;return jsxs(Vr,{className:`!h-8 p-0 cursor-pointer group last:border-b-0 first:border-t-0 ${v?"bg-muted/80 hover:bg-muted":"hover:bg-muted/30"}`,onClick:()=>{h?.setSelectedExtractionId(p.id),o(p);},children:[jsx(Ct,{className:"whitespace-nowrap text-2xs !h-8 flex items-center justify-between gap-2",children:jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[jsx(Kh,{extractionId:p.id,filename:p.file.filename||"Unknown",className:"shrink-0 h-4 w-4"}),jsx("div",{className:"min-w-0 flex-1",children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("span",{className:"inline-block w-fit max-w-full truncate font-medium align-middle",children:p.file.filename||"Unknown"})}),jsx(ze,{children:p.file.filename||"Unknown"})]})})]})}),!l&&jsx(Ct,{className:"whitespace-nowrap text-2xs px-2 text-muted-foreground !h-8 p-0",children:new Date(p.created_at).toLocaleString()}),jsx(Ct,{className:" !h-8 p-0 justify-center items-center gap-2",children:jsx(Gh,{humanReviewStatus:p.human_review_status})}),jsx(Ct,{className:" !h-8 p-0 justify-center items-center gap-2",children:jsxs(mr,{children:[jsx(hr,{asChild:true,children:jsx(K,{size:"iconSm",variant:"ghost",className:"h-6 w-6",onClick:y=>y.stopPropagation(),disabled:u===p.id||d===p.id,children:u===p.id||d===p.id?jsx(Loader2,{className:"h-3.5 w-3.5 animate-spin"}):jsx(MoreVertical,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),jsxs(gr,{align:"end",className:"w-52",children:[p.human_review_status==="review_required"&&jsxs(we,{onClick:y=>{s(y,p.id,"reviewed");},children:[jsx(ShieldCheck,{className:"h-3.5 w-3.5 mr-2"}),jsx("span",{children:"Mark as reviewed"})]}),(p.human_review_status==="success"||p.human_review_status==="reviewed")&&jsxs(we,{className:"text-xs",onClick:y=>{s(y,p.id,"review_required");},children:[jsx(ShieldUser,{className:"h-3.5 w-3.5 mr-2 "}),jsx("span",{className:"text-xs",children:"Mark as requiring review"})]}),jsxs(we,{className:"text-destructive focus:text-destructive focus:bg-destructive/10 text-xs",onClick:y=>{i(y,p.id);},children:[jsx(Trash2,{className:"h-3.5 w-3.5 mr-2 text-destructive"}),jsx("span",{children:"Delete extraction"})]})]})]})})]},p.id)})})]})}),g&&jsx("div",{className:"border-t bg-background items-center justify-center flex",children:jsxs(K,{variant:"ghost",size:"sm",className:"text-xs rounded-none text-muted-foreground hover:text-foreground py-4 w-full h-full",onClick:()=>{if(f){let p=f();h?.setSelectedExtractionId(p);}},children:[jsx(Upload,{className:"h-4 w-4 mr-2"}),"Upload file"]})})]})})})}function YV(e){return useMemo(()=>{let t=[{label:"Created At",value:"created_at"},{label:"Review Status",value:"human_review_status"}],r=[],n=["string","number","integer","boolean"],a=(o,i,s)=>{Object.keys(o).forEach(l=>{let c=o[l],u=i?`${i}.${l}`:l,d=c.title||l.charAt(0).toUpperCase()+l.slice(1).replace(/_/g," "),g=s?`${s} \u203A ${d}`:d;if(c.type!=="array"){if(c.type==="object"&&c.properties){a(c.properties,u,g);return}n.includes(c.type)&&r.push({label:g,value:`completion.${u}`});}});};return e[0]?.json_schema?.properties&&a(e[0].json_schema.properties,"",""),{builtInFields:t,propertyFields:r}},[e])}function eH(e){return useMemo(()=>[...e.builtInFields,...e.propertyFields],[e])}function tH(e){return useMemo(()=>{let t=new Map;for(let r of e){let n=r.predictions;n&&typeof n=="object"&&t.set(r.id,n);}return t},[e])}function rH(e,t){return useMemo(()=>{if(!e.startsWith("completion."))return null;let r=e.replace("completion.",""),n=t.find(o=>o.value===e),a=r.split(".").pop()||r;return {key:r,label:n?.label||a.charAt(0).toUpperCase()+a.slice(1).replace(/_/g," ")}},[e,t])}function IO(e){if(typeof e=="string"&&/^[-+]?\d+(?:\.\d+)?$/.test(e.trim())){let t=Number(e);return Number.isFinite(t)?t:e}return e}var FO={review_required:0,reviewed:1,success:2};function nH(e,t,r,n){return useMemo(()=>{if(!t||e.length===0)return e;let a=[...e].sort((o,i)=>{let s,l;if(t==="created_at")s=new Date(o.created_at).getTime(),l=new Date(i.created_at).getTime();else if(t==="human_review_status")s=FO[o.human_review_status]??3,l=FO[i.human_review_status]??3;else if(t.startsWith("completion.")){let d=t.replace("completion.",""),g=n.get(o.id),f=n.get(i.id);s=Zu(g,d),l=Zu(f,d);}if(s==null&&l==null)return 0;if(s==null)return 1;if(l==null)return -1;s=IO(s),l=IO(l);let c=typeof s,u=typeof l;return c==="boolean"&&u==="boolean"?s===l?0:s?-1:1:c==="number"&&u==="number"?s-l:c==="string"&&u==="string"?s.toLowerCase().localeCompare(l.toLowerCase()):String(s).localeCompare(String(l))});return r==="desc"?a.reverse():a},[e,t,r,n])}function Zh(e,t,r){let n=YV(e),a=eH(n),o=tH(e),i=nH(e,t,r,o),s=rH(t,a);return {sortFields:n,allSortFields:a,parsedPredictions:o,sortedExtractions:i,sortFieldInfo:s}}var gH=()=>{let e="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",t="extr_";for(let r=0;r<21;r++)t+=e.charAt(Math.floor(Math.random()*e.length));return t};function yH({projectId:e,extractionId:t,onNavigate:r,initialFilters:n=[],visibility:{search:a=false,metadataFilter:o=false,filterMenu:i=true,displayMenu:s=true,exportMenu:l=true,uploadButton:c=true,extractionDisplayOptions:{allowEditing:u=false,showReasoning:d=false,showTabs:g=true}={}}={},defaultView:f="form"}){let h=useQueryClient(),{fetchWithAuth:m}=Ve(),p=Za(),[v,y]=useState(true),x=useRef(null),[w,_]=useState(null),E=useCallback(()=>{let oe=gH();return x.current=oe,_(oe),r({extractionId:oe}),oe},[r]);useEffect(()=>{x.current&&t!==x.current&&(x.current=null,_(null));},[t]),useEffect(()=>{t&&p?.selectedExtractionId!==t&&p?.setSelectedExtractionId(t);},[t,p]);let C=t===x.current||t===w,{data:P}=Ga({origin_dot_id:e,human_review_status:"review_required",limit:10,order:"desc"}),T=useMemo(()=>{if(!t||t==="null"||!P?.data||P.data.length===0)return null;let oe=P.data,wt=oe.findIndex(Lt=>Lt.id===t);if(wt!==-1){let Lt=(wt+1)%oe.length;return oe[Lt].id}return oe.length>0?oe[0].id:null},[t,P]),N=useCallback(()=>{T?r({extractionId:T}):toast.info("No more items to review");},[T,r]),{data:S}=useQuery({queryKey:Bt.detail(t||"null"),queryFn:async()=>{if(!t)return null;let oe=await m(`/v1/extractions/${t}`);if(oe.status===404)return null;if(!oe.ok){let wt=await oe.text();throw new Error(`Failed to fetch extraction: ${oe.status} ${wt}`)}return oe.json()},enabled:!!t&&!C,retry:(oe,wt)=>wt.message?.includes("404")?false:oe<3}),[b,k]=useState(null),[D,O]=useState(null),[$,A]=useState(false),[F,X]=useState(20),[H,L]=useState("created_at"),[Q,z]=useState("desc"),[ae,M]=useState(n),j=useMemo(()=>{let oe=ae.find(At=>At.field==="created_date"&&At.operator==="within");if(oe)return {from:oe.value?new Date(oe.value):void 0,to:oe.endValue?new Date(oe.endValue):void 0};let wt=ae.find(At=>At.field==="created_date"&&At.operator==="after"),Lt=ae.find(At=>At.field==="created_date"&&At.operator==="before");return {from:wt?.value?new Date(wt.value):void 0,to:Lt?.value?new Date(Lt.value):void 0}},[ae]),ue=useMemo(()=>{let oe=ae.find(wt=>wt.field==="status");if(oe&&oe.operator!=="is_not")return oe?.value},[ae]),ie=useMemo(()=>{let oe=ae.filter(Lt=>Lt.field==="metadata"&&Lt.operator==="is"&&Lt.metadataKey);if(oe.length===0)return;let wt={};for(let Lt of oe)Lt.metadataKey&&(wt[Lt.metadataKey]=String(Lt.value));return wt},[ae]),[Ce,Te]=useState(""),[Je,vt]=useState("");useEffect(()=>{let oe=setTimeout(()=>{vt(Ce),k(null),O(null);},500);return ()=>clearTimeout(oe)},[Ce]);let gt=Ga({before:b||void 0,after:D||void 0,limit:F,order:H==="created_at"?Q:"desc",origin_dot_id:e,filename:Je||void 0,human_review_status:ue,from_date:j.from?format(j.from,"yyyy-MM-dd"):void 0,to_date:j.to?format(j.to,"yyyy-MM-dd"):void 0,metadata:ie}),bt=gt.data?.data||[],We=gt.data?.list_metadata,ke=useMemo(()=>{let oe=bt,wt=ae.find(At=>At.field==="status");wt&&wt.operator==="is_not"&&(oe=oe.filter(At=>At.human_review_status!==wt.value));let Lt=ae.filter(At=>At.field==="metadata"&&At.operator==="contains"&&At.metadataKey);for(let At of Lt)if(At.metadataKey){let bu=String(At.value).toLowerCase();oe=oe.filter(vl=>{let xu=vl.metadata?.[At.metadataKey];return xu===void 0?false:xu.toLowerCase().includes(bu)});}return oe},[bt,ae]),{sortFields:be,allSortFields:re,sortedExtractions:me}=Zh(ke,H,Q),{mutateAsync:ye}=vp(),{mutateAsync:ge}=ql(),[Z,W]=useState(null),[ee,V]=useState(null),[Re,Ee]=useState(null),$e=(oe,wt)=>{oe.stopPropagation(),Ee(wt);},nn=async()=>{if(Re){W(Re);try{await ye(Re),Ee(null);}finally{W(null);}}},Ln=async(oe,wt,Lt)=>{oe.stopPropagation(),V(wt);try{await ge({extractionId:wt,human_review_status:Lt}),h.invalidateQueries({queryKey:[...Bt.all,"count"]}),h.invalidateQueries({queryKey:Bt.lists()});}finally{V(null);}},an=useCallback(()=>{We?.after&&(O(We.after),k(null));},[We]),te=useCallback(()=>{We?.before&&(k(We.before),O(null));},[We]),Be=useCallback(oe=>{r({extractionId:oe.id});},[r]);return jsxs("div",{className:"flex-1 flex flex-col min-h-0 gap-0 overflow-hidden",children:[jsxs("div",{className:"flex items-center justify-between gap-2 p-2",children:[i&&jsx(Jh,{filters:ae,onFiltersChange:M,showMetadataFilter:o}),jsxs("div",{className:"flex items-center gap-2",children:[a&&jsxs("div",{className:"relative w-40",children:[jsx(Search,{className:"absolute left-2 top-1.75 h-3.5 w-3.5 text-muted-foreground"}),jsx(Ze,{placeholder:"Search file...",value:Ce,onChange:oe=>Te(oe.target.value),className:"pl-7 h-7 !text-2xs"})]}),s&&jsxs(Ht,{open:$,onOpenChange:A,children:[jsx(Jt,{asChild:true,children:jsxs(K,{variant:"outline",size:"sm",className:"text-2xs h-7 py-0 px-0.5",children:[jsx(Settings2,{className:"size-3.5 mr-1"}),jsx("span",{children:"Display"})]})}),jsx(Wt,{className:"w-72 p-3",align:"end",children:jsx("div",{className:"space-y-3",children:jsxs("div",{className:"flex flex-col gap-2",children:[jsxs("label",{className:"text-xs font-semibold text-gray-900 flex items-center gap-1.5",children:[jsx(ArrowUpWideNarrowIcon,{className:"h-3.5 w-3.5"}),"Ordering"]}),jsxs("div",{className:"flex items-center gap-2",children:[jsxs(mr,{children:[jsx(hr,{asChild:true,children:jsxs(K,{variant:"outline",className:"flex-1 min-w-0 justify-between text-xs h-8",children:[jsx("span",{className:"truncate",children:re.find(oe=>oe.value===H)?.label||"Select field"}),jsx(ChevronRight,{className:"h-3.5 w-3.5 ml-2 shrink-0 opacity-50 rotate-90"})]})}),jsxs(gr,{align:"start",className:"w-56",children:[jsx(oc,{value:H,onValueChange:L,children:be.builtInFields.map(oe=>jsx(ic,{value:oe.value,className:"text-xs",children:oe.label},oe.value))}),be.propertyFields.length>0&&jsxs(Fragment,{children:[jsx(ka,{}),jsxs(Xr,{children:[jsxs(Qr,{className:"text-xs",children:[jsx(Database,{className:"h-3.5 w-3.5 mr-2"}),"Extracted Properties"]}),jsx(Yr,{className:"max-h-64 max-w-56 overflow-y-auto",children:jsx(oc,{value:H,onValueChange:L,children:be.propertyFields.map(oe=>jsx(ic,{value:oe.value,className:"text-xs",children:jsx("span",{className:"truncate",children:oe.label})},oe.value))})})]})]})]})]}),jsxs("div",{className:"flex gap-2 shrink-0",children:[jsx("button",{onClick:()=>z("asc"),className:`flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs rounded transition-colors ${Q==="asc"?"bg-indigo-50 text-indigo-700 font-medium":"bg-gray-50 text-gray-600 hover:bg-gray-100"}`,children:jsx(ArrowUpWideNarrowIcon,{className:"h-4 w-4"})}),jsx("button",{onClick:()=>z("desc"),className:`flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs rounded transition-colors ${Q==="desc"?"bg-indigo-50 text-indigo-700 font-medium":"bg-gray-50 text-gray-600 hover:bg-gray-100"}`,children:jsx(ArrowDownWideNarrowIcon,{className:"h-4 w-4"})})]})]})]})})})]}),l&&jsx(RO,{projectId:e,metadata:ie,dateRange:j,statusFilter:ue,searchQuery:Je})]})]}),jsxs("div",{className:"flex flex-row gap-0 flex-1 min-h-0 overflow-hidden",children:[jsx($O,{extractions:me,isLoading:gt.isLoading,paginationMetadata:We,onPrevPage:te,onNextPage:an,onExtractionClick:Be,onDeleteClick:$e,onStatusChange:Ln,isCollapsed:v,onCollapseToggle:()=>y(!v),deletingId:Z,updatingId:ee,onNewExtraction:E,showUploadButton:c}),jsx("div",{className:"flex-col min-w-0 flex flex-1 min-h-0",children:t?jsx("div",{className:"bg-white flex flex-col flex-1 min-h-0 gap-3",children:jsx("div",{className:"flex-1 flex flex-col min-h-0 border-t border-gray-200",children:jsx(sw,{extractionId:t,projectId:e,isNewExtraction:C,extractionDisplayOptions:{view:f,allowEditing:u,showReasoning:d,showTabs:g},continueButtonOptions:{onClick:N,label:S?.human_review_status==="review_required"?"Mark as reviewed":"Save"}})})}):jsx("div",{className:"flex-1 flex items-center justify-center border-t border-gray-200",children:jsxs("div",{className:"flex flex-col items-center justify-center max-w-md text-center p-8 space-y-6",children:[jsxs("div",{className:"relative",children:[jsx("div",{className:"absolute inset-0 bg-indigo-100/60 rounded-full blur-xl animate-pulse"}),jsx("div",{className:"relative flex items-center justify-center w-20 h-20 rounded-full bg-gradient-to-br from-indigo-50 to-slate-100 border border-indigo-100/50 shadow-sm",children:jsx(FileSearch,{className:"w-9 h-9 text-indigo-400",strokeWidth:1.5})})]}),jsxs("div",{className:"space-y-2",children:[jsx("h3",{className:"text-lg font-semibold text-slate-800 tracking-tight",children:"Select an extraction"}),jsx("p",{className:"text-sm text-slate-500 leading-relaxed",children:"Choose an extraction from the list to view and review its details"})]}),jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 rounded-full bg-slate-100/80 border border-slate-200/60",children:[jsx(MousePointerClick,{className:"w-4 h-4 text-slate-400"}),jsx("span",{className:"text-xs text-slate-500 font-medium",children:"Click on any item in the list"})]})]})})})]}),jsx(Ri,{open:Re!==null,onOpenChange:oe=>!oe&&Ee(null),children:jsxs(Oi,{className:"p-0 gap-0 bg-gray-50 rounded-2xl border-none shadow-2xl",children:[jsx("div",{className:"bg-white shadow-xs rounded-2xl",children:jsxs(Di,{className:"p-6 pb-4",children:[jsx($i,{className:"text-lg font-medium text-slate-900",children:"Delete extraction"}),jsx(Ii,{children:"Are you sure you want to delete this extraction? This action cannot be undone."})]})}),jsxs(Ai,{className:"p-4",children:[jsx(wc,{disabled:Z!==null,children:"Cancel"}),jsx(Fi,{onClick:nn,disabled:Z!==null,className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay ring-1 bg-destructive hover:bg-destructive hover:opacity-80 text-white ring-destructive gap-2",children:Z!==null?jsxs(Fragment,{children:[jsx(Loader2,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})}function PH({title:e,onSelectExtraction:t,onNewExtractionClick:r,visibility:{displayPopover:n=true,statusColumn:a=false,dateColumn:o=true,search:i=true,filters:s=false,metadataFilter:l=false}={},initialFilters:c=[]}={}){let{project:u}=Fr(),d=useQueryClient(),g=Za(),f=g?.selectedExtractionId??null,[h,m]=useState(null),[p,v]=useState(null),[y,x]=useState(c),w=useMemo(()=>{let V=y.find($e=>$e.field==="created_date"&&$e.operator==="after"),Re=y.find($e=>$e.field==="created_date"&&$e.operator==="before"),Ee=y.find($e=>$e.field==="created_date"&&$e.operator==="within");return Ee?{from:Ee.value instanceof Date?Ee.value:new Date(Ee.value),to:Ee.endValue}:{from:V?.value?V.value instanceof Date?V.value:new Date(V.value):void 0,to:Re?.value?Re.value instanceof Date?Re.value:new Date(Re.value):void 0}},[y]),_=useMemo(()=>{let V=y.find(Re=>Re.field==="status");if(V&&V.operator!=="is_not")return V?.value},[y]),E=useMemo(()=>{let V=y.filter(Ee=>Ee.field==="metadata"&&Ee.operator==="is"&&Ee.metadataKey);if(V.length===0)return;let Re={};for(let Ee of V)Ee.metadataKey&&(Re[Ee.metadataKey]=String(Ee.value));return Re},[y]),[C,P]=useState(false),[T,N]=useState(20),[S,b]=useState("created_at"),[k,D]=useState("desc"),[O,$]=useState(""),[A,F]=useState("");useEffect(()=>{let V=setTimeout(()=>{F(O),m(null),v(null);},500);return ()=>clearTimeout(V)},[O]);let X=Ga({before:h||void 0,after:p||void 0,limit:T,order:S==="created_at"?k:"desc",origin_dot_id:u.id,filename:A||void 0,human_review_status:_,from_date:w.from?format(w.from,"yyyy-MM-dd"):void 0,to_date:w.to?format(w.to,"yyyy-MM-dd"):void 0,metadata:E}),H=X.data?.data||[],L=X.data?.list_metadata,Q=useMemo(()=>{let V=H,Re=y.find($e=>$e.field==="status");Re&&Re.operator==="is_not"&&(V=V.filter($e=>$e.human_review_status!==Re.value));let Ee=y.filter($e=>$e.field==="metadata"&&$e.operator==="contains"&&$e.metadataKey);for(let $e of Ee)if($e.metadataKey){let nn=String($e.value).toLowerCase();V=V.filter(Ln=>{let an=Ln.metadata?.[$e.metadataKey];return an===void 0?false:an.toLowerCase().includes(nn)});}return V},[H,y]),{sortFields:z,allSortFields:ae,sortedExtractions:M,sortFieldInfo:j,parsedPredictions:ue}=Zh(Q,S,k),ie=j!==null,{mutateAsync:Ce}=vp(),{mutateAsync:Te}=ql(),[Je,vt]=useState(null),[gt,bt]=useState(null),[We,ke]=useState(null),[be,re]=useState(null),me=(V,Re)=>{V.stopPropagation(),re(Re),ke(null);},ye=async()=>{if(be){vt(be);try{await Ce(be),re(null);}finally{vt(null);}}},ge=async(V,Re,Ee)=>{V.stopPropagation(),bt(Re),ke(null);try{await Te({extractionId:Re,human_review_status:Ee}),d.invalidateQueries({queryKey:[...Bt.all,"count"]}),d.invalidateQueries({queryKey:Bt.lists()});}finally{bt(null);}},Z=useCallback(()=>{L?.after&&(v(L.after),m(null));},[L]),W=useCallback(()=>{L?.before&&(m(L.before),v(null));},[L]),ee=useCallback(V=>{g?.setSelectedExtractionId(V.id),t&&t(V);},[t,g]);return jsxs(kn,{className:"shadow-none gap-3 border-none py-0 flex flex-1 min-h-0",children:[jsx(Rn,{className:"px-0 pb-0 gap-0",children:jsxs("div",{className:"flex items-center justify-between gap-2",children:[e&&jsx(On,{children:e}),s&&jsx(Jh,{size:"md",filters:y,onFiltersChange:x,showMetadataFilter:l}),jsxs("div",{className:"flex items-center gap-2 ml-auto",children:[i&&jsxs("div",{className:"relative w-40",children:[jsx(Search,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),jsx(Ze,{placeholder:"Search file...",value:O,onChange:V=>$(V.target.value),className:"pl-8 h-8 !text-xs"})]}),n&&jsxs(Ht,{open:C,onOpenChange:P,children:[jsx(Jt,{asChild:true,children:jsxs(K,{variant:"outline",size:"sm",className:"text-xs",children:[jsx(SlidersHorizontal,{className:"h-3.5 w-3.5 mr-1.5"}),jsx("span",{children:"Display"})]})}),jsx(Wt,{className:"w-80 p-4",align:"end",children:jsxs("div",{className:"space-y-4",children:[jsxs("div",{children:[jsx("label",{className:"text-xs font-semibold text-gray-900 mb-2 block",children:"Items per page"}),jsx("div",{className:"grid grid-cols-5 gap-2",children:[1,10,25,50,100].map(V=>jsx("button",{onClick:()=>N(V),className:`px-3 py-2 text-xs rounded border transition-all ${T===V?"bg-indigo-50 border-indigo-500 text-indigo-700 font-semibold":"border-gray-200 text-gray-700 hover:bg-gray-50 hover:border-gray-300"}`,children:V},V))})]}),jsx("div",{className:"border-t border-gray-200"}),jsxs("div",{className:"flex flex-col gap-2",children:[jsx("label",{className:"text-xs font-semibold text-gray-900 block",children:"Sort by"}),jsxs("div",{className:"flex items-center gap-2",children:[jsxs(mr,{children:[jsx(hr,{asChild:true,children:jsxs(K,{variant:"outline",className:"flex-1 min-w-0 justify-between text-xs h-9",children:[jsx("span",{className:"truncate",children:ae.find(V=>V.value===S)?.label||"Select field"}),jsx(ChevronRight,{className:"h-3.5 w-3.5 ml-2 shrink-0 opacity-50 rotate-90"})]})}),jsxs(gr,{align:"start",className:"w-56",children:[jsx(oc,{value:S,onValueChange:b,children:z.builtInFields.map(V=>jsx(ic,{value:V.value,className:"text-xs",children:V.label},V.value))}),z.propertyFields.length>0&&jsxs(Fragment,{children:[jsx(ka,{}),jsxs(Xr,{children:[jsxs(Qr,{className:"text-xs",children:[jsx(Database,{className:"h-3.5 w-3.5 mr-2"}),"Extracted Properties"]}),jsx(Yr,{className:"max-h-64 max-w-56 overflow-y-auto",children:jsx(oc,{value:S,onValueChange:b,children:z.propertyFields.map(V=>jsx(ic,{value:V.value,className:"text-xs",children:jsx("span",{className:"truncate",children:V.label})},V.value))})})]})]})]})]}),jsxs("div",{className:"flex gap-2 shrink-0",children:[jsx("button",{onClick:()=>D("asc"),className:`flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs rounded transition-colors ${k==="asc"?"bg-indigo-50 text-indigo-700 font-medium":"bg-gray-50 text-gray-600 hover:bg-gray-100"}`,children:jsx(ArrowUpWideNarrowIcon,{className:"h-4 w-4"})}),jsx("button",{onClick:()=>D("desc"),className:`flex items-center justify-center gap-1.5 px-2 py-1.5 text-xs rounded transition-colors ${k==="desc"?"bg-indigo-50 text-indigo-700 font-medium":"bg-gray-50 text-gray-600 hover:bg-gray-100"}`,children:jsx(ArrowDownWideNarrowIcon,{className:"h-4 w-4"})})]})]})]})]})})]})]})]})}),jsx(Dn,{className:"flex flex-col flex-1 min-h-0 p-0 border border-gray-200 rounded-md",children:jsx("div",{className:"rounded-md bg-card flex flex-col flex-1 min-h-0 overflow-hidden",children:X.isLoading?jsx("div",{className:"flex flex-col flex-1 min-h-0",children:jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:jsxs(oo,{className:"table-fixed w-full relative",children:[jsxs("colgroup",{children:[jsx("col",{style:{width:ie?"35%":o&&a?"40%":o||a?"50%":"90%"}}),ie&&jsx("col",{style:{width:"25%"}}),o&&jsx("col",{style:{width:ie?"20%":a?"30%":"40%"}}),a&&jsx("col",{style:{width:ie?"12%":o?"20%":"40%"}}),jsx("col",{style:{width:ie?"8%":"10%"}})]}),jsx(ji,{className:"sticky top-0 left-0 right-0 z-10 bg-white border-green-200",children:jsxs(Vr,{className:"border-none p-0 h-4",children:[jsx(Nr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"File"})}),ie&&jsx(Nr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:j?.label})}),o&&jsx(Nr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"Date"})}),a&&jsx(Nr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"Status"})}),jsx(Nr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full"})})]})}),jsx(io,{children:[...Array(5)].map((V,Re)=>jsxs(Vr,{className:"h-12.5",children:[jsx(Ct,{children:jsxs("div",{className:"flex items-center gap-3",children:[jsx(Ue,{className:"h-10 w-10 shrink-0"}),jsx(Ue,{className:"h-4 w-3/4"})]})}),ie&&jsx(Ct,{children:jsx(Ue,{className:"h-4 w-24"})}),o&&jsx(Ct,{children:jsx(Ue,{className:"h-4 w-32"})}),a&&jsx(Ct,{children:jsx(Ue,{className:"h-6 w-24"})}),jsx(Ct,{children:jsx(Ue,{className:"h-6 w-6"})})]},Re))})]})})}):M.length===0?jsxs("div",{className:"flex flex-col items-center justify-center p-8 gap-4 flex-1",children:[jsxs("div",{className:"text-center space-y-2",children:[jsx("p",{className:"text-sm text-muted-foreground",children:"No extractions yet."}),jsx("p",{className:"text-xs text-muted-foreground",children:"Upload and process files to see results here."})]}),r&&jsxs(K,{variant:"outline",size:"sm",onClick:r,className:"gap-2",children:[jsx(Upload,{className:"h-4 w-4"}),"Upload file"]})]}):jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:jsxs(oo,{className:"table-fixed w-full relative",children:[jsxs("colgroup",{children:[jsx("col",{style:{width:ie?"35%":o&&a?"40%":o||a?"50%":"90%"}}),ie&&jsx("col",{style:{width:"25%"}}),o&&jsx("col",{style:{width:ie?"20%":a?"30%":"40%"}}),a&&jsx("col",{style:{width:ie?"12%":o?"20%":"40%"}}),jsx("col",{style:{width:ie?"8%":"10%"}})]}),jsx(ji,{className:"sticky top-0 left-0 right-0 z-10 bg-white border-green-200",children:jsxs(Vr,{className:"border-none p-0 h-4",children:[jsx(Nr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"File"})}),ie&&jsx(Nr,{className:"text-xs text-black p-0",children:jsxs("button",{className:"border-b px-3 py-2 items-center flex w-full h-full gap-1 hover:bg-muted/50 transition-colors cursor-pointer",onClick:()=>D(k==="asc"?"desc":"asc"),children:[jsx("span",{className:"truncate",children:j?.label}),k==="asc"?jsx(ArrowUpWideNarrowIcon,{className:"h-3 w-3 text-muted-foreground shrink-0"}):jsx(ArrowDownWideNarrowIcon,{className:"h-3 w-3 text-muted-foreground shrink-0"})]})}),o&&jsx(Nr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"Date"})}),a&&jsx(Nr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"Status"})}),jsx(Nr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full"})})]})}),jsx(io,{className:" border-blue-200",children:M.map(V=>{let Re=f===V.id,Ee=j?Zu(ue.get(V.id),j.key):null;return jsxs(Vr,{className:`h-12.5 cursor-pointer group last:border-b-0 first:border-t-0 ${Re?"bg-muted/80 hover:bg-muted":"hover:bg-muted/30"}`,onClick:()=>ee(V),children:[jsx(Ct,{className:"whitespace-nowrap text-xs",children:jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[jsx(Kh,{extractionId:V.id,filename:V.file.filename||"Unknown",className:"shrink-0 h-6 w-6"}),jsx("div",{className:"min-w-0 flex-1",children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("span",{className:"inline-block w-fit max-w-full truncate font-medium align-middle",children:V.file.filename||"Unknown"})}),jsx(ze,{children:V.file.filename||"Unknown"})]})})]})}),ie&&jsx(Ct,{className:"text-xs text-muted-foreground",children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("span",{className:"inline-block max-w-full truncate",children:Ee!=null?typeof Ee=="boolean"?Ee?"Yes":"No":String(Ee):jsx("span",{className:"text-muted-foreground/50 italic",children:"\u2014"})})}),jsx(ze,{children:Ee!=null?String(Ee):"No value"})]})}),o&&jsx(Ct,{className:"whitespace-nowrap text-xs text-muted-foreground",children:new Date(V.created_at).toLocaleString()}),a&&jsx(Ct,{children:jsx(Gh,{style:"badge",humanReviewStatus:V.human_review_status})}),jsx(Ct,{className:"text-right pr-4",children:jsxs(Ht,{open:We===V.id,onOpenChange:$e=>ke($e?V.id:null),children:[jsx(Jt,{asChild:true,children:jsx(K,{size:"iconSm",variant:"ghost",className:"opacity-0 group-hover:opacity-100 transition-opacity h-6 w-6",onClick:$e=>$e.stopPropagation(),disabled:Je===V.id||gt===V.id,children:Je===V.id||gt===V.id?jsx(Loader2,{className:"h-3.5 w-3.5 animate-spin"}):jsx(MoreVertical,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),jsxs(Wt,{align:"end",className:"flex flex-col gap-1 p-2 w-52",children:[V.human_review_status==="review_required"&&jsxs("button",{className:"text-left px-3 py-2 flex items-center gap-2 text-xs rounded hover:bg-gray-50",onClick:$e=>{ge($e,V.id,"reviewed");},children:[jsx(ShieldCheck,{className:"h-3.5 w-3.5"}),jsx("span",{children:"Mark as reviewed"})]}),(V.human_review_status==="success"||V.human_review_status==="reviewed")&&jsxs("button",{className:"text-left px-3 py-2 flex items-center gap-2 text-xs rounded hover:bg-gray-50",onClick:$e=>{ge($e,V.id,"review_required");},children:[jsx(ShieldUser,{className:"h-3.5 w-3.5"}),jsx("span",{children:"Mark as requiring review"})]}),jsxs("button",{className:"text-left px-3 py-2 flex items-center gap-2 text-xs rounded hover:bg-destructive/10 text-destructive",onClick:$e=>me($e,V.id),children:[jsx(Trash2,{className:"h-3.5 w-3.5"}),jsx("span",{children:"Delete extraction"})]})]})]})})]},V.id)})})]})}),jsx("div",{className:"border-t bg-background",children:jsxs("div",{className:"flex justify-between items-center p-2 gap-2",children:[jsx("div",{children:r&&jsxs(K,{variant:"ghost",size:"sm",className:"text-xs text-muted-foreground hover:text-foreground",onClick:()=>{r();},children:[jsx(Upload,{className:"h-4 w-4 mr-2"}),"Upload file"]})}),jsxs("div",{className:"flex items-center gap-2",children:[jsxs(K,{variant:"outline",size:"sm",className:"text-xs group px-2",onClick:W,disabled:!L?.before||X.isLoading,children:[jsx(ChevronLeft,{className:"h-4 w-4 opacity-60 -translate-x-0.5 group-hover:-translate-x-3 group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),jsx(ChevronLeft,{className:"h-4 w-4 -ml-6 translate-x-2.5 opacity-0 group-hover:-translate-x-0 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),"Prev"]}),jsxs(K,{variant:"outline",size:"sm",className:"text-xs group px-2",onClick:Z,disabled:!L?.after||X.isLoading,children:["Next",jsx(ChevronRight,{className:"h-4 w-4 opacity-60 group-hover:translate-x-3 group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),jsx(ChevronRight,{className:"h-4 w-4 -ml-6 -translate-x-2.5 opacity-0 group-hover:translate-x-0.5 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"})]})]})]})})]})})}),jsx(Ri,{open:be!==null,onOpenChange:V=>!V&&re(null),children:jsxs(Oi,{className:"p-0 gap-0 bg-gray-50 rounded-2xl border-none shadow-2xl",children:[jsx("div",{className:"bg-white shadow-xs rounded-2xl",children:jsxs(Di,{className:"p-6 pb-4",children:[jsx($i,{className:"text-lg font-medium text-slate-900",children:"Delete extraction"}),jsx(Ii,{children:"Are you sure you want to delete this extraction? This action cannot be undone."})]})}),jsxs(Ai,{className:"p-4",children:[jsx(wc,{disabled:Je!==null,children:"Cancel"}),jsx(Fi,{onClick:ye,disabled:Je!==null,className:"group relative isolate inline-flex items-center justify-center overflow-hidden text-left font-medium transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)] before:duration-300 before:ease-[cubic-bezier(0.4,0.36,0,1)] before:transtion-opacity rounded-md shadow-[0_1px_theme(colors.white/0.07)_inset,0_1px_3px_theme(colors.gray.900/0.2)] before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:rounded-md before:bg-gradient-to-b before:from-white/20 before:opacity-50 hover:before:opacity-100 after:pointer-events-none after:absolute after:inset-0 after:-z-10 after:rounded-md after:bg-gradient-to-b after:from-white/10 after:from-[46%] after:to-[54%] after:mix-blend-overlay ring-1 bg-destructive hover:bg-destructive hover:opacity-80 text-white ring-destructive gap-2",children:Je!==null?jsxs(Fragment,{children:[jsx(Loader2,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})}function KO({className:e="h-12 w-12 text-gray-400",strokeWidth:t=2}){return jsx("svg",{className:e,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:t,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 0 1 -2 -2V5a2 2 0 0 1 2 -2h5.586a1 1 0 0 1 .707 .293l5.414 5.414a1 1 0 0 1 .293 .707V19a2 2 0 0 1 -2 2z"})})}function GO({open:e,onOpenChange:t,files:r}){let n=Gx,a=br("gray");return jsx(Ri,{open:e,onOpenChange:t,children:jsxs(Oi,{children:[jsxs(Di,{children:[jsx($i,{children:"PDF too long"}),jsxs(Ii,{children:["The following PDF file",r.length>1?"s are":" is"," over ",n," pages and cannot be uploaded. Please split ",r.length>1?"them":"it"," into smaller documents (\u2264 ",n," pages) and try again.",jsx("br",{})]})]}),r.length>0&&jsx("ul",{className:"mt-2 text-sm space-y-1",children:r.map(o=>jsxs("li",{className:"flex items-center justify-between gap-4",children:[jsx("div",{className:"flex",children:jsxs("div",{className:`flex items-center w-full justify-start ${a.headerText} border ${a.border} px-1 py-1 rounded-sm ${a.headerBg}`,children:[jsx(KO,{className:"h-4 w-4 mr-1"}),jsx("span",{className:"truncate",children:(()=>{let i=o.name,s=i.lastIndexOf(".");if(s>0){let l=i.substring(0,s);return l.length>10?`${l.substring(0,10)}...`:l}return i.length>15?`${i.substring(0,15)}...`:i})()}),o.name&&o.name.lastIndexOf(".")>0&&jsx("span",{className:"ml-0",children:o.name.substring(o.name.lastIndexOf("."))})]})}),jsxs(xn,{variant:"outline",className:"shrink-0 py-1 text-sm",children:[o.pages," pages"]})]},o.name))}),jsxs(Ai,{className:"flex flex-row gap-2 justify-between items-center",children:[jsxs("span",{className:"text-xs text-muted-foreground mr-auto",children:["Need help with a complex case? Email us at ",jsx("a",{href:"mailto:support@retab.com",className:"text-gray-800",children:"support@retab.com"})]}),jsx(Fi,{onClick:()=>t(false),children:"OK"})]})]})})}var hw=e=>(e/(1024*1024)).toFixed(1),XO=({children:e,handleFileUpload:t,multiple:r=false,className:n,accept:a,maxFileSize:o=10*1024*1024,exposeOpenDialog:i})=>{let[s,l]=useState(false),[c,u]=useState(false),d=useRef(0),g=useRef(null),[f,h]=useState(false),[m,p]=useState([]),v=N=>{if(!a)return true;let S=a.split(",").map(D=>D.trim().toLowerCase()),{type:b,name:k}=N;return S.some(D=>D.startsWith(".")?k.toLowerCase().endsWith(D):D.endsWith("/*")?b.startsWith(D.slice(0,-2)):b===D)},y=N=>v(N)?N.size>o?(toast.error(`Maximum size is ${hw(o)}\xA0MB, but ${N.name} is ${hw(N.size)}\xA0MB`),false):true:(toast.error(`The file ${N.name} is not an accepted type.`),false),x=async N=>{if(!r&&N.length>1){toast.error("Only one file allowed. Drop a single file or enable multiple uploads.");return}let S=Array.from(N).filter(y);S.length,N.length;let{accepted:b,rejected:k,corrupted:D}=await eO(S);if(k.length>0&&(p(k),h(true)),D.length>0){let A=D.map(F=>F.reason?`${F.name} (${F.reason})`:F.name).join(", ");toast.error(`Skipped corrupted file${D.length>1?"s":""}: ${A}`);}if(b.length===0)return;l(true);let O=new DataTransfer;for(let A of b)O.items.add(A);let $=()=>{l(false);};t(Array.from(O.files),$).catch(A=>{console.error(A),toast.error(A?.message||"Something went wrong"),l(false);});},w=useCallback(N=>{N.preventDefault(),d.current+=1,N.dataTransfer.items&&N.dataTransfer.items[0]&&N.dataTransfer.items[0].kind==="file"&&u(true);},[]),_=useCallback(N=>{N.preventDefault(),d.current-=1,d.current<=0&&(d.current=0,u(false));},[]),E=useCallback(N=>{N.preventDefault();},[]),C=useCallback(async N=>{N.preventDefault(),d.current=0,u(false);let S=N.dataTransfer?.files;S&&S.length&&await x(S);},[]),P=()=>{g.current?.click();};Rt__default.useEffect(()=>{typeof i=="function"&&i(P);},[i]);let T=async N=>{N.target.files&&(await x(N.target.files),N.target.value="");};return jsxs("div",{className:R("relative",n),onDragEnter:w,onDragLeave:_,onDragOver:E,onDrop:C,children:[e,c&&jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm",children:jsxs("div",{className:"p-12 max-w-md mx-4 text-center animate-in fade-in duration-200",children:[jsx("div",{className:"text-gray-100 mb-6",children:jsx(ImageIcon,{className:"h-16 w-16 mx-auto"})}),jsx("h3",{className:"text-2xl font-semibold text-white mb-3",children:"Drop Files Here"}),jsx("p",{className:"text-gray-100 text-base mb-4",children:"Release to upload documents to your project"}),a&&jsxs("p",{className:"text-sm text-gray-200 mt-3",children:["Supported: ",a]}),jsxs("p",{className:"text-sm text-gray-200 mt-2",children:["Maximum file size: ",hw(o)," MB"]})]})}),jsx("input",{"aria-label":"File input",ref:g,type:"file",accept:a,multiple:r,onChange:T,className:"hidden"}),s&&jsx("div",{className:"absolute inset-0 z-50 grid place-items-center bg-white/70 backdrop-blur-sm",children:jsx("span",{className:"text-sm text-gray-700 animate-pulse",children:"Uploading\u2026"})}),jsx(GO,{open:f,onOpenChange:h,files:m})]})};var fa={all:["upload-jobs"],lists:()=>[...fa.all,"list"],list:e=>[...fa.lists(),{filters:e}],details:()=>[...fa.all,"detail"],detail:e=>[...fa.details(),e]};var YO=(e={},t={})=>{let{enabled:r=true,refetchInterval:n}=t,{fetchWithAuth:a}=Ve();return useQuery({queryKey:fa.list(e),queryFn:async()=>{let o=new URLSearchParams;e.before&&o.append("before",e.before),e.after&&o.append("after",e.after),e.limit!==void 0&&o.append("limit",String(e.limit)),e.order&&o.append("order",e.order),e.sort_path&&o.append("sort_path",e.sort_path),e.status&&o.append("status",e.status),e.pipeline_status&&o.append("pipeline_status",e.pipeline_status),e.exclude_pipeline_status&&o.append("exclude_pipeline_status",e.exclude_pipeline_status),e.file_id&&o.append("file_id",e.file_id),e.extraction_id&&o.append("extraction_id",e.extraction_id),e.project_id&&o.append("project_id",e.project_id),e.metadata&&Object.keys(e.metadata).length>0&&o.append("metadata",JSON.stringify(e.metadata));let i=`/internal/upload-jobs${o.toString()?`?${o.toString()}`:""}`,s=await a(i);if(!s.ok)throw await Et(s,"Failed to fetch upload jobs");return s.json()},throwOnError:o=>sn(o).type!=="auth_error",enabled:r,refetchInterval:n})},eD=(e={},t={})=>{let{enabled:r=true,refetchInterval:n}=t,{fetchWithAuth:a}=Ve();return useQuery({queryKey:[...fa.list(e),"reconciled"],queryFn:async()=>{let o=new URLSearchParams;e.before&&o.append("before",e.before),e.after&&o.append("after",e.after),e.limit!==void 0&&o.append("limit",String(e.limit)),e.order&&o.append("order",e.order),e.sort_path&&o.append("sort_path",e.sort_path),e.status&&o.append("status",e.status),e.pipeline_status&&o.append("pipeline_status",e.pipeline_status),e.exclude_pipeline_status&&o.append("exclude_pipeline_status",e.exclude_pipeline_status),e.file_id&&o.append("file_id",e.file_id),e.extraction_id&&o.append("extraction_id",e.extraction_id),e.project_id&&o.append("project_id",e.project_id),e.metadata&&Object.keys(e.metadata).length>0&&o.append("metadata",JSON.stringify(e.metadata));let i=`/internal/upload-jobs/reconciled${o.toString()?`?${o.toString()}`:""}`,s=await a(i);if(!s.ok)throw await Et(s,"Failed to fetch upload jobs");return s.json()},throwOnError:o=>sn(o).type!=="auth_error",enabled:r,refetchInterval:n})},tD=()=>{let e=useQueryClient(),{fetchWithAuth:t}=Ve();return useMutation({mutationFn:async r=>{let n=new FormData;Array.from(r.files).forEach(s=>n.append("files",s));let a=new URLSearchParams;a.append("project_id",r.projectId),r.metadata&&Object.keys(r.metadata).length>0&&a.append("metadata",JSON.stringify(r.metadata));let o=`/internal/upload-jobs/batch?${a.toString()}`,i=await t(o,{method:"POST",body:n});if(!i.ok)throw await Et(i,"Failed to upload files");return i.json()},onSuccess:()=>{e.invalidateQueries({queryKey:fa.all});}})},rD=()=>{let e=useQueryClient(),{fetchWithAuth:t}=Ve();return useMutation({mutationFn:async r=>{let n=`/internal/upload-jobs/${encodeURIComponent(r.jobId)}/process`,a=await t(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:r.projectId})});if(!a.ok)throw await Et(a,"Failed to process job");return a.json()},onSuccess:()=>{e.invalidateQueries({queryKey:fa.all});}})},nD=()=>{let e=useQueryClient(),{fetchWithAuth:t}=Ve();return useMutation({mutationFn:async r=>{let n=`/internal/upload-jobs/${encodeURIComponent(r.jobId)}`,a=await t(n,{method:"DELETE"});if(!a.ok)throw await Et(a,"Failed to delete job")},onSuccess:()=>{e.invalidateQueries({queryKey:fa.all});}})},aD=()=>{let e=useQueryClient(),{fetchWithAuth:t}=Ve();return useMutation({mutationFn:async r=>{for(let o=0;o<r.jobIds.length;o+=100){let i=r.jobIds.slice(o,o+100);await Promise.allSettled(i.map(s=>t(`/internal/upload-jobs/${encodeURIComponent(s)}/process`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:r.projectId})}))),o+100<r.jobIds.length&&await new Promise(s=>setTimeout(s,50));}},onSuccess:()=>{e.invalidateQueries({queryKey:fa.all});}})},oD=()=>{let e=useQueryClient(),{fetchWithAuth:t}=Ve();return useMutation({mutationFn:async r=>{let n=new URLSearchParams;n.append("project_id",r.projectId),r.metadata&&Object.keys(r.metadata).length>0&&n.append("metadata",JSON.stringify(r.metadata));let a=await t(`/internal/upload-jobs/process-all?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!a.ok)throw await Et(a,"Failed to process all jobs");return a.json()},onSuccess:()=>{e.invalidateQueries({queryKey:fa.all});}})},iD=()=>{let e=useQueryClient(),{fetchWithAuth:t}=Ve();return useMutation({mutationFn:async r=>{for(let a=0;a<r.jobIds.length;a+=50){let o=r.jobIds.slice(a,a+50);await Promise.allSettled(o.map(i=>t(`/internal/upload-jobs/${encodeURIComponent(i)}`,{method:"DELETE"})));}},onSuccess:()=>{e.invalidateQueries({queryKey:fa.all});}})};var sD=createContext(void 0);function lD({children:e,metadata:t}){let{project:r}=Fr(),n=15,a=15,[o,i]=Rt.useState({before:null,after:null}),[s,l]=Rt.useState({before:null,after:null}),c=useMemo(()=>({limit:n,order:"desc",sort_path:"updated_at",exclude_pipeline_status:"completed",project_id:r.id,metadata:t&&Object.keys(t).length>0?t:void 0,...o}),[o,r.id,t]),u=YO(c,{refetchInterval:4e3}),d=u.data?.data??[],g=u.data?.list_metadata??{before:null,after:null},f=useMemo(()=>({limit:a,order:"desc",sort_path:"updated_at",pipeline_status:"completed",project_id:r.id,metadata:t&&Object.keys(t).length>0?t:void 0,...s}),[s,r.id,t]),h=eD(f,{refetchInterval:4e3}),m=h.data?.data??[],p=h.data?.list_metadata??{before:null,after:null},v=tD(),y=rD(),x=nD(),w=aD(),_=iD(),E=oD(),C=useCallback(async k=>{if(!(!k||k.length===0))try{let D=await v.mutateAsync({files:k,projectId:r.id,metadata:t&&Object.keys(t).length>0?t:void 0});toast.success(`Uploaded ${D.jobs.length} file${D.jobs.length>1?"s":""}`);}catch(D){throw toast.error(D?.message??"Upload failed"),D}},[v,r.id,t]),P=useCallback(async k=>{try{await y.mutateAsync({jobId:k,projectId:r.id}),toast.success("Processing started");}catch(D){throw toast.error(D?.message??"Processing failed"),D}},[y,r.id]),T=useCallback(async k=>{try{await x.mutateAsync({jobId:k}),toast.success("Upload removed");}catch(D){throw toast.error(D?.message??"Delete failed"),D}},[x]),N=useCallback(async()=>{try{let k=await E.mutateAsync({projectId:r.id,metadata:t&&Object.keys(t).length>0?t:void 0});if(k.queued_count===0){toast.error("No jobs eligible for processing");return}let D=t&&Object.keys(t).length>0;toast.success(`${k.queued_count} document${k.queued_count>1?"s":""} queued for processing${D?" with filters":""}`);}catch(k){throw toast.error(k?.message??"Process all failed"),k}},[r.id,t,E]),S=useCallback(async()=>{let k=d.filter(D=>!["queued","processing","completed"].includes(D.pipeline_status||"none"));if(k.length===0){toast.error("No jobs available to delete");return}if(window.confirm(`Delete ${k.length} upload job${k.length>1?"s":""}?`))try{await _.mutateAsync({jobIds:k.map(D=>D.id)}),toast.success(`Deleted ${k.length} upload job${k.length>1?"s":""}`);}catch(D){throw toast.error(D?.message??"Delete all failed"),D}},[d,_]),b=useMemo(()=>({pendingJobs:d,pendingLoading:u.isLoading||u.isRefetching,pendingCursors:g,pendingRefetch:()=>u.refetch(),pendingNextPage:()=>{g.after&&i({before:null,after:g.after});},pendingPrevPage:()=>{g.before&&i({before:g.before,after:null});},completedJobs:m,completedLoading:h.isLoading||h.isRefetching,completedCursors:p,completedRefetch:()=>h.refetch(),completedNextPage:()=>{p.after&&l({before:null,after:p.after});},completedPrevPage:()=>{p.before&&l({before:p.before,after:null});},uploadFiles:C,processJob:P,deleteJob:T,processAll:N,deleteAll:S,isUploading:v.isPending,isProcessing:y.isPending||w.isPending||E.isPending,isDeleting:x.isPending||_.isPending}),[d,u.isLoading,u.isRefetching,u.refetch,g,m,h.isLoading,h.isRefetching,h.refetch,p,C,P,T,N,S,v.isPending,y.isPending,w.isPending,E.isPending,x.isPending,_.isPending]);return jsx(sD.Provider,{value:b,children:e})}function cD(){let e=useContext(sD);if(e===void 0)throw new Error("useUploadJobs must be used within an UploadJobsProvider");return e}function uD({job:e,className:t}){let[r,n]=useState(null),[a,o]=useState(false),[i,s]=useState(true),[l,c]=useState(null),{fetchWithAuth:u}=Ve();return useEffect(()=>{let d=true,g=null,f=async()=>{try{s(!0),c(null);let h=await u(`/internal/upload-jobs/${e.id}/thumbnail`,{headers:{Accept:"image/png,image/jpeg,*/*"}});if(!h.ok)throw new Error(`Failed to load thumbnail: ${h.status}`);let m=await h.blob();if(!d)return;(m.type||h.headers.get("content-type")||"application/octet-stream").startsWith("image/")?(g=URL.createObjectURL(m),n(g),o(!0)):(n(null),o(!1));}catch{if(!d)return;c("Failed to load thumbnail"),n(null),o(false);}finally{d&&s(false);}};return e.id?f():s(false),()=>{d=false,g&&URL.revokeObjectURL(g);}},[e.id]),i?jsx(Ue,{className:Ul("h-9 w-9 rounded-md",t)}):!r||!a||l?jsxs("div",{className:Ul("h-6 w-6 rounded-xs border bg-muted flex items-center justify-center text-muted-foreground",t),children:[jsx(FileIcon,{className:"h-4 w-4","aria-hidden":"true"}),jsx("span",{className:"sr-only",children:e.filename})]}):jsx("div",{className:Ul("h-6 w-6 overflow-hidden rounded-xs border bg-muted/30",t),children:jsx("img",{src:r,alt:`Preview of ${e.filename}`,className:"h-full w-full object-cover",loading:"lazy"})})}function zH({status:e}){let t=e||"none";return t==="completed"?jsx(xn,{variant:"outline",className:"bg-emerald-50 text-emerald-800 border-emerald-200 text-xs",children:"Completed"}):t==="failed"?jsx(xn,{variant:"outline",className:"bg-red-50 text-red-800 border-red-200 text-xs",children:"Retry"}):t==="processing"?jsx(xn,{variant:"outline",className:"bg-blue-50 text-blue-800 border-blue-200 text-xs",children:"Processing"}):t==="queued"?jsx(xn,{variant:"outline",className:"bg-gray-50 text-gray-800 border-gray-200 text-xs",children:"Queued"}):jsx(xn,{variant:"outline",className:"bg-gray-50 text-gray-600 border-gray-200 text-xs",children:"None"})}function UH({metadata:e}){let{project:t}=Fr(),r=useRef(null),{pendingJobs:n,pendingLoading:a,pendingCursors:o,pendingNextPage:i,pendingPrevPage:s,uploadFiles:l,processJob:c,deleteJob:u,processAll:d,isUploading:g,isProcessing:f}=cD(),h=Ga({limit:20,order:"desc",origin_dot_id:t.id,metadata:e&&Object.keys(e).length>0?e:void 0}),m=useRef([]);useEffect(()=>{let y=m.current,x=n,w=x.some(E=>{let C=y.find(P=>P.id===E.id);return C&&C.pipeline_status!=="completed"&&E.pipeline_status==="completed"}),_=y.length>x.length;(w||_)&&h.refetch(),m.current=x;},[n,h]);let p=useCallback(async(y,x)=>{if(!y||y.length===0){x?.();return}await l(y),x?.();},[l]),v=useMemo(()=>n.filter(y=>y.status==="completed"&&y.file_id&&!y.extraction_id&&!["queued","processing","completed"].includes(y.pipeline_status||"none")),[n]);return jsx(XO,{handleFileUpload:p,multiple:true,accept:".pdf, application/pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, image/*, text/plain",className:"flex-1 min-h-0 flex",children:jsxs(kn,{className:"shadow-none gap-3 border-none py-0 flex flex-1 min-h-0",children:[jsx(Rn,{className:"px-0 pb-0 gap-0",children:jsxs("div",{className:"flex items-center justify-between",children:[jsx(On,{children:"Upload files"}),jsxs(K,{size:"sm",variant:"ghost",className:"rounded-full border border-gray-200 text-xs text-muted-foreground",onClick:()=>{d();},disabled:f||v.length===0,children:[`Process all${v.length>0?` (${v.length})`:""}`,f?jsx(Loader2,{className:"h-4 w-4 animate-spin mr-1"}):jsx(Play,{className:"h-4 w-4 mr-1"})]})]})}),jsx(Dn,{className:"flex flex-col flex-1 min-h-0 p-0 border border-gray-200 rounded-md",children:jsx("div",{className:"rounded-md bg-card flex flex-col flex-1 min-h-0 overflow-hidden",children:n.length===0?jsx("div",{className:"flex-1 min-h-0 flex min-w-0",children:jsx(Vh,{className:"bg-white hover:bg-white",onFileUploaded:(y,x)=>p([y])})}):jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:jsxs(oo,{className:"table-fixed w-full relative",children:[jsxs("colgroup",{children:[jsx("col",{style:{width:"50%"}}),jsx("col",{style:{width:"30%"}}),jsx("col",{style:{width:"20%"}})]}),jsx(ji,{className:"sticky top-0 left-0 right-0 z-10 bg-white border-green-200",children:jsxs(Vr,{className:"border-none p-0 h-4",children:[jsx(Nr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"File"})}),jsx(Nr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full",children:"Status"})}),jsx(Nr,{className:"text-xs text-black p-0",children:jsx("div",{className:"border-b px-3 py-2 items-center flex w-full h-full"})})]})}),jsx(io,{className:" border-blue-200",children:n.map(y=>{let x=y.pipeline_status==="queued"||y.pipeline_status==="processing",w=y.pipeline_status==="failed",_=!["queued","processing","completed"].includes(y.pipeline_status||"none");return jsxs(Vr,{className:"h-12.5 group last:border-b-0 first:border-t-0",children:[jsx(Ct,{className:"whitespace-nowrap text-xs",children:jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[jsx(uD,{job:y,className:"shrink-0 h-6 w-6"}),jsx("div",{className:"min-w-0 flex-1",children:jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx("span",{className:"inline-block w-fit max-w-full truncate font-medium align-middle",children:y.filename})}),jsx(ze,{children:y.filename})]})})]})}),jsx(Ct,{className:"whitespace-nowrap text-xs",children:jsx(zH,{status:y.pipeline_status})}),jsx(Ct,{className:"text-right pr-4",children:jsxs("div",{className:"inline-flex items-center gap-2 justify-end",children:[jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(K,{className:`group-hover:opacity-100 transition-opacity duration-300 ${w?"opacity-100":"opacity-0"}`,size:"iconSm",variant:w?"destructive":"ghost",onClick:()=>{c(y.id);},disabled:y.status!=="completed"||x,children:x?jsx(Loader2,{className:"h-4 w-4 animate-spin"}):jsx(Play,{})})}),jsx(ze,{children:"Run the extraction for this file"})]}),_&&jsxs(Me,{children:[jsx(je,{asChild:true,children:jsx(K,{size:"iconSm",variant:"ghost",onClick:()=>{u(y.id);},className:"group-hover:opacity-100 opacity-0 transition-opacity duration-300",children:jsx(Trash2,{className:"h-4 w-4"})})}),jsx(ze,{children:"Delete this queued file"})]})]})})]},y.id)})})]})}),jsx("div",{className:"border-t bg-background",children:jsxs("div",{className:"flex justify-between items-center p-2 gap-2",children:[jsxs("div",{children:[jsx("input",{ref:r,type:"file",accept:".pdf, application/pdf, .doc, .docx, .xls, .xlsx, .ppt, .pptx, image/*, text/plain",multiple:true,className:"hidden",onChange:y=>{let x=y.target.files;x&&x.length>0&&(p(Array.from(x)),y.target.value="");}}),jsx(K,{variant:"ghost",size:"sm",className:"text-xs text-muted-foreground hover:text-foreground",disabled:g,onClick:()=>r.current?.click(),children:g?jsxs(Fragment,{children:[jsx(Loader2,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):jsxs(Fragment,{children:[jsx(UploadCloud,{className:"h-4 w-4 mr-2"}),"Add file"]})})]}),jsxs("div",{className:"flex items-center gap-2",children:[jsxs(K,{variant:"outline",size:"sm",className:"text-xs group px-2",onClick:s,disabled:!o.before||a,children:[jsx(ChevronLeft,{className:"h-4 w-4 opacity-60 -translate-x-0.5 group-hover:-translate-x-3 group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),jsx(ChevronLeft,{className:"h-4 w-4 -ml-6 translate-x-2.5 opacity-0 group-hover:-translate-x-0 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),"Prev"]}),jsxs(K,{variant:"outline",size:"sm",className:"text-xs group px-2",onClick:i,disabled:!o.after||a,children:["Next",jsx(ChevronRight,{className:"h-4 w-4 opacity-60 group-hover:translate-x-3 group-hover:opacity-0 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"}),jsx(ChevronRight,{className:"h-4 w-4 -ml-6 -translate-x-2.5 opacity-0 group-hover:translate-x-0.5 group-hover:opacity-100 transition duration-300 ease-[cubic-bezier(0.4,0.36,0,1)]"})]})]})]})})]})})})]})})}function qH({metadata:e}={}){return jsx(lD,{metadata:e,children:jsx(UH,{metadata:e})})}function JH({className:e,variant:t="banner",renderError:r,children:n}){let{authError:a,isOnline:o,isAuthenticating:i,retryAuth:s}=Ve();if(a&&r)return jsx(Fragment,{children:r(a,s,o)});if(!a)return jsx(Fragment,{children:n});let l=()=>{switch(a.code){case "NETWORK_ERROR":return {icon:jsx(WifiOff,{className:"h-5 w-5"}),title:"Connection Issue",message:o?"Having trouble connecting. Please try again.":"You appear to be offline. Check your connection.",buttonText:o?"Retry Connection":"Waiting for connection..."};case "AUTH_EXPIRED":return {icon:jsx(KeyRound,{className:"h-5 w-5"}),title:"Session Expired",message:"Your session has expired. Please refresh to continue.",buttonText:"Refresh Session"};case "TOKEN_FETCH_FAILED":return {icon:jsx(AlertCircle,{className:"h-5 w-5"}),title:"Authentication Failed",message:"Unable to authenticate. Please try again.",buttonText:"Retry Authentication"};default:return {icon:jsx(AlertCircle,{className:"h-5 w-5"}),title:"Something Went Wrong",message:a.message||"An unexpected error occurred.",buttonText:"Try Again"}}},{icon:c,title:u,message:d,buttonText:g}=l();return t==="banner"?jsxs(Fragment,{children:[jsx("div",{className:R("bg-amber-50 border-l-4 border-amber-400 p-4 mb-4",e),role:"alert",children:jsxs("div",{className:"flex items-start",children:[jsx("div",{className:"flex-shrink-0 text-amber-500",children:c}),jsxs("div",{className:"ml-3 flex-1",children:[jsx("p",{className:"text-sm font-medium text-amber-800",children:u}),jsx("p",{className:"text-sm text-amber-700 mt-1",children:d}),a.retryCount>0&&jsxs("p",{className:"text-xs text-amber-600 mt-1",children:["Attempted ",a.retryCount," time",a.retryCount>1?"s":""]})]}),jsx("div",{className:"ml-4",children:jsxs(K,{onClick:s,disabled:i||!o&&a.code==="NETWORK_ERROR",size:"sm",variant:"outline",className:"border-amber-400 text-amber-700 hover:bg-amber-100",children:[jsx(RefreshCw,{className:R("h-4 w-4 mr-2",i&&"animate-spin")}),i?"Retrying...":g]})})]})}),n]}):t==="inline"?jsxs("div",{className:R("flex flex-col items-center justify-center p-6 text-center",e),children:[jsx("div",{className:"text-amber-500 mb-3",children:c}),jsx("h3",{className:"text-lg font-medium text-gray-900 mb-1",children:u}),jsx("p",{className:"text-sm text-gray-600 mb-4",children:d}),jsxs(K,{onClick:s,disabled:i||!o&&a.code==="NETWORK_ERROR",size:"sm",children:[jsx(RefreshCw,{className:R("h-4 w-4 mr-2",i&&"animate-spin")}),i?"Retrying...":g]}),a.retryCount>0&&jsxs("p",{className:"text-xs text-gray-500 mt-2",children:["Attempted ",a.retryCount," time",a.retryCount>1?"s":""]})]}):jsx("div",{className:R("fixed inset-0 bg-white/80 backdrop-blur-sm flex items-center justify-center z-50",e),children:jsxs("div",{className:"bg-white rounded-lg shadow-lg p-6 max-w-md w-full mx-4 text-center border border-gray-200",children:[jsx("div",{className:"text-amber-500 mb-4 flex justify-center",children:c}),jsx("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:u}),jsx("p",{className:"text-gray-600 mb-6",children:d}),jsxs(K,{onClick:s,disabled:i||!o&&a.code==="NETWORK_ERROR",className:"w-full",children:[jsx(RefreshCw,{className:R("h-4 w-4 mr-2",i&&"animate-spin")}),i?"Retrying...":g]}),a.retryCount>0&&jsxs("p",{className:"text-xs text-gray-500 mt-3",children:["Attempted ",a.retryCount," time",a.retryCount>1?"s":""]})]})})}
118
+ export{JH as AuthErrorDisplay,tb as DataComponent,sw as ExtractionComponent,yH as ExtractionReviewer,PH as ExtractionsList,aw as FileComponent,WF as RetabProvider,qH as UploadJobsList,R as cn,Ve as useAuth,c0 as useExtraction,Ga as useExtractionList,ZS as useExtractions,Ka as useJsonSchema,us as useOCR,Za as useOptionalExtractions,Fr as useProject};//# sourceMappingURL=index.mjs.map
112
119
  //# sourceMappingURL=index.mjs.map