gemi 0.116.0 → 0.117.0
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/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/app/index.js +2 -2
- package/dist/app/index.js.map +1 -1
- package/dist/auth/AuthServiceProvider.d.ts.map +1 -1
- package/dist/auth/config.d.ts +27 -0
- package/dist/auth/config.d.ts.map +1 -1
- package/dist/auth/connections/ConnectionManager.d.ts +133 -0
- package/dist/auth/connections/ConnectionManager.d.ts.map +1 -0
- package/dist/auth/connections/ConnectionStore.d.ts +146 -0
- package/dist/auth/connections/ConnectionStore.d.ts.map +1 -0
- package/dist/auth/connections/ConnectionsController.d.ts +23 -0
- package/dist/auth/connections/ConnectionsController.d.ts.map +1 -0
- package/dist/auth/connections/OAuthConnectionProvider.d.ts +105 -0
- package/dist/auth/connections/OAuthConnectionProvider.d.ts.map +1 -0
- package/dist/auth/connections/errors.d.ts +32 -0
- package/dist/auth/connections/errors.d.ts.map +1 -0
- package/dist/auth/oauth/oauthState.d.ts +15 -2
- package/dist/auth/oauth/oauthState.d.ts.map +1 -1
- package/dist/auth/routes.d.ts +13 -0
- package/dist/auth/routes.d.ts.map +1 -1
- package/dist/bin/orm/emit.d.ts.map +1 -1
- package/dist/bin/orm-generator.js +51 -4
- package/dist/bin/orm-generator.js.map +4 -4
- package/dist/bun/plugin.js +2 -2
- package/dist/bun/plugin.js.map +1 -1
- package/dist/bun/preload.js +2 -2
- package/dist/bun/preload.js.map +1 -1
- package/dist/chunk-00n3gwr8.js +71 -0
- package/dist/chunk-00n3gwr8.js.map +13 -0
- package/dist/{chunk-t4yh4nf9.js → chunk-076jezzg.js} +3 -3
- package/dist/{chunk-t4yh4nf9.js.map → chunk-076jezzg.js.map} +1 -1
- package/dist/{chunk-qjhw8nje.js → chunk-077rea02.js} +1 -1
- package/dist/{chunk-6cx8ncd4.js → chunk-1ckha5dt.js} +3 -3
- package/dist/{chunk-6cx8ncd4.js.map → chunk-1ckha5dt.js.map} +1 -1
- package/dist/{chunk-mschc94q.js → chunk-1zzd39qg.js} +2 -2
- package/dist/{chunk-mschc94q.js.map → chunk-1zzd39qg.js.map} +1 -1
- package/dist/{chunk-5stgtwqw.js → chunk-2bja99cq.js} +2 -2
- package/dist/{chunk-5stgtwqw.js.map → chunk-2bja99cq.js.map} +1 -1
- package/dist/chunk-2czfefn2.js +10 -0
- package/dist/{chunk-yf1njzd5.js.map → chunk-2czfefn2.js.map} +5 -4
- package/dist/{chunk-aazmrxj9.js → chunk-37pk2cjg.js} +2 -2
- package/dist/{chunk-aazmrxj9.js.map → chunk-37pk2cjg.js.map} +1 -1
- package/dist/{chunk-qsrcdzan.js → chunk-3w4hk6q2.js} +3 -3
- package/dist/{chunk-qsrcdzan.js.map → chunk-3w4hk6q2.js.map} +1 -1
- package/dist/chunk-51w202vr.js +5 -0
- package/dist/{chunk-whtzggn6.js.map → chunk-51w202vr.js.map} +3 -4
- package/dist/{chunk-4088szy9.js → chunk-5m8vvtvn.js} +3 -3
- package/dist/{chunk-4088szy9.js.map → chunk-5m8vvtvn.js.map} +1 -1
- package/dist/{chunk-6d8rvr1v.js → chunk-5p4z1fgc.js} +2 -2
- package/dist/{chunk-6d8rvr1v.js.map → chunk-5p4z1fgc.js.map} +1 -1
- package/dist/{chunk-kejwjerj.js → chunk-5w6kyxsj.js} +2 -2
- package/dist/{chunk-kejwjerj.js.map → chunk-5w6kyxsj.js.map} +1 -1
- package/dist/{chunk-pyk3gzvc.js → chunk-62jw0vsf.js} +2 -2
- package/dist/{chunk-pyk3gzvc.js.map → chunk-62jw0vsf.js.map} +1 -1
- package/dist/chunk-63ewmmhc.js +5 -0
- package/dist/{chunk-1q9kd20m.js.map → chunk-63ewmmhc.js.map} +1 -1
- package/dist/{chunk-p1aqq0ga.js → chunk-6ggmk2eg.js} +3 -3
- package/dist/{chunk-p1aqq0ga.js.map → chunk-6ggmk2eg.js.map} +1 -1
- package/dist/{chunk-2tzm58j3.js → chunk-6y4nk9f1.js} +2 -2
- package/dist/{chunk-2tzm58j3.js.map → chunk-6y4nk9f1.js.map} +1 -1
- package/dist/{chunk-1hr4xht1.js → chunk-8gtc3s1y.js} +2 -2
- package/dist/{chunk-1hr4xht1.js.map → chunk-8gtc3s1y.js.map} +1 -1
- package/dist/{chunk-frerzsxq.js → chunk-a22h5cby.js} +2 -2
- package/dist/{chunk-frerzsxq.js.map → chunk-a22h5cby.js.map} +1 -1
- package/dist/{chunk-zyt2w03d.js → chunk-a32wfzdq.js} +2 -2
- package/dist/{chunk-zyt2w03d.js.map → chunk-a32wfzdq.js.map} +1 -1
- package/dist/{chunk-t04f3akb.js → chunk-a77586gv.js} +2 -2
- package/dist/{chunk-t04f3akb.js.map → chunk-a77586gv.js.map} +1 -1
- package/dist/chunk-a7r39713.js +5 -0
- package/dist/chunk-a7r39713.js.map +10 -0
- package/dist/{chunk-vxm6yevm.js → chunk-arwmvgrz.js} +2 -2
- package/dist/{chunk-vxm6yevm.js.map → chunk-arwmvgrz.js.map} +1 -1
- package/dist/{chunk-41da9628.js → chunk-bvqae0px.js} +1 -1
- package/dist/{chunk-d9mar37g.js → chunk-c2n6zdyd.js} +2 -2
- package/dist/{chunk-d9mar37g.js.map → chunk-c2n6zdyd.js.map} +1 -1
- package/dist/{chunk-56jky6vf.js → chunk-cytss9mb.js} +2 -2
- package/dist/{chunk-56jky6vf.js.map → chunk-cytss9mb.js.map} +1 -1
- package/dist/{chunk-vw8849ys.js → chunk-dcgvq79a.js} +2 -2
- package/dist/{chunk-m54s6jpr.js.map → chunk-dcgvq79a.js.map} +1 -1
- package/dist/{chunk-6chz1ktz.js → chunk-de4t48j9.js} +3 -3
- package/dist/{chunk-6chz1ktz.js.map → chunk-de4t48j9.js.map} +1 -1
- package/dist/{chunk-cbqazg9k.js → chunk-dz99g58c.js} +2 -2
- package/dist/{chunk-cbqazg9k.js.map → chunk-dz99g58c.js.map} +1 -1
- package/dist/{chunk-e573yxpq.js → chunk-e7ezmag9.js} +3 -3
- package/dist/{chunk-e573yxpq.js.map → chunk-e7ezmag9.js.map} +1 -1
- package/dist/{chunk-yer1r3t3.js → chunk-epvpmakp.js} +2 -2
- package/dist/{chunk-yer1r3t3.js.map → chunk-epvpmakp.js.map} +1 -1
- package/dist/{chunk-yhrye9cm.js → chunk-f8vcwzgd.js} +2 -2
- package/dist/{chunk-yhrye9cm.js.map → chunk-f8vcwzgd.js.map} +1 -1
- package/dist/chunk-fa37qzm3.js +5 -0
- package/dist/chunk-fa37qzm3.js.map +12 -0
- package/dist/{chunk-fxgxf16k.js → chunk-ffgmqwzy.js} +2 -2
- package/dist/{chunk-fxgxf16k.js.map → chunk-ffgmqwzy.js.map} +1 -1
- package/dist/{chunk-er3wf6ng.js → chunk-fk6nxhxn.js} +2 -2
- package/dist/{chunk-er3wf6ng.js.map → chunk-fk6nxhxn.js.map} +1 -1
- package/dist/{chunk-3hrj5rwm.js → chunk-fnwbbmnk.js} +2 -2
- package/dist/{chunk-3hrj5rwm.js.map → chunk-fnwbbmnk.js.map} +1 -1
- package/dist/chunk-g2wncay4.js +9 -0
- package/dist/{chunk-hytt9qyj.js.map → chunk-g2wncay4.js.map} +3 -4
- package/dist/{chunk-gts5p6mw.js → chunk-ge9xjwgq.js} +4 -4
- package/dist/{chunk-gts5p6mw.js.map → chunk-ge9xjwgq.js.map} +1 -1
- package/dist/{chunk-tw5kwbx4.js → chunk-gjy2qjcr.js} +2 -2
- package/dist/{chunk-tw5kwbx4.js.map → chunk-gjy2qjcr.js.map} +1 -1
- package/dist/{chunk-15c2vgaf.js → chunk-gn7kne7r.js} +2 -2
- package/dist/{chunk-15c2vgaf.js.map → chunk-gn7kne7r.js.map} +1 -1
- package/dist/{chunk-9n1hx3mq.js → chunk-hr61ekcr.js} +3 -3
- package/dist/{chunk-9n1hx3mq.js.map → chunk-hr61ekcr.js.map} +1 -1
- package/dist/{chunk-m54s6jpr.js → chunk-hvgmqt6z.js} +2 -2
- package/dist/{chunk-vw8849ys.js.map → chunk-hvgmqt6z.js.map} +1 -1
- package/dist/{chunk-aeh67ynz.js → chunk-hvpn18bb.js} +3 -3
- package/dist/{chunk-aeh67ynz.js.map → chunk-hvpn18bb.js.map} +1 -1
- package/dist/{chunk-jdhdrr2k.js → chunk-j1453bn1.js} +2 -2
- package/dist/{chunk-jdhdrr2k.js.map → chunk-j1453bn1.js.map} +1 -1
- package/dist/{chunk-tn2bryy2.js → chunk-jpetnpzn.js} +2 -2
- package/dist/{chunk-tn2bryy2.js.map → chunk-jpetnpzn.js.map} +1 -1
- package/dist/{chunk-v1tfdgy1.js → chunk-jqrs16g2.js} +3 -3
- package/dist/{chunk-v1tfdgy1.js.map → chunk-jqrs16g2.js.map} +1 -1
- package/dist/{chunk-4mfrgd5m.js → chunk-kk77x2v4.js} +2 -2
- package/dist/{chunk-4mfrgd5m.js.map → chunk-kk77x2v4.js.map} +1 -1
- package/dist/chunk-kpn7f58a.js +14 -0
- package/dist/{chunk-pn8v6fj2.js.map → chunk-kpn7f58a.js.map} +11 -6
- package/dist/chunk-mhteg4yz.js +57 -0
- package/dist/{chunk-ms9k0rx6.js.map → chunk-mhteg4yz.js.map} +15 -11
- package/dist/{chunk-n672d4g8.js → chunk-n9jyjp4a.js} +2 -2
- package/dist/{chunk-n672d4g8.js.map → chunk-n9jyjp4a.js.map} +1 -1
- package/dist/{chunk-vbdty91k.js → chunk-nb2gggba.js} +3 -3
- package/dist/{chunk-vbdty91k.js.map → chunk-nb2gggba.js.map} +1 -1
- package/dist/chunk-ntxsdchf.js +50 -0
- package/dist/chunk-ntxsdchf.js.map +10 -0
- package/dist/{chunk-2z1981d0.js → chunk-pepzecrm.js} +2 -2
- package/dist/{chunk-2z1981d0.js.map → chunk-pepzecrm.js.map} +1 -1
- package/dist/{chunk-785b41h1.js → chunk-pgy3mfxw.js} +3 -3
- package/dist/{chunk-785b41h1.js.map → chunk-pgy3mfxw.js.map} +1 -1
- package/dist/{chunk-98m15b9x.js → chunk-qhw0hej0.js} +2 -2
- package/dist/{chunk-98m15b9x.js.map → chunk-qhw0hej0.js.map} +1 -1
- package/dist/{chunk-303mprnv.js → chunk-r3v2cnrj.js} +2 -2
- package/dist/{chunk-303mprnv.js.map → chunk-r3v2cnrj.js.map} +1 -1
- package/dist/{chunk-ktr3k768.js → chunk-rhmpphhc.js} +3 -3
- package/dist/{chunk-ktr3k768.js.map → chunk-rhmpphhc.js.map} +1 -1
- package/dist/{chunk-fre6f4nk.js → chunk-s4f56035.js} +2 -2
- package/dist/{chunk-fre6f4nk.js.map → chunk-s4f56035.js.map} +1 -1
- package/dist/{chunk-sr942vb1.js → chunk-sj4f7x4p.js} +2 -2
- package/dist/{chunk-sr942vb1.js.map → chunk-sj4f7x4p.js.map} +1 -1
- package/dist/{chunk-wyw6p3fg.js → chunk-sksmnjkn.js} +3 -3
- package/dist/{chunk-wyw6p3fg.js.map → chunk-sksmnjkn.js.map} +1 -1
- package/dist/{chunk-kqxdsv22.js → chunk-stnd9qht.js} +2 -2
- package/dist/{chunk-kqxdsv22.js.map → chunk-stnd9qht.js.map} +1 -1
- package/dist/{chunk-1myhm0g3.js → chunk-t65074mw.js} +3 -3
- package/dist/{chunk-1myhm0g3.js.map → chunk-t65074mw.js.map} +1 -1
- package/dist/chunk-t87w4h84.js +24 -0
- package/dist/{chunk-79xg42e7.js.map → chunk-t87w4h84.js.map} +2 -2
- package/dist/{chunk-z10cas5r.js → chunk-thz75w6e.js} +2 -2
- package/dist/{chunk-z10cas5r.js.map → chunk-thz75w6e.js.map} +1 -1
- package/dist/{chunk-xt9tv99x.js → chunk-v8vnxkvp.js} +2 -2
- package/dist/{chunk-xt9tv99x.js.map → chunk-v8vnxkvp.js.map} +1 -1
- package/dist/{chunk-x7cpth2f.js → chunk-veq07rp8.js} +1 -1
- package/dist/{chunk-agyfv3f8.js → chunk-vj5necm0.js} +1 -1
- package/dist/{chunk-p91b8zcn.js → chunk-vtc23xpk.js} +2 -2
- package/dist/{chunk-p91b8zcn.js.map → chunk-vtc23xpk.js.map} +1 -1
- package/dist/{chunk-jmpw6bqz.js → chunk-w4e480he.js} +2 -2
- package/dist/{chunk-jmpw6bqz.js.map → chunk-w4e480he.js.map} +1 -1
- package/dist/{chunk-8rv62v14.js → chunk-wgb79ysr.js} +2 -2
- package/dist/{chunk-8rv62v14.js.map → chunk-wgb79ysr.js.map} +1 -1
- package/dist/{chunk-1vzks22y.js → chunk-wk1tp1f1.js} +2 -2
- package/dist/{chunk-1vzks22y.js.map → chunk-wk1tp1f1.js.map} +1 -1
- package/dist/{chunk-bra1a1fq.js → chunk-wwdbgshx.js} +2 -2
- package/dist/{chunk-bra1a1fq.js.map → chunk-wwdbgshx.js.map} +1 -1
- package/dist/{chunk-eqse2m6n.js → chunk-wzzrz612.js} +2 -2
- package/dist/{chunk-eqse2m6n.js.map → chunk-wzzrz612.js.map} +1 -1
- package/dist/{chunk-hdps9n52.js → chunk-x7qwx07b.js} +3 -3
- package/dist/{chunk-hdps9n52.js.map → chunk-x7qwx07b.js.map} +1 -1
- package/dist/chunk-x84as3vy.js +5 -0
- package/dist/chunk-x84as3vy.js.map +12 -0
- package/dist/chunk-y0en07zh.js +302 -0
- package/dist/chunk-y0en07zh.js.map +17 -0
- package/dist/{chunk-d2gfcf85.js → chunk-yfwrbfnw.js} +2 -2
- package/dist/{chunk-d2gfcf85.js.map → chunk-yfwrbfnw.js.map} +1 -1
- package/dist/{chunk-mazznq15.js → chunk-yhp6bvhj.js} +3 -3
- package/dist/{chunk-mazznq15.js.map → chunk-yhp6bvhj.js.map} +1 -1
- package/dist/{chunk-tzm3c7n6.js → chunk-yvtmygrk.js} +4 -4
- package/dist/{chunk-tzm3c7n6.js.map → chunk-yvtmygrk.js.map} +1 -1
- package/dist/{chunk-mqfzdfnz.js → chunk-zkjs3m5m.js} +2 -2
- package/dist/{chunk-mqfzdfnz.js.map → chunk-zkjs3m5m.js.map} +1 -1
- package/dist/chunk-zw6843j3.js +5 -0
- package/dist/chunk-zw6843j3.js.map +12 -0
- package/dist/client/Head.d.ts.map +1 -1
- package/dist/client/fonts.d.ts +69 -0
- package/dist/client/fonts.d.ts.map +1 -0
- package/dist/client/index.d.ts +1 -0
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +75 -1
- package/dist/client/index.js.map +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/builtins.d.ts +13 -0
- package/dist/console/builtins.d.ts.map +1 -0
- package/dist/console/run.js +13 -11
- package/dist/console/run.js.map +6 -5
- package/dist/console/runner.d.ts.map +1 -1
- package/dist/console/usage.d.ts +2 -0
- package/dist/console/usage.d.ts.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/Connections.d.ts +36 -0
- package/dist/facades/Connections.d.ts.map +1 -0
- package/dist/facades/Crypt.d.ts +26 -0
- package/dist/facades/Crypt.d.ts.map +1 -0
- package/dist/facades/Meta.d.ts +7 -1
- package/dist/facades/Meta.d.ts.map +1 -1
- package/dist/facades/Storage.d.ts +29 -0
- package/dist/facades/Storage.d.ts.map +1 -1
- package/dist/facades/index.d.ts +2 -0
- package/dist/facades/index.d.ts.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/HttpRequest.d.ts +1 -0
- package/dist/http/HttpRequest.d.ts.map +1 -1
- package/dist/http/Metadata.d.ts +5 -0
- package/dist/http/Metadata.d.ts.map +1 -1
- package/dist/http/index.d.ts +3 -1
- package/dist/http/index.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/http/requestContext.d.ts +1 -0
- package/dist/http/requestContext.d.ts.map +1 -1
- package/dist/http/safeFetch/errors.d.ts +10 -0
- package/dist/http/safeFetch/errors.d.ts.map +1 -1
- package/dist/http/safeFetch/index.d.ts +1 -1
- package/dist/http/safeFetch/index.d.ts.map +1 -1
- package/dist/http/sitemap/Robots.d.ts +95 -0
- package/dist/http/sitemap/Robots.d.ts.map +1 -0
- package/dist/http/sitemap/Sitemap.d.ts +145 -0
- package/dist/http/sitemap/Sitemap.d.ts.map +1 -0
- package/dist/http/sitemap/fetchText.d.ts +16 -0
- package/dist/http/sitemap/fetchText.d.ts.map +1 -0
- package/dist/http/sitemap/index.d.ts +3 -0
- package/dist/http/sitemap/index.d.ts.map +1 -0
- package/dist/http/sitemap/xml.d.ts +21 -0
- package/dist/http/sitemap/xml.d.ts.map +1 -0
- package/dist/i18n/Translator.d.ts.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.d.ts +1 -1
- package/dist/i18n/index.d.ts.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +2 -2
- package/dist/i18n/resolveLocale.d.ts +18 -0
- package/dist/i18n/resolveLocale.d.ts.map +1 -1
- package/dist/kernel/index.js +3 -3
- package/dist/kernel/index.js.map +3 -3
- package/dist/kernel/providers.d.ts +2 -2
- package/dist/kernel/providers.d.ts.map +1 -1
- package/dist/orm/Model.d.ts.map +1 -1
- package/dist/orm/encryption-rotate.d.ts +44 -0
- package/dist/orm/encryption-rotate.d.ts.map +1 -0
- package/dist/orm/encryption.d.ts +54 -0
- package/dist/orm/encryption.d.ts.map +1 -0
- package/dist/orm/index.d.ts +2 -0
- package/dist/orm/index.d.ts.map +1 -1
- package/dist/orm/index.js +3 -3
- package/dist/orm/index.js.map +4 -4
- package/dist/orm/schema.d.ts +25 -1
- package/dist/orm/schema.d.ts.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/encryption/Encrypter.d.ts +86 -0
- package/dist/services/encryption/Encrypter.d.ts.map +1 -0
- package/dist/services/encryption/EncryptionServiceProvider.d.ts +13 -0
- package/dist/services/encryption/EncryptionServiceProvider.d.ts.map +1 -0
- package/dist/services/encryption/config.d.ts +36 -0
- package/dist/services/encryption/config.d.ts.map +1 -0
- package/dist/services/file-storage/drivers/FileStorageDriver.d.ts +12 -1
- package/dist/services/file-storage/drivers/FileStorageDriver.d.ts.map +1 -1
- package/dist/services/file-storage/drivers/FileSystemDriver.d.ts +8 -1
- package/dist/services/file-storage/drivers/FileSystemDriver.d.ts.map +1 -1
- package/dist/services/file-storage/drivers/types.d.ts +17 -0
- package/dist/services/file-storage/drivers/types.d.ts.map +1 -1
- package/dist/services/file-storage/putFromUrl.d.ts +56 -0
- package/dist/services/file-storage/putFromUrl.d.ts.map +1 -0
- package/dist/services/file-storage/sniffContentType.d.ts +33 -0
- package/dist/services/file-storage/sniffContentType.d.ts.map +1 -0
- package/dist/services/index.d.ts +18 -4
- package/dist/services/index.d.ts.map +1 -1
- package/dist/services/index.js +10 -10
- package/dist/services/index.js.map +4 -3
- package/dist/services/queue/DatabaseQueueDriver.d.ts +96 -7
- package/dist/services/queue/DatabaseQueueDriver.d.ts.map +1 -1
- package/dist/services/queue/Job.d.ts +72 -0
- package/dist/services/queue/Job.d.ts.map +1 -1
- package/dist/services/queue/MemoryQueueDriver.d.ts +22 -2
- package/dist/services/queue/MemoryQueueDriver.d.ts.map +1 -1
- package/dist/services/queue/QueueDriver.d.ts +74 -1
- package/dist/services/queue/QueueDriver.d.ts.map +1 -1
- package/dist/services/queue/QueueManager.d.ts +47 -0
- package/dist/services/queue/QueueManager.d.ts.map +1 -1
- package/dist/services/queue/batch.d.ts +112 -0
- package/dist/services/queue/batch.d.ts.map +1 -0
- package/dist/services/queue/queueDriverContract.d.ts +5 -0
- package/dist/services/queue/queueDriverContract.d.ts.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/services/router/ViewRouteDispatcher.d.ts.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +2 -2
- package/dist/vitest/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-1q9kd20m.js +0 -5
- package/dist/chunk-49nyyjfe.js +0 -5
- package/dist/chunk-49nyyjfe.js.map +0 -11
- package/dist/chunk-79xg42e7.js +0 -24
- package/dist/chunk-7vb4eey2.js +0 -217
- package/dist/chunk-7vb4eey2.js.map +0 -16
- package/dist/chunk-hytt9qyj.js +0 -54
- package/dist/chunk-jmg2zsaf.js +0 -5
- package/dist/chunk-jmg2zsaf.js.map +0 -12
- package/dist/chunk-ms9k0rx6.js +0 -46
- package/dist/chunk-pn8v6fj2.js +0 -14
- package/dist/chunk-whtzggn6.js +0 -5
- package/dist/chunk-yf1njzd5.js +0 -10
- /package/dist/{chunk-qjhw8nje.js.map → chunk-077rea02.js.map} +0 -0
- /package/dist/{chunk-41da9628.js.map → chunk-bvqae0px.js.map} +0 -0
- /package/dist/{chunk-x7cpth2f.js.map → chunk-veq07rp8.js.map} +0 -0
- /package/dist/{chunk-agyfv3f8.js.map → chunk-vj5necm0.js.map} +0 -0
package/dist/services/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{gb as Z8}from"../chunk-z10cas5r.js";import{Ab as E5,Bb as m5,Cb as k,Db as c5,Eb as u5,Fb as p5,Gb as d5,Hb as l5,Ib as n5,Jb as i5,Kb as o5,Lb as s5,Mb as a5,Nb as t5,Ob as r5,Pb as e5,Qb as W8,Rb as J8,hb as W5,ib as J5,jb as Z5,kb as $5,lb as z4,mb as Y5,nb as Y4,ob as Q4,pb as I1,qb as Q5,rb as K5,sb as v5,ub as P5,vb as w5,wb as y5,xb as A5,yb as h5,zb as g5}from"../chunk-yf1njzd5.js";import"../chunk-4088szy9.js";import{ic as L5,jc as D5,kc as F5,lc as H5,mc as U5,nc as O5,oc as R5,pc as f5,qc as _5,rc as k5,sc as C5,tc as I5,uc as b5,vc as T5}from"../chunk-ktr3k768.js";import{wc as S5}from"../chunk-2z1981d0.js";import{Ac as B5,Bc as M5,Cc as j5,Dc as N5,Ec as x5,xc as G5,yc as z5,zc as X5}from"../chunk-7vb4eey2.js";import{Jc as V5,Kc as q5}from"../chunk-v1tfdgy1.js";import"../chunk-n672d4g8.js";import{$c as r6,Ae as b1,Cd as LW,Dd as DW,Ed as FW,Fd as HW,Gd as UW,Hd as SW,Id as OW,Jd as RW,Kd as fW,Md as _W,Nd as kW,Od as CW,Pd as IW,Qd as bW,Rd as TW,Sd as vW,Td as x0,Ud as PW,Vd as wW,Wd as VW,Xd as qW,Yd as yW,ad as e6,ae as q,bd as WW,be as j1,cd as JW,ce as AW,dd as ZW,de as hW,ed as $W,ee as gW,fe as EW,ge as mW,hd as y0,id as S0,ie as cW,jd as O0,je as uW,kd as t1,ke as pW,ld as YW,le as dW,me as lW,od as QW,pd as GW,pe as nW,sd as A0,ue as iW,ye as oW}from"../chunk-ms9k0rx6.js";import"../chunk-whtzggn6.js";import"../chunk-hytt9qyj.js";import{Ag as o1,Bg as z1,Cg as f1,Dg as KW,Eg as zW,Fg as XW,Gg as BW,Ig as MW,Kg as _1,dg as a1,eg as i1,fg as K1,rg as $4,ug as i,wg as c}from"../chunk-pn8v6fj2.js";import"../chunk-15c2vgaf.js";import"../chunk-49nyyjfe.js";import{Xg as jW,Yg as NW,Zg as xW}from"../chunk-tn2bryy2.js";import"../chunk-cbqazg9k.js";import"../chunk-1myhm0g3.js";import"../chunk-kejwjerj.js";import"../chunk-aazmrxj9.js";import{Ph as sW,Qh as aW,Rh as tW,Sh as rW,Uh as eW}from"../chunk-qsrcdzan.js";import"../chunk-jmg2zsaf.js";import{bi as v}from"../chunk-t4yh4nf9.js";import"../chunk-1vzks22y.js";import"../chunk-zyt2w03d.js";import"../chunk-1hr4xht1.js";import"../chunk-d9mar37g.js";import{ui as D0}from"../chunk-vw8849ys.js";import{Buffer as L0}from"buffer";class F0 extends z1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-tzm3c7n6.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:J}={}){J?.throwIfAborted();let Z,$,Y,Q=process.env.BUCKET_NAME;if(W instanceof Blob)Z=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,$=W.type;else Z=W.body,Y=W.name,Q=W.bucket??Q,$=W.contentType||(Z instanceof Blob||Z instanceof File?Z.type:void 0);$=$||void 0;let G=Z instanceof L0?Z:Z instanceof Blob||Z instanceof File?L0.from(await Z.arrayBuffer()):"",{sdk:K,client:z}=await this.connect();return J?.throwIfAborted(),await z.send(new K.PutObjectCommand({Bucket:Q,Key:Y,Body:G,ContentType:$}),{abortSignal:J}),Y}async delete(W){let J=typeof W==="string"?W:W.name,Z=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!J)throw Error("Object name has to be specified");let{sdk:$,client:Y}=await this.connect();try{await Y.send(new $.DeleteObjectCommand({Bucket:Z,Key:J}))}catch(Q){if(Q?.name==="NoSuchKey"||Q?.$metadata?.httpStatusCode===404)return;throw Q}}async*pages(W,{bucket:J,signal:Z}){let{sdk:$,client:Y}=await this.connect(),Q;do{Z?.throwIfAborted();let G=await Y.send(new $.ListObjectsV2Command({Bucket:J??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:Q}),{abortSignal:Z});yield(G.Contents??[]).map((K)=>({name:K.Key,size:K.Size??0,lastModified:K.LastModified??new Date(0)})),Q=G.IsTruncated?G.NextContinuationToken:void 0}while(Q)}async*objects(W,J={}){for await(let Z of this.pages(W,J))yield*Z}async deletePrefix(W,J={}){o1(W);let Z=J.bucket??process.env.BUCKET_NAME,{sdk:$,client:Y}=await this.connect(),Q=0;for await(let G of this.pages(W,{...J,bucket:Z})){if(G.length===0)continue;J.signal?.throwIfAborted();let z=(await Y.send(new $.DeleteObjectsCommand({Bucket:Z,Delete:{Objects:G.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:J.signal}))?.Errors??[];if(z.length>0){let X=z[0];throw Error(`S3 could not delete ${z.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}Q+=G.length}return Q}async list(W){let{sdk:J,client:Z}=await this.connect();return await Z.send(new J.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:J}={}){J?.throwIfAborted();let Z=process.env.BUCKET_NAME,$;if(typeof W==="string")$=W;else Z=W.bucket??Z,$=W.name;if(!$)throw Error("Object name has to be specified");let{sdk:Y,client:Q}=await this.connect();J?.throwIfAborted();let G=await Q.send(new Y.GetObjectCommand({Bucket:Z,Key:$}),{abortSignal:J}),K=f1(G.Body.transformToWebStream(),J);return J?.throwIfAborted(),new Response(K,{headers:{"Content-Type":G.ContentType,"Content-Length":G.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":G.LastModified?.toUTCString()||"",ETag:G.ETag||""}})}async read(W){let J=typeof W==="string"?{name:W}:W,Z=J.bucket??process.env.BUCKET_NAME,{name:$,range:Y=null}=J;if(!$)throw Error("Object name has to be specified");let{sdk:Q,client:G}=await this.connect(),K;try{K=await G.send(new Q.GetObjectCommand({Bucket:Z,Key:$,Range:Y?i1(Y):void 0}))}catch(M){if(M?.name==="InvalidRange"||M?.$metadata?.httpStatusCode===416)throw new i(await this.size({name:$,bucket:Z}));if(M?.name==="NoSuchKey"||M?.$metadata?.httpStatusCode===404)throw new c($);throw M}let z=K1(K.ContentRange),X=Boolean(z)&&K.$metadata?.httpStatusCode===206,B=z?.total??K.ContentLength??0;return{body:K.Body.transformToWebStream(),start:z?.start??0,end:z?.end??B-1,total:B,partial:X,type:K.ContentType??"application/octet-stream",etag:K.ETag||void 0,lastModified:K.LastModified,name:$}}async size(W){let J=typeof W==="string"?W:W.name,Z=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:$,client:Y}=await this.connect();try{return(await Y.send(new $.HeadObjectCommand({Bucket:Z,Key:J}))).ContentLength??0}catch(Q){if(Q?.name==="NotFound"||Q?.$metadata?.httpStatusCode===404)throw new c(J);throw Q}}}import{Buffer as H0}from"buffer";import{Readable as H6}from"stream";function s1(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function U6(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class U0 extends z1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let J=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(J)return W.BlobServiceClient.fromConnectionString(J);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,J){if(!W)throw Error("Object name has to be specified");let Z=J??this.config.container??process.env.BUCKET_NAME;if(!Z)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient(Z).getBlockBlobClient(W)}async put(W,{signal:J}={}){J?.throwIfAborted();let Z,$,Y,Q;if(W instanceof Blob)Z=W,Y=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,$=W.type;else Z=W.body,Y=W.name,Q=W.bucket,$=W.contentType??(Z instanceof Blob||Z instanceof File?Z.type:void 0);let G=Z instanceof H0?Z:H0.from(await Z.arrayBuffer()),K=await this.blob(Y,Q);return J?.throwIfAborted(),await K.uploadData(G,{blobHTTPHeaders:$?{blobContentType:$}:void 0,abortSignal:J}),Y}async*objects(W,{bucket:J,signal:Z}={}){Z?.throwIfAborted();let $=J??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let Q=(await this.serviceClient()).getContainerClient($);for await(let G of Q.listBlobsFlat({prefix:W}))Z?.throwIfAborted(),yield{name:G.name,size:G.properties?.contentLength??0,lastModified:G.properties?.lastModified??new Date(0)}}async list(W){let J=this.config.container??process.env.BUCKET_NAME,$=(await this.serviceClient()).getContainerClient(J),Y=[];for await(let Q of $.listBlobsFlat({prefix:W}))Y.push(Q.name);return Y}async fetch(W,{signal:J}={}){J?.throwIfAborted();let Z=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},J);return new Response(Z.body,{headers:{"Content-Type":Z.type,"Content-Length":String(Z.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":Z.lastModified?.toUTCString()??"",ETag:Z.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,J){let{name:Z,bucket:$,range:Y=null}=W,Q=await this.blob(Z,$);J?.throwIfAborted();let G,K,z=Y?.kind==="suffix"||Y?.kind==="offset"&&Y.end===null&&Y.start===0;if(Y&&z){let H=await this.size({name:Z,bucket:$}),m=a1(Y,H);if(!m)throw new i(H);G=m.start,K=m.length}else if(Y?.kind==="offset")G=Y.start,K=Y.end===null?void 0:Y.end-Y.start+1;let X;try{X=await Q.download(G,K,J?{abortSignal:J}:void 0)}catch(H){if(U6(H))throw new i(await this.size({name:Z,bucket:$}));if(s1(H))throw new c(Z);throw H}let B=K1(X.contentRange),M=Boolean(B),D=B?.total??X.contentLength??0,S=await S6(X);if(S instanceof ReadableStream)S=f1(S,J);return J?.throwIfAborted(),{body:S,start:B?.start??0,end:B?.end??D-1,total:D,partial:M,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:Z}}async size(W){let J=typeof W==="string"?W:W.name,Z=typeof W==="string"?void 0:W.bucket,$=await this.blob(J,Z);try{return(await $.getProperties()).contentLength??0}catch(Y){if(s1(Y))throw new c(J);throw Y}}async delete(W){let J=typeof W==="string"?W:W.name,Z=typeof W==="string"?void 0:W.bucket,$=await this.blob(J,Z);try{await $.delete()}catch(Y){if(s1(Y))return;throw Y}}}async function S6(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return H6.toWeb(W.readableStreamBody);return null}var O6=`
|
|
2
|
+
import{hb as D8}from"../chunk-thz75w6e.js";import{Ab as t5,Bb as r5,Cb as e5,Db as W8,Eb as k,Fb as J8,Gb as Z8,Hb as $8,Ib as Q8,Jb as Y8,Kb as G8,Lb as K8,Mb as z8,Nb as X8,Ob as B8,Pb as M8,Qb as j8,Rb as N8,Sb as x8,Tb as L8,ib as N5,jb as x5,kb as L5,lb as D5,mb as z4,nb as F5,ob as Q4,pb as Y4,qb as I1,rb as H5,sb as S5,tb as d5,vb as p5,wb as l5,xb as o5,yb as s5,zb as a5}from"../chunk-2czfefn2.js";import"../chunk-5m8vvtvn.js";import{kc as b5,lc as T5,mc as v5,nc as P5,oc as w5,pc as q5,qc as y5,rc as A5,sc as h5,tc as g5,uc as E5,vc as m5,wc as c5,xc as u5}from"../chunk-rhmpphhc.js";import{yc as V5}from"../chunk-pepzecrm.js";import{Ac as O5,Bc as R5,Cc as f5,Dc as _5,Ec as k5,Fc as C5,Gc as I5,zc as U5}from"../chunk-y0en07zh.js";import{Lc as n5,Mc as i5}from"../chunk-jqrs16g2.js";import"../chunk-n9jyjp4a.js";import{$d as iW,Ce as K5,Ee as b1,Gd as bW,Hd as TW,Id as vW,Jd as PW,Kd as wW,Ld as VW,Md as qW,Nd as yW,Od as AW,Qd as hW,Rd as gW,Sd as EW,Td as mW,Ud as cW,Vd as uW,Wd as dW,Xd as x0,Yd as pW,Zd as lW,_d as nW,ae as oW,bd as e6,cd as WW,dd as JW,ed as ZW,ee as q,fd as $W,fe as j1,gd as QW,ge as sW,he as aW,ie as tW,jd as y0,je as rW,kd as S0,ke as eW,ld as O0,md as t1,me as W5,nd as YW,ne as J5,oe as Z5,pe as $5,qd as GW,qe as Q5,rd as KW,te as Y5,ud as A0,ye as G5}from"../chunk-mhteg4yz.js";import"../chunk-51w202vr.js";import"../chunk-g2wncay4.js";import{Kf as $4,Nf as i,Pf as c,Tf as o1,Uf as z1,Vf as f1,Wf as zW,Xf as XW,Yf as BW,Zf as MW,mg as jW,ng as NW,pg as xW,rg as _1,wf as a1,xf as i1,yf as K1}from"../chunk-kpn7f58a.js";import"../chunk-gn7kne7r.js";import"../chunk-x84as3vy.js";import{Eg as OW,Fg as RW,Gg as fW,Hg as _W,Ig as kW,Jg as CW,Kg as IW}from"../chunk-00n3gwr8.js";import{Qg as HW,Rg as UW,Sg as SW}from"../chunk-fa37qzm3.js";import"../chunk-ntxsdchf.js";import{Ah as DW,Bh as FW,zh as LW}from"../chunk-jpetnpzn.js";import"../chunk-dz99g58c.js";import"../chunk-t65074mw.js";import"../chunk-5w6kyxsj.js";import"../chunk-37pk2cjg.js";import{ri as z5,si as X5,ti as B5,ui as M5,wi as j5}from"../chunk-3w4hk6q2.js";import"../chunk-zw6843j3.js";import{Gi as v}from"../chunk-076jezzg.js";import"../chunk-wk1tp1f1.js";import"../chunk-a32wfzdq.js";import"../chunk-8gtc3s1y.js";import"../chunk-c2n6zdyd.js";import{Zi as D0}from"../chunk-dcgvq79a.js";import{Buffer as L0}from"buffer";class F0 extends z1{client;config;constructor(...W){super();this.config=W}async connect(){let W=await import("../chunk-yvtmygrk.js");return this.client??=new W.S3Client(...this.config),{sdk:W,client:this.client}}async put(W,{signal:J}={}){J?.throwIfAborted();let Z,$,Q,Y=process.env.BUCKET_NAME;if(W instanceof Blob)Z=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,$=W.type;else Z=W.body,Q=W.name,Y=W.bucket??Y,$=W.contentType||(Z instanceof Blob||Z instanceof File?Z.type:void 0);$=$||void 0;let G=Z instanceof L0?Z:Z instanceof Blob||Z instanceof File?L0.from(await Z.arrayBuffer()):"",{sdk:K,client:z}=await this.connect();return J?.throwIfAborted(),await z.send(new K.PutObjectCommand({Bucket:Y,Key:Q,Body:G,ContentType:$}),{abortSignal:J}),Q}async delete(W){let J=typeof W==="string"?W:W.name,Z=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME;if(!J)throw Error("Object name has to be specified");let{sdk:$,client:Q}=await this.connect();try{await Q.send(new $.DeleteObjectCommand({Bucket:Z,Key:J}))}catch(Y){if(Y?.name==="NoSuchKey"||Y?.$metadata?.httpStatusCode===404)return;throw Y}}async*pages(W,{bucket:J,signal:Z}){let{sdk:$,client:Q}=await this.connect(),Y;do{Z?.throwIfAborted();let G=await Q.send(new $.ListObjectsV2Command({Bucket:J??process.env.BUCKET_NAME,Prefix:W,ContinuationToken:Y}),{abortSignal:Z});yield(G.Contents??[]).map((K)=>({name:K.Key,size:K.Size??0,lastModified:K.LastModified??new Date(0)})),Y=G.IsTruncated?G.NextContinuationToken:void 0}while(Y)}async*objects(W,J={}){for await(let Z of this.pages(W,J))yield*Z}async deletePrefix(W,J={}){o1(W);let Z=J.bucket??process.env.BUCKET_NAME,{sdk:$,client:Q}=await this.connect(),Y=0;for await(let G of this.pages(W,{...J,bucket:Z})){if(G.length===0)continue;J.signal?.throwIfAborted();let z=(await Q.send(new $.DeleteObjectsCommand({Bucket:Z,Delete:{Objects:G.map((X)=>({Key:X.name})),Quiet:!0}}),{abortSignal:J.signal}))?.Errors??[];if(z.length>0){let X=z[0];throw Error(`S3 could not delete ${z.length} object(s) under "${W}", e.g. "${X.Key}": ${X.Code??"unknown"} ${X.Message??""}`.trim())}Y+=G.length}return Y}async list(W){let{sdk:J,client:Z}=await this.connect();return await Z.send(new J.ListObjectsV2Command({Bucket:process.env.BUCKET_NAME,Prefix:W}))}async fetch(W,{signal:J}={}){J?.throwIfAborted();let Z=process.env.BUCKET_NAME,$;if(typeof W==="string")$=W;else Z=W.bucket??Z,$=W.name;if(!$)throw Error("Object name has to be specified");let{sdk:Q,client:Y}=await this.connect();J?.throwIfAborted();let G=await Y.send(new Q.GetObjectCommand({Bucket:Z,Key:$}),{abortSignal:J}),K=f1(G.Body.transformToWebStream(),J);return J?.throwIfAborted(),new Response(K,{headers:{"Content-Type":G.ContentType,"Content-Length":G.ContentLength.toString(),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":G.LastModified?.toUTCString()||"",ETag:G.ETag||""}})}async read(W){let J=typeof W==="string"?{name:W}:W,Z=J.bucket??process.env.BUCKET_NAME,{name:$,range:Q=null}=J;if(!$)throw Error("Object name has to be specified");let{sdk:Y,client:G}=await this.connect(),K;try{K=await G.send(new Y.GetObjectCommand({Bucket:Z,Key:$,Range:Q?i1(Q):void 0}))}catch(M){if(M?.name==="InvalidRange"||M?.$metadata?.httpStatusCode===416)throw new i(await this.size({name:$,bucket:Z}));if(M?.name==="NoSuchKey"||M?.$metadata?.httpStatusCode===404)throw new c($);throw M}let z=K1(K.ContentRange),X=Boolean(z)&&K.$metadata?.httpStatusCode===206,B=z?.total??K.ContentLength??0;return{body:K.Body.transformToWebStream(),start:z?.start??0,end:z?.end??B-1,total:B,partial:X,type:K.ContentType??"application/octet-stream",etag:K.ETag||void 0,lastModified:K.LastModified,name:$}}async size(W){let J=typeof W==="string"?W:W.name,Z=(typeof W==="string"?void 0:W.bucket)??process.env.BUCKET_NAME,{sdk:$,client:Q}=await this.connect();try{return(await Q.send(new $.HeadObjectCommand({Bucket:Z,Key:J}))).ContentLength??0}catch(Y){if(Y?.name==="NotFound"||Y?.$metadata?.httpStatusCode===404)throw new c(J);throw Y}}}import{Buffer as H0}from"buffer";import{Readable as H6}from"stream";function s1(W){return W?.statusCode===404||W?.details?.errorCode==="BlobNotFound"||W?.code==="BlobNotFound"}function U6(W){return W?.statusCode===416||W?.details?.errorCode==="InvalidRange"||W?.code==="InvalidRange"}class U0 extends z1{config;serviceClientPromise=null;constructor(W={}){super();this.config=W}async serviceClient(){if(this.config.serviceClient)return this.config.serviceClient;return this.serviceClientPromise??=(async()=>{let W;try{W=await import("@azure/storage-blob")}catch{throw Error("AzureBlobDriver requires the '@azure/storage-blob' package. Install it with `bun add @azure/storage-blob`, or pass a pre-built `serviceClient`.")}let J=this.config.connectionString??process.env.AZURE_STORAGE_CONNECTION_STRING;if(this.config.url)return new W.BlobServiceClient(this.config.url,this.config.credential);if(J)return W.BlobServiceClient.fromConnectionString(J);throw Error("AzureBlobDriver needs a connection string (AZURE_STORAGE_CONNECTION_STRING), a `url`, or a `serviceClient`.")})(),this.serviceClientPromise}async blob(W,J){if(!W)throw Error("Object name has to be specified");let Z=J??this.config.container??process.env.BUCKET_NAME;if(!Z)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");return(await this.serviceClient()).getContainerClient(Z).getBlockBlobClient(W)}async put(W,{signal:J}={}){J?.throwIfAborted();let Z,$,Q,Y;if(W instanceof Blob)Z=W,Q=`${Bun.randomUUIDv7()}.${W.type.split("/")[1].split(";")[0]}`,$=W.type;else Z=W.body,Q=W.name,Y=W.bucket,$=W.contentType??(Z instanceof Blob||Z instanceof File?Z.type:void 0);let G=Z instanceof H0?Z:H0.from(await Z.arrayBuffer()),K=await this.blob(Q,Y);return J?.throwIfAborted(),await K.uploadData(G,{blobHTTPHeaders:$?{blobContentType:$}:void 0,abortSignal:J}),Q}async*objects(W,{bucket:J,signal:Z}={}){Z?.throwIfAborted();let $=J??this.config.container??process.env.BUCKET_NAME;if(!$)throw Error("AzureBlobDriver needs a container name, from `bucket`, the `container` config, or BUCKET_NAME.");let Y=(await this.serviceClient()).getContainerClient($);for await(let G of Y.listBlobsFlat({prefix:W}))Z?.throwIfAborted(),yield{name:G.name,size:G.properties?.contentLength??0,lastModified:G.properties?.lastModified??new Date(0)}}async list(W){let J=this.config.container??process.env.BUCKET_NAME,$=(await this.serviceClient()).getContainerClient(J),Q=[];for await(let Y of $.listBlobsFlat({prefix:W}))Q.push(Y.name);return Q}async fetch(W,{signal:J}={}){J?.throwIfAborted();let Z=await this.download(typeof W==="string"?{name:W}:{name:W.name,bucket:W.bucket},J);return new Response(Z.body,{headers:{"Content-Type":Z.type,"Content-Length":String(Z.total),"Cache-Control":"private, max-age=12000, must-revalidate","Last-Modified":Z.lastModified?.toUTCString()??"",ETag:Z.etag??""}})}async read(W){return this.download(typeof W==="string"?{name:W}:W)}async download(W,J){let{name:Z,bucket:$,range:Q=null}=W,Y=await this.blob(Z,$);J?.throwIfAborted();let G,K,z=Q?.kind==="suffix"||Q?.kind==="offset"&&Q.end===null&&Q.start===0;if(Q&&z){let H=await this.size({name:Z,bucket:$}),m=a1(Q,H);if(!m)throw new i(H);G=m.start,K=m.length}else if(Q?.kind==="offset")G=Q.start,K=Q.end===null?void 0:Q.end-Q.start+1;let X;try{X=await Y.download(G,K,J?{abortSignal:J}:void 0)}catch(H){if(U6(H))throw new i(await this.size({name:Z,bucket:$}));if(s1(H))throw new c(Z);throw H}let B=K1(X.contentRange),M=Boolean(B),D=B?.total??X.contentLength??0,S=await S6(X);if(S instanceof ReadableStream)S=f1(S,J);return J?.throwIfAborted(),{body:S,start:B?.start??0,end:B?.end??D-1,total:D,partial:M,type:X.contentType??"application/octet-stream",etag:X.etag||void 0,lastModified:X.lastModified,name:Z}}async size(W){let J=typeof W==="string"?W:W.name,Z=typeof W==="string"?void 0:W.bucket,$=await this.blob(J,Z);try{return(await $.getProperties()).contentLength??0}catch(Q){if(s1(Q))throw new c(J);throw Q}}async delete(W){let J=typeof W==="string"?W:W.name,Z=typeof W==="string"?void 0:W.bucket,$=await this.blob(J,Z);try{await $.delete()}catch(Q){if(s1(Q))return;throw Q}}}async function S6(W){if(W.blobBody)return await W.blobBody;if(W.readableStreamBody)return H6.toWeb(W.readableStreamBody);return null}function O6(W){return W}var R6=`
|
|
3
3
|
local currentKey = KEYS[1]
|
|
4
4
|
local previousKey = KEYS[2]
|
|
5
5
|
local limit = tonumber(ARGV[1])
|
|
@@ -26,7 +26,7 @@ current = redis.call("INCRBY", currentKey, cost)
|
|
|
26
26
|
redis.call("PEXPIRE", currentKey, window * 2)
|
|
27
27
|
|
|
28
28
|
return {1, current, previous}
|
|
29
|
-
`;class R0 extends t1{injectedClient;prefix;failOpen;onError;scriptSha=null;constructor(W={}){super();this.injectedClient=W.client,this.prefix=W.prefix??"gemi:rl",this.failOpen=W.failOpen??!0,this.onError=W.onError??((J)=>console.error(J))}async consume(W){let{key:J,limit:Z,window:$}=W,
|
|
29
|
+
`;class R0 extends t1{injectedClient;prefix;failOpen;onError;scriptSha=null;constructor(W={}){super();this.injectedClient=W.client,this.prefix=W.prefix??"gemi:rl",this.failOpen=W.failOpen??!0,this.onError=W.onError??((J)=>console.error(J))}async consume(W){let{key:J,limit:Z,window:$}=W,Q=W.cost??1,Y=Date.now(),G=S0(Y,$),K=Y-G,z=G/$;try{let X=await this.run([`${this.prefix}:${J}:${z}`,`${this.prefix}:${J}:${z-1}`],[String(Z),String($),String(K),String(Q)]),[B,M,D]=(Array.isArray(X)?X:[]).map(Number);return O0({allowed:B===1,current:Number.isFinite(M)?M:0,previous:Number.isFinite(D)?D:0,now:Y,elapsed:K,window:$,limit:Z,cost:Q})}catch(X){if(this.onError(X),!this.failOpen)return{allowed:!1,limit:Z,remaining:0,resetAt:Y+$,retryAfter:$};return{allowed:!0,limit:Z,remaining:Math.max(0,Math.floor(Z-Q)),resetAt:G+$,retryAfter:0}}}get client(){if(this.injectedClient)return this.injectedClient;let W=v(),J=W.bound(_1)?W.make(_1).client:void 0;if(!J)throw Error("RedisRateLimiter could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisRateLimiter({ client }).");return J}async run(W,J){let Z=this.client,$=[String(W.length),...W,...J];try{return await Z.send("EVALSHA",[await this.load(Z),...$])}catch(Q){if(!f6(Q))throw Q;return this.scriptSha=null,await Z.send("EVALSHA",[await this.load(Z),...$])}}load(W){if(!this.scriptSha)this.scriptSha=Promise.resolve(W.send("SCRIPT",["LOAD",R6])).then(String).catch((J)=>{throw this.scriptSha=null,J});return this.scriptSha}}function f6(W){return String(W?.message??W).includes("NOSCRIPT")}import{createHash as X4,randomBytes as u,timingSafeEqual as _6}from"crypto";var k1=Object.freeze({"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","X-Frame-Options":"DENY","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'","Referrer-Policy":"no-referrer","X-Content-Type-Options":"nosniff"});function f0(W,J){let Z=W.client.name?_(W.client.name):"An application",$=W.scopes.map((Y)=>`<li><strong>${_(Y.name)}</strong><br><span>${_(Y.description)}</span></li>`).join(""),Q=Object.entries(W.form.fields).map(([Y,G])=>`<input type="hidden" name="${_(Y)}" value="${_(G)}">`).join("");return`<!doctype html>
|
|
30
30
|
<html lang="en">
|
|
31
31
|
<head>
|
|
32
32
|
<meta charset="utf-8">
|
|
@@ -53,7 +53,7 @@ return {1, current, previous}
|
|
|
53
53
|
<p>It will be able to:</p>
|
|
54
54
|
<ul>${$}</ul>
|
|
55
55
|
<form method="post" action="${_(W.form.action)}">
|
|
56
|
-
${
|
|
56
|
+
${Q}
|
|
57
57
|
<div class="actions">
|
|
58
58
|
<button type="submit" name="decision" value="deny">Deny</button>
|
|
59
59
|
<button type="submit" name="decision" value="allow">Allow</button>
|
|
@@ -61,12 +61,12 @@ return {1, current, previous}
|
|
|
61
61
|
</form>
|
|
62
62
|
</main>
|
|
63
63
|
</body>
|
|
64
|
-
</html>`}function _0(W){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Authorization failed</title></head><body style="font-family: system-ui, sans-serif; padding: 24px"><h1 style="font-size: 1.2rem">This connection could not be authorized</h1><p>${_(W)}</p></body></html>`}function _(W){return W.replace(/[&<>"']/g,(J)=>`&#${J.charCodeAt(0)};`)}var r1="gmcp_at_",e1="gmcp_rt_",k0="gmcp_ac_",_6="gmcp_c_",k6="gmcp_cs_",W4="gemi.mcp.oauth.ticket.v1",C0="gemi.mcp.oauth.consent.v1",C6=600000,I0=120000,G4=16384,I6={limit:20,window:3600},b6={limit:60,window:60},C1=["none","client_secret_post","client_secret_basic"];class N extends Error{error;description;status;headers;constructor(W,J,Z=400,$={}){super(J);this.error=W;this.description=J;this.status=Z;this.headers=$}}class h0{options;name="oauth";context;issuer;base;accessTtl;refreshTtl;constructor(W){this.options=W;let J=W?.store;for(let Z of["createClient","findClient","saveCode","findCode","saveToken","findToken","use","revokeFamily"])if(typeof J?.[Z]!=="function")throw Error(`McpOAuthServer: store.${Z} is missing. Use MemoryMcpOAuthStore, or implement McpOAuthStore.`);if(typeof W.findUser!=="function")throw Error("McpOAuthServer: findUser(id) is required: it loads the user a token was issued to.");if(W.consentPath!==void 0&&!/^\/[^/\\]/.test(W.consentPath))throw Error('McpOAuthServer: consentPath must be a path on this app, like "/oauth/consent".');this.accessTtl=b0("accessTokenTtl",W.accessTokenTtl,3600),this.refreshTtl=b0("refreshTokenTtl",W.refreshTokenTtl,2592000)}get store(){return this.options.store}boot(W){this.context=W;let J=new URL(W.resource);this.issuer=J.origin,this.base=`${J.pathname}/oauth`}async resolve(W){let J=z4(W);if(!J?.startsWith(r1))return null;let Z=await this.store.findToken(P(J)),$=(Q)=>({ok:!1,error:"invalid_token",description:Q});if(!Z||Z.kind!=="access")return $("The access token is not valid.");if(Z.expiresAt<=Date.now())return $("The access token expired.");if(Z.resource!==this.context.resource)return $("The access token was not issued for this server.");let Y=await this.options.findUser(Z.userId);if(!Y)return $("The access token is not valid.");return{ok:!0,principal:{user:Y,via:this.name,id:Z.familyId,scopes:Z.scopes,clientId:Z.clientId}}}challenge(){let W=this.scopeNames().join(" ");return`Bearer resource_metadata="${this.resourceMetadataUrl()}", scope="${W}"`}async handle(W){let J=new URL(W.url).pathname,Y={[`/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-protected-resource"]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-authorization-server"]:{methods:["GET"],cors:!0,run:()=>this.serverMetadata()},[`${this.base}/register`]:{methods:["POST"],cors:!0,run:()=>this.register(W)},[`${this.base}/authorize`]:{methods:["GET"],cors:!1,run:()=>this.authorize(W)},[`${this.base}/consent`]:{methods:["GET","POST"],cors:!1,run:()=>W.method==="POST"?this.decide(W):this.consentScreen(W)},[`${this.base}/token`]:{methods:["POST"],cors:!0,run:()=>this.token(W)},[`${this.base}/revoke`]:{methods:["POST"],cors:!0,run:()=>this.revoke(W)}}[J];if(!Y)return null;if(J===`${this.base}/register`&&this.options.registration===!1)return null;let Q=Y.cors?T6:{};if(W.method==="OPTIONS"&&Y.cors)return new Response(null,{status:204,headers:{...Q,"Access-Control-Allow-Methods":Y.methods.join(", "),"Access-Control-Allow-Headers":"Authorization, Content-Type, MCP-Protocol-Version","Access-Control-Max-Age":"600"}});if(!Y.methods.includes(W.method))return new Response(null,{status:405,headers:{...Q,Allow:Y.methods.join(", ")}});let G;try{G=await Y.run()}catch(K){if(!(K instanceof N))throw K;G=X1({error:K.error,error_description:K.description},K.status,K.headers)}for(let[K,z]of Object.entries(Q))G.headers.set(K,z);return G}async consent(W,J){if(!J)return null;let Z=I1(W4,"gat1",W);if(!Z)return null;let $=await this.store.findClient(Z.c);if(!$||!$.redirectUris.some((K)=>Z4(K,Z.r)))return null;let Y=String(J.id),Q=Q4(C0,"gcs1",{t:T0(W),u:Y,exp:Z.exp}),G=new Map(this.context.registry.scopes().map((K)=>[K.name,K.description]));return{client:{id:$.clientId,name:$.clientName,redirectHost:new URL(Z.r).host},scopes:Z.s.map((K)=>({name:K,description:G.get(K)??K})),user:{id:Y,label:this.userLabel(J)},form:{action:`${this.issuer}${this.base}/consent`,method:"POST",fields:{request:W,csrf:Q}}}}resourceMetadata(){return X1({resource:this.context.resource,authorization_servers:[this.issuer],scopes_supported:this.scopeNames(),bearer_methods_supported:["header"]})}serverMetadata(){return X1({issuer:this.issuer,authorization_endpoint:`${this.issuer}${this.base}/authorize`,token_endpoint:`${this.issuer}${this.base}/token`,...this.options.registration===!1?{}:{registration_endpoint:`${this.issuer}${this.base}/register`},revocation_endpoint:`${this.issuer}${this.base}/revoke`,scopes_supported:this.scopeNames(),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],token_endpoint_auth_methods_supported:C1,revocation_endpoint_auth_methods_supported:C1,code_challenge_methods_supported:["S256"],authorization_response_iss_parameter_supported:!0,client_id_metadata_document_supported:!1})}async register(W){let J=this.options.registration||{},Z=await Y4(`mcp-oauth-register:${y0(new $4(W,{},"api",`${this.base}/register`))}`,J.rateLimit??I6);if(Z!==null)throw new N("slow_down","Too many registrations from this address.",429,{"Retry-After":String(Z)});if(!/^application\/json\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new N("invalid_client_metadata","Send the client metadata as application/json.");let $;try{$=JSON.parse(await K4(W,G4))}catch{throw new N("invalid_client_metadata","The client metadata is not JSON, or is too large.")}if(typeof $!=="object"||$===null||Array.isArray($))throw new N("invalid_client_metadata","The client metadata must be a JSON object.");let Y=$.redirect_uris;if(!Array.isArray(Y)||Y.length===0||Y.length>10)throw new N("invalid_redirect_uri","redirect_uris must list one to ten URIs.");for(let D of Y){let S=w6(D);if(S)throw new N("invalid_redirect_uri",`${String(D).slice(0,200)}: ${S}`);if(J.allowRedirectUri&&J.allowRedirectUri(new URL(D))!==!0)throw new N("invalid_redirect_uri",`${D}: this server does not accept it.`)}let Q=$.token_endpoint_auth_method??"client_secret_basic";if(!C1.includes(Q))throw new N("invalid_client_metadata",`token_endpoint_auth_method must be one of ${C1.join(", ")}.`);let G=$.grant_types??["authorization_code"];if(!Array.isArray(G)||G.some((D)=>D!=="authorization_code"&&D!=="refresh_token"))throw new N("invalid_client_metadata","grant_types may only be authorization_code and refresh_token.");let K=$.response_types??["code"];if(!Array.isArray(K)||K.some((D)=>D!=="code"))throw new N("invalid_client_metadata","response_types may only be code.");let z=w0($.client_name,100,"client_name"),X=w0($.client_uri,512,"client_uri");if(X!==null&&!P6(X))throw new N("invalid_client_metadata","client_uri must be an https URL.");let B=Q==="none"?null:`${k6}${u(32).toString("base64url")}`,M={clientId:`${_6}${u(16).toString("base64url")}`,clientSecretHash:B?P(B):null,tokenEndpointAuthMethod:Q,redirectUris:[...Y],clientName:z,clientUri:X,createdAt:Date.now()};return await this.store.createClient(M),X1({client_id:M.clientId,client_id_issued_at:Math.floor(M.createdAt/1000),...B?{client_secret:B,client_secret_expires_at:0}:{},redirect_uris:M.redirectUris,token_endpoint_auth_method:Q,grant_types:G,response_types:K,...z?{client_name:z}:{},...X?{client_uri:X}:{}},201)}async authorize(W){let J=new URL(W.url).searchParams;for(let H of new Set(J.keys()))if(J.getAll(H).length>1)return b(`The parameter ${H} was sent more than once.`);let Z=J.get("client_id"),$=Z?await this.store.findClient(Z):null;if(!$)return b("The application is not registered with this server.");let Y=J.get("redirect_uri")??($.redirectUris.length===1?$.redirectUris[0]:null);if(!Y||!$.redirectUris.some((H)=>Z4(H,Y)))return b("The redirect URI is not one the application registered.");let Q=J.get("state"),G=(H,m)=>this.redirectBack(Y,Q,{error:H,error_description:m});if(J.get("response_type")!=="code")return G("unsupported_response_type","Only response_type=code is supported.");let K=J.get("code_challenge");if(J.get("code_challenge_method")!=="S256"||!K||!/^[A-Za-z0-9_-]{43}$/.test(K))return G("invalid_request","PKCE is required: code_challenge with code_challenge_method=S256.");let z=J.get("resource");if(z!==null&&!V0(z,this.context.resource))return G("invalid_target","The resource is not this server's.");if(Q!==null&&Q.length>2048)return G("invalid_request","state is too long.");let X=this.scopeNames(),B=J.get("scope"),M=X;if(B!==null&&B.trim()!==""){if(M=[...new Set(B.split(" ").filter((H)=>X.includes(H)))],M.length===0)return G("invalid_scope","None of the requested scopes exist here.")}let D=Q4(W4,"gat1",{c:$.clientId,r:Y,s:M,cc:K,st:Q,n:u(16).toString("base64url"),exp:Date.now()+C6}),S=this.options.consentPath??`${this.base}/consent`;return J4(`${this.issuer}${S}?request=${encodeURIComponent(D)}`,302)}async consentScreen(W){let J=new URL(W.url).searchParams.get("request"),Z=await this.sessionUser(W);if(!Z){let Y=`${this.base}/consent?request=${encodeURIComponent(J??"")}`,Q=this.options.signInPath??v(b1).config.signInPath;return J4(`${Q}${Q.includes("?")?"&":"?"}redirect=${encodeURIComponent(Y)}`,302)}let $=await this.consent(J,Z);if(!$)return b("This authorization request has expired or is not valid. Start again from the application.");return new Response(f0($,{name:this.options.appName??new URL(this.issuer).host}),{status:200,headers:k1})}async decide(W){let J=W.headers.get("origin");if(!(J!==null?J===this.issuer:W.headers.get("sec-fetch-site")==="same-origin"))return b("This decision did not come from this site's consent page.",403);if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))return b("The decision must be a form post.");let $;try{$=new URLSearchParams(await K4(W,G4))}catch{return b("The decision is too large.")}let Y=$.get("request"),Q=I1(W4,"gat1",Y),G=I1(C0,"gcs1",$.get("csrf")),K=await this.sessionUser(W);if(!Q||!G||!K||G.t!==T0(Y)||G.u!==String(K.id))return b("This authorization request has expired or is not valid. Start again from the application.",403);let z=await this.store.findClient(Q.c);if(!z||!z.redirectUris.some((B)=>Z4(B,Q.r)))return b("The application is not registered with this server.");if(!await this.store.use(`ticket:${Q.n}`,Q.exp))return b("This request was already answered. Start again from the application.");if($.get("decision")!=="allow")return this.redirectBack(Q.r,Q.st,{error:"access_denied",error_description:"The user denied the request."},303);let X=`${k0}${u(32).toString("base64url")}`;return await this.store.saveCode({hash:P(X),clientId:z.clientId,userId:String(K.id),redirectUri:Q.r,codeChallenge:Q.cc,scopes:Q.s,resource:this.context.resource,familyId:u(16).toString("base64url"),expiresAt:Date.now()+I0}),this.redirectBack(Q.r,Q.st,{code:X},303)}async token(W){let J=await P0(W),Z=await this.authenticateClient(W,J),$=await Y4(`mcp-oauth-token:${Z.clientId}`,b6);if($!==null)throw new N("slow_down","Too many token requests.",429,{"Retry-After":String($)});let Y=J.get("resource");if(Y!==null&&!V0(Y,this.context.resource))throw new N("invalid_target","The resource is not this server's.");switch(J.get("grant_type")){case"authorization_code":{let Q=J.get("code")??"",G=Q.startsWith(k0)?await this.store.findCode(P(Q)):null;if(!G||G.clientId!==Z.clientId)throw new N("invalid_grant","The authorization code is not valid.");if(!await this.store.use(G.hash,G.expiresAt+I0))throw await this.store.revokeFamily(G.familyId),new N("invalid_grant","The authorization code was already used.");if(G.expiresAt<=Date.now())throw new N("invalid_grant","The authorization code expired.");if(J.get("redirect_uri")!==null&&J.get("redirect_uri")!==G.redirectUri)throw new N("invalid_grant","redirect_uri is not the one the code was issued to.");let K=J.get("code_verifier");if(!K||!/^[A-Za-z0-9._~-]{43,128}$/.test(K)||!v0(v6(K),G.codeChallenge))throw new N("invalid_grant","The PKCE code_verifier does not match.");if(!await this.options.findUser(G.userId))throw new N("invalid_grant","The authorization code is not valid.");return await this.issue(G)}case"refresh_token":{let Q=J.get("refresh_token")??"",G=Q.startsWith(e1)?await this.store.findToken(P(Q)):null;if(!G||G.kind!=="refresh"||G.clientId!==Z.clientId)throw new N("invalid_grant","The refresh token is not valid.");if(G.expiresAt<=Date.now())throw new N("invalid_grant","The refresh token expired.");if(!await this.store.use(G.hash,G.expiresAt))throw await this.store.revokeFamily(G.familyId),new N("invalid_grant","The refresh token was already used.");if(G.resource!==this.context.resource)throw new N("invalid_grant","The refresh token was not issued for this server.");let K=G.scopes,z=J.get("scope");if(z!==null&&z.trim()!==""){let X=[...new Set(z.split(" ").filter(Boolean))];if(X.some((B)=>!G.scopes.includes(B)))throw new N("invalid_scope","A refresh can only narrow the scopes that were granted.");K=X}if(!await this.options.findUser(G.userId))throw new N("invalid_grant","The refresh token is not valid.");return await this.issue({...G,scopes:K})}default:throw new N("unsupported_grant_type","grant_type must be authorization_code or refresh_token.")}}async issue(W){let J=Date.now(),Z=this.scopeNames(),$=W.scopes.filter((K)=>Z.includes(K)),Y=`${r1}${u(32).toString("base64url")}`,Q=`${e1}${u(32).toString("base64url")}`,G={clientId:W.clientId,userId:W.userId,scopes:$,resource:W.resource,familyId:W.familyId};return await this.store.saveToken({...G,hash:P(Y),kind:"access",expiresAt:J+this.accessTtl*1000}),await this.store.saveToken({...G,hash:P(Q),kind:"refresh",expiresAt:J+this.refreshTtl*1000}),X1({access_token:Y,token_type:"Bearer",expires_in:this.accessTtl,refresh_token:Q,scope:$.join(" ")})}async revoke(W){let J=await P0(W),Z=await this.authenticateClient(W,J),$=J.get("token")??"";if($.startsWith(r1)||$.startsWith(e1)){let Y=await this.store.findToken(P($));if(Y&&Y.clientId===Z.clientId)await this.store.revokeFamily(Y.familyId)}return new Response(null,{status:200,headers:{"Cache-Control":"no-store"}})}async authenticateClient(W,J){let Z=/^Basic\s+([A-Za-z0-9+/=]+)$/i.exec(W.headers.get("authorization")??""),$=J.get("client_id"),Y=J.get("client_secret");if(Z){let G=Buffer.from(Z[1],"base64").toString("utf8"),K=G.indexOf(":");if(K<0)throw p(!0);let z=q0(G.slice(0,K));if(z===null)throw p(!0);if($!==null&&$!==z)throw p(!0);if($=z,Y=q0(G.slice(K+1)),Y===null)throw p(!0)}let Q=$?await this.store.findClient($):null;if(!Q)throw p(Boolean(Z));if(Q.tokenEndpointAuthMethod==="none"){if(Y)throw p(Boolean(Z));return Q}if(!Y||!Q.clientSecretHash||!v0(P(Y),Q.clientSecretHash))throw p(Boolean(Z));return Q}redirectBack(W,J,Z,$=302){let Y=new URL(W);for(let[Q,G]of Object.entries(Z))Y.searchParams.set(Q,G);if(J!==null)Y.searchParams.set("state",J);return Y.searchParams.set("iss",this.issuer),J4(Y.href,$)}async sessionUser(W){let J=new $4(W,{},"api",this.base).cookies;return await A0(v(b1),{cookies:J,headers:{get:(Z)=>Z.toLowerCase()==="user-agent"?W.headers.get("user-agent"):null}})}userLabel(W){if(this.options.userLabel)return this.options.userLabel(W);let J=W;return String(J.email??J.name??J.id)}scopeNames(){return this.context.registry.scopes().map((W)=>W.name)}resourceMetadataUrl(){return`${this.issuer}/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`}}var T6={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"};function b0(W,J,Z){if(J===void 0)return Z;if(!Number.isInteger(J)||J<60)throw Error(`McpOAuthServer: ${W} must be a whole number of seconds, at least 60.`);return J}function P(W){return X4("sha256").update(W).digest("hex")}function T0(W){return X4("sha256").update(W).digest("base64url")}function v6(W){return X4("sha256").update(W).digest("base64url")}function v0(W,J){let Z=Buffer.from(W),$=Buffer.from(J);return Z.length===$.length&&f6(Z,$)}function X1(W,J=200,Z={}){return new Response(JSON.stringify(W),{status:J,headers:{"Content-Type":"application/json","Cache-Control":"no-store",Pragma:"no-cache",...Z}})}function J4(W,J){return new Response(null,{status:J,headers:{Location:W,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function b(W,J=400){return new Response(_0(W),{status:J,headers:k1})}function p(W){return new N("invalid_client","Client authentication failed.",401,W?{"WWW-Authenticate":'Basic realm="mcp-oauth"'}:{})}async function K4(W,J){let Z=Number(W.headers.get("content-length"));if(Number.isFinite(Z)&&Z>J)throw Error("too large");if(!W.body)return"";let $=W.body.getReader(),Y=[],Q=0;for(;;){let{done:G,value:K}=await $.read();if(G)break;if(Q+=K.byteLength,Q>J)throw await $.cancel(),Error("too large");Y.push(K)}return Buffer.concat(Y).toString("utf8")}async function P0(W){if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new N("invalid_request","Send the request as application/x-www-form-urlencoded.");let J;try{J=new URLSearchParams(await K4(W,G4))}catch{throw new N("invalid_request","The request is too large.")}for(let Z of new Set(J.keys()))if(J.getAll(Z).length>1)throw new N("invalid_request",`${Z} was sent more than once.`);return J}function w0(W,J,Z){if(W===void 0||W===null||W==="")return null;if(typeof W!=="string"||W.length>J||V6(W))throw new N("invalid_client_metadata",`${Z} must be text of at most ${J} characters.`);return W}function P6(W){try{return new URL(W).protocol==="https:"}catch{return!1}}function g0(W){return W.hostname==="localhost"||W.hostname==="127.0.0.1"||W.hostname==="[::1]"}function w6(W){if(typeof W!=="string"||W.length>2048)return"not a URI";let J;try{J=new URL(W)}catch{return"not an absolute URI"}if(J.hash||W.includes("#"))return"must not have a fragment";if(J.username||J.password)return"must not carry credentials";if(J.protocol==="https:")return null;if(J.protocol==="http:"&&g0(J))return null;return"must be https, or http on a loopback address"}function Z4(W,J){if(W===J)return!0;let Z,$;try{Z=new URL(W),$=new URL(J)}catch{return!1}return Z.protocol==="http:"&&$.protocol==="http:"&&g0(Z)&&Z.hostname===$.hostname&&Z.pathname===$.pathname&&Z.search===$.search&&!$.hash&&!$.username&&!$.password}function V0(W,J){return W===J||W===`${J}/`}function V6(W){for(let J=0;J<W.length;J++){let Z=W.charCodeAt(J);if(Z<32||Z===127)return!0}return!1}function q0(W){try{return decodeURIComponent(W.replace(/\+/g," "))}catch{return null}}class E0{clients=new Map;codes=new Map;tokens=new Map;used=new Map;revoked=new Set;async createClient(W){this.clients.set(W.clientId,structuredClone(W))}async findClient(W){let J=this.clients.get(W);return J?structuredClone(J):null}async saveCode(W){this.sweep(),this.codes.set(W.hash,structuredClone(W))}async findCode(W){let J=this.codes.get(W);return J&&!this.revoked.has(J.familyId)?structuredClone(J):null}async saveToken(W){this.sweep(),this.tokens.set(W.hash,structuredClone(W))}async findToken(W){let J=this.tokens.get(W);return J&&!this.revoked.has(J.familyId)?structuredClone(J):null}async use(W,J){if(this.used.has(W))return!1;return this.used.set(W,J),!0}async revokeFamily(W){this.revoked.add(W);for(let[J,Z]of this.tokens)if(Z.familyId===W)this.tokens.delete(J);for(let[J,Z]of this.codes)if(Z.familyId===W)this.codes.delete(J)}async families(W){let J=new Map;for(let Z of this.tokens.values())if(Z.userId===W&&!this.revoked.has(Z.familyId)&&Z.expiresAt>Date.now())J.set(Z.familyId,{familyId:Z.familyId,clientId:Z.clientId,scopes:[...Z.scopes]});return[...J.values()]}sweep(W=Date.now()){for(let[J,Z]of this.codes)if(Z.expiresAt<=W)this.codes.delete(J);for(let[J,Z]of this.tokens)if(Z.expiresAt<=W)this.tokens.delete(J);for(let[J,Z]of this.used)if(Z<=W)this.used.delete(J)}}class M1 extends k{application;previous;dispatched=[];static install(W){let J=W.resolved(k)?W.make(k):void 0;if(J instanceof M1)return J;let Z=new M1(W,J);return W.instance(k,Z),Z}constructor(W,J){super({listeners:[]});this.application=W;this.previous=J}dispatch(W,J){this.dispatched.push({event:W,args:J})}async dispatchAndWait(W,J){this.dispatched.push({event:W,args:J})}restore(){if(this.previous){this.application.instance(k,this.previous);return}this.application.forget(k)}assertDispatched(W,J){let Z=B1(W);if(this.matching(Z,J).length>0)return;throw Error(`Expected ${Z}${J?" matching the predicate":""} to have been dispatched. ${this.summary(Z,J!==void 0)}`)}assertNotDispatched(W,J){let Z=B1(W),$=this.matching(Z,J);if($.length===0)return;throw Error(`Expected ${Z}${J?" matching the predicate":""} not to have been dispatched, but it was dispatched ${B4($.length)}: ${T1($)}.`)}assertDispatchedTimes(W,J,Z){let $=B1(W),Y=this.matching($,Z);if(Y.length===J)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} to have been dispatched ${B4(J)}, but it was dispatched ${B4(Y.length)}. ${this.summary($,Z!==void 0)}`)}assertNothingDispatched(){if(this.dispatched.length===0)return;let W=this.dispatched.length;throw Error(`Expected nothing to have been dispatched, but ${W} ${W===1?"event was":"events were"}: ${T1(this.dispatched)}.`)}matching(W,J){return this.dispatched.filter((Z)=>B1(Z.event.constructor)===W&&(J===void 0||J(Z.event)))}summary(W,J){if(this.dispatched.length===0)return"Nothing was dispatched.";let Z=this.matching(W);if(J&&Z.length>0)return`Dispatched ${W}: ${T1(Z)}.`;return`Dispatched: ${T1(this.dispatched)}.`}}function B1(W){return W.name}function B4(W){return`${W} ${W===1?"time":"times"}`}function T1(W){return W.map(q6).join(", ")}function q6(W){let J=B1(W.event.constructor),Z=W.args??Object.values({...W.event});return`${J}(${Z.map(y6).join(", ")})`}function y6(W){try{return JSON.stringify(W)??String(W)}catch{return String(W)}}class c0{static name="unset";static afterCommit=!1;static dispatch(...W){m0(this),v(k).dispatch(new this(...W),W)}static dispatchAndWait(...W){return m0(this),v(k).dispatchAndWait(new this(...W),W)}static fake(){return M1.install(A6())}}function A6(){try{return v()}catch(W){throw Error("Event.fake() needs a booted application. The fake works by replacing the container's EventManager with a recorder, so there has to be a "+"container to replace it in \u2014 and a dispatch finds the recorder the "+"same way, by resolving from that container. Boot the app's kernel in the test's setup: `const kernel = new Kernel(); kernel.boot()` is enough on its own, since that is the phase that publishes the application every dispatch outside a request resolves through.",{cause:W})}}function m0(W){if(W.name!=="unset"&&W.name!=="")return;throw Error("Cannot dispatch an event with no name. Add `static name` to this Event "+"subclass \u2014 the listener registry is keyed by that string, and by that "+"string alone, so an event without one cannot reach a listener.")}var h6={clientId:process.env.GOOGLE_CLIENT_ID,clientSecret:process.env.GOOGLE_CLIENT_SECRET,redirectPath:"/auth/oauth/google/callback",scope:"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",authorizationParams:{}};function g6(W,J){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:J}class u0 extends j1{config;constructor(W={}){super();this.config={...h6,...W}}redirectUri(){return`${process.env.HOST_NAME??""}${this.config.redirectPath}`}getRedirectUrl(W,J){let Z=new URL("https://accounts.google.com/o/oauth2/v2/auth"),$={include_granted_scopes:"true",...this.config.authorizationParams,scope:this.config.scope,response_type:"code",redirect_uri:this.redirectUri(),client_id:this.config.clientId};if(J)$.state=J.state,$.code_challenge=J.codeChallenge,$.code_challenge_method=J.codeChallengeMethod;for(let[Y,Q]of Object.entries($))Z.searchParams.set(Y,Q);return Z.toString()}async onCallback(W,J){let Z=W.search.get("code");if(!Z)throw new q("missing_code");let $=new URLSearchParams({code:Z,client_id:this.config.clientId,client_secret:this.config.clientSecret,grant_type:"authorization_code",redirect_uri:this.redirectUri()});if(J?.codeVerifier)$.set("code_verifier",J.codeVerifier);let Y=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:$.toString()}),Q=await Y.json().catch(()=>({}));if(!Y.ok||typeof Q?.access_token!=="string"||Q.access_token==="")throw console.error("Google OAuth error: token exchange failed",Q?.error??Y.status),new q(g6(Q?.error,"exchange_failed"));let K=await(await fetch("https://www.googleapis.com/oauth2/v3/userinfo",{headers:{Authorization:`Bearer ${Q.access_token}`}})).json().catch(()=>({}));if(typeof K.sub!=="string"||K.sub==="")return console.error("Google OAuth error: sub not found in user info response",K),{};if(!K.email)console.error("Google OAuth error: email not found in user info response",K);return{providerId:K.sub,name:K.name,email:K.email,emailVerified:K.email_verified===!0||K.email_verified==="true"}}}var y="https://api.x.com/2/",o="https://api.x.com/labs/2/",A="https://api.x.com/1.1/",w="https://upload.x.com/1.1/",p0="https://stream.x.com/1.1/",s="https://ads-api.x.com/12/",a="https://ads-api-sandbox.twitter.com/12/";class M4{constructor({realData:W,rateLimit:J,instance:Z,queryParams:$,sharedParams:Y}){this._maxResultsWhenFetchLast=100,this._realData=W,this._rateLimit=J,this._instance=Z,this._queryParams=$,this._sharedParams=Y}get _isRateLimitOk(){if(!this._rateLimit)return!0;if(this._rateLimit.reset*1000<Date.now())return!0;return this._rateLimit.remaining>0}makeRequest(W){return this._instance.get(this.getEndpoint(),W,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(W,J){return new this.constructor({realData:W.data,rateLimit:W.rateLimit,instance:this._instance,queryParams:J,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(W){return{...W?{max_results:W}:{},...this._queryParams}}async next(W){let J=this.getNextQueryParams(W),Z=await this.makeRequest(J);return this.makeNewInstanceFromResult(Z,J)}async fetchNext(W){let J=this.getNextQueryParams(W),Z=await this.makeRequest(J);return await this.refreshInstanceFromResult(Z,!0),this}async fetchLast(W=1/0){let J=this.getNextQueryParams(this._maxResultsWhenFetchLast),Z=0;while(Z<W&&this._isRateLimitOk){let $=await this.makeRequest(J);if(await this.refreshInstanceFromResult($,!0),Z+=this.getPageLengthFromRequest($),this.isFetchLastOver($))break;J=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var W;return{...(W=this._rateLimit)!==null&&W!==void 0?W:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async*[Symbol.asyncIterator](){yield*this.getItemArray();let W=this,J=this.canFetchNextPage(this._realData);while(J&&this._isRateLimitOk&&W.getItemArray().length>0){let Z=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:Z._realData,headers:{},rateLimit:Z._rateLimit},!0),J=this.canFetchNextPage(Z._realData),yield*Z.getItemArray(),W=Z}}async*fetchAndIterate(){for(let Z of this.getItemArray())yield[Z,this];let W=this,J=this.canFetchNextPage(this._realData);while(J&&this._isRateLimitOk&&W.getItemArray().length>0){let Z=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:Z._realData,headers:{},rateLimit:Z._rateLimit},!0),J=this.canFetchNextPage(Z._realData);for(let $ of Z.getItemArray())yield[$,Z];this._rateLimit=Z._rateLimit,W=Z}}}class j4 extends M4{async previous(W){let J=this.getPreviousQueryParams(W),Z=await this.makeRequest(J);return this.makeNewInstanceFromResult(Z,J)}async fetchPrevious(W){let J=this.getPreviousQueryParams(W),Z=await this.makeRequest(J);return await this.refreshInstanceFromResult(Z,!1),this}}var t=M4;class F extends t{getNextQueryParams(W){var J;return{...this._queryParams,cursor:(J=this._realData.next_cursor_str)!==null&&J!==void 0?J:this._realData.next_cursor,...W?{count:W}:{}}}isFetchLastOver(W){return!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!this.isNextCursorInvalid(W.next_cursor)||!this.isNextCursorInvalid(W.next_cursor_str)}isNextCursorInvalid(W){return W===void 0||W===0||W===-1||W==="0"||W==="-1"}}class N4 extends F{constructor(){super(...arguments);this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.events.push(...Z.events),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class x4 extends F{constructor(){super(...arguments);this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.welcome_messages.push(...Z.welcome_messages),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}var L;(function(W){W.Jpeg="image/jpeg",W.Mp4="video/mp4",W.Mov="video/quicktime",W.Gif="image/gif",W.Png="image/png",W.Srt="text/plain",W.Webp="image/webp"})(L||(L={}));var h;(function(W){W.Create="message_create",W.WelcomeCreate="welcome_message"})(h||(h={}));var N1;(function(W){W.Request="request",W.PartialResponse="partial-response",W.Response="response"})(N1||(N1={}));class v1 extends Error{constructor(){super(...arguments);this.error=!0}}class x1 extends v1{constructor(W,J){super(W);this.type=N1.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:J})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class L1 extends v1{constructor(W,J){super(W);this.type=N1.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:J})}get request(){return this._options.request}get response(){return this._options.response}get responseError(){return this._options.responseError}get rawContent(){return this._options.rawContent}toJSON(){return{type:this.type,error:this.responseError}}}class D1 extends v1{constructor(W,J){super(W);if(this.type=N1.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:J}),this.code=J.code,this.headers=J.headers,this.rateLimit=J.rateLimit,J.data&&typeof J.data==="object"&&"error"in J.data&&!J.data.errors){let Z={...J.data};Z.errors=[{code:d.InternalError,message:Z.error}],this.data=Z}else this.data=J.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...W){let J=this.errors;if(!(J===null||J===void 0?void 0:J.length))return!1;if("code"in J[0])return J.some((Y)=>W.includes(Y.code));let Z=this.data;return W.includes(Z.type)}get errors(){var W;return(W=this.data)===null||W===void 0?void 0:W.errors}get rateLimitError(){return this.code===420||this.code===429}get isAuthError(){if(this.code===401)return!0;return this.hasErrorCode(d.AuthTimestampInvalid,d.AuthenticationFail,d.BadAuthenticationData,d.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var d;(function(W){W[W.InvalidCoordinates=3]="InvalidCoordinates",W[W.NoLocationFound=13]="NoLocationFound",W[W.AuthenticationFail=32]="AuthenticationFail",W[W.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",W[W.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",W[W.AuthTimestampInvalid=135]="AuthTimestampInvalid",W[W.BadAuthenticationData=215]="BadAuthenticationData",W[W.NoUserMatch=17]="NoUserMatch",W[W.UserNotFound=50]="UserNotFound",W[W.ResourceNotFound=34]="ResourceNotFound",W[W.TweetNotFound=144]="TweetNotFound",W[W.TweetNotVisible=179]="TweetNotVisible",W[W.NotAllowedResource=220]="NotAllowedResource",W[W.MediaIdNotFound=325]="MediaIdNotFound",W[W.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",W[W.TweetViolatedRules=422]="TweetViolatedRules",W[W.TargetUserSuspended=63]="TargetUserSuspended",W[W.YouAreSuspended=64]="YouAreSuspended",W[W.AccountUpdateFailed=120]="AccountUpdateFailed",W[W.NoSelfSpamReport=36]="NoSelfSpamReport",W[W.NoSelfMute=271]="NoSelfMute",W[W.AccountLocked=326]="AccountLocked",W[W.RateLimitExceeded=88]="RateLimitExceeded",W[W.NoDMRightForApp=93]="NoDMRightForApp",W[W.OverCapacity=130]="OverCapacity",W[W.InternalError=131]="InternalError",W[W.TooManyFollowings=161]="TooManyFollowings",W[W.TweetLimitExceeded=185]="TweetLimitExceeded",W[W.DuplicatedTweet=187]="DuplicatedTweet",W[W.TooManySpamReports=205]="TooManySpamReports",W[W.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",W[W.NoWriteRightForApp=261]="NoWriteRightForApp",W[W.TweetActionsDisabled=425]="TweetActionsDisabled",W[W.TweetRepliesRestricted=433]="TweetRepliesRestricted",W[W.NamedParameterMissing=38]="NamedParameterMissing",W[W.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",W[W.TweetTextTooLong=186]="TweetTextTooLong",W[W.MissingUrlParameter=195]="MissingUrlParameter",W[W.NoMultipleGifs=323]="NoMultipleGifs",W[W.InvalidMediaIds=324]="InvalidMediaIds",W[W.InvalidUrl=407]="InvalidUrl",W[W.TooManyTweetAttachments=386]="TooManyTweetAttachments",W[W.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",W[W.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",W[W.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",W[W.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",W[W.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",W[W.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",W[W.UnableToSendDM=151]="UnableToSendDM",W[W.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",W[W.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",W[W.DMTextTooLong=354]="DMTextTooLong",W[W.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",W[W.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",W[W.SuspendedApplication=416]="SuspendedApplication",W[W.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(d||(d={}));var d0;(function(W){W.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",W.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",W.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",W.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",W.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",W.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",W.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",W.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",W.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",W.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",W.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",W.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",W.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"})(d0||(d0={}));var j;(function(W){W.Connected="connected",W.ConnectError="connect error",W.ConnectionError="connection error",W.ConnectionClosed="connection closed",W.ConnectionLost="connection lost",W.ReconnectAttempt="reconnect attempt",W.Reconnected="reconnected",W.ReconnectError="reconnect error",W.ReconnectLimitExceeded="reconnect limit exceeded",W.DataKeepAlive="data keep-alive",W.Data="data event content",W.DataError="data twitter error",W.TweetParseError="data tweet parse error",W.Error="stream error"})(j||(j={}));class F1{constructor(W){this.value=W}}import*as m4 from"fs";var U={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function L4(W){let J={value:void 0,promise:W().then((Z)=>{return J.value=Z,Z})};return J}function P1(W){if(Array.isArray(W))return W;return[W]}function n0(W){for(let J of Object.keys(W))if(W[J]===void 0)delete W[J]}function w1(W){return typeof W==="object"&&"errors"in W&&!("data"in W)}function H1(W){if(Array.isArray(W)&&W.length>1)return!0;return W.toString().includes(",")}var l0=new Set;function D4(W){if(typeof console>"u"||!console.warn||!U.deprecationWarnings)return;let J=`${W.instance}-${W.method}-${W.problem}`;if(l0.has(J))return;let Z=`[twitter-api-v2] Deprecation warning: In ${W.instance}.${W.method}() call, ${W.problem}.
|
|
65
|
-
${W.resolution}.`;console.warn(Z),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),l0.add(J)}import{EventEmitter as p6}from"events";import{request as E6}from"https";import*as O from"zlib";import{EventEmitter as m6}from"events";class i0{constructor(W){this.requestData=W,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let W=this.requestData.url;return W.hostname+W.pathname}isCompressionDisabled(){return!this.requestData.compression||this.requestData.compression==="identity"}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(W){if(U.debug)U.logger.log("Request error:",W);return new x1("Request failed.",{request:this.req,error:W})}createPartialResponseError(W,J){let $=`Request failed with partial response with HTTP code ${this.res.statusCode}`;if(J)$+=" (connection abruptly closed)";else $+=" (parse error)";return new L1($,{request:this.req,response:this.res,responseError:W,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(W){return W.map(({code:J,message:Z})=>`${Z} (Twitter code ${J})`).join(", ")}formatV2Error(W){return`${W.title}: ${W.detail} (see ${W.type})`}createResponseError({res:W,data:J,rateLimit:Z,code:$}){var Y;if(U.debug)U.logger.log(`Request failed with code ${$}, data:`,J),U.logger.log("Response headers:",W.headers);let Q=`Request failed with code ${$}`;if((Y=J===null||J===void 0?void 0:J.errors)===null||Y===void 0?void 0:Y.length){let G=J.errors;if(typeof G[0]==="object"&&"code"in G[0])Q+=" - "+this.formatV1Errors(G);else Q+=" - "+this.formatV2Error(J)}return new D1(Q,{code:$,data:J,headers:W.headers,request:this.req,response:W,rateLimit:Z})}getResponseDataStream(W){if(this.isCompressionDisabled())return W;let J=(W.headers["content-encoding"]||"identity").trim().toLowerCase();if(J==="br"){let Z=O.createBrotliDecompress({flush:O.constants.BROTLI_OPERATION_FLUSH,finishFlush:O.constants.BROTLI_OPERATION_FLUSH});return W.pipe(Z),Z}if(J==="gzip"){let Z=O.createGunzip({flush:O.constants.Z_SYNC_FLUSH,finishFlush:O.constants.Z_SYNC_FLUSH});return W.pipe(Z),Z}if(J==="deflate"){let Z=O.createInflate({flush:O.constants.Z_SYNC_FLUSH,finishFlush:O.constants.Z_SYNC_FLUSH});return W.pipe(Z),Z}return W}detectResponseType(W){var J,Z;if(((J=W.headers["content-type"])===null||J===void 0?void 0:J.includes("application/json"))||((Z=W.headers["content-type"])===null||Z===void 0?void 0:Z.includes("application/problem+json")))return"json";else if(this.isFormEncodedEndpoint())return"url";return"text"}getParsedResponse(W){let J=this.responseData,Z=this.requestData.forceParseMode||this.detectResponseType(W);if(Z==="buffer")return Buffer.concat(J);else if(Z==="text")return Buffer.concat(J).toString();else if(Z==="json"){let $=Buffer.concat(J).toString();return $.length?JSON.parse($):void 0}else if(Z==="url"){let $=Buffer.concat(J).toString(),Y={};for(let[Q,G]of new URLSearchParams($))Y[Q]=G;return Y}else return}getRateLimitFromResponse(W){let J=void 0;if(W.headers["x-rate-limit-limit"]){if(J={limit:Number(W.headers["x-rate-limit-limit"]),remaining:Number(W.headers["x-rate-limit-remaining"]),reset:Number(W.headers["x-rate-limit-reset"])},W.headers["x-app-limit-24hour-limit"])J.day={limit:Number(W.headers["x-app-limit-24hour-limit"]),remaining:Number(W.headers["x-app-limit-24hour-remaining"]),reset:Number(W.headers["x-app-limit-24hour-reset"])};if(W.headers["x-user-limit-24hour-limit"])J.userDay={limit:Number(W.headers["x-user-limit-24hour-limit"]),remaining:Number(W.headers["x-user-limit-24hour-remaining"]),reset:Number(W.headers["x-user-limit-24hour-reset"])};if(this.requestData.rateLimitSaver)this.requestData.rateLimitSaver(J)}return J}onSocketEventHandler(W,J,Z){let $=this.onSocketCloseHandler.bind(this,W);Z.on("close",$),J.on("complete",()=>Z.off("close",$))}onSocketCloseHandler(W){if(this.req.removeAllListeners("timeout"),this.res)return;if(!this.requestErrorHandled)return W(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(W,J){var Z,$;($=(Z=this.requestData).requestEventDebugHandler)===null||$===void 0||$.call(Z,"request-error",{requestError:J}),this.requestErrorHandled=!0,W(this.createRequestError(J))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(W,J,Z){this.res=Z;let $=this.getResponseDataStream(Z);if($.on("data",(Y)=>this.responseData.push(Y)),$.on("end",this.onResponseEndHandler.bind(this,W,J)),$.on("close",this.onResponseCloseHandler.bind(this,W,J)),this.requestData.requestEventDebugHandler)this.requestData.requestEventDebugHandler("response",{res:Z}),Z.on("aborted",(Y)=>this.requestData.requestEventDebugHandler("response-aborted",{error:Y})),Z.on("error",(Y)=>this.requestData.requestEventDebugHandler("response-error",{error:Y})),Z.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),Z.on("end",()=>this.requestData.requestEventDebugHandler("response-end"))}onResponseEndHandler(W,J){let Z=this.getRateLimitFromResponse(this.res),$;try{$=this.getParsedResponse(this.res)}catch(Q){J(this.createPartialResponseError(Q,!1));return}let Y=this.res.statusCode;if(Y>=400){J(this.createResponseError({data:$,res:this.res,rateLimit:Z,code:Y}));return}if(U.debug)U.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),U.logger.log("Response body:",$);W({data:$,headers:this.res.headers,rateLimit:Z})}onResponseCloseHandler(W,J){let Z=this.res;if(Z.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(W,J)}catch($){return J(this.createPartialResponseError($,!0))}if(!Z.complete)return J(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(W,J,Z){if(Z.statusCode<400){if(U.debug)U.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${Z.statusCode} (starting stream)`);let Y=this.getResponseDataStream(Z);W({req:this.req,res:Y,originalResponse:Z,requestData:this.requestData})}else this.classicResponseHandler(()=>{return},J,Z)}debugRequest(){let W=this.requestData.url;if(U.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),W.search)U.logger.log("Request parameters:",[...W.searchParams.entries()].map(([J,Z])=>`${J}: ${Z}`));if(this.requestData.body)U.logger.log("Request body:",this.requestData.body)}buildRequest(){var W;let J=this.requestData.url,Z=J.username?`${J.username}:${J.password}`:void 0,$=(W=this.requestData.options.headers)!==null&&W!==void 0?W:{};if(this.requestData.compression===!0||this.requestData.compression==="brotli")$["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="gzip")$["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="deflate")$["accept-encoding"]="deflate;q=1, *;q=0.1";if(U.debug)this.debugRequest();this.req=E6({...this.requestData.options,host:J.hostname,port:J.port||void 0,path:J.pathname+J.search,protocol:J.protocol,auth:Z,headers:$})}registerRequestEventDebugHandlers(W){W.on("close",()=>this.requestData.requestEventDebugHandler("close")),W.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),W.on("socket",(J)=>{this.requestData.requestEventDebugHandler("socket",{socket:J}),J.on("error",(Z)=>this.requestData.requestEventDebugHandler("socket-error",{socket:J,error:Z})),J.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:J})),J.on("close",(Z)=>this.requestData.requestEventDebugHandler("socket-close",{socket:J,withError:Z})),J.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:J})),J.on("lookup",(...Z)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:J,data:Z})),J.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:J}))})}makeRequest(){return this.buildRequest(),new Promise((W,J)=>{let Z=(G)=>{Y.emit("complete"),W(G)},$=(G)=>{Y.emit("complete"),J(G)},Y=new m6,Q=this.req;if(Q.on("error",this.requestErrorHandler.bind(this,$)),Q.on("socket",this.onSocketEventHandler.bind(this,$,Y)),Q.on("response",this.classicResponseHandler.bind(this,Z,$)),this.requestData.options.timeout)Q.on("timeout",this.timeoutErrorHandler.bind(this));if(this.requestData.requestEventDebugHandler)this.registerRequestEventDebugHandlers(Q);if(this.requestData.body)Q.write(this.requestData.body);Q.end()})}async makeRequestAsStream(){let{req:W,res:J,requestData:Z,originalResponse:$}=await this.makeRequestAndResolveWhenReady();return new V1(Z,{req:W,res:J,originalResponse:$})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((W,J)=>{let Z=this.req;if(Z.on("error",this.requestErrorHandler.bind(this,J)),Z.on("response",this.streamResponseHandler.bind(this,W,J)),this.requestData.body)Z.write(this.requestData.body);Z.end()})}}var U1=i0;import{EventEmitter as c6}from"events";class o0 extends c6{constructor(W){super();this.stream=W,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),W.on(j.Data,this.onStreamData),W.on(j.ConnectionError,this.onStreamError),W.on(j.TweetParseError,this.onStreamError),W.on(j.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let W=this.stack;return this.stack=[],W}destroy(){this.removeAllListeners(),this.stream.off(j.Data,this.onStreamData),this.stream.off(j.ConnectionError,this.onStreamError),this.stream.off(j.TweetParseError,this.onStreamError),this.stream.off(j.ConnectionClosed,this.onStreamError)}emitEvent(W,J){this.emit("event",{type:W,payload:J})}onStreamError(W){this.emitEvent("error",W)}onStreamData(W){this.stack.push(W),this.emitEvent("data",W)}}var s0=o0;import{EventEmitter as u6}from"events";class q1 extends u6{constructor(){super(...arguments);this.currentMessage=""}push(W){this.currentMessage+=W,W=this.currentMessage;let J=W.length,Z=0,$=0;while($<J){if(W.slice($,$+2)===`\r
|
|
66
|
-
`){let
|
|
67
|
-
`)return this.emit(j.DataKeepAlive);this.parser.push(J.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let W=this.requestData.payloadIsError;this.parser.on(l.ParsedData,(J)=>{if(W&&W(J))this.emit(j.DataError,J),this.emit(j.Error,{type:j.DataError,error:J,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(j.Data,J)}),this.parser.on(l.ParseError,(J)=>{this.emit(j.TweetParseError,J),this.emit(j.Error,{type:j.TweetParseError,error:J,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){if(this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0)this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs)}onKeepAliveTimeout(){this.emit(j.ConnectionLost),this.onConnectionError()}unbindTimeouts(){this.unbindRetryTimeout(),this.unbindKeepAliveTimeout()}unbindKeepAliveTimeout(){if(this.keepAliveTimeout)clearTimeout(this.keepAliveTimeout),this.keepAliveTimeout=void 0}unbindRetryTimeout(){if(this.retryTimeout)clearTimeout(this.retryTimeout),this.retryTimeout=void 0}closeWithoutEmit(){if(this.unbindTimeouts(),this.res)this.res.removeAllListeners(),this.res.destroy();if(this.req)this.req.removeAllListeners(),this.req.destroy()}close(){this.emit(j.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let J=await new U1(this.requestData).makeRequestAsStream(),Z=this.eventNames();for(let $ of Z){let
|
|
68
|
-
`;I.DEFAULT_CONTENT_TYPE="application/octet-stream";class F4{static formatQueryToString(W){let J={};for(let Z in W)if(typeof W[Z]==="string")J[Z]=W[Z];else if(typeof W[Z]<"u")J[Z]=String(W[Z]);return J}static autoDetectBodyType(W){if(W.pathname.startsWith("/2/")||W.pathname.startsWith("/labs/2/")){if(W.password.startsWith("/2/oauth2"))return"url";return"json"}if(W.hostname==="upload.x.com"){if(W.pathname==="/1.1/media/upload.json")return"form-data";return"json"}let J=W.pathname.split("/1.1/",2)[1];if(this.JSON_1_1_ENDPOINTS.has(J))return"json";return"url"}static addQueryParamsToUrl(W,J){let Z=Object.entries(J);if(Z.length){let $="";for(let[Y,Q]of Z)$+=($.length?"&":"?")+`${S1.percentEncode(Y)}=${S1.percentEncode(Q)}`;W.search=$}}static constructBodyParams(W,J,Z){if(W instanceof Buffer)return W;if(Z==="json"){if(!J["content-type"])J["content-type"]="application/json;charset=UTF-8";return JSON.stringify(W)}else if(Z==="url"){if(!J["content-type"])J["content-type"]="application/x-www-form-urlencoded;charset=UTF-8";if(Object.keys(W).length)return new URLSearchParams(W).toString().replace(/\*/g,"%2A");return""}else if(Z==="raw")throw Error("You can only use raw body mode with Buffers. To give a string, use Buffer.from(str).");else{let $=new I;for(let Y in W)$.append(Y,W[Y]);if(!J["content-type"]){let Y=$.getHeaders();J["content-type"]=Y["content-type"]}return $.getBuffer()}}static setBodyLengthHeader(W,J){var Z;if(W.headers=(Z=W.headers)!==null&&Z!==void 0?Z:{},typeof J==="string")W.headers["content-length"]=Buffer.byteLength(J);else W.headers["content-length"]=J.length}static isOAuthSerializable(W){return!(W instanceof Buffer)}static mergeQueryAndBodyForOAuth(W,J){let Z={};for(let $ in W)Z[$]=W[$];if(this.isOAuthSerializable(J))for(let $ in J){let Y=J[$];if(this.isOAuthSerializable(Y))Z[$]=typeof Y==="object"&&Y!==null&&"toString"in Y?Y.toString():Y}return Z}static moveUrlQueryParamsIntoObject(W,J){for(let[Z,$]of W.searchParams)J[Z]=$;return W.search="",W}static applyRequestParametersToUrl(W,J){return W.pathname=W.pathname.replace(/:([A-Z_-]+)/ig,(Z,$)=>{if(J[$]!==void 0)return String(J[$]);return Z}),W}}F4.JSON_1_1_ENDPOINTS=new Set(["direct_messages/events/new.json","direct_messages/welcome_messages/new.json","direct_messages/welcome_messages/rules/new.json","media/metadata/create.json","collections/entries/curate.json"]);var R=F4;import*as $6 from"crypto";class n{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(W){return this.escapeBase64Url($6.createHash("sha256").update(W).digest("base64"))}static getAuthHeader(W,J){let Z=encodeURIComponent(W)+":"+encodeURIComponent(J);return Buffer.from(Z).toString("base64")}static generateRandomString(W){let J="",Z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";for(let $=0;$<W;$++)J+=Z[Math.floor(Math.random()*Z.length)];return J}static escapeBase64Url(W){return W.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class r{constructor(W){if(this.rateLimits={},this.clientSettings={},W)this.clientSettings=W}getRateLimits(){return this.rateLimits}saveRateLimit(W,J){this.rateLimits[W]=J}async send(W){var J,Z,$,Y,Q;if((J=this.clientSettings.plugins)===null||J===void 0?void 0:J.length){let M=await this.applyPreRequestConfigHooks(W);if(M)return M}let G=this.getHttpRequestArgs(W),K={method:G.method,headers:G.headers,timeout:W.timeout,agent:this.clientSettings.httpAgent},z=W.enableRateLimitSave!==!1;if(G.body)R.setBodyLengthHeader(K,G.body);if((Z=this.clientSettings.plugins)===null||Z===void 0?void 0:Z.length)await this.applyPreRequestHooks(W,G,K);let X=new U1({url:G.url,options:K,body:G.body,rateLimitSaver:z?this.saveRateLimit.bind(this,G.rawUrl):void 0,requestEventDebugHandler:W.requestEventDebugHandler,compression:(Y=($=W.compression)!==null&&$!==void 0?$:this.clientSettings.compression)!==null&&Y!==void 0?Y:!0,forceParseMode:W.forceParseMode}).makeRequest();if(r0(this))X=this.applyResponseErrorHooks(W,G,K,X);let B=await X;if((Q=this.clientSettings.plugins)===null||Q===void 0?void 0:Q.length){let M=await this.applyPostRequestHooks(W,G,K,B);if(M)return M.value}return B}sendStream(W){var J,Z;if(this.clientSettings.plugins)this.applyPreStreamRequestConfigHooks(W);let $=this.getHttpRequestArgs(W),Y={method:$.method,headers:$.headers,agent:this.clientSettings.httpAgent},Q=W.enableRateLimitSave!==!1,G=W.autoConnect!==!1;if($.body)R.setBodyLengthHeader(Y,$.body);let K={url:$.url,options:Y,body:$.body,rateLimitSaver:Q?this.saveRateLimit.bind(this,$.rawUrl):void 0,payloadIsError:W.payloadIsError,compression:(Z=(J=W.compression)!==null&&J!==void 0?J:this.clientSettings.compression)!==null&&Z!==void 0?Z:!0},z=new V1(K);if(!G)return z;return z.connect()}initializeToken(W){if(typeof W==="string")this.bearerToken=W;else if(typeof W==="object"&&"appKey"in W){if(this.consumerToken=W.appKey,this.consumerSecret=W.appSecret,W.accessToken&&W.accessSecret)this.accessToken=W.accessToken,this.accessSecret=W.accessSecret;this._oauth=this.buildOAuth()}else if(typeof W==="object"&&"username"in W){let J=encodeURIComponent(W.username)+":"+encodeURIComponent(W.password);this.basicToken=Buffer.from(J).toString("base64")}else if(typeof W==="object"&&"clientId"in W)this.clientId=W.clientId,this.clientSecret=W.clientSecret}getActiveTokens(){if(this.bearerToken)return{type:"oauth2",bearerToken:this.bearerToken};else if(this.basicToken)return{type:"basic",token:this.basicToken};else if(this.consumerSecret&&this._oauth)return{type:"oauth-1.0a",appKey:this.consumerToken,appSecret:this.consumerSecret,accessToken:this.accessToken,accessSecret:this.accessSecret};else if(this.clientId)return{type:"oauth2-user",clientId:this.clientId};return{type:"none"}}buildOAuth(){if(!this.consumerSecret||!this.consumerToken)throw Error("Invalid consumer tokens");return new S1({consumerKeys:{key:this.consumerToken,secret:this.consumerSecret}})}getOAuthAccessTokens(){if(!this.accessSecret||!this.accessToken)return;return{key:this.accessToken,secret:this.accessSecret}}getPlugins(){var W;return(W=this.clientSettings.plugins)!==null&&W!==void 0?W:[]}hasPlugins(){var W;return!!((W=this.clientSettings.plugins)===null||W===void 0?void 0:W.length)}async applyPluginMethod(W,J){var Z;let $;for(let Y of this.getPlugins()){let Q=await((Z=Y[W])===null||Z===void 0?void 0:Z.call(Y,J));if(Q&&Q instanceof F1)$=Q}return $}writeAuthHeaders({headers:W,bodyInSignature:J,url:Z,method:$,query:Y,body:Q}){if(W={...W},this.bearerToken)W.Authorization="Bearer "+this.bearerToken;else if(this.basicToken)W.Authorization="Basic "+this.basicToken;else if(this.clientId&&this.clientSecret)W.Authorization="Basic "+n.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let G=J?R.mergeQueryAndBodyForOAuth(Y,Q):Y,K=this._oauth.authorize({url:Z.toString(),method:$,data:G},this.getOAuthAccessTokens());W={...W,...this._oauth.toHeader(K)}}return W}getUrlObjectFromUrlString(W){if(!W.startsWith("http"))W="https://"+W;return new URL(W)}getHttpRequestArgs({url:W,method:J,query:Z={},body:$={},headers:Y,forceBodyMode:Q,enableAuth:G,params:K}){let z=void 0;if(J=J.toUpperCase(),Y=Y!==null&&Y!==void 0?Y:{},!Y["x-user-agent"])Y["x-user-agent"]="Node.twitter-api-v2";let X=this.getUrlObjectFromUrlString(W),B=X.origin+X.pathname;if(K)R.applyRequestParametersToUrl(X,K);let M=R.formatQueryToString(Z);if(R.moveUrlQueryParamsIntoObject(X,M),!($ instanceof Buffer))n0($);let D=Q!==null&&Q!==void 0?Q:R.autoDetectBodyType(X);if(G!==!1){let S=r.BODY_METHODS.has(J)&&D==="url";Y=this.writeAuthHeaders({headers:Y,bodyInSignature:S,method:J,query:M,url:X,body:$})}if(r.BODY_METHODS.has(J))z=R.constructBodyParams($,Y,D)||void 0;return R.addQueryParamsToUrl(X,M),{rawUrl:B,url:X,method:J,headers:Y,body:z}}async applyPreRequestConfigHooks(W){var J;let Z=this.getUrlObjectFromUrlString(W.url);for(let $ of this.getPlugins()){let Y=await((J=$.onBeforeRequestConfig)===null||J===void 0?void 0:J.call($,{client:this,url:Z,params:W}));if(Y)return Y}}applyPreStreamRequestConfigHooks(W){var J;let Z=this.getUrlObjectFromUrlString(W.url);for(let $ of this.getPlugins())(J=$.onBeforeStreamRequestConfig)===null||J===void 0||J.call($,{client:this,url:Z,params:W})}async applyPreRequestHooks(W,J,Z){await this.applyPluginMethod("onBeforeRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:J,requestOptions:Z})}async applyPostRequestHooks(W,J,Z,$){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:J,requestOptions:Z,response:$})}applyResponseErrorHooks(W,J,Z,$){return $.catch(e0.bind(this,W,J,Z))}}r.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class g{constructor(W,J={}){if(this._currentUser=null,this._currentUserV2=null,W instanceof g)this._requestMaker=W._requestMaker;else this._requestMaker=new r(J),this._requestMaker.initializeToken(W)}setPrefix(W){this._prefix=W}cloneWithPrefix(W){let J=this.constructor(this);return J.setPrefix(W),J}getActiveTokens(){return this._requestMaker.getActiveTokens()}getPlugins(){return this._requestMaker.getPlugins()}getPluginOfType(W){return this.getPlugins().find((J)=>J instanceof W)}hasHitRateLimit(W){var J;if(this.isRateLimitStatusObsolete(W))return!1;return((J=this.getLastRateLimitStatus(W))===null||J===void 0?void 0:J.remaining)===0}isRateLimitStatusObsolete(W){let J=this.getLastRateLimitStatus(W);if(J===void 0)return!0;return J.reset*1000<Date.now()}getLastRateLimitStatus(W){let J=W.match(/^https?:\/\//)?W:this._prefix+W;return this._requestMaker.getRateLimits()[J]}getCurrentUserObject(W=!1){if(!W&&this._currentUser){if(this._currentUser.value)return Promise.resolve(this._currentUser.value);return this._currentUser.promise}return this._currentUser=L4(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:A})),this._currentUser.promise}getCurrentUserV2Object(W=!1){if(!W&&this._currentUserV2){if(this._currentUserV2.value)return Promise.resolve(this._currentUserV2.value);return this._currentUserV2.promise}return this._currentUserV2=L4(()=>this.get("users/me",void 0,{prefix:y})),this._currentUserV2.promise}async get(W,J={},{fullResponse:Z,prefix:$=this._prefix,...Y}={}){if($)W=$+W;let Q=await this._requestMaker.send({url:W,method:"GET",query:J,...Y});return Z?Q:Q.data}async delete(W,J={},{fullResponse:Z,prefix:$=this._prefix,...Y}={}){if($)W=$+W;let Q=await this._requestMaker.send({url:W,method:"DELETE",query:J,...Y});return Z?Q:Q.data}async post(W,J,{fullResponse:Z,prefix:$=this._prefix,...Y}={}){if($)W=$+W;let Q=await this._requestMaker.send({url:W,method:"POST",body:J,...Y});return Z?Q:Q.data}async put(W,J,{fullResponse:Z,prefix:$=this._prefix,...Y}={}){if($)W=$+W;let Q=await this._requestMaker.send({url:W,method:"PUT",body:J,...Y});return Z?Q:Q.data}async patch(W,J,{fullResponse:Z,prefix:$=this._prefix,...Y}={}){if($)W=$+W;let Q=await this._requestMaker.send({url:W,method:"PATCH",body:J,...Y});return Z?Q:Q.data}getStream(W,J,{prefix:Z=this._prefix,...$}={}){return this._requestMaker.sendStream({url:Z?Z+W:W,method:"GET",query:J,...$})}postStream(W,J,{prefix:Z=this._prefix,...$}={}){return this._requestMaker.sendStream({url:Z?Z+W:W,method:"POST",body:J,...$})}}class f extends g{constructor(W){if(!(W instanceof g))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(W)}}class e extends t{constructor(){super(...arguments);this.hasFinishedFetch=!1}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.push(...Z),this.hasFinishedFetch=Z.length===0}getNextQueryParams(W){let J=BigInt(this._realData[this._realData.length-1].id_str);return{...this.injectQueryParams(W),max_id:(J-BigInt(1)).toString()}}getPageLengthFromRequest(W){return W.data.length}isFetchLastOver(W){return!W.data.length}canFetchNextPage(W){return W.length>0}getItemArray(){return this.tweets}get tweets(){return this._realData}get done(){return super.done||this.hasFinishedFetch}}class H4 extends e{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class U4 extends e{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class y1 extends e{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class S4 extends e{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class A1 extends e{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class O4 extends F{constructor(){super(...arguments);this._endpoint="mutes/users/list.json"}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.users.push(...Z.users),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class R4 extends F{constructor(){super(...arguments);this._endpoint="mutes/users/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.ids.push(...Z.ids),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class f4 extends F{constructor(){super(...arguments);this._endpoint="followers/list.json"}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.users.push(...Z.users),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class _4 extends F{constructor(){super(...arguments);this._endpoint="followers/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.ids.push(...Z.ids),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class k4 extends F{constructor(){super(...arguments);this._endpoint="friends/list.json"}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.users.push(...Z.users),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class C4 extends F{constructor(){super(...arguments);this._endpoint="friends/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.ids.push(...Z.ids),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class I4 extends t{constructor(){super(...arguments);this._endpoint="users/search.json"}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.push(...Z)}getNextQueryParams(W){var J;let Z=Number((J=this._queryParams.page)!==null&&J!==void 0?J:"1");return{...this._queryParams,page:Z+1,...W?{count:W}:{}}}getPageLengthFromRequest(W){return W.data.length}isFetchLastOver(W){return!W.data.length}canFetchNextPage(W){return W.length>0}getItemArray(){return this.users}get users(){return this._realData}}class h1 extends F{constructor(){super(...arguments);this._endpoint="friendships/incoming.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.ids.push(...Z.ids),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class b4 extends h1{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class g1 extends F{refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.lists.push(...Z.lists),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.lists.length}getItemArray(){return this.lists}get lists(){return this._realData.lists}}class T4 extends g1{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class v4 extends g1{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class P4 extends g1{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class w4 extends F{refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.users.push(...Z.users),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class V4 extends w4{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class q4 extends w4{constructor(){super(...arguments);this._endpoint="lists/subscribers.json"}}class W1 extends f{constructor(){super(...arguments);this._prefix=A}singleTweet(W,J={}){return this.get("statuses/show.json",{tweet_mode:"extended",id:W,...J})}tweets(W,J={}){return this.post("statuses/lookup.json",{tweet_mode:"extended",id:W,...J})}oembedTweet(W,J={}){return this.get("oembed",{url:`https://x.com/i/statuses/${W}`,...J},{prefix:"https://publish.x.com/"})}async homeTimeline(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("statuses/home_timeline.json",J,{fullResponse:!0});return new H4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async mentionTimeline(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("statuses/mentions_timeline.json",J,{fullResponse:!0});return new U4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async userTimeline(W,J={}){let Z={tweet_mode:"extended",user_id:W,...J},$=await this.get("statuses/user_timeline.json",Z,{fullResponse:!0});return new y1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userTimelineByUsername(W,J={}){let Z={tweet_mode:"extended",screen_name:W,...J},$=await this.get("statuses/user_timeline.json",Z,{fullResponse:!0});return new y1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async favoriteTimeline(W,J={}){let Z={tweet_mode:"extended",user_id:W,...J},$=await this.get("favorites/list.json",Z,{fullResponse:!0});return new A1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async favoriteTimelineByUsername(W,J={}){let Z={tweet_mode:"extended",screen_name:W,...J},$=await this.get("favorites/list.json",Z,{fullResponse:!0});return new A1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}user(W){return this.get("users/show.json",{tweet_mode:"extended",...W})}users(W){return this.get("users/lookup.json",{tweet_mode:"extended",...W})}verifyCredentials(W={}){return this.get("account/verify_credentials.json",W)}async listMutedUsers(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("mutes/users/list.json",J,{fullResponse:!0});return new O4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async listMutedUserIds(W={}){let J={stringify_ids:!0,...W},Z=await this.get("mutes/users/ids.json",J,{fullResponse:!0});return new R4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async userFriendList(W={}){let J={...W},Z=await this.get("friends/list.json",J,{fullResponse:!0});return new k4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async userFollowerList(W={}){let J={...W},Z=await this.get("followers/list.json",J,{fullResponse:!0});return new f4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async userFollowerIds(W={}){let J={stringify_ids:!0,...W},Z=await this.get("followers/ids.json",J,{fullResponse:!0});return new _4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async userFollowingIds(W={}){let J={stringify_ids:!0,...W},Z=await this.get("friends/ids.json",J,{fullResponse:!0});return new C4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async searchUsers(W,J={}){let Z={q:W,tweet_mode:"extended",page:1,...J},$=await this.get("users/search.json",Z,{fullResponse:!0});return new I4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}friendship(W){return this.get("friendships/show.json",W)}friendships(W){return this.get("friendships/lookup.json",W)}friendshipsNoRetweets(){return this.get("friendships/no_retweets/ids.json",{stringify_ids:!0})}async friendshipsIncoming(W={}){let J={stringify_ids:!0,...W},Z=await this.get("friendships/incoming.json",J,{fullResponse:!0});return new h1({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async friendshipsOutgoing(W={}){let J={stringify_ids:!0,...W},Z=await this.get("friendships/outgoing.json",J,{fullResponse:!0});return new b4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}accountSettings(){return this.get("account/settings.json")}userProfileBannerSizes(W){return this.get("users/profile_banner.json",W)}list(W){return this.get("lists/show.json",{tweet_mode:"extended",...W})}lists(W={}){return this.get("lists/list.json",{tweet_mode:"extended",...W})}async listMembers(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("lists/members.json",J,{fullResponse:!0});return new V4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}listGetMember(W){return this.get("lists/members/show.json",{tweet_mode:"extended",...W})}async listMemberships(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("lists/memberships.json",J,{fullResponse:!0});return new T4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async listOwnerships(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("lists/ownerships.json",J,{fullResponse:!0});return new v4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async listStatuses(W){let J={tweet_mode:"extended",...W},Z=await this.get("lists/statuses.json",J,{fullResponse:!0});return new S4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async listSubscribers(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("lists/subscribers.json",J,{fullResponse:!0});return new q4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}listGetSubscriber(W){return this.get("lists/subscribers/show.json",{tweet_mode:"extended",...W})}async listSubscriptions(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("lists/subscriptions.json",J,{fullResponse:!0});return new P4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}mediaInfo(W){return this.get("media/upload.json",{command:"STATUS",media_id:W},{prefix:w})}filterStream({autoConnect:W,...J}={}){let Z={};for(let[Y,Q]of Object.entries(J))if(Y==="follow"||Y==="track")Z[Y]=Q.toString();else if(Y==="locations"){let G=Q;Z.locations=P1(G).map((K)=>`${K.lng},${K.lat}`).join(",")}else Z[Y]=Q;return this.stream.postStream("statuses/filter.json",Z,{autoConnect:W})}sampleStream({autoConnect:W,...J}={}){return this.stream.getStream("statuses/sample.json",J,{autoConnect:W})}get stream(){let W=new E1(this);return W.setPrefix(p0),W}trendsByPlace(W,J={}){return this.get("trends/place.json",{id:W,...J})}trendsAvailable(){return this.get("trends/available.json")}trendsClosest(W,J){return this.get("trends/closest.json",{lat:W,long:J})}geoPlace(W){return this.get("geo/id/:place_id.json",void 0,{params:{place_id:W}})}geoSearch(W){return this.get("geo/search.json",W)}geoReverseGeoCode(W){return this.get("geo/reverse_geocode.json",W)}rateLimitStatuses(...W){return this.get("application/rate_limit_status.json",{resources:W})}supportedLanguages(){return this.get("help/languages.json")}}import*as E from"fs";async function y4(W){let J=await A4(W);if(typeof J==="number")return new Promise((Z,$)=>{E.readFile(J,(Y,Q)=>{if(Y)return $(Y);Z(Q)})});else if(J instanceof Buffer)return J;else return J.readFile()}function A4(W){if(typeof W==="string")return E.promises.open(W,"r");else if(typeof W==="number")return W;else if(typeof W==="object"&&!(W instanceof Buffer))return W;else if(!(W instanceof Buffer))throw Error("Given file is not valid, please check its type.");else return W}async function Y6(W){if(typeof W==="number")return(await new Promise((Z,$)=>{E.fstat(W,(Y,Q)=>{if(Y)$(Y);Z(Q)})})).size;else if(W instanceof Buffer)return W.length;else return(await W.stat()).size}function Q6(W,J,Z){if(typeof Z==="string")return Z;else if(typeof W==="string"&&!J)return o6(W);else if(typeof J==="string")return s6(J);throw Error("You must specify type if file is a file handle or Buffer.")}function o6(W){if(W.endsWith(".jpeg")||W.endsWith(".jpg"))return L.Jpeg;if(W.endsWith(".png"))return L.Png;if(W.endsWith(".webp"))return L.Webp;if(W.endsWith(".gif"))return L.Gif;if(W.endsWith(".mpeg4")||W.endsWith(".mp4"))return L.Mp4;if(W.endsWith(".mov")||W.endsWith(".mov"))return L.Mov;if(W.endsWith(".srt"))return L.Srt;return D4({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"options.mimeType is missing and filename couldn't help to resolve MIME type, so it will fallback to image/jpeg",resolution:"If you except to give filenames without extensions, please specify explicitlty the MIME type using options.mimeType"}),L.Jpeg}function s6(W){if(D4({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"you're using options.type",resolution:"Remove options.type argument and migrate to options.mimeType which takes the real MIME type. If you're using type=longmp4, add options.longVideo alongside of mimeType=EUploadMimeType.Mp4"}),W==="gif")return L.Gif;if(W==="jpg")return L.Jpeg;if(W==="png")return L.Png;if(W==="webp")return L.Webp;if(W==="srt")return L.Srt;if(W==="mp4"||W==="longmp4")return L.Mp4;if(W==="mov")return L.Mov;return W}function G6(W,J){if(W===L.Mp4||W===L.Mov)return J==="tweet"?"TweetVideo":"DmVideo";if(W===L.Gif)return J==="tweet"?"TweetGif":"DmGif";if(W===L.Srt)return"Subtitles";else return J==="tweet"?"TweetImage":"DmImage"}function h4(W){return new Promise((J)=>setTimeout(J,W*1000))}async function g4(W,J,Z=0,$){if(W instanceof Buffer){let Q=W.slice(Z,Z+J);return[Q,Q.length]}if(!$)throw Error("Well, we will need a buffer to store file content.");let Y;if(typeof W==="number")Y=await new Promise((Q,G)=>{E.read(W,$,0,J,Z,(K,z)=>{if(K)G(K);Q(z)})});else Y=(await W.read($,0,J,Z)).bytesRead;return[$,Y]}var E4="media/upload.json";class J1 extends W1{constructor(){super(...arguments);this._prefix=A}get readOnly(){return this}tweet(W,J={}){let Z={status:W,tweet_mode:"extended",...J};return this.post("statuses/update.json",Z)}async quote(W,J,Z={}){let $="https://x.com/i/statuses/"+J;return this.tweet(W,{...Z,attachment_url:$})}async tweetThread(W){let J=[];for(let Z of W){let $=J.length?J[J.length-1]:null,Y={...typeof Z==="string"?{status:Z}:Z},Q=$?$.id_str:Y.in_reply_to_status_id,G=Y.status;if(Q)J.push(await this.reply(G,Q,Y));else J.push(await this.tweet(G,Y))}return J}reply(W,J,Z={}){return this.tweet(W,{auto_populate_reply_metadata:!0,in_reply_to_status_id:J,...Z})}deleteTweet(W){return this.post("statuses/destroy/:id.json",{tweet_mode:"extended"},{params:{id:W}})}reportUserAsSpam(W){return this.post("users/report_spam.json",{tweet_mode:"extended",...W})}updateFriendship(W){return this.post("friendships/update.json",W)}createFriendship(W){return this.post("friendships/create.json",W)}destroyFriendship(W){return this.post("friendships/destroy.json",W)}updateAccountSettings(W){return this.post("account/settings.json",W)}updateAccountProfile(W){return this.post("account/update_profile.json",W)}async updateAccountProfileBanner(W,J={}){let Z={banner:await y4(W),...J};return this.post("account/update_profile_banner.json",Z,{forceBodyMode:"form-data"})}async updateAccountProfileImage(W,J={}){let Z={tweet_mode:"extended",image:await y4(W),...J};return this.post("account/update_profile_image.json",Z,{forceBodyMode:"form-data"})}removeAccountProfileBanner(){return this.post("account/remove_profile_banner.json")}createList(W){return this.post("lists/create.json",{tweet_mode:"extended",...W})}updateList(W){return this.post("lists/update.json",{tweet_mode:"extended",...W})}removeList(W){return this.post("lists/destroy.json",{tweet_mode:"extended",...W})}addListMembers(W){let Z=W.user_id&&H1(W.user_id)||W.screen_name&&H1(W.screen_name)?"lists/members/create_all.json":"lists/members/create.json";return this.post(Z,W)}removeListMembers(W){let Z=W.user_id&&H1(W.user_id)||W.screen_name&&H1(W.screen_name)?"lists/members/destroy_all.json":"lists/members/destroy.json";return this.post(Z,W)}subscribeToList(W){return this.post("lists/subscribers/create.json",{tweet_mode:"extended",...W})}unsubscribeOfList(W){return this.post("lists/subscribers/destroy.json",{tweet_mode:"extended",...W})}createMediaMetadata(W,J){return this.post("media/metadata/create.json",{media_id:W,...J},{prefix:w,forceBodyMode:"json"})}createMediaSubtitles(W,J){return this.post("media/subtitles/create.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:J}},{prefix:w,forceBodyMode:"json"})}deleteMediaSubtitles(W,...J){return this.post("media/subtitles/delete.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:J.map((Z)=>({language_code:Z}))}},{prefix:w,forceBodyMode:"json"})}async uploadMedia(W,J={},Z=!1){var $;let Y=($=J.chunkLength)!==null&&$!==void 0?$:1048576,{fileHandle:Q,mediaCategory:G,fileSize:K,mimeType:z}=await this.getUploadMediaRequirements(W,J);try{let X=await this.post(E4,{command:"INIT",total_bytes:K,media_type:z,media_category:G,additional_owners:J.additionalOwners,shared:J.shared?!0:void 0},{prefix:w});await this.mediaChunkedUpload(Q,Y,X.media_id_string,J.maxConcurrentUploads);let B=await this.post(E4,{command:"FINALIZE",media_id:X.media_id_string},{prefix:w});if(B.processing_info&&B.processing_info.state!=="succeeded")await this.awaitForMediaProcessingCompletion(B);if(Z)return B;else return B.media_id_string}finally{if(typeof W==="number")m4.close(W,()=>{});else if(typeof Q==="object"&&!(Q instanceof Buffer))Q.close()}}async awaitForMediaProcessingCompletion(W){var J;while(!0){W=await this.mediaInfo(W.media_id_string);let{processing_info:Z}=W;if(!Z||Z.state==="succeeded")return;if((J=Z.error)===null||J===void 0?void 0:J.code){let{name:$,message:Y}=Z.error;throw Error(`Failed to process media: ${$} - ${Y}.`)}if(Z.state==="failed")throw Error("Failed to process the media.");if(Z.check_after_secs)await h4(Z.check_after_secs);else await h4(5)}}async getUploadMediaRequirements(W,{mimeType:J,type:Z,target:$,longVideo:Y}={}){let Q;try{Q=await A4(W);let G=Q6(W,Z,J),K;if(G===L.Mp4&&(!J&&!Z&&$!=="dm"||Y))K="amplify_video";else K=G6(G,$!==null&&$!==void 0?$:"tweet");return{fileHandle:Q,mediaCategory:K,fileSize:await Y6(Q),mimeType:G}}catch(G){if(typeof W==="number")m4.close(W,()=>{});else if(typeof Q==="object"&&!(Q instanceof Buffer))Q.close();throw G}}async mediaChunkedUpload(W,J,Z,$=3){let Y=0;if($<1)throw RangeError("Bad maxConcurrentUploads parameter.");let Q=W instanceof Buffer?void 0:Buffer.alloc(J),G,K,z=0;[G,K]=await g4(W,J,z,Q),z+=K;let X=new Set;while(K){let B=G.slice(0,K);if(B.length){let M=this.post(E4,{command:"APPEND",media_id:Z,segment_index:Y,media:B},{prefix:w});X.add(M),M.then(()=>{X.delete(M)}),Y++}if(X.size>=$)await Promise.race(X);[G,K]=await g4(W,J,z,Q),z+=K}await Promise.all([...X])}}class K6 extends J1{constructor(){super(...arguments);this._prefix=A}get readWrite(){return this}sendDm({recipient_id:W,custom_profile_id:J,...Z}){let $={event:{type:h.Create,[h.Create]:{target:{recipient_id:W},message_data:Z}}};if(J)$.event[h.Create].custom_profile_id=J;return this.post("direct_messages/events/new.json",$,{forceBodyMode:"json"})}getDmEvent(W){return this.get("direct_messages/events/show.json",{id:W})}deleteDm(W){return this.delete("direct_messages/events/destroy.json",{id:W})}async listDmEvents(W={}){let J={...W},Z=await this.get("direct_messages/events/list.json",J,{fullResponse:!0});return new N4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}newWelcomeDm(W,J){let Z={[h.WelcomeCreate]:{name:W,message_data:J}};return this.post("direct_messages/welcome_messages/new.json",Z,{forceBodyMode:"json"})}getWelcomeDm(W){return this.get("direct_messages/welcome_messages/show.json",{id:W})}deleteWelcomeDm(W){return this.delete("direct_messages/welcome_messages/destroy.json",{id:W})}updateWelcomeDm(W,J){let Z={message_data:J};return this.put("direct_messages/welcome_messages/update.json",Z,{forceBodyMode:"json",query:{id:W}})}async listWelcomeDms(W={}){let J={...W},Z=await this.get("direct_messages/welcome_messages/list.json",J,{fullResponse:!0});return new x4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}newWelcomeDmRule(W){return this.post("direct_messages/welcome_messages/rules/new.json",{welcome_message_rule:{welcome_message_id:W}},{forceBodyMode:"json"})}getWelcomeDmRule(W){return this.get("direct_messages/welcome_messages/rules/show.json",{id:W})}deleteWelcomeDmRule(W){return this.delete("direct_messages/welcome_messages/rules/destroy.json",{id:W})}async listWelcomeDmRules(W={}){let J={...W};return this.get("direct_messages/welcome_messages/rules/list.json",J)}async setWelcomeDm(W,J=!0){var Z;let $=await this.listWelcomeDmRules();if((Z=$.welcome_message_rules)===null||Z===void 0?void 0:Z.length){for(let Y of $.welcome_message_rules)if(await this.deleteWelcomeDmRule(Y.id),J)await this.deleteWelcomeDm(Y.welcome_message_id)}return this.newWelcomeDmRule(W)}markDmAsRead(W,J){return this.post("direct_messages/mark_read.json",{last_read_event_id:W,recipient_id:J},{forceBodyMode:"url"})}indicateDmTyping(W){return this.post("direct_messages/indicate_typing.json",{recipient_id:W},{forceBodyMode:"url"})}async downloadDmImage(W){if(typeof W!=="string"){let Z=W[h.Create].message_data.attachment;if(!Z)throw Error("The given direct message doesn't contain any attachment");W=Z.media.media_url_https}let J=await this.get(W,void 0,{forceParseMode:"buffer",prefix:""});if(!J.length)throw Error("Image not found. Make sure you are logged with credentials able to access direct messages, and check the URL.");return J}}var E1=K6;class x{constructor(W){this.result=W}get tweets(){return x.tweets(this.result)}static tweets(W){var J,Z;return(Z=(J=W.includes)===null||J===void 0?void 0:J.tweets)!==null&&Z!==void 0?Z:[]}tweetById(W){return x.tweetById(this.result,W)}static tweetById(W,J){return this.tweets(W).find((Z)=>Z.id===J)}retweet(W){return x.retweet(this.result,W)}static retweet(W,J){var Z;let $=((Z=J.referenced_tweets)!==null&&Z!==void 0?Z:[]).filter((Y)=>Y.type==="retweeted").map((Y)=>Y.id);return this.tweets(W).find((Y)=>$.includes(Y.id))}quote(W){return x.quote(this.result,W)}static quote(W,J){var Z;let $=((Z=J.referenced_tweets)!==null&&Z!==void 0?Z:[]).filter((Y)=>Y.type==="quoted").map((Y)=>Y.id);return this.tweets(W).find((Y)=>$.includes(Y.id))}repliedTo(W){return x.repliedTo(this.result,W)}static repliedTo(W,J){var Z;let $=((Z=J.referenced_tweets)!==null&&Z!==void 0?Z:[]).filter((Y)=>Y.type==="replied_to").map((Y)=>Y.id);return this.tweets(W).find((Y)=>$.includes(Y.id))}author(W){return x.author(this.result,W)}static author(W,J){let Z=J.author_id;return Z?this.users(W).find(($)=>$.id===Z):void 0}repliedToAuthor(W){return x.repliedToAuthor(this.result,W)}static repliedToAuthor(W,J){let Z=J.in_reply_to_user_id;return Z?this.users(W).find(($)=>$.id===Z):void 0}get users(){return x.users(this.result)}static users(W){var J,Z;return(Z=(J=W.includes)===null||J===void 0?void 0:J.users)!==null&&Z!==void 0?Z:[]}userById(W){return x.userById(this.result,W)}static userById(W,J){return this.users(W).find((Z)=>Z.id===J)}pinnedTweet(W){return x.pinnedTweet(this.result,W)}static pinnedTweet(W,J){return J.pinned_tweet_id?this.tweets(W).find((Z)=>Z.id===J.pinned_tweet_id):void 0}get media(){return x.media(this.result)}static media(W){var J,Z;return(Z=(J=W.includes)===null||J===void 0?void 0:J.media)!==null&&Z!==void 0?Z:[]}medias(W){return x.medias(this.result,W)}static medias(W,J){var Z,$;let Y=($=(Z=J.attachments)===null||Z===void 0?void 0:Z.media_keys)!==null&&$!==void 0?$:[];return this.media(W).filter((Q)=>Y.includes(Q.media_key))}get polls(){return x.polls(this.result)}static polls(W){var J,Z;return(Z=(J=W.includes)===null||J===void 0?void 0:J.polls)!==null&&Z!==void 0?Z:[]}poll(W){return x.poll(this.result,W)}static poll(W,J){var Z,$;let Y=($=(Z=J.attachments)===null||Z===void 0?void 0:Z.poll_ids)!==null&&$!==void 0?$:[];if(Y.length){let Q=Y[0];return this.polls(W).find((G)=>G.id===Q)}return}get places(){return x.places(this.result)}static places(W){var J,Z;return(Z=(J=W.includes)===null||J===void 0?void 0:J.places)!==null&&Z!==void 0?Z:[]}place(W){return x.place(this.result,W)}static place(W,J){var Z;let $=(Z=J.geo)===null||Z===void 0?void 0:Z.place_id;return $?this.places(W).find((Y)=>Y.id===$):void 0}listOwner(W){return x.listOwner(this.result,W)}static listOwner(W,J){let Z=J.owner_id;return Z?this.users(W).find(($)=>$.id===Z):void 0}spaceCreator(W){return x.spaceCreator(this.result,W)}static spaceCreator(W,J){let Z=J.creator_id;return Z?this.users(W).find(($)=>$.id===Z):void 0}spaceHosts(W){return x.spaceHosts(this.result,W)}static spaceHosts(W,J){var Z;let $=(Z=J.host_ids)!==null&&Z!==void 0?Z:[];return this.users(W).filter((Y)=>$.includes(Y.id))}spaceSpeakers(W){return x.spaceSpeakers(this.result,W)}static spaceSpeakers(W,J){var Z;let $=(Z=J.speaker_ids)!==null&&Z!==void 0?Z:[];return this.users(W).filter((Y)=>$.includes(Y.id))}spaceInvitedUsers(W){return x.spaceInvitedUsers(this.result,W)}static spaceInvitedUsers(W,J){var Z;let $=(Z=J.invited_user_ids)!==null&&Z!==void 0?Z:[];return this.users(W).filter((Y)=>$.includes(Y.id))}}class m1 extends j4{updateIncludes(W){if(W.errors){if(!this._realData.errors)this._realData.errors=[];this._realData.errors=[...this._realData.errors,...W.errors]}if(!W.includes)return;if(!this._realData.includes)this._realData.includes={};let J=this._realData.includes;for(let[Z,$]of Object.entries(W.includes)){if(!J[Z])J[Z]=[];J[Z]=[...J[Z],...$]}}assertUsable(){if(this.unusable)throw Error("Unable to use this paginator to fetch more data, as it does not contain any metadata. Check .errors property for more details.")}get meta(){return this._realData.meta}get includes(){var W;if(!((W=this._realData)===null||W===void 0?void 0:W.includes))return new x(this._realData);if(this._includesInstance)return this._includesInstance;return this._includesInstance=new x(this._realData)}get errors(){var W;return(W=this._realData.errors)!==null&&W!==void 0?W:[]}get unusable(){return this.errors.length>0&&!this._realData.meta&&!this._realData.data}}class T extends m1{refreshInstanceFromResult(W,J){var Z;let $=W.data,Y=(Z=$.data)!==null&&Z!==void 0?Z:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(J)this._realData.meta.result_count+=$.meta.result_count,this._realData.meta.next_token=$.meta.next_token,this._realData.data.push(...Y);else this._realData.meta.result_count+=$.meta.result_count,this._realData.meta.previous_token=$.meta.previous_token,this._realData.data.unshift(...Y);this.updateIncludes($)}getNextQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),pagination_token:this._realData.meta.next_token}}getPreviousQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),pagination_token:this._realData.meta.previous_token}}getPageLengthFromRequest(W){var J,Z;return(Z=(J=W.data.data)===null||J===void 0?void 0:J.length)!==null&&Z!==void 0?Z:0}isFetchLastOver(W){var J;return!((J=W.data.data)===null||J===void 0?void 0:J.length)||!this.canFetchNextPage(W.data)}canFetchNextPage(W){var J;return!!((J=W.meta)===null||J===void 0?void 0:J.next_token)}}class c4 extends m1{refreshInstanceFromResult(W,J){var Z;let $=W.data,Y=(Z=$.data)!==null&&Z!==void 0?Z:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(J)this._realData.meta.oldest_id=$.meta.oldest_id,this._realData.meta.result_count+=$.meta.result_count,this._realData.meta.next_token=$.meta.next_token,this._realData.data.push(...Y);else this._realData.meta.newest_id=$.meta.newest_id,this._realData.meta.result_count+=$.meta.result_count,this._realData.data.unshift(...Y);this.updateIncludes($)}getNextQueryParams(W){this.assertUsable();let J={...this.injectQueryParams(W)};if(this._realData.meta.next_token)J.next_token=this._realData.meta.next_token;else{if(J.start_time)J.since_id=this.dateStringToSnowflakeId(J.start_time),delete J.start_time;if(J.end_time)delete J.end_time;J.until_id=this._realData.meta.oldest_id}return J}getPreviousQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),since_id:this._realData.meta.newest_id}}getPageLengthFromRequest(W){var J,Z;return(Z=(J=W.data.data)===null||J===void 0?void 0:J.length)!==null&&Z!==void 0?Z:0}isFetchLastOver(W){var J;return!((J=W.data.data)===null||J===void 0?void 0:J.length)||!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!!W.meta.next_token}getItemArray(){return this.tweets}dateStringToSnowflakeId(W){let J=BigInt("1288834974657"),Z=new Date(W);if(isNaN(Z.valueOf()))throw Error("Unable to convert start_time/end_time to a valid date. A ISO 8601 DateTime is excepted, please check your input.");return(BigInt(Z.valueOf())-J<<BigInt("22")).toString()}get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class Z1 extends T{refreshInstanceFromResult(W,J){super.refreshInstanceFromResult(W,J);let Z=W.data;if(J)this._realData.meta.oldest_id=Z.meta.oldest_id;else this._realData.meta.newest_id=Z.meta.newest_id}getItemArray(){return this.tweets}get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class u4 extends c4{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class p4 extends c4{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class d4 extends Z1{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class l4 extends Z1{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class n4 extends Z1{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class i4 extends Z1{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class o4 extends Z1{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class s4 extends T{get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class a4 extends s4{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class t4 extends s4{constructor(){super(...arguments);this._endpoint="lists/:id/tweets"}}class V extends T{getItemArray(){return this.users}get users(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class r4 extends V{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class e4 extends V{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class W0 extends V{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class J0 extends V{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class Z0 extends V{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class $0 extends V{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class Y0 extends V{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class Q0 extends V{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class c1 extends T{getItemArray(){return this.lists}get lists(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class G0 extends c1{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class K0 extends c1{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class z0 extends c1{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class $1 extends f{constructor(){super(...arguments);this._prefix=o}}class u1 extends T{getItemArray(){return this.events}get events(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class X0 extends u1{constructor(){super(...arguments);this._endpoint="dm_events"}}class B0 extends u1{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class M0 extends u1{constructor(){super(...arguments);this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class Y1 extends f{constructor(){super(...arguments);this._prefix=y}get labs(){if(this._labs)return this._labs;return this._labs=new $1(this)}async search(W,J={}){let Z=typeof W==="string"?{...J,query:W}:{...W},$=await this.get("tweets/search/recent",Z,{fullResponse:!0});return new u4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async searchAll(W,J={}){let Z={...J,query:W},$=await this.get("tweets/search/all",Z,{fullResponse:!0});return new p4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}singleTweet(W,J={}){return this.get("tweets/:id",J,{params:{id:W}})}tweets(W,J={}){return this.get("tweets",{ids:W,...J})}tweetCountRecent(W,J={}){return this.get("tweets/counts/recent",{query:W,...J})}tweetCountAll(W,J={}){return this.get("tweets/counts/all",{query:W,...J})}async tweetRetweetedBy(W,J={}){let{asPaginator:Z,...$}=J,Y=await this.get("tweets/:id/retweeted_by",$,{fullResponse:!0,params:{id:W}});if(!Z)return Y.data;return new Q0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:$,sharedParams:{id:W}})}async tweetLikedBy(W,J={}){let{asPaginator:Z,...$}=J,Y=await this.get("tweets/:id/liking_users",$,{fullResponse:!0,params:{id:W}});if(!Z)return Y.data;return new Y0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:$,sharedParams:{id:W}})}async homeTimeline(W={}){let J=await this.getCurrentUserV2Object(),Z=await this.get("users/:id/timelines/reverse_chronological",W,{fullResponse:!0,params:{id:J.data.id}});return new l4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:W,sharedParams:{id:J.data.id}})}async userTimeline(W,J={}){let Z=await this.get("users/:id/tweets",J,{fullResponse:!0,params:{id:W}});return new n4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J,sharedParams:{id:W}})}async userMentionTimeline(W,J={}){let Z=await this.get("users/:id/mentions",J,{fullResponse:!0,params:{id:W}});return new i4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J,sharedParams:{id:W}})}async quotes(W,J={}){let Z=await this.get("tweets/:id/quote_tweets",J,{fullResponse:!0,params:{id:W}});return new d4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J,sharedParams:{id:W}})}async bookmarks(W={}){let J=await this.getCurrentUserV2Object(),Z=await this.get("users/:id/bookmarks",W,{fullResponse:!0,params:{id:J.data.id}});return new o4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:W,sharedParams:{id:J.data.id}})}me(W={}){return this.get("users/me",W)}user(W,J={}){return this.get("users/:id",J,{params:{id:W}})}users(W,J={}){let Z=Array.isArray(W)?W.join(","):W;return this.get("users",{...J,ids:Z})}userByUsername(W,J={}){return this.get("users/by/username/:username",J,{params:{username:W}})}usersByUsernames(W,J={}){return W=Array.isArray(W)?W.join(","):W,this.get("users/by",{...J,usernames:W})}async followers(W,J={}){let{asPaginator:Z,...$}=J,Y={id:W};if(!Z)return this.get("users/:id/followers",$,{params:Y});let Q=await this.get("users/:id/followers",$,{fullResponse:!0,params:Y});return new W0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$,sharedParams:Y})}async following(W,J={}){let{asPaginator:Z,...$}=J,Y={id:W};if(!Z)return this.get("users/:id/following",$,{params:Y});let Q=await this.get("users/:id/following",$,{fullResponse:!0,params:Y});return new J0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$,sharedParams:Y})}async userLikedTweets(W,J={}){let Z={id:W},$=await this.get("users/:id/liked_tweets",J,{fullResponse:!0,params:Z});return new a4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async userBlockingUsers(W,J={}){let Z={id:W},$=await this.get("users/:id/blocking",J,{fullResponse:!0,params:Z});return new r4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async userMutingUsers(W,J={}){let Z={id:W},$=await this.get("users/:id/muting",J,{fullResponse:!0,params:Z});return new e4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}list(W,J={}){return this.get("lists/:id",J,{params:{id:W}})}async listsOwned(W,J={}){let Z={id:W},$=await this.get("users/:id/owned_lists",J,{fullResponse:!0,params:Z});return new G0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async listMemberships(W,J={}){let Z={id:W},$=await this.get("users/:id/list_memberships",J,{fullResponse:!0,params:Z});return new K0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async listFollowed(W,J={}){let Z={id:W},$=await this.get("users/:id/followed_lists",J,{fullResponse:!0,params:Z});return new z0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async listTweets(W,J={}){let Z={id:W},$=await this.get("lists/:id/tweets",J,{fullResponse:!0,params:Z});return new t4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async listMembers(W,J={}){let Z={id:W},$=await this.get("lists/:id/members",J,{fullResponse:!0,params:Z});return new Z0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async listFollowers(W,J={}){let Z={id:W},$=await this.get("lists/:id/followers",J,{fullResponse:!0,params:Z});return new $0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async listDmEvents(W={}){let J=await this.get("dm_events",W,{fullResponse:!0});return new X0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...W}})}async listDmEventsWithParticipant(W,J={}){let Z={participant_id:W},$=await this.get("dm_conversations/with/:participant_id/dm_events",J,{fullResponse:!0,params:Z});return new B0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async listDmEventsOfConversation(W,J={}){let Z={dm_conversation_id:W},$=await this.get("dm_conversations/:dm_conversation_id/dm_events",J,{fullResponse:!0,params:Z});return new M0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}space(W,J={}){return this.get("spaces/:id",J,{params:{id:W}})}spaces(W,J={}){return this.get("spaces",{ids:W,...J})}spacesByCreators(W,J={}){return this.get("spaces/by/creator_ids",{user_ids:W,...J})}searchSpaces(W){return this.get("spaces/search",W)}spaceBuyers(W,J={}){return this.get("spaces/:id/buyers",J,{params:{id:W}})}spaceTweets(W,J={}){return this.get("spaces/:id/tweets",J,{params:{id:W}})}searchStream({autoConnect:W,...J}={}){return this.getStream("tweets/search/stream",J,{payloadIsError:w1,autoConnect:W})}streamRules(W={}){return this.get("tweets/search/stream/rules",W)}updateStreamRules(W,J={}){return this.post("tweets/search/stream/rules",W,{query:J})}sampleStream({autoConnect:W,...J}={}){return this.getStream("tweets/sample/stream",J,{payloadIsError:w1,autoConnect:W})}sample10Stream({autoConnect:W,...J}={}){return this.getStream("tweets/sample10/stream",J,{payloadIsError:w1,autoConnect:W})}complianceJobs(W){return this.get("compliance/jobs",W)}complianceJob(W){return this.get("compliance/jobs/:id",void 0,{params:{id:W}})}async sendComplianceJob(W){let J=await this.post("compliance/jobs",{type:W.type,name:W.name}),Z=W.ids instanceof Buffer?W.ids:Buffer.from(W.ids.join(`
|
|
64
|
+
</html>`}function _0(W){return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Authorization failed</title></head><body style="font-family: system-ui, sans-serif; padding: 24px"><h1 style="font-size: 1.2rem">This connection could not be authorized</h1><p>${_(W)}</p></body></html>`}function _(W){return W.replace(/[&<>"']/g,(J)=>`&#${J.charCodeAt(0)};`)}var r1="gmcp_at_",e1="gmcp_rt_",k0="gmcp_ac_",k6="gmcp_c_",C6="gmcp_cs_",W4="gemi.mcp.oauth.ticket.v1",C0="gemi.mcp.oauth.consent.v1",I6=600000,I0=120000,G4=16384,b6={limit:20,window:3600},T6={limit:60,window:60},C1=["none","client_secret_post","client_secret_basic"];class N extends Error{error;description;status;headers;constructor(W,J,Z=400,$={}){super(J);this.error=W;this.description=J;this.status=Z;this.headers=$}}class h0{options;name="oauth";context;issuer;base;accessTtl;refreshTtl;constructor(W){this.options=W;let J=W?.store;for(let Z of["createClient","findClient","saveCode","findCode","saveToken","findToken","use","revokeFamily"])if(typeof J?.[Z]!=="function")throw Error(`McpOAuthServer: store.${Z} is missing. Use MemoryMcpOAuthStore, or implement McpOAuthStore.`);if(typeof W.findUser!=="function")throw Error("McpOAuthServer: findUser(id) is required: it loads the user a token was issued to.");if(W.consentPath!==void 0&&!/^\/[^/\\]/.test(W.consentPath))throw Error('McpOAuthServer: consentPath must be a path on this app, like "/oauth/consent".');this.accessTtl=b0("accessTokenTtl",W.accessTokenTtl,3600),this.refreshTtl=b0("refreshTokenTtl",W.refreshTokenTtl,2592000)}get store(){return this.options.store}boot(W){this.context=W;let J=new URL(W.resource);this.issuer=J.origin,this.base=`${J.pathname}/oauth`}async resolve(W){let J=z4(W);if(!J?.startsWith(r1))return null;let Z=await this.store.findToken(P(J)),$=(Y)=>({ok:!1,error:"invalid_token",description:Y});if(!Z||Z.kind!=="access")return $("The access token is not valid.");if(Z.expiresAt<=Date.now())return $("The access token expired.");if(Z.resource!==this.context.resource)return $("The access token was not issued for this server.");let Q=await this.options.findUser(Z.userId);if(!Q)return $("The access token is not valid.");return{ok:!0,principal:{user:Q,via:this.name,id:Z.familyId,scopes:Z.scopes,clientId:Z.clientId}}}challenge(){let W=this.scopeNames().join(" ");return`Bearer resource_metadata="${this.resourceMetadataUrl()}", scope="${W}"`}async handle(W){let J=new URL(W.url).pathname,Q={[`/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-protected-resource"]:{methods:["GET"],cors:!0,run:()=>this.resourceMetadata()},["/.well-known/oauth-authorization-server"]:{methods:["GET"],cors:!0,run:()=>this.serverMetadata()},[`${this.base}/register`]:{methods:["POST"],cors:!0,run:()=>this.register(W)},[`${this.base}/authorize`]:{methods:["GET"],cors:!1,run:()=>this.authorize(W)},[`${this.base}/consent`]:{methods:["GET","POST"],cors:!1,run:()=>W.method==="POST"?this.decide(W):this.consentScreen(W)},[`${this.base}/token`]:{methods:["POST"],cors:!0,run:()=>this.token(W)},[`${this.base}/revoke`]:{methods:["POST"],cors:!0,run:()=>this.revoke(W)}}[J];if(!Q)return null;if(J===`${this.base}/register`&&this.options.registration===!1)return null;let Y=Q.cors?v6:{};if(W.method==="OPTIONS"&&Q.cors)return new Response(null,{status:204,headers:{...Y,"Access-Control-Allow-Methods":Q.methods.join(", "),"Access-Control-Allow-Headers":"Authorization, Content-Type, MCP-Protocol-Version","Access-Control-Max-Age":"600"}});if(!Q.methods.includes(W.method))return new Response(null,{status:405,headers:{...Y,Allow:Q.methods.join(", ")}});let G;try{G=await Q.run()}catch(K){if(!(K instanceof N))throw K;G=X1({error:K.error,error_description:K.description},K.status,K.headers)}for(let[K,z]of Object.entries(Y))G.headers.set(K,z);return G}async consent(W,J){if(!J)return null;let Z=I1(W4,"gat1",W);if(!Z)return null;let $=await this.store.findClient(Z.c);if(!$||!$.redirectUris.some((K)=>Z4(K,Z.r)))return null;let Q=String(J.id),Y=Y4(C0,"gcs1",{t:T0(W),u:Q,exp:Z.exp}),G=new Map(this.context.registry.scopes().map((K)=>[K.name,K.description]));return{client:{id:$.clientId,name:$.clientName,redirectHost:new URL(Z.r).host},scopes:Z.s.map((K)=>({name:K,description:G.get(K)??K})),user:{id:Q,label:this.userLabel(J)},form:{action:`${this.issuer}${this.base}/consent`,method:"POST",fields:{request:W,csrf:Y}}}}resourceMetadata(){return X1({resource:this.context.resource,authorization_servers:[this.issuer],scopes_supported:this.scopeNames(),bearer_methods_supported:["header"]})}serverMetadata(){return X1({issuer:this.issuer,authorization_endpoint:`${this.issuer}${this.base}/authorize`,token_endpoint:`${this.issuer}${this.base}/token`,...this.options.registration===!1?{}:{registration_endpoint:`${this.issuer}${this.base}/register`},revocation_endpoint:`${this.issuer}${this.base}/revoke`,scopes_supported:this.scopeNames(),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],token_endpoint_auth_methods_supported:C1,revocation_endpoint_auth_methods_supported:C1,code_challenge_methods_supported:["S256"],authorization_response_iss_parameter_supported:!0,client_id_metadata_document_supported:!1})}async register(W){let J=this.options.registration||{},Z=await Q4(`mcp-oauth-register:${y0(new $4(W,{},"api",`${this.base}/register`))}`,J.rateLimit??b6);if(Z!==null)throw new N("slow_down","Too many registrations from this address.",429,{"Retry-After":String(Z)});if(!/^application\/json\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new N("invalid_client_metadata","Send the client metadata as application/json.");let $;try{$=JSON.parse(await K4(W,G4))}catch{throw new N("invalid_client_metadata","The client metadata is not JSON, or is too large.")}if(typeof $!=="object"||$===null||Array.isArray($))throw new N("invalid_client_metadata","The client metadata must be a JSON object.");let Q=$.redirect_uris;if(!Array.isArray(Q)||Q.length===0||Q.length>10)throw new N("invalid_redirect_uri","redirect_uris must list one to ten URIs.");for(let D of Q){let S=V6(D);if(S)throw new N("invalid_redirect_uri",`${String(D).slice(0,200)}: ${S}`);if(J.allowRedirectUri&&J.allowRedirectUri(new URL(D))!==!0)throw new N("invalid_redirect_uri",`${D}: this server does not accept it.`)}let Y=$.token_endpoint_auth_method??"client_secret_basic";if(!C1.includes(Y))throw new N("invalid_client_metadata",`token_endpoint_auth_method must be one of ${C1.join(", ")}.`);let G=$.grant_types??["authorization_code"];if(!Array.isArray(G)||G.some((D)=>D!=="authorization_code"&&D!=="refresh_token"))throw new N("invalid_client_metadata","grant_types may only be authorization_code and refresh_token.");let K=$.response_types??["code"];if(!Array.isArray(K)||K.some((D)=>D!=="code"))throw new N("invalid_client_metadata","response_types may only be code.");let z=w0($.client_name,100,"client_name"),X=w0($.client_uri,512,"client_uri");if(X!==null&&!w6(X))throw new N("invalid_client_metadata","client_uri must be an https URL.");let B=Y==="none"?null:`${C6}${u(32).toString("base64url")}`,M={clientId:`${k6}${u(16).toString("base64url")}`,clientSecretHash:B?P(B):null,tokenEndpointAuthMethod:Y,redirectUris:[...Q],clientName:z,clientUri:X,createdAt:Date.now()};return await this.store.createClient(M),X1({client_id:M.clientId,client_id_issued_at:Math.floor(M.createdAt/1000),...B?{client_secret:B,client_secret_expires_at:0}:{},redirect_uris:M.redirectUris,token_endpoint_auth_method:Y,grant_types:G,response_types:K,...z?{client_name:z}:{},...X?{client_uri:X}:{}},201)}async authorize(W){let J=new URL(W.url).searchParams;for(let H of new Set(J.keys()))if(J.getAll(H).length>1)return b(`The parameter ${H} was sent more than once.`);let Z=J.get("client_id"),$=Z?await this.store.findClient(Z):null;if(!$)return b("The application is not registered with this server.");let Q=J.get("redirect_uri")??($.redirectUris.length===1?$.redirectUris[0]:null);if(!Q||!$.redirectUris.some((H)=>Z4(H,Q)))return b("The redirect URI is not one the application registered.");let Y=J.get("state"),G=(H,m)=>this.redirectBack(Q,Y,{error:H,error_description:m});if(J.get("response_type")!=="code")return G("unsupported_response_type","Only response_type=code is supported.");let K=J.get("code_challenge");if(J.get("code_challenge_method")!=="S256"||!K||!/^[A-Za-z0-9_-]{43}$/.test(K))return G("invalid_request","PKCE is required: code_challenge with code_challenge_method=S256.");let z=J.get("resource");if(z!==null&&!V0(z,this.context.resource))return G("invalid_target","The resource is not this server's.");if(Y!==null&&Y.length>2048)return G("invalid_request","state is too long.");let X=this.scopeNames(),B=J.get("scope"),M=X;if(B!==null&&B.trim()!==""){if(M=[...new Set(B.split(" ").filter((H)=>X.includes(H)))],M.length===0)return G("invalid_scope","None of the requested scopes exist here.")}let D=Y4(W4,"gat1",{c:$.clientId,r:Q,s:M,cc:K,st:Y,n:u(16).toString("base64url"),exp:Date.now()+I6}),S=this.options.consentPath??`${this.base}/consent`;return J4(`${this.issuer}${S}?request=${encodeURIComponent(D)}`,302)}async consentScreen(W){let J=new URL(W.url).searchParams.get("request"),Z=await this.sessionUser(W);if(!Z){let Q=`${this.base}/consent?request=${encodeURIComponent(J??"")}`,Y=this.options.signInPath??v(b1).config.signInPath;return J4(`${Y}${Y.includes("?")?"&":"?"}redirect=${encodeURIComponent(Q)}`,302)}let $=await this.consent(J,Z);if(!$)return b("This authorization request has expired or is not valid. Start again from the application.");return new Response(f0($,{name:this.options.appName??new URL(this.issuer).host}),{status:200,headers:k1})}async decide(W){let J=W.headers.get("origin");if(!(J!==null?J===this.issuer:W.headers.get("sec-fetch-site")==="same-origin"))return b("This decision did not come from this site's consent page.",403);if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))return b("The decision must be a form post.");let $;try{$=new URLSearchParams(await K4(W,G4))}catch{return b("The decision is too large.")}let Q=$.get("request"),Y=I1(W4,"gat1",Q),G=I1(C0,"gcs1",$.get("csrf")),K=await this.sessionUser(W);if(!Y||!G||!K||G.t!==T0(Q)||G.u!==String(K.id))return b("This authorization request has expired or is not valid. Start again from the application.",403);let z=await this.store.findClient(Y.c);if(!z||!z.redirectUris.some((B)=>Z4(B,Y.r)))return b("The application is not registered with this server.");if(!await this.store.use(`ticket:${Y.n}`,Y.exp))return b("This request was already answered. Start again from the application.");if($.get("decision")!=="allow")return this.redirectBack(Y.r,Y.st,{error:"access_denied",error_description:"The user denied the request."},303);let X=`${k0}${u(32).toString("base64url")}`;return await this.store.saveCode({hash:P(X),clientId:z.clientId,userId:String(K.id),redirectUri:Y.r,codeChallenge:Y.cc,scopes:Y.s,resource:this.context.resource,familyId:u(16).toString("base64url"),expiresAt:Date.now()+I0}),this.redirectBack(Y.r,Y.st,{code:X},303)}async token(W){let J=await P0(W),Z=await this.authenticateClient(W,J),$=await Q4(`mcp-oauth-token:${Z.clientId}`,T6);if($!==null)throw new N("slow_down","Too many token requests.",429,{"Retry-After":String($)});let Q=J.get("resource");if(Q!==null&&!V0(Q,this.context.resource))throw new N("invalid_target","The resource is not this server's.");switch(J.get("grant_type")){case"authorization_code":{let Y=J.get("code")??"",G=Y.startsWith(k0)?await this.store.findCode(P(Y)):null;if(!G||G.clientId!==Z.clientId)throw new N("invalid_grant","The authorization code is not valid.");if(!await this.store.use(G.hash,G.expiresAt+I0))throw await this.store.revokeFamily(G.familyId),new N("invalid_grant","The authorization code was already used.");if(G.expiresAt<=Date.now())throw new N("invalid_grant","The authorization code expired.");if(J.get("redirect_uri")!==null&&J.get("redirect_uri")!==G.redirectUri)throw new N("invalid_grant","redirect_uri is not the one the code was issued to.");let K=J.get("code_verifier");if(!K||!/^[A-Za-z0-9._~-]{43,128}$/.test(K)||!v0(P6(K),G.codeChallenge))throw new N("invalid_grant","The PKCE code_verifier does not match.");if(!await this.options.findUser(G.userId))throw new N("invalid_grant","The authorization code is not valid.");return await this.issue(G)}case"refresh_token":{let Y=J.get("refresh_token")??"",G=Y.startsWith(e1)?await this.store.findToken(P(Y)):null;if(!G||G.kind!=="refresh"||G.clientId!==Z.clientId)throw new N("invalid_grant","The refresh token is not valid.");if(G.expiresAt<=Date.now())throw new N("invalid_grant","The refresh token expired.");if(!await this.store.use(G.hash,G.expiresAt))throw await this.store.revokeFamily(G.familyId),new N("invalid_grant","The refresh token was already used.");if(G.resource!==this.context.resource)throw new N("invalid_grant","The refresh token was not issued for this server.");let K=G.scopes,z=J.get("scope");if(z!==null&&z.trim()!==""){let X=[...new Set(z.split(" ").filter(Boolean))];if(X.some((B)=>!G.scopes.includes(B)))throw new N("invalid_scope","A refresh can only narrow the scopes that were granted.");K=X}if(!await this.options.findUser(G.userId))throw new N("invalid_grant","The refresh token is not valid.");return await this.issue({...G,scopes:K})}default:throw new N("unsupported_grant_type","grant_type must be authorization_code or refresh_token.")}}async issue(W){let J=Date.now(),Z=this.scopeNames(),$=W.scopes.filter((K)=>Z.includes(K)),Q=`${r1}${u(32).toString("base64url")}`,Y=`${e1}${u(32).toString("base64url")}`,G={clientId:W.clientId,userId:W.userId,scopes:$,resource:W.resource,familyId:W.familyId};return await this.store.saveToken({...G,hash:P(Q),kind:"access",expiresAt:J+this.accessTtl*1000}),await this.store.saveToken({...G,hash:P(Y),kind:"refresh",expiresAt:J+this.refreshTtl*1000}),X1({access_token:Q,token_type:"Bearer",expires_in:this.accessTtl,refresh_token:Y,scope:$.join(" ")})}async revoke(W){let J=await P0(W),Z=await this.authenticateClient(W,J),$=J.get("token")??"";if($.startsWith(r1)||$.startsWith(e1)){let Q=await this.store.findToken(P($));if(Q&&Q.clientId===Z.clientId)await this.store.revokeFamily(Q.familyId)}return new Response(null,{status:200,headers:{"Cache-Control":"no-store"}})}async authenticateClient(W,J){let Z=/^Basic\s+([A-Za-z0-9+/=]+)$/i.exec(W.headers.get("authorization")??""),$=J.get("client_id"),Q=J.get("client_secret");if(Z){let G=Buffer.from(Z[1],"base64").toString("utf8"),K=G.indexOf(":");if(K<0)throw d(!0);let z=q0(G.slice(0,K));if(z===null)throw d(!0);if($!==null&&$!==z)throw d(!0);if($=z,Q=q0(G.slice(K+1)),Q===null)throw d(!0)}let Y=$?await this.store.findClient($):null;if(!Y)throw d(Boolean(Z));if(Y.tokenEndpointAuthMethod==="none"){if(Q)throw d(Boolean(Z));return Y}if(!Q||!Y.clientSecretHash||!v0(P(Q),Y.clientSecretHash))throw d(Boolean(Z));return Y}redirectBack(W,J,Z,$=302){let Q=new URL(W);for(let[Y,G]of Object.entries(Z))Q.searchParams.set(Y,G);if(J!==null)Q.searchParams.set("state",J);return Q.searchParams.set("iss",this.issuer),J4(Q.href,$)}async sessionUser(W){let J=new $4(W,{},"api",this.base).cookies;return await A0(v(b1),{cookies:J,headers:{get:(Z)=>Z.toLowerCase()==="user-agent"?W.headers.get("user-agent"):null}})}userLabel(W){if(this.options.userLabel)return this.options.userLabel(W);let J=W;return String(J.email??J.name??J.id)}scopeNames(){return this.context.registry.scopes().map((W)=>W.name)}resourceMetadataUrl(){return`${this.issuer}/.well-known/oauth-protected-resource${new URL(this.context.resource).pathname}`}}var v6={"Access-Control-Allow-Origin":"*","Access-Control-Expose-Headers":"WWW-Authenticate"};function b0(W,J,Z){if(J===void 0)return Z;if(!Number.isInteger(J)||J<60)throw Error(`McpOAuthServer: ${W} must be a whole number of seconds, at least 60.`);return J}function P(W){return X4("sha256").update(W).digest("hex")}function T0(W){return X4("sha256").update(W).digest("base64url")}function P6(W){return X4("sha256").update(W).digest("base64url")}function v0(W,J){let Z=Buffer.from(W),$=Buffer.from(J);return Z.length===$.length&&_6(Z,$)}function X1(W,J=200,Z={}){return new Response(JSON.stringify(W),{status:J,headers:{"Content-Type":"application/json","Cache-Control":"no-store",Pragma:"no-cache",...Z}})}function J4(W,J){return new Response(null,{status:J,headers:{Location:W,"Cache-Control":"no-store","Referrer-Policy":"no-referrer"}})}function b(W,J=400){return new Response(_0(W),{status:J,headers:k1})}function d(W){return new N("invalid_client","Client authentication failed.",401,W?{"WWW-Authenticate":'Basic realm="mcp-oauth"'}:{})}async function K4(W,J){let Z=Number(W.headers.get("content-length"));if(Number.isFinite(Z)&&Z>J)throw Error("too large");if(!W.body)return"";let $=W.body.getReader(),Q=[],Y=0;for(;;){let{done:G,value:K}=await $.read();if(G)break;if(Y+=K.byteLength,Y>J)throw await $.cancel(),Error("too large");Q.push(K)}return Buffer.concat(Q).toString("utf8")}async function P0(W){if(!/^application\/x-www-form-urlencoded\s*(;|$)/i.test(W.headers.get("content-type")??""))throw new N("invalid_request","Send the request as application/x-www-form-urlencoded.");let J;try{J=new URLSearchParams(await K4(W,G4))}catch{throw new N("invalid_request","The request is too large.")}for(let Z of new Set(J.keys()))if(J.getAll(Z).length>1)throw new N("invalid_request",`${Z} was sent more than once.`);return J}function w0(W,J,Z){if(W===void 0||W===null||W==="")return null;if(typeof W!=="string"||W.length>J||q6(W))throw new N("invalid_client_metadata",`${Z} must be text of at most ${J} characters.`);return W}function w6(W){try{return new URL(W).protocol==="https:"}catch{return!1}}function g0(W){return W.hostname==="localhost"||W.hostname==="127.0.0.1"||W.hostname==="[::1]"}function V6(W){if(typeof W!=="string"||W.length>2048)return"not a URI";let J;try{J=new URL(W)}catch{return"not an absolute URI"}if(J.hash||W.includes("#"))return"must not have a fragment";if(J.username||J.password)return"must not carry credentials";if(J.protocol==="https:")return null;if(J.protocol==="http:"&&g0(J))return null;return"must be https, or http on a loopback address"}function Z4(W,J){if(W===J)return!0;let Z,$;try{Z=new URL(W),$=new URL(J)}catch{return!1}return Z.protocol==="http:"&&$.protocol==="http:"&&g0(Z)&&Z.hostname===$.hostname&&Z.pathname===$.pathname&&Z.search===$.search&&!$.hash&&!$.username&&!$.password}function V0(W,J){return W===J||W===`${J}/`}function q6(W){for(let J=0;J<W.length;J++){let Z=W.charCodeAt(J);if(Z<32||Z===127)return!0}return!1}function q0(W){try{return decodeURIComponent(W.replace(/\+/g," "))}catch{return null}}class E0{clients=new Map;codes=new Map;tokens=new Map;used=new Map;revoked=new Set;async createClient(W){this.clients.set(W.clientId,structuredClone(W))}async findClient(W){let J=this.clients.get(W);return J?structuredClone(J):null}async saveCode(W){this.sweep(),this.codes.set(W.hash,structuredClone(W))}async findCode(W){let J=this.codes.get(W);return J&&!this.revoked.has(J.familyId)?structuredClone(J):null}async saveToken(W){this.sweep(),this.tokens.set(W.hash,structuredClone(W))}async findToken(W){let J=this.tokens.get(W);return J&&!this.revoked.has(J.familyId)?structuredClone(J):null}async use(W,J){if(this.used.has(W))return!1;return this.used.set(W,J),!0}async revokeFamily(W){this.revoked.add(W);for(let[J,Z]of this.tokens)if(Z.familyId===W)this.tokens.delete(J);for(let[J,Z]of this.codes)if(Z.familyId===W)this.codes.delete(J)}async families(W){let J=new Map;for(let Z of this.tokens.values())if(Z.userId===W&&!this.revoked.has(Z.familyId)&&Z.expiresAt>Date.now())J.set(Z.familyId,{familyId:Z.familyId,clientId:Z.clientId,scopes:[...Z.scopes]});return[...J.values()]}sweep(W=Date.now()){for(let[J,Z]of this.codes)if(Z.expiresAt<=W)this.codes.delete(J);for(let[J,Z]of this.tokens)if(Z.expiresAt<=W)this.tokens.delete(J);for(let[J,Z]of this.used)if(Z<=W)this.used.delete(J)}}class M1 extends k{application;previous;dispatched=[];static install(W){let J=W.resolved(k)?W.make(k):void 0;if(J instanceof M1)return J;let Z=new M1(W,J);return W.instance(k,Z),Z}constructor(W,J){super({listeners:[]});this.application=W;this.previous=J}dispatch(W,J){this.dispatched.push({event:W,args:J})}async dispatchAndWait(W,J){this.dispatched.push({event:W,args:J})}restore(){if(this.previous){this.application.instance(k,this.previous);return}this.application.forget(k)}assertDispatched(W,J){let Z=B1(W);if(this.matching(Z,J).length>0)return;throw Error(`Expected ${Z}${J?" matching the predicate":""} to have been dispatched. ${this.summary(Z,J!==void 0)}`)}assertNotDispatched(W,J){let Z=B1(W),$=this.matching(Z,J);if($.length===0)return;throw Error(`Expected ${Z}${J?" matching the predicate":""} not to have been dispatched, but it was dispatched ${B4($.length)}: ${T1($)}.`)}assertDispatchedTimes(W,J,Z){let $=B1(W),Q=this.matching($,Z);if(Q.length===J)return;throw Error(`Expected ${$}${Z?" matching the predicate":""} to have been dispatched ${B4(J)}, but it was dispatched ${B4(Q.length)}. ${this.summary($,Z!==void 0)}`)}assertNothingDispatched(){if(this.dispatched.length===0)return;let W=this.dispatched.length;throw Error(`Expected nothing to have been dispatched, but ${W} ${W===1?"event was":"events were"}: ${T1(this.dispatched)}.`)}matching(W,J){return this.dispatched.filter((Z)=>B1(Z.event.constructor)===W&&(J===void 0||J(Z.event)))}summary(W,J){if(this.dispatched.length===0)return"Nothing was dispatched.";let Z=this.matching(W);if(J&&Z.length>0)return`Dispatched ${W}: ${T1(Z)}.`;return`Dispatched: ${T1(this.dispatched)}.`}}function B1(W){return W.name}function B4(W){return`${W} ${W===1?"time":"times"}`}function T1(W){return W.map(y6).join(", ")}function y6(W){let J=B1(W.event.constructor),Z=W.args??Object.values({...W.event});return`${J}(${Z.map(A6).join(", ")})`}function A6(W){try{return JSON.stringify(W)??String(W)}catch{return String(W)}}class c0{static name="unset";static afterCommit=!1;static dispatch(...W){m0(this),v(k).dispatch(new this(...W),W)}static dispatchAndWait(...W){return m0(this),v(k).dispatchAndWait(new this(...W),W)}static fake(){return M1.install(h6())}}function h6(){try{return v()}catch(W){throw Error("Event.fake() needs a booted application. The fake works by replacing the container's EventManager with a recorder, so there has to be a "+"container to replace it in \u2014 and a dispatch finds the recorder the "+"same way, by resolving from that container. Boot the app's kernel in the test's setup: `const kernel = new Kernel(); kernel.boot()` is enough on its own, since that is the phase that publishes the application every dispatch outside a request resolves through.",{cause:W})}}function m0(W){if(W.name!=="unset"&&W.name!=="")return;throw Error("Cannot dispatch an event with no name. Add `static name` to this Event "+"subclass \u2014 the listener registry is keyed by that string, and by that "+"string alone, so an event without one cannot reach a listener.")}var g6={clientId:process.env.GOOGLE_CLIENT_ID,clientSecret:process.env.GOOGLE_CLIENT_SECRET,redirectPath:"/auth/oauth/google/callback",scope:"https://www.googleapis.com/auth/userinfo.profile https://www.googleapis.com/auth/userinfo.email",authorizationParams:{}};function E6(W,J){return typeof W==="string"&&/^[a-z0-9_]{1,64}$/.test(W)?W:J}class u0 extends j1{config;constructor(W={}){super();this.config={...g6,...W}}redirectUri(){return`${process.env.HOST_NAME??""}${this.config.redirectPath}`}getRedirectUrl(W,J){let Z=new URL("https://accounts.google.com/o/oauth2/v2/auth"),$={include_granted_scopes:"true",...this.config.authorizationParams,scope:this.config.scope,response_type:"code",redirect_uri:this.redirectUri(),client_id:this.config.clientId};if(J)$.state=J.state,$.code_challenge=J.codeChallenge,$.code_challenge_method=J.codeChallengeMethod;for(let[Q,Y]of Object.entries($))Z.searchParams.set(Q,Y);return Z.toString()}async onCallback(W,J){let Z=W.search.get("code");if(!Z)throw new q("missing_code");let $=new URLSearchParams({code:Z,client_id:this.config.clientId,client_secret:this.config.clientSecret,grant_type:"authorization_code",redirect_uri:this.redirectUri()});if(J?.codeVerifier)$.set("code_verifier",J.codeVerifier);let Q=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:$.toString()}),Y=await Q.json().catch(()=>({}));if(!Q.ok||typeof Y?.access_token!=="string"||Y.access_token==="")throw console.error("Google OAuth error: token exchange failed",Y?.error??Q.status),new q(E6(Y?.error,"exchange_failed"));let K=await(await fetch("https://www.googleapis.com/oauth2/v3/userinfo",{headers:{Authorization:`Bearer ${Y.access_token}`}})).json().catch(()=>({}));if(typeof K.sub!=="string"||K.sub==="")return console.error("Google OAuth error: sub not found in user info response",K),{};if(!K.email)console.error("Google OAuth error: email not found in user info response",K);return{providerId:K.sub,name:K.name,email:K.email,emailVerified:K.email_verified===!0||K.email_verified==="true"}}}var y="https://api.x.com/2/",o="https://api.x.com/labs/2/",A="https://api.x.com/1.1/",w="https://upload.x.com/1.1/",d0="https://stream.x.com/1.1/",s="https://ads-api.x.com/12/",a="https://ads-api-sandbox.twitter.com/12/";class M4{constructor({realData:W,rateLimit:J,instance:Z,queryParams:$,sharedParams:Q}){this._maxResultsWhenFetchLast=100,this._realData=W,this._rateLimit=J,this._instance=Z,this._queryParams=$,this._sharedParams=Q}get _isRateLimitOk(){if(!this._rateLimit)return!0;if(this._rateLimit.reset*1000<Date.now())return!0;return this._rateLimit.remaining>0}makeRequest(W){return this._instance.get(this.getEndpoint(),W,{fullResponse:!0,params:this._sharedParams})}makeNewInstanceFromResult(W,J){return new this.constructor({realData:W.data,rateLimit:W.rateLimit,instance:this._instance,queryParams:J,sharedParams:this._sharedParams})}getEndpoint(){return this._endpoint}injectQueryParams(W){return{...W?{max_results:W}:{},...this._queryParams}}async next(W){let J=this.getNextQueryParams(W),Z=await this.makeRequest(J);return this.makeNewInstanceFromResult(Z,J)}async fetchNext(W){let J=this.getNextQueryParams(W),Z=await this.makeRequest(J);return await this.refreshInstanceFromResult(Z,!0),this}async fetchLast(W=1/0){let J=this.getNextQueryParams(this._maxResultsWhenFetchLast),Z=0;while(Z<W&&this._isRateLimitOk){let $=await this.makeRequest(J);if(await this.refreshInstanceFromResult($,!0),Z+=this.getPageLengthFromRequest($),this.isFetchLastOver($))break;J=this.getNextQueryParams(this._maxResultsWhenFetchLast)}return this}get rateLimit(){var W;return{...(W=this._rateLimit)!==null&&W!==void 0?W:{}}}get data(){return this._realData}get done(){return!this.canFetchNextPage(this._realData)}*[Symbol.iterator](){yield*this.getItemArray()}async*[Symbol.asyncIterator](){yield*this.getItemArray();let W=this,J=this.canFetchNextPage(this._realData);while(J&&this._isRateLimitOk&&W.getItemArray().length>0){let Z=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:Z._realData,headers:{},rateLimit:Z._rateLimit},!0),J=this.canFetchNextPage(Z._realData),yield*Z.getItemArray(),W=Z}}async*fetchAndIterate(){for(let Z of this.getItemArray())yield[Z,this];let W=this,J=this.canFetchNextPage(this._realData);while(J&&this._isRateLimitOk&&W.getItemArray().length>0){let Z=await W.next(this._maxResultsWhenFetchLast);this.refreshInstanceFromResult({data:Z._realData,headers:{},rateLimit:Z._rateLimit},!0),J=this.canFetchNextPage(Z._realData);for(let $ of Z.getItemArray())yield[$,Z];this._rateLimit=Z._rateLimit,W=Z}}}class j4 extends M4{async previous(W){let J=this.getPreviousQueryParams(W),Z=await this.makeRequest(J);return this.makeNewInstanceFromResult(Z,J)}async fetchPrevious(W){let J=this.getPreviousQueryParams(W),Z=await this.makeRequest(J);return await this.refreshInstanceFromResult(Z,!1),this}}var t=M4;class F extends t{getNextQueryParams(W){var J;return{...this._queryParams,cursor:(J=this._realData.next_cursor_str)!==null&&J!==void 0?J:this._realData.next_cursor,...W?{count:W}:{}}}isFetchLastOver(W){return!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!this.isNextCursorInvalid(W.next_cursor)||!this.isNextCursorInvalid(W.next_cursor_str)}isNextCursorInvalid(W){return W===void 0||W===0||W===-1||W==="0"||W==="-1"}}class N4 extends F{constructor(){super(...arguments);this._endpoint="direct_messages/events/list.json"}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.events.push(...Z.events),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.events.length}getItemArray(){return this.events}get events(){return this._realData.events}}class x4 extends F{constructor(){super(...arguments);this._endpoint="direct_messages/welcome_messages/list.json"}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.welcome_messages.push(...Z.welcome_messages),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.welcome_messages.length}getItemArray(){return this.welcomeMessages}get welcomeMessages(){return this._realData.welcome_messages}}var L;(function(W){W.Jpeg="image/jpeg",W.Mp4="video/mp4",W.Mov="video/quicktime",W.Gif="image/gif",W.Png="image/png",W.Srt="text/plain",W.Webp="image/webp"})(L||(L={}));var h;(function(W){W.Create="message_create",W.WelcomeCreate="welcome_message"})(h||(h={}));var N1;(function(W){W.Request="request",W.PartialResponse="partial-response",W.Response="response"})(N1||(N1={}));class v1 extends Error{constructor(){super(...arguments);this.error=!0}}class x1 extends v1{constructor(W,J){super(W);this.type=N1.Request,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:J})}get request(){return this._options.request}get requestError(){return this._options.requestError}toJSON(){return{type:this.type,error:this.requestError}}}class L1 extends v1{constructor(W,J){super(W);this.type=N1.PartialResponse,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:J})}get request(){return this._options.request}get response(){return this._options.response}get responseError(){return this._options.responseError}get rawContent(){return this._options.rawContent}toJSON(){return{type:this.type,error:this.responseError}}}class D1 extends v1{constructor(W,J){super(W);if(this.type=N1.Response,Error.captureStackTrace(this,this.constructor),Object.defineProperty(this,"_options",{value:J}),this.code=J.code,this.headers=J.headers,this.rateLimit=J.rateLimit,J.data&&typeof J.data==="object"&&"error"in J.data&&!J.data.errors){let Z={...J.data};Z.errors=[{code:p.InternalError,message:Z.error}],this.data=Z}else this.data=J.data}get request(){return this._options.request}get response(){return this._options.response}hasErrorCode(...W){let J=this.errors;if(!(J===null||J===void 0?void 0:J.length))return!1;if("code"in J[0])return J.some((Q)=>W.includes(Q.code));let Z=this.data;return W.includes(Z.type)}get errors(){var W;return(W=this.data)===null||W===void 0?void 0:W.errors}get rateLimitError(){return this.code===420||this.code===429}get isAuthError(){if(this.code===401)return!0;return this.hasErrorCode(p.AuthTimestampInvalid,p.AuthenticationFail,p.BadAuthenticationData,p.InvalidOrExpiredToken)}toJSON(){return{type:this.type,code:this.code,error:this.data,rateLimit:this.rateLimit,headers:this.headers}}}var p;(function(W){W[W.InvalidCoordinates=3]="InvalidCoordinates",W[W.NoLocationFound=13]="NoLocationFound",W[W.AuthenticationFail=32]="AuthenticationFail",W[W.InvalidOrExpiredToken=89]="InvalidOrExpiredToken",W[W.UnableToVerifyCredentials=99]="UnableToVerifyCredentials",W[W.AuthTimestampInvalid=135]="AuthTimestampInvalid",W[W.BadAuthenticationData=215]="BadAuthenticationData",W[W.NoUserMatch=17]="NoUserMatch",W[W.UserNotFound=50]="UserNotFound",W[W.ResourceNotFound=34]="ResourceNotFound",W[W.TweetNotFound=144]="TweetNotFound",W[W.TweetNotVisible=179]="TweetNotVisible",W[W.NotAllowedResource=220]="NotAllowedResource",W[W.MediaIdNotFound=325]="MediaIdNotFound",W[W.TweetNoLongerAvailable=421]="TweetNoLongerAvailable",W[W.TweetViolatedRules=422]="TweetViolatedRules",W[W.TargetUserSuspended=63]="TargetUserSuspended",W[W.YouAreSuspended=64]="YouAreSuspended",W[W.AccountUpdateFailed=120]="AccountUpdateFailed",W[W.NoSelfSpamReport=36]="NoSelfSpamReport",W[W.NoSelfMute=271]="NoSelfMute",W[W.AccountLocked=326]="AccountLocked",W[W.RateLimitExceeded=88]="RateLimitExceeded",W[W.NoDMRightForApp=93]="NoDMRightForApp",W[W.OverCapacity=130]="OverCapacity",W[W.InternalError=131]="InternalError",W[W.TooManyFollowings=161]="TooManyFollowings",W[W.TweetLimitExceeded=185]="TweetLimitExceeded",W[W.DuplicatedTweet=187]="DuplicatedTweet",W[W.TooManySpamReports=205]="TooManySpamReports",W[W.RequestLooksLikeSpam=226]="RequestLooksLikeSpam",W[W.NoWriteRightForApp=261]="NoWriteRightForApp",W[W.TweetActionsDisabled=425]="TweetActionsDisabled",W[W.TweetRepliesRestricted=433]="TweetRepliesRestricted",W[W.NamedParameterMissing=38]="NamedParameterMissing",W[W.InvalidAttachmentUrl=44]="InvalidAttachmentUrl",W[W.TweetTextTooLong=186]="TweetTextTooLong",W[W.MissingUrlParameter=195]="MissingUrlParameter",W[W.NoMultipleGifs=323]="NoMultipleGifs",W[W.InvalidMediaIds=324]="InvalidMediaIds",W[W.InvalidUrl=407]="InvalidUrl",W[W.TooManyTweetAttachments=386]="TooManyTweetAttachments",W[W.StatusAlreadyFavorited=139]="StatusAlreadyFavorited",W[W.FollowRequestAlreadySent=160]="FollowRequestAlreadySent",W[W.CannotUnmuteANonMutedAccount=272]="CannotUnmuteANonMutedAccount",W[W.TweetAlreadyRetweeted=327]="TweetAlreadyRetweeted",W[W.ReplyToDeletedTweet=385]="ReplyToDeletedTweet",W[W.DMReceiverNotFollowingYou=150]="DMReceiverNotFollowingYou",W[W.UnableToSendDM=151]="UnableToSendDM",W[W.MustAllowDMFromAnyone=214]="MustAllowDMFromAnyone",W[W.CannotSendDMToThisUser=349]="CannotSendDMToThisUser",W[W.DMTextTooLong=354]="DMTextTooLong",W[W.SubscriptionAlreadyExists=355]="SubscriptionAlreadyExists",W[W.CallbackUrlNotApproved=415]="CallbackUrlNotApproved",W[W.SuspendedApplication=416]="SuspendedApplication",W[W.OobOauthIsNotAllowed=417]="OobOauthIsNotAllowed"})(p||(p={}));var p0;(function(W){W.InvalidRequest="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request",W.ClientForbidden="https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden",W.UnsupportedAuthentication="https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication",W.InvalidRules="https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules",W.TooManyRules="https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap",W.DuplicatedRules="https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules",W.RateLimitExceeded="https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped",W.ConnectionError="https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection",W.ClientDisconnected="https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected",W.TwitterDisconnectedYou="https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect",W.ResourceNotFound="https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found",W.ResourceUnauthorized="https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource",W.DisallowedResource="https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource"})(p0||(p0={}));var j;(function(W){W.Connected="connected",W.ConnectError="connect error",W.ConnectionError="connection error",W.ConnectionClosed="connection closed",W.ConnectionLost="connection lost",W.ReconnectAttempt="reconnect attempt",W.Reconnected="reconnected",W.ReconnectError="reconnect error",W.ReconnectLimitExceeded="reconnect limit exceeded",W.DataKeepAlive="data keep-alive",W.Data="data event content",W.DataError="data twitter error",W.TweetParseError="data tweet parse error",W.Error="stream error"})(j||(j={}));class F1{constructor(W){this.value=W}}import*as m4 from"fs";var U={debug:!1,deprecationWarnings:!0,logger:{log:console.log.bind(console)}};function L4(W){let J={value:void 0,promise:W().then((Z)=>{return J.value=Z,Z})};return J}function P1(W){if(Array.isArray(W))return W;return[W]}function n0(W){for(let J of Object.keys(W))if(W[J]===void 0)delete W[J]}function w1(W){return typeof W==="object"&&"errors"in W&&!("data"in W)}function H1(W){if(Array.isArray(W)&&W.length>1)return!0;return W.toString().includes(",")}var l0=new Set;function D4(W){if(typeof console>"u"||!console.warn||!U.deprecationWarnings)return;let J=`${W.instance}-${W.method}-${W.problem}`;if(l0.has(J))return;let Z=`[twitter-api-v2] Deprecation warning: In ${W.instance}.${W.method}() call, ${W.problem}.
|
|
65
|
+
${W.resolution}.`;console.warn(Z),console.warn("To disable this message, import variable TwitterApiV2Settings from twitter-api-v2 and set TwitterApiV2Settings.deprecationWarnings to false."),l0.add(J)}import{EventEmitter as p6}from"events";import{request as m6}from"https";import*as O from"zlib";import{EventEmitter as c6}from"events";class i0{constructor(W){this.requestData=W,this.requestErrorHandled=!1,this.responseData=[]}get hrefPathname(){let W=this.requestData.url;return W.hostname+W.pathname}isCompressionDisabled(){return!this.requestData.compression||this.requestData.compression==="identity"}isFormEncodedEndpoint(){return this.requestData.url.href.startsWith("https://api.x.com/oauth/")}createRequestError(W){if(U.debug)U.logger.log("Request error:",W);return new x1("Request failed.",{request:this.req,error:W})}createPartialResponseError(W,J){let $=`Request failed with partial response with HTTP code ${this.res.statusCode}`;if(J)$+=" (connection abruptly closed)";else $+=" (parse error)";return new L1($,{request:this.req,response:this.res,responseError:W,rawContent:Buffer.concat(this.responseData).toString()})}formatV1Errors(W){return W.map(({code:J,message:Z})=>`${Z} (Twitter code ${J})`).join(", ")}formatV2Error(W){return`${W.title}: ${W.detail} (see ${W.type})`}createResponseError({res:W,data:J,rateLimit:Z,code:$}){var Q;if(U.debug)U.logger.log(`Request failed with code ${$}, data:`,J),U.logger.log("Response headers:",W.headers);let Y=`Request failed with code ${$}`;if((Q=J===null||J===void 0?void 0:J.errors)===null||Q===void 0?void 0:Q.length){let G=J.errors;if(typeof G[0]==="object"&&"code"in G[0])Y+=" - "+this.formatV1Errors(G);else Y+=" - "+this.formatV2Error(J)}return new D1(Y,{code:$,data:J,headers:W.headers,request:this.req,response:W,rateLimit:Z})}getResponseDataStream(W){if(this.isCompressionDisabled())return W;let J=(W.headers["content-encoding"]||"identity").trim().toLowerCase();if(J==="br"){let Z=O.createBrotliDecompress({flush:O.constants.BROTLI_OPERATION_FLUSH,finishFlush:O.constants.BROTLI_OPERATION_FLUSH});return W.pipe(Z),Z}if(J==="gzip"){let Z=O.createGunzip({flush:O.constants.Z_SYNC_FLUSH,finishFlush:O.constants.Z_SYNC_FLUSH});return W.pipe(Z),Z}if(J==="deflate"){let Z=O.createInflate({flush:O.constants.Z_SYNC_FLUSH,finishFlush:O.constants.Z_SYNC_FLUSH});return W.pipe(Z),Z}return W}detectResponseType(W){var J,Z;if(((J=W.headers["content-type"])===null||J===void 0?void 0:J.includes("application/json"))||((Z=W.headers["content-type"])===null||Z===void 0?void 0:Z.includes("application/problem+json")))return"json";else if(this.isFormEncodedEndpoint())return"url";return"text"}getParsedResponse(W){let J=this.responseData,Z=this.requestData.forceParseMode||this.detectResponseType(W);if(Z==="buffer")return Buffer.concat(J);else if(Z==="text")return Buffer.concat(J).toString();else if(Z==="json"){let $=Buffer.concat(J).toString();return $.length?JSON.parse($):void 0}else if(Z==="url"){let $=Buffer.concat(J).toString(),Q={};for(let[Y,G]of new URLSearchParams($))Q[Y]=G;return Q}else return}getRateLimitFromResponse(W){let J=void 0;if(W.headers["x-rate-limit-limit"]){if(J={limit:Number(W.headers["x-rate-limit-limit"]),remaining:Number(W.headers["x-rate-limit-remaining"]),reset:Number(W.headers["x-rate-limit-reset"])},W.headers["x-app-limit-24hour-limit"])J.day={limit:Number(W.headers["x-app-limit-24hour-limit"]),remaining:Number(W.headers["x-app-limit-24hour-remaining"]),reset:Number(W.headers["x-app-limit-24hour-reset"])};if(W.headers["x-user-limit-24hour-limit"])J.userDay={limit:Number(W.headers["x-user-limit-24hour-limit"]),remaining:Number(W.headers["x-user-limit-24hour-remaining"]),reset:Number(W.headers["x-user-limit-24hour-reset"])};if(this.requestData.rateLimitSaver)this.requestData.rateLimitSaver(J)}return J}onSocketEventHandler(W,J,Z){let $=this.onSocketCloseHandler.bind(this,W);Z.on("close",$),J.on("complete",()=>Z.off("close",$))}onSocketCloseHandler(W){if(this.req.removeAllListeners("timeout"),this.res)return;if(!this.requestErrorHandled)return W(this.createRequestError(Error("Socket closed without any information.")))}requestErrorHandler(W,J){var Z,$;($=(Z=this.requestData).requestEventDebugHandler)===null||$===void 0||$.call(Z,"request-error",{requestError:J}),this.requestErrorHandled=!0,W(this.createRequestError(J))}timeoutErrorHandler(){this.requestErrorHandled=!0,this.req.destroy(Error("Request timeout."))}classicResponseHandler(W,J,Z){this.res=Z;let $=this.getResponseDataStream(Z);if($.on("data",(Q)=>this.responseData.push(Q)),$.on("end",this.onResponseEndHandler.bind(this,W,J)),$.on("close",this.onResponseCloseHandler.bind(this,W,J)),this.requestData.requestEventDebugHandler)this.requestData.requestEventDebugHandler("response",{res:Z}),Z.on("aborted",(Q)=>this.requestData.requestEventDebugHandler("response-aborted",{error:Q})),Z.on("error",(Q)=>this.requestData.requestEventDebugHandler("response-error",{error:Q})),Z.on("close",()=>this.requestData.requestEventDebugHandler("response-close",{data:this.responseData})),Z.on("end",()=>this.requestData.requestEventDebugHandler("response-end"))}onResponseEndHandler(W,J){let Z=this.getRateLimitFromResponse(this.res),$;try{$=this.getParsedResponse(this.res)}catch(Y){J(this.createPartialResponseError(Y,!1));return}let Q=this.res.statusCode;if(Q>=400){J(this.createResponseError({data:$,res:this.res,rateLimit:Z,code:Q}));return}if(U.debug)U.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${this.res.statusCode}`),U.logger.log("Response body:",$);W({data:$,headers:this.res.headers,rateLimit:Z})}onResponseCloseHandler(W,J){let Z=this.res;if(Z.aborted)try{return this.getParsedResponse(this.res),this.onResponseEndHandler(W,J)}catch($){return J(this.createPartialResponseError($,!0))}if(!Z.complete)return J(this.createPartialResponseError(Error("Response has been interrupted before response could be parsed."),!0))}streamResponseHandler(W,J,Z){if(Z.statusCode<400){if(U.debug)U.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]: Request succeeds with code ${Z.statusCode} (starting stream)`);let Q=this.getResponseDataStream(Z);W({req:this.req,res:Q,originalResponse:Z,requestData:this.requestData})}else this.classicResponseHandler(()=>{return},J,Z)}debugRequest(){let W=this.requestData.url;if(U.logger.log(`[${this.requestData.options.method} ${this.hrefPathname}]`,this.requestData.options),W.search)U.logger.log("Request parameters:",[...W.searchParams.entries()].map(([J,Z])=>`${J}: ${Z}`));if(this.requestData.body)U.logger.log("Request body:",this.requestData.body)}buildRequest(){var W;let J=this.requestData.url,Z=J.username?`${J.username}:${J.password}`:void 0,$=(W=this.requestData.options.headers)!==null&&W!==void 0?W:{};if(this.requestData.compression===!0||this.requestData.compression==="brotli")$["accept-encoding"]="br;q=1.0, gzip;q=0.8, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="gzip")$["accept-encoding"]="gzip;q=1, deflate;q=0.5, *;q=0.1";else if(this.requestData.compression==="deflate")$["accept-encoding"]="deflate;q=1, *;q=0.1";if(U.debug)this.debugRequest();this.req=m6({...this.requestData.options,host:J.hostname,port:J.port||void 0,path:J.pathname+J.search,protocol:J.protocol,auth:Z,headers:$})}registerRequestEventDebugHandlers(W){W.on("close",()=>this.requestData.requestEventDebugHandler("close")),W.on("abort",()=>this.requestData.requestEventDebugHandler("abort")),W.on("socket",(J)=>{this.requestData.requestEventDebugHandler("socket",{socket:J}),J.on("error",(Z)=>this.requestData.requestEventDebugHandler("socket-error",{socket:J,error:Z})),J.on("connect",()=>this.requestData.requestEventDebugHandler("socket-connect",{socket:J})),J.on("close",(Z)=>this.requestData.requestEventDebugHandler("socket-close",{socket:J,withError:Z})),J.on("end",()=>this.requestData.requestEventDebugHandler("socket-end",{socket:J})),J.on("lookup",(...Z)=>this.requestData.requestEventDebugHandler("socket-lookup",{socket:J,data:Z})),J.on("timeout",()=>this.requestData.requestEventDebugHandler("socket-timeout",{socket:J}))})}makeRequest(){return this.buildRequest(),new Promise((W,J)=>{let Z=(G)=>{Q.emit("complete"),W(G)},$=(G)=>{Q.emit("complete"),J(G)},Q=new c6,Y=this.req;if(Y.on("error",this.requestErrorHandler.bind(this,$)),Y.on("socket",this.onSocketEventHandler.bind(this,$,Q)),Y.on("response",this.classicResponseHandler.bind(this,Z,$)),this.requestData.options.timeout)Y.on("timeout",this.timeoutErrorHandler.bind(this));if(this.requestData.requestEventDebugHandler)this.registerRequestEventDebugHandlers(Y);if(this.requestData.body)Y.write(this.requestData.body);Y.end()})}async makeRequestAsStream(){let{req:W,res:J,requestData:Z,originalResponse:$}=await this.makeRequestAndResolveWhenReady();return new V1(Z,{req:W,res:J,originalResponse:$})}makeRequestAndResolveWhenReady(){return this.buildRequest(),new Promise((W,J)=>{let Z=this.req;if(Z.on("error",this.requestErrorHandler.bind(this,J)),Z.on("response",this.streamResponseHandler.bind(this,W,J)),this.requestData.body)Z.write(this.requestData.body);Z.end()})}}var U1=i0;import{EventEmitter as u6}from"events";class o0 extends u6{constructor(W){super();this.stream=W,this.stack=[],this.onStreamData=this.onStreamData.bind(this),this.onStreamError=this.onStreamError.bind(this),this.onceNewEvent=this.once.bind(this,"event"),W.on(j.Data,this.onStreamData),W.on(j.ConnectionError,this.onStreamError),W.on(j.TweetParseError,this.onStreamError),W.on(j.ConnectionClosed,this.onStreamError)}nextEvent(){return new Promise(this.onceNewEvent)}hasStack(){return this.stack.length>0}popStack(){let W=this.stack;return this.stack=[],W}destroy(){this.removeAllListeners(),this.stream.off(j.Data,this.onStreamData),this.stream.off(j.ConnectionError,this.onStreamError),this.stream.off(j.TweetParseError,this.onStreamError),this.stream.off(j.ConnectionClosed,this.onStreamError)}emitEvent(W,J){this.emit("event",{type:W,payload:J})}onStreamError(W){this.emitEvent("error",W)}onStreamData(W){this.stack.push(W),this.emitEvent("data",W)}}var s0=o0;import{EventEmitter as d6}from"events";class q1 extends d6{constructor(){super(...arguments);this.currentMessage=""}push(W){this.currentMessage+=W,W=this.currentMessage;let J=W.length,Z=0,$=0;while($<J){if(W.slice($,$+2)===`\r
|
|
66
|
+
`){let Q=W.slice(Z,$);if(Z=$+=2,!Q.length)continue;try{let Y=JSON.parse(Q);if(Y){this.emit(l.ParsedData,Y);continue}}catch(Y){this.emit(l.ParseError,Y)}}$++}this.currentMessage=W.slice(Z,J)}reset(){this.currentMessage=""}}var l;(function(W){W.ParsedData="parsed data",W.ParseError="parse error"})(l||(l={}));var a0=[5,15,30,60,90,120,180,300,600,900],l6=(W)=>W>a0.length?901000:a0[W-1]*1000;class t0 extends p6{constructor(W,J){super();if(this.requestData=W,this.autoReconnect=!1,this.autoReconnectRetries=5,this.keepAliveTimeoutMs=120000,this.nextRetryTimeout=l6,this.parser=new q1,this.connectionProcessRunning=!1,this.onKeepAliveTimeout=this.onKeepAliveTimeout.bind(this),this.initEventsFromParser(),J)this.req=J.req,this.res=J.res,this.originalResponse=J.originalResponse,this.initEventsFromRequest()}on(W,J){return super.on(W,J)}initEventsFromRequest(){if(!this.req||!this.res)throw Error("TweetStream error: You cannot init TweetStream without a request and response object.");let W=(J)=>{this.emit(j.ConnectionError,J),this.emit(j.Error,{type:j.ConnectionError,error:J,message:"Connection lost or closed by Twitter."}),this.onConnectionError()};this.req.on("error",W),this.res.on("error",W),this.res.on("close",()=>W(Error("Connection closed by Twitter."))),this.res.on("data",(J)=>{if(this.resetKeepAliveTimeout(),J.toString()===`\r
|
|
67
|
+
`)return this.emit(j.DataKeepAlive);this.parser.push(J.toString())}),this.resetKeepAliveTimeout()}initEventsFromParser(){let W=this.requestData.payloadIsError;this.parser.on(l.ParsedData,(J)=>{if(W&&W(J))this.emit(j.DataError,J),this.emit(j.Error,{type:j.DataError,error:J,message:"Twitter sent a payload that is detected as an error payload."});else this.emit(j.Data,J)}),this.parser.on(l.ParseError,(J)=>{this.emit(j.TweetParseError,J),this.emit(j.Error,{type:j.TweetParseError,error:J,message:"Failed to parse stream data."})})}resetKeepAliveTimeout(){if(this.unbindKeepAliveTimeout(),this.keepAliveTimeoutMs!==1/0)this.keepAliveTimeout=setTimeout(this.onKeepAliveTimeout,this.keepAliveTimeoutMs)}onKeepAliveTimeout(){this.emit(j.ConnectionLost),this.onConnectionError()}unbindTimeouts(){this.unbindRetryTimeout(),this.unbindKeepAliveTimeout()}unbindKeepAliveTimeout(){if(this.keepAliveTimeout)clearTimeout(this.keepAliveTimeout),this.keepAliveTimeout=void 0}unbindRetryTimeout(){if(this.retryTimeout)clearTimeout(this.retryTimeout),this.retryTimeout=void 0}closeWithoutEmit(){if(this.unbindTimeouts(),this.res)this.res.removeAllListeners(),this.res.destroy();if(this.req)this.req.removeAllListeners(),this.req.destroy()}close(){this.emit(j.ConnectionClosed),this.closeWithoutEmit()}destroy(){this.removeAllListeners(),this.close()}async clone(){let J=await new U1(this.requestData).makeRequestAsStream(),Z=this.eventNames();for(let $ of Z){let Q=this.listeners($);for(let Y of Q)J.on($,Y)}return J}async connect(W={}){if(typeof W.autoReconnect<"u")this.autoReconnect=W.autoReconnect;if(typeof W.autoReconnectRetries<"u")this.autoReconnectRetries=W.autoReconnectRetries==="unlimited"?1/0:W.autoReconnectRetries;if(typeof W.keepAliveTimeout<"u")this.keepAliveTimeoutMs=W.keepAliveTimeout==="disable"?1/0:W.keepAliveTimeout;if(typeof W.nextRetryTimeout<"u")this.nextRetryTimeout=W.nextRetryTimeout;this.unbindTimeouts();try{await this.reconnect()}catch(J){if(this.emit(j.ConnectError,0),this.emit(j.Error,{type:j.ConnectError,error:J,message:"Connect error - Initial connection just failed."}),this.autoReconnect)this.makeAutoReconnectRetry(0,J);else throw J}return this}async reconnect(){if(this.connectionProcessRunning)throw Error("Connection process is already running.");this.connectionProcessRunning=!0;try{let W=!0;if(this.req)W=!1,this.closeWithoutEmit();let{req:J,res:Z,originalResponse:$}=await new U1(this.requestData).makeRequestAndResolveWhenReady();this.req=J,this.res=Z,this.originalResponse=$,this.emit(W?j.Connected:j.Reconnected),this.parser.reset(),this.initEventsFromRequest()}finally{this.connectionProcessRunning=!1}}async onConnectionError(W=0){if(this.unbindTimeouts(),this.closeWithoutEmit(),!this.autoReconnect){this.emit(j.ConnectionClosed);return}if(W>=this.autoReconnectRetries){this.emit(j.ReconnectLimitExceeded),this.emit(j.ConnectionClosed);return}try{this.emit(j.ReconnectAttempt,W),await this.reconnect()}catch(J){this.emit(j.ReconnectError,W),this.emit(j.Error,{type:j.ReconnectError,error:J,message:`Reconnect error - ${W+1} attempts made yet.`}),this.makeAutoReconnectRetry(W,J)}}makeAutoReconnectRetry(W,J){let Z=this.nextRetryTimeout(W+1,J);this.retryTimeout=setTimeout(()=>{this.onConnectionError(W+1)},Z)}async*[Symbol.asyncIterator](){let W=new s0(this);try{while(!0){if(!this.req||this.req.aborted)throw Error("Connection closed");if(W.hasStack())yield*W.popStack();let{type:J,payload:Z}=await W.nextEvent();if(J==="error")throw Z}}finally{W.destroy()}}}var V1=t0;function r0(W){var J;if(!((J=W.clientSettings.plugins)===null||J===void 0?void 0:J.length))return!1;for(let Z of W.clientSettings.plugins)if(Z.onRequestError||Z.onResponseError)return!0;return!1}async function e0(W,J,Z,$){let Q;if($ instanceof x1||$ instanceof L1)Q=await this.applyPluginMethod("onRequestError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:J,requestOptions:Z,error:$});else if($ instanceof D1)Q=await this.applyPluginMethod("onResponseError",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:J,requestOptions:Z,error:$});if(Q&&Q instanceof F1)return Q.value;return Promise.reject($)}import*as Z6 from"crypto";class C{constructor(W){this.nonceLength=32,this.consumerKeys=W.consumerKeys}static percentEncode(W){return encodeURIComponent(W).replace(/!/g,"%21").replace(/\*/g,"%2A").replace(/'/g,"%27").replace(/\(/g,"%28").replace(/\)/g,"%29")}hash(W,J){return Z6.createHmac("sha1",J).update(W).digest("base64")}authorize(W,J={}){let Z={oauth_consumer_key:this.consumerKeys.key,oauth_nonce:this.getNonce(),oauth_signature_method:"HMAC-SHA1",oauth_timestamp:this.getTimestamp(),oauth_version:"1.0"};if(J.key!==void 0)Z.oauth_token=J.key;if(!W.data)W.data={};return Z.oauth_signature=this.getSignature(W,J.secret,Z),Z}toHeader(W){let J=J6(W),Z="OAuth ";for(let $ of J){if($.key.indexOf("oauth_")!==0)continue;Z+=C.percentEncode($.key)+'="'+C.percentEncode($.value)+'",'}return{Authorization:Z.slice(0,Z.length-1)}}getNonce(){let J="";for(let Z=0;Z<this.nonceLength;Z++)J+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"[Math.trunc(Math.random()*62)];return J}getTimestamp(){return Math.trunc(new Date().getTime()/1000)}getSignature(W,J,Z){return this.hash(this.getBaseString(W,Z),this.getSigningKey(J))}getSigningKey(W){return C.percentEncode(this.consumerKeys.secret)+"&"+C.percentEncode(W||"")}getBaseString(W,J){return W.method.toUpperCase()+"&"+C.percentEncode(this.getBaseUrl(W.url))+"&"+C.percentEncode(this.getParameterString(W,J))}getParameterString(W,J){let Z=J6(o6(W6(J,W6(W.data,i6(W.url))))),$="";for(let{key:Q,value:Y}of Z)if(Y&&Array.isArray(Y)){Y.sort();let G="";Y.forEach((K,z)=>{if(G+=Q+"="+K,z<Y.length)G+="&"}),$+=G}else $+=Q+"="+Y+"&";return $.slice(0,$.length-1)}getBaseUrl(W){return W.split("?")[0]}}var S1=C;function W6(W,J){return{...W||{},...J||{}}}function J6(W){return Object.keys(W).sort().map((J)=>({key:J,value:W[J]}))}function n6(W){let J=W.split("&"),Z={};for(let $ of J){let[Q,Y=""]=$.split("=");if(Z[Q]){if(!Array.isArray(Z[Q]))Z[Q]=[Z[Q]];Z[Q].push(decodeURIComponent(Y))}else Z[Q]=decodeURIComponent(Y)}return Z}function i6(W){let J=W.split("?");if(J.length===1)return{};return n6(J[1])}function o6(W){let J={};for(let Z in W){let $=W[Z];if($&&Array.isArray($))$=$.map((Q)=>C.percentEncode(Q));else $=C.percentEncode($);J[C.percentEncode(Z)]=$}return J}class I{constructor(){this._boundary="",this._chunks=[]}bodyAppend(...W){let J=W.map((Z)=>Z instanceof Buffer?Z:Buffer.from(Z));this._chunks.push(...J)}append(W,J,Z){let $=J instanceof Buffer?J:J.toString(),Q=this.getMultipartHeader(W,$,Z);this.bodyAppend(Q,$,I.LINE_BREAK)}getHeaders(){return{"content-type":"multipart/form-data; boundary="+this.getBoundary()}}getLength(){return this._chunks.reduce((W,J)=>W+J.length,this.getMultipartFooter().length)}getBuffer(){let W=[...this._chunks,this.getMultipartFooter()],J=Buffer.alloc(this.getLength()),Z=0;for(let $ of W)for(let Q=0;Q<$.length;Z++,Q++)J[Z]=$[Q];return J}getBoundary(){if(!this._boundary)this.generateBoundary();return this._boundary}generateBoundary(){let W="--------------------------";for(let J=0;J<24;J++)W+=Math.floor(Math.random()*10).toString(16);this._boundary=W}getMultipartHeader(W,J,Z){if(!Z)Z=J instanceof Buffer?I.DEFAULT_CONTENT_TYPE:"";let $={"Content-Disposition":["form-data",`name="${W}"`],"Content-Type":Z},Q="";for(let[Y,G]of Object.entries($)){if(!G.length)continue;Q+=Y+": "+P1(G).join("; ")+I.LINE_BREAK}return"--"+this.getBoundary()+I.LINE_BREAK+Q+I.LINE_BREAK}getMultipartFooter(){if(this._footerChunk)return this._footerChunk;return this._footerChunk=Buffer.from("--"+this.getBoundary()+"--"+I.LINE_BREAK)}}I.LINE_BREAK=`\r
|
|
68
|
+
`;I.DEFAULT_CONTENT_TYPE="application/octet-stream";class F4{static formatQueryToString(W){let J={};for(let Z in W)if(typeof W[Z]==="string")J[Z]=W[Z];else if(typeof W[Z]<"u")J[Z]=String(W[Z]);return J}static autoDetectBodyType(W){if(W.pathname.startsWith("/2/")||W.pathname.startsWith("/labs/2/")){if(W.password.startsWith("/2/oauth2"))return"url";return"json"}if(W.hostname==="upload.x.com"){if(W.pathname==="/1.1/media/upload.json")return"form-data";return"json"}let J=W.pathname.split("/1.1/",2)[1];if(this.JSON_1_1_ENDPOINTS.has(J))return"json";return"url"}static addQueryParamsToUrl(W,J){let Z=Object.entries(J);if(Z.length){let $="";for(let[Q,Y]of Z)$+=($.length?"&":"?")+`${S1.percentEncode(Q)}=${S1.percentEncode(Y)}`;W.search=$}}static constructBodyParams(W,J,Z){if(W instanceof Buffer)return W;if(Z==="json"){if(!J["content-type"])J["content-type"]="application/json;charset=UTF-8";return JSON.stringify(W)}else if(Z==="url"){if(!J["content-type"])J["content-type"]="application/x-www-form-urlencoded;charset=UTF-8";if(Object.keys(W).length)return new URLSearchParams(W).toString().replace(/\*/g,"%2A");return""}else if(Z==="raw")throw Error("You can only use raw body mode with Buffers. To give a string, use Buffer.from(str).");else{let $=new I;for(let Q in W)$.append(Q,W[Q]);if(!J["content-type"]){let Q=$.getHeaders();J["content-type"]=Q["content-type"]}return $.getBuffer()}}static setBodyLengthHeader(W,J){var Z;if(W.headers=(Z=W.headers)!==null&&Z!==void 0?Z:{},typeof J==="string")W.headers["content-length"]=Buffer.byteLength(J);else W.headers["content-length"]=J.length}static isOAuthSerializable(W){return!(W instanceof Buffer)}static mergeQueryAndBodyForOAuth(W,J){let Z={};for(let $ in W)Z[$]=W[$];if(this.isOAuthSerializable(J))for(let $ in J){let Q=J[$];if(this.isOAuthSerializable(Q))Z[$]=typeof Q==="object"&&Q!==null&&"toString"in Q?Q.toString():Q}return Z}static moveUrlQueryParamsIntoObject(W,J){for(let[Z,$]of W.searchParams)J[Z]=$;return W.search="",W}static applyRequestParametersToUrl(W,J){return W.pathname=W.pathname.replace(/:([A-Z_-]+)/ig,(Z,$)=>{if(J[$]!==void 0)return String(J[$]);return Z}),W}}F4.JSON_1_1_ENDPOINTS=new Set(["direct_messages/events/new.json","direct_messages/welcome_messages/new.json","direct_messages/welcome_messages/rules/new.json","media/metadata/create.json","collections/entries/curate.json"]);var R=F4;import*as $6 from"crypto";class n{static getCodeVerifier(){return this.generateRandomString(128)}static getCodeChallengeFromVerifier(W){return this.escapeBase64Url($6.createHash("sha256").update(W).digest("base64"))}static getAuthHeader(W,J){let Z=encodeURIComponent(W)+":"+encodeURIComponent(J);return Buffer.from(Z).toString("base64")}static generateRandomString(W){let J="",Z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";for(let $=0;$<W;$++)J+=Z[Math.floor(Math.random()*Z.length)];return J}static escapeBase64Url(W){return W.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}}class r{constructor(W){if(this.rateLimits={},this.clientSettings={},W)this.clientSettings=W}getRateLimits(){return this.rateLimits}saveRateLimit(W,J){this.rateLimits[W]=J}async send(W){var J,Z,$,Q,Y;if((J=this.clientSettings.plugins)===null||J===void 0?void 0:J.length){let M=await this.applyPreRequestConfigHooks(W);if(M)return M}let G=this.getHttpRequestArgs(W),K={method:G.method,headers:G.headers,timeout:W.timeout,agent:this.clientSettings.httpAgent},z=W.enableRateLimitSave!==!1;if(G.body)R.setBodyLengthHeader(K,G.body);if((Z=this.clientSettings.plugins)===null||Z===void 0?void 0:Z.length)await this.applyPreRequestHooks(W,G,K);let X=new U1({url:G.url,options:K,body:G.body,rateLimitSaver:z?this.saveRateLimit.bind(this,G.rawUrl):void 0,requestEventDebugHandler:W.requestEventDebugHandler,compression:(Q=($=W.compression)!==null&&$!==void 0?$:this.clientSettings.compression)!==null&&Q!==void 0?Q:!0,forceParseMode:W.forceParseMode}).makeRequest();if(r0(this))X=this.applyResponseErrorHooks(W,G,K,X);let B=await X;if((Y=this.clientSettings.plugins)===null||Y===void 0?void 0:Y.length){let M=await this.applyPostRequestHooks(W,G,K,B);if(M)return M.value}return B}sendStream(W){var J,Z;if(this.clientSettings.plugins)this.applyPreStreamRequestConfigHooks(W);let $=this.getHttpRequestArgs(W),Q={method:$.method,headers:$.headers,agent:this.clientSettings.httpAgent},Y=W.enableRateLimitSave!==!1,G=W.autoConnect!==!1;if($.body)R.setBodyLengthHeader(Q,$.body);let K={url:$.url,options:Q,body:$.body,rateLimitSaver:Y?this.saveRateLimit.bind(this,$.rawUrl):void 0,payloadIsError:W.payloadIsError,compression:(Z=(J=W.compression)!==null&&J!==void 0?J:this.clientSettings.compression)!==null&&Z!==void 0?Z:!0},z=new V1(K);if(!G)return z;return z.connect()}initializeToken(W){if(typeof W==="string")this.bearerToken=W;else if(typeof W==="object"&&"appKey"in W){if(this.consumerToken=W.appKey,this.consumerSecret=W.appSecret,W.accessToken&&W.accessSecret)this.accessToken=W.accessToken,this.accessSecret=W.accessSecret;this._oauth=this.buildOAuth()}else if(typeof W==="object"&&"username"in W){let J=encodeURIComponent(W.username)+":"+encodeURIComponent(W.password);this.basicToken=Buffer.from(J).toString("base64")}else if(typeof W==="object"&&"clientId"in W)this.clientId=W.clientId,this.clientSecret=W.clientSecret}getActiveTokens(){if(this.bearerToken)return{type:"oauth2",bearerToken:this.bearerToken};else if(this.basicToken)return{type:"basic",token:this.basicToken};else if(this.consumerSecret&&this._oauth)return{type:"oauth-1.0a",appKey:this.consumerToken,appSecret:this.consumerSecret,accessToken:this.accessToken,accessSecret:this.accessSecret};else if(this.clientId)return{type:"oauth2-user",clientId:this.clientId};return{type:"none"}}buildOAuth(){if(!this.consumerSecret||!this.consumerToken)throw Error("Invalid consumer tokens");return new S1({consumerKeys:{key:this.consumerToken,secret:this.consumerSecret}})}getOAuthAccessTokens(){if(!this.accessSecret||!this.accessToken)return;return{key:this.accessToken,secret:this.accessSecret}}getPlugins(){var W;return(W=this.clientSettings.plugins)!==null&&W!==void 0?W:[]}hasPlugins(){var W;return!!((W=this.clientSettings.plugins)===null||W===void 0?void 0:W.length)}async applyPluginMethod(W,J){var Z;let $;for(let Q of this.getPlugins()){let Y=await((Z=Q[W])===null||Z===void 0?void 0:Z.call(Q,J));if(Y&&Y instanceof F1)$=Y}return $}writeAuthHeaders({headers:W,bodyInSignature:J,url:Z,method:$,query:Q,body:Y}){if(W={...W},this.bearerToken)W.Authorization="Bearer "+this.bearerToken;else if(this.basicToken)W.Authorization="Basic "+this.basicToken;else if(this.clientId&&this.clientSecret)W.Authorization="Basic "+n.getAuthHeader(this.clientId,this.clientSecret);else if(this.consumerSecret&&this._oauth){let G=J?R.mergeQueryAndBodyForOAuth(Q,Y):Q,K=this._oauth.authorize({url:Z.toString(),method:$,data:G},this.getOAuthAccessTokens());W={...W,...this._oauth.toHeader(K)}}return W}getUrlObjectFromUrlString(W){if(!W.startsWith("http"))W="https://"+W;return new URL(W)}getHttpRequestArgs({url:W,method:J,query:Z={},body:$={},headers:Q,forceBodyMode:Y,enableAuth:G,params:K}){let z=void 0;if(J=J.toUpperCase(),Q=Q!==null&&Q!==void 0?Q:{},!Q["x-user-agent"])Q["x-user-agent"]="Node.twitter-api-v2";let X=this.getUrlObjectFromUrlString(W),B=X.origin+X.pathname;if(K)R.applyRequestParametersToUrl(X,K);let M=R.formatQueryToString(Z);if(R.moveUrlQueryParamsIntoObject(X,M),!($ instanceof Buffer))n0($);let D=Y!==null&&Y!==void 0?Y:R.autoDetectBodyType(X);if(G!==!1){let S=r.BODY_METHODS.has(J)&&D==="url";Q=this.writeAuthHeaders({headers:Q,bodyInSignature:S,method:J,query:M,url:X,body:$})}if(r.BODY_METHODS.has(J))z=R.constructBodyParams($,Q,D)||void 0;return R.addQueryParamsToUrl(X,M),{rawUrl:B,url:X,method:J,headers:Q,body:z}}async applyPreRequestConfigHooks(W){var J;let Z=this.getUrlObjectFromUrlString(W.url);for(let $ of this.getPlugins()){let Q=await((J=$.onBeforeRequestConfig)===null||J===void 0?void 0:J.call($,{client:this,url:Z,params:W}));if(Q)return Q}}applyPreStreamRequestConfigHooks(W){var J;let Z=this.getUrlObjectFromUrlString(W.url);for(let $ of this.getPlugins())(J=$.onBeforeStreamRequestConfig)===null||J===void 0||J.call($,{client:this,url:Z,params:W})}async applyPreRequestHooks(W,J,Z){await this.applyPluginMethod("onBeforeRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:J,requestOptions:Z})}async applyPostRequestHooks(W,J,Z,$){return await this.applyPluginMethod("onAfterRequest",{client:this,url:this.getUrlObjectFromUrlString(W.url),params:W,computedParams:J,requestOptions:Z,response:$})}applyResponseErrorHooks(W,J,Z,$){return $.catch(e0.bind(this,W,J,Z))}}r.BODY_METHODS=new Set(["POST","PUT","PATCH"]);class g{constructor(W,J={}){if(this._currentUser=null,this._currentUserV2=null,W instanceof g)this._requestMaker=W._requestMaker;else this._requestMaker=new r(J),this._requestMaker.initializeToken(W)}setPrefix(W){this._prefix=W}cloneWithPrefix(W){let J=this.constructor(this);return J.setPrefix(W),J}getActiveTokens(){return this._requestMaker.getActiveTokens()}getPlugins(){return this._requestMaker.getPlugins()}getPluginOfType(W){return this.getPlugins().find((J)=>J instanceof W)}hasHitRateLimit(W){var J;if(this.isRateLimitStatusObsolete(W))return!1;return((J=this.getLastRateLimitStatus(W))===null||J===void 0?void 0:J.remaining)===0}isRateLimitStatusObsolete(W){let J=this.getLastRateLimitStatus(W);if(J===void 0)return!0;return J.reset*1000<Date.now()}getLastRateLimitStatus(W){let J=W.match(/^https?:\/\//)?W:this._prefix+W;return this._requestMaker.getRateLimits()[J]}getCurrentUserObject(W=!1){if(!W&&this._currentUser){if(this._currentUser.value)return Promise.resolve(this._currentUser.value);return this._currentUser.promise}return this._currentUser=L4(()=>this.get("account/verify_credentials.json",{tweet_mode:"extended"},{prefix:A})),this._currentUser.promise}getCurrentUserV2Object(W=!1){if(!W&&this._currentUserV2){if(this._currentUserV2.value)return Promise.resolve(this._currentUserV2.value);return this._currentUserV2.promise}return this._currentUserV2=L4(()=>this.get("users/me",void 0,{prefix:y})),this._currentUserV2.promise}async get(W,J={},{fullResponse:Z,prefix:$=this._prefix,...Q}={}){if($)W=$+W;let Y=await this._requestMaker.send({url:W,method:"GET",query:J,...Q});return Z?Y:Y.data}async delete(W,J={},{fullResponse:Z,prefix:$=this._prefix,...Q}={}){if($)W=$+W;let Y=await this._requestMaker.send({url:W,method:"DELETE",query:J,...Q});return Z?Y:Y.data}async post(W,J,{fullResponse:Z,prefix:$=this._prefix,...Q}={}){if($)W=$+W;let Y=await this._requestMaker.send({url:W,method:"POST",body:J,...Q});return Z?Y:Y.data}async put(W,J,{fullResponse:Z,prefix:$=this._prefix,...Q}={}){if($)W=$+W;let Y=await this._requestMaker.send({url:W,method:"PUT",body:J,...Q});return Z?Y:Y.data}async patch(W,J,{fullResponse:Z,prefix:$=this._prefix,...Q}={}){if($)W=$+W;let Y=await this._requestMaker.send({url:W,method:"PATCH",body:J,...Q});return Z?Y:Y.data}getStream(W,J,{prefix:Z=this._prefix,...$}={}){return this._requestMaker.sendStream({url:Z?Z+W:W,method:"GET",query:J,...$})}postStream(W,J,{prefix:Z=this._prefix,...$}={}){return this._requestMaker.sendStream({url:Z?Z+W:W,method:"POST",body:J,...$})}}class f extends g{constructor(W){if(!(W instanceof g))throw Error("You must instance SubTwitterApi instance from existing TwitterApi instance.");super(W)}}class e extends t{constructor(){super(...arguments);this.hasFinishedFetch=!1}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.push(...Z),this.hasFinishedFetch=Z.length===0}getNextQueryParams(W){let J=BigInt(this._realData[this._realData.length-1].id_str);return{...this.injectQueryParams(W),max_id:(J-BigInt(1)).toString()}}getPageLengthFromRequest(W){return W.data.length}isFetchLastOver(W){return!W.data.length}canFetchNextPage(W){return W.length>0}getItemArray(){return this.tweets}get tweets(){return this._realData}get done(){return super.done||this.hasFinishedFetch}}class H4 extends e{constructor(){super(...arguments);this._endpoint="statuses/home_timeline.json"}}class U4 extends e{constructor(){super(...arguments);this._endpoint="statuses/mentions_timeline.json"}}class y1 extends e{constructor(){super(...arguments);this._endpoint="statuses/user_timeline.json"}}class S4 extends e{constructor(){super(...arguments);this._endpoint="lists/statuses.json"}}class A1 extends e{constructor(){super(...arguments);this._endpoint="favorites/list.json"}}class O4 extends F{constructor(){super(...arguments);this._endpoint="mutes/users/list.json"}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.users.push(...Z.users),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class R4 extends F{constructor(){super(...arguments);this._endpoint="mutes/users/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.ids.push(...Z.ids),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class f4 extends F{constructor(){super(...arguments);this._endpoint="followers/list.json"}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.users.push(...Z.users),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class _4 extends F{constructor(){super(...arguments);this._endpoint="followers/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.ids.push(...Z.ids),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class k4 extends F{constructor(){super(...arguments);this._endpoint="friends/list.json"}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.users.push(...Z.users),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class C4 extends F{constructor(){super(...arguments);this._endpoint="friends/ids.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.ids.push(...Z.ids),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class I4 extends t{constructor(){super(...arguments);this._endpoint="users/search.json"}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.push(...Z)}getNextQueryParams(W){var J;let Z=Number((J=this._queryParams.page)!==null&&J!==void 0?J:"1");return{...this._queryParams,page:Z+1,...W?{count:W}:{}}}getPageLengthFromRequest(W){return W.data.length}isFetchLastOver(W){return!W.data.length}canFetchNextPage(W){return W.length>0}getItemArray(){return this.users}get users(){return this._realData}}class h1 extends F{constructor(){super(...arguments);this._endpoint="friendships/incoming.json",this._maxResultsWhenFetchLast=5000}refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.ids.push(...Z.ids),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.ids.length}getItemArray(){return this.ids}get ids(){return this._realData.ids}}class b4 extends h1{constructor(){super(...arguments);this._endpoint="friendships/outgoing.json"}}class g1 extends F{refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.lists.push(...Z.lists),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.lists.length}getItemArray(){return this.lists}get lists(){return this._realData.lists}}class T4 extends g1{constructor(){super(...arguments);this._endpoint="lists/memberships.json"}}class v4 extends g1{constructor(){super(...arguments);this._endpoint="lists/ownerships.json"}}class P4 extends g1{constructor(){super(...arguments);this._endpoint="lists/subscriptions.json"}}class w4 extends F{refreshInstanceFromResult(W,J){let Z=W.data;if(this._rateLimit=W.rateLimit,J)this._realData.users.push(...Z.users),this._realData.next_cursor=Z.next_cursor}getPageLengthFromRequest(W){return W.data.users.length}getItemArray(){return this.users}get users(){return this._realData.users}}class V4 extends w4{constructor(){super(...arguments);this._endpoint="lists/members.json"}}class q4 extends w4{constructor(){super(...arguments);this._endpoint="lists/subscribers.json"}}class W1 extends f{constructor(){super(...arguments);this._prefix=A}singleTweet(W,J={}){return this.get("statuses/show.json",{tweet_mode:"extended",id:W,...J})}tweets(W,J={}){return this.post("statuses/lookup.json",{tweet_mode:"extended",id:W,...J})}oembedTweet(W,J={}){return this.get("oembed",{url:`https://x.com/i/statuses/${W}`,...J},{prefix:"https://publish.x.com/"})}async homeTimeline(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("statuses/home_timeline.json",J,{fullResponse:!0});return new H4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async mentionTimeline(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("statuses/mentions_timeline.json",J,{fullResponse:!0});return new U4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async userTimeline(W,J={}){let Z={tweet_mode:"extended",user_id:W,...J},$=await this.get("statuses/user_timeline.json",Z,{fullResponse:!0});return new y1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async userTimelineByUsername(W,J={}){let Z={tweet_mode:"extended",screen_name:W,...J},$=await this.get("statuses/user_timeline.json",Z,{fullResponse:!0});return new y1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async favoriteTimeline(W,J={}){let Z={tweet_mode:"extended",user_id:W,...J},$=await this.get("favorites/list.json",Z,{fullResponse:!0});return new A1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async favoriteTimelineByUsername(W,J={}){let Z={tweet_mode:"extended",screen_name:W,...J},$=await this.get("favorites/list.json",Z,{fullResponse:!0});return new A1({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}user(W){return this.get("users/show.json",{tweet_mode:"extended",...W})}users(W){return this.get("users/lookup.json",{tweet_mode:"extended",...W})}verifyCredentials(W={}){return this.get("account/verify_credentials.json",W)}async listMutedUsers(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("mutes/users/list.json",J,{fullResponse:!0});return new O4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async listMutedUserIds(W={}){let J={stringify_ids:!0,...W},Z=await this.get("mutes/users/ids.json",J,{fullResponse:!0});return new R4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async userFriendList(W={}){let J={...W},Z=await this.get("friends/list.json",J,{fullResponse:!0});return new k4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async userFollowerList(W={}){let J={...W},Z=await this.get("followers/list.json",J,{fullResponse:!0});return new f4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async userFollowerIds(W={}){let J={stringify_ids:!0,...W},Z=await this.get("followers/ids.json",J,{fullResponse:!0});return new _4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async userFollowingIds(W={}){let J={stringify_ids:!0,...W},Z=await this.get("friends/ids.json",J,{fullResponse:!0});return new C4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async searchUsers(W,J={}){let Z={q:W,tweet_mode:"extended",page:1,...J},$=await this.get("users/search.json",Z,{fullResponse:!0});return new I4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}friendship(W){return this.get("friendships/show.json",W)}friendships(W){return this.get("friendships/lookup.json",W)}friendshipsNoRetweets(){return this.get("friendships/no_retweets/ids.json",{stringify_ids:!0})}async friendshipsIncoming(W={}){let J={stringify_ids:!0,...W},Z=await this.get("friendships/incoming.json",J,{fullResponse:!0});return new h1({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async friendshipsOutgoing(W={}){let J={stringify_ids:!0,...W},Z=await this.get("friendships/outgoing.json",J,{fullResponse:!0});return new b4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}accountSettings(){return this.get("account/settings.json")}userProfileBannerSizes(W){return this.get("users/profile_banner.json",W)}list(W){return this.get("lists/show.json",{tweet_mode:"extended",...W})}lists(W={}){return this.get("lists/list.json",{tweet_mode:"extended",...W})}async listMembers(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("lists/members.json",J,{fullResponse:!0});return new V4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}listGetMember(W){return this.get("lists/members/show.json",{tweet_mode:"extended",...W})}async listMemberships(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("lists/memberships.json",J,{fullResponse:!0});return new T4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async listOwnerships(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("lists/ownerships.json",J,{fullResponse:!0});return new v4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async listStatuses(W){let J={tweet_mode:"extended",...W},Z=await this.get("lists/statuses.json",J,{fullResponse:!0});return new S4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}async listSubscribers(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("lists/subscribers.json",J,{fullResponse:!0});return new q4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}listGetSubscriber(W){return this.get("lists/subscribers/show.json",{tweet_mode:"extended",...W})}async listSubscriptions(W={}){let J={tweet_mode:"extended",...W},Z=await this.get("lists/subscriptions.json",J,{fullResponse:!0});return new P4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}mediaInfo(W){return this.get("media/upload.json",{command:"STATUS",media_id:W},{prefix:w})}filterStream({autoConnect:W,...J}={}){let Z={};for(let[Q,Y]of Object.entries(J))if(Q==="follow"||Q==="track")Z[Q]=Y.toString();else if(Q==="locations"){let G=Y;Z.locations=P1(G).map((K)=>`${K.lng},${K.lat}`).join(",")}else Z[Q]=Y;return this.stream.postStream("statuses/filter.json",Z,{autoConnect:W})}sampleStream({autoConnect:W,...J}={}){return this.stream.getStream("statuses/sample.json",J,{autoConnect:W})}get stream(){let W=new E1(this);return W.setPrefix(d0),W}trendsByPlace(W,J={}){return this.get("trends/place.json",{id:W,...J})}trendsAvailable(){return this.get("trends/available.json")}trendsClosest(W,J){return this.get("trends/closest.json",{lat:W,long:J})}geoPlace(W){return this.get("geo/id/:place_id.json",void 0,{params:{place_id:W}})}geoSearch(W){return this.get("geo/search.json",W)}geoReverseGeoCode(W){return this.get("geo/reverse_geocode.json",W)}rateLimitStatuses(...W){return this.get("application/rate_limit_status.json",{resources:W})}supportedLanguages(){return this.get("help/languages.json")}}import*as E from"fs";async function y4(W){let J=await A4(W);if(typeof J==="number")return new Promise((Z,$)=>{E.readFile(J,(Q,Y)=>{if(Q)return $(Q);Z(Y)})});else if(J instanceof Buffer)return J;else return J.readFile()}function A4(W){if(typeof W==="string")return E.promises.open(W,"r");else if(typeof W==="number")return W;else if(typeof W==="object"&&!(W instanceof Buffer))return W;else if(!(W instanceof Buffer))throw Error("Given file is not valid, please check its type.");else return W}async function Q6(W){if(typeof W==="number")return(await new Promise((Z,$)=>{E.fstat(W,(Q,Y)=>{if(Q)$(Q);Z(Y)})})).size;else if(W instanceof Buffer)return W.length;else return(await W.stat()).size}function Y6(W,J,Z){if(typeof Z==="string")return Z;else if(typeof W==="string"&&!J)return s6(W);else if(typeof J==="string")return a6(J);throw Error("You must specify type if file is a file handle or Buffer.")}function s6(W){if(W.endsWith(".jpeg")||W.endsWith(".jpg"))return L.Jpeg;if(W.endsWith(".png"))return L.Png;if(W.endsWith(".webp"))return L.Webp;if(W.endsWith(".gif"))return L.Gif;if(W.endsWith(".mpeg4")||W.endsWith(".mp4"))return L.Mp4;if(W.endsWith(".mov")||W.endsWith(".mov"))return L.Mov;if(W.endsWith(".srt"))return L.Srt;return D4({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"options.mimeType is missing and filename couldn't help to resolve MIME type, so it will fallback to image/jpeg",resolution:"If you except to give filenames without extensions, please specify explicitlty the MIME type using options.mimeType"}),L.Jpeg}function a6(W){if(D4({instance:"TwitterApiv1ReadWrite",method:"uploadMedia",problem:"you're using options.type",resolution:"Remove options.type argument and migrate to options.mimeType which takes the real MIME type. If you're using type=longmp4, add options.longVideo alongside of mimeType=EUploadMimeType.Mp4"}),W==="gif")return L.Gif;if(W==="jpg")return L.Jpeg;if(W==="png")return L.Png;if(W==="webp")return L.Webp;if(W==="srt")return L.Srt;if(W==="mp4"||W==="longmp4")return L.Mp4;if(W==="mov")return L.Mov;return W}function G6(W,J){if(W===L.Mp4||W===L.Mov)return J==="tweet"?"TweetVideo":"DmVideo";if(W===L.Gif)return J==="tweet"?"TweetGif":"DmGif";if(W===L.Srt)return"Subtitles";else return J==="tweet"?"TweetImage":"DmImage"}function h4(W){return new Promise((J)=>setTimeout(J,W*1000))}async function g4(W,J,Z=0,$){if(W instanceof Buffer){let Y=W.slice(Z,Z+J);return[Y,Y.length]}if(!$)throw Error("Well, we will need a buffer to store file content.");let Q;if(typeof W==="number")Q=await new Promise((Y,G)=>{E.read(W,$,0,J,Z,(K,z)=>{if(K)G(K);Y(z)})});else Q=(await W.read($,0,J,Z)).bytesRead;return[$,Q]}var E4="media/upload.json";class J1 extends W1{constructor(){super(...arguments);this._prefix=A}get readOnly(){return this}tweet(W,J={}){let Z={status:W,tweet_mode:"extended",...J};return this.post("statuses/update.json",Z)}async quote(W,J,Z={}){let $="https://x.com/i/statuses/"+J;return this.tweet(W,{...Z,attachment_url:$})}async tweetThread(W){let J=[];for(let Z of W){let $=J.length?J[J.length-1]:null,Q={...typeof Z==="string"?{status:Z}:Z},Y=$?$.id_str:Q.in_reply_to_status_id,G=Q.status;if(Y)J.push(await this.reply(G,Y,Q));else J.push(await this.tweet(G,Q))}return J}reply(W,J,Z={}){return this.tweet(W,{auto_populate_reply_metadata:!0,in_reply_to_status_id:J,...Z})}deleteTweet(W){return this.post("statuses/destroy/:id.json",{tweet_mode:"extended"},{params:{id:W}})}reportUserAsSpam(W){return this.post("users/report_spam.json",{tweet_mode:"extended",...W})}updateFriendship(W){return this.post("friendships/update.json",W)}createFriendship(W){return this.post("friendships/create.json",W)}destroyFriendship(W){return this.post("friendships/destroy.json",W)}updateAccountSettings(W){return this.post("account/settings.json",W)}updateAccountProfile(W){return this.post("account/update_profile.json",W)}async updateAccountProfileBanner(W,J={}){let Z={banner:await y4(W),...J};return this.post("account/update_profile_banner.json",Z,{forceBodyMode:"form-data"})}async updateAccountProfileImage(W,J={}){let Z={tweet_mode:"extended",image:await y4(W),...J};return this.post("account/update_profile_image.json",Z,{forceBodyMode:"form-data"})}removeAccountProfileBanner(){return this.post("account/remove_profile_banner.json")}createList(W){return this.post("lists/create.json",{tweet_mode:"extended",...W})}updateList(W){return this.post("lists/update.json",{tweet_mode:"extended",...W})}removeList(W){return this.post("lists/destroy.json",{tweet_mode:"extended",...W})}addListMembers(W){let Z=W.user_id&&H1(W.user_id)||W.screen_name&&H1(W.screen_name)?"lists/members/create_all.json":"lists/members/create.json";return this.post(Z,W)}removeListMembers(W){let Z=W.user_id&&H1(W.user_id)||W.screen_name&&H1(W.screen_name)?"lists/members/destroy_all.json":"lists/members/destroy.json";return this.post(Z,W)}subscribeToList(W){return this.post("lists/subscribers/create.json",{tweet_mode:"extended",...W})}unsubscribeOfList(W){return this.post("lists/subscribers/destroy.json",{tweet_mode:"extended",...W})}createMediaMetadata(W,J){return this.post("media/metadata/create.json",{media_id:W,...J},{prefix:w,forceBodyMode:"json"})}createMediaSubtitles(W,J){return this.post("media/subtitles/create.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:J}},{prefix:w,forceBodyMode:"json"})}deleteMediaSubtitles(W,...J){return this.post("media/subtitles/delete.json",{media_id:W,media_category:"TweetVideo",subtitle_info:{subtitles:J.map((Z)=>({language_code:Z}))}},{prefix:w,forceBodyMode:"json"})}async uploadMedia(W,J={},Z=!1){var $;let Q=($=J.chunkLength)!==null&&$!==void 0?$:1048576,{fileHandle:Y,mediaCategory:G,fileSize:K,mimeType:z}=await this.getUploadMediaRequirements(W,J);try{let X=await this.post(E4,{command:"INIT",total_bytes:K,media_type:z,media_category:G,additional_owners:J.additionalOwners,shared:J.shared?!0:void 0},{prefix:w});await this.mediaChunkedUpload(Y,Q,X.media_id_string,J.maxConcurrentUploads);let B=await this.post(E4,{command:"FINALIZE",media_id:X.media_id_string},{prefix:w});if(B.processing_info&&B.processing_info.state!=="succeeded")await this.awaitForMediaProcessingCompletion(B);if(Z)return B;else return B.media_id_string}finally{if(typeof W==="number")m4.close(W,()=>{});else if(typeof Y==="object"&&!(Y instanceof Buffer))Y.close()}}async awaitForMediaProcessingCompletion(W){var J;while(!0){W=await this.mediaInfo(W.media_id_string);let{processing_info:Z}=W;if(!Z||Z.state==="succeeded")return;if((J=Z.error)===null||J===void 0?void 0:J.code){let{name:$,message:Q}=Z.error;throw Error(`Failed to process media: ${$} - ${Q}.`)}if(Z.state==="failed")throw Error("Failed to process the media.");if(Z.check_after_secs)await h4(Z.check_after_secs);else await h4(5)}}async getUploadMediaRequirements(W,{mimeType:J,type:Z,target:$,longVideo:Q}={}){let Y;try{Y=await A4(W);let G=Y6(W,Z,J),K;if(G===L.Mp4&&(!J&&!Z&&$!=="dm"||Q))K="amplify_video";else K=G6(G,$!==null&&$!==void 0?$:"tweet");return{fileHandle:Y,mediaCategory:K,fileSize:await Q6(Y),mimeType:G}}catch(G){if(typeof W==="number")m4.close(W,()=>{});else if(typeof Y==="object"&&!(Y instanceof Buffer))Y.close();throw G}}async mediaChunkedUpload(W,J,Z,$=3){let Q=0;if($<1)throw RangeError("Bad maxConcurrentUploads parameter.");let Y=W instanceof Buffer?void 0:Buffer.alloc(J),G,K,z=0;[G,K]=await g4(W,J,z,Y),z+=K;let X=new Set;while(K){let B=G.slice(0,K);if(B.length){let M=this.post(E4,{command:"APPEND",media_id:Z,segment_index:Q,media:B},{prefix:w});X.add(M),M.then(()=>{X.delete(M)}),Q++}if(X.size>=$)await Promise.race(X);[G,K]=await g4(W,J,z,Y),z+=K}await Promise.all([...X])}}class K6 extends J1{constructor(){super(...arguments);this._prefix=A}get readWrite(){return this}sendDm({recipient_id:W,custom_profile_id:J,...Z}){let $={event:{type:h.Create,[h.Create]:{target:{recipient_id:W},message_data:Z}}};if(J)$.event[h.Create].custom_profile_id=J;return this.post("direct_messages/events/new.json",$,{forceBodyMode:"json"})}getDmEvent(W){return this.get("direct_messages/events/show.json",{id:W})}deleteDm(W){return this.delete("direct_messages/events/destroy.json",{id:W})}async listDmEvents(W={}){let J={...W},Z=await this.get("direct_messages/events/list.json",J,{fullResponse:!0});return new N4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}newWelcomeDm(W,J){let Z={[h.WelcomeCreate]:{name:W,message_data:J}};return this.post("direct_messages/welcome_messages/new.json",Z,{forceBodyMode:"json"})}getWelcomeDm(W){return this.get("direct_messages/welcome_messages/show.json",{id:W})}deleteWelcomeDm(W){return this.delete("direct_messages/welcome_messages/destroy.json",{id:W})}updateWelcomeDm(W,J){let Z={message_data:J};return this.put("direct_messages/welcome_messages/update.json",Z,{forceBodyMode:"json",query:{id:W}})}async listWelcomeDms(W={}){let J={...W},Z=await this.get("direct_messages/welcome_messages/list.json",J,{fullResponse:!0});return new x4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J})}newWelcomeDmRule(W){return this.post("direct_messages/welcome_messages/rules/new.json",{welcome_message_rule:{welcome_message_id:W}},{forceBodyMode:"json"})}getWelcomeDmRule(W){return this.get("direct_messages/welcome_messages/rules/show.json",{id:W})}deleteWelcomeDmRule(W){return this.delete("direct_messages/welcome_messages/rules/destroy.json",{id:W})}async listWelcomeDmRules(W={}){let J={...W};return this.get("direct_messages/welcome_messages/rules/list.json",J)}async setWelcomeDm(W,J=!0){var Z;let $=await this.listWelcomeDmRules();if((Z=$.welcome_message_rules)===null||Z===void 0?void 0:Z.length){for(let Q of $.welcome_message_rules)if(await this.deleteWelcomeDmRule(Q.id),J)await this.deleteWelcomeDm(Q.welcome_message_id)}return this.newWelcomeDmRule(W)}markDmAsRead(W,J){return this.post("direct_messages/mark_read.json",{last_read_event_id:W,recipient_id:J},{forceBodyMode:"url"})}indicateDmTyping(W){return this.post("direct_messages/indicate_typing.json",{recipient_id:W},{forceBodyMode:"url"})}async downloadDmImage(W){if(typeof W!=="string"){let Z=W[h.Create].message_data.attachment;if(!Z)throw Error("The given direct message doesn't contain any attachment");W=Z.media.media_url_https}let J=await this.get(W,void 0,{forceParseMode:"buffer",prefix:""});if(!J.length)throw Error("Image not found. Make sure you are logged with credentials able to access direct messages, and check the URL.");return J}}var E1=K6;class x{constructor(W){this.result=W}get tweets(){return x.tweets(this.result)}static tweets(W){var J,Z;return(Z=(J=W.includes)===null||J===void 0?void 0:J.tweets)!==null&&Z!==void 0?Z:[]}tweetById(W){return x.tweetById(this.result,W)}static tweetById(W,J){return this.tweets(W).find((Z)=>Z.id===J)}retweet(W){return x.retweet(this.result,W)}static retweet(W,J){var Z;let $=((Z=J.referenced_tweets)!==null&&Z!==void 0?Z:[]).filter((Q)=>Q.type==="retweeted").map((Q)=>Q.id);return this.tweets(W).find((Q)=>$.includes(Q.id))}quote(W){return x.quote(this.result,W)}static quote(W,J){var Z;let $=((Z=J.referenced_tweets)!==null&&Z!==void 0?Z:[]).filter((Q)=>Q.type==="quoted").map((Q)=>Q.id);return this.tweets(W).find((Q)=>$.includes(Q.id))}repliedTo(W){return x.repliedTo(this.result,W)}static repliedTo(W,J){var Z;let $=((Z=J.referenced_tweets)!==null&&Z!==void 0?Z:[]).filter((Q)=>Q.type==="replied_to").map((Q)=>Q.id);return this.tweets(W).find((Q)=>$.includes(Q.id))}author(W){return x.author(this.result,W)}static author(W,J){let Z=J.author_id;return Z?this.users(W).find(($)=>$.id===Z):void 0}repliedToAuthor(W){return x.repliedToAuthor(this.result,W)}static repliedToAuthor(W,J){let Z=J.in_reply_to_user_id;return Z?this.users(W).find(($)=>$.id===Z):void 0}get users(){return x.users(this.result)}static users(W){var J,Z;return(Z=(J=W.includes)===null||J===void 0?void 0:J.users)!==null&&Z!==void 0?Z:[]}userById(W){return x.userById(this.result,W)}static userById(W,J){return this.users(W).find((Z)=>Z.id===J)}pinnedTweet(W){return x.pinnedTweet(this.result,W)}static pinnedTweet(W,J){return J.pinned_tweet_id?this.tweets(W).find((Z)=>Z.id===J.pinned_tweet_id):void 0}get media(){return x.media(this.result)}static media(W){var J,Z;return(Z=(J=W.includes)===null||J===void 0?void 0:J.media)!==null&&Z!==void 0?Z:[]}medias(W){return x.medias(this.result,W)}static medias(W,J){var Z,$;let Q=($=(Z=J.attachments)===null||Z===void 0?void 0:Z.media_keys)!==null&&$!==void 0?$:[];return this.media(W).filter((Y)=>Q.includes(Y.media_key))}get polls(){return x.polls(this.result)}static polls(W){var J,Z;return(Z=(J=W.includes)===null||J===void 0?void 0:J.polls)!==null&&Z!==void 0?Z:[]}poll(W){return x.poll(this.result,W)}static poll(W,J){var Z,$;let Q=($=(Z=J.attachments)===null||Z===void 0?void 0:Z.poll_ids)!==null&&$!==void 0?$:[];if(Q.length){let Y=Q[0];return this.polls(W).find((G)=>G.id===Y)}return}get places(){return x.places(this.result)}static places(W){var J,Z;return(Z=(J=W.includes)===null||J===void 0?void 0:J.places)!==null&&Z!==void 0?Z:[]}place(W){return x.place(this.result,W)}static place(W,J){var Z;let $=(Z=J.geo)===null||Z===void 0?void 0:Z.place_id;return $?this.places(W).find((Q)=>Q.id===$):void 0}listOwner(W){return x.listOwner(this.result,W)}static listOwner(W,J){let Z=J.owner_id;return Z?this.users(W).find(($)=>$.id===Z):void 0}spaceCreator(W){return x.spaceCreator(this.result,W)}static spaceCreator(W,J){let Z=J.creator_id;return Z?this.users(W).find(($)=>$.id===Z):void 0}spaceHosts(W){return x.spaceHosts(this.result,W)}static spaceHosts(W,J){var Z;let $=(Z=J.host_ids)!==null&&Z!==void 0?Z:[];return this.users(W).filter((Q)=>$.includes(Q.id))}spaceSpeakers(W){return x.spaceSpeakers(this.result,W)}static spaceSpeakers(W,J){var Z;let $=(Z=J.speaker_ids)!==null&&Z!==void 0?Z:[];return this.users(W).filter((Q)=>$.includes(Q.id))}spaceInvitedUsers(W){return x.spaceInvitedUsers(this.result,W)}static spaceInvitedUsers(W,J){var Z;let $=(Z=J.invited_user_ids)!==null&&Z!==void 0?Z:[];return this.users(W).filter((Q)=>$.includes(Q.id))}}class m1 extends j4{updateIncludes(W){if(W.errors){if(!this._realData.errors)this._realData.errors=[];this._realData.errors=[...this._realData.errors,...W.errors]}if(!W.includes)return;if(!this._realData.includes)this._realData.includes={};let J=this._realData.includes;for(let[Z,$]of Object.entries(W.includes)){if(!J[Z])J[Z]=[];J[Z]=[...J[Z],...$]}}assertUsable(){if(this.unusable)throw Error("Unable to use this paginator to fetch more data, as it does not contain any metadata. Check .errors property for more details.")}get meta(){return this._realData.meta}get includes(){var W;if(!((W=this._realData)===null||W===void 0?void 0:W.includes))return new x(this._realData);if(this._includesInstance)return this._includesInstance;return this._includesInstance=new x(this._realData)}get errors(){var W;return(W=this._realData.errors)!==null&&W!==void 0?W:[]}get unusable(){return this.errors.length>0&&!this._realData.meta&&!this._realData.data}}class T extends m1{refreshInstanceFromResult(W,J){var Z;let $=W.data,Q=(Z=$.data)!==null&&Z!==void 0?Z:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(J)this._realData.meta.result_count+=$.meta.result_count,this._realData.meta.next_token=$.meta.next_token,this._realData.data.push(...Q);else this._realData.meta.result_count+=$.meta.result_count,this._realData.meta.previous_token=$.meta.previous_token,this._realData.data.unshift(...Q);this.updateIncludes($)}getNextQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),pagination_token:this._realData.meta.next_token}}getPreviousQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),pagination_token:this._realData.meta.previous_token}}getPageLengthFromRequest(W){var J,Z;return(Z=(J=W.data.data)===null||J===void 0?void 0:J.length)!==null&&Z!==void 0?Z:0}isFetchLastOver(W){var J;return!((J=W.data.data)===null||J===void 0?void 0:J.length)||!this.canFetchNextPage(W.data)}canFetchNextPage(W){var J;return!!((J=W.meta)===null||J===void 0?void 0:J.next_token)}}class c4 extends m1{refreshInstanceFromResult(W,J){var Z;let $=W.data,Q=(Z=$.data)!==null&&Z!==void 0?Z:[];if(this._rateLimit=W.rateLimit,!this._realData.data)this._realData.data=[];if(J)this._realData.meta.oldest_id=$.meta.oldest_id,this._realData.meta.result_count+=$.meta.result_count,this._realData.meta.next_token=$.meta.next_token,this._realData.data.push(...Q);else this._realData.meta.newest_id=$.meta.newest_id,this._realData.meta.result_count+=$.meta.result_count,this._realData.data.unshift(...Q);this.updateIncludes($)}getNextQueryParams(W){this.assertUsable();let J={...this.injectQueryParams(W)};if(this._realData.meta.next_token)J.next_token=this._realData.meta.next_token;else{if(J.start_time)J.since_id=this.dateStringToSnowflakeId(J.start_time),delete J.start_time;if(J.end_time)delete J.end_time;J.until_id=this._realData.meta.oldest_id}return J}getPreviousQueryParams(W){return this.assertUsable(),{...this.injectQueryParams(W),since_id:this._realData.meta.newest_id}}getPageLengthFromRequest(W){var J,Z;return(Z=(J=W.data.data)===null||J===void 0?void 0:J.length)!==null&&Z!==void 0?Z:0}isFetchLastOver(W){var J;return!((J=W.data.data)===null||J===void 0?void 0:J.length)||!this.canFetchNextPage(W.data)}canFetchNextPage(W){return!!W.meta.next_token}getItemArray(){return this.tweets}dateStringToSnowflakeId(W){let J=BigInt("1288834974657"),Z=new Date(W);if(isNaN(Z.valueOf()))throw Error("Unable to convert start_time/end_time to a valid date. A ISO 8601 DateTime is excepted, please check your input.");return(BigInt(Z.valueOf())-J<<BigInt("22")).toString()}get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class Z1 extends T{refreshInstanceFromResult(W,J){super.refreshInstanceFromResult(W,J);let Z=W.data;if(J)this._realData.meta.oldest_id=Z.meta.oldest_id;else this._realData.meta.newest_id=Z.meta.newest_id}getItemArray(){return this.tweets}get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class u4 extends c4{constructor(){super(...arguments);this._endpoint="tweets/search/recent"}}class d4 extends c4{constructor(){super(...arguments);this._endpoint="tweets/search/all"}}class p4 extends Z1{constructor(){super(...arguments);this._endpoint="tweets/:id/quote_tweets"}}class l4 extends Z1{constructor(){super(...arguments);this._endpoint="users/:id/timelines/reverse_chronological"}}class n4 extends Z1{constructor(){super(...arguments);this._endpoint="users/:id/tweets"}}class i4 extends Z1{constructor(){super(...arguments);this._endpoint="users/:id/mentions"}}class o4 extends Z1{constructor(){super(...arguments);this._endpoint="users/:id/bookmarks"}}class s4 extends T{get tweets(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}getItemArray(){return this.tweets}}class a4 extends s4{constructor(){super(...arguments);this._endpoint="users/:id/liked_tweets"}}class t4 extends s4{constructor(){super(...arguments);this._endpoint="lists/:id/tweets"}}class V extends T{getItemArray(){return this.users}get users(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class r4 extends V{constructor(){super(...arguments);this._endpoint="users/:id/blocking"}}class e4 extends V{constructor(){super(...arguments);this._endpoint="users/:id/muting"}}class W0 extends V{constructor(){super(...arguments);this._endpoint="users/:id/followers"}}class J0 extends V{constructor(){super(...arguments);this._endpoint="users/:id/following"}}class Z0 extends V{constructor(){super(...arguments);this._endpoint="lists/:id/members"}}class $0 extends V{constructor(){super(...arguments);this._endpoint="lists/:id/followers"}}class Q0 extends V{constructor(){super(...arguments);this._endpoint="tweets/:id/liking_users"}}class Y0 extends V{constructor(){super(...arguments);this._endpoint="tweets/:id/retweeted_by"}}class c1 extends T{getItemArray(){return this.lists}get lists(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class G0 extends c1{constructor(){super(...arguments);this._endpoint="users/:id/owned_lists"}}class K0 extends c1{constructor(){super(...arguments);this._endpoint="users/:id/list_memberships"}}class z0 extends c1{constructor(){super(...arguments);this._endpoint="users/:id/followed_lists"}}class $1 extends f{constructor(){super(...arguments);this._prefix=o}}class u1 extends T{getItemArray(){return this.events}get events(){var W;return(W=this._realData.data)!==null&&W!==void 0?W:[]}get meta(){return super.meta}}class X0 extends u1{constructor(){super(...arguments);this._endpoint="dm_events"}}class B0 extends u1{constructor(){super(...arguments);this._endpoint="dm_conversations/with/:participant_id/dm_events"}}class M0 extends u1{constructor(){super(...arguments);this._endpoint="dm_conversations/:dm_conversation_id/dm_events"}}class Q1 extends f{constructor(){super(...arguments);this._prefix=y}get labs(){if(this._labs)return this._labs;return this._labs=new $1(this)}async search(W,J={}){let Z=typeof W==="string"?{...J,query:W}:{...W},$=await this.get("tweets/search/recent",Z,{fullResponse:!0});return new u4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}async searchAll(W,J={}){let Z={...J,query:W},$=await this.get("tweets/search/all",Z,{fullResponse:!0});return new d4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:Z})}singleTweet(W,J={}){return this.get("tweets/:id",J,{params:{id:W}})}tweets(W,J={}){return this.get("tweets",{ids:W,...J})}tweetCountRecent(W,J={}){return this.get("tweets/counts/recent",{query:W,...J})}tweetCountAll(W,J={}){return this.get("tweets/counts/all",{query:W,...J})}async tweetRetweetedBy(W,J={}){let{asPaginator:Z,...$}=J,Q=await this.get("tweets/:id/retweeted_by",$,{fullResponse:!0,params:{id:W}});if(!Z)return Q.data;return new Y0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$,sharedParams:{id:W}})}async tweetLikedBy(W,J={}){let{asPaginator:Z,...$}=J,Q=await this.get("tweets/:id/liking_users",$,{fullResponse:!0,params:{id:W}});if(!Z)return Q.data;return new Q0({realData:Q.data,rateLimit:Q.rateLimit,instance:this,queryParams:$,sharedParams:{id:W}})}async homeTimeline(W={}){let J=await this.getCurrentUserV2Object(),Z=await this.get("users/:id/timelines/reverse_chronological",W,{fullResponse:!0,params:{id:J.data.id}});return new l4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:W,sharedParams:{id:J.data.id}})}async userTimeline(W,J={}){let Z=await this.get("users/:id/tweets",J,{fullResponse:!0,params:{id:W}});return new n4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J,sharedParams:{id:W}})}async userMentionTimeline(W,J={}){let Z=await this.get("users/:id/mentions",J,{fullResponse:!0,params:{id:W}});return new i4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J,sharedParams:{id:W}})}async quotes(W,J={}){let Z=await this.get("tweets/:id/quote_tweets",J,{fullResponse:!0,params:{id:W}});return new p4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:J,sharedParams:{id:W}})}async bookmarks(W={}){let J=await this.getCurrentUserV2Object(),Z=await this.get("users/:id/bookmarks",W,{fullResponse:!0,params:{id:J.data.id}});return new o4({realData:Z.data,rateLimit:Z.rateLimit,instance:this,queryParams:W,sharedParams:{id:J.data.id}})}me(W={}){return this.get("users/me",W)}user(W,J={}){return this.get("users/:id",J,{params:{id:W}})}users(W,J={}){let Z=Array.isArray(W)?W.join(","):W;return this.get("users",{...J,ids:Z})}userByUsername(W,J={}){return this.get("users/by/username/:username",J,{params:{username:W}})}usersByUsernames(W,J={}){return W=Array.isArray(W)?W.join(","):W,this.get("users/by",{...J,usernames:W})}async followers(W,J={}){let{asPaginator:Z,...$}=J,Q={id:W};if(!Z)return this.get("users/:id/followers",$,{params:Q});let Y=await this.get("users/:id/followers",$,{fullResponse:!0,params:Q});return new W0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:$,sharedParams:Q})}async following(W,J={}){let{asPaginator:Z,...$}=J,Q={id:W};if(!Z)return this.get("users/:id/following",$,{params:Q});let Y=await this.get("users/:id/following",$,{fullResponse:!0,params:Q});return new J0({realData:Y.data,rateLimit:Y.rateLimit,instance:this,queryParams:$,sharedParams:Q})}async userLikedTweets(W,J={}){let Z={id:W},$=await this.get("users/:id/liked_tweets",J,{fullResponse:!0,params:Z});return new a4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async userBlockingUsers(W,J={}){let Z={id:W},$=await this.get("users/:id/blocking",J,{fullResponse:!0,params:Z});return new r4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async userMutingUsers(W,J={}){let Z={id:W},$=await this.get("users/:id/muting",J,{fullResponse:!0,params:Z});return new e4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}list(W,J={}){return this.get("lists/:id",J,{params:{id:W}})}async listsOwned(W,J={}){let Z={id:W},$=await this.get("users/:id/owned_lists",J,{fullResponse:!0,params:Z});return new G0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async listMemberships(W,J={}){let Z={id:W},$=await this.get("users/:id/list_memberships",J,{fullResponse:!0,params:Z});return new K0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async listFollowed(W,J={}){let Z={id:W},$=await this.get("users/:id/followed_lists",J,{fullResponse:!0,params:Z});return new z0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async listTweets(W,J={}){let Z={id:W},$=await this.get("lists/:id/tweets",J,{fullResponse:!0,params:Z});return new t4({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async listMembers(W,J={}){let Z={id:W},$=await this.get("lists/:id/members",J,{fullResponse:!0,params:Z});return new Z0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async listFollowers(W,J={}){let Z={id:W},$=await this.get("lists/:id/followers",J,{fullResponse:!0,params:Z});return new $0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async listDmEvents(W={}){let J=await this.get("dm_events",W,{fullResponse:!0});return new X0({realData:J.data,rateLimit:J.rateLimit,instance:this,queryParams:{...W}})}async listDmEventsWithParticipant(W,J={}){let Z={participant_id:W},$=await this.get("dm_conversations/with/:participant_id/dm_events",J,{fullResponse:!0,params:Z});return new B0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}async listDmEventsOfConversation(W,J={}){let Z={dm_conversation_id:W},$=await this.get("dm_conversations/:dm_conversation_id/dm_events",J,{fullResponse:!0,params:Z});return new M0({realData:$.data,rateLimit:$.rateLimit,instance:this,queryParams:{...J},sharedParams:Z})}space(W,J={}){return this.get("spaces/:id",J,{params:{id:W}})}spaces(W,J={}){return this.get("spaces",{ids:W,...J})}spacesByCreators(W,J={}){return this.get("spaces/by/creator_ids",{user_ids:W,...J})}searchSpaces(W){return this.get("spaces/search",W)}spaceBuyers(W,J={}){return this.get("spaces/:id/buyers",J,{params:{id:W}})}spaceTweets(W,J={}){return this.get("spaces/:id/tweets",J,{params:{id:W}})}searchStream({autoConnect:W,...J}={}){return this.getStream("tweets/search/stream",J,{payloadIsError:w1,autoConnect:W})}streamRules(W={}){return this.get("tweets/search/stream/rules",W)}updateStreamRules(W,J={}){return this.post("tweets/search/stream/rules",W,{query:J})}sampleStream({autoConnect:W,...J}={}){return this.getStream("tweets/sample/stream",J,{payloadIsError:w1,autoConnect:W})}sample10Stream({autoConnect:W,...J}={}){return this.getStream("tweets/sample10/stream",J,{payloadIsError:w1,autoConnect:W})}complianceJobs(W){return this.get("compliance/jobs",W)}complianceJob(W){return this.get("compliance/jobs/:id",void 0,{params:{id:W}})}async sendComplianceJob(W){let J=await this.post("compliance/jobs",{type:W.type,name:W.name}),Z=W.ids instanceof Buffer?W.ids:Buffer.from(W.ids.join(`
|
|
69
69
|
`));return await this.put(J.data.upload_url,Z,{forceBodyMode:"raw",enableAuth:!1,headers:{"Content-Type":"text/plain"},prefix:""}),J}async complianceJobResult(W){let J=W;while(J.status!=="complete"){if(J.status==="expired"||J.status==="failed")throw Error("Job failed to be completed.");await new Promise(($)=>setTimeout($,3500)),J=(await this.complianceJob(W.id)).data}return(await this.get(W.download_url,void 0,{enableAuth:!1,prefix:""})).trim().split(`
|
|
70
|
-
`).filter(($)=>$).map(($)=>JSON.parse($))}async usage(W={}){return this.get("usage/tweets",W)}community(W,J={}){return this.get("communities/:id",J,{params:{id:W}})}searchCommunities(W,J={}){return this.get("communities/search",{query:W,...J})}}class Q1 extends $1{constructor(){super(...arguments);this._prefix=o}get readOnly(){return this}}class G1 extends Y1{constructor(){super(...arguments);this._prefix=y}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new Q1(this)}hideReply(W,J){return this.put("tweets/:id/hidden",{hidden:J},{params:{id:W}})}like(W,J){return this.post("users/:id/likes",{tweet_id:J},{params:{id:W}})}unlike(W,J){return this.delete("users/:id/likes/:tweet_id",void 0,{params:{id:W,tweet_id:J}})}retweet(W,J){return this.post("users/:id/retweets",{tweet_id:J},{params:{id:W}})}unretweet(W,J){return this.delete("users/:id/retweets/:tweet_id",void 0,{params:{id:W,tweet_id:J}})}tweet(W,J={}){if(typeof W==="object")J=W;else J={text:W,...J};return this.post("tweets",J)}async uploadMedia(W,J,Z=1048576){let $=J.media_category;if(!J.media_category){if(J.media_type.includes("gif"))$="tweet_gif";else if(J.media_type.includes("image"))$="tweet_image";else if(J.media_type.includes("video"))$="tweet_video"}let Y={additional_owners:J.additional_owners,media_type:J.media_type,total_bytes:W.length,media_category:$},G=(await this.post("media/upload/initialize",Y)).data.id,K=Math.ceil(W.length/Z),z=new Uint8Array(W);for(let B=0;B<K;B++){let M=B*Z,D=Math.min(M+Z,W.length),S=z.slice(M,D),H=Buffer.from(S),m={segment_index:B,media:H};await this.post(`media/upload/${G}/append`,m,{forceBodyMode:"form-data"})}if((await this.post(`media/upload/${G}/finalize`)).data.processing_info)await this.waitForMediaProcessing(G);return G}async waitForMediaProcessing(W){var J;let $=(await this.get("media/upload",{command:"STATUS",media_id:W})).data.processing_info;if(!$)return;switch($.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${(J=$.error)===null||J===void 0?void 0:J.message}`);case"pending":case"in_progress":{let Y=$===null||$===void 0?void 0:$.check_after_secs;if(Y&&Y>0)await new Promise((Q)=>setTimeout(Q,Y*1000)),await this.waitForMediaProcessing(W)}}}createMediaMetadata(W,J){return this.post("media/metadata",{id:W,metadata:J})}reply(W,J,Z={}){var $;let Y={in_reply_to_tweet_id:J,...($=Z.reply)!==null&&$!==void 0?$:{}};return this.post("tweets",{text:W,...Z,reply:Y})}quote(W,J,Z={}){return this.tweet(W,{...Z,quote_tweet_id:J})}async tweetThread(W){var J,Z;let $=[];for(let Y of W){let Q=$.length?$[$.length-1]:null,G={...typeof Y==="string"?{text:Y}:Y},K=Q?Q.data.id:(J=G.reply)===null||J===void 0?void 0:J.in_reply_to_tweet_id,z=(Z=G.text)!==null&&Z!==void 0?Z:"";if(K)$.push(await this.reply(z,K,G));else $.push(await this.tweet(z,G))}return $}deleteTweet(W){return this.delete("tweets/:id",void 0,{params:{id:W}})}async bookmark(W){let J=await this.getCurrentUserV2Object();return this.post("users/:id/bookmarks",{tweet_id:W},{params:{id:J.data.id}})}async deleteBookmark(W){let J=await this.getCurrentUserV2Object();return this.delete("users/:id/bookmarks/:tweet_id",void 0,{params:{id:J.data.id,tweet_id:W}})}follow(W,J){return this.post("users/:id/following",{target_user_id:J},{params:{id:W}})}unfollow(W,J){return this.delete("users/:source_user_id/following/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:J}})}block(W,J){return this.post("users/:id/blocking",{target_user_id:J},{params:{id:W}})}unblock(W,J){return this.delete("users/:source_user_id/blocking/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:J}})}mute(W,J){return this.post("users/:id/muting",{target_user_id:J},{params:{id:W}})}unmute(W,J){return this.delete("users/:source_user_id/muting/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:J}})}createList(W){return this.post("lists",W)}updateList(W,J={}){return this.put("lists/:id",J,{params:{id:W}})}removeList(W){return this.delete("lists/:id",void 0,{params:{id:W}})}addListMember(W,J){return this.post("lists/:id/members",{user_id:J},{params:{id:W}})}removeListMember(W,J){return this.delete("lists/:id/members/:user_id",void 0,{params:{id:W,user_id:J}})}subscribeToList(W,J){return this.post("users/:id/followed_lists",{list_id:J},{params:{id:W}})}unsubscribeOfList(W,J){return this.delete("users/:id/followed_lists/:list_id",void 0,{params:{id:W,list_id:J}})}pinList(W,J){return this.post("users/:id/pinned_lists",{list_id:J},{params:{id:W}})}unpinList(W,J){return this.delete("users/:id/pinned_lists/:list_id",void 0,{params:{id:W,list_id:J}})}sendDmInConversation(W,J){return this.post("dm_conversations/:dm_conversation_id/messages",J,{params:{dm_conversation_id:W}})}sendDmToParticipant(W,J){return this.post("dm_conversations/with/:participant_id/messages",J,{params:{participant_id:W}})}createDmConversation(W){return this.post("dm_conversations",W)}}class z6 extends Q1{constructor(){super(...arguments);this._prefix=o}get readWrite(){return this}}var X6=z6;class B6 extends G1{constructor(){super(...arguments);this._prefix=y}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new X6(this)}}var M6=B6;class O1 extends g{get v1(){if(this._v1)return this._v1;return this._v1=new W1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new Y1(this)}async currentUser(W=!1){return await this.getCurrentUserObject(W)}async currentUserV2(W=!1){return await this.getCurrentUserV2Object(W)}search(W,J){return this.v2.search(W,J)}async generateAuthLink(W="oob",{authAccessType:J,linkMode:Z="authenticate",forceLogin:$,screenName:Y}={}){let Q=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:W,x_auth_access_type:J}),G=`https://api.x.com/oauth/${Z}?oauth_token=${encodeURIComponent(Q.oauth_token)}`;if($!==void 0)G+=`&force_login=${encodeURIComponent($)}`;if(Y!==void 0)G+=`&screen_name=${encodeURIComponent(Y)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:G,oauthResult:Q});return{url:G,...Q}}async login(W){let J=this.getActiveTokens();if(J.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept OAuth 1.0 login");let Z=await this.post("https://api.x.com/oauth/access_token",{oauth_token:J.accessToken,oauth_verifier:W}),$=new this.constructor({appKey:J.appKey,appSecret:J.appSecret,accessToken:Z.oauth_token,accessSecret:Z.oauth_token_secret},this._requestMaker.clientSettings);return{accessToken:Z.oauth_token,accessSecret:Z.oauth_token_secret,userId:Z.user_id,screenName:Z.screen_name,client:$}}async appLogin(){let W=this.getActiveTokens();if(W.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept app-only login");let Z=await new this.constructor({username:W.appKey,password:W.appSecret},this._requestMaker.clientSettings).post("https://api.x.com/oauth2/token",{grant_type:"client_credentials"});return new this.constructor(Z.access_token,this._requestMaker.clientSettings)}generateOAuth2AuthLink(W,J={}){var Z,$;if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. You can find your client ID in Twitter Developer Portal. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let Y=(Z=J.state)!==null&&Z!==void 0?Z:n.generateRandomString(32),Q=n.getCodeVerifier(),G=n.getCodeChallengeFromVerifier(Q),K=($=J.scope)!==null&&$!==void 0?$:"",z=Array.isArray(K)?K.join(" "):K,X=new URL("https://x.com/i/oauth2/authorize"),B={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:W,state:Y,code_challenge:G,code_challenge_method:"s256",scope:z};R.addQueryParamsToUrl(X,B);let M={url:X.toString(),state:Y,codeVerifier:Q,codeChallenge:G};if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:M,redirectUri:W});return M}async loginWithOAuth2({code:W,codeVerifier:J,redirectUri:Z}){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let $=await this.post("https://api.x.com/2/oauth2/token",{code:W,code_verifier:J,redirect_uri:Z,grant_type:"authorization_code",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult($)}async refreshOAuth2Token(W){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let J=await this.post("https://api.x.com/2/oauth2/token",{refresh_token:W,grant_type:"refresh_token",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(J)}async revokeOAuth2Token(W,J="access_token"){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");return await this.post("https://api.x.com/2/oauth2/revoke",{client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret,token:W,token_type_hint:J})}parseOAuth2AccessTokenResult(W){let J=new this.constructor(W.access_token,this._requestMaker.clientSettings),Z=W.scope.split(" ").filter(($)=>$);return{client:J,expiresIn:W.expires_in,accessToken:W.access_token,scope:Z,refreshToken:W.refresh_token}}}class R1 extends O1{get v1(){if(this._v1)return this._v1;return this._v1=new J1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new G1(this)}get readOnly(){return this}}class p1 extends f{constructor(){super(...arguments);this._prefix=s}}class d1 extends p1{constructor(){super(...arguments);this._prefix=s}get readOnly(){return this}}class l1 extends f{constructor(){super(...arguments);this._prefix=a}}class n1 extends l1{constructor(){super(...arguments);this._prefix=a}get readOnly(){return this}}class j6 extends n1{constructor(){super(...arguments);this._prefix=a}get readWrite(){return this}}var N6=j6;class x6 extends d1{constructor(){super(...arguments);this._prefix=s}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new N6(this)}}var L6=x6;class j0 extends R1{get v1(){if(this._v1)return this._v1;return this._v1=new E1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new M6(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new L6(this)}static getErrors(W){var J;if(typeof W!=="object")return[];if(!("data"in W))return[];return(J=W.data.errors)!==null&&J!==void 0?J:[]}static getProfileImageInSize(W,J){let Z=W.split("/").pop(),$=["normal","bigger","mini"],Y=W;for(let G of $)if(Z.includes(`_${G}`)){Y=W.replace(`_${G}`,"");break}if(J==="original")return Y;let Q=Y.lastIndexOf(".");if(Q!==-1){let G=Y.slice(Q+1);return Y.slice(0,Q)+"_"+J+"."+G}else return Y+"_"+J}}var a6={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class D6 extends j1{config;client;constructor(W={}){super();this.config={...a6,...W},this.client=new j0({clientId:this.config.clientId,clientSecret:this.config.clientSecret})}redirectUri(){return`${process.env.HOST_NAME??""}${this.config.redirectPath}`}getRedirectUrl(W,J){if(!J)throw Error("XOAuthProvider needs the state and PKCE challenge gemi passes.");let Z=new URL("https://x.com/i/oauth2/authorize"),$={response_type:"code",client_id:this.config.clientId,redirect_uri:this.redirectUri(),state:J.state,code_challenge:J.codeChallenge,code_challenge_method:J.codeChallengeMethod,scope:this.config.scope.join(" ")};for(let[Y,Q]of Object.entries($))Z.searchParams.set(Y,Q);return Z.toString()}async onCallback(W,J){let Z=W.search.get("code");if(!Z)throw new q("missing_code");if(!J?.codeVerifier)throw new q("invalid_state");let $;try{$=await this.client.loginWithOAuth2({code:Z,codeVerifier:J.codeVerifier,redirectUri:this.redirectUri()})}catch(X){throw console.error("X OAuth error: token exchange failed",X),new q("exchange_failed")}let{data:Y}=await $.client.v2.me({"user.fields":["name","username","entities"]}),{name:Q,email:G,id:K="",username:z}=Y??{};return{name:Q,email:G,username:z,providerId:K}}}class N0{describe;rollout;when;serverOnly;salt;constructor(W={}){if(W.rollout!==void 0){let{rollout:J}=W;if(!Number.isFinite(J)||J<0||J>100)throw Error(`A feature's \`rollout\` must be a number between 0 and 100, received ${String(J)}.`)}this.describe=W.describe,this.rollout=W.rollout,this.when=W.when,this.serverOnly=W.serverOnly??!1,this.salt=W.salt}}function t6(W={}){return new N0(W)}class F6 extends x0{rows=new Map;constructor(W={}){super();for(let[J,Z]of Object.entries(W))this.rows.set(J,{key:J,active:Z})}async load(){return[...this.rows.values()].map((W)=>({...W}))}async write(W,J,Z){return this.rows.set(W,{key:W,active:J,updatedBy:Z.actor,updatedAt:new Date}),{actorRecorded:!0}}}export{dW as viewRouteConfigDefaults,q5 as translationConfigDefaults,i1 as toRangeHeaderValue,bW as subjectFor,R5 as scheduleConfigDefaults,a1 as resolveRange,e5 as redisConfigDefaults,a5 as rateLimiterConfigDefaults,j5 as queueConfigDefaults,K1 as parseContentRange,ZW as mintSessionToken,e6 as middlewareConfigDefaults,rW as mailConfigDefaults,n5 as logConfigDefaults,JW as isSessionToken,CW as inRollout,EW as imageConfigDefaults,XW as filesystemConfigDefaults,g5 as featuresConfigDefaults,_5 as eventConfigDefaults,IW as evaluateFeature,FW as encodeCursor,T5 as discoverListeners,C5 as discoverJobs,I5 as discoverCronJobs,b5 as discoverCommands,V5 as defineTranslationConfig,O5 as defineScheduleConfig,uW as defineRouteConfig,r5 as defineRedisConfig,s5 as defineRateLimiterConfig,M5 as defineQueueConfig,r6 as defineMiddlewareConfig,tW as defineMailConfig,l5 as defineLogConfig,gW as defineImageConfig,zW as defineFilesystemConfig,h5 as defineFeaturesConfig,t6 as defineFeature,f5 as defineEventConfig,F5 as defineCommandConfig,U5 as defineCommand,LW as defineChangeFeedConfig,QW as defineAuthConfig,HW as decodeCursor,H5 as commandConfigDefaults,DW as changeFeedConfigDefaults,kW as bucketOf,_W as bucketKey,z4 as bearerToken,GW as authConfigDefaults,o1 as assertDeletablePrefix,pW as apiRouteConfigDefaults,D6 as XOAuthProvider,iW as ViewRouteDispatcher,VW as UndeclaredFeatureError,F6 as StaticFeatureFlagSource,hW as Sharp,K5 as Scheduler,y5 as ScheduleServiceProvider,WW as SESSION_TOKEN_PREFIX,F0 as S3Driver,J8 as RouteServiceProvider,aW as ResendDriver,W8 as RedisServiceProvider,R0 as RedisRateLimiter,_1 as RedisManager,t5 as RateLimiterServiceProvider,t1 as RateLimiterDriver,$W as RateLimiter,i as RangeNotSatisfiableError,v5 as QueueServiceProvider,x5 as QueueManager,j1 as OAuthProvider,q as OAuthCallbackError,o5 as MiddlewareServiceProvider,cW as MiddlewareRegistry,N5 as MemoryQueueDriver,E0 as MemoryMcpOAuthStore,G5 as MemoryLockStore,SW as MemoryChangeFeedDriver,J5 as McpToolError,$5 as McpRegistry,h0 as McpOAuthServer,Q5 as McpHttpServer,Z5 as McpCallRefusedError,Y5 as McpApiKeyResolver,m5 as MailServiceProvider,eW as MailManager,i5 as LogServiceProvider,MW as LogManager,xW as LockManager,jW as LockLostError,k5 as Listener,d5 as KernelIdServiceProvider,lW as KernelId,B5 as Job,YW as InMemoryRateLimiter,p5 as ImageServiceProvider,AW as ImageOptimizationDriver,mW as ImageManager,nW as ISLAND_LOADER_CSP_HASH,NW as HeldLock,u0 as GoogleOAuthProvider,u5 as FilesystemServiceProvider,BW as FilesystemManager,KW as FileSystemDriver,z1 as FileStorageDriver,c as FileNotFoundError,E5 as FeaturesServiceProvider,wW as FeatureSourceReadOnlyError,qW as FeatureScope,TW as FeatureReloadError,PW as FeatureModelMissingError,yW as FeatureManager,vW as FeatureFlagStore,x0 as FeatureFlagSource,N0 as Feature,c5 as EventServiceProvider,k as EventManager,c0 as Event,sW as EmailDriver,X5 as DatabaseQueueDriver,z5 as DatabaseLockStore,A5 as DatabaseFeatureFlagSource,UW as DatabaseChangeFeedDriver,W5 as DEFAULT_MCP_SCOPE,S5 as CronJob,Z8 as CommandRegistry,L5 as CommandFailed,D5 as Command,fW as ChangeFeedSubscription,P5 as ChangeFeedServiceProvider,RW as ChangeFeedManager,OW as ChangeFeedFullError,k1 as CONSENT_PAGE_HEADERS,U0 as AzureBlobDriver,w5 as AuthServiceProvider,b1 as AuthManager,oW as ApiRouteDispatcher};
|
|
70
|
+
`).filter(($)=>$).map(($)=>JSON.parse($))}async usage(W={}){return this.get("usage/tweets",W)}community(W,J={}){return this.get("communities/:id",J,{params:{id:W}})}searchCommunities(W,J={}){return this.get("communities/search",{query:W,...J})}}class Y1 extends $1{constructor(){super(...arguments);this._prefix=o}get readOnly(){return this}}class G1 extends Q1{constructor(){super(...arguments);this._prefix=y}get readOnly(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new Y1(this)}hideReply(W,J){return this.put("tweets/:id/hidden",{hidden:J},{params:{id:W}})}like(W,J){return this.post("users/:id/likes",{tweet_id:J},{params:{id:W}})}unlike(W,J){return this.delete("users/:id/likes/:tweet_id",void 0,{params:{id:W,tweet_id:J}})}retweet(W,J){return this.post("users/:id/retweets",{tweet_id:J},{params:{id:W}})}unretweet(W,J){return this.delete("users/:id/retweets/:tweet_id",void 0,{params:{id:W,tweet_id:J}})}tweet(W,J={}){if(typeof W==="object")J=W;else J={text:W,...J};return this.post("tweets",J)}async uploadMedia(W,J,Z=1048576){let $=J.media_category;if(!J.media_category){if(J.media_type.includes("gif"))$="tweet_gif";else if(J.media_type.includes("image"))$="tweet_image";else if(J.media_type.includes("video"))$="tweet_video"}let Q={additional_owners:J.additional_owners,media_type:J.media_type,total_bytes:W.length,media_category:$},G=(await this.post("media/upload/initialize",Q)).data.id,K=Math.ceil(W.length/Z),z=new Uint8Array(W);for(let B=0;B<K;B++){let M=B*Z,D=Math.min(M+Z,W.length),S=z.slice(M,D),H=Buffer.from(S),m={segment_index:B,media:H};await this.post(`media/upload/${G}/append`,m,{forceBodyMode:"form-data"})}if((await this.post(`media/upload/${G}/finalize`)).data.processing_info)await this.waitForMediaProcessing(G);return G}async waitForMediaProcessing(W){var J;let $=(await this.get("media/upload",{command:"STATUS",media_id:W})).data.processing_info;if(!$)return;switch($.state){case"succeeded":return;case"failed":throw Error(`Media processing failed: ${(J=$.error)===null||J===void 0?void 0:J.message}`);case"pending":case"in_progress":{let Q=$===null||$===void 0?void 0:$.check_after_secs;if(Q&&Q>0)await new Promise((Y)=>setTimeout(Y,Q*1000)),await this.waitForMediaProcessing(W)}}}createMediaMetadata(W,J){return this.post("media/metadata",{id:W,metadata:J})}reply(W,J,Z={}){var $;let Q={in_reply_to_tweet_id:J,...($=Z.reply)!==null&&$!==void 0?$:{}};return this.post("tweets",{text:W,...Z,reply:Q})}quote(W,J,Z={}){return this.tweet(W,{...Z,quote_tweet_id:J})}async tweetThread(W){var J,Z;let $=[];for(let Q of W){let Y=$.length?$[$.length-1]:null,G={...typeof Q==="string"?{text:Q}:Q},K=Y?Y.data.id:(J=G.reply)===null||J===void 0?void 0:J.in_reply_to_tweet_id,z=(Z=G.text)!==null&&Z!==void 0?Z:"";if(K)$.push(await this.reply(z,K,G));else $.push(await this.tweet(z,G))}return $}deleteTweet(W){return this.delete("tweets/:id",void 0,{params:{id:W}})}async bookmark(W){let J=await this.getCurrentUserV2Object();return this.post("users/:id/bookmarks",{tweet_id:W},{params:{id:J.data.id}})}async deleteBookmark(W){let J=await this.getCurrentUserV2Object();return this.delete("users/:id/bookmarks/:tweet_id",void 0,{params:{id:J.data.id,tweet_id:W}})}follow(W,J){return this.post("users/:id/following",{target_user_id:J},{params:{id:W}})}unfollow(W,J){return this.delete("users/:source_user_id/following/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:J}})}block(W,J){return this.post("users/:id/blocking",{target_user_id:J},{params:{id:W}})}unblock(W,J){return this.delete("users/:source_user_id/blocking/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:J}})}mute(W,J){return this.post("users/:id/muting",{target_user_id:J},{params:{id:W}})}unmute(W,J){return this.delete("users/:source_user_id/muting/:target_user_id",void 0,{params:{source_user_id:W,target_user_id:J}})}createList(W){return this.post("lists",W)}updateList(W,J={}){return this.put("lists/:id",J,{params:{id:W}})}removeList(W){return this.delete("lists/:id",void 0,{params:{id:W}})}addListMember(W,J){return this.post("lists/:id/members",{user_id:J},{params:{id:W}})}removeListMember(W,J){return this.delete("lists/:id/members/:user_id",void 0,{params:{id:W,user_id:J}})}subscribeToList(W,J){return this.post("users/:id/followed_lists",{list_id:J},{params:{id:W}})}unsubscribeOfList(W,J){return this.delete("users/:id/followed_lists/:list_id",void 0,{params:{id:W,list_id:J}})}pinList(W,J){return this.post("users/:id/pinned_lists",{list_id:J},{params:{id:W}})}unpinList(W,J){return this.delete("users/:id/pinned_lists/:list_id",void 0,{params:{id:W,list_id:J}})}sendDmInConversation(W,J){return this.post("dm_conversations/:dm_conversation_id/messages",J,{params:{dm_conversation_id:W}})}sendDmToParticipant(W,J){return this.post("dm_conversations/with/:participant_id/messages",J,{params:{participant_id:W}})}createDmConversation(W){return this.post("dm_conversations",W)}}class z6 extends Y1{constructor(){super(...arguments);this._prefix=o}get readWrite(){return this}}var X6=z6;class B6 extends G1{constructor(){super(...arguments);this._prefix=y}get readWrite(){return this}get labs(){if(this._labs)return this._labs;return this._labs=new X6(this)}}var M6=B6;class O1 extends g{get v1(){if(this._v1)return this._v1;return this._v1=new W1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new Q1(this)}async currentUser(W=!1){return await this.getCurrentUserObject(W)}async currentUserV2(W=!1){return await this.getCurrentUserV2Object(W)}search(W,J){return this.v2.search(W,J)}async generateAuthLink(W="oob",{authAccessType:J,linkMode:Z="authenticate",forceLogin:$,screenName:Q}={}){let Y=await this.post("https://api.x.com/oauth/request_token",{oauth_callback:W,x_auth_access_type:J}),G=`https://api.x.com/oauth/${Z}?oauth_token=${encodeURIComponent(Y.oauth_token)}`;if($!==void 0)G+=`&force_login=${encodeURIComponent($)}`;if(Q!==void 0)G+=`&screen_name=${encodeURIComponent(Q)}`;if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth1RequestToken",{client:this._requestMaker,url:G,oauthResult:Y});return{url:G,...Y}}async login(W){let J=this.getActiveTokens();if(J.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept OAuth 1.0 login");let Z=await this.post("https://api.x.com/oauth/access_token",{oauth_token:J.accessToken,oauth_verifier:W}),$=new this.constructor({appKey:J.appKey,appSecret:J.appSecret,accessToken:Z.oauth_token,accessSecret:Z.oauth_token_secret},this._requestMaker.clientSettings);return{accessToken:Z.oauth_token,accessSecret:Z.oauth_token_secret,userId:Z.user_id,screenName:Z.screen_name,client:$}}async appLogin(){let W=this.getActiveTokens();if(W.type!=="oauth-1.0a")throw Error("You must setup TwitterApi instance with consumer keys to accept app-only login");let Z=await new this.constructor({username:W.appKey,password:W.appSecret},this._requestMaker.clientSettings).post("https://api.x.com/oauth2/token",{grant_type:"client_credentials"});return new this.constructor(Z.access_token,this._requestMaker.clientSettings)}generateOAuth2AuthLink(W,J={}){var Z,$;if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. You can find your client ID in Twitter Developer Portal. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let Q=(Z=J.state)!==null&&Z!==void 0?Z:n.generateRandomString(32),Y=n.getCodeVerifier(),G=n.getCodeChallengeFromVerifier(Y),K=($=J.scope)!==null&&$!==void 0?$:"",z=Array.isArray(K)?K.join(" "):K,X=new URL("https://x.com/i/oauth2/authorize"),B={response_type:"code",client_id:this._requestMaker.clientId,redirect_uri:W,state:Q,code_challenge:G,code_challenge_method:"s256",scope:z};R.addQueryParamsToUrl(X,B);let M={url:X.toString(),state:Q,codeVerifier:Y,codeChallenge:G};if(this._requestMaker.hasPlugins())this._requestMaker.applyPluginMethod("onOAuth2RequestToken",{client:this._requestMaker,result:M,redirectUri:W});return M}async loginWithOAuth2({code:W,codeVerifier:J,redirectUri:Z}){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let $=await this.post("https://api.x.com/2/oauth2/token",{code:W,code_verifier:J,redirect_uri:Z,grant_type:"authorization_code",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult($)}async refreshOAuth2Token(W){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");let J=await this.post("https://api.x.com/2/oauth2/token",{refresh_token:W,grant_type:"refresh_token",client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret});return this.parseOAuth2AccessTokenResult(J)}async revokeOAuth2Token(W,J="access_token"){if(!this._requestMaker.clientId)throw Error("Twitter API instance is not initialized with client ID. Please build an instance with: new TwitterApi({ clientId: '<yourClientId>' })");return await this.post("https://api.x.com/2/oauth2/revoke",{client_id:this._requestMaker.clientId,client_secret:this._requestMaker.clientSecret,token:W,token_type_hint:J})}parseOAuth2AccessTokenResult(W){let J=new this.constructor(W.access_token,this._requestMaker.clientSettings),Z=W.scope.split(" ").filter(($)=>$);return{client:J,expiresIn:W.expires_in,accessToken:W.access_token,scope:Z,refreshToken:W.refresh_token}}}class R1 extends O1{get v1(){if(this._v1)return this._v1;return this._v1=new J1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new G1(this)}get readOnly(){return this}}class d1 extends f{constructor(){super(...arguments);this._prefix=s}}class p1 extends d1{constructor(){super(...arguments);this._prefix=s}get readOnly(){return this}}class l1 extends f{constructor(){super(...arguments);this._prefix=a}}class n1 extends l1{constructor(){super(...arguments);this._prefix=a}get readOnly(){return this}}class j6 extends n1{constructor(){super(...arguments);this._prefix=a}get readWrite(){return this}}var N6=j6;class x6 extends p1{constructor(){super(...arguments);this._prefix=s}get readWrite(){return this}get sandbox(){if(this._sandbox)return this._sandbox;return this._sandbox=new N6(this)}}var L6=x6;class j0 extends R1{get v1(){if(this._v1)return this._v1;return this._v1=new E1(this)}get v2(){if(this._v2)return this._v2;return this._v2=new M6(this)}get readWrite(){return this}get ads(){if(this._ads)return this._ads;return this._ads=new L6(this)}static getErrors(W){var J;if(typeof W!=="object")return[];if(!("data"in W))return[];return(J=W.data.errors)!==null&&J!==void 0?J:[]}static getProfileImageInSize(W,J){let Z=W.split("/").pop(),$=["normal","bigger","mini"],Q=W;for(let G of $)if(Z.includes(`_${G}`)){Q=W.replace(`_${G}`,"");break}if(J==="original")return Q;let Y=Q.lastIndexOf(".");if(Y!==-1){let G=Q.slice(Y+1);return Q.slice(0,Y)+"_"+J+"."+G}else return Q+"_"+J}}var t6={clientId:process.env.X_CLIENT_ID,clientSecret:process.env.X_SECRET,redirectPath:"/auth/oauth/x/callback",scope:["tweet.read","users.read","offline.access"]};class D6 extends j1{config;client;constructor(W={}){super();this.config={...t6,...W},this.client=new j0({clientId:this.config.clientId,clientSecret:this.config.clientSecret})}redirectUri(){return`${process.env.HOST_NAME??""}${this.config.redirectPath}`}getRedirectUrl(W,J){if(!J)throw Error("XOAuthProvider needs the state and PKCE challenge gemi passes.");let Z=new URL("https://x.com/i/oauth2/authorize"),$={response_type:"code",client_id:this.config.clientId,redirect_uri:this.redirectUri(),state:J.state,code_challenge:J.codeChallenge,code_challenge_method:J.codeChallengeMethod,scope:this.config.scope.join(" ")};for(let[Q,Y]of Object.entries($))Z.searchParams.set(Q,Y);return Z.toString()}async onCallback(W,J){let Z=W.search.get("code");if(!Z)throw new q("missing_code");if(!J?.codeVerifier)throw new q("invalid_state");let $;try{$=await this.client.loginWithOAuth2({code:Z,codeVerifier:J.codeVerifier,redirectUri:this.redirectUri()})}catch(X){throw console.error("X OAuth error: token exchange failed",X),new q("exchange_failed")}let{data:Q}=await $.client.v2.me({"user.fields":["name","username","entities"]}),{name:Y,email:G,id:K="",username:z}=Q??{};return{name:Y,email:G,username:z,providerId:K}}}class N0{describe;rollout;when;serverOnly;salt;constructor(W={}){if(W.rollout!==void 0){let{rollout:J}=W;if(!Number.isFinite(J)||J<0||J>100)throw Error(`A feature's \`rollout\` must be a number between 0 and 100, received ${String(J)}.`)}this.describe=W.describe,this.rollout=W.rollout,this.when=W.when,this.serverOnly=W.serverOnly??!1,this.salt=W.salt}}function r6(W={}){return new N0(W)}class F6 extends x0{rows=new Map;constructor(W={}){super();for(let[J,Z]of Object.entries(W))this.rows.set(J,{key:J,active:Z})}async load(){return[...this.rows.values()].map((W)=>({...W}))}async write(W,J,Z){return this.rows.set(W,{key:W,active:J,updatedBy:Z.actor,updatedAt:new Date}),{actorRecorded:!0}}}export{$5 as viewRouteConfigDefaults,i5 as translationConfigDefaults,i1 as toRangeHeaderValue,cW as subjectFor,jW as sniffContentType,y5 as scheduleConfigDefaults,a1 as resolveRange,N8 as redisConfigDefaults,B8 as rateLimiterConfigDefaults,k5 as queueConfigDefaults,K1 as parseContentRange,$W as mintSessionToken,WW as middlewareConfigDefaults,M5 as mailConfigDefaults,G8 as logConfigDefaults,ZW as isSessionToken,NW as isActiveContentType,EW as inRollout,rW as imageConfigDefaults,BW as filesystemConfigDefaults,t5 as featuresConfigDefaults,h5 as eventConfigDefaults,mW as evaluateFeature,vW as encodeCursor,u5 as discoverListeners,E5 as discoverJobs,m5 as discoverCronJobs,c5 as discoverCommands,n5 as defineTranslationConfig,q5 as defineScheduleConfig,J5 as defineRouteConfig,j8 as defineRedisConfig,X8 as defineRateLimiterConfig,_5 as defineQueueConfig,e6 as defineMiddlewareConfig,B5 as defineMailConfig,Y8 as defineLogConfig,tW as defineImageConfig,XW as defineFilesystemConfig,a5 as defineFeaturesConfig,r6 as defineFeature,A5 as defineEventConfig,O6 as defineEncryptionConfig,v5 as defineCommandConfig,w5 as defineCommand,bW as defineChangeFeedConfig,GW as defineAuthConfig,PW as decodeCursor,P5 as commandConfigDefaults,TW as changeFeedConfigDefaults,gW as bucketOf,hW as bucketKey,z4 as bearerToken,KW as authConfigDefaults,o1 as assertDeletablePrefix,Z5 as apiRouteConfigDefaults,D6 as XOAuthProvider,G5 as ViewRouteDispatcher,nW as UndeclaredFeatureError,F6 as StaticFeatureFlagSource,aW as Sharp,S5 as Scheduler,o5 as ScheduleServiceProvider,JW as SESSION_TOKEN_PREFIX,F0 as S3Driver,L8 as RouteServiceProvider,X5 as ResendDriver,x8 as RedisServiceProvider,R0 as RedisRateLimiter,_1 as RedisManager,M8 as RateLimiterServiceProvider,t1 as RateLimiterDriver,QW as RateLimiter,i as RangeNotSatisfiableError,d5 as QueueServiceProvider,I5 as QueueManager,IW as ProviderConnection,_W as OAuthReconnectRequiredError,j1 as OAuthProvider,kW as OAuthConnectionProvider,fW as OAuthConnectionError,q as OAuthCallbackError,z8 as MiddlewareServiceProvider,W5 as MiddlewareRegistry,C5 as MemoryQueueDriver,E0 as MemoryMcpOAuthStore,U5 as MemoryLockStore,OW as MemoryConnectionStore,VW as MemoryChangeFeedDriver,x5 as McpToolError,D5 as McpRegistry,h0 as McpOAuthServer,H5 as McpHttpServer,L5 as McpCallRefusedError,F5 as McpApiKeyResolver,e5 as MailServiceProvider,j5 as MailManager,K8 as LogServiceProvider,xW as LogManager,FW as LockManager,LW as LockLostError,g5 as Listener,Q8 as KernelIdServiceProvider,Q5 as KernelId,f5 as Job,YW as InMemoryRateLimiter,$8 as ImageServiceProvider,sW as ImageOptimizationDriver,eW as ImageManager,Y5 as ISLAND_LOADER_CSP_HASH,DW as HeldLock,u0 as GoogleOAuthProvider,Z8 as FilesystemServiceProvider,MW as FilesystemManager,zW as FileSystemDriver,z1 as FileStorageDriver,c as FileNotFoundError,r5 as FeaturesServiceProvider,lW as FeatureSourceReadOnlyError,iW as FeatureScope,uW as FeatureReloadError,pW as FeatureModelMissingError,oW as FeatureManager,dW as FeatureFlagStore,x0 as FeatureFlagSource,N0 as Feature,J8 as EventServiceProvider,k as EventManager,c0 as Event,W8 as EncryptionServiceProvider,UW as EncryptionKeyError,HW as Encrypter,z5 as EmailDriver,SW as DecryptionError,R5 as DatabaseQueueDriver,O5 as DatabaseLockStore,s5 as DatabaseFeatureFlagSource,RW as DatabaseConnectionStore,wW as DatabaseChangeFeedDriver,N5 as DEFAULT_MCP_SCOPE,V5 as CronJob,CW as ConnectionManager,D8 as CommandRegistry,b5 as CommandFailed,T5 as Command,AW as ChangeFeedSubscription,p5 as ChangeFeedServiceProvider,yW as ChangeFeedManager,qW as ChangeFeedFullError,k1 as CONSENT_PAGE_HEADERS,U0 as AzureBlobDriver,l5 as AuthServiceProvider,b1 as AuthManager,K5 as ApiRouteDispatcher};
|
|
71
71
|
|
|
72
|
-
//# debugId=
|
|
72
|
+
//# debugId=D6CED893D8F2462664756E2164756E21
|