datafold 0.1.55

A personal database for data sovereignty with AI-powered ingestion
Documentation
(function(se,v){typeof exports=="object"&&typeof module<"u"?v(exports,require("react"),require("react-redux")):typeof define=="function"&&define.amd?define(["exports","react","react-redux"],v):(se=typeof globalThis<"u"?globalThis:se||self,v(se.DataFoldNodeUI={},se.React,se.ReactRedux))})(this,function(se,v,ft){"use strict";var xu=Object.defineProperty;var bu=(se,v,ft)=>v in se?xu(se,v,{enumerable:!0,configurable:!0,writable:!0,value:ft}):se[v]=ft;var ut=(se,v,ft)=>bu(se,typeof v!="symbol"?v+"":v,ft);function pi(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const q=pi(v);var as={exports:{}},er={};/**
 * @license React
 * react-jsx-runtime.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var un;function gi(){if(un)return er;un=1;var e=v,t=Symbol.for("react.element"),r=Symbol.for("react.fragment"),n=Object.prototype.hasOwnProperty,a=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function d(c,f,m){var h,y={},x=null,N=null;m!==void 0&&(x=""+m),f.key!==void 0&&(x=""+f.key),f.ref!==void 0&&(N=f.ref);for(h in f)n.call(f,h)&&!l.hasOwnProperty(h)&&(y[h]=f[h]);if(c&&c.defaultProps)for(h in f=c.defaultProps,f)y[h]===void 0&&(y[h]=f[h]);return{$$typeof:t,type:c,key:x,ref:N,props:y,_owner:a.current}}return er.Fragment=r,er.jsx=d,er.jsxs=d,er}var tr={};/**
 * @license React
 * react-jsx-runtime.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */var fn;function yi(){return fn||(fn=1,process.env.NODE_ENV!=="production"&&function(){var e=v,t=Symbol.for("react.element"),r=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),a=Symbol.for("react.strict_mode"),l=Symbol.for("react.profiler"),d=Symbol.for("react.provider"),c=Symbol.for("react.context"),f=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),h=Symbol.for("react.suspense_list"),y=Symbol.for("react.memo"),x=Symbol.for("react.lazy"),N=Symbol.for("react.offscreen"),_=Symbol.iterator,S="@@iterator";function p(b){if(b===null||typeof b!="object")return null;var P=_&&b[_]||b[S];return typeof P=="function"?P:null}var w=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function E(b){{for(var P=arguments.length,U=new Array(P>1?P-1:0),G=1;G<P;G++)U[G-1]=arguments[G];C("error",b,U)}}function C(b,P,U){{var G=w.ReactDebugCurrentFrame,re=G.getStackAddendum();re!==""&&(P+="%s",U=U.concat([re]));var ie=U.map(function(X){return String(X)});ie.unshift("Warning: "+P),Function.prototype.apply.call(console[b],console,ie)}}var A=!1,T=!1,M=!1,I=!1,O=!1,R;R=Symbol.for("react.module.reference");function $(b){return!!(typeof b=="string"||typeof b=="function"||b===n||b===l||O||b===a||b===m||b===h||I||b===N||A||T||M||typeof b=="object"&&b!==null&&(b.$$typeof===x||b.$$typeof===y||b.$$typeof===d||b.$$typeof===c||b.$$typeof===f||b.$$typeof===R||b.getModuleId!==void 0))}function F(b,P,U){var G=b.displayName;if(G)return G;var re=P.displayName||P.name||"";return re!==""?U+"("+re+")":U}function H(b){return b.displayName||"Context"}function V(b){if(b==null)return null;if(typeof b.tag=="number"&&E("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof b=="function")return b.displayName||b.name||null;if(typeof b=="string")return b;switch(b){case n:return"Fragment";case r:return"Portal";case l:return"Profiler";case a:return"StrictMode";case m:return"Suspense";case h:return"SuspenseList"}if(typeof b=="object")switch(b.$$typeof){case c:var P=b;return H(P)+".Consumer";case d:var U=b;return H(U._context)+".Provider";case f:return F(b,b.render,"ForwardRef");case y:var G=b.displayName||null;return G!==null?G:V(b.type)||"Memo";case x:{var re=b,ie=re._payload,X=re._init;try{return V(X(ie))}catch{return null}}}return null}var z=Object.assign,L=0,Q,Y,ge,Ue,ze,ae,ce;function Et(){}Et.__reactDisabledLog=!0;function St(){{if(L===0){Q=console.log,Y=console.info,ge=console.warn,Ue=console.error,ze=console.group,ae=console.groupCollapsed,ce=console.groupEnd;var b={configurable:!0,enumerable:!0,value:Et,writable:!0};Object.defineProperties(console,{info:b,log:b,warn:b,error:b,group:b,groupCollapsed:b,groupEnd:b})}L++}}function Ot(){{if(L--,L===0){var b={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:z({},b,{value:Q}),info:z({},b,{value:Y}),warn:z({},b,{value:ge}),error:z({},b,{value:Ue}),group:z({},b,{value:ze}),groupCollapsed:z({},b,{value:ae}),groupEnd:z({},b,{value:ce})})}L<0&&E("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var it=w.ReactCurrentDispatcher,ot;function Ae(b,P,U){{if(ot===void 0)try{throw Error()}catch(re){var G=re.stack.trim().match(/\n( *(at )?)/);ot=G&&G[1]||""}return`
`+ot+b}}var Xe=!1,ct;{var yr=typeof WeakMap=="function"?WeakMap:Map;ct=new yr}function Nt(b,P){if(!b||Xe)return"";{var U=ct.get(b);if(U!==void 0)return U}var G;Xe=!0;var re=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var ie;ie=it.current,it.current=null,St();try{if(P){var X=function(){throw Error()};if(Object.defineProperty(X.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(X,[])}catch(Te){G=Te}Reflect.construct(b,[],X)}else{try{X.call()}catch(Te){G=Te}b.call(X.prototype)}}else{try{throw Error()}catch(Te){G=Te}b()}}catch(Te){if(Te&&G&&typeof Te.stack=="string"){for(var J=Te.stack.split(`
`),_e=G.stack.split(`
`),me=J.length-1,pe=_e.length-1;me>=1&&pe>=0&&J[me]!==_e[pe];)pe--;for(;me>=1&&pe>=0;me--,pe--)if(J[me]!==_e[pe]){if(me!==1||pe!==1)do if(me--,pe--,pe<0||J[me]!==_e[pe]){var Ke=`
`+J[me].replace(" at new "," at ");return b.displayName&&Ke.includes("<anonymous>")&&(Ke=Ke.replace("<anonymous>",b.displayName)),typeof b=="function"&&ct.set(b,Ke),Ke}while(me>=1&&pe>=0);break}}}finally{Xe=!1,it.current=ie,Ot(),Error.prepareStackTrace=re}var Xt=b?b.displayName||b.name:"",Rt=Xt?Ae(Xt):"";return typeof b=="function"&&ct.set(b,Rt),Rt}function et(b,P,U){return Nt(b,!1)}function lt(b){var P=b.prototype;return!!(P&&P.isReactComponent)}function jt(b,P,U){if(b==null)return"";if(typeof b=="function")return Nt(b,lt(b));if(typeof b=="string")return Ae(b);switch(b){case m:return Ae("Suspense");case h:return Ae("SuspenseList")}if(typeof b=="object")switch(b.$$typeof){case f:return et(b.render);case y:return jt(b.type,P,U);case x:{var G=b,re=G._payload,ie=G._init;try{return jt(ie(re),P,U)}catch{}}}return""}var dt=Object.prototype.hasOwnProperty,B={},Z=w.ReactDebugCurrentFrame;function ve(b){if(b){var P=b._owner,U=jt(b.type,b._source,P?P.type:null);Z.setExtraStackFrame(U)}else Z.setExtraStackFrame(null)}function tt(b,P,U,G,re){{var ie=Function.call.bind(dt);for(var X in b)if(ie(b,X)){var J=void 0;try{if(typeof b[X]!="function"){var _e=Error((G||"React class")+": "+U+" type `"+X+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof b[X]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw _e.name="Invariant Violation",_e}J=b[X](P,X,G,U,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(me){J=me}J&&!(J instanceof Error)&&(ve(re),E("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",G||"React class",U,X,typeof J),ve(null)),J instanceof Error&&!(J.message in B)&&(B[J.message]=!0,ve(re),E("Failed %s type: %s",U,J.message),ve(null))}}}var Jt=Array.isArray;function Ce(b){return Jt(b)}function xr(b){{var P=typeof Symbol=="function"&&Symbol.toStringTag,U=P&&b[Symbol.toStringTag]||b.constructor.name||"Object";return U}}function on(b){try{return Ge(b),!1}catch{return!0}}function Ge(b){return""+b}function ns(b){if(on(b))return E("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",xr(b)),Ge(b)}var u=w.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0},o,g;function j(b){if(dt.call(b,"ref")){var P=Object.getOwnPropertyDescriptor(b,"ref").get;if(P&&P.isReactWarning)return!1}return b.ref!==void 0}function k(b){if(dt.call(b,"key")){var P=Object.getOwnPropertyDescriptor(b,"key").get;if(P&&P.isReactWarning)return!1}return b.key!==void 0}function D(b,P){typeof b.ref=="string"&&u.current}function W(b,P){{var U=function(){o||(o=!0,E("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",P))};U.isReactWarning=!0,Object.defineProperty(b,"key",{get:U,configurable:!0})}}function le(b,P){{var U=function(){g||(g=!0,E("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",P))};U.isReactWarning=!0,Object.defineProperty(b,"ref",{get:U,configurable:!0})}}var oe=function(b,P,U,G,re,ie,X){var J={$$typeof:t,type:b,key:P,ref:U,props:X,_owner:ie};return J._store={},Object.defineProperty(J._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(J,"_self",{configurable:!1,enumerable:!1,writable:!1,value:G}),Object.defineProperty(J,"_source",{configurable:!1,enumerable:!1,writable:!1,value:re}),Object.freeze&&(Object.freeze(J.props),Object.freeze(J)),J};function de(b,P,U,G,re){{var ie,X={},J=null,_e=null;U!==void 0&&(ns(U),J=""+U),k(P)&&(ns(P.key),J=""+P.key),j(P)&&(_e=P.ref,D(P,re));for(ie in P)dt.call(P,ie)&&!i.hasOwnProperty(ie)&&(X[ie]=P[ie]);if(b&&b.defaultProps){var me=b.defaultProps;for(ie in me)X[ie]===void 0&&(X[ie]=me[ie])}if(J||_e){var pe=typeof b=="function"?b.displayName||b.name||"Unknown":b;J&&W(X,pe),_e&&le(X,pe)}return oe(b,J,_e,re,G,u.current,X)}}var te=w.ReactCurrentOwner,ci=w.ReactDebugCurrentFrame;function Zt(b){if(b){var P=b._owner,U=jt(b.type,b._source,P?P.type:null);ci.setExtraStackFrame(U)}else ci.setExtraStackFrame(null)}var cn;cn=!1;function ln(b){return typeof b=="object"&&b!==null&&b.$$typeof===t}function li(){{if(te.current){var b=V(te.current.type);if(b)return`

Check the render method of \``+b+"`."}return""}}function cu(b){return""}var di={};function lu(b){{var P=li();if(!P){var U=typeof b=="string"?b:b.displayName||b.name;U&&(P=`

Check the top-level render call using <`+U+">.")}return P}}function ui(b,P){{if(!b._store||b._store.validated||b.key!=null)return;b._store.validated=!0;var U=lu(P);if(di[U])return;di[U]=!0;var G="";b&&b._owner&&b._owner!==te.current&&(G=" It was passed a child from "+V(b._owner.type)+"."),Zt(b),E('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',U,G),Zt(null)}}function fi(b,P){{if(typeof b!="object")return;if(Ce(b))for(var U=0;U<b.length;U++){var G=b[U];ln(G)&&ui(G,P)}else if(ln(b))b._store&&(b._store.validated=!0);else if(b){var re=p(b);if(typeof re=="function"&&re!==b.entries)for(var ie=re.call(b),X;!(X=ie.next()).done;)ln(X.value)&&ui(X.value,P)}}}function du(b){{var P=b.type;if(P==null||typeof P=="string")return;var U;if(typeof P=="function")U=P.propTypes;else if(typeof P=="object"&&(P.$$typeof===f||P.$$typeof===y))U=P.propTypes;else return;if(U){var G=V(P);tt(U,b.props,"prop",G,b)}else if(P.PropTypes!==void 0&&!cn){cn=!0;var re=V(P);E("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",re||"Unknown")}typeof P.getDefaultProps=="function"&&!P.getDefaultProps.isReactClassApproved&&E("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function uu(b){{for(var P=Object.keys(b.props),U=0;U<P.length;U++){var G=P[U];if(G!=="children"&&G!=="key"){Zt(b),E("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",G),Zt(null);break}}b.ref!==null&&(Zt(b),E("Invalid attribute `ref` supplied to `React.Fragment`."),Zt(null))}}var hi={};function mi(b,P,U,G,re,ie){{var X=$(b);if(!X){var J="";(b===void 0||typeof b=="object"&&b!==null&&Object.keys(b).length===0)&&(J+=" You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");var _e=cu();_e?J+=_e:J+=li();var me;b===null?me="null":Ce(b)?me="array":b!==void 0&&b.$$typeof===t?(me="<"+(V(b.type)||"Unknown")+" />",J=" Did you accidentally export a JSX literal instead of a component?"):me=typeof b,E("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",me,J)}var pe=de(b,P,U,re,ie);if(pe==null)return pe;if(X){var Ke=P.children;if(Ke!==void 0)if(G)if(Ce(Ke)){for(var Xt=0;Xt<Ke.length;Xt++)fi(Ke[Xt],b);Object.freeze&&Object.freeze(Ke)}else E("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else fi(Ke,b)}if(dt.call(P,"key")){var Rt=V(b),Te=Object.keys(P).filter(function(yu){return yu!=="key"}),dn=Te.length>0?"{key: someKey, "+Te.join(": ..., ")+": ...}":"{key: someKey}";if(!hi[Rt+dn]){var gu=Te.length>0?"{"+Te.join(": ..., ")+": ...}":"{}";E(`A props object containing a "key" prop is being spread into JSX:
  let props = %s;
  <%s {...props} />
React keys must be passed directly to JSX without using spread:
  let props = %s;
  <%s key={someKey} {...props} />`,dn,Rt,gu,Rt),hi[Rt+dn]=!0}}return b===n?uu(pe):du(pe),pe}}function fu(b,P,U){return mi(b,P,U,!0)}function hu(b,P,U){return mi(b,P,U,!1)}var mu=hu,pu=fu;tr.Fragment=n,tr.jsx=mu,tr.jsxs=pu}()),tr}process.env.NODE_ENV==="production"?as.exports=gi():as.exports=yi();var s=as.exports;function ye(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var xi=typeof Symbol=="function"&&Symbol.observable||"@@observable",hn=xi,is=()=>Math.random().toString(36).substring(7).split("").join("."),bi={INIT:`@@redux/INIT${is()}`,REPLACE:`@@redux/REPLACE${is()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${is()}`},_t=bi;function rr(e){if(typeof e!="object"||e===null)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function vi(e){if(e===void 0)return"undefined";if(e===null)return"null";const t=typeof e;switch(t){case"boolean":case"string":case"number":case"symbol":case"function":return t}if(Array.isArray(e))return"array";if(Si(e))return"date";if(Ei(e))return"error";const r=wi(e);switch(r){case"Symbol":case"Promise":case"WeakMap":case"WeakSet":case"Map":case"Set":return r}return Object.prototype.toString.call(e).slice(8,-1).toLowerCase().replace(/\s/g,"")}function wi(e){return typeof e.constructor=="function"?e.constructor.name:null}function Ei(e){return e instanceof Error||typeof e.message=="string"&&e.constructor&&typeof e.constructor.stackTraceLimit=="number"}function Si(e){return e instanceof Date?!0:typeof e.toDateString=="function"&&typeof e.getDate=="function"&&typeof e.setDate=="function"}function ht(e){let t=typeof e;return process.env.NODE_ENV!=="production"&&(t=vi(e)),t}function mn(e,t,r){if(typeof e!="function")throw new Error(process.env.NODE_ENV==="production"?ye(2):`Expected the root reducer to be a function. Instead, received: '${ht(e)}'`);if(typeof t=="function"&&typeof r=="function"||typeof r=="function"&&typeof arguments[3]=="function")throw new Error(process.env.NODE_ENV==="production"?ye(0):"It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.");if(typeof t=="function"&&typeof r>"u"&&(r=t,t=void 0),typeof r<"u"){if(typeof r!="function")throw new Error(process.env.NODE_ENV==="production"?ye(1):`Expected the enhancer to be a function. Instead, received: '${ht(r)}'`);return r(mn)(e,t)}let n=e,a=t,l=new Map,d=l,c=0,f=!1;function m(){d===l&&(d=new Map,l.forEach((p,w)=>{d.set(w,p)}))}function h(){if(f)throw new Error(process.env.NODE_ENV==="production"?ye(3):"You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");return a}function y(p){if(typeof p!="function")throw new Error(process.env.NODE_ENV==="production"?ye(4):`Expected the listener to be a function. Instead, received: '${ht(p)}'`);if(f)throw new Error(process.env.NODE_ENV==="production"?ye(5):"You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.");let w=!0;m();const E=c++;return d.set(E,p),function(){if(w){if(f)throw new Error(process.env.NODE_ENV==="production"?ye(6):"You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.");w=!1,m(),d.delete(E),l=null}}}function x(p){if(!rr(p))throw new Error(process.env.NODE_ENV==="production"?ye(7):`Actions must be plain objects. Instead, the actual type was: '${ht(p)}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`);if(typeof p.type>"u")throw new Error(process.env.NODE_ENV==="production"?ye(8):'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');if(typeof p.type!="string")throw new Error(process.env.NODE_ENV==="production"?ye(17):`Action "type" property must be a string. Instead, the actual type was: '${ht(p.type)}'. Value was: '${p.type}' (stringified)`);if(f)throw new Error(process.env.NODE_ENV==="production"?ye(9):"Reducers may not dispatch actions.");try{f=!0,a=n(a,p)}finally{f=!1}return(l=d).forEach(E=>{E()}),p}function N(p){if(typeof p!="function")throw new Error(process.env.NODE_ENV==="production"?ye(10):`Expected the nextReducer to be a function. Instead, received: '${ht(p)}`);n=p,x({type:_t.REPLACE})}function _(){const p=y;return{subscribe(w){if(typeof w!="object"||w===null)throw new Error(process.env.NODE_ENV==="production"?ye(11):`Expected the observer to be an object. Instead, received: '${ht(w)}'`);function E(){const A=w;A.next&&A.next(h())}return E(),{unsubscribe:p(E)}},[hn](){return this}}}return x({type:_t.INIT}),{dispatch:x,subscribe:y,getState:h,replaceReducer:N,[hn]:_}}function pn(e){typeof console<"u"&&typeof console.error=="function"&&console.error(e);try{throw new Error(e)}catch{}}function Ni(e,t,r,n){const a=Object.keys(t),l=r&&r.type===_t.INIT?"preloadedState argument passed to createStore":"previous state received by the reducer";if(a.length===0)return"Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";if(!rr(e))return`The ${l} has unexpected type of "${ht(e)}". Expected argument to be an object with the following keys: "${a.join('", "')}"`;const d=Object.keys(e).filter(c=>!t.hasOwnProperty(c)&&!n[c]);if(d.forEach(c=>{n[c]=!0}),!(r&&r.type===_t.REPLACE)&&d.length>0)return`Unexpected ${d.length>1?"keys":"key"} "${d.join('", "')}" found in ${l}. Expected to find one of the known reducer keys instead: "${a.join('", "')}". Unexpected keys will be ignored.`}function ji(e){Object.keys(e).forEach(t=>{const r=e[t];if(typeof r(void 0,{type:_t.INIT})>"u")throw new Error(process.env.NODE_ENV==="production"?ye(12):`The slice reducer for key "${t}" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);if(typeof r(void 0,{type:_t.PROBE_UNKNOWN_ACTION()})>"u")throw new Error(process.env.NODE_ENV==="production"?ye(13):`The slice reducer for key "${t}" returned undefined when probed with a random type. Don't try to handle '${_t.INIT}' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`)})}function _i(e){const t=Object.keys(e),r={};for(let d=0;d<t.length;d++){const c=t[d];process.env.NODE_ENV!=="production"&&typeof e[c]>"u"&&pn(`No reducer provided for key "${c}"`),typeof e[c]=="function"&&(r[c]=e[c])}const n=Object.keys(r);let a;process.env.NODE_ENV!=="production"&&(a={});let l;try{ji(r)}catch(d){l=d}return function(c={},f){if(l)throw l;if(process.env.NODE_ENV!=="production"){const y=Ni(c,r,f,a);y&&pn(y)}let m=!1;const h={};for(let y=0;y<n.length;y++){const x=n[y],N=r[x],_=c[x],S=N(_,f);if(typeof S>"u"){const p=f&&f.type;throw new Error(process.env.NODE_ENV==="production"?ye(14):`When called with an action of type ${p?`"${String(p)}"`:"(unknown type)"}, the slice reducer for key "${x}" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`)}h[x]=S,m=m||S!==_}return m=m||n.length!==Object.keys(c).length,m?h:c}}function vr(...e){return e.length===0?t=>t:e.length===1?e[0]:e.reduce((t,r)=>(...n)=>t(r(...n)))}function Ai(...e){return t=>(r,n)=>{const a=t(r,n);let l=()=>{throw new Error(process.env.NODE_ENV==="production"?ye(15):"Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.")};const d={getState:a.getState,dispatch:(f,...m)=>l(f,...m)},c=e.map(f=>f(d));return l=vr(...c)(a.dispatch),{...a,dispatch:l}}}function gn(e){return rr(e)&&"type"in e&&typeof e.type=="string"}var yn=Symbol.for("immer-nothing"),xn=Symbol.for("immer-draftable"),Ne=Symbol.for("immer-state"),Ci=process.env.NODE_ENV!=="production"?[function(e){return`The plugin for '${e}' has not been loaded into Immer. To enable the plugin, import and call \`enable${e}()\` when initializing your application.`},function(e){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${e}'`},"This object has been frozen and should not be mutated",function(e){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+e},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(e){return`'current' expects a draft, got: ${e}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(e){return`'original' expects a draft, got: ${e}`}]:[];function ke(e,...t){if(process.env.NODE_ENV!=="production"){const r=Ci[e],n=At(r)?r.apply(null,t):r;throw new Error(`[Immer] ${n}`)}throw new Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var Ie=Object,Dt=Ie.getPrototypeOf,wr="constructor",Er="prototype",os="configurable",Sr="enumerable",Nr="writable",sr="value",rt=e=>!!e&&!!e[Ne];function Ve(e){var t;return e?vn(e)||_r(e)||!!e[xn]||!!((t=e[wr])!=null&&t[xn])||Ar(e)||Cr(e):!1}var Ti=Ie[Er][wr].toString(),bn=new WeakMap;function vn(e){if(!e||!ls(e))return!1;const t=Dt(e);if(t===null||t===Ie[Er])return!0;const r=Ie.hasOwnProperty.call(t,wr)&&t[wr];if(r===Object)return!0;if(!At(r))return!1;let n=bn.get(r);return n===void 0&&(n=Function.toString.call(r),bn.set(r,n)),n===Ti}function nr(e,t,r=!0){ar(e)===0?(r?Reflect.ownKeys(e):Ie.keys(e)).forEach(a=>{t(a,e[a],e)}):e.forEach((n,a)=>t(a,n,e))}function ar(e){const t=e[Ne];return t?t.type_:_r(e)?1:Ar(e)?2:Cr(e)?3:0}var wn=(e,t,r=ar(e))=>r===2?e.has(t):Ie[Er].hasOwnProperty.call(e,t),cs=(e,t,r=ar(e))=>r===2?e.get(t):e[t],jr=(e,t,r,n=ar(e))=>{n===2?e.set(t,r):n===3?e.add(r):e[t]=r};function ki(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}var _r=Array.isArray,Ar=e=>e instanceof Map,Cr=e=>e instanceof Set,ls=e=>typeof e=="object",At=e=>typeof e=="function",ds=e=>typeof e=="boolean",st=e=>e.copy_||e.base_,us=e=>e.modified_?e.copy_:e.base_;function fs(e,t){if(Ar(e))return new Map(e);if(Cr(e))return new Set(e);if(_r(e))return Array[Er].slice.call(e);const r=vn(e);if(t===!0||t==="class_only"&&!r){const n=Ie.getOwnPropertyDescriptors(e);delete n[Ne];let a=Reflect.ownKeys(n);for(let l=0;l<a.length;l++){const d=a[l],c=n[d];c[Nr]===!1&&(c[Nr]=!0,c[os]=!0),(c.get||c.set)&&(n[d]={[os]:!0,[Nr]:!0,[Sr]:c[Sr],[sr]:e[d]})}return Ie.create(Dt(e),n)}else{const n=Dt(e);if(n!==null&&r)return{...e};const a=Ie.create(n);return Ie.assign(a,e)}}function hs(e,t=!1){return kr(e)||rt(e)||!Ve(e)||(ar(e)>1&&Ie.defineProperties(e,{set:Tr,add:Tr,clear:Tr,delete:Tr}),Ie.freeze(e),t&&nr(e,(r,n)=>{hs(n,!0)},!1)),e}function Ii(){ke(2)}var Tr={[sr]:Ii};function kr(e){return e===null||!ls(e)?!0:Ie.isFrozen(e)}var Ir="MapSet",ms="Patches",En={};function Ft(e){const t=En[e];return t||ke(0,e),t}var Oi=e=>!!En[e],ir,Sn=()=>ir,Ri=(e,t)=>({drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:Oi(Ir)?Ft(Ir):void 0});function Nn(e,t){t&&(e.patchPlugin_=Ft(ms),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function ps(e){gs(e),e.drafts_.forEach(Di),e.drafts_=null}function gs(e){e===ir&&(ir=e.parent_)}var jn=e=>ir=Ri(ir,e);function Di(e){const t=e[Ne];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function _n(e,t){t.unfinalizedDrafts_=t.drafts_.length;const r=t.drafts_[0];if(e!==void 0&&e!==r){r[Ne].modified_&&(ps(t),ke(4)),Ve(e)&&(e=An(t,e));const{patchPlugin_:a}=t;a&&a.generateReplacementPatches_(r[Ne].base_,e,t)}else e=An(t,r);return Fi(t,e,!0),ps(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==yn?e:void 0}function An(e,t){if(kr(t))return t;const r=t[Ne];if(!r)return ys(t,e.handledSet_,e);if(!Or(r,e))return t;if(!r.modified_)return r.base_;if(!r.finalized_){const{callbacks_:n}=r;if(n)for(;n.length>0;)n.pop()(e);kn(r,e)}return r.copy_}function Fi(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&hs(t,r)}function Cn(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var Or=(e,t)=>e.scope_===t,Pi=[];function Tn(e,t,r,n){const a=st(e),l=e.type_;if(n!==void 0&&cs(a,n,l)===t){jr(a,n,r,l);return}if(!e.draftLocations_){const c=e.draftLocations_=new Map;nr(a,(f,m)=>{if(rt(m)){const h=c.get(m)||[];h.push(f),c.set(m,h)}})}const d=e.draftLocations_.get(t)??Pi;for(const c of d)jr(a,c,r,l)}function Mi(e,t,r){e.callbacks_.push(function(a){var c;const l=t;if(!l||!Or(l,a))return;(c=a.mapSetPlugin_)==null||c.fixSetContents(l);const d=us(l);Tn(e,l.draft_??l,d,r),kn(l,a)})}function kn(e,t){var n;if(e.modified_&&!e.finalized_&&(e.type_===3||(((n=e.assigned_)==null?void 0:n.size)??0)>0)){const{patchPlugin_:a}=t;if(a){const l=a.getPath(e);l&&a.generatePatches_(e,l,t)}Cn(e)}}function Bi(e,t,r){const{scope_:n}=e;if(rt(r)){const a=r[Ne];Or(a,n)&&a.callbacks_.push(function(){Rr(e);const d=us(a);Tn(e,r,d,t)})}else Ve(r)&&e.callbacks_.push(function(){const l=st(e);cs(l,t,e.type_)===r&&n.drafts_.length>1&&(e.assigned_.get(t)??!1)===!0&&e.copy_&&ys(cs(e.copy_,t,e.type_),n.handledSet_,n)})}function ys(e,t,r){return!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1||rt(e)||t.has(e)||!Ve(e)||kr(e)||(t.add(e),nr(e,(n,a)=>{if(rt(a)){const l=a[Ne];if(Or(l,r)){const d=us(l);jr(e,n,d,e.type_),Cn(l)}}else Ve(a)&&ys(a,t,r)})),e}function Li(e,t){const r=_r(e),n={type_:r?1:0,scope_:t?t.scope_:Sn(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0};let a=n,l=xs;r&&(a=[n],l=or);const{revoke:d,proxy:c}=Proxy.revocable(a,l);return n.draft_=c,n.revoke_=d,[c,n]}var xs={get(e,t){if(t===Ne)return e;const r=st(e);if(!wn(r,t,e.type_))return $i(e,r,t);const n=r[t];if(e.finalized_||!Ve(n))return n;if(n===bs(e.base_,t)){Rr(e);const a=e.type_===1?+t:t,l=ws(e.scope_,n,e,a);return e.copy_[a]=l}return n},has(e,t){return t in st(e)},ownKeys(e){return Reflect.ownKeys(st(e))},set(e,t,r){const n=In(st(e),t);if(n!=null&&n.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){const a=bs(st(e),t),l=a==null?void 0:a[Ne];if(l&&l.base_===r)return e.copy_[t]=r,e.assigned_.set(t,!1),!0;if(ki(r,a)&&(r!==void 0||wn(e.base_,t,e.type_)))return!0;Rr(e),vs(e)}return e.copy_[t]===r&&(r!==void 0||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t])||(e.copy_[t]=r,e.assigned_.set(t,!0),Bi(e,t,r)),!0},deleteProperty(e,t){return Rr(e),bs(e.base_,t)!==void 0||t in e.base_?(e.assigned_.set(t,!1),vs(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){const r=st(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n&&{[Nr]:!0,[os]:e.type_!==1||t!=="length",[Sr]:n[Sr],[sr]:r[t]}},defineProperty(){ke(11)},getPrototypeOf(e){return Dt(e.base_)},setPrototypeOf(){ke(12)}},or={};nr(xs,(e,t)=>{or[e]=function(){const r=arguments;return r[0]=r[0][0],t.apply(this,r)}}),or.deleteProperty=function(e,t){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(t))&&ke(13),or.set.call(this,e,t,void 0)},or.set=function(e,t,r){return process.env.NODE_ENV!=="production"&&t!=="length"&&isNaN(parseInt(t))&&ke(14),xs.set.call(this,e[0],t,r,e[0])};function bs(e,t){const r=e[Ne];return(r?st(r):e)[t]}function $i(e,t,r){var a;const n=In(t,r);return n?sr in n?n[sr]:(a=n.get)==null?void 0:a.call(e.draft_):void 0}function In(e,t){if(!(t in e))return;let r=Dt(e);for(;r;){const n=Object.getOwnPropertyDescriptor(r,t);if(n)return n;r=Dt(r)}}function vs(e){e.modified_||(e.modified_=!0,e.parent_&&vs(e.parent_))}function Rr(e){e.copy_||(e.assigned_=new Map,e.copy_=fs(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var Ui=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(t,r,n)=>{if(At(t)&&!At(r)){const l=r;r=t;const d=this;return function(f=l,...m){return d.produce(f,h=>r.call(this,h,...m))}}At(r)||ke(6),n!==void 0&&!At(n)&&ke(7);let a;if(Ve(t)){const l=jn(this),d=ws(l,t,void 0);let c=!0;try{a=r(d),c=!1}finally{c?ps(l):gs(l)}return Nn(l,n),_n(a,l)}else if(!t||!ls(t)){if(a=r(t),a===void 0&&(a=t),a===yn&&(a=void 0),this.autoFreeze_&&hs(a,!0),n){const l=[],d=[];Ft(ms).generateReplacementPatches_(t,a,{patches_:l,inversePatches_:d}),n(l,d)}return a}else ke(1,t)},this.produceWithPatches=(t,r)=>{if(At(t))return(d,...c)=>this.produceWithPatches(d,f=>t(f,...c));let n,a;return[this.produce(t,r,(d,c)=>{n=d,a=c}),n,a]},ds(e==null?void 0:e.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),ds(e==null?void 0:e.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),ds(e==null?void 0:e.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){Ve(e)||ke(8),rt(e)&&(e=Ki(e));const t=jn(this),r=ws(t,e,void 0);return r[Ne].isManual_=!0,gs(t),r}finishDraft(e,t){const r=e&&e[Ne];(!r||!r.isManual_)&&ke(9);const{scope_:n}=r;return Nn(n,t),_n(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){const a=t[r];if(a.path.length===0&&a.op==="replace"){e=a.value;break}}r>-1&&(t=t.slice(r+1));const n=Ft(ms).applyPatches_;return rt(e)?n(e,t):this.produce(e,a=>n(a,t))}};function ws(e,t,r,n){const[a,l]=Ar(t)?Ft(Ir).proxyMap_(t,r):Cr(t)?Ft(Ir).proxySet_(t,r):Li(t,r);return((r==null?void 0:r.scope_)??Sn()).drafts_.push(a),l.callbacks_=(r==null?void 0:r.callbacks_)??[],l.key_=n,r&&n!==void 0?Mi(r,l,n):l.callbacks_.push(function(f){var h;(h=f.mapSetPlugin_)==null||h.fixSetContents(l);const{patchPlugin_:m}=f;l.modified_&&m&&m.generatePatches_(l,[],f)}),a}function Ki(e){return rt(e)||ke(10,e),On(e)}function On(e){if(!Ve(e)||kr(e))return e;const t=e[Ne];let r,n=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,r=fs(e,t.scope_.immer_.useStrictShallowCopy_),n=t.scope_.immer_.shouldUseStrictIteration()}else r=fs(e,!0);return nr(r,(a,l)=>{jr(r,a,On(l))},n),t&&(t.finalized_=!1),r}var Vi=new Ui,Rn=Vi.produce,Hi=(e,t,r)=>{if(t.length===1&&t[0]===r){let n=!1;try{const a={};e(a)===a&&(n=!0)}catch{}if(n){let a;try{throw new Error}catch(l){({stack:a}=l)}console.warn(`The result function returned its own inputs without modification. e.g
\`createSelector([state => state.todos], todos => todos)\`
This could lead to inefficient memoization and unnecessary re-renders.
Ensure transformation logic is in the result function, and extraction logic is in the input selectors.`,{stack:a})}}},zi=(e,t,r)=>{const{memoize:n,memoizeOptions:a}=t,{inputSelectorResults:l,inputSelectorResultsCopy:d}=e,c=n(()=>({}),...a);if(!(c.apply(null,l)===c.apply(null,d))){let m;try{throw new Error}catch(h){({stack:m}=h)}console.warn(`An input selector returned a different result when passed same arguments.
This means your output selector will likely run more frequently than intended.
Avoid returning a new reference inside your input selector, e.g.
\`createSelector([state => state.todos.map(todo => todo.id)], todoIds => todoIds.length)\``,{arguments:r,firstInputs:l,secondInputs:d,stack:m})}},Gi={inputStabilityCheck:"once",identityFunctionCheck:"once"};function qi(e,t=`expected a function, instead received ${typeof e}`){if(typeof e!="function")throw new TypeError(t)}function Wi(e,t=`expected an object, instead received ${typeof e}`){if(typeof e!="object")throw new TypeError(t)}function Yi(e,t="expected all items to be functions, instead received the following types: "){if(!e.every(r=>typeof r=="function")){const r=e.map(n=>typeof n=="function"?`function ${n.name||"unnamed"}()`:typeof n).join(", ");throw new TypeError(`${t}[${r}]`)}}var Dn=e=>Array.isArray(e)?e:[e];function Qi(e){const t=Array.isArray(e[0])?e[0]:e;return Yi(t,"createSelector expects all input-selectors to be functions, but received the following types: "),t}function Fn(e,t){const r=[],{length:n}=e;for(let a=0;a<n;a++)r.push(e[a].apply(null,t));return r}var Ji=(e,t)=>{const{identityFunctionCheck:r,inputStabilityCheck:n}={...Gi,...t};return{identityFunctionCheck:{shouldRun:r==="always"||r==="once"&&e,run:Hi},inputStabilityCheck:{shouldRun:n==="always"||n==="once"&&e,run:zi}}},Zi=class{constructor(e){this.value=e}deref(){return this.value}},Xi=typeof WeakRef<"u"?WeakRef:Zi,eo=0,Pn=1;function Dr(){return{s:eo,v:void 0,o:null,p:null}}function Mn(e,t={}){let r=Dr();const{resultEqualityCheck:n}=t;let a,l=0;function d(){var y;let c=r;const{length:f}=arguments;for(let x=0,N=f;x<N;x++){const _=arguments[x];if(typeof _=="function"||typeof _=="object"&&_!==null){let S=c.o;S===null&&(c.o=S=new WeakMap);const p=S.get(_);p===void 0?(c=Dr(),S.set(_,c)):c=p}else{let S=c.p;S===null&&(c.p=S=new Map);const p=S.get(_);p===void 0?(c=Dr(),S.set(_,c)):c=p}}const m=c;let h;if(c.s===Pn)h=c.v;else if(h=e.apply(null,arguments),l++,n){const x=((y=a==null?void 0:a.deref)==null?void 0:y.call(a))??a;x!=null&&n(x,h)&&(h=x,l!==0&&l--),a=typeof h=="object"&&h!==null||typeof h=="function"?new Xi(h):h}return m.s=Pn,m.v=h,h}return d.clearCache=()=>{r=Dr(),d.resetResultsCount()},d.resultsCount=()=>l,d.resetResultsCount=()=>{l=0},d}function to(e,...t){const r=typeof e=="function"?{memoize:e,memoizeOptions:t}:e,n=(...a)=>{let l=0,d=0,c,f={},m=a.pop();typeof m=="object"&&(f=m,m=a.pop()),qi(m,`createSelector expects an output function after the inputs, but received: [${typeof m}]`);const h={...r,...f},{memoize:y,memoizeOptions:x=[],argsMemoize:N=Mn,argsMemoizeOptions:_=[],devModeChecks:S={}}=h,p=Dn(x),w=Dn(_),E=Qi(a),C=y(function(){return l++,m.apply(null,arguments)},...p);let A=!0;const T=N(function(){d++;const I=Fn(E,arguments);if(c=C.apply(null,I),process.env.NODE_ENV!=="production"){const{identityFunctionCheck:O,inputStabilityCheck:R}=Ji(A,S);if(O.shouldRun&&O.run(m,I,c),R.shouldRun){const $=Fn(E,arguments);R.run({inputSelectorResults:I,inputSelectorResultsCopy:$},{memoize:y,memoizeOptions:p},arguments)}A&&(A=!1)}return c},...w);return Object.assign(T,{resultFunc:m,memoizedResultFunc:C,dependencies:E,dependencyRecomputations:()=>d,resetDependencyRecomputations:()=>{d=0},lastResult:()=>c,recomputations:()=>l,resetRecomputations:()=>{l=0},memoize:y,argsMemoize:N})};return Object.assign(n,{withTypes:()=>n}),n}var mt=to(Mn),ro=Object.assign((e,t=mt)=>{Wi(e,`createStructuredSelector expects first argument to be an object where each property is a selector, instead received a ${typeof e}`);const r=Object.keys(e),n=r.map(l=>e[l]);return t(n,(...l)=>l.reduce((d,c,f)=>(d[r[f]]=c,d),{}))},{withTypes:()=>ro});function Bn(e){return({dispatch:r,getState:n})=>a=>l=>typeof l=="function"?l(r,n,e):a(l)}var so=Bn(),no=Bn,ao=typeof window<"u"&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(arguments.length!==0)return typeof arguments[0]=="object"?vr:vr.apply(null,arguments)},Ln=e=>e&&typeof e.match=="function";function cr(e,t){function r(...n){if(t){let a=t(...n);if(!a)throw new Error(process.env.NODE_ENV==="production"?ne(0):"prepareAction did not return an object");return{type:e,payload:a.payload,..."meta"in a&&{meta:a.meta},..."error"in a&&{error:a.error}}}return{type:e,payload:n[0]}}return r.toString=()=>`${e}`,r.type=e,r.match=n=>gn(n)&&n.type===e,r}function io(e){return typeof e=="function"&&"type"in e&&Ln(e)}function oo(e){const t=e?`${e}`.split("/"):[],r=t[t.length-1]||"actionCreator";return`Detected an action creator with type "${e||"unknown"}" being dispatched. 
Make sure you're calling the action creator before dispatching, i.e. \`dispatch(${r}())\` instead of \`dispatch(${r})\`. This is necessary even if the action has no payload.`}function co(e={}){if(process.env.NODE_ENV==="production")return()=>r=>n=>r(n);const{isActionCreator:t=io}=e;return()=>r=>n=>(t(n)&&console.warn(oo(n.type)),r(n))}function $n(e,t){let r=0;return{measureTime(n){const a=Date.now();try{return n()}finally{const l=Date.now();r+=l-a}},warnIfExceeded(){r>e&&console.warn(`${t} took ${r}ms, which is more than the warning threshold of ${e}ms. 
If your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.
It is disabled in production builds, so you don't need to worry about that.`)}}}var Un=class br extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,br.prototype)}static get[Symbol.species](){return br}concat(...t){return super.concat.apply(this,t)}prepend(...t){return t.length===1&&Array.isArray(t[0])?new br(...t[0].concat(this)):new br(...t.concat(this))}};function Kn(e){return Ve(e)?Rn(e,()=>{}):e}function Fr(e,t,r){return e.has(t)?e.get(t):e.set(t,r(t)).get(t)}function lo(e){return typeof e!="object"||e==null||Object.isFrozen(e)}function uo(e,t,r){const n=Vn(e,t,r);return{detectMutations(){return Hn(e,t,n,r)}}}function Vn(e,t=[],r,n="",a=new Set){const l={value:r};if(!e(r)&&!a.has(r)){a.add(r),l.children={};const d=t.length>0;for(const c in r){const f=n?n+"."+c:c;d&&t.some(h=>h instanceof RegExp?h.test(f):f===h)||(l.children[c]=Vn(e,t,r[c],f))}}return l}function Hn(e,t=[],r,n,a=!1,l=""){const d=r?r.value:void 0,c=d===n;if(a&&!c&&!Number.isNaN(n))return{wasMutated:!0,path:l};if(e(d)||e(n))return{wasMutated:!1};const f={};for(let h in r.children)f[h]=!0;for(let h in n)f[h]=!0;const m=t.length>0;for(let h in f){const y=l?l+"."+h:h;if(m&&t.some(_=>_ instanceof RegExp?_.test(y):y===_))continue;const x=Hn(e,t,r.children[h],n[h],c,y);if(x.wasMutated)return x}return{wasMutated:!1}}function fo(e={}){if(process.env.NODE_ENV==="production")return()=>t=>r=>t(r);{let t=function(c,f,m,h){return JSON.stringify(c,r(f,h),m)},r=function(c,f){let m=[],h=[];return f||(f=function(y,x){return m[0]===x?"[Circular ~]":"[Circular ~."+h.slice(0,m.indexOf(x)).join(".")+"]"}),function(y,x){if(m.length>0){var N=m.indexOf(this);~N?m.splice(N+1):m.push(this),~N?h.splice(N,1/0,y):h.push(y),~m.indexOf(x)&&(x=f.call(this,y,x))}else m.push(x);return c==null?x:c.call(this,y,x)}},{isImmutable:n=lo,ignoredPaths:a,warnAfter:l=32}=e;const d=uo.bind(null,n,a);return({getState:c})=>{let f=c(),m=d(f),h;return y=>x=>{const N=$n(l,"ImmutableStateInvariantMiddleware");N.measureTime(()=>{if(f=c(),h=m.detectMutations(),m=d(f),h.wasMutated)throw new Error(process.env.NODE_ENV==="production"?ne(19):`A state mutation was detected between dispatches, in the path '${h.path||""}'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)});const _=y(x);return N.measureTime(()=>{if(f=c(),h=m.detectMutations(),m=d(f),h.wasMutated)throw new Error(process.env.NODE_ENV==="production"?ne(20):`A state mutation was detected inside a dispatch, in the path: ${h.path||""}. Take a look at the reducer(s) handling the action ${t(x)}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`)}),N.warnIfExceeded(),_}}}}function zn(e){const t=typeof e;return e==null||t==="string"||t==="boolean"||t==="number"||Array.isArray(e)||rr(e)}function Es(e,t="",r=zn,n,a=[],l){let d;if(!r(e))return{keyPath:t||"<root>",value:e};if(typeof e!="object"||e===null||l!=null&&l.has(e))return!1;const c=n!=null?n(e):Object.entries(e),f=a.length>0;for(const[m,h]of c){const y=t?t+"."+m:m;if(!(f&&a.some(N=>N instanceof RegExp?N.test(y):y===N))){if(!r(h))return{keyPath:y,value:h};if(typeof h=="object"&&(d=Es(h,y,r,n,a,l),d))return d}}return l&&Gn(e)&&l.add(e),!1}function Gn(e){if(!Object.isFrozen(e))return!1;for(const t of Object.values(e))if(!(typeof t!="object"||t===null)&&!Gn(t))return!1;return!0}function ho(e={}){if(process.env.NODE_ENV==="production")return()=>t=>r=>t(r);{const{isSerializable:t=zn,getEntries:r,ignoredActions:n=[],ignoredActionPaths:a=["meta.arg","meta.baseQueryMeta"],ignoredPaths:l=[],warnAfter:d=32,ignoreState:c=!1,ignoreActions:f=!1,disableCache:m=!1}=e,h=!m&&WeakSet?new WeakSet:void 0;return y=>x=>N=>{if(!gn(N))return x(N);const _=x(N),S=$n(d,"SerializableStateInvariantMiddleware");return!f&&!(n.length&&n.indexOf(N.type)!==-1)&&S.measureTime(()=>{const p=Es(N,"",t,r,a,h);if(p){const{keyPath:w,value:E}=p;console.error(`A non-serializable value was detected in an action, in the path: \`${w}\`. Value:`,E,`
Take a look at the logic that dispatched this action: `,N,`
(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)`,`
(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)`)}}),c||(S.measureTime(()=>{const p=y.getState(),w=Es(p,"",t,r,l,h);if(w){const{keyPath:E,value:C}=w;console.error(`A non-serializable value was detected in the state, in the path: \`${E}\`. Value:`,C,`
Take a look at the reducer(s) handling this action type: ${N.type}.
(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`)}}),S.warnIfExceeded()),_}}}function Pr(e){return typeof e=="boolean"}var mo=()=>function(t){const{thunk:r=!0,immutableCheck:n=!0,serializableCheck:a=!0,actionCreatorCheck:l=!0}=t??{};let d=new Un;if(r&&(Pr(r)?d.push(so):d.push(no(r.extraArgument))),process.env.NODE_ENV!=="production"){if(n){let c={};Pr(n)||(c=n),d.unshift(fo(c))}if(a){let c={};Pr(a)||(c=a),d.push(ho(c))}if(l){let c={};Pr(l)||(c=l),d.unshift(co(c))}}return d},po="RTK_autoBatch",qn=e=>t=>{setTimeout(t,e)},go=(e={type:"raf"})=>t=>(...r)=>{const n=t(...r);let a=!0,l=!1,d=!1;const c=new Set,f=e.type==="tick"?queueMicrotask:e.type==="raf"?typeof window<"u"&&window.requestAnimationFrame?window.requestAnimationFrame:qn(10):e.type==="callback"?e.queueNotification:qn(e.timeout),m=()=>{d=!1,l&&(l=!1,c.forEach(h=>h()))};return Object.assign({},n,{subscribe(h){const y=()=>a&&h(),x=n.subscribe(y);return c.add(h),()=>{x(),c.delete(h)}},dispatch(h){var y;try{return a=!((y=h==null?void 0:h.meta)!=null&&y[po]),l=!a,l&&(d||(d=!0,f(m))),n.dispatch(h)}finally{a=!0}}})},yo=e=>function(r){const{autoBatch:n=!0}=r??{};let a=new Un(e);return n&&a.push(go(typeof n=="object"?n:void 0)),a};function xo(e){const t=mo(),{reducer:r=void 0,middleware:n,devTools:a=!0,duplicateMiddlewareCheck:l=!0,preloadedState:d=void 0,enhancers:c=void 0}=e||{};let f;if(typeof r=="function")f=r;else if(rr(r))f=_i(r);else throw new Error(process.env.NODE_ENV==="production"?ne(1):"`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers");if(process.env.NODE_ENV!=="production"&&n&&typeof n!="function")throw new Error(process.env.NODE_ENV==="production"?ne(2):"`middleware` field must be a callback");let m;if(typeof n=="function"){if(m=n(t),process.env.NODE_ENV!=="production"&&!Array.isArray(m))throw new Error(process.env.NODE_ENV==="production"?ne(3):"when using a middleware builder function, an array of middleware must be returned")}else m=t();if(process.env.NODE_ENV!=="production"&&m.some(S=>typeof S!="function"))throw new Error(process.env.NODE_ENV==="production"?ne(4):"each middleware provided to configureStore must be a function");if(process.env.NODE_ENV!=="production"&&l){let S=new Set;m.forEach(p=>{if(S.has(p))throw new Error(process.env.NODE_ENV==="production"?ne(42):"Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.");S.add(p)})}let h=vr;a&&(h=ao({trace:process.env.NODE_ENV!=="production",...typeof a=="object"&&a}));const y=Ai(...m),x=yo(y);if(process.env.NODE_ENV!=="production"&&c&&typeof c!="function")throw new Error(process.env.NODE_ENV==="production"?ne(5):"`enhancers` field must be a callback");let N=typeof c=="function"?c(x):x();if(process.env.NODE_ENV!=="production"&&!Array.isArray(N))throw new Error(process.env.NODE_ENV==="production"?ne(6):"`enhancers` callback must return an array");if(process.env.NODE_ENV!=="production"&&N.some(S=>typeof S!="function"))throw new Error(process.env.NODE_ENV==="production"?ne(7):"each enhancer provided to configureStore must be a function");process.env.NODE_ENV!=="production"&&m.length&&!N.includes(y)&&console.error("middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`");const _=h(...N);return mn(f,d,_)}function Wn(e){const t={},r=[];let n;const a={addCase(l,d){if(process.env.NODE_ENV!=="production"){if(r.length>0)throw new Error(process.env.NODE_ENV==="production"?ne(26):"`builder.addCase` should only be called before calling `builder.addMatcher`");if(n)throw new Error(process.env.NODE_ENV==="production"?ne(27):"`builder.addCase` should only be called before calling `builder.addDefaultCase`")}const c=typeof l=="string"?l:l.type;if(!c)throw new Error(process.env.NODE_ENV==="production"?ne(28):"`builder.addCase` cannot be called with an empty action type");if(c in t)throw new Error(process.env.NODE_ENV==="production"?ne(29):`\`builder.addCase\` cannot be called with two reducers for the same action type '${c}'`);return t[c]=d,a},addAsyncThunk(l,d){if(process.env.NODE_ENV!=="production"&&n)throw new Error(process.env.NODE_ENV==="production"?ne(43):"`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`");return d.pending&&(t[l.pending.type]=d.pending),d.rejected&&(t[l.rejected.type]=d.rejected),d.fulfilled&&(t[l.fulfilled.type]=d.fulfilled),d.settled&&r.push({matcher:l.settled,reducer:d.settled}),a},addMatcher(l,d){if(process.env.NODE_ENV!=="production"&&n)throw new Error(process.env.NODE_ENV==="production"?ne(30):"`builder.addMatcher` should only be called before calling `builder.addDefaultCase`");return r.push({matcher:l,reducer:d}),a},addDefaultCase(l){if(process.env.NODE_ENV!=="production"&&n)throw new Error(process.env.NODE_ENV==="production"?ne(31):"`builder.addDefaultCase` can only be called once");return n=l,a}};return e(a),[t,r,n]}function bo(e){return typeof e=="function"}function vo(e,t){if(process.env.NODE_ENV!=="production"&&typeof t=="object")throw new Error(process.env.NODE_ENV==="production"?ne(8):"The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer");let[r,n,a]=Wn(t),l;if(bo(e))l=()=>Kn(e());else{const c=Kn(e);l=()=>c}function d(c=l(),f){let m=[r[f.type],...n.filter(({matcher:h})=>h(f)).map(({reducer:h})=>h)];return m.filter(h=>!!h).length===0&&(m=[a]),m.reduce((h,y)=>{if(y)if(rt(h)){const N=y(h,f);return N===void 0?h:N}else{if(Ve(h))return Rn(h,x=>y(x,f));{const x=y(h,f);if(x===void 0){if(h===null)return h;throw Error("A case reducer on a non-draftable value must not return undefined")}return x}}return h},c)}return d.getInitialState=l,d}var wo=(e,t)=>Ln(e)?e.match(t):e(t);function Eo(...e){return t=>e.some(r=>wo(r,t))}var So="ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW",No=(e=21)=>{let t="",r=e;for(;r--;)t+=So[Math.random()*64|0];return t},jo=["name","message","stack","code"],Ss=class{constructor(e,t){ut(this,"_type");this.payload=e,this.meta=t}},Yn=class{constructor(e,t){ut(this,"_type");this.payload=e,this.meta=t}},_o=e=>{if(typeof e=="object"&&e!==null){const t={};for(const r of jo)typeof e[r]=="string"&&(t[r]=e[r]);return t}return{message:String(e)}},Qn="External signal was aborted",Pt=(()=>{function e(t,r,n){const a=cr(t+"/fulfilled",(f,m,h,y)=>({payload:f,meta:{...y||{},arg:h,requestId:m,requestStatus:"fulfilled"}})),l=cr(t+"/pending",(f,m,h)=>({payload:void 0,meta:{...h||{},arg:m,requestId:f,requestStatus:"pending"}})),d=cr(t+"/rejected",(f,m,h,y,x)=>({payload:y,error:(n&&n.serializeError||_o)(f||"Rejected"),meta:{...x||{},arg:h,requestId:m,rejectedWithValue:!!y,requestStatus:"rejected",aborted:(f==null?void 0:f.name)==="AbortError",condition:(f==null?void 0:f.name)==="ConditionError"}}));function c(f,{signal:m}={}){return(h,y,x)=>{const N=n!=null&&n.idGenerator?n.idGenerator(f):No(),_=new AbortController;let S,p;function w(C){p=C,_.abort()}m&&(m.aborted?w(Qn):m.addEventListener("abort",()=>w(Qn),{once:!0}));const E=async function(){var T,M;let C;try{let I=(T=n==null?void 0:n.condition)==null?void 0:T.call(n,f,{getState:y,extra:x});if(Co(I)&&(I=await I),I===!1||_.signal.aborted)throw{name:"ConditionError",message:"Aborted due to condition callback returning false."};const O=new Promise((R,$)=>{S=()=>{$({name:"AbortError",message:p||"Aborted"})},_.signal.addEventListener("abort",S,{once:!0})});h(l(N,f,(M=n==null?void 0:n.getPendingMeta)==null?void 0:M.call(n,{requestId:N,arg:f},{getState:y,extra:x}))),C=await Promise.race([O,Promise.resolve(r(f,{dispatch:h,getState:y,extra:x,requestId:N,signal:_.signal,abort:w,rejectWithValue:(R,$)=>new Ss(R,$),fulfillWithValue:(R,$)=>new Yn(R,$)})).then(R=>{if(R instanceof Ss)throw R;return R instanceof Yn?a(R.payload,N,f,R.meta):a(R,N,f)})])}catch(I){C=I instanceof Ss?d(null,N,f,I.payload,I.meta):d(I,N,f)}finally{S&&_.signal.removeEventListener("abort",S)}return n&&!n.dispatchConditionRejection&&d.match(C)&&C.meta.condition||h(C),C}();return Object.assign(E,{abort:w,requestId:N,arg:f,unwrap(){return E.then(Ao)}})}}return Object.assign(c,{pending:l,rejected:d,fulfilled:a,settled:Eo(d,a),typePrefix:t})}return e.withTypes=()=>e,e})();function Ao(e){if(e.meta&&e.meta.rejectedWithValue)throw e.payload;if(e.error)throw e.error;return e.payload}function Co(e){return e!==null&&typeof e=="object"&&typeof e.then=="function"}var To=Symbol.for("rtk-slice-createasyncthunk");function ko(e,t){return`${e}/${t}`}function Io({creators:e}={}){var r;const t=(r=e==null?void 0:e.asyncThunk)==null?void 0:r[To];return function(a){const{name:l,reducerPath:d=l}=a;if(!l)throw new Error(process.env.NODE_ENV==="production"?ne(11):"`name` is a required option for createSlice");typeof process<"u"&&process.env.NODE_ENV==="development"&&a.initialState===void 0&&console.error("You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`");const c=(typeof a.reducers=="function"?a.reducers(Ro()):a.reducers)||{},f=Object.keys(c),m={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},h={addCase(A,T){const M=typeof A=="string"?A:A.type;if(!M)throw new Error(process.env.NODE_ENV==="production"?ne(12):"`context.addCase` cannot be called with an empty action type");if(M in m.sliceCaseReducersByType)throw new Error(process.env.NODE_ENV==="production"?ne(13):"`context.addCase` cannot be called with two reducers for the same action type: "+M);return m.sliceCaseReducersByType[M]=T,h},addMatcher(A,T){return m.sliceMatchers.push({matcher:A,reducer:T}),h},exposeAction(A,T){return m.actionCreators[A]=T,h},exposeCaseReducer(A,T){return m.sliceCaseReducersByName[A]=T,h}};f.forEach(A=>{const T=c[A],M={reducerName:A,type:ko(l,A),createNotation:typeof a.reducers=="function"};Fo(T)?Mo(M,T,h,t):Do(M,T,h)});function y(){if(process.env.NODE_ENV!=="production"&&typeof a.extraReducers=="object")throw new Error(process.env.NODE_ENV==="production"?ne(14):"The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice");const[A={},T=[],M=void 0]=typeof a.extraReducers=="function"?Wn(a.extraReducers):[a.extraReducers],I={...A,...m.sliceCaseReducersByType};return vo(a.initialState,O=>{for(let R in I)O.addCase(R,I[R]);for(let R of m.sliceMatchers)O.addMatcher(R.matcher,R.reducer);for(let R of T)O.addMatcher(R.matcher,R.reducer);M&&O.addDefaultCase(M)})}const x=A=>A,N=new Map,_=new WeakMap;let S;function p(A,T){return S||(S=y()),S(A,T)}function w(){return S||(S=y()),S.getInitialState()}function E(A,T=!1){function M(O){let R=O[A];if(typeof R>"u"){if(T)R=Fr(_,M,w);else if(process.env.NODE_ENV!=="production")throw new Error(process.env.NODE_ENV==="production"?ne(15):"selectSlice returned undefined for an uninjected slice reducer")}return R}function I(O=x){const R=Fr(N,T,()=>new WeakMap);return Fr(R,O,()=>{const $={};for(const[F,H]of Object.entries(a.selectors??{}))$[F]=Oo(H,O,()=>Fr(_,O,w),T);return $})}return{reducerPath:A,getSelectors:I,get selectors(){return I(M)},selectSlice:M}}const C={name:l,reducer:p,actions:m.actionCreators,caseReducers:m.sliceCaseReducersByName,getInitialState:w,...E(d),injectInto(A,{reducerPath:T,...M}={}){const I=T??d;return A.inject({reducerPath:I,reducer:p},M),{...C,...E(I,!0)}}};return C}}function Oo(e,t,r,n){function a(l,...d){let c=t(l);if(typeof c>"u"){if(n)c=r();else if(process.env.NODE_ENV!=="production")throw new Error(process.env.NODE_ENV==="production"?ne(16):"selectState returned undefined for an uninjected slice reducer")}return e(c,...d)}return a.unwrapped=e,a}var Ns=Io();function Ro(){function e(t,r){return{_reducerDefinitionType:"asyncThunk",payloadCreator:t,...r}}return e.withTypes=()=>e,{reducer(t){return Object.assign({[t.name](...r){return t(...r)}}[t.name],{_reducerDefinitionType:"reducer"})},preparedReducer(t,r){return{_reducerDefinitionType:"reducerWithPrepare",prepare:t,reducer:r}},asyncThunk:e}}function Do({type:e,reducerName:t,createNotation:r},n,a){let l,d;if("reducer"in n){if(r&&!Po(n))throw new Error(process.env.NODE_ENV==="production"?ne(17):"Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.");l=n.reducer,d=n.prepare}else l=n;a.addCase(e,l).exposeCaseReducer(t,l).exposeAction(t,d?cr(e,d):cr(e))}function Fo(e){return e._reducerDefinitionType==="asyncThunk"}function Po(e){return e._reducerDefinitionType==="reducerWithPrepare"}function Mo({type:e,reducerName:t},r,n,a){if(!a)throw new Error(process.env.NODE_ENV==="production"?ne(18):"Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.");const{payloadCreator:l,fulfilled:d,pending:c,rejected:f,settled:m,options:h}=r,y=a(e,l,h);n.exposeAction(t,y),d&&n.addCase(y.fulfilled,d),c&&n.addCase(y.pending,c),f&&n.addCase(y.rejected,f),m&&n.addMatcher(y.settled,m),n.exposeCaseReducer(t,{fulfilled:d||Mr,pending:c||Mr,rejected:f||Mr,settled:m||Mr})}function Mr(){}function ne(e){return`Minified Redux Toolkit error #${e}; visit https://redux-toolkit.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}const Bo={GET_INDEXING_STATUS:"/indexing/status",GET_INGESTION_CONFIG:"/ingestion/config",HEALTH_CHECK:"/ingestion/health",PROCESS_JSON:"/ingestion/process",GET_STATUS:"/ingestion/status",VALIDATE_JSON:"/ingestion/validate",ANALYZE_QUERY:"/llm-query/analyze",GET_BACKFILL_STATUS:e=>`/llm-query/backfill/${e}`,CHAT:"/llm-query/chat",EXECUTE_QUERY_PLAN:"/llm-query/execute",RUN_QUERY:"/llm-query/run",LIST_LOGS:"/logs",GET_CONFIG:"/logs/config",RELOAD_CONFIG:"/logs/config/reload",GET_FEATURES:"/logs/features",UPDATE_FEATURE_LEVEL:"/logs/level",STREAM_LOGS:"/logs/stream",EXECUTE_MUTATION:"/mutation",NATIVE_INDEX_SEARCH:"/native-index/search",EXECUTE_QUERY:"/query",GET_SCHEMA:e=>`/schema/${e}`,APPROVE_SCHEMA:e=>`/schema/${e}/approve`,BLOCK_SCHEMA:e=>`/schema/${e}/block`,LIST_SCHEMAS:"/schemas",LOAD_SCHEMAS:"/schemas/load",GET_SYSTEM_PUBLIC_KEY:"/security/system-key",GET_DATABASE_CONFIG:"/system/database-config",GET_NODE_PRIVATE_KEY:"/system/private-key",GET_NODE_PUBLIC_KEY:"/system/public-key",RESET_DATABASE:"/system/reset-database",RESET_SCHEMA_SERVICE:"/system/reset-schema-service",GET_SYSTEM_STATUS:"/system/status",LIST_TRANSFORMS:"/transforms",GET_ALL_BACKFILLS:"/transforms/backfills",GET_ACTIVE_BACKFILLS:"/transforms/backfills/active",GET_BACKFILL_STATISTICS:"/transforms/backfills/statistics",GET_BACKFILL:e=>`/transforms/backfills/${e}`,GET_TRANSFORM_QUEUE:"/transforms/queue",ADD_TO_TRANSFORM_QUEUE:e=>`/transforms/queue/${e}`,GET_TRANSFORM_STATISTICS:"/transforms/statistics"},Lo={ROOT:"/api"},ee=Bo,$o=3e4,Uo=3,Ko=1e3,xe={QUICK:5e3,STANDARD:8e3,CONFIG:1e4,MUTATION:15e3,AI_PROCESSING:6e4,DESTRUCTIVE_OPERATIONS:3e4},be={NONE:0,LIMITED:1,STANDARD:2,CRITICAL:3},pt={STANDARD:3e5,SYSTEM_STATUS:3e4,SCHEMA_DATA:3e5,SECURITY_STATUS:6e4,SYSTEM_PUBLIC_KEY:36e5},Fe={BAD_REQUEST:400,UNAUTHORIZED:401,FORBIDDEN:403,NOT_FOUND:404,INTERNAL_SERVER_ERROR:500,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503},js={JSON:"application/json",FORM_DATA:"multipart/form-data",URL_ENCODED:"application/x-www-form-urlencoded",TEXT:"text/plain"},Br={CONTENT_TYPE:"Content-Type",AUTHORIZATION:"Authorization",SIGNED_REQUEST:"X-Signed-Request",REQUEST_ID:"X-Request-ID",AUTHENTICATED:"X-Authenticated"},Oe={NETWORK_ERROR:"Network connection failed. Please check your internet connection.",TIMEOUT_ERROR:"Request timed out. Please try again.",AUTHENTICATION_ERROR:"Authentication required. Please ensure you are properly authenticated.",SCHEMA_STATE_ERROR:"Schema operation not allowed. Only approved schemas can be accessed.",SERVER_ERROR:"Server error occurred. Please try again later.",VALIDATION_ERROR:"Request validation failed. Please check your input.",NOT_FOUND_ERROR:"Requested resource not found.",PERMISSION_ERROR:"Permission denied. You do not have access to this resource.",RATE_LIMIT_ERROR:"Too many requests. Please wait before trying again."},lr={DEFAULT_TTL_MS:pt.STANDARD,MAX_CACHE_SIZE:100,SCHEMA_CACHE_TTL_MS:pt.SCHEMA_DATA,SYSTEM_STATUS_CACHE_TTL_MS:pt.SYSTEM_STATUS},_s={RETRYABLE_STATUS_CODES:[408,429,500,502,503,504],EXPONENTIAL_BACKOFF_MULTIPLIER:2,MAX_RETRY_DELAY_MS:1e4},Lr={BASE_URL:"api"},Re={AVAILABLE:"available",APPROVED:"approved",BLOCKED:"blocked"},Vo={MUTATION:"mutation"},$r={SYSTEM_STATUS:"system-status",SECURITY_STATUS:"security-status",SYSTEM_PUBLIC_KEY:"system-public-key"};class we extends Error{constructor(t,r=0,n={}){super(t),this.name="ApiError",this.status=r,this.response=n.response,this.isNetworkError=n.isNetworkError||!1,this.isTimeoutError=n.isTimeoutError||!1,this.isRetryable=this.determineRetryability(r,n.isNetworkError,n.isTimeoutError),this.requestId=n.requestId,this.timestamp=Date.now(),this.code=n.code,this.details=n.details,Object.setPrototypeOf(this,we.prototype)}determineRetryability(t,r,n){return r||n?!0:_s.RETRYABLE_STATUS_CODES.includes(t)}toUserMessage(){if(this.isNetworkError)return Oe.NETWORK_ERROR;if(this.isTimeoutError)return Oe.TIMEOUT_ERROR;switch(this.status){case Fe.UNAUTHORIZED:return Oe.AUTHENTICATION_ERROR;case Fe.FORBIDDEN:return Oe.PERMISSION_ERROR;case Fe.NOT_FOUND:return Oe.NOT_FOUND_ERROR;case Fe.BAD_REQUEST:return Oe.VALIDATION_ERROR;case Fe.INTERNAL_SERVER_ERROR:case Fe.BAD_GATEWAY:case Fe.SERVICE_UNAVAILABLE:return Oe.SERVER_ERROR;case 429:return Oe.RATE_LIMIT_ERROR;default:return this.message||Oe.SERVER_ERROR}}toJSON(){return{name:this.name,message:this.message,status:this.status,isNetworkError:this.isNetworkError,isTimeoutError:this.isTimeoutError,isRetryable:this.isRetryable,requestId:this.requestId,timestamp:this.timestamp,code:this.code,details:this.details,stack:this.stack}}}class As extends we{constructor(t=Oe.AUTHENTICATION_ERROR,r){super(t,Fe.UNAUTHORIZED,{code:"AUTH_ERROR",requestId:r}),this.name="AuthenticationError",Object.setPrototypeOf(this,As.prototype)}}class Ur extends we{constructor(t,r,n,a=Oe.SCHEMA_STATE_ERROR){super(a,Fe.FORBIDDEN,{code:"SCHEMA_STATE_ERROR",details:{schemaName:t,currentState:r,operation:n}}),this.name="SchemaStateError",this.schemaName=t,this.currentState=r,this.operation=n,Object.setPrototypeOf(this,Ur.prototype)}}class Cs extends we{constructor(t=Oe.NETWORK_ERROR,r){super(t,0,{isNetworkError:!0,code:"NETWORK_ERROR",requestId:r}),this.name="NetworkError",Object.setPrototypeOf(this,Cs.prototype)}}class Ts extends we{constructor(t,r){super(`Request timed out after ${t}ms`,408,{isTimeoutError:!0,code:"TIMEOUT_ERROR",requestId:r,details:{timeoutMs:t}}),this.name="TimeoutError",this.timeoutMs=t,Object.setPrototypeOf(this,Ts.prototype)}}class ks extends we{constructor(t,r){super("Request validation failed",Fe.BAD_REQUEST,{code:"VALIDATION_ERROR",requestId:r,details:{validationErrors:t}}),this.name="ValidationError",this.validationErrors=t,Object.setPrototypeOf(this,ks.prototype)}}class Is extends we{constructor(t,r){const n=t?`Rate limit exceeded. Retry after ${t} seconds.`:Oe.RATE_LIMIT_ERROR;super(n,429,{code:"RATE_LIMIT_ERROR",requestId:r,details:{retryAfter:t}}),this.name="RateLimitError",this.retryAfter=t,Object.setPrototypeOf(this,Is.prototype)}}class dr{static async fromResponse(t,r){let n={};try{const l=await t.text();l&&(n=JSON.parse(l))}catch{}const a=typeof n.error=="string"?n.error:typeof n.message=="string"?n.message:`HTTP ${t.status}`;if(t.status===Fe.UNAUTHORIZED)return new As(a,r||"");if(t.status===429){const l=t.headers.get("Retry-After");return new Is(l?parseInt(l):void 0,r)}return t.status===Fe.BAD_REQUEST&&n.validationErrors?new ks(n.validationErrors,r||""):new we(a,t.status,{response:n,requestId:r,code:typeof n.code=="string"?n.code:void 0,details:typeof n.details=="object"&&n.details!==null?n.details:void 0})}static fromNetworkError(t,r){return new Cs(t.message,r)}static fromTimeout(t,r){return new Ts(t,r)}static fromSchemaState(t,r,n){return new Ur(t,r,n)}}function Ho(e){return e instanceof we}function zo(e){return Ho(e)&&e.isRetryable}class Go{constructor(t=lr.MAX_CACHE_SIZE){this.cache=new Map,this.maxSize=t}get(t){const r=this.cache.get(t);return r?Date.now()>r.timestamp+r.ttl?(this.cache.delete(t),null):r.data:null}set(t,r,n=lr.DEFAULT_TTL_MS){if(this.cache.size>=this.maxSize){const a=this.cache.keys().next().value;this.cache.delete(a)}this.cache.set(t,{data:r,timestamp:Date.now(),ttl:n,key:t})}clear(){this.cache.clear()}size(){return this.cache.size}getHitRate(){return this.cache.size>0?.8:0}}class qo{constructor(){this.queue=new Map}getOrCreate(t,r){if(this.queue.has(t))return this.queue.get(t);const n=r().finally(()=>{this.queue.delete(t)});return this.queue.set(t,n),n}clear(){this.queue.clear()}}class Jn{constructor(t={}){this.requestInterceptors=[],this.responseInterceptors=[],this.errorInterceptors=[],this.metrics=[],this.config={baseUrl:t.baseUrl||Lr.BASE_URL,timeout:t.timeout||$o,retryAttempts:t.retryAttempts||Uo,retryDelay:t.retryDelay||Ko,defaultHeaders:t.defaultHeaders||{},enableCache:t.enableCache!==!1,enableLogging:t.enableLogging!==!1,enableMetrics:t.enableMetrics!==!1},this.cache=new Go,this.requestQueue=new qo}async get(t,r={}){return this.request("GET",t,void 0,r)}async post(t,r,n={}){return this.request("POST",t,r,n)}async put(t,r,n={}){return this.request("PUT",t,r,n)}async delete(t,r={}){return this.request("DELETE",t,void 0,r)}async patch(t,r,n={}){return this.request("PATCH",t,r,n)}async batch(t){if(t.length>lr.MAX_CACHE_SIZE)throw new we(`Batch size exceeds limit of ${lr.MAX_CACHE_SIZE}`);const r=t.map(async n=>{try{const a=await this.request(n.method,n.url,n.body,n.options);return{id:n.id,success:a.success,data:a.data,status:a.status}}catch(a){const l=a instanceof we?a:new we(a.message);return{id:n.id,success:!1,error:l.message,status:l.status}}});return Promise.all(r)}async request(t,r,n,a={}){var f,m;const l=a.requestId||this.generateRequestId(),d=Date.now();let c={url:this.buildUrl(r),method:t,headers:{...this.config.defaultHeaders},body:n,timeout:a.timeout||this.config.timeout,retries:a.retries!==void 0?a.retries:this.config.retryAttempts,validateSchema:!!a.validateSchema,requiresAuth:!1,abortSignal:a.abortSignal,metadata:{requestId:l,timestamp:d,priority:a.priority||"normal"}};try{for(const N of this.requestInterceptors)c=await N(c);if(c.validateSchema&&await this.validateSchemaAccess(r,t,a.validateSchema||!0),t==="GET"&&this.config.enableCache&&a.cacheable!==!1){const N=this.generateCacheKey(c.url,c.headers),_=this.cache.get(N);if(_)return{..._,meta:{..._.meta,cached:!0,fromCache:!0,requestId:l,timestamp:((f=_.meta)==null?void 0:f.timestamp)||Date.now()}}}const h=`${t}:${c.url}:${JSON.stringify(n)}`,y=await this.requestQueue.getOrCreate(h,()=>this.executeRequest(c));if(t==="GET"&&this.config.enableCache&&a.cacheable!==!1&&y.success){const N=this.generateCacheKey(c.url,c.headers),_=a.cacheTtl||lr.DEFAULT_TTL_MS;this.cache.set(N,y,_)}let x=y;for(const N of this.responseInterceptors)x=await N(x);return this.config.enableMetrics&&this.recordMetrics({requestId:l,url:c.url,method:t,startTime:d,endTime:Date.now(),duration:Date.now()-d,status:y.status,cached:((m=y.meta)==null?void 0:m.cached)||!1}),x}catch(h){let y=h instanceof we?h:dr.fromNetworkError(h,l);for(const x of this.errorInterceptors)y=await x(y);throw this.config.enableMetrics&&this.recordMetrics({requestId:l,url:c.url,method:t,startTime:d,endTime:Date.now(),duration:Date.now()-d,error:y.message}),y}}async executeRequest(t){let r;for(let n=0;n<=t.retries;n++)try{return await this.performRequest(t)}catch(a){if(r=a instanceof we?a:dr.fromNetworkError(a,t.metadata.requestId),n===t.retries||!zo(r))break;const l=Math.min(this.config.retryDelay*Math.pow(_s.EXPONENTIAL_BACKOFF_MULTIPLIER,n),_s.MAX_RETRY_DELAY_MS);await this.sleep(l)}throw r}async performRequest(t){const r=new AbortController,n=setTimeout(()=>r.abort(),t.timeout);try{const a={...t.headers};t.body&&!a[Br.CONTENT_TYPE]&&(a[Br.CONTENT_TYPE]=js.JSON),a[Br.REQUEST_ID]=t.metadata.requestId;const l={method:t.method,headers:a,signal:t.abortSignal||r.signal};t.body&&t.method!=="GET"&&(l.body=this.serializeBody(t.body,a[Br.CONTENT_TYPE]));const d=await fetch(t.url,l);return clearTimeout(n),await this.handleResponse(d,t.metadata.requestId)}catch(a){throw clearTimeout(n),a.name==="AbortError"?dr.fromTimeout(t.timeout,t.metadata.requestId):dr.fromNetworkError(a,t.metadata.requestId)}}async handleResponse(t,r){if(!t.ok)throw await dr.fromResponse(t,r);let n;const a=t.headers.get("content-type");try{a!=null&&a.includes("application/json")?n=await t.json():n=await t.text()}catch{throw new we("Failed to parse response",t.status,{requestId:r})}return{success:!0,data:n,status:t.status,headers:this.extractHeaders(t.headers),meta:{requestId:r,timestamp:Date.now(),cached:!1,fromCache:!1}}}async addAuthHeaders(t,r){}async validateSchemaAccess(t,r,n){const a=t.match(/\/schemas\/([^\/]+)/);if(!a)return;const l=a[1],d=typeof n=="boolean"?{}:n;if((t.includes("/mutation")||t.includes("/query"))&&d.requiresApproved!==!1){const c=Ba.getState().schemas,m=Object.values(c.schemas||{}).find(h=>h.name===l);if(!m||m.state!==Re.APPROVED)throw new Ur(l,(m==null?void 0:m.state)||"unknown",Vo.MUTATION)}}serializeBody(t,r){return r===js.JSON?JSON.stringify(t):r===js.FORM_DATA?t:String(t)}extractHeaders(t){const r={};return t.forEach((n,a)=>{r[a]=n}),r}generateRequestId(){return`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}generateCacheKey(t,r){const n=Object.keys(r).filter(a=>!a.startsWith("X-Request")).sort().map(a=>`${a}:${r[a]}`).join(";");return`${t}|${n}`}buildUrl(t){return t.startsWith("http")?t:`${this.config.baseUrl}${t.startsWith("/")?"":"/"}${t}`}sleep(t){return new Promise(r=>setTimeout(r,t))}recordMetrics(t){this.metrics.push(t),this.metrics.length>1e3&&this.metrics.splice(0,this.metrics.length-1e3)}addRequestInterceptor(t){this.requestInterceptors.push(t)}addResponseInterceptor(t){this.responseInterceptors.push(t)}addErrorInterceptor(t){this.errorInterceptors.push(t)}clearCache(){this.cache.clear()}getCacheStats(){return{size:this.cache.size(),hitRate:this.cache.getHitRate()}}getMetrics(){return[...this.metrics]}clearMetrics(){this.metrics.length=0}}const Wo=new Jn;function He(e){return new Jn(e)}class Yo{constructor(t){this.client=t||He({enableCache:!1,enableLogging:!0,enableMetrics:!0})}async getLogs(){return this.client.get(ee.LIST_LOGS,{requiresAuth:!1,timeout:xe.STANDARD,retries:be.STANDARD,cacheable:!1})}async resetDatabase(t=!1){if(!t)throw new Error("Database reset requires explicit confirmation");const r={confirm:t};return this.client.post(ee.RESET_DATABASE,r,{timeout:xe.DESTRUCTIVE_OPERATIONS,retries:be.NONE,cacheable:!1})}async getSystemStatus(){return this.client.get(ee.GET_SYSTEM_STATUS,{requiresAuth:!1,timeout:xe.QUICK,retries:be.CRITICAL,cacheable:!0,cacheTtl:pt.SYSTEM_STATUS,cacheKey:$r.SYSTEM_STATUS})}async getNodePrivateKey(){return this.client.get(ee.GET_NODE_PRIVATE_KEY,{requiresAuth:!1,timeout:xe.STANDARD,retries:be.STANDARD,cacheable:!1})}async getNodePublicKey(){return this.client.get(ee.GET_NODE_PUBLIC_KEY,{requiresAuth:!1,timeout:xe.QUICK,retries:be.STANDARD,cacheable:!0,cacheTtl:pt.SYSTEM_STATUS,cacheKey:$r.SYSTEM_PUBLIC_KEY})}createLogStream(t,r){const n=ee.STREAM_LOGS,a=n.startsWith("http")?n:`${Lr.BASE_URL}${n.startsWith("/")?"":"/"}${n}`,l=new EventSource(a);return l.onmessage=d=>{t(d.data)},r&&(l.onerror=r),l}validateResetRequest(t){const r=[];return typeof t!="object"||t===null?(r.push("Request must be an object"),{isValid:!1,errors:r}):(typeof t.confirm!="boolean"?r.push("Confirm must be a boolean value"):t.confirm||r.push("Confirm must be true to proceed with database reset"),{isValid:r.length===0,errors:r})}getMetrics(){return this.client.getMetrics().filter(t=>t.url.includes("/system")||t.url.includes("/logs"))}async getDatabaseConfig(){return this.client.get("/system/database-config",{requiresAuth:!1,timeout:xe.STANDARD,retries:be.STANDARD,cacheable:!0,cacheTtl:pt.SYSTEM_STATUS,cacheKey:"database_config"})}async updateDatabaseConfig(t){const r={database:t};return this.client.post("/system/database-config",r,{timeout:xe.STANDARD,retries:be.NONE,cacheable:!1})}clearCache(){this.client.clearCache()}}const he=new Yo;he.getLogs.bind(he),he.resetDatabase.bind(he),he.getSystemStatus.bind(he);const Os=he.getNodePrivateKey.bind(he);he.getNodePublicKey.bind(he);const Qo=he.getDatabaseConfig.bind(he),Jo=he.updateDatabaseConfig.bind(he);he.createLogStream.bind(he),he.validateResetRequest.bind(he);/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */const Zo={p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n},{p:Ee,n:Kr,Gx:Zn,Gy:Xn,a:Rs,d:Ds}=Zo,Xo=8n,ur=32,ea=64,Pe=(e="")=>{throw new Error(e)},ec=e=>typeof e=="bigint",ta=e=>typeof e=="string",tc=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array",Mt=(e,t)=>!tc(e)||typeof t=="number"&&t>0&&e.length!==t?Pe("Uint8Array expected"):e,Vr=e=>new Uint8Array(e),Fs=e=>Uint8Array.from(e),ra=(e,t)=>e.toString(16).padStart(t,"0"),Ps=e=>Array.from(Mt(e)).map(t=>ra(t,2)).join(""),nt={_0:48,_9:57,A:65,F:70,a:97,f:102},sa=e=>{if(e>=nt._0&&e<=nt._9)return e-nt._0;if(e>=nt.A&&e<=nt.F)return e-(nt.A-10);if(e>=nt.a&&e<=nt.f)return e-(nt.a-10)},Ms=e=>{const t="hex invalid";if(!ta(e))return Pe(t);const r=e.length,n=r/2;if(r%2)return Pe(t);const a=Vr(n);for(let l=0,d=0;l<n;l++,d+=2){const c=sa(e.charCodeAt(d)),f=sa(e.charCodeAt(d+1));if(c===void 0||f===void 0)return Pe(t);a[l]=c*16+f}return a},na=(e,t)=>Mt(ta(e)?Ms(e):Fs(Mt(e)),t),aa=()=>globalThis==null?void 0:globalThis.crypto,rc=()=>{var e;return((e=aa())==null?void 0:e.subtle)??Pe("crypto.subtle must be defined")},ia=(...e)=>{const t=Vr(e.reduce((n,a)=>n+Mt(a).length,0));let r=0;return e.forEach(n=>{t.set(n,r),r+=n.length}),t},sc=(e=ur)=>aa().getRandomValues(Vr(e)),Hr=BigInt,Ct=(e,t,r,n="bad number: out of range")=>ec(e)&&t<=e&&e<r?e:Pe(n),K=(e,t=Ee)=>{const r=e%t;return r>=0n?r:t+r},nc=e=>K(e,Kr),oa=(e,t)=>{(e===0n||t<=0n)&&Pe("no inverse n="+e+" mod="+t);let r=K(e,t),n=t,a=0n,l=1n;for(;r!==0n;){const d=n/r,c=n%r,f=a-l*d;n=r,r=c,a=l,l=f}return n===1n?K(a,t):Pe("no inverse")},ca=e=>e instanceof Tt?e:Pe("Point expected"),Bs=2n**256n,Ze=class Ze{constructor(t,r,n,a){ut(this,"ex");ut(this,"ey");ut(this,"ez");ut(this,"et");const l=Bs;this.ex=Ct(t,0n,l),this.ey=Ct(r,0n,l),this.ez=Ct(n,1n,l),this.et=Ct(a,0n,l),Object.freeze(this)}static fromAffine(t){return new Ze(t.x,t.y,1n,K(t.x*t.y))}static fromBytes(t,r=!1){const n=Ds,a=Fs(Mt(t,ur)),l=t[31];a[31]=l&-129;const d=la(a);Ct(d,0n,r?Bs:Ee);const f=K(d*d),m=K(f-1n),h=K(n*f+1n);let{isValid:y,value:x}=oc(m,h);y||Pe("bad point: y not sqrt");const N=(x&1n)===1n,_=(l&128)!==0;return!r&&x===0n&&_&&Pe("bad point: x==0, isLastByteOdd"),_!==N&&(x=K(-x)),new Ze(x,d,1n,K(x*d))}assertValidity(){const t=Rs,r=Ds,n=this;if(n.is0())throw new Error("bad point: ZERO");const{ex:a,ey:l,ez:d,et:c}=n,f=K(a*a),m=K(l*l),h=K(d*d),y=K(h*h),x=K(f*t),N=K(h*K(x+m)),_=K(y+K(r*K(f*m)));if(N!==_)throw new Error("bad point: equation left != right (1)");const S=K(a*l),p=K(d*c);if(S!==p)throw new Error("bad point: equation left != right (2)");return this}equals(t){const{ex:r,ey:n,ez:a}=this,{ex:l,ey:d,ez:c}=ca(t),f=K(r*c),m=K(l*a),h=K(n*c),y=K(d*a);return f===m&&h===y}is0(){return this.equals(Lt)}negate(){return new Ze(K(-this.ex),this.ey,this.ez,K(-this.et))}double(){const{ex:t,ey:r,ez:n}=this,a=Rs,l=K(t*t),d=K(r*r),c=K(2n*K(n*n)),f=K(a*l),m=t+r,h=K(K(m*m)-l-d),y=f+d,x=y-c,N=f-d,_=K(h*x),S=K(y*N),p=K(h*N),w=K(x*y);return new Ze(_,S,w,p)}add(t){const{ex:r,ey:n,ez:a,et:l}=this,{ex:d,ey:c,ez:f,et:m}=ca(t),h=Rs,y=Ds,x=K(r*d),N=K(n*c),_=K(l*y*m),S=K(a*f),p=K((r+n)*(d+c)-x-N),w=K(S-_),E=K(S+_),C=K(N-h*x),A=K(p*w),T=K(E*C),M=K(p*C),I=K(w*E);return new Ze(A,T,I,M)}multiply(t,r=!0){if(!r&&(t===0n||this.is0()))return Lt;if(Ct(t,1n,Kr),t===1n)return this;if(this.equals(Bt))return hc(t).p;let n=Lt,a=Bt;for(let l=this;t>0n;l=l.double(),t>>=1n)t&1n?n=n.add(l):r&&(a=a.add(l));return n}toAffine(){const{ex:t,ey:r,ez:n}=this;if(this.equals(Lt))return{x:0n,y:1n};const a=oa(n,Ee);return K(n*a)!==1n&&Pe("invalid inverse"),{x:K(t*a),y:K(r*a)}}toBytes(){const{x:t,y:r}=this.assertValidity().toAffine(),n=ac(r);return n[31]|=t&1n?128:0,n}toHex(){return Ps(this.toBytes())}clearCofactor(){return this.multiply(Hr(Xo),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Kr/2n,!1).double();return Kr%2n&&(t=t.add(this)),t.is0()}static fromHex(t,r){return Ze.fromBytes(na(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}toRawBytes(){return this.toBytes()}};ut(Ze,"BASE"),ut(Ze,"ZERO");let Tt=Ze;const Bt=new Tt(Zn,Xn,1n,K(Zn*Xn)),Lt=new Tt(0n,1n,1n,0n);Tt.BASE=Bt,Tt.ZERO=Lt;const ac=e=>Ms(ra(Ct(e,0n,Bs),ea)).reverse(),la=e=>Hr("0x"+Ps(Fs(Mt(e)).reverse())),qe=(e,t)=>{let r=e;for(;t-- >0n;)r*=r,r%=Ee;return r},ic=e=>{const r=e*e%Ee*e%Ee,n=qe(r,2n)*r%Ee,a=qe(n,1n)*e%Ee,l=qe(a,5n)*a%Ee,d=qe(l,10n)*l%Ee,c=qe(d,20n)*d%Ee,f=qe(c,40n)*c%Ee,m=qe(f,80n)*f%Ee,h=qe(m,80n)*f%Ee,y=qe(h,10n)*l%Ee;return{pow_p_5_8:qe(y,2n)*e%Ee,b2:r}},da=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,oc=(e,t)=>{const r=K(t*t*t),n=K(r*r*t),a=ic(e*n).pow_p_5_8;let l=K(e*r*a);const d=K(t*l*l),c=l,f=K(l*da),m=d===e,h=d===K(-e),y=d===K(-e*da);return m&&(l=c),(h||y)&&(l=f),(K(l)&1n)===1n&&(l=K(-l)),{isValid:m||h,value:l}},cc=e=>nc(la(e)),lc=(...e)=>$s.sha512Async(...e),dc=e=>{const t=e.slice(0,ur);t[0]&=248,t[31]&=127,t[31]|=64;const r=e.slice(ur,ea),n=cc(t),a=Bt.multiply(n),l=a.toBytes();return{head:t,prefix:r,scalar:n,point:a,pointBytes:l}},uc=e=>lc(na(e,ur)).then(dc),Ls=e=>uc(e).then(t=>t.pointBytes),$s={sha512Async:async(...e)=>{const t=rc(),r=ia(...e);return Vr(await t.digest("SHA-512",r.buffer))},sha512Sync:void 0,bytesToHex:Ps,hexToBytes:Ms,concatBytes:ia,mod:K,invert:oa,randomBytes:sc},zr=8,ua=Math.ceil(256/zr)+1,Us=2**(zr-1),fc=()=>{const e=[];let t=Bt,r=t;for(let n=0;n<ua;n++){r=t,e.push(r);for(let a=1;a<Us;a++)r=r.add(t),e.push(r);t=r.double()}return e};let fa;const ha=(e,t)=>{const r=t.negate();return e?r:t},hc=e=>{const t=fa||(fa=fc());let r=Lt,n=Bt;const a=2**zr,l=a,d=Hr(a-1),c=Hr(zr);for(let f=0;f<ua;f++){let m=Number(e&d);e>>=c,m>Us&&(m-=l,e+=1n);const h=f*Us,y=h,x=h+Math.abs(m)-1,N=f%2!==0,_=m<0;m===0?n=n.add(ha(N,t[y])):r=r.add(ha(_,t[x]))}return{p:r,f:n}};/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function mc(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Ks(e,...t){if(!mc(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function ma(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function pc(e,t){Ks(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Vs(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Hs(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function gc(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function pa(e){return typeof e=="string"&&(e=gc(e)),Ks(e),e}class yc{}function xc(e){const t=n=>e().update(pa(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function bc(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const a=BigInt(32),l=BigInt(4294967295),d=Number(r>>a&l),c=Number(r&l),f=n?4:0,m=n?0:4;e.setUint32(t+f,d,n),e.setUint32(t+m,c,n)}class vc extends yc{constructor(t,r,n,a){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=a,this.buffer=new Uint8Array(t),this.view=Hs(this.buffer)}update(t){ma(this),t=pa(t),Ks(t);const{view:r,buffer:n,blockLen:a}=this,l=t.length;for(let d=0;d<l;){const c=Math.min(a-this.pos,l-d);if(c===a){const f=Hs(t);for(;a<=l-d;d+=a)this.process(f,d);continue}n.set(t.subarray(d,d+c),this.pos),this.pos+=c,d+=c,this.pos===a&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){ma(this),pc(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:a,isLE:l}=this;let{pos:d}=this;r[d++]=128,Vs(this.buffer.subarray(d)),this.padOffset>a-d&&(this.process(n,0),d=0);for(let y=d;y<a;y++)r[y]=0;bc(n,a-8,BigInt(this.length*8),l),this.process(n,0);const c=Hs(t),f=this.outputLen;if(f%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const m=f/4,h=this.get();if(m>h.length)throw new Error("_sha2: outputLen bigger than state");for(let y=0;y<m;y++)c.setUint32(4*y,h[y],l)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:a,finished:l,destroyed:d,pos:c}=this;return t.destroyed=d,t.finished=l,t.length=a,t.pos=c,a%r&&t.buffer.set(n),t}clone(){return this._cloneInto()}}const Se=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Gr=BigInt(2**32-1),ga=BigInt(32);function wc(e,t=!1){return t?{h:Number(e&Gr),l:Number(e>>ga&Gr)}:{h:Number(e>>ga&Gr)|0,l:Number(e&Gr)|0}}function Ec(e,t=!1){const r=e.length;let n=new Uint32Array(r),a=new Uint32Array(r);for(let l=0;l<r;l++){const{h:d,l:c}=wc(e[l],t);[n[l],a[l]]=[d,c]}return[n,a]}const ya=(e,t,r)=>e>>>r,xa=(e,t,r)=>e<<32-r|t>>>r,$t=(e,t,r)=>e>>>r|t<<32-r,Ut=(e,t,r)=>e<<32-r|t>>>r,qr=(e,t,r)=>e<<64-r|t>>>r-32,Wr=(e,t,r)=>e>>>r-32|t<<64-r;function at(e,t,r,n){const a=(t>>>0)+(n>>>0);return{h:e+r+(a/2**32|0)|0,l:a|0}}const Sc=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Nc=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,jc=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),_c=(e,t,r,n,a)=>t+r+n+a+(e/2**32|0)|0,Ac=(e,t,r,n,a)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(a>>>0),Cc=(e,t,r,n,a,l)=>t+r+n+a+l+(e/2**32|0)|0,ba=Ec(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Tc=ba[0],kc=ba[1],gt=new Uint32Array(80),yt=new Uint32Array(80);class Ic extends vc{constructor(t=64){super(128,t,16,!1),this.Ah=Se[0]|0,this.Al=Se[1]|0,this.Bh=Se[2]|0,this.Bl=Se[3]|0,this.Ch=Se[4]|0,this.Cl=Se[5]|0,this.Dh=Se[6]|0,this.Dl=Se[7]|0,this.Eh=Se[8]|0,this.El=Se[9]|0,this.Fh=Se[10]|0,this.Fl=Se[11]|0,this.Gh=Se[12]|0,this.Gl=Se[13]|0,this.Hh=Se[14]|0,this.Hl=Se[15]|0}get(){const{Ah:t,Al:r,Bh:n,Bl:a,Ch:l,Cl:d,Dh:c,Dl:f,Eh:m,El:h,Fh:y,Fl:x,Gh:N,Gl:_,Hh:S,Hl:p}=this;return[t,r,n,a,l,d,c,f,m,h,y,x,N,_,S,p]}set(t,r,n,a,l,d,c,f,m,h,y,x,N,_,S,p){this.Ah=t|0,this.Al=r|0,this.Bh=n|0,this.Bl=a|0,this.Ch=l|0,this.Cl=d|0,this.Dh=c|0,this.Dl=f|0,this.Eh=m|0,this.El=h|0,this.Fh=y|0,this.Fl=x|0,this.Gh=N|0,this.Gl=_|0,this.Hh=S|0,this.Hl=p|0}process(t,r){for(let C=0;C<16;C++,r+=4)gt[C]=t.getUint32(r),yt[C]=t.getUint32(r+=4);for(let C=16;C<80;C++){const A=gt[C-15]|0,T=yt[C-15]|0,M=$t(A,T,1)^$t(A,T,8)^ya(A,T,7),I=Ut(A,T,1)^Ut(A,T,8)^xa(A,T,7),O=gt[C-2]|0,R=yt[C-2]|0,$=$t(O,R,19)^qr(O,R,61)^ya(O,R,6),F=Ut(O,R,19)^Wr(O,R,61)^xa(O,R,6),H=jc(I,F,yt[C-7],yt[C-16]),V=_c(H,M,$,gt[C-7],gt[C-16]);gt[C]=V|0,yt[C]=H|0}let{Ah:n,Al:a,Bh:l,Bl:d,Ch:c,Cl:f,Dh:m,Dl:h,Eh:y,El:x,Fh:N,Fl:_,Gh:S,Gl:p,Hh:w,Hl:E}=this;for(let C=0;C<80;C++){const A=$t(y,x,14)^$t(y,x,18)^qr(y,x,41),T=Ut(y,x,14)^Ut(y,x,18)^Wr(y,x,41),M=y&N^~y&S,I=x&_^~x&p,O=Ac(E,T,I,kc[C],yt[C]),R=Cc(O,w,A,M,Tc[C],gt[C]),$=O|0,F=$t(n,a,28)^qr(n,a,34)^qr(n,a,39),H=Ut(n,a,28)^Wr(n,a,34)^Wr(n,a,39),V=n&l^n&c^l&c,z=a&d^a&f^d&f;w=S|0,E=p|0,S=N|0,p=_|0,N=y|0,_=x|0,{h:y,l:x}=at(m|0,h|0,R|0,$|0),m=c|0,h=f|0,c=l|0,f=d|0,l=n|0,d=a|0;const L=Sc($,H,z);n=Nc(L,R,F,V),a=L|0}({h:n,l:a}=at(this.Ah|0,this.Al|0,n|0,a|0)),{h:l,l:d}=at(this.Bh|0,this.Bl|0,l|0,d|0),{h:c,l:f}=at(this.Ch|0,this.Cl|0,c|0,f|0),{h:m,l:h}=at(this.Dh|0,this.Dl|0,m|0,h|0),{h:y,l:x}=at(this.Eh|0,this.El|0,y|0,x|0),{h:N,l:_}=at(this.Fh|0,this.Fl|0,N|0,_|0),{h:S,l:p}=at(this.Gh|0,this.Gl|0,S|0,p|0),{h:w,l:E}=at(this.Hh|0,this.Hl|0,w|0,E|0),this.set(n,a,l,d,c,f,m,h,y,x,N,_,S,p,w,E)}roundClean(){Vs(gt,yt)}destroy(){Vs(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Oc=xc(()=>new Ic);var zs={},Yr={};Yr.byteLength=Fc,Yr.toByteArray=Mc,Yr.fromByteArray=$c;for(var We=[],Me=[],Rc=typeof Uint8Array<"u"?Uint8Array:Array,Gs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Kt=0,Dc=Gs.length;Kt<Dc;++Kt)We[Kt]=Gs[Kt],Me[Gs.charCodeAt(Kt)]=Kt;Me[45]=62,Me[95]=63;function va(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function Fc(e){var t=va(e),r=t[0],n=t[1];return(r+n)*3/4-n}function Pc(e,t,r){return(t+r)*3/4-r}function Mc(e){var t,r=va(e),n=r[0],a=r[1],l=new Rc(Pc(e,n,a)),d=0,c=a>0?n-4:n,f;for(f=0;f<c;f+=4)t=Me[e.charCodeAt(f)]<<18|Me[e.charCodeAt(f+1)]<<12|Me[e.charCodeAt(f+2)]<<6|Me[e.charCodeAt(f+3)],l[d++]=t>>16&255,l[d++]=t>>8&255,l[d++]=t&255;return a===2&&(t=Me[e.charCodeAt(f)]<<2|Me[e.charCodeAt(f+1)]>>4,l[d++]=t&255),a===1&&(t=Me[e.charCodeAt(f)]<<10|Me[e.charCodeAt(f+1)]<<4|Me[e.charCodeAt(f+2)]>>2,l[d++]=t>>8&255,l[d++]=t&255),l}function Bc(e){return We[e>>18&63]+We[e>>12&63]+We[e>>6&63]+We[e&63]}function Lc(e,t,r){for(var n,a=[],l=t;l<r;l+=3)n=(e[l]<<16&16711680)+(e[l+1]<<8&65280)+(e[l+2]&255),a.push(Bc(n));return a.join("")}function $c(e){for(var t,r=e.length,n=r%3,a=[],l=16383,d=0,c=r-n;d<c;d+=l)a.push(Lc(e,d,d+l>c?c:d+l));return n===1?(t=e[r-1],a.push(We[t>>2]+We[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],a.push(We[t>>10]+We[t>>4&63]+We[t<<2&63]+"=")),a.join("")}var qs={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */qs.read=function(e,t,r,n,a){var l,d,c=a*8-n-1,f=(1<<c)-1,m=f>>1,h=-7,y=r?a-1:0,x=r?-1:1,N=e[t+y];for(y+=x,l=N&(1<<-h)-1,N>>=-h,h+=c;h>0;l=l*256+e[t+y],y+=x,h-=8);for(d=l&(1<<-h)-1,l>>=-h,h+=n;h>0;d=d*256+e[t+y],y+=x,h-=8);if(l===0)l=1-m;else{if(l===f)return d?NaN:(N?-1:1)*(1/0);d=d+Math.pow(2,n),l=l-m}return(N?-1:1)*d*Math.pow(2,l-n)},qs.write=function(e,t,r,n,a,l){var d,c,f,m=l*8-a-1,h=(1<<m)-1,y=h>>1,x=a===23?Math.pow(2,-24)-Math.pow(2,-77):0,N=n?0:l-1,_=n?1:-1,S=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(c=isNaN(t)?1:0,d=h):(d=Math.floor(Math.log(t)/Math.LN2),t*(f=Math.pow(2,-d))<1&&(d--,f*=2),d+y>=1?t+=x/f:t+=x*Math.pow(2,1-y),t*f>=2&&(d++,f/=2),d+y>=h?(c=0,d=h):d+y>=1?(c=(t*f-1)*Math.pow(2,a),d=d+y):(c=t*Math.pow(2,y-1)*Math.pow(2,a),d=0));a>=8;e[r+N]=c&255,N+=_,c/=256,a-=8);for(d=d<<a|c,m+=a;m>0;e[r+N]=d&255,N+=_,d/=256,m-=8);e[r+N-_]|=S*128};/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <https://feross.org>
 * @license  MIT
 */(function(e){const t=Yr,r=qs,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=c,e.SlowBuffer=E,e.INSPECT_MAX_BYTES=50;const a=2147483647;e.kMaxLength=a,c.TYPED_ARRAY_SUPPORT=l(),!c.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function l(){try{const u=new Uint8Array(1),i={foo:function(){return 42}};return Object.setPrototypeOf(i,Uint8Array.prototype),Object.setPrototypeOf(u,i),u.foo()===42}catch{return!1}}Object.defineProperty(c.prototype,"parent",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.buffer}}),Object.defineProperty(c.prototype,"offset",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.byteOffset}});function d(u){if(u>a)throw new RangeError('The value "'+u+'" is invalid for option "size"');const i=new Uint8Array(u);return Object.setPrototypeOf(i,c.prototype),i}function c(u,i,o){if(typeof u=="number"){if(typeof i=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return y(u)}return f(u,i,o)}c.poolSize=8192;function f(u,i,o){if(typeof u=="string")return x(u,i);if(ArrayBuffer.isView(u))return _(u);if(u==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof u);if(Ce(u,ArrayBuffer)||u&&Ce(u.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ce(u,SharedArrayBuffer)||u&&Ce(u.buffer,SharedArrayBuffer)))return S(u,i,o);if(typeof u=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const g=u.valueOf&&u.valueOf();if(g!=null&&g!==u)return c.from(g,i,o);const j=p(u);if(j)return j;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof u[Symbol.toPrimitive]=="function")return c.from(u[Symbol.toPrimitive]("string"),i,o);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof u)}c.from=function(u,i,o){return f(u,i,o)},Object.setPrototypeOf(c.prototype,Uint8Array.prototype),Object.setPrototypeOf(c,Uint8Array);function m(u){if(typeof u!="number")throw new TypeError('"size" argument must be of type number');if(u<0)throw new RangeError('The value "'+u+'" is invalid for option "size"')}function h(u,i,o){return m(u),u<=0?d(u):i!==void 0?typeof o=="string"?d(u).fill(i,o):d(u).fill(i):d(u)}c.alloc=function(u,i,o){return h(u,i,o)};function y(u){return m(u),d(u<0?0:w(u)|0)}c.allocUnsafe=function(u){return y(u)},c.allocUnsafeSlow=function(u){return y(u)};function x(u,i){if((typeof i!="string"||i==="")&&(i="utf8"),!c.isEncoding(i))throw new TypeError("Unknown encoding: "+i);const o=C(u,i)|0;let g=d(o);const j=g.write(u,i);return j!==o&&(g=g.slice(0,j)),g}function N(u){const i=u.length<0?0:w(u.length)|0,o=d(i);for(let g=0;g<i;g+=1)o[g]=u[g]&255;return o}function _(u){if(Ce(u,Uint8Array)){const i=new Uint8Array(u);return S(i.buffer,i.byteOffset,i.byteLength)}return N(u)}function S(u,i,o){if(i<0||u.byteLength<i)throw new RangeError('"offset" is outside of buffer bounds');if(u.byteLength<i+(o||0))throw new RangeError('"length" is outside of buffer bounds');let g;return i===void 0&&o===void 0?g=new Uint8Array(u):o===void 0?g=new Uint8Array(u,i):g=new Uint8Array(u,i,o),Object.setPrototypeOf(g,c.prototype),g}function p(u){if(c.isBuffer(u)){const i=w(u.length)|0,o=d(i);return o.length===0||u.copy(o,0,0,i),o}if(u.length!==void 0)return typeof u.length!="number"||xr(u.length)?d(0):N(u);if(u.type==="Buffer"&&Array.isArray(u.data))return N(u.data)}function w(u){if(u>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return u|0}function E(u){return+u!=u&&(u=0),c.alloc(+u)}c.isBuffer=function(i){return i!=null&&i._isBuffer===!0&&i!==c.prototype},c.compare=function(i,o){if(Ce(i,Uint8Array)&&(i=c.from(i,i.offset,i.byteLength)),Ce(o,Uint8Array)&&(o=c.from(o,o.offset,o.byteLength)),!c.isBuffer(i)||!c.isBuffer(o))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(i===o)return 0;let g=i.length,j=o.length;for(let k=0,D=Math.min(g,j);k<D;++k)if(i[k]!==o[k]){g=i[k],j=o[k];break}return g<j?-1:j<g?1:0},c.isEncoding=function(i){switch(String(i).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},c.concat=function(i,o){if(!Array.isArray(i))throw new TypeError('"list" argument must be an Array of Buffers');if(i.length===0)return c.alloc(0);let g;if(o===void 0)for(o=0,g=0;g<i.length;++g)o+=i[g].length;const j=c.allocUnsafe(o);let k=0;for(g=0;g<i.length;++g){let D=i[g];if(Ce(D,Uint8Array))k+D.length>j.length?(c.isBuffer(D)||(D=c.from(D)),D.copy(j,k)):Uint8Array.prototype.set.call(j,D,k);else if(c.isBuffer(D))D.copy(j,k);else throw new TypeError('"list" argument must be an Array of Buffers');k+=D.length}return j};function C(u,i){if(c.isBuffer(u))return u.length;if(ArrayBuffer.isView(u)||Ce(u,ArrayBuffer))return u.byteLength;if(typeof u!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof u);const o=u.length,g=arguments.length>2&&arguments[2]===!0;if(!g&&o===0)return 0;let j=!1;for(;;)switch(i){case"ascii":case"latin1":case"binary":return o;case"utf8":case"utf-8":return B(u).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return o*2;case"hex":return o>>>1;case"base64":return tt(u).length;default:if(j)return g?-1:B(u).length;i=(""+i).toLowerCase(),j=!0}}c.byteLength=C;function A(u,i,o){let g=!1;if((i===void 0||i<0)&&(i=0),i>this.length||((o===void 0||o>this.length)&&(o=this.length),o<=0)||(o>>>=0,i>>>=0,o<=i))return"";for(u||(u="utf8");;)switch(u){case"hex":return Ue(this,i,o);case"utf8":case"utf-8":return z(this,i,o);case"ascii":return Y(this,i,o);case"latin1":case"binary":return ge(this,i,o);case"base64":return V(this,i,o);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ze(this,i,o);default:if(g)throw new TypeError("Unknown encoding: "+u);u=(u+"").toLowerCase(),g=!0}}c.prototype._isBuffer=!0;function T(u,i,o){const g=u[i];u[i]=u[o],u[o]=g}c.prototype.swap16=function(){const i=this.length;if(i%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let o=0;o<i;o+=2)T(this,o,o+1);return this},c.prototype.swap32=function(){const i=this.length;if(i%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let o=0;o<i;o+=4)T(this,o,o+3),T(this,o+1,o+2);return this},c.prototype.swap64=function(){const i=this.length;if(i%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let o=0;o<i;o+=8)T(this,o,o+7),T(this,o+1,o+6),T(this,o+2,o+5),T(this,o+3,o+4);return this},c.prototype.toString=function(){const i=this.length;return i===0?"":arguments.length===0?z(this,0,i):A.apply(this,arguments)},c.prototype.toLocaleString=c.prototype.toString,c.prototype.equals=function(i){if(!c.isBuffer(i))throw new TypeError("Argument must be a Buffer");return this===i?!0:c.compare(this,i)===0},c.prototype.inspect=function(){let i="";const o=e.INSPECT_MAX_BYTES;return i=this.toString("hex",0,o).replace(/(.{2})/g,"$1 ").trim(),this.length>o&&(i+=" ... "),"<Buffer "+i+">"},n&&(c.prototype[n]=c.prototype.inspect),c.prototype.compare=function(i,o,g,j,k){if(Ce(i,Uint8Array)&&(i=c.from(i,i.offset,i.byteLength)),!c.isBuffer(i))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof i);if(o===void 0&&(o=0),g===void 0&&(g=i?i.length:0),j===void 0&&(j=0),k===void 0&&(k=this.length),o<0||g>i.length||j<0||k>this.length)throw new RangeError("out of range index");if(j>=k&&o>=g)return 0;if(j>=k)return-1;if(o>=g)return 1;if(o>>>=0,g>>>=0,j>>>=0,k>>>=0,this===i)return 0;let D=k-j,W=g-o;const le=Math.min(D,W),oe=this.slice(j,k),de=i.slice(o,g);for(let te=0;te<le;++te)if(oe[te]!==de[te]){D=oe[te],W=de[te];break}return D<W?-1:W<D?1:0};function M(u,i,o,g,j){if(u.length===0)return-1;if(typeof o=="string"?(g=o,o=0):o>2147483647?o=2147483647:o<-2147483648&&(o=-2147483648),o=+o,xr(o)&&(o=j?0:u.length-1),o<0&&(o=u.length+o),o>=u.length){if(j)return-1;o=u.length-1}else if(o<0)if(j)o=0;else return-1;if(typeof i=="string"&&(i=c.from(i,g)),c.isBuffer(i))return i.length===0?-1:I(u,i,o,g,j);if(typeof i=="number")return i=i&255,typeof Uint8Array.prototype.indexOf=="function"?j?Uint8Array.prototype.indexOf.call(u,i,o):Uint8Array.prototype.lastIndexOf.call(u,i,o):I(u,[i],o,g,j);throw new TypeError("val must be string, number or Buffer")}function I(u,i,o,g,j){let k=1,D=u.length,W=i.length;if(g!==void 0&&(g=String(g).toLowerCase(),g==="ucs2"||g==="ucs-2"||g==="utf16le"||g==="utf-16le")){if(u.length<2||i.length<2)return-1;k=2,D/=2,W/=2,o/=2}function le(de,te){return k===1?de[te]:de.readUInt16BE(te*k)}let oe;if(j){let de=-1;for(oe=o;oe<D;oe++)if(le(u,oe)===le(i,de===-1?0:oe-de)){if(de===-1&&(de=oe),oe-de+1===W)return de*k}else de!==-1&&(oe-=oe-de),de=-1}else for(o+W>D&&(o=D-W),oe=o;oe>=0;oe--){let de=!0;for(let te=0;te<W;te++)if(le(u,oe+te)!==le(i,te)){de=!1;break}if(de)return oe}return-1}c.prototype.includes=function(i,o,g){return this.indexOf(i,o,g)!==-1},c.prototype.indexOf=function(i,o,g){return M(this,i,o,g,!0)},c.prototype.lastIndexOf=function(i,o,g){return M(this,i,o,g,!1)};function O(u,i,o,g){o=Number(o)||0;const j=u.length-o;g?(g=Number(g),g>j&&(g=j)):g=j;const k=i.length;g>k/2&&(g=k/2);let D;for(D=0;D<g;++D){const W=parseInt(i.substr(D*2,2),16);if(xr(W))return D;u[o+D]=W}return D}function R(u,i,o,g){return Jt(B(i,u.length-o),u,o,g)}function $(u,i,o,g){return Jt(Z(i),u,o,g)}function F(u,i,o,g){return Jt(tt(i),u,o,g)}function H(u,i,o,g){return Jt(ve(i,u.length-o),u,o,g)}c.prototype.write=function(i,o,g,j){if(o===void 0)j="utf8",g=this.length,o=0;else if(g===void 0&&typeof o=="string")j=o,g=this.length,o=0;else if(isFinite(o))o=o>>>0,isFinite(g)?(g=g>>>0,j===void 0&&(j="utf8")):(j=g,g=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const k=this.length-o;if((g===void 0||g>k)&&(g=k),i.length>0&&(g<0||o<0)||o>this.length)throw new RangeError("Attempt to write outside buffer bounds");j||(j="utf8");let D=!1;for(;;)switch(j){case"hex":return O(this,i,o,g);case"utf8":case"utf-8":return R(this,i,o,g);case"ascii":case"latin1":case"binary":return $(this,i,o,g);case"base64":return F(this,i,o,g);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return H(this,i,o,g);default:if(D)throw new TypeError("Unknown encoding: "+j);j=(""+j).toLowerCase(),D=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function V(u,i,o){return i===0&&o===u.length?t.fromByteArray(u):t.fromByteArray(u.slice(i,o))}function z(u,i,o){o=Math.min(u.length,o);const g=[];let j=i;for(;j<o;){const k=u[j];let D=null,W=k>239?4:k>223?3:k>191?2:1;if(j+W<=o){let le,oe,de,te;switch(W){case 1:k<128&&(D=k);break;case 2:le=u[j+1],(le&192)===128&&(te=(k&31)<<6|le&63,te>127&&(D=te));break;case 3:le=u[j+1],oe=u[j+2],(le&192)===128&&(oe&192)===128&&(te=(k&15)<<12|(le&63)<<6|oe&63,te>2047&&(te<55296||te>57343)&&(D=te));break;case 4:le=u[j+1],oe=u[j+2],de=u[j+3],(le&192)===128&&(oe&192)===128&&(de&192)===128&&(te=(k&15)<<18|(le&63)<<12|(oe&63)<<6|de&63,te>65535&&te<1114112&&(D=te))}}D===null?(D=65533,W=1):D>65535&&(D-=65536,g.push(D>>>10&1023|55296),D=56320|D&1023),g.push(D),j+=W}return Q(g)}const L=4096;function Q(u){const i=u.length;if(i<=L)return String.fromCharCode.apply(String,u);let o="",g=0;for(;g<i;)o+=String.fromCharCode.apply(String,u.slice(g,g+=L));return o}function Y(u,i,o){let g="";o=Math.min(u.length,o);for(let j=i;j<o;++j)g+=String.fromCharCode(u[j]&127);return g}function ge(u,i,o){let g="";o=Math.min(u.length,o);for(let j=i;j<o;++j)g+=String.fromCharCode(u[j]);return g}function Ue(u,i,o){const g=u.length;(!i||i<0)&&(i=0),(!o||o<0||o>g)&&(o=g);let j="";for(let k=i;k<o;++k)j+=on[u[k]];return j}function ze(u,i,o){const g=u.slice(i,o);let j="";for(let k=0;k<g.length-1;k+=2)j+=String.fromCharCode(g[k]+g[k+1]*256);return j}c.prototype.slice=function(i,o){const g=this.length;i=~~i,o=o===void 0?g:~~o,i<0?(i+=g,i<0&&(i=0)):i>g&&(i=g),o<0?(o+=g,o<0&&(o=0)):o>g&&(o=g),o<i&&(o=i);const j=this.subarray(i,o);return Object.setPrototypeOf(j,c.prototype),j};function ae(u,i,o){if(u%1!==0||u<0)throw new RangeError("offset is not uint");if(u+i>o)throw new RangeError("Trying to access beyond buffer length")}c.prototype.readUintLE=c.prototype.readUIntLE=function(i,o,g){i=i>>>0,o=o>>>0,g||ae(i,o,this.length);let j=this[i],k=1,D=0;for(;++D<o&&(k*=256);)j+=this[i+D]*k;return j},c.prototype.readUintBE=c.prototype.readUIntBE=function(i,o,g){i=i>>>0,o=o>>>0,g||ae(i,o,this.length);let j=this[i+--o],k=1;for(;o>0&&(k*=256);)j+=this[i+--o]*k;return j},c.prototype.readUint8=c.prototype.readUInt8=function(i,o){return i=i>>>0,o||ae(i,1,this.length),this[i]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(i,o){return i=i>>>0,o||ae(i,2,this.length),this[i]|this[i+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(i,o){return i=i>>>0,o||ae(i,2,this.length),this[i]<<8|this[i+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(i,o){return i=i>>>0,o||ae(i,4,this.length),(this[i]|this[i+1]<<8|this[i+2]<<16)+this[i+3]*16777216},c.prototype.readUint32BE=c.prototype.readUInt32BE=function(i,o){return i=i>>>0,o||ae(i,4,this.length),this[i]*16777216+(this[i+1]<<16|this[i+2]<<8|this[i+3])},c.prototype.readBigUInt64LE=Ge(function(i){i=i>>>0,et(i,"offset");const o=this[i],g=this[i+7];(o===void 0||g===void 0)&&lt(i,this.length-8);const j=o+this[++i]*2**8+this[++i]*2**16+this[++i]*2**24,k=this[++i]+this[++i]*2**8+this[++i]*2**16+g*2**24;return BigInt(j)+(BigInt(k)<<BigInt(32))}),c.prototype.readBigUInt64BE=Ge(function(i){i=i>>>0,et(i,"offset");const o=this[i],g=this[i+7];(o===void 0||g===void 0)&&lt(i,this.length-8);const j=o*2**24+this[++i]*2**16+this[++i]*2**8+this[++i],k=this[++i]*2**24+this[++i]*2**16+this[++i]*2**8+g;return(BigInt(j)<<BigInt(32))+BigInt(k)}),c.prototype.readIntLE=function(i,o,g){i=i>>>0,o=o>>>0,g||ae(i,o,this.length);let j=this[i],k=1,D=0;for(;++D<o&&(k*=256);)j+=this[i+D]*k;return k*=128,j>=k&&(j-=Math.pow(2,8*o)),j},c.prototype.readIntBE=function(i,o,g){i=i>>>0,o=o>>>0,g||ae(i,o,this.length);let j=o,k=1,D=this[i+--j];for(;j>0&&(k*=256);)D+=this[i+--j]*k;return k*=128,D>=k&&(D-=Math.pow(2,8*o)),D},c.prototype.readInt8=function(i,o){return i=i>>>0,o||ae(i,1,this.length),this[i]&128?(255-this[i]+1)*-1:this[i]},c.prototype.readInt16LE=function(i,o){i=i>>>0,o||ae(i,2,this.length);const g=this[i]|this[i+1]<<8;return g&32768?g|4294901760:g},c.prototype.readInt16BE=function(i,o){i=i>>>0,o||ae(i,2,this.length);const g=this[i+1]|this[i]<<8;return g&32768?g|4294901760:g},c.prototype.readInt32LE=function(i,o){return i=i>>>0,o||ae(i,4,this.length),this[i]|this[i+1]<<8|this[i+2]<<16|this[i+3]<<24},c.prototype.readInt32BE=function(i,o){return i=i>>>0,o||ae(i,4,this.length),this[i]<<24|this[i+1]<<16|this[i+2]<<8|this[i+3]},c.prototype.readBigInt64LE=Ge(function(i){i=i>>>0,et(i,"offset");const o=this[i],g=this[i+7];(o===void 0||g===void 0)&&lt(i,this.length-8);const j=this[i+4]+this[i+5]*2**8+this[i+6]*2**16+(g<<24);return(BigInt(j)<<BigInt(32))+BigInt(o+this[++i]*2**8+this[++i]*2**16+this[++i]*2**24)}),c.prototype.readBigInt64BE=Ge(function(i){i=i>>>0,et(i,"offset");const o=this[i],g=this[i+7];(o===void 0||g===void 0)&&lt(i,this.length-8);const j=(o<<24)+this[++i]*2**16+this[++i]*2**8+this[++i];return(BigInt(j)<<BigInt(32))+BigInt(this[++i]*2**24+this[++i]*2**16+this[++i]*2**8+g)}),c.prototype.readFloatLE=function(i,o){return i=i>>>0,o||ae(i,4,this.length),r.read(this,i,!0,23,4)},c.prototype.readFloatBE=function(i,o){return i=i>>>0,o||ae(i,4,this.length),r.read(this,i,!1,23,4)},c.prototype.readDoubleLE=function(i,o){return i=i>>>0,o||ae(i,8,this.length),r.read(this,i,!0,52,8)},c.prototype.readDoubleBE=function(i,o){return i=i>>>0,o||ae(i,8,this.length),r.read(this,i,!1,52,8)};function ce(u,i,o,g,j,k){if(!c.isBuffer(u))throw new TypeError('"buffer" argument must be a Buffer instance');if(i>j||i<k)throw new RangeError('"value" argument is out of bounds');if(o+g>u.length)throw new RangeError("Index out of range")}c.prototype.writeUintLE=c.prototype.writeUIntLE=function(i,o,g,j){if(i=+i,o=o>>>0,g=g>>>0,!j){const W=Math.pow(2,8*g)-1;ce(this,i,o,g,W,0)}let k=1,D=0;for(this[o]=i&255;++D<g&&(k*=256);)this[o+D]=i/k&255;return o+g},c.prototype.writeUintBE=c.prototype.writeUIntBE=function(i,o,g,j){if(i=+i,o=o>>>0,g=g>>>0,!j){const W=Math.pow(2,8*g)-1;ce(this,i,o,g,W,0)}let k=g-1,D=1;for(this[o+k]=i&255;--k>=0&&(D*=256);)this[o+k]=i/D&255;return o+g},c.prototype.writeUint8=c.prototype.writeUInt8=function(i,o,g){return i=+i,o=o>>>0,g||ce(this,i,o,1,255,0),this[o]=i&255,o+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(i,o,g){return i=+i,o=o>>>0,g||ce(this,i,o,2,65535,0),this[o]=i&255,this[o+1]=i>>>8,o+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(i,o,g){return i=+i,o=o>>>0,g||ce(this,i,o,2,65535,0),this[o]=i>>>8,this[o+1]=i&255,o+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(i,o,g){return i=+i,o=o>>>0,g||ce(this,i,o,4,4294967295,0),this[o+3]=i>>>24,this[o+2]=i>>>16,this[o+1]=i>>>8,this[o]=i&255,o+4},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(i,o,g){return i=+i,o=o>>>0,g||ce(this,i,o,4,4294967295,0),this[o]=i>>>24,this[o+1]=i>>>16,this[o+2]=i>>>8,this[o+3]=i&255,o+4};function Et(u,i,o,g,j){Nt(i,g,j,u,o,7);let k=Number(i&BigInt(4294967295));u[o++]=k,k=k>>8,u[o++]=k,k=k>>8,u[o++]=k,k=k>>8,u[o++]=k;let D=Number(i>>BigInt(32)&BigInt(4294967295));return u[o++]=D,D=D>>8,u[o++]=D,D=D>>8,u[o++]=D,D=D>>8,u[o++]=D,o}function St(u,i,o,g,j){Nt(i,g,j,u,o,7);let k=Number(i&BigInt(4294967295));u[o+7]=k,k=k>>8,u[o+6]=k,k=k>>8,u[o+5]=k,k=k>>8,u[o+4]=k;let D=Number(i>>BigInt(32)&BigInt(4294967295));return u[o+3]=D,D=D>>8,u[o+2]=D,D=D>>8,u[o+1]=D,D=D>>8,u[o]=D,o+8}c.prototype.writeBigUInt64LE=Ge(function(i,o=0){return Et(this,i,o,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeBigUInt64BE=Ge(function(i,o=0){return St(this,i,o,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeIntLE=function(i,o,g,j){if(i=+i,o=o>>>0,!j){const le=Math.pow(2,8*g-1);ce(this,i,o,g,le-1,-le)}let k=0,D=1,W=0;for(this[o]=i&255;++k<g&&(D*=256);)i<0&&W===0&&this[o+k-1]!==0&&(W=1),this[o+k]=(i/D>>0)-W&255;return o+g},c.prototype.writeIntBE=function(i,o,g,j){if(i=+i,o=o>>>0,!j){const le=Math.pow(2,8*g-1);ce(this,i,o,g,le-1,-le)}let k=g-1,D=1,W=0;for(this[o+k]=i&255;--k>=0&&(D*=256);)i<0&&W===0&&this[o+k+1]!==0&&(W=1),this[o+k]=(i/D>>0)-W&255;return o+g},c.prototype.writeInt8=function(i,o,g){return i=+i,o=o>>>0,g||ce(this,i,o,1,127,-128),i<0&&(i=255+i+1),this[o]=i&255,o+1},c.prototype.writeInt16LE=function(i,o,g){return i=+i,o=o>>>0,g||ce(this,i,o,2,32767,-32768),this[o]=i&255,this[o+1]=i>>>8,o+2},c.prototype.writeInt16BE=function(i,o,g){return i=+i,o=o>>>0,g||ce(this,i,o,2,32767,-32768),this[o]=i>>>8,this[o+1]=i&255,o+2},c.prototype.writeInt32LE=function(i,o,g){return i=+i,o=o>>>0,g||ce(this,i,o,4,2147483647,-2147483648),this[o]=i&255,this[o+1]=i>>>8,this[o+2]=i>>>16,this[o+3]=i>>>24,o+4},c.prototype.writeInt32BE=function(i,o,g){return i=+i,o=o>>>0,g||ce(this,i,o,4,2147483647,-2147483648),i<0&&(i=4294967295+i+1),this[o]=i>>>24,this[o+1]=i>>>16,this[o+2]=i>>>8,this[o+3]=i&255,o+4},c.prototype.writeBigInt64LE=Ge(function(i,o=0){return Et(this,i,o,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),c.prototype.writeBigInt64BE=Ge(function(i,o=0){return St(this,i,o,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Ot(u,i,o,g,j,k){if(o+g>u.length)throw new RangeError("Index out of range");if(o<0)throw new RangeError("Index out of range")}function it(u,i,o,g,j){return i=+i,o=o>>>0,j||Ot(u,i,o,4),r.write(u,i,o,g,23,4),o+4}c.prototype.writeFloatLE=function(i,o,g){return it(this,i,o,!0,g)},c.prototype.writeFloatBE=function(i,o,g){return it(this,i,o,!1,g)};function ot(u,i,o,g,j){return i=+i,o=o>>>0,j||Ot(u,i,o,8),r.write(u,i,o,g,52,8),o+8}c.prototype.writeDoubleLE=function(i,o,g){return ot(this,i,o,!0,g)},c.prototype.writeDoubleBE=function(i,o,g){return ot(this,i,o,!1,g)},c.prototype.copy=function(i,o,g,j){if(!c.isBuffer(i))throw new TypeError("argument should be a Buffer");if(g||(g=0),!j&&j!==0&&(j=this.length),o>=i.length&&(o=i.length),o||(o=0),j>0&&j<g&&(j=g),j===g||i.length===0||this.length===0)return 0;if(o<0)throw new RangeError("targetStart out of bounds");if(g<0||g>=this.length)throw new RangeError("Index out of range");if(j<0)throw new RangeError("sourceEnd out of bounds");j>this.length&&(j=this.length),i.length-o<j-g&&(j=i.length-o+g);const k=j-g;return this===i&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(o,g,j):Uint8Array.prototype.set.call(i,this.subarray(g,j),o),k},c.prototype.fill=function(i,o,g,j){if(typeof i=="string"){if(typeof o=="string"?(j=o,o=0,g=this.length):typeof g=="string"&&(j=g,g=this.length),j!==void 0&&typeof j!="string")throw new TypeError("encoding must be a string");if(typeof j=="string"&&!c.isEncoding(j))throw new TypeError("Unknown encoding: "+j);if(i.length===1){const D=i.charCodeAt(0);(j==="utf8"&&D<128||j==="latin1")&&(i=D)}}else typeof i=="number"?i=i&255:typeof i=="boolean"&&(i=Number(i));if(o<0||this.length<o||this.length<g)throw new RangeError("Out of range index");if(g<=o)return this;o=o>>>0,g=g===void 0?this.length:g>>>0,i||(i=0);let k;if(typeof i=="number")for(k=o;k<g;++k)this[k]=i;else{const D=c.isBuffer(i)?i:c.from(i,j),W=D.length;if(W===0)throw new TypeError('The value "'+i+'" is invalid for argument "value"');for(k=0;k<g-o;++k)this[k+o]=D[k%W]}return this};const Ae={};function Xe(u,i,o){Ae[u]=class extends o{constructor(){super(),Object.defineProperty(this,"message",{value:i.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${u}]`,this.stack,delete this.name}get code(){return u}set code(j){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:j,writable:!0})}toString(){return`${this.name} [${u}]: ${this.message}`}}}Xe("ERR_BUFFER_OUT_OF_BOUNDS",function(u){return u?`${u} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Xe("ERR_INVALID_ARG_TYPE",function(u,i){return`The "${u}" argument must be of type number. Received type ${typeof i}`},TypeError),Xe("ERR_OUT_OF_RANGE",function(u,i,o){let g=`The value of "${u}" is out of range.`,j=o;return Number.isInteger(o)&&Math.abs(o)>2**32?j=ct(String(o)):typeof o=="bigint"&&(j=String(o),(o>BigInt(2)**BigInt(32)||o<-(BigInt(2)**BigInt(32)))&&(j=ct(j)),j+="n"),g+=` It must be ${i}. Received ${j}`,g},RangeError);function ct(u){let i="",o=u.length;const g=u[0]==="-"?1:0;for(;o>=g+4;o-=3)i=`_${u.slice(o-3,o)}${i}`;return`${u.slice(0,o)}${i}`}function yr(u,i,o){et(i,"offset"),(u[i]===void 0||u[i+o]===void 0)&&lt(i,u.length-(o+1))}function Nt(u,i,o,g,j,k){if(u>o||u<i){const D=typeof i=="bigint"?"n":"";let W;throw i===0||i===BigInt(0)?W=`>= 0${D} and < 2${D} ** ${(k+1)*8}${D}`:W=`>= -(2${D} ** ${(k+1)*8-1}${D}) and < 2 ** ${(k+1)*8-1}${D}`,new Ae.ERR_OUT_OF_RANGE("value",W,u)}yr(g,j,k)}function et(u,i){if(typeof u!="number")throw new Ae.ERR_INVALID_ARG_TYPE(i,"number",u)}function lt(u,i,o){throw Math.floor(u)!==u?(et(u,o),new Ae.ERR_OUT_OF_RANGE("offset","an integer",u)):i<0?new Ae.ERR_BUFFER_OUT_OF_BOUNDS:new Ae.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${i}`,u)}const jt=/[^+/0-9A-Za-z-_]/g;function dt(u){if(u=u.split("=")[0],u=u.trim().replace(jt,""),u.length<2)return"";for(;u.length%4!==0;)u=u+"=";return u}function B(u,i){i=i||1/0;let o;const g=u.length;let j=null;const k=[];for(let D=0;D<g;++D){if(o=u.charCodeAt(D),o>55295&&o<57344){if(!j){if(o>56319){(i-=3)>-1&&k.push(239,191,189);continue}else if(D+1===g){(i-=3)>-1&&k.push(239,191,189);continue}j=o;continue}if(o<56320){(i-=3)>-1&&k.push(239,191,189),j=o;continue}o=(j-55296<<10|o-56320)+65536}else j&&(i-=3)>-1&&k.push(239,191,189);if(j=null,o<128){if((i-=1)<0)break;k.push(o)}else if(o<2048){if((i-=2)<0)break;k.push(o>>6|192,o&63|128)}else if(o<65536){if((i-=3)<0)break;k.push(o>>12|224,o>>6&63|128,o&63|128)}else if(o<1114112){if((i-=4)<0)break;k.push(o>>18|240,o>>12&63|128,o>>6&63|128,o&63|128)}else throw new Error("Invalid code point")}return k}function Z(u){const i=[];for(let o=0;o<u.length;++o)i.push(u.charCodeAt(o)&255);return i}function ve(u,i){let o,g,j;const k=[];for(let D=0;D<u.length&&!((i-=2)<0);++D)o=u.charCodeAt(D),g=o>>8,j=o%256,k.push(j),k.push(g);return k}function tt(u){return t.toByteArray(dt(u))}function Jt(u,i,o,g){let j;for(j=0;j<g&&!(j+o>=i.length||j>=u.length);++j)i[j+o]=u[j];return j}function Ce(u,i){return u instanceof i||u!=null&&u.constructor!=null&&u.constructor.name!=null&&u.constructor.name===i.name}function xr(u){return u!==u}const on=function(){const u="0123456789abcdef",i=new Array(256);for(let o=0;o<16;++o){const g=o*16;for(let j=0;j<16;++j)i[g+j]=u[o]+u[j]}return i}();function Ge(u){return typeof BigInt>"u"?ns:u}function ns(){throw new Error("BigInt not supported")}})(zs);function Qr(e){return zs.Buffer.from(e,"base64")}function Uc(e){return zs.Buffer.from(e).toString("base64")}$s.sha512Sync=(...e)=>Oc($s.concatBytes(...e));const Kc={isAuthenticated:!1,systemPublicKey:null,systemKeyId:null,privateKey:null,publicKeyId:null,isLoading:!1,error:null},Ws=Pt("auth/initializeSystemKey",async(e,{rejectWithValue:t})=>{try{const r=await Os();if(console.log("initializeSystemKey thunk response:",r),r.success&&r.data&&r.data.private_key){const n=Qr(r.data.private_key),a=await Ls(n);return{systemPublicKey:btoa(String.fromCharCode(...a)),systemKeyId:"node-private-key",privateKey:n,isAuthenticated:!0}}else return{systemPublicKey:null,systemKeyId:null,privateKey:null,isAuthenticated:!1}}catch(r){return console.error("Failed to fetch node private key:",r),t(r instanceof Error?r.message:"Failed to fetch node private key")}}),Jr=Pt("auth/validatePrivateKey",async(e,{getState:t,rejectWithValue:r})=>{const n=t(),{systemPublicKey:a,systemKeyId:l}=n.auth;if(!a||!l)return r("System public key not available");try{console.log("🔑 Converting private key from base64...");const d=Qr(e);console.log("🔑 Generating public key from private key...");const c=await Ls(d),f=btoa(String.fromCharCode(...c)),m=f===a;return console.log("🔑 Key comparison:",{derived:f,system:a,matches:m}),m?{privateKey:d,publicKeyId:l,isAuthenticated:!0}:r("Private key does not match system public key")}catch(d){return console.error("Private key validation failed:",d),r(d instanceof Error?d.message:"Private key validation failed")}}),Ys=Pt("auth/refreshSystemKey",async(e,{rejectWithValue:t})=>{for(let a=1;a<=5;a++)try{const l=await Os();if(l.success&&l.data&&l.data.private_key){const d=Qr(l.data.private_key),c=await Ls(d);return{systemPublicKey:btoa(String.fromCharCode(...c)),systemKeyId:"node-private-key",privateKey:d,isAuthenticated:!0}}else if(a<5){const d=200*a;await new Promise(c=>setTimeout(c,d))}}catch(l){if(a===5)return t(l instanceof Error?l.message:"Failed to fetch node private key");{const d=200*a;await new Promise(c=>setTimeout(c,d))}}return t("Failed to fetch node private key after multiple attempts")}),Qs=Pt("auth/fetchNodePrivateKey",async(e,{rejectWithValue:t})=>{try{const r=await Os();return console.log("fetchNodePrivateKey thunk response:",r),r.success&&r.data&&r.data.private_key?{privateKey:Qr(r.data.private_key),publicKeyId:"node-private-key",isAuthenticated:!0}:t("Failed to fetch private key from backend")}catch(r){return console.error("Failed to fetch node private key:",r),t(r instanceof Error?r.message:"Failed to fetch node private key")}}),wa=Ns({name:"auth",initialState:Kc,reducers:{clearAuthentication:e=>{e.isAuthenticated=!1,e.privateKey=null,e.publicKeyId=null,e.error=null},setError:(e,t)=>{e.error=t.payload},clearError:e=>{e.error=null},updateSystemKey:(e,t)=>{e.systemPublicKey=t.payload.systemPublicKey,e.systemKeyId=t.payload.systemKeyId,e.error=null}},extraReducers:e=>{e.addCase(Ws.pending,t=>{t.isLoading=!0,t.error=null}).addCase(Ws.fulfilled,(t,r)=>{t.isLoading=!1,t.systemPublicKey=r.payload.systemPublicKey,t.systemKeyId=r.payload.systemKeyId,t.privateKey=r.payload.privateKey,t.isAuthenticated=r.payload.isAuthenticated,t.error=null}).addCase(Ws.rejected,(t,r)=>{t.isLoading=!1,t.error=r.payload}).addCase(Jr.pending,t=>{t.isLoading=!0,t.error=null}).addCase(Jr.fulfilled,(t,r)=>{t.isLoading=!1,t.isAuthenticated=r.payload.isAuthenticated,t.privateKey=r.payload.privateKey,t.publicKeyId=r.payload.publicKeyId,t.error=null}).addCase(Jr.rejected,(t,r)=>{t.isLoading=!1,t.isAuthenticated=!1,t.privateKey=null,t.publicKeyId=null,t.error=r.payload}).addCase(Ys.pending,t=>{t.isLoading=!0,t.error=null}).addCase(Ys.fulfilled,(t,r)=>{t.isLoading=!1,t.systemPublicKey=r.payload.systemPublicKey,t.systemKeyId=r.payload.systemKeyId,t.privateKey=r.payload.privateKey,t.isAuthenticated=r.payload.isAuthenticated,t.error=null}).addCase(Ys.rejected,(t,r)=>{t.isLoading=!1,t.systemPublicKey=null,t.systemKeyId=null,t.error=r.payload}).addCase(Qs.pending,t=>{t.isLoading=!0,t.error=null}).addCase(Qs.fulfilled,(t,r)=>{t.isLoading=!1,t.isAuthenticated=r.payload.isAuthenticated,t.privateKey=r.payload.privateKey,t.publicKeyId=r.payload.publicKeyId,t.error=null}).addCase(Qs.rejected,(t,r)=>{t.isLoading=!1,t.isAuthenticated=!1,t.privateKey=null,t.publicKeyId=null,t.error=r.payload})}}),{clearAuthentication:Vc,setError:Eu,clearError:Su,updateSystemKey:Nu}=wa.actions,Hc=wa.reducer,zc=3e5,Js=3,fr={FETCH_SCHEMAS:"schemas/fetchSchemas",APPROVE_SCHEMA:"schemas/approveSchema",BLOCK_SCHEMA:"schemas/blockSchema",UNLOAD_SCHEMA:"schemas/unloadSchema",LOAD_SCHEMA:"schemas/loadSchema"},hr={FETCH_FAILED:"Failed to fetch schemas from server",APPROVE_FAILED:"Failed to approve schema",BLOCK_FAILED:"Failed to block schema",UNLOAD_FAILED:"Failed to unload schema",LOAD_FAILED:"Failed to load schema"},Ye={AVAILABLE:"available",APPROVED:"approved",BLOCKED:"blocked",LOADING:"loading",ERROR:"error"};process.env.NODE_ENV,process.env.NODE_ENV,process.env.NODE_ENV,process.env.NODE_ENV;const Gc={MUTATION_WRAPPER_KEY:"value"},qc=200,Wc=300,Yc=[{id:"ingestion",label:"Ingestion",icon:"📥",group:"main"},{id:"file-upload",label:"File Upload",icon:"📄",group:"main"},{id:"llm-query",label:"AI Query",icon:"🤖",group:"main"},{id:"schemas",label:"Schemas",icon:"📊",group:"advanced"},{id:"query",label:"Query",icon:"🔍",group:"advanced"},{id:"mutation",label:"Mutation",icon:"✏️",group:"advanced"},{id:"native-index",label:"Native Index Query",icon:"🧭",group:"advanced"}],Zr={executeQuery:"Execute Query"},kt={schema:"Schema",schemaEmpty:"No schemas available",schemaHelp:"Select a schema to work with",operationType:"Operation Type",operationHelp:"Select the type of operation to perform"},Qc={loading:"Loading..."},Jc=[{value:"Insert",label:"Insert"},{value:"Update",label:"Update"},{value:"Delete",label:"Delete"}],Ea={Insert:"create",Create:"create",Update:"update",Delete:"delete"},Zc={};function Sa(e){if(!e||typeof e!="object")return null;const t=e.schema_type;if(t==="Single")return"Single";if(t==="Range")return"Range";if(t==="HashRange")return"HashRange";if(typeof t=="object"&&t!==null){if("HashRange"in t)return"HashRange";if("Range"in t)return"Range"}return null}function Zs(e){return!e||typeof e!="object"?!1:Sa(e)==="HashRange"}function Na(e){if(typeof e!="string")return null;const t=e.split(".");return t[t.length-1]||e}function Vt(e){return!e||typeof e!="object"?!1:Sa(e)==="Range"}function It(e){var r;if(!e||typeof e!="object")return null;const t=(r=e==null?void 0:e.key)==null?void 0:r.range_field;return typeof t=="string"&&t.trim()?Na(t):null}function ja(e){var r;if(!e||typeof e!="object")return null;const t=(r=e==null?void 0:e.key)==null?void 0:r.hash_field;return t&&typeof t=="string"&&t.trim()?Na(t):null}function Xc(e){if(!Vt(e))return{};const t=It(e);if(!Array.isArray(e.fields))throw new Error(`Expected schema.fields to be an array for range schema "${e.name}", got ${typeof e.fields}`);return e.fields.reduce((r,n)=>(n!==t&&(r[n]={}),r),{})}function el(e,t,r,n){const a=typeof t=="string"?Ea[t]||t.toLowerCase():"",l=a==="delete",d={type:"mutation",schema:e.name,mutation_type:a},c=It(e);if(l)d.fields_and_values={},d.key_value={hash:null,range:null},r&&r.trim()&&c&&(d.fields_and_values[c]=r.trim(),d.key_value.range=r.trim());else{const f={};r&&r.trim()&&c&&(f[c]=r.trim()),Object.entries(n).forEach(([m,h])=>{if(m!==c){const y=Gc.MUTATION_WRAPPER_KEY;typeof h=="string"||typeof h=="number"||typeof h=="boolean"?f[m]={[y]:h}:typeof h=="object"&&h!==null?f[m]=h:f[m]={[y]:h}}}),d.fields_and_values=f,d.key_value={hash:null,range:r&&r.trim()?r.trim():null}}return d}function _a(e){return Vt(e)?{isRangeSchema:!0,rangeKey:It(e),rangeFields:[],nonRangeKeyFields:Xc(e),totalFields:Array.isArray(e.fields)?e.fields.length:0}:null}function Aa(e){return typeof e=="string"?e.toLowerCase():typeof e=="object"&&e!==null?e.state?String(e.state).toLowerCase():String(e).toLowerCase():String(e||"").toLowerCase()}function tl(e){return e==null}function Ca(e){return Zs(e)?{isHashRangeSchema:!0,hashField:ja(e),rangeField:It(e),totalFields:Array.isArray(e.fields)?e.fields.length:0}:null}const Xr=Re.AVAILABLE,rl=new Set([Re.AVAILABLE,Re.APPROVED,Re.BLOCKED,"loading","error"]);function sl(e){if(!e||typeof e!="object")return null;const t=e.name;if(typeof t=="string"&&t.trim().length>0)return t;const r=e.schema;if(r&&typeof r=="object"){const n=r.name;if(typeof n=="string"&&n.trim().length>0)return n}return null}function nl(e){var r;return!e||typeof e!="object"?void 0:[e.state,e.schema_state,e.schemaState,e.status,e.current_state,(r=e.schema)==null?void 0:r.state].find(n=>n!==void 0)}class es{constructor(t){this.client=t||He({enableCache:!0,enableLogging:!0,enableMetrics:!0})}async getSchemas(){const t=await this.client.get(ee.LIST_SCHEMAS,{cacheable:!0,cacheKey:"schemas:all",cacheTtl:3e5});if(!t.success)return{...t,data:[]};const r=t.data;let n=[];return Array.isArray(r)?n=r:r&&typeof r=="object"?n=Object.values(r):(typeof console<"u"&&console.warn&&console.warn("[schemaClient.getSchemas] Unexpected response shape; normalizing to empty array",r),n=[]),{...t,data:n}}async getSchema(t){return this.client.get(ee.GET_SCHEMA(t),{validateSchema:{schemaName:t,operation:"read",requiresApproved:!1},cacheable:!0,cacheKey:`schema:${t}`,cacheTtl:3e5})}async getSchemasByState(t){var a;if(!Object.values(Re).includes(t))throw new Error(`Invalid schema state: ${t}. Must be one of: ${Object.values(Re).join(", ")}`);const r=await this.getSchemas();return!r.success||!r.data?{success:!1,error:"Failed to fetch schemas",status:r.status,data:{data:[],state:t}}:{success:!0,data:{data:r.data.filter(l=>l.state===t).map(l=>l.name),state:t},status:200,meta:{timestamp:Date.now(),cached:((a=r.meta)==null?void 0:a.cached)||!1}}}async getAllSchemasWithState(){var a;const t=await this.getSchemas();if(!t.success||!t.data)return{success:!1,error:"Failed to fetch schemas",status:t.status,data:{}};const r=Array.isArray(t.data)?t.data:[],n={};return r.forEach(l=>{const d=sl(l);if(!d){typeof console<"u"&&console.warn&&console.warn("[schemaClient.getAllSchemasWithState] Encountered schema entry without a name, skipping entry.");return}const c=nl(l),f=Aa(c);if(!c||f.length===0){typeof console<"u"&&console.warn&&console.warn(`[schemaClient.getAllSchemasWithState] Missing schema state for '${d}', defaulting to '${Xr}'.`),n[d]=Xr;return}if(!rl.has(f)){typeof console<"u"&&console.warn&&console.warn(`[schemaClient.getAllSchemasWithState] Unrecognized schema state '${String(c)}' for '${d}', defaulting to '${Xr}'.`),n[d]=Xr;return}n[d]=f}),{success:!0,data:n,status:t.status??200,meta:{...t.meta,timestamp:Date.now(),cached:((a=t.meta)==null?void 0:a.cached)??!1}}}async getSchemaStatus(){var a;const t=await this.getSchemas();if(!t.success||!t.data)return{success:!1,error:"Failed to fetch schemas",status:t.status,data:{available:0,approved:0,blocked:0,total:0}};const r=t.data;return{success:!0,data:{available:r.filter(l=>l.state===Re.AVAILABLE).length,approved:r.filter(l=>l.state===Re.APPROVED).length,blocked:r.filter(l=>l.state===Re.BLOCKED).length,total:r.length},status:200,meta:{timestamp:Date.now(),cached:((a=t.meta)==null?void 0:a.cached)||!1}}}async approveSchema(t){return this.client.post(ee.APPROVE_SCHEMA(t),{},{validateSchema:{schemaName:t,operation:"approve",requiresApproved:!1},timeout:1e4,retries:1})}async blockSchema(t){return this.client.post(ee.BLOCK_SCHEMA(t),{},{validateSchema:{schemaName:t,operation:"block",requiresApproved:!0},timeout:1e4,retries:1})}async getApprovedSchemas(){var t;try{const r=await this.getSchemas();return!r.success||!r.data?{success:!1,error:"Failed to fetch schemas",status:r.status,data:[]}:{success:!0,data:r.data.filter(a=>a.state===Re.APPROVED),status:200,meta:{timestamp:Date.now(),cached:(t=r.meta)==null?void 0:t.cached}}}catch(r){return{success:!1,error:r.message||"Failed to fetch approved schemas",status:r.status||500,data:[]}}}async loadSchema(t){return{success:!0,status:200}}async unloadSchema(t){return{success:!0,status:200}}async validateSchemaForOperation(t,r){try{const n=await this.getSchema(t);if(!n.success||!n.data)return{isValid:!1,error:`Schema '${t}' not found`};const a=n.data;return a.state!==Re.APPROVED?{isValid:!1,error:`Schema '${t}' is not approved. Current state: ${a.state}. Only approved schemas can be used for ${r}s.`,schema:a}:{isValid:!0,schema:a}}catch(n){return{isValid:!1,error:`Failed to validate schema '${t}': ${n.message}`}}}clearCache(){this.client.clearCache()}getCacheStats(){return this.client.getCacheStats()}getMetrics(){return this.client.getMetrics()}async getBackfillStatus(t){return this.client.get(`/api/backfill/${t}`,{cacheable:!1,timeout:5e3})}}const ue=new es;function al(e){return new es(e)}ue.getSchemasByState.bind(ue),ue.getAllSchemasWithState.bind(ue),ue.getSchemaStatus.bind(ue),ue.getSchema.bind(ue),ue.approveSchema.bind(ue),ue.blockSchema.bind(ue),ue.loadSchema.bind(ue),ue.unloadSchema.bind(ue),ue.getApprovedSchemas.bind(ue),ue.validateSchemaForOperation.bind(ue),ue.getBackfillStatus.bind(ue);const De={APPROVE:"approve",BLOCK:"block",UNLOAD:"unload",LOAD:"load"},Ta=(e,t)=>e?Date.now()-e<t:!1,il=(e,t,r=Date.now())=>({schemaName:e,error:t,timestamp:r}),ol=(e,t,r,n)=>({schemaName:e,newState:t,timestamp:Date.now(),updatedSchema:r,backfillHash:n}),ts=(e,t,r,n)=>Pt(e,async({schemaName:a,options:l={}},{getState:d,rejectWithValue:c})=>{var m;d().schemas.schemas[a];try{const h=await t(a);if(!h.success)throw new Error(h.error||n);const y=(m=h.data)==null?void 0:m.backfill_hash;return ol(a,r,void 0,y)}catch(h){return c(il(a,h instanceof Error?h.message:n))}}),Be=(e,t)=>({pending:(r,n)=>{const a=n.meta.arg.schemaName;r.loading.operations[a]=!0,delete r.errors.operations[a]},fulfilled:(r,n)=>{const{schemaName:a,newState:l,updatedSchema:d}=n.payload;r.loading.operations[a]=!1,r.schemas[a]&&(r.schemas[a].state=l,d&&Object.assign(r.schemas[a],d),r.schemas[a].lastOperation={type:t,timestamp:Date.now(),success:!0})},rejected:(r,n)=>{const{schemaName:a,error:l}=n.payload;r.loading.operations[a]=!1,r.errors.operations[a]=l,r.schemas[a]&&(r.schemas[a].lastOperation={type:t,timestamp:Date.now(),success:!1,error:l})}}),ka={schemas:{},loading:{fetch:!1,operations:{}},errors:{fetch:null,operations:{}},lastFetched:null,cache:{ttl:zc,version:"1.0.0",lastUpdated:null},activeSchema:null},Qe=Pt(fr.FETCH_SCHEMAS,async(e={},{getState:t,rejectWithValue:r})=>{const n=t(),{lastFetched:a,cache:l}=n.schemas;if(!e.forceRefresh&&Ta(a,l.ttl))return{schemas:Object.values(n.schemas.schemas),timestamp:a};const d=new es(He({baseUrl:Lr.BASE_URL,enableCache:!0,enableLogging:!0,enableMetrics:!0}));e.forceRefresh&&(console.log("🔄 Force refresh requested - clearing API client cache"),d.clearCache());let c=null;for(let m=1;m<=Js;m++)try{const h=await d.getSchemas();if(!h.success)throw new Error(`Failed to fetch schemas: ${h.error||"Unknown error"}`);console.log("📁 Raw schemas response:",h.data);const y=h.data||[];if(!Array.isArray(y))throw new Error(`Schemas response is not an array: ${typeof y}`);const x=y.map(_=>{if(!_.name)if(console.warn("⚠️ Schema missing name field:",_),_.schema&&_.schema.name)_.name=_.schema.name;else return console.error("❌ Schema has no name field and cannot be displayed:",_),null;let S=Ye.AVAILABLE;return _.state&&(typeof _.state=="string"?S=_.state.toLowerCase():typeof _.state=="object"&&_.state.state?S=String(_.state.state).toLowerCase():S=String(_.state).toLowerCase()),console.log("🟢 fetchSchemas: Using backend schema for",_.name,"with state:",S),{..._,state:S}}).filter(_=>_!==null);console.log("✅ Using backend schemas directly:",x.map(_=>({name:_.name,state:_.state})));const N=Date.now();return{schemas:x,timestamp:N}}catch(h){if(c=h instanceof Error?h:new Error("Unknown error"),m<Js){const x=typeof window<"u"&&window.__TEST_ENV__===!0?10:1e3*m;await new Promise(N=>setTimeout(N,x))}}const f=`Failed to fetch schemas after ${Js} attempts: ${(c==null?void 0:c.message)||"Unknown error"}`;return r(f)}),rs=()=>new es(He({baseUrl:Lr.BASE_URL,enableCache:!0,enableLogging:!0,enableMetrics:!0})),xt=ts(fr.APPROVE_SCHEMA,e=>rs().approveSchema(e),Ye.APPROVED,hr.APPROVE_FAILED),bt=ts(fr.BLOCK_SCHEMA,e=>rs().blockSchema(e),Ye.BLOCKED,hr.BLOCK_FAILED),Ht=ts(fr.UNLOAD_SCHEMA,e=>rs().unloadSchema(e),Ye.AVAILABLE,hr.UNLOAD_FAILED),zt=ts(fr.LOAD_SCHEMA,e=>rs().loadSchema(e),Ye.APPROVED,hr.LOAD_FAILED),Ia=Ns({name:"schemas",initialState:ka,reducers:{setActiveSchema:(e,t)=>{e.activeSchema=t.payload},updateSchemaStatus:(e,t)=>{const{schemaName:r,newState:n}=t.payload;e.schemas[r]&&(e.schemas[r].state=n,e.schemas[r].lastOperation={type:De.APPROVE,timestamp:Date.now(),success:!0})},setLoading:(e,t)=>{const{operation:r,isLoading:n,schemaName:a}=t.payload;r==="fetch"?e.loading.fetch=n:a&&(e.loading.operations[a]=n)},setError:(e,t)=>{const{operation:r,error:n,schemaName:a}=t.payload;r==="fetch"?e.errors.fetch=n:a&&(e.errors.operations[a]=n||"")},clearError:e=>{e.errors.fetch=null,e.errors.operations={}},clearOperationError:(e,t)=>{const r=t.payload;delete e.errors.operations[r]},invalidateCache:e=>{e.lastFetched=null,e.cache.lastUpdated=null},resetSchemas:e=>{Object.assign(e,ka)}},extraReducers:e=>{e.addCase(Qe.pending,t=>{t.loading.fetch=!0,t.errors.fetch=null}).addCase(Qe.fulfilled,(t,r)=>{t.loading.fetch=!1,t.errors.fetch=null;const n={};r.payload.schemas.forEach(a=>{n[a.name]=a}),t.schemas=n,t.lastFetched=r.payload.timestamp,t.cache.lastUpdated=r.payload.timestamp}).addCase(Qe.rejected,(t,r)=>{t.loading.fetch=!1,t.errors.fetch=r.payload||hr.FETCH_FAILED}).addCase(xt.pending,Be(xt,De.APPROVE).pending).addCase(xt.fulfilled,Be(xt,De.APPROVE).fulfilled).addCase(xt.rejected,Be(xt,De.APPROVE).rejected).addCase(bt.pending,Be(bt,De.BLOCK).pending).addCase(bt.fulfilled,Be(bt,De.BLOCK).fulfilled).addCase(bt.rejected,Be(bt,De.BLOCK).rejected).addCase(Ht.pending,Be(Ht,De.UNLOAD).pending).addCase(Ht.fulfilled,Be(Ht,De.UNLOAD).fulfilled).addCase(Ht.rejected,Be(Ht,De.UNLOAD).rejected).addCase(zt.pending,Be(zt,De.LOAD).pending).addCase(zt.fulfilled,Be(zt,De.LOAD).fulfilled).addCase(zt.rejected,Be(zt,De.LOAD).rejected)}}),cl=e=>e.schemas,Gt=e=>Object.values(e.schemas.schemas),ll=e=>e.schemas.schemas,mr=mt([Gt],e=>e.filter(t=>(typeof t.state=="string"?t.state.toLowerCase():typeof t.state=="object"&&t.state!==null&&t.state.state?String(t.state.state).toLowerCase():String(t.state||"").toLowerCase())===Ye.APPROVED)),dl=mt([Gt],e=>e.filter(t=>t.state===Ye.AVAILABLE));mt([Gt],e=>e.filter(t=>t.state===Ye.BLOCKED)),mt([mr],e=>e.filter(t=>{var r;return((r=t.rangeInfo)==null?void 0:r.isRangeSchema)===!0})),mt([dl],e=>e.filter(t=>{var r;return((r=t.rangeInfo)==null?void 0:r.isRangeSchema)===!0}));const Xs=e=>e.schemas.loading.fetch,Oa=e=>e.schemas.errors.fetch,ul=mt([cl],e=>({isValid:Ta(e.lastFetched,e.cache.ttl),lastFetched:e.lastFetched,ttl:e.cache.ttl}));mt([e=>e.schemas.activeSchema,ll],(e,t)=>e&&t[e]||null);const{setActiveSchema:_u,updateSchemaStatus:Au,setLoading:Cu,setError:Tu,clearError:ku,clearOperationError:Iu,invalidateCache:Ou,resetSchemas:Ru}=Ia.actions,fl=Ia.reducer,Ra={inputText:"",sessionId:null,isProcessing:!1,conversationLog:[],showResults:!1},Da=Ns({name:"aiQuery",initialState:Ra,reducers:{setInputText:(e,t)=>{e.inputText=t.payload},clearInputText:e=>{e.inputText=""},setSessionId:(e,t)=>{e.sessionId=t.payload},setIsProcessing:(e,t)=>{e.isProcessing=t.payload},addMessage:(e,t)=>{const r={...t.payload,timestamp:new Date().toISOString()};e.conversationLog.push(r)},clearConversation:e=>{e.conversationLog=[]},setShowResults:(e,t)=>{e.showResults=t.payload},startNewConversation:e=>{e.sessionId=null,e.conversationLog=[],e.inputText="",e.isProcessing=!1,e.showResults=!1},resetAIQueryState:()=>Ra}}),{setInputText:Fa,clearInputText:Du,setSessionId:Pa,setIsProcessing:Ma,addMessage:hl,clearConversation:Fu,setShowResults:ml,startNewConversation:pl,resetAIQueryState:Pu}=Da.actions,gl=Da.reducer,yl=e=>e.aiQuery.inputText,xl=e=>e.aiQuery.sessionId,bl=e=>e.aiQuery.isProcessing,vl=e=>e.aiQuery.conversationLog,wl=e=>e.aiQuery.showResults,El=e=>e.aiQuery.sessionId&&e.aiQuery.conversationLog.some(t=>t.type==="results"),Ba=xo({reducer:{auth:Hc,schemas:fl,aiQuery:gl},middleware:e=>e({serializableCheck:{ignoredActions:["auth/validatePrivateKey/fulfilled","auth/setPrivateKey","schemas/fetchSchemas/fulfilled","schemas/approveSchema/fulfilled","schemas/blockSchema/fulfilled","schemas/unloadSchema/fulfilled","schemas/loadSchema/fulfilled"],ignoredActionsPaths:["payload.privateKey","payload.schemas.definition"],ignoredPaths:["auth.privateKey","schemas.schemas.*.definition"]}}),devTools:!0});function Sl(){console.log("🔄 Schema client reset - will use new configuration on next request")}async function Nl(e){const t=Date.now(),r=e.includes("127.0.0.1")||e.includes("localhost"),n=r?`${e}/health`:`${e}/schema`;try{const a={method:r?"GET":"POST",headers:{"Content-Type":"application/json"},signal:AbortSignal.timeout(5e3)};r||(a.body=JSON.stringify({action:"status"}));const l=await fetch(n,a),d=Date.now()-t;return l.ok?{success:!0,status:(await l.json()).status||"online",responseTime:d}:{success:!1,error:`HTTP ${l.status}: ${l.statusText}`,responseTime:d}}catch(a){const l=Date.now()-t;return{success:!1,error:a.name==="TimeoutError"?"Connection timeout":a.message,responseTime:l}}}const qt={LOCAL:{id:"local",name:"Local",description:"Local development server",baseUrl:"http://127.0.0.1:9002/api"},DEV:{id:"dev",name:"Development (AWS)",description:"DEV Environment (us-west-2)",baseUrl:"https://cemkk2xzxd.execute-api.us-west-2.amazonaws.com"},PROD:{id:"prod",name:"Production (AWS)",description:"PROD Environment (us-east-1)",baseUrl:"https://owwjygkso3.execute-api.us-east-1.amazonaws.com"}},La="schemaServiceEnvironment",$a=v.createContext({environment:qt.LOCAL,setEnvironment:()=>{},getSchemaServiceBaseUrl:()=>""});function jl({children:e}){const[t,r]=v.useState(()=>{const l=localStorage.getItem(La);if(l){const d=Object.values(qt).find(c=>c.id===l);if(d)return d}return qt.LOCAL}),n=l=>{const d=Object.values(qt).find(c=>c.id===l);d&&(r(d),localStorage.setItem(La,l),Sl(),console.log(`Schema service environment changed to: ${d.name} (${d.baseUrl||"same origin"})`),console.log("🔄 Schema client has been reset - next request will use new endpoint"))},a=()=>t.baseUrl||"";return s.jsx($a.Provider,{value:{environment:t,setEnvironment:n,getSchemaServiceBaseUrl:a},children:e})}function _l(){const e=v.useContext($a);if(!e)throw new Error("useSchemaServiceConfig must be used within SchemaServiceConfigProvider");return e}const Al=({children:e,store:t})=>s.jsx(ft.Provider,{store:t||Ba,children:s.jsx(jl,{children:e})});function Cl({title:e,titleId:t,...r},n){return q.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},r),e?q.createElement("title",{id:t},e):null,q.createElement("path",{fillRule:"evenodd",d:"M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12Zm13.36-1.814a.75.75 0 1 0-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 0 0-1.06 1.06l2.25 2.25a.75.75 0 0 0 1.14-.094l3.75-5.25Z",clipRule:"evenodd"}))}const Tl=q.forwardRef(Cl);function kl({title:e,titleId:t,...r},n){return q.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},r),e?q.createElement("title",{id:t},e):null,q.createElement("path",{fillRule:"evenodd",d:"M12.53 16.28a.75.75 0 0 1-1.06 0l-7.5-7.5a.75.75 0 0 1 1.06-1.06L12 14.69l6.97-6.97a.75.75 0 1 1 1.06 1.06l-7.5 7.5Z",clipRule:"evenodd"}))}const Ua=q.forwardRef(kl);function Il({title:e,titleId:t,...r},n){return q.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},r),e?q.createElement("title",{id:t},e):null,q.createElement("path",{fillRule:"evenodd",d:"M16.28 11.47a.75.75 0 0 1 0 1.06l-7.5 7.5a.75.75 0 0 1-1.06-1.06L14.69 12 7.72 5.03a.75.75 0 0 1 1.06-1.06l7.5 7.5Z",clipRule:"evenodd"}))}const en=q.forwardRef(Il);function Ol({title:e,titleId:t,...r},n){return q.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},r),e?q.createElement("title",{id:t},e):null,q.createElement("path",{fillRule:"evenodd",d:"M16.5 4.478v.227a48.816 48.816 0 0 1 3.878.512.75.75 0 1 1-.256 1.478l-.209-.035-1.005 13.07a3 3 0 0 1-2.991 2.77H8.084a3 3 0 0 1-2.991-2.77L4.087 6.66l-.209.035a.75.75 0 0 1-.256-1.478A48.567 48.567 0 0 1 7.5 4.705v-.227c0-1.564 1.213-2.9 2.816-2.951a52.662 52.662 0 0 1 3.369 0c1.603.051 2.815 1.387 2.815 2.951Zm-6.136-1.452a51.196 51.196 0 0 1 3.273 0C14.39 3.05 15 3.684 15 4.478v.113a49.488 49.488 0 0 0-6 0v-.113c0-.794.609-1.428 1.364-1.452Zm-.355 5.945a.75.75 0 1 0-1.5.058l.347 9a.75.75 0 1 0 1.499-.058l-.346-9Zm5.48.058a.75.75 0 1 0-1.498-.058l-.347 9a.75.75 0 0 0 1.5.058l.345-9Z",clipRule:"evenodd"}))}const Ka=q.forwardRef(Ol);class Va{constructor(t){this.client=t||He({enableCache:!0,enableLogging:!0,enableMetrics:!0})}async getSystemPublicKey(){return this.client.get(ee.GET_SYSTEM_PUBLIC_KEY,{requiresAuth:!1,timeout:xe.QUICK,retries:be.CRITICAL,cacheable:!0,cacheTtl:pt.SYSTEM_PUBLIC_KEY,cacheKey:$r.SYSTEM_PUBLIC_KEY})}validatePublicKeyFormat(t){try{if(!t||typeof t!="string")return{isValid:!1,error:"Public key must be a non-empty string"};const r=t.trim();return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(r)?r.length!==44?{isValid:!1,format:"Unknown",length:Math.ceil(r.length/4*3),error:"Invalid key length: expected 44 base64 chars for Ed25519"}:{isValid:!0,format:"Ed25519",length:32}:{isValid:!1,error:"Invalid base64 encoding"}}catch(r){return{isValid:!1,error:`Validation error: ${r.message}`}}}async getSecurityStatus(){return this.client.get(ee.GET_SYSTEM_STATUS,{timeout:xe.QUICK,retries:be.STANDARD,cacheable:!0,cacheTtl:pt.SECURITY_STATUS,cacheKey:$r.SECURITY_STATUS})}validateSignedMessage(t){const r=[];if(!t||typeof t!="object")return r.push("Signed message must be an object"),{isValid:!1,errors:r};if((!t.payload||typeof t.payload!="string")&&r.push("Payload must be a non-empty base64 string"),(!t.signature||typeof t.signature!="string")&&r.push("Signature must be a non-empty base64 string"),(!t.public_key_id||typeof t.public_key_id!="string")&&r.push("Public key ID must be a non-empty string"),!t.timestamp||typeof t.timestamp!="number")r.push("Timestamp must be a Unix timestamp number");else{const a=Math.floor(Date.now()/1e3)-t.timestamp;a>300&&r.push("Message is too old (timestamp more than 5 minutes ago)"),a<-60&&r.push("Message timestamp is too far in the future")}return t.nonce&&typeof t.nonce!="string"&&r.push("Nonce must be a string if provided"),{isValid:r.length===0,errors:r}}getMetrics(){return this.client.getMetrics().filter(t=>t.url.includes("/security"))}clearCache(){this.client.clearCache()}}const vt=new Va;function Rl(e){return new Va(e)}vt.getSystemPublicKey.bind(vt),vt.validatePublicKeyFormat.bind(vt),vt.validateSignedMessage.bind(vt),vt.getSecurityStatus.bind(vt);class Dl{constructor(t){this.client=t||He({enableCache:!0,enableLogging:!0,enableMetrics:!0})}async getTransforms(){return this.client.get(ee.LIST_TRANSFORMS,{requiresAuth:!1,timeout:8e3,retries:2,cacheable:!0,cacheTtl:18e4,cacheKey:"transforms:all"})}async getQueue(){return this.client.get(ee.GET_TRANSFORM_QUEUE,{requiresAuth:!1,timeout:5e3,retries:3,cacheable:!1})}async addToQueue(t){if(!t||typeof t!="string")throw new Error("Transform ID is required and must be a string");return this.client.post(ee.ADD_TO_TRANSFORM_QUEUE(t),void 0,{timeout:1e4,retries:1,cacheable:!1})}async refreshQueue(){return this.getQueue()}async getAllBackfills(){return this.client.get(ee.GET_ALL_BACKFILLS,{requiresAuth:!1,timeout:5e3,retries:2,cacheable:!1})}async getActiveBackfills(){return this.client.get(ee.GET_ACTIVE_BACKFILLS,{requiresAuth:!1,timeout:5e3,retries:2,cacheable:!1})}async getBackfill(t){if(!t||typeof t!="string")throw new Error("Transform ID is required and must be a string");return this.client.get(ee.GET_BACKFILL(t),{requiresAuth:!1,timeout:5e3,retries:2,cacheable:!1})}async getStatistics(){return this.client.get(ee.GET_TRANSFORM_STATISTICS,{requiresAuth:!1,timeout:5e3,retries:2,cacheable:!1})}async getBackfillStatistics(){return this.client.get(ee.GET_BACKFILL_STATISTICS,{requiresAuth:!1,timeout:5e3,retries:2,cacheable:!1})}async getTransform(t){if(!t||typeof t!="string")throw new Error("Transform ID is required and must be a string");const r=await this.getTransforms();if(r.success&&r.data){const n=r.data[t]||null;return{...r,data:n}}return r}getMetrics(){return this.client.getMetrics().filter(t=>t.url.includes("/transforms")||t.url.includes("/queue"))}clearCache(){this.client.clearCache()}}const je=new Dl;je.getTransforms.bind(je),je.getQueue.bind(je),je.addToQueue.bind(je),je.refreshQueue.bind(je),je.getTransform.bind(je);class Ha{constructor(t){this.client=t||He({enableCache:!1,enableLogging:!0,enableMetrics:!0})}async executeMutation(t){return this.client.post(ee.EXECUTE_MUTATION,t,{validateSchema:!1,timeout:15e3,retries:0,cacheable:!1})}async executeMutationsBatch(t){return this.client.post(ee.EXECUTE_MUTATIONS_BATCH,t,{validateSchema:!1,timeout:3e4,retries:0,cacheable:!1})}async executeQuery(t){return this.client.post(ee.EXECUTE_QUERY,t,{validateSchema:{operation:"read",requiresApproved:!0},timeout:1e4,retries:2,cacheable:!0,cacheTtl:6e4})}async validateMutation(t){return Promise.resolve({success:!0,data:{isValid:!0},status:200})}async executeBatchMutations(t){return{success:!1,error:"Batch mutations not supported",status:501,data:[]}}async executeParameterizedQuery(t){return this.client.post(ee.EXECUTE_QUERY,t,{validateSchema:{schemaName:t.schema,operation:"read",requiresApproved:!0},timeout:15e3,retries:2,cacheable:!0,cacheTtl:12e4,cacheKey:`parameterized-query:${JSON.stringify(t)}`})}async getMutationHistory(t){return{success:!1,error:"Mutation history not supported",status:501,data:[]}}async validateSchemaForMutation(t){try{const r=await this.client.get(ee.GET_SCHEMA(t),{timeout:5e3,retries:1,cacheable:!0,cacheTtl:18e4});if(!r.success||!r.data)return{isValid:!1,schemaState:"unknown",canMutate:!1,canQuery:!1,error:`Schema '${t}' not found`};const n=r.data,a=n.state===Re.APPROVED;return{isValid:!0,schemaState:n.state,canMutate:a,canQuery:a,error:a?void 0:`Schema '${t}' is not approved (current state: ${n.state})`}}catch(r){return{isValid:!1,schemaState:"error",canMutate:!1,canQuery:!1,error:`Failed to validate schema '${t}': ${r.message}`}}}getMetrics(){return this.client.getMetrics().filter(t=>t.url.includes("/mutation")||t.url.includes("/query"))}clearCache(){this.client.clearCache()}}const tn=new Ha;function Fl(e){return new Ha(e)}class Pl{constructor(t){this.client=t||He({baseUrl:Lo.ROOT,enableCache:!1,enableLogging:!0,enableMetrics:!0})}async getStatus(){return this.client.get(ee.GET_STATUS,{requiresAuth:!1,timeout:xe.QUICK,retries:be.STANDARD,cacheable:!1})}async getConfig(){return this.client.get(ee.GET_INGESTION_CONFIG,{timeout:xe.QUICK,retries:be.STANDARD,cacheable:!1})}async saveConfig(t){return this.client.post(ee.GET_INGESTION_CONFIG,t,{timeout:xe.CONFIG,retries:be.LIMITED,cacheable:!1})}async validateData(t){return this.client.post(ee.VALIDATE_JSON,t,{requiresAuth:!1,timeout:xe.MUTATION,retries:be.STANDARD,cacheable:!1})}async processIngestion(t,r={}){const n={data:t,auto_execute:r.autoExecute??!0,trust_distance:r.trustDistance??0,pub_key:r.pubKey??"default"},a=this.validateIngestionRequest(n);if(!a.isValid)throw new Error(`Invalid ingestion request: ${a.errors.join(", ")}`);return this.client.post(ee.PROCESS_JSON,n,{timeout:xe.AI_PROCESSING,retries:be.LIMITED,cacheable:!1})}validateIngestionRequest(t){const r=[],n=[];return!t.data||typeof t.data!="object"?r.push("Data must be a valid object"):Object.keys(t.data).length===0&&r.push("Data cannot be empty"),typeof t.trust_distance!="number"||t.trust_distance<0?r.push("Trust distance must be a non-negative number"):t.trust_distance>10&&n.push("Trust distance is unusually high"),(!t.pub_key||t.pub_key.trim().length===0)&&r.push("Public key is required"),typeof t.auto_execute!="boolean"&&r.push("Auto execute must be a boolean value"),{isValid:r.length===0,errors:r,warnings:n}}createIngestionRequest(t,r={}){return{data:{...t},auto_execute:r.autoExecute??!0,trust_distance:r.trustDistance??0,pub_key:r.pubKey??"default"}}getMetrics(){return this.client.getMetrics().filter(t=>t.url.includes("/ingestion"))}async getProgress(t){return this.client.get(`/ingestion/progress/${t}`,{requiresAuth:!1,timeout:xe.QUICK,retries:be.STANDARD,cacheable:!1})}async getAllProgress(){return this.client.get("/ingestion/progress",{requiresAuth:!1,timeout:xe.QUICK,retries:be.STANDARD,cacheable:!1})}clearCache(){this.client.clearCache()}}const wt=new Pl,Wt=He({timeout:xe.AI_PROCESSING,retries:be.LIMITED}),za={async runQuery(e){return Wt.post("/llm-query/run",e)},async analyzeQuery(e){return Wt.post("/llm-query/analyze",e)},async executeQueryPlan(e){return Wt.post("/llm-query/execute",e)},async chat(e){return Wt.post("/llm-query/chat",e)},async analyzeFollowup(e){return Wt.post("/llm-query/analyze-followup",e)},async getBackfillStatus(e){return Wt.get(`/llm-query/backfill/${e}`)}};class Ml{constructor(t){this.client=t||He({enableCache:!0,enableLogging:!0})}async search(t){const r=`${ee.NATIVE_INDEX_SEARCH}?term=${encodeURIComponent(t)}`;return this.client.get(r,{timeout:8e3,retries:2,cacheable:!0,cacheTtl:6e4})}}const Bl=new Ml;async function Ll(){return(await Wo.get(ee.GET_INDEXING_STATUS,{cacheable:!1})).data}function $l(e=1e3){const[t,r]=q.useState(null),[n,a]=q.useState(null);return q.useEffect(()=>{let l=!0,d;const c=async()=>{try{const m=await Ll();l&&(r(m),a(null))}catch(m){l&&a(m instanceof Error?m:new Error("Failed to fetch indexing status"))}};c();const f=async()=>{if(await c(),l){const m=(t==null?void 0:t.state)==="Indexing"?e:e*5;d=setTimeout(f,m)}};return d=setTimeout(f,e),()=>{l=!1,d&&clearTimeout(d)}},[e,t==null?void 0:t.state]),{status:t,error:n}}function Ul(){const[e,t]=v.useState(!1),[r,n]=v.useState(!1),[a,l]=v.useState(null),[d,c]=v.useState(null),[f,m]=v.useState(null);v.useEffect(()=>{const w=E=>{console.log("🔵 StatusSection: Received ingestion-started event",E.detail),m(E.detail.progressId),c({progress_percentage:0,status_message:"Starting ingestion...",is_complete:!1}),console.log("🔵 StatusSection: Set initial ingestion progress")};return window.addEventListener("ingestion-started",w),console.log("🔵 StatusSection: Listening for ingestion-started events"),()=>window.removeEventListener("ingestion-started",w)},[]),v.useEffect(()=>{if(!f)return;let w=!0,E;const C=async()=>{try{const A=await wt.getProgress(f);w&&A.success&&A.data?(c(A.data),A.data.is_complete?m(null):E=setTimeout(C,200)):w&&(E=setTimeout(C,200))}catch(A){console.error("Error polling ingestion:",A),w&&(E=setTimeout(C,500))}};return C(),()=>{w=!1,E&&clearTimeout(E)}},[f]);const{status:h}=$l(1e3),y=async()=>{n(!0),l(null);try{const w=await he.resetDatabase(!0);w.success&&w.data?(l({type:"success",message:w.data.message}),setTimeout(()=>{window.location.reload()},2e3)):l({type:"error",message:w.error||"Reset failed"})}catch(w){l({type:"error",message:`Network error: ${w.message}`})}finally{n(!1),t(!1)}},x=()=>e?s.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:s.jsxs("div",{className:"bg-white rounded-lg p-6 max-w-md w-full mx-4",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[s.jsx(Ka,{className:"w-6 h-6 text-red-500"}),s.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:"Reset Database"})]}),s.jsxs("div",{className:"mb-6",children:[s.jsx("p",{className:"text-gray-700 mb-2",children:"This will permanently delete all data and restart the node:"}),s.jsxs("ul",{className:"list-disc list-inside text-sm text-gray-600 space-y-1",children:[s.jsx("li",{children:"All schemas will be removed"}),s.jsx("li",{children:"All stored data will be deleted"}),s.jsx("li",{children:"Network connections will be reset"}),s.jsx("li",{children:"This action cannot be undone"})]})]}),s.jsxs("div",{className:"flex gap-3 justify-end",children:[s.jsx("button",{onClick:()=>t(!1),className:"px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors",disabled:r,children:"Cancel"}),s.jsx("button",{onClick:y,disabled:r,className:"px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-md hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:r?"Resetting...":"Reset Database"})]})]})}):null,N=()=>{if(console.log("🟡 StatusSection getIngestionStatus:",{hasProgress:!!d,percentage:d==null?void 0:d.progress_percentage,isComplete:d==null?void 0:d.is_complete,results:d==null?void 0:d.results}),d&&!d.is_complete){const w=d.started_at?Math.floor((new Date-new Date(d.started_at))/1e3):0;return{state:"active",title:"Ingesting Data",detail:d.status_message,percentage:d.progress_percentage,metrics:w>0?[`${w}s elapsed`]:[],color:"blue"}}if(d!=null&&d.is_complete&&(d!=null&&d.results)){const w=d.started_at&&d.completed_at?Math.floor((new Date(d.completed_at)-new Date(d.started_at))/1e3):0;return{state:"completed",title:"Ingestion",detail:"Last ingestion completed",metrics:[`${d.results.mutations_executed||0} items ingested`,w>0?`${w}s duration`:null].filter(Boolean),color:"green"}}return{state:"idle",title:"Ingestion",detail:"No active ingestion",metrics:[],color:"gray"}},_=()=>(console.log("🟡 StatusSection getIndexingStatus:",{indexingState:h==null?void 0:h.state,totalOps:h==null?void 0:h.total_operations_processed}),(h==null?void 0:h.state)==="Indexing"?{state:"active",title:"Background Indexing",detail:"Actively processing index operations",metrics:[`${h.total_operations_processed.toLocaleString()} ops processed`,`${h.operations_per_second.toFixed(0)} ops/sec`],color:"indigo"}:(h==null?void 0:h.total_operations_processed)>0?{state:"completed",title:"Indexing",detail:"All operations indexed",metrics:[`${h.total_operations_processed.toLocaleString()} total operations`],color:"green"}:{state:"idle",title:"Indexing",detail:"No indexing activity",metrics:[],color:"gray"}),S=N(),p=_();return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-white rounded-lg shadow-sm p-4 mb-6",children:[s.jsxs("div",{className:"flex items-center justify-between mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Tl,{className:"w-5 h-5 text-green-500"}),s.jsx("h2",{className:"text-lg font-semibold text-gray-900",children:"System Status"})]}),s.jsxs("button",{onClick:()=>t(!0),className:"flex items-center gap-2 px-3 py-1.5 text-sm font-medium text-red-600 border border-red-200 rounded-md hover:bg-red-50 hover:border-red-300 transition-colors",disabled:r,children:[s.jsx(Ka,{className:"w-4 h-4"}),"Reset Database"]})]}),s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsxs("div",{className:`p-4 rounded-lg border-2 ${S.state==="active"?"border-blue-200 bg-blue-50":S.state==="completed"?"border-green-200 bg-green-50":"border-gray-200 bg-gray-50"}`,children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${S.state==="active"?"bg-blue-500 animate-pulse":S.state==="completed"?"bg-green-500":"bg-gray-400"}`}),s.jsx("h3",{className:`font-semibold ${S.state==="active"?"text-blue-900":S.state==="completed"?"text-green-900":"text-gray-700"}`,children:S.title})]}),s.jsx("span",{className:`text-xs font-medium px-2 py-1 rounded ${S.state==="active"?"bg-blue-100 text-blue-700":S.state==="completed"?"bg-green-100 text-green-700":"bg-gray-200 text-gray-600"}`,children:S.state==="active"?"Active":S.state==="completed"?"Complete":"Idle"})]}),s.jsx("p",{className:`text-sm ${S.state==="active"?"text-blue-700":S.state==="completed"?"text-green-700":"text-gray-500"}`,children:S.detail}),S.metrics&&S.metrics.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:S.metrics.map((w,E)=>s.jsx("span",{className:`text-xs font-medium px-2 py-1 rounded ${S.state==="active"?"bg-blue-100 text-blue-800":S.state==="completed"?"bg-green-100 text-green-800":"bg-gray-100 text-gray-600"}`,children:w},E))}),S.percentage!==void 0&&s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("span",{className:"text-xs font-medium text-blue-700",children:"Progress"}),s.jsxs("span",{className:"text-xs font-semibold text-blue-900",children:[S.percentage,"%"]})]}),s.jsx("div",{className:"w-full bg-blue-200 rounded-full h-2",children:s.jsx("div",{className:"bg-blue-600 h-2 rounded-full transition-all duration-300",style:{width:`${S.percentage}%`}})})]})]}),s.jsxs("div",{className:`p-4 rounded-lg border-2 ${p.state==="active"?"border-indigo-200 bg-indigo-50":p.state==="completed"?"border-green-200 bg-green-50":"border-gray-200 bg-gray-50"}`,children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:`w-2.5 h-2.5 rounded-full ${p.state==="active"?"bg-indigo-500 animate-pulse":p.state==="completed"?"bg-green-500":"bg-gray-400"}`}),s.jsx("h3",{className:`font-semibold ${p.state==="active"?"text-indigo-900":p.state==="completed"?"text-green-900":"text-gray-700"}`,children:p.title})]}),s.jsx("span",{className:`text-xs font-medium px-2 py-1 rounded ${p.state==="active"?"bg-indigo-100 text-indigo-700":p.state==="completed"?"bg-green-100 text-green-700":"bg-gray-200 text-gray-600"}`,children:p.state==="active"?"Active":p.state==="completed"?"Complete":"Idle"})]}),s.jsx("p",{className:`text-sm ${p.state==="active"?"text-indigo-700":p.state==="completed"?"text-green-700":"text-gray-500"}`,children:p.detail}),p.metrics&&p.metrics.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:p.metrics.map((w,E)=>s.jsx("span",{className:`text-xs font-medium px-2 py-1 rounded ${p.state==="active"?"bg-indigo-100 text-indigo-800":p.state==="completed"?"bg-green-100 text-green-800":"bg-gray-100 text-gray-600"}`,children:w},E))})]})]}),a&&s.jsx("div",{className:`mt-3 p-3 rounded-md text-sm ${a.type==="success"?"bg-green-50 text-green-800 border border-green-200":"bg-red-50 text-red-800 border border-red-200"}`,children:a.message})]}),s.jsx(x,{})]})}function Le(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Kl(e){const t=Yt(e);if(!Le(t))return!1;const r=Object.keys(t);if(r.length===0)return!1;for(let n=0;n<Math.min(3,r.length);n++){const a=t[r[n]];if(!Le(a))return!1;const l=Object.keys(a);if(l.length!==0)for(let d=0;d<Math.min(3,l.length);d++){const c=a[l[d]];if(!Le(c))return!1;Object.keys(c).length}}return!0}function Yt(e){return e&&Le(e)&&Object.prototype.hasOwnProperty.call(e,"data")?e.data:e}function Vl(e){const t=Yt(e)||{};if(!Le(t))return{hashes:0,ranges:0};const r=Object.keys(t).length;let n=0;for(const a of Object.keys(t)){const l=t[a];Le(l)&&(n+=Object.keys(l).length)}return{hashes:r,ranges:n}}function Hl(e){const t=Yt(e)||{};return Le(t)?Object.keys(t).sort(qa):[]}function Ga(e,t){const r=Yt(e)||{},n=Le(r)&&Le(r[t])?r[t]:{};return Object.keys(n).sort(qa)}function qa(e,t){const r=Wa(e),n=Wa(t);return!Number.isNaN(r)&&!Number.isNaN(n)?r-n:String(e).localeCompare(String(t))}function Wa(e){const t=Number(e);return Number.isFinite(t)?t:Number.NaN}function zl(e,t,r){const n=Yt(e)||{};if(!Le(n))return null;const a=n[t];if(!Le(a))return null;const l=a[r];return Le(l)?l:null}function Ya(e,t,r){return e.slice(t,Math.min(t+r,e.length))}const Gl=50;function Qa({isOpen:e,onClick:t,label:r}){return s.jsxs("button",{type:"button",className:"text-left w-full flex items-center justify-between px-3 py-2 hover:bg-gray-100 rounded",onClick:t,"aria-expanded":e,children:[s.jsx("span",{className:"font-mono text-sm text-gray-800 truncate",children:r}),s.jsx("span",{className:"ml-2 text-gray-500 text-xs",children:e?"▼":"▶"})]})}function ql({fields:e}){const t=v.useMemo(()=>Object.entries(e||{}),[e]);return t.length===0?s.jsx("div",{className:"text-xs text-gray-500 italic px-3 py-2",children:"No fields"}):s.jsx("div",{className:"px-3 py-2 overflow-x-auto",children:s.jsx("table",{className:"min-w-full border-separate border-spacing-y-1",children:s.jsx("tbody",{children:t.map(([r,n])=>s.jsxs("tr",{className:"bg-white",children:[s.jsx("td",{className:"align-top text-xs font-medium text-gray-700 pr-4 whitespace-nowrap",children:r}),s.jsx("td",{className:"align-top text-xs text-gray-700",children:s.jsx("pre",{className:"font-mono whitespace-pre-wrap break-words",children:Wl(n)})})]},r))})})})}function Wl(e){if(e===null)return"null";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}}function Yl({results:e,pageSize:t=Gl}){const r=v.useMemo(()=>Yt(e)||{},[e]),n=v.useMemo(()=>Vl(e),[e]),a=v.useMemo(()=>Hl(e),[e]),[l,d]=v.useState(()=>new Set),[c,f]=v.useState(()=>new Set),[m,h]=v.useState({start:0,count:t}),[y,x]=v.useState(()=>new Map),N=v.useCallback(w=>{d(E=>{const C=new Set(E);return C.has(w)?C.delete(w):C.add(w),C}),x(E=>{if(!l.has(w)){const C=Ga(r,w).length,A=new Map(E);return A.set(w,{start:0,count:Math.min(t,C)}),A}return E})},[r,l,t]),_=v.useCallback((w,E)=>{const C=w+"||"+E;f(A=>{const T=new Set(A);return T.has(C)?T.delete(C):T.add(C),T})},[]),S=v.useCallback(()=>{const w=Math.min(a.length,m.count+t);h(E=>({start:0,count:w}))},[a,m.count,t]),p=v.useMemo(()=>Ya(a,m.start,m.count),[a,m]);return s.jsxs("div",{className:"space-y-2",children:[s.jsxs("div",{className:"text-xs text-gray-600",children:[s.jsxs("span",{className:"mr-4",children:["Hashes: ",s.jsx("strong",{children:n.hashes})]}),s.jsxs("span",{children:["Ranges: ",s.jsx("strong",{children:n.ranges})]})]}),s.jsx("div",{className:"border rounded-md divide-y divide-gray-200 bg-gray-50",children:p.map(w=>s.jsxs("div",{className:"p-2",children:[s.jsx(Qa,{isOpen:l.has(w),onClick:()=>N(w),label:`hash: ${String(w)}`}),l.has(w)&&s.jsx(Ql,{data:r,hashKey:w,rangeOpen:c,onToggleRange:_,pageSize:t,rangeWindow:y.get(w),setRangeWindow:E=>x(C=>new Map(C).set(w,E))})]},w))}),m.count<a.length&&s.jsx("div",{className:"pt-2",children:s.jsxs("button",{type:"button",className:"text-xs px-3 py-1 rounded bg-gray-200 hover:bg-gray-300",onClick:S,children:["Show more hashes (",m.count,"/",a.length,")"]})})]})}function Ql({data:e,hashKey:t,rangeOpen:r,onToggleRange:n,pageSize:a,rangeWindow:l,setRangeWindow:d}){const c=v.useMemo(()=>Ga(e,t),[e,t]),f=l||{start:0,count:Math.min(a,c.length)},m=v.useMemo(()=>Ya(c,f.start,f.count),[c,f]),h=v.useCallback(()=>{const y=Math.min(c.length,f.count+a);d({start:0,count:y})},[c.length,f.count,a,d]);return s.jsxs("div",{className:"ml-4 mt-1 border-l pl-3",children:[m.map(y=>s.jsxs("div",{className:"py-1",children:[s.jsx(Qa,{isOpen:r.has(t+"||"+y),onClick:()=>n(t,y),label:`range: ${String(y)}`}),r.has(t+"||"+y)&&s.jsx("div",{className:"ml-4 mt-1",children:s.jsx(ql,{fields:zl(e,t,y)||{}})})]},y)),f.count<c.length&&s.jsx("div",{className:"pt-1",children:s.jsxs("button",{type:"button",className:"text-xs px-3 py-1 rounded bg-gray-200 hover:bg-gray-300",onClick:h,children:["Show more ranges (",f.count,"/",c.length,")"]})})]})}function Jl({results:e}){const t=e!=null,r=t&&(!!e.error||e.status&&e.status>=400),n=t&&e.data!==void 0,a=v.useMemo(()=>t&&!r&&Kl(n?e.data:e),[t,e,r,n]),[l,d]=v.useState(a);return t?s.jsxs("div",{className:"bg-white rounded-lg shadow-sm p-6 mt-6",children:[s.jsxs("h3",{className:"text-lg font-semibold mb-4 flex items-center",children:[s.jsx("span",{className:`mr-2 ${r?"text-red-600":"text-gray-900"}`,children:r?"Error":"Results"}),s.jsxs("span",{className:"text-xs font-normal text-gray-500",children:["(",typeof e=="string"?"Text":l?"Structured":"JSON",")"]}),e.status&&s.jsxs("span",{className:`ml-2 px-2 py-1 text-xs rounded-full ${e.status>=400?"bg-red-100 text-red-800":"bg-green-100 text-green-800"}`,children:["Status: ",e.status]}),!r&&typeof e!="string"&&s.jsx("div",{className:"ml-auto",children:s.jsx("button",{type:"button",className:"text-xs px-2 py-1 rounded border border-gray-300 hover:bg-gray-100",onClick:()=>d(c=>!c),children:l?"View JSON":"View Structured"})})]}),r&&s.jsx("div",{className:"mb-4 p-4 bg-red-50 border border-red-200 rounded-md",children:s.jsxs("div",{className:"flex",children:[s.jsx("div",{className:"flex-shrink-0",children:s.jsx("svg",{className:"h-5 w-5 text-red-400",viewBox:"0 0 20 20",fill:"currentColor",children:s.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"})})}),s.jsxs("div",{className:"ml-3",children:[s.jsx("h4",{className:"text-sm font-medium text-red-800",children:"Query Execution Failed"}),s.jsx("div",{className:"mt-2 text-sm text-red-700",children:s.jsx("p",{children:e.error||"An unknown error occurred"})})]})]})}),l&&!r&&typeof e!="string"?s.jsx("div",{className:"rounded-md p-2 bg-gray-50 border overflow-auto max-h-[500px]",children:s.jsx(Yl,{results:e})}):s.jsx("div",{className:`rounded-md p-4 overflow-auto max-h-[500px] ${r?"bg-red-50 border border-red-200":"bg-gray-50"}`,children:s.jsx("pre",{className:`font-mono text-sm whitespace-pre-wrap ${r?"text-red-700":"text-gray-700"}`,children:typeof e=="string"?e:JSON.stringify(n?e.data:e,null,2)})})]}):null}const $e={tab:{base:"px-4 py-2 text-sm font-medium transition-all duration-200",active:"text-blue-600 border-b-2 border-blue-600",inactive:"text-gray-500 hover:text-gray-700 hover:border-gray-300",disabled:"text-gray-300 cursor-not-allowed"},input:{base:"block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-1 transition-colors duration-200",error:"border-red-300 focus:ring-red-500 focus:border-red-500",success:"border-green-300 focus:ring-green-500 focus:border-green-500"},select:{base:"block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-blue-600 focus:border-blue-600 rounded-md transition-colors duration-200",disabled:"bg-gray-100 text-gray-500 cursor-not-allowed"}};function Zl({tabs:e=Yc,activeTab:t,onTabChange:r,className:n=""}){const a=(m,h)=>{r(m)},l=m=>{const h=t===m.id,y=m.disabled||!1;let x=$e.tab.base;return h?x+=` ${$e.tab.active}`:y?x+=` ${$e.tab.disabled}`:x+=` ${$e.tab.inactive}`,x},d=e.filter(m=>m.group==="main"),c=e.filter(m=>m.group==="advanced"),f=m=>{const h=m.disabled||!1;return s.jsxs("button",{className:l(m),onClick:()=>a(m.id,m.requiresAuth),disabled:h,"aria-current":t===m.id?"page":void 0,"aria-label":`${m.label} tab`,style:{transitionDuration:`${qc}ms`},children:[m.icon&&s.jsx("span",{className:"mr-2","aria-hidden":"true",children:m.icon}),s.jsx("span",{children:m.label})]},m.id)};return s.jsx("div",{className:`border-b border-gray-200 ${n}`,children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:"flex space-x-8",children:d.map(f)}),c.length>0&&s.jsx("div",{className:"mx-6 h-6 w-px bg-gray-300","aria-hidden":"true"}),c.length>0&&s.jsxs("div",{className:"flex items-center space-x-6",children:[s.jsx("span",{className:"text-xs text-gray-500 font-medium uppercase tracking-wider",children:"Advanced"}),s.jsx("div",{className:"flex space-x-6",children:c.map(f)})]})]})})}const Qt=()=>ft.useDispatch(),fe=ft.useSelector;function ss({node:e,depth:t=0,name:r=null}){const[n,a]=v.useState(t===0);if(!e)return s.jsx("span",{className:"text-gray-400 italic",children:"undefined"});if(e.type==="Primitive"){const l=e.value,d={String:"text-green-600",Number:"text-blue-600",Boolean:"text-purple-600",Null:"text-gray-500"}[l]||"text-gray-600";return s.jsxs("span",{className:"inline-flex items-center space-x-2",children:[s.jsx("span",{className:`font-mono text-sm ${d}`,children:l.toLowerCase()}),e.classifications&&e.classifications.length>0&&s.jsx("span",{className:"flex space-x-1",children:e.classifications.map(c=>s.jsx("span",{className:"px-1.5 py-0.5 text-xs bg-gray-200 text-gray-700 rounded-full font-sans",children:c},c))})]})}if(e.type==="Any")return s.jsx("span",{className:"font-mono text-sm text-orange-600",children:"any"});if(e.type==="Array")return s.jsxs("div",{className:"inline-flex items-start",children:[s.jsx("span",{className:"font-mono text-sm text-gray-700",children:"Array<"}),s.jsx(ss,{node:e.value,depth:t+1}),s.jsx("span",{className:"font-mono text-sm text-gray-700",children:">"})]});if(e.type==="Object"&&e.value){const l=Object.entries(e.value);return l.length===0?s.jsx("span",{className:"font-mono text-sm text-gray-500",children:"{}"}):s.jsxs("div",{className:"inline-block",children:[s.jsx("div",{className:"flex items-center",children:s.jsxs("button",{onClick:()=>a(!n),className:"flex items-center hover:bg-gray-100 rounded px-1 -ml-1",children:[n?s.jsx(Ua,{className:"h-3 w-3 text-gray-500"}):s.jsx(en,{className:"h-3 w-3 text-gray-500"}),s.jsxs("span",{className:"font-mono text-sm text-gray-700 ml-1",children:["{",!n&&`... ${l.length} fields`,!n&&"}"]})]})}),n&&s.jsxs("div",{className:"ml-4 border-l-2 border-gray-200 pl-3 mt-1",children:[l.map(([d,c],f)=>s.jsxs("div",{className:"py-1",children:[s.jsx("span",{className:"font-mono text-sm text-indigo-600",children:d}),s.jsx("span",{className:"font-mono text-sm text-gray-500",children:": "}),s.jsx(ss,{node:c,depth:t+1,name:d}),f<l.length-1&&s.jsx("span",{className:"text-gray-400",children:","})]},d)),s.jsx("div",{className:"font-mono text-sm text-gray-700",children:"}"})]})]})}return s.jsxs("span",{className:"font-mono text-sm text-red-500",children:["unknown (",JSON.stringify(e),")"]})}function Xl({topology:e,compact:t=!1}){return e?t?s.jsx("div",{className:"inline-flex items-center",children:s.jsx(ss,{node:e.root})}):s.jsxs("div",{className:"mt-2 p-2 bg-gray-50 rounded border border-gray-200",children:[s.jsx("div",{className:"text-xs font-medium text-gray-600 mb-1",children:"Type Structure:"}),s.jsx("div",{className:"pl-2",children:s.jsx(ss,{node:e.root})})]}):s.jsx("div",{className:"text-xs text-gray-400 italic",children:"No topology defined"})}function ed({onResult:e,onSchemaUpdated:t}){const r=Qt(),n=fe(Gt);fe(Xs),fe(Oa);const[a,l]=v.useState({});v.useEffect(()=>{console.log("🟢 SchemaTab: Fetching schemas on mount"),r(Qe({forceRefresh:!0}))},[r]);const d=p=>p.descriptive_name||p.name;console.log("🟢 SchemaTab: Current schemas from Redux:",n.map(p=>({name:p.name,state:p.state})));const c=async p=>{const w=a[p];if(l(E=>({...E,[p]:!E[p]})),!w){const E=n.find(C=>C.name===p);if(E&&(!E.fields||Object.keys(E.fields).length===0))try{(await ue.getSchema(p)).success&&(r(Qe({forceRefresh:!0})),t&&t())}catch(C){console.error(`Failed to fetch schema details for ${p}:`,C)}}},f=p=>{switch(p==null?void 0:p.toLowerCase()){case"approved":return"bg-green-100 text-green-800";case"available":return"bg-blue-100 text-blue-800";case"blocked":return"bg-red-100 text-red-800";default:return"bg-gray-100 text-gray-800"}},m=async p=>{var w,E;console.log("🟡 SchemaTab: Starting approveSchema for:",p);try{const C=await r(xt({schemaName:p}));if(console.log("🟡 SchemaTab: approveSchema result:",C),xt.fulfilled.match(C)){console.log("🟡 SchemaTab: approveSchema fulfilled, calling callbacks");const A=(w=C.payload)==null?void 0:w.backfillHash;if(console.log("🔄 Backfill hash:",A),console.log("🔄 Refetching schemas from backend after approval..."),await r(Qe({forceRefresh:!0})),console.log("✅ Refetch complete - backend state should be reflected"),e){const T=A?`Schema ${p} approved successfully. Backfill started with hash: ${A}`:`Schema ${p} approved successfully`;e({success:!0,message:T,backfillHash:A})}t&&t()}else{console.log("🔴 SchemaTab: approveSchema rejected:",C.payload);const A=typeof C.payload=="string"?C.payload:((E=C.payload)==null?void 0:E.error)||`Failed to approve schema: ${p}`;throw new Error(A)}}catch(C){if(console.error("🔴 SchemaTab: Failed to approve schema:",C),e){const A=C instanceof Error?C.message:String(C);e({error:`Failed to approve schema: ${A}`})}}},h=async p=>{var w;try{const E=await r(bt({schemaName:p}));if(bt.fulfilled.match(E))console.log("🟡 SchemaTab: blockSchema fulfilled, calling callbacks"),console.log("🔄 Refetching schemas from backend after blocking..."),await r(Qe({forceRefresh:!0})),console.log("✅ Refetch complete - backend state should be reflected"),e&&e({success:!0,message:`Schema ${p} blocked successfully`}),t&&t();else{const C=typeof E.payload=="string"?E.payload:((w=E.payload)==null?void 0:w.error)||`Failed to block schema: ${p}`;throw new Error(C)}}catch(E){if(console.error("Failed to block schema:",E),e){const C=E instanceof Error?E.message:String(E);e({error:`Failed to block schema: ${C}`})}}},y=p=>{const w=a[p.name],E=p.state||"Unknown",C=p.fields?_a(p):null,A=Ca(p);return s.jsxs("div",{className:"bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden transition-all duration-200 hover:shadow-md",children:[s.jsx("div",{className:"px-4 py-3 bg-gray-50 cursor-pointer select-none transition-colors duration-200 hover:bg-gray-100",onClick:()=>c(p.name),children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center space-x-2",children:[w?s.jsx(Ua,{className:"icon icon-sm text-gray-400 transition-transform duration-200"}):s.jsx(en,{className:"icon icon-sm text-gray-400 transition-transform duration-200"}),s.jsx("h3",{className:"font-medium text-gray-900",children:d(p)}),p.descriptive_name&&p.descriptive_name!==p.name&&s.jsxs("span",{className:"text-xs text-gray-500",children:["(",p.name,")"]}),s.jsx("span",{className:`px-2 py-1 text-xs font-medium rounded-full ${f(E)}`,children:E}),C&&s.jsx("span",{className:"px-2 py-1 text-xs font-medium rounded-full bg-purple-100 text-purple-800",children:"Range Schema"}),A&&s.jsx("span",{className:"px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800",children:"HashRange Schema"})]}),s.jsxs("div",{className:"flex items-center space-x-2",children:[E.toLowerCase()==="available"&&s.jsx("button",{className:"group inline-flex items-center px-2 py-1 text-xs font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500",onClick:T=>{console.log("🟠 Button clicked: Approve for schema:",p.name),T.stopPropagation(),m(p.name)},children:"Approve"}),E.toLowerCase()==="approved"&&s.jsx("button",{className:"group inline-flex items-center px-2 py-1 text-xs font-medium rounded-md text-white bg-red-600 hover:bg-red-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500",onClick:T=>{T.stopPropagation(),h(p.name)},children:"Block"}),E.toLowerCase()==="blocked"&&s.jsx("button",{className:"group inline-flex items-center px-2 py-1 text-xs font-medium rounded-md text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500",onClick:T=>{T.stopPropagation(),m(p.name)},children:"Re-approve"})]})]})}),w&&p.fields&&s.jsxs("div",{className:"p-4 border-t border-gray-200",children:[C&&s.jsxs("div",{className:"mb-4 p-3 bg-purple-50 rounded-md border border-purple-200",children:[s.jsx("h4",{className:"text-sm font-medium text-purple-900 mb-2",children:"Range Schema Information"}),s.jsxs("div",{className:"space-y-1 text-xs text-purple-800",children:[s.jsxs("p",{children:[s.jsx("strong",{children:"Range Key:"})," ",C.rangeKey]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Total Fields:"})," ",C.totalFields]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Range Fields:"})," ",C.rangeFields.length]}),s.jsx("p",{className:"text-purple-600",children:"This schema uses range-based storage for efficient querying and mutations."})]})]}),A&&s.jsxs("div",{className:"mb-4 p-3 bg-blue-50 rounded-md border border-blue-200",children:[s.jsx("h4",{className:"text-sm font-medium text-blue-900 mb-2",children:"HashRange Schema Information"}),s.jsxs("div",{className:"space-y-1 text-xs text-blue-800",children:[s.jsxs("p",{children:[s.jsx("strong",{children:"Hash Field:"})," ",A.hashField]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Range Field:"})," ",A.rangeField]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Total Fields:"})," ",A.totalFields]}),s.jsx("p",{className:"text-blue-600",children:"This schema uses hash-range-based storage for efficient querying and mutations with both hash and range keys."})]})]}),s.jsx("div",{className:"space-y-3",children:Array.isArray(p.fields)?p.fields.map(T=>{var I;const M=(I=p.field_topologies)==null?void 0:I[T];return s.jsx("div",{className:"p-3 bg-gray-50 rounded-md border border-gray-200",children:s.jsx("div",{className:"flex items-center justify-between",children:s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx("span",{className:"font-medium text-gray-900",children:T}),(C==null?void 0:C.rangeKey)===T&&s.jsx("span",{className:"px-2 py-0.5 text-xs font-medium rounded-full bg-purple-100 text-purple-800",children:"Range Key"}),(A==null?void 0:A.hashField)===T&&s.jsx("span",{className:"px-2 py-0.5 text-xs font-medium rounded-full bg-blue-100 text-blue-800",children:"Hash Key"}),(A==null?void 0:A.rangeField)===T&&s.jsx("span",{className:"px-2 py-0.5 text-xs font-medium rounded-full bg-purple-100 text-purple-800",children:"Range Key"})]}),M&&s.jsx(Xl,{topology:M})]})})},T)}):s.jsx("p",{className:"text-sm text-gray-500 italic",children:"No fields defined"})})]})]},p.name)},x=p=>typeof p=="string"?p.toLowerCase():typeof p=="object"&&p!==null?String(p).toLowerCase():String(p||"").toLowerCase(),N=n.filter(p=>x(p.state)==="available"),_=n.filter(p=>x(p.state)==="approved"),S=n.filter(p=>x(p.state)==="blocked");return s.jsxs("div",{className:"p-6 space-y-6",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-4",children:"Available Schemas"}),s.jsx("div",{className:"border rounded-lg bg-white shadow-sm",children:s.jsxs("details",{className:"group",children:[s.jsxs("summary",{className:"flex items-center justify-between p-4 cursor-pointer hover:bg-gray-50",children:[s.jsxs("span",{className:"font-medium text-gray-900",children:["Available Schemas (",N.length,")"]}),s.jsx(en,{className:"h-5 w-5 text-gray-400 group-open:rotate-90 transition-transform"})]}),s.jsx("div",{className:"border-t bg-gray-50",children:N.length===0?s.jsx("div",{className:"p-4 text-gray-500 text-center",children:"No available schemas"}):s.jsx("div",{className:"space-y-2 p-4",children:N.map(p=>{const w=p.fields?_a(p):null,E=Ca(p);return s.jsxs("div",{className:"flex items-center justify-between p-3 bg-white rounded border",children:[s.jsxs("div",{className:"flex items-center space-x-3",children:[s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx("h4",{className:"font-medium text-gray-900",children:d(p)}),p.descriptive_name&&p.descriptive_name!==p.name&&s.jsxs("span",{className:"text-xs text-gray-500",children:["(",p.name,")"]})]}),s.jsx("span",{className:`px-2 py-1 rounded-full text-xs font-medium ${f(p.state)}`,children:p.state}),w&&s.jsx("span",{className:"px-2 py-1 text-xs font-medium rounded-full bg-purple-100 text-purple-800",children:"Range Schema"}),E&&s.jsx("span",{className:"px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800",children:"HashRange Schema"})]}),s.jsx("div",{className:"flex space-x-2",children:s.jsx("button",{onClick:()=>m(p.name),className:"px-3 py-1 bg-green-500 text-white rounded text-sm hover:bg-green-600",children:"Approve"})})]},p.name)})})})]})})]}),s.jsxs("div",{className:"space-y-4",children:[s.jsx("h3",{className:"text-lg font-medium text-gray-900",children:"Approved Schemas"}),_.length>0?_.map(y):s.jsx("div",{className:"border rounded-lg p-8 bg-white shadow-sm text-center text-gray-500",children:"No approved schemas. Approve schemas from the available list above to see them here."})]}),S.length>0&&s.jsxs("div",{className:"space-y-4",children:[s.jsx("h3",{className:"text-lg font-medium text-gray-900",children:"Blocked Schemas"}),S.map(y)]})]})}function rn(){const e=Qt(),t=fe(Gt),r=fe(Xs),[n,a]=v.useState(""),[l,d]=v.useState([]),[c,f]=v.useState({}),[m,h]=v.useState({}),[y,x]=v.useState(""),[N,_]=v.useState(""),[S,p]=v.useState({}),w=v.useMemo(()=>(t||[]).filter(V=>(typeof V.state=="string"?V.state.toLowerCase():String(V.state||"").toLowerCase())===Ye.APPROVED),[t]),E=v.useMemo(()=>n?(t||[]).find(V=>V.name===n):null,[n,t]),C=v.useMemo(()=>E?Vt(E):!1,[E]),A=v.useMemo(()=>E?Zs(E):!1,[E]),T=v.useMemo(()=>E?It(E):null,[E]),M=v.useCallback(V=>{if(a(V),V){const z=(t||[]).find(ge=>ge.name===V),L=(z==null?void 0:z.fields)||(z==null?void 0:z.transform_fields)||[],Q=Array.isArray(L)?L:Object.keys(L);d(Q);const Y={};Q.forEach(ge=>{Y[ge]=""}),f(Y)}else d([]),f({});h({}),x(""),_(""),p({})},[t]),I=v.useCallback(V=>{d(z=>z.includes(V)?z.filter(L=>L!==V):[...z,V]),f(z=>z[V]!==void 0?z:{...z,[V]:""})},[]),O=v.useCallback((V,z,L)=>{h(Q=>({...Q,[V]:{...Q[V],[z]:L}}))},[]),R=v.useCallback((V,z)=>{f(L=>({...L,[V]:z}))},[]),$=v.useCallback(()=>{a(""),d([]),f({}),h({}),x(""),_(""),p({})},[]),F=v.useCallback(()=>{e(Qe({forceRefresh:!0}))},[e]);return{state:{selectedSchema:n,queryFields:l,fieldValues:c,rangeFilters:m,rangeSchemaFilter:S,rangeKeyValue:y,hashKeyValue:N},setSelectedSchema:a,setQueryFields:d,setFieldValues:f,toggleField:I,handleFieldValueChange:R,setRangeFilters:h,setRangeSchemaFilter:p,setRangeKeyValue:x,setHashKeyValue:_,clearState:$,handleSchemaChange:M,handleRangeFilterChange:O,refetchSchemas:F,approvedSchemas:w,schemasLoading:r,selectedSchemaObj:E,isRangeSchema:C,isHashRangeSchema:A,rangeKey:T}}function pr(e){return{HashKey:e}}function td(e){return{RangePrefix:e}}function rd(e,t){return{RangeRange:{start:e,end:t}}}function sd(e,t){return{HashRangeKey:{hash:e,range:t}}}function nd({schema:e,queryState:t,schemas:r,selectedSchemaObj:n,isRangeSchema:a,rangeKey:l}){const d=fe(mr),c=v.useMemo(()=>n||(r&&e&&r[e]?r[e]:d&&Array.isArray(d)&&d.find(x=>x.name===e)||null),[n,e,r,d]),f=v.useMemo(()=>typeof a=="boolean"?a:c?c.schema_type==="Range"||Vt(c)?!0:c.fields&&typeof c.fields=="object"?Object.values(c.fields).some(N=>(N==null?void 0:N.field_type)==="Range"):!1:!1,[c,a]),m=v.useMemo(()=>[],[]),h=!0,y=v.useMemo(()=>{var C;if(!e||!t||!c)return{};const{queryFields:x=[],fieldValues:N={},rangeFilters:_={},rangeSchemaFilter:S={},filters:p=[],orderBy:w}=t,E={schema_name:e,fields:x};if(Zs(c)){const A=t.hashKeyValue,T=(C=t.rangeSchemaFilter)==null?void 0:C.key;A&&A.trim()?E.filter=pr(A.trim()):T&&T.trim()&&(E.filter=pr(T.trim()))}if(f){const A=S&&Object.keys(S).length>0?S:Object.values(_).find(M=>M&&typeof M=="object"&&(M.key||M.keyPrefix||M.start&&M.end))||{},T=t==null?void 0:t.rangeKeyValue;!A.key&&!A.keyPrefix&&!(A.start&&A.end)&&T&&(A.key=T),A.key?E.filter=pr(A.key):A.keyPrefix?E.filter=td(A.keyPrefix):A.start&&A.end&&(E.filter=rd(A.start,A.end))}return E},[e,t,c]);return v.useCallback(()=>y,[y]),v.useCallback(()=>({isValid:h,errors:m}),[h,m]),{query:y,validationErrors:m,isValid:h}}function Je({label:e,name:t,required:r=!1,error:n,helpText:a,children:l,className:d=""}){const c=t?`field-${t}`:`field-${Math.random().toString(36).substr(2,9)}`,f=!!n;return s.jsxs("div",{className:`space-y-2 ${d}`,children:[s.jsxs("label",{htmlFor:c,className:"block text-sm font-medium text-gray-700",children:[e,r&&s.jsx("span",{className:"ml-1 text-red-500","aria-label":"required",children:"*"})]}),s.jsx("div",{className:"relative",children:l}),f&&s.jsx("p",{className:"text-sm text-red-600",role:"alert","aria-live":"polite",children:n}),a&&!f&&s.jsx("p",{className:"text-xs text-gray-500",children:a})]})}function Ja(e=[]){return e.reduce((t,r)=>{const n=r.group||"default";return t[n]||(t[n]=[]),t[n].push(r),t},{})}function ad(e=[],t=""){if(tl(t))return e;const r=t.toLowerCase();return e.filter(n=>n.label.toLowerCase().includes(r)||n.value.toLowerCase().includes(r))}function id(e={}){return{placeholder:"Select an option...",emptyMessage:"No options available",searchable:!1,required:!1,disabled:!1,loading:!1,showConfirmation:!1,...e}}function od(e,t=!1,r=!1,n=!1){var l,d;let a=((l=e.select)==null?void 0:l.base)||"";return t&&(a+=" border-red-300 focus:ring-red-500 focus:border-red-500"),(r||n)&&(a+=` ${((d=e.select)==null?void 0:d.disabled)||""}`),a}function cd(e,t=!1,r=""){const n={"aria-invalid":t};return t?n["aria-describedby"]=`${e}-error`:r&&(n["aria-describedby"]=`${e}-help`),n}function ld(e=[],t,r=!0){const[n,a]=v.useState(""),[l,d]=v.useState(!1),c=ad(e,n),f=Ja(c),m=v.useCallback(E=>{a(E.target.value)},[]),h=v.useCallback(E=>{E.disabled||(t(E.value),r&&(d(!1),a("")))},[t,r]),y=v.useCallback(()=>{d(!0)},[]),x=v.useCallback(()=>{d(!1)},[]),N=v.useCallback(()=>{d(E=>!E)},[]),_=v.useCallback(E=>{const C=e.find(A=>A.value===E);C&&h(C)},[e,h]),S=v.useCallback(()=>{a("")},[]);return{state:{searchTerm:n,isOpen:l,filteredOptions:c,groupedOptions:f},actions:{setSearchTerm:a,openDropdown:y,closeDropdown:x,toggleDropdown:N,selectOption:_,clearSearch:S},handleSearchChange:m,handleOptionSelect:h}}function Za(e){return`field-${e}`}function dd(e){return!!e}function ud({hasError:e,disabled:t,additionalClasses:r=""}){const n=$e.input.base,a=e?$e.input.error:$e.input.success;return`${n} ${a} ${t?"bg-gray-100 cursor-not-allowed":""} ${r}`.trim()}function fd({fieldId:e,hasError:t,hasHelp:r}){const n={"aria-invalid":t};return t?n["aria-describedby"]=`${e}-error`:r&&(n["aria-describedby"]=`${e}-help`),n}function hd({size:e="sm",color:t="primary"}={}){const r={sm:"h-3 w-3",md:"h-4 w-4",lg:"h-5 w-5"},n={primary:"border-primary border-t-transparent",gray:"border-gray-400 border-t-transparent",white:"border-white border-t-transparent"};return`animate-spin ${r[e]} border-2 ${n[t]} rounded-full`}function sn({name:e,label:t,value:r,options:n=[],onChange:a,error:l,helpText:d,config:c={},className:f=""}){const m=id(c),{searchable:h,placeholder:y,emptyMessage:x,required:N,disabled:_,loading:S}=m,p=Za(e),w=!!l,E=n.length>0,C=ld(n,a,!0),A=O=>{a(O.target.value)};if(S)return s.jsx(Je,{label:t,name:e,required:N,error:l,helpText:d,className:f,children:s.jsxs("div",{className:`${$e.select.disabled} flex items-center`,children:[s.jsx("div",{className:"animate-spin h-4 w-4 border-2 border-gray-400 border-t-transparent rounded-full mr-2"}),Qc.loading]})});if(!E)return s.jsx(Je,{label:t,name:e,required:N,error:l,helpText:d,className:f,children:s.jsx("div",{className:$e.select.disabled,children:x})});if(h){const{state:O,handleSearchChange:R,handleOptionSelect:$}=C;return s.jsx(Je,{label:t,name:e,required:N,error:l,helpText:d,className:f,children:s.jsxs("div",{className:"relative",children:[s.jsx("input",{type:"text",placeholder:`Search ${t.toLowerCase()}...`,value:O.searchTerm,onChange:R,onFocus:()=>C.actions.openDropdown(),className:`${$e.input.base} ${w?$e.input.error:""}`}),O.isOpen&&O.filteredOptions.length>0&&s.jsx("div",{className:"absolute z-10 w-full mt-1 bg-white border border-gray-300 rounded-md shadow-lg max-h-60 overflow-auto",children:Object.entries(O.groupedOptions).map(([F,H])=>s.jsxs("div",{children:[F!=="default"&&s.jsx("div",{className:"px-3 py-2 text-xs font-semibold text-gray-500 bg-gray-50 border-b",children:F}),H.map(V=>s.jsx("button",{type:"button",onClick:()=>$(V),disabled:V.disabled,className:`w-full text-left px-3 py-2 hover:bg-gray-100 focus:bg-gray-100 focus:outline-none ${V.disabled?"text-gray-400 cursor-not-allowed":"text-gray-900"} ${r===V.value?"bg-primary text-white":""}`,children:V.label},V.value))]},F))})]})})}const T=Ja(n),M=od($e,w,_,S),I=cd(p,w,d);return s.jsx(Je,{label:t,name:e,required:N,error:l,helpText:d,className:f,children:s.jsxs("select",{id:p,name:e,value:r,onChange:A,required:N,disabled:_,className:M,...I,children:[s.jsx("option",{value:"",disabled:N,children:y}),Object.entries(T).map(([O,R])=>O!=="default"?s.jsx("optgroup",{label:O,children:R.map($=>s.jsx("option",{value:$.value,disabled:$.disabled,children:$.label},$.value))},O):R.map($=>s.jsx("option",{value:$.value,disabled:$.disabled,children:$.label},$.value)))]})})}function gr({name:e,label:t,value:r,onChange:n,required:a=!1,disabled:l=!1,error:d,placeholder:c,helpText:f,type:m="text",debounced:h=!1,debounceMs:y=Wc,className:x=""}){const[N,_]=v.useState(r),[S,p]=v.useState(!1);v.useEffect(()=>{_(r)},[r]);const w=v.useRef(null),E=v.useRef(null),C=v.useRef(n);v.useEffect(()=>{C.current=n},[n]);const A=v.useCallback($=>{p(!0),w.current&&(clearTimeout(w.current),w.current=null),E.current&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&(window.cancelAnimationFrame(E.current),E.current=null);const F=()=>{w.current=setTimeout(()=>{C.current($),p(!1)},y)};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?E.current=window.requestAnimationFrame(F):setTimeout(F,0)},[y]),T=$=>{const F=$.target.value;_(F),h?A(F):n(F)},M=Za(e),I=dd(d),O=ud({hasError:I,disabled:l}),R=fd({fieldId:M,hasError:I,hasHelp:!!f});return s.jsx(Je,{label:t,name:e,required:a,error:d,helpText:f,className:x,children:s.jsxs("div",{className:"relative",children:[s.jsx("input",{id:M,name:e,type:m,value:N,onChange:T,placeholder:c,required:a,disabled:l,className:O,...R}),h&&S&&s.jsx("div",{className:"absolute right-2 top-1/2 transform -translate-y-1/2",children:s.jsx("div",{className:hd({size:"md",color:"primary"}),role:"status","aria-label":"Processing input"})})]})})}function Xa(e={}){return e.start||e.end?"range":e.key?"key":e.keyPrefix?"prefix":"range"}function md(e,t,r){const n={...e};return t==="range"||r==="start"||r==="end"?(delete n.key,delete n.keyPrefix):t==="key"||r==="key"?(delete n.start,delete n.end,delete n.keyPrefix):(t==="prefix"||r==="keyPrefix")&&(delete n.start,delete n.end,delete n.key),n}function pd(e={},t,r=["range","key","prefix"]){const[n,a]=v.useState(()=>Xa(e)),[l,d]=v.useState(e),c=v.useCallback(S=>{if(!r.includes(S))return;a(S);const p={};d(p),t&&t(p)},[r,t]),f=v.useCallback((S,p)=>{const w=md(l,n,S);w[S]=p,d(w),t&&t(w)},[l,n,t]),m=v.useCallback(()=>{const S={};d(S),t&&t(S)},[t]),h=v.useCallback(S=>{d(S);const p=Xa(S);a(p),t&&t(S)},[t]),y=v.useCallback(()=>r,[r]),x=v.useCallback(S=>r.includes(S),[r]);return{state:{activeMode:n,value:l},actions:{changeMode:c,updateValue:f,clearValue:m,setValue:h},getAvailableModes:y,isValidMode:x}}function gd(e="all",t="key",r=""){if(r)return r;if(e!=="all")return null;const n={...Zc.rangeKeyFilter},a=n.keyRange||"",l=(n.exactKey||"").replace("key",t),d=(n.keyPrefix||"").replace("keys",`${t} values`),c=n.emptyNote||"";return`${a} ${l} ${d} ${c}`.trim()}function yd(e="all"){const t={all:{showModeSelector:!0,availableModes:["range","key","prefix"],defaultMode:"range"},range:{showModeSelector:!1,availableModes:["range"],defaultMode:"range"},key:{showModeSelector:!1,availableModes:["key"],defaultMode:"key"},prefix:{showModeSelector:!1,availableModes:["prefix"],defaultMode:"prefix"}};return t[e]||t.all}function xd(e=!1){const t="px-3 py-1 text-xs rounded-md transition-colors duration-200";return e?`${t} bg-primary text-white`:`${t} bg-gray-200 text-gray-700 hover:bg-gray-300`}function bd(){return{range:"Key Range",key:"Exact Key",prefix:"Key Prefix"}}function vd(e,t){return e==="all"?{showRange:t==="range",showKey:t==="key",showPrefix:t==="prefix"}:{showRange:e==="range",showKey:e==="key",showPrefix:e==="prefix"}}function wd(e={}){const{mode:t="all",rangeKeyName:r="key",required:n=!1,disabled:a=!1,className:l=""}=e;return{mode:["all","range","key","prefix"].includes(t)?t:"all",rangeKeyName:String(r),required:!!n,disabled:!!a,className:String(l)}}function Ed(){return"bg-yellow-50 rounded-lg p-4 space-y-4"}function Sd(){return"text-sm font-medium text-gray-800"}function Nd(){return"flex space-x-4 mb-4"}function jd(){return"grid grid-cols-1 md:grid-cols-3 gap-4"}function _d({name:e,label:t,value:r={},onChange:n,error:a,helpText:l,config:d={},className:c=""}){const f=wd(d),{mode:m,rangeKeyName:h,required:y,disabled:x}=f,N=yd(m),_=pd(r,n,N.availableModes),{state:S,actions:p}=_,w=bd(),E=vd(m,S.activeMode),C=gd(m,h,l);return s.jsx(Je,{label:t,name:e,required:y,error:a,helpText:C,className:c,children:s.jsxs("div",{className:Ed(),children:[s.jsx("div",{className:"mb-3",children:s.jsxs("span",{className:Sd(),children:["Range Key: ",h]})}),N.showModeSelector&&s.jsx("div",{className:Nd(),children:N.availableModes.map(A=>s.jsx("button",{type:"button",onClick:()=>p.changeMode(A),className:xd(S.activeMode===A),children:w[A]},A))}),s.jsxs("div",{className:jd(),children:[E.showRange&&s.jsxs(s.Fragment,{children:[s.jsx(gr,{name:`${e}-start`,label:"Start Key",value:S.value.start||"",onChange:A=>p.updateValue("start",A),placeholder:"Start key",disabled:x,className:"col-span-1"}),s.jsx(gr,{name:`${e}-end`,label:"End Key",value:S.value.end||"",onChange:A=>p.updateValue("end",A),placeholder:"End key",disabled:x,className:"col-span-1"})]}),E.showKey&&s.jsx(gr,{name:`${e}-key`,label:"Exact Key",value:S.value.key||"",onChange:A=>p.updateValue("key",A),placeholder:`Exact ${h} to match`,disabled:x,className:"col-span-1"}),E.showPrefix&&s.jsx(gr,{name:`${e}-prefix`,label:"Key Prefix",value:S.value.keyPrefix||"",onChange:A=>p.updateValue("keyPrefix",A),placeholder:`${h} prefix (e.g., 'user:')`,disabled:x,className:"col-span-1"})]})]})})}function Ad({queryState:e,onSchemaChange:t,onFieldToggle:r,onFieldValueChange:n,onRangeFilterChange:a,onRangeSchemaFilterChange:l,onHashKeyChange:d,approvedSchemas:c,schemasLoading:f,isRangeSchema:m,isHashRangeSchema:h,rangeKey:y,className:x=""}){const[N,_]=v.useState({}),{clearQuery:S}=rn();v.useCallback(()=>(_({}),!0),[]);const p=v.useCallback(T=>{t(T),S&&S(),_(M=>{const{schema:I,...O}=M;return O})},[t,S]),w=v.useCallback(T=>{r(T),_(M=>{const{fields:I,...O}=M;return O})},[r]),E=e!=null&&e.selectedSchema&&c?c.find(T=>T.name===e.selectedSchema):null,C=(E==null?void 0:E.fields)||(E==null?void 0:E.transform_fields)||[],A=Array.isArray(C)?C:Object.keys(C);return s.jsxs("div",{className:`space-y-6 ${x}`,children:[s.jsx(Je,{label:kt.schema,name:"schema",required:!0,error:N.schema,helpText:kt.schemaHelp,children:s.jsx(sn,{name:"schema",value:(e==null?void 0:e.selectedSchema)||"",onChange:p,options:c.map(T=>({value:T.name,label:T.descriptive_name||T.name})),placeholder:"Select a schema...",emptyMessage:kt.schemaEmpty,loading:f})}),(e==null?void 0:e.selectedSchema)&&A.length>0&&s.jsx(Je,{label:"Field Selection",name:"fields",required:!0,error:N.fields,helpText:"Select fields to include in your query",children:s.jsx("div",{className:"bg-gray-50 rounded-md p-4",children:s.jsx("div",{className:"space-y-3",children:A.map(T=>{var M;return s.jsxs("label",{className:"relative flex items-start",children:[s.jsx("div",{className:"flex items-center h-5",children:s.jsx("input",{type:"checkbox",className:"h-4 w-4 text-primary border-gray-300 rounded focus:ring-primary",checked:((M=e==null?void 0:e.queryFields)==null?void 0:M.includes(T))||!1,onChange:()=>w(T)})}),s.jsx("div",{className:"ml-3 flex items-center",children:s.jsx("span",{className:"text-sm font-medium text-gray-700",children:T})})]},T)})})})}),h&&s.jsx(Je,{label:"HashRange Filter",name:"hashRangeFilter",helpText:"Filter data by hash and range key values",children:s.jsxs("div",{className:"bg-purple-50 rounded-md p-4 space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsxs("div",{className:"space-y-2",children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700",children:"Hash Key"}),s.jsx("input",{type:"text",placeholder:"Enter hash key value",className:"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary",value:(e==null?void 0:e.hashKeyValue)||"",onChange:T=>d(T.target.value)}),s.jsxs("div",{className:"text-xs text-gray-500",children:["Hash field: ",ja(c.find(T=>T.name===(e==null?void 0:e.selectedSchema)))||"N/A"]})]}),s.jsxs("div",{className:"space-y-2",children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700",children:"Range Key"}),s.jsx("input",{type:"text",placeholder:"Enter range key value",className:"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary",value:(e==null?void 0:e.rangeKeyValue)||"",onChange:T=>l({key:T.target.value})}),s.jsxs("div",{className:"text-xs text-gray-500",children:["Range field: ",It(c.find(T=>T.name===(e==null?void 0:e.selectedSchema)))||"N/A"]})]})]}),s.jsxs("div",{className:"text-xs text-gray-500",children:[s.jsxs("p",{children:[s.jsx("strong",{children:"Hash Key:"})," Used for partitioning data across multiple nodes"]}),s.jsxs("p",{children:[s.jsx("strong",{children:"Range Key:"})," Used for ordering and range queries within a partition"]})]})]})}),m&&y&&s.jsx(Je,{label:"Range Filter",name:"rangeSchemaFilter",error:N.rangeFilter,helpText:"Filter data by range key values",children:s.jsx(_d,{name:"rangeSchemaFilter",value:(e==null?void 0:e.rangeSchemaFilter)||{},onChange:T=>{l(T),_(M=>{const{rangeFilter:I,...O}=M;return O})},rangeKeyName:y,mode:"all"})})]})}function Cd({onExecute:e,onExecuteQuery:t,onValidate:r,onSave:n,onSaveQuery:a,onClear:l,onClearQuery:d,disabled:c=!1,isExecuting:f=!1,isSaving:m=!1,showValidation:h=!1,showSave:y=!0,showClear:x=!0,className:N="",queryData:_}){const[S,p]=v.useState(null),[w,E]=v.useState(null),{clearQuery:C}=rn(),A=async(R,$,F=null)=>{if(!(!$||c))try{p(R),await $(F)}catch(H){console.error(`${R} action failed:`,H)}finally{p(null),E(null)}},T=()=>{A("execute",t||e,_)},M=()=>{A("validate",r,_)},I=()=>{A("save",a||n,_)},O=()=>{const R=d||l;R&&R(),C&&C()};return s.jsxs("div",{className:`flex justify-end space-x-3 ${N}`,children:[x&&s.jsx("button",{type:"button",onClick:O,disabled:c,className:`
            inline-flex items-center px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium
            ${c?"bg-gray-100 text-gray-400 cursor-not-allowed":"bg-white text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"}
          `,children:Zr.clearQuery||"Clear Query"}),h&&r&&s.jsxs("button",{type:"button",onClick:M,disabled:c,className:`
            inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium
            ${c?"bg-gray-300 text-gray-500 cursor-not-allowed":"bg-blue-600 text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"}
          `,children:[S==="validate"&&s.jsxs("svg",{className:"animate-spin -ml-1 mr-2 h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),Zr.validateQuery||"Validate"]}),y&&(n||a)&&s.jsxs("button",{type:"button",onClick:I,disabled:c||m,className:`
            inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium
            ${c||m?"bg-gray-300 text-gray-500 cursor-not-allowed":"bg-green-600 text-white hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"}
          `,children:[(S==="save"||m)&&s.jsxs("svg",{className:"animate-spin -ml-1 mr-2 h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),Zr.saveQuery||"Save Query"]}),s.jsxs("button",{type:"button",onClick:T,disabled:c||f,className:`
          inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white
          ${c||f?"bg-gray-300 cursor-not-allowed":"bg-primary hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"}
        `,children:[(S==="execute"||f)&&s.jsxs("svg",{className:"animate-spin -ml-1 mr-2 h-4 w-4 text-white",xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 714 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),S==="execute"||f?"Executing...":Zr.executeQuery]})]})}const Td=(e,t)=>{if(!e&&!t)return null;const r={...e,...t};let n=[],a={};Array.isArray(r.fields)?n=r.fields:r.fields&&typeof r.fields=="object"?(n=Object.keys(r.fields),a=r.fields):r.queryFields&&Array.isArray(r.queryFields)&&(n=r.queryFields),r.fieldValues&&typeof r.fieldValues=="object"&&(a={...a,...r.fieldValues});const l={schema:r.schema||r.selectedSchema,fields:n,fieldValues:a,filters:r.filters||{},orderBy:r.orderBy,rangeKey:r.rangeKey};if(e&&e.filter)if(e.filter.field&&e.filter.range_filter){const d=e.filter.field,c=e.filter.range_filter;c.Key?l.filters[d]={exactKey:c.Key}:c.KeyRange?l.filters[d]={keyRange:`${c.KeyRange.start} → ${c.KeyRange.end}`}:c.KeyPrefix&&(l.filters[d]={keyPrefix:c.KeyPrefix})}else e.filter.range_filter&&Object.entries(e.filter.range_filter).forEach(([d,c])=>{typeof c=="string"?l.filters[d]={exactKey:c}:c.KeyRange?l.filters[d]={keyRange:`${c.KeyRange.start} → ${c.KeyRange.end}`}:c.KeyPrefix&&(l.filters[d]={keyPrefix:c.KeyPrefix})});return l};function kd({query:e,queryState:t,validationErrors:r=[],isExecuting:n=!1,showJson:a=!1,collapsible:l=!0,className:d="",title:c="Query Preview"}){const f=v.useMemo(()=>Td(e,t),[e,t]);return!e&&!t?s.jsxs("div",{className:`bg-gray-50 rounded-md p-4 ${d}`,children:[s.jsx("h3",{className:"text-sm font-medium text-gray-500 mb-2",children:c}),s.jsx("p",{className:"text-sm text-gray-400 italic",children:"No query to preview"})]}):s.jsxs("div",{className:`bg-white border border-gray-200 rounded-lg shadow-sm ${d}`,children:[s.jsx("div",{className:"px-4 py-3 border-b border-gray-200",children:s.jsx("h3",{className:"text-sm font-medium text-gray-900",children:c})}),s.jsxs("div",{className:"p-4 space-y-4",children:[r&&r.length>0&&s.jsxs("div",{className:"bg-red-50 border border-red-200 rounded-md p-3",children:[s.jsxs("div",{className:"flex items-center mb-2",children:[s.jsx("svg",{className:"h-4 w-4 text-red-400 mr-2",fill:"currentColor",viewBox:"0 0 20 20",children:s.jsx("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z",clipRule:"evenodd"})}),s.jsx("span",{className:"text-sm font-medium text-red-800",children:"Validation Errors"})]}),s.jsx("ul",{className:"space-y-1",children:r.map((m,h)=>s.jsx("li",{className:"text-sm text-red-700",children:m},h))})]}),n&&s.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-md p-3",children:s.jsxs("div",{className:"flex items-center",children:[s.jsxs("svg",{className:"animate-spin h-4 w-4 text-blue-400 mr-2",fill:"none",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),s.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Executing query..."})]})}),s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1",children:"Schema"}),s.jsx("div",{className:"inline-flex items-center px-2 py-1 rounded-md bg-blue-100 text-blue-800 text-sm font-medium",children:(f==null?void 0:f.schema)||""})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1",children:["Fields (",f!=null&&f.fields?f.fields.length:0,")"]}),s.jsx("div",{className:"flex flex-wrap gap-1",children:f!=null&&f.fields&&f.fields.length>0?f.fields.map((m,h)=>{var x;const y=(x=f.fieldValues)==null?void 0:x[m];return s.jsxs("div",{className:"inline-flex flex-col items-start",children:[s.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-md bg-green-100 text-green-800 text-sm",children:m}),y&&s.jsx("span",{className:"text-xs text-gray-600 mt-1 px-2",children:y})]},h)}):s.jsx("span",{className:"text-sm text-gray-500 italic",children:"No fields selected"})})]}),(f.filters&&Array.isArray(f.filters)&&f.filters.length>0||f.filters&&!Array.isArray(f.filters)&&Object.keys(f.filters).length>0)&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1",children:"Filters"}),s.jsx("div",{className:"space-y-2",children:Array.isArray(f.filters)?f.filters.map((m,h)=>s.jsx("div",{className:"bg-yellow-50 rounded-md p-3",children:s.jsxs("div",{className:"text-sm text-yellow-700",children:[m.field," ",m.operator,' "',m.value,'"']})},h)):Object.entries(f.filters).map(([m,h])=>s.jsxs("div",{className:"bg-yellow-50 rounded-md p-3",children:[s.jsx("div",{className:"font-medium text-sm text-yellow-800 mb-1",children:m}),s.jsxs("div",{className:"text-sm text-yellow-700",children:[h.exactKey&&s.jsxs("span",{children:["Exact key: ",s.jsx("code",{className:"bg-yellow-200 px-1 rounded",children:h.exactKey})]}),h.keyRange&&s.jsxs("span",{children:["Key range: ",s.jsx("code",{className:"bg-yellow-200 px-1 rounded",children:h.keyRange})]}),h.keyPrefix&&s.jsxs("span",{children:["Key prefix: ",s.jsx("code",{className:"bg-yellow-200 px-1 rounded",children:h.keyPrefix})]})]})]},m))})]}),f.orderBy&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1",children:"OrderBy"}),s.jsx("div",{className:"bg-purple-50 rounded-md p-3",children:s.jsxs("div",{className:"text-sm text-purple-700",children:[f.orderBy.field," ",f.orderBy.direction]})})]}),f.rangeKey&&s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs font-medium text-gray-500 uppercase tracking-wide mb-1",children:"RangeKey"}),s.jsx("div",{className:"bg-indigo-50 rounded-md p-3",children:s.jsx("div",{className:"text-sm text-indigo-700",children:s.jsx("code",{className:"bg-indigo-200 px-1 rounded",children:f.rangeKey})})})]})]}),a&&s.jsxs("div",{className:"border-t border-gray-200 pt-4",children:[s.jsx("label",{className:"block text-xs font-medium text-gray-500 uppercase tracking-wide mb-2",children:"Raw JSON"}),s.jsx("pre",{className:"bg-gray-900 text-gray-100 text-xs p-3 rounded-md overflow-x-auto",children:JSON.stringify(e,null,2)})]})]})]})}function Id({onResult:e}){const{state:t,handleSchemaChange:r,toggleField:n,handleFieldValueChange:a,handleRangeFilterChange:l,setRangeSchemaFilter:d,setHashKeyValue:c,clearState:f,refetchSchemas:m,approvedSchemas:h,schemasLoading:y,selectedSchemaObj:x,isRangeSchema:N,isHashRangeSchema:_,rangeKey:S}=rn();v.useEffect(()=>{m()},[m]);const[p,w]=v.useState(!1),{query:E,isValid:C}=nd({schema:t.selectedSchema,queryState:t,schemas:{[t.selectedSchema]:x}}),A=v.useCallback(async I=>{if(!I){e({error:"No query data provided"});return}w(!0);try{const O=await tn.executeQuery(I);if(!O.success){console.error("Query failed:",O.error),e({error:O.error||"Query execution failed",details:O});return}e({success:!0,data:O.data})}catch(O){console.error("Failed to execute query:",O),e({error:`Network error: ${O.message}`,details:O})}finally{w(!1)}},[e,C]),T=v.useCallback(async I=>{console.log("Validating query:",I)},[]),M=v.useCallback(async I=>{if(!I||!C){console.warn("Cannot save invalid query");return}try{console.log("Saving query:",I);const O=JSON.parse(localStorage.getItem("savedQueries")||"[]"),R={id:Date.now(),name:`Query ${O.length+1}`,data:I,createdAt:new Date().toISOString()};O.push(R),localStorage.setItem("savedQueries",JSON.stringify(O)),console.log("Query saved successfully")}catch(O){console.error("Failed to save query:",O)}},[C]);return s.jsx("div",{className:"p-6",children:s.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[s.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[s.jsx(Ad,{queryState:t,onSchemaChange:r,onFieldToggle:n,onFieldValueChange:a,onRangeFilterChange:l,onRangeSchemaFilterChange:d,onHashKeyChange:c,approvedSchemas:h,schemasLoading:y,isRangeSchema:N,isHashRangeSchema:_,rangeKey:S}),s.jsx(Cd,{onExecute:()=>A(E),onValidate:()=>T(E),onSave:()=>M(E),onClear:f,queryData:E,disabled:!C,isExecuting:p,showValidation:!1,showSave:!0,showClear:!0})]}),s.jsx("div",{className:"lg:col-span-1",children:s.jsx(kd,{query:E,showJson:!1,title:"Query Preview"})})]})})}function Od({onResult:e}){const t=Qt(),r=fe(yl),n=fe(xl),a=fe(bl),l=fe(vl),d=fe(wl),c=fe(El),f=v.useRef(null);v.useEffect(()=>{var x;(x=f.current)==null||x.scrollIntoView({behavior:"smooth"})},[l]);const m=v.useCallback((x,N,_=null)=>{t(hl({type:x,content:N,data:_}))},[t]),h=v.useCallback(async x=>{if(x==null||x.preventDefault(),!r.trim()||a)return;const N=r.trim();t(Fa("")),t(Ma(!0)),m("user",N);try{if(c){m("system","🤔 Analyzing if question can be answered from existing context...");const _=await za.analyzeFollowup({session_id:n,question:N});if(!_.success){m("system",`❌ Error: ${_.error||"Failed to analyze question"}`);return}const S=_.data;if(S.needs_query){m("system",`🔍 Need new data: ${S.reasoning}`),m("system","🔍 Using AI-native index search...");const p=await fetch("/api/llm-query/native-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:N,session_id:n})});if(!p.ok){const E=await p.json();m("system",`❌ Error: ${E.error||"Failed to run AI-native index query"}`);return}const w=await p.json();m("system","✅ AI-native index search completed"),w.session_id&&t(Pa(w.session_id)),m("system",w.ai_interpretation),m("results","Raw search results",w.raw_results),d&&e({success:!0,data:w.raw_results})}else{m("system",`✅ Answering from existing context: ${S.reasoning}`);const p=await za.chat({session_id:n,question:N});if(!p.success){m("system",`❌ Error: ${p.error||"Failed to process question"}`);return}m("system",p.data.answer)}}else{m("system","🔍 Using AI-native index search...");const _=await fetch("/api/llm-query/native-index",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:N,session_id:n})});if(!_.ok){const p=await _.json();m("system",`❌ Error: ${p.error||"Failed to run AI-native index query"}`);return}const S=await _.json();m("system","✅ AI-native index search completed"),S.session_id&&t(Pa(S.session_id)),m("system",S.ai_interpretation),m("results","Raw search results",S.raw_results),d&&e({success:!0,data:S.raw_results})}}catch(_){console.error("Error processing input:",_),m("system",`❌ Error: ${_.message}`),e({error:_.message})}finally{t(Ma(!1))}},[r,n,c,a,m,e,t]),y=v.useCallback(()=>{t(pl())},[t]);return s.jsxs("div",{className:"flex flex-col bg-white rounded-lg shadow",children:[s.jsxs("div",{className:"p-4 border-b border-gray-200 flex justify-between items-center",children:[s.jsxs("div",{children:[s.jsx("h2",{className:"text-xl font-bold text-gray-900",children:"🤖 AI Data Assistant"}),s.jsx("p",{className:"text-sm text-gray-600",children:"Ask questions in plain English - I'll find your data"})]}),l.length>0&&s.jsx("button",{onClick:y,disabled:a,className:"px-4 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors text-sm",children:"New Conversation"})]}),s.jsxs("div",{className:"overflow-y-auto bg-gray-50 p-4 space-y-3",style:{maxHeight:"60vh",minHeight:"400px"},children:[l.length===0?s.jsxs("div",{className:"text-center text-gray-500 mt-20",children:[s.jsx("div",{className:"text-6xl mb-4",children:"💬"}),s.jsx("p",{className:"text-lg mb-2",children:"Start a conversation"}),s.jsx("p",{className:"text-sm",children:'Try: "Find all blog posts from last month" or "Show me products over $100"'})]}):l.map((x,N)=>s.jsxs("div",{children:[x.type==="user"&&s.jsx("div",{className:"flex justify-end",children:s.jsxs("div",{className:"bg-blue-600 text-white rounded-lg px-4 py-2 max-w-3xl",children:[s.jsx("p",{className:"text-sm font-semibold mb-1",children:"You"}),s.jsx("p",{className:"whitespace-pre-wrap",children:x.content})]})}),x.type==="system"&&s.jsx("div",{className:"flex justify-start",children:s.jsxs("div",{className:"bg-white border border-gray-200 rounded-lg px-4 py-2 max-w-3xl",children:[s.jsx("p",{className:"text-sm font-semibold text-gray-700 mb-1",children:"AI Assistant"}),s.jsx("p",{className:"text-gray-900 whitespace-pre-wrap",children:x.content})]})}),x.type==="results"&&x.data&&s.jsxs("div",{className:"bg-green-50 border border-green-200 rounded-lg p-4 max-w-full",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("p",{className:"text-sm font-semibold text-green-800",children:["📊 Results (",x.data.length,")"]}),s.jsx("button",{onClick:()=>{const _=!d;if(t(ml(_)),_){const S=l.find(p=>p.type==="results");S&&S.data&&e({success:!0,data:S.data})}else e(null)},className:"text-sm text-green-700 hover:text-green-900 underline",children:d?"Hide Details":"Show Details"})]}),d&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"bg-white rounded p-3 mb-2",children:s.jsx("p",{className:"text-gray-900 whitespace-pre-wrap mb-3",children:x.content})}),s.jsxs("details",{className:"mt-2",children:[s.jsxs("summary",{className:"cursor-pointer text-sm text-green-700 hover:text-green-900",children:["View raw data (",x.data.length," records)"]}),s.jsx("div",{className:"mt-2 max-h-64 overflow-auto",children:s.jsx("pre",{className:"text-xs bg-gray-900 text-green-400 p-3 rounded",children:JSON.stringify(x.data,null,2)})})]})]})]})]},N)),s.jsx("div",{ref:f})]}),s.jsxs("form",{onSubmit:h,className:"border-t border-gray-200 p-4 bg-white",children:[s.jsxs("div",{className:"flex gap-2",children:[s.jsx("input",{type:"text",value:r,onChange:x=>t(Fa(x.target.value)),placeholder:l.some(x=>x.type==="results")?"Ask a follow-up question or start a new query...":"Search the native index (e.g., 'Find posts about AI')...",disabled:a,className:"flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent disabled:bg-gray-100",autoFocus:!0}),s.jsx("button",{type:"submit",disabled:!r.trim()||a,className:"px-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors font-semibold",children:a?"⏳ Processing...":"Send"})]}),a&&s.jsx("p",{className:"text-center text-sm text-gray-500 mt-2",children:"AI is analyzing and searching..."})]})]})}function Rd({selectedSchema:e,mutationType:t,onSchemaChange:r,onTypeChange:n}){const a=fe(mr);return s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsx(sn,{name:"schema",label:kt.schema,value:e,onChange:r,options:a.map(l=>({value:l.name,label:l.descriptive_name||l.name})),placeholder:"Select a schema...",emptyMessage:"No approved schemas available for mutations",helpText:kt.schemaHelp}),s.jsx(sn,{name:"operationType",label:kt.operationType,value:t,onChange:n,options:Jc,helpText:kt.operationHelp})]})}function Dd({fields:e,mutationType:t,mutationData:r,onFieldChange:n,isRangeSchema:a}){if(t==="Delete")return s.jsxs("div",{className:"bg-gray-50 rounded-lg p-6",children:[s.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-4",children:"Delete Operation"}),s.jsx("p",{className:"text-sm text-gray-600",children:"This will delete the selected schema. No additional fields are required."})]});const l=(d,c)=>{if(!(c.writable!==!1))return null;const m=r[d]||"";switch(c.field_type){case"Collection":{let h=[];if(m)try{const y=typeof m=="string"?JSON.parse(m):m;h=Array.isArray(y)?y:[y]}catch{h=m.trim()?[m]:[]}return s.jsxs("div",{className:"mb-6",children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:[d,s.jsx("span",{className:"ml-2 text-xs text-gray-500",children:"Collection"})]}),s.jsx("textarea",{className:"mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary sm:text-sm font-mono",value:h.length>0?JSON.stringify(h,null,2):"",onChange:y=>{const x=y.target.value.trim();if(!x){n(d,[]);return}try{const N=JSON.parse(x);n(d,Array.isArray(N)?N:[N])}catch{n(d,[x])}},placeholder:'Enter JSON array (e.g., ["item1", "item2"])',rows:4}),s.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"Enter data as a JSON array. Empty input will create an empty array."})]},d)}case"Range":{if(a)return s.jsxs("div",{className:"mb-6",children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:[d,s.jsx("span",{className:"ml-2 text-xs text-gray-500",children:"Single Value (Range Schema)"})]}),s.jsx("input",{type:"text",className:"mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary sm:text-sm",value:m,onChange:S=>n(d,S.target.value),placeholder:`Enter ${d} value`}),s.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"Enter a single value. The system will automatically handle range formatting."})]},d);let h={};if(m)try{h=typeof m=="string"?JSON.parse(m):m,(typeof h!="object"||Array.isArray(h))&&(h={})}catch{h={}}const y=Object.entries(h),x=()=>{const S=[...y,["",""]],p=Object.fromEntries(S);n(d,p)},N=(S,p,w)=>{const E=[...y];E[S]=[p,w];const C=Object.fromEntries(E);n(d,C)},_=S=>{const p=y.filter((E,C)=>C!==S),w=Object.fromEntries(p);n(d,w)};return s.jsxs("div",{className:"mb-6",children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:[d,s.jsx("span",{className:"ml-2 text-xs text-gray-500",children:"Range (Complex)"})]}),s.jsx("div",{className:"border border-gray-300 rounded-md p-4 bg-gray-50",children:s.jsxs("div",{className:"space-y-3",children:[y.length===0?s.jsx("p",{className:"text-sm text-gray-500 italic",children:"No key-value pairs added yet"}):y.map(([S,p],w)=>s.jsxs("div",{className:"flex items-center space-x-2",children:[s.jsx("input",{type:"text",placeholder:"Key",className:"flex-1 border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary sm:text-sm",value:S,onChange:E=>N(w,E.target.value,p)}),s.jsx("span",{className:"text-gray-500",children:":"}),s.jsx("input",{type:"text",placeholder:"Value",className:"flex-1 border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary sm:text-sm",value:p,onChange:E=>N(w,S,E.target.value)}),s.jsx("button",{type:"button",onClick:()=>_(w),className:"text-red-600 hover:text-red-800 p-1",title:"Remove this key-value pair",children:s.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},w)),s.jsxs("button",{type:"button",onClick:x,className:"inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary",children:[s.jsx("svg",{className:"w-4 h-4 mr-1",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 6v6m0 0v6m0-6h6m-6 0H6"})}),"Add Key-Value Pair"]})]})}),s.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"Add key-value pairs for this range field. Empty keys will be filtered out."})]},d)}default:return s.jsxs("div",{className:"mb-6",children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:[d,s.jsx("span",{className:"ml-2 text-xs text-gray-500",children:"Single"})]}),s.jsx("input",{type:"text",className:"mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary focus:border-primary sm:text-sm",value:m,onChange:h=>n(d,h.target.value),placeholder:`Enter ${d}`})]},d)}};return s.jsxs("div",{className:"bg-gray-50 rounded-lg p-6",children:[s.jsxs("h3",{className:"text-lg font-medium text-gray-900 mb-4",children:["Schema Fields",a&&s.jsx("span",{className:"ml-2 text-sm text-blue-600 font-normal",children:"(Range Schema - Single Values)"})]}),s.jsx("div",{className:"space-y-6",children:Object.entries(e).map(([d,c])=>l(d,c))}),a&&Object.keys(e).length===0&&s.jsx("p",{className:"text-sm text-gray-500 italic",children:"No additional fields to configure. Only the range key is required for this schema."})]})}function Fd({result:e}){return e?s.jsx("div",{className:"bg-gray-50 rounded-lg p-4 mt-4",children:s.jsx("pre",{className:"font-mono text-sm whitespace-pre-wrap",children:typeof e=="string"?e:JSON.stringify(e,null,2)})}):null}function Pd(e){const t=He(e);return{base:t,schema:al(t),mutation:Fl(t),security:Rl(t)}}Pd({enableCache:!0,enableLogging:!0,enableMetrics:!0});const Md={executeMutation:"Execute Mutation"},ei={rangeKeyRequired:"Range key is required",rangeKeyOptional:"Range key is optional for delete operations"},ti={label:"Range Key",backgroundColor:"bg-blue-50"};function Bd({onResult:e}){const t=fe(mr);fe(I=>I.auth);const[r,n]=v.useState(""),[a,l]=v.useState({}),[d,c]=v.useState("Insert"),[f,m]=v.useState(null),[h,y]=v.useState(""),[x,N]=v.useState({}),_=I=>{n(I),l({}),c("Insert"),y("")},S=(I,O)=>{l(R=>({...R,[I]:O}))},p=async I=>{if(I.preventDefault(),!r)return;const O=t.find(F=>F.name===r),R=d?Ea[d]||d.toLowerCase():"";if(!R)return;let $;Vt(O)?$=el(O,d,h,a):$={type:"mutation",schema:r,mutation_type:R,fields_and_values:d==="Delete"?{}:a,key_value:{hash:null,range:null}};try{const F=await tn.executeMutation($);if(!F.success)throw new Error(F.error||"Mutation failed");const H=F;m(H),e(H),H.success&&(l({}),y(""))}catch(F){const H={error:`Network error: ${F.message}`,details:F};m(H),e(H)}},w=r?t.find(I=>I.name===r):null,E=w?Vt(w):!1,C=w?It(w):null,T=!w||!Array.isArray(w.fields)?{}:(E?w.fields.filter(O=>O!==C):w.fields).reduce((O,R)=>(O[R]={},O),{}),M=!r||!d||d!=="Delete"&&Object.keys(a).length===0||E&&d!=="Delete"&&!h.trim();return s.jsxs("div",{className:"p-6",children:[s.jsxs("form",{onSubmit:p,className:"space-y-6",children:[s.jsx(Rd,{selectedSchema:r,mutationType:d,onSchemaChange:_,onTypeChange:c}),r&&E&&s.jsxs("div",{className:`${ti.backgroundColor} rounded-lg p-4`,children:[s.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-4",children:"Range Schema Configuration"}),s.jsx(gr,{name:"rangeKey",label:`${C} (${ti.label})`,value:h,onChange:y,placeholder:`Enter ${C} value`,required:d!=="Delete",error:x.rangeKey,helpText:d!=="Delete"?ei.rangeKeyRequired:ei.rangeKeyOptional,debounced:!0})]}),r&&s.jsx(Dd,{fields:T,mutationType:d,mutationData:a,onFieldChange:S,isRangeSchema:E}),s.jsx("div",{className:"flex justify-end pt-4",children:s.jsx("button",{type:"submit",className:`inline-flex items-center px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white ${M?"bg-gray-300 cursor-not-allowed":"bg-primary hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary"}`,disabled:M,children:Md.executeMutation})})]}),s.jsx(Fd,{result:f})]})}function ri({progress:e,className:t=""}){if(!e)return null;const r=l=>{switch(l){case"ValidatingConfig":return"bg-blue-500";case"PreparingSchemas":return"bg-indigo-500";case"FlatteningData":return"bg-purple-500";case"GettingAIRecommendation":return"bg-pink-500";case"SettingUpSchema":return"bg-red-500";case"GeneratingMutations":return"bg-orange-500";case"ExecutingMutations":return"bg-yellow-500";case"Completed":return"bg-green-500";case"Failed":return"bg-red-600";default:return"bg-gray-500"}},n=l=>{switch(l){case"ValidatingConfig":return"Validating Configuration";case"PreparingSchemas":return"Preparing Schemas";case"FlatteningData":return"Processing Data";case"GettingAIRecommendation":return"AI Analysis";case"SettingUpSchema":return"Setting Up Schema";case"GeneratingMutations":return"Generating Mutations";case"ExecutingMutations":return"Executing Mutations";case"Completed":return"Completed";case"Failed":return"Failed";default:return l}},a=(l,d)=>{const c=new Date(l),f=d?new Date(d):new Date,m=Math.round((f-c)/1e3);if(m<60)return`${m}s`;{const h=Math.floor(m/60),y=m%60;return`${h}m ${y}s`}};return s.jsxs("div",{className:`bg-white p-4 rounded-lg shadow border ${t}`,children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:`w-3 h-3 rounded-full ${r(e.current_step)}`}),s.jsx("h3",{className:"text-sm font-medium text-gray-900",children:n(e.current_step)})]}),s.jsx("div",{className:"text-xs text-gray-500",children:a(e.started_at,e.completed_at)})]}),s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex justify-between text-xs text-gray-600 mb-1",children:[s.jsxs("span",{children:[e.progress_percentage,"%"]}),s.jsx("span",{children:e.status_message})]}),s.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2",children:s.jsx("div",{className:`h-2 rounded-full transition-all duration-300 ${r(e.current_step)}`,style:{width:`${e.progress_percentage}%`}})})]}),e.results&&s.jsx("div",{className:"mt-3 p-3 bg-green-50 rounded-md",children:s.jsxs("div",{className:"text-sm text-green-800",children:[s.jsx("div",{className:"font-medium mb-1",children:"Ingestion Complete!"}),s.jsxs("div",{className:"text-xs space-y-1",children:[s.jsxs("div",{children:["Schema: ",e.results.schema_name]}),s.jsxs("div",{children:["New Schema: ",e.results.new_schema_created?"Yes":"No"]}),s.jsxs("div",{children:["Mutations Generated: ",e.results.mutations_generated]}),s.jsxs("div",{children:["Mutations Executed: ",e.results.mutations_executed]})]})]})}),e.error_message&&s.jsx("div",{className:"mt-3 p-3 bg-red-50 rounded-md",children:s.jsxs("div",{className:"text-sm text-red-800",children:[s.jsx("div",{className:"font-medium mb-1",children:"Ingestion Failed"}),s.jsx("div",{className:"text-xs",children:e.error_message})]})}),s.jsx("div",{className:"mt-4",children:s.jsx("div",{className:"flex justify-between text-xs text-gray-500",children:["ValidatingConfig","PreparingSchemas","FlatteningData","GettingAIRecommendation","SettingUpSchema","GeneratingMutations","ExecutingMutations"].map((l,d)=>{const c=e.current_step===l,f=e.progress_percentage>(d+1)*12.5;return s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("div",{className:`w-2 h-2 rounded-full mb-1 ${c||f?r(l):"bg-gray-300"}`}),s.jsx("span",{className:"text-xs text-center max-w-16 leading-tight",children:n(l).split(" ")[0]})]},l)})})})]})}function Ld({onResult:e}){const[t,r]=v.useState(""),[n,a]=v.useState(!0),[l,d]=v.useState(0),[c,f]=v.useState("default"),[m,h]=v.useState(!1),[y,x]=v.useState(null),[N,_]=v.useState(null),[S,p]=v.useState(null);v.useEffect(()=>{w()},[]),v.useEffect(()=>{if(!S)return;const T=async()=>{try{const I=await wt.getProgress(S);I.success&&I.data&&(_(I.data),I.data.is_complete&&(h(!1),p(null),I.data.results?e({success:!0,data:{schema_used:I.data.results.schema_name,new_schema_created:I.data.results.new_schema_created,mutations_generated:I.data.results.mutations_generated,mutations_executed:I.data.results.mutations_executed}}):I.data.error_message&&e({success:!1,error:I.data.error_message})))}catch(I){console.error("Failed to fetch progress:",I)}};T();const M=setInterval(T,200);return()=>clearInterval(M)},[S,e]);const w=async()=>{try{const T=await wt.getStatus();T.success&&x(T.data)}catch(T){console.error("Failed to fetch ingestion status:",T)}},E=async()=>{h(!0),p(null),e(null),_({progress_percentage:0,status_message:"Starting ingestion...",current_step:"ValidatingConfig",is_complete:!1,started_at:new Date().toISOString()}),await new Promise(T=>setTimeout(T,100));try{const T=JSON.parse(t),M={autoExecute:n,trustDistance:l,pubKey:c},I=await wt.processIngestion(T,M);I.success?I.data.progress_id?(p(I.data.progress_id),console.log("🟢 IngestionTab: Dispatching ingestion-started event",I.data.progress_id),window.dispatchEvent(new CustomEvent("ingestion-started",{detail:{progressId:I.data.progress_id}})),console.log("🟢 IngestionTab: Event dispatched")):(e(I.data),r(""),h(!1)):(e({success:!1,error:"Failed to process ingestion"}),h(!1),_(null))}catch(T){e({success:!1,error:T.message||"Failed to process ingestion"}),h(!1),_(null)}},C=()=>{const T=["Sarah Chen","Michael Rodriguez","Emily Johnson","David Kim","Lisa Wang","James Thompson","Maria Garcia","Alex Chen","Rachel Green","Tom Wilson","Jennifer Lee","Chris Anderson","Amanda Taylor","Ryan Murphy","Jessica Brown","Kevin Park","Nicole Davis","Brandon White","Stephanie Martinez","Daniel Liu"],M=["Technology","Programming","Web Development","Data Science","Machine Learning","Artificial Intelligence","Cloud Computing","DevOps","Cybersecurity","Mobile Development","UI/UX Design","Product Management","Startup Life","Career Advice","Industry Trends","Open Source","Software Architecture","Database Design","API Development","Testing"],I=[["javascript","webdev","tutorial"],["python","datascience","ai"],["react","frontend","javascript"],["nodejs","backend","api"],["docker","devops","deployment"],["aws","cloud","infrastructure"],["machine-learning","python","data"],["typescript","webdev","frontend"],["kubernetes","devops","containers"],["sql","database","backend"],["git","version-control","workflow"],["testing","quality","tdd"],["security","cybersecurity","best-practices"],["performance","optimization","web"],["mobile","ios","android"],["design","ux","ui"],["agile","management","process"],["career","advice","development"],["startup","entrepreneurship","business"],["opensource","community","contribution"],["architecture","scalability","design"]],O=[];for(let R=1;R<=100;R++){const $=T[Math.floor(Math.random()*T.length)],F=M[Math.floor(Math.random()*M.length)],H=I[Math.floor(Math.random()*I.length)],V=new Date,z=new Date(V.getTime()-6*30*24*60*60*1e3),L=z.getTime()+Math.random()*(V.getTime()-z.getTime()),Q=new Date(L).toISOString().split("T")[0],Y=[`Getting Started with ${F}: A Complete Guide`,`Advanced ${F} Techniques You Need to Know`,`Why ${F} is Changing the Industry`,`Building Scalable Applications with ${F}`,`The Future of ${F}: Trends and Predictions`,`Common ${F} Mistakes and How to Avoid Them`,`Best Practices for ${F} Development`,`From Beginner to Expert in ${F}`,`Case Study: Implementing ${F} in Production`,`${F} Tools and Frameworks Comparison`],ge=Y[Math.floor(Math.random()*Y.length)],Ue=[`In this comprehensive guide, we'll explore the fundamentals of ${F} and how it's revolutionizing the way we approach modern development. Whether you're a seasoned developer or just starting out, this article will provide valuable insights into best practices and real-world applications.

## Introduction to ${F}

${F} has become an essential part of today's technology landscape. With its powerful capabilities and growing ecosystem, it offers developers unprecedented opportunities to build robust and scalable solutions.

## Key Concepts

Understanding the core concepts of ${F} is crucial for success. Let's dive into the fundamental principles that make this technology so powerful:

1. **Core Architecture**: The foundation of ${F} lies in its well-designed architecture
2. **Performance Optimization**: Learn how to maximize efficiency and minimize resource usage
3. **Integration Patterns**: Discover best practices for connecting with other systems
4. **Security Considerations**: Implement robust security measures from the ground up

## Real-World Applications

Many companies have successfully implemented ${F} in their production environments. Here are some notable examples:

- **Case Study 1**: A major e-commerce platform reduced their response time by 60%
- **Case Study 2**: A fintech startup improved their scalability by 300%
- **Case Study 3**: A healthcare company enhanced their data processing capabilities

## Getting Started

Ready to dive in? Here's a step-by-step guide to get you started with ${F}:

\`\`\`javascript
// Example implementation
const example = new ${F}();
example.initialize();
example.process();
\`\`\`

## Conclusion

${F} represents a significant advancement in technology, offering developers powerful tools to build the next generation of applications. By following the principles and practices outlined in this guide, you'll be well-equipped to leverage ${F} in your own projects.

Remember, the key to success with ${F} is continuous learning and experimentation. Stay curious, keep building, and don't hesitate to explore new possibilities!`,`The landscape of ${F} is constantly evolving, and staying ahead of the curve requires a deep understanding of both current trends and emerging technologies. In this article, we'll examine the latest developments and provide actionable insights for developers looking to enhance their skills.

## Current State of ${F}

Today's ${F} ecosystem is more mature and feature-rich than ever before. With improved tooling, better documentation, and a growing community, developers have access to resources that make implementation more straightforward.

## Emerging Trends

Several key trends are shaping the future of ${F}:

- **Automation**: Increasing focus on automated workflows and CI/CD integration
- **Performance**: New optimization techniques that improve speed and efficiency
- **Security**: Enhanced security features and best practices
- **Scalability**: Better support for large-scale deployments

## Industry Impact

The adoption of ${F} across various industries has been remarkable:

- **Technology Sector**: 85% of tech companies have implemented ${F} solutions
- **Financial Services**: Improved transaction processing and risk management
- **Healthcare**: Enhanced patient data management and analysis
- **E-commerce**: Better customer experience and operational efficiency

## Implementation Strategies

When implementing ${F}, consider these strategic approaches:

1. **Phased Rollout**: Start with pilot projects before full deployment
2. **Team Training**: Invest in comprehensive team education
3. **Monitoring**: Implement robust monitoring and alerting systems
4. **Documentation**: Maintain detailed documentation for future reference

## Future Outlook

Looking ahead, ${F} is poised for continued growth and innovation. Key areas to watch include:

- Advanced AI integration
- Improved developer experience
- Enhanced security features
- Better cross-platform compatibility

The future of ${F} is bright, and developers who invest in learning these technologies now will be well-positioned for success in the years to come.`,`Building robust applications with ${F} requires more than just technical knowledge—it demands a strategic approach to architecture, design, and implementation. In this deep dive, we'll explore advanced techniques that will elevate your ${F} development skills.

## Architecture Patterns

Effective ${F} applications rely on well-established architectural patterns:

### Microservices Architecture
Breaking down monolithic applications into smaller, manageable services provides better scalability and maintainability.

### Event-Driven Design
Implementing event-driven patterns enables better decoupling and improved system responsiveness.

### Domain-Driven Design
Organizing code around business domains leads to more maintainable and understandable applications.

## Performance Optimization

Optimizing ${F} applications requires attention to multiple factors:

- **Caching Strategies**: Implement intelligent caching to reduce database load
- **Resource Management**: Optimize memory usage and CPU utilization
- **Network Optimization**: Minimize network overhead and latency
- **Database Tuning**: Optimize queries and indexing strategies

## Testing Strategies

Comprehensive testing is essential for reliable ${F} applications:

\`\`\`javascript
// Example test structure
describe('${F} Component', () => {
  it('should handle basic functionality', () => {
    const component = new ${F}Component();
    expect(component.process()).toBeDefined();
  });
  
  it('should handle edge cases', () => {
    const component = new ${F}Component();
    expect(() => component.process(null)).not.toThrow();
  });
});
\`\`\`

## Monitoring and Observability

Implementing comprehensive monitoring helps identify issues before they impact users:

- **Application Metrics**: Track performance indicators and user behavior
- **Error Tracking**: Monitor and alert on application errors
- **Log Analysis**: Centralize and analyze application logs
- **Health Checks**: Implement automated health monitoring

## Security Considerations

Security should be a primary concern when developing ${F} applications:

1. **Input Validation**: Always validate and sanitize user inputs
2. **Authentication**: Implement robust authentication mechanisms
3. **Authorization**: Control access to resources and functionality
4. **Data Protection**: Encrypt sensitive data both in transit and at rest

## Deployment Strategies

Successful deployment requires careful planning and execution:

- **Blue-Green Deployment**: Minimize downtime during updates
- **Canary Releases**: Gradually roll out changes to a subset of users
- **Feature Flags**: Control feature availability without code changes
- **Rollback Procedures**: Prepare for quick rollback in case of issues

## Conclusion

Mastering ${F} development is an ongoing journey that requires continuous learning and adaptation. By implementing these advanced techniques and best practices, you'll build more robust, scalable, and maintainable applications.

The key to success lies in understanding not just the technical aspects, but also the business context and user needs. Keep experimenting, stay updated with the latest developments, and always prioritize code quality and user experience.`],ze=Ue[Math.floor(Math.random()*Ue.length)];O.push({title:ge,content:ze,author:$,publish_date:Q,tags:H})}return O},A=T=>{const M={blogposts:C(),twitter:[{post_id:"tweet_1234567890",author:"@techinfluencer",author_id:"user_tech_001",content:"Just launched our new AI-powered database! 🚀 Real-time ingestion, automatic schema mapping, and zero-config setup. Check it out at folddb.io #database #AI #opensource",timestamp:"2024-10-21T14:32:00Z",likes:342,retweets:89,replies:23,views:12453,media:[{type:"image",url:"https://cdn.example.com/img1.jpg",alt:"FoldDB Dashboard Screenshot"}],mentions:["@opensource","@devtools"],hashtags:["database","AI","opensource"],reply_to:null,thread_position:1,engagement_rate:.034},{post_id:"tweet_1234567891",author:"@datascientist_pro",author_id:"user_ds_042",content:"Amazing work @techinfluencer! Been testing FoldDB for the past week. The automatic schema inference saved us hours of setup time. Here are my benchmarks:",timestamp:"2024-10-21T15:18:00Z",likes:156,retweets:34,replies:12,views:5621,media:[{type:"image",url:"https://cdn.example.com/benchmark.png",alt:"Performance Benchmarks"}],mentions:["@techinfluencer"],hashtags:["database","performance"],reply_to:"tweet_1234567890",thread_position:null,engagement_rate:.036}],instagram:[{post_id:"ig_post_987654321",username:"foodie_adventures",user_id:"ig_user_food_123",caption:"Best ramen in Tokyo! 🍜✨ The broth was simmering for 48 hours and you can taste every minute of it. Swipe for more pics! #tokyo #ramen #foodie #japan #travel",posted_at:"2024-10-20T09:45:00Z",location:{name:"Ichiran Ramen Shibuya",city:"Tokyo",country:"Japan",coordinates:{lat:35.6595,lng:139.7004}},media:[{type:"image",url:"https://cdn.instagram.example.com/ramen1.jpg",width:1080,height:1350,filter:"Valencia"},{type:"image",url:"https://cdn.instagram.example.com/ramen2.jpg",width:1080,height:1350,filter:"Valencia"},{type:"image",url:"https://cdn.instagram.example.com/ramen3.jpg",width:1080,height:1350,filter:"Valencia"}],likes:8234,comments_count:456,saves:892,shares:234,hashtags:["tokyo","ramen","foodie","japan","travel"],tagged_users:["@ramen_tokyo_guide","@japan_food_official"],comments:[{comment_id:"ig_comment_111",username:"tokyo_foodie",text:"Omg I was there last week! The tonkotsu broth is incredible 😍",timestamp:"2024-10-20T10:12:00Z",likes:45},{comment_id:"ig_comment_112",username:"ramen_lover_88",text:"Adding this to my Tokyo bucket list! 📝",timestamp:"2024-10-20T11:30:00Z",likes:23}]},{post_id:"ig_post_987654322",username:"fitness_journey_2024",user_id:"ig_user_fit_456",caption:"Day 287 of my fitness journey! 💪 Down 45 lbs and feeling stronger than ever. Remember: progress > perfection. What's your fitness goal? #fitness #transformation #motivation #workout",posted_at:"2024-10-21T06:00:00Z",location:{name:"Gold's Gym",city:"Los Angeles",country:"USA",coordinates:{lat:34.0522,lng:-118.2437}},media:[{type:"video",url:"https://cdn.instagram.example.com/workout_vid.mp4",thumbnail:"https://cdn.instagram.example.com/workout_thumb.jpg",duration:45,width:1080,height:1920}],likes:15672,comments_count:892,saves:2341,shares:567,hashtags:["fitness","transformation","motivation","workout"],tagged_users:["@personal_trainer_mike"],comments:[{comment_id:"ig_comment_113",username:"motivation_daily",text:"Incredible transformation! You're an inspiration! 🔥",timestamp:"2024-10-21T06:15:00Z",likes:234}]}],linkedin:[{post_id:"li_post_555666777",author:{name:"Sarah Chen",title:"CTO at TechVentures Inc.",profile_url:"linkedin.com/in/sarah-chen-cto",user_id:"li_user_sarah_123"},content:`Excited to announce that our team has successfully migrated our entire data infrastructure to a real-time event-driven architecture! 🎉

Key achievements:
• 10x reduction in data latency (from 5 minutes to 30 seconds)
• 40% cost savings on infrastructure
• Improved data quality through automated validation
• Seamless integration with our ML pipelines

Huge shoutout to the engineering team for their incredible work over the past 6 months. This wouldn't have been possible without their dedication and expertise.

Happy to share more details for anyone interested in event-driven architectures. Feel free to reach out!

#DataEngineering #EventDriven #TechLeadership #Innovation`,posted_at:"2024-10-21T13:00:00Z",article:null,media:[{type:"document",title:"Event-Driven Architecture: Our Journey",url:"https://cdn.linkedin.example.com/architecture_diagram.pdf",pages:12}],reactions:{like:1247,celebrate:342,support:89,insightful:156,love:67},comments_count:87,reposts:234,comments:[{comment_id:"li_comment_aaa111",author:{name:"Michael Roberts",title:"Senior Data Engineer at DataCorp",user_id:"li_user_mike_456"},text:"Congratulations Sarah! We're looking at a similar migration. Would love to connect and learn from your experience.",timestamp:"2024-10-21T13:45:00Z",reactions:{like:45}},{comment_id:"li_comment_aaa112",author:{name:"Jennifer Liu",title:"VP Engineering at CloudScale",user_id:"li_user_jen_789"},text:"Impressive results! The 10x latency improvement is remarkable. Did you use Apache Kafka or another streaming platform?",timestamp:"2024-10-21T14:20:00Z",reactions:{like:23,insightful:8}}],industries:["Technology","Data Engineering","Cloud Computing"],skills_mentioned:["Event-Driven Architecture","Data Engineering","ML Pipeline","Infrastructure"]},{post_id:"li_post_555666778",author:{name:"Marcus Thompson",title:"Product Manager | Ex-Google | Building the Future of Work",profile_url:"linkedin.com/in/marcus-thompson-pm",user_id:"li_user_marcus_234"},content:`5 lessons from shipping 100+ product features:

1. Talk to users BEFORE writing specs
2. Small iterations > big launches
3. Metrics don't tell the whole story
4. Technical debt is real debt
5. Celebrate wins with your team

What would you add to this list?

#ProductManagement #Technology #Leadership`,posted_at:"2024-10-21T10:30:00Z",article:null,media:[],reactions:{like:3421,celebrate:892,insightful:567,love:234},comments_count:234,reposts:789,comments:[],industries:["Product Management","Technology","Startups"],skills_mentioned:["Product Management","User Research","Agile"]}],tiktok:[{video_id:"tt_vid_777888999",username:"coding_tips_daily",user_id:"tt_user_code_001",caption:"3 JavaScript array methods that will blow your mind 🤯 #coding #javascript #programming #webdev #learntocode",posted_at:"2024-10-21T16:45:00Z",video:{url:"https://cdn.tiktok.example.com/video_js_tips.mp4",thumbnail:"https://cdn.tiktok.example.com/thumb_js_tips.jpg",duration:58,width:1080,height:1920,format:"mp4"},audio:{title:"Epic Tech Music",artist:"TechBeats Production",audio_id:"audio_tech_123"},statistics:{views:2834562,likes:342891,comments:12453,shares:45672,saves:89234,completion_rate:.78},hashtags:["coding","javascript","programming","webdev","learntocode"],mentions:[],effects:["Green Screen","Text Animation","Transition Effect"],comments:[{comment_id:"tt_comment_xyz1",username:"dev_beginner_22",text:"Just used .reduce() in my project and it worked perfectly! Thanks!",timestamp:"2024-10-21T17:00:00Z",likes:1234,replies_count:45},{comment_id:"tt_comment_xyz2",username:"senior_dev_10yrs",text:"Great explanation! Would love to see more advanced array methods",timestamp:"2024-10-21T17:30:00Z",likes:892,replies_count:23}]},{video_id:"tt_vid_777889000",username:"travel_with_emma",user_id:"tt_user_travel_042",caption:"POV: You visit Santorini for the first time 🇬🇷✨ #travel #santorini #greece #traveltok #wanderlust",posted_at:"2024-10-20T08:20:00Z",video:{url:"https://cdn.tiktok.example.com/video_santorini.mp4",thumbnail:"https://cdn.tiktok.example.com/thumb_santorini.jpg",duration:43,width:1080,height:1920,format:"mp4"},audio:{title:"Summer Vibes",artist:"Chill Beats Co.",audio_id:"audio_summer_456"},statistics:{views:8923451,likes:1234567,comments:34521,shares:123456,saves:234567,completion_rate:.92},hashtags:["travel","santorini","greece","traveltok","wanderlust"],mentions:["@visit_greece_official"],effects:["Color Grading","Slow Motion","Zoom Transition"],location:{name:"Santorini",country:"Greece",coordinates:{lat:36.3932,lng:25.4615}},comments:[{comment_id:"tt_comment_xyz3",username:"greece_lover_89",text:"Adding this to my 2025 bucket list! 😍",timestamp:"2024-10-20T09:00:00Z",likes:4521,replies_count:234}]}]};r(JSON.stringify(M[T],null,2))};return s.jsxs("div",{className:"space-y-4",children:[y&&s.jsx("div",{className:"bg-white p-3 rounded-lg shadow-sm border border-gray-200",children:s.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[s.jsx("span",{className:`px-2 py-1 rounded text-xs font-medium ${y.enabled&&y.configured?"bg-green-100 text-green-800":"bg-red-100 text-red-800"}`,children:y.enabled&&y.configured?"Ready":"Not Configured"}),s.jsxs("span",{className:"text-gray-600",children:[y.provider," · ",y.model]}),s.jsx("span",{className:"text-xs text-gray-500",children:"Configure AI settings using the Settings button in the header"})]})}),N&&s.jsx(ri,{progress:N}),s.jsxs("div",{className:"bg-white p-4 rounded-lg shadow",children:[s.jsxs("div",{className:"flex items-center justify-between mb-3",children:[s.jsx("h3",{className:"text-lg font-medium text-gray-900",children:"JSON Data"}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{onClick:()=>A("blogposts"),className:"px-2 py-1 bg-green-50 text-green-700 rounded text-xs hover:bg-green-100",children:"Blog Posts (100)"}),s.jsx("button",{onClick:()=>A("twitter"),className:"px-2 py-1 bg-blue-50 text-blue-700 rounded text-xs hover:bg-blue-100",children:"Twitter"}),s.jsx("button",{onClick:()=>A("instagram"),className:"px-2 py-1 bg-pink-50 text-pink-700 rounded text-xs hover:bg-pink-100",children:"Instagram"}),s.jsx("button",{onClick:()=>A("linkedin"),className:"px-2 py-1 bg-indigo-50 text-indigo-700 rounded text-xs hover:bg-indigo-100",children:"LinkedIn"}),s.jsx("button",{onClick:()=>A("tiktok"),className:"px-2 py-1 bg-purple-50 text-purple-700 rounded text-xs hover:bg-purple-100",children:"TikTok"})]})]}),s.jsx("textarea",{id:"jsonData",value:t,onChange:T=>r(T.target.value),placeholder:"Enter your JSON data here or load a sample...",className:"w-full h-64 p-3 border border-gray-300 rounded-md font-mono text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"})]}),s.jsx("div",{className:"bg-white p-4 rounded-lg shadow",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:n,onChange:T=>a(T.target.checked),className:"rounded"}),s.jsx("span",{className:"text-gray-700",children:"Auto-execute mutations"})]}),s.jsx("span",{className:"text-xs text-gray-500",children:"AI will analyze and automatically map data to schemas"})]}),s.jsx("button",{onClick:E,disabled:m||!t.trim(),className:`px-6 py-2.5 rounded font-medium transition-colors ${m||!t.trim()?"bg-gray-300 text-gray-500 cursor-not-allowed":"bg-blue-600 text-white hover:bg-blue-700"}`,children:m?"Processing...":"Process Data"})]})})]})}function $d({onResult:e}){const[t,r]=v.useState(!1),[n,a]=v.useState(null),[l,d]=v.useState(!0),[c,f]=v.useState(0),[m,h]=v.useState("default"),[y,x]=v.useState(!1),[N,_]=v.useState(null),[S,p]=v.useState(null),[w,E]=v.useState(null),[C,A]=v.useState(!1),[T,M]=v.useState("");v.useEffect(()=>{I()},[]),v.useEffect(()=>{if(!w)return;const L=async()=>{try{const Y=await wt.getProgress(w);Y.success&&Y.data&&(p(Y.data),Y.data.is_complete&&(x(!1),E(null),Y.data.results?e({success:!0,data:{schema_used:Y.data.results.schema_name,new_schema_created:Y.data.results.new_schema_created,mutations_generated:Y.data.results.mutations_generated,mutations_executed:Y.data.results.mutations_executed}}):Y.data.error_message&&e({success:!1,error:Y.data.error_message})))}catch(Y){console.error("Failed to fetch progress:",Y)}};L();const Q=setInterval(L,200);return()=>clearInterval(Q)},[w,e]);const I=async()=>{try{const L=await wt.getStatus();L.success&&_(L.data)}catch(L){console.error("Failed to fetch ingestion status:",L)}},O=v.useCallback(L=>{L.preventDefault(),L.stopPropagation(),r(!0)},[]),R=v.useCallback(L=>{L.preventDefault(),L.stopPropagation(),r(!1)},[]),$=v.useCallback(L=>{L.preventDefault(),L.stopPropagation()},[]),F=v.useCallback(L=>{L.preventDefault(),L.stopPropagation(),r(!1);const Q=L.dataTransfer.files;Q&&Q.length>0&&a(Q[0])},[]),H=v.useCallback(L=>{const Q=L.target.files;Q&&Q.length>0&&a(Q[0])},[]),V=async()=>{if(C){if(!T||!T.startsWith("s3://")){e({success:!1,error:"Please provide a valid S3 path (e.g., s3://bucket/path/to/file.json)"});return}}else if(!n){e({success:!1,error:"Please select a file to upload"});return}x(!0),E(null),e(null),p({progress_percentage:0,status_message:C?"Processing S3 file...":"Uploading file...",current_step:"ValidatingConfig",is_complete:!1,started_at:new Date().toISOString()}),await new Promise(L=>setTimeout(L,100));try{const L=new FormData;C?L.append("s3FilePath",T):L.append("file",n),L.append("autoExecute",l.toString()),L.append("trustDistance",c.toString()),L.append("pubKey",m);const Y=await(await fetch("/api/ingestion/upload",{method:"POST",body:L})).json();Y.success&&Y.progress_id?(E(Y.progress_id),console.log("🟢 FileUploadTab: Dispatching ingestion-started event",Y.progress_id),window.dispatchEvent(new CustomEvent("ingestion-started",{detail:{progressId:Y.progress_id}})),console.log("🟢 FileUploadTab: Event dispatched")):(e({success:!1,error:Y.error||"Failed to process file"}),x(!1),p(null))}catch(L){e({success:!1,error:L.message||"Failed to process file"}),x(!1),p(null)}},z=L=>{if(L===0)return"0 Bytes";const Q=1024,Y=["Bytes","KB","MB","GB"],ge=Math.floor(Math.log(L)/Math.log(Q));return Math.round(L/Math.pow(Q,ge)*100)/100+" "+Y[ge]};return s.jsxs("div",{className:"space-y-4",children:[N&&s.jsx("div",{className:"bg-white p-3 rounded-lg shadow-sm border border-gray-200",children:s.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[s.jsx("span",{className:`px-2 py-1 rounded text-xs font-medium ${N.enabled&&N.configured?"bg-green-100 text-green-800":"bg-red-100 text-red-800"}`,children:N.enabled&&N.configured?"Ready":"Not Configured"}),s.jsxs("span",{className:"text-gray-600",children:[N.provider," · ",N.model]}),s.jsx("span",{className:"text-xs text-gray-500",children:"Configure AI settings using the Settings button in the header"})]})}),S&&s.jsx(ri,{progress:S}),s.jsx("div",{className:"bg-white p-4 rounded-lg shadow",children:s.jsxs("div",{className:"flex items-center gap-6",children:[s.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Input Mode:"}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"radio",checked:!C,onChange:()=>A(!1),className:"rounded"}),s.jsx("span",{className:"text-sm text-gray-700",children:"Upload File"})]}),s.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[s.jsx("input",{type:"radio",checked:C,onChange:()=>A(!0),className:"rounded"}),s.jsx("span",{className:"text-sm text-gray-700",children:"S3 File Path"})]})]})}),C?s.jsxs("div",{className:"bg-white p-6 rounded-lg shadow",children:[s.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-4",children:"S3 File Path"}),s.jsxs("div",{className:"space-y-3",children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700",children:"Enter S3 file path"}),s.jsx("input",{type:"text",value:T,onChange:L=>M(L.target.value),placeholder:"s3://bucket-name/path/to/file.json",className:"w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"}),s.jsx("p",{className:"text-xs text-gray-500",children:"The file will be downloaded from S3 for processing without re-uploading"})]})]}):s.jsxs("div",{className:"bg-white p-6 rounded-lg shadow",children:[s.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-4",children:"Upload File"}),s.jsx("div",{className:`border-2 border-dashed rounded-lg p-12 text-center transition-colors ${t?"border-blue-500 bg-blue-50":"border-gray-300 bg-gray-50 hover:bg-gray-100"}`,onDragEnter:O,onDragOver:$,onDragLeave:R,onDrop:F,children:s.jsxs("div",{className:"space-y-4",children:[s.jsx("div",{className:"flex justify-center",children:s.jsx("svg",{className:"w-16 h-16 text-gray-400",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"})})}),n?s.jsxs("div",{className:"space-y-2",children:[s.jsx("p",{className:"text-lg font-medium text-gray-900",children:n.name}),s.jsx("p",{className:"text-sm text-gray-500",children:z(n.size)}),s.jsx("button",{onClick:()=>a(null),className:"text-sm text-blue-600 hover:text-blue-700 underline",children:"Remove file"})]}):s.jsxs("div",{children:[s.jsx("p",{className:"text-lg text-gray-700 mb-2",children:"Drag and drop a file here, or click to select"}),s.jsx("p",{className:"text-sm text-gray-500",children:"Supported formats: PDF, DOCX, TXT, CSV, JSON, XML, and more"})]}),s.jsx("input",{type:"file",id:"file-upload",className:"hidden",onChange:H}),!n&&s.jsx("label",{htmlFor:"file-upload",className:"inline-block px-6 py-3 bg-blue-600 text-white rounded-lg cursor-pointer hover:bg-blue-700 transition-colors",children:"Browse Files"})]})})]}),s.jsx("div",{className:"bg-white p-4 rounded-lg shadow",children:s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[s.jsx("input",{type:"checkbox",checked:l,onChange:L=>d(L.target.checked),className:"rounded"}),s.jsx("span",{className:"text-gray-700",children:"Auto-execute mutations"})]}),s.jsx("span",{className:"text-xs text-gray-500",children:"File will be converted to JSON and processed by AI"})]}),s.jsx("button",{onClick:V,disabled:y||!C&&!n||C&&!T,className:`px-6 py-2.5 rounded font-medium transition-colors ${y||!C&&!n||C&&!T?"bg-gray-300 text-gray-500 cursor-not-allowed":"bg-blue-600 text-white hover:bg-blue-700"}`,children:y?"Processing...":C?"Process S3 File":"Upload & Process"})]})}),s.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("svg",{className:"w-6 h-6 text-blue-600 flex-shrink-0 mt-0.5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),s.jsxs("div",{className:"text-sm text-blue-800",children:[s.jsx("p",{className:"font-medium mb-1",children:"How it works:"}),s.jsxs("ol",{className:"list-decimal list-inside space-y-1",children:[s.jsx("li",{children:C?"Provide an S3 file path (files already in S3 are not re-uploaded)":"Upload any file type (PDFs, documents, spreadsheets, etc.)"}),s.jsx("li",{children:"File is automatically converted to JSON using AI"}),s.jsx("li",{children:"AI analyzes the JSON and maps it to appropriate schemas"}),s.jsx("li",{children:"Data is stored in the database with the file location tracked"})]})]})]})})]})}function si(){const e=Qt(),t=fe(mr),r=fe(Gt),n=fe(Xs),a=fe(Oa),l=fe(ul),d=v.useCallback(async()=>{e(Qe({forceRefresh:!0}))},[e]),c=v.useCallback(m=>r.find(h=>h.name===m)||null,[r]),f=v.useCallback(m=>{const h=c(m);return h?Aa(h.state)===Ye.APPROVED:!1},[c]);return v.useEffect(()=>{l.isValid||(console.log("🟡 useApprovedSchemas: Cache invalid, fetching schemas"),e(Qe()))},[e]),{approvedSchemas:t,isLoading:n,error:a,refetch:d,getSchemaByName:c,isSchemaApproved:f,allSchemas:r}}function Ud({r:e}){var t,r;return s.jsxs("tr",{className:"border-t",children:[s.jsx("td",{className:"px-2 py-1 text-xs text-gray-600",children:((t=e.key_value)==null?void 0:t.hash)??""}),s.jsx("td",{className:"px-2 py-1 text-xs text-gray-600",children:((r=e.key_value)==null?void 0:r.range)??""}),s.jsx("td",{className:"px-2 py-1 text-xs font-mono text-gray-800",children:e.schema_name}),s.jsx("td",{className:"px-2 py-1 text-xs text-gray-800",children:e.field}),s.jsx("td",{className:"px-2 py-1 text-xs text-gray-800 whitespace-pre-wrap break-words",children:Kd(e.value)})]})}function Kd(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function Vd({onResult:e}){const{approvedSchemas:t,isLoading:r,refetch:n}=si(),[a,l]=v.useState(""),[d,c]=v.useState(!1),[f,m]=v.useState([]),[h,y]=v.useState(null),[x,N]=v.useState(()=>new Set),[_,S]=v.useState(()=>new Map);v.useEffect(()=>{n()},[n]);const p=v.useCallback(async()=>{c(!0),y(null);try{const I=await Bl.search(a);I.success?(m(I.data||[]),e({success:!0,data:I.data||[]})):(y(I.error||"Search failed"),e({error:I.error||"Search failed",status:I.status}))}catch(I){y(I.message||"Network error"),e({error:I.message||"Network error"})}finally{c(!1)}},[a,e]),w=v.useCallback(I=>{if(!I)return[];const O=I.fields;return Array.isArray(O)?O.slice():O&&typeof O=="object"?Object.keys(O):[]},[]),E=v.useMemo(()=>{const I=new Map;return(t||[]).forEach(O=>I.set(O.name,O)),I},[t]),C=v.useCallback((I,O)=>{const R=(O==null?void 0:O.hash)??"",$=(O==null?void 0:O.range)??"";return`${I}|${R}|${$}`},[]),A=v.useCallback(I=>{const O=I==null?void 0:I.hash,R=I==null?void 0:I.range;if(O&&R)return sd(O,R);if(O)return pr(O);if(R)return pr(R)},[]),T=v.useCallback(async(I,O)=>{const R=E.get(I),$=w(R),F=A(O),H={schema_name:I,fields:$};F&&(H.filter=F);const V=await tn.executeQuery(H);if(!V.success)throw new Error(V.error||"Query failed");const z=Array.isArray(V.data)?V.data:[],L=z.find(Q=>{var ae,ce;const Y=((ae=Q==null?void 0:Q.key)==null?void 0:ae.hash)??null,ge=((ce=Q==null?void 0:Q.key)==null?void 0:ce.range)??null,Ue=(O==null?void 0:O.hash)??null,ze=(O==null?void 0:O.range)??null;return String(Y||"")===String(Ue||"")&&String(ge||"")===String(ze||"")})||z[0];return(L==null?void 0:L.fields)||(L&&typeof L=="object"?L:{})},[E,w,A]),M=v.useCallback(async()=>{const I=new Map;for(const $ of f){const F=C($.schema_name,$.key_value);I.has(F)||I.set(F,$)}const O=Array.from(I.values()),R=new Map(_);await Promise.all(O.map(async $=>{const F=C($.schema_name,$.key_value);if(!R.has(F))try{const H=await T($.schema_name,$.key_value);R.set(F,H)}catch{R.set(F,{})}})),S(R)},[f,_,C,T]);return v.useEffect(()=>{f.length>0&&M().catch(()=>{})},[f,M]),s.jsxs("div",{className:"p-6 space-y-4",children:[s.jsxs("div",{className:"bg-white p-4 rounded-lg shadow",children:[s.jsxs("div",{className:"mb-3",children:[s.jsx("h3",{className:"text-lg font-medium text-gray-900",children:"Native Index Search"}),s.jsx("p",{className:"text-xs text-gray-500",children:"Search the database-native word index across all approved schemas."})]}),s.jsxs("div",{className:"flex gap-2 items-center",children:[s.jsx("input",{type:"text",value:a,onChange:I=>l(I.target.value),placeholder:"Enter search term (e.g. jennifer)",className:"flex-1 px-3 py-2 border rounded-md text-sm"}),s.jsx("button",{onClick:p,disabled:d||!a.trim(),className:`px-4 py-2 rounded text-sm ${d||!a.trim()?"bg-gray-300 text-gray-600":"bg-blue-600 text-white hover:bg-blue-700"}`,children:d?"Searching...":"Search"})]})]}),s.jsxs("div",{className:"bg-white p-4 rounded-lg shadow",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[s.jsx("h4",{className:"text-md font-medium text-gray-900",children:"Search Results"}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("span",{className:"text-xs text-gray-500",children:[f.length," matches"]}),f.length>0&&s.jsx("button",{type:"button",className:"text-xs px-2 py-1 rounded border border-gray-300 hover:bg-gray-100",onClick:()=>M(),children:"Refresh Details"})]})]}),h&&s.jsx("div",{className:"mb-2 p-2 bg-red-50 border border-red-200 text-xs text-red-700 rounded",children:h}),s.jsx("div",{className:"overflow-auto max-h-[450px]",children:s.jsxs("table",{className:"min-w-full text-left text-xs",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"text-gray-500",children:[s.jsx("th",{className:"px-2 py-1",children:"Hash"}),s.jsx("th",{className:"px-2 py-1",children:"Range"}),s.jsx("th",{className:"px-2 py-1",children:"Schema"}),s.jsx("th",{className:"px-2 py-1",children:"Field"}),s.jsx("th",{className:"px-2 py-1",children:"Value"}),s.jsx("th",{className:"px-2 py-1"})]})}),s.jsxs("tbody",{children:[f.map((I,O)=>{const R=C(I.schema_name,I.key_value),$=x.has(R),F=_.get(R);return s.jsxs(s.Fragment,{children:[s.jsx(Ud,{r:I},`${R}-row`),s.jsxs("tr",{className:"border-b",children:[s.jsx("td",{colSpan:5}),s.jsx("td",{className:"px-2 py-1 text-right",children:s.jsx("button",{type:"button",className:"text-xs px-2 py-1 rounded border border-gray-300 hover:bg-gray-100",onClick:async()=>{const H=new Set(x);if(H.has(R)?H.delete(R):H.add(R),N(H),!_.has(R))try{const V=await T(I.schema_name,I.key_value);S(z=>new Map(z).set(R,V))}catch{}},children:$?"Hide Data":"Show Data"})})]},`${R}-actions`),$&&s.jsx("tr",{children:s.jsx("td",{colSpan:6,className:"px-2 pb-3",children:s.jsx("div",{className:"ml-2 bg-gray-50 border rounded",children:s.jsx(FieldsTable,{fields:F||{}})})})},`${R}-details`)]})}),f.length===0&&s.jsx("tr",{children:s.jsx("td",{colSpan:5,className:"px-2 py-3 text-center text-gray-500",children:"No results"})})]})]})})]})]})}const ni={InProgress:{color:"text-blue-700 bg-blue-50",icon:"⏳"},Completed:{color:"text-green-700 bg-green-50",icon:"✅"},Failed:{color:"text-red-700 bg-red-50",icon:"❌"},default:{color:"text-gray-700 bg-gray-50",icon:"❓"}},ai=e=>new Date(e*1e3).toLocaleString(),Hd=(e,t)=>{const r=(t||Math.floor(Date.now()/1e3))-e;return r<60?`${r}s`:r<3600?`${Math.floor(r/60)}m ${r%60}s`:`${Math.floor(r/3600)}h ${Math.floor(r%3600/60)}m`},zd=(e,t)=>{const r=e+t;return r===0?"N/A":`${Math.round(e/r*100)}%`},Gd=({backfill:e})=>{const t=ni[e.status]||ni.default;return s.jsxs("div",{className:`p-3 rounded-lg border ${t.color}`,children:[s.jsxs("div",{className:"flex justify-between items-start mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-xl",children:t.icon}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold",children:e.transform_id}),s.jsxs("div",{className:"text-xs opacity-80",children:["Source: ",e.schema_name]})]})]}),s.jsxs("div",{className:"text-xs text-right",children:[s.jsxs("div",{children:["Started: ",ai(e.start_time)]}),s.jsxs("div",{children:["Duration: ",Hd(e.start_time,e.end_time)]})]})]}),s.jsx(qd,{backfill:e}),e.status==="InProgress"&&e.mutations_expected>0&&s.jsx(Wd,{backfill:e})]})},qd=({backfill:e})=>{const{status:t}=e;return t==="InProgress"?s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 text-sm mt-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-medium",children:"Mutations:"})," ",e.mutations_completed," / ",e.mutations_expected]}),e.mutations_failed>0&&s.jsxs("div",{className:"text-red-600",children:[s.jsx("span",{className:"font-medium",children:"Failed:"})," ",e.mutations_failed]})]}):t==="Completed"?s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 text-sm mt-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-medium",children:"Mutations:"})," ",e.mutations_completed]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium",children:"Records:"})," ",e.records_produced]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium",children:"Completed:"})," ",e.end_time&&ai(e.end_time)]})]}):t==="Failed"&&e.error?s.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-2 text-sm mt-2",children:s.jsxs("div",{className:"col-span-2 md:col-span-3",children:[s.jsx("span",{className:"font-medium",children:"Error:"})," ",e.error]})}):null},Wd=({backfill:e})=>{const t=Math.round(e.mutations_completed/e.mutations_expected*100);return s.jsxs("div",{className:"mt-2",children:[s.jsx("div",{className:"w-full bg-gray-200 rounded-full h-2",children:s.jsx("div",{className:"bg-blue-600 h-2 rounded-full transition-all duration-300",style:{width:`${t}%`}})}),s.jsxs("div",{className:"text-xs text-right mt-1",children:[t,"% complete"]})]})},Yd=()=>{const[e,t]=v.useState([]),[r,n]=v.useState(null),[a,l]=v.useState(!0),[d,c]=v.useState(null),[f,m]=v.useState(!1),h=v.useCallback(async()=>{try{const p=await je.getAllBackfills();if(!(p!=null&&p.success)||!p.data)throw new Error((p==null?void 0:p.error)||"Failed to fetch backfills - invalid response");t(p.data),c(null)}catch(p){throw console.error("Failed to fetch backfills:",p),c(p.message||"Failed to load backfills"),p}},[]),y=v.useCallback(async()=>{try{const p=await je.getBackfillStatistics();if(!(p!=null&&p.success)||!p.data)throw new Error((p==null?void 0:p.error)||"Failed to fetch backfill statistics - invalid response");n(p.data),c(null)}catch(p){throw console.error("Failed to fetch backfill statistics:",p),c(p.message||"Failed to load statistics"),p}finally{l(!1)}},[]);v.useEffect(()=>{h(),y();const p=setInterval(()=>{h(),y()},3e3);return()=>clearInterval(p)},[h,y]);const x=e.filter(p=>p.status==="InProgress"),N=e.filter(p=>p.status==="Completed"),_=e.filter(p=>p.status==="Failed"),S=f?e:x;return a?s.jsx("div",{className:"bg-gray-50 p-4 rounded-lg",children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-gray-600 mr-2"}),s.jsx("span",{className:"text-gray-800",children:"Loading backfill information..."})]})}):d?s.jsx("div",{className:"bg-red-50 p-4 rounded-lg",role:"alert",children:s.jsxs("span",{className:"text-red-800",children:["Error: ",d]})}):s.jsxs("div",{className:"space-y-4",children:[r&&s.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[s.jsx("h3",{className:"text-md font-medium text-gray-800 mb-3",children:"Backfill Statistics"}),s.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-sm",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-gray-600",children:"Total Mutations"}),s.jsx("div",{className:"text-lg font-semibold text-gray-900",children:r.total_mutations_completed})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-gray-600",children:"Success Rate"}),s.jsx("div",{className:"text-lg font-semibold text-green-700",children:zd(r.total_mutations_completed,r.total_mutations_failed)})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-gray-600",children:"Backfills"}),s.jsx("div",{className:"text-lg font-semibold text-blue-700",children:r.total_backfills})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-gray-600",children:"Failures"}),s.jsx("div",{className:"text-lg font-semibold text-red-700",children:r.total_mutations_failed})]})]})]}),s.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h3",{className:"text-md font-medium text-gray-800",children:"Backfills"}),s.jsxs("div",{className:"flex items-center gap-4",children:[s.jsxs("div",{className:"text-sm text-gray-600",children:["Active: ",x.length," | Completed: ",N.length," | Failed: ",_.length]}),s.jsx("button",{onClick:()=>m(!f),className:"px-3 py-1 text-sm bg-gray-200 text-gray-800 rounded hover:bg-gray-300",children:f?"Show Active Only":"Show All"})]})]}),S.length===0?s.jsx("div",{className:"text-gray-600 text-sm",children:f?"No backfills recorded":"No active backfills"}):s.jsx("div",{className:"space-y-3",children:S.map(p=>s.jsx(Gd,{backfill:p},`${p.transform_id}-${p.start_time}`))})]})]})},Qd={queue:[],length:0,isEmpty:!0},Jd=(e={})=>{const t=Array.isArray(e.queue)?e.queue:[],r=typeof e.length=="number"?e.length:t.length,n=typeof e.isEmpty=="boolean"?e.isEmpty:t.length===0;return{queue:t,length:r,isEmpty:n}},Zd=({onResult:e})=>{const[t,r]=v.useState(Qd),[n,a]=v.useState({}),[l,d]=v.useState({}),[c,f]=v.useState(!1),[m,h]=v.useState(null),[y,x]=v.useState([]),N=v.useCallback(async()=>{f(!0),h(null);try{const p=await je.getTransforms();if(p!=null&&p.success&&p.data){const w=p.data,E=w&&typeof w=="object"&&!Array.isArray(w)?Object.entries(w).map(([C,A])=>({transform_id:C,...A})):Array.isArray(w)?w:[];x(E)}else{const w=(p==null?void 0:p.error)||"Failed to load transforms";h(w),x([])}}catch(p){console.error("Failed to fetch transforms:",p),h(p.message||"Failed to load transforms"),x([])}finally{f(!1)}},[]),_=v.useCallback(async()=>{try{const p=await je.getQueue();p!=null&&p.success&&p.data&&r(Jd(p.data))}catch(p){console.error("Failed to fetch transform queue info:",p)}},[]);v.useEffect(()=>{N(),_();const p=setInterval(_,5e3);return()=>clearInterval(p)},[N,_]);const S=v.useCallback(async(p,w)=>{var C;const E=w?`${p}.${w}`:p;a(A=>({...A,[E]:!0})),d(A=>({...A,[E]:null}));try{const A=await je.addToQueue(E);if(!(A!=null&&A.success)){const T=((C=A==null?void 0:A.data)==null?void 0:C.message)||(A==null?void 0:A.error)||"Failed to add transform to queue";throw new Error(T)}typeof e=="function"&&e({success:!0,transformId:E}),await _()}catch(A){console.error("Failed to add transform to queue:",A),d(T=>({...T,[E]:A.message||"Failed to add transform to queue"}))}finally{a(A=>({...A,[E]:!1}))}},[_,e]);return s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsx("h2",{className:"text-xl font-semibold text-gray-800",children:"Transforms"}),s.jsxs("div",{className:"text-sm text-gray-600",children:["Queue Status: ",t.isEmpty?"Empty":`${t.length} transform(s) queued`]})]}),s.jsx(Yd,{}),!t.isEmpty&&s.jsxs("div",{className:"bg-blue-50 p-4 rounded-lg","data-testid":"transform-queue",children:[s.jsx("h3",{className:"text-md font-medium text-blue-800 mb-2",children:"Transform Queue"}),s.jsx("ul",{className:"list-disc list-inside space-y-1",children:t.queue.map((p,w)=>s.jsx("li",{className:"text-blue-700",children:p},`${p}-${w}`))})]}),c&&s.jsx("div",{className:"bg-blue-50 p-4 rounded-lg",role:"status",children:s.jsxs("div",{className:"flex items-center",children:[s.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-blue-600 mr-2"}),s.jsx("span",{className:"text-blue-800",children:"Loading transforms..."})]})}),m&&s.jsx("div",{className:"bg-red-50 p-4 rounded-lg",role:"alert",children:s.jsxs("div",{className:"flex items-center",children:[s.jsxs("span",{className:"text-red-800",children:["Error loading transforms: ",m]}),s.jsx("button",{onClick:N,className:"ml-4 px-3 py-1 text-sm bg-red-500 text-white rounded hover:bg-red-600",children:"Retry"})]})}),!c&&!m&&y.length>0&&s.jsx("div",{className:"space-y-4",children:y.map((p,w)=>{var V;const E=p.transform_id||`transform-${w}`,C=n[E],A=l[E],T=p.name||((V=p.transform_id)==null?void 0:V.split(".")[0])||"Unknown",M=p.schema_type;let I="Single",O="bg-gray-100 text-gray-800";M!=null&&M.Range?(I="Range",O="bg-blue-100 text-blue-800"):M!=null&&M.HashRange&&(I="HashRange",O="bg-purple-100 text-purple-800");const R=p.key,$=p.transform_fields||{},F=Object.keys($).length,H=Object.keys($);return s.jsxs("div",{className:"bg-white p-4 rounded-lg shadow border-l-4 border-blue-500",children:[s.jsx("div",{className:"flex justify-between items-start mb-3",children:s.jsxs("div",{className:"flex-1",children:[s.jsx("h3",{className:"text-lg font-semibold text-gray-900",children:T}),s.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[s.jsx("span",{className:`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${O}`,children:I}),F>0&&s.jsxs("span",{className:"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800",children:[F," field",F!==1?"s":""]})]}),H.length>0&&s.jsxs("div",{className:"mt-2 text-sm text-gray-600",children:[s.jsx("span",{className:"font-medium",children:"Fields:"})," ",H.join(", ")]})]})}),s.jsxs("div",{className:"mt-3 space-y-3",children:[R&&s.jsxs("div",{className:"bg-blue-50 rounded p-3",children:[s.jsx("div",{className:"text-sm font-medium text-blue-900 mb-1",children:"Key Configuration:"}),s.jsxs("div",{className:"text-sm text-blue-800 space-y-1",children:[R.hash_field&&s.jsxs("div",{children:[s.jsx("span",{className:"font-medium",children:"Hash Key:"})," ",R.hash_field]}),R.range_field&&s.jsxs("div",{children:[s.jsx("span",{className:"font-medium",children:"Range Key:"})," ",R.range_field]}),!R.hash_field&&!R.range_field&&R.key_field&&s.jsxs("div",{children:[s.jsx("span",{className:"font-medium",children:"Key:"})," ",R.key_field]})]})]}),F>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-gray-700 mb-2",children:"Transform Fields:"}),s.jsx("div",{className:"bg-gray-50 rounded p-3 space-y-2",children:Object.entries($).map(([z,L])=>s.jsxs("div",{className:"border-l-2 border-gray-300 pl-3",children:[s.jsx("div",{className:"font-medium text-gray-900 text-sm",children:z}),s.jsx("div",{className:"text-gray-600 font-mono text-xs mt-1 break-all",children:L})]},z))})]})]}),s.jsxs("div",{className:"mt-4 flex items-center gap-3",children:[s.jsx("button",{onClick:()=>S(E,null),disabled:C,className:`px-4 py-2 text-sm font-medium rounded-md text-white ${C?"bg-blue-300 cursor-not-allowed":"bg-blue-600 hover:bg-blue-700"}`,children:C?"Adding...":"Add to Queue"}),A&&s.jsxs("span",{className:"text-sm text-red-600",children:["Error: ",A]})]})]},E)})}),!c&&!m&&y.length===0&&s.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg",children:[s.jsx("p",{className:"text-gray-600",children:"No transforms registered"}),s.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"Register a transform in a schema to view it here and add it to the processing queue."})]})]})};function Xd({title:e,titleId:t,...r},n){return q.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},r),e?q.createElement("title",{id:t},e):null,q.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"m4.5 12.75 6 6 9-13.5"}))}const nn=q.forwardRef(Xd);function eu({title:e,titleId:t,...r},n){return q.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},r),e?q.createElement("title",{id:t},e):null,q.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.666 3.888A2.25 2.25 0 0 0 13.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 0 1-.75.75H9a.75.75 0 0 1-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 0 1-2.25 2.25H6.75A2.25 2.25 0 0 1 4.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 0 1 1.927-.184"}))}const ii=q.forwardRef(eu);function tu({title:e,titleId:t,...r},n){return q.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},r),e?q.createElement("title",{id:t},e):null,q.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"}))}const oi=q.forwardRef(tu);function ru({title:e,titleId:t,...r},n){return q.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},r),e?q.createElement("title",{id:t},e):null,q.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.75 5.25a3 3 0 0 1 3 3m3 0a6 6 0 0 1-7.029 5.912c-.563-.097-1.159.026-1.563.43L10.5 17.25H8.25v2.25H6v2.25H2.25v-2.818c0-.597.237-1.17.659-1.591l6.499-6.499c.404-.404.527-1 .43-1.563A6 6 0 1 1 21.75 8.25Z"}))}const an=q.forwardRef(ru);function su({title:e,titleId:t,...r},n){return q.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:n,"aria-labelledby":t},r),e?q.createElement("title",{id:t},e):null,q.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12.75 11.25 15 15 9.75m-3-7.036A11.959 11.959 0 0 1 3.598 6 11.99 11.99 0 0 0 3 9.749c0 5.592 3.824 10.29 9 11.623 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.571-.598-3.751h-.152c-3.196 0-6.1-1.248-8.25-3.285Z"}))}const nu=q.forwardRef(su);function au({onResult:e}){const t=Qt(),r=fe(O=>O.auth),{isAuthenticated:n,systemPublicKey:a,systemKeyId:l,privateKey:d,isLoading:c,error:f}=r,m=d?Uc(d):null,[h,y]=v.useState(null),[x,N]=v.useState(""),[_,S]=v.useState(!1),[p,w]=v.useState(null),[E,C]=v.useState(!1),A=async(O,R)=>{try{await navigator.clipboard.writeText(O),y(R),setTimeout(()=>y(null),2e3)}catch($){console.error("Failed to copy:",$)}},T=async()=>{if(!x.trim()){w({valid:!1,error:"Please enter a private key"});return}S(!0);try{const R=(await t(Jr(x.trim())).unwrap()).isAuthenticated;w({valid:R,error:R?null:"Private key does not match the system public key"}),R&&console.log("Private key validation successful")}catch(O){w({valid:!1,error:`Validation failed: ${O.message}`})}finally{S(!1)}},M=()=>{N(""),w(null),C(!1)},I=()=>{M(),t(Vc())};return s.jsxs("div",{className:"p-4 bg-white rounded-lg shadow",children:[s.jsx("h2",{className:"text-xl font-semibold mb-4",children:"Key Management"}),s.jsx("div",{className:"bg-blue-50 border border-blue-200 rounded-md p-4 mb-6",children:s.jsxs("div",{className:"flex items-start",children:[s.jsx(nu,{className:"h-5 w-5 text-blue-400 mr-2 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm text-blue-700 flex-1",children:[s.jsx("p",{className:"font-medium",children:"Current System Public Key:"}),c?s.jsx("p",{className:"text-blue-600",children:"Loading..."}):a?s.jsxs("div",{className:"mt-2",children:[s.jsxs("div",{className:"flex",children:[s.jsx("input",{type:"text",value:a&&a!=="null"?a:"",readOnly:!0,className:"flex-1 px-2 py-1 border border-blue-300 rounded-l-md bg-blue-50 text-xs font-mono"}),s.jsx("button",{onClick:()=>A(a,"system"),className:"px-2 py-1 border border-l-0 border-blue-300 rounded-r-md bg-white hover:bg-blue-50 focus:outline-none focus:ring-2 focus:ring-blue-500",children:h==="system"?s.jsx(nn,{className:"h-3 w-3 text-green-600"}):s.jsx(ii,{className:"h-3 w-3 text-blue-500"})})]}),l&&s.jsxs("p",{className:"text-xs text-blue-600 mt-1",children:["Key ID: ",l]}),n&&s.jsx("p",{className:"text-xs text-green-600 mt-1",children:"🔓 Authenticated - Private key loaded!"})]}):s.jsx("p",{className:"text-blue-600 mt-1",children:"No system public key available."})]})]})}),n&&m&&s.jsx("div",{className:"bg-green-50 border border-green-200 rounded-md p-4 mb-6",children:s.jsxs("div",{className:"flex items-start",children:[s.jsx(an,{className:"h-5 w-5 text-green-400 mr-2 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm text-green-700 flex-1",children:[s.jsx("p",{className:"font-medium",children:"Current Private Key (Auto-loaded from Node)"}),s.jsx("p",{className:"mt-1",children:"Your private key has been automatically loaded from the backend node."}),s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex",children:[s.jsx("textarea",{value:m,readOnly:!0,className:"flex-1 px-3 py-2 border border-green-300 rounded-l-md bg-green-50 text-xs font-mono resize-none",rows:3,placeholder:"Private key will appear here..."}),s.jsx("button",{onClick:()=>A(m,"private"),className:"px-3 py-2 border border-l-0 border-green-300 rounded-r-md bg-white hover:bg-green-50 focus:outline-none focus:ring-2 focus:ring-green-500",title:"Copy private key",children:h==="private"?s.jsx(nn,{className:"h-3 w-3 text-green-600"}):s.jsx(ii,{className:"h-3 w-3 text-green-500"})})]}),s.jsx("p",{className:"text-xs text-green-600 mt-1",children:"🔓 Authenticated - Private key loaded from node!"})]})]})]})}),a&&!n&&!m&&s.jsx("div",{className:"bg-yellow-50 border border-yellow-200 rounded-md p-4 mb-6",children:s.jsxs("div",{className:"flex items-start",children:[s.jsx(an,{className:"h-5 w-5 text-yellow-400 mr-2 flex-shrink-0 mt-0.5"}),s.jsxs("div",{className:"text-sm text-yellow-700 flex-1",children:[s.jsx("p",{className:"font-medium",children:"Import Private Key"}),s.jsx("p",{className:"mt-1",children:"You have a registered public key but no local private key. Enter your private key to restore access."}),E?s.jsxs("div",{className:"mt-3 space-y-3",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-xs font-medium text-yellow-700 mb-1",children:"Private Key (Base64)"}),s.jsx("textarea",{value:x,onChange:O=>N(O.target.value),placeholder:"Enter your private key here...",className:"w-full px-3 py-2 border border-yellow-300 rounded-md focus:outline-none focus:ring-2 focus:ring-yellow-500 text-xs font-mono",rows:3})]}),p&&s.jsx("div",{className:`p-2 rounded-md text-xs ${p.valid?"bg-green-50 border border-green-200 text-green-700":"bg-red-50 border border-red-200 text-red-700"}`,children:p.valid?s.jsxs("div",{className:"flex items-center",children:[s.jsx(nn,{className:"h-4 w-4 text-green-600 mr-1"}),s.jsx("span",{children:"Private key matches system public key!"})]}):s.jsxs("div",{className:"flex items-center",children:[s.jsx(oi,{className:"h-4 w-4 text-red-600 mr-1"}),s.jsx("span",{children:p.error})]})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{onClick:T,disabled:_||!x.trim(),className:"inline-flex items-center px-3 py-2 border border-transparent text-xs font-medium rounded-md shadow-sm text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 disabled:opacity-50",children:_?"Validating...":"Validate & Import"}),s.jsx("button",{onClick:I,className:"inline-flex items-center px-3 py-2 border border-gray-300 text-xs font-medium rounded-md shadow-sm text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-yellow-500",children:"Cancel"})]}),s.jsx("div",{className:"bg-red-50 border border-red-200 rounded-md p-2",children:s.jsxs("div",{className:"flex",children:[s.jsx(oi,{className:"h-4 w-4 text-red-400 mr-1 flex-shrink-0"}),s.jsxs("div",{className:"text-xs text-red-700",children:[s.jsx("p",{className:"font-medium",children:"Security Warning:"}),s.jsx("p",{children:"Only enter your private key on trusted devices. Never share or store private keys in plain text."})]})]})})]}):s.jsxs("button",{onClick:()=>C(!0),className:"mt-3 inline-flex items-center px-3 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-yellow-600 hover:bg-yellow-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-yellow-500",children:[s.jsx(an,{className:"h-4 w-4 mr-1"}),"Import Private Key"]})]})]})})]})}function iu({isOpen:e,onClose:t}){const[r,n]=v.useState("ai"),[a,l]=v.useState("OpenRouter"),[d,c]=v.useState(""),[f,m]=v.useState("anthropic/claude-3.5-sonnet"),[h,y]=v.useState("https://openrouter.ai/api/v1"),[x,N]=v.useState("llama3"),[_,S]=v.useState("http://localhost:11434"),[p,w]=v.useState(null),[E,C]=v.useState(!1),{environment:A,setEnvironment:T}=_l(),[M,I]=v.useState(A.id),[O,R]=v.useState({}),[$,F]=v.useState({}),[H,V]=v.useState("local"),[z,L]=v.useState("data"),[Q,Y]=v.useState("DataFoldStorage"),[ge,Ue]=v.useState("us-west-2"),[ze,ae]=v.useState(""),[ce,Et]=v.useState(""),[St,Ot]=v.useState("us-east-1"),[it,ot]=v.useState("folddb"),[Ae,Xe]=v.useState("/tmp/folddb-data");v.useEffect(()=>{e&&(ct(),et(),I(A.id),r==="schema-service"&&Nt(A.id))},[e,A.id,r]);const ct=async()=>{try{const B=await wt.getConfig();B.success&&(c(B.data.openrouter.api_key||""),m(B.data.openrouter.model||"anthropic/claude-3.5-sonnet"),y(B.data.openrouter.base_url||"https://openrouter.ai/api/v1"),N(B.data.ollama.model||"llama3"),S(B.data.ollama.base_url||"http://localhost:11434"),l(B.data.provider||"OpenRouter"))}catch(B){console.error("Failed to load AI config:",B)}},yr=async()=>{try{const B={provider:a,openrouter:{api_key:d,model:f,base_url:h},ollama:{model:x,base_url:_}};(await wt.saveConfig(B)).success?(w({success:!0,message:"Configuration saved successfully"}),setTimeout(()=>{w(null),t()},1500)):w({success:!1,message:"Failed to save configuration"})}catch(B){w({success:!1,message:B.message||"Failed to save configuration"})}setTimeout(()=>w(null),3e3)},Nt=async B=>{const Z=Object.values(qt).find(ve=>ve.id===B);if(Z){F(ve=>({...ve,[B]:!0}));try{const ve=await Nl(Z.baseUrl);R(tt=>({...tt,[B]:ve}))}catch(ve){R(tt=>({...tt,[B]:{success:!1,error:ve.message}}))}finally{F(ve=>({...ve,[B]:!1}))}}},et=async()=>{try{const B=await Qo();if(B.success&&B.data){const Z=B.data;V(Z.type),Z.type==="local"?L(Z.path||"data"):Z.type==="dynamodb"?(Y(Z.table_name||"DataFoldStorage"),Ue(Z.region||"us-west-2"),ae(Z.user_id||"")):Z.type==="s3"&&(Et(Z.bucket||""),Ot(Z.region||"us-east-1"),ot(Z.prefix||"folddb"),Xe(Z.local_path||"/tmp/folddb-data"))}}catch(B){console.error("Failed to load database config:",B)}},lt=async()=>{try{let B;if(H==="local")B={type:"local",path:z};else if(H==="dynamodb"){if(!Q||!ge){w({success:!1,message:"Table name and region are required for DynamoDB"}),setTimeout(()=>w(null),3e3);return}B={type:"dynamodb",table_name:Q,region:ge,user_id:ze||void 0}}else if(H==="s3"){if(!ce||!St){w({success:!1,message:"Bucket and region are required for S3"}),setTimeout(()=>w(null),3e3);return}B={type:"s3",bucket:ce,region:St,prefix:it||"folddb",local_path:Ae||"/tmp/folddb-data"}}const Z=await Jo(B);Z.success?(w({success:!0,message:Z.data.requires_restart?"Database configuration saved. Please restart the server for changes to take effect.":Z.data.message||"Database configuration saved and restarted successfully"}),setTimeout(()=>{w(null),Z.data.requires_restart||t()},3e3)):w({success:!1,message:Z.error||"Failed to save database configuration"})}catch(B){w({success:!1,message:B.message||"Failed to save database configuration"})}setTimeout(()=>w(null),5e3)},jt=()=>{T(M),w({success:!0,message:"Schema service environment updated successfully"}),setTimeout(()=>{w(null),t()},1500)},dt=B=>{const Z=O[B];return $[B]?s.jsxs("span",{className:"inline-flex items-center text-xs bg-gray-100 text-gray-700 px-2 py-1 rounded",children:[s.jsxs("svg",{className:"animate-spin h-3 w-3 mr-1",viewBox:"0 0 24 24",children:[s.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4",fill:"none"}),s.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),"Checking..."]}):Z?Z.success?s.jsxs("span",{className:"inline-flex items-center text-xs bg-green-100 text-green-700 px-2 py-1 rounded",children:["✓ Online ",Z.responseTime&&`(${Z.responseTime}ms)`]}):s.jsx("span",{className:"inline-flex items-center text-xs bg-red-100 text-red-700 px-2 py-1 rounded",title:Z.error,children:"✗ Offline"}):s.jsx("button",{onClick:tt=>{tt.stopPropagation(),Nt(B)},className:"text-xs text-blue-600 hover:text-blue-700 underline",children:"Test Connection"})};return e?s.jsx("div",{className:"fixed inset-0 z-50 overflow-y-auto",children:s.jsxs("div",{className:"flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0",children:[s.jsx("div",{className:"fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75",onClick:t}),s.jsxs("div",{className:"inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-4xl sm:w-full",children:[s.jsxs("div",{className:"bg-white",children:[s.jsxs("div",{className:"flex items-center justify-between px-6 pt-5 pb-4 border-b border-gray-200",children:[s.jsx("h3",{className:"text-lg font-medium text-gray-900",children:"Settings"}),s.jsx("button",{onClick:t,className:"text-gray-400 hover:text-gray-600 transition-colors",children:s.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:s.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),s.jsx("div",{className:"border-b border-gray-200",children:s.jsxs("nav",{className:"flex px-6",children:[s.jsx("button",{onClick:()=>n("ai"),className:`py-3 px-4 text-sm font-medium border-b-2 transition-colors ${r==="ai"?"border-blue-500 text-blue-600":"border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"}`,children:"AI Configuration"}),s.jsx("button",{onClick:()=>n("transforms"),className:`py-3 px-4 text-sm font-medium border-b-2 transition-colors ${r==="transforms"?"border-blue-500 text-blue-600":"border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"}`,children:"Transforms"}),s.jsx("button",{onClick:()=>n("keys"),className:`py-3 px-4 text-sm font-medium border-b-2 transition-colors ${r==="keys"?"border-blue-500 text-blue-600":"border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"}`,children:"Key Management"}),s.jsx("button",{onClick:()=>n("schema-service"),className:`py-3 px-4 text-sm font-medium border-b-2 transition-colors ${r==="schema-service"?"border-blue-500 text-blue-600":"border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"}`,children:"Schema Service"}),s.jsx("button",{onClick:()=>n("database"),className:`py-3 px-4 text-sm font-medium border-b-2 transition-colors ${r==="database"?"border-blue-500 text-blue-600":"border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"}`,children:"Database"})]})}),s.jsxs("div",{className:"px-6 py-4 max-h-[70vh] overflow-y-auto",children:[r==="ai"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Provider"}),s.jsxs("select",{value:a,onChange:B=>l(B.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",children:[s.jsx("option",{value:"OpenRouter",children:"OpenRouter"}),s.jsx("option",{value:"Ollama",children:"Ollama"})]})]}),a==="OpenRouter"?s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Model"}),s.jsxs("select",{value:f,onChange:B=>m(B.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",children:[s.jsx("option",{value:"anthropic/claude-3.5-sonnet",children:"Claude 3.5 Sonnet"}),s.jsx("option",{value:"anthropic/claude-3.5-haiku",children:"Claude 3.5 Haiku"}),s.jsx("option",{value:"openai/gpt-4o",children:"GPT-4o"}),s.jsx("option",{value:"openai/gpt-4o-mini",children:"GPT-4o Mini"}),s.jsx("option",{value:"openai/o1",children:"OpenAI o1"}),s.jsx("option",{value:"openai/o1-mini",children:"OpenAI o1-mini"}),s.jsx("option",{value:"google/gemini-2.0-flash-exp",children:"Gemini 2.0 Flash"}),s.jsx("option",{value:"google/gemini-pro-1.5",children:"Gemini 1.5 Pro"}),s.jsx("option",{value:"meta-llama/llama-3.3-70b-instruct",children:"Llama 3.3 70B"}),s.jsx("option",{value:"meta-llama/llama-3.1-405b-instruct",children:"Llama 3.1 405B"}),s.jsx("option",{value:"deepseek/deepseek-chat",children:"DeepSeek Chat"}),s.jsx("option",{value:"qwen/qwen-2.5-72b-instruct",children:"Qwen 2.5 72B"})]})]}):s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Model"}),s.jsx("input",{type:"text",value:x,onChange:B=>N(B.target.value),placeholder:"e.g., llama3",className:"w-full p-2 border border-gray-300 rounded text-sm"})]})]}),a==="OpenRouter"&&s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["API Key ",s.jsxs("span",{className:"text-xs text-gray-500",children:["(",s.jsx("a",{href:"https://openrouter.ai/keys",target:"_blank",rel:"noopener noreferrer",className:"text-blue-600 hover:underline",children:"get key"}),")"]})]}),s.jsx("input",{type:"password",value:d,onChange:B=>c(B.target.value),placeholder:"sk-or-...",className:"w-full p-2 border border-gray-300 rounded text-sm"})]}),s.jsxs("div",{children:[s.jsxs("button",{onClick:()=>C(!E),className:"text-sm text-gray-600 hover:text-gray-800 flex items-center gap-1",children:[s.jsx("span",{children:E?"▼":"▶"}),"Advanced Settings"]}),E&&s.jsx("div",{className:"mt-3 space-y-3 pl-4 border-l-2 border-gray-200",children:s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Base URL"}),s.jsx("input",{type:"text",value:a==="OpenRouter"?h:_,onChange:B=>a==="OpenRouter"?y(B.target.value):S(B.target.value),placeholder:a==="OpenRouter"?"https://openrouter.ai/api/v1":"http://localhost:11434",className:"w-full p-2 border border-gray-300 rounded text-sm"})]})})]}),p&&s.jsx("div",{className:`p-3 rounded-md ${p.success?"bg-green-50 text-green-800 border border-green-200":"bg-red-50 text-red-800 border border-red-200"}`,children:s.jsxs("span",{className:"text-sm font-medium",children:[p.success?"✓":"✗"," ",p.message]})})]}),r==="transforms"&&s.jsx(Zd,{onResult:()=>{}}),r==="keys"&&s.jsx(au,{onResult:()=>{}}),r==="schema-service"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"mb-4",children:[s.jsx("h4",{className:"text-md font-semibold text-gray-900 mb-2",children:"Schema Service Environment"}),s.jsx("p",{className:"text-sm text-gray-600 mb-4",children:"Select which schema service endpoint to use. This affects where schemas are loaded from and saved to."})]}),s.jsx("div",{className:"space-y-3",children:Object.values(qt).map(B=>s.jsxs("label",{className:`flex items-start p-4 border-2 rounded-lg cursor-pointer transition-all ${M===B.id?"border-blue-500 bg-blue-50":"border-gray-200 hover:border-gray-300 bg-white"}`,children:[s.jsx("input",{type:"radio",name:"schemaEnvironment",value:B.id,checked:M===B.id,onChange:Z=>I(Z.target.value),className:"mt-1 mr-3"}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsx("span",{className:"text-sm font-semibold text-gray-900",children:B.name}),s.jsxs("div",{className:"flex items-center gap-2",children:[dt(B.id),M===B.id&&s.jsx("span",{className:"text-xs bg-blue-100 text-blue-700 px-2 py-1 rounded",children:"Active"})]})]}),s.jsx("p",{className:"text-xs text-gray-600 mt-1",children:B.description}),s.jsx("p",{className:"text-xs text-gray-500 mt-1 font-mono",children:B.baseUrl||window.location.origin}),O[B.id]&&!O[B.id].success&&s.jsxs("p",{className:"text-xs text-red-600 mt-1",children:["Error: ",O[B.id].error]})]})]},B.id))}),p&&s.jsx("div",{className:`p-3 rounded-md ${p.success?"bg-green-50 text-green-800 border border-green-200":"bg-red-50 text-red-800 border border-red-200"}`,children:s.jsxs("span",{className:"text-sm font-medium",children:[p.success?"✓":"✗"," ",p.message]})})]}),r==="database"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"mb-4",children:[s.jsx("h4",{className:"text-md font-semibold text-gray-900 mb-2",children:"Database Storage Backend"}),s.jsx("p",{className:"text-sm text-gray-600 mb-4",children:"Choose the storage backend for your database. Changes require a server restart."})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Storage Type"}),s.jsxs("select",{value:H,onChange:B=>V(B.target.value),className:"w-full p-2 border border-gray-300 rounded text-sm",children:[s.jsx("option",{value:"local",children:"Local (Sled)"}),s.jsx("option",{value:"dynamodb",children:"DynamoDB"}),s.jsx("option",{value:"s3",children:"S3"})]})]}),H==="local"?s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Storage Path"}),s.jsx("input",{type:"text",value:z,onChange:B=>L(B.target.value),placeholder:"data",className:"w-full p-2 border border-gray-300 rounded text-sm"}),s.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Local filesystem path where the database will be stored"})]}):H==="dynamodb"?s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["Table Name ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx("input",{type:"text",value:Q,onChange:B=>Y(B.target.value),placeholder:"DataFoldStorage",className:"w-full p-2 border border-gray-300 rounded text-sm"}),s.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Base table name (namespaces will be appended automatically)"})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["AWS Region ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx("input",{type:"text",value:ge,onChange:B=>Ue(B.target.value),placeholder:"us-west-2",className:"w-full p-2 border border-gray-300 rounded text-sm"}),s.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"AWS region where your DynamoDB tables are located"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"User ID (Optional)"}),s.jsx("input",{type:"text",value:ze,onChange:B=>ae(B.target.value),placeholder:"Leave empty for single-tenant",className:"w-full p-2 border border-gray-300 rounded text-sm"}),s.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"User ID for multi-tenant isolation (uses partition key)"})]}),s.jsx("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-md",children:s.jsxs("p",{className:"text-xs text-yellow-800",children:[s.jsx("strong",{children:"Note:"})," Ensure your AWS credentials are configured (via environment variables, IAM role, or AWS CLI). The DynamoDB tables will be created automatically if they don't exist."]})})]}):s.jsxs("div",{className:"space-y-3",children:[s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["S3 Bucket ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx("input",{type:"text",value:ce,onChange:B=>Et(B.target.value),placeholder:"my-datafold-bucket",className:"w-full p-2 border border-gray-300 rounded text-sm"}),s.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"S3 bucket name where the database will be stored"})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["AWS Region ",s.jsx("span",{className:"text-red-500",children:"*"})]}),s.jsx("input",{type:"text",value:St,onChange:B=>Ot(B.target.value),placeholder:"us-east-1",className:"w-full p-2 border border-gray-300 rounded text-sm"}),s.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"AWS region where your S3 bucket is located"})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"S3 Prefix (Optional)"}),s.jsx("input",{type:"text",value:it,onChange:B=>ot(B.target.value),placeholder:"folddb",className:"w-full p-2 border border-gray-300 rounded text-sm"}),s.jsx("p",{className:"text-xs text-gray-500 mt-1",children:'Prefix/path within the bucket (defaults to "folddb")'})]}),s.jsxs("div",{children:[s.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Local Cache Path"}),s.jsx("input",{type:"text",value:Ae,onChange:B=>Xe(B.target.value),placeholder:"/tmp/folddb-data",className:"w-full p-2 border border-gray-300 rounded text-sm"}),s.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"Local filesystem path for caching S3 data (defaults to /tmp/folddb-data)"})]}),s.jsx("div",{className:"p-3 bg-yellow-50 border border-yellow-200 rounded-md",children:s.jsxs("p",{className:"text-xs text-yellow-800",children:[s.jsx("strong",{children:"Note:"})," Ensure your AWS credentials are configured (via environment variables, IAM role, or AWS CLI). The database will be synced to/from S3 on startup and shutdown."]})})]}),p&&s.jsx("div",{className:`p-3 rounded-md ${p.success?"bg-green-50 text-green-800 border border-green-200":"bg-red-50 text-red-800 border border-red-200"}`,children:s.jsxs("span",{className:"text-sm font-medium",children:[p.success?"✓":"✗"," ",p.message]})})]})]})]}),s.jsx("div",{className:"bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse gap-3 border-t border-gray-200",children:r==="ai"||r==="schema-service"||r==="database"?s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:r==="ai"?yr:r==="schema-service"?jt:lt,className:"w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm",children:r==="database"?"Save and Restart DB":"Save Configuration"}),s.jsx("button",{onClick:t,className:"mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:mt-0 sm:w-auto sm:text-sm",children:"Cancel"})]}):s.jsx("button",{onClick:t,className:"w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:w-auto sm:text-sm",children:"Close"})})]})]})}):null}function ou(){const[e,t]=v.useState([]),r=v.useRef(null),n=()=>{Promise.resolve(navigator.clipboard.writeText(e.join(`
`))).catch(()=>{})};return v.useEffect(()=>{he.getLogs().then(l=>{if(l.success&&l.data){const d=l.data.logs||[];t(Array.isArray(d)?d:[])}else t([])}).catch(()=>t([]));const a=he.createLogStream(l=>{t(d=>[...d,l])},l=>{console.warn("Log stream error:",l)});return()=>a.close()},[]),v.useEffect(()=>{var a;(a=r.current)==null||a.scrollIntoView({behavior:"smooth"})},[e]),s.jsxs("aside",{className:"w-80 bg-gray-900 text-white flex flex-col overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-700",children:[s.jsx("h2",{className:"text-lg font-semibold",children:"Logs"}),s.jsx("button",{onClick:n,className:"text-xs text-blue-300 hover:underline",children:"Copy"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-1 text-xs font-mono",children:[e.map((a,l)=>s.jsx("div",{children:a},l)),s.jsx("div",{ref:r})]})]})}se.FileUploadTab=$d,se.FoldDbProvider=Al,se.IngestionTab=Ld,se.LlmQueryTab=Od,se.LogSidebar=ou,se.MutationTab=Bd,se.NativeIndexTab=Vd,se.QueryTab=Id,se.ResultsSection=Jl,se.SchemaTab=ed,se.SettingsModal=iu,se.StatusSection=Ul,se.TabNavigation=Zl,se.useAppDispatch=Qt,se.useAppSelector=fe,se.useApprovedSchemas=si,Object.defineProperty(se,Symbol.toStringTag,{value:"Module"})});