@kyro-cms/core 0.12.44 → 0.12.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{WebhookService-C19xR8qE.d.ts → WebhookService-CZf_na-J.d.ts} +1 -1
- package/dist/{WebhookService-BBcCHBo8.d.cts → WebhookService-DgIx21X-.d.cts} +1 -1
- package/dist/api-handler-graphql.cjs +1 -1
- package/dist/api-handler-graphql.js +2 -1
- package/dist/api-handler-trpc.cjs +1 -1
- package/dist/api-handler-trpc.js +2 -1
- package/dist/api-handler.cjs +1 -1
- package/dist/api-handler.js +1 -1
- package/dist/{base-yXdYZxFK.d.ts → base-7vJMzr4V.d.ts} +1 -1
- package/dist/{base-C2iwjdJQ.d.cts → base-DDEmdRqV.d.cts} +1 -1
- package/dist/bcryptjs-AZA6WEN2.js +2 -0
- package/dist/bcryptjs-WIQSWJGK.cjs +1 -0
- package/dist/better-sqlite3-42Q3FG3E.js +2 -0
- package/dist/better-sqlite3-5IISPX34.cjs +1 -0
- package/dist/bootstrap-7CI3NVSY.js +1 -0
- package/dist/bootstrap-DOOM2CNQ.cjs +1 -0
- package/dist/bowser-FI5JQGKZ.js +11 -0
- package/dist/bowser-VX6B6ZSE.cjs +10 -0
- package/dist/chokidar-24HVS6XD.cjs +5 -0
- package/dist/chokidar-43DT7CVN.js +6 -0
- package/dist/chunk-227MEHYX.cjs +269 -0
- package/dist/chunk-26Q7JXM4.cjs +3 -0
- package/dist/chunk-2BUODBE2.js +2 -0
- package/dist/chunk-2WFTETFB.js +2 -0
- package/dist/chunk-35PGCW3S.cjs +1 -0
- package/dist/chunk-3VXEK5ZW.cjs +1 -0
- package/dist/chunk-45TJAB5X.js +301 -0
- package/dist/chunk-5DWYVUQR.cjs +1 -0
- package/dist/chunk-5LPNEYK5.cjs +1 -0
- package/dist/chunk-66BJXVFJ.js +2 -0
- package/dist/chunk-6KRR7YHA.js +2 -0
- package/dist/chunk-6KUL2BSA.cjs +133 -0
- package/dist/chunk-6MSS5X77.js +2 -0
- package/dist/chunk-6QWLXJ7L.js +2 -0
- package/dist/chunk-73D2PNHD.cjs +7 -0
- package/dist/chunk-7ACHOBWY.cjs +13 -0
- package/dist/chunk-7AQSH3KR.js +2 -0
- package/dist/chunk-7GGZA5YU.cjs +2 -0
- package/dist/chunk-7I6URA6F.js +4 -0
- package/dist/chunk-7JWQ2PZP.cjs +1 -0
- package/dist/chunk-7T35572E.js +75 -0
- package/dist/chunk-7V67ONUD.js +4 -0
- package/dist/chunk-7WMMKGEO.cjs +1 -0
- package/dist/chunk-A73AVVFR.js +11 -0
- package/dist/chunk-AK754S3T.cjs +2 -0
- package/dist/chunk-AMGJ5AFH.cjs +1 -0
- package/dist/chunk-ATBH763U.js +2 -0
- package/dist/chunk-B3GDQ7UI.cjs +114 -0
- package/dist/chunk-BAVN7VDR.cjs +1 -0
- package/dist/chunk-BCEE4NBZ.cjs +2 -0
- package/dist/{chunk-J4252I5B.cjs → chunk-BHR7OAU4.cjs} +4 -4
- package/dist/chunk-BLH2MRK4.js +2 -0
- package/dist/chunk-BPMA2ECA.js +10 -0
- package/dist/chunk-BUNLC3II.cjs +1 -0
- package/dist/chunk-C2PXMVR5.js +2 -0
- package/dist/chunk-CAJ4ZJO6.cjs +1 -0
- package/dist/chunk-CGPAS4U5.js +4 -0
- package/dist/chunk-DS5DE5BU.js +2 -0
- package/dist/chunk-DT3LHRQT.js +57 -0
- package/dist/chunk-DUO523BH.cjs +1 -0
- package/dist/chunk-DVWYO3KK.cjs +1 -0
- package/dist/chunk-E27KEZPT.js +2 -0
- package/dist/chunk-EHWUALGH.cjs +1 -0
- package/dist/chunk-EN65ZEK2.cjs +2 -0
- package/dist/chunk-EOOZDOL7.js +3 -0
- package/dist/chunk-EZIDQBXI.cjs +1 -0
- package/dist/chunk-F4ITQ6XQ.cjs +3 -0
- package/dist/chunk-GIS6X43A.cjs +3 -0
- package/dist/chunk-GNEVCEJU.cjs +3 -0
- package/dist/chunk-GNOSG3PK.cjs +1 -0
- package/dist/chunk-HLAEJB5R.js +384 -0
- package/dist/chunk-HPYH7GTS.cjs +1 -0
- package/dist/chunk-HT44I66C.js +24 -0
- package/dist/chunk-HTYVI2HK.cjs +9 -0
- package/dist/chunk-ICVQWR2A.js +2 -0
- package/dist/chunk-IP6JUEH3.js +3 -0
- package/dist/chunk-IPXOY4RI.js +2 -0
- package/dist/chunk-IUAWDAUD.cjs +56 -0
- package/dist/chunk-J6U5LWZ7.js +11 -0
- package/dist/{chunk-UHFDH3PG.js → chunk-JT36FTHY.cjs} +4 -4
- package/dist/chunk-JUJZOG6P.js +2 -0
- package/dist/{chunk-2BTRHVT3.cjs → chunk-K7YNEKVE.js} +5 -4
- package/dist/chunk-KCHPADCH.cjs +7 -0
- package/dist/chunk-KH7LM52S.js +3 -0
- package/dist/chunk-LEBM6ZSZ.cjs +10 -0
- package/dist/chunk-LQ3YZTPU.cjs +15 -0
- package/dist/chunk-LY7N3UHH.cjs +23 -0
- package/dist/chunk-MCZ3YZ2L.js +2 -0
- package/dist/chunk-MP5VC5ER.cjs +1 -0
- package/dist/chunk-MVX2PYJJ.cjs +1 -0
- package/dist/chunk-MY42EWZP.js +2 -0
- package/dist/chunk-MZOWPV4D.js +20 -0
- package/dist/chunk-NGNJSUGL.cjs +1 -0
- package/dist/chunk-NWCREF47.js +3 -0
- package/dist/chunk-OMWQVPV7.js +14 -0
- package/dist/chunk-ORG67NXX.js +3 -0
- package/dist/chunk-OSAVAYJZ.js +16 -0
- package/dist/chunk-P7XYIKL6.cjs +300 -0
- package/dist/chunk-PBOZJOKN.js +2 -0
- package/dist/chunk-PITMDQYN.cjs +18 -0
- package/dist/chunk-PL5AIE6F.js +2 -0
- package/dist/chunk-PTWQQMWW.js +270 -0
- package/dist/chunk-QC4YXUBT.cjs +383 -0
- package/dist/chunk-QDHP5E4P.cjs +2 -0
- package/dist/chunk-QVDY6S4B.js +2 -0
- package/dist/chunk-QYI3GOHF.cjs +1 -0
- package/dist/chunk-R3NEPC4I.js +3 -0
- package/dist/chunk-R4LXRAMX.js +2 -0
- package/dist/chunk-S5HTTLN7.cjs +2 -0
- package/dist/chunk-STX5V7HG.cjs +20 -0
- package/dist/chunk-SVYUTQVE.js +115 -0
- package/dist/chunk-SYEP5QLG.js +19 -0
- package/dist/chunk-TR3ZS3T3.js +3 -0
- package/dist/chunk-UB5TJHQR.js +2 -0
- package/dist/chunk-UD6ZPO7T.js +2 -0
- package/dist/chunk-UNYXWPLZ.cjs +2 -0
- package/dist/chunk-VBPAAQEF.js +2 -0
- package/dist/chunk-VIUU4D5I.js +2 -0
- package/dist/chunk-VJ2WMKPK.js +21 -0
- package/dist/chunk-VOQUO2EZ.cjs +74 -0
- package/dist/chunk-VQ53TFYA.cjs +1 -0
- package/dist/chunk-VRZC4TTF.cjs +1 -0
- package/dist/chunk-W46LZ4MY.js +2 -0
- package/dist/chunk-WCFHS7EZ.cjs +1 -0
- package/dist/chunk-WGESLAWV.js +8 -0
- package/dist/chunk-WSP7PSXC.js +8 -0
- package/dist/chunk-X54XZACS.cjs +10 -0
- package/dist/{chunk-Q2UYCYKV.js → chunk-XBH4YMC7.js} +5 -4
- package/dist/chunk-XDE7CFV6.cjs +19 -0
- package/dist/chunk-XOACKBG7.js +4 -0
- package/dist/chunk-XPPVX4GQ.cjs +1 -0
- package/dist/chunk-ZJE3VAAW.js +134 -0
- package/dist/chunk-ZO3YB5DK.cjs +1 -0
- package/dist/chunk-ZOVH6QT5.cjs +1 -0
- package/dist/cli/index.cjs +197 -78
- package/dist/cli/index.js +198 -78
- package/dist/client.cjs +1 -1
- package/dist/client.d.cts +1 -1
- package/dist/client.d.ts +1 -1
- package/dist/client.js +2 -1
- package/dist/d1-5ZQJOFDX.cjs +1 -0
- package/dist/d1-VPH75GI2.js +2 -0
- package/dist/dist-es-3SSNUZST.cjs +1 -0
- package/dist/dist-es-6SVFVYN3.js +1 -0
- package/dist/dist-es-6TQTDPE7.js +2 -0
- package/dist/dist-es-A5OF2STN.cjs +2 -0
- package/dist/dist-es-BOW5V247.cjs +6 -0
- package/dist/dist-es-CRIMATLL.cjs +2 -0
- package/dist/dist-es-DL3VLVP6.cjs +1 -0
- package/dist/dist-es-EMUQ6ZNZ.js +3 -0
- package/dist/dist-es-MNIQZC4U.js +2 -0
- package/dist/dist-es-P25IKLBI.cjs +1 -0
- package/dist/dist-es-SJ76GYCI.js +2 -0
- package/dist/dist-es-SRPWSAF4.cjs +1 -0
- package/dist/dist-es-T2H2W5BX.cjs +3 -0
- package/dist/dist-es-TX4DBXEW.js +3 -0
- package/dist/dist-es-U4ZB3ZDA.js +7 -0
- package/dist/dist-es-XZBHIIKY.js +4 -0
- package/dist/drizzle/index.cjs +1 -1
- package/dist/drizzle/index.d.cts +2 -2
- package/dist/drizzle/index.d.ts +2 -2
- package/dist/drizzle/index.js +1 -1
- package/dist/drizzle-orm-47ELDEM6.cjs +1 -0
- package/dist/drizzle-orm-7YTX5NTT.js +1 -0
- package/dist/event-streams-25YJ2Z6R.js +1 -0
- package/dist/event-streams-JBMWCI2O.cjs +1 -0
- package/dist/fields/index.cjs +1 -1
- package/dist/fields/index.js +1 -1
- package/dist/fs-DGKZLRM6.cjs +1 -0
- package/dist/fs-YZJ5FM6J.js +2 -0
- package/dist/graphql/index.cjs +1 -1
- package/dist/graphql/index.d.cts +2 -2
- package/dist/graphql/index.d.ts +2 -2
- package/dist/graphql/index.js +1 -1
- package/dist/{index-DTz6u7w9.d.cts → index-BJ1rwHxk.d.cts} +1 -1
- package/dist/{index-BeQtbl3z.d.ts → index-BTjlptCL.d.ts} +1 -1
- package/dist/index.cjs +28 -46
- package/dist/index.d.cts +23 -9
- package/dist/index.d.ts +23 -9
- package/dist/index.js +29 -46
- package/dist/integration.cjs +1 -1
- package/dist/integration.js +1 -1
- package/dist/jsonwebtoken-DFB6ZBZA.cjs +8 -0
- package/dist/jsonwebtoken-S7BG2YWK.js +9 -0
- package/dist/lib-5QYYN6ML.cjs +12 -0
- package/dist/lib-IYW32OER.js +13 -0
- package/dist/loadSso-JY4WDQPS.cjs +2 -0
- package/dist/loadSso-YTG2GQGW.js +3 -0
- package/dist/local-VDCSEMC2.js +1 -0
- package/dist/local-YCWBUF3R.cjs +1 -0
- package/dist/media-3Z6YW5J4.cjs +1 -0
- package/dist/media-HK2IZMUZ.js +1 -0
- package/dist/mongo-auth-adapter-7K64Y2QM.cjs +1 -0
- package/dist/mongo-auth-adapter-BUKINEZL.js +1 -0
- package/dist/mongodb/index.cjs +1 -1
- package/dist/mongodb/index.d.cts +2 -2
- package/dist/mongodb/index.d.ts +2 -2
- package/dist/mongodb/index.js +1 -1
- package/dist/nodemailer-AXROO37D.js +54 -0
- package/dist/nodemailer-IDML4L6W.cjs +53 -0
- package/dist/postgres-auth-adapter-2M4RNEY3.cjs +1 -0
- package/dist/postgres-auth-adapter-MKSHIJDL.js +1 -0
- package/dist/postgres-js-3Y54EXVQ.cjs +1 -0
- package/dist/postgres-js-INQPBHJP.js +1 -0
- package/dist/redis-adapter-EGMUN65D.cjs +1 -0
- package/dist/redis-adapter-SXOXLHNH.js +1 -0
- package/dist/rest/index.cjs +1 -1
- package/dist/rest/index.d.cts +5 -5
- package/dist/rest/index.d.ts +5 -5
- package/dist/rest/index.js +1 -1
- package/dist/schema-RT6WSUYC.cjs +1 -0
- package/dist/schema-XC5ISGNR.js +2 -0
- package/dist/signin-KZBIAHGS.js +3 -0
- package/dist/signin-VFBLX7EL.cjs +2 -0
- package/dist/sqlite-adapter-DV7ZX2EJ.js +1 -0
- package/dist/sqlite-adapter-ZTABLT2X.cjs +1 -0
- package/dist/src-6LAUXXDM.cjs +1 -0
- package/dist/src-GZRZ4VAO.js +1 -0
- package/dist/sso-oidc-54BIRYR6.cjs +2 -0
- package/dist/sso-oidc-SX5OIQGG.js +3 -0
- package/dist/sts-HVGDJYIF.js +3 -0
- package/dist/sts-YLXXIB3X.cjs +2 -0
- package/dist/templates/index.cjs +1 -1
- package/dist/templates/index.d.cts +1 -1
- package/dist/templates/index.d.ts +1 -1
- package/dist/templates/index.js +1 -1
- package/dist/trpc/index.cjs +1 -1
- package/dist/trpc/index.d.cts +7 -7
- package/dist/trpc/index.d.ts +7 -7
- package/dist/trpc/index.js +1 -1
- package/dist/{types-CaXXmV9h.d.ts → types-CYGXsNcJ.d.ts} +5 -5
- package/dist/{types-BjivdGbU.d.cts → types-DOKMyC3y.d.cts} +5 -5
- package/dist/ws/index.cjs +1 -1
- package/dist/ws/index.js +1 -1
- package/package.json +2 -2
- package/dist/bootstrap-ROSTPMVL.js +0 -1
- package/dist/bootstrap-WW5NJ6EB.cjs +0 -1
- package/dist/chunk-3CVLI5C5.cjs +0 -3
- package/dist/chunk-3Q2WUG63.cjs +0 -2
- package/dist/chunk-3RSMK4DA.cjs +0 -2
- package/dist/chunk-4IGWJMBY.cjs +0 -2
- package/dist/chunk-4ORJMSJU.cjs +0 -1
- package/dist/chunk-4RMFCTWH.js +0 -1
- package/dist/chunk-5B6X2GBJ.js +0 -2
- package/dist/chunk-5J6HXUF6.js +0 -1
- package/dist/chunk-5KOQYQEE.js +0 -1
- package/dist/chunk-5SEHX7ON.js +0 -1
- package/dist/chunk-6ROHVUXF.js +0 -1
- package/dist/chunk-6SPPR5JZ.js +0 -3
- package/dist/chunk-7IVN6TTY.js +0 -133
- package/dist/chunk-AHSFSERC.cjs +0 -1
- package/dist/chunk-B5XWYVWK.js +0 -1
- package/dist/chunk-BGX27ZRG.cjs +0 -300
- package/dist/chunk-C2W5PSHC.js +0 -300
- package/dist/chunk-CCUQZ66T.cjs +0 -133
- package/dist/chunk-D5P2IPGX.cjs +0 -3
- package/dist/chunk-EPMGPNBE.js +0 -1
- package/dist/chunk-FHJJKFAU.cjs +0 -1
- package/dist/chunk-FVZ5RFLO.js +0 -2
- package/dist/chunk-FZ6Q2EBJ.cjs +0 -20
- package/dist/chunk-G3J2EU5D.cjs +0 -1
- package/dist/chunk-G7SSHELM.cjs +0 -1
- package/dist/chunk-GKYEJ2UF.js +0 -1
- package/dist/chunk-GO34AOBZ.cjs +0 -1
- package/dist/chunk-GYQMNXXW.cjs +0 -114
- package/dist/chunk-HLSB2MCK.js +0 -1
- package/dist/chunk-HQP2Y7QQ.js +0 -251
- package/dist/chunk-HS2KNFAB.cjs +0 -2
- package/dist/chunk-HVXO3OFB.cjs +0 -1
- package/dist/chunk-IETGL7WJ.js +0 -1
- package/dist/chunk-IFJ73O3A.cjs +0 -1
- package/dist/chunk-ILEZ3NYX.cjs +0 -2
- package/dist/chunk-INB4LNA6.js +0 -90
- package/dist/chunk-K6WUOU6P.js +0 -1
- package/dist/chunk-KD7LUCFY.cjs +0 -1
- package/dist/chunk-KDNYHLD2.js +0 -1
- package/dist/chunk-LHW4R367.js +0 -1
- package/dist/chunk-MIOMMB23.cjs +0 -1
- package/dist/chunk-N5VNHUJS.cjs +0 -4
- package/dist/chunk-NRLIGDYF.js +0 -1
- package/dist/chunk-NY47CFVP.cjs +0 -1
- package/dist/chunk-NZJAGASC.cjs +0 -251
- package/dist/chunk-OG7CNQGU.js +0 -1
- package/dist/chunk-PP5S2UBV.js +0 -0
- package/dist/chunk-PP7W5UKL.js +0 -2
- package/dist/chunk-Q3Q7BJVQ.cjs +0 -1
- package/dist/chunk-QCA3AP3M.cjs +0 -1
- package/dist/chunk-QOCHBPMK.js +0 -2
- package/dist/chunk-QYFU5Y7S.js +0 -3
- package/dist/chunk-RHCWCG3O.js +0 -114
- package/dist/chunk-SK2Q4PRV.cjs +0 -90
- package/dist/chunk-TFBHE5FF.cjs +0 -1
- package/dist/chunk-UBRYJP2G.js +0 -1
- package/dist/chunk-V65NPSR5.cjs +0 -1
- package/dist/chunk-VGQ4VUG6.js +0 -2
- package/dist/chunk-W7C6SJXZ.js +0 -20
- package/dist/chunk-WIZ6C5QZ.cjs +0 -1
- package/dist/chunk-ZIWJJRWQ.js +0 -4
- package/dist/chunk-ZUVP4UK7.cjs +0 -1
- package/dist/media-L5XDD47D.js +0 -1
- package/dist/media-OUBQTIQP.cjs +0 -1
- package/dist/mongo-auth-adapter-5TJO5J5U.js +0 -1
- package/dist/mongo-auth-adapter-JVE5M3S4.cjs +0 -1
- package/dist/postgres-auth-adapter-33QOIRXT.js +0 -1
- package/dist/postgres-auth-adapter-JKDYYULH.cjs +0 -1
- package/dist/redis-adapter-NN3H4GRX.js +0 -1
- package/dist/redis-adapter-OUKQGYCH.cjs +0 -1
- package/dist/schema-HIUSHSUI.cjs +0 -1
- package/dist/schema-KFYUM674.js +0 -1
- package/dist/sqlite-adapter-GTTVSXRV.cjs +0 -1
- package/dist/sqlite-adapter-UPANATIW.js +0 -1
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import {createRequire}from'module';import {a as a$1}from'./chunk-HT44I66C.js';import {c,a as a$2,b,d as d$2,e}from'./chunk-VBPAAQEF.js';import {i,$,T,Y,f,R as R$1,h,g as g$2,S as S$1,X as X$1,p,n,P,j,Q,d as d$1,aa as aa$1,k as k$1,l as l$1,Z as Z$1}from'./chunk-IP6JUEH3.js';import {U,a,k,R,Z,X,c as c$1,A,i as i$1,N,l,t,S,qa,m,J,g as g$1,d,v,H as H$1,ea,da,ga,ja,ka,la,aa,ba,na,w,M,Q as Q$1,j as j$1,V,T as T$1,n as n$1}from'./chunk-7AQSH3KR.js';import {g}from'./chunk-C2PXMVR5.js';createRequire(import.meta.url);
|
|
2
|
+
g();g();g();g();g();g();g();g();var ee=class extends N{static[a]="PgViewBase"};var H=class{static[a]="PgDialect";casing;constructor(e){this.casing=new b(e?.casing);}async migrate(e,t,i){let s=typeof i=="string"?"__drizzle_migrations":i.migrationsTable??"__drizzle_migrations",n=typeof i=="string"?"drizzle":i.migrationsSchema??"drizzle",o=J`
|
|
3
|
+
CREATE TABLE IF NOT EXISTS ${J.identifier(n)}.${J.identifier(s)} (
|
|
4
|
+
id SERIAL PRIMARY KEY,
|
|
5
|
+
hash text NOT NULL,
|
|
6
|
+
created_at bigint
|
|
7
|
+
)
|
|
8
|
+
`;await t.execute(J`CREATE SCHEMA IF NOT EXISTS ${J.identifier(n)}`),await t.execute(o);let h=(await t.all(J`select id, hash, created_at from ${J.identifier(n)}.${J.identifier(s)} order by created_at desc limit 1`))[0];await t.transaction(async u=>{for await(let d of e)if(!h||Number(h.created_at)<d.folderMillis){for(let w of d.sql)await u.execute(J.raw(w));await u.execute(J`insert into ${J.identifier(n)}.${J.identifier(s)} ("hash", "created_at") values(${d.hash}, ${d.folderMillis})`);}});}escapeName(e){return `"${e}"`}escapeParam(e){return `$${e+1}`}escapeString(e){return `'${e.replace(/'/g,"''")}'`}buildWithCTE(e){if(!e?.length)return;let t=[J`with `];for(let[i,s]of e.entries())t.push(J`${J.identifier(s._.alias)} as (${s._.sql})`),i<e.length-1&&t.push(J`, `);return t.push(J` `),J.join(t)}buildDeleteQuery({table:e,where:t,returning:i,withList:s}){let n=this.buildWithCTE(s),o=i?J` returning ${this.buildSelection(i,{isSingleTable:true})}`:void 0,a=t?J` where ${t}`:void 0;return J`${n}delete from ${e}${a}${o}`}buildUpdateSet(e,t$1){let i=e[t.Symbol.Columns],s=Object.keys(i).filter(o=>t$1[o]!==void 0||i[o]?.onUpdateFn!==void 0),n=s.length;return J.join(s.flatMap((o,a)=>{let h=i[o],u=t$1[o]??J.param(h.onUpdateFn(),h),d=J`${J.identifier(this.casing.getColumnCasing(h))} = ${u}`;return a<n-1?[d,J.raw(", ")]:[d]}))}buildUpdateQuery({table:e,set:t,where:i,returning:s,withList:n,from:o,joins:a}){let h=this.buildWithCTE(n),u=e[qa.Symbol.Name],d=e[qa.Symbol.Schema],w=e[qa.Symbol.OriginalName],$=u===w?void 0:u,x=J`${d?J`${J.identifier(d)}.`:void 0}${J.identifier(w)}${$&&J` ${J.identifier($)}`}`,q=this.buildUpdateSet(e,t),N=o&&J.join([J.raw(" from "),this.buildFromTable(o)]),C=this.buildJoins(a),y=s?J` returning ${this.buildSelection(s,{isSingleTable:!o})}`:void 0,j=i?J` where ${i}`:void 0;return J`${h}update ${x} set ${q}${N}${C}${j}${y}`}buildSelection(e,{isSingleTable:t=false}={}){let i=e.length,s=e.flatMap(({field:n},o)=>{let a=[];if(c$1(n,A.Aliased)&&n.isSelectionField)a.push(J.identifier(n.fieldAlias));else if(c$1(n,A.Aliased)||c$1(n,A)){let h=c$1(n,A.Aliased)?n.sql:n;t?a.push(new A(h.queryChunks.map(u=>c$1(u,g$1)?J.identifier(this.casing.getColumnCasing(u)):u))):a.push(h),c$1(n,A.Aliased)&&a.push(J` as ${J.identifier(n.fieldAlias)}`);}else c$1(n,d)&&(t?a.push(J.identifier(this.casing.getColumnCasing(n))):a.push(n));return o<i-1&&a.push(J`, `),a});return J.join(s)}buildJoins(e){if(!e||e.length===0)return;let t=[];for(let[i,s]of e.entries()){i===0&&t.push(J` `);let n=s.table,o=s.lateral?J` lateral`:void 0,a=s.on?J` on ${s.on}`:void 0;if(c$1(n,qa)){let h=n[qa.Symbol.Name],u=n[qa.Symbol.Schema],d=n[qa.Symbol.OriginalName],w=h===d?void 0:s.alias;t.push(J`${J.raw(s.joinType)} join${o} ${u?J`${J.identifier(u)}.`:void 0}${J.identifier(d)}${w&&J` ${J.identifier(w)}`}${a}`);}else if(c$1(n,N)){let h=n[l].name,u=n[l].schema,d=n[l].originalName,w=h===d?void 0:s.alias;t.push(J`${J.raw(s.joinType)} join${o} ${u?J`${J.identifier(u)}.`:void 0}${J.identifier(d)}${w&&J` ${J.identifier(w)}`}${a}`);}else t.push(J`${J.raw(s.joinType)} join${o} ${n}${a}`);i<e.length-1&&t.push(J` `);}return J.join(t)}buildFromTable(e){if(c$1(e,t)&&e[t.Symbol.IsAlias]){let t$1=J`${J.identifier(e[t.Symbol.OriginalName])}`;return e[t.Symbol.Schema]&&(t$1=J`${J.identifier(e[t.Symbol.Schema])}.${t$1}`),J`${t$1} ${J.identifier(e[t.Symbol.Name])}`}return e}buildSelectQuery({withList:e,fields:t$1,fieldsFlat:i,where:s,having:n,table:o,joins:a,orderBy:h,groupBy:u,limit:d$1,offset:w,lockingClause:$,distinct:x,setOperators:q}){let N=i??R(t$1);for(let B of N)if(c$1(B.field,d)&&v(B.field.table)!==(c$1(o,i$1)?o._.alias:c$1(o,ee)?o[l].name:c$1(o,A)?void 0:v(o))&&!(R=>a?.some(({alias:je})=>je===(R[t.Symbol.IsAlias]?v(R):R[t.Symbol.BaseName])))(B.field.table)){let R=v(B.field.table);throw new Error(`Your "${B.path.join("->")}" field references a column "${R}"."${B.field.name}", but the table "${R}" is not part of the query! Did you forget to join it?`)}let C=!a||a.length===0,y=this.buildWithCTE(e),j;x&&(j=x===true?J` distinct`:J` distinct on (${J.join(x.on,J`, `)})`);let L=this.buildSelection(N,{isSingleTable:C}),Q=this.buildFromTable(o),W=this.buildJoins(a),k=s?J` where ${s}`:void 0,m=n?J` having ${n}`:void 0,p;h&&h.length>0&&(p=J` order by ${J.join(h,J`, `)}`);let M;u&&u.length>0&&(M=J` group by ${J.join(u,J`, `)}`);let he=typeof d$1=="object"||typeof d$1=="number"&&d$1>=0?J` limit ${d$1}`:void 0,Qe=w?J` offset ${w}`:void 0,G=J.empty();if($){let B=J` for ${J.raw($.strength)}`;$.config.of&&B.append(J` of ${J.join(Array.isArray($.config.of)?$.config.of:[$.config.of],J`, `)}`),$.config.noWait?B.append(J` nowait`):$.config.skipLocked&&B.append(J` skip locked`),G.append(B);}let U=J`${y}select${j} ${L} from ${Q}${W}${k}${M}${m}${p}${he}${Qe}${G}`;return q.length>0?this.buildSetOperations(U,q):U}buildSetOperations(e,t){let[i,...s]=t;if(!i)throw new Error("Cannot pass undefined values to any set operator");return s.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:i}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:i}),s)}buildSetOperationQuery({leftSelect:e,setOperator:{type:t,isAll:i,rightSelect:s,limit:n,orderBy:o,offset:a}}){let h=J`(${e.getSQL()}) `,u=J`(${s.getSQL()})`,d;if(o&&o.length>0){let q=[];for(let N of o)if(c$1(N,g$1))q.push(J.identifier(N.name));else if(c$1(N,A)){for(let C=0;C<N.queryChunks.length;C++){let y=N.queryChunks[C];c$1(y,g$1)&&(N.queryChunks[C]=J.identifier(y.name));}q.push(J`${N}`);}else q.push(J`${N}`);d=J` order by ${J.join(q,J`, `)} `;}let w=typeof n=="object"||typeof n=="number"&&n>=0?J` limit ${n}`:void 0,$=J.raw(`${t} ${i?"all ":""}`),x=a?J` offset ${a}`:void 0;return J`${h}${$}${u}${d}${w}${x}`}buildInsertQuery({table:e,values:t$1,onConflict:i,returning:s,withList:n,select:o,overridingSystemValue_:a}){let h=[],u=e[t.Symbol.Columns],d=Object.entries(u).filter(([y,j])=>!j.shouldDisableInsert()),w=d.map(([,y])=>J.identifier(this.casing.getColumnCasing(y)));if(o){let y=t$1;c$1(y,A)?h.push(y):h.push(y.getSQL());}else {let y=t$1;h.push(J.raw("values "));for(let[j,L]of y.entries()){let Q=[];for(let[W,k]of d){let m=L[W];if(m===void 0||c$1(m,H$1)&&m.value===void 0)if(k.defaultFn!==void 0){let p=k.defaultFn(),M=c$1(p,A)?p:J.param(p,k);Q.push(M);}else if(!k.default&&k.onUpdateFn!==void 0){let p=k.onUpdateFn(),M=c$1(p,A)?p:J.param(p,k);Q.push(M);}else Q.push(J`default`);else Q.push(m);}h.push(Q),j<y.length-1&&h.push(J`, `);}}let $=this.buildWithCTE(n),x=J.join(h),q=s?J` returning ${this.buildSelection(s,{isSingleTable:true})}`:void 0,N=i?J` on conflict ${i}`:void 0,C=a===true?J`overriding system value `:void 0;return J`${$}insert into ${e} ${w} ${C}${x}${N}${q}`}buildRefreshMaterializedViewQuery({view:e,concurrently:t,withNoData:i}){let s=t?J` concurrently`:void 0,n=i?J` with no data`:void 0;return J`refresh materialized view${s} ${e}${n}`}prepareTyping(e){return c$1(e,ea)||c$1(e,da)?"json":c$1(e,ga)?"decimal":c$1(e,ja)?"time":c$1(e,ka)||c$1(e,la)?"timestamp":c$1(e,aa)||c$1(e,ba)?"date":c$1(e,na)?"uuid":"none"}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:t})}buildRelationalQueryWithoutPK({fullSchema:e,schema:t,tableNamesMap:i,table:s,tableConfig:n$1,queryConfig:o,tableAlias:a,nestedQueryRelation:h$1,joinOn:u}){let d$2=[],w$1,$,x=[],q,N=[];if(o===true)d$2=Object.entries(n$1.columns).map(([j,L])=>({dbKey:L.name,tsKey:j,field:f(L,a),relationTableTsKey:void 0,isJson:false,selection:[]}));else {let y=Object.fromEntries(Object.entries(n$1.columns).map(([m,p])=>[m,f(p,a)]));if(o.where){let m=typeof o.where=="function"?o.where(y,R$1()):o.where;q=m&&h(m,a);}let j=[],L=[];if(o.columns){let m=false;for(let[p,M]of Object.entries(o.columns))M!==void 0&&p in n$1.columns&&(!m&&M===true&&(m=true),L.push(p));L.length>0&&(L=m?L.filter(p=>o.columns?.[p]===true):Object.keys(n$1.columns).filter(p=>!L.includes(p)));}else L=Object.keys(n$1.columns);for(let m of L){let p=n$1.columns[m];j.push({tsKey:m,value:p});}let Q=[];o.with&&(Q=Object.entries(o.with).filter(m=>!!m[1]).map(([m,p])=>({tsKey:m,queryConfig:p,relation:n$1.relations[m]})));let W;if(o.extras){W=typeof o.extras=="function"?o.extras(y,{sql:J}):o.extras;for(let[m,p]of Object.entries(W))j.push({tsKey:m,value:g$2(p,a)});}for(let{tsKey:m,value:p}of j)d$2.push({dbKey:c$1(p,A.Aliased)?p.fieldAlias:n$1.columns[m].name,tsKey:m,field:c$1(p,d)?f(p,a):p,relationTableTsKey:void 0,isJson:false,selection:[]});let k=typeof o.orderBy=="function"?o.orderBy(y,S$1()):o.orderBy??[];Array.isArray(k)||(k=[k]),x=k.map(m=>c$1(m,d)?f(m,a):h(m,a)),w$1=o.limit,$=o.offset;for(let{tsKey:m,queryConfig:p$1,relation:M}of Q){let he=X$1(t,i,M),Qe=w(M.referencedTable),G=i[Qe],U=`${a}_${m}`,B=p(...he.fields.map((bt,wt)=>n(f(he.references[wt],U),f(bt,a)))),R=this.buildRelationalQueryWithoutPK({fullSchema:e,schema:t,tableNamesMap:i,table:e[G],tableConfig:t[G],queryConfig:c$1(M,P)?p$1===true?{limit:1}:{...p$1,limit:1}:p$1,tableAlias:U,joinOn:B,nestedQueryRelation:M}),je=J`${J.identifier(U)}.${J.identifier("data")}`.as(m);N.push({on:J`true`,table:new i$1(R.sql,{},U),alias:U,joinType:"left",lateral:true}),d$2.push({dbKey:m,tsKey:m,field:je,relationTableTsKey:G,isJson:true,selection:R.selection});}}if(d$2.length===0)throw new j({message:`No fields selected for table "${n$1.tsName}" ("${a}")`});let C;if(q=p(u,q),h$1){let y=J`json_build_array(${J.join(d$2.map(({field:Q,tsKey:W,isJson:k})=>k?J`${J.identifier(`${a}_${W}`)}.${J.identifier("data")}`:c$1(Q,A.Aliased)?Q.sql:Q),J`, `)})`;c$1(h$1,Q)&&(y=J`coalesce(json_agg(${y}${x.length>0?J` order by ${J.join(x,J`, `)}`:void 0}), '[]'::json)`);let j=[{dbKey:"data",tsKey:"data",field:y.as("data"),isJson:true,relationTableTsKey:n$1.tsName,selection:d$2}];w$1!==void 0||$!==void 0||x.length>0?(C=this.buildSelectQuery({table:d$1(s,a),fields:{},fieldsFlat:[{path:[],field:J.raw("*")}],where:q,limit:w$1,offset:$,orderBy:x,setOperators:[]}),q=void 0,w$1=void 0,$=void 0,x=[]):C=d$1(s,a),C=this.buildSelectQuery({table:c$1(C,qa)?C:new i$1(C,{},a),fields:{},fieldsFlat:j.map(({field:Q})=>({path:[],field:c$1(Q,d)?f(Q,a):Q})),joins:N,where:q,limit:w$1,offset:$,orderBy:x,setOperators:[]});}else C=this.buildSelectQuery({table:d$1(s,a),fields:{},fieldsFlat:d$2.map(({field:y})=>({path:[],field:c$1(y,d)?f(y,a):y})),joins:N,where:q,limit:w$1,offset:$,orderBy:x,setOperators:[]});return {tableTsKey:n$1.tsName,sql:C,selection:d$2}}};g();var z=class{static[a]="PgSelectBuilder";fields;session;dialect;withList=[];distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,e.withList&&(this.withList=e.withList),this.distinct=e.distinct;}authToken;setToken(e){return this.authToken=e,this}from(e){let t=!!this.fields,i=e,s;return this.fields?s=this.fields:c$1(i,i$1)?s=Object.fromEntries(Object.keys(i._.selectedFields).map(n=>[n,i[n]])):c$1(i,ee)?s=i[l].selectedFields:c$1(i,A)?s={}:s=V(i),new be({table:i,fields:s,isPartialSelect:t,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}},Me=class extends c{static[a]="PgSelectQueryBuilder";_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:i,session:s,dialect:n,withList:o,distinct:a}){super(),this.config={withList:o,table:e,fields:{...t},distinct:a,setOperators:[]},this.isPartialSelect=i,this.session=s,this.dialect=n,this._={selectedFields:t,config:this.config},this.tableName=X(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:true}:{};for(let h of E(e))this.usedTables.add(h);}getUsedTables(){return [...this.usedTables]}createJoin(e,t$1){return (i,s)=>{let n=this.tableName,o=X(i);for(let a of E(i))this.usedTables.add(a);if(typeof o=="string"&&this.config.joins?.some(a=>a.alias===o))throw new Error(`Alias "${o}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof n=="string"&&(this.config.fields={[n]:this.config.fields}),typeof o=="string"&&!c$1(i,A))){let a=c$1(i,i$1)?i._.selectedFields:c$1(i,N)?i[l].selectedFields:i[t.Symbol.Columns];this.config.fields[o]=a;}if(typeof s=="function"&&(s=s(new Proxy(this.config.fields,new a$2({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:s,table:i,joinType:e,alias:o,lateral:t$1}),typeof o=="string")switch(e){case "left":{this.joinsNotNullableMap[o]=false;break}case "right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,false])),this.joinsNotNullableMap[o]=true;break}case "cross":case "inner":{this.joinsNotNullableMap[o]=true;break}case "full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([a])=>[a,false])),this.joinsNotNullableMap[o]=false;break}}return this}}leftJoin=this.createJoin("left",false);leftJoinLateral=this.createJoin("left",true);rightJoin=this.createJoin("right",false);innerJoin=this.createJoin("inner",false);innerJoinLateral=this.createJoin("inner",true);fullJoin=this.createJoin("full",false);crossJoin=this.createJoin("cross",false);crossJoinLateral=this.createJoin("cross",true);createSetOperator(e,t){return i=>{let s=typeof i=="function"?i(St()):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);intersectAll=this.createSetOperator("intersect",true);except=this.createSetOperator("except",false);exceptAll=this.createSetOperator("except",true);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new a$2({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})))),this.config.where=e,this}having(e){return typeof e=="function"&&(e=e(new Proxy(this.config.fields,new a$2({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$2({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$2({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}for(e,t={}){return this.config.lockingClause={strength:e,config:t},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(...E(this.config.table)),this.config.joins)for(let i of this.config.joins)t.push(...E(i.table));return new Proxy(new i$1(this.getSQL(),this.config.fields,e,false,[...new Set(t)]),new a$2({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}getSelectedFields(){return new Proxy(this.config.fields,new a$2({alias:this.tableName,sqlAliasedBehavior:"alias",sqlBehavior:"error"}))}$dynamic(){return this}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:true,autoInvalidate:true}:e===false?{enable:false}:{enable:true,autoInvalidate:true,...e},this}},be=class extends Me{static[a]="PgSelect";_prepare(e){let{session:t,config:i,dialect:s,joinsNotNullableMap:n,authToken:o,cacheConfig:a,usedTables:h}=this;if(!t)throw new Error("Cannot execute a query on a query builder. Please use a database instance instead.");let{fields:u}=i;return k.startActiveSpan("drizzle.prepareQuery",()=>{let d=R(u),w=t.prepareQuery(s.sqlToQuery(this.getSQL()),d,e,true,void 0,{type:"select",tables:[...h]},a);return w.joinsNotNullableMap=n,w.setToken(o)})}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>k.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken))};U(be,[i]);function te(c,e){return (t,i,...s)=>{let n=[i,...s].map(o=>({type:c,isAll:e,rightSelect:o}));for(let o of n)if(!S(t.getSelectedFields(),o.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(n)}}var St=()=>({union:vt,unionAll:$t,intersect:Tt,intersectAll:qt,except:Nt,exceptAll:Ct}),vt=te("union",false),$t=te("union",true),Tt=te("intersect",false),qt=te("intersect",true),Nt=te("except",false),Ct=te("except",true);var ie=class{static[a]="PgQueryBuilder";dialect;dialectConfig;constructor(e){this.dialect=c$1(e,H)?e:void 0,this.dialectConfig=c$1(e,H)?void 0:e;}$with=(e,t)=>{let i=this;return {as:n=>(typeof n=="function"&&(n=n(i)),new Proxy(new j$1(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,true),new a$2({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};with(...e){let t=this;function i(o){return new z({fields:o??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function s(o){return new z({fields:o??void 0,session:void 0,dialect:t.getDialect(),distinct:true})}function n(o,a){return new z({fields:a??void 0,session:void 0,dialect:t.getDialect(),distinct:{on:o}})}return {select:i,selectDistinct:s,selectDistinctOn:n}}select(e){return new z({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new z({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:true})}selectDistinctOn(e,t){return new z({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:e}})}getDialect(){return this.dialect||(this.dialect=new H(this.dialectConfig)),this.dialect}};function E(c){return c$1(c,qa)?[c[m]?`${c[m]}.${c[t.Symbol.BaseName]}`:c[t.Symbol.BaseName]]:c$1(c,i$1)?c._.usedTables??[]:c$1(c,A)?c.usedTables??[]:[]}var oe=class extends i{constructor(e,t,i,s){super(),this.session=t,this.dialect=i,this.config={table:e,withList:s};}static[a]="PgDelete";config;cacheConfig;where(e){return this.config.where=e,this}returning(e=this.config.table[t.Symbol.Columns]){return this.config.returningFields=e,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){return k.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,true,void 0,{type:"delete",tables:E(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>k.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new a$2({alias:v(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};g();var ae=class{constructor(e,t,i,s,n){this.table=e,this.session=t,this.dialect=i,this.withList=s,this.overridingSystemValue_=n;}static[a]="PgInsertBuilder";authToken;setToken(e){return this.authToken=e,this}overridingSystemValue(){return this.overridingSystemValue_=true,this}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={},n=this.table[t.Symbol.Columns];for(let o of Object.keys(i)){let a=i[o];s[o]=c$1(a,A)?a:new H$1(a,n[o]);}return s});return new we(this.table,t$1,this.session,this.dialect,this.withList,false,this.overridingSystemValue_).setToken(this.authToken)}select(e){let t=typeof e=="function"?e(new ie):e;if(!c$1(t,A)&&!S(this.table[n$1],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 we(this.table,t,this.session,this.dialect,this.withList,true)}},we=class extends i{constructor(e,t,i,s,n,o,a){super(),this.session=i,this.dialect=s,this.config={table:e,values:t,withList:n,select:o,overridingSystemValue_:a};}static[a]="PgInsert";config;cacheConfig;returning(e=this.config.table[t.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=R(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=J`do nothing`;else {let t="";t=Array.isArray(e.target)?e.target.map(s=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(s))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target));let i=e.where?J` where ${e.where}`:void 0;this.config.onConflict=J`(${J.raw(t)})${i} do nothing`;}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.');let t=e.where?J` where ${e.where}`:void 0,i=e.targetWhere?J` where ${e.targetWhere}`:void 0,s=e.setWhere?J` where ${e.setWhere}`:void 0,n=this.dialect.buildUpdateSet(this.config.table,T$1(this.config.table,e.set)),o="";return o=Array.isArray(e.target)?e.target.map(a=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(a))).join(","):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target)),this.config.onConflict=J`(${J.raw(o)})${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){return k.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,true,void 0,{type:"insert",tables:E(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>k.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new a$2({alias:v(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};g();var Se=class extends i{constructor(e,t,i){super(),this.session=t,this.dialect=i,this.config={view:e};}static[a]="PgRefreshMaterializedView";config;concurrently(){if(this.config.withNoData!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.concurrently=true,this}withNoData(){if(this.config.concurrently!==void 0)throw new Error("Cannot use concurrently and withNoData together");return this.config.withNoData=true,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return k.startActiveSpan("drizzle.prepareQuery",()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,e,true))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>k.startActiveSpan("drizzle.operation",()=>this._prepare().execute(e,this.authToken))};g();var le=class{constructor(e,t,i,s){this.table=e,this.session=t,this.dialect=i,this.withList=s;}static[a]="PgUpdateBuilder";authToken;setToken(e){return this.authToken=e,this}set(e){return new Ae(this.table,T$1(this.table,e),this.session,this.dialect,this.withList).setToken(this.authToken)}},Ae=class extends i{constructor(e,t,i,s,n){super(),this.session=i,this.dialect=s,this.config={set:t,table:e,withList:n,joins:[]},this.tableName=X(e),this.joinsNotNullableMap=typeof this.tableName=="string"?{[this.tableName]:true}:{};}static[a]="PgUpdate";config;tableName;joinsNotNullableMap;cacheConfig;from(e){let t=e,i=X(t);return typeof i=="string"&&(this.joinsNotNullableMap[i]=true),this.config.from=t,this}getTableLikeFields(e){return c$1(e,qa)?e[t.Symbol.Columns]:c$1(e,i$1)?e._.selectedFields:e[l].selectedFields}createJoin(e){return (t$1,i)=>{let s=X(t$1);if(typeof s=="string"&&this.config.joins.some(n=>n.alias===s))throw new Error(`Alias "${s}" is already used in this query`);if(typeof i=="function"){let n=this.config.from&&!c$1(this.config.from,A)?this.getTableLikeFields(this.config.from):void 0;i=i(new Proxy(this.config.table[t.Symbol.Columns],new a$2({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})),n&&new Proxy(n,new a$2({sqlAliasedBehavior:"sql",sqlBehavior:"sql"})));}if(this.config.joins.push({on:i,table:t$1,joinType:e,alias:s}),typeof s=="string")switch(e){case "left":{this.joinsNotNullableMap[s]=false;break}case "right":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,false])),this.joinsNotNullableMap[s]=true;break}case "inner":{this.joinsNotNullableMap[s]=true;break}case "full":{this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([n])=>[n,false])),this.joinsNotNullableMap[s]=false;break}}return 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}returning(e){if(!e&&(e=Object.assign({},this.config.table[t.Symbol.Columns]),this.config.from)){let t=X(this.config.from);if(typeof t=="string"&&this.config.from&&!c$1(this.config.from,A)){let i=this.getTableLikeFields(this.config.from);e[t]=i;}for(let i of this.config.joins){let s=X(i.table);if(typeof s=="string"&&!c$1(i.table,A)){let n=this.getTableLikeFields(i.table);e[s]=n;}}}return this.config.returningFields=e,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){let t=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,true,void 0,{type:"insert",tables:E(this.config.table)},this.cacheConfig);return t.joinsNotNullableMap=this.joinsNotNullableMap,t}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>this._prepare().execute(e,this.authToken);getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new a$2({alias:v(this.config.table),sqlAliasedBehavior:"alias",sqlBehavior:"error"})):void 0}$dynamic(){return this}};g();var ve=class c extends A{constructor(e){super(c.buildEmbeddedCount(e.source,e.filters).queryChunks),this.params=e,this.mapWith(Number),this.session=e.session,this.sql=c.buildCount(e.source,e.filters);}sql;token;static[a]="PgCountBuilder";[Symbol.toStringTag]="PgCountBuilder";session;static buildEmbeddedCount(e,t){return J`(select count(*) from ${e}${J.raw(" where ").if(t)}${t})`}static buildCount(e,t){return J`select count(*) as count from ${e}${J.raw(" where ").if(t)}${t};`}setToken(e){return this.token=e,this}then(e,t){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}};g();var $e=class{constructor(e,t,i,s,n,o,a){this.fullSchema=e,this.schema=t,this.tableNamesMap=i,this.table=s,this.tableConfig=n,this.dialect=o,this.session=a;}static[a]="PgRelationalQueryBuilder";findMany(e){return new Te(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},"many")}findFirst(e){return new Te(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},"first")}},Te=class extends i{constructor(e,t,i,s,n,o,a,h,u){super(),this.fullSchema=e,this.schema=t,this.tableNamesMap=i,this.table=s,this.tableConfig=n,this.dialect=o,this.session=a,this.config=h,this.mode=u;}static[a]="PgRelationalQuery";_prepare(e){return k.startActiveSpan("drizzle.prepareQuery",()=>{let{query:t,builtQuery:i}=this._toSQL();return this.session.prepareQuery(i,void 0,e,true,(s,n)=>{let o=s.map(a=>Z$1(this.schema,this.tableConfig,a,t.selection,n));return this.mode==="first"?o[0]:o})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect.buildRelationalQueryWithoutPK({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let e=this._getQuery(),t=this.dialect.sqlToQuery(e.sql);return {query:e,builtQuery:t}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(e){return this.authToken=e,this}execute(){return k.startActiveSpan("drizzle.operation",()=>this._prepare().execute(void 0,this.authToken))}};g();var qe=class extends i{constructor(e,t,i,s){super(),this.execute=e,this.sql=t,this.query=i,this.mapBatchResult=s;}static[a]="PgRaw";getSQL(){return this.sql}getQuery(){return this.query}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return false}};var se=class{constructor(e,t,i){if(this.dialect=e,this.session=t,this._=i?{schema:i.schema,fullSchema:i.fullSchema,tableNamesMap:i.tableNamesMap,session:t}:{schema:void 0,fullSchema:{},tableNamesMap:{},session:t},this.query={},this._.schema)for(let[s,n]of Object.entries(this._.schema))this.query[s]=new $e(i.fullSchema,this._.schema,this._.tableNamesMap,i.fullSchema[s],n,e,t);this.$cache={invalidate:async s=>{}};}static[a]="PgDatabase";query;$with=(e,t)=>{let i=this;return {as:n=>(typeof n=="function"&&(n=n(new ie(i.dialect))),new Proxy(new j$1(n.getSQL(),t??("getSelectedFields"in n?n.getSelectedFields()??{}:{}),e,true),new a$2({alias:e,sqlAliasedBehavior:"alias",sqlBehavior:"error"})))}};$count(e,t){return new ve({source:e,filters:t,session:this.session})}$cache;with(...e){let t=this;function i(u){return new z({fields:u??void 0,session:t.session,dialect:t.dialect,withList:e})}function s(u){return new z({fields:u??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:true})}function n(u,d){return new z({fields:d??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:{on:u}})}function o(u){return new le(u,t.session,t.dialect,e)}function a(u){return new ae(u,t.session,t.dialect,e)}function h(u){return new oe(u,t.session,t.dialect,e)}return {select:i,selectDistinct:s,selectDistinctOn:n,update:o,insert:a,delete:h}}select(e){return new z({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new z({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:true})}selectDistinctOn(e,t){return new z({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:{on:e}})}update(e){return new le(e,this.session,this.dialect)}insert(e){return new ae(e,this.session,this.dialect)}delete(e){return new oe(e,this.session,this.dialect)}refreshMaterializedView(e){return new Se(e,this.session,this.dialect)}authToken;execute(e){let t=typeof e=="string"?J.raw(e):e.getSQL(),i=this.dialect.sqlToQuery(t),s=this.session.prepareQuery(i,void 0,void 0,false);return new qe(()=>s.execute(void 0,this.authToken),t,i,n=>s.mapResult(n,true))}transaction(e,t){return this.session.transaction(e,t)}};g();g();var Ne=class{constructor(e,t,i,s){this.query=e,this.cache=t,this.queryMetadata=i,this.cacheConfig=s,t&&t.strategy()==="all"&&s===void 0&&(this.cacheConfig={enable:true,autoInvalidate:true}),this.cacheConfig?.enable||(this.cacheConfig=void 0);}authToken;getQuery(){return this.query}mapResult(e,t){return e}setToken(e){return this.authToken=e,this}static[a]="PgPreparedQuery";joinsNotNullableMap;async queryWithCache(e$1,t,i){if(this.cache===void 0||c$1(this.cache,d$2)||this.queryMetadata===void 0)try{return await i()}catch(s){throw new k$1(e$1,t,s)}if(this.cacheConfig&&!this.cacheConfig.enable)try{return await i()}catch(s){throw new k$1(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$1(e$1,t,s)}if(!this.cacheConfig)try{return await i()}catch(s){throw new k$1(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 n;try{n=await i();}catch(o){throw new k$1(e$1,t,o)}return await this.cache.put(this.cacheConfig.tag??await e(e$1,t),n,this.cacheConfig.autoInvalidate?this.queryMetadata.tables:[],this.cacheConfig.tag!==void 0,this.cacheConfig.config),n}return s}try{return await i()}catch(s){throw new k$1(e$1,t,s)}}},Ce=class{constructor(e){this.dialect=e;}static[a]="PgSession";execute(e,t){return k.startActiveSpan("drizzle.operation",()=>k.startActiveSpan("drizzle.prepareQuery",()=>this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,false)).setToken(t).execute(void 0,t))}all(e){return this.prepareQuery(this.dialect.sqlToQuery(e),void 0,void 0,false).all()}async count(e,t){let i=await this.execute(e,t);return Number(i[0].count)}},xe=class extends se{constructor(e,t,i,s=0){super(e,t,i),this.schema=i,this.nestedIndex=s;}static[a]="PgTransaction";rollback(){throw new l$1}getTransactionConfigSQL(e){let t=[];return e.isolationLevel&&t.push(`isolation level ${e.isolationLevel}`),e.accessMode&&t.push(e.accessMode),typeof e.deferrable=="boolean"&&t.push(e.deferrable?"deferrable":"not deferrable"),J.raw(t.join(" "))}setTransaction(e){return this.session.execute(J`set transaction ${this.getTransactionConfigSQL(e)}`)}};var Be=class extends Ne{constructor(e,t,i,s,n,o,a,h,u,d){super({sql:t,params:i},n,o,a),this.client=e,this.queryString=t,this.params=i,this.logger=s,this.fields=h,this._isResponseInArrayMode=u,this.customResultMapper=d;}static[a]="PostgresJsPreparedQuery";async execute(e={}){return k.startActiveSpan("drizzle.execute",async t=>{let i=M(this.params,e);t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.logger.logQuery(this.queryString,i);let{fields:s,queryString:n,client:o,joinsNotNullableMap:a,customResultMapper:h}=this;if(!s&&!h)return k.startActiveSpan("drizzle.driver.execute",()=>this.queryWithCache(n,i,async()=>await o.unsafe(n,i)));let u=await k.startActiveSpan("drizzle.driver.execute",()=>(t?.setAttributes({"drizzle.query.text":n,"drizzle.query.params":JSON.stringify(i)}),this.queryWithCache(n,i,async()=>await o.unsafe(n,i).values())));return k.startActiveSpan("drizzle.mapResponse",()=>h?h(u):u.map(d=>Q$1(s,d,a)))})}all(e={}){return k.startActiveSpan("drizzle.execute",async t=>{let i=M(this.params,e);return t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.logger.logQuery(this.queryString,i),k.startActiveSpan("drizzle.driver.execute",()=>(t?.setAttributes({"drizzle.query.text":this.queryString,"drizzle.query.params":JSON.stringify(i)}),this.queryWithCache(this.queryString,i,async()=>this.client.unsafe(this.queryString,i))))})}isResponseInArrayMode(){return this._isResponseInArrayMode}},ce=class c extends Ce{constructor(e,t,i,s={}){super(t),this.client=e,this.schema=i,this.options=s,this.logger=s.logger??new aa$1,this.cache=s.cache??new d$2;}static[a]="PostgresJsSession";logger;cache;prepareQuery(e,t,i,s,n,o,a){return new Be(this.client,e.sql,e.params,this.logger,this.cache,o,a,t,s,n)}query(e,t){return this.logger.logQuery(e,t),this.client.unsafe(e,t).values()}queryObjects(e,t){return this.client.unsafe(e,t)}transaction(e,t){return this.client.begin(async i=>{let s=new c(i,this.dialect,this.schema,this.options),n=new _e(this.dialect,s,this.schema);return t&&await n.setTransaction(t),e(n)})}},_e=class c extends xe{constructor(e,t,i,s=0){super(e,t,i,s),this.session=t;}static[a]="PostgresJsTransaction";transaction(e){return this.session.client.savepoint(t=>{let i=new ce(t,this.dialect,this.schema,this.session.options),s=new c(this.dialect,i,this.schema);return e(s)})}};var Fe=class extends se{static[a]="PostgresJsDatabase"};function re(c,e={}){let t=h=>h;for(let h of ["1184","1082","1083","1114","1182","1185","1115","1231"])c.options.parsers[h]=t,c.options.serializers[h]=t;c.options.serializers[114]=t,c.options.serializers[3802]=t;let i=new H({casing:e.casing}),s;e.logger===true?s=new $:e.logger!==false&&(s=e.logger);let n;if(e.schema){let h=T(e.schema,Y);n={fullSchema:e.schema,schema:h.tables,tableNamesMap:h.tableNamesMap};}let o=new ce(c,i,n,{logger:s,cache:e.cache}),a=new Fe(i,o,n);return a.$client=c,a.$cache=e.cache,a.$cache&&(a.$cache.invalidate=e.cache?.onMutate),a}function yt(...c){if(typeof c[0]=="string"){let e=a$1(c[0]);return re(e,c[1])}if(Z(c[0])){let{connection:e,client:t,...i}=c[0];if(t)return re(t,i);if(typeof e=="object"&&e.url!==void 0){let{url:n,...o}=e,a=a$1(n,o);return re(a,i)}let s=a$1(e);return re(s,i)}return re(c[0],c[1])}(c=>{function e(t){return re({options:{parsers:{},serializers:{}}},t)}c.mock=e;})(yt||(yt={}));export{H as a,Be as b,ce as c,_e as d,Fe as e,yt as f};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import {createRequire}from'module';import {c,g,a,e}from'./chunk-C2PXMVR5.js';createRequire(import.meta.url);
|
|
2
|
+
var L=c((wr,Ye)=>{g();var ze=["nodebuffer","arraybuffer","fragments"],He=typeof Blob<"u";He&&ze.push("blob");Ye.exports={BINARY_TYPES:ze,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:He,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};});var J=c((Tr,oe)=>{g();var{EMPTY_BUFFER:Zt}=L(),ve=Buffer[Symbol.species];function Qt(t,e){if(t.length===0)return Zt;if(t.length===1)return t[0];let s=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let n=t[i];s.set(n,r),r+=n.length;}return r<e?new ve(s.buffer,s.byteOffset,r):s}function Ke(t,e,s,r,i){for(let n=0;n<i;n++)s[r+n]=t[n]^e[n&3];}function Xe(t,e){for(let s=0;s<t.length;s++)t[s]^=e[s&3];}function Jt(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function be(t){if(be.readOnly=true,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new ve(t):ArrayBuffer.isView(t)?e=new ve(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),be.readOnly=false),e}oe.exports={concat:Qt,mask:Ke,toArrayBuffer:Jt,toBuffer:be,unmask:Xe};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=a("bufferutil");oe.exports.mask=function(e,s,r,i,n){n<48?Ke(e,s,r,i,n):t.mask(e,s,r,i,n);},oe.exports.unmask=function(e,s){e.length<32?Xe(e,s):t.unmask(e,s);};}catch{}});var Je=c((Cr,Qe)=>{g();var Ze=Symbol("kDone"),we=Symbol("kRun"),Oe=class{constructor(e){this[Ze]=()=>{this.pending--,this[we]();},this.concurrency=e||1/0,this.jobs=[],this.pending=0;}add(e){this.jobs.push(e),this[we]();}[we](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Ze]);}}};Qe.exports=Oe;});var V=c((Nr,rt)=>{g();var ee=a("zlib"),et=J(),es=Je(),{kStatusCode:tt}=L(),ts=Buffer[Symbol.species],ss=Buffer.from([0,0,255,255]),fe=Symbol("permessage-deflate"),N=Symbol("total-length"),$=Symbol("callback"),U=Symbol("buffers"),j=Symbol("error"),ae,Te=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!ae){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ae=new es(s);}}static get extensionName(){return "permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=true),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=true),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=true),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[$];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"));}}acceptAsServer(e){let s=this._options,r=e.find(i=>!(s.serverNoContextTakeover===false&&i.server_no_context_takeover||i.server_max_window_bits&&(s.serverMaxWindowBits===false||typeof s.serverMaxWindowBits=="number"&&s.serverMaxWindowBits>i.server_max_window_bits)||typeof s.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return s.serverNoContextTakeover&&(r.server_no_context_takeover=true),s.clientNoContextTakeover&&(r.client_no_context_takeover=true),typeof s.serverMaxWindowBits=="number"&&(r.server_max_window_bits=s.serverMaxWindowBits),typeof s.clientMaxWindowBits=="number"?r.client_max_window_bits=s.clientMaxWindowBits:(r.client_max_window_bits===true||s.clientMaxWindowBits===false)&&delete r.client_max_window_bits,r}acceptAsClient(e){let s=e[0];if(this._options.clientNoContextTakeover===false&&s.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!s.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(s.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===false||typeof this._options.clientMaxWindowBits=="number"&&s.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return s}normalizeParams(e){return e.forEach(s=>{Object.keys(s).forEach(r=>{let i=s[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==true){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=n;}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=n;}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==true)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);s[r]=i;});}),e}decompress(e,s,r){ae.add(i=>{this._decompress(e,s,(n,o)=>{i(),r(n,o);});});}compress(e,s,r){ae.add(i=>{this._compress(e,s,(n,o)=>{i(),r(n,o);});});}_decompress(e,s,r){let i=this._isServer?"client":"server";if(!this._inflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?ee.Z_DEFAULT_WINDOWBITS:this.params[n];this._inflate=ee.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[fe]=this,this._inflate[N]=0,this._inflate[U]=[],this._inflate.on("error",is),this._inflate.on("data",st);}this._inflate[$]=r,this._inflate.write(e),s&&this._inflate.write(ss),this._inflate.flush(()=>{let n=this._inflate[j];if(n){this._inflate.close(),this._inflate=null,r(n);return}let o=et.concat(this._inflate[U],this._inflate[N]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[N]=0,this._inflate[U]=[],s&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,o);});}_compress(e,s,r){let i=this._isServer?"server":"client";if(!this._deflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!="number"?ee.Z_DEFAULT_WINDOWBITS:this.params[n];this._deflate=ee.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[N]=0,this._deflate[U]=[],this._deflate.on("data",rs);}this._deflate[$]=r,this._deflate.write(e),this._deflate.flush(ee.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let n=et.concat(this._deflate[U],this._deflate[N]);s&&(n=new ts(n.buffer,n.byteOffset,n.length-4)),this._deflate[$]=null,this._deflate[N]=0,this._deflate[U]=[],s&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,n);});}};rt.exports=Te;function rs(t){this[U].push(t),this[N]+=t.length;}function st(t){if(this[N]+=t.length,this[fe]._maxPayload<1||this[N]<=this[fe]._maxPayload){this[U].push(t);return}this[j]=new RangeError("Max payload size exceeded"),this[j].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[j][tt]=1009,this.removeListener("data",st),this.reset();}function is(t){if(this[fe]._inflate=null,this[j]){this[$](this[j]);return}t[tt]=1007,this[$](t);}});var z=c((Br,le)=>{g();var{isUtf8:it}=a("buffer"),{hasBlob:ns}=L(),os=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function as(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function ke(t){let e=t.length,s=0;for(;s<e;)if((t[s]&128)===0)s++;else if((t[s]&224)===192){if(s+1===e||(t[s+1]&192)!==128||(t[s]&254)===192)return false;s+=2;}else if((t[s]&240)===224){if(s+2>=e||(t[s+1]&192)!==128||(t[s+2]&192)!==128||t[s]===224&&(t[s+1]&224)===128||t[s]===237&&(t[s+1]&224)===160)return false;s+=3;}else if((t[s]&248)===240){if(s+3>=e||(t[s+1]&192)!==128||(t[s+2]&192)!==128||(t[s+3]&192)!==128||t[s]===240&&(t[s+1]&240)===128||t[s]===244&&t[s+1]>143||t[s]>244)return false;s+=4;}else return false;return true}function fs(t){return ns&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}le.exports={isBlob:fs,isValidStatusCode:as,isValidUTF8:ke,tokenChars:os};if(it)le.exports.isValidUTF8=function(t){return t.length<24?ke(t):it(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=a("utf-8-validate");le.exports.isValidUTF8=function(e){return e.length<32?ke(e):t(e)};}catch{}});var Be=c((Ur,ct)=>{g();var{Writable:ls}=a("stream"),nt=V(),{BINARY_TYPES:hs,EMPTY_BUFFER:ot,kStatusCode:cs,kWebSocket:us}=L(),{concat:Ce,toArrayBuffer:ds,unmask:_s}=J(),{isValidStatusCode:ms,isValidUTF8:at}=z(),he=Buffer[Symbol.species],O=0,ft=1,lt=2,ht=3,Le=4,Ne=5,ce=6,Pe=class extends ls{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:true,this._binaryType=e.binaryType||hs[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[us]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=false,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=false,this._fin=false,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=false,this._loop=false,this._state=O;}_write(e,s,r){if(this._opcode===8&&this._state==O)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r);}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new he(r.buffer,r.byteOffset+e,r.length-e),new he(r.buffer,r.byteOffset,e)}let s=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=s.length-e;e>=r.length?s.set(this._buffers.shift(),i):(s.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new he(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length;}while(e>0);return s}startLoop(e){this._loop=true;do switch(this._state){case O:this.getInfo(e);break;case ft:this.getPayloadLength16(e);break;case lt:this.getPayloadLength64(e);break;case ht:this.getMask();break;case Le:this.getData(e);break;case Ne:case ce:this._loop=false;return}while(this._loop);this._errored||e();}getInfo(e){if(this._bufferedBytes<2){this._loop=false;return}let s=this.consume(2);if((s[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(s[0]&64)===64;if(r&&!this._extensions[nt.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(s[0]&128)===128,this._opcode=s[0]&15,this._payloadLength=s[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",true,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented;}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r;}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",true,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",true,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,true,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else {let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,true,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(s[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",true,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",true,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=ft:this._payloadLength===127?this._state=lt:this.haveLength(e);}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=false;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e);}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=false;return}let s=this.consume(8),r=s.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",false,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+s.readUInt32BE(4),this.haveLength(e);}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let s=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(s);return}this._masked?this._state=ht:this._state=Le;}getMask(){if(this._bufferedBytes<4){this._loop=false;return}this._mask=this.consume(4),this._state=Le;}getData(e){let s=ot;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=false;return}s=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&_s(s,this._mask);}if(this._opcode>7){this.controlMessage(s,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",false,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=Ne,this.decompress(s,e);return}s.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(s)),this.dataMessage(e);}decompress(e,s){this._extensions[nt.extensionName].decompress(e,this._fin,(i,n)=>{if(i)return s(i);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",false,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");s(o);return}this._fragments.push(n);}this.dataMessage(s),this._state===O&&this.startLoop(s);});}dataMessage(e){if(!this._fin){this._state=O;return}let s=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=Ce(r,s):this._binaryType==="arraybuffer"?i=ds(Ce(r,s)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,true),this._state=O):(this._state=ce,setImmediate(()=>{this.emit("message",i,true),this._state=O,this.startLoop(e);}));}else {let i=Ce(r,s);if(!this._skipUTF8Validation&&!at(i)){let n=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");e(n);return}this._state===Ne||this._allowSynchronousEvents?(this.emit("message",i,false),this._state=O):(this._state=ce,setImmediate(()=>{this.emit("message",i,false),this._state=O,this.startLoop(e);}));}}controlMessage(e,s){if(this._opcode===8){if(e.length===0)this._loop=false,this.emit("conclude",1005,ot),this.end();else {let r=e.readUInt16BE(0);if(!ms(r)){let n=this.createError(RangeError,`invalid status code ${r}`,true,1002,"WS_ERR_INVALID_CLOSE_CODE");s(n);return}let i=new he(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!at(i)){let n=this.createError(Error,"invalid UTF-8 sequence",true,1007,"WS_ERR_INVALID_UTF8");s(n);return}this._loop=false,this.emit("conclude",r,i),this.end();}this._state=O;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=O):(this._state=ce,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=O,this.startLoop(s);}));}createError(e,s,r,i,n){this._loop=false,this._errored=true;let o=new e(r?`Invalid WebSocket frame: ${s}`:s);return Error.captureStackTrace(o,this.createError),o.code=n,o[cs]=i,o}};ct.exports=Pe;});var Ie=c((Mr,_t)=>{g();var{Duplex:Dr}=a("stream"),{randomFillSync:ps}=a("crypto"),{types:{isUint8Array:gs}}=a("util"),ut=V(),{EMPTY_BUFFER:ys,kWebSocket:xs,NOOP:Ss}=L(),{isBlob:H,isValidStatusCode:Es}=z(),{mask:dt,toBuffer:D}=J(),T=Symbol("kByteLength"),vs=Buffer.alloc(4),ue=8*1024,M,Y=ue,k=0,bs=1,ws=2,Re=class t{constructor(e,s,r){this._extensions=s||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=true,this._compress=false,this._bufferedBytes=0,this._queue=[],this._state=k,this.onerror=Ss,this[xs]=void 0;}static frame(e,s){let r,i=false,n=2,o=false;s.mask&&(r=s.maskBuffer||vs,s.generateMask?s.generateMask(r):(Y===ue&&(M===void 0&&(M=Buffer.alloc(ue)),ps(M,0,ue),Y=0),r[0]=M[Y++],r[1]=M[Y++],r[2]=M[Y++],r[3]=M[Y++]),o=(r[0]|r[1]|r[2]|r[3])===0,n=6);let f;typeof e=="string"?(!s.mask||o)&&s[T]!==void 0?f=s[T]:(e=Buffer.from(e),f=e.length):(f=e.length,i=s.mask&&s.readOnly&&!o);let l=f;f>=65536?(n+=8,l=127):f>125&&(n+=2,l=126);let a=Buffer.allocUnsafe(i?f+n:n);return a[0]=s.fin?s.opcode|128:s.opcode,s.rsv1&&(a[0]|=64),a[1]=l,l===126?a.writeUInt16BE(f,2):l===127&&(a[2]=a[3]=0,a.writeUIntBE(f,4,6)),s.mask?(a[1]|=128,a[n-4]=r[0],a[n-3]=r[1],a[n-2]=r[2],a[n-1]=r[3],o?[a,e]:i?(dt(e,r,a,n,f),[a]):(dt(e,r,e,0,f),[a,e])):[a,e]}close(e,s,r,i){let n;if(e===void 0)n=ys;else {if(typeof e!="number"||!Es(e))throw new TypeError("First argument must be a valid error code number");if(s===void 0||!s.length)n=Buffer.allocUnsafe(2),n.writeUInt16BE(e,0);else {let f=Buffer.byteLength(s);if(f>123)throw new RangeError("The message must not be greater than 123 bytes");if(n=Buffer.allocUnsafe(2+f),n.writeUInt16BE(e,0),typeof s=="string")n.write(s,2);else if(gs(s))n.set(s,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[T]:n.length,fin:true,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:false,rsv1:false};this._state!==k?this.enqueue([this.dispatch,n,false,o,i]):this.sendFrame(t.frame(n,o),i);}ping(e,s,r){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=false):H(e)?(i=e.size,n=false):(e=D(e),i=e.length,n=D.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[T]:i,fin:true,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:false};H(e)?this._state!==k?this.enqueue([this.getBlobData,e,false,o,r]):this.getBlobData(e,false,o,r):this._state!==k?this.enqueue([this.dispatch,e,false,o,r]):this.sendFrame(t.frame(e,o),r);}pong(e,s,r){let i,n;if(typeof e=="string"?(i=Buffer.byteLength(e),n=false):H(e)?(i=e.size,n=false):(e=D(e),i=e.length,n=D.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[T]:i,fin:true,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:false};H(e)?this._state!==k?this.enqueue([this.getBlobData,e,false,o,r]):this.getBlobData(e,false,o,r):this._state!==k?this.enqueue([this.dispatch,e,false,o,r]):this.sendFrame(t.frame(e,o),r);}send(e,s,r){let i=this._extensions[ut.extensionName],n=s.binary?2:1,o=s.compress,f,l;typeof e=="string"?(f=Buffer.byteLength(e),l=false):H(e)?(f=e.size,l=false):(e=D(e),f=e.length,l=D.readOnly),this._firstFragment?(this._firstFragment=false,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=f>=i._threshold),this._compress=o):(o=false,n=0),s.fin&&(this._firstFragment=true);let a={[T]:f,fin:s.fin,generateMask:this._generateMask,mask:s.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:l,rsv1:o};H(e)?this._state!==k?this.enqueue([this.getBlobData,e,this._compress,a,r]):this.getBlobData(e,this._compress,a,r):this._state!==k?this.enqueue([this.dispatch,e,this._compress,a,r]):this.dispatch(e,this._compress,a,r);}getBlobData(e,s,r,i){this._bufferedBytes+=r[T],this._state=ws,e.arrayBuffer().then(n=>{if(this._socket.destroyed){let f=new Error("The socket was closed while the blob was being read");process.nextTick(Ue,this,f,i);return}this._bufferedBytes-=r[T];let o=D(n);s?this.dispatch(o,s,r,i):(this._state=k,this.sendFrame(t.frame(o,r),i),this.dequeue());}).catch(n=>{process.nextTick(Os,this,n,i);});}dispatch(e,s,r,i){if(!s){this.sendFrame(t.frame(e,r),i);return}let n=this._extensions[ut.extensionName];this._bufferedBytes+=r[T],this._state=bs,n.compress(e,r.fin,(o,f)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Ue(this,l,i);return}this._bufferedBytes-=r[T],this._state=k,r.readOnly=false,this.sendFrame(t.frame(f,r),i),this.dequeue();});}dequeue(){for(;this._state===k&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][T],Reflect.apply(e[0],this,e.slice(1));}}enqueue(e){this._bufferedBytes+=e[3][T],this._queue.push(e);}sendFrame(e,s){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],s),this._socket.uncork()):this._socket.write(e[0],s);}};_t.exports=Re;function Ue(t,e,s){typeof s=="function"&&s(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],n=i[i.length-1];typeof n=="function"&&n(e);}}function Os(t,e,s){Ue(t,e,s),t.onerror(e);}});var bt=c((Ar,vt)=>{g();var{kForOnEventAttribute:te,kListener:De}=L(),mt=Symbol("kCode"),pt=Symbol("kData"),gt=Symbol("kError"),yt=Symbol("kMessage"),xt=Symbol("kReason"),K=Symbol("kTarget"),St=Symbol("kType"),Et=Symbol("kWasClean"),P=class{constructor(e){this[K]=null,this[St]=e;}get target(){return this[K]}get type(){return this[St]}};Object.defineProperty(P.prototype,"target",{enumerable:true});Object.defineProperty(P.prototype,"type",{enumerable:true});var F=class extends P{constructor(e,s={}){super(e),this[mt]=s.code===void 0?0:s.code,this[xt]=s.reason===void 0?"":s.reason,this[Et]=s.wasClean===void 0?false:s.wasClean;}get code(){return this[mt]}get reason(){return this[xt]}get wasClean(){return this[Et]}};Object.defineProperty(F.prototype,"code",{enumerable:true});Object.defineProperty(F.prototype,"reason",{enumerable:true});Object.defineProperty(F.prototype,"wasClean",{enumerable:true});var X=class extends P{constructor(e,s={}){super(e),this[gt]=s.error===void 0?null:s.error,this[yt]=s.message===void 0?"":s.message;}get error(){return this[gt]}get message(){return this[yt]}};Object.defineProperty(X.prototype,"error",{enumerable:true});Object.defineProperty(X.prototype,"message",{enumerable:true});var se=class extends P{constructor(e,s={}){super(e),this[pt]=s.data===void 0?null:s.data;}get data(){return this[pt]}};Object.defineProperty(se.prototype,"data",{enumerable:true});var Ts={addEventListener(t,e,s={}){for(let i of this.listeners(t))if(!s[te]&&i[De]===e&&!i[te])return;let r;if(t==="message")r=function(n,o){let f=new se("message",{data:o?n:n.toString()});f[K]=this,de(e,this,f);};else if(t==="close")r=function(n,o){let f=new F("close",{code:n,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});f[K]=this,de(e,this,f);};else if(t==="error")r=function(n){let o=new X("error",{error:n,message:n.message});o[K]=this,de(e,this,o);};else if(t==="open")r=function(){let n=new P("open");n[K]=this,de(e,this,n);};else return;r[te]=!!s[te],r[De]=e,s.once?this.once(t,r):this.on(t,r);},removeEventListener(t,e){for(let s of this.listeners(t))if(s[De]===e&&!s[te]){this.removeListener(t,s);break}}};vt.exports={CloseEvent:F,ErrorEvent:X,Event:P,EventTarget:Ts,MessageEvent:se};function de(t,e,s){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,s):t.call(e,s);}});var _e=c((qr,wt)=>{g();var{tokenChars:re}=z();function C(t,e,s){t[e]===void 0?t[e]=[s]:t[e].push(s);}function ks(t){let e=Object.create(null),s=Object.create(null),r=false,i=false,n=false,o,f,l=-1,a=-1,h=-1,c=0;for(;c<t.length;c++)if(a=t.charCodeAt(c),o===void 0)if(h===-1&&re[a]===1)l===-1&&(l=c);else if(c!==0&&(a===32||a===9))h===-1&&l!==-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c);let y=t.slice(l,h);a===44?(C(e,y,s),s=Object.create(null)):o=y,l=h=-1;}else throw new SyntaxError(`Unexpected character at index ${c}`);else if(f===void 0)if(h===-1&&re[a]===1)l===-1&&(l=c);else if(a===32||a===9)h===-1&&l!==-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c),C(s,t.slice(l,h),true),a===44&&(C(e,o,s),s=Object.create(null),o=void 0),l=h=-1;}else if(a===61&&l!==-1&&h===-1)f=t.slice(l,c),l=h=-1;else throw new SyntaxError(`Unexpected character at index ${c}`);else if(i){if(re[a]!==1)throw new SyntaxError(`Unexpected character at index ${c}`);l===-1?l=c:r||(r=true),i=false;}else if(n)if(re[a]===1)l===-1&&(l=c);else if(a===34&&l!==-1)n=false,h=c;else if(a===92)i=true;else throw new SyntaxError(`Unexpected character at index ${c}`);else if(a===34&&t.charCodeAt(c-1)===61)n=true;else if(h===-1&&re[a]===1)l===-1&&(l=c);else if(l!==-1&&(a===32||a===9))h===-1&&(h=c);else if(a===59||a===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${c}`);h===-1&&(h=c);let y=t.slice(l,h);r&&(y=y.replace(/\\/g,""),r=false),C(s,f,y),a===44&&(C(e,o,s),s=Object.create(null),o=void 0),f=void 0,l=h=-1;}else throw new SyntaxError(`Unexpected character at index ${c}`);if(l===-1||n||a===32||a===9)throw new SyntaxError("Unexpected end of input");h===-1&&(h=c);let m=t.slice(l,h);return o===void 0?C(e,m,s):(f===void 0?C(s,m,true):r?C(s,f,m.replace(/\\/g,"")):C(s,f,m),C(e,o,s)),e}function Cs(t){return Object.keys(t).map(e=>{let s=t[e];return Array.isArray(s)||(s=[s]),s.map(r=>[e].concat(Object.keys(r).map(i=>{let n=r[i];return Array.isArray(n)||(n=[n]),n.map(o=>o===true?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}wt.exports={format:Cs,parse:ks};});var ye=c((Vr,Dt)=>{g();var Ls=a("events"),Ns=a("https"),Ps=a("http"),kt=a("net"),Bs=a("tls"),{randomBytes:Rs,createHash:Us}=a("crypto"),{Duplex:$r,Readable:jr}=a("stream"),{URL:Me}=a("url"),I=V(),Is=Be(),Ds=Ie(),{isBlob:Ms}=z(),{BINARY_TYPES:Ot,CLOSE_TIMEOUT:Fs,EMPTY_BUFFER:me,GUID:As,kForOnEventAttribute:Fe,kListener:Ws,kStatusCode:qs,kWebSocket:x,NOOP:Ct}=L(),{EventTarget:{addEventListener:Gs,removeEventListener:$s}}=bt(),{format:js,parse:Vs}=_e(),{toBuffer:zs}=J(),Lt=Symbol("kAborted"),Ae=[8,13],B=["CONNECTING","OPEN","CLOSING","CLOSED"],Hs=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,_=class t extends Ls{constructor(e,s,r){super(),this._binaryType=Ot[0],this._closeCode=1006,this._closeFrameReceived=false,this._closeFrameSent=false,this._closeMessage=me,this._closeTimer=null,this._errorEmitted=false,this._extensions={},this._paused=false,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=false,this._redirects=0,s===void 0?s=[]:Array.isArray(s)||(typeof s=="object"&&s!==null?(r=s,s=[]):s=[s]),Nt(this,e,s,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=true);}get binaryType(){return this._binaryType}set binaryType(e){Ot.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e));}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,s,r){let i=new Is({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),n=new Ds(e,this._extensions,r.generateMask);this._receiver=i,this._sender=n,this._socket=e,i[x]=this,n[x]=this,e[x]=this,i.on("conclude",Xs),i.on("drain",Zs),i.on("error",Qs),i.on("message",Js),i.on("ping",er),i.on("pong",tr),n.onerror=sr,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),s.length>0&&e.unshift(s),e.on("close",Rt),e.on("data",ge),e.on("end",Ut),e.on("error",It),this._readyState=t.OPEN,this.emit("open");}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[I.extensionName]&&this._extensions[I.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);}close(e,s){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){w(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,s,!this._isServer,r=>{r||(this._closeFrameSent=true,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end());}),Bt(this);}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=true,this._socket.pause());}ping(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=s=void 0):typeof s=="function"&&(r=s,s=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){We(this,e,r);return}s===void 0&&(s=!this._isServer),this._sender.ping(e||me,s,r);}pong(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=s=void 0):typeof s=="function"&&(r=s,s=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){We(this,e,r);return}s===void 0&&(s=!this._isServer),this._sender.pong(e||me,s,r);}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=false,this._receiver._writableState.needDrain||this._socket.resume());}send(e,s,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof s=="function"&&(r=s,s={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){We(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:true,fin:true,...s};this._extensions[I.extensionName]||(i.compress=false),this._sender.send(e||me,i,r);}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){w(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy());}}};Object.defineProperty(_,"CONNECTING",{enumerable:true,value:B.indexOf("CONNECTING")});Object.defineProperty(_.prototype,"CONNECTING",{enumerable:true,value:B.indexOf("CONNECTING")});Object.defineProperty(_,"OPEN",{enumerable:true,value:B.indexOf("OPEN")});Object.defineProperty(_.prototype,"OPEN",{enumerable:true,value:B.indexOf("OPEN")});Object.defineProperty(_,"CLOSING",{enumerable:true,value:B.indexOf("CLOSING")});Object.defineProperty(_.prototype,"CLOSING",{enumerable:true,value:B.indexOf("CLOSING")});Object.defineProperty(_,"CLOSED",{enumerable:true,value:B.indexOf("CLOSED")});Object.defineProperty(_.prototype,"CLOSED",{enumerable:true,value:B.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(_.prototype,t,{enumerable:true});});["open","error","close","message"].forEach(t=>{Object.defineProperty(_.prototype,`on${t}`,{enumerable:true,get(){for(let e of this.listeners(t))if(e[Fe])return e[Ws];return null},set(e){for(let s of this.listeners(t))if(s[Fe]){this.removeListener(t,s);break}typeof e=="function"&&this.addEventListener(t,e,{[Fe]:true});}});});_.prototype.addEventListener=Gs;_.prototype.removeEventListener=$s;Dt.exports=_;function Nt(t,e,s,r){let i={allowSynchronousEvents:true,autoPong:true,closeTimeout:Fs,protocolVersion:Ae[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:false,perMessageDeflate:true,followRedirects:false,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!Ae.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Ae.join(", ")})`);let n;if(e instanceof Me)n=e;else try{n=new Me(e);}catch{throw new SyntaxError(`Invalid URL: ${e}`)}n.protocol==="http:"?n.protocol="ws:":n.protocol==="https:"&&(n.protocol="wss:"),t._url=n.href;let o=n.protocol==="wss:",f=n.protocol==="ws+unix:",l;if(n.protocol!=="ws:"&&!o&&!f?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:f&&!n.pathname?l="The URL's pathname is empty":n.hash&&(l="The URL contains a fragment identifier"),l){let u=new SyntaxError(l);if(t._redirects===0)throw u;pe(t,u);return}let a=o?443:80,h=Rs(16).toString("base64"),c=o?Ns.request:Ps.request,m=new Set,y;if(i.createConnection=i.createConnection||(o?Ks:Ys),i.defaultPort=i.defaultPort||a,i.port=n.port||a,i.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":h,Connection:"Upgrade",Upgrade:"websocket"},i.path=n.pathname+n.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(y=new I({...i.perMessageDeflate,isServer:false,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=js({[I.extensionName]:y.offer()})),s.length){for(let u of s){if(typeof u!="string"||!Hs.test(u)||m.has(u))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(u);}i.headers["Sec-WebSocket-Protocol"]=s.join(",");}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(n.username||n.password)&&(i.auth=`${n.username}:${n.password}`),f){let u=i.path.split(":");i.socketPath=u[0],i.path=u[1];}let p;if(i.followRedirects){if(t._redirects===0){t._originalIpc=f,t._originalSecure=o,t._originalHostOrSocketPath=f?i.socketPath:n.host;let u=r&&r.headers;if(r={...r,headers:{}},u)for(let[S,q]of Object.entries(u))r.headers[S.toLowerCase()]=q;}else if(t.listenerCount("redirect")===0){let u=f?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:false:t._originalIpc?false:n.host===t._originalHostOrSocketPath;(!u||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,u||delete i.headers.host,i.auth=void 0);}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),p=t._req=c(i),t._redirects&&t.emit("redirect",t.url,p);}else p=t._req=c(i);i.timeout&&p.on("timeout",()=>{w(t,p,"Opening handshake has timed out");}),p.on("error",u=>{p===null||p[Lt]||(p=t._req=null,pe(t,u));}),p.on("response",u=>{let S=u.headers.location,q=u.statusCode;if(S&&i.followRedirects&&q>=300&&q<400){if(++t._redirects>i.maxRedirects){w(t,p,"Maximum redirects exceeded");return}p.abort();let Z;try{Z=new Me(S,e);}catch{let G=new SyntaxError(`Invalid URL: ${S}`);pe(t,G);return}Nt(t,Z,s,r);}else t.emit("unexpected-response",p,u)||w(t,p,`Unexpected server response: ${u.statusCode}`);}),p.on("upgrade",(u,S,q)=>{if(t.emit("upgrade",u),t.readyState!==_.CONNECTING)return;p=t._req=null;let Z=u.headers.upgrade;if(Z===void 0||Z.toLowerCase()!=="websocket"){w(t,S,"Invalid Upgrade header");return}let $e=Us("sha1").update(h+As).digest("base64");if(u.headers["sec-websocket-accept"]!==$e){w(t,S,"Invalid Sec-WebSocket-Accept header");return}let G=u.headers["sec-websocket-protocol"],Q;if(G!==void 0?m.size?m.has(G)||(Q="Server sent an invalid subprotocol"):Q="Server sent a subprotocol but none was requested":m.size&&(Q="Server sent no subprotocol"),Q){w(t,S,Q);return}G&&(t._protocol=G);let je=u.headers["sec-websocket-extensions"];if(je!==void 0){if(!y){w(t,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Se;try{Se=Vs(je);}catch{w(t,S,"Invalid Sec-WebSocket-Extensions header");return}let Ve=Object.keys(Se);if(Ve.length!==1||Ve[0]!==I.extensionName){w(t,S,"Server indicated an extension that was not requested");return}try{y.accept(Se[I.extensionName]);}catch{w(t,S,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[I.extensionName]=y;}t.setSocket(S,q,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation});}),i.finishRequest?i.finishRequest(p,t):p.end();}function pe(t,e){t._readyState=_.CLOSING,t._errorEmitted=true,t.emit("error",e),t.emitClose();}function Ys(t){return t.path=t.socketPath,kt.connect(t)}function Ks(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=kt.isIP(t.host)?"":t.host),Bs.connect(t)}function w(t,e,s){t._readyState=_.CLOSING;let r=new Error(s);Error.captureStackTrace(r,w),e.setHeader?(e[Lt]=true,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(pe,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)));}function We(t,e,s){if(e){let r=Ms(e)?e.size:zs(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r;}if(s){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${B[t.readyState]})`);process.nextTick(s,r);}}function Xs(t,e){let s=this[x];s._closeFrameReceived=true,s._closeMessage=e,s._closeCode=t,s._socket[x]!==void 0&&(s._socket.removeListener("data",ge),process.nextTick(Pt,s._socket),t===1005?s.close():s.close(t,e));}function Zs(){let t=this[x];t.isPaused||t._socket.resume();}function Qs(t){let e=this[x];e._socket[x]!==void 0&&(e._socket.removeListener("data",ge),process.nextTick(Pt,e._socket),e.close(t[qs])),e._errorEmitted||(e._errorEmitted=true,e.emit("error",t));}function Tt(){this[x].emitClose();}function Js(t,e){this[x].emit("message",t,e);}function er(t){let e=this[x];e._autoPong&&e.pong(t,!this._isServer,Ct),e.emit("ping",t);}function tr(t){this[x].emit("pong",t);}function Pt(t){t.resume();}function sr(t){let e=this[x];e.readyState!==_.CLOSED&&(e.readyState===_.OPEN&&(e._readyState=_.CLOSING,Bt(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=true,e.emit("error",t)));}function Bt(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout);}function Rt(){let t=this[x];if(this.removeListener("close",Rt),this.removeListener("data",ge),this.removeListener("end",Ut),t._readyState=_.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e);}t._receiver.end(),this[x]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Tt),t._receiver.on("finish",Tt));}function ge(t){this[x]._receiver.write(t)||this.pause();}function Ut(){let t=this[x];t._readyState=_.CLOSING,t._receiver.end(),this.end();}function It(){let t=this[x];this.removeListener("error",It),this.on("error",Ct),t&&(t._readyState=_.CLOSING,this.destroy());}});var Wt=c((Yr,At)=>{g();ye();var {Duplex:rr}=a("stream");function Mt(t){t.emit("close");}function ir(){!this.destroyed&&this._writableState.finished&&this.destroy();}function Ft(t){this.removeListener("error",Ft),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t);}function nr(t,e){let s=true,r=new rr({...e,autoDestroy:false,emitClose:false,objectMode:false,writableObjectMode:false});return t.on("message",function(n,o){let f=!o&&r._readableState.objectMode?n.toString():n;r.push(f)||t.pause();}),t.once("error",function(n){r.destroyed||(s=false,r.destroy(n));}),t.once("close",function(){r.destroyed||r.push(null);}),r._destroy=function(i,n){if(t.readyState===t.CLOSED){n(i),process.nextTick(Mt,r);return}let o=false;t.once("error",function(l){o=true,n(l);}),t.once("close",function(){o||n(i),process.nextTick(Mt,r);}),s&&t.terminate();},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i);});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i();}),t.close()));},r._read=function(){t.isPaused&&t.resume();},r._write=function(i,n,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,n,o);});return}t.send(i,o);},r.on("end",ir),r.on("error",Ft),r}At.exports=nr;});var qe=c((Xr,qt)=>{g();var{tokenChars:or}=z();function ar(t){let e=new Set,s=-1,r=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(r===-1&&or[o]===1)s===-1&&(s=i);else if(i!==0&&(o===32||o===9))r===-1&&s!==-1&&(r=i);else if(o===44){if(s===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let f=t.slice(s,r);if(e.has(f))throw new SyntaxError(`The "${f}" subprotocol is duplicated`);e.add(f),s=r=-1;}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(s===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let n=t.slice(s,i);if(e.has(n))throw new SyntaxError(`The "${n}" subprotocol is duplicated`);return e.add(n),e}qt.exports={parse:ar};});var Yt=c((Jr,Ht)=>{g();var fr=a("events"),xe=a("http"),{Duplex:Qr}=a("stream"),{createHash:lr}=a("crypto"),Gt=_e(),A=V(),hr=qe(),cr=ye(),{CLOSE_TIMEOUT:ur,GUID:dr,kWebSocket:_r}=L(),mr=/^[+/0-9A-Za-z]{22}==$/,$t=0,jt=1,zt=2,Ge=class extends fr{constructor(e,s){if(super(),e={allowSynchronousEvents:true,autoPong:true,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:false,perMessageDeflate:false,handleProtocols:null,clientTracking:true,closeTimeout:ur,verifyClient:null,noServer:false,backlog:null,server:null,host:null,path:null,port:null,WebSocket:cr,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=xe.createServer((r,i)=>{let n=xe.STATUS_CODES[426];i.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),i.end(n);}),this._server.listen(e.port,e.host,e.backlog,s)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=pr(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,n,o)=>{this.handleUpgrade(i,n,o,r);}});}e.perMessageDeflate===true&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=false),this.options=e,this._state=$t;}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===zt){e&&this.once("close",()=>{e(new Error("The server is not running"));}),process.nextTick(ie,this);return}if(e&&this.once("close",e),this._state!==jt)if(this._state=jt,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=true:process.nextTick(ie,this):process.nextTick(ie,this);else {let s=this._server;this._removeListeners(),this._removeListeners=this._server=null,s.close(()=>{ie(this);});}}shouldHandle(e){if(this.options.path){let s=e.url.indexOf("?");if((s!==-1?e.url.slice(0,s):e.url)!==this.options.path)return false}return true}handleUpgrade(e,s,r,i){s.on("error",Vt);let n=e.headers["sec-websocket-key"],o=e.headers.upgrade,f=+e.headers["sec-websocket-version"];if(e.method!=="GET"){W(this,e,s,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){W(this,e,s,400,"Invalid Upgrade header");return}if(n===void 0||!mr.test(n)){W(this,e,s,400,"Missing or invalid Sec-WebSocket-Key header");return}if(f!==13&&f!==8){W(this,e,s,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ne(s,400);return}let l=e.headers["sec-websocket-protocol"],a=new Set;if(l!==void 0)try{a=hr.parse(l);}catch{W(this,e,s,400,"Invalid Sec-WebSocket-Protocol header");return}let h=e.headers["sec-websocket-extensions"],c={};if(this.options.perMessageDeflate&&h!==void 0){let m=new A({...this.options.perMessageDeflate,isServer:true,maxPayload:this.options.maxPayload});try{let y=Gt.parse(h);y[A.extensionName]&&(m.accept(y[A.extensionName]),c[A.extensionName]=m);}catch{W(this,e,s,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${f===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(y,p,u,S)=>{if(!y)return ne(s,p||401,u,S);this.completeUpgrade(c,n,a,e,s,r,i);});return}if(!this.options.verifyClient(m))return ne(s,401)}this.completeUpgrade(c,n,a,e,s,r,i);}completeUpgrade(e,s,r,i,n,o,f){if(!n.readable||!n.writable)return n.destroy();if(n[_r])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>$t)return ne(n,503);let a=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${lr("sha1").update(s+dr).digest("base64")}`],h=new this.options.WebSocket(null,void 0,this.options);if(r.size){let c=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;c&&(a.push(`Sec-WebSocket-Protocol: ${c}`),h._protocol=c);}if(e[A.extensionName]){let c=e[A.extensionName].params,m=Gt.format({[A.extensionName]:[c]});a.push(`Sec-WebSocket-Extensions: ${m}`),h._extensions=e;}this.emit("headers",a,i),n.write(a.concat(`\r
|
|
3
|
+
`).join(`\r
|
|
4
|
+
`)),n.removeListener("error",Vt),h.setSocket(n,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(h),h.on("close",()=>{this.clients.delete(h),this._shouldEmitClose&&!this.clients.size&&process.nextTick(ie,this);})),f(h,i);}};Ht.exports=Ge;function pr(t,e){for(let s of Object.keys(e))t.on(s,e[s]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r]);}}function ie(t){t._state=zt,t.emit("close");}function Vt(){this.destroy();}function ne(t,e,s,r){s=s||xe.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(s),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${xe.STATUS_CODES[e]}\r
|
|
5
|
+
`+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
|
|
6
|
+
`)+`\r
|
|
7
|
+
\r
|
|
8
|
+
`+s);}function W(t,e,s,r,i,n){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,W),t.emit("wsClientError",o,s,e);}else ne(s,r,i,n);}});g();e(Wt(),1);e(_e(),1);e(V(),1);e(Be(),1);e(Ie(),1);e(qe(),1);var Kt=e(ye(),1),br=e(Yt(),1);var ti=Kt.default;export{Kt as a,br as b,ti as c};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
'use strict';var chunkXPPVX4GQ_cjs=require('./chunk-XPPVX4GQ.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),fs=require('fs'),path=require('path');var oe=chunkBUNLC3II_cjs.c((yr,Me)=>{chunkBUNLC3II_cjs.h();var Ct=chunkBUNLC3II_cjs.a("path"),z="\\\\/",Be=`[^${z}]`,$t=0,V="\\.",mt="\\+",Ht="\\?",pe="\\/",Tt="(?=.)",Pe="[^/]",Re=`(?:${pe}|$)`,De=`(?:^|${pe})`,_e=`${V}{1,2}${Re}`,Lt=`(?!${V})`,Ot=`(?!${De}${_e})`,vt=`(?!${V}{0,1}${Re})`,wt=`(?!${_e})`,It=`[^.${pe}]`,kt=`${Pe}*?`,Ge={DOT_LITERAL:V,PLUS_LITERAL:mt,QMARK_LITERAL:Ht,SLASH_LITERAL:pe,ONE_CHAR:Tt,QMARK:Pe,END_ANCHOR:Re,DOTS_SLASH:_e,NO_DOT:Lt,NO_DOTS:Ot,NO_DOT_SLASH:vt,NO_DOTS_SLASH:wt,QMARK_NO_DOT:It,STAR:kt,START_ANCHOR:De},Nt={...Ge,SLASH_LITERAL:`[${z}]`,QMARK:Be,STAR:`${Be}*?`,DOTS_SLASH:`${V}{1,2}(?:[${z}]|$)`,NO_DOT:`(?!${V})`,NO_DOTS:`(?!(?:^|[${z}])${V}{1,2}(?:[${z}]|$))`,NO_DOT_SLASH:`(?!${V}{0,1}(?:[${z}]|$))`,NO_DOTS_SLASH:`(?!${V}{1,2}(?:[${z}]|$))`,QMARK_NO_DOT:`[^.${z}]`,START_ANCHOR:`(?:^|[${z}])`,END_ANCHOR:`(?:[${z}]|$)`},Bt={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};Me.exports={DEFAULT_MAX_EXTGLOB_RECURSION:$t,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:Bt,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:Ct.sep,extglobChars(e){return {"!":{type:"negate",open:"(?:(?!(?:",close:`))${e.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(e){return e===true?Nt:Ge}};});var fe=chunkBUNLC3II_cjs.c(M=>{chunkBUNLC3II_cjs.h();var Pt=chunkBUNLC3II_cjs.a("path"),Dt=process.platform==="win32",{REGEX_BACKSLASH:Gt,REGEX_REMOVE_BACKSLASH:Mt,REGEX_SPECIAL_CHARS:Ft,REGEX_SPECIAL_CHARS_GLOBAL:Ut}=oe();M.isObject=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);M.hasRegexChars=e=>Ft.test(e);M.isRegexChar=e=>e.length===1&&M.hasRegexChars(e);M.escapeRegex=e=>e.replace(Ut,"\\$1");M.toPosixSlashes=e=>e.replace(Gt,"/");M.removeBackslashes=e=>e.replace(Mt,r=>r==="\\"?"":r);M.supportsLookbehinds=()=>{let e=process.version.slice(1).split(".").map(Number);return e.length===3&&e[0]>=9||e[0]===8&&e[1]>=10};M.isWindows=e=>e&&typeof e.windows=="boolean"?e.windows:Dt===true||Pt.sep==="\\";M.escapeLast=(e,r,t)=>{let i=e.lastIndexOf(r,t);return i===-1?e:e[i-1]==="\\"?M.escapeLast(e,r,i-1):`${e.slice(0,i)}\\${e.slice(i)}`};M.removePrefix=(e,r={})=>{let t=e;return t.startsWith("./")&&(t=t.slice(2),r.prefix="./"),t};M.wrapOutput=(e,r={},t={})=>{let i=t.contains?"":"^",a=t.contains?"":"$",p=`${i}(?:${e})${a}`;return r.negated===true&&(p=`(?:^(?!${p}).*$)`),p};});var je=chunkBUNLC3II_cjs.c(($r,Qe)=>{chunkBUNLC3II_cjs.h();var Fe=fe(),{CHAR_ASTERISK:ge,CHAR_AT:Kt,CHAR_BACKWARD_SLASH:ue,CHAR_COMMA:qt,CHAR_DOT:Ee,CHAR_EXCLAMATION_MARK:de,CHAR_FORWARD_SLASH:We,CHAR_LEFT_CURLY_BRACE:xe,CHAR_LEFT_PARENTHESES:ye,CHAR_LEFT_SQUARE_BRACKET:Xt,CHAR_PLUS:Wt,CHAR_QUESTION_MARK:Ue,CHAR_RIGHT_CURLY_BRACE:Qt,CHAR_RIGHT_PARENTHESES:Ke,CHAR_RIGHT_SQUARE_BRACKET:jt}=oe(),qe=e=>e===We||e===ue,Xe=e=>{e.isPrefix!==true&&(e.depth=e.isGlobstar?1/0:1);},zt=(e,r)=>{let t=r||{},i=e.length-1,a=t.parts===true||t.scanToEnd===true,p=[],u=[],f=[],h=e,d=-1,R=0,$=0,O=false,P=false,y=false,T=false,Y=false,K=false,U=false,L=false,q=false,N=false,J=0,D,A,x={value:"",depth:0,isGlob:false},k=()=>d>=i,o=()=>h.charCodeAt(d+1),m=()=>(D=A,h.charCodeAt(++d));for(;d<i;){A=m();let G;if(A===ue){U=x.backslashes=true,A=m(),A===xe&&(K=true);continue}if(K===true||A===xe){for(J++;k()!==true&&(A=m());){if(A===ue){U=x.backslashes=true,m();continue}if(A===xe){J++;continue}if(K!==true&&A===Ee&&(A=m())===Ee){if(O=x.isBrace=true,y=x.isGlob=true,N=true,a===true)continue;break}if(K!==true&&A===qt){if(O=x.isBrace=true,y=x.isGlob=true,N=true,a===true)continue;break}if(A===Qt&&(J--,J===0)){K=false,O=x.isBrace=true,N=true;break}}if(a===true)continue;break}if(A===We){if(p.push(d),u.push(x),x={value:"",depth:0,isGlob:false},N===true)continue;if(D===Ee&&d===R+1){R+=2;continue}$=d+1;continue}if(t.noext!==true&&(A===Wt||A===Kt||A===ge||A===Ue||A===de)===true&&o()===ye){if(y=x.isGlob=true,T=x.isExtglob=true,N=true,A===de&&d===R&&(q=true),a===true){for(;k()!==true&&(A=m());){if(A===ue){U=x.backslashes=true,A=m();continue}if(A===Ke){y=x.isGlob=true,N=true;break}}continue}break}if(A===ge){if(D===ge&&(Y=x.isGlobstar=true),y=x.isGlob=true,N=true,a===true)continue;break}if(A===Ue){if(y=x.isGlob=true,N=true,a===true)continue;break}if(A===Xt){for(;k()!==true&&(G=m());){if(G===ue){U=x.backslashes=true,m();continue}if(G===jt){P=x.isBracket=true,y=x.isGlob=true,N=true;break}}if(a===true)continue;break}if(t.nonegate!==true&&A===de&&d===R){L=x.negated=true,R++;continue}if(t.noparen!==true&&A===ye){if(y=x.isGlob=true,a===true){for(;k()!==true&&(A=m());){if(A===ye){U=x.backslashes=true,A=m();continue}if(A===Ke){N=true;break}}continue}break}if(y===true){if(N=true,a===true)continue;break}}t.noext===true&&(T=false,y=false);let S=h,ee="",n="";R>0&&(ee=h.slice(0,R),h=h.slice(R),$-=R),S&&y===true&&$>0?(S=h.slice(0,$),n=h.slice($)):y===true?(S="",n=h):S=h,S&&S!==""&&S!=="/"&&S!==h&&qe(S.charCodeAt(S.length-1))&&(S=S.slice(0,-1)),t.unescape===true&&(n&&(n=Fe.removeBackslashes(n)),S&&U===true&&(S=Fe.removeBackslashes(S)));let s={prefix:ee,input:e,start:R,base:S,glob:n,isBrace:O,isBracket:P,isGlob:y,isExtglob:T,isGlobstar:Y,negated:L,negatedExtglob:q};if(t.tokens===true&&(s.maxDepth=0,qe(A)||u.push(x),s.tokens=u),t.parts===true||t.tokens===true){let G;for(let E=0;E<p.length;E++){let X=G?G+1:R,W=p[E],F=e.slice(X,W);t.tokens&&(E===0&&R!==0?(u[E].isPrefix=true,u[E].value=ee):u[E].value=F,Xe(u[E]),s.maxDepth+=u[E].depth),(E!==0||F!=="")&&f.push(F),G=W;}if(G&&G+1<e.length){let E=e.slice(G+1);f.push(E),t.tokens&&(u[u.length-1].value=E,Xe(u[u.length-1]),s.maxDepth+=u[u.length-1].depth);}s.slashes=p,s.parts=f;}return s};Qe.exports=zt;});var Je=chunkBUNLC3II_cjs.c((Hr,Ye)=>{chunkBUNLC3II_cjs.h();var ae=oe(),B=fe(),{MAX_LENGTH:he,POSIX_REGEX_SOURCE:Vt,REGEX_NON_SPECIAL_CHARS:Zt,REGEX_SPECIAL_CHARS_BACKREF:Yt,REPLACEMENTS:ze}=ae,Jt=(e,r)=>{if(typeof r.expandRange=="function")return r.expandRange(...e,r);e.sort();let t=`[${e.join("-")}]`;try{new RegExp(t);}catch{return e.map(a=>B.escapeRegex(a)).join("..")}return t},se=(e,r)=>`Missing ${e}: "${r}" - use "\\\\${r}" to match literal characters`,Ve=e=>{let r=[],t=0,i=0,a=0,p="",u=false;for(let f of e){if(u===true){p+=f,u=false;continue}if(f==="\\"){p+=f,u=true;continue}if(f==='"'){a=a===1?0:1,p+=f;continue}if(a===0){if(f==="[")t++;else if(f==="]"&&t>0)t--;else if(t===0){if(f==="(")i++;else if(f===")"&&i>0)i--;else if(f==="|"&&i===0){r.push(p),p="";continue}}}p+=f;}return r.push(p),r},er=e=>{let r=false;for(let t of e){if(r===true){r=false;continue}if(t==="\\"){r=true;continue}if(/[?*+@!()[\]{}]/.test(t))return false}return true},Ze=e=>{let r=e.trim(),t=true;for(;t===true;)t=false,/^@\([^\\()[\]{}|]+\)$/.test(r)&&(r=r.slice(2,-1),t=true);if(er(r))return r.replace(/\\(.)/g,"$1")},tr=e=>{let r=e.map(Ze).filter(Boolean);for(let t=0;t<r.length;t++)for(let i=t+1;i<r.length;i++){let a=r[t],p=r[i],u=a[0];if(!(!u||a!==u.repeat(a.length)||p!==u.repeat(p.length))&&(a===p||a.startsWith(p)||p.startsWith(a)))return true}return false},be=(e,r=true)=>{if(e[0]!=="+"&&e[0]!=="*"||e[1]!=="(")return;let t=0,i=0,a=0,p=false;for(let u=1;u<e.length;u++){let f=e[u];if(p===true){p=false;continue}if(f==="\\"){p=true;continue}if(f==='"'){a=a===1?0:1;continue}if(a!==1){if(f==="["){t++;continue}if(f==="]"&&t>0){t--;continue}if(!(t>0)){if(f==="("){i++;continue}if(f===")"&&(i--,i===0))return r===true&&u!==e.length-1?void 0:{type:e[0],body:e.slice(2,u),end:u}}}}},rr=e=>{let r=0,t=[];for(;r<e.length;){let a=be(e.slice(r),false);if(!a||a.type!=="*")return;let p=Ve(a.body).map(f=>f.trim());if(p.length!==1)return;let u=Ze(p[0]);if(!u||u.length!==1)return;t.push(u),r+=a.end+1;}return t.length<1?void 0:`${t.length===1?B.escapeRegex(t[0]):`[${t.map(a=>B.escapeRegex(a)).join("")}]`}*`},nr=e=>{let r=0,t=e.trim(),i=be(t);for(;i;)r++,t=i.body.trim(),i=be(t);return r},sr=(e,r)=>{if(r.maxExtglobRecursion===false)return {risky:false};let t=typeof r.maxExtglobRecursion=="number"?r.maxExtglobRecursion:ae.DEFAULT_MAX_EXTGLOB_RECURSION,i=Ve(e).map(a=>a.trim());if(i.length>1&&(i.some(a=>a==="")||i.some(a=>/^[*?]+$/.test(a))||tr(i)))return {risky:true};for(let a of i){let p=rr(a);if(p)return {risky:true,safeOutput:p};if(nr(a)>t)return {risky:true}}return {risky:false}},Se=(e,r)=>{if(typeof e!="string")throw new TypeError("Expected a string");e=ze[e]||e;let t={...r},i=typeof t.maxLength=="number"?Math.min(he,t.maxLength):he,a=e.length;if(a>i)throw new SyntaxError(`Input length: ${a}, exceeds maximum allowed length: ${i}`);let p={type:"bos",value:"",output:t.prepend||""},u=[p],f=t.capture?"":"?:",h=B.isWindows(r),d=ae.globChars(h),R=ae.extglobChars(d),{DOT_LITERAL:$,PLUS_LITERAL:O,SLASH_LITERAL:P,ONE_CHAR:y,DOTS_SLASH:T,NO_DOT:Y,NO_DOT_SLASH:K,NO_DOTS_SLASH:U,QMARK:L,QMARK_NO_DOT:q,STAR:N,START_ANCHOR:J}=d,D=l=>`(${f}(?:(?!${J}${l.dot?T:$}).)*?)`,A=t.dot?"":Y,x=t.dot?L:q,k=t.bash===true?D(t):N;t.capture&&(k=`(${k})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let o={input:e,index:-1,start:0,dot:t.dot===true,consumed:"",output:"",prefix:"",backtrack:false,negated:false,brackets:0,braces:0,parens:0,quotes:0,globstar:false,tokens:u};e=B.removePrefix(e,o),a=e.length;let m=[],S=[],ee=[],n=p,s,G=()=>o.index===a-1,E=o.peek=(l=1)=>e[o.index+l],X=o.advance=()=>e[++o.index]||"",W=()=>e.slice(o.index+1),F=(l="",H=0)=>{o.consumed+=l,o.index+=H;},ie=l=>{o.output+=l.output!=null?l.output:l.value,F(l.value);},xt=()=>{let l=1;for(;E()==="!"&&(E(2)!=="("||E(3)==="?");)X(),o.start++,l++;return l%2===0?false:(o.negated=true,o.start++,true)},ce=l=>{o[l]++,ee.push(l);},te=l=>{o[l]--,ee.pop();},g=l=>{if(n.type==="globstar"){let H=o.braces>0&&(l.type==="comma"||l.type==="brace"),c=l.extglob===true||m.length&&(l.type==="pipe"||l.type==="paren");l.type!=="slash"&&l.type!=="paren"&&!H&&!c&&(o.output=o.output.slice(0,-n.output.length),n.type="star",n.value="*",n.output=k,o.output+=n.output);}if(m.length&&l.type!=="paren"&&(m[m.length-1].inner+=l.value),(l.value||l.output)&&ie(l),n&&n.type==="text"&&l.type==="text"){n.value+=l.value,n.output=(n.output||"")+l.value;return}l.prev=n,u.push(l),n=l;},le=(l,H)=>{let c={...R[H],conditions:1,inner:""};c.prev=n,c.parens=o.parens,c.output=o.output,c.startIndex=o.index,c.tokensIndex=u.length;let _=(t.capture?"(":"")+c.open;ce("parens"),g({type:l,value:H,output:o.output?"":y}),g({type:"paren",extglob:true,value:X(),output:_}),m.push(c);},yt=l=>{let H=e.slice(l.startIndex,o.index+1),c=e.slice(l.startIndex+2,o.index),_=sr(c,t);if((l.type==="plus"||l.type==="star")&&_.risky){let b=_.safeOutput?(l.output?"":y)+(t.capture?`(${_.safeOutput})`:_.safeOutput):void 0,Q=u[l.tokensIndex];Q.type="text",Q.value=H,Q.output=b||B.escapeRegex(H);for(let j=l.tokensIndex+1;j<u.length;j++)u[j].value="",u[j].output="",delete u[j].suffix;o.output=l.output+Q.output,o.backtrack=true,g({type:"paren",extglob:true,value:s,output:""}),te("parens");return}let C=l.close+(t.capture?")":""),I;if(l.type==="negate"){let b=k;if(l.inner&&l.inner.length>1&&l.inner.includes("/")&&(b=D(t)),(b!==k||G()||/^\)+$/.test(W()))&&(C=l.close=`)$))${b}`),l.inner.includes("*")&&(I=W())&&/^\.[^\\/.]+$/.test(I)){let Q=Se(I,{...r,fastpaths:false}).output;C=l.close=`)${Q})${b})`;}l.prev.type==="bos"&&(o.negatedExtglob=true);}g({type:"paren",extglob:true,value:s,output:C}),te("parens");};if(t.fastpaths!==false&&!/(^[*!]|[/()[\]{}"])/.test(e)){let l=false,H=e.replace(Yt,(c,_,C,I,b,Q)=>I==="\\"?(l=true,c):I==="?"?_?_+I+(b?L.repeat(b.length):""):Q===0?x+(b?L.repeat(b.length):""):L.repeat(C.length):I==="."?$.repeat(C.length):I==="*"?_?_+I+(b?k:""):k:_?c:`\\${c}`);return l===true&&(t.unescape===true?H=H.replace(/\\/g,""):H=H.replace(/\\+/g,c=>c.length%2===0?"\\\\":c?"\\":"")),H===e&&t.contains===true?(o.output=e,o):(o.output=B.wrapOutput(H,o,r),o)}for(;!G();){if(s=X(),s==="\0")continue;if(s==="\\"){let c=E();if(c==="/"&&t.bash!==true||c==="."||c===";")continue;if(!c){s+="\\",g({type:"text",value:s});continue}let _=/^\\+/.exec(W()),C=0;if(_&&_[0].length>2&&(C=_[0].length,o.index+=C,C%2!==0&&(s+="\\")),t.unescape===true?s=X():s+=X(),o.brackets===0){g({type:"text",value:s});continue}}if(o.brackets>0&&(s!=="]"||n.value==="["||n.value==="[^")){if(t.posix!==false&&s===":"){let c=n.value.slice(1);if(c.includes("[")&&(n.posix=true,c.includes(":"))){let _=n.value.lastIndexOf("["),C=n.value.slice(0,_),I=n.value.slice(_+2),b=Vt[I];if(b){n.value=C+b,o.backtrack=true,X(),!p.output&&u.indexOf(n)===1&&(p.output=y);continue}}}(s==="["&&E()!==":"||s==="-"&&E()==="]")&&(s=`\\${s}`),s==="]"&&(n.value==="["||n.value==="[^")&&(s=`\\${s}`),t.posix===true&&s==="!"&&n.value==="["&&(s="^"),n.value+=s,ie({value:s});continue}if(o.quotes===1&&s!=='"'){s=B.escapeRegex(s),n.value+=s,ie({value:s});continue}if(s==='"'){o.quotes=o.quotes===1?0:1,t.keepQuotes===true&&g({type:"text",value:s});continue}if(s==="("){ce("parens"),g({type:"paren",value:s});continue}if(s===")"){if(o.parens===0&&t.strictBrackets===true)throw new SyntaxError(se("opening","("));let c=m[m.length-1];if(c&&o.parens===c.parens+1){yt(m.pop());continue}g({type:"paren",value:s,output:o.parens?")":"\\)"}),te("parens");continue}if(s==="["){if(t.nobracket===true||!W().includes("]")){if(t.nobracket!==true&&t.strictBrackets===true)throw new SyntaxError(se("closing","]"));s=`\\${s}`;}else ce("brackets");g({type:"bracket",value:s});continue}if(s==="]"){if(t.nobracket===true||n&&n.type==="bracket"&&n.value.length===1){g({type:"text",value:s,output:`\\${s}`});continue}if(o.brackets===0){if(t.strictBrackets===true)throw new SyntaxError(se("opening","["));g({type:"text",value:s,output:`\\${s}`});continue}te("brackets");let c=n.value.slice(1);if(n.posix!==true&&c[0]==="^"&&!c.includes("/")&&(s=`/${s}`),n.value+=s,ie({value:s}),t.literalBrackets===false||B.hasRegexChars(c))continue;let _=B.escapeRegex(n.value);if(o.output=o.output.slice(0,-n.value.length),t.literalBrackets===true){o.output+=_,n.value=_;continue}n.value=`(${f}${_}|${n.value})`,o.output+=n.value;continue}if(s==="{"&&t.nobrace!==true){ce("braces");let c={type:"brace",value:s,output:"(",outputIndex:o.output.length,tokensIndex:o.tokens.length};S.push(c),g(c);continue}if(s==="}"){let c=S[S.length-1];if(t.nobrace===true||!c){g({type:"text",value:s,output:s});continue}let _=")";if(c.dots===true){let C=u.slice(),I=[];for(let b=C.length-1;b>=0&&(u.pop(),C[b].type!=="brace");b--)C[b].type!=="dots"&&I.unshift(C[b].value);_=Jt(I,t),o.backtrack=true;}if(c.comma!==true&&c.dots!==true){let C=o.output.slice(0,c.outputIndex),I=o.tokens.slice(c.tokensIndex);c.value=c.output="\\{",s=_="\\}",o.output=C;for(let b of I)o.output+=b.output||b.value;}g({type:"brace",value:s,output:_}),te("braces"),S.pop();continue}if(s==="|"){m.length>0&&m[m.length-1].conditions++,g({type:"text",value:s});continue}if(s===","){let c=s,_=S[S.length-1];_&&ee[ee.length-1]==="braces"&&(_.comma=true,c="|"),g({type:"comma",value:s,output:c});continue}if(s==="/"){if(n.type==="dot"&&o.index===o.start+1){o.start=o.index+1,o.consumed="",o.output="",u.pop(),n=p;continue}g({type:"slash",value:s,output:P});continue}if(s==="."){if(o.braces>0&&n.type==="dot"){n.value==="."&&(n.output=$);let c=S[S.length-1];n.type="dots",n.output+=s,n.value+=s,c.dots=true;continue}if(o.braces+o.parens===0&&n.type!=="bos"&&n.type!=="slash"){g({type:"text",value:s,output:$});continue}g({type:"dot",value:s,output:$});continue}if(s==="?"){if(!(n&&n.value==="(")&&t.noextglob!==true&&E()==="("&&E(2)!=="?"){le("qmark",s);continue}if(n&&n.type==="paren"){let _=E(),C=s;if(_==="<"&&!B.supportsLookbehinds())throw new Error("Node.js v10 or higher is required for regex lookbehinds");(n.value==="("&&!/[!=<:]/.test(_)||_==="<"&&!/<([!=]|\w+>)/.test(W()))&&(C=`\\${s}`),g({type:"text",value:s,output:C});continue}if(t.dot!==true&&(n.type==="slash"||n.type==="bos")){g({type:"qmark",value:s,output:q});continue}g({type:"qmark",value:s,output:L});continue}if(s==="!"){if(t.noextglob!==true&&E()==="("&&(E(2)!=="?"||!/[!=<:]/.test(E(3)))){le("negate",s);continue}if(t.nonegate!==true&&o.index===0){xt();continue}}if(s==="+"){if(t.noextglob!==true&&E()==="("&&E(2)!=="?"){le("plus",s);continue}if(n&&n.value==="("||t.regex===false){g({type:"plus",value:s,output:O});continue}if(n&&(n.type==="bracket"||n.type==="paren"||n.type==="brace")||o.parens>0){g({type:"plus",value:s});continue}g({type:"plus",value:O});continue}if(s==="@"){if(t.noextglob!==true&&E()==="("&&E(2)!=="?"){g({type:"at",extglob:true,value:s,output:""});continue}g({type:"text",value:s});continue}if(s!=="*"){(s==="$"||s==="^")&&(s=`\\${s}`);let c=Zt.exec(W());c&&(s+=c[0],o.index+=c[0].length),g({type:"text",value:s});continue}if(n&&(n.type==="globstar"||n.star===true)){n.type="star",n.star=true,n.value+=s,n.output=k,o.backtrack=true,o.globstar=true,F(s);continue}let l=W();if(t.noextglob!==true&&/^\([^?]/.test(l)){le("star",s);continue}if(n.type==="star"){if(t.noglobstar===true){F(s);continue}let c=n.prev,_=c.prev,C=c.type==="slash"||c.type==="bos",I=_&&(_.type==="star"||_.type==="globstar");if(t.bash===true&&(!C||l[0]&&l[0]!=="/")){g({type:"star",value:s,output:""});continue}let b=o.braces>0&&(c.type==="comma"||c.type==="brace"),Q=m.length&&(c.type==="pipe"||c.type==="paren");if(!C&&c.type!=="paren"&&!b&&!Q){g({type:"star",value:s,output:""});continue}for(;l.slice(0,3)==="/**";){let j=e[o.index+4];if(j&&j!=="/")break;l=l.slice(3),F("/**",3);}if(c.type==="bos"&&G()){n.type="globstar",n.value+=s,n.output=D(t),o.output=n.output,o.globstar=true,F(s);continue}if(c.type==="slash"&&c.prev.type!=="bos"&&!I&&G()){o.output=o.output.slice(0,-(c.output+n.output).length),c.output=`(?:${c.output}`,n.type="globstar",n.output=D(t)+(t.strictSlashes?")":"|$)"),n.value+=s,o.globstar=true,o.output+=c.output+n.output,F(s);continue}if(c.type==="slash"&&c.prev.type!=="bos"&&l[0]==="/"){let j=l[1]!==void 0?"|$":"";o.output=o.output.slice(0,-(c.output+n.output).length),c.output=`(?:${c.output}`,n.type="globstar",n.output=`${D(t)}${P}|${P}${j})`,n.value+=s,o.output+=c.output+n.output,o.globstar=true,F(s+X()),g({type:"slash",value:"/",output:""});continue}if(c.type==="bos"&&l[0]==="/"){n.type="globstar",n.value+=s,n.output=`(?:^|${P}|${D(t)}${P})`,o.output=n.output,o.globstar=true,F(s+X()),g({type:"slash",value:"/",output:""});continue}o.output=o.output.slice(0,-n.output.length),n.type="globstar",n.output=D(t),n.value+=s,o.output+=n.output,o.globstar=true,F(s);continue}let H={type:"star",value:s,output:k};if(t.bash===true){H.output=".*?",(n.type==="bos"||n.type==="slash")&&(H.output=A+H.output),g(H);continue}if(n&&(n.type==="bracket"||n.type==="paren")&&t.regex===true){H.output=s,g(H);continue}(o.index===o.start||n.type==="slash"||n.type==="dot")&&(n.type==="dot"?(o.output+=K,n.output+=K):t.dot===true?(o.output+=U,n.output+=U):(o.output+=A,n.output+=A),E()!=="*"&&(o.output+=y,n.output+=y)),g(H);}for(;o.brackets>0;){if(t.strictBrackets===true)throw new SyntaxError(se("closing","]"));o.output=B.escapeLast(o.output,"["),te("brackets");}for(;o.parens>0;){if(t.strictBrackets===true)throw new SyntaxError(se("closing",")"));o.output=B.escapeLast(o.output,"("),te("parens");}for(;o.braces>0;){if(t.strictBrackets===true)throw new SyntaxError(se("closing","}"));o.output=B.escapeLast(o.output,"{"),te("braces");}if(t.strictSlashes!==true&&(n.type==="star"||n.type==="bracket")&&g({type:"maybe_slash",value:"",output:`${P}?`}),o.backtrack===true){o.output="";for(let l of o.tokens)o.output+=l.output!=null?l.output:l.value,l.suffix&&(o.output+=l.suffix);}return o};Se.fastpaths=(e,r)=>{let t={...r},i=typeof t.maxLength=="number"?Math.min(he,t.maxLength):he,a=e.length;if(a>i)throw new SyntaxError(`Input length: ${a}, exceeds maximum allowed length: ${i}`);e=ze[e]||e;let p=B.isWindows(r),{DOT_LITERAL:u,SLASH_LITERAL:f,ONE_CHAR:h,DOTS_SLASH:d,NO_DOT:R,NO_DOTS:$,NO_DOTS_SLASH:O,STAR:P,START_ANCHOR:y}=ae.globChars(p),T=t.dot?$:R,Y=t.dot?O:R,K=t.capture?"":"?:",U={negated:false,prefix:""},L=t.bash===true?".*?":P;t.capture&&(L=`(${L})`);let q=A=>A.noglobstar===true?L:`(${K}(?:(?!${y}${A.dot?d:u}).)*?)`,N=A=>{switch(A){case "*":return `${T}${h}${L}`;case ".*":return `${u}${h}${L}`;case "*.*":return `${T}${L}${u}${h}${L}`;case "*/*":return `${T}${L}${f}${h}${Y}${L}`;case "**":return T+q(t);case "**/*":return `(?:${T}${q(t)}${f})?${Y}${h}${L}`;case "**/*.*":return `(?:${T}${q(t)}${f})?${Y}${L}${u}${h}${L}`;case "**/.*":return `(?:${T}${q(t)}${f})?${u}${h}${L}`;default:{let x=/^(.*?)\.(\w+)$/.exec(A);if(!x)return;let k=N(x[1]);return k?k+u+x[2]:void 0}}},J=B.removePrefix(e,U),D=N(J);return D&&t.strictSlashes!==true&&(D+=`${f}?`),D};Ye.exports=Se;});var tt=chunkBUNLC3II_cjs.c((Lr,et)=>{chunkBUNLC3II_cjs.h();var or=chunkBUNLC3II_cjs.a("path"),ur=je(),Ce=Je(),$e=fe(),ar=oe(),ir=e=>e&&typeof e=="object"&&!Array.isArray(e),v=(e,r,t=false)=>{if(Array.isArray(e)){let R=e.map(O=>v(O,r,t));return O=>{for(let P of R){let y=P(O);if(y)return y}return false}}let i=ir(e)&&e.tokens&&e.input;if(e===""||typeof e!="string"&&!i)throw new TypeError("Expected pattern to be a non-empty string");let a=r||{},p=$e.isWindows(r),u=i?v.compileRe(e,r):v.makeRe(e,r,false,true),f=u.state;delete u.state;let h=()=>false;if(a.ignore){let R={...r,ignore:null,onMatch:null,onResult:null};h=v(a.ignore,R,t);}let d=(R,$=false)=>{let{isMatch:O,match:P,output:y}=v.test(R,u,r,{glob:e,posix:p}),T={glob:e,state:f,regex:u,posix:p,input:R,output:y,match:P,isMatch:O};return typeof a.onResult=="function"&&a.onResult(T),O===false?(T.isMatch=false,$?T:false):h(R)?(typeof a.onIgnore=="function"&&a.onIgnore(T),T.isMatch=false,$?T:false):(typeof a.onMatch=="function"&&a.onMatch(T),$?T:true)};return t&&(d.state=f),d};v.test=(e,r,t,{glob:i,posix:a}={})=>{if(typeof e!="string")throw new TypeError("Expected input to be a string");if(e==="")return {isMatch:false,output:""};let p=t||{},u=p.format||(a?$e.toPosixSlashes:null),f=e===i,h=f&&u?u(e):e;return f===false&&(h=u?u(e):e,f=h===i),(f===false||p.capture===true)&&(p.matchBase===true||p.basename===true?f=v.matchBase(e,r,t,a):f=r.exec(h)),{isMatch:!!f,match:f,output:h}};v.matchBase=(e,r,t,i=$e.isWindows(t))=>(r instanceof RegExp?r:v.makeRe(r,t)).test(or.basename(e));v.isMatch=(e,r,t)=>v(r,t)(e);v.parse=(e,r)=>Array.isArray(e)?e.map(t=>v.parse(t,r)):Ce(e,{...r,fastpaths:false});v.scan=(e,r)=>ur(e,r);v.compileRe=(e,r,t=false,i=false)=>{if(t===true)return e.output;let a=r||{},p=a.contains?"":"^",u=a.contains?"":"$",f=`${p}(?:${e.output})${u}`;e&&e.negated===true&&(f=`^(?!${f}).*$`);let h=v.toRegex(f,r);return i===true&&(h.state=e),h};v.makeRe=(e,r={},t=false,i=false)=>{if(!e||typeof e!="string")throw new TypeError("Expected a non-empty string");let a={negated:false,fastpaths:true};return r.fastpaths!==false&&(e[0]==="."||e[0]==="*")&&(a.output=Ce.fastpaths(e,r)),a.output||(a=Ce(e,r)),v.compileRe(a,r,t,i)};v.toRegex=(e,r)=>{try{let t=r||{};return new RegExp(e,t.flags||(t.nocase?"i":""))}catch(t){if(r&&r.debug===true)throw t;return /$^/}};v.constants=ar;et.exports=v;});var nt=chunkBUNLC3II_cjs.c((vr,rt)=>{chunkBUNLC3II_cjs.h();rt.exports=tt();});var ot=chunkBUNLC3II_cjs.c((Ir,st)=>{chunkBUNLC3II_cjs.h();st.exports=function(e,r){if(typeof e!="string")throw new TypeError("expected path to be a string");if(e==="\\"||e==="/")return "/";var t=e.length;if(t<=1)return e;var i="";if(t>4&&e[3]==="\\"){var a=e[2];(a==="?"||a===".")&&e.slice(0,2)==="\\\\"&&(e=e.slice(2),i="//");}var p=e.split(/[/\\]+/);return r!==false&&p[p.length-1]===""&&p.pop(),i+p.join("/")};});var pt=chunkBUNLC3II_cjs.c((ct,lt)=>{chunkBUNLC3II_cjs.h();Object.defineProperty(ct,"__esModule",{value:true});var it=nt(),cr=ot(),ut="!",lr={returnIndex:false},pr=e=>Array.isArray(e)?e:[e],fr=(e,r)=>{if(typeof e=="function")return e;if(typeof e=="string"){let t=it(e,r);return i=>e===i||t(i)}return e instanceof RegExp?t=>e.test(t):t=>false},at=(e,r,t,i)=>{let a=Array.isArray(t),p=a?t[0]:t;if(!a&&typeof p!="string")throw new TypeError("anymatch: second argument must be a string: got "+Object.prototype.toString.call(p));let u=cr(p,false);for(let h=0;h<r.length;h++){let d=r[h];if(d(u))return i?-1:false}let f=a&&[u].concat(t.slice(1));for(let h=0;h<e.length;h++){let d=e[h];if(a?d(...f):d(u))return i?h:true}return i?-1:false},me=(e,r,t=lr)=>{if(e==null)throw new TypeError("anymatch: specify first argument");let i=typeof t=="boolean"?{returnIndex:t}:t,a=i.returnIndex||false,p=pr(e),u=p.filter(h=>typeof h=="string"&&h.charAt(0)===ut).map(h=>h.slice(1)).map(h=>it(h,i)),f=p.filter(h=>typeof h!="string"||typeof h=="string"&&h.charAt(0)!==ut).map(h=>fr(h,i));return r==null?(h,d=false)=>at(f,u,h,typeof d=="boolean"?d:false):at(f,u,r,a)};me.default=me;lt.exports=me;});function He(e){return e.code==="ENOENT"||e.code==="EISDIR"?null:e}function ft(e){return e.code==="EEXIST"?null:e}async function Te(e,r,t){return await gt(path.dirname(e)),fs.promises.writeFile(e,r,t)}function Le(e,r){return fs.promises.readFile(e,r).catch(He)}function Rt(e){return fs.promises.unlink(e).catch(He)}function _t(e){return fs.promises.readdir(e,{withFileTypes:true}).catch(He).then(r=>r||[])}async function gt(e){fs.existsSync(e)||(await gt(path.dirname(e)).catch(ft),await fs.promises.mkdir(e).catch(ft));}async function Oe(e,r,t){if(r&&r(e))return [];let i=await _t(e),a=[];return await Promise.all(i.map(async p=>{let u=path.resolve(e,p.name);if(p.isDirectory()){if(t===void 0||t>0){let f=await Oe(u,r,t===void 0?void 0:t-1);a.push(...f.map(h=>p.name+"/"+h));}}else r&&r(p.name)||a.push(p.name);})),a}async function ve(e){let r=await _t(e);await Promise.all(r.map(t=>{let i=path.resolve(e,t.name);return t.isDirectory()?ve(i).then(()=>fs.promises.rmdir(i)):fs.promises.unlink(i)}));}var Et=chunkBUNLC3II_cjs.b(()=>{chunkBUNLC3II_cjs.h();});var dt,dr,we;exports.a=void 0;var xr=chunkBUNLC3II_cjs.b(()=>{chunkBUNLC3II_cjs.h();dt=chunkBUNLC3II_cjs.e(pt(),1);chunkXPPVX4GQ_cjs.c();Et();dr=/\.\.:|\.\.$/,we="fs",exports.a=(e={})=>{if(!e.base)throw chunkXPPVX4GQ_cjs.b(we,"base");let r=path.resolve(e.base),t=(0, dt.default)(e.ignore||["**/node_modules/**","**/.git/**"]),i=u=>{if(dr.test(u))throw chunkXPPVX4GQ_cjs.a(we,`Invalid key: ${JSON.stringify(u)}. It should not contain .. segments`);return path.join(r,u.replace(/:/g,"/"))},a,p=async()=>{a&&(await a.close(),a=void 0);};return {name:we,options:e,flags:{maxDepth:true},hasItem(u){return fs.existsSync(i(u))},getItem(u){return Le(i(u),"utf8")},getItemRaw(u){return Le(i(u))},async getMeta(u){let{atime:f,mtime:h,size:d,birthtime:R,ctime:$}=await fs.promises.stat(i(u)).catch(()=>({}));return {atime:f,mtime:h,size:d,birthtime:R,ctime:$}},setItem(u,f){if(!e.readOnly)return Te(i(u),f,"utf8")},setItemRaw(u,f){if(!e.readOnly)return Te(i(u),f)},removeItem(u){if(!e.readOnly)return Rt(i(u))},getKeys(u,f){return Oe(i("."),t,f?.maxDepth)},async clear(){e.readOnly||e.noClear||await ve(i("."));},async dispose(){a&&await a.close();},async watch(u){if(a)return p;let{watch:f}=await import('./chokidar-24HVS6XD.cjs');return await new Promise((h,d)=>{let R={ignoreInitial:true,...e.watchOptions};R.ignored?Array.isArray(R.ignored)?R.ignored=[...R.ignored]:R.ignored=[R.ignored]:R.ignored=[],R.ignored.push(t),a=f(r,R).on("ready",()=>{h();}).on("error",d).on("all",($,O)=>{O=path.relative(r,O),$==="change"||$==="add"?u("update",O):$==="unlink"&&u("remove",O);});}),p}}};});/*! Bundled license information:
|
|
2
|
+
|
|
3
|
+
normalize-path/index.js:
|
|
4
|
+
(*!
|
|
5
|
+
* normalize-path <https://github.com/jonschlinkert/normalize-path>
|
|
6
|
+
*
|
|
7
|
+
* Copyright (c) 2014-2018, Jon Schlinkert.
|
|
8
|
+
* Released under the MIT License.
|
|
9
|
+
*)
|
|
10
|
+
*/exports.b=xr;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import
|
|
1
|
+
import {createRequire}from'module';import {a}from'./chunk-BPMA2ECA.js';import {g,e}from'./chunk-C2PXMVR5.js';import {randomBytes}from'crypto';import {mkdirSync}from'fs';import {dirname}from'path';createRequire(import.meta.url);
|
|
2
|
+
g();var E=e(a(),1);var c;function k(){return c||(c=createRequire("file:///")("node:sqlite").DatabaseSync,c)}var A=5e3,y=1e3,R=-64e3,L=268435456,p=class{db=null;path;saltRounds;externalDb;busyTimeout;walAutoCheckpoint;cacheSize;mmapSize;preparedStatements=new Map;constructor(e={}){this.path=e.path||"./data/auth.db",this.saltRounds=e.saltRounds||12,this.externalDb=!!e.db,this.busyTimeout=e.busyTimeout??A,this.walAutoCheckpoint=e.walAutoCheckpoint??y,this.cacheSize=e.cacheSize??R,this.mmapSize=e.mmapSize??L,e.db&&(this.db=e.db);}async connect(){if(this.db)return;let e=dirname(this.path);e&&e!=="."&&mkdirSync(e,{recursive:true}),this.db=new(k())(this.path),this.db.exec(`PRAGMA busy_timeout = ${this.busyTimeout}`),this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA synchronous = NORMAL"),this.db.exec("PRAGMA cache_size = "+this.cacheSize),this.db.exec("PRAGMA mmap_size = "+this.mmapSize),this.db.exec("PRAGMA wal_autocheckpoint = "+this.walAutoCheckpoint),this.db.exec("PRAGMA foreign_keys = ON"),this.db.exec("PRAGMA temp_store = MEMORY"),this.ensureTables(),this.prepareStatements();}async disconnect(){this.db&&!this.externalDb&&(this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)"),this.db.close(),this.db=null,this.preparedStatements.clear());}async ensureConnected(){if(this.db||await this.connect(),!this.db)throw new Error("Failed to connect to SQLite database");return this.db}ensureTables(){if(this.db){this.db.exec(`
|
|
2
3
|
CREATE TABLE IF NOT EXISTS kyro_users (
|
|
3
4
|
id TEXT PRIMARY KEY,
|
|
4
5
|
name TEXT,
|
|
@@ -115,8 +116,8 @@ import E from'bcryptjs';import {randomBytes}from'crypto';import {mkdirSync}from'
|
|
|
115
116
|
locked_at = excluded.locked_at,
|
|
116
117
|
locked_until = excluded.locked_until
|
|
117
118
|
`)),this.preparedStatements.set("resetLockout",this.db.prepare("UPDATE kyro_lockouts SET attempts = 0, locked_at = NULL, locked_until = NULL WHERE user_id = ?")));}stmt(e){let s=this.preparedStatements.get(e);if(!s)throw new Error(`Prepared statement not found: ${e}`);return s}async cleanupExpiredSessions(){return await this.ensureConnected(),this.stmt("deleteExpiredSessions").run(new Date().toISOString()).changes}async cleanupOldAuditLogs(e=30){await this.ensureConnected();let s=new Date(Date.now()-e*24*60*60*1e3).toISOString();return this.stmt("cleanupOldAuditLogs").run(s).changes}async getStats(){await this.ensureConnected();let e=this.stmt("countUsers").get().count,s=this.db.prepare("SELECT COUNT(*) as count FROM kyro_sessions WHERE expires_at > ?").get(new Date().toISOString()).count,t=this.db.prepare("SELECT COUNT(*) as count FROM kyro_audit_logs").get().count;return {userCount:e,activeSessionCount:s,auditLogCount:t}}async createUser(e){await this.ensureConnected();let s=randomBytes(16).toString("hex"),t=new Date().toISOString(),r=await this.hashPassword(e.password),n={id:s,name:e.name,email:e.email.toLowerCase(),passwordHash:r,role:e.role||"customer",avatar:e.avatar,tenantId:e.tenantId,createdAt:t,updatedAt:t};return this.db.prepare(`INSERT INTO kyro_users (id, name, email, password_hash, role, avatar, tenant_id, created_at, updated_at)
|
|
118
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,n.name||null,n.email,n.passwordHash,n.role,n.avatar||null,n.tenantId||null,t,t),n}async findUserByEmail(e){await this.ensureConnected();let s=this.stmt("findUserByEmail").get(e.toLowerCase());return s?this.rowToUser(s):null}async findUserById(e){await this.ensureConnected();let s=this.stmt("findUserById").get(e);return s?this.rowToUser(s):null}async updateUser(e,s){if(await this.ensureConnected(),!await this.findUserById(e))return null;let r=[],n=[];return s.email!==void 0&&(r.push("email = ?"),n.push(s.email.toLowerCase())),s.name!==void 0&&(r.push("name = ?"),n.push(s.name)),s.passwordHash!==void 0&&(r.push("password_hash = ?"),n.push(s.passwordHash)),s.role!==void 0&&(r.push("role = ?"),n.push(s.role)),s.avatar!==void 0&&(r.push("avatar = ?"),n.push(s.avatar)),s.tenantId!==void 0&&(r.push("tenant_id = ?"),n.push(s.tenantId)),s.emailVerified!==void 0&&(r.push("email_verified = ?"),n.push(s.emailVerified?1:0)),s.locked!==void 0&&(r.push("locked = ?"),n.push(s.locked?1:0)),s.lastLogin!==void 0&&(r.push("last_login = ?"),n.push(s.lastLogin)),s.failedLoginAttempts!==void 0&&(r.push("failed_login_attempts = ?"),n.push(s.failedLoginAttempts)),r.push("updated_at = ?"),n.push(new Date().toISOString()),n.push(e),this.db.prepare(`UPDATE kyro_users SET ${r.join(", ")} WHERE id = ?`).run(...n),this.findUserById(e)}async deleteUser(e){return await this.ensureConnected(),this.stmt("deleteUser").run(e).changes>0}async hashPassword(e){return E.hash(e,this.saltRounds)}async verifyPassword(e,s){await this.ensureConnected();let t=await this.findUserByEmail(e);if(!t)return null;let r=this.db.prepare("SELECT password_hash FROM kyro_users WHERE id = ?").get(t.id);return r?.password_hash&&await E.compare(s,r.password_hash)?t:null}async createSession(e,s={}){await this.ensureConnected();let t=randomBytes(32).toString("hex"),r=randomBytes(32).toString("base64url"),n=randomBytes(32).toString("base64url"),d=new Date,u=new Date(d.getTime()+864e5).toISOString(),i={id:t,userId:e,token:r,refreshToken:n,expiresAt:u,createdAt:d.toISOString(),ipAddress:s.ipAddress,userAgent:s.userAgent};return this.db.prepare(`INSERT INTO kyro_sessions (id, user_id, token, refresh_token, expires_at, created_at, ip_address, user_agent)
|
|
119
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(i.id,i.userId,i.token,i.refreshToken??null,i.expiresAt,i.createdAt,i.ipAddress??null,i.userAgent??null),i}async findSessionByToken(e){await this.ensureConnected();let s=this.stmt("findSessionByToken").get(e);return s?this.rowToSession(s):null}async findSessionByRefreshToken(e){await this.ensureConnected();let s=this.stmt("findSessionByRefreshToken").get(e);return s?this.rowToSession(s):null}async deleteSession(e){return await this.ensureConnected(),this.stmt("deleteSession").run(e,e).changes>0}async deleteUserSessions(e){return await this.ensureConnected(),this.stmt("deleteUserSessions").run(e).changes}async hasAnyUsers(){return await this.ensureConnected(),this.stmt("countUsers").get().count>0}async findUsers(e={}){await this.ensureConnected();let s=e.page??1,t=e.limit??10,r=(s-1)*t,n=e.search,d,u;if(n){let i=`%${n}%`;d=this.stmt("countUsersWithSearch").get(i).count,u=this.stmt("findUsersWithSearch").all(i,t,r);}else d=this.stmt("countUsers").get().count,u=this.stmt("findUsersPaginated").all(t,r);return {users:u.map(i=>this.rowToUser(i)),total:d}}async addPasswordToHistory(e,s){await this.ensureConnected(),this.stmt("addPasswordHistory").run(e,s,new Date().toISOString()),this.stmt("trimPasswordHistory").run(e);}async getPasswordHistory(e,s=5){return await this.ensureConnected(),this.stmt("getPasswordHistory").all(e,s).map(r=>r.password_hash)}async isPasswordInHistory(e,s,t=5){let r=await this.getPasswordHistory(s,t);for(let n of r)if(await E.compare(e,n))return true;return false}async recordFailedAttempt(e){await this.ensureConnected();let s=Date.now(),t=this.stmt("getLockout").get(e),r=(t?.attempts||0)+1,n=r>=5?s+900*1e3:t?.locked_until||null;this.stmt("upsertLockout").run(e,r,s,n!==null?s:null,n);}async resetAttempts(e){await this.ensureConnected(),this.stmt("resetLockout").run(e);}async checkLockout(e){await this.ensureConnected(),this.stmt("cleanupExpiredLockouts").run(Date.now());let s=this.stmt("getLockout").get(e);return s?s.locked_until!==null&&s.locked_until>Date.now()?{locked:true,attemptsRemaining:0,lockedUntil:new Date(s.locked_until),totalAttempts:s.attempts}:{locked:false,attemptsRemaining:Math.max(0,5-s.attempts),totalAttempts:s.attempts}:{locked:false,attemptsRemaining:5,totalAttempts:0}}async logAudit(e){await this.ensureConnected();let s=randomBytes(16).toString("hex"),t=new Date().toISOString();return this.db.prepare(`INSERT INTO kyro_audit_logs (
|
|
119
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,n.name||null,n.email,n.passwordHash,n.role,n.avatar||null,n.tenantId||null,t,t),n}async findUserByEmail(e){await this.ensureConnected();let s=this.stmt("findUserByEmail").get(e.toLowerCase());return s?this.rowToUser(s):null}async findUserById(e){await this.ensureConnected();let s=this.stmt("findUserById").get(e);return s?this.rowToUser(s):null}async updateUser(e,s){if(await this.ensureConnected(),!await this.findUserById(e))return null;let r=[],n=[];return s.email!==void 0&&(r.push("email = ?"),n.push(s.email.toLowerCase())),s.name!==void 0&&(r.push("name = ?"),n.push(s.name)),s.passwordHash!==void 0&&(r.push("password_hash = ?"),n.push(s.passwordHash)),s.role!==void 0&&(r.push("role = ?"),n.push(s.role)),s.avatar!==void 0&&(r.push("avatar = ?"),n.push(s.avatar)),s.tenantId!==void 0&&(r.push("tenant_id = ?"),n.push(s.tenantId)),s.emailVerified!==void 0&&(r.push("email_verified = ?"),n.push(s.emailVerified?1:0)),s.locked!==void 0&&(r.push("locked = ?"),n.push(s.locked?1:0)),s.lastLogin!==void 0&&(r.push("last_login = ?"),n.push(s.lastLogin)),s.failedLoginAttempts!==void 0&&(r.push("failed_login_attempts = ?"),n.push(s.failedLoginAttempts)),r.push("updated_at = ?"),n.push(new Date().toISOString()),n.push(e),this.db.prepare(`UPDATE kyro_users SET ${r.join(", ")} WHERE id = ?`).run(...n),this.findUserById(e)}async deleteUser(e){return await this.ensureConnected(),this.stmt("deleteUser").run(e).changes>0}async hashPassword(e){return E.default.hash(e,this.saltRounds)}async verifyPassword(e,s){await this.ensureConnected();let t=await this.findUserByEmail(e);if(!t)return null;let r=this.db.prepare("SELECT password_hash FROM kyro_users WHERE id = ?").get(t.id);return r?.password_hash&&await E.default.compare(s,r.password_hash)?t:null}async createSession(e,s={}){await this.ensureConnected();let t=randomBytes(32).toString("hex"),r=randomBytes(32).toString("base64url"),n=randomBytes(32).toString("base64url"),d=new Date,u=new Date(d.getTime()+864e5).toISOString(),i={id:t,userId:e,token:r,refreshToken:n,expiresAt:u,createdAt:d.toISOString(),ipAddress:s.ipAddress,userAgent:s.userAgent};return this.db.prepare(`INSERT INTO kyro_sessions (id, user_id, token, refresh_token, expires_at, created_at, ip_address, user_agent)
|
|
120
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(i.id,i.userId,i.token,i.refreshToken??null,i.expiresAt,i.createdAt,i.ipAddress??null,i.userAgent??null),i}async findSessionByToken(e){await this.ensureConnected();let s=this.stmt("findSessionByToken").get(e);return s?this.rowToSession(s):null}async findSessionByRefreshToken(e){await this.ensureConnected();let s=this.stmt("findSessionByRefreshToken").get(e);return s?this.rowToSession(s):null}async deleteSession(e){return await this.ensureConnected(),this.stmt("deleteSession").run(e,e).changes>0}async deleteUserSessions(e){return await this.ensureConnected(),this.stmt("deleteUserSessions").run(e).changes}async hasAnyUsers(){return await this.ensureConnected(),this.stmt("countUsers").get().count>0}async findUsers(e={}){await this.ensureConnected();let s=e.page??1,t=e.limit??10,r=(s-1)*t,n=e.search,d,u;if(n){let i=`%${n}%`;d=this.stmt("countUsersWithSearch").get(i).count,u=this.stmt("findUsersWithSearch").all(i,t,r);}else d=this.stmt("countUsers").get().count,u=this.stmt("findUsersPaginated").all(t,r);return {users:u.map(i=>this.rowToUser(i)),total:d}}async addPasswordToHistory(e,s){await this.ensureConnected(),this.stmt("addPasswordHistory").run(e,s,new Date().toISOString()),this.stmt("trimPasswordHistory").run(e);}async getPasswordHistory(e,s=5){return await this.ensureConnected(),this.stmt("getPasswordHistory").all(e,s).map(r=>r.password_hash)}async isPasswordInHistory(e,s,t=5){let r=await this.getPasswordHistory(s,t);for(let n of r)if(await E.default.compare(e,n))return true;return false}async recordFailedAttempt(e){await this.ensureConnected();let s=Date.now(),t=this.stmt("getLockout").get(e),r=(t?.attempts||0)+1,n=r>=5?s+900*1e3:t?.locked_until||null;this.stmt("upsertLockout").run(e,r,s,n!==null?s:null,n);}async resetAttempts(e){await this.ensureConnected(),this.stmt("resetLockout").run(e);}async checkLockout(e){await this.ensureConnected(),this.stmt("cleanupExpiredLockouts").run(Date.now());let s=this.stmt("getLockout").get(e);return s?s.locked_until!==null&&s.locked_until>Date.now()?{locked:true,attemptsRemaining:0,lockedUntil:new Date(s.locked_until),totalAttempts:s.attempts}:{locked:false,attemptsRemaining:Math.max(0,5-s.attempts),totalAttempts:s.attempts}:{locked:false,attemptsRemaining:5,totalAttempts:0}}async logAudit(e){await this.ensureConnected();let s=randomBytes(16).toString("hex"),t=new Date().toISOString();return this.db.prepare(`INSERT INTO kyro_audit_logs (
|
|
120
121
|
id, timestamp, action, user_id, user_email, role, resource, resource_id,
|
|
121
122
|
ip_address, user_agent, success, error, metadata, created_at
|
|
122
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,t,e.action,e.userId||null,e.userEmail||null,e.role||null,e.resource,e.resourceId||null,e.ipAddress||null,e.userAgent||null,e.success?1:0,e.error||null,e.metadata?JSON.stringify(e.metadata):null,new Date().toISOString()),s}async queryAuditLogs(e={}){await this.ensureConnected();let s=[],t=[];e.action&&(s.push("action = ?"),t.push(e.action)),e.userId&&(s.push("user_id = ?"),t.push(e.userId)),e.resource&&(s.push("resource = ?"),t.push(e.resource)),e.success!==void 0&&(s.push("success = ?"),t.push(e.success?1:0)),e.startDate&&(s.push("timestamp >= ?"),t.push(e.startDate.toISOString())),e.endDate&&(s.push("timestamp <= ?"),t.push(e.endDate.toISOString()));let r=s.length>0?"WHERE "+s.join(" AND "):"",n=e.limit||50,d=e.offset||0,u=this.db.prepare(`SELECT COUNT(*) as count FROM kyro_audit_logs ${r}`).get(...t),i=this.db.prepare(`SELECT * FROM kyro_audit_logs ${r} ORDER BY timestamp DESC LIMIT ? OFFSET ?`).all(...t,n,d);return {total:u.count,logs:i.map(a=>({id:a.id,timestamp:new Date(a.timestamp),action:a.action,userId:a.user_id||void 0,userEmail:a.user_email||void 0,resource:a.resource,resourceId:a.resource_id||void 0,ipAddress:a.ip_address||void 0,userAgent:a.user_agent||void 0,success:a.success===1,error:a.error||void 0,metadata:a.metadata?JSON.parse(a.metadata):void 0}))}}rowToUser(e){return {id:e.id,name:e.name||void 0,email:e.email,passwordHash:e.password_hash,role:e.role,tenantId:e.tenant_id,avatar:e.avatar,emailVerified:e.email_verified===1,locked:e.locked===1,lastLogin:e.last_login,failedLoginAttempts:e.failed_login_attempts||0,createdAt:e.created_at,updatedAt:e.updated_at}}rowToSession(e){return {id:e.id,userId:e.user_id,token:e.token,refreshToken:e.refresh_token,expiresAt:e.expires_at,createdAt:e.created_at,ipAddress:e.ip_address,userAgent:e.user_agent}}async findAuditLogs(e){let s=await this.queryAuditLogs({action:e.action,userId:e.userId,resource:e.resource,success:e.success,startDate:e.startDate,endDate:e.endDate,limit:e.limit,offset:e.offset});return {logs:s.logs.map(t=>({...t,action:t.action})),total:s.total}}async createAuditLog(e){let s=await this.logAudit({action:e.action,userId:e.userId,userEmail:e.userEmail,role:e.role,resource:e.resource,resourceId:e.resourceId,ipAddress:e.ipAddress,userAgent:e.userAgent,success:e.success,error:e.error,metadata:e.metadata}),t=this.db?.prepare("SELECT * FROM kyro_audit_logs WHERE id = ?").get(s);return {...e,id:s,timestamp:t?new Date(t.timestamp):new Date}}async createEmailVerificationToken(e){await this.ensureConnected();let s=randomBytes(16).toString("hex"),t=randomBytes(32).toString("hex"),r=new Date(Date.now()+1440*60*1e3);return this.db.prepare("INSERT INTO kyro_email_verifications (id, user_id, token, expires_at, created_at) VALUES (?, ?, ?, ?, ?)").run(s,e,t,r.toISOString(),new Date().toISOString()),{token:t,expiresAt:r}}async verifyEmailToken(e){await this.ensureConnected();let s=this.db.prepare("SELECT * FROM kyro_email_verifications WHERE token = ?").get(e);return s?new Date(s.expires_at)<new Date?{success:false,error:"Verification token has expired"}:(this.db.prepare("UPDATE kyro_users SET email_verified = 1 WHERE id = ?").run(s.user_id),this.db.prepare("DELETE FROM kyro_email_verifications WHERE id = ?").run(s.id),{success:true,userId:s.user_id}):{success:false,error:"Invalid verification token"}}async createPasswordResetToken(e){await this.ensureConnected();let s=await this.findUserByEmail(e);if(!s)return {token:"",expiresAt:new Date,error:"User not found"};let t=randomBytes(16).toString("hex"),r=randomBytes(32).toString("hex"),n=new Date(Date.now()+3600*1e3);return this.db.prepare("INSERT INTO kyro_password_resets (id, user_id, token, expires_at, created_at) VALUES (?, ?, ?, ?, ?)").run(t,s.id,r,n.toISOString(),new Date().toISOString()),{token:r,expiresAt:n}}async resetPasswordWithToken(e,s){await this.ensureConnected();let t=this.db.prepare("SELECT * FROM kyro_password_resets WHERE token = ?").get(e);if(!t)return {success:false,error:"Invalid reset token"};if(new Date(t.expires_at)<new Date)return {success:false,error:"Reset token has expired"};if(t.used_at)return {success:false,error:"Reset token has already been used"};let r=await this.hashPassword(s);return this.db.prepare("UPDATE kyro_users SET password_hash = ?, updated_at = ? WHERE id = ?").run(r,new Date().toISOString(),t.user_id),this.db.prepare("UPDATE kyro_password_resets SET used_at = ? WHERE id = ?").run(new Date().toISOString(),t.id),this.db.prepare("DELETE FROM kyro_sessions WHERE user_id = ?").run(t.user_id),{success:true}}};export{
|
|
123
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(s,t,e.action,e.userId||null,e.userEmail||null,e.role||null,e.resource,e.resourceId||null,e.ipAddress||null,e.userAgent||null,e.success?1:0,e.error||null,e.metadata?JSON.stringify(e.metadata):null,new Date().toISOString()),s}async queryAuditLogs(e={}){await this.ensureConnected();let s=[],t=[];e.action&&(s.push("action = ?"),t.push(e.action)),e.userId&&(s.push("user_id = ?"),t.push(e.userId)),e.resource&&(s.push("resource = ?"),t.push(e.resource)),e.success!==void 0&&(s.push("success = ?"),t.push(e.success?1:0)),e.startDate&&(s.push("timestamp >= ?"),t.push(e.startDate.toISOString())),e.endDate&&(s.push("timestamp <= ?"),t.push(e.endDate.toISOString()));let r=s.length>0?"WHERE "+s.join(" AND "):"",n=e.limit||50,d=e.offset||0,u=this.db.prepare(`SELECT COUNT(*) as count FROM kyro_audit_logs ${r}`).get(...t),i=this.db.prepare(`SELECT * FROM kyro_audit_logs ${r} ORDER BY timestamp DESC LIMIT ? OFFSET ?`).all(...t,n,d);return {total:u.count,logs:i.map(a=>({id:a.id,timestamp:new Date(a.timestamp),action:a.action,userId:a.user_id||void 0,userEmail:a.user_email||void 0,resource:a.resource,resourceId:a.resource_id||void 0,ipAddress:a.ip_address||void 0,userAgent:a.user_agent||void 0,success:a.success===1,error:a.error||void 0,metadata:a.metadata?JSON.parse(a.metadata):void 0}))}}rowToUser(e){return {id:e.id,name:e.name||void 0,email:e.email,passwordHash:e.password_hash,role:e.role,tenantId:e.tenant_id,avatar:e.avatar,emailVerified:e.email_verified===1,locked:e.locked===1,lastLogin:e.last_login,failedLoginAttempts:e.failed_login_attempts||0,createdAt:e.created_at,updatedAt:e.updated_at}}rowToSession(e){return {id:e.id,userId:e.user_id,token:e.token,refreshToken:e.refresh_token,expiresAt:e.expires_at,createdAt:e.created_at,ipAddress:e.ip_address,userAgent:e.user_agent}}async findAuditLogs(e){let s=await this.queryAuditLogs({action:e.action,userId:e.userId,resource:e.resource,success:e.success,startDate:e.startDate,endDate:e.endDate,limit:e.limit,offset:e.offset});return {logs:s.logs.map(t=>({...t,action:t.action})),total:s.total}}async createAuditLog(e){let s=await this.logAudit({action:e.action,userId:e.userId,userEmail:e.userEmail,role:e.role,resource:e.resource,resourceId:e.resourceId,ipAddress:e.ipAddress,userAgent:e.userAgent,success:e.success,error:e.error,metadata:e.metadata}),t=this.db?.prepare("SELECT * FROM kyro_audit_logs WHERE id = ?").get(s);return {...e,id:s,timestamp:t?new Date(t.timestamp):new Date}}async createEmailVerificationToken(e){await this.ensureConnected();let s=randomBytes(16).toString("hex"),t=randomBytes(32).toString("hex"),r=new Date(Date.now()+1440*60*1e3);return this.db.prepare("INSERT INTO kyro_email_verifications (id, user_id, token, expires_at, created_at) VALUES (?, ?, ?, ?, ?)").run(s,e,t,r.toISOString(),new Date().toISOString()),{token:t,expiresAt:r}}async verifyEmailToken(e){await this.ensureConnected();let s=this.db.prepare("SELECT * FROM kyro_email_verifications WHERE token = ?").get(e);return s?new Date(s.expires_at)<new Date?{success:false,error:"Verification token has expired"}:(this.db.prepare("UPDATE kyro_users SET email_verified = 1 WHERE id = ?").run(s.user_id),this.db.prepare("DELETE FROM kyro_email_verifications WHERE id = ?").run(s.id),{success:true,userId:s.user_id}):{success:false,error:"Invalid verification token"}}async createPasswordResetToken(e){await this.ensureConnected();let s=await this.findUserByEmail(e);if(!s)return {token:"",expiresAt:new Date,error:"User not found"};let t=randomBytes(16).toString("hex"),r=randomBytes(32).toString("hex"),n=new Date(Date.now()+3600*1e3);return this.db.prepare("INSERT INTO kyro_password_resets (id, user_id, token, expires_at, created_at) VALUES (?, ?, ?, ?, ?)").run(t,s.id,r,n.toISOString(),new Date().toISOString()),{token:r,expiresAt:n}}async resetPasswordWithToken(e,s){await this.ensureConnected();let t=this.db.prepare("SELECT * FROM kyro_password_resets WHERE token = ?").get(e);if(!t)return {success:false,error:"Invalid reset token"};if(new Date(t.expires_at)<new Date)return {success:false,error:"Reset token has expired"};if(t.used_at)return {success:false,error:"Reset token has already been used"};let r=await this.hashPassword(s);return this.db.prepare("UPDATE kyro_users SET password_hash = ?, updated_at = ? WHERE id = ?").run(r,new Date().toISOString(),t.user_id),this.db.prepare("UPDATE kyro_password_resets SET used_at = ? WHERE id = ?").run(new Date().toISOString(),t.id),this.db.prepare("DELETE FROM kyro_sessions WHERE user_id = ?").run(t.user_id),{success:true}}};export{p as a};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
'use strict';var chunkVQ53TFYA_cjs=require('./chunk-VQ53TFYA.cjs'),chunkZOVH6QT5_cjs=require('./chunk-ZOVH6QT5.cjs'),chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs'),module$1=require('module'),crypto=require('crypto');chunkBUNLC3II_cjs.h();chunkBUNLC3II_cjs.h();var _;function x(){return _||(_=module$1.createRequire("file:///")("node:sqlite").DatabaseSync,_)}function N(T){let e=[];for(let a of T)if(a.type==="tabs"&&"tabs"in a)for(let n of a.tabs)e.push(...N(n.fields));else a.type==="row"&&"fields"in a?e.push(...N(a.fields)):a.type==="collapsible"&&"fields"in a?e.push(...N(a.fields)):e.push(a);return e}function G(T,e){let a=e,n=T[a.name];if(a.type==="json"||a.type==="richtext"||a.type==="array"||a.type==="group"||a.type==="blocks"||a.type==="list"||a.type==="relationship-block")try{n=n?JSON.parse(n):null;}catch{n=null;}if(a.type==="checkbox"&&(n=!!n),a.type==="date"&&n)try{let i=new Date(n);isNaN(i.getTime())?n=null:n=i.toISOString();}catch{n=null;}if((a.type==="upload"||a.type==="image")&&n)try{let i=JSON.parse(n);Array.isArray(i)?n=i.map(o=>typeof o=="object"&&o!==null?o:{id:o}):n=typeof i=="object"?i:{id:i};}catch{n={id:n};}if(a.type==="relationship"&&n)try{let i=JSON.parse(n);Array.isArray(i),n=i;}catch{n={relationTo:Array.isArray(a.relationTo)?a.relationTo[0]:a.relationTo,value:n};}if(a.type==="list"&&n)try{let i=JSON.parse(n);n=Array.isArray(i)?i:[];}catch{n=[];}if(a.type==="relationship-block"&&n)try{let i=JSON.parse(n);n=Array.isArray(i)?i:[];}catch{n=[];}return n}function P(T,e){return Array.isArray(T)?T.map(a=>{if(!a||typeof a!="object")return a;let n=a.data?{...a.data}:void 0;if(!n)return a;let i=e.find(o=>o.slug===a.type||o.slug===a.slug);if(!i||!Array.isArray(i.fields))return a;for(let o of i.fields){if(o.name&&(o.type==="upload"||o.type==="image")&&n[o.name]){let t=n[o.name];Array.isArray(t)?n[o.name]=t.map(s=>typeof s=="string"?{id:s}:s):typeof t=="string"&&(n[o.name]={id:t});}if(o.type==="blocks"&&o.name&&n[o.name]){let t=o.blocks||[];n[o.name]=P(n[o.name],t);}}return {...a,data:n}}):T}function O(T,e){try{return T.prepare(`PRAGMA table_info(${e})`).all().map(n=>n.name)}catch{return []}}var L=class extends chunkVQ53TFYA_cjs.a{db;path;migrations=new Map;versionsTableName="kyro_versions";constructor(e){super(),this.path=e.path,e.db?this.db=e.db:this.db=null;}async connect(){if(!this.db)this.db=new(x())(this.path||":memory:");else try{this.db.exec("SELECT 1");}catch{this.db=new(x())(this.path||":memory:");}if(this.db&&typeof this.db.prepare=="function"&&!this.db.prepare.__wrapped){let e=this.db.prepare.bind(this.db),a=n=>{let i=e(n),o=t=>typeof t=="boolean"?t?1:0:t===void 0?null:t;return new Proxy(i,{get(t,s,r){if(s==="all")return (...c)=>t.all(...c.map(o));if(s==="get")return (...c)=>t.get(...c.map(o));if(s==="run")return (...c)=>t.run(...c.map(o));let l=Reflect.get(t,s,r);return typeof l=="function"?l.bind(t):l}})};a.__wrapped=true,this.db.prepare=a;}this.db.exec("PRAGMA journal_mode = WAL"),this.db.exec("PRAGMA foreign_keys = ON"),this.connected=true;}async disconnect(){if(this.db){try{this.db.close();}catch{}this.db=null;}this.connected=false;}ensureTable(e,a){let n=a||this.getTableNameFor(e.slug),i=["id TEXT PRIMARY KEY"];for(let s of N(e.fields)){if(!s.name||s.name==="id")continue;let r=this.fieldToSQL(s);r&&i.push(r);}let o=N(e.fields);o.some(s=>s.name==="createdAt")||i.push(`${this.col("createdAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="updatedAt")||i.push(`${this.col("updatedAt")} TEXT DEFAULT (datetime('now'))`),o.some(s=>s.name==="status")||i.push("status TEXT DEFAULT 'draft'"),o.some(s=>s.name==="hasDraft")||i.push("hasDraft INTEGER DEFAULT 0"),e.tenantScoped&&i.push("tenant_id TEXT NOT NULL");let t=O(this.db,n);if(t.length===0){let s=`CREATE TABLE IF NOT EXISTS ${n} (${i.join(", ")})`;this.db.exec(s),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_status ON ${n}(status)`);for(let r of N(e.fields))r.name&&r.indexed&&this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${n}_${r.name} ON ${n}(${this.col(r.name)})`),r.name&&r.unique&&this.db.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_${n}_${r.name}_unique ON ${n}(${this.col(r.name)})`);}else {let s=new Set(t);for(let r of i){let l=r.split(" ")[0].replace(/^"/,"").replace(/"$/,"");if(!s.has(l)&&l!=="id")try{l==="status"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} TEXT DEFAULT 'published'`):l==="hasDraft"?this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} INTEGER DEFAULT 0`):this.db.exec(`ALTER TABLE ${n} ADD COLUMN ${this.col(l)} TEXT`);}catch{}}}this.migrations.set(n,true);}ensureVersionsTable(){this.db.exec(`
|
|
2
|
+
CREATE TABLE IF NOT EXISTS ${this.versionsTableName} (
|
|
3
|
+
id TEXT PRIMARY KEY,
|
|
4
|
+
collection_slug TEXT NOT NULL,
|
|
5
|
+
document_id TEXT NOT NULL,
|
|
6
|
+
tenant_id TEXT,
|
|
7
|
+
version INTEGER NOT NULL,
|
|
8
|
+
status TEXT NOT NULL DEFAULT 'draft',
|
|
9
|
+
autosave INTEGER NOT NULL DEFAULT 0,
|
|
10
|
+
data TEXT NOT NULL,
|
|
11
|
+
created_by TEXT,
|
|
12
|
+
change_description TEXT,
|
|
13
|
+
published_at TEXT,
|
|
14
|
+
created_at TEXT DEFAULT (datetime('now')),
|
|
15
|
+
updated_at TEXT DEFAULT (datetime('now'))
|
|
16
|
+
)
|
|
17
|
+
`);try{this.db.exec(`ALTER TABLE ${this.versionsTableName} ADD COLUMN autosave INTEGER NOT NULL DEFAULT 0`);}catch{}this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_doc ON ${this.versionsTableName}(collection_slug, document_id)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_status ON ${this.versionsTableName}(status)`),this.db.exec(`CREATE INDEX IF NOT EXISTS idx_${this.versionsTableName}_autosave ON ${this.versionsTableName}(autosave)`);}resolveCol(e,a){let n=a.replace(/^-/,""),i=O(this.db,e);if(!i.includes(n)){if(n==="created_at"&&i.includes("createdAt"))return '"createdAt"';if(n==="createdAt"&&i.includes("created_at"))return '"created_at"';if(n==="updated_at"&&i.includes("updatedAt"))return '"updatedAt"';if(n==="updatedAt"&&i.includes("updated_at"))return '"updated_at"'}return this.col(n)}col(e){return `"${e}"`}fieldToSQL(e){switch(e.type){case "text":case "email":case "password":case "textarea":case "color":case "icon":case "code":case "markdown":case "url":return this.col(e.name)+" TEXT";case "number":return this.col(e.name)+" REAL";case "checkbox":return this.col(e.name)+" INTEGER DEFAULT 0";case "date":return this.col(e.name)+" TEXT";case "select":case "radio":return this.col(e.name)+" TEXT";case "relationship":case "upload":return this.col(e.name)+" TEXT";case "json":case "richtext":case "array":case "group":case "blocks":return this.col(e.name)+" TEXT";default:return null}}parseGlobalsSlug(e){if(e.startsWith("_globals_")){let a=e.replace("_globals_","");return {isGlobal:true,globalSlug:a,tableName:`global_${a.replace(/-/g,"_")}`}}return {isGlobal:false,globalSlug:"",tableName:this.getTableNameFor(e)}}async find(e){let{collection:a,where:n={},sort:i,limit:o=10,page:t=1,tenantId:s,draft:r=false}=e,l=this.parseGlobalsSlug(a),c=l.isGlobal?this.globals.get(l.globalSlug):this.getCollection(a);this.ensureTable(c,l.tableName);let d=l.tableName,y=`SELECT * FROM ${d}`,u=[],p=[],f={...n};this.tenantContext&&c.tenantScoped&&(f=chunkVQ53TFYA_cjs.c({where:f},a,this.tenantContext,chunkVQ53TFYA_cjs.b).where||{});let E=c.fields.find(h=>h.name==="status"),b=E?.type==="select"&&Array.isArray(E.options)&&E.options.some(h=>h.value==="published");!r&&b&&(p.push("status = ?"),u.push("published")),s&&c.tenantScoped&&(p.push("tenant_id = ?"),u.push(s));for(let[h,m]of Object.entries(f)){if(h==="AND"||h==="OR")continue;let S=this.resolveCol(d,h);typeof m=="object"&&m!==null?(m.equals!==void 0&&(p.push(`${S} = ?`),u.push(m.equals)),m.in!==void 0&&(p.push(`${S} IN (${m.in.map(()=>"?").join(", ")})`),u.push(...m.in)),m.not_equals!==void 0&&(p.push(`${S} != ?`),u.push(m.not_equals))):(p.push(`${S} = ?`),u.push(m));}p.length>0&&(y+=` WHERE ${p.join(" AND ")}`);let g=i||"-createdAt",w=this.resolveCol(d,g),M=g.startsWith("-")?"DESC":"ASC";y+=` ORDER BY ${w} ${M}`;let U=y.replace("SELECT *","SELECT COUNT(*) as count"),D=this.db.prepare(U).get(...u)?.count||0;y+=" LIMIT ? OFFSET ?",u.push(o,(t-1)*o);let A=this.db.prepare(y).all(...u).map(h=>this.rowToDoc(h,c));return this.tenantContext&&!this.tenantContext.isSuperAdmin&&(A=A.filter(h=>chunkVQ53TFYA_cjs.d(h,a,this.tenantContext,chunkVQ53TFYA_cjs.b))),r&&(A=await Promise.all(A.map(async h=>{let m=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(a,h.id);if(m){let S=m.data?JSON.parse(m.data):{};return chunkZOVH6QT5_cjs.a({...h,...S,status:h.status})}return h}))),A=A.map(h=>chunkZOVH6QT5_cjs.a(h)),{docs:A,totalDocs:D,limit:o,totalPages:Math.ceil(D/o),page:t,pagingCounter:(t-1)*o+1,hasPrevPage:t>1,hasNextPage:t<Math.ceil(D/o),prevPage:t>1?t-1:null,nextPage:t<Math.ceil(D/o)?t+1:null}}async findByID(e){let{collection:a,id:n,tenantId:i,draft:o=false}=e,t=this.parseGlobalsSlug(a),s=t.isGlobal?this.globals.get(t.globalSlug):this.getCollection(a);this.ensureTable(s,t.tableName);let l=`SELECT * FROM ${t.tableName} WHERE id = ?`,c=[n];if(this.tenantContext&&s.tenantScoped){let f={id:n,tenant_id:this.tenantContext.tenantId};if(!chunkVQ53TFYA_cjs.d(f,a,this.tenantContext,chunkVQ53TFYA_cjs.b))return null}let d=s.fields.find(f=>f.name==="status"),y=d?.type==="select"&&Array.isArray(d.options)&&d.options.some(f=>f.value==="published");!o&&y&&(l+=" AND status = ?",c.push("published")),i&&s.tenantScoped&&(l+=" AND tenant_id = ?",c.push(i));let u=this.db.prepare(l).get(...c);if(!u)return null;let p=this.rowToDoc(u,s);if(o){let f=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(a,p.id);if(f){let E=f.data?JSON.parse(f.data):{};p={...p,...E,status:p.status};}}return chunkZOVH6QT5_cjs.a(p)}async create(e){let{collection:a,data:n,tenantId:i}=e,o=this.parseGlobalsSlug(a),t=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(a);this.ensureTable(t,o.tableName);let s=o.tableName,r=o.isGlobal?o.globalSlug:n.id||this.generateId(),l=this.prepareData(n,t);l.id=r;let c=new Date().toISOString();l.created_at=c,l.updated_at=c,i&&t.tenantScoped&&(l.tenant_id=i);let d=Object.keys(l),y=O(this.db,s),u={};for(let g of d)y.includes(g)&&(u[g]=l[g]);let p=Object.keys(u),f=p.map(g=>this.col(g)),E=p.map(()=>"?").join(", "),b=Object.values(u).map(g=>g!==null&&typeof g=="object"?JSON.stringify(g):g);return this.db.prepare(`INSERT OR REPLACE INTO ${s} (${f.join(", ")}) VALUES (${E})`).run(...b),this.ensureVersionsTable(),this.findByID({collection:a,id:r,tenantId:i,draft:true})}async update(e){let{collection:a,id:n,data:i,tenantId:o}=e,t=this.parseGlobalsSlug(a),s=t.isGlobal?this.globals.get(t.globalSlug):this.getCollection(a);this.ensureTable(s,t.tableName);let r=t.tableName,l=this.prepareData(i,s);l.updated_at=new Date().toISOString();let c=O(this.db,r),d={};for(let b of Object.keys(l))c.includes(b)&&(d[b]=l[b]);let u=Object.keys(d).map(b=>`${this.col(b)} = ?`).join(", "),p=Object.values(d).map(b=>b!==null&&typeof b=="object"?JSON.stringify(b):b),f=`UPDATE ${r} SET ${u} WHERE id = ?`,E=[...p,n];return o&&s.tenantScoped&&(f+=" AND tenant_id = ?",E.push(o)),this.db.prepare(f).run(...E),this.ensureVersionsTable(),this.findByID({collection:a,id:n,tenantId:o,draft:true})}async delete(e){let{collection:a,id:n,tenantId:i}=e,o=this.parseGlobalsSlug(a),t=o.isGlobal?this.globals.get(o.globalSlug):this.getCollection(a);this.ensureTable(t,o.tableName),this.ensureVersionsTable();let s=await this.findByID({collection:a,id:n,tenantId:i,draft:true});if(!s)throw new Error(`Document not found: ${a}/${n}`);let l=`DELETE FROM ${o.tableName} WHERE id = ?`,c=[n];return i&&t.tenantScoped&&(l+=" AND tenant_id = ?",c.push(i)),this.db.prepare(l).run(...c),s}async count(e){let{collection:a,tenantId:n}=e,i=this.parseGlobalsSlug(a),o=i.isGlobal?this.globals.get(i.globalSlug):this.getCollection(a);this.ensureTable(o,i.tableName);let s=`SELECT COUNT(*) as count FROM ${i.tableName}`,r=[];return n&&o.tenantScoped&&(s+=" WHERE tenant_id = ?",r.push(n)),this.db.prepare(s).get(...r)?.count||0}async findOne(e){let a=this.parseGlobalsSlug(e.collection);if(a.isGlobal){let i=this.globals.get(a.globalSlug);if(!i)throw new Error(`Global "${a.globalSlug}" not found in adapter`);this.ensureTable(i,a.tableName);let o=`SELECT * FROM ${a.tableName}`,t=[],s=[],r=i.fields.find(d=>d.name==="status"),l=r?.type==="select"&&Array.isArray(r.options)&&r.options.some(d=>d.value==="published");!e.draft&&i.versions&&l&&t.push("status = 'published'"),t.length>0&&(o+=` WHERE ${t.join(" AND ")}`),o+=" LIMIT 1";let c=this.db.prepare(o).get(...s);if(c){let d=this.rowToDoc(c,i);if(e.draft){let y=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND tenant_id IS NULL ORDER BY version DESC LIMIT 1`).get(e.collection,a.globalSlug);if(y){let u=y.data?JSON.parse(y.data):{};d={...d,...u,status:d.status};}}return d}return null}return (await this.find({...e,limit:1})).docs[0]||null}async findVersions(e){this.ensureVersionsTable();let{collection:a,documentId:n,tenantId:i,limit:o=20,page:t=1}=e,s=["collection_slug = ?","document_id = ?","autosave = 0"],r=[a,n];i?(s.push("tenant_id = ?"),r.push(i)):s.push("tenant_id IS NULL");let l=`WHERE ${s.join(" AND ")}`,d=this.db.prepare(`SELECT COUNT(*) as count FROM ${this.versionsTableName} ${l}`).get(...r)?.count||0,y=(t-1)*o;return {docs:this.db.prepare(`SELECT * FROM ${this.versionsTableName} ${l} ORDER BY version DESC LIMIT ? OFFSET ?`).all(...r,o,y).map(f=>this.rowToVersion(f)),totalDocs:d,limit:o,totalPages:Math.ceil(d/o),page:t,pagingCounter:(t-1)*o+1,hasPrevPage:t>1,hasNextPage:t<Math.ceil(d/o),prevPage:t>1?t-1:null,nextPage:t<Math.ceil(d/o)?t+1:null}}async findVersionByID(e){this.ensureVersionsTable();let a=this.db.prepare(`SELECT * FROM ${this.versionsTableName} WHERE id = ? AND collection_slug = ? LIMIT 1`).get(e.versionId,e.collection);return a?this.rowToVersion(a):null}async createVersion(e){this.ensureVersionsTable();let a=new Date().toISOString();if(e.autosave){let s=`SELECT * FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 1`,r=[e.collection,e.documentId];e.tenantId?(s+=" AND tenant_id = ?",r.push(e.tenantId)):s+=" AND tenant_id IS NULL",s+=" LIMIT 1";let l=this.db.prepare(s).get(...r);if(l){this.db.prepare(`UPDATE ${this.versionsTableName} SET data = ?, status = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(e.data),e.status,a,l.id);let c=await this.findVersionByID({collection:e.collection,versionId:l.id});if(c)return c}}let n=this.generateId(),o=(this.db.prepare(`SELECT version FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? AND autosave = 0 ORDER BY version DESC LIMIT 1`).get(e.collection,e.documentId)?.version??0)+1;if(this.db.prepare(`INSERT INTO ${this.versionsTableName} (
|
|
18
|
+
id, collection_slug, document_id, tenant_id, version, status, autosave, data, created_by, change_description, published_at, created_at, updated_at
|
|
19
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(n,e.collection,e.documentId,e.tenantId??null,o,e.status,e.autosave?1:0,JSON.stringify(e.data),e.createdBy??null,e.changeDescription??null,e.status==="published"?a:null,a,a),!e.autosave){let r=this.collections.get(e.collection)?.versions?.maxPerDoc;r&&r>0&&await this.deleteVersions({collection:e.collection,documentId:e.documentId,keepLatest:r,tenantId:e.tenantId});}return await this.findVersionByID({collection:e.collection,versionId:n})}async updateLatestVersion(e){return this.createVersion({...e,autosave:true})}async deleteVersions(e){this.ensureVersionsTable();let{collection:a,documentId:n,keepLatest:i,tenantId:o}=e;if(i&&i>0){let t=this.db.prepare(`SELECT id, status, autosave FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ? ORDER BY version DESC`).all(a,n),s=0,r=[];for(let l of t)l.status==="published"||l.autosave===1||(s++,s>i&&r.push(l.id));for(let l of r)this.db.prepare(`DELETE FROM ${this.versionsTableName} WHERE id = ?`).run(l);}else {let t=`DELETE FROM ${this.versionsTableName} WHERE collection_slug = ? AND document_id = ?`,s=[a,n];o&&(t+=" AND tenant_id = ?",s.push(o)),this.db.prepare(t).run(...s);}}rowToVersion(e){return {id:String(e.id),collection:e.collection_slug,documentId:e.document_id,version:e.version,status:e.status,data:e.data?JSON.parse(e.data):{},createdBy:e.created_by??void 0,changeDescription:e.change_description??void 0,publishedAt:e.published_at??null,createdAt:e.created_at,updatedAt:e.updated_at}}prepareData(e,a){let n={},i=N(a.fields),o=(t,s)=>{let r=t;if(r.type==="json"||r.type==="richtext"||r.type==="array"||r.type==="group"||r.type==="blocks"||r.type==="list"||r.type==="relationship-block")return s!=null?JSON.stringify(s):null;if(r.type==="checkbox")return s?1:0;if(r.type==="number")return s!==null&&s!==""?Number(s):null;if(r.type==="upload"||r.type==="image"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?c.id||c._id||c:String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify(s):String(s)}else if(t.type==="relationship"){if(s==null)return null;if(Array.isArray(s)){let l=s.map(c=>typeof c=="string"?c:typeof c=="object"?JSON.stringify({relationTo:t.relationTo,value:c.id||c}):String(c));return JSON.stringify(l)}return typeof s=="string"?s:typeof s=="object"?JSON.stringify({relationTo:t.relationTo,value:s.id||s}):String(s)}return s};for(let t of i){if(!t.name||t.name==="id"||a.fields.some(l=>l.type==="tabs"&&l.name&&"tabs"in l&&l.tabs.some(c=>c.fields.some(d=>d.name===t.name))))continue;let r=e[t.name];r!==void 0&&(n[t.name]=o(t,r));}for(let t of a.fields)if(t.type==="tabs"&&"tabs"in t&&t.name){let s=e[t.name];if(s&&typeof s=="object"){for(let r of t.tabs)for(let l of r.fields)if(l.name&&l.name!=="id"){let c=s[l.name];c!==void 0&&(n[l.name]=o(l,c));}}}return n}rowToDoc(e,a){let n={id:e.id};for(let i of N(a.fields)){if(!i.name||i.name==="id")continue;let o=i,t=e[o.name];if(o.type==="json"||o.type==="richtext"||o.type==="array"||o.type==="group"||o.type==="blocks"||o.type==="list"||o.type==="relationship-block")try{t=t?JSON.parse(t):null;}catch{t=null;}if(o.type==="blocks"&&t&&Array.isArray(t)){let s=o.blocks||[];t=P(t,s);}if(i.type==="checkbox"&&(t=!!t),i.type==="date"&&t)try{let s=new Date(t);isNaN(s.getTime())?(console.warn(`[LocalAdapter] Invalid date value for field "${i.name}":`,t),t=null):t=s.toISOString();}catch{t=null;}if((i.type==="upload"||i.type==="image")&&t)try{let s=JSON.parse(t);Array.isArray(s)?t=s.map(r=>typeof r=="object"&&r!==null?r:{id:r}):t=typeof s=="object"?s:{id:s};}catch{t={id:t};}if(i.type==="relationship"&&t)try{let s=JSON.parse(t);Array.isArray(s),t=s;}catch{t={relationTo:Array.isArray(i.relationTo)?i.relationTo[0]:i.relationTo,value:t};}n[i.name]=t;}for(let i of a.fields)if(!(!i.name||i.name==="id"||i.name==="row"||i.name==="collapsible")&&i.type==="tabs"&&"tabs"in i){let o={};for(let t of i.tabs)for(let s of t.fields)s.name&&s.name!=="id"&&(o[s.name]=G(e,s));n[i.name]=o;}if(a.timestamps){let i=e.createdAt||e.created_at,o=e.updatedAt||e.updated_at;if(i)try{let t=new Date(i);isNaN(t.getTime())||(n.createdAt=t.toISOString());}catch{}if(o)try{let t=new Date(o);isNaN(t.getTime())||(n.updatedAt=t.toISOString());}catch{}}a.tenantScoped&&(n.tenantId=e.tenant_id),n.status=e.status??"published",n.hasDraft=e.hasDraft?!!e.hasDraft:false;for(let i of Object.keys(n))/^\d+$/.test(i)&&delete n[i];return n}generateId(){let e=Date.now().toString(16).padStart(12,"0"),a=crypto.randomBytes(6).toString("hex");return e+a}getMediaById(e){try{let a=this.getTableNameFor("media"),n=this.db.prepare(`SELECT id, url, thumbnail_url FROM ${a} WHERE id = ?`).get(e);if(n)return {id:n.id,url:n.url,thumbnailUrl:n.thumbnail_url||n.url}}catch{}return null}getTableNameFor(e){return e.replace(/-/g,"_")}async migrate(){for(let e of this.collections.values())this.ensureTable(e);}async rollback(){}async transaction(e){return new Promise((a,n)=>{let i=this.db.transaction(async()=>e({db:this.db}));try{let o=i();a(o);}catch(o){n(o);}})}getDatabase(){return this.db}exec(e){this.db.exec(e);}prepare(e){return this.db.prepare(e)}};function B(T){return new L(T||{})}exports.a=L;exports.b=B;
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import {createRequire}from'module';import {B as B$1,A as A$1,p,q as q$1,b,m,o,n,k as k$1,r,e,c,D as D$1,d,f,l}from'./chunk-OSAVAYJZ.js';import {g}from'./chunk-C2PXMVR5.js';import {join,sep}from'path';import {homedir}from'os';import {readFile}from'fs/promises';import {createHash}from'crypto';createRequire(import.meta.url);
|
|
2
|
+
g();var te;(function(r){r.MD5="md5",r.CRC32="crc32",r.CRC32C="crc32c",r.SHA1="sha1",r.SHA256="sha256";})(te||(te={}));g();g();var re="__smithy_context";g();g();var ye;(function(r){r.HTTP="http",r.HTTPS="https";})(ye||(ye={}));g();var _;(function(r){r.PROFILE="profile",r.SSO_SESSION="sso-session",r.SERVICES="services";})(_||(_={}));g();var H=r=>r[re]||(r[re]={});g();var Lt=r=>{if(typeof r=="function")return r;let e=Promise.resolve(r);return ()=>e};g();g();function qe(r){let e={};if(r=r.replace(/^\?/,""),r)for(let t of r.split("&")){let[o,s=null]=t.split("=");o=decodeURIComponent(o),s&&(s=decodeURIComponent(s)),o in e?Array.isArray(e[o])?e[o].push(s):e[o]=[e[o],s]:e[o]=s;}return e}var M=r=>{if(typeof r=="string")return M(new URL(r));let{hostname:e,pathname:t,port:o,protocol:s,search:n}=r,a;return n&&(a=qe(n)),{hostname:e,port:o?parseInt(o):void 0,protocol:s,path:t,query:a}};g();g();var N=class r{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?e.protocol.slice(-1)!==":"?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?e.path.charAt(0)!=="/"?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment;}static clone(e){let t=new r({...e,headers:{...e.headers}});return t.query&&(t.query=zt(t.query)),t}static isInstance(e){if(!e)return false;let t=e;return "method"in t&&"protocol"in t&&"hostname"in t&&"path"in t&&typeof t.query=="object"&&typeof t.headers=="object"}clone(){return r.clone(this)}};function zt(r){return Object.keys(r).reduce((e,t)=>{let o=r[t];return {...e,[t]:Array.isArray(o)?[...o]:o}},{})}g();var v=class{statusCode;reason;headers;body;constructor(e){this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body;}static isInstance(e){if(!e)return false;let t=e;return typeof t.statusCode=="number"&&typeof t.headers=="object"}};g();var Ht=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),oe=(r,e=false)=>{if(!e)return Ht.test(r);let t=r.split(".");for(let o of t)if(!oe(o))return false;return true};g();function xe(r){return /^[a-z0-9][a-z0-9.-]*[a-z0-9]$/.test(r)}g();var Te=r=>{if(typeof r=="object"){if("url"in r){let e=M(r.url);if(r.headers){e.headers={};for(let t in r.headers)e.headers[t.toLowerCase()]=r.headers[t].join(", ");}return e}return r}return M(r)};g();g();g();var se=(r,e,t,o,s)=>({name:e,namespace:r,traits:t,input:o,output:s});var Qe=r=>(e,t)=>async o=>{let{response:s}=await e(o),{operationSchema:n}=H(t),[,a,h,f,l,g]=n??[];try{let d=await r.protocol.deserializeResponse(se(a,h,f,l,g),{...r,...t},s);return {response:s,output:d}}catch(d){if(Object.defineProperty(d,"$response",{value:s,enumerable:false,writable:false,configurable:false}),!("$metadata"in d)){let E="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{d.message+=`
|
|
3
|
+
`+E;}catch{!t.logger||t.logger?.constructor?.name==="NoOpLogger"?console.warn(E):t.logger?.warn?.(E);}typeof d.$responseBodyText<"u"&&d.$response&&(d.$response.body=d.$responseBodyText);try{if(v.isInstance(s)){let{headers:y={},statusCode:u}=s,p=Object.entries(y);d.$metadata={httpStatusCode:u,requestId:be(/^x-[\w-]+-request-?id$/,p),extendedRequestId:be(/^x-[\w-]+-id-2$/,p),cfId:be(/^x-[\w-]+-cf-id$/,p)};}}catch{}}throw d}},be=(r,e)=>(e.find(([t])=>t.match(r))||[void 0,void 0])[1];g();var Xe=r=>(e,t)=>async o=>{let{operationSchema:s}=H(t),[,n,a,h,f,l]=s??[],g=t.endpointV2?async()=>Te(t.endpointV2):r.endpoint,d=await r.protocol.serializeRequest(se(n,a,h,f,l),o.input,{...r,...t,endpoint:g});return e({...o,request:d})};var Je={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:true},Ye={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:true};function Ut(r){return {applyToStack:e=>{e.add(Xe(r),Ye),e.add(Qe(r),Je),r.protocol.setSerdeContext(r);}}}g();var U=class r{namespace;schemas;exceptions;static registries=new Map;constructor(e,t=new Map,o=new Map){this.namespace=e,this.schemas=t,this.exceptions=o;}static for(e){return r.registries.has(e)||r.registries.set(e,new r(e)),r.registries.get(e)}copyFrom(e){let{schemas:t,exceptions:o}=this;for(let[s,n]of e.schemas)t.has(s)||t.set(s,n);for(let[s,n]of e.exceptions)o.has(s)||o.set(s,n);}register(e,t){let o=this.normalizeShapeId(e);for(let s of [this,r.for(o.split("#")[0])])s.schemas.set(o,t);}getSchema(e){let t=this.normalizeShapeId(e);if(!this.schemas.has(t)){if(!e.includes("#")){let o="#"+e,s=[];for(let[n,a]of this.schemas.entries())n.endsWith(o)&&s.push(a);if(s.length===1)return s[0]}throw new Error(`@smithy/core/schema - schema not found for ${t}`)}return this.schemas.get(t)}registerError(e,t){let o=e,s=o[1];for(let n of [this,r.for(s)])n.schemas.set(s+"#"+o[2],o),n.exceptions.set(o,t);}getErrorCtor(e){let t=e;return this.exceptions.has(t)?this.exceptions.get(t):r.for(t[1]).exceptions.get(t)}getBaseException(){for(let e of this.exceptions.keys())if(Array.isArray(e)){let[,t,o]=e,s=t+"#"+o;if(s.startsWith("smithy.ts.sdk.synthetic.")&&s.endsWith("ServiceException"))return e}}find(e){for(let t of this.schemas.values())if(e(t))return t}clear(){this.schemas.clear(),this.exceptions.clear();}normalizeShapeId(e){return e.includes("#")?e:this.namespace+"#"+e}};g();g();var k=r=>typeof r=="function"?r():r;g();g();var ie=[];function w(r){if(typeof r=="object")return r;if(r=r|0,ie[r])return ie[r];let e={},t=0;for(let o of ["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])(r>>t++&1)===1&&(e[o]=1);return ie[r]=e}var $={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},ne=[],ae={},x=class r{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=r.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(e,t){this.ref=e,this.memberName=t;let o=[],s=e,n=e;for(this._isMemberSchema=false;Ne(s);)o.push(s[1]),s=s[0],n=k(s),this._isMemberSchema=true;if(o.length>0){this.memberTraits={};for(let a=o.length-1;a>=0;--a){let h=o[a];Object.assign(this.memberTraits,w(h));}}else this.memberTraits=0;if(n instanceof r){let a=this.memberTraits;Object.assign(this,n),this.memberTraits=Object.assign({},a,n.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=t??n.memberName;return}if(this.schema=k(n),Ze(this.schema)?(this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3]):(this.name=this.memberName??String(n),this.traits=0),this._isMemberSchema&&!t)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`)}static[Symbol.hasInstance](e){let t=this.prototype.isPrototypeOf(e);return !t&&typeof e=="object"&&e!==null?e.symbol===this.symbol:t}static of(e){let t=typeof e=="function"||typeof e=="object"&&e!==null;if(typeof e=="number"){if(ne[e])return ne[e]}else if(typeof e=="string"){if(ae[e])return ae[e]}else if(t&&e[$.ns])return e[$.ns];let o=k(e);if(o instanceof r)return o;if(Ne(o)){let[n,a]=o;if(n instanceof r)return Object.assign(n.getMergedTraits(),w(a)),n;throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(e,null,2)}.`)}let s=new r(o);return t?e[$.ns]=s:typeof o=="string"?ae[o]=s:typeof o=="number"?ne[o]=s:s}getSchema(){let e=this.schema;return Array.isArray(e)&&e[0]===0?e[4]:e}getName(e=false){let{name:t}=this;return !e&&t&&t.includes("#")?t.split("#")[1]:t||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){let e=this.getSchema();return typeof e=="number"?e>=64&&e<128:e[0]===1}isMapSchema(){let e=this.getSchema();return typeof e=="number"?e>=128&&e<=255:e[0]===2}isStructSchema(){let e=this.getSchema();if(typeof e!="object")return false;let t=e[0];return t===3||t===-3||t===4}isUnionSchema(){let e=this.getSchema();return typeof e!="object"?false:e[0]===4}isBlobSchema(){let e=this.getSchema();return e===21||e===42}isTimestampSchema(){let e=this.getSchema();return typeof e=="number"&&e>=4&&e<=7}isUnitSchema(){return this.getSchema()==="unit"}isDocumentSchema(){return this.getSchema()===15}isStringSchema(){return this.getSchema()===0}isBooleanSchema(){return this.getSchema()===2}isNumericSchema(){return this.getSchema()===1}isBigIntegerSchema(){return this.getSchema()===17}isBigDecimalSchema(){return this.getSchema()===19}isStreaming(){let{streaming:e}=this.getMergedTraits();return !!e||this.getSchema()===42}isIdempotencyToken(){return !!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return w(this.memberTraits)}getOwnTraits(){return w(this.traits)}getKeySchema(){let[e,t]=[this.isDocumentSchema(),this.isMapSchema()];if(!e&&!t)throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`);let o=this.getSchema(),s=e?15:o[4]??0;return V([s,0],"key")}getValueSchema(){let e=this.getSchema(),[t,o,s]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],n=typeof e=="number"?63&e:e&&typeof e=="object"&&(o||s)?e[3+e[0]]:t?15:void 0;if(n!=null)return V([n,0],o?"value":"member");throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`)}getMemberSchema(e){let t=this.getSchema();if(this.isStructSchema()&&t[4].includes(e)){let o=t[4].indexOf(e),s=t[5][o];return V(Ne(s)?s:[s,0],e)}if(this.isDocumentSchema())return V([15,0],e);throw new Error(`@smithy/core/schema - ${this.getName(true)} has no member=${e}.`)}getMemberSchemas(){let e={};try{for(let[t,o]of this.structIterator())e[t]=o;}catch{}return e}getEventStreamMember(){if(this.isStructSchema()){for(let[e,t]of this.structIterator())if(t.isStreaming()&&t.isStructSchema())return e}return ""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");let e=this.getSchema(),t=e[4].length,o=e[$.it];if(o&&t===o.length){yield*o;return}o=Array(t);for(let s=0;s<t;++s){let n=e[4][s],a=V([e[5][s],0],n);yield o[s]=[n,a];}e[$.it]=o;}};function V(r,e){if(r instanceof x)return Object.assign(r,{memberName:e,_isMemberSchema:true});let t=x;return new t(r,e)}var Ne=r=>Array.isArray(r)&&r.length===2,Ze=r=>Array.isArray(r)&&r.length>=5;g();var I=class r extends Error{name="ProviderError";tryNextLink;constructor(e,t=true){let o,s=true;typeof t=="boolean"?(o=void 0,s=t):t!=null&&typeof t=="object"&&(o=t.logger,s=t.tryNextLink??true),super(e),this.tryNextLink=s,Object.setPrototypeOf(this,r.prototype),o?.debug?.(`@smithy/property-provider ${s?"->":"(!)"} ${e}`);}static from(e,t=true){return Object.assign(new this(e.message,t),e)}};g();var P=class r extends I{name="CredentialsProviderError";constructor(e,t=true){super(e,t),Object.setPrototypeOf(this,r.prototype);}};g();var et="AWS_PROFILE",tt="default",Ce=r=>r.profile||process.env[et]||tt;g();g();g();var _e={},Vt=()=>process&&process.geteuid?`${process.geteuid()}`:"DEFAULT",F=()=>{let{HOME:r,USERPROFILE:e,HOMEPATH:t,HOMEDRIVE:o=`C:${sep}`}=process.env;if(r)return r;if(e)return e;if(t)return `${o}${t}`;let s=Vt();return _e[s]||(_e[s]=homedir()),_e[s]};var Gt="AWS_CONFIG_FILE",ce=()=>process.env[Gt]||join(F(),".aws","config");g();g();g();var rt=r=>Object.entries(r).filter(([e])=>{let t=e.indexOf(".");return t===-1?false:Object.values(_).includes(e.substring(0,t))}).reduce((e,[t,o])=>{let s=t.indexOf("."),n=t.substring(0,s)===_.PROFILE?t.substring(s+1):t;return e[n]=o,e},{...r.default&&{default:r.default}});g();var Wt="AWS_SHARED_CREDENTIALS_FILE",ot=()=>process.env[Wt]||join(F(),".aws","credentials");g();var Kt=/^([\w-]+)\s(["'])?([\w-@+.%:/]+)\2$/,qt=["__proto__","profile __proto__"],G=r=>{let e={},t,o;for(let s of r.split(/\r?\n/)){let n=s.split(/(^|\s)[;#]/)[0].trim();if(n[0]==="["&&n[n.length-1]==="]"){t=void 0,o=void 0;let h=n.substring(1,n.length-1),f=Kt.exec(h);if(f){let[,l,,g]=f;Object.values(_).includes(l)&&(t=[l,g].join("."));}else t=h;if(qt.includes(h))throw new Error(`Found invalid profile name "${h}"`)}else if(t){let h=n.indexOf("=");if(![0,-1].includes(h)){let[f,l]=[n.substring(0,h).trim(),n.substring(h+1).trim()];if(l==="")o=f;else {o&&s.trimStart()===s&&(o=void 0),e[t]=e[t]||{};let g=o?[o,f].join("."):f;e[t][g]=l;}}}}return e};g();var we={},B={},L=(r,e)=>B[r]!==void 0?B[r]:((!we[r]||e?.ignoreCache)&&(we[r]=readFile(r,"utf8")),we[r]);var it=()=>({}),me=async(r={})=>{let{filepath:e=ot(),configFilepath:t=ce()}=r,o=F(),s="~/",n=e;e.startsWith(s)&&(n=join(o,e.slice(2)));let a=t;t.startsWith(s)&&(a=join(o,t.slice(2)));let h=await Promise.all([L(a,{ignoreCache:r.ignoreCache}).then(G).then(rt).catch(it),L(n,{ignoreCache:r.ignoreCache}).then(G).catch(it)]);return {configFile:h[0],credentialsFile:h[1]}};var nt=r=>Object.entries(r).filter(([e])=>e.startsWith(_.SSO_SESSION+".")).reduce((e,[t,o])=>({...e,[t.substring(t.indexOf(".")+1)]:o}),{});var Xt=()=>({}),Jt=async(r={})=>L(r.configFilepath??ce()).then(G).then(nt).catch(Xt);g();g();var at=(...r)=>{let e={};for(let t of r)for(let[o,s]of Object.entries(t))e[o]!==void 0?Object.assign(e[o],s):e[o]=s;return e};var Yt=async r=>{let e=await me(r);return at(e.configFile,e.credentialsFile)};g();g();g();var Oe=r=>{let t=createHash("sha1").update(r).digest("hex");return join(F(),".aws","sso","cache",`${t}.json`)};var W={},rr=async r=>{if(W[r])return W[r];let e=Oe(r),t=await readFile(e,"utf8");return JSON.parse(t)};var or={getFileRecord(){return B},interceptFile(r,e){B[r]=Promise.resolve(e);},getTokenRecord(){return W},interceptToken(r,e){W[r]=e;}};g();g();var Ie=(...r)=>async()=>{if(r.length===0)throw new I("No providers in chain");let e;for(let t of r)try{return await t()}catch(o){if(e=o,o?.tryNextLink)continue;throw o}throw e};g();var fe=(r,e,t)=>{let o,s,n,a=false,h=async()=>{s||(s=r());try{o=await s,n=!0,a=!1;}finally{s=void 0;}return o};return e===void 0?async f=>((!n||f?.forceRefresh)&&(o=await h()),o):async f=>((!n||f?.forceRefresh)&&(o=await h()),a?o:t&&!t(o)?(a=true,o):(e(o)&&await h(),o))};g();g();function he(r){try{let e=new Set(Array.from(r.match(/([A-Z_]){3,}/g)??[]));return e.delete("CONFIG"),e.delete("CONFIG_PREFIX_SEPARATOR"),e.delete("ENV"),[...e].join(", ")}catch{return r}}var ct=(r,e)=>async()=>{try{let t=r(process.env,e);if(t===void 0)throw new Error;return t}catch(t){throw new P(t.message||`Not found in ENV: ${he(r.toString())}`,{logger:e?.logger})}};g();var mt=(r,{preferredFile:e="config",...t}={})=>async()=>{let o=Ce(t),{configFile:s,credentialsFile:n}=await me(t),a=n[o]||{},h=s[o]||{},f=e==="config"?{...a,...h}:{...h,...a};try{let g=r(f,e==="config"?s:n);if(g===void 0)throw new Error;return g}catch(l){throw new P(l.message||`Not found in config files w/ profile [${o}]: ${he(r.toString())}`,{logger:t.logger})}};g();g();var ft=r=>()=>Promise.resolve(r);var sr=r=>typeof r=="function",ht=r=>sr(r)?async()=>await r():ft(r);var le=({environmentVariableSelector:r,configFileSelector:e,default:t},o={})=>{let{signingName:s,logger:n}=o;return fe(Ie(ct(r,{signingName:s,logger:n}),mt(e,o),ht(t)))};g();g();var lt=new Set,pt=(r,e=oe)=>{if(!lt.has(r)&&!e(r))if(r==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw new Error(`Region not accepted: region="${r}" is not a valid hostname component.`);else lt.add(r);};g();g();var pe=r=>typeof r=="string"&&(r.startsWith("fips-")||r.endsWith("-fips"));var dt=r=>pe(r)?["fips-aws-global","aws-fips"].includes(r)?"us-east-1":r.replace(/fips-(dkr-|prod-)?|-fips/,""):r;var ir=r=>{let{region:e,useFipsEndpoint:t}=r;if(!e)throw new Error("Region is missing");return Object.assign(r,{region:async()=>{let o=typeof e=="function"?await e():e,s=dt(o);return pt(s),s},useFipsEndpoint:async()=>{let o=typeof e=="string"?e:await e();return pe(o)?true:typeof t!="function"?Promise.resolve(!!t):t()}})};g();g();var Ae=class r extends I{name="TokenProviderError";constructor(e,t=true){super(e,t),Object.setPrototypeOf(this,r.prototype);}};g();var R=(r,e,t)=>{if(e in r){if(r[e]==="true")return true;if(r[e]==="false")return false;throw new Error(`Cannot load ${t} "${e}". Expected "true" or "false", got ${r[e]}.`)}};g();var A;(function(r){r.ENV="env",r.CONFIG="shared config entry";})(A||(A={}));g();var ut="AWS_USE_DUALSTACK_ENDPOINT",gt="use_dualstack_endpoint";var nr={environmentVariableSelector:r=>R(r,ut,A.ENV),configFileSelector:r=>R(r,gt,A.CONFIG),default:false};g();var St="AWS_USE_FIPS_ENDPOINT",Et="use_fips_endpoint";var ar={environmentVariableSelector:r=>R(r,St,A.ENV),configFileSelector:r=>R(r,Et,A.CONFIG),default:false};g();g();g();var yt="AWS_EXECUTION_ENV",De="AWS_REGION",ve="AWS_DEFAULT_REGION",xt="AWS_EC2_METADATA_DISABLED",Tt=["in-region","cross-region","mobile","standard","legacy"],bt="/latest/meta-data/placement/region",Nt="/latest/api/token",Ct="x-aws-ec2-metadata-token",_t="x-aws-ec2-metadata-token-ttl-seconds";var wt=1e3,cr=6e4,At=0,de=async()=>{if(!process.env[xt]&&!(Date.now()<At))try{let r=mr(),e=(await It({...r,path:Nt,method:"PUT",headers:{[_t]:"21600"}})).toString();return (await It({...r,path:bt,method:"GET",headers:{[Ct]:e}})).toString().trim()||Ot()}catch{return Ot()}},Ot=()=>{At=Date.now()+cr;},mr=()=>{let r=process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT;if(r){let e=new URL(r);return {hostname:e.hostname.replace(/^\[(.+)]$/,"$1"),port:e.port?Number(e.port):void 0}}return process.env.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE==="IPv6"?{hostname:"fd00:ec2::254"}:{hostname:"169.254.169.254"}},It=async r=>{let{request:e}=await import('http');return new Promise((t,o)=>{let s=e({hostname:r.hostname,port:r.port,path:r.path,method:r.method,headers:r.headers,timeout:wt,signal:AbortSignal.timeout(wt)});s.on("error",n=>{o(n),s.destroy();}),s.on("timeout",()=>{o(new Error("TimeoutError from instance metadata service")),s.destroy();}),s.on("response",n=>{let{statusCode:a=400}=n;if(a<200||a>=300){o(Object.assign(new Error("Error response received from instance metadata service"),{statusCode:a})),s.destroy();return}let h=[];n.on("data",f=>h.push(f)),n.on("end",()=>{t(Buffer.concat(h)),s.destroy();});}),s.end();})};var Dt="AWS_REGION",vt="region",Fe={environmentVariableSelector:r=>r[Dt],configFileSelector:r=>r[vt],default:async()=>{let r=await de();if(r)return r;throw new Error("Region is missing")}},fr={preferredFile:"credentials"};g();g();var hr="AWS_DEFAULTS_MODE",lr="defaults_mode",Ft={environmentVariableSelector:r=>r[hr],configFileSelector:r=>r[lr],default:"legacy"};var pr=({region:r=le(Fe),defaultsMode:e=le(Ft)}={})=>fe(async()=>{let t=typeof e=="function"?await e():e;switch(t?.toLowerCase()){case "auto":return dr(r);case "in-region":case "cross-region":case "mobile":case "standard":case "legacy":return Promise.resolve(t?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${Tt.join(", ")}, got ${t}`)}}),dr=async r=>{if(r){let e=typeof r=="function"?await r():r,t=await ur();return t?e===t?"in-region":"cross-region":"standard"}return "standard"},ur=async()=>process.env[yt]&&(process.env[De]||process.env[ve])?process.env[De]??process.env[ve]:de();g();var Pt="content-length";function Rt(r){return e=>async t=>{let o=t.request;if(N.isInstance(o)){let{body:s,headers:n}=o;if(s&&Object.keys(n).map(a=>a.toLowerCase()).indexOf(Pt)===-1)try{let a=r(s);o.headers={...o.headers,[Pt]:String(a)};}catch{}}return e({...t,request:o})}}var Mt={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:true},gr=r=>({applyToStack:e=>{e.add(Rt(r.bodyLengthChecker),Mt);}});g();g();var D=async(r=new Uint8Array,e)=>{if(r instanceof Uint8Array)return B$1.mutate(r);if(!r)return B$1.mutate(new Uint8Array);let t=e.streamCollector(r);return B$1.mutate(await t)};g();function ue(r){return encodeURIComponent(r).replace(/[!'()*]/g,function(e){return "%"+e.charCodeAt(0).toString(16).toUpperCase()})}g();g();g();var O=class{serdeContext;setSerdeContext(e){this.serdeContext=e;}};var z=class extends O{options;compositeErrorRegistry;constructor(e){super(),this.options=e,this.compositeErrorRegistry=U.for(e.defaultNamespace);for(let t of e.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t);}getRequestType(){return N}getResponseType(){return v}setSerdeContext(e){this.serdeContext=e,this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e),this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(e);}updateServiceEndpoint(e,t){if("url"in t){e.protocol=t.url.protocol,e.hostname=t.url.hostname,e.port=t.url.port?Number(t.url.port):void 0,e.path=t.url.pathname,e.fragment=t.url.hash||void 0,e.username=t.url.username||void 0,e.password=t.url.password||void 0,e.query||(e.query={});for(let[o,s]of t.url.searchParams.entries())e.query[o]=s;if(t.headers)for(let o in t.headers)e.headers[o]=t.headers[o].join(", ");return e}else {if(e.protocol=t.protocol,e.hostname=t.hostname,e.port=t.port?Number(t.port):void 0,e.path=t.path,e.query={...t.query},t.headers)for(let o in t.headers)e.headers[o]=t.headers[o];return e}}setHostPrefix(e,t,o){if(this.serdeContext?.disableHostPrefix)return;let s=x.of(t.input),n=w(t.traits??{});if(n.endpoint){let a=n.endpoint?.[0];if(typeof a=="string"){for(let[h,f]of s.structIterator()){if(!f.getMergedTraits().hostLabel)continue;let l=o[h];if(typeof l!="string")throw new Error(`@smithy/core/schema - ${h} in input must be a string as hostLabel.`);a=a.replace(`{${h}}`,l);}if(e.hostname=a+e.hostname,!xe(e.hostname))throw new Error(`[${e.hostname}] is not a valid hostname.`)}}}deserializeMetadata(e){return {httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:e,requestSchema:t,initialRequest:o}){return (await this.loadEventStreamCapability()).serializeEventStream({eventStream:e,requestSchema:t,initialRequest:o})}async deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:o}){return (await this.loadEventStreamCapability()).deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:o})}async loadEventStreamCapability(){let{EventStreamSerde:e,eventStreamSerdeProvider:t}=await import('./event-streams-25YJ2Z6R.js'),o=this.resolveEventStreamMarshaller(t);return new e({marshaller:o,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(e){let t=this.serdeContext;return t.eventStreamMarshaller?t.eventStreamMarshaller:e(this.serdeContext)}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(e,t,o,s,n){return []}getEventStreamMarshaller(){let e=this.serdeContext;if(!e.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return e.eventStreamMarshaller}};var Pe=class extends z{async serializeRequest(e,t,o){let s=t&&typeof t=="object"?t:{},n=this.serializer,a={},h={},f=await o.endpoint(),l=x.of(e?.input),g=[],d=[],E=false,y,u=new N({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:a,headers:h,body:void 0});if(f){this.updateServiceEndpoint(u,f),this.setHostPrefix(u,e,s);let p=w(e.traits);if(p.http){u.method=p.http[0];let[S,T]=p.http[1].split("?");u.path=="/"?u.path=S:u.path+=S;let b=new URLSearchParams(T??"");for(let[C,X]of b)a[C]=X;}}for(let[p,S]of l.structIterator()){let T=S.getMergedTraits()??{},b=s[p];if(b==null&&!S.isIdempotencyToken()){if(T.httpLabel&&(u.path.includes(`{${p}+}`)||u.path.includes(`{${p}}`)))throw new Error(`No value provided for input HTTP label: ${p}.`);continue}if(T.httpPayload)S.isStreaming()?S.isStructSchema()?s[p]&&(y=await this.serializeEventStream({eventStream:s[p],requestSchema:l})):y=b:(n.write(S,b),y=n.flush());else if(T.httpLabel){n.write(S,b);let C=n.flush();u.path.includes(`{${p}+}`)?u.path=u.path.replace(`{${p}+}`,C.split("/").map(ue).join("/")):u.path.includes(`{${p}}`)&&(u.path=u.path.replace(`{${p}}`,ue(C)));}else if(T.httpHeader)n.write(S,b),h[T.httpHeader.toLowerCase()]=String(n.flush());else if(typeof T.httpPrefixHeaders=="string")for(let C in b){let X=b[C],ze=T.httpPrefixHeaders+C;n.write([S.getValueSchema(),{httpHeader:ze}],X),h[ze.toLowerCase()]=n.flush();}else T.httpQuery||T.httpQueryParams?this.serializeQuery(S,b,a):(E=true,g.push(p),d.push(S));}if(E&&s){let[p,S]=(l.getName(true)??"#Unknown").split("#"),T=l.getSchema()[6],b=[3,p,S,l.getMergedTraits(),g,d,void 0];T?b[6]=T:b.pop(),n.write(b,s),y=n.flush();}return u.headers=h,u.query=a,u.body=y,u}serializeQuery(e,t,o){let s=this.serializer,n=e.getMergedTraits();if(n.httpQueryParams){for(let a in t)if(!(a in o)){let h=t[a],f=e.getValueSchema();Object.assign(f.getMergedTraits(),{...n,httpQuery:a,httpQueryParams:void 0}),this.serializeQuery(f,h,o);}return}if(e.isListSchema()){let a=!!e.getMergedTraits().sparse,h=[];for(let f of t){s.write([e.getValueSchema(),n],f);let l=s.flush();(a||l!==void 0)&&h.push(l);}o[n.httpQuery]=h;}else s.write([e,n],t),o[n.httpQuery]=s.flush();}async deserializeResponse(e,t,o){let s=this.deserializer,n=x.of(e.output),a={};if(o.statusCode>=300){let f=await D(o.body,t);throw f.byteLength>0&&Object.assign(a,await s.read(15,f)),await this.handleError(e,t,o,a,this.deserializeMetadata(o)),new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(let f in o.headers){let l=o.headers[f];delete o.headers[f],o.headers[f.toLowerCase()]=l;}let h=await this.deserializeHttpMessage(n,t,o,a);if(h.length){let f=await D(o.body,t);if(f.byteLength>0){let l=await s.read(n,f);for(let g of h)l[g]!=null&&(a[g]=l[g]);}}else h.discardResponseBody&&await D(o.body,t);return a.$metadata=this.deserializeMetadata(o),a}async deserializeHttpMessage(e,t,o,s,n){let a;s instanceof Set?a=n:a=s;let h=true,f=this.deserializer,l=x.of(e),g=[];for(let[d,E]of l.structIterator()){let y=E.getMemberTraits();if(y.httpPayload){if(h=false,E.isStreaming())E.isStructSchema()?a[d]=await this.deserializeEventStream({response:o,responseSchema:l}):a[d]=A$1(o.body);else if(o.body){let p=await D(o.body,t);p.byteLength>0&&(a[d]=await f.read(E,p));}}else if(y.httpHeader){let u=String(y.httpHeader).toLowerCase(),p$1=o.headers[u];if(p$1!=null)if(E.isListSchema()){let S=E.getValueSchema();S.getMergedTraits().httpHeader=u;let T;S.isTimestampSchema()&&S.getSchema()===4?T=p(p$1,",",2):T=q$1(p$1);let b=[];for(let C of T)b.push(await f.read(S,C.trim()));a[d]=b;}else a[d]=await f.read(E,p$1);}else if(y.httpPrefixHeaders!==void 0){a[d]={};for(let u in o.headers)if(u.startsWith(y.httpPrefixHeaders)){let p=o.headers[u],S=E.getValueSchema();S.getMergedTraits().httpHeader=u,a[d][u.slice(y.httpPrefixHeaders.length)]=await f.read(S,p);}}else y.httpResponseCode?a[d]=o.statusCode:g.push(d);}return g.discardResponseBody=h,g}};g();var Re=class extends z{async serializeRequest(e,t,o){let s=this.serializer,n={},a={},h=await o.endpoint(),f=x.of(e?.input),l=f.getSchema(),g,d=t&&typeof t=="object"?t:{},E=new N({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:n,headers:a,body:void 0});if(h&&(this.updateServiceEndpoint(E,h),this.setHostPrefix(E,e,d)),d){let y=f.getEventStreamMember();if(y){if(d[y]){let u={};for(let[p,S]of f.structIterator())p!==y&&d[p]&&(s.write(S,d[p]),u[p]=s.flush());g=await this.serializeEventStream({eventStream:d[y],requestSchema:f,initialRequest:u});}}else s.write(l,d),g=s.flush();}return E.headers=Object.assign(E.headers,a),E.query=n,E.body=g,E.method="POST",E}async deserializeResponse(e,t,o){let s=this.deserializer,n=x.of(e.output),a={};if(o.statusCode>=300){let f=await D(o.body,t);throw f.byteLength>0&&Object.assign(a,await s.read(15,f)),await this.handleError(e,t,o,a,this.deserializeMetadata(o)),new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(let f in o.headers){let l=o.headers[f];delete o.headers[f],o.headers[f.toLowerCase()]=l;}let h=n.getEventStreamMember();if(h)a[h]=await this.deserializeEventStream({response:o,responseSchema:n,initialResponseContainer:a});else {let f=await D(o.body,t);f.byteLength>0&&Object.assign(a,await s.read(n,f));}return a.$metadata=this.deserializeMetadata(o),a}};g();g();function K(r,e){if(e.timestampFormat.useTrait&&r.isTimestampSchema()&&(r.getSchema()===5||r.getSchema()===6||r.getSchema()===7))return r.getSchema();let{httpLabel:t,httpPrefixHeaders:o,httpHeader:s,httpQuery:n}=r.getMergedTraits();return (e.httpBindings?typeof o=="string"||s?6:n||t?5:void 0:void 0)??e.timestampFormat.default}var q=class extends O{settings;constructor(e){super(),this.settings=e;}read(e,t){let o$1=x.of(e);if(o$1.isListSchema())return q$1(t).map(s=>this.read(o$1.getValueSchema(),s));if(o$1.isBlobSchema())return (this.serdeContext?.base64Decoder??b)(t);if(o$1.isTimestampSchema())switch(K(o$1,this.settings)){case 5:return n(t);case 6:return o(t);case 7:return m(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(o$1.isStringSchema()){let s=o$1.getMergedTraits().mediaType,n=t;if(s)return o$1.getMergedTraits().httpHeader&&(n=this.base64ToUtf8(n)),(s==="application/json"||s.endsWith("+json"))&&(n=k$1.from(n)),n}return o$1.isNumericSchema()?Number(t):o$1.isBigIntegerSchema()?BigInt(t):o$1.isBigDecimalSchema()?new r(t,"bigDecimal"):o$1.isBooleanSchema()?String(t).toLowerCase()==="true":t}base64ToUtf8(e$1){return (this.serdeContext?.utf8Encoder??e)((this.serdeContext?.base64Decoder??b)(e$1))}};g();var Me=class extends O{codecDeserializer;stringDeserializer;constructor(e,t){super(),this.codecDeserializer=e,this.stringDeserializer=new q(t);}setSerdeContext(e){this.stringDeserializer.setSerdeContext(e),this.codecDeserializer.setSerdeContext(e),this.serdeContext=e;}read(e$1,t){let o=x.of(e$1),s=o.getMergedTraits(),n=this.serdeContext?.utf8Encoder??e;if(s.httpHeader||s.httpResponseCode)return this.stringDeserializer.read(o,n(t));if(s.httpPayload){if(o.isBlobSchema()){let a=this.serdeContext?.utf8Decoder??c;return typeof t=="string"?a(t):t}else if(o.isStringSchema())return "byteLength"in t?n(t):t}return this.codecDeserializer.read(o,t)}};g();g();var ge=class extends O{settings;stringBuffer="";constructor(e){super(),this.settings=e;}write(e,t){let o=x.of(e);switch(typeof t){case "object":if(t===null){this.stringBuffer="null";return}if(o.isTimestampSchema()){if(!(t instanceof Date))throw new Error(`@smithy/core/protocols - received non-Date value ${t} when schema expected Date in ${o.getName(true)}`);switch(K(o,this.settings)){case 5:this.stringBuffer=t.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=f(t);break;case 7:this.stringBuffer=String(t.getTime()/1e3);break;default:console.warn("Missing timestamp format, using epoch seconds",t),this.stringBuffer=String(t.getTime()/1e3);}return}if(o.isBlobSchema()&&"byteLength"in t){this.stringBuffer=(this.serdeContext?.base64Encoder??d)(t);return}if(o.isListSchema()&&Array.isArray(t)){let a="";for(let h of t){this.write([o.getValueSchema(),o.getMergedTraits()],h);let f=this.flush(),l$1=o.getValueSchema().isTimestampSchema()?f:l(f);a!==""&&(a+=", "),a+=l$1;}this.stringBuffer=a;return}this.stringBuffer=JSON.stringify(t,null,2);break;case "string":let s=o.getMergedTraits().mediaType,n=t;if(s&&((s==="application/json"||s.endsWith("+json"))&&(n=k$1.from(n)),o.getMergedTraits().httpHeader)){this.stringBuffer=(this.serdeContext?.base64Encoder??d)(n.toString());return}this.stringBuffer=t;break;default:o.isIdempotencyToken()?this.stringBuffer=D$1():this.stringBuffer=String(t);}}flush(){let e=this.stringBuffer;return this.stringBuffer="",e}};var Le=class{codecSerializer;stringSerializer;buffer;constructor(e,t,o=new ge(t)){this.codecSerializer=e,this.stringSerializer=o;}setSerdeContext(e){this.codecSerializer.setSerdeContext(e),this.stringSerializer.setSerdeContext(e);}write(e,t){let o=x.of(e),s=o.getMergedTraits();if(s.httpHeader||s.httpLabel||s.httpQuery){this.stringSerializer.write(o,t),this.buffer=this.stringSerializer.flush();return}return this.codecSerializer.write(o,t)}flush(){if(this.buffer!==void 0){let e=this.buffer;return this.buffer=void 0,e}return this.codecSerializer.flush()}};g();var Sr=r=>({setHttpHandler(e){r.httpHandler=e;},httpHandler(){return r.httpHandler},updateHttpClientConfig(e,t){r.httpHandler?.updateHttpClientConfig(e,t);},httpHandlerConfigs(){return r.httpHandler.httpHandlerConfigs()}}),Er=r=>({httpHandler:r.httpHandler()});g();var Q=r=>encodeURIComponent(r).replace(/[!'()*]/g,yr),yr=r=>`%${r.charCodeAt(0).toString(16).toUpperCase()}`;g();function xr(r){let e=[];for(let t of Object.keys(r).sort()){let o=r[t];if(t=Q(t),Array.isArray(o))for(let s=0,n=o.length;s<n;s++)e.push(`${t}=${Q(o[s])}`);else {let s=t;(o||typeof o=="string")&&(s+=`=${Q(o)}`),e.push(s);}}return e.join("&")}
|
|
4
|
+
export{Yt as A,or as B,le as C,nr as D,ar as E,Fe as F,fr as G,ir as H,pr as I,D as J,ue as K,Pe as L,Re as M,K as N,q as O,Me as P,Le as Q,Sr as R,Er as S,gr as T,Q as U,xr as V,ye as a,te as b,re as c,H as d,N as e,v as f,oe as g,Lt as h,M as i,Te as j,k,Ut as l,x as m,U as n,I as o,P as p,Ae as q,Ie as r,R as s,A as t,et as u,Ce as v,Oe as w,rr as x,L as y,Jt as z};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
'use strict';var chunkBUNLC3II_cjs=require('./chunk-BUNLC3II.cjs');function t(e,r,o){let n=new Error(`[unstorage] [${e}] ${r}`,o);return Error.captureStackTrace&&Error.captureStackTrace(n,t),n}function p(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}\`.`)}var c=chunkBUNLC3II_cjs.b(()=>{chunkBUNLC3II_cjs.h();});exports.a=t;exports.b=p;exports.c=c;
|