azot 5.0.0-alpha.17 → 5.0.0-alpha.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +43 -3
- package/dist/api.mjs +1 -0
- package/dist/azot.mjs +19 -0
- package/dist/azt.mjs +1 -1
- package/dist/chunk-cpUYaJdV.mjs +1 -0
- package/dist/context-P15t7YGq.mjs +3 -0
- package/dist/context.mjs +1 -1
- package/dist/vitest.mjs +1 -1
- package/package.json +58 -34
- package/types/{main.d.ts → api.d.ts} +24 -1
- package/types/extension-v2.d.ts +81 -0
- package/types/extension.d.ts +1 -1
- package/types/manifest.d.ts +9 -0
- package/dist/azt.cjs +0 -2
- package/dist/chunk-350yNsax.cjs +0 -1
- package/dist/chunk-DtROqxiw.mjs +0 -1
- package/dist/context-DHVMX6Ku.mjs +0 -5
- package/dist/context-NfAQSZZu.cjs +0 -5
- package/dist/context.cjs +0 -1
- package/dist/main.cjs +0 -1
- package/dist/main.mjs +0 -1
- package/dist/open-DWfOU8xH.cjs +0 -2
- package/dist/open-rfKrXH0-.mjs +0 -2
- package/dist/vitest.cjs +0 -1
package/README.md
CHANGED
|
@@ -1,10 +1,50 @@
|
|
|
1
|
-
# Azot
|
|
1
|
+
# Azot
|
|
2
|
+
|
|
3
|
+
## Extensions API
|
|
2
4
|
|
|
3
5
|
Type definitions for the latest [Azot](https://azot.mov) API.
|
|
4
6
|
|
|
5
|
-
|
|
7
|
+
Check [docs](https://azot.mov/docs/extensions/globals) or [TypeScript definitions](https://npmx.dev/package-code/azot/v/5.0.0-alpha.18/types) to get started with our API. If you want to discover and install extensions, check out [Extension List](https://azot.mov/extensions).
|
|
8
|
+
|
|
9
|
+
## Command-line interface
|
|
10
|
+
|
|
11
|
+
### Quick Start
|
|
12
|
+
|
|
13
|
+
Run following command to install Azot CLI globally ([Node.js](https://nodejs.org/en/download) 24 or higher is required):
|
|
14
|
+
|
|
15
|
+
```shell
|
|
16
|
+
npm install -g azot
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
> Use `azot --help` command to see all available options.
|
|
20
|
+
|
|
21
|
+
Install `premier` extension to download videos from [PREMIER](https://premier.one/)):
|
|
22
|
+
|
|
23
|
+
```shell
|
|
24
|
+
azot install premier
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Download a video from [RUTUBE](https://rutube.ru/) using built-in `rutube` extension:
|
|
28
|
+
|
|
29
|
+
```shell
|
|
30
|
+
azot https://rutube.ru/video/a5d8e842f1b9ea08d9f64cd78d7e722e/
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
```text
|
|
34
|
+
11:19:44.874 INFO Fetching content metadata...
|
|
35
|
+
11:19:45.257 INFO Fetching metadata finished
|
|
36
|
+
11:19:45.289 INFO Как речной транспорт экономит время москвичей? — Москва 24
|
|
37
|
+
11:19:45.290 INFO Content Matched: HTTP Live Streaming
|
|
38
|
+
11:19:45.290 INFO Parsing streams...
|
|
39
|
+
11:19:46.223 INFO Extracted, there are 16 tracks, 8 video tracks, 8 audio tracks
|
|
40
|
+
11:19:46.226 INFO Как речной транспорт экономит время москвичей — Москва 24 (480p, avc) ∙ VIDEO ∙ 848x480 ∙ 485 KiB/s
|
|
41
|
+
✔:19:46.226 INFO Downloading ∙ 21.77 MB
|
|
42
|
+
11:19:52.761 INFO Как речной транспорт экономит время москвичей — Москва 24 (480p, avc) ∙ AUDIO ∙ UND ∙ 44100 kHz ∙ 485 KiB/s
|
|
43
|
+
✔:19:52.762 INFO Downloading ∙ 21.77 MB
|
|
44
|
+
✔:19:57.009 INFO Muxed
|
|
45
|
+
```
|
|
6
46
|
|
|
7
|
-
|
|
47
|
+
> You can find downloaded video in `~/Downloads/` directory by default.
|
|
8
48
|
|
|
9
49
|
## Community
|
|
10
50
|
|
package/dist/api.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=Azot??Streamyx??{};e&&(e.defineExtension||=e=>e);const t=e.defineExtension,n=e.version,r=e.sleep,i=e.input,a=e.prompt,o=e.notify,s=e.confirm,c=e.ask,l=e.utils,u=e.Input,d=e.UrlSource,f=e.ALL_FORMATS,p=e.DASH,m=e.DASH_FORMATS,h=e.HLS,g=e.HLS_FORMATS,_=e.MP4,v=e.MP3;export{f as ALL_FORMATS,p as DASH,m as DASH_FORMATS,h as HLS,g as HLS_FORMATS,u as Input,v as MP3,_ as MP4,d as UrlSource,c as ask,s as confirm,e as default,t as defineExtension,i as input,o as notify,a as prompt,r as sleep,l as utils,n as version};
|
package/dist/azot.mjs
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{n as __require,r as __toESM,t as __commonJSMin}from"./chunk-cpUYaJdV.mjs";import{A as shortVersion,C as SETTINGS_PATH,D as VITE_API_URL,E as APP_TITLE,O as VITE_PUBLIC_KEY,S as EXTENSIONS_SOURCES_DIR,T as APP_NAME,_ as APP_TEMP_DIR,a as prompt,b as EXTENSIONS_DIR,c as FileStorage,d as normalizeError,f as clearOutdatedLogs,g as APP_LOG_DIR,h as APP_DATA_DIR,i as httpClient,j as package_default,k as fullVersion,l as createConf,m as APP_CONFIG_DIR,n as load,o as getCurrentDateTimeString,p as logger,r as HttpClient,s as getLogPrefix,t as createContext,u as errors,v as DOWNLOAD_DIR,w as resolveDir,x as EXTENSIONS_INDEX_PATH,y as EXTENSIONS_DATA_DIR}from"./context-P15t7YGq.mjs";import{constants,existsSync,rmSync}from"node:fs";import*as path$1 from"node:path";import path,{basename,dirname,extname,join,parse,resolve}from"node:path";import yargs from"yargs";import"urlpattern-polyfill";import colors from"picocolors";import*as fs from"node:fs/promises";import fsp,{open,readFile,readdir,rm,stat,writeFile}from"node:fs/promises";import{platform}from"node:process";import{hideBin}from"yargs/helpers";import{EventEmitter}from"node:events";import{z}from"zod";import{DASH_FORMATS,HLS_FORMATS,Input,UrlSource}from"dasha";import{checkbox,confirm}from"@inquirer/prompts";import{execFileSync}from"node:child_process";import{createAuthClient}from"better-auth/client";import{deviceAuthorizationClient}from"better-auth/client/plugins";import{tributeClient}from"@tribute-tg/better-auth";import{QueryCache,QueryClient}from"@tanstack/query-core";import{createHash}from"node:crypto";import{inspect}from"node:util";import{ALL_FORMATS as ALL_FORMATS$1,EncodedAudioPacketSource,EncodedPacketSink,EncodedVideoPacketSource,Input as Input$1,MkvOutputFormat,Mp4OutputFormat,Output,StreamSource,StreamTarget,TextSubtitleSource,UrlSource as UrlSource$1}from"mediabunny";import{Download}from"molnia";import{isatty}from"node:tty";import{createSpinner}from"nanospinner";import{RemoteCdm,requestMediaKeySystemAccess}from"okova";import{Decryption,FilePathSource,FilePathTarget,Input as Input$2,Output as Output$1}from"shifro";import{convert}from"@transcrobes/subs-convert";import open$1 from"open";const getWinConsoleAddonPath=()=>{let e=[];process.resourcesPath&&e.push(join(process.resourcesPath,`bin`,`winconsole.node`));let t=join(__dirname,`..`,`..`,`..`);return e.push(join(t,`assets`,`bin`,`win32`,`winconsole.node`)),e.push(join(t,`native`,`winconsole`,`build`,`Release`,`winconsole.node`)),e.find(e=>existsSync(e))||null},loadWinConsoleAddon=()=>{if(process.platform!==`win32`)return null;let e=getWinConsoleAddonPath();if(!e)return null;try{return __require(e)}catch{return null}};if(process.platform===`win32`){let e=loadWinConsoleAddon();e&&(e.attachParentConsole?.(),e.enableUtf8?.())}const getCliArgs=(e=process.argv,t=process.env)=>t.ELECTRON_RUN_AS_NODE===`1`?e.slice(2):hideBin(e),getDefaultLanguage=()=>Intl.DateTimeFormat().resolvedOptions().locale.startsWith(`ru`)?`ru`:`en`,THEME={dark:`dark`,light:`light`,system:`system`},VIDEO_CONTAINER_FORMAT={mp4:`mp4`,mkv:`mkv`},SettingsSchema=z.object({downloadDir:z.string().default(DOWNLOAD_DIR),binariesDir:z.string().default(resolveDir(join(APP_CONFIG_DIR,`bin`))),drmDir:z.string().default(resolveDir(join(APP_CONFIG_DIR,`drm`))),language:z.string().default(getDefaultLanguage()),theme:z.enum([THEME.dark,THEME.light,THEME.system]).default(THEME.system),preferHardsub:z.coerce.boolean().default(!1),retry:z.coerce.number().int().min(1).max(10).default(3),connections:z.coerce.number().int().min(1).max(64).default(4),maxActiveDownloads:z.coerce.number().int().min(1).default(1),proxy:z.string().optional(),proxyMeta:z.string().optional(),proxyMedia:z.string().optional(),movieFilenameTemplate:z.string().default(`{title} ({quality}, {codec})`),seriesFilenameTemplate:z.string().default(`{title} S{s}E{e} ({quality}, {codec})`),developerMode:z.coerce.boolean().default(!1),allowUnknownSources:z.coerce.boolean().default(!1),videoContainerFormat:z.enum([VIDEO_CONTAINER_FORMAT.mp4,VIDEO_CONTAINER_FORMAT.mkv]).default(VIDEO_CONTAINER_FORMAT.mp4),useAlternativeServer:z.coerce.boolean().default(!1),automaticUpdates:z.coerce.boolean().default(!0)}),defaultSettings=SettingsSchema.parse({});var SettingsStore=class{#e;constructor(e){this.#e=createConf({defaults:defaultSettings,cwd:dirname(e),configName:basename(e,`.json`)}),this.#t()}#t(){let e=this.#e.store,t=SettingsSchema.safeParse(e),n=`{title}.{audioType}.{quality}.{tag}.{format}.{codec}`,r=`{title}.S{s}E{e}.{episodeTitle}.{audioType}.{quality}.{tag}.{format}.{codec}`;if(e.movieFilenameTemplate===`{title}.{audioType}.{quality}.{tag}.{format}.{codec}`&&this.#e.set(`movieFilenameTemplate`,e.seriesFilenameTemplate),e.seriesFilenameTemplate===`{title}.S{s}E{e}.{episodeTitle}.{audioType}.{quality}.{tag}.{format}.{codec}`&&this.#e.set(`seriesFilenameTemplate`,e.seriesFilenameTemplate),!t.success){console.warn(`Settings validation failed! Resetting to defaults.`,t.error.flatten()),this.#e.set(defaultSettings);return}Object.hasOwn(e,`askForOptions`)&&this.#e.set(t.data)}getAll(){return this.#e.store}get(e){return this.#e.get(e)}set(e){let t={...this.#e.store,...e},n=SettingsSchema.safeParse(t);if(!n.success)throw console.error(`Invalid settings update:`,n.error.flatten()),Error(`Settings update failed validation.`);this.#e.set(n.data)}onDidChange(e){this.#e.onDidAnyChange(e)}};const exists=async e=>{try{return await fsp.access(e),!0}catch(e){if(e.code===`ENOENT`)return!1;throw e}},ls=async(e,{recursive:t=!1}={})=>await fsp.readdir(e,{withFileTypes:!0,recursive:t}),rm$1=async(e,{recursive:t=!0,force:n=!0}={})=>{await fsp.rm(e,{recursive:t,force:n})},mkdir=async(e,{recursive:t=!0}={})=>{await fsp.mkdir(e,{recursive:t})},assertDownloadDirWritable=async e=>{try{await fsp.access(e,constants.W_OK)}catch(e){let t=e.code;throw t===`EPERM`||t===`EACCES`||t===`ENOENT`?Object.assign(Error(`Download directory is not writable`),{code:`DOWNLOAD_DIR_NOT_WRITABLE`}):e}},readJson=async e=>{try{let t=await fsp.readFile(e,{encoding:`utf8`});return JSON.parse(t)}catch(t){throw Error(`Failed to read JSON file: ${e}`,{cause:t})}},writeJson=async(e,t)=>{let n=parse(e).dir;try{let r=await exists(n);n&&!r&&await fsp.mkdir(n),await fsp.writeFile(e,JSON.stringify(t,null,2),`utf8`)}catch(t){throw Error(`Failed to save data to file: ${e}`,{cause:t})}},tar={extract:(e,t)=>execFileSync(`tar`,[`-xf`,e,...t?[`-C`,t]:[]],{stdio:`inherit`})},INSTALL_EXTENSION_ERROR_CODES={CHANNEL_NOT_FOUND:`EXTENSION_INSTALL_CHANNEL_NOT_FOUND`,VERSION_NOT_FOUND:`EXTENSION_INSTALL_VERSION_NOT_FOUND`,RELEASE_NOT_FOUND:`EXTENSION_INSTALL_RELEASE_NOT_FOUND`,ASSET_NOT_FOUND:`EXTENSION_INSTALL_ASSET_NOT_FOUND`,UNSUPPORTED_SOURCE:`EXTENSION_INSTALL_UNSUPPORTED_SOURCE`,UNSUPPORTED_PACKAGE_TYPE:`EXTENSION_INSTALL_UNSUPPORTED_PACKAGE_TYPE`,IMPORT_INVALID:`EXTENSION_INSTALL_IMPORT_INVALID`,SOURCE_NOT_FOUND:`EXTENSION_INSTALL_SOURCE_NOT_FOUND`,UNKNOWN:`EXTENSION_INSTALL_UNKNOWN`},KNOWN_INSTALL_EXTENSION_ERROR_CODES=new Set(Object.values(INSTALL_EXTENSION_ERROR_CODES));var InstallExtensionError=class extends Error{code;details;hint;constructor(e){super(e.message),this.name=`InstallExtensionError`,this.code=e.code,this.details=e.details,this.hint=e.hint}toPayload(){return{code:this.code,message:this.message,details:this.details,hint:this.hint}}};const createInstallExtensionError=(e,t,n,r)=>new InstallExtensionError({code:e,message:t,details:n,hint:r}),getChannel=e=>{let t=(e?.startsWith(`v`)?e[1]:e?.[0])??``;return Number.isNaN(parseInt(t))?e?.split(`.`).at(0)||`latest`:e?.split(`-`).at(1)?.split(`.`).at(0)||`latest`},getReleaseTag=e=>(e.version||e.tag_name||``).replace(/^v/,``),toUniqueList=e=>[...new Set(e.filter(Boolean))],getAvailableReleaseDetails=e=>({availableVersions:toUniqueList((e||[]).map(e=>getReleaseTag(e))),availableChannels:toUniqueList((e||[]).map(e=>getChannel(getReleaseTag(e))))}),createRequestedReleaseNotFoundError=(e,t,n)=>{let r={source:n,preferredVersion:e.preferredVersion,preferredChannel:e.preferredChannel,appChannel:e.appChannel,...getAvailableReleaseDetails(t)};return e.preferredVersion?createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.VERSION_NOT_FOUND,`Release not found for requested version: ${e.preferredVersion}`,r):createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.CHANNEL_NOT_FOUND,`Release not found for requested channel: ${e.preferredChannel}`,r)},selectRelease=(e,t,n)=>{if(!e?.length)return null;if(t.preferredVersion)return e.find(e=>getReleaseTag(e)===t.preferredVersion)||null;if(!t.isExplicitSelection){let t=e.find(e=>getChannel(getReleaseTag(e))===`latest`);if(t)return t}return e.find(e=>getChannel(getReleaseTag(e))===t.preferredChannel)||(t.allowFallback&&t.preferredChannel!==`latest`?(logger.debug(`Release ${t.preferredChannel} not found for ${n}, falling back to latest stable`),e.find(e=>getChannel(getReleaseTag(e))===`latest`)||(logger.debug(`Latest stable release not found for ${n}, falling back to latest with any channel`),e.at(0)||null)):null)},parseReleasePreference=e=>{let[,t=``]=e.split(`@`),n=e.replace(t?`@${t}`:``,``),r=getChannel(package_default.version),i=!!t;return{name:n,preferredVersion:Number.isNaN(parseInt(t[0]??``))?``:t,preferredChannel:i?getChannel(t):r,appChannel:r,isExplicitSelection:i,allowFallback:!i&&r!==`latest`}},fetchExtensionAsset=async(e,t)=>{logger.info(`Fetching bundle...`),logger.debug(e);let n=await fetch(e);if(!n.ok)throw createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.ASSET_NOT_FOUND,`Failed to download extension bundle: ${n.status} ${n.statusText}`,{url:e,status:n.status,statusText:n.statusText});let r=n.headers.get(`content-disposition`)?.split(`filename=`)[1]?.split(`;`)[0]?.replaceAll(`"`,``),i=path.basename(e),a=t||r||i,o=await n.arrayBuffer(),s=path.join(EXTENSIONS_SOURCES_DIR,a);return await fsp.writeFile(s,Buffer.from(o)),await fsp.stat(s).then(e=>{logger.debug(`Bundle downloaded (${e.size/1e3} KB): ${s}`)}).catch(()=>{logger.error(`Bundle download failed: can't find output file`)}),s},downloadExtension=async(e,t)=>{if(e.startsWith(`npm:`)||e.startsWith(`@streamyx/`))throw createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.UNSUPPORTED_SOURCE,`NPM extension sources are no longer supported`,{source:e});let n=e,r=e,i=path.dirname(e),a=i!==`.`&&await fsp.stat(i).then(()=>!0,()=>!1),o=e.startsWith(`./`)||e.startsWith(`../`)||e.startsWith(`/`)||e.startsWith(`~`)||a,s=await fsp.stat(e).then(()=>!0,()=>!1),c=e.startsWith(`https://`),l=e.startsWith(`gl:`)||e.startsWith(`gitlab:`),u=e.startsWith(`github:`)||e.startsWith(`gh:`);if(o&&!s&&!c&&!u&&!l)throw logger.warn(`Installed extension not found: ${e}`),logger.warn(`Run 'azot list' and remove the extension from the list.`),createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.SOURCE_NOT_FOUND,`Installed extension source not found: ${e}`,{source:e});e=e.replace(/^gl:/,``).replace(/^gitlab:/,``).replace(/^gh:/,``).replace(/^github:/,``);let d=parseReleasePreference(e),{name:f}=d;if(c)n=await fetchExtensionAsset(e);else if(u){let[e,t]=f.split(`/`),r=`https://api.github.com/repos/${e}/${t}/releases`,i=await fetch(r).then(e=>e.json());if(i?.message&&!Array.isArray(i))throw createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.RELEASE_NOT_FOUND,`GitHub releases request failed: ${i.message}`,{source:f,provider:`github`,apiMessage:i.message});let a=Array.isArray(i)?i:[],o=selectRelease(a,d,f);if(!o)throw d.isExplicitSelection?createRequestedReleaseNotFoundError(d,a,f):createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.RELEASE_NOT_FOUND,`GitHub release not found`,{source:f,provider:`github`,...getAvailableReleaseDetails(a)});let s=o.assets?.find(e=>e.name.endsWith(`.tgz`)||e.name.endsWith(`.zip`));if(!s)throw logger.debug(o),createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.ASSET_NOT_FOUND,`GitHub release asset not found`,{source:f,provider:`github`,releaseTag:getReleaseTag(o)});let c=s.browser_download_url;n=await fetchExtensionAsset(c)}else if(!s){let e=t?.find(e=>e.name===f),r=e?.releases||[],i=selectRelease(r,d,f),a=i?.assets.find(e=>e.name.endsWith(`.tgz`));if(e&&!i&&d.isExplicitSelection)throw createRequestedReleaseNotFoundError(d,r,f);if(a)n=await fetchExtensionAsset(a.url,a.name);else{let[e,t=`streamyx-extensions`]=f.split(`/`).reverse(),r=`https://gitlab.com/api/v4/projects/${t}%2F${e}/releases`,i=await fetch(r).then(e=>e.json());if(i?.message&&!Array.isArray(i))throw createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.RELEASE_NOT_FOUND,`GitLab releases request failed: ${i.message}`,{source:f,provider:`gitlab`,apiMessage:i.message});let a=Array.isArray(i)?i:[],o=selectRelease(a,d,f);if(!o)throw d.isExplicitSelection?createRequestedReleaseNotFoundError(d,a,f):createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.RELEASE_NOT_FOUND,`GitLab release not found`,{source:f,provider:`gitlab`,...getAvailableReleaseDetails(a)});let s=o.assets?.links?.find(e=>e.name.endsWith(`.tgz`));if(!s)throw createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.ASSET_NOT_FOUND,`GitLab release asset not found`,{source:f,provider:`gitlab`,releaseTag:getReleaseTag(o)});n=await fetchExtensionAsset(s.direct_asset_url||s.url,s.name)}}let p=path.extname(n),m=p===`.zip`,h=p===`.tgz`,g=new Set([`.js`,`.mjs`,`.cjs`]).has(p),_=await fsp.stat(n).then(e=>e.isDirectory()).catch(()=>!1);if(g?r=path.dirname(n):_?r=n:(r=n.replace(`.tgz`,``).replace(`.zip`,``),await exists(r)||await mkdir(r)),m||h)tar.extract(n,r),await rm$1(n);else if(!(g||_))throw createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.UNSUPPORTED_PACKAGE_TYPE,`Unsupported package type`,{source:e,extensionSource:n,packageType:p||`unknown`});return r},getExports=e=>e&&`exports`in e?e.exports:e,getExtensionName=e=>e?.package?.name||`(unknown extension)`,getExtensionApiVersion=e=>{let t=getExports(e);return!t||typeof t!=`object`?null:typeof t.resolveEntries==`function`?`v2`:typeof t.getMediaInfo==`function`?`legacy-media`:typeof t.fetchContentMetadata==`function`?`legacy-content`:null},isSupportedExtensionExports=e=>getExtensionApiVersion(e)!==null,getCompatibleExtensionExports=e=>{let t=getExports(e);if(!t||typeof t!=`object`)throw Error(`Invalid extension exports`);return t},initializeExtension=async e=>{let t=getCompatibleExtensionExports(e),n=getExtensionName(e);try{if(typeof t.setup==`function`){await t.setup();return}typeof t.init==`function`&&await t.init()}catch(e){let r=typeof t.setup==`function`?`setup`:`init`,i=e instanceof Error?e:Error(String(e));throw logger.error(`Extension ${n} ${r} failed: ${i.message}`),i.stack&&logger.debug(i.stack),i}},loginWithExtension=async(e,t)=>{let n=getCompatibleExtensionExports(e),r=getExtensionName(e);try{if(typeof n.auth?.login==`function`){await n.auth.login(t);return}typeof n.login==`function`&&await n.login(t)}catch(e){let t=typeof n.auth?.login==`function`?`auth.login`:`login`,i=e instanceof Error?e:Error(String(e));throw logger.error(`Extension ${r} ${t} failed: ${i.message}`),i.stack&&logger.debug(i.stack),i}},logoutWithExtension=async e=>{let t=getCompatibleExtensionExports(e),n=getExtensionName(e);try{if(typeof t.auth?.logout==`function`){await t.auth.logout();return}typeof t.logout==`function`&&await t.logout()}catch(e){let r=typeof t.auth?.logout==`function`?`auth.logout`:`logout`,i=e instanceof Error?e:Error(String(e));throw logger.error(`Extension ${n} ${r} failed: ${i.message}`),i.stack&&logger.debug(i.stack),i}},runBeforeDownloadHook=async e=>{let t=getCompatibleExtensionExports(e);typeof t.hooks?.beforeDownload==`function`&&await t.hooks.beforeDownload()},runAfterDownloadHook=async(e,{skipMux:t=!1}={})=>{let n=getCompatibleExtensionExports(e),r=getExtensionName(e);if(!t&&typeof n.hooks?.afterMux==`function`)try{await n.hooks.afterMux()}catch(e){let t=e instanceof Error?e:Error(String(e));logger.error(`Extension ${r} hooks.afterMux failed: ${t.message}`),t.stack&&logger.debug(t.stack)}if(typeof n.onDownloadFinished==`function`)try{await n.onDownloadFinished()}catch(e){let t=e instanceof Error?e:Error(String(e));logger.error(`Extension ${r} onDownloadFinished failed: ${t.message}`),t.stack&&logger.debug(t.stack)}},loadExtension=async(e,{context:t,dirname:n,skipValidation:r})=>{let i=await load(e,{dirname:n,context:t}).finally(()=>{});if(!i)return null;let a=`default`in i.exports?i.exports.default:i.exports;if(!r&&!isSupportedExtensionExports(a))throw logger.error(`Incompatible extension interface`),createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.IMPORT_INVALID,`Incompatible extension interface`,{extensionPath:e});return i.exports=a,i},sanitizeExtensionName=e=>e.split(`/`).reverse()[0].replaceAll(`@`,``).replace(`extension-`,``).replace(`-extension`,``),readExtensionInfo=async e=>{let t=[join(e,`package.json`),join(e,`package`,`package.json`)],n;for(let e of t)if(await exists(e)){n=e;break}let r={},i=``,a=``,o=``;if(n){let e=dirname(n);r=__require(n)||{},i=join(e,r.main||`index.js`),a=r.name,o=e}else{let t=await ls(e),n=t.find(e=>e.name===`index.js`)||t.find(e=>e.name===`main.js`)||t.find(e=>e.name===`service.js`)||t.find(e=>e.name===`extension.js`)||t.find(e=>e.name.endsWith(`.js`));n&&(i=join(e,n.name),a=parse(i).name)}if(!i)throw createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.IMPORT_INVALID,`Extension main script not found: ${e}`,{dir:e});return o||=dirname(i),{name:sanitizeExtensionName(a),path:i,dir:o,package:r}},importExtension=async(e,t)=>{try{let n=await readExtensionInfo(e),r=n.package?.config?.title||n.name,i=createContext({name:n.name,title:r,dir:EXTENSIONS_DATA_DIR});await i.cookieStore.import(join(EXTENSIONS_DATA_DIR,n.name,`cookies.txt`));let a=await loadExtension(n.path,{context:i,dirname:n.dir});if(!a)throw createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.IMPORT_INVALID,`Failed to load extension script: ${n.path}`,{source:t,dir:e,path:n.path});return{source:t,exports:a.exports,context:i,...n}}catch(e){throw logger.error(`Error importing module: ${e.message}`),logger.debug(e instanceof Error?e.stack||e.message:String(e)),e}},PRIMARY_API_URL=VITE_API_URL;let apiBaseUrl=PRIMARY_API_URL;const normalizeBase=e=>e.replace(/\/+$/,``),getApiBaseUrl=()=>normalizeBase(apiBaseUrl),joinUrl=(e,t)=>{let n=normalizeBase(e);return t?`${n}/${t.startsWith(`/`)?t.slice(1):t}`:n},getApiUrl=e=>joinUrl(getApiBaseUrl(),e);let publicKey=null;async function verifyResponse(e){if(!publicKey){logger.debug(`Public key not found`);let e=await fetchPublicKey();if(e)logger.debug(`Public key found: ${e.slice(0,50)}...`);else return logger.error(`Public key not found in response`),!1;if(publicKey=await importPublicKey(e).catch(()=>null),!publicKey)return logger.error(`Public key import failed`),!1}let t=e.headers.get(`X-Signature-Timestamp`),n=e.headers.get(`X-Signature`);if(!t||!n)return logger.error(`Signature headers not found`),!1;if(Date.now()-parseInt(t)>3e5)return!1;let r=`${t}:${await e.clone().text()}`,i=base64ToArrayBuffer(n),a=new TextEncoder,o=crypto.subtle.verify({name:`ECDSA`,hash:`SHA-256`},publicKey,i,a.encode(r));return o||(publicKey=null),o}const getPublicKeyFromEnv=()=>atob(VITE_PUBLIC_KEY);async function fetchPublicKey(e=`/auth/.well-known/public-key`){try{let t=await fetch(`${getApiBaseUrl()}${e}`);return t.ok?await t.text():getPublicKeyFromEnv()}catch(e){return logger.error(e.message),getPublicKeyFromEnv()}}async function importPublicKey(e){let t=base64ToArrayBuffer(e.replace(`-----BEGIN PUBLIC KEY-----`,``).replace(`-----END PUBLIC KEY-----`,``).trim());return crypto.subtle.importKey(`spki`,t,{name:`ECDSA`,namedCurve:`P-256`},!0,[`verify`])}function base64ToArrayBuffer(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}const createClient=e=>createAuthClient({baseURL:`${e}/auth`,plugins:[deviceAuthorizationClient(),tributeClient()],fetchOptions:{retry:0,onSuccess:e=>{let t=e.response.headers.get(`set-auth-token`);t&&(authState.accessToken=t,saveAuth(authState))},auth:{type:`Bearer`,token:()=>authState.accessToken||loadAuth().then(e=>e?.accessToken)},onResponse:async e=>await verifyResponse(e.response).catch(()=>!1)?(logger.debug(`Response verified: ${e.response.url}`),e):(logger.error(`Response verification failed: ${e.response.status} ${e.response.statusText} ${e.response.url}`),errors.emit(`error`,{code:`SIGNATURE_VERIFICATION_FAILED`}),new Response(JSON.stringify({error:`SIGNATURE_VERIFICATION_FAILED`,message:`Signature verification failed`}),{status:401,statusText:`Unauthorized`}))}});let authClientBaseUrl=``,authClient=createClient(getApiBaseUrl());const getAuthClient=()=>{let e=getApiBaseUrl();return(!authClient||authClientBaseUrl!==e)&&(authClientBaseUrl=e,authClient=createClient(e)),authClient},getJson=async(e,t,n={})=>{let{signal:r,timeoutMs:i=1e4}=n,a=new AbortController,o=()=>a.abort(r?.reason);r?.addEventListener(`abort`,o,{once:!0});let s=!1,c=setTimeout(()=>{s=!0,a.abort(Error(`Request timeout`))},i);try{let n=await fetch(e,{...t,signal:a.signal});if(!n.ok)throw Error(`Request failed: ${n.status}`);return n.json()}catch(e){throw s&&e instanceof DOMException&&e.name===`AbortError`?Error(`Request timed out after ${i}ms`,{cause:e}):e}finally{clearTimeout(c),r?.removeEventListener(`abort`,o)}},backendApi={getExtensions:(e,t)=>getJson(getApiUrl(`extensions`),{headers:e?{Authorization:`Bearer ${e}`}:void 0},{signal:t}),getSubscriptions:(e,t)=>getJson(getApiUrl(`subscriptions`),{headers:{Authorization:`Bearer ${e}`}},{signal:t})},STALE_TIME=300*1e3,GC_TIME=300*1e3,queryClient=new QueryClient({queryCache:new QueryCache,defaultOptions:{queries:{staleTime:STALE_TIME,gcTime:GC_TIME}}}),cache={get:e=>queryClient.getQueryData(e),set:(e,t)=>queryClient.setQueryData(e,t),reset:e=>{e?queryClient.removeQueries({queryKey:e}):queryClient.clear()},invalidate:e=>queryClient.invalidateQueries({queryKey:e}),refresh:async(e,t)=>(queryClient.invalidateQueries({queryKey:e}),useQuery({queryKey:e,queryFn:t}))},useQuery=async({queryKey:e,queryFn:t,staleTime:n,enabled:r=!0})=>{try{let i=queryClient.getQueryState(e),a=i?i?.isInvalidated||!i?.dataUpdatedAt&&!i?.errorUpdatedAt||Date.now()-i.dataUpdatedAt>(n??STALE_TIME):!0,o=()=>cache.reset(e),s=()=>cache.invalidate(e),c=()=>cache.refresh(e,t);return r?i&&!a?{data:i.data,reset:o,invalidate:s,refresh:c}:{data:await queryClient.fetchQuery({queryKey:e,queryFn:t,staleTime:n}),reset:o,invalidate:s,refresh:c}:{data:null,reset:o,invalidate:s,refresh:c}}catch(t){throw queryClient.removeQueries({queryKey:e}),t}},sessionStorage=new FileStorage(join(APP_DATA_DIR,`session.json`)),authState={accessToken:``,tokenType:``,scope:``,createdAt:``},saveAuth=async e=>{sessionStorage.setItem(`access_token`,e.access_token),sessionStorage.setItem(`token_type`,e.token_type||`Bearer`),sessionStorage.setItem(`scope`,e.scope),sessionStorage.setItem(`created_at`,new Date().toISOString()),authState.accessToken=e.access_token,authState.tokenType=e.token_type||`Bearer`,authState.scope=e.scope,authState.createdAt=new Date().toISOString()},loadAuth=async()=>{let e=sessionStorage.getItem(`access_token`),t=sessionStorage.getItem(`token_type`),n=sessionStorage.getItem(`scope`),r=sessionStorage.getItem(`created_at`);return!e||!t||!n||!r?null:{accessToken:e,tokenType:t,scope:n,createdAt:new Date(r)}},getAuth=async()=>{let e=await useQuery({queryKey:[`session`,getApiBaseUrl()],queryFn:()=>getAuthClient().getSession()});return{session:e.data?.data?.session,user:e.data?.data?.user,error:e.data?.error}},getSubscriptions=async()=>{let{user:e,error:t}=await getAuth(),n=await useQuery({queryKey:[`subscriptions`,getApiBaseUrl()],queryFn:async()=>getAuthClient().subscription.list(),enabled:!!e?.id});return{data:n.data?.data,error:n.data?.error??t}},basicBenefits=[`lowConnectionsCount`,`oneDevice`],plusBenefits=[`mediumConnectionsCount`,`twoDevices`,`proxy`,`decryption`,`customIcon`,`tags`,`parallelDownloads`,`userExtensions`,`portableBuild`],proBenefits=[`highConnectionsCount`,`threeDevices`,`customMuxFormat`,`customDecrypter`,`customDrmClient`,`premiumExtensions`],benefits={basic:basicBenefits,plus:plusBenefits,pro:[...basicBenefits,...plusBenefits,...proBenefits]},getUserSubscriptions=()=>useQuery({queryKey:[`lava-subscriptions`,getApiBaseUrl()],queryFn:async()=>{let e=authState.accessToken||(await loadAuth())?.accessToken;return e?backendApi.getSubscriptions(e):[]}}),getUserPlan=async()=>{let e=await getSubscriptions();return{plan:(await getUserSubscriptions()).data?.[0]?.productTitle||e.data?.find(e=>new Date(e.expiresAt)>new Date)?.tributeSubscriptionName,error:e.error}},getCustomerState=async()=>{let{user:e,session:t}=await getAuth(),{plan:n,error:r}=await getUserPlan();return{user:e,session:t,error:r,plan:n,grantedBenefits:n?benefits[n.toLowerCase()]??[]:[]}};var require_builtins=__commonJSMin(((e,t)=>{t.exports={instagram:{create:e=>{let t={exports:{}};return((e,n,r,i,a,o,s,c,l,u)=>{let d=e??Streamyx??{};d&&(d.defineExtension||=e=>e);let f=d.defineExtension;d.version,d.sleep,d.input,d.prompt,d.notify,d.confirm,d.ask,d.utils;let p=d.Input,m=d.UrlSource;d.ALL_FORMATS,d.DASH,d.DASH_FORMATS,d.HLS,d.HLS_FORMATS,d.MP4,d.MP3;let h={Referer:`https://www.instagram.com/`},g={"X-IG-App-ID":`936619743392459`,"User-Agent":`Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36`},_=async e=>{let t=new URLSearchParams({doc_id:`8845758582119845`,variables:JSON.stringify({shortcode:e,child_comment_count:3,fetch_comment_count:40,parent_comment_count:24,has_threaded_comments:!0})});try{let e=await n(`https://www.instagram.com/graphql/query/?${t.toString()}`,{headers:g});return e.ok?(await e.json()).data?.xdt_shortcode_media??null:(a.error(`GraphQL request failed with status: ${e.status}`),null)}catch(e){return a.error(`Error during GraphQL fetch:`,e),null}},v=async e=>{try{let t=await n(`https://www.instagram.com/p/${e}/embed/captioned/`,{headers:{"User-Agent":g[`User-Agent`]}});if(!t.ok)return null;let r=(await t.text()).match(/window\.__additionalDataLoaded\('extra',\s*({.+?})\s*\);/);return r?.[1]?JSON.parse(r[1]).shortcode_media??null:null}catch(e){return a.error(`Error during embed page fetch:`,e),null}},y=e=>{let t=e.edge_media_to_caption?.edges?.[0]?.node?.text||`Instagram Post`,n=[],r=e=>{if(!e)return;let r=e.is_video&&e.video_url?e.video_url:e.display_url;r&&n.push({title:t,input:new p({source:new m(r,{requestInit:{headers:h}})})})},i=e.edge_sidecar_to_children?.edges;if(i?.length)for(let e of i)r(e.node);else r(e);return n};t.exports=f({canHandle:e=>{try{let t=new URL(e).hostname.toLowerCase();return t===`instagram.com`||t.endsWith(`.instagram.com`)}catch{return!1}},async resolveEntries(e){let t=new URLPattern({pathname:`/:type(p|reel|tv|reels|videos)/:shortcode{/*}?`,baseURL:new URL(e).origin}).exec(e)?.pathname.groups.shortcode;if(!t)return a.error(`Could not extract a valid Instagram shortcode from the URL`),a.debug(e),[];try{let e=await _(t);return e||=(a.warn(`GraphQL method failed. Falling back to embed page scraping.`),await v(t)),e?y(e):(a.error(`All extraction methods failed. The post may be private, deleted, or require a login.`),[])}catch(e){return a.error(`A critical error occurred while fetching Instagram metadata:`,e),[]}}})})(e.Azot,e.fetch,e.localStorage,e.cookieStore,e.console,e.prompt,e.alert,e.document,e.navigator,e.window),t.exports.default||t.exports},manifest:{icon:`https://is1-ssl.mzstatic.com/image/thumb/Purple221/v4/41/91/13/419113d2-6246-c557-669e-0f0a5c62bcc5/Prod-0-0-1x_U007epad-0-1-0-sRGB-85-220.png/460x0w.webp`,title:`Instagram`,name:`Instagram`},pkg:{name:`instagram`,version:`0.0.1`,private:!0,keywords:[`social-networks`],homepage:`https://instagram.com/`,author:{name:`Azot`,url:`https://azot.mov/`},contributors:[{name:`Vitaly Gashkov`,email:`vitalygashkov@vk.com`,url:`https://github.com/vitalygashkov`}],type:`module`,main:`instagram.ts`,config:{icon:`https://is1-ssl.mzstatic.com/image/thumb/Purple221/v4/41/91/13/419113d2-6246-c557-669e-0f0a5c62bcc5/Prod-0-0-1x_U007epad-0-1-0-sRGB-85-220.png/460x0w.webp`,title:`Instagram`}}},ntv:{create:e=>{let t={exports:{}};return((e,n,r,i,a,o,s,c,l,u)=>{let d=e??Streamyx??{};d&&(d.defineExtension||=e=>e);let f=d.defineExtension;d.version,d.sleep,d.input,d.prompt,d.notify,d.confirm,d.ask,d.utils;let p=d.Input,m=d.UrlSource;d.ALL_FORMATS,d.DASH,d.DASH_FORMATS,d.HLS,d.HLS_FORMATS,d.MP4,d.MP3;let h=(e,t,n)=>e.split(t)[1]?.split(n)[0],g=(e,t)=>{let n=h(e,`<${t}>`,`</${t}>`)?.trim();if(!n)return;let r=n.match(/<!\[CDATA\[(.*?)\]\]>/s);return r?.[1]?r[1].trim():n.split(`DATA[`)[1]?.split(`]`)[0]?.trim()||n},_=async(e,t)=>{let r=await n(e);return r.ok?await r.text():(a.error(`Failed to fetch ${t}. Status: ${r.status} ${r.statusText}`),null)},v=async(e,t,n)=>{let r=new URL(e).pathname,i=new Set;for(let n of t.split(`href="/serial`)){if(!n.startsWith(`/`))continue;let t=n.split(`"`)[0];!t||t.length<=1||t.includes(`/issues/`)||t.includes(`/about/`)||t.split(`/`).length<=2||i.add(e.replace(r,`/serial${t}`))}let a=[];for(let e of i)a.push(...await y(e,n));return a},y=async(e,t=new Set)=>{if(t.has(e))return[];t.add(e);let n=await _(e,`NTV page`);if(!n)return[];let r=h(n,`<meta property="ya:ovs:feed_url" content="`,`">`)??h(n,`<meta property="ya:ovs:feed_url" content="`,`" />`);if(!r)return new URL(e).pathname.includes(`/serial`)?v(e,n,t):(a.error(`Could not find video link in the page.`),[]);let i=r.split(`video/`)[1]?.split(`/`)[0];if(!i)return a.error(`Could not parse NTV video id.`),[];let o=await _(`https://www.ntv.ru/vi${i}/`,`NTV XML metadata`);if(!o)return[];let s=g(o,`dash`)||g(o,`hls`),c=g(o,`file`)||g(o,`video`),l=g(o,`hifile`)||g(o,`hd_video`)||s||c;if(!l)return a.error(`Could not resolve NTV media URL.`),[];let u=h(o,`<embed_tag>`,`</embed_tag>`)||`NTV`,d=h(n,`"name":"`,`"`),f=d?.includes(`серия`)?d.split(`-`)[0]:void 0,y=f?parseInt(f,10):void 0,b=h(o,`<subtitles>`,`</subtitles>`),x=b?`https://www.ntv.ru${b}`:void 0;x&&a.debug(`Subtitles: ${x}`);let S=new p({source:new m(l)});return x&&S.addSubtitleTrack(new m(x),{languageCode:`ru`,name:`Russian`}),[{type:y?`episode`:`video`,title:u,season:y?1:void 0,episode:y,input:S}]};t.exports=f({resolveEntries(e){return y(e,new Set)}})})(e.Azot,e.fetch,e.localStorage,e.cookieStore,e.console,e.prompt,e.alert,e.document,e.navigator,e.window),t.exports.default||t.exports},manifest:{icon:`https://static.ntv.ru/static/images/logo.png`,title:`НТВ`,name:`НТВ`},pkg:{name:`ntv`,version:`0.0.9`,private:!0,keywords:[`tv-channels`],homepage:`https://www.ntv.ru/`,author:{name:`Azot`,url:`https://azot.mov/`},contributors:[{name:`Vitaly Gashkov`,email:`vitalygashkov@vk.com`,url:`https://github.com/vitalygashkov`}],type:`module`,main:`ntv.ts`,config:{icon:`https://static.ntv.ru/static/images/logo.png`,title:`НТВ`}}},rbc:{create:e=>{let t={exports:{}};return((e,n,r,i,a,o,s,c,l,u)=>{let d=e??Streamyx??{};d&&(d.defineExtension||=e=>e);let f=d.defineExtension;d.version,d.sleep,d.input,d.prompt,d.notify,d.confirm,d.ask,d.utils;let p=d.Input,m=d.UrlSource;d.ALL_FORMATS,d.DASH,d.DASH_FORMATS,d.HLS,d.HLS_FORMATS,d.MP4,d.MP3,t.exports=f({async resolveEntries(e){let t=await n(e);if(!t.ok)throw Error(`Failed to fetch RBC page: ${t.status} ${t.statusText}`);let r=(await t.text()).match(/(?:https?:)?\/\/[^\s"'<>]+\.m3u8(?:\?[^\s"'<>]*)?/i)?.[0];if(!r)throw Error(`Could not find RBC playlist URL.`);return[{type:`video`,input:new p({source:new m(r.startsWith(`//`)?`https:${r}`:r)})}]}})})(e.Azot,e.fetch,e.localStorage,e.cookieStore,e.console,e.prompt,e.alert,e.document,e.navigator,e.window),t.exports.default||t.exports},manifest:{icon:`https://static.rustore.ru/imgproxy/A-G-s2Q1x2iqq3qHCAo66-nllrtlqEr7XNU_JKXt4mQ/preset:web_app_icon_160/aHR0cHM6Ly9zdGF0aWMucnVzdG9yZS5ydS80MGViMWY3MS1kMDkzLTQ2NDMtOTkyNi0xZWM0ZjkwNzViMTQ=.webp`,title:`РБК`,name:`РБК`},pkg:{name:`rbc`,version:`0.0.2`,private:!0,keywords:[`news`],homepage:`https://rbc.ru/`,author:{name:`Azot`,url:`https://azot.mov/`},contributors:[{name:`Vitaly Gashkov`,email:`vitalygashkov@vk.com`,url:`https://github.com/vitalygashkov`}],type:`module`,main:`rbc.ts`,config:{icon:`https://static.rustore.ru/imgproxy/A-G-s2Q1x2iqq3qHCAo66-nllrtlqEr7XNU_JKXt4mQ/preset:web_app_icon_160/aHR0cHM6Ly9zdGF0aWMucnVzdG9yZS5ydS80MGViMWY3MS1kMDkzLTQ2NDMtOTkyNi0xZWM0ZjkwNzViMTQ=.webp`,title:`РБК`}}},rutube:{create:e=>{let t={exports:{}};return((e,n,r,i,a,o,s,c,l,u)=>{let d=e??Streamyx??{};d&&(d.defineExtension||=e=>e);let f=d.defineExtension;d.version,d.sleep,d.input,d.prompt,d.notify,d.confirm,d.ask,d.utils;let p=d.Input,m=d.UrlSource;d.ALL_FORMATS,d.DASH,d.DASH_FORMATS,d.HLS,d.HLS_FORMATS,d.MP4,d.MP3;let h=[`/video/:id{/}?`,`/play/embed/:id{/}?`,`/shorts/:id{/}?`,`/yappy/:yappyId{/}?`,`/video/private/:id{/}?p=:key{/}?`,`/video/private/:id{/}?`],g=e=>{let t={yappyId:``,id:``,key:``};for(let n of h){let r=new URLPattern(n,`https://rutube.ru`).exec(e);r&&(Object.assign(t,r.pathname.groups),Object.assign(t,r.search.groups))}return t},_=async e=>{let t=(await n(`https://rutube.ru/pangolin/api/web/yappy/yappypage/?client=wdp&videoId=${e}&page=1&page_size=15`).then(e=>e.json()).catch(()=>null))?.results?.find(t=>String(t.id)===e)?.link;return t?[{type:`video`,title:`rutube_yappy_${e}`,input:new p({source:new m(t)})}]:(a.error(`ErrorEmptyDownload`),[])};t.exports=f({async resolveEntries(e){let t=g(e);if(t.yappyId)return _(t.yappyId);if(!t.id)return a.error(`Could not extract Rutube video id`),[];let r=new URL(`https://rutube.ru/api/play/options/${t.id}/?no_404=true&referer&pver=v2`);t.key&&r.searchParams.set(`p`,t.key);let i=await n(r).then(e=>e.json()).catch(e=>(e instanceof Error&&a.debug(e.message),null));return i?i.detail||!i.video_balancer?.m3u8?(a.error(`Play info is empty`),[]):i.live_streams?.hls?(a.error(`Live videos are not supported`),[]):[{type:`video`,title:i.title?.trim()||`rutube_${t.id}`,input:new p({source:new m(i.video_balancer.m3u8)})}]:(a.error(`Cannot fetch play info`),[])}})})(e.Azot,e.fetch,e.localStorage,e.cookieStore,e.console,e.prompt,e.alert,e.document,e.navigator,e.window),t.exports.default||t.exports},manifest:{icon:`https://static.rustore.ru/imgproxy/vcyBc0LG-3ybXcGs_-_OJXH9ULjoegHlLs-DacemG08/preset:app_card_icon/aHR0cHM6Ly9zdGF0aWMucnVzdG9yZS5ydS9hcGsvMjQ2MjA3L2NvbnRlbnQvSUNPTi9hNTZhZWJlMy01NjVhLTRiZjYtOTQyZC0xZjE0OTk0YjlhNmUucG5n.webp`,title:`RUTUBE`,name:`RUTUBE`},pkg:{name:`rutube`,version:`0.0.13`,private:!0,keywords:[`video-hostings`],homepage:`https://rutube.ru/`,author:{name:`Azot`,url:`https://azot.mov/`},contributors:[{name:`Vitaly Gashkov`,email:`vitalygashkov@vk.com`,url:`https://github.com/vitalygashkov`}],type:`module`,main:`rutube.ts`,config:{icon:`https://static.rustore.ru/imgproxy/vcyBc0LG-3ybXcGs_-_OJXH9ULjoegHlLs-DacemG08/preset:app_card_icon/aHR0cHM6Ly9zdGF0aWMucnVzdG9yZS5ydS9hcGsvMjQ2MjA3L2NvbnRlbnQvSUNPTi9hNTZhZWJlMy01NjVhLTRiZjYtOTQyZC0xZjE0OTk0YjlhNmUucG5n.webp`,title:`RUTUBE`}}},soundcloud:{create:e=>{let t={exports:{}};return((e,n,r,i,a,o,s,c,l,u)=>{let d=e??Streamyx??{};d&&(d.defineExtension||=e=>e);let f=d.defineExtension;d.version,d.sleep,d.input,d.prompt,d.notify,d.confirm,d.ask;let p=d.utils,m=d.Input,h=d.UrlSource;d.ALL_FORMATS,d.DASH,d.DASH_FORMATS,d.HLS,d.HLS_FORMATS,d.MP4,d.MP3;let g={version:``,id:``},_=async()=>{try{let e=await n(`https://soundcloud.com/`).then(e=>e.text()).catch(e=>{let t=e instanceof Error&&e.cause!=null?String(e.cause):``;return e instanceof Error&&t.includes(`ECONNRESET`)&&a.warn(`Soundcloud may be blocked in your region. Use proxy or VPN to bypass restrictions.`),``}),t=e.match(/window\.__sc_version="([0-9]{10})"/)?.[1];if(t&&g.version===t)return g.id;let r=``;for(let t of e.matchAll(/<script.+src="(.+)">/g)){let e=t[1];if(!e?.startsWith(`https://a-v2.sndcdn.com/`))continue;let i=(await n(e).then(e=>e.text()).catch(()=>``)).match(/\("client_id=[A-Za-z0-9]{32}"\)/)?.[0].match(/[A-Za-z0-9]{32}/)?.[0];if(i){r=i;break}}return t&&(g.version=t,g.id=r),r}catch{return``}},v=e=>e.audioCodecs?.some(e=>e===`aac`||e===`mp3`)??!1;t.exports=f({async resolveEntries(e,t){let{author:r,song:i,accessKey:a,shortLink:o}=p.execUrlPatterns(e,[`:author/:song/s-:accessKey`,`:author/:song`,`:shortLink`],[`https://soundcloud.com`,`https://on.soundcloud.com`]).pathname,s=await _();if(!s)throw Error(`No client ID`);let c;if(new URL(e).hostname===`on.soundcloud.com`&&o&&(c=await n(`https://on.soundcloud.com/${o}/`,{redirect:`manual`}).then(e=>{let t=e.headers.get(`location`);if(e.status===302&&t?.startsWith(`https://soundcloud.com/`))return t.split(`?`,1)[0]}).catch(()=>void 0)),!c&&r&&i&&(c=`https://soundcloud.com/${r}/${i}${a?`/s-${a}`:``}`),!c)throw Error(`Could not fetch`);let l=await n(`https://api-v2.soundcloud.com/resolve?url=${c}&client_id=${s}`).then(e=>e.status===200?e.json():null).catch(()=>null);if(!l)throw Error(`Could not fetch`);let u=l.media?.transcodings;if(!u?.length)throw Error(`Empty download`);let d=u.find(e=>e.preset===`opus_0_0`),f=u.find(e=>e.preset===`mp3_0_0`);if(f&&(v(t)||!d)&&(d=f),!d)throw Error(`Empty download`);let g=`${d.url}${d.url.includes(`?`)?`&`:`?`}client_id=${s}&track_authorization=${l.track_authorization}`;if(!g.startsWith(`https://api-v2.soundcloud.com/media/soundcloud:tracks:`))throw Error(`Empty download`);let y=await n(g).then(async e=>(await e.json()).url??``).catch(()=>``);if(!y)throw Error(`Could not fetch`);return[{type:`audio`,title:l.title.trim(),author:l.user.username.trim(),input:new m({source:new h(y)})}]}})})(e.Azot,e.fetch,e.localStorage,e.cookieStore,e.console,e.prompt,e.alert,e.document,e.navigator,e.window),t.exports.default||t.exports},manifest:{icon:`https://play-lh.googleusercontent.com/JSSeB3XQtb9sHD5FWTqVM4AksY_Kg2q20eExenxGqPJZdn2uVQxi8eoHkP5MA-IR4w=w480-h960-rw`,title:`SoundCloud`,name:`SoundCloud`},pkg:{name:`soundcloud`,version:`0.0.6`,private:!0,keywords:[`music`],homepage:`https://soundcloud.com/`,author:{name:`Azot`,url:`https://azot.mov/`},contributors:[{name:`Vitaly Gashkov`,email:`vitalygashkov@vk.com`,url:`https://github.com/vitalygashkov`}],type:`module`,main:`soundcloud.ts`,config:{icon:`https://play-lh.googleusercontent.com/JSSeB3XQtb9sHD5FWTqVM4AksY_Kg2q20eExenxGqPJZdn2uVQxi8eoHkP5MA-IR4w=w480-h960-rw`,title:`SoundCloud`}}},tiktok:{create:e=>{let t={exports:{}};return((e,n,r,i,a,o,s,c,l,u)=>{let d=e??Streamyx??{};d&&(d.defineExtension||=e=>e);let f=d.defineExtension;d.version,d.sleep,d.input,d.prompt,d.notify,d.confirm,d.ask,d.utils;let p=d.Input,m=d.UrlSource;d.ALL_FORMATS,d.DASH,d.DASH_FORMATS,d.HLS,d.HLS_FORMATS,d.MP4,d.MP3,t.exports=f({canHandle:e=>{try{let t=new URL(e).hostname.toLowerCase();return t===`tiktok.com`||t.endsWith(`.tiktok.com`)}catch{return!1}},async resolveEntries(e){let t=await n(e);if(!t.ok)return a.error(`Failed to fetch TikTok page. Status: ${t.status}`),[];let r=(await t.text()).split(`<script id="__UNIVERSAL_DATA_FOR_REHYDRATION__" type="application/json">`)[1]?.split(`<\/script>`)[0];if(!r)return a.error(`Could not find target script tag. TikTok might have updated their page structure.`),[];let i;try{i=JSON.parse(r)}catch(t){return a.error(`Failed to parse TikTok page JSON`,t,{url:e}),[]}let o=i.__DEFAULT_SCOPE__?.[`webapp.video-detail`],s=o?.itemInfo?.itemStruct;if(!s)return a.error(`Could not find video data in the JSON payload. The content might be unavailable or the structure has changed.`),o?.statusMsg&&a.error(`Error ${o.statusCode}: ${o.statusMsg}`),[];let l=s.video?.playAddr;return l?[{type:`video`,title:s.desc||`TikTok Video`,input:new p({source:new m(l,{requestInit:{headers:{Referer:`https://www.tiktok.com/`,Cookie:c.cookie}}})})}]:(a.error(`Could not find a video URL (playAddr) in the JSON payload.`),[])}})})(e.Azot,e.fetch,e.localStorage,e.cookieStore,e.console,e.prompt,e.alert,e.document,e.navigator,e.window),t.exports.default||t.exports},manifest:{name:`TikTok`,tag:`TT`,icon:`https://play-lh.googleusercontent.com/LdBITldj-tJxqLm-CsWSbnt4BMo2gk53cgM7mWIL-zn44m1ywLyQgxRsHKqp8r0qceXs=w480-h960-rw`,permissions:[],matches:[`https://*.tiktok.com/*`],manifestVersion:1,title:`TikTok`},pkg:{name:`tiktok`,version:`0.0.2`,private:!0,keywords:[`social-networks`],homepage:`https://www.tiktok.com/`,author:{name:`Azot`,url:`https://azot.mov/`},contributors:[{name:`Vitaly Gashkov`,email:`vitalygashkov@vk.com`,url:`https://github.com/vitalygashkov`}],type:`module`,main:`tiktok.ts`,config:{name:`TikTok`,tag:`TT`,icon:`https://play-lh.googleusercontent.com/LdBITldj-tJxqLm-CsWSbnt4BMo2gk53cgM7mWIL-zn44m1ywLyQgxRsHKqp8r0qceXs=w480-h960-rw`,permissions:[],matches:[`https://*.tiktok.com/*`],manifestVersion:1,title:`TikTok`}}},virtualroom:{create:e=>{let t={exports:{}};return((e,n,r,i,a,o,s,c,l,u)=>{let d=e??Streamyx??{};d&&(d.defineExtension||=e=>e);let f=d.defineExtension;d.version,d.sleep,d.input,d.prompt,d.notify,d.confirm,d.ask,d.utils;let p=d.Input,m=d.UrlSource;d.ALL_FORMATS,d.DASH,d.DASH_FORMATS,d.HLS,d.HLS_FORMATS,d.MP4,d.MP3,t.exports=f({async resolveEntries(e){let t=new URL(e).searchParams.get(`recordId`);if(!t)return a.error(`Could not extract VirtualRoom recordId.`),[];let r=await n(`https://mv1.virtualroom.ru/vr/player/records/${t}/info`).then(e=>e.ok?e.json():null).catch(()=>null),i=await n(`https://mv1.virtualroom.ru/vr/player/records/${t}/events`).then(e=>e.ok?e.json():null).catch(()=>null),o=r?.data?.roomParameters?.name??`VirtualRoom`;return(i?.data?.translations??[]).filter(e=>!!e.url).map(e=>({title:[o,e.type,e.source,e.start].filter(Boolean).join(` `),input:new p({source:new m(e.url)})}))}})})(e.Azot,e.fetch,e.localStorage,e.cookieStore,e.console,e.prompt,e.alert,e.document,e.navigator,e.window),t.exports.default||t.exports},manifest:{icon:`https://sun9-50.userapi.com/impg/rY5N7sdA93TFdjkeYqPTnPIjvCJ0rALo_V7V8g/zLAaAv0PpvY.jpg?size=400x400&quality=95&sign=5ddcd6358131b204b8619cb8eeff943f&type=album`,title:`VirtualRoom`,name:`VirtualRoom`},pkg:{name:`virtualroom`,version:`0.0.7`,private:!0,keywords:[`videotelephony`],homepage:`https://virtualroom.ru/`,author:{name:`Azot`,url:`https://azot.mov/`},contributors:[{name:`Vitaly Gashkov`,email:`vitalygashkov@vk.com`,url:`https://github.com/vitalygashkov`}],type:`module`,main:`virtualroom.ts`,config:{icon:`https://sun9-50.userapi.com/impg/rY5N7sdA93TFdjkeYqPTnPIjvCJ0rALo_V7V8g/zLAaAv0PpvY.jpg?size=400x400&quality=95&sign=5ddcd6358131b204b8619cb8eeff943f&type=album`,title:`VirtualRoom`}}},vk:{create:e=>{let t={exports:{}};return((e,n,r,i,a,o,s,c,l,u)=>{let d=e??Streamyx??{};d&&(d.defineExtension||=e=>e);let f=d.defineExtension;d.version,d.sleep,d.input,d.prompt,d.notify,d.confirm,d.ask,d.utils;let p=d.Input,m=d.UrlSource;d.ALL_FORMATS,d.DASH,d.DASH_FORMATS,d.HLS,d.HLS_FORMATS,d.MP4,d.MP3;let h=[`2160`,`1440`,`1080`,`720`,`480`,`360`,`240`,`144`],g=e=>{let t=e.match(/video-(\d+)_(\d+)/);return t?{ownerId:t[1],videoId:t[2]}:null},_=e=>{if(!e)return null;for(let t of e)if(Array.isArray(t)){for(let e of t)if(e&&typeof e==`object`&&`player`in e)return e}return null},v=(e,t)=>{let n=t.videoQuality?.replace(`p`,``).trim(),r=h.filter(t=>!!e[`url${t}`]);return r.length?n&&r.includes(n)?n:r[0]:null};t.exports=f({async resolveEntries(e,t){let r=g(e);if(!r)return a.error(`Could not extract VK video identifiers`),[];let i=await n(`https://vkvideo.ru/al_video.php?act=show`,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded; charset=utf-8`,accept:`*/*`,"accept-language":`ru-RU,ru;q=0.9`,"sec-ch-ua":`"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"`,"sec-ch-ua-mobile":`?0`,"sec-ch-ua-platform":`"macOS"`,"sec-fetch-dest":`empty`,"sec-fetch-mode":`cors`,"sec-fetch-site":`same-origin`,"x-requested-with":`XMLHttpRequest`,Referer:e,"Referrer-Policy":`strict-origin-when-cross-origin`},body:new URLSearchParams({al:`1`,autoplay:`1`,claim:``,force_no_repeat:`true`,is_video_page:`true`,list:``,module:`direct`,t:``,video:`-${r.ownerId}_${r.videoId}`}).toString()});if(!i.ok)throw Error(`VK request failed: ${i.status} ${i.statusText}`);let o=_((await i.json()).payload),s=o?.player?.params,l=s&&s.length>0?s[0]:void 0;if(!o||!l)return a.error(`Could not find VK player payload`),[];if(o.mvData?.is_active_live===1||o.mvData?.is_active_live===`1`)return a.error(`Live videos are not supported`),[];let u=v(l,t),d=u?l[`url${u}`]:void 0,f=l.dash_sep||d;return f?[{type:`video`,title:[l.md_title?.trim(),l.md_author?.trim()].filter(Boolean).join(` `),input:new p({source:new m(f,{requestInit:{headers:{Referer:e,Cookie:c.cookie}}})})}]:(a.error(`Could not find video URL`),[])}})})(e.Azot,e.fetch,e.localStorage,e.cookieStore,e.console,e.prompt,e.alert,e.document,e.navigator,e.window),t.exports.default||t.exports},manifest:{icon:`https://static.rustore.ru/imgproxy/kSjDiz_MKxD_jzwgEqqaIjQZTE-NEP1Xt8HtJT7EU4s/preset:app_card_icon/aHR0cHM6Ly9zdGF0aWMucnVzdG9yZS5ydS9hcGsvMjAyNzgyMzI5NS9jb250ZW50L0lDT04vOTc0ODYwMTgtNTc4NS00MjRkLTljYWItNGZlNDk2ZDI3Yzc2LnBuZw==.webp`,title:`VK`,name:`VK`},pkg:{name:`vk`,version:`0.0.8`,private:!0,keywords:[`video-hostings`],homepage:`https://vkvideo.ru/`,author:{name:`Azot`,url:`https://azot.mov/`},contributors:[{name:`Vitaly Gashkov`,email:`vitalygashkov@vk.com`,url:`https://github.com/vitalygashkov`}],type:`module`,main:`vk.ts`,config:{icon:`https://static.rustore.ru/imgproxy/kSjDiz_MKxD_jzwgEqqaIjQZTE-NEP1Xt8HtJT7EU4s/preset:app_card_icon/aHR0cHM6Ly9zdGF0aWMucnVzdG9yZS5ydS9hcGsvMjAyNzgyMzI5NS9jb250ZW50L0lDT04vOTc0ODYwMTgtNTc4NS00MjRkLTljYWItNGZlNDk2ZDI3Yzc2LnBuZw==.webp`,title:`VK`}}},weibo:{create:e=>{let t={exports:{}};return((e,n,r,i,a,o,s,c,l,u)=>{let d=e??Streamyx??{};d&&(d.defineExtension||=e=>e);let f=d.defineExtension;d.version,d.sleep,d.input,d.prompt,d.notify,d.confirm,d.ask;let p=d.utils,m=d.Input,h=d.UrlSource;d.ALL_FORMATS,d.DASH,d.DASH_FORMATS,d.HLS,d.HLS_FORMATS,d.MP4,d.MP3,t.exports=f({async resolveEntries(e){let t=p.execUrlPatterns(e,[`/:userId(\\d+)/:bid`,`/detail/:mid`],[`https://weibo.com/`,`https://m.weibo.cn`]),r=t.pathname.bid||t.pathname.mid;if(!r)return[];let i=await n(`https://m.weibo.cn/statuses/show?id=${r}`,{credentials:`include`,referrer:`https://m.weibo.cn/status/${t.pathname.bid??r}?jumpfrom=weibocom`,method:`GET`,mode:`cors`}).then(e=>e.json()).catch(()=>null);if(!i?.data)return a.error(`Could not resolve Weibo post metadata`),[];let o=[],s=i.data.pics,c=i.data.page_info;if(s?.length)for(let e of s.filter(e=>e.type===`video`||e.type===`livephoto`))e.videoSrc&&o.push({type:`video`,title:e.pid,input:new m({source:new h(e.videoSrc)})});else if(c?.type===`video`){let e=Object.values(c.urls??{})[0],t=c.media_info?.stream_url_hd||c.media_info?.stream_url,n=e||t;n&&o.push({type:`video`,title:c.title||c.page_title,input:new m({source:new h(n)})})}return o}})})(e.Azot,e.fetch,e.localStorage,e.cookieStore,e.console,e.prompt,e.alert,e.document,e.navigator,e.window),t.exports.default||t.exports},manifest:{icon:`https://play-lh.googleusercontent.com/TTKq2trnzgtoyM0jc1pyrrmXtA_Yd3A2hxubZtDahdZStYf4GPANZa-wjDb1ELHrGqh_=w480-h960-rw`,title:`Weibo`,name:`Weibo`},pkg:{name:`weibo`,version:`0.0.6`,private:!0,keywords:[`social-networks`],homepage:`https://weibo.com/`,author:{name:`Azot`,url:`https://azot.mov/`},contributors:[{name:`Vitaly Gashkov`,email:`vitalygashkov@vk.com`,url:`https://github.com/vitalygashkov`}],type:`module`,main:`weibo.ts`,config:{icon:`https://play-lh.googleusercontent.com/TTKq2trnzgtoyM0jc1pyrrmXtA_Yd3A2hxubZtDahdZStYf4GPANZa-wjDb1ELHrGqh_=w480-h960-rw`,title:`Weibo`}}}}})),import_builtins=__toESM(require_builtins(),1);const extractExtensionInfo=e=>({name:e.name,source:e.source,dir:e.dir,path:e.path,package:e.package,installedAt:e.installedAt||new Date().toISOString()});var ExtensionManager=class ExtensionManager extends EventEmitter{extensions=new Map;extensionDirs;indexPath;infoList=[];constructor({dirs:e,indexPath:t}={}){super(),this.extensionDirs=e??[process.cwd()],this.indexPath=t??path$1.join(process.cwd(),`index.json`)}async init(){return await this.ensureValidIndexPath(),await this.loadInfo(),this}async loadInfo(){return this.infoList=await readJson(this.indexPath).catch(()=>[]),this.infoList}async saveInfo(){return await this.ensureValidIndexPath(),await writeJson(this.indexPath,this.infoList)}async ensureValidIndexPath(){(await fs.stat(this.indexPath).catch(()=>null))?.isDirectory()&&(logger.warn(`Invalid extensions index path repaired: ${this.indexPath}`),await rm$1(this.indexPath),await fs.writeFile(this.indexPath,`[]`,`utf8`))}static async getAvailableExtensions(){try{return(await backendApi.getExtensions(authState.accessToken,AbortSignal.timeout(8e3))).data}catch(e){return logger.warn(`Failed to fetch extensions catalog: ${e instanceof Error?e.message:String(e)}`),[]}}async discover(){for(let e of this.extensionDirs){logger.debug(`Loading extensions from ${e}`);let t=await fs.readdir(e,{withFileTypes:!0}).catch(()=>[]);for(let n of t)if(n.isDirectory()){let t=path$1.join(e,n.name);if(await fs.readdir(t).then(e=>e.filter(e=>!e.startsWith(`.`))).then(e=>!e.length))continue;await this.loadExtension(t)}}for(let e of this.infoList)this.extensionDirs.some(t=>e.dir?.includes(t))||!e.dir||(logger.debug(`Loading dev extension from ${e.dir}`),await this.loadExtension(e.dir))}async#e(scriptPath,context){const code=await fs.readFile(scriptPath,`utf8`),{Azot,fetch,console,localStorage,cookieStore,window,document,navigator}=context,module={exports:{}};eval(`(() => {${code}})();`);const exports=module.exports;return{exports,context}}async prepareContext(e,t){let n=createContext({name:e,dir:EXTENSIONS_DATA_DIR,title:t});return await n.cookieStore.import(path$1.join(EXTENSIONS_DATA_DIR,e,`cookies.txt`)),n}async loadScript(e,t){let n=t.name,r=t.config?.title||n,i=await this.prepareContext(n,r),a=await load(e,{dirname:t.dir,context:i});if(a)return a.exports=`default`in a.exports?a.exports.default:a.exports,a}async loadCoreExtensions(){let e=Object.keys(import_builtins.default);logger.debug(`Loading ${e.length} built-in extensions: ${e.join(`, `)}`);for(let e of Object.values(import_builtins.default)){let t=e.pkg.name,n=e.manifest?.name;try{let r=await this.prepareContext(t,n),i={exports:e.create(r),package:e.pkg,context:r};this.validate(i),this.extensions.set(t,i),this.emit(`loaded`,t)}catch(e){logger.debug(e instanceof Error?e.message:String(e)),this.emit(`error`,e,t)}}}async loadExtension(e){try{logger.debug(`Loading extension from ${e}`);let t=await readExtensionInfo(e).catch(e=>logger.error(e));if(!t)return;t.package.dir=t.dir;let n=await this.loadScript(t.path,t.package);if(!n)return;let r={package:t.package,exports:n.exports,context:n.context};this.validate(r),this.extensions.set(t.package.name,r),this.emit(`loaded`,t.package.name)}catch(t){this.emit(`error`,t,e)}}validate(e){if(typeof e!=`object`||!e||!isSupportedExtensionExports(e.exports))throw Error(`Invalid extension interface: ${e.package.name}`)}getExtension(e){return this.extensions.get(e)??Array.from(this.extensions.values()).find(t=>t.package.name===e)??null}async getExtensionForUrl(e){for(let t of this.extensions.values()){let n=null,r=t.exports.canHandle,i=new URL(e).hostname.includes(t.package.name);if(n=typeof r==`function`?await r(e):typeof r==`string`?new URLPattern(r).test(e):i,n)return t}return null}async install(e){let t=await ExtensionManager.getAvailableExtensions(),n=[];for(let r of e){let e=await stat(r).then(e=>e.isDirectory()).catch(()=>!1)?r:await downloadExtension(r,t);if(!e)throw createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.SOURCE_NOT_FOUND,`Extension source not found: ${r}`,{source:r});let i=await importExtension(e,r);if(!i)throw createInstallExtensionError(INSTALL_EXTENSION_ERROR_CODES.IMPORT_INVALID,`Extension import failed: ${r}`,{source:r,dir:e});n.push(i);let a=this.infoList.find(({name:e})=>e===i.name);if(a){let e=a.source;e!==i.source&&await rm$1(e);let t=a.dir?this.#t(a.dir):null,n=i.dir?this.#t(i.dir):null;t&&t!==n&&await rm$1(t),a.installedAt=new Date().toISOString(),Object.assign(a,extractExtensionInfo(i)),logger.info(`Extension ${i.name} updated`)}else this.infoList.push(extractExtensionInfo(i)),logger.info(`Extension ${i.name} added`)}if(await this.saveInfo(),n.length)for(let e of n)this.extensions.set(e.name,e)}#t(e){let t=path$1.parse(e);return t.dir===EXTENSIONS_SOURCES_DIR?e:t.dir}async uninstall(e){for(let t of e){let e=this.infoList.find(e=>e.name===t);if(!e){logger.error(`Extension ${t} not found`);return}let n=e.dir??``,r=n?.includes(EXTENSIONS_SOURCES_DIR);await exists(n)?(r&&await rm$1(this.#t(n)),this.infoList=this.infoList.filter(e=>e.name!==t),logger.info(`Extension ${t} removed`),this.extensions.delete(t)):logger.warn(`Extension ${t} directory not found: ${n}`)}await this.saveInfo()}async importCookies(e,t){let n=this.getExtension(e);if(!n)throw Error(`Extension ${e} not found`);return await n.context.cookieStore.import(t,{removeSource:!1})}async login(e,t={}){let n=this.getExtension(e);n&&await loginWithExtension(n,t)}async logout(e){for(let t of e){let e=this.getExtension(t);if(!e)return;logger.info(`Logging out...`),await logoutWithExtension(e),logger.debug(`Clearing localStorage...`),e.context.localStorage.clear(),logger.debug(`Clearing cookies store...`);let n=await e.context.cookieStore.getAll();for(let t of n)await e.context.cookieStore.delete(t);logger.info(`Logged out from extension ${t}`)}}list(){return Array.from(this.extensions.values()).map(e=>({name:e.package.name,version:e.package.version,description:e.package.description,package:e.package}))}};const mergeExtensionHeadersIntoDrm=(e,t)=>!e||`payload`in e||`keys`in e?e:{...e,headers:{...e.headers,...t?.context.http.headers}},defaultLegacyRequestFilter=async(e,t)=>{if(!t)return e;let n=await e.clone().arrayBuffer(),r=Buffer.from(n).toString(`base64`),i=t.replace(`{{challenge}}`,r);return new Request(e.url,{method:e.method,headers:e.headers,body:i})},defaultLegacyResponseFilter=async e=>{let t=await e.clone().arrayBuffer();if(t[0]===123){let n=null;try{n=JSON.parse(Buffer.from(t).toString(`utf8`))}catch(e){logger.error(`Can't parse license response as JSON`),logger.debug(e.message),logger.debug(`Base64 response data: ${Buffer.from(t).toString(`base64`)}`)}if(!n)return e;try{let n=`CAIS`,r=n+Buffer.from(t).toString(`utf8`).split(`"${n}`)[1].split(`"`)[0],i=Buffer.from(r,`base64`);return new Response(i,{status:e.status,headers:e.headers})}catch{logger.error(`Can't recognize license response`),logger.error(`Response: ${JSON.stringify(n)}`)}}return e},normalizeLegacyMediaInfoList=e=>typeof e==`string`?[{sources:[{url:e}]}]:Array.isArray(e)&&typeof e[0]==`string`?e.map(e=>({sources:[{url:e}]})):Array.isArray(e)?e:e&&typeof e==`object`?[e]:[],normalizeLegacyStreams=e=>e.sources??e.streams??[],resolveLegacyMediaMetadata=(e,t)=>({id:e.id,title:e.title,tag:t.package.config?.tag,seasonNumber:e.seasonNumber??e.season,episodeNumber:e.episodeNumber??e.episode,episodeTitle:e.episodeTitle}),resolveLegacyMediaResources=async(e,t,n)=>{let r=getCompatibleExtensionExports(n);if(typeof r.getMediaInfo==`function`){let i=normalizeLegacyMediaInfoList(await r.getMediaInfo(e,t));if(!i.length)return logger.info(`No metadata found`),[];let a=[];for(let e of i){if(typeof r.refreshMediaInfo==`function`){let n=await r.refreshMediaInfo(e,t);n&&typeof n==`object`&&Object.assign(e,n)}let i=normalizeLegacyStreams(e);for(let t of i){let r=typeof t==`string`?{url:t}:t;a.push({source:{url:r.url,headers:r.headers,drm:r.drm&&!Array.isArray(r.drm)&&typeof r.drm==`object`?{server:r.drm.server}:void 0},metadata:resolveLegacyMediaMetadata(e,n),drm:r.drm&&!Array.isArray(r.drm)&&typeof r.drm==`object`?{server:r.drm.server}:void 0})}}return logger.info(`Fetching metadata finished`),a}let i=await r.fetchContentMetadata?.(e,t);if(!i?.length)return logger.info(`No metadata found`),[];let a=[];for(let e of i){let r={...e},i;if(!r.source&&n.exports.fetchContentSource&&r.id){let e=await n.exports.fetchContentSource(r.id,t);e&&(r.source=e)}if(!r.source?.url){logger.error(`Can't find content source`);continue}r.source.drm&&`payload`in r.source.drm&&n.exports.fetchContentDrm&&(i=r.source.drm.payload,r.source.drm=void 0);let{source:o,...s}=r,c=mergeExtensionHeadersIntoDrm(r.source.drm,n);o.drm=c,o.headers={...o.headers,...n.context.http.headers},n.exports.tag&&(s.tag=n.exports.tag),a.push({source:o,metadata:s,drm:c,drmPayload:i})}return logger.info(`Fetching metadata finished`),a},resolveLegacyMediaResourceDrm=async(e,t,n)=>{if(e.drmPayload&&n?.exports.fetchContentDrm){let r=mergeExtensionHeadersIntoDrm(await n.exports.fetchContentDrm(e.drmPayload,t),n);return e.source.drm=r,e.drm=r,r}let r=mergeExtensionHeadersIntoDrm(e.source.drm??e.drm,n);return e.source.drm=r,e.drm=r,r},createLegacyDrmLicenseResolver=e=>{let t=e.template?defaultLegacyRequestFilter:void 0,n=defaultLegacyResponseFilter,r=new HttpClient;return async({url:i,data:a})=>{let o=new Request(i,{body:Buffer.from(a),method:`POST`,headers:e.headers}),s=await t?.(o,e.template)||o,c=await r.fetch(s.url,{body:await s.arrayBuffer(),headers:s.headers,method:s.method}),l=await n?.(c)||c;return new Uint8Array(await l.arrayBuffer())}},resolvedInputs=new Map,normalizeHeaders=e=>{if(!e)return;let t=Object.fromEntries(new Headers(e).entries());return Object.keys(t).length?t:void 0},serializeMediaEntry=e=>{let{input:t,...n}=e;return n},createEntryCacheKey=(e,t,n)=>createHash(`sha1`).update(JSON.stringify({extension:e.package.name,url:t,id:n.id??null,title:n.title??null,season:n.season??null,episode:n.episode??null})).digest(`hex`),extractInputSource=(e,t)=>{let n=e.source??e._rootSource,r=n?.rootPath;if(typeof r!=`string`||!r)return t??null;let i=n?._url instanceof Request?n._url.headers:void 0,a=n?._options?.requestInit?.headers,o={...normalizeHeaders(i),...normalizeHeaders(a)};return{...t??{},url:r,headers:Object.keys(o).length?o:t?.headers}},createEntryMetadata=(e,t)=>{let n=e.id??e.details?.id;return{id:n==null?void 0:String(n),title:e.title,tag:t.package.config?.tag,seasonNumber:e.season,episodeNumber:e.episode,episodeTitle:e.episodeTitle}},normalizeResolvedResources=e=>e.length?e.length===1?e[0]:e:null,createDirectMediaMetadata=e=>{let t;try{t=new URL(e)}catch{throw Error(`Invalid direct media URL: ${e}`)}let n=t.pathname.replace(/\/+$/,``).split(`/`).filter(Boolean).pop(),r=n?.split(`.`).slice(0,-1).join(`.`)||n||t.hostname||`download`;return{source:{url:e},metadata:{title:r}}},configureExtensionProxy=(e,t)=>{let n=t.proxy||t.proxyMeta;n&&(e.context.http.configure({proxyUrl:n}),httpClient.configure({proxyUrl:n}))},analyzeMediaResource=async(e,t,n)=>{if(!n){logger.warn(`No suitable extension available. Downloading as a direct link...`);let{source:n,metadata:r}=createDirectMediaMetadata(e);return n.audioLanguage=t.languages?.[0],n.http2=t.http2,{source:n,metadata:r}}if(configureExtensionProxy(n,t),await initializeExtension(n),getExtensionApiVersion(n)===`v2`){let r=getCompatibleExtensionExports(n);logger.info(`Resolving media entries...`);let i=await r.resolveEntries(e,t);if(!i?.length)return logger.info(`No metadata found`),null;let a=i.map(t=>{let r=t,i=serializeMediaEntry(t),a=t.input?createEntryCacheKey(n,e,r):void 0;a&&t.input&&resolvedInputs.set(a,t.input);let o=t.input?extractInputSource(t.input):null;return{source:o??{url:e},metadata:createEntryMetadata(i,n),extension:{api:`v2`,entry:i,cacheKey:a,hasResolvedSource:!!o}}});return logger.info(`Resolving media entries finished`),normalizeResolvedResources(a)}return logger.info(`Fetching content metadata...`),normalizeResolvedResources(await resolveLegacyMediaResources(e,t,n))},materializeMediaResource=async({resource:e,url:t,options:n,extension:r})=>{if(!r||!e.extension||e.extension.api!==`v2`||getExtensionApiVersion(r)!==`v2`)return{source:e.source};configureExtensionProxy(r,n),await initializeExtension(r);let i=getCompatibleExtensionExports(r),a=e.extension.entry,o=e.extension.cacheKey?resolvedInputs.get(e.extension.cacheKey):void 0;if(!o&&typeof i.resolveMedia==`function`&&(o=await i.resolveMedia(t,n,a)??void 0,o&&e.extension.cacheKey&&resolvedInputs.set(e.extension.cacheKey,o)),!o){if(e.extension.hasResolvedSource)return{source:e.source,entry:a};throw Error(`Extension ${r.package.name} could not materialize media entry. Provide resolveMedia() or an inline input rooted in UrlSource.`)}return{source:extractInputSource(o,e.source)??e.source,input:o,entry:a}},resolveMediaResourceDrm=async(e,t,n)=>resolveLegacyMediaResourceDrm(e,t,n);var DownloadRunState=class{#e=[];#t=new Set;#n=new Map;#r=new Map;#i=new Set;get activeRunCount(){return this.#r.size}get queuedCount(){return this.#e.length}getActiveRun(e){return this.#r.get(e)}setActiveRun(e,t){this.#r.set(e,t)}deleteActiveRun(e){this.#r.delete(e)}getActiveJob(e){return this.#n.get(e)}setActiveJob(e){this.#n.set(e.id,e)}deleteActiveJob(e){this.#n.delete(e)}queueResumeAfterStop(e){this.#i.add(e)}consumeResumeAfterStop(e){let t=this.#i.has(e);return t&&this.#i.delete(e),t}enqueue(e){this.#t.has(e.id)||this.#r.has(e.id)||(this.#e.push(e.id),this.#t.add(e.id))}dequeue(e){if(!this.#t.has(e))return!1;let t=this.#e.indexOf(e);return t!==-1&&this.#e.splice(t,1),this.#t.delete(e),!0}dequeueNext(e){for(;this.#e.length>0;){let t=this.#e.shift();if(!t)return;this.#t.delete(t);let n=e(t);if(n&&n.status===`queued`)return n}}};const ERROR_DETAIL_KEYS=[`code`,`errno`,`syscall`,`address`,`port`,`host`,`hostname`,`path`,`type`],isResponseLike=e=>typeof e==`object`&&!!e&&`status`in e&&`statusText`in e&&`url`in e,getOwnErrorDetails=e=>{let t=[],n=e;for(let e of ERROR_DETAIL_KEYS){let r=n[e];r==null||r===``||t.push(`${e}=${String(r)}`)}return t},formatErrorDetails=(e,t=0)=>{if(t>3)return`[max-depth]`;if(e instanceof Error){let n=getOwnErrorDetails(e),r=`cause`in e?e.cause:void 0,i=[`${e.name}: ${e.message}`];return n.length&&i.push(`details=${n.join(`, `)}`),r!==void 0&&r!==e&&i.push(`cause=${formatErrorDetails(r,t+1)}`),i.join(` | `)}return isResponseLike(e)?`Response ${e.status} ${e.statusText} url=${e.url}`:inspect(e,{depth:2,breakLength:1/0})},logErrorDetails=(e,t)=>{logger.debug(`${e}: ${formatErrorDetails(t)}`),t instanceof Error&&t.stack&&logger.debug(t.stack)},getTrackDescription=(e,t)=>{let n=`${t} ∙ `;return e.type===`subtitle`?n+=`SUBTITLES`:n+=e.type?.toUpperCase(),e.type===`video`&&(e.width&&(n+=` ∙ ${e.width}x${e.height}`),e.bitrate&&(n+=` ∙ ${Math.round(e.bitrate/1e3)} KiB/s`)),e.type===`audio`&&(e.languageCode&&(n+=` ∙ ${e.languageCode.toUpperCase()}`),e.name&&(n+=` (${e.name})`),e.sampleRate&&(n+=` ∙ ${e.sampleRate} kHz`),e.bitrate&&(n+=` ∙ ${Math.round(e.bitrate/1e3)} KiB/s`)),e.type===`subtitle`&&(e.languageCode&&(n+=` ∙ ${e.languageCode.toUpperCase()}`),e.name&&(n+=` (${e.name})`),e.forced&&(n+=` FORCED`)),n},getTrackId=e=>e.id,findDuplicateTrackIds=e=>{let t=new Map;for(let n of e){let e=getTrackId(n),r=t.get(e);if(r){r.push(n);continue}t.set(e,[n])}return Array.from(t.entries()).filter(([,e])=>e.length>1)},assertUniqueTrackIds=e=>{let t=findDuplicateTrackIds(e);if(!t.length)return;let n=t.map(([e,t])=>`${e} (${t.length} copies)`).join(`, `);throw Object.assign(Error(`Duplicate tracks selected: ${n}`),{code:`DUPLICATE_TRACKS_SELECTED`})},getErrorCode=e=>{if(!e||typeof e!=`object`||!(`code`in e))return;let t=e.code;return typeof t==`string`?t:void 0};var DownloaderError=class extends Error{code;constructor(e,t=e,n){super(t,n),this.name=`DownloaderError`,this.code=e}};const normalizeDownloaderError=(e,t=`DOWNLOAD_FAILED`)=>{if(e instanceof DownloaderError||e instanceof Error&&e.name===`AbortError`)return e;if(e instanceof Error){let n=new DownloaderError(getErrorCode(e)??t,e.message,{cause:e});return e.stack&&(n.stack=e.stack),n}return new DownloaderError(t,typeof e==`string`?e:`Unknown error`)},sanitizeFilename=e=>{let t=e.replace(/[<>:"/\\|?*\x00-\x1F]/g,``);t=t.replace(/^[\s.]+|[\s.]+$/g,``),t=t.replace(/\s+/g,` `);let n=t.lastIndexOf(`.`),r=n>0,i=r?t.slice(n):``,a=r?t.slice(0,n):t;if(i.length>=255)t=t.slice(0,255);else{let e=255-i.length;a.length>e&&(a=a.slice(0,e)),t=a+i}let o=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i;if(i.length<255){let e=t.lastIndexOf(`.`),n=e>0;if(i=n?t.slice(e):``,a=n?t.slice(0,e):t,o.test(a)){let e=255-i.length;t=`_${a}`.slice(0,e)+i}}return t.length===0?`untitled`:t},fillTemplate=(e,t)=>Object.keys(t).reduce((e,n)=>{let r=`{${n}}`,i=t[n];if(!i){let t=RegExp(`(?:\\.|^)\\{${n}\\}(?=\\.|$)|\\{${n}\\}(\\.|$)|\\{${n}\\}`,`g`);return e.replace(t,(e,t)=>``).replaceAll(`....`,`...`)}return e.replaceAll(r,i)},e).replaceAll(` `,` `),resolveContainerFormat=e=>typeof e==`string`&&e.trim()||`mp4`,createDownloadMetadata=e=>{let t=`seasonNumber`in e?`${e.seasonNumber}`:``,n=`episodeNumber`in e?`${e.episodeNumber}`:``,r=t?`S${t}`:``,i=n?`E${n}`:``,a=t&&n?`${r}:${i}`:``,o=`episodeTitle`in e&&e.episodeTitle?.trim()?`"${e.episodeTitle}"`:``;return{title:`${e.title??``} ${a} ${o}`.trim()}},resolveDownloadOutputPlan=({settings:e,options:t,source:n,meta:r,allTracks:i})=>{let a=r.title,o=r.tag,s=`seasonNumber`in r?r.seasonNumber:void 0,c=`episodeNumber`in r?r.episodeNumber:void 0,l=`episodeTitle`in r?r.episodeTitle:``,u=i.find(e=>e.type===`video`)?.codec??``,d=e.get(`downloadDir`),f=t.movieTemplate||e.get(`movieFilenameTemplate`),p=t.episodeTemplate||e.get(`seriesFilenameTemplate`),m=`${sanitizeFilename(fillTemplate(c?p:f,{title:a??``,s:s?s.toString().padStart(2,`0`):``,e:c?c.toString().padStart(2,`0`):``,quality:t.videoQuality??``,codec:u,tag:o??``,episodeTitle:l??``,audioType:n.audioType?n.audioType.toUpperCase():``,format:`WEB-DL`}))}.${resolveContainerFormat(t.format||e.get(`videoContainerFormat`))}`,h=t.outputPath||join(d,m),g=parse(h);return{downloadDir:d,outputPath:h,resolvedFilenameWithoutExtension:g.name,filenameWithExtension:g.base,outputDirectory:g.dir||d,downloadMetadata:createDownloadMetadata(r)}},openFileHandle=async(e,t,n)=>n??open(e,t),createMediabunnyFileSource=e=>{let t=null;return new StreamSource({getSize:async()=>(t=await openFileHandle(e,`r`,t),(await t.stat()).size),read:async(n,r)=>{t=await openFileHandle(e,`r`,t);let i=new Uint8Array(r-n);return await t.read(i,0,r-n,n),i},dispose:async()=>{let e=t;t=null,await e?.close()},prefetchProfile:`fileSystem`})},createMediabunnyFileTarget=e=>{let t=null;return new StreamTarget(new WritableStream({start:async()=>{t=await openFileHandle(e,`w`,t)},write:async n=>{if(!t)throw Error(`MediaBunny output handle was not initialized for ${e}`);await t.write(n.data,0,n.data.byteLength,n.position)},close:async()=>{let e=t;t=null,await e?.close()},abort:async()=>{let e=t;t=null,await e?.close()}}),{chunked:!0})},inspectMedia=async(e,t)=>{let n=new Input$1({formats:ALL_FORMATS$1,source:e.startsWith(`https`)?new UrlSource$1(e,{requestInit:{headers:t}}):createMediabunnyFileSource(e)});return{tracks:await n.getTracks(),primaryVideoTrack:await n.getPrimaryVideoTrack(),primaryAudioTrack:await n.getPrimaryAudioTrack()}},ALL_DASHA_FORMATS=[...DASH_FORMATS,...HLS_FORMATS],SENSITIVE_HEADER_KEYS=new Set([`authorization`,`cookie`,`set-cookie`,`api-key`]),getSafeHeadersForLogging=e=>Object.fromEntries(Object.keys(e).map(t=>[t,SENSITIVE_HEADER_KEYS.has(t.toLowerCase())?`[REDACTED]`:e[t]])),getManifestFormats=e=>e===`mpd`?DASH_FORMATS:e===`m3u8`?HLS_FORMATS:ALL_DASHA_FORMATS,createManifestInput=({http:e,source:t,detection:n})=>(logger.debug(`Fetching manifest...`),logger.debug(t.url),t.headers&&logger.debug(JSON.stringify(getSafeHeadersForLogging(t.headers))),new Input({source:new UrlSource(t.url,{requestInit:{headers:t.headers},fetchFn:e.fetch.bind(e)}),formats:getManifestFormats(n.kind)})),getStableHash=e=>createHash(`sha1`).update(e).digest(`hex`),normalizeTrackLanguageCode=(e,t)=>{if(e)switch(e){case`aar`:case`abk`:return`rus`;case`ave`:return`eng`;case`zu`:return t?.includes(`start.film`)?`ru`:`zu`;default:return e}},createPreparedTrackId=({origin:e,type:t,sourceUrl:n,languageCode:r,name:i,codec:a})=>`${e}:${t}:${getStableHash([n??``,r??``,i??``,a??``].join(`|`))}`,createPreparedTrackFromManifestTrack=async(e,t)=>{let[n,r,i,a,o,s]=await Promise.all([e.getCodec(),e.getBitrate(),e.getLanguageCode(),e.getName(),e.getDisposition(),e.hasOnlyKeyPackets()]),c={id:`manifest:${e.type}:${e.id}`,origin:`manifest`,type:e.type,codec:n,bitrate:r,languageCode:normalizeTrackLanguageCode(i,t),name:a,forced:o.forced,hearingImpaired:o.hearingImpaired,visuallyImpaired:o.visuallyImpaired,isDefault:o.default,isIFrameOnly:s,inputTrack:e};if(e.isVideoTrack()){let[t,n]=await Promise.all([e.getDisplayWidth(),e.getDisplayHeight()]);c.width=t,c.height=n}if(e.isAudioTrack()){let[t,n]=await Promise.all([e.getNumberOfChannels(),e.getSampleRate()]);c.numberOfChannels=t,c.sampleRate=n}return c},ensurePreparedTrackSegments=async e=>e.segments?e.segments:e.inputTrack?(e.segmentsPromise??=e.inputTrack.getSegments().then(t=>(e.segments=t,e.segmentCount=t.length,t)),e.segmentsPromise):(e.segments=[],e.segmentCount=0,e.segments),filterByCodecs=(e,t)=>{let n=e.filter(e=>t.some(t=>t===e.codec));return n.length?n:e.toSorted((e,t)=>(t.bitrate??0)-(e.bitrate??0))},filterByQuality=(e,t)=>{let n=t?parseInt(String(t),10)*16/9:void 0,r=e.toSorted((e,t)=>(t.bitrate??0)-(e.bitrate??0));if(!t)return r;let i=e.filter(e=>Number(e.height)===Number(t));if(i.length)return i;let a=e.filter(e=>Number(e.width)===Number(n));return a.length?a:r},filterByChannels=(e,t)=>e.filter(e=>e.numberOfChannels===Number(t)),normalizeLanguage=e=>e?.trim().toLowerCase()??``,getLanguageFamily=e=>normalizeLanguage(e).slice(0,2),getLanguageVariant=e=>normalizeLanguage(e)||`und`,matchesRequestedLanguage=(e,t)=>{let n=normalizeLanguage(e),r=normalizeLanguage(t);return!n||!r?!1:n===r||n.startsWith(`${r}-`)?!0:getLanguageFamily(n)===getLanguageFamily(r)},getUniqueLanguageFamilies=e=>Array.from(new Map(e.map(e=>normalizeLanguage(e)).filter(Boolean).map(e=>[getLanguageFamily(e),e])).values()),takeBestTracksPerVariant=(e,t)=>{let n=new Map;for(let r of e){let e=getLanguageVariant(r.languageCode),i=n.get(e);if(!i){n.set(e,[r]);continue}i.length<t&&i.push(r)}return Array.from(n.values()).flat()},filterByLanguages=(e,t,n=1)=>{let r=e.toSorted((e,t)=>(t.bitrate??0)-(e.bitrate??0)),i=getUniqueLanguageFamilies(t),a=[];for(let e of i){let t=r.filter(t=>matchesRequestedLanguage(t.languageCode,e));t.length&&a.push(...takeBestTracksPerVariant(t,n))}let o=getUniqueLanguageFamilies(e.map(e=>e.languageCode||`und`));if(!a.length)for(let e of o){let t=r.filter(t=>matchesRequestedLanguage(t.languageCode??`und`,e));t.length&&a.push(...takeBestTracksPerVariant(t,n))}return a},filterPairableAudios=(e,t)=>{if(!t?.inputTrack)return e;let n=t.inputTrack,r=e.filter(e=>e.inputTrack?e.inputTrack.canBePairedWith(n):!0);return r.length?r:e},toKbps=e=>(e??0)/1e3,getSegmentCountLabel=async e=>{if(typeof e.segmentCount==`number`)return`${e.segmentCount} Segments`;if(!e.inputTrack)return`Direct`;try{return`${(await ensurePreparedTrackSegments(e)).length} Segments`}catch{return`? Segments`}},buildSelectedTracks=({videos:e,audios:t,subtitles:n})=>({videos:e,audios:t,subtitles:n,all:[...e,...t,...n]});async function getTracks(e,t,n){let r=t.videoQuality,i=e.filter(e=>e.type===`video`&&!e.isIFrameOnly),a=e.filter(e=>e.type===`audio`),o=e.filter(e=>e.type===`subtitle`);if(t.select){let e=await Promise.all(i.map(async(e,t)=>({name:`${e.width??`?`}x${e.height??`?`} | ${toKbps(e.bitrate)||`?`} Kbps | ${e.codec??`?`} | ${await getSegmentCountLabel(e)}`,value:e.id,checked:t===0}))),t=i.length?await checkbox({message:`Select video streams`,pageSize:12,choices:e,loop:!1}):[],n=i.filter(e=>t.includes(e.id)),r=await Promise.all(a.map(async(e,t)=>({name:`${e.name?`${e.name} | `:``}${toKbps(e.bitrate)||`?`} Kbps | ${e.codec?`${e.codec} | `:``}${e.languageCode||`und`} | ${e.numberOfChannels??`?`}CH | ${await getSegmentCountLabel(e)}`,value:e.id,checked:t===0}))),s=a.length?await checkbox({message:`Select audio streams`,pageSize:12,choices:r,loop:!1}):[],c=a.filter(e=>s.includes(e.id)),l=await Promise.all(o.map(async(e,t)=>({name:`${e.codec??`?`} | ${e.languageCode||`und`} | ${await getSegmentCountLabel(e)}`,value:e.id,checked:t===0}))),u=o.length?await checkbox({message:`Select subtitles`,pageSize:12,choices:l,loop:!1}):[];return buildSelectedTracks({videos:n,audios:c,subtitles:o.filter(e=>u.includes(e.id))})}t.videoCodecs&&(i=filterByCodecs(i,t.videoCodecs)),i=filterByQuality(i,r||NaN);let s=i[0],c=[...t.languages||[]],l=n.audioLanguage?.slice(0,2);!c.length&&l&&c.push(l);let u=filterPairableAudios(a,s);t.audioChannels&&(u=filterByChannels(u,t.audioChannels)),t.audioCodecs&&(u=filterByCodecs(u,t.audioCodecs));let d=filterByLanguages(u,c,1);d.length&&(u=d);let f=c.at(-1),p=f?u.map(e=>!e.languageCode||e.languageCode===`und`?{...e,languageCode:f}:e):u,m=o.filter(e=>t.subtitleLanguages?.length?t.subtitleLanguages.some(t=>matchesRequestedLanguage(e.languageCode||`und`,t)):!1);return buildSelectedTracks({videos:t.skipVideo||!s?[]:[s],audios:t.skipAudio?[]:p,subtitles:t.skipSubtitles?[]:m})}const createEmptyPreparedTracks=()=>({videos:[],audios:[],subtitles:[],all:[]}),audioCodecMap={aac:`aac`,mp4a:`aac`,"mp4a.40.2":`aac`,ac3:`ac3`,"ac-3":`ac3`,eac3:`eac3`,"ec-3":`eac3`,opus:`opus`,vorbis:`vorbis`,flac:`flac`},tryGetUrl=e=>{if(!e)return null;try{return new URL(e)}catch{return null}},normalizePathname=e=>{let t=tryGetUrl(e);if(t)try{return decodeURIComponent(t.pathname)}catch{return t.pathname}},normalizeAudioStreamCodec=e=>{if(!e)return`aac`;let t=e.toLowerCase();return audioCodecMap[t]??audioCodecMap[t.split(`.`)[0]??``]??`aac`},countTracksByType=(e,t)=>e.filter(e=>e.type===t).length,logExtractedTracks=e=>{let t=`Extracted, there are `;if(e.length===0)t+=`no tracks`;else{t+=`${e.length} tracks`;let n=countTracksByType(e,`video`);n&&(t+=`, ${n} video tracks`);let r=countTracksByType(e,`audio`);r&&(t+=`, ${r} audio tracks`);let i=countTracksByType(e,`subtitle`);i&&(t+=`, ${i} subtitle tracks`)}logger.info(t)},appendAdditionalSubtitles=(e,t=[])=>{let n=[...t];for(let t of e.subtitles??[]){let r=normalizePathname(t.url),i=normalizeTrackLanguageCode(t.language,e.url);n.some(e=>{let t=normalizePathname(e.sourceUrl);return!r||!t?!1:r===t})||n.push({id:createPreparedTrackId({origin:`external-subtitle`,type:`subtitle`,sourceUrl:t.url,languageCode:i,name:t.label||t.title,codec:t.format}),origin:`external-subtitle`,type:`subtitle`,sourceUrl:t.url,languageCode:i,codec:t.format,forced:t.forced,name:t.label||t.title})}return n},prepareProgressiveSource=async({options:e,source:t,meta:n,detection:r})=>{let i={...e},a={...n};if(!a.title){let e=tryGetUrl(t.url)?.pathname.split(`/`).pop();e&&(a.title=e)}let{primaryVideoTrack:o,primaryAudioTrack:s}=await inspectMedia(t.url,t.headers),c=await o?.getCodec(),l=await o?.getCodedWidth(),u=await o?.getCodedHeight();i.videoQuality||=u?`${u}p`:void 0;let d=createEmptyPreparedTracks();if(d.subtitles=appendAdditionalSubtitles(t),d.all.push(...d.subtitles),r.isAudio&&!i.skipAudio){let e={id:createPreparedTrackId({origin:`progressive`,type:`audio`,sourceUrl:t.url,languageCode:t.audioLanguage,codec:await s?.getCodec()}),origin:`progressive`,type:`audio`,codec:normalizeAudioStreamCodec(await s?.getCodec()),languageCode:normalizeTrackLanguageCode(await s?.getLanguageCode(),t.url)??normalizeTrackLanguageCode(t.audioLanguage,t.url)??`und`,numberOfChannels:await s?.getNumberOfChannels(),sampleRate:await s?.getSampleRate(),sourceUrl:t.url};return d.audios.push(e),d.all.push(e),{options:i,source:t,meta:a,allTracks:[e],tracks:d}}if(!i.skipVideo){let e=parseInt((i.videoQuality??``).replace(`p`,``),10),n={id:createPreparedTrackId({origin:`progressive`,type:`video`,sourceUrl:t.url,codec:c}),origin:`progressive`,type:`video`,codec:c??`avc`,width:l??void 0,height:u??(e||void 0),sourceUrl:t.url};return d.videos.push(n),d.all.push(n),{options:i,source:t,meta:a,allTracks:[n],tracks:d}}return{options:i,source:t,meta:a,allTracks:[],tracks:d}},prepareInputSource=async({options:e,source:t,meta:n,input:r,disposeInput:i=!0})=>{let a={...e},o={...n},s=i;try{let e=await r.getTracks();if(!e.length)throw new DownloaderError(`MANIFEST_PARSE_FAILED`,`Failed to parse manifest`);let n=await Promise.all(e.map(e=>createPreparedTrackFromManifestTrack(e,t.url)));logExtractedTracks(n);let c=await getTracks(n,a,t),l=c.videos[0]?.height;if(l&&(a.videoQuality=`${l}p`),!o.title){let e=tryGetUrl(t.url)?.host;e&&(o.title=`${e}_${getCurrentDateTimeString()}`)}return s=!1,{options:a,source:t,meta:o,allTracks:n,tracks:c,dispose:i?()=>r.dispose?.():void 0}}finally{s&&r.dispose?.()}},prepareManifestSource=async({http:e,options:t,source:n,meta:r,detection:i})=>prepareInputSource({options:t,source:n,meta:r,input:createManifestInput({http:e,source:n,detection:i})}),prepareSource=async({http:e,options:t,source:n,meta:r,input:i,detection:a})=>i?prepareInputSource({options:t,source:n,meta:r,input:i,disposeInput:!1}):a.strategy===`progressive`?prepareProgressiveSource({options:t,source:n,meta:r,detection:a}):prepareManifestSource({http:e,options:t,source:n,meta:r,detection:a}),hasSuffix=(e,t)=>{try{let n=new URL(e);return n.pathname.endsWith(t)||n.search.endsWith(t)}catch{return!1}},selectPreparationStrategy=async(e,t)=>{let n=hasSuffix(t.url,`.m3u8`),r=hasSuffix(t.url,`.mpd`),i=hasSuffix(t.url,`.mp4`),a=hasSuffix(t.url,`.mov`),o=!1,s=!1;if(!n&&!r&&!i&&!a)try{let n=await e.fetch(t.url,{method:`HEAD`,headers:t.headers});if(!n.ok)logger.warn(`HEAD request for ${t.url} returned ${n.status} ${n.statusText}`);else{let e=n.headers.get(`content-type`);o=!!e?.includes(`audio`),s=!!e?.includes(`video`)}}catch(e){let n=e instanceof Error?e.message:String(e);logger.warn(`HEAD request failed for ${t.url}: ${n}`)}return r?{strategy:`manifest`,kind:`mpd`,isAudio:o,isVideo:s,matchedContentLabel:`Dynamic Adaptive Streaming over HTTP`}:n?{strategy:`manifest`,kind:`m3u8`,isAudio:o,isVideo:s,matchedContentLabel:`HTTP Live Streaming`}:o||s||i||a?{strategy:`progressive`,kind:`progressive`,isAudio:o,isVideo:s,matchedContentLabel:`Progressive Stream`}:{strategy:`manifest`,kind:`unknown`,isAudio:o,isVideo:s}},retry=async({attempts:e,fn:t,shouldRetry:n,onRetry:r})=>{let i=Math.max(1,Math.trunc(e)),a;for(let e=1;e<=i;e+=1)try{return await t(e)}catch(t){if(a=t,e>=i||!n?.(t,e))throw t;await r?.(t,e)}throw a instanceof Error?a:Error(String(a))},forceNanospinnerTtyIfNeeded=()=>{if(process.platform===`win32`&&!isatty(process.stderr.fd)&&loadWinConsoleAddon()?.getConsoleSize?.()?.columns)try{let e=__require(`nanospinner/dist/consts.js`);e&&e.isTTY===!1&&(e.isTTY=!0,e.symbols?.frames?.length===1&&(e.symbols.frames=[`-`,`\\`,`|`,`/`]))}catch{}},getSpinnerStream=e=>{let t=process.stderr;if(!e||process.platform!==`win32`)return t;if(!t.columns||t.columns!==e){let n=Object.getOwnPropertyDescriptor(t,`columns`)??Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t),`columns`);if(!n||n.writable||n.set)try{t.columns=e}catch{}if(t.columns!==e){let n=Object.create(t);return Object.defineProperty(n,`columns`,{value:e,configurable:!0,enumerable:!0,writable:!0}),logger.warn(`Unable to override stderr.columns; using spinner-local width ${e}.`),n}}return t},logLevelsColors={debug:`gray`,info:`green`,warn:`yellow`,error:`red`},getColorizedLogLevel=e=>{let t=e.toUpperCase(),n=colors[logLevelsColors[e]];return n(t)},withPrefixedText=(e,t)=>typeof t==`string`?`${e} ${t}`:t&&{...t,text:`${e} ${t.text??``}`.trimEnd()},createSpinner$1=(e,t)=>{forceNanospinnerTtyIfNeeded();let n=getLogPrefix(getColorizedLogLevel(`info`)),r=createSpinner(e,{stream:getSpinnerStream(loadWinConsoleAddon()?.getConsoleSize?.()?.columns??process.stderr.columns??process.stdout.columns??(process.platform===`win32`?120:80))}).start({text:`${n} ${e}`,color:t}),i=r.update.bind(r),a=r.success.bind(r),o=r.error.bind(r);return r.update=e=>i(withPrefixedText(n,e)),r.success=e=>a(withPrefixedText(n,e)),r.error=e=>o(withPrefixedText(n,e)),r},MAX_SAFE_MOLNIA_WORKERS=16,getWidevinePssh=e=>{if(!(!e||typeof e!=`object`||!(`drm`in e)))return e.drm?.widevine?.pssh},getTrackResumeKey=(e,t)=>createHash(`sha1`).update(`${e}:${getTrackId(t)}`).digest(`hex`),buildTrackArtifactPath=({outputDirectory:e,resolvedFilenameWithoutExtension:t,track:n})=>join(e,`${t}.${createHash(`sha256`).update(getTrackId(n)).digest(`hex`).slice(0,6)}.${n.type===`subtitle`?`vtt`:n.type===`audio`?`m4a`:`mp4`}`),getSegmentRangeHeaders=(e,t)=>{if(t)return{Range:`bytes=${e}-${e+t-1}`}},buildTrackDownloadInput=async e=>{if(e.sourceUrl&&!e.inputTrack)return e.sourceUrl;let t=[],n=await ensurePreparedTrackSegments(e),r=n[0];r?.initSegment&&t.push({url:r.initSegment.location.path,headers:getSegmentRangeHeaders(r.initSegment.location.offset,r.initSegment.location.length)});for(let e of n)t.push({url:e.location.path,headers:getSegmentRangeHeaders(e.location.offset,e.location.length)});return!t.length&&e.sourceUrl?e.sourceUrl:t.length===1&&!t[0]?.headers?t[0].url:t},resolveMaxWorkerCount=e=>{let t=Math.max(1,Math.trunc(e)),n=Math.min(MAX_SAFE_MOLNIA_WORKERS,t);return{normalizedRequestedConnections:t,maxWorkerCount:n,wasClamped:t!==n}},resolveMaxAttempts=e=>Math.max(1,Math.trunc(e)+1),buildTrackResume=(e,t)=>t.origin===`manifest`?{enabled:!0,key:getTrackResumeKey(e,t)}:!0,buildTrackProgressInfo=({title:e,progress:t,track:n,filepath:r,target:i})=>{let a={b:t.totalBytes??NaN,mb:(t.totalBytes??NaN)/1024/1024},o={b:t.bytesDownloaded??NaN,mb:(t.bytesDownloaded??NaN)/1024/1024},s=t.totalBytes?Math.round(t.bytesDownloaded/t.totalBytes*100):void 0;return{title:e,total:a,current:o,percentage:s,speed:{bps:t.bytesPerSecond??NaN,mbps:(t.bytesPerSecond??NaN)/1024/1024},trackName:basename(r),trackPath:r,finalName:i.finalName,finalPath:i.finalPath,state:s===100?`downloaded`:`downloading`,quality:n.type===`video`&&n.width?`${n.width}x${n.height}`:void 0,codec:n.type===`video`?n.codec??void 0:void 0}},buildTrackProgressMessage=e=>`Downloading ∙ ${`${(e.bytesDownloaded/1024/1024).toFixed(2)} MB`}${e.totalBytes?` of ${(e.totalBytes/1024/1024).toFixed(2)} MB`:``}`,collectPsshList=e=>e.flatMap(e=>{let t=e.segments?.[0],n=getWidevinePssh(t?.initSegment?.encryption)??getWidevinePssh(t?.encryption);return n?[n]:[]}).map(e=>{let t=e;return typeof t==`string`?t:t instanceof Uint8Array||t instanceof ArrayBuffer?Buffer.from(t).toString(`base64`):ArrayBuffer.isView(t)?Buffer.from(t.buffer).toString(`base64`):String(t)}),toDownloadArtifact=(e,t)=>({path:t,type:e.type,language:e.languageCode,label:e.name??void 0,forced:e.type===`subtitle`?e.forced:!1}),downloadTrack=async({track:e,filepath:t,description:n,target:r,source:i,options:a,settings:o,abortSignal:s,title:c,emitProgress:l})=>{logger.info(n),logger.debug(`Path: ${t}`);let u=a.connections??o.get(`connections`)??1,{maxWorkerCount:d,wasClamped:f}=resolveMaxWorkerCount(u);f&&logger.warn(`Connections value ${u} was clamped to ${d} for stability`),logger.debug(`Max worker count: ${d}`);let p=createSpinner$1(`Downloading`,`yellow`),m=``,h=await buildTrackDownloadInput(e),g=resolveMaxAttempts(a.retry??o.get(`retry`)??1);try{await retry({attempts:g,fn:async()=>{let n=await Download.init({input:h,output:t,tempDir:APP_TEMP_DIR,requestInit:{headers:i.headers,signal:s},proxy:a.proxyMedia||a.proxy||void 0,resume:buildTrackResume(i.url,e),maxRetries:a.retry,maxWorkerCount:d,onProgress:n=>{l(buildTrackProgressInfo({title:c,progress:n,track:e,filepath:t,target:r})),m=buildTrackProgressMessage(n),p.update(m)}});if(s?.aborted){logger.debug(`Track download skipped, already aborted: ${t}`);let e=Error(`The operation was aborted`);throw e.name=`AbortError`,e}await n.execute()},shouldRetry:e=>!(e instanceof Error&&e.name===`AbortError`),onRetry:async(e,n)=>{let r=e instanceof Error?e.message:String(e);logger.warn(`Track download retry ${n}/${g-1} scheduled for ${t}: ${r}`)}}),p.success(m)}catch(e){if(p.error(n),e instanceof Error&&e.name===`AbortError`)throw e;let t=e instanceof Error?e.message:String(e);throw logger.error(`Download track failed: ${t}`),e instanceof Error&&e.stack?logger.debug(e.stack):logger.debug(t),e instanceof Error?e:Error(t)}},isAbortError=e=>e instanceof Error&&e.name===`AbortError`,isAbortSignal=e=>!!e&&typeof e==`object`&&`aborted`in e&&`addEventListener`in e&&typeof e.addEventListener==`function`;var Downloader=class extends EventEmitter{#e;#t;#n;#r;#i;#a;constructor({settings:e,downloadsStorage:t}){super(),this.#i=e,this.#a=t}async start(e,t,n={id:crypto.randomUUID()},r,i){isAbortSignal(r)?(this.#r=new AbortController,r.addEventListener(`abort`,()=>{this.#r?.abort()})):this.#r=void 0;let a=new HttpClient({proxyUrl:e.proxy||e.proxyMeta||void 0});this.#e={...e},this.#t=t,this.#n={...n};let o;try{this.#o();let e=await selectPreparationStrategy(a,this.#t);e.matchedContentLabel&&logger.info(`Content Matched: ${e.matchedContentLabel}`),logger.info(`Parsing streams...`),o=await prepareSource({http:a,options:this.#e,source:this.#t,meta:this.#n,input:i,detection:e}),this.#e=o.options,this.#n=o.meta,await assertDownloadDirWritable(this.#i.get(`downloadDir`));let t=resolveDownloadOutputPlan({settings:this.#i,options:this.#e,source:this.#t,meta:this.#n,allTracks:o.allTracks});return this.#s(t.outputPath,t.resolvedFilenameWithoutExtension),await this.#c(o,t)}catch(e){if(isAbortError(e))throw e;let t=normalizeDownloaderError(e);throw this.emit(`error`,t),t}finally{await o?.dispose?.()}}#o(){logger.debug(`URL: ${this.#t.url}`);let e=`seasonNumber`in this.#n?this.#n.seasonNumber:void 0,t=`episodeNumber`in this.#n?this.#n.episodeNumber:void 0,n=`episodeTitle`in this.#n?this.#n.episodeTitle:``,r=[this.#n.title,e?`S${e}`:``,t?`E${t}`:``,n].filter(Boolean).join(` ∙ `);r&&logger.info(r)}#s(e,t){this.emit(`output-path`,e),logger.debug(`Resolved output path: ${e}`);let n=createDownloadMetadata(this.#n),r=this.#a.getByFilePath(e);r&&(r.title=n.title||t),logger.debug(`Emit download start`),this.emit(`start`,this.#a.jobs)}async#c(e,t){logger.debug(`Downloading tracks`);let n=[];assertUniqueTrackIds(e.tracks.all);for(let r of e.tracks.all){let e=buildTrackArtifactPath({outputDirectory:t.outputDirectory,resolvedFilenameWithoutExtension:t.resolvedFilenameWithoutExtension,track:r}),i=getTrackDescription(r,t.resolvedFilenameWithoutExtension);r.type===`subtitle`&&logger.debug(`URL: ${r.sourceUrl??`manifest subtitle track`}`),await downloadTrack({track:r,filepath:e,description:i,target:{finalName:t.filenameWithExtension,finalPath:t.outputPath},source:this.#t,options:this.#e,settings:this.#i,abortSignal:this.#r?.signal,title:createDownloadMetadata(this.#n).title,emitProgress:e=>{this.emit(`progress`,e,t.outputPath)}}),await exists(e)&&n.push(toDownloadArtifact(r,e))}return{downloaded:n,psshList:collectPsshList(e.tracks.all),selectedTracks:e.tracks.all}}};const describeUrl=e=>{try{let t=new URL(e),n=[...new Set(t.searchParams.keys())],r=n.length?`?${n.join(`,`)}`:``;return`${t.origin}${t.pathname}${r}`}catch{return e}},getContentKeys=async(e,t)=>{let{verbose:n,url:r,resolveLicense:i}=t,a=Buffer.from(e,`base64`),o=`cenc`,s=joinUrl(getApiBaseUrl(),`drm`),c=new RemoteCdm({keySystem:`com.widevine.alpha`,baseUrl:s,headers:{Authorization:`Bearer ${authState.accessToken}`}}),l=`initializing`,u=null;try{logger.debug(`DRM key request started: license=${describeUrl(r)}, remoteCdm=${describeUrl(s)}, psshLength=${e.length}, initDataBytes=${a.length}`),l=`requesting-media-key-system-access`;let t=requestMediaKeySystemAccess(c.keySystem,[]);l=`creating-media-keys`;let o=await t.createMediaKeys({cdm:c});l=`creating-session`,u=o.createSession(),l=`generating-license-request`,logger.debug(`Generating license request...`);let d=u.waitForLicenseRequest();await u.generateRequest(`cenc`,a);let f=await d;logger.debug(`License request of ${f.length} bytes generated for session ${u.sessionId}`),l=`requesting-license`,logger.debug(`Requesting license at ${r}`);let p=await i({url:r,pssh:e,data:new Uint8Array(f),sessionId:u.sessionId});if(p[0]===123||p[0]===60){logger.debug(`License response is not binary`);let e=Buffer.from(p).toString(`utf8`);if(logger.debug(e),e.includes(`<html>`))throw Error(`Invalid license response`)}l=`updating-session`,logger.debug(`Updating session...`),await u.update(new Uint8Array(p)),l=`waiting-for-key-statuses-change`,logger.debug(`Waiting for key statuses change...`);let m=await u.waitForKeyStatusesChange();logger.debug(`Keys count: ${m.length}`),l=`closing-session`,await u.close(),await u.remove();for(let e of m){let t=`Key: ${e.keyId}:${e.key}`;n?logger.info(t):logger.debug(t)}return m.map(e=>({kid:e.keyId,key:e.key}))}catch(e){throw logger.error(`Failed to get DRM content keys at stage=${l} for license=${describeUrl(r)} via remoteCdm=${describeUrl(s)}`),logErrorDetails(`DRM content key error`,e),e}finally{if(u){try{await u.close()}catch{}try{await u.remove()}catch{}}}},extractDecryptionKeys=async({keys:e,drm:t,psshList:n,drmDir:r,resolveLicense:i,licenseUrl:a})=>{logger.debug(`Extracting decryption keys`);let o=[],s=t&&`keys`in t?t.keys:[],c=[...e||[],...s];c.length&&o.push(...c);let l=a??(t&&`server`in t?t.server:void 0);if(i&&l){let e=[...new Set(n??[])];for(let[t,n]of e.entries()){logger.debug(`Resolving DRM keys for PSSH ${t+1}/${e.length} using ${describeUrl(l)}`),logger.debug(`PSSH: ${n}`);let a=await getContentKeys(n,{url:l,resolveLicense:i,clientDir:r});a&&a.length&&o.push(...a)}o.length||(logger.warn(`Can't get decryption keys`),logger.debug(`PSSH: ${e.join(`, `)}`))}return o};var Decrypter=class{strategy;constructor(e){this.strategy=e}async prepare(){await this.strategy.prepare?.()}async process(e){let t=await this.strategy.decryptFile(e);return e.cleanup&&await rm(e.input,{force:!0}),t}};const normalizeHex=e=>e.replaceAll(`-`,``).toLowerCase();var ShifroDecrypter=class{async decryptFile(e){let t=new Map;for(let n of e.keys){if(!n.kid)throw Error(`Shifro requires a KID for every decryption key`);t.set(normalizeHex(n.kid),normalizeHex(n.key))}return logger.debug(`Decrypting via shifro: ${e.input}`),await(await Decryption.init({input:new Input$2({source:new FilePathSource(e.input),keys:t}),output:new Output$1({target:new FilePathTarget(e.output)})})).execute(),e.output}};const cueBlockHeaderRegex=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}\.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}\.\d{3})([^\n]*)/g,preambleStartRegex=/^\uFEFF?WEBVTT(?:.|\n)*?\n{2}/,subtitleTimestampRegex=/(?:(\d{2}):)?(\d{2}):(\d{2})\.(\d{3})/,knownLanguageCodes={ar:`ara`,de:`deu`,en:`eng`,es:`spa`,fr:`fra`,hi:`hin`,it:`ita`,ja:`jpn`,ko:`kor`,pl:`pol`,pt:`por`,ru:`rus`,th:`tha`,tr:`tur`,uk:`ukr`,und:`und`,vi:`vie`,zh:`zho`},isSubtitleInput=e=>e===`subtitle`||e===`text`,parseMuxTimestamp=e=>{let t=e.trim().split(`:`);if(t.length<2||t.length>3)throw Error(`Invalid trim timestamp: ${e}`);let n=Number(t.at(-1)),r=Number(t.at(-2)),i=t.length===3?Number(t[0]):0;if(![i,r,n].every(e=>Number.isFinite(e)&&e>=0))throw Error(`Invalid trim timestamp: ${e}`);return i*3600+r*60+n},parseSubtitleTimestamp=e=>{let t=subtitleTimestampRegex.exec(e);if(!t)throw Error(`Invalid WebVTT timestamp: ${e}`);return 3600*1e3*Number(t[1]||`0`)+60*1e3*Number(t[2])+1e3*Number(t[3])+Number(t[4])},formatWebVttTimestamp=e=>{let t=Math.floor(e/(3600*1e3)),n=Math.floor(e%(3600*1e3)/(60*1e3)),r=Math.floor(e%(60*1e3)/1e3),i=e%1e3;return`${t.toString().padStart(2,`0`)}:${n.toString().padStart(2,`0`)}:${r.toString().padStart(2,`0`)}.${i.toString().padStart(3,`0`)}`},formatSubtitleConversionIssues=e=>{let t=[e.invalidEntries?.length?`${e.invalidEntries.length} invalid entries`:void 0,e.invalidTimecodes?.length?`${e.invalidTimecodes.length} invalid timecodes`:void 0,e.invalidIndices?.length?`${e.invalidIndices.length} invalid indices`:void 0,e.timecodeIssues?.reversedTimecodes?.length?`${e.timecodeIssues.reversedTimecodes.length} reversed timecodes`:void 0,e.timecodeIssues?.overlappingTimecodes?.length?`${e.timecodeIssues.overlappingTimecodes.length} overlapping timecodes`:void 0].filter(Boolean);return t.length?` (${t.join(`, `)})`:``},convertSubtitleTextToWebVtt=e=>{let t=e.replaceAll(`\r
|
|
3
|
+
`,`
|
|
4
|
+
`).replaceAll(`\r`,`
|
|
5
|
+
`).trim();if(preambleStartRegex.test(t))return t;let{subtitle:n,status:r}=convert(e,`.vtt`);if(!r.success)throw Error(`Failed to convert subtitle to WebVTT${formatSubtitleConversionIssues(r)}.`);return n.replaceAll(`\r
|
|
6
|
+
`,`
|
|
7
|
+
`).replaceAll(`\r`,`
|
|
8
|
+
`).trim()},normalizeLanguageCode=e=>{if(!e)return;let t=e.trim().toLowerCase();if(!t)return;let n=t.split(`-`)[0]??t;return/^[a-z]{3}$/.test(n)?n:knownLanguageCodes[n]},createOutputFormat=e=>{switch(extname(e).toLowerCase()){case`.mp4`:return new Mp4OutputFormat;case`.mkv`:return new MkvOutputFormat;default:throw Error(`Unsupported mux output format: ${e}`)}},createInput=e=>new Input$1({formats:ALL_FORMATS$1,source:createMediabunnyFileSource(e)}),getTrimRange=e=>{let t=e.trimBegin?parseMuxTimestamp(e.trimBegin):void 0,n=e.trimEnd?parseMuxTimestamp(e.trimEnd):void 0;if(t!==void 0&&n!==void 0&&n<=t)throw Error(`trimEnd must be greater than trimBegin`);return{trimBegin:t,trimEnd:n}},prepareVideoTrack=async(e,t,n,r,i)=>{let a=createInput(t),o=await a.getPrimaryVideoTrack();if(!o)throw Error(`Missing video track in ${t}`);let s=o.codec;if(!s)throw Error(`Unknown video codec in ${t}`);if(i!==void 0&&i>=await o.computeDuration())throw Error(`trimBegin excludes the full video track in ${t}`);let c=new EncodedPacketSink(o),l=i===void 0?await c.getFirstKeyPacket({verifyKeyPackets:!0}):await c.getKeyPacket(i,{verifyKeyPackets:!0})??await c.getFirstKeyPacket({verifyKeyPackets:!0});if(!l)throw Error(`No video packets found in ${t}`);let u=new EncodedVideoPacketSource(s);return e.addVideoTrack(u,{disposition:o.disposition,name:n??o.name??void 0,rotation:r.supportsVideoRotationMetadata?o.rotation:void 0}),{kind:`video`,input:a,sink:c,source:u,startPacket:l,startTimestamp:l.timestamp,emit:async e=>{let t={decoderConfig:await o.getDecoderConfig()??void 0},n=!0;for await(let r of c.packets(l,void 0,{verifyKeyPackets:!0}))await u.add(r.clone({timestamp:r.timestamp-e}),n?t:void 0),n=!1;u.close()}}},prepareAudioTrack=async(e,t,n,r,i)=>{let a=createInput(t),o=await a.getPrimaryAudioTrack();if(!o)throw Error(`Missing audio track in ${t}`);let s=o.codec;if(!s)throw Error(`Unknown audio codec in ${t}`);if(i!==void 0&&i>=await o.computeDuration())throw Error(`trimBegin excludes the full audio track in ${t}`);let c=new EncodedPacketSink(o),l=i===void 0?await c.getFirstPacket():await c.getPacket(i)??await c.getFirstPacket();if(!l)throw Error(`No audio packets found in ${t}`);let u=new EncodedAudioPacketSource(s);return e.addAudioTrack(u,{disposition:o.disposition,languageCode:normalizeLanguageCode(n)??normalizeLanguageCode(o.languageCode),name:r??o.name??void 0}),{kind:`audio`,input:a,sink:c,source:u,startPacket:l,startTimestamp:l.timestamp,emit:async e=>{let t={decoderConfig:await o.getDecoderConfig()??void 0},n=!0;for await(let r of c.packets(l))await u.add(r.clone({timestamp:r.timestamp-e}),n?t:void 0),n=!1;u.close()}}},rebaseWebVtt=(e,{trimBegin:t,trimEnd:n,commonStart:r})=>{let i=e.replaceAll(`\r
|
|
9
|
+
`,`
|
|
10
|
+
`).replaceAll(`\r`,`
|
|
11
|
+
`).trim();if(!preambleStartRegex.test(i))throw Error(`Only WebVTT subtitles are supported by the MediaBunny muxer.`);let a=t===void 0?void 0:Math.round(t*1e3),o=n===void 0?void 0:Math.round(n*1e3),s=Math.round(r*1e3);cueBlockHeaderRegex.lastIndex=0;let c=cueBlockHeaderRegex.exec(i),l=i.slice(0,c?.index??i.length).trimEnd(),u=[],d=c?i.slice(c.index):``;for(;;){cueBlockHeaderRegex.lastIndex=0;let e=cueBlockHeaderRegex.exec(d);if(!e)break;let t=e.index+e[0].length,n=d.indexOf(`
|
|
12
|
+
`,t)+1,r=d.indexOf(`
|
|
13
|
+
|
|
14
|
+
`,t);r===-1&&(r=d.length);let i=e[1]?.trim(),c=e[4]?.trim(),l=d.slice(n,r).trim(),f=parseSubtitleTimestamp(e[2]),p=parseSubtitleTimestamp(e[3]),m=Math.max(f,a??f)-s,h=Math.min(p,o??p)-s;if(h>m){let e=`${formatWebVttTimestamp(m)} --> ${formatWebVttTimestamp(h)}${c?` ${c}`:``}`;u.push([i,e,l].filter(Boolean).join(`
|
|
15
|
+
`))}d=d.slice(r).trimStart()}return[l,...u].filter(Boolean).join(`
|
|
16
|
+
|
|
17
|
+
`)},addTrackToOutput=async(e,t,n,r,i)=>{if(n.type===`video`)return prepareVideoTrack(e,n.path,n.label,t,r);if(n.type===`audio`)return prepareAudioTrack(e,n.path,n.language,n.label,r);if(isSubtitleInput(n.type)){let t=convertSubtitleTextToWebVtt(await readFile(n.path,`utf8`)),a=new TextSubtitleSource(`webvtt`);return e.addSubtitleTrack(a,{disposition:n.forced?{forced:!0}:void 0,languageCode:normalizeLanguageCode(n.language),name:n.label}),{kind:`subtitle`,source:a,emit:async e=>{let n=rebaseWebVtt(t,{trimBegin:r,trimEnd:i,commonStart:e});await a.add(n),a.close()}}}throw Error(`Unsupported mux input type: ${n.type}`)};var MediaBunnyMuxer=class{async mux(e){let{trimBegin:t,trimEnd:n}=getTrimRange(e),r=createOutputFormat(e.output),i=new Output({format:r,target:createMediabunnyFileTarget(e.output)}),a=[];try{for(let o of e.inputs)a.push(await addTrackToOutput(i,r,o,t,n));let o=a.filter(e=>e.kind!==`subtitle`);if(!a.length)throw Error(`No tracks provided for muxing.`);let s=o.length>0?Math.min(...o.map(e=>e.startTimestamp)):t??0;await i.start();for(let e of a){if(e.kind===`subtitle`){await e.emit(s);continue}await e.emit(s)}return await i.finalize(),e.output}catch(e){throw await i.cancel().catch(()=>void 0),e}finally{for(let e of a)e.kind!==`subtitle`&&e.input.dispose()}}},Muxer=class{strategy;constructor(e){this.strategy=e}async prepare(){await this.strategy.prepare?.()}async process(e){let t=await this.strategy.mux(e);if(e.cleanup)for(let t of new Set(e.inputs.map(e=>e.path)))await rm(t,{force:!0});return t}},ProcessingHandler=class{fn;next=null;constructor(e){this.fn=e,this.next=null}},ProcessingChain=class{first=null;last=null;constructor(){this.first=null,this.last=null}add(e){let t=new ProcessingHandler(e);return this.first?this.last.next=t:this.first=t,this.last=t,this}async process(e){let t=this.first,n=async()=>await t.fn(e,async()=>{if(t=t.next,t)return await n();throw Error(`No handler detected`)});return await n()}};const decryption=async(e,t)=>{if(!e.keys.length)return t();let n=createSpinner$1(`Decrypting`),r=new Decrypter(new ShifroDecrypter);await r.prepare();for(let t of e.inputs){let n=extname(t.path),i=t.path.replace(n,`.dec`+n);if(!(t.type!==`video`&&t.type!==`audio`)){if(await r.process({input:t.path,output:i,keys:e.keys,type:t.type,cleanup:!0}),!existsSync(i))throw Error(`Decryption failed for file ${t.path}. Unable to find ${i}`);t.path=i}}n.success(`Decrypted`),await t()},muxing=async(e,t)=>{if(e.skipMux)return t();let n=createSpinner$1(`Muxing`),r=new Muxer(new MediaBunnyMuxer);await r.prepare(),await r.process({inputs:e.inputs,output:e.output,trimBegin:e.trimBegin,trimEnd:e.trimEnd,cleanup:!0}),existsSync(e.output)?(n.success(`Muxed`),logger.debug(`Muxed: ${e.output}`)):n.error(`Muxing failed. Output file not found: ${e.output}`)},MIN_CONNECTIONS=1,BASIC_MAX_CONNECTIONS=4,PLUS_MAX_CONNECTIONS=8,PRO_MAX_CONNECTIONS=16,normalizeConnections=(e,t)=>Math.max(MIN_CONNECTIONS,Math.trunc(typeof e==`number`&&Number.isFinite(e)?e:t)),resolveMaxConnectionsByBenefits=e=>e.includes(`highConnectionsCount`)?PRO_MAX_CONNECTIONS:e.includes(`mediumConnectionsCount`)?PLUS_MAX_CONNECTIONS:BASIC_MAX_CONNECTIONS,sanitizeConnectionsByBenefits=({requestedConnections:e,fallbackConnections:t=MIN_CONNECTIONS,grantedBenefits:n})=>{let r=normalizeConnections(e,normalizeConnections(t,MIN_CONNECTIONS)),i=resolveMaxConnectionsByBenefits(n),a=Math.min(r,i);return{connections:a,normalizedRequestedConnections:r,maxAllowedConnections:i,wasClamped:a<r}},verifySettings=async e=>{let{grantedBenefits:t}=await getCustomerState(),n=null,r=t.includes(`parallelDownloads`),i=e.maxActiveDownloads&&e.maxActiveDownloads>1;if(!r&&i&&(n=Error(`PARALLEL_DOWNLOADS_NOT_ALLOWED`),e.maxActiveDownloads=1),e.proxy||e.proxyMeta||e.proxyMedia){let r=t.includes(`proxy`),i=e.proxy||e.proxyMeta||e.proxyMedia;!r&&i&&(n=Error(`PROXY_NOT_ALLOWED`),delete e.proxy,delete e.proxyMeta,delete e.proxyMedia)}if(e.videoContainerFormat&&e.videoContainerFormat!==`mp4`&&(t.includes(`customMuxFormat`)||(n=Error(`CUSTOM_MUX_FORMAT_NOT_ALLOWED`),e.videoContainerFormat=`mp4`)),typeof e.connections==`number`){let{connections:n}=sanitizeConnectionsByBenefits({requestedConnections:e.connections,grantedBenefits:t});e.connections=n}return{error:n,data:e}},getBaseDownloadOptions=e=>({retry:e.get(`retry`),connections:e.get(`connections`),proxy:e.get(`proxy`),proxyMeta:e.get(`proxyMeta`),proxyMedia:e.get(`proxyMedia`),movieTemplate:e.get(`movieFilenameTemplate`),episodeTemplate:e.get(`seriesFilenameTemplate`),hardsub:e.get(`preferHardsub`),format:e.get(`videoContainerFormat`)}),applyBenefitLimitedConnections=({options:e,fallbackConnections:t,grantedBenefits:n})=>{let r=sanitizeConnectionsByBenefits({requestedConnections:e.connections,fallbackConnections:t,grantedBenefits:n});return{options:{...e,connections:r.connections},limit:r}},resolveDownloadJobOptions=({settings:e,requestedOptions:t,filePath:n,grantedBenefits:r})=>{let i=getBaseDownloadOptions(e),{options:a,limit:o}=applyBenefitLimitedConnections({options:{...i,...t},fallbackConnections:i.connections,grantedBenefits:r});return n&&(a.outputPath=n),{baseOptions:i,options:a,limit:o}};var DownloadJobRunner=class{settings;extensionManager;downloadsStorage;callbacks;constructor(e,t,n,r){this.settings=e,this.extensionManager=t,this.downloadsStorage=n,this.callbacks=r}async run(e,t,n){let r;try{e.status=`downloading`,await this.callbacks.persistJob(e),this.callbacks.emitStatusChanged(e);let{options:i,limit:a}=resolveDownloadJobOptions({settings:this.settings,requestedOptions:e.options,filePath:e.filePath,grantedBenefits:n});a.wasClamped&&logger.warn(`Connections value ${a.normalizedRequestedConnections} exceeds tier limit (${a.maxAllowedConnections}). Using ${a.connections}.`);let o=new Downloader({settings:this.settings,downloadsStorage:this.downloadsStorage});this.#e(e,t,o);let s=e.resource;if(!s)throw Error(`Download job is missing a media resource`);let c=e.url?await this.extensionManager.getExtensionForUrl(e.url):null,l=e.url?await materializeMediaResource({resource:s,url:e.url,options:i,extension:c}):{source:s.source};r=l.input,s.source=l.source,await this.callbacks.persistJob(e),c&&await runBeforeDownloadHook(c);let{downloaded:u=[],psshList:d,selectedTracks:f}=await o.start(i,l.source,s.metadata,t.signal,l.input);if(t.signal.aborted)return;if(!u.length)throw errors.emit(`error`,{code:`NO_FILES_DOWNLOADED`}),Error(`No files were downloaded`);u.length&&!e.filePath&&(e.filePath=u[0]?.path),this.callbacks.trackArtifact(e.id,e.filePath);for(let t of u)this.callbacks.trackArtifact(e.id,t.path);if(e.status!==`downloading`)return;e.status=`processing`,this.callbacks.emitStatusChanged(e);let p=await this.#r({job:e,options:i,psshList:d??[],selectedTracks:f,extension:c,resolvedEntry:l.entry,resolvedInput:l.input}),m=new ProcessingChain;m.add(decryption).add(muxing),await m.process({inputs:u,output:e.filePath,keys:p,trimBegin:i.trimBegin,trimEnd:i.trimEnd,binariesDir:this.settings.get(`binariesDir`),skipMux:i.skipMux}),c&&await runAfterDownloadHook(c,{skipMux:i.skipMux}),e.status=`completed`,e.progress=100,this.callbacks.emitStatusChanged(e),this.callbacks.emitJobCompleted(e)}catch(t){if(t instanceof Error&&t.name===`AbortError`){logger.debug(`Download was aborted (paused): ${e.id}`);return}let{normalizedError:n,alreadyHandled:r}=this.#t(e,t);if(this.#n(n),r)return;logger.error(`Download job failed: ${n}`),logErrorDetails(`Download job failure`,n),this.callbacks.emitStatusChanged(e),this.callbacks.emitJobError(e,n)}finally{await r?.dispose?.()}}#e(e,t,n){n.on(`output-path`,t=>{e.filePath=t,this.callbacks.trackArtifact(e.id,t),this.callbacks.persistJob(e),logger.debug(`Job output path persisted early: id=${e.id}, path=${t}`)});let r={};n.on(`progress`,n=>{if(t.signal.aborted||e.status!==`downloading`)return;r[n.trackPath]=n,this.callbacks.trackArtifact(e.id,n.trackPath),this.callbacks.trackArtifact(e.id,n.finalPath);let i=0,a=0;for(let e in r)i+=r[e].current.b,a+=r[e].total.b;let o=a>0?i/a*100:0;e.filePath=n.finalPath,e.progress=o,e.downloadedBytes=i,e.totalBytes=a,n.quality&&(e.quality=n.quality),n.codec&&(e.codec=n.codec),this.callbacks.emitProgress(e),this.callbacks.persistJob(e)}),n.on(`error`,n=>{if(e.status===`paused`||t.signal.aborted)return;let{normalizedError:r,alreadyHandled:i}=this.#t(e,n);i||(logger.error(`Downloader process failed: ${r.message}`),r.stack&&logger.debug(r.stack),this.callbacks.emitStatusChanged(e),this.callbacks.emitJobError(e,r))})}#t(e,t){let n=t instanceof Error?t:Error(String(t)),r=e.status===`error`&&e.error===n.message;return r||(e.status=`error`,e.error=n.message),{normalizedError:n,alreadyHandled:r}}#n(e){(e&&typeof e==`object`&&`code`in e?String(e.code):``)===`DOWNLOAD_DIR_NOT_WRITABLE`&&errors.emit(`error`,{code:`DOWNLOAD_DIR_NOT_WRITABLE`})}async#r({job:e,options:t,psshList:n,selectedTracks:r,extension:i,resolvedEntry:a,resolvedInput:o}){let s=e.resource?.source?.drm??e.resource?.drm;e.resource?.drmPayload&&e.url&&(s=await resolveMediaResourceDrm(e.resource,t,i));let c=await this.#i({extension:i,selectedTracks:r,resolvedEntry:a,resolvedInput:o,options:t}),l=await this.#a({extension:i,selectedTracks:r,resolvedEntry:a,resolvedInput:o,options:t}),u=s&&`server`in s?createLegacyDrmLicenseResolver(s):void 0,d=l.resolveLicense??u,f=l.licenseUrl??(s&&`server`in s?s.server:void 0);return extractDecryptionKeys({keys:[...t.keys??[],...c],drm:s,psshList:n,drmDir:this.settings.get(`drmDir`),resolveLicense:d,licenseUrl:f}).catch(r=>{throw logger.error(`Failed to extract decryption keys for job ${e.id}`),logger.debug(`DRM extraction context: title=${e.title||e.resource?.metadata?.title||`(unknown)`}, drmServer=${s&&`server`in s?s.server:`(none)`}, psshCount=${n.length}, providedKeyCount=${t.keys?.length??0}`),r instanceof Error?(logErrorDetails(`DRM extraction failure`,r),r.message===`Unauthorized`&&errors.emit(`error`,{code:`DRM_UNAUTHORIZED`}),r.message===`Forbidden`&&errors.emit(`error`,{code:`DRM_FORBIDDEN`})):logger.debug(String(r)),r})}async#i({extension:e,selectedTracks:t,resolvedEntry:n,resolvedInput:r,options:i}){if(!e||!n||!r)return[];let a=getCompatibleExtensionExports(e);if(typeof a.drm?.getKeys!=`function`)return[];let o=new Map,s={...n,input:r};for(let e of t){if(!e.inputTrack)continue;let t=(await ensurePreparedTrackSegments(e).catch(()=>[]))[0],n=t?.initSegment?.encryption??t?.encryption,r=[n?.drm?.widevine?`widevine`:null,n?.drm?.playready?`playready`:null,n?.drm?.fairplay?`fairplay`:null].filter(Boolean)[0];if(!r)continue;let c=await a.drm.getKeys({system:r,entry:s,track:e.inputTrack,options:i});for(let[e,t]of c??[])o.set(e,t)}return Array.from(o,([e,t])=>({kid:e,key:t}))}async#a({extension:e,selectedTracks:t,resolvedEntry:n,resolvedInput:r,options:i}){if(!e||!n||!r)return{};let a=getCompatibleExtensionExports(e);if(typeof a.drm?.getLicense!=`function`)return{};let o=await this.#o(t);if(!o.size)return{};let s={...n,input:r};return{licenseUrl:`extension://${e.package.name}/license`,resolveLicense:async({pssh:e,data:t})=>{let n=o.get(e);if(!n)throw Error(`No DRM track binding found for PSSH ${e}`);return await a.drm.getLicense({system:n.system,entry:s,track:n.track,options:i,data:t})}}}async#o(e){let t=new Map;for(let n of e){if(!n.inputTrack)continue;let e=(await ensurePreparedTrackSegments(n).catch(()=>[]))[0],r=e?.initSegment?.encryption??e?.encryption;for(let e of[this.#s(n,`widevine`,r?.drm?.widevine?.pssh),this.#s(n,`playready`,r?.drm?.playready?.pssh),this.#s(n,`fairplay`,r?.drm?.fairplay?.pssh)])!e||t.has(e.pssh)||t.set(e.pssh,e)}return t}#s(e,t,n){if(!e.inputTrack||!n)return null;let r=typeof n==`string`?n:n instanceof Uint8Array||n instanceof ArrayBuffer?Buffer.from(n).toString(`base64`):null;return r?{pssh:r,system:t,track:e.inputTrack}:null}},DownloadManager=class extends EventEmitter{settings;extensionManager;downloadsStorage;#e=new DownloadRunState;#t=new Map;#n=null;#r;maxActiveDownloads;constructor(e,t,n){super(),this.settings=e,this.extensionManager=t,this.downloadsStorage=n,this.maxActiveDownloads=e.get(`maxActiveDownloads`),this.#r=new DownloadJobRunner(e,t,n,{persistJob:e=>this.downloadsStorage.update(e),emitStatusChanged:e=>this.emit(`job-status-changed`,e),emitProgress:e=>this.emit(`job-progress`,e),emitJobError:(e,t)=>this.emit(`job-error`,e,t),emitJobCompleted:e=>this.emit(`job-completed`,e),trackArtifact:(e,t)=>this.#m(e,t)}),logger.debug(`Created download manager with max active downloads: ${this.maxActiveDownloads}`)}async initializeFromStorage(){let e=new Set([`downloading`,`queued`,`processing`,`pending`,`analyzing`]);for(let t of this.downloadsStorage.jobs)t.status===`paused`||t.status===`completed`||t.status===`error`||e.has(t.status)&&(t.status!==`queued`&&(t.status=`queued`,t.error=void 0,await this.downloadsStorage.update(t)),this.#d(t));this.#s()}async analyze(e,t={}){if(!e){let e=Error(`Cannot prepare job without a URL.`);throw this.emit(`error`,e),e}let n=await analyzeMediaResource(e,t,await this.extensionManager.getExtensionForUrl(e));if(!n)throw Error(`No media resource found`);return n}async add(e){if(!e.url&&!e.resource)throw Error(`Job must have either a URL or a pre-prepared resource.`);let t={id:crypto.randomUUID(),status:`queued`,progress:0,downloadedBytes:0,createdAt:new Date().toISOString(),...e};logger.debug(`Adding new job: ${t.id}`),logger.debug(`URL: ${t.url}`),await this.downloadsStorage.add(t),this.emit(`job-added`,t),this.#d(t),this.#s()}async pause(e){let t=await this.#i(e,`pause`);t&&logger.debug(`Paused download: ${t.id}`)}async resume(e){let t=this.#e.getActiveRun(e);if(t){t.cancellationReason===`pause`||t.controller.signal.aborted?(this.#e.queueResumeAfterStop(e),logger.debug(`Resume queued until stop completes: ${e}`)):logger.debug(`Resume skipped while job is active: ${e}`);return}let n=this.#y(e);if(!n){logger.warn(`Resume failed: Job ${e} not found`);return}if(n.status===`paused`){await this.#a(n),logger.debug(`Resumed download: ${n.id}`);return}n.status===`error`&&await this.#o(n)&&logger.debug(`Retried download: ${n.id}`)}async remove(e){await this.#i(e,`remove`),await this.downloadsStorage.delete(e),this.#t.delete(e)}async removeWithFile(e){let t=this.#y(e),n=await this.#i(e,`remove-with-file`)||t,r=this.#h(e,n);await this.downloadsStorage.delete(e),await this.#_(r),this.#t.delete(e)}async#i(e,t){let n=this.#f(e),r=this.#e.getActiveRun(e),i=this.#y(e);return r?t===`pause`&&r.job.status!==`downloading`?(logger.debug(`Pause ignored for non-downloading stage: id=${e}, stage=${r.job.status}`),r.job):(r.cancellationReason=t,t===`pause`&&(r.job.status=`paused`,r.job.error=void 0,await this.downloadsStorage.update(r.job),this.emit(`job-status-changed`,r.job)),r.controller.abort(),await r.runPromise,r.job):(t===`pause`&&i&&(n||i.status===`queued`)&&(i.status=`paused`,i.error=void 0,await this.downloadsStorage.update(i),this.emit(`job-status-changed`,i)),i??void 0)}async#a(e){e.status=`queued`,e.error=void 0,await this.downloadsStorage.update(e),this.emit(`job-status-changed`,e),this.#d(e),this.#s()}async#o(e){let t=this.#h(e.id,e);this.#t.delete(e.id),await this.#_(t),e.status=`analyzing`,e.error=void 0,e.progress=0,e.downloadedBytes=0,e.totalBytes=void 0,e.quality=void 0,e.codec=void 0,await this.downloadsStorage.update(e),this.emit(`job-status-changed`,e);try{if(e.url){let t=await this.analyze(e.url,e.options??{}),n=this.#g(e,t);if(!n)throw Error(`No media resource found`);e.resource=n}return await this.#a(e),!0}catch(t){return e.status=`error`,e.error=t instanceof Error?t.message:String(t),await this.downloadsStorage.update(e),this.emit(`job-status-changed`,e),this.emit(`job-error`,e,t),!1}}#s(){for(this.maxActiveDownloads=this.settings.get(`maxActiveDownloads`);this.#e.activeRunCount<this.maxActiveDownloads;){let e=this.#p();if(!e)break;this.#c(e)}this.#e.queuedCount===0&&this.#e.activeRunCount===0&&this.emit(`idle`)}#c(e){if(e.status!==`queued`){logger.warn(`Skipping non-queued job start: ${e.id} (${e.status})`);return}let t=new AbortController,n={controller:t,job:e,runPromise:Promise.resolve()};this.#e.setActiveRun(e.id,n),n.runPromise=this.#u(e,t).catch(e=>{let t=e instanceof Error?e:Error(`Download run failed: ${String(e)}`);logger.error(t.message),this.emit(`error`,t)})}async#l(){if(this.#n)return this.#n;try{let{grantedBenefits:e}=await getCustomerState();this.#n=e}catch(e){let t=e instanceof Error?e.message:String(e);logger.warn(`Failed to resolve customer plan for connection limits. Falling back to Free limits: ${t}`),this.#n=[]}return this.#n}async#u(e,t){this.#e.setActiveJob(e);try{let n=await this.#l();await this.#r.run(e,t,n)}finally{let t=this.#e.getActiveRun(e.id);if(t){let n=t?.cancellationReason,r=n===`pause`&&this.#e.consumeResumeAfterStop(e.id);n===`pause`?(e.status=`paused`,e.error=void 0,await this.downloadsStorage.update(e),this.emit(`job-status-changed`,e)):n!==`remove`&&n!==`remove-with-file`&&await this.downloadsStorage.update(e),this.#e.deleteActiveJob(e.id),this.#e.deleteActiveRun(e.id),r&&e.status===`paused`&&(e.status=`queued`,e.error=void 0,await this.downloadsStorage.update(e),this.emit(`job-status-changed`,e),this.#d(e)),this.#s()}}}#d(e){this.#e.enqueue(e)}#f(e){return this.#e.dequeue(e)}#p(){return this.#e.dequeueNext(e=>this.#y(e))}#m(e,t){if(!t)return;let n=this.#t.get(e);n||(n=new Set,this.#t.set(e,n)),n.add(t)}#h(e,t){let n=new Set;for(let t of this.#t.get(e)??[])n.add(t);t?.filePath&&n.add(t.filePath);let r=new Set;for(let e of n)r.add(e),r.add(`${e}.part.json`),r.add(this.#v(e));return r}#g(e,t){let n=Array.isArray(t)?t:[t];if(n.length<=1)return n[0];let r=e.resource?.metadata,i=e.resource?.source.url,a=r&&`seasonNumber`in r?r.seasonNumber:null,o=r&&`episodeNumber`in r?r.episodeNumber:null,s=r&&`episodeTitle`in r?r.episodeTitle:null;return n.find(e=>{let t=e.metadata;if(r?.id&&t?.id)return r.id===t.id;let n=t&&`seasonNumber`in t?t.seasonNumber:null,c=t&&`episodeNumber`in t?t.episodeNumber:null,l=t&&`episodeTitle`in t?t.episodeTitle:null;return r?.title&&t?.title&&r.title===t.title&&a===n&&o===c&&s===l?!0:!!i&&i===e.source.url})??n[0]}async#_(e){e.size!==0&&await Promise.all([...e].map(e=>rm(e,{recursive:!0,force:!0}).catch(()=>void 0)))}#v(e){let t=resolve(e),n=parse(e).name;return join(APP_TEMP_DIR,`${n}-${createHash(`sha1`).update(t).digest(`hex`).slice(0,10)}`)}#y(e){return this.#e.getActiveJob(e)||this.downloadsStorage.get(e)}onJobAdded(e){return this.on(`job-added`,e),()=>this.removeListener(`job-added`,e)}onJobStatusChanged(e){return this.on(`job-status-changed`,e),()=>this.removeListener(`job-status-changed`,e)}onJobProgress(e){return this.on(`job-progress`,e),()=>this.removeListener(`job-progress`,e)}onJobCompleted(e){return this.on(`job-completed`,e),()=>this.removeListener(`job-completed`,e)}onJobError(e){return this.on(`job-error`,e),()=>this.removeListener(`job-error`,e)}onIdle(e){return this.on(`idle`,e),()=>this.removeListener(`idle`,e)}onError(e){return this.on(`error`,e),()=>this.removeListener(`error`,e)}waitForIdle(){return new Promise(e=>this.onIdle(e))}};const parseSingleEpisode=e=>{if(!e)return null;let[t,n]=e.toLowerCase().split(`e`);return[parseInt(t.trim().toLowerCase().replace(`s`,``)),parseFloat(n?.trim())]},parseEpisodesBySeasons=e=>{let t=0,n=9999,r=[],i=e.split(`,`);for(let e of i){let[t,i]=e.split(`-`),a=parseSingleEpisode(t),o=parseSingleEpisode(i);if(a&&!i){let[e,t]=a;if(isNaN(t))for(let t=0;t<=n;t++)r.push([e,t]);else r.push([e,t])}else if(a&&o){let[e,t]=a,[i,s]=o;for(let a=e;a<=i;a++){let e=t||0,o=a===i?s:n;for(let t=e;t<=o;t++)r.push([a,t])}}}let a=new Map;for(let[e,t]of r)a.has(e)||a.set(e,new Set),a.get(e)?.add(t);return a},parseHeaders=e=>{if(!e)return{};let t={},n=typeof e==`string`?e.split(`|`):e;for(let e of n){let[n,...r]=e.split(`:`),i=r.join(`:`);if(!i)throw Error(`Can't parse header: ${e}`);t[n.trim()]=i.trim()}return t},validateUrl=async e=>{let t=!1,n=e;do try{n?t=!!new URL(n):n=(await prompt.ask({fields:{url:{label:`URL`}}})).url}catch{n=(await prompt.ask({fields:{url:{label:`URL`}}})).url}while(!t);return n!==e&&logger.debug(`URL: ${n}`),n},compareJobsByCreatedAtDesc=(e,t)=>new Date(t.createdAt??0).getTime()-new Date(e.createdAt??0).getTime();var DownloadsStorage=class{filePath;jobs=[];#e=Promise.resolve();constructor(e){this.filePath=e}parse(e){let t=JSON.parse(e),n=Object.entries(t);return new Map(n)}async load(){await this.#e;try{let e=await readFile(this.filePath,{encoding:`utf8`});this.jobs=JSON.parse(e).toSorted(compareJobsByCreatedAtDesc)}catch{this.jobs=[]}return this}get size(){return this.jobs.length}async add(e){await this.#t(async()=>{this.jobs.unshift(e),await this.save()})}async update(e){await this.#t(async()=>{let t=this.jobs.findIndex(t=>t.id===e.id);t!==-1&&(this.jobs[t]=e,await this.save())})}getByFilePath(e){return this.jobs.find(t=>t.filePath===e)}get(e){return this.jobs.find(t=>t.id===e)}has(e){return this.jobs.some(t=>t.id===e)}async delete(e){await this.#t(async()=>{let t=this.jobs.findIndex(t=>t.id===e);t!==-1&&(this.jobs.splice(t,1),await this.save())})}async deleteWithFile(e){let t=await this.#t(async()=>{let t=this.jobs.findIndex(t=>t.id===e);if(t===-1)return null;let[n]=this.jobs.splice(t,1);return await this.save(),n??null});t?.filePath&&await rm(t.filePath,{recursive:!0,force:!0})}async clear(){await this.#t(async()=>{this.jobs=[],await this.save()})}async save(){return writeFile(this.filePath,JSON.stringify(this.jobs,null,2))}#t(e){let t=this.#e.then(e,e);return this.#e=t.then(()=>void 0,()=>void 0),t}};const downloadCommand={command:[`download [urls..]`,`$0 [urls..]`],aliases:[`dl`],describe:`Download media content by URL`,builder:e=>e.option(`quality`,{alias:`q`,describe:`Video resolution quality - 2160p/1080p/720p/..., defaults to highest available`,type:`string`}).option(`video-codec`,{alias:`v`,describe:`Video codec - avc | hevc | vp8 | vp9 | av1 | vc1, defaults to any`,type:`string`}).option(`video-range`,{alias:`r`,describe:`Video color range - sdr | hlg | hdr10 | hdr10+ | dv, defaults to sdr`,type:`string`}).option(`video-bitrate`,{describe:`Video bitrate (in kbps), defaults to highest available`,type:`number`}).option(`video-dimension`,{describe:`Video dimension - 2D/3D (HSBS/HOU/FSBS/OU), defaults to 2D`,default:`2D`,type:`string`}).option(`audio-codec`,{alias:`a`,describe:`Audio codec - aac | opus | mp3 | vorbis | flac | alac | ac3 | eac3 | dts, defaults to any`,type:`string`}).option(`audio-channels`,{alias:`c`,describe:`Audio channels, matches sub-channel layouts like 5.1 with 6.0`,type:`number`}).option(`audio-bitrate`,{describe:`Audio bitrate (in kbps), defaults to highest available`,type:`number`}).option(`subs-format`,{alias:`s`,describe:`Subtitle format - SRT/SSA/ASS/TTML/VTT/STPP/WVTT`,type:`string`}).option(`subs-lang`,{alias:`S`,describe:`Subtitles language(s)`,type:`string`}).option(`lang`,{alias:`l`,describe:`Video/audio language(s)`,type:`string`}).option(`skip-video`,{describe:`do not download video`,type:`boolean`}).option(`skip-audio`,{describe:`do not download audio`,type:`boolean`}).option(`skip-subtitles`,{describe:`do not download subtitles`,type:`boolean`}).option(`skip-mux`,{describe:`Disable merge audio/video/subs into single file`,type:`boolean`}).option(`select`,{describe:`Select audio/video/subtitle streams from manifest manually`,type:`boolean`}).option(`episodes`,{alias:`e`,describe:"Seasons/episodes to download, e.g. `S01E01`, `S01-S05,S07`, `S01E01-S02E03`, `S02-S02E03`, etc.",type:`string`,coerce:e=>parseEpisodesBySeasons(e)}).option(`retry`,{alias:`R`,describe:`Number of retries in case of unsuccessful request`,type:`number`,default:defaultSettings.retry}).option(`connections`,{alias:`C`,describe:`Number of parallel http connections per download`,type:`number`,default:defaultSettings.connections}).option(`proxy`,{describe:`Use specified HTTP/HTTPS proxy for all requests`,type:`string`}).option(`proxy-meta`,{describe:`Use specified HTTP/HTTPS proxy for metadata fetching`,type:`string`}).option(`proxy-media`,{describe:`Use specified HTTP/HTTPS proxy for media downloading`,type:`string`}).option(`movie-template`,{describe:`Movie filename template`,type:`string`,default:defaultSettings.movieFilenameTemplate}).option(`episode-template`,{describe:`Episode filename template`,type:`string`,default:defaultSettings.seriesFilenameTemplate}).option(`hardsub`,{describe:`Download hardsubbed video if available`,type:`boolean`}).option(`trim-begin`,{describe:`Trim video at the beginning; example: 00:00:06`,type:`string`}).option(`trim-end`,{describe:`Trim video at the end; example: 00:01:30`,type:`string`}).option(`key`,{describe:`Set content decryption key (if manifest URL as main URL passed), format: KID:KEY`,type:`array`,string:!0,coerce:e=>e.map(e=>{let[t,n]=e.split(`:`);return{kid:t,key:n}})}).option(`header`,{alias:`H`,describe:`Pass custom header(s) for manifest request`,type:`array`,string:!0,coerce:e=>parseHeaders(e)}).option(`format`,{alias:`f`,describe:`Video container format - mp4 | mkv (Pro only)`,type:`string`,choices:[`mp4`,`mkv`]}),handler:async e=>{let t=e;t.videoQuality=e.quality;let n=new SettingsStore(SETTINGS_PATH);if(t.format){let{error:e}=await verifySettings({videoContainerFormat:t.format});e&&(logger.error(`Invalid format: ${e.message}`),logger.info(`Learn more: https://azot.mov/pricing`),process.exit(1))}let r=[];try{({grantedBenefits:r}=await getCustomerState())}catch(e){let t=e instanceof Error?e.message:String(e);logger.warn(`Failed to resolve customer plan for connection limits. Falling back to Free limits: ${t}`)}let{options:i,limit:{normalizedRequestedConnections:a,maxAllowedConnections:o,wasClamped:s,connections:c}}=applyBenefitLimitedConnections({options:t,fallbackConnections:n.get(`connections`),grantedBenefits:r});Object.assign(t,i),s&&logger.warn(`Connections value ${a} exceeds tier limit (${o}). Using ${c}.`);let l=new ExtensionManager({dirs:[EXTENSIONS_SOURCES_DIR],indexPath:EXTENSIONS_INDEX_PATH});await l.init(),await l.loadCoreExtensions(),await l.discover();let u=new DownloadsStorage(join(APP_CONFIG_DIR,`downloads.json`));await u.load();let d=new DownloadManager(n,l,u);loadAuth().then(e=>Object.assign(authState,e)),d.onJobCompleted(e=>{logger.debug(`Job completed: ${e.id}`)}),d.onJobError(e=>{logger.debug(`Job failed: ${e.error}`)}),d.onError(e=>{logger.error(`Download manager error: ${e.message}`)});let f=(Array.isArray(e.urls)?e.urls:[]).filter(e=>e!==process.argv[1]),p=f.length>0?f:[``];for(let e of p){let n=await validateUrl(e),r=await d.analyze(n,t),i=Array.isArray(r)?r:[r];for(let e of i)d.add({url:n,options:t,resource:e})}await d.waitForIdle()}},CLIENT_ID=`azot-desktop`,login=async()=>{if(await loadAuth()&&!await confirm({message:`You're already logged in. Do you want to log in again?`,default:!1})){logger.debug(`Login cancelled`);return}let e=createSpinner(`Requesting device authorization...`);e.start();try{let t=getAuthClient(),{data:n,error:r}=await t.device.code({client_id:CLIENT_ID,scope:`openid profile email`});if(e.stop(),r||!n)logger.error(`Failed to request device authorization: ${r?.error_description||r?.statusText||`Unknown error`}`),logger.debug(r);else{let{device_code:e,user_code:r,verification_uri:i,verification_uri_complete:a,interval:o=5,expires_in:s}=n;console.log(``),console.log(colors.cyan(`📱 Device Authorization Required`)),console.log(``),console.log(`Please visit: ${colors.underline(colors.blue(i))}`),console.log(`Enter code: ${colors.bold(colors.green(r))}`),console.log(``),await confirm({message:`Open browser automatically?`,default:!0})&&await open$1(a||i),console.log(colors.gray(`Waiting for authorization (expires in ${Math.floor(s/60)} minutes)...`));let c=await pollForToken(t,e,CLIENT_ID,o);if(c){await saveAuth(c);let{data:e}=await t.getSession({fetchOptions:{headers:{Authorization:`Bearer ${c.access_token}`}}});console.log(colors.green(`✅ Login successful! Logged in as ${e?.user?.name||e?.user?.email||`User`}`))}}}catch(t){e.stop(),logger.error(`Login failed: ${t instanceof Error?t.message:`Unknown error`}`)}};async function pollForToken(e,t,n,r){let i=r,a=createSpinner(``,{color:`cyan`}),o=0;return new Promise(r=>{let s=async()=>{o=(o+1)%4,a.update(colors.gray(`Polling for authorization${`.`.repeat(o)}${` `.repeat(3-o)}`)),a.isSpinning()||a.start();try{let{data:o,error:s}=await e.device.token({grant_type:`urn:ietf:params:oauth:grant-type:device_code`,device_code:t,client_id:n,fetchOptions:{headers:{"user-agent":`Azot Desktop`}}});if(o?.access_token){a.stop(),r(o);return}else if(s)switch(s.error){case`authorization_pending`:break;case`slow_down`:i+=5,a.update(colors.yellow(`Slowing down polling to ${i}s`));break;case`access_denied`:a.stop(),logger.error(`Access was denied by the user`);break;case`expired_token`:a.stop(),logger.error(`The device code has expired. Please try again.`);break;default:a.stop(),logger.error(`Error: ${s.error_description}`)}}catch(e){a.stop(),logger.error(`Network error: ${e instanceof Error?e.message:`Unknown error`}`);return}setTimeout(s,i*1e3)};setTimeout(s,i*1e3)})}const logout=async()=>{logger.info(`Logging out...`);let e=await getAuthClient().signOut();e.error?logger.error(`Logout failed: ${e.error.message}`):(logger.info(`Logout successful`),await saveAuth({}))},loginCommand={command:`login [extension]`,describe:`Login to extension (or if no extension is specified, login to Azot account)`,builder:e=>e.option(`username`,{alias:`u`,describe:`Username`,type:`string`}).option(`password`,{alias:`p`,describe:`Password`,type:`string`}).option(`otp`,{alias:`o`,describe:`One-time password`,type:`string`}),handler:async e=>{let t=e.extension,n={username:e.username,password:e.password,otp:e.otp};if(t){let e=new ExtensionManager({dirs:[EXTENSIONS_SOURCES_DIR],indexPath:EXTENSIONS_INDEX_PATH});await e.init(),await e.discover(),await e.login(t,n)}else login()}},listCommand={command:`list`,aliases:[`ls`],describe:`Lists information about installed/active extensions`,handler:async()=>{let e=await new ExtensionManager({indexPath:EXTENSIONS_INDEX_PATH}).init();if(!e.infoList.length)return console.log(`No added extensions found`);for(let t of e.infoList){let e=`${colors.bold(colors.blue(t.name.padEnd(15)))}`,n=colors.green(t.package?.version);console.log(e+n)}console.log(`
|
|
18
|
+
`+colors.dim(`Location: ${EXTENSIONS_DIR}`))}},rtf=new Intl.RelativeTimeFormat(`en`,{style:`long`}),getTimeAgo=e=>{let t=Math.floor(e/24),n=Math.abs(t);return n>365?rtf.format(Math.floor(t/365),`year`):n>30?rtf.format(Math.floor(t/30),`month`):n>7?rtf.format(Math.floor(t/7),`week`):n>1?rtf.format(Math.floor(t),`day`):rtf.format(Math.floor(e),`hour`)},row=(e,t,n)=>{let r=`${colors.bold(colors.blue(e.padEnd(15)))}`,i=colors.green(t.padEnd(10)),a=colors.dim(n);console.log(r+i+a)},listRemoteCommand={command:`list-remote`,aliases:[`ls-remote`],describe:`List all available extensions`,handler:async()=>{loadAuth().then(e=>Object.assign(authState,e));let e=await ExtensionManager.getAvailableExtensions(),t=Date.now();for(let n of e){let e=n.releases.toSorted((e,t)=>new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()).at(0);if(!e)continue;let r=e.createdAt,i=new Date(r).getTime()-t,a=getTimeAgo(Math.floor(i/36e5));row(n.name,e.version,a)}}},logoutCommand={command:`logout [extensions..]`,describe:`Logout from extension (or if no extension is specified, logout from Azot account)`,handler:async e=>{let t=e.extensions;if(t?.length){let e=new ExtensionManager({dirs:[EXTENSIONS_SOURCES_DIR],indexPath:EXTENSIONS_INDEX_PATH});await e.init(),await e.discover(),await e.logout(t)}else logout()}},settingsCommand={command:`settings [key] [value]`,describe:`CLI access to get/set configuration settings`,handler:async e=>{let t=new SettingsStore(SETTINGS_PATH),n=e.key,r=e.value;if(n&&r){t.set({[n]:r}),console.log(`Setting ${colors.bold(colors.blue(n))} set to ${colors.green(r)}`);return}else if(n){let e=t.get(n);console.log(e?`Setting ${colors.bold(colors.blue(n))} is ${colors.green(e)}`:`Setting ${colors.bold(colors.blue(n))} is not found`);return}let i=t.getAll();for(let[e,t]of Object.entries(i)){let n=`${e}`.padEnd(25),r=String(t).replaceAll(`{`,`{{`).replaceAll(`}`,`}}`);console.log(`${colors.bold(colors.blue(n))} ${r}`)}console.log(`
|
|
19
|
+
`+colors.dim(`Location: ${SETTINGS_PATH}`))}},uninstallCommand={command:`uninstall <extensions..>`,aliases:[`rm`],describe:`Uninstall an extension`,handler:async e=>{let t=e.extensions,n=new ExtensionManager({dirs:[EXTENSIONS_SOURCES_DIR],indexPath:EXTENSIONS_INDEX_PATH});await n.init(),await n.uninstall(t)}},installCommand={command:`install <extensions..>`,aliases:[`i`],describe:`Install extension`,handler:async e=>{let t=e.extensions,n=new ExtensionManager({dirs:[EXTENSIONS_SOURCES_DIR],indexPath:EXTENSIONS_INDEX_PATH});await n.init(),await n.install(t)}},logsCommand={command:`logs`,describe:`Show logs list`,handler:async()=>{let e=APP_LOG_DIR,t=await readdir(e).then(e=>e.filter(e=>e.endsWith(`.log`))),n=t=>join(e,t);t.length||logger.info(`No logs found`);for(let e of t)logger.info(n(e))}};logger.debug(fullVersion);const cliArgs=getCliArgs(process.argv);logger.debug(`${APP_NAME} ${cliArgs.join(` `)}`),errors.on(`error`,e=>{let t=normalizeError(e);logger.error(t.message)});const description=`${colors.magenta(colors.bold(APP_TITLE))} is ${package_default.description.toLocaleLowerCase()}`,usage=colors.bold(`Usage: $0 <command> ${colors.cyan(`[...options]`)}`);yargs(cliArgs).scriptName(APP_NAME).usage(`${description}\n\n${usage}`).command(downloadCommand).command(listCommand).command(listRemoteCommand).command(installCommand).command(uninstallCommand).command(loginCommand).command(logoutCommand).command(settingsCommand).command(logsCommand).option(`debug`,{describe:`Debug mode`,type:`boolean`}).wrap(yargs().terminalWidth()).help().alias(`h`,`help`).showHelpOnFail(!1).version(shortVersion).updateStrings({"Commands:":colors.bold(`Commands:`),"Options:":colors.bold(`Options:`),default:colors.dim(`default`),aliases:colors.dim(`aliases`),boolean:colors.dim(`boolean`),string:colors.dim(`string`),number:colors.dim(`number`)}).epilogue(`Learn more about Azot: ${colors.magenta(`https://azot.mov`)}.`).parse(),clearOutdatedLogs(APP_LOG_DIR),process.on(`uncaughtException`,e=>{logger.fatal(`Unexpected error: ${e.message}`),e.stack&&logger.debug(e.stack),rmSync(APP_TEMP_DIR,{recursive:!0,force:!0}),process.exit(1)});export{};
|
package/dist/azt.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{n as e}from"./chunk-
|
|
2
|
+
import{n as e}from"./chunk-cpUYaJdV.mjs";import{readFileSync as t,readdirSync as n,rmSync as r,writeFileSync as i}from"node:fs";import a from"node:path";import{createCipheriv as o,createDecipheriv as s,privateDecrypt as c,publicEncrypt as l,randomBytes as u}from"node:crypto";import{parseArgs as d}from"node:util";import{build as f}from"tsdown";import p from"javascript-obfuscator";const m=Buffer.from(`STX`,`utf8`),h=(e,n,r)=>{let a=u(32),s=u(16),c=t(n),d=o(`aes-256-cbc`,a,s),f=Buffer.concat([d.update(c),d.final()]),p=l(e,a),h=Buffer.concat([m,s,p,f]);return r&&i(r,h),{aesIv:s,encryptedAesKey:p,encryptedCode:f}},g=(e,n,r)=>{let a=t(n),o=m.byteLength;if(!a.subarray(0,o).equals(m))throw Error(`Incorrect file format`);let l=o,u=l+16,d=u+512,f=a.subarray(l,u),p=a.subarray(u,d),h=a.subarray(d),g=s(`aes-256-cbc`,c(e,p),f),_=Buffer.concat([g.update(h),g.final()]).toString(`utf8`);return r&&i(r,_),_},_=(e,n)=>{let r=t(e,`utf8`);console.log(`Obfuscating ${e}...`),console.time(`Obfuscation complete in`);let a=p.obfuscate(r,{target:`node`,compact:!0,controlFlowFlattening:!0,controlFlowFlatteningThreshold:1,deadCodeInjection:!0,debugProtection:!0,identifierNamesGenerator:`hexadecimal`,numbersToExpressions:!0,selfDefending:!0,simplify:!0,splitStrings:!0,splitStringsChunkLength:5,stringArray:!0,stringArrayCallsTransform:!0,stringArrayCallsTransformThreshold:1,stringArrayEncoding:[`base64`],stringArrayIndexShift:!0,stringArrayRotate:!0,stringArrayShuffle:!0,stringArrayWrappersCount:2,stringArrayWrappersChainedCalls:!0,stringArrayWrappersType:`function`,stringArrayThreshold:1,transformObjectKeys:!0,unicodeEscapeSequence:!1});console.timeEnd(`Obfuscation complete in`);let o=a.getObfuscatedCode();return i(n||e,o),o},v=d({allowPositionals:!0,allowNegative:!0,options:{input:{type:`string`,short:`i`,description:`Path to the input file`},key:{type:`string`,short:`k`,description:`Path to the key file (public for encrypt, private for decrypt)`},output:{type:`string`,short:`o`,description:`Path to the output file`},format:{type:`string`,short:`f`,description:`Output format`},watch:{type:`boolean`,description:`Watch file changes`},minify:{type:`boolean`,description:`Minify output`},obfuscate:{type:`boolean`,description:`Obfuscate output`},encrypt:{type:`boolean`,description:`Encrypt extension source code (.js will be packed inside .stx)`},decrypt:{type:`boolean`,description:`Decrypt encrypted extension`}}}),y=()=>{let e=[process.cwd(),a.join(process.cwd(),`src`),a.join(process.cwd(),`lib`)];for(let t of e){let e=n(t).filter(e=>!e.endsWith(`.d.ts`)).filter(e=>new Set([`.ts`,`.js`,`.cjs`,`.mjs`]).has(a.extname(e))),r=e=>a.basename(e,a.extname(e)),i=e.find(e=>r(e)===`index`)||e.find(e=>r(e)===`main`)||e[0];if(i)return a.join(t,i)}},b=e=>e===`esm`?`mjs`:`cjs`,x=(e,t)=>a.join(process.cwd(),`dist`,`${a.parse(e).name}.${b(t)}`),S=(e,t)=>{let{dir:n,name:r}=a.parse(e);return a.join(n,`${r}-${t}.azt`)};(async()=>{let[n,...i]=v.positionals,o=v.values.input||i[0]||y();if(!o)throw Error(`No entry file found`);if(n===`build`||n===`pack`){let i=typeof v.values.minify==`boolean`?v.values.minify:!0,s=v.values.format??`cjs`;await f({entry:o.replace(process.cwd(),`.`).replace(a.sep,`/`),format:s,platform:`node`,target:`node24`,watch:v.values.watch,minify:i,inlineOnly:!1}),v.values.input=x(o,s);let c=e(a.join(process.cwd(),`package.json`));if((typeof v.values.obfuscate==`boolean`?v.values.obfuscate:c.private)&&_(v.values.input,v.values.input),v.values.encrypt||n===`pack`){let e=t(v.values.key||a.join(__dirname,`../public.pem`),`utf8`),n=v.values.output||S(v.values.input,c.version);h(e,v.values.input,n),r(v.values.input)}}else if(n===`decrypt`)g(t(v.values.key||a.join(__dirname,`../private.pem`),`utf8`),o,v.values.output||o.replace(/\.stx$/,`.js`)),v.values.input&&r(v.values.input);else if(n===`dev`||n===`develop`||!n){let e=typeof v.values.minify==`boolean`?v.values.minify:!1;await f({entry:o,format:v.values.format??`cjs`,platform:`node`,target:`node22`,watch:!0,minify:e})}})();export{};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createRequire as e}from"node:module";var t=Object.create,n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.getPrototypeOf,o=Object.prototype.hasOwnProperty,s=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),c=(e,t,a,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var c=i(t),l=0,u=c.length,d;l<u;l++)d=c[l],!o.call(e,d)&&d!==a&&n(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(s=r(t,d))||s.enumerable});return e},l=(e,r,i)=>(i=e==null?{}:t(a(e)),c(r||!e||!e.__esModule?n(i,`default`,{value:e,enumerable:!0}):i,e)),u=e(import.meta.url);export{u as n,l as r,s as t};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{closeSync as e,existsSync as t,mkdirSync as n,openSync as r,readSync as i,writeSync as a}from"node:fs";import o,{basename as s,dirname as c,join as l}from"node:path";import"urlpattern-polyfill";import u from"picocolors";import d,{readFile as f,readdir as p,rm as m,stat as h,unlink as g,writeFile as _}from"node:fs/promises";import{configureSync as ee,getConsoleSink as v,getLogger as te,withFilter as ne}from"@logtape/logtape";import{getFileSink as re}from"@logtape/file";import{getPrettyFormatter as ie}from"@logtape/pretty";import y,{EOL as ae,homedir as oe,tmpdir as se}from"node:os";import{arch as ce,platform as le,stdin as b,stdout as ue,version as de}from"node:process";import fe,{EventEmitter as x}from"node:events";import S from"conf";import{setTimeout as C}from"node:timers/promises";import{ALL_FORMATS as pe,DASH as me,DASH_FORMATS as he,HLS as ge,HLS_FORMATS as _e,Input as ve,MP3 as ye,MP4 as be,UrlSource as xe}from"dasha";import{createInterface as Se}from"node:readline/promises";import{Impit as Ce}from"impit";import we from"ky";import{Agent as Te,ProxyAgent as Ee}from"undici";import{parseSetCookie as De}from"cookie";import w from"metavm";import{confirm as Oe,input as ke,number as Ae,password as je,select as Me}from"@inquirer/prompts";var Ne=`azot`,T=`5.0.0-alpha.19`,Pe=`Azot`,E={name:Ne,version:T,description:`A powerful, extensible app for downloading videos`,homepage:`https://azot.mov`,author:`Vitaly Gashkov <vitalygashkov@vk.com>`,bin:{azot:`./dist/azot.mjs`,azt:`./dist/azt.mjs`},files:[`dist`,`types`],type:`module`,main:`./dist/api.mjs`,types:`./types/api.d.ts`,exports:{".":{types:`./types/api.d.ts`,import:`./dist/api.mjs`,"module-sync":`./dist/api.mjs`},"./context":{types:`./types/context.d.ts`,import:`./dist/context.mjs`,"module-sync":`./dist/context.mjs`},"./types/extension":`./types/extension.d.ts`,"./vitest":{import:`./dist/vitest.mjs`,"module-sync":`./dist/vitest.mjs`}},scripts:{start:`tsx --env-file-if-exists .env.local ./src/cli.ts`,dev:`tsx watch --env-file-if-exists .env.local ./src/cli.ts`,"bundle:extensions":`node ./scripts/bundle-extensions.mjs`,build:`pnpm run bundle:extensions && tsdown`,typecheck:`tsc --noEmit -p tsconfig.json --composite false`,test:`vitest`},dependencies:{"@azot/shared":`workspace:*`,"@gitbeaker/rest":`^43.8.0`,"@inquirer/prompts":`^8.3.2`,"@logtape/file":`^2.0.4`,"@logtape/logtape":`^2.0.4`,"@logtape/pretty":`^2.0.4`,"@tanstack/query-core":`^5.90.20`,"@transcrobes/subs-convert":`^5.2.0`,"@tribute-tg/better-auth":`^2.1.10`,"better-auth":`^1.5.5`,conf:`^15.1.0`,cookie:`^1.1.1`,"cross-spawn":`^7.0.6`,dasha:`^4.2.0`,impit:`^0.13.0`,ky:`^1.14.3`,mediabunny:`^1.44.2`,metavm:`^1.4.5`,molnia:`workspace:*`,nanospinner:`^1.2.2`,okova:`^0.11.0`,open:`^11.0.0`,"p-queue":`^9.1.0`,picocolors:`^1.1.1`,"posthog-js":`^1.360.2`,semver:`^7.7.4`,shifro:`^1.1.4`,"telegram-better-auth":`^0.0.8`,undici:`^7.24.4`,"urlpattern-polyfill":`^10.1.0`,yargs:`^18.0.0`,yauzl:`^3.2.1`,zod:`^4.3.6`},devDependencies:{"@types/node":`^25.5.0`,"@types/semver":`^7.7.1`,"@types/yargs":`^17.0.35`,execa:`^9.6.1`,"javascript-obfuscator":`^4.1.1`,tsdown:`^0.22.0`,tsx:`^4.21.0`,typescript:`^6.0.3`},peerDependencies:{vitest:`^4.1.0`},engines:{node:`>=24.10`,pnpm:`>=10`},packageManager:`pnpm@11.0.0`,productName:Pe};`pkg`in process&&process.pkg,process.versions.electron,process.env.AZOT_E2E;const Fe=`v${T} ${le}-${ce} node-${de}`,Ie=`v${T}`,Le=Ne?.split(`/`)[0]?.split(`-`)[0]?.replace(`@`,``),D=Pe,Re={darwin:`macOS`,win32:`Windows`,linux:`Linux`}[process.platform],ze=`https://azot.mov/api`,Be=`LS0tLS1CRUdJTiBQVUJMSUMgS0VZLS0tLS0KTUZrd0V3WUhLb1pJemowQ0FRWUlLb1pJemowREFRY0RRZ0FFY243SFdZaXVyMWR3UU5pSmhFSGZHczZFM25rOAo4TXhOZVo5Ly85UWpaUStVNm5Ud0twMGJNTXJydGxHVVZ5ZWFGQS9lREtkL29QZHg0NXpmU0Rkc1lRPT0KLS0tLS1FTkQgUFVCTElDIEtFWS0tLS0tCg`,O=e=>{let r=typeof e==`string`?e:e[Re];return t(r)||n(r,{recursive:!0}),r},k=oe(),Ve=se(),A=O({Windows:process.env.APPDATA||l(k,`AppData`,`Roaming`),macOS:l(k,`Library`,`Application Support`),Linux:process.env.XDG_DATA_HOME||l(k,`.local`,`share`)}),j=O({Windows:process.env.APPDATA||l(k,`AppData`,`Roaming`),macOS:l(k,`Library`,`Application Support`),Linux:process.env.XDG_CONFIG_HOME||l(k,`.config`)});O({Windows:process.env.LOCALAPPDATA||l(k,`AppData`,`Local`),macOS:l(k,`Library`,`Caches`),Linux:process.env.XDG_CACHE_HOME||l(k,`.cache`)});const He=O({Windows:l(k,`Downloads`),macOS:l(k,`Downloads`),Linux:process.env.XDG_DOWNLOAD_DIR||l(k,`Downloads`)}),Ue=O({Windows:l(A,D),macOS:l(A,D),Linux:l(A,D.toLowerCase())}),We=O({Windows:l(j,D),macOS:l(j,D),Linux:l(j,D.toLowerCase())}),Ge=O({Windows:l(j,D,`logs`),macOS:l(k,`Library`,`Logs`,D),Linux:l(j,D.toLowerCase(),`logs`)}),Ke=l(Ve,D.toLowerCase()),M=O(l(Ue,`extensions`)),qe=O(l(M,`installed`)),Je=O(l(M,`work`)),Ye=l(M,`index.json`),Xe=l(We,`settings.json`),Ze=process.argv.includes(`-d`)||process.argv.includes(`--debug`)||process.env.NODE_ENV_ELECTRON_VITE===`development`||!!process.env.ELECTRON_CLI_ARGS;ee({sinks:{console:ne(v({formatter:ie({timestamp:`time`,messageColor:null,messageStyle:null,levelStyle:null,icons:!1,colors:!0,level:`FULL`,categoryWidth:0,categoryStyle:null,categoryTruncate:`end`,wordWrap:!0})}),Ze?`debug`:`info`),file:re(l(Ge,`Azot_${new Date().toISOString().split(`.`)[0].replace(`T`,`_`).replaceAll(`-`,``).replaceAll(`:`,``)}.log`),{flushInterval:0})},loggers:[{category:[],lowestLevel:`trace`,sinks:[`console`,`file`]},{category:[`logtape`,`meta`],lowestLevel:`error`,sinks:[`console`]}]});const N=te([]),Qe=async e=>{let t=await p(e).then(e=>e.filter(e=>e.endsWith(`.log`))),n=t=>l(e,t),r=t.map(e=>h(n(e)).catch(()=>null).then(t=>({stats:t,path:n(e)}))),i=(await Promise.all(r)).filter(Boolean);i.sort((e,t)=>t.stats.mtime.getTime()-e.stats.mtime.getTime());let a=i.slice(50).map(e=>g(e.path));await Promise.allSettled(a).catch(N.error)},$e=e=>{if(typeof e==`string`)return{message:e};if(e instanceof Error)return{message:e.message};if(e&&typeof e==`object`){let t=`message`in e?String(e.message):void 0,n=`code`in e?String(e.code):void 0;if(t||n)return{message:t||n||`Unknown error`,code:n}}return{message:`Unknown error`}},et=new fe,P=e=>new(`default`in S?S.default:S)(e);var F=class{#e;constructor(e){this.#e=P({cwd:c(e),configName:s(e,`.json`)})}get length(){return Object.keys(this.#e.store).length}clear(){this.#e.clear()}getItem(e){return this.#e.get(e)??null}key(e){return Object.keys(this.#e.store).at(e)??null}removeItem(e){this.#e.delete(e)}setItem(e,t){this.#e.set(e,t)}};const I=e=>{let t=[`}`,`{`,`%`,`>`,`<`,`^`,`;`,"`",`$`,`"`,`@`,`=`],n=e;for(let e in t)n=n.replaceAll(`/`,`_`).replaceAll(t[e],``);return n},L=(e,t,n)=>{let r={},i={};for(let a of n)for(let n of t){let t=new URLPattern(n,a).exec(e);t&&(Object.assign(r,t.pathname.groups),Object.assign(i,t.search.groups))}return{pathname:r,search:i}},R=(e=new Map)=>{let t=(t,n)=>{for(let r of e.keys())for(let i of e.get(r)||[]){let e=n===void 0||isNaN(n),a=t===void 0||isNaN(t),o=!1;if(o=a?r===n:(e?isNaN(r):r===n)&&i===t,o)return!0}return!1},n=(t,n)=>{let r=n||NaN,i=t||NaN;e.has(r)?e.get(r)?.add(i):e.set(r,new Set([i]))},r=()=>Array.from(e.values()).flatMap(e=>Array.from(e)),i=e.size,a=r();return{items:e,has:t,set:n,getMin:()=>Math.min(...a),getMax:()=>Math.max(...a),seasonsCount:i,episodesCount:a.length}},tt=new Intl.DateTimeFormat(`en-US`,{year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}),nt=new Intl.DateTimeFormat(`en-US`,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}),rt=()=>{let e=new Date;return tt.format(e).replaceAll(`/`,`-`).replace(`, `,`_`).replaceAll(`:`,`-`)},it=()=>{let e=new Date,t=e.getMilliseconds().toString().padStart(3,`0`);return`${nt.format(e)}.${t}`},at=e=>`${u.gray(it().slice(2))} ${e.padEnd(18,` `)}`,z=new class t extends x{static requestEventName=`form`;static responseEventName=`form:response`;title;#e=Promise.resolve();constructor(t={}){super(),this.title=t.title,this.listen(async t=>{let{title:n,description:i,fields:a,...o}=t,s={},c=Object.entries(a||o);if(!b.isTTY||process.platform===`win32`){let t=0,a=1,o=!1;if(process.platform===`win32`)try{t=r(`\\\\.\\CONIN$`,`r`),a=r(`\\\\.\\CONOUT$`,`w`),o=!0}catch{}try{for(let[e,{label:r,type:o}]of c){let c=o===`confirm`;s[e]=ct([n,i,r].filter(Boolean).join(`. `)+(c?` (y/n)`:``)+`: `,void 0,{inputFd:t,outputFd:a})??``}return s}finally{o&&(e(t),e(a))}}b.setEncoding&&b.setEncoding(`utf8`),b.isTTY&&b.setRawMode&&b.setRawMode(!1),b.resume();let l=Se({input:b,output:ue,terminal:!0});try{for(let[e,{label:t,type:r}]of c){let a=r===`confirm`,o=[n,i,t].filter(Boolean).join(`. `)+(a?` (y/n)`:``)+`: `;s[e]=await Promise.race([l.question(o),C(st,``)])}return s}finally{l.close()}})}async ask(e){let n=()=>new Promise(n=>{this.once(t.responseEventName,e=>{n(e)}),this.emit(t.requestEventName,e)}),r=this.#e.then(n,n);return this.#e=r.then(()=>void 0,()=>void 0),r}listen(e){this.addListener(t.requestEventName,async n=>{let r=await e(n);this.emit(t.responseEventName,r)})}},ot=async(e,t)=>{let n=t?.fields??{answer:{label:e}};return await z.ask({title:t?.title,description:e,fields:n})},st=12e4,ct=(e,t,n)=>{let r=n?.inputFd??0;a(n?.outputFd??1,e||``);let o=Buffer.alloc(1),s=``;for(;;){try{i(r,o,0,1,null)}catch(e){if(e.code===`EOF`)break;throw e}let e=o.toString(`utf-8`);if(e===`
|
|
2
|
+
`||e===`\r`){if(e===`\r`)try{i(r,o,0,1,null),o.toString(`utf-8`)}catch(e){if(e.code===`EOF`)break;throw e}break}s+=e}return s.trim()||t},B=e=>{let t=[];for(let n of e)try{let e=De(n),r={...e,expires:e.expires instanceof Date?e.expires.getTime():e.expires,sameSite:typeof e.sameSite==`boolean`?`strict`:e.sameSite};t.push(r)}catch(e){N.debug(e instanceof Error?e.stack??e.message:String(e))}return t},lt=async e=>{let t=await f(e,`utf8`).catch(()=>``);if(!t)return[];let n=t.split(ae).flatMap(e=>e.split(`
|
|
3
|
+
`)).filter(e=>!!e.trim()&&!e.startsWith(`# `)).map(e=>e.split(` `)),r=[];for(let e of n){let[t,n,i,a,o,s,c]=e;r.push({name:s,value:c,expires:Number(o),maxAge:void 0,domain:t.replace(`#HttpOnly_`,``),path:i,secure:a===`TRUE`,httpOnly:void 0,sameSite:void 0})}return r},ut=(e,t)=>e.name===t.name&&e.domain===t.domain&&e.path===t.path&&e.partitioned===t.partitioned,V=(e,t)=>{let n=[...e];for(let e of t){let t=n.findIndex(t=>ut(t,e));t>=0?n[t]=e:n.push(e)}return n},dt=(e,t)=>{if(typeof e!=`string`)return e;if(t===void 0)throw TypeError(`CookieStore.set(name, value) requires a value argument`);return{name:e,value:t}};var H=class{#e={};#t;#n;#r=!1;static parse(e){return B(e)}constructor({storagePath:e}={}){this.#n=e,this.#t=[]}async import(e,{removeSource:t=!0}={}){if(await this.#i(),!(await h(e).catch(()=>null))?.isFile())return 0;N.debug(`Importing cookies from ${e}`);let n=await lt(e);this.#t=V(this.#t,n);try{await this.#a(),t&&await m(e,{force:!0})}catch(e){throw e}return n.length}async#i(){if(!(!this.#n||this.#r)){if((await h(this.#n).catch(()=>null))?.isFile()){let e=await f(this.#n,`utf8`);this.#e=e?JSON.parse(e):{},this.#t=`cookies`in this.#e?this.#e.cookies:[]}this.#r=!0}}async#a(){if(!this.#n)return;let e=JSON.stringify({...this.#e,cookies:this.#t},null,2);await _(this.#n,e,`utf8`)}async get(e){await this.#i();let t=typeof e==`string`?e:e.name;return this.#t.find(e=>e.name===t)??null}async getAll(e){if(await this.#i(),!e)return this.#t;let t=typeof e==`string`?e:e.name;return this.#t.filter(e=>e.name===t)??null}async set(e,t){await this.#i();let n=dt(e,t);this.#t=V(this.#t,[n]),await this.#a()}async delete(e){if(await this.#i(),!e)this.#t=[];else{let t=typeof e==`string`?e:e.name;this.#t=this.#t.filter(e=>e.name!==t)}await this.#a()}toString(){return this.#t.map(e=>`${e.name}=${e.value}`).join(`; `)}};const U=we.default??we,ft=e=>e?e instanceof Headers?e.has(`User-Agent`):typeof e==`object`&&e?`User-Agent`in e||`user-agent`in e:!1:!1,W=e=>e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e);var G=class{cookieStore;headers;#e;#t;constructor(e={}){this.headers=new Headers,this.configure(e)}configure({maxRetries:e=3,proxyUrl:t,allowH2:n=!0,cookieStore:r,fetch:i}={}){this.cookieStore=r??this.cookieStore??new H;let a=t?new Ee({uri:t,allowH2:n}):new Te({allowH2:n}),o={retry:e};this.#e=U.create({dispatcher:a,proxy:t,fetch:i,...o});let s=new Ce({browser:`chrome142`,proxyUrl:t,ignoreTlsErrors:!0,followRedirects:!1}),c=async(e,t)=>{let n=await s.fetch.bind(s)(e,t);return new Response(n.body,n)};this.#t=U.create({fetch:this.#r.bind(this,i??c),...o})}async fetch(e,t={}){let n=await this.#o(e,t)??{},r=e instanceof Request?e:new Request(e,n),i=await this.#n(e,n.headers??r.headers),a=(ft(t?.headers)?this.#e:this.#t)[n.method?.toLowerCase()??r?.method?.toLowerCase()??`get`],o=n.body,s=await a(r.url,{...n,body:o,headers:i}),c=s.headers.getSetCookie();return c&&await this.setCookies(c),s}async#n(e,t){let n=this.appendHeaders(t),r=await this.cookieStore.getAll(),i=r.filter(t=>!t.domain||W(e).hostname.includes(t.domain));for(let e of r)i.find(t=>t.name===e.name)||e.domain||i.push(e);let a=i.map(e=>`${e.name}=${e.value}`).join(`; `);return a?(n.has(`cookie`)?n.get(`cookie`)||n.delete(`cookie`):n.set(`cookie`,a),n):(n.get(`cookie`)||n.delete(`cookie`),n)}async setCookies(e){let t=[];if(typeof e==`string`){let[n]=B([e]);n&&t.push(n)}else if(Array.isArray(e)&&typeof e.at(0)==`string`){let n=B(e);t.push(...n)}else Array.isArray(e)&&typeof e[0]!=`string`&&t.push(...e);if(!(!t||!t?.length))for(let e of t)await this.cookieStore.set(e)}appendHeaders(e){let t=new Headers(this.headers),n=e instanceof Headers?e.entries():Object.entries(e??{});for(let[e,r]of n)t.set(e,r);return t}setHeader(e,t){this.headers.set(e,t)}removeHeader(e){this.headers.delete(e)}async#r(e,t,n={}){let r=0,i=t instanceof Request?new URL(t.url):t,a=await this.#o(t,n)??{};for(a.redirect=`manual`;;){let t=await e(i,a),n=t.headers.getSetCookie();if(n.length&&await this.setCookies(n),!this.#a(t.status))return t;let o=t.headers.get(`location`);if(!o)return t;if(r>=20)throw Error(`Maximum redirect limit (20) exceeded`);r+=1,i=new URL(o,W(i)),a=this.#i(a,t.status)??{},a.headers=await this.#n(i,a.headers)}}#i(e={},t){let n=e.method?.toUpperCase()??`GET`;if(t===303||(t===301||t===302)&&n===`POST`){let t=new Headers(e.headers);return t.delete(`content-length`),t.delete(`content-type`),{...e,method:`GET`,body:void 0,headers:t,redirect:`manual`}}return{...e,redirect:`manual`}}#a(e){return[301,302,303,307,308].includes(e)}async#o(e,t={}){if(!(e instanceof Request))return{...t};let n=new Headers(e.headers);for(let[e,r]of new Headers(t.headers).entries())n.set(e,r);let r=(t.method??e.method).toUpperCase(),i={...t,method:r,headers:n};return t.body!==void 0||r===`GET`||r===`HEAD`?(i.body=t.body,i):(i.body=await e.clone().arrayBuffer(),i)}};const pt=new G,{COMMON_CONTEXT:mt}=w,ht=async e=>{let t=async e=>{let n=await d.readdir(e,{withFileTypes:!0});return(await Promise.all(n.map(async n=>{let r=n.name.endsWith(`.js`),i=n.name.endsWith(`.test.js`);return n.isDirectory()&&n.name!==`node_modules`?t(o.join(e,n.name)):n.isFile()&&r&&!i?[o.join(e,n.name)]:[]}))).flat()};return t(e)},gt=async(e,t={})=>{let n={};if(t.dirname){let e=await ht(t.dirname);for(let r of e)n[r.replace(t.dirname,`.`)]=!0}let r={context:w.createContext({...mt,...t.context}),dirname:t.dirname,access:{"node:crypto":!0,crypto:!0,azot:!0,...n,...t.access},type:t.format===`esm`?w.MODULE_TYPE.ECMA:w.MODULE_TYPE.COMMONJS};return await d.stat(e).then(()=>!0).catch(()=>!1)?await d.access(e).then(()=>!0).catch(()=>!1)?await w.readScript(e,r):w.createScript(t.name??`default`,e,r):_t(e,t.name??`default`,r)},_t=(e,t=`Eval`,n)=>{try{return w.createScript(t,e,n)}catch(t){return console.debug(t),console.debug(e),console.error(`Syntax Error: ${t.message}`),null}},vt=(e,t=1)=>typeof e==`string`?Array.from({length:t},()=>e[Math.floor(Math.random()*e.length)]):!Array.isArray(e)||e.length===0?[]:Array.from({length:t},()=>e[Math.floor(Math.random()*e.length)]),yt=new class e extends x{static requestEventName=`feedback`;static responseEventName=`feedback:response`;#e=Promise.resolve();async ask(t){let n=()=>new Promise(n=>{this.once(e.responseEventName,e=>{n(e)}),this.emit(e.requestEventName,t)}),r=this.#e.then(n,n);return this.#e=r.then(()=>void 0,()=>void 0),r}listen(t){this.addListener(e.requestEventName,async n=>{let r=await t(n);this.emit(e.responseEventName,r)})}},K=e=>{if(!e||typeof e!=`object`)return!1;let t=`name`in e?String(e.name):``;return t===`ExitPromptError`||t===`AbortPromptError`},bt=e=>e&&e[0].toUpperCase()+e.slice(1),q=(e,t=!1)=>{if(typeof e==`boolean`)return e;if(typeof e!=`string`)return t;let n=e.trim().toLowerCase();return[`1`,`true`,`yes`,`y`,`on`].includes(n)?!0:[`0`,`false`,`no`,`n`,`off`].includes(n)?!1:t},J=(e,t=0)=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e!=`string`)return t;let n=Number(e);return Number.isFinite(n)?n:t},xt=e=>{switch(e.type){case`checkbox`:return q(e.defaultValue,!1);case`number`:return J(e.defaultValue,0);default:return e.defaultValue??``}},St=(e,t)=>{switch(e.type){case`checkbox`:return q(t,q(e.defaultValue,!1));case`number`:return J(t,J(e.defaultValue,0));default:return typeof t==`string`?t:t==null?e.defaultValue??``:String(t)}},Ct=e=>{let t=Object.entries(e).map(([e,t])=>[e,xt(t)]);return Object.fromEntries(t)},Y=(e,t)=>{let n=Object.entries(e).map(([e,n])=>[e,St(n,t[e])]);return Object.fromEntries(n)},wt=e=>!!e&&typeof e==`object`&&`fields`in e,Tt=e=>{switch(e){case`password`:case`number`:case`checkbox`:return e;default:return`text`}},Et=e=>{let t=Object.fromEntries(Object.entries(e.fields).map(([e,t])=>[e,{type:Tt(t.type),title:t.label||e,description:t.description,placeholder:t.placeholder,defaultValue:t.defaultValue??t.value,required:t.required,autoFocus:t.autoFocus}]));return{message:e.description??``,options:{title:e.title,form:t,primaryAction:e.actions?.primaryAction,secondaryAction:e.actions?.secondaryAction}}},X=async e=>{e?.onAction&&await e.onAction()},Z=async(e,t)=>{if(!t.length)return`dismiss`;try{return await Me({message:e,loop:!1,choices:t.map(e=>({name:e.action.title,value:e.kind}))})}catch(e){if(K(e))return`dismiss`;throw e}},Dt=new Set([`http:`,`https:`,`mailto:`]),Ot=e=>{try{return Dt.has(new URL(e).protocol)}catch{return!1}},kt=async(e,t)=>{if(!Ot(e)){N.warn(`Blocked unsupported external URL protocol: ${e}`);return}if(t){let{default:t}=await import(`open`);await t(e);return}let{shell:n}=await import(`electron`);await n.openExternal(e)},At=({isCLI:e,resolveTitle:t,requestPrompt:n})=>{let r=(t,n,r)=>{let i=typeof t==`string`?t:t?.toString();return i?.trim()&&kt(i,e).catch(e=>{N.error(`Failed to open URL: ${i}`),N.debug(e instanceof Error?e.message:String(e))}),null},i=async(n,r={})=>{let i=t(r.title)??`Azot`,a=[r.primaryAction?{kind:`primary`,action:r.primaryAction}:null,r.secondaryAction?{kind:`secondary`,action:r.secondaryAction}:null].filter(Boolean);if(e){if(!a.length)return N.info(n);let e=await Z(n,a);e===`primary`&&await X(r.primaryAction),e===`secondary`&&await X(r.secondaryAction);return}let o=(await yt.ask({variant:`notify`,title:i,message:n,style:r.style,primaryAction:r.primaryAction?{title:r.primaryAction.title,style:r.primaryAction.style}:void 0,secondaryAction:r.secondaryAction?{title:r.secondaryAction.title,style:r.secondaryAction.style}:void 0})).action??`dismiss`;o===`primary`&&await X(r.primaryAction),o===`secondary`&&await X(r.secondaryAction)},a=async(n,r={})=>{let i=t(r.title)??`Azot`,a=!!r.primaryAction||!!r.secondaryAction,o=r.primaryAction??{title:`OK`},s=r.secondaryAction??{title:`Cancel`,style:`cancel`};if(e){if(a){let e=await Z(n,[{kind:`primary`,action:o},{kind:`secondary`,action:s}]);return e===`primary`?(await X(o),!0):(e===`secondary`&&await X(s),!1)}try{let e=await Oe({message:n,default:!0});return e?await X(r.primaryAction):await X(r.secondaryAction),e}catch(e){if(K(e))return!1;throw e}}let c=await yt.ask({variant:`confirm`,title:i,message:n,style:r.style,primaryAction:{title:o.title,style:o.style},secondaryAction:{title:s.title,style:s.style}}),l=c.action===`primary`;return l?await X(o):c.action===`secondary`&&await X(s),l},o=async(r,i)=>{let a=Ct(i.form),o=Object.entries(i.form),s=!!i.primaryAction||!!i.secondaryAction,c=i.primaryAction??{title:`Submit`},l=i.secondaryAction??{title:`Cancel`,style:`cancel`};if(e){let e={};try{for(let[t,n]of o){let r=[n.title||t,n.description].filter(Boolean).join(` - `);if(n.type===`checkbox`){e[t]=await Oe({message:r,default:q(n.defaultValue,!1)});continue}if(n.type===`number`){let i=J(n.defaultValue,NaN);e[t]=await Ae({message:r,default:Number.isFinite(i)?i:void 0,validate:e=>(e===void 0||Number.isNaN(e))&&n.required?`This field is required`:!0});continue}if(n.type===`password`){e[t]=await je({message:r,validate:n.required?e=>String(e??``).trim()?!0:`This field is required`:void 0});continue}e[t]=await ke({message:r,default:n.defaultValue,validate:n.required?e=>String(e??``).trim()?!0:`This field is required`:void 0})}}catch(e){if(K(e))return a;throw e}if(!s)return Y(i.form,e);let t=await Z(r,[{kind:`primary`,action:c},{kind:`secondary`,action:l}]);return t===`primary`?(await X(c),Y(i.form,e)):(t===`secondary`&&await X(l),a)}let u=Object.fromEntries(o.map(([e,t])=>[e,{type:t.type,label:t.title||e,description:t.description,placeholder:t.placeholder,defaultValue:t.defaultValue,value:t.defaultValue,required:t.required,autoFocus:t.autoFocus}])),d=await n({title:t(i.title),description:r,fields:u,actions:s?{primaryAction:{title:c.title,style:c.style},secondaryAction:{title:l.title,style:l.style}}:void 0}),f=d.__action??`primary`,p={...d};return delete p.__action,f===`primary`?(await X(i.primaryAction),Y(i.form,p)):(f===`secondary`&&await X(i.secondaryAction),a)};return{notify:i,confirm:a,askPrompt:async(e,t)=>{if(wt(e)){let t=Et(e);return o(t.message,t.options)}if(!t)throw TypeError(`prompt(message, options) requires a form definition`);return o(e,t)},openWindow:r}},Q=(e,t,n)=>{Object.getOwnPropertyDescriptor(e,t)||Object.defineProperty(e,t,n)},jt=()=>{Q(Uint8Array.prototype,`toBase64`,{value:function(){return Buffer.from(this).toString(`base64`)},writable:!0,configurable:!0}),Q(Uint8Array.prototype,`toHex`,{value:function(){return Buffer.from(this).toString(`hex`)},writable:!0,configurable:!0}),Q(Uint8Array,`fromBase64`,{value:function(e){return new Uint8Array(Buffer.from(e,`base64`))},writable:!0,configurable:!0}),Q(Uint8Array,`fromHex`,{value:function(e){return new Uint8Array(Buffer.from(e,`hex`))},writable:!0,configurable:!0})},Mt=new Map([[24,[`Sequoia`,`15`]],[23,[`Sonoma`,`14`]],[22,[`Ventura`,`13`]],[21,[`Monterey`,`12`]],[20,[`Big Sur`,`11`]],[19,[`Catalina`,`10.15`]],[18,[`Mojave`,`10.14`]],[17,[`High Sierra`,`10.13`]],[16,[`Sierra`,`10.12`]],[15,[`El Capitan`,`10.11`]],[14,[`Yosemite`,`10.10`]],[13,[`Mavericks`,`10.9`]],[12,[`Mountain Lion`,`10.8`]],[11,[`Lion`,`10.7`]],[10,[`Snow Leopard`,`10.6`]],[9,[`Leopard`,`10.5`]],[8,[`Tiger`,`10.4`]],[7,[`Panther`,`10.3`]],[6,[`Jaguar`,`10.2`]],[5,[`Puma`,`10.1`]]]),$=()=>{switch(y.type()){case`Darwin`:return`macOS`;case`Windows_NT`:return`Windows`;default:return`Linux`}},Nt=()=>{let e=Number(y.release().split(`.`)[0]),[t,n]=Mt.get(e)||[`Unknown`,``];return{name:t,version:n}},Pt=()=>{switch($()){case`macOS`:return Nt().version;case`Windows`:return y.release();case`Linux`:return y.release()}},Ft=e=>{let t=process.version.replace(/^v/,``),n=[{brand:`Azot`,version:e.split(`.`).slice(0,2).join(`.`)},{brand:`Node.js`,version:t.split(`.`).slice(0,1).join(`.`)}];return{mobile:!1,platform:$(),brands:n,getHighEntropyValues:async r=>{let i={mobile:!1,platform:$(),brands:n};return r.includes(`architecture`)&&(i.architecture=y.arch()),r.includes(`platform`)&&(i.platform=$()),r.includes(`platformVersion`)&&(i.platformVersion=Pt()),r.includes(`fullVersionList`)&&(i.fullVersionList=[{brand:`Azot`,version:e},{brand:`Node.js`,version:t}]),i}}},It=({name:e=`extension`,dir:t=process.cwd(),title:n}={})=>{jt();let r=O(l(t,e)),i=new F(l(r,`storage.json`)),a=new H({storagePath:l(r,`cookies.json`)}),o=new G({cookieStore:a}),s=(e,t,n)=>e.split(t)[1]?.split(n)[0]?.trim(),c={sanitizeString:I,execUrlPatterns:L,extendEpisodes:R,between:s,getRandomElements:vt},u=n?bt(n):void 0,{notify:d,confirm:f,askPrompt:p,openWindow:m}=At({isCLI:!0,resolveTitle:e=>e||u,requestPrompt:async e=>(e.title||=u,await z.ask(e))});class h extends ve{constructor(e){super({...e,formats:e.formats??pe})}}class g extends xe{constructor(e,t={}){super(e,{fetchFn:o.fetch.bind(o),...t,requestInit:{...t.requestInit,headers:{...o.headers,...t.requestInit?.headers}}})}}let _={defineExtension:e=>e,version:E.version,sleep:C,sanitizeString:I,execUrlPatterns:L,extendEpisodes:R,between:s,getRandomElements:vt,utils:c,notify:d,confirm:f,prompt:p,Input:h,UrlSource:g,ALL_FORMATS:pe,DASH:me,DASH_FORMATS:he,HLS:ge,HLS_FORMATS:_e,MP4:be,MP3:ye,input:ot,ask:p};class ee{get cookie(){return a.toString()}}let v={fetch:o.fetch.bind(o),Response,Request,Headers,AbortController,AbortSignal,URL,URLSearchParams,URLPattern,open:m,Blob,structuredClone,btoa,atob,TextEncoder,TextDecoder,Uint8Array,crypto,console:{log:console.log,info:N.info.bind(N),warn:N.warn.bind(N),error:(...e)=>{let t=String(e[0]??`Unknown error`);et.emit(`error`,{message:t}),N.error(t)},trace:N.trace.bind(N),debug:N.debug.bind(N)},Event,EventTarget,localStorage:i,cookieStore:a,document:new ee,eval:e=>_t(e)?.exports,navigator:{appName:`Azot`,appVersion:E.version,platform:process.platform,userAgent:`Azot/${E.version}`,userAgentData:Ft(E.version)}};return{http:o,question:z,common:c,Streamyx:_,Azot:_,window:v,...v}};export{Ie as A,Xe as C,ze as D,D as E,Be as O,qe as S,Le as T,Ke as _,z as a,M as b,F as c,$e as d,Qe as f,Ge as g,Ue as h,pt as i,E as j,Fe as k,P as l,We as m,gt as n,rt as o,N as p,G as r,at as s,It as t,et as u,He as v,O as w,Ye as x,Je as y};
|
package/dist/context.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./context-
|
|
1
|
+
import{t as e}from"./context-P15t7YGq.mjs";export{e as createContext};
|
package/dist/vitest.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./context-
|
|
1
|
+
import{t as e}from"./context-P15t7YGq.mjs";import"./context.mjs";import{beforeEach as t,vi as n}from"vitest";const r=e();Object.entries(r).forEach(([e,t])=>{n.stubGlobal(e,t)}),n.mock(`azot`,async()=>r.Azot),t(async()=>{r.localStorage.clear();let e=await r.cookieStore.getAll();for(let t of e)await r.cookieStore.delete(t.name);n.clearAllMocks()});export{};
|
package/package.json
CHANGED
|
@@ -1,73 +1,97 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "azot",
|
|
3
|
-
"version": "5.0.0-alpha.
|
|
4
|
-
"description": "
|
|
5
|
-
"
|
|
6
|
-
"api",
|
|
7
|
-
"azot",
|
|
8
|
-
"extensions",
|
|
9
|
-
"types"
|
|
10
|
-
],
|
|
11
|
-
"homepage": "https://azot.mov/docs",
|
|
12
|
-
"license": "MIT",
|
|
3
|
+
"version": "5.0.0-alpha.19",
|
|
4
|
+
"description": "A powerful, extensible app for downloading videos",
|
|
5
|
+
"homepage": "https://azot.mov",
|
|
13
6
|
"author": "Vitaly Gashkov <vitalygashkov@vk.com>",
|
|
14
7
|
"bin": {
|
|
15
|
-
"
|
|
8
|
+
"azot": "./dist/azot.mjs",
|
|
9
|
+
"azt": "./dist/azt.mjs"
|
|
16
10
|
},
|
|
17
11
|
"files": [
|
|
18
12
|
"dist",
|
|
19
13
|
"types"
|
|
20
14
|
],
|
|
21
|
-
"
|
|
22
|
-
"
|
|
15
|
+
"type": "module",
|
|
16
|
+
"main": "./dist/api.mjs",
|
|
17
|
+
"types": "./types/api.d.ts",
|
|
23
18
|
"exports": {
|
|
24
19
|
".": {
|
|
25
|
-
"types": "./types/
|
|
26
|
-
"import": "./dist/
|
|
27
|
-
"
|
|
20
|
+
"types": "./types/api.d.ts",
|
|
21
|
+
"import": "./dist/api.mjs",
|
|
22
|
+
"module-sync": "./dist/api.mjs"
|
|
28
23
|
},
|
|
29
24
|
"./context": {
|
|
30
25
|
"types": "./types/context.d.ts",
|
|
31
26
|
"import": "./dist/context.mjs",
|
|
32
|
-
"
|
|
27
|
+
"module-sync": "./dist/context.mjs"
|
|
33
28
|
},
|
|
29
|
+
"./types/extension": "./types/extension.d.ts",
|
|
34
30
|
"./vitest": {
|
|
35
31
|
"import": "./dist/vitest.mjs",
|
|
36
|
-
"
|
|
32
|
+
"module-sync": "./dist/vitest.mjs"
|
|
37
33
|
}
|
|
38
34
|
},
|
|
39
35
|
"scripts": {
|
|
40
|
-
"
|
|
41
|
-
"
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
"
|
|
45
|
-
"
|
|
36
|
+
"start": "tsx --env-file-if-exists .env.local ./src/cli.ts",
|
|
37
|
+
"dev": "tsx watch --env-file-if-exists .env.local ./src/cli.ts",
|
|
38
|
+
"bundle:extensions": "node ./scripts/bundle-extensions.mjs",
|
|
39
|
+
"build": "pnpm run bundle:extensions && tsdown",
|
|
40
|
+
"typecheck": "tsc --noEmit -p tsconfig.json --composite false",
|
|
41
|
+
"test": "vitest"
|
|
46
42
|
},
|
|
47
43
|
"dependencies": {
|
|
44
|
+
"@azot/shared": "workspace:*",
|
|
45
|
+
"@gitbeaker/rest": "^43.8.0",
|
|
48
46
|
"@inquirer/prompts": "^8.3.2",
|
|
49
47
|
"@logtape/file": "^2.0.4",
|
|
50
48
|
"@logtape/logtape": "^2.0.4",
|
|
51
49
|
"@logtape/pretty": "^2.0.4",
|
|
50
|
+
"@tanstack/query-core": "^5.90.20",
|
|
51
|
+
"@transcrobes/subs-convert": "^5.2.0",
|
|
52
|
+
"@tribute-tg/better-auth": "^2.1.10",
|
|
53
|
+
"better-auth": "^1.5.5",
|
|
52
54
|
"conf": "^15.1.0",
|
|
53
|
-
"
|
|
54
|
-
"
|
|
55
|
+
"cookie": "^1.1.1",
|
|
56
|
+
"cross-spawn": "^7.0.6",
|
|
57
|
+
"dasha": "^4.2.0",
|
|
58
|
+
"impit": "^0.13.0",
|
|
59
|
+
"ky": "^1.14.3",
|
|
60
|
+
"mediabunny": "^1.44.2",
|
|
55
61
|
"metavm": "^1.4.5",
|
|
62
|
+
"molnia": "workspace:*",
|
|
56
63
|
"nanospinner": "^1.2.2",
|
|
57
|
-
"
|
|
64
|
+
"okova": "^0.11.0",
|
|
65
|
+
"open": "^11.0.0",
|
|
66
|
+
"p-queue": "^9.1.0",
|
|
67
|
+
"picocolors": "^1.1.1",
|
|
68
|
+
"posthog-js": "^1.360.2",
|
|
69
|
+
"semver": "^7.7.4",
|
|
70
|
+
"shifro": "^1.1.4",
|
|
71
|
+
"telegram-better-auth": "^0.0.8",
|
|
58
72
|
"undici": "^7.24.4",
|
|
59
|
-
"urlpattern-polyfill": "^10.1.0"
|
|
73
|
+
"urlpattern-polyfill": "^10.1.0",
|
|
74
|
+
"yargs": "^18.0.0",
|
|
75
|
+
"yauzl": "^3.2.1",
|
|
76
|
+
"zod": "^4.3.6"
|
|
60
77
|
},
|
|
61
78
|
"devDependencies": {
|
|
62
|
-
"@types/node": "^25.
|
|
63
|
-
"
|
|
64
|
-
"
|
|
79
|
+
"@types/node": "^25.5.0",
|
|
80
|
+
"@types/semver": "^7.7.1",
|
|
81
|
+
"@types/yargs": "^17.0.35",
|
|
82
|
+
"execa": "^9.6.1",
|
|
83
|
+
"javascript-obfuscator": "^4.1.1",
|
|
84
|
+
"tsdown": "^0.22.0",
|
|
85
|
+
"tsx": "^4.21.0",
|
|
86
|
+
"typescript": "^6.0.3"
|
|
65
87
|
},
|
|
66
88
|
"peerDependencies": {
|
|
67
|
-
"vitest": "
|
|
89
|
+
"vitest": "^4.1.0"
|
|
68
90
|
},
|
|
69
91
|
"engines": {
|
|
70
|
-
"node": ">=24.10"
|
|
92
|
+
"node": ">=24.10",
|
|
93
|
+
"pnpm": ">=10"
|
|
71
94
|
},
|
|
72
|
-
"
|
|
95
|
+
"packageManager": "pnpm@11.0.0",
|
|
96
|
+
"productName": "Azot"
|
|
73
97
|
}
|
|
@@ -1,12 +1,35 @@
|
|
|
1
|
-
import { Extension } from "./extension";
|
|
1
|
+
import type { Extension } from "./extension";
|
|
2
|
+
import type { ExtensionV2 } from "./extension-v2";
|
|
3
|
+
import type { InputFormat, InputOptions } from "mediabunny";
|
|
2
4
|
|
|
3
5
|
export * from "./extension";
|
|
6
|
+
export * from "./extension-v2";
|
|
4
7
|
export * from "./feedback";
|
|
5
8
|
|
|
9
|
+
import { Input as OriginalInput } from "dasha";
|
|
10
|
+
export {
|
|
11
|
+
InputTrack,
|
|
12
|
+
UrlSource,
|
|
13
|
+
ALL_FORMATS,
|
|
14
|
+
DASH,
|
|
15
|
+
DASH_FORMATS,
|
|
16
|
+
HLS,
|
|
17
|
+
HLS_FORMATS,
|
|
18
|
+
MP4,
|
|
19
|
+
MP3,
|
|
20
|
+
} from "dasha";
|
|
21
|
+
|
|
22
|
+
export class Input extends OriginalInput {
|
|
23
|
+
constructor(options: Omit<InputOptions, "formats"> & { formats?: readonly InputFormat[] });
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export { InputFormat, InputOptions };
|
|
27
|
+
|
|
6
28
|
/**
|
|
7
29
|
* Simple wrapper to support type checking
|
|
8
30
|
*/
|
|
9
31
|
export function defineExtension(extension: Extension): Extension;
|
|
32
|
+
export function defineExtension(extension: ExtensionV2): ExtensionV2;
|
|
10
33
|
|
|
11
34
|
/**
|
|
12
35
|
* Get Azot version
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
VideoCodec,
|
|
3
|
+
VideoDynamicRange,
|
|
4
|
+
AudioCodec,
|
|
5
|
+
// SubtitleCodec,
|
|
6
|
+
Input,
|
|
7
|
+
InputTrack,
|
|
8
|
+
MaybePromise,
|
|
9
|
+
} from "dasha";
|
|
10
|
+
import { Options } from "./extension";
|
|
11
|
+
|
|
12
|
+
export type UrlPatternString = string;
|
|
13
|
+
|
|
14
|
+
export interface ExtensionV2 {
|
|
15
|
+
/**
|
|
16
|
+
* Returns whether the extension can handle a URL, or a URLPattern-compatible string
|
|
17
|
+
* that will be tested against the input URL.
|
|
18
|
+
*/
|
|
19
|
+
canHandle?: ((url: string) => MaybePromise<boolean>) | UrlPatternString;
|
|
20
|
+
setup?(): MaybePromise<void>;
|
|
21
|
+
|
|
22
|
+
search?(query: string): MaybePromise<SearchResult[]>;
|
|
23
|
+
resolveEntries(url: string, options: Options): MaybePromise<MediaEntry[]>;
|
|
24
|
+
resolveMedia?(url: string, options: Options, entry: MediaEntry): MaybePromise<Input | null>;
|
|
25
|
+
|
|
26
|
+
auth?: {
|
|
27
|
+
getState?(): MaybePromise<{ authenticated: boolean; user?: string } | null>;
|
|
28
|
+
login?(credentials: { username?: string; password?: string; otp?: string }): MaybePromise<void>;
|
|
29
|
+
logout?(): MaybePromise<void>;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
drm?: {
|
|
33
|
+
getCertificate?(request: CertificateRequest): MaybePromise<Uint8Array>;
|
|
34
|
+
getLicense?(request: LicenseRequest): MaybePromise<Uint8Array>;
|
|
35
|
+
getKeys?(request: DrmRequest): MaybePromise<Map<string, string>>;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
hooks?: {
|
|
39
|
+
beforeDownload?(): MaybePromise<void>;
|
|
40
|
+
afterMux?(): MaybePromise<void>;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface SearchResult extends MediaEntry {
|
|
45
|
+
id: string | number;
|
|
46
|
+
url?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface MediaEntry {
|
|
50
|
+
type?: "movie" | "episode" | "video" | "audio" | "subtitle";
|
|
51
|
+
title?: string;
|
|
52
|
+
description?: string;
|
|
53
|
+
thumbnailUrl?: string;
|
|
54
|
+
author?: string;
|
|
55
|
+
year?: number;
|
|
56
|
+
|
|
57
|
+
season?: number;
|
|
58
|
+
episode?: number;
|
|
59
|
+
episodeTitle?: string;
|
|
60
|
+
|
|
61
|
+
input?: Input;
|
|
62
|
+
|
|
63
|
+
details?: Record<string, any>;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export type RequiredMediaEntry = MediaEntry & { input: Input };
|
|
67
|
+
|
|
68
|
+
export interface DrmRequest {
|
|
69
|
+
system: "widevine" | "playready" | "fairplay" | "clearkey";
|
|
70
|
+
entry: RequiredMediaEntry;
|
|
71
|
+
track?: InputTrack;
|
|
72
|
+
options?: Options;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface CertificateRequest extends DrmRequest {
|
|
76
|
+
data: Uint8Array;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface LicenseRequest extends DrmRequest {
|
|
80
|
+
data: Uint8Array;
|
|
81
|
+
}
|
package/types/extension.d.ts
CHANGED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface ExtensionManifest {
|
|
2
|
+
matches: string[];
|
|
3
|
+
name: string;
|
|
4
|
+
tag?: string;
|
|
5
|
+
icon?: string;
|
|
6
|
+
permissions?: string[];
|
|
7
|
+
regions?: string[]; // Examples: ["NO", "CH"] - extension is available only in Norway and Switzerland; ["-US", "-RU"] - extension is available in all countries except USA and Russia
|
|
8
|
+
manifestVersion: number;
|
|
9
|
+
}
|
package/dist/azt.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
const e=require(`./chunk-350yNsax.cjs`);let t=require(`node:util`),n=require(`node:fs`),r=require(`node:path`);r=e.n(r);let i=require(`tsdown`),a=require(`node:crypto`),o=require(`javascript-obfuscator`);o=e.n(o);const s=Buffer.from(`STX`,`utf8`),c=(e,t,r)=>{let i=(0,a.randomBytes)(32),o=(0,a.randomBytes)(16),c=(0,n.readFileSync)(t),l=(0,a.createCipheriv)(`aes-256-cbc`,i,o),u=Buffer.concat([l.update(c),l.final()]),d=(0,a.publicEncrypt)(e,i),f=Buffer.concat([s,o,d,u]);return r&&(0,n.writeFileSync)(r,f),{aesIv:o,encryptedAesKey:d,encryptedCode:u}},l=(e,t,r)=>{let i=(0,n.readFileSync)(t),o=s.byteLength;if(!i.subarray(0,o).equals(s))throw Error(`Incorrect file format`);let c=o,l=c+16,u=l+512,d=i.subarray(c,l),f=i.subarray(l,u),p=i.subarray(u),m=(0,a.createDecipheriv)(`aes-256-cbc`,(0,a.privateDecrypt)(e,f),d),h=Buffer.concat([m.update(p),m.final()]).toString(`utf8`);return r&&(0,n.writeFileSync)(r,h),h},u=(e,t)=>{let r=(0,n.readFileSync)(e,`utf8`);console.log(`Obfuscating...`),console.time(`Obfuscation complete in`);let i=o.default.obfuscate(r,{target:`node`,compact:!0,controlFlowFlattening:!0,controlFlowFlatteningThreshold:1,deadCodeInjection:!0,debugProtection:!0,identifierNamesGenerator:`hexadecimal`,numbersToExpressions:!0,selfDefending:!0,simplify:!0,splitStrings:!0,splitStringsChunkLength:5,stringArray:!0,stringArrayCallsTransform:!0,stringArrayCallsTransformThreshold:1,stringArrayEncoding:[`base64`],stringArrayIndexShift:!0,stringArrayRotate:!0,stringArrayShuffle:!0,stringArrayWrappersCount:2,stringArrayWrappersChainedCalls:!0,stringArrayWrappersType:`function`,stringArrayThreshold:1,transformObjectKeys:!0,unicodeEscapeSequence:!1});console.timeEnd(`Obfuscation complete in`);let a=i.getObfuscatedCode();return(0,n.writeFileSync)(t||e,a),a},d=(0,t.parseArgs)({allowPositionals:!0,allowNegative:!0,options:{input:{type:`string`,short:`i`,description:`Path to the input file`},key:{type:`string`,short:`k`,description:`Path to the key file (public for encrypt, private for decrypt)`},output:{type:`string`,short:`o`,description:`Path to the output file`},format:{type:`string`,short:`f`,description:`Output format`},watch:{type:`boolean`,description:`Watch file changes`},minify:{type:`boolean`,description:`Minify output`},obfuscate:{type:`boolean`,description:`Obfuscate output`},encrypt:{type:`boolean`,description:`Encrypt extension source code (.js will be packed inside .stx)`},decrypt:{type:`boolean`,description:`Decrypt encrypted extension`}}}),f=()=>{let e=[process.cwd(),r.default.join(process.cwd(),`src`),r.default.join(process.cwd(),`lib`)];for(let t of e){let e=(0,n.readdirSync)(t).filter(e=>!e.endsWith(`.d.ts`)).filter(e=>new Set([`.ts`,`.js`,`.cjs`,`.mjs`]).has(r.default.extname(e))),i=e=>r.default.basename(e,r.default.extname(e)),a=e.find(e=>i(e)===`index`)||e.find(e=>i(e)===`main`)||e[0];if(a)return r.default.join(t,a)}},p=e=>e===`esm`?`mjs`:`cjs`,m=(e,t)=>r.default.join(process.cwd(),`dist`,`${r.default.parse(e).name}.${p(t)}`),h=(e,t)=>{let{dir:n,name:i}=r.default.parse(e);return r.default.join(n,`${i}-${t}.azt`)};(async()=>{let[e,...t]=d.positionals,a=d.values.input||t[0]||f();if(!a)throw Error(`No entry file found`);if(e===`build`||e===`pack`){let t=typeof d.values.minify==`boolean`?d.values.minify:!0,o=d.values.format??`cjs`;await(0,i.build)({entry:a.replace(process.cwd(),`.`).replace(r.default.sep,`/`),format:o,platform:`node`,target:`node24`,watch:d.values.watch,minify:t,inlineOnly:!1}),d.values.input=m(a,o);let s=require(r.default.join(process.cwd(),`package.json`));if((typeof d.values.obfuscate==`boolean`?d.values.obfuscate:s.private)&&u(d.values.input,d.values.input),d.values.encrypt||e===`pack`){let e=(0,n.readFileSync)(d.values.key||r.default.join(__dirname,`../public.pem`),`utf8`),t=d.values.output||h(d.values.input,s.version);c(e,d.values.input,t),(0,n.rmSync)(d.values.input)}}else if(e===`decrypt`)l((0,n.readFileSync)(d.values.key||r.default.join(__dirname,`../private.pem`),`utf8`),a,d.values.output||a.replace(/\.stx$/,`.js`)),d.values.input&&(0,n.rmSync)(d.values.input);else if(e===`dev`||e===`develop`||!e){let e=typeof d.values.minify==`boolean`?d.values.minify:!1;await(0,i.build)({entry:a,format:d.values.format??`cjs`,platform:`node`,target:`node22`,watch:!0,minify:e})}})();
|
package/dist/chunk-350yNsax.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,a)=>(a=n==null?{}:e(i(n)),s(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return o}});
|
package/dist/chunk-DtROqxiw.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";var t=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),n=e(import.meta.url);export{n,t};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./chunk-DtROqxiw.mjs";import{closeSync as t,existsSync as n,mkdirSync as r,openSync as i,readSync as a,writeSync as o}from"node:fs";import{basename as s,dirname as c,join as l}from"node:path";import u,{EOL as d,homedir as f,tmpdir as p}from"node:os";import{setTimeout as m}from"node:timers/promises";import{confirm as ee,input as te,number as ne,password as re,select as h}from"@inquirer/prompts";import{readFile as g,rm as _,stat as v,writeFile as ie}from"node:fs/promises";import{configureSync as y,getConsoleSink as ae,getLogger as oe,withFilter as se}from"@logtape/logtape";import{getFileSink as ce}from"@logtape/file";import{getPrettyFormatter as le}from"@logtape/pretty";import{arch as ue,platform as de,stdin as b,stdout as fe,version as pe}from"node:process";import me,{EventEmitter as x}from"node:events";import"picocolors";import"urlpattern-polyfill";import{createInterface as he}from"node:readline/promises";import{Impit as ge}from"impit";import{Agent as _e,ProxyAgent as ve}from"undici";import ye from"metavm";import"nanospinner";import S from"conf";var be=`@azot/desktop`,C=`5.0.0-alpha.55`,xe=`Azot`,w={name:be,version:C,description:`A powerful, extensible app for downloading videos`,keywords:[`downloader`],homepage:`https://azot.mov`,author:`Vitaly Gashkov <vitalygashkov@vk.com>`,repository:{type:`git`,url:`https://github.com/azot-labs/azot.git`},funding:[{type:`individual`,url:`https://t.me/tribute/app?startapp=dqW2`}],files:[`out`],os:[`darwin`,`linux`,`win32`],main:`./out/main.js`,scripts:{start:`tsx --env-file-if-exists .env.local ./src/main/cli.ts`,preview:`electron-vite preview --config vite.desktop.config.mjs`,dev:`pnpm run bundle:extensions && electron-vite dev --config vite.desktop.config.mjs --watch`,cli:`pnpm run bundle:extensions && bun run ./src/main/cli.ts --env-file .env`,test:`vitest`,coverage:`vitest run --coverage`,"prepare:runtime-deps":`pnpm -C ../../packages/api build && pnpm -C ../../packages/molnia build`,"bundle:extensions":`node ./scripts/bundle-extensions.mjs`,"bundle:cli":`pnpm run bundle:extensions && node ./scripts/bundle-cli.mjs`,bundle:`pnpm run prepare:runtime-deps && pnpm run bundle:extensions && electron-vite build --config vite.cli.config.mjs && electron-vite build --config vite.desktop.config.mjs`,"build:cli":`pnpm run prepare:runtime-deps && pnpm run bundle:cli && bun build --compile ./out/cli.mjs --minify --outfile ./release/azot`,build:`pnpm run bundle && electron-builder build --config electron-builder.config.js`,"build:mac":`pnpm run bundle && electron-builder build --mac --arm64 --config electron-builder.config.js`,"build:mac:intel":`pnpm run bundle && electron-builder build --mac --x64 --config electron-builder.config.js`,"build:win":`pnpm run build:winconsole && pnpm run bundle && electron-builder build --win --config electron-builder.config.js`,"build:winconsole":`node ./scripts/build-winconsole.mjs`,"build:linux":`pnpm run bundle && electron-builder build --linux --config electron-builder.config.js`,"publish:desktop":`pnpm run bundle && electron-builder build --publish always --config electron-builder.config.js`,"sync:native-optionals":`node ./scripts/sync-native-optionals.mjs`,"check:native-optionals":`node ./scripts/sync-native-optionals.mjs --check`,typecheck:`pnpm run typecheck:node && pnpm run typecheck:web`,"typecheck:node":`tsc --noEmit -p tsconfig.node.json --composite false`,"typecheck:web":`vue-tsc --noEmit -p tsconfig.web.json --composite false`,lint:`../../node_modules/.bin/oxlint -c ../../.oxlintrc.json .`,"lint:fix":`../../node_modules/.bin/oxlint -c ../../.oxlintrc.json --fix .`,fmt:`../../node_modules/.bin/oxfmt -c ../../.oxfmtrc.json .`,"fmt:check":`../../node_modules/.bin/oxfmt -c ../../.oxfmtrc.json --check .`},dependencies:{"@electron-toolkit/preload":`^3.0.2`,"@electron-toolkit/utils":`^4.0.0`,"@gitbeaker/rest":`^43.8.0`,"@inquirer/prompts":`^8.3.0`,"@logtape/file":`^2.0.2`,"@logtape/logtape":`^2.0.2`,"@logtape/pretty":`^2.0.2`,"@tanstack/query-core":`^5.90.20`,"@tribute-tg/better-auth":`^2.1.9`,azot:`workspace:*`,"better-auth":`^1.4.19`,bytenode:`^1.5.7`,conf:`^15.1.0`,cookie:`^1.1.1`,"cross-spawn":`^7.0.6`,dasha:`4.0.0-alpha.12`,"electron-updater":`^6.8.3`,impit:`^0.11.0`,ky:`^1.14.3`,mediabunny:`^1.38.1`,metavm:`^1.4.5`,molnia:`workspace:*`,nanospinner:`^1.2.2`,okova:`^0.10.5`,open:`^11.0.0`,"p-queue":`^9.1.0`,picocolors:`^1.1.1`,"posthog-js":`^1.353.1`,semver:`^7.7.4`,"telegram-better-auth":`^0.0.8`,undici:`^7.22.0`,"urlpattern-polyfill":`^10.1.0`,yargs:`^18.0.0`,yauzl:`^3.2.0`,zod:`^4.3.6`},devDependencies:{"@electron-toolkit/tsconfig":`^2.0.0`,"@iconify/vue":`^5.0.0`,"@intlify/unplugin-vue-i18n":`^11.0.7`,"@tailwindcss/vite":`^4.2.1`,"@tanstack/vue-query":`^5.92.9`,"@types/node":`^25.3.0`,"@types/semver":`^7.7.1`,"@types/wicg-file-system-access":`^2023.10.7`,"@types/yargs":`^17.0.35`,"@vee-validate/zod":`^4.15.1`,"@vitejs/plugin-vue":`^6.0.4`,"@vueuse/core":`^14.2.1`,"class-variance-authority":`^0.7.1`,clsx:`^2.1.1`,dotenv:`^17.3.1`,electron:`41.0.2`,"electron-builder":`^26.8.1`,"electron-vite":`^5.0.0`,esbuild:`^0.27.3`,execa:`^9.6.1`,"lucide-vue-next":`^0.575.0`,"node-gyp":`^12.2.0`,"non.geist":`^1.0.4`,pinia:`^3.0.4`,postcss:`^8.5.6`,"reka-ui":`^2.8.2`,rolldown:`^1.0.0-rc.5`,sass:`^1.97.3`,"tailwind-merge":`^3.5.0`,tailwindcss:`^4.2.1`,"tailwindcss-animate":`^1.0.7`,tsdown:`^0.20.3`,tsx:`^4.21.0`,typescript:`^5.9.3`,"vee-validate":`^4.15.1`,vite:`^7.3.1`,"vite-plugin-static-copy":`^3.1.2`,vitest:`^4.0.18`,vue:`^3.5.29`,"vue-i18n":`^11.2.8`,"vue-sonner":`^2.0.9`,"vue-tsc":`^3.2.5`},peerDependencies:{vitest:`>=4.0.0`},optionalDependencies:{"impit-darwin-arm64":`0.11.0`,"impit-darwin-x64":`0.11.0`,"impit-linux-arm64-gnu":`0.11.0`,"impit-linux-arm64-musl":`0.11.0`,"impit-linux-x64-gnu":`0.11.0`,"impit-linux-x64-musl":`0.11.0`,"impit-win32-arm64-msvc":`0.11.0`,"impit-win32-x64-msvc":`0.11.0`},engines:{node:`>=24.10`},packageManager:`pnpm@10.28.2`,productName:xe,readmeFilename:`README.md`};`pkg`in process&&process.pkg,process.versions.electron,`${C}${de}${ue}${pe}`,`${C}`,be.split(`/`)[0]?.split(`-`)[0]?.replace(`@`,``);const T=xe,Se={darwin:`macOS`,win32:`Windows`,linux:`Linux`}[process.platform],E=e=>{let t=typeof e==`string`?e:e[Se];return n(t)||r(t,{recursive:!0}),t},D=f(),Ce=p(),O=E({Windows:process.env.APPDATA||l(D,`AppData`,`Roaming`),macOS:l(D,`Library`,`Application Support`),Linux:process.env.XDG_DATA_HOME||l(D,`.local`,`share`)}),k=E({Windows:process.env.APPDATA||l(D,`AppData`,`Roaming`),macOS:l(D,`Library`,`Application Support`),Linux:process.env.XDG_CONFIG_HOME||l(D,`.config`)});E({Windows:process.env.LOCALAPPDATA||l(D,`AppData`,`Local`),macOS:l(D,`Library`,`Caches`),Linux:process.env.XDG_CACHE_HOME||l(D,`.cache`)}),E({Windows:l(D,`Downloads`),macOS:l(D,`Downloads`),Linux:process.env.XDG_DOWNLOAD_DIR||l(D,`Downloads`)});const we=E({Windows:l(O,T),macOS:l(O,T),Linux:l(O,T.toLowerCase())}),Te=E({Windows:l(k,T),macOS:l(k,T),Linux:l(k,T.toLowerCase())}),Ee=E({Windows:l(k,T,`logs`),macOS:l(D,`Library`,`Logs`,T),Linux:l(k,T.toLowerCase(),`logs`)});l(Ce,T.toLowerCase());const A=E(l(we,`extensions`));E(l(A,`installed`)),E(l(A,`work`)),l(A,`index.json`),l(Te,`settings.json`);const De=process.argv.includes(`-d`)||process.argv.includes(`--debug`)||process.env.NODE_ENV_ELECTRON_VITE===`development`||!!process.env.ELECTRON_CLI_ARGS;y({sinks:{console:se(ae({formatter:le({timestamp:`time`,messageColor:null,messageStyle:null,levelStyle:null,icons:!1,colors:!0,level:`FULL`,categoryWidth:0,categoryStyle:null,categoryTruncate:`end`,wordWrap:!0})}),De?`debug`:`info`),file:ce(l(Ee,`Azot_${new Date().toISOString().split(`.`)[0].replace(`T`,`_`).replaceAll(`-`,``).replaceAll(`:`,``)}.log`),{flushInterval:0})},loggers:[{category:[],lowestLevel:`trace`,sinks:[`console`,`file`]},{category:[`logtape`,`meta`],lowestLevel:`error`,sinks:[`console`]}]});const j=oe([]),Oe=new class e extends x{static requestEventName=`feedback`;static responseEventName=`feedback:response`;#e=Promise.resolve();async ask(t){let n=()=>new Promise(n=>{this.once(e.responseEventName,e=>{n(e)}),this.emit(e.requestEventName,t)}),r=this.#e.then(n,n);return this.#e=r.then(()=>void 0,()=>void 0),r}listen(t){this.addListener(e.requestEventName,async n=>{let r=await t(n);this.emit(e.responseEventName,r)})}},ke=e=>{let t=[`}`,`{`,`%`,`>`,`<`,`^`,`;`,"`",`$`,`"`,`@`,`=`],n=e;for(let e in t)n=n.replaceAll(`/`,`_`).replaceAll(t[e],``);return n},Ae=(e,t,n)=>{let r={},i={};for(let a of n)for(let n of t){let t=new URLPattern(n,a).exec(e);t&&(Object.assign(r,t.pathname.groups),Object.assign(i,t.search.groups))}return{pathname:r,search:i}},je=(e=new Map)=>{let t=(t,n)=>{for(let r of e.keys())for(let i of e.get(r)||[]){let e=n===void 0||isNaN(n),a=t===void 0||isNaN(t),o=!1;if(o=a?r===n:(e?isNaN(r):r===n)&&i===t,o)return!0}return!1},n=(t,n)=>{let r=n||NaN,i=t||NaN;e.has(r)?e.get(r)?.add(i):e.set(r,new Set([i]))},r=()=>Array.from(e.values()).flatMap(e=>Array.from(e)),i=e.size,a=r();return{items:e,has:t,set:n,getMin:()=>Math.min(...a),getMax:()=>Math.max(...a),seasonsCount:i,episodesCount:a.length}};new Intl.DateTimeFormat(`en-US`,{year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}),new Intl.DateTimeFormat(`en-US`,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1});const M=new class e extends x{static requestEventName=`form`;static responseEventName=`form:response`;title;#e=Promise.resolve();constructor(e={}){super(),this.title=e.title,this.listen(async e=>{let{title:n,description:r,fields:a,...o}=e,s={},c=Object.entries(a||o);if(!b.isTTY||process.platform===`win32`){let e=0,a=1,o=!1;if(process.platform===`win32`)try{e=i(`\\\\.\\CONIN$`,`r`),a=i(`\\\\.\\CONOUT$`,`w`),o=!0}catch{}try{for(let[t,{label:i,type:o}]of c){let c=o===`confirm`;s[t]=Pe([n,r,i].filter(Boolean).join(`. `)+(c?` (y/n)`:``)+`: `,void 0,{inputFd:e,outputFd:a})??``}return s}finally{o&&(t(e),t(a))}}b.setEncoding&&b.setEncoding(`utf8`),b.isTTY&&b.setRawMode&&b.setRawMode(!1),b.resume();let l=he({input:b,output:fe,terminal:!0});try{for(let[e,{label:t,type:i}]of c){let a=i===`confirm`,o=[n,r,t].filter(Boolean).join(`. `)+(a?` (y/n)`:``)+`: `;s[e]=await Promise.race([l.question(o),m(Ne,``)])}return s}finally{l.close()}})}async ask(t){let n=()=>new Promise(n=>{this.once(e.responseEventName,e=>{n(e)}),this.emit(e.requestEventName,t)}),r=this.#e.then(n,n);return this.#e=r.then(()=>void 0,()=>void 0),r}listen(t){this.addListener(e.requestEventName,async n=>{let r=await t(n);this.emit(e.responseEventName,r)})}},Me=async(e,t)=>{let n=t?.fields??{answer:{label:e}};return await M.ask({title:t?.title,description:e,fields:n})},Ne=12e4,Pe=(e,t,n)=>{let r=n?.inputFd??0;o(n?.outputFd??1,e||``);let i=Buffer.alloc(1),s=``;for(;;){try{a(r,i,0,1,null)}catch(e){if(e.code===`EOF`)break;throw e}let e=i.toString(`utf-8`);if(e===`
|
|
2
|
-
`||e===`\r`){if(e===`\r`)try{a(r,i,0,1,null),i.toString(`utf-8`)}catch(e){if(e.code===`EOF`)break;throw e}break}s+=e}return s.trim()||t};var N=class extends Error{response;request;options;constructor(e,t,n){let r=`${e.status||e.status===0?e.status:``} ${e.statusText??``}`.trim(),i=r?`status code ${r}`:`an unknown error`;super(`Request failed with ${i}: ${t.method} ${t.url}`),this.name=`HTTPError`,this.response=e,this.request=t,this.options=n}},Fe=class extends Error{name=`NonError`;value;constructor(e){let t=`Non-error value was thrown`;try{typeof e==`string`?t=e:e&&typeof e==`object`&&`message`in e&&typeof e.message==`string`&&(t=e.message)}catch{}super(t),this.value=e}},P=class extends Error{name=`ForceRetryError`;customDelay;code;customRequest;constructor(e){let t=e?.cause?e.cause instanceof Error?e.cause:new Fe(e.cause):void 0;super(e?.code?`Forced retry: ${e.code}`:`Forced retry`,t?{cause:t}:void 0),this.customDelay=e?.delay,this.code=e?.code,this.customRequest=e?.request}};const Ie=(()=>{let e=!1,t=!1,n=typeof globalThis.ReadableStream==`function`,r=typeof globalThis.Request==`function`;if(n&&r)try{t=new globalThis.Request(`https://empty.invalid`,{body:new globalThis.ReadableStream,method:`POST`,get duplex(){return e=!0,`half`}}).headers.has(`Content-Type`)}catch(e){if(e instanceof Error&&e.message===`unsupported BodyInit type`)return!1;throw e}return e&&!t})(),Le=typeof globalThis.AbortController==`function`,Re=typeof globalThis.AbortSignal==`function`&&typeof globalThis.AbortSignal.any==`function`,ze=typeof globalThis.ReadableStream==`function`,Be=typeof globalThis.FormData==`function`,Ve=[`get`,`post`,`put`,`patch`,`head`,`delete`],He={json:`application/json`,text:`text/*`,formData:`multipart/form-data`,arrayBuffer:`*/*`,blob:`*/*`,bytes:`*/*`},F=2147483647,Ue=new TextEncoder().encode(`------WebKitFormBoundaryaxpyiPgbbPti10Rw`).length,I=Symbol(`stop`);var L=class{options;constructor(e){this.options=e}};const We=e=>new L(e),Ge={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},Ke={next:!0},qe={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0},Je=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[n,r]of e)t+=Ue,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${n}"`).length,t+=typeof r==`string`?new TextEncoder().encode(r).length:r.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e==`string`)return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if(`byteLength`in e)return e.byteLength;if(typeof e==`object`&&e)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},R=(e,t,n)=>{let r,i=0;return e.pipeThrough(new TransformStream({transform(e,a){if(a.enqueue(e),r){i+=r.byteLength;let e=t===0?0:i/t;e>=1&&(e=1-2**-52),n?.({percent:e,totalBytes:Math.max(t,i),transferredBytes:i},r)}r=e},flush(){r&&(i+=r.byteLength,n?.({percent:1,totalBytes:Math.max(t,i),transferredBytes:i},r))}}))},Ye=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let n=Math.max(0,Number(e.headers.get(`content-length`))||0);return new Response(R(e.body,n,t),{status:e.status,statusText:e.statusText,headers:e.headers})},Xe=(e,t,n)=>{if(!e.body)return e;let r=Je(n??e.body);return new Request(e,{duplex:`half`,body:R(e.body,r,t)})},z=e=>typeof e==`object`&&!!e,B=(...e)=>{for(let t of e)if((!z(t)||Array.isArray(t))&&t!==void 0)throw TypeError("The `options` argument must be an object");return U({},...e)},V=(e={},t={})=>{let n=new globalThis.Headers(e),r=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[e,t]of i.entries())r&&t===`undefined`||t===void 0?n.delete(e):n.set(e,t);return n};function H(e,t,n){return Object.hasOwn(t,n)&&t[n]===void 0?[]:U(e[n]??[],t[n]??[])}const Ze=(e={},t={})=>({beforeRequest:H(e,t,`beforeRequest`),beforeRetry:H(e,t,`beforeRetry`),afterResponse:H(e,t,`afterResponse`),beforeError:H(e,t,`beforeError`)}),Qe=(e,t)=>{let n=new URLSearchParams;for(let r of[e,t])if(r!==void 0)if(r instanceof URLSearchParams)for(let[e,t]of r.entries())n.append(e,t);else if(Array.isArray(r))for(let e of r){if(!Array.isArray(e)||e.length!==2)throw TypeError(`Array search parameters must be provided in [[key, value], ...] format`);n.append(String(e[0]),String(e[1]))}else if(z(r))for(let[e,t]of Object.entries(r))t!==void 0&&n.append(e,String(t));else{let e=new URLSearchParams(r);for(let[t,r]of e.entries())n.append(t,r)}return n},U=(...e)=>{let t={},n={},r={},i,a=[];for(let o of e)if(Array.isArray(o))Array.isArray(t)||(t=[]),t=[...t,...o];else if(z(o)){for(let[e,n]of Object.entries(o)){if(e===`signal`&&n instanceof globalThis.AbortSignal){a.push(n);continue}if(e===`context`){if(n!=null&&(!z(n)||Array.isArray(n)))throw TypeError("The `context` option must be an object");t={...t,context:n==null?{}:{...t.context,...n}};continue}if(e===`searchParams`){i=n==null?void 0:i===void 0?n:Qe(i,n);continue}z(n)&&e in t&&(n=U(t[e],n)),t={...t,[e]:n}}z(o.hooks)&&(r=Ze(r,o.hooks),t.hooks=r),z(o.headers)&&(n=V(n,o.headers),t.headers=n)}return i!==void 0&&(t.searchParams=i),a.length>0&&(a.length===1?t.signal=a[0]:Re?t.signal=AbortSignal.any(a):t.signal=a.at(-1)),t},$e=e=>Ve.includes(e)?e.toUpperCase():e,et={limit:2,methods:[`get`,`put`,`head`,`delete`,`options`,`trace`],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:1/0,backoffLimit:1/0,delay:e=>.3*2**(e-1)*1e3,jitter:void 0,retryOnTimeout:!1},tt=(e={})=>{if(typeof e==`number`)return{...et,limit:e};if(e.methods&&!Array.isArray(e.methods))throw Error(`retry.methods must be an array`);if(e.methods&&=e.methods.map(e=>e.toLowerCase()),e.statusCodes&&!Array.isArray(e.statusCodes))throw Error(`retry.statusCodes must be an array`);let t=Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0));return{...et,...t}};var W=class extends Error{request;constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.name=`TimeoutError`,this.request=e}};async function nt(e,t,n,r){return new Promise((i,a)=>{let o=setTimeout(()=>{n&&n.abort(),a(new W(e))},r.timeout);r.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(o)})})}async function rt(e,{signal:t}){return new Promise((n,r)=>{t&&(t.throwIfAborted(),t.addEventListener(`abort`,i,{once:!0}));function i(){clearTimeout(a),r(t.reason)}let a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e)})}const it=(e,t)=>{let n={};for(let r in t)Object.hasOwn(t,r)&&!(r in qe)&&!(r in Ge)&&(!(r in e)||r in Ke)&&(n[r]=t[r]);return n},at=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e==`object`?Object.keys(e).length>0:typeof e==`string`?e.trim().length>0:!!e;function ot(e){return e instanceof N||e?.name===N.name}function st(e){return e instanceof W||e?.name===W.name}var ct=class e{static create(t,n){let r=new e(t,n),i=r.#p(async()=>{if(typeof r.#i.timeout==`number`&&r.#i.timeout>2147483647)throw RangeError(`The \`timeout\` option cannot be greater than ${F}`);await Promise.resolve();let e=await r.#m();for(let t of r.#i.hooks.afterResponse){let n=r.#u(e.clone()),i;try{i=await t(r.request,r.#h(),n,{retryCount:r.#n})}catch(t){throw r.#f(n),r.#f(e),t}if(i instanceof L)throw r.#f(n),r.#f(e),new P(i.options);let a=i instanceof globalThis.Response?i:e;n!==a&&r.#f(n),e!==a&&r.#f(e),e=a}if(r.#u(e),!e.ok&&(typeof r.#i.throwHttpErrors==`function`?r.#i.throwHttpErrors(e.status):r.#i.throwHttpErrors)){let t=new N(e,r.request,r.#h());for(let e of r.#i.hooks.beforeError)t=await e(t,{retryCount:r.#n});throw t}if(r.#i.onDownloadProgress){if(typeof r.#i.onDownloadProgress!=`function`)throw TypeError("The `onDownloadProgress` option must be a function");if(!ze)throw Error("Streams are not supported in your environment. `ReadableStream` is missing.");let t=e.clone();return r.#f(e),Ye(t,r.#i.onDownloadProgress)}return e}).finally(()=>{let e=r.#a;r.#d(e?.body??void 0),r.#d(r.request.body??void 0)});for(let[e,t]of Object.entries(He))e===`bytes`&&typeof globalThis.Response?.prototype?.bytes!=`function`||(i[e]=async()=>{r.request.headers.set(`accept`,r.request.headers.get(`accept`)||t);let a=await i;if(e===`json`){if(a.status===204)return``;let e=await a.text();return e===``?``:n.parseJson?n.parseJson(e):JSON.parse(e)}return a[e]()});return i}static#e(e){return e&&typeof e==`object`&&!Array.isArray(e)&&!(e instanceof URLSearchParams)?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):e}request;#t;#n=0;#r;#i;#a;#o;#s;constructor(t,n={}){if(this.#r=t,this.#i={...n,headers:V(this.#r.headers,n.headers),hooks:Ze({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:$e(n.method??this.#r.method??`GET`),prefixUrl:String(n.prefixUrl||``),retry:tt(n.retry),throwHttpErrors:n.throwHttpErrors??!0,timeout:n.timeout??1e4,fetch:n.fetch??globalThis.fetch.bind(globalThis),context:n.context??{}},typeof this.#r!=`string`&&!(this.#r instanceof URL||this.#r instanceof globalThis.Request))throw TypeError("`input` must be a string, URL, or Request");if(this.#i.prefixUrl&&typeof this.#r==`string`){if(this.#r.startsWith(`/`))throw Error("`input` must not begin with a slash when using `prefixUrl`");this.#i.prefixUrl.endsWith(`/`)||(this.#i.prefixUrl+=`/`),this.#r=this.#i.prefixUrl+this.#r}Le&&Re&&(this.#o=this.#i.signal??this.#r.signal,this.#t=new globalThis.AbortController,this.#i.signal=this.#o?AbortSignal.any([this.#o,this.#t.signal]):this.#t.signal),Ie&&(this.#i.duplex=`half`),this.#i.json!==void 0&&(this.#i.body=this.#i.stringifyJson?.(this.#i.json)??JSON.stringify(this.#i.json),this.#i.headers.set(`content-type`,this.#i.headers.get(`content-type`)??`application/json`));let r=n.headers&&new globalThis.Headers(n.headers).has(`content-type`);if(this.#r instanceof globalThis.Request&&(Be&&this.#i.body instanceof globalThis.FormData||this.#i.body instanceof URLSearchParams)&&!r&&this.#i.headers.delete(`content-type`),this.request=new globalThis.Request(this.#r,this.#i),at(this.#i.searchParams)){let t=`?`+(typeof this.#i.searchParams==`string`?this.#i.searchParams.replace(/^\?/,``):new URLSearchParams(e.#e(this.#i.searchParams)).toString()),n=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,t);this.request=new globalThis.Request(n,this.#i)}if(this.#i.onUploadProgress){if(typeof this.#i.onUploadProgress!=`function`)throw TypeError("The `onUploadProgress` option must be a function");if(!Ie)throw Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request=this.#_(this.request,this.#i.body??void 0)}}#c(){let e=this.#i.retry.delay(this.#n),t=e;this.#i.retry.jitter===!0?t=Math.random()*e:typeof this.#i.retry.jitter==`function`&&(t=this.#i.retry.jitter(e),(!Number.isFinite(t)||t<0)&&(t=e));let n=this.#i.retry.backoffLimit??1/0;return Math.min(n,t)}async#l(e){if(this.#n++,this.#n>this.#i.retry.limit)throw e;let t=e instanceof Error?e:new Fe(e);if(t instanceof P)return t.customDelay??this.#c();if(!this.#i.retry.methods.includes(this.request.method.toLowerCase()))throw e;if(this.#i.retry.shouldRetry!==void 0){let n=await this.#i.retry.shouldRetry({error:t,retryCount:this.#n});if(n===!1)throw e;if(n===!0)return this.#c()}if(st(e)&&!this.#i.retry.retryOnTimeout)throw e;if(ot(e)){if(!this.#i.retry.statusCodes.includes(e.response.status))throw e;let t=e.response.headers.get(`Retry-After`)??e.response.headers.get(`RateLimit-Reset`)??e.response.headers.get(`X-RateLimit-Retry-After`)??e.response.headers.get(`X-RateLimit-Reset`)??e.response.headers.get(`X-Rate-Limit-Reset`);if(t&&this.#i.retry.afterStatusCodes.includes(e.response.status)){let e=Number(t)*1e3;Number.isNaN(e)?e=Date.parse(t)-Date.now():e>=Date.parse(`2024-01-01`)&&(e-=Date.now());let n=this.#i.retry.maxRetryAfter??e;return e<n?e:n}if(e.response.status===413)throw e}return this.#c()}#u(e){return this.#i.parseJson&&(e.json=async()=>this.#i.parseJson(await e.text())),e}#d(e){e&&e.cancel().catch(()=>void 0)}#f(e){this.#d(e.body??void 0)}async#p(e){try{return await e()}catch(t){let n=Math.min(await this.#l(t),F);if(this.#n<1)throw t;if(await rt(n,this.#o?{signal:this.#o}:{}),t instanceof P&&t.customRequest){let e=this.#i.signal?new globalThis.Request(t.customRequest,{signal:this.#i.signal}):new globalThis.Request(t.customRequest);this.#g(e)}for(let e of this.#i.hooks.beforeRetry){let n=await e({request:this.request,options:this.#h(),error:t,retryCount:this.#n});if(n instanceof globalThis.Request){this.#g(n);break}if(n instanceof globalThis.Response)return n;if(n===I)return}return this.#p(e)}}async#m(){this.#t?.signal.aborted&&(this.#t=new globalThis.AbortController,this.#i.signal=this.#o?AbortSignal.any([this.#o,this.#t.signal]):this.#t.signal,this.request=new globalThis.Request(this.request,{signal:this.#i.signal}));for(let e of this.#i.hooks.beforeRequest){let t=await e(this.request,this.#h(),{retryCount:this.#n});if(t instanceof Response)return t;if(t instanceof globalThis.Request){this.#g(t);break}}let e=it(this.request,this.#i);return this.#a=this.request,this.request=this.#a.clone(),this.#i.timeout===!1?this.#i.fetch(this.#a,e):nt(this.#a,e,this.#t,this.#i)}#h(){if(!this.#s){let{hooks:e,...t}=this.#i;this.#s=Object.freeze(t)}return this.#s}#g(e){this.#s=void 0,this.request=this.#_(e)}#_(e,t){return!this.#i.onUploadProgress||!e.body?e:Xe(e,this.#i.onUploadProgress,t??this.#i.body??void 0)}};
|
|
3
|
-
/*! MIT License © Sindre Sorhus */
|
|
4
|
-
const G=e=>{let t=(t,n)=>ct.create(t,B(e,n));for(let n of Ve)t[n]=(t,r)=>ct.create(t,B(e,r,{method:n}));return t.create=e=>G(B(e)),t.extend=t=>(typeof t==`function`&&(t=t(e??{})),G(B(e,t))),t.stop=I,t.retry=We,t},lt=G();var ut=e((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.stringifySetCookie=s,e.serialize=s,e.parseSetCookie=c,e.stringifySetCookie=s,e.serialize=s;let t=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,n=/^[\u0021-\u003A\u003C-\u007E]*$/,r=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,i=/^[\u0020-\u003A\u003D-\u007E]*$/,a=/^-?\d+$/,o=Object.prototype.toString;function s(e,a,o){let s=typeof e==`object`?e:{...o,name:e,value:String(a)},c=(typeof a==`object`?a:o)?.encode||encodeURIComponent;if(!t.test(s.name))throw TypeError(`argument name is invalid: ${s.name}`);let l=s.value?c(s.value):``;if(!n.test(l))throw TypeError(`argument val is invalid: ${s.value}`);let u=s.name+`=`+l;if(s.maxAge!==void 0){if(!Number.isInteger(s.maxAge))throw TypeError(`option maxAge is invalid: ${s.maxAge}`);u+=`; Max-Age=`+s.maxAge}if(s.domain){if(!r.test(s.domain))throw TypeError(`option domain is invalid: ${s.domain}`);u+=`; Domain=`+s.domain}if(s.path){if(!i.test(s.path))throw TypeError(`option path is invalid: ${s.path}`);u+=`; Path=`+s.path}if(s.expires){if(!p(s.expires)||!Number.isFinite(s.expires.valueOf()))throw TypeError(`option expires is invalid: ${s.expires}`);u+=`; Expires=`+s.expires.toUTCString()}if(s.httpOnly&&(u+=`; HttpOnly`),s.secure&&(u+=`; Secure`),s.partitioned&&(u+=`; Partitioned`),s.priority)switch(typeof s.priority==`string`?s.priority.toLowerCase():void 0){case`low`:u+=`; Priority=Low`;break;case`medium`:u+=`; Priority=Medium`;break;case`high`:u+=`; Priority=High`;break;default:throw TypeError(`option priority is invalid: ${s.priority}`)}if(s.sameSite)switch(typeof s.sameSite==`string`?s.sameSite.toLowerCase():s.sameSite){case!0:case`strict`:u+=`; SameSite=Strict`;break;case`lax`:u+=`; SameSite=Lax`;break;case`none`:u+=`; SameSite=None`;break;default:throw TypeError(`option sameSite is invalid: ${s.sameSite}`)}return u}function c(e,t){let n=t?.decode||f,r=e.length,i=l(e,0,r),o=u(e,0,i),s=o===-1?{name:``,value:n(d(e,0,i))}:{name:d(e,0,o),value:n(d(e,o+1,i))},c=i+1;for(;c<r;){let t=l(e,c,r),n=u(e,c,t),i=n===-1?d(e,c,t):d(e,c,n),o=n===-1?void 0:d(e,n+1,t);switch(i.toLowerCase()){case`httponly`:s.httpOnly=!0;break;case`secure`:s.secure=!0;break;case`partitioned`:s.partitioned=!0;break;case`domain`:s.domain=o;break;case`path`:s.path=o;break;case`max-age`:o&&a.test(o)&&(s.maxAge=Number(o));break;case`expires`:if(!o)break;let e=new Date(o);Number.isFinite(e.valueOf())&&(s.expires=e);break;case`priority`:if(!o)break;let t=o.toLowerCase();(t===`low`||t===`medium`||t===`high`)&&(s.priority=t);break;case`samesite`:if(!o)break;let n=o.toLowerCase();(n===`lax`||n===`strict`||n===`none`)&&(s.sameSite=n);break}c=t+1}return s}function l(e,t,n){let r=e.indexOf(`;`,t);return r===-1?n:r}function u(e,t,n){let r=e.indexOf(`=`,t);return r<n?r:-1}function d(e,t,n){let r=t,i=n;do{let t=e.charCodeAt(r);if(t!==32&&t!==9)break}while(++r<i);for(;i>r;){let t=e.charCodeAt(i-1);if(t!==32&&t!==9)break;i--}return e.slice(r,i)}function f(e){if(e.indexOf(`%`)===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function p(e){return o.call(e)===`[object Date]`}}))();const K=e=>{let t=[];for(let n of e)try{let e=(0,ut.parseSetCookie)(n),r={...e,expires:e.expires instanceof Date?e.expires.getTime():e.expires,sameSite:typeof e.sameSite==`boolean`?`strict`:e.sameSite};t.push(r)}catch(e){j.debug(e)}return t},dt=async e=>{let t=await g(e,`utf8`).catch(()=>``);if(!t)return[];let n=t.split(d).flatMap(e=>e.split(`
|
|
5
|
-
`)).filter(e=>!!e.trim()&&!e.startsWith(`# `)).map(e=>e.split(` `)),r=[];for(let e of n){let[t,n,i,a,o,s,c]=e;r.push({name:s,value:c,expires:Number(o),maxAge:void 0,domain:t.replace(`#HttpOnly_`,``),path:i,secure:a===`TRUE`,httpOnly:void 0,sameSite:void 0})}return r},ft=(e,t)=>e.name===t.name&&e.domain===t.domain&&e.path===t.path&&e.partitioned===t.partitioned,pt=(e,t)=>{let n=[...e];for(let e of t){let t=n.findIndex(t=>ft(t,e));t>=0?n[t]=e:n.push(e)}return n},mt=(e,t)=>{if(typeof e!=`string`)return e;if(t===void 0)throw TypeError(`CookieStore.set(name, value) requires a value argument`);return{name:e,value:t}};var ht=class{#e={};#t;#n;#r=!1;static parse(e){return K(e)}constructor({storagePath:e}={}){this.#n=e,this.#t=[]}async import(e,{removeSource:t=!0}={}){if(await this.#i(),!(await v(e).catch(()=>null))?.isFile())return 0;j.debug(`Importing cookies from ${e}`);let n=await dt(e);this.#t=pt(this.#t,n);try{await this.#a(),t&&await _(e,{force:!0})}catch(e){throw e}return n.length}async#i(){if(!(!this.#n||this.#r)){if((await v(this.#n).catch(()=>null))?.isFile()){let e=await g(this.#n,`utf8`);this.#e=e?JSON.parse(e):{},this.#t=`cookies`in this.#e?this.#e.cookies:[]}this.#r=!0}}async#a(){if(!this.#n)return;let e=JSON.stringify({...this.#e,cookies:this.#t},null,2);await ie(this.#n,e,`utf8`)}async get(e){await this.#i();let t=typeof e==`string`?e:e.name;return this.#t.find(e=>e.name===t)??null}async getAll(e){if(await this.#i(),!e)return this.#t;let t=typeof e==`string`?e:e.name;return this.#t.filter(e=>e.name===t)??null}async set(e,t){await this.#i();let n=mt(e,t);this.#t=pt(this.#t,[n]),await this.#a()}async delete(e){if(await this.#i(),!e)this.#t=[];else{let t=typeof e==`string`?e:e.name;this.#t=this.#t.filter(e=>e.name!==t)}await this.#a()}toString(){return this.#t.map(e=>`${e.name}=${e.value}`).join(`; `)}};const gt=lt.default??lt,_t=e=>e?e instanceof Headers?e.has(`User-Agent`):typeof e==`object`&&e?`User-Agent`in e||`user-agent`in e:!1:!1,vt=e=>e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e);var yt=class{cookieStore;headers;#e;#t;constructor(e={}){this.headers=new Headers,this.configure(e)}configure({maxRetries:e=3,proxyUrl:t,allowH2:n=!0,cookieStore:r,fetch:i}={}){this.cookieStore=r??this.cookieStore??new ht;let a=t?new ve({uri:t,allowH2:n}):new _e({allowH2:n}),o={retry:e};this.#e=gt.create({dispatcher:a,proxy:t,fetch:i,...o});let s=new ge({browser:`chrome`,proxyUrl:t,ignoreTlsErrors:!0,followRedirects:!1});this.#t=gt.create({fetch:this.#r.bind(this,i??s.fetch.bind(s)),...o})}async fetch(e,t={}){let n=await this.#n(e,t?.headers),r=(_t(t?.headers)?this.#e:this.#t)[t?.method?.toLowerCase()??`get`],i=await r(e,{...t,headers:n}),a=i.headers.getSetCookie();return a&&await this.setCookies(a),i}async#n(e,t){let n=this.appendHeaders(t),r=await this.cookieStore.getAll(),i=r.filter(t=>!t.domain||vt(e).hostname.includes(t.domain));for(let e of r)i.find(t=>t.name===e.name)||e.domain||i.push(e);let a=i.map(e=>`${e.name}=${e.value}`).join(`; `);return a?(n.has(`cookie`)?n.get(`cookie`)||n.delete(`cookie`):n.set(`cookie`,a),n):(n.get(`cookie`)||n.delete(`cookie`),n)}async setCookies(e){let t=[];if(typeof e==`string`){let[n]=K([e]);n&&t.push(n)}else if(Array.isArray(e)&&typeof e.at(0)==`string`){let n=K(e);t.push(...n)}else Array.isArray(e)&&typeof e[0]!=`string`&&t.push(...e);if(!(!t||!t?.length))for(let e of t)await this.cookieStore.set(e)}appendHeaders(e){let t=new Headers(this.headers),n=e instanceof Headers?e.entries():Object.entries(e??{});for(let[e,r]of n)t.set(e,r);return t}setHeader(e,t){this.headers.set(e,t)}removeHeader(e){this.headers.delete(e)}async#r(e,t,n={}){let r=0,i=t instanceof Request?new URL(t.url):t,a=await this.#o(t,n)??{};for(a.redirect=`manual`;;){let t=await e(i,a),n=t.headers.getSetCookie();if(n.length&&await this.setCookies(n),!this.#a(t.status))return t;let o=t.headers.get(`location`);if(!o)return t;if(r>=20)throw Error(`Maximum redirect limit (20) exceeded`);r+=1,i=new URL(o,vt(i)),a=this.#i(a,t.status)??{},a.headers=await this.#n(i,a.headers)}}#i(e={},t){let n=e.method?.toUpperCase()??`GET`;if(t===303||(t===301||t===302)&&n===`POST`){let t=new Headers(e.headers);return t.delete(`content-length`),t.delete(`content-type`),{...e,method:`GET`,body:void 0,headers:t,redirect:`manual`}}return{...e,redirect:`manual`}}#a(e){return[301,302,303,307,308].includes(e)}async#o(e,t={}){if(!(e instanceof Request))return{...t};let n=new Headers(e.headers);for(let[e,r]of new Headers(t.headers).entries())n.set(e,r);let r=(t.method??e.method).toUpperCase(),i={...t,method:r,headers:n};return t.body!==void 0||r===`GET`||r===`HEAD`?(i.body=t.body,i):(i.body=await e.clone().arrayBuffer(),i)}};new yt;const{COMMON_CONTEXT:bt}=ye,xt=(e,t=`Eval`,n)=>{try{return ye.createScript(t,e,n)}catch(t){return console.debug(t),console.debug(e),console.error(`Syntax Error: ${t.message}`),null}},St=(e,t=1)=>{if(Array.isArray(e)||typeof e==`string`){let n=[];for(let r=1;r<=t;r++)n.push(e[Math.floor(Math.random()*e.length)]);return n}else return[]},Ct=e=>new(`default`in S?S.default:S)(e);var wt=class{#e;constructor(e){this.#e=Ct({cwd:c(e),configName:s(e,`.json`)})}get length(){return Object.keys(this.#e.store).length}clear(){this.#e.clear()}getItem(e){return this.#e.get(e)??null}key(e){return Object.keys(this.#e.store).at(e)??null}removeItem(e){this.#e.delete(e)}setItem(e,t){this.#e.set(e,t)}};const Tt=new me,q=e=>{if(!e||typeof e!=`object`)return!1;let t=`name`in e?String(e.name):``;return t===`ExitPromptError`||t===`AbortPromptError`},Et=e=>e&&e[0].toUpperCase()+e.slice(1),J=(e,t=!1)=>{if(typeof e==`boolean`)return e;if(typeof e!=`string`)return t;let n=e.trim().toLowerCase();return[`1`,`true`,`yes`,`y`,`on`].includes(n)?!0:[`0`,`false`,`no`,`n`,`off`].includes(n)?!1:t},Y=(e,t=0)=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e!=`string`)return t;let n=Number(e);return Number.isFinite(n)?n:t},Dt=e=>{switch(e.type){case`checkbox`:return J(e.defaultValue,!1);case`number`:return Y(e.defaultValue,0);default:return e.defaultValue??``}},Ot=(e,t)=>{switch(e.type){case`checkbox`:return J(t,J(e.defaultValue,!1));case`number`:return Y(t,Y(e.defaultValue,0));default:return typeof t==`string`?t:t==null?e.defaultValue??``:String(t)}},kt=e=>{let t=Object.entries(e).map(([e,t])=>[e,Dt(t)]);return Object.fromEntries(t)},X=(e,t)=>{let n=Object.entries(e).map(([e,n])=>[e,Ot(n,t[e])]);return Object.fromEntries(n)},At=e=>!!e&&typeof e==`object`&&`fields`in e,jt=e=>{switch(e){case`password`:case`number`:case`checkbox`:return e;default:return`text`}},Mt=e=>{let t=Object.fromEntries(Object.entries(e.fields).map(([e,t])=>[e,{type:jt(t.type),title:t.label||e,description:t.description,placeholder:t.placeholder,defaultValue:t.defaultValue??t.value,required:t.required,autoFocus:t.autoFocus}]));return{message:e.description??``,options:{title:e.title,form:t,primaryAction:e.actions?.primaryAction,secondaryAction:e.actions?.secondaryAction}}},Z=async e=>{e?.onAction&&await e.onAction()},Nt=async e=>{{let{default:t}=await import(`./open-rfKrXH0-.mjs`);await t(e);return}let{shell:t}=await import(`electron`);await t.openExternal(e)},Pt=(e,t,n)=>{let r=typeof e==`string`?e:e?.toString();return r?.trim()&&Nt(r).catch(e=>{j.error(`Failed to open URL: ${r}`),j.debug(e instanceof Error?e.message:String(e))}),null},Q=async(e,t)=>{if(!t.length)return`dismiss`;try{return await h({message:e,loop:!1,choices:t.map(e=>({name:e.action.title,value:e.kind}))})}catch(e){if(q(e))return`dismiss`;throw e}},$=()=>{switch(u.type()){case`Darwin`:return`macOS`;case`Windows_NT`:return`Windows`;default:return`Linux`}};Object.defineProperties(Uint8Array.prototype,{toBase64:{value:function(){return Buffer.from(this).toString(`base64`)},writable:!0,configurable:!0},toHex:{value:function(){return Buffer.from(this).toString(`hex`)},writable:!0,configurable:!0}}),Object.defineProperties(Uint8Array,{fromBase64:{value:function(e){return new Uint8Array(Buffer.from(e,`base64`))},writable:!0,configurable:!0},fromHex:{value:function(e){return new Uint8Array(Buffer.from(e,`hex`))},writable:!0,configurable:!0}});const Ft=new Map([[24,[`Sequoia`,`15`]],[23,[`Sonoma`,`14`]],[22,[`Ventura`,`13`]],[21,[`Monterey`,`12`]],[20,[`Big Sur`,`11`]],[19,[`Catalina`,`10.15`]],[18,[`Mojave`,`10.14`]],[17,[`High Sierra`,`10.13`]],[16,[`Sierra`,`10.12`]],[15,[`El Capitan`,`10.11`]],[14,[`Yosemite`,`10.10`]],[13,[`Mavericks`,`10.9`]],[12,[`Mountain Lion`,`10.8`]],[11,[`Lion`,`10.7`]],[10,[`Snow Leopard`,`10.6`]],[9,[`Leopard`,`10.5`]],[8,[`Tiger`,`10.4`]],[7,[`Panther`,`10.3`]],[6,[`Jaguar`,`10.2`]],[5,[`Puma`,`10.1`]]]),It=()=>{let e=Number(u.release().split(`.`)[0]),[t,n]=Ft.get(e)||[`Unknown`,``];return{name:t,version:n}},Lt=()=>{switch($()){case`macOS`:return It().version;case`Windows`:return u.release();case`Linux`:return u.release()}},Rt=()=>{let e=[{brand:`Azot`,version:w.version.split(`.`).slice(0,2).join(`.`)},{brand:`Node.js`,version:process.version.replace(`v`,``).split(`.`).slice(0,1).join(`.`)}];return{mobile:!1,platform:$(),brands:e,getHighEntropyValues:async t=>{let n={mobile:!1,platform:$(),brands:e};return t.includes(`architecture`)&&(n.architecture=u.arch()),t.includes(`platform`)&&(n.platform=$()),t.includes(`platformVersion`)&&(n.platformVersion=Lt()),t.includes(`fullVersionList`)&&(n.fullVersionList=[{brand:`Azot`,version:w.version},{brand:`Node.js`,version:process.version}]),n}}},zt=({name:e=`extension`,dir:t=process.cwd(),title:n}={})=>{let r=E(l(t,e)),i=new wt(l(r,`storage.json`)),a=new ht({storagePath:l(r,`cookies.json`)}),o=new yt({cookieStore:a}),s=(e,t,n)=>e.split(t)[1]?.split(n)[0]?.trim(),c={sanitizeString:ke,execUrlPatterns:Ae,extendEpisodes:je,between:s,getRandomElements:St},u=n?Et(n):void 0,d=e=>e||u,f=async e=>(e.title||=u,await M.ask(e)),p=async(e,t={})=>{let n=d(t.title)??`Azot`,r=[t.primaryAction?{kind:`primary`,action:t.primaryAction}:null,t.secondaryAction?{kind:`secondary`,action:t.secondaryAction}:null].filter(Boolean);{if(!r.length)return j.info(e);let n=await Q(e,r);n===`primary`&&await Z(t.primaryAction),n===`secondary`&&await Z(t.secondaryAction);return}let i=(await Oe.ask({variant:`notify`,title:n,message:e,style:t.style,primaryAction:t.primaryAction?{title:t.primaryAction.title,style:t.primaryAction.style}:void 0,secondaryAction:t.secondaryAction?{title:t.secondaryAction.title,style:t.secondaryAction.style}:void 0})).action??`dismiss`;i===`primary`&&await Z(t.primaryAction),i===`secondary`&&await Z(t.secondaryAction)},h=async(e,t={})=>{let n=d(t.title)??`Azot`,r=!!t.primaryAction||!!t.secondaryAction,i=t.primaryAction??{title:`OK`},a=t.secondaryAction??{title:`Cancel`,style:`cancel`};if(r){let t=await Q(e,[{kind:`primary`,action:i},{kind:`secondary`,action:a}]);return t===`primary`?(await Z(i),!0):(t===`secondary`&&await Z(a),!1)}try{let n=await ee({message:e,default:!0});return n?await Z(t.primaryAction):await Z(t.secondaryAction),n}catch(e){if(q(e))return!1;throw e}let o=await Oe.ask({variant:`confirm`,title:n,message:e,style:t.style,primaryAction:{title:i.title,style:i.style},secondaryAction:{title:a.title,style:a.style}}),s=o.action===`primary`;return s?await Z(i):o.action===`secondary`&&await Z(a),s},g=async(e,t)=>{let n=kt(t.form),r=Object.entries(t.form),i=!!t.primaryAction||!!t.secondaryAction,a=t.primaryAction??{title:`Submit`},o=t.secondaryAction??{title:`Cancel`,style:`cancel`};{let s={};try{for(let[e,t]of r){let n=[t.title||e,t.description].filter(Boolean).join(` - `);if(t.type===`checkbox`){s[e]=await ee({message:n,default:J(t.defaultValue,!1)});continue}if(t.type===`number`){let r=Y(t.defaultValue,NaN);s[e]=await ne({message:n,default:Number.isFinite(r)?r:void 0,validate:e=>(e===void 0||Number.isNaN(e))&&t.required?`This field is required`:!0});continue}if(t.type===`password`){s[e]=await re({message:n,validate:t.required?e=>String(e??``).trim()?!0:`This field is required`:void 0});continue}s[e]=await te({message:n,default:t.defaultValue,validate:t.required?e=>String(e??``).trim()?!0:`This field is required`:void 0})}}catch(e){if(q(e))return n;throw e}if(!i)return X(t.form,s);let c=await Q(e,[{kind:`primary`,action:a},{kind:`secondary`,action:o}]);return c===`primary`?(await Z(a),X(t.form,s)):(c===`secondary`&&await Z(o),n)}let s=Object.fromEntries(r.map(([e,t])=>[e,{type:t.type,label:t.title||e,description:t.description,placeholder:t.placeholder,defaultValue:t.defaultValue,value:t.defaultValue,required:t.required,autoFocus:t.autoFocus}])),c=await f({title:d(t.title),description:e,fields:s,actions:i?{primaryAction:{title:a.title,style:a.style},secondaryAction:{title:o.title,style:o.style}}:void 0}),l=c.__action??`primary`,u={...c};return delete u.__action,l===`primary`?(await Z(t.primaryAction),X(t.form,u)):(l===`secondary`&&await Z(t.secondaryAction),n)},_=async(e,t)=>{if(At(e)){let t=Mt(e);return g(t.message,t.options)}if(!t)throw TypeError(`prompt(message, options) requires a form definition`);return g(e,t)},v={defineExtension:e=>e,version:w.version,sleep:m,sanitizeString:ke,execUrlPatterns:Ae,extendEpisodes:je,between:s,getRandomElements:St,utils:c,notify:p,confirm:h,prompt:_,input:Me,ask:_};class ie{get cookie(){return a.toString()}}let y={fetch:o.fetch.bind(o),Response,Request,Headers,AbortController,AbortSignal,URL,URLSearchParams,URLPattern,open:Pt,Blob,structuredClone,btoa,atob,TextEncoder,TextDecoder,Uint8Array,crypto,console:{log:console.log,info:j.info.bind(j),warn:j.warn.bind(j),error:(...e)=>{let t=String(e[0]??`Unknown error`);Tt.emit(`error`,{message:t}),j.error(t)},trace:j.trace.bind(j),debug:j.debug.bind(j)},Event,EventTarget,localStorage:i,cookieStore:a,document:new ie,eval:e=>xt(e)?.exports,navigator:{appName:`Azot`,appVersion:w.version,platform:process.platform,userAgent:`Azot/${w.version}`,userAgentData:Rt()}};return{http:o,question:M,common:c,Streamyx:v,Azot:v,window:y,...y}};export{zt as t};
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
const e=require(`./chunk-350yNsax.cjs`);let t=require(`node:fs`),n=require(`node:path`);n=e.n(n);let r=require(`node:os`);r=e.n(r);let i=require(`node:timers/promises`),a=require(`@inquirer/prompts`),o=require(`node:fs/promises`);o=e.n(o);let s=require(`@logtape/logtape`),c=require(`@logtape/file`),l=require(`@logtape/pretty`),u=require(`node:process`),d=require(`node:events`);d=e.n(d),require(`picocolors`),require(`urlpattern-polyfill`);let f=require(`node:readline/promises`),p=require(`impit`),m=require(`undici`),h=require(`metavm`);h=e.n(h),require(`node:child_process`),require(`nanospinner`);let g=require(`conf`);g=e.n(g);var _=`@azot/desktop`,v=`5.0.0-alpha.55`,y=`Azot`,b={name:_,version:v,description:`A powerful, extensible app for downloading videos`,keywords:[`downloader`],homepage:`https://azot.mov`,author:`Vitaly Gashkov <vitalygashkov@vk.com>`,repository:{type:`git`,url:`https://github.com/azot-labs/azot.git`},funding:[{type:`individual`,url:`https://t.me/tribute/app?startapp=dqW2`}],files:[`out`],os:[`darwin`,`linux`,`win32`],main:`./out/main.js`,scripts:{start:`tsx --env-file-if-exists .env.local ./src/main/cli.ts`,preview:`electron-vite preview --config vite.desktop.config.mjs`,dev:`pnpm run bundle:extensions && electron-vite dev --config vite.desktop.config.mjs --watch`,cli:`pnpm run bundle:extensions && bun run ./src/main/cli.ts --env-file .env`,test:`vitest`,coverage:`vitest run --coverage`,"prepare:runtime-deps":`pnpm -C ../../packages/api build && pnpm -C ../../packages/molnia build`,"bundle:extensions":`node ./scripts/bundle-extensions.mjs`,"bundle:cli":`pnpm run bundle:extensions && node ./scripts/bundle-cli.mjs`,bundle:`pnpm run prepare:runtime-deps && pnpm run bundle:extensions && electron-vite build --config vite.cli.config.mjs && electron-vite build --config vite.desktop.config.mjs`,"build:cli":`pnpm run prepare:runtime-deps && pnpm run bundle:cli && bun build --compile ./out/cli.mjs --minify --outfile ./release/azot`,build:`pnpm run bundle && electron-builder build --config electron-builder.config.js`,"build:mac":`pnpm run bundle && electron-builder build --mac --arm64 --config electron-builder.config.js`,"build:mac:intel":`pnpm run bundle && electron-builder build --mac --x64 --config electron-builder.config.js`,"build:win":`pnpm run build:winconsole && pnpm run bundle && electron-builder build --win --config electron-builder.config.js`,"build:winconsole":`node ./scripts/build-winconsole.mjs`,"build:linux":`pnpm run bundle && electron-builder build --linux --config electron-builder.config.js`,"publish:desktop":`pnpm run bundle && electron-builder build --publish always --config electron-builder.config.js`,"sync:native-optionals":`node ./scripts/sync-native-optionals.mjs`,"check:native-optionals":`node ./scripts/sync-native-optionals.mjs --check`,typecheck:`pnpm run typecheck:node && pnpm run typecheck:web`,"typecheck:node":`tsc --noEmit -p tsconfig.node.json --composite false`,"typecheck:web":`vue-tsc --noEmit -p tsconfig.web.json --composite false`,lint:`../../node_modules/.bin/oxlint -c ../../.oxlintrc.json .`,"lint:fix":`../../node_modules/.bin/oxlint -c ../../.oxlintrc.json --fix .`,fmt:`../../node_modules/.bin/oxfmt -c ../../.oxfmtrc.json .`,"fmt:check":`../../node_modules/.bin/oxfmt -c ../../.oxfmtrc.json --check .`},dependencies:{"@electron-toolkit/preload":`^3.0.2`,"@electron-toolkit/utils":`^4.0.0`,"@gitbeaker/rest":`^43.8.0`,"@inquirer/prompts":`^8.3.0`,"@logtape/file":`^2.0.2`,"@logtape/logtape":`^2.0.2`,"@logtape/pretty":`^2.0.2`,"@tanstack/query-core":`^5.90.20`,"@tribute-tg/better-auth":`^2.1.9`,azot:`workspace:*`,"better-auth":`^1.4.19`,bytenode:`^1.5.7`,conf:`^15.1.0`,cookie:`^1.1.1`,"cross-spawn":`^7.0.6`,dasha:`4.0.0-alpha.12`,"electron-updater":`^6.8.3`,impit:`^0.11.0`,ky:`^1.14.3`,mediabunny:`^1.38.1`,metavm:`^1.4.5`,molnia:`workspace:*`,nanospinner:`^1.2.2`,okova:`^0.10.5`,open:`^11.0.0`,"p-queue":`^9.1.0`,picocolors:`^1.1.1`,"posthog-js":`^1.353.1`,semver:`^7.7.4`,"telegram-better-auth":`^0.0.8`,undici:`^7.22.0`,"urlpattern-polyfill":`^10.1.0`,yargs:`^18.0.0`,yauzl:`^3.2.0`,zod:`^4.3.6`},devDependencies:{"@electron-toolkit/tsconfig":`^2.0.0`,"@iconify/vue":`^5.0.0`,"@intlify/unplugin-vue-i18n":`^11.0.7`,"@tailwindcss/vite":`^4.2.1`,"@tanstack/vue-query":`^5.92.9`,"@types/node":`^25.3.0`,"@types/semver":`^7.7.1`,"@types/wicg-file-system-access":`^2023.10.7`,"@types/yargs":`^17.0.35`,"@vee-validate/zod":`^4.15.1`,"@vitejs/plugin-vue":`^6.0.4`,"@vueuse/core":`^14.2.1`,"class-variance-authority":`^0.7.1`,clsx:`^2.1.1`,dotenv:`^17.3.1`,electron:`41.0.2`,"electron-builder":`^26.8.1`,"electron-vite":`^5.0.0`,esbuild:`^0.27.3`,execa:`^9.6.1`,"lucide-vue-next":`^0.575.0`,"node-gyp":`^12.2.0`,"non.geist":`^1.0.4`,pinia:`^3.0.4`,postcss:`^8.5.6`,"reka-ui":`^2.8.2`,rolldown:`^1.0.0-rc.5`,sass:`^1.97.3`,"tailwind-merge":`^3.5.0`,tailwindcss:`^4.2.1`,"tailwindcss-animate":`^1.0.7`,tsdown:`^0.20.3`,tsx:`^4.21.0`,typescript:`^5.9.3`,"vee-validate":`^4.15.1`,vite:`^7.3.1`,"vite-plugin-static-copy":`^3.1.2`,vitest:`^4.0.18`,vue:`^3.5.29`,"vue-i18n":`^11.2.8`,"vue-sonner":`^2.0.9`,"vue-tsc":`^3.2.5`},peerDependencies:{vitest:`>=4.0.0`},optionalDependencies:{"impit-darwin-arm64":`0.11.0`,"impit-darwin-x64":`0.11.0`,"impit-linux-arm64-gnu":`0.11.0`,"impit-linux-arm64-musl":`0.11.0`,"impit-linux-x64-gnu":`0.11.0`,"impit-linux-x64-musl":`0.11.0`,"impit-win32-arm64-msvc":`0.11.0`,"impit-win32-x64-msvc":`0.11.0`},engines:{node:`>=24.10`},packageManager:`pnpm@10.28.2`,productName:y,readmeFilename:`README.md`};`pkg`in process&&process.pkg,process.versions.electron,`${v}${u.platform}${u.arch}${u.version}`,`${v}`,_.split(`/`)[0]?.split(`-`)[0]?.replace(`@`,``);const x=y,S={darwin:`macOS`,win32:`Windows`,linux:`Linux`}[process.platform],C=e=>{let n=typeof e==`string`?e:e[S];return(0,t.existsSync)(n)||(0,t.mkdirSync)(n,{recursive:!0}),n},w=(0,r.homedir)(),ee=(0,r.tmpdir)(),T=C({Windows:process.env.APPDATA||(0,n.join)(w,`AppData`,`Roaming`),macOS:(0,n.join)(w,`Library`,`Application Support`),Linux:process.env.XDG_DATA_HOME||(0,n.join)(w,`.local`,`share`)}),E=C({Windows:process.env.APPDATA||(0,n.join)(w,`AppData`,`Roaming`),macOS:(0,n.join)(w,`Library`,`Application Support`),Linux:process.env.XDG_CONFIG_HOME||(0,n.join)(w,`.config`)});C({Windows:process.env.LOCALAPPDATA||(0,n.join)(w,`AppData`,`Local`),macOS:(0,n.join)(w,`Library`,`Caches`),Linux:process.env.XDG_CACHE_HOME||(0,n.join)(w,`.cache`)}),C({Windows:(0,n.join)(w,`Downloads`),macOS:(0,n.join)(w,`Downloads`),Linux:process.env.XDG_DOWNLOAD_DIR||(0,n.join)(w,`Downloads`)});const te=C({Windows:(0,n.join)(T,x),macOS:(0,n.join)(T,x),Linux:(0,n.join)(T,x.toLowerCase())}),ne=C({Windows:(0,n.join)(E,x),macOS:(0,n.join)(E,x),Linux:(0,n.join)(E,x.toLowerCase())}),re=C({Windows:(0,n.join)(E,x,`logs`),macOS:(0,n.join)(w,`Library`,`Logs`,x),Linux:(0,n.join)(E,x.toLowerCase(),`logs`)});(0,n.join)(ee,x.toLowerCase());const D=C((0,n.join)(te,`extensions`));C((0,n.join)(D,`installed`)),C((0,n.join)(D,`work`)),(0,n.join)(D,`index.json`),(0,n.join)(ne,`settings.json`);const ie=process.argv.includes(`-d`)||process.argv.includes(`--debug`)||process.env.NODE_ENV_ELECTRON_VITE===`development`||!!process.env.ELECTRON_CLI_ARGS;(0,s.configureSync)({sinks:{console:(0,s.withFilter)((0,s.getConsoleSink)({formatter:(0,l.getPrettyFormatter)({timestamp:`time`,messageColor:null,messageStyle:null,levelStyle:null,icons:!1,colors:!0,level:`FULL`,categoryWidth:0,categoryStyle:null,categoryTruncate:`end`,wordWrap:!0})}),ie?`debug`:`info`),file:(0,c.getFileSink)((0,n.join)(re,`Azot_${new Date().toISOString().split(`.`)[0].replace(`T`,`_`).replaceAll(`-`,``).replaceAll(`:`,``)}.log`),{flushInterval:0})},loggers:[{category:[],lowestLevel:`trace`,sinks:[`console`,`file`]},{category:[`logtape`,`meta`],lowestLevel:`error`,sinks:[`console`]}]});const O=(0,s.getLogger)([]),k=new class e extends d.EventEmitter{static requestEventName=`feedback`;static responseEventName=`feedback:response`;#e=Promise.resolve();async ask(t){let n=()=>new Promise(n=>{this.once(e.responseEventName,e=>{n(e)}),this.emit(e.requestEventName,t)}),r=this.#e.then(n,n);return this.#e=r.then(()=>void 0,()=>void 0),r}listen(t){this.addListener(e.requestEventName,async n=>{let r=await t(n);this.emit(e.responseEventName,r)})}},ae=e=>{let t=[`}`,`{`,`%`,`>`,`<`,`^`,`;`,"`",`$`,`"`,`@`,`=`],n=e;for(let e in t)n=n.replaceAll(`/`,`_`).replaceAll(t[e],``);return n},oe=(e,t,n)=>{let r={},i={};for(let a of n)for(let n of t){let t=new URLPattern(n,a).exec(e);t&&(Object.assign(r,t.pathname.groups),Object.assign(i,t.search.groups))}return{pathname:r,search:i}},se=(e=new Map)=>{let t=(t,n)=>{for(let r of e.keys())for(let i of e.get(r)||[]){let e=n===void 0||isNaN(n),a=t===void 0||isNaN(t),o=!1;if(o=a?r===n:(e?isNaN(r):r===n)&&i===t,o)return!0}return!1},n=(t,n)=>{let r=n||NaN,i=t||NaN;e.has(r)?e.get(r)?.add(i):e.set(r,new Set([i]))},r=()=>Array.from(e.values()).flatMap(e=>Array.from(e)),i=e.size,a=r();return{items:e,has:t,set:n,getMin:()=>Math.min(...a),getMax:()=>Math.max(...a),seasonsCount:i,episodesCount:a.length}};new Intl.DateTimeFormat(`en-US`,{year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1}),new Intl.DateTimeFormat(`en-US`,{hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1});const A=new class e extends d.EventEmitter{static requestEventName=`form`;static responseEventName=`form:response`;title;#e=Promise.resolve();constructor(e={}){super(),this.title=e.title,this.listen(async e=>{let{title:n,description:r,fields:a,...o}=e,s={},c=Object.entries(a||o);if(!u.stdin.isTTY||process.platform===`win32`){let e=0,i=1,a=!1;if(process.platform===`win32`)try{e=(0,t.openSync)(`\\\\.\\CONIN$`,`r`),i=(0,t.openSync)(`\\\\.\\CONOUT$`,`w`),a=!0}catch{}try{for(let[t,{label:a,type:o}]of c){let c=o===`confirm`;s[t]=ue([n,r,a].filter(Boolean).join(`. `)+(c?` (y/n)`:``)+`: `,void 0,{inputFd:e,outputFd:i})??``}return s}finally{a&&((0,t.closeSync)(e),(0,t.closeSync)(i))}}u.stdin.setEncoding&&u.stdin.setEncoding(`utf8`),u.stdin.isTTY&&u.stdin.setRawMode&&u.stdin.setRawMode(!1),u.stdin.resume();let l=(0,f.createInterface)({input:u.stdin,output:u.stdout,terminal:!0});try{for(let[e,{label:t,type:a}]of c){let o=a===`confirm`,c=[n,r,t].filter(Boolean).join(`. `)+(o?` (y/n)`:``)+`: `;s[e]=await Promise.race([l.question(c),(0,i.setTimeout)(le,``)])}return s}finally{l.close()}})}async ask(t){let n=()=>new Promise(n=>{this.once(e.responseEventName,e=>{n(e)}),this.emit(e.requestEventName,t)}),r=this.#e.then(n,n);return this.#e=r.then(()=>void 0,()=>void 0),r}listen(t){this.addListener(e.requestEventName,async n=>{let r=await t(n);this.emit(e.responseEventName,r)})}},ce=async(e,t)=>{let n=t?.fields??{answer:{label:e}};return await A.ask({title:t?.title,description:e,fields:n})},le=12e4,ue=(e,n,r)=>{let i=r?.inputFd??0;(0,t.writeSync)(r?.outputFd??1,e||``);let a=Buffer.alloc(1),o=``;for(;;){try{(0,t.readSync)(i,a,0,1,null)}catch(e){if(e.code===`EOF`)break;throw e}let e=a.toString(`utf-8`);if(e===`
|
|
2
|
-
`||e===`\r`){if(e===`\r`)try{(0,t.readSync)(i,a,0,1,null),a.toString(`utf-8`)}catch(e){if(e.code===`EOF`)break;throw e}break}o+=e}return o.trim()||n};var j=class extends Error{response;request;options;constructor(e,t,n){let r=`${e.status||e.status===0?e.status:``} ${e.statusText??``}`.trim(),i=r?`status code ${r}`:`an unknown error`;super(`Request failed with ${i}: ${t.method} ${t.url}`),this.name=`HTTPError`,this.response=e,this.request=t,this.options=n}},de=class extends Error{name=`NonError`;value;constructor(e){let t=`Non-error value was thrown`;try{typeof e==`string`?t=e:e&&typeof e==`object`&&`message`in e&&typeof e.message==`string`&&(t=e.message)}catch{}super(t),this.value=e}},M=class extends Error{name=`ForceRetryError`;customDelay;code;customRequest;constructor(e){let t=e?.cause?e.cause instanceof Error?e.cause:new de(e.cause):void 0;super(e?.code?`Forced retry: ${e.code}`:`Forced retry`,t?{cause:t}:void 0),this.customDelay=e?.delay,this.code=e?.code,this.customRequest=e?.request}};const fe=(()=>{let e=!1,t=!1,n=typeof globalThis.ReadableStream==`function`,r=typeof globalThis.Request==`function`;if(n&&r)try{t=new globalThis.Request(`https://empty.invalid`,{body:new globalThis.ReadableStream,method:`POST`,get duplex(){return e=!0,`half`}}).headers.has(`Content-Type`)}catch(e){if(e instanceof Error&&e.message===`unsupported BodyInit type`)return!1;throw e}return e&&!t})(),pe=typeof globalThis.AbortController==`function`,N=typeof globalThis.AbortSignal==`function`&&typeof globalThis.AbortSignal.any==`function`,me=typeof globalThis.ReadableStream==`function`,he=typeof globalThis.FormData==`function`,P=[`get`,`post`,`put`,`patch`,`head`,`delete`],ge={json:`application/json`,text:`text/*`,formData:`multipart/form-data`,arrayBuffer:`*/*`,blob:`*/*`,bytes:`*/*`},F=2147483647,_e=new TextEncoder().encode(`------WebKitFormBoundaryaxpyiPgbbPti10Rw`).length,ve=Symbol(`stop`);var ye=class{options;constructor(e){this.options=e}};const be=e=>new ye(e),xe={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},Se={next:!0},Ce={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0},we=e=>{if(!e)return 0;if(e instanceof FormData){let t=0;for(let[n,r]of e)t+=_e,t+=new TextEncoder().encode(`Content-Disposition: form-data; name="${n}"`).length,t+=typeof r==`string`?new TextEncoder().encode(r).length:r.size;return t}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength;if(typeof e==`string`)return new TextEncoder().encode(e).length;if(e instanceof URLSearchParams)return new TextEncoder().encode(e.toString()).length;if(`byteLength`in e)return e.byteLength;if(typeof e==`object`&&e)try{let t=JSON.stringify(e);return new TextEncoder().encode(t).length}catch{return 0}return 0},Te=(e,t,n)=>{let r,i=0;return e.pipeThrough(new TransformStream({transform(e,a){if(a.enqueue(e),r){i+=r.byteLength;let e=t===0?0:i/t;e>=1&&(e=1-2**-52),n?.({percent:e,totalBytes:Math.max(t,i),transferredBytes:i},r)}r=e},flush(){r&&(i+=r.byteLength,n?.({percent:1,totalBytes:Math.max(t,i),transferredBytes:i},r))}}))},Ee=(e,t)=>{if(!e.body)return e;if(e.status===204)return new Response(null,{status:e.status,statusText:e.statusText,headers:e.headers});let n=Math.max(0,Number(e.headers.get(`content-length`))||0);return new Response(Te(e.body,n,t),{status:e.status,statusText:e.statusText,headers:e.headers})},De=(e,t,n)=>{if(!e.body)return e;let r=we(n??e.body);return new Request(e,{duplex:`half`,body:Te(e.body,r,t)})},I=e=>typeof e==`object`&&!!e,L=(...e)=>{for(let t of e)if((!I(t)||Array.isArray(t))&&t!==void 0)throw TypeError("The `options` argument must be an object");return V({},...e)},R=(e={},t={})=>{let n=new globalThis.Headers(e),r=t instanceof globalThis.Headers,i=new globalThis.Headers(t);for(let[e,t]of i.entries())r&&t===`undefined`||t===void 0?n.delete(e):n.set(e,t);return n};function z(e,t,n){return Object.hasOwn(t,n)&&t[n]===void 0?[]:V(e[n]??[],t[n]??[])}const B=(e={},t={})=>({beforeRequest:z(e,t,`beforeRequest`),beforeRetry:z(e,t,`beforeRetry`),afterResponse:z(e,t,`afterResponse`),beforeError:z(e,t,`beforeError`)}),Oe=(e,t)=>{let n=new URLSearchParams;for(let r of[e,t])if(r!==void 0)if(r instanceof URLSearchParams)for(let[e,t]of r.entries())n.append(e,t);else if(Array.isArray(r))for(let e of r){if(!Array.isArray(e)||e.length!==2)throw TypeError(`Array search parameters must be provided in [[key, value], ...] format`);n.append(String(e[0]),String(e[1]))}else if(I(r))for(let[e,t]of Object.entries(r))t!==void 0&&n.append(e,String(t));else{let e=new URLSearchParams(r);for(let[t,r]of e.entries())n.append(t,r)}return n},V=(...e)=>{let t={},n={},r={},i,a=[];for(let o of e)if(Array.isArray(o))Array.isArray(t)||(t=[]),t=[...t,...o];else if(I(o)){for(let[e,n]of Object.entries(o)){if(e===`signal`&&n instanceof globalThis.AbortSignal){a.push(n);continue}if(e===`context`){if(n!=null&&(!I(n)||Array.isArray(n)))throw TypeError("The `context` option must be an object");t={...t,context:n==null?{}:{...t.context,...n}};continue}if(e===`searchParams`){i=n==null?void 0:i===void 0?n:Oe(i,n);continue}I(n)&&e in t&&(n=V(t[e],n)),t={...t,[e]:n}}I(o.hooks)&&(r=B(r,o.hooks),t.hooks=r),I(o.headers)&&(n=R(n,o.headers),t.headers=n)}return i!==void 0&&(t.searchParams=i),a.length>0&&(a.length===1?t.signal=a[0]:N?t.signal=AbortSignal.any(a):t.signal=a.at(-1)),t},ke=e=>P.includes(e)?e.toUpperCase():e,H={limit:2,methods:[`get`,`put`,`head`,`delete`,`options`,`trace`],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:1/0,backoffLimit:1/0,delay:e=>.3*2**(e-1)*1e3,jitter:void 0,retryOnTimeout:!1},Ae=(e={})=>{if(typeof e==`number`)return{...H,limit:e};if(e.methods&&!Array.isArray(e.methods))throw Error(`retry.methods must be an array`);if(e.methods&&=e.methods.map(e=>e.toLowerCase()),e.statusCodes&&!Array.isArray(e.statusCodes))throw Error(`retry.statusCodes must be an array`);let t=Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0));return{...H,...t}};var U=class extends Error{request;constructor(e){super(`Request timed out: ${e.method} ${e.url}`),this.name=`TimeoutError`,this.request=e}};async function je(e,t,n,r){return new Promise((i,a)=>{let o=setTimeout(()=>{n&&n.abort(),a(new U(e))},r.timeout);r.fetch(e,t).then(i).catch(a).then(()=>{clearTimeout(o)})})}async function Me(e,{signal:t}){return new Promise((n,r)=>{t&&(t.throwIfAborted(),t.addEventListener(`abort`,i,{once:!0}));function i(){clearTimeout(a),r(t.reason)}let a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e)})}const Ne=(e,t)=>{let n={};for(let r in t)Object.hasOwn(t,r)&&!(r in Ce)&&!(r in xe)&&(!(r in e)||r in Se)&&(n[r]=t[r]);return n},Pe=e=>e===void 0?!1:Array.isArray(e)?e.length>0:e instanceof URLSearchParams?e.size>0:typeof e==`object`?Object.keys(e).length>0:typeof e==`string`?e.trim().length>0:!!e;function Fe(e){return e instanceof j||e?.name===j.name}function Ie(e){return e instanceof U||e?.name===U.name}var W=class e{static create(t,n){let r=new e(t,n),i=r.#p(async()=>{if(typeof r.#i.timeout==`number`&&r.#i.timeout>2147483647)throw RangeError(`The \`timeout\` option cannot be greater than ${F}`);await Promise.resolve();let e=await r.#m();for(let t of r.#i.hooks.afterResponse){let n=r.#u(e.clone()),i;try{i=await t(r.request,r.#h(),n,{retryCount:r.#n})}catch(t){throw r.#f(n),r.#f(e),t}if(i instanceof ye)throw r.#f(n),r.#f(e),new M(i.options);let a=i instanceof globalThis.Response?i:e;n!==a&&r.#f(n),e!==a&&r.#f(e),e=a}if(r.#u(e),!e.ok&&(typeof r.#i.throwHttpErrors==`function`?r.#i.throwHttpErrors(e.status):r.#i.throwHttpErrors)){let t=new j(e,r.request,r.#h());for(let e of r.#i.hooks.beforeError)t=await e(t,{retryCount:r.#n});throw t}if(r.#i.onDownloadProgress){if(typeof r.#i.onDownloadProgress!=`function`)throw TypeError("The `onDownloadProgress` option must be a function");if(!me)throw Error("Streams are not supported in your environment. `ReadableStream` is missing.");let t=e.clone();return r.#f(e),Ee(t,r.#i.onDownloadProgress)}return e}).finally(()=>{let e=r.#a;r.#d(e?.body??void 0),r.#d(r.request.body??void 0)});for(let[e,t]of Object.entries(ge))e===`bytes`&&typeof globalThis.Response?.prototype?.bytes!=`function`||(i[e]=async()=>{r.request.headers.set(`accept`,r.request.headers.get(`accept`)||t);let a=await i;if(e===`json`){if(a.status===204)return``;let e=await a.text();return e===``?``:n.parseJson?n.parseJson(e):JSON.parse(e)}return a[e]()});return i}static#e(e){return e&&typeof e==`object`&&!Array.isArray(e)&&!(e instanceof URLSearchParams)?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):e}request;#t;#n=0;#r;#i;#a;#o;#s;constructor(t,n={}){if(this.#r=t,this.#i={...n,headers:R(this.#r.headers,n.headers),hooks:B({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},n.hooks),method:ke(n.method??this.#r.method??`GET`),prefixUrl:String(n.prefixUrl||``),retry:Ae(n.retry),throwHttpErrors:n.throwHttpErrors??!0,timeout:n.timeout??1e4,fetch:n.fetch??globalThis.fetch.bind(globalThis),context:n.context??{}},typeof this.#r!=`string`&&!(this.#r instanceof URL||this.#r instanceof globalThis.Request))throw TypeError("`input` must be a string, URL, or Request");if(this.#i.prefixUrl&&typeof this.#r==`string`){if(this.#r.startsWith(`/`))throw Error("`input` must not begin with a slash when using `prefixUrl`");this.#i.prefixUrl.endsWith(`/`)||(this.#i.prefixUrl+=`/`),this.#r=this.#i.prefixUrl+this.#r}pe&&N&&(this.#o=this.#i.signal??this.#r.signal,this.#t=new globalThis.AbortController,this.#i.signal=this.#o?AbortSignal.any([this.#o,this.#t.signal]):this.#t.signal),fe&&(this.#i.duplex=`half`),this.#i.json!==void 0&&(this.#i.body=this.#i.stringifyJson?.(this.#i.json)??JSON.stringify(this.#i.json),this.#i.headers.set(`content-type`,this.#i.headers.get(`content-type`)??`application/json`));let r=n.headers&&new globalThis.Headers(n.headers).has(`content-type`);if(this.#r instanceof globalThis.Request&&(he&&this.#i.body instanceof globalThis.FormData||this.#i.body instanceof URLSearchParams)&&!r&&this.#i.headers.delete(`content-type`),this.request=new globalThis.Request(this.#r,this.#i),Pe(this.#i.searchParams)){let t=`?`+(typeof this.#i.searchParams==`string`?this.#i.searchParams.replace(/^\?/,``):new URLSearchParams(e.#e(this.#i.searchParams)).toString()),n=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,t);this.request=new globalThis.Request(n,this.#i)}if(this.#i.onUploadProgress){if(typeof this.#i.onUploadProgress!=`function`)throw TypeError("The `onUploadProgress` option must be a function");if(!fe)throw Error("Request streams are not supported in your environment. The `duplex` option for `Request` is not available.");this.request=this.#_(this.request,this.#i.body??void 0)}}#c(){let e=this.#i.retry.delay(this.#n),t=e;this.#i.retry.jitter===!0?t=Math.random()*e:typeof this.#i.retry.jitter==`function`&&(t=this.#i.retry.jitter(e),(!Number.isFinite(t)||t<0)&&(t=e));let n=this.#i.retry.backoffLimit??1/0;return Math.min(n,t)}async#l(e){if(this.#n++,this.#n>this.#i.retry.limit)throw e;let t=e instanceof Error?e:new de(e);if(t instanceof M)return t.customDelay??this.#c();if(!this.#i.retry.methods.includes(this.request.method.toLowerCase()))throw e;if(this.#i.retry.shouldRetry!==void 0){let n=await this.#i.retry.shouldRetry({error:t,retryCount:this.#n});if(n===!1)throw e;if(n===!0)return this.#c()}if(Ie(e)&&!this.#i.retry.retryOnTimeout)throw e;if(Fe(e)){if(!this.#i.retry.statusCodes.includes(e.response.status))throw e;let t=e.response.headers.get(`Retry-After`)??e.response.headers.get(`RateLimit-Reset`)??e.response.headers.get(`X-RateLimit-Retry-After`)??e.response.headers.get(`X-RateLimit-Reset`)??e.response.headers.get(`X-Rate-Limit-Reset`);if(t&&this.#i.retry.afterStatusCodes.includes(e.response.status)){let e=Number(t)*1e3;Number.isNaN(e)?e=Date.parse(t)-Date.now():e>=Date.parse(`2024-01-01`)&&(e-=Date.now());let n=this.#i.retry.maxRetryAfter??e;return e<n?e:n}if(e.response.status===413)throw e}return this.#c()}#u(e){return this.#i.parseJson&&(e.json=async()=>this.#i.parseJson(await e.text())),e}#d(e){e&&e.cancel().catch(()=>void 0)}#f(e){this.#d(e.body??void 0)}async#p(e){try{return await e()}catch(t){let n=Math.min(await this.#l(t),F);if(this.#n<1)throw t;if(await Me(n,this.#o?{signal:this.#o}:{}),t instanceof M&&t.customRequest){let e=this.#i.signal?new globalThis.Request(t.customRequest,{signal:this.#i.signal}):new globalThis.Request(t.customRequest);this.#g(e)}for(let e of this.#i.hooks.beforeRetry){let n=await e({request:this.request,options:this.#h(),error:t,retryCount:this.#n});if(n instanceof globalThis.Request){this.#g(n);break}if(n instanceof globalThis.Response)return n;if(n===ve)return}return this.#p(e)}}async#m(){this.#t?.signal.aborted&&(this.#t=new globalThis.AbortController,this.#i.signal=this.#o?AbortSignal.any([this.#o,this.#t.signal]):this.#t.signal,this.request=new globalThis.Request(this.request,{signal:this.#i.signal}));for(let e of this.#i.hooks.beforeRequest){let t=await e(this.request,this.#h(),{retryCount:this.#n});if(t instanceof Response)return t;if(t instanceof globalThis.Request){this.#g(t);break}}let e=Ne(this.request,this.#i);return this.#a=this.request,this.request=this.#a.clone(),this.#i.timeout===!1?this.#i.fetch(this.#a,e):je(this.#a,e,this.#t,this.#i)}#h(){if(!this.#s){let{hooks:e,...t}=this.#i;this.#s=Object.freeze(t)}return this.#s}#g(e){this.#s=void 0,this.request=this.#_(e)}#_(e,t){return!this.#i.onUploadProgress||!e.body?e:De(e,this.#i.onUploadProgress,t??this.#i.body??void 0)}};
|
|
3
|
-
/*! MIT License © Sindre Sorhus */
|
|
4
|
-
const G=e=>{let t=(t,n)=>W.create(t,L(e,n));for(let n of P)t[n]=(t,r)=>W.create(t,L(e,r,{method:n}));return t.create=e=>G(L(e)),t.extend=t=>(typeof t==`function`&&(t=t(e??{})),G(L(e,t))),t.stop=ve,t.retry=be,t},Le=G();var Re=e.t((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.stringifySetCookie=s,e.serialize=s,e.parseSetCookie=c,e.stringifySetCookie=s,e.serialize=s;let t=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,n=/^[\u0021-\u003A\u003C-\u007E]*$/,r=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,i=/^[\u0020-\u003A\u003D-\u007E]*$/,a=/^-?\d+$/,o=Object.prototype.toString;function s(e,a,o){let s=typeof e==`object`?e:{...o,name:e,value:String(a)},c=(typeof a==`object`?a:o)?.encode||encodeURIComponent;if(!t.test(s.name))throw TypeError(`argument name is invalid: ${s.name}`);let l=s.value?c(s.value):``;if(!n.test(l))throw TypeError(`argument val is invalid: ${s.value}`);let u=s.name+`=`+l;if(s.maxAge!==void 0){if(!Number.isInteger(s.maxAge))throw TypeError(`option maxAge is invalid: ${s.maxAge}`);u+=`; Max-Age=`+s.maxAge}if(s.domain){if(!r.test(s.domain))throw TypeError(`option domain is invalid: ${s.domain}`);u+=`; Domain=`+s.domain}if(s.path){if(!i.test(s.path))throw TypeError(`option path is invalid: ${s.path}`);u+=`; Path=`+s.path}if(s.expires){if(!p(s.expires)||!Number.isFinite(s.expires.valueOf()))throw TypeError(`option expires is invalid: ${s.expires}`);u+=`; Expires=`+s.expires.toUTCString()}if(s.httpOnly&&(u+=`; HttpOnly`),s.secure&&(u+=`; Secure`),s.partitioned&&(u+=`; Partitioned`),s.priority)switch(typeof s.priority==`string`?s.priority.toLowerCase():void 0){case`low`:u+=`; Priority=Low`;break;case`medium`:u+=`; Priority=Medium`;break;case`high`:u+=`; Priority=High`;break;default:throw TypeError(`option priority is invalid: ${s.priority}`)}if(s.sameSite)switch(typeof s.sameSite==`string`?s.sameSite.toLowerCase():s.sameSite){case!0:case`strict`:u+=`; SameSite=Strict`;break;case`lax`:u+=`; SameSite=Lax`;break;case`none`:u+=`; SameSite=None`;break;default:throw TypeError(`option sameSite is invalid: ${s.sameSite}`)}return u}function c(e,t){let n=t?.decode||f,r=e.length,i=l(e,0,r),o=u(e,0,i),s=o===-1?{name:``,value:n(d(e,0,i))}:{name:d(e,0,o),value:n(d(e,o+1,i))},c=i+1;for(;c<r;){let t=l(e,c,r),n=u(e,c,t),i=n===-1?d(e,c,t):d(e,c,n),o=n===-1?void 0:d(e,n+1,t);switch(i.toLowerCase()){case`httponly`:s.httpOnly=!0;break;case`secure`:s.secure=!0;break;case`partitioned`:s.partitioned=!0;break;case`domain`:s.domain=o;break;case`path`:s.path=o;break;case`max-age`:o&&a.test(o)&&(s.maxAge=Number(o));break;case`expires`:if(!o)break;let e=new Date(o);Number.isFinite(e.valueOf())&&(s.expires=e);break;case`priority`:if(!o)break;let t=o.toLowerCase();(t===`low`||t===`medium`||t===`high`)&&(s.priority=t);break;case`samesite`:if(!o)break;let n=o.toLowerCase();(n===`lax`||n===`strict`||n===`none`)&&(s.sameSite=n);break}c=t+1}return s}function l(e,t,n){let r=e.indexOf(`;`,t);return r===-1?n:r}function u(e,t,n){let r=e.indexOf(`=`,t);return r<n?r:-1}function d(e,t,n){let r=t,i=n;do{let t=e.charCodeAt(r);if(t!==32&&t!==9)break}while(++r<i);for(;i>r;){let t=e.charCodeAt(i-1);if(t!==32&&t!==9)break;i--}return e.slice(r,i)}function f(e){if(e.indexOf(`%`)===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function p(e){return o.call(e)===`[object Date]`}}))();const K=e=>{let t=[];for(let n of e)try{let e=(0,Re.parseSetCookie)(n),r={...e,expires:e.expires instanceof Date?e.expires.getTime():e.expires,sameSite:typeof e.sameSite==`boolean`?`strict`:e.sameSite};t.push(r)}catch(e){O.debug(e)}return t},ze=async e=>{let t=await(0,o.readFile)(e,`utf8`).catch(()=>``);if(!t)return[];let n=t.split(r.EOL).flatMap(e=>e.split(`
|
|
5
|
-
`)).filter(e=>!!e.trim()&&!e.startsWith(`# `)).map(e=>e.split(` `)),i=[];for(let e of n){let[t,n,r,a,o,s,c]=e;i.push({name:s,value:c,expires:Number(o),maxAge:void 0,domain:t.replace(`#HttpOnly_`,``),path:r,secure:a===`TRUE`,httpOnly:void 0,sameSite:void 0})}return i},Be=(e,t)=>e.name===t.name&&e.domain===t.domain&&e.path===t.path&&e.partitioned===t.partitioned,Ve=(e,t)=>{let n=[...e];for(let e of t){let t=n.findIndex(t=>Be(t,e));t>=0?n[t]=e:n.push(e)}return n},He=(e,t)=>{if(typeof e!=`string`)return e;if(t===void 0)throw TypeError(`CookieStore.set(name, value) requires a value argument`);return{name:e,value:t}};var Ue=class{#e={};#t;#n;#r=!1;static parse(e){return K(e)}constructor({storagePath:e}={}){this.#n=e,this.#t=[]}async import(e,{removeSource:t=!0}={}){if(await this.#i(),!(await(0,o.stat)(e).catch(()=>null))?.isFile())return 0;O.debug(`Importing cookies from ${e}`);let n=await ze(e);this.#t=Ve(this.#t,n);try{await this.#a(),t&&await(0,o.rm)(e,{force:!0})}catch(e){throw e}return n.length}async#i(){if(!(!this.#n||this.#r)){if((await(0,o.stat)(this.#n).catch(()=>null))?.isFile()){let e=await(0,o.readFile)(this.#n,`utf8`);this.#e=e?JSON.parse(e):{},this.#t=`cookies`in this.#e?this.#e.cookies:[]}this.#r=!0}}async#a(){if(!this.#n)return;let e=JSON.stringify({...this.#e,cookies:this.#t},null,2);await(0,o.writeFile)(this.#n,e,`utf8`)}async get(e){await this.#i();let t=typeof e==`string`?e:e.name;return this.#t.find(e=>e.name===t)??null}async getAll(e){if(await this.#i(),!e)return this.#t;let t=typeof e==`string`?e:e.name;return this.#t.filter(e=>e.name===t)??null}async set(e,t){await this.#i();let n=He(e,t);this.#t=Ve(this.#t,[n]),await this.#a()}async delete(e){if(await this.#i(),!e)this.#t=[];else{let t=typeof e==`string`?e:e.name;this.#t=this.#t.filter(e=>e.name!==t)}await this.#a()}toString(){return this.#t.map(e=>`${e.name}=${e.value}`).join(`; `)}};const We=Le.default??Le,Ge=e=>e?e instanceof Headers?e.has(`User-Agent`):typeof e==`object`&&e?`User-Agent`in e||`user-agent`in e:!1:!1,Ke=e=>e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e);var qe=class{cookieStore;headers;#e;#t;constructor(e={}){this.headers=new Headers,this.configure(e)}configure({maxRetries:e=3,proxyUrl:t,allowH2:n=!0,cookieStore:r,fetch:i}={}){this.cookieStore=r??this.cookieStore??new Ue;let a=t?new m.ProxyAgent({uri:t,allowH2:n}):new m.Agent({allowH2:n}),o={retry:e};this.#e=We.create({dispatcher:a,proxy:t,fetch:i,...o});let s=new p.Impit({browser:`chrome`,proxyUrl:t,ignoreTlsErrors:!0,followRedirects:!1});this.#t=We.create({fetch:this.#r.bind(this,i??s.fetch.bind(s)),...o})}async fetch(e,t={}){let n=await this.#n(e,t?.headers),r=(Ge(t?.headers)?this.#e:this.#t)[t?.method?.toLowerCase()??`get`],i=await r(e,{...t,headers:n}),a=i.headers.getSetCookie();return a&&await this.setCookies(a),i}async#n(e,t){let n=this.appendHeaders(t),r=await this.cookieStore.getAll(),i=r.filter(t=>!t.domain||Ke(e).hostname.includes(t.domain));for(let e of r)i.find(t=>t.name===e.name)||e.domain||i.push(e);let a=i.map(e=>`${e.name}=${e.value}`).join(`; `);return a?(n.has(`cookie`)?n.get(`cookie`)||n.delete(`cookie`):n.set(`cookie`,a),n):(n.get(`cookie`)||n.delete(`cookie`),n)}async setCookies(e){let t=[];if(typeof e==`string`){let[n]=K([e]);n&&t.push(n)}else if(Array.isArray(e)&&typeof e.at(0)==`string`){let n=K(e);t.push(...n)}else Array.isArray(e)&&typeof e[0]!=`string`&&t.push(...e);if(!(!t||!t?.length))for(let e of t)await this.cookieStore.set(e)}appendHeaders(e){let t=new Headers(this.headers),n=e instanceof Headers?e.entries():Object.entries(e??{});for(let[e,r]of n)t.set(e,r);return t}setHeader(e,t){this.headers.set(e,t)}removeHeader(e){this.headers.delete(e)}async#r(e,t,n={}){let r=0,i=t instanceof Request?new URL(t.url):t,a=await this.#o(t,n)??{};for(a.redirect=`manual`;;){let t=await e(i,a),n=t.headers.getSetCookie();if(n.length&&await this.setCookies(n),!this.#a(t.status))return t;let o=t.headers.get(`location`);if(!o)return t;if(r>=20)throw Error(`Maximum redirect limit (20) exceeded`);r+=1,i=new URL(o,Ke(i)),a=this.#i(a,t.status)??{},a.headers=await this.#n(i,a.headers)}}#i(e={},t){let n=e.method?.toUpperCase()??`GET`;if(t===303||(t===301||t===302)&&n===`POST`){let t=new Headers(e.headers);return t.delete(`content-length`),t.delete(`content-type`),{...e,method:`GET`,body:void 0,headers:t,redirect:`manual`}}return{...e,redirect:`manual`}}#a(e){return[301,302,303,307,308].includes(e)}async#o(e,t={}){if(!(e instanceof Request))return{...t};let n=new Headers(e.headers);for(let[e,r]of new Headers(t.headers).entries())n.set(e,r);let r=(t.method??e.method).toUpperCase(),i={...t,method:r,headers:n};return t.body!==void 0||r===`GET`||r===`HEAD`?(i.body=t.body,i):(i.body=await e.clone().arrayBuffer(),i)}};new qe;const{COMMON_CONTEXT:Je}=h.default,Ye=(e,t=`Eval`,n)=>{try{return h.default.createScript(t,e,n)}catch(t){return console.debug(t),console.debug(e),console.error(`Syntax Error: ${t.message}`),null}},Xe=(e,t=1)=>{if(Array.isArray(e)||typeof e==`string`){let n=[];for(let r=1;r<=t;r++)n.push(e[Math.floor(Math.random()*e.length)]);return n}else return[]},Ze=e=>new(`default`in g.default?g.default.default:g.default)(e);var Qe=class{#e;constructor(e){this.#e=Ze({cwd:(0,n.dirname)(e),configName:(0,n.basename)(e,`.json`)})}get length(){return Object.keys(this.#e.store).length}clear(){this.#e.clear()}getItem(e){return this.#e.get(e)??null}key(e){return Object.keys(this.#e.store).at(e)??null}removeItem(e){this.#e.delete(e)}setItem(e,t){this.#e.set(e,t)}};const $e=new d.default,q=e=>{if(!e||typeof e!=`object`)return!1;let t=`name`in e?String(e.name):``;return t===`ExitPromptError`||t===`AbortPromptError`},et=e=>e&&e[0].toUpperCase()+e.slice(1),J=(e,t=!1)=>{if(typeof e==`boolean`)return e;if(typeof e!=`string`)return t;let n=e.trim().toLowerCase();return[`1`,`true`,`yes`,`y`,`on`].includes(n)?!0:[`0`,`false`,`no`,`n`,`off`].includes(n)?!1:t},Y=(e,t=0)=>{if(typeof e==`number`&&Number.isFinite(e))return e;if(typeof e!=`string`)return t;let n=Number(e);return Number.isFinite(n)?n:t},tt=e=>{switch(e.type){case`checkbox`:return J(e.defaultValue,!1);case`number`:return Y(e.defaultValue,0);default:return e.defaultValue??``}},nt=(e,t)=>{switch(e.type){case`checkbox`:return J(t,J(e.defaultValue,!1));case`number`:return Y(t,Y(e.defaultValue,0));default:return typeof t==`string`?t:t==null?e.defaultValue??``:String(t)}},rt=e=>{let t=Object.entries(e).map(([e,t])=>[e,tt(t)]);return Object.fromEntries(t)},X=(e,t)=>{let n=Object.entries(e).map(([e,n])=>[e,nt(n,t[e])]);return Object.fromEntries(n)},it=e=>!!e&&typeof e==`object`&&`fields`in e,at=e=>{switch(e){case`password`:case`number`:case`checkbox`:return e;default:return`text`}},ot=e=>{let t=Object.fromEntries(Object.entries(e.fields).map(([e,t])=>[e,{type:at(t.type),title:t.label||e,description:t.description,placeholder:t.placeholder,defaultValue:t.defaultValue??t.value,required:t.required,autoFocus:t.autoFocus}]));return{message:e.description??``,options:{title:e.title,form:t,primaryAction:e.actions?.primaryAction,secondaryAction:e.actions?.secondaryAction}}},Z=async e=>{e?.onAction&&await e.onAction()},st=async e=>{{let{default:t}=await Promise.resolve().then(()=>require(`./open-DWfOU8xH.cjs`));await t(e);return}let{shell:t}=await import(`electron`);await t.openExternal(e)},ct=(e,t,n)=>{let r=typeof e==`string`?e:e?.toString();return r?.trim()&&st(r).catch(e=>{O.error(`Failed to open URL: ${r}`),O.debug(e instanceof Error?e.message:String(e))}),null},Q=async(e,t)=>{if(!t.length)return`dismiss`;try{return await(0,a.select)({message:e,loop:!1,choices:t.map(e=>({name:e.action.title,value:e.kind}))})}catch(e){if(q(e))return`dismiss`;throw e}},$=()=>{switch(r.default.type()){case`Darwin`:return`macOS`;case`Windows_NT`:return`Windows`;default:return`Linux`}};Object.defineProperties(Uint8Array.prototype,{toBase64:{value:function(){return Buffer.from(this).toString(`base64`)},writable:!0,configurable:!0},toHex:{value:function(){return Buffer.from(this).toString(`hex`)},writable:!0,configurable:!0}}),Object.defineProperties(Uint8Array,{fromBase64:{value:function(e){return new Uint8Array(Buffer.from(e,`base64`))},writable:!0,configurable:!0},fromHex:{value:function(e){return new Uint8Array(Buffer.from(e,`hex`))},writable:!0,configurable:!0}});const lt=new Map([[24,[`Sequoia`,`15`]],[23,[`Sonoma`,`14`]],[22,[`Ventura`,`13`]],[21,[`Monterey`,`12`]],[20,[`Big Sur`,`11`]],[19,[`Catalina`,`10.15`]],[18,[`Mojave`,`10.14`]],[17,[`High Sierra`,`10.13`]],[16,[`Sierra`,`10.12`]],[15,[`El Capitan`,`10.11`]],[14,[`Yosemite`,`10.10`]],[13,[`Mavericks`,`10.9`]],[12,[`Mountain Lion`,`10.8`]],[11,[`Lion`,`10.7`]],[10,[`Snow Leopard`,`10.6`]],[9,[`Leopard`,`10.5`]],[8,[`Tiger`,`10.4`]],[7,[`Panther`,`10.3`]],[6,[`Jaguar`,`10.2`]],[5,[`Puma`,`10.1`]]]),ut=()=>{let e=Number(r.default.release().split(`.`)[0]),[t,n]=lt.get(e)||[`Unknown`,``];return{name:t,version:n}},dt=()=>{switch($()){case`macOS`:return ut().version;case`Windows`:return r.default.release();case`Linux`:return r.default.release()}},ft=()=>{let e=[{brand:`Azot`,version:b.version.split(`.`).slice(0,2).join(`.`)},{brand:`Node.js`,version:process.version.replace(`v`,``).split(`.`).slice(0,1).join(`.`)}];return{mobile:!1,platform:$(),brands:e,getHighEntropyValues:async t=>{let n={mobile:!1,platform:$(),brands:e};return t.includes(`architecture`)&&(n.architecture=r.default.arch()),t.includes(`platform`)&&(n.platform=$()),t.includes(`platformVersion`)&&(n.platformVersion=dt()),t.includes(`fullVersionList`)&&(n.fullVersionList=[{brand:`Azot`,version:b.version},{brand:`Node.js`,version:process.version}]),n}}},pt=({name:e=`extension`,dir:t=process.cwd(),title:r}={})=>{let o=C((0,n.join)(t,e)),s=new Qe((0,n.join)(o,`storage.json`)),c=new Ue({storagePath:(0,n.join)(o,`cookies.json`)}),l=new qe({cookieStore:c}),u=(e,t,n)=>e.split(t)[1]?.split(n)[0]?.trim(),d={sanitizeString:ae,execUrlPatterns:oe,extendEpisodes:se,between:u,getRandomElements:Xe},f=r?et(r):void 0,p=e=>e||f,m=async e=>(e.title||=f,await A.ask(e)),h=async(e,t={})=>{let n=p(t.title)??`Azot`,r=[t.primaryAction?{kind:`primary`,action:t.primaryAction}:null,t.secondaryAction?{kind:`secondary`,action:t.secondaryAction}:null].filter(Boolean);{if(!r.length)return O.info(e);let n=await Q(e,r);n===`primary`&&await Z(t.primaryAction),n===`secondary`&&await Z(t.secondaryAction);return}let i=(await k.ask({variant:`notify`,title:n,message:e,style:t.style,primaryAction:t.primaryAction?{title:t.primaryAction.title,style:t.primaryAction.style}:void 0,secondaryAction:t.secondaryAction?{title:t.secondaryAction.title,style:t.secondaryAction.style}:void 0})).action??`dismiss`;i===`primary`&&await Z(t.primaryAction),i===`secondary`&&await Z(t.secondaryAction)},g=async(e,t={})=>{let n=p(t.title)??`Azot`,r=!!t.primaryAction||!!t.secondaryAction,i=t.primaryAction??{title:`OK`},o=t.secondaryAction??{title:`Cancel`,style:`cancel`};if(r){let t=await Q(e,[{kind:`primary`,action:i},{kind:`secondary`,action:o}]);return t===`primary`?(await Z(i),!0):(t===`secondary`&&await Z(o),!1)}try{let n=await(0,a.confirm)({message:e,default:!0});return n?await Z(t.primaryAction):await Z(t.secondaryAction),n}catch(e){if(q(e))return!1;throw e}let s=await k.ask({variant:`confirm`,title:n,message:e,style:t.style,primaryAction:{title:i.title,style:i.style},secondaryAction:{title:o.title,style:o.style}}),c=s.action===`primary`;return c?await Z(i):s.action===`secondary`&&await Z(o),c},_=async(e,t)=>{let n=rt(t.form),r=Object.entries(t.form),i=!!t.primaryAction||!!t.secondaryAction,o=t.primaryAction??{title:`Submit`},s=t.secondaryAction??{title:`Cancel`,style:`cancel`};{let c={};try{for(let[e,t]of r){let n=[t.title||e,t.description].filter(Boolean).join(` - `);if(t.type===`checkbox`){c[e]=await(0,a.confirm)({message:n,default:J(t.defaultValue,!1)});continue}if(t.type===`number`){let r=Y(t.defaultValue,NaN);c[e]=await(0,a.number)({message:n,default:Number.isFinite(r)?r:void 0,validate:e=>(e===void 0||Number.isNaN(e))&&t.required?`This field is required`:!0});continue}if(t.type===`password`){c[e]=await(0,a.password)({message:n,validate:t.required?e=>String(e??``).trim()?!0:`This field is required`:void 0});continue}c[e]=await(0,a.input)({message:n,default:t.defaultValue,validate:t.required?e=>String(e??``).trim()?!0:`This field is required`:void 0})}}catch(e){if(q(e))return n;throw e}if(!i)return X(t.form,c);let l=await Q(e,[{kind:`primary`,action:o},{kind:`secondary`,action:s}]);return l===`primary`?(await Z(o),X(t.form,c)):(l===`secondary`&&await Z(s),n)}let c=Object.fromEntries(r.map(([e,t])=>[e,{type:t.type,label:t.title||e,description:t.description,placeholder:t.placeholder,defaultValue:t.defaultValue,value:t.defaultValue,required:t.required,autoFocus:t.autoFocus}])),l=await m({title:p(t.title),description:e,fields:c,actions:i?{primaryAction:{title:o.title,style:o.style},secondaryAction:{title:s.title,style:s.style}}:void 0}),u=l.__action??`primary`,d={...l};return delete d.__action,u===`primary`?(await Z(t.primaryAction),X(t.form,d)):(u===`secondary`&&await Z(t.secondaryAction),n)},v=async(e,t)=>{if(it(e)){let t=ot(e);return _(t.message,t.options)}if(!t)throw TypeError(`prompt(message, options) requires a form definition`);return _(e,t)},y={defineExtension:e=>e,version:b.version,sleep:i.setTimeout,sanitizeString:ae,execUrlPatterns:oe,extendEpisodes:se,between:u,getRandomElements:Xe,utils:d,notify:h,confirm:g,prompt:v,input:ce,ask:v};class x{get cookie(){return c.toString()}}let S={fetch:l.fetch.bind(l),Response,Request,Headers,AbortController,AbortSignal,URL,URLSearchParams,URLPattern,open:ct,Blob,structuredClone,btoa,atob,TextEncoder,TextDecoder,Uint8Array,crypto,console:{log:console.log,info:O.info.bind(O),warn:O.warn.bind(O),error:(...e)=>{let t=String(e[0]??`Unknown error`);$e.emit(`error`,{message:t}),O.error(t)},trace:O.trace.bind(O),debug:O.debug.bind(O)},Event,EventTarget,localStorage:s,cookieStore:c,document:new x,eval:e=>Ye(e)?.exports,navigator:{appName:`Azot`,appVersion:b.version,platform:process.platform,userAgent:`Azot/${b.version}`,userAgentData:ft()}};return{http:l,question:A,common:d,Streamyx:y,Azot:y,window:S,...S}};Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return pt}});
|
package/dist/context.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./context-NfAQSZZu.cjs`);exports.createContext=e.t;
|
package/dist/main.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:`Module`}});const e=Azot??Streamyx??{};e&&(e.defineExtension||=e=>e);const t=e.defineExtension,n=e.version,r=e.sleep,i=e.input,a=e.prompt,o=e.notify,s=e.confirm,c=e.ask,l=e.utils;exports.ask=c,exports.confirm=s,exports.default=e,exports.defineExtension=t,exports.input=i,exports.notify=o,exports.prompt=a,exports.sleep=r,exports.utils=l,exports.version=n;
|
package/dist/main.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=Azot??Streamyx??{};e&&(e.defineExtension||=e=>e);const t=e.defineExtension,n=e.version,r=e.sleep,i=e.input,a=e.prompt,o=e.notify,s=e.confirm,c=e.ask,l=e.utils;export{c as ask,s as confirm,e as default,t as defineExtension,i as input,o as notify,a as prompt,r as sleep,l as utils,n as version};
|
package/dist/open-DWfOU8xH.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`./chunk-350yNsax.cjs`);let t=require(`node:util`),n=require(`node:fs`);n=e.n(n);let r=require(`node:path`);r=e.n(r);let i=require(`node:os`);i=e.n(i);let a=require(`node:fs/promises`);a=e.n(a);let o=require(`node:process`);o=e.n(o);let s=require(`node:child_process`);s=e.n(s);let c=require(`node:url`),l=require(`node:buffer`),u;function d(){try{return n.default.statSync(`/.dockerenv`),!0}catch{return!1}}function f(){try{return n.default.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function ee(){return u===void 0&&(u=d()||f()),u}let p;const m=()=>{try{return n.default.statSync(`/run/.containerenv`),!0}catch{return!1}};function h(){return p===void 0&&(p=m()||ee()),p}const g=()=>{if(o.default.platform!==`linux`)return!1;if(i.default.release().toLowerCase().includes(`microsoft`))return!h();try{return n.default.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!h():!1}catch{return!1}};var _=o.default.env.__IS_WSL_TEST__?g:g();const v=(0,t.promisify)(s.default.execFile),y=()=>`${o.default.env.SYSTEMROOT||o.default.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,b=async(e,t={})=>{let{powerShellPath:n,...r}=t,i=b.encodeCommand(e);return v(n??y(),[...b.argumentsPrefix,i],{encoding:`utf8`,...r})};b.argumentsPrefix=[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`],b.encodeCommand=e=>l.Buffer.from(e,`utf16le`).toString(`base64`),b.escapeArgument=e=>`'${String(e).replaceAll(`'`,`''`)}'`;function x(e){for(let t of e.split(`
|
|
2
|
-
`)){if(/^\s*#/.test(t))continue;let e=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(e)return e.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,``)}}const S=(0,t.promisify)(s.default.execFile),te=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await a.default.access(n,a.constants.F_OK),r=!0}catch{}if(!r)return e;let i=x(await a.default.readFile(n,{encoding:`utf8`}));return i===void 0?e:(t=i,t=t.endsWith(`/`)?t:`${t}/`,t)}})(),C=_?async()=>`${await te()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`:y;let w;const T=async()=>(w??=(async()=>{try{let e=await C();return await a.default.access(e,a.constants.X_OK),!0}catch{return!1}})(),w),E=async()=>{let e=await C(),{stdout:t}=await b(String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{powerShellPath:e});return t.trim()},D=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await S(`wslpath`,[`-aw`,e],{encoding:`utf8`});return t.trim()}catch{return e}};function O(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const k=(0,t.promisify)(s.execFile);async function A(){if(o.default.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await k(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const j=(0,t.promisify)(s.execFile);async function M(e,{humanReadableOutput:t=!0}={}){if(o.default.platform!==`darwin`)throw Error(`macOS only`);let{stdout:n}=await j(`osascript`,[`-e`,e,t?[]:[`-ss`]]);return n.trim()}async function N(e){return M(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const P=(0,t.promisify)(s.execFile),F={MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeBHTML:{name:`Edge Beta`,id:`com.microsoft.edge.beta`},MSEdgeDHTML:{name:`Edge Dev`,id:`com.microsoft.edge.dev`},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},ChromeBHTML:{name:`Chrome Beta`,id:`com.google.chrome.beta`},ChromeDHTML:{name:`Chrome Dev`,id:`com.google.chrome.dev`},ChromiumHTM:{name:`Chromium`,id:`org.chromium.Chromium`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveDHTML:{name:`Brave Dev`,id:`com.brave.Browser.dev`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},OperaStable:{name:`Opera`,id:`com.operasoftware.Opera`},VivaldiHTM:{name:`Vivaldi`,id:`com.vivaldi.Vivaldi`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`}},I=new Map(Object.entries(F));var L=class extends Error{};async function R(e=P){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new L(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=r.lastIndexOf(`.`),a=r.lastIndexOf(`-`),o=i===-1?void 0:r.slice(0,i),s=a===-1?void 0:r.slice(0,a);return F[r]??F[o]??F[s]??{name:r,id:r}}const z=(0,t.promisify)(s.execFile),B=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function V(){if(o.default.platform===`darwin`){let e=await A();return{name:await N(e),id:e}}if(o.default.platform===`linux`){let{stdout:e}=await z(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:B(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(o.default.platform===`win32`)return R();throw Error(`Only macOS, Linux, and Windows are supported`)}const H=!!(o.default.env.SSH_CONNECTION||o.default.env.SSH_CLIENT||o.default.env.SSH_TTY),U=Symbol(`fallbackAttempt`),W=require(`url`).pathToFileURL(__filename).href?r.default.dirname((0,c.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)):``,G=r.default.join(W,`xdg-open`),{platform:K,arch:q}=o.default,J=async(e,t)=>{if(e.length===0)return;let n=[];for(let r of e)try{return await t(r)}catch(e){n.push(e)}throw AggregateError(n,`Failed to open in all supported apps`)},Y=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[U]===!0;if(delete e[U],Array.isArray(e.app))return J(e.app,t=>Y({...e,app:t,[U]:!0}));let{name:n,arguments:r=[]}=e.app??{};if(r=[...r],Array.isArray(n))return J(n,t=>Y({...e,app:{name:t,arguments:r},[U]:!0}));if(n===`browser`||n===`browserPrivate`){let t={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`,"com.apple.safari":`safari`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a;if(_){let e=await E();a=I.get(e)??{}}else a=await V();if(a.id in t){let o=t[a.id.toLowerCase()];if(n===`browserPrivate`){if(o===`safari`)throw Error(`Safari doesn't support opening in private mode via command line`);r.push(i[o])}return Y({...e,app:{name:$[o],arguments:r}})}throw Error(`${a.name} is not supported as a default browser`)}let i,c=[],l={},u=!1;if(_&&!h()&&!H&&!n&&(u=await T()),K===`darwin`)i=`open`,e.wait&&c.push(`--wait-apps`),e.background&&c.push(`--background`),e.newInstance&&c.push(`--new`),n&&c.push(`-a`,n);else if(K===`win32`||u){i=await C(),c.push(...b.argumentsPrefix),_||(l.windowsVerbatimArguments=!0),_&&e.target&&(e.target=await D(e.target));let t=[`$ProgressPreference = 'SilentlyContinue';`,`Start`];e.wait&&t.push(`-Wait`),n?(t.push(b.escapeArgument(n)),e.target&&r.push(e.target)):e.target&&t.push(b.escapeArgument(e.target)),r.length>0&&(r=r.map(e=>b.escapeArgument(e)),t.push(`-ArgumentList`,r.join(`,`))),e.target=b.encodeCommand(t.join(` `)),e.wait||(l.stdio=`ignore`)}else{if(n)i=n;else{let e=!W||W===`/`,t=!1;try{await a.default.access(G,a.constants.X_OK),t=!0}catch{}i=o.default.versions.electron??(K===`android`||e||!t)?`xdg-open`:G}r.length>0&&c.push(...r),e.wait||(l.stdio=`ignore`,l.detached=!0)}K===`darwin`&&r.length>0&&c.push(`--args`,...r),e.target&&c.push(e.target);let d=s.default.spawn(i,c,l);return e.wait?new Promise((t,n)=>{d.once(`error`,n),d.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r!==0){n(Error(`Exited with code ${r}`));return}t(d)})}):t?new Promise((e,t)=>{d.once(`error`,t),d.once(`spawn`,()=>{d.once(`close`,n=>{if(d.off(`error`,t),n!==0){t(Error(`Exited with code ${n}`));return}d.unref(),e(d)})})}):(d.unref(),new Promise((e,t)=>{d.once(`error`,t),d.once(`spawn`,()=>{d.off(`error`,t),e(d)})}))},X=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return Y({...t,target:e})};function Z(e){if(typeof e==`string`||Array.isArray(e))return e;let{[q]:t}=e;if(!t)throw Error(`${q} is not supported`);return t}function Q({[K]:e},{wsl:t}={}){if(t&&_)return Z(t);if(!e)throw Error(`${K} is not supported`);return Z(e)}const $={browser:`browser`,browserPrivate:`browserPrivate`};O($,`chrome`,()=>Q({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`,`chromium-browser`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),O($,`brave`,()=>Q({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),O($,`firefox`,()=>Q({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),O($,`edge`,()=>Q({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),O($,`safari`,()=>Q({darwin:`Safari`})),exports.default=X;
|
package/dist/open-rfKrXH0-.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{promisify as e}from"node:util";import t from"node:fs";import n from"node:path";import r from"node:os";import i,{constants as a}from"node:fs/promises";import o from"node:process";import s,{execFile as c}from"node:child_process";import{fileURLToPath as l}from"node:url";import{Buffer as u}from"node:buffer";let d;function f(){try{return t.statSync(`/.dockerenv`),!0}catch{return!1}}function p(){try{return t.readFileSync(`/proc/self/cgroup`,`utf8`).includes(`docker`)}catch{return!1}}function m(){return d===void 0&&(d=f()||p()),d}let h;const g=()=>{try{return t.statSync(`/run/.containerenv`),!0}catch{return!1}};function _(){return h===void 0&&(h=g()||m()),h}const v=()=>{if(o.platform!==`linux`)return!1;if(r.release().toLowerCase().includes(`microsoft`))return!_();try{return t.readFileSync(`/proc/version`,`utf8`).toLowerCase().includes(`microsoft`)?!_():!1}catch{return!1}};var y=o.env.__IS_WSL_TEST__?v:v();const b=e(s.execFile),x=()=>`${o.env.SYSTEMROOT||o.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,S=async(e,t={})=>{let{powerShellPath:n,...r}=t,i=S.encodeCommand(e);return b(n??x(),[...S.argumentsPrefix,i],{encoding:`utf8`,...r})};S.argumentsPrefix=[`-NoProfile`,`-NonInteractive`,`-ExecutionPolicy`,`Bypass`,`-EncodedCommand`],S.encodeCommand=e=>u.from(e,`utf16le`).toString(`base64`),S.escapeArgument=e=>`'${String(e).replaceAll(`'`,`''`)}'`;function ee(e){for(let t of e.split(`
|
|
2
|
-
`)){if(/^\s*#/.test(t))continue;let e=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(e)return e.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,``)}}const C=e(s.execFile),w=(()=>{let e=`/mnt/`,t;return async function(){if(t)return t;let n=`/etc/wsl.conf`,r=!1;try{await i.access(n,a.F_OK),r=!0}catch{}if(!r)return e;let o=ee(await i.readFile(n,{encoding:`utf8`}));return o===void 0?e:(t=o,t=t.endsWith(`/`)?t:`${t}/`,t)}})(),T=y?async()=>`${await w()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`:x;let E;const D=async()=>(E??=(async()=>{try{let e=await T();return await i.access(e,a.X_OK),!0}catch{return!1}})(),E),O=async()=>{let e=await T(),{stdout:t}=await S(String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{powerShellPath:e});return t.trim()},k=async e=>{if(/^[a-z]+:\/\//i.test(e))return e;try{let{stdout:t}=await C(`wslpath`,[`-aw`,e],{encoding:`utf8`});return t.trim()}catch{return e}};function A(e,t,n){let r=n=>Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let e=n();return r(e),e},set(e){r(e)}}),e}const j=e(c);async function te(){if(o.platform!==`darwin`)throw Error(`macOS only`);let{stdout:e}=await j(`defaults`,[`read`,`com.apple.LaunchServices/com.apple.launchservices.secure`,`LSHandlers`]);return/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??`com.apple.Safari`}const ne=e(c);async function M(e,{humanReadableOutput:t=!0}={}){if(o.platform!==`darwin`)throw Error(`macOS only`);let{stdout:n}=await ne(`osascript`,[`-e`,e,t?[]:[`-ss`]]);return n.trim()}async function N(e){return M(`tell application "Finder" to set app_path to application file id "${e}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}const P=e(c),F={MSEdgeHTM:{name:`Edge`,id:`com.microsoft.edge`},MSEdgeBHTML:{name:`Edge Beta`,id:`com.microsoft.edge.beta`},MSEdgeDHTML:{name:`Edge Dev`,id:`com.microsoft.edge.dev`},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:`Edge`,id:`com.microsoft.edge.old`},ChromeHTML:{name:`Chrome`,id:`com.google.chrome`},ChromeBHTML:{name:`Chrome Beta`,id:`com.google.chrome.beta`},ChromeDHTML:{name:`Chrome Dev`,id:`com.google.chrome.dev`},ChromiumHTM:{name:`Chromium`,id:`org.chromium.Chromium`},BraveHTML:{name:`Brave`,id:`com.brave.Browser`},BraveBHTML:{name:`Brave Beta`,id:`com.brave.Browser.beta`},BraveDHTML:{name:`Brave Dev`,id:`com.brave.Browser.dev`},BraveSSHTM:{name:`Brave Nightly`,id:`com.brave.Browser.nightly`},FirefoxURL:{name:`Firefox`,id:`org.mozilla.firefox`},OperaStable:{name:`Opera`,id:`com.operasoftware.Opera`},VivaldiHTM:{name:`Vivaldi`,id:`com.vivaldi.Vivaldi`},"IE.HTTP":{name:`Internet Explorer`,id:`com.microsoft.ie`}},I=new Map(Object.entries(F));var L=class extends Error{};async function R(e=P){let{stdout:t}=await e(`reg`,[`QUERY`,` HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice`,`/v`,`ProgId`]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(t);if(!n)throw new L(`Cannot find Windows browser in stdout: ${JSON.stringify(t)}`);let{id:r}=n.groups,i=r.lastIndexOf(`.`),a=r.lastIndexOf(`-`),o=i===-1?void 0:r.slice(0,i),s=a===-1?void 0:r.slice(0,a);return F[r]??F[o]??F[s]??{name:r,id:r}}const z=e(c),B=e=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,e=>e.toUpperCase());async function V(){if(o.platform===`darwin`){let e=await te();return{name:await N(e),id:e}}if(o.platform===`linux`){let{stdout:e}=await z(`xdg-mime`,[`query`,`default`,`x-scheme-handler/http`]),t=e.trim();return{name:B(t.replace(/.desktop$/,``).replace(`-`,` `)),id:t}}if(o.platform===`win32`)return R();throw Error(`Only macOS, Linux, and Windows are supported`)}const H=!!(o.env.SSH_CONNECTION||o.env.SSH_CLIENT||o.env.SSH_TTY),U=Symbol(`fallbackAttempt`),W=import.meta.url?n.dirname(l(import.meta.url)):``,G=n.join(W,`xdg-open`),{platform:K,arch:q}=o,J=async(e,t)=>{if(e.length===0)return;let n=[];for(let r of e)try{return await t(r)}catch(e){n.push(e)}throw AggregateError(n,`Failed to open in all supported apps`)},Y=async e=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[U]===!0;if(delete e[U],Array.isArray(e.app))return J(e.app,t=>Y({...e,app:t,[U]:!0}));let{name:n,arguments:r=[]}=e.app??{};if(r=[...r],Array.isArray(n))return J(n,t=>Y({...e,app:{name:t,arguments:r},[U]:!0}));if(n===`browser`||n===`browserPrivate`){let t={"com.google.chrome":`chrome`,"google-chrome.desktop":`chrome`,"com.brave.browser":`brave`,"org.mozilla.firefox":`firefox`,"firefox.desktop":`firefox`,"com.microsoft.msedge":`edge`,"com.microsoft.edge":`edge`,"com.microsoft.edgemac":`edge`,"microsoft-edge.desktop":`edge`,"com.apple.safari":`safari`},i={chrome:`--incognito`,brave:`--incognito`,firefox:`--private-window`,edge:`--inPrivate`},a;if(y){let e=await O();a=I.get(e)??{}}else a=await V();if(a.id in t){let o=t[a.id.toLowerCase()];if(n===`browserPrivate`){if(o===`safari`)throw Error(`Safari doesn't support opening in private mode via command line`);r.push(i[o])}return Y({...e,app:{name:$[o],arguments:r}})}throw Error(`${a.name} is not supported as a default browser`)}let c,l=[],u={},d=!1;if(y&&!_()&&!H&&!n&&(d=await D()),K===`darwin`)c=`open`,e.wait&&l.push(`--wait-apps`),e.background&&l.push(`--background`),e.newInstance&&l.push(`--new`),n&&l.push(`-a`,n);else if(K===`win32`||d){c=await T(),l.push(...S.argumentsPrefix),y||(u.windowsVerbatimArguments=!0),y&&e.target&&(e.target=await k(e.target));let t=[`$ProgressPreference = 'SilentlyContinue';`,`Start`];e.wait&&t.push(`-Wait`),n?(t.push(S.escapeArgument(n)),e.target&&r.push(e.target)):e.target&&t.push(S.escapeArgument(e.target)),r.length>0&&(r=r.map(e=>S.escapeArgument(e)),t.push(`-ArgumentList`,r.join(`,`))),e.target=S.encodeCommand(t.join(` `)),e.wait||(u.stdio=`ignore`)}else{if(n)c=n;else{let e=!W||W===`/`,t=!1;try{await i.access(G,a.X_OK),t=!0}catch{}c=o.versions.electron??(K===`android`||e||!t)?`xdg-open`:G}r.length>0&&l.push(...r),e.wait||(u.stdio=`ignore`,u.detached=!0)}K===`darwin`&&r.length>0&&l.push(`--args`,...r),e.target&&l.push(e.target);let f=s.spawn(c,l,u);return e.wait?new Promise((t,n)=>{f.once(`error`,n),f.once(`close`,r=>{if(!e.allowNonzeroExitCode&&r!==0){n(Error(`Exited with code ${r}`));return}t(f)})}):t?new Promise((e,t)=>{f.once(`error`,t),f.once(`spawn`,()=>{f.once(`close`,n=>{if(f.off(`error`,t),n!==0){t(Error(`Exited with code ${n}`));return}f.unref(),e(f)})})}):(f.unref(),new Promise((e,t)=>{f.once(`error`,t),f.once(`spawn`,()=>{f.off(`error`,t),e(f)})}))},X=(e,t)=>{if(typeof e!=`string`)throw TypeError("Expected a `target`");return Y({...t,target:e})};function Z(e){if(typeof e==`string`||Array.isArray(e))return e;let{[q]:t}=e;if(!t)throw Error(`${q} is not supported`);return t}function Q({[K]:e},{wsl:t}={}){if(t&&y)return Z(t);if(!e)throw Error(`${K} is not supported`);return Z(e)}const $={browser:`browser`,browserPrivate:`browserPrivate`};A($,`chrome`,()=>Q({darwin:`google chrome`,win32:`chrome`,linux:[`google-chrome`,`google-chrome-stable`,`chromium`,`chromium-browser`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`,x64:[`/mnt/c/Program Files/Google/Chrome/Application/chrome.exe`,`/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe`]}})),A($,`brave`,()=>Q({darwin:`brave browser`,win32:`brave`,linux:[`brave-browser`,`brave`]},{wsl:{ia32:`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`,x64:[`/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe`,`/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe`]}})),A($,`firefox`,()=>Q({darwin:`firefox`,win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:`firefox`},{wsl:`/mnt/c/Program Files/Mozilla Firefox/firefox.exe`})),A($,`edge`,()=>Q({darwin:`microsoft edge`,win32:`msedge`,linux:[`microsoft-edge`,`microsoft-edge-dev`]},{wsl:`/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe`})),A($,`safari`,()=>Q({darwin:`Safari`}));export{X as default};
|
package/dist/vitest.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
require(`./chunk-350yNsax.cjs`);const e=require(`./context-NfAQSZZu.cjs`);let t=require(`vitest`);const n=e.t();Object.entries(n).forEach(([e,n])=>{t.vi.stubGlobal(e,n)}),t.vi.mock(`azot`,async()=>n.Azot),(0,t.beforeEach)(async()=>{n.localStorage.clear();let e=await n.cookieStore.getAll();for(let t of e)await n.cookieStore.delete(t.name);t.vi.clearAllMocks()});
|