omniroute 2.8.6 → 2.8.7

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.
Files changed (94) hide show
  1. package/app/.next/BUILD_ID +1 -1
  2. package/app/.next/build-manifest.json +2 -2
  3. package/app/.next/prerender-manifest.json +3 -3
  4. package/app/.next/server/app/(dashboard)/dashboard/a2a/page_client-reference-manifest.js +1 -1
  5. package/app/.next/server/app/(dashboard)/dashboard/agents/page_client-reference-manifest.js +1 -1
  6. package/app/.next/server/app/(dashboard)/dashboard/analytics/page_client-reference-manifest.js +1 -1
  7. package/app/.next/server/app/(dashboard)/dashboard/api-manager/page_client-reference-manifest.js +1 -1
  8. package/app/.next/server/app/(dashboard)/dashboard/audit-log/page_client-reference-manifest.js +1 -1
  9. package/app/.next/server/app/(dashboard)/dashboard/auto-combo/page_client-reference-manifest.js +1 -1
  10. package/app/.next/server/app/(dashboard)/dashboard/cli-tools/page_client-reference-manifest.js +1 -1
  11. package/app/.next/server/app/(dashboard)/dashboard/combos/page_client-reference-manifest.js +1 -1
  12. package/app/.next/server/app/(dashboard)/dashboard/costs/page_client-reference-manifest.js +1 -1
  13. package/app/.next/server/app/(dashboard)/dashboard/endpoint/page_client-reference-manifest.js +1 -1
  14. package/app/.next/server/app/(dashboard)/dashboard/health/page_client-reference-manifest.js +1 -1
  15. package/app/.next/server/app/(dashboard)/dashboard/limits/page_client-reference-manifest.js +1 -1
  16. package/app/.next/server/app/(dashboard)/dashboard/logs/page_client-reference-manifest.js +1 -1
  17. package/app/.next/server/app/(dashboard)/dashboard/mcp/page_client-reference-manifest.js +1 -1
  18. package/app/.next/server/app/(dashboard)/dashboard/media/page_client-reference-manifest.js +1 -1
  19. package/app/.next/server/app/(dashboard)/dashboard/onboarding/page_client-reference-manifest.js +1 -1
  20. package/app/.next/server/app/(dashboard)/dashboard/page_client-reference-manifest.js +1 -1
  21. package/app/.next/server/app/(dashboard)/dashboard/playground/page_client-reference-manifest.js +1 -1
  22. package/app/.next/server/app/(dashboard)/dashboard/profile/page_client-reference-manifest.js +1 -1
  23. package/app/.next/server/app/(dashboard)/dashboard/providers/[id]/page_client-reference-manifest.js +1 -1
  24. package/app/.next/server/app/(dashboard)/dashboard/providers/new/page_client-reference-manifest.js +1 -1
  25. package/app/.next/server/app/(dashboard)/dashboard/providers/page_client-reference-manifest.js +1 -1
  26. package/app/.next/server/app/(dashboard)/dashboard/search-tools/page_client-reference-manifest.js +1 -1
  27. package/app/.next/server/app/(dashboard)/dashboard/settings/page_client-reference-manifest.js +1 -1
  28. package/app/.next/server/app/(dashboard)/dashboard/settings/pricing/page_client-reference-manifest.js +1 -1
  29. package/app/.next/server/app/(dashboard)/dashboard/translator/page_client-reference-manifest.js +1 -1
  30. package/app/.next/server/app/(dashboard)/dashboard/usage/page_client-reference-manifest.js +1 -1
  31. package/app/.next/server/app/400/page_client-reference-manifest.js +1 -1
  32. package/app/.next/server/app/401/page_client-reference-manifest.js +1 -1
  33. package/app/.next/server/app/403/page_client-reference-manifest.js +1 -1
  34. package/app/.next/server/app/408/page_client-reference-manifest.js +1 -1
  35. package/app/.next/server/app/429/page_client-reference-manifest.js +1 -1
  36. package/app/.next/server/app/500/page_client-reference-manifest.js +1 -1
  37. package/app/.next/server/app/502/page_client-reference-manifest.js +1 -1
  38. package/app/.next/server/app/503/page_client-reference-manifest.js +1 -1
  39. package/app/.next/server/app/_global-error.html +2 -2
  40. package/app/.next/server/app/_global-error.rsc +1 -1
  41. package/app/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  42. package/app/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  43. package/app/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  44. package/app/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  45. package/app/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  46. package/app/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  47. package/app/.next/server/app/api/v1/embeddings/route.js +7 -6
  48. package/app/.next/server/app/api/v1/embeddings/route.js.nft.json +1 -1
  49. package/app/.next/server/app/callback/page_client-reference-manifest.js +1 -1
  50. package/app/.next/server/app/docs/page_client-reference-manifest.js +1 -1
  51. package/app/.next/server/app/forbidden/page_client-reference-manifest.js +1 -1
  52. package/app/.next/server/app/forgot-password/page_client-reference-manifest.js +1 -1
  53. package/app/.next/server/app/landing/page_client-reference-manifest.js +1 -1
  54. package/app/.next/server/app/login/page_client-reference-manifest.js +1 -1
  55. package/app/.next/server/app/maintenance/page_client-reference-manifest.js +1 -1
  56. package/app/.next/server/app/offline/page_client-reference-manifest.js +1 -1
  57. package/app/.next/server/app/page_client-reference-manifest.js +1 -1
  58. package/app/.next/server/app/privacy/page_client-reference-manifest.js +1 -1
  59. package/app/.next/server/app/status/page_client-reference-manifest.js +1 -1
  60. package/app/.next/server/app/terms/page_client-reference-manifest.js +1 -1
  61. package/app/.next/server/chunks/[root-of-the-server]__007da72e._.js +3 -0
  62. package/app/.next/server/chunks/[root-of-the-server]__09c944b3._.js +1 -1
  63. package/app/.next/server/chunks/[root-of-the-server]__7d9b23e7._.js +1 -1
  64. package/app/.next/server/chunks/[root-of-the-server]__80e3bfc3._.js +1 -1
  65. package/app/.next/server/chunks/[root-of-the-server]__84e445b2._.js +2 -2
  66. package/app/.next/server/chunks/[root-of-the-server]__92cb0def._.js +1 -1
  67. package/app/.next/server/chunks/[root-of-the-server]__d4563e10._.js +1 -1
  68. package/app/.next/server/chunks/[root-of-the-server]__db2f9fe0._.js +1 -1
  69. package/app/.next/server/chunks/[root-of-the-server]__e27a89bd._.js +1 -1
  70. package/app/.next/server/chunks/_05c48915._.js +1 -1
  71. package/app/.next/server/chunks/_2115d8de._.js +1 -1
  72. package/app/.next/server/chunks/_3ac953eb._.js +1 -1
  73. package/app/.next/server/chunks/_4b8fd853._.js +1 -1
  74. package/app/.next/server/chunks/_5677b5e2._.js +1 -1
  75. package/app/.next/server/chunks/_68683848._.js +1 -1
  76. package/app/.next/server/chunks/_b39b1914._.js +3 -0
  77. package/app/.next/server/chunks/_ee9b677b._.js +1 -1
  78. package/app/.next/server/chunks/ssr/[root-of-the-server]__9affb65e._.js +1 -1
  79. package/app/.next/server/chunks/ssr/[root-of-the-server]__a6942102._.js +1 -1
  80. package/app/.next/server/pages/500.html +2 -2
  81. package/app/.next/server/server-reference-manifest.js +1 -1
  82. package/app/.next/server/server-reference-manifest.json +1 -1
  83. package/app/.next/static/chunks/{353ef826fbae436d.js → 53e0c73d409ce003.js} +1 -1
  84. package/app/CHANGELOG.md +18 -0
  85. package/app/docs/openapi.yaml +1 -1
  86. package/app/open-sse/services/rateLimitManager.ts +10 -5
  87. package/app/package-lock.json +2 -2
  88. package/app/package.json +1 -1
  89. package/app/src/app/api/v1/embeddings/route.ts +33 -3
  90. package/package.json +1 -1
  91. package/app/.next/server/chunks/[root-of-the-server]__6b56b04f._.js +0 -3
  92. /package/app/.next/static/{m9BrfW8GQTdaCjvX6OgP2 → zi0Yj1AW2_CKS-WmB5ZUc}/_buildManifest.js +0 -0
  93. /package/app/.next/static/{m9BrfW8GQTdaCjvX6OgP2 → zi0Yj1AW2_CKS-WmB5ZUc}/_clientMiddlewareManifest.json +0 -0
  94. /package/app/.next/static/{m9BrfW8GQTdaCjvX6OgP2 → zi0Yj1AW2_CKS-WmB5ZUc}/_ssgManifest.js +0 -0
@@ -1,3 +1,3 @@
1
- module.exports=[150447,(e,t,n)=>{"use strict";n.load=function(e,t,n={}){var r,i,s;for(r in t)s=t[r],n[r]=null!=(i=e[r])?i:s;return n},n.overwrite=function(e,t,n={}){var r,i;for(r in e)i=e[r],void 0!==t[r]&&(n[r]=i);return n}},818344,(e,t,n)=>{"use strict";t.exports=class{constructor(e,t){this.incr=e,this.decr=t,this._first=null,this._last=null,this.length=0}push(e){var t;this.length++,"function"==typeof this.incr&&this.incr(),t={value:e,prev:this._last,next:null},null!=this._last?(this._last.next=t,this._last=t):this._first=this._last=t}shift(){var e;return null==this._first?void 0:(this.length--,"function"==typeof this.decr&&this.decr(),e=this._first.value,null!=(this._first=this._first.next)?this._first.prev=null:this._last=null,e)}first(){if(null!=this._first)return this._first.value}getArray(){var e,t,n;for(e=this._first,n=[];null!=e;)n.push((t=e,e=e.next,t.value));return n}forEachShift(e){var t;for(t=this.shift();null!=t;)e(t),t=this.shift()}debug(){var e,t,n,r,i;for(e=this._first,i=[];null!=e;)i.push((t=e,e=e.next,{value:t.value,prev:null!=(n=t.prev)?n.value:void 0,next:null!=(r=t.next)?r.value:void 0}));return i}}},589243,(e,t,n)=>{"use strict";function r(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function i(e){return function(){var t=this,n=arguments;return new Promise(function(i,s){var o=e.apply(t,n);function a(e){r(o,i,s,a,l,"next",e)}function l(e){r(o,i,s,a,l,"throw",e)}a(void 0)})}}t.exports=class{constructor(e){if(this.instance=e,this._events={},null!=this.instance.on||null!=this.instance.once||null!=this.instance.removeAllListeners)throw Error("An Emitter already exists for this object");this.instance.on=(e,t)=>this._addListener(e,"many",t),this.instance.once=(e,t)=>this._addListener(e,"once",t),this.instance.removeAllListeners=(e=null)=>null!=e?delete this._events[e]:this._events={}}_addListener(e,t,n){var r;return null==(r=this._events)[e]&&(r[e]=[]),this._events[e].push({cb:n,status:t}),this.instance}listenerCount(e){return null!=this._events[e]?this._events[e].length:0}trigger(e,...t){var n=this;return i(function*(){var r,s;try{if("debug"!==e&&n.trigger("debug",`Event triggered: ${e}`,t),null==n._events[e])return;return n._events[e]=n._events[e].filter(function(e){return"none"!==e.status}),s=n._events[e].map(function(){var e=i(function*(e){var r,i;if("none"!==e.status){"once"===e.status&&(e.status="none");try{if(i="function"==typeof e.cb?e.cb(...t):void 0,"function"==typeof(null!=i?i.then:void 0))return yield i;return i}catch(e){return r=e,n.trigger("error",r),null}}});return function(t){return e.apply(this,arguments)}}()),(yield Promise.all(s)).find(function(e){return null!=e})}catch(e){return r=e,n.trigger("error",r),null}})()}}},247595,(e,t,n)=>{"use strict";var r,i;r=e.r(818344),i=e.r(589243),t.exports=class{constructor(e){var t;this.Events=new i(this),this._length=0,this._lists=(function(){var n,i,s;for(s=[],t=n=1,i=e;1<=i?n<=i:n>=i;t=1<=i?++n:--n)s.push(new r(()=>this.incr(),()=>this.decr()));return s}).call(this)}incr(){if(0==this._length++)return this.Events.trigger("leftzero")}decr(){if(0==--this._length)return this.Events.trigger("zero")}push(e){return this._lists[e.options.priority].push(e)}queued(e){return null!=e?this._lists[e].length:this._length}shiftAll(e){return this._lists.forEach(function(t){return t.forEachShift(e)})}getFirst(e=this._lists){var t,n,r;for(t=0,n=e.length;t<n;t++)if((r=e[t]).length>0)return r;return[]}shiftLastFrom(e){return this.getFirst(this._lists.slice(e).reverse()).shift()}}},938539,(e,t,n)=>{"use strict";t.exports=class extends Error{}},62367,(e,t,n)=>{"use strict";var r,i,s,o;function a(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function l(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function o(e){a(s,r,i,o,l,"next",e)}function l(e){a(s,r,i,o,l,"throw",e)}o(void 0)})}}s=10,i=5,o=e.r(150447),r=e.r(938539),t.exports=class{constructor(e,t,n,r,i,s,a,l){this.task=e,this.args=t,this.rejectOnDrop=i,this.Events=s,this._states=a,this.Promise=l,this.options=o.load(n,r),this.options.priority=this._sanitizePriority(this.options.priority),this.options.id===r.id&&(this.options.id=`${this.options.id}-${this._randomIndex()}`),this.promise=new this.Promise((e,t)=>{this._resolve=e,this._reject=t}),this.retryCount=0}_sanitizePriority(e){var t;return(t=~~e!==e?i:e)<0?0:t>s-1?s-1:t}_randomIndex(){return Math.random().toString(36).slice(2)}doDrop({error:e,message:t="This job has been dropped by Bottleneck"}={}){return!!this._states.remove(this.options.id)&&(this.rejectOnDrop&&this._reject(null!=e?e:new r(t)),this.Events.trigger("dropped",{args:this.args,options:this.options,task:this.task,promise:this.promise}),!0)}_assertStatus(e){var t;if((t=this._states.jobStatus(this.options.id))!==e&&("DONE"!==e||null!==t))throw new r(`Invalid job status ${t}, expected ${e}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`)}doReceive(){return this._states.start(this.options.id),this.Events.trigger("received",{args:this.args,options:this.options})}doQueue(e,t){return this._assertStatus("RECEIVED"),this._states.next(this.options.id),this.Events.trigger("queued",{args:this.args,options:this.options,reachedHWM:e,blocked:t})}doRun(){return 0===this.retryCount?(this._assertStatus("QUEUED"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),this.Events.trigger("scheduled",{args:this.args,options:this.options})}doExecute(e,t,n,r){var i=this;return l(function*(){var s,o,a;0===i.retryCount?(i._assertStatus("RUNNING"),i._states.next(i.options.id)):i._assertStatus("EXECUTING"),o={args:i.args,options:i.options,retryCount:i.retryCount},i.Events.trigger("executing",o);try{if(a=yield null!=e?e.schedule(i.options,i.task,...i.args):i.task(...i.args),t())return i.doDone(o),yield r(i.options,o),i._assertStatus("DONE"),i._resolve(a)}catch(e){return s=e,i._onFailure(s,o,t,n,r)}})()}doExpire(e,t,n){var i,s;return this._states.jobStatus("RUNNING"===this.options.id)&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),s={args:this.args,options:this.options,retryCount:this.retryCount},i=new r(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(i,s,e,t,n)}_onFailure(e,t,n,r,i){var s=this;return l(function*(){var o,a;if(n())return null!=(o=yield s.Events.trigger("failed",e,t))?(a=~~o,s.Events.trigger("retry",`Retrying ${s.options.id} after ${a} ms`,t),s.retryCount++,r(a)):(s.doDone(t),yield i(s.options,t),s._assertStatus("DONE"),s._reject(e))})()}doDone(e){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",e)}}},725648,(e,t,n)=>{"use strict";var r,i;function s(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function o(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){s(o,r,i,a,l,"next",e)}function l(e){s(o,r,i,a,l,"throw",e)}a(void 0)})}}i=e.r(150447),r=e.r(938539),t.exports=class{constructor(e,t,n){this.instance=e,this.storeOptions=t,this.clientId=this.instance._randomIndex(),i.load(n,n,this),this._nextRequest=this._lastReservoirRefresh=this._lastReservoirIncrease=Date.now(),this._running=0,this._done=0,this._unblockTime=0,this.ready=this.Promise.resolve(),this.clients={},this._startHeartbeat()}_startHeartbeat(){var e;return null==this.heartbeat&&(null!=this.storeOptions.reservoirRefreshInterval&&null!=this.storeOptions.reservoirRefreshAmount||null!=this.storeOptions.reservoirIncreaseInterval&&null!=this.storeOptions.reservoirIncreaseAmount)?"function"==typeof(e=this.heartbeat=setInterval(()=>{var e,t,n,r,i;if(r=Date.now(),null!=this.storeOptions.reservoirRefreshInterval&&r>=this._lastReservoirRefresh+this.storeOptions.reservoirRefreshInterval&&(this._lastReservoirRefresh=r,this.storeOptions.reservoir=this.storeOptions.reservoirRefreshAmount,this.instance._drainAll(this.computeCapacity())),null!=this.storeOptions.reservoirIncreaseInterval&&r>=this._lastReservoirIncrease+this.storeOptions.reservoirIncreaseInterval){var s=this.storeOptions;if(e=s.reservoirIncreaseAmount,n=s.reservoirIncreaseMaximum,i=s.reservoir,this._lastReservoirIncrease=r,(t=null!=n?Math.min(e,n-i):e)>0)return this.storeOptions.reservoir+=t,this.instance._drainAll(this.computeCapacity())}},this.heartbeatInterval)).unref?e.unref():void 0:clearInterval(this.heartbeat)}__publish__(e){var t=this;return o(function*(){return yield t.yieldLoop(),t.instance.Events.trigger("message",e.toString())})()}__disconnect__(e){var t=this;return o(function*(){return yield t.yieldLoop(),clearInterval(t.heartbeat),t.Promise.resolve()})()}yieldLoop(e=0){return new this.Promise(function(t,n){return setTimeout(t,e)})}computePenalty(){var e;return null!=(e=this.storeOptions.penalty)?e:15*this.storeOptions.minTime||5e3}__updateSettings__(e){var t=this;return o(function*(){return yield t.yieldLoop(),i.overwrite(e,e,t.storeOptions),t._startHeartbeat(),t.instance._drainAll(t.computeCapacity()),!0})()}__running__(){var e=this;return o(function*(){return yield e.yieldLoop(),e._running})()}__queued__(){var e=this;return o(function*(){return yield e.yieldLoop(),e.instance.queued()})()}__done__(){var e=this;return o(function*(){return yield e.yieldLoop(),e._done})()}__groupCheck__(e){var t=this;return o(function*(){return yield t.yieldLoop(),t._nextRequest+t.timeout<e})()}computeCapacity(){var e,t,n=this.storeOptions;return(e=n.maxConcurrent,t=n.reservoir,null!=e&&null!=t)?Math.min(e-this._running,t):null!=e?e-this._running:null!=t?t:null}conditionsCheck(e){var t;return null==(t=this.computeCapacity())||e<=t}__incrementReservoir__(e){var t=this;return o(function*(){var n;return yield t.yieldLoop(),n=t.storeOptions.reservoir+=e,t.instance._drainAll(t.computeCapacity()),n})()}__currentReservoir__(){var e=this;return o(function*(){return yield e.yieldLoop(),e.storeOptions.reservoir})()}isBlocked(e){return this._unblockTime>=e}check(e,t){return this.conditionsCheck(e)&&this._nextRequest-t<=0}__check__(e){var t=this;return o(function*(){var n;return yield t.yieldLoop(),n=Date.now(),t.check(e,n)})()}__register__(e,t,n){var r=this;return o(function*(){var e,n;return(yield r.yieldLoop(),e=Date.now(),r.conditionsCheck(t))?(r._running+=t,null!=r.storeOptions.reservoir&&(r.storeOptions.reservoir-=t),n=Math.max(r._nextRequest-e,0),r._nextRequest=e+n+r.storeOptions.minTime,{success:!0,wait:n,reservoir:r.storeOptions.reservoir}):{success:!1}})()}strategyIsBlock(){return 3===this.storeOptions.strategy}__submit__(e,t){var n=this;return o(function*(){var i,s,o;if(yield n.yieldLoop(),null!=n.storeOptions.maxConcurrent&&t>n.storeOptions.maxConcurrent)throw new r(`Impossible to add a job having a weight of ${t} to a limiter having a maxConcurrent setting of ${n.storeOptions.maxConcurrent}`);return s=Date.now(),o=null!=n.storeOptions.highWater&&e===n.storeOptions.highWater&&!n.check(t,s),(i=n.strategyIsBlock()&&(o||n.isBlocked(s)))&&(n._unblockTime=s+n.computePenalty(),n._nextRequest=n._unblockTime+n.storeOptions.minTime,n.instance._dropAllQueued()),{reachedHWM:o,blocked:i,strategy:n.storeOptions.strategy}})()}__free__(e,t){var n=this;return o(function*(){return yield n.yieldLoop(),n._running-=t,n._done+=t,n.instance._drainAll(n.computeCapacity()),{running:n._running}})()}}},592324,e=>{e.v(JSON.parse("{\"blacklist_client.lua\":\"local blacklist = ARGV[num_static_argv + 1]\\n\\nif redis.call('zscore', client_last_seen_key, blacklist) then\\n redis.call('zadd', client_last_seen_key, 0, blacklist)\\nend\\n\\n\\nreturn {}\\n\",\"check.lua\":\"local weight = tonumber(ARGV[num_static_argv + 1])\\n\\nlocal capacity = process_tick(now, false)['capacity']\\nlocal nextRequest = tonumber(redis.call('hget', settings_key, 'nextRequest'))\\n\\nreturn conditions_check(capacity, weight) and nextRequest - now <= 0\\n\",\"conditions_check.lua\":\"local conditions_check = function (capacity, weight)\\n return capacity == nil or weight <= capacity\\nend\\n\",\"current_reservoir.lua\":\"return process_tick(now, false)['reservoir']\\n\",\"done.lua\":\"process_tick(now, false)\\n\\nreturn tonumber(redis.call('hget', settings_key, 'done'))\\n\",\"free.lua\":\"local index = ARGV[num_static_argv + 1]\\n\\nredis.call('zadd', job_expirations_key, 0, index)\\n\\nreturn process_tick(now, false)['running']\\n\",\"get_time.lua\":\"redis.replicate_commands()\\n\\nlocal get_time = function ()\\n local time = redis.call('time')\\n\\n return tonumber(time[1]..string.sub(time[2], 1, 3))\\nend\\n\",\"group_check.lua\":\"return not (redis.call('exists', settings_key) == 1)\\n\",\"heartbeat.lua\":\"process_tick(now, true)\\n\",\"increment_reservoir.lua\":\"local incr = tonumber(ARGV[num_static_argv + 1])\\n\\nredis.call('hincrby', settings_key, 'reservoir', incr)\\n\\nlocal reservoir = process_tick(now, true)['reservoir']\\n\\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\\nrefresh_expiration(0, 0, groupTimeout)\\n\\nreturn reservoir\\n\",\"init.lua\":\"local clear = tonumber(ARGV[num_static_argv + 1])\\nlocal limiter_version = ARGV[num_static_argv + 2]\\nlocal num_local_argv = num_static_argv + 2\\n\\nif clear == 1 then\\n redis.call('del', unpack(KEYS))\\nend\\n\\nif redis.call('exists', settings_key) == 0 then\\n -- Create\\n local args = {'hmset', settings_key}\\n\\n for i = num_local_argv + 1, #ARGV do\\n table.insert(args, ARGV[i])\\n end\\n\\n redis.call(unpack(args))\\n redis.call('hmset', settings_key,\\n 'nextRequest', now,\\n 'lastReservoirRefresh', now,\\n 'lastReservoirIncrease', now,\\n 'running', 0,\\n 'done', 0,\\n 'unblockTime', 0,\\n 'capacityPriorityCounter', 0\\n )\\n\\nelse\\n -- Apply migrations\\n local settings = redis.call('hmget', settings_key,\\n 'id',\\n 'version'\\n )\\n local id = settings[1]\\n local current_version = settings[2]\\n\\n if current_version ~= limiter_version then\\n local version_digits = {}\\n for k, v in string.gmatch(current_version, \\\"([^.]+)\\\") do\\n table.insert(version_digits, tonumber(k))\\n end\\n\\n -- 2.10.0\\n if version_digits[2] < 10 then\\n redis.call('hsetnx', settings_key, 'reservoirRefreshInterval', '')\\n redis.call('hsetnx', settings_key, 'reservoirRefreshAmount', '')\\n redis.call('hsetnx', settings_key, 'lastReservoirRefresh', '')\\n redis.call('hsetnx', settings_key, 'done', 0)\\n redis.call('hset', settings_key, 'version', '2.10.0')\\n end\\n\\n -- 2.11.1\\n if version_digits[2] < 11 or (version_digits[2] == 11 and version_digits[3] < 1) then\\n if redis.call('hstrlen', settings_key, 'lastReservoirRefresh') == 0 then\\n redis.call('hmset', settings_key,\\n 'lastReservoirRefresh', now,\\n 'version', '2.11.1'\\n )\\n end\\n end\\n\\n -- 2.14.0\\n if version_digits[2] < 14 then\\n local old_running_key = 'b_'..id..'_running'\\n local old_executing_key = 'b_'..id..'_executing'\\n\\n if redis.call('exists', old_running_key) == 1 then\\n redis.call('rename', old_running_key, job_weights_key)\\n end\\n if redis.call('exists', old_executing_key) == 1 then\\n redis.call('rename', old_executing_key, job_expirations_key)\\n end\\n redis.call('hset', settings_key, 'version', '2.14.0')\\n end\\n\\n -- 2.15.2\\n if version_digits[2] < 15 or (version_digits[2] == 15 and version_digits[3] < 2) then\\n redis.call('hsetnx', settings_key, 'capacityPriorityCounter', 0)\\n redis.call('hset', settings_key, 'version', '2.15.2')\\n end\\n\\n -- 2.17.0\\n if version_digits[2] < 17 then\\n redis.call('hsetnx', settings_key, 'clientTimeout', 10000)\\n redis.call('hset', settings_key, 'version', '2.17.0')\\n end\\n\\n -- 2.18.0\\n if version_digits[2] < 18 then\\n redis.call('hsetnx', settings_key, 'reservoirIncreaseInterval', '')\\n redis.call('hsetnx', settings_key, 'reservoirIncreaseAmount', '')\\n redis.call('hsetnx', settings_key, 'reservoirIncreaseMaximum', '')\\n redis.call('hsetnx', settings_key, 'lastReservoirIncrease', now)\\n redis.call('hset', settings_key, 'version', '2.18.0')\\n end\\n\\n end\\n\\n process_tick(now, false)\\nend\\n\\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\\nrefresh_expiration(0, 0, groupTimeout)\\n\\nreturn {}\\n\",\"process_tick.lua\":\"local process_tick = function (now, always_publish)\\n\\n local compute_capacity = function (maxConcurrent, running, reservoir)\\n if maxConcurrent ~= nil and reservoir ~= nil then\\n return math.min((maxConcurrent - running), reservoir)\\n elseif maxConcurrent ~= nil then\\n return maxConcurrent - running\\n elseif reservoir ~= nil then\\n return reservoir\\n else\\n return nil\\n end\\n end\\n\\n local settings = redis.call('hmget', settings_key,\\n 'id',\\n 'maxConcurrent',\\n 'running',\\n 'reservoir',\\n 'reservoirRefreshInterval',\\n 'reservoirRefreshAmount',\\n 'lastReservoirRefresh',\\n 'reservoirIncreaseInterval',\\n 'reservoirIncreaseAmount',\\n 'reservoirIncreaseMaximum',\\n 'lastReservoirIncrease',\\n 'capacityPriorityCounter',\\n 'clientTimeout'\\n )\\n local id = settings[1]\\n local maxConcurrent = tonumber(settings[2])\\n local running = tonumber(settings[3])\\n local reservoir = tonumber(settings[4])\\n local reservoirRefreshInterval = tonumber(settings[5])\\n local reservoirRefreshAmount = tonumber(settings[6])\\n local lastReservoirRefresh = tonumber(settings[7])\\n local reservoirIncreaseInterval = tonumber(settings[8])\\n local reservoirIncreaseAmount = tonumber(settings[9])\\n local reservoirIncreaseMaximum = tonumber(settings[10])\\n local lastReservoirIncrease = tonumber(settings[11])\\n local capacityPriorityCounter = tonumber(settings[12])\\n local clientTimeout = tonumber(settings[13])\\n\\n local initial_capacity = compute_capacity(maxConcurrent, running, reservoir)\\n\\n --\\n -- Process 'running' changes\\n --\\n local expired = redis.call('zrangebyscore', job_expirations_key, '-inf', '('..now)\\n\\n if #expired > 0 then\\n redis.call('zremrangebyscore', job_expirations_key, '-inf', '('..now)\\n\\n local flush_batch = function (batch, acc)\\n local weights = redis.call('hmget', job_weights_key, unpack(batch))\\n redis.call('hdel', job_weights_key, unpack(batch))\\n local clients = redis.call('hmget', job_clients_key, unpack(batch))\\n redis.call('hdel', job_clients_key, unpack(batch))\\n\\n -- Calculate sum of removed weights\\n for i = 1, #weights do\\n acc['total'] = acc['total'] + (tonumber(weights[i]) or 0)\\n end\\n\\n -- Calculate sum of removed weights by client\\n local client_weights = {}\\n for i = 1, #clients do\\n local removed = tonumber(weights[i]) or 0\\n if removed > 0 then\\n acc['client_weights'][clients[i]] = (acc['client_weights'][clients[i]] or 0) + removed\\n end\\n end\\n end\\n\\n local acc = {\\n ['total'] = 0,\\n ['client_weights'] = {}\\n }\\n local batch_size = 1000\\n\\n -- Compute changes to Zsets and apply changes to Hashes\\n for i = 1, #expired, batch_size do\\n local batch = {}\\n for j = i, math.min(i + batch_size - 1, #expired) do\\n table.insert(batch, expired[j])\\n end\\n\\n flush_batch(batch, acc)\\n end\\n\\n -- Apply changes to Zsets\\n if acc['total'] > 0 then\\n redis.call('hincrby', settings_key, 'done', acc['total'])\\n running = tonumber(redis.call('hincrby', settings_key, 'running', -acc['total']))\\n end\\n\\n for client, weight in pairs(acc['client_weights']) do\\n redis.call('zincrby', client_running_key, -weight, client)\\n end\\n end\\n\\n --\\n -- Process 'reservoir' changes\\n --\\n local reservoirRefreshActive = reservoirRefreshInterval ~= nil and reservoirRefreshAmount ~= nil\\n if reservoirRefreshActive and now >= lastReservoirRefresh + reservoirRefreshInterval then\\n reservoir = reservoirRefreshAmount\\n redis.call('hmset', settings_key,\\n 'reservoir', reservoir,\\n 'lastReservoirRefresh', now\\n )\\n end\\n\\n local reservoirIncreaseActive = reservoirIncreaseInterval ~= nil and reservoirIncreaseAmount ~= nil\\n if reservoirIncreaseActive and now >= lastReservoirIncrease + reservoirIncreaseInterval then\\n local num_intervals = math.floor((now - lastReservoirIncrease) / reservoirIncreaseInterval)\\n local incr = reservoirIncreaseAmount * num_intervals\\n if reservoirIncreaseMaximum ~= nil then\\n incr = math.min(incr, reservoirIncreaseMaximum - (reservoir or 0))\\n end\\n if incr > 0 then\\n reservoir = (reservoir or 0) + incr\\n end\\n redis.call('hmset', settings_key,\\n 'reservoir', reservoir,\\n 'lastReservoirIncrease', lastReservoirIncrease + (num_intervals * reservoirIncreaseInterval)\\n )\\n end\\n\\n --\\n -- Clear unresponsive clients\\n --\\n local unresponsive = redis.call('zrangebyscore', client_last_seen_key, '-inf', (now - clientTimeout))\\n local unresponsive_lookup = {}\\n local terminated_clients = {}\\n for i = 1, #unresponsive do\\n unresponsive_lookup[unresponsive[i]] = true\\n if tonumber(redis.call('zscore', client_running_key, unresponsive[i])) == 0 then\\n table.insert(terminated_clients, unresponsive[i])\\n end\\n end\\n if #terminated_clients > 0 then\\n redis.call('zrem', client_running_key, unpack(terminated_clients))\\n redis.call('hdel', client_num_queued_key, unpack(terminated_clients))\\n redis.call('zrem', client_last_registered_key, unpack(terminated_clients))\\n redis.call('zrem', client_last_seen_key, unpack(terminated_clients))\\n end\\n\\n --\\n -- Broadcast capacity changes\\n --\\n local final_capacity = compute_capacity(maxConcurrent, running, reservoir)\\n\\n if always_publish or (initial_capacity ~= nil and final_capacity == nil) then\\n -- always_publish or was not unlimited, now unlimited\\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\\n\\n elseif initial_capacity ~= nil and final_capacity ~= nil and final_capacity > initial_capacity then\\n -- capacity was increased\\n -- send the capacity message to the limiter having the lowest number of running jobs\\n -- the tiebreaker is the limiter having not registered a job in the longest time\\n\\n local lowest_concurrency_value = nil\\n local lowest_concurrency_clients = {}\\n local lowest_concurrency_last_registered = {}\\n local client_concurrencies = redis.call('zrange', client_running_key, 0, -1, 'withscores')\\n\\n for i = 1, #client_concurrencies, 2 do\\n local client = client_concurrencies[i]\\n local concurrency = tonumber(client_concurrencies[i+1])\\n\\n if (\\n lowest_concurrency_value == nil or lowest_concurrency_value == concurrency\\n ) and (\\n not unresponsive_lookup[client]\\n ) and (\\n tonumber(redis.call('hget', client_num_queued_key, client)) > 0\\n ) then\\n lowest_concurrency_value = concurrency\\n table.insert(lowest_concurrency_clients, client)\\n local last_registered = tonumber(redis.call('zscore', client_last_registered_key, client))\\n table.insert(lowest_concurrency_last_registered, last_registered)\\n end\\n end\\n\\n if #lowest_concurrency_clients > 0 then\\n local position = 1\\n local earliest = lowest_concurrency_last_registered[1]\\n\\n for i,v in ipairs(lowest_concurrency_last_registered) do\\n if v < earliest then\\n position = i\\n earliest = v\\n end\\n end\\n\\n local next_client = lowest_concurrency_clients[position]\\n redis.call('publish', 'b_'..id,\\n 'capacity-priority:'..(final_capacity or '')..\\n ':'..next_client..\\n ':'..capacityPriorityCounter\\n )\\n redis.call('hincrby', settings_key, 'capacityPriorityCounter', '1')\\n else\\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\\n end\\n end\\n\\n return {\\n ['capacity'] = final_capacity,\\n ['running'] = running,\\n ['reservoir'] = reservoir\\n }\\nend\\n\",\"queued.lua\":\"local clientTimeout = tonumber(redis.call('hget', settings_key, 'clientTimeout'))\\nlocal valid_clients = redis.call('zrangebyscore', client_last_seen_key, (now - clientTimeout), 'inf')\\nlocal client_queued = redis.call('hmget', client_num_queued_key, unpack(valid_clients))\\n\\nlocal sum = 0\\nfor i = 1, #client_queued do\\n sum = sum + tonumber(client_queued[i])\\nend\\n\\nreturn sum\\n\",\"refresh_expiration.lua\":\"local refresh_expiration = function (now, nextRequest, groupTimeout)\\n\\n if groupTimeout ~= nil then\\n local ttl = (nextRequest + groupTimeout) - now\\n\\n for i = 1, #KEYS do\\n redis.call('pexpire', KEYS[i], ttl)\\n end\\n end\\n\\nend\\n\",\"refs.lua\":\"local settings_key = KEYS[1]\\nlocal job_weights_key = KEYS[2]\\nlocal job_expirations_key = KEYS[3]\\nlocal job_clients_key = KEYS[4]\\nlocal client_running_key = KEYS[5]\\nlocal client_num_queued_key = KEYS[6]\\nlocal client_last_registered_key = KEYS[7]\\nlocal client_last_seen_key = KEYS[8]\\n\\nlocal now = tonumber(ARGV[1])\\nlocal client = ARGV[2]\\n\\nlocal num_static_argv = 2\\n\",\"register.lua\":\"local index = ARGV[num_static_argv + 1]\\nlocal weight = tonumber(ARGV[num_static_argv + 2])\\nlocal expiration = tonumber(ARGV[num_static_argv + 3])\\n\\nlocal state = process_tick(now, false)\\nlocal capacity = state['capacity']\\nlocal reservoir = state['reservoir']\\n\\nlocal settings = redis.call('hmget', settings_key,\\n 'nextRequest',\\n 'minTime',\\n 'groupTimeout'\\n)\\nlocal nextRequest = tonumber(settings[1])\\nlocal minTime = tonumber(settings[2])\\nlocal groupTimeout = tonumber(settings[3])\\n\\nif conditions_check(capacity, weight) then\\n\\n redis.call('hincrby', settings_key, 'running', weight)\\n redis.call('hset', job_weights_key, index, weight)\\n if expiration ~= nil then\\n redis.call('zadd', job_expirations_key, now + expiration, index)\\n end\\n redis.call('hset', job_clients_key, index, client)\\n redis.call('zincrby', client_running_key, weight, client)\\n redis.call('hincrby', client_num_queued_key, client, -1)\\n redis.call('zadd', client_last_registered_key, now, client)\\n\\n local wait = math.max(nextRequest - now, 0)\\n local newNextRequest = now + wait + minTime\\n\\n if reservoir == nil then\\n redis.call('hset', settings_key,\\n 'nextRequest', newNextRequest\\n )\\n else\\n reservoir = reservoir - weight\\n redis.call('hmset', settings_key,\\n 'reservoir', reservoir,\\n 'nextRequest', newNextRequest\\n )\\n end\\n\\n refresh_expiration(now, newNextRequest, groupTimeout)\\n\\n return {true, wait, reservoir}\\n\\nelse\\n return {false}\\nend\\n\",\"register_client.lua\":\"local queued = tonumber(ARGV[num_static_argv + 1])\\n\\n-- Could have been re-registered concurrently\\nif not redis.call('zscore', client_last_seen_key, client) then\\n redis.call('zadd', client_running_key, 0, client)\\n redis.call('hset', client_num_queued_key, client, queued)\\n redis.call('zadd', client_last_registered_key, 0, client)\\nend\\n\\nredis.call('zadd', client_last_seen_key, now, client)\\n\\nreturn {}\\n\",\"running.lua\":\"return process_tick(now, false)['running']\\n\",\"submit.lua\":\"local queueLength = tonumber(ARGV[num_static_argv + 1])\\nlocal weight = tonumber(ARGV[num_static_argv + 2])\\n\\nlocal capacity = process_tick(now, false)['capacity']\\n\\nlocal settings = redis.call('hmget', settings_key,\\n 'id',\\n 'maxConcurrent',\\n 'highWater',\\n 'nextRequest',\\n 'strategy',\\n 'unblockTime',\\n 'penalty',\\n 'minTime',\\n 'groupTimeout'\\n)\\nlocal id = settings[1]\\nlocal maxConcurrent = tonumber(settings[2])\\nlocal highWater = tonumber(settings[3])\\nlocal nextRequest = tonumber(settings[4])\\nlocal strategy = tonumber(settings[5])\\nlocal unblockTime = tonumber(settings[6])\\nlocal penalty = tonumber(settings[7])\\nlocal minTime = tonumber(settings[8])\\nlocal groupTimeout = tonumber(settings[9])\\n\\nif maxConcurrent ~= nil and weight > maxConcurrent then\\n return redis.error_reply('OVERWEIGHT:'..weight..':'..maxConcurrent)\\nend\\n\\nlocal reachedHWM = (highWater ~= nil and queueLength == highWater\\n and not (\\n conditions_check(capacity, weight)\\n and nextRequest - now <= 0\\n )\\n)\\n\\nlocal blocked = strategy == 3 and (reachedHWM or unblockTime >= now)\\n\\nif blocked then\\n local computedPenalty = penalty\\n if computedPenalty == nil then\\n if minTime == 0 then\\n computedPenalty = 5000\\n else\\n computedPenalty = 15 * minTime\\n end\\n end\\n\\n local newNextRequest = now + computedPenalty + minTime\\n\\n redis.call('hmset', settings_key,\\n 'unblockTime', now + computedPenalty,\\n 'nextRequest', newNextRequest\\n )\\n\\n local clients_queued_reset = redis.call('hkeys', client_num_queued_key)\\n local queued_reset = {}\\n for i = 1, #clients_queued_reset do\\n table.insert(queued_reset, clients_queued_reset[i])\\n table.insert(queued_reset, 0)\\n end\\n redis.call('hmset', client_num_queued_key, unpack(queued_reset))\\n\\n redis.call('publish', 'b_'..id, 'blocked:')\\n\\n refresh_expiration(now, newNextRequest, groupTimeout)\\nend\\n\\nif not blocked and not reachedHWM then\\n redis.call('hincrby', client_num_queued_key, client, 1)\\nend\\n\\nreturn {reachedHWM, blocked, strategy}\\n\",\"update_settings.lua\":\"local args = {'hmset', settings_key}\\n\\nfor i = num_static_argv + 1, #ARGV do\\n table.insert(args, ARGV[i])\\nend\\n\\nredis.call(unpack(args))\\n\\nprocess_tick(now, true)\\n\\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\\nrefresh_expiration(0, 0, groupTimeout)\\n\\nreturn {}\\n\",\"validate_client.lua\":\"if not redis.call('zscore', client_last_seen_key, client) then\\n return redis.error_reply('UNKNOWN_CLIENT')\\nend\\n\\nredis.call('zadd', client_last_seen_key, now, client)\\n\",\"validate_keys.lua\":\"if not (redis.call('exists', settings_key) == 1) then\\n return redis.error_reply('SETTINGS_KEY_NOT_FOUND')\\nend\\n\"}"))},964638,(e,t,n)=>{"use strict";var r,i,s;r={refs:(i=e.r(592324))["refs.lua"],validate_keys:i["validate_keys.lua"],validate_client:i["validate_client.lua"],refresh_expiration:i["refresh_expiration.lua"],process_tick:i["process_tick.lua"],conditions_check:i["conditions_check.lua"],get_time:i["get_time.lua"]},n.allKeys=function(e){return[`b_${e}_settings`,`b_${e}_job_weights`,`b_${e}_job_expirations`,`b_${e}_job_clients`,`b_${e}_client_running`,`b_${e}_client_num_queued`,`b_${e}_client_last_registered`,`b_${e}_client_last_seen`]},s={init:{keys:n.allKeys,headers:["process_tick"],refresh_expiration:!0,code:i["init.lua"]},group_check:{keys:n.allKeys,headers:[],refresh_expiration:!1,code:i["group_check.lua"]},register_client:{keys:n.allKeys,headers:["validate_keys"],refresh_expiration:!1,code:i["register_client.lua"]},blacklist_client:{keys:n.allKeys,headers:["validate_keys","validate_client"],refresh_expiration:!1,code:i["blacklist_client.lua"]},heartbeat:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:i["heartbeat.lua"]},update_settings:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:i["update_settings.lua"]},running:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:i["running.lua"]},queued:{keys:n.allKeys,headers:["validate_keys","validate_client"],refresh_expiration:!1,code:i["queued.lua"]},done:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:i["done.lua"]},check:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!1,code:i["check.lua"]},submit:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!0,code:i["submit.lua"]},register:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!0,code:i["register.lua"]},free:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:i["free.lua"]},current_reservoir:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:i["current_reservoir.lua"]},increment_reservoir:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:i["increment_reservoir.lua"]}},n.names=Object.keys(s),n.keys=function(e,t){return s[e].keys(t)},n.payload=function(e){var t;return t=s[e],Array.prototype.concat(r.refs,t.headers.map(function(e){return r[e]}),t.refresh_expiration?r.refresh_expiration:"",t.code).join("\n")}},489410,(__turbopack_context__,module,exports)=>{"use strict";var Events,RedisConnection,Scripts,parser;function asyncGeneratorStep(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep(s,r,i,o,a,"throw",e)}o(void 0)})}}parser=__turbopack_context__.r(150447),Events=__turbopack_context__.r(589243),Scripts=__turbopack_context__.r(964638),RedisConnection=(function(){class RedisConnection{constructor(options={}){parser.load(options,this.defaults,this),null==this.Redis&&(this.Redis=eval("require")("redis")),null==this.Events&&(this.Events=new Events(this)),this.terminated=!1,null==this.client&&(this.client=this.Redis.createClient(this.clientOptions)),this.subscriber=this.client.duplicate(),this.limiters={},this.shas={},this.ready=this.Promise.all([this._setup(this.client,!1),this._setup(this.subscriber,!0)]).then(()=>this._loadScripts()).then(()=>({client:this.client,subscriber:this.subscriber}))}_setup(e,t){return e.setMaxListeners(0),new this.Promise((n,r)=>(e.on("error",e=>this.Events.trigger("error",e)),t&&e.on("message",(e,t)=>{var n;return null!=(n=this.limiters[e])?n._store.onMessage(e,t):void 0}),e.ready)?n():e.once("ready",n))}_loadScript(e){return new this.Promise((t,n)=>{var r;return r=Scripts.payload(e),this.client.multi([["script","load",r]]).exec((r,i)=>null!=r?n(r):(this.shas[e]=i[0],t(i[0])))})}_loadScripts(){return this.Promise.all(Scripts.names.map(e=>this._loadScript(e)))}__runCommand__(e){var t=this;return _asyncToGenerator(function*(){return yield t.ready,new t.Promise((n,r)=>t.client.multi([e]).exec_atomic(function(e,t){return null!=e?r(e):n(t[0])}))})()}__addLimiter__(e){return this.Promise.all([e.channel(),e.channel_client()].map(t=>new this.Promise((n,r)=>{var i;return i=r=>{if(r===t)return this.subscriber.removeListener("subscribe",i),this.limiters[t]=e,n()},this.subscriber.on("subscribe",i),this.subscriber.subscribe(t)})))}__removeLimiter__(e){var t=this;return this.Promise.all([e.channel(),e.channel_client()].map(function(){var e=_asyncToGenerator(function*(e){return t.terminated||(yield new t.Promise((n,r)=>t.subscriber.unsubscribe(e,function(t,i){return null!=t?r(t):i===e?n():void 0}))),delete t.limiters[e]});return function(t){return e.apply(this,arguments)}}()))}__scriptArgs__(e,t,n,r){var i;return i=Scripts.keys(e,t),[this.shas[e],i.length].concat(i,n,r)}__scriptFn__(e){return this.client.evalsha.bind(this.client)}disconnect(e=!0){var t,n,r,i;for(t=0,r=(i=Object.keys(this.limiters)).length;t<r;t++)n=i[t],clearInterval(this.limiters[n]._store.heartbeat);return this.limiters={},this.terminated=!0,this.client.end(e),this.subscriber.end(e),this.Promise.resolve()}}return RedisConnection.prototype.datastore="redis",RedisConnection.prototype.defaults={Redis:null,clientOptions:{},client:null,Promise:Promise,Events:null},RedisConnection}).call(void 0),module.exports=RedisConnection},6827,(__turbopack_context__,module,exports)=>{"use strict";var Events,IORedisConnection,Scripts,parser;function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_nonIterableRest()}function _nonIterableRest(){throw TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArrayLimit(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function _arrayWithHoles(e){if(Array.isArray(e))return e}function asyncGeneratorStep(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep(s,r,i,o,a,"throw",e)}o(void 0)})}}parser=__turbopack_context__.r(150447),Events=__turbopack_context__.r(589243),Scripts=__turbopack_context__.r(964638),IORedisConnection=(function(){class IORedisConnection{constructor(options={}){parser.load(options,this.defaults,this),null==this.Redis&&(this.Redis=eval("require")("ioredis")),null==this.Events&&(this.Events=new Events(this)),this.terminated=!1,null!=this.clusterNodes?(this.client=new this.Redis.Cluster(this.clusterNodes,this.clientOptions),this.subscriber=new this.Redis.Cluster(this.clusterNodes,this.clientOptions)):null!=this.client&&null==this.client.duplicate?this.subscriber=new this.Redis.Cluster(this.client.startupNodes,this.client.options):(null==this.client&&(this.client=new this.Redis(this.clientOptions)),this.subscriber=this.client.duplicate()),this.limiters={},this.ready=this.Promise.all([this._setup(this.client,!1),this._setup(this.subscriber,!0)]).then(()=>(this._loadScripts(),{client:this.client,subscriber:this.subscriber}))}_setup(e,t){return e.setMaxListeners(0),new this.Promise((n,r)=>(e.on("error",e=>this.Events.trigger("error",e)),t&&e.on("message",(e,t)=>{var n;return null!=(n=this.limiters[e])?n._store.onMessage(e,t):void 0}),"ready"===e.status)?n():e.once("ready",n))}_loadScripts(){return Scripts.names.forEach(e=>this.client.defineCommand(e,{lua:Scripts.payload(e)}))}__runCommand__(e){var t=this;return _asyncToGenerator(function*(){yield t.ready;var n,r=_slicedToArray((yield t.client.pipeline([e]).exec()),1),i=_slicedToArray(r[0],2);return n=i[0],i[1]})()}__addLimiter__(e){return this.Promise.all([e.channel(),e.channel_client()].map(t=>new this.Promise((n,r)=>this.subscriber.subscribe(t,()=>(this.limiters[t]=e,n())))))}__removeLimiter__(e){var t=this;return[e.channel(),e.channel_client()].forEach(function(){var e=_asyncToGenerator(function*(e){return t.terminated||(yield t.subscriber.unsubscribe(e)),delete t.limiters[e]});return function(t){return e.apply(this,arguments)}}())}__scriptArgs__(e,t,n,r){var i;return[(i=Scripts.keys(e,t)).length].concat(i,n,r)}__scriptFn__(e){return this.client[e].bind(this.client)}disconnect(e=!0){var t,n,r,i;for(t=0,r=(i=Object.keys(this.limiters)).length;t<r;t++)n=i[t],clearInterval(this.limiters[n]._store.heartbeat);return(this.limiters={},this.terminated=!0,e)?this.Promise.all([this.client.quit(),this.subscriber.quit()]):(this.client.disconnect(),this.subscriber.disconnect(),this.Promise.resolve())}}return IORedisConnection.prototype.datastore="ioredis",IORedisConnection.prototype.defaults={Redis:null,clientOptions:{},clusterNodes:null,client:null,Promise:Promise,Events:null},IORedisConnection}).call(void 0),module.exports=IORedisConnection},844112,(e,t,n)=>{"use strict";var r,i,s,o;function a(e,t){return u(e)||c(e,t)||l()}function l(){throw TypeError("Invalid attempt to destructure non-iterable instance")}function c(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function u(e){if(Array.isArray(e))return e}function h(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function d(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function o(e){h(s,r,i,o,a,"next",e)}function a(e){h(s,r,i,o,a,"throw",e)}o(void 0)})}}o=e.r(150447),r=e.r(938539),s=e.r(489410),i=e.r(6827),t.exports=class{constructor(e,t,n){this.instance=e,this.storeOptions=t,this.originalId=this.instance.id,this.clientId=this.instance._randomIndex(),o.load(n,n,this),this.clients={},this.capacityPriorityCounters={},this.sharedConnection=null!=this.connection,null==this.connection&&(this.connection="redis"===this.instance.datastore?new s({Redis:this.Redis,clientOptions:this.clientOptions,Promise:this.Promise,Events:this.instance.Events}):"ioredis"===this.instance.datastore?new i({Redis:this.Redis,clientOptions:this.clientOptions,clusterNodes:this.clusterNodes,Promise:this.Promise,Events:this.instance.Events}):void 0),this.instance.connection=this.connection,this.instance.datastore=this.connection.datastore,this.ready=this.connection.ready.then(e=>(this.clients=e,this.runScript("init",this.prepareInitSettings(this.clearDatastore)))).then(()=>this.connection.__addLimiter__(this.instance)).then(()=>this.runScript("register_client",[this.instance.queued()])).then(()=>{var e;return"function"==typeof(e=this.heartbeat=setInterval(()=>this.runScript("heartbeat",[]).catch(e=>this.instance.Events.trigger("error",e)),this.heartbeatInterval)).unref&&e.unref(),this.clients})}__publish__(e){var t=this;return d(function*(){return(yield t.ready).client.publish(t.instance.channel(),`message:${e.toString()}`)})()}onMessage(e,t){var n=this;return d(function*(){var e,r,i,s,o,l,c,u,h,_;try{c=t.indexOf(":");var p=[t.slice(0,c),t.slice(c+1)];if(_=p[0],i=p[1],"capacity"===_)return yield n.instance._drainAll(i.length>0?~~i:void 0);if("capacity-priority"===_){var v=i.split(":"),m=a(v,3);if(h=m[0],u=m[1],r=m[2],e=h.length>0?~~h:void 0,u===n.clientId)return s=yield n.instance._drainAll(e),l=null!=e?e-(s||0):"",yield n.clients.client.publish(n.instance.channel(),`capacity-priority:${l}::${r}`);if(""===u)return clearTimeout(n.capacityPriorityCounters[r]),delete n.capacityPriorityCounters[r],n.instance._drainAll(e);return n.capacityPriorityCounters[r]=setTimeout(d(function*(){var t;try{return delete n.capacityPriorityCounters[r],yield n.runScript("blacklist_client",[u]),yield n.instance._drainAll(e)}catch(e){return t=e,n.instance.Events.trigger("error",t)}}),1e3)}if("message"===_)return n.instance.Events.trigger("message",i);else if("blocked"===_)return yield n.instance._dropAllQueued()}catch(e){return o=e,n.instance.Events.trigger("error",o)}})()}__disconnect__(e){return(clearInterval(this.heartbeat),this.sharedConnection)?this.connection.__removeLimiter__(this.instance):this.connection.disconnect(e)}runScript(e,t){var n=this;return d(function*(){return"init"!==e&&"register_client"!==e&&(yield n.ready),new n.Promise((r,i)=>{var s,o;return s=[Date.now(),n.clientId].concat(t),n.instance.Events.trigger("debug",`Calling Redis script: ${e}.lua`,s),o=n.connection.__scriptArgs__(e,n.originalId,s,function(e,t){return null!=e?i(e):r(t)}),n.connection.__scriptFn__(e)(...o)}).catch(r=>{if("SETTINGS_KEY_NOT_FOUND"===r.message)if("heartbeat"===e)return n.Promise.resolve();else return n.runScript("init",n.prepareInitSettings(!1)).then(()=>n.runScript(e,t));return"UNKNOWN_CLIENT"===r.message?n.runScript("register_client",[n.instance.queued()]).then(()=>n.runScript(e,t)):n.Promise.reject(r)})})()}prepareArray(e){var t,n,r,i;for(t=0,r=[],n=e.length;t<n;t++)i=e[t],r.push(null!=i?i.toString():"");return r}prepareObject(e){var t,n,r;for(n in t=[],e)r=e[n],t.push(n,null!=r?r.toString():"");return t}prepareInitSettings(e){var t;return(t=this.prepareObject(Object.assign({},this.storeOptions,{id:this.originalId,version:this.instance.version,groupTimeout:this.timeout,clientTimeout:this.clientTimeout}))).unshift(+!!e,this.instance.version),t}convertBool(e){return!!e}__updateSettings__(e){var t=this;return d(function*(){return yield t.runScript("update_settings",t.prepareObject(e)),o.overwrite(e,e,t.storeOptions)})()}__running__(){return this.runScript("running",[])}__queued__(){return this.runScript("queued",[])}__done__(){return this.runScript("done",[])}__groupCheck__(){var e=this;return d(function*(){return e.convertBool((yield e.runScript("group_check",[])))})()}__incrementReservoir__(e){return this.runScript("increment_reservoir",[e])}__currentReservoir__(){return this.runScript("current_reservoir",[])}__check__(e){var t=this;return d(function*(){return t.convertBool((yield t.runScript("check",t.prepareArray([e]))))})()}__register__(e,t,n){var r=this;return d(function*(){var i,s,o,l=a((yield r.runScript("register",r.prepareArray([e,t,n]))),3);return s=l[0],o=l[1],i=l[2],{success:r.convertBool(s),wait:o,reservoir:i}})()}__submit__(e,t){var n=this;return d(function*(){var i,s,o,l,c,u;try{var h=yield n.runScript("submit",n.prepareArray([e,t])),d=a(h,3);return c=d[0],i=d[1],u=d[2],{reachedHWM:n.convertBool(c),blocked:n.convertBool(i),strategy:u}}catch(e){if(0===(s=e).message.indexOf("OVERWEIGHT")){var _=a(s.message.split(":"),3);throw l=_[0],t=_[1],o=_[2],new r(`Impossible to add a job having a weight of ${t} to a limiter having a maxConcurrent setting of ${o}`)}throw s}})()}__free__(e,t){var n=this;return d(function*(){return{running:yield n.runScript("free",n.prepareArray([e]))}})()}}},827551,(e,t,n)=>{"use strict";var r;r=e.r(938539),t.exports=class{constructor(e){this.status=e,this._jobs={},this.counts=this.status.map(function(){return 0})}next(e){var t,n;return(n=(t=this._jobs[e])+1,null!=t&&n<this.status.length)?(this.counts[t]--,this.counts[n]++,this._jobs[e]++):null!=t?(this.counts[t]--,delete this._jobs[e]):void 0}start(e){var t;return t=0,this._jobs[e]=t,this.counts[t]++}remove(e){var t;return null!=(t=this._jobs[e])&&(this.counts[t]--,delete this._jobs[e]),null!=t}jobStatus(e){var t;return null!=(t=this.status[this._jobs[e]])?t:null}statusJobs(e){var t,n,i,s;if(null==e)return Object.keys(this._jobs);if((n=this.status.indexOf(e))<0)throw new r(`status must be one of ${this.status.join(", ")}`);for(t in i=this._jobs,s=[],i)i[t]===n&&s.push(t);return s}statusCounts(){return this.counts.reduce((e,t,n)=>(e[this.status[n]]=t,e),{})}}},786110,(e,t,n)=>{"use strict";var r;function i(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function s(e){return function(){var t=this,n=arguments;return new Promise(function(r,s){var o=e.apply(t,n);function a(e){i(o,r,s,a,l,"next",e)}function l(e){i(o,r,s,a,l,"throw",e)}a(void 0)})}}r=e.r(818344),t.exports=class{constructor(e,t){this.schedule=this.schedule.bind(this),this.name=e,this.Promise=t,this._running=0,this._queue=new r}isEmpty(){return 0===this._queue.length}_tryToRun(){var e=this;return s(function*(){var t,n,r,i,o,a,l;if(e._running<1&&e._queue.length>0){e._running++;var c=e._queue.shift();return l=c.task,t=c.args,o=c.resolve,i=c.reject,n=yield s(function*(){try{return a=yield l(...t),function(){return o(a)}}catch(e){return r=e,function(){return i(r)}}})(),e._running--,e._tryToRun(),n()}})()}schedule(e,...t){var n,r,i;return i=r=null,n=new this.Promise(function(e,t){return i=e,r=t}),this._queue.push({task:e,args:t,resolve:i,reject:r}),this._tryToRun(),n}}},297549,e=>{e.v({version:"2.19.5"})},449670,(e,t,n)=>{"use strict";var r,i,s,o,a;function l(e,t){return h(e)||u(e,t)||c()}function c(){throw TypeError("Invalid attempt to destructure non-iterable instance")}function u(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function h(e){if(Array.isArray(e))return e}function d(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function _(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function o(e){d(s,r,i,o,a,"next",e)}function a(e){d(s,r,i,o,a,"throw",e)}o(void 0)})}}a=e.r(150447),r=e.r(589243),s=e.r(489410),i=e.r(6827),o=e.r(964638),t.exports=(function(){class t{constructor(t={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=t,a.load(this.limiterOptions,this.defaults,this),this.Events=new r(this),this.instances={},this.Bottleneck=e.r(579366),this._startAutoCleanup(),this.sharedConnection=null!=this.connection,null==this.connection&&("redis"===this.limiterOptions.datastore?this.connection=new s(Object.assign({},this.limiterOptions,{Events:this.Events})):"ioredis"===this.limiterOptions.datastore&&(this.connection=new i(Object.assign({},this.limiterOptions,{Events:this.Events}))))}key(e=""){var t;return null!=(t=this.instances[e])?t:(()=>{var t;return t=this.instances[e]=new this.Bottleneck(Object.assign(this.limiterOptions,{id:`${this.id}-${e}`,timeout:this.timeout,connection:this.connection})),this.Events.trigger("created",t,e),t})()}deleteKey(e=""){var t=this;return _(function*(){var n,r;return r=t.instances[e],t.connection&&(n=yield t.connection.__runCommand__(["del",...o.allKeys(`${t.id}-${e}`)])),null!=r&&(delete t.instances[e],yield r.disconnect()),null!=r||n>0})()}limiters(){var e,t,n,r;for(e in t=this.instances,n=[],t)r=t[e],n.push({key:e,limiter:r});return n}keys(){return Object.keys(this.instances)}clusterKeys(){var e=this;return _(function*(){var t,n,r,i,s,o,a,c,u;if(null==e.connection)return e.Promise.resolve(e.keys());for(o=[],t=null,u=`b_${e.id}-`.length,n=9;0!==t;){var h=l((yield e.connection.__runCommand__(["scan",null!=t?t:0,"match",`b_${e.id}-*_settings`,"count",1e4])),2);for(i=0,c=h[0],r=h[1],t=~~c,a=r.length;i<a;i++)s=r[i],o.push(s.slice(u,-n))}return o})()}_startAutoCleanup(){var e,t=this;return clearInterval(this.interval),"function"==typeof(e=this.interval=setInterval(_(function*(){var e,n,r,i,s,o;for(n in s=Date.now(),r=t.instances,i=[],r){o=r[n];try{(yield o._store.__groupCheck__(s))?i.push(t.deleteKey(n)):i.push(void 0)}catch(t){e=t,i.push(o.Events.trigger("error",e))}}return i}),this.timeout/2)).unref?e.unref():void 0}updateSettings(e={}){if(a.overwrite(e,this.defaults,this),a.overwrite(e,e,this.limiterOptions),null!=e.timeout)return this._startAutoCleanup()}disconnect(e=!0){var t;if(!this.sharedConnection)return null!=(t=this.connection)?t.disconnect(e):void 0}}return t.prototype.defaults={timeout:3e5,connection:null,Promise:Promise,id:"group-key"},t}).call(void 0)},212375,(e,t,n)=>{"use strict";var r,i;i=e.r(150447),r=e.r(589243),t.exports=(function(){class e{constructor(e={}){this.options=e,i.load(this.options,this.defaults,this),this.Events=new r(this),this._arr=[],this._resetPromise(),this._lastFlush=Date.now()}_resetPromise(){return this._promise=new this.Promise((e,t)=>this._resolve=e)}_flush(){return clearTimeout(this._timeout),this._lastFlush=Date.now(),this._resolve(),this.Events.trigger("batch",this._arr),this._arr=[],this._resetPromise()}add(e){var t;return this._arr.push(e),t=this._promise,this._arr.length===this.maxSize?this._flush():null!=this.maxTime&&1===this._arr.length&&(this._timeout=setTimeout(()=>this._flush(),this.maxTime)),t}}return e.prototype.defaults={maxTime:null,maxSize:null,Promise:Promise},e}).call(void 0)},579366,(e,t,n)=>{"use strict";function r(e,t){return l(e)||i(e,t)||o()}function i(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function s(e){return l(e)||a(e)||o()}function o(){throw TypeError("Invalid attempt to destructure non-iterable instance")}function a(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}function l(e){if(Array.isArray(e))return e}function c(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function u(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function o(e){c(s,r,i,o,a,"next",e)}function a(e){c(s,r,i,o,a,"throw",e)}o(void 0)})}}var h,d,_,p,v,m,f,g,y,b,k=[].splice;v=10,h=5,b=e.r(150447),m=e.r(247595),_=e.r(62367),p=e.r(725648),f=e.r(844112),d=e.r(589243),g=e.r(827551),y=e.r(786110),t.exports=(function(){class t{constructor(e={},...n){var r,i;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(e,n),b.load(e,this.instanceDefaults,this),this._queues=new m(v),this._scheduled={},this._states=new g(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new d(this),this._submitLock=new y("submit",this.Promise),this._registerLock=new y("register",this.Promise),i=b.load(e,this.storeDefaults,{}),this._store=(function(){if("redis"===this.datastore||"ioredis"===this.datastore||null!=this.connection)return new f(this,i,r=b.load(e,this.redisStoreDefaults,{}));if("local"===this.datastore)return new p(this,i,r=b.load(e,this.localStoreDefaults,{}));throw new t.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`)}).call(this),this._queues.on("leftzero",()=>{var e;return null!=(e=this._store.heartbeat)&&"function"==typeof e.ref?e.ref():void 0}),this._queues.on("zero",()=>{var e;return null!=(e=this._store.heartbeat)&&"function"==typeof e.unref?e.unref():void 0})}_validateOptions(e,n){if(null==e||"object"!=typeof e||0!==n.length)throw new t.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.")}ready(){return this._store.ready}clients(){return this._store.clients}channel(){return`b_${this.id}`}channel_client(){return`b_${this.id}_${this._store.clientId}`}publish(e){return this._store.__publish__(e)}disconnect(e=!0){return this._store.__disconnect__(e)}chain(e){return this._limiter=e,this}queued(e){return this._queues.queued(e)}clusterQueued(){return this._store.__queued__()}empty(){return 0===this.queued()&&this._submitLock.isEmpty()}running(){return this._store.__running__()}done(){return this._store.__done__()}jobStatus(e){return this._states.jobStatus(e)}jobs(e){return this._states.statusJobs(e)}counts(){return this._states.statusCounts()}_randomIndex(){return Math.random().toString(36).slice(2)}check(e=1){return this._store.__check__(e)}_clearGlobalState(e){return null!=this._scheduled[e]&&(clearTimeout(this._scheduled[e].expiration),delete this._scheduled[e],!0)}_free(e,t,n,r){var i=this;return u(function*(){var t,s;try{if(s=(yield i._store.__free__(e,n.weight)).running,i.Events.trigger("debug",`Freed ${n.id}`,r),0===s&&i.empty())return i.Events.trigger("idle")}catch(e){return t=e,i.Events.trigger("error",t)}})()}_run(e,t,n){var r,i,s;return t.doRun(),r=this._clearGlobalState.bind(this,e),s=this._run.bind(this,e,t),i=this._free.bind(this,e,t),this._scheduled[e]={timeout:setTimeout(()=>t.doExecute(this._limiter,r,s,i),n),expiration:null!=t.options.expiration?setTimeout(function(){return t.doExpire(r,s,i)},n+t.options.expiration):void 0,job:t}}_drainOne(e){return this._registerLock.schedule(()=>{if(0===this.queued())return this.Promise.resolve(null);var t,n,r,i,s=this._queues.getFirst(),o=r=s.first();return(i=o.options,t=o.args,null!=e&&i.weight>e)?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${i.id}`,{args:t,options:i}),n=this._randomIndex(),this._store.__register__(n,i.weight,i.expiration).then(({success:e,wait:o,reservoir:a})=>{var l;return(this.Events.trigger("debug",`Drained ${i.id}`,{success:e,args:t,options:i}),e)?(s.shift(),(l=this.empty())&&this.Events.trigger("empty"),0===a&&this.Events.trigger("depleted",l),this._run(n,r,o),this.Promise.resolve(i.weight)):this.Promise.resolve(null)}))})}_drainAll(e,t=0){return this._drainOne(e).then(n=>{var r;return null!=n?(r=null!=e?e-n:e,this._drainAll(r,t+n)):this.Promise.resolve(t)}).catch(e=>this.Events.trigger("error",e))}_dropAllQueued(e){return this._queues.shiftAll(function(t){return t.doDrop({message:e})})}stop(e={}){var n,r;return e=b.load(e,this.stopDefaults),r=e=>{var t;return t=()=>{var t;return(t=this._states.counts)[0]+t[1]+t[2]+t[3]===e},new this.Promise((e,n)=>t()?e():this.on("done",()=>{if(t())return this.removeAllListeners("done"),e()}))},n=e.dropWaitingJobs?(this._run=function(t,n){return n.doDrop({message:e.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule(()=>this._submitLock.schedule(()=>{var t,n,i;for(t in n=this._scheduled)i=n[t],"RUNNING"===this.jobStatus(i.job.options.id)&&(clearTimeout(i.timeout),clearTimeout(i.expiration),i.job.doDrop({message:e.dropErrorMessage}));return this._dropAllQueued(e.dropErrorMessage),r(0)}))):this.schedule({priority:v-1,weight:0},()=>r(1)),this._receive=function(n){return n._reject(new t.prototype.BottleneckError(e.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new t.prototype.BottleneckError("stop() has already been called")),n}_addToQueue(e){var n=this;return u(function*(){var r,i,s,o,a,l,c;r=e.args,o=e.options;try{var u=yield n._store.__submit__(n.queued(),o.weight);a=u.reachedHWM,i=u.blocked,c=u.strategy}catch(t){return s=t,n.Events.trigger("debug",`Could not queue ${o.id}`,{args:r,options:o,error:s}),e.doDrop({error:s}),!1}return i?(e.doDrop(),!0):a&&(null!=(l=c===t.prototype.strategy.LEAK?n._queues.shiftLastFrom(o.priority):c===t.prototype.strategy.OVERFLOW_PRIORITY?n._queues.shiftLastFrom(o.priority+1):c===t.prototype.strategy.OVERFLOW?e:void 0)&&l.doDrop(),null==l||c===t.prototype.strategy.OVERFLOW)?(null==l&&e.doDrop(),a):(e.doQueue(a,i),n._queues.push(e),yield n._drainAll(),a)})()}_receive(e){return null!=this._states.jobStatus(e.options.id)?(e._reject(new t.prototype.BottleneckError(`A job with the same id already exists (id=${e.options.id})`)),!1):(e.doReceive(),this._submitLock.schedule(this._addToQueue,e))}submit(...e){var t,n,i,o,a,l;return"function"==typeof e[0]?(n=(a=s(e))[0],e=a.slice(1),t=r(k.call(e,-1),1)[0],o=b.load({},this.jobDefaults)):(o=(l=s(e))[0],n=l[1],e=l.slice(2),t=r(k.call(e,-1),1)[0],o=b.load(o,this.jobDefaults)),(i=new _((...e)=>new this.Promise(function(t,r){return n(...e,function(...e){return(null!=e[0]?r:t)(e)})}),e,o,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise)).promise.then(function(e){return"function"==typeof t?t(...e):void 0}).catch(function(e){return Array.isArray(e)?"function"==typeof t?t(...e):void 0:"function"==typeof t?t(e):void 0}),this._receive(i)}schedule(...e){var t,n,r;if("function"==typeof e[0]){var i=s(e);r=i[0],e=i.slice(1),n={}}else{var o=s(e);n=o[0],r=o[1],e=o.slice(2)}return t=new _(r,e,n,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(t),t.promise}wrap(e){var t,n;return t=this.schedule.bind(this),(n=function(...n){return t(e.bind(this),...n)}).withOptions=function(n,...r){return t(n,e,...r)},n}updateSettings(e={}){var t=this;return u(function*(){return yield t._store.__updateSettings__(b.overwrite(e,t.storeDefaults)),b.overwrite(e,t.instanceDefaults,t),t})()}currentReservoir(){return this._store.__currentReservoir__()}incrementReservoir(e=0){return this._store.__incrementReservoir__(e)}}return t.default=t,t.Events=d,t.version=t.prototype.version=e.r(297549).version,t.strategy=t.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},t.BottleneckError=t.prototype.BottleneckError=e.r(938539),t.Group=t.prototype.Group=e.r(449670),t.RedisConnection=t.prototype.RedisConnection=e.r(489410),t.IORedisConnection=t.prototype.IORedisConnection=e.r(6827),t.Batcher=t.prototype.Batcher=e.r(212375),t.prototype.jobDefaults={priority:h,weight:1,expiration:null,id:"<no-id>"},t.prototype.storeDefaults={maxConcurrent:null,minTime:0,highWater:null,strategy:t.prototype.strategy.LEAK,penalty:null,reservoir:null,reservoirRefreshInterval:null,reservoirRefreshAmount:null,reservoirIncreaseInterval:null,reservoirIncreaseAmount:null,reservoirIncreaseMaximum:null},t.prototype.localStoreDefaults={Promise:Promise,timeout:null,heartbeatInterval:250},t.prototype.redisStoreDefaults={Promise:Promise,timeout:null,heartbeatInterval:5e3,clientTimeout:1e4,Redis:null,clientOptions:{},clusterNodes:null,clearDatastore:!1,connection:null},t.prototype.instanceDefaults={datastore:"local",connection:null,id:"<no-id>",rejectOnDrop:!0,trackDoneStatus:!1,Promise:Promise},t.prototype.stopDefaults={enqueueErrorMessage:"This limiter has been stopped and cannot accept new jobs.",dropWaitingJobs:!0,dropErrorMessage:"This limiter has been stopped."},t}).call(void 0)},944883,(e,t,n)=>{"use strict";t.exports=e.r(579366)},20870,e=>{"use strict";var t=e.i(944883),n=e.i(441637),r=e.i(828059),i=e.i(16023);function s(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function o(e,t=0){let n="number"==typeof e?e:"string"==typeof e&&e.trim().length>0?Number(e):NaN;return Number.isFinite(n)?n:t}let a=new Map,l=new Set,c={},u=null,h=6e4,d=!1,_=parseInt(process.env.RATE_LIMIT_MAX_WAIT_MS||"120000",10),p={maxConcurrent:10,minTime:0,reservoir:null,reservoirRefreshAmount:null,reservoirRefreshInterval:null,maxWait:_};async function v(){if(!d){d=!0;try{let{getProviderConnections:n}=await e.A(605589),c=await n(),u=0,h=0,d=0;for(let e of c){let n=s(e),c="string"==typeof n.id?n.id:"",p="string"==typeof n.provider?n.provider:"",v=!0===n.isActive,m=!0===n.rateLimitProtection,f=o(n.customRpm,0),g=o(n.customTpm,0);if(c&&p){if(f>0||g>0){l.add(c),d++;let e=`${p}:${c}`,n=f>0?f:i.DEFAULT_API_LIMITS.requestsPerMinute,r=Math.max(0,Math.floor(6e4/n)-10);a.has(e)||a.set(e,new t.default({maxConcurrent:i.DEFAULT_API_LIMITS.concurrentRequests,minTime:r,reservoir:n,reservoirRefreshAmount:n,reservoirRefreshInterval:6e4,maxWait:_,id:e}))}else if(m)l.add(c),u++;else if("apikey"===(0,r.getProviderCategory)(p)&&v){l.add(c),h++;let e=`${p}:${c}`;a.has(e)||a.set(e,new t.default({maxConcurrent:i.DEFAULT_API_LIMITS.concurrentRequests,minTime:i.DEFAULT_API_LIMITS.minTimeBetweenRequests,reservoir:i.DEFAULT_API_LIMITS.requestsPerMinute,reservoirRefreshAmount:i.DEFAULT_API_LIMITS.requestsPerMinute,reservoirRefreshInterval:6e4,maxWait:_,id:e}))}}}(u>0||h>0||d>0)&&console.log(`🛡️ [RATE-LIMIT] Loaded ${u} explicit + ${h} auto-enabled + ${d} custom rpm/tpm protection(s)`),await P()}catch(e){console.error("[RATE-LIMIT] Failed to load settings:",e.message)}}}function m(e){l.add(e)}function f(e){for(let[t]of(l.delete(e),a))if(t.includes(e)){let e=a.get(t);e?.disconnect(),a.delete(t)}}function g(e){return l.has(e)}function y(e,n,r=null){let i=r?`${e}:${n}:${r}`:`${e}:${n}`;if(!a.has(i)){let e=new t.default({...p,id:i});e.on("queued",()=>{let t=e.counts();t.QUEUED>0&&console.log(`⏳ [RATE-LIMIT] ${i} — ${t.QUEUED} request(s) queued, ${t.RUNNING} running`)}),a.set(i,e)}return a.get(i)}async function b(e,t,n,r){return l.has(t)?y(e,t,null).schedule(r):r()}let k={limit:"x-ratelimit-limit-requests",remaining:"x-ratelimit-remaining-requests",reset:"x-ratelimit-reset-requests",limitTokens:"x-ratelimit-limit-tokens",remainingTokens:"x-ratelimit-remaining-tokens",resetTokens:"x-ratelimit-reset-tokens",retryAfter:"retry-after",overLimit:"x-ratelimit-over-limit"},w={limit:"anthropic-ratelimit-requests-limit",remaining:"anthropic-ratelimit-requests-remaining",reset:"anthropic-ratelimit-requests-reset",limitTokens:"anthropic-ratelimit-input-tokens-limit",remainingTokens:"anthropic-ratelimit-input-tokens-remaining",resetTokens:"anthropic-ratelimit-input-tokens-reset",retryAfter:"retry-after"};function x(e){if(!e)return null;let t=e.match(/^(?:(\d+)h)?(?:(\d+)m(?!s))?(?:(\d+)s)?(?:(\d+)ms)?$/);if(t){let[,e,n,r,i]=t;return(3600*parseInt(e||0)+60*parseInt(n||0)+parseInt(r||0))*1e3+parseInt(i||0)}let n=parseFloat(e);if(!isNaN(n)&&n>0)return n>17e8?Math.max(0,1e3*n-Date.now()):1e3*n;try{let t=new Date(e);if(!isNaN(t.getTime()))return Math.max(0,t.getTime()-Date.now())}catch{}return null}function R(e,t,n,r,i=null){if(!l.has(t)||!n)return;let s=y(e,t,null),o="claude"===e||"anthropic"===e?w:k,a=e=>"function"==typeof n.get?n.get(e):n[e]||null,c=parseInt(a(o.limit)),u=parseInt(a(o.remaining)),h=a(o.reset),d=a(o.retryAfter),_=a(k.overLimit);if(429===r){let n=x(d)||6e4;console.log(`🚫 [RATE-LIMIT] ${e}:${t.slice(0,8)} — 429 received, pausing for ${Math.ceil(n/1e3)}s`),s.updateSettings({reservoir:0,reservoirRefreshAmount:c||60,reservoirRefreshInterval:n});return}if("yes"===_){console.log(`⚠️ [RATE-LIMIT] ${e}:${t.slice(0,8)} — near capacity, slowing down`),s.updateSettings({minTime:200});return}if(!isNaN(c)&&c>0){let n=x(h)||6e4,r={minTime:Math.max(0,Math.floor(6e4/c)-10)};!isNaN(u)&&(u<.1*c?(r.reservoir=u,r.reservoirRefreshAmount=c,r.reservoirRefreshInterval=n,console.log(`⚠️ [RATE-LIMIT] ${e}:${t.slice(0,8)} — ${u}/${c} remaining, throttling`)):u>.5*c&&(r.minTime=0,r.reservoir=null,r.reservoirRefreshAmount=null,r.reservoirRefreshInterval=null)),s.updateSettings(r),A(e,t,{limit:c,remaining:u,minTime:r.minTime})}}function I(e,t){let n=`${e}:${t}`,r=a.get(n);if(!r)return{enabled:l.has(t),active:!1,queued:0,running:0};let i=r.counts();return{enabled:l.has(t),active:!0,queued:i.QUEUED||0,running:i.RUNNING||0,executing:i.EXECUTING||0,done:i.DONE||0}}function E(){let e={};for(let[t,n]of a){let r=n.counts();e[t]={queued:r.QUEUED||0,running:r.RUNNING||0,executing:r.EXECUTING||0}}return e}function T(){return{...c}}function A(t,n,r){c[`${t}:${n}`]={...r,provider:t,connectionId:n,lastUpdated:Date.now()},u||(u=setTimeout(async()=>{u=null;try{let{updateSettings:t}=await e.A(606102);await t({learnedRateLimits:JSON.stringify(c)}),console.log(`💾 [RATE-LIMIT] Persisted learned limits for ${Object.keys(c).length} provider(s)`)}catch(e){console.error("[RATE-LIMIT] Failed to persist learned limits:",e.message)}},h))}async function P(){try{let{getSettings:t}=await e.A(606102),n=await t(),r=n?.learnedRateLimits;if("string"!=typeof r||0===r.trim().length)return;let i=s(JSON.parse(r)),u=0;for(let[e,t]of Object.entries(i)){let n=s(t),r=o(n.lastUpdated,0);if(r>0&&Date.now()-r>864e5)continue;let i="string"==typeof n.connectionId?n.connectionId:"",h="string"==typeof n.provider?n.provider:"",d=o(n.limit,0),_=o(n.remaining,0),p=o(n.minTime,0);if(c[e]={provider:h,connectionId:i,lastUpdated:r,...d>0?{limit:d}:{},..._>=0?{remaining:_}:{},...p>=0?{minTime:p}:{}},i&&l.has(i)){let t=a.get(e);if(t&&d>0){let e=p||Math.max(0,Math.floor(6e4/d)-10);t.updateSettings({minTime:e}),u++}}}u>0&&console.log(`📥 [RATE-LIMIT] Restored ${u} learned rate limit(s) from persistence`)}catch(e){console.error("[RATE-LIMIT] Failed to load persisted limits:",e.message)}}function O(e,t,r,i,s=null){if(!l.has(t))return;let{retryAfterMs:o,reason:a}=(0,n.parseRetryAfterFromBody)(r);if(o&&o>0){let r=y(e,t,null);console.log(`🚫 [RATE-LIMIT] ${e}:${t.slice(0,8)} — body-parsed retry: ${Math.ceil(o/1e3)}s (${a})`),r.updateSettings({reservoir:0,reservoirRefreshAmount:60,reservoirRefreshInterval:o}),s&&(0,n.lockModel)(e,t,s,a,o)}}e.s(["disableRateLimitProtection",()=>f,"enableRateLimitProtection",()=>m,"getAllRateLimitStatus",()=>E,"getLearnedLimits",()=>T,"getRateLimitStatus",()=>I,"initializeRateLimits",()=>v,"isRateLimitEnabled",()=>g,"updateFromHeaders",()=>R,"updateFromResponseBody",()=>O,"withRateLimit",()=>b])}];
1
+ module.exports=[150447,(e,t,n)=>{"use strict";n.load=function(e,t,n={}){var r,i,s;for(r in t)s=t[r],n[r]=null!=(i=e[r])?i:s;return n},n.overwrite=function(e,t,n={}){var r,i;for(r in e)i=e[r],void 0!==t[r]&&(n[r]=i);return n}},818344,(e,t,n)=>{"use strict";t.exports=class{constructor(e,t){this.incr=e,this.decr=t,this._first=null,this._last=null,this.length=0}push(e){var t;this.length++,"function"==typeof this.incr&&this.incr(),t={value:e,prev:this._last,next:null},null!=this._last?(this._last.next=t,this._last=t):this._first=this._last=t}shift(){var e;return null==this._first?void 0:(this.length--,"function"==typeof this.decr&&this.decr(),e=this._first.value,null!=(this._first=this._first.next)?this._first.prev=null:this._last=null,e)}first(){if(null!=this._first)return this._first.value}getArray(){var e,t,n;for(e=this._first,n=[];null!=e;)n.push((t=e,e=e.next,t.value));return n}forEachShift(e){var t;for(t=this.shift();null!=t;)e(t),t=this.shift()}debug(){var e,t,n,r,i;for(e=this._first,i=[];null!=e;)i.push((t=e,e=e.next,{value:t.value,prev:null!=(n=t.prev)?n.value:void 0,next:null!=(r=t.next)?r.value:void 0}));return i}}},589243,(e,t,n)=>{"use strict";function r(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function i(e){return function(){var t=this,n=arguments;return new Promise(function(i,s){var o=e.apply(t,n);function a(e){r(o,i,s,a,l,"next",e)}function l(e){r(o,i,s,a,l,"throw",e)}a(void 0)})}}t.exports=class{constructor(e){if(this.instance=e,this._events={},null!=this.instance.on||null!=this.instance.once||null!=this.instance.removeAllListeners)throw Error("An Emitter already exists for this object");this.instance.on=(e,t)=>this._addListener(e,"many",t),this.instance.once=(e,t)=>this._addListener(e,"once",t),this.instance.removeAllListeners=(e=null)=>null!=e?delete this._events[e]:this._events={}}_addListener(e,t,n){var r;return null==(r=this._events)[e]&&(r[e]=[]),this._events[e].push({cb:n,status:t}),this.instance}listenerCount(e){return null!=this._events[e]?this._events[e].length:0}trigger(e,...t){var n=this;return i(function*(){var r,s;try{if("debug"!==e&&n.trigger("debug",`Event triggered: ${e}`,t),null==n._events[e])return;return n._events[e]=n._events[e].filter(function(e){return"none"!==e.status}),s=n._events[e].map(function(){var e=i(function*(e){var r,i;if("none"!==e.status){"once"===e.status&&(e.status="none");try{if(i="function"==typeof e.cb?e.cb(...t):void 0,"function"==typeof(null!=i?i.then:void 0))return yield i;return i}catch(e){return r=e,n.trigger("error",r),null}}});return function(t){return e.apply(this,arguments)}}()),(yield Promise.all(s)).find(function(e){return null!=e})}catch(e){return r=e,n.trigger("error",r),null}})()}}},247595,(e,t,n)=>{"use strict";var r,i;r=e.r(818344),i=e.r(589243),t.exports=class{constructor(e){var t;this.Events=new i(this),this._length=0,this._lists=(function(){var n,i,s;for(s=[],t=n=1,i=e;1<=i?n<=i:n>=i;t=1<=i?++n:--n)s.push(new r(()=>this.incr(),()=>this.decr()));return s}).call(this)}incr(){if(0==this._length++)return this.Events.trigger("leftzero")}decr(){if(0==--this._length)return this.Events.trigger("zero")}push(e){return this._lists[e.options.priority].push(e)}queued(e){return null!=e?this._lists[e].length:this._length}shiftAll(e){return this._lists.forEach(function(t){return t.forEachShift(e)})}getFirst(e=this._lists){var t,n,r;for(t=0,n=e.length;t<n;t++)if((r=e[t]).length>0)return r;return[]}shiftLastFrom(e){return this.getFirst(this._lists.slice(e).reverse()).shift()}}},938539,(e,t,n)=>{"use strict";t.exports=class extends Error{}},62367,(e,t,n)=>{"use strict";var r,i,s,o;function a(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function l(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function o(e){a(s,r,i,o,l,"next",e)}function l(e){a(s,r,i,o,l,"throw",e)}o(void 0)})}}s=10,i=5,o=e.r(150447),r=e.r(938539),t.exports=class{constructor(e,t,n,r,i,s,a,l){this.task=e,this.args=t,this.rejectOnDrop=i,this.Events=s,this._states=a,this.Promise=l,this.options=o.load(n,r),this.options.priority=this._sanitizePriority(this.options.priority),this.options.id===r.id&&(this.options.id=`${this.options.id}-${this._randomIndex()}`),this.promise=new this.Promise((e,t)=>{this._resolve=e,this._reject=t}),this.retryCount=0}_sanitizePriority(e){var t;return(t=~~e!==e?i:e)<0?0:t>s-1?s-1:t}_randomIndex(){return Math.random().toString(36).slice(2)}doDrop({error:e,message:t="This job has been dropped by Bottleneck"}={}){return!!this._states.remove(this.options.id)&&(this.rejectOnDrop&&this._reject(null!=e?e:new r(t)),this.Events.trigger("dropped",{args:this.args,options:this.options,task:this.task,promise:this.promise}),!0)}_assertStatus(e){var t;if((t=this._states.jobStatus(this.options.id))!==e&&("DONE"!==e||null!==t))throw new r(`Invalid job status ${t}, expected ${e}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`)}doReceive(){return this._states.start(this.options.id),this.Events.trigger("received",{args:this.args,options:this.options})}doQueue(e,t){return this._assertStatus("RECEIVED"),this._states.next(this.options.id),this.Events.trigger("queued",{args:this.args,options:this.options,reachedHWM:e,blocked:t})}doRun(){return 0===this.retryCount?(this._assertStatus("QUEUED"),this._states.next(this.options.id)):this._assertStatus("EXECUTING"),this.Events.trigger("scheduled",{args:this.args,options:this.options})}doExecute(e,t,n,r){var i=this;return l(function*(){var s,o,a;0===i.retryCount?(i._assertStatus("RUNNING"),i._states.next(i.options.id)):i._assertStatus("EXECUTING"),o={args:i.args,options:i.options,retryCount:i.retryCount},i.Events.trigger("executing",o);try{if(a=yield null!=e?e.schedule(i.options,i.task,...i.args):i.task(...i.args),t())return i.doDone(o),yield r(i.options,o),i._assertStatus("DONE"),i._resolve(a)}catch(e){return s=e,i._onFailure(s,o,t,n,r)}})()}doExpire(e,t,n){var i,s;return this._states.jobStatus("RUNNING"===this.options.id)&&this._states.next(this.options.id),this._assertStatus("EXECUTING"),s={args:this.args,options:this.options,retryCount:this.retryCount},i=new r(`This job timed out after ${this.options.expiration} ms.`),this._onFailure(i,s,e,t,n)}_onFailure(e,t,n,r,i){var s=this;return l(function*(){var o,a;if(n())return null!=(o=yield s.Events.trigger("failed",e,t))?(a=~~o,s.Events.trigger("retry",`Retrying ${s.options.id} after ${a} ms`,t),s.retryCount++,r(a)):(s.doDone(t),yield i(s.options,t),s._assertStatus("DONE"),s._reject(e))})()}doDone(e){return this._assertStatus("EXECUTING"),this._states.next(this.options.id),this.Events.trigger("done",e)}}},725648,(e,t,n)=>{"use strict";var r,i;function s(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function o(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var o=e.apply(t,n);function a(e){s(o,r,i,a,l,"next",e)}function l(e){s(o,r,i,a,l,"throw",e)}a(void 0)})}}i=e.r(150447),r=e.r(938539),t.exports=class{constructor(e,t,n){this.instance=e,this.storeOptions=t,this.clientId=this.instance._randomIndex(),i.load(n,n,this),this._nextRequest=this._lastReservoirRefresh=this._lastReservoirIncrease=Date.now(),this._running=0,this._done=0,this._unblockTime=0,this.ready=this.Promise.resolve(),this.clients={},this._startHeartbeat()}_startHeartbeat(){var e;return null==this.heartbeat&&(null!=this.storeOptions.reservoirRefreshInterval&&null!=this.storeOptions.reservoirRefreshAmount||null!=this.storeOptions.reservoirIncreaseInterval&&null!=this.storeOptions.reservoirIncreaseAmount)?"function"==typeof(e=this.heartbeat=setInterval(()=>{var e,t,n,r,i;if(r=Date.now(),null!=this.storeOptions.reservoirRefreshInterval&&r>=this._lastReservoirRefresh+this.storeOptions.reservoirRefreshInterval&&(this._lastReservoirRefresh=r,this.storeOptions.reservoir=this.storeOptions.reservoirRefreshAmount,this.instance._drainAll(this.computeCapacity())),null!=this.storeOptions.reservoirIncreaseInterval&&r>=this._lastReservoirIncrease+this.storeOptions.reservoirIncreaseInterval){var s=this.storeOptions;if(e=s.reservoirIncreaseAmount,n=s.reservoirIncreaseMaximum,i=s.reservoir,this._lastReservoirIncrease=r,(t=null!=n?Math.min(e,n-i):e)>0)return this.storeOptions.reservoir+=t,this.instance._drainAll(this.computeCapacity())}},this.heartbeatInterval)).unref?e.unref():void 0:clearInterval(this.heartbeat)}__publish__(e){var t=this;return o(function*(){return yield t.yieldLoop(),t.instance.Events.trigger("message",e.toString())})()}__disconnect__(e){var t=this;return o(function*(){return yield t.yieldLoop(),clearInterval(t.heartbeat),t.Promise.resolve()})()}yieldLoop(e=0){return new this.Promise(function(t,n){return setTimeout(t,e)})}computePenalty(){var e;return null!=(e=this.storeOptions.penalty)?e:15*this.storeOptions.minTime||5e3}__updateSettings__(e){var t=this;return o(function*(){return yield t.yieldLoop(),i.overwrite(e,e,t.storeOptions),t._startHeartbeat(),t.instance._drainAll(t.computeCapacity()),!0})()}__running__(){var e=this;return o(function*(){return yield e.yieldLoop(),e._running})()}__queued__(){var e=this;return o(function*(){return yield e.yieldLoop(),e.instance.queued()})()}__done__(){var e=this;return o(function*(){return yield e.yieldLoop(),e._done})()}__groupCheck__(e){var t=this;return o(function*(){return yield t.yieldLoop(),t._nextRequest+t.timeout<e})()}computeCapacity(){var e,t,n=this.storeOptions;return(e=n.maxConcurrent,t=n.reservoir,null!=e&&null!=t)?Math.min(e-this._running,t):null!=e?e-this._running:null!=t?t:null}conditionsCheck(e){var t;return null==(t=this.computeCapacity())||e<=t}__incrementReservoir__(e){var t=this;return o(function*(){var n;return yield t.yieldLoop(),n=t.storeOptions.reservoir+=e,t.instance._drainAll(t.computeCapacity()),n})()}__currentReservoir__(){var e=this;return o(function*(){return yield e.yieldLoop(),e.storeOptions.reservoir})()}isBlocked(e){return this._unblockTime>=e}check(e,t){return this.conditionsCheck(e)&&this._nextRequest-t<=0}__check__(e){var t=this;return o(function*(){var n;return yield t.yieldLoop(),n=Date.now(),t.check(e,n)})()}__register__(e,t,n){var r=this;return o(function*(){var e,n;return(yield r.yieldLoop(),e=Date.now(),r.conditionsCheck(t))?(r._running+=t,null!=r.storeOptions.reservoir&&(r.storeOptions.reservoir-=t),n=Math.max(r._nextRequest-e,0),r._nextRequest=e+n+r.storeOptions.minTime,{success:!0,wait:n,reservoir:r.storeOptions.reservoir}):{success:!1}})()}strategyIsBlock(){return 3===this.storeOptions.strategy}__submit__(e,t){var n=this;return o(function*(){var i,s,o;if(yield n.yieldLoop(),null!=n.storeOptions.maxConcurrent&&t>n.storeOptions.maxConcurrent)throw new r(`Impossible to add a job having a weight of ${t} to a limiter having a maxConcurrent setting of ${n.storeOptions.maxConcurrent}`);return s=Date.now(),o=null!=n.storeOptions.highWater&&e===n.storeOptions.highWater&&!n.check(t,s),(i=n.strategyIsBlock()&&(o||n.isBlocked(s)))&&(n._unblockTime=s+n.computePenalty(),n._nextRequest=n._unblockTime+n.storeOptions.minTime,n.instance._dropAllQueued()),{reachedHWM:o,blocked:i,strategy:n.storeOptions.strategy}})()}__free__(e,t){var n=this;return o(function*(){return yield n.yieldLoop(),n._running-=t,n._done+=t,n.instance._drainAll(n.computeCapacity()),{running:n._running}})()}}},592324,e=>{e.v(JSON.parse("{\"blacklist_client.lua\":\"local blacklist = ARGV[num_static_argv + 1]\\n\\nif redis.call('zscore', client_last_seen_key, blacklist) then\\n redis.call('zadd', client_last_seen_key, 0, blacklist)\\nend\\n\\n\\nreturn {}\\n\",\"check.lua\":\"local weight = tonumber(ARGV[num_static_argv + 1])\\n\\nlocal capacity = process_tick(now, false)['capacity']\\nlocal nextRequest = tonumber(redis.call('hget', settings_key, 'nextRequest'))\\n\\nreturn conditions_check(capacity, weight) and nextRequest - now <= 0\\n\",\"conditions_check.lua\":\"local conditions_check = function (capacity, weight)\\n return capacity == nil or weight <= capacity\\nend\\n\",\"current_reservoir.lua\":\"return process_tick(now, false)['reservoir']\\n\",\"done.lua\":\"process_tick(now, false)\\n\\nreturn tonumber(redis.call('hget', settings_key, 'done'))\\n\",\"free.lua\":\"local index = ARGV[num_static_argv + 1]\\n\\nredis.call('zadd', job_expirations_key, 0, index)\\n\\nreturn process_tick(now, false)['running']\\n\",\"get_time.lua\":\"redis.replicate_commands()\\n\\nlocal get_time = function ()\\n local time = redis.call('time')\\n\\n return tonumber(time[1]..string.sub(time[2], 1, 3))\\nend\\n\",\"group_check.lua\":\"return not (redis.call('exists', settings_key) == 1)\\n\",\"heartbeat.lua\":\"process_tick(now, true)\\n\",\"increment_reservoir.lua\":\"local incr = tonumber(ARGV[num_static_argv + 1])\\n\\nredis.call('hincrby', settings_key, 'reservoir', incr)\\n\\nlocal reservoir = process_tick(now, true)['reservoir']\\n\\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\\nrefresh_expiration(0, 0, groupTimeout)\\n\\nreturn reservoir\\n\",\"init.lua\":\"local clear = tonumber(ARGV[num_static_argv + 1])\\nlocal limiter_version = ARGV[num_static_argv + 2]\\nlocal num_local_argv = num_static_argv + 2\\n\\nif clear == 1 then\\n redis.call('del', unpack(KEYS))\\nend\\n\\nif redis.call('exists', settings_key) == 0 then\\n -- Create\\n local args = {'hmset', settings_key}\\n\\n for i = num_local_argv + 1, #ARGV do\\n table.insert(args, ARGV[i])\\n end\\n\\n redis.call(unpack(args))\\n redis.call('hmset', settings_key,\\n 'nextRequest', now,\\n 'lastReservoirRefresh', now,\\n 'lastReservoirIncrease', now,\\n 'running', 0,\\n 'done', 0,\\n 'unblockTime', 0,\\n 'capacityPriorityCounter', 0\\n )\\n\\nelse\\n -- Apply migrations\\n local settings = redis.call('hmget', settings_key,\\n 'id',\\n 'version'\\n )\\n local id = settings[1]\\n local current_version = settings[2]\\n\\n if current_version ~= limiter_version then\\n local version_digits = {}\\n for k, v in string.gmatch(current_version, \\\"([^.]+)\\\") do\\n table.insert(version_digits, tonumber(k))\\n end\\n\\n -- 2.10.0\\n if version_digits[2] < 10 then\\n redis.call('hsetnx', settings_key, 'reservoirRefreshInterval', '')\\n redis.call('hsetnx', settings_key, 'reservoirRefreshAmount', '')\\n redis.call('hsetnx', settings_key, 'lastReservoirRefresh', '')\\n redis.call('hsetnx', settings_key, 'done', 0)\\n redis.call('hset', settings_key, 'version', '2.10.0')\\n end\\n\\n -- 2.11.1\\n if version_digits[2] < 11 or (version_digits[2] == 11 and version_digits[3] < 1) then\\n if redis.call('hstrlen', settings_key, 'lastReservoirRefresh') == 0 then\\n redis.call('hmset', settings_key,\\n 'lastReservoirRefresh', now,\\n 'version', '2.11.1'\\n )\\n end\\n end\\n\\n -- 2.14.0\\n if version_digits[2] < 14 then\\n local old_running_key = 'b_'..id..'_running'\\n local old_executing_key = 'b_'..id..'_executing'\\n\\n if redis.call('exists', old_running_key) == 1 then\\n redis.call('rename', old_running_key, job_weights_key)\\n end\\n if redis.call('exists', old_executing_key) == 1 then\\n redis.call('rename', old_executing_key, job_expirations_key)\\n end\\n redis.call('hset', settings_key, 'version', '2.14.0')\\n end\\n\\n -- 2.15.2\\n if version_digits[2] < 15 or (version_digits[2] == 15 and version_digits[3] < 2) then\\n redis.call('hsetnx', settings_key, 'capacityPriorityCounter', 0)\\n redis.call('hset', settings_key, 'version', '2.15.2')\\n end\\n\\n -- 2.17.0\\n if version_digits[2] < 17 then\\n redis.call('hsetnx', settings_key, 'clientTimeout', 10000)\\n redis.call('hset', settings_key, 'version', '2.17.0')\\n end\\n\\n -- 2.18.0\\n if version_digits[2] < 18 then\\n redis.call('hsetnx', settings_key, 'reservoirIncreaseInterval', '')\\n redis.call('hsetnx', settings_key, 'reservoirIncreaseAmount', '')\\n redis.call('hsetnx', settings_key, 'reservoirIncreaseMaximum', '')\\n redis.call('hsetnx', settings_key, 'lastReservoirIncrease', now)\\n redis.call('hset', settings_key, 'version', '2.18.0')\\n end\\n\\n end\\n\\n process_tick(now, false)\\nend\\n\\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\\nrefresh_expiration(0, 0, groupTimeout)\\n\\nreturn {}\\n\",\"process_tick.lua\":\"local process_tick = function (now, always_publish)\\n\\n local compute_capacity = function (maxConcurrent, running, reservoir)\\n if maxConcurrent ~= nil and reservoir ~= nil then\\n return math.min((maxConcurrent - running), reservoir)\\n elseif maxConcurrent ~= nil then\\n return maxConcurrent - running\\n elseif reservoir ~= nil then\\n return reservoir\\n else\\n return nil\\n end\\n end\\n\\n local settings = redis.call('hmget', settings_key,\\n 'id',\\n 'maxConcurrent',\\n 'running',\\n 'reservoir',\\n 'reservoirRefreshInterval',\\n 'reservoirRefreshAmount',\\n 'lastReservoirRefresh',\\n 'reservoirIncreaseInterval',\\n 'reservoirIncreaseAmount',\\n 'reservoirIncreaseMaximum',\\n 'lastReservoirIncrease',\\n 'capacityPriorityCounter',\\n 'clientTimeout'\\n )\\n local id = settings[1]\\n local maxConcurrent = tonumber(settings[2])\\n local running = tonumber(settings[3])\\n local reservoir = tonumber(settings[4])\\n local reservoirRefreshInterval = tonumber(settings[5])\\n local reservoirRefreshAmount = tonumber(settings[6])\\n local lastReservoirRefresh = tonumber(settings[7])\\n local reservoirIncreaseInterval = tonumber(settings[8])\\n local reservoirIncreaseAmount = tonumber(settings[9])\\n local reservoirIncreaseMaximum = tonumber(settings[10])\\n local lastReservoirIncrease = tonumber(settings[11])\\n local capacityPriorityCounter = tonumber(settings[12])\\n local clientTimeout = tonumber(settings[13])\\n\\n local initial_capacity = compute_capacity(maxConcurrent, running, reservoir)\\n\\n --\\n -- Process 'running' changes\\n --\\n local expired = redis.call('zrangebyscore', job_expirations_key, '-inf', '('..now)\\n\\n if #expired > 0 then\\n redis.call('zremrangebyscore', job_expirations_key, '-inf', '('..now)\\n\\n local flush_batch = function (batch, acc)\\n local weights = redis.call('hmget', job_weights_key, unpack(batch))\\n redis.call('hdel', job_weights_key, unpack(batch))\\n local clients = redis.call('hmget', job_clients_key, unpack(batch))\\n redis.call('hdel', job_clients_key, unpack(batch))\\n\\n -- Calculate sum of removed weights\\n for i = 1, #weights do\\n acc['total'] = acc['total'] + (tonumber(weights[i]) or 0)\\n end\\n\\n -- Calculate sum of removed weights by client\\n local client_weights = {}\\n for i = 1, #clients do\\n local removed = tonumber(weights[i]) or 0\\n if removed > 0 then\\n acc['client_weights'][clients[i]] = (acc['client_weights'][clients[i]] or 0) + removed\\n end\\n end\\n end\\n\\n local acc = {\\n ['total'] = 0,\\n ['client_weights'] = {}\\n }\\n local batch_size = 1000\\n\\n -- Compute changes to Zsets and apply changes to Hashes\\n for i = 1, #expired, batch_size do\\n local batch = {}\\n for j = i, math.min(i + batch_size - 1, #expired) do\\n table.insert(batch, expired[j])\\n end\\n\\n flush_batch(batch, acc)\\n end\\n\\n -- Apply changes to Zsets\\n if acc['total'] > 0 then\\n redis.call('hincrby', settings_key, 'done', acc['total'])\\n running = tonumber(redis.call('hincrby', settings_key, 'running', -acc['total']))\\n end\\n\\n for client, weight in pairs(acc['client_weights']) do\\n redis.call('zincrby', client_running_key, -weight, client)\\n end\\n end\\n\\n --\\n -- Process 'reservoir' changes\\n --\\n local reservoirRefreshActive = reservoirRefreshInterval ~= nil and reservoirRefreshAmount ~= nil\\n if reservoirRefreshActive and now >= lastReservoirRefresh + reservoirRefreshInterval then\\n reservoir = reservoirRefreshAmount\\n redis.call('hmset', settings_key,\\n 'reservoir', reservoir,\\n 'lastReservoirRefresh', now\\n )\\n end\\n\\n local reservoirIncreaseActive = reservoirIncreaseInterval ~= nil and reservoirIncreaseAmount ~= nil\\n if reservoirIncreaseActive and now >= lastReservoirIncrease + reservoirIncreaseInterval then\\n local num_intervals = math.floor((now - lastReservoirIncrease) / reservoirIncreaseInterval)\\n local incr = reservoirIncreaseAmount * num_intervals\\n if reservoirIncreaseMaximum ~= nil then\\n incr = math.min(incr, reservoirIncreaseMaximum - (reservoir or 0))\\n end\\n if incr > 0 then\\n reservoir = (reservoir or 0) + incr\\n end\\n redis.call('hmset', settings_key,\\n 'reservoir', reservoir,\\n 'lastReservoirIncrease', lastReservoirIncrease + (num_intervals * reservoirIncreaseInterval)\\n )\\n end\\n\\n --\\n -- Clear unresponsive clients\\n --\\n local unresponsive = redis.call('zrangebyscore', client_last_seen_key, '-inf', (now - clientTimeout))\\n local unresponsive_lookup = {}\\n local terminated_clients = {}\\n for i = 1, #unresponsive do\\n unresponsive_lookup[unresponsive[i]] = true\\n if tonumber(redis.call('zscore', client_running_key, unresponsive[i])) == 0 then\\n table.insert(terminated_clients, unresponsive[i])\\n end\\n end\\n if #terminated_clients > 0 then\\n redis.call('zrem', client_running_key, unpack(terminated_clients))\\n redis.call('hdel', client_num_queued_key, unpack(terminated_clients))\\n redis.call('zrem', client_last_registered_key, unpack(terminated_clients))\\n redis.call('zrem', client_last_seen_key, unpack(terminated_clients))\\n end\\n\\n --\\n -- Broadcast capacity changes\\n --\\n local final_capacity = compute_capacity(maxConcurrent, running, reservoir)\\n\\n if always_publish or (initial_capacity ~= nil and final_capacity == nil) then\\n -- always_publish or was not unlimited, now unlimited\\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\\n\\n elseif initial_capacity ~= nil and final_capacity ~= nil and final_capacity > initial_capacity then\\n -- capacity was increased\\n -- send the capacity message to the limiter having the lowest number of running jobs\\n -- the tiebreaker is the limiter having not registered a job in the longest time\\n\\n local lowest_concurrency_value = nil\\n local lowest_concurrency_clients = {}\\n local lowest_concurrency_last_registered = {}\\n local client_concurrencies = redis.call('zrange', client_running_key, 0, -1, 'withscores')\\n\\n for i = 1, #client_concurrencies, 2 do\\n local client = client_concurrencies[i]\\n local concurrency = tonumber(client_concurrencies[i+1])\\n\\n if (\\n lowest_concurrency_value == nil or lowest_concurrency_value == concurrency\\n ) and (\\n not unresponsive_lookup[client]\\n ) and (\\n tonumber(redis.call('hget', client_num_queued_key, client)) > 0\\n ) then\\n lowest_concurrency_value = concurrency\\n table.insert(lowest_concurrency_clients, client)\\n local last_registered = tonumber(redis.call('zscore', client_last_registered_key, client))\\n table.insert(lowest_concurrency_last_registered, last_registered)\\n end\\n end\\n\\n if #lowest_concurrency_clients > 0 then\\n local position = 1\\n local earliest = lowest_concurrency_last_registered[1]\\n\\n for i,v in ipairs(lowest_concurrency_last_registered) do\\n if v < earliest then\\n position = i\\n earliest = v\\n end\\n end\\n\\n local next_client = lowest_concurrency_clients[position]\\n redis.call('publish', 'b_'..id,\\n 'capacity-priority:'..(final_capacity or '')..\\n ':'..next_client..\\n ':'..capacityPriorityCounter\\n )\\n redis.call('hincrby', settings_key, 'capacityPriorityCounter', '1')\\n else\\n redis.call('publish', 'b_'..id, 'capacity:'..(final_capacity or ''))\\n end\\n end\\n\\n return {\\n ['capacity'] = final_capacity,\\n ['running'] = running,\\n ['reservoir'] = reservoir\\n }\\nend\\n\",\"queued.lua\":\"local clientTimeout = tonumber(redis.call('hget', settings_key, 'clientTimeout'))\\nlocal valid_clients = redis.call('zrangebyscore', client_last_seen_key, (now - clientTimeout), 'inf')\\nlocal client_queued = redis.call('hmget', client_num_queued_key, unpack(valid_clients))\\n\\nlocal sum = 0\\nfor i = 1, #client_queued do\\n sum = sum + tonumber(client_queued[i])\\nend\\n\\nreturn sum\\n\",\"refresh_expiration.lua\":\"local refresh_expiration = function (now, nextRequest, groupTimeout)\\n\\n if groupTimeout ~= nil then\\n local ttl = (nextRequest + groupTimeout) - now\\n\\n for i = 1, #KEYS do\\n redis.call('pexpire', KEYS[i], ttl)\\n end\\n end\\n\\nend\\n\",\"refs.lua\":\"local settings_key = KEYS[1]\\nlocal job_weights_key = KEYS[2]\\nlocal job_expirations_key = KEYS[3]\\nlocal job_clients_key = KEYS[4]\\nlocal client_running_key = KEYS[5]\\nlocal client_num_queued_key = KEYS[6]\\nlocal client_last_registered_key = KEYS[7]\\nlocal client_last_seen_key = KEYS[8]\\n\\nlocal now = tonumber(ARGV[1])\\nlocal client = ARGV[2]\\n\\nlocal num_static_argv = 2\\n\",\"register.lua\":\"local index = ARGV[num_static_argv + 1]\\nlocal weight = tonumber(ARGV[num_static_argv + 2])\\nlocal expiration = tonumber(ARGV[num_static_argv + 3])\\n\\nlocal state = process_tick(now, false)\\nlocal capacity = state['capacity']\\nlocal reservoir = state['reservoir']\\n\\nlocal settings = redis.call('hmget', settings_key,\\n 'nextRequest',\\n 'minTime',\\n 'groupTimeout'\\n)\\nlocal nextRequest = tonumber(settings[1])\\nlocal minTime = tonumber(settings[2])\\nlocal groupTimeout = tonumber(settings[3])\\n\\nif conditions_check(capacity, weight) then\\n\\n redis.call('hincrby', settings_key, 'running', weight)\\n redis.call('hset', job_weights_key, index, weight)\\n if expiration ~= nil then\\n redis.call('zadd', job_expirations_key, now + expiration, index)\\n end\\n redis.call('hset', job_clients_key, index, client)\\n redis.call('zincrby', client_running_key, weight, client)\\n redis.call('hincrby', client_num_queued_key, client, -1)\\n redis.call('zadd', client_last_registered_key, now, client)\\n\\n local wait = math.max(nextRequest - now, 0)\\n local newNextRequest = now + wait + minTime\\n\\n if reservoir == nil then\\n redis.call('hset', settings_key,\\n 'nextRequest', newNextRequest\\n )\\n else\\n reservoir = reservoir - weight\\n redis.call('hmset', settings_key,\\n 'reservoir', reservoir,\\n 'nextRequest', newNextRequest\\n )\\n end\\n\\n refresh_expiration(now, newNextRequest, groupTimeout)\\n\\n return {true, wait, reservoir}\\n\\nelse\\n return {false}\\nend\\n\",\"register_client.lua\":\"local queued = tonumber(ARGV[num_static_argv + 1])\\n\\n-- Could have been re-registered concurrently\\nif not redis.call('zscore', client_last_seen_key, client) then\\n redis.call('zadd', client_running_key, 0, client)\\n redis.call('hset', client_num_queued_key, client, queued)\\n redis.call('zadd', client_last_registered_key, 0, client)\\nend\\n\\nredis.call('zadd', client_last_seen_key, now, client)\\n\\nreturn {}\\n\",\"running.lua\":\"return process_tick(now, false)['running']\\n\",\"submit.lua\":\"local queueLength = tonumber(ARGV[num_static_argv + 1])\\nlocal weight = tonumber(ARGV[num_static_argv + 2])\\n\\nlocal capacity = process_tick(now, false)['capacity']\\n\\nlocal settings = redis.call('hmget', settings_key,\\n 'id',\\n 'maxConcurrent',\\n 'highWater',\\n 'nextRequest',\\n 'strategy',\\n 'unblockTime',\\n 'penalty',\\n 'minTime',\\n 'groupTimeout'\\n)\\nlocal id = settings[1]\\nlocal maxConcurrent = tonumber(settings[2])\\nlocal highWater = tonumber(settings[3])\\nlocal nextRequest = tonumber(settings[4])\\nlocal strategy = tonumber(settings[5])\\nlocal unblockTime = tonumber(settings[6])\\nlocal penalty = tonumber(settings[7])\\nlocal minTime = tonumber(settings[8])\\nlocal groupTimeout = tonumber(settings[9])\\n\\nif maxConcurrent ~= nil and weight > maxConcurrent then\\n return redis.error_reply('OVERWEIGHT:'..weight..':'..maxConcurrent)\\nend\\n\\nlocal reachedHWM = (highWater ~= nil and queueLength == highWater\\n and not (\\n conditions_check(capacity, weight)\\n and nextRequest - now <= 0\\n )\\n)\\n\\nlocal blocked = strategy == 3 and (reachedHWM or unblockTime >= now)\\n\\nif blocked then\\n local computedPenalty = penalty\\n if computedPenalty == nil then\\n if minTime == 0 then\\n computedPenalty = 5000\\n else\\n computedPenalty = 15 * minTime\\n end\\n end\\n\\n local newNextRequest = now + computedPenalty + minTime\\n\\n redis.call('hmset', settings_key,\\n 'unblockTime', now + computedPenalty,\\n 'nextRequest', newNextRequest\\n )\\n\\n local clients_queued_reset = redis.call('hkeys', client_num_queued_key)\\n local queued_reset = {}\\n for i = 1, #clients_queued_reset do\\n table.insert(queued_reset, clients_queued_reset[i])\\n table.insert(queued_reset, 0)\\n end\\n redis.call('hmset', client_num_queued_key, unpack(queued_reset))\\n\\n redis.call('publish', 'b_'..id, 'blocked:')\\n\\n refresh_expiration(now, newNextRequest, groupTimeout)\\nend\\n\\nif not blocked and not reachedHWM then\\n redis.call('hincrby', client_num_queued_key, client, 1)\\nend\\n\\nreturn {reachedHWM, blocked, strategy}\\n\",\"update_settings.lua\":\"local args = {'hmset', settings_key}\\n\\nfor i = num_static_argv + 1, #ARGV do\\n table.insert(args, ARGV[i])\\nend\\n\\nredis.call(unpack(args))\\n\\nprocess_tick(now, true)\\n\\nlocal groupTimeout = tonumber(redis.call('hget', settings_key, 'groupTimeout'))\\nrefresh_expiration(0, 0, groupTimeout)\\n\\nreturn {}\\n\",\"validate_client.lua\":\"if not redis.call('zscore', client_last_seen_key, client) then\\n return redis.error_reply('UNKNOWN_CLIENT')\\nend\\n\\nredis.call('zadd', client_last_seen_key, now, client)\\n\",\"validate_keys.lua\":\"if not (redis.call('exists', settings_key) == 1) then\\n return redis.error_reply('SETTINGS_KEY_NOT_FOUND')\\nend\\n\"}"))},964638,(e,t,n)=>{"use strict";var r,i,s;r={refs:(i=e.r(592324))["refs.lua"],validate_keys:i["validate_keys.lua"],validate_client:i["validate_client.lua"],refresh_expiration:i["refresh_expiration.lua"],process_tick:i["process_tick.lua"],conditions_check:i["conditions_check.lua"],get_time:i["get_time.lua"]},n.allKeys=function(e){return[`b_${e}_settings`,`b_${e}_job_weights`,`b_${e}_job_expirations`,`b_${e}_job_clients`,`b_${e}_client_running`,`b_${e}_client_num_queued`,`b_${e}_client_last_registered`,`b_${e}_client_last_seen`]},s={init:{keys:n.allKeys,headers:["process_tick"],refresh_expiration:!0,code:i["init.lua"]},group_check:{keys:n.allKeys,headers:[],refresh_expiration:!1,code:i["group_check.lua"]},register_client:{keys:n.allKeys,headers:["validate_keys"],refresh_expiration:!1,code:i["register_client.lua"]},blacklist_client:{keys:n.allKeys,headers:["validate_keys","validate_client"],refresh_expiration:!1,code:i["blacklist_client.lua"]},heartbeat:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:i["heartbeat.lua"]},update_settings:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:i["update_settings.lua"]},running:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:i["running.lua"]},queued:{keys:n.allKeys,headers:["validate_keys","validate_client"],refresh_expiration:!1,code:i["queued.lua"]},done:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:i["done.lua"]},check:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!1,code:i["check.lua"]},submit:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!0,code:i["submit.lua"]},register:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick","conditions_check"],refresh_expiration:!0,code:i["register.lua"]},free:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:i["free.lua"]},current_reservoir:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!1,code:i["current_reservoir.lua"]},increment_reservoir:{keys:n.allKeys,headers:["validate_keys","validate_client","process_tick"],refresh_expiration:!0,code:i["increment_reservoir.lua"]}},n.names=Object.keys(s),n.keys=function(e,t){return s[e].keys(t)},n.payload=function(e){var t;return t=s[e],Array.prototype.concat(r.refs,t.headers.map(function(e){return r[e]}),t.refresh_expiration?r.refresh_expiration:"",t.code).join("\n")}},489410,(__turbopack_context__,module,exports)=>{"use strict";var Events,RedisConnection,Scripts,parser;function asyncGeneratorStep(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep(s,r,i,o,a,"throw",e)}o(void 0)})}}parser=__turbopack_context__.r(150447),Events=__turbopack_context__.r(589243),Scripts=__turbopack_context__.r(964638),RedisConnection=(function(){class RedisConnection{constructor(options={}){parser.load(options,this.defaults,this),null==this.Redis&&(this.Redis=eval("require")("redis")),null==this.Events&&(this.Events=new Events(this)),this.terminated=!1,null==this.client&&(this.client=this.Redis.createClient(this.clientOptions)),this.subscriber=this.client.duplicate(),this.limiters={},this.shas={},this.ready=this.Promise.all([this._setup(this.client,!1),this._setup(this.subscriber,!0)]).then(()=>this._loadScripts()).then(()=>({client:this.client,subscriber:this.subscriber}))}_setup(e,t){return e.setMaxListeners(0),new this.Promise((n,r)=>(e.on("error",e=>this.Events.trigger("error",e)),t&&e.on("message",(e,t)=>{var n;return null!=(n=this.limiters[e])?n._store.onMessage(e,t):void 0}),e.ready)?n():e.once("ready",n))}_loadScript(e){return new this.Promise((t,n)=>{var r;return r=Scripts.payload(e),this.client.multi([["script","load",r]]).exec((r,i)=>null!=r?n(r):(this.shas[e]=i[0],t(i[0])))})}_loadScripts(){return this.Promise.all(Scripts.names.map(e=>this._loadScript(e)))}__runCommand__(e){var t=this;return _asyncToGenerator(function*(){return yield t.ready,new t.Promise((n,r)=>t.client.multi([e]).exec_atomic(function(e,t){return null!=e?r(e):n(t[0])}))})()}__addLimiter__(e){return this.Promise.all([e.channel(),e.channel_client()].map(t=>new this.Promise((n,r)=>{var i;return i=r=>{if(r===t)return this.subscriber.removeListener("subscribe",i),this.limiters[t]=e,n()},this.subscriber.on("subscribe",i),this.subscriber.subscribe(t)})))}__removeLimiter__(e){var t=this;return this.Promise.all([e.channel(),e.channel_client()].map(function(){var e=_asyncToGenerator(function*(e){return t.terminated||(yield new t.Promise((n,r)=>t.subscriber.unsubscribe(e,function(t,i){return null!=t?r(t):i===e?n():void 0}))),delete t.limiters[e]});return function(t){return e.apply(this,arguments)}}()))}__scriptArgs__(e,t,n,r){var i;return i=Scripts.keys(e,t),[this.shas[e],i.length].concat(i,n,r)}__scriptFn__(e){return this.client.evalsha.bind(this.client)}disconnect(e=!0){var t,n,r,i;for(t=0,r=(i=Object.keys(this.limiters)).length;t<r;t++)n=i[t],clearInterval(this.limiters[n]._store.heartbeat);return this.limiters={},this.terminated=!0,this.client.end(e),this.subscriber.end(e),this.Promise.resolve()}}return RedisConnection.prototype.datastore="redis",RedisConnection.prototype.defaults={Redis:null,clientOptions:{},client:null,Promise:Promise,Events:null},RedisConnection}).call(void 0),module.exports=RedisConnection},6827,(__turbopack_context__,module,exports)=>{"use strict";var Events,IORedisConnection,Scripts,parser;function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_nonIterableRest()}function _nonIterableRest(){throw TypeError("Invalid attempt to destructure non-iterable instance")}function _iterableToArrayLimit(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function _arrayWithHoles(e){if(Array.isArray(e))return e}function asyncGeneratorStep(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function _asyncToGenerator(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function o(e){asyncGeneratorStep(s,r,i,o,a,"next",e)}function a(e){asyncGeneratorStep(s,r,i,o,a,"throw",e)}o(void 0)})}}parser=__turbopack_context__.r(150447),Events=__turbopack_context__.r(589243),Scripts=__turbopack_context__.r(964638),IORedisConnection=(function(){class IORedisConnection{constructor(options={}){parser.load(options,this.defaults,this),null==this.Redis&&(this.Redis=eval("require")("ioredis")),null==this.Events&&(this.Events=new Events(this)),this.terminated=!1,null!=this.clusterNodes?(this.client=new this.Redis.Cluster(this.clusterNodes,this.clientOptions),this.subscriber=new this.Redis.Cluster(this.clusterNodes,this.clientOptions)):null!=this.client&&null==this.client.duplicate?this.subscriber=new this.Redis.Cluster(this.client.startupNodes,this.client.options):(null==this.client&&(this.client=new this.Redis(this.clientOptions)),this.subscriber=this.client.duplicate()),this.limiters={},this.ready=this.Promise.all([this._setup(this.client,!1),this._setup(this.subscriber,!0)]).then(()=>(this._loadScripts(),{client:this.client,subscriber:this.subscriber}))}_setup(e,t){return e.setMaxListeners(0),new this.Promise((n,r)=>(e.on("error",e=>this.Events.trigger("error",e)),t&&e.on("message",(e,t)=>{var n;return null!=(n=this.limiters[e])?n._store.onMessage(e,t):void 0}),"ready"===e.status)?n():e.once("ready",n))}_loadScripts(){return Scripts.names.forEach(e=>this.client.defineCommand(e,{lua:Scripts.payload(e)}))}__runCommand__(e){var t=this;return _asyncToGenerator(function*(){yield t.ready;var n,r=_slicedToArray((yield t.client.pipeline([e]).exec()),1),i=_slicedToArray(r[0],2);return n=i[0],i[1]})()}__addLimiter__(e){return this.Promise.all([e.channel(),e.channel_client()].map(t=>new this.Promise((n,r)=>this.subscriber.subscribe(t,()=>(this.limiters[t]=e,n())))))}__removeLimiter__(e){var t=this;return[e.channel(),e.channel_client()].forEach(function(){var e=_asyncToGenerator(function*(e){return t.terminated||(yield t.subscriber.unsubscribe(e)),delete t.limiters[e]});return function(t){return e.apply(this,arguments)}}())}__scriptArgs__(e,t,n,r){var i;return[(i=Scripts.keys(e,t)).length].concat(i,n,r)}__scriptFn__(e){return this.client[e].bind(this.client)}disconnect(e=!0){var t,n,r,i;for(t=0,r=(i=Object.keys(this.limiters)).length;t<r;t++)n=i[t],clearInterval(this.limiters[n]._store.heartbeat);return(this.limiters={},this.terminated=!0,e)?this.Promise.all([this.client.quit(),this.subscriber.quit()]):(this.client.disconnect(),this.subscriber.disconnect(),this.Promise.resolve())}}return IORedisConnection.prototype.datastore="ioredis",IORedisConnection.prototype.defaults={Redis:null,clientOptions:{},clusterNodes:null,client:null,Promise:Promise,Events:null},IORedisConnection}).call(void 0),module.exports=IORedisConnection},844112,(e,t,n)=>{"use strict";var r,i,s,o;function a(e,t){return u(e)||c(e,t)||l()}function l(){throw TypeError("Invalid attempt to destructure non-iterable instance")}function c(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function u(e){if(Array.isArray(e))return e}function h(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function d(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function o(e){h(s,r,i,o,a,"next",e)}function a(e){h(s,r,i,o,a,"throw",e)}o(void 0)})}}o=e.r(150447),r=e.r(938539),s=e.r(489410),i=e.r(6827),t.exports=class{constructor(e,t,n){this.instance=e,this.storeOptions=t,this.originalId=this.instance.id,this.clientId=this.instance._randomIndex(),o.load(n,n,this),this.clients={},this.capacityPriorityCounters={},this.sharedConnection=null!=this.connection,null==this.connection&&(this.connection="redis"===this.instance.datastore?new s({Redis:this.Redis,clientOptions:this.clientOptions,Promise:this.Promise,Events:this.instance.Events}):"ioredis"===this.instance.datastore?new i({Redis:this.Redis,clientOptions:this.clientOptions,clusterNodes:this.clusterNodes,Promise:this.Promise,Events:this.instance.Events}):void 0),this.instance.connection=this.connection,this.instance.datastore=this.connection.datastore,this.ready=this.connection.ready.then(e=>(this.clients=e,this.runScript("init",this.prepareInitSettings(this.clearDatastore)))).then(()=>this.connection.__addLimiter__(this.instance)).then(()=>this.runScript("register_client",[this.instance.queued()])).then(()=>{var e;return"function"==typeof(e=this.heartbeat=setInterval(()=>this.runScript("heartbeat",[]).catch(e=>this.instance.Events.trigger("error",e)),this.heartbeatInterval)).unref&&e.unref(),this.clients})}__publish__(e){var t=this;return d(function*(){return(yield t.ready).client.publish(t.instance.channel(),`message:${e.toString()}`)})()}onMessage(e,t){var n=this;return d(function*(){var e,r,i,s,o,l,c,u,h,_;try{c=t.indexOf(":");var p=[t.slice(0,c),t.slice(c+1)];if(_=p[0],i=p[1],"capacity"===_)return yield n.instance._drainAll(i.length>0?~~i:void 0);if("capacity-priority"===_){var v=i.split(":"),m=a(v,3);if(h=m[0],u=m[1],r=m[2],e=h.length>0?~~h:void 0,u===n.clientId)return s=yield n.instance._drainAll(e),l=null!=e?e-(s||0):"",yield n.clients.client.publish(n.instance.channel(),`capacity-priority:${l}::${r}`);if(""===u)return clearTimeout(n.capacityPriorityCounters[r]),delete n.capacityPriorityCounters[r],n.instance._drainAll(e);return n.capacityPriorityCounters[r]=setTimeout(d(function*(){var t;try{return delete n.capacityPriorityCounters[r],yield n.runScript("blacklist_client",[u]),yield n.instance._drainAll(e)}catch(e){return t=e,n.instance.Events.trigger("error",t)}}),1e3)}if("message"===_)return n.instance.Events.trigger("message",i);else if("blocked"===_)return yield n.instance._dropAllQueued()}catch(e){return o=e,n.instance.Events.trigger("error",o)}})()}__disconnect__(e){return(clearInterval(this.heartbeat),this.sharedConnection)?this.connection.__removeLimiter__(this.instance):this.connection.disconnect(e)}runScript(e,t){var n=this;return d(function*(){return"init"!==e&&"register_client"!==e&&(yield n.ready),new n.Promise((r,i)=>{var s,o;return s=[Date.now(),n.clientId].concat(t),n.instance.Events.trigger("debug",`Calling Redis script: ${e}.lua`,s),o=n.connection.__scriptArgs__(e,n.originalId,s,function(e,t){return null!=e?i(e):r(t)}),n.connection.__scriptFn__(e)(...o)}).catch(r=>{if("SETTINGS_KEY_NOT_FOUND"===r.message)if("heartbeat"===e)return n.Promise.resolve();else return n.runScript("init",n.prepareInitSettings(!1)).then(()=>n.runScript(e,t));return"UNKNOWN_CLIENT"===r.message?n.runScript("register_client",[n.instance.queued()]).then(()=>n.runScript(e,t)):n.Promise.reject(r)})})()}prepareArray(e){var t,n,r,i;for(t=0,r=[],n=e.length;t<n;t++)i=e[t],r.push(null!=i?i.toString():"");return r}prepareObject(e){var t,n,r;for(n in t=[],e)r=e[n],t.push(n,null!=r?r.toString():"");return t}prepareInitSettings(e){var t;return(t=this.prepareObject(Object.assign({},this.storeOptions,{id:this.originalId,version:this.instance.version,groupTimeout:this.timeout,clientTimeout:this.clientTimeout}))).unshift(+!!e,this.instance.version),t}convertBool(e){return!!e}__updateSettings__(e){var t=this;return d(function*(){return yield t.runScript("update_settings",t.prepareObject(e)),o.overwrite(e,e,t.storeOptions)})()}__running__(){return this.runScript("running",[])}__queued__(){return this.runScript("queued",[])}__done__(){return this.runScript("done",[])}__groupCheck__(){var e=this;return d(function*(){return e.convertBool((yield e.runScript("group_check",[])))})()}__incrementReservoir__(e){return this.runScript("increment_reservoir",[e])}__currentReservoir__(){return this.runScript("current_reservoir",[])}__check__(e){var t=this;return d(function*(){return t.convertBool((yield t.runScript("check",t.prepareArray([e]))))})()}__register__(e,t,n){var r=this;return d(function*(){var i,s,o,l=a((yield r.runScript("register",r.prepareArray([e,t,n]))),3);return s=l[0],o=l[1],i=l[2],{success:r.convertBool(s),wait:o,reservoir:i}})()}__submit__(e,t){var n=this;return d(function*(){var i,s,o,l,c,u;try{var h=yield n.runScript("submit",n.prepareArray([e,t])),d=a(h,3);return c=d[0],i=d[1],u=d[2],{reachedHWM:n.convertBool(c),blocked:n.convertBool(i),strategy:u}}catch(e){if(0===(s=e).message.indexOf("OVERWEIGHT")){var _=a(s.message.split(":"),3);throw l=_[0],t=_[1],o=_[2],new r(`Impossible to add a job having a weight of ${t} to a limiter having a maxConcurrent setting of ${o}`)}throw s}})()}__free__(e,t){var n=this;return d(function*(){return{running:yield n.runScript("free",n.prepareArray([e]))}})()}}},827551,(e,t,n)=>{"use strict";var r;r=e.r(938539),t.exports=class{constructor(e){this.status=e,this._jobs={},this.counts=this.status.map(function(){return 0})}next(e){var t,n;return(n=(t=this._jobs[e])+1,null!=t&&n<this.status.length)?(this.counts[t]--,this.counts[n]++,this._jobs[e]++):null!=t?(this.counts[t]--,delete this._jobs[e]):void 0}start(e){var t;return t=0,this._jobs[e]=t,this.counts[t]++}remove(e){var t;return null!=(t=this._jobs[e])&&(this.counts[t]--,delete this._jobs[e]),null!=t}jobStatus(e){var t;return null!=(t=this.status[this._jobs[e]])?t:null}statusJobs(e){var t,n,i,s;if(null==e)return Object.keys(this._jobs);if((n=this.status.indexOf(e))<0)throw new r(`status must be one of ${this.status.join(", ")}`);for(t in i=this._jobs,s=[],i)i[t]===n&&s.push(t);return s}statusCounts(){return this.counts.reduce((e,t,n)=>(e[this.status[n]]=t,e),{})}}},786110,(e,t,n)=>{"use strict";var r;function i(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function s(e){return function(){var t=this,n=arguments;return new Promise(function(r,s){var o=e.apply(t,n);function a(e){i(o,r,s,a,l,"next",e)}function l(e){i(o,r,s,a,l,"throw",e)}a(void 0)})}}r=e.r(818344),t.exports=class{constructor(e,t){this.schedule=this.schedule.bind(this),this.name=e,this.Promise=t,this._running=0,this._queue=new r}isEmpty(){return 0===this._queue.length}_tryToRun(){var e=this;return s(function*(){var t,n,r,i,o,a,l;if(e._running<1&&e._queue.length>0){e._running++;var c=e._queue.shift();return l=c.task,t=c.args,o=c.resolve,i=c.reject,n=yield s(function*(){try{return a=yield l(...t),function(){return o(a)}}catch(e){return r=e,function(){return i(r)}}})(),e._running--,e._tryToRun(),n()}})()}schedule(e,...t){var n,r,i;return i=r=null,n=new this.Promise(function(e,t){return i=e,r=t}),this._queue.push({task:e,args:t,resolve:i,reject:r}),this._tryToRun(),n}}},297549,e=>{e.v({version:"2.19.5"})},449670,(e,t,n)=>{"use strict";var r,i,s,o,a;function l(e,t){return h(e)||u(e,t)||c()}function c(){throw TypeError("Invalid attempt to destructure non-iterable instance")}function u(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function h(e){if(Array.isArray(e))return e}function d(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function _(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function o(e){d(s,r,i,o,a,"next",e)}function a(e){d(s,r,i,o,a,"throw",e)}o(void 0)})}}a=e.r(150447),r=e.r(589243),s=e.r(489410),i=e.r(6827),o=e.r(964638),t.exports=(function(){class t{constructor(t={}){this.deleteKey=this.deleteKey.bind(this),this.limiterOptions=t,a.load(this.limiterOptions,this.defaults,this),this.Events=new r(this),this.instances={},this.Bottleneck=e.r(579366),this._startAutoCleanup(),this.sharedConnection=null!=this.connection,null==this.connection&&("redis"===this.limiterOptions.datastore?this.connection=new s(Object.assign({},this.limiterOptions,{Events:this.Events})):"ioredis"===this.limiterOptions.datastore&&(this.connection=new i(Object.assign({},this.limiterOptions,{Events:this.Events}))))}key(e=""){var t;return null!=(t=this.instances[e])?t:(()=>{var t;return t=this.instances[e]=new this.Bottleneck(Object.assign(this.limiterOptions,{id:`${this.id}-${e}`,timeout:this.timeout,connection:this.connection})),this.Events.trigger("created",t,e),t})()}deleteKey(e=""){var t=this;return _(function*(){var n,r;return r=t.instances[e],t.connection&&(n=yield t.connection.__runCommand__(["del",...o.allKeys(`${t.id}-${e}`)])),null!=r&&(delete t.instances[e],yield r.disconnect()),null!=r||n>0})()}limiters(){var e,t,n,r;for(e in t=this.instances,n=[],t)r=t[e],n.push({key:e,limiter:r});return n}keys(){return Object.keys(this.instances)}clusterKeys(){var e=this;return _(function*(){var t,n,r,i,s,o,a,c,u;if(null==e.connection)return e.Promise.resolve(e.keys());for(o=[],t=null,u=`b_${e.id}-`.length,n=9;0!==t;){var h=l((yield e.connection.__runCommand__(["scan",null!=t?t:0,"match",`b_${e.id}-*_settings`,"count",1e4])),2);for(i=0,c=h[0],r=h[1],t=~~c,a=r.length;i<a;i++)s=r[i],o.push(s.slice(u,-n))}return o})()}_startAutoCleanup(){var e,t=this;return clearInterval(this.interval),"function"==typeof(e=this.interval=setInterval(_(function*(){var e,n,r,i,s,o;for(n in s=Date.now(),r=t.instances,i=[],r){o=r[n];try{(yield o._store.__groupCheck__(s))?i.push(t.deleteKey(n)):i.push(void 0)}catch(t){e=t,i.push(o.Events.trigger("error",e))}}return i}),this.timeout/2)).unref?e.unref():void 0}updateSettings(e={}){if(a.overwrite(e,this.defaults,this),a.overwrite(e,e,this.limiterOptions),null!=e.timeout)return this._startAutoCleanup()}disconnect(e=!0){var t;if(!this.sharedConnection)return null!=(t=this.connection)?t.disconnect(e):void 0}}return t.prototype.defaults={timeout:3e5,connection:null,Promise:Promise,id:"group-key"},t}).call(void 0)},212375,(e,t,n)=>{"use strict";var r,i;i=e.r(150447),r=e.r(589243),t.exports=(function(){class e{constructor(e={}){this.options=e,i.load(this.options,this.defaults,this),this.Events=new r(this),this._arr=[],this._resetPromise(),this._lastFlush=Date.now()}_resetPromise(){return this._promise=new this.Promise((e,t)=>this._resolve=e)}_flush(){return clearTimeout(this._timeout),this._lastFlush=Date.now(),this._resolve(),this.Events.trigger("batch",this._arr),this._arr=[],this._resetPromise()}add(e){var t;return this._arr.push(e),t=this._promise,this._arr.length===this.maxSize?this._flush():null!=this.maxTime&&1===this._arr.length&&(this._timeout=setTimeout(()=>this._flush(),this.maxTime)),t}}return e.prototype.defaults={maxTime:null,maxSize:null,Promise:Promise},e}).call(void 0)},579366,(e,t,n)=>{"use strict";function r(e,t){return l(e)||i(e,t)||o()}function i(e,t){var n=[],r=!0,i=!1,s=void 0;try{for(var o,a=e[Symbol.iterator]();!(r=(o=a.next()).done)&&(n.push(o.value),!t||n.length!==t);r=!0);}catch(e){i=!0,s=e}finally{try{r||null==a.return||a.return()}finally{if(i)throw s}}return n}function s(e){return l(e)||a(e)||o()}function o(){throw TypeError("Invalid attempt to destructure non-iterable instance")}function a(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}function l(e){if(Array.isArray(e))return e}function c(e,t,n,r,i,s,o){try{var a=e[s](o),l=a.value}catch(e){n(e);return}a.done?t(l):Promise.resolve(l).then(r,i)}function u(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var s=e.apply(t,n);function o(e){c(s,r,i,o,a,"next",e)}function a(e){c(s,r,i,o,a,"throw",e)}o(void 0)})}}var h,d,_,p,v,m,g,f,y,b,k=[].splice;v=10,h=5,b=e.r(150447),m=e.r(247595),_=e.r(62367),p=e.r(725648),g=e.r(844112),d=e.r(589243),f=e.r(827551),y=e.r(786110),t.exports=(function(){class t{constructor(e={},...n){var r,i;this._addToQueue=this._addToQueue.bind(this),this._validateOptions(e,n),b.load(e,this.instanceDefaults,this),this._queues=new m(v),this._scheduled={},this._states=new f(["RECEIVED","QUEUED","RUNNING","EXECUTING"].concat(this.trackDoneStatus?["DONE"]:[])),this._limiter=null,this.Events=new d(this),this._submitLock=new y("submit",this.Promise),this._registerLock=new y("register",this.Promise),i=b.load(e,this.storeDefaults,{}),this._store=(function(){if("redis"===this.datastore||"ioredis"===this.datastore||null!=this.connection)return new g(this,i,r=b.load(e,this.redisStoreDefaults,{}));if("local"===this.datastore)return new p(this,i,r=b.load(e,this.localStoreDefaults,{}));throw new t.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`)}).call(this),this._queues.on("leftzero",()=>{var e;return null!=(e=this._store.heartbeat)&&"function"==typeof e.ref?e.ref():void 0}),this._queues.on("zero",()=>{var e;return null!=(e=this._store.heartbeat)&&"function"==typeof e.unref?e.unref():void 0})}_validateOptions(e,n){if(null==e||"object"!=typeof e||0!==n.length)throw new t.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1.")}ready(){return this._store.ready}clients(){return this._store.clients}channel(){return`b_${this.id}`}channel_client(){return`b_${this.id}_${this._store.clientId}`}publish(e){return this._store.__publish__(e)}disconnect(e=!0){return this._store.__disconnect__(e)}chain(e){return this._limiter=e,this}queued(e){return this._queues.queued(e)}clusterQueued(){return this._store.__queued__()}empty(){return 0===this.queued()&&this._submitLock.isEmpty()}running(){return this._store.__running__()}done(){return this._store.__done__()}jobStatus(e){return this._states.jobStatus(e)}jobs(e){return this._states.statusJobs(e)}counts(){return this._states.statusCounts()}_randomIndex(){return Math.random().toString(36).slice(2)}check(e=1){return this._store.__check__(e)}_clearGlobalState(e){return null!=this._scheduled[e]&&(clearTimeout(this._scheduled[e].expiration),delete this._scheduled[e],!0)}_free(e,t,n,r){var i=this;return u(function*(){var t,s;try{if(s=(yield i._store.__free__(e,n.weight)).running,i.Events.trigger("debug",`Freed ${n.id}`,r),0===s&&i.empty())return i.Events.trigger("idle")}catch(e){return t=e,i.Events.trigger("error",t)}})()}_run(e,t,n){var r,i,s;return t.doRun(),r=this._clearGlobalState.bind(this,e),s=this._run.bind(this,e,t),i=this._free.bind(this,e,t),this._scheduled[e]={timeout:setTimeout(()=>t.doExecute(this._limiter,r,s,i),n),expiration:null!=t.options.expiration?setTimeout(function(){return t.doExpire(r,s,i)},n+t.options.expiration):void 0,job:t}}_drainOne(e){return this._registerLock.schedule(()=>{if(0===this.queued())return this.Promise.resolve(null);var t,n,r,i,s=this._queues.getFirst(),o=r=s.first();return(i=o.options,t=o.args,null!=e&&i.weight>e)?this.Promise.resolve(null):(this.Events.trigger("debug",`Draining ${i.id}`,{args:t,options:i}),n=this._randomIndex(),this._store.__register__(n,i.weight,i.expiration).then(({success:e,wait:o,reservoir:a})=>{var l;return(this.Events.trigger("debug",`Drained ${i.id}`,{success:e,args:t,options:i}),e)?(s.shift(),(l=this.empty())&&this.Events.trigger("empty"),0===a&&this.Events.trigger("depleted",l),this._run(n,r,o),this.Promise.resolve(i.weight)):this.Promise.resolve(null)}))})}_drainAll(e,t=0){return this._drainOne(e).then(n=>{var r;return null!=n?(r=null!=e?e-n:e,this._drainAll(r,t+n)):this.Promise.resolve(t)}).catch(e=>this.Events.trigger("error",e))}_dropAllQueued(e){return this._queues.shiftAll(function(t){return t.doDrop({message:e})})}stop(e={}){var n,r;return e=b.load(e,this.stopDefaults),r=e=>{var t;return t=()=>{var t;return(t=this._states.counts)[0]+t[1]+t[2]+t[3]===e},new this.Promise((e,n)=>t()?e():this.on("done",()=>{if(t())return this.removeAllListeners("done"),e()}))},n=e.dropWaitingJobs?(this._run=function(t,n){return n.doDrop({message:e.dropErrorMessage})},this._drainOne=()=>this.Promise.resolve(null),this._registerLock.schedule(()=>this._submitLock.schedule(()=>{var t,n,i;for(t in n=this._scheduled)i=n[t],"RUNNING"===this.jobStatus(i.job.options.id)&&(clearTimeout(i.timeout),clearTimeout(i.expiration),i.job.doDrop({message:e.dropErrorMessage}));return this._dropAllQueued(e.dropErrorMessage),r(0)}))):this.schedule({priority:v-1,weight:0},()=>r(1)),this._receive=function(n){return n._reject(new t.prototype.BottleneckError(e.enqueueErrorMessage))},this.stop=()=>this.Promise.reject(new t.prototype.BottleneckError("stop() has already been called")),n}_addToQueue(e){var n=this;return u(function*(){var r,i,s,o,a,l,c;r=e.args,o=e.options;try{var u=yield n._store.__submit__(n.queued(),o.weight);a=u.reachedHWM,i=u.blocked,c=u.strategy}catch(t){return s=t,n.Events.trigger("debug",`Could not queue ${o.id}`,{args:r,options:o,error:s}),e.doDrop({error:s}),!1}return i?(e.doDrop(),!0):a&&(null!=(l=c===t.prototype.strategy.LEAK?n._queues.shiftLastFrom(o.priority):c===t.prototype.strategy.OVERFLOW_PRIORITY?n._queues.shiftLastFrom(o.priority+1):c===t.prototype.strategy.OVERFLOW?e:void 0)&&l.doDrop(),null==l||c===t.prototype.strategy.OVERFLOW)?(null==l&&e.doDrop(),a):(e.doQueue(a,i),n._queues.push(e),yield n._drainAll(),a)})()}_receive(e){return null!=this._states.jobStatus(e.options.id)?(e._reject(new t.prototype.BottleneckError(`A job with the same id already exists (id=${e.options.id})`)),!1):(e.doReceive(),this._submitLock.schedule(this._addToQueue,e))}submit(...e){var t,n,i,o,a,l;return"function"==typeof e[0]?(n=(a=s(e))[0],e=a.slice(1),t=r(k.call(e,-1),1)[0],o=b.load({},this.jobDefaults)):(o=(l=s(e))[0],n=l[1],e=l.slice(2),t=r(k.call(e,-1),1)[0],o=b.load(o,this.jobDefaults)),(i=new _((...e)=>new this.Promise(function(t,r){return n(...e,function(...e){return(null!=e[0]?r:t)(e)})}),e,o,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise)).promise.then(function(e){return"function"==typeof t?t(...e):void 0}).catch(function(e){return Array.isArray(e)?"function"==typeof t?t(...e):void 0:"function"==typeof t?t(e):void 0}),this._receive(i)}schedule(...e){var t,n,r;if("function"==typeof e[0]){var i=s(e);r=i[0],e=i.slice(1),n={}}else{var o=s(e);n=o[0],r=o[1],e=o.slice(2)}return t=new _(r,e,n,this.jobDefaults,this.rejectOnDrop,this.Events,this._states,this.Promise),this._receive(t),t.promise}wrap(e){var t,n;return t=this.schedule.bind(this),(n=function(...n){return t(e.bind(this),...n)}).withOptions=function(n,...r){return t(n,e,...r)},n}updateSettings(e={}){var t=this;return u(function*(){return yield t._store.__updateSettings__(b.overwrite(e,t.storeDefaults)),b.overwrite(e,t.instanceDefaults,t),t})()}currentReservoir(){return this._store.__currentReservoir__()}incrementReservoir(e=0){return this._store.__incrementReservoir__(e)}}return t.default=t,t.Events=d,t.version=t.prototype.version=e.r(297549).version,t.strategy=t.prototype.strategy={LEAK:1,OVERFLOW:2,OVERFLOW_PRIORITY:4,BLOCK:3},t.BottleneckError=t.prototype.BottleneckError=e.r(938539),t.Group=t.prototype.Group=e.r(449670),t.RedisConnection=t.prototype.RedisConnection=e.r(489410),t.IORedisConnection=t.prototype.IORedisConnection=e.r(6827),t.Batcher=t.prototype.Batcher=e.r(212375),t.prototype.jobDefaults={priority:h,weight:1,expiration:null,id:"<no-id>"},t.prototype.storeDefaults={maxConcurrent:null,minTime:0,highWater:null,strategy:t.prototype.strategy.LEAK,penalty:null,reservoir:null,reservoirRefreshInterval:null,reservoirRefreshAmount:null,reservoirIncreaseInterval:null,reservoirIncreaseAmount:null,reservoirIncreaseMaximum:null},t.prototype.localStoreDefaults={Promise:Promise,timeout:null,heartbeatInterval:250},t.prototype.redisStoreDefaults={Promise:Promise,timeout:null,heartbeatInterval:5e3,clientTimeout:1e4,Redis:null,clientOptions:{},clusterNodes:null,clearDatastore:!1,connection:null},t.prototype.instanceDefaults={datastore:"local",connection:null,id:"<no-id>",rejectOnDrop:!0,trackDoneStatus:!1,Promise:Promise},t.prototype.stopDefaults={enqueueErrorMessage:"This limiter has been stopped and cannot accept new jobs.",dropWaitingJobs:!0,dropErrorMessage:"This limiter has been stopped."},t}).call(void 0)},944883,(e,t,n)=>{"use strict";t.exports=e.r(579366)},20870,e=>{"use strict";var t=e.i(944883),n=e.i(441637),r=e.i(828059),i=e.i(16023);function s(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}function o(e,t=0){let n="number"==typeof e?e:"string"==typeof e&&e.trim().length>0?Number(e):NaN;return Number.isFinite(n)?n:t}let a=new Map,l=new Set,c={},u=null,h=6e4,d=!1,_=parseInt(process.env.RATE_LIMIT_MAX_WAIT_MS||"120000",10),p={maxConcurrent:10,minTime:0,reservoir:null,reservoirRefreshAmount:null,reservoirRefreshInterval:null,maxWait:_};async function v(){if(!d){d=!0;try{let{getProviderConnections:n}=await e.A(605589),c=await n(),u=0,h=0,d=0;for(let e of c){let n=s(e),c="string"==typeof n.id?n.id:"",p="string"==typeof n.provider?n.provider:"",v=!0===n.isActive,m=!0===n.rateLimitProtection,g=o(n.customRpm,0),f=o(n.customTpm,0);if(c&&p){if(g>0||f>0){l.add(c),d++;let e=`${p}:${c}`,n=g>0?g:i.DEFAULT_API_LIMITS.requestsPerMinute,r=Math.max(0,Math.floor(6e4/n)-10);a.has(e)||a.set(e,new t.default({maxConcurrent:i.DEFAULT_API_LIMITS.concurrentRequests,minTime:r,reservoir:n,reservoirRefreshAmount:n,reservoirRefreshInterval:6e4,maxWait:_,id:e}))}else if(m)l.add(c),u++;else if("apikey"===(0,r.getProviderCategory)(p)&&v){l.add(c),h++;let e=`${p}:${c}`;a.has(e)||a.set(e,new t.default({maxConcurrent:i.DEFAULT_API_LIMITS.concurrentRequests,minTime:i.DEFAULT_API_LIMITS.minTimeBetweenRequests,reservoir:i.DEFAULT_API_LIMITS.requestsPerMinute,reservoirRefreshAmount:i.DEFAULT_API_LIMITS.requestsPerMinute,reservoirRefreshInterval:6e4,maxWait:_,id:e}))}}}(u>0||h>0||d>0)&&console.log(`🛡️ [RATE-LIMIT] Loaded ${u} explicit + ${h} auto-enabled + ${d} custom rpm/tpm protection(s)`),await P()}catch(e){console.error("[RATE-LIMIT] Failed to load settings:",e.message)}}}function m(e){l.add(e)}function g(e){for(let[t]of(l.delete(e),a))if(t.includes(e)){let e=a.get(t);e?.disconnect(),a.delete(t)}}function f(e){return l.has(e)}function y(e,n,r=null){let i=r?`${e}:${n}:${r}`:`${e}:${n}`;if(!a.has(i)){let e=new t.default({...p,id:i});e.on("queued",()=>{let t=e.counts();t.QUEUED>0&&console.log(`⏳ [RATE-LIMIT] ${i} — ${t.QUEUED} request(s) queued, ${t.RUNNING} running`)}),a.set(i,e)}return a.get(i)}async function b(e,t,n,r){return l.has(t)?y(e,t,null).schedule(r):r()}let k={limit:"x-ratelimit-limit-requests",remaining:"x-ratelimit-remaining-requests",reset:"x-ratelimit-reset-requests",limitTokens:"x-ratelimit-limit-tokens",remainingTokens:"x-ratelimit-remaining-tokens",resetTokens:"x-ratelimit-reset-tokens",retryAfter:"retry-after",overLimit:"x-ratelimit-over-limit"},w={limit:"anthropic-ratelimit-requests-limit",remaining:"anthropic-ratelimit-requests-remaining",reset:"anthropic-ratelimit-requests-reset",limitTokens:"anthropic-ratelimit-input-tokens-limit",remainingTokens:"anthropic-ratelimit-input-tokens-remaining",resetTokens:"anthropic-ratelimit-input-tokens-reset",retryAfter:"retry-after"};function x(e){if(!e)return null;let t=e.match(/^(?:(\d+)h)?(?:(\d+)m(?!s))?(?:(\d+)s)?(?:(\d+)ms)?$/);if(t){let[,e,n,r,i]=t;return(3600*parseInt(e||0)+60*parseInt(n||0)+parseInt(r||0))*1e3+parseInt(i||0)}let n=parseFloat(e);if(!isNaN(n)&&n>0)return n>17e8?Math.max(0,1e3*n-Date.now()):1e3*n;try{let t=new Date(e);if(!isNaN(t.getTime()))return Math.max(0,t.getTime()-Date.now())}catch{}return null}function R(e,t,n,r,i=null){if(!l.has(t)||!n)return;let s=y(e,t,null),o="claude"===e||"anthropic"===e?w:k,c=e=>"function"==typeof n.get?n.get(e):n[e]||null,u=parseInt(c(o.limit)),h=parseInt(c(o.remaining)),d=c(o.reset),_=c(o.retryAfter),p=c(k.overLimit);if(429===r){let n=x(_)||6e4,r=s.counts(),i=`${e}:${t}`;console.log(`🚫 [RATE-LIMIT] ${e}:${t.slice(0,8)} — 429 received, pausing for ${Math.ceil(n/1e3)}s, dropping ${r.QUEUED} queued request(s)`),s.stop({dropWaitingJobs:!0}).finally(()=>{a.delete(i)});return}if("yes"===p){console.log(`⚠️ [RATE-LIMIT] ${e}:${t.slice(0,8)} — near capacity, slowing down`),s.updateSettings({minTime:200});return}if(!isNaN(u)&&u>0){let n=x(d)||6e4,r={minTime:Math.max(0,Math.floor(6e4/u)-10)};!isNaN(h)&&(h<.1*u?(r.reservoir=h,r.reservoirRefreshAmount=u,r.reservoirRefreshInterval=n,console.log(`⚠️ [RATE-LIMIT] ${e}:${t.slice(0,8)} — ${h}/${u} remaining, throttling`)):h>.5*u&&(r.minTime=0,r.reservoir=null,r.reservoirRefreshAmount=null,r.reservoirRefreshInterval=null)),s.updateSettings(r),A(e,t,{limit:u,remaining:h,minTime:r.minTime})}}function I(e,t){let n=`${e}:${t}`,r=a.get(n);if(!r)return{enabled:l.has(t),active:!1,queued:0,running:0};let i=r.counts();return{enabled:l.has(t),active:!0,queued:i.QUEUED||0,running:i.RUNNING||0,executing:i.EXECUTING||0,done:i.DONE||0}}function E(){let e={};for(let[t,n]of a){let r=n.counts();e[t]={queued:r.QUEUED||0,running:r.RUNNING||0,executing:r.EXECUTING||0}}return e}function T(){return{...c}}function A(t,n,r){c[`${t}:${n}`]={...r,provider:t,connectionId:n,lastUpdated:Date.now()},u||(u=setTimeout(async()=>{u=null;try{let{updateSettings:t}=await e.A(606102);await t({learnedRateLimits:JSON.stringify(c)}),console.log(`💾 [RATE-LIMIT] Persisted learned limits for ${Object.keys(c).length} provider(s)`)}catch(e){console.error("[RATE-LIMIT] Failed to persist learned limits:",e.message)}},h))}async function P(){try{let{getSettings:t}=await e.A(606102),n=await t(),r=n?.learnedRateLimits;if("string"!=typeof r||0===r.trim().length)return;let i=s(JSON.parse(r)),u=0;for(let[e,t]of Object.entries(i)){let n=s(t),r=o(n.lastUpdated,0);if(r>0&&Date.now()-r>864e5)continue;let i="string"==typeof n.connectionId?n.connectionId:"",h="string"==typeof n.provider?n.provider:"",d=o(n.limit,0),_=o(n.remaining,0),p=o(n.minTime,0);if(c[e]={provider:h,connectionId:i,lastUpdated:r,...d>0?{limit:d}:{},..._>=0?{remaining:_}:{},...p>=0?{minTime:p}:{}},i&&l.has(i)){let t=a.get(e);if(t&&d>0){let e=p||Math.max(0,Math.floor(6e4/d)-10);t.updateSettings({minTime:e}),u++}}}u>0&&console.log(`📥 [RATE-LIMIT] Restored ${u} learned rate limit(s) from persistence`)}catch(e){console.error("[RATE-LIMIT] Failed to load persisted limits:",e.message)}}function O(e,t,r,i,s=null){if(!l.has(t))return;let{retryAfterMs:o,reason:a}=(0,n.parseRetryAfterFromBody)(r);if(o&&o>0){let r=y(e,t,null);console.log(`🚫 [RATE-LIMIT] ${e}:${t.slice(0,8)} — body-parsed retry: ${Math.ceil(o/1e3)}s (${a})`),r.updateSettings({reservoir:0,reservoirRefreshAmount:60,reservoirRefreshInterval:o}),s&&(0,n.lockModel)(e,t,s,a,o)}}e.s(["disableRateLimitProtection",()=>g,"enableRateLimitProtection",()=>m,"getAllRateLimitStatus",()=>E,"getLearnedLimits",()=>T,"getRateLimitStatus",()=>I,"initializeRateLimits",()=>v,"isRateLimitEnabled",()=>f,"updateFromHeaders",()=>R,"updateFromResponseBody",()=>O,"withRateLimit",()=>b])}];
2
2
 
3
3
  //# sourceMappingURL=_5677b5e2._.js.map
@@ -1,3 +1,3 @@
1
- module.exports=[114902,e=>e.a(async(t,a)=>{try{var r=e.i(745015),n=e.i(89171),i=e.i(924868),o=e.i(814747),s=e.i(446786),l=e.i(266240),u=e.i(841788),d=e.i(197892),c=e.i(676088),p=e.i(200392),f=e.i(195975),h=t([c,p]);[c,p]=h.then?(await h)():h;let w=o.default.join(s.default.homedir(),".local","share","kilo"),y=o.default.join(w,"auth.json");o.default.join(s.default.homedir(),".config","kilo");let v=async()=>{try{let e=await i.default.readFile(y,"utf-8");return JSON.parse(e)}catch(e){if("ENOENT"===e.code)return null;throw e}};async function m(){try{let e=await (0,l.getCliRuntimeStatus)("kilo");if(!e.installed||!e.runnable)return n.NextResponse.json({installed:e.installed,runnable:e.runnable,command:e.command,commandPath:e.commandPath,runtimeMode:e.runtimeMode,reason:e.reason,settings:null,message:e.installed&&!e.runnable?"Kilo Code CLI is installed but not runnable":"Kilo Code CLI is not installed"});let t=await v(),a=null;try{let e=o.default.join(s.default.homedir(),".config","Code","User","settings.json"),t=await i.default.readFile(e,"utf-8"),r=JSON.parse(t);for(let[e,t]of(a={},Object.entries(r)))(e.startsWith("kilocode.")||e.startsWith("kilo-code.")||e.startsWith("kilo."))&&(a[e]=t)}catch{}return n.NextResponse.json({installed:e.installed,runnable:e.runnable,command:e.command,commandPath:e.commandPath,runtimeMode:e.runtimeMode,reason:e.reason,settings:{auth:t?Object.keys(t):[],extensionSettings:a},hasOmniRoute:(e=>{if(!e)return!1;let t=e["openai-compatible"]||e.omniroute;if(!t)return!1;let a=t.baseUrl||t.baseURL||"";return a.includes("localhost")||a.includes("127.0.0.1")||a.includes("omniroute")})(t),authPath:y})}catch(e){return console.log("Error checking kilo settings:",e),n.NextResponse.json({error:"Failed to check kilo settings"},{status:500})}}async function g(e){let t;try{t=await e.json()}catch{return n.NextResponse.json({error:{message:"Invalid request",details:[{field:"body",message:"Invalid JSON body"}]}},{status:400})}try{let e=(0,l.ensureCliConfigWriteAllowed)();if(e)return n.NextResponse.json({error:e},{status:403});let a=(0,p.validateBody)(c.cliModelConfigSchema,t);if((0,p.isValidationFailure)(a))return n.NextResponse.json({error:a.error},{status:400});let{baseUrl:r,apiKey:f,model:h}=a.data;await i.default.mkdir(w,{recursive:!0}),await (0,u.createBackup)("kilo",y);let m={};try{let e=await i.default.readFile(y,"utf-8");m=JSON.parse(e)}catch{}let g=r.endsWith("/v1")?r:`${r}/v1`;m["openai-compatible"]={type:"api-key",apiKey:f||"sk_omniroute",baseUrl:g,model:h},await i.default.writeFile(y,JSON.stringify(m,null,2));try{let e=o.default.join(s.default.homedir(),".config","Code","User","settings.json"),t={};try{let a=await i.default.readFile(e,"utf-8");t=JSON.parse(a)}catch{}t["kilocode.customProvider"]={name:"OmniRoute",baseURL:g,apiKey:f||"sk_omniroute"},t["kilocode.defaultModel"]=h,await i.default.writeFile(e,JSON.stringify(t,null,2))}catch{}try{(0,d.saveCliToolLastConfigured)("kilo")}catch{}return n.NextResponse.json({success:!0,message:"Kilo Code settings applied successfully!",authPath:y})}catch(e){return console.log("Error updating kilo settings:",e),n.NextResponse.json({error:"Failed to update kilo settings"},{status:500})}}async function R(){try{let e=(0,l.ensureCliConfigWriteAllowed)();if(e)return n.NextResponse.json({error:e},{status:403});await (0,u.createBackup)("kilo",y);let t={};try{let e=await i.default.readFile(y,"utf-8");t=JSON.parse(e)}catch(e){if("ENOENT"===e.code)return n.NextResponse.json({success:!0,message:"No settings file to reset"});throw e}delete t["openai-compatible"],delete t.omniroute,await i.default.writeFile(y,JSON.stringify(t,null,2));try{let e=o.default.join(s.default.homedir(),".config","Code","User","settings.json"),t=await i.default.readFile(e,"utf-8"),a=JSON.parse(t);delete a["kilocode.customProvider"],delete a["kilocode.defaultModel"],await i.default.writeFile(e,JSON.stringify(a,null,2))}catch{}try{(0,d.deleteCliToolLastConfigured)("kilo")}catch{}return n.NextResponse.json({success:!0,message:"OmniRoute settings removed from Kilo Code"})}catch(e){return console.log("Error resetting kilo settings:",e),n.NextResponse.json({error:"Failed to reset kilo settings"},{status:500})}}(0,f.ensureServerEntryExports)([m,g,R]),(0,r.registerServerReference)(m,"004471e62174b53fec620b7e18d51f30657b390dcf",null),(0,r.registerServerReference)(g,"40623df8c4f502e33f9c5137500302c55265c858bf",null),(0,r.registerServerReference)(R,"0010577e26fbfd30992884a12e41eeba4d5a3655bc",null),e.s(["DELETE",()=>R,"GET",()=>m,"POST",()=>g]),a()}catch(e){a(e)}},!1),472224,e=>e.a(async(t,a)=>{try{var r=e.i(747909),n=e.i(174017),i=e.i(996250),o=e.i(759756),s=e.i(561916),l=e.i(174677),u=e.i(869741),d=e.i(316795),c=e.i(487718),p=e.i(995169),f=e.i(47587),h=e.i(666012),m=e.i(570101),g=e.i(626937),R=e.i(10372),w=e.i(193695);e.i(52474);var y=e.i(600220),v=e.i(114902),C=t([v]);[v]=C.then?(await C)():C;let b=new r.AppRouteRouteModule({definition:{kind:n.RouteKind.APP_ROUTE,page:"/api/cli-tools/kilo-settings/route",pathname:"/api/cli-tools/kilo-settings",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/src/app/api/cli-tools/kilo-settings/route.ts",nextConfigOutput:"standalone",userland:v}),{workAsyncStorage:k,workUnitAsyncStorage:x,serverHooks:O}=b;function E(){return(0,i.patchFetch)({workAsyncStorage:k,workUnitAsyncStorage:x})}async function N(e,t,a){b.isDev&&(0,o.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let r="/api/cli-tools/kilo-settings/route";r=r.replace(/\/index$/,"")||"/";let i=await b.prepare(e,t,{srcPage:r,multiZoneDraftMode:!1});if(!i)return t.statusCode=400,t.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve()),null;let{buildId:v,params:C,nextConfig:E,parsedUrl:N,isDraftMode:k,prerenderManifest:x,routerServerContext:O,isOnDemandRevalidate:S,revalidateOnlyGenerated:j,resolvedPathname:P,clientReferenceManifest:A,serverActionsManifest:T}=i,U=(0,u.normalizeAppPath)(r),F=!!(x.dynamicRoutes[U]||x.routes[P]),_=async()=>((null==O?void 0:O.render404)?await O.render404(e,t,N,!1):t.end("This page could not be found"),null);if(F&&!k){let e=!!x.routes[P],t=x.dynamicRoutes[U];if(t&&!1===t.fallback&&!e){if(E.experimental.adapterPath)return await _();throw new w.NoFallbackError}}let I=null;!F||b.isDev||k||(I=P,I="/index"===I?"/":I);let M=!0===b.isDev||!F,H=F&&!M;T&&A&&(0,l.setManifestsSingleton)({page:r,clientReferenceManifest:A,serverActionsManifest:T});let q=e.method||"GET",D=(0,s.getTracer)(),K=D.getActiveScopeSpan(),L={params:C,prerenderManifest:x,renderOpts:{experimental:{authInterrupts:!!E.experimental.authInterrupts},cacheComponents:!!E.cacheComponents,supportsDynamicResponse:M,incrementalCache:(0,o.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:E.cacheLife,waitUntil:a.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,a,r,n)=>b.onRequestError(e,t,r,n,O)},sharedContext:{buildId:v}},J=new d.NodeNextRequest(e),$=new d.NodeNextResponse(t),B=c.NextRequestAdapter.fromNodeNextRequest(J,(0,c.signalFromNodeResponse)(t));try{let i=async e=>b.handle(B,L).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let a=D.getRootSpanAttributes();if(!a)return;if(a.get("next.span_type")!==p.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${a.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let n=a.get("next.route");if(n){let t=`${q} ${n}`;e.setAttributes({"next.route":n,"http.route":n,"next.span_name":t}),e.updateName(t)}else e.updateName(`${q} ${r}`)}),l=!!(0,o.getRequestMeta)(e,"minimalMode"),u=async o=>{var s,u;let d=async({previousCacheEntry:n})=>{try{if(!l&&S&&j&&!n)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let r=await i(o);e.fetchMetrics=L.renderOpts.fetchMetrics;let s=L.renderOpts.pendingWaitUntil;s&&a.waitUntil&&(a.waitUntil(s),s=void 0);let u=L.renderOpts.collectedTags;if(!F)return await (0,h.sendResponse)(J,$,r,L.renderOpts.pendingWaitUntil),null;{let e=await r.blob(),t=(0,m.toNodeOutgoingHttpHeaders)(r.headers);u&&(t[R.NEXT_CACHE_TAGS_HEADER]=u),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let a=void 0!==L.renderOpts.collectedRevalidate&&!(L.renderOpts.collectedRevalidate>=R.INFINITE_CACHE)&&L.renderOpts.collectedRevalidate,n=void 0===L.renderOpts.collectedExpire||L.renderOpts.collectedExpire>=R.INFINITE_CACHE?void 0:L.renderOpts.collectedExpire;return{value:{kind:y.CachedRouteKind.APP_ROUTE,status:r.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:a,expire:n}}}}catch(t){throw(null==n?void 0:n.isStale)&&await b.onRequestError(e,t,{routerKind:"App Router",routePath:r,routeType:"route",revalidateReason:(0,f.getRevalidateReason)({isStaticGeneration:H,isOnDemandRevalidate:S})},!1,O),t}},c=await b.handleResponse({req:e,nextConfig:E,cacheKey:I,routeKind:n.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:x,isRoutePPREnabled:!1,isOnDemandRevalidate:S,revalidateOnlyGenerated:j,responseGenerator:d,waitUntil:a.waitUntil,isMinimalMode:l});if(!F)return null;if((null==c||null==(s=c.value)?void 0:s.kind)!==y.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==c||null==(u=c.value)?void 0:u.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});l||t.setHeader("x-nextjs-cache",S?"REVALIDATED":c.isMiss?"MISS":c.isStale?"STALE":"HIT"),k&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let p=(0,m.fromNodeOutgoingHttpHeaders)(c.value.headers);return l&&F||p.delete(R.NEXT_CACHE_TAGS_HEADER),!c.cacheControl||t.getHeader("Cache-Control")||p.get("Cache-Control")||p.set("Cache-Control",(0,g.getCacheControlHeader)(c.cacheControl)),await (0,h.sendResponse)(J,$,new Response(c.value.body,{headers:p,status:c.value.status||200})),null};K?await u(K):await D.withPropagatedContext(e.headers,()=>D.trace(p.BaseServerSpan.handleRequest,{spanName:`${q} ${r}`,kind:s.SpanKind.SERVER,attributes:{"http.method":q,"http.target":e.url}},u))}catch(t){if(t instanceof w.NoFallbackError||await b.onRequestError(e,t,{routerKind:"App Router",routePath:U,routeType:"route",revalidateReason:(0,f.getRevalidateReason)({isStaticGeneration:H,isOnDemandRevalidate:S})},!1,O),F)throw t;return await (0,h.sendResponse)(J,$,new Response(null,{status:500})),null}}e.s(["handler",()=>N,"patchFetch",()=>E,"routeModule",()=>b,"serverHooks",()=>O,"workAsyncStorage",()=>k,"workUnitAsyncStorage",()=>x]),a()}catch(e){a(e)}},!1)];
1
+ module.exports=[114902,e=>e.a(async(t,a)=>{try{var r=e.i(745015),n=e.i(89171),i=e.i(924868),o=e.i(814747),s=e.i(446786),l=e.i(266240),u=e.i(841788),d=e.i(197892),c=e.i(676088),p=e.i(200392),f=e.i(195975),h=t([c,p]);[c,p]=h.then?(await h)():h;let w=o.default.join(s.default.homedir(),".local","share","kilo"),y=o.default.join(w,"auth.json");o.default.join(s.default.homedir(),".config","kilo");let v=async()=>{try{let e=await i.default.readFile(y,"utf-8");return JSON.parse(e)}catch(e){if("ENOENT"===e.code)return null;throw e}};async function m(){try{let e=await (0,l.getCliRuntimeStatus)("kilo");if(!e.installed||!e.runnable)return n.NextResponse.json({installed:e.installed,runnable:e.runnable,command:e.command,commandPath:e.commandPath,runtimeMode:e.runtimeMode,reason:e.reason,settings:null,message:e.installed&&!e.runnable?"Kilo Code CLI is installed but not runnable":"Kilo Code CLI is not installed"});let t=await v(),a=null;try{let e=o.default.join(s.default.homedir(),".config","Code","User","settings.json"),t=await i.default.readFile(e,"utf-8"),r=JSON.parse(t);for(let[e,t]of(a={},Object.entries(r)))(e.startsWith("kilocode.")||e.startsWith("kilo-code.")||e.startsWith("kilo."))&&(a[e]=t)}catch{}return n.NextResponse.json({installed:e.installed,runnable:e.runnable,command:e.command,commandPath:e.commandPath,runtimeMode:e.runtimeMode,reason:e.reason,settings:{auth:t?Object.keys(t):[],extensionSettings:a},hasOmniRoute:(e=>{if(!e)return!1;let t=e["openai-compatible"]||e.omniroute;if(!t)return!1;let a=t.baseUrl||t.baseURL||"";return a.includes("localhost")||a.includes("127.0.0.1")||a.includes("omniroute")})(t),authPath:y})}catch(e){return console.log("Error checking kilo settings:",e),n.NextResponse.json({error:"Failed to check kilo settings"},{status:500})}}async function g(e){let t;try{t=await e.json()}catch{return n.NextResponse.json({error:{message:"Invalid request",details:[{field:"body",message:"Invalid JSON body"}]}},{status:400})}try{let e=(0,l.ensureCliConfigWriteAllowed)();if(e)return n.NextResponse.json({error:e},{status:403});let a=(0,p.validateBody)(c.cliModelConfigSchema,t);if((0,p.isValidationFailure)(a))return n.NextResponse.json({error:a.error},{status:400});let{baseUrl:r,apiKey:f,model:h}=a.data;await i.default.mkdir(w,{recursive:!0}),await (0,u.createBackup)("kilo",y);let m={};try{let e=await i.default.readFile(y,"utf-8");m=JSON.parse(e)}catch{}let g=r.endsWith("/v1")?r:`${r}/v1`;m["openai-compatible"]={type:"api-key",apiKey:f||"sk_omniroute",baseUrl:g,model:h},await i.default.writeFile(y,JSON.stringify(m,null,2));try{let e=o.default.join(s.default.homedir(),".config","Code","User","settings.json"),t={};try{let a=await i.default.readFile(e,"utf-8");t=JSON.parse(a)}catch{}t["kilocode.customProvider"]={name:"OmniRoute",baseURL:g,apiKey:f||"sk_omniroute"},t["kilocode.defaultModel"]=h,await i.default.writeFile(e,JSON.stringify(t,null,2))}catch{}try{(0,d.saveCliToolLastConfigured)("kilo")}catch{}return n.NextResponse.json({success:!0,message:"Kilo Code settings applied successfully!",authPath:y})}catch(e){return console.log("Error updating kilo settings:",e),n.NextResponse.json({error:"Failed to update kilo settings"},{status:500})}}async function R(){try{let e=(0,l.ensureCliConfigWriteAllowed)();if(e)return n.NextResponse.json({error:e},{status:403});await (0,u.createBackup)("kilo",y);let t={};try{let e=await i.default.readFile(y,"utf-8");t=JSON.parse(e)}catch(e){if("ENOENT"===e.code)return n.NextResponse.json({success:!0,message:"No settings file to reset"});throw e}delete t["openai-compatible"],delete t.omniroute,await i.default.writeFile(y,JSON.stringify(t,null,2));try{let e=o.default.join(s.default.homedir(),".config","Code","User","settings.json"),t=await i.default.readFile(e,"utf-8"),a=JSON.parse(t);delete a["kilocode.customProvider"],delete a["kilocode.defaultModel"],await i.default.writeFile(e,JSON.stringify(a,null,2))}catch{}try{(0,d.deleteCliToolLastConfigured)("kilo")}catch{}return n.NextResponse.json({success:!0,message:"OmniRoute settings removed from Kilo Code"})}catch(e){return console.log("Error resetting kilo settings:",e),n.NextResponse.json({error:"Failed to reset kilo settings"},{status:500})}}(0,f.ensureServerEntryExports)([m,g,R]),(0,r.registerServerReference)(m,"006c131f5ca01b2c4f23e40f755097bc026aae24eb",null),(0,r.registerServerReference)(g,"401461bab61861df22510712e9d4a419949948502d",null),(0,r.registerServerReference)(R,"00be2ecca54d9542826bcb02afcbac275ad71b0720",null),e.s(["DELETE",()=>R,"GET",()=>m,"POST",()=>g]),a()}catch(e){a(e)}},!1),472224,e=>e.a(async(t,a)=>{try{var r=e.i(747909),n=e.i(174017),i=e.i(996250),o=e.i(759756),s=e.i(561916),l=e.i(174677),u=e.i(869741),d=e.i(316795),c=e.i(487718),p=e.i(995169),f=e.i(47587),h=e.i(666012),m=e.i(570101),g=e.i(626937),R=e.i(10372),w=e.i(193695);e.i(52474);var y=e.i(600220),v=e.i(114902),C=t([v]);[v]=C.then?(await C)():C;let b=new r.AppRouteRouteModule({definition:{kind:n.RouteKind.APP_ROUTE,page:"/api/cli-tools/kilo-settings/route",pathname:"/api/cli-tools/kilo-settings",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/src/app/api/cli-tools/kilo-settings/route.ts",nextConfigOutput:"standalone",userland:v}),{workAsyncStorage:k,workUnitAsyncStorage:x,serverHooks:O}=b;function E(){return(0,i.patchFetch)({workAsyncStorage:k,workUnitAsyncStorage:x})}async function N(e,t,a){b.isDev&&(0,o.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let r="/api/cli-tools/kilo-settings/route";r=r.replace(/\/index$/,"")||"/";let i=await b.prepare(e,t,{srcPage:r,multiZoneDraftMode:!1});if(!i)return t.statusCode=400,t.end("Bad Request"),null==a.waitUntil||a.waitUntil.call(a,Promise.resolve()),null;let{buildId:v,params:C,nextConfig:E,parsedUrl:N,isDraftMode:k,prerenderManifest:x,routerServerContext:O,isOnDemandRevalidate:S,revalidateOnlyGenerated:j,resolvedPathname:P,clientReferenceManifest:A,serverActionsManifest:T}=i,U=(0,u.normalizeAppPath)(r),F=!!(x.dynamicRoutes[U]||x.routes[P]),_=async()=>((null==O?void 0:O.render404)?await O.render404(e,t,N,!1):t.end("This page could not be found"),null);if(F&&!k){let e=!!x.routes[P],t=x.dynamicRoutes[U];if(t&&!1===t.fallback&&!e){if(E.experimental.adapterPath)return await _();throw new w.NoFallbackError}}let I=null;!F||b.isDev||k||(I=P,I="/index"===I?"/":I);let M=!0===b.isDev||!F,H=F&&!M;T&&A&&(0,l.setManifestsSingleton)({page:r,clientReferenceManifest:A,serverActionsManifest:T});let q=e.method||"GET",D=(0,s.getTracer)(),K=D.getActiveScopeSpan(),L={params:C,prerenderManifest:x,renderOpts:{experimental:{authInterrupts:!!E.experimental.authInterrupts},cacheComponents:!!E.cacheComponents,supportsDynamicResponse:M,incrementalCache:(0,o.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:E.cacheLife,waitUntil:a.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,a,r,n)=>b.onRequestError(e,t,r,n,O)},sharedContext:{buildId:v}},J=new d.NodeNextRequest(e),$=new d.NodeNextResponse(t),B=c.NextRequestAdapter.fromNodeNextRequest(J,(0,c.signalFromNodeResponse)(t));try{let i=async e=>b.handle(B,L).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let a=D.getRootSpanAttributes();if(!a)return;if(a.get("next.span_type")!==p.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${a.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let n=a.get("next.route");if(n){let t=`${q} ${n}`;e.setAttributes({"next.route":n,"http.route":n,"next.span_name":t}),e.updateName(t)}else e.updateName(`${q} ${r}`)}),l=!!(0,o.getRequestMeta)(e,"minimalMode"),u=async o=>{var s,u;let d=async({previousCacheEntry:n})=>{try{if(!l&&S&&j&&!n)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let r=await i(o);e.fetchMetrics=L.renderOpts.fetchMetrics;let s=L.renderOpts.pendingWaitUntil;s&&a.waitUntil&&(a.waitUntil(s),s=void 0);let u=L.renderOpts.collectedTags;if(!F)return await (0,h.sendResponse)(J,$,r,L.renderOpts.pendingWaitUntil),null;{let e=await r.blob(),t=(0,m.toNodeOutgoingHttpHeaders)(r.headers);u&&(t[R.NEXT_CACHE_TAGS_HEADER]=u),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let a=void 0!==L.renderOpts.collectedRevalidate&&!(L.renderOpts.collectedRevalidate>=R.INFINITE_CACHE)&&L.renderOpts.collectedRevalidate,n=void 0===L.renderOpts.collectedExpire||L.renderOpts.collectedExpire>=R.INFINITE_CACHE?void 0:L.renderOpts.collectedExpire;return{value:{kind:y.CachedRouteKind.APP_ROUTE,status:r.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:a,expire:n}}}}catch(t){throw(null==n?void 0:n.isStale)&&await b.onRequestError(e,t,{routerKind:"App Router",routePath:r,routeType:"route",revalidateReason:(0,f.getRevalidateReason)({isStaticGeneration:H,isOnDemandRevalidate:S})},!1,O),t}},c=await b.handleResponse({req:e,nextConfig:E,cacheKey:I,routeKind:n.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:x,isRoutePPREnabled:!1,isOnDemandRevalidate:S,revalidateOnlyGenerated:j,responseGenerator:d,waitUntil:a.waitUntil,isMinimalMode:l});if(!F)return null;if((null==c||null==(s=c.value)?void 0:s.kind)!==y.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==c||null==(u=c.value)?void 0:u.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});l||t.setHeader("x-nextjs-cache",S?"REVALIDATED":c.isMiss?"MISS":c.isStale?"STALE":"HIT"),k&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let p=(0,m.fromNodeOutgoingHttpHeaders)(c.value.headers);return l&&F||p.delete(R.NEXT_CACHE_TAGS_HEADER),!c.cacheControl||t.getHeader("Cache-Control")||p.get("Cache-Control")||p.set("Cache-Control",(0,g.getCacheControlHeader)(c.cacheControl)),await (0,h.sendResponse)(J,$,new Response(c.value.body,{headers:p,status:c.value.status||200})),null};K?await u(K):await D.withPropagatedContext(e.headers,()=>D.trace(p.BaseServerSpan.handleRequest,{spanName:`${q} ${r}`,kind:s.SpanKind.SERVER,attributes:{"http.method":q,"http.target":e.url}},u))}catch(t){if(t instanceof w.NoFallbackError||await b.onRequestError(e,t,{routerKind:"App Router",routePath:U,routeType:"route",revalidateReason:(0,f.getRevalidateReason)({isStaticGeneration:H,isOnDemandRevalidate:S})},!1,O),F)throw t;return await (0,h.sendResponse)(J,$,new Response(null,{status:500})),null}}e.s(["handler",()=>N,"patchFetch",()=>E,"routeModule",()=>b,"serverHooks",()=>O,"workAsyncStorage",()=>k,"workUnitAsyncStorage",()=>x]),a()}catch(e){a(e)}},!1)];
2
2
 
3
3
  //# sourceMappingURL=_68683848._.js.map
@@ -0,0 +1,3 @@
1
+ module.exports=[532400,e=>e.a(async(t,r)=>{try{var n=e.i(224010),a=e.i(344448),i=e.i(287726),o=e.i(261189),s=e.i(719201),d=e.i(16023),l=e.i(706901),u=e.i(249157),c=e.i(740512),p=e.i(478847),h=e.i(676088),R=e.i(200392);e.i(245272);var m=e.i(542949),v=e.i(385498),f=t([h,R]);async function E(){return new Response(null,{headers:{"Access-Control-Allow-Origin":n.CORS_ORIGIN,"Access-Control-Allow-Methods":"GET, POST, OPTIONS","Access-Control-Allow-Headers":"*"}})}async function y(){let e=(0,o.getAllEmbeddingModels)(),t=Math.floor(Date.now()/1e3),r=e.map(e=>({id:e.id,object:"model",created:t,owned_by:e.provider,type:"embedding",dimensions:e.dimensions}));try{let e=await (0,m.getAllCustomModels)();for(let[n,a]of Object.entries(e))if(Array.isArray(a))for(let e of a){if(!e?.id||!Array.isArray(e.supportedEndpoints)||!e.supportedEndpoints.includes("embeddings"))continue;let a=`${n}/${e.id}`;r.some(e=>e.id===a)||r.push({id:a,object:"model",created:t,owned_by:n,type:"embedding",dimensions:null})}}catch{}return new Response(JSON.stringify({object:"list",data:r}),{headers:{"Content-Type":"application/json"}})}async function g(e){let t;try{t=await e.json()}catch{return l.warn("EMBED","Invalid JSON body"),(0,s.errorResponse)(d.HTTP_STATUS.BAD_REQUEST,"Invalid JSON body")}let r=(0,R.validateBody)(h.v1EmbeddingsSchema,t);if((0,R.isValidationFailure)(r))return(0,s.errorResponse)(d.HTTP_STATUS.BAD_REQUEST,r.error.message);let n=r.data;if("true"===process.env.REQUIRE_API_KEY){let t=(0,i.extractApiKey)(e);if(!t)return(0,s.errorResponse)(d.HTTP_STATUS.UNAUTHORIZED,"Missing API key");if(!await (0,i.isValidApiKey)(t))return(0,s.errorResponse)(d.HTTP_STATUS.UNAUTHORIZED,"Invalid API key")}let m=await (0,p.enforceApiKeyPolicy)(e,n.model);if(m.rejection)return m.rejection;let f=[];try{let e=await (0,v.getProviderNodes)();f=(Array.isArray(e)?e:[]).filter(e=>{if("chat"!==e.apiType&&"responses"!==e.apiType)return!1;try{let t=new URL(e.baseUrl).hostname;return"localhost"===t||"127.0.0.1"===t||"::1"===t||"[::1]"===t}catch{return!1}}).map(e=>{try{return(0,o.buildDynamicEmbeddingProvider)(e)}catch(t){return l.error("EMBED",`Skipping invalid provider_node ${e.prefix}: ${t}`),null}}).filter(e=>null!==e)}catch(e){l.error("EMBED",`Failed to load provider_nodes for embeddings: ${e}`)}let{provider:E,model:y}=(0,o.parseEmbeddingModel)(n.model,f);if(!E)return(0,s.errorResponse)(d.HTTP_STATUS.BAD_REQUEST,`Invalid embedding model: ${n.model}. Use format: provider/model`);let g=f.find(e=>e.id===E)||(0,o.getEmbeddingProvider)(E)||null;if(!g)try{let e=await (0,v.getProviderNodes)(),t=(Array.isArray(e)?e:[]).find(e=>e.prefix===E&&("chat"===e.apiType||"responses"===e.apiType)&&e.baseUrl);if(t){let e=String(t.baseUrl).replace(/\/+$/,"");g={id:t.prefix,baseUrl:`${e}/embeddings`,authType:"apikey",authHeader:"bearer",models:[]},l.info("EMBED",`Resolved custom embedding provider: ${E} → ${g.baseUrl}`)}}catch(e){l.error("EMBED",`Failed to resolve custom embedding provider ${E}: ${e}`)}if(!g)return(0,s.errorResponse)(d.HTTP_STATUS.BAD_REQUEST,`Unknown embedding provider: ${E}. No matching hardcoded or local provider found.`);let T=null;if(g&&"none"!==g.authType&&!(T=await (0,i.getProviderCredentials)(E)))return(0,s.errorResponse)(d.HTTP_STATUS.BAD_REQUEST,`No credentials for embedding provider: ${E}`);let A=await (0,a.handleEmbedding)({body:n,credentials:T,log:u,resolvedProvider:g,resolvedModel:y});if(A.success)return T&&await (0,i.clearRecoveredProviderState)(T),new Response(JSON.stringify(A.data),{status:200,headers:{"Content-Type":"application/json"}});let w=(0,c.toJsonErrorPayload)(A.error,"Embedding provider error");return new Response(JSON.stringify(w),{status:A.status,headers:{"Content-Type":"application/json"}})}[h,R]=f.then?(await f)():f,e.s(["GET",()=>y,"OPTIONS",()=>E,"POST",()=>g]),r()}catch(e){r(e)}},!1),559282,e=>e.a(async(t,r)=>{try{var n=e.i(747909),a=e.i(174017),i=e.i(996250),o=e.i(759756),s=e.i(561916),d=e.i(174677),l=e.i(869741),u=e.i(316795),c=e.i(487718),p=e.i(995169),h=e.i(47587),R=e.i(666012),m=e.i(570101),v=e.i(626937),f=e.i(10372),E=e.i(193695);e.i(52474);var y=e.i(600220),g=e.i(532400),T=t([g]);[g]=T.then?(await T)():T;let b=new n.AppRouteRouteModule({definition:{kind:a.RouteKind.APP_ROUTE,page:"/api/v1/embeddings/route",pathname:"/api/v1/embeddings",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/src/app/api/v1/embeddings/route.ts",nextConfigOutput:"standalone",userland:g}),{workAsyncStorage:S,workUnitAsyncStorage:P,serverHooks:C}=b;function A(){return(0,i.patchFetch)({workAsyncStorage:S,workUnitAsyncStorage:P})}async function w(e,t,r){b.isDev&&(0,o.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let n="/api/v1/embeddings/route";n=n.replace(/\/index$/,"")||"/";let i=await b.prepare(e,t,{srcPage:n,multiZoneDraftMode:!1});if(!i)return t.statusCode=400,t.end("Bad Request"),null==r.waitUntil||r.waitUntil.call(r,Promise.resolve()),null;let{buildId:g,params:T,nextConfig:A,parsedUrl:w,isDraftMode:S,prerenderManifest:P,routerServerContext:C,isOnDemandRevalidate:U,revalidateOnlyGenerated:_,resolvedPathname:O,clientReferenceManifest:N,serverActionsManifest:x}=i,I=(0,l.normalizeAppPath)(n),H=!!(P.dynamicRoutes[I]||P.routes[O]),D=async()=>((null==C?void 0:C.render404)?await C.render404(e,t,w,!1):t.end("This page could not be found"),null);if(H&&!S){let e=!!P.routes[O],t=P.dynamicRoutes[I];if(t&&!1===t.fallback&&!e){if(A.experimental.adapterPath)return await D();throw new E.NoFallbackError}}let M=null;!H||b.isDev||S||(M=O,M="/index"===M?"/":M);let $=!0===b.isDev||!H,k=H&&!$;x&&N&&(0,d.setManifestsSingleton)({page:n,clientReferenceManifest:N,serverActionsManifest:x});let j=e.method||"GET",B=(0,s.getTracer)(),q=B.getActiveScopeSpan(),K={params:T,prerenderManifest:P,renderOpts:{experimental:{authInterrupts:!!A.experimental.authInterrupts},cacheComponents:!!A.cacheComponents,supportsDynamicResponse:$,incrementalCache:(0,o.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:A.cacheLife,waitUntil:r.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,n,a)=>b.onRequestError(e,t,n,a,C)},sharedContext:{buildId:g}},F=new u.NodeNextRequest(e),G=new u.NodeNextResponse(t),J=c.NextRequestAdapter.fromNodeNextRequest(F,(0,c.signalFromNodeResponse)(t));try{let i=async e=>b.handle(J,K).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=B.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==p.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let a=r.get("next.route");if(a){let t=`${j} ${a}`;e.setAttributes({"next.route":a,"http.route":a,"next.span_name":t}),e.updateName(t)}else e.updateName(`${j} ${n}`)}),d=!!(0,o.getRequestMeta)(e,"minimalMode"),l=async o=>{var s,l;let u=async({previousCacheEntry:a})=>{try{if(!d&&U&&_&&!a)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let n=await i(o);e.fetchMetrics=K.renderOpts.fetchMetrics;let s=K.renderOpts.pendingWaitUntil;s&&r.waitUntil&&(r.waitUntil(s),s=void 0);let l=K.renderOpts.collectedTags;if(!H)return await (0,R.sendResponse)(F,G,n,K.renderOpts.pendingWaitUntil),null;{let e=await n.blob(),t=(0,m.toNodeOutgoingHttpHeaders)(n.headers);l&&(t[f.NEXT_CACHE_TAGS_HEADER]=l),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==K.renderOpts.collectedRevalidate&&!(K.renderOpts.collectedRevalidate>=f.INFINITE_CACHE)&&K.renderOpts.collectedRevalidate,a=void 0===K.renderOpts.collectedExpire||K.renderOpts.collectedExpire>=f.INFINITE_CACHE?void 0:K.renderOpts.collectedExpire;return{value:{kind:y.CachedRouteKind.APP_ROUTE,status:n.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:a}}}}catch(t){throw(null==a?void 0:a.isStale)&&await b.onRequestError(e,t,{routerKind:"App Router",routePath:n,routeType:"route",revalidateReason:(0,h.getRevalidateReason)({isStaticGeneration:k,isOnDemandRevalidate:U})},!1,C),t}},c=await b.handleResponse({req:e,nextConfig:A,cacheKey:M,routeKind:a.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:P,isRoutePPREnabled:!1,isOnDemandRevalidate:U,revalidateOnlyGenerated:_,responseGenerator:u,waitUntil:r.waitUntil,isMinimalMode:d});if(!H)return null;if((null==c||null==(s=c.value)?void 0:s.kind)!==y.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==c||null==(l=c.value)?void 0:l.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});d||t.setHeader("x-nextjs-cache",U?"REVALIDATED":c.isMiss?"MISS":c.isStale?"STALE":"HIT"),S&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let p=(0,m.fromNodeOutgoingHttpHeaders)(c.value.headers);return d&&H||p.delete(f.NEXT_CACHE_TAGS_HEADER),!c.cacheControl||t.getHeader("Cache-Control")||p.get("Cache-Control")||p.set("Cache-Control",(0,v.getCacheControlHeader)(c.cacheControl)),await (0,R.sendResponse)(F,G,new Response(c.value.body,{headers:p,status:c.value.status||200})),null};q?await l(q):await B.withPropagatedContext(e.headers,()=>B.trace(p.BaseServerSpan.handleRequest,{spanName:`${j} ${n}`,kind:s.SpanKind.SERVER,attributes:{"http.method":j,"http.target":e.url}},l))}catch(t){if(t instanceof E.NoFallbackError||await b.onRequestError(e,t,{routerKind:"App Router",routePath:I,routeType:"route",revalidateReason:(0,h.getRevalidateReason)({isStaticGeneration:k,isOnDemandRevalidate:U})},!1,C),H)throw t;return await (0,R.sendResponse)(F,G,new Response(null,{status:500})),null}}e.s(["handler",()=>w,"patchFetch",()=>A,"routeModule",()=>b,"serverHooks",()=>C,"workAsyncStorage",()=>S,"workUnitAsyncStorage",()=>P]),r()}catch(e){r(e)}},!1)];
2
+
3
+ //# sourceMappingURL=_b39b1914._.js.map
@@ -1,3 +1,3 @@
1
- module.exports=[675336,e=>e.a(async(t,r)=>{try{var a=e.i(745015),n=e.i(89171),s=e.i(924868),o=e.i(814747),i=e.i(266240),l=e.i(841788),d=e.i(197892),u=e.i(676088),c=e.i(200392),p=e.i(195975),m=t([u,c]);[u,c]=m.then?(await m)():m;let R=()=>(0,i.getCliPrimaryConfigPath)("droid"),y=async()=>{try{let e=R(),t=await s.default.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if("ENOENT"===e.code)return null;throw e}};async function h(){try{let e=await (0,i.getCliRuntimeStatus)("droid");if(!e.installed||!e.runnable)return n.NextResponse.json({installed:e.installed,runnable:e.runnable,command:e.command,commandPath:e.commandPath,runtimeMode:e.runtimeMode,reason:e.reason,settings:null,message:e.installed&&!e.runnable?"Factory Droid CLI is installed but not runnable":"Factory Droid CLI is not installed"});let t=await y();return n.NextResponse.json({installed:e.installed,runnable:e.runnable,command:e.command,commandPath:e.commandPath,runtimeMode:e.runtimeMode,reason:e.reason,settings:t,hasOmniRoute:!!t&&!!t.customModels&&t.customModels.some(e=>"custom:OmniRoute-0"===e.id),settingsPath:R()})}catch(e){return console.log("Error checking droid settings:",e),n.NextResponse.json({error:"Failed to check droid settings"},{status:500})}}async function f(e){let t;try{t=await e.json()}catch{return n.NextResponse.json({error:{message:"Invalid request",details:[{field:"body",message:"Invalid JSON body"}]}},{status:400})}try{let e=(0,i.ensureCliConfigWriteAllowed)();if(e)return n.NextResponse.json({error:e},{status:403});let r=(0,c.validateBody)(u.cliModelConfigSchema,t);if((0,c.isValidationFailure)(r))return n.NextResponse.json({error:r.error},{status:400});let{baseUrl:a,apiKey:p,model:m}=r.data,h=o.default.dirname(R()),f=R();await s.default.mkdir(h,{recursive:!0}),await (0,l.createBackup)("droid",f);let g={};try{let e=await s.default.readFile(f,"utf-8");g=JSON.parse(e)}catch{}g.customModels||(g.customModels=[]),g.customModels=g.customModels.filter(e=>"custom:OmniRoute-0"!==e.id);let y=a.endsWith("/v1")?a:`${a}/v1`;g.customModels.unshift({model:m,id:"custom:OmniRoute-0",index:0,baseUrl:y,apiKey:p||"your_api_key",displayName:m,maxOutputTokens:131072,noImageSupport:!1,provider:"openai"}),await s.default.writeFile(f,JSON.stringify(g,null,2));try{(0,d.saveCliToolLastConfigured)("droid")}catch{}return n.NextResponse.json({success:!0,message:"Factory Droid settings applied successfully!",settingsPath:f})}catch(e){return console.log("Error updating droid settings:",e),n.NextResponse.json({error:"Failed to update droid settings"},{status:500})}}async function g(){try{let e=(0,i.ensureCliConfigWriteAllowed)();if(e)return n.NextResponse.json({error:e},{status:403});let t=R();await (0,l.createBackup)("droid",t);let r={};try{let e=await s.default.readFile(t,"utf-8");r=JSON.parse(e)}catch(e){if("ENOENT"===e.code)return n.NextResponse.json({success:!0,message:"No settings file to reset"});throw e}r.customModels&&(r.customModels=r.customModels.filter(e=>"custom:OmniRoute-0"!==e.id),0===r.customModels.length&&delete r.customModels),await s.default.writeFile(t,JSON.stringify(r,null,2));try{(0,d.deleteCliToolLastConfigured)("droid")}catch{}return n.NextResponse.json({success:!0,message:"OmniRoute settings removed successfully"})}catch(e){return console.log("Error resetting droid settings:",e),n.NextResponse.json({error:"Failed to reset droid settings"},{status:500})}}(0,p.ensureServerEntryExports)([h,f,g]),(0,a.registerServerReference)(h,"0007a56088b8f2e1a56f60d23bf24fe3b29e12415a",null),(0,a.registerServerReference)(f,"40270b834221abffff11affe63c6f733c5a77f0ae6",null),(0,a.registerServerReference)(g,"001e413c31ea01c6625070253d19b8b5bae0780ee6",null),e.s(["DELETE",()=>g,"GET",()=>h,"POST",()=>f]),r()}catch(e){r(e)}},!1),122141,e=>e.a(async(t,r)=>{try{var a=e.i(747909),n=e.i(174017),s=e.i(996250),o=e.i(759756),i=e.i(561916),l=e.i(174677),d=e.i(869741),u=e.i(316795),c=e.i(487718),p=e.i(995169),m=e.i(47587),h=e.i(666012),f=e.i(570101),g=e.i(626937),R=e.i(10372),y=e.i(193695);e.i(52474);var v=e.i(600220),w=e.i(675336),E=t([w]);[w]=E.then?(await E)():E;let x=new a.AppRouteRouteModule({definition:{kind:n.RouteKind.APP_ROUTE,page:"/api/cli-tools/droid-settings/route",pathname:"/api/cli-tools/droid-settings",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/src/app/api/cli-tools/droid-settings/route.ts",nextConfigOutput:"standalone",userland:w}),{workAsyncStorage:b,workUnitAsyncStorage:O,serverHooks:S}=x;function C(){return(0,s.patchFetch)({workAsyncStorage:b,workUnitAsyncStorage:O})}async function N(e,t,r){x.isDev&&(0,o.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let a="/api/cli-tools/droid-settings/route";a=a.replace(/\/index$/,"")||"/";let s=await x.prepare(e,t,{srcPage:a,multiZoneDraftMode:!1});if(!s)return t.statusCode=400,t.end("Bad Request"),null==r.waitUntil||r.waitUntil.call(r,Promise.resolve()),null;let{buildId:w,params:E,nextConfig:C,parsedUrl:N,isDraftMode:b,prerenderManifest:O,routerServerContext:S,isOnDemandRevalidate:T,revalidateOnlyGenerated:A,resolvedPathname:P,clientReferenceManifest:M,serverActionsManifest:_}=s,j=(0,d.normalizeAppPath)(a),k=!!(O.dynamicRoutes[j]||O.routes[P]),F=async()=>((null==S?void 0:S.render404)?await S.render404(e,t,N,!1):t.end("This page could not be found"),null);if(k&&!b){let e=!!O.routes[P],t=O.dynamicRoutes[j];if(t&&!1===t.fallback&&!e){if(C.experimental.adapterPath)return await F();throw new y.NoFallbackError}}let I=null;!k||x.isDev||b||(I=P,I="/index"===I?"/":I);let D=!0===x.isDev||!k,H=k&&!D;_&&M&&(0,l.setManifestsSingleton)({page:a,clientReferenceManifest:M,serverActionsManifest:_});let U=e.method||"GET",q=(0,i.getTracer)(),L=q.getActiveScopeSpan(),$={params:E,prerenderManifest:O,renderOpts:{experimental:{authInterrupts:!!C.experimental.authInterrupts},cacheComponents:!!C.cacheComponents,supportsDynamicResponse:D,incrementalCache:(0,o.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:C.cacheLife,waitUntil:r.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,a,n)=>x.onRequestError(e,t,a,n,S)},sharedContext:{buildId:w}},K=new u.NodeNextRequest(e),B=new u.NodeNextResponse(t),J=c.NextRequestAdapter.fromNodeNextRequest(K,(0,c.signalFromNodeResponse)(t));try{let s=async e=>x.handle(J,$).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=q.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==p.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let n=r.get("next.route");if(n){let t=`${U} ${n}`;e.setAttributes({"next.route":n,"http.route":n,"next.span_name":t}),e.updateName(t)}else e.updateName(`${U} ${a}`)}),l=!!(0,o.getRequestMeta)(e,"minimalMode"),d=async o=>{var i,d;let u=async({previousCacheEntry:n})=>{try{if(!l&&T&&A&&!n)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let a=await s(o);e.fetchMetrics=$.renderOpts.fetchMetrics;let i=$.renderOpts.pendingWaitUntil;i&&r.waitUntil&&(r.waitUntil(i),i=void 0);let d=$.renderOpts.collectedTags;if(!k)return await (0,h.sendResponse)(K,B,a,$.renderOpts.pendingWaitUntil),null;{let e=await a.blob(),t=(0,f.toNodeOutgoingHttpHeaders)(a.headers);d&&(t[R.NEXT_CACHE_TAGS_HEADER]=d),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==$.renderOpts.collectedRevalidate&&!($.renderOpts.collectedRevalidate>=R.INFINITE_CACHE)&&$.renderOpts.collectedRevalidate,n=void 0===$.renderOpts.collectedExpire||$.renderOpts.collectedExpire>=R.INFINITE_CACHE?void 0:$.renderOpts.collectedExpire;return{value:{kind:v.CachedRouteKind.APP_ROUTE,status:a.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:n}}}}catch(t){throw(null==n?void 0:n.isStale)&&await x.onRequestError(e,t,{routerKind:"App Router",routePath:a,routeType:"route",revalidateReason:(0,m.getRevalidateReason)({isStaticGeneration:H,isOnDemandRevalidate:T})},!1,S),t}},c=await x.handleResponse({req:e,nextConfig:C,cacheKey:I,routeKind:n.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:O,isRoutePPREnabled:!1,isOnDemandRevalidate:T,revalidateOnlyGenerated:A,responseGenerator:u,waitUntil:r.waitUntil,isMinimalMode:l});if(!k)return null;if((null==c||null==(i=c.value)?void 0:i.kind)!==v.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==c||null==(d=c.value)?void 0:d.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});l||t.setHeader("x-nextjs-cache",T?"REVALIDATED":c.isMiss?"MISS":c.isStale?"STALE":"HIT"),b&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let p=(0,f.fromNodeOutgoingHttpHeaders)(c.value.headers);return l&&k||p.delete(R.NEXT_CACHE_TAGS_HEADER),!c.cacheControl||t.getHeader("Cache-Control")||p.get("Cache-Control")||p.set("Cache-Control",(0,g.getCacheControlHeader)(c.cacheControl)),await (0,h.sendResponse)(K,B,new Response(c.value.body,{headers:p,status:c.value.status||200})),null};L?await d(L):await q.withPropagatedContext(e.headers,()=>q.trace(p.BaseServerSpan.handleRequest,{spanName:`${U} ${a}`,kind:i.SpanKind.SERVER,attributes:{"http.method":U,"http.target":e.url}},d))}catch(t){if(t instanceof y.NoFallbackError||await x.onRequestError(e,t,{routerKind:"App Router",routePath:j,routeType:"route",revalidateReason:(0,m.getRevalidateReason)({isStaticGeneration:H,isOnDemandRevalidate:T})},!1,S),k)throw t;return await (0,h.sendResponse)(K,B,new Response(null,{status:500})),null}}e.s(["handler",()=>N,"patchFetch",()=>C,"routeModule",()=>x,"serverHooks",()=>S,"workAsyncStorage",()=>b,"workUnitAsyncStorage",()=>O]),r()}catch(e){r(e)}},!1)];
1
+ module.exports=[675336,e=>e.a(async(t,r)=>{try{var a=e.i(745015),n=e.i(89171),s=e.i(924868),o=e.i(814747),i=e.i(266240),l=e.i(841788),d=e.i(197892),u=e.i(676088),c=e.i(200392),p=e.i(195975),m=t([u,c]);[u,c]=m.then?(await m)():m;let R=()=>(0,i.getCliPrimaryConfigPath)("droid"),y=async()=>{try{let e=R(),t=await s.default.readFile(e,"utf-8");return JSON.parse(t)}catch(e){if("ENOENT"===e.code)return null;throw e}};async function h(){try{let e=await (0,i.getCliRuntimeStatus)("droid");if(!e.installed||!e.runnable)return n.NextResponse.json({installed:e.installed,runnable:e.runnable,command:e.command,commandPath:e.commandPath,runtimeMode:e.runtimeMode,reason:e.reason,settings:null,message:e.installed&&!e.runnable?"Factory Droid CLI is installed but not runnable":"Factory Droid CLI is not installed"});let t=await y();return n.NextResponse.json({installed:e.installed,runnable:e.runnable,command:e.command,commandPath:e.commandPath,runtimeMode:e.runtimeMode,reason:e.reason,settings:t,hasOmniRoute:!!t&&!!t.customModels&&t.customModels.some(e=>"custom:OmniRoute-0"===e.id),settingsPath:R()})}catch(e){return console.log("Error checking droid settings:",e),n.NextResponse.json({error:"Failed to check droid settings"},{status:500})}}async function f(e){let t;try{t=await e.json()}catch{return n.NextResponse.json({error:{message:"Invalid request",details:[{field:"body",message:"Invalid JSON body"}]}},{status:400})}try{let e=(0,i.ensureCliConfigWriteAllowed)();if(e)return n.NextResponse.json({error:e},{status:403});let r=(0,c.validateBody)(u.cliModelConfigSchema,t);if((0,c.isValidationFailure)(r))return n.NextResponse.json({error:r.error},{status:400});let{baseUrl:a,apiKey:p,model:m}=r.data,h=o.default.dirname(R()),f=R();await s.default.mkdir(h,{recursive:!0}),await (0,l.createBackup)("droid",f);let g={};try{let e=await s.default.readFile(f,"utf-8");g=JSON.parse(e)}catch{}g.customModels||(g.customModels=[]),g.customModels=g.customModels.filter(e=>"custom:OmniRoute-0"!==e.id);let y=a.endsWith("/v1")?a:`${a}/v1`;g.customModels.unshift({model:m,id:"custom:OmniRoute-0",index:0,baseUrl:y,apiKey:p||"your_api_key",displayName:m,maxOutputTokens:131072,noImageSupport:!1,provider:"openai"}),await s.default.writeFile(f,JSON.stringify(g,null,2));try{(0,d.saveCliToolLastConfigured)("droid")}catch{}return n.NextResponse.json({success:!0,message:"Factory Droid settings applied successfully!",settingsPath:f})}catch(e){return console.log("Error updating droid settings:",e),n.NextResponse.json({error:"Failed to update droid settings"},{status:500})}}async function g(){try{let e=(0,i.ensureCliConfigWriteAllowed)();if(e)return n.NextResponse.json({error:e},{status:403});let t=R();await (0,l.createBackup)("droid",t);let r={};try{let e=await s.default.readFile(t,"utf-8");r=JSON.parse(e)}catch(e){if("ENOENT"===e.code)return n.NextResponse.json({success:!0,message:"No settings file to reset"});throw e}r.customModels&&(r.customModels=r.customModels.filter(e=>"custom:OmniRoute-0"!==e.id),0===r.customModels.length&&delete r.customModels),await s.default.writeFile(t,JSON.stringify(r,null,2));try{(0,d.deleteCliToolLastConfigured)("droid")}catch{}return n.NextResponse.json({success:!0,message:"OmniRoute settings removed successfully"})}catch(e){return console.log("Error resetting droid settings:",e),n.NextResponse.json({error:"Failed to reset droid settings"},{status:500})}}(0,p.ensureServerEntryExports)([h,f,g]),(0,a.registerServerReference)(h,"00b92a8fa5a12d2a4f41993a5e38b94273dc80baf1",null),(0,a.registerServerReference)(f,"40b4bc098c969316ca80e78254a85d5a005fe8955d",null),(0,a.registerServerReference)(g,"00e9b62a1976e56bcf78fd75bcff49109ba27c4a33",null),e.s(["DELETE",()=>g,"GET",()=>h,"POST",()=>f]),r()}catch(e){r(e)}},!1),122141,e=>e.a(async(t,r)=>{try{var a=e.i(747909),n=e.i(174017),s=e.i(996250),o=e.i(759756),i=e.i(561916),l=e.i(174677),d=e.i(869741),u=e.i(316795),c=e.i(487718),p=e.i(995169),m=e.i(47587),h=e.i(666012),f=e.i(570101),g=e.i(626937),R=e.i(10372),y=e.i(193695);e.i(52474);var v=e.i(600220),w=e.i(675336),E=t([w]);[w]=E.then?(await E)():E;let x=new a.AppRouteRouteModule({definition:{kind:n.RouteKind.APP_ROUTE,page:"/api/cli-tools/droid-settings/route",pathname:"/api/cli-tools/droid-settings",filename:"route",bundlePath:""},distDir:".next",relativeProjectDir:"",resolvedPagePath:"[project]/src/app/api/cli-tools/droid-settings/route.ts",nextConfigOutput:"standalone",userland:w}),{workAsyncStorage:b,workUnitAsyncStorage:O,serverHooks:S}=x;function C(){return(0,s.patchFetch)({workAsyncStorage:b,workUnitAsyncStorage:O})}async function N(e,t,r){x.isDev&&(0,o.addRequestMeta)(e,"devRequestTimingInternalsEnd",process.hrtime.bigint());let a="/api/cli-tools/droid-settings/route";a=a.replace(/\/index$/,"")||"/";let s=await x.prepare(e,t,{srcPage:a,multiZoneDraftMode:!1});if(!s)return t.statusCode=400,t.end("Bad Request"),null==r.waitUntil||r.waitUntil.call(r,Promise.resolve()),null;let{buildId:w,params:E,nextConfig:C,parsedUrl:N,isDraftMode:b,prerenderManifest:O,routerServerContext:S,isOnDemandRevalidate:T,revalidateOnlyGenerated:A,resolvedPathname:P,clientReferenceManifest:M,serverActionsManifest:_}=s,j=(0,d.normalizeAppPath)(a),k=!!(O.dynamicRoutes[j]||O.routes[P]),F=async()=>((null==S?void 0:S.render404)?await S.render404(e,t,N,!1):t.end("This page could not be found"),null);if(k&&!b){let e=!!O.routes[P],t=O.dynamicRoutes[j];if(t&&!1===t.fallback&&!e){if(C.experimental.adapterPath)return await F();throw new y.NoFallbackError}}let I=null;!k||x.isDev||b||(I=P,I="/index"===I?"/":I);let D=!0===x.isDev||!k,H=k&&!D;_&&M&&(0,l.setManifestsSingleton)({page:a,clientReferenceManifest:M,serverActionsManifest:_});let U=e.method||"GET",q=(0,i.getTracer)(),L=q.getActiveScopeSpan(),$={params:E,prerenderManifest:O,renderOpts:{experimental:{authInterrupts:!!C.experimental.authInterrupts},cacheComponents:!!C.cacheComponents,supportsDynamicResponse:D,incrementalCache:(0,o.getRequestMeta)(e,"incrementalCache"),cacheLifeProfiles:C.cacheLife,waitUntil:r.waitUntil,onClose:e=>{t.on("close",e)},onAfterTaskError:void 0,onInstrumentationRequestError:(t,r,a,n)=>x.onRequestError(e,t,a,n,S)},sharedContext:{buildId:w}},K=new u.NodeNextRequest(e),B=new u.NodeNextResponse(t),J=c.NextRequestAdapter.fromNodeNextRequest(K,(0,c.signalFromNodeResponse)(t));try{let s=async e=>x.handle(J,$).finally(()=>{if(!e)return;e.setAttributes({"http.status_code":t.statusCode,"next.rsc":!1});let r=q.getRootSpanAttributes();if(!r)return;if(r.get("next.span_type")!==p.BaseServerSpan.handleRequest)return void console.warn(`Unexpected root span type '${r.get("next.span_type")}'. Please report this Next.js issue https://github.com/vercel/next.js`);let n=r.get("next.route");if(n){let t=`${U} ${n}`;e.setAttributes({"next.route":n,"http.route":n,"next.span_name":t}),e.updateName(t)}else e.updateName(`${U} ${a}`)}),l=!!(0,o.getRequestMeta)(e,"minimalMode"),d=async o=>{var i,d;let u=async({previousCacheEntry:n})=>{try{if(!l&&T&&A&&!n)return t.statusCode=404,t.setHeader("x-nextjs-cache","REVALIDATED"),t.end("This page could not be found"),null;let a=await s(o);e.fetchMetrics=$.renderOpts.fetchMetrics;let i=$.renderOpts.pendingWaitUntil;i&&r.waitUntil&&(r.waitUntil(i),i=void 0);let d=$.renderOpts.collectedTags;if(!k)return await (0,h.sendResponse)(K,B,a,$.renderOpts.pendingWaitUntil),null;{let e=await a.blob(),t=(0,f.toNodeOutgoingHttpHeaders)(a.headers);d&&(t[R.NEXT_CACHE_TAGS_HEADER]=d),!t["content-type"]&&e.type&&(t["content-type"]=e.type);let r=void 0!==$.renderOpts.collectedRevalidate&&!($.renderOpts.collectedRevalidate>=R.INFINITE_CACHE)&&$.renderOpts.collectedRevalidate,n=void 0===$.renderOpts.collectedExpire||$.renderOpts.collectedExpire>=R.INFINITE_CACHE?void 0:$.renderOpts.collectedExpire;return{value:{kind:v.CachedRouteKind.APP_ROUTE,status:a.status,body:Buffer.from(await e.arrayBuffer()),headers:t},cacheControl:{revalidate:r,expire:n}}}}catch(t){throw(null==n?void 0:n.isStale)&&await x.onRequestError(e,t,{routerKind:"App Router",routePath:a,routeType:"route",revalidateReason:(0,m.getRevalidateReason)({isStaticGeneration:H,isOnDemandRevalidate:T})},!1,S),t}},c=await x.handleResponse({req:e,nextConfig:C,cacheKey:I,routeKind:n.RouteKind.APP_ROUTE,isFallback:!1,prerenderManifest:O,isRoutePPREnabled:!1,isOnDemandRevalidate:T,revalidateOnlyGenerated:A,responseGenerator:u,waitUntil:r.waitUntil,isMinimalMode:l});if(!k)return null;if((null==c||null==(i=c.value)?void 0:i.kind)!==v.CachedRouteKind.APP_ROUTE)throw Object.defineProperty(Error(`Invariant: app-route received invalid cache entry ${null==c||null==(d=c.value)?void 0:d.kind}`),"__NEXT_ERROR_CODE",{value:"E701",enumerable:!1,configurable:!0});l||t.setHeader("x-nextjs-cache",T?"REVALIDATED":c.isMiss?"MISS":c.isStale?"STALE":"HIT"),b&&t.setHeader("Cache-Control","private, no-cache, no-store, max-age=0, must-revalidate");let p=(0,f.fromNodeOutgoingHttpHeaders)(c.value.headers);return l&&k||p.delete(R.NEXT_CACHE_TAGS_HEADER),!c.cacheControl||t.getHeader("Cache-Control")||p.get("Cache-Control")||p.set("Cache-Control",(0,g.getCacheControlHeader)(c.cacheControl)),await (0,h.sendResponse)(K,B,new Response(c.value.body,{headers:p,status:c.value.status||200})),null};L?await d(L):await q.withPropagatedContext(e.headers,()=>q.trace(p.BaseServerSpan.handleRequest,{spanName:`${U} ${a}`,kind:i.SpanKind.SERVER,attributes:{"http.method":U,"http.target":e.url}},d))}catch(t){if(t instanceof y.NoFallbackError||await x.onRequestError(e,t,{routerKind:"App Router",routePath:j,routeType:"route",revalidateReason:(0,m.getRevalidateReason)({isStaticGeneration:H,isOnDemandRevalidate:T})},!1,S),k)throw t;return await (0,h.sendResponse)(K,B,new Response(null,{status:500})),null}}e.s(["handler",()=>N,"patchFetch",()=>C,"routeModule",()=>x,"serverHooks",()=>S,"workAsyncStorage",()=>b,"workUnitAsyncStorage",()=>O]),r()}catch(e){r(e)}},!1)];
2
2
 
3
3
  //# sourceMappingURL=_ee9b677b._.js.map
@@ -1,3 +1,3 @@
1
- module.exports=[918622,(a,b,c)=>{b.exports=a.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},677850,a=>a.a(async(b,c)=>{try{let b=await a.y("zod");a.n(b),c()}catch(a){c(a)}},!0),342602,(a,b,c)=>{"use strict";b.exports=a.r(918622)},187924,(a,b,c)=>{"use strict";b.exports=a.r(342602).vendored["react-ssr"].ReactJsxRuntime},572131,(a,b,c)=>{"use strict";b.exports=a.r(342602).vendored["react-ssr"].React},804730,a=>{a.v({name:"omniroute",version:"2.8.6",description:"Smart AI Router with auto fallback — route to FREE & cheap models, zero downtime. Works with Cursor, Cline, Claude Desktop, Codex, and any OpenAI-compatible tool.",type:"module",bin:{omniroute:"bin/omniroute.mjs","omniroute-reset-password":"bin/reset-password.mjs"},files:["bin/","app/","open-sse/mcp-server/","src/shared/contracts/","scripts/postinstall.mjs","scripts/native-binary-compat.mjs","README.md","LICENSE"],workspaces:["open-sse"],engines:{node:">=18.0.0 <24.0.0"},keywords:["ai","router","proxy","openai","claude","anthropic","gemini","fallback","cursor","cline","codex","llm","auto-fallback"],license:"MIT",author:"diegosouzapw",repository:{type:"git",url:"https://github.com/diegosouzapw/OmniRoute"},homepage:"https://omniroute.online",scripts:{dev:"node scripts/run-next.mjs dev",build:"next build","build:cli":"node scripts/prepublish.mjs",start:"node scripts/run-next.mjs start",lint:"eslint .","electron:dev":'concurrently "npm run dev" "wait-on http://localhost:20128 && cd electron && npm run dev"',"electron:build":"npm run build && cd electron && npm run build","electron:build:win":"npm run build && cd electron && npm run build:win","electron:build:mac":"npm run build && cd electron && npm run build:mac","electron:build:linux":"npm run build && cd electron && npm run build:linux",test:"node --import tsx/esm --test tests/unit/*.test.mjs","test:unit":"node --import tsx/esm --test tests/unit/*.test.mjs","test:plan3":"node --import tsx/esm --test tests/unit/plan3-p0.test.mjs","test:fixes":"node --import tsx/esm --test tests/unit/fixes-p1.test.mjs","test:security":"node --import tsx/esm --test tests/unit/security-fase01.test.mjs","check:cycles":"node scripts/check-cycles.mjs","check:route-validation:t06":"node scripts/check-route-validation.mjs","check:any-budget:t11":"node scripts/check-t11-any-budget.mjs","check:docs-sync":"node scripts/check-docs-sync.mjs","typecheck:core":"tsc --pretty false -p tsconfig.typecheck-core.json","typecheck:noimplicit:core":"tsc --pretty false -p tsconfig.typecheck-noimplicit-core.json","test:integration":"node --import tsx/esm --test tests/integration/*.test.mjs","test:e2e":"node scripts/run-playwright-tests.mjs test tests/e2e/*.spec.ts","test:protocols:e2e":"node scripts/run-protocol-clients-tests.mjs","test:vitest":"vitest run open-sse/mcp-server/__tests__/*.test.ts open-sse/services/autoCombo/__tests__/*.test.ts","test:ecosystem":"node scripts/run-ecosystem-tests.mjs","test:coverage":"npx c8 --exclude=open-sse --check-coverage --lines 50 --functions 50 --branches 50 node --import tsx/esm --test tests/unit/*.test.mjs","test:all":"npm run test:unit && npm run test:vitest && npm run test:ecosystem && npm run test:e2e",check:"npm run lint && npm run test",prepublishOnly:"npm run build:cli",postinstall:"node scripts/postinstall.mjs",prepare:"husky","system-info":"node scripts/system-info.mjs"},dependencies:{"@modelcontextprotocol/sdk":"^1.27.1","@monaco-editor/react":"^4.7.0",bcryptjs:"^3.0.3","better-sqlite3":"^12.6.2",bottleneck:"^2.19.5",dompurify:"^3.3.2",express:"^5.2.1","fetch-socks":"^1.3.2","http-proxy-middleware":"^3.0.5","https-proxy-agent":"^8.0.0",jose:"^6.1.3",lowdb:"^7.0.1","monaco-editor":"^0.55.1",next:"^16.1.6","next-intl":"^4.8.3","node-machine-id":"^1.1.12",open:"^11.0.0",ora:"^9.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",react:"19.2.4","react-dom":"19.2.4",recharts:"^3.7.0",selfsigned:"^5.5.0",tsx:"^4.21.0",undici:"^7.19.2",uuid:"^13.0.0","wreq-js":"^2.0.1",zod:"^4.3.6",zustand:"^5.0.10","@swc/helpers":"0.5.19"},devDependencies:{"@playwright/test":"^1.58.2","@tailwindcss/postcss":"^4.1.18","@types/bcryptjs":"^3.0.0","@types/better-sqlite3":"^7.6.13","@types/node":"^25.2.3","@types/react":"^19.2.14","@types/react-dom":"^19.2.3",concurrently:"^9.2.1","cross-env":"^10.1.0",eslint:"^9.39.2","eslint-config-next":"16.1.6",husky:"^9.1.7","lint-staged":"^16.2.7",prettier:"^3.8.1",tailwindcss:"^4",typescript:"^5.9.3","typescript-eslint":"^8.56.0",vitest:"^4.0.18","wait-on":"^9.0.4"},"lint-staged":{"*.{js,jsx,ts,tsx,mjs}":["prettier --write","eslint --fix --no-error-on-unmatched-pattern"],"*.{json,md,yml,yaml,css}":["prettier --write"]},pnpm:{onlyBuiltDependencies:["@parcel/watcher","@swc/core","better-sqlite3","esbuild","omniroute","sharp"]}})},588788,a=>{"use strict";var b=a.i(32886),c=a.i(187924);function d({locale:a,...d}){if(!a)throw Error(void 0);return(0,c.jsx)(b.IntlProvider,{locale:a,...d})}a.s(["default",()=>d])}];
1
+ module.exports=[918622,(a,b,c)=>{b.exports=a.x("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js",()=>require("next/dist/compiled/next-server/app-page-turbo.runtime.prod.js"))},677850,a=>a.a(async(b,c)=>{try{let b=await a.y("zod");a.n(b),c()}catch(a){c(a)}},!0),342602,(a,b,c)=>{"use strict";b.exports=a.r(918622)},187924,(a,b,c)=>{"use strict";b.exports=a.r(342602).vendored["react-ssr"].ReactJsxRuntime},572131,(a,b,c)=>{"use strict";b.exports=a.r(342602).vendored["react-ssr"].React},804730,a=>{a.v({name:"omniroute",version:"2.8.7",description:"Smart AI Router with auto fallback — route to FREE & cheap models, zero downtime. Works with Cursor, Cline, Claude Desktop, Codex, and any OpenAI-compatible tool.",type:"module",bin:{omniroute:"bin/omniroute.mjs","omniroute-reset-password":"bin/reset-password.mjs"},files:["bin/","app/","open-sse/mcp-server/","src/shared/contracts/","scripts/postinstall.mjs","scripts/native-binary-compat.mjs","README.md","LICENSE"],workspaces:["open-sse"],engines:{node:">=18.0.0 <24.0.0"},keywords:["ai","router","proxy","openai","claude","anthropic","gemini","fallback","cursor","cline","codex","llm","auto-fallback"],license:"MIT",author:"diegosouzapw",repository:{type:"git",url:"https://github.com/diegosouzapw/OmniRoute"},homepage:"https://omniroute.online",scripts:{dev:"node scripts/run-next.mjs dev",build:"next build","build:cli":"node scripts/prepublish.mjs",start:"node scripts/run-next.mjs start",lint:"eslint .","electron:dev":'concurrently "npm run dev" "wait-on http://localhost:20128 && cd electron && npm run dev"',"electron:build":"npm run build && cd electron && npm run build","electron:build:win":"npm run build && cd electron && npm run build:win","electron:build:mac":"npm run build && cd electron && npm run build:mac","electron:build:linux":"npm run build && cd electron && npm run build:linux",test:"node --import tsx/esm --test tests/unit/*.test.mjs","test:unit":"node --import tsx/esm --test tests/unit/*.test.mjs","test:plan3":"node --import tsx/esm --test tests/unit/plan3-p0.test.mjs","test:fixes":"node --import tsx/esm --test tests/unit/fixes-p1.test.mjs","test:security":"node --import tsx/esm --test tests/unit/security-fase01.test.mjs","check:cycles":"node scripts/check-cycles.mjs","check:route-validation:t06":"node scripts/check-route-validation.mjs","check:any-budget:t11":"node scripts/check-t11-any-budget.mjs","check:docs-sync":"node scripts/check-docs-sync.mjs","typecheck:core":"tsc --pretty false -p tsconfig.typecheck-core.json","typecheck:noimplicit:core":"tsc --pretty false -p tsconfig.typecheck-noimplicit-core.json","test:integration":"node --import tsx/esm --test tests/integration/*.test.mjs","test:e2e":"node scripts/run-playwright-tests.mjs test tests/e2e/*.spec.ts","test:protocols:e2e":"node scripts/run-protocol-clients-tests.mjs","test:vitest":"vitest run open-sse/mcp-server/__tests__/*.test.ts open-sse/services/autoCombo/__tests__/*.test.ts","test:ecosystem":"node scripts/run-ecosystem-tests.mjs","test:coverage":"npx c8 --exclude=open-sse --check-coverage --lines 50 --functions 50 --branches 50 node --import tsx/esm --test tests/unit/*.test.mjs","test:all":"npm run test:unit && npm run test:vitest && npm run test:ecosystem && npm run test:e2e",check:"npm run lint && npm run test",prepublishOnly:"npm run build:cli",postinstall:"node scripts/postinstall.mjs",prepare:"husky","system-info":"node scripts/system-info.mjs"},dependencies:{"@modelcontextprotocol/sdk":"^1.27.1","@monaco-editor/react":"^4.7.0",bcryptjs:"^3.0.3","better-sqlite3":"^12.6.2",bottleneck:"^2.19.5",dompurify:"^3.3.2",express:"^5.2.1","fetch-socks":"^1.3.2","http-proxy-middleware":"^3.0.5","https-proxy-agent":"^8.0.0",jose:"^6.1.3",lowdb:"^7.0.1","monaco-editor":"^0.55.1",next:"^16.1.6","next-intl":"^4.8.3","node-machine-id":"^1.1.12",open:"^11.0.0",ora:"^9.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",react:"19.2.4","react-dom":"19.2.4",recharts:"^3.7.0",selfsigned:"^5.5.0",tsx:"^4.21.0",undici:"^7.19.2",uuid:"^13.0.0","wreq-js":"^2.0.1",zod:"^4.3.6",zustand:"^5.0.10","@swc/helpers":"0.5.19"},devDependencies:{"@playwright/test":"^1.58.2","@tailwindcss/postcss":"^4.1.18","@types/bcryptjs":"^3.0.0","@types/better-sqlite3":"^7.6.13","@types/node":"^25.2.3","@types/react":"^19.2.14","@types/react-dom":"^19.2.3",concurrently:"^9.2.1","cross-env":"^10.1.0",eslint:"^9.39.2","eslint-config-next":"16.1.6",husky:"^9.1.7","lint-staged":"^16.2.7",prettier:"^3.8.1",tailwindcss:"^4",typescript:"^5.9.3","typescript-eslint":"^8.56.0",vitest:"^4.0.18","wait-on":"^9.0.4"},"lint-staged":{"*.{js,jsx,ts,tsx,mjs}":["prettier --write","eslint --fix --no-error-on-unmatched-pattern"],"*.{json,md,yml,yaml,css}":["prettier --write"]},pnpm:{onlyBuiltDependencies:["@parcel/watcher","@swc/core","better-sqlite3","esbuild","omniroute","sharp"]}})},588788,a=>{"use strict";var b=a.i(32886),c=a.i(187924);function d({locale:a,...d}){if(!a)throw Error(void 0);return(0,c.jsx)(b.IntlProvider,{locale:a,...d})}a.s(["default",()=>d])}];
2
2
 
3
3
  //# sourceMappingURL=%5Broot-of-the-server%5D__9affb65e._.js.map
@@ -1,3 +1,3 @@
1
- module.exports=[193695,(a,b,c)=>{b.exports=a.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},677850,a=>a.a(async(b,c)=>{try{let b=await a.y("zod");a.n(b),c()}catch(a){c(a)}},!0),804730,a=>{a.v({name:"omniroute",version:"2.8.6",description:"Smart AI Router with auto fallback — route to FREE & cheap models, zero downtime. Works with Cursor, Cline, Claude Desktop, Codex, and any OpenAI-compatible tool.",type:"module",bin:{omniroute:"bin/omniroute.mjs","omniroute-reset-password":"bin/reset-password.mjs"},files:["bin/","app/","open-sse/mcp-server/","src/shared/contracts/","scripts/postinstall.mjs","scripts/native-binary-compat.mjs","README.md","LICENSE"],workspaces:["open-sse"],engines:{node:">=18.0.0 <24.0.0"},keywords:["ai","router","proxy","openai","claude","anthropic","gemini","fallback","cursor","cline","codex","llm","auto-fallback"],license:"MIT",author:"diegosouzapw",repository:{type:"git",url:"https://github.com/diegosouzapw/OmniRoute"},homepage:"https://omniroute.online",scripts:{dev:"node scripts/run-next.mjs dev",build:"next build","build:cli":"node scripts/prepublish.mjs",start:"node scripts/run-next.mjs start",lint:"eslint .","electron:dev":'concurrently "npm run dev" "wait-on http://localhost:20128 && cd electron && npm run dev"',"electron:build":"npm run build && cd electron && npm run build","electron:build:win":"npm run build && cd electron && npm run build:win","electron:build:mac":"npm run build && cd electron && npm run build:mac","electron:build:linux":"npm run build && cd electron && npm run build:linux",test:"node --import tsx/esm --test tests/unit/*.test.mjs","test:unit":"node --import tsx/esm --test tests/unit/*.test.mjs","test:plan3":"node --import tsx/esm --test tests/unit/plan3-p0.test.mjs","test:fixes":"node --import tsx/esm --test tests/unit/fixes-p1.test.mjs","test:security":"node --import tsx/esm --test tests/unit/security-fase01.test.mjs","check:cycles":"node scripts/check-cycles.mjs","check:route-validation:t06":"node scripts/check-route-validation.mjs","check:any-budget:t11":"node scripts/check-t11-any-budget.mjs","check:docs-sync":"node scripts/check-docs-sync.mjs","typecheck:core":"tsc --pretty false -p tsconfig.typecheck-core.json","typecheck:noimplicit:core":"tsc --pretty false -p tsconfig.typecheck-noimplicit-core.json","test:integration":"node --import tsx/esm --test tests/integration/*.test.mjs","test:e2e":"node scripts/run-playwright-tests.mjs test tests/e2e/*.spec.ts","test:protocols:e2e":"node scripts/run-protocol-clients-tests.mjs","test:vitest":"vitest run open-sse/mcp-server/__tests__/*.test.ts open-sse/services/autoCombo/__tests__/*.test.ts","test:ecosystem":"node scripts/run-ecosystem-tests.mjs","test:coverage":"npx c8 --exclude=open-sse --check-coverage --lines 50 --functions 50 --branches 50 node --import tsx/esm --test tests/unit/*.test.mjs","test:all":"npm run test:unit && npm run test:vitest && npm run test:ecosystem && npm run test:e2e",check:"npm run lint && npm run test",prepublishOnly:"npm run build:cli",postinstall:"node scripts/postinstall.mjs",prepare:"husky","system-info":"node scripts/system-info.mjs"},dependencies:{"@modelcontextprotocol/sdk":"^1.27.1","@monaco-editor/react":"^4.7.0",bcryptjs:"^3.0.3","better-sqlite3":"^12.6.2",bottleneck:"^2.19.5",dompurify:"^3.3.2",express:"^5.2.1","fetch-socks":"^1.3.2","http-proxy-middleware":"^3.0.5","https-proxy-agent":"^8.0.0",jose:"^6.1.3",lowdb:"^7.0.1","monaco-editor":"^0.55.1",next:"^16.1.6","next-intl":"^4.8.3","node-machine-id":"^1.1.12",open:"^11.0.0",ora:"^9.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",react:"19.2.4","react-dom":"19.2.4",recharts:"^3.7.0",selfsigned:"^5.5.0",tsx:"^4.21.0",undici:"^7.19.2",uuid:"^13.0.0","wreq-js":"^2.0.1",zod:"^4.3.6",zustand:"^5.0.10","@swc/helpers":"0.5.19"},devDependencies:{"@playwright/test":"^1.58.2","@tailwindcss/postcss":"^4.1.18","@types/bcryptjs":"^3.0.0","@types/better-sqlite3":"^7.6.13","@types/node":"^25.2.3","@types/react":"^19.2.14","@types/react-dom":"^19.2.3",concurrently:"^9.2.1","cross-env":"^10.1.0",eslint:"^9.39.2","eslint-config-next":"16.1.6",husky:"^9.1.7","lint-staged":"^16.2.7",prettier:"^3.8.1",tailwindcss:"^4",typescript:"^5.9.3","typescript-eslint":"^8.56.0",vitest:"^4.0.18","wait-on":"^9.0.4"},"lint-staged":{"*.{js,jsx,ts,tsx,mjs}":["prettier --write","eslint --fix --no-error-on-unmatched-pattern"],"*.{json,md,yml,yaml,css}":["prettier --write"]},pnpm:{onlyBuiltDependencies:["@parcel/watcher","@swc/core","better-sqlite3","esbuild","omniroute","sharp"]}})},569264,a=>{a.n(a.i(354832))},650645,a=>{a.n(a.i(827572))},923576,a=>{a.n(a.i(104858))},825210,a=>{a.n(a.i(402747))},517537,a=>{a.n(a.i(903363))},13718,a=>{a.n(a.i(685523))},118198,a=>{a.n(a.i(545518))},296736,(a,b,c)=>{"use strict";function d(a){if("function"!=typeof WeakMap)return null;var b=new WeakMap,c=new WeakMap;return(d=function(a){return a?c:b})(a)}c._=function(a,b){if(!b&&a&&a.__esModule)return a;if(null===a||"object"!=typeof a&&"function"!=typeof a)return{default:a};var c=d(b);if(c&&c.has(a))return c.get(a);var e={__proto__:null},f=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in a)if("default"!==g&&Object.prototype.hasOwnProperty.call(a,g)){var h=f?Object.getOwnPropertyDescriptor(a,g):null;h&&(h.get||h.set)?Object.defineProperty(e,g,h):e[g]=a[g]}return e.default=a,c&&c.set(a,e),e}},500790,(a,b,c)=>{let{createClientModuleProxy:d}=a.r(211857);a.n(d("[project]/node_modules/next/dist/client/app-dir/link.js <module evaluation>"))},784707,(a,b,c)=>{let{createClientModuleProxy:d}=a.r(211857);a.n(d("[project]/node_modules/next/dist/client/app-dir/link.js"))},297647,a=>{"use strict";a.i(500790);var b=a.i(784707);a.n(b)},395936,(a,b,c)=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});var d={default:function(){return i},useLinkStatus:function(){return h.useLinkStatus}};for(var e in d)Object.defineProperty(c,e,{enumerable:!0,get:d[e]});let f=a.r(296736),g=a.r(907997),h=f._(a.r(297647));function i(a){let b=a.legacyBehavior,c="string"==typeof a.children||"number"==typeof a.children||"string"==typeof a.children?.type,d=a.children?.type?.$$typeof===Symbol.for("react.client.reference");return!b||c||d||(a.children?.type?.$$typeof===Symbol.for("react.lazy")?console.error("Using a Lazy Component as a direct child of `<Link legacyBehavior>` from a Server Component is not supported. If you need legacyBehavior, wrap your Lazy Component in a Client Component that renders the Link's `<a>` tag."):console.error("Using a Server Component as a direct child of `<Link legacyBehavior>` is not supported. If you need legacyBehavior, wrap your Server Component in a Client Component that renders the Link's `<a>` tag.")),(0,g.jsx)(h.default,{...a})}("function"==typeof c.default||"object"==typeof c.default&&null!==c.default)&&void 0===c.default.__esModule&&(Object.defineProperty(c.default,"__esModule",{value:!0}),Object.assign(c.default,c),b.exports=c.default)},330878,a=>{"use strict";var b=a.i(800717),c=a.i(118845),d=a.i(40953),e=(0,b.cache)(function(a,b){return function({_cache:a=(0,c.b)(),_formatters:b=(0,c.c)(a),getMessageFallback:e=d.d,messages:f,namespace:g,onError:h=d.b,...i}){return function({messages:a,namespace:b,...c},e){return a=a["!"],b=(0,d.r)(b,"!"),(0,d.a)({...c,messages:a,namespace:b})}({...i,onError:h,cache:a,formatters:b,getMessageFallback:e,messages:{"!":f},namespace:g?`!.${g}`:"!"},0)}({...a,namespace:b})});a.s(["default",()=>e],330878)},442979,a=>{"use strict";var b=a.i(330878),c=a.i(767228),d=a.i(800717)["use".trim()];function e(...[a]){let f=function(a){var b=(0,c.default)();try{return d(b)}catch(b){throw b instanceof TypeError&&b.message.includes("Cannot read properties of null (reading 'use')")?Error(`\`${a}\` is not callable within an async component. Please refer to https://next-intl.dev/docs/environments/server-client-components#async-components`,{cause:b}):b}}("useTranslations");return(0,b.default)(f,a)}a.s(["useTranslations",()=>e],442979)}];
1
+ module.exports=[193695,(a,b,c)=>{b.exports=a.x("next/dist/shared/lib/no-fallback-error.external.js",()=>require("next/dist/shared/lib/no-fallback-error.external.js"))},677850,a=>a.a(async(b,c)=>{try{let b=await a.y("zod");a.n(b),c()}catch(a){c(a)}},!0),804730,a=>{a.v({name:"omniroute",version:"2.8.7",description:"Smart AI Router with auto fallback — route to FREE & cheap models, zero downtime. Works with Cursor, Cline, Claude Desktop, Codex, and any OpenAI-compatible tool.",type:"module",bin:{omniroute:"bin/omniroute.mjs","omniroute-reset-password":"bin/reset-password.mjs"},files:["bin/","app/","open-sse/mcp-server/","src/shared/contracts/","scripts/postinstall.mjs","scripts/native-binary-compat.mjs","README.md","LICENSE"],workspaces:["open-sse"],engines:{node:">=18.0.0 <24.0.0"},keywords:["ai","router","proxy","openai","claude","anthropic","gemini","fallback","cursor","cline","codex","llm","auto-fallback"],license:"MIT",author:"diegosouzapw",repository:{type:"git",url:"https://github.com/diegosouzapw/OmniRoute"},homepage:"https://omniroute.online",scripts:{dev:"node scripts/run-next.mjs dev",build:"next build","build:cli":"node scripts/prepublish.mjs",start:"node scripts/run-next.mjs start",lint:"eslint .","electron:dev":'concurrently "npm run dev" "wait-on http://localhost:20128 && cd electron && npm run dev"',"electron:build":"npm run build && cd electron && npm run build","electron:build:win":"npm run build && cd electron && npm run build:win","electron:build:mac":"npm run build && cd electron && npm run build:mac","electron:build:linux":"npm run build && cd electron && npm run build:linux",test:"node --import tsx/esm --test tests/unit/*.test.mjs","test:unit":"node --import tsx/esm --test tests/unit/*.test.mjs","test:plan3":"node --import tsx/esm --test tests/unit/plan3-p0.test.mjs","test:fixes":"node --import tsx/esm --test tests/unit/fixes-p1.test.mjs","test:security":"node --import tsx/esm --test tests/unit/security-fase01.test.mjs","check:cycles":"node scripts/check-cycles.mjs","check:route-validation:t06":"node scripts/check-route-validation.mjs","check:any-budget:t11":"node scripts/check-t11-any-budget.mjs","check:docs-sync":"node scripts/check-docs-sync.mjs","typecheck:core":"tsc --pretty false -p tsconfig.typecheck-core.json","typecheck:noimplicit:core":"tsc --pretty false -p tsconfig.typecheck-noimplicit-core.json","test:integration":"node --import tsx/esm --test tests/integration/*.test.mjs","test:e2e":"node scripts/run-playwright-tests.mjs test tests/e2e/*.spec.ts","test:protocols:e2e":"node scripts/run-protocol-clients-tests.mjs","test:vitest":"vitest run open-sse/mcp-server/__tests__/*.test.ts open-sse/services/autoCombo/__tests__/*.test.ts","test:ecosystem":"node scripts/run-ecosystem-tests.mjs","test:coverage":"npx c8 --exclude=open-sse --check-coverage --lines 50 --functions 50 --branches 50 node --import tsx/esm --test tests/unit/*.test.mjs","test:all":"npm run test:unit && npm run test:vitest && npm run test:ecosystem && npm run test:e2e",check:"npm run lint && npm run test",prepublishOnly:"npm run build:cli",postinstall:"node scripts/postinstall.mjs",prepare:"husky","system-info":"node scripts/system-info.mjs"},dependencies:{"@modelcontextprotocol/sdk":"^1.27.1","@monaco-editor/react":"^4.7.0",bcryptjs:"^3.0.3","better-sqlite3":"^12.6.2",bottleneck:"^2.19.5",dompurify:"^3.3.2",express:"^5.2.1","fetch-socks":"^1.3.2","http-proxy-middleware":"^3.0.5","https-proxy-agent":"^8.0.0",jose:"^6.1.3",lowdb:"^7.0.1","monaco-editor":"^0.55.1",next:"^16.1.6","next-intl":"^4.8.3","node-machine-id":"^1.1.12",open:"^11.0.0",ora:"^9.1.0",pino:"^10.3.1","pino-pretty":"^13.1.3",react:"19.2.4","react-dom":"19.2.4",recharts:"^3.7.0",selfsigned:"^5.5.0",tsx:"^4.21.0",undici:"^7.19.2",uuid:"^13.0.0","wreq-js":"^2.0.1",zod:"^4.3.6",zustand:"^5.0.10","@swc/helpers":"0.5.19"},devDependencies:{"@playwright/test":"^1.58.2","@tailwindcss/postcss":"^4.1.18","@types/bcryptjs":"^3.0.0","@types/better-sqlite3":"^7.6.13","@types/node":"^25.2.3","@types/react":"^19.2.14","@types/react-dom":"^19.2.3",concurrently:"^9.2.1","cross-env":"^10.1.0",eslint:"^9.39.2","eslint-config-next":"16.1.6",husky:"^9.1.7","lint-staged":"^16.2.7",prettier:"^3.8.1",tailwindcss:"^4",typescript:"^5.9.3","typescript-eslint":"^8.56.0",vitest:"^4.0.18","wait-on":"^9.0.4"},"lint-staged":{"*.{js,jsx,ts,tsx,mjs}":["prettier --write","eslint --fix --no-error-on-unmatched-pattern"],"*.{json,md,yml,yaml,css}":["prettier --write"]},pnpm:{onlyBuiltDependencies:["@parcel/watcher","@swc/core","better-sqlite3","esbuild","omniroute","sharp"]}})},569264,a=>{a.n(a.i(354832))},650645,a=>{a.n(a.i(827572))},923576,a=>{a.n(a.i(104858))},825210,a=>{a.n(a.i(402747))},517537,a=>{a.n(a.i(903363))},13718,a=>{a.n(a.i(685523))},118198,a=>{a.n(a.i(545518))},296736,(a,b,c)=>{"use strict";function d(a){if("function"!=typeof WeakMap)return null;var b=new WeakMap,c=new WeakMap;return(d=function(a){return a?c:b})(a)}c._=function(a,b){if(!b&&a&&a.__esModule)return a;if(null===a||"object"!=typeof a&&"function"!=typeof a)return{default:a};var c=d(b);if(c&&c.has(a))return c.get(a);var e={__proto__:null},f=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var g in a)if("default"!==g&&Object.prototype.hasOwnProperty.call(a,g)){var h=f?Object.getOwnPropertyDescriptor(a,g):null;h&&(h.get||h.set)?Object.defineProperty(e,g,h):e[g]=a[g]}return e.default=a,c&&c.set(a,e),e}},500790,(a,b,c)=>{let{createClientModuleProxy:d}=a.r(211857);a.n(d("[project]/node_modules/next/dist/client/app-dir/link.js <module evaluation>"))},784707,(a,b,c)=>{let{createClientModuleProxy:d}=a.r(211857);a.n(d("[project]/node_modules/next/dist/client/app-dir/link.js"))},297647,a=>{"use strict";a.i(500790);var b=a.i(784707);a.n(b)},395936,(a,b,c)=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});var d={default:function(){return i},useLinkStatus:function(){return h.useLinkStatus}};for(var e in d)Object.defineProperty(c,e,{enumerable:!0,get:d[e]});let f=a.r(296736),g=a.r(907997),h=f._(a.r(297647));function i(a){let b=a.legacyBehavior,c="string"==typeof a.children||"number"==typeof a.children||"string"==typeof a.children?.type,d=a.children?.type?.$$typeof===Symbol.for("react.client.reference");return!b||c||d||(a.children?.type?.$$typeof===Symbol.for("react.lazy")?console.error("Using a Lazy Component as a direct child of `<Link legacyBehavior>` from a Server Component is not supported. If you need legacyBehavior, wrap your Lazy Component in a Client Component that renders the Link's `<a>` tag."):console.error("Using a Server Component as a direct child of `<Link legacyBehavior>` is not supported. If you need legacyBehavior, wrap your Server Component in a Client Component that renders the Link's `<a>` tag.")),(0,g.jsx)(h.default,{...a})}("function"==typeof c.default||"object"==typeof c.default&&null!==c.default)&&void 0===c.default.__esModule&&(Object.defineProperty(c.default,"__esModule",{value:!0}),Object.assign(c.default,c),b.exports=c.default)},330878,a=>{"use strict";var b=a.i(800717),c=a.i(118845),d=a.i(40953),e=(0,b.cache)(function(a,b){return function({_cache:a=(0,c.b)(),_formatters:b=(0,c.c)(a),getMessageFallback:e=d.d,messages:f,namespace:g,onError:h=d.b,...i}){return function({messages:a,namespace:b,...c},e){return a=a["!"],b=(0,d.r)(b,"!"),(0,d.a)({...c,messages:a,namespace:b})}({...i,onError:h,cache:a,formatters:b,getMessageFallback:e,messages:{"!":f},namespace:g?`!.${g}`:"!"},0)}({...a,namespace:b})});a.s(["default",()=>e],330878)},442979,a=>{"use strict";var b=a.i(330878),c=a.i(767228),d=a.i(800717)["use".trim()];function e(...[a]){let f=function(a){var b=(0,c.default)();try{return d(b)}catch(b){throw b instanceof TypeError&&b.message.includes("Cannot read properties of null (reading 'use')")?Error(`\`${a}\` is not callable within an async component. Please refer to https://next-intl.dev/docs/environments/server-client-components#async-components`,{cause:b}):b}}("useTranslations");return(0,b.default)(f,a)}a.s(["useTranslations",()=>e],442979)}];
2
2
 
3
3
  //# sourceMappingURL=%5Broot-of-the-server%5D__a6942102._.js.map