@kyro-cms/core 0.12.48 → 0.12.50
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/README.md +1 -0
- package/dist/api-handler-graphql.cjs +1 -1
- package/dist/api-handler-graphql.js +1 -1
- package/dist/api-handler-trpc.cjs +1 -1
- package/dist/api-handler-trpc.js +1 -1
- package/dist/api-handler.cjs +1 -1
- package/dist/api-handler.d.cts +2 -1
- package/dist/api-handler.d.ts +2 -1
- package/dist/api-handler.js +1 -1
- package/dist/auth-session-DHVGXHOH.cjs +1 -0
- package/dist/auth-session-O7IIH7EP.js +1 -0
- package/dist/bcryptjs-ZEEHSMAG.js +2 -0
- package/dist/{better-sqlite3-42Q3FG3E.js → better-sqlite3-B34RIU4C.js} +1 -1
- package/dist/bootstrap-4FK3LPPH.js +1 -0
- package/dist/bootstrap-F4SDJLPK.cjs +1 -0
- package/dist/{bowser-FI5JQGKZ.js → bowser-SB3ZUPO4.js} +1 -1
- package/dist/chokidar-5RVQZVHP.cjs +5 -0
- package/dist/chokidar-BOYGRT4Q.js +6 -0
- package/dist/{chunk-DS5DE5BU.js → chunk-24L3UEJJ.js} +1 -1
- package/dist/{chunk-HT44I66C.js → chunk-2HA6EKXX.js} +1 -1
- package/dist/{chunk-7AQSH3KR.js → chunk-3NSZZCOJ.js} +1 -1
- package/dist/{chunk-VIUU4D5I.js → chunk-47CXBWMA.js} +1 -1
- package/dist/{chunk-6MSS5X77.js → chunk-5M3FKE2V.js} +1 -1
- package/dist/chunk-6TPICJ2L.js +7 -0
- package/dist/{chunk-K7YNEKVE.js → chunk-7FXEXHK6.js} +1 -1
- package/dist/{chunk-WSP7PSXC.js → chunk-7MNDQU6K.js} +1 -1
- package/dist/{chunk-7V67ONUD.js → chunk-7N7U2ERH.js} +1 -1
- package/dist/{chunk-BPMA2ECA.js → chunk-7NH7H3WA.js} +1 -1
- package/dist/{chunk-ZJE3VAAW.js → chunk-BU6O3TP7.js} +3 -3
- package/dist/{chunk-W46LZ4MY.js → chunk-C7QCZX7X.js} +1 -1
- package/dist/chunk-CFZVJTXW.cjs +264 -0
- package/dist/{chunk-2WFTETFB.js → chunk-CIVA6SKW.js} +1 -1
- package/dist/chunk-EFGOYI57.js +265 -0
- package/dist/{chunk-2BUODBE2.js → chunk-EML5FDUU.js} +1 -1
- package/dist/{chunk-66BJXVFJ.js → chunk-FLMUMPDE.js} +1 -1
- package/dist/chunk-H5UFXXWD.js +2 -0
- package/dist/{chunk-M2QRXAWT.js → chunk-HAM4M6VZ.js} +9 -9
- package/dist/{chunk-QYI3GOHF.cjs → chunk-HKNQVI76.cjs} +1 -1
- package/dist/{chunk-IP6JUEH3.js → chunk-HRAY65XH.js} +1 -1
- package/dist/{chunk-KH7LM52S.js → chunk-IKGVPXMK.js} +1 -1
- package/dist/{chunk-XOACKBG7.js → chunk-JRUQ5ABB.js} +2 -2
- package/dist/{chunk-OMWQVPV7.js → chunk-JV4HJBXW.js} +1 -1
- package/dist/{chunk-X54XZACS.cjs → chunk-KZHXYXSH.cjs} +2 -2
- package/dist/{chunk-UD6ZPO7T.js → chunk-L2QXP26Q.js} +1 -1
- package/dist/{chunk-ORG67NXX.js → chunk-L3Q64RUX.js} +1 -1
- package/dist/chunk-LELK3TYX.js +3 -0
- package/dist/{chunk-7I6URA6F.js → chunk-LVBHOZZF.js} +1 -1
- package/dist/{chunk-R3NEPC4I.js → chunk-LWM4WABU.js} +1 -1
- package/dist/{chunk-TR3ZS3T3.js → chunk-M75VGFCI.js} +1 -1
- package/dist/chunk-MCIZG4A3.cjs +1 -0
- package/dist/{chunk-VBPAAQEF.js → chunk-N5POANYV.js} +1 -1
- package/dist/chunk-O4YE57OS.cjs +6 -0
- package/dist/{chunk-A73AVVFR.js → chunk-OBYAIJVU.js} +1 -1
- package/dist/chunk-OLRCZ6E3.js +2 -0
- package/dist/{chunk-WGESLAWV.js → chunk-OXGJOYEO.js} +1 -1
- package/dist/{chunk-CGPAS4U5.js → chunk-P6JITOFF.js} +1 -1
- package/dist/{chunk-JUJZOG6P.js → chunk-PA4ZZREG.js} +1 -1
- package/dist/{chunk-45TJAB5X.js → chunk-PENOCINR.js} +3 -3
- package/dist/{chunk-MZOWPV4D.js → chunk-PRMILS4Y.js} +1 -1
- package/dist/chunk-QDBGBDCT.js +2 -0
- package/dist/{chunk-XBH4YMC7.js → chunk-R25WLKX4.js} +1 -1
- package/dist/{chunk-J6U5LWZ7.js → chunk-RPRGGGIW.js} +3 -3
- package/dist/{chunk-E27KEZPT.js → chunk-RTHJ6SS5.js} +1 -1
- package/dist/{chunk-MCZ3YZ2L.js → chunk-SLMIYECU.js} +1 -1
- package/dist/{chunk-IPXOY4RI.js → chunk-SQBTIMWF.js} +1 -1
- package/dist/{chunk-VJ2WMKPK.js → chunk-SZT6BLUR.js} +1 -1
- package/dist/{chunk-6KRR7YHA.js → chunk-TBHNE4VV.js} +1 -1
- package/dist/{chunk-FAAAHE5O.cjs → chunk-TUIKVRQN.cjs} +8 -8
- package/dist/{chunk-OSAVAYJZ.js → chunk-TYQYKKWJ.js} +1 -1
- package/dist/{chunk-ICVQWR2A.js → chunk-U6KFONKM.js} +1 -1
- package/dist/chunk-UT7RGIYS.js +2 -0
- package/dist/{chunk-PBOZJOKN.js → chunk-UWHWSWDE.js} +1 -1
- package/dist/chunk-VVVCCB6R.js +2 -0
- package/dist/{chunk-MY42EWZP.js → chunk-W45TLOOT.js} +1 -1
- package/dist/chunk-WJBQ2NBD.cjs +1 -0
- package/dist/{chunk-ATBH763U.js → chunk-WPM6LFCY.js} +1 -1
- package/dist/chunk-XBQ6HV3T.cjs +114 -0
- package/dist/{chunk-C2PXMVR5.js → chunk-Y2YAKDEQ.js} +1 -1
- package/dist/chunk-YENNL5HG.js +2 -0
- package/dist/chunk-YP3SCVT3.cjs +1 -0
- package/dist/{chunk-SYEP5QLG.js → chunk-YUUXFD73.js} +1 -1
- package/dist/{chunk-NWCREF47.js → chunk-YZEMLLD2.js} +1 -1
- package/dist/chunk-ZKHTFR5S.cjs +2 -0
- package/dist/{chunk-7T35572E.js → chunk-ZMG7Z3KF.js} +1 -1
- package/dist/{chunk-HLAEJB5R.js → chunk-ZRIBWDYJ.js} +1 -1
- package/dist/chunk-ZWDBPEXL.js +115 -0
- package/dist/cli/index.cjs +1 -1
- package/dist/cli/index.js +2 -2
- package/dist/client.js +1 -1
- package/dist/{d1-VPH75GI2.js → d1-HPB6B253.js} +1 -1
- package/dist/{dist-es-6TQTDPE7.js → dist-es-64F22JL2.js} +2 -2
- package/dist/{dist-es-XZBHIIKY.js → dist-es-F2ZR55UK.js} +2 -2
- package/dist/dist-es-IPSSZNFP.js +1 -0
- package/dist/{dist-es-SJ76GYCI.js → dist-es-M2F7M27Y.js} +1 -1
- package/dist/{dist-es-U4ZB3ZDA.js → dist-es-M66JKZF5.js} +1 -1
- package/dist/{dist-es-MNIQZC4U.js → dist-es-OKLLRYI3.js} +2 -2
- package/dist/{dist-es-TX4DBXEW.js → dist-es-SVHZDVUF.js} +2 -2
- package/dist/{dist-es-EMUQ6ZNZ.js → dist-es-WFI55HKT.js} +1 -1
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.d.cts +1 -0
- package/dist/drizzle/index.d.ts +1 -0
- package/dist/drizzle/index.js +1 -1
- package/dist/drizzle-orm-XRTSOQJS.js +1 -0
- package/dist/event-streams-7NAWZW2I.js +1 -0
- package/dist/fields/index.js +1 -1
- package/dist/fs-KWBRQ6T6.js +1 -0
- package/dist/fs-ZQYOJOIO.cjs +1 -0
- package/dist/graphql/index.js +1 -1
- package/dist/index.cjs +9 -9
- package/dist/index.d.cts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +10 -10
- package/dist/integration.js +1 -1
- package/dist/{jsonwebtoken-S7BG2YWK.js → jsonwebtoken-OD67R5JS.js} +3 -3
- package/dist/{lib-IYW32OER.js → lib-XXYYUPMW.js} +3 -3
- package/dist/{loadSso-YTG2GQGW.js → loadSso-UQR6545M.js} +1 -1
- package/dist/local-3V3XEQUY.js +1 -0
- package/dist/media-E762GEHL.js +1 -0
- package/dist/mongo-auth-adapter-QDXVHREJ.js +1 -0
- package/dist/{mongo-auth-adapter-7K64Y2QM.cjs → mongo-auth-adapter-W3HLB7OR.cjs} +1 -1
- package/dist/mongodb/index.cjs +1 -1
- package/dist/mongodb/index.js +1 -1
- package/dist/{nodemailer-AXROO37D.js → nodemailer-NITB45SS.js} +3 -3
- package/dist/postgres-auth-adapter-SK3N3OSS.js +1 -0
- package/dist/postgres-auth-adapter-ZO6HK5AK.cjs +1 -0
- package/dist/postgres-js-3Y54EXVQ.cjs +1 -1
- package/dist/postgres-js-4CI7FMYS.js +1 -0
- package/dist/redis-adapter-QPCTMF55.js +1 -0
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.js +1 -1
- package/dist/schema-YFMSJK2P.js +2 -0
- package/dist/{signin-KZBIAHGS.js → signin-N3T2KF5Q.js} +1 -1
- package/dist/sqlite-adapter-4TPNROJK.js +1 -0
- package/dist/src-QBADSZV4.js +1 -0
- package/dist/{sso-oidc-SX5OIQGG.js → sso-oidc-UB7G4END.js} +1 -1
- package/dist/{sts-HVGDJYIF.js → sts-WAA6I22C.js} +1 -1
- package/dist/templates/index.js +1 -1
- package/dist/trpc/index.js +1 -1
- package/dist/ws/index.js +1 -1
- package/package.json +2 -2
- package/dist/bcryptjs-AZA6WEN2.js +0 -2
- package/dist/bootstrap-7CI3NVSY.js +0 -1
- package/dist/bootstrap-DOOM2CNQ.cjs +0 -1
- package/dist/chokidar-24HVS6XD.cjs +0 -5
- package/dist/chokidar-43DT7CVN.js +0 -6
- package/dist/chunk-5DWYVUQR.cjs +0 -1
- package/dist/chunk-6QWLXJ7L.js +0 -2
- package/dist/chunk-B3GDQ7UI.cjs +0 -114
- package/dist/chunk-BLH2MRK4.js +0 -2
- package/dist/chunk-EOOZDOL7.js +0 -3
- package/dist/chunk-IIOVJTCD.cjs +0 -1
- package/dist/chunk-L4ZAI2XB.cjs +0 -269
- package/dist/chunk-PL5AIE6F.js +0 -2
- package/dist/chunk-QDHP5E4P.cjs +0 -2
- package/dist/chunk-R2CLQMNJ.js +0 -270
- package/dist/chunk-R4LXRAMX.js +0 -2
- package/dist/chunk-SVYUTQVE.js +0 -115
- package/dist/chunk-UB5TJHQR.js +0 -2
- package/dist/chunk-XPPVX4GQ.cjs +0 -1
- package/dist/chunk-XRINX47D.js +0 -2
- package/dist/dist-es-6SVFVYN3.js +0 -1
- package/dist/drizzle-orm-7YTX5NTT.js +0 -1
- package/dist/event-streams-25YJ2Z6R.js +0 -1
- package/dist/fs-DGKZLRM6.cjs +0 -1
- package/dist/fs-YZJ5FM6J.js +0 -2
- package/dist/local-VDCSEMC2.js +0 -1
- package/dist/media-HK2IZMUZ.js +0 -1
- package/dist/mongo-auth-adapter-BUKINEZL.js +0 -1
- package/dist/postgres-auth-adapter-2M4RNEY3.cjs +0 -1
- package/dist/postgres-auth-adapter-MKSHIJDL.js +0 -1
- package/dist/postgres-js-INQPBHJP.js +0 -1
- package/dist/redis-adapter-SXOXLHNH.js +0 -1
- package/dist/schema-XC5ISGNR.js +0 -2
- package/dist/sqlite-adapter-DV7ZX2EJ.js +0 -1
- package/dist/src-GZRZ4VAO.js +0 -1
- /package/dist/{chunk-P7XYIKL6.cjs → chunk-YUER4JU3.cjs} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {g as g$1}from'./chunk-Y2YAKDEQ.js';import {getRandomValues}from'crypto';import {ReadStream,lstatSync,fstatSync}from'fs';import {Readable,Writable}from'stream';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
g$1();g$1();g$1();var J=e=>typeof ArrayBuffer=="function"&&e instanceof ArrayBuffer||Object.prototype.toString.call(e)==="[object ArrayBuffer]";var B=(e,t=0,r=e.byteLength-t)=>{if(!J(e))throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof e} (${e})`);return Buffer.from(e,t,r)},U=(e,t)=>{if(typeof e!="string")throw new TypeError(`The "input" argument must be of type string. Received type ${typeof e} (${e})`);return t?Buffer.from(e,t):Buffer.from(e)};var R=e=>{let t=U(e,"utf8");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength/Uint8Array.BYTES_PER_ELEMENT)};g$1();var se=e=>{if(typeof e=="string")return e;if(typeof e!="object"||typeof e.byteOffset!="number"||typeof e.byteLength!="number")throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return B(e.buffer,e.byteOffset,e.byteLength).toString("utf8")};g$1();var ie={},W={};for(let e=0;e<256;e++){let t=e.toString(16).toLowerCase();t.length===1&&(t=`0${t}`),ie[e]=t,W[t]=e;}function De(e){if(e.length%2!==0)throw new Error("Hex encoded strings must have an even number length");let t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2){let n=e.slice(r,r+2).toLowerCase();if(n in W)t[r/2]=W[n];else throw new Error(`Cannot decode unrecognized sequence ${n} as hexadecimal`)}return t}function z(e){let t="";for(let r=0;r<e.byteLength;r++)t+=ie[e[r]];return t}g$1();g$1();var _e=/^[A-Za-z0-9+/]*={0,2}$/,ae=e=>{if(e.length*3%4!==0)throw new TypeError("Incorrect padding on base64 string.");if(!_e.exec(e))throw new TypeError("Invalid base64 string.");let t=U(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)};g$1();var F=e=>{let t;if(typeof e=="string"?t=R(e):t=e,typeof t!="object"||typeof t.byteOffset!="number"||typeof t.byteLength!="number")throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");return B(t.buffer,t.byteOffset,t.byteLength).toString("base64")};g$1();function fe(e,t,r,n){return class O extends Uint8Array{static fromString(s,a="utf-8"){if(typeof s=="string")return a==="base64"?O.mutate(n(s)):O.mutate(t(s));throw new Error(`Unsupported conversion from ${typeof s} to Uint8ArrayBlobAdapter.`)}static mutate(s){return Object.setPrototypeOf(s,O.prototype),s}transformToString(s="utf-8"){return s==="base64"?r(this):e(this)}}}g$1();var l=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function ce(e){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?()=>crypto.randomUUID():()=>{let t=new Uint8Array(16);return e(t),t[6]=t[6]&15|64,t[8]=t[8]&63|128,l[t[0]]+l[t[1]]+l[t[2]]+l[t[3]]+"-"+l[t[4]]+l[t[5]]+"-"+l[t[6]]+l[t[7]]+"-"+l[t[8]]+l[t[9]]+"-"+l[t[10]]+l[t[11]]+l[t[12]]+l[t[13]]+l[t[14]]+l[t[15]]}}g$1();g$1();var j=e=>{if(e!=null){if(typeof e=="string"){let t=parseFloat(e);if(!Number.isNaN(t))return String(t)!==String(e)&&ze.warn(We(`Expected number but observed string: ${e}`)),t}if(typeof e=="number")return e;throw new TypeError(`Expected number, got ${typeof e}: ${e}`)}},ke=Math.ceil(34028234663852886e22),ue=e=>{let t=j(e);if(t!==void 0&&!Number.isNaN(t)&&t!==1/0&&t!==-1/0&&Math.abs(t)>ke)throw new TypeError(`Expected 32-bit float, got ${e}`);return t},Pe=e=>{if(e!=null){if(Number.isInteger(e)&&!Number.isNaN(e))return e;throw new TypeError(`Expected integer, got ${typeof e}: ${e}`)}};var de=e=>me(e,16),pe=e=>me(e,8),me=(e,t)=>{let r=Pe(e);if(r!==void 0&&He(r,t)!==r)throw new TypeError(`Expected ${t}-bit integer, got ${e}`);return r},He=(e,t)=>{switch(t){case 32:return Int32Array.of(e)[0];case 16:return Int16Array.of(e)[0];case 8:return Int8Array.of(e)[0]}};var he=e=>j(typeof e=="string"?L(e):e);var ye=e=>ue(typeof e=="string"?L(e):e),Je=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,L=e=>{let t=e.match(Je);if(t===null||t[0].length!==e.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(e)};var N=e=>de(typeof e=="string"?L(e):e),le=e=>pe(typeof e=="string"?L(e):e),We=e=>String(new TypeError(e).stack||e).split(`
|
|
3
3
|
`).slice(0,5).filter(t=>!t.includes("stackTraceWarning")).join(`
|
|
4
4
|
`),ze={warn:console.warn};var je=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Y=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function qe(e){let t=e.getUTCFullYear(),r=e.getUTCMonth(),n=e.getUTCDay(),o=e.getUTCDate(),s=e.getUTCHours(),a=e.getUTCMinutes(),f=e.getUTCSeconds(),c=o<10?`0${o}`:`${o}`,u=s<10?`0${s}`:`${s}`,m=a<10?`0${a}`:`${a}`,h=f<10?`0${f}`:`${f}`;return `${je[n]}, ${c} ${Y[r]} ${t} ${u}:${m}:${h} GMT`}var Ye=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/),Ve=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let t=Ye.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,s,a,f,c,u]=t,m=N(C(n)),h=w(o,"month",1,12),y=w(s,"day",1,31);return M(m,h,y,{hours:a,minutes:f,seconds:c,fractionalMilliseconds:u})},Ge=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}:\d{2})|[zZ])$/),Xe=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");let t=Ge.exec(e);if(!t)throw new TypeError("Invalid RFC-3339 date-time value");let[r,n,o,s,a,f,c,u,m]=t,h=N(C(n)),y=w(o,"month",1,12),b=w(s,"day",1,31),x=M(h,y,b,{hours:a,minutes:f,seconds:c,fractionalMilliseconds:u});return m.toUpperCase()!="Z"&&x.setTime(x.getTime()-ft(m)),x},Ze=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),Ke=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),Qe=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),ve=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let t=Ze.exec(e);if(t){let[r,n,o,s,a,f,c,u]=t;return M(N(C(s)),q(o),w(n,"day",1,31),{hours:a,minutes:f,seconds:c,fractionalMilliseconds:u})}if(t=Ke.exec(e),t){let[r,n,o,s,a,f,c,u]=t;return nt(M(tt(s),q(o),w(n,"day",1,31),{hours:a,minutes:f,seconds:c,fractionalMilliseconds:u}))}if(t=Qe.exec(e),t){let[r,n,o,s,a,f,c,u]=t;return M(N(C(u)),q(n),w(o.trimLeft(),"day",1,31),{hours:s,minutes:a,seconds:f,fractionalMilliseconds:c})}throw new TypeError("Invalid RFC-7231 date-time value")},et=e=>{if(e==null)return;let t;if(typeof e=="number")t=e;else if(typeof e=="string")t=he(e);else if(typeof e=="object"&&e.tag===1)t=e.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(t)||t===1/0||t===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(t*1e3))},M=(e,t,r,n)=>{let o=t-1;return st(e,o,r),new Date(Date.UTC(e,o,r,w(n.hours,"hour",0,23),w(n.minutes,"minute",0,59),w(n.seconds,"seconds",0,60),at(n.fractionalMilliseconds)))},tt=e=>{let t=new Date().getUTCFullYear(),r=Math.floor(t/100)*100+N(C(e));return r<t?r+100:r},rt=50*365*24*60*60*1e3,nt=e=>e.getTime()-new Date().getTime()>rt?new Date(Date.UTC(e.getUTCFullYear()-100,e.getUTCMonth(),e.getUTCDate(),e.getUTCHours(),e.getUTCMinutes(),e.getUTCSeconds(),e.getUTCMilliseconds())):e,q=e=>{let t=Y.indexOf(e);if(t<0)throw new TypeError(`Invalid month: ${e}`);return t+1},ot=[31,28,31,30,31,30,31,31,30,31,30,31],st=(e,t,r)=>{let n=ot[t];if(t===1&&it(e)&&(n=29),r>n)throw new TypeError(`Invalid day for ${Y[t]} in ${e}: ${r}`)},it=e=>e%4===0&&(e%100!==0||e%400===0),w=(e,t,r,n)=>{let o=le(C(e));if(o<r||o>n)throw new TypeError(`${t} must be between ${r} and ${n}, inclusive`);return o},at=e=>e==null?0:ye("0."+e)*1e3,ft=e=>{let t=e[0],r=1;if(t=="+")r=1;else if(t=="-")r=-1;else throw new TypeError(`Offset direction, ${t}, must be "+" or "-"`);let n=Number(e.substring(1,3)),o=Number(e.substring(4,6));return r*(n*60+o)*60*1e3},C=e=>{let t=0;for(;t<e.length-1&&e.charAt(t)==="0";)t++;return t===0?e:e.slice(t)};g$1();var T=function(t){return Object.assign(new String(t),{deserializeJSON(){return JSON.parse(String(t))},toString(){return String(t)},toJSON(){return String(t)}})};T.from=e=>e&&typeof e=="object"&&(e instanceof T||"deserializeJSON"in e)?e:typeof e=="string"||Object.getPrototypeOf(e)===String.prototype?T(String(e)):T(JSON.stringify(e));T.fromObject=T.from;g$1();function ct(e){return (e.includes(",")||e.includes('"'))&&(e=`"${e.replace(/"/g,'\\"')}"`),e}g$1();var V="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?",G="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)",X="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?",be="(\\d?\\d)",ge="(\\d{4})",ut=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/),dt=new RegExp(`^${V}, ${be} ${G} ${ge} ${X} GMT$`),pt=new RegExp(`^${V}, ${be}-${G}-(\\d\\d) ${X} GMT$`),mt=new RegExp(`^${V} ${G} ( [1-9]|\\d\\d) ${X} ${ge}$`),ht=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],yt=e=>{if(e==null)return;let t=NaN;if(typeof e=="number")t=e;else if(typeof e=="string"){if(!/^-?\d*\.?\d+$/.test(e))throw new TypeError("parseEpochTimestamp - numeric string invalid.");t=Number.parseFloat(e);}else typeof e=="object"&&e.tag===1&&(t=e.value);if(isNaN(t)||Math.abs(t)===1/0)throw new TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(t*1e3))},lt=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC3339 timestamps must be strings");let t=ut.exec(e);if(!t)throw new TypeError(`Invalid RFC3339 timestamp format ${e}`);let[,r,n,o,s,a,f,,c,u]=t;S(n,1,12),S(o,1,31),S(s,0,23),S(a,0,59),S(f,0,60);let m=new Date(Date.UTC(Number(r),Number(n)-1,Number(o),Number(s),Number(a),Number(f),Number(c)?Math.round(parseFloat(`0.${c}`)*1e3):0));if(m.setUTCFullYear(Number(r)),u.toUpperCase()!="Z"){let[,h,y,b]=/([+-])(\d\d):(\d\d)/.exec(u)||[void 0,"+",0,0],x=h==="-"?1:-1;m.setTime(m.getTime()+x*(Number(y)*60*60*1e3+Number(b)*60*1e3));}return m},bt=e=>{if(e==null)return;if(typeof e!="string")throw new TypeError("RFC7231 timestamps must be strings.");let t,r,n,o,s,a,f,c;if((c=dt.exec(e))?[,t,r,n,o,s,a,f]=c:(c=pt.exec(e))?([,t,r,n,o,s,a,f]=c,n=(Number(n)+1900).toString()):(c=mt.exec(e))&&([,r,t,o,s,a,f,n]=c),n&&a){let u=Date.UTC(Number(n),ht.indexOf(r),Number(t),Number(o),Number(s),Number(a),f?Math.round(parseFloat(`0.${f}`)*1e3):0);S(t,1,31),S(o,0,23),S(s,0,59),S(a,0,60);let m=new Date(u);return m.setUTCFullYear(Number(n)),m}throw new TypeError(`Invalid RFC7231 date-time value ${e}.`)};function S(e,t,r){let n=Number(e);if(n<t||n>r)throw new Error(`Value ${n} out of range [${t}, ${r}]`)}g$1();function gt(e,t,r){if(r<=0||!Number.isInteger(r))throw new Error("Invalid number of delimiters ("+r+") for splitEvery.");let n=e.split(t);if(r===1)return n;let o=[],s="";for(let a=0;a<n.length;a++)s===""?s=n[a]:s+=t+n[a],(a+1)%r===0&&(o.push(s),s="");return s!==""&&o.push(s),o}g$1();var wt=e=>{let t=e.length,r=[],n=false,o,s=0;for(let a=0;a<t;++a){let f=e[a];switch(f){case '"':o!=="\\"&&(n=!n);break;case ",":n||(r.push(e.slice(s,a)),s=a+1);break;}o=f;}return r.push(e.slice(s)),r.map(a=>{a=a.trim();let f=a.length;return f<2?a:(a[0]==='"'&&a[f-1]==='"'&&(a=a.slice(1,f-1)),a.replace(/\\"/g,'"'))})};g$1();var we=/^-?\d*(\.\d+)?$/,Z=class e{string;type;constructor(t,r){if(this.string=t,this.type=r,!we.test(t))throw new Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](t){if(!t||typeof t!="object")return false;let r=t;return e.prototype.isPrototypeOf(t)||r.type==="bigDecimal"&&we.test(r.string)}};g$1();var Tt=e=>{if(!e)return 0;if(typeof e=="string")return Buffer.byteLength(e);if(typeof e.byteLength=="number")return e.byteLength;if(typeof e.size=="number")return e.size;if(typeof e.start=="number"&&typeof e.end=="number")return e.end+1-e.start;if(e instanceof ReadStream){if(e.path!=null)return lstatSync(e.path).size;if(typeof e.fd=="number")return fstatSync(e.fd).size}throw new Error(`Body Length computation failed for ${e}`)};g$1();var $t=e=>e instanceof Uint8Array?e:typeof e=="string"?R(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e);g$1();function I(e,t){if(t===void 0){t=0;for(let o of e)t+=o.byteLength;}let r=new Uint8Array(t),n=0;for(let o of e)r.set(o,n),n+=o.byteLength;return r}g$1();var D=class extends Readable{expectedChecksum;checksumSourceLocation;checksum;source;base64Encoder;constructor({expectedChecksum:t,checksum:r,source:n,checksumSourceLocation:o,base64Encoder:s}){if(super(),typeof n.pipe!="function")throw new Error(`@smithy/util-stream: unsupported source type ${n?.constructor?.name??n} in ChecksumStream.`);this.source=n,this.base64Encoder=s??F,this.expectedChecksum=t,this.checksum=r,this.checksumSourceLocation=o,this.source.on("data",this.onSourceData),this.source.on("end",this.onSourceEnd),this.source.on("error",this.onSourceError),this.source.on("close",this.onSourceClose),this.source.pause();}onSourceData=t=>{if(!this.destroyed){try{this.checksum.update(t);}catch(r){this.destroy(r);return}this.push(t)||this.source.pause();}};onSourceEnd=async()=>{if(!this.destroyed){try{let t=await this.checksum.digest(),r=this.base64Encoder(t);if(this.expectedChecksum!==r){this.destroy(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${r}" in response header "${this.checksumSourceLocation}".`));return}}catch(t){this.destroy(t);return}this.push(null);}};onSourceError=t=>{this.destroy(t);};onSourceClose=()=>{!this.destroyed&&!this.source.readableEnded&&this.destroy(new Error("Connection lost or stream closed before all data was received."));};_read(t){this.source.resume();}_destroy(t,r){this.source?.removeListener("data",this.onSourceData),this.source?.removeListener("end",this.onSourceEnd),this.source?.removeListener("error",this.onSourceError),this.source?.removeListener("close",this.onSourceClose),this.source?.destroy(),r(t);}};g$1();g$1();var g=e=>typeof ReadableStream=="function"&&(e?.constructor?.name===ReadableStream.name||e instanceof ReadableStream),_=e=>typeof Blob=="function"&&(e?.constructor?.name===Blob.name||e instanceof Blob);g$1();g$1();g$1();var xe=e=>new TextEncoder().encode(e);g$1();var Se="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";Object.entries(Se).reduce((e,[t,r])=>(e[r]=Number(t),e),{});var Ee=Se.split(""),k=6,K=8,Te=63;function P(e){let t;typeof e=="string"?t=xe(e):t=e;let r=typeof t=="object"&&typeof t.length=="number",n=typeof t=="object"&&typeof t.byteOffset=="number"&&typeof t.byteLength=="number";if(!r&&!n)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let o="";for(let s=0;s<t.length;s+=3){let a=0,f=0;for(let u=s,m=Math.min(s+3,t.length);u<m;u++)a|=t[u]<<(m-u-1)*K,f+=K;let c=Math.ceil(f/k);a<<=c*k-f;for(let u=1;u<=c;u++){let m=(c-u)*k;o+=Ee[(a&Te<<m)>>m];}o+="==".slice(0,4-c);}return o}g$1();var Bt=typeof ReadableStream=="function"?ReadableStream:function(){},H=class extends Bt{};var $e=({expectedChecksum:e,checksum:t,source:r,checksumSourceLocation:n,base64Encoder:o})=>{if(!g(r))throw new Error(`@smithy/util-stream: unsupported source type ${r?.constructor?.name??r} in ChecksumStream.`);let s=o??P;if(typeof TransformStream!="function")throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");let a=new TransformStream({start(){},async transform(c,u){t.update(c),u.enqueue(c);},async flush(c){let u=await t.digest(),m=s(u);if(e!==m){let h=new Error(`Checksum mismatch: expected "${e}" but received "${m}" in response header "${n}".`);c.error(h);}else c.terminate();}});r.pipeThrough(a);let f=a.readable;return Object.setPrototypeOf(f,H.prototype),f};function Rt(e){return typeof ReadableStream=="function"&&g(e.source)?$e(e):new D(e)}g$1();g$1();var $=class{allocByteArray;byteLength=0;byteArrays=[];constructor(t){this.allocByteArray=t;}push(t){this.byteArrays.push(t),this.byteLength+=t.byteLength;}flush(){if(this.byteArrays.length===1){let n=this.byteArrays[0];return this.reset(),n}let t=this.allocByteArray(this.byteLength),r=0;for(let n=0;n<this.byteArrays.length;++n){let o=this.byteArrays[n];t.set(o,r),r+=o.byteLength;}return this.reset(),t}reset(){this.byteArrays=[],this.byteLength=0;}};g$1();function Ae(e,t,r){let n=e.getReader(),o=false,s=0,a=["",new $(u=>new Uint8Array(u))],f=-1,c=async u=>{let{value:m,done:h}=await n.read(),y=m;if(h){if(f!==-1){let b=A(a,f);E(b)>0&&u.enqueue(b);}u.close();}else {let b=v(y,false);if(f!==b&&(f>=0&&u.enqueue(A(a,f)),f=b),f===-1){u.enqueue(y);return}let x=E(y);s+=x;let Le=E(a[f]);if(x>=t&&Le===0)u.enqueue(y);else {let Ie=Q(a,f,y);!o&&s>t*2&&(o=true,r?.warn(`@smithy/util-stream - stream chunk size ${x} is below threshold of ${t}, automatically buffering.`)),Ie>=t?u.enqueue(A(a,f)):await c(u);}}};return new ReadableStream({pull:c})}function Q(e,t,r){switch(t){case 0:return e[0]+=r,E(e[0]);case 1:case 2:return e[t].push(r),E(e[t])}}function A(e,t){switch(t){case 0:let r=e[0];return e[0]="",r;case 1:case 2:return e[t].flush()}throw new Error(`@smithy/util-stream - invalid index ${t} given to flush()`)}function E(e){return e?.byteLength??e?.length??0}function v(e,t=true){return t&&typeof Buffer<"u"&&e instanceof Buffer?2:e instanceof Uint8Array?1:typeof e=="string"?0:-1}function Ct(e,t,r){if(g(e))return Ae(e,t,r);let n=new Readable({read(){}}),o=false,s=0,a=["",new $(c=>new Uint8Array(c)),new $(c=>Buffer.from(new Uint8Array(c)))],f=-1;return e.on("data",c=>{let u=v(c,true);if(f!==u&&(f>=0&&n.push(A(a,f)),f=u),f===-1){n.push(c);return}let m=E(c);s+=m;let h=E(a[f]);if(m>=t&&h===0)n.push(c);else {let y=Q(a,f,c);!o&&s>t*2&&(o=true,r?.warn(`@smithy/util-stream - stream chunk size ${m} is below threshold of ${t}, automatically buffering.`)),y>=t&&n.push(A(a,f));}}),e.on("end",()=>{if(f!==-1){let c=A(a,f);E(c)>0&&n.push(c);}n.push(null);}),n}g$1();g$1();var Be=(e,t)=>{let{base64Encoder:r,bodyLengthChecker:n,checksumAlgorithmFn:o,checksumLocationName:s,streamHasher:a}=t,f=r!==void 0&&n!==void 0&&o!==void 0&&s!==void 0&&a!==void 0,c=f?a(o,e):void 0,u=e.getReader();return new ReadableStream({async pull(m){let{value:h,done:y}=await u.read();if(y){if(m.enqueue(`0\r
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {v as v$1}from'./chunk-TYQYKKWJ.js';import {g}from'./chunk-Y2YAKDEQ.js';import*as N from'zlib';import {Writable}from'stream';import {createHash,createHmac}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
g();g();var M=new Uint32Array(256);for(let n=0;n<256;++n){let e=n;for(let t=0;t<8;++t)e=e&1?3988292384^e>>>1:e>>>1;M[n]=e>>>0;}var H=4294967295,w=class{digestLength=4;checksum=H;update(e){for(let t=0;t<e.length;++t)this.checksum=this.checksum>>>8^M[(this.checksum^e[t])&255];}digestSync(){return (this.checksum^H)>>>0}async digest(){let e=this.digestSync(),t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,false),t}reset(){this.checksum=H;}};var v=typeof N.crc32=="function"?N.crc32:void 0,E=v?G(v):w;function G(n){return class{digestLength=4;value=0;update(t){this.value=n(t,this.value);}digestSync(){return this.value>>>0}async digest(){let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,this.digestSync(),false),t}reset(){this.value=0;}}}g();g();var A=class extends Writable{hash;constructor(e,t){super(t),this.hash=e;}_write(e,t,r){try{this.hash.update(v$1(e));}catch(s){return r(s)}r();}};g();var _=(n,e)=>{if(e.readableFlowing!==null)throw new Error("Unable to calculate hash for flowing readable stream");let t=new n,r=new A(t);return e.pipe(r),new Promise((s,f)=>{e.on("error",h=>{r.end(),f(h);}),r.on("error",f),r.on("finish",()=>{t.digest().then(s).catch(f);});})};g();var U=class{digestLength=16;state=Uint32Array.from(I);writeBuffer=new DataView(new ArrayBuffer(64));bufferLength=0;bytesHashed=0;update(e){let t=v$1(e),r=0,s=t.byteLength;for(this.bytesHashed+=s;s>0;)this.writeBuffer.setUint8(this.bufferLength++,t[r++]),--s,this.bufferLength===64&&(S(this.state,this.writeBuffer),this.bufferLength=0);}async digest(){let e=Uint32Array.from(this.state),t=new DataView(this.writeBuffer.buffer.slice(0)),r=this.bufferLength,s=this.bytesHashed*8;if(t.setUint8(r++,128),this.bufferLength%64>=56){for(let i=r;i<64;++i)t.setUint8(i,0);S(e,t),r=0;}for(let i=r;i<56;++i)t.setUint8(i,0);t.setUint32(56,s>>>0,true),t.setUint32(60,Math.floor(s/2**32),true),S(e,t);let f=new Uint8Array(16),h=new DataView(f.buffer);for(let i=0;i<4;++i)h.setUint32(i*4,e[i],true);return f}reset(){this.state.set(I),this.writeBuffer=new DataView(new ArrayBuffer(64)),this.bufferLength=0,this.bytesHashed=0;}},I=[1732584193,4023233417,2562383102,271733878],y=4294967295,R=Uint8Array.of(7,12,17,22,5,9,14,20,4,11,16,23,6,10,15,21),F=Array.from({length:64},(n,e)=>Math.abs(Math.sin(e+1))*2**32>>>0);function S(n,e){let t=n[0],r=n[1],s=n[2],f=n[3];for(let h=0;h<64;++h){let i,c;h<16?(i=r&s|~r&f,c=h):h<32?(i=f&r|s&~f,c=(5*h+1)%16):h<48?(i=r^s^f,c=(3*h+5)%16):(i=s^(r|~f),c=7*h%16);let m=e.getUint32(c*4,true),p=f;f=s,s=r;let g=R[(h>>4)*4+(h&3)],a=(t+i&y)+(m+F[h]&y)&y;r=r+((a<<g|a>>>32-g)>>>0)&y,t=p;}n[0]=n[0]+t&y,n[1]=n[1]+r&y,n[2]=n[2]+s&y,n[3]=n[3]+f&y;}g();var P=(()=>{try{return createHash("md5"),!0}catch{return false}})(),D=P?X():U;function X(){return class{digestLength=16;hash=createHash("md5");update(e){this.hash.update(v$1(e));}async digest(){let e=this.hash.copy().digest();return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}reset(){this.hash=createHash("md5");}}}g();var u=64,V=32,q=2**53-1,L=class n{digestLength=V;state=Int32Array.from(k);w;buffer=new Uint8Array(64);bufferLength=0;bytesHashed=0;finished=false;inner;outer;constructor(e){if(e){let t=n.normalizeKey(e);this.inner=new n,this.outer=new n;let{inner:r,outer:s}=this,f=new Uint8Array(u*2);for(let h=0;h<u;++h)f[h]=54^t[h],f[h+u]=92^t[h];r.update(f.subarray(0,u)),s.update(f.subarray(u));}}update(e){if(this.finished)throw new Error("Attempted to update an already finished HMAC.");if(this.inner){this.inner.update(e);return}let t=v$1(e),r=0,{byteLength:s}=t;if(this.bytesHashed+=s,this.bytesHashed*8>q)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;s>0;)this.buffer[this.bufferLength++]=t[r++],s--,this.bufferLength===u&&(this.hashBuffer(),this.bufferLength=0);}async digest(){let{inner:e,outer:t}=this;if(e&&t){if(this.finished)throw new Error("Attempted to digest an already finished HMAC.");this.finished=true;let r=e.digestSync();return t.update(r),t.digestSync()}return this.digestSync()}reset(){this.state=Int32Array.from(k),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0;}digestSync(){let e=this.state.slice(),t=this.buffer.slice(),r=this.bufferLength,s=this.bytesHashed*8,f=new DataView(t.buffer,t.byteOffset,t.byteLength);if(f.setUint8(r++,128),(r-1)%u>=u-8){for(let i=r;i<u;++i)f.setUint8(i,0);this.hashBufferWith(e,t),r=0;}for(let i=r;i<u-8;++i)f.setUint8(i,0);f.setUint32(u-8,Math.floor(s/4294967296),false),f.setUint32(u-4,s,false),this.hashBufferWith(e,t);let h=new Uint8Array(V);for(let i=0;i<8;++i)h[i*4]=e[i]>>>24&255,h[i*4+1]=e[i]>>>16&255,h[i*4+2]=e[i]>>>8&255,h[i*4+3]=e[i]>>>0&255;return h}static normalizeKey(e){let t=v$1(e);if(t.byteLength>u){let r=new n;r.update(t);let s=r.digestSync(),f=new Uint8Array(u);return f.set(s),f}if(t.byteLength<u){let r=new Uint8Array(u);return r.set(t),r}return t}hashBuffer(){this.hashBufferWith(this.state,this.buffer);}hashBufferWith(e,t){let r=this.w??=new Int32Array(64),s=e[0],f=e[1],h=e[2],i=e[3],c=e[4],m=e[5],p=e[6],g=e[7];for(let a=0;a<u;++a){if(a<16)r[a]=(t[a*4]&255)<<24|(t[a*4+1]&255)<<16|(t[a*4+2]&255)<<8|t[a*4+3]&255;else {let d=r[a-2],W=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10;d=r[a-15];let K=(d>>>7|d<<25)^(d>>>18|d<<14)^d>>>3;r[a]=(W+r[a-7]|0)+(K+r[a-16]|0);}let C=(((c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&m^~c&p)|0)+(g+(Q[a]+r[a]|0)|0)|0,O=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&f^s&h^f&h)|0;g=p,p=m,m=c,c=i+C|0,i=h,h=f,f=s,s=C+O|0;}e[0]+=s,e[1]+=f,e[2]+=h,e[3]+=i,e[4]+=c,e[5]+=m,e[6]+=p,e[7]+=g;}},k=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Q=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);g();var Z=(()=>{try{return createHash("sha256"),!0}catch{return false}})(),z=Z?$():L;function $(){return class{digestLength=32;secret;hash;isHmac;finished=false;constructor(e){this.secret=e,this.isHmac=!!e,this.hash=this.createHash();}update(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");this.hash.update(e);}async digest(){let e;return this.isHmac?(this.finished=true,e=this.hash.digest()):e=this.hash.copy().digest(),new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}reset(){this.hash=this.createHash(),this.finished=false;}createHash(){return this.secret?createHmac("sha256",j(this.secret)):createHash("sha256")}}}function j(n){return typeof n=="string"?n:ArrayBuffer.isView(n)?Buffer.from(n.buffer,n.byteOffset,n.byteLength):Buffer.from(n)}export{_ as a,D as b,E as c,z as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {a}from'./chunk-7NH7H3WA.js';import {g as g$1,e}from'./chunk-Y2YAKDEQ.js';import {randomUUID,randomBytes}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
g$1();var c=e(a(),1);var g=class{db;adapter;prefix;sessionTTL;refreshTokenTTL;indexesEnsured=false;constructor(e){this.db=e.db,this.adapter=e.adapter,this.prefix=e.collectionPrefix||"",this.sessionTTL=e.sessionTTL||86400,this.refreshTokenTTL=e.refreshTokenTTL||604800;}getDatabase(){let e=typeof this.db=="function"?this.db():this.db;if(!e&&this.adapter&&(this.adapter.db?e=this.adapter.db:this.adapter.client&&(this.adapter.db=this.adapter.client.db(this.adapter.database||"kyro_cms"),e=this.adapter.db)),!e)throw new Error("MongoDB database not initialized");return e}col(e){return this.getDatabase().collection(`${this.prefix}${e}`)}async connect(){this.adapter&&!this.adapter.connected&&await this.adapter.connect(),this.indexesEnsured||await this.ensureIndexes();}async disconnect(){}async ensureIndexes(){await this.col("users").createIndex({email:1},{unique:true}),await this.col("users").createIndex({tenantId:1}),await this.col("users").createIndex({role:1}),await this.col("sessions").createIndex({token:1},{unique:true}),await this.col("sessions").createIndex({refreshToken:1}),await this.col("sessions").createIndex({userId:1}),await this.col("sessions").createIndex({expiresAt:1},{expireAfterSeconds:0}),await this.col("audit_logs").createIndex({timestamp:-1}),await this.col("audit_logs").createIndex({userId:1}),await this.col("audit_logs").createIndex({action:1}),await this.col("audit_logs").createIndex({resource:1}),await this.col("password_history").createIndex({userId:1,createdAt:-1}),await this.col("lockouts").createIndex({userId:1},{unique:true}),await this.col("lockouts").createIndex({lockedUntil:1}),this.indexesEnsured=true;}async createUser(e){let s=randomUUID(),t=new Date,i=await this.hashPassword(e.password),r={_id:s,name:e.name||null,email:e.email.toLowerCase(),passwordHash:i,role:e.role||"customer",avatar:e.avatar||null,tenantId:e.tenantId||null,emailVerified:false,locked:false,lastLogin:null,failedLoginAttempts:0,createdAt:t,updatedAt:t};return await this.col("users").insertOne(r),this.docToAuthUser(r)}async findUserByEmail(e){let s=await this.col("users").findOne({email:e.toLowerCase()});return s?this.docToAuthUser(s):null}async findUserById(e){let s=await this.col("users").findOne({_id:e});return s?this.docToAuthUser(s):null}async updateUser(e,s){let t={updatedAt:new Date};s.name!==void 0&&(t.name=s.name),s.email!==void 0&&(t.email=s.email),s.passwordHash!==void 0&&(t.passwordHash=s.passwordHash),s.role!==void 0&&(t.role=s.role),s.avatar!==void 0&&(t.avatar=s.avatar),s.tenantId!==void 0&&(t.tenantId=s.tenantId),s.emailVerified!==void 0&&(t.emailVerified=s.emailVerified),s.locked!==void 0&&(t.locked=s.locked),s.lastLogin!==void 0&&(t.lastLogin=s.lastLogin?new Date(s.lastLogin):null),s.failedLoginAttempts!==void 0&&(t.failedLoginAttempts=s.failedLoginAttempts);let i=await this.col("users").findOneAndUpdate({_id:e},{$set:t},{returnDocument:"after"});return i?this.docToAuthUser(i):null}async deleteUser(e){return (await this.col("users").deleteOne({_id:e})).deletedCount>0}async verifyPassword(e,s){let t=await this.findUserByEmail(e);if(!t)return null;let i=await this.col("users").findOne({email:e.toLowerCase()},{projection:{passwordHash:1}});return i?.passwordHash&&await c.default.compare(s,i.passwordHash)?t:null}async hashPassword(e){return c.default.hash(e,12)}async createSession(e,s){let t=randomUUID(),i=randomBytes(32).toString("base64url"),r=randomBytes(32).toString("base64url"),o=new Date,u=new Date(o.getTime()+this.sessionTTL*1e3),d={_id:t,userId:e,token:i,refreshToken:r,ipAddress:s?.ipAddress||null,userAgent:s?.userAgent||null,expiresAt:u,createdAt:o};return await this.col("sessions").insertOne(d),this.docToSession(d)}async findSessionByToken(e){let s=await this.col("sessions").findOne({token:e,expiresAt:{$gt:new Date}});return s?this.docToSession(s):null}async findSessionByRefreshToken(e){let s=await this.col("sessions").findOne({refreshToken:e,expiresAt:{$gt:new Date}});return s?this.docToSession(s):null}async deleteSession(e){return (await this.col("sessions").deleteOne({_id:e})).deletedCount>0}async deleteUserSessions(e){return (await this.col("sessions").deleteMany({userId:e})).deletedCount}async hasAnyUsers(){return await this.col("users").countDocuments()>0}async addPasswordToHistory(e,s){await this.col("password_history").insertOne({userId:e,passwordHash:s,createdAt:new Date});}async getPasswordHistory(e,s=5){return (await this.col("password_history").find({userId:e}).sort({createdAt:-1}).limit(s).toArray()).map(i=>i.passwordHash)}async isPasswordInHistory(e,s,t=5){let i=await this.getPasswordHistory(s,t);for(let r of i)if(await c.default.compare(e,r))return true;return false}async findAuditLogs(e){let{limit:s=50,offset:t=0,userId:i,action:r,resource:o,resourceId:u,success:d,startDate:f,endDate:h}=e,a={};i&&(a.userId=i),r&&(Array.isArray(r)?a.action={$in:r}:a.action=r),o&&(a.resource=o),u&&(a.resourceId=u),d!==void 0&&(a.success=d),(f||h)&&(a.timestamp={},f&&(a.timestamp.$gte=f),h&&(a.timestamp.$lte=h));let w=await this.col("audit_logs").countDocuments(a);return {logs:(await this.col("audit_logs").find(a).sort({timestamp:-1}).skip(t).limit(s).toArray()).map(n=>({id:n._id,timestamp:n.timestamp,action:n.action,userId:n.userId||void 0,userEmail:n.userEmail||void 0,role:n.role||void 0,resource:n.resource,resourceId:n.resourceId||void 0,changes:n.changes||void 0,ipAddress:n.ipAddress||void 0,userAgent:n.userAgent||void 0,success:n.success,error:n.error||void 0,metadata:n.metadata||void 0})),total:w}}async createAuditLog(e){let s=randomUUID(),t=new Date;return await this.col("audit_logs").insertOne({_id:s,action:e.action,userId:e.userId||null,userEmail:e.userEmail||null,role:e.role||null,resource:e.resource,resourceId:e.resourceId||null,changes:e.changes||null,ipAddress:e.ipAddress||null,userAgent:e.userAgent||null,success:e.success,error:e.error||null,metadata:e.metadata||null,timestamp:t}),{...e,id:s,timestamp:t}}docToAuthUser(e){return {id:e._id,name:e.name||void 0,email:e.email,passwordHash:e.passwordHash||void 0,role:e.role,tenantId:e.tenantId||void 0,avatar:e.avatar||void 0,emailVerified:e.emailVerified||false,locked:e.locked||false,lastLogin:e.lastLogin?.toISOString?.()||e.lastLogin||void 0,failedLoginAttempts:e.failedLoginAttempts||0,createdAt:e.createdAt?.toISOString?.()||e.createdAt,updatedAt:e.updatedAt?.toISOString?.()||e.updatedAt}}docToSession(e){return {id:e._id,userId:e.userId,token:e.token,refreshToken:e.refreshToken||void 0,expiresAt:e.expiresAt?.toISOString?.()||e.expiresAt,createdAt:e.createdAt?.toISOString?.()||e.createdAt,ipAddress:e.ipAddress||void 0,userAgent:e.userAgent||void 0}}async createEmailVerificationToken(e){let s=randomBytes(32).toString("hex"),t=new Date(Date.now()+1440*60*1e3),i=await import('./lib-XXYYUPMW.js'),r=i.ObjectId??i.default?.ObjectId;return await this.db.collection("email_verifications").insertOne({userId:new r(e),token:s,expiresAt:t,createdAt:new Date}),{token:s,expiresAt:t}}async verifyEmailToken(e){let s=await this.db.collection("email_verifications").findOne({token:e});return s?s.expiresAt<new Date?{success:false,error:"Verification token has expired"}:(await this.db.collection("users").updateOne({_id:s.userId},{$set:{emailVerified:true}}),await this.db.collection("email_verifications").deleteOne({_id:s._id}),{success:true,userId:s.userId.toString()}):{success:false,error:"Invalid verification token"}}async createPasswordResetToken(e){let s=await this.findUserByEmail(e);if(!s)return {token:"",expiresAt:new Date,error:"User not found"};let t=randomBytes(32).toString("hex"),i=new Date(Date.now()+3600*1e3),r=await import('./lib-XXYYUPMW.js'),o=r.ObjectId??r.default?.ObjectId;return await this.db.collection("password_resets").insertOne({userId:new o(s.id),token:t,expiresAt:i,createdAt:new Date}),{token:t,expiresAt:i}}async resetPasswordWithToken(e,s){let t=await this.db.collection("password_resets").findOne({token:e});if(!t)return {success:false,error:"Invalid reset token"};if(t.expiresAt<new Date)return {success:false,error:"Reset token has expired"};if(t.usedAt)return {success:false,error:"Reset token has already been used"};let i=await this.hashPassword(s);return await this.db.collection("users").updateOne({_id:t.userId},{$set:{passwordHash:i,updatedAt:new Date}}),await this.db.collection("password_resets").updateOne({_id:t._id},{$set:{usedAt:new Date}}),await this.db.collection("sessions").deleteMany({userId:t.userId}),{success:true}}};export{g as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {d,g as g$2,h,f}from'./chunk-JV4HJBXW.js';import {c,a as a$1,d as d$1,e}from'./chunk-N5POANYV.js';import {i,k,j as j$1,l as l$1,Z}from'./chunk-HRAY65XH.js';import {U as U$1,a,R,X,c as c$1,A as A$1,i as i$1,N,l,t,S,j,J as J$1,V as V$1,T as T$1,H as H$1,n}from'./chunk-3NSZZCOJ.js';import {g as g$1}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
g$1();g$1();g$1();function g(o){return c$1(o,d)?[`${o[t.Symbol.BaseName]}`]:c$1(o,i$1)?o._.usedTables??[]:c$1(o,A$1)?o.usedTables??[]:[]}var T=class extends i{constructor(e,t,i,s){super(),this.table=e,this.session=t,this.dialect=i,this.config={table:e,withList:s};}static[a]="SQLiteDelete";config;where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]=="function"){let t$1=e[0](new Proxy(this.config.table[t.Symbol.Columns],new a$1({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),i=Array.isArray(t$1)?t$1:[t$1];this.config.orderBy=i;}else {let t=e;this.config.orderBy=t;}return this}limit(e){return this.config.limit=e,this}returning(e=this.table[d.Symbol.Columns]){return this.config.returning=R(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=true){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",true,void 0,{type:"delete",tables:g(this.config.table)})}prepare(){return this._prepare(false)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(e){return this._prepare().execute(e)}$dynamic(){return this}};g$1();g$1();g$1();var y=class{static[a]="SQLiteSelectBuilder";fields;session;dialect;withList;distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,this.withList=e.withList,this.distinct=e.distinct;}from(e){let t=!!this.fields,i;return this.fields?i=this.fields:c$1(e,i$1)?i=Object.fromEntries(Object.keys(e._.selectedFields).map(s=>[s,e[s]])):c$1(e,f)?i=e[l].selectedFields:c$1(e,A$1)?i={}:i=V$1(e),new P({table:e,fields:i,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct})}},U=class extends c{static[a]="SQLiteSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:i,session:s,dialect:r,withList:n,distinct:f}){super(),this.config={withList:n,table:e,fields:{...t},distinct:f,setOperators:[]},this.isPartialSelect=i,this.session=s,this.dialect=r,this._={selectedFields:t,config:this.config},this.tableName=X(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:true}:{};for(let d of g(e))this.usedTables.add(d);}getUsedTables(){return [...this.usedTables]}createJoin(e){return (t$1,i)=>{let s=this.tableName,r=X(t$1);for(let n of g(t$1))this.usedTables.add(n);if(typeof r=="string"&&this.config.joins?.some(n=>n.alias===r))throw new Error(`Alias "${r}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof s=="string"&&(this.config.fields={[s]:this.config.fields}),typeof r=="string"&&!c$1(t$1,A$1))){let n=c$1(t$1,i$1)?t$1._.selectedFields:c$1(t$1,N)?t$1[l].selectedFields:t$1[t.Symbol.Columns];this.config.fields[r]=n;}if(typeof i=="function"&&(i=i(new Proxy(this.config.fields,new a$1({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:i,table:t$1,joinType:e,alias:r}),typeof r=="string")switch(e){case "left":{this.joinsNotNullableMap[r]=false;break}case "right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,false])),this.joinsNotNullableMap[r]=true;break}case "cross":case "inner":{this.joinsNotNullableMap[r]=true;break}case "full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,false])),this.joinsNotNullableMap[r]=false;break}}return this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");crossJoin=this.createJoin("cross");createSetOperator(e,t){return i=>{let s=typeof i=="function"?i(ce()):i;if(!S(this.getSelectedFields(),s.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return this.config.setOperators.push({type:e,isAll:t,rightSelect:s}),this}}union=this.createSetOperator("union",false);unionAll=this.createSetOperator("union",true);intersect=this.createSetOperator("intersect",false);except=this.createSetOperator("except",false);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new a$1({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new a$1({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]=="function"){let t=e[0](new Proxy(this.config.fields,new a$1({sqlAliasedBehavior:"alias",sqlBehavior:"sql"})));this.config.groupBy=Array.isArray(t)?t:[t];}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]=="function"){let t=e[0](new Proxy(this.config.fields,new a$1({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),i=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=i:this.config.orderBy=i;}else {let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t;}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...g(this.config.table)),this.config.joins)for(let i of this.config.joins)t.push(...g(i.table));return new Proxy(new i$1(this.getSQL(),this.config.fields,e,false,[...new Set(t)]),new a$1({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new a$1({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}},P=class extends U{static[a]="SQLiteSelect";_prepare(e=true){if(!this.session)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let t=R(this.config.fields),i=this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),t,"all",true,void 0,{type:"select",tables:[...this.usedTables]},this.cacheConfig);return i.joinsNotNullableMap=this.joinsNotNullableMap,i}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:true,autoInvalidate:true}:e===false?{enable:false}:{enable:true,autoInvalidate:true,...e},this}prepare(){return this._prepare(false)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(){return this.all()}};U$1(P,[i]);function F(o,e){return (t,i,...s)=>{let r=[i,...s].map(n=>({type:o,isAll:e,rightSelect:n}));for(let n of r)if(!S(t.getSelectedFields(),n.rightSelect.getSelectedFields()))throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order");return t.addSetOperators(r)}}var ce=()=>({union:ue,unionAll:fe,intersect:de,except:pe}),ue=F("union",false),fe=F("union",true),de=F("intersect",false),pe=F("except",false);var q=class{static[a]="SQLiteQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=c$1(e,g$2)?e:void 0,this.dialectConfig=c$1(e,g$2)?void 0:e;}$with=(e,t)=>{let i=this;return {as:r=>(typeof r=="function"&&(r=r(i)),new Proxy(new j(r.getSQL(),t??("getSelectedFields"in r?r.getSelectedFields()??{}:{}),e,true),new a$1({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};with(...e){let t=this;function i(r){return new y({fields:r??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function s(r){return new y({fields:r??void 0,session:void 0,dialect:t.getDialect(),withList:e,distinct:true})}return {select:i,selectDistinct:s}}select(e){return new y({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new y({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:true})}getDialect(){return this.dialect||(this.dialect=new h(this.dialectConfig)),this.dialect}};var A=class{constructor(e,t,i,s){this.table=e,this.session=t,this.dialect=i,this.withList=s;}static[a]="SQLiteInsertBuilder";values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw new Error("values() must be called with at least one value");let t$1=e.map(i=>{let s={},r=this.table[t.Symbol.Columns];for(let n of Object.keys(i)){let f=i[n];s[n]=c$1(f,A$1)?f:new H$1(f,r[n]);}return s});return new E(this.table,t$1,this.session,this.dialect,this.withList)}select(e){let t=typeof e=="function"?e(new q):e;if(!c$1(t,A$1)&&!S(this.table[n],t._.selectedFields))throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition");return new E(this.table,t,this.session,this.dialect,this.withList,true)}},E=class extends i{constructor(e,t,i,s,r,n){super(),this.session=i,this.dialect=s,this.config={table:e,values:t,withList:r,select:n};}static[a]="SQLiteInsert";config;returning(e=this.config.table[d.Symbol.Columns]){return this.config.returning=R(e),this}onConflictDoNothing(e={}){if(this.config.onConflict||(this.config.onConflict=[]),e.target===void 0)this.config.onConflict.push(J$1` on conflict do nothing`);else {let t=Array.isArray(e.target)?J$1`${e.target}`:J$1`${[e.target]}`,i=e.where?J$1` where ${e.where}`:J$1``;this.config.onConflict.push(J$1` on conflict ${t} do nothing${i}`);}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.');this.config.onConflict||(this.config.onConflict=[]);let t=e.where?J$1` where ${e.where}`:void 0,i=e.targetWhere?J$1` where ${e.targetWhere}`:void 0,s=e.setWhere?J$1` where ${e.setWhere}`:void 0,r=Array.isArray(e.target)?J$1`${e.target}`:J$1`${[e.target]}`,n=this.dialect.buildUpdateSet(this.config.table,T$1(this.config.table,e.set));return this.config.onConflict.push(J$1` on conflict ${r}${i} do update set ${n}${t}${s}`),this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=true){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",true,void 0,{type:"insert",tables:g(this.config.table)})}prepare(){return this._prepare(false)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}};g$1();var M=class{constructor(e,t,i,s){this.table=e,this.session=t,this.dialect=i,this.withList=s;}static[a]="SQLiteUpdateBuilder";set(e){return new I(this.table,T$1(this.table,e),this.session,this.dialect,this.withList)}},I=class extends i{constructor(e,t,i,s,r){super(),this.session=i,this.dialect=s,this.config={set:t,table:e,withList:r,joins:[]};}static[a]="SQLiteUpdate";config;from(e){return this.config.from=e,this}createJoin(e){return (t$1,i)=>{let s=X(t$1);if(typeof s=="string"&&this.config.joins.some(r=>r.alias===s))throw new Error(`Alias "${s}" is already used in this query`);if(typeof i=="function"){let r=this.config.from?c$1(t$1,d)?t$1[t.Symbol.Columns]:c$1(t$1,i$1)?t$1._.selectedFields:c$1(t$1,f)?t$1[l].selectedFields:void 0:void 0;i=i(new Proxy(this.config.table[t.Symbol.Columns],new a$1({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),r&&new Proxy(r,new a$1({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));}return this.config.joins.push({on:i,table:t$1,joinType:e,alias:s}),this}}leftJoin=this.createJoin("left");rightJoin=this.createJoin("right");innerJoin=this.createJoin("inner");fullJoin=this.createJoin("full");where(e){return this.config.where=e,this}orderBy(...e){if(typeof e[0]=="function"){let t$1=e[0](new Proxy(this.config.table[t.Symbol.Columns],new a$1({sqlAliasedBehavior:"alias",sqlBehavior:"sql"}))),i=Array.isArray(t$1)?t$1:[t$1];this.config.orderBy=i;}else {let t=e;this.config.orderBy=t;}return this}limit(e){return this.config.limit=e,this}returning(e=this.config.table[d.Symbol.Columns]){return this.config.returning=R(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e=true){return this.session[e?"prepareOneTimeQuery":"prepareQuery"](this.dialect.sqlToQuery(this.getSQL()),this.config.returning,this.config.returning?"all":"run",true,void 0,{type:"insert",tables:g(this.config.table)})}prepare(){return this._prepare(false)}run=e=>this._prepare().run(e);all=e=>this._prepare().all(e);get=e=>this._prepare().get(e);values=e=>this._prepare().values(e);async execute(){return this.config.returning?this.all():this.run()}$dynamic(){return this}};g$1();var K=class o extends A$1{constructor(e){super(o.buildEmbeddedCount(e.source,e.filters).queryChunks),this.params=e,this.session=e.session,this.sql=o.buildCount(e.source,e.filters);}sql;static[a]="SQLiteCountBuilderAsync";[Symbol.toStringTag]="SQLiteCountBuilderAsync";session;static buildEmbeddedCount(e,t){return J$1`(select count(*) from ${e}${J$1.raw(" where ").if(t)}${t})`}static buildCount(e,t){return J$1`select count(*) from ${e}${J$1.raw(" where ").if(t)}${t}`}then(e,t){return Promise.resolve(this.session.count(this.sql)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}};g$1();var D=class{constructor(e,t,i,s,r,n,f,d){this.mode=e,this.fullSchema=t,this.schema=i,this.tableNamesMap=s,this.table=r,this.tableConfig=n,this.dialect=f,this.session=d;}static[a]="SQLiteAsyncRelationalQueryBuilder";findMany(e){return this.mode==="sync"?new J(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many"):new O(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many")}findFirst(e){return this.mode==="sync"?new J(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first"):new O(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}},O=class extends i{constructor(e,t,i,s,r,n,f,d,he){super(),this.fullSchema=e,this.schema=t,this.tableNamesMap=i,this.table=s,this.tableConfig=r,this.dialect=n,this.session=f,this.config=d,this.mode=he;}static[a]="SQLiteAsyncRelationalQuery";mode;getSQL(){return this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}).sql}_prepare(e=false){let{query:t,builtQuery:i}=this._toSQL();return this.session[e?"prepareOneTimeQuery":"prepareQuery"](i,void 0,this.mode==="first"?"get":"all",true,(s,r)=>{let n=s.map(f=>Z(this.schema,this.tableConfig,f,t.selection,r));return this.mode==="first"?n[0]:n})}prepare(){return this._prepare(false)}_toSQL(){let e=this.dialect.buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName}),t=this.dialect.sqlToQuery(e.sql);return {query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}executeRaw(){return this.mode==="first"?this._prepare(false).get():this._prepare(false).all()}async execute(){return this.executeRaw()}},J=class extends O{static[a]="SQLiteSyncRelationalQuery";sync(){return this.executeRaw()}};g$1();var C=class extends i{constructor(e,t,i,s,r){super(),this.execute=e,this.getSQL=t,this.dialect=s,this.mapBatchResult=r,this.config={action:i};}static[a]="SQLiteRaw";config;getQuery(){return {...this.dialect.sqlToQuery(this.getSQL()),method:this.config.action}}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return false}};var V=class{constructor(e,t,i,s){this.resultKind=e,this.dialect=t,this.session=i,this._=s?{schema:s.schema,fullSchema:s.fullSchema,tableNamesMap:s.tableNamesMap}:{schema:void 0,fullSchema:{},tableNamesMap:{}},this.query={};let r=this.query;if(this._.schema)for(let[n,f]of Object.entries(this._.schema))r[n]=new D(e,s.fullSchema,this._.schema,this._.tableNamesMap,s.fullSchema[n],f,t,i);this.$cache={invalidate:async n=>{}};}static[a]="BaseSQLiteDatabase";query;$with=(e,t)=>{let i=this;return {as:r=>(typeof r=="function"&&(r=r(new q(i.dialect))),new Proxy(new j(r.getSQL(),t??("getSelectedFields"in r?r.getSelectedFields()??{}:{}),e,true),new a$1({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};$count(e,t){return new K({source:e,filters:t,session:this.session})}with(...e){let t=this;function i(d){return new y({fields:d??void 0,session:t.session,dialect:t.dialect,withList:e})}function s(d){return new y({fields:d??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:true})}function r(d){return new M(d,t.session,t.dialect,e)}function n(d){return new A(d,t.session,t.dialect,e)}function f(d){return new T(d,t.session,t.dialect,e)}return {select:i,selectDistinct:s,update:r,insert:n,delete:f}}select(e){return new y({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new y({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:true})}update(e){return new M(e,this.session,this.dialect)}$cache;insert(e){return new A(e,this.session,this.dialect)}delete(e){return new T(e,this.session,this.dialect)}run(e){let t=typeof e=="string"?J$1.raw(e):e.getSQL();return this.resultKind==="async"?new C(async()=>this.session.run(t),()=>t,"run",this.dialect,this.session.extractRawRunValueFromBatchResult.bind(this.session)):this.session.run(t)}all(e){let t=typeof e=="string"?J$1.raw(e):e.getSQL();return this.resultKind==="async"?new C(async()=>this.session.all(t),()=>t,"all",this.dialect,this.session.extractRawAllValueFromBatchResult.bind(this.session)):this.session.all(t)}get(e){let t=typeof e=="string"?J$1.raw(e):e.getSQL();return this.resultKind==="async"?new C(async()=>this.session.get(t),()=>t,"get",this.dialect,this.session.extractRawGetValueFromBatchResult.bind(this.session)):this.session.get(t)}values(e){let t=typeof e=="string"?J$1.raw(e):e.getSQL();return this.resultKind==="async"?new C(async()=>this.session.values(t),()=>t,"values",this.dialect,this.session.extractRawValuesValueFromBatchResult.bind(this.session)):this.session.values(t)}transaction(e,t){return this.session.transaction(e,t)}};g$1();var H=class extends i{constructor(e){super(),this.resultCb=e;}static[a]="ExecuteResultSync";async execute(){return this.resultCb()}sync(){return this.resultCb()}},oe=class{constructor(e,t,i,s,r,n){this.mode=e,this.executeMethod=t,this.query=i,this.cache=s,this.queryMetadata=r,this.cacheConfig=n,s&&s.strategy()==="all"&&n===void 0&&(this.cacheConfig={enable:true,autoInvalidate:true}),this.cacheConfig?.enable||(this.cacheConfig=void 0);}static[a]="PreparedQuery";joinsNotNullableMap;async queryWithCache(e$1,t,i){if(this.cache===void 0||c$1(this.cache,d$1)||this.queryMetadata===void 0)try{return await i()}catch(s){throw new k(e$1,t,s)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await i()}catch(s){throw new k(e$1,t,s)}if((this.queryMetadata.type==="insert"||this.queryMetadata.type==="update"||this.queryMetadata.type==="delete")&&this.queryMetadata.tables.length>0)try{let[s]=await Promise.all([i(),this.cache.onMutate({tables:this.queryMetadata.tables})]);return s}catch(s){throw new k(e$1,t,s)}if(!this.cacheConfig)try{return await i()}catch(s){throw new k(e$1,t,s)}if(this.queryMetadata.type==="select"){let s=await this.cache.get(this.cacheConfig.tag??await e(e$1,t),this.queryMetadata.tables,this.cacheConfig.tag!==void 0,this.cacheConfig.autoInvalidate);if(s===void 0){let r;try{r=await i();}catch(n){throw new k(e$1,t,n)}return await this.cache.put(this.cacheConfig.tag??await e(e$1,t),r,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),r}return s}try{return await i()}catch(s){throw new k(e$1,t,s)}}getQuery(){return this.query}mapRunResult(e,t){return e}mapAllResult(e,t){throw new Error("Not implemented")}mapGetResult(e,t){throw new Error("Not implemented")}execute(e){return this.mode==="async"?this[this.executeMethod](e):new H(()=>this[this.executeMethod](e))}mapResult(e,t){switch(this.executeMethod){case "run":return this.mapRunResult(e,t);case "all":return this.mapAllResult(e,t);case "get":return this.mapGetResult(e,t)}}},ae=class{constructor(e){this.dialect=e;}static[a]="SQLiteSession";prepareOneTimeQuery(e,t,i,s,r,n,f){return this.prepareQuery(e,t,i,s,r,n,f)}run(e){let t=this.dialect.sqlToQuery(e);try{return this.prepareOneTimeQuery(t,void 0,"run",!1).run()}catch(i){throw new j$1({cause:i,message:`Failed to run the query '${t.sql}'`})}}extractRawRunValueFromBatchResult(e){return e}all(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",false).all()}extractRawAllValueFromBatchResult(e){throw new Error("Not implemented")}get(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",false).get()}extractRawGetValueFromBatchResult(e){throw new Error("Not implemented")}values(e){return this.prepareOneTimeQuery(this.dialect.sqlToQuery(e),void 0,"run",false).values()}async count(e){return (await this.values(e))[0][0]}extractRawValuesValueFromBatchResult(e){throw new Error("Not implemented")}},le=class extends V{constructor(e,t,i,s,r=0){super(e,t,i,s),this.schema=s,this.nestedIndex=r;}static[a]="SQLiteTransaction";rollback(){throw new l$1}};export{V as a,oe as b,ae as c,le as d};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {g}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
g();function o(e){if(e==null)return e;if(Array.isArray(e))return e.map(n=>o(n));if(typeof e=="object"&&!(e instanceof Date)&&!(e instanceof RegExp)){let n={};for(let r of Object.keys(e))/^\d+$/.test(r)||(n[r]=o(e[r]));return n}return e}export{o as a};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {b}from'./chunk-OBYAIJVU.js';import {p as p$1}from'./chunk-JRUQ5ABB.js';import {g}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
g();g();var C="AWS_ACCESS_KEY_ID",A="AWS_SECRET_ACCESS_KEY",p="AWS_SESSION_TOKEN",I="AWS_CREDENTIAL_EXPIRATION",a="AWS_CREDENTIAL_SCOPE",i="AWS_ACCOUNT_ID",V=o=>async()=>{o?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv");let E=process.env[C],r=process.env[A],n=process.env[p],s=process.env[I],t=process.env[a],c=process.env[i];if(E&&r){let _={accessKeyId:E,secretAccessKey:r,...n&&{sessionToken:n},...s&&{expiration:new Date(s)},...t&&{credentialScope:t},...c&&{accountId:c}};return b(_,"CREDENTIALS_ENV_VARS","g"),_}throw new p$1("Unable to find environment variable credentials.",{logger:o?.logger})};export{C as a,A as b,p as c,I as d,a as e,i as f,V as g};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkHTYVI2HK_cjs=require('./chunk-HTYVI2HK.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto=require('crypto');chunkBUNLC3II_cjs.h();var c=chunkBUNLC3II_cjs.e(chunkHTYVI2HK_cjs.a(),1);var g=class{db;adapter;prefix;sessionTTL;refreshTokenTTL;indexesEnsured=false;constructor(e){this.db=e.db,this.adapter=e.adapter,this.prefix=e.collectionPrefix||"",this.sessionTTL=e.sessionTTL||86400,this.refreshTokenTTL=e.refreshTokenTTL||604800;}getDatabase(){let e=typeof this.db=="function"?this.db():this.db;if(!e&&this.adapter&&(this.adapter.db?e=this.adapter.db:this.adapter.client&&(this.adapter.db=this.adapter.client.db(this.adapter.database||"kyro_cms"),e=this.adapter.db)),!e)throw new Error("MongoDB database not initialized");return e}col(e){return this.getDatabase().collection(`${this.prefix}${e}`)}async connect(){this.adapter&&!this.adapter.connected&&await this.adapter.connect(),this.indexesEnsured||await this.ensureIndexes();}async disconnect(){}async ensureIndexes(){await this.col("users").createIndex({email:1},{unique:true}),await this.col("users").createIndex({tenantId:1}),await this.col("users").createIndex({role:1}),await this.col("sessions").createIndex({token:1},{unique:true}),await this.col("sessions").createIndex({refreshToken:1}),await this.col("sessions").createIndex({userId:1}),await this.col("sessions").createIndex({expiresAt:1},{expireAfterSeconds:0}),await this.col("audit_logs").createIndex({timestamp:-1}),await this.col("audit_logs").createIndex({userId:1}),await this.col("audit_logs").createIndex({action:1}),await this.col("audit_logs").createIndex({resource:1}),await this.col("password_history").createIndex({userId:1,createdAt:-1}),await this.col("lockouts").createIndex({userId:1},{unique:true}),await this.col("lockouts").createIndex({lockedUntil:1}),this.indexesEnsured=true;}async createUser(e){let s=crypto.randomUUID(),t=new Date,i=await this.hashPassword(e.password),r={_id:s,name:e.name||null,email:e.email.toLowerCase(),passwordHash:i,role:e.role||"customer",avatar:e.avatar||null,tenantId:e.tenantId||null,emailVerified:false,locked:false,lastLogin:null,failedLoginAttempts:0,createdAt:t,updatedAt:t};return await this.col("users").insertOne(r),this.docToAuthUser(r)}async findUserByEmail(e){let s=await this.col("users").findOne({email:e.toLowerCase()});return s?this.docToAuthUser(s):null}async findUserById(e){let s=await this.col("users").findOne({_id:e});return s?this.docToAuthUser(s):null}async updateUser(e,s){let t={updatedAt:new Date};s.name!==void 0&&(t.name=s.name),s.email!==void 0&&(t.email=s.email),s.passwordHash!==void 0&&(t.passwordHash=s.passwordHash),s.role!==void 0&&(t.role=s.role),s.avatar!==void 0&&(t.avatar=s.avatar),s.tenantId!==void 0&&(t.tenantId=s.tenantId),s.emailVerified!==void 0&&(t.emailVerified=s.emailVerified),s.locked!==void 0&&(t.locked=s.locked),s.lastLogin!==void 0&&(t.lastLogin=s.lastLogin?new Date(s.lastLogin):null),s.failedLoginAttempts!==void 0&&(t.failedLoginAttempts=s.failedLoginAttempts);let i=await this.col("users").findOneAndUpdate({_id:e},{$set:t},{returnDocument:"after"});return i?this.docToAuthUser(i):null}async deleteUser(e){return (await this.col("users").deleteOne({_id:e})).deletedCount>0}async verifyPassword(e,s){let t=await this.findUserByEmail(e);if(!t)return null;let i=await this.col("users").findOne({email:e.toLowerCase()},{projection:{passwordHash:1}});return i?.passwordHash&&await c.default.compare(s,i.passwordHash)?t:null}async hashPassword(e){return c.default.hash(e,12)}async createSession(e,s){let t=crypto.randomUUID(),i=crypto.randomBytes(32).toString("base64url"),r=crypto.randomBytes(32).toString("base64url"),o=new Date,u=new Date(o.getTime()+this.sessionTTL*1e3),d={_id:t,userId:e,token:i,refreshToken:r,ipAddress:s?.ipAddress||null,userAgent:s?.userAgent||null,expiresAt:u,createdAt:o};return await this.col("sessions").insertOne(d),this.docToSession(d)}async findSessionByToken(e){let s=await this.col("sessions").findOne({token:e,expiresAt:{$gt:new Date}});return s?this.docToSession(s):null}async findSessionByRefreshToken(e){let s=await this.col("sessions").findOne({refreshToken:e,expiresAt:{$gt:new Date}});return s?this.docToSession(s):null}async deleteSession(e){return (await this.col("sessions").deleteOne({_id:e})).deletedCount>0}async deleteUserSessions(e){return (await this.col("sessions").deleteMany({userId:e})).deletedCount}async hasAnyUsers(){return await this.col("users").countDocuments()>0}async addPasswordToHistory(e,s){await this.col("password_history").insertOne({userId:e,passwordHash:s,createdAt:new Date});}async getPasswordHistory(e,s=5){return (await this.col("password_history").find({userId:e}).sort({createdAt:-1}).limit(s).toArray()).map(i=>i.passwordHash)}async isPasswordInHistory(e,s,t=5){let i=await this.getPasswordHistory(s,t);for(let r of i)if(await c.default.compare(e,r))return true;return false}async findAuditLogs(e){let{limit:s=50,offset:t=0,userId:i,action:r,resource:o,resourceId:u,success:d,startDate:f,endDate:h}=e,a={};i&&(a.userId=i),r&&(Array.isArray(r)?a.action={$in:r}:a.action=r),o&&(a.resource=o),u&&(a.resourceId=u),d!==void 0&&(a.success=d),(f||h)&&(a.timestamp={},f&&(a.timestamp.$gte=f),h&&(a.timestamp.$lte=h));let w=await this.col("audit_logs").countDocuments(a);return {logs:(await this.col("audit_logs").find(a).sort({timestamp:-1}).skip(t).limit(s).toArray()).map(n=>({id:n._id,timestamp:n.timestamp,action:n.action,userId:n.userId||void 0,userEmail:n.userEmail||void 0,role:n.role||void 0,resource:n.resource,resourceId:n.resourceId||void 0,changes:n.changes||void 0,ipAddress:n.ipAddress||void 0,userAgent:n.userAgent||void 0,success:n.success,error:n.error||void 0,metadata:n.metadata||void 0})),total:w}}async createAuditLog(e){let s=crypto.randomUUID(),t=new Date;return await this.col("audit_logs").insertOne({_id:s,action:e.action,userId:e.userId||null,userEmail:e.userEmail||null,role:e.role||null,resource:e.resource,resourceId:e.resourceId||null,changes:e.changes||null,ipAddress:e.ipAddress||null,userAgent:e.userAgent||null,success:e.success,error:e.error||null,metadata:e.metadata||null,timestamp:t}),{...e,id:s,timestamp:t}}docToAuthUser(e){return {id:e._id,name:e.name||void 0,email:e.email,passwordHash:e.passwordHash||void 0,role:e.role,tenantId:e.tenantId||void 0,avatar:e.avatar||void 0,emailVerified:e.emailVerified||false,locked:e.locked||false,lastLogin:e.lastLogin?.toISOString?.()||e.lastLogin||void 0,failedLoginAttempts:e.failedLoginAttempts||0,createdAt:e.createdAt?.toISOString?.()||e.createdAt,updatedAt:e.updatedAt?.toISOString?.()||e.updatedAt}}docToSession(e){return {id:e._id,userId:e.userId,token:e.token,refreshToken:e.refreshToken||void 0,expiresAt:e.expiresAt?.toISOString?.()||e.expiresAt,createdAt:e.createdAt?.toISOString?.()||e.createdAt,ipAddress:e.ipAddress||void 0,userAgent:e.userAgent||void 0}}async createEmailVerificationToken(e){let s=crypto.randomBytes(32).toString("hex"),t=new Date(Date.now()+1440*60*1e3),i=await import('./lib-5QYYN6ML.cjs'),r=i.ObjectId??i.default?.ObjectId;return await this.db.collection("email_verifications").insertOne({userId:new r(e),token:s,expiresAt:t,createdAt:new Date}),{token:s,expiresAt:t}}async verifyEmailToken(e){let s=await this.db.collection("email_verifications").findOne({token:e});return s?s.expiresAt<new Date?{success:false,error:"Verification token has expired"}:(await this.db.collection("users").updateOne({_id:s.userId},{$set:{emailVerified:true}}),await this.db.collection("email_verifications").deleteOne({_id:s._id}),{success:true,userId:s.userId.toString()}):{success:false,error:"Invalid verification token"}}async createPasswordResetToken(e){let s=await this.findUserByEmail(e);if(!s)return {token:"",expiresAt:new Date,error:"User not found"};let t=crypto.randomBytes(32).toString("hex"),i=new Date(Date.now()+3600*1e3),r=await import('./lib-5QYYN6ML.cjs'),o=r.ObjectId??r.default?.ObjectId;return await this.db.collection("password_resets").insertOne({userId:new o(s.id),token:t,expiresAt:i,createdAt:new Date}),{token:t,expiresAt:i}}async resetPasswordWithToken(e,s){let t=await this.db.collection("password_resets").findOne({token:e});if(!t)return {success:false,error:"Invalid reset token"};if(t.expiresAt<new Date)return {success:false,error:"Reset token has expired"};if(t.usedAt)return {success:false,error:"Reset token has already been used"};let i=await this.hashPassword(s);return await this.db.collection("users").updateOne({_id:t.userId},{$set:{passwordHash:i,updatedAt:new Date}}),await this.db.collection("password_resets").updateOne({_id:t._id},{$set:{usedAt:new Date}}),await this.db.collection("sessions").deleteMany({userId:t.userId}),{success:true}}};exports.a=g;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {c}from'./chunk-U6KFONKM.js';import {t,s,e,c as c$1}from'./chunk-TYQYKKWJ.js';import {g}from'./chunk-Y2YAKDEQ.js';import {Readable}from'stream';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
g();g();g();g();var k=class n{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776e3||e<-9223372036854776e3)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);let t=new Uint8Array(8);for(let r=7,s=Math.abs(Math.round(e));r>-1&&s>0;r--,s/=256)t[r]=s;return e<0&&R(t),new n(t)}valueOf(){let e=this.bytes.slice(0),t$1=e[0]&128;return t$1&&R(e),parseInt(t(e),16)*(t$1?-1:1)}toString(){return String(this.valueOf())}};function R(n){for(let e=0;e<8;e++)n[e]^=255;for(let e=7;e>-1&&(n[e]++,n[e]===0);e--);}var z=class{toUtf8;fromUtf8;constructor(e,t){this.toUtf8=e,this.fromUtf8=t;}format(e){let t=[];for(let a of Object.keys(e)){let c=this.fromUtf8(a);t.push(Uint8Array.from([c.byteLength]),c,this.formatHeaderValue(e[a]));}let r=new Uint8Array(t.reduce((a,c)=>a+c.byteLength,0)),s=0;for(let a of t)r.set(a,s),s+=a.byteLength;return r}formatHeaderValue(e){switch(e.type){case "boolean":return Uint8Array.from([e.value?y.boolTrue:y.boolFalse]);case "byte":return Uint8Array.from([y.byte,e.value]);case "short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,y.short),t.setInt16(1,e.value,false),new Uint8Array(t.buffer);case "integer":let r=new DataView(new ArrayBuffer(5));return r.setUint8(0,y.integer),r.setInt32(1,e.value,false),new Uint8Array(r.buffer);case "long":let s$1=new Uint8Array(9);return s$1[0]=y.long,s$1.set(e.value.bytes,1),s$1;case "binary":let a=new DataView(new ArrayBuffer(3+e.value.byteLength));a.setUint8(0,y.byteArray),a.setUint16(1,e.value.byteLength,false);let c=new Uint8Array(a.buffer);return c.set(e.value,3),c;case "string":let o=this.fromUtf8(e.value),f=new DataView(new ArrayBuffer(3+o.byteLength));f.setUint8(0,y.string),f.setUint16(1,o.byteLength,false);let w=new Uint8Array(f.buffer);return w.set(o,3),w;case "timestamp":let g=new Uint8Array(9);return g[0]=y.timestamp,g.set(k.fromNumber(e.value.valueOf()).bytes,1),g;case "uuid":if(!se.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);let l=new Uint8Array(17);return l[0]=y.uuid,l.set(s(e.value.replace(/-/g,"")),1),l}}parse(e){let t$1={},r=0;for(;r<e.byteLength;){let s=e.getUint8(r++),a=this.toUtf8(new Uint8Array(e.buffer,e.byteOffset+r,s));switch(r+=s,e.getUint8(r++)){case y.boolTrue:t$1[a]={type:X,value:true};break;case y.boolFalse:t$1[a]={type:X,value:false};break;case y.byte:t$1[a]={type:V,value:e.getInt8(r++)};break;case y.short:t$1[a]={type:E,value:e.getInt16(r,false)},r+=2;break;case y.integer:t$1[a]={type:_,value:e.getInt32(r,false)},r+=4;break;case y.long:t$1[a]={type:Y,value:new k(new Uint8Array(e.buffer,e.byteOffset+r,8))},r+=8;break;case y.byteArray:let c=e.getUint16(r,false);r+=2,t$1[a]={type:ee,value:new Uint8Array(e.buffer,e.byteOffset+r,c)},r+=c;break;case y.string:let o=e.getUint16(r,false);r+=2,t$1[a]={type:te,value:this.toUtf8(new Uint8Array(e.buffer,e.byteOffset+r,o))},r+=o;break;case y.timestamp:t$1[a]={type:re,value:new Date(new k(new Uint8Array(e.buffer,e.byteOffset+r,8)).valueOf())},r+=8;break;case y.uuid:let f=new Uint8Array(e.buffer,e.byteOffset+r,16);r+=16,t$1[a]={type:ne,value:`${t(f.subarray(0,4))}-${t(f.subarray(4,6))}-${t(f.subarray(6,8))}-${t(f.subarray(8,10))}-${t(f.subarray(10))}`};break;default:throw new Error("Unrecognized header type tag")}}return t$1}},y;(function(n){n[n.boolTrue=0]="boolTrue",n[n.boolFalse=1]="boolFalse",n[n.byte=2]="byte",n[n.short=3]="short",n[n.integer=4]="integer",n[n.long=5]="long",n[n.byteArray=6]="byteArray",n[n.string=7]="string",n[n.timestamp=8]="timestamp",n[n.uuid=9]="uuid";})(y||(y={}));var X="boolean",V="byte",E="short",_="integer",Y="long",ee="binary",te="string",re="timestamp",ne="uuid",se=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;g();var Z=4,M=Z*2,B=4,ae=M+B*2;function H({byteLength:n,byteOffset:e,buffer:t}){if(n<ae)throw new Error("Provided message too short to accommodate event stream message overhead");let r=new DataView(t,e,n),s=r.getUint32(0,false);if(n!==s)throw new Error("Reported message length does not match received message length");let a=r.getUint32(Z,false),c$1=r.getUint32(M,false),o=r.getUint32(n-B,false),f=new c;if(f.update(new Uint8Array(t,e,M)),c$1!==f.digestSync())throw new Error(`The prelude checksum specified in the message (${c$1}) does not match the calculated CRC32 checksum (${f.digestSync()})`);if(f.update(new Uint8Array(t,e+M,n-(M+B))),o!==f.digestSync())throw new Error(`The message checksum (${f.digestSync()}) did not match the expected value of ${o}`);return {headers:new DataView(t,e+M+B,a),body:new Uint8Array(t,e+M+B+a,s-a-(M+B+B))}}var O=class{headerMarshaller;messageBuffer;isEndOfStream;constructor(e,t){this.headerMarshaller=new z(e,t),this.messageBuffer=[],this.isEndOfStream=false;}feed(e){this.messageBuffer.push(this.decode(e));}endOfStream(){this.isEndOfStream=true;}getMessage(){let e=this.messageBuffer.pop(),t=this.isEndOfStream;return {getMessage(){return e},isEndOfStream(){return t}}}getAvailableMessages(){let e=this.messageBuffer;this.messageBuffer=[];let t=this.isEndOfStream;return {getMessages(){return e},isEndOfStream(){return t}}}encode({headers:e,body:t}){let r=this.headerMarshaller.format(e),s=r.byteLength+t.byteLength+16,a=new Uint8Array(s),c$1=new DataView(a.buffer,a.byteOffset,a.byteLength),o=new c;return c$1.setUint32(0,s,false),c$1.setUint32(4,r.byteLength,false),o.update(a.subarray(0,8)),c$1.setUint32(8,o.digestSync(),false),a.set(r,12),a.set(t,r.byteLength+12),o.update(a.subarray(8,s-4)),c$1.setUint32(s-4,o.digestSync(),false),a}decode(e){let{headers:t,body:r}=H(e);return {headers:this.headerMarshaller.parse(t),body:r}}formatHeaders(e){return this.headerMarshaller.format(e)}};g();var N=class{options;constructor(e){this.options=e;}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.inputStream)yield this.options.decoder.decode(e);}};g();var G=class{options;constructor(e){this.options=e;}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.messageStream)yield this.options.encoder.encode(e);this.options.includeEndFrame&&(yield new Uint8Array(0));}};g();var $=class{options;constructor(e){this.options=e;}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.messageStream){let t=await this.options.deserializer(e);t!==void 0&&(yield t);}}};g();var A=class{options;constructor(e){this.options=e;}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(let e of this.options.inputStream)yield this.options.serializer(e);}};g();g();g();function K(n){let e=0,t=0,r=null,s=null,a=o=>{if(typeof o!="number")throw new Error("Attempted to allocate an event message where size was not a number: "+o);e=o,t=4,r=new Uint8Array(o),new DataView(r.buffer).setUint32(0,o,false);},c=async function*(){let o=n[Symbol.asyncIterator]();for(;;){let{value:f,done:w}=await o.next();if(w){if(e)if(e===t)yield r;else throw new Error("Truncated event message received.");else return;return}let g=f.length,l=0;for(;l<g;){if(!r){let m=g-l;s||(s=new Uint8Array(4));let d=Math.min(4-t,m);if(s.set(f.slice(l,l+d),t),t+=d,l+=d,t<4)break;a(new DataView(s.buffer).getUint32(0,false)),s=null;}let u=Math.min(e-t,g-l);r.set(f.slice(l,l+u),t),t+=u,l+=u,e&&e===t&&(yield r,r=null,e=0,t=0);}}};return {[Symbol.asyncIterator]:c}}g();function oe(n,e){let t=F(e.deserializer,e.toUtf8);return {[Symbol.asyncIterator]:async function*(){for await(let r of n){let s=e.eventStreamCodec.decode(r),a=await t(s);a!==void 0&&(yield a);}}}}function F(n,e){return async function(t){let{value:r}=t.headers[":message-type"];if(r==="error"){let s=new Error(t.headers[":error-message"].value||"UnknownError");throw s.name=t.headers[":error-code"].value,s}else if(r==="exception"){let s=t.headers[":exception-type"].value,a={[s]:t},c=await n(a);if(c.$unknown){let o=new Error(e(t.body));throw o.name=s,o}throw c[s]}else if(r==="event"){let s={[t.headers[":event-type"].value]:t},a=await n(s);return a.$unknown?void 0:a}else throw Error(`Unrecognizable event type: ${t.headers[":event-type"].value}`)}}var C=class{eventStreamCodec;utfEncoder;constructor({utf8Encoder:e,utf8Decoder:t}){this.eventStreamCodec=new O(e,t),this.utfEncoder=e;}deserialize(e,t){let r=K(e);return new $({messageStream:new N({inputStream:r,decoder:this.eventStreamCodec}),deserializer:F(t,this.utfEncoder)})}serialize(e,t){return new G({messageStream:new A({inputStream:e,serializer:t}),encoder:this.eventStreamCodec,includeEndFrame:true})}},ie=n=>new C(n);var j=class{universalMarshaller;constructor({utf8Encoder:e,utf8Decoder:t}){this.universalMarshaller=new C({utf8Decoder:t,utf8Encoder:e});}deserialize(e,t){let r=typeof e[Symbol.asyncIterator]=="function"?e:fe(e);return this.universalMarshaller.deserialize(r,t)}serialize(e,t){return Readable.from(this.universalMarshaller.serialize(e,t))}},le=n=>new j(n);async function*fe(n){let e=false,t=false,r=new Array;for(n.on("error",s=>{if(e||(e=true),s)throw s}),n.on("data",s=>{r.push(s);}),n.on("end",()=>{e=true;});!t;){let s=await new Promise(a=>setTimeout(()=>a(r.shift()),0));s&&(yield s),t=e&&r.length===0;}}g();var ue=n=>({[Symbol.asyncIterator]:async function*(){let e=n.getReader();try{for(;;){let{done:t,value:r}=await e.read();if(t)return;yield r;}}finally{e.releaseLock();}}}),me=n=>{let e=n[Symbol.asyncIterator]();return new ReadableStream({async pull(t){let{done:r,value:s}=await e.next();if(r)return t.close();t.enqueue(s);}})};g();var ye=n=>Object.assign(n,{eventStreamMarshaller:n.eventStreamSerdeProvider(n)});g();var q=class{marshaller;serializer;deserializer;serdeContext;defaultContentType;constructor({marshaller:e,serializer:t,deserializer:r,serdeContext:s,defaultContentType:a}){this.marshaller=e,this.serializer=t,this.deserializer=r,this.serdeContext=s,this.defaultContentType=a;}async serializeEventStream({eventStream:e,requestSchema:t,initialRequest:r}){let s=this.marshaller,a=t.getEventStreamMember(),c=t.getMemberSchema(a),o=this.serializer,f=this.defaultContentType,w=Symbol("initialRequestMarker"),g={async*[Symbol.asyncIterator](){if(r){let l={":event-type":{type:"string",value:"initial-request"},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:f}};o.write(t,r);let u=o.flush();yield {[w]:true,headers:l,body:u};}for await(let l of e)yield l;}};return s.serialize(g,l=>{if(l[w])return {headers:l.headers,body:l.body};let u="";for(let h in l)if(h!=="__type"){u=h;break}let{additionalHeaders:m,body:d,eventType:S,explicitPayloadContentType:v}=this.writeEventBody(u,c,l);return {headers:{":event-type":{type:"string",value:S},":message-type":{type:"string",value:"event"},":content-type":{type:"string",value:v??f},...m},body:d}})}async deserializeEventStream({response:e$1,responseSchema:t,initialResponseContainer:r}){let s=this.marshaller,a=t.getEventStreamMember(),o=t.getMemberSchema(a).getMemberSchemas(),f=Symbol("initialResponseMarker"),w=s.deserialize(e$1.body,async u=>{let m="";for(let S in u)if(S!=="__type"){m=S;break}let d=u[m].body;if(m==="initial-response"){let S=await this.deserializer.read(t,d);return delete S[a],{[f]:true,...S}}else if(m in o){let S=o[m];if(S.isStructSchema()){let v={},U=false;for(let[h,T]of S.structIterator()){let{eventHeader:P,eventPayload:W}=T.getMergedTraits();if(U=U||!!(P||W),W)T.isBlobSchema()?v[h]=d:T.isStringSchema()?v[h]=(this.serdeContext?.utf8Encoder??e)(d):T.isStructSchema()&&(v[h]=await this.deserializer.read(T,d));else if(P){let I=u[m].headers[h]?.value;I!=null&&(T.isNumericSchema()?I&&typeof I=="object"&&"bytes"in I?v[h]=BigInt(I.toString()):v[h]=Number(I):v[h]=I);}}if(U)return {[m]:v};if(d.byteLength===0)return {[m]:{}}}return {[m]:await this.deserializer.read(S,d)}}else return {$unknown:u}}),g=w[Symbol.asyncIterator](),l=await g.next();if(l.done)return w;if(l.value?.[f]){if(!t)throw new Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given.");for(let u in l.value)r[u]=l.value[u];}return {async*[Symbol.asyncIterator](){for(l?.value?.[f]||(yield l.value);;){let{done:u,value:m}=await g.next();if(u)break;yield m;}}}}writeEventBody(e,t,r){let s=this.serializer,a=e,c=null,o,f=t.getSchema()[4].includes(e),w={};if(f){let u=t.getMemberSchema(e);if(u.isStructSchema()){for(let[m,d]of u.structIterator()){let{eventHeader:S,eventPayload:v}=d.getMergedTraits();if(v)c=m;else if(S){let U=r[e][m],h="binary";d.isNumericSchema()?(-2)**31<=U&&U<=2**31-1?h="integer":h="long":d.isTimestampSchema()?h="timestamp":d.isStringSchema()?h="string":d.isBooleanSchema()&&(h="boolean"),U!=null&&(w[m]={type:h,value:U},delete r[e][m]);}}if(c!==null){let m=u.getMemberSchema(c);m.isBlobSchema()?o="application/octet-stream":m.isStringSchema()&&(o="text/plain"),s.write(m,r[e][c]);}else s.write(u,r[e]);}else if(u.isUnitSchema())s.write(u,{});else throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union.")}else {let[u,m]=r[e];a=u,s.write(15,m);}let g=s.flush()??new Uint8Array;return {body:typeof g=="string"?(this.serdeContext?.utf8Decoder??c$1)(g):g,eventType:a,explicitPayloadContentType:o,additionalHeaders:w}}};export{k as a,z as b,O as c,N as d,G as e,$ as f,A as g,K as h,oe as i,F as j,C as k,ie as l,j as m,le as n,ue as o,me as p,ye as q,q as r};
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
'use strict';var chunk7JWQ2PZP_cjs=require('./chunk-7JWQ2PZP.cjs'),chunkBCEE4NBZ_cjs=require('./chunk-BCEE4NBZ.cjs'),chunkVRZC4TTF_cjs=require('./chunk-VRZC4TTF.cjs'),chunkHTYVI2HK_cjs=require('./chunk-HTYVI2HK.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto$1=require('crypto');chunkBUNLC3II_cjs.h();var R=chunkBUNLC3II_cjs.e(chunkHTYVI2HK_cjs.a(),1);var S=false,_=class{db;prefix;sessionTTL;refreshTokenTTL;constructor(e){this.db=e.db,this.prefix=e.prefix||"kyro:",this.sessionTTL=e.sessionTTL||86400,this.refreshTokenTTL=e.refreshTokenTTL||604800;}async connect(){S||(await this.db.execute(chunkVRZC4TTF_cjs.J`
|
|
2
|
+
CREATE TABLE IF NOT EXISTS "users" (
|
|
3
|
+
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
4
|
+
"name" VARCHAR(255),
|
|
5
|
+
"email" VARCHAR(255) NOT NULL,
|
|
6
|
+
"password_hash" VARCHAR(255),
|
|
7
|
+
"role" VARCHAR(50) NOT NULL DEFAULT 'customer',
|
|
8
|
+
"tenant_id" UUID,
|
|
9
|
+
"email_verified" BOOLEAN DEFAULT false,
|
|
10
|
+
"locked" BOOLEAN DEFAULT false,
|
|
11
|
+
"last_login" TIMESTAMP,
|
|
12
|
+
"failed_login_attempts" INTEGER DEFAULT 0,
|
|
13
|
+
"metadata" JSONB,
|
|
14
|
+
"avatar" VARCHAR(255),
|
|
15
|
+
"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
|
|
16
|
+
"updated_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
17
|
+
)
|
|
18
|
+
`),await this.db.execute(chunkVRZC4TTF_cjs.J`ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "avatar" VARCHAR(255)`),await this.db.execute(chunkVRZC4TTF_cjs.J`CREATE UNIQUE INDEX IF NOT EXISTS "users_email_idx" ON "users" ("email")`),await this.db.execute(chunkVRZC4TTF_cjs.J`CREATE INDEX IF NOT EXISTS "users_tenant_idx" ON "users" ("tenant_id")`),await this.db.execute(chunkVRZC4TTF_cjs.J`CREATE INDEX IF NOT EXISTS "users_role_idx" ON "users" ("role")`),await this.db.execute(chunkVRZC4TTF_cjs.J`
|
|
19
|
+
CREATE TABLE IF NOT EXISTS "sessions" (
|
|
20
|
+
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
21
|
+
"user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
|
|
22
|
+
"token" VARCHAR(512) NOT NULL UNIQUE,
|
|
23
|
+
"refresh_token" VARCHAR(512),
|
|
24
|
+
"ip_address" VARCHAR(45),
|
|
25
|
+
"user_agent" TEXT,
|
|
26
|
+
"expires_at" TIMESTAMP NOT NULL,
|
|
27
|
+
"created_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
28
|
+
)
|
|
29
|
+
`),await this.db.execute(chunkVRZC4TTF_cjs.J`CREATE INDEX IF NOT EXISTS "sessions_user_idx" ON "sessions" ("user_id")`),await this.db.execute(chunkVRZC4TTF_cjs.J`CREATE INDEX IF NOT EXISTS "sessions_token_idx" ON "sessions" ("token")`),await this.db.execute(chunkVRZC4TTF_cjs.J`CREATE INDEX IF NOT EXISTS "sessions_expires_idx" ON "sessions" ("expires_at")`),await this.db.execute(chunkVRZC4TTF_cjs.J`
|
|
30
|
+
CREATE TABLE IF NOT EXISTS "audit_logs" (
|
|
31
|
+
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
32
|
+
"action" VARCHAR(100) NOT NULL,
|
|
33
|
+
"user_id" UUID REFERENCES "users"("id") ON DELETE SET NULL,
|
|
34
|
+
"user_email" VARCHAR(255),
|
|
35
|
+
"role" VARCHAR(50),
|
|
36
|
+
"resource" VARCHAR(100) NOT NULL,
|
|
37
|
+
"resource_id" VARCHAR(255),
|
|
38
|
+
"changes" JSONB,
|
|
39
|
+
"ip_address" VARCHAR(45),
|
|
40
|
+
"user_agent" TEXT,
|
|
41
|
+
"success" BOOLEAN NOT NULL DEFAULT true,
|
|
42
|
+
"error" TEXT,
|
|
43
|
+
"metadata" JSONB,
|
|
44
|
+
"timestamp" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
45
|
+
)
|
|
46
|
+
`),await this.db.execute(chunkVRZC4TTF_cjs.J`ALTER TABLE "audit_logs" ALTER COLUMN "resource_id" TYPE VARCHAR(255)`),await this.db.execute(chunkVRZC4TTF_cjs.J`CREATE INDEX IF NOT EXISTS "audit_logs_user_idx" ON "audit_logs" ("user_id")`),await this.db.execute(chunkVRZC4TTF_cjs.J`CREATE INDEX IF NOT EXISTS "audit_logs_action_idx" ON "audit_logs" ("action")`),await this.db.execute(chunkVRZC4TTF_cjs.J`CREATE INDEX IF NOT EXISTS "audit_logs_resource_idx" ON "audit_logs" ("resource")`),await this.db.execute(chunkVRZC4TTF_cjs.J`CREATE INDEX IF NOT EXISTS "audit_logs_timestamp_idx" ON "audit_logs" ("timestamp")`),await this.db.execute(chunkVRZC4TTF_cjs.J`
|
|
47
|
+
CREATE TABLE IF NOT EXISTS "password_history" (
|
|
48
|
+
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
49
|
+
"user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
|
|
50
|
+
"password_hash" VARCHAR(255) NOT NULL,
|
|
51
|
+
"created_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
52
|
+
)
|
|
53
|
+
`),await this.db.execute(chunkVRZC4TTF_cjs.J`CREATE INDEX IF NOT EXISTS "password_history_user_idx" ON "password_history" ("user_id")`),await this.db.execute(chunkVRZC4TTF_cjs.J`
|
|
54
|
+
CREATE TABLE IF NOT EXISTS "lockouts" (
|
|
55
|
+
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
56
|
+
"user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
|
|
57
|
+
"ip_address" VARCHAR(45),
|
|
58
|
+
"reason" VARCHAR(255),
|
|
59
|
+
"locked_until" TIMESTAMP NOT NULL,
|
|
60
|
+
"released_at" TIMESTAMP,
|
|
61
|
+
"created_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
62
|
+
)
|
|
63
|
+
`),await this.db.execute(chunkVRZC4TTF_cjs.J`CREATE INDEX IF NOT EXISTS "lockouts_user_idx" ON "lockouts" ("user_id")`),await this.db.execute(chunkVRZC4TTF_cjs.J`CREATE INDEX IF NOT EXISTS "lockouts_locked_until_idx" ON "lockouts" ("locked_until")`),await this.db.execute(chunkVRZC4TTF_cjs.J`
|
|
64
|
+
CREATE TABLE IF NOT EXISTS "roles" (
|
|
65
|
+
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
66
|
+
"name" VARCHAR(100) NOT NULL UNIQUE,
|
|
67
|
+
"level" INTEGER NOT NULL DEFAULT 0,
|
|
68
|
+
"inherits" TEXT[],
|
|
69
|
+
"description" TEXT,
|
|
70
|
+
"permissions" JSONB DEFAULT '[]',
|
|
71
|
+
"is_system" BOOLEAN DEFAULT false,
|
|
72
|
+
"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
|
|
73
|
+
"updated_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
74
|
+
)
|
|
75
|
+
`),await this.db.execute(chunkVRZC4TTF_cjs.J`CREATE INDEX IF NOT EXISTS "roles_level_idx" ON "roles" ("level")`),await this.db.execute(chunkVRZC4TTF_cjs.J`
|
|
76
|
+
CREATE TABLE IF NOT EXISTS "tenants" (
|
|
77
|
+
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
78
|
+
"name" VARCHAR(255) NOT NULL,
|
|
79
|
+
"slug" VARCHAR(100) NOT NULL UNIQUE,
|
|
80
|
+
"settings" JSONB DEFAULT '{}',
|
|
81
|
+
"is_active" BOOLEAN DEFAULT true,
|
|
82
|
+
"created_at" TIMESTAMP NOT NULL DEFAULT NOW(),
|
|
83
|
+
"updated_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
84
|
+
)
|
|
85
|
+
`),await this.db.execute(chunkVRZC4TTF_cjs.J`
|
|
86
|
+
CREATE TABLE IF NOT EXISTS "api_keys" (
|
|
87
|
+
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
88
|
+
"user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
|
|
89
|
+
"name" VARCHAR(255) NOT NULL,
|
|
90
|
+
"key" VARCHAR(64) NOT NULL UNIQUE,
|
|
91
|
+
"key_prefix" VARCHAR(8) NOT NULL,
|
|
92
|
+
"permissions" JSONB DEFAULT '[]',
|
|
93
|
+
"last_used_at" TIMESTAMP,
|
|
94
|
+
"expires_at" TIMESTAMP,
|
|
95
|
+
"created_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
96
|
+
)
|
|
97
|
+
`),await this.db.execute(chunkVRZC4TTF_cjs.J`
|
|
98
|
+
CREATE TABLE IF NOT EXISTS "email_verifications" (
|
|
99
|
+
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
100
|
+
"user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
|
|
101
|
+
"token" VARCHAR(64) NOT NULL UNIQUE,
|
|
102
|
+
"expires_at" TIMESTAMP NOT NULL,
|
|
103
|
+
"created_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
104
|
+
)
|
|
105
|
+
`),await this.db.execute(chunkVRZC4TTF_cjs.J`
|
|
106
|
+
CREATE TABLE IF NOT EXISTS "password_resets" (
|
|
107
|
+
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
108
|
+
"user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
|
|
109
|
+
"token" VARCHAR(64) NOT NULL UNIQUE,
|
|
110
|
+
"expires_at" TIMESTAMP NOT NULL,
|
|
111
|
+
"used_at" TIMESTAMP,
|
|
112
|
+
"created_at" TIMESTAMP NOT NULL DEFAULT NOW()
|
|
113
|
+
)
|
|
114
|
+
`),S=true);}async disconnect(){}async createUser(e){let s=await this.hashPassword(e.password),[t]=await this.db.insert(chunk7JWQ2PZP_cjs.a).values({email:e.email.toLowerCase(),name:e.name,passwordHash:s,role:e.role||"customer",avatar:e.avatar,tenantId:e.tenantId,emailVerified:e.emailVerified??true}).returning();return this.userToAuthUser(t)}async findUserByEmail(e){let[s]=await this.db.select().from(chunk7JWQ2PZP_cjs.a).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.a.email,e.toLowerCase())).limit(1);return s?this.userToAuthUser(s):null}async findUserById(e){let[s]=await this.db.select().from(chunk7JWQ2PZP_cjs.a).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.a.id,e)).limit(1);return s?this.userToAuthUser(s):null}async updateUser(e,s){let t={updatedAt:new Date};s.name!==void 0&&(t.name=s.name),s.email!==void 0&&(t.email=s.email),s.passwordHash!==void 0&&(t.passwordHash=s.passwordHash),s.role!==void 0&&(t.role=s.role),s.tenantId!==void 0&&(t.tenantId=s.tenantId),s.avatar!==void 0&&(t.avatar=s.avatar),s.emailVerified!==void 0&&(t.emailVerified=s.emailVerified),s.locked!==void 0&&(t.locked=s.locked),s.lastLogin!==void 0&&(t.lastLogin=s.lastLogin?new Date(s.lastLogin):null),s.failedLoginAttempts!==void 0&&(t.failedLoginAttempts=s.failedLoginAttempts);let[r]=await this.db.update(chunk7JWQ2PZP_cjs.a).set(t).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.a.id,e)).returning();return r?this.userToAuthUser(r):null}async deleteUser(e){return await this.db.delete(chunk7JWQ2PZP_cjs.a).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.a.id,e)),true}async findUsers(e={}){let s=e.page??1,t=e.limit??10,r=(s-1)*t,u=e.search;if(u){let m=`%${u}%`,[w,[{count:p}]]=await Promise.all([this.db.select().from(chunk7JWQ2PZP_cjs.a).where(chunkVRZC4TTF_cjs.J`${chunk7JWQ2PZP_cjs.a.email} ILIKE ${m}`).orderBy(chunkBCEE4NBZ_cjs.M(chunk7JWQ2PZP_cjs.a.createdAt)).limit(t).offset(r),this.db.select({count:chunkVRZC4TTF_cjs.J`count(*)`}).from(chunk7JWQ2PZP_cjs.a).where(chunkVRZC4TTF_cjs.J`${chunk7JWQ2PZP_cjs.a.email} ILIKE ${m}`)]);return {users:w.map(T=>this.userToAuthUser(T)),total:Number(p)}}let[c,[{count:E}]]=await Promise.all([this.db.select().from(chunk7JWQ2PZP_cjs.a).orderBy(chunkBCEE4NBZ_cjs.M(chunk7JWQ2PZP_cjs.a.createdAt)).limit(t).offset(r),this.db.select({count:chunkVRZC4TTF_cjs.J`count(*)`}).from(chunk7JWQ2PZP_cjs.a)]);return {users:c.map(m=>this.userToAuthUser(m)),total:Number(E)}}async verifyPassword(e,s){let t=await this.findUserByEmail(e);if(!t)return null;let[r]=await this.db.select().from(chunk7JWQ2PZP_cjs.a).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.a.email,e.toLowerCase())).limit(1);return r?.passwordHash&&await R.default.compare(s,r.passwordHash)?t:null}async hashPassword(e){return R.default.hash(e,12)}async createSession(e,s){let t=crypto$1.randomBytes(32).toString("base64url"),r=crypto$1.randomBytes(32).toString("base64url"),u=new Date(Date.now()+this.sessionTTL*1e3);new Date(Date.now()+this.refreshTokenTTL*1e3);let [E]=await this.db.insert(chunk7JWQ2PZP_cjs.d).values({userId:e,token:t,refreshToken:r,ipAddress:s?.ipAddress,userAgent:s?.userAgent,expiresAt:u}).returning();return this.sessionToSession(E)}async findSessionByToken(e){let[s]=await this.db.select().from(chunk7JWQ2PZP_cjs.d).where(chunkBCEE4NBZ_cjs.p(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.d.token,e),chunkBCEE4NBZ_cjs.s(chunk7JWQ2PZP_cjs.d.expiresAt,new Date))).limit(1);return s?this.sessionToSession(s):null}async findSessionByRefreshToken(e){let[s]=await this.db.select().from(chunk7JWQ2PZP_cjs.d).where(chunkBCEE4NBZ_cjs.p(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.d.refreshToken,e),chunkBCEE4NBZ_cjs.s(chunk7JWQ2PZP_cjs.d.expiresAt,new Date))).limit(1);return s?this.sessionToSession(s):null}async deleteSession(e){return await this.db.delete(chunk7JWQ2PZP_cjs.d).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.d.id,e)),true}async deleteUserSessions(e){return await this.db.delete(chunk7JWQ2PZP_cjs.d).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.d.userId,e)),1}async addPasswordToHistory(e,s){await this.db.insert(chunk7JWQ2PZP_cjs.j).values({userId:e,passwordHash:s});}async getPasswordHistory(e,s=5){return (await this.db.select({passwordHash:chunk7JWQ2PZP_cjs.j.passwordHash}).from(chunk7JWQ2PZP_cjs.j).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.j.userId,e)).orderBy(chunkBCEE4NBZ_cjs.M(chunk7JWQ2PZP_cjs.j.createdAt)).limit(s)).map(r=>r.passwordHash)}async isPasswordInHistory(e,s,t=5){let r=await this.getPasswordHistory(s,t);for(let u of r)if(await this.verifyPassword(e,u))return true;return false}async isLocked(e){let[s]=await this.db.select().from(chunk7JWQ2PZP_cjs.k).where(chunkBCEE4NBZ_cjs.p(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.k.userId,e),chunkBCEE4NBZ_cjs.s(chunk7JWQ2PZP_cjs.k.lockedUntil,new Date))).limit(1);return !!s}async getLockout(e){let[s]=await this.db.select().from(chunk7JWQ2PZP_cjs.k).where(chunkBCEE4NBZ_cjs.p(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.k.userId,e),chunkBCEE4NBZ_cjs.s(chunk7JWQ2PZP_cjs.k.lockedUntil,new Date))).limit(1);return s?{lockedUntil:s.lockedUntil}:null}async recordFailedAttempt(e,s){let r=((await this.findUserById(e))?.failedLoginAttempts||0)+1;await this.updateUser(e,{failedLoginAttempts:r});let c=r>=5;return c&&await this.db.insert(chunk7JWQ2PZP_cjs.k).values({userId:e,ipAddress:s,reason:"Too many failed login attempts",lockedUntil:new Date(Date.now()+9e5)}),{attempts:r,locked:c}}async resetAttempts(e){await this.updateUser(e,{failedLoginAttempts:0});}async findAuditLogs(e){let{limit:s=50,offset:t=0,userId:r,action:u,resource:c,resourceId:E,success:m,startDate:w,endDate:p}=e,T=[];r&&T.push(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.e.userId,r)),u&&(Array.isArray(u)?T.push(chunkVRZC4TTF_cjs.J`${chunk7JWQ2PZP_cjs.e.action} = ANY(${u})`):T.push(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.e.action,u))),c&&T.push(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.e.resource,c)),E&&T.push(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.e.resourceId,E)),m!==void 0&&T.push(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.e.success,m)),w&&T.push(chunkVRZC4TTF_cjs.J`${chunk7JWQ2PZP_cjs.e.timestamp} >= ${w}`),p&&T.push(chunkVRZC4TTF_cjs.J`${chunk7JWQ2PZP_cjs.e.timestamp} <= ${p}`);let O=T.length>0?chunkBCEE4NBZ_cjs.p(...T):void 0,b=await this.db.select({count:chunkVRZC4TTF_cjs.J`count(*)`}).from(chunk7JWQ2PZP_cjs.e).where(O);return {logs:(await this.db.select().from(chunk7JWQ2PZP_cjs.e).where(O).orderBy(chunkBCEE4NBZ_cjs.M(chunk7JWQ2PZP_cjs.e.timestamp)).limit(s).offset(t)).map(o=>({id:o.id,timestamp:o.timestamp,action:o.action,userId:o.userId||void 0,userEmail:o.userEmail||void 0,role:o.role||void 0,resource:o.resource,resourceId:o.resourceId||void 0,changes:o.changes||void 0,ipAddress:o.ipAddress||void 0,userAgent:o.userAgent||void 0,success:o.success,error:o.error||void 0,metadata:o.metadata||void 0})),total:Number(b[0]?.count||0)}}async createAuditLog(e){let s=crypto.randomUUID(),t=new Date;return await this.db.insert(chunk7JWQ2PZP_cjs.e).values({id:s,action:e.action,userId:e.userId??null,userEmail:e.userEmail??null,role:e.role??null,resource:e.resource,resourceId:e.resourceId??null,changes:e.changes??null,ipAddress:e.ipAddress??null,userAgent:e.userAgent??null,success:e.success,error:e.error??null,metadata:e.metadata??null,timestamp:t}),{...e,id:s,timestamp:t}}userToAuthUser(e){return {id:e.id,name:e.name||void 0,email:e.email,passwordHash:e.passwordHash||void 0,role:e.role,avatar:e.avatar&&typeof e.avatar=="object"?e.avatar.id||void 0:e.avatar||void 0,tenantId:e.tenantId||void 0,emailVerified:e.emailVerified||false,locked:e.locked||false,lastLogin:e.lastLogin?new Date(e.lastLogin).toISOString():void 0,failedLoginAttempts:e.failedLoginAttempts||0,createdAt:new Date(e.createdAt).toISOString(),updatedAt:new Date(e.updatedAt).toISOString()}}sessionToSession(e){return {id:e.id,userId:e.userId,token:e.token,refreshToken:e.refreshToken||void 0,expiresAt:new Date(e.expiresAt).toISOString(),createdAt:new Date(e.createdAt).toISOString(),ipAddress:e.ipAddress||void 0,userAgent:e.userAgent||void 0}}async createEmailVerificationToken(e){let s=crypto$1.randomBytes(32).toString("hex"),t=new Date(Date.now()+1440*60*1e3);return await this.db.insert(chunk7JWQ2PZP_cjs.h).values({userId:e,token:s,expiresAt:t}),{token:s,expiresAt:t}}async verifyEmailToken(e){let[s]=await this.db.select().from(chunk7JWQ2PZP_cjs.h).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.h.token,e)).limit(1);return s?s.expiresAt<new Date?{success:false,error:"Verification token has expired"}:(await this.db.update(chunk7JWQ2PZP_cjs.a).set({emailVerified:true}).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.a.id,s.userId)),await this.db.delete(chunk7JWQ2PZP_cjs.h).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.h.id,s.id)),{success:true,userId:s.userId}):{success:false,error:"Invalid verification token"}}async createPasswordResetToken(e){let s=await this.findUserByEmail(e);if(!s)return {token:"",expiresAt:new Date,error:"User not found"};let t=crypto$1.randomBytes(32).toString("hex"),r=new Date(Date.now()+3600*1e3);return await this.db.insert(chunk7JWQ2PZP_cjs.i).values({userId:s.id,token:t,expiresAt:r}),{token:t,expiresAt:r}}async resetPasswordWithToken(e,s){let[t]=await this.db.select().from(chunk7JWQ2PZP_cjs.i).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.i.token,e)).limit(1);if(!t)return {success:false,error:"Invalid reset token"};if(t.expiresAt<new Date)return {success:false,error:"Reset token has expired"};if(t.usedAt)return {success:false,error:"Reset token has already been used"};let r=await this.hashPassword(s);return await this.db.update(chunk7JWQ2PZP_cjs.a).set({passwordHash:r,updatedAt:new Date}).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.a.id,t.userId)),await this.db.update(chunk7JWQ2PZP_cjs.i).set({usedAt:new Date}).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.i.id,t.id)),await this.db.delete(chunk7JWQ2PZP_cjs.d).where(chunkBCEE4NBZ_cjs.n(chunk7JWQ2PZP_cjs.d.userId,t.userId)),{success:true}}};exports.a=_;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
1
|
+
import'path';import'url';var require$1; if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); require$1 = createRequire(import.meta.url); }
|
|
2
2
|
var a=Object.create;var r=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var c=Object.getOwnPropertyNames;var f=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty;var d=(t=>typeof require$1<"u"?require$1:typeof Proxy<"u"?new Proxy(t,{get:(e,o)=>(typeof require$1<"u"?require$1:e)[o]}):t)(function(t){if(typeof require$1<"u")return require$1.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var s=(t,e)=>()=>(t&&(e=t(t=0)),e);var g=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),h=(t,e)=>{for(var o in e)r(t,o,{get:e[o],enumerable:true});},n=(t,e,o,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let m of c(e))!l.call(t,m)&&m!==o&&r(t,m,{get:()=>e[m],enumerable:!(i=p(e,m))||i.enumerable});return t};var x=(t,e,o)=>(o=t!=null?a(f(t)):{},n(e||!t||!t.__esModule?r(o,"default",{value:t,enumerable:true}):o,t)),u=t=>n(r({},"__esModule",{value:true}),t);var _=s(()=>{});export{d as a,s as b,g as c,h as d,x as e,u as f,_ as g};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {g}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
|
+
g();function t(e,r,o){let n=new Error(`[unstorage] [${e}] ${r}`,o);return Error.captureStackTrace&&Error.captureStackTrace(n,t),n}function a(e,r){return Array.isArray(r)?t(e,`Missing some of the required options ${r.map(o=>"`"+o+"`").join(", ")}`):t(e,`Missing required option \`${r}\`.`)}export{t as a,a as b};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkTUIKVRQN_cjs=require('./chunk-TUIKVRQN.cjs'),chunkHKNQVI76_cjs=require('./chunk-HKNQVI76.cjs'),chunkCFZVJTXW_cjs=require('./chunk-CFZVJTXW.cjs'),chunkBHR7OAU4_cjs=require('./chunk-BHR7OAU4.cjs'),chunk6KUL2BSA_cjs=require('./chunk-6KUL2BSA.cjs'),chunkXBQ6HV3T_cjs=require('./chunk-XBQ6HV3T.cjs'),chunkWJBQ2NBD_cjs=require('./chunk-WJBQ2NBD.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),w=require('kyro:config');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var w__default=/*#__PURE__*/_interopDefault(w);chunkBUNLC3II_cjs.h();exports.a=null;var l=null;async function b(){if(!exports.a){if(globalThis.__KYRO_INSTANCE__)try{await globalThis.__KYRO_INSTANCE__.shutdown();}catch{}try{let e=w__default.default.default||w__default.default,t=e.adapter,o=t&&!t.dialect&&typeof t.connect=="function";if(globalThis.DB&&(!t||o)){let s=globalThis.DB;e.adapter=new chunk6KUL2BSA_cjs.c({type:"sqlite",client:s}),chunkTUIKVRQN_cjs.D.info("Hot-swapped to D1 DrizzleAdapter");}exports.a=chunkTUIKVRQN_cjs.A(e),await exports.a.init();let a=e.adapter,p=a&&a.dialect&&(a.dialect==="postgres"||a.dialect==="sqlite"),c=a&&a.dialect==="mongodb",n;if(p)a.dialect==="postgres"?n=new chunkXBQ6HV3T_cjs.a({db:a.client}):a.dialect==="sqlite"&&(n=new chunkCFZVJTXW_cjs.fb({db:a.rawClient||a.client}));else if(o&&!globalThis.DB){let s=process.env.KYRO_AUTH_DB_PATH||"./data/auth.db";n=new chunkBHR7OAU4_cjs.a({path:s});}else c&&(n=new chunkWJBQ2NBD_cjs.a({adapter:a}));if(n?.connect)try{await n.connect();}catch(s){chunkTUIKVRQN_cjs.D.warn("Auth connect warning:",s);}try{await exports.a.loadSettings();}catch(s){chunkTUIKVRQN_cjs.D.warn("loadSettings warning:",s);}try{await chunkHKNQVI76_cjs.e(n);}catch(s){chunkTUIKVRQN_cjs.D.warn("autoBootstrap warning:",s);}globalThis.__KYRO_INSTANCE__=exports.a;}catch(e){throw exports.a=null,l=null,chunkTUIKVRQN_cjs.D.error("Init failed, will retry:",e),e}}}async function E(e){let t=globalThis.DB?globalThis:null;try{let{env:o}=await import('cloudflare:workers');o&&(t=o);}catch{}if(e)try{t=e.locals?.cfContext?.env||e?.env||t;}catch{}if(!t)try{t=process.env;}catch{}t?.DB&&(globalThis.DB=t.DB),t?.STORAGE_BUCKET&&(globalThis.STORAGE_BUCKET=t.STORAGE_BUCKET),l||(l=b()),await l;}var _={graphqlEnabled:false,trpcEnabled:false,wsEnabled:false,requireAuth:false};function T(e){return exports.a?exports.a.settings?.access?.apiAccess?.[e]??_[e]??true:_[e]??true}var R=async e=>{if(!exports.a)try{await Promise.race([E(e),new Promise((t,o)=>setTimeout(()=>o(new Error("Initialization timeout")),3e4))]);}catch(t){return console.error("[Kyro API] Warm error:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Service Unavailable",message:"Kyro CMS is still starting up. Please try again in a moment."}),{status:503,headers:{"Content-Type":"application/json","Retry-After":"5"}})}try{let o=new URL(e.request.url).pathname,a=__KYRO_API_PATH__;if(o===`${a}/graphql`&&typeof exports.a.getGraphQL=="function"){if(!T("graphqlEnabled"))return new Response(JSON.stringify({error:"GraphQL is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await exports.a.getGraphQL().fetch(e.request,e.locals);return new Response(n.body,n)}if(o.startsWith(`${a}/trpc/`)&&typeof exports.a.getTRPC=="function"){if(!T("trpcEnabled"))return new Response(JSON.stringify({error:"tRPC is disabled"}),{status:503,headers:{"Content-Type":"application/json"}});let n=await exports.a.getTRPC().fetch(e.request,e.locals);return new Response(n.body,n)}return await(await exports.a.getREST()).fetch(e.request,e.locals)}catch(t){return console.error("[Kyro API Execution Error]:",t?.stack||t?.message||t),new Response(JSON.stringify({error:"Internal Server Error",message:t?.message||String(t),stack:t?.stack}),{status:500,headers:{"Content-Type":"application/json"}})}},L=R;exports.b=E;exports.c=R;exports.d=L;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {H,b,M,K as K$1,L,g as g$1,l}from'./chunk-OBYAIJVU.js';import {e,o,L as L$1,Q,P,m,M as M$1,k,J as J$1,f,h,U as U$1,n,N as N$1,K as K$2,O}from'./chunk-JRUQ5ABB.js';import {t,v as v$1,c,s,a,d,D as D$1,r,f as f$1,e as e$1,k as k$1,b as b$1,j as j$1,i,h as h$1}from'./chunk-TYQYKKWJ.js';import {g}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
g();g();g();var se=i=>f.isInstance(i)?i.headers?.date??i.headers?.Date:void 0;g();var U=i=>new Date(Date.now()+i);g();g();var st=(i,e)=>Math.abs(U(e).getTime()-i)>=3e5;var ie=(i,e)=>{let t=Date.parse(i);return st(t,e)?t-Date.now():e};var q=(i,e)=>{if(!e)throw new Error(`Property \`${i}\` is not resolved for AWS SDK SigV4Auth`);return e},v=async i=>{let e=q("context",i.context),t=q("config",i.config),r=e.endpointV2?.properties?.authSchemes?.[0],o=await q("signer",t.signer)(r),n=i?.signingRegion,a=i?.signingRegionSet,m=i?.signingName;return {config:t,signer:o,signingRegion:n,signingRegionSet:a,signingName:m}},K=class{async sign(e$1,t,r){if(!e.isInstance(e$1))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");let s=await v(r),{config:o,signer:n}=s,{signingRegion:a,signingName:m}=s,c=r.context;if(c?.authSchemes?.length??false){let[l,h]=c.authSchemes;l?.name==="sigv4a"&&h?.name==="sigv4"&&(a=h?.signingRegion??a,m=h?.signingName??m);}return r._preRequestSystemClockOffset=o.systemClockOffset,await n.sign(e$1,{signingDate:U(o.systemClockOffset),signingRegion:a,signingService:m})}errorHandler(e){return t=>{let r=t,s=r.ServerTime??se(r.$response);if(s){let o=q("config",e.config),n=e._preRequestSystemClockOffset,a=ie(s,o.systemClockOffset);(a!==o.systemClockOffset||n!==void 0&&n!==a)&&r.$metadata&&(o.systemClockOffset=a,r.$metadata.clockSkewCorrected=true);}throw t}}successHandler(e,t){let r=se(e);if(r){let s=q("config",t.config);s.systemClockOffset=ie(r,s.systemClockOffset);}}};g();var oe=class extends K{async sign(e$1,t,r){if(!e.isInstance(e$1))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");let{config:s,signer:o,signingRegion:n,signingRegionSet:a,signingName:m}=await v(r),f=(await s.sigv4aSigningRegionSet?.()??a??[n]).join(",");return r._preRequestSystemClockOffset=s.systemClockOffset,await o.sign(e$1,{signingDate:U(s.systemClockOffset),signingRegion:f,signingService:m})}};g();g();var be=i=>typeof i=="string"&&i.length>0?i.split(",").map(e=>e.trim()):[];g();var it=i=>`AWS_BEARER_TOKEN_${i.replace(/[\s-]/g,"_").toUpperCase()}`;var ot="AWS_AUTH_SCHEME_PREFERENCE",nt="auth_scheme_preference",at={environmentVariableSelector:(i,e)=>{if(e?.signingName&&it(e.signingName)in i)return ["httpBearerAuth"];if(ot in i)return be(i[ot])},configFileSelector:i=>{if(nt in i)return be(i[nt])},default:[]};g();var ct=i=>(i.sigv4aSigningRegionSet=H(i.sigv4aSigningRegionSet),i),mt={environmentVariableSelector(i){if(i.AWS_SIGV4A_SIGNING_REGION_SET)return i.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map(e=>e.trim());throw new o("AWS_SIGV4A_SIGNING_REGION_SET not set in env.",{tryNextLink:true})},configFileSelector(i){if(i.sigv4a_signing_region_set)return (i.sigv4a_signing_region_set??"").split(",").map(e=>e.trim());throw new o("sigv4a_signing_region_set not set in profile.",{tryNextLink:true})},default:void 0};g();g();g();g();var ne=class{format(e){let t=[];for(let o of Object.keys(e)){let n=c(o);t.push(Uint8Array.from([n.byteLength]),n,this.formatHeaderValue(e[o]));}let r=new Uint8Array(t.reduce((o,n)=>o+n.byteLength,0)),s=0;for(let o of t)r.set(o,s),s+=o.byteLength;return r}formatHeaderValue(e){switch(e.type){case "boolean":return Uint8Array.from([e.value?T.boolTrue:T.boolFalse]);case "byte":return Uint8Array.from([T.byte,e.value]);case "short":let t=new DataView(new ArrayBuffer(3));return t.setUint8(0,T.short),t.setInt16(1,e.value,false),new Uint8Array(t.buffer);case "integer":let r=new DataView(new ArrayBuffer(5));return r.setUint8(0,T.integer),r.setInt32(1,e.value,false),new Uint8Array(r.buffer);case "long":let s$1=new Uint8Array(9);return s$1[0]=T.long,s$1.set(e.value.bytes,1),s$1;case "binary":let o=new DataView(new ArrayBuffer(3+e.value.byteLength));o.setUint8(0,T.byteArray),o.setUint16(1,e.value.byteLength,false);let n=new Uint8Array(o.buffer);return n.set(e.value,3),n;case "string":let a=c(e.value),m=new DataView(new ArrayBuffer(3+a.byteLength));m.setUint8(0,T.string),m.setUint16(1,a.byteLength,false);let c$1=new Uint8Array(m.buffer);return c$1.set(a,3),c$1;case "timestamp":let f=new Uint8Array(9);return f[0]=T.timestamp,f.set(Re.fromNumber(e.value.valueOf()).bytes,1),f;case "uuid":if(!Vt.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);let l=new Uint8Array(17);return l[0]=T.uuid,l.set(s(e.value.replace(/-/g,"")),1),l}}},T;(function(i){i[i.boolTrue=0]="boolTrue",i[i.boolFalse=1]="boolFalse",i[i.byte=2]="byte",i[i.short=3]="short",i[i.integer=4]="integer",i[i.long=5]="long",i[i.byteArray=6]="byteArray",i[i.string=7]="string",i[i.timestamp=8]="timestamp",i[i.uuid=9]="uuid";})(T||(T={}));var Vt=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/,Re=class i{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776e3||e<-9223372036854776e3)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);let t=new Uint8Array(8);for(let r=7,s=Math.abs(Math.round(e));r>-1&&s>0;r--,s/=256)t[r]=s;return e<0&&ft(t),new i(t)}valueOf(){let e=this.bytes.slice(0),t$1=e[0]&128;return t$1&&ft(e),parseInt(t(e),16)*(t$1?-1:1)}toString(){return String(this.valueOf())}};function ft(i){for(let e=0;e<8;e++)i[e]^=255;for(let e=7;e>-1&&(i[e]++,i[e]===0);e--);}g();g();g();var dt="X-Amz-Algorithm",lt="X-Amz-Credential",Te="X-Amz-Date",ht="X-Amz-SignedHeaders",ut="X-Amz-Expires",_e="X-Amz-Signature",ke="X-Amz-Security-Token";var Ie="authorization",Me=Te.toLowerCase(),jt="date",gt=[Ie,Me,jt],pt=_e.toLowerCase(),J="x-amz-content-sha256",yt=ke.toLowerCase();var St={authorization:true,"cache-control":true,connection:true,expect:true,from:true,"keep-alive":true,"max-forwards":true,pragma:true,referer:true,te:true,trailer:true,"transfer-encoding":true,upgrade:true,"user-agent":true,"x-amzn-trace-id":true},wt=/^proxy-/,Et=/^sec-/;var ae="AWS4-HMAC-SHA256";var xt="AWS4-HMAC-SHA256-PAYLOAD",At="UNSIGNED-PAYLOAD",Nt=50,De="aws4_request",Ct=3600*24*7;var bt=({query:i={}})=>{let e=[],t={};for(let r of Object.keys(i)){if(r.toLowerCase()===pt)continue;let s=U$1(r);e.push(s);let o=i[r];typeof o=="string"?t[s]=`${s}=${U$1(o)}`:Array.isArray(o)&&(t[s]=o.slice(0).reduce((n,a)=>n.concat([`${s}=${U$1(a)}`]),[]).sort().join("&"));}return e.sort().map(r=>t[r]).filter(r=>r).join("&")};g();var Rt=i=>Xt(i).toISOString().replace(/\.\d{3}Z$/,"Z"),Xt=i=>typeof i=="number"?new Date(i*1e3):typeof i=="string"?Number(i)?new Date(Number(i)*1e3):new Date(i):i;var ce=class{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:e,credentials:t,region:r,service:s,sha256:o,uriEscapePath:n=true}){this.service=s,this.sha256=o,this.uriEscapePath=n,this.applyChecksum=typeof e=="boolean"?e:true,this.regionProvider=h(r),this.credentialProvider=h(t);}createCanonicalRequest(e,t,r){let s=Object.keys(t).sort();return `${e.method}
|
|
3
3
|
${this.getCanonicalPath(e)}
|
|
4
4
|
${bt(e)}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {a as a$1,h}from'./chunk-RTHJ6SS5.js';import {a}from'./chunk-VVVCCB6R.js';import {a as a$2}from'./chunk-TBHNE4VV.js';import {g}from'./chunk-Y2YAKDEQ.js';import {createHmac,randomBytes,randomUUID}from'crypto';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
g();var _={COLLECTION_CREATE:"collection.create",COLLECTION_UPDATE:"collection.update",COLLECTION_DELETE:"collection.delete",MEDIA_UPLOAD:"media.upload",MEDIA_DELETE:"media.delete",AUTH_LOGIN:"auth.login",AUTH_REGISTER:"auth.register",AUTH_LOGOUT:"auth.logout",ORDER_CREATED:"order.created",ORDER_PAID:"order.paid",ORDER_SHIPPED:"order.shipped",ORDER_DELIVERED:"order.delivered"},G=Object.values(_);var k="_webhooks",w="_webhook_deliveries";g();g();g();g();async function L(o,t,s,e={}){let r=e.timeout||3e4,i=Date.now(),u=new AbortController,c=setTimeout(()=>u.abort(),r);try{let a=await fetch(o,{method:"POST",headers:t,body:s,signal:u.signal});clearTimeout(c);let n=Date.now()-i,l;try{l=(await a.text()).slice(0,1e3);}catch{}let d={success:a.ok,status:a.status,statusText:a.statusText,body:l,duration:n};return d.success&&e.onSuccess?e.onSuccess(d):!d.success&&e.onFailure&&e.onFailure(`HTTP ${a.status}: ${a.statusText}`),d}catch(a){clearTimeout(c);let n=Date.now()-i,l=a.name==="AbortError"?`Request timed out after ${r}ms`:a.message||"Unknown error";return e.onFailure&&e.onFailure(l),{success:false,status:0,duration:n,error:l}}}async function $(o,t,s={}){let e=JSON.stringify(t),r={"Content-Type":"application/json","User-Agent":"Kyro-CMS-Webhook/1.0","X-Webhook-Event":t.event,"X-Webhook-Delivery":t.id,"X-Webhook-Timestamp":t.timestamp,...o.headers||{}};return o.secret&&(r["X-Webhook-Signature"]=P(e,o.secret)),L(o.url,r,e,s)}g();async function j(o,t,s={}){let e=o.config||{},r=process.env.GITHUB_TOKEN;if(!r)return {success:false,status:0,duration:0,error:"GITHUB_TOKEN environment variable is not set"};if(!e.githubOwner||!e.githubRepo)return {success:false,status:0,duration:0,error:"GitHub owner and repo are required"};let i=e.githubBranch||"main",u=Date.now(),c=async(a,n,l)=>{let d=await fetch(a,{method:n,headers:{"Content-Type":"application/json",Accept:"application/vnd.github+json",Authorization:`Bearer ${r}`,"X-GitHub-Api-Version":"2022-11-28","User-Agent":"Kyro-CMS-Webhook/1.0"},body:l?JSON.stringify(l):void 0});if(!d.ok){let y=await d.text();throw new Error(`GitHub API HTTP ${d.status}: ${y}`)}return d.json()};try{let a=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/refs/heads/${i}`,l=(await c(a,"GET")).object.sha,d=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/commits/${l}`,f=(await c(d,"GET")).tree.sha,p=`https://api.github.com/repos/${e.githubOwner}/${e.githubRepo}/git/commits`,b=(await c(p,"POST",{message:`Content updated via Kyro CMS (${t.event})`,tree:f,parents:[l]})).sha;return await c(a,"PATCH",{sha:b,force:!1}),{success:!0,status:201,duration:Date.now()-u,body:`Successfully pushed empty commit ${b} to branch ${i}`}}catch(a){return {success:false,status:0,duration:Date.now()-u,error:a.message||"Failed to push empty commit to GitHub"}}}var K={generic:$,"github-push":j};function S(o){return K[o||"generic"]||K.generic}function P(o,t){return `sha256=${createHmac("sha256",t).update(o).digest("hex")}`}function x(){return randomBytes(32).toString("hex")}async function U(o,t,s={}){return S(o.action)(o,t,s)}async function I(o,t,s,e={}){let r=e.maxRetries??5,i=e.retryDelay??1e3,u=null;for(let c=0;c<=r;c++){if(c>0){let a=Math.min(i*Math.pow(2,c-1),3e4);e.onRetry&&e.onRetry(c,`Retrying in ${a}ms...`),await F(a);}if(e.onRetry&&c>0&&e.onRetry(c,`Attempt ${c+1}/${r+1}`),u=await U(o,t,{...e,onRetry:void 0,onSuccess:void 0,onFailure:void 0}),u.success)return u;if(!(u.error?.includes("timed out")&&c<r)&&u.status>=400&&u.status<500)return u}return u||{success:false,status:0,duration:0,error:"All delivery attempts failed"}}function H(o,t,s,e,r,i){return {id:o,webhookId:t,event:s,payload:e,attempt:r,status:i.success?"success":"failed",responseStatus:i.status||void 0,responseBody:i.body,duration:i.duration,error:i.error,createdAt:new Date().toISOString(),deliveredAt:i.success?new Date().toISOString():void 0}}function F(o){return new Promise(t=>setTimeout(t,o))}function z(){return {id:`test_${Date.now()}`,event:"collection.create",timestamp:new Date().toISOString(),collection:"test",operation:"create",data:{message:"This is a test webhook delivery"},user:{id:"system",email:"system@kyro.dev",role:"super_admin"}}}g();function N(o){let t=new Set,s=[];for(let e of o){let r=e==="create"||e==="update"||e==="delete"?`collection.${e}`:e;t.has(r)||(t.add(r),s.push(r));}return s}var O=class{db;constructor(t){this.db=t;}async getWebhooks(t){let e=(await this.db.find({collection:k,where:t?.status?{status:{equals:t.status}}:{},limit:100,page:1,draft:true})).docs;return t?.event?e.filter(r=>r.events.includes(t.event)):e}async getWebhookById(t){return this.db.findByID({collection:k,id:t,draft:true})}async createWebhook(t){let s=new Date().toISOString(),e=t.secret||x(),r={id:randomUUID(),name:t.name,url:t.url,events:N(t.events),collections:t.collections||[],status:t.status||"active",secret:e,headers:t.headers||{},action:t.action||"generic",config:t.config||{},createdAt:s,updatedAt:s};return await this.db.create({collection:k,data:r}),r}async updateWebhook(t,s){let e=await this.getWebhookById(t);if(!e)return null;let r={...e,...s,events:s.events?N(s.events):e.events,collections:s.collections!==void 0?s.collections:e.collections,action:s.action!==void 0?s.action:e.action,config:s.config!==void 0?{...e.config,...s.config}:e.config,updatedAt:new Date().toISOString()};return s.secret===""&&"secret"in s&&delete r.secret,await this.db.update({collection:k,id:t,data:r}),r}async deleteWebhook(t){await this.db.delete({collection:k,id:t});}async trigger(t,s){let e=await this.getWebhooks({status:"active",event:t}),r=s.collection,i=e.filter(a=>!a.collections||a.collections.length===0||!r?true:a.collections.includes(r));if(i.length===0)return [];let u={id:randomUUID(),event:t,timestamp:new Date().toISOString(),...s},c=[];for(let a of i){let n=await this.triggerWebhook(a,u);c.push(n);}return c}async triggerWebhook(t,s){let e=randomUUID();try{let r=await I(t,s,e,{maxRetries:5,retryDelay:1e3}),i=H(e,t.id,t.events[0],s,1,r);try{await this.db.create({collection:w,data:i});}catch{console.warn("[WebhookService] Failed to save delivery record:",e);}return r.success?await this.updateWebhook(t.id,{lastTriggered:new Date().toISOString(),lastError:null}).catch(()=>{}):await this.updateWebhook(t.id,{lastError:r.error||`HTTP ${r.status}`}).catch(()=>{}),{deliveryId:e,webhookId:t.id,event:t.events[0],status:r.success?"success":"failed",responseStatus:r.status,duration:r.duration,error:r.error}}catch(r){return {deliveryId:e,webhookId:t.id,event:t.events[0],status:"failed",error:r.message}}}async testWebhook(t){let s=await this.getWebhookById(t);if(!s)return null;let e={id:randomUUID(),event:s.events[0]||"collection.create",timestamp:new Date().toISOString(),collection:"test",operation:"create",data:{message:"This is a test webhook delivery from Kyro CMS"},user:{id:"system",email:"system@kyro.dev",role:"super_admin"}};return this.triggerWebhook(s,e)}async getDeliveryHistory(t,s=50){return (await this.db.find({collection:w,where:{webhookId:{equals:t}},sort:"-createdAt",limit:s,page:1})).docs}async retryDelivery(t){let s=await this.db.findByID({collection:w,id:t});if(!s)return null;let e=await this.getWebhookById(s.webhookId);return e?this.triggerWebhook(e,s.payload):null}};function X(o){return new O(o)}g();g();function Y(o){if(!o)return [];if(typeof o=="string")return [{id:o}];if(Array.isArray(o))return o.map(t=>typeof t=="object"?{id:t.value??t.id??t,relationTo:t.relationTo}:{id:t});if(typeof o=="object"){let t=o.value??o.id??o;if(typeof t=="string")return [{id:t,relationTo:o.relationTo}];if(Array.isArray(t))return t.map(s=>({id:s,relationTo:o.relationTo}))}return []}function W(o,t,s){if(!(!o||typeof o!="object")){for(let e of t)if(!(!e.name&&e.type!=="row"&&e.type!=="collapsible"&&e.type!=="tabs")){if(e.type==="relationship"||e.type==="upload")s(e,o);else if(e.type==="group"||e.type==="collapsible"||e.type==="row"){let r=e.name?o[e.name]:o;W(r,e.fields||[],s);}else if(e.type==="tabs"&&e.tabs){let r=e.name?o[e.name]:o;for(let i of e.tabs)W(r,i.fields||[],s);}else if(e.type==="array"&&e.name&&Array.isArray(o[e.name]))for(let r of o[e.name])W(r,e.fields||[],s);else if(e.type==="blocks"&&e.name&&Array.isArray(o[e.name]))for(let r of o[e.name]){if(!r||typeof r!="object")continue;let i=r.type||r.blockType;if(!i)continue;let u=e.blocks?.find(c=>c.slug===i);if(u&&Array.isArray(u.fields)){let c=r.data&&typeof r.data=="object"?r.data:r;W(c,u.fields,s);}}}}}function J(o,t,s){W(o,t,(e,r)=>{let i=r[e.name];if(!i)return;let u=Array.isArray(e.relationTo)?e.relationTo:[e.relationTo],c=Y(i);for(let a of c){if(!a.id)continue;let n=a.relationTo?[a.relationTo]:u;for(let l of n)l!=="*"&&(s.has(l)||s.set(l,new Set),s.get(l).add(a.id));}});}function Q(o,t,s){W(o,t,(e,r)=>{let i=r[e.name];if(!i)return;let u=Array.isArray(e.relationTo)?e.relationTo:[e.relationTo],c=n=>{r[e.name]=n;},a=(n,l)=>{let d=l?[l]:u;for(let y of d){let f=s.get(y);if(f&&f.has(n))return f.get(n)}return null};if(typeof i=="string"){let n=a(i);c(n||{id:i});}else if(Array.isArray(i))c(i.map(n=>{let l=typeof n=="object"?n.value??n.id:n,d=typeof n=="object"?n.relationTo:void 0,y=a(l,d);return y||{id:l}}));else if(typeof i=="object"){let n=i.value??i.id,l=i.relationTo,d=a(n,l);c(d||{id:n});}});}async function Z(o,t,s,e,r=1,i=0){if(!o||o.length===0||r>i)return;let u=new Map;for(let n of o)J(n,t,u);if(u.size===0)return;let c=new Map,a$1=new Map;for(let[n,l]of u.entries()){if(l.size===0||!e.getCollection(n))continue;let y=new Map,f=Array.from(l),p=[];for(let E of f){try{let v=(await s.find({collection:n,where:{id:{in:f}},limit:f.length,draft:!0}))?.docs||[];for(let A of v)A&&A.id&&(y.set(String(A.id),A),p.push(A));}catch{for(let b of f)try{let v=await s.findByID({collection:n,id:b,draft:!0});v&&(y.set(b,v),p.push(v));}catch{}}break}c.set(n,y),p.length>0&&a$1.set(n,p);}if(r<i)for(let[n,l]of a$1.entries()){let d=e.getCollection(n);d&&await Z(l,d.fields,s,e,r+1,i);}for(let n=0;n<o.length;n++)Q(o[n],t,c),o[n]=a(o[n]);}g();function M(o){return o==="read"?"read":o==="create"?"create":o==="update"?"update":"delete"}function ee(o,t){return {none:false,read:o==="read",create:o==="read"||o==="create",update:o==="read"||o==="create"||o==="update",delete:o==="read"||o==="create"||o==="update"||o==="delete",admin:true}[t]||false}async function Le(o,t,s,e={}){let{user:r,req:i,tenantId:u,apiKey:c}=s,{enablePublicAccess:a=true,defaultAccess:n="none"}=e,l=o.access?.[t];if(l){let y=await a$1(l,{req:i,user:r,tenantId:u});return y===false?{allowed:false,error:"Access denied",status:403}:typeof y=="object"?{allowed:true,extraWhere:y}:{allowed:true}}if(c?.permissions?.length>0){let y=o.slug,f=M(t),p=`${y}:${f}`;return !h(c.permissions,p)&&!h(c.permissions,`${y}:admin`)?{allowed:false,error:"Access denied: insufficient permissions",status:403}:{allowed:true}}if(r){let y=o.slug,f=M(t),p=`${y}:${f}`,E=a$2({id:r.id,email:r.email,role:r.role},p),b=a$2({id:r.id,email:r.email,role:r.role},`${y}:admin`);return E||b?{allowed:true}:{allowed:false,error:"Access denied: missing RBAC permission",status:403}}let d=ee(t,n);return a&&d?{allowed:true}:{allowed:false,error:"Authentication required",status:401}}async function $e(o,t,s,e={}){let{user:r,req:i,tenantId:u}=s,{enablePublicAccess:c=true}=e,a=o.access?.[t];if(a)return await a$1(a,{req:i,user:r,tenantId:u})===false?{allowed:false,error:"Access denied",status:403}:{allowed:true};if(r){let n=`globals:${t}`,l=a$2({id:r.id,email:r.email,role:r.role},n),d=a$2({id:r.id,email:r.email,role:r.role},"globals:admin");return l||d?{allowed:true}:{allowed:false,error:"Access denied: missing RBAC permission",status:403}}return c?{allowed:true}:{allowed:false,error:"Authentication required",status:401}}
|
|
3
3
|
export{Z as a,Le as b,$e as c,_ as d,G as e,k as f,w as g,P as h,x as i,U as j,I as k,H as l,z as m,O as n,X as o};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';var chunkVQ53TFYA_cjs=require('./chunk-VQ53TFYA.cjs'),chunkF4ITQ6XQ_cjs=require('./chunk-F4ITQ6XQ.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),crypto=require('crypto');chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();var w=class extends chunkVQ53TFYA_cjs.a{dialect="mongodb";client;db;database;connectionString;constructor(o){if(super(),o.connectionString){this.connectionString=o.connectionString;try{let e=new URL(o.connectionString);this.database=e.pathname.replace(/^\//,"")||"kyro_cms";}catch{this.database="kyro_cms";}}else this.client=o.client,this.database=o.database;}async connect(){if(this.connectionString&&!this.client){let o;try{let e=await import('./lib-5QYYN6ML.cjs');o=e.MongoClient??e.default?.MongoClient;}catch{chunkF4ITQ6XQ_cjs.a(["mongodb"]);let n=await import('./lib-5QYYN6ML.cjs');o=n.MongoClient??n.default?.MongoClient;}this.client=new o(this.connectionString),await this.client.connect();}this.db=this.client.db(this.database),this.connected=true;}async disconnect(){this.client&&(await this.client.close(),this.connected=false);}getMongoCollection(o){if(!this.db)throw new Error("MongoDB not connected");return this.db.collection(o)}async find(o){let{collection:e,where:n={},sort:s,limit:t=10,page:i=1,tenantId:r,select:a,draft:l}=o,d=this.getCollectionConfig(e),f=this.getMongoCollection(e),g={...n};this.tenantContext&&d.tenantScoped&&(g=chunkVQ53TFYA_cjs.c({where:g},e,this.tenantContext,chunkVQ53TFYA_cjs.b).where||{});let u=this.buildFilter(g,d.tenantScoped?r:void 0),c=d.fields.find(p=>p.name==="status"),h=c?.type==="select"&&Array.isArray(c.options)&&c.options.some(p=>p.value==="published");!l&&h&&(u.status="published");let y=this.parseSort(s),O={[y.field]:y.direction==="asc"?1:-1},$=(i-1)*t,[x,M]=await Promise.all([f.find(u).sort(O).skip($).limit(t).project(this.buildProjection(a)).toArray(),f.countDocuments(u)]),C=x.map(p=>this.processResult(p,d));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(C=C.filter(p=>chunkVQ53TFYA_cjs.d(p,e,this.tenantContext,chunkVQ53TFYA_cjs.b))),l&&(C=await Promise.all(C.map(async p=>{let m=await this.getMongoCollection(`${e}_versions`).findOne({document_id:p.id},{sort:{createdAt:-1}});if(m){let P=typeof m.data=="string"?JSON.parse(m.data):m.data&&typeof m.data=="object"?m.data:{};return {...p,...P,status:p.status}}return p}))),{docs:C,...this.calculatePagination(i,t,M)}}async findByID(o){let{collection:e,id:n,tenantId:s,draft:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e);if(this.tenantContext&&i.tenantScoped){let u={_id:n,tenantId:this.tenantContext.tenantId};if(!chunkVQ53TFYA_cjs.d(u,e,this.tenantContext,chunkVQ53TFYA_cjs.b))return null}let a={_id:n};s&&i.tenantScoped&&(a.tenantId=s);let l=i.fields.find(u=>u.name==="status"),d=l?.type==="select"&&Array.isArray(l.options)&&l.options.some(u=>u.value==="published");!t&&d&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let g=this.processResult(f,i);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:g.id},{sort:{createdAt:-1}});if(c){let h=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};g={...g,...h,status:g.status};}}return g}async create(o){let{collection:e,data:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r=this.prepareData(n,t),a=r.id||this.generateId();delete r.id;let l={...r,_id:a};return s&&t.tenantScoped&&(l.tenantId=s),await i.insertOne(l),this.processResult(l,t)}async update(o){let{collection:e,id:n,data:s,tenantId:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e),a={_id:n};t&&i.tenantScoped&&(a.tenantId=t);let l=this.prepareData(s,i),d=await r.findOneAndUpdate(a,{$set:l},{returnDocument:"after"});if(!d)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(d,i)}async delete(o){let{collection:e,id:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r={_id:n};s&&t.tenantScoped&&(r.tenantId=s);let a=await i.findOneAndDelete(r);if(!a)throw new Error(`Document not found: ${e}/${n}`);return this.processResult(a,t)}async count(o){let{collection:e,where:n={},tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(e),r=this.buildFilter(n,t.tenantScoped?s:void 0);return i.countDocuments(r)}async findOne(o){let{collection:e,where:n={},tenantId:s,draft:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(e),a=this.buildFilter(n,i.tenantScoped?s:void 0),l=i.fields.find(u=>u.name==="status"),d=l?.type==="select"&&Array.isArray(l.options)&&l.options.some(u=>u.value==="published");!t&&d&&(a.status="published");let f=await r.findOne(a);if(!f)return null;let g=this.processResult(f,i);if(t){let c=await this.getMongoCollection(`${e}_versions`).findOne({document_id:g.id},{sort:{createdAt:-1}});if(c){let h=typeof c.data=="string"?JSON.parse(c.data):c.data&&typeof c.data=="object"?c.data:{};g={...g,...h,status:g.status};}}return g}async findVersions(o){let{collection:e,documentId:n,sort:s,limit:t=10,page:i=1,tenantId:r}=o,a=this.getCollectionConfig(e),l=this.getMongoCollection(`${e}_versions`),d={document_id:n,autosave:{$ne:true}};r&&a.tenantScoped&&(d.tenant_id=r);let f=(i-1)*t,g=this.parseSort(s),u={[g.field]:g.direction==="asc"?1:-1},[c,h]=await Promise.all([l.find(d).sort(u).skip(f).limit(t).toArray(),l.countDocuments(d)]);return {docs:c.map(y=>this.processResult(y,{})),...this.calculatePagination(i,t,h)}}async findVersionByID(o){let{collection:e,versionId:n,tenantId:s}=o,t=this.getCollectionConfig(e),i=this.getMongoCollection(`${e}_versions`),r={_id:n};s&&t.tenantScoped&&(r.tenant_id=s);let a=await i.findOne(r);return a?this.processResult(a,{}):null}async createVersion(o){let{collection:e,documentId:n,data:s,status:t,createdBy:i,changeDescription:r,tenantId:a,autosave:l}=o,d=this.getCollectionConfig(e),f=this.getMongoCollection(`${e}_versions`);if(l){let c={document_id:n,collection_slug:e,autosave:true};a&&d.tenantScoped&&(c.tenant_id=a);let h=await f.findOne(c);if(h){let y=new Date().toISOString();return await f.updateOne({_id:h._id},{$set:{data:s,status:t,updatedAt:y}}),this.processResult({...h,data:s,status:t,updatedAt:y},{})}}let g=new Date().toISOString(),u={_id:this.generateId(),document_id:n,collection_slug:e,data:s,status:t,autosave:l===true,created_by:i,change_description:r,createdAt:g,updatedAt:g};if(a&&d.tenantScoped&&(u.tenant_id=a),await f.insertOne(u),!l){let c=this.getCollectionConfig(e);c.versions?.maxPerDoc&&await this.deleteVersions({collection:e,documentId:n,keepLatest:c.versions.maxPerDoc,tenantId:a});}return this.processResult(u,{})}async updateLatestVersion(o){return this.createVersion({...o,autosave:true})}async deleteVersions(o){let{collection:e,documentId:n,keepLatest:s,tenantId:t}=o,i=this.getCollectionConfig(e),r=this.getMongoCollection(`${e}_versions`);if(s){let a={document_id:n,autosave:{$ne:true}};t&&i.tenantScoped&&(a.tenant_id=t);let d=(await r.find(a).sort({createdAt:-1}).limit(s).project({_id:1}).toArray()).map(f=>f._id);d.length>0&&await r.deleteMany({document_id:n,autosave:{$ne:true},_id:{$nin:d},...t&&i.tenantScoped?{tenant_id:t}:{}});}else {let a={document_id:n};t&&i.tenantScoped&&(a.tenant_id=t),await r.deleteMany(a);}}async migrate(){for(let o of this.collections.values()){let e=this.getMongoCollection(o.slug);await e.createIndex({_id:1}),o.tenantScoped&&await e.createIndex({tenantId:1}),o.timestamps&&await e.createIndex({createdAt:-1});for(let n of o.fields)n.unique&&n.name&&await e.createIndex({[n.name]:1},{unique:true}),n.indexed&&n.name&&await e.createIndex({[n.name]:1});}}getCollectionConfig(o){if(o.startsWith("_globals_")){let n=o.replace("_globals_",""),s=this.globals.get(n);if(!s)throw new Error(`Global "${n}" not found`);return s}let e=this.collections.get(o);if(!e)throw new Error(`Collection "${o}" not found`);return e}buildFilter(o={},e){let n={};e&&(n.tenantId=e);for(let[s,t]of Object.entries(o))if(s==="AND"&&Array.isArray(t)){let i=t.map(r=>this.buildFilter(r));Object.assign(n,...i);}else if(s==="OR"&&Array.isArray(t))n.$or=t.map(i=>this.buildFilter(i));else if(typeof t=="object"&&t!==null&&!Array.isArray(t)){let i={};if(t.equals!==void 0){n[s==="id"?"_id":s]=t.equals;continue}t.not_equals!==void 0&&(i.$ne=t.not_equals),t.in!==void 0&&(i.$in=t.in),t.not_in!==void 0&&(i.$nin=t.not_in),t.greater_than!==void 0&&(i.$gt=t.greater_than),t.greater_than_equal!==void 0&&(i.$gte=t.greater_than_equal),t.less_than!==void 0&&(i.$lt=t.less_than),t.less_than_equal!==void 0&&(i.$lte=t.less_than_equal),t.like!==void 0&&(i.$regex=new RegExp(t.like.replace(/%/g,".*"),"i")),t.not_like!==void 0&&(i.$not=new RegExp(t.not_like.replace(/%/g,".*"),"i")),t.contains!==void 0&&(i.$regex=new RegExp(`.*${t.contains}.*`,"i")),t.exists!==void 0&&(i.$exists=t.exists),Object.keys(i).length>0&&(n[s==="id"?"_id":s]=i);}else n[s==="id"?"_id":s]=t;return n}buildProjection(o){if(!o||o.length===0)return;let e={_id:1};for(let n of o)e[n]=1;return e}processResult(o,e){if(!o)return null;let n={...o};for(let s of Object.keys(n))/^\d+$/.test(s)&&delete n[s];return o._id&&(n.id=o._id,delete n._id),delete n.__v,n.createdAt&&(n.createdAt=new Date(n.createdAt).toISOString()),n.updatedAt&&(n.updatedAt=new Date(n.updatedAt).toISOString()),chunkZOVH6QT5_cjs.a(n)}generateId(){let o=Date.now().toString(16).padStart(12,"0"),e=crypto.randomBytes(6).toString("hex");return o+e}};function V(v){return new w(v)}
|
|
2
|
+
exports.a=w;exports.b=V;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {h,a}from'./chunk-RTHJ6SS5.js';import {a as a$1}from'./chunk-TBHNE4VV.js';import {g}from'./chunk-Y2YAKDEQ.js';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
g();g();g();g();var Mi=Object.freeze({major:16,minor:14,patch:2,preReleaseTag:null});g();function F(e,t){throw new Error(t)}g();g();g();g();function ae(e){return typeof e=="object"&&e!==null}g();g();function W(e,t){throw new Error(t??"Unexpected invariant triggered.")}var ji=/\r\n|[\n\r]/g;function Xe(e,t){let n=0,r=1;for(let i of e.body.matchAll(ji)){if(typeof i.index=="number"||W(),i.index>=t)break;n=i.index+i[0].length,r+=1;}return {line:r,column:t+1-n}}g();function wn(e){return Yt(e.source,Xe(e.source,e.start))}function Yt(e,t){let n=e.locationOffset.column-1,r="".padStart(n)+e.body,i=t.line-1,s=e.locationOffset.line-1,o=t.line+s,a=t.line===1?n:0,p=t.column+a,c=`${e.name}:${o}:${p}
|
|
3
3
|
`,f=r.split(/\r\n|[\n\r]/g),d=f[i];if(d.length>120){let h=Math.floor(p/80),v=p%80,g=[];for(let A=0;A<d.length;A+=80)g.push(d.slice(A,A+80));return c+Jr([[`${o} |`,g[0]],...g.slice(1,h+1).map(A=>["|",A]),["|","^".padStart(v)],["|",g[h+1]]])}return c+Jr([[`${o-1} |`,f[i-1]],[`${o} |`,d],["|","^".padStart(p)],[`${o+1} |`,f[i+1]]])}function Jr(e){let t=e.filter(([r,i])=>i!==void 0),n=Math.max(...t.map(([r])=>r.length));return t.map(([r,i])=>r.padStart(n)+(i?" "+i:"")).join(`
|
|
4
4
|
`)}function Gi(e){let t=e[0];return t==null||"kind"in t||"length"in t?{nodes:t,source:e[1],positions:e[2],path:e[3],originalError:e[4],extensions:e[5]}:t}var m=class e extends Error{constructor(t,...n){var r,i,s;let{nodes:o,source:a,positions:p,path:c,originalError:f,extensions:d}=Gi(n);super(t),this.name="GraphQLError",this.path=c??void 0,this.originalError=f??void 0,this.nodes=Xr(Array.isArray(o)?o:o?[o]:void 0);let h=Xr((r=this.nodes)===null||r===void 0?void 0:r.map(g=>g.loc).filter(g=>g!=null));this.source=a??(h==null||(i=h[0])===null||i===void 0?void 0:i.source),this.positions=p??h?.map(g=>g.start),this.locations=p&&a?p.map(g=>Xe(a,g)):h?.map(g=>Xe(g.source,g.start));let v=ae(f?.extensions)?f?.extensions:void 0;this.extensions=(s=d??v)!==null&&s!==void 0?s:Object.create(null),Object.defineProperties(this,{message:{writable:true,enumerable:true},name:{enumerable:false},nodes:{enumerable:false},source:{enumerable:false},positions:{enumerable:false},originalError:{enumerable:false}}),f!=null&&f.stack?Object.defineProperty(this,"stack",{value:f.stack,writable:true,configurable:true}):Error.captureStackTrace?Error.captureStackTrace(this,e):Object.defineProperty(this,"stack",{value:Error().stack,writable:true,configurable:true});}get[Symbol.toStringTag](){return "GraphQLError"}toString(){let t=this.message;if(this.nodes)for(let n of this.nodes)n.loc&&(t+=`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {c as c$1}from'./chunk-7MNDQU6K.js';import {c,g,e}from'./chunk-Y2YAKDEQ.js';import {URL as URL$1,URLSearchParams as URLSearchParams$1}from'url';import Ip from'fs';import Rp from'path';import SR,{webcrypto}from'crypto';import {Buffer as Buffer$1,Blob}from'buffer';import {TextEncoder,TextDecoder as TextDecoder$1}from'util';import Fl from'stream';import {ReadableStream}from'stream/web';import Yx,{Script}from'vm';import {isIP}from'net';import BD from'http';import VD from'https';import Jp from'zlib';import sF from'child_process';import {PerformanceObserver,PerformanceEntry}from'perf_hooks';if (typeof window === "undefined") { const { createRequire } = await import(/* @vite-ignore */ 'module'); createRequire(import.meta.url); }
|
|
2
2
|
var vk=c((u6,Ek)=>{g();function bO(o){return o.toString("ascii",0,2)==="BM"}function gO(o){return {width:o.readUInt32LE(18),height:Math.abs(o.readInt32LE(22))}}Ek.exports={detect:bO,calculate:gO};});var wx=c((p6,kk)=>{g();var SO=1,PO=6,AO=16;function wO(o){var t;return o.readUInt16LE(0)!==0?false:(t=o.readUInt16LE(2),t===SO)}function Tk(o,t){var e=o.readUInt8(t);return e===0?256:e}function Ck(o,t){var e=PO+t*AO;return {width:Tk(o,e),height:Tk(o,e+1)}}function xO(o){var t=o.readUInt16LE(4),e=Ck(o,0),r;if(t===1)return e;for(e.images=[{width:e.width,height:e.height}],r=1;r<t;r+=1)e.images.push(Ck(o,r));return e}kk.exports={detect:wO,calculate:xO};});var Lk=c((h6,Nk)=>{g();var EO=2;function vO(o){var t;return o.readUInt16LE(0)!==0?false:(t=o.readUInt16LE(2),t===EO)}Nk.exports={detect:vO,calculate:wx().calculate};});var Ik=c((d6,Mk)=>{g();function TO(o){return o.readUInt32LE(0)===542327876}function CO(o){return {height:o.readUInt32LE(12),width:o.readUInt32LE(16)}}Mk.exports={detect:TO,calculate:CO};});var Dk=c((b6,Rk)=>{g();var kO=/^GIF8[79]a/;function NO(o){var t=o.toString("ascii",0,6);return kO.test(t)}function LO(o){return {width:o.readUInt16LE(6),height:o.readUInt16LE(8)}}Rk.exports={detect:NO,calculate:LO};});var Fk=c((S6,Ok)=>{g();function MO(o){var t=o.toString("hex",0,2);return t==="ffd8"}function IO(o,t){return {height:o.readUInt16BE(t),width:o.readUInt16BE(t+2)}}function RO(o,t){if(t>o.length)throw new TypeError("Corrupt JPG, exceeded buffer limits");if(o[t]!==255)throw new TypeError("Invalid JPG, marker table corrupted")}function DO(o){o=o.slice(4);for(var t,e;o.length;){if(t=o.readUInt16BE(0),RO(o,t),e=o[t+1],e===192||e===193||e===194)return IO(o,t+5);o=o.slice(t+2);}throw new TypeError("Invalid JPG, no size found")}Ok.exports={detect:MO,calculate:DO};});var Hk=c((A6,Vk)=>{g();var OO=`PNG\r
|
|
3
3
|
|
|
4
4
|
`,FO="IHDR",Bk="CgBI";function BO(o){if(OO===o.toString("ascii",1,8)){var t=o.toString("ascii",12,16);if(t===Bk&&(t=o.toString("ascii",28,32)),t!==FO)throw new TypeError("invalid png");return true}}function VO(o){return o.toString("ascii",12,16)===Bk?{width:o.readUInt32BE(32),height:o.readUInt32BE(36)}:{width:o.readUInt32BE(16),height:o.readUInt32BE(20)}}Vk.exports={detect:BO,calculate:VO};});var Uk=c((x6,Gk)=>{g();function HO(o){return o.toString("ascii",0,4)==="8BPS"}function GO(o){return {width:o.readUInt32BE(18),height:o.readUInt32BE(14)}}Gk.exports={detect:HO,calculate:GO};});var zk=c((v6,Wk)=>{g();var UO=/<svg[^>]+[^>]*>/;function WO(o){return UO.test(o)}var HS={root:/<svg\s[^>]+>/,width:/\bwidth=(['"])([^%]+?)\1/,height:/\bheight=(['"])([^%]+?)\1/,viewbox:/\bviewBox=(['"])(.+?)\1/};function zO(o){var t=o.split(" ");return {width:parseInt(t[2],10),height:parseInt(t[3],10)}}function _O(o){var t=o.match(HS.width),e=o.match(HS.height),r=o.match(HS.viewbox);return {width:t&&parseInt(t[2],10),height:e&&parseInt(e[2],10),viewbox:r&&zO(r[2])}}function $O(o){return {width:o.width,height:o.height}}function KO(o){var t=o.viewbox.width/o.viewbox.height;return o.width?{width:o.width,height:Math.floor(o.width/t)}:o.height?{width:Math.floor(o.height*t),height:o.height}:{width:o.viewbox.width,height:o.viewbox.height}}function jO(o){var t=o.toString("utf8").match(HS.root);if(t){var e=_O(t[0]);if(e.width&&e.height)return $O(e);if(e.viewbox)return KO(e)}throw new TypeError("invalid svg")}Wk.exports={detect:WO,calculate:jO};});var $k=c((C6,_k)=>{g();function qO(o){var t=o.toString("ascii",0,4)==="RIFF",e=o.toString("ascii",8,12)==="WEBP",r=o.toString("ascii",12,15)==="VP8";return t&&e&&r}function YO(o){var t=o.toString("ascii",12,16);if(o=o.slice(20,30),t==="VP8X"){var e=o[0],r=(e&192)===0,n=(e&1)===0;return r&&n?QO(o):false}if(t==="VP8 "&&o[0]!==47)return XO(o);var i=o.toString("hex",3,6);return t==="VP8L"&&i!=="9d012a"?JO(o):false}function QO(o){return {width:1+o.readUIntLE(4,3),height:1+o.readUIntLE(7,3)}}function JO(o){return {width:1+((o[2]&63)<<8|o[1]),height:1+((o[4]&15)<<10|o[3]<<2|(o[2]&192)>>6)}}function XO(o){return {width:o.readInt16LE(6)&16383,height:o.readInt16LE(8)&16383}}_k.exports={detect:qO,calculate:YO};});var xx=c((N6,Kk)=>{g();var ZO={bmp:vk(),cur:Lk(),dds:Ik(),gif:Dk(),ico:wx(),jpg:Fk(),png:Hk(),psd:Uk(),svg:zk(),webp:$k()};Kk.exports=ZO;});var Yk=c((M6,qk)=>{g();var jk=xx();qk.exports=function(o){var t,e;for(t in jk)if(e=jk[t].detect(o),e)return t};});var Qk=c((R6,vx)=>{g();var Ex=xx(),tF=Yk();function eF(o){var t=tF(o);if(t in Ex){var e=Ex[t].calculate(o);if(e!==false)return e.type=t,e}throw new TypeError("unsupported file type: "+t)}vx.exports=function(o){if(Buffer.isBuffer(o))return eF(o);throw new TypeError("expecting only a buffer as input")};vx.exports.types=Object.keys(Ex);});var Rf=c(wu=>{g();wu.removeLeadingAndTrailingHTTPWhitespace=o=>o.replace(/^[ \t\n\r]+/u,"").replace(/[ \t\n\r]+$/u,"");wu.removeTrailingHTTPWhitespace=o=>o.replace(/[ \t\n\r]+$/u,"");wu.isHTTPWhitespaceChar=o=>o===" "||o===" "||o===`
|