@standardbeagle/edit-db 0.4.583 → 0.4.597

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,17 @@
1
- (function(ae,u){typeof exports=="object"&&typeof module<"u"?u(exports,require("react"),require("@tanstack/react-query"),require("lucide-react"),require("radix-ui"),require("@radix-ui/react-slot"),require("@tanstack/react-form"),require("@tanstack/react-table")):typeof define=="function"&&define.amd?define(["exports","react","@tanstack/react-query","lucide-react","radix-ui","@radix-ui/react-slot","@tanstack/react-form","@tanstack/react-table"],u):(ae=typeof globalThis<"u"?globalThis:ae||self,u(ae.editor={},ae.React,ae.ReactQuery,ae.LucideReact,ae.RadixUI,ae.RadixReactSlot,ae.ReactForm,ae.ReactTable))})(this,(function(ae,u,de,C,R,ka,Tn,$n){"use strict";function Sa(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const Ve=Sa(u);var En={exports:{}},sn={};var ls;function Ta(){if(ls)return sn;ls=1;var e=u,t=Symbol.for("react.element"),r=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function a(l,c,m){var d,f={},p=null,x=null;m!==void 0&&(p=""+m),c.key!==void 0&&(p=""+c.key),c.ref!==void 0&&(x=c.ref);for(d in c)s.call(c,d)&&!i.hasOwnProperty(d)&&(f[d]=c[d]);if(l&&l.defaultProps)for(d in c=l.defaultProps,c)f[d]===void 0&&(f[d]=c[d]);return{$$typeof:t,type:l,key:p,ref:x,props:f,_owner:o.current}}return sn.Fragment=r,sn.jsx=a,sn.jsxs=a,sn}var on={};var cs;function $a(){return cs||(cs=1,process.env.NODE_ENV!=="production"&&(function(){var e=u,t=Symbol.for("react.element"),r=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),a=Symbol.for("react.provider"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),x=Symbol.for("react.offscreen"),h=Symbol.iterator,y="@@iterator";function N(g){if(g===null||typeof g!="object")return null;var M=h&&g[h]||g[y];return typeof M=="function"?M:null}var T=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function k(g){{for(var M=arguments.length,G=new Array(M>1?M-1:0),te=1;te<M;te++)G[te-1]=arguments[te];$("error",g,G)}}function $(g,M,G){{var te=T.ReactDebugCurrentFrame,pe=te.getStackAddendum();pe!==""&&(M+="%s",G=G.concat([pe]));var ge=G.map(function(ue){return String(ue)});ge.unshift("Warning: "+M),Function.prototype.apply.call(console[g],console,ge)}}var b=!1,v=!1,w=!1,F=!1,j=!1,V;V=Symbol.for("react.module.reference");function S(g){return!!(typeof g=="string"||typeof g=="function"||g===s||g===i||j||g===o||g===m||g===d||F||g===x||b||v||w||typeof g=="object"&&g!==null&&(g.$$typeof===p||g.$$typeof===f||g.$$typeof===a||g.$$typeof===l||g.$$typeof===c||g.$$typeof===V||g.getModuleId!==void 0))}function L(g,M,G){var te=g.displayName;if(te)return te;var pe=M.displayName||M.name||"";return pe!==""?G+"("+pe+")":G}function A(g){return g.displayName||"Context"}function D(g){if(g==null)return null;if(typeof g.tag=="number"&&k("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof g=="function")return g.displayName||g.name||null;if(typeof g=="string")return g;switch(g){case s:return"Fragment";case r:return"Portal";case i:return"Profiler";case o:return"StrictMode";case m:return"Suspense";case d:return"SuspenseList"}if(typeof g=="object")switch(g.$$typeof){case l:var M=g;return A(M)+".Consumer";case a:var G=g;return A(G._context)+".Provider";case c:return L(g,g.render,"ForwardRef");case f:var te=g.displayName||null;return te!==null?te:D(g.type)||"Memo";case p:{var pe=g,ge=pe._payload,ue=pe._init;try{return D(ue(ge))}catch{return null}}}return null}var B=Object.assign,X=0,E,P,q,U,_,ce,he;function Ue(){}Ue.__reactDisabledLog=!0;function Pe(){{if(X===0){E=console.log,P=console.info,q=console.warn,U=console.error,_=console.group,ce=console.groupCollapsed,he=console.groupEnd;var g={configurable:!0,enumerable:!0,value:Ue,writable:!0};Object.defineProperties(console,{info:g,log:g,warn:g,error:g,group:g,groupCollapsed:g,groupEnd:g})}X++}}function ie(){{if(X--,X===0){var g={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:B({},g,{value:E}),info:B({},g,{value:P}),warn:B({},g,{value:q}),error:B({},g,{value:U}),group:B({},g,{value:_}),groupCollapsed:B({},g,{value:ce}),groupEnd:B({},g,{value:he})})}X<0&&k("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var se=T.ReactCurrentDispatcher,ke;function Ae(g,M,G){{if(ke===void 0)try{throw Error()}catch(pe){var te=pe.stack.trim().match(/\n( *(at )?)/);ke=te&&te[1]||""}return`
1
+ (function(ae,u){typeof exports=="object"&&typeof module<"u"?u(exports,require("react"),require("@tanstack/react-query"),require("lucide-react"),require("radix-ui"),require("@radix-ui/react-slot"),require("@tanstack/react-form"),require("@tanstack/react-table")):typeof define=="function"&&define.amd?define(["exports","react","@tanstack/react-query","lucide-react","radix-ui","@radix-ui/react-slot","@tanstack/react-form","@tanstack/react-table"],u):(ae=typeof globalThis<"u"?globalThis:ae||self,u(ae.editor={},ae.React,ae.ReactQuery,ae.LucideReact,ae.RadixUI,ae.RadixReactSlot,ae.ReactForm,ae.ReactTable))})(this,(function(ae,u,de,w,R,Sa,Tn,$n){"use strict";function Ta(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const Ve=Ta(u);var En={exports:{}},sn={};var is;function $a(){if(is)return sn;is=1;var e=u,t=Symbol.for("react.element"),r=Symbol.for("react.fragment"),s=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,i={key:!0,ref:!0,__self:!0,__source:!0};function a(l,c,m){var d,p={},f=null,x=null;m!==void 0&&(f=""+m),c.key!==void 0&&(f=""+c.key),c.ref!==void 0&&(x=c.ref);for(d in c)s.call(c,d)&&!i.hasOwnProperty(d)&&(p[d]=c[d]);if(l&&l.defaultProps)for(d in c=l.defaultProps,c)p[d]===void 0&&(p[d]=c[d]);return{$$typeof:t,type:l,key:f,ref:x,props:p,_owner:o.current}}return sn.Fragment=r,sn.jsx=a,sn.jsxs=a,sn}var on={};var ls;function Ea(){return ls||(ls=1,process.env.NODE_ENV!=="production"&&(function(){var e=u,t=Symbol.for("react.element"),r=Symbol.for("react.portal"),s=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),a=Symbol.for("react.provider"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),m=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),p=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),x=Symbol.for("react.offscreen"),h=Symbol.iterator,b="@@iterator";function N(g){if(g===null||typeof g!="object")return null;var M=h&&g[h]||g[b];return typeof M=="function"?M:null}var T=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function k(g){{for(var M=arguments.length,G=new Array(M>1?M-1:0),te=1;te<M;te++)G[te-1]=arguments[te];E("error",g,G)}}function E(g,M,G){{var te=T.ReactDebugCurrentFrame,pe=te.getStackAddendum();pe!==""&&(M+="%s",G=G.concat([pe]));var ge=G.map(function(ue){return String(ue)});ge.unshift("Warning: "+M),Function.prototype.apply.call(console[g],console,ge)}}var y=!1,v=!1,j=!1,S=!1,C=!1,B;B=Symbol.for("react.module.reference");function $(g){return!!(typeof g=="string"||typeof g=="function"||g===s||g===i||C||g===o||g===m||g===d||S||g===x||y||v||j||typeof g=="object"&&g!==null&&(g.$$typeof===f||g.$$typeof===p||g.$$typeof===a||g.$$typeof===l||g.$$typeof===c||g.$$typeof===B||g.getModuleId!==void 0))}function L(g,M,G){var te=g.displayName;if(te)return te;var pe=M.displayName||M.name||"";return pe!==""?G+"("+pe+")":G}function q(g){return g.displayName||"Context"}function D(g){if(g==null)return null;if(typeof g.tag=="number"&&k("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof g=="function")return g.displayName||g.name||null;if(typeof g=="string")return g;switch(g){case s:return"Fragment";case r:return"Portal";case i:return"Profiler";case o:return"StrictMode";case m:return"Suspense";case d:return"SuspenseList"}if(typeof g=="object")switch(g.$$typeof){case l:var M=g;return q(M)+".Consumer";case a:var G=g;return q(G._context)+".Provider";case c:return L(g,g.render,"ForwardRef");case p:var te=g.displayName||null;return te!==null?te:D(g.type)||"Memo";case f:{var pe=g,ge=pe._payload,ue=pe._init;try{return D(ue(ge))}catch{return null}}}return null}var V=Object.assign,X=0,F,P,A,U,_,ce,he;function Ue(){}Ue.__reactDisabledLog=!0;function Pe(){{if(X===0){F=console.log,P=console.info,A=console.warn,U=console.error,_=console.group,ce=console.groupCollapsed,he=console.groupEnd;var g={configurable:!0,enumerable:!0,value:Ue,writable:!0};Object.defineProperties(console,{info:g,log:g,warn:g,error:g,group:g,groupCollapsed:g,groupEnd:g})}X++}}function ie(){{if(X--,X===0){var g={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:V({},g,{value:F}),info:V({},g,{value:P}),warn:V({},g,{value:A}),error:V({},g,{value:U}),group:V({},g,{value:_}),groupCollapsed:V({},g,{value:ce}),groupEnd:V({},g,{value:he})})}X<0&&k("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var se=T.ReactCurrentDispatcher,ke;function Ae(g,M,G){{if(ke===void 0)try{throw Error()}catch(pe){var te=pe.stack.trim().match(/\n( *(at )?)/);ke=te&&te[1]||""}return`
2
2
  `+ke+g}}var re=!1,Ee;{var Ie=typeof WeakMap=="function"?WeakMap:Map;Ee=new Ie}function Le(g,M){if(!g||re)return"";{var G=Ee.get(g);if(G!==void 0)return G}var te;re=!0;var pe=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var ge;ge=se.current,se.current=null,Pe();try{if(M){var ue=function(){throw Error()};if(Object.defineProperty(ue.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(ue,[])}catch(Re){te=Re}Reflect.construct(g,[],ue)}else{try{ue.call()}catch(Re){te=Re}g.call(ue.prototype)}}else{try{throw Error()}catch(Re){te=Re}g()}}catch(Re){if(Re&&te&&typeof Re.stack=="string"){for(var le=Re.stack.split(`
3
3
  `),We=te.stack.split(`
4
4
  `),Te=le.length-1,Fe=We.length-1;Te>=1&&Fe>=0&&le[Te]!==We[Fe];)Fe--;for(;Te>=1&&Fe>=0;Te--,Fe--)if(le[Te]!==We[Fe]){if(Te!==1||Fe!==1)do if(Te--,Fe--,Fe<0||le[Te]!==We[Fe]){var at=`
5
- `+le[Te].replace(" at new "," at ");return g.displayName&&at.includes("<anonymous>")&&(at=at.replace("<anonymous>",g.displayName)),typeof g=="function"&&Ee.set(g,at),at}while(Te>=1&&Fe>=0);break}}}finally{re=!1,se.current=ge,ie(),Error.prepareStackTrace=pe}var rn=g?g.displayName||g.name:"",Yt=rn?Ae(rn):"";return typeof g=="function"&&Ee.set(g,Yt),Yt}function Ge(g,M,G){return Le(g,!1)}function Oe(g){var M=g.prototype;return!!(M&&M.isReactComponent)}function ye(g,M,G){if(g==null)return"";if(typeof g=="function")return Le(g,Oe(g));if(typeof g=="string")return Ae(g);switch(g){case m:return Ae("Suspense");case d:return Ae("SuspenseList")}if(typeof g=="object")switch(g.$$typeof){case c:return Ge(g.render);case f:return ye(g.type,M,G);case p:{var te=g,pe=te._payload,ge=te._init;try{return ye(ge(pe),M,G)}catch{}}}return""}var ze=Object.prototype.hasOwnProperty,O={},Z=T.ReactDebugCurrentFrame;function ee(g){if(g){var M=g._owner,G=ye(g.type,g._source,M?M.type:null);Z.setExtraStackFrame(G)}else Z.setExtraStackFrame(null)}function Ce(g,M,G,te,pe){{var ge=Function.call.bind(ze);for(var ue in g)if(ge(g,ue)){var le=void 0;try{if(typeof g[ue]!="function"){var We=Error((te||"React class")+": "+G+" type `"+ue+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof g[ue]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw We.name="Invariant Violation",We}le=g[ue](M,ue,te,G,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(Te){le=Te}le&&!(le instanceof Error)&&(ee(pe),k("%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).",te||"React class",G,ue,typeof le),ee(null)),le instanceof Error&&!(le.message in O)&&(O[le.message]=!0,ee(pe),k("Failed %s type: %s",G,le.message),ee(null))}}}var xe=Array.isArray;function qe(g){return xe(g)}function W(g){{var M=typeof Symbol=="function"&&Symbol.toStringTag,G=M&&g[Symbol.toStringTag]||g.constructor.name||"Object";return G}}function me(g){try{return Ne(g),!1}catch{return!0}}function Ne(g){return""+g}function ve(g){if(me(g))return k("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",W(g)),Ne(g)}var rt=T.ReactCurrentOwner,Mt={key:!0,ref:!0,__self:!0,__source:!0},be,ft;function Nt(g){if(ze.call(g,"ref")){var M=Object.getOwnPropertyDescriptor(g,"ref").get;if(M&&M.isReactWarning)return!1}return g.ref!==void 0}function Ye(g){if(ze.call(g,"key")){var M=Object.getOwnPropertyDescriptor(g,"key").get;if(M&&M.isReactWarning)return!1}return g.key!==void 0}function Xe(g,M){typeof g.ref=="string"&&rt.current}function Qt(g,M){{var G=function(){be||(be=!0,k("%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)",M))};G.isReactWarning=!0,Object.defineProperty(g,"key",{get:G,configurable:!0})}}function kn(g,M){{var G=function(){ft||(ft=!0,k("%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)",M))};G.isReactWarning=!0,Object.defineProperty(g,"ref",{get:G,configurable:!0})}}var Sn=function(g,M,G,te,pe,ge,ue){var le={$$typeof:t,type:g,key:M,ref:G,props:ue,_owner:ge};return le._store={},Object.defineProperty(le._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(le,"_self",{configurable:!1,enumerable:!1,writable:!1,value:te}),Object.defineProperty(le,"_source",{configurable:!1,enumerable:!1,writable:!1,value:pe}),Object.freeze&&(Object.freeze(le.props),Object.freeze(le)),le};function Ht(g,M,G,te,pe){{var ge,ue={},le=null,We=null;G!==void 0&&(ve(G),le=""+G),Ye(M)&&(ve(M.key),le=""+M.key),Nt(M)&&(We=M.ref,Xe(M,pe));for(ge in M)ze.call(M,ge)&&!Mt.hasOwnProperty(ge)&&(ue[ge]=M[ge]);if(g&&g.defaultProps){var Te=g.defaultProps;for(ge in Te)ue[ge]===void 0&&(ue[ge]=Te[ge])}if(le||We){var Fe=typeof g=="function"?g.displayName||g.name||"Unknown":g;le&&Qt(ue,Fe),We&&kn(ue,Fe)}return Sn(g,le,We,pe,te,rt.current,ue)}}var pt=T.ReactCurrentOwner,It=T.ReactDebugCurrentFrame;function st(g){if(g){var M=g._owner,G=ye(g.type,g._source,M?M.type:null);It.setExtraStackFrame(G)}else It.setExtraStackFrame(null)}var Ut;Ut=!1;function Lt(g){return typeof g=="object"&&g!==null&&g.$$typeof===t}function z(){{if(pt.current){var g=D(pt.current.type);if(g)return`
5
+ `+le[Te].replace(" at new "," at ");return g.displayName&&at.includes("<anonymous>")&&(at=at.replace("<anonymous>",g.displayName)),typeof g=="function"&&Ee.set(g,at),at}while(Te>=1&&Fe>=0);break}}}finally{re=!1,se.current=ge,ie(),Error.prepareStackTrace=pe}var rn=g?g.displayName||g.name:"",Yt=rn?Ae(rn):"";return typeof g=="function"&&Ee.set(g,Yt),Yt}function Ge(g,M,G){return Le(g,!1)}function Oe(g){var M=g.prototype;return!!(M&&M.isReactComponent)}function ye(g,M,G){if(g==null)return"";if(typeof g=="function")return Le(g,Oe(g));if(typeof g=="string")return Ae(g);switch(g){case m:return Ae("Suspense");case d:return Ae("SuspenseList")}if(typeof g=="object")switch(g.$$typeof){case c:return Ge(g.render);case p:return ye(g.type,M,G);case f:{var te=g,pe=te._payload,ge=te._init;try{return ye(ge(pe),M,G)}catch{}}}return""}var ze=Object.prototype.hasOwnProperty,O={},Z=T.ReactDebugCurrentFrame;function ee(g){if(g){var M=g._owner,G=ye(g.type,g._source,M?M.type:null);Z.setExtraStackFrame(G)}else Z.setExtraStackFrame(null)}function Ce(g,M,G,te,pe){{var ge=Function.call.bind(ze);for(var ue in g)if(ge(g,ue)){var le=void 0;try{if(typeof g[ue]!="function"){var We=Error((te||"React class")+": "+G+" type `"+ue+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof g[ue]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw We.name="Invariant Violation",We}le=g[ue](M,ue,te,G,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(Te){le=Te}le&&!(le instanceof Error)&&(ee(pe),k("%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).",te||"React class",G,ue,typeof le),ee(null)),le instanceof Error&&!(le.message in O)&&(O[le.message]=!0,ee(pe),k("Failed %s type: %s",G,le.message),ee(null))}}}var xe=Array.isArray;function qe(g){return xe(g)}function W(g){{var M=typeof Symbol=="function"&&Symbol.toStringTag,G=M&&g[Symbol.toStringTag]||g.constructor.name||"Object";return G}}function me(g){try{return Ne(g),!1}catch{return!0}}function Ne(g){return""+g}function ve(g){if(me(g))return k("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",W(g)),Ne(g)}var rt=T.ReactCurrentOwner,Mt={key:!0,ref:!0,__self:!0,__source:!0},be,ft;function Nt(g){if(ze.call(g,"ref")){var M=Object.getOwnPropertyDescriptor(g,"ref").get;if(M&&M.isReactWarning)return!1}return g.ref!==void 0}function Ye(g){if(ze.call(g,"key")){var M=Object.getOwnPropertyDescriptor(g,"key").get;if(M&&M.isReactWarning)return!1}return g.key!==void 0}function Xe(g,M){typeof g.ref=="string"&&rt.current}function Qt(g,M){{var G=function(){be||(be=!0,k("%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)",M))};G.isReactWarning=!0,Object.defineProperty(g,"key",{get:G,configurable:!0})}}function kn(g,M){{var G=function(){ft||(ft=!0,k("%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)",M))};G.isReactWarning=!0,Object.defineProperty(g,"ref",{get:G,configurable:!0})}}var Sn=function(g,M,G,te,pe,ge,ue){var le={$$typeof:t,type:g,key:M,ref:G,props:ue,_owner:ge};return le._store={},Object.defineProperty(le._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(le,"_self",{configurable:!1,enumerable:!1,writable:!1,value:te}),Object.defineProperty(le,"_source",{configurable:!1,enumerable:!1,writable:!1,value:pe}),Object.freeze&&(Object.freeze(le.props),Object.freeze(le)),le};function Ht(g,M,G,te,pe){{var ge,ue={},le=null,We=null;G!==void 0&&(ve(G),le=""+G),Ye(M)&&(ve(M.key),le=""+M.key),Nt(M)&&(We=M.ref,Xe(M,pe));for(ge in M)ze.call(M,ge)&&!Mt.hasOwnProperty(ge)&&(ue[ge]=M[ge]);if(g&&g.defaultProps){var Te=g.defaultProps;for(ge in Te)ue[ge]===void 0&&(ue[ge]=Te[ge])}if(le||We){var Fe=typeof g=="function"?g.displayName||g.name||"Unknown":g;le&&Qt(ue,Fe),We&&kn(ue,Fe)}return Sn(g,le,We,pe,te,rt.current,ue)}}var pt=T.ReactCurrentOwner,It=T.ReactDebugCurrentFrame;function st(g){if(g){var M=g._owner,G=ye(g.type,g._source,M?M.type:null);It.setExtraStackFrame(G)}else It.setExtraStackFrame(null)}var Ut;Ut=!1;function Lt(g){return typeof g=="object"&&g!==null&&g.$$typeof===t}function z(){{if(pt.current){var g=D(pt.current.type);if(g)return`
6
6
 
7
7
  Check the render method of \``+g+"`."}return""}}function H(g){return""}var I={};function ne(g){{var M=z();if(!M){var G=typeof g=="string"?g:g.displayName||g.name;G&&(M=`
8
8
 
9
- Check the top-level render call using <`+G+">.")}return M}}function Se(g,M){{if(!g._store||g._store.validated||g.key!=null)return;g._store.validated=!0;var G=ne(M);if(I[G])return;I[G]=!0;var te="";g&&g._owner&&g._owner!==pt.current&&(te=" It was passed a child from "+D(g._owner.type)+"."),st(g),k('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',G,te),st(null)}}function De(g,M){{if(typeof g!="object")return;if(qe(g))for(var G=0;G<g.length;G++){var te=g[G];Lt(te)&&Se(te,M)}else if(Lt(g))g._store&&(g._store.validated=!0);else if(g){var pe=N(g);if(typeof pe=="function"&&pe!==g.entries)for(var ge=pe.call(g),ue;!(ue=ge.next()).done;)Lt(ue.value)&&Se(ue.value,M)}}}function ot(g){{var M=g.type;if(M==null||typeof M=="string")return;var G;if(typeof M=="function")G=M.propTypes;else if(typeof M=="object"&&(M.$$typeof===c||M.$$typeof===f))G=M.propTypes;else return;if(G){var te=D(M);Ce(G,g.props,"prop",te,g)}else if(M.PropTypes!==void 0&&!Ut){Ut=!0;var pe=D(M);k("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",pe||"Unknown")}typeof M.getDefaultProps=="function"&&!M.getDefaultProps.isReactClassApproved&&k("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function ht(g){{for(var M=Object.keys(g.props),G=0;G<M.length;G++){var te=M[G];if(te!=="children"&&te!=="key"){st(g),k("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",te),st(null);break}}g.ref!==null&&(st(g),k("Invalid attribute `ref` supplied to `React.Fragment`."),st(null))}}var Ke={};function kt(g,M,G,te,pe,ge){{var ue=S(g);if(!ue){var le="";(g===void 0||typeof g=="object"&&g!==null&&Object.keys(g).length===0)&&(le+=" 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 We=H();We?le+=We:le+=z();var Te;g===null?Te="null":qe(g)?Te="array":g!==void 0&&g.$$typeof===t?(Te="<"+(D(g.type)||"Unknown")+" />",le=" Did you accidentally export a JSX literal instead of a component?"):Te=typeof g,k("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",Te,le)}var Fe=Ht(g,M,G,pe,ge);if(Fe==null)return Fe;if(ue){var at=M.children;if(at!==void 0)if(te)if(qe(at)){for(var rn=0;rn<at.length;rn++)De(at[rn],g);Object.freeze&&Object.freeze(at)}else k("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 De(at,g)}if(ze.call(M,"key")){var Yt=D(g),Re=Object.keys(M).filter(function(wm){return wm!=="key"}),is=Re.length>0?"{key: someKey, "+Re.join(": ..., ")+": ...}":"{key: someKey}";if(!Ke[Yt+is]){var jm=Re.length>0?"{"+Re.join(": ..., ")+": ...}":"{}";k(`A props object containing a "key" prop is being spread into JSX:
9
+ Check the top-level render call using <`+G+">.")}return M}}function Se(g,M){{if(!g._store||g._store.validated||g.key!=null)return;g._store.validated=!0;var G=ne(M);if(I[G])return;I[G]=!0;var te="";g&&g._owner&&g._owner!==pt.current&&(te=" It was passed a child from "+D(g._owner.type)+"."),st(g),k('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',G,te),st(null)}}function De(g,M){{if(typeof g!="object")return;if(qe(g))for(var G=0;G<g.length;G++){var te=g[G];Lt(te)&&Se(te,M)}else if(Lt(g))g._store&&(g._store.validated=!0);else if(g){var pe=N(g);if(typeof pe=="function"&&pe!==g.entries)for(var ge=pe.call(g),ue;!(ue=ge.next()).done;)Lt(ue.value)&&Se(ue.value,M)}}}function ot(g){{var M=g.type;if(M==null||typeof M=="string")return;var G;if(typeof M=="function")G=M.propTypes;else if(typeof M=="object"&&(M.$$typeof===c||M.$$typeof===p))G=M.propTypes;else return;if(G){var te=D(M);Ce(G,g.props,"prop",te,g)}else if(M.PropTypes!==void 0&&!Ut){Ut=!0;var pe=D(M);k("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",pe||"Unknown")}typeof M.getDefaultProps=="function"&&!M.getDefaultProps.isReactClassApproved&&k("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function ht(g){{for(var M=Object.keys(g.props),G=0;G<M.length;G++){var te=M[G];if(te!=="children"&&te!=="key"){st(g),k("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",te),st(null);break}}g.ref!==null&&(st(g),k("Invalid attribute `ref` supplied to `React.Fragment`."),st(null))}}var Ke={};function kt(g,M,G,te,pe,ge){{var ue=$(g);if(!ue){var le="";(g===void 0||typeof g=="object"&&g!==null&&Object.keys(g).length===0)&&(le+=" 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 We=H();We?le+=We:le+=z();var Te;g===null?Te="null":qe(g)?Te="array":g!==void 0&&g.$$typeof===t?(Te="<"+(D(g.type)||"Unknown")+" />",le=" Did you accidentally export a JSX literal instead of a component?"):Te=typeof g,k("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",Te,le)}var Fe=Ht(g,M,G,pe,ge);if(Fe==null)return Fe;if(ue){var at=M.children;if(at!==void 0)if(te)if(qe(at)){for(var rn=0;rn<at.length;rn++)De(at[rn],g);Object.freeze&&Object.freeze(at)}else k("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 De(at,g)}if(ze.call(M,"key")){var Yt=D(g),Re=Object.keys(M).filter(function(Cm){return Cm!=="key"}),as=Re.length>0?"{key: someKey, "+Re.join(": ..., ")+": ...}":"{key: someKey}";if(!Ke[Yt+as]){var wm=Re.length>0?"{"+Re.join(": ..., ")+": ...}":"{}";k(`A props object containing a "key" prop is being spread into JSX:
10
10
  let props = %s;
11
11
  <%s {...props} />
12
12
  React keys must be passed directly to JSX without using spread:
13
13
  let props = %s;
14
- <%s key={someKey} {...props} />`,is,Yt,jm,Yt),Ke[Yt+is]=!0}}return g===s?ht(Fe):ot(Fe),Fe}}function gt(g,M,G){return kt(g,M,G,!0)}function nn(g,M,G){return kt(g,M,G,!1)}var Me=nn,as=gt;on.Fragment=s,on.jsx=Me,on.jsxs=as})()),on}var us;function Ea(){return us||(us=1,process.env.NODE_ENV==="production"?En.exports=Ta():En.exports=$a()),En.exports}var n=Ea();const ds={path:"/",history:[],location:0},ms={path:"*",data:{},hash:"",query:""},Fn=u.createContext(ds),ar=u.createContext(null),an=u.createContext(ms),fs=e=>({type:"NAVIGATE",payload:e}),Fa=(e=1)=>({type:"BACK",payload:e}),_a=(e=1)=>({type:"FORWARD",payload:e}),Pa=100;function za(e,t){switch(t.type){case"NAVIGATE":{let{history:r,location:s}=e;return s>0&&(r=r.slice(s)),{path:La(e.path,t.payload),history:[t.payload,...r].slice(0,Pa),location:0}}case"BACK":{const r=e.location+t.payload,s=e.history.at(r);return s?{path:s,history:e.history,location:r}:e}case"FORWARD":{const r=e.location-t.payload,s=e.history.at(r);return s?{path:s,history:e.history,location:r}:e}default:return e}}function ps(){return u.useContext(Fn).path}function _n(){const e=u.useContext(ar);return u.useCallback(t=>e?.(fs(t)),[e])}function Da(){const e=u.useContext(ar),t=u.useContext(Fn);return u.useMemo(()=>({navigate:r=>e?.(fs(r)),back:(r=1)=>e?.(Fa(r)),forward:(r=1)=>e?.(_a(r)),hasBack:t.location<t.history.length-1,...t}),[e,t])}function ir(){return u.useContext(an).data}function hs(){const{query:e,hash:t}=u.useContext(an);return u.useMemo(()=>({search:new URLSearchParams(e),hash:t}),[e,t])}function Ma({path:e,children:t}){const r=e?{path:e,history:[],location:0}:ds,[s,o]=u.useReducer(za,r);return n.jsx(Fn.Provider,{value:s,children:n.jsx(ar.Provider,{value:o,children:n.jsx(an.Provider,{value:ms,children:t})})})}const Pn=u.forwardRef(({to:e,children:t,...r},s)=>{const o=_n(),i=a=>{a.defaultPrevented||a.preventDefault(),o(e)};return n.jsx("a",{...r,href:e,ref:s,onClick:i,children:t})});function lr({children:e}){const t=u.useContext(an),r=u.useContext(Fn),s=xs(e,t.path),o=Ia(s.map(a=>a.route),r.path);if(!o)return n.jsx(n.Fragment,{});const i=s.find(a=>a.route===o.route).element;return n.jsx(an.Provider,{value:{...o.match},children:i})}function gs(e){let t=0;for(const r of e.split("/"))r===""||r==="*"||(t+=r.startsWith(":")?1:100);return t}function Ia(e,t){let r=null;for(const s of e){const o=qa(s,t);o.isMatch&&(r===null||gs(s)>gs(r.route))&&(r={route:s,match:o})}return r}function Be({path:e,element:t}){return n.jsx(n.Fragment,{})}function xs(e,t){const r=[];return u.Children.map(e,s=>{if(!u.isValidElement(s))return;if(s.type===u.Fragment){r.push.apply(r,xs(s.props.children,t));return}const o=s.props;return r.push({route:Aa(t,o.path),element:o.element}),s}),r}const La=(e,t)=>{if(t.startsWith("/"))return t;if(t.startsWith("?")){const[o]=e?.split("?")??[""];return o+t}let r=0;const s=t.split("/").filter(o=>o!=="");for(;s.length>0&&(s[0]==="."||s[0]==="..");)s.shift()==".."&&++r;return Oa(e,s.join("/"),r)},Oa=(e,t,r)=>{const s=e.split("/").filter(a=>a!==""),o=t.split("/").filter(a=>a!=="");return`/${[...s.slice(0,Math.max(0,s.length-r)),...o].join("/")}`},Aa=(e,t)=>{const r=e.split("/").filter(o=>o!==""),s=t.split("/").filter(o=>o!=="");return r.length>0&&r.at(-1)==="*"&&r.pop(),r.length===0?`/${s.join("/")}`:`/${r.join("/")}/${s.join("/")}`},qa=(e,t)=>{let r=e.split("/"),s=t.split("/");if(r.at(-1)===""&&(r=r.slice(0,-1)),s.at(-1)===""&&(s=s.slice(0,-1)),r.length>s.length)return{isMatch:!1,remainer:"",data:{},query:"",hash:"",path:""};if(r.length<s.length&&r.at(-1)!=="*")return{isMatch:!1,remainer:"",data:{},query:"",hash:"",path:""};let o={},i="",a="";for(let l=0;l<r.length;++l){const c=r[l],d=[...s[l].matchAll(/([?#]?)((?:(?![?#]).)*)/g)],f=d?.find(p=>p[1]==="")?.[2]??"";if(i=d?.find(p=>p[1]==="?")?.[2]??"",a=d?.find(p=>p[1]==="#")?.[2]??"",c.startsWith(":")&&f&&f!==""){o[c.substring(1)]=f;continue}if(c==="*"){const x=[...s.slice(l).join("/").matchAll(/([?#]?)((?:(?![?#]).)*)/g)];return{isMatch:!0,data:o,remainer:x.find(h=>h[1]==="")?.[2]??"",query:x.find(h=>h[1]==="?")?.[2]??"",hash:x.find(h=>h[1]==="#")?.[2]??"",path:s.slice(0,l).join("/")}}if(c!==f)return{isMatch:!1,data:{},remainer:"",query:"",hash:"",path:""}}return{isMatch:!0,remainer:"",data:o,query:i,hash:a,path:t?.split("?")?.[0]??""}},Va=`
14
+ <%s key={someKey} {...props} />`,as,Yt,wm,Yt),Ke[Yt+as]=!0}}return g===s?ht(Fe):ot(Fe),Fe}}function gt(g,M,G){return kt(g,M,G,!0)}function nn(g,M,G){return kt(g,M,G,!1)}var Me=nn,os=gt;on.Fragment=s,on.jsx=Me,on.jsxs=os})()),on}var cs;function Fa(){return cs||(cs=1,process.env.NODE_ENV==="production"?En.exports=$a():En.exports=Ea()),En.exports}var n=Fa();const us={path:"/",history:[],location:0},ds={path:"*",data:{},hash:"",query:""},Fn=u.createContext(us),ir=u.createContext(null),an=u.createContext(ds),ms=e=>({type:"NAVIGATE",payload:e}),_a=(e=1)=>({type:"BACK",payload:e}),Pa=(e=1)=>({type:"FORWARD",payload:e}),za=100;function Da(e,t){switch(t.type){case"NAVIGATE":{let{history:r}=e;const{location:s}=e;return s>0&&(r=r.slice(s)),{path:Oa(e.path,t.payload),history:[t.payload,...r].slice(0,za),location:0}}case"BACK":{const r=e.location+t.payload,s=e.history.at(r);return s?{path:s,history:e.history,location:r}:e}case"FORWARD":{const r=e.location-t.payload,s=e.history.at(r);return s?{path:s,history:e.history,location:r}:e}default:return e}}function fs(){return u.useContext(Fn).path}function _n(){const e=u.useContext(ir);return u.useCallback(t=>e?.(ms(t)),[e])}function Ma(){const e=u.useContext(ir),t=u.useContext(Fn);return u.useMemo(()=>({navigate:r=>e?.(ms(r)),back:(r=1)=>e?.(_a(r)),forward:(r=1)=>e?.(Pa(r)),hasBack:t.location<t.history.length-1,...t}),[e,t])}function lr(){return u.useContext(an).data}function ps(){const{query:e,hash:t}=u.useContext(an);return u.useMemo(()=>({search:new URLSearchParams(e),hash:t}),[e,t])}function Ia({path:e,children:t}){const r=e?{path:e,history:[],location:0}:us,[s,o]=u.useReducer(Da,r);return n.jsx(Fn.Provider,{value:s,children:n.jsx(ir.Provider,{value:o,children:n.jsx(an.Provider,{value:ds,children:t})})})}const Pn=u.forwardRef(({to:e,children:t,...r},s)=>{const o=_n(),i=a=>{a.defaultPrevented||a.preventDefault(),o(e)};return n.jsx("a",{...r,href:e,ref:s,onClick:i,children:t})});function cr({children:e}){const t=u.useContext(an),r=u.useContext(Fn),s=gs(e,t.path),o=La(s.map(a=>a.route),r.path);if(!o)return n.jsx(n.Fragment,{});const i=s.find(a=>a.route===o.route).element;return n.jsx(an.Provider,{value:{...o.match},children:i})}function hs(e){let t=0;for(const r of e.split("/"))r===""||r==="*"||(t+=r.startsWith(":")?1:100);return t}function La(e,t){let r=null;for(const s of e){const o=Va(s,t);o.isMatch&&(r===null||hs(s)>hs(r.route))&&(r={route:s,match:o})}return r}function Be(e){return n.jsx(n.Fragment,{})}function gs(e,t){const r=[];return u.Children.map(e,s=>{if(!u.isValidElement(s))return;if(s.type===u.Fragment){r.push(...gs(s.props.children,t));return}const o=s.props;return r.push({route:qa(t,o.path),element:o.element}),s}),r}const Oa=(e,t)=>{if(t.startsWith("/"))return t;if(t.startsWith("?")){const[o]=e?.split("?")??[""];return o+t}let r=0;const s=t.split("/").filter(o=>o!=="");for(;s.length>0&&(s[0]==="."||s[0]==="..");)s.shift()==".."&&++r;return Aa(e,s.join("/"),r)},Aa=(e,t,r)=>{const s=e.split("/").filter(a=>a!==""),o=t.split("/").filter(a=>a!=="");return`/${[...s.slice(0,Math.max(0,s.length-r)),...o].join("/")}`},qa=(e,t)=>{const r=e.split("/").filter(o=>o!==""),s=t.split("/").filter(o=>o!=="");return r.length>0&&r.at(-1)==="*"&&r.pop(),r.length===0?`/${s.join("/")}`:`/${r.join("/")}/${s.join("/")}`},Va=(e,t)=>{let r=e.split("/"),s=t.split("/");if(r.at(-1)===""&&(r=r.slice(0,-1)),s.at(-1)===""&&(s=s.slice(0,-1)),r.length>s.length)return{isMatch:!1,remainer:"",data:{},query:"",hash:"",path:""};if(r.length<s.length&&r.at(-1)!=="*")return{isMatch:!1,remainer:"",data:{},query:"",hash:"",path:""};const o={};let i="",a="";for(let l=0;l<r.length;++l){const c=r[l],d=[...s[l].matchAll(/([?#]?)((?:(?![?#]).)*)/g)],p=d?.find(f=>f[1]==="")?.[2]??"";if(i=d?.find(f=>f[1]==="?")?.[2]??"",a=d?.find(f=>f[1]==="#")?.[2]??"",c.startsWith(":")&&p&&p!==""){o[c.substring(1)]=p;continue}if(c==="*"){const x=[...s.slice(l).join("/").matchAll(/([?#]?)((?:(?![?#]).)*)/g)];return{isMatch:!0,data:o,remainer:x.find(h=>h[1]==="")?.[2]??"",query:x.find(h=>h[1]==="?")?.[2]??"",hash:x.find(h=>h[1]==="#")?.[2]??"",path:s.slice(0,l).join("/")}}if(c!==p)return{isMatch:!1,data:{},remainer:"",query:"",hash:"",path:""}}return{isMatch:!0,remainer:"",data:o,query:i,hash:a,path:t?.split("?")?.[0]??""}},Ba=`
15
15
  query dbSchema {
16
16
  _dbSchema {
17
17
  dbName
@@ -84,39 +84,39 @@ query dbSchema {
84
84
  columns
85
85
  }
86
86
  }
87
- }`;class bs extends Error{constructor(t,r){super(t.map(s=>s.message).join("; ")),this.errors=t,this.data=r,this.name="GraphQLRequestError"}errors;data}class ys{constructor(t){this.uri=t}uri;async query(t,r,s){const o=await fetch(this.uri,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:t,variables:r}),signal:s?.signal});if(!o.ok)throw new Error(`GraphQL request failed: ${o.status} ${o.statusText}`);const i=await o.json();if(i.errors?.length)throw new bs(i.errors,i.data);return i.data}}const vs=u.createContext(null),js=vs.Provider;function $e(){const e=u.useContext(vs);if(!e)throw new Error("useFetcher must be used within a FetcherProvider");return e}function Ba(e){const t=e.lastIndexOf(".");return t>=0?e.slice(t+1):e}function Ga(e){return Ba(e).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[_\-\s]+/).filter(Boolean)}function Ka(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}function zn(e){return e&&Ga(e).map(Ka).join(" ")}const Wa={showStats:!1},ws=u.createContext(Wa);function Ja({config:e,children:t}){return n.jsx(ws.Provider,{value:e,children:t})}function cr(){return u.useContext(ws)}const Cs=u.createContext({loading:!0,error:null,data:[],findTable:()=>{}}),Ns=({children:e})=>{const t=Ha();return n.jsx(Cs.Provider,{value:t,children:e})};function Je(){return u.useContext(Cs)}function Qa(e,t){if(!t||t.length===0)return e;const r=new Set(t.map(s=>s.toLowerCase()));return e.filter(s=>r.has(s.graphQlName.toLowerCase())||r.has(s.dbName.toLowerCase()))}function Ha(){const e=$e(),{tables:t}=cr(),{isLoading:r,error:s,data:o}=de.useQuery({queryKey:["dbSchema"],queryFn:()=>e.query(Va),staleTime:1/0});return u.useMemo(()=>{if(r)return{loading:!0,error:null,data:[],findTable:()=>{}};if(s)return{loading:!1,error:{message:s.message},data:[],findTable:()=>{}};if(!o)return{loading:!1,error:null,data:[],findTable:()=>{}};const i=o._dbSchema.map(c=>({...c,name:c.graphQlName,label:zn(c.dbName),metadata:ks(c.metadata),columns:c.columns.map(m=>({...m,name:m.graphQlName,label:zn(m.dbName),metadata:ks(m.metadata),inputType:Xa(m.inputType)}))})),a=Qa(i,t);return{loading:!1,error:null,data:a,findTable:c=>a.find(m=>m.graphQlName===c)}},[r,s,o,t])}function ks(e){return e.reduce((t,r)=>({...t,[r.key]:Ua(r)}),{})}function Ua({key:e,value:t}){return e==="type"?Ya(t):t}function Ya(e){const t=e.match(/lookup\s*\(\s*(?<id>\w+)\s*,\s*(?<label>\w+)\s*\)/m);if(t?.groups?.id&&t?.groups?.label)return{type:"lookup",id:t.groups.id,label:t.groups.label}}const Ra=["text","email","url","tel","date","datetime-local","number","password","search"];function Xa(e){if(e&&Ra.includes(e))return e}function Ss(e){var t,r,s="";if(typeof e=="string"||typeof e=="number")s+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(r=Ss(e[t]))&&(s&&(s+=" "),s+=r)}else for(r in e)e[r]&&(s&&(s+=" "),s+=r);return s}function Ts(){for(var e,t,r=0,s="",o=arguments.length;r<o;r++)(e=arguments[r])&&(t=Ss(e))&&(s&&(s+=" "),s+=t);return s}const $s=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Es=Ts,Fs=(e,t)=>r=>{var s;if(t?.variants==null)return Es(e,r?.class,r?.className);const{variants:o,defaultVariants:i}=t,a=Object.keys(o).map(m=>{const d=r?.[m],f=i?.[m];if(d===null)return null;const p=$s(d)||$s(f);return o[m][p]}),l=r&&Object.entries(r).reduce((m,d)=>{let[f,p]=d;return p===void 0||(m[f]=p),m},{}),c=t==null||(s=t.compoundVariants)===null||s===void 0?void 0:s.reduce((m,d)=>{let{class:f,className:p,...x}=d;return Object.entries(x).every(h=>{let[y,N]=h;return Array.isArray(N)?N.includes({...i,...l}[y]):{...i,...l}[y]===N})?[...m,f,p]:m},[]);return Es(e,a,c,r?.class,r?.className)},Za=(e,t)=>{const r=new Array(e.length+t.length);for(let s=0;s<e.length;s++)r[s]=e[s];for(let s=0;s<t.length;s++)r[e.length+s]=t[s];return r},ei=(e,t)=>({classGroupId:e,validator:t}),_s=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),Dn="-",Ps=[],ti="arbitrary..",ni=e=>{const t=si(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:a=>{if(a.startsWith("[")&&a.endsWith("]"))return ri(a);const l=a.split(Dn),c=l[0]===""&&l.length>1?1:0;return zs(l,c,t)},getConflictingClassGroupIds:(a,l)=>{if(l){const c=s[a],m=r[a];return c?m?Za(m,c):c:m||Ps}return r[a]||Ps}}},zs=(e,t,r)=>{if(e.length-t===0)return r.classGroupId;const o=e[t],i=r.nextPart.get(o);if(i){const m=zs(e,t+1,i);if(m)return m}const a=r.validators;if(a===null)return;const l=t===0?e.join(Dn):e.slice(t).join(Dn),c=a.length;for(let m=0;m<c;m++){const d=a[m];if(d.validator(l))return d.classGroupId}},ri=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),r=t.indexOf(":"),s=t.slice(0,r);return s?ti+s:void 0})(),si=e=>{const{theme:t,classGroups:r}=e;return oi(r,t)},oi=(e,t)=>{const r=_s();for(const s in e){const o=e[s];ur(o,r,s,t)}return r},ur=(e,t,r,s)=>{const o=e.length;for(let i=0;i<o;i++){const a=e[i];ai(a,t,r,s)}},ai=(e,t,r,s)=>{if(typeof e=="string"){ii(e,t,r);return}if(typeof e=="function"){li(e,t,r,s);return}ci(e,t,r,s)},ii=(e,t,r)=>{const s=e===""?t:Ds(t,e);s.classGroupId=r},li=(e,t,r,s)=>{if(ui(e)){ur(e(s),t,r,s);return}t.validators===null&&(t.validators=[]),t.validators.push(ei(r,e))},ci=(e,t,r,s)=>{const o=Object.entries(e),i=o.length;for(let a=0;a<i;a++){const[l,c]=o[a];ur(c,Ds(t,l),r,s)}},Ds=(e,t)=>{let r=e;const s=t.split(Dn),o=s.length;for(let i=0;i<o;i++){const a=s[i];let l=r.nextPart.get(a);l||(l=_s(),r.nextPart.set(a,l)),r=l}return r},ui=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,di=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=Object.create(null),s=Object.create(null);const o=(i,a)=>{r[i]=a,t++,t>e&&(t=0,s=r,r=Object.create(null))};return{get(i){let a=r[i];if(a!==void 0)return a;if((a=s[i])!==void 0)return o(i,a),a},set(i,a){i in r?r[i]=a:o(i,a)}}},dr="!",Ms=":",mi=[],Is=(e,t,r,s,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:s,isExternal:o}),fi=e=>{const{prefix:t,experimentalParseClassName:r}=e;let s=o=>{const i=[];let a=0,l=0,c=0,m;const d=o.length;for(let y=0;y<d;y++){const N=o[y];if(a===0&&l===0){if(N===Ms){i.push(o.slice(c,y)),c=y+1;continue}if(N==="/"){m=y;continue}}N==="["?a++:N==="]"?a--:N==="("?l++:N===")"&&l--}const f=i.length===0?o:o.slice(c);let p=f,x=!1;f.endsWith(dr)?(p=f.slice(0,-1),x=!0):f.startsWith(dr)&&(p=f.slice(1),x=!0);const h=m&&m>c?m-c:void 0;return Is(i,x,p,h)};if(t){const o=t+Ms,i=s;s=a=>a.startsWith(o)?i(a.slice(o.length)):Is(mi,!1,a,void 0,!0)}if(r){const o=s;s=i=>r({className:i,parseClassName:o})}return s},pi=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((r,s)=>{t.set(r,1e6+s)}),r=>{const s=[];let o=[];for(let i=0;i<r.length;i++){const a=r[i],l=a[0]==="[",c=t.has(a);l||c?(o.length>0&&(o.sort(),s.push(...o),o=[]),s.push(a)):o.push(a)}return o.length>0&&(o.sort(),s.push(...o)),s}},hi=e=>({cache:di(e.cacheSize),parseClassName:fi(e),sortModifiers:pi(e),postfixLookupClassGroupIds:gi(e),...ni(e)}),gi=e=>{const t=Object.create(null),r=e.postfixLookupClassGroups;if(r)for(let s=0;s<r.length;s++)t[r[s]]=!0;return t},xi=/\s+/,bi=(e,t)=>{const{parseClassName:r,getClassGroupId:s,getConflictingClassGroupIds:o,sortModifiers:i,postfixLookupClassGroupIds:a}=t,l=[],c=e.trim().split(xi);let m="";for(let d=c.length-1;d>=0;d-=1){const f=c[d],{isExternal:p,modifiers:x,hasImportantModifier:h,baseClassName:y,maybePostfixModifierPosition:N}=r(f);if(p){m=f+(m.length>0?" "+m:m);continue}let T=!!N,k;if(T){const F=y.substring(0,N);k=s(F);const j=k&&a[k]?s(y):void 0;j&&j!==k&&(k=j,T=!1)}else k=s(y);if(!k){if(!T){m=f+(m.length>0?" "+m:m);continue}if(k=s(y),!k){m=f+(m.length>0?" "+m:m);continue}T=!1}const $=x.length===0?"":x.length===1?x[0]:i(x).join(":"),b=h?$+dr:$,v=b+k;if(l.indexOf(v)>-1)continue;l.push(v);const w=o(k,T);for(let F=0;F<w.length;++F){const j=w[F];l.push(b+j)}m=f+(m.length>0?" "+m:m)}return m},yi=(...e)=>{let t=0,r,s,o="";for(;t<e.length;)(r=e[t++])&&(s=Ls(r))&&(o&&(o+=" "),o+=s);return o},Ls=e=>{if(typeof e=="string")return e;let t,r="";for(let s=0;s<e.length;s++)e[s]&&(t=Ls(e[s]))&&(r&&(r+=" "),r+=t);return r},vi=(e,...t)=>{let r,s,o,i;const a=c=>{const m=t.reduce((d,f)=>f(d),e());return r=hi(m),s=r.cache.get,o=r.cache.set,i=l,l(c)},l=c=>{const m=s(c);if(m)return m;const d=bi(c,r);return o(c,d),d};return i=a,(...c)=>i(yi(...c))},ji=[],_e=e=>{const t=r=>r[e]||ji;return t.isThemeGetter=!0,t},Os=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,As=/^\((?:(\w[\w-]*):)?(.+)\)$/i,wi=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,Ci=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Ni=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,ki=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Si=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Ti=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,St=e=>wi.test(e),oe=e=>!!e&&!Number.isNaN(Number(e)),ct=e=>!!e&&Number.isInteger(Number(e)),mr=e=>e.endsWith("%")&&oe(e.slice(0,-1)),xt=e=>Ci.test(e),qs=()=>!0,$i=e=>Ni.test(e)&&!ki.test(e),fr=()=>!1,Ei=e=>Si.test(e),Fi=e=>Ti.test(e),_i=e=>!K(e)&&!J(e),Pi=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),zi=e=>Tt(e,Js,fr),K=e=>Os.test(e),Ot=e=>Tt(e,Qs,$i),Vs=e=>Tt(e,Vi,oe),Di=e=>Tt(e,Us,qs),Mi=e=>Tt(e,Hs,fr),Bs=e=>Tt(e,Ks,fr),Ii=e=>Tt(e,Ws,Fi),Mn=e=>Tt(e,Ys,Ei),J=e=>As.test(e),ln=e=>At(e,Qs),Li=e=>At(e,Hs),Gs=e=>At(e,Ks),Oi=e=>At(e,Js),Ai=e=>At(e,Ws),In=e=>At(e,Ys,!0),qi=e=>At(e,Us,!0),Tt=(e,t,r)=>{const s=Os.exec(e);return s?s[1]?t(s[1]):r(s[2]):!1},At=(e,t,r=!1)=>{const s=As.exec(e);return s?s[1]?t(s[1]):r:!1},Ks=e=>e==="position"||e==="percentage",Ws=e=>e==="image"||e==="url",Js=e=>e==="length"||e==="size"||e==="bg-size",Qs=e=>e==="length",Vi=e=>e==="number",Hs=e=>e==="family-name",Us=e=>e==="number"||e==="weight",Ys=e=>e==="shadow",Bi=vi(()=>{const e=_e("color"),t=_e("font"),r=_e("text"),s=_e("font-weight"),o=_e("tracking"),i=_e("leading"),a=_e("breakpoint"),l=_e("container"),c=_e("spacing"),m=_e("radius"),d=_e("shadow"),f=_e("inset-shadow"),p=_e("text-shadow"),x=_e("drop-shadow"),h=_e("blur"),y=_e("perspective"),N=_e("aspect"),T=_e("ease"),k=_e("animate"),$=()=>["auto","avoid","all","avoid-page","page","left","right","column"],b=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],v=()=>[...b(),J,K],w=()=>["auto","hidden","clip","visible","scroll"],F=()=>["auto","contain","none"],j=()=>[J,K,c],V=()=>[St,"full","auto",...j()],S=()=>[ct,"none","subgrid",J,K],L=()=>["auto",{span:["full",ct,J,K]},ct,J,K],A=()=>[ct,"auto",J,K],D=()=>["auto","min","max","fr",J,K],B=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],X=()=>["start","end","center","stretch","center-safe","end-safe"],E=()=>["auto",...j()],P=()=>[St,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...j()],q=()=>[St,"screen","full","dvw","lvw","svw","min","max","fit",...j()],U=()=>[St,"screen","full","lh","dvh","lvh","svh","min","max","fit",...j()],_=()=>[e,J,K],ce=()=>[...b(),Gs,Bs,{position:[J,K]}],he=()=>["no-repeat",{repeat:["","x","y","space","round"]}],Ue=()=>["auto","cover","contain",Oi,zi,{size:[J,K]}],Pe=()=>[mr,ln,Ot],ie=()=>["","none","full",m,J,K],se=()=>["",oe,ln,Ot],ke=()=>["solid","dashed","dotted","double"],Ae=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],re=()=>[oe,mr,Gs,Bs],Ee=()=>["","none",h,J,K],Ie=()=>["none",oe,J,K],Le=()=>["none",oe,J,K],Ge=()=>[oe,J,K],Oe=()=>[St,"full",...j()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[xt],breakpoint:[xt],color:[qs],container:[xt],"drop-shadow":[xt],ease:["in","out","in-out"],font:[_i],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[xt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[xt],shadow:[xt],spacing:["px",oe],text:[xt],"text-shadow":[xt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",St,K,J,N]}],container:["container"],"container-type":[{"@container":["","normal","size",J,K]}],"container-named":[Pi],columns:[{columns:[oe,K,J,l]}],"break-after":[{"break-after":$()}],"break-before":[{"break-before":$()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:v()}],overflow:[{overflow:w()}],"overflow-x":[{"overflow-x":w()}],"overflow-y":[{"overflow-y":w()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:V()}],"inset-x":[{"inset-x":V()}],"inset-y":[{"inset-y":V()}],start:[{"inset-s":V(),start:V()}],end:[{"inset-e":V(),end:V()}],"inset-bs":[{"inset-bs":V()}],"inset-be":[{"inset-be":V()}],top:[{top:V()}],right:[{right:V()}],bottom:[{bottom:V()}],left:[{left:V()}],visibility:["visible","invisible","collapse"],z:[{z:[ct,"auto",J,K]}],basis:[{basis:[St,"full","auto",l,...j()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[oe,St,"auto","initial","none",K]}],grow:[{grow:["",oe,J,K]}],shrink:[{shrink:["",oe,J,K]}],order:[{order:[ct,"first","last","none",J,K]}],"grid-cols":[{"grid-cols":S()}],"col-start-end":[{col:L()}],"col-start":[{"col-start":A()}],"col-end":[{"col-end":A()}],"grid-rows":[{"grid-rows":S()}],"row-start-end":[{row:L()}],"row-start":[{"row-start":A()}],"row-end":[{"row-end":A()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":D()}],"auto-rows":[{"auto-rows":D()}],gap:[{gap:j()}],"gap-x":[{"gap-x":j()}],"gap-y":[{"gap-y":j()}],"justify-content":[{justify:[...B(),"normal"]}],"justify-items":[{"justify-items":[...X(),"normal"]}],"justify-self":[{"justify-self":["auto",...X()]}],"align-content":[{content:["normal",...B()]}],"align-items":[{items:[...X(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...X(),{baseline:["","last"]}]}],"place-content":[{"place-content":B()}],"place-items":[{"place-items":[...X(),"baseline"]}],"place-self":[{"place-self":["auto",...X()]}],p:[{p:j()}],px:[{px:j()}],py:[{py:j()}],ps:[{ps:j()}],pe:[{pe:j()}],pbs:[{pbs:j()}],pbe:[{pbe:j()}],pt:[{pt:j()}],pr:[{pr:j()}],pb:[{pb:j()}],pl:[{pl:j()}],m:[{m:E()}],mx:[{mx:E()}],my:[{my:E()}],ms:[{ms:E()}],me:[{me:E()}],mbs:[{mbs:E()}],mbe:[{mbe:E()}],mt:[{mt:E()}],mr:[{mr:E()}],mb:[{mb:E()}],ml:[{ml:E()}],"space-x":[{"space-x":j()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":j()}],"space-y-reverse":["space-y-reverse"],size:[{size:P()}],"inline-size":[{inline:["auto",...q()]}],"min-inline-size":[{"min-inline":["auto",...q()]}],"max-inline-size":[{"max-inline":["none",...q()]}],"block-size":[{block:["auto",...U()]}],"min-block-size":[{"min-block":["auto",...U()]}],"max-block-size":[{"max-block":["none",...U()]}],w:[{w:[l,"screen",...P()]}],"min-w":[{"min-w":[l,"screen","none",...P()]}],"max-w":[{"max-w":[l,"screen","none","prose",{screen:[a]},...P()]}],h:[{h:["screen","lh",...P()]}],"min-h":[{"min-h":["screen","lh","none",...P()]}],"max-h":[{"max-h":["screen","lh",...P()]}],"font-size":[{text:["base",r,ln,Ot]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,qi,Di]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",mr,K]}],"font-family":[{font:[Li,Mi,t]}],"font-features":[{"font-features":[K]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,J,K]}],"line-clamp":[{"line-clamp":[oe,"none",J,Vs]}],leading:[{leading:[i,...j()]}],"list-image":[{"list-image":["none",J,K]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",J,K]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:_()}],"text-color":[{text:_()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ke(),"wavy"]}],"text-decoration-thickness":[{decoration:[oe,"from-font","auto",J,Ot]}],"text-decoration-color":[{decoration:_()}],"underline-offset":[{"underline-offset":[oe,"auto",J,K]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:j()}],"tab-size":[{tab:[ct,J,K]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",J,K]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",J,K]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:ce()}],"bg-repeat":[{bg:he()}],"bg-size":[{bg:Ue()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ct,J,K],radial:["",J,K],conic:[ct,J,K]},Ai,Ii]}],"bg-color":[{bg:_()}],"gradient-from-pos":[{from:Pe()}],"gradient-via-pos":[{via:Pe()}],"gradient-to-pos":[{to:Pe()}],"gradient-from":[{from:_()}],"gradient-via":[{via:_()}],"gradient-to":[{to:_()}],rounded:[{rounded:ie()}],"rounded-s":[{"rounded-s":ie()}],"rounded-e":[{"rounded-e":ie()}],"rounded-t":[{"rounded-t":ie()}],"rounded-r":[{"rounded-r":ie()}],"rounded-b":[{"rounded-b":ie()}],"rounded-l":[{"rounded-l":ie()}],"rounded-ss":[{"rounded-ss":ie()}],"rounded-se":[{"rounded-se":ie()}],"rounded-ee":[{"rounded-ee":ie()}],"rounded-es":[{"rounded-es":ie()}],"rounded-tl":[{"rounded-tl":ie()}],"rounded-tr":[{"rounded-tr":ie()}],"rounded-br":[{"rounded-br":ie()}],"rounded-bl":[{"rounded-bl":ie()}],"border-w":[{border:se()}],"border-w-x":[{"border-x":se()}],"border-w-y":[{"border-y":se()}],"border-w-s":[{"border-s":se()}],"border-w-e":[{"border-e":se()}],"border-w-bs":[{"border-bs":se()}],"border-w-be":[{"border-be":se()}],"border-w-t":[{"border-t":se()}],"border-w-r":[{"border-r":se()}],"border-w-b":[{"border-b":se()}],"border-w-l":[{"border-l":se()}],"divide-x":[{"divide-x":se()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":se()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ke(),"hidden","none"]}],"divide-style":[{divide:[...ke(),"hidden","none"]}],"border-color":[{border:_()}],"border-color-x":[{"border-x":_()}],"border-color-y":[{"border-y":_()}],"border-color-s":[{"border-s":_()}],"border-color-e":[{"border-e":_()}],"border-color-bs":[{"border-bs":_()}],"border-color-be":[{"border-be":_()}],"border-color-t":[{"border-t":_()}],"border-color-r":[{"border-r":_()}],"border-color-b":[{"border-b":_()}],"border-color-l":[{"border-l":_()}],"divide-color":[{divide:_()}],"outline-style":[{outline:[...ke(),"none","hidden"]}],"outline-offset":[{"outline-offset":[oe,J,K]}],"outline-w":[{outline:["",oe,ln,Ot]}],"outline-color":[{outline:_()}],shadow:[{shadow:["","none",d,In,Mn]}],"shadow-color":[{shadow:_()}],"inset-shadow":[{"inset-shadow":["none",f,In,Mn]}],"inset-shadow-color":[{"inset-shadow":_()}],"ring-w":[{ring:se()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:_()}],"ring-offset-w":[{"ring-offset":[oe,Ot]}],"ring-offset-color":[{"ring-offset":_()}],"inset-ring-w":[{"inset-ring":se()}],"inset-ring-color":[{"inset-ring":_()}],"text-shadow":[{"text-shadow":["none",p,In,Mn]}],"text-shadow-color":[{"text-shadow":_()}],opacity:[{opacity:[oe,J,K]}],"mix-blend":[{"mix-blend":[...Ae(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Ae()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[oe]}],"mask-image-linear-from-pos":[{"mask-linear-from":re()}],"mask-image-linear-to-pos":[{"mask-linear-to":re()}],"mask-image-linear-from-color":[{"mask-linear-from":_()}],"mask-image-linear-to-color":[{"mask-linear-to":_()}],"mask-image-t-from-pos":[{"mask-t-from":re()}],"mask-image-t-to-pos":[{"mask-t-to":re()}],"mask-image-t-from-color":[{"mask-t-from":_()}],"mask-image-t-to-color":[{"mask-t-to":_()}],"mask-image-r-from-pos":[{"mask-r-from":re()}],"mask-image-r-to-pos":[{"mask-r-to":re()}],"mask-image-r-from-color":[{"mask-r-from":_()}],"mask-image-r-to-color":[{"mask-r-to":_()}],"mask-image-b-from-pos":[{"mask-b-from":re()}],"mask-image-b-to-pos":[{"mask-b-to":re()}],"mask-image-b-from-color":[{"mask-b-from":_()}],"mask-image-b-to-color":[{"mask-b-to":_()}],"mask-image-l-from-pos":[{"mask-l-from":re()}],"mask-image-l-to-pos":[{"mask-l-to":re()}],"mask-image-l-from-color":[{"mask-l-from":_()}],"mask-image-l-to-color":[{"mask-l-to":_()}],"mask-image-x-from-pos":[{"mask-x-from":re()}],"mask-image-x-to-pos":[{"mask-x-to":re()}],"mask-image-x-from-color":[{"mask-x-from":_()}],"mask-image-x-to-color":[{"mask-x-to":_()}],"mask-image-y-from-pos":[{"mask-y-from":re()}],"mask-image-y-to-pos":[{"mask-y-to":re()}],"mask-image-y-from-color":[{"mask-y-from":_()}],"mask-image-y-to-color":[{"mask-y-to":_()}],"mask-image-radial":[{"mask-radial":[J,K]}],"mask-image-radial-from-pos":[{"mask-radial-from":re()}],"mask-image-radial-to-pos":[{"mask-radial-to":re()}],"mask-image-radial-from-color":[{"mask-radial-from":_()}],"mask-image-radial-to-color":[{"mask-radial-to":_()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[oe]}],"mask-image-conic-from-pos":[{"mask-conic-from":re()}],"mask-image-conic-to-pos":[{"mask-conic-to":re()}],"mask-image-conic-from-color":[{"mask-conic-from":_()}],"mask-image-conic-to-color":[{"mask-conic-to":_()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:ce()}],"mask-repeat":[{mask:he()}],"mask-size":[{mask:Ue()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",J,K]}],filter:[{filter:["","none",J,K]}],blur:[{blur:Ee()}],brightness:[{brightness:[oe,J,K]}],contrast:[{contrast:[oe,J,K]}],"drop-shadow":[{"drop-shadow":["","none",x,In,Mn]}],"drop-shadow-color":[{"drop-shadow":_()}],grayscale:[{grayscale:["",oe,J,K]}],"hue-rotate":[{"hue-rotate":[oe,J,K]}],invert:[{invert:["",oe,J,K]}],saturate:[{saturate:[oe,J,K]}],sepia:[{sepia:["",oe,J,K]}],"backdrop-filter":[{"backdrop-filter":["","none",J,K]}],"backdrop-blur":[{"backdrop-blur":Ee()}],"backdrop-brightness":[{"backdrop-brightness":[oe,J,K]}],"backdrop-contrast":[{"backdrop-contrast":[oe,J,K]}],"backdrop-grayscale":[{"backdrop-grayscale":["",oe,J,K]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[oe,J,K]}],"backdrop-invert":[{"backdrop-invert":["",oe,J,K]}],"backdrop-opacity":[{"backdrop-opacity":[oe,J,K]}],"backdrop-saturate":[{"backdrop-saturate":[oe,J,K]}],"backdrop-sepia":[{"backdrop-sepia":["",oe,J,K]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":j()}],"border-spacing-x":[{"border-spacing-x":j()}],"border-spacing-y":[{"border-spacing-y":j()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",J,K]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[oe,"initial",J,K]}],ease:[{ease:["linear","initial",T,J,K]}],delay:[{delay:[oe,J,K]}],animate:[{animate:["none",k,J,K]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[y,J,K]}],"perspective-origin":[{"perspective-origin":v()}],rotate:[{rotate:Ie()}],"rotate-x":[{"rotate-x":Ie()}],"rotate-y":[{"rotate-y":Ie()}],"rotate-z":[{"rotate-z":Ie()}],scale:[{scale:Le()}],"scale-x":[{"scale-x":Le()}],"scale-y":[{"scale-y":Le()}],"scale-z":[{"scale-z":Le()}],"scale-3d":["scale-3d"],skew:[{skew:Ge()}],"skew-x":[{"skew-x":Ge()}],"skew-y":[{"skew-y":Ge()}],transform:[{transform:[J,K,"","none","gpu","cpu"]}],"transform-origin":[{origin:v()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Oe()}],"translate-x":[{"translate-x":Oe()}],"translate-y":[{"translate-y":Oe()}],"translate-z":[{"translate-z":Oe()}],"translate-none":["translate-none"],zoom:[{zoom:[ct,J,K]}],accent:[{accent:_()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:_()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",J,K]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":_()}],"scrollbar-track-color":[{"scrollbar-track":_()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":j()}],"scroll-mx":[{"scroll-mx":j()}],"scroll-my":[{"scroll-my":j()}],"scroll-ms":[{"scroll-ms":j()}],"scroll-me":[{"scroll-me":j()}],"scroll-mbs":[{"scroll-mbs":j()}],"scroll-mbe":[{"scroll-mbe":j()}],"scroll-mt":[{"scroll-mt":j()}],"scroll-mr":[{"scroll-mr":j()}],"scroll-mb":[{"scroll-mb":j()}],"scroll-ml":[{"scroll-ml":j()}],"scroll-p":[{"scroll-p":j()}],"scroll-px":[{"scroll-px":j()}],"scroll-py":[{"scroll-py":j()}],"scroll-ps":[{"scroll-ps":j()}],"scroll-pe":[{"scroll-pe":j()}],"scroll-pbs":[{"scroll-pbs":j()}],"scroll-pbe":[{"scroll-pbe":j()}],"scroll-pt":[{"scroll-pt":j()}],"scroll-pr":[{"scroll-pr":j()}],"scroll-pb":[{"scroll-pb":j()}],"scroll-pl":[{"scroll-pl":j()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",J,K]}],fill:[{fill:["none",..._()]}],"stroke-w":[{stroke:[oe,ln,Ot,Vs]}],stroke:[{stroke:["none",..._()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});function Y(...e){return Bi(Ts(e))}const Gi=Fs("relative grid w-full grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current"}},defaultVariants:{variant:"default"}});function Rt({className:e,variant:t,...r}){return n.jsx("div",{"data-slot":"alert",role:"alert",className:Y(Gi({variant:t}),e),...r})}function Rs({className:e,...t}){return n.jsx("div",{"data-slot":"alert-title",className:Y("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",e),...t})}function Xt({className:e,...t}){return n.jsx("div",{"data-slot":"alert-description",className:Y("col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed",e),...t})}const Qe=Ve.forwardRef(({className:e,type:t,...r},s)=>n.jsx("input",{type:t,ref:s,"data-slot":"input",className:Y("h-9 w-full min-w-0 rounded-md border border-input bg-transparent text-foreground px-3 py-0 text-sm shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...r}));Qe.displayName="Input";function Ln({...e}){return n.jsx(R.DropdownMenu.Root,{"data-slot":"dropdown-menu",...e})}function On({...e}){return n.jsx(R.DropdownMenu.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}function An({className:e,sideOffset:t=4,...r}){return n.jsx(R.DropdownMenu.Portal,{children:n.jsx(R.DropdownMenu.Content,{"data-slot":"dropdown-menu-content",sideOffset:t,className:Y("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...r})})}function bt({className:e,inset:t,variant:r="default",...s}){return n.jsx(R.DropdownMenu.Item,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":r,className:Y("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...s})}function Ki({className:e,children:t,checked:r,...s}){return n.jsxs(R.DropdownMenu.CheckboxItem,{"data-slot":"dropdown-menu-checkbox-item",className:Y("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),checked:r,...s,children:[n.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:n.jsx(R.DropdownMenu.ItemIndicator,{children:n.jsx(C.CheckIcon,{className:"size-4"})})}),t]})}function Wi({className:e,inset:t,...r}){return n.jsx(R.DropdownMenu.Label,{"data-slot":"dropdown-menu-label","data-inset":t,className:Y("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...r})}function yt({className:e,...t}){return n.jsx(R.DropdownMenu.Separator,{"data-slot":"dropdown-menu-separator",className:Y("-mx-1 my-1 h-px bg-border",e),...t})}function cn({...e}){return n.jsx(R.DropdownMenu.Sub,{"data-slot":"dropdown-menu-sub",...e})}function un({className:e,inset:t,children:r,...s}){return n.jsxs(R.DropdownMenu.SubTrigger,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:Y("flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...s,children:[r,n.jsx(C.ChevronRightIcon,{className:"ml-auto size-4"})]})}function dn({className:e,...t}){return n.jsx(R.DropdownMenu.SubContent,{"data-slot":"dropdown-menu-sub-content",className:Y("z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})}function ut(e){return(e??"").replace("!","")}const Xs=new Set(["Int","Short","Byte","BigInt"]),Ji=new Set(["Float","Decimal"]),Qi=new Set(["DateTime","DateTimeOffset"]),Hi=new Set(["BigInt","Decimal"]);function qt(e){return Xs.has(ut(e))}function Vt(e){const t=ut(e);return Xs.has(t)||Ji.has(t)}function Bt(e){return Hi.has(ut(e))}function Zs(e){return Qi.has(ut(e))}function Ui(e){return ut(e)==="String"}function eo(e,t){const r=e.trim();if(r===""||r==="-"||r==="+"||!(qt(t)?/^[+-]?\d+$/.test(r):/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?$/.test(r)))return null;if(Bt(t))return r;const o=Number(r);return Number.isFinite(o)?o:null}function dt(e,t){if(e==null)return null;if(Bt(t))return String(e);if(qt(t)){const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.trunc(r):e}switch(ut(t)){case"Float":{const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?r:e}case"Boolean":return typeof e=="boolean"?e:e==="true"||e===1?!0:e==="false"||e===0?!1:!!e;default:return String(e)}}function mn(e){return e?.paramType?.replace("!","")??"String"}function Gt(e){return(e.sourceColumnNames?.length??0)>1}function Yi(e,t){const r=(e.sourceColumnNames??[]).indexOf(t);return r<0?null:(e.destinationColumnNames??[])[r]??null}function Ri(e,t,r,s="fk"){if(!e)return null;const o=t.sourceColumnNames??[],i=t.destinationColumnNames??[];if(o.length===0||o.length!==i.length)return null;const a=new Map((r?.columns??[]).map(f=>[f.name,f])),l=[],c={},m=[];for(let f=0;f<o.length;f++){const p=o[f],x=i[f];if(!(p in e))return null;const h=mn(a.get(x)),y=`${s}_${x}`;c[y]=dt(e[p],h),m.push(`$${y}: ${h}`),l.push(`{${x}: {_eq: $${y}}}`)}return{filterText:l.length===1?l[0]:`{and: [${l.join(", ")}]}`,variables:c,params:m}}const pr="::";function Xi(e){return e==null?"":encodeURIComponent(String(e))}function hr(e){if(e==="")return null;try{return decodeURIComponent(e)}catch{return e}}function $t(e){return e.map(Xi).join(pr)}function to(e,t){const r=t<=1?[e]:e.split(pr);if(r.length!==t)throw new Error(`Route id '${e}' has ${r.length} part(s) but ${t} were expected.`);return r.map(s=>s===""?"":hr(s)??"")}function He(e,t,r){const s=t.primaryKeys??[];return s.length===0?`row-${r}`:$t(s.map(o=>e?.[o]))}function mt(e,t){const r=t.primaryKeys??[];if(r.length===0||e==null)return null;const s={};for(const o of r){if(!(o in e))return null;s[o]=e[o]}return s}function qn(e,t){const r=mt(e,t);if(!r)return null;const s=new Map((t.columns??[]).map(c=>[c.name,c])),o=[],i={},a=[];for(const c of t.primaryKeys??[]){const m=mn(s.get(c)),d=`pk_${c}`;i[d]=dt(r[c],m),a.push(`$${d}: ${m}`),o.push(`{${c}: {_eq: $${d}}}`)}return{filterText:o.length===1?o[0]:`{and: [${o.join(", ")}]}`,variables:i,params:a}}function Vn(e,t){const r=t.primaryKeys??[];return r.length===0?"":$t(r.map(s=>e[s]))}function fn(e,t){const r=t.primaryKeys??[];if(r.length===0)return null;const s=r.length===1?[e]:e.split(pr);if(s.length!==r.length)return null;const o={};for(let i=0;i<r.length;i++){const a=hr(s[i]);if(a===null)return null;o[r[i]]=a}return o}function Zi(e,t,r){if(!e)return;const s=e.filter(o=>o.destinationTable===t);if(s.length!==0){if(s.length===1)return s[0];if(r)return s.find(o=>o.destinationColumnNames?.[0]===r)}}function el(e){return e.fieldName??e.destinationTable}const tl=new Set(["binary","varbinary","image","blob","tinyblob","mediumblob","longblob","bytea"]),nl=new Set(["text","ntext","xml"]),rl=new Set(["json","jsonb"]);function Et(e){return tl.has(e.toLowerCase().replace(/\(.*\)/,""))}function no(e){return rl.has(e.toLowerCase().replace(/\(.*\)/,""))}function Ft(e){return no(e.dbType)||e.paramType==="JSON"}function gr(e){const t=e.toLowerCase(),r=t.replace(/\(.*\)/,"");return!!(nl.has(r)||t.includes("(max)"))}function _t(e){return typeof e.isLargeValue=="boolean"?e.isLargeValue:Et(e.dbType)||gr(e.dbType)}function Bn(e,t){if(!e)return"text";if(t&&Et(t))return"binary";if(t&&no(t))return"json";const r=e.trimStart();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{return JSON.parse(r),"json"}catch{}return r.startsWith("<?xml")||r.startsWith("<")&&r.includes("</")&&r.endsWith(">")?"xml":/^[aOsidb]:\d+[:{;]/.test(r)?"php-serialized":e.length>200||e.includes(`
88
- `)?"longtext":"text"}const ro=80;function sl(e){return e.length<=ro?e:e.slice(0,ro)+"..."}function xr(e){const t=Math.ceil(e.length*3/4);return t<1024?`${t} bytes`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function so(e){const t={kind:"unknown",mime:"application/octet-stream",extension:".bin"};let r;try{r=atob(e.slice(0,24))}catch{return t}const s=o=>r.charCodeAt(o);return r.length>=4&&s(0)===137&&r.slice(1,4)==="PNG"?{kind:"image",mime:"image/png",extension:".png"}:r.length>=3&&s(0)===255&&s(1)===216&&s(2)===255?{kind:"image",mime:"image/jpeg",extension:".jpg"}:r.slice(0,4)==="GIF8"?{kind:"image",mime:"image/gif",extension:".gif"}:r.slice(0,4)==="RIFF"&&r.slice(8,12)==="WEBP"?{kind:"image",mime:"image/webp",extension:".webp"}:r.slice(0,4)==="%PDF"?{kind:"pdf",mime:"application/pdf",extension:".pdf"}:t}function oo(e,t){return`data:${t};base64,${e}`}const Pt=["_eq","_neq","_gt","_gte","_lt","_lte","_between","_null"],br={String:["_eq","_neq","_contains","_starts_with","_ends_with","_null"],Int:Pt,Float:Pt,Short:Pt,Byte:Pt,BigInt:Pt,Decimal:Pt,Boolean:["_eq","_null"],DateTime:Pt,DateTimeOffset:Pt},ol=new Set(["DateTime","DateTimeOffset"]),al=/^[_A-Za-z][_0-9A-Za-z]*$/,il=/^[_A-Za-z][_0-9A-Za-z]*!?$/,ll=new Set(Object.values(br).flat());function it(e){return typeof e=="string"&&al.test(e)}function je(e,t){if(!it(e))throw new Error(`Invalid GraphQL ${t}: ${String(e)}`)}function cl(e){return typeof e=="string"&&il.test(e)}function ao(e,t){return typeof e=="string"&&pn(t).includes(e)}function pn(e){const t=e.replace("!","");return br[t]??br.String}function ul(){return{variables:{},param:"",filterText:"",error:null}}function hn(e){return{variables:{},param:"",filterText:"",error:e}}function yr(e){if(!e)return ul();let t;try{t=JSON.parse(e)}catch{return hn("The filter in the URL is not valid JSON.")}if(!Array.isArray(t)||t.length<4)return hn("The filter in the URL is malformed.");const[r,s,o,i]=t;return it(r)?cl(i)?ao(s,i)?{variables:{filter:o},param:`, $filter: ${i}`,filterText:`{${r}: {${s}: $filter} }`,error:null}:hn(`Filter operator '${String(s)}' is not supported for ${String(i)} column '${String(r)}'.`):hn(`Filter type '${String(i)}' is not a valid type name.`):hn(`Filter column '${String(r)}' is not a valid column name.`)}function dl(e,t,r=0){return He(e,t,r)}function io(e){const t=e.replace("!","");switch(t){case"Int":case"Float":case"Short":case"Byte":case"Boolean":case"BigInt":case"Decimal":case"DateTime":case"DateTimeOffset":return t;default:return"String"}}const ml=/^\d{4}-\d{2}-\d{2}$/;function fl(e){const t=e<=0?"+":"-",r=Math.abs(e),s=String(Math.floor(r/60)).padStart(2,"0"),o=String(r%60).padStart(2,"0");return`${t}${s}:${o}`}function lo(e,t,r,s){const i=`${e}T${t==="start"?"00:00:00.000":"23:59:59.999"}`;if(r!=="DateTimeOffset")return i;const a=new Date(`${e}T00:00:00`).getTimezoneOffset();return`${i}${fl(a)}`}function pl(e,t,r,s){if(!ol.has(r))return{operator:e,value:t};const o=l=>lo(String(l),"start",r),i=l=>lo(String(l),"end",r),a=l=>typeof l=="string"&&ml.test(l);if(e==="_between"){const l=Array.isArray(t)?t:null;return!l||l.length!==2?{operator:e,value:t}:{operator:e,value:[a(l[0])?o(l[0]):l[0],a(l[1])?i(l[1]):l[1]]}}if(!a(t))return{operator:e,value:t};switch(e){case"_eq":return{operator:"_between",value:[o(t),i(t)]};case"_neq":return{operator:"_nbetween",value:[o(t),i(t)]};case"_gt":case"_lte":return{operator:e,value:i(t)};default:return{operator:e,value:o(t)}}}function Gn(e,t){const r={},s=[],o=[],i=[];for(let a=0;a<e.length;a++){const l=e[a],c=l.value;if(c.value===void 0||c.value===null||c.value==="")continue;const m=t.columns.find(x=>x.name===l.id);if(!m){i.push(`Column '${String(l.id)}' is not on this table.`);continue}if(!it(l.id)){i.push(`Column '${String(l.id)}' is not a valid column name.`);continue}if(!ao(c.operator,m.paramType)){i.push(`Operator '${String(c.operator)}' is not supported for column '${l.id}'.`);continue}const d=`cf_${l.id}_${a}`,f=io(m.paramType);if(c.operator==="_null"){o.push(`{${l.id}: {_null: ${c.value?"true":"false"}}}`);continue}const p=pl(c.operator,c.value,f);if(p.operator==="_between"||p.operator==="_nbetween"){const x=p.value;if(!Array.isArray(x)||x.length!==2){i.push(`The range filter on column '${l.id}' needs exactly two bounds.`);continue}const h=`${d}_lo`,y=`${d}_hi`;r[h]=x[0],r[y]=x[1],s.push(`$${h}: ${f}`,`$${y}: ${f}`),o.push(`{${l.id}: {${p.operator}: [$${h}, $${y}]}}`);continue}r[d]=p.value,s.push(`$${d}: ${f}`),o.push(`{${l.id}: {${p.operator}: $${d}}}`)}return{variables:r,params:s,filterTexts:o,errors:i}}function co(e,t,r){const s=yr(t),o=Gn(r,e);return s.error?[s.error,...o.errors]:o.errors}function vr(e){return e.length===0?"":JSON.stringify(e.map(t=>[t.id,t.value.operator,t.value.value]))}function jr(e){try{if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(hl).map(([r,s,o])=>({id:r,value:{operator:s,value:o}})):[]}catch{return[]}}function hl(e){if(!Array.isArray(e)||e.length!==3)return!1;const[t,r]=e;return it(t)&&typeof r=="string"&&ll.has(r)}function uo(e){return zt(e)[0]?.gqlType??"Int"}function zt(e){const t=e.primaryKeys??[];if(t.length===0)return[];const r=new Map(e.columns.map(s=>[s.name,s]));return t.map(s=>({name:s,gqlType:r.get(s)?.paramType?.replace("!","")??"String"}))}function gl(e,t=()=>!0){const r=e.indexes??[];if(r.length===0)return null;const s=new Map(e.columns.map(i=>[i.name,i])),o=i=>{const a=i.columns[0],l=a?s.get(a):void 0;return l&&t(l)?l.name:null};for(const i of[a=>a.isClustered,a=>a.isUnique,()=>!0])for(const a of r){if(!i(a))continue;const l=o(a);if(l)return l}return null}function wr(e,t){if(zt(t).length<=1)return{id:dt(hr(e),uo(t))};const s=fn(e,t);return s?qn(s,t)?.variables??{}:{}}function Cr(e,t,r){je(e.name,"single-row table name");for(const o of r)je(o,"single-row selection field");const s=t.params.length>0?`(${t.params.join(", ")})`:"";return`query GetSingleRow_${e.name}${s} { value: ${e.name}(filter: ${t.filterText}) { data { ${r.join(" ")} } } }`}function mo(e,t,r){je(e.name,"rows-by-pk table name");for(const d of r)je(d,"rows-by-pk selection field");const s=e.primaryKeys??[];if(s.length===0||t.length===0||r.length===0)return null;for(const d of s)je(d,"rows-by-pk key column");const o=new Map((e.columns??[]).map(d=>[d.name,d])),i=[],a={},l=[];t.forEach((d,f)=>{const p=[];for(const x of s){const h=mn(o.get(x)),y=`pk${f}_${x}`;a[y]=dt(d[x],h),i.push(`$${y}: ${h}`),p.push(`{${x}: {_eq: $${y}}}`)}l.push(p.length===1?p[0]:`{and: [${p.join(", ")}]}`)});const c=l.length===1?l[0]:`{or: [${l.join(", ")}]}`;return{query:`query GetRowsByPk_${e.name}(${i.join(", ")}) { value: ${e.name}(filter: ${c} limit: ${t.length}) { data { ${r.join(" ")} } } }`,variables:a}}const xl=11;function fo(e,t){return t.map(r=>{const s=e.findTable(r.destinationTable),o=s?.labelColumn??"id",a=[...s?.primaryKeys?.length?s.primaryKeys:["id"]];return o&&!a.includes(o)&&a.push(o),`${r.fieldName??r.destinationTable}(limit: ${xl}) { total data { ${a.join(" ")} } }`}).join(" ")}function Nr(e,t,r,s){return`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${t}) { ${e.name}(sort: $sort limit: $limit offset: $offset ${r}) { total offset limit data {${s}}}}`}function bl(e,t,r){const s=new Set;return e.columns.filter(o=>o?.joinTable===void 0).filter(o=>o.isPrimaryKey||!_t(o)).map(o=>{const i=r.singleJoins.find(c=>c.sourceColumnNames?.[0]===o.name);if(!i)return o;const l=t.findTable(i.destinationTable)?.labelColumn??"id";return{...o,joinTable:i,joinLabelColumn:l}}).map(o=>{if(o?.joinTable){s.add(o.name);const i=t.findTable(o.joinTable.destinationTable),a=i?.primaryKeys?.length?i.primaryKeys:o.joinTable.destinationColumnNames,l=o.joinLabelColumn??"id",c=l&&!a.includes(l)?` label: ${l}`:"",m=o.joinTable.fieldName??o.joinTable.destinationTable;return a.length===1?`${o.name} ${m} { id: ${a[0]}${c} }`:`${o.name} ${m} { ${a.join(" ")}${c} }`}return o.name}).join(" ")}function yl(e,t,r,s,o,i,a,l=!1){const c=$r(e,t,i,a);if(c&&Tr(c.childJoin)){const m=c.childJoin.destinationColumnNames[0],f=`, $id: ${zt(c.parentTable)[0]?.gqlType??"Int"}`,p=`filter: { ${m}: { _eq: $id } }`,x=l?"":fo(t,r.multiJoins.filter(y=>!wl(y,c.childJoin))),h=x?`${s} ${x}`:s;return Nr(e,f,p,h)}if(c){const m=`${c.childField}(limit: $limit offset: $offset sort: $sort) { total offset limit data {${o}} }`,d=zt(c.parentTable);if(d.length===0)return null;let f,p;if(d.length===1){const x=d[0].name;f=`, $id: ${d[0].gqlType}`,p=`{ ${x}: { _eq: $id}}`}else f=`, ${d.map(y=>`$pk_${y.name}: ${y.gqlType}`).join(", ")}`,p=`{and: [${d.map(y=>`{${y.name}: {_eq: $pk_${y.name}}}`).join(", ")}]}`;return`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${f}) { ${c.parentTable.name}(filter: ${p}) { data { ${m} } } }`}return null}function vl(e,t,r){const s=zt(t);if(s.length===0)return null;let o,i;if(s.length===1){const a=uo(t),l=s[0].name;o=`, $id: ${a}`,i=`{ ${l}: { _eq: $id}}`}else o=`, ${s.map(l=>`$pk_${l.name}: ${l.gqlType}`).join(", ")}`,i=`{and: [${s.map(l=>`{${l.name}: {_eq: $pk_${l.name}}}`).join(", ")}]}`;return Nr(e,o,`filter: ${i}`,r)}function jl(e,t,r,s){let{param:o,filterText:i}=yr(t);const{params:a,filterTexts:l}=Gn(r,e);a.length>0&&(o+=a.map(m=>`, ${m}`).join(""));const c=[];return i&&c.push(i),c.push(...l),c.length>1?i=`{and: [${c.join(", ")}]}`:c.length===1?i=c[0]:i="",Nr(e,o,i?`filter: ${i}`:"",s)}function kr(e){return e.columns.filter(t=>t.isPrimaryKey||!Et(t.dbType))}function Sr(e,t,r,s,o,i,a,l){if(!e||!t?.data)return null;const c=t.findTable(e.graphQlName);if(!c)return null;const m=l?.fields==="export",d=m?kr(e).map(x=>x.name).join(" "):bl(e,t,c),f=m?"":fo(t,c.multiJoins),p=f?`${d} ${f}`:d;return o&&(a||i)?yl(e,t,c,d,p,i,a,m):o&&!i&&!a?vl(e,c,p):co(e,r,s).length>0?null:jl(e,r,s,p)}function Tr(e){return!Gt(e)&&e.isPolymorphic!==!0&&(e.destinationColumnNames?.length??0)===1}function wl(e,t){return(e.fieldName??e.destinationTable)===(t.fieldName??t.destinationTable)&&e.destinationTable===t.destinationTable&&(e.destinationColumnNames??[]).join("\0")===(t.destinationColumnNames??[]).join("\0")&&(e.sourceColumnNames??[]).join("\0")===(t.sourceColumnNames??[]).join("\0")}const Cl={data:[],total:0,offset:0,limit:0};function po(e,t,r){const i=e?.[t]?.data?.[0]?.[r];return!i||!Array.isArray(i.data)?Cl:i}function $r(e,t,r,s){const o=r??t.findTable(e.graphQlName)?.singleJoins.find(l=>l.destinationTable===s)?.destinationTable;if(!o)return null;const i=t.findTable(o);if(!i)return null;const a=Zi(i.multiJoins,e.graphQlName,s);return a?{parentTable:i,childField:el(a),childJoin:a}:null}function Nl(e){const t=e.filter(it);return t.length===0?null:`query GetTableRowCounts { ${t.map(s=>`${s}: ${s}(limit: 1) { total }`).join(" ")} }`}function kl(e=!0){const{data:t,loading:r,error:s}=Je(),o=$e(),i=u.useMemo(()=>t.map(f=>f.name),[t]),a=u.useMemo(()=>Nl(i),[i]),{data:l,isLoading:c,error:m}=de.useQuery({queryKey:["tableRowCounts",i],queryFn:()=>o.query(a),enabled:e&&!!a&&i.length>0,staleTime:300*1e3});return{stats:u.useMemo(()=>{const f={};for(const p of t){const h=l?.[p.name]?.total??null;f[p.name]={columnCount:p.columns.length,rowCount:h,fkCount:p.singleJoins.length,isLoading:c,error:m?m.message:null}}return f},[t,l,c,m]),isLoading:r||c,error:s}}function Zt({kind:e}){return n.jsx("span",{className:"text-muted-foreground/60 italic select-none",children:e==="null"?"NULL":"empty"})}const Sl="display-format",Tl="display-format-preview",$l=new Set(["date","datetime","time","relative","number","percent","raw"]);function El(e){return{param:(e.paramType??"").replace("!","").toLowerCase(),db:(e.dbType??"").toLowerCase()}}function Fl({param:e,db:t}){return e==="date"||t==="date"}function _l({param:e,db:t}){return e==="datetime"||e==="datetimeoffset"||t.includes("datetime")||t==="timestamp"||t==="smalldatetime"}function ho(e,t){const s=(t?e.metadata?.[t]:void 0)??e.metadata?.[Sl];if(typeof s=="string"&&$l.has(s.toLowerCase()))return s.toLowerCase();const o=El(e);return _l(o)?"datetime":Fl(o)?"date":null}function Pl(e){if(e instanceof Date)return isNaN(e.getTime())?null:e;if(typeof e=="number"){const t=new Date(e);return isNaN(t.getTime())?null:t}if(typeof e=="string"){const t=new Date(e);return isNaN(t.getTime())?null:t}return null}const zl=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"}),Dl=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}),Ml=new Intl.DateTimeFormat(void 0,{timeStyle:"short"}),Il=new Intl.DateTimeFormat(void 0,{dateStyle:"full",timeStyle:"medium"}),go=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Ll=[["year",31536e3],["month",2592e3],["week",604800],["day",86400],["hour",3600],["minute",60],["second",1]];function Ol(e,t=new Date){const r=Math.round((e.getTime()-t.getTime())/1e3),s=Math.abs(r);for(const[o,i]of Ll)if(s>=i||o==="second")return go.format(Math.round(r/i),o);return go.format(0,"second")}function Kn(e,t,r){if(e==null)return n.jsx(Zt,{kind:"null"});if(e==="")return n.jsx(Zt,{kind:"empty"});const s=ho(t,r?.formatKey);if(s===null||s==="raw")return String(e);if(s==="date"||s==="datetime"||s==="time"||s==="relative"){const o=Pl(e);if(!o)return String(e);const i=Il.format(o);if(s==="relative")return n.jsx("span",{title:i,className:"cursor-help underline decoration-dotted decoration-muted-foreground/40 underline-offset-2",children:Ol(o)});const a=(s==="date"?zl:s==="time"?Ml:Dl).format(o);return n.jsx("span",{title:i,children:a})}if(s==="number"||s==="percent"){const o=typeof e=="number"?e:Number(e);if(isNaN(o))return String(e);const i=s==="percent"?new Intl.NumberFormat(void 0,{style:"percent",maximumFractionDigits:2}).format(o):new Intl.NumberFormat(void 0).format(o);return n.jsx("span",{title:String(e),children:i})}return String(e)}function xo(e){if(!e)return"";const t=new Date(e);return t.toString()==="Invalid Date"||t.getTime()===0||t.getUTCFullYear()<=1?"":t.toLocaleString()}function Al(e){if(e===null)return"—";if(e===0)return"0";if(e<1e3)return e.toString();if(e<1e6){const r=e/1e3;return r%1===0?`${r.toFixed(0)}k`:`${r.toFixed(1)}k`}const t=e/1e6;return t%1===0?`${t.toFixed(0)}M`:`${t.toFixed(1)}M`}const bo="\uFEFF",ql=/["\n\r,]/;function Er(e){if(e==null)return"";const t=Vl(e);return t===""?'""':ql.test(t)?`"${t.replace(/"/g,'""')}"`:t}function Vl(e){switch(typeof e){case"string":return e;case"bigint":return e.toString();case"number":case"boolean":return String(e);case"object":return e instanceof Date?e.toISOString():JSON.stringify(e);default:return String(e)}}function yo(e,t,r={}){const s=e.map(Er).join(","),o=t.map(a=>a.map(Er).join(",")),i=[s,...o].join(`\r
89
- `);return r.bom?bo+i:i}function vo(e,t){return typeof t=="bigint"?t.toString():t}function jo(e,t){const r={};for(let s=0;s<e.length;s++)r[e[s]]=t[s];return r}function wo(e,t,r={}){if(r.mode==="lines")return t.map(o=>JSON.stringify(jo(e,o),vo)).join(`
90
- `);const s=t.map(o=>jo(e,o));return JSON.stringify(s,vo,2)}const Bl=500;function Fr(e){if(e?.aborted)throw new DOMException("Export cancelled","AbortError")}async function _r(e){const t=e.pageSize??Bl,{rowCap:r,signal:s}=e,o=[];let i=0,a=!1;Fr(s);let l=0,c=Number.POSITIVE_INFINITY;for(;l<c;){Fr(s);const d=await e.fetchPage(l,t);i=d.total,c=d.total;for(const f of d.rows){if(r!==void 0&&o.length>=r){a=!0;break}o.push(f)}if(e.onProgress?.(o.length,i),a||d.rows.length===0)break;l+=d.rows.length}return Fr(s),{content:e.format==="csv"?yo(e.headers,o,e.csv):wo(e.headers,o,e.json),rowCount:o.length,total:i,truncated:a}}const Pr=1e5;function zr(e){return e==="csv"?"text/csv;charset=utf-8;":"application/json;charset=utf-8;"}function Dr(e,t){return`${e}-export.${t}`}function Mr(e,t,r){if(typeof window>"u"||typeof document>"u")return;const s=new Blob([e],{type:r}),o=URL.createObjectURL(s),i=document.createElement("a");i.href=o,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o)}function Gl(e,t,r){if(typeof window>"u"||typeof document>"u")return;const s=Uint8Array.from(atob(e),l=>l.charCodeAt(0)),o=new Blob([s],{type:r}),i=URL.createObjectURL(o),a=document.createElement("a");a.href=i,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}function Kl(){const e=Je(),t=$e();return u.useCallback(async(r,s)=>{const o=Sr(r,e,"",[],void 0,void 0,void 0,{fields:"export"});if(!o)throw new Error(`Cannot export '${r.label??r.name}': no export query could be built.`);const i=kr(r),a=await _r({format:s,headers:i.map(l=>l.label??l.name),csv:{bom:!0},rowCap:Pr,fetchPage:async(l,c)=>{const d=(await t.query(o,{limit:c,offset:l}))?.[r.name],f=d?.data??[];return{rows:f.map(p=>i.map(x=>p[x.name])),total:d?.total??f.length}}});return Mr(a.content,Dr(r.name,s),zr(s)),a},[e,t])}const Co=u.createContext({toast:()=>{}}),Wl=4e3;function No({children:e}){const[t,r]=u.useState([]),s=u.useRef(0),o=u.useRef(new Set),i=u.useCallback(c=>{r(m=>m.filter(d=>d.id!==c))},[]),a=u.useCallback((c,m="success")=>{const d=s.current++;r(p=>[...p,{id:d,message:c,variant:m}]);const f=setTimeout(()=>{i(d),o.current.delete(f)},Wl);o.current.add(f)},[i]);u.useEffect(()=>{const c=o.current;return()=>{c.forEach(clearTimeout)}},[]);const l=u.useMemo(()=>({toast:a}),[a]);return n.jsxs(Co.Provider,{value:l,children:[e,n.jsx("div",{className:"fixed bottom-4 right-4 z-[100] flex flex-col gap-2 max-w-sm",role:"region","aria-label":"Notifications",children:t.map(c=>n.jsxs("div",{role:"status",className:Y("flex items-start gap-2 rounded-md border px-3 py-2 text-sm shadow-md bg-popover",c.variant==="error"?"border-destructive/40 text-destructive":"border-border text-foreground"),children:[c.variant==="error"?n.jsx(C.AlertCircle,{className:"size-4 shrink-0 mt-0.5"}):n.jsx(C.CheckCircle2,{className:"size-4 shrink-0 mt-0.5 text-green-600"}),n.jsx("span",{className:"flex-1 break-words",children:c.message}),n.jsx("button",{type:"button",onClick:()=>i(c.id),"aria-label":"Dismiss notification",className:"shrink-0 opacity-60 hover:opacity-100",children:n.jsx(C.X,{className:"size-3.5"})})]},c.id))})]})}function vt(){return u.useContext(Co)}const Wn=50;function Jl(e,t){return e===null||t<=0?0:Math.max(2,Math.min(100,Math.round(e/t*100)))}function Ql({percent:e,label:t}){return n.jsx("span",{className:"flex-1 min-w-[1.5em] h-[0.5em] rounded-full bg-muted/70 overflow-hidden",role:"img","aria-label":t,title:t,children:n.jsx("span",{className:"block h-full rounded-full bg-emerald-500/70 dark:bg-emerald-400/70",style:{width:`${e}%`}})})}function Ir({count:e}){return e<=0?null:n.jsxs("span",{className:"shrink-0 rounded px-1 py-px text-[0.85em] tabular-nums bg-blue-100 text-blue-700 dark:bg-blue-900/60 dark:text-blue-300",children:[e," FK"]})}function Hl(e){try{return decodeURIComponent(e)}catch{return e}}function Ul({stats:e,maxRowCount:t}){const r=Jl(e.rowCount,t),s="flex items-center gap-1.5 text-xs leading-none min-w-0";return e.isLoading?n.jsxs("div",{className:`${s} text-muted-foreground`,children:[n.jsxs("span",{className:"tabular-nums shrink-0",children:[e.columnCount,"c"]}),n.jsx("span",{className:"flex-1 min-w-[1.5em] h-[0.5em] rounded-full bg-muted/70 overflow-hidden",children:n.jsx("span",{className:"block h-full w-1/3 rounded-full bg-muted-foreground/30 animate-pulse"})}),n.jsx(C.Loader2,{className:"size-[1em] shrink-0 animate-spin"}),n.jsx(Ir,{count:e.fkCount})]}):e.error?n.jsxs("div",{className:s,children:[n.jsxs("span",{className:"tabular-nums shrink-0 text-muted-foreground",children:[e.columnCount,"c"]}),n.jsx("span",{className:"flex-1 text-destructive truncate",title:e.error,children:"err"}),n.jsx(Ir,{count:e.fkCount})]}):n.jsxs("div",{className:s,children:[n.jsxs("span",{className:"tabular-nums shrink-0 text-muted-foreground/70",children:[e.columnCount,"c"]}),n.jsx(Ql,{percent:r,label:`${e.rowCount?.toLocaleString()??"unknown"} rows`}),n.jsx("span",{className:"tabular-nums shrink-0 text-right text-muted-foreground",children:Al(e.rowCount)}),n.jsx(Ir,{count:e.fkCount})]})}function Yl({table:e,stats:t,maxRowCount:r,showStats:s,active:o,actions:i}){const a=(i??[]).filter(l=>l.enabled?.(e)??!0);return n.jsxs("div",{className:`group/tablerow flex items-stretch border-l-2 ${o?"bg-accent text-accent-foreground border-primary":"text-foreground border-transparent hover:bg-muted/50"}`,children:[n.jsx(Pn,{to:`/${e.name}`,"aria-current":o?"page":void 0,className:`plain-link flex-1 min-w-0 no-underline py-1.5 px-2 text-sm font-medium ${o?"":"hover:text-primary"}`,children:n.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[n.jsx("span",{className:"truncate",title:e.label,children:e.label}),s&&n.jsx(Ul,{stats:t,maxRowCount:r})]})}),a.length>0&&n.jsxs(Ln,{children:[n.jsx(On,{asChild:!0,children:n.jsx("button",{type:"button","aria-label":`Actions for ${e.label}`,className:"shrink-0 px-1 opacity-0 group-hover/tablerow:opacity-100 focus:opacity-100 data-[state=open]:opacity-100 text-muted-foreground hover:text-foreground",children:n.jsx(C.MoreVertical,{className:"size-3.5"})})}),n.jsx(An,{align:"start",children:a.map(l=>{const c=l.icon;return n.jsxs(bt,{onSelect:()=>{l.onSelect(e)},children:[c&&n.jsx(c,{className:"size-3.5"}),l.label]},l.id)})})]})]})}function Lr(e){const t=e.dbName.lastIndexOf(".");return t>0?e.dbName.slice(0,t):null}function ko({schema:e,count:t,collapsed:r,context:s,onToggle:o}){const i=r?C.ChevronRight:C.ChevronDown,a=n.jsxs(n.Fragment,{children:[n.jsx(i,{className:"size-3.5 shrink-0 text-muted-foreground"}),n.jsx("span",{className:"truncate font-semibold",title:e,children:e}),n.jsx("span",{className:"ml-auto shrink-0 tabular-nums text-[0.85em] text-muted-foreground",children:t})]}),l="flex items-center gap-1.5 w-full px-2 py-1 text-xs uppercase tracking-wide text-muted-foreground bg-muted/40 border-y border-border sticky top-0 z-10";return s?n.jsx("div",{className:l,"aria-hidden":"true",children:a}):n.jsx("button",{type:"button",onClick:o,"aria-expanded":!r,className:`${l} hover:bg-muted/70 text-left`,children:a})}function Rl(){const{showStats:e,tableActions:t}=cr(),{loading:r,error:s,data:o}=Je(),i=Kl(),{toast:a}=vt(),l=u.useCallback(async(E,P)=>{try{const q=await i(E,P);a(q.truncated?`${E.label} exported (truncated to ${q.rowCount.toLocaleString()} of ${q.total.toLocaleString()} rows)`:`${E.label} exported (${q.rowCount.toLocaleString()} rows)`)}catch(q){a(`Export failed: ${q.message}`,"error")}},[i,a]),c=u.useMemo(()=>[{id:"download-csv",label:"Download CSV",icon:C.Download,onSelect:E=>l(E,"csv")},{id:"download-json",label:"Download JSON",icon:C.Download,onSelect:E=>l(E,"json")},...t??[]],[l,t]),{stats:m,isLoading:d}=kl(e),[f,p]=u.useState(""),[x,h]=u.useState(new Set),[y,N]=u.useState(0),T=ps(),k=Hl(T.split("/")[1]??""),$=u.useMemo(()=>{const E=Object.values(m).map(P=>P.rowCount).filter(P=>P!==null);return E.length>0?Math.max(...E):0},[m]),b=f.trim().length>0,v=u.useMemo(()=>{const E=f.trim().toLowerCase();return E?o.filter(P=>{const q=Lr(P);return P.label.toLowerCase().includes(E)||P.dbName.toLowerCase().includes(E)||(q?.toLowerCase().includes(E)??!1)}):o},[o,f]),{schemas:w,grouped:F,multiSchema:j}=u.useMemo(()=>{const E=new Map;for(const q of v){const U=Lr(q),_=E.get(U)??[];_.push(q),E.set(U,_)}const P=[...E.keys()].filter(q=>q!==null).sort((q,U)=>q.localeCompare(U));return{schemas:P,grouped:E,multiSchema:P.length>1}},[v]),V=u.useMemo(()=>{const E=[];if(j){const P=[...w,...F.has(null)?[null]:[]];for(const q of P){const U=F.get(q===void 0?null:q)??[],_=!b&&x.has(q);if(E.push({kind:"group",schema:q??"(no schema)",count:U.length,collapsed:_}),!_)for(const ce of U)E.push({kind:"table",schema:q,table:ce})}}else for(const P of v)E.push({kind:"table",schema:Lr(P),table:P});return E},[j,w,F,v,x,b]);u.useEffect(()=>{N(0)},[f]);const S=Math.max(1,Math.ceil(V.length/Wn)),L=Math.min(y,S-1),A=L*Wn,D=V.slice(A,A+Wn),B=j&&D[0]?.kind==="table"&&D[0].schema?D[0].schema:null,X=E=>h(P=>{const q=new Set(P);return q.has(E)?q.delete(E):q.add(E),q});return r?n.jsxs("div",{className:"flex items-center justify-center gap-2 p-4",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):s?n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",s.message]})}):o.length===0?n.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[n.jsx("p",{className:"font-medium",children:"No tables found"}),n.jsx("p",{className:"mt-1",children:"The database may be empty or the connection may have failed."})]}):n.jsxs("div",{className:"@container min-w-0 flex flex-col h-full",children:[n.jsxs("div",{className:"sticky top-0 z-20 bg-background p-2 border-b border-border",children:[n.jsxs("div",{className:"relative",children:[n.jsx(C.Search,{className:"absolute left-2 top-1/2 -translate-y-1/2 size-4 text-muted-foreground pointer-events-none"}),n.jsx(Qe,{type:"search",value:f,onChange:E=>p(E.target.value),placeholder:"Search tables...","aria-label":"Search tables",className:"pl-8 pr-8 h-8 text-sm"}),b&&n.jsx("button",{type:"button",onClick:()=>p(""),"aria-label":"Clear search",className:"absolute right-1.5 top-1/2 -translate-y-1/2 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted",children:n.jsx(C.X,{className:"size-4"})})]}),b&&n.jsxs("p",{className:"mt-1 px-0.5 text-xs text-muted-foreground",children:[v.length," match",v.length!==1?"es":""]})]}),n.jsx("div",{className:"flex-1 overflow-y-auto min-h-0",children:V.length===0?n.jsxs("p",{className:"p-4 text-center text-sm text-muted-foreground",children:["No tables match “",f,"”."]}):n.jsxs(n.Fragment,{children:[B&&n.jsx(ko,{schema:B,count:F.get(B)?.length??0,collapsed:!1,context:!0}),D.map(E=>E.kind==="group"?n.jsx(ko,{schema:E.schema,count:E.count,collapsed:E.collapsed,onToggle:()=>X(E.schema)},`g:${E.schema}`):n.jsx(Yl,{table:E.table,stats:m[E.table.name]??{columnCount:E.table.columns.length,rowCount:null,fkCount:E.table.singleJoins.length,isLoading:d,error:null},maxRowCount:$,showStats:e,active:E.table.name===k,actions:c},`t:${E.table.name}`))]})}),S>1&&n.jsxs("div",{className:"sticky bottom-0 z-20 bg-background border-t border-border flex items-center justify-between gap-2 px-2 py-1.5",children:[n.jsx("button",{type:"button",onClick:()=>N(E=>Math.max(0,E-1)),disabled:L===0,"aria-label":"Previous page",className:"p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 disabled:pointer-events-none",children:n.jsx(C.ChevronLeft,{className:"size-4"})}),n.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:[A+1,"–",Math.min(A+Wn,V.length)," of ",V.length]}),n.jsx("button",{type:"button",onClick:()=>N(E=>Math.min(S-1,E+1)),disabled:L>=S-1,"aria-label":"Next page",className:"p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 disabled:pointer-events-none",children:n.jsx(C.ChevronRight,{className:"size-4"})})]})]})}const Xl=Fs("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background text-foreground hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"text-foreground hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10","icon-sm":"h-8 w-8 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),Q=Ve.forwardRef(({className:e,variant:t,size:r,asChild:s=!1,...o},i)=>{const a=s?ka.Slot:"button";return n.jsx(a,{className:Y(Xl({variant:t,size:r,className:e})),ref:i,...o})});Q.displayName="Button";const gn=Ve.forwardRef(({...e},t)=>n.jsx(R.HoverCard.Root,{"data-slot":"hover-card",...e}));gn.displayName="HoverCard";const xn=Ve.forwardRef(({...e},t)=>n.jsx(R.HoverCard.Trigger,{"data-slot":"hover-card-trigger",...e}));xn.displayName="HoverCardTrigger";const bn=Ve.forwardRef(({className:e,align:t="center",sideOffset:r=4,...s},o)=>n.jsx(R.HoverCard.Portal,{children:n.jsx(R.HoverCard.Content,{ref:o,"data-slot":"hover-card-content",align:t,sideOffset:r,className:Y("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...s})}));bn.displayName="HoverCardContent";function Ze({...e}){return n.jsx(R.Select.Root,{"data-slot":"select",...e})}function et({...e}){return n.jsx(R.Select.Value,{"data-slot":"select-value",...e})}function tt({className:e,size:t="default",children:r,...s}){return n.jsxs(R.Select.Trigger,{"data-slot":"select-trigger","data-size":t,className:Y("flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent text-foreground px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...s,children:[r,n.jsx(R.Select.Icon,{asChild:!0,children:n.jsx(C.ChevronDownIcon,{className:"size-4 opacity-50"})})]})}function nt({className:e,children:t,position:r="item-aligned",align:s="center",...o}){return n.jsx(R.Select.Portal,{children:n.jsxs(R.Select.Content,{"data-slot":"select-content",className:Y("relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:r,align:s,...o,children:[n.jsx(Zl,{}),n.jsx(R.Select.Viewport,{className:Y("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),n.jsx(ec,{})]})})}function we({className:e,children:t,...r}){return n.jsxs(R.Select.Item,{"data-slot":"select-item",className:Y("relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...r,children:[n.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:n.jsx(R.Select.ItemIndicator,{children:n.jsx(C.CheckIcon,{className:"size-4"})})}),n.jsx(R.Select.ItemText,{children:t})]})}function Zl({className:e,...t}){return n.jsx(R.Select.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:Y("flex cursor-default items-center justify-center py-1",e),...t,children:n.jsx(C.ChevronUpIcon,{className:"size-4"})})}function ec({className:e,...t}){return n.jsx(R.Select.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:Y("flex cursor-default items-center justify-center py-1",e),...t,children:n.jsx(C.ChevronDownIcon,{className:"size-4"})})}function So(e){const t=u.useRef(null),r=u.useRef(null),s=u.useRef(e);s.current=e;const o=u.useMemo(()=>{const i=()=>{t.current&&(clearTimeout(t.current),t.current=null)},a=()=>{i();const l=r.current;r.current=null,l?.()};return{schedule:l=>{i(),r.current=l,t.current=setTimeout(a,s.current)},cancel:()=>{i(),r.current=null},flush:a}},[]);return u.useEffect(()=>()=>o.flush(),[o]),o}const To={_contains:"Contains",_starts_with:"Starts with",_ends_with:"Ends with",_eq:"Equals",_neq:"Not equals",_null:"Is null"},tc=300;function nc({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(y=>y in To),s=e.getFilterValue(),[o,i]=u.useState(s?.operator??"_contains"),[a,l]=u.useState(s?.operator==="_null"?"":String(s?.value??"")),{schedule:c,cancel:m}=So(tc),d=o==="_null",f=(y,N)=>{if(y==="_null"){m(),e.setFilterValue({operator:"_null",value:!0});return}if(!N){m(),e.setFilterValue(void 0);return}c(()=>e.setFilterValue({operator:y,value:N}))},p=y=>{i(y),y==="_null"?(l(""),f("_null","")):a?f(y,a):(m(),e.setFilterValue(void 0))},x=y=>{l(y),f(o,y)},h=()=>{m(),i("_contains"),l(""),e.setFilterValue(void 0)};return r.length===0?null:n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:o,onValueChange:p,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:r.map(y=>n.jsx(we,{value:y,children:To[y]},y))})]}),!d&&n.jsx(Qe,{placeholder:"Filter value...",value:a,onChange:y=>x(y.target.value),className:"h-8 text-xs",autoFocus:!0}),s!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:h,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}const $o={_eq:"Equals",_neq:"Not equals",_gt:"Greater than",_gte:"Greater or equal",_lt:"Less than",_lte:"Less or equal",_between:"Between",_null:"Is null"},rc=300;function sc(e){return e.columnDef.meta?.paramType??""}function Or(e,t){return eo(e,t)}function oc({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(D=>D in $o),s=sc(e),o=qt(s),i=Bt(s),a=e.getFilterValue(),l=a?.operator??"_eq",[c,m]=u.useState(l),[d,f]=u.useState(()=>!a||a.operator==="_null"||a.operator==="_between"?"":String(a.value??"")),[p,x]=u.useState(()=>a?.operator==="_between"&&Array.isArray(a.value)?String(a.value[0]??""):""),[h,y]=u.useState(()=>a?.operator==="_between"&&Array.isArray(a.value)?String(a.value[1]??""):""),{schedule:N,cancel:T}=So(rc),k=(D,B)=>{if(D==="_null"){T(),e.setFilterValue({operator:"_null",value:!0});return}const X=Or(B,s);if(X===null){T(),e.setFilterValue(void 0);return}N(()=>e.setFilterValue({operator:D,value:X}))},$=(D,B)=>{const X=Or(D,s),E=Or(B,s);if(X===null||E===null){T(),e.setFilterValue(void 0);return}N(()=>e.setFilterValue({operator:"_between",value:[X,E]}))},b=D=>{m(D),D==="_null"?(f(""),x(""),y(""),k("_null","")):D==="_between"?(f(""),p&&h?$(p,h):(T(),e.setFilterValue(void 0))):(x(""),y(""),d?k(D,d):(T(),e.setFilterValue(void 0)))},v=D=>{f(D),k(c,D)},w=D=>{x(D),$(D,h)},F=D=>{y(D),$(p,D)},j=()=>{T(),m("_eq"),f(""),x(""),y(""),e.setFilterValue(void 0)};if(r.length===0)return null;const V=c==="_between",S=c==="_null",L=i?"text":"number",A=i?o?"numeric":"decimal":void 0;return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:c,onValueChange:b,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:r.map(D=>n.jsx(we,{value:D,children:$o[D]},D))})]}),!S&&!V&&n.jsx(Qe,{type:L,inputMode:A,placeholder:"Filter value...",value:d,onChange:D=>v(D.target.value),className:"h-8 text-xs",autoFocus:!0}),V&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Qe,{type:L,inputMode:A,placeholder:"Min",value:p,onChange:D=>w(D.target.value),className:"h-8 text-xs",autoFocus:!0}),n.jsx(Qe,{type:L,inputMode:A,placeholder:"Max",value:h,onChange:D=>F(D.target.value),className:"h-8 text-xs"})]}),a!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:j,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}const Eo={_eq:"On",_neq:"Not on",_gt:"After",_gte:"On or after",_lt:"Before",_lte:"On or before",_between:"Between",_null:"Is null"};function ac({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(w=>w in Eo),s=e.getFilterValue(),o=s?.operator??"_eq",[i,a]=u.useState(o),[l,c]=u.useState(()=>!s||s.operator==="_null"||s.operator==="_between"?"":String(s.value??"")),[m,d]=u.useState(()=>s?.operator==="_between"&&Array.isArray(s.value)?String(s.value[0]??""):""),[f,p]=u.useState(()=>s?.operator==="_between"&&Array.isArray(s.value)?String(s.value[1]??""):""),x=(w,F)=>{if(w==="_null"){e.setFilterValue({operator:"_null",value:!0});return}if(!F){e.setFilterValue(void 0);return}e.setFilterValue({operator:w,value:F})},h=(w,F)=>{if(!w||!F){e.setFilterValue(void 0);return}e.setFilterValue({operator:"_between",value:[w,F]})},y=w=>{a(w),w==="_null"?(c(""),d(""),p(""),e.setFilterValue({operator:"_null",value:!0})):w==="_between"?(c(""),m&&f?h(m,f):e.setFilterValue(void 0)):(d(""),p(""),l?x(w,l):e.setFilterValue(void 0))},N=w=>{c(w),x(i,w)},T=w=>{d(w),h(w,f)},k=w=>{p(w),h(m,w)},$=()=>{a("_eq"),c(""),d(""),p(""),e.setFilterValue(void 0)};if(r.length===0)return null;const b=i==="_between",v=i==="_null";return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:i,onValueChange:y,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:r.map(w=>n.jsx(we,{value:w,children:Eo[w]},w))})]}),!v&&!b&&n.jsx(Qe,{type:"date",value:l,onChange:w=>N(w.target.value),className:"h-8 text-xs"}),b&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Qe,{type:"date",value:m,onChange:w=>T(w.target.value),className:"h-8 text-xs"}),n.jsx(Qe,{type:"date",value:f,onChange:w=>k(w.target.value),className:"h-8 text-xs"})]}),s!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:$,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}const ic={all:"All",true:"True",false:"False",_null:"Is null"};function lc(e){return e?e.operator==="_null"?"_null":e.operator==="_eq"&&e.value===!0?"true":e.operator==="_eq"&&e.value===!1?"false":"all":"all"}function cc({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).includes("_null"),s=e.getFilterValue(),o=lc(s),i=r?["all","true","false","_null"]:["all","true","false"],a=c=>{switch(c){case"true":e.setFilterValue({operator:"_eq",value:!0});break;case"false":e.setFilterValue({operator:"_eq",value:!1});break;case"_null":e.setFilterValue({operator:"_null",value:!0});break;default:e.setFilterValue(void 0)}},l=()=>{e.setFilterValue(void 0)};return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:o,onValueChange:a,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:i.map(c=>n.jsx(we,{value:c,children:ic[c]},c))})]}),s!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:l,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}function uc(e,t,r,s){return!it(e)||!it(t)||!it(r)||s&&(!s.some(o=>o.name===t)||!s.some(o=>o.name===r))?null:`query Lookup${e} { ${e}(sort: [${t}_asc], limit: 100) { data { id: ${r} label: ${t} } } }`}function dc({column:e,joinTable:t,joinLabelColumn:r,joinFkColumn:s}){const o=$e(),a=Je().findTable(t),l=uc(t,r,s,a?.columns),c=mn(a?.columns.find(y=>y.name===s)),{data:m}=de.useQuery({queryKey:["fkLookup",t,r,s],queryFn:()=>o.query(l),staleTime:300*1e3,enabled:!!a&&!!l}),d=m?.[t]?.data??[],f=e.getFilterValue(),p=f?.operator==="_eq"&&f.value!=null?String(f.value):"all",x=y=>{if(y==="all"){e.setFilterValue(void 0);return}e.setFilterValue({operator:"_eq",value:dt(y,c)})},h=()=>{e.setFilterValue(void 0)};return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:p,onValueChange:x,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsxs(nt,{children:[n.jsx(we,{value:"all",children:"All"}),d.map(y=>n.jsx(we,{value:String(y.id),children:String(y.label)},String(y.id)))]})]}),f!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:h,children:[n.jsx(C.X,{className:"size-3"}),"Clear filter"]})]})}function Jn(e){return(e.columnDef.meta?.paramType??"").replace("!","")}function mc(e){return Jn(e)==="String"}function fc(e){return Vt(Jn(e))}function pc(e){return Zs(Jn(e))}function hc(e){return Jn(e)==="Boolean"}function gc(e){const t=e.columnDef.meta;return t?.joinTable?{joinTable:t.joinTable,joinLabelColumn:t.joinLabelColumn??"id",joinFkColumn:t.joinFkColumn??null,isSelfReference:t.isSelfReference===!0}:null}function xc(e){return e.columnDef.meta?.column}function Fo(e){const t=e.paramType.replace("!","");if(e.dbType){const r=e.dbType.toUpperCase();return e.maxLength&&(r.includes("VARCHAR")||r.includes("CHAR"))?`${r}(${e.maxLength})`:(r.includes("DECIMAL")||r.includes("NUMERIC"),r)}return t}function bc(e){const t=e.paramType.replace("!","");return e.isPrimaryKey?n.jsx(C.Key,{className:"size-3.5"}):Vt(t)?n.jsx(C.Hash,{className:"size-3.5"}):Zs(t)?n.jsx(C.Calendar,{className:"size-3.5"}):t==="Boolean"?n.jsx(C.ToggleLeft,{className:"size-3.5"}):n.jsx(C.Type,{className:"size-3.5"})}function yc({column:e,fkMeta:t}){const r=Fo(e),s=e.isNullable,o=e.isPrimaryKey,i=e.isIdentity,a=e.defaultValue;return n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2 border-b pb-2",children:[bc(e),n.jsx("span",{className:"font-semibold text-foreground",children:e.label})]}),n.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:[n.jsx("dt",{className:"text-muted-foreground",children:"Type"}),n.jsx("dd",{className:"text-foreground font-medium",children:r}),n.jsx("dt",{className:"text-muted-foreground",children:"Nullable"}),n.jsx("dd",{className:"text-foreground",children:s?"Yes":"No"}),o&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Primary Key"}),n.jsxs("dd",{className:"text-foreground text-primary flex items-center gap-1",children:[n.jsx(C.Key,{className:"size-3"}),"Yes"]})]}),i&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Auto Increment"}),n.jsx("dd",{className:"text-foreground",children:"Yes"})]}),t&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Foreign Key"}),n.jsxs("dd",{className:"text-foreground text-primary flex items-center gap-1",children:[n.jsx(C.Link2,{className:"size-3"}),t.joinTable,t.isSelfReference&&n.jsx("span",{className:"ml-1 px-1 rounded bg-primary/10 text-[10px] font-medium",children:"self-ref"})]})]}),a!=null&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Default"}),n.jsx("dd",{className:"text-foreground font-mono text-xs truncate max-w-[150px]",children:String(a)})]}),e.maxLength!==void 0&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Max Length"}),n.jsx("dd",{className:"text-foreground",children:e.maxLength})]}),e.min!==void 0&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Min"}),n.jsx("dd",{className:"text-foreground",children:e.min})]}),e.max!==void 0&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Max"}),n.jsx("dd",{className:"text-foreground",children:e.max})]})]})]})}function yn({column:e,table:t,title:r}){const s=t.options.meta?.onResetColumnWidths;if(!e.getCanSort())return n.jsx("span",{children:r});const o=e.getIsSorted(),i=e.getFilterValue()!==void 0,a=gc(e),l=a?.joinFkColumn??null,c=!l&&mc(e),m=!l&&fc(e),d=!l&&pc(e),f=!l&&hc(e),p=xc(e),x=n.jsxs(Q,{variant:"ghost",size:"sm",className:Y("-ml-2 h-7 text-xs data-[state=open]:bg-accent",o&&"text-foreground"),children:[n.jsx("span",{children:r}),i&&n.jsx(C.Filter,{className:"size-3 text-primary"}),o==="desc"?n.jsx(C.ArrowDown,{className:"size-4"}):o==="asc"?n.jsx(C.ArrowUp,{className:"size-4"}):n.jsx(C.ArrowUpDown,{className:"size-4"})]});return n.jsxs(gn,{openDelay:400,closeDelay:200,children:[n.jsx(xn,{asChild:!0,children:n.jsx("span",{className:"inline-flex",children:n.jsxs(Ln,{children:[n.jsx(On,{asChild:!0,children:x}),n.jsxs(An,{align:"start",children:[p&&n.jsxs(n.Fragment,{children:[n.jsxs(Wi,{className:"text-xs font-normal text-muted-foreground",children:[Fo(p),p.isNullable?" · nullable":" · required",p.isPrimaryKey?" · PK":"",a?` · FK → ${a.joinTable}`:""]}),n.jsx(yt,{})]}),n.jsxs(bt,{onClick:()=>e.toggleSorting(!1),children:[n.jsx(C.ArrowUp,{className:"size-3.5 text-muted-foreground"}),"Asc"]}),n.jsxs(bt,{onClick:()=>e.toggleSorting(!0),children:[n.jsx(C.ArrowDown,{className:"size-3.5 text-muted-foreground"}),"Desc"]}),o&&n.jsxs(bt,{onClick:()=>e.clearSorting(),children:[n.jsx(C.ArrowUpDown,{className:"size-3.5 text-muted-foreground"}),"Clear"]}),c&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(nc,{column:e})})]})]}),m&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(oc,{column:e})})]})]}),d&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(ac,{column:e})})]})]}),f&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(cc,{column:e})})]})]}),a&&l&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(C.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(dc,{column:e,joinTable:a.joinTable,joinLabelColumn:a.joinLabelColumn,joinFkColumn:l})})]})]}),e.getCanHide()&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(bt,{onClick:()=>e.toggleVisibility(!1),children:[n.jsx(C.EyeOff,{className:"size-3.5 text-muted-foreground"}),"Hide"]})]}),s&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(bt,{onClick:s,children:[n.jsx(C.RotateCcw,{className:"size-3.5 text-muted-foreground"}),"Reset column widths"]})]})]})]})})}),p&&n.jsx(bn,{align:"start",className:"w-64",children:n.jsx(yc,{column:p,fkMeta:a})})]})}const vc=5,jc=400,wc=200;function Cc(e){return e.filter(t=>!t.isPrimaryKey&&!_t(t)).slice(0,vc)}function Nc(e,t,r,s){const o=t.map(i=>i.name).join(" ");return`query FkPreview($id: ${s}) { ${e}(filter: { ${r}: { _eq: $id } } limit: 1) { data { ${o} } } }`}function kc(e,t,r,s){const o=t.map(i=>i.name).join(" ");return`query FkPreview(${r}) { ${e}(filter: ${s} limit: 1) { data { ${o} } } }`}function Sc(e,t,r,s,o,i,a){if(r.length===0)return null;if(s&&Gt(s)&&o){const d=Ri(o,s,t);if(!d)return null;const f=d.params.join(", ");return{query:kc(e,r,f,d.filterText),variables:d.variables,cacheKey:d.variables}}const l=t.columns.find(d=>d.name===a)?.paramType??"Int",c=io(l),m={id:dt(i,c)};return{query:Nc(e,r,a,c),variables:m,cacheKey:`${a}:${i}`}}function Tc({tableName:e,fkValue:t,filterColumn:r,join:s,sourceRow:o,children:i}){const[a,l]=u.useState(!1),c=Je(),m=$e(),d=c.findTable(e),f=d?Cc(d.columns):[],p=d?Sc(e,d,f,s,o,t,r):null,{data:x,isLoading:h}=de.useQuery({queryKey:["fkPreview",e,p?.cacheKey],queryFn:()=>m.query(p.query,p.variables),enabled:a&&!!p,staleTime:300*1e3}),y=x?.[e]?.data?.[0];return n.jsxs(gn,{openDelay:jc,closeDelay:wc,open:a,onOpenChange:l,children:[n.jsx(xn,{asChild:!0,children:i}),n.jsx(bn,{align:"start",className:"w-72",children:n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground",children:d?.label??e}),h&&n.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading..."}),y&&n.jsx("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:f.map(N=>n.jsxs("div",{className:"contents",children:[n.jsx("dt",{className:"text-muted-foreground truncate",children:N.label}),n.jsx("dd",{className:"text-foreground truncate",children:Kn(y[N.name],N,{formatKey:Tl})})]},N.name))}),!h&&!y&&a&&n.jsx("p",{className:"text-xs text-muted-foreground",children:"Record not found"})]})})]})}const $c={json:C.Braces,xml:C.Code,"php-serialized":C.Database,binary:C.Binary,longtext:C.FileText,text:C.FileText},Ec={json:"JSON",xml:"XML","php-serialized":"PHP",binary:"Binary",longtext:"Text",text:"Text"};function Fc(e,t){if(t==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return e}function _o({value:e,dbType:t,onExpand:r,deferred:s}){if(e===void 0&&s)return n.jsxs("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[n.jsx(C.FileText,{className:"size-3.5"}),n.jsx("span",{className:"text-xs italic",children:"content"}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(C.Expand,{className:"size-3"})})]});if(e==null)return n.jsx(Zt,{kind:"null"});const o=typeof e=="object"?JSON.stringify(e):String(e);if(o==="")return n.jsx(Zt,{kind:"empty"});const i=Bn(o,t);if(i==="text")return n.jsx("span",{children:o});if(i==="binary")return n.jsxs("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[n.jsx(C.Binary,{className:"size-3.5"}),n.jsx("span",{className:"text-xs font-mono",children:xr(o)}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(C.Expand,{className:"size-3"})})]});const a=$c[i],l=sl(o);return o.length>80||i==="json"||i==="xml"||i==="php-serialized"?n.jsxs("span",{className:"inline-flex items-center gap-1.5 max-w-full",children:[n.jsxs(gn,{openDelay:300,closeDelay:200,children:[n.jsx(xn,{asChild:!0,children:n.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 text-left hover:text-primary transition-colors min-w-0",children:[n.jsx(a,{className:"size-3 text-muted-foreground shrink-0"}),n.jsx("span",{className:"font-mono text-xs truncate",children:l})]})}),n.jsxs(bn,{side:"bottom",align:"start",className:"w-[420px] max-h-[320px] p-0",children:[n.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 border-b border-border bg-muted/30",children:[n.jsx(a,{className:"size-3.5 text-muted-foreground"}),n.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:Ec[i]}),n.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:[o.length," chars"]})]}),n.jsx("pre",{className:"p-3 text-xs font-mono overflow-auto max-h-[280px] whitespace-pre-wrap break-all",children:Fc(o,i)})]})]}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(C.Expand,{className:"size-3"})})]}):n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(a,{className:"size-3 text-muted-foreground shrink-0"}),n.jsx("span",{className:"font-mono text-xs",children:o}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(C.Expand,{className:"size-3"})})]})}const Po="gb",Ar="gs",zo=/^[_A-Za-z][_0-9A-Za-z]*$/;function Do(e,t){return!e||!t?null:t.columns.find(r=>r.name===e||r.graphQlName===e)??null}const en={field:"key",desc:!1};function _c(e,t){if(!e||!t)return null;const r=Do(e,t);return r&&/^(byte|short|int|long|float|double|decimal|numeric|money|real)/i.test(r.paramType.replace(/[!\[\]]/g,""))?r:null}function Mo(e,t,r){const s=new URLSearchParams(e);return r?s.set(t,r):s.delete(t),s}function Pc(e){const t=new URLSearchParams(e);return t.delete(Po),t.delete(Ar),t}function Io(e,t,r){const s=[];try{const o=JSON.parse(r);if(Array.isArray(o)&&o.length===4){const[i,a,l,c]=o,m=typeof i=="string"?t.columns.find(d=>d.name===i):void 0;m&&c===m.paramType&&typeof a=="string"&&pn(m.paramType).includes(a)&&s.push({[m.graphQlName]:{[a]:a==="_null"?!!l:l}})}}catch{}for(const o of e){const i=o.value,a=t.columns.find(l=>l.name===o.id);!a||!pn(a.paramType).includes(i.operator)||i.operator!=="_null"&&(i.value===void 0||i.value===null||i.value==="")||s.push({[a.graphQlName]:{[i.operator]:i.operator==="_null"?!!i.value:i.value}})}return s.length===0?void 0:s.length===1?s[0]:{and:s}}function zc(e,t,r,s,o=null,i=en){for(const m of[e.name,e.graphQlName,t.graphQlName,...o?[o.graphQlName]:[]])if(!zo.test(m))throw new Error("Invalid schema-derived grouping name.");const a=Io(r,e,s),l=a?`($filter: ${e.graphQlName}Filter)`:"",c=[a?"filter: $filter":"",`groupBy: [${t.graphQlName}]`].filter(Boolean).join(", ");return{query:`query GridGrouping${l} { ${e.name}Aggregate(${c}) { ${t.graphQlName} _count${o?` _sum { ${o.graphQlName} }`:""} } }`,variables:a?{filter:a}:{},groupBy:t,sumBy:o,sort:i}}function Lo(e,t){return e.value===t.value?0:e.value===null||e.value===void 0?-1:t.value===null||t.value===void 0?1:typeof e.value=="number"&&typeof t.value=="number"?e.value-t.value:String(e.value).localeCompare(String(t.value))}function Dc(e,t,r=en){if(r.field==="count"){const o=e.count-t.count;return o!==0?r.desc?-o:o:Lo(e,t)}const s=Lo(e,t);return r.desc?-s:s}function Mc(e,t,r,s,o=en){const i=e?.[`${t.name}Aggregate`];return Array.isArray(i)?i.map(a=>{const l=a;return{value:l[r.graphQlName],count:Number(l._count??0),sum:s?l._sum?.[s.graphQlName]:void 0}}).sort((a,l)=>Dc(a,l,o)):[]}function Ic(e,t,r,s,o,i=[]){for(const d of[e.name,e.graphQlName,t.graphQlName,...e.columns.map(f=>f.graphQlName)])if(!zo.test(d))throw new Error("Invalid schema-derived grouping name.");const a=Io(s,e,o),l={[t.graphQlName]:r==null?{_null:!0}:{_eq:r}},c=a?{and:[a,l]}:l,m=e.columns.map(d=>d.graphQlName).join(" ");return{query:`query GridGroupMembers($filter: ${e.graphQlName}Filter, $sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int) { ${e.name}(filter: $filter sort: $sort limit: $limit offset: $offset) { total offset limit data { ${m} } } }`,variables:{filter:c,sort:[...i],limit:50,offset:0},responseKey:e.name}}function Lc(e,t){return!e||!t?"":(t.primaryKeys?.length??0)<=1?$t([e?.id]):He(e,t,0)}function Oc(e,t){const r=Math.max(0,t-1);return e<0?0:e>r?r:e}function Oo(e,t){return vr(e)===t?e:jr(t)}function Ac(e,t){const r=t.fieldName??t.destinationTable;return e[r]?.data??[]}function qc(e,t){const r=t.fieldName??t.destinationTable;return e[r]}function Vc(e,t){const r=t.fieldName??t.destinationTable,s=e[r];return s?.total??s?.data?.length??0}function vn(e,t,r={}){return{sortField:e.name,paramType:e.paramType,filterOperators:t,column:e,...r}}function Bc(e,t,r,s,o,i){const a=s.findTable(t.destinationTable),l=a?.labelColumn??"id",c=Gt(t),m=t.destinationTable===r.name,d=m?`Parent ${e.label}`:e.label;return{id:e.name,accessorKey:e.name,header:({column:f,table:p})=>n.jsx(yn,{column:f,table:p,title:d}),enableSorting:!0,meta:vn(e,o,{joinTable:t.destinationTable,joinLabelColumn:l,joinFkColumn:t.destinationColumnNames[0],isSelfReference:m,isCompositeFk:c}),cell:({row:f})=>{const p=qc(f.original,t);if(!p)return n.jsx(Zt,{kind:"null"});const x=Lc(p,a);return x?n.jsxs("span",{className:"group/fk inline-flex items-center gap-0.5",children:[n.jsx(Tc,{tableName:t.destinationTable,fkValue:x,filterColumn:t.destinationColumnNames[0],join:t,sourceRow:f.original,children:n.jsx(Pn,{to:"/"+a?.name+"/"+x,className:"text-primary hover:text-primary/80 hover:underline",children:p?.label})}),i&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"opacity-0 group-hover/fk:opacity-100 size-5 shrink-0",onClick:h=>{h.stopPropagation(),i({tableName:t.destinationTable,filterId:x})},"aria-label":"Open in side column",title:"Open in side column",children:n.jsx(C.PanelRight,{className:"size-3"})})]}):n.jsx(n.Fragment,{children:p?.label})}}}function Gc(e,t,r,s,o,i){if(t){const c=s.findTable(t.destinationTable)?.labelColumn??"id",m=t.destinationTable===r.name;return{id:e.name,accessorFn:d=>e.name?String(d?.[e.name]??""):"",cell:({row:d})=>Kn(d.original[e.name],e),header:({column:d,table:f})=>n.jsx(yn,{column:d,table:f,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType,joinTable:t.destinationTable,joinLabelColumn:c,joinFkColumn:Yi(t,e.name),isSelfReference:m,isCompositeFk:!0,isCompositeFkMember:!0})}}return e?.paramType==="DateTime"?{id:e.name,accessorFn:l=>xo(l?.[e.name]),cell:({row:l})=>{const c=l.original[e.name];return c==null||c===""?n.jsx(Zt,{kind:c===""?"empty":"null"}):xo(c)},header:({column:l,table:c})=>n.jsx(yn,{column:l,table:c,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType})}:_t(e)||Ft(e)?{id:e.name,accessorFn:l=>e.name?String(l?.[e.name]??""):"",header:({column:l,table:c})=>n.jsx(yn,{column:l,table:c,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType}),cell:({row:l})=>n.jsx(_o,{value:l.original[e.name],dbType:e.dbType,deferred:_t(e),onExpand:i?()=>i(l.index,e.name):void 0})}:{id:e.name,accessorFn:l=>e.name?String(l?.[e.name]??""):"",cell:({row:l})=>{const c=l.original[e.name];if(typeof c=="string"&&c.length>1){const m=Bn(c);if(m==="json"||m==="xml"||m==="php-serialized")return n.jsx(_o,{value:c,dbType:e.dbType,onExpand:i?()=>i(l.index,e.name):void 0})}return Kn(c,e)},header:({column:l,table:c})=>n.jsx(yn,{column:l,table:c,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType})}}const Kc=(e,t,r,s)=>{if(!e||!t)return[];const o=e.columns.map(a=>{const l=e.singleJoins.find(d=>d.sourceColumnNames?.[0]===a.name),c=l?void 0:e.singleJoins.find(d=>(d.sourceColumnNames??[]).includes(a.name)),m=pn(a.paramType);return l?Bc(a,l,e,t,m,s):Gc(a,c,e,t,m,r)}),i=e.multiJoins.map(a=>{const l=t.findTable(a.destinationTable),c=l?.labelColumn??"id",d=a.destinationTable===e.name?`Child ${l?.label??a.destinationTable}`:l?.label??a.destinationTable;return{id:`join_${a.fieldName??a.destinationTable}`,header:d,enableSorting:!1,enableHiding:!0,cell:({row:f})=>{const p=dl(f.original,e,f.index),x=Ac(f.original,a),h=Vc(f.original,a);if(h===0)return n.jsx("span",{className:"text-muted-foreground",children:"—"});const y=x.slice(0,10).map(T=>String(T[c]??"")).filter(Boolean),N=l?.label??a.destinationTable;return n.jsxs("span",{className:"group/fk inline-flex items-center gap-1",children:[n.jsxs(gn,{openDelay:300,closeDelay:100,children:[n.jsx(xn,{asChild:!0,children:n.jsxs(Pn,{to:"/"+l?.name+"/from/"+e.name+"/"+p,className:"inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs font-medium text-primary hover:bg-muted hover:border-primary/40 transition-colors",children:[n.jsx(C.List,{className:"size-3"}),h]})}),n.jsxs(bn,{align:"start",sideOffset:6,className:"w-auto max-w-xs p-3",children:[n.jsxs("div",{className:"flex items-center gap-2 border-b pb-2 mb-2",children:[n.jsx(C.List,{className:"size-3.5 text-primary"}),n.jsxs("span",{className:"text-xs font-semibold text-foreground",children:[h," ",N]})]}),n.jsxs("ul",{className:"space-y-0.5 text-xs text-foreground",children:[y.map((T,k)=>n.jsx("li",{className:"truncate",children:T},k)),h>10&&n.jsxs("li",{className:"text-muted-foreground italic",children:["… and ",h-10," more"]})]})]})]}),s&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"opacity-40 group-hover/fk:opacity-100 size-5 shrink-0 transition-opacity",onClick:T=>{T.stopPropagation(),s({tableName:a.destinationTable,filterTable:e.name,filterId:p,...Gt(a)?{}:{filterColumn:a.destinationColumnNames[0]}})},"aria-label":"Open in side column",title:"Open in side column",children:n.jsx(C.PanelRight,{className:"size-3"})})]})}}});return[...o,...i]};function Wc(e,t,r,s,o){if(!s&&!o)return wr(e,t);const i=$r(t,r,s,o);return i?wr(e,i.parentTable):wr(e,t)}function Jc(e,t,r,s,o,i){const{search:a}=hs(),l=_n(),c=a.get("filter")??"",m=a.get("cf")??"",d=a.get("gb"),f=a.get("gs"),p=u.useMemo(()=>yr(c).variables,[c]),x=Je(),h=$e(),[y,N]=u.useState([]),[T,k]=u.useState(en),[$,b]=u.useState(()=>jr(m)),[v,w]=u.useState(0),[F,j]=u.useState(50),V=u.useRef(e);e&&e!==V.current&&(V.current=e,y.length>0&&N([]),T!==en&&k(en),v!==0&&w(0)),u.useEffect(()=>{b(W=>Oo(W,m))},[m]);const S=u.useMemo(()=>Oo($,m),[$,m]),L=u.useRef(e?.name),A=L.current!==e?.name;A&&(L.current=e?.name);const D=u.useMemo(()=>A?null:Do(d,e),[A,d,e]),B=u.useMemo(()=>A?null:_c(f,e),[A,f,e]);u.useEffect(()=>{if(!A||!d)return;const me=Pc(a).toString();l(me?`?${me}`:"?")},[A,d,a,l]);const X=u.useMemo(()=>{if(!e)return"id";const W=zt(e)[0]?.name;if(W&&e.columns.some(ve=>ve.name===W))return W;const me=gl(e,ve=>!_t(ve)&&!Ft(ve));return me||(e.columns.find(ve=>!_t(ve)&&!Ft(ve))?.name??e.columns.at(0)?.name??"id")},[e]),E=u.useMemo(()=>{if(y.length>0&&e){const W=y[0];if(e.columns.some(Ne=>Ne.name===W.id))return[`${W.id}_${W.desc?"desc":"asc"}`]}return e?[`${X}_asc`]:[]},[y,e,X]),P=u.useMemo(()=>Sr(e,x,c,S,t,r,s),[e,x,c,S,t,r,s]),q=u.useMemo(()=>e?Gn(S,e).variables:{},[S,e]),U=u.useMemo(()=>{if(!e)return null;const W=co(e,c,S);return W.length===0?null:new Error(`These rows can't be shown because the filter can't be applied: ${W.join(" ")}`)},[e,c,S]),_=v*F,ce=u.useMemo(()=>({sort:E,limit:F,offset:_,...t&&e?Wc(t,e,x,r,s):{},...p,...q}),[E,F,_,t,e,x,r,s,p,q]),{isLoading:he,isFetching:Ue,error:Pe,data:ie}=de.useQuery({queryKey:["tableData",e?.name,P,ce],queryFn:({signal:W})=>h.query(P,ce,{signal:W}),enabled:!!P&&!!e&&E.length>0,placeholderData:(W,me)=>me?.queryKey?.[1]===e?.name?W:void 0}),se=u.useMemo(()=>e&&D?zc(e,D,S,c,B,T):null,[e,D,B,S,c,T]),ke=de.useQuery({queryKey:["tableGrouping",e?.name,se?.query,se?.variables],queryFn:({signal:W})=>h.query(se.query,se.variables,{signal:W}),enabled:se!==null,placeholderData:void 0}),Ae=u.useMemo(()=>e?Kc(e,x,o,i):[],[e,x,o,i]),re=u.useMemo(()=>t&&(r||s)&&e?$r(e,x,r,s):null,[t,r,s,e,x]);let Ee,Ie;if(re&&!Tr(re.childJoin)){const W=po(ie,re.parentTable.name,re.childField);Ee=W.data,Ie=W.total}else{const W=ie?.[e?.name??""];Ee=W?.data??[],Ie=W?.total??0}const Le=Math.max(1,Math.ceil(Ie/F));u.useEffect(()=>{const W=Oc(v,Le);W!==v&&w(W)},[v,Le]);const Ge=u.useCallback(W=>{const me=new URLSearchParams(a),Ne=vr(W);Ne?me.set("cf",Ne):me.delete("cf");const ve=me.toString();l(ve?`?${ve}`:"?")},[a,l]),Oe=u.useCallback(W=>{N(W),w(0)},[]),ye=u.useCallback(W=>{b(W),w(0),Ge(W)},[Ge]),ze=u.useCallback(W=>{w(W)},[]),O=u.useCallback(W=>{j(W),w(0)},[]),Z=u.useCallback(W=>{const me=Mo(a,Po,W);W||me.delete(Ar);const Ne=me.toString();l(Ne?`?${Ne}`:"?")},[a,l]),ee=u.useCallback(W=>{const Ne=Mo(a,Ar,W).toString();l(Ne?`?${Ne}`:"?")},[a,l]),Ce=e?.primaryKeys??[],xe=u.useMemo(()=>e?Sr(e,x,c,S,t,r,s,{fields:"export"}):null,[e,x,c,S,t,r,s]),qe=u.useCallback(async W=>{if(!xe||!e)return null;const me=kr(e),Ne=me.map(rt=>rt.label),ve=me.map(rt=>rt.name);return _r({headers:Ne,format:W.format,signal:W.signal,onProgress:W.onProgress,rowCap:W.rowCap,csv:{bom:!0},fetchPage:async(rt,Mt)=>{const be={...ce,limit:Mt,offset:rt},ft=await h.query(xe,be,{signal:W.signal});let Nt,Ye;if(re&&!Tr(re.childJoin)){const Xe=po(ft,re.parentTable.name,re.childField);Nt=Xe.data,Ye=Xe.total}else{const Xe=ft?.[e.name];Nt=Xe?.data??[],Ye=Xe?.total??0}return{rows:Nt.map(Xe=>ve.map(Qt=>Xe[Qt])),total:Ye}}})},[xe,e,ce,h,re]);return{columns:Ae,sorting:y,columnFilters:$,primaryKeys:Ce,pageIndex:v,pageSize:F,pageCount:Le,rows:Ee,totalRows:Ie,grouping:se?{column:se.groupBy,sumColumn:se.sumBy,rows:Mc(ke.data,e,se.groupBy,se.sumBy,se.sort),loading:ke.isLoading,error:ke.error,sort:se.sort,onSortChange:k,memberRequest:W=>Ic(e,se.groupBy,W,S,c,E)}:null,exportRows:qe,loading:he,fetching:Ue&&!he,error:U??Pe,onSortingChange:Oe,onColumnFiltersChange:ye,onPageIndexChange:ze,onPageSizeChange:O,onGroupingChange:Z,onGroupingSumChange:ee}}const Qc=new Set(["tableData","editRecord","tableRowCounts","m2mRows","fkPreview"]),Hc=new Set(["tableRef","tableRefValue","compositeTableRef","m2mTargets"]);function jn(e,t){return e.invalidateQueries({predicate:r=>{const[s,o]=r.queryKey;return typeof s!="string"?!1:Qc.has(s)?!0:Hc.has(s)?o===t:!1}})}function Uc(e){return typeof e=="object"&&e!==null}function Ao(e,t){if(e==null)return null;if(!t)return e;const r=ut(t);if(Bt(t))return String(e);if(qt(t)){const s=typeof e=="number"?e:Number(e);return Number.isFinite(s)?Math.trunc(s):e}if(r==="Float"){const s=typeof e=="number"?e:Number(e);return Number.isFinite(s)?s:e}return r==="Boolean"?typeof e=="boolean"?e:e==="true"||e===1:String(e)}function Qn(e){je(e.name,"delete mutation table name");const t=$e(),r=de.useQueryClient(),{toast:s}=vt(),o=u.useMemo(()=>{const h=new Map;for(const y of e.columns)h.set(y.name,y.paramType);return h},[e]),i=u.useMemo(()=>e.primaryKeys??[],[e]),a=h=>{if(i.length===0)throw new Error(`Cannot delete from '${e.name}': the table has no primary key.`);const y={};if(Uc(h)){for(const T of i){const k=h[T];if(k==null)throw new Error(`Cannot delete row: missing value for primary-key column '${T}'.`);y[T]=Ao(k,o.get(T))}return y}if(i.length!==1)throw new Error(`Cannot delete from '${e.name}': composite primary key requires an object key, not a scalar.`);if(h==null)throw new Error(`Cannot delete row: missing value for primary-key column '${i[0]}'.`);const N=i[0];return y[N]=Ao(h,o.get(N)),y},l=u.useMemo(()=>`mutation deleteSingle($detail: Delete_${e.name}){
87
+ }`;class xs extends Error{constructor(t,r){super(t.map(s=>s.message).join("; ")),this.errors=t,this.data=r,this.name="GraphQLRequestError"}errors;data}class bs{constructor(t){this.uri=t}uri;async query(t,r,s){const o=await fetch(this.uri,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({query:t,variables:r}),signal:s?.signal});if(!o.ok)throw new Error(`GraphQL request failed: ${o.status} ${o.statusText}`);const i=await o.json();if(i.errors?.length)throw new xs(i.errors,i.data);return i.data}}const ys=u.createContext(null),vs=ys.Provider;function $e(){const e=u.useContext(ys);if(!e)throw new Error("useFetcher must be used within a FetcherProvider");return e}function Ga(e){const t=e.lastIndexOf(".");return t>=0?e.slice(t+1):e}function Ka(e){return Ga(e).replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[_\-\s]+/).filter(Boolean)}function Wa(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()}function zn(e){return e&&Ka(e).map(Wa).join(" ")}const Ja={showStats:!1},js=u.createContext(Ja);function Qa({config:e,children:t}){return n.jsx(js.Provider,{value:e,children:t})}function Dn(){return u.useContext(js)}const ws=u.createContext({loading:!0,error:null,data:[],findTable:()=>{}}),Cs=({children:e})=>{const t=Ua();return n.jsx(ws.Provider,{value:t,children:e})};function Je(){return u.useContext(ws)}function Ha(e,t){if(!t||t.length===0)return e;const r=new Set(t.map(s=>s.toLowerCase()));return e.filter(s=>r.has(s.graphQlName.toLowerCase())||r.has(s.dbName.toLowerCase()))}function Ua(){const e=$e(),{tables:t}=Dn(),{isLoading:r,error:s,data:o}=de.useQuery({queryKey:["dbSchema"],queryFn:()=>e.query(Ba),staleTime:1/0});return u.useMemo(()=>{if(r)return{loading:!0,error:null,data:[],findTable:()=>{}};if(s)return{loading:!1,error:{message:s.message},data:[],findTable:()=>{}};if(!o)return{loading:!1,error:null,data:[],findTable:()=>{}};const i=o._dbSchema.map(c=>({...c,name:c.graphQlName,label:zn(c.dbName),metadata:Ns(c.metadata),columns:c.columns.map(m=>({...m,name:m.graphQlName,label:zn(m.dbName),metadata:Ns(m.metadata),inputType:Za(m.inputType)}))})),a=Ha(i,t);return{loading:!1,error:null,data:a,findTable:c=>a.find(m=>m.graphQlName===c)}},[r,s,o,t])}function Ns(e){return e.reduce((t,r)=>({...t,[r.key]:Ya(r)}),{})}function Ya({key:e,value:t}){return e==="type"?Ra(t):t}function Ra(e){const t=e.match(/lookup\s*\(\s*(?<id>\w+)\s*,\s*(?<label>\w+)\s*\)/m);if(t?.groups?.id&&t?.groups?.label)return{type:"lookup",id:t.groups.id,label:t.groups.label}}const Xa=["text","email","url","tel","date","datetime-local","number","password","search"];function Za(e){if(e&&Xa.includes(e))return e}function ks(e){var t,r,s="";if(typeof e=="string"||typeof e=="number")s+=e;else if(typeof e=="object")if(Array.isArray(e)){var o=e.length;for(t=0;t<o;t++)e[t]&&(r=ks(e[t]))&&(s&&(s+=" "),s+=r)}else for(r in e)e[r]&&(s&&(s+=" "),s+=r);return s}function Ss(){for(var e,t,r=0,s="",o=arguments.length;r<o;r++)(e=arguments[r])&&(t=ks(e))&&(s&&(s+=" "),s+=t);return s}const Ts=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,$s=Ss,Es=(e,t)=>r=>{var s;if(t?.variants==null)return $s(e,r?.class,r?.className);const{variants:o,defaultVariants:i}=t,a=Object.keys(o).map(m=>{const d=r?.[m],p=i?.[m];if(d===null)return null;const f=Ts(d)||Ts(p);return o[m][f]}),l=r&&Object.entries(r).reduce((m,d)=>{let[p,f]=d;return f===void 0||(m[p]=f),m},{}),c=t==null||(s=t.compoundVariants)===null||s===void 0?void 0:s.reduce((m,d)=>{let{class:p,className:f,...x}=d;return Object.entries(x).every(h=>{let[b,N]=h;return Array.isArray(N)?N.includes({...i,...l}[b]):{...i,...l}[b]===N})?[...m,p,f]:m},[]);return $s(e,a,c,r?.class,r?.className)},ei=(e,t)=>{const r=new Array(e.length+t.length);for(let s=0;s<e.length;s++)r[s]=e[s];for(let s=0;s<t.length;s++)r[e.length+s]=t[s];return r},ti=(e,t)=>({classGroupId:e,validator:t}),Fs=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),Mn="-",_s=[],ni="arbitrary..",ri=e=>{const t=oi(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:s}=e;return{getClassGroupId:a=>{if(a.startsWith("[")&&a.endsWith("]"))return si(a);const l=a.split(Mn),c=l[0]===""&&l.length>1?1:0;return Ps(l,c,t)},getConflictingClassGroupIds:(a,l)=>{if(l){const c=s[a],m=r[a];return c?m?ei(m,c):c:m||_s}return r[a]||_s}}},Ps=(e,t,r)=>{if(e.length-t===0)return r.classGroupId;const o=e[t],i=r.nextPart.get(o);if(i){const m=Ps(e,t+1,i);if(m)return m}const a=r.validators;if(a===null)return;const l=t===0?e.join(Mn):e.slice(t).join(Mn),c=a.length;for(let m=0;m<c;m++){const d=a[m];if(d.validator(l))return d.classGroupId}},si=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),r=t.indexOf(":"),s=t.slice(0,r);return s?ni+s:void 0})(),oi=e=>{const{theme:t,classGroups:r}=e;return ai(r,t)},ai=(e,t)=>{const r=Fs();for(const s in e){const o=e[s];ur(o,r,s,t)}return r},ur=(e,t,r,s)=>{const o=e.length;for(let i=0;i<o;i++){const a=e[i];ii(a,t,r,s)}},ii=(e,t,r,s)=>{if(typeof e=="string"){li(e,t,r);return}if(typeof e=="function"){ci(e,t,r,s);return}ui(e,t,r,s)},li=(e,t,r)=>{const s=e===""?t:zs(t,e);s.classGroupId=r},ci=(e,t,r,s)=>{if(di(e)){ur(e(s),t,r,s);return}t.validators===null&&(t.validators=[]),t.validators.push(ti(r,e))},ui=(e,t,r,s)=>{const o=Object.entries(e),i=o.length;for(let a=0;a<i;a++){const[l,c]=o[a];ur(c,zs(t,l),r,s)}},zs=(e,t)=>{let r=e;const s=t.split(Mn),o=s.length;for(let i=0;i<o;i++){const a=s[i];let l=r.nextPart.get(a);l||(l=Fs(),r.nextPart.set(a,l)),r=l}return r},di=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,mi=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=Object.create(null),s=Object.create(null);const o=(i,a)=>{r[i]=a,t++,t>e&&(t=0,s=r,r=Object.create(null))};return{get(i){let a=r[i];if(a!==void 0)return a;if((a=s[i])!==void 0)return o(i,a),a},set(i,a){i in r?r[i]=a:o(i,a)}}},dr="!",Ds=":",fi=[],Ms=(e,t,r,s,o)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:s,isExternal:o}),pi=e=>{const{prefix:t,experimentalParseClassName:r}=e;let s=o=>{const i=[];let a=0,l=0,c=0,m;const d=o.length;for(let b=0;b<d;b++){const N=o[b];if(a===0&&l===0){if(N===Ds){i.push(o.slice(c,b)),c=b+1;continue}if(N==="/"){m=b;continue}}N==="["?a++:N==="]"?a--:N==="("?l++:N===")"&&l--}const p=i.length===0?o:o.slice(c);let f=p,x=!1;p.endsWith(dr)?(f=p.slice(0,-1),x=!0):p.startsWith(dr)&&(f=p.slice(1),x=!0);const h=m&&m>c?m-c:void 0;return Ms(i,x,f,h)};if(t){const o=t+Ds,i=s;s=a=>a.startsWith(o)?i(a.slice(o.length)):Ms(fi,!1,a,void 0,!0)}if(r){const o=s;s=i=>r({className:i,parseClassName:o})}return s},hi=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((r,s)=>{t.set(r,1e6+s)}),r=>{const s=[];let o=[];for(let i=0;i<r.length;i++){const a=r[i],l=a[0]==="[",c=t.has(a);l||c?(o.length>0&&(o.sort(),s.push(...o),o=[]),s.push(a)):o.push(a)}return o.length>0&&(o.sort(),s.push(...o)),s}},gi=e=>({cache:mi(e.cacheSize),parseClassName:pi(e),sortModifiers:hi(e),postfixLookupClassGroupIds:xi(e),...ri(e)}),xi=e=>{const t=Object.create(null),r=e.postfixLookupClassGroups;if(r)for(let s=0;s<r.length;s++)t[r[s]]=!0;return t},bi=/\s+/,yi=(e,t)=>{const{parseClassName:r,getClassGroupId:s,getConflictingClassGroupIds:o,sortModifiers:i,postfixLookupClassGroupIds:a}=t,l=[],c=e.trim().split(bi);let m="";for(let d=c.length-1;d>=0;d-=1){const p=c[d],{isExternal:f,modifiers:x,hasImportantModifier:h,baseClassName:b,maybePostfixModifierPosition:N}=r(p);if(f){m=p+(m.length>0?" "+m:m);continue}let T=!!N,k;if(T){const S=b.substring(0,N);k=s(S);const C=k&&a[k]?s(b):void 0;C&&C!==k&&(k=C,T=!1)}else k=s(b);if(!k){if(!T){m=p+(m.length>0?" "+m:m);continue}if(k=s(b),!k){m=p+(m.length>0?" "+m:m);continue}T=!1}const E=x.length===0?"":x.length===1?x[0]:i(x).join(":"),y=h?E+dr:E,v=y+k;if(l.indexOf(v)>-1)continue;l.push(v);const j=o(k,T);for(let S=0;S<j.length;++S){const C=j[S];l.push(y+C)}m=p+(m.length>0?" "+m:m)}return m},vi=(...e)=>{let t=0,r,s,o="";for(;t<e.length;)(r=e[t++])&&(s=Is(r))&&(o&&(o+=" "),o+=s);return o},Is=e=>{if(typeof e=="string")return e;let t,r="";for(let s=0;s<e.length;s++)e[s]&&(t=Is(e[s]))&&(r&&(r+=" "),r+=t);return r},ji=(e,...t)=>{let r,s,o,i;const a=c=>{const m=t.reduce((d,p)=>p(d),e());return r=gi(m),s=r.cache.get,o=r.cache.set,i=l,l(c)},l=c=>{const m=s(c);if(m)return m;const d=yi(c,r);return o(c,d),d};return i=a,(...c)=>i(vi(...c))},wi=[],_e=e=>{const t=r=>r[e]||wi;return t.isThemeGetter=!0,t},Ls=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Os=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Ci=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,Ni=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,ki=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Si=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Ti=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,$i=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,St=e=>Ci.test(e),oe=e=>!!e&&!Number.isNaN(Number(e)),ct=e=>!!e&&Number.isInteger(Number(e)),mr=e=>e.endsWith("%")&&oe(e.slice(0,-1)),xt=e=>Ni.test(e),As=()=>!0,Ei=e=>ki.test(e)&&!Si.test(e),fr=()=>!1,Fi=e=>Ti.test(e),_i=e=>$i.test(e),Pi=e=>!K(e)&&!J(e),zi=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),Di=e=>Tt(e,Ws,fr),K=e=>Ls.test(e),Ot=e=>Tt(e,Js,Ei),qs=e=>Tt(e,Bi,oe),Mi=e=>Tt(e,Hs,As),Ii=e=>Tt(e,Qs,fr),Vs=e=>Tt(e,Gs,fr),Li=e=>Tt(e,Ks,_i),In=e=>Tt(e,Us,Fi),J=e=>Os.test(e),ln=e=>At(e,Js),Oi=e=>At(e,Qs),Bs=e=>At(e,Gs),Ai=e=>At(e,Ws),qi=e=>At(e,Ks),Ln=e=>At(e,Us,!0),Vi=e=>At(e,Hs,!0),Tt=(e,t,r)=>{const s=Ls.exec(e);return s?s[1]?t(s[1]):r(s[2]):!1},At=(e,t,r=!1)=>{const s=Os.exec(e);return s?s[1]?t(s[1]):r:!1},Gs=e=>e==="position"||e==="percentage",Ks=e=>e==="image"||e==="url",Ws=e=>e==="length"||e==="size"||e==="bg-size",Js=e=>e==="length",Bi=e=>e==="number",Qs=e=>e==="family-name",Hs=e=>e==="number"||e==="weight",Us=e=>e==="shadow",Gi=ji(()=>{const e=_e("color"),t=_e("font"),r=_e("text"),s=_e("font-weight"),o=_e("tracking"),i=_e("leading"),a=_e("breakpoint"),l=_e("container"),c=_e("spacing"),m=_e("radius"),d=_e("shadow"),p=_e("inset-shadow"),f=_e("text-shadow"),x=_e("drop-shadow"),h=_e("blur"),b=_e("perspective"),N=_e("aspect"),T=_e("ease"),k=_e("animate"),E=()=>["auto","avoid","all","avoid-page","page","left","right","column"],y=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],v=()=>[...y(),J,K],j=()=>["auto","hidden","clip","visible","scroll"],S=()=>["auto","contain","none"],C=()=>[J,K,c],B=()=>[St,"full","auto",...C()],$=()=>[ct,"none","subgrid",J,K],L=()=>["auto",{span:["full",ct,J,K]},ct,J,K],q=()=>[ct,"auto",J,K],D=()=>["auto","min","max","fr",J,K],V=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],X=()=>["start","end","center","stretch","center-safe","end-safe"],F=()=>["auto",...C()],P=()=>[St,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...C()],A=()=>[St,"screen","full","dvw","lvw","svw","min","max","fit",...C()],U=()=>[St,"screen","full","lh","dvh","lvh","svh","min","max","fit",...C()],_=()=>[e,J,K],ce=()=>[...y(),Bs,Vs,{position:[J,K]}],he=()=>["no-repeat",{repeat:["","x","y","space","round"]}],Ue=()=>["auto","cover","contain",Ai,Di,{size:[J,K]}],Pe=()=>[mr,ln,Ot],ie=()=>["","none","full",m,J,K],se=()=>["",oe,ln,Ot],ke=()=>["solid","dashed","dotted","double"],Ae=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],re=()=>[oe,mr,Bs,Vs],Ee=()=>["","none",h,J,K],Ie=()=>["none",oe,J,K],Le=()=>["none",oe,J,K],Ge=()=>[oe,J,K],Oe=()=>[St,"full",...C()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[xt],breakpoint:[xt],color:[As],container:[xt],"drop-shadow":[xt],ease:["in","out","in-out"],font:[Pi],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[xt],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[xt],shadow:[xt],spacing:["px",oe],text:[xt],"text-shadow":[xt],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",St,K,J,N]}],container:["container"],"container-type":[{"@container":["","normal","size",J,K]}],"container-named":[zi],columns:[{columns:[oe,K,J,l]}],"break-after":[{"break-after":E()}],"break-before":[{"break-before":E()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:v()}],overflow:[{overflow:j()}],"overflow-x":[{"overflow-x":j()}],"overflow-y":[{"overflow-y":j()}],overscroll:[{overscroll:S()}],"overscroll-x":[{"overscroll-x":S()}],"overscroll-y":[{"overscroll-y":S()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:B()}],"inset-x":[{"inset-x":B()}],"inset-y":[{"inset-y":B()}],start:[{"inset-s":B(),start:B()}],end:[{"inset-e":B(),end:B()}],"inset-bs":[{"inset-bs":B()}],"inset-be":[{"inset-be":B()}],top:[{top:B()}],right:[{right:B()}],bottom:[{bottom:B()}],left:[{left:B()}],visibility:["visible","invisible","collapse"],z:[{z:[ct,"auto",J,K]}],basis:[{basis:[St,"full","auto",l,...C()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[oe,St,"auto","initial","none",K]}],grow:[{grow:["",oe,J,K]}],shrink:[{shrink:["",oe,J,K]}],order:[{order:[ct,"first","last","none",J,K]}],"grid-cols":[{"grid-cols":$()}],"col-start-end":[{col:L()}],"col-start":[{"col-start":q()}],"col-end":[{"col-end":q()}],"grid-rows":[{"grid-rows":$()}],"row-start-end":[{row:L()}],"row-start":[{"row-start":q()}],"row-end":[{"row-end":q()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":D()}],"auto-rows":[{"auto-rows":D()}],gap:[{gap:C()}],"gap-x":[{"gap-x":C()}],"gap-y":[{"gap-y":C()}],"justify-content":[{justify:[...V(),"normal"]}],"justify-items":[{"justify-items":[...X(),"normal"]}],"justify-self":[{"justify-self":["auto",...X()]}],"align-content":[{content:["normal",...V()]}],"align-items":[{items:[...X(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...X(),{baseline:["","last"]}]}],"place-content":[{"place-content":V()}],"place-items":[{"place-items":[...X(),"baseline"]}],"place-self":[{"place-self":["auto",...X()]}],p:[{p:C()}],px:[{px:C()}],py:[{py:C()}],ps:[{ps:C()}],pe:[{pe:C()}],pbs:[{pbs:C()}],pbe:[{pbe:C()}],pt:[{pt:C()}],pr:[{pr:C()}],pb:[{pb:C()}],pl:[{pl:C()}],m:[{m:F()}],mx:[{mx:F()}],my:[{my:F()}],ms:[{ms:F()}],me:[{me:F()}],mbs:[{mbs:F()}],mbe:[{mbe:F()}],mt:[{mt:F()}],mr:[{mr:F()}],mb:[{mb:F()}],ml:[{ml:F()}],"space-x":[{"space-x":C()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":C()}],"space-y-reverse":["space-y-reverse"],size:[{size:P()}],"inline-size":[{inline:["auto",...A()]}],"min-inline-size":[{"min-inline":["auto",...A()]}],"max-inline-size":[{"max-inline":["none",...A()]}],"block-size":[{block:["auto",...U()]}],"min-block-size":[{"min-block":["auto",...U()]}],"max-block-size":[{"max-block":["none",...U()]}],w:[{w:[l,"screen",...P()]}],"min-w":[{"min-w":[l,"screen","none",...P()]}],"max-w":[{"max-w":[l,"screen","none","prose",{screen:[a]},...P()]}],h:[{h:["screen","lh",...P()]}],"min-h":[{"min-h":["screen","lh","none",...P()]}],"max-h":[{"max-h":["screen","lh",...P()]}],"font-size":[{text:["base",r,ln,Ot]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[s,Vi,Mi]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",mr,K]}],"font-family":[{font:[Oi,Ii,t]}],"font-features":[{"font-features":[K]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[o,J,K]}],"line-clamp":[{"line-clamp":[oe,"none",J,qs]}],leading:[{leading:[i,...C()]}],"list-image":[{"list-image":["none",J,K]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",J,K]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:_()}],"text-color":[{text:_()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ke(),"wavy"]}],"text-decoration-thickness":[{decoration:[oe,"from-font","auto",J,Ot]}],"text-decoration-color":[{decoration:_()}],"underline-offset":[{"underline-offset":[oe,"auto",J,K]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:C()}],"tab-size":[{tab:[ct,J,K]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",J,K]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",J,K]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:ce()}],"bg-repeat":[{bg:he()}],"bg-size":[{bg:Ue()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ct,J,K],radial:["",J,K],conic:[ct,J,K]},qi,Li]}],"bg-color":[{bg:_()}],"gradient-from-pos":[{from:Pe()}],"gradient-via-pos":[{via:Pe()}],"gradient-to-pos":[{to:Pe()}],"gradient-from":[{from:_()}],"gradient-via":[{via:_()}],"gradient-to":[{to:_()}],rounded:[{rounded:ie()}],"rounded-s":[{"rounded-s":ie()}],"rounded-e":[{"rounded-e":ie()}],"rounded-t":[{"rounded-t":ie()}],"rounded-r":[{"rounded-r":ie()}],"rounded-b":[{"rounded-b":ie()}],"rounded-l":[{"rounded-l":ie()}],"rounded-ss":[{"rounded-ss":ie()}],"rounded-se":[{"rounded-se":ie()}],"rounded-ee":[{"rounded-ee":ie()}],"rounded-es":[{"rounded-es":ie()}],"rounded-tl":[{"rounded-tl":ie()}],"rounded-tr":[{"rounded-tr":ie()}],"rounded-br":[{"rounded-br":ie()}],"rounded-bl":[{"rounded-bl":ie()}],"border-w":[{border:se()}],"border-w-x":[{"border-x":se()}],"border-w-y":[{"border-y":se()}],"border-w-s":[{"border-s":se()}],"border-w-e":[{"border-e":se()}],"border-w-bs":[{"border-bs":se()}],"border-w-be":[{"border-be":se()}],"border-w-t":[{"border-t":se()}],"border-w-r":[{"border-r":se()}],"border-w-b":[{"border-b":se()}],"border-w-l":[{"border-l":se()}],"divide-x":[{"divide-x":se()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":se()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ke(),"hidden","none"]}],"divide-style":[{divide:[...ke(),"hidden","none"]}],"border-color":[{border:_()}],"border-color-x":[{"border-x":_()}],"border-color-y":[{"border-y":_()}],"border-color-s":[{"border-s":_()}],"border-color-e":[{"border-e":_()}],"border-color-bs":[{"border-bs":_()}],"border-color-be":[{"border-be":_()}],"border-color-t":[{"border-t":_()}],"border-color-r":[{"border-r":_()}],"border-color-b":[{"border-b":_()}],"border-color-l":[{"border-l":_()}],"divide-color":[{divide:_()}],"outline-style":[{outline:[...ke(),"none","hidden"]}],"outline-offset":[{"outline-offset":[oe,J,K]}],"outline-w":[{outline:["",oe,ln,Ot]}],"outline-color":[{outline:_()}],shadow:[{shadow:["","none",d,Ln,In]}],"shadow-color":[{shadow:_()}],"inset-shadow":[{"inset-shadow":["none",p,Ln,In]}],"inset-shadow-color":[{"inset-shadow":_()}],"ring-w":[{ring:se()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:_()}],"ring-offset-w":[{"ring-offset":[oe,Ot]}],"ring-offset-color":[{"ring-offset":_()}],"inset-ring-w":[{"inset-ring":se()}],"inset-ring-color":[{"inset-ring":_()}],"text-shadow":[{"text-shadow":["none",f,Ln,In]}],"text-shadow-color":[{"text-shadow":_()}],opacity:[{opacity:[oe,J,K]}],"mix-blend":[{"mix-blend":[...Ae(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":Ae()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[oe]}],"mask-image-linear-from-pos":[{"mask-linear-from":re()}],"mask-image-linear-to-pos":[{"mask-linear-to":re()}],"mask-image-linear-from-color":[{"mask-linear-from":_()}],"mask-image-linear-to-color":[{"mask-linear-to":_()}],"mask-image-t-from-pos":[{"mask-t-from":re()}],"mask-image-t-to-pos":[{"mask-t-to":re()}],"mask-image-t-from-color":[{"mask-t-from":_()}],"mask-image-t-to-color":[{"mask-t-to":_()}],"mask-image-r-from-pos":[{"mask-r-from":re()}],"mask-image-r-to-pos":[{"mask-r-to":re()}],"mask-image-r-from-color":[{"mask-r-from":_()}],"mask-image-r-to-color":[{"mask-r-to":_()}],"mask-image-b-from-pos":[{"mask-b-from":re()}],"mask-image-b-to-pos":[{"mask-b-to":re()}],"mask-image-b-from-color":[{"mask-b-from":_()}],"mask-image-b-to-color":[{"mask-b-to":_()}],"mask-image-l-from-pos":[{"mask-l-from":re()}],"mask-image-l-to-pos":[{"mask-l-to":re()}],"mask-image-l-from-color":[{"mask-l-from":_()}],"mask-image-l-to-color":[{"mask-l-to":_()}],"mask-image-x-from-pos":[{"mask-x-from":re()}],"mask-image-x-to-pos":[{"mask-x-to":re()}],"mask-image-x-from-color":[{"mask-x-from":_()}],"mask-image-x-to-color":[{"mask-x-to":_()}],"mask-image-y-from-pos":[{"mask-y-from":re()}],"mask-image-y-to-pos":[{"mask-y-to":re()}],"mask-image-y-from-color":[{"mask-y-from":_()}],"mask-image-y-to-color":[{"mask-y-to":_()}],"mask-image-radial":[{"mask-radial":[J,K]}],"mask-image-radial-from-pos":[{"mask-radial-from":re()}],"mask-image-radial-to-pos":[{"mask-radial-to":re()}],"mask-image-radial-from-color":[{"mask-radial-from":_()}],"mask-image-radial-to-color":[{"mask-radial-to":_()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":y()}],"mask-image-conic-pos":[{"mask-conic":[oe]}],"mask-image-conic-from-pos":[{"mask-conic-from":re()}],"mask-image-conic-to-pos":[{"mask-conic-to":re()}],"mask-image-conic-from-color":[{"mask-conic-from":_()}],"mask-image-conic-to-color":[{"mask-conic-to":_()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:ce()}],"mask-repeat":[{mask:he()}],"mask-size":[{mask:Ue()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",J,K]}],filter:[{filter:["","none",J,K]}],blur:[{blur:Ee()}],brightness:[{brightness:[oe,J,K]}],contrast:[{contrast:[oe,J,K]}],"drop-shadow":[{"drop-shadow":["","none",x,Ln,In]}],"drop-shadow-color":[{"drop-shadow":_()}],grayscale:[{grayscale:["",oe,J,K]}],"hue-rotate":[{"hue-rotate":[oe,J,K]}],invert:[{invert:["",oe,J,K]}],saturate:[{saturate:[oe,J,K]}],sepia:[{sepia:["",oe,J,K]}],"backdrop-filter":[{"backdrop-filter":["","none",J,K]}],"backdrop-blur":[{"backdrop-blur":Ee()}],"backdrop-brightness":[{"backdrop-brightness":[oe,J,K]}],"backdrop-contrast":[{"backdrop-contrast":[oe,J,K]}],"backdrop-grayscale":[{"backdrop-grayscale":["",oe,J,K]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[oe,J,K]}],"backdrop-invert":[{"backdrop-invert":["",oe,J,K]}],"backdrop-opacity":[{"backdrop-opacity":[oe,J,K]}],"backdrop-saturate":[{"backdrop-saturate":[oe,J,K]}],"backdrop-sepia":[{"backdrop-sepia":["",oe,J,K]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":C()}],"border-spacing-x":[{"border-spacing-x":C()}],"border-spacing-y":[{"border-spacing-y":C()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",J,K]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[oe,"initial",J,K]}],ease:[{ease:["linear","initial",T,J,K]}],delay:[{delay:[oe,J,K]}],animate:[{animate:["none",k,J,K]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[b,J,K]}],"perspective-origin":[{"perspective-origin":v()}],rotate:[{rotate:Ie()}],"rotate-x":[{"rotate-x":Ie()}],"rotate-y":[{"rotate-y":Ie()}],"rotate-z":[{"rotate-z":Ie()}],scale:[{scale:Le()}],"scale-x":[{"scale-x":Le()}],"scale-y":[{"scale-y":Le()}],"scale-z":[{"scale-z":Le()}],"scale-3d":["scale-3d"],skew:[{skew:Ge()}],"skew-x":[{"skew-x":Ge()}],"skew-y":[{"skew-y":Ge()}],transform:[{transform:[J,K,"","none","gpu","cpu"]}],"transform-origin":[{origin:v()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Oe()}],"translate-x":[{"translate-x":Oe()}],"translate-y":[{"translate-y":Oe()}],"translate-z":[{"translate-z":Oe()}],"translate-none":["translate-none"],zoom:[{zoom:[ct,J,K]}],accent:[{accent:_()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:_()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",J,K]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":_()}],"scrollbar-track-color":[{"scrollbar-track":_()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mbs":[{"scroll-mbs":C()}],"scroll-mbe":[{"scroll-mbe":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pbs":[{"scroll-pbs":C()}],"scroll-pbe":[{"scroll-pbe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",J,K]}],fill:[{fill:["none",..._()]}],"stroke-w":[{stroke:[oe,ln,Ot,qs]}],stroke:[{stroke:["none",..._()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});function Y(...e){return Gi(Ss(e))}const Ki=Es("relative grid w-full grid-cols-[0_1fr] items-start gap-y-0.5 rounded-lg border px-4 py-3 text-sm has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] has-[>svg]:gap-x-3 [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 [&>svg]:text-current"}},defaultVariants:{variant:"default"}});function Rt({className:e,variant:t,...r}){return n.jsx("div",{"data-slot":"alert",role:"alert",className:Y(Ki({variant:t}),e),...r})}function Ys({className:e,...t}){return n.jsx("div",{"data-slot":"alert-title",className:Y("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",e),...t})}function Xt({className:e,...t}){return n.jsx("div",{"data-slot":"alert-description",className:Y("col-start-2 grid justify-items-start gap-1 text-sm text-muted-foreground [&_p]:leading-relaxed",e),...t})}const Qe=Ve.forwardRef(({className:e,type:t,...r},s)=>n.jsx("input",{type:t,ref:s,"data-slot":"input",className:Y("h-9 w-full min-w-0 rounded-md border border-input bg-transparent text-foreground px-3 py-0 text-sm shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 dark:bg-input/30","focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40",e),...r}));Qe.displayName="Input";function On({...e}){return n.jsx(R.DropdownMenu.Root,{"data-slot":"dropdown-menu",...e})}function An({...e}){return n.jsx(R.DropdownMenu.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}function qn({className:e,sideOffset:t=4,...r}){return n.jsx(R.DropdownMenu.Portal,{children:n.jsx(R.DropdownMenu.Content,{"data-slot":"dropdown-menu-content",sideOffset:t,className:Y("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...r})})}function bt({className:e,inset:t,variant:r="default",...s}){return n.jsx(R.DropdownMenu.Item,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":r,className:Y("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...s})}function Wi({className:e,children:t,checked:r,...s}){return n.jsxs(R.DropdownMenu.CheckboxItem,{"data-slot":"dropdown-menu-checkbox-item",className:Y("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),checked:r,...s,children:[n.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:n.jsx(R.DropdownMenu.ItemIndicator,{children:n.jsx(w.CheckIcon,{className:"size-4"})})}),t]})}function Ji({className:e,inset:t,...r}){return n.jsx(R.DropdownMenu.Label,{"data-slot":"dropdown-menu-label","data-inset":t,className:Y("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...r})}function yt({className:e,...t}){return n.jsx(R.DropdownMenu.Separator,{"data-slot":"dropdown-menu-separator",className:Y("-mx-1 my-1 h-px bg-border",e),...t})}function cn({...e}){return n.jsx(R.DropdownMenu.Sub,{"data-slot":"dropdown-menu-sub",...e})}function un({className:e,inset:t,children:r,...s}){return n.jsxs(R.DropdownMenu.SubTrigger,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:Y("flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...s,children:[r,n.jsx(w.ChevronRightIcon,{className:"ml-auto size-4"})]})}function dn({className:e,...t}){return n.jsx(R.DropdownMenu.SubContent,{"data-slot":"dropdown-menu-sub-content",className:Y("z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),...t})}function ut(e){return(e??"").replace("!","")}const Rs=new Set(["Int","Short","Byte","BigInt"]),Qi=new Set(["Float","Decimal"]),Hi=new Set(["DateTime","DateTimeOffset"]),Ui=new Set(["BigInt","Decimal"]);function qt(e){return Rs.has(ut(e))}function Vt(e){const t=ut(e);return Rs.has(t)||Qi.has(t)}function Bt(e){return Ui.has(ut(e))}function Xs(e){return Hi.has(ut(e))}function Yi(e){return ut(e)==="String"}function Zs(e,t){const r=e.trim();if(r===""||r==="-"||r==="+"||!(qt(t)?/^[+-]?\d+$/.test(r):/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?$/.test(r)))return null;if(Bt(t))return r;const o=Number(r);return Number.isFinite(o)?o:null}function dt(e,t){if(e==null)return null;if(Bt(t))return String(e);if(qt(t)){const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.trunc(r):e}switch(ut(t)){case"Float":{const r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?r:e}case"Boolean":return typeof e=="boolean"?e:e==="true"||e===1?!0:e==="false"||e===0?!1:!!e;default:return String(e)}}function mn(e){return e?.paramType?.replace("!","")??"String"}function Gt(e){return(e.sourceColumnNames?.length??0)>1}function Ri(e,t){const r=(e.sourceColumnNames??[]).indexOf(t);return r<0?null:(e.destinationColumnNames??[])[r]??null}function Xi(e,t,r,s="fk"){if(!e)return null;const o=t.sourceColumnNames??[],i=t.destinationColumnNames??[];if(o.length===0||o.length!==i.length)return null;const a=new Map((r?.columns??[]).map(p=>[p.name,p])),l=[],c={},m=[];for(let p=0;p<o.length;p++){const f=o[p],x=i[p];if(!(f in e))return null;const h=mn(a.get(x)),b=`${s}_${x}`;c[b]=dt(e[f],h),m.push(`$${b}: ${h}`),l.push(`{${x}: {_eq: $${b}}}`)}return{filterText:l.length===1?l[0]:`{and: [${l.join(", ")}]}`,variables:c,params:m}}const pr="::";function Zi(e){return e==null?"":encodeURIComponent(String(e))}function hr(e){if(e==="")return null;try{return decodeURIComponent(e)}catch{return e}}function $t(e){return e.map(Zi).join(pr)}function eo(e,t){const r=t<=1?[e]:e.split(pr);if(r.length!==t)throw new Error(`Route id '${e}' has ${r.length} part(s) but ${t} were expected.`);return r.map(s=>s===""?"":hr(s)??"")}function He(e,t,r){const s=t.primaryKeys??[];return s.length===0?`row-${r}`:$t(s.map(o=>e?.[o]))}function mt(e,t){const r=t.primaryKeys??[];if(r.length===0||e==null)return null;const s={};for(const o of r){if(!(o in e))return null;s[o]=e[o]}return s}function Vn(e,t){const r=mt(e,t);if(!r)return null;const s=new Map((t.columns??[]).map(c=>[c.name,c])),o=[],i={},a=[];for(const c of t.primaryKeys??[]){const m=mn(s.get(c)),d=`pk_${c}`;i[d]=dt(r[c],m),a.push(`$${d}: ${m}`),o.push(`{${c}: {_eq: $${d}}}`)}return{filterText:o.length===1?o[0]:`{and: [${o.join(", ")}]}`,variables:i,params:a}}function Bn(e,t){const r=t.primaryKeys??[];return r.length===0?"":$t(r.map(s=>e[s]))}function fn(e,t){const r=t.primaryKeys??[];if(r.length===0)return null;const s=r.length===1?[e]:e.split(pr);if(s.length!==r.length)return null;const o={};for(let i=0;i<r.length;i++){const a=hr(s[i]);if(a===null)return null;o[r[i]]=a}return o}function el(e,t,r){if(!e)return;const s=e.filter(o=>o.destinationTable===t);if(s.length!==0){if(s.length===1)return s[0];if(r)return s.find(o=>o.destinationColumnNames?.[0]===r)}}function tl(e){return e.fieldName??e.destinationTable}const nl=new Set(["binary","varbinary","image","blob","tinyblob","mediumblob","longblob","bytea"]),rl=new Set(["text","ntext","xml"]),sl=new Set(["json","jsonb"]);function Et(e){return nl.has(e.toLowerCase().replace(/\(.*\)/,""))}function to(e){return sl.has(e.toLowerCase().replace(/\(.*\)/,""))}function Ft(e){return to(e.dbType)||e.paramType==="JSON"}function gr(e){const t=e.toLowerCase(),r=t.replace(/\(.*\)/,"");return!!(rl.has(r)||t.includes("(max)"))}function _t(e){return typeof e.isLargeValue=="boolean"?e.isLargeValue:Et(e.dbType)||gr(e.dbType)}function Gn(e,t){if(!e)return"text";if(t&&Et(t))return"binary";if(t&&to(t))return"json";const r=e.trimStart();if(r.startsWith("{")&&r.endsWith("}")||r.startsWith("[")&&r.endsWith("]"))try{return JSON.parse(r),"json"}catch{}return r.startsWith("<?xml")||r.startsWith("<")&&r.includes("</")&&r.endsWith(">")?"xml":/^[aOsidb]:\d+[:{;]/.test(r)?"php-serialized":e.length>200||e.includes(`
88
+ `)?"longtext":"text"}const no=80;function ol(e){return e.length<=no?e:e.slice(0,no)+"..."}function xr(e){const t=Math.ceil(e.length*3/4);return t<1024?`${t} bytes`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function ro(e){const t={kind:"unknown",mime:"application/octet-stream",extension:".bin"};let r;try{r=atob(e.slice(0,24))}catch{return t}const s=o=>r.charCodeAt(o);return r.length>=4&&s(0)===137&&r.slice(1,4)==="PNG"?{kind:"image",mime:"image/png",extension:".png"}:r.length>=3&&s(0)===255&&s(1)===216&&s(2)===255?{kind:"image",mime:"image/jpeg",extension:".jpg"}:r.slice(0,4)==="GIF8"?{kind:"image",mime:"image/gif",extension:".gif"}:r.slice(0,4)==="RIFF"&&r.slice(8,12)==="WEBP"?{kind:"image",mime:"image/webp",extension:".webp"}:r.slice(0,4)==="%PDF"?{kind:"pdf",mime:"application/pdf",extension:".pdf"}:t}function so(e,t){return`data:${t};base64,${e}`}const Pt=["_eq","_neq","_gt","_gte","_lt","_lte","_between","_null"],br={String:["_eq","_neq","_contains","_starts_with","_ends_with","_null"],Int:Pt,Float:Pt,Short:Pt,Byte:Pt,BigInt:Pt,Decimal:Pt,Boolean:["_eq","_null"],DateTime:Pt,DateTimeOffset:Pt},al=new Set(["DateTime","DateTimeOffset"]),il=/^[_A-Za-z][_0-9A-Za-z]*$/,ll=/^[_A-Za-z][_0-9A-Za-z]*!?$/,cl=new Set(Object.values(br).flat());function it(e){return typeof e=="string"&&il.test(e)}function je(e,t){if(!it(e))throw new Error(`Invalid GraphQL ${t}: ${String(e)}`)}function ul(e){return typeof e=="string"&&ll.test(e)}function oo(e,t){return typeof e=="string"&&pn(t).includes(e)}function pn(e){const t=e.replace("!","");return br[t]??br.String}function dl(){return{variables:{},param:"",filterText:"",error:null}}function hn(e){return{variables:{},param:"",filterText:"",error:e}}function yr(e){if(!e)return dl();let t;try{t=JSON.parse(e)}catch{return hn("The filter in the URL is not valid JSON.")}if(!Array.isArray(t)||t.length<4)return hn("The filter in the URL is malformed.");const[r,s,o,i]=t;return it(r)?ul(i)?oo(s,i)?{variables:{filter:o},param:`, $filter: ${i}`,filterText:`{${r}: {${s}: $filter} }`,error:null}:hn(`Filter operator '${String(s)}' is not supported for ${String(i)} column '${String(r)}'.`):hn(`Filter type '${String(i)}' is not a valid type name.`):hn(`Filter column '${String(r)}' is not a valid column name.`)}function ml(e,t,r=0){return He(e,t,r)}function ao(e){const t=e.replace("!","");switch(t){case"Int":case"Float":case"Short":case"Byte":case"Boolean":case"BigInt":case"Decimal":case"DateTime":case"DateTimeOffset":return t;default:return"String"}}const fl=/^\d{4}-\d{2}-\d{2}$/;function pl(e){const t=e<=0?"+":"-",r=Math.abs(e),s=String(Math.floor(r/60)).padStart(2,"0"),o=String(r%60).padStart(2,"0");return`${t}${s}:${o}`}function io(e,t,r,s){const i=`${e}T${t==="start"?"00:00:00.000":"23:59:59.999"}`;if(r!=="DateTimeOffset")return i;const a=new Date(`${e}T00:00:00`).getTimezoneOffset();return`${i}${pl(a)}`}function hl(e,t,r,s){if(!al.has(r))return{operator:e,value:t};const o=l=>io(String(l),"start",r),i=l=>io(String(l),"end",r),a=l=>typeof l=="string"&&fl.test(l);if(e==="_between"){const l=Array.isArray(t)?t:null;return!l||l.length!==2?{operator:e,value:t}:{operator:e,value:[a(l[0])?o(l[0]):l[0],a(l[1])?i(l[1]):l[1]]}}if(!a(t))return{operator:e,value:t};switch(e){case"_eq":return{operator:"_between",value:[o(t),i(t)]};case"_neq":return{operator:"_nbetween",value:[o(t),i(t)]};case"_gt":case"_lte":return{operator:e,value:i(t)};default:return{operator:e,value:o(t)}}}function Kn(e,t){const r={},s=[],o=[],i=[];for(let a=0;a<e.length;a++){const l=e[a],c=l.value;if(c.value===void 0||c.value===null||c.value==="")continue;const m=t.columns.find(x=>x.name===l.id);if(!m){i.push(`Column '${String(l.id)}' is not on this table.`);continue}if(!it(l.id)){i.push(`Column '${String(l.id)}' is not a valid column name.`);continue}if(!oo(c.operator,m.paramType)){i.push(`Operator '${String(c.operator)}' is not supported for column '${l.id}'.`);continue}const d=`cf_${l.id}_${a}`,p=ao(m.paramType);if(c.operator==="_null"){o.push(`{${l.id}: {_null: ${c.value?"true":"false"}}}`);continue}const f=hl(c.operator,c.value,p);if(f.operator==="_between"||f.operator==="_nbetween"){const x=f.value;if(!Array.isArray(x)||x.length!==2){i.push(`The range filter on column '${l.id}' needs exactly two bounds.`);continue}const h=`${d}_lo`,b=`${d}_hi`;r[h]=x[0],r[b]=x[1],s.push(`$${h}: ${p}`,`$${b}: ${p}`),o.push(`{${l.id}: {${f.operator}: [$${h}, $${b}]}}`);continue}r[d]=f.value,s.push(`$${d}: ${p}`),o.push(`{${l.id}: {${f.operator}: $${d}}}`)}return{variables:r,params:s,filterTexts:o,errors:i}}function lo(e,t,r){const s=yr(t),o=Kn(r,e);return s.error?[s.error,...o.errors]:o.errors}function vr(e){return e.length===0?"":JSON.stringify(e.map(t=>[t.id,t.value.operator,t.value.value]))}function jr(e){try{if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(gl).map(([r,s,o])=>({id:r,value:{operator:s,value:o}})):[]}catch{return[]}}function gl(e){if(!Array.isArray(e)||e.length!==3)return!1;const[t,r]=e;return it(t)&&typeof r=="string"&&cl.has(r)}function co(e){return zt(e)[0]?.gqlType??"Int"}function zt(e){const t=e.primaryKeys??[];if(t.length===0)return[];const r=new Map(e.columns.map(s=>[s.name,s]));return t.map(s=>({name:s,gqlType:r.get(s)?.paramType?.replace("!","")??"String"}))}function xl(e,t=()=>!0){const r=e.indexes??[];if(r.length===0)return null;const s=new Map(e.columns.map(i=>[i.name,i])),o=i=>{const a=i.columns[0],l=a?s.get(a):void 0;return l&&t(l)?l.name:null};for(const i of[a=>a.isClustered,a=>a.isUnique,()=>!0])for(const a of r){if(!i(a))continue;const l=o(a);if(l)return l}return null}function wr(e,t){if(zt(t).length<=1)return{id:dt(hr(e),co(t))};const s=fn(e,t);return s?Vn(s,t)?.variables??{}:{}}function Cr(e,t,r){je(e.name,"single-row table name");for(const o of r)je(o,"single-row selection field");const s=t.params.length>0?`(${t.params.join(", ")})`:"";return`query GetSingleRow_${e.name}${s} { value: ${e.name}(filter: ${t.filterText}) { data { ${r.join(" ")} } } }`}function uo(e,t,r){je(e.name,"rows-by-pk table name");for(const d of r)je(d,"rows-by-pk selection field");const s=e.primaryKeys??[];if(s.length===0||t.length===0||r.length===0)return null;for(const d of s)je(d,"rows-by-pk key column");const o=new Map((e.columns??[]).map(d=>[d.name,d])),i=[],a={},l=[];t.forEach((d,p)=>{const f=[];for(const x of s){const h=mn(o.get(x)),b=`pk${p}_${x}`;a[b]=dt(d[x],h),i.push(`$${b}: ${h}`),f.push(`{${x}: {_eq: $${b}}}`)}l.push(f.length===1?f[0]:`{and: [${f.join(", ")}]}`)});const c=l.length===1?l[0]:`{or: [${l.join(", ")}]}`;return{query:`query GetRowsByPk_${e.name}(${i.join(", ")}) { value: ${e.name}(filter: ${c} limit: ${t.length}) { data { ${r.join(" ")} } } }`,variables:a}}const bl=11;function mo(e,t){return t.map(r=>{const s=e.findTable(r.destinationTable),o=s?.labelColumn??"id",a=[...s?.primaryKeys?.length?s.primaryKeys:["id"]];return o&&!a.includes(o)&&a.push(o),`${r.fieldName??r.destinationTable}(limit: ${bl}) { total data { ${a.join(" ")} } }`}).join(" ")}function Nr(e,t,r,s){return`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${t}) { ${e.name}(sort: $sort limit: $limit offset: $offset ${r}) { total offset limit data {${s}}}}`}function yl(e,t,r){const s=new Set;return e.columns.filter(o=>o?.joinTable===void 0).filter(o=>o.isPrimaryKey||!_t(o)).map(o=>{const i=r.singleJoins.find(c=>c.sourceColumnNames?.[0]===o.name);if(!i)return o;const l=t.findTable(i.destinationTable)?.labelColumn??"id";return{...o,joinTable:i,joinLabelColumn:l}}).map(o=>{if(o?.joinTable){s.add(o.name);const i=t.findTable(o.joinTable.destinationTable),a=i?.primaryKeys?.length?i.primaryKeys:o.joinTable.destinationColumnNames,l=o.joinLabelColumn??"id",c=l&&!a.includes(l)?` label: ${l}`:"",m=o.joinTable.fieldName??o.joinTable.destinationTable;return a.length===1?`${o.name} ${m} { id: ${a[0]}${c} }`:`${o.name} ${m} { ${a.join(" ")}${c} }`}return o.name}).join(" ")}function vl(e,t,r,s,o,i,a,l=!1){const c=$r(e,t,i,a);if(c&&Tr(c.childJoin)){const m=c.childJoin.destinationColumnNames[0],p=`, $id: ${zt(c.parentTable)[0]?.gqlType??"Int"}`,f=`filter: { ${m}: { _eq: $id } }`,x=l?"":mo(t,r.multiJoins.filter(b=>!Cl(b,c.childJoin))),h=x?`${s} ${x}`:s;return Nr(e,p,f,h)}if(c){const m=`${c.childField}(limit: $limit offset: $offset sort: $sort) { total offset limit data {${o}} }`,d=zt(c.parentTable);if(d.length===0)return null;let p,f;if(d.length===1){const x=d[0].name;p=`, $id: ${d[0].gqlType}`,f=`{ ${x}: { _eq: $id}}`}else p=`, ${d.map(b=>`$pk_${b.name}: ${b.gqlType}`).join(", ")}`,f=`{and: [${d.map(b=>`{${b.name}: {_eq: $pk_${b.name}}}`).join(", ")}]}`;return`query Get${e.name}($sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int ${p}) { ${c.parentTable.name}(filter: ${f}) { data { ${m} } } }`}return null}function jl(e,t,r){const s=zt(t);if(s.length===0)return null;let o,i;if(s.length===1){const a=co(t),l=s[0].name;o=`, $id: ${a}`,i=`{ ${l}: { _eq: $id}}`}else o=`, ${s.map(l=>`$pk_${l.name}: ${l.gqlType}`).join(", ")}`,i=`{and: [${s.map(l=>`{${l.name}: {_eq: $pk_${l.name}}}`).join(", ")}]}`;return Nr(e,o,`filter: ${i}`,r)}function wl(e,t,r,s){let{param:o,filterText:i}=yr(t);const{params:a,filterTexts:l}=Kn(r,e);a.length>0&&(o+=a.map(m=>`, ${m}`).join(""));const c=[];return i&&c.push(i),c.push(...l),c.length>1?i=`{and: [${c.join(", ")}]}`:c.length===1?i=c[0]:i="",Nr(e,o,i?`filter: ${i}`:"",s)}function kr(e){return e.columns.filter(t=>t.isPrimaryKey||!Et(t.dbType))}function Sr(e,t,r,s,o,i,a,l){if(!e||!t?.data)return null;const c=t.findTable(e.graphQlName);if(!c)return null;const m=l?.fields==="export",d=m?kr(e).map(x=>x.name).join(" "):yl(e,t,c),p=m?"":mo(t,c.multiJoins),f=p?`${d} ${p}`:d;return o&&(a||i)?vl(e,t,c,d,f,i,a,m):o&&!i&&!a?jl(e,c,f):lo(e,r,s).length>0?null:wl(e,r,s,f)}function Tr(e){return!Gt(e)&&e.isPolymorphic!==!0&&(e.destinationColumnNames?.length??0)===1}function Cl(e,t){return(e.fieldName??e.destinationTable)===(t.fieldName??t.destinationTable)&&e.destinationTable===t.destinationTable&&(e.destinationColumnNames??[]).join("\0")===(t.destinationColumnNames??[]).join("\0")&&(e.sourceColumnNames??[]).join("\0")===(t.sourceColumnNames??[]).join("\0")}const Nl={data:[],total:0,offset:0,limit:0};function fo(e,t,r){const i=e?.[t]?.data?.[0]?.[r];return!i||!Array.isArray(i.data)?Nl:i}function $r(e,t,r,s){const o=r??t.findTable(e.graphQlName)?.singleJoins.find(l=>l.destinationTable===s)?.destinationTable;if(!o)return null;const i=t.findTable(o);if(!i)return null;const a=el(i.multiJoins,e.graphQlName,s);return a?{parentTable:i,childField:tl(a),childJoin:a}:null}function kl(e){const t=e.filter(it);return t.length===0?null:`query GetTableRowCounts { ${t.map(s=>`${s}: ${s}(limit: 1) { total }`).join(" ")} }`}function Sl(e=!0){const{data:t,loading:r,error:s}=Je(),o=$e(),i=u.useMemo(()=>t.map(p=>p.name),[t]),a=u.useMemo(()=>kl(i),[i]),{data:l,isLoading:c,error:m}=de.useQuery({queryKey:["tableRowCounts",i],queryFn:()=>o.query(a),enabled:e&&!!a&&i.length>0,staleTime:300*1e3});return{stats:u.useMemo(()=>{const p={};for(const f of t){const h=l?.[f.name]?.total??null;p[f.name]={columnCount:f.columns.length,rowCount:h,fkCount:f.singleJoins.length,isLoading:c,error:m?m.message:null}}return p},[t,l,c,m]),isLoading:r||c,error:s}}function Zt({kind:e}){return n.jsx("span",{className:"text-muted-foreground/60 italic select-none",children:e==="null"?"NULL":"empty"})}const Tl="display-format",$l="display-format-preview",El=new Set(["date","datetime","time","relative","number","percent","raw"]);function Fl(e){return{param:(e.paramType??"").replace("!","").toLowerCase(),db:(e.dbType??"").toLowerCase()}}function _l({param:e,db:t}){return e==="date"||t==="date"}function Pl({param:e,db:t}){return e==="datetime"||e==="datetimeoffset"||t.includes("datetime")||t==="timestamp"||t==="smalldatetime"}function po(e,t){const s=(t?e.metadata?.[t]:void 0)??e.metadata?.[Tl];if(typeof s=="string"&&El.has(s.toLowerCase()))return s.toLowerCase();const o=Fl(e);return Pl(o)?"datetime":_l(o)?"date":null}function zl(e){if(e instanceof Date)return isNaN(e.getTime())?null:e;if(typeof e=="number"){const t=new Date(e);return isNaN(t.getTime())?null:t}if(typeof e=="string"){const t=new Date(e);return isNaN(t.getTime())?null:t}return null}const Dl=new Intl.DateTimeFormat(void 0,{dateStyle:"medium"}),Ml=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"short"}),Il=new Intl.DateTimeFormat(void 0,{timeStyle:"short"}),Ll=new Intl.DateTimeFormat(void 0,{dateStyle:"full",timeStyle:"medium"}),ho=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"}),Ol=[["year",31536e3],["month",2592e3],["week",604800],["day",86400],["hour",3600],["minute",60],["second",1]];function Al(e,t=new Date){const r=Math.round((e.getTime()-t.getTime())/1e3),s=Math.abs(r);for(const[o,i]of Ol)if(s>=i||o==="second")return ho.format(Math.round(r/i),o);return ho.format(0,"second")}function Wn(e,t,r){if(e==null)return n.jsx(Zt,{kind:"null"});if(e==="")return n.jsx(Zt,{kind:"empty"});const s=po(t,r?.formatKey);if(s===null||s==="raw")return String(e);if(s==="date"||s==="datetime"||s==="time"||s==="relative"){const o=zl(e);if(!o)return String(e);const i=Ll.format(o);if(s==="relative")return n.jsx("span",{title:i,className:"cursor-help underline decoration-dotted decoration-muted-foreground/40 underline-offset-2",children:Al(o)});const a=(s==="date"?Dl:s==="time"?Il:Ml).format(o);return n.jsx("span",{title:i,children:a})}if(s==="number"||s==="percent"){const o=typeof e=="number"?e:Number(e);if(isNaN(o))return String(e);const i=s==="percent"?new Intl.NumberFormat(void 0,{style:"percent",maximumFractionDigits:2}).format(o):new Intl.NumberFormat(void 0).format(o);return n.jsx("span",{title:String(e),children:i})}return String(e)}function go(e){if(!e)return"";const t=new Date(e);return t.toString()==="Invalid Date"||t.getTime()===0||t.getUTCFullYear()<=1?"":t.toLocaleString()}function ql(e){if(e===null)return"—";if(e===0)return"0";if(e<1e3)return e.toString();if(e<1e6){const r=e/1e3;return r%1===0?`${r.toFixed(0)}k`:`${r.toFixed(1)}k`}const t=e/1e6;return t%1===0?`${t.toFixed(0)}M`:`${t.toFixed(1)}M`}const xo="\uFEFF",Vl=/["\n\r,]/;function Er(e){if(e==null)return"";const t=Bl(e);return t===""?'""':Vl.test(t)?`"${t.replace(/"/g,'""')}"`:t}function Bl(e){switch(typeof e){case"string":return e;case"bigint":return e.toString();case"number":case"boolean":return String(e);case"object":return e instanceof Date?e.toISOString():JSON.stringify(e);default:return String(e)}}function bo(e,t,r={}){const s=e.map(Er).join(","),o=t.map(a=>a.map(Er).join(",")),i=[s,...o].join(`\r
89
+ `);return r.bom?xo+i:i}function yo(e,t){return typeof t=="bigint"?t.toString():t}function vo(e,t){const r={};for(let s=0;s<e.length;s++)r[e[s]]=t[s];return r}function jo(e,t,r={}){if(r.mode==="lines")return t.map(o=>JSON.stringify(vo(e,o),yo)).join(`
90
+ `);const s=t.map(o=>vo(e,o));return JSON.stringify(s,yo,2)}const Gl=500;function Fr(e){if(e?.aborted)throw new DOMException("Export cancelled","AbortError")}async function _r(e){const t=e.pageSize??Gl,{rowCap:r,signal:s}=e,o=[];let i=0,a=!1;Fr(s);let l=0,c=Number.POSITIVE_INFINITY;for(;l<c;){Fr(s);const d=await e.fetchPage(l,t);i=d.total,c=d.total;for(const p of d.rows){if(r!==void 0&&o.length>=r){a=!0;break}o.push(p)}if(e.onProgress?.(o.length,i),a||d.rows.length===0)break;l+=d.rows.length}return Fr(s),{content:e.format==="csv"?bo(e.headers,o,e.csv):jo(e.headers,o,e.json),rowCount:o.length,total:i,truncated:a}}const Pr=1e5;function zr(e){return e==="csv"?"text/csv;charset=utf-8;":"application/json;charset=utf-8;"}function Dr(e,t){return`${e}-export.${t}`}function wo(e,t,r){if(typeof window>"u"||typeof document>"u")return;const s=new Blob([e],{type:r}),o=URL.createObjectURL(s),i=document.createElement("a");i.href=o,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o)}function Kl(e,t,r){if(typeof window>"u"||typeof document>"u")return;const s=Uint8Array.from(atob(e),l=>l.charCodeAt(0)),o=new Blob([s],{type:r}),i=URL.createObjectURL(o),a=document.createElement("a");a.href=i,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}function Co(){const{saveFile:e}=Dn();return u.useCallback(async(t,r,s)=>{if(e){await e({filename:t,content:r,mime:s});return}wo(r,t,s)},[e])}function Wl(){const e=Je(),t=$e(),r=Co();return u.useCallback(async(s,o)=>{const i=Sr(s,e,"",[],void 0,void 0,void 0,{fields:"export"});if(!i)throw new Error(`Cannot export '${s.label??s.name}': no export query could be built.`);const a=kr(s),l=await _r({format:o,headers:a.map(c=>c.label??c.name),csv:{bom:!0},rowCap:Pr,fetchPage:async(c,m)=>{const p=(await t.query(i,{limit:m,offset:c}))?.[s.name],f=p?.data??[];return{rows:f.map(x=>a.map(h=>x[h.name])),total:p?.total??f.length}}});return await r(Dr(s.name,o),l.content,zr(o)),l},[e,t,r])}const No=u.createContext({toast:()=>{}}),Jl=4e3;function ko({children:e}){const[t,r]=u.useState([]),s=u.useRef(0),o=u.useRef(new Set),i=u.useCallback(c=>{r(m=>m.filter(d=>d.id!==c))},[]),a=u.useCallback((c,m="success")=>{const d=s.current++;r(f=>[...f,{id:d,message:c,variant:m}]);const p=setTimeout(()=>{i(d),o.current.delete(p)},Jl);o.current.add(p)},[i]);u.useEffect(()=>{const c=o.current;return()=>{c.forEach(clearTimeout)}},[]);const l=u.useMemo(()=>({toast:a}),[a]);return n.jsxs(No.Provider,{value:l,children:[e,n.jsx("div",{className:"fixed bottom-4 right-4 z-[100] flex flex-col gap-2 max-w-sm",role:"region","aria-label":"Notifications",children:t.map(c=>n.jsxs("div",{role:"status",className:Y("flex items-start gap-2 rounded-md border px-3 py-2 text-sm shadow-md bg-popover",c.variant==="error"?"border-destructive/40 text-destructive":"border-border text-foreground"),children:[c.variant==="error"?n.jsx(w.AlertCircle,{className:"size-4 shrink-0 mt-0.5"}):n.jsx(w.CheckCircle2,{className:"size-4 shrink-0 mt-0.5 text-green-600"}),n.jsx("span",{className:"flex-1 break-words",children:c.message}),n.jsx("button",{type:"button",onClick:()=>i(c.id),"aria-label":"Dismiss notification",className:"shrink-0 opacity-60 hover:opacity-100",children:n.jsx(w.X,{className:"size-3.5"})})]},c.id))})]})}function vt(){return u.useContext(No)}const Jn=50;function Ql(e,t){return e===null||t<=0?0:Math.max(2,Math.min(100,Math.round(e/t*100)))}function Hl({percent:e,label:t}){return n.jsx("span",{className:"flex-1 min-w-[1.5em] h-[0.5em] rounded-full bg-muted/70 overflow-hidden",role:"img","aria-label":t,title:t,children:n.jsx("span",{className:"block h-full rounded-full bg-emerald-500/70 dark:bg-emerald-400/70",style:{width:`${e}%`}})})}function Mr({count:e}){return e<=0?null:n.jsxs("span",{className:"shrink-0 rounded px-1 py-px text-[0.85em] tabular-nums bg-blue-100 text-blue-700 dark:bg-blue-900/60 dark:text-blue-300",children:[e," FK"]})}function Ul(e){try{return decodeURIComponent(e)}catch{return e}}function Yl({stats:e,maxRowCount:t}){const r=Ql(e.rowCount,t),s="flex items-center gap-1.5 text-xs leading-none min-w-0";return e.isLoading?n.jsxs("div",{className:`${s} text-muted-foreground`,children:[n.jsxs("span",{className:"tabular-nums shrink-0",children:[e.columnCount,"c"]}),n.jsx("span",{className:"flex-1 min-w-[1.5em] h-[0.5em] rounded-full bg-muted/70 overflow-hidden",children:n.jsx("span",{className:"block h-full w-1/3 rounded-full bg-muted-foreground/30 animate-pulse"})}),n.jsx(w.Loader2,{className:"size-[1em] shrink-0 animate-spin"}),n.jsx(Mr,{count:e.fkCount})]}):e.error?n.jsxs("div",{className:s,children:[n.jsxs("span",{className:"tabular-nums shrink-0 text-muted-foreground",children:[e.columnCount,"c"]}),n.jsx("span",{className:"flex-1 text-destructive truncate",title:e.error,children:"err"}),n.jsx(Mr,{count:e.fkCount})]}):n.jsxs("div",{className:s,children:[n.jsxs("span",{className:"tabular-nums shrink-0 text-muted-foreground/70",children:[e.columnCount,"c"]}),n.jsx(Hl,{percent:r,label:`${e.rowCount?.toLocaleString()??"unknown"} rows`}),n.jsx("span",{className:"tabular-nums shrink-0 text-right text-muted-foreground",children:ql(e.rowCount)}),n.jsx(Mr,{count:e.fkCount})]})}function Rl({table:e,stats:t,maxRowCount:r,showStats:s,active:o,actions:i}){const a=(i??[]).filter(l=>l.enabled?.(e)??!0);return n.jsxs("div",{className:`group/tablerow flex items-stretch border-l-2 ${o?"bg-accent text-accent-foreground border-primary":"text-foreground border-transparent hover:bg-muted/50"}`,children:[n.jsx(Pn,{to:`/${e.name}`,"aria-current":o?"page":void 0,className:`plain-link flex-1 min-w-0 no-underline py-1.5 px-2 text-sm font-medium ${o?"":"hover:text-primary"}`,children:n.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0",children:[n.jsx("span",{className:"truncate",title:e.label,children:e.label}),s&&n.jsx(Yl,{stats:t,maxRowCount:r})]})}),a.length>0&&n.jsxs(On,{children:[n.jsx(An,{asChild:!0,children:n.jsx("button",{type:"button","aria-label":`Actions for ${e.label}`,className:"shrink-0 px-1 opacity-0 group-hover/tablerow:opacity-100 focus:opacity-100 data-[state=open]:opacity-100 text-muted-foreground hover:text-foreground",children:n.jsx(w.MoreVertical,{className:"size-3.5"})})}),n.jsx(qn,{align:"start",children:a.map(l=>{const c=l.icon;return n.jsxs(bt,{onSelect:()=>{l.onSelect(e)},children:[c&&n.jsx(c,{className:"size-3.5"}),l.label]},l.id)})})]})]})}function Ir(e){const t=e.dbName.lastIndexOf(".");return t>0?e.dbName.slice(0,t):null}function So({schema:e,count:t,collapsed:r,context:s,onToggle:o}){const i=r?w.ChevronRight:w.ChevronDown,a=n.jsxs(n.Fragment,{children:[n.jsx(i,{className:"size-3.5 shrink-0 text-muted-foreground"}),n.jsx("span",{className:"truncate font-semibold",title:e,children:e}),n.jsx("span",{className:"ml-auto shrink-0 tabular-nums text-[0.85em] text-muted-foreground",children:t})]}),l="flex items-center gap-1.5 w-full px-2 py-1 text-xs uppercase tracking-wide text-muted-foreground bg-muted/40 border-y border-border sticky top-0 z-10";return s?n.jsx("div",{className:l,"aria-hidden":"true",children:a}):n.jsx("button",{type:"button",onClick:o,"aria-expanded":!r,className:`${l} hover:bg-muted/70 text-left`,children:a})}function Xl(){const{showStats:e,tableActions:t}=Dn(),{loading:r,error:s,data:o}=Je(),i=Wl(),{toast:a}=vt(),l=u.useCallback(async(F,P)=>{try{const A=await i(F,P);a(A.truncated?`${F.label} exported (truncated to ${A.rowCount.toLocaleString()} of ${A.total.toLocaleString()} rows)`:`${F.label} exported (${A.rowCount.toLocaleString()} rows)`)}catch(A){a(`Export failed: ${A.message}`,"error")}},[i,a]),c=u.useMemo(()=>[{id:"download-csv",label:"Download CSV",icon:w.Download,onSelect:F=>l(F,"csv")},{id:"download-json",label:"Download JSON",icon:w.Download,onSelect:F=>l(F,"json")},...t??[]],[l,t]),{stats:m,isLoading:d}=Sl(e),[p,f]=u.useState(""),[x,h]=u.useState(new Set),[b,N]=u.useState(0),T=fs(),k=Ul(T.split("/")[1]??""),E=u.useMemo(()=>{const F=Object.values(m).map(P=>P.rowCount).filter(P=>P!==null);return F.length>0?Math.max(...F):0},[m]),y=p.trim().length>0,v=u.useMemo(()=>{const F=p.trim().toLowerCase();return F?o.filter(P=>{const A=Ir(P);return P.label.toLowerCase().includes(F)||P.dbName.toLowerCase().includes(F)||(A?.toLowerCase().includes(F)??!1)}):o},[o,p]),{schemas:j,grouped:S,multiSchema:C}=u.useMemo(()=>{const F=new Map;for(const A of v){const U=Ir(A),_=F.get(U)??[];_.push(A),F.set(U,_)}const P=[...F.keys()].filter(A=>A!==null).sort((A,U)=>A.localeCompare(U));return{schemas:P,grouped:F,multiSchema:P.length>1}},[v]),B=u.useMemo(()=>{const F=[];if(C){const P=[...j,...S.has(null)?[null]:[]];for(const A of P){const U=S.get(A===void 0?null:A)??[],_=!y&&x.has(A);if(F.push({kind:"group",schema:A??"(no schema)",count:U.length,collapsed:_}),!_)for(const ce of U)F.push({kind:"table",schema:A,table:ce})}}else for(const P of v)F.push({kind:"table",schema:Ir(P),table:P});return F},[C,j,S,v,x,y]);u.useEffect(()=>{N(0)},[p]);const $=Math.max(1,Math.ceil(B.length/Jn)),L=Math.min(b,$-1),q=L*Jn,D=B.slice(q,q+Jn),V=C&&D[0]?.kind==="table"&&D[0].schema?D[0].schema:null,X=F=>h(P=>{const A=new Set(P);return A.has(F)?A.delete(F):A.add(F),A});return r?n.jsxs("div",{className:"flex items-center justify-center gap-2 p-4",children:[n.jsx(w.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):s?n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",s.message]})}):o.length===0?n.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[n.jsx("p",{className:"font-medium",children:"No tables found"}),n.jsx("p",{className:"mt-1",children:"The database may be empty or the connection may have failed."})]}):n.jsxs("div",{className:"@container min-w-0 flex flex-col h-full",children:[n.jsxs("div",{className:"sticky top-0 z-20 bg-background p-2 border-b border-border",children:[n.jsxs("div",{className:"relative",children:[n.jsx(w.Search,{className:"absolute left-2 top-1/2 -translate-y-1/2 size-4 text-muted-foreground pointer-events-none"}),n.jsx(Qe,{type:"search",value:p,onChange:F=>f(F.target.value),placeholder:"Search tables...","aria-label":"Search tables",className:"pl-8 pr-8 h-8 text-sm"}),y&&n.jsx("button",{type:"button",onClick:()=>f(""),"aria-label":"Clear search",className:"absolute right-1.5 top-1/2 -translate-y-1/2 p-0.5 rounded text-muted-foreground hover:text-foreground hover:bg-muted",children:n.jsx(w.X,{className:"size-4"})})]}),y&&n.jsxs("p",{className:"mt-1 px-0.5 text-xs text-muted-foreground",children:[v.length," match",v.length!==1?"es":""]})]}),n.jsx("div",{className:"flex-1 overflow-y-auto min-h-0",children:B.length===0?n.jsxs("p",{className:"p-4 text-center text-sm text-muted-foreground",children:["No tables match “",p,"”."]}):n.jsxs(n.Fragment,{children:[V&&n.jsx(So,{schema:V,count:S.get(V)?.length??0,collapsed:!1,context:!0}),D.map(F=>F.kind==="group"?n.jsx(So,{schema:F.schema,count:F.count,collapsed:F.collapsed,onToggle:()=>X(F.schema)},`g:${F.schema}`):n.jsx(Rl,{table:F.table,stats:m[F.table.name]??{columnCount:F.table.columns.length,rowCount:null,fkCount:F.table.singleJoins.length,isLoading:d,error:null},maxRowCount:E,showStats:e,active:F.table.name===k,actions:c},`t:${F.table.name}`))]})}),$>1&&n.jsxs("div",{className:"sticky bottom-0 z-20 bg-background border-t border-border flex items-center justify-between gap-2 px-2 py-1.5",children:[n.jsx("button",{type:"button",onClick:()=>N(F=>Math.max(0,F-1)),disabled:L===0,"aria-label":"Previous page",className:"p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 disabled:pointer-events-none",children:n.jsx(w.ChevronLeft,{className:"size-4"})}),n.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:[q+1,"–",Math.min(q+Jn,B.length)," of ",B.length]}),n.jsx("button",{type:"button",onClick:()=>N(F=>Math.min($-1,F+1)),disabled:L>=$-1,"aria-label":"Next page",className:"p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted disabled:opacity-40 disabled:pointer-events-none",children:n.jsx(w.ChevronRight,{className:"size-4"})})]})]})}const Zl=Es("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background text-foreground hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"text-foreground hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10","icon-sm":"h-8 w-8 rounded-md"}},defaultVariants:{variant:"default",size:"default"}}),Q=Ve.forwardRef(({className:e,variant:t,size:r,asChild:s=!1,...o},i)=>{const a=s?Sa.Slot:"button";return n.jsx(a,{className:Y(Zl({variant:t,size:r,className:e})),ref:i,...o})});Q.displayName="Button";const gn=Ve.forwardRef(({...e},t)=>n.jsx(R.HoverCard.Root,{"data-slot":"hover-card",...e}));gn.displayName="HoverCard";const xn=Ve.forwardRef(({...e},t)=>n.jsx(R.HoverCard.Trigger,{"data-slot":"hover-card-trigger",...e}));xn.displayName="HoverCardTrigger";const bn=Ve.forwardRef(({className:e,align:t="center",sideOffset:r=4,...s},o)=>n.jsx(R.HoverCard.Portal,{children:n.jsx(R.HoverCard.Content,{ref:o,"data-slot":"hover-card-content",align:t,sideOffset:r,className:Y("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...s})}));bn.displayName="HoverCardContent";function Ze({...e}){return n.jsx(R.Select.Root,{"data-slot":"select",...e})}function et({...e}){return n.jsx(R.Select.Value,{"data-slot":"select-value",...e})}function tt({className:e,size:t="default",children:r,...s}){return n.jsxs(R.Select.Trigger,{"data-slot":"select-trigger","data-size":t,className:Y("flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent text-foreground px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...s,children:[r,n.jsx(R.Select.Icon,{asChild:!0,children:n.jsx(w.ChevronDownIcon,{className:"size-4 opacity-50"})})]})}function nt({className:e,children:t,position:r="item-aligned",align:s="center",...o}){return n.jsx(R.Select.Portal,{children:n.jsxs(R.Select.Content,{"data-slot":"select-content",className:Y("relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",r==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:r,align:s,...o,children:[n.jsx(ec,{}),n.jsx(R.Select.Viewport,{className:Y("p-1",r==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),n.jsx(tc,{})]})})}function we({className:e,children:t,...r}){return n.jsxs(R.Select.Item,{"data-slot":"select-item",className:Y("relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...r,children:[n.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:n.jsx(R.Select.ItemIndicator,{children:n.jsx(w.CheckIcon,{className:"size-4"})})}),n.jsx(R.Select.ItemText,{children:t})]})}function ec({className:e,...t}){return n.jsx(R.Select.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:Y("flex cursor-default items-center justify-center py-1",e),...t,children:n.jsx(w.ChevronUpIcon,{className:"size-4"})})}function tc({className:e,...t}){return n.jsx(R.Select.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:Y("flex cursor-default items-center justify-center py-1",e),...t,children:n.jsx(w.ChevronDownIcon,{className:"size-4"})})}function To(e){const t=u.useRef(null),r=u.useRef(null),s=u.useRef(e);s.current=e;const o=u.useMemo(()=>{const i=()=>{t.current&&(clearTimeout(t.current),t.current=null)},a=()=>{i();const l=r.current;r.current=null,l?.()};return{schedule:l=>{i(),r.current=l,t.current=setTimeout(a,s.current)},cancel:()=>{i(),r.current=null},flush:a}},[]);return u.useEffect(()=>()=>o.flush(),[o]),o}const $o={_contains:"Contains",_starts_with:"Starts with",_ends_with:"Ends with",_eq:"Equals",_neq:"Not equals",_null:"Is null"},nc=300;function rc({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(b=>b in $o),s=e.getFilterValue(),[o,i]=u.useState(s?.operator??"_contains"),[a,l]=u.useState(s?.operator==="_null"?"":String(s?.value??"")),{schedule:c,cancel:m}=To(nc),d=o==="_null",p=(b,N)=>{if(b==="_null"){m(),e.setFilterValue({operator:"_null",value:!0});return}if(!N){m(),e.setFilterValue(void 0);return}c(()=>e.setFilterValue({operator:b,value:N}))},f=b=>{i(b),b==="_null"?(l(""),p("_null","")):a?p(b,a):(m(),e.setFilterValue(void 0))},x=b=>{l(b),p(o,b)},h=()=>{m(),i("_contains"),l(""),e.setFilterValue(void 0)};return r.length===0?null:n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:o,onValueChange:f,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:r.map(b=>n.jsx(we,{value:b,children:$o[b]},b))})]}),!d&&n.jsx(Qe,{placeholder:"Filter value...",value:a,onChange:b=>x(b.target.value),className:"h-8 text-xs",autoFocus:!0}),s!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:h,children:[n.jsx(w.X,{className:"size-3"}),"Clear filter"]})]})}const Eo={_eq:"Equals",_neq:"Not equals",_gt:"Greater than",_gte:"Greater or equal",_lt:"Less than",_lte:"Less or equal",_between:"Between",_null:"Is null"},sc=300;function oc(e){return e.columnDef.meta?.paramType??""}function Lr(e,t){return Zs(e,t)}function ac({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(D=>D in Eo),s=oc(e),o=qt(s),i=Bt(s),a=e.getFilterValue(),l=a?.operator??"_eq",[c,m]=u.useState(l),[d,p]=u.useState(()=>!a||a.operator==="_null"||a.operator==="_between"?"":String(a.value??"")),[f,x]=u.useState(()=>a?.operator==="_between"&&Array.isArray(a.value)?String(a.value[0]??""):""),[h,b]=u.useState(()=>a?.operator==="_between"&&Array.isArray(a.value)?String(a.value[1]??""):""),{schedule:N,cancel:T}=To(sc),k=(D,V)=>{if(D==="_null"){T(),e.setFilterValue({operator:"_null",value:!0});return}const X=Lr(V,s);if(X===null){T(),e.setFilterValue(void 0);return}N(()=>e.setFilterValue({operator:D,value:X}))},E=(D,V)=>{const X=Lr(D,s),F=Lr(V,s);if(X===null||F===null){T(),e.setFilterValue(void 0);return}N(()=>e.setFilterValue({operator:"_between",value:[X,F]}))},y=D=>{m(D),D==="_null"?(p(""),x(""),b(""),k("_null","")):D==="_between"?(p(""),f&&h?E(f,h):(T(),e.setFilterValue(void 0))):(x(""),b(""),d?k(D,d):(T(),e.setFilterValue(void 0)))},v=D=>{p(D),k(c,D)},j=D=>{x(D),E(D,h)},S=D=>{b(D),E(f,D)},C=()=>{T(),m("_eq"),p(""),x(""),b(""),e.setFilterValue(void 0)};if(r.length===0)return null;const B=c==="_between",$=c==="_null",L=i?"text":"number",q=i?o?"numeric":"decimal":void 0;return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:c,onValueChange:y,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:r.map(D=>n.jsx(we,{value:D,children:Eo[D]},D))})]}),!$&&!B&&n.jsx(Qe,{type:L,inputMode:q,placeholder:"Filter value...",value:d,onChange:D=>v(D.target.value),className:"h-8 text-xs",autoFocus:!0}),B&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Qe,{type:L,inputMode:q,placeholder:"Min",value:f,onChange:D=>j(D.target.value),className:"h-8 text-xs",autoFocus:!0}),n.jsx(Qe,{type:L,inputMode:q,placeholder:"Max",value:h,onChange:D=>S(D.target.value),className:"h-8 text-xs"})]}),a!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:C,children:[n.jsx(w.X,{className:"size-3"}),"Clear filter"]})]})}const Fo={_eq:"On",_neq:"Not on",_gt:"After",_gte:"On or after",_lt:"Before",_lte:"On or before",_between:"Between",_null:"Is null"};function ic({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).filter(j=>j in Fo),s=e.getFilterValue(),o=s?.operator??"_eq",[i,a]=u.useState(o),[l,c]=u.useState(()=>!s||s.operator==="_null"||s.operator==="_between"?"":String(s.value??"")),[m,d]=u.useState(()=>s?.operator==="_between"&&Array.isArray(s.value)?String(s.value[0]??""):""),[p,f]=u.useState(()=>s?.operator==="_between"&&Array.isArray(s.value)?String(s.value[1]??""):""),x=(j,S)=>{if(j==="_null"){e.setFilterValue({operator:"_null",value:!0});return}if(!S){e.setFilterValue(void 0);return}e.setFilterValue({operator:j,value:S})},h=(j,S)=>{if(!j||!S){e.setFilterValue(void 0);return}e.setFilterValue({operator:"_between",value:[j,S]})},b=j=>{a(j),j==="_null"?(c(""),d(""),f(""),e.setFilterValue({operator:"_null",value:!0})):j==="_between"?(c(""),m&&p?h(m,p):e.setFilterValue(void 0)):(d(""),f(""),l?x(j,l):e.setFilterValue(void 0))},N=j=>{c(j),x(i,j)},T=j=>{d(j),h(j,p)},k=j=>{f(j),h(m,j)},E=()=>{a("_eq"),c(""),d(""),f(""),e.setFilterValue(void 0)};if(r.length===0)return null;const y=i==="_between",v=i==="_null";return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:i,onValueChange:b,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:r.map(j=>n.jsx(we,{value:j,children:Fo[j]},j))})]}),!v&&!y&&n.jsx(Qe,{type:"date",value:l,onChange:j=>N(j.target.value),className:"h-8 text-xs"}),y&&n.jsxs("div",{className:"flex gap-2",children:[n.jsx(Qe,{type:"date",value:m,onChange:j=>T(j.target.value),className:"h-8 text-xs"}),n.jsx(Qe,{type:"date",value:p,onChange:j=>k(j.target.value),className:"h-8 text-xs"})]}),s!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:E,children:[n.jsx(w.X,{className:"size-3"}),"Clear filter"]})]})}const lc={all:"All",true:"True",false:"False",_null:"Is null"};function cc(e){return e?e.operator==="_null"?"_null":e.operator==="_eq"&&e.value===!0?"true":e.operator==="_eq"&&e.value===!1?"false":"all":"all"}function uc({column:e}){const r=(e.columnDef.meta?.filterOperators??[]).includes("_null"),s=e.getFilterValue(),o=cc(s),i=r?["all","true","false","_null"]:["all","true","false"],a=c=>{switch(c){case"true":e.setFilterValue({operator:"_eq",value:!0});break;case"false":e.setFilterValue({operator:"_eq",value:!1});break;case"_null":e.setFilterValue({operator:"_null",value:!0});break;default:e.setFilterValue(void 0)}},l=()=>{e.setFilterValue(void 0)};return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:o,onValueChange:a,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:i.map(c=>n.jsx(we,{value:c,children:lc[c]},c))})]}),s!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:l,children:[n.jsx(w.X,{className:"size-3"}),"Clear filter"]})]})}function dc(e,t,r,s){return!it(e)||!it(t)||!it(r)||s&&(!s.some(o=>o.name===t)||!s.some(o=>o.name===r))?null:`query Lookup${e} { ${e}(sort: [${t}_asc], limit: 100) { data { id: ${r} label: ${t} } } }`}function mc({column:e,joinTable:t,joinLabelColumn:r,joinFkColumn:s}){const o=$e(),a=Je().findTable(t),l=dc(t,r,s,a?.columns),c=mn(a?.columns.find(b=>b.name===s)),{data:m}=de.useQuery({queryKey:["fkLookup",t,r,s],queryFn:()=>o.query(l),staleTime:300*1e3,enabled:!!a&&!!l}),d=m?.[t]?.data??[],p=e.getFilterValue(),f=p?.operator==="_eq"&&p.value!=null?String(p.value):"all",x=b=>{if(b==="all"){e.setFilterValue(void 0);return}e.setFilterValue({operator:"_eq",value:dt(b,c)})},h=()=>{e.setFilterValue(void 0)};return n.jsxs("div",{className:"flex flex-col gap-2 p-2 min-w-[220px]",children:[n.jsxs(Ze,{value:f,onValueChange:x,children:[n.jsx(tt,{size:"sm",className:"w-full text-xs",children:n.jsx(et,{})}),n.jsxs(nt,{children:[n.jsx(we,{value:"all",children:"All"}),d.map(b=>n.jsx(we,{value:String(b.id),children:String(b.label)},String(b.id)))]})]}),p!==void 0&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 text-xs justify-start",onClick:h,children:[n.jsx(w.X,{className:"size-3"}),"Clear filter"]})]})}function Qn(e){return(e.columnDef.meta?.paramType??"").replace("!","")}function fc(e){return Qn(e)==="String"}function pc(e){return Vt(Qn(e))}function hc(e){return Xs(Qn(e))}function gc(e){return Qn(e)==="Boolean"}function xc(e){const t=e.columnDef.meta;return t?.joinTable?{joinTable:t.joinTable,joinLabelColumn:t.joinLabelColumn??"id",joinFkColumn:t.joinFkColumn??null,isSelfReference:t.isSelfReference===!0}:null}function bc(e){return e.columnDef.meta?.column}function _o(e){const t=e.paramType.replace("!","");if(e.dbType){const r=e.dbType.toUpperCase();return e.maxLength&&(r.includes("VARCHAR")||r.includes("CHAR"))?`${r}(${e.maxLength})`:(r.includes("DECIMAL")||r.includes("NUMERIC"),r)}return t}function yc(e){const t=e.paramType.replace("!","");return e.isPrimaryKey?n.jsx(w.Key,{className:"size-3.5"}):Vt(t)?n.jsx(w.Hash,{className:"size-3.5"}):Xs(t)?n.jsx(w.Calendar,{className:"size-3.5"}):t==="Boolean"?n.jsx(w.ToggleLeft,{className:"size-3.5"}):n.jsx(w.Type,{className:"size-3.5"})}function vc({column:e,fkMeta:t}){const r=_o(e),s=e.isNullable,o=e.isPrimaryKey,i=e.isIdentity,a=e.defaultValue;return n.jsxs("div",{className:"space-y-2",children:[n.jsxs("div",{className:"flex items-center gap-2 border-b pb-2",children:[yc(e),n.jsx("span",{className:"font-semibold text-foreground",children:e.label})]}),n.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:[n.jsx("dt",{className:"text-muted-foreground",children:"Type"}),n.jsx("dd",{className:"text-foreground font-medium",children:r}),n.jsx("dt",{className:"text-muted-foreground",children:"Nullable"}),n.jsx("dd",{className:"text-foreground",children:s?"Yes":"No"}),o&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Primary Key"}),n.jsxs("dd",{className:"text-foreground text-primary flex items-center gap-1",children:[n.jsx(w.Key,{className:"size-3"}),"Yes"]})]}),i&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Auto Increment"}),n.jsx("dd",{className:"text-foreground",children:"Yes"})]}),t&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Foreign Key"}),n.jsxs("dd",{className:"text-foreground text-primary flex items-center gap-1",children:[n.jsx(w.Link2,{className:"size-3"}),t.joinTable,t.isSelfReference&&n.jsx("span",{className:"ml-1 px-1 rounded bg-primary/10 text-[10px] font-medium",children:"self-ref"})]})]}),a!=null&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Default"}),n.jsx("dd",{className:"text-foreground font-mono text-xs truncate max-w-[150px]",children:String(a)})]}),e.maxLength!==void 0&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Max Length"}),n.jsx("dd",{className:"text-foreground",children:e.maxLength})]}),e.min!==void 0&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Min"}),n.jsx("dd",{className:"text-foreground",children:e.min})]}),e.max!==void 0&&n.jsxs(n.Fragment,{children:[n.jsx("dt",{className:"text-muted-foreground",children:"Max"}),n.jsx("dd",{className:"text-foreground",children:e.max})]})]})]})}function yn({column:e,table:t,title:r}){const s=t.options.meta?.onResetColumnWidths;if(!e.getCanSort())return n.jsx("span",{children:r});const o=e.getIsSorted(),i=e.getFilterValue()!==void 0,a=xc(e),l=a?.joinFkColumn??null,c=!l&&fc(e),m=!l&&pc(e),d=!l&&hc(e),p=!l&&gc(e),f=bc(e),x=n.jsxs(Q,{variant:"ghost",size:"sm",className:Y("-ml-2 h-7 text-xs data-[state=open]:bg-accent",o&&"text-foreground"),children:[n.jsx("span",{children:r}),i&&n.jsx(w.Filter,{className:"size-3 text-primary"}),o==="desc"?n.jsx(w.ArrowDown,{className:"size-4"}):o==="asc"?n.jsx(w.ArrowUp,{className:"size-4"}):n.jsx(w.ArrowUpDown,{className:"size-4"})]});return n.jsxs(gn,{openDelay:400,closeDelay:200,children:[n.jsx(xn,{asChild:!0,children:n.jsx("span",{className:"inline-flex",children:n.jsxs(On,{children:[n.jsx(An,{asChild:!0,children:x}),n.jsxs(qn,{align:"start",children:[f&&n.jsxs(n.Fragment,{children:[n.jsxs(Ji,{className:"text-xs font-normal text-muted-foreground",children:[_o(f),f.isNullable?" · nullable":" · required",f.isPrimaryKey?" · PK":"",a?` · FK → ${a.joinTable}`:""]}),n.jsx(yt,{})]}),n.jsxs(bt,{onClick:()=>e.toggleSorting(!1),children:[n.jsx(w.ArrowUp,{className:"size-3.5 text-muted-foreground"}),"Asc"]}),n.jsxs(bt,{onClick:()=>e.toggleSorting(!0),children:[n.jsx(w.ArrowDown,{className:"size-3.5 text-muted-foreground"}),"Desc"]}),o&&n.jsxs(bt,{onClick:()=>e.clearSorting(),children:[n.jsx(w.ArrowUpDown,{className:"size-3.5 text-muted-foreground"}),"Clear"]}),c&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(w.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(rc,{column:e})})]})]}),m&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(w.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(ac,{column:e})})]})]}),d&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(w.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(ic,{column:e})})]})]}),p&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(w.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(uc,{column:e})})]})]}),a&&l&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(cn,{children:[n.jsxs(un,{children:[n.jsx(w.Filter,{className:Y("size-3.5",i?"text-primary":"text-muted-foreground")}),"Filter"]}),n.jsx(dn,{children:n.jsx(mc,{column:e,joinTable:a.joinTable,joinLabelColumn:a.joinLabelColumn,joinFkColumn:l})})]})]}),e.getCanHide()&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(bt,{onClick:()=>e.toggleVisibility(!1),children:[n.jsx(w.EyeOff,{className:"size-3.5 text-muted-foreground"}),"Hide"]})]}),s&&n.jsxs(n.Fragment,{children:[n.jsx(yt,{}),n.jsxs(bt,{onClick:s,children:[n.jsx(w.RotateCcw,{className:"size-3.5 text-muted-foreground"}),"Reset column widths"]})]})]})]})})}),f&&n.jsx(bn,{align:"start",className:"w-64",children:n.jsx(vc,{column:f,fkMeta:a})})]})}const jc=5,wc=400,Cc=200;function Nc(e){return e.filter(t=>!t.isPrimaryKey&&!_t(t)).slice(0,jc)}function kc(e,t,r,s){const o=t.map(i=>i.name).join(" ");return`query FkPreview($id: ${s}) { ${e}(filter: { ${r}: { _eq: $id } } limit: 1) { data { ${o} } } }`}function Sc(e,t,r,s){const o=t.map(i=>i.name).join(" ");return`query FkPreview(${r}) { ${e}(filter: ${s} limit: 1) { data { ${o} } } }`}function Tc(e,t,r,s,o,i,a){if(r.length===0)return null;if(s&&Gt(s)&&o){const d=Xi(o,s,t);if(!d)return null;const p=d.params.join(", ");return{query:Sc(e,r,p,d.filterText),variables:d.variables,cacheKey:d.variables}}const l=t.columns.find(d=>d.name===a)?.paramType??"Int",c=ao(l),m={id:dt(i,c)};return{query:kc(e,r,a,c),variables:m,cacheKey:`${a}:${i}`}}function $c({tableName:e,fkValue:t,filterColumn:r,join:s,sourceRow:o,children:i}){const[a,l]=u.useState(!1),c=Je(),m=$e(),d=c.findTable(e),p=d?Nc(d.columns):[],f=d?Tc(e,d,p,s,o,t,r):null,{data:x,isLoading:h}=de.useQuery({queryKey:["fkPreview",e,f?.cacheKey],queryFn:()=>m.query(f.query,f.variables),enabled:a&&!!f,staleTime:300*1e3}),b=x?.[e]?.data?.[0];return n.jsxs(gn,{openDelay:wc,closeDelay:Cc,open:a,onOpenChange:l,children:[n.jsx(xn,{asChild:!0,children:i}),n.jsx(bn,{align:"start",className:"w-72",children:n.jsxs("div",{className:"space-y-2",children:[n.jsx("p",{className:"text-sm font-semibold text-foreground",children:d?.label??e}),h&&n.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading..."}),b&&n.jsx("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs",children:p.map(N=>n.jsxs("div",{className:"contents",children:[n.jsx("dt",{className:"text-muted-foreground truncate",children:N.label}),n.jsx("dd",{className:"text-foreground truncate",children:Wn(b[N.name],N,{formatKey:$l})})]},N.name))}),!h&&!b&&a&&n.jsx("p",{className:"text-xs text-muted-foreground",children:"Record not found"})]})})]})}const Ec={json:w.Braces,xml:w.Code,"php-serialized":w.Database,binary:w.Binary,longtext:w.FileText,text:w.FileText},Fc={json:"JSON",xml:"XML","php-serialized":"PHP",binary:"Binary",longtext:"Text",text:"Text"};function _c(e,t){if(t==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return e}function Po({value:e,dbType:t,onExpand:r,deferred:s}){if(e===void 0&&s)return n.jsxs("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[n.jsx(w.FileText,{className:"size-3.5"}),n.jsx("span",{className:"text-xs italic",children:"content"}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(w.Expand,{className:"size-3"})})]});if(e==null)return n.jsx(Zt,{kind:"null"});const o=typeof e=="object"?JSON.stringify(e):String(e);if(o==="")return n.jsx(Zt,{kind:"empty"});const i=Gn(o,t);if(i==="text")return n.jsx("span",{children:o});if(i==="binary")return n.jsxs("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground",children:[n.jsx(w.Binary,{className:"size-3.5"}),n.jsx("span",{className:"text-xs font-mono",children:xr(o)}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(w.Expand,{className:"size-3"})})]});const a=Ec[i],l=ol(o);return o.length>80||i==="json"||i==="xml"||i==="php-serialized"?n.jsxs("span",{className:"inline-flex items-center gap-1.5 max-w-full",children:[n.jsxs(gn,{openDelay:300,closeDelay:200,children:[n.jsx(xn,{asChild:!0,children:n.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 text-left hover:text-primary transition-colors min-w-0",children:[n.jsx(a,{className:"size-3 text-muted-foreground shrink-0"}),n.jsx("span",{className:"font-mono text-xs truncate",children:l})]})}),n.jsxs(bn,{side:"bottom",align:"start",className:"w-[420px] max-h-[320px] p-0",children:[n.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 border-b border-border bg-muted/30",children:[n.jsx(a,{className:"size-3.5 text-muted-foreground"}),n.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:Fc[i]}),n.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:[o.length," chars"]})]}),n.jsx("pre",{className:"p-3 text-xs font-mono overflow-auto max-h-[280px] whitespace-pre-wrap break-all",children:_c(o,i)})]})]}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(w.Expand,{className:"size-3"})})]}):n.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[n.jsx(a,{className:"size-3 text-muted-foreground shrink-0"}),n.jsx("span",{className:"font-mono text-xs",children:o}),r&&n.jsx("button",{type:"button",className:"shrink-0 opacity-40 hover:opacity-100 transition-opacity",onClick:m=>{m.stopPropagation(),r()},"aria-label":"Expand content",children:n.jsx(w.Expand,{className:"size-3"})})]})}const zo="gb",Or="gs",Do=/^[_A-Za-z][_0-9A-Za-z]*$/;function Mo(e,t){return!e||!t?null:t.columns.find(r=>r.name===e||r.graphQlName===e)??null}const en={field:"key",desc:!1};function Pc(e,t){if(!e||!t)return null;const r=Mo(e,t);return r&&/^(byte|short|int|long|float|double|decimal|numeric|money|real)/i.test(r.paramType.replace(/[![\]]/g,""))?r:null}function Io(e,t,r){const s=new URLSearchParams(e);return r?s.set(t,r):s.delete(t),s}function zc(e){const t=new URLSearchParams(e);return t.delete(zo),t.delete(Or),t}function Lo(e,t,r){const s=[];try{const o=JSON.parse(r);if(Array.isArray(o)&&o.length===4){const[i,a,l,c]=o,m=typeof i=="string"?t.columns.find(d=>d.name===i):void 0;m&&c===m.paramType&&typeof a=="string"&&pn(m.paramType).includes(a)&&s.push({[m.graphQlName]:{[a]:a==="_null"?!!l:l}})}}catch{}for(const o of e){const i=o.value,a=t.columns.find(l=>l.name===o.id);!a||!pn(a.paramType).includes(i.operator)||i.operator!=="_null"&&(i.value===void 0||i.value===null||i.value==="")||s.push({[a.graphQlName]:{[i.operator]:i.operator==="_null"?!!i.value:i.value}})}return s.length===0?void 0:s.length===1?s[0]:{and:s}}function Dc(e,t,r,s,o=null,i=en){for(const m of[e.name,e.graphQlName,t.graphQlName,...o?[o.graphQlName]:[]])if(!Do.test(m))throw new Error("Invalid schema-derived grouping name.");const a=Lo(r,e,s),l=a?`($filter: ${e.graphQlName}Filter)`:"",c=[a?"filter: $filter":"",`groupBy: [${t.graphQlName}]`].filter(Boolean).join(", ");return{query:`query GridGrouping${l} { ${e.name}Aggregate(${c}) { ${t.graphQlName} _count${o?` _sum { ${o.graphQlName} }`:""} } }`,variables:a?{filter:a}:{},groupBy:t,sumBy:o,sort:i}}function Oo(e,t){return e.value===t.value?0:e.value===null||e.value===void 0?-1:t.value===null||t.value===void 0?1:typeof e.value=="number"&&typeof t.value=="number"?e.value-t.value:String(e.value).localeCompare(String(t.value))}function Mc(e,t,r=en){if(r.field==="count"){const o=e.count-t.count;return o!==0?r.desc?-o:o:Oo(e,t)}const s=Oo(e,t);return r.desc?-s:s}function Ic(e,t,r,s,o=en){const i=e?.[`${t.name}Aggregate`];return Array.isArray(i)?i.map(a=>{const l=a;return{value:l[r.graphQlName],count:Number(l._count??0),sum:s?l._sum?.[s.graphQlName]:void 0}}).sort((a,l)=>Mc(a,l,o)):[]}function Lc(e,t,r,s,o,i=[]){for(const d of[e.name,e.graphQlName,t.graphQlName,...e.columns.map(p=>p.graphQlName)])if(!Do.test(d))throw new Error("Invalid schema-derived grouping name.");const a=Lo(s,e,o),l={[t.graphQlName]:r==null?{_null:!0}:{_eq:r}},c=a?{and:[a,l]}:l,m=e.columns.map(d=>d.graphQlName).join(" ");return{query:`query GridGroupMembers($filter: ${e.graphQlName}Filter, $sort: [${e.graphQlName}SortEnum!], $limit: Int, $offset: Int) { ${e.name}(filter: $filter sort: $sort limit: $limit offset: $offset) { total offset limit data { ${m} } } }`,variables:{filter:c,sort:[...i],limit:50,offset:0},responseKey:e.name}}function Oc(e,t){return!e||!t?"":(t.primaryKeys?.length??0)<=1?$t([e?.id]):He(e,t,0)}function Ac(e,t){const r=Math.max(0,t-1);return e<0?0:e>r?r:e}function Ao(e,t){return vr(e)===t?e:jr(t)}function qc(e,t){const r=t.fieldName??t.destinationTable;return e[r]?.data??[]}function Vc(e,t){const r=t.fieldName??t.destinationTable;return e[r]}function Bc(e,t){const r=t.fieldName??t.destinationTable,s=e[r];return s?.total??s?.data?.length??0}function vn(e,t,r={}){return{sortField:e.name,paramType:e.paramType,filterOperators:t,column:e,...r}}function Gc(e,t,r,s,o,i){const a=s.findTable(t.destinationTable),l=a?.labelColumn??"id",c=Gt(t),m=t.destinationTable===r.name,d=m?`Parent ${e.label}`:e.label;return{id:e.name,accessorKey:e.name,header:({column:p,table:f})=>n.jsx(yn,{column:p,table:f,title:d}),enableSorting:!0,meta:vn(e,o,{joinTable:t.destinationTable,joinLabelColumn:l,joinFkColumn:t.destinationColumnNames[0],isSelfReference:m,isCompositeFk:c}),cell:({row:p})=>{const f=Vc(p.original,t);if(!f)return n.jsx(Zt,{kind:"null"});const x=Oc(f,a);return x?n.jsxs("span",{className:"group/fk inline-flex items-center gap-0.5",children:[n.jsx($c,{tableName:t.destinationTable,fkValue:x,filterColumn:t.destinationColumnNames[0],join:t,sourceRow:p.original,children:n.jsx(Pn,{to:"/"+a?.name+"/"+x,className:"text-primary hover:text-primary/80 hover:underline",children:f?.label})}),i&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"opacity-0 group-hover/fk:opacity-100 size-5 shrink-0",onClick:h=>{h.stopPropagation(),i({tableName:t.destinationTable,filterId:x})},"aria-label":"Open in side column",title:"Open in side column",children:n.jsx(w.PanelRight,{className:"size-3"})})]}):n.jsx(n.Fragment,{children:f?.label})}}}function Kc(e,t,r,s,o,i){if(t){const c=s.findTable(t.destinationTable)?.labelColumn??"id",m=t.destinationTable===r.name;return{id:e.name,accessorFn:d=>e.name?String(d?.[e.name]??""):"",cell:({row:d})=>Wn(d.original[e.name],e),header:({column:d,table:p})=>n.jsx(yn,{column:d,table:p,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType,joinTable:t.destinationTable,joinLabelColumn:c,joinFkColumn:Ri(t,e.name),isSelfReference:m,isCompositeFk:!0,isCompositeFkMember:!0})}}return e?.paramType==="DateTime"?{id:e.name,accessorFn:l=>go(l?.[e.name]),cell:({row:l})=>{const c=l.original[e.name];return c==null||c===""?n.jsx(Zt,{kind:c===""?"empty":"null"}):go(c)},header:({column:l,table:c})=>n.jsx(yn,{column:l,table:c,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType})}:_t(e)||Ft(e)?{id:e.name,accessorFn:l=>e.name?String(l?.[e.name]??""):"",header:({column:l,table:c})=>n.jsx(yn,{column:l,table:c,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType}),cell:({row:l})=>n.jsx(Po,{value:l.original[e.name],dbType:e.dbType,deferred:_t(e),onExpand:i?()=>i(l.index,e.name):void 0})}:{id:e.name,accessorFn:l=>e.name?String(l?.[e.name]??""):"",cell:({row:l})=>{const c=l.original[e.name];if(typeof c=="string"&&c.length>1){const m=Gn(c);if(m==="json"||m==="xml"||m==="php-serialized")return n.jsx(Po,{value:c,dbType:e.dbType,onExpand:i?()=>i(l.index,e.name):void 0})}return Wn(c,e)},header:({column:l,table:c})=>n.jsx(yn,{column:l,table:c,title:e.label}),enableSorting:!0,meta:vn(e,o,{dbType:e.dbType})}}const Wc=(e,t,r,s)=>{if(!e||!t)return[];const o=e.columns.map(a=>{const l=e.singleJoins.find(d=>d.sourceColumnNames?.[0]===a.name),c=l?void 0:e.singleJoins.find(d=>(d.sourceColumnNames??[]).includes(a.name)),m=pn(a.paramType);return l?Gc(a,l,e,t,m,s):Kc(a,c,e,t,m,r)}),i=e.multiJoins.map(a=>{const l=t.findTable(a.destinationTable),c=l?.labelColumn??"id",d=a.destinationTable===e.name?`Child ${l?.label??a.destinationTable}`:l?.label??a.destinationTable;return{id:`join_${a.fieldName??a.destinationTable}`,header:d,enableSorting:!1,enableHiding:!0,cell:({row:p})=>{const f=ml(p.original,e,p.index),x=qc(p.original,a),h=Bc(p.original,a);if(h===0)return n.jsx("span",{className:"text-muted-foreground",children:"—"});const b=x.slice(0,10).map(T=>String(T[c]??"")).filter(Boolean),N=l?.label??a.destinationTable;return n.jsxs("span",{className:"group/fk inline-flex items-center gap-1",children:[n.jsxs(gn,{openDelay:300,closeDelay:100,children:[n.jsx(xn,{asChild:!0,children:n.jsxs(Pn,{to:"/"+l?.name+"/from/"+e.name+"/"+f,className:"inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs font-medium text-primary hover:bg-muted hover:border-primary/40 transition-colors",children:[n.jsx(w.List,{className:"size-3"}),h]})}),n.jsxs(bn,{align:"start",sideOffset:6,className:"w-auto max-w-xs p-3",children:[n.jsxs("div",{className:"flex items-center gap-2 border-b pb-2 mb-2",children:[n.jsx(w.List,{className:"size-3.5 text-primary"}),n.jsxs("span",{className:"text-xs font-semibold text-foreground",children:[h," ",N]})]}),n.jsxs("ul",{className:"space-y-0.5 text-xs text-foreground",children:[b.map((T,k)=>n.jsx("li",{className:"truncate",children:T},k)),h>10&&n.jsxs("li",{className:"text-muted-foreground italic",children:["… and ",h-10," more"]})]})]})]}),s&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"opacity-40 group-hover/fk:opacity-100 size-5 shrink-0 transition-opacity",onClick:T=>{T.stopPropagation(),s({tableName:a.destinationTable,filterTable:e.name,filterId:f,...Gt(a)?{}:{filterColumn:a.destinationColumnNames[0]}})},"aria-label":"Open in side column",title:"Open in side column",children:n.jsx(w.PanelRight,{className:"size-3"})})]})}}});return[...o,...i]};function Jc(e,t,r,s,o){if(!s&&!o)return wr(e,t);const i=$r(t,r,s,o);return i?wr(e,i.parentTable):wr(e,t)}function Qc(e,t,r,s,o,i){const{search:a}=ps(),l=_n(),c=a.get("filter")??"",m=a.get("cf")??"",d=a.get("gb"),p=a.get("gs"),f=u.useMemo(()=>yr(c).variables,[c]),x=Je(),h=$e(),[b,N]=u.useState([]),[T,k]=u.useState(en),[E,y]=u.useState(()=>jr(m)),[v,j]=u.useState(0),[S,C]=u.useState(50),B=u.useRef(e);e&&e!==B.current&&(B.current=e,b.length>0&&N([]),T!==en&&k(en),v!==0&&j(0)),u.useEffect(()=>{y(W=>Ao(W,m))},[m]);const $=u.useMemo(()=>Ao(E,m),[E,m]),L=u.useRef(e?.name),q=L.current!==e?.name;q&&(L.current=e?.name);const D=u.useMemo(()=>q?null:Mo(d,e),[q,d,e]),V=u.useMemo(()=>q?null:Pc(p,e),[q,p,e]);u.useEffect(()=>{if(!q||!d)return;const me=zc(a).toString();l(me?`?${me}`:"?")},[q,d,a,l]);const X=u.useMemo(()=>{if(!e)return"id";const W=zt(e)[0]?.name;if(W&&e.columns.some(ve=>ve.name===W))return W;const me=xl(e,ve=>!_t(ve)&&!Ft(ve));return me||(e.columns.find(ve=>!_t(ve)&&!Ft(ve))?.name??e.columns.at(0)?.name??"id")},[e]),F=u.useMemo(()=>{if(b.length>0&&e){const W=b[0];if(e.columns.some(Ne=>Ne.name===W.id))return[`${W.id}_${W.desc?"desc":"asc"}`]}return e?[`${X}_asc`]:[]},[b,e,X]),P=u.useMemo(()=>Sr(e,x,c,$,t,r,s),[e,x,c,$,t,r,s]),A=u.useMemo(()=>e?Kn($,e).variables:{},[$,e]),U=u.useMemo(()=>{if(!e)return null;const W=lo(e,c,$);return W.length===0?null:new Error(`These rows can't be shown because the filter can't be applied: ${W.join(" ")}`)},[e,c,$]),_=v*S,ce=u.useMemo(()=>({sort:F,limit:S,offset:_,...t&&e?Jc(t,e,x,r,s):{},...f,...A}),[F,S,_,t,e,x,r,s,f,A]),{isLoading:he,isFetching:Ue,error:Pe,data:ie}=de.useQuery({queryKey:["tableData",e?.name,P,ce],queryFn:({signal:W})=>h.query(P,ce,{signal:W}),enabled:!!P&&!!e&&F.length>0,placeholderData:(W,me)=>me?.queryKey?.[1]===e?.name?W:void 0}),se=u.useMemo(()=>e&&D?Dc(e,D,$,c,V,T):null,[e,D,V,$,c,T]),ke=de.useQuery({queryKey:["tableGrouping",e?.name,se?.query,se?.variables],queryFn:({signal:W})=>h.query(se.query,se.variables,{signal:W}),enabled:se!==null,placeholderData:void 0}),Ae=u.useMemo(()=>e?Wc(e,x,o,i):[],[e,x,o,i]),re=u.useMemo(()=>t&&(r||s)&&e?$r(e,x,r,s):null,[t,r,s,e,x]);let Ee,Ie;if(re&&!Tr(re.childJoin)){const W=fo(ie,re.parentTable.name,re.childField);Ee=W.data,Ie=W.total}else{const W=ie?.[e?.name??""];Ee=W?.data??[],Ie=W?.total??0}const Le=Math.max(1,Math.ceil(Ie/S));u.useEffect(()=>{const W=Ac(v,Le);W!==v&&j(W)},[v,Le]);const Ge=u.useCallback(W=>{const me=new URLSearchParams(a),Ne=vr(W);Ne?me.set("cf",Ne):me.delete("cf");const ve=me.toString();l(ve?`?${ve}`:"?")},[a,l]),Oe=u.useCallback(W=>{N(W),j(0)},[]),ye=u.useCallback(W=>{y(W),j(0),Ge(W)},[Ge]),ze=u.useCallback(W=>{j(W)},[]),O=u.useCallback(W=>{C(W),j(0)},[]),Z=u.useCallback(W=>{const me=Io(a,zo,W);W||me.delete(Or);const Ne=me.toString();l(Ne?`?${Ne}`:"?")},[a,l]),ee=u.useCallback(W=>{const Ne=Io(a,Or,W).toString();l(Ne?`?${Ne}`:"?")},[a,l]),Ce=e?.primaryKeys??[],xe=u.useMemo(()=>e?Sr(e,x,c,$,t,r,s,{fields:"export"}):null,[e,x,c,$,t,r,s]),qe=u.useCallback(async W=>{if(!xe||!e)return null;const me=kr(e),Ne=me.map(rt=>rt.label),ve=me.map(rt=>rt.name);return _r({headers:Ne,format:W.format,signal:W.signal,onProgress:W.onProgress,rowCap:W.rowCap,csv:{bom:!0},fetchPage:async(rt,Mt)=>{const be={...ce,limit:Mt,offset:rt},ft=await h.query(xe,be,{signal:W.signal});let Nt,Ye;if(re&&!Tr(re.childJoin)){const Xe=fo(ft,re.parentTable.name,re.childField);Nt=Xe.data,Ye=Xe.total}else{const Xe=ft?.[e.name];Nt=Xe?.data??[],Ye=Xe?.total??0}return{rows:Nt.map(Xe=>ve.map(Qt=>Xe[Qt])),total:Ye}}})},[xe,e,ce,h,re]);return{columns:Ae,sorting:b,columnFilters:E,primaryKeys:Ce,pageIndex:v,pageSize:S,pageCount:Le,rows:Ee,totalRows:Ie,grouping:se?{column:se.groupBy,sumColumn:se.sumBy,rows:Ic(ke.data,e,se.groupBy,se.sumBy,se.sort),loading:ke.isLoading,error:ke.error,sort:se.sort,onSortChange:k,memberRequest:W=>Lc(e,se.groupBy,W,$,c,F)}:null,exportRows:qe,loading:he,fetching:Ue&&!he,error:U??Pe,onSortingChange:Oe,onColumnFiltersChange:ye,onPageIndexChange:ze,onPageSizeChange:O,onGroupingChange:Z,onGroupingSumChange:ee}}const Hc=new Set(["tableData","editRecord","tableRowCounts","m2mRows","fkPreview"]),Uc=new Set(["tableRef","tableRefValue","compositeTableRef","m2mTargets"]);function jn(e,t){return e.invalidateQueries({predicate:r=>{const[s,o]=r.queryKey;return typeof s!="string"?!1:Hc.has(s)?!0:Uc.has(s)?o===t:!1}})}function Yc(e){return typeof e=="object"&&e!==null}function qo(e,t){if(e==null)return null;if(!t)return e;const r=ut(t);if(Bt(t))return String(e);if(qt(t)){const s=typeof e=="number"?e:Number(e);return Number.isFinite(s)?Math.trunc(s):e}if(r==="Float"){const s=typeof e=="number"?e:Number(e);return Number.isFinite(s)?s:e}return r==="Boolean"?typeof e=="boolean"?e:e==="true"||e===1:String(e)}function Hn(e){je(e.name,"delete mutation table name");const t=$e(),r=de.useQueryClient(),{toast:s}=vt(),o=u.useMemo(()=>{const h=new Map;for(const b of e.columns)h.set(b.name,b.paramType);return h},[e]),i=u.useMemo(()=>e.primaryKeys??[],[e]),a=h=>{if(i.length===0)throw new Error(`Cannot delete from '${e.name}': the table has no primary key.`);const b={};if(Yc(h)){for(const T of i){const k=h[T];if(k==null)throw new Error(`Cannot delete row: missing value for primary-key column '${T}'.`);b[T]=qo(k,o.get(T))}return b}if(i.length!==1)throw new Error(`Cannot delete from '${e.name}': composite primary key requires an object key, not a scalar.`);if(h==null)throw new Error(`Cannot delete row: missing value for primary-key column '${i[0]}'.`);const N=i[0];return b[N]=qo(h,o.get(N)),b},l=u.useMemo(()=>`mutation deleteSingle($detail: Delete_${e.name}){
91
91
  ${e.name}(delete: $detail)
92
92
  }`,[e]),c=u.useMemo(()=>`mutation deleteMany($delta: ${e.name}_delta){
93
93
  ${e.name}(delta: $delta)
94
- }`,[e]),m=de.useMutation({mutationFn:h=>t.query(l,{detail:h}),onSuccess:()=>{jn(r,e.name),s("Row deleted")}}),d=de.useMutation({mutationFn:h=>t.query(c,{delta:{deleted:h}}),onSuccess:(h,y)=>{jn(r,e.name);const N=y.length;s(`${N} ${N===1?"row":"rows"} deleted`)}}),f=h=>{let y;try{y=a(h)}catch(N){return Promise.reject(N)}return m.mutateAsync(y)},p=h=>{let y;try{y=h.map(N=>a(N))}catch(N){return Promise.reject(N)}return d.mutateAsync(y)},x=m.error??d.error;return{deleteRow:f,deleteRows:p,isPending:m.isPending||d.isPending,error:x}}function Yc(e){return(e.inserted?.length??0)+(e.updated?.length??0)+(e.deleted?.length??0)}function qo(e){je(e.name,"delta mutation table name");const t=$e(),r=de.useQueryClient(),{toast:s}=vt(),o=u.useMemo(()=>`mutation saveDelta($delta: ${e.name}_delta){
94
+ }`,[e]),m=de.useMutation({mutationFn:h=>t.query(l,{detail:h}),onSuccess:()=>{jn(r,e.name),s("Row deleted")}}),d=de.useMutation({mutationFn:h=>t.query(c,{delta:{deleted:h}}),onSuccess:(h,b)=>{jn(r,e.name);const N=b.length;s(`${N} ${N===1?"row":"rows"} deleted`)}}),p=h=>{let b;try{b=a(h)}catch(N){return Promise.reject(N)}return m.mutateAsync(b)},f=h=>{let b;try{b=h.map(N=>a(N))}catch(N){return Promise.reject(N)}return d.mutateAsync(b)},x=m.error??d.error;return{deleteRow:p,deleteRows:f,isPending:m.isPending||d.isPending,error:x}}function Rc(e){return(e.inserted?.length??0)+(e.updated?.length??0)+(e.deleted?.length??0)}function Vo(e){je(e.name,"delta mutation table name");const t=$e(),r=de.useQueryClient(),{toast:s}=vt(),o=u.useMemo(()=>`mutation saveDelta($delta: ${e.name}_delta){
95
95
  ${e.name}(delta: $delta)
96
- }`,[e]),i=de.useMutation({mutationFn:a=>t.query(o,{delta:a}),onSuccess:(a,l)=>{jn(r,e.name);const c=Yc(l);s(`${c} ${c===1?"change":"changes"} saved`)}});return{saveDelta:a=>i.mutateAsync(a),isPending:i.isPending,error:i.error}}function Rc(e){return Vt(e.paramType)}function Xc(e){return qt(e.paramType)}const Zc={Int:{min:-2147483648,max:2147483647},Short:{min:-32768,max:32767},Byte:{min:0,max:255}},eu=-(2n**63n),tu=2n**63n-1n;function nu(e){const t=(e.dbType??"").toLowerCase().trim(),r=t.includes("(")?t.slice(0,t.indexOf("(")).trimEnd():t;if(r==="datetimeoffset"||r==="datetime"||r==="datetime2"||r==="smalldatetime"||r.startsWith("timestamp"))return"datetime";if(r==="date")return"date";if(r.startsWith("time"))return"time"}function ru(e){const t=/^[+-]?(\d*)(?:\.\d*)?$/.exec(e.trim());return t?t[1].replace(/^0+/,"").length:void 0}function su(e){return e.startsWith("^")?e:`^(?:${e})$`}function ou(e){if(e!==e.trim()||/\s/.test(e))return!1;const t=e.lastIndexOf("@");if(t<=0||t===e.length-1)return!1;const r=e.slice(t+1);return r.includes(".")&&!r.startsWith(".")&&!r.endsWith(".")}function au(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function qr(e,t,r){const s=e.label;if(r&&(t==null||t===""))return`${s} is required`;if(t==null||t==="")return;if(typeof t=="string"){if(e.pattern){let i;try{i=new RegExp(su(e.pattern))}catch{return`${s} has an invalid validation pattern`}if(!i.test(t))return e.patternMessage||`${s} format is invalid`}if(e.minLength&&t.length<e.minLength)return`${s} must be at least ${e.minLength} characters`;if(e.maxLength&&t.length>e.maxLength)return`${s} must be at most ${e.maxLength} characters`;if(e.inputType==="email"&&!ou(t))return"Invalid email address";if(e.inputType==="url"&&!au(t))return"Invalid URL"}const o=nu(e);if(o&&typeof t=="string"){if(!(o==="time"?/^\d{1,2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(t.trim()):!Number.isNaN(new Date(t).getTime())))return`${s} must be a valid ${o==="datetime"?"date/time":o}`;if(o!=="time"){const a=new Date(t).getTime(),l=typeof e.min=="string"?new Date(e.min).getTime():NaN,c=typeof e.max=="string"?new Date(e.max).getTime():NaN;if(!Number.isNaN(l)&&a<l)return`${s} must be on or after ${e.min}`;if(!Number.isNaN(c)&&a>c)return`${s} must be on or before ${e.max}`}return}if(ut(e.paramType)==="BigInt"&&typeof t=="string"&&t.trim()!==""){const i=t.trim();if(!/^[+-]?\d+$/.test(i))return`${s} must be a whole number`;const a=BigInt(i);return a<eu||a>tu?`${s} is out of range for a 64-bit integer`:void 0}if(e.precision!=null&&(typeof t=="string"||typeof t=="number")){const i=Math.max(e.precision-(e.scale??0),0),a=ru(String(t));if(a!==void 0&&a>i)return`${s} must have at most ${i} digits before the decimal point`}if(Rc(e)){const i=Number(t);if(!Number.isFinite(i))return`${s} must be a number`;if(Xc(e)&&!Number.isInteger(i))return`${s} must be a whole number`;const a=Zc[ut(e.paramType)];if(a&&(i<a.min||i>a.max))return`${s} must be between ${a.min} and ${a.max}`;const l=e.min==null?NaN:Number(e.min),c=e.max==null?NaN:Number(e.max);if(!Number.isNaN(l)&&i<l)return`${s} must be at least ${e.min}`;if(!Number.isNaN(c)&&i>c)return`${s} must be at most ${e.max}`}}function Hn(e,t){const r=[];for(const s of e){const o=t[s.name];if(o==null||o==="")continue;const i=qr(s,o,!1);i&&r.push(i)}return r}const Vo=e=>Vt(e)&&!Bt(e),iu=["Boolean","Boolean!"];function Bo(e,t,r){const s=ut(t),o=qt(t);if(typeof e=="number"){if(Number.isFinite(e)&&(!o||Number.isInteger(e)))return e;throw new Error(`Invalid ${s} value for column '${r}'.`)}const i=String(e).trim();if(!(o?/^[+-]?\d+$/.test(i):/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?$/.test(i)))throw new Error(`Invalid ${s} value for column '${r}'.`);const l=Number(i);if(!Number.isFinite(l))throw new Error(`Invalid ${s} value for column '${r}'.`);return l}function Un(e,t,r,s,o){const i={...e};for(const{column:a}of t){if(i[a.name]===null){i[a.name]=o?void 0:null;continue}if(Vo(a.paramType)){const l=i[a.name];i[a.name]=l==null?void 0:l===""?o?void 0:null:Bo(l,a.paramType,a.name)}if(Bt(a.paramType)){const l=i[a.name];i[a.name]=l==null?void 0:l===""?o?void 0:null:String(l)}if(iu.some(l=>l===a.paramType)){const l=i[a.name];a.isNullable&&l==null?i[a.name]=o?void 0:null:i[a.name]=!!l}if(Ft(a)){const l=i[a.name];if(typeof l=="string"&&l.trim()!=="")try{i[a.name]=JSON.parse(l)}catch{}}}if(!o&&s)for(const a of r){const l=s[a.name];Vo(a.paramType)?i[a.name]=l==null?null:Bo(l,a.paramType,a.name):i[a.name]=l}return i}function lu(e,t,r,s,o){const i=t.map(a=>({column:a}));return s.map(a=>{const l=mt(a,e);if(!l)throw new Error("Cannot bulk edit: a selected row has no resolvable primary key.");const c={};for(const d of t)c[d.name]=a[d.name]??null;Object.assign(c,o);const m=Hn(t,c);if(m.length>0)throw new Error(m.join(" "));return Un(c,i,r,l,!1)})}function cu(e,t,r,s,o){return s.map(i=>{const a=o(i);if(!a||Object.keys(a).length===0)throw new Error("Cannot save: a fetched row carries no staged changes.");const l=mt(i,e);if(!l)throw new Error("Cannot save: an edited row has no resolvable primary key.");const c=t.filter(f=>!f.isNullable||f.name in a),m={};for(const f of c)m[f.name]=i[f.name]??null;Object.assign(m,a);const d=Hn(c,m);if(d.length>0)throw new Error(d.join(" "));return Un(m,c.map(f=>({column:f})),r,l,!1)})}function wn(e,t,r,s){je(e.name,"table mutation table name");const o=$e(),i=de.useQueryClient(),{toast:a}=vt(),l=s===void 0||s==="",c=u.useMemo(()=>`mutation updateSingle($detail: Update_${e.name}){
96
+ }`,[e]),i=de.useMutation({mutationFn:a=>t.query(o,{delta:a}),onSuccess:(a,l)=>{jn(r,e.name);const c=Rc(l);s(`${c} ${c===1?"change":"changes"} saved`)}});return{saveDelta:a=>i.mutateAsync(a),isPending:i.isPending,error:i.error}}function Xc(e){return Vt(e.paramType)}function Zc(e){return qt(e.paramType)}const eu={Int:{min:-2147483648,max:2147483647},Short:{min:-32768,max:32767},Byte:{min:0,max:255}},tu=-(2n**63n),nu=2n**63n-1n;function ru(e){const t=(e.dbType??"").toLowerCase().trim(),r=t.includes("(")?t.slice(0,t.indexOf("(")).trimEnd():t;if(r==="datetimeoffset"||r==="datetime"||r==="datetime2"||r==="smalldatetime"||r.startsWith("timestamp"))return"datetime";if(r==="date")return"date";if(r.startsWith("time"))return"time"}function su(e){const t=/^[+-]?(\d*)(?:\.\d*)?$/.exec(e.trim());return t?t[1].replace(/^0+/,"").length:void 0}function ou(e){return e.startsWith("^")?e:`^(?:${e})$`}function au(e){if(e!==e.trim()||/\s/.test(e))return!1;const t=e.lastIndexOf("@");if(t<=0||t===e.length-1)return!1;const r=e.slice(t+1);return r.includes(".")&&!r.startsWith(".")&&!r.endsWith(".")}function iu(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Ar(e,t,r){const s=e.label;if(r&&(t==null||t===""))return`${s} is required`;if(t==null||t==="")return;if(typeof t=="string"){if(e.pattern){let i;try{i=new RegExp(ou(e.pattern))}catch{return`${s} has an invalid validation pattern`}if(!i.test(t))return e.patternMessage||`${s} format is invalid`}if(e.minLength&&t.length<e.minLength)return`${s} must be at least ${e.minLength} characters`;if(e.maxLength&&t.length>e.maxLength)return`${s} must be at most ${e.maxLength} characters`;if(e.inputType==="email"&&!au(t))return"Invalid email address";if(e.inputType==="url"&&!iu(t))return"Invalid URL"}const o=ru(e);if(o&&typeof t=="string"){if(!(o==="time"?/^\d{1,2}:\d{2}(:\d{2}(\.\d+)?)?$/.test(t.trim()):!Number.isNaN(new Date(t).getTime())))return`${s} must be a valid ${o==="datetime"?"date/time":o}`;if(o!=="time"){const a=new Date(t).getTime(),l=typeof e.min=="string"?new Date(e.min).getTime():NaN,c=typeof e.max=="string"?new Date(e.max).getTime():NaN;if(!Number.isNaN(l)&&a<l)return`${s} must be on or after ${e.min}`;if(!Number.isNaN(c)&&a>c)return`${s} must be on or before ${e.max}`}return}if(ut(e.paramType)==="BigInt"&&typeof t=="string"&&t.trim()!==""){const i=t.trim();if(!/^[+-]?\d+$/.test(i))return`${s} must be a whole number`;const a=BigInt(i);return a<tu||a>nu?`${s} is out of range for a 64-bit integer`:void 0}if(e.precision!=null&&(typeof t=="string"||typeof t=="number")){const i=Math.max(e.precision-(e.scale??0),0),a=su(String(t));if(a!==void 0&&a>i)return`${s} must have at most ${i} digits before the decimal point`}if(Xc(e)){const i=Number(t);if(!Number.isFinite(i))return`${s} must be a number`;if(Zc(e)&&!Number.isInteger(i))return`${s} must be a whole number`;const a=eu[ut(e.paramType)];if(a&&(i<a.min||i>a.max))return`${s} must be between ${a.min} and ${a.max}`;const l=e.min==null?NaN:Number(e.min),c=e.max==null?NaN:Number(e.max);if(!Number.isNaN(l)&&i<l)return`${s} must be at least ${e.min}`;if(!Number.isNaN(c)&&i>c)return`${s} must be at most ${e.max}`}}function Un(e,t){const r=[];for(const s of e){const o=t[s.name];if(o==null||o==="")continue;const i=Ar(s,o,!1);i&&r.push(i)}return r}const Bo=e=>Vt(e)&&!Bt(e),lu=["Boolean","Boolean!"];function Go(e,t,r){const s=ut(t),o=qt(t);if(typeof e=="number"){if(Number.isFinite(e)&&(!o||Number.isInteger(e)))return e;throw new Error(`Invalid ${s} value for column '${r}'.`)}const i=String(e).trim();if(!(o?/^[+-]?\d+$/.test(i):/^[+-]?(?:(?:\d+\.?\d*)|(?:\.\d+))(?:[eE][+-]?\d+)?$/.test(i)))throw new Error(`Invalid ${s} value for column '${r}'.`);const l=Number(i);if(!Number.isFinite(l))throw new Error(`Invalid ${s} value for column '${r}'.`);return l}function Yn(e,t,r,s,o){const i={...e};for(const{column:a}of t){if(i[a.name]===null){i[a.name]=o?void 0:null;continue}if(Bo(a.paramType)){const l=i[a.name];i[a.name]=l==null?void 0:l===""?o?void 0:null:Go(l,a.paramType,a.name)}if(Bt(a.paramType)){const l=i[a.name];i[a.name]=l==null?void 0:l===""?o?void 0:null:String(l)}if(lu.some(l=>l===a.paramType)){const l=i[a.name];a.isNullable&&l==null?i[a.name]=o?void 0:null:i[a.name]=!!l}if(Ft(a)){const l=i[a.name];if(typeof l=="string"&&l.trim()!=="")try{i[a.name]=JSON.parse(l)}catch{}}}if(!o&&s)for(const a of r){const l=s[a.name];Bo(a.paramType)?i[a.name]=l==null?null:Go(l,a.paramType,a.name):i[a.name]=l}return i}function cu(e,t,r,s,o){const i=t.map(a=>({column:a}));return s.map(a=>{const l=mt(a,e);if(!l)throw new Error("Cannot bulk edit: a selected row has no resolvable primary key.");const c={};for(const d of t)c[d.name]=a[d.name]??null;Object.assign(c,o);const m=Un(t,c);if(m.length>0)throw new Error(m.join(" "));return Yn(c,i,r,l,!1)})}function uu(e,t,r,s,o){return s.map(i=>{const a=o(i);if(!a||Object.keys(a).length===0)throw new Error("Cannot save: a fetched row carries no staged changes.");const l=mt(i,e);if(!l)throw new Error("Cannot save: an edited row has no resolvable primary key.");const c=t.filter(p=>!p.isNullable||p.name in a),m={};for(const p of c)m[p.name]=i[p.name]??null;Object.assign(m,a);const d=Un(c,m);if(d.length>0)throw new Error(d.join(" "));return Yn(m,c.map(p=>({column:p})),r,l,!1)})}function wn(e,t,r,s){je(e.name,"table mutation table name");const o=$e(),i=de.useQueryClient(),{toast:a}=vt(),l=s===void 0||s==="",c=u.useMemo(()=>`mutation updateSingle($detail: Update_${e.name}){
97
97
  ${e.name}(update: $detail)
98
98
  }`,[e]),m=u.useMemo(()=>`mutation insertSingle($detail: Insert_${e.name}){
99
99
  ${e.name}(insert: $detail)
100
- }`,[e]),d=de.useMutation({mutationFn:$=>o.query(c,{detail:$}),onSuccess:()=>{jn(i,e.name),a(`${e.label??e.name} saved`)}}),f=de.useMutation({mutationFn:$=>o.query(m,{detail:$}),onSuccess:()=>{jn(i,e.name),a(`${e.label??e.name} created`)}}),p=u.useMemo(()=>l||!s?null:fn(s,e),[l,s,e]),[x,h]=u.useState(null),y=$=>{const b=$ instanceof Error?$:new Error(String($));return h(b),Promise.reject(b)},N=$=>{if(h(null),!p||r.length===0)return y(new Error(`Cannot update ${e.label??e.name}: the record has no resolvable primary key.`));const b=Hn(t.map(w=>w.column),$);if(b.length>0)return y(new Error(b.join(" ")));let v;try{v=Un($,t,r,p,!1)}catch(w){return y(w)}return d.mutateAsync(v)},T=$=>{h(null);const b=Hn(t.map(w=>w.column),$);if(b.length>0)return y(new Error(b.join(" ")));let v;try{v=Un($,t,r,null,!0)}catch(w){return y(w)}return f.mutateAsync(v)},k=x??d.error??f.error;return{update:N,insert:T,isPending:d.isPending||f.isPending,error:k}}const uu=1e3,du=50;function Go(e){const t=e.labelColumn||zt(e)[0]?.name||e.columns[0]?.name;if(!t)throw new Error(`Table '${e.name}' has no usable label column for a reference dropdown.`);return t}function mu(e,t,r){je(e.name,"reference table name"),je(t,"reference key column");const s=Go(e);if(je(s,"reference label column"),!e.columns.some(d=>d.name===t))throw new Error(`Reference table '${e.name}' has no key column '${t}'.`);const i=e.columns.find(d=>d.name===s)?.paramType?.replace("!","")==="String",a=!!r&&r.trim()!==""&&i,l=a?"$limit: Int, $search: String":"$limit: Int",c=a?`filter: {${s}: {_contains: $search}} `:"";return{query:`query Get_${e.name}_Ref(${l}) {
100
+ }`,[e]),d=de.useMutation({mutationFn:E=>o.query(c,{detail:E}),onSuccess:()=>{jn(i,e.name),a(`${e.label??e.name} saved`)}}),p=de.useMutation({mutationFn:E=>o.query(m,{detail:E}),onSuccess:()=>{jn(i,e.name),a(`${e.label??e.name} created`)}}),f=u.useMemo(()=>l||!s?null:fn(s,e),[l,s,e]),[x,h]=u.useState(null),b=E=>{const y=E instanceof Error?E:new Error(String(E));return h(y),Promise.reject(y)},N=E=>{if(h(null),!f||r.length===0)return b(new Error(`Cannot update ${e.label??e.name}: the record has no resolvable primary key.`));const y=Un(t.map(j=>j.column),E);if(y.length>0)return b(new Error(y.join(" ")));let v;try{v=Yn(E,t,r,f,!1)}catch(j){return b(j)}return d.mutateAsync(v)},T=E=>{h(null);const y=Un(t.map(j=>j.column),E);if(y.length>0)return b(new Error(y.join(" ")));let v;try{v=Yn(E,t,r,null,!0)}catch(j){return b(j)}return p.mutateAsync(v)},k=x??d.error??p.error;return{update:N,insert:T,isPending:d.isPending||p.isPending,error:k}}const du=1e3,mu=50;function Ko(e){const t=e.labelColumn||zt(e)[0]?.name||e.columns[0]?.name;if(!t)throw new Error(`Table '${e.name}' has no usable label column for a reference dropdown.`);return t}function fu(e,t,r){je(e.name,"reference table name"),je(t,"reference key column");const s=Ko(e);if(je(s,"reference label column"),!e.columns.some(d=>d.name===t))throw new Error(`Reference table '${e.name}' has no key column '${t}'.`);const i=e.columns.find(d=>d.name===s)?.paramType?.replace("!","")==="String",a=!!r&&r.trim()!==""&&i,l=a?"$limit: Int, $search: String":"$limit: Int",c=a?`filter: {${s}: {_contains: $search}} `:"";return{query:`query Get_${e.name}_Ref(${l}) {
101
101
  values: ${e.name}(${c}limit: $limit sort: [${s}_asc]) {
102
102
  data {
103
103
  key: ${t}
104
104
  label: ${s}
105
105
  }
106
106
  }
107
- }`,labelColumn:s,serverSearch:i}}function fu(e,t){je(e.name,"reference table name"),je(t,"reference key column");const r=Go(e);je(r,"reference label column");const s=e.columns.find(a=>a.name===t);if(!s)throw new Error(`Reference table '${e.name}' has no key column '${t}'.`);const o=s.paramType.replace("!","");return{query:`query Get_${e.name}_RefValue($key: ${o}) {
107
+ }`,labelColumn:s,serverSearch:i}}function pu(e,t){je(e.name,"reference table name"),je(t,"reference key column");const r=Ko(e);je(r,"reference label column");const s=e.columns.find(a=>a.name===t);if(!s)throw new Error(`Reference table '${e.name}' has no key column '${t}'.`);const o=s.paramType.replace("!","");return{query:`query Get_${e.name}_RefValue($key: ${o}) {
108
108
  values: ${e.name}(filter: {${t}: {_eq: $key}} limit: 1) {
109
109
  data {
110
110
  key: ${t}
111
111
  label: ${r}
112
112
  }
113
113
  }
114
- }`,keyType:o}}function pu(e,t){return dt(t,e)}function Ko(e,t){return e?.data?.find(r=>r.graphQlName===t)}function hu(e,t,r,s="",o=!0){const i=$e(),a=u.useMemo(()=>Ko(e,t),[e,t]),l=s.trim(),c=u.useMemo(()=>e.loading||e.error||!a?null:mu(a,r,l),[r,a,e.loading,e.error,l]),m=c?.serverSearch?l:"",{isLoading:d,error:f,data:p}=de.useQuery({queryKey:["tableRef",t,r,m],queryFn:({signal:x})=>i.query(c.query,m?{limit:du,search:m}:{limit:uu},{signal:x}),enabled:!!c&&o});return{loading:d||e.loading,error:f||e.error,data:p?.values?.data??[],serverSearch:c?.serverSearch??!1}}function gu(e,t,r,s){const o=$e(),i=u.useMemo(()=>Ko(e,t),[e,t]),a=!e.loading&&!e.error&&!!i&&s!=null&&s!=="",l=u.useMemo(()=>a?fu(i,r):null,[a,i,r]),{isLoading:c,error:m,data:d}=de.useQuery({queryKey:["tableRefValue",t,r,String(s??"")],queryFn:({signal:f})=>o.query(l.query,{key:pu(l.keyType,s)},{signal:f}),enabled:!!l});return{loading:c,error:m||e.error,value:d?.values?.data?.at(0)??null}}const xu=500,bu=50;function yu(e,t,r,s={}){const o=$e(),{search:i="",enabled:a=!0,currentValues:l=null}=s,c=i.trim(),m=u.useMemo(()=>e?.data?.find(S=>S.graphQlName===t),[e,t]),d=u.useMemo(()=>m?.labelColumn||r[0],[m,r]),f=u.useMemo(()=>m?.columns.find(L=>L.name===d)?.paramType?.replace("!","")==="String",[m,d]),p=u.useMemo(()=>{if(!m||r.length===0||!it(t)||!it(d))return!1;const S=new Set(m.columns.map(L=>L.name));return S.has(d)?r.every(L=>it(L)&&S.has(L)):!1},[m,t,r,d]),x=u.useMemo(()=>{if(!m||!p)return"";const S=new Set(r);return S.add(d),Array.from(S).join(" ")},[m,p,r,d]),h=!!c&&f,y=u.useMemo(()=>{if(e.loading||e.error||!m||r.length===0||!p)return null;const S=h?"($limit: Int, $search: String)":"($limit: Int)",L=h?`filter: {${d}: {_contains: $search}} `:"";return`query Get_${t}_CompositeRef${S} { values: ${t}(${L}limit: $limit sort: [${d}_asc]) { data { ${x} } } }`},[m,t,x,d,h,e.loading,e.error,r.length,p]),N=f?c:"",{isLoading:T,error:k,data:$}=de.useQuery({queryKey:["compositeTableRef",t,r.join("|"),N],queryFn:()=>o.query(y,N?{limit:bu,search:N}:{limit:xu}),enabled:!!y&&a}),b=u.useMemo(()=>{if(!m||!$)return[];const S={primaryKeys:r};return($.values?.data??[]).map((L,A)=>{const D={};for(const X of r)D[X]=L[X];const B=He(L,S,A);return{route:B,values:D,label:String(L[d]??B)}})},[m,r,d,$]),v=u.useMemo(()=>{if(!l)return"";const S=[];for(const L of r){const A=l[L];if(A==null||A==="")return"";S.push(A)}return $t(S)},[l,r]),w=v===""||b.some(S=>S.route===v),F=u.useMemo(()=>{if(!m||!p||w||v===""||!l)return null;const S=new Map(m.columns.map(E=>[E.name,E])),L=[],A=[],D={};for(let E=0;E<r.length;E++){const P=r[E],q=mn(S.get(P)),U=`k${E}`;A.push(`$${U}: ${q}`),L.push(`{${P}: {_eq: $${U}}}`),D[U]=dt(l[P],q)}const B=L.length===1?L[0]:`{and: [${L.join(", ")}]}`;return{query:`query Get_${t}_CompositeRefValue(${A.join(", ")}) { values: ${t}(filter: ${B} limit: 1) { data { ${x} } } }`,variables:D}},[m,t,x,r,w,v,l,p]),{data:j}=de.useQuery({queryKey:["compositeTableRefValue",t,v],queryFn:()=>o.query(F.query,F.variables),enabled:!!F}),V=u.useMemo(()=>{const S=j?.values?.data?.[0];if(!S)return b;const L={};for(const D of r)L[D]=S[D];const A=$t(r.map(D=>S[D]));return b.some(D=>D.route===A)?b:[{route:A,values:L,label:String(S[d]??A)},...b]},[b,j,r,d]);return{loading:T||e.loading,error:k||e.error,data:V,serverSearch:f}}const vu=new Set(["DateTime","DateTime!"]);function Yn(e){return vu.has(e.paramType)}function Vr(e){return ho(e)==="datetime"}function Br(e,t){if(!e)return"";const r=e.match(/^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}(?::\d{2})?))?/);if(!r||r[1]==="0001-01-01")return"";if(!t||!r[2])return r[1];const s=r[2].length===5?`${r[2]}:00`:r[2];return`${r[1]}T${s}`}function ju(e,t,r){const s={...e};for(const o of r){if(!Yn(o))continue;const i=t[o.name];typeof i!="string"||i===""||Br(i,Vr(o))===s[o.name]&&(s[o.name]=i)}return s}function Wo(e,t,r){const s=e;return String(s.label??s[t]??"").toLowerCase().includes(r.toLowerCase())}const jt=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Root,{"data-slot":"dialog",...e}));jt.displayName="Dialog";const wu=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Trigger,{"data-slot":"dialog-trigger",...e}));wu.displayName="DialogTrigger";const Jo=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Portal,{"data-slot":"dialog-portal",...e}));Jo.displayName="DialogPortal";const Cu=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Close,{"data-slot":"dialog-close",...e}));Cu.displayName="DialogClose";const Qo=Ve.forwardRef(({className:e,...t},r)=>n.jsx(R.Dialog.Overlay,{ref:r,"data-slot":"dialog-overlay",className:Y("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t}));Qo.displayName="DialogOverlay";const wt=Ve.forwardRef(({className:e,children:t,showCloseButton:r=!0,...s},o)=>n.jsxs(Jo,{"data-slot":"dialog-portal",children:[n.jsx(Qo,{}),n.jsxs(R.Dialog.Content,{ref:o,"data-slot":"dialog-content",className:Y("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...s,children:[t,r&&n.jsxs(R.Dialog.Close,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[n.jsx(C.XIcon,{}),n.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));wt.displayName="DialogContent";const tn=Ve.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,"data-slot":"dialog-header",className:Y("flex flex-col gap-2 text-center sm:text-left",e),...t}));tn.displayName="DialogHeader";const Gr=Ve.forwardRef(({className:e,showCloseButton:t=!1,children:r,...s},o)=>n.jsxs("div",{ref:o,"data-slot":"dialog-footer",className:Y("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...s,children:[r,t&&n.jsx(R.Dialog.Close,{asChild:!0,children:n.jsx(Q,{variant:"outline",children:"Close"})})]}));Gr.displayName="DialogFooter";const Ct=Ve.forwardRef(({className:e,...t},r)=>n.jsx(R.Dialog.Title,{ref:r,"data-slot":"dialog-title",className:Y("text-lg leading-none font-semibold",e),...t}));Ct.displayName="DialogTitle";const Kt=Ve.forwardRef(({className:e,...t},r)=>n.jsx(R.Dialog.Description,{ref:r,"data-slot":"dialog-description",className:Y("text-sm text-muted-foreground",e),...t}));Kt.displayName="DialogDescription";function Cn({className:e,...t}){return n.jsx(R.Checkbox.Root,{"data-slot":"checkbox",className:Y("peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary",e),...t,children:n.jsx(R.Checkbox.Indicator,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none",children:n.jsx(C.CheckIcon,{className:"size-3.5"})})})}function Wt({className:e,...t}){return n.jsx(R.Label.Root,{"data-slot":"label",className:Y("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function Kr({open:e,onOpenChange:t,title:r,description:s,confirmLabel:o="Confirm",cancelLabel:i="Cancel",variant:a="default",isPending:l=!1,onConfirm:c}){return n.jsx(jt,{open:e,onOpenChange:t,children:n.jsxs(wt,{showCloseButton:!1,children:[n.jsxs(tn,{children:[n.jsx(Ct,{children:r}),n.jsx(Kt,{asChild:!0,children:n.jsx("div",{children:s})})]}),n.jsxs(Gr,{children:[n.jsx(Q,{variant:"outline",onClick:()=>t(!1),disabled:l,children:i}),n.jsx(Q,{variant:a==="destructive"?"destructive":"default",onClick:c,disabled:l,children:l?`${o}…`:o})]})]})})}function Nu({name:e,label:t,value:r,dbType:s,onChange:o,onBlur:i,required:a,invalid:l}){const c=Et(s),m=gr(s),d=Bn(r,s),[f,p]=u.useState(null),x=u.useRef(null),h=u.useCallback(()=>{const k=x.current;k&&(k.style.height="auto",k.style.height=Math.min(k.scrollHeight,400)+"px")},[]);if(u.useEffect(h,[r,h]),c)return n.jsx(ku,{name:e,label:t,value:r});if(!m&&d==="text")return null;const y=()=>{if(p(null),d==="json")try{o(JSON.stringify(JSON.parse(r),null,2))}catch{p("Invalid JSON")}else if(d==="xml")try{const k=r.replace(/>\s*</g,`>
114
+ }`,keyType:o}}function hu(e,t){return dt(t,e)}function Wo(e,t){return e?.data?.find(r=>r.graphQlName===t)}function gu(e,t,r,s="",o=!0){const i=$e(),a=u.useMemo(()=>Wo(e,t),[e,t]),l=s.trim(),c=u.useMemo(()=>e.loading||e.error||!a?null:fu(a,r,l),[r,a,e.loading,e.error,l]),m=c?.serverSearch?l:"",{isLoading:d,error:p,data:f}=de.useQuery({queryKey:["tableRef",t,r,m],queryFn:({signal:x})=>i.query(c.query,m?{limit:mu,search:m}:{limit:du},{signal:x}),enabled:!!c&&o});return{loading:d||e.loading,error:p||e.error,data:f?.values?.data??[],serverSearch:c?.serverSearch??!1}}function xu(e,t,r,s){const o=$e(),i=u.useMemo(()=>Wo(e,t),[e,t]),a=!e.loading&&!e.error&&!!i&&s!=null&&s!=="",l=u.useMemo(()=>a?pu(i,r):null,[a,i,r]),{isLoading:c,error:m,data:d}=de.useQuery({queryKey:["tableRefValue",t,r,String(s??"")],queryFn:({signal:p})=>o.query(l.query,{key:hu(l.keyType,s)},{signal:p}),enabled:!!l});return{loading:c,error:m||e.error,value:d?.values?.data?.at(0)??null}}const bu=500,yu=50;function vu(e,t,r,s={}){const o=$e(),{search:i="",enabled:a=!0,currentValues:l=null}=s,c=i.trim(),m=u.useMemo(()=>e?.data?.find($=>$.graphQlName===t),[e,t]),d=u.useMemo(()=>m?.labelColumn||r[0],[m,r]),p=u.useMemo(()=>m?.columns.find(L=>L.name===d)?.paramType?.replace("!","")==="String",[m,d]),f=u.useMemo(()=>{if(!m||r.length===0||!it(t)||!it(d))return!1;const $=new Set(m.columns.map(L=>L.name));return $.has(d)?r.every(L=>it(L)&&$.has(L)):!1},[m,t,r,d]),x=u.useMemo(()=>{if(!m||!f)return"";const $=new Set(r);return $.add(d),Array.from($).join(" ")},[m,f,r,d]),h=!!c&&p,b=u.useMemo(()=>{if(e.loading||e.error||!m||r.length===0||!f)return null;const $=h?"($limit: Int, $search: String)":"($limit: Int)",L=h?`filter: {${d}: {_contains: $search}} `:"";return`query Get_${t}_CompositeRef${$} { values: ${t}(${L}limit: $limit sort: [${d}_asc]) { data { ${x} } } }`},[m,t,x,d,h,e.loading,e.error,r.length,f]),N=p?c:"",{isLoading:T,error:k,data:E}=de.useQuery({queryKey:["compositeTableRef",t,r.join("|"),N],queryFn:()=>o.query(b,N?{limit:yu,search:N}:{limit:bu}),enabled:!!b&&a}),y=u.useMemo(()=>{if(!m||!E)return[];const $={primaryKeys:r};return(E.values?.data??[]).map((L,q)=>{const D={};for(const X of r)D[X]=L[X];const V=He(L,$,q);return{route:V,values:D,label:String(L[d]??V)}})},[m,r,d,E]),v=u.useMemo(()=>{if(!l)return"";const $=[];for(const L of r){const q=l[L];if(q==null||q==="")return"";$.push(q)}return $t($)},[l,r]),j=v===""||y.some($=>$.route===v),S=u.useMemo(()=>{if(!m||!f||j||v===""||!l)return null;const $=new Map(m.columns.map(F=>[F.name,F])),L=[],q=[],D={};for(let F=0;F<r.length;F++){const P=r[F],A=mn($.get(P)),U=`k${F}`;q.push(`$${U}: ${A}`),L.push(`{${P}: {_eq: $${U}}}`),D[U]=dt(l[P],A)}const V=L.length===1?L[0]:`{and: [${L.join(", ")}]}`;return{query:`query Get_${t}_CompositeRefValue(${q.join(", ")}) { values: ${t}(filter: ${V} limit: 1) { data { ${x} } } }`,variables:D}},[m,t,x,r,j,v,l,f]),{data:C}=de.useQuery({queryKey:["compositeTableRefValue",t,v],queryFn:()=>o.query(S.query,S.variables),enabled:!!S}),B=u.useMemo(()=>{const $=C?.values?.data?.[0];if(!$)return y;const L={};for(const D of r)L[D]=$[D];const q=$t(r.map(D=>$[D]));return y.some(D=>D.route===q)?y:[{route:q,values:L,label:String($[d]??q)},...y]},[y,C,r,d]);return{loading:T||e.loading,error:k||e.error,data:B,serverSearch:p}}const ju=new Set(["DateTime","DateTime!"]);function Rn(e){return ju.has(e.paramType)}function qr(e){return po(e)==="datetime"}function Vr(e,t){if(!e)return"";const r=e.match(/^(\d{4}-\d{2}-\d{2})(?:[T ](\d{2}:\d{2}(?::\d{2})?))?/);if(!r||r[1]==="0001-01-01")return"";if(!t||!r[2])return r[1];const s=r[2].length===5?`${r[2]}:00`:r[2];return`${r[1]}T${s}`}function wu(e,t,r){const s={...e};for(const o of r){if(!Rn(o))continue;const i=t[o.name];typeof i!="string"||i===""||Vr(i,qr(o))===s[o.name]&&(s[o.name]=i)}return s}function Jo(e,t,r){const s=e;return String(s.label??s[t]??"").toLowerCase().includes(r.toLowerCase())}const jt=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Root,{"data-slot":"dialog",...e}));jt.displayName="Dialog";const Cu=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Trigger,{"data-slot":"dialog-trigger",...e}));Cu.displayName="DialogTrigger";const Qo=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Portal,{"data-slot":"dialog-portal",...e}));Qo.displayName="DialogPortal";const Nu=Ve.forwardRef(({...e},t)=>n.jsx(R.Dialog.Close,{"data-slot":"dialog-close",...e}));Nu.displayName="DialogClose";const Ho=Ve.forwardRef(({className:e,...t},r)=>n.jsx(R.Dialog.Overlay,{ref:r,"data-slot":"dialog-overlay",className:Y("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t}));Ho.displayName="DialogOverlay";const wt=Ve.forwardRef(({className:e,children:t,showCloseButton:r=!0,...s},o)=>n.jsxs(Qo,{"data-slot":"dialog-portal",children:[n.jsx(Ho,{}),n.jsxs(R.Dialog.Content,{ref:o,"data-slot":"dialog-content",className:Y("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),...s,children:[t,r&&n.jsxs(R.Dialog.Close,{"data-slot":"dialog-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[n.jsx(w.XIcon,{}),n.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));wt.displayName="DialogContent";const tn=Ve.forwardRef(({className:e,...t},r)=>n.jsx("div",{ref:r,"data-slot":"dialog-header",className:Y("flex flex-col gap-2 text-center sm:text-left",e),...t}));tn.displayName="DialogHeader";const Br=Ve.forwardRef(({className:e,showCloseButton:t=!1,children:r,...s},o)=>n.jsxs("div",{ref:o,"data-slot":"dialog-footer",className:Y("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...s,children:[r,t&&n.jsx(R.Dialog.Close,{asChild:!0,children:n.jsx(Q,{variant:"outline",children:"Close"})})]}));Br.displayName="DialogFooter";const Ct=Ve.forwardRef(({className:e,...t},r)=>n.jsx(R.Dialog.Title,{ref:r,"data-slot":"dialog-title",className:Y("text-lg leading-none font-semibold",e),...t}));Ct.displayName="DialogTitle";const Kt=Ve.forwardRef(({className:e,...t},r)=>n.jsx(R.Dialog.Description,{ref:r,"data-slot":"dialog-description",className:Y("text-sm text-muted-foreground",e),...t}));Kt.displayName="DialogDescription";function Cn({className:e,...t}){return n.jsx(R.Checkbox.Root,{"data-slot":"checkbox",className:Y("peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[state=checked]:border-primary data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-[state=checked]:bg-primary",e),...t,children:n.jsx(R.Checkbox.Indicator,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none",children:n.jsx(w.CheckIcon,{className:"size-3.5"})})})}function Wt({className:e,...t}){return n.jsx(R.Label.Root,{"data-slot":"label",className:Y("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}function Gr({open:e,onOpenChange:t,title:r,description:s,confirmLabel:o="Confirm",cancelLabel:i="Cancel",variant:a="default",isPending:l=!1,onConfirm:c}){return n.jsx(jt,{open:e,onOpenChange:t,children:n.jsxs(wt,{showCloseButton:!1,children:[n.jsxs(tn,{children:[n.jsx(Ct,{children:r}),n.jsx(Kt,{asChild:!0,children:n.jsx("div",{children:s})})]}),n.jsxs(Br,{children:[n.jsx(Q,{variant:"outline",onClick:()=>t(!1),disabled:l,children:i}),n.jsx(Q,{variant:a==="destructive"?"destructive":"default",onClick:c,disabled:l,children:l?`${o}…`:o})]})]})})}function ku({name:e,label:t,value:r,dbType:s,onChange:o,onBlur:i,required:a,invalid:l}){const c=Et(s),m=gr(s),d=Gn(r,s),[p,f]=u.useState(null),x=u.useRef(null),h=u.useCallback(()=>{const k=x.current;k&&(k.style.height="auto",k.style.height=Math.min(k.scrollHeight,400)+"px")},[]);if(u.useEffect(h,[r,h]),c)return n.jsx(Su,{name:e,label:t,value:r});if(!m&&d==="text")return null;const b=()=>{if(f(null),d==="json")try{o(JSON.stringify(JSON.parse(r),null,2))}catch{f("Invalid JSON")}else if(d==="xml")try{const k=r.replace(/>\s*</g,`>
115
115
  <`).replace(/(<[^/][^>]*[^/]>)\n/g,`$1
116
- `).trim();o(k)}catch{p("Could not format XML")}},N=()=>{if(p(null),d==="json")try{o(JSON.stringify(JSON.parse(r)))}catch{p("Invalid JSON")}else d==="xml"&&o(r.replace(/\n\s*/g,"").trim())},T=d==="json"||d==="xml";return n.jsxs("div",{className:"grid gap-1",children:[T&&n.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs px-2",onClick:y,children:[n.jsx(C.WrapText,{className:"size-3"}),"Format"]}),n.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs px-2",onClick:N,children:"Minify"})]}),n.jsx("textarea",{ref:x,id:e,value:r,onChange:k=>{o(k.target.value),p(null)},onBlur:i,required:a,"aria-invalid":l,className:Y("flex w-full rounded-md border border-input bg-background px-3 py-2","text-xs font-mono leading-relaxed","ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","disabled:cursor-not-allowed disabled:opacity-50","resize-none min-h-[80px] max-h-[400px]",l&&"border-destructive")}),f&&n.jsx("p",{className:"text-xs text-destructive",children:f})]})}function ku({name:e,label:t,value:r}){const s=r?Math.ceil(r.length*3/4):0,o=s<1024?`${s} bytes`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`,i=r?r.slice(0,256)+(r.length>256?"...":""):"(empty)",a=r?so(r):null;return n.jsxs("div",{className:"grid gap-2",children:[n.jsxs(Wt,{htmlFor:e,className:"flex items-center gap-1.5",children:[n.jsx(C.Binary,{className:"size-3.5 text-muted-foreground"}),t,n.jsxs("span",{className:"text-xs text-muted-foreground font-normal ml-1",children:["(binary, ",o,")"]})]}),a?.kind==="image"?n.jsx("img",{src:oo(r,a.mime),alt:t,className:"max-h-[160px] w-fit rounded-md border border-input"}):n.jsx("div",{className:"rounded-md border border-input bg-muted/30 p-3 max-h-[160px] overflow-auto",children:n.jsx("pre",{className:"text-xs font-mono text-muted-foreground break-all whitespace-pre-wrap",children:i})}),n.jsx("p",{className:"text-xs text-muted-foreground",children:"Binary fields are read-only in this editor."})]})}const Wr=["Boolean","Boolean!"],Dt="__none__";function Ho(e,t){return e==null||e===""?t?Dt:"":String(e)}function Jr(e){return t=>{t!==""&&e(t)}}function Nn(e,t){const r=({value:s})=>qr(e,s,t);return{onSubmit:r,onBlur:r}}function Rn(e,t){const r=e.state.meta.errors.length>0;return{hasError:r,ariaProps:{"aria-invalid":r,"aria-describedby":r?t:void 0}}}function Uo(e){return Et(e.dbType)||gr(e.dbType)||Ft(e)}const Yo={filterText:"",variables:{},params:[]};function Su(e,t){return t!=="none"||(e.enumValues?.length??0)>0}function Tu(e,t){return u.useMemo(()=>{const r=e?.data?.find(l=>l.graphQlName===t),o=r.columns.filter(l=>!l.isReadOnly&&!l.isIdentity).map(l=>{const c=r.singleJoins.find(d=>d.sourceColumnNames[0]===l.graphQlName);if(c)return{column:l,join:c,fkRole:Gt(c)?"anchor-composite":"anchor-single"};const m=r.singleJoins.find(d=>(d.sourceColumnNames??[]).includes(l.graphQlName));return m?{column:l,join:m,fkRole:"member-composite"}:{column:l,fkRole:"none"}}),i=new Map(r.columns.map(l=>[l.name,l])),a=(r.primaryKeys??[]).map(l=>i.get(l)).filter(l=>!!l);return[r,o,a]},[e,t])}function $u(e,t,r){const s=$e(),o=r===void 0||r==="",i=u.useMemo(()=>o?null:fn(r,e),[o,r,e]),a=u.useMemo(()=>o||!i?Yo:qn(i,e)??Yo,[o,i,e]),l=!o&&a.filterText==="",c=u.useMemo(()=>{const N=a.params.length>0?a.params.join(", "):"";return`query GetSingleEdit_${e.name}(${N}){
116
+ `).trim();o(k)}catch{f("Could not format XML")}},N=()=>{if(f(null),d==="json")try{o(JSON.stringify(JSON.parse(r)))}catch{f("Invalid JSON")}else d==="xml"&&o(r.replace(/\n\s*/g,"").trim())},T=d==="json"||d==="xml";return n.jsxs("div",{className:"grid gap-1",children:[T&&n.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs px-2",onClick:b,children:[n.jsx(w.WrapText,{className:"size-3"}),"Format"]}),n.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs px-2",onClick:N,children:"Minify"})]}),n.jsx("textarea",{ref:x,id:e,value:r,onChange:k=>{o(k.target.value),f(null)},onBlur:i,required:a,"aria-invalid":l,className:Y("flex w-full rounded-md border border-input bg-background px-3 py-2","text-xs font-mono leading-relaxed","ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","disabled:cursor-not-allowed disabled:opacity-50","resize-none min-h-[80px] max-h-[400px]",l&&"border-destructive")}),p&&n.jsx("p",{className:"text-xs text-destructive",children:p})]})}function Su({name:e,label:t,value:r}){const s=r?Math.ceil(r.length*3/4):0,o=s<1024?`${s} bytes`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`,i=r?r.slice(0,256)+(r.length>256?"...":""):"(empty)",a=r?ro(r):null;return n.jsxs("div",{className:"grid gap-2",children:[n.jsxs(Wt,{htmlFor:e,className:"flex items-center gap-1.5",children:[n.jsx(w.Binary,{className:"size-3.5 text-muted-foreground"}),t,n.jsxs("span",{className:"text-xs text-muted-foreground font-normal ml-1",children:["(binary, ",o,")"]})]}),a?.kind==="image"?n.jsx("img",{src:so(r,a.mime),alt:t,className:"max-h-[160px] w-fit rounded-md border border-input"}):n.jsx("div",{className:"rounded-md border border-input bg-muted/30 p-3 max-h-[160px] overflow-auto",children:n.jsx("pre",{className:"text-xs font-mono text-muted-foreground break-all whitespace-pre-wrap",children:i})}),n.jsx("p",{className:"text-xs text-muted-foreground",children:"Binary fields are read-only in this editor."})]})}const Kr=["Boolean","Boolean!"],Dt="__none__";function Uo(e,t){return e==null||e===""?t?Dt:"":String(e)}function Wr(e){return t=>{t!==""&&e(t)}}function Nn(e,t){const r=({value:s})=>Ar(e,s,t);return{onSubmit:r,onBlur:r}}function Xn(e,t){const r=e.state.meta.errors.length>0;return{hasError:r,ariaProps:{"aria-invalid":r,"aria-describedby":r?t:void 0}}}function Yo(e){return Et(e.dbType)||gr(e.dbType)||Ft(e)}const Ro={filterText:"",variables:{},params:[]};function Tu(e,t){return t!=="none"||(e.enumValues?.length??0)>0}function $u(e,t){return u.useMemo(()=>{const r=e?.data?.find(l=>l.graphQlName===t);if(!r)throw new Error(`useTable: table '${t}' not found in schema`);const o=r.columns.filter(l=>!l.isReadOnly&&!l.isIdentity).map(l=>{const c=r.singleJoins.find(d=>d.sourceColumnNames[0]===l.graphQlName);if(c)return{column:l,join:c,fkRole:Gt(c)?"anchor-composite":"anchor-single"};const m=r.singleJoins.find(d=>(d.sourceColumnNames??[]).includes(l.graphQlName));return m?{column:l,join:m,fkRole:"member-composite"}:{column:l,fkRole:"none"}}),i=new Map(r.columns.map(l=>[l.name,l])),a=(r.primaryKeys??[]).map(l=>i.get(l)).filter(l=>!!l);return[r,o,a]},[e,t])}function Eu(e,t,r){const s=$e(),o=r===void 0||r==="",i=u.useMemo(()=>o?null:fn(r,e),[o,r,e]),a=u.useMemo(()=>o||!i?Ro:Vn(i,e)??Ro,[o,i,e]),l=!o&&a.filterText==="",c=u.useMemo(()=>{const N=a.params.length>0?a.params.join(", "):"";return`query GetSingleEdit_${e.name}(${N}){
117
117
  value: ${e.name}(filter: ${a.filterText||"{}"}) {
118
118
  data { ${t.map(({column:T})=>T.name).join(" ")} }
119
119
  }
120
- }`},[e,t,a]),{isLoading:m,error:d,data:f}=de.useQuery({queryKey:["editRecord",e.name,r],queryFn:()=>s.query(c,a.variables),enabled:!!e&&!o&&a.filterText!==""}),p=f?.value?.data?.at(0),x=!o&&f!==void 0&&p===void 0,h=u.useMemo(()=>p??{},[p]),y=u.useMemo(()=>{const N={};for(const{column:T,fkRole:k}of t){const $=Su(T,k);if(Yn(T))N[T.name]=Br(h[T.name],Vr(T));else if(Wr.some(b=>b===T.paramType)){const b=h[T.name];N[T.name]=T.isNullable&&b==null?null:!!b}else if(Ft(T)){const b=h[T.name];N[T.name]=b==null?"":JSON.stringify(b,null,2)}else if($){const b=h[T.name];N[T.name]=b??null}else N[T.name]=h[T.name]??""}return N},[h,t]);return{isLoading:m,error:d,value:h,defaultValues:y,pkResolveFailed:l,recordNotFound:x}}function Eu({table:e,schema:t,editId:r,onClose:s}){const o=r===void 0||r==="",[i,a,l]=Tu(t,e),c=i.labelColumn,m=i.label,d=wn(i,a,l,r),{isLoading:f,error:p,value:x,defaultValues:h,pkResolveFailed:y,recordNotFound:N}=$u(i,a,r),T=Tn.useForm({defaultValues:h,onSubmit:async({value:S})=>{const L=ju(S,x,a.map(({column:D})=>D));await(o?d.insert:d.update)(L),s()}}),k=Tn.useStore(T.store,S=>S.isDirty),[$,b]=u.useState(!1),v=()=>{k?b(!0):s()};if(f&&!o)return n.jsx(jt,{open:!0,onOpenChange:S=>{S||s()},children:n.jsxs(wt,{showCloseButton:!1,className:"sm:max-w-2xl",children:[n.jsx(Ct,{className:"sr-only",children:"Loading record"}),n.jsx(Kt,{className:"sr-only",children:"Loading record for editing"}),n.jsxs("div",{className:"flex items-center justify-center gap-2 py-10 text-sm text-muted-foreground",children:[n.jsx(C.LoaderCircle,{className:"size-4 animate-spin"}),"Loading…"]})]})});if(p)return n.jsxs("div",{children:["Error: ",p.message]});if(y||N)return n.jsx(jt,{open:!0,onOpenChange:S=>{S||s()},children:n.jsxs(wt,{showCloseButton:!1,className:"sm:max-w-md",children:[n.jsx(Ct,{className:"text-sm font-semibold",children:"Cannot edit record"}),n.jsxs(Kt,{className:"text-sm text-muted-foreground",children:[y?`This record can't be opened for editing: its key (${r||"empty"}) is missing or malformed for the ${m} table.`:`No ${m} record matches the key ${r}. It may have been deleted or is no longer visible to you.`," ","Return to the grid and try again."]}),n.jsx("div",{className:"flex justify-end",children:n.jsx(Q,{type:"button",size:"sm",onClick:s,children:"Close"})})]})});const w=x?.[c]??r,F=a.filter(({column:S})=>Wr.some(L=>L===S.paramType)),j=a.filter(({column:S})=>Uo(S)),V=a.filter(({column:S})=>!Wr.some(L=>L===S.paramType)&&!Uo(S));return n.jsxs(jt,{open:!0,onOpenChange:S=>{S||v()},children:[n.jsxs(wt,{showCloseButton:!1,className:"sm:max-w-2xl max-h-[90vh] flex flex-col gap-0 p-0 overflow-hidden",children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-border bg-muted/30 shrink-0",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx(Ct,{className:"text-sm font-semibold truncate",children:o?`New ${m}`:`${m} : ${w}`}),n.jsxs(Kt,{className:"sr-only",children:[o?"Create":"Edit"," ",m," record"]})]}),n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:v,"aria-label":"Close",className:"shrink-0 -mr-1",children:n.jsx(C.X,{className:"size-4"})})]}),d.error&&n.jsxs("div",{className:"flex items-center gap-2 px-5 py-2 bg-destructive/10 border-b border-destructive/20 text-destructive text-sm shrink-0",children:[n.jsx(C.AlertCircle,{className:"size-3.5 shrink-0"}),n.jsx("span",{className:"truncate",children:d.error.message})]}),n.jsxs("form",{onSubmit:S=>{S.preventDefault(),S.stopPropagation(),T.handleSubmit().catch(()=>{})},className:"flex flex-col flex-1 min-h-0",children:[n.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[V.length>0&&n.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-3",children:V.map(({column:S,join:L,fkRole:A})=>n.jsx(Pu,{column:S,join:L,fkRole:A,form:T,schema:t},S.name))}),F.length>0&&n.jsx("div",{className:V.length>0?"mt-4 pt-4 border-t border-border":"",children:n.jsx("div",{className:"flex flex-wrap gap-x-6 gap-y-2",children:F.map(({column:S})=>n.jsx(Du,{column:S,form:T},S.name))})}),j.length>0&&n.jsx("div",{className:V.length>0||F.length>0?"mt-4 pt-4 border-t border-border":"",children:n.jsx("div",{className:"grid gap-3",children:j.map(({column:S})=>n.jsx(Mu,{column:S,form:T},S.name))})})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3 border-t border-border bg-muted/30 shrink-0",children:[n.jsx(Q,{type:"button",variant:"outline",size:"sm",onClick:v,children:"Cancel"}),n.jsxs(Q,{type:"submit",size:"sm",disabled:d.isPending,children:[d.isPending?n.jsx(C.LoaderCircle,{className:"size-3.5 animate-spin"}):n.jsx(C.Save,{className:"size-3.5"}),o?"Create":"Save"]})]})]})]}),n.jsx(Kr,{open:$,onOpenChange:b,title:"Discard unsaved changes?",description:n.jsx("p",{children:"You have unsaved changes. Closing now will discard them."}),confirmLabel:"Discard",cancelLabel:"Keep editing",variant:"destructive",onConfirm:()=>{b(!1),s()}})]})}function Xn(){const{table:e,editId:t}=ir(),r=_n();if(!e)return n.jsx("div",{children:"Table missing"});const s=t?"../..":"..";return n.jsx(Ro,{table:e,editId:t??"",onClose:()=>r(s)})}function Ro({table:e,editId:t,onClose:r}){const s=Je();return e?s.loading?n.jsx("div",{children:"Loading..."}):s.error?n.jsxs("div",{children:["Error: ",s.error.message]}):s.findTable(e)?n.jsx(Eu,{table:e,schema:s,editId:t,onClose:r}):n.jsxs("div",{className:"p-4 text-sm text-destructive",children:["Table not found: ",e]}):n.jsx("div",{children:"Table missing"})}function Fu({current:e,max:t}){const r=t-e,s=r<=10&&r>0,o=r<=0;return n.jsx("div",{className:"text-xs text-right mt-0.5","aria-live":"polite",children:n.jsxs("span",{className:o?"text-destructive font-medium":s?"text-amber-500":"text-muted-foreground",children:[e,"/",t]})})}function _u({min:e,max:t,step:r}){if(e===void 0&&t===void 0)return null;let s="";return e!=null&&t!==void 0&&t!==null?s=`Range: ${e} to ${t}`:e!=null?s=`Min: ${e}`:t!=null&&(s=`Max: ${t}`),r!=null&&r!==1&&(s+=` (step: ${r})`),n.jsx("div",{className:"text-xs text-muted-foreground mt-0.5","aria-live":"polite",children:s})}function Pu({column:e,join:t,fkRole:r,form:s,schema:o}){const i=e.name,a=!e.isNullable;if(r==="member-composite")return null;const l=Yn(e),c=Vt(e.paramType),m=e.maxLength&&e.maxLength>0&&!l&&!c;if(e.enumValues&&e.enumValues.length>0)return n.jsx(zu,{column:e,form:s,isRequired:a});if(t&&o)return r==="anchor-composite"?n.jsx(Lu,{column:e,join:t,form:s,schema:o,isRequired:a}):n.jsx(Iu,{column:e,join:t,form:s,schema:o,isRequired:a});const d=Bt(e.paramType),f=e.inputType||(l?Vr(e)?"datetime-local":"date":d?"text":c?"number":"text"),p=d?qt(e.paramType)?"numeric":"decimal":void 0,x=`${i}-error`;return n.jsx(s.Field,{name:i,validators:Nn(e,a),children:h=>{const{ariaProps:y}=Rn(h,x);return n.jsxs("div",{className:"grid gap-1",children:[n.jsxs(Wt,{htmlFor:i,className:"text-xs text-muted-foreground",children:[e.label,a&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),n.jsx(Qe,{id:i,type:f,inputMode:p,value:h.state.value??"",onChange:N=>h.handleChange(N.target.value),onBlur:h.handleBlur,required:a,maxLength:e.maxLength,minLength:e.minLength,min:e.min,max:e.max,step:e.step,pattern:e.pattern,title:e.patternMessage,...y,className:"h-8 text-sm"}),m&&n.jsx(Fu,{current:String(h.state.value??"").length,max:e.maxLength}),c&&(e.min!==void 0||e.max!==void 0)&&n.jsx(_u,{min:e.min,max:e.max,step:e.step}),n.jsx(Zn,{errors:h.state.meta.errors,id:x})]})}})}function zu({column:e,form:t,isRequired:r}){const s=e.name,o=e.enumValues||[],i=e.enumLabels&&e.enumLabels.length===o.length?e.enumLabels:o,a=`${s}-error`;return n.jsx(t.Field,{name:s,validators:Nn(e,r),children:l=>{const{ariaProps:c}=Rn(l,a);return n.jsxs("div",{className:"grid gap-1",children:[n.jsxs(Wt,{htmlFor:s,className:"text-xs text-muted-foreground",children:[e.label,r&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),n.jsxs(Ze,{value:Ho(l.state.value,!r),onValueChange:Jr(m=>l.handleChange(m===Dt?null:m)),children:[n.jsx(tt,{id:s,className:"w-full h-8 text-sm",...c,children:n.jsx(et,{placeholder:`Select ${e.label}`})}),n.jsxs(nt,{children:[!r&&n.jsx(we,{value:Dt,className:"text-muted-foreground",children:"(none)"}),o.map((m,d)=>n.jsx(we,{value:m,children:i[d]||m},m))]})]}),n.jsx(Zn,{errors:l.state.meta.errors,id:a})]})}})}const Qr="true",Xo="false";function Du({column:e,form:t}){const r=e.name;return e.isNullable?n.jsx(t.Field,{name:r,children:s=>{const o=s.state.value,i=o==null?Dt:o?Qr:Xo;return n.jsxs("div",{className:"grid gap-1 min-w-[10rem]",children:[n.jsx(Wt,{htmlFor:r,className:"text-xs text-muted-foreground",children:e.label}),n.jsxs(Ze,{value:i,onValueChange:Jr(a=>s.handleChange(a===Dt?null:a===Qr)),children:[n.jsx(tt,{id:r,className:"w-full h-8 text-sm",children:n.jsx(et,{})}),n.jsxs(nt,{children:[n.jsx(we,{value:Dt,className:"text-muted-foreground",children:"(unset)"}),n.jsx(we,{value:Qr,children:"Yes"}),n.jsx(we,{value:Xo,children:"No"})]})]})]})}}):n.jsx(t.Field,{name:r,children:s=>n.jsxs("label",{htmlFor:r,className:"flex items-center gap-2 cursor-pointer select-none",children:[n.jsx(Cn,{id:r,checked:!!s.state.value,onCheckedChange:o=>s.handleChange(!!o),onBlur:s.handleBlur}),n.jsx("span",{className:"text-sm",children:e.label})]})})}function Mu({column:e,form:t}){const r=e.name,s=!e.isNullable,o=`${r}-error`;return n.jsx(t.Field,{name:r,validators:Nn(e,s),children:i=>{const{hasError:a}=Rn(i,o);return n.jsxs("div",{className:"grid gap-1",children:[n.jsxs(Wt,{htmlFor:r,className:"text-xs text-muted-foreground",children:[e.label,s&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),n.jsx(Nu,{name:r,label:e.label,value:String(i.state.value??""),dbType:e.dbType,onChange:l=>i.handleChange(l),onBlur:i.handleBlur,required:s,invalid:a}),n.jsx(Zn,{errors:i.state.meta.errors,id:o})]})}})}function Zo(){const[e,t]=u.useState(""),[r,s]=u.useState(""),[o,i]=u.useState(!1);return u.useEffect(()=>{const l=setTimeout(()=>s(e),300);return()=>clearTimeout(l)},[e]),{search:e,setSearch:t,debounced:r,open:o,onOpenChange:l=>{i(l),l||(t(""),s(""))}}}function ea({field:e,column:t,isRequired:r,errorId:s,value:o,onValueChange:i,search:a,setSearch:l,onOpenChange:c,loadError:m,composite:d,children:f}){const{ariaProps:p}=Rn(e,s);return n.jsxs("div",{className:d?"grid gap-1 sm:col-span-2":"grid gap-1",children:[n.jsxs(Wt,{htmlFor:t.name,className:"text-xs text-muted-foreground",children:[t.label,r&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"}),d&&n.jsxs("span",{className:"ml-2 px-1 rounded bg-primary/10 text-[10px] font-medium text-primary",children:["composite FK (",d.cols," cols)"]})]}),n.jsxs(Ze,{value:o,onValueChange:Jr(i),onOpenChange:c,children:[n.jsx(tt,{id:t.name,className:"w-full h-8 text-sm",...p,children:n.jsx(et,{placeholder:`Select ${t.label}`})}),n.jsxs(nt,{children:[n.jsx("div",{className:"px-1 pb-1 sticky top-0 bg-popover z-10",children:n.jsx(Qe,{value:a,onChange:x=>l(x.target.value),onKeyDown:x=>{(x.key.length===1||x.key==="Backspace"||x.key==="Delete")&&x.stopPropagation()},placeholder:"Search…",className:"h-7 text-xs"})}),f]})]}),m!=null&&n.jsxs("p",{className:"text-xs text-destructive",role:"alert",children:["Failed to load ",t.label," options: ",String(m?.message??m)]}),n.jsx(Zn,{errors:e.state.meta.errors,id:s})]})}function Iu({column:e,join:t,form:r,schema:s,isRequired:o}){const i=e.name,a=t.destinationColumnNames[0],{search:l,setSearch:c,debounced:m,open:d,onOpenChange:f}=Zo(),p=hu(s,t.destinationTable,a,m,d),x=Tn.useStore(r.store,b=>b.values?.[i]),h=x==null||x===""||p.data.some(b=>String(b.key)===String(x)),y=gu(s,t.destinationTable,a,!p.loading&&!h?x:null),N=`${i}-error`,T=m.trim(),k=p.serverSearch||!T?p.data:p.data.filter(b=>Wo(b,"key",T)),$=x==null||x===""?null:p.data.find(b=>String(b.key)===String(x))??y.value??{key:String(x),label:String(x)};return n.jsx(r.Field,{name:i,validators:Nn(e,o),children:b=>n.jsxs(ea,{field:b,column:e,isRequired:o,errorId:N,value:Ho(b.state.value,!o),onValueChange:v=>b.handleChange(v===Dt?null:v),search:l,setSearch:c,onOpenChange:f,loadError:p.error,children:[!o&&n.jsx(we,{value:Dt,className:"text-muted-foreground",children:"(none)"}),$&&!k.some(v=>String(v.key)===String($.key))&&n.jsx(we,{value:String($.key),children:$.label}),k.map(v=>n.jsx(we,{value:String(v.key),children:v.label},v.key)),k.length===0&&n.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No matches."})]})})}function Lu({column:e,join:t,form:r,schema:s,isRequired:o}){const i=t.sourceColumnNames??[],a=t.destinationColumnNames??[],{search:l,setSearch:c,debounced:m,open:d,onOpenChange:f}=Zo(),p=Tn.useStore(r.store,$=>{const b={};for(let v=0;v<i.length;v++)b[a[v]]=$.values?.[i[v]];return b}),x=yu(s,t.destinationTable,a,{search:m,enabled:d,currentValues:p}),h=u.useMemo(()=>{const $=[];for(let b=0;b<i.length;b++){const v=p[a[b]];if(v==null||v==="")return"";$.push(v)}return $t($)},[p,i,a]),y=m.trim(),N=x.serverSearch||!y?x.data:x.data.filter($=>$.label.toLowerCase().includes(y.toLowerCase())),T=$=>{const b=x.data.find(v=>v.route===$);if(b)for(let v=0;v<i.length;v++){const w=a[v],F=i[v];r.setFieldValue(F,b.values[w])}},k=`${e.name}-error`;return n.jsx(r.Field,{name:e.name,validators:Nn(e,o),children:$=>n.jsxs(ea,{field:$,column:e,isRequired:o,errorId:k,value:h,onValueChange:T,search:l,setSearch:c,onOpenChange:f,loadError:x.error,composite:{cols:i.length},children:[N.map(b=>n.jsx(we,{value:b.route,children:b.label},b.route)),N.length===0&&n.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No matches."})]})})}function Zn({errors:e,id:t}){return e.length===0?null:n.jsx("div",{id:t,role:"alert",children:e.map((r,s)=>n.jsx("p",{className:"text-xs text-destructive",children:String(r)},s))})}const ta=40,na=32;function Ou({className:e,...t}){return n.jsx("div",{"data-slot":"table-container",className:"relative w-full h-full overflow-x-auto",children:n.jsx("table",{"data-slot":"table",className:Y("min-w-full caption-bottom text-sm border-separate border-spacing-0",e),...t})})}function Au({className:e,...t}){return n.jsx("thead",{"data-slot":"table-header",className:Y("[&_tr]:border-b",e),...t})}function qu({className:e,...t}){return n.jsx("tbody",{"data-slot":"table-body",className:Y("[&_tr:last-child]:border-0 [&_tr:nth-child(even)]:bg-muted/25",e),...t})}function er({className:e,style:t,...r}){return n.jsx("tr",{"data-slot":"table-row",className:Y("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),style:{height:ta,...t},...r})}function Vu({className:e,style:t,...r}){return n.jsx("th",{"data-slot":"table-head",className:Y("px-2 text-left align-middle font-medium whitespace-nowrap text-muted-foreground text-xs border-r border-border last:border-r-0 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),style:{height:na,...t},...r})}function Hr({className:e,...t}){return n.jsx("td",{"data-slot":"table-cell",className:Y("px-2 py-1 align-middle whitespace-nowrap text-[13px] overflow-hidden text-ellipsis border-r border-border last:border-r-0 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function Bu({anchorEl:e,onEdit:t,onDelete:r,onMouseEnter:s,onDismiss:o}){const i=u.useRef(null);return u.useEffect(()=>{const a=i.current;return a?((()=>{const c=e.getBoundingClientRect(),m=a.offsetHeight,d=a.offsetWidth;a.style.top=`${c.top+(c.height-m)/2}px`;const f=Math.min(c.right-d-8,window.innerWidth-d-8);a.style.left=`${Math.max(8,f)}px`})(),a.showPopover(),()=>{try{a.hidePopover()}catch{}}):void 0},[e]),u.useEffect(()=>{const a=l=>{const c=i.current;c&&!c.contains(l.target)&&o()};return document.addEventListener("pointerdown",a),()=>document.removeEventListener("pointerdown",a)},[o]),n.jsxs("div",{ref:i,popover:"manual",className:"flex items-center gap-0.5 rounded-md border border-border bg-popover px-1 py-0.5 shadow-md m-0",style:{position:"fixed"},onClick:a=>a.stopPropagation(),onMouseEnter:s,onMouseLeave:o,onFocusCapture:s,onBlur:a=>{a.currentTarget.contains(a.relatedTarget)||o()},children:[t&&n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:t,"aria-label":"Edit row",title:"Edit",className:"size-6",children:n.jsx(C.Pencil,{className:"size-3.5"})}),r&&n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:r,"aria-label":"Delete row",title:"Delete",className:"size-6 text-destructive hover:text-destructive",children:n.jsx(C.Trash2,{className:"size-3.5"})})]})}function Gu({exportRows:e,total:t,tableName:r,rowCap:s=Pr}){const{toast:o}=vt(),[i,a]=u.useState(!1),[l,c]=u.useState(0),m=u.useRef(null);u.useEffect(()=>()=>m.current?.abort(),[]);const d=u.useCallback(async p=>{if(i||t>s&&typeof window<"u"&&!window.confirm(`This export has ${t.toLocaleString()} rows, over the ${s.toLocaleString()} row limit. Only the first ${s.toLocaleString()} rows will be exported. Continue?`))return;const x=new AbortController;m.current=x,a(!0),c(0);try{const h=await e({format:p,signal:x.signal,rowCap:s,onProgress:y=>c(y)});if(!h)return;Mr(h.content,Dr(r,p),zr(p)),h.truncated&&o(`Export truncated at ${h.rowCount.toLocaleString()} rows.`,"error")}catch(h){if(x.signal.aborted)return;o(`Export failed: ${h instanceof Error?h.message:String(h)}`,"error")}finally{a(!1),m.current=null}},[i,t,s,e,r,o]),f=u.useCallback(()=>m.current?.abort(),[]);return i?n.jsxs(Q,{variant:"outline",size:"sm",onClick:f,title:"Cancel export",children:[n.jsx(C.X,{className:"size-3.5"}),"Cancel (",l.toLocaleString(),")"]}):n.jsxs(Ln,{children:[n.jsx(On,{asChild:!0,children:n.jsxs(Q,{variant:"outline",size:"sm",children:[n.jsx(C.Download,{className:"size-3.5"}),"Export",n.jsx(C.ChevronDown,{className:"size-3.5"})]})}),n.jsxs(An,{align:"end",children:[n.jsx(bt,{onClick:()=>{d("csv")},children:"CSV"}),n.jsx(bt,{onClick:()=>{d("json")},children:"JSON"})]})]})}const Ur=60,ra=450,Ku=150,Yr="bifrost-col-sizes:";function sa(e){try{const t=localStorage.getItem(Yr+e);return t?Wu(JSON.parse(t)):{}}catch{return{}}}function Wu(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={};for(const[r,s]of Object.entries(e))typeof s!="number"||!Number.isFinite(s)||(t[r]=Math.min(Math.max(s,Ur),ra));return t}function Rr(e,t){try{Object.keys(t).length===0?localStorage.removeItem(Yr+e):localStorage.setItem(Yr+e,JSON.stringify(t))}catch{}}function Ju(e){const[t,r]=u.useState(()=>e?sa(e):{}),s=u.useRef(null),o=u.useRef(!0);u.useEffect(()=>{const a=s.current;if(a&&a.tableName!==e&&(s.current=null,Rr(a.tableName,a.sizing)),!e)return;if(o.current){o.current=!1;return}s.current={tableName:e,sizing:t};const l=setTimeout(()=>{s.current=null,Rr(e,t)},300);return()=>clearTimeout(l)},[e,t]),u.useEffect(()=>()=>{const a=s.current;a&&Rr(a.tableName,a.sizing)},[]);const i=u.useRef(e);if(e&&e!==i.current){i.current=e,o.current=!0;const a=sa(e);r(a)}return{columnSizing:t,setColumnSizing:r}}const Qu="bifrost-col-visibility:";function Xr(e){return Qu+e}function Zr(e){try{const t=localStorage.getItem(Xr(e));return t?Hu(JSON.parse(t)):null}catch{return null}}function Hu(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;const t={};for(const[r,s]of Object.entries(e))typeof s=="boolean"&&(t[r]=s);return t}function Uu(e,t){try{localStorage.setItem(Xr(e),JSON.stringify(t))}catch{}}function Yu(e){try{localStorage.removeItem(Xr(e))}catch{}}function Ru(e,t){if(!t||t.length===0)return{};const r=new Set(t),s={};for(const o of e)s[o]=r.has(o);return s}function Xu(e,t){const[r,s]=u.useState(()=>(e?Zr(e):null)??t),o=u.useRef(r),i=u.useCallback(d=>{o.current=d,s(d)},[]),a=u.useCallback(d=>{const f=typeof d=="function"?d(o.current):d;i(f),e&&Uu(e,f)},[i,e]),l=u.useCallback(()=>{e&&Yu(e),i(t)},[i,t,e]),c=u.useRef(e);e&&e!==c.current&&(c.current=e,i(Zr(e)??t));const m=u.useRef(t);return e&&m.current!==t&&(m.current=t,Zr(e)===null&&i(t)),{columnVisibility:r,setColumnVisibility:a,resetColumnVisibility:l}}const Zu=500;function ed(){const[e,t]=u.useState(null),r=u.useRef(null),s=u.useCallback((p,x)=>{r.current&&(clearTimeout(r.current),r.current=null),t({rowId:p,el:x})},[]),o=u.useCallback(()=>{r.current&&clearTimeout(r.current),r.current=setTimeout(()=>t(null),150)},[]),i=u.useCallback(()=>{r.current&&(clearTimeout(r.current),r.current=null)},[]),a=u.useRef(null),l=u.useRef(!1),c=u.useRef(!1),m=u.useCallback(()=>{a.current&&(clearTimeout(a.current),a.current=null)},[]),d=u.useCallback((p,x,h)=>{h.pointerType==="touch"&&(l.current=!1,m(),a.current=setTimeout(()=>{l.current||(c.current=!0,s(p,x))},Zu))},[m,s]),f=u.useCallback(()=>{l.current=!0,m()},[m]);return{hoveredRow:e,hoverRow:s,scheduleDismiss:o,cancelDismiss:i,suppressClick:c,startPress:d,onPressMove:f,cancelPress:m}}const es=-1;function td(e){return Math.max(5,Math.floor((e-na)/ta))}function nd(e,t){const[r,s]=u.useState(!0),o=u.useRef(0),i=u.useCallback(()=>{const a=e.current;return a?td(a.clientHeight):10},[e]);return u.useEffect(()=>{if(!r)return;const a=e.current;if(!a)return;const l=()=>{const f=i();f!==o.current&&(o.current=f,t(f))},c=requestAnimationFrame(l);let m=null;const d=new ResizeObserver(()=>{m&&clearTimeout(m),m=setTimeout(()=>requestAnimationFrame(l),200)});return d.observe(a),()=>{cancelAnimationFrame(c),m&&clearTimeout(m),d.disconnect()}},[r,i,t,e]),{fitMode:r,setFitMode:s,computeFitSize:i}}function rd(e){return e.id??("accessorKey"in e?String(e.accessorKey):void 0)}function oa(e,t){return t.map(r=>e.find(s=>rd(s)===r)).filter(r=>r!==void 0)}function sd(e,{leading:t,trailing:r}){const s=t?oa(e,t):[],o=r?oa(e,r):[];if(s.length===0&&o.length===0)return e;const i=new Set([...s,...o]),a=e.filter(l=>!i.has(l));return[...s,...a,...o]}function od({label:e,rows:t,loading:r,error:s,sumLabel:o,pageSize:i,sort:a,onSortChange:l,memberRequest:c}){const m=$e(),[d,f]=u.useState(0),[p,x]=u.useState(null),h=p===null?null:c(p.value),y=de.useQuery({queryKey:["groupMembers",h?.query,h?.variables],queryFn:({signal:v})=>m.query(h.query,h.variables,{signal:v}),enabled:h!==null}),N=t.map(v=>`${String(v.value)}:${v.count}:${String(v.sum)}`).join("|");if(u.useEffect(()=>{f(0),x(null)},[e,N,i]),s)return n.jsxs("p",{role:"alert",className:"px-2 py-1 text-sm text-destructive",children:["Grouping failed: ",s.message]});if(r)return n.jsx("p",{className:"px-2 py-1 text-sm text-muted-foreground",children:"Loading grouped results…"});const T=Math.max(1,i),k=Math.max(1,Math.ceil(t.length/T)),$=t.slice(Math.min(d,k-1)*T,(Math.min(d,k-1)+1)*T),b=h?y.data?.[h.responseKey]:void 0;return n.jsxs("div",{className:"border-b px-2 py-2","aria-label":`Grouped by ${e}`,children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2 text-sm font-medium",children:[n.jsxs("span",{children:["Grouped by ",e]}),n.jsxs("label",{className:"text-xs font-normal text-muted-foreground",children:["Group order",n.jsxs("select",{"aria-label":"Group order",className:"ml-1 rounded border bg-background px-1 py-0.5 text-foreground",value:`${a.field}:${a.desc?"desc":"asc"}`,onChange:v=>{const[w,F]=v.target.value.split(":");l({field:w==="count"?"count":"key",desc:F==="desc"})},children:[n.jsxs("option",{value:"key:asc",children:[e," ascending"]}),n.jsxs("option",{value:"key:desc",children:[e," descending"]}),n.jsx("option",{value:"count:desc",children:"Count high to low"}),n.jsx("option",{value:"count:asc",children:"Count low to high"})]})]}),n.jsxs("span",{className:"text-muted-foreground",children:[t.length," groups"]})]}),n.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto_auto] gap-x-4 gap-y-1 text-sm",children:[$.map((v,w)=>n.jsxs("div",{className:"contents",children:[n.jsx("button",{type:"button",className:"text-left underline-offset-2 hover:underline","aria-expanded":p===v,onClick:()=>x(p===v?null:v),children:v.value===null||v.value===void 0?"(null)":String(v.value)}),n.jsx("span",{className:"tabular-nums text-muted-foreground",children:v.count}),n.jsx("span",{className:"tabular-nums text-muted-foreground",children:o?String(v.sum??"—"):""})]},`${String(v.value)}-${w}`)),t.length===0&&n.jsx("span",{className:"text-muted-foreground",children:"No grouped results."})]}),t.length>T&&n.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs",children:[n.jsx("button",{type:"button",disabled:d===0,onClick:()=>f(v=>v-1),children:"Previous groups"}),n.jsxs("span",{children:["Group page ",Math.min(d,k-1)+1," of ",k]}),n.jsx("button",{type:"button",disabled:d>=k-1,onClick:()=>f(v=>v+1),children:"Next groups"})]}),h&&n.jsx("div",{className:"mt-2 rounded bg-muted/40 p-2 text-xs","aria-live":"polite",children:y.isLoading?"Loading group members…":y.error?"Group member query failed.":n.jsxs(n.Fragment,{children:[n.jsxs("div",{children:[b?.total??0," matching members"]}),n.jsx("pre",{className:"max-h-32 overflow-auto",children:JSON.stringify(b?.data??[],null,2)})]})})]})}const ad=[10,20,30,50,100];function id({columns:e,data:t,tableName:r,pageCount:s,pageIndex:o,pageSize:i,sorting:a,columnFilters:l,loading:c,fetching:m=!1,selectable:d=!1,primaryKeys:f=[],selectedRowId:p,onRowSelect:x,onSortingChange:h,onColumnFiltersChange:y,onPageIndexChange:N,onPageSizeChange:T,onEditRow:k,onDeleteRow:$,onDeleteSelected:b,onBulkEditSelected:v,inlineEditableColumns:w,inlineBooleanColumns:F,pendingEdits:j,onCellCommit:V,onSaveAllEdits:S,onDiscardAllEdits:L,savingEdits:A=!1,stackingEnabled:D,onToggleStacking:B,exportRows:X,totalRows:E,onVisualize:P,groupableColumns:q,grouping:U,onGroupingChange:_,onGroupingSumChange:ce}){const{hoveredRow:he,hoverRow:Ue,scheduleDismiss:Pe,cancelDismiss:ie,suppressClick:se,startPress:ke,onPressMove:Ae,cancelPress:re}=ed(),{defaultColumns:Ee,trailingColumns:Ie}=cr(),[Le,Ge]=u.useState({}),[Oe,ye]=u.useState(null),{columnSizing:ze,setColumnSizing:O}=Ju(r),Z=u.useRef(null),{fitMode:ee,setFitMode:Ce,computeFitSize:xe}=nd(Z,T),qe=u.useCallback(z=>{const H=Z.current;if(!H)return;const I=H.querySelectorAll(`[data-col-id="${z}"]`);let ne=Ur;I.forEach(De=>{const ot=De.scrollWidth+4;ot>ne&&(ne=ot)});const Se=Math.min(ne,ra);O(De=>({...De,[z]:Se}))},[O]),W=u.useCallback(()=>{O({})},[O]);u.useEffect(()=>{Ge({})},[t,o]);const me=u.useMemo(()=>{const z=[];return d&&z.push({id:"_select",header:({table:H})=>n.jsx(Cn,{checked:H.getIsAllPageRowsSelected()||H.getIsSomePageRowsSelected()&&"indeterminate",onCheckedChange:I=>H.toggleAllPageRowsSelected(!!I),"aria-label":"Select all"}),cell:({row:H})=>n.jsx(Cn,{checked:H.getIsSelected(),onCheckedChange:I=>H.toggleSelected(!!I),onClick:I=>I.stopPropagation(),"aria-label":"Select row"}),enableSorting:!1,enableHiding:!1,enableResizing:!1,size:32}),z.push(...sd(e,{leading:r?Ee?.[r]:void 0,trailing:Ie})),z},[e,d,Ee,r,Ie]),Ne=u.useMemo(()=>Ru(me.filter(z=>z.enableHiding!==!1).map(z=>z.id).filter(z=>z!==void 0),r?Ee?.[r]:void 0),[me,Ee,r]),{columnVisibility:ve,setColumnVisibility:rt,resetColumnVisibility:Mt}=Xu(r,Ne),be=$n.useReactTable({data:t,columns:me,pageCount:s,getRowId:(z,H)=>He(z,{primaryKeys:f},H),state:{sorting:a,columnFilters:l,pagination:{pageIndex:o,pageSize:i},columnVisibility:ve,rowSelection:Le,columnSizing:ze},defaultColumn:{minSize:Ur,size:Ku},columnResizeMode:"onChange",enableColumnResizing:!0,onColumnSizingChange:O,meta:{onResetColumnWidths:W},onSortingChange:z=>{const H=typeof z=="function"?z(a):z;h(H)},onPaginationChange:z=>{const I=typeof z=="function"?z({pageIndex:o,pageSize:i}):z;I.pageSize!==i?(T(I.pageSize),N(0)):N(I.pageIndex)},onColumnFiltersChange:z=>{const H=typeof z=="function"?z(l):z;y(H)},onColumnVisibilityChange:rt,onRowSelectionChange:Ge,enableRowSelection:d,getCoreRowModel:$n.getCoreRowModel(),manualSorting:!0,manualFiltering:!0,manualPagination:!0}),ft=Object.keys(Le).length,Nt=be.getVisibleLeafColumns().map(z=>z.id).join("|"),Ye=u.useCallback(()=>{const z=[];for(const H of be.getSelectedRowModel().rows){const I=mt(H.original,{primaryKeys:f});I&&z.push(I)}return z},[be,f]),Xe=u.useCallback(()=>{if(!b)return;const z=Ye();z.length>0&&b(z)},[Ye,b]),Qt=u.useCallback(()=>{if(!v)return;const z=Ye();z.length>0&&v(z)},[Ye,v]),kn=u.useCallback((z,H)=>{ye({rowId:z,columnId:H})},[]),Sn=u.useCallback((z,H,I)=>{ye(null),V?.(z,H,I)},[V]),Ht=u.useCallback(()=>ye(null),[]),pt=u.useCallback(z=>{const H=be.getRow(z);return H?mt(H.original,{primaryKeys:f}):null},[be,f]),It=u.useCallback(z=>{if(!k)return;const H=pt(z);H&&k(H)},[k,pt]),st=u.useCallback(z=>{if(!$)return;const H=pt(z);H&&$(H)},[$,pt]),Ut=u.useCallback(()=>{he&&It(he.rowId)},[he,It]),Lt=u.useCallback(()=>{he&&st(he.rowId)},[he,st]);return n.jsxs("div",{className:"flex flex-col w-full min-h-0 flex-1",children:[n.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[l.length>0&&n.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>be.resetColumnFilters(),title:"Clear all column filters",children:[n.jsx(C.FilterX,{className:"size-3.5"}),"Clear filters"]}),ft>0&&(b||v)&&n.jsxs(n.Fragment,{children:[n.jsxs("span",{className:"text-xs text-muted-foreground",children:[ft," selected"]}),v&&n.jsxs(Q,{variant:"outline",size:"sm",onClick:Qt,title:"Apply one set of field changes to every selected row in one transaction",children:[n.jsx(C.Pencil,{className:"size-3.5"}),"Edit"]}),b&&n.jsxs(Q,{variant:"outline",size:"sm",onClick:Xe,className:"text-destructive hover:text-destructive",children:[n.jsx(C.Trash2,{className:"size-3.5"}),"Delete"]})]}),(j?.size??0)>0&&S&&n.jsxs(n.Fragment,{children:[n.jsxs("span",{className:"text-xs text-amber-600 dark:text-amber-400",children:[j.size," unsaved ",j.size===1?"row":"rows"]}),n.jsx(Q,{size:"sm",onClick:S,disabled:A,children:A?"Saving…":"Save all"}),L&&n.jsx(Q,{variant:"outline",size:"sm",onClick:L,disabled:A,children:"Discard"})]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[P&&n.jsx(Q,{variant:"outline",size:"sm",onClick:P,title:"Open a chart using this table and its active filters",children:"Visualize"}),X&&n.jsx(Gu,{exportRows:X,total:E??0,tableName:r??"export"}),B&&n.jsxs(Q,{variant:D?"secondary":"outline",size:"sm",role:"switch","aria-checked":!!D,onClick:()=>B(!D),title:D?"Stacked drill-down active — click for flat grid":"Flat grid active — click for stacked drill-down",children:[D?n.jsx(C.PanelRight,{className:"size-3.5"}):n.jsx(C.Rows3,{className:"size-3.5"}),D?"Stacked":"Grid"]}),_&&q&&n.jsxs(Ze,{value:U?.column.name??"__none",onValueChange:z=>_(z==="__none"?null:z),children:[n.jsx(tt,{size:"sm",className:"w-40","aria-label":"Group grid by column",children:n.jsx(et,{placeholder:"Group by"})}),n.jsxs(nt,{children:[n.jsx(we,{value:"__none",children:"No grouping"}),q.map(z=>n.jsx(we,{value:z.name,children:z.label},z.name))]})]}),U&&ce&&q&&n.jsxs(Ze,{value:U.sumColumn?.name??"__none",onValueChange:z=>ce(z==="__none"?null:z),children:[n.jsx(tt,{size:"sm",className:"w-40","aria-label":"Group sum column",children:n.jsx(et,{placeholder:"Sum column"})}),n.jsxs(nt,{children:[n.jsx(we,{value:"__none",children:"Count only"}),q.filter(z=>/^(byte|short|int|long|float|double|decimal|numeric|money|real)/i.test(z.paramType.replace(/[!\[\]]/g,""))).map(z=>n.jsxs(we,{value:z.name,children:["Sum ",z.label]},z.name))]})]}),n.jsxs(Ln,{children:[n.jsx(On,{asChild:!0,children:n.jsxs(Q,{variant:"outline",size:"sm",children:[n.jsx(C.Columns3,{className:"size-3.5"}),"Columns",n.jsx(C.ChevronDown,{className:"size-3.5"})]})}),n.jsxs(An,{align:"end",children:[be.getAllColumns().filter(z=>z.getCanHide()).map(z=>{const I=z.columnDef.meta?.column?.label??(typeof z.columnDef.header=="string"?z.columnDef.header:z.id);return n.jsx(Ki,{checked:z.getIsVisible(),onCheckedChange:ne=>z.toggleVisibility(!!ne),children:I},z.id)}),n.jsx(yt,{}),n.jsx(bt,{onClick:Mt,children:"Reset to default columns"})]})]})]})]}),U?n.jsxs(n.Fragment,{children:[n.jsx(od,{label:U.column.label,rows:U.rows,loading:U.loading,error:U.error,sumLabel:U.sumColumn?.label,pageSize:i,sort:U.sort,onSortChange:U.onSortChange,memberRequest:U.memberRequest}),n.jsx("p",{className:"border-b px-2 py-1 text-xs text-muted-foreground",role:"note",children:"Inline editing is disabled while grouping is active; expand a group to inspect its server-filtered members."})]}):n.jsxs(n.Fragment,{children:[m&&n.jsx("div",{className:"relative h-0 z-20",children:n.jsxs("div",{"data-testid":"fetch-indicator",role:"progressbar","aria-label":"Loading page",className:"absolute inset-x-0 top-0 h-0.5 overflow-hidden bg-primary/20",children:[n.jsx("div",{className:"h-full w-1/3 bg-primary",style:{animation:"edit-db-indeterminate 1.2s ease-in-out infinite"}}),n.jsx("style",{children:"@keyframes edit-db-indeterminate { 0% { transform: translateX(-100%); } 100% { transform: translateX(300%); } }"})]})}),n.jsxs("div",{ref:Z,className:"relative flex-1 overflow-auto min-h-0","aria-busy":m||c,children:[n.jsxs(Ou,{style:{tableLayout:"fixed",width:be.getTotalSize()},children:[n.jsx("colgroup",{children:be.getVisibleLeafColumns().map(z=>n.jsx("col",{style:{width:z.getSize()}},z.id))}),n.jsx(Au,{children:be.getHeaderGroups().map(z=>n.jsx(er,{children:z.headers.map(H=>n.jsxs(Vu,{"data-col-id":H.column.id,className:"relative","aria-sort":H.column.getIsSorted()==="asc"?"ascending":H.column.getIsSorted()==="desc"?"descending":H.column.getCanSort()?"none":void 0,children:[H.isPlaceholder?null:$n.flexRender(H.column.columnDef.header,H.getContext()),H.column.getCanResize()&&n.jsx("div",{onMouseDown:H.getResizeHandler(),onTouchStart:H.getResizeHandler(),onDoubleClick:()=>qe(H.column.id),className:`absolute top-0 right-0 w-1 h-full cursor-col-resize select-none touch-none opacity-0 hover:opacity-100 transition-opacity ${H.column.getIsResizing()?"bg-primary opacity-100":"bg-border hover:bg-muted-foreground"}`})]},H.id))},z.id))}),n.jsx(qu,{children:c?n.jsx(er,{children:n.jsx(Hr,{colSpan:me.length,className:"h-24 text-center",children:"Loading..."})}):be.getRowModel().rows.length===0?n.jsx(er,{children:n.jsx(Hr,{colSpan:me.length,className:"h-24 text-center",children:"No results."})}):be.getRowModel().rows.map(z=>n.jsx(cd,{row:z,isSelected:p!=null&&z.id===p,checked:z.getIsSelected(),visibleKey:Nt,pending:j?.get(z.id),editingColumnId:Oe?.rowId===z.id?Oe.columnId:null,inlineEditableColumns:V?w:void 0,inlineBooleanColumns:F,onStartEditCell:V?kn:void 0,onCommitCell:Sn,onCancelEditCell:Ht,onRowSelect:x,onEditRow:k?It:void 0,onDeleteRow:$?st:void 0,suppressClick:se,hoverRow:Ue,scheduleDismiss:Pe,startPress:ke,onPressMove:Ae,cancelPress:re},z.id))})]}),he&&(k||$)&&n.jsx(Bu,{anchorEl:he.el,onEdit:k?Ut:void 0,onDelete:$?Lt:void 0,onMouseEnter:ie,onDismiss:Pe})]}),n.jsxs("div",{className:"flex items-center justify-between px-2 py-1.5 border-t border-border mt-auto shrink-0",children:[n.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[n.jsx("span",{children:"Rows per page"}),n.jsxs(Ze,{value:String(ee?es:i),onValueChange:z=>{const H=Number(z);H===es?(Ce(!0),T(xe())):(Ce(!1),T(H))},children:[n.jsx(tt,{size:"sm",className:"w-auto h-7 text-xs","aria-label":"Rows per page",children:n.jsx(et,{children:ee?"Fit":i})}),n.jsxs(nt,{children:[n.jsx(we,{value:String(es),children:"Fit"}),ad.map(z=>n.jsx(we,{value:String(z),children:z},z))]})]})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsxs("span",{className:"text-xs text-muted-foreground mr-2",children:["Page ",o+1," of ",s||1]}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(0),disabled:o===0,"aria-label":"First page",title:"First page",children:n.jsx(C.ChevronsLeft,{className:"size-4"})}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(o-1),disabled:!be.getCanPreviousPage(),"aria-label":"Previous page",title:"Previous page",children:n.jsx(C.ChevronLeft,{className:"size-4"})}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(o+1),disabled:!be.getCanNextPage(),"aria-label":"Next page",title:"Next page",children:n.jsx(C.ChevronRight,{className:"size-4"})}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(s-1),disabled:o>=s-1,"aria-label":"Last page",title:"Last page",children:n.jsx(C.ChevronsRight,{className:"size-4"})})]})]})]})]})}function ld({row:e,isSelected:t,checked:r,pending:s,editingColumnId:o,inlineEditableColumns:i,inlineBooleanColumns:a,onStartEditCell:l,onCommitCell:c,onCancelEditCell:m,onRowSelect:d,onEditRow:f,onDeleteRow:p,suppressClick:x,hoverRow:h,scheduleDismiss:y,startPress:N,onPressMove:T,cancelPress:k}){const $=!!(d||f||p);return n.jsx(er,{"data-state":t||r?"selected":void 0,className:d?"cursor-pointer group/row focus-visible:outline-2 focus-visible:outline-primary":"group/row focus-visible:outline-2 focus-visible:outline-primary",tabIndex:$?0:void 0,onClick:d?()=>{if(x.current){x.current=!1;return}window.getSelection()?.toString()||d(t?null:e.id)}:void 0,onKeyDown:$?b=>{b.target===b.currentTarget&&((b.key==="Enter"||b.key===" ")&&d?(b.preventDefault(),d(t?null:e.id)):(b.key==="e"||b.key==="E")&&f?(b.preventDefault(),f(e.id)):(b.key==="Delete"||b.key==="Backspace")&&p&&(b.preventDefault(),p(e.id)))}:void 0,onFocus:b=>{b.target===b.currentTarget&&h(e.id,b.currentTarget)},onBlur:b=>{b.currentTarget.contains(b.relatedTarget)||y()},onPointerEnter:b=>{b.pointerType==="mouse"&&h(e.id,b.currentTarget)},onPointerLeave:b=>{b.pointerType==="mouse"&&y()},onPointerDown:b=>N(e.id,b.currentTarget,b),onPointerMove:T,onPointerUp:k,onPointerCancel:k,children:e.getVisibleCells().map(b=>{const v=b.column.id,w=!!l&&!!i?.has(v),F=o===v,j=!!s&&v in s;return n.jsx(Hr,{"data-col-id":v,"data-dirty":j?"true":void 0,className:j?"bg-amber-500/10 border-l-2 border-l-amber-500":void 0,title:w&&!F?"Double-click to edit":void 0,onDoubleClick:w&&!F?()=>l(e.id,v):void 0,children:F&&c&&m?n.jsx(ud,{initialValue:j?s[v]:e.original[v],boolean:!!a?.has(v),onCommit:V=>c(e.id,v,V),onCancel:m}):j?n.jsx("span",{title:"Unsaved change",children:s[v]==null?"":String(s[v])}):$n.flexRender(b.column.columnDef.cell,b.getContext())},b.id)})})}const cd=u.memo(ld);function ud({initialValue:e,boolean:t,onCommit:r,onCancel:s}){const[o,i]=u.useState(e==null?"":String(e));return t?n.jsx("input",{type:"checkbox",autoFocus:!0,defaultChecked:e===!0||e==="true",onChange:a=>r(a.target.checked),onKeyDown:a=>{a.key==="Escape"&&s()},onBlur:s,"aria-label":"Edit cell value"}):n.jsx("input",{autoFocus:!0,className:"w-full bg-background border border-primary rounded px-1 py-0.5 text-sm outline-none",value:o,onChange:a=>i(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),r(o)):a.key==="Escape"&&(a.preventDefault(),s()),a.stopPropagation()},onBlur:()=>r(o),onClick:a=>a.stopPropagation(),onDoubleClick:a=>a.stopPropagation(),"aria-label":"Edit cell value"})}function dd({table:e,pks:t,onClose:r}){const s=$e(),{toast:o}=vt(),i=qo(e),[a,l]=u.useState({}),[c,m]=u.useState(null),[d,f]=u.useState(!1),p=u.useMemo(()=>e.columns.filter(b=>!b.isReadOnly&&!b.isIdentity&&!b.isPrimaryKey&&!Et(b.dbType)),[e]),x=u.useMemo(()=>e.columns.some(b=>!b.isReadOnly&&!b.isIdentity&&!b.isPrimaryKey&&!b.isNullable&&Et(b.dbType)),[e]),h=u.useMemo(()=>{const b=new Map(e.columns.map(v=>[v.name,v]));return(e.primaryKeys??[]).map(v=>b.get(v)).filter(v=>!!v)},[e]),y=p.filter(b=>a[b.name]?.enabled),N=d||i.isPending,T=(b,v)=>l(w=>{const F=w[b]??{enabled:!1,value:"",setNull:!1};return{...w,[b]:{...F,...v}}}),k=b=>{const v=a[b.name];return v.setNull?null:b.paramType.startsWith("Boolean")?v.value==="true":v.value},$=async()=>{if(m(null),y.length===0){m("Choose at least one field to change.");return}f(!0);try{const b={};for(const L of y)b[L.name]=k(L);const v=p.filter(L=>!L.isNullable||b[L.name]!==void 0),w=[...new Set([...e.primaryKeys??[],...v.map(L=>L.name)])],F=mo(e,t,w);if(!F)throw new Error("The selected rows have no resolvable primary keys.");const V=(await s.query(F.query,F.variables))?.value?.data??[];if(V.length!==t.length)throw new Error(`Only ${V.length} of ${t.length} selected rows still exist. Refresh and retry.`);const S=lu(e,v,h,V,b);await i.saveDelta({updated:S}),r()}catch(b){const v=b.message??String(b);m(v),o(`Bulk edit failed: ${v}`,"error")}finally{f(!1)}};return n.jsx(jt,{open:!0,onOpenChange:b=>{!b&&!N&&r()},children:n.jsxs(wt,{showCloseButton:!1,className:"max-w-lg",children:[n.jsxs(tn,{children:[n.jsxs(Ct,{children:["Edit ",t.length," ",t.length===1?"row":"rows"]}),n.jsx(Kt,{children:"Chosen fields are applied to every selected row and saved in one transaction — if any row fails, nothing changes."})]}),x?n.jsx("p",{className:"text-sm text-destructive",children:"This table has a required binary column, which bulk edit cannot echo. Edit rows individually."}):n.jsx("div",{className:"flex flex-col gap-2 max-h-80 overflow-y-auto py-1",children:p.map(b=>{const v=a[b.name]??{enabled:!1,value:"",setNull:!1},w=b.paramType.startsWith("Boolean");return n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Cn,{id:`bulk-${b.name}`,checked:v.enabled,onCheckedChange:F=>T(b.name,{enabled:F===!0})}),n.jsx(Wt,{htmlFor:`bulk-${b.name}`,className:"w-40 truncate",title:b.label??b.name,children:b.label??b.name}),w?n.jsxs("select",{className:"h-8 rounded-md border bg-transparent px-2 text-sm flex-1",disabled:!v.enabled||v.setNull,value:v.value==="true"?"true":"false",onChange:F=>T(b.name,{value:F.target.value}),children:[n.jsx("option",{value:"true",children:"true"}),n.jsx("option",{value:"false",children:"false"})]}):n.jsx(Qe,{className:"h-8 flex-1",disabled:!v.enabled||v.setNull,value:v.value,onChange:F=>T(b.name,{value:F.target.value})}),b.isNullable&&n.jsxs("label",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[n.jsx(Cn,{checked:v.setNull,disabled:!v.enabled,onCheckedChange:F=>T(b.name,{setNull:F===!0})}),"null"]})]},b.name)})}),c&&n.jsx("p",{className:"text-sm text-destructive",children:c}),n.jsxs(Gr,{children:[n.jsx(Q,{variant:"outline",onClick:r,disabled:N,children:"Cancel"}),n.jsx(Q,{onClick:$,disabled:N||x,children:N?"Saving…":`Apply to ${t.length} ${t.length===1?"row":"rows"}`})]})]})})}function md({...e}){return n.jsx(R.Dialog.Root,{"data-slot":"sheet",...e})}function fd({...e}){return n.jsx(R.Dialog.Portal,{"data-slot":"sheet-portal",...e})}function pd({className:e,...t}){return n.jsx(R.Dialog.Overlay,{"data-slot":"sheet-overlay",className:Y("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function hd({className:e,children:t,side:r="right",...s}){return n.jsxs(fd,{children:[n.jsx(pd,{}),n.jsxs(R.Dialog.Content,{"data-slot":"sheet-content",className:Y("fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out duration-200 outline-none","data-[state=closed]:animate-out data-[state=open]:animate-in data-[state=closed]:duration-200 data-[state=open]:duration-200",r==="right"&&"inset-y-0 right-0 h-full w-3/4 max-w-md border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right",r==="left"&&"inset-y-0 left-0 h-full w-3/4 max-w-md border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left",r==="top"&&"inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",r==="bottom"&&"inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",e),...s,children:[t,n.jsxs(R.Dialog.Close,{"data-slot":"sheet-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[n.jsx(C.XIcon,{}),n.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function gd({className:e,...t}){return n.jsx("div",{"data-slot":"sheet-header",className:Y("flex flex-col gap-2 p-4 pb-0",e),...t})}function xd({className:e,...t}){return n.jsx(R.Dialog.Title,{"data-slot":"sheet-title",className:Y("text-lg leading-none font-semibold",e),...t})}function bd({className:e,...t}){return n.jsx(R.Dialog.Description,{"data-slot":"sheet-description",className:Y("text-sm text-muted-foreground",e),...t})}const yd={json:C.Braces,xml:C.Code,"php-serialized":C.Database,binary:C.Binary,longtext:C.FileText,text:C.FileText},aa={json:"JSON",xml:"XML","php-serialized":"PHP Serialized",binary:"Binary",longtext:"Text",text:"Text"};function vd(e,t){if(t==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return t==="xml"?e.replace(/>\s*</g,`>
121
- <`).trim():e}function jd({target:e,onClose:t,onNavigate:r,onSave:s,canNavigatePrev:o,canNavigateNext:i}){const{toast:a}=vt(),[l,c]=u.useState(!1),[m,d]=u.useState(!1),[f,p]=u.useState(""),[x,h]=u.useState(!1),[y,N]=u.useState(!1),T=u.useRef(null),k=e?.value??"",$=Bn(k,e?.dbType),b=yd[$],v=vd(k,$),w=$==="binary"&&k?so(k):null,F=u.useCallback(()=>{!e||!w||Gl(k,`${e.columnName}${w.extension}`,w.mime)},[e,w,k]);u.useEffect(()=>{d(!1),p(""),h(!1),N(!1)},[e?.rowKey,e?.columnName]),u.useEffect(()=>{if(!e)return;const _=ce=>{m||(ce.key==="ArrowUp"&&o?(ce.preventDefault(),r("prev")):ce.key==="ArrowDown"&&i&&(ce.preventDefault(),r("next")))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[e,m,o,i,r]);const j=u.useRef(null);u.useEffect(()=>()=>{j.current&&clearTimeout(j.current)},[]);const V=u.useCallback(async()=>{try{await navigator.clipboard.writeText(k)}catch(_){a(`Copy failed: ${_ instanceof Error?_.message:String(_)}`,"error");return}h(!0),j.current&&clearTimeout(j.current),j.current=setTimeout(()=>h(!1),1500)},[k,a]),S=u.useCallback(()=>{p(v),d(!0),requestAnimationFrame(()=>T.current?.focus())},[v]),L=u.useCallback(()=>{d(!1),p("")},[]),A=u.useCallback(async()=>{if(f===v){d(!1);return}if(!(!s||y)){N(!0);try{await s(f),d(!1)}catch{}finally{N(!1)}}},[s,f,v,y]),D=u.useCallback(()=>{if($==="json")try{p(JSON.stringify(JSON.parse(f),null,2))}catch{}else $==="xml"&&p(f.replace(/>\s*</g,`>
122
- <`).trim())},[f,$]),B=$==="json"||$==="xml",X=!!s&&!e?.isReadOnly&&$!=="binary",E=n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx(b,{className:"size-4 text-muted-foreground shrink-0"}),n.jsx("span",{className:"truncate font-semibold text-sm",children:e?.columnLabel}),n.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:w?w.kind==="image"?w.mime.replace("image/","").toUpperCase()+" image":w.kind==="pdf"?"PDF document":aa[$]:aa[$]}),n.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:w?xr(k):`${k.length} chars`})]}),P=n.jsxs("div",{className:"flex items-center gap-1 px-4 pb-2",children:[n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:V,children:[x?n.jsx(C.Check,{className:"size-3"}):n.jsx(C.Copy,{className:"size-3"}),x?"Copied":"Copy"]}),w&&n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:F,children:[n.jsx(C.Download,{className:"size-3"}),"Download"]}),X&&!m&&n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:S,children:[n.jsx(C.Pencil,{className:"size-3"}),"Edit"]}),m&&B&&n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:D,children:[n.jsx(C.WrapText,{className:"size-3"}),"Format"]}),n.jsxs("div",{className:"flex items-center gap-1 ml-auto",children:[n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>r("prev"),disabled:!o,"aria-label":"Previous row",title:"Previous row",children:n.jsx(C.ChevronUp,{className:"size-4"})}),n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>r("next"),disabled:!i,"aria-label":"Next row",title:"Next row",children:n.jsx(C.ChevronDown,{className:"size-4"})}),n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>c(_=>!_),"aria-label":l?"Exit full screen":"Full screen",title:l?"Exit full screen":"Full screen",children:l?n.jsx(C.Minimize2,{className:"size-4"}):n.jsx(C.Maximize2,{className:"size-4"})})]})]}),q=n.jsx("div",{className:"flex-1 min-h-0 overflow-auto px-4 pb-4",children:m?n.jsxs("div",{className:"flex flex-col gap-2 h-full",children:[n.jsx("textarea",{ref:T,value:f,onChange:_=>p(_.target.value),className:Y("flex-1 w-full rounded-md border border-input bg-background px-3 py-2","text-xs font-mono leading-relaxed","ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","resize-none min-h-[200px]")}),n.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[n.jsx(Q,{type:"button",variant:"ghost",size:"sm",onClick:L,disabled:y,children:"Cancel"}),n.jsx(Q,{type:"button",size:"sm",onClick:A,disabled:y,children:y?"Saving…":"Save"})]})]}):w?.kind==="image"?n.jsx("img",{src:oo(k,w.mime),alt:e?.columnLabel??"Image content",className:"max-w-full rounded-md border border-input"}):w?n.jsxs("div",{className:"rounded-md border border-input bg-muted/30 p-4 text-sm text-muted-foreground",children:[n.jsxs("p",{children:[w.kind==="pdf"?"PDF document":"Binary content"," · ",xr(k)]}),n.jsx("p",{className:"mt-1 text-xs",children:"Use Download to save and open the file."})]}):n.jsx("pre",{className:"text-xs font-mono leading-relaxed whitespace-pre-wrap break-all",children:v})}),U=!!e;return n.jsxs(n.Fragment,{children:[n.jsx(md,{open:U&&!l,onOpenChange:_=>{_||t()},children:n.jsxs(hd,{side:"right",className:"w-[480px] max-w-[90vw]",children:[n.jsxs(gd,{children:[n.jsx(xd,{children:E}),n.jsx(bd,{className:"sr-only",children:"Content viewer panel"})]}),P,q]})}),n.jsx(jt,{open:U&&l,onOpenChange:_=>{_||c(!1)},children:n.jsxs(wt,{className:"max-w-[90vw] max-h-[90vh] w-full h-full flex flex-col",children:[n.jsxs(tn,{children:[n.jsx(Ct,{children:E}),n.jsx(Kt,{className:"sr-only",children:"Content viewer full screen"})]}),P,q]})})]})}function wd(e,t){if(Gn(e,t).filterTexts.length===0)return;const s=[];for(const o of e){const i=o.value,a=t.columns.find(l=>l.name===o.id);!a||!pn(a.paramType).includes(i.operator)||i.value===void 0||i.value===""&&i.operator!=="_null"||s.push({[a.graphQlName]:{[i.operator]:i.value}})}return s.length===1?s[0]:s.length>1?{and:s}:void 0}function ts({table:e,id:t,filterTable:r,filterColumn:s,selectedRowId:o,onRowSelect:i,onOpenColumn:a,stackingEnabled:l,onToggleStacking:c}){const m=Qn(e),[d,f]=u.useState(null),[p,x]=u.useState(null),[h,y]=u.useState(null),N=u.useRef([]),T=u.useCallback(I=>{x(Vn(I,e))},[e]),k=u.useCallback(I=>{f({type:"single",pk:I})},[]),$=u.useCallback(I=>{I.length!==0&&f({type:"batch",pks:I})},[]),[b,v]=u.useState(null),w=u.useCallback(I=>{I.length!==0&&v(I)},[]),[F,j]=u.useState(new Map),V=u.useRef(F);V.current=F;const[S,L]=u.useState(!1),A=qo(e),D=u.useCallback((I,ne)=>{const Se=N.current[I];y({columnName:ne,pk:Se?mt(Se,e):null,rowIndex:I,tableName:e.name})},[e]),{columns:B,sorting:X,columnFilters:E,pageIndex:P,pageSize:q,pageCount:U,rows:_,totalRows:ce,grouping:he,exportRows:Ue,loading:Pe,fetching:ie,error:se,onSortingChange:ke,onColumnFiltersChange:Ae,onPageIndexChange:re,onPageSizeChange:Ee,onGroupingChange:Ie,onGroupingSumChange:Le}=Jc(e,t,r,s,D,a),Ge=u.useCallback(async()=>{if(d)try{d.type==="single"?await m.deleteRow(d.pk):await m.deleteRows(d.pks),f(null)}catch{}},[d,m]),Oe=d?.type==="batch"?d.pks.length:1;N.current=_;const{toast:ye}=vt(),ze=$e(),O=e.isEditable!==!1,Z=u.useMemo(()=>h?.pk?Vn(h.pk,e):null,[h,e]),ee=u.useMemo(()=>!h||h.tableName!==e.name?-1:Z===null?h.rowIndex<_.length?h.rowIndex:-1:_.findIndex(I=>{const ne=mt(I,e);return ne!==null&&Vn(ne,e)===Z}),[h,Z,_,e]),Ce=ee>=0?_[ee]:void 0,xe=u.useMemo(()=>h?.pk?qn(h.pk,e):null,[h,e]),qe=h?e.columns.find(I=>I.name===h.columnName):void 0,W=!!h&&!!qe&&!!xe&&_t(qe)&&Ce!==void 0&&!(qe.name in Ce),{data:me,isLoading:Ne,error:ve}=de.useQuery({queryKey:["contentPanelValue",e.name,h?.columnName,Z],queryFn:async()=>{const I=Cr(e,xe,[qe.name]),Se=(await ze.query(I,xe.variables))?.value?.data?.at(0);if(!Se)throw new Error("Row no longer exists.");return Se[qe.name]??null},enabled:W});u.useEffect(()=>{h!==null&&W&&ve&&(y(null),ye(`Could not load content: ${ve.message}`,"error"))},[h,W,ve,ye]),u.useEffect(()=>{h!==null&&h.tableName!==e.name&&y(null)},[h,e.name]),u.useEffect(()=>{h!==null&&h.tableName===e.name&&!Pe&&ee===-1&&(y(null),ye("Row is no longer in the current view; panel closed.","error"))},[h,e.name,Pe,ee,ye]);const rt=u.useMemo(()=>{if(!h||!Ce)return null;const I=e.columns.find(ot=>ot.name===h.columnName);if(!I||W&&(Ne||ve))return null;const ne=W?me:Ce[h.columnName],Se=Ft(I);return{value:ne==null?"":Se||typeof ne=="object"?JSON.stringify(ne,null,2):String(ne),columnName:I.name,columnLabel:I.label,dbType:I.dbType,rowKey:Z??`row-${h.rowIndex}`,isReadOnly:I.isReadOnly||I.isPrimaryKey||I.isIdentity}},[h,Ce,Z,e,W,me,Ne,ve]),Mt=u.useMemo(()=>e.columns.filter(I=>!I.isReadOnly&&!I.isIdentity),[e]),be=u.useMemo(()=>Mt.filter(I=>!I.isNullable||I.name===h?.columnName),[Mt,h?.columnName]),ft=u.useMemo(()=>be.map(I=>({column:I})),[be]),Nt=u.useMemo(()=>{const I=new Map(e.columns.map(ne=>[ne.name,ne]));return(e.primaryKeys??[]).map(ne=>I.get(ne)).filter(ne=>!!ne)},[e]),Ye=wn(e,ft,Nt,Z??""),Xe=O&&xe!==null&&!Ye.isPending,Qt=u.useCallback(async I=>{if(!h||!xe)return;const ne=e.columns.find(De=>De.name===h.columnName);let Se=I;if(ne&&Ft(ne))try{Se=JSON.parse(I)}catch{}try{const De=Cr(e,xe,be.map(kt=>kt.name)),ht=(await ze.query(De,xe.variables))?.value?.data?.[0];if(!ht)throw new Error("Row no longer exists.");const Ke={};for(const kt of be)Ke[kt.name]=ht[kt.name]??null;Ke[h.columnName]=Se,await Ye.update(Ke)}catch(De){throw ye(`Save failed: ${De.message}`,"error"),De}},[h,xe,e,be,Ye,ze,ye]),kn=u.useCallback(()=>{y(null)},[]),Sn=u.useCallback(I=>{if(!h||ee<0)return;const ne=I==="prev"?Math.max(0,ee-1):Math.min(_.length-1,ee+1);D(ne,h.columnName)},[h,ee,_.length,D]),Ht=u.useMemo(()=>new Set(e.columns.filter(I=>!I.isReadOnly&&!I.isIdentity&&!I.isPrimaryKey&&!Et(I.dbType)&&!_t(I)).map(I=>I.name)),[e]),pt=u.useMemo(()=>new Set(e.columns.filter(I=>I.paramType.startsWith("Boolean")).map(I=>I.name)),[e]),It=u.useCallback((I,ne,Se)=>{const De=fn(I,e);if(!De)return;const ot=N.current.find(ht=>He(ht,e,-1)===I);j(ht=>{const Ke=new Map(ht),gt={...Ke.get(I)?.changes??{}},nn=ot?.[ne];return ot!==void 0&&nn==null==(Se==null)&&String(nn??"")===String(Se??"")?delete gt[ne]:gt[ne]=Se,Object.keys(gt).length===0?Ke.delete(I):Ke.set(I,{pk:De,changes:gt}),Ke})},[e]),st=u.useCallback(()=>j(new Map),[]),Ut=u.useCallback(async()=>{const I=[...V.current.entries()];if(I.length!==0){L(!0);try{const ne=e.columns.filter(Me=>Ht.has(Me.name)),Se=(e.primaryKeys??[]).map(Me=>e.columns.find(as=>as.name===Me)).filter(Me=>!!Me),De=new Set(I.flatMap(([,Me])=>Object.keys(Me.changes))),ot=ne.filter(Me=>!Me.isNullable||De.has(Me.name)),ht=[...new Set([...e.primaryKeys??[],...ot.map(Me=>Me.name)])],Ke=mo(e,I.map(([,Me])=>Me.pk),ht);if(!Ke)throw new Error("The edited rows have no resolvable primary keys.");const gt=(await ze.query(Ke.query,Ke.variables))?.value?.data??[];if(gt.length!==I.length)throw new Error(`Only ${gt.length} of ${I.length} edited rows still exist. Refresh and retry.`);const nn=cu(e,ne,Se,gt,Me=>V.current.get(He(Me,e,-1))?.changes);await A.saveDelta({updated:nn}),j(new Map)}catch(ne){ye(`Save failed: ${ne.message}`,"error")}finally{L(!1)}}},[e,Ht,A,ze,ye]),Lt=u.useRef(e.name);u.useEffect(()=>{Lt.current!==e.name&&(Lt.current=e.name,V.current.size>0&&(j(new Map),ye("Unsaved cell edits were discarded on table switch","error")))},[e.name,ye]);const z=u.useMemo(()=>new Map([...F].map(([I,ne])=>[I,ne.changes])),[F]),H=u.useCallback(()=>{const I=wd(E,e);window.dispatchEvent(new CustomEvent("bifrostql:visualize",{detail:{table:e.graphQlName,filter:I,filterType:`TableFilter${e.graphQlName}Input`}}))},[E,e]);return se?n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",se.message]})}):n.jsxs(n.Fragment,{children:[n.jsx(id,{columns:B,data:_,tableName:e.name,pageCount:U,pageIndex:P,pageSize:q,sorting:X,columnFilters:E,loading:Pe,fetching:ie,primaryKeys:e.primaryKeys??[],selectable:O&&!he,selectedRowId:o,onRowSelect:i,onSortingChange:ke,onColumnFiltersChange:Ae,onPageIndexChange:re,onPageSizeChange:Ee,onEditRow:O&&!he?T:void 0,onDeleteRow:O&&!he?k:void 0,onDeleteSelected:O&&!he?$:void 0,onBulkEditSelected:O&&!he?w:void 0,inlineEditableColumns:Ht,inlineBooleanColumns:pt,pendingEdits:z,onCellCommit:O&&!he?It:void 0,onSaveAllEdits:Ut,onDiscardAllEdits:st,savingEdits:S,stackingEnabled:l,onToggleStacking:c,exportRows:Ue,totalRows:ce,groupableColumns:e.columns,grouping:he,onGroupingChange:Ie,onGroupingSumChange:Le,onVisualize:H}),n.jsx(Kr,{open:d!==null,onOpenChange:I=>{I||f(null)},title:`Delete ${Oe} ${Oe===1?"row":"rows"}?`,description:n.jsxs(n.Fragment,{children:[n.jsx("p",{children:"This action cannot be undone."}),m.error&&n.jsx("p",{className:"mt-2 text-sm text-destructive",children:m.error.message})]}),confirmLabel:`Delete ${Oe===1?"row":`${Oe} rows`}`,variant:"destructive",isPending:m.isPending,onConfirm:Ge}),n.jsx(jd,{target:rt,onClose:kn,onNavigate:Sn,onSave:Xe?Qt:void 0,canNavigatePrev:ee>0,canNavigateNext:ee>=0&&ee<_.length-1}),b!==null&&n.jsx(dd,{table:e,pks:b,onClose:()=>v(null)}),p!==null&&n.jsx(Ro,{table:e.graphQlName,editId:p,onClose:()=>x(null)})]})}function Cd(e){return new Set((e.manyToManyJoins??[]).map(t=>t.junctionTable))}function ia(e){const t=Cd(e),r=e.multiJoins.filter(o=>!t.has(o.destinationTable)).map(o=>({kind:"child",key:`child:${o.fieldName??o.destinationTable}`,join:o})),s=(e.manyToManyJoins??[]).map(o=>({kind:"m2m",key:`m2m:${o.junctionTable}:${o.targetTable}`,m2m:o}));return[...r,...s]}function la(e,t){const r=new Set([...t.junctionSourceColumnNames,...t.junctionTargetColumnNames]);return e.columns.filter(s=>!s.isPrimaryKey&&!r.has(s.name))}function Nd(e,t,r,s){const o=r.junctionSourceColumnNames;if(o.length===0)throw new Error(`Many-to-many relationship '${r.name}' has no junction source columns.`);const i=to(s,o.length),a=new Map(e.columns.map($=>[$.name,$])),l=[],c=[],m={};o.forEach(($,b)=>{const v=a.get($);if(!v)throw new Error(`Junction table '${e.name}' has no column '${$}' (junction source column of many-to-many relationship '${r.name}').`);const w=v.paramType.replace("!",""),F=`src${b}`;l.push(`$${F}: ${w}`),c.push(`{ ${$}: { _eq: $${F} } }`),m[F]=dt(i[b],w)});const d=c.length===1?c[0]:`{ and: [${c.join(", ")}] }`,f=e.primaryKeys??[],p=la(e,r).map($=>$.name),x=t.primaryKeys?.length?t.primaryKeys:r.targetColumnNames,h=t.labelColumn,y=[...x];h&&!x.includes(h)&&y.push(`label: ${h}`);const N=`${r.junctionTargetField} { ${y.join(" ")} }`,T=[...f,...p,N].join(" ");return{query:`query GetLinks_${e.name}(${l.join(", ")}, $limit: Int, $offset: Int) { ${e.name}(filter: ${d} limit: $limit offset: $offset) { total offset limit data { ${T} } } }`,variables:m}}function ca(e,t){const r=zt(e).map(s=>s.name);return r.length>0?r:[...t.targetColumnNames]}function kd(e,t,r){je(e.name,"many-to-many target table name");const s=ca(e,t),o=t.targetColumnNames[0],i=e.labelColumn||s[0];for(const h of s)je(h,"many-to-many target identity column");je(o,"many-to-many junction target column"),je(i,"many-to-many target label column");const l=`${[...new Set([...s,o])].join(" ")} label: ${i}`,c=e.columns.find(h=>h.name===i);if(!c)throw new Error(`Target table '${e.name}' has no column '${i}' (label column for the '${t.name}' many-to-many picker).`);const m=c.paramType.replace("!","")==="String",d=!!r&&r.trim()!==""&&m,f=d?"$limit: Int, $search: String":"$limit: Int",p=d?`filter: {${i}: {_contains: $search}} `:"";return{query:`query PickTarget(${f}) { ${e.name}(${p}limit: $limit sort: [${i}_asc]) { data { ${l} } } }`,identityColumns:s,linkColumn:o,serverSearch:m}}function Sd(e,t,r){const s=e[t.junctionTargetField];if(!s)return null;const o=He(s,r,0),i=s.label!=null?String(s.label):o;return{id:o,label:i}}function Td(e,t,r){if(e.junctionSourceColumnNames.length!==1||e.junctionTargetColumnNames.length!==1)throw new Error("attachJunctionDetail supports single-column junction FKs only; this relationship uses a composite key which is not yet supported.");const[s]=to(t,1);return{[e.junctionSourceColumnNames[0]]:s,[e.junctionTargetColumnNames[0]]:r}}const ns=200,$d=50,Ed=500;function Fd({m2m:e,parentRowId:t,onOpenColumn:r}){const s=Je(),o=s.findTable(e.junctionTable),i=s.findTable(e.targetTable);return!o||!i?n.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Relationship schema unavailable."}):n.jsx(_d,{m2m:e,parentRowId:t,onOpenColumn:r,junction:o,target:i})}function _d({m2m:e,parentRowId:t,onOpenColumn:r,junction:s,target:o}){const i=$e(),a=de.useQueryClient(),{toast:l}=vt(),[c,m]=u.useState(!1),[d,f]=u.useState(null),p=Qn(s);let x={query:null,variables:{}},h=null;try{x=Nd(s,o,e,t)}catch(A){h=A}const{query:y,variables:N}=x,T=u.useMemo(()=>["m2mRows",e.junctionTable,e.targetTable,t],[e.junctionTable,e.targetTable,t]),{data:k,isLoading:$,error:b}=de.useQuery({queryKey:T,queryFn:()=>i.query(y,{...N,limit:ns,offset:0}),enabled:!!y}),v=u.useCallback(()=>a.invalidateQueries({queryKey:T}),[a,T]),w=u.useCallback(async A=>{const D=mt(A,s);if(!D)throw new Error(`This link cannot be removed: its ${s.label} row is missing one or more key columns (${(s.primaryKeys??[]).join(", ")||"none declared"}).`);await p.deleteRow(D),await v()},[s,p,v]);if(h)return n.jsxs("div",{className:"p-4 text-sm text-destructive",children:["Relationship misconfigured: ",h.message]});const F=k?.[s.name]?.data??[],j=la(s,e),V=s.isEditable!==!1,S=ca(o,e),L=new Set;for(const A of F){const D=A[e.junctionTargetField];D&&(S.some(B=>D[B]==null)||L.add($t(S.map(B=>D[B]))))}return n.jsxs("div",{className:"flex flex-col min-h-0 flex-1 overflow-hidden",children:[n.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 bg-muted/20 border-b border-border shrink-0",children:[n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs text-muted-foreground",title:`Linked through ${s.label}`,children:[n.jsx(C.Link2,{className:"size-3"}),"via ",s.label]}),V&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs ml-auto",onClick:()=>m(!0),children:[n.jsx(C.Plus,{className:"size-3 mr-1"})," Add link"]})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-auto",children:[b&&n.jsxs("div",{className:"p-3 text-sm text-destructive",children:["Error: ",b.message]}),$&&n.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin"})," Loading…"]}),!$&&F.length===0&&n.jsxs("div",{className:"p-3 text-sm text-muted-foreground",children:["No linked ",o.label,"."]}),F.length>0&&n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"border-b border-border text-left text-xs text-muted-foreground",children:[n.jsx("th",{className:"px-2 py-1 font-medium",children:o.label}),j.map(A=>n.jsx("th",{className:"px-2 py-1 font-medium",children:A.label},A.name)),V&&n.jsx("th",{className:"px-2 py-1 w-8","aria-label":"actions"})]})}),n.jsx("tbody",{children:F.map((A,D)=>{const B=Sd(A,e,o);return n.jsxs("tr",{className:"border-b border-border/50 hover:bg-muted/30",children:[n.jsx("td",{className:"px-2 py-1",children:B?n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Pn,{to:`/${o.name}/${B.id}`,className:"text-primary hover:underline",children:B.label}),r&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"size-5",onClick:()=>r({tableName:o.name,filterId:B.id}),"aria-label":`Open ${B.label} in side column`,title:"Open in side column",children:n.jsx(C.Search,{className:"size-3"})})]}):n.jsx("span",{className:"text-muted-foreground",children:"—"})}),j.map(X=>n.jsx("td",{className:"px-2 py-1",children:Kn(A[X.name],X)},X.name)),V&&n.jsx("td",{className:"px-2 py-1",children:n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"size-6 text-muted-foreground hover:text-destructive",onClick:()=>f(A),disabled:p.isPending,"aria-label":`Detach ${B?.label??"link"}`,title:"Detach",children:n.jsx(C.Unlink,{className:"size-3.5"})})})]},D)})})]}),F.length>=ns&&n.jsxs("div",{className:"px-3 py-2 text-xs text-muted-foreground italic border-t border-border",children:["Showing the first ",ns," links. Detach some or narrow the parent selection to see more."]})]}),c&&n.jsx(Pd,{target:o,junction:s,m2m:e,parentRowId:t,linkedIds:L,onClose:()=>m(!1),onLinked:v}),n.jsx(Kr,{open:d!==null,onOpenChange:A=>{A||f(null)},title:"Detach this link?",description:n.jsxs("p",{children:["This removes the link row. The ",o.label," record itself is not deleted."]}),confirmLabel:"Detach",variant:"destructive",isPending:p.isPending,onConfirm:async()=>{try{d&&await w(d)}catch(A){l(`Detach failed: ${A.message}`,"error")}finally{f(null)}}})]})}function Pd({target:e,junction:t,m2m:r,parentRowId:s,linkedIds:o,onClose:i,onLinked:a}){const l=$e(),c=t.columns.filter(B=>r.junctionSourceColumnNames.includes(B.name)||r.junctionTargetColumnNames.includes(B.name)).map(B=>({column:B})),m=wn(t,c,[]),[d,f]=u.useState(""),[p,x]=u.useState("");u.useEffect(()=>{const B=setTimeout(()=>x(d),300);return()=>clearTimeout(B)},[d]);const h=p.trim();let y=null,N=null;try{y=kd(e,r,h)}catch(B){N=B}const{query:T,identityColumns:k,linkColumn:$,serverSearch:b}=y??{query:"",identityColumns:[],linkColumn:"",serverSearch:!1},v=b?$d:Ed,{data:w,isLoading:F}=de.useQuery({queryKey:["m2mTargets",e.name,b?h:""],queryFn:({signal:B})=>l.query(T,b&&h?{limit:v,search:h}:{limit:v},{signal:B}),enabled:y!==null}),j=w?.[e.name]?.data??[],V=b||!h?j:j.filter(B=>Wo(B,"label",h)),S=j.length>=v,[L,A]=u.useState(null),D=u.useCallback(async(B,X)=>{if(o.has(B))return;let E;try{E=Td(r,s,X)}catch(P){A(P);return}A(null);try{await m.insert(E)}catch{return}await a(),i()},[m,r,s,o,a,i]);return N?n.jsx(jt,{open:!0,onOpenChange:B=>{B||i()},children:n.jsxs(wt,{className:"max-w-md",children:[n.jsx(tn,{children:n.jsxs(Ct,{children:["Add ",e.label," link"]})}),n.jsxs("p",{className:"text-sm text-destructive",children:["Relationship misconfigured: ",N.message]})]})}):n.jsx(jt,{open:!0,onOpenChange:B=>{B||i()},children:n.jsxs(wt,{className:"max-w-md",children:[n.jsx(tn,{children:n.jsxs(Ct,{children:["Add ",e.label," link"]})}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(C.Search,{className:"size-4 text-muted-foreground"}),n.jsx(Qe,{autoFocus:!0,placeholder:`Search ${e.label}…`,value:d,onChange:B=>f(B.target.value)})]}),L&&n.jsx("p",{className:"text-sm text-destructive",children:L.message}),m.error&&n.jsx("p",{className:"text-sm text-destructive",children:m.error.message}),n.jsxs("div",{className:"max-h-72 overflow-auto border border-border rounded-md",children:[F&&n.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin"})," Loading…"]}),!F&&V.length===0&&n.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No matches."}),V.map((B,X)=>{const E=$t(k.map(_=>B[_])),P=String(B[$]??""),q=B.label!=null?String(B.label):E,U=o.has(E);return n.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-2 text-left px-3 py-1.5 text-sm hover:bg-muted/50 disabled:opacity-50 disabled:hover:bg-transparent",disabled:m.isPending||U,onClick:()=>D(E,P),children:[n.jsx("span",{className:"truncate",children:q}),U&&n.jsx("span",{className:"shrink-0 text-xs text-muted-foreground italic",children:"Already linked"})]},X)}),!F&&S&&n.jsx("div",{className:"px-3 py-1.5 text-xs text-muted-foreground italic border-t border-border",children:b?`Showing the first ${v} matches — type to narrow.`:`Showing the first ${v} rows; some may not be listed.`})]})]})})}function ua(e){return e.kind==="child"?e.join.destinationTable:e.m2m.targetTable}function da({parentTable:e,selectedRowId:t,onClose:r,onOpenColumn:s}){const o=Je(),i=ia(e),[a,l]=u.useState(i[0]?.key??""),[c,m]=u.useState(!1),[d,f]=u.useState(null),p=i.find(y=>y.key===a)??i[0];if(u.useEffect(()=>{f(null)},[a,t]),i.length===0||!o.data)return null;const x=p.kind==="child"?o.findTable(p.join.destinationTable):void 0,h=(x?.multiJoins?.length??0)>0;return n.jsxs("div",{className:"border-t-2 border-primary/20 flex flex-col flex-1 shrink-0",children:[n.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted/30 border-b border-border shrink-0",children:[n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:()=>m(!c),"aria-label":c?"Expand detail panel":"Collapse detail panel",title:c?"Expand detail panel":"Collapse detail panel",children:c?n.jsx(C.ChevronUp,{className:"size-3.5"}):n.jsx(C.ChevronDown,{className:"size-3.5"})}),n.jsx("span",{className:"text-xs text-muted-foreground mr-1",children:"Detail:"}),n.jsx("div",{className:"flex items-center gap-0.5 overflow-x-auto",children:i.map(y=>{const T=o.findTable(ua(y))?.label??ua(y),k=y.key===p.key;return n.jsxs("span",{className:"group/tab inline-flex items-center",children:[n.jsx(Q,{variant:k?"secondary":"ghost",size:"sm",className:Y("text-xs h-7 px-2.5",k&&"font-semibold"),onClick:()=>l(y.key),children:T}),s&&y.kind==="child"&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"opacity-0 group-hover/tab:opacity-100 size-5 shrink-0",onClick:()=>s({tableName:y.join.destinationTable,filterTable:e.name,filterId:t,...Gt(y.join)?{}:{filterColumn:y.join.destinationColumnNames[0]}}),"aria-label":"Open in side column",title:"Open in side column",children:n.jsx(C.PanelRight,{className:"size-3"})})]},y.key)})}),r&&n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:r,className:"ml-auto shrink-0","aria-label":"Close detail panel",title:"Close detail panel",children:n.jsx(C.X,{className:"size-3.5"})})]}),!c&&n.jsx("div",{className:"flex-1 flex flex-col",children:p.kind==="child"&&!x?n.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"This related table is not available."}):p.kind==="child"?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex-1 min-h-[11rem] overflow-hidden flex flex-col",children:n.jsx(ts,{table:x,id:t,filterTable:e.name,...Gt(p.join)?{}:{filterColumn:p.join.destinationColumnNames[0]},selectedRowId:h?d:void 0,onRowSelect:h?f:void 0,onOpenColumn:s},`${p.key}-${t}`)}),h&&d&&n.jsx("div",{className:"flex-1 flex flex-col",children:n.jsx(da,{parentTable:x,selectedRowId:d,onClose:()=>f(null),onOpenColumn:s})})]}):n.jsx(Fd,{m2m:p.m2m,parentRowId:t,onOpenColumn:s},`${p.key}-${t}`)})]})}const zd={mainTable:null,columns:[],focusedIndex:0,focusColumn:()=>{},closeColumn:()=>{}},ma=u.createContext(zd),fa=u.createContext({register:()=>{},unregister:()=>{}});function Dd({children:e}){const[t,r]=u.useState(null),[s,o]=u.useState(0),i=u.useCallback(p=>{r(p)},[]),a=u.useCallback(()=>{r(null),o(0)},[]),l=u.useCallback(p=>{if(o(p),!t)return;const x=t.columnRefs.get(p);x&&x.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},[t]),c=u.useCallback(p=>{t&&p>0&&t.onClose(p-1)},[t]),m=u.useMemo(()=>t?t.columns.map((p,x)=>({panel:p,element:t.columnRefs.get(x+1)??null})):[],[t]),d=u.useMemo(()=>({mainTable:t?.mainTable??null,columns:m,focusedIndex:s,focusColumn:l,closeColumn:c}),[t,m,s,l,c]),f=u.useMemo(()=>({register:i,unregister:a}),[i,a]);return n.jsx(fa.Provider,{value:f,children:n.jsx(ma.Provider,{value:d,children:e})})}function Md(){return u.useContext(ma)}function Id(){return u.useContext(fa)}function pa(e,t){return e.tableName===t.tableName&&e.filterTable===t.filterTable&&e.filterId===t.filterId&&e.filterColumn===t.filterColumn}function Ld(e,t){const r=e[e.length-1];if(r&&pa(r,t))return e;const s=e.findIndex(o=>pa(o,t));return s>=0?e.slice(0,s+1):[...e,t]}function Od(e,t){return t<0?[]:t>=e.length?e:e.slice(0,t)}function Ad(e,t,r){const s=i=>r(i)??i,o=[{index:-1,label:s(e)}];for(let i=0;i<t.length;i++){const a=t[i],l=a.filterTable?s(a.filterTable):s(i===0?e:t[i-1].tableName),c=a.filterId?`from ${l} #${a.filterId}`:void 0;o.push({index:i,label:s(a.tableName),detail:c,frame:a})}return o}const ha="edit-db:panel:",qd=16;function ga(e,t,r){return Math.min(r,Math.max(t,e))}function Vd(e,t,r,s){try{const o=localStorage.getItem(ha+e),i=o===null?NaN:Number(o);return Number.isFinite(i)?ga(i,r,s):t}catch{return t}}function Bd(e,t){try{localStorage.setItem(ha+e,String(Math.round(t)))}catch{}}function xa({key:e,initial:t,min:r,max:s,axis:o,invert:i=!1}){const[a,l]=u.useState(()=>Vd(e,t,r,s)),c=u.useRef(null),m=u.useCallback(p=>{const x=ga(p,r,s);return l(x),Bd(e,x),x},[e,r,s]),d=u.useCallback(p=>{if(p.button!==0)return;p.preventDefault();const x=p.currentTarget;x.setPointerCapture(p.pointerId),c.current={start:o==="x"?p.clientX:p.clientY,startSize:a};const h=N=>{if(!c.current)return;const k=((o==="x"?N.clientX:N.clientY)-c.current.start)*(i?-1:1);m(c.current.startSize+k)},y=N=>{c.current=null;try{x.releasePointerCapture(N.pointerId)}catch{}x.removeEventListener("pointermove",h),x.removeEventListener("pointerup",y),x.removeEventListener("pointercancel",y)};x.addEventListener("pointermove",h),x.addEventListener("pointerup",y),x.addEventListener("pointercancel",y)},[m,o,i,a]),f=u.useCallback(p=>{const x=o==="x"?"ArrowRight":"ArrowDown",h=o==="x"?"ArrowLeft":"ArrowUp";if(p.key!==x&&p.key!==h)return;p.preventDefault();const y=(p.key===x?1:-1)*(i?-1:1);m(a+y*qd)},[m,o,i,a]);return{size:a,onPointerDown:d,onKeyDown:f}}function tr(e,t){return e.find(r=>r.name===t)}function Jt(){const e=ir(),{table:t,id:r,filterTable:s}=e,{loading:o,error:i,data:a}=Je(),[l,c]=u.useState(null),m=xa({key:"detail-height",initial:300,min:120,max:800,axis:"y",invert:!0}),[d,f]=u.useState([]),[p,x]=u.useState(!0),[h,y]=u.useState(new Set),N=u.useRef(t);t!==N.current&&(N.current=t,d.length>0&&f([]),h.size>0&&y(new Set));const T=u.useCallback(P=>{y(q=>{const U=new Set(q);return U.has(P)?U.delete(P):U.add(P),U})},[]),{register:k,unregister:$}=Id(),b=u.useRef(null),v=u.useRef(new Map),w=u.useMemo(()=>a?tr(a,t):void 0,[a,t]),F=w?ia(w).length>0:!1,j=u.useCallback(P=>{f(q=>Ld(q,P))},[]),V=u.useCallback(P=>{x(P),P||f([])},[]),S=p?j:void 0,L=u.useCallback(P=>{f(q=>q.filter((U,_)=>_!==P))},[]),A=u.useCallback(P=>{f(q=>Od(q,P+1))},[]),D=u.useMemo(()=>Ad(t??"",d,P=>{if(a)return tr(a,P)?.label}),[t,d,a]);if(u.useEffect(()=>{const P=v.current;P.set(0,b.current);for(const q of P.keys())q>d.length&&P.delete(q);return k({mainTable:t,columns:d,columnRefs:P,onClose:L}),()=>$()},[t,d,k,$,L]),!t)return n.jsx("div",{className:"p-5 text-center text-muted-foreground",children:"Table missing"});if(o)return n.jsxs("div",{className:"flex items-center justify-center gap-2 p-5",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]});if(i)return n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",i.message]})});if(!w)return n.jsx("div",{className:"p-5 text-center text-muted-foreground",children:"Table not found"});const B=n.jsx(ts,{table:w,id:r,filterTable:s,selectedRowId:F?l:void 0,onRowSelect:F?c:void 0,onOpenColumn:S,stackingEnabled:p,onToggleStacking:V});if(d.length===0){const P=F&&l;return n.jsx("div",{className:"flex flex-col flex-1 min-h-0",children:n.jsxs("div",{ref:b,className:"flex flex-col flex-1 min-h-0 min-w-0",children:[n.jsx("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:B}),P&&n.jsxs(n.Fragment,{children:[n.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":"Resize detail panel",tabIndex:0,"data-testid":"detail-resize-handle",className:"h-1.5 shrink-0 cursor-row-resize select-none touch-none hover:bg-primary/40 focus-visible:bg-primary/60 focus-visible:outline-none",onPointerDown:m.onPointerDown,onKeyDown:m.onKeyDown}),n.jsx("div",{className:"min-h-0 overflow-y-auto flex flex-col",style:{flex:`0 0 ${m.size}px`},children:n.jsx(da,{parentTable:w,selectedRowId:l,onClose:()=>c(null),onOpenColumn:S})})]})]})})}const X=d.length-1,E=(P,q)=>q||h.has(P);return n.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[n.jsx(Gd,{crumbs:D,onCrumbClick:A,activeIndex:d.length-1}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto flex flex-col gap-0.5 p-0.5",children:[n.jsx(ba,{title:w.label,selectedRowId:d[0]?.filterId,expanded:E(-1,!1),active:!1,onToggle:()=>T(-1),onRef:P=>{b.current=P,v.current.set(0,P)},children:B}),d.map((P,q)=>{const U=q===X;return n.jsx(ba,{title:tr(a,P.tableName)?.label??P.tableName,selectedRowId:d[q+1]?.filterId,expanded:E(q,U),active:U,onToggle:()=>T(q),onClose:()=>L(q),onRef:_=>{v.current.set(q+1,_)},children:n.jsx(ts,{table:tr(a,P.tableName),id:P.filterId,filterTable:P.filterTable,filterColumn:P.filterColumn,onOpenColumn:j})},`${P.tableName}|${P.filterTable??""}|${P.filterId??""}|${P.filterColumn??""}`)})]})]})}function Gd({crumbs:e,onCrumbClick:t,activeIndex:r}){return n.jsx("nav",{"aria-label":"Drill-down breadcrumb",className:"flex items-center gap-1 px-2 py-1 bg-muted/20 border-b border-border shrink-0 overflow-x-auto",children:e.map((s,o)=>{const i=s.index===r,a=o===0;return n.jsxs("span",{className:"inline-flex items-center gap-1 shrink-0",children:[!a&&n.jsx(C.ChevronRight,{className:"size-3 text-muted-foreground shrink-0"}),n.jsxs(Q,{variant:i?"secondary":"ghost",size:"sm",className:Y("h-6 px-2 text-xs gap-1",i&&"font-semibold"),onClick:()=>t(s.index),"aria-current":i?"page":void 0,title:s.detail?`${s.label} (${s.detail})`:s.label,children:[a&&n.jsx(C.Home,{className:"size-3"}),n.jsx("span",{className:"truncate max-w-[12rem]",children:s.label}),s.detail&&n.jsx("span",{className:"text-muted-foreground font-normal truncate max-w-[10rem]",children:s.detail})]})]},`${s.index}-${s.label}`)})})}function ba({title:e,selectedRowId:t,expanded:r,active:s,onToggle:o,onClose:i,onRef:a,children:l}){return n.jsxs("div",{ref:a,className:"shrink-0 flex flex-col border border-border rounded-sm overflow-hidden",children:[n.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted/30 border-b border-border shrink-0",children:[n.jsx("button",{type:"button",onClick:o,className:"inline-flex items-center justify-center size-5 shrink-0 text-muted-foreground hover:text-foreground","aria-expanded":r,"aria-label":r?"Collapse table":"Expand table",title:r?"Collapse":"Expand",children:r?n.jsx(C.ChevronDown,{className:"size-3.5"}):n.jsx(C.ChevronRight,{className:"size-3.5"})}),n.jsx("span",{className:"text-xs font-medium truncate",children:e}),s&&n.jsx("span",{className:"text-[10px] uppercase tracking-wide text-primary/70 shrink-0",children:"active"}),!r&&t&&n.jsxs("span",{className:"text-xs text-muted-foreground truncate",children:["#",t]}),n.jsx("div",{className:"flex-1"}),i&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"shrink-0",onClick:i,"aria-label":"Close column",title:"Close column",children:n.jsx(C.X,{className:"size-3.5"})})]}),r&&n.jsx("div",{className:"flex flex-col min-h-[18rem] max-h-[34rem]",children:l})]})}function rs(){const e=ir(),{loading:t,error:r,data:s}=Je(),{mainTable:o,columns:i,focusedIndex:a,focusColumn:l,closeColumn:c}=Md(),[m,d]=u.useState(""),f=_n(),{search:p}=hs(),x=!!p.get("filter"),{back:h,hasBack:y}=Da(),N=e?.table,T=i.length>0,k=u.useMemo(()=>s?.find(j=>j.graphQlName===N),[s,N]),$=u.useMemo(()=>k?.columns?.filter(j=>Ui(j.paramType)||Vt(j.paramType)).map(j=>({key:j.name,value:`${j.name},${j.paramType}`,label:j.label})),[k]),[b,v]=u.useState($?.at(0)?.value??"");u.useEffect(()=>{d(""),v($?.at(0)?.value??"")},[$]);const w=()=>{if(!m)return;const[j,V]=b.split(",");if(!V)return;const S=V.replace("!","");if(Vt(S)){const L=eo(m,S);if(L===null)return;f(`?filter=["${j}", "_eq", ${JSON.stringify(L)}, "${V}"]`)}else S==="String"&&f(`?filter=["${j}", "_contains", ${JSON.stringify(m)}, "${V}"]`)},F=()=>{d("");const j=new URLSearchParams(p.toString());j.delete("filter");const V=j.toString();f(V?`?${V}`:"?")};return t?n.jsxs("div",{className:"flex items-center gap-2 p-2.5",children:[n.jsx(C.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):r?n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",r.message]})}):n.jsxs("header",{className:"flex flex-wrap items-center gap-x-3 gap-y-1.5 px-3 py-1.5 min-h-[2.5rem]",children:[n.jsxs("div",{className:"flex items-center gap-1.5 overflow-x-auto min-w-0 flex-1",children:[n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:()=>y&&h(),disabled:!y,"aria-label":"Go back",title:"Go back",className:"shrink-0",children:n.jsx(C.ChevronLeft,{className:"size-4"})}),T?n.jsxs("div",{className:"flex items-center gap-1 overflow-x-auto",children:[n.jsx("button",{type:"button",onClick:()=>l(0),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium whitespace-nowrap transition-colors ${a===0?"bg-primary text-primary-foreground":"bg-muted/50 text-muted-foreground hover:bg-muted"}`,children:k?.label??zn(e?.table??"")}),i.map((j,V)=>{const L=s?.find(A=>A.graphQlName===j.panel.tableName)?.label??zn(j.panel.tableName);return n.jsxs("span",{className:`inline-flex items-center gap-1 pl-2 pr-1 py-0.5 rounded text-xs font-medium whitespace-nowrap transition-colors ${a===V+1?"bg-primary text-primary-foreground":"bg-muted/50 text-muted-foreground hover:bg-muted"}`,children:[n.jsx("button",{type:"button",onClick:()=>l(V+1),className:"whitespace-nowrap",children:L}),n.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),c(V+1)},className:"rounded-sm hover:bg-background/50 p-px","aria-label":`Close ${L}`,children:n.jsx(C.X,{className:"size-3"})})]},`${j.panel.tableName}-${j.panel.filterId??V}`)})]}):n.jsx("h2",{className:"text-sm font-semibold whitespace-nowrap",children:k?.label??e?.table??"(Select)"})]}),$&&$.length>0&&n.jsxs("div",{className:"flex items-center border border-border rounded-md overflow-hidden flex-[2_2_16rem] min-w-[12rem]",children:[n.jsxs(Ze,{value:b,onValueChange:v,children:[n.jsx(tt,{size:"sm",className:"w-auto min-w-[120px] shrink-0 border-0 rounded-none border-r border-border h-8 text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:$.map(j=>n.jsx(we,{value:j.value,children:j.label},j.key))})]}),n.jsxs("div",{className:"relative flex-1 min-w-[180px]",children:[n.jsx(C.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground pointer-events-none"}),n.jsx(Qe,{type:"search",value:m,onChange:j=>d(j.target.value),onKeyDown:j=>j.key==="Enter"&&w(),className:"h-8 border-0 rounded-none focus-visible:ring-0 focus-visible:ring-offset-0",style:{paddingLeft:"2.25rem"},placeholder:"Search..."})]}),n.jsxs(Q,{variant:"ghost",size:"sm",onClick:w,className:"shrink-0 rounded-none border-l border-border h-8 px-3 text-xs",children:[n.jsx(C.Filter,{className:"size-3.5"}),"Filter"]}),x&&n.jsx(Q,{variant:"ghost",size:"sm",onClick:F,title:"Clear filter","aria-label":"Clear filter",className:"shrink-0 rounded-none border-l border-border h-8 px-2 text-xs text-muted-foreground",children:n.jsx(C.X,{className:"size-3.5"})})]}),k&&n.jsxs("div",{className:"flex items-center gap-px border border-border rounded-md overflow-hidden shrink-0",children:[n.jsxs(Q,{variant:"ghost",size:"sm",onClick:()=>f("/"),title:"Back to table list",className:"text-muted-foreground text-xs h-8 px-3 rounded-none",children:[n.jsx(C.Home,{className:"size-3.5"}),"Home"]}),k?.isEditable&&n.jsxs(Q,{variant:"default",size:"sm",onClick:()=>f("edit/"),className:"h-8 text-xs px-4 rounded-none",children:[n.jsx(C.Plus,{className:"size-3.5"}),"Add"]})]})]})}class nr extends u.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){const{onError:s,section:o}=this.props;console.error(`Error in ${o??"component"}:`,t,r),s?.(t,r)}handleRetry=()=>{this.setState({hasError:!1,error:null})};render(){const{hasError:t,error:r}=this.state,{children:s,fallback:o,section:i}=this.props;return t?o||n.jsx("div",{className:"flex items-center justify-center p-5 min-h-[100px]",children:n.jsxs(Rt,{variant:"destructive",className:"max-w-[400px]",children:[n.jsx(C.AlertCircle,{className:"size-4"}),n.jsxs(Rs,{children:["Something went wrong",i?` in ${i}`:""]}),n.jsxs(Xt,{className:"mt-2",children:[n.jsx("p",{children:r?.message??"An unexpected error occurred"}),n.jsx(Q,{variant:"destructive",size:"sm",className:"mt-3",onClick:this.handleRetry,children:"Try Again"})]})]})}):s}}function Kd(){const{loading:e,error:t,data:r}=Je();return e?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[n.jsx(C.Database,{className:"size-10 animate-pulse"}),n.jsx("p",{className:"text-sm",children:"Loading schema..."})]}):t?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 max-w-md mx-auto text-center",children:[n.jsx(C.Database,{className:"size-12 text-destructive"}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Connection Error"}),n.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:t.message})]})]}):r.length===0?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 max-w-md mx-auto text-center",children:[n.jsx(C.Database,{className:"size-12 text-muted-foreground/50"}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"No Tables Found"}),n.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"This database doesn't contain any tables. It may be a new or empty database."}),n.jsx("p",{className:"mt-3 text-xs text-muted-foreground/70",children:"Create tables in your database and reconnect, or try a different connection."})]})]}):n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-6 max-w-lg mx-auto text-center",children:[n.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground/50",children:[n.jsx(C.Table2,{className:"size-10"}),n.jsx(C.MousePointerClick,{className:"size-6"})]}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Select a Table"}),n.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Choose a table from the sidebar to browse and edit its data."})]}),n.jsxs("div",{className:"text-xs text-muted-foreground/60 border border-border rounded-md px-4 py-3 bg-muted/30",children:[n.jsxs("p",{className:"font-medium text-muted-foreground mb-1",children:[r.length," table",r.length!==1?"s":""," available"]}),n.jsxs("p",{className:"leading-relaxed",children:[r.slice(0,8).map(s=>s.label).join(", "),r.length>8?`, and ${r.length-8} more`:""]})]})]})}function Wd({children:e}){const{loading:t,error:r}=Je();return t?n.jsxs("div",{className:"flex items-center justify-center flex-1 gap-3 text-muted-foreground",children:[n.jsx(C.Loader2,{className:"size-6 animate-spin"}),n.jsx("span",{className:"text-sm",children:"Connecting to database..."})]}):r?n.jsx("div",{className:"flex items-center justify-center flex-1",children:n.jsxs(Rt,{variant:"destructive",className:"max-w-lg",children:[n.jsx(C.AlertCircle,{className:"size-4"}),n.jsx(Rs,{children:"Database Connection Error"}),n.jsxs(Xt,{className:"mt-2",children:[n.jsx("p",{className:"text-sm",children:r.message}),n.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Check your connection string and ensure the database server is running."})]})]})}):n.jsx(n.Fragment,{children:e})}function Jd(){const[e,t]=u.useState(!0),r=xa({key:"sidebar-width",initial:240,min:150,max:560,axis:"x"});return n.jsx(Wd,{children:n.jsx(Dd,{children:n.jsxs("div",{className:"grid h-full flex-1 min-h-0 grid-rows-[auto_1fr]",style:{gridTemplateColumns:e?`${r.size}px 1fr`:"0px 1fr"},children:[n.jsxs("div",{className:"col-span-full sticky top-0 z-50 bg-background border-b border-border flex items-center",children:[n.jsx(Q,{variant:"ghost",size:"icon",className:"md:hidden ml-1 shrink-0",onClick:()=>t(!e),"aria-label":"Toggle sidebar",title:"Toggle sidebar",children:n.jsx(C.PanelLeft,{className:"size-5"})}),n.jsx("div",{className:"flex-1 min-w-0",children:n.jsx(nr,{section:"Header",children:n.jsxs(lr,{children:[n.jsx(Be,{path:"/:table/*",element:n.jsx(rs,{})}),n.jsx(Be,{path:"/:table",element:n.jsx(rs,{})}),n.jsx(Be,{path:"/",element:n.jsx(rs,{})})]})})})]}),n.jsxs("nav",{"aria-label":"Tables",className:`relative border-r border-border overflow-hidden min-h-0 ${e?"":"hidden"} md:block`,children:[n.jsx(nr,{section:"Table List",children:n.jsx(Rl,{})}),n.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize table list",tabIndex:0,"data-testid":"sidebar-resize-handle",className:"absolute inset-y-0 right-0 w-1.5 cursor-col-resize select-none touch-none hover:bg-primary/40 focus-visible:bg-primary/60 focus-visible:outline-none",onPointerDown:r.onPointerDown,onKeyDown:r.onKeyDown})]}),n.jsxs("main",{className:"flex flex-col overflow-hidden min-h-0 px-1 py-0.5",children:[n.jsx(nr,{section:"Data Panel",children:n.jsxs(lr,{children:[n.jsx(Be,{path:"/:table/from/:filterTable/:id/edit/:editId",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/from/:filterTable/:id",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/:id/edit/:editId",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/:id",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/edit/:editId",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/edit",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/",element:n.jsx(Kd,{})})]})}),n.jsx(nr,{section:"Data Edit",children:n.jsxs(lr,{children:[n.jsx(Be,{path:"/:table/from/:filterTable/:id/edit/:editId",element:n.jsx(Xn,{})}),n.jsx(Be,{path:"/:table/:id/edit/:editId",element:n.jsx(Xn,{})}),n.jsx(Be,{path:"/:table/edit/:editId",element:n.jsx(Xn,{})}),n.jsx(Be,{path:"/:table/edit",element:n.jsx(Xn,{})})]})})]})]})})})}function Qd({onLocate:e}){const t=ps();return u.useEffect(()=>{e?.(t)},[t,e]),n.jsx(Jd,{})}function ya({uri:e,fetcher:t,uiPath:r,onLocate:s,showStats:o=!1,tables:i,defaultColumns:a,trailingColumns:l,tableActions:c}){const m=u.useMemo(()=>t||(e?new ys(e):null),[e,t]),d=u.useMemo(()=>({showStats:o,tables:i,defaultColumns:a,trailingColumns:l,tableActions:c}),[o,i,a,l,c]),f=u.useMemo(()=>new de.QueryClient({defaultOptions:{queries:{staleTime:300*1e3,retry:1}}}),[]);if(!m)throw new Error("Editor requires either a `fetcher` (GraphQLFetcher) or a `uri` prop to reach the GraphQL endpoint; neither was provided.");return n.jsx(de.QueryClientProvider,{client:f,children:n.jsx(js,{value:m,children:n.jsx(Ja,{config:d,children:n.jsx(No,{children:n.jsx(Ma,{path:r||"/",children:n.jsx(Ns,{children:n.jsx(Qd,{onLocate:s})})})})})})})}const Hd=["query","form","report","dashboard"];class va extends Error{constructor(t){super(t),this.name="SavedObjectConflictError"}}const ja="/_saved-objects";function Ud(e=""){const t=`${e}${ja}`,r=encodeURIComponent;async function s(o){try{return(await o.json())?.error??`${o.status} ${o.statusText}`}catch{return`${o.status} ${o.statusText}`}}return{async list(o,i,a){const l=o?`${t}/${r(o)}`:t,c=await fetch(l,{signal:i});if(!c.ok)throw new Error(`Failed to list saved objects: ${await s(c)}`);const m=await c.json();if(!Array.isArray(m))throw new Error("Failed to list saved objects: the server did not return a list.");const d=m.map(rr),f=d.filter(p=>p!==null);return f.length!==d.length&&a?.(d.length-f.length),f},async get(o,i,a){const l=await fetch(`${t}/${r(o)}/${r(i)}`,{signal:a});if(l.status===404)return null;if(!l.ok)throw new Error(`Failed to load saved object: ${await s(l)}`);return rr(await l.json())},async put(o,i){const a=await fetch(`${t}/${r(o.type)}/${r(o.id)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:i});if(a.status===409)throw new va(await s(a));if(!a.ok)throw new Error(`Failed to save object: ${await s(a)}`);const l=rr(await a.json());if(l===null)throw new Error("Server returned a malformed saved object.");return l},async remove(o,i,a){const l=await fetch(`${t}/${r(o)}/${r(i)}`,{method:"DELETE",signal:a});if(!l.ok&&l.status!==404)throw new Error(`Failed to delete saved object: ${await s(l)}`)}}}function rr(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.id!="string"||t.id.length===0||typeof t.type!="string"||!Hd.includes(t.type)||typeof t.name!="string"||typeof t.version!="number"||!("definition"in t)?null:{id:t.id,type:t.type,name:t.name,folder:typeof t.folder=="string"?t.folder:void 0,definition:t.definition,version:t.version}}const Yd=4,Rd=new Set(["text","textarea","number","checkbox","date","datetime","select"]);function Xd(e){return typeof e=="string"&&Rd.has(e)?e:"text"}function Zd(e){return typeof e!="number"||!Number.isFinite(e)?1:Math.min(Yd,Math.max(1,Math.trunc(e)))}function em(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.column!="string"||t.column===""?null:{column:t.column,label:typeof t.label=="string"?t.label:t.column,control:Xd(t.control),readOnly:t.readOnly===!0,required:t.required===!0,include:t.include!==!1}}function tm(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.relationship!="string"||typeof t.childTable!="string"||!Array.isArray(t.parentColumns)||!Array.isArray(t.childColumns)||!t.parentColumns.every(r=>typeof r=="string")||!t.childColumns.every(r=>typeof r=="string")||t.parentColumns.length===0||t.parentColumns.length!==t.childColumns.length?null:{relationship:t.relationship,childTable:t.childTable,parentColumns:t.parentColumns,childColumns:t.childColumns,label:typeof t.label=="string"?t.label:t.childTable,mode:t.mode==="stacked"?"stacked":"grid"}}function nm(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.table!="string"||t.table===""||!Array.isArray(t.fields))return null;const r=t.fields.map(em).filter(s=>s!==null);return r.length===0?null:{table:t.table,title:typeof t.title=="string"?t.title:t.table,columns:Zd(t.columns),fields:r,subforms:Array.isArray(t.subforms)?t.subforms.map(tm).filter(s=>s!==null):void 0}}function wa(e){return e.fields.filter(t=>t.include)}const rm=new Set(["text","textarea","number","checkbox","date","datetime","select"]);function sm(e){return e!==void 0&&rm.has(e)?e:void 0}function om(e,t){return{control:sm(t?.widget)??e.control,readOnly:e.readOnly||t?.readOnly===!0,visible:e.include&&t?.visible!==!1}}function am(e){switch(e){case"textarea":return{kind:"textarea"};case"checkbox":return{kind:"checkbox"};case"select":return{kind:"select"};case"number":return{kind:"input",type:"number"};case"date":return{kind:"input",type:"date"};case"datetime":return{kind:"input",type:"datetime-local"};default:return{kind:"input",type:"text"}}}function Ca(e,t,r){const s=Math.max(0,t-1);switch(r){case"first":return 0;case"last":return s;case"prev":return Math.max(0,Math.min(s,e-1));case"next":return Math.max(0,Math.min(s,e+1))}}function sr(e,t,r){return Ca(e,t,r)!==e}function im(e,t){return t<=0?"0 of 0":`${e+1} of ${t}`}function lm(e,t,r){return r.sourceColumnNames.length>0&&r.sourceColumnNames.length===r.destinationColumnNames.length&&r.sourceColumnNames.every(s=>e.columns.some(o=>o.name===s))&&r.destinationColumnNames.every(s=>t.columns.some(o=>o.name===s))}function cm(e,t,r,s){if(!s||!lm(e,t,r))return null;const o=[],i=[],a={};for(let l=0;l<r.sourceColumnNames.length;l++){const c=r.sourceColumnNames[l],m=r.destinationColumnNames[l],d=s[c];if(d==null)return null;const f=t.columns.find(x=>x.name===m)?.paramType.replace("!","")??"String",p=`parent_${c}`;o.push(`$${p}: ${f}`),i.push(`{${m}: {_eq: $${p}}}`),a[p]=dt(d,f)}return{params:o,filter:i.length===1?i[0]:`{and: [${i.join(", ")}]}`,variables:a}}function um(e,t){return!t||e.sourceColumnNames.length!==e.destinationColumnNames.length?{}:Object.fromEntries(e.destinationColumnNames.map((r,s)=>[r,t[e.sourceColumnNames[s]]]))}function dm(e){return{table:e.name,title:e.label,columns:1,fields:e.columns.map(t=>({column:t.name,label:t.label,control:t.paramType.startsWith("Boolean")?"checkbox":t.paramType.startsWith("Int")||t.paramType.startsWith("Float")||t.paramType.startsWith("Decimal")?"number":"text",readOnly:t.isReadOnly||t.isIdentity,required:!t.isNullable,include:!0}))}}function mm({parent:e,child:t,subform:r,row:s}){const o=$e(),i=de.useQueryClient(),a=Qn(t),[l,c]=u.useState(null),m=u.useMemo(()=>({name:r.relationship,fieldName:r.relationship,sourceColumnNames:r.parentColumns,destinationTable:t.name,destinationColumnNames:r.childColumns}),[r,t.name]),d=u.useMemo(()=>cm(e,t,m,s),[e,t,m,s]),f=u.useMemo(()=>t.columns.map(w=>(je(w.name,"form subform field"),w.name)),[t]),p=u.useMemo(()=>d?(je(t.name,"form subform table"),`query FormSubform_${t.name}(${d.params.join(", ")}) { ${t.name}(filter: ${d.filter}) { data { ${f.join(" ")} } } }`):null,[t.name,f,d]),x=["formSubform",e.name,t.name,He(s,e,0)],{data:h,isLoading:y,error:N}=de.useQuery({queryKey:x,queryFn:()=>o.query(p,d.variables),enabled:!!p}),T=u.useMemo(()=>dm(t),[t]),k=u.useMemo(()=>um(m,s),[m,s]);if(!d)return n.jsx("p",{style:lt.notice,children:"Related records unavailable: this relationship is incomplete."});if(y)return n.jsxs("p",{style:lt.notice,children:["Loading ",r.label,"…"]});if(N)return n.jsxs("p",{role:"alert",style:lt.error,children:["Failed to load ",r.label,": ",N.message]});const $=h?.[t.name]?.data??[],b=async w=>{const F=mt(w,t);F&&(await a.deleteRow(F),await i.invalidateQueries({queryKey:x}))},v=async()=>{c(null),await i.invalidateQueries({queryKey:x})};return n.jsxs("section",{style:lt.root,"aria-label":r.label,children:[n.jsx("h3",{style:lt.title,children:r.label}),n.jsxs("button",{type:"button",onClick:()=>c({kind:"create"}),children:["Add ",r.label]}),l?n.jsx("div",{style:lt.childForm,children:n.jsx(os,{table:t,definition:T,hiddenFields:r.childColumns,initialValues:l.kind==="create"?k:void 0,startInNewMode:l.kind==="create",initialPkRoute:l.kind==="edit"?He(l.row,t,l.index??0):void 0,onClose:()=>{v()}},l.kind==="create"?"create":He(l.row,t,l.index??0))}):$.length===0?n.jsx("p",{style:lt.notice,children:"No related records."}):r.mode==="grid"?n.jsxs("table",{style:lt.table,children:[n.jsx("thead",{children:n.jsxs("tr",{children:[t.columns.map(w=>n.jsx("th",{style:lt.cell,children:w.label},w.name)),n.jsx("th",{})]})}),n.jsx("tbody",{children:$.map((w,F)=>n.jsxs("tr",{children:[t.columns.map(j=>n.jsx("td",{style:lt.cell,children:String(w[j.name]??"")},j.name)),n.jsxs("td",{children:[n.jsx("button",{type:"button",onClick:()=>c({kind:"edit",row:w,index:F}),children:"Edit"}),n.jsx("button",{type:"button",onClick:()=>b(w),disabled:a.isPending,children:"Delete"})]})]},He(w,t,F)))})]}):n.jsx("div",{children:$.map((w,F)=>n.jsxs("article",{style:lt.card,children:[t.columns.map(j=>n.jsxs("div",{children:[n.jsxs("strong",{children:[j.label,": "]}),String(w[j.name]??"")]},j.name)),n.jsx("button",{type:"button",onClick:()=>c({kind:"edit",row:w,index:F}),children:"Edit"}),n.jsx("button",{type:"button",onClick:()=>b(w),disabled:a.isPending,children:"Delete"})]},He(w,t,F)))})]})}const lt={root:{marginTop:20,borderTop:"1px solid #d1d5db",paddingTop:12},title:{margin:"0 0 8px",fontSize:15},notice:{color:"#6b7280",fontSize:13},error:{color:"#b91c1c",fontSize:13},table:{width:"100%",borderCollapse:"collapse",fontSize:13},cell:{textAlign:"left",padding:5,borderBottom:"1px solid #e5e7eb"},card:{border:"1px solid #e5e7eb",borderRadius:6,padding:8,marginBottom:8,fontSize:13},childForm:{minHeight:420,border:"1px solid #e5e7eb",borderRadius:6,marginTop:8}},fm={};function pm(e){const t=e.lastIndexOf(".");return t>=0?e.slice(t+1):e}function ss(e,t){const r=e.findTable(t);if(r)return r;const s=pm(t);return e.data.find(o=>o.graphQlName===t||o.dbName===t||o.graphQlName===s||o.dbName===s)}const hm="\0new";function gm(e,t){const r=new Set;for(const s of e)r.add(s.column.name);for(const s of t.primaryKeys??[])r.add(s);return[...r]}function xm(e,t){je(e.name,"form browse table name");for(const r of t)je(r,"form browse selection field");return`query FormBrowse_${e.name}($limit: Int, $offset: Int) { ${e.name}(limit: $limit offset: $offset) { total data { ${t.join(" ")} } } }`}function or(e,t,r){return e==="checkbox"?!!r:(e==="date"||e==="datetime")&&(r==null||typeof r=="string")?Br(r??void 0,e==="datetime"||Yn(t)&&!1):r==null?"":String(r)}function bm(e,t){const r={fields:{},form:null},s=e?.errors;if(Array.isArray(s)){const o=[];for(const i of s){const a=i.path?.[i.path.length-1];typeof a=="string"&&t.has(a)?r.fields[a]=i.message:o.push(i.message)}return r.form=o.length>0?o.join("; "):null,r}return r.form=e instanceof Error?e.message:String(e),r}function os({table:e,definition:t,fieldMetadata:r,onClose:s,schema:o,initialValues:i=fm,hiddenFields:a=[],startInNewMode:l=!1,initialPkRoute:c}){const m=$e(),d=de.useQueryClient(),f=u.useMemo(()=>new Map(e.columns.map(O=>[O.name,O])),[e]),[p,x]=u.useState(c?{kind:"pk",route:c}:{kind:"offset",index:0}),[h,y]=u.useState(l?"new":"browse"),[N,T]=u.useState(i),[k,$]=u.useState({}),[b,v]=u.useState(null),[w,F]=u.useState(""),[j,V]=u.useState(0),S=h==="new",L=u.useMemo(()=>wa(t).map(O=>{const Z=f.get(O.column);if(!Z)return null;const ee=om(O,r?.[O.column]);return ee.visible?{field:O,column:Z,control:ee.control,readOnly:ee.readOnly}:null}).filter(O=>O!==null),[t,f,r]),A=u.useCallback(O=>!(O.readOnly||O.column.isReadOnly||O.column.isIdentity||O.column.isPrimaryKey&&!S),[S]),D=u.useMemo(()=>L.filter(A).map(O=>({column:O.column})),[L,A]),B=u.useMemo(()=>(e.primaryKeys??[]).map(O=>f.get(O)).filter(O=>!!O),[e,f]),X=u.useMemo(()=>new Set(D.map(O=>O.column.name)),[D]),E=u.useMemo(()=>{const O=new Set(gm(L,e));for(const Z of t.subforms??[])for(const ee of Z.parentColumns)O.add(ee);return[...O]},[L,e,t.subforms]),P=u.useMemo(()=>{if(S||L.length===0)return null;if(p.kind==="offset")return{text:xm(e,E),variables:{limit:1,offset:p.index},kind:"offset"};const O=fn(p.route,e),Z=O?qn(O,e):null;return Z?{text:Cr(e,Z,E),variables:Z.variables,kind:"pk"}:null},[S,L.length,p,e,E]),{data:q,isLoading:U,error:_}=de.useQuery({queryKey:["formRunner",e.name,p,S],queryFn:()=>m.query(P.text,P.variables),enabled:!S&&P!==null}),ce=u.useMemo(()=>!q||!P?null:P.kind==="offset"?q[e.name]?.data?.[0]??null:q.value?.data?.[0]??null,[q,P,e.name]);u.useEffect(()=>{if(q&&P?.kind==="offset"){const O=q[e.name];O&&V(O.total)}},[q,P,e.name]);const he=S?hm:ce?He(ce,e,0):null,Ue=u.useRef(null),Pe=u.useRef(!1);u.useEffect(()=>{if(Ue.current===he&&Pe.current)return;if(Ue.current=he,Pe.current=!1,$({}),v(null),S){T(i);return}const O={};for(const Z of L)O[Z.column.name]=ce?.[Z.column.name]??null;T(O)},[he,ce,S,L,i]);const ie=p.kind==="offset"?p.index:-1,se=u.useMemo(()=>S||!ce?"":He(ce,e,ie<0?0:ie),[S,ce,e,ie]),ke=wn(e,D,B,se),Ae=Qn(e),re=u.useCallback(O=>{y("browse"),x(Z=>{const ee=Z.kind==="offset"?Z.index:0;return{kind:"offset",index:Ca(ee,j,O)}})},[j]),Ee=u.useCallback(()=>{y("new")},[]),Ie=u.useCallback(()=>{const O=w.trim();O!==""&&(y("browse"),x({kind:"pk",route:O}))},[w]),Le=u.useCallback((O,Z)=>{Pe.current=!0,T(ee=>({...ee,[O]:Z}))},[]),Ge=u.useCallback(async()=>{const O={};for(const ee of L){if(!A(ee))continue;const Ce=ee.field.required||!ee.column.isNullable,xe=qr(ee.column,N[ee.column.name],Ce);xe&&(O[ee.column.name]=xe)}if(Object.keys(O).length>0){$(O),v(null);return}$({}),v(null);const Z={};for(const ee of X)Z[ee]=N[ee];try{if(S){const Ce=(await ke.insert(Z))?.[e.name],xe={},qe=e.primaryKeys??[];for(const W of qe){const me=f.get(W);xe[W]=qe.length===1&&me?.isIdentity?Ce:N[W]}y("browse"),x({kind:"pk",route:Vn(xe,e)})}else await ke.update(Z),Pe.current=!1,await d.invalidateQueries({queryKey:["formRunner",e.name]})}catch(ee){const Ce=bm(ee,X);$(Ce.fields),v(Ce.form)}},[L,A,N,X,S,ke,e,f,d]),Oe=u.useCallback(async()=>{const O=mt(ce,e);if(O)try{await Ae.deleteRow(O),y("browse"),x({kind:"offset",index:Math.max(0,(ie<0?0:ie)-1)}),await d.invalidateQueries({queryKey:["formRunner",e.name]})}catch(Z){v(Z instanceof Error?Z.message:String(Z))}},[ce,e,Ae,ie,d]);if(L.length===0)return n.jsx("div",{style:fe.notice,children:"This form has no fields that match the current schema."});const ye=p.kind==="pk"?`key ${p.route}`:im(ie,j),ze=!S&&p.kind==="offset"&&j===0&&!U;return n.jsxs("div",{style:fe.root,children:[n.jsxs("div",{style:fe.toolbar,role:"toolbar","aria-label":"Record navigation",children:[n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("first"),disabled:S||!sr(ie,j,"first"),"aria-label":"First record",children:"⏮"}),n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("prev"),disabled:S||!sr(ie,j,"prev"),"aria-label":"Previous record",children:"◀"}),n.jsx("span",{style:fe.position,"aria-label":"Record position",children:S?"New record":ye}),n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("next"),disabled:S||!sr(ie,j,"next"),"aria-label":"Next record",children:"▶"}),n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("last"),disabled:S||!sr(ie,j,"last"),"aria-label":"Last record",children:"⏭"}),n.jsx("span",{style:fe.spacer}),n.jsx("input",{style:fe.jump,value:w,onChange:O=>F(O.target.value),placeholder:"Jump to key…","aria-label":"Jump to key"}),n.jsx("button",{type:"button",style:fe.btn,onClick:Ie,"aria-label":"Go to key",children:"Go"}),n.jsx("button",{type:"button",style:fe.btn,onClick:Ee,"aria-label":"New record",children:"New"}),s&&n.jsx("button",{type:"button",style:fe.btn,onClick:s,"aria-label":"Close form",children:"✕"})]}),n.jsxs("div",{style:fe.body,children:[n.jsx("h2",{style:fe.title,children:t.title}),b&&n.jsx("div",{role:"alert",style:fe.formError,children:b}),_&&n.jsxs("div",{role:"alert",style:fe.formError,children:["Failed to load record: ",_.message]}),ze?n.jsx("p",{style:fe.notice,children:"No records. Use “New” to create one."}):n.jsx("div",{style:{...fe.grid,gridTemplateColumns:`repeat(${t.columns}, minmax(0, 1fr))`},children:L.filter(O=>!a.includes(O.column.name)).map(O=>{const Z=A(O),ee=N[O.column.name],Ce=k[O.column.name],xe=O.field.required||!O.column.isNullable;return n.jsxs("label",{style:fe.field,children:[n.jsxs("span",{style:fe.label,children:[O.field.label,xe&&n.jsx("span",{style:fe.req,children:" *"})]}),ym(O,ee,Z,xe,Le),Ce&&n.jsx("span",{role:"alert",style:fe.fieldError,children:Ce})]},O.column.name)})}),!S&&ce&&o&&(t.subforms??[]).map(O=>{const Z=ss(o,O.childTable);return Z?n.jsx(mm,{parent:e,child:Z,subform:O,row:ce},O.relationship):n.jsxs("p",{style:fe.notice,children:[O.label," is not available in this schema."]},O.relationship)})]}),n.jsxs("div",{style:fe.footer,children:[n.jsx("button",{type:"button",style:fe.primaryBtn,onClick:Ge,disabled:ke.isPending||ze&&!S,children:S?"Create":"Save"}),!S&&!ze&&n.jsx("button",{type:"button",style:fe.btn,onClick:Oe,disabled:Ae.isPending,children:"Delete"})]})]})}function ym(e,t,r,s,o){const i=e.column.name,a=am(e.control),l={id:i,"aria-label":e.field.label,disabled:!r,style:fe.control};if(a.kind==="checkbox")return n.jsx("input",{...l,type:"checkbox",checked:!!or("checkbox",e.column,t),onChange:c=>o(i,c.target.checked)});if(a.kind==="textarea")return n.jsx("textarea",{...l,rows:3,required:s,value:String(or("text",e.column,t)),onChange:c=>o(i,c.target.value)});if(a.kind==="select"){const c=e.column.enumValues??[],m=e.column.enumLabels&&e.column.enumLabels.length===c.length?e.column.enumLabels:c;return n.jsxs("select",{...l,value:String(or("text",e.column,t)),onChange:d=>o(i,d.target.value===""?null:d.target.value),children:[!s&&n.jsx("option",{value:"",children:"(none)"}),c.map((d,f)=>n.jsx("option",{value:d,children:m[f]??d},d))]})}return n.jsx("input",{...l,type:a.type,required:s,value:String(or(e.control,e.column,t)),onChange:c=>o(i,c.target.value)})}function Na({definition:e,fieldMetadata:t,onClose:r}){const s=Je();if(s.loading)return n.jsx("div",{style:fe.notice,children:"Loading schema…"});if(s.error)return n.jsxs("div",{style:fe.notice,children:["Could not load schema: ",s.error.message]});const o=ss(s,e.table);return o?n.jsx(os,{table:o,definition:e,fieldMetadata:t,onClose:r,schema:s}):n.jsxs("div",{style:fe.notice,children:["Table “",e.table,"” is not in the current schema."]})}const fe={root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},toolbar:{display:"flex",alignItems:"center",gap:6,padding:"8px 12px",borderBottom:"1px solid var(--border, #d1d5db)",flexWrap:"wrap"},position:{fontSize:13,color:"#374151",minWidth:80,textAlign:"center"},spacer:{flex:1},jump:{padding:"4px 6px",border:"1px solid var(--border, #d1d5db)",borderRadius:6,font:"inherit",fontSize:13,width:120},body:{flex:1,minHeight:0,overflow:"auto",padding:16},title:{margin:"0 0 16px",fontSize:18},grid:{display:"grid",gap:14,maxWidth:720},field:{display:"flex",flexDirection:"column",gap:4,minWidth:0},label:{fontSize:12,fontWeight:600,color:"#374151"},control:{padding:"6px 8px",border:"1px solid var(--border, #d1d5db)",borderRadius:6,font:"inherit",fontSize:13},footer:{display:"flex",gap:8,padding:"8px 12px",borderTop:"1px solid var(--border, #d1d5db)"},btn:{border:"1px solid var(--border, #d1d5db)",background:"transparent",borderRadius:6,padding:"6px 12px",cursor:"pointer",font:"inherit"},primaryBtn:{border:"1px solid #2563eb",background:"#2563eb",color:"#fff",borderRadius:6,padding:"6px 16px",cursor:"pointer",font:"inherit"},req:{color:"#dc2626"},formError:{background:"#fef2f2",border:"1px solid #fecaca",color:"#b91c1c",borderRadius:6,padding:"8px 10px",marginBottom:12,fontSize:13},fieldError:{color:"#dc2626",fontSize:12},notice:{padding:24,color:"#6b7280"}};function vm({fetcher:e,definition:t,fieldMetadata:r,onClose:s}){const o=u.useMemo(()=>new de.QueryClient({defaultOptions:{queries:{staleTime:3e5,retry:1}}}),[]);return n.jsx(de.QueryClientProvider,{client:o,children:n.jsx(js,{value:e,children:n.jsx(No,{children:n.jsx(Ns,{children:n.jsx(Na,{definition:t,fieldMetadata:r,onClose:s})})})})})}ae.DEFAULT_ROW_CAP=Pr,ae.Editor=ya,ae.FormRunner=Na,ae.FormRunnerHost=vm,ae.FormRunnerView=os,ae.GraphQLRequestError=bs,ae.HttpGraphQLFetcher=ys,ae.SAVED_OBJECTS_PATH=ja,ae.SavedObjectConflictError=va,ae.UTF8_BOM=bo,ae.buildCsv=yo,ae.buildJson=wo,ae.createSavedObjectsClient=Ud,ae.default=ya,ae.deserializeColumnFilters=jr,ae.downloadTextFile=Mr,ae.exportAllRows=_r,ae.filenameFor=Dr,ae.formatCsvCell=Er,ae.mimeFor=zr,ae.parseFormDefinition=nm,ae.parseSavedObject=rr,ae.resolveDefinitionTable=ss,ae.serializeColumnFilters=vr,ae.useTableMutation=wn,ae.visibleFields=wa,Object.defineProperties(ae,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));
120
+ }`},[e,t,a]),{isLoading:m,error:d,data:p}=de.useQuery({queryKey:["editRecord",e.name,r],queryFn:()=>s.query(c,a.variables),enabled:!!e&&!o&&a.filterText!==""}),f=p?.value?.data?.at(0),x=!o&&p!==void 0&&f===void 0,h=u.useMemo(()=>f??{},[f]),b=u.useMemo(()=>{const N={};for(const{column:T,fkRole:k}of t){const E=Tu(T,k);if(Rn(T))N[T.name]=Vr(h[T.name],qr(T));else if(Kr.some(y=>y===T.paramType)){const y=h[T.name];N[T.name]=T.isNullable&&y==null?null:!!y}else if(Ft(T)){const y=h[T.name];N[T.name]=y==null?"":JSON.stringify(y,null,2)}else if(E){const y=h[T.name];N[T.name]=y??null}else N[T.name]=h[T.name]??""}return N},[h,t]);return{isLoading:m,error:d,value:h,defaultValues:b,pkResolveFailed:l,recordNotFound:x}}function Fu({table:e,schema:t,editId:r,onClose:s}){const o=r===void 0||r==="",[i,a,l]=$u(t,e),c=i.labelColumn,m=i.label,d=wn(i,a,l,r),{isLoading:p,error:f,value:x,defaultValues:h,pkResolveFailed:b,recordNotFound:N}=Eu(i,a,r),T=Tn.useForm({defaultValues:h,onSubmit:async({value:$})=>{const L=wu($,x,a.map(({column:D})=>D));await(o?d.insert:d.update)(L),s()}}),k=Tn.useStore(T.store,$=>$.isDirty),[E,y]=u.useState(!1),v=()=>{k?y(!0):s()};if(p&&!o)return n.jsx(jt,{open:!0,onOpenChange:$=>{$||s()},children:n.jsxs(wt,{showCloseButton:!1,className:"sm:max-w-2xl",children:[n.jsx(Ct,{className:"sr-only",children:"Loading record"}),n.jsx(Kt,{className:"sr-only",children:"Loading record for editing"}),n.jsxs("div",{className:"flex items-center justify-center gap-2 py-10 text-sm text-muted-foreground",children:[n.jsx(w.LoaderCircle,{className:"size-4 animate-spin"}),"Loading…"]})]})});if(f)return n.jsxs("div",{children:["Error: ",f.message]});if(b||N)return n.jsx(jt,{open:!0,onOpenChange:$=>{$||s()},children:n.jsxs(wt,{showCloseButton:!1,className:"sm:max-w-md",children:[n.jsx(Ct,{className:"text-sm font-semibold",children:"Cannot edit record"}),n.jsxs(Kt,{className:"text-sm text-muted-foreground",children:[b?`This record can't be opened for editing: its key (${r||"empty"}) is missing or malformed for the ${m} table.`:`No ${m} record matches the key ${r}. It may have been deleted or is no longer visible to you.`," ","Return to the grid and try again."]}),n.jsx("div",{className:"flex justify-end",children:n.jsx(Q,{type:"button",size:"sm",onClick:s,children:"Close"})})]})});const j=x?.[c]??r,S=a.filter(({column:$})=>Kr.some(L=>L===$.paramType)),C=a.filter(({column:$})=>Yo($)),B=a.filter(({column:$})=>!Kr.some(L=>L===$.paramType)&&!Yo($));return n.jsxs(jt,{open:!0,onOpenChange:$=>{$||v()},children:[n.jsxs(wt,{showCloseButton:!1,className:"sm:max-w-2xl max-h-[90vh] flex flex-col gap-0 p-0 overflow-hidden",children:[n.jsxs("div",{className:"flex items-center justify-between px-5 py-3 border-b border-border bg-muted/30 shrink-0",children:[n.jsxs("div",{className:"min-w-0",children:[n.jsx(Ct,{className:"text-sm font-semibold truncate",children:o?`New ${m}`:`${m} : ${j}`}),n.jsxs(Kt,{className:"sr-only",children:[o?"Create":"Edit"," ",m," record"]})]}),n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:v,"aria-label":"Close",className:"shrink-0 -mr-1",children:n.jsx(w.X,{className:"size-4"})})]}),d.error&&n.jsxs("div",{className:"flex items-center gap-2 px-5 py-2 bg-destructive/10 border-b border-destructive/20 text-destructive text-sm shrink-0",children:[n.jsx(w.AlertCircle,{className:"size-3.5 shrink-0"}),n.jsx("span",{className:"truncate",children:d.error.message})]}),n.jsxs("form",{onSubmit:$=>{$.preventDefault(),$.stopPropagation(),T.handleSubmit().catch(()=>{})},className:"flex flex-col flex-1 min-h-0",children:[n.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[B.length>0&&n.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-3",children:B.map(({column:$,join:L,fkRole:q})=>n.jsx(zu,{column:$,join:L,fkRole:q,form:T,schema:t},$.name))}),S.length>0&&n.jsx("div",{className:B.length>0?"mt-4 pt-4 border-t border-border":"",children:n.jsx("div",{className:"flex flex-wrap gap-x-6 gap-y-2",children:S.map(({column:$})=>n.jsx(Mu,{column:$,form:T},$.name))})}),C.length>0&&n.jsx("div",{className:B.length>0||S.length>0?"mt-4 pt-4 border-t border-border":"",children:n.jsx("div",{className:"grid gap-3",children:C.map(({column:$})=>n.jsx(Iu,{column:$,form:T},$.name))})})]}),n.jsxs("div",{className:"flex items-center justify-end gap-2 px-5 py-3 border-t border-border bg-muted/30 shrink-0",children:[n.jsx(Q,{type:"button",variant:"outline",size:"sm",onClick:v,children:"Cancel"}),n.jsxs(Q,{type:"submit",size:"sm",disabled:d.isPending,children:[d.isPending?n.jsx(w.LoaderCircle,{className:"size-3.5 animate-spin"}):n.jsx(w.Save,{className:"size-3.5"}),o?"Create":"Save"]})]})]})]}),n.jsx(Gr,{open:E,onOpenChange:y,title:"Discard unsaved changes?",description:n.jsx("p",{children:"You have unsaved changes. Closing now will discard them."}),confirmLabel:"Discard",cancelLabel:"Keep editing",variant:"destructive",onConfirm:()=>{y(!1),s()}})]})}function Zn(){const{table:e,editId:t}=lr(),r=_n();if(!e)return n.jsx("div",{children:"Table missing"});const s=t?"../..":"..";return n.jsx(Xo,{table:e,editId:t??"",onClose:()=>r(s)})}function Xo({table:e,editId:t,onClose:r}){const s=Je();return e?s.loading?n.jsx("div",{children:"Loading..."}):s.error?n.jsxs("div",{children:["Error: ",s.error.message]}):s.findTable(e)?n.jsx(Fu,{table:e,schema:s,editId:t,onClose:r}):n.jsxs("div",{className:"p-4 text-sm text-destructive",children:["Table not found: ",e]}):n.jsx("div",{children:"Table missing"})}function _u({current:e,max:t}){const r=t-e,s=r<=10&&r>0,o=r<=0;return n.jsx("div",{className:"text-xs text-right mt-0.5","aria-live":"polite",children:n.jsxs("span",{className:o?"text-destructive font-medium":s?"text-amber-500":"text-muted-foreground",children:[e,"/",t]})})}function Pu({min:e,max:t,step:r}){if(e===void 0&&t===void 0)return null;let s="";return e!=null&&t!==void 0&&t!==null?s=`Range: ${e} to ${t}`:e!=null?s=`Min: ${e}`:t!=null&&(s=`Max: ${t}`),r!=null&&r!==1&&(s+=` (step: ${r})`),n.jsx("div",{className:"text-xs text-muted-foreground mt-0.5","aria-live":"polite",children:s})}function zu({column:e,join:t,fkRole:r,form:s,schema:o}){const i=e.name,a=!e.isNullable;if(r==="member-composite")return null;const l=Rn(e),c=Vt(e.paramType),m=e.maxLength&&e.maxLength>0&&!l&&!c;if(e.enumValues&&e.enumValues.length>0)return n.jsx(Du,{column:e,form:s,isRequired:a});if(t&&o)return r==="anchor-composite"?n.jsx(Ou,{column:e,join:t,form:s,schema:o,isRequired:a}):n.jsx(Lu,{column:e,join:t,form:s,schema:o,isRequired:a});const d=Bt(e.paramType),p=e.inputType||(l?qr(e)?"datetime-local":"date":d?"text":c?"number":"text"),f=d?qt(e.paramType)?"numeric":"decimal":void 0,x=`${i}-error`;return n.jsx(s.Field,{name:i,validators:Nn(e,a),children:h=>{const{ariaProps:b}=Xn(h,x);return n.jsxs("div",{className:"grid gap-1",children:[n.jsxs(Wt,{htmlFor:i,className:"text-xs text-muted-foreground",children:[e.label,a&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),n.jsx(Qe,{id:i,type:p,inputMode:f,value:h.state.value??"",onChange:N=>h.handleChange(N.target.value),onBlur:h.handleBlur,required:a,maxLength:e.maxLength,minLength:e.minLength,min:e.min,max:e.max,step:e.step,pattern:e.pattern,title:e.patternMessage,...b,className:"h-8 text-sm"}),m&&n.jsx(_u,{current:String(h.state.value??"").length,max:e.maxLength}),c&&(e.min!==void 0||e.max!==void 0)&&n.jsx(Pu,{min:e.min,max:e.max,step:e.step}),n.jsx(er,{errors:h.state.meta.errors,id:x})]})}})}function Du({column:e,form:t,isRequired:r}){const s=e.name,o=e.enumValues||[],i=e.enumLabels&&e.enumLabels.length===o.length?e.enumLabels:o,a=`${s}-error`;return n.jsx(t.Field,{name:s,validators:Nn(e,r),children:l=>{const{ariaProps:c}=Xn(l,a);return n.jsxs("div",{className:"grid gap-1",children:[n.jsxs(Wt,{htmlFor:s,className:"text-xs text-muted-foreground",children:[e.label,r&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),n.jsxs(Ze,{value:Uo(l.state.value,!r),onValueChange:Wr(m=>l.handleChange(m===Dt?null:m)),children:[n.jsx(tt,{id:s,className:"w-full h-8 text-sm",...c,children:n.jsx(et,{placeholder:`Select ${e.label}`})}),n.jsxs(nt,{children:[!r&&n.jsx(we,{value:Dt,className:"text-muted-foreground",children:"(none)"}),o.map((m,d)=>n.jsx(we,{value:m,children:i[d]||m},m))]})]}),n.jsx(er,{errors:l.state.meta.errors,id:a})]})}})}const Jr="true",Zo="false";function Mu({column:e,form:t}){const r=e.name;return e.isNullable?n.jsx(t.Field,{name:r,children:s=>{const o=s.state.value,i=o==null?Dt:o?Jr:Zo;return n.jsxs("div",{className:"grid gap-1 min-w-[10rem]",children:[n.jsx(Wt,{htmlFor:r,className:"text-xs text-muted-foreground",children:e.label}),n.jsxs(Ze,{value:i,onValueChange:Wr(a=>s.handleChange(a===Dt?null:a===Jr)),children:[n.jsx(tt,{id:r,className:"w-full h-8 text-sm",children:n.jsx(et,{})}),n.jsxs(nt,{children:[n.jsx(we,{value:Dt,className:"text-muted-foreground",children:"(unset)"}),n.jsx(we,{value:Jr,children:"Yes"}),n.jsx(we,{value:Zo,children:"No"})]})]})]})}}):n.jsx(t.Field,{name:r,children:s=>n.jsxs("label",{htmlFor:r,className:"flex items-center gap-2 cursor-pointer select-none",children:[n.jsx(Cn,{id:r,checked:!!s.state.value,onCheckedChange:o=>s.handleChange(!!o),onBlur:s.handleBlur}),n.jsx("span",{className:"text-sm",children:e.label})]})})}function Iu({column:e,form:t}){const r=e.name,s=!e.isNullable,o=`${r}-error`;return n.jsx(t.Field,{name:r,validators:Nn(e,s),children:i=>{const{hasError:a}=Xn(i,o);return n.jsxs("div",{className:"grid gap-1",children:[n.jsxs(Wt,{htmlFor:r,className:"text-xs text-muted-foreground",children:[e.label,s&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"})]}),n.jsx(ku,{name:r,label:e.label,value:String(i.state.value??""),dbType:e.dbType,onChange:l=>i.handleChange(l),onBlur:i.handleBlur,required:s,invalid:a}),n.jsx(er,{errors:i.state.meta.errors,id:o})]})}})}function ea(){const[e,t]=u.useState(""),[r,s]=u.useState(""),[o,i]=u.useState(!1);return u.useEffect(()=>{const l=setTimeout(()=>s(e),300);return()=>clearTimeout(l)},[e]),{search:e,setSearch:t,debounced:r,open:o,onOpenChange:l=>{i(l),l||(t(""),s(""))}}}function ta({field:e,column:t,isRequired:r,errorId:s,value:o,onValueChange:i,search:a,setSearch:l,onOpenChange:c,loadError:m,composite:d,children:p}){const{ariaProps:f}=Xn(e,s);return n.jsxs("div",{className:d?"grid gap-1 sm:col-span-2":"grid gap-1",children:[n.jsxs(Wt,{htmlFor:t.name,className:"text-xs text-muted-foreground",children:[t.label,r&&n.jsx("span",{className:"text-destructive ml-0.5",children:"*"}),d&&n.jsxs("span",{className:"ml-2 px-1 rounded bg-primary/10 text-[10px] font-medium text-primary",children:["composite FK (",d.cols," cols)"]})]}),n.jsxs(Ze,{value:o,onValueChange:Wr(i),onOpenChange:c,children:[n.jsx(tt,{id:t.name,className:"w-full h-8 text-sm",...f,children:n.jsx(et,{placeholder:`Select ${t.label}`})}),n.jsxs(nt,{children:[n.jsx("div",{className:"px-1 pb-1 sticky top-0 bg-popover z-10",children:n.jsx(Qe,{value:a,onChange:x=>l(x.target.value),onKeyDown:x=>{(x.key.length===1||x.key==="Backspace"||x.key==="Delete")&&x.stopPropagation()},placeholder:"Search…",className:"h-7 text-xs"})}),p]})]}),m!=null&&n.jsxs("p",{className:"text-xs text-destructive",role:"alert",children:["Failed to load ",t.label," options: ",String(m?.message??m)]}),n.jsx(er,{errors:e.state.meta.errors,id:s})]})}function Lu({column:e,join:t,form:r,schema:s,isRequired:o}){const i=e.name,a=t.destinationColumnNames[0],{search:l,setSearch:c,debounced:m,open:d,onOpenChange:p}=ea(),f=gu(s,t.destinationTable,a,m,d),x=Tn.useStore(r.store,y=>y.values?.[i]),h=x==null||x===""||f.data.some(y=>String(y.key)===String(x)),b=xu(s,t.destinationTable,a,!f.loading&&!h?x:null),N=`${i}-error`,T=m.trim(),k=f.serverSearch||!T?f.data:f.data.filter(y=>Jo(y,"key",T)),E=x==null||x===""?null:f.data.find(y=>String(y.key)===String(x))??b.value??{key:String(x),label:String(x)};return n.jsx(r.Field,{name:i,validators:Nn(e,o),children:y=>n.jsxs(ta,{field:y,column:e,isRequired:o,errorId:N,value:Uo(y.state.value,!o),onValueChange:v=>y.handleChange(v===Dt?null:v),search:l,setSearch:c,onOpenChange:p,loadError:f.error,children:[!o&&n.jsx(we,{value:Dt,className:"text-muted-foreground",children:"(none)"}),E&&!k.some(v=>String(v.key)===String(E.key))&&n.jsx(we,{value:String(E.key),children:E.label}),k.map(v=>n.jsx(we,{value:String(v.key),children:v.label},v.key)),k.length===0&&n.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No matches."})]})})}function Ou({column:e,join:t,form:r,schema:s,isRequired:o}){const i=u.useMemo(()=>t.sourceColumnNames??[],[t.sourceColumnNames]),a=u.useMemo(()=>t.destinationColumnNames??[],[t.destinationColumnNames]),{search:l,setSearch:c,debounced:m,open:d,onOpenChange:p}=ea(),f=Tn.useStore(r.store,E=>{const y={};for(let v=0;v<i.length;v++)y[a[v]]=E.values?.[i[v]];return y}),x=vu(s,t.destinationTable,a,{search:m,enabled:d,currentValues:f}),h=u.useMemo(()=>{const E=[];for(let y=0;y<i.length;y++){const v=f[a[y]];if(v==null||v==="")return"";E.push(v)}return $t(E)},[f,i,a]),b=m.trim(),N=x.serverSearch||!b?x.data:x.data.filter(E=>E.label.toLowerCase().includes(b.toLowerCase())),T=E=>{const y=x.data.find(v=>v.route===E);if(y)for(let v=0;v<i.length;v++){const j=a[v],S=i[v];r.setFieldValue(S,y.values[j])}},k=`${e.name}-error`;return n.jsx(r.Field,{name:e.name,validators:Nn(e,o),children:E=>n.jsxs(ta,{field:E,column:e,isRequired:o,errorId:k,value:h,onValueChange:T,search:l,setSearch:c,onOpenChange:p,loadError:x.error,composite:{cols:i.length},children:[N.map(y=>n.jsx(we,{value:y.route,children:y.label},y.route)),N.length===0&&n.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No matches."})]})})}function er({errors:e,id:t}){return e.length===0?null:n.jsx("div",{id:t,role:"alert",children:e.map((r,s)=>n.jsx("p",{className:"text-xs text-destructive",children:String(r)},s))})}const na=40,ra=32;function Au({className:e,...t}){return n.jsx("div",{"data-slot":"table-container",className:"relative w-full h-full overflow-x-auto",children:n.jsx("table",{"data-slot":"table",className:Y("min-w-full caption-bottom text-sm border-separate border-spacing-0",e),...t})})}function qu({className:e,...t}){return n.jsx("thead",{"data-slot":"table-header",className:Y("[&_tr]:border-b",e),...t})}function Vu({className:e,...t}){return n.jsx("tbody",{"data-slot":"table-body",className:Y("[&_tr:last-child]:border-0 [&_tr:nth-child(even)]:bg-muted/25",e),...t})}function tr({className:e,style:t,...r}){return n.jsx("tr",{"data-slot":"table-row",className:Y("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",e),style:{height:na,...t},...r})}function Bu({className:e,style:t,...r}){return n.jsx("th",{"data-slot":"table-head",className:Y("px-2 text-left align-middle font-medium whitespace-nowrap text-muted-foreground text-xs border-r border-border last:border-r-0 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),style:{height:ra,...t},...r})}function Qr({className:e,...t}){return n.jsx("td",{"data-slot":"table-cell",className:Y("px-2 py-1 align-middle whitespace-nowrap text-[13px] overflow-hidden text-ellipsis border-r border-border last:border-r-0 [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",e),...t})}function Gu({anchorEl:e,onEdit:t,onDelete:r,onMouseEnter:s,onDismiss:o}){const i=u.useRef(null);return u.useEffect(()=>{const a=i.current;return a?((()=>{const c=e.getBoundingClientRect(),m=a.offsetHeight,d=a.offsetWidth;a.style.top=`${c.top+(c.height-m)/2}px`;const p=Math.min(c.right-d-8,window.innerWidth-d-8);a.style.left=`${Math.max(8,p)}px`})(),a.showPopover(),()=>{try{a.hidePopover()}catch{}}):void 0},[e]),u.useEffect(()=>{const a=l=>{const c=i.current;c&&!c.contains(l.target)&&o()};return document.addEventListener("pointerdown",a),()=>document.removeEventListener("pointerdown",a)},[o]),n.jsxs("div",{ref:i,popover:"manual",className:"flex items-center gap-0.5 rounded-md border border-border bg-popover px-1 py-0.5 shadow-md m-0",style:{position:"fixed"},onClick:a=>a.stopPropagation(),onMouseEnter:s,onMouseLeave:o,onFocusCapture:s,onBlur:a=>{a.currentTarget.contains(a.relatedTarget)||o()},children:[t&&n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:t,"aria-label":"Edit row",title:"Edit",className:"size-6",children:n.jsx(w.Pencil,{className:"size-3.5"})}),r&&n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:r,"aria-label":"Delete row",title:"Delete",className:"size-6 text-destructive hover:text-destructive",children:n.jsx(w.Trash2,{className:"size-3.5"})})]})}function Ku({exportRows:e,total:t,tableName:r,rowCap:s=Pr}){const{toast:o}=vt(),i=Co(),[a,l]=u.useState(!1),[c,m]=u.useState(0),d=u.useRef(null);u.useEffect(()=>()=>d.current?.abort(),[]);const p=u.useCallback(async x=>{if(a||t>s&&typeof window<"u"&&!window.confirm(`This export has ${t.toLocaleString()} rows, over the ${s.toLocaleString()} row limit. Only the first ${s.toLocaleString()} rows will be exported. Continue?`))return;const h=new AbortController;d.current=h,l(!0),m(0);try{const b=await e({format:x,signal:h.signal,rowCap:s,onProgress:N=>m(N)});if(!b)return;await i(Dr(r,x),b.content,zr(x)),b.truncated&&o(`Export truncated at ${b.rowCount.toLocaleString()} rows.`,"error")}catch(b){if(h.signal.aborted)return;o(`Export failed: ${b instanceof Error?b.message:String(b)}`,"error")}finally{l(!1),d.current=null}},[a,t,s,e,r,o,i]),f=u.useCallback(()=>d.current?.abort(),[]);return a?n.jsxs(Q,{variant:"outline",size:"sm",onClick:f,title:"Cancel export",children:[n.jsx(w.X,{className:"size-3.5"}),"Cancel (",c.toLocaleString(),")"]}):n.jsxs(On,{children:[n.jsx(An,{asChild:!0,children:n.jsxs(Q,{variant:"outline",size:"sm",children:[n.jsx(w.Download,{className:"size-3.5"}),"Export",n.jsx(w.ChevronDown,{className:"size-3.5"})]})}),n.jsxs(qn,{align:"end",children:[n.jsx(bt,{onClick:()=>{p("csv")},children:"CSV"}),n.jsx(bt,{onClick:()=>{p("json")},children:"JSON"})]})]})}const Hr=60,sa=450,Wu=150,Ur="bifrost-col-sizes:";function oa(e){try{const t=localStorage.getItem(Ur+e);return t?Ju(JSON.parse(t)):{}}catch{return{}}}function Ju(e){if(typeof e!="object"||e===null||Array.isArray(e))return{};const t={};for(const[r,s]of Object.entries(e))typeof s!="number"||!Number.isFinite(s)||(t[r]=Math.min(Math.max(s,Hr),sa));return t}function Yr(e,t){try{Object.keys(t).length===0?localStorage.removeItem(Ur+e):localStorage.setItem(Ur+e,JSON.stringify(t))}catch{}}function Qu(e){const[t,r]=u.useState(()=>e?oa(e):{}),s=u.useRef(null),o=u.useRef(!0);u.useEffect(()=>{const a=s.current;if(a&&a.tableName!==e&&(s.current=null,Yr(a.tableName,a.sizing)),!e)return;if(o.current){o.current=!1;return}s.current={tableName:e,sizing:t};const l=setTimeout(()=>{s.current=null,Yr(e,t)},300);return()=>clearTimeout(l)},[e,t]),u.useEffect(()=>()=>{const a=s.current;a&&Yr(a.tableName,a.sizing)},[]);const i=u.useRef(e);if(e&&e!==i.current){i.current=e,o.current=!0;const a=oa(e);r(a)}return{columnSizing:t,setColumnSizing:r}}const Hu="bifrost-col-visibility:";function Rr(e){return Hu+e}function Xr(e){try{const t=localStorage.getItem(Rr(e));return t?Uu(JSON.parse(t)):null}catch{return null}}function Uu(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;const t={};for(const[r,s]of Object.entries(e))typeof s=="boolean"&&(t[r]=s);return t}function Yu(e,t){try{localStorage.setItem(Rr(e),JSON.stringify(t))}catch{}}function Ru(e){try{localStorage.removeItem(Rr(e))}catch{}}function Xu(e,t){if(!t||t.length===0)return{};const r=new Set(t),s={};for(const o of e)s[o]=r.has(o);return s}function Zu(e,t){const[r,s]=u.useState(()=>(e?Xr(e):null)??t),o=u.useRef(r),i=u.useCallback(d=>{o.current=d,s(d)},[]),a=u.useCallback(d=>{const p=typeof d=="function"?d(o.current):d;i(p),e&&Yu(e,p)},[i,e]),l=u.useCallback(()=>{e&&Ru(e),i(t)},[i,t,e]),c=u.useRef(e);e&&e!==c.current&&(c.current=e,i(Xr(e)??t));const m=u.useRef(t);return e&&m.current!==t&&(m.current=t,Xr(e)===null&&i(t)),{columnVisibility:r,setColumnVisibility:a,resetColumnVisibility:l}}const ed=500;function td(){const[e,t]=u.useState(null),r=u.useRef(null),s=u.useCallback((f,x)=>{r.current&&(clearTimeout(r.current),r.current=null),t({rowId:f,el:x})},[]),o=u.useCallback(()=>{r.current&&clearTimeout(r.current),r.current=setTimeout(()=>t(null),150)},[]),i=u.useCallback(()=>{r.current&&(clearTimeout(r.current),r.current=null)},[]),a=u.useRef(null),l=u.useRef(!1),c=u.useRef(!1),m=u.useCallback(()=>{a.current&&(clearTimeout(a.current),a.current=null)},[]),d=u.useCallback((f,x,h)=>{h.pointerType==="touch"&&(l.current=!1,m(),a.current=setTimeout(()=>{l.current||(c.current=!0,s(f,x))},ed))},[m,s]),p=u.useCallback(()=>{l.current=!0,m()},[m]);return{hoveredRow:e,hoverRow:s,scheduleDismiss:o,cancelDismiss:i,suppressClick:c,startPress:d,onPressMove:p,cancelPress:m}}const Zr=-1;function nd(e){return Math.max(5,Math.floor((e-ra)/na))}function rd(e,t){const[r,s]=u.useState(!0),o=u.useRef(0),i=u.useCallback(()=>{const a=e.current;return a?nd(a.clientHeight):10},[e]);return u.useEffect(()=>{if(!r)return;const a=e.current;if(!a)return;const l=()=>{const p=i();p!==o.current&&(o.current=p,t(p))},c=requestAnimationFrame(l);let m=null;const d=new ResizeObserver(()=>{m&&clearTimeout(m),m=setTimeout(()=>requestAnimationFrame(l),200)});return d.observe(a),()=>{cancelAnimationFrame(c),m&&clearTimeout(m),d.disconnect()}},[r,i,t,e]),{fitMode:r,setFitMode:s,computeFitSize:i}}function sd(e){return e.id??("accessorKey"in e?String(e.accessorKey):void 0)}function aa(e,t){return t.map(r=>e.find(s=>sd(s)===r)).filter(r=>r!==void 0)}function od(e,{leading:t,trailing:r}){const s=t?aa(e,t):[],o=r?aa(e,r):[];if(s.length===0&&o.length===0)return e;const i=new Set([...s,...o]),a=e.filter(l=>!i.has(l));return[...s,...a,...o]}function ad({label:e,rows:t,loading:r,error:s,sumLabel:o,pageSize:i,sort:a,onSortChange:l,memberRequest:c}){const m=$e(),[d,p]=u.useState(0),[f,x]=u.useState(null),h=f===null?null:c(f.value),b=de.useQuery({queryKey:["groupMembers",h?.query,h?.variables],queryFn:({signal:v})=>m.query(h.query,h.variables,{signal:v}),enabled:h!==null}),N=t.map(v=>`${String(v.value)}:${v.count}:${String(v.sum)}`).join("|");if(u.useEffect(()=>{p(0),x(null)},[e,N,i]),s)return n.jsxs("p",{role:"alert",className:"px-2 py-1 text-sm text-destructive",children:["Grouping failed: ",s.message]});if(r)return n.jsx("p",{className:"px-2 py-1 text-sm text-muted-foreground",children:"Loading grouped results…"});const T=Math.max(1,i),k=Math.max(1,Math.ceil(t.length/T)),E=t.slice(Math.min(d,k-1)*T,(Math.min(d,k-1)+1)*T),y=h?b.data?.[h.responseKey]:void 0;return n.jsxs("div",{className:"border-b px-2 py-2","aria-label":`Grouped by ${e}`,children:[n.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2 text-sm font-medium",children:[n.jsxs("span",{children:["Grouped by ",e]}),n.jsxs("label",{className:"text-xs font-normal text-muted-foreground",children:["Group order",n.jsxs("select",{"aria-label":"Group order",className:"ml-1 rounded border bg-background px-1 py-0.5 text-foreground",value:`${a.field}:${a.desc?"desc":"asc"}`,onChange:v=>{const[j,S]=v.target.value.split(":");l({field:j==="count"?"count":"key",desc:S==="desc"})},children:[n.jsxs("option",{value:"key:asc",children:[e," ascending"]}),n.jsxs("option",{value:"key:desc",children:[e," descending"]}),n.jsx("option",{value:"count:desc",children:"Count high to low"}),n.jsx("option",{value:"count:asc",children:"Count low to high"})]})]}),n.jsxs("span",{className:"text-muted-foreground",children:[t.length," groups"]})]}),n.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto_auto] gap-x-4 gap-y-1 text-sm",children:[E.map((v,j)=>n.jsxs("div",{className:"contents",children:[n.jsx("button",{type:"button",className:"text-left underline-offset-2 hover:underline","aria-expanded":f===v,onClick:()=>x(f===v?null:v),children:v.value===null||v.value===void 0?"(null)":String(v.value)}),n.jsx("span",{className:"tabular-nums text-muted-foreground",children:v.count}),n.jsx("span",{className:"tabular-nums text-muted-foreground",children:o?String(v.sum??"—"):""})]},`${String(v.value)}-${j}`)),t.length===0&&n.jsx("span",{className:"text-muted-foreground",children:"No grouped results."})]}),t.length>T&&n.jsxs("div",{className:"mt-2 flex items-center gap-2 text-xs",children:[n.jsx("button",{type:"button",disabled:d===0,onClick:()=>p(v=>v-1),children:"Previous groups"}),n.jsxs("span",{children:["Group page ",Math.min(d,k-1)+1," of ",k]}),n.jsx("button",{type:"button",disabled:d>=k-1,onClick:()=>p(v=>v+1),children:"Next groups"})]}),h&&n.jsx("div",{className:"mt-2 rounded bg-muted/40 p-2 text-xs","aria-live":"polite",children:b.isLoading?"Loading group members…":b.error?"Group member query failed.":n.jsxs(n.Fragment,{children:[n.jsxs("div",{children:[y?.total??0," matching members"]}),n.jsx("pre",{className:"max-h-32 overflow-auto",children:JSON.stringify(y?.data??[],null,2)})]})})]})}const id=[10,20,30,50,100];function ld({columns:e,data:t,tableName:r,pageCount:s,pageIndex:o,pageSize:i,sorting:a,columnFilters:l,loading:c,fetching:m=!1,selectable:d=!1,primaryKeys:p=[],selectedRowId:f,onRowSelect:x,onSortingChange:h,onColumnFiltersChange:b,onPageIndexChange:N,onPageSizeChange:T,onEditRow:k,onDeleteRow:E,onDeleteSelected:y,onBulkEditSelected:v,inlineEditableColumns:j,inlineBooleanColumns:S,pendingEdits:C,onCellCommit:B,onSaveAllEdits:$,onDiscardAllEdits:L,savingEdits:q=!1,stackingEnabled:D,onToggleStacking:V,exportRows:X,totalRows:F,onVisualize:P,groupableColumns:A,grouping:U,onGroupingChange:_,onGroupingSumChange:ce}){const{hoveredRow:he,hoverRow:Ue,scheduleDismiss:Pe,cancelDismiss:ie,suppressClick:se,startPress:ke,onPressMove:Ae,cancelPress:re}=td(),{defaultColumns:Ee,trailingColumns:Ie}=Dn(),[Le,Ge]=u.useState({}),[Oe,ye]=u.useState(null),{columnSizing:ze,setColumnSizing:O}=Qu(r),Z=u.useRef(null),{fitMode:ee,setFitMode:Ce,computeFitSize:xe}=rd(Z,T),qe=u.useCallback(z=>{const H=Z.current;if(!H)return;const I=H.querySelectorAll(`[data-col-id="${z}"]`);let ne=Hr;I.forEach(De=>{const ot=De.scrollWidth+4;ot>ne&&(ne=ot)});const Se=Math.min(ne,sa);O(De=>({...De,[z]:Se}))},[O]),W=u.useCallback(()=>{O({})},[O]);u.useEffect(()=>{Ge({})},[t,o]);const me=u.useMemo(()=>{const z=[];return d&&z.push({id:"_select",header:({table:H})=>n.jsx(Cn,{checked:H.getIsAllPageRowsSelected()||H.getIsSomePageRowsSelected()&&"indeterminate",onCheckedChange:I=>H.toggleAllPageRowsSelected(!!I),"aria-label":"Select all"}),cell:({row:H})=>n.jsx(Cn,{checked:H.getIsSelected(),onCheckedChange:I=>H.toggleSelected(!!I),onClick:I=>I.stopPropagation(),"aria-label":"Select row"}),enableSorting:!1,enableHiding:!1,enableResizing:!1,size:32}),z.push(...od(e,{leading:r?Ee?.[r]:void 0,trailing:Ie})),z},[e,d,Ee,r,Ie]),Ne=u.useMemo(()=>Xu(me.filter(z=>z.enableHiding!==!1).map(z=>z.id).filter(z=>z!==void 0),r?Ee?.[r]:void 0),[me,Ee,r]),{columnVisibility:ve,setColumnVisibility:rt,resetColumnVisibility:Mt}=Zu(r,Ne),be=$n.useReactTable({data:t,columns:me,pageCount:s,getRowId:(z,H)=>He(z,{primaryKeys:p},H),state:{sorting:a,columnFilters:l,pagination:{pageIndex:o,pageSize:i},columnVisibility:ve,rowSelection:Le,columnSizing:ze},defaultColumn:{minSize:Hr,size:Wu},columnResizeMode:"onChange",enableColumnResizing:!0,onColumnSizingChange:O,meta:{onResetColumnWidths:W},onSortingChange:z=>{const H=typeof z=="function"?z(a):z;h(H)},onPaginationChange:z=>{const I=typeof z=="function"?z({pageIndex:o,pageSize:i}):z;I.pageSize!==i?(T(I.pageSize),N(0)):N(I.pageIndex)},onColumnFiltersChange:z=>{const H=typeof z=="function"?z(l):z;b(H)},onColumnVisibilityChange:rt,onRowSelectionChange:Ge,enableRowSelection:d,getCoreRowModel:$n.getCoreRowModel(),manualSorting:!0,manualFiltering:!0,manualPagination:!0}),ft=Object.keys(Le).length,Nt=be.getVisibleLeafColumns().map(z=>z.id).join("|"),Ye=u.useCallback(()=>{const z=[];for(const H of be.getSelectedRowModel().rows){const I=mt(H.original,{primaryKeys:p});I&&z.push(I)}return z},[be,p]),Xe=u.useCallback(()=>{if(!y)return;const z=Ye();z.length>0&&y(z)},[Ye,y]),Qt=u.useCallback(()=>{if(!v)return;const z=Ye();z.length>0&&v(z)},[Ye,v]),kn=u.useCallback((z,H)=>{ye({rowId:z,columnId:H})},[]),Sn=u.useCallback((z,H,I)=>{ye(null),B?.(z,H,I)},[B]),Ht=u.useCallback(()=>ye(null),[]),pt=u.useCallback(z=>{const H=be.getRow(z);return H?mt(H.original,{primaryKeys:p}):null},[be,p]),It=u.useCallback(z=>{if(!k)return;const H=pt(z);H&&k(H)},[k,pt]),st=u.useCallback(z=>{if(!E)return;const H=pt(z);H&&E(H)},[E,pt]),Ut=u.useCallback(()=>{he&&It(he.rowId)},[he,It]),Lt=u.useCallback(()=>{he&&st(he.rowId)},[he,st]);return n.jsxs("div",{className:"flex flex-col w-full min-h-0 flex-1",children:[n.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[n.jsxs("div",{className:"flex items-center gap-2",children:[l.length>0&&n.jsxs(Q,{variant:"outline",size:"sm",onClick:()=>be.resetColumnFilters(),title:"Clear all column filters",children:[n.jsx(w.FilterX,{className:"size-3.5"}),"Clear filters"]}),ft>0&&(y||v)&&n.jsxs(n.Fragment,{children:[n.jsxs("span",{className:"text-xs text-muted-foreground",children:[ft," selected"]}),v&&n.jsxs(Q,{variant:"outline",size:"sm",onClick:Qt,title:"Apply one set of field changes to every selected row in one transaction",children:[n.jsx(w.Pencil,{className:"size-3.5"}),"Edit"]}),y&&n.jsxs(Q,{variant:"outline",size:"sm",onClick:Xe,className:"text-destructive hover:text-destructive",children:[n.jsx(w.Trash2,{className:"size-3.5"}),"Delete"]})]}),(C?.size??0)>0&&$&&n.jsxs(n.Fragment,{children:[n.jsxs("span",{className:"text-xs text-amber-600 dark:text-amber-400",children:[C.size," unsaved ",C.size===1?"row":"rows"]}),n.jsx(Q,{size:"sm",onClick:$,disabled:q,children:q?"Saving…":"Save all"}),L&&n.jsx(Q,{variant:"outline",size:"sm",onClick:L,disabled:q,children:"Discard"})]})]}),n.jsxs("div",{className:"flex items-center gap-2",children:[P&&n.jsx(Q,{variant:"outline",size:"sm",onClick:P,title:"Open a chart using this table and its active filters",children:"Visualize"}),X&&n.jsx(Ku,{exportRows:X,total:F??0,tableName:r??"export"}),V&&n.jsxs(Q,{variant:D?"secondary":"outline",size:"sm",role:"switch","aria-checked":!!D,onClick:()=>V(!D),title:D?"Stacked drill-down active — click for flat grid":"Flat grid active — click for stacked drill-down",children:[D?n.jsx(w.PanelRight,{className:"size-3.5"}):n.jsx(w.Rows3,{className:"size-3.5"}),D?"Stacked":"Grid"]}),_&&A&&n.jsxs(Ze,{value:U?.column.name??"__none",onValueChange:z=>_(z==="__none"?null:z),children:[n.jsx(tt,{size:"sm",className:"w-40","aria-label":"Group grid by column",children:n.jsx(et,{placeholder:"Group by"})}),n.jsxs(nt,{children:[n.jsx(we,{value:"__none",children:"No grouping"}),A.map(z=>n.jsx(we,{value:z.name,children:z.label},z.name))]})]}),U&&ce&&A&&n.jsxs(Ze,{value:U.sumColumn?.name??"__none",onValueChange:z=>ce(z==="__none"?null:z),children:[n.jsx(tt,{size:"sm",className:"w-40","aria-label":"Group sum column",children:n.jsx(et,{placeholder:"Sum column"})}),n.jsxs(nt,{children:[n.jsx(we,{value:"__none",children:"Count only"}),A.filter(z=>/^(byte|short|int|long|float|double|decimal|numeric|money|real)/i.test(z.paramType.replace(/[![\]]/g,""))).map(z=>n.jsxs(we,{value:z.name,children:["Sum ",z.label]},z.name))]})]}),n.jsxs(On,{children:[n.jsx(An,{asChild:!0,children:n.jsxs(Q,{variant:"outline",size:"sm",children:[n.jsx(w.Columns3,{className:"size-3.5"}),"Columns",n.jsx(w.ChevronDown,{className:"size-3.5"})]})}),n.jsxs(qn,{align:"end",children:[be.getAllColumns().filter(z=>z.getCanHide()).map(z=>{const I=z.columnDef.meta?.column?.label??(typeof z.columnDef.header=="string"?z.columnDef.header:z.id);return n.jsx(Wi,{checked:z.getIsVisible(),onCheckedChange:ne=>z.toggleVisibility(!!ne),children:I},z.id)}),n.jsx(yt,{}),n.jsx(bt,{onClick:Mt,children:"Reset to default columns"})]})]})]})]}),U?n.jsxs(n.Fragment,{children:[n.jsx(ad,{label:U.column.label,rows:U.rows,loading:U.loading,error:U.error,sumLabel:U.sumColumn?.label,pageSize:i,sort:U.sort,onSortChange:U.onSortChange,memberRequest:U.memberRequest}),n.jsx("p",{className:"border-b px-2 py-1 text-xs text-muted-foreground",role:"note",children:"Inline editing is disabled while grouping is active; expand a group to inspect its server-filtered members."})]}):n.jsxs(n.Fragment,{children:[m&&n.jsx("div",{className:"relative h-0 z-20",children:n.jsxs("div",{"data-testid":"fetch-indicator",role:"progressbar","aria-label":"Loading page",className:"absolute inset-x-0 top-0 h-0.5 overflow-hidden bg-primary/20",children:[n.jsx("div",{className:"h-full w-1/3 bg-primary",style:{animation:"edit-db-indeterminate 1.2s ease-in-out infinite"}}),n.jsx("style",{children:"@keyframes edit-db-indeterminate { 0% { transform: translateX(-100%); } 100% { transform: translateX(300%); } }"})]})}),n.jsxs("div",{ref:Z,className:"relative flex-1 overflow-auto min-h-0","aria-busy":m||c,children:[n.jsxs(Au,{style:{tableLayout:"fixed",width:be.getTotalSize()},children:[n.jsx("colgroup",{children:be.getVisibleLeafColumns().map(z=>n.jsx("col",{style:{width:z.getSize()}},z.id))}),n.jsx(qu,{children:be.getHeaderGroups().map(z=>n.jsx(tr,{children:z.headers.map(H=>n.jsxs(Bu,{"data-col-id":H.column.id,className:"relative","aria-sort":H.column.getIsSorted()==="asc"?"ascending":H.column.getIsSorted()==="desc"?"descending":H.column.getCanSort()?"none":void 0,children:[H.isPlaceholder?null:$n.flexRender(H.column.columnDef.header,H.getContext()),H.column.getCanResize()&&n.jsx("div",{onMouseDown:H.getResizeHandler(),onTouchStart:H.getResizeHandler(),onDoubleClick:()=>qe(H.column.id),className:`absolute top-0 right-0 w-1 h-full cursor-col-resize select-none touch-none opacity-0 hover:opacity-100 transition-opacity ${H.column.getIsResizing()?"bg-primary opacity-100":"bg-border hover:bg-muted-foreground"}`})]},H.id))},z.id))}),n.jsx(Vu,{children:c?n.jsx(tr,{children:n.jsx(Qr,{colSpan:me.length,className:"h-24 text-center",children:"Loading..."})}):be.getRowModel().rows.length===0?n.jsx(tr,{children:n.jsx(Qr,{colSpan:me.length,className:"h-24 text-center",children:"No results."})}):be.getRowModel().rows.map(z=>n.jsx(ud,{row:z,isSelected:f!=null&&z.id===f,checked:z.getIsSelected(),visibleKey:Nt,pending:C?.get(z.id),editingColumnId:Oe?.rowId===z.id?Oe.columnId:null,inlineEditableColumns:B?j:void 0,inlineBooleanColumns:S,onStartEditCell:B?kn:void 0,onCommitCell:Sn,onCancelEditCell:Ht,onRowSelect:x,onEditRow:k?It:void 0,onDeleteRow:E?st:void 0,suppressClick:se,hoverRow:Ue,scheduleDismiss:Pe,startPress:ke,onPressMove:Ae,cancelPress:re},z.id))})]}),he&&(k||E)&&n.jsx(Gu,{anchorEl:he.el,onEdit:k?Ut:void 0,onDelete:E?Lt:void 0,onMouseEnter:ie,onDismiss:Pe})]}),n.jsxs("div",{className:"flex items-center justify-between px-2 py-1.5 border-t border-border mt-auto shrink-0",children:[n.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[n.jsx("span",{children:"Rows per page"}),n.jsxs(Ze,{value:String(ee?Zr:i),onValueChange:z=>{const H=Number(z);H===Zr?(Ce(!0),T(xe())):(Ce(!1),T(H))},children:[n.jsx(tt,{size:"sm",className:"w-auto h-7 text-xs","aria-label":"Rows per page",children:n.jsx(et,{children:ee?"Fit":i})}),n.jsxs(nt,{children:[n.jsx(we,{value:String(Zr),children:"Fit"}),id.map(z=>n.jsx(we,{value:String(z),children:z},z))]})]})]}),n.jsxs("div",{className:"flex items-center gap-1.5",children:[n.jsxs("span",{className:"text-xs text-muted-foreground mr-2",children:["Page ",o+1," of ",s||1]}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(0),disabled:o===0,"aria-label":"First page",title:"First page",children:n.jsx(w.ChevronsLeft,{className:"size-4"})}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(o-1),disabled:!be.getCanPreviousPage(),"aria-label":"Previous page",title:"Previous page",children:n.jsx(w.ChevronLeft,{className:"size-4"})}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(o+1),disabled:!be.getCanNextPage(),"aria-label":"Next page",title:"Next page",children:n.jsx(w.ChevronRight,{className:"size-4"})}),n.jsx(Q,{variant:"outline",size:"icon-sm",onClick:()=>N(s-1),disabled:o>=s-1,"aria-label":"Last page",title:"Last page",children:n.jsx(w.ChevronsRight,{className:"size-4"})})]})]})]})]})}function cd({row:e,isSelected:t,checked:r,pending:s,editingColumnId:o,inlineEditableColumns:i,inlineBooleanColumns:a,onStartEditCell:l,onCommitCell:c,onCancelEditCell:m,onRowSelect:d,onEditRow:p,onDeleteRow:f,suppressClick:x,hoverRow:h,scheduleDismiss:b,startPress:N,onPressMove:T,cancelPress:k}){const E=!!(d||p||f);return n.jsx(tr,{"data-state":t||r?"selected":void 0,className:d?"cursor-pointer group/row focus-visible:outline-2 focus-visible:outline-primary":"group/row focus-visible:outline-2 focus-visible:outline-primary",tabIndex:E?0:void 0,onClick:d?()=>{if(x.current){x.current=!1;return}window.getSelection()?.toString()||d(t?null:e.id)}:void 0,onKeyDown:E?y=>{y.target===y.currentTarget&&((y.key==="Enter"||y.key===" ")&&d?(y.preventDefault(),d(t?null:e.id)):(y.key==="e"||y.key==="E")&&p?(y.preventDefault(),p(e.id)):(y.key==="Delete"||y.key==="Backspace")&&f&&(y.preventDefault(),f(e.id)))}:void 0,onFocus:y=>{y.target===y.currentTarget&&h(e.id,y.currentTarget)},onBlur:y=>{y.currentTarget.contains(y.relatedTarget)||b()},onPointerEnter:y=>{y.pointerType==="mouse"&&h(e.id,y.currentTarget)},onPointerLeave:y=>{y.pointerType==="mouse"&&b()},onPointerDown:y=>N(e.id,y.currentTarget,y),onPointerMove:T,onPointerUp:k,onPointerCancel:k,children:e.getVisibleCells().map(y=>{const v=y.column.id,j=!!l&&!!i?.has(v),S=o===v,C=!!s&&v in s;return n.jsx(Qr,{"data-col-id":v,"data-dirty":C?"true":void 0,className:C?"bg-amber-500/10 border-l-2 border-l-amber-500":void 0,title:j&&!S?"Double-click to edit":void 0,onDoubleClick:j&&!S?()=>l(e.id,v):void 0,children:S&&c&&m?n.jsx(dd,{initialValue:C?s[v]:e.original[v],boolean:!!a?.has(v),onCommit:B=>c(e.id,v,B),onCancel:m}):C?n.jsx("span",{title:"Unsaved change",children:s[v]==null?"":String(s[v])}):$n.flexRender(y.column.columnDef.cell,y.getContext())},y.id)})})}const ud=u.memo(cd);function dd({initialValue:e,boolean:t,onCommit:r,onCancel:s}){const[o,i]=u.useState(e==null?"":String(e));return t?n.jsx("input",{type:"checkbox",autoFocus:!0,defaultChecked:e===!0||e==="true",onChange:a=>r(a.target.checked),onKeyDown:a=>{a.key==="Escape"&&s()},onBlur:s,"aria-label":"Edit cell value"}):n.jsx("input",{autoFocus:!0,className:"w-full bg-background border border-primary rounded px-1 py-0.5 text-sm outline-none",value:o,onChange:a=>i(a.target.value),onKeyDown:a=>{a.key==="Enter"?(a.preventDefault(),r(o)):a.key==="Escape"&&(a.preventDefault(),s()),a.stopPropagation()},onBlur:()=>r(o),onClick:a=>a.stopPropagation(),onDoubleClick:a=>a.stopPropagation(),"aria-label":"Edit cell value"})}function md({table:e,pks:t,onClose:r}){const s=$e(),{toast:o}=vt(),i=Vo(e),[a,l]=u.useState({}),[c,m]=u.useState(null),[d,p]=u.useState(!1),f=u.useMemo(()=>e.columns.filter(y=>!y.isReadOnly&&!y.isIdentity&&!y.isPrimaryKey&&!Et(y.dbType)),[e]),x=u.useMemo(()=>e.columns.some(y=>!y.isReadOnly&&!y.isIdentity&&!y.isPrimaryKey&&!y.isNullable&&Et(y.dbType)),[e]),h=u.useMemo(()=>{const y=new Map(e.columns.map(v=>[v.name,v]));return(e.primaryKeys??[]).map(v=>y.get(v)).filter(v=>!!v)},[e]),b=f.filter(y=>a[y.name]?.enabled),N=d||i.isPending,T=(y,v)=>l(j=>{const S=j[y]??{enabled:!1,value:"",setNull:!1};return{...j,[y]:{...S,...v}}}),k=y=>{const v=a[y.name];return v.setNull?null:y.paramType.startsWith("Boolean")?v.value==="true":v.value},E=async()=>{if(m(null),b.length===0){m("Choose at least one field to change.");return}p(!0);try{const y={};for(const L of b)y[L.name]=k(L);const v=f.filter(L=>!L.isNullable||y[L.name]!==void 0),j=[...new Set([...e.primaryKeys??[],...v.map(L=>L.name)])],S=uo(e,t,j);if(!S)throw new Error("The selected rows have no resolvable primary keys.");const B=(await s.query(S.query,S.variables))?.value?.data??[];if(B.length!==t.length)throw new Error(`Only ${B.length} of ${t.length} selected rows still exist. Refresh and retry.`);const $=cu(e,v,h,B,y);await i.saveDelta({updated:$}),r()}catch(y){const v=y.message??String(y);m(v),o(`Bulk edit failed: ${v}`,"error")}finally{p(!1)}};return n.jsx(jt,{open:!0,onOpenChange:y=>{!y&&!N&&r()},children:n.jsxs(wt,{showCloseButton:!1,className:"max-w-lg",children:[n.jsxs(tn,{children:[n.jsxs(Ct,{children:["Edit ",t.length," ",t.length===1?"row":"rows"]}),n.jsx(Kt,{children:"Chosen fields are applied to every selected row and saved in one transaction — if any row fails, nothing changes."})]}),x?n.jsx("p",{className:"text-sm text-destructive",children:"This table has a required binary column, which bulk edit cannot echo. Edit rows individually."}):n.jsx("div",{className:"flex flex-col gap-2 max-h-80 overflow-y-auto py-1",children:f.map(y=>{const v=a[y.name]??{enabled:!1,value:"",setNull:!1},j=y.paramType.startsWith("Boolean");return n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(Cn,{id:`bulk-${y.name}`,checked:v.enabled,onCheckedChange:S=>T(y.name,{enabled:S===!0})}),n.jsx(Wt,{htmlFor:`bulk-${y.name}`,className:"w-40 truncate",title:y.label??y.name,children:y.label??y.name}),j?n.jsxs("select",{className:"h-8 rounded-md border bg-transparent px-2 text-sm flex-1",disabled:!v.enabled||v.setNull,value:v.value==="true"?"true":"false",onChange:S=>T(y.name,{value:S.target.value}),children:[n.jsx("option",{value:"true",children:"true"}),n.jsx("option",{value:"false",children:"false"})]}):n.jsx(Qe,{className:"h-8 flex-1",disabled:!v.enabled||v.setNull,value:v.value,onChange:S=>T(y.name,{value:S.target.value})}),y.isNullable&&n.jsxs("label",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[n.jsx(Cn,{checked:v.setNull,disabled:!v.enabled,onCheckedChange:S=>T(y.name,{setNull:S===!0})}),"null"]})]},y.name)})}),c&&n.jsx("p",{className:"text-sm text-destructive",children:c}),n.jsxs(Br,{children:[n.jsx(Q,{variant:"outline",onClick:r,disabled:N,children:"Cancel"}),n.jsx(Q,{onClick:E,disabled:N||x,children:N?"Saving…":`Apply to ${t.length} ${t.length===1?"row":"rows"}`})]})]})})}function fd({...e}){return n.jsx(R.Dialog.Root,{"data-slot":"sheet",...e})}function pd({...e}){return n.jsx(R.Dialog.Portal,{"data-slot":"sheet-portal",...e})}function hd({className:e,...t}){return n.jsx(R.Dialog.Overlay,{"data-slot":"sheet-overlay",className:Y("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function gd({className:e,children:t,side:r="right",...s}){return n.jsxs(pd,{children:[n.jsx(hd,{}),n.jsxs(R.Dialog.Content,{"data-slot":"sheet-content",className:Y("fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out duration-200 outline-none","data-[state=closed]:animate-out data-[state=open]:animate-in data-[state=closed]:duration-200 data-[state=open]:duration-200",r==="right"&&"inset-y-0 right-0 h-full w-3/4 max-w-md border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right",r==="left"&&"inset-y-0 left-0 h-full w-3/4 max-w-md border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left",r==="top"&&"inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",r==="bottom"&&"inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",e),...s,children:[t,n.jsxs(R.Dialog.Close,{"data-slot":"sheet-close",className:"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[n.jsx(w.XIcon,{}),n.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function xd({className:e,...t}){return n.jsx("div",{"data-slot":"sheet-header",className:Y("flex flex-col gap-2 p-4 pb-0",e),...t})}function bd({className:e,...t}){return n.jsx(R.Dialog.Title,{"data-slot":"sheet-title",className:Y("text-lg leading-none font-semibold",e),...t})}function yd({className:e,...t}){return n.jsx(R.Dialog.Description,{"data-slot":"sheet-description",className:Y("text-sm text-muted-foreground",e),...t})}const vd={json:w.Braces,xml:w.Code,"php-serialized":w.Database,binary:w.Binary,longtext:w.FileText,text:w.FileText},ia={json:"JSON",xml:"XML","php-serialized":"PHP Serialized",binary:"Binary",longtext:"Text",text:"Text"};function jd(e,t){if(t==="json")try{return JSON.stringify(JSON.parse(e),null,2)}catch{return e}return t==="xml"?e.replace(/>\s*</g,`>
121
+ <`).trim():e}function wd({target:e,onClose:t,onNavigate:r,onSave:s,canNavigatePrev:o,canNavigateNext:i}){const{toast:a}=vt(),[l,c]=u.useState(!1),[m,d]=u.useState(!1),[p,f]=u.useState(""),[x,h]=u.useState(!1),[b,N]=u.useState(!1),T=u.useRef(null),k=e?.value??"",E=Gn(k,e?.dbType),y=vd[E],v=jd(k,E),j=E==="binary"&&k?ro(k):null,S=u.useCallback(()=>{!e||!j||Kl(k,`${e.columnName}${j.extension}`,j.mime)},[e,j,k]);u.useEffect(()=>{d(!1),f(""),h(!1),N(!1)},[e?.rowKey,e?.columnName]),u.useEffect(()=>{if(!e)return;const _=ce=>{m||(ce.key==="ArrowUp"&&o?(ce.preventDefault(),r("prev")):ce.key==="ArrowDown"&&i&&(ce.preventDefault(),r("next")))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[e,m,o,i,r]);const C=u.useRef(null);u.useEffect(()=>()=>{C.current&&clearTimeout(C.current)},[]);const B=u.useCallback(async()=>{try{await navigator.clipboard.writeText(k)}catch(_){a(`Copy failed: ${_ instanceof Error?_.message:String(_)}`,"error");return}h(!0),C.current&&clearTimeout(C.current),C.current=setTimeout(()=>h(!1),1500)},[k,a]),$=u.useCallback(()=>{f(v),d(!0),requestAnimationFrame(()=>T.current?.focus())},[v]),L=u.useCallback(()=>{d(!1),f("")},[]),q=u.useCallback(async()=>{if(p===v){d(!1);return}if(!(!s||b)){N(!0);try{await s(p),d(!1)}catch{}finally{N(!1)}}},[s,p,v,b]),D=u.useCallback(()=>{if(E==="json")try{f(JSON.stringify(JSON.parse(p),null,2))}catch{}else E==="xml"&&f(p.replace(/>\s*</g,`>
122
+ <`).trim())},[p,E]),V=E==="json"||E==="xml",X=!!s&&!e?.isReadOnly&&E!=="binary",F=n.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[n.jsx(y,{className:"size-4 text-muted-foreground shrink-0"}),n.jsx("span",{className:"truncate font-semibold text-sm",children:e?.columnLabel}),n.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:j?j.kind==="image"?j.mime.replace("image/","").toUpperCase()+" image":j.kind==="pdf"?"PDF document":ia[E]:ia[E]}),n.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:j?xr(k):`${k.length} chars`})]}),P=n.jsxs("div",{className:"flex items-center gap-1 px-4 pb-2",children:[n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:B,children:[x?n.jsx(w.Check,{className:"size-3"}):n.jsx(w.Copy,{className:"size-3"}),x?"Copied":"Copy"]}),j&&n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:S,children:[n.jsx(w.Download,{className:"size-3"}),"Download"]}),X&&!m&&n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:$,children:[n.jsx(w.Pencil,{className:"size-3"}),"Edit"]}),m&&V&&n.jsxs(Q,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs px-2",onClick:D,children:[n.jsx(w.WrapText,{className:"size-3"}),"Format"]}),n.jsxs("div",{className:"flex items-center gap-1 ml-auto",children:[n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>r("prev"),disabled:!o,"aria-label":"Previous row",title:"Previous row",children:n.jsx(w.ChevronUp,{className:"size-4"})}),n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>r("next"),disabled:!i,"aria-label":"Next row",title:"Next row",children:n.jsx(w.ChevronDown,{className:"size-4"})}),n.jsx(Q,{type:"button",variant:"ghost",size:"icon-sm",onClick:()=>c(_=>!_),"aria-label":l?"Exit full screen":"Full screen",title:l?"Exit full screen":"Full screen",children:l?n.jsx(w.Minimize2,{className:"size-4"}):n.jsx(w.Maximize2,{className:"size-4"})})]})]}),A=n.jsx("div",{className:"flex-1 min-h-0 overflow-auto px-4 pb-4",children:m?n.jsxs("div",{className:"flex flex-col gap-2 h-full",children:[n.jsx("textarea",{ref:T,value:p,onChange:_=>f(_.target.value),className:Y("flex-1 w-full rounded-md border border-input bg-background px-3 py-2","text-xs font-mono leading-relaxed","ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2","resize-none min-h-[200px]")}),n.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[n.jsx(Q,{type:"button",variant:"ghost",size:"sm",onClick:L,disabled:b,children:"Cancel"}),n.jsx(Q,{type:"button",size:"sm",onClick:q,disabled:b,children:b?"Saving…":"Save"})]})]}):j?.kind==="image"?n.jsx("img",{src:so(k,j.mime),alt:e?.columnLabel??"Image content",className:"max-w-full rounded-md border border-input"}):j?n.jsxs("div",{className:"rounded-md border border-input bg-muted/30 p-4 text-sm text-muted-foreground",children:[n.jsxs("p",{children:[j.kind==="pdf"?"PDF document":"Binary content"," · ",xr(k)]}),n.jsx("p",{className:"mt-1 text-xs",children:"Use Download to save and open the file."})]}):n.jsx("pre",{className:"text-xs font-mono leading-relaxed whitespace-pre-wrap break-all",children:v})}),U=!!e;return n.jsxs(n.Fragment,{children:[n.jsx(fd,{open:U&&!l,onOpenChange:_=>{_||t()},children:n.jsxs(gd,{side:"right",className:"w-[480px] max-w-[90vw]",children:[n.jsxs(xd,{children:[n.jsx(bd,{children:F}),n.jsx(yd,{className:"sr-only",children:"Content viewer panel"})]}),P,A]})}),n.jsx(jt,{open:U&&l,onOpenChange:_=>{_||c(!1)},children:n.jsxs(wt,{className:"max-w-[90vw] max-h-[90vh] w-full h-full flex flex-col",children:[n.jsxs(tn,{children:[n.jsx(Ct,{children:F}),n.jsx(Kt,{className:"sr-only",children:"Content viewer full screen"})]}),P,A]})})]})}function Cd(e,t){if(Kn(e,t).filterTexts.length===0)return;const s=[];for(const o of e){const i=o.value,a=t.columns.find(l=>l.name===o.id);!a||!pn(a.paramType).includes(i.operator)||i.value===void 0||i.value===""&&i.operator!=="_null"||s.push({[a.graphQlName]:{[i.operator]:i.value}})}return s.length===1?s[0]:s.length>1?{and:s}:void 0}function es({table:e,id:t,filterTable:r,filterColumn:s,selectedRowId:o,onRowSelect:i,onOpenColumn:a,stackingEnabled:l,onToggleStacking:c}){const m=Hn(e),[d,p]=u.useState(null),[f,x]=u.useState(null),[h,b]=u.useState(null),N=u.useRef([]),T=u.useCallback(I=>{x(Bn(I,e))},[e]),k=u.useCallback(I=>{p({type:"single",pk:I})},[]),E=u.useCallback(I=>{I.length!==0&&p({type:"batch",pks:I})},[]),[y,v]=u.useState(null),j=u.useCallback(I=>{I.length!==0&&v(I)},[]),[S,C]=u.useState(new Map),B=u.useRef(S);B.current=S;const[$,L]=u.useState(!1),q=Vo(e),D=u.useCallback((I,ne)=>{const Se=N.current[I];b({columnName:ne,pk:Se?mt(Se,e):null,rowIndex:I,tableName:e.name})},[e]),{columns:V,sorting:X,columnFilters:F,pageIndex:P,pageSize:A,pageCount:U,rows:_,totalRows:ce,grouping:he,exportRows:Ue,loading:Pe,fetching:ie,error:se,onSortingChange:ke,onColumnFiltersChange:Ae,onPageIndexChange:re,onPageSizeChange:Ee,onGroupingChange:Ie,onGroupingSumChange:Le}=Qc(e,t,r,s,D,a),Ge=u.useCallback(async()=>{if(d)try{d.type==="single"?await m.deleteRow(d.pk):await m.deleteRows(d.pks),p(null)}catch{}},[d,m]),Oe=d?.type==="batch"?d.pks.length:1;N.current=_;const{toast:ye}=vt(),ze=$e(),O=e.isEditable!==!1,Z=u.useMemo(()=>h?.pk?Bn(h.pk,e):null,[h,e]),ee=u.useMemo(()=>!h||h.tableName!==e.name?-1:Z===null?h.rowIndex<_.length?h.rowIndex:-1:_.findIndex(I=>{const ne=mt(I,e);return ne!==null&&Bn(ne,e)===Z}),[h,Z,_,e]),Ce=ee>=0?_[ee]:void 0,xe=u.useMemo(()=>h?.pk?Vn(h.pk,e):null,[h,e]),qe=h?e.columns.find(I=>I.name===h.columnName):void 0,W=!!h&&!!qe&&!!xe&&_t(qe)&&Ce!==void 0&&!(qe.name in Ce),{data:me,isLoading:Ne,error:ve}=de.useQuery({queryKey:["contentPanelValue",e.name,h?.columnName,Z],queryFn:async()=>{const I=Cr(e,xe,[qe.name]),Se=(await ze.query(I,xe.variables))?.value?.data?.at(0);if(!Se)throw new Error("Row no longer exists.");return Se[qe.name]??null},enabled:W});u.useEffect(()=>{h!==null&&W&&ve&&(b(null),ye(`Could not load content: ${ve.message}`,"error"))},[h,W,ve,ye]),u.useEffect(()=>{h!==null&&h.tableName!==e.name&&b(null)},[h,e.name]),u.useEffect(()=>{h!==null&&h.tableName===e.name&&!Pe&&ee===-1&&(b(null),ye("Row is no longer in the current view; panel closed.","error"))},[h,e.name,Pe,ee,ye]);const rt=u.useMemo(()=>{if(!h||!Ce)return null;const I=e.columns.find(ot=>ot.name===h.columnName);if(!I||W&&(Ne||ve))return null;const ne=W?me:Ce[h.columnName],Se=Ft(I);return{value:ne==null?"":Se||typeof ne=="object"?JSON.stringify(ne,null,2):String(ne),columnName:I.name,columnLabel:I.label,dbType:I.dbType,rowKey:Z??`row-${h.rowIndex}`,isReadOnly:I.isReadOnly||I.isPrimaryKey||I.isIdentity}},[h,Ce,Z,e,W,me,Ne,ve]),Mt=u.useMemo(()=>e.columns.filter(I=>!I.isReadOnly&&!I.isIdentity),[e]),be=u.useMemo(()=>Mt.filter(I=>!I.isNullable||I.name===h?.columnName),[Mt,h?.columnName]),ft=u.useMemo(()=>be.map(I=>({column:I})),[be]),Nt=u.useMemo(()=>{const I=new Map(e.columns.map(ne=>[ne.name,ne]));return(e.primaryKeys??[]).map(ne=>I.get(ne)).filter(ne=>!!ne)},[e]),Ye=wn(e,ft,Nt,Z??""),Xe=O&&xe!==null&&!Ye.isPending,Qt=u.useCallback(async I=>{if(!h||!xe)return;const ne=e.columns.find(De=>De.name===h.columnName);let Se=I;if(ne&&Ft(ne))try{Se=JSON.parse(I)}catch{}try{const De=Cr(e,xe,be.map(kt=>kt.name)),ht=(await ze.query(De,xe.variables))?.value?.data?.[0];if(!ht)throw new Error("Row no longer exists.");const Ke={};for(const kt of be)Ke[kt.name]=ht[kt.name]??null;Ke[h.columnName]=Se,await Ye.update(Ke)}catch(De){throw ye(`Save failed: ${De.message}`,"error"),De}},[h,xe,e,be,Ye,ze,ye]),kn=u.useCallback(()=>{b(null)},[]),Sn=u.useCallback(I=>{if(!h||ee<0)return;const ne=I==="prev"?Math.max(0,ee-1):Math.min(_.length-1,ee+1);D(ne,h.columnName)},[h,ee,_.length,D]),Ht=u.useMemo(()=>new Set(e.columns.filter(I=>!I.isReadOnly&&!I.isIdentity&&!I.isPrimaryKey&&!Et(I.dbType)&&!_t(I)).map(I=>I.name)),[e]),pt=u.useMemo(()=>new Set(e.columns.filter(I=>I.paramType.startsWith("Boolean")).map(I=>I.name)),[e]),It=u.useCallback((I,ne,Se)=>{const De=fn(I,e);if(!De)return;const ot=N.current.find(ht=>He(ht,e,-1)===I);C(ht=>{const Ke=new Map(ht),gt={...Ke.get(I)?.changes??{}},nn=ot?.[ne];return ot!==void 0&&nn==null==(Se==null)&&String(nn??"")===String(Se??"")?delete gt[ne]:gt[ne]=Se,Object.keys(gt).length===0?Ke.delete(I):Ke.set(I,{pk:De,changes:gt}),Ke})},[e]),st=u.useCallback(()=>C(new Map),[]),Ut=u.useCallback(async()=>{const I=[...B.current.entries()];if(I.length!==0){L(!0);try{const ne=e.columns.filter(Me=>Ht.has(Me.name)),Se=(e.primaryKeys??[]).map(Me=>e.columns.find(os=>os.name===Me)).filter(Me=>!!Me),De=new Set(I.flatMap(([,Me])=>Object.keys(Me.changes))),ot=ne.filter(Me=>!Me.isNullable||De.has(Me.name)),ht=[...new Set([...e.primaryKeys??[],...ot.map(Me=>Me.name)])],Ke=uo(e,I.map(([,Me])=>Me.pk),ht);if(!Ke)throw new Error("The edited rows have no resolvable primary keys.");const gt=(await ze.query(Ke.query,Ke.variables))?.value?.data??[];if(gt.length!==I.length)throw new Error(`Only ${gt.length} of ${I.length} edited rows still exist. Refresh and retry.`);const nn=uu(e,ne,Se,gt,Me=>B.current.get(He(Me,e,-1))?.changes);await q.saveDelta({updated:nn}),C(new Map)}catch(ne){ye(`Save failed: ${ne.message}`,"error")}finally{L(!1)}}},[e,Ht,q,ze,ye]),Lt=u.useRef(e.name);u.useEffect(()=>{Lt.current!==e.name&&(Lt.current=e.name,B.current.size>0&&(C(new Map),ye("Unsaved cell edits were discarded on table switch","error")))},[e.name,ye]);const z=u.useMemo(()=>new Map([...S].map(([I,ne])=>[I,ne.changes])),[S]),H=u.useCallback(()=>{const I=Cd(F,e);window.dispatchEvent(new CustomEvent("bifrostql:visualize",{detail:{table:e.graphQlName,filter:I,filterType:`TableFilter${e.graphQlName}Input`}}))},[F,e]);return se?n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",se.message]})}):n.jsxs(n.Fragment,{children:[n.jsx(ld,{columns:V,data:_,tableName:e.name,pageCount:U,pageIndex:P,pageSize:A,sorting:X,columnFilters:F,loading:Pe,fetching:ie,primaryKeys:e.primaryKeys??[],selectable:O&&!he,selectedRowId:o,onRowSelect:i,onSortingChange:ke,onColumnFiltersChange:Ae,onPageIndexChange:re,onPageSizeChange:Ee,onEditRow:O&&!he?T:void 0,onDeleteRow:O&&!he?k:void 0,onDeleteSelected:O&&!he?E:void 0,onBulkEditSelected:O&&!he?j:void 0,inlineEditableColumns:Ht,inlineBooleanColumns:pt,pendingEdits:z,onCellCommit:O&&!he?It:void 0,onSaveAllEdits:Ut,onDiscardAllEdits:st,savingEdits:$,stackingEnabled:l,onToggleStacking:c,exportRows:Ue,totalRows:ce,groupableColumns:e.columns,grouping:he,onGroupingChange:Ie,onGroupingSumChange:Le,onVisualize:H}),n.jsx(Gr,{open:d!==null,onOpenChange:I=>{I||p(null)},title:`Delete ${Oe} ${Oe===1?"row":"rows"}?`,description:n.jsxs(n.Fragment,{children:[n.jsx("p",{children:"This action cannot be undone."}),m.error&&n.jsx("p",{className:"mt-2 text-sm text-destructive",children:m.error.message})]}),confirmLabel:`Delete ${Oe===1?"row":`${Oe} rows`}`,variant:"destructive",isPending:m.isPending,onConfirm:Ge}),n.jsx(wd,{target:rt,onClose:kn,onNavigate:Sn,onSave:Xe?Qt:void 0,canNavigatePrev:ee>0,canNavigateNext:ee>=0&&ee<_.length-1}),y!==null&&n.jsx(md,{table:e,pks:y,onClose:()=>v(null)}),f!==null&&n.jsx(Xo,{table:e.graphQlName,editId:f,onClose:()=>x(null)})]})}function Nd(e){return new Set((e.manyToManyJoins??[]).map(t=>t.junctionTable))}function la(e){const t=Nd(e),r=e.multiJoins.filter(o=>!t.has(o.destinationTable)).map(o=>({kind:"child",key:`child:${o.fieldName??o.destinationTable}`,join:o})),s=(e.manyToManyJoins??[]).map(o=>({kind:"m2m",key:`m2m:${o.junctionTable}:${o.targetTable}`,m2m:o}));return[...r,...s]}function ca(e,t){const r=new Set([...t.junctionSourceColumnNames,...t.junctionTargetColumnNames]);return e.columns.filter(s=>!s.isPrimaryKey&&!r.has(s.name))}function kd(e,t,r,s){const o=r.junctionSourceColumnNames;if(o.length===0)throw new Error(`Many-to-many relationship '${r.name}' has no junction source columns.`);const i=eo(s,o.length),a=new Map(e.columns.map(E=>[E.name,E])),l=[],c=[],m={};o.forEach((E,y)=>{const v=a.get(E);if(!v)throw new Error(`Junction table '${e.name}' has no column '${E}' (junction source column of many-to-many relationship '${r.name}').`);const j=v.paramType.replace("!",""),S=`src${y}`;l.push(`$${S}: ${j}`),c.push(`{ ${E}: { _eq: $${S} } }`),m[S]=dt(i[y],j)});const d=c.length===1?c[0]:`{ and: [${c.join(", ")}] }`,p=e.primaryKeys??[],f=ca(e,r).map(E=>E.name),x=t.primaryKeys?.length?t.primaryKeys:r.targetColumnNames,h=t.labelColumn,b=[...x];h&&!x.includes(h)&&b.push(`label: ${h}`);const N=`${r.junctionTargetField} { ${b.join(" ")} }`,T=[...p,...f,N].join(" ");return{query:`query GetLinks_${e.name}(${l.join(", ")}, $limit: Int, $offset: Int) { ${e.name}(filter: ${d} limit: $limit offset: $offset) { total offset limit data { ${T} } } }`,variables:m}}function ua(e,t){const r=zt(e).map(s=>s.name);return r.length>0?r:[...t.targetColumnNames]}function Sd(e,t,r){je(e.name,"many-to-many target table name");const s=ua(e,t),o=t.targetColumnNames[0],i=e.labelColumn||s[0];for(const h of s)je(h,"many-to-many target identity column");je(o,"many-to-many junction target column"),je(i,"many-to-many target label column");const l=`${[...new Set([...s,o])].join(" ")} label: ${i}`,c=e.columns.find(h=>h.name===i);if(!c)throw new Error(`Target table '${e.name}' has no column '${i}' (label column for the '${t.name}' many-to-many picker).`);const m=c.paramType.replace("!","")==="String",d=!!r&&r.trim()!==""&&m,p=d?"$limit: Int, $search: String":"$limit: Int",f=d?`filter: {${i}: {_contains: $search}} `:"";return{query:`query PickTarget(${p}) { ${e.name}(${f}limit: $limit sort: [${i}_asc]) { data { ${l} } } }`,identityColumns:s,linkColumn:o,serverSearch:m}}function Td(e,t,r){const s=e[t.junctionTargetField];if(!s)return null;const o=He(s,r,0),i=s.label!=null?String(s.label):o;return{id:o,label:i}}function $d(e,t,r){if(e.junctionSourceColumnNames.length!==1||e.junctionTargetColumnNames.length!==1)throw new Error("attachJunctionDetail supports single-column junction FKs only; this relationship uses a composite key which is not yet supported.");const[s]=eo(t,1);return{[e.junctionSourceColumnNames[0]]:s,[e.junctionTargetColumnNames[0]]:r}}const ts=200,Ed=50,Fd=500;function _d({m2m:e,parentRowId:t,onOpenColumn:r}){const s=Je(),o=s.findTable(e.junctionTable),i=s.findTable(e.targetTable);return!o||!i?n.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Relationship schema unavailable."}):n.jsx(Pd,{m2m:e,parentRowId:t,onOpenColumn:r,junction:o,target:i})}function Pd({m2m:e,parentRowId:t,onOpenColumn:r,junction:s,target:o}){const i=$e(),a=de.useQueryClient(),{toast:l}=vt(),[c,m]=u.useState(!1),[d,p]=u.useState(null),f=Hn(s);let x={query:null,variables:{}},h=null;try{x=kd(s,o,e,t)}catch(q){h=q}const{query:b,variables:N}=x,T=u.useMemo(()=>["m2mRows",e.junctionTable,e.targetTable,t],[e.junctionTable,e.targetTable,t]),{data:k,isLoading:E,error:y}=de.useQuery({queryKey:T,queryFn:()=>i.query(b,{...N,limit:ts,offset:0}),enabled:!!b}),v=u.useCallback(()=>a.invalidateQueries({queryKey:T}),[a,T]),j=u.useCallback(async q=>{const D=mt(q,s);if(!D)throw new Error(`This link cannot be removed: its ${s.label} row is missing one or more key columns (${(s.primaryKeys??[]).join(", ")||"none declared"}).`);await f.deleteRow(D),await v()},[s,f,v]);if(h)return n.jsxs("div",{className:"p-4 text-sm text-destructive",children:["Relationship misconfigured: ",h.message]});const S=k?.[s.name]?.data??[],C=ca(s,e),B=s.isEditable!==!1,$=ua(o,e),L=new Set;for(const q of S){const D=q[e.junctionTargetField];D&&($.some(V=>D[V]==null)||L.add($t($.map(V=>D[V]))))}return n.jsxs("div",{className:"flex flex-col min-h-0 flex-1 overflow-hidden",children:[n.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 bg-muted/20 border-b border-border shrink-0",children:[n.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-border bg-muted/40 px-2 py-0.5 text-xs text-muted-foreground",title:`Linked through ${s.label}`,children:[n.jsx(w.Link2,{className:"size-3"}),"via ",s.label]}),B&&n.jsxs(Q,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs ml-auto",onClick:()=>m(!0),children:[n.jsx(w.Plus,{className:"size-3 mr-1"})," Add link"]})]}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-auto",children:[y&&n.jsxs("div",{className:"p-3 text-sm text-destructive",children:["Error: ",y.message]}),E&&n.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[n.jsx(w.Loader2,{className:"size-4 animate-spin"})," Loading…"]}),!E&&S.length===0&&n.jsxs("div",{className:"p-3 text-sm text-muted-foreground",children:["No linked ",o.label,"."]}),S.length>0&&n.jsxs("table",{className:"w-full text-sm",children:[n.jsx("thead",{children:n.jsxs("tr",{className:"border-b border-border text-left text-xs text-muted-foreground",children:[n.jsx("th",{className:"px-2 py-1 font-medium",children:o.label}),C.map(q=>n.jsx("th",{className:"px-2 py-1 font-medium",children:q.label},q.name)),B&&n.jsx("th",{className:"px-2 py-1 w-8","aria-label":"actions"})]})}),n.jsx("tbody",{children:S.map((q,D)=>{const V=Td(q,e,o);return n.jsxs("tr",{className:"border-b border-border/50 hover:bg-muted/30",children:[n.jsx("td",{className:"px-2 py-1",children:V?n.jsxs("span",{className:"inline-flex items-center gap-1",children:[n.jsx(Pn,{to:`/${o.name}/${V.id}`,className:"text-primary hover:underline",children:V.label}),r&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"size-5",onClick:()=>r({tableName:o.name,filterId:V.id}),"aria-label":`Open ${V.label} in side column`,title:"Open in side column",children:n.jsx(w.Search,{className:"size-3"})})]}):n.jsx("span",{className:"text-muted-foreground",children:"—"})}),C.map(X=>n.jsx("td",{className:"px-2 py-1",children:Wn(q[X.name],X)},X.name)),B&&n.jsx("td",{className:"px-2 py-1",children:n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"size-6 text-muted-foreground hover:text-destructive",onClick:()=>p(q),disabled:f.isPending,"aria-label":`Detach ${V?.label??"link"}`,title:"Detach",children:n.jsx(w.Unlink,{className:"size-3.5"})})})]},D)})})]}),S.length>=ts&&n.jsxs("div",{className:"px-3 py-2 text-xs text-muted-foreground italic border-t border-border",children:["Showing the first ",ts," links. Detach some or narrow the parent selection to see more."]})]}),c&&n.jsx(zd,{target:o,junction:s,m2m:e,parentRowId:t,linkedIds:L,onClose:()=>m(!1),onLinked:v}),n.jsx(Gr,{open:d!==null,onOpenChange:q=>{q||p(null)},title:"Detach this link?",description:n.jsxs("p",{children:["This removes the link row. The ",o.label," record itself is not deleted."]}),confirmLabel:"Detach",variant:"destructive",isPending:f.isPending,onConfirm:async()=>{try{d&&await j(d)}catch(q){l(`Detach failed: ${q.message}`,"error")}finally{p(null)}}})]})}function zd({target:e,junction:t,m2m:r,parentRowId:s,linkedIds:o,onClose:i,onLinked:a}){const l=$e(),c=t.columns.filter(V=>r.junctionSourceColumnNames.includes(V.name)||r.junctionTargetColumnNames.includes(V.name)).map(V=>({column:V})),m=wn(t,c,[]),[d,p]=u.useState(""),[f,x]=u.useState("");u.useEffect(()=>{const V=setTimeout(()=>x(d),300);return()=>clearTimeout(V)},[d]);const h=f.trim();let b=null,N=null;try{b=Sd(e,r,h)}catch(V){N=V}const{query:T,identityColumns:k,linkColumn:E,serverSearch:y}=b??{query:"",identityColumns:[],linkColumn:"",serverSearch:!1},v=y?Ed:Fd,{data:j,isLoading:S}=de.useQuery({queryKey:["m2mTargets",e.name,y?h:""],queryFn:({signal:V})=>l.query(T,y&&h?{limit:v,search:h}:{limit:v},{signal:V}),enabled:b!==null}),C=j?.[e.name]?.data??[],B=y||!h?C:C.filter(V=>Jo(V,"label",h)),$=C.length>=v,[L,q]=u.useState(null),D=u.useCallback(async(V,X)=>{if(o.has(V))return;let F;try{F=$d(r,s,X)}catch(P){q(P);return}q(null);try{await m.insert(F)}catch{return}await a(),i()},[m,r,s,o,a,i]);return N?n.jsx(jt,{open:!0,onOpenChange:V=>{V||i()},children:n.jsxs(wt,{className:"max-w-md",children:[n.jsx(tn,{children:n.jsxs(Ct,{children:["Add ",e.label," link"]})}),n.jsxs("p",{className:"text-sm text-destructive",children:["Relationship misconfigured: ",N.message]})]})}):n.jsx(jt,{open:!0,onOpenChange:V=>{V||i()},children:n.jsxs(wt,{className:"max-w-md",children:[n.jsx(tn,{children:n.jsxs(Ct,{children:["Add ",e.label," link"]})}),n.jsxs("div",{className:"flex items-center gap-2",children:[n.jsx(w.Search,{className:"size-4 text-muted-foreground"}),n.jsx(Qe,{autoFocus:!0,placeholder:`Search ${e.label}…`,value:d,onChange:V=>p(V.target.value)})]}),L&&n.jsx("p",{className:"text-sm text-destructive",children:L.message}),m.error&&n.jsx("p",{className:"text-sm text-destructive",children:m.error.message}),n.jsxs("div",{className:"max-h-72 overflow-auto border border-border rounded-md",children:[S&&n.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[n.jsx(w.Loader2,{className:"size-4 animate-spin"})," Loading…"]}),!S&&B.length===0&&n.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No matches."}),B.map((V,X)=>{const F=$t(k.map(_=>V[_])),P=String(V[E]??""),A=V.label!=null?String(V.label):F,U=o.has(F);return n.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-2 text-left px-3 py-1.5 text-sm hover:bg-muted/50 disabled:opacity-50 disabled:hover:bg-transparent",disabled:m.isPending||U,onClick:()=>D(F,P),children:[n.jsx("span",{className:"truncate",children:A}),U&&n.jsx("span",{className:"shrink-0 text-xs text-muted-foreground italic",children:"Already linked"})]},X)}),!S&&$&&n.jsx("div",{className:"px-3 py-1.5 text-xs text-muted-foreground italic border-t border-border",children:y?`Showing the first ${v} matches — type to narrow.`:`Showing the first ${v} rows; some may not be listed.`})]})]})})}function da(e){return e.kind==="child"?e.join.destinationTable:e.m2m.targetTable}function ma({parentTable:e,selectedRowId:t,onClose:r,onOpenColumn:s}){const o=Je(),i=la(e),[a,l]=u.useState(i[0]?.key??""),[c,m]=u.useState(!1),[d,p]=u.useState(null),f=i.find(b=>b.key===a)??i[0];if(u.useEffect(()=>{p(null)},[a,t]),i.length===0||!o.data)return null;const x=f.kind==="child"?o.findTable(f.join.destinationTable):void 0,h=(x?.multiJoins?.length??0)>0;return n.jsxs("div",{className:"border-t-2 border-primary/20 flex flex-col flex-1 shrink-0",children:[n.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted/30 border-b border-border shrink-0",children:[n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:()=>m(!c),"aria-label":c?"Expand detail panel":"Collapse detail panel",title:c?"Expand detail panel":"Collapse detail panel",children:c?n.jsx(w.ChevronUp,{className:"size-3.5"}):n.jsx(w.ChevronDown,{className:"size-3.5"})}),n.jsx("span",{className:"text-xs text-muted-foreground mr-1",children:"Detail:"}),n.jsx("div",{className:"flex items-center gap-0.5 overflow-x-auto",children:i.map(b=>{const T=o.findTable(da(b))?.label??da(b),k=b.key===f.key;return n.jsxs("span",{className:"group/tab inline-flex items-center",children:[n.jsx(Q,{variant:k?"secondary":"ghost",size:"sm",className:Y("text-xs h-7 px-2.5",k&&"font-semibold"),onClick:()=>l(b.key),children:T}),s&&b.kind==="child"&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"opacity-0 group-hover/tab:opacity-100 size-5 shrink-0",onClick:()=>s({tableName:b.join.destinationTable,filterTable:e.name,filterId:t,...Gt(b.join)?{}:{filterColumn:b.join.destinationColumnNames[0]}}),"aria-label":"Open in side column",title:"Open in side column",children:n.jsx(w.PanelRight,{className:"size-3"})})]},b.key)})}),r&&n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:r,className:"ml-auto shrink-0","aria-label":"Close detail panel",title:"Close detail panel",children:n.jsx(w.X,{className:"size-3.5"})})]}),!c&&n.jsx("div",{className:"flex-1 flex flex-col",children:f.kind==="child"&&!x?n.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"This related table is not available."}):f.kind==="child"?n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"flex-1 min-h-[11rem] overflow-hidden flex flex-col",children:n.jsx(es,{table:x,id:t,filterTable:e.name,...Gt(f.join)?{}:{filterColumn:f.join.destinationColumnNames[0]},selectedRowId:h?d:void 0,onRowSelect:h?p:void 0,onOpenColumn:s},`${f.key}-${t}`)}),h&&d&&n.jsx("div",{className:"flex-1 flex flex-col",children:n.jsx(ma,{parentTable:x,selectedRowId:d,onClose:()=>p(null),onOpenColumn:s})})]}):n.jsx(_d,{m2m:f.m2m,parentRowId:t,onOpenColumn:s},`${f.key}-${t}`)})]})}const Dd={mainTable:null,columns:[],focusedIndex:0,focusColumn:()=>{},closeColumn:()=>{}},fa=u.createContext(Dd),pa=u.createContext({register:()=>{},unregister:()=>{}});function Md({children:e}){const[t,r]=u.useState(null),[s,o]=u.useState(0),i=u.useCallback(f=>{r(f)},[]),a=u.useCallback(()=>{r(null),o(0)},[]),l=u.useCallback(f=>{if(o(f),!t)return;const x=t.columnRefs.get(f);x&&x.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},[t]),c=u.useCallback(f=>{t&&f>0&&t.onClose(f-1)},[t]),m=u.useMemo(()=>t?t.columns.map((f,x)=>({panel:f,element:t.columnRefs.get(x+1)??null})):[],[t]),d=u.useMemo(()=>({mainTable:t?.mainTable??null,columns:m,focusedIndex:s,focusColumn:l,closeColumn:c}),[t,m,s,l,c]),p=u.useMemo(()=>({register:i,unregister:a}),[i,a]);return n.jsx(pa.Provider,{value:p,children:n.jsx(fa.Provider,{value:d,children:e})})}function Id(){return u.useContext(fa)}function Ld(){return u.useContext(pa)}function ha(e,t){return e.tableName===t.tableName&&e.filterTable===t.filterTable&&e.filterId===t.filterId&&e.filterColumn===t.filterColumn}function Od(e,t){const r=e[e.length-1];if(r&&ha(r,t))return e;const s=e.findIndex(o=>ha(o,t));return s>=0?e.slice(0,s+1):[...e,t]}function Ad(e,t){return t<0?[]:t>=e.length?e:e.slice(0,t)}function qd(e,t,r){const s=i=>r(i)??i,o=[{index:-1,label:s(e)}];for(let i=0;i<t.length;i++){const a=t[i],l=a.filterTable?s(a.filterTable):s(i===0?e:t[i-1].tableName),c=a.filterId?`from ${l} #${a.filterId}`:void 0;o.push({index:i,label:s(a.tableName),detail:c,frame:a})}return o}const ga="edit-db:panel:",Vd=16;function xa(e,t,r){return Math.min(r,Math.max(t,e))}function Bd(e,t,r,s){try{const o=localStorage.getItem(ga+e),i=o===null?NaN:Number(o);return Number.isFinite(i)?xa(i,r,s):t}catch{return t}}function Gd(e,t){try{localStorage.setItem(ga+e,String(Math.round(t)))}catch{}}function ba({key:e,initial:t,min:r,max:s,axis:o,invert:i=!1}){const[a,l]=u.useState(()=>Bd(e,t,r,s)),c=u.useRef(null),m=u.useCallback(f=>{const x=xa(f,r,s);return l(x),Gd(e,x),x},[e,r,s]),d=u.useCallback(f=>{if(f.button!==0)return;f.preventDefault();const x=f.currentTarget;x.setPointerCapture(f.pointerId),c.current={start:o==="x"?f.clientX:f.clientY,startSize:a};const h=N=>{if(!c.current)return;const k=((o==="x"?N.clientX:N.clientY)-c.current.start)*(i?-1:1);m(c.current.startSize+k)},b=N=>{c.current=null;try{x.releasePointerCapture(N.pointerId)}catch{}x.removeEventListener("pointermove",h),x.removeEventListener("pointerup",b),x.removeEventListener("pointercancel",b)};x.addEventListener("pointermove",h),x.addEventListener("pointerup",b),x.addEventListener("pointercancel",b)},[m,o,i,a]),p=u.useCallback(f=>{const x=o==="x"?"ArrowRight":"ArrowDown",h=o==="x"?"ArrowLeft":"ArrowUp";if(f.key!==x&&f.key!==h)return;f.preventDefault();const b=(f.key===x?1:-1)*(i?-1:1);m(a+b*Vd)},[m,o,i,a]);return{size:a,onPointerDown:d,onKeyDown:p}}function nr(e,t){return e.find(r=>r.name===t)}function Jt(){const e=lr(),{table:t,id:r,filterTable:s}=e,{loading:o,error:i,data:a}=Je(),[l,c]=u.useState(null),m=ba({key:"detail-height",initial:300,min:120,max:800,axis:"y",invert:!0}),[d,p]=u.useState([]),[f,x]=u.useState(!0),[h,b]=u.useState(new Set),N=u.useRef(t);t!==N.current&&(N.current=t,d.length>0&&p([]),h.size>0&&b(new Set));const T=u.useCallback(P=>{b(A=>{const U=new Set(A);return U.has(P)?U.delete(P):U.add(P),U})},[]),{register:k,unregister:E}=Ld(),y=u.useRef(null),v=u.useRef(new Map),j=u.useMemo(()=>a?nr(a,t):void 0,[a,t]),S=j?la(j).length>0:!1,C=u.useCallback(P=>{p(A=>Od(A,P))},[]),B=u.useCallback(P=>{x(P),P||p([])},[]),$=f?C:void 0,L=u.useCallback(P=>{p(A=>A.filter((U,_)=>_!==P))},[]),q=u.useCallback(P=>{p(A=>Ad(A,P+1))},[]),D=u.useMemo(()=>qd(t??"",d,P=>{if(a)return nr(a,P)?.label}),[t,d,a]);if(u.useEffect(()=>{const P=v.current;P.set(0,y.current);for(const A of P.keys())A>d.length&&P.delete(A);return k({mainTable:t,columns:d,columnRefs:P,onClose:L}),()=>E()},[t,d,k,E,L]),!t)return n.jsx("div",{className:"p-5 text-center text-muted-foreground",children:"Table missing"});if(o)return n.jsxs("div",{className:"flex items-center justify-center gap-2 p-5",children:[n.jsx(w.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]});if(i)return n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",i.message]})});if(!j)return n.jsx("div",{className:"p-5 text-center text-muted-foreground",children:"Table not found"});const V=n.jsx(es,{table:j,id:r,filterTable:s,selectedRowId:S?l:void 0,onRowSelect:S?c:void 0,onOpenColumn:$,stackingEnabled:f,onToggleStacking:B});if(d.length===0){const P=S&&l;return n.jsx("div",{className:"flex flex-col flex-1 min-h-0",children:n.jsxs("div",{ref:y,className:"flex flex-col flex-1 min-h-0 min-w-0",children:[n.jsx("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col",children:V}),P&&n.jsxs(n.Fragment,{children:[n.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":"Resize detail panel",tabIndex:0,"data-testid":"detail-resize-handle",className:"h-1.5 shrink-0 cursor-row-resize select-none touch-none hover:bg-primary/40 focus-visible:bg-primary/60 focus-visible:outline-none",onPointerDown:m.onPointerDown,onKeyDown:m.onKeyDown}),n.jsx("div",{className:"min-h-0 overflow-y-auto flex flex-col",style:{flex:`0 0 ${m.size}px`},children:n.jsx(ma,{parentTable:j,selectedRowId:l,onClose:()=>c(null),onOpenColumn:$})})]})]})})}const X=d.length-1,F=(P,A)=>A||h.has(P);return n.jsxs("div",{className:"flex flex-col flex-1 min-h-0",children:[n.jsx(Kd,{crumbs:D,onCrumbClick:q,activeIndex:d.length-1}),n.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto flex flex-col gap-0.5 p-0.5",children:[n.jsx(ya,{title:j.label,selectedRowId:d[0]?.filterId,expanded:F(-1,!1),active:!1,onToggle:()=>T(-1),onRef:P=>{y.current=P,v.current.set(0,P)},children:V}),d.map((P,A)=>{const U=A===X;return n.jsx(ya,{title:nr(a,P.tableName)?.label??P.tableName,selectedRowId:d[A+1]?.filterId,expanded:F(A,U),active:U,onToggle:()=>T(A),onClose:()=>L(A),onRef:_=>{v.current.set(A+1,_)},children:n.jsx(es,{table:nr(a,P.tableName),id:P.filterId,filterTable:P.filterTable,filterColumn:P.filterColumn,onOpenColumn:C})},`${P.tableName}|${P.filterTable??""}|${P.filterId??""}|${P.filterColumn??""}`)})]})]})}function Kd({crumbs:e,onCrumbClick:t,activeIndex:r}){return n.jsx("nav",{"aria-label":"Drill-down breadcrumb",className:"flex items-center gap-1 px-2 py-1 bg-muted/20 border-b border-border shrink-0 overflow-x-auto",children:e.map((s,o)=>{const i=s.index===r,a=o===0;return n.jsxs("span",{className:"inline-flex items-center gap-1 shrink-0",children:[!a&&n.jsx(w.ChevronRight,{className:"size-3 text-muted-foreground shrink-0"}),n.jsxs(Q,{variant:i?"secondary":"ghost",size:"sm",className:Y("h-6 px-2 text-xs gap-1",i&&"font-semibold"),onClick:()=>t(s.index),"aria-current":i?"page":void 0,title:s.detail?`${s.label} (${s.detail})`:s.label,children:[a&&n.jsx(w.Home,{className:"size-3"}),n.jsx("span",{className:"truncate max-w-[12rem]",children:s.label}),s.detail&&n.jsx("span",{className:"text-muted-foreground font-normal truncate max-w-[10rem]",children:s.detail})]})]},`${s.index}-${s.label}`)})})}function ya({title:e,selectedRowId:t,expanded:r,active:s,onToggle:o,onClose:i,onRef:a,children:l}){return n.jsxs("div",{ref:a,className:"shrink-0 flex flex-col border border-border rounded-sm overflow-hidden",children:[n.jsxs("div",{className:"flex items-center gap-1 px-2 py-1 bg-muted/30 border-b border-border shrink-0",children:[n.jsx("button",{type:"button",onClick:o,className:"inline-flex items-center justify-center size-5 shrink-0 text-muted-foreground hover:text-foreground","aria-expanded":r,"aria-label":r?"Collapse table":"Expand table",title:r?"Collapse":"Expand",children:r?n.jsx(w.ChevronDown,{className:"size-3.5"}):n.jsx(w.ChevronRight,{className:"size-3.5"})}),n.jsx("span",{className:"text-xs font-medium truncate",children:e}),s&&n.jsx("span",{className:"text-[10px] uppercase tracking-wide text-primary/70 shrink-0",children:"active"}),!r&&t&&n.jsxs("span",{className:"text-xs text-muted-foreground truncate",children:["#",t]}),n.jsx("div",{className:"flex-1"}),i&&n.jsx(Q,{variant:"ghost",size:"icon-sm",className:"shrink-0",onClick:i,"aria-label":"Close column",title:"Close column",children:n.jsx(w.X,{className:"size-3.5"})})]}),r&&n.jsx("div",{className:"flex flex-col min-h-[18rem] max-h-[34rem]",children:l})]})}function ns(){const e=lr(),{loading:t,error:r,data:s}=Je(),{columns:o,focusedIndex:i,focusColumn:a,closeColumn:l}=Id(),[c,m]=u.useState(""),d=_n(),{search:p}=ps(),f=!!p.get("filter"),{back:x,hasBack:h}=Ma(),b=e?.table,N=o.length>0,T=u.useMemo(()=>s?.find(S=>S.graphQlName===b),[s,b]),k=u.useMemo(()=>T?.columns?.filter(S=>Yi(S.paramType)||Vt(S.paramType)).map(S=>({key:S.name,value:`${S.name},${S.paramType}`,label:S.label})),[T]),[E,y]=u.useState(k?.at(0)?.value??"");u.useEffect(()=>{m(""),y(k?.at(0)?.value??"")},[k]);const v=()=>{if(!c)return;const[S,C]=E.split(",");if(!C)return;const B=C.replace("!","");if(Vt(B)){const $=Zs(c,B);if($===null)return;d(`?filter=["${S}", "_eq", ${JSON.stringify($)}, "${C}"]`)}else B==="String"&&d(`?filter=["${S}", "_contains", ${JSON.stringify(c)}, "${C}"]`)},j=()=>{m("");const S=new URLSearchParams(p.toString());S.delete("filter");const C=S.toString();d(C?`?${C}`:"?")};return t?n.jsxs("div",{className:"flex items-center gap-2 p-2.5",children:[n.jsx(w.Loader2,{className:"size-4 animate-spin text-muted-foreground"}),n.jsx("span",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):r?n.jsx(Rt,{variant:"destructive",className:"m-2",children:n.jsxs(Xt,{children:["Error: ",r.message]})}):n.jsxs("header",{className:"flex flex-wrap items-center gap-x-3 gap-y-1.5 px-3 py-1.5 min-h-[2.5rem]",children:[n.jsxs("div",{className:"flex items-center gap-1.5 overflow-x-auto min-w-0 flex-1",children:[n.jsx(Q,{variant:"ghost",size:"icon-sm",onClick:()=>h&&x(),disabled:!h,"aria-label":"Go back",title:"Go back",className:"shrink-0",children:n.jsx(w.ChevronLeft,{className:"size-4"})}),N?n.jsxs("div",{className:"flex items-center gap-1 overflow-x-auto",children:[n.jsx("button",{type:"button",onClick:()=>a(0),className:`flex items-center gap-1 px-2 py-0.5 rounded text-xs font-medium whitespace-nowrap transition-colors ${i===0?"bg-primary text-primary-foreground":"bg-muted/50 text-muted-foreground hover:bg-muted"}`,children:T?.label??zn(e?.table??"")}),o.map((S,C)=>{const $=s?.find(L=>L.graphQlName===S.panel.tableName)?.label??zn(S.panel.tableName);return n.jsxs("span",{className:`inline-flex items-center gap-1 pl-2 pr-1 py-0.5 rounded text-xs font-medium whitespace-nowrap transition-colors ${i===C+1?"bg-primary text-primary-foreground":"bg-muted/50 text-muted-foreground hover:bg-muted"}`,children:[n.jsx("button",{type:"button",onClick:()=>a(C+1),className:"whitespace-nowrap",children:$}),n.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),l(C+1)},className:"rounded-sm hover:bg-background/50 p-px","aria-label":`Close ${$}`,children:n.jsx(w.X,{className:"size-3"})})]},`${S.panel.tableName}-${S.panel.filterId??C}`)})]}):n.jsx("h2",{className:"text-sm font-semibold whitespace-nowrap",children:T?.label??e?.table??"(Select)"})]}),k&&k.length>0&&n.jsxs("div",{className:"flex items-center border border-border rounded-md overflow-hidden flex-[2_2_16rem] min-w-[12rem]",children:[n.jsxs(Ze,{value:E,onValueChange:y,children:[n.jsx(tt,{size:"sm",className:"w-auto min-w-[120px] shrink-0 border-0 rounded-none border-r border-border h-8 text-xs",children:n.jsx(et,{})}),n.jsx(nt,{children:k.map(S=>n.jsx(we,{value:S.value,children:S.label},S.key))})]}),n.jsxs("div",{className:"relative flex-1 min-w-[180px]",children:[n.jsx(w.Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 size-3.5 text-muted-foreground pointer-events-none"}),n.jsx(Qe,{type:"search",value:c,onChange:S=>m(S.target.value),onKeyDown:S=>S.key==="Enter"&&v(),className:"h-8 border-0 rounded-none focus-visible:ring-0 focus-visible:ring-offset-0",style:{paddingLeft:"2.25rem"},placeholder:"Search..."})]}),n.jsxs(Q,{variant:"ghost",size:"sm",onClick:v,className:"shrink-0 rounded-none border-l border-border h-8 px-3 text-xs",children:[n.jsx(w.Filter,{className:"size-3.5"}),"Filter"]}),f&&n.jsx(Q,{variant:"ghost",size:"sm",onClick:j,title:"Clear filter","aria-label":"Clear filter",className:"shrink-0 rounded-none border-l border-border h-8 px-2 text-xs text-muted-foreground",children:n.jsx(w.X,{className:"size-3.5"})})]}),T&&n.jsxs("div",{className:"flex items-center gap-px border border-border rounded-md overflow-hidden shrink-0",children:[n.jsxs(Q,{variant:"ghost",size:"sm",onClick:()=>d("/"),title:"Back to table list",className:"text-muted-foreground text-xs h-8 px-3 rounded-none",children:[n.jsx(w.Home,{className:"size-3.5"}),"Home"]}),T?.isEditable&&n.jsxs(Q,{variant:"default",size:"sm",onClick:()=>d("edit/"),className:"h-8 text-xs px-4 rounded-none",children:[n.jsx(w.Plus,{className:"size-3.5"}),"Add"]})]})]})}class rr extends u.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,r){const{onError:s,section:o}=this.props;console.error(`Error in ${o??"component"}:`,t,r),s?.(t,r)}handleRetry=()=>{this.setState({hasError:!1,error:null})};render(){const{hasError:t,error:r}=this.state,{children:s,fallback:o,section:i}=this.props;return t?o||n.jsx("div",{className:"flex items-center justify-center p-5 min-h-[100px]",children:n.jsxs(Rt,{variant:"destructive",className:"max-w-[400px]",children:[n.jsx(w.AlertCircle,{className:"size-4"}),n.jsxs(Ys,{children:["Something went wrong",i?` in ${i}`:""]}),n.jsxs(Xt,{className:"mt-2",children:[n.jsx("p",{children:r?.message??"An unexpected error occurred"}),n.jsx(Q,{variant:"destructive",size:"sm",className:"mt-3",onClick:this.handleRetry,children:"Try Again"})]})]})}):s}}function Wd(){const{loading:e,error:t,data:r}=Je();return e?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-3 text-muted-foreground",children:[n.jsx(w.Database,{className:"size-10 animate-pulse"}),n.jsx("p",{className:"text-sm",children:"Loading schema..."})]}):t?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 max-w-md mx-auto text-center",children:[n.jsx(w.Database,{className:"size-12 text-destructive"}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Connection Error"}),n.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:t.message})]})]}):r.length===0?n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-4 max-w-md mx-auto text-center",children:[n.jsx(w.Database,{className:"size-12 text-muted-foreground/50"}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"No Tables Found"}),n.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"This database doesn't contain any tables. It may be a new or empty database."}),n.jsx("p",{className:"mt-3 text-xs text-muted-foreground/70",children:"Create tables in your database and reconnect, or try a different connection."})]})]}):n.jsxs("div",{className:"flex flex-col items-center justify-center h-full gap-6 max-w-lg mx-auto text-center",children:[n.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground/50",children:[n.jsx(w.Table2,{className:"size-10"}),n.jsx(w.MousePointerClick,{className:"size-6"})]}),n.jsxs("div",{children:[n.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Select a Table"}),n.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Choose a table from the sidebar to browse and edit its data."})]}),n.jsxs("div",{className:"text-xs text-muted-foreground/60 border border-border rounded-md px-4 py-3 bg-muted/30",children:[n.jsxs("p",{className:"font-medium text-muted-foreground mb-1",children:[r.length," table",r.length!==1?"s":""," available"]}),n.jsxs("p",{className:"leading-relaxed",children:[r.slice(0,8).map(s=>s.label).join(", "),r.length>8?`, and ${r.length-8} more`:""]})]})]})}function Jd({children:e}){const{loading:t,error:r}=Je();return t?n.jsxs("div",{className:"flex items-center justify-center flex-1 gap-3 text-muted-foreground",children:[n.jsx(w.Loader2,{className:"size-6 animate-spin"}),n.jsx("span",{className:"text-sm",children:"Connecting to database..."})]}):r?n.jsx("div",{className:"flex items-center justify-center flex-1",children:n.jsxs(Rt,{variant:"destructive",className:"max-w-lg",children:[n.jsx(w.AlertCircle,{className:"size-4"}),n.jsx(Ys,{children:"Database Connection Error"}),n.jsxs(Xt,{className:"mt-2",children:[n.jsx("p",{className:"text-sm",children:r.message}),n.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Check your connection string and ensure the database server is running."})]})]})}):n.jsx(n.Fragment,{children:e})}function Qd(){const[e,t]=u.useState(!0),r=ba({key:"sidebar-width",initial:240,min:150,max:560,axis:"x"});return n.jsx(Jd,{children:n.jsx(Md,{children:n.jsxs("div",{className:"grid h-full flex-1 min-h-0 grid-rows-[auto_1fr]",style:{gridTemplateColumns:e?`${r.size}px 1fr`:"0px 1fr"},children:[n.jsxs("div",{className:"col-span-full sticky top-0 z-50 bg-background border-b border-border flex items-center",children:[n.jsx(Q,{variant:"ghost",size:"icon",className:"md:hidden ml-1 shrink-0",onClick:()=>t(!e),"aria-label":"Toggle sidebar",title:"Toggle sidebar",children:n.jsx(w.PanelLeft,{className:"size-5"})}),n.jsx("div",{className:"flex-1 min-w-0",children:n.jsx(rr,{section:"Header",children:n.jsxs(cr,{children:[n.jsx(Be,{path:"/:table/*",element:n.jsx(ns,{})}),n.jsx(Be,{path:"/:table",element:n.jsx(ns,{})}),n.jsx(Be,{path:"/",element:n.jsx(ns,{})})]})})})]}),n.jsxs("nav",{"aria-label":"Tables",className:`relative border-r border-border overflow-hidden min-h-0 ${e?"":"hidden"} md:block`,children:[n.jsx(rr,{section:"Table List",children:n.jsx(Xl,{})}),n.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize table list",tabIndex:0,"data-testid":"sidebar-resize-handle",className:"absolute inset-y-0 right-0 w-1.5 cursor-col-resize select-none touch-none hover:bg-primary/40 focus-visible:bg-primary/60 focus-visible:outline-none",onPointerDown:r.onPointerDown,onKeyDown:r.onKeyDown})]}),n.jsxs("main",{className:"flex flex-col overflow-hidden min-h-0 px-1 py-0.5",children:[n.jsx(rr,{section:"Data Panel",children:n.jsxs(cr,{children:[n.jsx(Be,{path:"/:table/from/:filterTable/:id/edit/:editId",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/from/:filterTable/:id",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/:id/edit/:editId",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/:id",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/edit/:editId",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table/edit",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/:table",element:n.jsx(Jt,{})}),n.jsx(Be,{path:"/",element:n.jsx(Wd,{})})]})}),n.jsx(rr,{section:"Data Edit",children:n.jsxs(cr,{children:[n.jsx(Be,{path:"/:table/from/:filterTable/:id/edit/:editId",element:n.jsx(Zn,{})}),n.jsx(Be,{path:"/:table/:id/edit/:editId",element:n.jsx(Zn,{})}),n.jsx(Be,{path:"/:table/edit/:editId",element:n.jsx(Zn,{})}),n.jsx(Be,{path:"/:table/edit",element:n.jsx(Zn,{})})]})})]})]})})})}function Hd({onLocate:e}){const t=fs();return u.useEffect(()=>{e?.(t)},[t,e]),n.jsx(Qd,{})}function va({uri:e,fetcher:t,uiPath:r,onLocate:s,showStats:o=!1,tables:i,defaultColumns:a,trailingColumns:l,tableActions:c,saveFile:m}){const d=u.useMemo(()=>t||(e?new bs(e):null),[e,t]),p=u.useMemo(()=>({showStats:o,tables:i,defaultColumns:a,trailingColumns:l,tableActions:c,saveFile:m}),[o,i,a,l,c,m]),f=u.useMemo(()=>new de.QueryClient({defaultOptions:{queries:{staleTime:300*1e3,retry:1}}}),[]);if(!d)throw new Error("Editor requires either a `fetcher` (GraphQLFetcher) or a `uri` prop to reach the GraphQL endpoint; neither was provided.");return n.jsx(de.QueryClientProvider,{client:f,children:n.jsx(vs,{value:d,children:n.jsx(Qa,{config:p,children:n.jsx(ko,{children:n.jsx(Ia,{path:r||"/",children:n.jsx(Cs,{children:n.jsx(Hd,{onLocate:s})})})})})})})}const Ud=["query","form","report","dashboard"];class ja extends Error{constructor(t){super(t),this.name="SavedObjectConflictError"}}const wa="/_saved-objects";function Yd(e=""){const t=`${e}${wa}`,r=encodeURIComponent;async function s(o){try{return(await o.json())?.error??`${o.status} ${o.statusText}`}catch{return`${o.status} ${o.statusText}`}}return{async list(o,i,a){const l=o?`${t}/${r(o)}`:t,c=await fetch(l,{signal:i});if(!c.ok)throw new Error(`Failed to list saved objects: ${await s(c)}`);const m=await c.json();if(!Array.isArray(m))throw new Error("Failed to list saved objects: the server did not return a list.");const d=m.map(sr),p=d.filter(f=>f!==null);return p.length!==d.length&&a?.(d.length-p.length),p},async get(o,i,a){const l=await fetch(`${t}/${r(o)}/${r(i)}`,{signal:a});if(l.status===404)return null;if(!l.ok)throw new Error(`Failed to load saved object: ${await s(l)}`);return sr(await l.json())},async put(o,i){const a=await fetch(`${t}/${r(o.type)}/${r(o.id)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:i});if(a.status===409)throw new ja(await s(a));if(!a.ok)throw new Error(`Failed to save object: ${await s(a)}`);const l=sr(await a.json());if(l===null)throw new Error("Server returned a malformed saved object.");return l},async remove(o,i,a){const l=await fetch(`${t}/${r(o)}/${r(i)}`,{method:"DELETE",signal:a});if(!l.ok&&l.status!==404)throw new Error(`Failed to delete saved object: ${await s(l)}`)}}}function sr(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.id!="string"||t.id.length===0||typeof t.type!="string"||!Ud.includes(t.type)||typeof t.name!="string"||typeof t.version!="number"||!("definition"in t)?null:{id:t.id,type:t.type,name:t.name,folder:typeof t.folder=="string"?t.folder:void 0,definition:t.definition,version:t.version}}const Rd=4,Xd=new Set(["text","textarea","number","checkbox","date","datetime","select"]);function Zd(e){return typeof e=="string"&&Xd.has(e)?e:"text"}function em(e){return typeof e!="number"||!Number.isFinite(e)?1:Math.min(Rd,Math.max(1,Math.trunc(e)))}function tm(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.column!="string"||t.column===""?null:{column:t.column,label:typeof t.label=="string"?t.label:t.column,control:Zd(t.control),readOnly:t.readOnly===!0,required:t.required===!0,include:t.include!==!1}}function nm(e){if(typeof e!="object"||e===null)return null;const t=e;return typeof t.relationship!="string"||typeof t.childTable!="string"||!Array.isArray(t.parentColumns)||!Array.isArray(t.childColumns)||!t.parentColumns.every(r=>typeof r=="string")||!t.childColumns.every(r=>typeof r=="string")||t.parentColumns.length===0||t.parentColumns.length!==t.childColumns.length?null:{relationship:t.relationship,childTable:t.childTable,parentColumns:t.parentColumns,childColumns:t.childColumns,label:typeof t.label=="string"?t.label:t.childTable,mode:t.mode==="stacked"?"stacked":"grid"}}function rm(e){if(typeof e!="object"||e===null)return null;const t=e;if(typeof t.table!="string"||t.table===""||!Array.isArray(t.fields))return null;const r=t.fields.map(tm).filter(s=>s!==null);return r.length===0?null:{table:t.table,title:typeof t.title=="string"?t.title:t.table,columns:em(t.columns),fields:r,subforms:Array.isArray(t.subforms)?t.subforms.map(nm).filter(s=>s!==null):void 0}}function Ca(e){return e.fields.filter(t=>t.include)}const sm=new Set(["text","textarea","number","checkbox","date","datetime","select"]);function om(e){return e!==void 0&&sm.has(e)?e:void 0}function am(e,t){return{control:om(t?.widget)??e.control,readOnly:e.readOnly||t?.readOnly===!0,visible:e.include&&t?.visible!==!1}}function im(e){switch(e){case"textarea":return{kind:"textarea"};case"checkbox":return{kind:"checkbox"};case"select":return{kind:"select"};case"number":return{kind:"input",type:"number"};case"date":return{kind:"input",type:"date"};case"datetime":return{kind:"input",type:"datetime-local"};default:return{kind:"input",type:"text"}}}function Na(e,t,r){const s=Math.max(0,t-1);switch(r){case"first":return 0;case"last":return s;case"prev":return Math.max(0,Math.min(s,e-1));case"next":return Math.max(0,Math.min(s,e+1))}}function or(e,t,r){return Na(e,t,r)!==e}function lm(e,t){return t<=0?"0 of 0":`${e+1} of ${t}`}function cm(e,t,r){return r.sourceColumnNames.length>0&&r.sourceColumnNames.length===r.destinationColumnNames.length&&r.sourceColumnNames.every(s=>e.columns.some(o=>o.name===s))&&r.destinationColumnNames.every(s=>t.columns.some(o=>o.name===s))}function um(e,t,r,s){if(!s||!cm(e,t,r))return null;const o=[],i=[],a={};for(let l=0;l<r.sourceColumnNames.length;l++){const c=r.sourceColumnNames[l],m=r.destinationColumnNames[l],d=s[c];if(d==null)return null;const p=t.columns.find(x=>x.name===m)?.paramType.replace("!","")??"String",f=`parent_${c}`;o.push(`$${f}: ${p}`),i.push(`{${m}: {_eq: $${f}}}`),a[f]=dt(d,p)}return{params:o,filter:i.length===1?i[0]:`{and: [${i.join(", ")}]}`,variables:a}}function dm(e,t){return!t||e.sourceColumnNames.length!==e.destinationColumnNames.length?{}:Object.fromEntries(e.destinationColumnNames.map((r,s)=>[r,t[e.sourceColumnNames[s]]]))}function mm(e){return{table:e.name,title:e.label,columns:1,fields:e.columns.map(t=>({column:t.name,label:t.label,control:t.paramType.startsWith("Boolean")?"checkbox":t.paramType.startsWith("Int")||t.paramType.startsWith("Float")||t.paramType.startsWith("Decimal")?"number":"text",readOnly:t.isReadOnly||t.isIdentity,required:!t.isNullable,include:!0}))}}function fm({parent:e,child:t,subform:r,row:s}){const o=$e(),i=de.useQueryClient(),a=Hn(t),[l,c]=u.useState(null),m=u.useMemo(()=>({name:r.relationship,fieldName:r.relationship,sourceColumnNames:r.parentColumns,destinationTable:t.name,destinationColumnNames:r.childColumns}),[r,t.name]),d=u.useMemo(()=>um(e,t,m,s),[e,t,m,s]),p=u.useMemo(()=>t.columns.map(j=>(je(j.name,"form subform field"),j.name)),[t]),f=u.useMemo(()=>d?(je(t.name,"form subform table"),`query FormSubform_${t.name}(${d.params.join(", ")}) { ${t.name}(filter: ${d.filter}) { data { ${p.join(" ")} } } }`):null,[t.name,p,d]),x=["formSubform",e.name,t.name,He(s,e,0)],{data:h,isLoading:b,error:N}=de.useQuery({queryKey:x,queryFn:()=>o.query(f,d.variables),enabled:!!f}),T=u.useMemo(()=>mm(t),[t]),k=u.useMemo(()=>dm(m,s),[m,s]);if(!d)return n.jsx("p",{style:lt.notice,children:"Related records unavailable: this relationship is incomplete."});if(b)return n.jsxs("p",{style:lt.notice,children:["Loading ",r.label,"…"]});if(N)return n.jsxs("p",{role:"alert",style:lt.error,children:["Failed to load ",r.label,": ",N.message]});const E=h?.[t.name]?.data??[],y=async j=>{const S=mt(j,t);S&&(await a.deleteRow(S),await i.invalidateQueries({queryKey:x}))},v=async()=>{c(null),await i.invalidateQueries({queryKey:x})};return n.jsxs("section",{style:lt.root,"aria-label":r.label,children:[n.jsx("h3",{style:lt.title,children:r.label}),n.jsxs("button",{type:"button",onClick:()=>c({kind:"create"}),children:["Add ",r.label]}),l?n.jsx("div",{style:lt.childForm,children:n.jsx(ss,{table:t,definition:T,hiddenFields:r.childColumns,initialValues:l.kind==="create"?k:void 0,startInNewMode:l.kind==="create",initialPkRoute:l.kind==="edit"?He(l.row,t,l.index??0):void 0,onClose:()=>{v()}},l.kind==="create"?"create":He(l.row,t,l.index??0))}):E.length===0?n.jsx("p",{style:lt.notice,children:"No related records."}):r.mode==="grid"?n.jsxs("table",{style:lt.table,children:[n.jsx("thead",{children:n.jsxs("tr",{children:[t.columns.map(j=>n.jsx("th",{style:lt.cell,children:j.label},j.name)),n.jsx("th",{})]})}),n.jsx("tbody",{children:E.map((j,S)=>n.jsxs("tr",{children:[t.columns.map(C=>n.jsx("td",{style:lt.cell,children:String(j[C.name]??"")},C.name)),n.jsxs("td",{children:[n.jsx("button",{type:"button",onClick:()=>c({kind:"edit",row:j,index:S}),children:"Edit"}),n.jsx("button",{type:"button",onClick:()=>y(j),disabled:a.isPending,children:"Delete"})]})]},He(j,t,S)))})]}):n.jsx("div",{children:E.map((j,S)=>n.jsxs("article",{style:lt.card,children:[t.columns.map(C=>n.jsxs("div",{children:[n.jsxs("strong",{children:[C.label,": "]}),String(j[C.name]??"")]},C.name)),n.jsx("button",{type:"button",onClick:()=>c({kind:"edit",row:j,index:S}),children:"Edit"}),n.jsx("button",{type:"button",onClick:()=>y(j),disabled:a.isPending,children:"Delete"})]},He(j,t,S)))})]})}const lt={root:{marginTop:20,borderTop:"1px solid #d1d5db",paddingTop:12},title:{margin:"0 0 8px",fontSize:15},notice:{color:"#6b7280",fontSize:13},error:{color:"#b91c1c",fontSize:13},table:{width:"100%",borderCollapse:"collapse",fontSize:13},cell:{textAlign:"left",padding:5,borderBottom:"1px solid #e5e7eb"},card:{border:"1px solid #e5e7eb",borderRadius:6,padding:8,marginBottom:8,fontSize:13},childForm:{minHeight:420,border:"1px solid #e5e7eb",borderRadius:6,marginTop:8}},pm={};function hm(e){const t=e.lastIndexOf(".");return t>=0?e.slice(t+1):e}function rs(e,t){const r=e.findTable(t);if(r)return r;const s=hm(t);return e.data.find(o=>o.graphQlName===t||o.dbName===t||o.graphQlName===s||o.dbName===s)}const gm="\0new";function xm(e,t){const r=new Set;for(const s of e)r.add(s.column.name);for(const s of t.primaryKeys??[])r.add(s);return[...r]}function bm(e,t){je(e.name,"form browse table name");for(const r of t)je(r,"form browse selection field");return`query FormBrowse_${e.name}($limit: Int, $offset: Int) { ${e.name}(limit: $limit offset: $offset) { total data { ${t.join(" ")} } } }`}function ar(e,t,r){return e==="checkbox"?!!r:(e==="date"||e==="datetime")&&(r==null||typeof r=="string")?Vr(r??void 0,e==="datetime"||Rn(t)&&!1):r==null?"":String(r)}function ym(e,t){const r={fields:{},form:null},s=e?.errors;if(Array.isArray(s)){const o=[];for(const i of s){const a=i.path?.[i.path.length-1];typeof a=="string"&&t.has(a)?r.fields[a]=i.message:o.push(i.message)}return r.form=o.length>0?o.join("; "):null,r}return r.form=e instanceof Error?e.message:String(e),r}function ss({table:e,definition:t,fieldMetadata:r,onClose:s,schema:o,initialValues:i=pm,hiddenFields:a=[],startInNewMode:l=!1,initialPkRoute:c}){const m=$e(),d=de.useQueryClient(),p=u.useMemo(()=>new Map(e.columns.map(O=>[O.name,O])),[e]),[f,x]=u.useState(c?{kind:"pk",route:c}:{kind:"offset",index:0}),[h,b]=u.useState(l?"new":"browse"),[N,T]=u.useState(i),[k,E]=u.useState({}),[y,v]=u.useState(null),[j,S]=u.useState(""),[C,B]=u.useState(0),$=h==="new",L=u.useMemo(()=>Ca(t).map(O=>{const Z=p.get(O.column);if(!Z)return null;const ee=am(O,r?.[O.column]);return ee.visible?{field:O,column:Z,control:ee.control,readOnly:ee.readOnly}:null}).filter(O=>O!==null),[t,p,r]),q=u.useCallback(O=>!(O.readOnly||O.column.isReadOnly||O.column.isIdentity||O.column.isPrimaryKey&&!$),[$]),D=u.useMemo(()=>L.filter(q).map(O=>({column:O.column})),[L,q]),V=u.useMemo(()=>(e.primaryKeys??[]).map(O=>p.get(O)).filter(O=>!!O),[e,p]),X=u.useMemo(()=>new Set(D.map(O=>O.column.name)),[D]),F=u.useMemo(()=>{const O=new Set(xm(L,e));for(const Z of t.subforms??[])for(const ee of Z.parentColumns)O.add(ee);return[...O]},[L,e,t.subforms]),P=u.useMemo(()=>{if($||L.length===0)return null;if(f.kind==="offset")return{text:bm(e,F),variables:{limit:1,offset:f.index},kind:"offset"};const O=fn(f.route,e),Z=O?Vn(O,e):null;return Z?{text:Cr(e,Z,F),variables:Z.variables,kind:"pk"}:null},[$,L.length,f,e,F]),{data:A,isLoading:U,error:_}=de.useQuery({queryKey:["formRunner",e.name,f,$],queryFn:()=>m.query(P.text,P.variables),enabled:!$&&P!==null}),ce=u.useMemo(()=>!A||!P?null:P.kind==="offset"?A[e.name]?.data?.[0]??null:A.value?.data?.[0]??null,[A,P,e.name]);u.useEffect(()=>{if(A&&P?.kind==="offset"){const O=A[e.name];O&&B(O.total)}},[A,P,e.name]);const he=$?gm:ce?He(ce,e,0):null,Ue=u.useRef(null),Pe=u.useRef(!1);u.useEffect(()=>{if(Ue.current===he&&Pe.current)return;if(Ue.current=he,Pe.current=!1,E({}),v(null),$){T(i);return}const O={};for(const Z of L)O[Z.column.name]=ce?.[Z.column.name]??null;T(O)},[he,ce,$,L,i]);const ie=f.kind==="offset"?f.index:-1,se=u.useMemo(()=>$||!ce?"":He(ce,e,ie<0?0:ie),[$,ce,e,ie]),ke=wn(e,D,V,se),Ae=Hn(e),re=u.useCallback(O=>{b("browse"),x(Z=>{const ee=Z.kind==="offset"?Z.index:0;return{kind:"offset",index:Na(ee,C,O)}})},[C]),Ee=u.useCallback(()=>{b("new")},[]),Ie=u.useCallback(()=>{const O=j.trim();O!==""&&(b("browse"),x({kind:"pk",route:O}))},[j]),Le=u.useCallback((O,Z)=>{Pe.current=!0,T(ee=>({...ee,[O]:Z}))},[]),Ge=u.useCallback(async()=>{const O={};for(const ee of L){if(!q(ee))continue;const Ce=ee.field.required||!ee.column.isNullable,xe=Ar(ee.column,N[ee.column.name],Ce);xe&&(O[ee.column.name]=xe)}if(Object.keys(O).length>0){E(O),v(null);return}E({}),v(null);const Z={};for(const ee of X)Z[ee]=N[ee];try{if($){const Ce=(await ke.insert(Z))?.[e.name],xe={},qe=e.primaryKeys??[];for(const W of qe){const me=p.get(W);xe[W]=qe.length===1&&me?.isIdentity?Ce:N[W]}b("browse"),x({kind:"pk",route:Bn(xe,e)})}else await ke.update(Z),Pe.current=!1,await d.invalidateQueries({queryKey:["formRunner",e.name]})}catch(ee){const Ce=ym(ee,X);E(Ce.fields),v(Ce.form)}},[L,q,N,X,$,ke,e,p,d]),Oe=u.useCallback(async()=>{const O=mt(ce,e);if(O)try{await Ae.deleteRow(O),b("browse"),x({kind:"offset",index:Math.max(0,(ie<0?0:ie)-1)}),await d.invalidateQueries({queryKey:["formRunner",e.name]})}catch(Z){v(Z instanceof Error?Z.message:String(Z))}},[ce,e,Ae,ie,d]);if(L.length===0)return n.jsx("div",{style:fe.notice,children:"This form has no fields that match the current schema."});const ye=f.kind==="pk"?`key ${f.route}`:lm(ie,C),ze=!$&&f.kind==="offset"&&C===0&&!U;return n.jsxs("div",{style:fe.root,children:[n.jsxs("div",{style:fe.toolbar,role:"toolbar","aria-label":"Record navigation",children:[n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("first"),disabled:$||!or(ie,C,"first"),"aria-label":"First record",children:"⏮"}),n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("prev"),disabled:$||!or(ie,C,"prev"),"aria-label":"Previous record",children:"◀"}),n.jsx("span",{style:fe.position,"aria-label":"Record position",children:$?"New record":ye}),n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("next"),disabled:$||!or(ie,C,"next"),"aria-label":"Next record",children:"▶"}),n.jsx("button",{type:"button",style:fe.btn,onClick:()=>re("last"),disabled:$||!or(ie,C,"last"),"aria-label":"Last record",children:"⏭"}),n.jsx("span",{style:fe.spacer}),n.jsx("input",{style:fe.jump,value:j,onChange:O=>S(O.target.value),placeholder:"Jump to key…","aria-label":"Jump to key"}),n.jsx("button",{type:"button",style:fe.btn,onClick:Ie,"aria-label":"Go to key",children:"Go"}),n.jsx("button",{type:"button",style:fe.btn,onClick:Ee,"aria-label":"New record",children:"New"}),s&&n.jsx("button",{type:"button",style:fe.btn,onClick:s,"aria-label":"Close form",children:"✕"})]}),n.jsxs("div",{style:fe.body,children:[n.jsx("h2",{style:fe.title,children:t.title}),y&&n.jsx("div",{role:"alert",style:fe.formError,children:y}),_&&n.jsxs("div",{role:"alert",style:fe.formError,children:["Failed to load record: ",_.message]}),ze?n.jsx("p",{style:fe.notice,children:"No records. Use “New” to create one."}):n.jsx("div",{style:{...fe.grid,gridTemplateColumns:`repeat(${t.columns}, minmax(0, 1fr))`},children:L.filter(O=>!a.includes(O.column.name)).map(O=>{const Z=q(O),ee=N[O.column.name],Ce=k[O.column.name],xe=O.field.required||!O.column.isNullable;return n.jsxs("label",{style:fe.field,children:[n.jsxs("span",{style:fe.label,children:[O.field.label,xe&&n.jsx("span",{style:fe.req,children:" *"})]}),vm(O,ee,Z,xe,Le),Ce&&n.jsx("span",{role:"alert",style:fe.fieldError,children:Ce})]},O.column.name)})}),!$&&ce&&o&&(t.subforms??[]).map(O=>{const Z=rs(o,O.childTable);return Z?n.jsx(fm,{parent:e,child:Z,subform:O,row:ce},O.relationship):n.jsxs("p",{style:fe.notice,children:[O.label," is not available in this schema."]},O.relationship)})]}),n.jsxs("div",{style:fe.footer,children:[n.jsx("button",{type:"button",style:fe.primaryBtn,onClick:Ge,disabled:ke.isPending||ze&&!$,children:$?"Create":"Save"}),!$&&!ze&&n.jsx("button",{type:"button",style:fe.btn,onClick:Oe,disabled:Ae.isPending,children:"Delete"})]})]})}function vm(e,t,r,s,o){const i=e.column.name,a=im(e.control),l={id:i,"aria-label":e.field.label,disabled:!r,style:fe.control};if(a.kind==="checkbox")return n.jsx("input",{...l,type:"checkbox",checked:!!ar("checkbox",e.column,t),onChange:c=>o(i,c.target.checked)});if(a.kind==="textarea")return n.jsx("textarea",{...l,rows:3,required:s,value:String(ar("text",e.column,t)),onChange:c=>o(i,c.target.value)});if(a.kind==="select"){const c=e.column.enumValues??[],m=e.column.enumLabels&&e.column.enumLabels.length===c.length?e.column.enumLabels:c;return n.jsxs("select",{...l,value:String(ar("text",e.column,t)),onChange:d=>o(i,d.target.value===""?null:d.target.value),children:[!s&&n.jsx("option",{value:"",children:"(none)"}),c.map((d,p)=>n.jsx("option",{value:d,children:m[p]??d},d))]})}return n.jsx("input",{...l,type:a.type,required:s,value:String(ar(e.control,e.column,t)),onChange:c=>o(i,c.target.value)})}function ka({definition:e,fieldMetadata:t,onClose:r}){const s=Je();if(s.loading)return n.jsx("div",{style:fe.notice,children:"Loading schema…"});if(s.error)return n.jsxs("div",{style:fe.notice,children:["Could not load schema: ",s.error.message]});const o=rs(s,e.table);return o?n.jsx(ss,{table:o,definition:e,fieldMetadata:t,onClose:r,schema:s}):n.jsxs("div",{style:fe.notice,children:["Table “",e.table,"” is not in the current schema."]})}const fe={root:{display:"flex",flexDirection:"column",height:"100%",minHeight:0},toolbar:{display:"flex",alignItems:"center",gap:6,padding:"8px 12px",borderBottom:"1px solid var(--border, #d1d5db)",flexWrap:"wrap"},position:{fontSize:13,color:"#374151",minWidth:80,textAlign:"center"},spacer:{flex:1},jump:{padding:"4px 6px",border:"1px solid var(--border, #d1d5db)",borderRadius:6,font:"inherit",fontSize:13,width:120},body:{flex:1,minHeight:0,overflow:"auto",padding:16},title:{margin:"0 0 16px",fontSize:18},grid:{display:"grid",gap:14,maxWidth:720},field:{display:"flex",flexDirection:"column",gap:4,minWidth:0},label:{fontSize:12,fontWeight:600,color:"#374151"},control:{padding:"6px 8px",border:"1px solid var(--border, #d1d5db)",borderRadius:6,font:"inherit",fontSize:13},footer:{display:"flex",gap:8,padding:"8px 12px",borderTop:"1px solid var(--border, #d1d5db)"},btn:{border:"1px solid var(--border, #d1d5db)",background:"transparent",borderRadius:6,padding:"6px 12px",cursor:"pointer",font:"inherit"},primaryBtn:{border:"1px solid #2563eb",background:"#2563eb",color:"#fff",borderRadius:6,padding:"6px 16px",cursor:"pointer",font:"inherit"},req:{color:"#dc2626"},formError:{background:"#fef2f2",border:"1px solid #fecaca",color:"#b91c1c",borderRadius:6,padding:"8px 10px",marginBottom:12,fontSize:13},fieldError:{color:"#dc2626",fontSize:12},notice:{padding:24,color:"#6b7280"}};function jm({fetcher:e,definition:t,fieldMetadata:r,onClose:s}){const o=u.useMemo(()=>new de.QueryClient({defaultOptions:{queries:{staleTime:3e5,retry:1}}}),[]);return n.jsx(de.QueryClientProvider,{client:o,children:n.jsx(vs,{value:e,children:n.jsx(ko,{children:n.jsx(Cs,{children:n.jsx(ka,{definition:t,fieldMetadata:r,onClose:s})})})})})}ae.DEFAULT_ROW_CAP=Pr,ae.Editor=va,ae.FormRunner=ka,ae.FormRunnerHost=jm,ae.FormRunnerView=ss,ae.GraphQLRequestError=xs,ae.HttpGraphQLFetcher=bs,ae.SAVED_OBJECTS_PATH=wa,ae.SavedObjectConflictError=ja,ae.UTF8_BOM=xo,ae.buildCsv=bo,ae.buildJson=jo,ae.createSavedObjectsClient=Yd,ae.default=va,ae.deserializeColumnFilters=jr,ae.downloadTextFile=wo,ae.exportAllRows=_r,ae.filenameFor=Dr,ae.formatCsvCell=Er,ae.mimeFor=zr,ae.parseFormDefinition=rm,ae.parseSavedObject=sr,ae.resolveDefinitionTable=rs,ae.serializeColumnFilters=vr,ae.useTableMutation=wn,ae.visibleFields=Ca,Object.defineProperties(ae,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})}));