openrouter-model-picker
Version:
Third-party React component for OpenRouter model selection
31 lines (28 loc) • 39.2 kB
JavaScript
"use strict";var Er=Object.defineProperty;var kr=(i,t,o)=>t in i?Er(i,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):i[t]=o;var K=(i,t,o)=>kr(i,typeof t!="symbol"?t+"":t,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const j=require("react");var he={exports:{}},H={};/**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var Ne;function _r(){if(Ne)return H;Ne=1;var i=j,t=Symbol.for("react.element"),o=Symbol.for("react.fragment"),l=Object.prototype.hasOwnProperty,d=i.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,h={key:!0,ref:!0,__self:!0,__source:!0};function C(v,a,y){var x,c={},u=null,p=null;y!==void 0&&(u=""+y),a.key!==void 0&&(u=""+a.key),a.ref!==void 0&&(p=a.ref);for(x in a)l.call(a,x)&&!h.hasOwnProperty(x)&&(c[x]=a[x]);if(v&&v.defaultProps)for(x in a=v.defaultProps,a)c[x]===void 0&&(c[x]=a[x]);return{$$typeof:t,type:v,key:u,ref:p,props:c,_owner:d.current}}return H.Fragment=o,H.jsx=C,H.jsxs=C,H}var J={};/**
* @license React
* react-jsx-runtime.development.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/var ze;function Sr(){return ze||(ze=1,process.env.NODE_ENV!=="production"&&function(){var i=j,t=Symbol.for("react.element"),o=Symbol.for("react.portal"),l=Symbol.for("react.fragment"),d=Symbol.for("react.strict_mode"),h=Symbol.for("react.profiler"),C=Symbol.for("react.provider"),v=Symbol.for("react.context"),a=Symbol.for("react.forward_ref"),y=Symbol.for("react.suspense"),x=Symbol.for("react.suspense_list"),c=Symbol.for("react.memo"),u=Symbol.for("react.lazy"),p=Symbol.for("react.offscreen"),k=Symbol.iterator,R="@@iterator";function P(e){if(e===null||typeof e!="object")return null;var n=k&&e[k]||e[R];return typeof n=="function"?n:null}var T=i.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;function E(e){{for(var n=arguments.length,s=new Array(n>1?n-1:0),f=1;f<n;f++)s[f-1]=arguments[f];L("error",e,s)}}function L(e,n,s){{var f=T.ReactDebugCurrentFrame,b=f.getStackAddendum();b!==""&&(n+="%s",s=s.concat([b]));var w=s.map(function(g){return String(g)});w.unshift("Warning: "+n),Function.prototype.apply.call(console[e],console,w)}}var N=!1,re=!1,Y=!1,te=!1,ne=!1,W;W=Symbol.for("react.module.reference");function oe(e){return!!(typeof e=="string"||typeof e=="function"||e===l||e===h||ne||e===d||e===y||e===x||te||e===p||N||re||Y||typeof e=="object"&&e!==null&&(e.$$typeof===u||e.$$typeof===c||e.$$typeof===C||e.$$typeof===v||e.$$typeof===a||e.$$typeof===W||e.getModuleId!==void 0))}function ie(e,n,s){var f=e.displayName;if(f)return f;var b=n.displayName||n.name||"";return b!==""?s+"("+b+")":s}function I(e){return e.displayName||"Context"}function M(e){if(e==null)return null;if(typeof e.tag=="number"&&E("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case l:return"Fragment";case o:return"Portal";case h:return"Profiler";case d:return"StrictMode";case y:return"Suspense";case x:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case v:var n=e;return I(n)+".Consumer";case C:var s=e;return I(s._context)+".Provider";case a:return ie(e,e.render,"ForwardRef");case c:var f=e.displayName||null;return f!==null?f:M(e.type)||"Memo";case u:{var b=e,w=b._payload,g=b._init;try{return M(g(w))}catch{return null}}}return null}var $=Object.assign,B=0,ge,ve,ye,xe,be,je,Ce;function we(){}we.__reactDisabledLog=!0;function Ze(){{if(B===0){ge=console.log,ve=console.info,ye=console.warn,xe=console.error,be=console.group,je=console.groupCollapsed,Ce=console.groupEnd;var e={configurable:!0,enumerable:!0,value:we,writable:!0};Object.defineProperties(console,{info:e,log:e,warn:e,error:e,group:e,groupCollapsed:e,groupEnd:e})}B++}}function Qe(){{if(B--,B===0){var e={configurable:!0,enumerable:!0,writable:!0};Object.defineProperties(console,{log:$({},e,{value:ge}),info:$({},e,{value:ve}),warn:$({},e,{value:ye}),error:$({},e,{value:xe}),group:$({},e,{value:be}),groupCollapsed:$({},e,{value:je}),groupEnd:$({},e,{value:Ce})})}B<0&&E("disabledDepth fell below zero. This is a bug in React. Please file an issue.")}}var se=T.ReactCurrentDispatcher,ae;function G(e,n,s){{if(ae===void 0)try{throw Error()}catch(b){var f=b.stack.trim().match(/\n( *(at )?)/);ae=f&&f[1]||""}return`
`+ae+e}}var le=!1,X;{var er=typeof WeakMap=="function"?WeakMap:Map;X=new er}function Te(e,n){if(!e||le)return"";{var s=X.get(e);if(s!==void 0)return s}var f;le=!0;var b=Error.prepareStackTrace;Error.prepareStackTrace=void 0;var w;w=se.current,se.current=null,Ze();try{if(n){var g=function(){throw Error()};if(Object.defineProperty(g.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(g,[])}catch(O){f=O}Reflect.construct(e,[],g)}else{try{g.call()}catch(O){f=O}e.call(g.prototype)}}else{try{throw Error()}catch(O){f=O}e()}}catch(O){if(O&&f&&typeof O.stack=="string"){for(var m=O.stack.split(`
`),F=f.stack.split(`
`),_=m.length-1,S=F.length-1;_>=1&&S>=0&&m[_]!==F[S];)S--;for(;_>=1&&S>=0;_--,S--)if(m[_]!==F[S]){if(_!==1||S!==1)do if(_--,S--,S<0||m[_]!==F[S]){var D=`
`+m[_].replace(" at new "," at ");return e.displayName&&D.includes("<anonymous>")&&(D=D.replace("<anonymous>",e.displayName)),typeof e=="function"&&X.set(e,D),D}while(_>=1&&S>=0);break}}}finally{le=!1,se.current=w,Qe(),Error.prepareStackTrace=b}var V=e?e.displayName||e.name:"",z=V?G(V):"";return typeof e=="function"&&X.set(e,z),z}function rr(e,n,s){return Te(e,!1)}function tr(e){var n=e.prototype;return!!(n&&n.isReactComponent)}function Z(e,n,s){if(e==null)return"";if(typeof e=="function")return Te(e,tr(e));if(typeof e=="string")return G(e);switch(e){case y:return G("Suspense");case x:return G("SuspenseList")}if(typeof e=="object")switch(e.$$typeof){case a:return rr(e.render);case c:return Z(e.type,n,s);case u:{var f=e,b=f._payload,w=f._init;try{return Z(w(b),n,s)}catch{}}}return""}var q=Object.prototype.hasOwnProperty,Ee={},ke=T.ReactDebugCurrentFrame;function Q(e){if(e){var n=e._owner,s=Z(e.type,e._source,n?n.type:null);ke.setExtraStackFrame(s)}else ke.setExtraStackFrame(null)}function nr(e,n,s,f,b){{var w=Function.call.bind(q);for(var g in e)if(w(e,g)){var m=void 0;try{if(typeof e[g]!="function"){var F=Error((f||"React class")+": "+s+" type `"+g+"` is invalid; it must be a function, usually from the `prop-types` package, but received `"+typeof e[g]+"`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");throw F.name="Invariant Violation",F}m=e[g](n,g,f,s,null,"SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED")}catch(_){m=_}m&&!(m instanceof Error)&&(Q(b),E("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).",f||"React class",s,g,typeof m),Q(null)),m instanceof Error&&!(m.message in Ee)&&(Ee[m.message]=!0,Q(b),E("Failed %s type: %s",s,m.message),Q(null))}}}var or=Array.isArray;function ce(e){return or(e)}function ir(e){{var n=typeof Symbol=="function"&&Symbol.toStringTag,s=n&&e[Symbol.toStringTag]||e.constructor.name||"Object";return s}}function sr(e){try{return _e(e),!1}catch{return!0}}function _e(e){return""+e}function Se(e){if(sr(e))return E("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.",ir(e)),_e(e)}var Re=T.ReactCurrentOwner,ar={key:!0,ref:!0,__self:!0,__source:!0},Pe,Fe;function lr(e){if(q.call(e,"ref")){var n=Object.getOwnPropertyDescriptor(e,"ref").get;if(n&&n.isReactWarning)return!1}return e.ref!==void 0}function cr(e){if(q.call(e,"key")){var n=Object.getOwnPropertyDescriptor(e,"key").get;if(n&&n.isReactWarning)return!1}return e.key!==void 0}function ur(e,n){typeof e.ref=="string"&&Re.current}function dr(e,n){{var s=function(){Pe||(Pe=!0,E("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",n))};s.isReactWarning=!0,Object.defineProperty(e,"key",{get:s,configurable:!0})}}function fr(e,n){{var s=function(){Fe||(Fe=!0,E("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)",n))};s.isReactWarning=!0,Object.defineProperty(e,"ref",{get:s,configurable:!0})}}var pr=function(e,n,s,f,b,w,g){var m={$$typeof:t,type:e,key:n,ref:s,props:g,_owner:w};return m._store={},Object.defineProperty(m._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(m,"_self",{configurable:!1,enumerable:!1,writable:!1,value:f}),Object.defineProperty(m,"_source",{configurable:!1,enumerable:!1,writable:!1,value:b}),Object.freeze&&(Object.freeze(m.props),Object.freeze(m)),m};function hr(e,n,s,f,b){{var w,g={},m=null,F=null;s!==void 0&&(Se(s),m=""+s),cr(n)&&(Se(n.key),m=""+n.key),lr(n)&&(F=n.ref,ur(n,b));for(w in n)q.call(n,w)&&!ar.hasOwnProperty(w)&&(g[w]=n[w]);if(e&&e.defaultProps){var _=e.defaultProps;for(w in _)g[w]===void 0&&(g[w]=_[w])}if(m||F){var S=typeof e=="function"?e.displayName||e.name||"Unknown":e;m&&dr(g,S),F&&fr(g,S)}return pr(e,m,F,b,f,Re.current,g)}}var ue=T.ReactCurrentOwner,Me=T.ReactDebugCurrentFrame;function U(e){if(e){var n=e._owner,s=Z(e.type,e._source,n?n.type:null);Me.setExtraStackFrame(s)}else Me.setExtraStackFrame(null)}var de;de=!1;function fe(e){return typeof e=="object"&&e!==null&&e.$$typeof===t}function Oe(){{if(ue.current){var e=M(ue.current.type);if(e)return`
Check the render method of \``+e+"`."}return""}}function mr(e){return""}var Ie={};function gr(e){{var n=Oe();if(!n){var s=typeof e=="string"?e:e.displayName||e.name;s&&(n=`
Check the top-level render call using <`+s+">.")}return n}}function Ae(e,n){{if(!e._store||e._store.validated||e.key!=null)return;e._store.validated=!0;var s=gr(n);if(Ie[s])return;Ie[s]=!0;var f="";e&&e._owner&&e._owner!==ue.current&&(f=" It was passed a child from "+M(e._owner.type)+"."),U(e),E('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.',s,f),U(null)}}function De(e,n){{if(typeof e!="object")return;if(ce(e))for(var s=0;s<e.length;s++){var f=e[s];fe(f)&&Ae(f,n)}else if(fe(e))e._store&&(e._store.validated=!0);else if(e){var b=P(e);if(typeof b=="function"&&b!==e.entries)for(var w=b.call(e),g;!(g=w.next()).done;)fe(g.value)&&Ae(g.value,n)}}}function vr(e){{var n=e.type;if(n==null||typeof n=="string")return;var s;if(typeof n=="function")s=n.propTypes;else if(typeof n=="object"&&(n.$$typeof===a||n.$$typeof===c))s=n.propTypes;else return;if(s){var f=M(n);nr(s,e.props,"prop",f,e)}else if(n.PropTypes!==void 0&&!de){de=!0;var b=M(n);E("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?",b||"Unknown")}typeof n.getDefaultProps=="function"&&!n.getDefaultProps.isReactClassApproved&&E("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.")}}function yr(e){{for(var n=Object.keys(e.props),s=0;s<n.length;s++){var f=n[s];if(f!=="children"&&f!=="key"){U(e),E("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.",f),U(null);break}}e.ref!==null&&(U(e),E("Invalid attribute `ref` supplied to `React.Fragment`."),U(null))}}var $e={};function Le(e,n,s,f,b,w){{var g=oe(e);if(!g){var m="";(e===void 0||typeof e=="object"&&e!==null&&Object.keys(e).length===0)&&(m+=" 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 F=mr();F?m+=F:m+=Oe();var _;e===null?_="null":ce(e)?_="array":e!==void 0&&e.$$typeof===t?(_="<"+(M(e.type)||"Unknown")+" />",m=" Did you accidentally export a JSX literal instead of a component?"):_=typeof e,E("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",_,m)}var S=hr(e,n,s,b,w);if(S==null)return S;if(g){var D=n.children;if(D!==void 0)if(f)if(ce(D)){for(var V=0;V<D.length;V++)De(D[V],e);Object.freeze&&Object.freeze(D)}else E("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else De(D,e)}if(q.call(n,"key")){var z=M(e),O=Object.keys(n).filter(function(Tr){return Tr!=="key"}),pe=O.length>0?"{key: someKey, "+O.join(": ..., ")+": ...}":"{key: someKey}";if(!$e[z+pe]){var wr=O.length>0?"{"+O.join(": ..., ")+": ...}":"{}";E(`A props object containing a "key" prop is being spread into JSX:
let props = %s;
<%s {...props} />
React keys must be passed directly to JSX without using spread:
let props = %s;
<%s key={someKey} {...props} />`,pe,z,wr,z),$e[z+pe]=!0}}return e===l?yr(S):vr(S),S}}function xr(e,n,s){return Le(e,n,s,!0)}function br(e,n,s){return Le(e,n,s,!1)}var jr=br,Cr=xr;J.Fragment=l,J.jsx=jr,J.jsxs=Cr}()),J}process.env.NODE_ENV==="production"?he.exports=_r():he.exports=Sr();var r=he.exports,Rr={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};const Pr=i=>i.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Fr=(i,t)=>{const o=j.forwardRef(({color:l="currentColor",size:d=24,strokeWidth:h=2,absoluteStrokeWidth:C,children:v,...a},y)=>j.createElement("svg",{ref:y,...Rr,width:d,height:d,stroke:l,strokeWidth:C?Number(h)*24/Number(d):h,className:`lucide lucide-${Pr(i)}`,...a},[...t.map(([x,c])=>j.createElement(x,c)),...(Array.isArray(v)?v:[v])||[]]));return o.displayName=`${i}`,o};var A=Fr;const Mr=A("AlertCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]),Or=A("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]),We=A("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]),Ir=A("Eye",[["path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z",key:"rwhkz3"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),Ar=A("FileText",[["path",{d:"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z",key:"1nnpy2"}],["polyline",{points:"14 2 14 8 20 8",key:"1ew0cm"}],["line",{x1:"16",x2:"8",y1:"13",y2:"13",key:"14keom"}],["line",{x1:"16",x2:"8",y1:"17",y2:"17",key:"17nazh"}],["line",{x1:"10",x2:"8",y1:"9",y2:"9",key:"1a5vjj"}]]),Dr=A("Filter",[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]]),$r=A("Loader2",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),Lr=A("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]),Nr=A("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]),zr=A("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]),Wr=A("Shield",[["path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z",key:"3xmgem"}]]),Ur=A("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Vr=A("Zap",[["polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2",key:"45s27k"}]]),Yr="https://openrouter.ai/api/v1/models",Br="https://openrouter.ai/api/v1/chat/completions";class Ve{constructor(t){K(this,"endpoint");K(this,"cache",null);K(this,"cacheTimestamp",0);K(this,"CACHE_DURATION",5*60*1e3);this.endpoint=t||Yr}async fetchModels(t=!1){if(!t&&this.cache&&Date.now()-this.cacheTimestamp<this.CACHE_DURATION)return this.cache;try{const o={"Content-Type":"application/json"},l=await fetch(this.endpoint,{headers:o});if(!l.ok)throw new Error(`HTTP error! status: ${l.status}`);const d=await l.json(),h=d.data.length,C=this.filterAvailableModels(d.data),v=h-C.length;console.log(`📊 Model filtering stats: ${h} total → ${C.length} available (${v} filtered out)`);const a=C.map(y=>this.transformModel(y));return this.cache=a,this.cacheTimestamp=Date.now(),a}catch(o){return console.error("Failed to fetch models from OpenRouter:",o),this.cache?this.cache:this.getFallbackModels()}}async testModel(t,o,l="Hello! Please respond with a brief greeting."){var d,h,C,v;if(!o)return{success:!1,error:"API key is required for testing models"};try{const a=await fetch(Br,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({model:t,messages:[{role:"user",content:l}],max_tokens:100,temperature:.7})});if(!a.ok){const x=await a.json().catch(()=>({}));return{success:!1,error:`HTTP ${a.status}: ${((d=x.error)==null?void 0:d.message)||a.statusText}`}}const y=await a.json();return{success:!0,response:((v=(C=(h=y.choices)==null?void 0:h[0])==null?void 0:C.message)==null?void 0:v.content)||"No response content",usage:y.usage}}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error occurred"}}}filterAvailableModels(t){return t.filter(o=>{if(!o.context_length||o.context_length<=0)return console.debug(`Filtered out model ${o.id}: invalid context length (${o.context_length})`),!1;if(this.isModelDeprecated(o))return console.debug(`Filtered out model ${o.id}: deprecated`),!1;if(o.per_request_limits){const d=parseInt(o.per_request_limits.prompt_tokens||"0"),h=parseInt(o.per_request_limits.completion_tokens||"0");if(d<=0&&h<=0)return console.debug(`Filtered out model ${o.id}: zero capacity limits`),!1}return!o.pricing||!o.pricing.prompt&&!o.pricing.completion?(console.debug(`Filtered out model ${o.id}: invalid pricing`),!1):!o.id||o.id.trim()===""?(console.debug("Filtered out model: empty or invalid ID"),!1):this.isKnownProblematicModel(o.id)?(console.debug(`Filtered out model ${o.id}: known problematic model`),!1):!0})}isModelDeprecated(t){var l,d,h,C;if((d=(l=t.architecture)==null?void 0:l.instruct_type)!=null&&d.toLowerCase().includes("deprecated"))return!0;if(t.description){const v=t.description.toLowerCase();if(["deprecated","has been deprecated","please switch to","no longer supported","discontinued","replaced by"].some(y=>v.includes(y)))return!0}if([/.*-exp-\d{2}-\d{2}$/,/.*experimental.*$/i].some(v=>v.test(t.id))){const v=parseFloat(((h=t.pricing)==null?void 0:h.prompt)||"0"),a=parseFloat(((C=t.pricing)==null?void 0:C.completion)||"0");if(v===0&&a===0)return!0}return!1}isKnownProblematicModel(t){return["google/gemini-2.5-pro-exp-03-25"].includes(t)}categorizeModels(t){const o=[],l=[];return t.forEach(d=>{d.costTier==="free"?o.push(d):l.push(d)}),{freeModels:o,paidModels:l}}transformModel(t){const o=this.extractProvider(t.id),l=this.calculateCostTier(t.pricing),d=this.extractFeatures(t);return{id:t.id,name:t.name,provider:o,costTier:l,description:t.description||"No description available",features:d,pricing:{input:parseFloat(t.pricing.prompt)||0,output:parseFloat(t.pricing.completion)||0,currency:"USD"},context:t.context_length,multimodal:this.isMultimodal(t)}}extractProvider(t){const o=t.split("/");if(o.length>1){const l=o[0];return l.charAt(0).toUpperCase()+l.slice(1)}return"Unknown"}calculateCostTier(t){const o=parseFloat(t.prompt)||0,l=parseFloat(t.completion)||0;if(o===0&&l===0)return"free";const d=(o+l)/2;return d<1e-6?"low":d<1e-5?"medium":"high"}extractFeatures(t){var h;const o=[];((h=t.architecture.input_modalities)!=null&&h.includes("image")||t.architecture.modality==="multimodal")&&o.push("Vision"),t.top_provider.is_moderated&&o.push("Moderated"),t.context_length>1e5&&o.push("Long Context"),t.architecture.instruct_type&&o.push("Instruct");const l=parseFloat(t.pricing.prompt)||0,d=parseFloat(t.pricing.completion)||0;return l===0&&d===0&&o.push("Free"),o}isMultimodal(t){var o;return((o=t.architecture.input_modalities)==null?void 0:o.includes("image"))||t.architecture.modality==="multimodal"||!1}getFallbackModels(){return[{id:"openai/gpt-4o-mini",name:"GPT-4o Mini",provider:"OpenAI",costTier:"low",description:"Fast and affordable multimodal model",features:["Vision","Fast"],pricing:{input:15e-5,output:6e-4,currency:"USD"},context:128e3,multimodal:!0},{id:"openai/gpt-4o",name:"GPT-4o",provider:"OpenAI",costTier:"high",description:"Most capable multimodal model",features:["Vision","Advanced"],pricing:{input:.005,output:.015,currency:"USD"},context:128e3,multimodal:!0},{id:"anthropic/claude-3-sonnet",name:"Claude 3 Sonnet",provider:"Anthropic",costTier:"medium",description:"Balanced performance and cost",features:["Long Context"],pricing:{input:.003,output:.015,currency:"USD"},context:2e5,multimodal:!1},{id:"meta-llama/llama-3.2-3b-instruct:free",name:"Llama 3.2 3B Instruct (Free)",provider:"Meta",costTier:"free",description:"Free tier access to Llama 3.2 3B",features:["Free","Instruct"],pricing:{input:0,output:0,currency:"USD"},context:131072,multimodal:!1}]}clearCache(){this.cache=null,this.cacheTimestamp=0}}function Ye(i,t){const[o,l]=j.useState([]),[d,h]=j.useState([]),[C,v]=j.useState([]),[a,y]=j.useState(!0),[x,c]=j.useState(null),[u]=j.useState(()=>new Ve(i)),p=j.useCallback(async(P=!1)=>{try{y(!0),c(null);let T;try{T=await u.fetchModels(P)}catch(N){if(t&&t.length>0)T=t;else throw N}l(T);const{freeModels:E,paidModels:L}=u.categorizeModels(T);h(E),v(L)}catch(T){const E=T instanceof Error?T.message:"Failed to fetch models";if(c(E),t&&t.length>0){l(t);const{freeModels:L,paidModels:N}=u.categorizeModels(t);h(L),v(N)}}finally{y(!1)}},[u,t]),k=j.useCallback(async()=>{await p(!0)},[p]),R=j.useCallback(async(P,T,E)=>await u.testModel(P,T,E),[u]);return j.useEffect(()=>{p()},[p]),{models:o,freeModels:d,paidModels:C,loading:a,error:x,refresh:k,testModel:R}}const Ue={searchTerm:"",selectedProviders:[],selectedCostTiers:[],showMultimodal:!1,hideExperimental:!1};function Be(i){const[t,o]=j.useState(Ue),[l,d]=j.useState({key:null,direction:"asc"}),h=j.useMemo(()=>[...new Set(i.map(p=>p.provider))].sort(),[i]),C=j.useCallback((u,p)=>{o(k=>({...k,[u]:p}))},[]),v=j.useCallback(()=>{o(Ue)},[]),a=j.useCallback((u,p="asc")=>{d(k=>k.key===u?{key:u,direction:k.direction==="asc"?"desc":"asc"}:{key:u,direction:p})},[]),y=j.useCallback(u=>[/.*-exp-\d{2}-\d{2}$/i,/.*experimental.*$/i,/.*-preview.*$/i,/.*-beta.*$/i,/.*-alpha.*$/i,/.*-test.*$/i].some(k=>k.test(u.id))||u.name.toLowerCase().includes("experimental")||u.name.toLowerCase().includes("preview")||u.name.toLowerCase().includes("beta")||u.description.toLowerCase().includes("experimental"),[]),x=j.useMemo(()=>{let u=[...i];if(t.searchTerm){const p=t.searchTerm.toLowerCase();u=u.filter(k=>{var R;return k.name.toLowerCase().includes(p)||k.provider.toLowerCase().includes(p)||k.description.toLowerCase().includes(p)||k.id.toLowerCase().includes(p)||((R=k.features)==null?void 0:R.some(P=>P.toLowerCase().includes(p)))})}return t.selectedProviders.length>0&&(u=u.filter(p=>t.selectedProviders.includes(p.provider))),t.selectedCostTiers.length>0&&(u=u.filter(p=>t.selectedCostTiers.includes(p.costTier))),t.showMultimodal&&(u=u.filter(p=>p.multimodal)),t.hideExperimental&&(u=u.filter(p=>!y(p))),l.key&&u.sort((p,k)=>{const R=p[l.key],P=k[l.key];if(R===void 0&&P===void 0)return 0;if(R===void 0)return 1;if(P===void 0)return-1;let T=0;return typeof R=="string"&&typeof P=="string"?T=R.localeCompare(P):typeof R=="number"&&typeof P=="number"?T=R-P:T=String(R).localeCompare(String(P)),l.direction==="desc"?-T:T}),u},[i,t,l,y]),c=j.useMemo(()=>({total:i.length,filtered:x.length}),[i.length,x.length]);return{filteredModels:x,filterState:t,sortConfig:l,updateFilter:C,clearFilters:v,setSort:a,availableProviders:h,filterStats:c}}function me(i){if(i===0)return"Free";const t=i*1e3;return t<.01?`$${t.toFixed(4)}/1K`:`$${t.toFixed(2)}/1K`}function qe(i){return i?i>=1e6?`${(i/1e6).toFixed(1)}M`:i>=1e3?`${(i/1e3).toFixed(0)}K`:i.toString():"Unknown"}function qr(i){switch(i){case"free":return"#10b981";case"low":return"#3b82f6";case"medium":return"#f59e0b";case"high":return"#ef4444";default:return"#6b7280"}}function Ke(i){switch(i){case"free":return"Free";case"low":return"Low Cost";case"medium":return"Medium Cost";case"high":return"High Cost";default:return"Unknown"}}function He(i,t){return i.length<=t?i:i.slice(0,t-3)+"..."}function Kr(i,t){let o;return(...l)=>{clearTimeout(o),o=setTimeout(()=>i(...l),t)}}const Hr=["free","low","medium","high"];function Je({filterState:i,onFilterChange:t,onClearFilters:o,availableProviders:l,filterStats:d}){const h=j.useRef(),C=j.useCallback(c=>{h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{t("searchTerm",c)},300)},[t]),v=c=>{C(c.target.value)},a=c=>{const u=i.selectedProviders.includes(c)?i.selectedProviders.filter(p=>p!==c):[...i.selectedProviders,c];t("selectedProviders",u)},y=c=>{const u=i.selectedCostTiers.includes(c)?i.selectedCostTiers.filter(p=>p!==c):[...i.selectedCostTiers,c];t("selectedCostTiers",u)},x=i.searchTerm||i.selectedProviders.length>0||i.selectedCostTiers.length>0||i.showMultimodal||i.hideExperimental;return r.jsxs("div",{className:"filter-bar",children:[r.jsxs("div",{style:{position:"relative",marginBottom:"0.75rem"},children:[r.jsx(zr,{style:{position:"absolute",left:"0.75rem",top:"50%",transform:"translateY(-50%)",color:"var(--or-text-secondary)",width:"1rem",height:"1rem"}}),r.jsx("input",{type:"text",placeholder:"Search models, providers, or features...",className:"search-input",style:{paddingLeft:"2.5rem"},onChange:v,defaultValue:i.searchTerm})]}),r.jsxs("div",{className:"filter-row",style:{flexDirection:"column",gap:"0.5rem",alignItems:"flex-start"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem",justifyContent:"space-between",width:"100%"},children:[r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[r.jsx(Dr,{style:{width:"1rem",height:"1rem",color:"var(--or-text-secondary)"}}),r.jsx("span",{style:{fontSize:"0.875rem",fontWeight:"500",color:"var(--or-text)"},children:"Filters:"})]}),x&&r.jsxs("button",{onClick:o,className:"clear-filters-button",style:{display:"flex",alignItems:"center",gap:"0.25rem"},children:[r.jsx(Nr,{style:{width:"0.75rem",height:"0.75rem"}}),"Clear all"]})]}),r.jsxs("div",{style:{width:"100%"},children:[r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.5rem",alignItems:"center",marginBottom:"0.25rem"},children:r.jsx("span",{style:{fontSize:"0.75rem",color:"var(--or-text-secondary)",textTransform:"uppercase",fontWeight:"500",minWidth:"fit-content"},children:"Provider:"})}),r.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.375rem",maxHeight:"50px",overflowY:"auto",padding:"0.375rem",border:"1px solid var(--or-border)",borderRadius:"0.25rem",backgroundColor:"rgba(0, 0, 0, 0.01)"},children:l.map(c=>r.jsx("button",{onClick:()=>a(c),className:`filter-button ${i.selectedProviders.includes(c)?"active":""}`,style:{fontSize:"0.7rem",padding:"0.25rem 0.5rem"},children:c},c))})]}),r.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.375rem",alignItems:"center"},children:[r.jsx("span",{style:{fontSize:"0.75rem",color:"var(--or-text-secondary)",textTransform:"uppercase",fontWeight:"500"},children:"Cost:"}),Hr.map(c=>r.jsx("button",{onClick:()=>y(c),className:`filter-button ${i.selectedCostTiers.includes(c)?"active":""}`,style:{fontSize:"0.7rem",padding:"0.25rem 0.5rem"},children:Ke(c)},c))]}),r.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.75rem",alignItems:"center"},children:[r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.375rem",cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:i.showMultimodal,onChange:c=>t("showMultimodal",c.target.checked),style:{width:"0.875rem",height:"0.875rem"}}),r.jsx("span",{style:{fontSize:"0.8rem",color:"var(--or-text)"},children:"Multimodal only"})]}),r.jsxs("label",{style:{display:"flex",alignItems:"center",gap:"0.375rem",cursor:"pointer"},children:[r.jsx("input",{type:"checkbox",checked:i.hideExperimental,onChange:c=>t("hideExperimental",c.target.checked),style:{width:"0.875rem",height:"0.875rem"}}),r.jsx("span",{style:{fontSize:"0.8rem",color:"var(--or-text)"},children:"Hide experimental"})]})]})]}),r.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",fontSize:"0.8rem",color:"var(--or-text-secondary)",marginTop:"0.5rem",paddingTop:"0.5rem",borderTop:"1px solid var(--or-border)"},children:[r.jsxs("span",{className:"results-count",children:["Showing ",d.filtered," of ",d.total," models"]}),d.filtered<d.total&&r.jsxs("span",{style:{color:"var(--or-primary-color)",marginLeft:"1rem"},children:[d.total-d.filtered," hidden by filters"]})]})]})}function ee({models:i,selectedModel:t,onModelSelect:o,sortConfig:l,onSort:d}){const h=a=>l.key!==a?r.jsx(We,{style:{width:"1rem",height:"1rem",color:"var(--or-text-secondary)"}}):l.direction==="asc"?r.jsx(We,{style:{width:"1rem",height:"1rem",color:"var(--or-primary-color)"}}):r.jsx(Or,{style:{width:"1rem",height:"1rem",color:"var(--or-primary-color)"}}),C=a=>{const y={width:"0.75rem",height:"0.75rem"};switch(a.toLowerCase()){case"vision":return r.jsx(Ir,{style:y});case"fast":return r.jsx(Vr,{style:y});case"moderated":return r.jsx(Wr,{style:y});case"long context":return r.jsx(Ar,{style:y});default:return null}},v=a=>{if(!a||a.length===0)return null;const y=a.slice(0,3),x=a.length-3;return r.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"0.25rem"},children:[y.map((c,u)=>r.jsxs("span",{className:"feature-tag",children:[C(c),c]},u)),x>0&&r.jsxs("span",{style:{padding:"0.25rem 0.5rem",fontSize:"0.75rem",color:"var(--or-text-secondary)",borderRadius:"0.375rem"},children:["+",x," more"]})]})};return r.jsxs("div",{className:"table-container",children:[r.jsxs("table",{className:"model-table",children:[r.jsx("thead",{children:r.jsxs("tr",{children:[r.jsx("th",{children:r.jsxs("button",{onClick:()=>d("name"),style:{display:"flex",alignItems:"center",gap:"0.5rem",background:"none",border:"none",cursor:"pointer",fontSize:"0.875rem",fontWeight:"500",color:"var(--or-text)"},children:["Model",h("name")]})}),r.jsx("th",{children:r.jsxs("button",{onClick:()=>d("provider"),style:{display:"flex",alignItems:"center",gap:"0.5rem",background:"none",border:"none",cursor:"pointer",fontSize:"0.875rem",fontWeight:"500",color:"var(--or-text)"},children:["Provider",h("provider")]})}),r.jsx("th",{children:r.jsxs("button",{onClick:()=>d("costTier"),style:{display:"flex",alignItems:"center",gap:"0.5rem",background:"none",border:"none",cursor:"pointer",fontSize:"0.875rem",fontWeight:"500",color:"var(--or-text)"},children:["Cost",h("costTier")]})}),r.jsx("th",{children:r.jsxs("button",{onClick:()=>d("context"),style:{display:"flex",alignItems:"center",gap:"0.5rem",background:"none",border:"none",cursor:"pointer",fontSize:"0.875rem",fontWeight:"500",color:"var(--or-text)"},children:["Context",h("context")]})}),r.jsx("th",{children:r.jsx("span",{style:{fontSize:"0.875rem",fontWeight:"500",color:"var(--or-text)"},children:"Features"})}),r.jsx("th",{children:r.jsx("span",{style:{fontSize:"0.875rem",fontWeight:"500",color:"var(--or-text)"},children:"Description"})})]})}),r.jsx("tbody",{children:i.map(a=>r.jsxs("tr",{onClick:()=>o(a.id),className:t===a.id?"selected":"",children:[r.jsx("td",{children:r.jsxs("div",{style:{display:"flex",flexDirection:"column"},children:[r.jsx("span",{style:{fontWeight:"500",color:"var(--or-text)"},children:a.name}),r.jsx("span",{style:{fontSize:"0.75rem",color:"var(--or-text-secondary)"},children:a.id})]})}),r.jsx("td",{children:r.jsx("span",{style:{fontSize:"0.875rem",color:"var(--or-text)"},children:a.provider})}),r.jsx("td",{children:r.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"0.25rem"},children:[r.jsx("span",{className:`cost-tier-${a.costTier}`,style:{display:"inline-flex",alignItems:"center",padding:"0.25rem 0.5rem",fontSize:"0.75rem",fontWeight:"500",borderRadius:"0.375rem",color:"white",width:"fit-content"},children:a.costTier.charAt(0).toUpperCase()+a.costTier.slice(1)}),a.pricing&&r.jsxs("div",{style:{fontSize:"0.75rem",color:"var(--or-text-secondary)"},children:["In: ",me(a.pricing.input)," | Out: ",me(a.pricing.output)]})]})}),r.jsx("td",{children:r.jsx("span",{style:{fontSize:"0.875rem",color:"var(--or-text)"},children:qe(a.context)})}),r.jsx("td",{children:v(a.features)}),r.jsx("td",{children:r.jsx("p",{style:{fontSize:"0.875rem",color:"var(--or-text-secondary)",maxWidth:"20rem",margin:0},children:He(a.description,100)})})]},a.id))})]}),i.length===0&&r.jsxs("div",{className:"empty-container",children:[r.jsx("div",{style:{fontSize:"1.125rem",fontWeight:"500",marginBottom:"0.5rem",color:"var(--or-text)"},children:"No models found"}),r.jsx("p",{style:{fontSize:"0.875rem",textAlign:"center",maxWidth:"24rem",margin:0},children:"Try adjusting your search terms or clearing some filters to see more results."})]})]})}function Ge({message:i="Loading models..."}){return r.jsxs("div",{className:"loading-container",children:[r.jsx($r,{className:"loading-spinner spinner",style:{width:"2rem",height:"2rem"}}),r.jsx("p",{style:{color:"var(--or-text-secondary)",textAlign:"center"},children:i})]})}function Xe({error:i,onRetry:t}){return r.jsxs("div",{className:"error-container",children:[r.jsx(Mr,{style:{width:"2rem",height:"2rem",color:"#ef4444",marginBottom:"1rem"}}),r.jsx("h3",{style:{fontSize:"1.125rem",fontWeight:"500",color:"var(--or-text)",marginBottom:"0.5rem"},children:"Failed to load models"}),r.jsx("p",{className:"error-message",style:{textAlign:"center",maxWidth:"24rem"},children:i}),t&&r.jsxs("button",{onClick:t,className:"retry-button",style:{display:"flex",alignItems:"center",gap:"0.5rem"},children:[r.jsx(Lr,{style:{width:"1rem",height:"1rem"}}),"Try Again"]})]})}function Jr({onClearFilters:i}){return r.jsxs("div",{className:"empty-container",children:[r.jsx("div",{style:{fontSize:"3.75rem",marginBottom:"1rem"},children:"🔍"}),r.jsx("h3",{style:{fontSize:"1.125rem",fontWeight:"500",color:"var(--or-text)",marginBottom:"0.5rem"},children:"No models match your criteria"}),r.jsx("p",{style:{color:"var(--or-text-secondary)",textAlign:"center",maxWidth:"24rem",marginBottom:"1rem"},children:"Try adjusting your search terms or clearing some filters to see more results."}),i&&r.jsx("button",{onClick:i,style:{padding:"0.5rem 1rem",backgroundColor:"rgba(0, 0, 0, 0.05)",color:"var(--or-text)",border:"none",borderRadius:"0.5rem",cursor:"pointer",fontSize:"0.875rem"},children:"Clear all filters"})]})}function Gr({isOpen:i,onClose:t,selectedModel:o,onModelChange:l,apiEndpoint:d,fallbackModels:h,theme:C="light",maxHeight:v="80vh",maxWidth:a,className:y,categorizeByType:x=!1}){const{models:c,freeModels:u,paidModels:p,loading:k,error:R,refresh:P}=Ye(d,h),{filteredModels:T,filterState:E,sortConfig:L,updateFilter:N,clearFilters:re,setSort:Y,availableProviders:te,filterStats:ne}=Be(c);j.useEffect(()=>{const I=M=>{M.key==="Escape"&&t()};return i&&(document.addEventListener("keydown",I),document.body.style.overflow="hidden"),()=>{document.removeEventListener("keydown",I),document.body.style.overflow=""}},[i,t]);const W=j.useCallback(I=>{l(I)},[l]),oe=j.useCallback(()=>{o&&t()},[o,t]);if(!i)return null;const ie=()=>{if(!x)return r.jsx(ee,{models:T,selectedModel:o,onModelSelect:W,sortConfig:L,onSort:Y});const I=T.filter($=>$.costTier==="free"),M=T.filter($=>$.costTier!=="free");return r.jsxs("div",{className:"categorized-models",children:[I.length>0&&r.jsxs("div",{className:"model-category",children:[r.jsxs("h3",{style:{fontSize:"1rem",fontWeight:"600",margin:"0.75rem 0 0.5rem",color:"#10b981",display:"flex",alignItems:"center",gap:"0.5rem"},children:["Free Models (",I.length,")"]}),r.jsx(ee,{models:I,selectedModel:o,onModelSelect:W,sortConfig:L,onSort:Y})]}),M.length>0&&r.jsxs("div",{className:"model-category",children:[r.jsxs("h3",{style:{fontSize:"1rem",fontWeight:"600",margin:"1rem 0 0.5rem",color:"var(--or-text)",display:"flex",alignItems:"center",gap:"0.5rem"},children:["Paid Models (",M.length,")"]}),r.jsx(ee,{models:M,selectedModel:o,onModelSelect:W,sortConfig:L,onSort:Y})]})]})};return r.jsx("div",{className:`openrouter-modal ${C==="dark"?"dark":""} ${y||""}`,children:r.jsx("div",{className:"modal-overlay",onClick:t,children:r.jsxs("div",{className:"modal-content",onClick:I=>I.stopPropagation(),style:{maxHeight:v,...a&&{maxWidth:a,width:a}},children:[r.jsxs("div",{className:"modal-header",children:[r.jsxs("h2",{className:"modal-title",children:["Choose OpenRouter LLM Model",!k&&!R&&c.length>0&&r.jsxs("span",{style:{fontWeight:"400",fontSize:"0.875rem",color:"var(--or-text-secondary)",marginLeft:"0.5rem"},children:["(",c.length," models",u.length>0&&`: ${u.length} free, ${p.length} paid`,")"]})]}),r.jsx("button",{onClick:t,className:"modal-close-button",children:r.jsx(Ur,{style:{width:"1.25rem",height:"1.25rem"}})})]}),r.jsx("div",{className:"modal-body",children:k?r.jsx(Ge,{message:"Loading available models..."}):R?r.jsx(Xe,{error:R,onRetry:P}):r.jsxs(r.Fragment,{children:[r.jsx(Je,{filterState:E,onFilterChange:N,onClearFilters:re,availableProviders:te,filterStats:ne}),ie()]})}),r.jsxs("div",{style:{padding:"1rem 1.5rem",borderTop:"1px solid var(--or-border)",backgroundColor:"rgba(0, 0, 0, 0.02)",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[r.jsx("div",{children:o&&r.jsxs("div",{style:{fontSize:"0.875rem",color:"var(--or-text-secondary)"},children:["Selected: ",r.jsx("span",{style:{fontWeight:"500",color:"var(--or-text)",fontFamily:"monospace",fontSize:"0.8rem"},children:o})]})}),r.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[r.jsx("button",{onClick:t,style:{padding:"0.5rem 1rem",color:"var(--or-text)",backgroundColor:"var(--or-background)",border:"1px solid var(--or-border)",borderRadius:"0.5rem",cursor:"pointer",fontSize:"0.875rem"},children:"Cancel"}),r.jsx("button",{onClick:oe,disabled:!o,style:{padding:"0.5rem 1.5rem",borderRadius:"0.5rem",fontWeight:"500",fontSize:"0.875rem",border:"none",cursor:o?"pointer":"not-allowed",backgroundColor:o?"var(--or-primary-color)":"#d1d5db",color:o?"white":"#6b7280"},children:"Select Model"})]})]})]})})})}exports.ApiClient=Ve;exports.EmptyState=Jr;exports.ErrorState=Xe;exports.FilterBar=Je;exports.LoadingState=Ge;exports.ModelChooserModal=Gr;exports.ModelTable=ee;exports.debounce=Kr;exports.formatContextLength=qe;exports.formatPrice=me;exports.getCostTierColor=qr;exports.getCostTierLabel=Ke;exports.truncateText=He;exports.useFiltering=Be;exports.useModelData=Ye;