bun-query-builder 0.2.54 → 0.2.55
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/cli.js +2 -2
- package/dist/{chunk-wwssp8h1.js → chunk-5vqqnp0w.js} +1 -1
- package/dist/{chunk-fkjeeh31.js → chunk-7e64yq76.js} +2 -2
- package/dist/{chunk-yw12p1mp.js → chunk-9ps7fkza.js} +59 -59
- package/dist/chunk-gp6krpcs.js +2 -0
- package/dist/{chunk-c6mb5jxz.js → chunk-x8tfs1sw.js} +1 -1
- package/dist/{chunk-605xwkdk.js → chunk-y718nsbf.js} +1 -1
- package/dist/client.d.ts +35 -0
- package/dist/src/browser.js +1 -1
- package/dist/src/dynamodb/index.js +1 -1
- package/dist/src/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-h8hxz607.js +0 -2
package/dist/bin/cli.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import{
|
|
3
|
+
import{C as V6,D as W6,E as D6,F as L6,G as M6,H as w6,I as P6,J as N6,K as O6,L as T6,M as x6,N as B6,O as E6,P as b6,Q as I6,R as A6,S as R6,W as C6,X as k6,da as l,ea as r,fa as a,ja as h6,ka as v6,la as y6,ma as S6,n as K6,na as g6,oa as _6,pa as f6,qa as m6,ra as s,sa as t,ta as d6,ua as u6,va as i6,wa as c6,xa as n6,ya as p6,za as l6}from"../chunk-9ps7fkza.js";import"../chunk-7e64yq76.js";import"../chunk-y718nsbf.js";import{rc as K}from"../chunk-x8tfs1sw.js";import{existsSync as r6}from"fs";import S from"fs/promises";import e from"os";import g from"path";import T from"process";import{EventEmitter as a6}from"events";import N from"process";import z6 from"process";import d from"process";import k from"process";import E from"process";import Z6 from"tty";import S4,{stdin as Dz,stdout as Lz}from"process";import Q6,{stdin as f4,stdout as m4}from"process";import d4 from"readline";class j6{configPath;config=null;events=[];retryCount=0;maxRetries=3;retryDelayMs=1000;constructor(){let z=e.homedir(),q=g.join(z,".config","clapp");this.configPath=g.join(q,"telemetry.json")}async isEnabled(){if(T.env.DO_NOT_TRACK==="1"||T.env.DO_NOT_TRACK==="true")return!1;if(T.env.NO_TELEMETRY==="1"||T.env.NO_TELEMETRY==="true")return!1;return(await this.loadConfig()).enabled}async enable(){let z=await this.loadConfig();if(z.enabled=!0,!z.userId)z.userId=this.generateUserId();await this.saveConfig(z)}async disable(){let z=await this.loadConfig();z.enabled=!1,await this.saveConfig(z)}async track(z,q){if(!await this.isEnabled())return;let Z={event:z,...q,timestamp:Date.now(),platform:e.platform(),nodeVersion:T.version};if(this.events.push(Z),this.events.length>=10)await this.send()}async trackCommand(z,q){await this.track("command",{command:z,duration:q})}async trackError(z,q){await this.track("error",{error:z,command:q})}async send(){if(!await this.isEnabled()||this.events.length===0)return!0;try{this.events=[],this.retryCount=0;let q=await this.loadConfig();return q.lastSent=Date.now(),await this.saveConfig(q),!0}catch{if(this.retryCount<this.maxRetries){this.retryCount++;let q=this.retryDelayMs*2**(this.retryCount-1);return await this.sleep(q),this.send()}return this.events=[],this.retryCount=0,!1}}async flush(){if(this.events.length===0)return!0;return this.send()}sleep(z){return new Promise((q)=>setTimeout(q,z))}async status(){let z=await this.loadConfig();return{enabled:z.enabled,doNotTrack:T.env.DO_NOT_TRACK==="1"||T.env.DO_NOT_TRACK==="true",eventsQueued:this.events.length,lastSent:z.lastSent}}async loadConfig(){if(this.config)return this.config;try{if(r6(this.configPath)){let z=await S.readFile(this.configPath,"utf-8");return this.config=JSON.parse(z),this.config}}catch{}return this.config={enabled:!1},this.config}async saveConfig(z){this.config=z;try{let q=g.dirname(this.configPath);await S.mkdir(q,{recursive:!0}),await S.writeFile(this.configPath,JSON.stringify(z,null,2),"utf-8")}catch{}}generateUserId(){let z=Math.random().toString(36).substring(2,15),q=Date.now().toString(36);return`${z}-${q}`}}var $z=new j6;function m(z){return z.replace(/[<[].+/,"").trim()}function s6(z){let q=/<([^>]+)>/g,J=/\[([^\]]+)\]/g,Z=[],$=(X)=>{let Q=!1,j=X[1];if(j.startsWith("..."))j=j.slice(3),Q=!0;return{required:X[0].startsWith("<"),value:j,variadic:Q}},Y;while(Y=q.exec(z))Z.push($(Y));let F;while(F=J.exec(z))Z.push($(F));return Z}function t6(z){let q={alias:{},boolean:[]};for(let[J,Z]of z.entries()){if(Z.names.length>1)q.alias[Z.names[0]]=Z.names.slice(1);if(Z.isBoolean)if(Z.negated){if(!z.some((Y,F)=>{return F!==J&&Y.names.some((X)=>Z.names.includes(X))&&typeof Y.required==="boolean"}))q.boolean.push(Z.names[0])}else q.boolean.push(Z.names[0])}return q}function q6(z){return z.reduce((q,J)=>q.length>=J.length?q:J,"")}function _(z,q){return z.length>=q?z:`${z}${" ".repeat(q-z.length)}`}function C(z){return z.replace(/([a-z])-([a-z])/g,(q,J,Z)=>{return J+Z.toUpperCase()})}function o6(z,q,J){let Z=0,$=q.length,Y=z,F;for(;Z<$;++Z)F=Y[q[Z]],Y=Y[q[Z]]=Z===$-1?J:F!=null?F:!!~q[Z+1].indexOf(".")||!(+q[Z+1]>-1)?{}:[]}function e6(z,q){for(let J of Object.keys(q)){let Z=q[J];if(Z.shouldTransform){if(z[J]=Array.prototype.concat.call([],z[J]),typeof Z.transformFunction==="function")z[J]=z[J].map(Z.transformFunction)}}}function z4(z){let q=/([^\\/]+)$/.exec(z);return q?q[1]:""}function b(z){return z.split(".").map((q,J)=>{return J===0?C(q):q}).join(".")}class I extends Error{exitCode=2;isUsageError=!0;usage;constructor(z,q){super(z);if(this.name=this.constructor.name,q!==void 0)this.usage=q;if(typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,this.constructor);else this.stack=Error(z).stack}format(z=!1){if(z&&this.stack)return`${this.message}
|
|
4
4
|
|
|
5
5
|
Stack trace:
|
|
6
6
|
${this.stack}`;return this.message}}function q4(z){if(z instanceof I)return!0;return!!z&&typeof z==="object"&&z.name==="ClappError"&&typeof z.message==="string"}function J4(){let{env:z}=z6,{TERM:q,TERM_PROGRAM:J}=z;if(z6.platform!=="win32")return q!=="linux";return Boolean(z.WT_SESSION)||Boolean(z.TERMINUS_SUBLIME)||z.ConEmuTask==="{cmd::Cmder}"||J==="Terminus-Sublime"||J==="vscode"||q==="xterm-256color"||q==="alacritty"||q==="rxvt-unicode"||q==="rxvt-unicode-256color"||z.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var y="\x1B",L=`${y}[`;var P={to(z,q){if(!q)return`${L}${z+1}G`;return`${L}${q+1};${z+1}H`},move(z,q){let J="";if(z<0)J+=`${L}${-z}D`;else if(z>0)J+=`${L}${z}C`;if(q<0)J+=`${L}${-q}A`;else if(q>0)J+=`${L}${q}B`;return J},up:(z=1)=>`${L}${z}A`,down:(z=1)=>`${L}${z}B`,forward:(z=1)=>`${L}${z}C`,backward:(z=1)=>`${L}${z}D`,nextLine:(z=1)=>`${L}E`.repeat(z),prevLine:(z=1)=>`${L}F`.repeat(z),left:`${L}G`,hide:`${L}?25l`,show:`${L}?25h`,save:`${y}7`,restore:`${y}8`};var f={screen:`${L}2J`,up:(z=1)=>`${L}1J`.repeat(z),down:(z=1)=>`${L}J`.repeat(z),line:`${L}2K`,lineEnd:`${L}K`,lineStart:`${L}1K`,lines(z){let q="";for(let J=0;J<z;J++)q+=this.line+(J<z-1?P.up():"");if(z)q+=P.left;return q}},Xz={screen:`${y}c`};function Z4(z,q){let J=[];for(let Z=0;Z<=q.length;Z++)J[Z]=[Z];for(let Z=0;Z<=z.length;Z++)J[0][Z]=Z;for(let Z=1;Z<=q.length;Z++)for(let $=1;$<=z.length;$++)if(q.charAt(Z-1)===z.charAt($-1))J[Z][$]=J[Z-1][$-1];else J[Z][$]=Math.min(J[Z-1][$-1]+1,J[Z][$-1]+1,J[Z-1][$]+1);return J[q.length][z.length]}function X6(z,q,J=2,Z=3){return q.map(($)=>({cmd:$,distance:Z4(z,$)})).filter(({distance:$})=>$<=J).sort(($,Y)=>$.distance-Y.distance).slice(0,Z).map(({cmd:$})=>$)}function $4(z,q={}){let J={_:[]},Z=q.alias||{},$=new Set(q.boolean||[]),Y={};for(let X of Object.keys(Z))for(let Q of Z[X])Y[Q]=X;for(let X of $)if(Z[X])for(let Q of Z[X])$.add(Q);function F(X,Q){let j=Y[X]||X;if(J[j]=Q,Z[j])for(let U of Z[j])J[U]=Q;if(Y[X]&&Z[Y[X]])for(let U of Z[Y[X]])J[U]=Q;J[X]=Q}for(let X=0;X<z.length;X++){let Q=z[X];if(Q==="--"){J._.push(...z.slice(X+1));break}if(Q.startsWith("--")){let j=Q.indexOf("=");if(j!==-1){let U=C(Q.slice(2,j)),H=Q.slice(j+1);F(U,H)}else{let U=Q.slice(2);if(U.startsWith("no-")){let w=C(U.slice(3));F(w,!1);continue}let H=C(U),V=Y[H]||H;if($.has(V)||$.has(H))F(H,!0);else{let w=z[X+1];if(w!==void 0&&!w.startsWith("-"))F(H,w),X++;else F(H,!0)}}}else if(Q.startsWith("-")&&Q.length>1){let j=Q.slice(1);for(let U=0;U<j.length;U++){let H=j[U],V=Y[H]||H;if(U===j.length-1&&!$.has(V)&&!$.has(H)){let w=z[X+1];if(w!==void 0&&!w.startsWith("-"))F(H,w),X++;else F(H,!0)}else F(H,!0)}}else J._.push(Q)}return J}class U6{rawName;description;name;names;isBoolean;required;config;negated;constructor(z,q,J){if(this.rawName=z,this.description=q,this.config=Object.assign({},J),z=z.replace(/\.\*/g,""),this.negated=!1,this.names=m(z).split(",").map((Z)=>{let $=Z.trim().replace(/^-{1,2}/,"");if($.startsWith("no-"))this.negated=!0,$=$.replace(/^no-/,"");return b($)}).sort((Z,$)=>Z.length>$.length?1:-1),this.name=this.names[this.names.length-1],this.negated&&this.config.default==null)this.config.default=!0;if(z.includes("<"))this.required=!0;else if(z.includes("["))this.required=!1;else this.isBoolean=!0}}var Fz=d.argv,Q4=`${d.platform}-${d.arch} bun-v${typeof Bun<"u"?Bun.version:"unknown"}`,J6=k.argv,Y4=`${k.platform}-${k.arch} node-${k.version}`;class u{rawName;description;config;cli;options;aliasNames;name;namespace;args;commandAction;usageText;versionNumber;examples;helpCallback;globalCommand;beforeHooks;afterHooks;middleware;constructor(z,q,J,Z){this.rawName=z,this.description=q,this.config=J,this.cli=Z,this.options=[],this.aliasNames=[],this.name=m(z);let $=m(z),Y=$.indexOf(":");if(Y>0)this.namespace=$.substring(0,Y),this.name=$.substring(Y+1);if(this.args=s6(z),this.examples=[],this.beforeHooks=[],this.afterHooks=[],this.middleware=[],!J)this.config={}}usage(z){return this.usageText=z,this}allowUnknownOptions(){return this.config.allowUnknownOptions=!0,this}ignoreOptionDefaultValue(){return this.config.ignoreOptionDefaultValue=!0,this}version(z,q="-v, --version"){return this.versionNumber=z,this.option(q,"Display version number"),this}example(z){return this.examples.push(z),this}option(z,q,J){let Z=new U6(z,q,J);return this.options.push(Z),this}alias(z){return this.aliasNames.push(z),this}action(z){return this.commandAction=z,this}before(z){return this.beforeHooks.push(z),this}after(z){return this.afterHooks.push(z),this}use(z){return this.middleware.push(z),this}isMatched(z){if(this.aliasNames.includes(z))return!0;if(this.namespace)return`${this.namespace}:${this.name}`===z;return this.name===z}get isDefaultCommand(){return this.name===""||this.aliasNames.includes("!")}get isGlobalCommand(){return this instanceof i}get displayName(){return this.namespace?`${this.namespace}:${this.name}`:this.name}hasOption(z){let q=b(z.split(".")[0]);return!!this.options.find((J)=>{return J.names.some((Z)=>b(Z)===q)})}outputHelp(){let{name:z,commands:q}=this.cli,{versionNumber:J,options:Z,helpCallback:$}=this.cli.globalCommand,Y=[{body:`${z}${J?`/${J}`:""}`}];if(Y.push({title:"Usage",body:` $ ${z} ${this.usageText||this.rawName}`}),(this.isGlobalCommand||this.isDefaultCommand)&&q.length>0){let j=q6(q.map((M)=>M.rawName)),U=new Map,H=[];for(let M of q)if(M.namespace){if(!U.has(M.namespace))U.set(M.namespace,[]);U.get(M.namespace).push(M)}else H.push(M);let V="";if(H.sort((M,A)=>M.rawName<A.rawName?-1:M.rawName>A.rawName?1:0),H.length>0)V+=H.map((M)=>{return` ${_(M.rawName,j.length)} ${M.description}`}).join(`
|
|
@@ -38,7 +38,7 @@ Run \`${this.name??"cli"} --help\` for usage.`;N.stderr.write(`${J}${q}${Z}
|
|
|
38
38
|
`).length-1;this.output.write(P.move(-999,z*-1))}render(){let z=Y6(this._render(this)??"",Q6.stdout.columns,{hard:!0,trim:!1});if(z===this._prevFrame)return;if(this.state==="initial")this.output.write(P.hide);else{let q=_4(this._prevFrame,z);if(this.restoreCursor(),q&&q?.length===1){let J=q[0];this.output.write(P.move(0,J)),this.output.write(f.lines(1));let Z=z.split(`
|
|
39
39
|
`);this.output.write(Z[J]),this._prevFrame=z,this.output.write(P.move(0,Z.length-J-1));return}if(q&&q?.length>1){let J=q[0];this.output.write(P.move(0,J)),this.output.write(f.down());let $=z.split(`
|
|
40
40
|
`).slice(J);this.output.write($.join(`
|
|
41
|
-
`)),this._prevFrame=z;return}this.output.write(f.down())}if(this.output.write(z),this.state==="initial")this.state="active";this._prevFrame=z}}function c4(z,q){if(z===void 0)return 0;if(q.length===0)return 0;let Z=q.findIndex(($)=>$.value===z);return Z!==-1?Z:0}function n4(z,q){return(q.label??String(q.value)).toLowerCase().includes(z.toLowerCase())}function p4(z,q){if(!q)return;if(z)return q;return q[0]}class l4 extends n{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#z=0;#J="";#Z;#q;get cursor(){return this.#z}get userInputWithCursor(){if(!this.userInput)return h.inverse(h.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let z=this.userInput.slice(0,this._cursor),[q,...J]=this.userInput.slice(this._cursor);return`${z}${h.inverse(q)}${J.join("")}`}get options(){if(typeof this.#q==="function")return this.#q();return this.#q}constructor(z){super(z);this.#q=z.options;let q=this.options;this.filteredOptions=[...q],this.multiple=z.multiple===!0,this.#Z=z.filter??n4;let J;if(z.initialValue&&Array.isArray(z.initialValue))if(this.multiple)J=z.initialValue;else J=z.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)J=[this.options[0].value];if(J)for(let Z of J){let $=q.findIndex((Y)=>Y.value===Z);if($!==-1)this.toggleSelected(Z),this.#z=$}this.focusedValue=this.options[this.#z]?.value,this.on("key",(Z,$)=>this.#$(Z,$)),this.on("userInput",(Z)=>this.#Q(Z))}_isActionKey(z,q){return z==="\t"||this.multiple&&this.isNavigating&&q.name==="space"&&z!==void 0&&z!==""}#$(z,q){let J=q.name==="up",Z=q.name==="down",$=q.name==="return";if(J||Z){if(this.#z=Math.max(0,Math.min(this.#z+(J?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if($)this.value=p4(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(q.name==="tab"||this.isNavigating&&q.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(z){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(z))this.selectedValues=this.selectedValues.filter((q)=>q!==z);else this.selectedValues=[...this.selectedValues,z];else this.selectedValues=[z]}#Q(z){if(z!==this.#J){this.#J=z;let q=this.options;if(z)this.filteredOptions=q.filter((J)=>this.#Z(z,J));else this.filteredOptions=[...q];if(this.#z=c4(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class r4 extends n{options;cursor=0;#z;getGroupItems(z){return this.options.filter((q)=>q.group===z)}isGroupSelected(z){let q=this.getGroupItems(z),J=this.value;if(J===void 0)return!1;return q.every((Z)=>J.includes(Z.value))}toggleValue(){let z=this.options[this.cursor];if(this.value===void 0)this.value=[];if(z.group===!0){let q=String(z.value),J=this.getGroupItems(q);if(this.isGroupSelected(q))this.value=this.value.filter((Z)=>J.findIndex(($)=>$.value===Z)===-1);else this.value=[...this.value,...J.map((Z)=>Z.value)];this.value=Array.from(new Set(this.value))}else{let q=this.value.includes(z.value);this.value=q?this.value.filter((J)=>J!==z.value):[...this.value,z.value]}}constructor(z){super(z,!1);let{options:q}=z;this.#z=z.selectableGroups!==!1,this.options=Object.entries(q).flatMap(([J,Z])=>[{value:J,group:!0,label:J},...Z.map(($)=>({...$,group:J}))]),this.value=[...z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:J})=>J===z.cursorAt),this.#z?0:1),this.on("cursor",(J)=>{switch(J){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Z=this.options[this.cursor]?.group===!0;if(!this.#z&&Z)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Z=this.options[this.cursor]?.group===!0;if(!this.#z&&Z)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var a4=J4();var W=(z,q)=>a4?z:q,Nz=W("\u25C6","*"),Oz=W("\u25A0","x"),Tz=W("\u25B2","x"),xz=W("\u25C7","o"),Bz=W("\u250C","T"),s4=W("\u2502","|"),Ez=W("\u2514","\u2014"),bz=W("\u25CF",">"),Iz=W("\u25CB"," "),Az=W("\u25FB","[\u2022]"),Rz=W("\u25FC","[+]"),Cz=W("\u25FB","[ ]"),kz=W("\u25AA","\u2022"),hz=W("\u2500","-"),vz=W("\u256E","+"),yz=W("\u251C","+"),Sz=W("\u256F","+"),gz=W("\u25CF","\u2022"),_z=W("\u25C6","*"),fz=W("\u25B2","!"),mz=W("\u25A0","x");var dz={light:W("\u2500","-"),heavy:W("\u2501","="),block:W("\u2588","#")};function t4(){return`${h.gray(s4)} `}var uz=t4();var p="0.2.
|
|
41
|
+
`)),this._prevFrame=z;return}this.output.write(f.down())}if(this.output.write(z),this.state==="initial")this.state="active";this._prevFrame=z}}function c4(z,q){if(z===void 0)return 0;if(q.length===0)return 0;let Z=q.findIndex(($)=>$.value===z);return Z!==-1?Z:0}function n4(z,q){return(q.label??String(q.value)).toLowerCase().includes(z.toLowerCase())}function p4(z,q){if(!q)return;if(z)return q;return q[0]}class l4 extends n{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#z=0;#J="";#Z;#q;get cursor(){return this.#z}get userInputWithCursor(){if(!this.userInput)return h.inverse(h.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let z=this.userInput.slice(0,this._cursor),[q,...J]=this.userInput.slice(this._cursor);return`${z}${h.inverse(q)}${J.join("")}`}get options(){if(typeof this.#q==="function")return this.#q();return this.#q}constructor(z){super(z);this.#q=z.options;let q=this.options;this.filteredOptions=[...q],this.multiple=z.multiple===!0,this.#Z=z.filter??n4;let J;if(z.initialValue&&Array.isArray(z.initialValue))if(this.multiple)J=z.initialValue;else J=z.initialValue.slice(0,1);else if(!this.multiple&&this.options.length>0)J=[this.options[0].value];if(J)for(let Z of J){let $=q.findIndex((Y)=>Y.value===Z);if($!==-1)this.toggleSelected(Z),this.#z=$}this.focusedValue=this.options[this.#z]?.value,this.on("key",(Z,$)=>this.#$(Z,$)),this.on("userInput",(Z)=>this.#Q(Z))}_isActionKey(z,q){return z==="\t"||this.multiple&&this.isNavigating&&q.name==="space"&&z!==void 0&&z!==""}#$(z,q){let J=q.name==="up",Z=q.name==="down",$=q.name==="return";if(J||Z){if(this.#z=Math.max(0,Math.min(this.#z+(J?-1:1),this.filteredOptions.length-1)),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)this.selectedValues=[this.focusedValue];this.isNavigating=!0}else if($)this.value=p4(this.multiple,this.selectedValues);else if(this.multiple)if(this.focusedValue!==void 0&&(q.name==="tab"||this.isNavigating&&q.name==="space"))this.toggleSelected(this.focusedValue);else this.isNavigating=!1;else{if(this.focusedValue)this.selectedValues=[this.focusedValue];this.isNavigating=!1}}deselectAll(){this.selectedValues=[]}toggleSelected(z){if(this.filteredOptions.length===0)return;if(this.multiple)if(this.selectedValues.includes(z))this.selectedValues=this.selectedValues.filter((q)=>q!==z);else this.selectedValues=[...this.selectedValues,z];else this.selectedValues=[z]}#Q(z){if(z!==this.#J){this.#J=z;let q=this.options;if(z)this.filteredOptions=q.filter((J)=>this.#Z(z,J));else this.filteredOptions=[...q];if(this.#z=c4(this.focusedValue,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#z]?.value,!this.multiple)if(this.focusedValue!==void 0)this.toggleSelected(this.focusedValue);else this.deselectAll()}}}class r4 extends n{options;cursor=0;#z;getGroupItems(z){return this.options.filter((q)=>q.group===z)}isGroupSelected(z){let q=this.getGroupItems(z),J=this.value;if(J===void 0)return!1;return q.every((Z)=>J.includes(Z.value))}toggleValue(){let z=this.options[this.cursor];if(this.value===void 0)this.value=[];if(z.group===!0){let q=String(z.value),J=this.getGroupItems(q);if(this.isGroupSelected(q))this.value=this.value.filter((Z)=>J.findIndex(($)=>$.value===Z)===-1);else this.value=[...this.value,...J.map((Z)=>Z.value)];this.value=Array.from(new Set(this.value))}else{let q=this.value.includes(z.value);this.value=q?this.value.filter((J)=>J!==z.value):[...this.value,z.value]}}constructor(z){super(z,!1);let{options:q}=z;this.#z=z.selectableGroups!==!1,this.options=Object.entries(q).flatMap(([J,Z])=>[{value:J,group:!0,label:J},...Z.map(($)=>({...$,group:J}))]),this.value=[...z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:J})=>J===z.cursorAt),this.#z?0:1),this.on("cursor",(J)=>{switch(J){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let Z=this.options[this.cursor]?.group===!0;if(!this.#z&&Z)this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let Z=this.options[this.cursor]?.group===!0;if(!this.#z&&Z)this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;break}case"space":this.toggleValue();break}})}}var a4=J4();var W=(z,q)=>a4?z:q,Nz=W("\u25C6","*"),Oz=W("\u25A0","x"),Tz=W("\u25B2","x"),xz=W("\u25C7","o"),Bz=W("\u250C","T"),s4=W("\u2502","|"),Ez=W("\u2514","\u2014"),bz=W("\u25CF",">"),Iz=W("\u25CB"," "),Az=W("\u25FB","[\u2022]"),Rz=W("\u25FC","[+]"),Cz=W("\u25FB","[ ]"),kz=W("\u25AA","\u2022"),hz=W("\u2500","-"),vz=W("\u256E","+"),yz=W("\u251C","+"),Sz=W("\u256F","+"),gz=W("\u25CF","\u2022"),_z=W("\u25C6","*"),fz=W("\u25B2","!"),mz=W("\u25A0","x");var dz={light:W("\u2500","-"),heavy:W("\u2501","="),block:W("\u2588","#")};function t4(){return`${h.gray(s4)} `}var uz=t4();var p="0.2.55";var G=new c("query-builder");G.command("introspect <dir>","Load models and print inferred schema").option("--verbose","Enable verbose logging").example("query-builder introspect ./app/Models --verbose").action(async(z,q)=>{await R6(z,q)});G.command("introspect:db","Reverse-introspect the live database into defineModel() source (#1047)").option("--table <table>","Limit to a single table (repeatable)").example("query-builder introspect:db > app/Models/generated.ts").action(async(z)=>{let q=z?.table,J=q?Array.isArray(q)?q:[q]:void 0,Z=await C6({tables:J});console.log(`import { defineModel } from 'bun-query-builder'
|
|
42
42
|
|
|
43
43
|
${Z.map(($)=>$.source).join(`
|
|
44
44
|
`)}`)});G.command("sql <dir> <table>","Build a sample query for a table").option("--limit <n>","Limit rows",{default:10}).example("query-builder sql ./app/Models users --limit 5").action(async(z,q,J)=>{await i6(z,q,J)});G.command("ping","Test database connectivity (uses environment variables)").example("query-builder ping").action(async()=>{await _6()});G.command("wait-ready","Wait for database to become ready").option("--attempts <n>","Number of attempts",{default:10}).option("--delay <ms>","Delay between attempts",{default:100}).example("query-builder wait-ready --attempts 30 --delay 250").action(async(z)=>{try{await l6(z)}catch{let q=await import("process");q.default.exitCode=1}});G.command("unsafe <sql>","Execute an unsafe SQL string (one statement with params)").option("--params <json>","JSON array of parameters").example('query-builder unsafe "SELECT * FROM users WHERE id = $1" --params "[1]"').action(async(z,q)=>{await c6(z,q)});G.command("file <path>","Execute a SQL file (supports $1, $2 params)").option("--params <json>","JSON array of parameters").example("query-builder file ./migrations/seed.sql").example('query-builder file ./reports/top.sql --params "[30]"').action(async(z,q)=>{await b6(z,q)});G.command("migrate <dir>","Generate SQL migrations from models").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--apply","Execute the generated SQL against the database").option("--full","Force full migration SQL instead of incremental diff").example("query-builder migrate ./app/Models --dialect postgres").action(async(z,q)=>{try{await l(z,{dialect:q.dialect,state:q.state,apply:q.apply,full:q.full}),await r()}catch(J){console.error("-- Migration failed:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("explain <sql>","Explain a query").example('query-builder explain "SELECT * FROM users WHERE active = true"').action(async(z)=>{await E6(z)});G.command("query:explain-all <path>","Run EXPLAIN on all SQL files in a directory").option("--verbose","Enable verbose output").option("--json","Output as JSON").example("query-builder query:explain-all ./queries").example("query-builder query:explain-all ./queries/users.sql").action(async(z,q)=>{try{await f6(z,{verbose:q.verbose,json:q.json})}catch(J){console.error("-- Explain all failed:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("relation:diagram","Generate relationship diagram from models").option("--dir <path>","Models directory (defaults to app/Models)").option("--format <fmt>","Output format (mermaid|dot)",{default:"mermaid"}).option("--output <path>","Output file path").option("--verbose","Enable verbose output").example("query-builder relation:diagram").example("query-builder relation:diagram --format dot --output schema.dot").example("query-builder relation:diagram --output schema.mmd").action(async(z)=>{try{await m6({dir:z.dir,format:z.format,output:z.output,verbose:z.verbose})}catch(q){console.error("-- Diagram generation failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("migrate:fresh <dir>","Reset database and run all migrations").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").option("--full","Force full migration SQL instead of incremental diff").example("query-builder migrate:fresh ./app/Models --dialect postgres").action(async(z,q)=>{try{console.log("-- Resetting database..."),await a(z,{dialect:q.dialect,state:q.state}),console.log("-- Generating fresh migrations..."),await l(z,{dialect:q.dialect,state:q.state,full:q.full}),console.log("-- Executing migrations..."),await r()}catch(J){console.error("-- Migrate fresh failed:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("reset <dir>","Drop all tables and reset database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file (defaults to <dir>/.qb-migrations.<dialect>.json)").example("query-builder reset ./app/Models --dialect postgres").action(async(z,q)=>{try{await a(z,{dialect:q.dialect,state:q.state})}catch(J){console.error("-- Reset failed:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("seed","Run database seeders").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder seed").example("query-builder seed --class UserSeeder").example("query-builder seed --dir ./database/seeders").action(async(z)=>{try{if(z.class)await t(z.class,{verbose:z.verbose});else await s({seedersDir:z.dir,verbose:z.verbose})}catch(q){console.error("-- Seeding failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("db:seed","Run database seeders (alias for seed)").option("--dir <path>","Path to seeders directory (defaults to database/seeders)").option("--class <name>","Run a specific seeder class").option("--verbose","Enable verbose logging").example("query-builder db:seed").example("query-builder db:seed --class UserSeeder").action(async(z)=>{try{if(z.class)await t(z.class,{verbose:z.verbose});else await s({seedersDir:z.dir,verbose:z.verbose})}catch(q){console.error("-- Seeding failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("make:seeder <name>","Create a new seeder file").example("query-builder make:seeder User").example("query-builder make:seeder UserSeeder").action(async(z)=>{try{await d6(z)}catch(q){console.error("-- Failed to create seeder:",q);let J=await import("process");J.default.exitCode=1}});G.command("db:fresh","Drop all tables, re-run migrations and seed the database").option("--models <path>","Path to models directory (defaults to app/Models)").option("--seeders <path>","Path to seeders directory (defaults to database/seeders)").option("--verbose","Enable verbose logging").example("query-builder db:fresh").example("query-builder db:fresh --models ./app/Models --seeders ./database/seeders").action(async(z)=>{try{await u6({modelsDir:z.models,seedersDir:z.seeders,verbose:z.verbose})}catch(q){console.error("-- Database fresh failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("make:model <name>","Create a new model file").option("--table <name>","Table name (defaults to plural of model name)").option("--dir <path>","Models directory (defaults to app/Models)").option("--timestamps","Include timestamp fields (default: true)").example("query-builder make:model User").example("query-builder make:model Post --table=blog_posts").action(async(z,q)=>{try{await k6(z,{table:q.table,dir:q.dir,timestamps:q.timestamps})}catch(J){console.error("-- Failed to create model:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("model:show <name>","Show detailed model information").option("--dir <path>","Models directory (defaults to app/Models)").option("--json","Output as JSON").option("--verbose","Enable verbose output").example("query-builder model:show User").example("query-builder model:show Post --json").action(async(z,q)=>{try{await g6(z,{dir:q.dir,json:q.json,verbose:q.verbose})}catch(J){console.error("-- Failed to show model:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("migrate:status","Show migration status").example("query-builder migrate:status").action(async()=>{try{await y6()}catch(z){console.error("-- Failed to get migration status:",z);let q=await import("process");q.default.exitCode=1}});G.command("migrate:list","List all migrations (alias for migrate:status)").example("query-builder migrate:list").action(async()=>{try{await S6()}catch(z){console.error("-- Failed to list migrations:",z);let q=await import("process");q.default.exitCode=1}});G.command("migrate:rollback","Rollback migrations").option("--steps <n>","Number of migrations to rollback",{default:1}).option("--no-reverse-schema","Only remove the migration records; leave the schema alone").option("--delete-files","Also delete the rolled-back migration files from disk").example("query-builder migrate:rollback").example("query-builder migrate:rollback --steps 2").example("query-builder migrate:rollback --no-reverse-schema").action(async(z)=>{try{await v6({steps:Number(z.steps),reverseSchema:z.reverseSchema,deleteFiles:Boolean(z.deleteFiles)})}catch(q){console.error("-- Rollback failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("migrate:generate [dir]","Generate migration from model changes").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--state <path>","Path to migration state file").option("--apply","Execute the generated SQL").option("--full","Force full migration SQL").example("query-builder migrate:generate").example("query-builder migrate:generate ./app/Models --dialect postgres").action(async(z,q)=>{try{await h6(z,{dialect:q?.dialect,state:q?.state,apply:q?.apply,full:q?.full})}catch(J){console.error("-- Generate migration failed:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("db:info","Show database information and statistics").example("query-builder db:info").action(async()=>{try{await O6()}catch(z){console.error("-- Failed to get database info:",z);let q=await import("process");q.default.exitCode=1}});G.command("db:stats","Show database statistics (alias for db:info)").example("query-builder db:stats").action(async()=>{try{await T6()}catch(z){console.error("-- Failed to get database stats:",z);let q=await import("process");q.default.exitCode=1}});G.command("db:wipe","Drop all tables from the database").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--force","Skip confirmation prompt").option("--verbose","Enable verbose output").example("query-builder db:wipe").example("query-builder db:wipe --force").action(async(z)=>{try{await B6({dialect:z.dialect,force:z.force,verbose:z.verbose})}catch(q){console.error("-- Wipe failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("db:optimize","Optimize database tables (VACUUM, ANALYZE, OPTIMIZE)").option("--dialect <d>","Dialect (postgres|mysql|sqlite) \u2014 defaults to the configured dialect").option("--aggressive","Use aggressive optimization (VACUUM FULL for postgres)").option("--tables <tables>","Comma-separated list of tables to optimize").option("--verbose","Enable verbose output").example("query-builder db:optimize").example("query-builder db:optimize --aggressive").example("query-builder db:optimize --tables users,posts").action(async(z)=>{try{await x6({dialect:z.dialect,aggressive:z.aggressive,tables:z.tables?z.tables.split(","):void 0,verbose:z.verbose})}catch(q){console.error("-- Optimize failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("console","Start interactive query console").example("query-builder console").action(async()=>{try{await L6()}catch(z){console.error("-- Console failed:",z);let q=await import("process");q.default.exitCode=1}});G.command("tinker","Start interactive query console (alias for console)").example("query-builder tinker").action(async()=>{try{await M6()}catch(z){console.error("-- Tinker failed:",z);let q=await import("process");q.default.exitCode=1}});G.command("inspect <table>","Inspect a table structure").option("--verbose","Enable verbose output",{default:!0}).example("query-builder inspect users").action(async(z,q)=>{try{await I6(z,{verbose:q.verbose})}catch(J){console.error("-- Failed to inspect table:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("table:info <table>","Show table information (alias for inspect)").option("--verbose","Enable verbose output",{default:!0}).example("query-builder table:info users").action(async(z,q)=>{try{await A6(z,{verbose:q.verbose})}catch(J){console.error("-- Failed to get table info:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("cache:clear","Clear the query cache").example("query-builder cache:clear").action(async()=>{try{await V6()}catch(z){console.error("-- Failed to clear cache:",z);let q=await import("process");q.default.exitCode=1}});G.command("cache:stats","Show cache statistics").example("query-builder cache:stats").action(async()=>{try{await W6()}catch(z){console.error("-- Failed to get cache stats:",z);let q=await import("process");q.default.exitCode=1}});G.command("cache:config","Configure cache settings").option("--size <n>","Set maximum cache size").example("query-builder cache:config --size 500").action(async(z)=>{try{await D6({size:z.size})}catch(q){console.error("-- Failed to configure cache:",q);let J=await import("process");J.default.exitCode=1}});G.command("benchmark","Run performance benchmarks").option("--operations <ops>","Comma-separated list of operations (select,insert,update,delete,count)").option("--iterations <n>","Number of iterations per operation",{default:1000}).example("query-builder benchmark").example("query-builder benchmark --operations select,insert --iterations 5000").action(async(z)=>{try{await K6({operations:z.operations,iterations:z.iterations?Number(z.iterations):void 0})}catch(q){console.error("-- Benchmark failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("validate:schema [dir]","Validate models against database schema").example("query-builder validate:schema").example("query-builder validate:schema ./app/Models").action(async(z)=>{try{await n6(z)}catch(q){console.error("-- Validation failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("check [dir]","Validate schema (alias for validate:schema)").example("query-builder check").action(async(z)=>{try{await p6(z)}catch(q){console.error("-- Check failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("export <table>","Export data from a table").option("--format <fmt>","Export format (json|csv|sql)",{default:"json"}).option("--output <path>","Output file path").option("--limit <n>","Limit number of rows").example("query-builder export users").example("query-builder export users --format csv --output users.csv").example("query-builder export users --format sql --limit 100").action(async(z,q)=>{try{await w6(z,{format:q.format,output:q.output,limit:q.limit?Number(q.limit):void 0})}catch(J){console.error("-- Export failed:",J);let Z=await import("process");Z.default.exitCode=1}});G.command("import <table> <file>","Import data into a table").option("--format <fmt>","Import format (json|csv)").option("--truncate","Truncate table before import").example("query-builder import users users.json").example("query-builder import users users.csv --truncate").action(async(z,q,J)=>{try{await P6(z,q,{format:J.format,truncate:J.truncate})}catch(Z){console.error("-- Import failed:",Z);let $=await import("process");$.default.exitCode=1}});G.command("dump","Dump database to SQL file").option("--tables <tables>","Comma-separated list of tables to dump").option("--output <path>","Output file path").example("query-builder dump").example("query-builder dump --tables users,posts").example("query-builder dump --output backup.sql").action(async(z)=>{try{await N6({tables:z.tables,output:z.output})}catch(q){console.error("-- Dump failed:",q);let J=await import("process");J.default.exitCode=1}});G.command("version","Show the version of the CLI").action(()=>{console.log(p)});G.version(p);G.help();G.parse();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{pc as Nt,qc as B}from"./chunk-c6mb5jxz.js";import{existsSync as tr}from"fs";import{join as rr}from"path";import ar from"process";import{existsSync as ut,statSync as dt}from"fs";import{join as ir,relative as nr,resolve as ft}from"path";import Ee from"process";import{Buffer as M}from"buffer";import{createCipheriv as or,createDecipheriv as sr,randomBytes as We}from"crypto";import{closeSync as Ie,createReadStream as gt,createWriteStream as lr,existsSync as pe,fsyncSync as pt,openSync as yt,writeFileSync as cr}from"fs";import{access as hr,constants as bt,mkdir as mr,readdir as ye,rename as wt,stat as L,unlink as be,writeFile as Je}from"fs/promises";import{isAbsolute as ur,join as F,resolve as dr}from"path";import g from"process";import{pipeline as fr}from"stream/promises";import{createGzip as Ct}from"zlib";import D from"process";import $ from"process";import we from"process";import{existsSync as Ce}from"fs";import{resolve as ze}from"path";import{existsSync as gr}from"fs";import{existsSync as Ye,mkdirSync as pr,readdirSync as yr,readFileSync as br,writeFileSync as wr}from"fs";import{homedir as H}from"os";import{dirname as vt,resolve as w}from"path";import R from"process";import{existsSync as Cr,readdirSync as vr}from"fs";import{extname as _e,resolve as St}from"path";import Sr from"process";import{spawnSync as fa}from"child_process";import{existsSync as O,readFileSync as ga}from"fs";import{join as j}from"path";import qt from"process";function Ar(e,t){this[e]=kr.bind(null,t)}class at{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let i=this.generateKey(e,r),n=a??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:n,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!ut(e))return!0;return dt(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let i=ut(r)?dt(r):null,n=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:n},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,i)=>a+i.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class it{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),i=new Date;try{let n=await t(),o=performance.now()-a;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),n}catch(n){let o=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),n}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),a=r.reduce((i,n)=>i+n,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Tr(e,t={}){let r=Object.keys(t).sort().map((a)=>`${a}:${t[a]}`).join("|");return r?`${e}:${r}`:e}function Pr(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Nr(e){return e.getStats().size*2}function xr(e,t={}){let r=Ee.cwd();while(r.includes("storage"))r=ft(r,"..");let a=ft(r,e||"");if(t?.relative)return nr(Ee.cwd(),a);return a}function p(){if($.env.NODE_ENV==="test"||$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Rr(){if($.env.NODE_ENV==="test"||$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $<"u"){let e=$.type;if(e==="renderer"||e==="worker")return!1;return!!($.versions&&($.versions.node||$.versions.bun))}return!1}class Rt{async format(e){let t=await Rr(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:D.pid,hostname:t(),environment:D.env.NODE_ENV||"development",platform:D.platform,version:D.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:D.env.NODE_ENV||D.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class He{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...V},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Rt,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??g.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},a=t.timestamp!==void 0;if(a)delete r.timestamp;if(this.config={...this.config,...r,timestamp:a||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Se,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Se};return{...Se,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:V.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let a,i=0,n=3,o=1000;while(i<n)try{try{try{await hr(this.config.logDirectory,bt.F_OK|bt.W_OK)}catch(s){if(s instanceof Error&&"code"in s)if(s.code==="ENOENT")await mr(this.config.logDirectory,{recursive:!0,mode:493});else if(s.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw s;else throw s}}catch(s){throw console.error("Debug: [writeToFile] Failed to create log directory:",s),s}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:M.from(e);try{if(!pe(this.currentLogFile))await Je(this.currentLogFile,"",{mode:420});if(a=yt(this.currentLogFile,"a",420),cr(a,l,{flag:"a"}),pt(a),a!==void 0)Ie(a),a=void 0;if((await L(this.currentLogFile)).size===0){if(await Je(this.currentLogFile,l,{flag:"w",mode:420}),(await L(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(s){let c=s;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(i<n-1){let h=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${n}:`,h);let m=o*2**i;await new Promise((u)=>setTimeout(u,m)),i++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(a!==void 0)try{Ie(a)}catch(s){console.error("Debug: [writeToFile] Error closing file descriptor:",s)}}}catch(l){if(i===n-1){let c=l,h=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),l}i++;let s=o*2**(i-1);await new Promise((c)=>setTimeout(c,s))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(a){throw console.error("Debug: [writeToFile] Error in operation:",a),a}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return F(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return F(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return F(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((a)=>{console.error("Error rotating keys:",a)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let a=Array.from(this.encryptionKeys.entries()).sort(([,o],[,l])=>l.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,n=Math.max(1,i);if(a.length>n)for(let[o]of a.slice(n))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return We(16).toString("hex")}generateKey(){return We(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=We(16),a=or("aes-256-gcm",t,r),i=M.isBuffer(e)?e:M.from(e,"utf8"),n=a.update(i),o=a.final(),l=n.length+o.length,s=a.getAuthTag(),c=M.allocUnsafe(16+l+16);return r.copy(c,0),n.copy(c,16),o.copy(c,16+n.length),s.copy(c,16+l),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let a=Ct(),i=[];a.on("data",(n)=>i.push(n)),a.on("end",()=>t(M.from(M.concat(i)))),a.on("error",r),a.write(e),a.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let e=await L(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,a=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await ye(this.config.logDirectory),n=i.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,c)=>{let h=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),o=n.length>0?Number.parseInt(n[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${o}`;if(await L(r).catch(()=>null))try{if(await wt(r,l),t.compress)try{let s=`${l}.gz`;await this.compressLogFile(l,s),await be(l)}catch(s){console.error("Error compressing rotated file:",s)}if(n.length===0&&!i.some((s)=>s.endsWith(".log.1")))try{let s=`${r}.1`;await Je(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),n=r.replace(/\.log$/,`-${i}.log`);if(await L(r).catch(()=>null))await wt(r,n)}if(this.currentLogFile=a,t.maxFiles){let i=(await ye(this.config.logDirectory)).filter((n)=>n.startsWith(this.name)).sort((n,o)=>o.localeCompare(n));for(let n of i.slice(t.maxFiles))await be(F(this.config.logDirectory,n))}}}async compressLogFile(e,t){let r=gt(e),a=lr(t),i=Ct();await fr(r,i,a)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let a=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(a);console.log(a)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),pe(this.currentLogFile))try{let e=yt(this.currentLogFile,"r+");pt(e),Ie(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ye(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await be(F(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?f.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let e=typeof g.env.NO_COLOR<"u",t=g.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof g.stderr<"u"&&g.stderr.isTTY||typeof g.stdout<"u"&&g.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:i,level:n,showTimestamp:o=!0}=e,l=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(n==="warning")d.push("WARN");else if(n==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)d.push(a.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let s=g.stdout.columns||120,c="";if(n==="warning"||n==="error")c=`${r} ${i}`;else if(n==="info"||n==="success")c=`${r} ${a} ${i}`;else c=`${r} ${a} ${f.cyan(i)}`;if(!o)return c.trim();let h=l(c).trim().length,m=l(t).length,u=Math.max(1,s-2-h-m);return`${c.trim()}${" ".repeat(u)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(n,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):n});let r=/%([sdijfo%])/g,a=0,i=e.replace(r,(n,o)=>{if(o==="%")return"%";if(a>=t.length)return n;let l=t[a++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return n}});if(a<t.length)i+=` ${t.slice(a).map((n)=>typeof n==="object"?JSON.stringify(n,null,2):String(n)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,a,i)=>{let n=f.underline(f.blue(a)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,s="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${n}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${n}\x1B]8;;\x1B\\`;return n}),t=t.replace(/`([^`]+)`/g,(r,a)=>f.bgGray(a)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,a)=>f.bold(a)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,a)=>f.italic(a)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,a)=>f.italic(a)),t=t.replace(/~([^~]+)~/g,(r,a)=>f.strikethrough(a)),t}supportsHyperlinks(){if(p())return!1;let e=g.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=g.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ur(t)||t.startsWith("./")||t.startsWith("../"))t=dr(t);else return null;return pe(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let a=new Date,i=this.formatConsoleTimestamp(a),n=this.formatFileTimestamp(a),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,r);let{consoleText:s,fileText:c}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":Lt[e],u=this.options.showTags!==!1&&this.name?f.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:f.gray(s),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:f.green(s),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.error(d),l){let S=l.split(`
|
|
2
|
+
import{qc as Nt,rc as B}from"./chunk-x8tfs1sw.js";import{existsSync as tr}from"fs";import{join as rr}from"path";import ar from"process";import{existsSync as ut,statSync as dt}from"fs";import{join as ir,relative as nr,resolve as ft}from"path";import Ee from"process";import{Buffer as M}from"buffer";import{createCipheriv as or,createDecipheriv as sr,randomBytes as We}from"crypto";import{closeSync as Ie,createReadStream as gt,createWriteStream as lr,existsSync as pe,fsyncSync as pt,openSync as yt,writeFileSync as cr}from"fs";import{access as hr,constants as bt,mkdir as mr,readdir as ye,rename as wt,stat as L,unlink as be,writeFile as Je}from"fs/promises";import{isAbsolute as ur,join as F,resolve as dr}from"path";import g from"process";import{pipeline as fr}from"stream/promises";import{createGzip as Ct}from"zlib";import D from"process";import $ from"process";import we from"process";import{existsSync as Ce}from"fs";import{resolve as ze}from"path";import{existsSync as gr}from"fs";import{existsSync as Ye,mkdirSync as pr,readdirSync as yr,readFileSync as br,writeFileSync as wr}from"fs";import{homedir as H}from"os";import{dirname as vt,resolve as w}from"path";import R from"process";import{existsSync as Cr,readdirSync as vr}from"fs";import{extname as _e,resolve as St}from"path";import Sr from"process";import{spawnSync as fa}from"child_process";import{existsSync as O,readFileSync as ga}from"fs";import{join as j}from"path";import qt from"process";function Ar(e,t){this[e]=kr.bind(null,t)}class at{cache=new Map;totalHits=0;totalMisses=0;options;constructor(e={}){this.options={enabled:!0,ttl:300000,maxSize:100,keyPrefix:"bunfig:",...e}}generateKey(e,t){let r=t?`:${t}`:"";return`${this.options.keyPrefix}${e}${r}`}isExpired(e){return Date.now()-e.timestamp.getTime()>e.ttl}estimateSize(e){try{return JSON.stringify(e).length}catch{return 1000}}evictIfNeeded(){if(this.cache.size<=this.options.maxSize)return;let e=Array.from(this.cache.entries()).sort(([,r],[,a])=>r.timestamp.getTime()-a.timestamp.getTime()),t=e.length-this.options.maxSize+1;for(let r=0;r<t;r++)this.cache.delete(e[r][0])}set(e,t,r,a){if(!this.options.enabled)return;let i=this.generateKey(e,r),n=a??this.options.ttl,o=this.estimateSize(t);this.cache.set(i,{value:t,timestamp:new Date,ttl:n,hits:0,size:o}),this.evictIfNeeded()}get(e,t){if(!this.options.enabled){this.totalMisses++;return}let r=this.generateKey(e,t),a=this.cache.get(r);if(!a){this.totalMisses++;return}if(this.isExpired(a)){this.cache.delete(r),this.totalMisses++;return}return a.hits++,this.totalHits++,a.value}isFileModified(e,t){try{if(!ut(e))return!0;return dt(e).mtime>t}catch{return!0}}getWithFileCheck(e,t){let r=this.get(e,t);if(!r)return;if(this.isFileModified(t,r.fileTimestamp)){this.delete(e,t);return}return r.value}setWithFileCheck(e,t,r,a){try{let i=ut(r)?dt(r):null,n=i?i.mtime:new Date;this.set(e,{value:t,fileTimestamp:n},r,a)}catch{this.set(e,t,r,a)}}delete(e,t){let r=this.generateKey(e,t);return this.cache.delete(r)}clear(){this.cache.clear(),this.totalHits=0,this.totalMisses=0}cleanup(){let e=0;for(let[t,r]of this.cache.entries())if(this.isExpired(r))this.cache.delete(t),e++;return e}getStats(){let e=Array.from(this.cache.values()),t=e.reduce((a,i)=>a+i.size,0),r=e.map((a)=>a.timestamp).sort();return{size:t,maxSize:this.options.maxSize,hitRate:this.totalHits+this.totalMisses>0?this.totalHits/(this.totalHits+this.totalMisses):0,totalHits:this.totalHits,totalMisses:this.totalMisses,entries:this.cache.size,oldestEntry:r[0],newestEntry:r[r.length-1]}}export(){let e={};for(let[t,r]of this.cache.entries())e[t]={value:r.value,timestamp:r.timestamp.toISOString(),ttl:r.ttl,hits:r.hits,size:r.size};return e}import(e){this.cache.clear();for(let[t,r]of Object.entries(e))if(typeof r==="object"&&r!==null){let a=r;this.cache.set(t,{value:a.value,timestamp:new Date(a.timestamp),ttl:a.ttl,hits:a.hits,size:a.size})}}}class it{metrics=[];maxMetrics=1000;async track(e,t,r={}){let a=performance.now(),i=new Date;try{let n=await t(),o=performance.now()-a;return this.recordMetric({operation:e,duration:o,timestamp:i,...r}),n}catch(n){let o=performance.now()-a;throw this.recordMetric({operation:`${e}:error`,duration:o,timestamp:i,...r}),n}}recordMetric(e){if(this.metrics.push(e),this.metrics.length>this.maxMetrics)this.metrics=this.metrics.slice(-this.maxMetrics)}getStats(e){let t=e?this.metrics.filter((i)=>i.operation===e):this.metrics;if(t.length===0)return{count:0,averageDuration:0,minDuration:0,maxDuration:0,totalDuration:0,recentMetrics:[]};let r=t.map((i)=>i.duration),a=r.reduce((i,n)=>i+n,0);return{count:t.length,averageDuration:a/t.length,minDuration:Math.min(...r),maxDuration:Math.max(...r),totalDuration:a,recentMetrics:t.slice(-10)}}getAllMetrics(){return[...this.metrics]}clearMetrics(){this.metrics=[]}getSlowOperations(e){return this.metrics.filter((t)=>t.duration>e)}}function Tr(e,t={}){let r=Object.keys(t).sort().map((a)=>`${a}:${t[a]}`).join("|");return r?`${e}:${r}`:e}function Pr(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return e===t}}function Nr(e){return e.getStats().size*2}function xr(e,t={}){let r=Ee.cwd();while(r.includes("storage"))r=ft(r,"..");let a=ft(r,e||"");if(t?.relative)return nr(Ee.cwd(),a);return a}function p(){if($.env.NODE_ENV==="test"||$.env.BUN_ENV==="test")return!1;return typeof window<"u"}async function Rr(){if($.env.NODE_ENV==="test"||$.env.BUN_ENV==="test")return!0;if(typeof navigator<"u"&&navigator.product==="ReactNative")return!0;if(typeof $<"u"){let e=$.type;if(e==="renderer"||e==="worker")return!1;return!!($.versions&&($.versions.node||$.versions.bun))}return!1}class Rt{async format(e){let t=await Rr(),r=await this.getMetadata(t);return JSON.stringify({timestamp:e.timestamp.toISOString(),level:e.level,name:e.name,message:e.message,metadata:r})}async getMetadata(e){if(e){let{hostname:t}=await import("os");return{pid:D.pid,hostname:t(),environment:D.env.NODE_ENV||"development",platform:D.platform,version:D.version}}return{userAgent:navigator.userAgent,hostname:window.location.hostname||"browser",environment:D.env.NODE_ENV||D.env.BUN_ENV||"development",viewport:{width:window.innerWidth,height:window.innerHeight},language:navigator.language}}}class He{name;fileLocks=new Map;currentKeyId=null;keys=new Map;fingersCrossedConfig;fingersCrossedActive=!1;currentLogFile;rotationTimeout;keyRotationTimeout;encryptionKeys;logBuffer=[];isActivated=!1;pendingOperations=[];enabled;fancy;tagFormat;timestampPosition;environment;config;options;formatter;timers=new Set;subLoggers=new Set;fingersCrossedBuffer=[];ANSI_PATTERN=/\u001B\[.*?m/g;activeProgressBar=null;constructor(e,t={}){this.name=e,this.config={...V},this.options=this.normalizeOptions(t),this.formatter=this.options.formatter||new Rt,this.enabled=t.enabled??!0,this.fancy=t.fancy??!0,this.tagFormat=t.tagFormat??{prefix:"[",suffix:"]"},this.timestampPosition=t.timestampPosition??"right",this.environment=t.environment??g.env.APP_ENV??"local",this.fingersCrossedConfig=this.initializeFingersCrossedConfig(t);let r={...t},a=t.timestamp!==void 0;if(a)delete r.timestamp;if(this.config={...this.config,...r,timestamp:a||this.config.timestamp,level:this.options.level??"info"},this.currentLogFile=this.generateLogFilename(),this.encryptionKeys=new Map,this.validateEncryptionConfig()){this.setupRotation();let i=this.generateKeyId(),n=this.generateKey();this.currentKeyId=i,this.keys.set(i,n),this.encryptionKeys.set(i,{key:n,createdAt:new Date}),this.setupKeyRotation()}}shouldActivateFingersCrossed(e){if(!this.fingersCrossedConfig)return!1;let t={debug:0,info:1,success:2,warning:3,error:4},r=this.fingersCrossedConfig.activationLevel??"error";return t[e]>=t[r]}initializeFingersCrossedConfig(e){if(!e.fingersCrossedEnabled&&e.fingersCrossed)return{...Se,...e.fingersCrossed};if(!e.fingersCrossedEnabled)return null;if(!e.fingersCrossed)return{...Se};return{...Se,...e.fingersCrossed}}normalizeOptions(e){let t={format:"json",level:"info",logDirectory:V.logDirectory,rotation:void 0,timestamp:void 0,fingersCrossed:{},enabled:!0,showTags:!1,showIcons:!0,formatter:void 0},r={...t,...Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))};if(!r.level||!["debug","info","success","warning","error"].includes(r.level))r.level=t.level;return r}shouldWriteToFile(){return!p()&&this.config.writeToFile===!0}async writeToFile(e){let t=(async()=>{let a,i=0,n=3,o=1000;while(i<n)try{try{try{await hr(this.config.logDirectory,bt.F_OK|bt.W_OK)}catch(s){if(s instanceof Error&&"code"in s)if(s.code==="ENOENT")await mr(this.config.logDirectory,{recursive:!0,mode:493});else if(s.code==="EACCES")throw Error(`No write permission for log directory: ${this.config.logDirectory}`);else throw s;else throw s}}catch(s){throw console.error("Debug: [writeToFile] Failed to create log directory:",s),s}let l=this.validateEncryptionConfig()?(await this.encrypt(e)).encrypted:M.from(e);try{if(!pe(this.currentLogFile))await Je(this.currentLogFile,"",{mode:420});if(a=yt(this.currentLogFile,"a",420),cr(a,l,{flag:"a"}),pt(a),a!==void 0)Ie(a),a=void 0;if((await L(this.currentLogFile)).size===0){if(await Je(this.currentLogFile,l,{flag:"w",mode:420}),(await L(this.currentLogFile)).size===0)throw Error("File exists but is empty after retry write")}return}catch(s){let c=s;if(c.code&&["ENETDOWN","ENETUNREACH","ENOTFOUND","ETIMEDOUT"].includes(c.code)){if(i<n-1){let h=typeof c.message==="string"?c.message:"Unknown error";console.error(`Network error during write attempt ${i+1}/${n}:`,h);let m=o*2**i;await new Promise((u)=>setTimeout(u,m)),i++;continue}}if(c?.code&&["ENOSPC","EDQUOT"].includes(c.code))throw Error(`Disk quota exceeded or no space left on device: ${c.message}`);throw console.error("Debug: [writeToFile] Error writing to file:",c),c}finally{if(a!==void 0)try{Ie(a)}catch(s){console.error("Debug: [writeToFile] Error closing file descriptor:",s)}}}catch(l){if(i===n-1){let c=l,h=typeof c.message==="string"?c.message:"Unknown error";throw console.error("Debug: [writeToFile] Max retries reached. Final error:",h),l}i++;let s=o*2**(i-1);await new Promise((c)=>setTimeout(c,s))}})();this.pendingOperations.push(t);let r=this.pendingOperations.length-1;try{await t}catch(a){throw console.error("Debug: [writeToFile] Error in operation:",a),a}finally{this.pendingOperations.splice(r,1)}}generateLogFilename(){if(this.name.includes("stream-throughput")||this.name.includes("decompress-perf-test")||this.name.includes("decompression-latency")||this.name.includes("concurrent-read-test")||this.name.includes("clock-change-test"))return F(this.config.logDirectory,`${this.name}.log`);if(this.name.includes("pending-test")||this.name.includes("temp-file-test")||this.name==="crash-test"||this.name==="corrupt-test"||this.name.includes("rotation-load-test")||this.name==="sigterm-test"||this.name==="sigint-test"||this.name==="failed-rotation-test"||this.name==="integration-test")return F(this.config.logDirectory,`${this.name}.log`);let e=new Date().toISOString().split("T")[0];return F(this.config.logDirectory,`${this.name}-${e}.log`)}setupRotation(){if(p())return;if(!this.shouldWriteToFile())return;if(typeof this.config.rotation==="boolean")return;let e=this.config.rotation,t;switch(e.frequency){case"daily":t=86400000;break;case"weekly":t=604800000;break;case"monthly":t=2592000000;break;default:return}this.rotationTimeout=setInterval(()=>{this.rotateLog()},t)}setupKeyRotation(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation setup");return}let e=this.config.rotation.keyRotation;if(!e?.enabled)return;let t=typeof e.interval==="number"?e.interval:60,r=Math.max(t,60)*1000;this.keyRotationTimeout=setInterval(()=>{this.rotateKeys().catch((a)=>{console.error("Error rotating keys:",a)})},r)}async rotateKeys(){if(!this.validateEncryptionConfig()){console.error("Invalid encryption configuration detected during key rotation");return}let e=this.config.rotation.keyRotation,t=this.generateKeyId(),r=this.generateKey();this.currentKeyId=t,this.keys.set(t,r),this.encryptionKeys.set(t,{key:r,createdAt:new Date});let a=Array.from(this.encryptionKeys.entries()).sort(([,o],[,l])=>l.createdAt.getTime()-o.createdAt.getTime()),i=typeof e.maxKeys==="number"?e.maxKeys:1,n=Math.max(1,i);if(a.length>n)for(let[o]of a.slice(n))this.encryptionKeys.delete(o),this.keys.delete(o)}generateKeyId(){return We(16).toString("hex")}generateKey(){return We(32)}getCurrentKey(){if(!this.currentKeyId)throw Error("Encryption is not properly initialized. Make sure encryption is enabled in the configuration.");let e=this.keys.get(this.currentKeyId);if(!e)throw Error(`No key found for ID ${this.currentKeyId}. The encryption key may have been rotated or removed.`);return{key:e,id:this.currentKeyId}}encrypt(e){let{key:t}=this.getCurrentKey(),r=We(16),a=or("aes-256-gcm",t,r),i=M.isBuffer(e)?e:M.from(e,"utf8"),n=a.update(i),o=a.final(),l=n.length+o.length,s=a.getAuthTag(),c=M.allocUnsafe(16+l+16);return r.copy(c,0),n.copy(c,16),o.copy(c,16+n.length),s.copy(c,16+l),{encrypted:c,iv:r}}async compressData(e){return new Promise((t,r)=>{let a=Ct(),i=[];a.on("data",(n)=>i.push(n)),a.on("end",()=>t(M.from(M.concat(i)))),a.on("error",r),a.write(e),a.end()})}getEncryptionOptions(){if(!this.config.rotation||typeof this.config.rotation==="boolean"||!this.config.rotation.encrypt)return{};let e={algorithm:"aes-256-cbc",compress:!1};if(typeof this.config.rotation.encrypt==="object"){let t=this.config.rotation.encrypt;return{...e,...t}}return e}async rotateLog(){if(p())return;if(!this.shouldWriteToFile())return;let e=await L(this.currentLogFile).catch(()=>null);if(!e)return;let t=this.config.rotation;if(typeof t==="boolean")return;if(t.maxSize&&e.size>=t.maxSize){let r=this.currentLogFile,a=this.generateLogFilename();if(this.name.includes("rotation-load-test")||this.name==="failed-rotation-test"){let i=await ye(this.config.logDirectory),n=i.filter((s)=>s.startsWith(this.name)&&/\.log\.\d+$/.test(s)).sort((s,c)=>{let h=Number.parseInt(s.match(/\.log\.(\d+)$/)?.[1]||"0");return Number.parseInt(c.match(/\.log\.(\d+)$/)?.[1]||"0")-h}),o=n.length>0?Number.parseInt(n[0].match(/\.log\.(\d+)$/)?.[1]||"0")+1:1,l=`${r}.${o}`;if(await L(r).catch(()=>null))try{if(await wt(r,l),t.compress)try{let s=`${l}.gz`;await this.compressLogFile(l,s),await be(l)}catch(s){console.error("Error compressing rotated file:",s)}if(n.length===0&&!i.some((s)=>s.endsWith(".log.1")))try{let s=`${r}.1`;await Je(s,"")}catch(s){console.error("Error creating backup file:",s)}}catch(s){console.error(`Error during rotation: ${s instanceof Error?s.message:String(s)}`)}}else{let i=new Date().toISOString().replace(/[:.]/g,"-"),n=r.replace(/\.log$/,`-${i}.log`);if(await L(r).catch(()=>null))await wt(r,n)}if(this.currentLogFile=a,t.maxFiles){let i=(await ye(this.config.logDirectory)).filter((n)=>n.startsWith(this.name)).sort((n,o)=>o.localeCompare(n));for(let n of i.slice(t.maxFiles))await be(F(this.config.logDirectory,n))}}}async compressLogFile(e,t){let r=gt(e),a=lr(t),i=Ct();await fr(r,i,a)}async handleFingersCrossedBuffer(e,t){if(!this.fingersCrossedConfig)return;if(this.shouldActivateFingersCrossed(e)&&!this.isActivated){this.isActivated=!0;for(let r of this.logBuffer){let a=await this.formatter.format(r);if(this.shouldWriteToFile())await this.writeToFile(a);console.log(a)}if(this.fingersCrossedConfig.stopBuffering)this.logBuffer=[]}if(this.isActivated){if(this.shouldWriteToFile())await this.writeToFile(t);console.log(t)}}shouldLog(e){if(!this.enabled)return!1;let t={debug:0,info:1,success:2,warning:3,error:4};return t[e]>=t[this.config.level]}async flushPendingWrites(){if(await Promise.all(this.pendingOperations.map((e)=>{if(e instanceof Promise)return e.catch((t)=>{console.error("Error in pending write operation:",t)});return Promise.resolve()})),pe(this.currentLogFile))try{let e=yt(this.currentLogFile,"r+");pt(e),Ie(e)}catch(e){console.error(`Error flushing file: ${e}`)}}async destroy(){if(this.rotationTimeout)clearInterval(this.rotationTimeout);if(this.keyRotationTimeout)clearInterval(this.keyRotationTimeout);this.timers.clear();for(let e of this.pendingOperations)if(typeof e.cancel==="function")e.cancel();return(async()=>{if(this.pendingOperations.length>0)try{await Promise.allSettled(this.pendingOperations)}catch(e){console.error("Error waiting for pending operations:",e)}if(!p()&&this.config.rotation&&typeof this.config.rotation!=="boolean"&&this.config.rotation.compress)try{let e=(await ye(this.config.logDirectory)).filter((t)=>(t.includes("temp")||t.includes(".tmp"))&&t.includes(this.name));for(let t of e)try{await be(F(this.config.logDirectory,t))}catch(r){console.error(`Failed to delete temp file ${t}:`,r)}}catch(e){console.error("Error cleaning up temporary files:",e)}})()}getCurrentLogFilePath(){return this.currentLogFile}formatTag(e){if(!e)return"";return`${this.tagFormat.prefix}${e}${this.tagFormat.suffix}`}formatFileTimestamp(e){return`[${e.toISOString()}]`}formatConsoleTimestamp(e){return this.shouldStyleConsole()?f.gray(e.toLocaleTimeString()):e.toLocaleTimeString()}shouldStyleConsole(){if(!this.fancy||p())return!1;let e=typeof g.env.NO_COLOR<"u",t=g.env.FORCE_COLOR==="0";if(e||t)return!1;return!!(typeof g.stderr<"u"&&g.stderr.isTTY||typeof g.stdout<"u"&&g.stdout.isTTY)}formatConsoleMessage(e){let{timestamp:t,icon:r="",tag:a="",message:i,level:n,showTimestamp:o=!0}=e,l=(d)=>d.replace(this.ANSI_PATTERN,"");if(!this.fancy){let d=[];if(o)d.push(t);if(n==="warning")d.push("WARN");else if(n==="error")d.push("ERROR");else if(r)d.push(r.replace(/[^\p{L}\p{N}\p{P}\p{Z}]/gu,""));if(a)d.push(a.replace(/[[\]]/g,""));return d.push(i),d.join(" ")}let s=g.stdout.columns||120,c="";if(n==="warning"||n==="error")c=`${r} ${i}`;else if(n==="info"||n==="success")c=`${r} ${a} ${i}`;else c=`${r} ${a} ${f.cyan(i)}`;if(!o)return c.trim();let h=l(c).trim().length,m=l(t).length,u=Math.max(1,s-2-h-m);return`${c.trim()}${" ".repeat(u)}${t}`}formatMessage(e,t){if(t.length===1&&Array.isArray(t[0]))return e.replace(/\{(\d+)\}/g,(n,o)=>{let l=Number.parseInt(o,10);return l<t[0].length?String(t[0][l]):n});let r=/%([sdijfo%])/g,a=0,i=e.replace(r,(n,o)=>{if(o==="%")return"%";if(a>=t.length)return n;let l=t[a++];switch(o){case"s":return String(l);case"d":case"i":return Number(l).toString();case"j":case"o":return JSON.stringify(l,null,2);default:return n}});if(a<t.length)i+=` ${t.slice(a).map((n)=>typeof n==="object"?JSON.stringify(n,null,2):String(n)).join(" ")}`;return i}formatMarkdown(e){if(!e)return e;let t=e;return t=t.replace(/\[([^\]]+)\]\(([^)]+)\)/g,(r,a,i)=>{let n=f.underline(f.blue(a)),o=this.toAbsoluteFilePath(i);if(o&&this.shouldStyleConsole()&&this.supportsHyperlinks()){let l=`file://${encodeURI(o)}`,s="\x1B]8;;",c="\x1B\\";return`\x1B]8;;${l}\x1B\\${n}\x1B]8;;\x1B\\`}if(this.shouldStyleConsole()&&this.supportsHyperlinks())return`\x1B]8;;${i}\x1B\\${n}\x1B]8;;\x1B\\`;return n}),t=t.replace(/`([^`]+)`/g,(r,a)=>f.bgGray(a)),t=t.replace(/\*\*([^*]+)\*\*/g,(r,a)=>f.bold(a)),t=t.replace(/(?<!\*)\*([^*]+)\*(?!\*)/g,(r,a)=>f.italic(a)),t=t.replace(/(?<!_)_([^_]+)_(?!_)/g,(r,a)=>f.italic(a)),t=t.replace(/~([^~]+)~/g,(r,a)=>f.strikethrough(a)),t}supportsHyperlinks(){if(p())return!1;let e=g.env;if(!e)return!1;if(e.TERM_PROGRAM==="iTerm.app"||e.TERM_PROGRAM==="vscode"||e.TERM_PROGRAM==="WezTerm")return!0;if(e.WT_SESSION)return!0;if(e.TERM==="xterm-kitty")return!0;let t=e.VTE_VERSION?Number.parseInt(e.VTE_VERSION,10):0;if(!Number.isNaN(t)&&t>=5000)return!0;return!1}toAbsoluteFilePath(e){try{let t=e;if(t.startsWith("file://"))t=t.replace(/^file:\/\//,"");if(t.startsWith("~")){let r=g.env.HOME||"";if(r)t=t.replace(/^~(?=$|\/)/,r)}if(ur(t)||t.startsWith("./")||t.startsWith("../"))t=dr(t);else return null;return pe(t)?t:null}catch{return null}}buildOutputTexts(e){let t=this.shouldStyleConsole()?this.formatMarkdown(e):e,r=e.replace(this.ANSI_PATTERN,"");return{consoleText:t,fileText:r}}async log(e,t,...r){if(!this.shouldLog(e))return;let a=new Date,i=this.formatConsoleTimestamp(a),n=this.formatFileTimestamp(a),o,l;if(t instanceof Error)o=t.message,l=t.stack;else o=this.formatMessage(t,r);let{consoleText:s,fileText:c}=this.buildOutputTexts(o);if(this.shouldStyleConsole()){let m=this.options.showIcons===!1?"":Lt[e],u=this.options.showTags!==!1&&this.name?f.gray(this.formatTag(this.name)):"",d;switch(e){case"debug":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:f.gray(s),level:e}),console.error(d);break;case"info":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.warn(d);break;case"success":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:f.green(s),level:e}),console.error(d);break;case"warning":d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.warn(d);break;case"error":if(d=this.formatConsoleMessage({timestamp:i,icon:m,tag:u,message:s,level:e}),console.error(d),l){let S=l.split(`
|
|
3
3
|
`);for(let b of S)if(b.trim()&&!b.includes(o))console.error(this.formatConsoleMessage({timestamp:i,message:f.gray(` ${b}`),level:e,showTimestamp:!1}))}break}}else if(!p()){if(console.error(`${n} ${this.environment}.${e.toUpperCase()}: ${o}`),l)console.error(l)}let h=`${n} ${this.environment}.${e.toUpperCase()}: ${c}
|
|
4
4
|
`;if(l)h+=`${l}
|
|
5
5
|
`;if(h=h.replace(this.ANSI_PATTERN,""),this.shouldWriteToFile())await this.writeToFile(h)}progress(e,t=""){let r={update:(i,n)=>{},finish:(i)=>{},interrupt:(i,n)=>{}};if(!this.enabled)return r;let a=30;if(this.activeProgressBar={total:Math.max(1,e||1),current:0,message:t||"",barLength:a,lastRenderedLine:""},this.shouldStyleConsole()&&!p()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar);return{update:(i,n)=>{if(!this.enabled||!this.activeProgressBar)return;if(this.activeProgressBar.current=Math.min(Math.max(0,i),this.activeProgressBar.total),n!==void 0)this.activeProgressBar.message=n;if(this.shouldStyleConsole()&&!p()&&g.stdout.isTTY)this.renderProgressBar(this.activeProgressBar)},finish:(i)=>{if(!this.activeProgressBar)return;this.finishProgressBar(this.activeProgressBar,i)},interrupt:(i,n="info")=>{if(!p()&&g.stdout.isTTY)g.stdout.write(`
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{pc as T}from"./chunk-c6mb5jxz.js";function I(z){K={...K,...z}}function R(){return K}function P(){return typeof window<"u"&&typeof document<"u"}async function D(){if(K.getToken){let z=K.getToken();return z instanceof Promise?z:z}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function W(){let z={"Content-Type":"application/json",Accept:"application/json",...K.headers},F=await D();if(F)z.Authorization=`Bearer ${F}`;return z}async function X(z){if(z.status===401)throw K.onUnauthorized?.(),new Y("Unauthorized",401);if(!z.ok){let G=await z.json().catch(()=>({message:"Request failed"}));throw new Y(G.message||`HTTP ${z.status}`,z.status)}let F=await z.json();if(K.transformResponse)return K.transformResponse(F);return F}class x{state;constructor(z){this.state={table:z,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...z){return this.state.selectColumns=z,this}where(z,F,G){if(G===void 0)this.state.wheres.push({column:z,operator:"=",value:F,boolean:"and"});else this.state.wheres.push({column:z,operator:F,value:G,boolean:"and"});return this}orWhere(z,F,G){if(G===void 0)this.state.wheres.push({column:z,operator:"=",value:F,boolean:"or"});else this.state.wheres.push({column:z,operator:F,value:G,boolean:"or"});return this}andWhere(z,F,G){return G===void 0?this.where(z,F):this.where(z,F,G)}whereNull(z){return this.where(z,"is",null)}whereNotNull(z){return this.where(z,"is not",null)}whereIn(z,F){return this.where(z,"in",F)}whereNotIn(z,F){return this.where(z,"not in",F)}orderBy(z,F="asc"){return this.state.orderBy.push({column:z,direction:F}),this}orderByDesc(z){return this.orderBy(z,"desc")}latest(z="created_at"){return this.orderBy(z,"desc")}oldest(z="created_at"){return this.orderBy(z,"asc")}limit(z){return this.state.limitValue=z,this}offset(z){return this.state.offsetValue=z,this}skip(z){return this.offset(z)}take(z){return this.limit(z)}with(...z){return this.state.withRelations.push(...z),this}buildQueryParams(){let z=new URLSearchParams;for(let F of this.state.wheres)if(F.operator==="=")z.append(F.column,String(F.value));else if(F.operator==="in"&&Array.isArray(F.value))z.append(`${F.column}[]`,F.value.join(","));else if(F.operator==="is"&&F.value===null)z.append(`filter[${F.column}][is]`,"null");else if(F.operator==="is not"&&F.value===null)z.append(`filter[${F.column}][is_not]`,"null");else z.append(`filter[${F.column}][${F.operator}]`,String(F.value));if(this.state.orderBy.length>0){let F=this.state.orderBy.map((G)=>`${G.direction==="desc"?"-":""}${G.column}`).join(",");z.append("sort",F)}if(this.state.limitValue!==void 0)z.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)z.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))z.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)z.append("include",this.state.withRelations.join(","));return z}buildUrl(z){let F=`${K.baseUrl}/${this.state.table}`;if(z!==void 0)return`${F}/${z}`;let J=this.buildQueryParams().toString();return J?`${F}?${J}`:F}async get(){let z=this.buildUrl(),F=await fetch(z,{method:"GET",headers:await W()}),G=await X(F);return Array.isArray(G)?G:G.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let z=await this.first();if(!z)throw new Y(`No ${this.state.table} found`,404);return z}async find(z){let F=this.buildUrl(z);try{let G=await fetch(F,{method:"GET",headers:await W()});if(G.status===404)return null;let J=await X(G);return"data"in J&&!Array.isArray(J.data)?J.data:J}catch{return null}}async findOrFail(z){let F=await this.find(z);if(!F)throw new Y(`${this.state.table} with id ${z} not found`,404);return F}async count(){let z=this.buildQueryParams();z.append("count","true");let F=`${K.baseUrl}/${this.state.table}?${z.toString()}`,G=await fetch(F,{method:"GET",headers:await W()});return(await X(G)).count}async exists(){return await this.count()>0}async create(z){let F=`${K.baseUrl}/${this.state.table}`,G=K.transformRequest?K.transformRequest(z):z,J=await fetch(F,{method:"POST",headers:await W(),body:JSON.stringify(G)}),L=await X(J);return"data"in L&&!Array.isArray(L.data)?L.data:L}async insert(z){return this.create(z)}async update(z,F){let G=`${K.baseUrl}/${this.state.table}/${z}`,J=K.transformRequest?K.transformRequest(F):F,L=await fetch(G,{method:"PATCH",headers:await W(),body:JSON.stringify(J)}),U=await X(L);return"data"in U&&!Array.isArray(U.data)?U.data:U}async delete(z){let F=`${K.baseUrl}/${this.state.table}/${z}`;return(await fetch(F,{method:"DELETE",headers:await W()})).ok}async destroy(z){return this.delete(z)}async paginate(z=1,F=15){this.limit(F).offset((z-1)*F);let G=this.buildQueryParams();G.append("paginate","true");let J=`${K.baseUrl}/${this.state.table}?${G.toString()}`,L=await fetch(J,{method:"GET",headers:await W()});return X(L)}toState(){return{...this.state}}}function q(z){return new x(z)}function H(){return new Proxy({},{get:(z,F)=>{return()=>q(F)}})}class j{_attributes;_definition;constructor(z,F={}){this._definition=z,this._attributes={...F}}get(z){return this._attributes[z]}set(z,F){this._attributes[z]=F}get attributes(){return{...this._attributes}}get id(){let z=this._definition.primaryKey||"id";return this._attributes[z]}toJSON(){let z=new Set;for(let[G,J]of Object.entries(this._definition.attributes))if(J.hidden)z.add(G);let F={};for(let[G,J]of Object.entries(this._attributes))if(!z.has(G))F[G]=J;return F}}class N{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(z){this._definition=z}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(z,F,G){if(G===void 0)this._wheres.push({column:z,operator:"=",value:F,boolean:"and"});else this._wheres.push({column:z,operator:F,value:G,boolean:"and"});return this}orWhere(z,F,G){if(G===void 0)this._wheres.push({column:z,operator:"=",value:F,boolean:"or"});else this._wheres.push({column:z,operator:F,value:G,boolean:"or"});return this}whereIn(z,F){return this._wheres.push({column:z,operator:"in",value:F,boolean:"and"}),this}whereNotIn(z,F){return this._wheres.push({column:z,operator:"not in",value:F,boolean:"and"}),this}whereNull(z){return this._wheres.push({column:z,operator:"is",value:null,boolean:"and"}),this}whereNotNull(z){return this._wheres.push({column:z,operator:"is not",value:null,boolean:"and"}),this}whereLike(z,F){return this._wheres.push({column:z,operator:"like",value:F,boolean:"and"}),this}orderBy(z,F="asc"){return this._orderBy.push({column:z,direction:F}),this}orderByDesc(z){return this.orderBy(z,"desc")}orderByAsc(z){return this.orderBy(z,"asc")}limit(z){return this._limit=z,this}take(z){return this.limit(z)}offset(z){return this._offset=z,this}skip(z){return this.offset(z)}select(...z){return this._select=z,this}with(...z){return this._withRelations.push(...z),this}latest(z="created_at"){return this.orderByDesc(z)}oldest(z="created_at"){return this.orderByAsc(z)}buildQueryParams(){let z=new URLSearchParams;for(let F of this._wheres)if(F.operator==="=")z.append(F.column,String(F.value));else if(F.operator==="in"&&Array.isArray(F.value))z.append(`${F.column}[]`,F.value.join(","));else if(F.operator==="is"&&F.value===null)z.append(`filter[${F.column}][is]`,"null");else if(F.operator==="is not"&&F.value===null)z.append(`filter[${F.column}][is_not]`,"null");else z.append(`filter[${F.column}][${F.operator}]`,String(F.value));if(this._orderBy.length>0){let F=this._orderBy.map((G)=>`${G.direction==="desc"?"-":""}${G.column}`).join(",");z.append("sort",F)}if(this._limit!==void 0)z.append("limit",String(this._limit));if(this._offset!==void 0)z.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))z.append("fields",this._select.join(","));if(this._withRelations.length>0)z.append("include",this._withRelations.join(","));return z}buildUrl(z){let F=`${K.baseUrl}/${this.getTablePath()}`;if(z!==void 0)return`${F}/${z}`;let J=this.buildQueryParams().toString();return J?`${F}?${J}`:F}async get(){let z=this.buildUrl(),F=await fetch(z,{method:"GET",headers:await W()}),G=await X(F);return(Array.isArray(G)?G:G.data).map((L)=>new j(this._definition,L))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let z=await this.first();if(!z)throw new Y(`No ${this._definition.name} found`,404);return z}async find(z){let F=this.buildUrl(z);try{let G=await fetch(F,{method:"GET",headers:await W()});if(G.status===404)return null;let J=await X(G),L="data"in J&&!Array.isArray(J.data)?J.data:J;return new j(this._definition,L)}catch{return null}}async findOrFail(z){let F=await this.find(z);if(!F)throw new Y(`${this._definition.name} with id ${z} not found`,404);return F}async count(){let z=this.buildQueryParams();z.append("count","true");let F=`${K.baseUrl}/${this.getTablePath()}?${z.toString()}`,G=await fetch(F,{method:"GET",headers:await W()});return(await X(G)).count}async exists(){return await this.count()>0}async pluck(z){return this._select=[z],(await this.get()).map((G)=>G.get(z))}async paginate(z=1,F=15){this._limit=F,this._offset=(z-1)*F;let G=this.buildQueryParams();G.append("paginate","true");let J=`${K.baseUrl}/${this.getTablePath()}?${G.toString()}`,L=await fetch(J,{method:"GET",headers:await W()}),U=await X(L);return{...U,data:U.data.map((Z)=>new j(this._definition,Z))}}}function k(z){return new Proxy({query:()=>new N(z),where(G,J,L){return new N(z).where(G,J,L)},orWhere(G,J,L){return new N(z).orWhere(G,J,L)},whereIn(G,J){return new N(z).whereIn(G,J)},whereNotIn(G,J){return new N(z).whereNotIn(G,J)},whereNull(G){return new N(z).whereNull(G)},whereNotNull(G){return new N(z).whereNotNull(G)},whereLike(G,J){return new N(z).whereLike(G,J)},orderBy(G,J="asc"){return new N(z).orderBy(G,J)},orderByDesc(G){return new N(z).orderByDesc(G)},select(...G){return new N(z).select(...G)},limit:(G)=>new N(z).limit(G),take:(G)=>new N(z).take(G),skip:(G)=>new N(z).skip(G),latest:(G="created_at")=>new N(z).latest(G),oldest:(G="created_at")=>new N(z).oldest(G),async find(G){return new N(z).find(G)},async findOrFail(G){return new N(z).findOrFail(G)},async all(){return new N(z).get()},async first(){return new N(z).first()},async firstOrFail(){return new N(z).firstOrFail()},async count(){return new N(z).count()},async exists(){return new N(z).exists()},async paginate(G,J){return new N(z).paginate(G,J)},async pluck(G){return new N(z).pluck(G)},async create(G){let J=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,L=`${K.baseUrl}/${J}`,U=K.transformRequest?K.transformRequest(G):G,Z=await fetch(L,{method:"POST",headers:await W(),body:JSON.stringify(U)}),_=await X(Z),$="data"in _&&!Array.isArray(_.data)?_.data:_;return new j(z,$)},async update(G,J){let L=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,U=`${K.baseUrl}/${L}/${G}`,Z=K.transformRequest?K.transformRequest(J):J,_=await fetch(U,{method:"PATCH",headers:await W(),body:JSON.stringify(Z)}),$=await X(_),A="data"in $&&!Array.isArray($.data)?$.data:$;return new j(z,A)},async delete(G){let J=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,L=`${K.baseUrl}/${J}/${G}`;return(await fetch(L,{method:"DELETE",headers:await W()})).ok},async destroy(G){return this.delete(G)},getDefinition:()=>z,getTable:()=>z.table},{get(G,J){if(typeof J==="string"&&J.startsWith("where")&&J.length>5){let L=J.slice(5),U=L.charAt(0).toLowerCase()+L.slice(1);if(U in z.attributes||U==="id"||U===z.primaryKey)return(Z)=>new N(z).where(U,Z)}return Reflect.get(G,J)}})}var K,Y,E,V;var S=T(()=>{K={baseUrl:""};Y=class Y extends Error{status;constructor(z,F){super(z);this.name="BrowserQueryError",this.status=F}};E={async login(z){let F=await fetch(`${K.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...K.headers},body:JSON.stringify(z)});if(!F.ok){let L=await F.json().catch(()=>({message:"Login failed"}));throw new Y(L.message||"Login failed",F.status)}let G=await F.json(),J=G.data||G;if(typeof localStorage<"u"&&J.token)localStorage.setItem("auth_token",J.token);return J},async register(z){let F=await fetch(`${K.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...K.headers},body:JSON.stringify(z)});if(!F.ok){let L=await F.json().catch(()=>({message:"Registration failed"}));throw new Y(L.message||"Registration failed",F.status)}let G=await F.json(),J=G.data||G;if(typeof localStorage<"u"&&J.token)localStorage.setItem("auth_token",J.token);return J},async logout(){if(await D())try{await fetch(`${K.baseUrl}/logout`,{method:"POST",headers:await W()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await D())return null;try{let F=await fetch(`${K.baseUrl}/user`,{method:"GET",headers:await W()});if(F.status===401)return K.onUnauthorized?.(),null;if(!F.ok)return null;let G=await F.json();return G.user||G}catch{return null}},async check(){return await this.user()!==null},getToken:D},V=q});
|
|
3
|
-
export{I as
|
|
2
|
+
import{qc as T}from"./chunk-x8tfs1sw.js";function I(z){K={...K,...z}}function R(){return K}function P(){return typeof window<"u"&&typeof document<"u"}async function D(){if(K.getToken){let z=K.getToken();return z instanceof Promise?z:z}if(typeof localStorage<"u")return localStorage.getItem("auth_token");return null}async function W(){let z={"Content-Type":"application/json",Accept:"application/json",...K.headers},F=await D();if(F)z.Authorization=`Bearer ${F}`;return z}async function X(z){if(z.status===401)throw K.onUnauthorized?.(),new Y("Unauthorized",401);if(!z.ok){let G=await z.json().catch(()=>({message:"Request failed"}));throw new Y(G.message||`HTTP ${z.status}`,z.status)}let F=await z.json();if(K.transformResponse)return K.transformResponse(F);return F}class x{state;constructor(z){this.state={table:z,wheres:[],orderBy:[],selectColumns:["*"],withRelations:[]}}select(...z){return this.state.selectColumns=z,this}where(z,F,G){if(G===void 0)this.state.wheres.push({column:z,operator:"=",value:F,boolean:"and"});else this.state.wheres.push({column:z,operator:F,value:G,boolean:"and"});return this}orWhere(z,F,G){if(G===void 0)this.state.wheres.push({column:z,operator:"=",value:F,boolean:"or"});else this.state.wheres.push({column:z,operator:F,value:G,boolean:"or"});return this}andWhere(z,F,G){return G===void 0?this.where(z,F):this.where(z,F,G)}whereNull(z){return this.where(z,"is",null)}whereNotNull(z){return this.where(z,"is not",null)}whereIn(z,F){return this.where(z,"in",F)}whereNotIn(z,F){return this.where(z,"not in",F)}orderBy(z,F="asc"){return this.state.orderBy.push({column:z,direction:F}),this}orderByDesc(z){return this.orderBy(z,"desc")}latest(z="created_at"){return this.orderBy(z,"desc")}oldest(z="created_at"){return this.orderBy(z,"asc")}limit(z){return this.state.limitValue=z,this}offset(z){return this.state.offsetValue=z,this}skip(z){return this.offset(z)}take(z){return this.limit(z)}with(...z){return this.state.withRelations.push(...z),this}buildQueryParams(){let z=new URLSearchParams;for(let F of this.state.wheres)if(F.operator==="=")z.append(F.column,String(F.value));else if(F.operator==="in"&&Array.isArray(F.value))z.append(`${F.column}[]`,F.value.join(","));else if(F.operator==="is"&&F.value===null)z.append(`filter[${F.column}][is]`,"null");else if(F.operator==="is not"&&F.value===null)z.append(`filter[${F.column}][is_not]`,"null");else z.append(`filter[${F.column}][${F.operator}]`,String(F.value));if(this.state.orderBy.length>0){let F=this.state.orderBy.map((G)=>`${G.direction==="desc"?"-":""}${G.column}`).join(",");z.append("sort",F)}if(this.state.limitValue!==void 0)z.append("limit",String(this.state.limitValue));if(this.state.offsetValue!==void 0)z.append("offset",String(this.state.offsetValue));if(this.state.selectColumns.length>0&&!this.state.selectColumns.includes("*"))z.append("fields",this.state.selectColumns.join(","));if(this.state.withRelations.length>0)z.append("include",this.state.withRelations.join(","));return z}buildUrl(z){let F=`${K.baseUrl}/${this.state.table}`;if(z!==void 0)return`${F}/${z}`;let J=this.buildQueryParams().toString();return J?`${F}?${J}`:F}async get(){let z=this.buildUrl(),F=await fetch(z,{method:"GET",headers:await W()}),G=await X(F);return Array.isArray(G)?G:G.data}async first(){return this.limit(1),(await this.get())[0]??null}async firstOrFail(){let z=await this.first();if(!z)throw new Y(`No ${this.state.table} found`,404);return z}async find(z){let F=this.buildUrl(z);try{let G=await fetch(F,{method:"GET",headers:await W()});if(G.status===404)return null;let J=await X(G);return"data"in J&&!Array.isArray(J.data)?J.data:J}catch{return null}}async findOrFail(z){let F=await this.find(z);if(!F)throw new Y(`${this.state.table} with id ${z} not found`,404);return F}async count(){let z=this.buildQueryParams();z.append("count","true");let F=`${K.baseUrl}/${this.state.table}?${z.toString()}`,G=await fetch(F,{method:"GET",headers:await W()});return(await X(G)).count}async exists(){return await this.count()>0}async create(z){let F=`${K.baseUrl}/${this.state.table}`,G=K.transformRequest?K.transformRequest(z):z,J=await fetch(F,{method:"POST",headers:await W(),body:JSON.stringify(G)}),L=await X(J);return"data"in L&&!Array.isArray(L.data)?L.data:L}async insert(z){return this.create(z)}async update(z,F){let G=`${K.baseUrl}/${this.state.table}/${z}`,J=K.transformRequest?K.transformRequest(F):F,L=await fetch(G,{method:"PATCH",headers:await W(),body:JSON.stringify(J)}),U=await X(L);return"data"in U&&!Array.isArray(U.data)?U.data:U}async delete(z){let F=`${K.baseUrl}/${this.state.table}/${z}`;return(await fetch(F,{method:"DELETE",headers:await W()})).ok}async destroy(z){return this.delete(z)}async paginate(z=1,F=15){this.limit(F).offset((z-1)*F);let G=this.buildQueryParams();G.append("paginate","true");let J=`${K.baseUrl}/${this.state.table}?${G.toString()}`,L=await fetch(J,{method:"GET",headers:await W()});return X(L)}toState(){return{...this.state}}}function q(z){return new x(z)}function H(){return new Proxy({},{get:(z,F)=>{return()=>q(F)}})}class j{_attributes;_definition;constructor(z,F={}){this._definition=z,this._attributes={...F}}get(z){return this._attributes[z]}set(z,F){this._attributes[z]=F}get attributes(){return{...this._attributes}}get id(){let z=this._definition.primaryKey||"id";return this._attributes[z]}toJSON(){let z=new Set;for(let[G,J]of Object.entries(this._definition.attributes))if(J.hidden)z.add(G);let F={};for(let[G,J]of Object.entries(this._attributes))if(!z.has(G))F[G]=J;return F}}class N{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];constructor(z){this._definition=z}getTablePath(){return typeof this._definition.traits?.useApi==="object"&&this._definition.traits.useApi?.uri||this._definition.table}where(z,F,G){if(G===void 0)this._wheres.push({column:z,operator:"=",value:F,boolean:"and"});else this._wheres.push({column:z,operator:F,value:G,boolean:"and"});return this}orWhere(z,F,G){if(G===void 0)this._wheres.push({column:z,operator:"=",value:F,boolean:"or"});else this._wheres.push({column:z,operator:F,value:G,boolean:"or"});return this}whereIn(z,F){return this._wheres.push({column:z,operator:"in",value:F,boolean:"and"}),this}whereNotIn(z,F){return this._wheres.push({column:z,operator:"not in",value:F,boolean:"and"}),this}whereNull(z){return this._wheres.push({column:z,operator:"is",value:null,boolean:"and"}),this}whereNotNull(z){return this._wheres.push({column:z,operator:"is not",value:null,boolean:"and"}),this}whereLike(z,F){return this._wheres.push({column:z,operator:"like",value:F,boolean:"and"}),this}orderBy(z,F="asc"){return this._orderBy.push({column:z,direction:F}),this}orderByDesc(z){return this.orderBy(z,"desc")}orderByAsc(z){return this.orderBy(z,"asc")}limit(z){return this._limit=z,this}take(z){return this.limit(z)}offset(z){return this._offset=z,this}skip(z){return this.offset(z)}select(...z){return this._select=z,this}with(...z){return this._withRelations.push(...z),this}latest(z="created_at"){return this.orderByDesc(z)}oldest(z="created_at"){return this.orderByAsc(z)}buildQueryParams(){let z=new URLSearchParams;for(let F of this._wheres)if(F.operator==="=")z.append(F.column,String(F.value));else if(F.operator==="in"&&Array.isArray(F.value))z.append(`${F.column}[]`,F.value.join(","));else if(F.operator==="is"&&F.value===null)z.append(`filter[${F.column}][is]`,"null");else if(F.operator==="is not"&&F.value===null)z.append(`filter[${F.column}][is_not]`,"null");else z.append(`filter[${F.column}][${F.operator}]`,String(F.value));if(this._orderBy.length>0){let F=this._orderBy.map((G)=>`${G.direction==="desc"?"-":""}${G.column}`).join(",");z.append("sort",F)}if(this._limit!==void 0)z.append("limit",String(this._limit));if(this._offset!==void 0)z.append("offset",String(this._offset));if(this._select.length>0&&!this._select.includes("*"))z.append("fields",this._select.join(","));if(this._withRelations.length>0)z.append("include",this._withRelations.join(","));return z}buildUrl(z){let F=`${K.baseUrl}/${this.getTablePath()}`;if(z!==void 0)return`${F}/${z}`;let J=this.buildQueryParams().toString();return J?`${F}?${J}`:F}async get(){let z=this.buildUrl(),F=await fetch(z,{method:"GET",headers:await W()}),G=await X(F);return(Array.isArray(G)?G:G.data).map((L)=>new j(this._definition,L))}async first(){return this._limit=1,(await this.get())[0]??null}async firstOrFail(){let z=await this.first();if(!z)throw new Y(`No ${this._definition.name} found`,404);return z}async find(z){let F=this.buildUrl(z);try{let G=await fetch(F,{method:"GET",headers:await W()});if(G.status===404)return null;let J=await X(G),L="data"in J&&!Array.isArray(J.data)?J.data:J;return new j(this._definition,L)}catch{return null}}async findOrFail(z){let F=await this.find(z);if(!F)throw new Y(`${this._definition.name} with id ${z} not found`,404);return F}async count(){let z=this.buildQueryParams();z.append("count","true");let F=`${K.baseUrl}/${this.getTablePath()}?${z.toString()}`,G=await fetch(F,{method:"GET",headers:await W()});return(await X(G)).count}async exists(){return await this.count()>0}async pluck(z){return this._select=[z],(await this.get()).map((G)=>G.get(z))}async paginate(z=1,F=15){this._limit=F,this._offset=(z-1)*F;let G=this.buildQueryParams();G.append("paginate","true");let J=`${K.baseUrl}/${this.getTablePath()}?${G.toString()}`,L=await fetch(J,{method:"GET",headers:await W()}),U=await X(L);return{...U,data:U.data.map((Z)=>new j(this._definition,Z))}}}function k(z){return new Proxy({query:()=>new N(z),where(G,J,L){return new N(z).where(G,J,L)},orWhere(G,J,L){return new N(z).orWhere(G,J,L)},whereIn(G,J){return new N(z).whereIn(G,J)},whereNotIn(G,J){return new N(z).whereNotIn(G,J)},whereNull(G){return new N(z).whereNull(G)},whereNotNull(G){return new N(z).whereNotNull(G)},whereLike(G,J){return new N(z).whereLike(G,J)},orderBy(G,J="asc"){return new N(z).orderBy(G,J)},orderByDesc(G){return new N(z).orderByDesc(G)},select(...G){return new N(z).select(...G)},limit:(G)=>new N(z).limit(G),take:(G)=>new N(z).take(G),skip:(G)=>new N(z).skip(G),latest:(G="created_at")=>new N(z).latest(G),oldest:(G="created_at")=>new N(z).oldest(G),async find(G){return new N(z).find(G)},async findOrFail(G){return new N(z).findOrFail(G)},async all(){return new N(z).get()},async first(){return new N(z).first()},async firstOrFail(){return new N(z).firstOrFail()},async count(){return new N(z).count()},async exists(){return new N(z).exists()},async paginate(G,J){return new N(z).paginate(G,J)},async pluck(G){return new N(z).pluck(G)},async create(G){let J=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,L=`${K.baseUrl}/${J}`,U=K.transformRequest?K.transformRequest(G):G,Z=await fetch(L,{method:"POST",headers:await W(),body:JSON.stringify(U)}),_=await X(Z),$="data"in _&&!Array.isArray(_.data)?_.data:_;return new j(z,$)},async update(G,J){let L=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,U=`${K.baseUrl}/${L}/${G}`,Z=K.transformRequest?K.transformRequest(J):J,_=await fetch(U,{method:"PATCH",headers:await W(),body:JSON.stringify(Z)}),$=await X(_),A="data"in $&&!Array.isArray($.data)?$.data:$;return new j(z,A)},async delete(G){let J=typeof z.traits?.useApi==="object"&&z.traits.useApi?.uri||z.table,L=`${K.baseUrl}/${J}/${G}`;return(await fetch(L,{method:"DELETE",headers:await W()})).ok},async destroy(G){return this.delete(G)},getDefinition:()=>z,getTable:()=>z.table},{get(G,J){if(typeof J==="string"&&J.startsWith("where")&&J.length>5){let L=J.slice(5),U=L.charAt(0).toLowerCase()+L.slice(1);if(U in z.attributes||U==="id"||U===z.primaryKey)return(Z)=>new N(z).where(U,Z)}return Reflect.get(G,J)}})}var K,Y,E,V;var S=T(()=>{K={baseUrl:""};Y=class Y extends Error{status;constructor(z,F){super(z);this.name="BrowserQueryError",this.status=F}};E={async login(z){let F=await fetch(`${K.baseUrl}/login`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...K.headers},body:JSON.stringify(z)});if(!F.ok){let L=await F.json().catch(()=>({message:"Login failed"}));throw new Y(L.message||"Login failed",F.status)}let G=await F.json(),J=G.data||G;if(typeof localStorage<"u"&&J.token)localStorage.setItem("auth_token",J.token);return J},async register(z){let F=await fetch(`${K.baseUrl}/register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",...K.headers},body:JSON.stringify(z)});if(!F.ok){let L=await F.json().catch(()=>({message:"Registration failed"}));throw new Y(L.message||"Registration failed",F.status)}let G=await F.json(),J=G.data||G;if(typeof localStorage<"u"&&J.token)localStorage.setItem("auth_token",J.token);return J},async logout(){if(await D())try{await fetch(`${K.baseUrl}/logout`,{method:"POST",headers:await W()})}catch{}if(typeof localStorage<"u")localStorage.removeItem("auth_token")},async user(){if(!await D())return null;try{let F=await fetch(`${K.baseUrl}/user`,{method:"GET",headers:await W()});if(F.status===401)return K.onUnauthorized?.(),null;if(!F.ok)return null;let G=await F.json();return G.user||G}catch{return null}},async check(){return await this.user()!==null},getToken:D},V=q});
|
|
3
|
+
export{I as Lb,R as Mb,P as Nb,Y as Ob,x as Pb,q as Qb,H as Rb,k as Sb,E as Tb,V as Ub,S as Vb};
|