diff --git a/node_modules/.bin/vite b/node_modules/.bin/vite deleted file mode 100644 index a6b17f0..0000000 --- a/node_modules/.bin/vite +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*|*MINGW*|*MSYS*) - if command -v cygpath > /dev/null 2>&1; then - basedir=`cygpath -w "$basedir"` - fi - ;; -esac - -if [ -z "$NODE_PATH" ]; then - export NODE_PATH="/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/vite@5.4.19/node_modules/vite/bin/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/vite@5.4.19/node_modules/vite/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/vite@5.4.19/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/node_modules" -else - export NODE_PATH="/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/vite@5.4.19/node_modules/vite/bin/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/vite@5.4.19/node_modules/vite/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/vite@5.4.19/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/node_modules:$NODE_PATH" -fi -if [ -x "$basedir/node" ]; then - exec "$basedir/node" "$basedir/../vite/bin/vite.js" "$@" -else - exec node "$basedir/../vite/bin/vite.js" "$@" -fi diff --git a/node_modules/.bin/vite.ps1 b/node_modules/.bin/vite.ps1 deleted file mode 100644 index 5340a39..0000000 --- a/node_modules/.bin/vite.ps1 +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env pwsh -$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent - -$exe="" -$pathsep=":" -$env_node_path=$env:NODE_PATH -$new_node_path="F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\vite@5.4.19\node_modules\vite\bin\node_modules;F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\vite@5.4.19\node_modules\vite\node_modules;F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\vite@5.4.19\node_modules;F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\node_modules" -if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { - # Fix case when both the Windows and Linux builds of Node - # are installed in the same directory - $exe=".exe" - $pathsep=";" -} else { - $new_node_path="/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/vite@5.4.19/node_modules/vite/bin/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/vite@5.4.19/node_modules/vite/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/vite@5.4.19/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/node_modules" -} -if ([string]::IsNullOrEmpty($env_node_path)) { - $env:NODE_PATH=$new_node_path -} else { - $env:NODE_PATH="$new_node_path$pathsep$env_node_path" -} - -$ret=0 -if (Test-Path "$basedir/node$exe") { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "$basedir/node$exe" "$basedir/../vite/bin/vite.js" $args - } else { - & "$basedir/node$exe" "$basedir/../vite/bin/vite.js" $args - } - $ret=$LASTEXITCODE -} else { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "node$exe" "$basedir/../vite/bin/vite.js" $args - } else { - & "node$exe" "$basedir/../vite/bin/vite.js" $args - } - $ret=$LASTEXITCODE -} -$env:NODE_PATH=$env_node_path -exit $ret diff --git a/node_modules/.pnpm-workspace-state.json b/node_modules/.pnpm-workspace-state.json deleted file mode 100644 index da765f4..0000000 --- a/node_modules/.pnpm-workspace-state.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "lastValidatedTimestamp": 1747389434647, - "projects": {}, - "pnpmfileExists": false, - "settings": { - "autoInstallPeers": true, - "dedupeDirectDeps": false, - "dedupeInjectedDeps": true, - "dedupePeerDependents": true, - "dev": true, - "excludeLinksFromLockfile": false, - "hoistPattern": [ - "*" - ], - "hoistWorkspacePackages": true, - "injectWorkspacePackages": false, - "linkWorkspacePackages": false, - "nodeLinker": "isolated", - "optional": true, - "preferWorkspacePackages": false, - "production": true, - "publicHoistPattern": [] - }, - "filteredInstall": false -} diff --git a/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/LICENSE b/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/LICENSE deleted file mode 100644 index 4a56f14..0000000 --- a/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2022 JOU Amjs - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/dist/alova-shared.common.cjs b/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/dist/alova-shared.common.cjs deleted file mode 100644 index 66f8e57..0000000 --- a/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/dist/alova-shared.common.cjs +++ /dev/null @@ -1,607 +0,0 @@ -/** - * @alova/shared 1.1.2 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2024 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -'use strict'; - -const undefStr = 'undefined'; -// The following unified processing functions or variables added to reduce the amount of compiled code -const PromiseCls = Promise; -const promiseResolve = (value) => PromiseCls.resolve(value); -const promiseReject = (value) => PromiseCls.reject(value); -const ObjectCls = Object; -const RegExpCls = RegExp; -const undefinedValue = undefined; -const nullValue = null; -const trueValue = true; -const falseValue = false; -const promiseThen = (promise, onFulfilled, onrejected) => promise.then(onFulfilled, onrejected); -const promiseCatch = (promise, onrejected) => promise.catch(onrejected); -const promiseFinally = (promise, onfinally) => promise.finally(onfinally); -const JSONStringify = (value, replacer, space) => JSON.stringify(value, replacer, space); -const JSONParse = (value) => JSON.parse(value); -const setTimeoutFn = (fn, delay = 0) => setTimeout(fn, delay); -const clearTimeoutTimer = (timer) => clearTimeout(timer); -const objectKeys = (obj) => ObjectCls.keys(obj); -const objectValues = (obj) => ObjectCls.values(obj); -const forEach = (ary, fn) => ary.forEach(fn); -const pushItem = (ary, ...item) => ary.push(...item); -const mapItem = (ary, callbackfn) => ary.map(callbackfn); -const filterItem = (ary, predicate) => ary.filter(predicate); -const shift = (ary) => ary.shift(); -const slice = (ary, start, end) => ary.slice(start, end); -const splice = (ary, start, deleteCount = 0, ...items) => ary.splice(start, deleteCount, ...items); -const len = (data) => data.length; -const isArray = (arg) => Array.isArray(arg); -const deleteAttr = (arg, attr) => delete arg[attr]; -const typeOf = (arg) => typeof arg; -const regexpTest = (reg, str) => reg.test(`${str}`); -const includes = (ary, target) => ary.includes(target); -const valueObject = (value, writable = falseValue) => ({ value, writable }); -const defineProperty = (o, key, value, isDescriptor = falseValue) => ObjectCls.defineProperty(o, key, isDescriptor ? value : valueObject(value, falseValue)); -// Whether it is running on the server side, node and bun are judged by process, and deno is judged by Deno. -// Some frameworks (such as Alipay and uniapp) will inject the process object as a global variable. -// Therefore, the process.cwd function unique to the server is used as the basis for judgment. -const isSSR = typeof window === undefStr && - (typeof process !== undefStr ? typeof process.cwd === 'function' : typeof Deno !== undefStr); -/** cache mode */ -// only cache in memory, it's default option -const MEMORY = 'memory'; -// persistent cache, and will be read to memory when page is refreshed, it means that the memory cache always exist until cache is expired. -const STORAGE_RESTORE = 'restore'; - -/** - * Empty function for compatibility processing - */ -const noop = () => { }; -/** - * A function that returns the parameter itself, used for compatibility processing - * Since some systems use self as a reserved word, $self is used to distinguish it. - * @param arg any parameter - * @returns return parameter itself - */ -const $self = (arg) => arg; -/** - * Determine whether the parameter is a function any parameter - * @returns Whether the parameter is a function - */ -const isFn = (arg) => typeOf(arg) === 'function'; -/** - * Determine whether the parameter is a number any parameter - * @returns Whether the parameter is a number - */ -const isNumber = (arg) => typeOf(arg) === 'number' && !Number.isNaN(arg); -/** - * Determine whether the parameter is a string any parameter - * @returns Whether the parameter is a string - */ -const isString = (arg) => typeOf(arg) === 'string'; -/** - * Determine whether the parameter is an object any parameter - * @returns Whether the parameter is an object - */ -const isObject = (arg) => arg !== nullValue && typeOf(arg) === 'object'; -/** - * Global toString any parameter stringified parameters - */ -const globalToString = (arg) => ObjectCls.prototype.toString.call(arg); -/** - * Determine whether it is a normal object any parameter - * @returns Judgment result - */ -const isPlainObject = (arg) => globalToString(arg) === '[object Object]'; -/** - * Determine whether it is an instance of a certain class any parameter - * @returns Judgment result - */ -const instanceOf = (arg, cls) => arg instanceof cls; -/** - * Unified timestamp acquisition function - * @returns Timestamp - */ -const getTime = (date) => (date ? date.getTime() : Date.now()); -/** - * Get the alova instance through the method instance alova example - */ -const getContext = (methodInstance) => methodInstance.context; -/** - * Get method instance configuration data - * @returns Configuration object - */ -const getConfig = (methodInstance) => methodInstance.config; -/** - * Get alova configuration data alova configuration object - */ -const getContextOptions = (alovaInstance) => alovaInstance.options; -/** - * Get alova configuration data through method instance alova configuration object - */ -const getOptions = (methodInstance) => getContextOptions(getContext(methodInstance)); -/** - * Get the key value of the request method - * @returns The key value of this request method - */ -const key = (methodInstance) => { - const { params, headers } = getConfig(methodInstance); - return JSONStringify([methodInstance.type, methodInstance.url, params, methodInstance.data, headers]); -}; -/** - * Create uuid simple version uuid - */ -const uuid = () => { - const timestamp = new Date().getTime(); - return Math.floor(Math.random() * timestamp).toString(36); -}; -/** - * Get the key value of the method instance method instance - * @returns The key value of this method instance - */ -const getMethodInternalKey = (methodInstance) => methodInstance.key; -/** - * Get the request method object - * @param methodHandler Request method handle - * @param args Method call parameters request method object - */ -const getHandlerMethod = (methodHandler, assert, args = []) => { - const methodInstance = isFn(methodHandler) ? methodHandler(...args) : methodHandler; - assert(!!methodInstance.key, 'hook handler must be a method instance or a function that returns method instance'); - return methodInstance; -}; -/** - * Is it special data - * @param data Submit data - * @returns Judgment result - */ -const isSpecialRequestBody = (data) => { - const dataTypeString = globalToString(data); - return (/^\[object (Blob|FormData|ReadableStream|URLSearchParams)\]$/i.test(dataTypeString) || instanceOf(data, ArrayBuffer)); -}; -const objAssign = (target, ...sources) => ObjectCls.assign(target, ...sources); -/** - * Excludes specified attributes from a data collection and returns a new data collection data collection - * @param keys Excluded keys new data collection - */ -const omit = (obj, ...keys) => { - const result = {}; - for (const key in obj) { - if (!keys.includes(key)) { - result[key] = obj[key]; - } - } - return result; -}; -/** - * the same as `Promise.withResolvers` - * @returns promise with resolvers. - */ -function usePromise() { - let retResolve; - let retReject; - const promise = new Promise((resolve, reject) => { - retResolve = resolve; - retReject = reject; - }); - return { promise, resolve: retResolve, reject: retReject }; -} -/** - * Get cached configuration parameters, fixedly returning an object in the format { e: function, c: any, f: any, m: number, s: boolean, t: string } e is the abbreviation of expire, which returns the cache expiration time point (timestamp) in milliseconds. - * c is controlled, indicating whether it is a controlled cache - * f is the original value of cacheFor, which is used to call to obtain cached data when c is true. - * m is the abbreviation of mode, storage mode - * s is the abbreviation of storage, whether to store it locally - * t is the abbreviation of tag, which stores tags persistently. - * @param methodInstance method instance - * @returns Unified cache parameter object - */ -const getLocalCacheConfigParam = (methodInstance) => { - const { cacheFor } = getConfig(methodInstance); - const getCacheExpireTs = (cacheExpire) => isNumber(cacheExpire) ? getTime() + cacheExpire : getTime(cacheExpire || undefinedValue); - let cacheMode = MEMORY; - let expire = () => 0; - let store = falseValue; - let tag = undefinedValue; - const controlled = isFn(cacheFor); - if (!controlled) { - let expireColumn = cacheFor; - if (isPlainObject(cacheFor)) { - const { mode = MEMORY, expire, tag: configTag } = cacheFor || {}; - cacheMode = mode; - store = mode === STORAGE_RESTORE; - tag = configTag ? configTag.toString() : undefinedValue; - expireColumn = expire; - } - expire = (mode) => getCacheExpireTs(isFn(expireColumn) ? expireColumn({ method: methodInstance, mode }) : expireColumn); - } - return { - f: cacheFor, - c: controlled, - e: expire, - m: cacheMode, - s: store, - t: tag - }; -}; -/** - * Create class instance - * @param Cls Constructor - * @param args Constructor parameters class instance - */ -const newInstance = (Cls, ...args) => new Cls(...args); -/** - * Unified configuration - * @param data - * @returns unified configuration - */ -const sloughConfig = (config, args = []) => isFn(config) ? config(...args) : config; -const sloughFunction = (arg, defaultFn) => isFn(arg) ? arg : ![falseValue, nullValue].includes(arg) ? defaultFn : noop; -/** - * Create an executor that calls multiple times synchronously and only executes it once asynchronously - */ -const createSyncOnceRunner = (delay = 0) => { - let timer = undefinedValue; - // Executing multiple calls to this function will execute once asynchronously - return (fn) => { - if (timer) { - clearTimeout(timer); - } - timer = setTimeoutFn(fn, delay); - }; -}; -/** - * Create an asynchronous function queue, the asynchronous function will be executed serially queue add function - */ -const createAsyncQueue = (catchError = falseValue) => { - const queue = []; - let completedHandler = undefinedValue; - let executing = false; - const executeQueue = async () => { - executing = true; - while (len(queue) > 0) { - const asyncFunc = shift(queue); - if (asyncFunc) { - await asyncFunc(); - } - } - completedHandler && completedHandler(); - executing = false; - }; - const addQueue = (asyncFunc) => newInstance((PromiseCls), (resolve, reject) => { - const wrappedFunc = () => promiseThen(asyncFunc(), resolve, err => { - catchError ? resolve(undefinedValue) : reject(err); - }); - pushItem(queue, wrappedFunc); - if (!executing) { - executeQueue(); - } - }); - const onComplete = (fn) => { - completedHandler = fn; - }; - return { - addQueue, - onComplete - }; -}; -/** - * Traverse the target object deeply target audience - * @param callback Traversal callback - * @param preorder Whether to traverse in preorder, the default is true - * @param key The currently traversed key - * @param parent The parent node currently traversed - */ -const walkObject = (target, callback, preorder = trueValue, key, parent) => { - const callCallback = () => { - if (parent && key) { - target = callback(target, key, parent); - if (target !== parent[key]) { - parent[key] = target; - } - } - }; - // Preorder traversal - preorder && callCallback(); - if (isObject(target)) { - for (const i in target) { - if (!instanceOf(target, String)) { - walkObject(target[i], callback, preorder, i, target); - } - } - } - // Postal order traversal - !preorder && callCallback(); - return target; -}; -const cacheKeyPrefix = '$a.'; -/** - * build common cache key. - */ -const buildNamespacedCacheKey = (namespace, key) => cacheKeyPrefix + namespace + key; -/** - * Calculate retry delay time based on avoidance strategy and number of retries avoid parameters - * @param retryTimes Number of retries - * @returns Retry delay time - */ -const delayWithBackoff = (backoff, retryTimes) => { - let { startQuiver, endQuiver } = backoff; - const { delay, multiplier = 1 } = backoff; - let retryDelayFinally = (delay || 0) * multiplier ** (retryTimes - 1); - // If start quiver or end quiver has a value, you need to increase the random jitter value in the specified range - if (startQuiver || endQuiver) { - startQuiver = startQuiver || 0; - endQuiver = endQuiver || 1; - retryDelayFinally += - retryDelayFinally * startQuiver + Math.random() * retryDelayFinally * (endQuiver - startQuiver); - retryDelayFinally = Math.floor(retryDelayFinally); // round delay - } - return retryDelayFinally; -}; -/** - * Build the complete url baseURL path url parameters complete url - */ -const buildCompletedURL = (baseURL, url, params) => { - // If the Base url ends with /, remove / - baseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL; - // If it does not start with /or http protocol, you need to add / - // Compatible with some RESTful usage fix: https://github.com/alovajs/alova/issues/382 - if (url !== '') { - url = url.match(/^(\/|https?:\/\/)/) ? url : `/${url}`; - } - const completeURL = baseURL + url; - // Convert params object to get string - // Filter out those whose value is undefined - const paramsStr = mapItem(filterItem(objectKeys(params), key => params[key] !== undefinedValue), key => `${key}=${params[key]}`).join('&'); - // Splice the get parameters behind the url. Note that the url may already have parameters. - return paramsStr - ? +completeURL.includes('?') - ? `${completeURL}&${paramsStr}` - : `${completeURL}?${paramsStr}` - : completeURL; -}; -/** - * Deep clone an object. - * - * @param obj The object to be cloned. - * @returns The cloned object. - */ -const deepClone = (obj) => { - if (isArray(obj)) { - return mapItem(obj, deepClone); - } - if (isPlainObject(obj) && obj.constructor === ObjectCls) { - const clone = {}; - forEach(objectKeys(obj), key => { - clone[key] = deepClone(obj[key]); - }); - return clone; - } - return obj; -}; - -/** - * alova error class - */ -class AlovaError extends Error { - constructor(prefix, message, errorCode) { - super(message + (errorCode ? `\n\nFor detailed: https://alova.js.org/error#${errorCode}` : '')); - this.name = `[alova${prefix ? `/${prefix}` : ''}]`; - } -} -/** - * Custom assertion function that throws an error when the expression is false - * When errorCode is passed in, a link to the error document will be provided to guide the user to correct it. - * @param expression Judgment expression, true or false - * @param message Assert message - */ -const createAssert = (prefix = '') => (expression, message, errorCode) => { - if (!expression) { - throw newInstance(AlovaError, prefix, message, errorCode); - } -}; - -const createEventManager = () => { - const eventMap = {}; - return { - eventMap, - on(type, handler) { - const eventTypeItem = (eventMap[type] = eventMap[type] || []); - pushItem(eventTypeItem, handler); - // return the off function - return () => { - eventMap[type] = filterItem(eventTypeItem, item => item !== handler); - }; - }, - off(type, handler) { - const handlers = eventMap[type]; - if (!handlers) { - return; - } - if (handler) { - const index = handlers.indexOf(handler); - index > -1 && handlers.splice(index, 1); - } - else { - delete eventMap[type]; - } - }, - emit(type, event) { - const handlers = eventMap[type] || []; - return mapItem(handlers, handler => handler(event)); - } - }; -}; -const decorateEvent = (onEvent, decoratedHandler) => { - const emitter = createEventManager(); - const eventType = uuid(); - const eventReturn = onEvent(event => emitter.emit(eventType, event)); - return (handler) => { - emitter.on(eventType, event => { - decoratedHandler(handler, event); - }); - return eventReturn; - }; -}; - -class FrameworkReadableState { - constructor(state, key, dehydrate, exportState) { - this.s = state; - this.k = key; - this.$dhy = dehydrate; - this.$exp = exportState; - } - get v() { - return this.$dhy(this.s); - } - get e() { - return this.$exp(this.s); - } -} -class FrameworkState extends FrameworkReadableState { - constructor(state, key, dehydrate, exportState, update) { - super(state, key, dehydrate, exportState); - this.$upd = update; - } - set v(newValue) { - this.$upd(this.s, newValue); - } - get v() { - return super.v; - } -} - -class QueueCallback { - /** - * @param [limit=null] no limit if set undefined or null - * @param [initialProcessing=false] - */ - constructor(limit, initialProcessing = false) { - this.limit = limit; - this.callbackQueue = []; - this.isProcessing = false; - this.interrupt = false; - this.isProcessing = initialProcessing; - } - /** - * Adds a callback function to the callback queue. - * If a limit is set and the queue has reached its limit, the callback will not be added. - * @param callback The callback function to be added to the queue. - */ - queueCallback(callback) { - if (this.limit && this.callbackQueue.length >= this.limit) { - return; - } - this.callbackQueue.push(callback); - if (!this.isProcessing) { - this.tryRunQueueCallback(); - } - } - /** - * Tries to run the callbacks in the queue. - * If there are callbacks in the queue, it removes the first callback and executes it. - * This method is called recursively until there are no more callbacks in the queue. - */ - async tryRunQueueCallback() { - this.isProcessing = true; - this.interrupt = false; - while (this.callbackQueue.length > 0 && !this.interrupt) { - const cb = this.callbackQueue.shift(); - await (cb === null || cb === void 0 ? void 0 : cb()); - } - this.isProcessing = false; - } - /** - * If set the param `state` to true, it will interrupt the current job (whether or not the current processing state is true) - * If set the param `state` to false, then get on with the rest of the work - */ - setProcessingState(state) { - this.isProcessing = state; - if (!state) { - this.tryRunQueueCallback(); - } - else { - this.interrupt = true; - } - } -} - -const type = {}; - -exports.$self = $self; -exports.AlovaError = AlovaError; -exports.FrameworkReadableState = FrameworkReadableState; -exports.FrameworkState = FrameworkState; -exports.JSONParse = JSONParse; -exports.JSONStringify = JSONStringify; -exports.MEMORY = MEMORY; -exports.ObjectCls = ObjectCls; -exports.PromiseCls = PromiseCls; -exports.QueueCallback = QueueCallback; -exports.RegExpCls = RegExpCls; -exports.STORAGE_RESTORE = STORAGE_RESTORE; -exports.buildCompletedURL = buildCompletedURL; -exports.buildNamespacedCacheKey = buildNamespacedCacheKey; -exports.clearTimeoutTimer = clearTimeoutTimer; -exports.createAssert = createAssert; -exports.createAsyncQueue = createAsyncQueue; -exports.createEventManager = createEventManager; -exports.createSyncOnceRunner = createSyncOnceRunner; -exports.decorateEvent = decorateEvent; -exports.deepClone = deepClone; -exports.defineProperty = defineProperty; -exports.delayWithBackoff = delayWithBackoff; -exports.deleteAttr = deleteAttr; -exports.falseValue = falseValue; -exports.filterItem = filterItem; -exports.forEach = forEach; -exports.getConfig = getConfig; -exports.getContext = getContext; -exports.getContextOptions = getContextOptions; -exports.getHandlerMethod = getHandlerMethod; -exports.getLocalCacheConfigParam = getLocalCacheConfigParam; -exports.getMethodInternalKey = getMethodInternalKey; -exports.getOptions = getOptions; -exports.getTime = getTime; -exports.globalToString = globalToString; -exports.includes = includes; -exports.instanceOf = instanceOf; -exports.isArray = isArray; -exports.isFn = isFn; -exports.isNumber = isNumber; -exports.isObject = isObject; -exports.isPlainObject = isPlainObject; -exports.isSSR = isSSR; -exports.isSpecialRequestBody = isSpecialRequestBody; -exports.isString = isString; -exports.key = key; -exports.len = len; -exports.mapItem = mapItem; -exports.newInstance = newInstance; -exports.noop = noop; -exports.nullValue = nullValue; -exports.objAssign = objAssign; -exports.objectKeys = objectKeys; -exports.objectValues = objectValues; -exports.omit = omit; -exports.promiseCatch = promiseCatch; -exports.promiseFinally = promiseFinally; -exports.promiseReject = promiseReject; -exports.promiseResolve = promiseResolve; -exports.promiseThen = promiseThen; -exports.pushItem = pushItem; -exports.regexpTest = regexpTest; -exports.setTimeoutFn = setTimeoutFn; -exports.shift = shift; -exports.slice = slice; -exports.sloughConfig = sloughConfig; -exports.sloughFunction = sloughFunction; -exports.splice = splice; -exports.trueValue = trueValue; -exports.type = type; -exports.typeOf = typeOf; -exports.undefinedValue = undefinedValue; -exports.usePromise = usePromise; -exports.uuid = uuid; -exports.valueObject = valueObject; -exports.walkObject = walkObject; diff --git a/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/dist/alova-shared.esm.js b/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/dist/alova-shared.esm.js deleted file mode 100644 index 2bf69a2..0000000 --- a/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/dist/alova-shared.esm.js +++ /dev/null @@ -1,529 +0,0 @@ -/** - * @alova/shared 1.1.2 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2024 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -const undefStr = 'undefined'; -// The following unified processing functions or variables added to reduce the amount of compiled code -const PromiseCls = Promise; -const promiseResolve = (value) => PromiseCls.resolve(value); -const promiseReject = (value) => PromiseCls.reject(value); -const ObjectCls = Object; -const RegExpCls = RegExp; -const undefinedValue = undefined; -const nullValue = null; -const trueValue = true; -const falseValue = false; -const promiseThen = (promise, onFulfilled, onrejected) => promise.then(onFulfilled, onrejected); -const promiseCatch = (promise, onrejected) => promise.catch(onrejected); -const promiseFinally = (promise, onfinally) => promise.finally(onfinally); -const JSONStringify = (value, replacer, space) => JSON.stringify(value, replacer, space); -const JSONParse = (value) => JSON.parse(value); -const setTimeoutFn = (fn, delay = 0) => setTimeout(fn, delay); -const clearTimeoutTimer = (timer) => clearTimeout(timer); -const objectKeys = (obj) => ObjectCls.keys(obj); -const objectValues = (obj) => ObjectCls.values(obj); -const forEach = (ary, fn) => ary.forEach(fn); -const pushItem = (ary, ...item) => ary.push(...item); -const mapItem = (ary, callbackfn) => ary.map(callbackfn); -const filterItem = (ary, predicate) => ary.filter(predicate); -const shift = (ary) => ary.shift(); -const slice = (ary, start, end) => ary.slice(start, end); -const splice = (ary, start, deleteCount = 0, ...items) => ary.splice(start, deleteCount, ...items); -const len = (data) => data.length; -const isArray = (arg) => Array.isArray(arg); -const deleteAttr = (arg, attr) => delete arg[attr]; -const typeOf = (arg) => typeof arg; -const regexpTest = (reg, str) => reg.test(`${str}`); -const includes = (ary, target) => ary.includes(target); -const valueObject = (value, writable = falseValue) => ({ value, writable }); -const defineProperty = (o, key, value, isDescriptor = falseValue) => ObjectCls.defineProperty(o, key, isDescriptor ? value : valueObject(value, falseValue)); -// Whether it is running on the server side, node and bun are judged by process, and deno is judged by Deno. -// Some frameworks (such as Alipay and uniapp) will inject the process object as a global variable. -// Therefore, the process.cwd function unique to the server is used as the basis for judgment. -const isSSR = typeof window === undefStr && - (typeof process !== undefStr ? typeof process.cwd === 'function' : typeof Deno !== undefStr); -/** cache mode */ -// only cache in memory, it's default option -const MEMORY = 'memory'; -// persistent cache, and will be read to memory when page is refreshed, it means that the memory cache always exist until cache is expired. -const STORAGE_RESTORE = 'restore'; - -/** - * Empty function for compatibility processing - */ -const noop = () => { }; -/** - * A function that returns the parameter itself, used for compatibility processing - * Since some systems use self as a reserved word, $self is used to distinguish it. - * @param arg any parameter - * @returns return parameter itself - */ -const $self = (arg) => arg; -/** - * Determine whether the parameter is a function any parameter - * @returns Whether the parameter is a function - */ -const isFn = (arg) => typeOf(arg) === 'function'; -/** - * Determine whether the parameter is a number any parameter - * @returns Whether the parameter is a number - */ -const isNumber = (arg) => typeOf(arg) === 'number' && !Number.isNaN(arg); -/** - * Determine whether the parameter is a string any parameter - * @returns Whether the parameter is a string - */ -const isString = (arg) => typeOf(arg) === 'string'; -/** - * Determine whether the parameter is an object any parameter - * @returns Whether the parameter is an object - */ -const isObject = (arg) => arg !== nullValue && typeOf(arg) === 'object'; -/** - * Global toString any parameter stringified parameters - */ -const globalToString = (arg) => ObjectCls.prototype.toString.call(arg); -/** - * Determine whether it is a normal object any parameter - * @returns Judgment result - */ -const isPlainObject = (arg) => globalToString(arg) === '[object Object]'; -/** - * Determine whether it is an instance of a certain class any parameter - * @returns Judgment result - */ -const instanceOf = (arg, cls) => arg instanceof cls; -/** - * Unified timestamp acquisition function - * @returns Timestamp - */ -const getTime = (date) => (date ? date.getTime() : Date.now()); -/** - * Get the alova instance through the method instance alova example - */ -const getContext = (methodInstance) => methodInstance.context; -/** - * Get method instance configuration data - * @returns Configuration object - */ -const getConfig = (methodInstance) => methodInstance.config; -/** - * Get alova configuration data alova configuration object - */ -const getContextOptions = (alovaInstance) => alovaInstance.options; -/** - * Get alova configuration data through method instance alova configuration object - */ -const getOptions = (methodInstance) => getContextOptions(getContext(methodInstance)); -/** - * Get the key value of the request method - * @returns The key value of this request method - */ -const key = (methodInstance) => { - const { params, headers } = getConfig(methodInstance); - return JSONStringify([methodInstance.type, methodInstance.url, params, methodInstance.data, headers]); -}; -/** - * Create uuid simple version uuid - */ -const uuid = () => { - const timestamp = new Date().getTime(); - return Math.floor(Math.random() * timestamp).toString(36); -}; -/** - * Get the key value of the method instance method instance - * @returns The key value of this method instance - */ -const getMethodInternalKey = (methodInstance) => methodInstance.key; -/** - * Get the request method object - * @param methodHandler Request method handle - * @param args Method call parameters request method object - */ -const getHandlerMethod = (methodHandler, assert, args = []) => { - const methodInstance = isFn(methodHandler) ? methodHandler(...args) : methodHandler; - assert(!!methodInstance.key, 'hook handler must be a method instance or a function that returns method instance'); - return methodInstance; -}; -/** - * Is it special data - * @param data Submit data - * @returns Judgment result - */ -const isSpecialRequestBody = (data) => { - const dataTypeString = globalToString(data); - return (/^\[object (Blob|FormData|ReadableStream|URLSearchParams)\]$/i.test(dataTypeString) || instanceOf(data, ArrayBuffer)); -}; -const objAssign = (target, ...sources) => ObjectCls.assign(target, ...sources); -/** - * Excludes specified attributes from a data collection and returns a new data collection data collection - * @param keys Excluded keys new data collection - */ -const omit = (obj, ...keys) => { - const result = {}; - for (const key in obj) { - if (!keys.includes(key)) { - result[key] = obj[key]; - } - } - return result; -}; -/** - * the same as `Promise.withResolvers` - * @returns promise with resolvers. - */ -function usePromise() { - let retResolve; - let retReject; - const promise = new Promise((resolve, reject) => { - retResolve = resolve; - retReject = reject; - }); - return { promise, resolve: retResolve, reject: retReject }; -} -/** - * Get cached configuration parameters, fixedly returning an object in the format { e: function, c: any, f: any, m: number, s: boolean, t: string } e is the abbreviation of expire, which returns the cache expiration time point (timestamp) in milliseconds. - * c is controlled, indicating whether it is a controlled cache - * f is the original value of cacheFor, which is used to call to obtain cached data when c is true. - * m is the abbreviation of mode, storage mode - * s is the abbreviation of storage, whether to store it locally - * t is the abbreviation of tag, which stores tags persistently. - * @param methodInstance method instance - * @returns Unified cache parameter object - */ -const getLocalCacheConfigParam = (methodInstance) => { - const { cacheFor } = getConfig(methodInstance); - const getCacheExpireTs = (cacheExpire) => isNumber(cacheExpire) ? getTime() + cacheExpire : getTime(cacheExpire || undefinedValue); - let cacheMode = MEMORY; - let expire = () => 0; - let store = falseValue; - let tag = undefinedValue; - const controlled = isFn(cacheFor); - if (!controlled) { - let expireColumn = cacheFor; - if (isPlainObject(cacheFor)) { - const { mode = MEMORY, expire, tag: configTag } = cacheFor || {}; - cacheMode = mode; - store = mode === STORAGE_RESTORE; - tag = configTag ? configTag.toString() : undefinedValue; - expireColumn = expire; - } - expire = (mode) => getCacheExpireTs(isFn(expireColumn) ? expireColumn({ method: methodInstance, mode }) : expireColumn); - } - return { - f: cacheFor, - c: controlled, - e: expire, - m: cacheMode, - s: store, - t: tag - }; -}; -/** - * Create class instance - * @param Cls Constructor - * @param args Constructor parameters class instance - */ -const newInstance = (Cls, ...args) => new Cls(...args); -/** - * Unified configuration - * @param data - * @returns unified configuration - */ -const sloughConfig = (config, args = []) => isFn(config) ? config(...args) : config; -const sloughFunction = (arg, defaultFn) => isFn(arg) ? arg : ![falseValue, nullValue].includes(arg) ? defaultFn : noop; -/** - * Create an executor that calls multiple times synchronously and only executes it once asynchronously - */ -const createSyncOnceRunner = (delay = 0) => { - let timer = undefinedValue; - // Executing multiple calls to this function will execute once asynchronously - return (fn) => { - if (timer) { - clearTimeout(timer); - } - timer = setTimeoutFn(fn, delay); - }; -}; -/** - * Create an asynchronous function queue, the asynchronous function will be executed serially queue add function - */ -const createAsyncQueue = (catchError = falseValue) => { - const queue = []; - let completedHandler = undefinedValue; - let executing = false; - const executeQueue = async () => { - executing = true; - while (len(queue) > 0) { - const asyncFunc = shift(queue); - if (asyncFunc) { - await asyncFunc(); - } - } - completedHandler && completedHandler(); - executing = false; - }; - const addQueue = (asyncFunc) => newInstance((PromiseCls), (resolve, reject) => { - const wrappedFunc = () => promiseThen(asyncFunc(), resolve, err => { - catchError ? resolve(undefinedValue) : reject(err); - }); - pushItem(queue, wrappedFunc); - if (!executing) { - executeQueue(); - } - }); - const onComplete = (fn) => { - completedHandler = fn; - }; - return { - addQueue, - onComplete - }; -}; -/** - * Traverse the target object deeply target audience - * @param callback Traversal callback - * @param preorder Whether to traverse in preorder, the default is true - * @param key The currently traversed key - * @param parent The parent node currently traversed - */ -const walkObject = (target, callback, preorder = trueValue, key, parent) => { - const callCallback = () => { - if (parent && key) { - target = callback(target, key, parent); - if (target !== parent[key]) { - parent[key] = target; - } - } - }; - // Preorder traversal - preorder && callCallback(); - if (isObject(target)) { - for (const i in target) { - if (!instanceOf(target, String)) { - walkObject(target[i], callback, preorder, i, target); - } - } - } - // Postal order traversal - !preorder && callCallback(); - return target; -}; -const cacheKeyPrefix = '$a.'; -/** - * build common cache key. - */ -const buildNamespacedCacheKey = (namespace, key) => cacheKeyPrefix + namespace + key; -/** - * Calculate retry delay time based on avoidance strategy and number of retries avoid parameters - * @param retryTimes Number of retries - * @returns Retry delay time - */ -const delayWithBackoff = (backoff, retryTimes) => { - let { startQuiver, endQuiver } = backoff; - const { delay, multiplier = 1 } = backoff; - let retryDelayFinally = (delay || 0) * multiplier ** (retryTimes - 1); - // If start quiver or end quiver has a value, you need to increase the random jitter value in the specified range - if (startQuiver || endQuiver) { - startQuiver = startQuiver || 0; - endQuiver = endQuiver || 1; - retryDelayFinally += - retryDelayFinally * startQuiver + Math.random() * retryDelayFinally * (endQuiver - startQuiver); - retryDelayFinally = Math.floor(retryDelayFinally); // round delay - } - return retryDelayFinally; -}; -/** - * Build the complete url baseURL path url parameters complete url - */ -const buildCompletedURL = (baseURL, url, params) => { - // If the Base url ends with /, remove / - baseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL; - // If it does not start with /or http protocol, you need to add / - // Compatible with some RESTful usage fix: https://github.com/alovajs/alova/issues/382 - if (url !== '') { - url = url.match(/^(\/|https?:\/\/)/) ? url : `/${url}`; - } - const completeURL = baseURL + url; - // Convert params object to get string - // Filter out those whose value is undefined - const paramsStr = mapItem(filterItem(objectKeys(params), key => params[key] !== undefinedValue), key => `${key}=${params[key]}`).join('&'); - // Splice the get parameters behind the url. Note that the url may already have parameters. - return paramsStr - ? +completeURL.includes('?') - ? `${completeURL}&${paramsStr}` - : `${completeURL}?${paramsStr}` - : completeURL; -}; -/** - * Deep clone an object. - * - * @param obj The object to be cloned. - * @returns The cloned object. - */ -const deepClone = (obj) => { - if (isArray(obj)) { - return mapItem(obj, deepClone); - } - if (isPlainObject(obj) && obj.constructor === ObjectCls) { - const clone = {}; - forEach(objectKeys(obj), key => { - clone[key] = deepClone(obj[key]); - }); - return clone; - } - return obj; -}; - -/** - * alova error class - */ -class AlovaError extends Error { - constructor(prefix, message, errorCode) { - super(message + (errorCode ? `\n\nFor detailed: https://alova.js.org/error#${errorCode}` : '')); - this.name = `[alova${prefix ? `/${prefix}` : ''}]`; - } -} -/** - * Custom assertion function that throws an error when the expression is false - * When errorCode is passed in, a link to the error document will be provided to guide the user to correct it. - * @param expression Judgment expression, true or false - * @param message Assert message - */ -const createAssert = (prefix = '') => (expression, message, errorCode) => { - if (!expression) { - throw newInstance(AlovaError, prefix, message, errorCode); - } -}; - -const createEventManager = () => { - const eventMap = {}; - return { - eventMap, - on(type, handler) { - const eventTypeItem = (eventMap[type] = eventMap[type] || []); - pushItem(eventTypeItem, handler); - // return the off function - return () => { - eventMap[type] = filterItem(eventTypeItem, item => item !== handler); - }; - }, - off(type, handler) { - const handlers = eventMap[type]; - if (!handlers) { - return; - } - if (handler) { - const index = handlers.indexOf(handler); - index > -1 && handlers.splice(index, 1); - } - else { - delete eventMap[type]; - } - }, - emit(type, event) { - const handlers = eventMap[type] || []; - return mapItem(handlers, handler => handler(event)); - } - }; -}; -const decorateEvent = (onEvent, decoratedHandler) => { - const emitter = createEventManager(); - const eventType = uuid(); - const eventReturn = onEvent(event => emitter.emit(eventType, event)); - return (handler) => { - emitter.on(eventType, event => { - decoratedHandler(handler, event); - }); - return eventReturn; - }; -}; - -class FrameworkReadableState { - constructor(state, key, dehydrate, exportState) { - this.s = state; - this.k = key; - this.$dhy = dehydrate; - this.$exp = exportState; - } - get v() { - return this.$dhy(this.s); - } - get e() { - return this.$exp(this.s); - } -} -class FrameworkState extends FrameworkReadableState { - constructor(state, key, dehydrate, exportState, update) { - super(state, key, dehydrate, exportState); - this.$upd = update; - } - set v(newValue) { - this.$upd(this.s, newValue); - } - get v() { - return super.v; - } -} - -class QueueCallback { - /** - * @param [limit=null] no limit if set undefined or null - * @param [initialProcessing=false] - */ - constructor(limit, initialProcessing = false) { - this.limit = limit; - this.callbackQueue = []; - this.isProcessing = false; - this.interrupt = false; - this.isProcessing = initialProcessing; - } - /** - * Adds a callback function to the callback queue. - * If a limit is set and the queue has reached its limit, the callback will not be added. - * @param callback The callback function to be added to the queue. - */ - queueCallback(callback) { - if (this.limit && this.callbackQueue.length >= this.limit) { - return; - } - this.callbackQueue.push(callback); - if (!this.isProcessing) { - this.tryRunQueueCallback(); - } - } - /** - * Tries to run the callbacks in the queue. - * If there are callbacks in the queue, it removes the first callback and executes it. - * This method is called recursively until there are no more callbacks in the queue. - */ - async tryRunQueueCallback() { - this.isProcessing = true; - this.interrupt = false; - while (this.callbackQueue.length > 0 && !this.interrupt) { - const cb = this.callbackQueue.shift(); - await (cb === null || cb === void 0 ? void 0 : cb()); - } - this.isProcessing = false; - } - /** - * If set the param `state` to true, it will interrupt the current job (whether or not the current processing state is true) - * If set the param `state` to false, then get on with the rest of the work - */ - setProcessingState(state) { - this.isProcessing = state; - if (!state) { - this.tryRunQueueCallback(); - } - else { - this.interrupt = true; - } - } -} - -const type = {}; - -export { $self, AlovaError, FrameworkReadableState, FrameworkState, JSONParse, JSONStringify, MEMORY, ObjectCls, PromiseCls, QueueCallback, RegExpCls, STORAGE_RESTORE, buildCompletedURL, buildNamespacedCacheKey, clearTimeoutTimer, createAssert, createAsyncQueue, createEventManager, createSyncOnceRunner, decorateEvent, deepClone, defineProperty, delayWithBackoff, deleteAttr, falseValue, filterItem, forEach, getConfig, getContext, getContextOptions, getHandlerMethod, getLocalCacheConfigParam, getMethodInternalKey, getOptions, getTime, globalToString, includes, instanceOf, isArray, isFn, isNumber, isObject, isPlainObject, isSSR, isSpecialRequestBody, isString, key, len, mapItem, newInstance, noop, nullValue, objAssign, objectKeys, objectValues, omit, promiseCatch, promiseFinally, promiseReject, promiseResolve, promiseThen, pushItem, regexpTest, setTimeoutFn, shift, slice, sloughConfig, sloughFunction, splice, trueValue, type, typeOf, undefinedValue, usePromise, uuid, valueObject, walkObject }; diff --git a/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/package.json b/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/package.json deleted file mode 100644 index b97276a..0000000 --- a/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "@alova/shared", - "version": "1.1.2", - "type": "module", - "author": "Scott Hu", - "main": "dist/alova-shared.common.cjs", - "module": "dist/alova-shared.esm.js", - "types": "typings/alova-shared.d.ts", - "license": "MIT", - "homepage": "https://alova.js.org", - "repository": { - "type": "git", - "url": "https://github.com/alovajs/alova.git" - }, - "bugs": { - "url": "https://github.com/alovajs/alova/issues" - }, - "files": [ - "dist", - "typings" - ], - "devDependencies": { - "@alova/scripts": "1.1.1" - }, - "scripts": { - "clean": "rimraf ./dist", - "test": "vitest run", - "lint": "eslint", - "lint:fix": "eslint --fix", - "build": "pnpm run clean && alova-scripts build" - } -} \ No newline at end of file diff --git a/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/typings/alova-shared.d.ts b/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/typings/alova-shared.d.ts deleted file mode 100644 index d324ee1..0000000 --- a/node_modules/.pnpm/@alova+shared@1.1.2/node_modules/@alova/shared/typings/alova-shared.d.ts +++ /dev/null @@ -1,387 +0,0 @@ -/** - * @alova/shared 1.1.2 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2024 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -/** - * alova error class - */ -declare class AlovaError extends Error { - constructor(prefix: string, message: string, errorCode?: number); -} -/** - * Custom assertion function that throws an error when the expression is false - * When errorCode is passed in, a link to the error document will be provided to guide the user to correct it. - * @param expression Judgment expression, true or false - * @param message Assert message - */ -declare const createAssert: (prefix?: string) => (expression: boolean, message: string, errorCode?: number) => void; - -interface EventManager { - on(type: K, handler: (event: E[K]) => void): () => void; - off(type: K, handler?: (event: E[K]) => void): () => void; - /** - * @param type - * @param event - * @param sync Whether to synchronize emit events, if set to `true`, this will wait for all listeners to return results using Promise.all - */ - emit(type: K, event: E[K]): any[]; - eventMap: EventMap; -} -type EventMap = { - [K in keyof E]?: ((event: E[K]) => void)[]; -}; -declare const createEventManager: () => EventManager; -declare const decorateEvent: void) => any>(onEvent: OnEvent, decoratedHandler: (handler: Parameters[0], event: Parameters[0]>[0]) => void) => (handler: Parameters[0]) => any; - -type GeneralFn = (...args: any[]) => any; -/** - * common UI framework state type - */ -interface GeneralState { - [x: string]: T; -} -/** - * is any type - */ -type IsAny = 0 extends 1 & T ? P : N; -/** - * is unknown type - */ -type IsUnknown = IsAny extends P ? N : unknown extends T ? P : N; -type IsAssignable = T2 extends T ? true : false; -type Equal = (() => T extends X ? 1 : 2) extends () => T extends Y ? 1 : 2 ? true : false; -type UsePromiseExposure = { - promise: Promise; - resolve: (value: T | PromiseLike) => void; - reject: (reason?: any) => void; -}; -interface BackoffPolicy { - /** - * Delay time for re-request, in milliseconds - * @default 1000 - */ - delay?: number; - /** - * Specify the delay multiple. For example, if the multiplier is set to 1.5 and the delay is 2 seconds, the first retry will be 2 seconds, the second will be 3 seconds, and the third will be 4.5 seconds - * @default 1 - */ - multiplier?: number; - /** - * The jitter starting percentage value of the delay request, ranging from 0-1 - * When only startQuiver is set, endQuiver defaults to 1 - * For example, if it is set to 0.5, it will add a random time of 50% to 100% to the current delay time - * If endQuiver has a value, the delay time will increase by a random value in the range of startQuiver and endQuiver - */ - startQuiver?: number; - /** - * The jitter ending percentage value of the delay request, ranging from 0-1 - * When only endQuiver is set, startQuiver defaults to 0 - * For example, if it is set to 0.5, it will add a random time from 0% to 50% to the current delay time - * If startQuiver has a value, the delay time will increase by a random value between startQuiver and endQuiver - */ - endQuiver?: number; -} -declare const type: {}; - -type UpdateFn = (state: GeneralState, newValue: Data) => void; -type DehydrateFn = (state: GeneralState) => Data; -type ExportFn = (state: GeneralState) => GeneralState; -declare class FrameworkReadableState { - s: GeneralState; - k: Key; - protected $dhy: DehydrateFn; - protected $exp: ExportFn; - constructor(state: GeneralState, key: Key, dehydrate: DehydrateFn, exportState: ExportFn); - get v(): Data; - get e(): GeneralState; -} -declare class FrameworkState extends FrameworkReadableState { - private $upd; - constructor(state: GeneralState, key: Key, dehydrate: DehydrateFn, exportState: ExportFn, update: UpdateFn); - set v(newValue: Data); - get v(): Data; -} - -/** - * Request cache settings - * expire: expiration time - * 1. When set to a number: if it is greater than 0, the cached data will be returned first, the expiration time unit is milliseconds, if it is less than or equal to 0, it will not be cached, and Infinity will never expire; - * 2. When set to a Date object, it means - * mode: cache mode, optional values are memory, restore - */ -type CacheExpire = number | Date | null; -type CacheMode = 'memory' | 'restore'; - -/** - * Empty function for compatibility processing - */ -declare const noop: () => void; -/** - * A function that returns the parameter itself, used for compatibility processing - * Since some systems use self as a reserved word, $self is used to distinguish it. - * @param arg any parameter - * @returns return parameter itself - */ -declare const $self: (arg: T) => T; -/** - * Determine whether the parameter is a function any parameter - * @returns Whether the parameter is a function - */ -declare const isFn: (arg: any) => arg is GeneralFn; -/** - * Determine whether the parameter is a number any parameter - * @returns Whether the parameter is a number - */ -declare const isNumber: (arg: any) => arg is number; -/** - * Determine whether the parameter is a string any parameter - * @returns Whether the parameter is a string - */ -declare const isString: (arg: any) => arg is string; -/** - * Determine whether the parameter is an object any parameter - * @returns Whether the parameter is an object - */ -declare const isObject: (arg: any) => arg is T; -/** - * Global toString any parameter stringified parameters - */ -declare const globalToString: (arg: any) => string; -/** - * Determine whether it is a normal object any parameter - * @returns Judgment result - */ -declare const isPlainObject: (arg: any) => arg is Record; -/** - * Determine whether it is an instance of a certain class any parameter - * @returns Judgment result - */ -declare const instanceOf: (arg: any, cls: new (...args: any[]) => T) => arg is T; -/** - * Unified timestamp acquisition function - * @returns Timestamp - */ -declare const getTime: (date?: Date) => number; -/** - * Get the alova instance through the method instance alova example - */ -declare const getContext: (methodInstance: T) => T["context"]; -/** - * Get method instance configuration data - * @returns Configuration object - */ -declare const getConfig: (methodInstance: T) => T["config"]; -/** - * Get alova configuration data alova configuration object - */ -declare const getContextOptions: (alovaInstance: T) => T["options"]; -/** - * Get alova configuration data through method instance alova configuration object - */ -declare const getOptions: (methodInstance: T) => T["context"]["options"]; -/** - * Get the key value of the request method - * @returns The key value of this request method - */ -declare const key: (methodInstance: T) => string; -/** - * Create uuid simple version uuid - */ -declare const uuid: () => string; -/** - * Get the key value of the method instance method instance - * @returns The key value of this method instance - */ -declare const getMethodInternalKey: (methodInstance: T) => T["key"]; -/** - * Get the request method object - * @param methodHandler Request method handle - * @param args Method call parameters request method object - */ -declare const getHandlerMethod: (methodHandler: T | ((...args: any[]) => T), assert: (expression: boolean, msg: string) => void, args?: any[]) => T; -/** - * Is it special data - * @param data Submit data - * @returns Judgment result - */ -declare const isSpecialRequestBody: (data: any) => boolean; -declare const objAssign: , U extends Record[]>(target: T, ...sources: U) => T & U[number]; -type Omit = Pick>; -/** - * Excludes specified attributes from a data collection and returns a new data collection data collection - * @param keys Excluded keys new data collection - */ -declare const omit: , K extends keyof T>(obj: T, ...keys: K[]) => Pick>; -/** - * the same as `Promise.withResolvers` - * @returns promise with resolvers. - */ -declare function usePromise(): UsePromiseExposure; -/** - * Get cached configuration parameters, fixedly returning an object in the format { e: function, c: any, f: any, m: number, s: boolean, t: string } e is the abbreviation of expire, which returns the cache expiration time point (timestamp) in milliseconds. - * c is controlled, indicating whether it is a controlled cache - * f is the original value of cacheFor, which is used to call to obtain cached data when c is true. - * m is the abbreviation of mode, storage mode - * s is the abbreviation of storage, whether to store it locally - * t is the abbreviation of tag, which stores tags persistently. - * @param methodInstance method instance - * @returns Unified cache parameter object - */ -declare const getLocalCacheConfigParam: (methodInstance: T) => { - f: any; - c: boolean; - e: (mode: CacheMode) => ReturnType<(cacheExpire: CacheExpire) => number>; - m: CacheMode; - s: boolean; - t: string | undefined; -}; -/** - * Create class instance - * @param Cls Constructor - * @param args Constructor parameters class instance - */ -declare const newInstance: ; -}>(Cls: T, ...args: ConstructorParameters) => InstanceType; -/** - * Unified configuration - * @param data - * @returns unified configuration - */ -declare const sloughConfig: (config: T | ((...args: any[]) => T), args?: any[]) => T; -declare const sloughFunction: (arg: T | undefined, defaultFn: U) => (() => void) | U | (T & GeneralFn); -/** - * Create an executor that calls multiple times synchronously and only executes it once asynchronously - */ -declare const createSyncOnceRunner: (delay?: number) => (fn: () => void) => void; -/** - * Create an asynchronous function queue, the asynchronous function will be executed serially queue add function - */ -declare const createAsyncQueue: (catchError?: boolean) => { - addQueue: (asyncFunc: (...args: any[]) => Promise) => Promise; - onComplete: (fn: GeneralFn) => void; -}; -/** - * Traverse the target object deeply target audience - * @param callback Traversal callback - * @param preorder Whether to traverse in preorder, the default is true - * @param key The currently traversed key - * @param parent The parent node currently traversed - */ -declare const walkObject: (target: any, callback: (value: any, key: string | number | symbol, parent: any) => void, preorder?: boolean, key?: string | number | symbol, parent?: any) => any; -/** - * build common cache key. - */ -declare const buildNamespacedCacheKey: (namespace: string, key: string) => string; -/** - * Calculate retry delay time based on avoidance strategy and number of retries avoid parameters - * @param retryTimes Number of retries - * @returns Retry delay time - */ -declare const delayWithBackoff: (backoff: BackoffPolicy, retryTimes: number) => number; -/** - * Build the complete url baseURL path url parameters complete url - */ -declare const buildCompletedURL: (baseURL: string, url: string, params: Record) => string; -/** - * Deep clone an object. - * - * @param obj The object to be cloned. - * @returns The cloned object. - */ -declare const deepClone: (obj: T) => T; - -type CallbackFn = () => void | Promise; -declare class QueueCallback { - protected limit?: (number | null) | undefined; - private callbackQueue; - private isProcessing; - private interrupt; - /** - * @param [limit=null] no limit if set undefined or null - * @param [initialProcessing=false] - */ - constructor(limit?: (number | null) | undefined, initialProcessing?: boolean); - /** - * Adds a callback function to the callback queue. - * If a limit is set and the queue has reached its limit, the callback will not be added. - * @param callback The callback function to be added to the queue. - */ - queueCallback(callback: CallbackFn): void; - /** - * Tries to run the callbacks in the queue. - * If there are callbacks in the queue, it removes the first callback and executes it. - * This method is called recursively until there are no more callbacks in the queue. - */ - tryRunQueueCallback(): Promise; - /** - * If set the param `state` to true, it will interrupt the current job (whether or not the current processing state is true) - * If set the param `state` to false, then get on with the rest of the work - */ - setProcessingState(state: boolean): void; -} - -declare const PromiseCls: PromiseConstructor; -declare const promiseResolve: (value?: T) => Promise | undefined>; -declare const promiseReject: (value: T) => Promise; -declare const ObjectCls: ObjectConstructor; -declare const RegExpCls: RegExpConstructor; -declare const undefinedValue: undefined; -declare const nullValue: null; -declare const trueValue = true; -declare const falseValue = false; -declare const promiseThen: (promise: Promise, onFulfilled?: ((value: T) => TResult1 | PromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike) | undefined | null) => Promise; -declare const promiseCatch: (promise: Promise, onrejected?: ((reason: any) => TResult | PromiseLike) | undefined | null) => Promise; -declare const promiseFinally: (promise: Promise, onfinally?: (() => void) | undefined | null) => Promise; -declare const JSONStringify: (value: T, replacer?: (this: any, key: string, value: any) => any, space?: string | number) => string; -declare const JSONParse: (value: string) => any; -declare const setTimeoutFn: (fn: GeneralFn, delay?: number) => number; -declare const clearTimeoutTimer: (timer: NodeJS.Timeout | string | number) => void; -declare const objectKeys: (obj: object) => string[]; -declare const objectValues: (obj: object) => any[]; -declare const forEach: (ary: T[], fn: (item: T, index: number, ary: T[]) => void) => void; -declare const pushItem: (ary: T[], ...item: T[]) => number; -declare const mapItem: (ary: T[], callbackfn: (value: T, index: number, array: T[]) => R) => R[]; -declare const filterItem: (ary: T[], predicate: (value: T, index: number, array: T[]) => unknown) => T[]; -declare const shift: (ary: T[]) => T | undefined; -declare const slice: (ary: T[], start?: number, end?: number) => T[]; -declare const splice: (ary: T[], start: number, deleteCount?: number, ...items: T[]) => T[]; -declare const len: (data: any[] | Uint8Array | string) => number; -declare const isArray: (arg: any) => arg is any[]; -declare const deleteAttr: >(arg: T, attr: keyof T) => boolean; -declare const typeOf: (arg: any) => "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"; -declare const regexpTest: (reg: RegExp, str: string | number) => boolean; -declare const includes: (ary: T[], target: T) => boolean; -declare const valueObject: (value: T, writable?: boolean) => { - value: T; - writable: boolean; -}; -declare const defineProperty: (o: object, key: string | symbol, value: any, isDescriptor?: boolean) => object; -declare const isSSR: boolean; -/** cache mode */ -declare const MEMORY = "memory"; -declare const STORAGE_RESTORE = "restore"; - -export { $self, AlovaError, type BackoffPolicy, type CallbackFn, type Equal, type EventManager, FrameworkReadableState, FrameworkState, type GeneralFn, type GeneralState, type IsAny, type IsAssignable, type IsUnknown, JSONParse, JSONStringify, MEMORY, ObjectCls, type Omit, PromiseCls, QueueCallback, RegExpCls, STORAGE_RESTORE, type UsePromiseExposure, buildCompletedURL, buildNamespacedCacheKey, clearTimeoutTimer, createAssert, createAsyncQueue, createEventManager, createSyncOnceRunner, decorateEvent, deepClone, defineProperty, delayWithBackoff, deleteAttr, falseValue, filterItem, forEach, getConfig, getContext, getContextOptions, getHandlerMethod, getLocalCacheConfigParam, getMethodInternalKey, getOptions, getTime, globalToString, includes, instanceOf, isArray, isFn, isNumber, isObject, isPlainObject, isSSR, isSpecialRequestBody, isString, key, len, mapItem, newInstance, noop, nullValue, objAssign, objectKeys, objectValues, omit, promiseCatch, promiseFinally, promiseReject, promiseResolve, promiseThen, pushItem, regexpTest, setTimeoutFn, shift, slice, sloughConfig, sloughFunction, splice, trueValue, type, typeOf, undefinedValue, usePromise, uuid, valueObject, walkObject }; diff --git a/node_modules/.pnpm/@esbuild+win32-x64@0.21.5/node_modules/@esbuild/win32-x64/README.md b/node_modules/.pnpm/@esbuild+win32-x64@0.21.5/node_modules/@esbuild/win32-x64/README.md deleted file mode 100644 index a99ee7c..0000000 --- a/node_modules/.pnpm/@esbuild+win32-x64@0.21.5/node_modules/@esbuild/win32-x64/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# esbuild - -This is the Windows 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details. diff --git a/node_modules/.pnpm/@esbuild+win32-x64@0.21.5/node_modules/@esbuild/win32-x64/package.json b/node_modules/.pnpm/@esbuild+win32-x64@0.21.5/node_modules/@esbuild/win32-x64/package.json deleted file mode 100644 index 94abf8c..0000000 --- a/node_modules/.pnpm/@esbuild+win32-x64@0.21.5/node_modules/@esbuild/win32-x64/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "@esbuild/win32-x64", - "version": "0.21.5", - "description": "The Windows 64-bit binary for esbuild, a JavaScript bundler.", - "repository": { - "type": "git", - "url": "git+https://github.com/evanw/esbuild.git" - }, - "license": "MIT", - "preferUnplugged": true, - "engines": { - "node": ">=12" - }, - "os": [ - "win32" - ], - "cpu": [ - "x64" - ] -} diff --git a/node_modules/.pnpm/@rollup+rollup-win32-x64-msvc@4.40.2/node_modules/@rollup/rollup-win32-x64-msvc/README.md b/node_modules/.pnpm/@rollup+rollup-win32-x64-msvc@4.40.2/node_modules/@rollup/rollup-win32-x64-msvc/README.md deleted file mode 100644 index 7382dbc..0000000 --- a/node_modules/.pnpm/@rollup+rollup-win32-x64-msvc@4.40.2/node_modules/@rollup/rollup-win32-x64-msvc/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# `@rollup/rollup-win32-x64-msvc` - -This is the **x86_64-pc-windows-msvc** binary for `rollup` diff --git a/node_modules/.pnpm/@rollup+rollup-win32-x64-msvc@4.40.2/node_modules/@rollup/rollup-win32-x64-msvc/package.json b/node_modules/.pnpm/@rollup+rollup-win32-x64-msvc@4.40.2/node_modules/@rollup/rollup-win32-x64-msvc/package.json deleted file mode 100644 index e21bf40..0000000 --- a/node_modules/.pnpm/@rollup+rollup-win32-x64-msvc@4.40.2/node_modules/@rollup/rollup-win32-x64-msvc/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "@rollup/rollup-win32-x64-msvc", - "version": "4.40.2", - "os": [ - "win32" - ], - "cpu": [ - "x64" - ], - "files": [ - "rollup.win32-x64-msvc.node" - ], - "description": "Native bindings for Rollup", - "author": "Lukas Taegert-Atkinson", - "homepage": "https://rollupjs.org/", - "license": "MIT", - "repository": "rollup/rollup", - "main": "./rollup.win32-x64-msvc.node" -} \ No newline at end of file diff --git a/node_modules/.pnpm/@rollup+rollup-win32-x64-msvc@4.40.2/node_modules/@rollup/rollup-win32-x64-msvc/rollup.win32-x64-msvc.node b/node_modules/.pnpm/@rollup+rollup-win32-x64-msvc@4.40.2/node_modules/@rollup/rollup-win32-x64-msvc/rollup.win32-x64-msvc.node deleted file mode 100644 index 5a894e6..0000000 Binary files a/node_modules/.pnpm/@rollup+rollup-win32-x64-msvc@4.40.2/node_modules/@rollup/rollup-win32-x64-msvc/rollup.win32-x64-msvc.node and /dev/null differ diff --git a/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/LICENSE b/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/LICENSE deleted file mode 100644 index 9e841e7..0000000 --- a/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ - MIT License - - Copyright (c) Microsoft Corporation. - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE diff --git a/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/README.md b/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/README.md deleted file mode 100644 index b0baf5f..0000000 --- a/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# Installation -> `npm install --save @types/estree` - -# Summary -This package contains type definitions for estree (https://github.com/estree/estree). - -# Details -Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree. - -### Additional Details - * Last updated: Mon, 24 Mar 2025 07:34:10 GMT - * Dependencies: none - -# Credits -These definitions were written by [RReverser](https://github.com/RReverser). diff --git a/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/flow.d.ts b/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/flow.d.ts deleted file mode 100644 index 9d001a9..0000000 --- a/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/flow.d.ts +++ /dev/null @@ -1,167 +0,0 @@ -declare namespace ESTree { - interface FlowTypeAnnotation extends Node {} - - interface FlowBaseTypeAnnotation extends FlowTypeAnnotation {} - - interface FlowLiteralTypeAnnotation extends FlowTypeAnnotation, Literal {} - - interface FlowDeclaration extends Declaration {} - - interface AnyTypeAnnotation extends FlowBaseTypeAnnotation {} - - interface ArrayTypeAnnotation extends FlowTypeAnnotation { - elementType: FlowTypeAnnotation; - } - - interface BooleanLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} - - interface BooleanTypeAnnotation extends FlowBaseTypeAnnotation {} - - interface ClassImplements extends Node { - id: Identifier; - typeParameters?: TypeParameterInstantiation | null; - } - - interface ClassProperty { - key: Expression; - value?: Expression | null; - typeAnnotation?: TypeAnnotation | null; - computed: boolean; - static: boolean; - } - - interface DeclareClass extends FlowDeclaration { - id: Identifier; - typeParameters?: TypeParameterDeclaration | null; - body: ObjectTypeAnnotation; - extends: InterfaceExtends[]; - } - - interface DeclareFunction extends FlowDeclaration { - id: Identifier; - } - - interface DeclareModule extends FlowDeclaration { - id: Literal | Identifier; - body: BlockStatement; - } - - interface DeclareVariable extends FlowDeclaration { - id: Identifier; - } - - interface FunctionTypeAnnotation extends FlowTypeAnnotation { - params: FunctionTypeParam[]; - returnType: FlowTypeAnnotation; - rest?: FunctionTypeParam | null; - typeParameters?: TypeParameterDeclaration | null; - } - - interface FunctionTypeParam { - name: Identifier; - typeAnnotation: FlowTypeAnnotation; - optional: boolean; - } - - interface GenericTypeAnnotation extends FlowTypeAnnotation { - id: Identifier | QualifiedTypeIdentifier; - typeParameters?: TypeParameterInstantiation | null; - } - - interface InterfaceExtends extends Node { - id: Identifier | QualifiedTypeIdentifier; - typeParameters?: TypeParameterInstantiation | null; - } - - interface InterfaceDeclaration extends FlowDeclaration { - id: Identifier; - typeParameters?: TypeParameterDeclaration | null; - extends: InterfaceExtends[]; - body: ObjectTypeAnnotation; - } - - interface IntersectionTypeAnnotation extends FlowTypeAnnotation { - types: FlowTypeAnnotation[]; - } - - interface MixedTypeAnnotation extends FlowBaseTypeAnnotation {} - - interface NullableTypeAnnotation extends FlowTypeAnnotation { - typeAnnotation: TypeAnnotation; - } - - interface NumberLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} - - interface NumberTypeAnnotation extends FlowBaseTypeAnnotation {} - - interface StringLiteralTypeAnnotation extends FlowLiteralTypeAnnotation {} - - interface StringTypeAnnotation extends FlowBaseTypeAnnotation {} - - interface TupleTypeAnnotation extends FlowTypeAnnotation { - types: FlowTypeAnnotation[]; - } - - interface TypeofTypeAnnotation extends FlowTypeAnnotation { - argument: FlowTypeAnnotation; - } - - interface TypeAlias extends FlowDeclaration { - id: Identifier; - typeParameters?: TypeParameterDeclaration | null; - right: FlowTypeAnnotation; - } - - interface TypeAnnotation extends Node { - typeAnnotation: FlowTypeAnnotation; - } - - interface TypeCastExpression extends Expression { - expression: Expression; - typeAnnotation: TypeAnnotation; - } - - interface TypeParameterDeclaration extends Node { - params: Identifier[]; - } - - interface TypeParameterInstantiation extends Node { - params: FlowTypeAnnotation[]; - } - - interface ObjectTypeAnnotation extends FlowTypeAnnotation { - properties: ObjectTypeProperty[]; - indexers: ObjectTypeIndexer[]; - callProperties: ObjectTypeCallProperty[]; - } - - interface ObjectTypeCallProperty extends Node { - value: FunctionTypeAnnotation; - static: boolean; - } - - interface ObjectTypeIndexer extends Node { - id: Identifier; - key: FlowTypeAnnotation; - value: FlowTypeAnnotation; - static: boolean; - } - - interface ObjectTypeProperty extends Node { - key: Expression; - value: FlowTypeAnnotation; - optional: boolean; - static: boolean; - } - - interface QualifiedTypeIdentifier extends Node { - qualification: Identifier | QualifiedTypeIdentifier; - id: Identifier; - } - - interface UnionTypeAnnotation extends FlowTypeAnnotation { - types: FlowTypeAnnotation[]; - } - - interface VoidTypeAnnotation extends FlowBaseTypeAnnotation {} -} diff --git a/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/index.d.ts b/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/index.d.ts deleted file mode 100644 index 1c13265..0000000 --- a/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/index.d.ts +++ /dev/null @@ -1,694 +0,0 @@ -// This definition file follows a somewhat unusual format. ESTree allows -// runtime type checks based on the `type` parameter. In order to explain this -// to typescript we want to use discriminated union types: -// https://github.com/Microsoft/TypeScript/pull/9163 -// -// For ESTree this is a bit tricky because the high level interfaces like -// Node or Function are pulling double duty. We want to pass common fields down -// to the interfaces that extend them (like Identifier or -// ArrowFunctionExpression), but you can't extend a type union or enforce -// common fields on them. So we've split the high level interfaces into two -// types, a base type which passes down inherited fields, and a type union of -// all types which extend the base type. Only the type union is exported, and -// the union is how other types refer to the collection of inheriting types. -// -// This makes the definitions file here somewhat more difficult to maintain, -// but it has the notable advantage of making ESTree much easier to use as -// an end user. - -export interface BaseNodeWithoutComments { - // Every leaf interface that extends BaseNode must specify a type property. - // The type property should be a string literal. For example, Identifier - // has: `type: "Identifier"` - type: string; - loc?: SourceLocation | null | undefined; - range?: [number, number] | undefined; -} - -export interface BaseNode extends BaseNodeWithoutComments { - leadingComments?: Comment[] | undefined; - trailingComments?: Comment[] | undefined; -} - -export interface NodeMap { - AssignmentProperty: AssignmentProperty; - CatchClause: CatchClause; - Class: Class; - ClassBody: ClassBody; - Expression: Expression; - Function: Function; - Identifier: Identifier; - Literal: Literal; - MethodDefinition: MethodDefinition; - ModuleDeclaration: ModuleDeclaration; - ModuleSpecifier: ModuleSpecifier; - Pattern: Pattern; - PrivateIdentifier: PrivateIdentifier; - Program: Program; - Property: Property; - PropertyDefinition: PropertyDefinition; - SpreadElement: SpreadElement; - Statement: Statement; - Super: Super; - SwitchCase: SwitchCase; - TemplateElement: TemplateElement; - VariableDeclarator: VariableDeclarator; -} - -export type Node = NodeMap[keyof NodeMap]; - -export interface Comment extends BaseNodeWithoutComments { - type: "Line" | "Block"; - value: string; -} - -export interface SourceLocation { - source?: string | null | undefined; - start: Position; - end: Position; -} - -export interface Position { - /** >= 1 */ - line: number; - /** >= 0 */ - column: number; -} - -export interface Program extends BaseNode { - type: "Program"; - sourceType: "script" | "module"; - body: Array; - comments?: Comment[] | undefined; -} - -export interface Directive extends BaseNode { - type: "ExpressionStatement"; - expression: Literal; - directive: string; -} - -export interface BaseFunction extends BaseNode { - params: Pattern[]; - generator?: boolean | undefined; - async?: boolean | undefined; - // The body is either BlockStatement or Expression because arrow functions - // can have a body that's either. FunctionDeclarations and - // FunctionExpressions have only BlockStatement bodies. - body: BlockStatement | Expression; -} - -export type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression; - -export type Statement = - | ExpressionStatement - | BlockStatement - | StaticBlock - | EmptyStatement - | DebuggerStatement - | WithStatement - | ReturnStatement - | LabeledStatement - | BreakStatement - | ContinueStatement - | IfStatement - | SwitchStatement - | ThrowStatement - | TryStatement - | WhileStatement - | DoWhileStatement - | ForStatement - | ForInStatement - | ForOfStatement - | Declaration; - -export interface BaseStatement extends BaseNode {} - -export interface EmptyStatement extends BaseStatement { - type: "EmptyStatement"; -} - -export interface BlockStatement extends BaseStatement { - type: "BlockStatement"; - body: Statement[]; - innerComments?: Comment[] | undefined; -} - -export interface StaticBlock extends Omit { - type: "StaticBlock"; -} - -export interface ExpressionStatement extends BaseStatement { - type: "ExpressionStatement"; - expression: Expression; -} - -export interface IfStatement extends BaseStatement { - type: "IfStatement"; - test: Expression; - consequent: Statement; - alternate?: Statement | null | undefined; -} - -export interface LabeledStatement extends BaseStatement { - type: "LabeledStatement"; - label: Identifier; - body: Statement; -} - -export interface BreakStatement extends BaseStatement { - type: "BreakStatement"; - label?: Identifier | null | undefined; -} - -export interface ContinueStatement extends BaseStatement { - type: "ContinueStatement"; - label?: Identifier | null | undefined; -} - -export interface WithStatement extends BaseStatement { - type: "WithStatement"; - object: Expression; - body: Statement; -} - -export interface SwitchStatement extends BaseStatement { - type: "SwitchStatement"; - discriminant: Expression; - cases: SwitchCase[]; -} - -export interface ReturnStatement extends BaseStatement { - type: "ReturnStatement"; - argument?: Expression | null | undefined; -} - -export interface ThrowStatement extends BaseStatement { - type: "ThrowStatement"; - argument: Expression; -} - -export interface TryStatement extends BaseStatement { - type: "TryStatement"; - block: BlockStatement; - handler?: CatchClause | null | undefined; - finalizer?: BlockStatement | null | undefined; -} - -export interface WhileStatement extends BaseStatement { - type: "WhileStatement"; - test: Expression; - body: Statement; -} - -export interface DoWhileStatement extends BaseStatement { - type: "DoWhileStatement"; - body: Statement; - test: Expression; -} - -export interface ForStatement extends BaseStatement { - type: "ForStatement"; - init?: VariableDeclaration | Expression | null | undefined; - test?: Expression | null | undefined; - update?: Expression | null | undefined; - body: Statement; -} - -export interface BaseForXStatement extends BaseStatement { - left: VariableDeclaration | Pattern; - right: Expression; - body: Statement; -} - -export interface ForInStatement extends BaseForXStatement { - type: "ForInStatement"; -} - -export interface DebuggerStatement extends BaseStatement { - type: "DebuggerStatement"; -} - -export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration; - -export interface BaseDeclaration extends BaseStatement {} - -export interface MaybeNamedFunctionDeclaration extends BaseFunction, BaseDeclaration { - type: "FunctionDeclaration"; - /** It is null when a function declaration is a part of the `export default function` statement */ - id: Identifier | null; - body: BlockStatement; -} - -export interface FunctionDeclaration extends MaybeNamedFunctionDeclaration { - id: Identifier; -} - -export interface VariableDeclaration extends BaseDeclaration { - type: "VariableDeclaration"; - declarations: VariableDeclarator[]; - kind: "var" | "let" | "const"; -} - -export interface VariableDeclarator extends BaseNode { - type: "VariableDeclarator"; - id: Pattern; - init?: Expression | null | undefined; -} - -export interface ExpressionMap { - ArrayExpression: ArrayExpression; - ArrowFunctionExpression: ArrowFunctionExpression; - AssignmentExpression: AssignmentExpression; - AwaitExpression: AwaitExpression; - BinaryExpression: BinaryExpression; - CallExpression: CallExpression; - ChainExpression: ChainExpression; - ClassExpression: ClassExpression; - ConditionalExpression: ConditionalExpression; - FunctionExpression: FunctionExpression; - Identifier: Identifier; - ImportExpression: ImportExpression; - Literal: Literal; - LogicalExpression: LogicalExpression; - MemberExpression: MemberExpression; - MetaProperty: MetaProperty; - NewExpression: NewExpression; - ObjectExpression: ObjectExpression; - SequenceExpression: SequenceExpression; - TaggedTemplateExpression: TaggedTemplateExpression; - TemplateLiteral: TemplateLiteral; - ThisExpression: ThisExpression; - UnaryExpression: UnaryExpression; - UpdateExpression: UpdateExpression; - YieldExpression: YieldExpression; -} - -export type Expression = ExpressionMap[keyof ExpressionMap]; - -export interface BaseExpression extends BaseNode {} - -export type ChainElement = SimpleCallExpression | MemberExpression; - -export interface ChainExpression extends BaseExpression { - type: "ChainExpression"; - expression: ChainElement; -} - -export interface ThisExpression extends BaseExpression { - type: "ThisExpression"; -} - -export interface ArrayExpression extends BaseExpression { - type: "ArrayExpression"; - elements: Array; -} - -export interface ObjectExpression extends BaseExpression { - type: "ObjectExpression"; - properties: Array; -} - -export interface PrivateIdentifier extends BaseNode { - type: "PrivateIdentifier"; - name: string; -} - -export interface Property extends BaseNode { - type: "Property"; - key: Expression | PrivateIdentifier; - value: Expression | Pattern; // Could be an AssignmentProperty - kind: "init" | "get" | "set"; - method: boolean; - shorthand: boolean; - computed: boolean; -} - -export interface PropertyDefinition extends BaseNode { - type: "PropertyDefinition"; - key: Expression | PrivateIdentifier; - value?: Expression | null | undefined; - computed: boolean; - static: boolean; -} - -export interface FunctionExpression extends BaseFunction, BaseExpression { - id?: Identifier | null | undefined; - type: "FunctionExpression"; - body: BlockStatement; -} - -export interface SequenceExpression extends BaseExpression { - type: "SequenceExpression"; - expressions: Expression[]; -} - -export interface UnaryExpression extends BaseExpression { - type: "UnaryExpression"; - operator: UnaryOperator; - prefix: true; - argument: Expression; -} - -export interface BinaryExpression extends BaseExpression { - type: "BinaryExpression"; - operator: BinaryOperator; - left: Expression | PrivateIdentifier; - right: Expression; -} - -export interface AssignmentExpression extends BaseExpression { - type: "AssignmentExpression"; - operator: AssignmentOperator; - left: Pattern | MemberExpression; - right: Expression; -} - -export interface UpdateExpression extends BaseExpression { - type: "UpdateExpression"; - operator: UpdateOperator; - argument: Expression; - prefix: boolean; -} - -export interface LogicalExpression extends BaseExpression { - type: "LogicalExpression"; - operator: LogicalOperator; - left: Expression; - right: Expression; -} - -export interface ConditionalExpression extends BaseExpression { - type: "ConditionalExpression"; - test: Expression; - alternate: Expression; - consequent: Expression; -} - -export interface BaseCallExpression extends BaseExpression { - callee: Expression | Super; - arguments: Array; -} -export type CallExpression = SimpleCallExpression | NewExpression; - -export interface SimpleCallExpression extends BaseCallExpression { - type: "CallExpression"; - optional: boolean; -} - -export interface NewExpression extends BaseCallExpression { - type: "NewExpression"; -} - -export interface MemberExpression extends BaseExpression, BasePattern { - type: "MemberExpression"; - object: Expression | Super; - property: Expression | PrivateIdentifier; - computed: boolean; - optional: boolean; -} - -export type Pattern = Identifier | ObjectPattern | ArrayPattern | RestElement | AssignmentPattern | MemberExpression; - -export interface BasePattern extends BaseNode {} - -export interface SwitchCase extends BaseNode { - type: "SwitchCase"; - test?: Expression | null | undefined; - consequent: Statement[]; -} - -export interface CatchClause extends BaseNode { - type: "CatchClause"; - param: Pattern | null; - body: BlockStatement; -} - -export interface Identifier extends BaseNode, BaseExpression, BasePattern { - type: "Identifier"; - name: string; -} - -export type Literal = SimpleLiteral | RegExpLiteral | BigIntLiteral; - -export interface SimpleLiteral extends BaseNode, BaseExpression { - type: "Literal"; - value: string | boolean | number | null; - raw?: string | undefined; -} - -export interface RegExpLiteral extends BaseNode, BaseExpression { - type: "Literal"; - value?: RegExp | null | undefined; - regex: { - pattern: string; - flags: string; - }; - raw?: string | undefined; -} - -export interface BigIntLiteral extends BaseNode, BaseExpression { - type: "Literal"; - value?: bigint | null | undefined; - bigint: string; - raw?: string | undefined; -} - -export type UnaryOperator = "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"; - -export type BinaryOperator = - | "==" - | "!=" - | "===" - | "!==" - | "<" - | "<=" - | ">" - | ">=" - | "<<" - | ">>" - | ">>>" - | "+" - | "-" - | "*" - | "/" - | "%" - | "**" - | "|" - | "^" - | "&" - | "in" - | "instanceof"; - -export type LogicalOperator = "||" | "&&" | "??"; - -export type AssignmentOperator = - | "=" - | "+=" - | "-=" - | "*=" - | "/=" - | "%=" - | "**=" - | "<<=" - | ">>=" - | ">>>=" - | "|=" - | "^=" - | "&=" - | "||=" - | "&&=" - | "??="; - -export type UpdateOperator = "++" | "--"; - -export interface ForOfStatement extends BaseForXStatement { - type: "ForOfStatement"; - await: boolean; -} - -export interface Super extends BaseNode { - type: "Super"; -} - -export interface SpreadElement extends BaseNode { - type: "SpreadElement"; - argument: Expression; -} - -export interface ArrowFunctionExpression extends BaseExpression, BaseFunction { - type: "ArrowFunctionExpression"; - expression: boolean; - body: BlockStatement | Expression; -} - -export interface YieldExpression extends BaseExpression { - type: "YieldExpression"; - argument?: Expression | null | undefined; - delegate: boolean; -} - -export interface TemplateLiteral extends BaseExpression { - type: "TemplateLiteral"; - quasis: TemplateElement[]; - expressions: Expression[]; -} - -export interface TaggedTemplateExpression extends BaseExpression { - type: "TaggedTemplateExpression"; - tag: Expression; - quasi: TemplateLiteral; -} - -export interface TemplateElement extends BaseNode { - type: "TemplateElement"; - tail: boolean; - value: { - /** It is null when the template literal is tagged and the text has an invalid escape (e.g. - tag`\unicode and \u{55}`) */ - cooked?: string | null | undefined; - raw: string; - }; -} - -export interface AssignmentProperty extends Property { - value: Pattern; - kind: "init"; - method: boolean; // false -} - -export interface ObjectPattern extends BasePattern { - type: "ObjectPattern"; - properties: Array; -} - -export interface ArrayPattern extends BasePattern { - type: "ArrayPattern"; - elements: Array; -} - -export interface RestElement extends BasePattern { - type: "RestElement"; - argument: Pattern; -} - -export interface AssignmentPattern extends BasePattern { - type: "AssignmentPattern"; - left: Pattern; - right: Expression; -} - -export type Class = ClassDeclaration | ClassExpression; -export interface BaseClass extends BaseNode { - superClass?: Expression | null | undefined; - body: ClassBody; -} - -export interface ClassBody extends BaseNode { - type: "ClassBody"; - body: Array; -} - -export interface MethodDefinition extends BaseNode { - type: "MethodDefinition"; - key: Expression | PrivateIdentifier; - value: FunctionExpression; - kind: "constructor" | "method" | "get" | "set"; - computed: boolean; - static: boolean; -} - -export interface MaybeNamedClassDeclaration extends BaseClass, BaseDeclaration { - type: "ClassDeclaration"; - /** It is null when a class declaration is a part of the `export default class` statement */ - id: Identifier | null; -} - -export interface ClassDeclaration extends MaybeNamedClassDeclaration { - id: Identifier; -} - -export interface ClassExpression extends BaseClass, BaseExpression { - type: "ClassExpression"; - id?: Identifier | null | undefined; -} - -export interface MetaProperty extends BaseExpression { - type: "MetaProperty"; - meta: Identifier; - property: Identifier; -} - -export type ModuleDeclaration = - | ImportDeclaration - | ExportNamedDeclaration - | ExportDefaultDeclaration - | ExportAllDeclaration; -export interface BaseModuleDeclaration extends BaseNode {} - -export type ModuleSpecifier = ImportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ExportSpecifier; -export interface BaseModuleSpecifier extends BaseNode { - local: Identifier; -} - -export interface ImportDeclaration extends BaseModuleDeclaration { - type: "ImportDeclaration"; - specifiers: Array; - attributes: ImportAttribute[]; - source: Literal; -} - -export interface ImportSpecifier extends BaseModuleSpecifier { - type: "ImportSpecifier"; - imported: Identifier | Literal; -} - -export interface ImportAttribute extends BaseNode { - type: "ImportAttribute"; - key: Identifier | Literal; - value: Literal; -} - -export interface ImportExpression extends BaseExpression { - type: "ImportExpression"; - source: Expression; - options?: Expression | null | undefined; -} - -export interface ImportDefaultSpecifier extends BaseModuleSpecifier { - type: "ImportDefaultSpecifier"; -} - -export interface ImportNamespaceSpecifier extends BaseModuleSpecifier { - type: "ImportNamespaceSpecifier"; -} - -export interface ExportNamedDeclaration extends BaseModuleDeclaration { - type: "ExportNamedDeclaration"; - declaration?: Declaration | null | undefined; - specifiers: ExportSpecifier[]; - attributes: ImportAttribute[]; - source?: Literal | null | undefined; -} - -export interface ExportSpecifier extends Omit { - type: "ExportSpecifier"; - local: Identifier | Literal; - exported: Identifier | Literal; -} - -export interface ExportDefaultDeclaration extends BaseModuleDeclaration { - type: "ExportDefaultDeclaration"; - declaration: MaybeNamedFunctionDeclaration | MaybeNamedClassDeclaration | Expression; -} - -export interface ExportAllDeclaration extends BaseModuleDeclaration { - type: "ExportAllDeclaration"; - exported: Identifier | Literal | null; - attributes: ImportAttribute[]; - source: Literal; -} - -export interface AwaitExpression extends BaseExpression { - type: "AwaitExpression"; - argument: Expression; -} diff --git a/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/package.json b/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/package.json deleted file mode 100644 index 61ce23a..0000000 --- a/node_modules/.pnpm/@types+estree@1.0.7/node_modules/@types/estree/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "@types/estree", - "version": "1.0.7", - "description": "TypeScript definitions for estree", - "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/estree", - "license": "MIT", - "contributors": [ - { - "name": "RReverser", - "githubUsername": "RReverser", - "url": "https://github.com/RReverser" - } - ], - "main": "", - "types": "index.d.ts", - "repository": { - "type": "git", - "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", - "directory": "types/estree" - }, - "scripts": {}, - "dependencies": {}, - "peerDependencies": {}, - "typesPublisherContentHash": "1ab11f4e78319f80655b4ca20a073da0dc035be5f3290fb0bfa1e08a055d0c7d", - "typeScriptVersion": "5.0", - "nonNpm": true -} \ No newline at end of file diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/application.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/application.js deleted file mode 100644 index a017d4a..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/application.js +++ /dev/null @@ -1,32 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -import { newRuntimeCaller, objectNames } from "./runtime.js"; -const call = newRuntimeCaller(objectNames.Application); -const HideMethod = 0; -const ShowMethod = 1; -const QuitMethod = 2; -/** - * Hides a certain method by calling the HideMethod function. - */ -export function Hide() { - return call(HideMethod); -} -/** - * Calls the ShowMethod and returns the result. - */ -export function Show() { - return call(ShowMethod); -} -/** - * Calls the QuitMethod to terminate the program. - */ -export function Quit() { - return call(QuitMethod); -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/browser.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/browser.js deleted file mode 100644 index 6339890..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/browser.js +++ /dev/null @@ -1,20 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -import { newRuntimeCaller, objectNames } from "./runtime.js"; -const call = newRuntimeCaller(objectNames.Browser); -const BrowserOpenURL = 0; -/** - * Open a browser window to the given URL. - * - * @param url - The URL to open - */ -export function OpenURL(url) { - return call(BrowserOpenURL, { url: url.toString() }); -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/callable.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/callable.js deleted file mode 100644 index c382735..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/callable.js +++ /dev/null @@ -1,144 +0,0 @@ -// Source: https://github.com/inspect-js/is-callable -// The MIT License (MIT) -// -// Copyright (c) 2015 Jordan Harband -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -// SOFTWARE. -var fnToStr = Function.prototype.toString; -var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply; -var badArrayLike; -var isCallableMarker; -if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') { - try { - badArrayLike = Object.defineProperty({}, 'length', { - get: function () { - throw isCallableMarker; - } - }); - isCallableMarker = {}; - // eslint-disable-next-line no-throw-literal - reflectApply(function () { throw 42; }, null, badArrayLike); - } - catch (_) { - if (_ !== isCallableMarker) { - reflectApply = null; - } - } -} -else { - reflectApply = null; -} -var constructorRegex = /^\s*class\b/; -var isES6ClassFn = function isES6ClassFunction(value) { - try { - var fnStr = fnToStr.call(value); - return constructorRegex.test(fnStr); - } - catch (e) { - return false; // not a function - } -}; -var tryFunctionObject = function tryFunctionToStr(value) { - try { - if (isES6ClassFn(value)) { - return false; - } - fnToStr.call(value); - return true; - } - catch (e) { - return false; - } -}; -var toStr = Object.prototype.toString; -var objectClass = '[object Object]'; -var fnClass = '[object Function]'; -var genClass = '[object GeneratorFunction]'; -var ddaClass = '[object HTMLAllCollection]'; // IE 11 -var ddaClass2 = '[object HTML document.all class]'; -var ddaClass3 = '[object HTMLCollection]'; // IE 9-10 -var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag` -var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing -var isDDA = function isDocumentDotAll() { return false; }; -if (typeof document === 'object') { - // Firefox 3 canonicalizes DDA to undefined when it's not accessed directly - var all = document.all; - if (toStr.call(all) === toStr.call(document.all)) { - isDDA = function isDocumentDotAll(value) { - /* globals document: false */ - // in IE 6-8, typeof document.all is "object" and it's truthy - if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) { - try { - var str = toStr.call(value); - return (str === ddaClass - || str === ddaClass2 - || str === ddaClass3 // opera 12.16 - || str === objectClass // IE 6-8 - ) && value('') == null; // eslint-disable-line eqeqeq - } - catch (e) { /**/ } - } - return false; - }; - } -} -function isCallableRefApply(value) { - if (isDDA(value)) { - return true; - } - if (!value) { - return false; - } - if (typeof value !== 'function' && typeof value !== 'object') { - return false; - } - try { - reflectApply(value, null, badArrayLike); - } - catch (e) { - if (e !== isCallableMarker) { - return false; - } - } - return !isES6ClassFn(value) && tryFunctionObject(value); -} -function isCallableNoRefApply(value) { - if (isDDA(value)) { - return true; - } - if (!value) { - return false; - } - if (typeof value !== 'function' && typeof value !== 'object') { - return false; - } - if (hasToStringTag) { - return tryFunctionObject(value); - } - if (isES6ClassFn(value)) { - return false; - } - var strClass = toStr.call(value); - if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { - return false; - } - return tryFunctionObject(value); -} -; -export default reflectApply ? isCallableRefApply : isCallableNoRefApply; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/calls.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/calls.js deleted file mode 100644 index a6777fa..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/calls.js +++ /dev/null @@ -1,194 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -import { CancellablePromise } from "./cancellable.js"; -import { newRuntimeCaller, objectNames } from "./runtime.js"; -import { nanoid } from "./nanoid.js"; -// Setup -window._wails = window._wails || {}; -window._wails.callResultHandler = resultHandler; -window._wails.callErrorHandler = errorHandler; -const call = newRuntimeCaller(objectNames.Call); -const cancelCall = newRuntimeCaller(objectNames.CancelCall); -const callResponses = new Map(); -const CallBinding = 0; -const CancelMethod = 0; -/** - * Exception class that will be thrown in case the bound method returns an error. - * The value of the {@link RuntimeError#name} property is "RuntimeError". - */ -export class RuntimeError extends Error { - /** - * Constructs a new RuntimeError instance. - * @param message - The error message. - * @param options - Options to be forwarded to the Error constructor. - */ - constructor(message, options) { - super(message, options); - this.name = "RuntimeError"; - } -} -/** - * Handles the result of a call request. - * - * @param id - The id of the request to handle the result for. - * @param data - The result data of the request. - * @param isJSON - Indicates whether the data is JSON or not. - */ -function resultHandler(id, data, isJSON) { - const resolvers = getAndDeleteResponse(id); - if (!resolvers) { - return; - } - if (!data) { - resolvers.resolve(undefined); - } - else if (!isJSON) { - resolvers.resolve(data); - } - else { - try { - resolvers.resolve(JSON.parse(data)); - } - catch (err) { - resolvers.reject(new TypeError("could not parse result: " + err.message, { cause: err })); - } - } -} -/** - * Handles the error from a call request. - * - * @param id - The id of the promise handler. - * @param data - The error data to reject the promise handler with. - * @param isJSON - Indicates whether the data is JSON or not. - */ -function errorHandler(id, data, isJSON) { - const resolvers = getAndDeleteResponse(id); - if (!resolvers) { - return; - } - if (!isJSON) { - resolvers.reject(new Error(data)); - } - else { - let error; - try { - error = JSON.parse(data); - } - catch (err) { - resolvers.reject(new TypeError("could not parse error: " + err.message, { cause: err })); - return; - } - let options = {}; - if (error.cause) { - options.cause = error.cause; - } - let exception; - switch (error.kind) { - case "ReferenceError": - exception = new ReferenceError(error.message, options); - break; - case "TypeError": - exception = new TypeError(error.message, options); - break; - case "RuntimeError": - exception = new RuntimeError(error.message, options); - break; - default: - exception = new Error(error.message, options); - break; - } - resolvers.reject(exception); - } -} -/** - * Retrieves and removes the response associated with the given ID from the callResponses map. - * - * @param id - The ID of the response to be retrieved and removed. - * @returns The response object associated with the given ID, if any. - */ -function getAndDeleteResponse(id) { - const response = callResponses.get(id); - callResponses.delete(id); - return response; -} -/** - * Generates a unique ID using the nanoid library. - * - * @returns A unique ID that does not exist in the callResponses set. - */ -function generateID() { - let result; - do { - result = nanoid(); - } while (callResponses.has(result)); - return result; -} -/** - * Call a bound method according to the given call options. - * - * In case of failure, the returned promise will reject with an exception - * among ReferenceError (unknown method), TypeError (wrong argument count or type), - * {@link RuntimeError} (method returned an error), or other (network or internal errors). - * The exception might have a "cause" field with the value returned - * by the application- or service-level error marshaling functions. - * - * @param options - A method call descriptor. - * @returns The result of the call. - */ -export function Call(options) { - const id = generateID(); - const result = CancellablePromise.withResolvers(); - callResponses.set(id, { resolve: result.resolve, reject: result.reject }); - const request = call(CallBinding, Object.assign({ "call-id": id }, options)); - let running = false; - request.then(() => { - running = true; - }, (err) => { - callResponses.delete(id); - result.reject(err); - }); - const cancel = () => { - callResponses.delete(id); - return cancelCall(CancelMethod, { "call-id": id }).catch((err) => { - console.error("Error while requesting binding call cancellation:", err); - }); - }; - result.oncancelled = () => { - if (running) { - return cancel(); - } - else { - return request.then(cancel); - } - }; - return result.promise; -} -/** - * Calls a bound method by name with the specified arguments. - * See {@link Call} for details. - * - * @param methodName - The name of the method in the format 'package.struct.method'. - * @param args - The arguments to pass to the method. - * @returns The result of the method call. - */ -export function ByName(methodName, ...args) { - return Call({ methodName, args }); -} -/** - * Calls a method by its numeric ID with the specified arguments. - * See {@link Call} for details. - * - * @param methodID - The ID of the method to call. - * @param args - The arguments to pass to the method. - * @return The result of the method call. - */ -export function ByID(methodID, ...args) { - return Call({ methodID, args }); -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/cancellable.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/cancellable.js deleted file mode 100644 index 834cb94..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/cancellable.js +++ /dev/null @@ -1,792 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -var _a; -import isCallable from "./callable.js"; -/** - * Exception class that will be used as rejection reason - * in case a {@link CancellablePromise} is cancelled successfully. - * - * The value of the {@link name} property is the string `"CancelError"`. - * The value of the {@link cause} property is the cause passed to the cancel method, if any. - */ -export class CancelError extends Error { - /** - * Constructs a new `CancelError` instance. - * @param message - The error message. - * @param options - Options to be forwarded to the Error constructor. - */ - constructor(message, options) { - super(message, options); - this.name = "CancelError"; - } -} -/** - * Exception class that will be reported as an unhandled rejection - * in case a {@link CancellablePromise} rejects after being cancelled, - * or when the `oncancelled` callback throws or rejects. - * - * The value of the {@link name} property is the string `"CancelledRejectionError"`. - * The value of the {@link cause} property is the reason the promise rejected with. - * - * Because the original promise was cancelled, - * a wrapper promise will be passed to the unhandled rejection listener instead. - * The {@link promise} property holds a reference to the original promise. - */ -export class CancelledRejectionError extends Error { - /** - * Constructs a new `CancelledRejectionError` instance. - * @param promise - The promise that caused the error originally. - * @param reason - The rejection reason. - * @param info - An optional informative message specifying the circumstances in which the error was thrown. - * Defaults to the string `"Unhandled rejection in cancelled promise."`. - */ - constructor(promise, reason, info) { - super((info !== null && info !== void 0 ? info : "Unhandled rejection in cancelled promise.") + " Reason: " + errorMessage(reason), { cause: reason }); - this.promise = promise; - this.name = "CancelledRejectionError"; - } -} -// Private field names. -const barrierSym = Symbol("barrier"); -const cancelImplSym = Symbol("cancelImpl"); -const species = (_a = Symbol.species) !== null && _a !== void 0 ? _a : Symbol("speciesPolyfill"); -/** - * A promise with an attached method for cancelling long-running operations (see {@link CancellablePromise#cancel}). - * Cancellation can optionally be bound to an {@link AbortSignal} - * for better composability (see {@link CancellablePromise#cancelOn}). - * - * Cancelling a pending promise will result in an immediate rejection - * with an instance of {@link CancelError} as reason, - * but whoever started the promise will be responsible - * for actually aborting the underlying operation. - * To this purpose, the constructor and all chaining methods - * accept optional cancellation callbacks. - * - * If a `CancellablePromise` still resolves after having been cancelled, - * the result will be discarded. If it rejects, the reason - * will be reported as an unhandled rejection, - * wrapped in a {@link CancelledRejectionError} instance. - * To facilitate the handling of cancellation requests, - * cancelled `CancellablePromise`s will _not_ report unhandled `CancelError`s - * whose `cause` field is the same as the one with which the current promise was cancelled. - * - * All usual promise methods are defined and return a `CancellablePromise` - * whose cancel method will cancel the parent operation as well, propagating the cancellation reason - * upwards through promise chains. - * Conversely, cancelling a promise will not automatically cancel dependent promises downstream: - * ```ts - * let root = new CancellablePromise((resolve, reject) => { ... }); - * let child1 = root.then(() => { ... }); - * let child2 = child1.then(() => { ... }); - * let child3 = root.catch(() => { ... }); - * child1.cancel(); // Cancels child1 and root, but not child2 or child3 - * ``` - * Cancelling a promise that has already settled is safe and has no consequence. - * - * The `cancel` method returns a promise that _always fulfills_ - * after the whole chain has processed the cancel request - * and all attached callbacks up to that moment have run. - * - * All ES2024 promise methods (static and instance) are defined on CancellablePromise, - * but actual availability may vary with OS/webview version. - * - * In line with the proposal at https://github.com/tc39/proposal-rm-builtin-subclassing, - * `CancellablePromise` does not support transparent subclassing. - * Extenders should take care to provide their own method implementations. - * This might be reconsidered in case the proposal is retired. - * - * CancellablePromise is a wrapper around the DOM Promise object - * and is compliant with the [Promises/A+ specification](https://promisesaplus.com/) - * (it passes the [compliance suite](https://github.com/promises-aplus/promises-tests)) - * if so is the underlying implementation. - */ -export class CancellablePromise extends Promise { - /** - * Creates a new `CancellablePromise`. - * - * @param executor - A callback used to initialize the promise. This callback is passed two arguments: - * a `resolve` callback used to resolve the promise with a value - * or the result of another promise (possibly cancellable), - * and a `reject` callback used to reject the promise with a provided reason or error. - * If the value provided to the `resolve` callback is a thenable _and_ cancellable object - * (it has a `then` _and_ a `cancel` method), - * cancellation requests will be forwarded to that object and the oncancelled will not be invoked anymore. - * If any one of the two callbacks is called _after_ the promise has been cancelled, - * the provided values will be cancelled and resolved as usual, - * but their results will be discarded. - * However, if the resolution process ultimately ends up in a rejection - * that is not due to cancellation, the rejection reason - * will be wrapped in a {@link CancelledRejectionError} - * and bubbled up as an unhandled rejection. - * @param oncancelled - It is the caller's responsibility to ensure that any operation - * started by the executor is properly halted upon cancellation. - * This optional callback can be used to that purpose. - * It will be called _synchronously_ with a cancellation cause - * when cancellation is requested, _after_ the promise has already rejected - * with a {@link CancelError}, but _before_ - * any {@link then}/{@link catch}/{@link finally} callback runs. - * If the callback returns a thenable, the promise returned from {@link cancel} - * will only fulfill after the former has settled. - * Unhandled exceptions or rejections from the callback will be wrapped - * in a {@link CancelledRejectionError} and bubbled up as unhandled rejections. - * If the `resolve` callback is called before cancellation with a cancellable promise, - * cancellation requests on this promise will be diverted to that promise, - * and the original `oncancelled` callback will be discarded. - */ - constructor(executor, oncancelled) { - let resolve; - let reject; - super((res, rej) => { resolve = res; reject = rej; }); - if (this.constructor[species] !== Promise) { - throw new TypeError("CancellablePromise does not support transparent subclassing. Please refrain from overriding the [Symbol.species] static property."); - } - let promise = { - promise: this, - resolve, - reject, - get oncancelled() { return oncancelled !== null && oncancelled !== void 0 ? oncancelled : null; }, - set oncancelled(cb) { oncancelled = cb !== null && cb !== void 0 ? cb : undefined; } - }; - const state = { - get root() { return state; }, - resolving: false, - settled: false - }; - // Setup cancellation system. - void Object.defineProperties(this, { - [barrierSym]: { - configurable: false, - enumerable: false, - writable: true, - value: null - }, - [cancelImplSym]: { - configurable: false, - enumerable: false, - writable: false, - value: cancellerFor(promise, state) - } - }); - // Run the actual executor. - const rejector = rejectorFor(promise, state); - try { - executor(resolverFor(promise, state), rejector); - } - catch (err) { - if (state.resolving) { - console.log("Unhandled exception in CancellablePromise executor.", err); - } - else { - rejector(err); - } - } - } - /** - * Cancels immediately the execution of the operation associated with this promise. - * The promise rejects with a {@link CancelError} instance as reason, - * with the {@link CancelError#cause} property set to the given argument, if any. - * - * Has no effect if called after the promise has already settled; - * repeated calls in particular are safe, but only the first one - * will set the cancellation cause. - * - * The `CancelError` exception _need not_ be handled explicitly _on the promises that are being cancelled:_ - * cancelling a promise with no attached rejection handler does not trigger an unhandled rejection event. - * Therefore, the following idioms are all equally correct: - * ```ts - * new CancellablePromise((resolve, reject) => { ... }).cancel(); - * new CancellablePromise((resolve, reject) => { ... }).then(...).cancel(); - * new CancellablePromise((resolve, reject) => { ... }).then(...).catch(...).cancel(); - * ``` - * Whenever some cancelled promise in a chain rejects with a `CancelError` - * with the same cancellation cause as itself, the error will be discarded silently. - * However, the `CancelError` _will still be delivered_ to all attached rejection handlers - * added by {@link then} and related methods: - * ```ts - * let cancellable = new CancellablePromise((resolve, reject) => { ... }); - * cancellable.then(() => { ... }).catch(console.log); - * cancellable.cancel(); // A CancelError is printed to the console. - * ``` - * If the `CancelError` is not handled downstream by the time it reaches - * a _non-cancelled_ promise, it _will_ trigger an unhandled rejection event, - * just like normal rejections would: - * ```ts - * let cancellable = new CancellablePromise((resolve, reject) => { ... }); - * let chained = cancellable.then(() => { ... }).then(() => { ... }); // No catch... - * cancellable.cancel(); // Unhandled rejection event on chained! - * ``` - * Therefore, it is important to either cancel whole promise chains from their tail, - * as shown in the correct idioms above, or take care of handling errors everywhere. - * - * @returns A cancellable promise that _fulfills_ after the cancel callback (if any) - * and all handlers attached up to the call to cancel have run. - * If the cancel callback returns a thenable, the promise returned by `cancel` - * will also wait for that thenable to settle. - * This enables callers to wait for the cancelled operation to terminate - * without being forced to handle potential errors at the call site. - * ```ts - * cancellable.cancel().then(() => { - * // Cleanup finished, it's safe to do something else. - * }, (err) => { - * // Unreachable: the promise returned from cancel will never reject. - * }); - * ``` - * Note that the returned promise will _not_ handle implicitly any rejection - * that might have occurred already in the cancelled chain. - * It will just track whether registered handlers have been executed or not. - * Therefore, unhandled rejections will never be silently handled by calling cancel. - */ - cancel(cause) { - return new CancellablePromise((resolve) => { - // INVARIANT: the result of this[cancelImplSym] and the barrier do not ever reject. - // Unfortunately macOS High Sierra does not support Promise.allSettled. - Promise.all([ - this[cancelImplSym](new CancelError("Promise cancelled.", { cause })), - currentBarrier(this) - ]).then(() => resolve(), () => resolve()); - }); - } - /** - * Binds promise cancellation to the abort event of the given {@link AbortSignal}. - * If the signal has already aborted, the promise will be cancelled immediately. - * When either condition is verified, the cancellation cause will be set - * to the signal's abort reason (see {@link AbortSignal#reason}). - * - * Has no effect if called (or if the signal aborts) _after_ the promise has already settled. - * Only the first signal to abort will set the cancellation cause. - * - * For more details about the cancellation process, - * see {@link cancel} and the `CancellablePromise` constructor. - * - * This method enables `await`ing cancellable promises without having - * to store them for future cancellation, e.g.: - * ```ts - * await longRunningOperation().cancelOn(signal); - * ``` - * instead of: - * ```ts - * let promiseToBeCancelled = longRunningOperation(); - * await promiseToBeCancelled; - * ``` - * - * @returns This promise, for method chaining. - */ - cancelOn(signal) { - if (signal.aborted) { - void this.cancel(signal.reason); - } - else { - signal.addEventListener('abort', () => void this.cancel(signal.reason), { capture: true }); - } - return this; - } - /** - * Attaches callbacks for the resolution and/or rejection of the `CancellablePromise`. - * - * The optional `oncancelled` argument will be invoked when the returned promise is cancelled, - * with the same semantics as the `oncancelled` argument of the constructor. - * When the parent promise rejects or is cancelled, the `onrejected` callback will run, - * _even after the returned promise has been cancelled:_ - * in that case, should it reject or throw, the reason will be wrapped - * in a {@link CancelledRejectionError} and bubbled up as an unhandled rejection. - * - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A `CancellablePromise` for the completion of whichever callback is executed. - * The returned promise is hooked up to propagate cancellation requests up the chain, but not down: - * - * - if the parent promise is cancelled, the `onrejected` handler will be invoked with a `CancelError` - * and the returned promise _will resolve regularly_ with its result; - * - conversely, if the returned promise is cancelled, _the parent promise is cancelled too;_ - * the `onrejected` handler will still be invoked with the parent's `CancelError`, - * but its result will be discarded - * and the returned promise will reject with a `CancelError` as well. - * - * The promise returned from {@link cancel} will fulfill only after all attached handlers - * up the entire promise chain have been run. - * - * If either callback returns a cancellable promise, - * cancellation requests will be diverted to it, - * and the specified `oncancelled` callback will be discarded. - */ - then(onfulfilled, onrejected, oncancelled) { - if (!(this instanceof CancellablePromise)) { - throw new TypeError("CancellablePromise.prototype.then called on an invalid object."); - } - // NOTE: TypeScript's built-in type for then is broken, - // as it allows specifying an arbitrary TResult1 != T even when onfulfilled is not a function. - // We cannot fix it if we want to CancellablePromise to implement PromiseLike. - if (!isCallable(onfulfilled)) { - onfulfilled = identity; - } - if (!isCallable(onrejected)) { - onrejected = thrower; - } - if (onfulfilled === identity && onrejected == thrower) { - // Shortcut for trivial arguments. - return new CancellablePromise((resolve) => resolve(this)); - } - const barrier = {}; - this[barrierSym] = barrier; - return new CancellablePromise((resolve, reject) => { - void super.then((value) => { - var _a; - if (this[barrierSym] === barrier) { - this[barrierSym] = null; - } - (_a = barrier.resolve) === null || _a === void 0 ? void 0 : _a.call(barrier); - try { - resolve(onfulfilled(value)); - } - catch (err) { - reject(err); - } - }, (reason) => { - var _a; - if (this[barrierSym] === barrier) { - this[barrierSym] = null; - } - (_a = barrier.resolve) === null || _a === void 0 ? void 0 : _a.call(barrier); - try { - resolve(onrejected(reason)); - } - catch (err) { - reject(err); - } - }); - }, async (cause) => { - //cancelled = true; - try { - return oncancelled === null || oncancelled === void 0 ? void 0 : oncancelled(cause); - } - finally { - await this.cancel(cause); - } - }); - } - /** - * Attaches a callback for only the rejection of the Promise. - * - * The optional `oncancelled` argument will be invoked when the returned promise is cancelled, - * with the same semantics as the `oncancelled` argument of the constructor. - * When the parent promise rejects or is cancelled, the `onrejected` callback will run, - * _even after the returned promise has been cancelled:_ - * in that case, should it reject or throw, the reason will be wrapped - * in a {@link CancelledRejectionError} and bubbled up as an unhandled rejection. - * - * It is equivalent to - * ```ts - * cancellablePromise.then(undefined, onrejected, oncancelled); - * ``` - * and the same caveats apply. - * - * @returns A Promise for the completion of the callback. - * Cancellation requests on the returned promise - * will propagate up the chain to the parent promise, - * but not in the other direction. - * - * The promise returned from {@link cancel} will fulfill only after all attached handlers - * up the entire promise chain have been run. - * - * If `onrejected` returns a cancellable promise, - * cancellation requests will be diverted to it, - * and the specified `oncancelled` callback will be discarded. - * See {@link then} for more details. - */ - catch(onrejected, oncancelled) { - return this.then(undefined, onrejected, oncancelled); - } - /** - * Attaches a callback that is invoked when the CancellablePromise is settled (fulfilled or rejected). The - * resolved value cannot be accessed or modified from the callback. - * The returned promise will settle in the same state as the original one - * after the provided callback has completed execution, - * unless the callback throws or returns a rejecting promise, - * in which case the returned promise will reject as well. - * - * The optional `oncancelled` argument will be invoked when the returned promise is cancelled, - * with the same semantics as the `oncancelled` argument of the constructor. - * Once the parent promise settles, the `onfinally` callback will run, - * _even after the returned promise has been cancelled:_ - * in that case, should it reject or throw, the reason will be wrapped - * in a {@link CancelledRejectionError} and bubbled up as an unhandled rejection. - * - * This method is implemented in terms of {@link then} and the same caveats apply. - * It is polyfilled, hence available in every OS/webview version. - * - * @returns A Promise for the completion of the callback. - * Cancellation requests on the returned promise - * will propagate up the chain to the parent promise, - * but not in the other direction. - * - * The promise returned from {@link cancel} will fulfill only after all attached handlers - * up the entire promise chain have been run. - * - * If `onfinally` returns a cancellable promise, - * cancellation requests will be diverted to it, - * and the specified `oncancelled` callback will be discarded. - * See {@link then} for more details. - */ - finally(onfinally, oncancelled) { - if (!(this instanceof CancellablePromise)) { - throw new TypeError("CancellablePromise.prototype.finally called on an invalid object."); - } - if (!isCallable(onfinally)) { - return this.then(onfinally, onfinally, oncancelled); - } - return this.then((value) => CancellablePromise.resolve(onfinally()).then(() => value), (reason) => CancellablePromise.resolve(onfinally()).then(() => { throw reason; }), oncancelled); - } - /** - * We use the `[Symbol.species]` static property, if available, - * to disable the built-in automatic subclassing features from {@link Promise}. - * It is critical for performance reasons that extenders do not override this. - * Once the proposal at https://github.com/tc39/proposal-rm-builtin-subclassing - * is either accepted or retired, this implementation will have to be revised accordingly. - * - * @ignore - * @internal - */ - static get [species]() { - return Promise; - } - static all(values) { - let collected = Array.from(values); - const promise = collected.length === 0 - ? CancellablePromise.resolve(collected) - : new CancellablePromise((resolve, reject) => { - void Promise.all(collected).then(resolve, reject); - }, (cause) => cancelAll(promise, collected, cause)); - return promise; - } - static allSettled(values) { - let collected = Array.from(values); - const promise = collected.length === 0 - ? CancellablePromise.resolve(collected) - : new CancellablePromise((resolve, reject) => { - void Promise.allSettled(collected).then(resolve, reject); - }, (cause) => cancelAll(promise, collected, cause)); - return promise; - } - static any(values) { - let collected = Array.from(values); - const promise = collected.length === 0 - ? CancellablePromise.resolve(collected) - : new CancellablePromise((resolve, reject) => { - void Promise.any(collected).then(resolve, reject); - }, (cause) => cancelAll(promise, collected, cause)); - return promise; - } - static race(values) { - let collected = Array.from(values); - const promise = new CancellablePromise((resolve, reject) => { - void Promise.race(collected).then(resolve, reject); - }, (cause) => cancelAll(promise, collected, cause)); - return promise; - } - /** - * Creates a new cancelled CancellablePromise for the provided cause. - * - * @group Static Methods - */ - static cancel(cause) { - const p = new CancellablePromise(() => { }); - p.cancel(cause); - return p; - } - /** - * Creates a new CancellablePromise that cancels - * after the specified timeout, with the provided cause. - * - * If the {@link AbortSignal.timeout} factory method is available, - * it is used to base the timeout on _active_ time rather than _elapsed_ time. - * Otherwise, `timeout` falls back to {@link setTimeout}. - * - * @group Static Methods - */ - static timeout(milliseconds, cause) { - const promise = new CancellablePromise(() => { }); - if (AbortSignal && typeof AbortSignal === 'function' && AbortSignal.timeout && typeof AbortSignal.timeout === 'function') { - AbortSignal.timeout(milliseconds).addEventListener('abort', () => void promise.cancel(cause)); - } - else { - setTimeout(() => void promise.cancel(cause), milliseconds); - } - return promise; - } - static sleep(milliseconds, value) { - return new CancellablePromise((resolve) => { - setTimeout(() => resolve(value), milliseconds); - }); - } - /** - * Creates a new rejected CancellablePromise for the provided reason. - * - * @group Static Methods - */ - static reject(reason) { - return new CancellablePromise((_, reject) => reject(reason)); - } - static resolve(value) { - if (value instanceof CancellablePromise) { - // Optimise for cancellable promises. - return value; - } - return new CancellablePromise((resolve) => resolve(value)); - } - /** - * Creates a new CancellablePromise and returns it in an object, along with its resolve and reject functions - * and a getter/setter for the cancellation callback. - * - * This method is polyfilled, hence available in every OS/webview version. - * - * @group Static Methods - */ - static withResolvers() { - let result = { oncancelled: null }; - result.promise = new CancellablePromise((resolve, reject) => { - result.resolve = resolve; - result.reject = reject; - }, (cause) => { var _a; (_a = result.oncancelled) === null || _a === void 0 ? void 0 : _a.call(result, cause); }); - return result; - } -} -/** - * Returns a callback that implements the cancellation algorithm for the given cancellable promise. - * The promise returned from the resulting function does not reject. - */ -function cancellerFor(promise, state) { - let cancellationPromise = undefined; - return (reason) => { - if (!state.settled) { - state.settled = true; - state.reason = reason; - promise.reject(reason); - // Attach an error handler that ignores this specific rejection reason and nothing else. - // In theory, a sane underlying implementation at this point - // should always reject with our cancellation reason, - // hence the handler will never throw. - void Promise.prototype.then.call(promise.promise, undefined, (err) => { - if (err !== reason) { - throw err; - } - }); - } - // If reason is not set, the promise resolved regularly, hence we must not call oncancelled. - // If oncancelled is unset, no need to go any further. - if (!state.reason || !promise.oncancelled) { - return; - } - cancellationPromise = new Promise((resolve) => { - try { - resolve(promise.oncancelled(state.reason.cause)); - } - catch (err) { - Promise.reject(new CancelledRejectionError(promise.promise, err, "Unhandled exception in oncancelled callback.")); - } - }).catch((reason) => { - Promise.reject(new CancelledRejectionError(promise.promise, reason, "Unhandled rejection in oncancelled callback.")); - }); - // Unset oncancelled to prevent repeated calls. - promise.oncancelled = null; - return cancellationPromise; - }; -} -/** - * Returns a callback that implements the resolution algorithm for the given cancellable promise. - */ -function resolverFor(promise, state) { - return (value) => { - if (state.resolving) { - return; - } - state.resolving = true; - if (value === promise.promise) { - if (state.settled) { - return; - } - state.settled = true; - promise.reject(new TypeError("A promise cannot be resolved with itself.")); - return; - } - if (value != null && (typeof value === 'object' || typeof value === 'function')) { - let then; - try { - then = value.then; - } - catch (err) { - state.settled = true; - promise.reject(err); - return; - } - if (isCallable(then)) { - try { - let cancel = value.cancel; - if (isCallable(cancel)) { - const oncancelled = (cause) => { - Reflect.apply(cancel, value, [cause]); - }; - if (state.reason) { - // If already cancelled, propagate cancellation. - // The promise returned from the canceller algorithm does not reject - // so it can be discarded safely. - void cancellerFor(Object.assign(Object.assign({}, promise), { oncancelled }), state)(state.reason); - } - else { - promise.oncancelled = oncancelled; - } - } - } - catch (_a) { } - const newState = { - root: state.root, - resolving: false, - get settled() { return this.root.settled; }, - set settled(value) { this.root.settled = value; }, - get reason() { return this.root.reason; } - }; - const rejector = rejectorFor(promise, newState); - try { - Reflect.apply(then, value, [resolverFor(promise, newState), rejector]); - } - catch (err) { - rejector(err); - } - return; // IMPORTANT! - } - } - if (state.settled) { - return; - } - state.settled = true; - promise.resolve(value); - }; -} -/** - * Returns a callback that implements the rejection algorithm for the given cancellable promise. - */ -function rejectorFor(promise, state) { - return (reason) => { - if (state.resolving) { - return; - } - state.resolving = true; - if (state.settled) { - try { - if (reason instanceof CancelError && state.reason instanceof CancelError && Object.is(reason.cause, state.reason.cause)) { - // Swallow late rejections that are CancelErrors whose cancellation cause is the same as ours. - return; - } - } - catch (_a) { } - void Promise.reject(new CancelledRejectionError(promise.promise, reason)); - } - else { - state.settled = true; - promise.reject(reason); - } - }; -} -/** - * Cancels all values in an array that look like cancellable thenables. - * Returns a promise that fulfills once all cancellation procedures for the given values have settled. - */ -function cancelAll(parent, values, cause) { - const results = []; - for (const value of values) { - let cancel; - try { - if (!isCallable(value.then)) { - continue; - } - cancel = value.cancel; - if (!isCallable(cancel)) { - continue; - } - } - catch (_a) { - continue; - } - let result; - try { - result = Reflect.apply(cancel, value, [cause]); - } - catch (err) { - Promise.reject(new CancelledRejectionError(parent, err, "Unhandled exception in cancel method.")); - continue; - } - if (!result) { - continue; - } - results.push((result instanceof Promise ? result : Promise.resolve(result)).catch((reason) => { - Promise.reject(new CancelledRejectionError(parent, reason, "Unhandled rejection in cancel method.")); - })); - } - return Promise.all(results); -} -/** - * Returns its argument. - */ -function identity(x) { - return x; -} -/** - * Throws its argument. - */ -function thrower(reason) { - throw reason; -} -/** - * Attempts various strategies to convert an error to a string. - */ -function errorMessage(err) { - try { - if (err instanceof Error || typeof err !== 'object' || err.toString !== Object.prototype.toString) { - return "" + err; - } - } - catch (_a) { } - try { - return JSON.stringify(err); - } - catch (_b) { } - try { - return Object.prototype.toString.call(err); - } - catch (_c) { } - return ""; -} -/** - * Gets the current barrier promise for the given cancellable promise. If necessary, initialises the barrier. - */ -function currentBarrier(promise) { - var _a; - let pwr = (_a = promise[barrierSym]) !== null && _a !== void 0 ? _a : {}; - if (!('promise' in pwr)) { - Object.assign(pwr, promiseWithResolvers()); - } - if (promise[barrierSym] == null) { - pwr.resolve(); - promise[barrierSym] = pwr; - } - return pwr.promise; -} -// Polyfill Promise.withResolvers. -let promiseWithResolvers = Promise.withResolvers; -if (promiseWithResolvers && typeof promiseWithResolvers === 'function') { - promiseWithResolvers = promiseWithResolvers.bind(Promise); -} -else { - promiseWithResolvers = function () { - let resolve; - let reject; - const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); - return { promise, resolve, reject }; - }; -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/clipboard.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/clipboard.js deleted file mode 100644 index d579d4b..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/clipboard.js +++ /dev/null @@ -1,30 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -import { newRuntimeCaller, objectNames } from "./runtime.js"; -const call = newRuntimeCaller(objectNames.Clipboard); -const ClipboardSetText = 0; -const ClipboardText = 1; -/** - * Sets the text to the Clipboard. - * - * @param text - The text to be set to the Clipboard. - * @return A Promise that resolves when the operation is successful. - */ -export function SetText(text) { - return call(ClipboardSetText, { text }); -} -/** - * Get the Clipboard text - * - * @returns A promise that resolves with the text from the Clipboard. - */ -export function Text() { - return call(ClipboardText); -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/contextmenu.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/contextmenu.js deleted file mode 100644 index 1485c3a..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/contextmenu.js +++ /dev/null @@ -1,80 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -import { newRuntimeCaller, objectNames } from "./runtime.js"; -import { IsDebug } from "./system.js"; -import { eventTarget } from "./utils"; -// setup -window.addEventListener('contextmenu', contextMenuHandler); -const call = newRuntimeCaller(objectNames.ContextMenu); -const ContextMenuOpen = 0; -function openContextMenu(id, x, y, data) { - void call(ContextMenuOpen, { id, x, y, data }); -} -function contextMenuHandler(event) { - const target = eventTarget(event); - // Check for custom context menu - const customContextMenu = window.getComputedStyle(target).getPropertyValue("--custom-contextmenu").trim(); - if (customContextMenu) { - event.preventDefault(); - const data = window.getComputedStyle(target).getPropertyValue("--custom-contextmenu-data"); - openContextMenu(customContextMenu, event.clientX, event.clientY, data); - } - else { - processDefaultContextMenu(event, target); - } -} -/* ---default-contextmenu: auto; (default) will show the default context menu if contentEditable is true OR text has been selected OR element is input or textarea ---default-contextmenu: show; will always show the default context menu ---default-contextmenu: hide; will always hide the default context menu - -This rule is inherited like normal CSS rules, so nesting works as expected -*/ -function processDefaultContextMenu(event, target) { - // Debug builds always show the menu - if (IsDebug()) { - return; - } - // Process default context menu - switch (window.getComputedStyle(target).getPropertyValue("--default-contextmenu").trim()) { - case 'show': - return; - case 'hide': - event.preventDefault(); - return; - } - // Check if contentEditable is true - if (target.isContentEditable) { - return; - } - // Check if text has been selected - const selection = window.getSelection(); - const hasSelection = selection && selection.toString().length > 0; - if (hasSelection) { - for (let i = 0; i < selection.rangeCount; i++) { - const range = selection.getRangeAt(i); - const rects = range.getClientRects(); - for (let j = 0; j < rects.length; j++) { - const rect = rects[j]; - if (document.elementFromPoint(rect.left, rect.top) === target) { - return; - } - } - } - } - // Check if tag is input or textarea. - if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) { - if (hasSelection || (!target.readOnly && !target.disabled)) { - return; - } - } - // hide default context menu - event.preventDefault(); -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/create.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/create.js deleted file mode 100644 index 6103625..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/create.js +++ /dev/null @@ -1,94 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -/** - * Any is a dummy creation function for simple or unknown types. - */ -export function Any(source) { - return source; -} -/** - * ByteSlice is a creation function that replaces - * null strings with empty strings. - */ -export function ByteSlice(source) { - return ((source == null) ? "" : source); -} -/** - * Array takes a creation function for an arbitrary type - * and returns an in-place creation function for an array - * whose elements are of that type. - */ -export function Array(element) { - if (element === Any) { - return (source) => (source === null ? [] : source); - } - return (source) => { - if (source === null) { - return []; - } - for (let i = 0; i < source.length; i++) { - source[i] = element(source[i]); - } - return source; - }; -} -/** - * Map takes creation functions for two arbitrary types - * and returns an in-place creation function for an object - * whose keys and values are of those types. - */ -export function Map(key, value) { - if (value === Any) { - return (source) => (source === null ? {} : source); - } - return (source) => { - if (source === null) { - return {}; - } - for (const key in source) { - source[key] = value(source[key]); - } - return source; - }; -} -/** - * Nullable takes a creation function for an arbitrary type - * and returns a creation function for a nullable value of that type. - */ -export function Nullable(element) { - if (element === Any) { - return Any; - } - return (source) => (source === null ? null : element(source)); -} -/** - * Struct takes an object mapping field names to creation functions - * and returns an in-place creation function for a struct. - */ -export function Struct(createField) { - let allAny = true; - for (const name in createField) { - if (createField[name] !== Any) { - allAny = false; - break; - } - } - if (allAny) { - return Any; - } - return (source) => { - for (const name in createField) { - if (name in source) { - source[name] = createField[name](source[name]); - } - } - return source; - }; -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/dialogs.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/dialogs.js deleted file mode 100644 index 2cfa475..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/dialogs.js +++ /dev/null @@ -1,134 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -import { newRuntimeCaller, objectNames } from "./runtime.js"; -import { nanoid } from './nanoid.js'; -// setup -window._wails = window._wails || {}; -window._wails.dialogErrorCallback = dialogErrorCallback; -window._wails.dialogResultCallback = dialogResultCallback; -const call = newRuntimeCaller(objectNames.Dialog); -const dialogResponses = new Map(); -// Define constants from the `methods` object in Title Case -const DialogInfo = 0; -const DialogWarning = 1; -const DialogError = 2; -const DialogQuestion = 3; -const DialogOpenFile = 4; -const DialogSaveFile = 5; -/** - * Handles the result of a dialog request. - * - * @param id - The id of the request to handle the result for. - * @param data - The result data of the request. - * @param isJSON - Indicates whether the data is JSON or not. - */ -function dialogResultCallback(id, data, isJSON) { - let resolvers = getAndDeleteResponse(id); - if (!resolvers) { - return; - } - if (isJSON) { - try { - resolvers.resolve(JSON.parse(data)); - } - catch (err) { - resolvers.reject(new TypeError("could not parse result: " + err.message, { cause: err })); - } - } - else { - resolvers.resolve(data); - } -} -/** - * Handles the error from a dialog request. - * - * @param id - The id of the promise handler. - * @param message - An error message. - */ -function dialogErrorCallback(id, message) { - var _a; - (_a = getAndDeleteResponse(id)) === null || _a === void 0 ? void 0 : _a.reject(new window.Error(message)); -} -/** - * Retrieves and removes the response associated with the given ID from the dialogResponses map. - * - * @param id - The ID of the response to be retrieved and removed. - * @returns The response object associated with the given ID, if any. - */ -function getAndDeleteResponse(id) { - const response = dialogResponses.get(id); - dialogResponses.delete(id); - return response; -} -/** - * Generates a unique ID using the nanoid library. - * - * @returns A unique ID that does not exist in the dialogResponses set. - */ -function generateID() { - let result; - do { - result = nanoid(); - } while (dialogResponses.has(result)); - return result; -} -/** - * Presents a dialog of specified type with the given options. - * - * @param type - Dialog type. - * @param options - Options for the dialog. - * @returns A promise that resolves with result of dialog. - */ -function dialog(type, options = {}) { - const id = generateID(); - return new Promise((resolve, reject) => { - dialogResponses.set(id, { resolve, reject }); - call(type, Object.assign({ "dialog-id": id }, options)).catch((err) => { - dialogResponses.delete(id); - reject(err); - }); - }); -} -/** - * Presents an info dialog. - * - * @param options - Dialog options - * @returns A promise that resolves with the label of the chosen button. - */ -export function Info(options) { return dialog(DialogInfo, options); } -/** - * Presents a warning dialog. - * - * @param options - Dialog options. - * @returns A promise that resolves with the label of the chosen button. - */ -export function Warning(options) { return dialog(DialogWarning, options); } -/** - * Presents an error dialog. - * - * @param options - Dialog options. - * @returns A promise that resolves with the label of the chosen button. - */ -export function Error(options) { return dialog(DialogError, options); } -/** - * Presents a question dialog. - * - * @param options - Dialog options. - * @returns A promise that resolves with the label of the chosen button. - */ -export function Question(options) { return dialog(DialogQuestion, options); } -export function OpenFile(options) { var _a; return (_a = dialog(DialogOpenFile, options)) !== null && _a !== void 0 ? _a : []; } -/** - * Presents a file selection dialog to pick a file to save. - * - * @param options - Dialog options. - * @returns Selected file, or a blank string if no file has been selected. - */ -export function SaveFile(options) { return dialog(DialogSaveFile, options); } diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/drag.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/drag.js deleted file mode 100644 index ae4ecc3..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/drag.js +++ /dev/null @@ -1,222 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -import { invoke, IsWindows } from "./system.js"; -import { GetFlag } from "./flags.js"; -import { canTrackButtons, eventTarget } from "./utils.js"; -// Setup -let canDrag = false; -let dragging = false; -let resizable = false; -let canResize = false; -let resizing = false; -let resizeEdge = ""; -let defaultCursor = "auto"; -let buttons = 0; -const buttonsTracked = canTrackButtons(); -window._wails = window._wails || {}; -window._wails.setResizable = (value) => { - resizable = value; - if (!resizable) { - // Stop resizing if in progress. - canResize = resizing = false; - setResize(); - } -}; -window.addEventListener('mousedown', update, { capture: true }); -window.addEventListener('mousemove', update, { capture: true }); -window.addEventListener('mouseup', update, { capture: true }); -for (const ev of ['click', 'contextmenu', 'dblclick']) { - window.addEventListener(ev, suppressEvent, { capture: true }); -} -function suppressEvent(event) { - // Suppress click events while resizing or dragging. - if (dragging || resizing) { - event.stopImmediatePropagation(); - event.stopPropagation(); - event.preventDefault(); - } -} -// Use constants to avoid comparing strings multiple times. -const MouseDown = 0; -const MouseUp = 1; -const MouseMove = 2; -function update(event) { - // Windows suppresses mouse events at the end of dragging or resizing, - // so we need to be smart and synthesize button events. - let eventType, eventButtons = event.buttons; - switch (event.type) { - case 'mousedown': - eventType = MouseDown; - if (!buttonsTracked) { - eventButtons = buttons | (1 << event.button); - } - break; - case 'mouseup': - eventType = MouseUp; - if (!buttonsTracked) { - eventButtons = buttons & ~(1 << event.button); - } - break; - default: - eventType = MouseMove; - if (!buttonsTracked) { - eventButtons = buttons; - } - break; - } - let released = buttons & ~eventButtons; - let pressed = eventButtons & ~buttons; - buttons = eventButtons; - // Synthesize a release-press sequence if we detect a press of an already pressed button. - if (eventType === MouseDown && !(pressed & event.button)) { - released |= (1 << event.button); - pressed |= (1 << event.button); - } - // Suppress all button events during dragging and resizing, - // unless this is a mouseup event that is ending a drag action. - if (eventType !== MouseMove // Fast path for mousemove - && resizing - || (dragging - && (eventType === MouseDown - || event.button !== 0))) { - event.stopImmediatePropagation(); - event.stopPropagation(); - event.preventDefault(); - } - // Handle releases - if (released & 1) { - primaryUp(event); - } - // Handle presses - if (pressed & 1) { - primaryDown(event); - } - // Handle mousemove - if (eventType === MouseMove) { - onMouseMove(event); - } - ; -} -function primaryDown(event) { - // Reset readiness state. - canDrag = false; - canResize = false; - // Ignore repeated clicks on macOS and Linux. - if (!IsWindows()) { - if (event.type === 'mousedown' && event.button === 0 && event.detail !== 1) { - return; - } - } - if (resizeEdge) { - // Ready to resize if the primary button was pressed for the first time. - canResize = true; - // Do not start drag operations when on resize edges. - return; - } - // Retrieve target element - const target = eventTarget(event); - // Ready to drag if the primary button was pressed for the first time on a draggable element. - // Ignore clicks on the scrollbar. - const style = window.getComputedStyle(target); - canDrag = (style.getPropertyValue("--wails-draggable").trim() === "drag" - && (event.offsetX - parseFloat(style.paddingLeft) < target.clientWidth - && event.offsetY - parseFloat(style.paddingTop) < target.clientHeight)); -} -function primaryUp(event) { - // Stop dragging and resizing. - canDrag = false; - dragging = false; - canResize = false; - resizing = false; -} -const cursorForEdge = Object.freeze({ - "se-resize": "nwse-resize", - "sw-resize": "nesw-resize", - "nw-resize": "nwse-resize", - "ne-resize": "nesw-resize", - "w-resize": "ew-resize", - "n-resize": "ns-resize", - "s-resize": "ns-resize", - "e-resize": "ew-resize", -}); -function setResize(edge) { - if (edge) { - if (!resizeEdge) { - defaultCursor = document.body.style.cursor; - } - document.body.style.cursor = cursorForEdge[edge]; - } - else if (!edge && resizeEdge) { - document.body.style.cursor = defaultCursor; - } - resizeEdge = edge || ""; -} -function onMouseMove(event) { - if (canResize && resizeEdge) { - // Start resizing. - resizing = true; - invoke("wails:resize:" + resizeEdge); - } - else if (canDrag) { - // Start dragging. - dragging = true; - invoke("wails:drag"); - } - if (dragging || resizing) { - // Either drag or resize is ongoing, - // reset readiness and stop processing. - canDrag = canResize = false; - return; - } - if (!resizable || !IsWindows()) { - if (resizeEdge) { - setResize(); - } - return; - } - const resizeHandleHeight = GetFlag("system.resizeHandleHeight") || 5; - const resizeHandleWidth = GetFlag("system.resizeHandleWidth") || 5; - // Extra pixels for the corner areas. - const cornerExtra = GetFlag("resizeCornerExtra") || 10; - const rightBorder = (window.outerWidth - event.clientX) < resizeHandleWidth; - const leftBorder = event.clientX < resizeHandleWidth; - const topBorder = event.clientY < resizeHandleHeight; - const bottomBorder = (window.outerHeight - event.clientY) < resizeHandleHeight; - // Adjust for corner areas. - const rightCorner = (window.outerWidth - event.clientX) < (resizeHandleWidth + cornerExtra); - const leftCorner = event.clientX < (resizeHandleWidth + cornerExtra); - const topCorner = event.clientY < (resizeHandleHeight + cornerExtra); - const bottomCorner = (window.outerHeight - event.clientY) < (resizeHandleHeight + cornerExtra); - if (!leftCorner && !topCorner && !bottomCorner && !rightCorner) { - // Optimisation: out of all corner areas implies out of borders. - setResize(); - } - // Detect corners. - else if (rightCorner && bottomCorner) - setResize("se-resize"); - else if (leftCorner && bottomCorner) - setResize("sw-resize"); - else if (leftCorner && topCorner) - setResize("nw-resize"); - else if (topCorner && rightCorner) - setResize("ne-resize"); - // Detect borders. - else if (leftBorder) - setResize("w-resize"); - else if (topBorder) - setResize("n-resize"); - else if (bottomBorder) - setResize("s-resize"); - else if (rightBorder) - setResize("e-resize"); - // Out of border area. - else - setResize(); -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/event_types.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/event_types.js deleted file mode 100644 index 6cf95d6..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/event_types.js +++ /dev/null @@ -1,229 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -// Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL -// This file is automatically generated. DO NOT EDIT -export const Types = Object.freeze({ - Windows: Object.freeze({ - APMPowerSettingChange: "windows:APMPowerSettingChange", - APMPowerStatusChange: "windows:APMPowerStatusChange", - APMResumeAutomatic: "windows:APMResumeAutomatic", - APMResumeSuspend: "windows:APMResumeSuspend", - APMSuspend: "windows:APMSuspend", - ApplicationStarted: "windows:ApplicationStarted", - SystemThemeChanged: "windows:SystemThemeChanged", - WebViewNavigationCompleted: "windows:WebViewNavigationCompleted", - WindowActive: "windows:WindowActive", - WindowBackgroundErase: "windows:WindowBackgroundErase", - WindowClickActive: "windows:WindowClickActive", - WindowClosing: "windows:WindowClosing", - WindowDidMove: "windows:WindowDidMove", - WindowDidResize: "windows:WindowDidResize", - WindowDPIChanged: "windows:WindowDPIChanged", - WindowDragDrop: "windows:WindowDragDrop", - WindowDragEnter: "windows:WindowDragEnter", - WindowDragLeave: "windows:WindowDragLeave", - WindowDragOver: "windows:WindowDragOver", - WindowEndMove: "windows:WindowEndMove", - WindowEndResize: "windows:WindowEndResize", - WindowFullscreen: "windows:WindowFullscreen", - WindowHide: "windows:WindowHide", - WindowInactive: "windows:WindowInactive", - WindowKeyDown: "windows:WindowKeyDown", - WindowKeyUp: "windows:WindowKeyUp", - WindowKillFocus: "windows:WindowKillFocus", - WindowNonClientHit: "windows:WindowNonClientHit", - WindowNonClientMouseDown: "windows:WindowNonClientMouseDown", - WindowNonClientMouseLeave: "windows:WindowNonClientMouseLeave", - WindowNonClientMouseMove: "windows:WindowNonClientMouseMove", - WindowNonClientMouseUp: "windows:WindowNonClientMouseUp", - WindowPaint: "windows:WindowPaint", - WindowRestore: "windows:WindowRestore", - WindowSetFocus: "windows:WindowSetFocus", - WindowShow: "windows:WindowShow", - WindowStartMove: "windows:WindowStartMove", - WindowStartResize: "windows:WindowStartResize", - WindowUnFullscreen: "windows:WindowUnFullscreen", - WindowZOrderChanged: "windows:WindowZOrderChanged", - WindowMinimise: "windows:WindowMinimise", - WindowUnMinimise: "windows:WindowUnMinimise", - WindowMaximise: "windows:WindowMaximise", - WindowUnMaximise: "windows:WindowUnMaximise", - }), - Mac: Object.freeze({ - ApplicationDidBecomeActive: "mac:ApplicationDidBecomeActive", - ApplicationDidChangeBackingProperties: "mac:ApplicationDidChangeBackingProperties", - ApplicationDidChangeEffectiveAppearance: "mac:ApplicationDidChangeEffectiveAppearance", - ApplicationDidChangeIcon: "mac:ApplicationDidChangeIcon", - ApplicationDidChangeOcclusionState: "mac:ApplicationDidChangeOcclusionState", - ApplicationDidChangeScreenParameters: "mac:ApplicationDidChangeScreenParameters", - ApplicationDidChangeStatusBarFrame: "mac:ApplicationDidChangeStatusBarFrame", - ApplicationDidChangeStatusBarOrientation: "mac:ApplicationDidChangeStatusBarOrientation", - ApplicationDidChangeTheme: "mac:ApplicationDidChangeTheme", - ApplicationDidFinishLaunching: "mac:ApplicationDidFinishLaunching", - ApplicationDidHide: "mac:ApplicationDidHide", - ApplicationDidResignActive: "mac:ApplicationDidResignActive", - ApplicationDidUnhide: "mac:ApplicationDidUnhide", - ApplicationDidUpdate: "mac:ApplicationDidUpdate", - ApplicationShouldHandleReopen: "mac:ApplicationShouldHandleReopen", - ApplicationWillBecomeActive: "mac:ApplicationWillBecomeActive", - ApplicationWillFinishLaunching: "mac:ApplicationWillFinishLaunching", - ApplicationWillHide: "mac:ApplicationWillHide", - ApplicationWillResignActive: "mac:ApplicationWillResignActive", - ApplicationWillTerminate: "mac:ApplicationWillTerminate", - ApplicationWillUnhide: "mac:ApplicationWillUnhide", - ApplicationWillUpdate: "mac:ApplicationWillUpdate", - MenuDidAddItem: "mac:MenuDidAddItem", - MenuDidBeginTracking: "mac:MenuDidBeginTracking", - MenuDidClose: "mac:MenuDidClose", - MenuDidDisplayItem: "mac:MenuDidDisplayItem", - MenuDidEndTracking: "mac:MenuDidEndTracking", - MenuDidHighlightItem: "mac:MenuDidHighlightItem", - MenuDidOpen: "mac:MenuDidOpen", - MenuDidPopUp: "mac:MenuDidPopUp", - MenuDidRemoveItem: "mac:MenuDidRemoveItem", - MenuDidSendAction: "mac:MenuDidSendAction", - MenuDidSendActionToItem: "mac:MenuDidSendActionToItem", - MenuDidUpdate: "mac:MenuDidUpdate", - MenuWillAddItem: "mac:MenuWillAddItem", - MenuWillBeginTracking: "mac:MenuWillBeginTracking", - MenuWillDisplayItem: "mac:MenuWillDisplayItem", - MenuWillEndTracking: "mac:MenuWillEndTracking", - MenuWillHighlightItem: "mac:MenuWillHighlightItem", - MenuWillOpen: "mac:MenuWillOpen", - MenuWillPopUp: "mac:MenuWillPopUp", - MenuWillRemoveItem: "mac:MenuWillRemoveItem", - MenuWillSendAction: "mac:MenuWillSendAction", - MenuWillSendActionToItem: "mac:MenuWillSendActionToItem", - MenuWillUpdate: "mac:MenuWillUpdate", - WebViewDidCommitNavigation: "mac:WebViewDidCommitNavigation", - WebViewDidFinishNavigation: "mac:WebViewDidFinishNavigation", - WebViewDidReceiveServerRedirectForProvisionalNavigation: "mac:WebViewDidReceiveServerRedirectForProvisionalNavigation", - WebViewDidStartProvisionalNavigation: "mac:WebViewDidStartProvisionalNavigation", - WindowDidBecomeKey: "mac:WindowDidBecomeKey", - WindowDidBecomeMain: "mac:WindowDidBecomeMain", - WindowDidBeginSheet: "mac:WindowDidBeginSheet", - WindowDidChangeAlpha: "mac:WindowDidChangeAlpha", - WindowDidChangeBackingLocation: "mac:WindowDidChangeBackingLocation", - WindowDidChangeBackingProperties: "mac:WindowDidChangeBackingProperties", - WindowDidChangeCollectionBehavior: "mac:WindowDidChangeCollectionBehavior", - WindowDidChangeEffectiveAppearance: "mac:WindowDidChangeEffectiveAppearance", - WindowDidChangeOcclusionState: "mac:WindowDidChangeOcclusionState", - WindowDidChangeOrderingMode: "mac:WindowDidChangeOrderingMode", - WindowDidChangeScreen: "mac:WindowDidChangeScreen", - WindowDidChangeScreenParameters: "mac:WindowDidChangeScreenParameters", - WindowDidChangeScreenProfile: "mac:WindowDidChangeScreenProfile", - WindowDidChangeScreenSpace: "mac:WindowDidChangeScreenSpace", - WindowDidChangeScreenSpaceProperties: "mac:WindowDidChangeScreenSpaceProperties", - WindowDidChangeSharingType: "mac:WindowDidChangeSharingType", - WindowDidChangeSpace: "mac:WindowDidChangeSpace", - WindowDidChangeSpaceOrderingMode: "mac:WindowDidChangeSpaceOrderingMode", - WindowDidChangeTitle: "mac:WindowDidChangeTitle", - WindowDidChangeToolbar: "mac:WindowDidChangeToolbar", - WindowDidDeminiaturize: "mac:WindowDidDeminiaturize", - WindowDidEndSheet: "mac:WindowDidEndSheet", - WindowDidEnterFullScreen: "mac:WindowDidEnterFullScreen", - WindowDidEnterVersionBrowser: "mac:WindowDidEnterVersionBrowser", - WindowDidExitFullScreen: "mac:WindowDidExitFullScreen", - WindowDidExitVersionBrowser: "mac:WindowDidExitVersionBrowser", - WindowDidExpose: "mac:WindowDidExpose", - WindowDidFocus: "mac:WindowDidFocus", - WindowDidMiniaturize: "mac:WindowDidMiniaturize", - WindowDidMove: "mac:WindowDidMove", - WindowDidOrderOffScreen: "mac:WindowDidOrderOffScreen", - WindowDidOrderOnScreen: "mac:WindowDidOrderOnScreen", - WindowDidResignKey: "mac:WindowDidResignKey", - WindowDidResignMain: "mac:WindowDidResignMain", - WindowDidResize: "mac:WindowDidResize", - WindowDidUpdate: "mac:WindowDidUpdate", - WindowDidUpdateAlpha: "mac:WindowDidUpdateAlpha", - WindowDidUpdateCollectionBehavior: "mac:WindowDidUpdateCollectionBehavior", - WindowDidUpdateCollectionProperties: "mac:WindowDidUpdateCollectionProperties", - WindowDidUpdateShadow: "mac:WindowDidUpdateShadow", - WindowDidUpdateTitle: "mac:WindowDidUpdateTitle", - WindowDidUpdateToolbar: "mac:WindowDidUpdateToolbar", - WindowDidZoom: "mac:WindowDidZoom", - WindowFileDraggingEntered: "mac:WindowFileDraggingEntered", - WindowFileDraggingExited: "mac:WindowFileDraggingExited", - WindowFileDraggingPerformed: "mac:WindowFileDraggingPerformed", - WindowHide: "mac:WindowHide", - WindowMaximise: "mac:WindowMaximise", - WindowUnMaximise: "mac:WindowUnMaximise", - WindowMinimise: "mac:WindowMinimise", - WindowUnMinimise: "mac:WindowUnMinimise", - WindowShouldClose: "mac:WindowShouldClose", - WindowShow: "mac:WindowShow", - WindowWillBecomeKey: "mac:WindowWillBecomeKey", - WindowWillBecomeMain: "mac:WindowWillBecomeMain", - WindowWillBeginSheet: "mac:WindowWillBeginSheet", - WindowWillChangeOrderingMode: "mac:WindowWillChangeOrderingMode", - WindowWillClose: "mac:WindowWillClose", - WindowWillDeminiaturize: "mac:WindowWillDeminiaturize", - WindowWillEnterFullScreen: "mac:WindowWillEnterFullScreen", - WindowWillEnterVersionBrowser: "mac:WindowWillEnterVersionBrowser", - WindowWillExitFullScreen: "mac:WindowWillExitFullScreen", - WindowWillExitVersionBrowser: "mac:WindowWillExitVersionBrowser", - WindowWillFocus: "mac:WindowWillFocus", - WindowWillMiniaturize: "mac:WindowWillMiniaturize", - WindowWillMove: "mac:WindowWillMove", - WindowWillOrderOffScreen: "mac:WindowWillOrderOffScreen", - WindowWillOrderOnScreen: "mac:WindowWillOrderOnScreen", - WindowWillResignMain: "mac:WindowWillResignMain", - WindowWillResize: "mac:WindowWillResize", - WindowWillUnfocus: "mac:WindowWillUnfocus", - WindowWillUpdate: "mac:WindowWillUpdate", - WindowWillUpdateAlpha: "mac:WindowWillUpdateAlpha", - WindowWillUpdateCollectionBehavior: "mac:WindowWillUpdateCollectionBehavior", - WindowWillUpdateCollectionProperties: "mac:WindowWillUpdateCollectionProperties", - WindowWillUpdateShadow: "mac:WindowWillUpdateShadow", - WindowWillUpdateTitle: "mac:WindowWillUpdateTitle", - WindowWillUpdateToolbar: "mac:WindowWillUpdateToolbar", - WindowWillUpdateVisibility: "mac:WindowWillUpdateVisibility", - WindowWillUseStandardFrame: "mac:WindowWillUseStandardFrame", - WindowZoomIn: "mac:WindowZoomIn", - WindowZoomOut: "mac:WindowZoomOut", - WindowZoomReset: "mac:WindowZoomReset", - }), - Linux: Object.freeze({ - ApplicationStartup: "linux:ApplicationStartup", - SystemThemeChanged: "linux:SystemThemeChanged", - WindowDeleteEvent: "linux:WindowDeleteEvent", - WindowDidMove: "linux:WindowDidMove", - WindowDidResize: "linux:WindowDidResize", - WindowFocusIn: "linux:WindowFocusIn", - WindowFocusOut: "linux:WindowFocusOut", - WindowLoadChanged: "linux:WindowLoadChanged", - }), - Common: Object.freeze({ - ApplicationOpenedWithFile: "common:ApplicationOpenedWithFile", - ApplicationStarted: "common:ApplicationStarted", - ThemeChanged: "common:ThemeChanged", - WindowClosing: "common:WindowClosing", - WindowDidMove: "common:WindowDidMove", - WindowDidResize: "common:WindowDidResize", - WindowDPIChanged: "common:WindowDPIChanged", - WindowFilesDropped: "common:WindowFilesDropped", - WindowFocus: "common:WindowFocus", - WindowFullscreen: "common:WindowFullscreen", - WindowHide: "common:WindowHide", - WindowLostFocus: "common:WindowLostFocus", - WindowMaximise: "common:WindowMaximise", - WindowMinimise: "common:WindowMinimise", - WindowRestore: "common:WindowRestore", - WindowRuntimeReady: "common:WindowRuntimeReady", - WindowShow: "common:WindowShow", - WindowUnFullscreen: "common:WindowUnFullscreen", - WindowUnMaximise: "common:WindowUnMaximise", - WindowUnMinimise: "common:WindowUnMinimise", - WindowZoom: "common:WindowZoom", - WindowZoomIn: "common:WindowZoomIn", - WindowZoomOut: "common:WindowZoomOut", - WindowZoomReset: "common:WindowZoomReset", - }), -}); diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/events.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/events.js deleted file mode 100644 index ba8b2d3..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/events.js +++ /dev/null @@ -1,101 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -import { newRuntimeCaller, objectNames } from "./runtime.js"; -import { eventListeners, Listener, listenerOff } from "./listener.js"; -// Setup -window._wails = window._wails || {}; -window._wails.dispatchWailsEvent = dispatchWailsEvent; -const call = newRuntimeCaller(objectNames.Events); -const EmitMethod = 0; -export { Types } from "./event_types.js"; -/** - * Represents a system event or a custom event emitted through wails-provided facilities. - */ -export class WailsEvent { - constructor(name, data = null) { - this.name = name; - this.data = data; - } -} -function dispatchWailsEvent(event) { - let listeners = eventListeners.get(event.name); - if (!listeners) { - return; - } - let wailsEvent = new WailsEvent(event.name, event.data); - if ('sender' in event) { - wailsEvent.sender = event.sender; - } - listeners = listeners.filter(listener => !listener.dispatch(wailsEvent)); - if (listeners.length === 0) { - eventListeners.delete(event.name); - } - else { - eventListeners.set(event.name, listeners); - } -} -/** - * Register a callback function to be called multiple times for a specific event. - * - * @param eventName - The name of the event to register the callback for. - * @param callback - The callback function to be called when the event is triggered. - * @param maxCallbacks - The maximum number of times the callback can be called for the event. Once the maximum number is reached, the callback will no longer be called. - * @returns A function that, when called, will unregister the callback from the event. - */ -export function OnMultiple(eventName, callback, maxCallbacks) { - let listeners = eventListeners.get(eventName) || []; - const thisListener = new Listener(eventName, callback, maxCallbacks); - listeners.push(thisListener); - eventListeners.set(eventName, listeners); - return () => listenerOff(thisListener); -} -/** - * Registers a callback function to be executed when the specified event occurs. - * - * @param eventName - The name of the event to register the callback for. - * @param callback - The callback function to be called when the event is triggered. - * @returns A function that, when called, will unregister the callback from the event. - */ -export function On(eventName, callback) { - return OnMultiple(eventName, callback, -1); -} -/** - * Registers a callback function to be executed only once for the specified event. - * - * @param eventName - The name of the event to register the callback for. - * @param callback - The callback function to be called when the event is triggered. - * @returns A function that, when called, will unregister the callback from the event. - */ -export function Once(eventName, callback) { - return OnMultiple(eventName, callback, 1); -} -/** - * Removes event listeners for the specified event names. - * - * @param eventNames - The name of the events to remove listeners for. - */ -export function Off(...eventNames) { - eventNames.forEach(eventName => eventListeners.delete(eventName)); -} -/** - * Removes all event listeners. - */ -export function OffAll() { - eventListeners.clear(); -} -/** - * Emits the given event. - * - * @param event - The name of the event to emit. - * @returns A promise that will be fulfilled once the event has been emitted. - */ -export function Emit(event) { - return call(EmitMethod, event); -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/flags.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/flags.js deleted file mode 100644 index 31071c2..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/flags.js +++ /dev/null @@ -1,23 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -/** - * Retrieves the value associated with the specified key from the flag map. - * - * @param key - The key to retrieve the value for. - * @return The value associated with the specified key. - */ -export function GetFlag(key) { - try { - return window._wails.flags[key]; - } - catch (e) { - throw new Error("Unable to retrieve flag '" + key + "': " + e, { cause: e }); - } -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/index.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/index.js deleted file mode 100644 index 34f741b..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/index.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -// Setup -window._wails = window._wails || {}; -import "./contextmenu.js"; -import "./drag.js"; -// Re-export public API -import * as Application from "./application.js"; -import * as Browser from "./browser.js"; -import * as Call from "./calls.js"; -import * as Clipboard from "./clipboard.js"; -import * as Create from "./create.js"; -import * as Dialogs from "./dialogs.js"; -import * as Events from "./events.js"; -import * as Flags from "./flags.js"; -import * as Screens from "./screens.js"; -import * as System from "./system.js"; -import Window from "./window.js"; -import * as WML from "./wml.js"; -export { Application, Browser, Call, Clipboard, Dialogs, Events, Flags, Screens, System, Window, WML }; -/** - * An internal utility consumed by the binding generator. - * - * @ignore - * @internal - */ -export { Create }; -export * from "./cancellable.js"; -// Notify backend -window._wails.invoke = System.invoke; -System.invoke("wails:runtime:ready"); diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/listener.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/listener.js deleted file mode 100644 index 9604088..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/listener.js +++ /dev/null @@ -1,44 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -// The following utilities have been factored out of ./events.ts -// for testing purposes. -export const eventListeners = new Map(); -export class Listener { - constructor(eventName, callback, maxCallbacks) { - this.eventName = eventName; - this.callback = callback; - this.maxCallbacks = maxCallbacks || -1; - } - dispatch(data) { - try { - this.callback(data); - } - catch (err) { - console.error(err); - } - if (this.maxCallbacks === -1) - return false; - this.maxCallbacks -= 1; - return this.maxCallbacks === 0; - } -} -export function listenerOff(listener) { - let listeners = eventListeners.get(listener.eventName); - if (!listeners) { - return; - } - listeners = listeners.filter(l => l !== listener); - if (listeners.length === 0) { - eventListeners.delete(listener.eventName); - } - else { - eventListeners.set(listener.eventName, listeners); - } -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/nanoid.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/nanoid.js deleted file mode 100644 index c0d5e24..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/nanoid.js +++ /dev/null @@ -1,38 +0,0 @@ -// Source: https://github.com/ai/nanoid -// The MIT License (MIT) -// -// Copyright 2017 Andrey Sitnik -// -// Permission is hereby granted, free of charge, to any person obtaining a copy of -// this software and associated documentation files (the "Software"), to deal in -// the Software without restriction, including without limitation the rights to -// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -// the Software, and to permit persons to whom the Software is furnished to do so, -// subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in all -// copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -// This alphabet uses `A-Za-z0-9_-` symbols. -// The order of characters is optimized for better gzip and brotli compression. -// References to the same file (works both for gzip and brotli): -// `'use`, `andom`, and `rict'` -// References to the brotli default dictionary: -// `-26T`, `1983`, `40px`, `75px`, `bush`, `jack`, `mind`, `very`, and `wolf` -const urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'; -export function nanoid(size = 21) { - let id = ''; - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = size | 0; - while (i--) { - // `| 0` is more compact and faster than `Math.floor()`. - id += urlAlphabet[(Math.random() * 64) | 0]; - } - return id; -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/runtime.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/runtime.js deleted file mode 100644 index f11df1c..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/runtime.js +++ /dev/null @@ -1,63 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -import { nanoid } from './nanoid.js'; -const runtimeURL = window.location.origin + "/wails/runtime"; -// Object Names -export const objectNames = Object.freeze({ - Call: 0, - Clipboard: 1, - Application: 2, - Events: 3, - ContextMenu: 4, - Dialog: 5, - Window: 6, - Screens: 7, - System: 8, - Browser: 9, - CancelCall: 10, -}); -export let clientId = nanoid(); -/** - * Creates a new runtime caller with specified ID. - * - * @param object - The object to invoke the method on. - * @param windowName - The name of the window. - * @return The new runtime caller function. - */ -export function newRuntimeCaller(object, windowName = '') { - return function (method, args = null) { - return runtimeCallWithID(object, method, windowName, args); - }; -} -async function runtimeCallWithID(objectID, method, windowName, args) { - var _a, _b; - let url = new URL(runtimeURL); - url.searchParams.append("object", objectID.toString()); - url.searchParams.append("method", method.toString()); - if (args) { - url.searchParams.append("args", JSON.stringify(args)); - } - let headers = { - ["x-wails-client-id"]: clientId - }; - if (windowName) { - headers["x-wails-window-name"] = windowName; - } - let response = await fetch(url, { headers }); - if (!response.ok) { - throw new Error(await response.text()); - } - if (((_b = (_a = response.headers.get("Content-Type")) === null || _a === void 0 ? void 0 : _a.indexOf("application/json")) !== null && _b !== void 0 ? _b : -1) !== -1) { - return response.json(); - } - else { - return response.text(); - } -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/screens.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/screens.js deleted file mode 100644 index b09dc58..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/screens.js +++ /dev/null @@ -1,38 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -import { newRuntimeCaller, objectNames } from "./runtime.js"; -const call = newRuntimeCaller(objectNames.Screens); -const getAll = 0; -const getPrimary = 1; -const getCurrent = 2; -/** - * Gets all screens. - * - * @returns A promise that resolves to an array of Screen objects. - */ -export function GetAll() { - return call(getAll); -} -/** - * Gets the primary screen. - * - * @returns A promise that resolves to the primary screen. - */ -export function GetPrimary() { - return call(getPrimary); -} -/** - * Gets the current active screen. - * - * @returns A promise that resolves with the current active screen. - */ -export function GetCurrent() { - return call(getCurrent); -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/system.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/system.js deleted file mode 100644 index 4d51cf8..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/system.js +++ /dev/null @@ -1,116 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -import { newRuntimeCaller, objectNames } from "./runtime.js"; -const call = newRuntimeCaller(objectNames.System); -const SystemIsDarkMode = 0; -const SystemEnvironment = 1; -const _invoke = (function () { - var _a, _b, _c, _d, _e; - try { - if ((_b = (_a = window.chrome) === null || _a === void 0 ? void 0 : _a.webview) === null || _b === void 0 ? void 0 : _b.postMessage) { - return window.chrome.webview.postMessage.bind(window.chrome.webview); - } - else if ((_e = (_d = (_c = window.webkit) === null || _c === void 0 ? void 0 : _c.messageHandlers) === null || _d === void 0 ? void 0 : _d['external']) === null || _e === void 0 ? void 0 : _e.postMessage) { - return window.webkit.messageHandlers['external'].postMessage.bind(window.webkit.messageHandlers['external']); - } - } - catch (e) { } - console.warn('\n%c⚠️ Browser Environment Detected %c\n\n%cOnly UI previews are available in the browser. For full functionality, please run the application in desktop mode.\nMore information at: https://v3.wails.io/learn/build/#using-a-browser-for-development\n', 'background: #ffffff; color: #000000; font-weight: bold; padding: 4px 8px; border-radius: 4px; border: 2px solid #000000;', 'background: transparent;', 'color: #ffffff; font-style: italic; font-weight: bold;'); - return null; -})(); -export function invoke(msg) { - _invoke === null || _invoke === void 0 ? void 0 : _invoke(msg); -} -/** - * Retrieves the system dark mode status. - * - * @returns A promise that resolves to a boolean value indicating if the system is in dark mode. - */ -export function IsDarkMode() { - return call(SystemIsDarkMode); -} -/** - * Fetches the capabilities of the application from the server. - * - * @returns A promise that resolves to an object containing the capabilities. - */ -export async function Capabilities() { - let response = await fetch("/wails/capabilities"); - if (response.ok) { - return response.json(); - } - else { - throw new Error("could not fetch capabilities: " + response.statusText); - } -} -/** - * Retrieves environment details. - * - * @returns A promise that resolves to an object containing OS and system architecture. - */ -export function Environment() { - return call(SystemEnvironment); -} -/** - * Checks if the current operating system is Windows. - * - * @return True if the operating system is Windows, otherwise false. - */ -export function IsWindows() { - return window._wails.environment.OS === "windows"; -} -/** - * Checks if the current operating system is Linux. - * - * @returns Returns true if the current operating system is Linux, false otherwise. - */ -export function IsLinux() { - return window._wails.environment.OS === "linux"; -} -/** - * Checks if the current environment is a macOS operating system. - * - * @returns True if the environment is macOS, false otherwise. - */ -export function IsMac() { - return window._wails.environment.OS === "darwin"; -} -/** - * Checks if the current environment architecture is AMD64. - * - * @returns True if the current environment architecture is AMD64, false otherwise. - */ -export function IsAMD64() { - return window._wails.environment.Arch === "amd64"; -} -/** - * Checks if the current architecture is ARM. - * - * @returns True if the current architecture is ARM, false otherwise. - */ -export function IsARM() { - return window._wails.environment.Arch === "arm"; -} -/** - * Checks if the current environment is ARM64 architecture. - * - * @returns Returns true if the environment is ARM64 architecture, otherwise returns false. - */ -export function IsARM64() { - return window._wails.environment.Arch === "arm64"; -} -/** - * Reports whether the app is being run in debug mode. - * - * @returns True if the app is being run in debug mode. - */ -export function IsDebug() { - return Boolean(window._wails.environment.Debug); -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/utils.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/utils.js deleted file mode 100644 index 4752828..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/utils.js +++ /dev/null @@ -1,95 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -/** - * Logs a message to the console with custom formatting. - * - * @param message - The message to be logged. - */ -export function debugLog(message) { - // eslint-disable-next-line - console.log('%c wails3 %c ' + message + ' ', 'background: #aa0000; color: #fff; border-radius: 3px 0px 0px 3px; padding: 1px; font-size: 0.7rem', 'background: #009900; color: #fff; border-radius: 0px 3px 3px 0px; padding: 1px; font-size: 0.7rem'); -} -/** - * Checks whether the webview supports the {@link MouseEvent#buttons} property. - * Looking at you macOS High Sierra! - */ -export function canTrackButtons() { - return (new MouseEvent('mousedown')).buttons === 0; -} -/** - * Checks whether the browser supports removing listeners by triggering an AbortSignal - * (see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#signal). - */ -export function canAbortListeners() { - if (!EventTarget || !AbortSignal || !AbortController) - return false; - let result = true; - const target = new EventTarget(); - const controller = new AbortController(); - target.addEventListener('test', () => { result = false; }, { signal: controller.signal }); - controller.abort(); - target.dispatchEvent(new CustomEvent('test')); - return result; -} -/** - * Resolves the closest HTMLElement ancestor of an event's target. - */ -export function eventTarget(event) { - var _a; - if (event.target instanceof HTMLElement) { - return event.target; - } - else if (!(event.target instanceof HTMLElement) && event.target instanceof Node) { - return (_a = event.target.parentElement) !== null && _a !== void 0 ? _a : document.body; - } - else { - return document.body; - } -} -/*** - This technique for proper load detection is taken from HTMX: - - BSD 2-Clause License - - Copyright (c) 2020, Big Sky Software - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - ***/ -let isReady = false; -document.addEventListener('DOMContentLoaded', () => { isReady = true; }); -export function whenReady(callback) { - if (isReady || document.readyState === 'complete') { - callback(); - } - else { - document.addEventListener('DOMContentLoaded', callback); - } -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/window.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/window.js deleted file mode 100644 index c44d1ee..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/window.js +++ /dev/null @@ -1,438 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -import { newRuntimeCaller, objectNames } from "./runtime.js"; -const PositionMethod = 0; -const CenterMethod = 1; -const CloseMethod = 2; -const DisableSizeConstraintsMethod = 3; -const EnableSizeConstraintsMethod = 4; -const FocusMethod = 5; -const ForceReloadMethod = 6; -const FullscreenMethod = 7; -const GetScreenMethod = 8; -const GetZoomMethod = 9; -const HeightMethod = 10; -const HideMethod = 11; -const IsFocusedMethod = 12; -const IsFullscreenMethod = 13; -const IsMaximisedMethod = 14; -const IsMinimisedMethod = 15; -const MaximiseMethod = 16; -const MinimiseMethod = 17; -const NameMethod = 18; -const OpenDevToolsMethod = 19; -const RelativePositionMethod = 20; -const ReloadMethod = 21; -const ResizableMethod = 22; -const RestoreMethod = 23; -const SetPositionMethod = 24; -const SetAlwaysOnTopMethod = 25; -const SetBackgroundColourMethod = 26; -const SetFramelessMethod = 27; -const SetFullscreenButtonEnabledMethod = 28; -const SetMaxSizeMethod = 29; -const SetMinSizeMethod = 30; -const SetRelativePositionMethod = 31; -const SetResizableMethod = 32; -const SetSizeMethod = 33; -const SetTitleMethod = 34; -const SetZoomMethod = 35; -const ShowMethod = 36; -const SizeMethod = 37; -const ToggleFullscreenMethod = 38; -const ToggleMaximiseMethod = 39; -const UnFullscreenMethod = 40; -const UnMaximiseMethod = 41; -const UnMinimiseMethod = 42; -const WidthMethod = 43; -const ZoomMethod = 44; -const ZoomInMethod = 45; -const ZoomOutMethod = 46; -const ZoomResetMethod = 47; -// Private field names. -const callerSym = Symbol("caller"); -class Window { - /** - * Initialises a window object with the specified name. - * - * @private - * @param name - The name of the target window. - */ - constructor(name = '') { - this[callerSym] = newRuntimeCaller(objectNames.Window, name); - // bind instance method to make them easily usable in event handlers - for (const method of Object.getOwnPropertyNames(Window.prototype)) { - if (method !== "constructor" - && typeof this[method] === "function") { - this[method] = this[method].bind(this); - } - } - } - /** - * Gets the specified window. - * - * @param name - The name of the window to get. - * @returns The corresponding window object. - */ - Get(name) { - return new Window(name); - } - /** - * Returns the absolute position of the window. - * - * @returns The current absolute position of the window. - */ - Position() { - return this[callerSym](PositionMethod); - } - /** - * Centers the window on the screen. - */ - Center() { - return this[callerSym](CenterMethod); - } - /** - * Closes the window. - */ - Close() { - return this[callerSym](CloseMethod); - } - /** - * Disables min/max size constraints. - */ - DisableSizeConstraints() { - return this[callerSym](DisableSizeConstraintsMethod); - } - /** - * Enables min/max size constraints. - */ - EnableSizeConstraints() { - return this[callerSym](EnableSizeConstraintsMethod); - } - /** - * Focuses the window. - */ - Focus() { - return this[callerSym](FocusMethod); - } - /** - * Forces the window to reload the page assets. - */ - ForceReload() { - return this[callerSym](ForceReloadMethod); - } - /** - * Switches the window to fullscreen mode. - */ - Fullscreen() { - return this[callerSym](FullscreenMethod); - } - /** - * Returns the screen that the window is on. - * - * @returns The screen the window is currently on. - */ - GetScreen() { - return this[callerSym](GetScreenMethod); - } - /** - * Returns the current zoom level of the window. - * - * @returns The current zoom level. - */ - GetZoom() { - return this[callerSym](GetZoomMethod); - } - /** - * Returns the height of the window. - * - * @returns The current height of the window. - */ - Height() { - return this[callerSym](HeightMethod); - } - /** - * Hides the window. - */ - Hide() { - return this[callerSym](HideMethod); - } - /** - * Returns true if the window is focused. - * - * @returns Whether the window is currently focused. - */ - IsFocused() { - return this[callerSym](IsFocusedMethod); - } - /** - * Returns true if the window is fullscreen. - * - * @returns Whether the window is currently fullscreen. - */ - IsFullscreen() { - return this[callerSym](IsFullscreenMethod); - } - /** - * Returns true if the window is maximised. - * - * @returns Whether the window is currently maximised. - */ - IsMaximised() { - return this[callerSym](IsMaximisedMethod); - } - /** - * Returns true if the window is minimised. - * - * @returns Whether the window is currently minimised. - */ - IsMinimised() { - return this[callerSym](IsMinimisedMethod); - } - /** - * Maximises the window. - */ - Maximise() { - return this[callerSym](MaximiseMethod); - } - /** - * Minimises the window. - */ - Minimise() { - return this[callerSym](MinimiseMethod); - } - /** - * Returns the name of the window. - * - * @returns The name of the window. - */ - Name() { - return this[callerSym](NameMethod); - } - /** - * Opens the development tools pane. - */ - OpenDevTools() { - return this[callerSym](OpenDevToolsMethod); - } - /** - * Returns the relative position of the window to the screen. - * - * @returns The current relative position of the window. - */ - RelativePosition() { - return this[callerSym](RelativePositionMethod); - } - /** - * Reloads the page assets. - */ - Reload() { - return this[callerSym](ReloadMethod); - } - /** - * Returns true if the window is resizable. - * - * @returns Whether the window is currently resizable. - */ - Resizable() { - return this[callerSym](ResizableMethod); - } - /** - * Restores the window to its previous state if it was previously minimised, maximised or fullscreen. - */ - Restore() { - return this[callerSym](RestoreMethod); - } - /** - * Sets the absolute position of the window. - * - * @param x - The desired horizontal absolute position of the window. - * @param y - The desired vertical absolute position of the window. - */ - SetPosition(x, y) { - return this[callerSym](SetPositionMethod, { x, y }); - } - /** - * Sets the window to be always on top. - * - * @param alwaysOnTop - Whether the window should stay on top. - */ - SetAlwaysOnTop(alwaysOnTop) { - return this[callerSym](SetAlwaysOnTopMethod, { alwaysOnTop }); - } - /** - * Sets the background colour of the window. - * - * @param r - The desired red component of the window background. - * @param g - The desired green component of the window background. - * @param b - The desired blue component of the window background. - * @param a - The desired alpha component of the window background. - */ - SetBackgroundColour(r, g, b, a) { - return this[callerSym](SetBackgroundColourMethod, { r, g, b, a }); - } - /** - * Removes the window frame and title bar. - * - * @param frameless - Whether the window should be frameless. - */ - SetFrameless(frameless) { - return this[callerSym](SetFramelessMethod, { frameless }); - } - /** - * Disables the system fullscreen button. - * - * @param enabled - Whether the fullscreen button should be enabled. - */ - SetFullscreenButtonEnabled(enabled) { - return this[callerSym](SetFullscreenButtonEnabledMethod, { enabled }); - } - /** - * Sets the maximum size of the window. - * - * @param width - The desired maximum width of the window. - * @param height - The desired maximum height of the window. - */ - SetMaxSize(width, height) { - return this[callerSym](SetMaxSizeMethod, { width, height }); - } - /** - * Sets the minimum size of the window. - * - * @param width - The desired minimum width of the window. - * @param height - The desired minimum height of the window. - */ - SetMinSize(width, height) { - return this[callerSym](SetMinSizeMethod, { width, height }); - } - /** - * Sets the relative position of the window to the screen. - * - * @param x - The desired horizontal relative position of the window. - * @param y - The desired vertical relative position of the window. - */ - SetRelativePosition(x, y) { - return this[callerSym](SetRelativePositionMethod, { x, y }); - } - /** - * Sets whether the window is resizable. - * - * @param resizable - Whether the window should be resizable. - */ - SetResizable(resizable) { - return this[callerSym](SetResizableMethod, { resizable }); - } - /** - * Sets the size of the window. - * - * @param width - The desired width of the window. - * @param height - The desired height of the window. - */ - SetSize(width, height) { - return this[callerSym](SetSizeMethod, { width, height }); - } - /** - * Sets the title of the window. - * - * @param title - The desired title of the window. - */ - SetTitle(title) { - return this[callerSym](SetTitleMethod, { title }); - } - /** - * Sets the zoom level of the window. - * - * @param zoom - The desired zoom level. - */ - SetZoom(zoom) { - return this[callerSym](SetZoomMethod, { zoom }); - } - /** - * Shows the window. - */ - Show() { - return this[callerSym](ShowMethod); - } - /** - * Returns the size of the window. - * - * @returns The current size of the window. - */ - Size() { - return this[callerSym](SizeMethod); - } - /** - * Toggles the window between fullscreen and normal. - */ - ToggleFullscreen() { - return this[callerSym](ToggleFullscreenMethod); - } - /** - * Toggles the window between maximised and normal. - */ - ToggleMaximise() { - return this[callerSym](ToggleMaximiseMethod); - } - /** - * Un-fullscreens the window. - */ - UnFullscreen() { - return this[callerSym](UnFullscreenMethod); - } - /** - * Un-maximises the window. - */ - UnMaximise() { - return this[callerSym](UnMaximiseMethod); - } - /** - * Un-minimises the window. - */ - UnMinimise() { - return this[callerSym](UnMinimiseMethod); - } - /** - * Returns the width of the window. - * - * @returns The current width of the window. - */ - Width() { - return this[callerSym](WidthMethod); - } - /** - * Zooms the window. - */ - Zoom() { - return this[callerSym](ZoomMethod); - } - /** - * Increases the zoom level of the webview content. - */ - ZoomIn() { - return this[callerSym](ZoomInMethod); - } - /** - * Decreases the zoom level of the webview content. - */ - ZoomOut() { - return this[callerSym](ZoomOutMethod); - } - /** - * Resets the zoom level of the webview content. - */ - ZoomReset() { - return this[callerSym](ZoomResetMethod); - } -} -/** - * The window within which the script is running. - */ -const thisWindow = new Window(''); -export default thisWindow; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/wml.js b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/wml.js deleted file mode 100644 index 9939282..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/dist/wml.js +++ /dev/null @@ -1,179 +0,0 @@ -/* - _ __ _ __ -| | / /___ _(_) /____ -| | /| / / __ `/ / / ___/ -| |/ |/ / /_/ / / (__ ) -|__/|__/\__,_/_/_/____/ -The electron alternative for Go -(c) Lea Anthony 2019-present -*/ -import { OpenURL } from "./browser.js"; -import { Question } from "./dialogs.js"; -import { Emit, WailsEvent } from "./events.js"; -import { canAbortListeners, whenReady } from "./utils.js"; -import Window from "./window.js"; -/** - * Sends an event with the given name and optional data. - * - * @param eventName - - The name of the event to send. - * @param [data=null] - - Optional data to send along with the event. - */ -function sendEvent(eventName, data = null) { - Emit(new WailsEvent(eventName, data)); -} -/** - * Calls a method on a specified window. - * - * @param windowName - The name of the window to call the method on. - * @param methodName - The name of the method to call. - */ -function callWindowMethod(windowName, methodName) { - const targetWindow = Window.Get(windowName); - const method = targetWindow[methodName]; - if (typeof method !== "function") { - console.error(`Window method '${methodName}' not found`); - return; - } - try { - method.call(targetWindow); - } - catch (e) { - console.error(`Error calling window method '${methodName}': `, e); - } -} -/** - * Responds to a triggering event by running appropriate WML actions for the current target. - */ -function onWMLTriggered(ev) { - const element = ev.currentTarget; - function runEffect(choice = "Yes") { - if (choice !== "Yes") - return; - const eventType = element.getAttribute('wml-event') || element.getAttribute('data-wml-event'); - const targetWindow = element.getAttribute('wml-target-window') || element.getAttribute('data-wml-target-window') || ""; - const windowMethod = element.getAttribute('wml-window') || element.getAttribute('data-wml-window'); - const url = element.getAttribute('wml-openurl') || element.getAttribute('data-wml-openurl'); - if (eventType !== null) - sendEvent(eventType); - if (windowMethod !== null) - callWindowMethod(targetWindow, windowMethod); - if (url !== null) - void OpenURL(url); - } - const confirm = element.getAttribute('wml-confirm') || element.getAttribute('data-wml-confirm'); - if (confirm) { - Question({ - Title: "Confirm", - Message: confirm, - Detached: false, - Buttons: [ - { Label: "Yes" }, - { Label: "No", IsDefault: true } - ] - }).then(runEffect); - } - else { - runEffect(); - } -} -// Private field names. -const controllerSym = Symbol("controller"); -const triggerMapSym = Symbol("triggerMap"); -const elementCountSym = Symbol("elementCount"); -/** - * AbortControllerRegistry does not actually remember active event listeners: instead - * it ties them to an AbortSignal and uses an AbortController to remove them all at once. - */ -class AbortControllerRegistry { - constructor() { - this[controllerSym] = new AbortController(); - } - /** - * Returns an options object for addEventListener that ties the listener - * to the AbortSignal from the current AbortController. - * - * @param element - An HTML element - * @param triggers - The list of active WML trigger events for the specified elements - */ - set(element, triggers) { - return { signal: this[controllerSym].signal }; - } - /** - * Removes all registered event listeners and resets the registry. - */ - reset() { - this[controllerSym].abort(); - this[controllerSym] = new AbortController(); - } -} -/** - * WeakMapRegistry maps active trigger events to each DOM element through a WeakMap. - * This ensures that the mapping remains private to this module, while still allowing garbage - * collection of the involved elements. - */ -class WeakMapRegistry { - constructor() { - this[triggerMapSym] = new WeakMap(); - this[elementCountSym] = 0; - } - /** - * Sets active triggers for the specified element. - * - * @param element - An HTML element - * @param triggers - The list of active WML trigger events for the specified element - */ - set(element, triggers) { - if (!this[triggerMapSym].has(element)) { - this[elementCountSym]++; - } - this[triggerMapSym].set(element, triggers); - return {}; - } - /** - * Removes all registered event listeners. - */ - reset() { - if (this[elementCountSym] <= 0) - return; - for (const element of document.body.querySelectorAll('*')) { - if (this[elementCountSym] <= 0) - break; - const triggers = this[triggerMapSym].get(element); - if (triggers != null) { - this[elementCountSym]--; - } - for (const trigger of triggers || []) - element.removeEventListener(trigger, onWMLTriggered); - } - this[triggerMapSym] = new WeakMap(); - this[elementCountSym] = 0; - } -} -const triggerRegistry = canAbortListeners() ? new AbortControllerRegistry() : new WeakMapRegistry(); -/** - * Adds event listeners to the specified element. - */ -function addWMLListeners(element) { - const triggerRegExp = /\S+/g; - const triggerAttr = (element.getAttribute('wml-trigger') || element.getAttribute('data-wml-trigger') || "click"); - const triggers = []; - let match; - while ((match = triggerRegExp.exec(triggerAttr)) !== null) - triggers.push(match[0]); - const options = triggerRegistry.set(element, triggers); - for (const trigger of triggers) - element.addEventListener(trigger, onWMLTriggered, options); -} -/** - * Schedules an automatic reload of WML to be performed as soon as the document is fully loaded. - */ -export function Enable() { - whenReady(Reload); -} -/** - * Reloads the WML page by adding necessary event listeners and browser listeners. - */ -export function Reload() { - triggerRegistry.reset(); - document.body.querySelectorAll('[wml-event], [wml-window], [wml-openurl], [data-wml-event], [data-wml-window], [data-wml-openurl]').forEach(addWMLListeners); -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/package.json b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/package.json deleted file mode 100644 index 495abe2..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "name": "@wailsio/runtime", - "type": "module", - "version": "3.0.0-alpha.66", - "description": "Wails Runtime", - "types": "types/index.d.ts", - "exports": { - "types": "./types/index.d.ts", - "import": "./dist/index.js" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/wailsapp/wails.git", - "directory": "v3/internal/runtime/desktop/@wailsio/runtime" - }, - "author": "The Wails Team", - "license": "MIT", - "homepage": "https://v3.wails.io", - "bugs": { - "url": "https://github.com/wailsapp/wails/issues" - }, - "files": [ - "./dist", - "./types" - ], - "sideEffects": [ - "./dist/index.js", - "./dist/contextmenu.js", - "./dist/drag.js" - ], - "scripts": { - "check": "npx tsc --noEmit", - "test": "npx vitest run", - "clean": "npx rimraf ./dist ./docs ./types ./tsconfig.tsbuildinfo", - "generate:events": "task generate:events", - "generate": "npm run generate:events", - "prebuild": "npm run clean && npm run generate", - "build:code": "npx tsc", - "build:docs": "npx typedoc --plugin typedoc-plugin-mdn-links --plugin typedoc-plugin-missing-exports ./src/index.ts", - "build:docs:md": "npx typedoc --plugin typedoc-plugin-markdown --plugin typedoc-plugin-mdn-links --plugin typedoc-plugin-missing-exports ./src/index.ts", - "build": "npm run build:code & npm run build:docs & wait", - "prepack": "npm run build" - }, - "devDependencies": { - "happy-dom": "^17.1.1", - "promises-aplus-tests": "2.1.2", - "rimraf": "^5.0.5", - "typedoc": "^0.27.7", - "typedoc-plugin-markdown": "^4.4.2", - "typedoc-plugin-mdn-links": "^4.0.13", - "typedoc-plugin-missing-exports": "^3.1.0", - "typescript": "^5.7.3", - "vitest": "^3.0.6" - }, - "overrides": { - "promises-aplus-tests": { - "mocha": "^11.1.0", - "sinon": "^19.0.2", - "underscore": "^1.13.7" - } - } -} diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/application.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/application.d.ts deleted file mode 100644 index bfab64a..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/application.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -/** - * Hides a certain method by calling the HideMethod function. - */ -export declare function Hide(): Promise; -/** - * Calls the ShowMethod and returns the result. - */ -export declare function Show(): Promise; -/** - * Calls the QuitMethod to terminate the program. - */ -export declare function Quit(): Promise; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/browser.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/browser.d.ts deleted file mode 100644 index 799a457..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/browser.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -/** - * Open a browser window to the given URL. - * - * @param url - The URL to open - */ -export declare function OpenURL(url: string | URL): Promise; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/callable.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/callable.d.ts deleted file mode 100644 index 54a1c6c..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/callable.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -declare function isCallableRefApply(value: T | unknown): value is (...args: any[]) => any; -declare const _default: typeof isCallableRefApply; -export default _default; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/calls.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/calls.d.ts deleted file mode 100644 index a96fa80..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/calls.d.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { CancellablePromise } from "./cancellable.js"; -/** - * Holds all required information for a binding call. - * May provide either a method ID or a method name, but not both. - */ -export type CallOptions = { - /** The numeric ID of the bound method to call. */ - methodID: number; - /** The fully qualified name of the bound method to call. */ - methodName?: never; - /** Arguments to be passed into the bound method. */ - args: any[]; -} | { - /** The numeric ID of the bound method to call. */ - methodID?: never; - /** The fully qualified name of the bound method to call. */ - methodName: string; - /** Arguments to be passed into the bound method. */ - args: any[]; -}; -/** - * Exception class that will be thrown in case the bound method returns an error. - * The value of the {@link RuntimeError#name} property is "RuntimeError". - */ -export declare class RuntimeError extends Error { - /** - * Constructs a new RuntimeError instance. - * @param message - The error message. - * @param options - Options to be forwarded to the Error constructor. - */ - constructor(message?: string, options?: ErrorOptions); -} -/** - * Call a bound method according to the given call options. - * - * In case of failure, the returned promise will reject with an exception - * among ReferenceError (unknown method), TypeError (wrong argument count or type), - * {@link RuntimeError} (method returned an error), or other (network or internal errors). - * The exception might have a "cause" field with the value returned - * by the application- or service-level error marshaling functions. - * - * @param options - A method call descriptor. - * @returns The result of the call. - */ -export declare function Call(options: CallOptions): CancellablePromise; -/** - * Calls a bound method by name with the specified arguments. - * See {@link Call} for details. - * - * @param methodName - The name of the method in the format 'package.struct.method'. - * @param args - The arguments to pass to the method. - * @returns The result of the method call. - */ -export declare function ByName(methodName: string, ...args: any[]): CancellablePromise; -/** - * Calls a method by its numeric ID with the specified arguments. - * See {@link Call} for details. - * - * @param methodID - The ID of the method to call. - * @param args - The arguments to pass to the method. - * @return The result of the method call. - */ -export declare function ByID(methodID: number, ...args: any[]): CancellablePromise; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/cancellable.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/cancellable.d.ts deleted file mode 100644 index a65a2ba..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/cancellable.d.ts +++ /dev/null @@ -1,434 +0,0 @@ -/** - * Exception class that will be used as rejection reason - * in case a {@link CancellablePromise} is cancelled successfully. - * - * The value of the {@link name} property is the string `"CancelError"`. - * The value of the {@link cause} property is the cause passed to the cancel method, if any. - */ -export declare class CancelError extends Error { - /** - * Constructs a new `CancelError` instance. - * @param message - The error message. - * @param options - Options to be forwarded to the Error constructor. - */ - constructor(message?: string, options?: ErrorOptions); -} -/** - * Exception class that will be reported as an unhandled rejection - * in case a {@link CancellablePromise} rejects after being cancelled, - * or when the `oncancelled` callback throws or rejects. - * - * The value of the {@link name} property is the string `"CancelledRejectionError"`. - * The value of the {@link cause} property is the reason the promise rejected with. - * - * Because the original promise was cancelled, - * a wrapper promise will be passed to the unhandled rejection listener instead. - * The {@link promise} property holds a reference to the original promise. - */ -export declare class CancelledRejectionError extends Error { - /** - * Holds a reference to the promise that was cancelled and then rejected. - */ - promise: CancellablePromise; - /** - * Constructs a new `CancelledRejectionError` instance. - * @param promise - The promise that caused the error originally. - * @param reason - The rejection reason. - * @param info - An optional informative message specifying the circumstances in which the error was thrown. - * Defaults to the string `"Unhandled rejection in cancelled promise."`. - */ - constructor(promise: CancellablePromise, reason?: any, info?: string); -} -type CancellablePromiseResolver = (value: T | PromiseLike | CancellablePromiseLike) => void; -type CancellablePromiseRejector = (reason?: any) => void; -type CancellablePromiseCanceller = (cause?: any) => void | PromiseLike; -type CancellablePromiseExecutor = (resolve: CancellablePromiseResolver, reject: CancellablePromiseRejector) => void; -export interface CancellablePromiseLike { - then(onfulfilled?: ((value: T) => TResult1 | PromiseLike | CancellablePromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike | CancellablePromiseLike) | undefined | null): CancellablePromiseLike; - cancel(cause?: any): void | PromiseLike; -} -/** - * Wraps a cancellable promise along with its resolution methods. - * The `oncancelled` field will be null initially but may be set to provide a custom cancellation function. - */ -export interface CancellablePromiseWithResolvers { - promise: CancellablePromise; - resolve: CancellablePromiseResolver; - reject: CancellablePromiseRejector; - oncancelled: CancellablePromiseCanceller | null; -} -/** - * A promise with an attached method for cancelling long-running operations (see {@link CancellablePromise#cancel}). - * Cancellation can optionally be bound to an {@link AbortSignal} - * for better composability (see {@link CancellablePromise#cancelOn}). - * - * Cancelling a pending promise will result in an immediate rejection - * with an instance of {@link CancelError} as reason, - * but whoever started the promise will be responsible - * for actually aborting the underlying operation. - * To this purpose, the constructor and all chaining methods - * accept optional cancellation callbacks. - * - * If a `CancellablePromise` still resolves after having been cancelled, - * the result will be discarded. If it rejects, the reason - * will be reported as an unhandled rejection, - * wrapped in a {@link CancelledRejectionError} instance. - * To facilitate the handling of cancellation requests, - * cancelled `CancellablePromise`s will _not_ report unhandled `CancelError`s - * whose `cause` field is the same as the one with which the current promise was cancelled. - * - * All usual promise methods are defined and return a `CancellablePromise` - * whose cancel method will cancel the parent operation as well, propagating the cancellation reason - * upwards through promise chains. - * Conversely, cancelling a promise will not automatically cancel dependent promises downstream: - * ```ts - * let root = new CancellablePromise((resolve, reject) => { ... }); - * let child1 = root.then(() => { ... }); - * let child2 = child1.then(() => { ... }); - * let child3 = root.catch(() => { ... }); - * child1.cancel(); // Cancels child1 and root, but not child2 or child3 - * ``` - * Cancelling a promise that has already settled is safe and has no consequence. - * - * The `cancel` method returns a promise that _always fulfills_ - * after the whole chain has processed the cancel request - * and all attached callbacks up to that moment have run. - * - * All ES2024 promise methods (static and instance) are defined on CancellablePromise, - * but actual availability may vary with OS/webview version. - * - * In line with the proposal at https://github.com/tc39/proposal-rm-builtin-subclassing, - * `CancellablePromise` does not support transparent subclassing. - * Extenders should take care to provide their own method implementations. - * This might be reconsidered in case the proposal is retired. - * - * CancellablePromise is a wrapper around the DOM Promise object - * and is compliant with the [Promises/A+ specification](https://promisesaplus.com/) - * (it passes the [compliance suite](https://github.com/promises-aplus/promises-tests)) - * if so is the underlying implementation. - */ -export declare class CancellablePromise extends Promise implements PromiseLike, CancellablePromiseLike { - static [x: symbol]: PromiseConstructor; - /** - * Creates a new `CancellablePromise`. - * - * @param executor - A callback used to initialize the promise. This callback is passed two arguments: - * a `resolve` callback used to resolve the promise with a value - * or the result of another promise (possibly cancellable), - * and a `reject` callback used to reject the promise with a provided reason or error. - * If the value provided to the `resolve` callback is a thenable _and_ cancellable object - * (it has a `then` _and_ a `cancel` method), - * cancellation requests will be forwarded to that object and the oncancelled will not be invoked anymore. - * If any one of the two callbacks is called _after_ the promise has been cancelled, - * the provided values will be cancelled and resolved as usual, - * but their results will be discarded. - * However, if the resolution process ultimately ends up in a rejection - * that is not due to cancellation, the rejection reason - * will be wrapped in a {@link CancelledRejectionError} - * and bubbled up as an unhandled rejection. - * @param oncancelled - It is the caller's responsibility to ensure that any operation - * started by the executor is properly halted upon cancellation. - * This optional callback can be used to that purpose. - * It will be called _synchronously_ with a cancellation cause - * when cancellation is requested, _after_ the promise has already rejected - * with a {@link CancelError}, but _before_ - * any {@link then}/{@link catch}/{@link finally} callback runs. - * If the callback returns a thenable, the promise returned from {@link cancel} - * will only fulfill after the former has settled. - * Unhandled exceptions or rejections from the callback will be wrapped - * in a {@link CancelledRejectionError} and bubbled up as unhandled rejections. - * If the `resolve` callback is called before cancellation with a cancellable promise, - * cancellation requests on this promise will be diverted to that promise, - * and the original `oncancelled` callback will be discarded. - */ - constructor(executor: CancellablePromiseExecutor, oncancelled?: CancellablePromiseCanceller); - /** - * Cancels immediately the execution of the operation associated with this promise. - * The promise rejects with a {@link CancelError} instance as reason, - * with the {@link CancelError#cause} property set to the given argument, if any. - * - * Has no effect if called after the promise has already settled; - * repeated calls in particular are safe, but only the first one - * will set the cancellation cause. - * - * The `CancelError` exception _need not_ be handled explicitly _on the promises that are being cancelled:_ - * cancelling a promise with no attached rejection handler does not trigger an unhandled rejection event. - * Therefore, the following idioms are all equally correct: - * ```ts - * new CancellablePromise((resolve, reject) => { ... }).cancel(); - * new CancellablePromise((resolve, reject) => { ... }).then(...).cancel(); - * new CancellablePromise((resolve, reject) => { ... }).then(...).catch(...).cancel(); - * ``` - * Whenever some cancelled promise in a chain rejects with a `CancelError` - * with the same cancellation cause as itself, the error will be discarded silently. - * However, the `CancelError` _will still be delivered_ to all attached rejection handlers - * added by {@link then} and related methods: - * ```ts - * let cancellable = new CancellablePromise((resolve, reject) => { ... }); - * cancellable.then(() => { ... }).catch(console.log); - * cancellable.cancel(); // A CancelError is printed to the console. - * ``` - * If the `CancelError` is not handled downstream by the time it reaches - * a _non-cancelled_ promise, it _will_ trigger an unhandled rejection event, - * just like normal rejections would: - * ```ts - * let cancellable = new CancellablePromise((resolve, reject) => { ... }); - * let chained = cancellable.then(() => { ... }).then(() => { ... }); // No catch... - * cancellable.cancel(); // Unhandled rejection event on chained! - * ``` - * Therefore, it is important to either cancel whole promise chains from their tail, - * as shown in the correct idioms above, or take care of handling errors everywhere. - * - * @returns A cancellable promise that _fulfills_ after the cancel callback (if any) - * and all handlers attached up to the call to cancel have run. - * If the cancel callback returns a thenable, the promise returned by `cancel` - * will also wait for that thenable to settle. - * This enables callers to wait for the cancelled operation to terminate - * without being forced to handle potential errors at the call site. - * ```ts - * cancellable.cancel().then(() => { - * // Cleanup finished, it's safe to do something else. - * }, (err) => { - * // Unreachable: the promise returned from cancel will never reject. - * }); - * ``` - * Note that the returned promise will _not_ handle implicitly any rejection - * that might have occurred already in the cancelled chain. - * It will just track whether registered handlers have been executed or not. - * Therefore, unhandled rejections will never be silently handled by calling cancel. - */ - cancel(cause?: any): CancellablePromise; - /** - * Binds promise cancellation to the abort event of the given {@link AbortSignal}. - * If the signal has already aborted, the promise will be cancelled immediately. - * When either condition is verified, the cancellation cause will be set - * to the signal's abort reason (see {@link AbortSignal#reason}). - * - * Has no effect if called (or if the signal aborts) _after_ the promise has already settled. - * Only the first signal to abort will set the cancellation cause. - * - * For more details about the cancellation process, - * see {@link cancel} and the `CancellablePromise` constructor. - * - * This method enables `await`ing cancellable promises without having - * to store them for future cancellation, e.g.: - * ```ts - * await longRunningOperation().cancelOn(signal); - * ``` - * instead of: - * ```ts - * let promiseToBeCancelled = longRunningOperation(); - * await promiseToBeCancelled; - * ``` - * - * @returns This promise, for method chaining. - */ - cancelOn(signal: AbortSignal): CancellablePromise; - /** - * Attaches callbacks for the resolution and/or rejection of the `CancellablePromise`. - * - * The optional `oncancelled` argument will be invoked when the returned promise is cancelled, - * with the same semantics as the `oncancelled` argument of the constructor. - * When the parent promise rejects or is cancelled, the `onrejected` callback will run, - * _even after the returned promise has been cancelled:_ - * in that case, should it reject or throw, the reason will be wrapped - * in a {@link CancelledRejectionError} and bubbled up as an unhandled rejection. - * - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A `CancellablePromise` for the completion of whichever callback is executed. - * The returned promise is hooked up to propagate cancellation requests up the chain, but not down: - * - * - if the parent promise is cancelled, the `onrejected` handler will be invoked with a `CancelError` - * and the returned promise _will resolve regularly_ with its result; - * - conversely, if the returned promise is cancelled, _the parent promise is cancelled too;_ - * the `onrejected` handler will still be invoked with the parent's `CancelError`, - * but its result will be discarded - * and the returned promise will reject with a `CancelError` as well. - * - * The promise returned from {@link cancel} will fulfill only after all attached handlers - * up the entire promise chain have been run. - * - * If either callback returns a cancellable promise, - * cancellation requests will be diverted to it, - * and the specified `oncancelled` callback will be discarded. - */ - then(onfulfilled?: ((value: T) => TResult1 | PromiseLike | CancellablePromiseLike) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike | CancellablePromiseLike) | undefined | null, oncancelled?: CancellablePromiseCanceller): CancellablePromise; - /** - * Attaches a callback for only the rejection of the Promise. - * - * The optional `oncancelled` argument will be invoked when the returned promise is cancelled, - * with the same semantics as the `oncancelled` argument of the constructor. - * When the parent promise rejects or is cancelled, the `onrejected` callback will run, - * _even after the returned promise has been cancelled:_ - * in that case, should it reject or throw, the reason will be wrapped - * in a {@link CancelledRejectionError} and bubbled up as an unhandled rejection. - * - * It is equivalent to - * ```ts - * cancellablePromise.then(undefined, onrejected, oncancelled); - * ``` - * and the same caveats apply. - * - * @returns A Promise for the completion of the callback. - * Cancellation requests on the returned promise - * will propagate up the chain to the parent promise, - * but not in the other direction. - * - * The promise returned from {@link cancel} will fulfill only after all attached handlers - * up the entire promise chain have been run. - * - * If `onrejected` returns a cancellable promise, - * cancellation requests will be diverted to it, - * and the specified `oncancelled` callback will be discarded. - * See {@link then} for more details. - */ - catch(onrejected?: ((reason: any) => (PromiseLike | TResult)) | undefined | null, oncancelled?: CancellablePromiseCanceller): CancellablePromise; - /** - * Attaches a callback that is invoked when the CancellablePromise is settled (fulfilled or rejected). The - * resolved value cannot be accessed or modified from the callback. - * The returned promise will settle in the same state as the original one - * after the provided callback has completed execution, - * unless the callback throws or returns a rejecting promise, - * in which case the returned promise will reject as well. - * - * The optional `oncancelled` argument will be invoked when the returned promise is cancelled, - * with the same semantics as the `oncancelled` argument of the constructor. - * Once the parent promise settles, the `onfinally` callback will run, - * _even after the returned promise has been cancelled:_ - * in that case, should it reject or throw, the reason will be wrapped - * in a {@link CancelledRejectionError} and bubbled up as an unhandled rejection. - * - * This method is implemented in terms of {@link then} and the same caveats apply. - * It is polyfilled, hence available in every OS/webview version. - * - * @returns A Promise for the completion of the callback. - * Cancellation requests on the returned promise - * will propagate up the chain to the parent promise, - * but not in the other direction. - * - * The promise returned from {@link cancel} will fulfill only after all attached handlers - * up the entire promise chain have been run. - * - * If `onfinally` returns a cancellable promise, - * cancellation requests will be diverted to it, - * and the specified `oncancelled` callback will be discarded. - * See {@link then} for more details. - */ - finally(onfinally?: (() => void) | undefined | null, oncancelled?: CancellablePromiseCanceller): CancellablePromise; - /** - * Creates a CancellablePromise that is resolved with an array of results - * when all of the provided Promises resolve, or rejected when any Promise is rejected. - * - * Every one of the provided objects that is a thenable _and_ cancellable object - * will be cancelled when the returned promise is cancelled, with the same cause. - * - * @group Static Methods - */ - static all(values: Iterable>): CancellablePromise[]>; - static all(values: T): CancellablePromise<{ - -readonly [P in keyof T]: Awaited; - }>; - /** - * Creates a CancellablePromise that is resolved with an array of results - * when all of the provided Promises resolve or reject. - * - * Every one of the provided objects that is a thenable _and_ cancellable object - * will be cancelled when the returned promise is cancelled, with the same cause. - * - * @group Static Methods - */ - static allSettled(values: Iterable>): CancellablePromise>[]>; - static allSettled(values: T): CancellablePromise<{ - -readonly [P in keyof T]: PromiseSettledResult>; - }>; - /** - * The any function returns a promise that is fulfilled by the first given promise to be fulfilled, - * or rejected with an AggregateError containing an array of rejection reasons - * if all of the given promises are rejected. - * It resolves all elements of the passed iterable to promises as it runs this algorithm. - * - * Every one of the provided objects that is a thenable _and_ cancellable object - * will be cancelled when the returned promise is cancelled, with the same cause. - * - * @group Static Methods - */ - static any(values: Iterable>): CancellablePromise>; - static any(values: T): CancellablePromise>; - /** - * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved or rejected. - * - * Every one of the provided objects that is a thenable _and_ cancellable object - * will be cancelled when the returned promise is cancelled, with the same cause. - * - * @group Static Methods - */ - static race(values: Iterable>): CancellablePromise>; - static race(values: T): CancellablePromise>; - /** - * Creates a new cancelled CancellablePromise for the provided cause. - * - * @group Static Methods - */ - static cancel(cause?: any): CancellablePromise; - /** - * Creates a new CancellablePromise that cancels - * after the specified timeout, with the provided cause. - * - * If the {@link AbortSignal.timeout} factory method is available, - * it is used to base the timeout on _active_ time rather than _elapsed_ time. - * Otherwise, `timeout` falls back to {@link setTimeout}. - * - * @group Static Methods - */ - static timeout(milliseconds: number, cause?: any): CancellablePromise; - /** - * Creates a new CancellablePromise that resolves after the specified timeout. - * The returned promise can be cancelled without consequences. - * - * @group Static Methods - */ - static sleep(milliseconds: number): CancellablePromise; - /** - * Creates a new CancellablePromise that resolves after - * the specified timeout, with the provided value. - * The returned promise can be cancelled without consequences. - * - * @group Static Methods - */ - static sleep(milliseconds: number, value: T): CancellablePromise; - /** - * Creates a new rejected CancellablePromise for the provided reason. - * - * @group Static Methods - */ - static reject(reason?: any): CancellablePromise; - /** - * Creates a new resolved CancellablePromise. - * - * @group Static Methods - */ - static resolve(): CancellablePromise; - /** - * Creates a new resolved CancellablePromise for the provided value. - * - * @group Static Methods - */ - static resolve(value: T): CancellablePromise>; - /** - * Creates a new resolved CancellablePromise for the provided value. - * - * @group Static Methods - */ - static resolve(value: T | PromiseLike): CancellablePromise>; - /** - * Creates a new CancellablePromise and returns it in an object, along with its resolve and reject functions - * and a getter/setter for the cancellation callback. - * - * This method is polyfilled, hence available in every OS/webview version. - * - * @group Static Methods - */ - static withResolvers(): CancellablePromiseWithResolvers; -} -export {}; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/clipboard.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/clipboard.d.ts deleted file mode 100644 index 4d03634..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/clipboard.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -/** - * Sets the text to the Clipboard. - * - * @param text - The text to be set to the Clipboard. - * @return A Promise that resolves when the operation is successful. - */ -export declare function SetText(text: string): Promise; -/** - * Get the Clipboard text - * - * @returns A promise that resolves with the text from the Clipboard. - */ -export declare function Text(): Promise; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/contextmenu.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/contextmenu.d.ts deleted file mode 100644 index cb0ff5c..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/contextmenu.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/create.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/create.d.ts deleted file mode 100644 index a3332a4..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/create.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Any is a dummy creation function for simple or unknown types. - */ -export declare function Any(source: any): T; -/** - * ByteSlice is a creation function that replaces - * null strings with empty strings. - */ -export declare function ByteSlice(source: any): string; -/** - * Array takes a creation function for an arbitrary type - * and returns an in-place creation function for an array - * whose elements are of that type. - */ -export declare function Array(element: (source: any) => T): (source: any) => T[]; -/** - * Map takes creation functions for two arbitrary types - * and returns an in-place creation function for an object - * whose keys and values are of those types. - */ -export declare function Map(key: (source: any) => string, value: (source: any) => V): (source: any) => Record; -/** - * Nullable takes a creation function for an arbitrary type - * and returns a creation function for a nullable value of that type. - */ -export declare function Nullable(element: (source: any) => T): (source: any) => (T | null); -/** - * Struct takes an object mapping field names to creation functions - * and returns an in-place creation function for a struct. - */ -export declare function Struct(createField: Record any>): = any>(source: any) => U; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/dialogs.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/dialogs.d.ts deleted file mode 100644 index 223d43e..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/dialogs.d.ts +++ /dev/null @@ -1,140 +0,0 @@ -export interface OpenFileDialogOptions { - /** Indicates if directories can be chosen. */ - CanChooseDirectories?: boolean; - /** Indicates if files can be chosen. */ - CanChooseFiles?: boolean; - /** Indicates if directories can be created. */ - CanCreateDirectories?: boolean; - /** Indicates if hidden files should be shown. */ - ShowHiddenFiles?: boolean; - /** Indicates if aliases should be resolved. */ - ResolvesAliases?: boolean; - /** Indicates if multiple selection is allowed. */ - AllowsMultipleSelection?: boolean; - /** Indicates if the extension should be hidden. */ - HideExtension?: boolean; - /** Indicates if hidden extensions can be selected. */ - CanSelectHiddenExtension?: boolean; - /** Indicates if file packages should be treated as directories. */ - TreatsFilePackagesAsDirectories?: boolean; - /** Indicates if other file types are allowed. */ - AllowsOtherFiletypes?: boolean; - /** Array of file filters. */ - Filters?: FileFilter[]; - /** Title of the dialog. */ - Title?: string; - /** Message to show in the dialog. */ - Message?: string; - /** Text to display on the button. */ - ButtonText?: string; - /** Directory to open in the dialog. */ - Directory?: string; - /** Indicates if the dialog should appear detached from the main window. */ - Detached?: boolean; -} -export interface SaveFileDialogOptions { - /** Default filename to use in the dialog. */ - Filename?: string; - /** Indicates if directories can be chosen. */ - CanChooseDirectories?: boolean; - /** Indicates if files can be chosen. */ - CanChooseFiles?: boolean; - /** Indicates if directories can be created. */ - CanCreateDirectories?: boolean; - /** Indicates if hidden files should be shown. */ - ShowHiddenFiles?: boolean; - /** Indicates if aliases should be resolved. */ - ResolvesAliases?: boolean; - /** Indicates if the extension should be hidden. */ - HideExtension?: boolean; - /** Indicates if hidden extensions can be selected. */ - CanSelectHiddenExtension?: boolean; - /** Indicates if file packages should be treated as directories. */ - TreatsFilePackagesAsDirectories?: boolean; - /** Indicates if other file types are allowed. */ - AllowsOtherFiletypes?: boolean; - /** Array of file filters. */ - Filters?: FileFilter[]; - /** Title of the dialog. */ - Title?: string; - /** Message to show in the dialog. */ - Message?: string; - /** Text to display on the button. */ - ButtonText?: string; - /** Directory to open in the dialog. */ - Directory?: string; - /** Indicates if the dialog should appear detached from the main window. */ - Detached?: boolean; -} -export interface MessageDialogOptions { - /** The title of the dialog window. */ - Title?: string; - /** The main message to show in the dialog. */ - Message?: string; - /** Array of button options to show in the dialog. */ - Buttons?: Button[]; - /** True if the dialog should appear detached from the main window (if applicable). */ - Detached?: boolean; -} -export interface Button { - /** Text that appears within the button. */ - Label?: string; - /** True if the button should cancel an operation when clicked. */ - IsCancel?: boolean; - /** True if the button should be the default action when the user presses enter. */ - IsDefault?: boolean; -} -export interface FileFilter { - /** Display name for the filter, it could be "Text Files", "Images" etc. */ - DisplayName?: string; - /** Pattern to match for the filter, e.g. "*.txt;*.md" for text markdown files. */ - Pattern?: string; -} -/** - * Presents an info dialog. - * - * @param options - Dialog options - * @returns A promise that resolves with the label of the chosen button. - */ -export declare function Info(options: MessageDialogOptions): Promise; -/** - * Presents a warning dialog. - * - * @param options - Dialog options. - * @returns A promise that resolves with the label of the chosen button. - */ -export declare function Warning(options: MessageDialogOptions): Promise; -/** - * Presents an error dialog. - * - * @param options - Dialog options. - * @returns A promise that resolves with the label of the chosen button. - */ -export declare function Error(options: MessageDialogOptions): Promise; -/** - * Presents a question dialog. - * - * @param options - Dialog options. - * @returns A promise that resolves with the label of the chosen button. - */ -export declare function Question(options: MessageDialogOptions): Promise; -/** - * Presents a file selection dialog to pick one or more files to open. - * - * @param options - Dialog options. - * @returns Selected file or list of files, or a blank string/empty list if no file has been selected. - */ -export declare function OpenFile(options: OpenFileDialogOptions & { - AllowsMultipleSelection: true; -}): Promise; -export declare function OpenFile(options: OpenFileDialogOptions & { - AllowsMultipleSelection?: false | undefined; -}): Promise; -export declare function OpenFile(options: OpenFileDialogOptions): Promise; -/** - * Presents a file selection dialog to pick a file to save. - * - * @param options - Dialog options. - * @returns Selected file, or a blank string if no file has been selected. - */ -export declare function SaveFile(options: SaveFileDialogOptions): Promise; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/drag.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/drag.d.ts deleted file mode 100644 index cb0ff5c..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/drag.d.ts +++ /dev/null @@ -1 +0,0 @@ -export {}; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/event_types.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/event_types.d.ts deleted file mode 100644 index 382c324..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/event_types.d.ts +++ /dev/null @@ -1,218 +0,0 @@ -export declare const Types: Readonly<{ - Windows: Readonly<{ - APMPowerSettingChange: "windows:APMPowerSettingChange"; - APMPowerStatusChange: "windows:APMPowerStatusChange"; - APMResumeAutomatic: "windows:APMResumeAutomatic"; - APMResumeSuspend: "windows:APMResumeSuspend"; - APMSuspend: "windows:APMSuspend"; - ApplicationStarted: "windows:ApplicationStarted"; - SystemThemeChanged: "windows:SystemThemeChanged"; - WebViewNavigationCompleted: "windows:WebViewNavigationCompleted"; - WindowActive: "windows:WindowActive"; - WindowBackgroundErase: "windows:WindowBackgroundErase"; - WindowClickActive: "windows:WindowClickActive"; - WindowClosing: "windows:WindowClosing"; - WindowDidMove: "windows:WindowDidMove"; - WindowDidResize: "windows:WindowDidResize"; - WindowDPIChanged: "windows:WindowDPIChanged"; - WindowDragDrop: "windows:WindowDragDrop"; - WindowDragEnter: "windows:WindowDragEnter"; - WindowDragLeave: "windows:WindowDragLeave"; - WindowDragOver: "windows:WindowDragOver"; - WindowEndMove: "windows:WindowEndMove"; - WindowEndResize: "windows:WindowEndResize"; - WindowFullscreen: "windows:WindowFullscreen"; - WindowHide: "windows:WindowHide"; - WindowInactive: "windows:WindowInactive"; - WindowKeyDown: "windows:WindowKeyDown"; - WindowKeyUp: "windows:WindowKeyUp"; - WindowKillFocus: "windows:WindowKillFocus"; - WindowNonClientHit: "windows:WindowNonClientHit"; - WindowNonClientMouseDown: "windows:WindowNonClientMouseDown"; - WindowNonClientMouseLeave: "windows:WindowNonClientMouseLeave"; - WindowNonClientMouseMove: "windows:WindowNonClientMouseMove"; - WindowNonClientMouseUp: "windows:WindowNonClientMouseUp"; - WindowPaint: "windows:WindowPaint"; - WindowRestore: "windows:WindowRestore"; - WindowSetFocus: "windows:WindowSetFocus"; - WindowShow: "windows:WindowShow"; - WindowStartMove: "windows:WindowStartMove"; - WindowStartResize: "windows:WindowStartResize"; - WindowUnFullscreen: "windows:WindowUnFullscreen"; - WindowZOrderChanged: "windows:WindowZOrderChanged"; - WindowMinimise: "windows:WindowMinimise"; - WindowUnMinimise: "windows:WindowUnMinimise"; - WindowMaximise: "windows:WindowMaximise"; - WindowUnMaximise: "windows:WindowUnMaximise"; - }>; - Mac: Readonly<{ - ApplicationDidBecomeActive: "mac:ApplicationDidBecomeActive"; - ApplicationDidChangeBackingProperties: "mac:ApplicationDidChangeBackingProperties"; - ApplicationDidChangeEffectiveAppearance: "mac:ApplicationDidChangeEffectiveAppearance"; - ApplicationDidChangeIcon: "mac:ApplicationDidChangeIcon"; - ApplicationDidChangeOcclusionState: "mac:ApplicationDidChangeOcclusionState"; - ApplicationDidChangeScreenParameters: "mac:ApplicationDidChangeScreenParameters"; - ApplicationDidChangeStatusBarFrame: "mac:ApplicationDidChangeStatusBarFrame"; - ApplicationDidChangeStatusBarOrientation: "mac:ApplicationDidChangeStatusBarOrientation"; - ApplicationDidChangeTheme: "mac:ApplicationDidChangeTheme"; - ApplicationDidFinishLaunching: "mac:ApplicationDidFinishLaunching"; - ApplicationDidHide: "mac:ApplicationDidHide"; - ApplicationDidResignActive: "mac:ApplicationDidResignActive"; - ApplicationDidUnhide: "mac:ApplicationDidUnhide"; - ApplicationDidUpdate: "mac:ApplicationDidUpdate"; - ApplicationShouldHandleReopen: "mac:ApplicationShouldHandleReopen"; - ApplicationWillBecomeActive: "mac:ApplicationWillBecomeActive"; - ApplicationWillFinishLaunching: "mac:ApplicationWillFinishLaunching"; - ApplicationWillHide: "mac:ApplicationWillHide"; - ApplicationWillResignActive: "mac:ApplicationWillResignActive"; - ApplicationWillTerminate: "mac:ApplicationWillTerminate"; - ApplicationWillUnhide: "mac:ApplicationWillUnhide"; - ApplicationWillUpdate: "mac:ApplicationWillUpdate"; - MenuDidAddItem: "mac:MenuDidAddItem"; - MenuDidBeginTracking: "mac:MenuDidBeginTracking"; - MenuDidClose: "mac:MenuDidClose"; - MenuDidDisplayItem: "mac:MenuDidDisplayItem"; - MenuDidEndTracking: "mac:MenuDidEndTracking"; - MenuDidHighlightItem: "mac:MenuDidHighlightItem"; - MenuDidOpen: "mac:MenuDidOpen"; - MenuDidPopUp: "mac:MenuDidPopUp"; - MenuDidRemoveItem: "mac:MenuDidRemoveItem"; - MenuDidSendAction: "mac:MenuDidSendAction"; - MenuDidSendActionToItem: "mac:MenuDidSendActionToItem"; - MenuDidUpdate: "mac:MenuDidUpdate"; - MenuWillAddItem: "mac:MenuWillAddItem"; - MenuWillBeginTracking: "mac:MenuWillBeginTracking"; - MenuWillDisplayItem: "mac:MenuWillDisplayItem"; - MenuWillEndTracking: "mac:MenuWillEndTracking"; - MenuWillHighlightItem: "mac:MenuWillHighlightItem"; - MenuWillOpen: "mac:MenuWillOpen"; - MenuWillPopUp: "mac:MenuWillPopUp"; - MenuWillRemoveItem: "mac:MenuWillRemoveItem"; - MenuWillSendAction: "mac:MenuWillSendAction"; - MenuWillSendActionToItem: "mac:MenuWillSendActionToItem"; - MenuWillUpdate: "mac:MenuWillUpdate"; - WebViewDidCommitNavigation: "mac:WebViewDidCommitNavigation"; - WebViewDidFinishNavigation: "mac:WebViewDidFinishNavigation"; - WebViewDidReceiveServerRedirectForProvisionalNavigation: "mac:WebViewDidReceiveServerRedirectForProvisionalNavigation"; - WebViewDidStartProvisionalNavigation: "mac:WebViewDidStartProvisionalNavigation"; - WindowDidBecomeKey: "mac:WindowDidBecomeKey"; - WindowDidBecomeMain: "mac:WindowDidBecomeMain"; - WindowDidBeginSheet: "mac:WindowDidBeginSheet"; - WindowDidChangeAlpha: "mac:WindowDidChangeAlpha"; - WindowDidChangeBackingLocation: "mac:WindowDidChangeBackingLocation"; - WindowDidChangeBackingProperties: "mac:WindowDidChangeBackingProperties"; - WindowDidChangeCollectionBehavior: "mac:WindowDidChangeCollectionBehavior"; - WindowDidChangeEffectiveAppearance: "mac:WindowDidChangeEffectiveAppearance"; - WindowDidChangeOcclusionState: "mac:WindowDidChangeOcclusionState"; - WindowDidChangeOrderingMode: "mac:WindowDidChangeOrderingMode"; - WindowDidChangeScreen: "mac:WindowDidChangeScreen"; - WindowDidChangeScreenParameters: "mac:WindowDidChangeScreenParameters"; - WindowDidChangeScreenProfile: "mac:WindowDidChangeScreenProfile"; - WindowDidChangeScreenSpace: "mac:WindowDidChangeScreenSpace"; - WindowDidChangeScreenSpaceProperties: "mac:WindowDidChangeScreenSpaceProperties"; - WindowDidChangeSharingType: "mac:WindowDidChangeSharingType"; - WindowDidChangeSpace: "mac:WindowDidChangeSpace"; - WindowDidChangeSpaceOrderingMode: "mac:WindowDidChangeSpaceOrderingMode"; - WindowDidChangeTitle: "mac:WindowDidChangeTitle"; - WindowDidChangeToolbar: "mac:WindowDidChangeToolbar"; - WindowDidDeminiaturize: "mac:WindowDidDeminiaturize"; - WindowDidEndSheet: "mac:WindowDidEndSheet"; - WindowDidEnterFullScreen: "mac:WindowDidEnterFullScreen"; - WindowDidEnterVersionBrowser: "mac:WindowDidEnterVersionBrowser"; - WindowDidExitFullScreen: "mac:WindowDidExitFullScreen"; - WindowDidExitVersionBrowser: "mac:WindowDidExitVersionBrowser"; - WindowDidExpose: "mac:WindowDidExpose"; - WindowDidFocus: "mac:WindowDidFocus"; - WindowDidMiniaturize: "mac:WindowDidMiniaturize"; - WindowDidMove: "mac:WindowDidMove"; - WindowDidOrderOffScreen: "mac:WindowDidOrderOffScreen"; - WindowDidOrderOnScreen: "mac:WindowDidOrderOnScreen"; - WindowDidResignKey: "mac:WindowDidResignKey"; - WindowDidResignMain: "mac:WindowDidResignMain"; - WindowDidResize: "mac:WindowDidResize"; - WindowDidUpdate: "mac:WindowDidUpdate"; - WindowDidUpdateAlpha: "mac:WindowDidUpdateAlpha"; - WindowDidUpdateCollectionBehavior: "mac:WindowDidUpdateCollectionBehavior"; - WindowDidUpdateCollectionProperties: "mac:WindowDidUpdateCollectionProperties"; - WindowDidUpdateShadow: "mac:WindowDidUpdateShadow"; - WindowDidUpdateTitle: "mac:WindowDidUpdateTitle"; - WindowDidUpdateToolbar: "mac:WindowDidUpdateToolbar"; - WindowDidZoom: "mac:WindowDidZoom"; - WindowFileDraggingEntered: "mac:WindowFileDraggingEntered"; - WindowFileDraggingExited: "mac:WindowFileDraggingExited"; - WindowFileDraggingPerformed: "mac:WindowFileDraggingPerformed"; - WindowHide: "mac:WindowHide"; - WindowMaximise: "mac:WindowMaximise"; - WindowUnMaximise: "mac:WindowUnMaximise"; - WindowMinimise: "mac:WindowMinimise"; - WindowUnMinimise: "mac:WindowUnMinimise"; - WindowShouldClose: "mac:WindowShouldClose"; - WindowShow: "mac:WindowShow"; - WindowWillBecomeKey: "mac:WindowWillBecomeKey"; - WindowWillBecomeMain: "mac:WindowWillBecomeMain"; - WindowWillBeginSheet: "mac:WindowWillBeginSheet"; - WindowWillChangeOrderingMode: "mac:WindowWillChangeOrderingMode"; - WindowWillClose: "mac:WindowWillClose"; - WindowWillDeminiaturize: "mac:WindowWillDeminiaturize"; - WindowWillEnterFullScreen: "mac:WindowWillEnterFullScreen"; - WindowWillEnterVersionBrowser: "mac:WindowWillEnterVersionBrowser"; - WindowWillExitFullScreen: "mac:WindowWillExitFullScreen"; - WindowWillExitVersionBrowser: "mac:WindowWillExitVersionBrowser"; - WindowWillFocus: "mac:WindowWillFocus"; - WindowWillMiniaturize: "mac:WindowWillMiniaturize"; - WindowWillMove: "mac:WindowWillMove"; - WindowWillOrderOffScreen: "mac:WindowWillOrderOffScreen"; - WindowWillOrderOnScreen: "mac:WindowWillOrderOnScreen"; - WindowWillResignMain: "mac:WindowWillResignMain"; - WindowWillResize: "mac:WindowWillResize"; - WindowWillUnfocus: "mac:WindowWillUnfocus"; - WindowWillUpdate: "mac:WindowWillUpdate"; - WindowWillUpdateAlpha: "mac:WindowWillUpdateAlpha"; - WindowWillUpdateCollectionBehavior: "mac:WindowWillUpdateCollectionBehavior"; - WindowWillUpdateCollectionProperties: "mac:WindowWillUpdateCollectionProperties"; - WindowWillUpdateShadow: "mac:WindowWillUpdateShadow"; - WindowWillUpdateTitle: "mac:WindowWillUpdateTitle"; - WindowWillUpdateToolbar: "mac:WindowWillUpdateToolbar"; - WindowWillUpdateVisibility: "mac:WindowWillUpdateVisibility"; - WindowWillUseStandardFrame: "mac:WindowWillUseStandardFrame"; - WindowZoomIn: "mac:WindowZoomIn"; - WindowZoomOut: "mac:WindowZoomOut"; - WindowZoomReset: "mac:WindowZoomReset"; - }>; - Linux: Readonly<{ - ApplicationStartup: "linux:ApplicationStartup"; - SystemThemeChanged: "linux:SystemThemeChanged"; - WindowDeleteEvent: "linux:WindowDeleteEvent"; - WindowDidMove: "linux:WindowDidMove"; - WindowDidResize: "linux:WindowDidResize"; - WindowFocusIn: "linux:WindowFocusIn"; - WindowFocusOut: "linux:WindowFocusOut"; - WindowLoadChanged: "linux:WindowLoadChanged"; - }>; - Common: Readonly<{ - ApplicationOpenedWithFile: "common:ApplicationOpenedWithFile"; - ApplicationStarted: "common:ApplicationStarted"; - ThemeChanged: "common:ThemeChanged"; - WindowClosing: "common:WindowClosing"; - WindowDidMove: "common:WindowDidMove"; - WindowDidResize: "common:WindowDidResize"; - WindowDPIChanged: "common:WindowDPIChanged"; - WindowFilesDropped: "common:WindowFilesDropped"; - WindowFocus: "common:WindowFocus"; - WindowFullscreen: "common:WindowFullscreen"; - WindowHide: "common:WindowHide"; - WindowLostFocus: "common:WindowLostFocus"; - WindowMaximise: "common:WindowMaximise"; - WindowMinimise: "common:WindowMinimise"; - WindowRestore: "common:WindowRestore"; - WindowRuntimeReady: "common:WindowRuntimeReady"; - WindowShow: "common:WindowShow"; - WindowUnFullscreen: "common:WindowUnFullscreen"; - WindowUnMaximise: "common:WindowUnMaximise"; - WindowUnMinimise: "common:WindowUnMinimise"; - WindowZoom: "common:WindowZoom"; - WindowZoomIn: "common:WindowZoomIn"; - WindowZoomOut: "common:WindowZoomOut"; - WindowZoomReset: "common:WindowZoomReset"; - }>; -}>; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/events.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/events.d.ts deleted file mode 100644 index 11d03e1..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/events.d.ts +++ /dev/null @@ -1,66 +0,0 @@ -export { Types } from "./event_types.js"; -/** - * The type of handlers for a given event. - */ -export type Callback = (ev: WailsEvent) => void; -/** - * Represents a system event or a custom event emitted through wails-provided facilities. - */ -export declare class WailsEvent { - /** - * The name of the event. - */ - name: string; - /** - * Optional data associated with the emitted event. - */ - data: any; - /** - * Name of the originating window. Omitted for application events. - * Will be overridden if set manually. - */ - sender?: string; - constructor(name: string, data?: any); -} -/** - * Register a callback function to be called multiple times for a specific event. - * - * @param eventName - The name of the event to register the callback for. - * @param callback - The callback function to be called when the event is triggered. - * @param maxCallbacks - The maximum number of times the callback can be called for the event. Once the maximum number is reached, the callback will no longer be called. - * @returns A function that, when called, will unregister the callback from the event. - */ -export declare function OnMultiple(eventName: string, callback: Callback, maxCallbacks: number): () => void; -/** - * Registers a callback function to be executed when the specified event occurs. - * - * @param eventName - The name of the event to register the callback for. - * @param callback - The callback function to be called when the event is triggered. - * @returns A function that, when called, will unregister the callback from the event. - */ -export declare function On(eventName: string, callback: Callback): () => void; -/** - * Registers a callback function to be executed only once for the specified event. - * - * @param eventName - The name of the event to register the callback for. - * @param callback - The callback function to be called when the event is triggered. - * @returns A function that, when called, will unregister the callback from the event. - */ -export declare function Once(eventName: string, callback: Callback): () => void; -/** - * Removes event listeners for the specified event names. - * - * @param eventNames - The name of the events to remove listeners for. - */ -export declare function Off(...eventNames: [string, ...string[]]): void; -/** - * Removes all event listeners. - */ -export declare function OffAll(): void; -/** - * Emits the given event. - * - * @param event - The name of the event to emit. - * @returns A promise that will be fulfilled once the event has been emitted. - */ -export declare function Emit(event: WailsEvent): Promise; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/flags.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/flags.d.ts deleted file mode 100644 index 272aa91..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/flags.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -/** - * Retrieves the value associated with the specified key from the flag map. - * - * @param key - The key to retrieve the value for. - * @return The value associated with the specified key. - */ -export declare function GetFlag(key: string): any; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/index.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/index.d.ts deleted file mode 100644 index 54dca22..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/index.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import "./contextmenu.js"; -import "./drag.js"; -import * as Application from "./application.js"; -import * as Browser from "./browser.js"; -import * as Call from "./calls.js"; -import * as Clipboard from "./clipboard.js"; -import * as Create from "./create.js"; -import * as Dialogs from "./dialogs.js"; -import * as Events from "./events.js"; -import * as Flags from "./flags.js"; -import * as Screens from "./screens.js"; -import * as System from "./system.js"; -import Window from "./window.js"; -import * as WML from "./wml.js"; -export { Application, Browser, Call, Clipboard, Dialogs, Events, Flags, Screens, System, Window, WML }; -export * from "./cancellable.js"; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/listener.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/listener.d.ts deleted file mode 100644 index 75bb5c4..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/listener.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -export declare const eventListeners: Map; -export declare class Listener { - eventName: string; - callback: (data: any) => void; - maxCallbacks: number; - constructor(eventName: string, callback: (data: any) => void, maxCallbacks: number); - dispatch(data: any): boolean; -} -export declare function listenerOff(listener: Listener): void; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/nanoid.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/nanoid.d.ts deleted file mode 100644 index a691510..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/nanoid.d.ts +++ /dev/null @@ -1 +0,0 @@ -export declare function nanoid(size?: number): string; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/runtime.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/runtime.d.ts deleted file mode 100644 index 60f7606..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/runtime.d.ts +++ /dev/null @@ -1,22 +0,0 @@ -export declare const objectNames: Readonly<{ - Call: 0; - Clipboard: 1; - Application: 2; - Events: 3; - ContextMenu: 4; - Dialog: 5; - Window: 6; - Screens: 7; - System: 8; - Browser: 9; - CancelCall: 10; -}>; -export declare let clientId: string; -/** - * Creates a new runtime caller with specified ID. - * - * @param object - The object to invoke the method on. - * @param windowName - The name of the window. - * @return The new runtime caller function. - */ -export declare function newRuntimeCaller(object: number, windowName?: string): (method: number, args?: any) => Promise; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/screens.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/screens.d.ts deleted file mode 100644 index b4a2f62..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/screens.d.ts +++ /dev/null @@ -1,60 +0,0 @@ -export interface Size { - /** The width of a rectangular area. */ - Width: number; - /** The height of a rectangular area. */ - Height: number; -} -export interface Rect { - /** The X coordinate of the origin. */ - X: number; - /** The Y coordinate of the origin. */ - Y: number; - /** The width of the rectangle. */ - Width: number; - /** The height of the rectangle. */ - Height: number; -} -export interface Screen { - /** Unique identifier for the screen. */ - ID: string; - /** Human-readable name of the screen. */ - Name: string; - /** The scale factor of the screen (DPI/96). 1 = standard DPI, 2 = HiDPI (Retina), etc. */ - ScaleFactor: number; - /** The X coordinate of the screen. */ - X: number; - /** The Y coordinate of the screen. */ - Y: number; - /** Contains the width and height of the screen. */ - Size: Size; - /** Contains the bounds of the screen in terms of X, Y, Width, and Height. */ - Bounds: Rect; - /** Contains the physical bounds of the screen in terms of X, Y, Width, and Height (before scaling). */ - PhysicalBounds: Rect; - /** Contains the area of the screen that is actually usable (excluding taskbar and other system UI). */ - WorkArea: Rect; - /** Contains the physical WorkArea of the screen (before scaling). */ - PhysicalWorkArea: Rect; - /** True if this is the primary monitor selected by the user in the operating system. */ - IsPrimary: boolean; - /** The rotation of the screen. */ - Rotation: number; -} -/** - * Gets all screens. - * - * @returns A promise that resolves to an array of Screen objects. - */ -export declare function GetAll(): Promise; -/** - * Gets the primary screen. - * - * @returns A promise that resolves to the primary screen. - */ -export declare function GetPrimary(): Promise; -/** - * Gets the current active screen. - * - * @returns A promise that resolves with the current active screen. - */ -export declare function GetCurrent(): Promise; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/system.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/system.d.ts deleted file mode 100644 index 1e1924b..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/system.d.ts +++ /dev/null @@ -1,83 +0,0 @@ -export declare function invoke(msg: any): void; -/** - * Retrieves the system dark mode status. - * - * @returns A promise that resolves to a boolean value indicating if the system is in dark mode. - */ -export declare function IsDarkMode(): Promise; -/** - * Fetches the capabilities of the application from the server. - * - * @returns A promise that resolves to an object containing the capabilities. - */ -export declare function Capabilities(): Promise>; -export interface OSInfo { - /** The branding of the OS. */ - Branding: string; - /** The ID of the OS. */ - ID: string; - /** The name of the OS. */ - Name: string; - /** The version of the OS. */ - Version: string; -} -export interface EnvironmentInfo { - /** The architecture of the system. */ - Arch: string; - /** True if the application is running in debug mode, otherwise false. */ - Debug: boolean; - /** The operating system in use. */ - OS: string; - /** Details of the operating system. */ - OSInfo: OSInfo; - /** Additional platform information. */ - PlatformInfo: Record; -} -/** - * Retrieves environment details. - * - * @returns A promise that resolves to an object containing OS and system architecture. - */ -export declare function Environment(): Promise; -/** - * Checks if the current operating system is Windows. - * - * @return True if the operating system is Windows, otherwise false. - */ -export declare function IsWindows(): boolean; -/** - * Checks if the current operating system is Linux. - * - * @returns Returns true if the current operating system is Linux, false otherwise. - */ -export declare function IsLinux(): boolean; -/** - * Checks if the current environment is a macOS operating system. - * - * @returns True if the environment is macOS, false otherwise. - */ -export declare function IsMac(): boolean; -/** - * Checks if the current environment architecture is AMD64. - * - * @returns True if the current environment architecture is AMD64, false otherwise. - */ -export declare function IsAMD64(): boolean; -/** - * Checks if the current architecture is ARM. - * - * @returns True if the current architecture is ARM, false otherwise. - */ -export declare function IsARM(): boolean; -/** - * Checks if the current environment is ARM64 architecture. - * - * @returns Returns true if the environment is ARM64 architecture, otherwise returns false. - */ -export declare function IsARM64(): boolean; -/** - * Reports whether the app is being run in debug mode. - * - * @returns True if the app is being run in debug mode. - */ -export declare function IsDebug(): boolean; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/utils.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/utils.d.ts deleted file mode 100644 index d748a04..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/utils.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * Logs a message to the console with custom formatting. - * - * @param message - The message to be logged. - */ -export declare function debugLog(message: any): void; -/** - * Checks whether the webview supports the {@link MouseEvent#buttons} property. - * Looking at you macOS High Sierra! - */ -export declare function canTrackButtons(): boolean; -/** - * Checks whether the browser supports removing listeners by triggering an AbortSignal - * (see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#signal). - */ -export declare function canAbortListeners(): boolean; -/** - * Resolves the closest HTMLElement ancestor of an event's target. - */ -export declare function eventTarget(event: Event): HTMLElement; -export declare function whenReady(callback: () => void): void; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/window.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/window.d.ts deleted file mode 100644 index 3acecfb..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/window.d.ts +++ /dev/null @@ -1,292 +0,0 @@ -import type { Screen } from "./screens.js"; -/** - * A record describing the position of a window. - */ -interface Position { - /** The horizontal position of the window. */ - x: number; - /** The vertical position of the window. */ - y: number; -} -/** - * A record describing the size of a window. - */ -interface Size { - /** The width of the window. */ - width: number; - /** The height of the window. */ - height: number; -} -declare const callerSym: unique symbol; -declare class Window { - private [callerSym]; - /** - * Initialises a window object with the specified name. - * - * @private - * @param name - The name of the target window. - */ - constructor(name?: string); - /** - * Gets the specified window. - * - * @param name - The name of the window to get. - * @returns The corresponding window object. - */ - Get(name: string): Window; - /** - * Returns the absolute position of the window. - * - * @returns The current absolute position of the window. - */ - Position(): Promise; - /** - * Centers the window on the screen. - */ - Center(): Promise; - /** - * Closes the window. - */ - Close(): Promise; - /** - * Disables min/max size constraints. - */ - DisableSizeConstraints(): Promise; - /** - * Enables min/max size constraints. - */ - EnableSizeConstraints(): Promise; - /** - * Focuses the window. - */ - Focus(): Promise; - /** - * Forces the window to reload the page assets. - */ - ForceReload(): Promise; - /** - * Switches the window to fullscreen mode. - */ - Fullscreen(): Promise; - /** - * Returns the screen that the window is on. - * - * @returns The screen the window is currently on. - */ - GetScreen(): Promise; - /** - * Returns the current zoom level of the window. - * - * @returns The current zoom level. - */ - GetZoom(): Promise; - /** - * Returns the height of the window. - * - * @returns The current height of the window. - */ - Height(): Promise; - /** - * Hides the window. - */ - Hide(): Promise; - /** - * Returns true if the window is focused. - * - * @returns Whether the window is currently focused. - */ - IsFocused(): Promise; - /** - * Returns true if the window is fullscreen. - * - * @returns Whether the window is currently fullscreen. - */ - IsFullscreen(): Promise; - /** - * Returns true if the window is maximised. - * - * @returns Whether the window is currently maximised. - */ - IsMaximised(): Promise; - /** - * Returns true if the window is minimised. - * - * @returns Whether the window is currently minimised. - */ - IsMinimised(): Promise; - /** - * Maximises the window. - */ - Maximise(): Promise; - /** - * Minimises the window. - */ - Minimise(): Promise; - /** - * Returns the name of the window. - * - * @returns The name of the window. - */ - Name(): Promise; - /** - * Opens the development tools pane. - */ - OpenDevTools(): Promise; - /** - * Returns the relative position of the window to the screen. - * - * @returns The current relative position of the window. - */ - RelativePosition(): Promise; - /** - * Reloads the page assets. - */ - Reload(): Promise; - /** - * Returns true if the window is resizable. - * - * @returns Whether the window is currently resizable. - */ - Resizable(): Promise; - /** - * Restores the window to its previous state if it was previously minimised, maximised or fullscreen. - */ - Restore(): Promise; - /** - * Sets the absolute position of the window. - * - * @param x - The desired horizontal absolute position of the window. - * @param y - The desired vertical absolute position of the window. - */ - SetPosition(x: number, y: number): Promise; - /** - * Sets the window to be always on top. - * - * @param alwaysOnTop - Whether the window should stay on top. - */ - SetAlwaysOnTop(alwaysOnTop: boolean): Promise; - /** - * Sets the background colour of the window. - * - * @param r - The desired red component of the window background. - * @param g - The desired green component of the window background. - * @param b - The desired blue component of the window background. - * @param a - The desired alpha component of the window background. - */ - SetBackgroundColour(r: number, g: number, b: number, a: number): Promise; - /** - * Removes the window frame and title bar. - * - * @param frameless - Whether the window should be frameless. - */ - SetFrameless(frameless: boolean): Promise; - /** - * Disables the system fullscreen button. - * - * @param enabled - Whether the fullscreen button should be enabled. - */ - SetFullscreenButtonEnabled(enabled: boolean): Promise; - /** - * Sets the maximum size of the window. - * - * @param width - The desired maximum width of the window. - * @param height - The desired maximum height of the window. - */ - SetMaxSize(width: number, height: number): Promise; - /** - * Sets the minimum size of the window. - * - * @param width - The desired minimum width of the window. - * @param height - The desired minimum height of the window. - */ - SetMinSize(width: number, height: number): Promise; - /** - * Sets the relative position of the window to the screen. - * - * @param x - The desired horizontal relative position of the window. - * @param y - The desired vertical relative position of the window. - */ - SetRelativePosition(x: number, y: number): Promise; - /** - * Sets whether the window is resizable. - * - * @param resizable - Whether the window should be resizable. - */ - SetResizable(resizable: boolean): Promise; - /** - * Sets the size of the window. - * - * @param width - The desired width of the window. - * @param height - The desired height of the window. - */ - SetSize(width: number, height: number): Promise; - /** - * Sets the title of the window. - * - * @param title - The desired title of the window. - */ - SetTitle(title: string): Promise; - /** - * Sets the zoom level of the window. - * - * @param zoom - The desired zoom level. - */ - SetZoom(zoom: number): Promise; - /** - * Shows the window. - */ - Show(): Promise; - /** - * Returns the size of the window. - * - * @returns The current size of the window. - */ - Size(): Promise; - /** - * Toggles the window between fullscreen and normal. - */ - ToggleFullscreen(): Promise; - /** - * Toggles the window between maximised and normal. - */ - ToggleMaximise(): Promise; - /** - * Un-fullscreens the window. - */ - UnFullscreen(): Promise; - /** - * Un-maximises the window. - */ - UnMaximise(): Promise; - /** - * Un-minimises the window. - */ - UnMinimise(): Promise; - /** - * Returns the width of the window. - * - * @returns The current width of the window. - */ - Width(): Promise; - /** - * Zooms the window. - */ - Zoom(): Promise; - /** - * Increases the zoom level of the webview content. - */ - ZoomIn(): Promise; - /** - * Decreases the zoom level of the webview content. - */ - ZoomOut(): Promise; - /** - * Resets the zoom level of the webview content. - */ - ZoomReset(): Promise; -} -/** - * The window within which the script is running. - */ -declare const thisWindow: Window; -export default thisWindow; diff --git a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/wml.d.ts b/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/wml.d.ts deleted file mode 100644 index 020a3c5..0000000 --- a/node_modules/.pnpm/@wailsio+runtime@3.0.0-alpha.66/node_modules/@wailsio/runtime/types/wml.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -/** - * Schedules an automatic reload of WML to be performed as soon as the document is fully loaded. - */ -export declare function Enable(): void; -/** - * Reloads the WML page by adding necessary event listeners and browser listeners. - */ -export declare function Reload(): void; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/LICENSE b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/LICENSE deleted file mode 100644 index 4a56f14..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2022 JOU Amjs - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/README.md b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/README.md deleted file mode 100644 index ed66242..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/README.md +++ /dev/null @@ -1,77 +0,0 @@ -

- -

- -

Workflow-Streamlined next-generation request tools.
Extremely improve your API using efficiency and save brainpower Just one step

- -

English | Chinese

- -[![npm](https://img.shields.io/npm/v/alova)](https://www.npmjs.com/package/alova) -[![build](https://github.com/alovajs/alova/actions/workflows/release.yml/badge.svg?branch=main)](https://github.com/alovajs/alova/actions/workflows/release.yml) -[![coverage status](https://coveralls.io/repos/github/alovajs/alova/badge.svg?branch=main)](https://coveralls.io/github/alovajs/alova?branch=main) -[![stars](https://img.shields.io/github/stars/alovajs/alova?style=social)](https://github.com/alovajs/alova) -[![discord](https://img.shields.io/badge/chat-Discord-515ff1)](https://discord.gg/S47QGJgkVb) -[![wechat](https://img.shields.io/badge/chat_with_CH-Wechat-07c160)](https://alova.js.org/img/wechat_qrcode.jpg) -[![tree shaking](https://badgen.net/bundlephobia/tree-shaking/alova)](https://bundlephobia.com/package/alova) -![typescript](https://badgen.net/badge/icon/typescript?icon=typescript&label) -![license](https://img.shields.io/badge/license-MIT-blue.svg) - -## What is alova? - -alova(pronounced /əˈləʊva/) is a workflow-streamlined next-generation request tool. Starting from front-end and back-end collaboration and API integration, it streamline API integration workflow from 7 steps to only 1 step, extremely streamline API integration workflow and making network requests very simple. Let's see how alova can help you simplify your work. - -![](https://alova.js.org/img/overview_flow_en.png) - -## Is there any difference? - -Unlike other request libraries, alova aims to make requests very simple and maintain more efficient data interaction. - -We consider both developers and App users. For developers, alova provides them with the ultimate user experience, and for application users, they can enjoy the smooth experience brought by alova's high-performance data interaction. - -In addition, let's take a look at the specific features: - -- The API design similar to Axios makes the learning cost of users lower; -- High-performance client and server request strategies make the application smoother; -- High flexibility, Alova's adapter allows Alova to work with any UI framework in any JS environment, and provides a unified user experience and perfect code migration; -- 2 cache modes and request sharing mechanisms to improve request performance and reduce server pressure; -- High aggregation organization of API code, each API's request parameters, cache behavior, response data conversion, etc. will be gathered in the same code block, which is a great advantage for managing a large number of APIs; - -> You can also check [Comparison with other request libraries](https://alova.js.org/about/comparison) to learn more about the differences of Alova. - -## Documentation - -Visit the [alova website](https://alova.js.org) for more information, or [check out the examples to try running](https://alova.js.org/category/examples). - -## Join the community - -- [Follow us on X to get the latest updates](https://x.com/alovajs) - -- [Join the Discord](https://discord.gg/S47QGJgkVb) - -- [Join the WeChat group](https://alova.js.org/img/wechat_qrcode.jpg) - -## We need your support - -If you like alova, we are very grateful for giving us a star in the upper right corner, which is a recognition and encouragement for our work. - -## Welcome to contribute - -We are honored to receive active participation from developers around the world in Issues and Discussions. - -We hope to make alova a common project for everyone who is willing to participate, rather than the alova team. We encourage everyone to become a contributor to the alova community with an open and inclusive attitude. Even if you are a junior developer, as long as your ideas meet the development guidelines of alova, please participate generously. - -Effective contributions will win you a certain reputation in the Alova community. Before contributing, please be sure to read the [Contribution Guide](https://github.com/alovajs/alova/blob/main/CONTRIBUTING.md) in detail to ensure your contribution is effective. - -## Changelog - -[Link](https://github.com/alovajs/alova/releases) - -## Contributors - - - - - -## LICENSE - -[MIT](https://en.wikipedia.org/wiki/MIT_License) diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/README.zh-CN.md b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/README.zh-CN.md deleted file mode 100644 index ae844c1..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/README.zh-CN.md +++ /dev/null @@ -1,75 +0,0 @@ -

- -

- -

工作流精简的下一代请求工具
极致地简化你的API集成工作流,仅需一步

- -

📑English | 中文

- -[![npm](https://img.shields.io/npm/v/alova)](https://www.npmjs.com/package/alova) -[![build](https://github.com/alovajs/alova/actions/workflows/release.yml/badge.svg?branch=main)](https://github.com/alovajs/alova/actions/workflows/release.yml) -[![coverage status](https://coveralls.io/repos/github/alovajs/alova/badge.svg?branch=main)](https://coveralls.io/github/alovajs/alova?branch=main) -[![stars](https://img.shields.io/github/stars/alovajs/alova?style=social)](https://github.com/alovajs/alova) -[![discord](https://img.shields.io/badge/chat-Discord-515ff1)](https://discord.gg/S47QGJgkVb) -[![wechat](https://img.shields.io/badge/chat_with_CH-Wechat-07c160)](https://alova.js.org/img/wechat_qrcode.jpg) -[![tree shaking](https://badgen.net/bundlephobia/tree-shaking/alova)](https://bundlephobia.com/package/alova) -![typescript](https://badgen.net/badge/icon/typescript?icon=typescript&label) -![license](https://img.shields.io/badge/license-MIT-blue.svg) - -## alova 是什么? - -alova(读作/əˈləʊva/)是一个流程精简的下一代请求工具,从前后端协作和 API 集成作为出发点,将 API 集成步骤从 7 步简化为只有 1 步,极致地简化 API 集成工作流,让网络请求变得非常简单。我们来看看 alova 是如何帮你的简化工作的。 - -![](https://alova.js.org/img/overview_flow_cn.png) - -## 有什么不同吗? - -与其他请求库不同的是,alova 的目标是让请求变得非常简单,并且保持更高效的数据交互。 - -我们为开发者和 App 使用者双方考虑,对于开发者来说,alova 为他们提供了极致的使用体验,对于应用的用户来说,他们可以享受到 alova 的高性能数据交互带来的流畅体验。 - -此外,再从具体的特性来看看: - -- 与 axios 相似的 api 设计,让使用者学习成本更低; -- 高性能的客户端和服务端请求策略,让应用更流畅; -- 灵活性高,alova 的适配器可以让 alova 在任何 js 环境下,与任何 UI 框架协作使用,并且提供了统一的使用体验和完美的代码迁移; -- 2 种缓存模式和请求共享机制,提升请求性能并降低服务端压力; -- api 代码的高聚合组织,每个 api 的请求参数、缓存行为、响应数据转换等都将聚集在相同的代码块中,这对于管理大量的 api 有很大的优势; - -> 你还可以查看请[与其他请求库比较](https://alova.js.org/about/comparison)详细了解 alova 的不同之处。 - -## 文档 - -访问[alova 网站](https://alova.js.org)了解更多信息,或[查尝试运行的示例](https://alova.js.org/category/examples)。 - -## 加入交流社区 - -- [在 X 上关注我们,持续获得最新动态](https://x.com/alovajs) -- [加入在 Discord 社区参与交流](https://discord.gg/S47QGJgkVb) -- [加入微信群参与交流](https://alova.js.org/img/wechat_qrcode.jpg) - -## 我们需要你的支持 - -如果你喜欢 alova,我们非常感谢您在右上角给我们 star,这是对我们工作的认可和鼓励。 - -## 欢迎参与贡献 - -我们在 Issues 和 Disscussion 中收到了来自世界各地的开发者积极参与的信息,深感荣幸。 - -我们期望将 alova 打造成每位愿意参与的人的共同项目,而不是 alova 团队的,我们以开放包容的态度鼓励每个人成为 alova 社区的贡献者,即使你是一位初级开发者,只要想法符合 alova 的发展准则,也请大方地参与进来。 - -有效的贡献将为你赢得一定的 alova 社区名望。在参与贡献前,请务必详细阅读 [贡献指南](https://github.com/alovajs/alova/blob/main/CONTRIBUTING.zh-CN.md),以保证你的有效贡献。 - -## Changelog - -[前往查看](https://github.com/alovajs/alova/releases) - -## Contributors - - - - - -## LICENSE - -[MIT](https://en.wikipedia.org/wiki/MIT_License) diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/adapter/fetch.common.cjs b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/adapter/fetch.common.cjs deleted file mode 100644 index a88fe5d..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/adapter/fetch.common.cjs +++ /dev/null @@ -1,92 +0,0 @@ -/** - * alova 3.2.10 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -'use strict'; - -var shared = require('@alova/shared'); - -const isBodyData = (data) => shared.isString(data) || shared.isSpecialRequestBody(data); -function adapterFetch() { - return (elements, method) => { - const adapterConfig = method.config; - const timeout = adapterConfig.timeout || 0; - const ctrl = new AbortController(); - const { data, headers } = elements; - const isContentTypeSet = /content-type/i.test(shared.ObjectCls.keys(headers).join()); - const isDataFormData = data && data.toString() === '[object FormData]'; - // When the content type is not set and the data is not a form data object, the content type is set to application/json by default. - if (!isContentTypeSet && !isDataFormData) { - headers['Content-Type'] = 'application/json;charset=UTF-8'; - } - const fetchPromise = fetch(elements.url, { - ...adapterConfig, - method: elements.type, - signal: ctrl.signal, - body: isBodyData(data) ? data : shared.JSONStringify(data) - }); - // If the interruption time is set, the request will be interrupted after the specified time. - let abortTimer; - let isTimeout = shared.falseValue; - if (timeout > 0) { - abortTimer = shared.setTimeoutFn(() => { - isTimeout = shared.trueValue; - ctrl.abort(); - }, timeout); - } - return { - response: () => fetchPromise.then(response => { - // Clear interrupt processing after successful request - shared.clearTimeoutTimer(abortTimer); - // Response's readable can only be read once and needs to be cloned before it can be reused. - return response.clone(); - }, err => shared.promiseReject(isTimeout ? shared.newInstance(Error, 'fetchError: network timeout') : err)), - // The then in the Headers function needs to catch exceptions, otherwise the correct error object will not be obtained internally. - headers: () => fetchPromise.then(({ headers: responseHeaders }) => responseHeaders, () => ({})), - // Due to limitations of the node fetch library, this code cannot be unit tested, but it has passed the test in the browser. - /* c8 ignore start */ - onDownload: async (cb) => { - let isAborted = shared.falseValue; - const response = await fetchPromise.catch(() => { - isAborted = shared.trueValue; - }); - if (!response) - return; - const { headers: responseHeaders, body } = response.clone(); - const reader = body ? body.getReader() : shared.undefinedValue; - const total = Number(responseHeaders.get('Content-Length') || responseHeaders.get('content-length') || 0); - if (total <= 0) { - return; - } - let loaded = 0; - if (reader) { - const pump = () => reader.read().then(({ done, value = new Uint8Array() }) => { - if (done || isAborted) { - isAborted && cb(total, 0); - } - else { - loaded += value.byteLength; - cb(total, loaded); - return pump(); - } - }); - pump(); - } - }, - onUpload() { - // eslint-disable-next-line no-console - console.error("fetch API does'nt support uploading progress. please consider to change `@alova/adapter-xhr` or `@alova/adapter-axios`"); - }, - /* c8 ignore stop */ - abort: () => { - ctrl.abort(); - shared.clearTimeoutTimer(abortTimer); - } - }; - }; -} - -module.exports = adapterFetch; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/adapter/fetch.esm.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/adapter/fetch.esm.js deleted file mode 100644 index 091d013..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/adapter/fetch.esm.js +++ /dev/null @@ -1,90 +0,0 @@ -/** - * alova 3.2.10 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -import { ObjectCls, JSONStringify, setTimeoutFn, clearTimeoutTimer, promiseReject, newInstance, undefinedValue, isString, isSpecialRequestBody, falseValue, trueValue } from '@alova/shared'; - -const isBodyData = (data) => isString(data) || isSpecialRequestBody(data); -function adapterFetch() { - return (elements, method) => { - const adapterConfig = method.config; - const timeout = adapterConfig.timeout || 0; - const ctrl = new AbortController(); - const { data, headers } = elements; - const isContentTypeSet = /content-type/i.test(ObjectCls.keys(headers).join()); - const isDataFormData = data && data.toString() === '[object FormData]'; - // When the content type is not set and the data is not a form data object, the content type is set to application/json by default. - if (!isContentTypeSet && !isDataFormData) { - headers['Content-Type'] = 'application/json;charset=UTF-8'; - } - const fetchPromise = fetch(elements.url, { - ...adapterConfig, - method: elements.type, - signal: ctrl.signal, - body: isBodyData(data) ? data : JSONStringify(data) - }); - // If the interruption time is set, the request will be interrupted after the specified time. - let abortTimer; - let isTimeout = falseValue; - if (timeout > 0) { - abortTimer = setTimeoutFn(() => { - isTimeout = trueValue; - ctrl.abort(); - }, timeout); - } - return { - response: () => fetchPromise.then(response => { - // Clear interrupt processing after successful request - clearTimeoutTimer(abortTimer); - // Response's readable can only be read once and needs to be cloned before it can be reused. - return response.clone(); - }, err => promiseReject(isTimeout ? newInstance(Error, 'fetchError: network timeout') : err)), - // The then in the Headers function needs to catch exceptions, otherwise the correct error object will not be obtained internally. - headers: () => fetchPromise.then(({ headers: responseHeaders }) => responseHeaders, () => ({})), - // Due to limitations of the node fetch library, this code cannot be unit tested, but it has passed the test in the browser. - /* c8 ignore start */ - onDownload: async (cb) => { - let isAborted = falseValue; - const response = await fetchPromise.catch(() => { - isAborted = trueValue; - }); - if (!response) - return; - const { headers: responseHeaders, body } = response.clone(); - const reader = body ? body.getReader() : undefinedValue; - const total = Number(responseHeaders.get('Content-Length') || responseHeaders.get('content-length') || 0); - if (total <= 0) { - return; - } - let loaded = 0; - if (reader) { - const pump = () => reader.read().then(({ done, value = new Uint8Array() }) => { - if (done || isAborted) { - isAborted && cb(total, 0); - } - else { - loaded += value.byteLength; - cb(total, loaded); - return pump(); - } - }); - pump(); - } - }, - onUpload() { - // eslint-disable-next-line no-console - console.error("fetch API does'nt support uploading progress. please consider to change `@alova/adapter-xhr` or `@alova/adapter-axios`"); - }, - /* c8 ignore stop */ - abort: () => { - ctrl.abort(); - clearTimeoutTimer(abortTimer); - } - }; - }; -} - -export { adapterFetch as default }; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/adapter/fetch.umd.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/adapter/fetch.umd.js deleted file mode 100644 index abd7a9b..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/adapter/fetch.umd.js +++ /dev/null @@ -1,150 +0,0 @@ -/** - * alova 3.2.10 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.alovaFetch = factory()); -})(this, (function () { 'use strict'; - - /** - * @alova/shared 1.1.2 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) - */ - - const undefStr = 'undefined'; - // The following unified processing functions or variables added to reduce the amount of compiled code - const PromiseCls = Promise; - const promiseReject = (value) => PromiseCls.reject(value); - const ObjectCls = Object; - const undefinedValue = undefined; - const trueValue = true; - const falseValue = false; - const JSONStringify = (value, replacer, space) => JSON.stringify(value, replacer, space); - const setTimeoutFn = (fn, delay = 0) => setTimeout(fn, delay); - const clearTimeoutTimer = (timer) => clearTimeout(timer); - const typeOf = (arg) => typeof arg; - // Whether it is running on the server side, node and bun are judged by process, and deno is judged by Deno. - // Some frameworks (such as Alipay and uniapp) will inject the process object as a global variable. - // Therefore, the process.cwd function unique to the server is used as the basis for judgment. - typeof window === undefStr && - (typeof process !== undefStr ? typeof process.cwd === 'function' : typeof Deno !== undefStr); - /** - * Determine whether the parameter is a string any parameter - * @returns Whether the parameter is a string - */ - const isString = (arg) => typeOf(arg) === 'string'; - /** - * Global toString any parameter stringified parameters - */ - const globalToString = (arg) => ObjectCls.prototype.toString.call(arg); - /** - * Determine whether it is an instance of a certain class any parameter - * @returns Judgment result - */ - const instanceOf = (arg, cls) => arg instanceof cls; - /** - * Is it special data - * @param data Submit data - * @returns Judgment result - */ - const isSpecialRequestBody = (data) => { - const dataTypeString = globalToString(data); - return (/^\[object (Blob|FormData|ReadableStream|URLSearchParams)\]$/i.test(dataTypeString) || instanceOf(data, ArrayBuffer)); - }; - /** - * Create class instance - * @param Cls Constructor - * @param args Constructor parameters class instance - */ - const newInstance = (Cls, ...args) => new Cls(...args); - - const isBodyData = (data) => isString(data) || isSpecialRequestBody(data); - function adapterFetch() { - return (elements, method) => { - const adapterConfig = method.config; - const timeout = adapterConfig.timeout || 0; - const ctrl = new AbortController(); - const { data, headers } = elements; - const isContentTypeSet = /content-type/i.test(ObjectCls.keys(headers).join()); - const isDataFormData = data && data.toString() === '[object FormData]'; - // When the content type is not set and the data is not a form data object, the content type is set to application/json by default. - if (!isContentTypeSet && !isDataFormData) { - headers['Content-Type'] = 'application/json;charset=UTF-8'; - } - const fetchPromise = fetch(elements.url, { - ...adapterConfig, - method: elements.type, - signal: ctrl.signal, - body: isBodyData(data) ? data : JSONStringify(data) - }); - // If the interruption time is set, the request will be interrupted after the specified time. - let abortTimer; - let isTimeout = falseValue; - if (timeout > 0) { - abortTimer = setTimeoutFn(() => { - isTimeout = trueValue; - ctrl.abort(); - }, timeout); - } - return { - response: () => fetchPromise.then(response => { - // Clear interrupt processing after successful request - clearTimeoutTimer(abortTimer); - // Response's readable can only be read once and needs to be cloned before it can be reused. - return response.clone(); - }, err => promiseReject(isTimeout ? newInstance(Error, 'fetchError: network timeout') : err)), - // The then in the Headers function needs to catch exceptions, otherwise the correct error object will not be obtained internally. - headers: () => fetchPromise.then(({ headers: responseHeaders }) => responseHeaders, () => ({})), - // Due to limitations of the node fetch library, this code cannot be unit tested, but it has passed the test in the browser. - /* c8 ignore start */ - onDownload: async (cb) => { - let isAborted = falseValue; - const response = await fetchPromise.catch(() => { - isAborted = trueValue; - }); - if (!response) - return; - const { headers: responseHeaders, body } = response.clone(); - const reader = body ? body.getReader() : undefinedValue; - const total = Number(responseHeaders.get('Content-Length') || responseHeaders.get('content-length') || 0); - if (total <= 0) { - return; - } - let loaded = 0; - if (reader) { - const pump = () => reader.read().then(({ done, value = new Uint8Array() }) => { - if (done || isAborted) { - isAborted && cb(total, 0); - } - else { - loaded += value.byteLength; - cb(total, loaded); - return pump(); - } - }); - pump(); - } - }, - onUpload() { - // eslint-disable-next-line no-console - console.error("fetch API does'nt support uploading progress. please consider to change `@alova/adapter-xhr` or `@alova/adapter-axios`"); - }, - /* c8 ignore stop */ - abort: () => { - ctrl.abort(); - clearTimeoutTimer(abortTimer); - } - }; - }; - } - - return adapterFetch; - -})); diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/adapter/fetch.umd.min.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/adapter/fetch.umd.min.js deleted file mode 100644 index ac98894..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/adapter/fetch.umd.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).alovaFetch=t()}(this,(function(){"use strict";const e="undefined",t=Promise,o=Object,n=!0,r=!1,a=e=>clearTimeout(e);typeof window===e&&typeof process!==e&&process.cwd;const s=e=>{const t=(n=e,o.prototype.toString.call(n));var n;return/^\[object (Blob|FormData|ReadableStream|URLSearchParams)\]$/i.test(t)||((e,t)=>e instanceof t)(e,ArrayBuffer)},i=e=>"string"===(e=>typeof e)(e)||s(e);return function(){return(e,s)=>{const c=s.config,d=c.timeout||0,l=new AbortController,{data:f,headers:u}=e,p=/content-type/i.test(o.keys(u).join()),h=f&&"[object FormData]"===f.toString();p||h||(u["Content-Type"]="application/json;charset=UTF-8");const y=fetch(e.url,{...c,method:e.type,signal:l.signal,body:i(f)?f:(g=f,JSON.stringify(g,b,m))});var g,b,m;let w,j=r;return d>0&&(w=((e,t=0)=>setTimeout(e,t))((()=>{j=n,l.abort()}),d)),{response:()=>y.then((e=>(a(w),e.clone())),(e=>(e=>t.reject(e))(j?((e,...t)=>new e(...t))(Error,"fetchError: network timeout"):e))),headers:()=>y.then((({headers:e})=>e),(()=>({}))),onDownload:async e=>{let t=r;const o=await y.catch((()=>{t=n}));if(!o)return;const{headers:a,body:s}=o.clone(),i=s?s.getReader():undefined,c=Number(a.get("Content-Length")||a.get("content-length")||0);if(c<=0)return;let d=0;if(i){const o=()=>i.read().then((({done:n,value:r=new Uint8Array})=>{if(!n&&!t)return d+=r.byteLength,e(c,d),o();t&&e(c,0)}));o()}},onUpload(){console.error("fetch API does'nt support uploading progress. please consider to change `@alova/adapter-xhr` or `@alova/adapter-axios`")},abort:()=>{l.abort(),a(w)}}}}})); diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/alova.common.cjs b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/alova.common.cjs deleted file mode 100644 index a23814d..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/alova.common.cjs +++ /dev/null @@ -1,930 +0,0 @@ -/** - * alova 3.2.10 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -'use strict'; - -var shared = require('@alova/shared'); - -exports.globalConfigMap = { - autoHitCache: 'global', - ssr: shared.isSSR -}; -/** - * Set global configuration - * @param config - */ -var globalConfig = (config) => { - exports.globalConfigMap = { - ...exports.globalConfigMap, - ...config - }; -}; - -const titleStyle = 'color: black; font-size: 12px; font-weight: bolder'; -/** - * Default cacheLogger function - */ -var defaultCacheLogger = (response, methodInstance, cacheMode, tag) => { - const cole = console; - // eslint-disable-next-line - const log = (...args) => console.log(...args); - const { url } = methodInstance; - const isRestoreMode = cacheMode === shared.STORAGE_RESTORE; - const hdStyle = '\x1B[42m%s\x1B[49m'; - const labelStyle = '\x1B[32m%s\x1B[39m'; - const startSep = ` [HitCache]${url} `; - const endSepFn = () => Array(shared.len(startSep) + 1).join('^'); - if (exports.globalConfigMap.ssr) { - log(hdStyle, startSep); - log(labelStyle, ' Cache ', response); - log(labelStyle, ' Mode ', cacheMode); - isRestoreMode && log(labelStyle, ' Tag ', tag); - log(labelStyle, endSepFn()); - } - else { - cole.groupCollapsed - ? cole.groupCollapsed('%cHitCache', 'padding: 2px 6px; background: #c4fcd3; color: #53b56d;', url) - : log(hdStyle, startSep); - log('%c[Cache]', titleStyle, response); - log('%c[Mode]', titleStyle, cacheMode); - isRestoreMode && log('%c[Tag]', titleStyle, tag); - log('%c[Method]', titleStyle, methodInstance); - cole.groupEnd ? cole.groupEnd() : log(labelStyle, endSepFn()); - } -}; - -const hitSourceStringCacheKey = (key) => `hss.${key}`; -const hitSourceRegexpPrefix = 'hsr.'; -const hitSourceRegexpCacheKey = (regexpStr) => hitSourceRegexpPrefix + regexpStr; -const unifiedHitSourceRegexpCacheKey = '$$hsrs'; -const regexpSourceFlagSeparator = '__$<>$__'; -const addItem = (obj, item) => { - obj[item] = 0; -}; -/** - * set or update cache - * @param namespace namespace - * @param key stored key - * @param response Stored response content - * @param expireTimestamp Timestamp representation of expiration time point - * @param storage storage object - * @param tag Storage tags, used to distinguish different storage tags - */ -const setWithCacheAdapter = async (namespace, key, data, expireTimestamp, cacheAdapter, hitSource, tag) => { - // not to cache if expireTimestamp is less than current timestamp - if (expireTimestamp > shared.getTime() && data) { - const methodCacheKey = shared.buildNamespacedCacheKey(namespace, key); - await cacheAdapter.set(methodCacheKey, shared.filterItem([data, expireTimestamp === Infinity ? shared.undefinedValue : expireTimestamp, tag], Boolean)); - // save the relationship between this method and its hitSources. - // cache structure is like this: - /* - { - "$a.[namespace][methodKey]": [cache data], - ... - "hss.[sourceMethodKey]": "{ - [targetMethodKey1]: 0, - [targetMethodKey2]: 0, - ... - }", - "hss.[sourceMethodName]": "{ - [targetMethodKey3]: 0, - [targetMethodKey4]: 0, - ... - }", - "hsr.[sourceMethodNameRegexpSource]": "{ - [targetMethodKey5]: 0, - [targetMethodKey6]: 0, - ... - }", - "hsr.regexp1": ["hss.key1", "hss.key2"], - "hsr.regexp2": ["hss.key1", "hss.key2"] - } - */ - if (hitSource) { - // filter repeat items and categorize the regexp, to prevent unnecessary cost of IO - const hitSourceKeys = {}; - const hitSourceRegexpSources = []; - shared.forEach(hitSource, sourceItem => { - const isRegexp = shared.instanceOf(sourceItem, shared.RegExpCls); - const targetHitSourceKey = isRegexp - ? sourceItem.source + (sourceItem.flags ? regexpSourceFlagSeparator + sourceItem.flags : '') - : sourceItem; - if (targetHitSourceKey) { - if (isRegexp && !hitSourceKeys[targetHitSourceKey]) { - shared.pushItem(hitSourceRegexpSources, targetHitSourceKey); - } - addItem(hitSourceKeys, isRegexp ? hitSourceRegexpCacheKey(targetHitSourceKey) : hitSourceStringCacheKey(targetHitSourceKey)); - } - }); - // save the relationship. Minimize IO as much as possible - const promises = shared.mapItem(shared.objectKeys(hitSourceKeys), async (hitSourceKey) => { - // filter the empty strings. - const targetMethodKeys = (await cacheAdapter.get(hitSourceKey)) || {}; - addItem(targetMethodKeys, methodCacheKey); - await cacheAdapter.set(hitSourceKey, targetMethodKeys); - }); - const saveRegexp = async () => { - // save the regexp source if regexp exists. - if (shared.len(hitSourceRegexpSources)) { - const regexpList = (await cacheAdapter.get(unifiedHitSourceRegexpCacheKey)) || []; - // TODO: hitSourceRegexpSources needs to be deduplicated - shared.pushItem(regexpList, ...hitSourceRegexpSources); - await cacheAdapter.set(unifiedHitSourceRegexpCacheKey, regexpList); - } - }; - // parallel executing all async tasks. - await shared.PromiseCls.all([...promises, saveRegexp()]); - } - } -}; -/** - * Delete stored response data - * @param namespace namespace - * @param key stored key - * @param storage storage object - */ -const removeWithCacheAdapter = async (namespace, key, cacheAdapter) => { - const methodStoreKey = shared.buildNamespacedCacheKey(namespace, key); - await cacheAdapter.remove(methodStoreKey); -}; -/** - * Get stored response data - * @param namespace namespace - * @param key stored key - * @param storage storage object - * @param tag Store tags. If the tag changes, the data will become invalid. - */ -const getRawWithCacheAdapter = async (namespace, key, cacheAdapter, tag) => { - const storagedData = await cacheAdapter.get(shared.buildNamespacedCacheKey(namespace, key)); - if (storagedData) { - // Eslint disable next line - const [dataUnused, expireTimestamp, storedTag] = storagedData; - // If there is no expiration time, it means that the data will never expire. Otherwise, you need to determine whether it has expired. - if (storedTag === tag && (!expireTimestamp || expireTimestamp > shared.getTime())) { - return storagedData; - } - // If expired, delete cache - await removeWithCacheAdapter(namespace, key, cacheAdapter); - } -}; -/** - * Get stored response data - * @param namespace namespace - * @param key stored key - * @param storage storage object - * @param tag Store tags. If the tag changes, the data will become invalid. - */ -const getWithCacheAdapter = async (namespace, key, cacheAdapter, tag) => { - const rawData = await getRawWithCacheAdapter(namespace, key, cacheAdapter, tag); - return rawData ? rawData[0] : shared.undefinedValue; -}; -/** - * clear all cached data - */ -const clearWithCacheAdapter = async (cacheAdapters) => shared.PromiseCls.all(cacheAdapters.map(cacheAdapter => cacheAdapter.clear())); -/** - * query and delete target cache with key and name of source method instance. - * @param sourceKey source method instance key - * @param sourceName source method instance name - * @param cacheAdapter cache adapter - */ -const hitTargetCacheWithCacheAdapter = async (sourceKey, sourceName, cacheAdapter) => { - const sourceNameStr = `${sourceName}`; - // map that recording the source key and target method keys. - const sourceTargetKeyMap = {}; - // get hit key by method key. - const hitSourceKey = hitSourceStringCacheKey(sourceKey); - sourceTargetKeyMap[hitSourceKey] = await cacheAdapter.get(hitSourceKey); - let unifiedHitSourceRegexpChannel; - if (sourceName) { - const hitSourceName = hitSourceStringCacheKey(sourceNameStr); - // get hit key by method name if it is exists. - sourceTargetKeyMap[hitSourceName] = await cacheAdapter.get(hitSourceName); - // match regexped key by source method name and get hit key by method name. - unifiedHitSourceRegexpChannel = await cacheAdapter.get(unifiedHitSourceRegexpCacheKey); - const matchedRegexpStrings = []; - if (unifiedHitSourceRegexpChannel && shared.len(unifiedHitSourceRegexpChannel)) { - shared.forEach(unifiedHitSourceRegexpChannel, regexpStr => { - const [source, flag] = regexpStr.split(regexpSourceFlagSeparator); - if (shared.newInstance(shared.RegExpCls, source, flag).test(sourceNameStr)) { - shared.pushItem(matchedRegexpStrings, regexpStr); - } - }); - // parallel get hit key by matched regexps. - await shared.PromiseCls.all(shared.mapItem(matchedRegexpStrings, async (regexpString) => { - const hitSourceRegexpString = hitSourceRegexpCacheKey(regexpString); - sourceTargetKeyMap[hitSourceRegexpString] = await cacheAdapter.get(hitSourceRegexpString); - })); - } - } - const removeWithTargetKey = async (targetKey) => { - try { - await cacheAdapter.remove(targetKey); - // loop sourceTargetKeyMap and remove this key to prevent unnecessary cost of IO. - for (const sourceKey in sourceTargetKeyMap) { - const targetKeys = sourceTargetKeyMap[sourceKey]; - if (targetKeys) { - shared.deleteAttr(targetKeys, targetKey); - } - } - } - catch (_a) { - // the try-catch is used to prevent throwing error, cause throwing error in `Promise.all` below. - } - }; - // now let's start to delete target caches. - // and filter the finished keys. - const accessedKeys = {}; - await shared.PromiseCls.all(shared.mapItem(shared.objectKeys(sourceTargetKeyMap), async (sourceKey) => { - const targetKeys = sourceTargetKeyMap[sourceKey]; - if (targetKeys) { - const removingPromises = []; - for (const key in targetKeys) { - if (!accessedKeys[key]) { - addItem(accessedKeys, key); - shared.pushItem(removingPromises, removeWithTargetKey(key)); - } - } - await shared.PromiseCls.all(removingPromises); - } - })); - // update source key if there is still has keys. - // remove source key if its keys is empty. - const unifiedHitSourceRegexpChannelLen = shared.len(unifiedHitSourceRegexpChannel || []); - await shared.PromiseCls.all(shared.mapItem(shared.objectKeys(sourceTargetKeyMap), async (sourceKey) => { - const targetKeys = sourceTargetKeyMap[sourceKey]; - if (targetKeys) { - if (shared.len(shared.objectKeys(targetKeys))) { - await cacheAdapter.set(sourceKey, targetKeys); - } - else { - await cacheAdapter.remove(sourceKey); - // if this is a regexped key, need to remove it from unified regexp channel. - if (sourceKey.includes(hitSourceRegexpPrefix) && unifiedHitSourceRegexpChannel) { - unifiedHitSourceRegexpChannel = shared.filterItem(unifiedHitSourceRegexpChannel, rawRegexpStr => hitSourceRegexpCacheKey(rawRegexpStr) !== sourceKey); - } - } - } - })); - // update unified hit source regexp channel if its length was changed. - if (unifiedHitSourceRegexpChannelLen !== shared.len(unifiedHitSourceRegexpChannel || [])) { - await cacheAdapter.set(unifiedHitSourceRegexpCacheKey, unifiedHitSourceRegexpChannel); - } -}; - -var cloneMethod = (methodInstance) => { - const { data, config } = methodInstance; - const newConfig = { ...config }; - const { headers = {}, params = {} } = newConfig; - const ctx = shared.getContext(methodInstance); - newConfig.headers = { ...headers }; - newConfig.params = { ...params }; - const newMethod = shared.newInstance((Method), methodInstance.type, ctx, methodInstance.url, newConfig, data); - return shared.objAssign(newMethod, { - ...methodInstance, - config: newConfig - }); -}; - -/* - * The matchers in the following three functions are Method instance matchers, which are divided into three situations: - * 1. If the matcher is a Method instance, clear the cache of the Method instance. - * 2. If matcher is a string or regular expression, clear the cache of all Method instances that meet the conditions. - * 3. If no matcher is passed in, all caches will be cleared. - */ -/** - * Query cache - * @param matcher Method instance matcher - * @returns Cache data, return undefined if not found - */ -const queryCache = async (matcher, { policy = 'all' } = {}) => { - // if key exists, that means it's a method instance. - if (matcher && matcher.key) { - const { id, l1Cache, l2Cache } = shared.getContext(matcher); - const methodKey = shared.getMethodInternalKey(matcher); - const { f: cacheFor, c: controlled, s: store, e: expireMilliseconds, t: tag } = shared.getLocalCacheConfigParam(matcher); - // if it's controlled cache, it will return the result of cacheFor function. - if (controlled) { - return cacheFor(); - } - let cachedData = policy !== 'l2' ? await getWithCacheAdapter(id, methodKey, l1Cache) : shared.undefinedValue; - if (policy === 'l2') { - cachedData = await getWithCacheAdapter(id, methodKey, l2Cache, tag); - } - else if (policy === 'all' && !cachedData) { - if (store && expireMilliseconds(shared.STORAGE_RESTORE) > shared.getTime()) { - cachedData = await getWithCacheAdapter(id, methodKey, l2Cache, tag); - } - } - return cachedData; - } -}; -/** - * Manually set cache response data. If the corresponding methodInstance sets persistent storage, the cache in the persistent storage will also be checked out. - * @param matcher Method instance matcher cache data - */ -const setCache = async (matcher, dataOrUpdater, { policy = 'all' } = {}) => { - const methodInstances = shared.isArray(matcher) ? matcher : [matcher]; - const batchPromises = methodInstances.map(async (methodInstance) => { - const { hitSource } = methodInstance; - const { id, l1Cache, l2Cache } = shared.getContext(methodInstance); - const methodKey = shared.getMethodInternalKey(methodInstance); - const { e: expireMilliseconds, s: toStore, t: tag, c: controlled } = shared.getLocalCacheConfigParam(methodInstance); - // don't set cache when it's controlled cache. - if (controlled) { - return; - } - let data = dataOrUpdater; - if (shared.isFn(dataOrUpdater)) { - let cachedData = policy !== 'l2' ? await getWithCacheAdapter(id, methodKey, l1Cache) : shared.undefinedValue; - if (policy === 'l2' || - (policy === 'all' && !cachedData && toStore && expireMilliseconds(shared.STORAGE_RESTORE) > shared.getTime())) { - cachedData = await getWithCacheAdapter(id, methodKey, l2Cache, tag); - } - data = dataOrUpdater(cachedData); - if (data === shared.undefinedValue) { - return; - } - } - return shared.PromiseCls.all([ - policy !== 'l2' && setWithCacheAdapter(id, methodKey, data, expireMilliseconds(shared.MEMORY), l1Cache, hitSource), - policy === 'l2' || (policy === 'all' && toStore) - ? setWithCacheAdapter(id, methodKey, data, expireMilliseconds(shared.STORAGE_RESTORE), l2Cache, hitSource, tag) - : shared.undefinedValue - ]); - }); - return shared.PromiseCls.all(batchPromises); -}; -/** - * invalid cache - * @param matcher Method instance matcher - */ -const invalidateCache = async (matcher) => { - if (!matcher) { - await shared.PromiseCls.all([clearWithCacheAdapter(usingL1CacheAdapters), clearWithCacheAdapter(usingL2CacheAdapters)]); - return; - } - const methodInstances = shared.isArray(matcher) ? matcher : [matcher]; - const batchPromises = methodInstances.map(methodInstance => { - const { id, l1Cache, l2Cache } = shared.getContext(methodInstance); - const { c: controlled, m: cacheMode } = shared.getLocalCacheConfigParam(methodInstance); - // don't invalidate cache when it's controlled cache. - if (controlled) { - return; - } - const methodKey = shared.getMethodInternalKey(methodInstance); - return shared.PromiseCls.all([ - removeWithCacheAdapter(id, methodKey, l1Cache), - cacheMode === shared.STORAGE_RESTORE ? removeWithCacheAdapter(id, methodKey, l2Cache) : shared.promiseResolve() - ]); - }); - await shared.PromiseCls.all(batchPromises); -}; -/** - * hit(invalidate) target caches by source method - * this is the implementation of auto invalidate cache - * @param sourceMethod source method instance - */ -const hitCacheBySource = async (sourceMethod) => { - // Find the hit target cache and invalidate its cache - // Control the automatic cache invalidation range through global configuration `autoHitCache` - const { autoHitCache } = exports.globalConfigMap; - const { l1Cache, l2Cache } = shared.getContext(sourceMethod); - const sourceKey = shared.getMethodInternalKey(sourceMethod); - const { name: sourceName } = shared.getConfig(sourceMethod); - const cacheAdaptersInvolved = { - global: [...usingL1CacheAdapters, ...usingL2CacheAdapters], - self: [l1Cache, l2Cache], - close: [] - }[autoHitCache]; - if (cacheAdaptersInvolved && shared.len(cacheAdaptersInvolved)) { - await shared.PromiseCls.all(shared.mapItem(cacheAdaptersInvolved, involvedCacheAdapter => hitTargetCacheWithCacheAdapter(sourceKey, sourceName, involvedCacheAdapter))); - } -}; - -const adapterReturnMap = {}; -/** - * actual request function - * @param method request method object - * @param forceRequest Ignore cache - * @returns response data - */ -function sendRequest(methodInstance, forceRequest) { - let fromCache = shared.trueValue; - let requestAdapterCtrlsPromiseResolveFn; - const requestAdapterCtrlsPromise = shared.newInstance(shared.PromiseCls, resolve => { - requestAdapterCtrlsPromiseResolveFn = resolve; - }); - const response = async () => { - const { beforeRequest = shared.noop, responded, requestAdapter, cacheLogger } = shared.getOptions(methodInstance); - const methodKey = shared.getMethodInternalKey(methodInstance); - const { s: toStorage, t: tag, m: cacheMode, e: expireMilliseconds } = shared.getLocalCacheConfigParam(methodInstance); - const { id, l1Cache, l2Cache, snapshots } = shared.getContext(methodInstance); - // Get controlled cache or uncontrolled cache - const { cacheFor } = shared.getConfig(methodInstance); - const { hitSource: methodHitSource } = methodInstance; - // If the current method sets a controlled cache, check whether there is custom data - let cachedResponse = await (shared.isFn(cacheFor) - ? cacheFor() - : // If it is a forced request, skip the step of getting it from the cache - // Otherwise, determine whether to use cached data - forceRequest - ? shared.undefinedValue - : getWithCacheAdapter(id, methodKey, l1Cache)); - // If it is storage restore mode and there is no data in the cache, the persistent data needs to be restored to the cache, and the cached expiration time must be used. - if (cacheMode === shared.STORAGE_RESTORE && !cachedResponse && !forceRequest) { - const rawL2CacheData = await getRawWithCacheAdapter(id, methodKey, l2Cache, tag); - if (rawL2CacheData) { - const [l2Response, l2ExpireMilliseconds] = rawL2CacheData; - await setWithCacheAdapter(id, methodKey, l2Response, l2ExpireMilliseconds, l1Cache, methodHitSource); - cachedResponse = l2Response; - } - } - // Clone the method as a parameter and pass it to beforeRequest to prevent side effects when using the original method instance request multiple times. - // Place it after `let cachedResponse = await...` to solve the problem of first assigning promise to the method instance in method.send, otherwise the promise will be undefined in clonedMethod. - const clonedMethod = cloneMethod(methodInstance); - // Call the hook function before sending the request - // beforeRequest supports synchronous functions and asynchronous functions - await beforeRequest(clonedMethod); - const { baseURL, url: newUrl, type, data } = clonedMethod; - const { params = {}, headers = {}, transform = shared.$self, shareRequest } = shared.getConfig(clonedMethod); - const namespacedAdapterReturnMap = (adapterReturnMap[id] = adapterReturnMap[id] || {}); - const requestBody = clonedMethod.data; - const requestBodyIsSpecial = shared.isSpecialRequestBody(requestBody); - // Will not share the request when requestBody is special data - let requestAdapterCtrls = requestBodyIsSpecial ? shared.undefinedValue : namespacedAdapterReturnMap[methodKey]; - let responseSuccessHandler = shared.$self; - let responseErrorHandler = shared.undefinedValue; - let responseCompleteHandler = shared.noop; - // uniform handler of onSuccess, onError, onComplete - if (shared.isFn(responded)) { - responseSuccessHandler = responded; - } - else if (shared.isPlainObject(responded)) { - const { onSuccess: successHandler, onError: errorHandler, onComplete: completeHandler } = responded; - responseSuccessHandler = shared.isFn(successHandler) ? successHandler : responseSuccessHandler; - responseErrorHandler = shared.isFn(errorHandler) ? errorHandler : responseErrorHandler; - responseCompleteHandler = shared.isFn(completeHandler) ? completeHandler : responseCompleteHandler; - } - // If there is no cache, make a request - if (cachedResponse !== shared.undefinedValue) { - requestAdapterCtrlsPromiseResolveFn(); // Ctrls will not be passed in when cache is encountered - // Print cache log - clonedMethod.fromCache = shared.trueValue; - shared.sloughFunction(cacheLogger, defaultCacheLogger)(cachedResponse, clonedMethod, cacheMode, tag); - responseCompleteHandler(clonedMethod); - return cachedResponse; - } - fromCache = shared.falseValue; - if (!shareRequest || !requestAdapterCtrls) { - // Request data - const ctrls = requestAdapter({ - url: shared.buildCompletedURL(baseURL, newUrl, params), - type, - data, - headers - }, clonedMethod); - requestAdapterCtrls = namespacedAdapterReturnMap[methodKey] = ctrls; - } - // Pass request adapter ctrls to promise for use in on download, on upload and abort - requestAdapterCtrlsPromiseResolveFn(requestAdapterCtrls); - /** - * Process response tasks and do not cache data on failure - * @param responsePromise Respond to promise instances - * @param responseHeaders Request header - * @param callInSuccess Whether to call in success callback - * @returns Processed response - */ - const handleResponseTask = async (handlerReturns, responseHeaders, callInSuccess = shared.trueValue) => { - const responseData = await handlerReturns; - const transformedData = await transform(responseData, responseHeaders || {}); - snapshots.save(methodInstance); - // Even if the cache operation fails, the response structure will be returned normally to avoid request errors caused by cache operation problems. - // The cache operation results can be obtained through `cacheAdapter.emitter.on('success' | 'fail', event => {})` - try { - // Automatic cache invalidation - await hitCacheBySource(clonedMethod); - } - catch (_a) { } - // Do not save cache when requestBody is special data - // Reason 1: Special data is generally submitted and requires interaction with the server. - // Reason 2: Special data is not convenient for generating cache keys - const toCache = !requestBody || !requestBodyIsSpecial; - // Use the latest expiration time after the response to cache data to avoid the problem of expiration time loss due to too long response time - if (toCache && callInSuccess) { - try { - await shared.PromiseCls.all([ - setWithCacheAdapter(id, methodKey, transformedData, expireMilliseconds(shared.MEMORY), l1Cache, methodHitSource), - toStorage && - setWithCacheAdapter(id, methodKey, transformedData, expireMilliseconds(shared.STORAGE_RESTORE), l2Cache, methodHitSource, tag) - ]); - } - catch (_b) { } - } - // Deep clone the transformed data before returning to avoid reference issues - // the `deepClone` will only clone array and plain object - return shared.deepClone(transformedData); - }; - return shared.promiseFinally(shared.promiseThen(shared.PromiseCls.all([requestAdapterCtrls.response(), requestAdapterCtrls.headers()]), ([rawResponse, rawHeaders]) => { - // Regardless of whether the request succeeds or fails, the shared request needs to be removed first - shared.deleteAttr(namespacedAdapterReturnMap, methodKey); - return handleResponseTask(responseSuccessHandler(rawResponse, clonedMethod), rawHeaders); - }, (error) => { - // Regardless of whether the request succeeds or fails, the shared request needs to be removed first - shared.deleteAttr(namespacedAdapterReturnMap, methodKey); - return shared.isFn(responseErrorHandler) - ? // When responding to an error, if no error is thrown, the successful response process will be processed, but the data will not be cached. - handleResponseTask(responseErrorHandler(error, clonedMethod), shared.undefinedValue, shared.falseValue) - : shared.promiseReject(error); - }), () => { - responseCompleteHandler(clonedMethod); - }); - }; - return { - // request interrupt function - abort: () => { - shared.promiseThen(requestAdapterCtrlsPromise, requestAdapterCtrls => requestAdapterCtrls && requestAdapterCtrls.abort()); - }, - onDownload: (handler) => { - shared.promiseThen(requestAdapterCtrlsPromise, requestAdapterCtrls => requestAdapterCtrls && requestAdapterCtrls.onDownload && requestAdapterCtrls.onDownload(handler)); - }, - onUpload: (handler) => { - shared.promiseThen(requestAdapterCtrlsPromise, requestAdapterCtrls => requestAdapterCtrls && requestAdapterCtrls.onUpload && requestAdapterCtrls.onUpload(handler)); - }, - response, - fromCache: () => fromCache - }; -} - -const offEventCallback = (offHandler, handlers) => () => { - const index = handlers.indexOf(offHandler); - index >= 0 && handlers.splice(index, 1); -}; -class Method { - constructor(type, context, url, config, data) { - this.dhs = []; - this.uhs = []; - this.fromCache = shared.undefinedValue; - const abortRequest = () => { - abortRequest.a(); - }; - abortRequest.a = shared.noop; - const instance = this; - const contextOptions = shared.getContextOptions(context); - instance.abort = abortRequest; - instance.baseURL = contextOptions.baseURL || ''; - instance.url = url; - instance.type = type; - instance.context = context; - // Merge request-related global configuration into the method object - const contextConcatConfig = {}; - const mergedLocalCacheKey = 'cacheFor'; - const globalLocalCache = shared.isPlainObject(contextOptions[mergedLocalCacheKey]) - ? contextOptions[mergedLocalCacheKey][type] - : shared.undefinedValue; - const hitSource = config && config.hitSource; - // Merge parameters - shared.forEach(['timeout', 'shareRequest'], mergedKey => { - if (contextOptions[mergedKey] !== shared.undefinedValue) { - contextConcatConfig[mergedKey] = contextOptions[mergedKey]; - } - }); - // Merge local cache - if (globalLocalCache !== shared.undefinedValue) { - contextConcatConfig[mergedLocalCacheKey] = globalLocalCache; - } - // Unify hit sources into arrays and convert them into method keys when there are method instances - if (hitSource) { - instance.hitSource = shared.mapItem(shared.isArray(hitSource) ? hitSource : [hitSource], sourceItem => shared.instanceOf(sourceItem, Method) ? shared.getMethodInternalKey(sourceItem) : sourceItem); - shared.deleteAttr(config, 'hitSource'); - } - instance.config = { - ...contextConcatConfig, - headers: {}, - params: {}, - ...(config || {}) - }; - instance.data = data; - instance.meta = config ? config.meta : instance.meta; - // The original key needs to be used externally instead of generating the key in real time. - // The reason is that the parameters of the method may pass in reference type values, but when the reference type value changes externally, the key generated in real time also changes, so it is more accurate to use the initial key. - instance.key = instance.generateKey(); - } - /** - * Bind download progress callback function - * @param progressHandler Download progress callback function - * @version 2.17.0 - * @return unbind function - */ - onDownload(downloadHandler) { - shared.pushItem(this.dhs, downloadHandler); - return offEventCallback(downloadHandler, this.dhs); - } - /** - * Bind upload progress callback function - * @param progressHandler Upload progress callback function - * @version 2.17.0 - * @return unbind function - */ - onUpload(uploadHandler) { - shared.pushItem(this.uhs, uploadHandler); - return offEventCallback(uploadHandler, this.uhs); - } - /** - * Send a request through a method instance and return a promise object - */ - send(forceRequest = shared.falseValue) { - const instance = this; - const { response, onDownload, onUpload, abort, fromCache } = sendRequest(instance, forceRequest); - shared.len(instance.dhs) > 0 && - onDownload((loaded, total) => shared.forEach(instance.dhs, handler => handler({ loaded, total }))); - shared.len(instance.uhs) > 0 && onUpload((loaded, total) => shared.forEach(instance.uhs, handler => handler({ loaded, total }))); - // The interrupt function is bound to the method instance for each request. The user can also interrupt the current request through method instance.abort() - instance.abort.a = abort; - instance.fromCache = shared.undefinedValue; - instance.promise = shared.promiseThen(response(), r => { - instance.fromCache = fromCache(); - return r; - }); - return instance.promise; - } - /** - * Set the method name, if there is already a name it will be overwritten - * @param name method name - */ - setName(name) { - shared.getConfig(this).name = name; - } - generateKey() { - return shared.key(this); - } - /** - * Bind callbacks for resolve and/or reject Promise - * @param onfulfilled The callback to be executed when resolving the Promise - * @param onrejected The callback to be executed when the Promise is rejected - * @returns Returns a Promise for executing any callbacks - */ - then(onfulfilled, onrejected) { - return shared.promiseThen(this.send(), onfulfilled, onrejected); - } - /** - * Bind a callback only for reject Promise - * @param onrejected The callback to be executed when the Promise is rejected - * @returns Returns a Promise that completes the callback - */ - catch(onrejected) { - return shared.promiseCatch(this.send(), onrejected); - } - /** - * Bind a callback that is called when the Promise is resolved (resolve or reject) - * @param onfinally Callback executed when Promise is resolved (resolve or reject). - * @return Returns a Promise that completes the callback. - */ - finally(onfinally) { - return shared.promiseFinally(this.send(), onfinally); - } -} - -/** - * Custom assertion function, throws an error when the expression is false - * @param expression Judgment expression, true or false - * @param msg assert message - */ -const myAssert = shared.createAssert(); - -// local storage will not fail the operation. -const EVENT_SUCCESS_KEY = 'success'; -const memoryAdapter = () => { - let l1Cache = {}; - const l1CacheEmitter = shared.createEventManager(); - const adapter = { - set(key, value) { - l1Cache[key] = value; - l1CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'set', key, value, container: l1Cache }); - }, - get: key => { - const value = l1Cache[key]; - l1CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'get', key, value, container: l1Cache }); - return value; - }, - remove(key) { - shared.deleteAttr(l1Cache, key); - l1CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'remove', key, container: l1Cache }); - }, - clear: () => { - l1Cache = {}; - l1CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'clear', key: '', container: l1Cache }); - }, - emitter: l1CacheEmitter - }; - return adapter; -}; -const localStorageAdapter = () => { - const l2CacheEmitter = shared.createEventManager(); - const instance = localStorage; - const adapter = { - set: (key, value) => { - instance.setItem(key, shared.JSONStringify(value)); - l2CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'set', key, value, container: instance }); - }, - get: key => { - const data = instance.getItem(key); - const value = data ? shared.JSONParse(data) : data; - l2CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'get', key, value, container: instance }); - return value; - }, - remove: key => { - instance.removeItem(key); - l2CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'remove', key, container: instance }); - }, - clear: () => { - instance.clear(); - l2CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'clear', key: '', container: instance }); - }, - emitter: l2CacheEmitter - }; - return adapter; -}; -const placeholderAdapter = () => { - const l2CacheNotDefinedAssert = () => { - myAssert(shared.falseValue, 'l2Cache is not defined.'); - }; - return { - set: () => { - l2CacheNotDefinedAssert(); - }, - get: () => { - l2CacheNotDefinedAssert(); - return shared.undefinedValue; - }, - remove: () => { - l2CacheNotDefinedAssert(); - }, - clear: () => { } - }; -}; - -const SetCls = Set; -class MethodSnapshotContainer { - constructor(capacity) { - /** - * Method instance snapshot collection, method instances that have sent requests will be saved - */ - this.records = {}; - this.occupy = 0; - myAssert(capacity >= 0, 'expected snapshots limit to be >= 0'); - this.capacity = capacity; - } - /** - * Save method instance snapshot - * @param methodInstance method instance - */ - save(methodInstance) { - const { name } = shared.getConfig(methodInstance); - const { records, occupy, capacity } = this; - if (name && occupy < capacity) { - // Using the name of the method as the key, save the method instance to the snapshot - const targetSnapshots = (records[name] = records[name] || shared.newInstance(SetCls)); - targetSnapshots.add(methodInstance); - // Statistical quantity - this.occupy += 1; - } - } - /** - * Get a Method instance snapshot, which will filter out the corresponding Method instance based on the matcher - * @param matcher Matching snapshot name, which can be a string or regular expression, or an object with a filter function - * @returns Array of matched Method instance snapshots - */ - match(matcher, matchAll = true) { - // Unify the filter parameters into name matcher and match handler - let nameString; - let nameReg; - let matchHandler; - let nameMatcher = matcher; - if (shared.isPlainObject(matcher)) { - nameMatcher = matcher.name; - matchHandler = matcher.filter; - } - if (shared.instanceOf(nameMatcher, shared.RegExpCls)) { - nameReg = nameMatcher; - } - else if (shared.isString(nameMatcher)) { - nameString = nameMatcher; - } - const { records } = this; - // Get the corresponding method instance snapshot through the deconstructed name matcher and filter handler - let matches = shared.newInstance((SetCls)); - // If the namespace parameter is provided, it will only be searched in this namespace, otherwise it will be searched in all cached data. - if (nameString) { - matches = records[nameString] || matches; - } - else if (nameReg) { - shared.forEach(shared.filterItem(shared.objectKeys(records), methodName => nameReg.test(methodName)), methodName => { - records[methodName].forEach(method => matches.add(method)); - }); - } - const fromMatchesArray = shared.isFn(matchHandler) ? shared.filterItem([...matches], matchHandler) : [...matches]; - return (matchAll ? fromMatchesArray : fromMatchesArray[0]); - } -} - -const typeGet = 'GET'; -const typeHead = 'HEAD'; -const typePost = 'POST'; -const typePut = 'PUT'; -const typePatch = 'PATCH'; -const typeDelete = 'DELETE'; -const typeOptions = 'OPTIONS'; -const defaultAlovaOptions = { - /** - * GET requests are cached for 5 minutes (300000 milliseconds) by default, and other requests are not cached by default. - */ - cacheFor: { - [typeGet]: 300000 - }, - /** - * Share requests default to true - */ - shareRequest: shared.trueValue, - /** - * Number of method snapshots, default is 1000 - */ - snapshots: 1000 -}; -let idCount = 0; -class Alova { - constructor(options) { - var _a, _b; - const instance = this; - instance.id = (options.id || (idCount += 1)).toString(); - // If storage is not specified, local storage is used by default. - instance.l1Cache = options.l1Cache || memoryAdapter(); - instance.l2Cache = - options.l2Cache || (typeof localStorage !== 'undefined' ? localStorageAdapter() : placeholderAdapter()); - // Merge default options - instance.options = { - ...defaultAlovaOptions, - ...options - }; - instance.snapshots = shared.newInstance((MethodSnapshotContainer), (_b = (_a = options.snapshots) !== null && _a !== void 0 ? _a : defaultAlovaOptions.snapshots) !== null && _b !== void 0 ? _b : 0); - } - Get(url, config) { - return shared.newInstance((Method), typeGet, this, url, config); - } - Post(url, data, config) { - return shared.newInstance((Method), typePost, this, url, config, data); - } - Delete(url, data, config) { - return shared.newInstance((Method), typeDelete, this, url, config, data); - } - Put(url, data, config) { - return shared.newInstance((Method), typePut, this, url, config, data); - } - Head(url, config) { - return shared.newInstance((Method), typeHead, this, url, config); - } - Patch(url, data, config) { - return shared.newInstance((Method), typePatch, this, url, config, data); - } - Options(url, config) { - return shared.newInstance((Method), typeOptions, this, url, config); - } -} -let boundStatesHook = shared.undefinedValue; -const usingL1CacheAdapters = []; -const usingL2CacheAdapters = []; -/** - * create an alova instance. - * @param options alova configuration. - * @returns alova instance. - */ -const createAlova = (options) => { - const alovaInstance = shared.newInstance((Alova), options); - const newStatesHook = alovaInstance.options.statesHook; - if (boundStatesHook) { - myAssert(boundStatesHook === newStatesHook, 'expected to use the same `statesHook`'); - } - boundStatesHook = newStatesHook; - const { l1Cache, l2Cache } = alovaInstance; - !usingL1CacheAdapters.includes(l1Cache) && shared.pushItem(usingL1CacheAdapters, l1Cache); - !usingL2CacheAdapters.includes(l2Cache) && shared.pushItem(usingL2CacheAdapters, l2Cache); - return alovaInstance; -}; - -const promiseStatesHook = () => { - myAssert(!!boundStatesHook, '`statesHook` is not set in alova instance'); - return boundStatesHook; -}; - -exports.Method = Method; -exports.createAlova = createAlova; -exports.globalConfig = globalConfig; -exports.hitCacheBySource = hitCacheBySource; -exports.invalidateCache = invalidateCache; -exports.promiseStatesHook = promiseStatesHook; -exports.queryCache = queryCache; -exports.setCache = setCache; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/alova.esm.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/alova.esm.js deleted file mode 100644 index 77ad947..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/alova.esm.js +++ /dev/null @@ -1,921 +0,0 @@ -/** - * alova 3.2.10 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -import { isSSR, STORAGE_RESTORE, len, getTime, buildNamespacedCacheKey, filterItem, undefinedValue, forEach, instanceOf, RegExpCls, pushItem, mapItem, objectKeys, PromiseCls, newInstance, deleteAttr, getContext, objAssign, getMethodInternalKey, getLocalCacheConfigParam, isArray, isFn, MEMORY, promiseResolve, getConfig, promiseThen, trueValue, getOptions, isSpecialRequestBody, isPlainObject, sloughFunction, falseValue, buildCompletedURL, promiseFinally, promiseReject, noop, $self, deepClone, getContextOptions, key, promiseCatch, createAssert, createEventManager, JSONStringify, JSONParse, isString } from '@alova/shared'; - -let globalConfigMap = { - autoHitCache: 'global', - ssr: isSSR -}; -/** - * Set global configuration - * @param config - */ -var globalConfig = (config) => { - globalConfigMap = { - ...globalConfigMap, - ...config - }; -}; - -const titleStyle = 'color: black; font-size: 12px; font-weight: bolder'; -/** - * Default cacheLogger function - */ -var defaultCacheLogger = (response, methodInstance, cacheMode, tag) => { - const cole = console; - // eslint-disable-next-line - const log = (...args) => console.log(...args); - const { url } = methodInstance; - const isRestoreMode = cacheMode === STORAGE_RESTORE; - const hdStyle = '\x1B[42m%s\x1B[49m'; - const labelStyle = '\x1B[32m%s\x1B[39m'; - const startSep = ` [HitCache]${url} `; - const endSepFn = () => Array(len(startSep) + 1).join('^'); - if (globalConfigMap.ssr) { - log(hdStyle, startSep); - log(labelStyle, ' Cache ', response); - log(labelStyle, ' Mode ', cacheMode); - isRestoreMode && log(labelStyle, ' Tag ', tag); - log(labelStyle, endSepFn()); - } - else { - cole.groupCollapsed - ? cole.groupCollapsed('%cHitCache', 'padding: 2px 6px; background: #c4fcd3; color: #53b56d;', url) - : log(hdStyle, startSep); - log('%c[Cache]', titleStyle, response); - log('%c[Mode]', titleStyle, cacheMode); - isRestoreMode && log('%c[Tag]', titleStyle, tag); - log('%c[Method]', titleStyle, methodInstance); - cole.groupEnd ? cole.groupEnd() : log(labelStyle, endSepFn()); - } -}; - -const hitSourceStringCacheKey = (key) => `hss.${key}`; -const hitSourceRegexpPrefix = 'hsr.'; -const hitSourceRegexpCacheKey = (regexpStr) => hitSourceRegexpPrefix + regexpStr; -const unifiedHitSourceRegexpCacheKey = '$$hsrs'; -const regexpSourceFlagSeparator = '__$<>$__'; -const addItem = (obj, item) => { - obj[item] = 0; -}; -/** - * set or update cache - * @param namespace namespace - * @param key stored key - * @param response Stored response content - * @param expireTimestamp Timestamp representation of expiration time point - * @param storage storage object - * @param tag Storage tags, used to distinguish different storage tags - */ -const setWithCacheAdapter = async (namespace, key, data, expireTimestamp, cacheAdapter, hitSource, tag) => { - // not to cache if expireTimestamp is less than current timestamp - if (expireTimestamp > getTime() && data) { - const methodCacheKey = buildNamespacedCacheKey(namespace, key); - await cacheAdapter.set(methodCacheKey, filterItem([data, expireTimestamp === Infinity ? undefinedValue : expireTimestamp, tag], Boolean)); - // save the relationship between this method and its hitSources. - // cache structure is like this: - /* - { - "$a.[namespace][methodKey]": [cache data], - ... - "hss.[sourceMethodKey]": "{ - [targetMethodKey1]: 0, - [targetMethodKey2]: 0, - ... - }", - "hss.[sourceMethodName]": "{ - [targetMethodKey3]: 0, - [targetMethodKey4]: 0, - ... - }", - "hsr.[sourceMethodNameRegexpSource]": "{ - [targetMethodKey5]: 0, - [targetMethodKey6]: 0, - ... - }", - "hsr.regexp1": ["hss.key1", "hss.key2"], - "hsr.regexp2": ["hss.key1", "hss.key2"] - } - */ - if (hitSource) { - // filter repeat items and categorize the regexp, to prevent unnecessary cost of IO - const hitSourceKeys = {}; - const hitSourceRegexpSources = []; - forEach(hitSource, sourceItem => { - const isRegexp = instanceOf(sourceItem, RegExpCls); - const targetHitSourceKey = isRegexp - ? sourceItem.source + (sourceItem.flags ? regexpSourceFlagSeparator + sourceItem.flags : '') - : sourceItem; - if (targetHitSourceKey) { - if (isRegexp && !hitSourceKeys[targetHitSourceKey]) { - pushItem(hitSourceRegexpSources, targetHitSourceKey); - } - addItem(hitSourceKeys, isRegexp ? hitSourceRegexpCacheKey(targetHitSourceKey) : hitSourceStringCacheKey(targetHitSourceKey)); - } - }); - // save the relationship. Minimize IO as much as possible - const promises = mapItem(objectKeys(hitSourceKeys), async (hitSourceKey) => { - // filter the empty strings. - const targetMethodKeys = (await cacheAdapter.get(hitSourceKey)) || {}; - addItem(targetMethodKeys, methodCacheKey); - await cacheAdapter.set(hitSourceKey, targetMethodKeys); - }); - const saveRegexp = async () => { - // save the regexp source if regexp exists. - if (len(hitSourceRegexpSources)) { - const regexpList = (await cacheAdapter.get(unifiedHitSourceRegexpCacheKey)) || []; - // TODO: hitSourceRegexpSources needs to be deduplicated - pushItem(regexpList, ...hitSourceRegexpSources); - await cacheAdapter.set(unifiedHitSourceRegexpCacheKey, regexpList); - } - }; - // parallel executing all async tasks. - await PromiseCls.all([...promises, saveRegexp()]); - } - } -}; -/** - * Delete stored response data - * @param namespace namespace - * @param key stored key - * @param storage storage object - */ -const removeWithCacheAdapter = async (namespace, key, cacheAdapter) => { - const methodStoreKey = buildNamespacedCacheKey(namespace, key); - await cacheAdapter.remove(methodStoreKey); -}; -/** - * Get stored response data - * @param namespace namespace - * @param key stored key - * @param storage storage object - * @param tag Store tags. If the tag changes, the data will become invalid. - */ -const getRawWithCacheAdapter = async (namespace, key, cacheAdapter, tag) => { - const storagedData = await cacheAdapter.get(buildNamespacedCacheKey(namespace, key)); - if (storagedData) { - // Eslint disable next line - const [dataUnused, expireTimestamp, storedTag] = storagedData; - // If there is no expiration time, it means that the data will never expire. Otherwise, you need to determine whether it has expired. - if (storedTag === tag && (!expireTimestamp || expireTimestamp > getTime())) { - return storagedData; - } - // If expired, delete cache - await removeWithCacheAdapter(namespace, key, cacheAdapter); - } -}; -/** - * Get stored response data - * @param namespace namespace - * @param key stored key - * @param storage storage object - * @param tag Store tags. If the tag changes, the data will become invalid. - */ -const getWithCacheAdapter = async (namespace, key, cacheAdapter, tag) => { - const rawData = await getRawWithCacheAdapter(namespace, key, cacheAdapter, tag); - return rawData ? rawData[0] : undefinedValue; -}; -/** - * clear all cached data - */ -const clearWithCacheAdapter = async (cacheAdapters) => PromiseCls.all(cacheAdapters.map(cacheAdapter => cacheAdapter.clear())); -/** - * query and delete target cache with key and name of source method instance. - * @param sourceKey source method instance key - * @param sourceName source method instance name - * @param cacheAdapter cache adapter - */ -const hitTargetCacheWithCacheAdapter = async (sourceKey, sourceName, cacheAdapter) => { - const sourceNameStr = `${sourceName}`; - // map that recording the source key and target method keys. - const sourceTargetKeyMap = {}; - // get hit key by method key. - const hitSourceKey = hitSourceStringCacheKey(sourceKey); - sourceTargetKeyMap[hitSourceKey] = await cacheAdapter.get(hitSourceKey); - let unifiedHitSourceRegexpChannel; - if (sourceName) { - const hitSourceName = hitSourceStringCacheKey(sourceNameStr); - // get hit key by method name if it is exists. - sourceTargetKeyMap[hitSourceName] = await cacheAdapter.get(hitSourceName); - // match regexped key by source method name and get hit key by method name. - unifiedHitSourceRegexpChannel = await cacheAdapter.get(unifiedHitSourceRegexpCacheKey); - const matchedRegexpStrings = []; - if (unifiedHitSourceRegexpChannel && len(unifiedHitSourceRegexpChannel)) { - forEach(unifiedHitSourceRegexpChannel, regexpStr => { - const [source, flag] = regexpStr.split(regexpSourceFlagSeparator); - if (newInstance(RegExpCls, source, flag).test(sourceNameStr)) { - pushItem(matchedRegexpStrings, regexpStr); - } - }); - // parallel get hit key by matched regexps. - await PromiseCls.all(mapItem(matchedRegexpStrings, async (regexpString) => { - const hitSourceRegexpString = hitSourceRegexpCacheKey(regexpString); - sourceTargetKeyMap[hitSourceRegexpString] = await cacheAdapter.get(hitSourceRegexpString); - })); - } - } - const removeWithTargetKey = async (targetKey) => { - try { - await cacheAdapter.remove(targetKey); - // loop sourceTargetKeyMap and remove this key to prevent unnecessary cost of IO. - for (const sourceKey in sourceTargetKeyMap) { - const targetKeys = sourceTargetKeyMap[sourceKey]; - if (targetKeys) { - deleteAttr(targetKeys, targetKey); - } - } - } - catch (_a) { - // the try-catch is used to prevent throwing error, cause throwing error in `Promise.all` below. - } - }; - // now let's start to delete target caches. - // and filter the finished keys. - const accessedKeys = {}; - await PromiseCls.all(mapItem(objectKeys(sourceTargetKeyMap), async (sourceKey) => { - const targetKeys = sourceTargetKeyMap[sourceKey]; - if (targetKeys) { - const removingPromises = []; - for (const key in targetKeys) { - if (!accessedKeys[key]) { - addItem(accessedKeys, key); - pushItem(removingPromises, removeWithTargetKey(key)); - } - } - await PromiseCls.all(removingPromises); - } - })); - // update source key if there is still has keys. - // remove source key if its keys is empty. - const unifiedHitSourceRegexpChannelLen = len(unifiedHitSourceRegexpChannel || []); - await PromiseCls.all(mapItem(objectKeys(sourceTargetKeyMap), async (sourceKey) => { - const targetKeys = sourceTargetKeyMap[sourceKey]; - if (targetKeys) { - if (len(objectKeys(targetKeys))) { - await cacheAdapter.set(sourceKey, targetKeys); - } - else { - await cacheAdapter.remove(sourceKey); - // if this is a regexped key, need to remove it from unified regexp channel. - if (sourceKey.includes(hitSourceRegexpPrefix) && unifiedHitSourceRegexpChannel) { - unifiedHitSourceRegexpChannel = filterItem(unifiedHitSourceRegexpChannel, rawRegexpStr => hitSourceRegexpCacheKey(rawRegexpStr) !== sourceKey); - } - } - } - })); - // update unified hit source regexp channel if its length was changed. - if (unifiedHitSourceRegexpChannelLen !== len(unifiedHitSourceRegexpChannel || [])) { - await cacheAdapter.set(unifiedHitSourceRegexpCacheKey, unifiedHitSourceRegexpChannel); - } -}; - -var cloneMethod = (methodInstance) => { - const { data, config } = methodInstance; - const newConfig = { ...config }; - const { headers = {}, params = {} } = newConfig; - const ctx = getContext(methodInstance); - newConfig.headers = { ...headers }; - newConfig.params = { ...params }; - const newMethod = newInstance((Method), methodInstance.type, ctx, methodInstance.url, newConfig, data); - return objAssign(newMethod, { - ...methodInstance, - config: newConfig - }); -}; - -/* - * The matchers in the following three functions are Method instance matchers, which are divided into three situations: - * 1. If the matcher is a Method instance, clear the cache of the Method instance. - * 2. If matcher is a string or regular expression, clear the cache of all Method instances that meet the conditions. - * 3. If no matcher is passed in, all caches will be cleared. - */ -/** - * Query cache - * @param matcher Method instance matcher - * @returns Cache data, return undefined if not found - */ -const queryCache = async (matcher, { policy = 'all' } = {}) => { - // if key exists, that means it's a method instance. - if (matcher && matcher.key) { - const { id, l1Cache, l2Cache } = getContext(matcher); - const methodKey = getMethodInternalKey(matcher); - const { f: cacheFor, c: controlled, s: store, e: expireMilliseconds, t: tag } = getLocalCacheConfigParam(matcher); - // if it's controlled cache, it will return the result of cacheFor function. - if (controlled) { - return cacheFor(); - } - let cachedData = policy !== 'l2' ? await getWithCacheAdapter(id, methodKey, l1Cache) : undefinedValue; - if (policy === 'l2') { - cachedData = await getWithCacheAdapter(id, methodKey, l2Cache, tag); - } - else if (policy === 'all' && !cachedData) { - if (store && expireMilliseconds(STORAGE_RESTORE) > getTime()) { - cachedData = await getWithCacheAdapter(id, methodKey, l2Cache, tag); - } - } - return cachedData; - } -}; -/** - * Manually set cache response data. If the corresponding methodInstance sets persistent storage, the cache in the persistent storage will also be checked out. - * @param matcher Method instance matcher cache data - */ -const setCache = async (matcher, dataOrUpdater, { policy = 'all' } = {}) => { - const methodInstances = isArray(matcher) ? matcher : [matcher]; - const batchPromises = methodInstances.map(async (methodInstance) => { - const { hitSource } = methodInstance; - const { id, l1Cache, l2Cache } = getContext(methodInstance); - const methodKey = getMethodInternalKey(methodInstance); - const { e: expireMilliseconds, s: toStore, t: tag, c: controlled } = getLocalCacheConfigParam(methodInstance); - // don't set cache when it's controlled cache. - if (controlled) { - return; - } - let data = dataOrUpdater; - if (isFn(dataOrUpdater)) { - let cachedData = policy !== 'l2' ? await getWithCacheAdapter(id, methodKey, l1Cache) : undefinedValue; - if (policy === 'l2' || - (policy === 'all' && !cachedData && toStore && expireMilliseconds(STORAGE_RESTORE) > getTime())) { - cachedData = await getWithCacheAdapter(id, methodKey, l2Cache, tag); - } - data = dataOrUpdater(cachedData); - if (data === undefinedValue) { - return; - } - } - return PromiseCls.all([ - policy !== 'l2' && setWithCacheAdapter(id, methodKey, data, expireMilliseconds(MEMORY), l1Cache, hitSource), - policy === 'l2' || (policy === 'all' && toStore) - ? setWithCacheAdapter(id, methodKey, data, expireMilliseconds(STORAGE_RESTORE), l2Cache, hitSource, tag) - : undefinedValue - ]); - }); - return PromiseCls.all(batchPromises); -}; -/** - * invalid cache - * @param matcher Method instance matcher - */ -const invalidateCache = async (matcher) => { - if (!matcher) { - await PromiseCls.all([clearWithCacheAdapter(usingL1CacheAdapters), clearWithCacheAdapter(usingL2CacheAdapters)]); - return; - } - const methodInstances = isArray(matcher) ? matcher : [matcher]; - const batchPromises = methodInstances.map(methodInstance => { - const { id, l1Cache, l2Cache } = getContext(methodInstance); - const { c: controlled, m: cacheMode } = getLocalCacheConfigParam(methodInstance); - // don't invalidate cache when it's controlled cache. - if (controlled) { - return; - } - const methodKey = getMethodInternalKey(methodInstance); - return PromiseCls.all([ - removeWithCacheAdapter(id, methodKey, l1Cache), - cacheMode === STORAGE_RESTORE ? removeWithCacheAdapter(id, methodKey, l2Cache) : promiseResolve() - ]); - }); - await PromiseCls.all(batchPromises); -}; -/** - * hit(invalidate) target caches by source method - * this is the implementation of auto invalidate cache - * @param sourceMethod source method instance - */ -const hitCacheBySource = async (sourceMethod) => { - // Find the hit target cache and invalidate its cache - // Control the automatic cache invalidation range through global configuration `autoHitCache` - const { autoHitCache } = globalConfigMap; - const { l1Cache, l2Cache } = getContext(sourceMethod); - const sourceKey = getMethodInternalKey(sourceMethod); - const { name: sourceName } = getConfig(sourceMethod); - const cacheAdaptersInvolved = { - global: [...usingL1CacheAdapters, ...usingL2CacheAdapters], - self: [l1Cache, l2Cache], - close: [] - }[autoHitCache]; - if (cacheAdaptersInvolved && len(cacheAdaptersInvolved)) { - await PromiseCls.all(mapItem(cacheAdaptersInvolved, involvedCacheAdapter => hitTargetCacheWithCacheAdapter(sourceKey, sourceName, involvedCacheAdapter))); - } -}; - -const adapterReturnMap = {}; -/** - * actual request function - * @param method request method object - * @param forceRequest Ignore cache - * @returns response data - */ -function sendRequest(methodInstance, forceRequest) { - let fromCache = trueValue; - let requestAdapterCtrlsPromiseResolveFn; - const requestAdapterCtrlsPromise = newInstance(PromiseCls, resolve => { - requestAdapterCtrlsPromiseResolveFn = resolve; - }); - const response = async () => { - const { beforeRequest = noop, responded, requestAdapter, cacheLogger } = getOptions(methodInstance); - const methodKey = getMethodInternalKey(methodInstance); - const { s: toStorage, t: tag, m: cacheMode, e: expireMilliseconds } = getLocalCacheConfigParam(methodInstance); - const { id, l1Cache, l2Cache, snapshots } = getContext(methodInstance); - // Get controlled cache or uncontrolled cache - const { cacheFor } = getConfig(methodInstance); - const { hitSource: methodHitSource } = methodInstance; - // If the current method sets a controlled cache, check whether there is custom data - let cachedResponse = await (isFn(cacheFor) - ? cacheFor() - : // If it is a forced request, skip the step of getting it from the cache - // Otherwise, determine whether to use cached data - forceRequest - ? undefinedValue - : getWithCacheAdapter(id, methodKey, l1Cache)); - // If it is storage restore mode and there is no data in the cache, the persistent data needs to be restored to the cache, and the cached expiration time must be used. - if (cacheMode === STORAGE_RESTORE && !cachedResponse && !forceRequest) { - const rawL2CacheData = await getRawWithCacheAdapter(id, methodKey, l2Cache, tag); - if (rawL2CacheData) { - const [l2Response, l2ExpireMilliseconds] = rawL2CacheData; - await setWithCacheAdapter(id, methodKey, l2Response, l2ExpireMilliseconds, l1Cache, methodHitSource); - cachedResponse = l2Response; - } - } - // Clone the method as a parameter and pass it to beforeRequest to prevent side effects when using the original method instance request multiple times. - // Place it after `let cachedResponse = await...` to solve the problem of first assigning promise to the method instance in method.send, otherwise the promise will be undefined in clonedMethod. - const clonedMethod = cloneMethod(methodInstance); - // Call the hook function before sending the request - // beforeRequest supports synchronous functions and asynchronous functions - await beforeRequest(clonedMethod); - const { baseURL, url: newUrl, type, data } = clonedMethod; - const { params = {}, headers = {}, transform = $self, shareRequest } = getConfig(clonedMethod); - const namespacedAdapterReturnMap = (adapterReturnMap[id] = adapterReturnMap[id] || {}); - const requestBody = clonedMethod.data; - const requestBodyIsSpecial = isSpecialRequestBody(requestBody); - // Will not share the request when requestBody is special data - let requestAdapterCtrls = requestBodyIsSpecial ? undefinedValue : namespacedAdapterReturnMap[methodKey]; - let responseSuccessHandler = $self; - let responseErrorHandler = undefinedValue; - let responseCompleteHandler = noop; - // uniform handler of onSuccess, onError, onComplete - if (isFn(responded)) { - responseSuccessHandler = responded; - } - else if (isPlainObject(responded)) { - const { onSuccess: successHandler, onError: errorHandler, onComplete: completeHandler } = responded; - responseSuccessHandler = isFn(successHandler) ? successHandler : responseSuccessHandler; - responseErrorHandler = isFn(errorHandler) ? errorHandler : responseErrorHandler; - responseCompleteHandler = isFn(completeHandler) ? completeHandler : responseCompleteHandler; - } - // If there is no cache, make a request - if (cachedResponse !== undefinedValue) { - requestAdapterCtrlsPromiseResolveFn(); // Ctrls will not be passed in when cache is encountered - // Print cache log - clonedMethod.fromCache = trueValue; - sloughFunction(cacheLogger, defaultCacheLogger)(cachedResponse, clonedMethod, cacheMode, tag); - responseCompleteHandler(clonedMethod); - return cachedResponse; - } - fromCache = falseValue; - if (!shareRequest || !requestAdapterCtrls) { - // Request data - const ctrls = requestAdapter({ - url: buildCompletedURL(baseURL, newUrl, params), - type, - data, - headers - }, clonedMethod); - requestAdapterCtrls = namespacedAdapterReturnMap[methodKey] = ctrls; - } - // Pass request adapter ctrls to promise for use in on download, on upload and abort - requestAdapterCtrlsPromiseResolveFn(requestAdapterCtrls); - /** - * Process response tasks and do not cache data on failure - * @param responsePromise Respond to promise instances - * @param responseHeaders Request header - * @param callInSuccess Whether to call in success callback - * @returns Processed response - */ - const handleResponseTask = async (handlerReturns, responseHeaders, callInSuccess = trueValue) => { - const responseData = await handlerReturns; - const transformedData = await transform(responseData, responseHeaders || {}); - snapshots.save(methodInstance); - // Even if the cache operation fails, the response structure will be returned normally to avoid request errors caused by cache operation problems. - // The cache operation results can be obtained through `cacheAdapter.emitter.on('success' | 'fail', event => {})` - try { - // Automatic cache invalidation - await hitCacheBySource(clonedMethod); - } - catch (_a) { } - // Do not save cache when requestBody is special data - // Reason 1: Special data is generally submitted and requires interaction with the server. - // Reason 2: Special data is not convenient for generating cache keys - const toCache = !requestBody || !requestBodyIsSpecial; - // Use the latest expiration time after the response to cache data to avoid the problem of expiration time loss due to too long response time - if (toCache && callInSuccess) { - try { - await PromiseCls.all([ - setWithCacheAdapter(id, methodKey, transformedData, expireMilliseconds(MEMORY), l1Cache, methodHitSource), - toStorage && - setWithCacheAdapter(id, methodKey, transformedData, expireMilliseconds(STORAGE_RESTORE), l2Cache, methodHitSource, tag) - ]); - } - catch (_b) { } - } - // Deep clone the transformed data before returning to avoid reference issues - // the `deepClone` will only clone array and plain object - return deepClone(transformedData); - }; - return promiseFinally(promiseThen(PromiseCls.all([requestAdapterCtrls.response(), requestAdapterCtrls.headers()]), ([rawResponse, rawHeaders]) => { - // Regardless of whether the request succeeds or fails, the shared request needs to be removed first - deleteAttr(namespacedAdapterReturnMap, methodKey); - return handleResponseTask(responseSuccessHandler(rawResponse, clonedMethod), rawHeaders); - }, (error) => { - // Regardless of whether the request succeeds or fails, the shared request needs to be removed first - deleteAttr(namespacedAdapterReturnMap, methodKey); - return isFn(responseErrorHandler) - ? // When responding to an error, if no error is thrown, the successful response process will be processed, but the data will not be cached. - handleResponseTask(responseErrorHandler(error, clonedMethod), undefinedValue, falseValue) - : promiseReject(error); - }), () => { - responseCompleteHandler(clonedMethod); - }); - }; - return { - // request interrupt function - abort: () => { - promiseThen(requestAdapterCtrlsPromise, requestAdapterCtrls => requestAdapterCtrls && requestAdapterCtrls.abort()); - }, - onDownload: (handler) => { - promiseThen(requestAdapterCtrlsPromise, requestAdapterCtrls => requestAdapterCtrls && requestAdapterCtrls.onDownload && requestAdapterCtrls.onDownload(handler)); - }, - onUpload: (handler) => { - promiseThen(requestAdapterCtrlsPromise, requestAdapterCtrls => requestAdapterCtrls && requestAdapterCtrls.onUpload && requestAdapterCtrls.onUpload(handler)); - }, - response, - fromCache: () => fromCache - }; -} - -const offEventCallback = (offHandler, handlers) => () => { - const index = handlers.indexOf(offHandler); - index >= 0 && handlers.splice(index, 1); -}; -class Method { - constructor(type, context, url, config, data) { - this.dhs = []; - this.uhs = []; - this.fromCache = undefinedValue; - const abortRequest = () => { - abortRequest.a(); - }; - abortRequest.a = noop; - const instance = this; - const contextOptions = getContextOptions(context); - instance.abort = abortRequest; - instance.baseURL = contextOptions.baseURL || ''; - instance.url = url; - instance.type = type; - instance.context = context; - // Merge request-related global configuration into the method object - const contextConcatConfig = {}; - const mergedLocalCacheKey = 'cacheFor'; - const globalLocalCache = isPlainObject(contextOptions[mergedLocalCacheKey]) - ? contextOptions[mergedLocalCacheKey][type] - : undefinedValue; - const hitSource = config && config.hitSource; - // Merge parameters - forEach(['timeout', 'shareRequest'], mergedKey => { - if (contextOptions[mergedKey] !== undefinedValue) { - contextConcatConfig[mergedKey] = contextOptions[mergedKey]; - } - }); - // Merge local cache - if (globalLocalCache !== undefinedValue) { - contextConcatConfig[mergedLocalCacheKey] = globalLocalCache; - } - // Unify hit sources into arrays and convert them into method keys when there are method instances - if (hitSource) { - instance.hitSource = mapItem(isArray(hitSource) ? hitSource : [hitSource], sourceItem => instanceOf(sourceItem, Method) ? getMethodInternalKey(sourceItem) : sourceItem); - deleteAttr(config, 'hitSource'); - } - instance.config = { - ...contextConcatConfig, - headers: {}, - params: {}, - ...(config || {}) - }; - instance.data = data; - instance.meta = config ? config.meta : instance.meta; - // The original key needs to be used externally instead of generating the key in real time. - // The reason is that the parameters of the method may pass in reference type values, but when the reference type value changes externally, the key generated in real time also changes, so it is more accurate to use the initial key. - instance.key = instance.generateKey(); - } - /** - * Bind download progress callback function - * @param progressHandler Download progress callback function - * @version 2.17.0 - * @return unbind function - */ - onDownload(downloadHandler) { - pushItem(this.dhs, downloadHandler); - return offEventCallback(downloadHandler, this.dhs); - } - /** - * Bind upload progress callback function - * @param progressHandler Upload progress callback function - * @version 2.17.0 - * @return unbind function - */ - onUpload(uploadHandler) { - pushItem(this.uhs, uploadHandler); - return offEventCallback(uploadHandler, this.uhs); - } - /** - * Send a request through a method instance and return a promise object - */ - send(forceRequest = falseValue) { - const instance = this; - const { response, onDownload, onUpload, abort, fromCache } = sendRequest(instance, forceRequest); - len(instance.dhs) > 0 && - onDownload((loaded, total) => forEach(instance.dhs, handler => handler({ loaded, total }))); - len(instance.uhs) > 0 && onUpload((loaded, total) => forEach(instance.uhs, handler => handler({ loaded, total }))); - // The interrupt function is bound to the method instance for each request. The user can also interrupt the current request through method instance.abort() - instance.abort.a = abort; - instance.fromCache = undefinedValue; - instance.promise = promiseThen(response(), r => { - instance.fromCache = fromCache(); - return r; - }); - return instance.promise; - } - /** - * Set the method name, if there is already a name it will be overwritten - * @param name method name - */ - setName(name) { - getConfig(this).name = name; - } - generateKey() { - return key(this); - } - /** - * Bind callbacks for resolve and/or reject Promise - * @param onfulfilled The callback to be executed when resolving the Promise - * @param onrejected The callback to be executed when the Promise is rejected - * @returns Returns a Promise for executing any callbacks - */ - then(onfulfilled, onrejected) { - return promiseThen(this.send(), onfulfilled, onrejected); - } - /** - * Bind a callback only for reject Promise - * @param onrejected The callback to be executed when the Promise is rejected - * @returns Returns a Promise that completes the callback - */ - catch(onrejected) { - return promiseCatch(this.send(), onrejected); - } - /** - * Bind a callback that is called when the Promise is resolved (resolve or reject) - * @param onfinally Callback executed when Promise is resolved (resolve or reject). - * @return Returns a Promise that completes the callback. - */ - finally(onfinally) { - return promiseFinally(this.send(), onfinally); - } -} - -/** - * Custom assertion function, throws an error when the expression is false - * @param expression Judgment expression, true or false - * @param msg assert message - */ -const myAssert = createAssert(); - -// local storage will not fail the operation. -const EVENT_SUCCESS_KEY = 'success'; -const memoryAdapter = () => { - let l1Cache = {}; - const l1CacheEmitter = createEventManager(); - const adapter = { - set(key, value) { - l1Cache[key] = value; - l1CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'set', key, value, container: l1Cache }); - }, - get: key => { - const value = l1Cache[key]; - l1CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'get', key, value, container: l1Cache }); - return value; - }, - remove(key) { - deleteAttr(l1Cache, key); - l1CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'remove', key, container: l1Cache }); - }, - clear: () => { - l1Cache = {}; - l1CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'clear', key: '', container: l1Cache }); - }, - emitter: l1CacheEmitter - }; - return adapter; -}; -const localStorageAdapter = () => { - const l2CacheEmitter = createEventManager(); - const instance = localStorage; - const adapter = { - set: (key, value) => { - instance.setItem(key, JSONStringify(value)); - l2CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'set', key, value, container: instance }); - }, - get: key => { - const data = instance.getItem(key); - const value = data ? JSONParse(data) : data; - l2CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'get', key, value, container: instance }); - return value; - }, - remove: key => { - instance.removeItem(key); - l2CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'remove', key, container: instance }); - }, - clear: () => { - instance.clear(); - l2CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'clear', key: '', container: instance }); - }, - emitter: l2CacheEmitter - }; - return adapter; -}; -const placeholderAdapter = () => { - const l2CacheNotDefinedAssert = () => { - myAssert(falseValue, 'l2Cache is not defined.'); - }; - return { - set: () => { - l2CacheNotDefinedAssert(); - }, - get: () => { - l2CacheNotDefinedAssert(); - return undefinedValue; - }, - remove: () => { - l2CacheNotDefinedAssert(); - }, - clear: () => { } - }; -}; - -const SetCls = Set; -class MethodSnapshotContainer { - constructor(capacity) { - /** - * Method instance snapshot collection, method instances that have sent requests will be saved - */ - this.records = {}; - this.occupy = 0; - myAssert(capacity >= 0, 'expected snapshots limit to be >= 0'); - this.capacity = capacity; - } - /** - * Save method instance snapshot - * @param methodInstance method instance - */ - save(methodInstance) { - const { name } = getConfig(methodInstance); - const { records, occupy, capacity } = this; - if (name && occupy < capacity) { - // Using the name of the method as the key, save the method instance to the snapshot - const targetSnapshots = (records[name] = records[name] || newInstance(SetCls)); - targetSnapshots.add(methodInstance); - // Statistical quantity - this.occupy += 1; - } - } - /** - * Get a Method instance snapshot, which will filter out the corresponding Method instance based on the matcher - * @param matcher Matching snapshot name, which can be a string or regular expression, or an object with a filter function - * @returns Array of matched Method instance snapshots - */ - match(matcher, matchAll = true) { - // Unify the filter parameters into name matcher and match handler - let nameString; - let nameReg; - let matchHandler; - let nameMatcher = matcher; - if (isPlainObject(matcher)) { - nameMatcher = matcher.name; - matchHandler = matcher.filter; - } - if (instanceOf(nameMatcher, RegExpCls)) { - nameReg = nameMatcher; - } - else if (isString(nameMatcher)) { - nameString = nameMatcher; - } - const { records } = this; - // Get the corresponding method instance snapshot through the deconstructed name matcher and filter handler - let matches = newInstance((SetCls)); - // If the namespace parameter is provided, it will only be searched in this namespace, otherwise it will be searched in all cached data. - if (nameString) { - matches = records[nameString] || matches; - } - else if (nameReg) { - forEach(filterItem(objectKeys(records), methodName => nameReg.test(methodName)), methodName => { - records[methodName].forEach(method => matches.add(method)); - }); - } - const fromMatchesArray = isFn(matchHandler) ? filterItem([...matches], matchHandler) : [...matches]; - return (matchAll ? fromMatchesArray : fromMatchesArray[0]); - } -} - -const typeGet = 'GET'; -const typeHead = 'HEAD'; -const typePost = 'POST'; -const typePut = 'PUT'; -const typePatch = 'PATCH'; -const typeDelete = 'DELETE'; -const typeOptions = 'OPTIONS'; -const defaultAlovaOptions = { - /** - * GET requests are cached for 5 minutes (300000 milliseconds) by default, and other requests are not cached by default. - */ - cacheFor: { - [typeGet]: 300000 - }, - /** - * Share requests default to true - */ - shareRequest: trueValue, - /** - * Number of method snapshots, default is 1000 - */ - snapshots: 1000 -}; -let idCount = 0; -class Alova { - constructor(options) { - var _a, _b; - const instance = this; - instance.id = (options.id || (idCount += 1)).toString(); - // If storage is not specified, local storage is used by default. - instance.l1Cache = options.l1Cache || memoryAdapter(); - instance.l2Cache = - options.l2Cache || (typeof localStorage !== 'undefined' ? localStorageAdapter() : placeholderAdapter()); - // Merge default options - instance.options = { - ...defaultAlovaOptions, - ...options - }; - instance.snapshots = newInstance((MethodSnapshotContainer), (_b = (_a = options.snapshots) !== null && _a !== void 0 ? _a : defaultAlovaOptions.snapshots) !== null && _b !== void 0 ? _b : 0); - } - Get(url, config) { - return newInstance((Method), typeGet, this, url, config); - } - Post(url, data, config) { - return newInstance((Method), typePost, this, url, config, data); - } - Delete(url, data, config) { - return newInstance((Method), typeDelete, this, url, config, data); - } - Put(url, data, config) { - return newInstance((Method), typePut, this, url, config, data); - } - Head(url, config) { - return newInstance((Method), typeHead, this, url, config); - } - Patch(url, data, config) { - return newInstance((Method), typePatch, this, url, config, data); - } - Options(url, config) { - return newInstance((Method), typeOptions, this, url, config); - } -} -let boundStatesHook = undefinedValue; -const usingL1CacheAdapters = []; -const usingL2CacheAdapters = []; -/** - * create an alova instance. - * @param options alova configuration. - * @returns alova instance. - */ -const createAlova = (options) => { - const alovaInstance = newInstance((Alova), options); - const newStatesHook = alovaInstance.options.statesHook; - if (boundStatesHook) { - myAssert(boundStatesHook === newStatesHook, 'expected to use the same `statesHook`'); - } - boundStatesHook = newStatesHook; - const { l1Cache, l2Cache } = alovaInstance; - !usingL1CacheAdapters.includes(l1Cache) && pushItem(usingL1CacheAdapters, l1Cache); - !usingL2CacheAdapters.includes(l2Cache) && pushItem(usingL2CacheAdapters, l2Cache); - return alovaInstance; -}; - -const promiseStatesHook = () => { - myAssert(!!boundStatesHook, '`statesHook` is not set in alova instance'); - return boundStatesHook; -}; - -export { Method, createAlova, globalConfig, globalConfigMap, hitCacheBySource, invalidateCache, promiseStatesHook, queryCache, setCache }; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/alova.umd.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/alova.umd.js deleted file mode 100644 index 827b20c..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/alova.umd.js +++ /dev/null @@ -1,1207 +0,0 @@ -/** - * alova 3.2.10 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.alova = {})); -})(this, (function (exports) { 'use strict'; - - /** - * @alova/shared 1.1.2 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) - */ - - const undefStr = 'undefined'; - // The following unified processing functions or variables added to reduce the amount of compiled code - const PromiseCls = Promise; - const promiseResolve = (value) => PromiseCls.resolve(value); - const promiseReject = (value) => PromiseCls.reject(value); - const ObjectCls = Object; - const RegExpCls = RegExp; - const undefinedValue = undefined; - const nullValue = null; - const trueValue = true; - const falseValue = false; - const promiseThen = (promise, onFulfilled, onrejected) => promise.then(onFulfilled, onrejected); - const promiseCatch = (promise, onrejected) => promise.catch(onrejected); - const promiseFinally = (promise, onfinally) => promise.finally(onfinally); - const JSONStringify = (value, replacer, space) => JSON.stringify(value, replacer, space); - const JSONParse = (value) => JSON.parse(value); - const objectKeys = (obj) => ObjectCls.keys(obj); - const forEach = (ary, fn) => ary.forEach(fn); - const pushItem = (ary, ...item) => ary.push(...item); - const mapItem = (ary, callbackfn) => ary.map(callbackfn); - const filterItem = (ary, predicate) => ary.filter(predicate); - const len = (data) => data.length; - const isArray = (arg) => Array.isArray(arg); - const deleteAttr = (arg, attr) => delete arg[attr]; - const typeOf = (arg) => typeof arg; - // Whether it is running on the server side, node and bun are judged by process, and deno is judged by Deno. - // Some frameworks (such as Alipay and uniapp) will inject the process object as a global variable. - // Therefore, the process.cwd function unique to the server is used as the basis for judgment. - const isSSR = typeof window === undefStr && - (typeof process !== undefStr ? typeof process.cwd === 'function' : typeof Deno !== undefStr); - /** cache mode */ - // only cache in memory, it's default option - const MEMORY = 'memory'; - // persistent cache, and will be read to memory when page is refreshed, it means that the memory cache always exist until cache is expired. - const STORAGE_RESTORE = 'restore'; - - /** - * Empty function for compatibility processing - */ - const noop = () => { }; - /** - * A function that returns the parameter itself, used for compatibility processing - * Since some systems use self as a reserved word, $self is used to distinguish it. - * @param arg any parameter - * @returns return parameter itself - */ - const $self = (arg) => arg; - /** - * Determine whether the parameter is a function any parameter - * @returns Whether the parameter is a function - */ - const isFn = (arg) => typeOf(arg) === 'function'; - /** - * Determine whether the parameter is a number any parameter - * @returns Whether the parameter is a number - */ - const isNumber = (arg) => typeOf(arg) === 'number' && !Number.isNaN(arg); - /** - * Determine whether the parameter is a string any parameter - * @returns Whether the parameter is a string - */ - const isString = (arg) => typeOf(arg) === 'string'; - /** - * Global toString any parameter stringified parameters - */ - const globalToString = (arg) => ObjectCls.prototype.toString.call(arg); - /** - * Determine whether it is a normal object any parameter - * @returns Judgment result - */ - const isPlainObject = (arg) => globalToString(arg) === '[object Object]'; - /** - * Determine whether it is an instance of a certain class any parameter - * @returns Judgment result - */ - const instanceOf = (arg, cls) => arg instanceof cls; - /** - * Unified timestamp acquisition function - * @returns Timestamp - */ - const getTime = (date) => (date ? date.getTime() : Date.now()); - /** - * Get the alova instance through the method instance alova example - */ - const getContext = (methodInstance) => methodInstance.context; - /** - * Get method instance configuration data - * @returns Configuration object - */ - const getConfig = (methodInstance) => methodInstance.config; - /** - * Get alova configuration data alova configuration object - */ - const getContextOptions = (alovaInstance) => alovaInstance.options; - /** - * Get alova configuration data through method instance alova configuration object - */ - const getOptions = (methodInstance) => getContextOptions(getContext(methodInstance)); - /** - * Get the key value of the request method - * @returns The key value of this request method - */ - const key = (methodInstance) => { - const { params, headers } = getConfig(methodInstance); - return JSONStringify([methodInstance.type, methodInstance.url, params, methodInstance.data, headers]); - }; - /** - * Get the key value of the method instance method instance - * @returns The key value of this method instance - */ - const getMethodInternalKey = (methodInstance) => methodInstance.key; - /** - * Is it special data - * @param data Submit data - * @returns Judgment result - */ - const isSpecialRequestBody = (data) => { - const dataTypeString = globalToString(data); - return (/^\[object (Blob|FormData|ReadableStream|URLSearchParams)\]$/i.test(dataTypeString) || instanceOf(data, ArrayBuffer)); - }; - const objAssign = (target, ...sources) => ObjectCls.assign(target, ...sources); - /** - * Get cached configuration parameters, fixedly returning an object in the format { e: function, c: any, f: any, m: number, s: boolean, t: string } e is the abbreviation of expire, which returns the cache expiration time point (timestamp) in milliseconds. - * c is controlled, indicating whether it is a controlled cache - * f is the original value of cacheFor, which is used to call to obtain cached data when c is true. - * m is the abbreviation of mode, storage mode - * s is the abbreviation of storage, whether to store it locally - * t is the abbreviation of tag, which stores tags persistently. - * @param methodInstance method instance - * @returns Unified cache parameter object - */ - const getLocalCacheConfigParam = (methodInstance) => { - const { cacheFor } = getConfig(methodInstance); - const getCacheExpireTs = (cacheExpire) => isNumber(cacheExpire) ? getTime() + cacheExpire : getTime(cacheExpire || undefinedValue); - let cacheMode = MEMORY; - let expire = () => 0; - let store = falseValue; - let tag = undefinedValue; - const controlled = isFn(cacheFor); - if (!controlled) { - let expireColumn = cacheFor; - if (isPlainObject(cacheFor)) { - const { mode = MEMORY, expire, tag: configTag } = cacheFor || {}; - cacheMode = mode; - store = mode === STORAGE_RESTORE; - tag = configTag ? configTag.toString() : undefinedValue; - expireColumn = expire; - } - expire = (mode) => getCacheExpireTs(isFn(expireColumn) ? expireColumn({ method: methodInstance, mode }) : expireColumn); - } - return { - f: cacheFor, - c: controlled, - e: expire, - m: cacheMode, - s: store, - t: tag - }; - }; - /** - * Create class instance - * @param Cls Constructor - * @param args Constructor parameters class instance - */ - const newInstance = (Cls, ...args) => new Cls(...args); - const sloughFunction = (arg, defaultFn) => isFn(arg) ? arg : ![falseValue, nullValue].includes(arg) ? defaultFn : noop; - const cacheKeyPrefix = '$a.'; - /** - * build common cache key. - */ - const buildNamespacedCacheKey = (namespace, key) => cacheKeyPrefix + namespace + key; - /** - * Build the complete url baseURL path url parameters complete url - */ - const buildCompletedURL = (baseURL, url, params) => { - // If the Base url ends with /, remove / - baseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL; - // If it does not start with /or http protocol, you need to add / - // Compatible with some RESTful usage fix: https://github.com/alovajs/alova/issues/382 - if (url !== '') { - url = url.match(/^(\/|https?:\/\/)/) ? url : `/${url}`; - } - const completeURL = baseURL + url; - // Convert params object to get string - // Filter out those whose value is undefined - const paramsStr = mapItem(filterItem(objectKeys(params), key => params[key] !== undefinedValue), key => `${key}=${params[key]}`).join('&'); - // Splice the get parameters behind the url. Note that the url may already have parameters. - return paramsStr - ? +completeURL.includes('?') - ? `${completeURL}&${paramsStr}` - : `${completeURL}?${paramsStr}` - : completeURL; - }; - /** - * Deep clone an object. - * - * @param obj The object to be cloned. - * @returns The cloned object. - */ - const deepClone = (obj) => { - if (isArray(obj)) { - return mapItem(obj, deepClone); - } - if (isPlainObject(obj) && obj.constructor === ObjectCls) { - const clone = {}; - forEach(objectKeys(obj), key => { - clone[key] = deepClone(obj[key]); - }); - return clone; - } - return obj; - }; - - /** - * alova error class - */ - class AlovaError extends Error { - constructor(prefix, message, errorCode) { - super(message + (errorCode ? `\n\nFor detailed: https://alova.js.org/error#${errorCode}` : '')); - this.name = `[alova${prefix ? `/${prefix}` : ''}]`; - } - } - /** - * Custom assertion function that throws an error when the expression is false - * When errorCode is passed in, a link to the error document will be provided to guide the user to correct it. - * @param expression Judgment expression, true or false - * @param message Assert message - */ - const createAssert = (prefix = '') => (expression, message, errorCode) => { - if (!expression) { - throw newInstance(AlovaError, prefix, message, errorCode); - } - }; - - const createEventManager = () => { - const eventMap = {}; - return { - eventMap, - on(type, handler) { - const eventTypeItem = (eventMap[type] = eventMap[type] || []); - pushItem(eventTypeItem, handler); - // return the off function - return () => { - eventMap[type] = filterItem(eventTypeItem, item => item !== handler); - }; - }, - off(type, handler) { - const handlers = eventMap[type]; - if (!handlers) { - return; - } - if (handler) { - const index = handlers.indexOf(handler); - index > -1 && handlers.splice(index, 1); - } - else { - delete eventMap[type]; - } - }, - emit(type, event) { - const handlers = eventMap[type] || []; - return mapItem(handlers, handler => handler(event)); - } - }; - }; - - exports.globalConfigMap = { - autoHitCache: 'global', - ssr: isSSR - }; - /** - * Set global configuration - * @param config - */ - var globalConfig = (config) => { - exports.globalConfigMap = { - ...exports.globalConfigMap, - ...config - }; - }; - - const titleStyle = 'color: black; font-size: 12px; font-weight: bolder'; - /** - * Default cacheLogger function - */ - var defaultCacheLogger = (response, methodInstance, cacheMode, tag) => { - const cole = console; - // eslint-disable-next-line - const log = (...args) => console.log(...args); - const { url } = methodInstance; - const isRestoreMode = cacheMode === STORAGE_RESTORE; - const hdStyle = '\x1B[42m%s\x1B[49m'; - const labelStyle = '\x1B[32m%s\x1B[39m'; - const startSep = ` [HitCache]${url} `; - const endSepFn = () => Array(len(startSep) + 1).join('^'); - if (exports.globalConfigMap.ssr) { - log(hdStyle, startSep); - log(labelStyle, ' Cache ', response); - log(labelStyle, ' Mode ', cacheMode); - isRestoreMode && log(labelStyle, ' Tag ', tag); - log(labelStyle, endSepFn()); - } - else { - cole.groupCollapsed - ? cole.groupCollapsed('%cHitCache', 'padding: 2px 6px; background: #c4fcd3; color: #53b56d;', url) - : log(hdStyle, startSep); - log('%c[Cache]', titleStyle, response); - log('%c[Mode]', titleStyle, cacheMode); - isRestoreMode && log('%c[Tag]', titleStyle, tag); - log('%c[Method]', titleStyle, methodInstance); - cole.groupEnd ? cole.groupEnd() : log(labelStyle, endSepFn()); - } - }; - - const hitSourceStringCacheKey = (key) => `hss.${key}`; - const hitSourceRegexpPrefix = 'hsr.'; - const hitSourceRegexpCacheKey = (regexpStr) => hitSourceRegexpPrefix + regexpStr; - const unifiedHitSourceRegexpCacheKey = '$$hsrs'; - const regexpSourceFlagSeparator = '__$<>$__'; - const addItem = (obj, item) => { - obj[item] = 0; - }; - /** - * set or update cache - * @param namespace namespace - * @param key stored key - * @param response Stored response content - * @param expireTimestamp Timestamp representation of expiration time point - * @param storage storage object - * @param tag Storage tags, used to distinguish different storage tags - */ - const setWithCacheAdapter = async (namespace, key, data, expireTimestamp, cacheAdapter, hitSource, tag) => { - // not to cache if expireTimestamp is less than current timestamp - if (expireTimestamp > getTime() && data) { - const methodCacheKey = buildNamespacedCacheKey(namespace, key); - await cacheAdapter.set(methodCacheKey, filterItem([data, expireTimestamp === Infinity ? undefinedValue : expireTimestamp, tag], Boolean)); - // save the relationship between this method and its hitSources. - // cache structure is like this: - /* - { - "$a.[namespace][methodKey]": [cache data], - ... - "hss.[sourceMethodKey]": "{ - [targetMethodKey1]: 0, - [targetMethodKey2]: 0, - ... - }", - "hss.[sourceMethodName]": "{ - [targetMethodKey3]: 0, - [targetMethodKey4]: 0, - ... - }", - "hsr.[sourceMethodNameRegexpSource]": "{ - [targetMethodKey5]: 0, - [targetMethodKey6]: 0, - ... - }", - "hsr.regexp1": ["hss.key1", "hss.key2"], - "hsr.regexp2": ["hss.key1", "hss.key2"] - } - */ - if (hitSource) { - // filter repeat items and categorize the regexp, to prevent unnecessary cost of IO - const hitSourceKeys = {}; - const hitSourceRegexpSources = []; - forEach(hitSource, sourceItem => { - const isRegexp = instanceOf(sourceItem, RegExpCls); - const targetHitSourceKey = isRegexp - ? sourceItem.source + (sourceItem.flags ? regexpSourceFlagSeparator + sourceItem.flags : '') - : sourceItem; - if (targetHitSourceKey) { - if (isRegexp && !hitSourceKeys[targetHitSourceKey]) { - pushItem(hitSourceRegexpSources, targetHitSourceKey); - } - addItem(hitSourceKeys, isRegexp ? hitSourceRegexpCacheKey(targetHitSourceKey) : hitSourceStringCacheKey(targetHitSourceKey)); - } - }); - // save the relationship. Minimize IO as much as possible - const promises = mapItem(objectKeys(hitSourceKeys), async (hitSourceKey) => { - // filter the empty strings. - const targetMethodKeys = (await cacheAdapter.get(hitSourceKey)) || {}; - addItem(targetMethodKeys, methodCacheKey); - await cacheAdapter.set(hitSourceKey, targetMethodKeys); - }); - const saveRegexp = async () => { - // save the regexp source if regexp exists. - if (len(hitSourceRegexpSources)) { - const regexpList = (await cacheAdapter.get(unifiedHitSourceRegexpCacheKey)) || []; - // TODO: hitSourceRegexpSources needs to be deduplicated - pushItem(regexpList, ...hitSourceRegexpSources); - await cacheAdapter.set(unifiedHitSourceRegexpCacheKey, regexpList); - } - }; - // parallel executing all async tasks. - await PromiseCls.all([...promises, saveRegexp()]); - } - } - }; - /** - * Delete stored response data - * @param namespace namespace - * @param key stored key - * @param storage storage object - */ - const removeWithCacheAdapter = async (namespace, key, cacheAdapter) => { - const methodStoreKey = buildNamespacedCacheKey(namespace, key); - await cacheAdapter.remove(methodStoreKey); - }; - /** - * Get stored response data - * @param namespace namespace - * @param key stored key - * @param storage storage object - * @param tag Store tags. If the tag changes, the data will become invalid. - */ - const getRawWithCacheAdapter = async (namespace, key, cacheAdapter, tag) => { - const storagedData = await cacheAdapter.get(buildNamespacedCacheKey(namespace, key)); - if (storagedData) { - // Eslint disable next line - const [dataUnused, expireTimestamp, storedTag] = storagedData; - // If there is no expiration time, it means that the data will never expire. Otherwise, you need to determine whether it has expired. - if (storedTag === tag && (!expireTimestamp || expireTimestamp > getTime())) { - return storagedData; - } - // If expired, delete cache - await removeWithCacheAdapter(namespace, key, cacheAdapter); - } - }; - /** - * Get stored response data - * @param namespace namespace - * @param key stored key - * @param storage storage object - * @param tag Store tags. If the tag changes, the data will become invalid. - */ - const getWithCacheAdapter = async (namespace, key, cacheAdapter, tag) => { - const rawData = await getRawWithCacheAdapter(namespace, key, cacheAdapter, tag); - return rawData ? rawData[0] : undefinedValue; - }; - /** - * clear all cached data - */ - const clearWithCacheAdapter = async (cacheAdapters) => PromiseCls.all(cacheAdapters.map(cacheAdapter => cacheAdapter.clear())); - /** - * query and delete target cache with key and name of source method instance. - * @param sourceKey source method instance key - * @param sourceName source method instance name - * @param cacheAdapter cache adapter - */ - const hitTargetCacheWithCacheAdapter = async (sourceKey, sourceName, cacheAdapter) => { - const sourceNameStr = `${sourceName}`; - // map that recording the source key and target method keys. - const sourceTargetKeyMap = {}; - // get hit key by method key. - const hitSourceKey = hitSourceStringCacheKey(sourceKey); - sourceTargetKeyMap[hitSourceKey] = await cacheAdapter.get(hitSourceKey); - let unifiedHitSourceRegexpChannel; - if (sourceName) { - const hitSourceName = hitSourceStringCacheKey(sourceNameStr); - // get hit key by method name if it is exists. - sourceTargetKeyMap[hitSourceName] = await cacheAdapter.get(hitSourceName); - // match regexped key by source method name and get hit key by method name. - unifiedHitSourceRegexpChannel = await cacheAdapter.get(unifiedHitSourceRegexpCacheKey); - const matchedRegexpStrings = []; - if (unifiedHitSourceRegexpChannel && len(unifiedHitSourceRegexpChannel)) { - forEach(unifiedHitSourceRegexpChannel, regexpStr => { - const [source, flag] = regexpStr.split(regexpSourceFlagSeparator); - if (newInstance(RegExpCls, source, flag).test(sourceNameStr)) { - pushItem(matchedRegexpStrings, regexpStr); - } - }); - // parallel get hit key by matched regexps. - await PromiseCls.all(mapItem(matchedRegexpStrings, async (regexpString) => { - const hitSourceRegexpString = hitSourceRegexpCacheKey(regexpString); - sourceTargetKeyMap[hitSourceRegexpString] = await cacheAdapter.get(hitSourceRegexpString); - })); - } - } - const removeWithTargetKey = async (targetKey) => { - try { - await cacheAdapter.remove(targetKey); - // loop sourceTargetKeyMap and remove this key to prevent unnecessary cost of IO. - for (const sourceKey in sourceTargetKeyMap) { - const targetKeys = sourceTargetKeyMap[sourceKey]; - if (targetKeys) { - deleteAttr(targetKeys, targetKey); - } - } - } - catch (_a) { - // the try-catch is used to prevent throwing error, cause throwing error in `Promise.all` below. - } - }; - // now let's start to delete target caches. - // and filter the finished keys. - const accessedKeys = {}; - await PromiseCls.all(mapItem(objectKeys(sourceTargetKeyMap), async (sourceKey) => { - const targetKeys = sourceTargetKeyMap[sourceKey]; - if (targetKeys) { - const removingPromises = []; - for (const key in targetKeys) { - if (!accessedKeys[key]) { - addItem(accessedKeys, key); - pushItem(removingPromises, removeWithTargetKey(key)); - } - } - await PromiseCls.all(removingPromises); - } - })); - // update source key if there is still has keys. - // remove source key if its keys is empty. - const unifiedHitSourceRegexpChannelLen = len(unifiedHitSourceRegexpChannel || []); - await PromiseCls.all(mapItem(objectKeys(sourceTargetKeyMap), async (sourceKey) => { - const targetKeys = sourceTargetKeyMap[sourceKey]; - if (targetKeys) { - if (len(objectKeys(targetKeys))) { - await cacheAdapter.set(sourceKey, targetKeys); - } - else { - await cacheAdapter.remove(sourceKey); - // if this is a regexped key, need to remove it from unified regexp channel. - if (sourceKey.includes(hitSourceRegexpPrefix) && unifiedHitSourceRegexpChannel) { - unifiedHitSourceRegexpChannel = filterItem(unifiedHitSourceRegexpChannel, rawRegexpStr => hitSourceRegexpCacheKey(rawRegexpStr) !== sourceKey); - } - } - } - })); - // update unified hit source regexp channel if its length was changed. - if (unifiedHitSourceRegexpChannelLen !== len(unifiedHitSourceRegexpChannel || [])) { - await cacheAdapter.set(unifiedHitSourceRegexpCacheKey, unifiedHitSourceRegexpChannel); - } - }; - - var cloneMethod = (methodInstance) => { - const { data, config } = methodInstance; - const newConfig = { ...config }; - const { headers = {}, params = {} } = newConfig; - const ctx = getContext(methodInstance); - newConfig.headers = { ...headers }; - newConfig.params = { ...params }; - const newMethod = newInstance((Method), methodInstance.type, ctx, methodInstance.url, newConfig, data); - return objAssign(newMethod, { - ...methodInstance, - config: newConfig - }); - }; - - /* - * The matchers in the following three functions are Method instance matchers, which are divided into three situations: - * 1. If the matcher is a Method instance, clear the cache of the Method instance. - * 2. If matcher is a string or regular expression, clear the cache of all Method instances that meet the conditions. - * 3. If no matcher is passed in, all caches will be cleared. - */ - /** - * Query cache - * @param matcher Method instance matcher - * @returns Cache data, return undefined if not found - */ - const queryCache = async (matcher, { policy = 'all' } = {}) => { - // if key exists, that means it's a method instance. - if (matcher && matcher.key) { - const { id, l1Cache, l2Cache } = getContext(matcher); - const methodKey = getMethodInternalKey(matcher); - const { f: cacheFor, c: controlled, s: store, e: expireMilliseconds, t: tag } = getLocalCacheConfigParam(matcher); - // if it's controlled cache, it will return the result of cacheFor function. - if (controlled) { - return cacheFor(); - } - let cachedData = policy !== 'l2' ? await getWithCacheAdapter(id, methodKey, l1Cache) : undefinedValue; - if (policy === 'l2') { - cachedData = await getWithCacheAdapter(id, methodKey, l2Cache, tag); - } - else if (policy === 'all' && !cachedData) { - if (store && expireMilliseconds(STORAGE_RESTORE) > getTime()) { - cachedData = await getWithCacheAdapter(id, methodKey, l2Cache, tag); - } - } - return cachedData; - } - }; - /** - * Manually set cache response data. If the corresponding methodInstance sets persistent storage, the cache in the persistent storage will also be checked out. - * @param matcher Method instance matcher cache data - */ - const setCache = async (matcher, dataOrUpdater, { policy = 'all' } = {}) => { - const methodInstances = isArray(matcher) ? matcher : [matcher]; - const batchPromises = methodInstances.map(async (methodInstance) => { - const { hitSource } = methodInstance; - const { id, l1Cache, l2Cache } = getContext(methodInstance); - const methodKey = getMethodInternalKey(methodInstance); - const { e: expireMilliseconds, s: toStore, t: tag, c: controlled } = getLocalCacheConfigParam(methodInstance); - // don't set cache when it's controlled cache. - if (controlled) { - return; - } - let data = dataOrUpdater; - if (isFn(dataOrUpdater)) { - let cachedData = policy !== 'l2' ? await getWithCacheAdapter(id, methodKey, l1Cache) : undefinedValue; - if (policy === 'l2' || - (policy === 'all' && !cachedData && toStore && expireMilliseconds(STORAGE_RESTORE) > getTime())) { - cachedData = await getWithCacheAdapter(id, methodKey, l2Cache, tag); - } - data = dataOrUpdater(cachedData); - if (data === undefinedValue) { - return; - } - } - return PromiseCls.all([ - policy !== 'l2' && setWithCacheAdapter(id, methodKey, data, expireMilliseconds(MEMORY), l1Cache, hitSource), - policy === 'l2' || (policy === 'all' && toStore) - ? setWithCacheAdapter(id, methodKey, data, expireMilliseconds(STORAGE_RESTORE), l2Cache, hitSource, tag) - : undefinedValue - ]); - }); - return PromiseCls.all(batchPromises); - }; - /** - * invalid cache - * @param matcher Method instance matcher - */ - const invalidateCache = async (matcher) => { - if (!matcher) { - await PromiseCls.all([clearWithCacheAdapter(usingL1CacheAdapters), clearWithCacheAdapter(usingL2CacheAdapters)]); - return; - } - const methodInstances = isArray(matcher) ? matcher : [matcher]; - const batchPromises = methodInstances.map(methodInstance => { - const { id, l1Cache, l2Cache } = getContext(methodInstance); - const { c: controlled, m: cacheMode } = getLocalCacheConfigParam(methodInstance); - // don't invalidate cache when it's controlled cache. - if (controlled) { - return; - } - const methodKey = getMethodInternalKey(methodInstance); - return PromiseCls.all([ - removeWithCacheAdapter(id, methodKey, l1Cache), - cacheMode === STORAGE_RESTORE ? removeWithCacheAdapter(id, methodKey, l2Cache) : promiseResolve() - ]); - }); - await PromiseCls.all(batchPromises); - }; - /** - * hit(invalidate) target caches by source method - * this is the implementation of auto invalidate cache - * @param sourceMethod source method instance - */ - const hitCacheBySource = async (sourceMethod) => { - // Find the hit target cache and invalidate its cache - // Control the automatic cache invalidation range through global configuration `autoHitCache` - const { autoHitCache } = exports.globalConfigMap; - const { l1Cache, l2Cache } = getContext(sourceMethod); - const sourceKey = getMethodInternalKey(sourceMethod); - const { name: sourceName } = getConfig(sourceMethod); - const cacheAdaptersInvolved = { - global: [...usingL1CacheAdapters, ...usingL2CacheAdapters], - self: [l1Cache, l2Cache], - close: [] - }[autoHitCache]; - if (cacheAdaptersInvolved && len(cacheAdaptersInvolved)) { - await PromiseCls.all(mapItem(cacheAdaptersInvolved, involvedCacheAdapter => hitTargetCacheWithCacheAdapter(sourceKey, sourceName, involvedCacheAdapter))); - } - }; - - const adapterReturnMap = {}; - /** - * actual request function - * @param method request method object - * @param forceRequest Ignore cache - * @returns response data - */ - function sendRequest(methodInstance, forceRequest) { - let fromCache = trueValue; - let requestAdapterCtrlsPromiseResolveFn; - const requestAdapterCtrlsPromise = newInstance(PromiseCls, resolve => { - requestAdapterCtrlsPromiseResolveFn = resolve; - }); - const response = async () => { - const { beforeRequest = noop, responded, requestAdapter, cacheLogger } = getOptions(methodInstance); - const methodKey = getMethodInternalKey(methodInstance); - const { s: toStorage, t: tag, m: cacheMode, e: expireMilliseconds } = getLocalCacheConfigParam(methodInstance); - const { id, l1Cache, l2Cache, snapshots } = getContext(methodInstance); - // Get controlled cache or uncontrolled cache - const { cacheFor } = getConfig(methodInstance); - const { hitSource: methodHitSource } = methodInstance; - // If the current method sets a controlled cache, check whether there is custom data - let cachedResponse = await (isFn(cacheFor) - ? cacheFor() - : // If it is a forced request, skip the step of getting it from the cache - // Otherwise, determine whether to use cached data - forceRequest - ? undefinedValue - : getWithCacheAdapter(id, methodKey, l1Cache)); - // If it is storage restore mode and there is no data in the cache, the persistent data needs to be restored to the cache, and the cached expiration time must be used. - if (cacheMode === STORAGE_RESTORE && !cachedResponse && !forceRequest) { - const rawL2CacheData = await getRawWithCacheAdapter(id, methodKey, l2Cache, tag); - if (rawL2CacheData) { - const [l2Response, l2ExpireMilliseconds] = rawL2CacheData; - await setWithCacheAdapter(id, methodKey, l2Response, l2ExpireMilliseconds, l1Cache, methodHitSource); - cachedResponse = l2Response; - } - } - // Clone the method as a parameter and pass it to beforeRequest to prevent side effects when using the original method instance request multiple times. - // Place it after `let cachedResponse = await...` to solve the problem of first assigning promise to the method instance in method.send, otherwise the promise will be undefined in clonedMethod. - const clonedMethod = cloneMethod(methodInstance); - // Call the hook function before sending the request - // beforeRequest supports synchronous functions and asynchronous functions - await beforeRequest(clonedMethod); - const { baseURL, url: newUrl, type, data } = clonedMethod; - const { params = {}, headers = {}, transform = $self, shareRequest } = getConfig(clonedMethod); - const namespacedAdapterReturnMap = (adapterReturnMap[id] = adapterReturnMap[id] || {}); - const requestBody = clonedMethod.data; - const requestBodyIsSpecial = isSpecialRequestBody(requestBody); - // Will not share the request when requestBody is special data - let requestAdapterCtrls = requestBodyIsSpecial ? undefinedValue : namespacedAdapterReturnMap[methodKey]; - let responseSuccessHandler = $self; - let responseErrorHandler = undefinedValue; - let responseCompleteHandler = noop; - // uniform handler of onSuccess, onError, onComplete - if (isFn(responded)) { - responseSuccessHandler = responded; - } - else if (isPlainObject(responded)) { - const { onSuccess: successHandler, onError: errorHandler, onComplete: completeHandler } = responded; - responseSuccessHandler = isFn(successHandler) ? successHandler : responseSuccessHandler; - responseErrorHandler = isFn(errorHandler) ? errorHandler : responseErrorHandler; - responseCompleteHandler = isFn(completeHandler) ? completeHandler : responseCompleteHandler; - } - // If there is no cache, make a request - if (cachedResponse !== undefinedValue) { - requestAdapterCtrlsPromiseResolveFn(); // Ctrls will not be passed in when cache is encountered - // Print cache log - clonedMethod.fromCache = trueValue; - sloughFunction(cacheLogger, defaultCacheLogger)(cachedResponse, clonedMethod, cacheMode, tag); - responseCompleteHandler(clonedMethod); - return cachedResponse; - } - fromCache = falseValue; - if (!shareRequest || !requestAdapterCtrls) { - // Request data - const ctrls = requestAdapter({ - url: buildCompletedURL(baseURL, newUrl, params), - type, - data, - headers - }, clonedMethod); - requestAdapterCtrls = namespacedAdapterReturnMap[methodKey] = ctrls; - } - // Pass request adapter ctrls to promise for use in on download, on upload and abort - requestAdapterCtrlsPromiseResolveFn(requestAdapterCtrls); - /** - * Process response tasks and do not cache data on failure - * @param responsePromise Respond to promise instances - * @param responseHeaders Request header - * @param callInSuccess Whether to call in success callback - * @returns Processed response - */ - const handleResponseTask = async (handlerReturns, responseHeaders, callInSuccess = trueValue) => { - const responseData = await handlerReturns; - const transformedData = await transform(responseData, responseHeaders || {}); - snapshots.save(methodInstance); - // Even if the cache operation fails, the response structure will be returned normally to avoid request errors caused by cache operation problems. - // The cache operation results can be obtained through `cacheAdapter.emitter.on('success' | 'fail', event => {})` - try { - // Automatic cache invalidation - await hitCacheBySource(clonedMethod); - } - catch (_a) { } - // Do not save cache when requestBody is special data - // Reason 1: Special data is generally submitted and requires interaction with the server. - // Reason 2: Special data is not convenient for generating cache keys - const toCache = !requestBody || !requestBodyIsSpecial; - // Use the latest expiration time after the response to cache data to avoid the problem of expiration time loss due to too long response time - if (toCache && callInSuccess) { - try { - await PromiseCls.all([ - setWithCacheAdapter(id, methodKey, transformedData, expireMilliseconds(MEMORY), l1Cache, methodHitSource), - toStorage && - setWithCacheAdapter(id, methodKey, transformedData, expireMilliseconds(STORAGE_RESTORE), l2Cache, methodHitSource, tag) - ]); - } - catch (_b) { } - } - // Deep clone the transformed data before returning to avoid reference issues - // the `deepClone` will only clone array and plain object - return deepClone(transformedData); - }; - return promiseFinally(promiseThen(PromiseCls.all([requestAdapterCtrls.response(), requestAdapterCtrls.headers()]), ([rawResponse, rawHeaders]) => { - // Regardless of whether the request succeeds or fails, the shared request needs to be removed first - deleteAttr(namespacedAdapterReturnMap, methodKey); - return handleResponseTask(responseSuccessHandler(rawResponse, clonedMethod), rawHeaders); - }, (error) => { - // Regardless of whether the request succeeds or fails, the shared request needs to be removed first - deleteAttr(namespacedAdapterReturnMap, methodKey); - return isFn(responseErrorHandler) - ? // When responding to an error, if no error is thrown, the successful response process will be processed, but the data will not be cached. - handleResponseTask(responseErrorHandler(error, clonedMethod), undefinedValue, falseValue) - : promiseReject(error); - }), () => { - responseCompleteHandler(clonedMethod); - }); - }; - return { - // request interrupt function - abort: () => { - promiseThen(requestAdapterCtrlsPromise, requestAdapterCtrls => requestAdapterCtrls && requestAdapterCtrls.abort()); - }, - onDownload: (handler) => { - promiseThen(requestAdapterCtrlsPromise, requestAdapterCtrls => requestAdapterCtrls && requestAdapterCtrls.onDownload && requestAdapterCtrls.onDownload(handler)); - }, - onUpload: (handler) => { - promiseThen(requestAdapterCtrlsPromise, requestAdapterCtrls => requestAdapterCtrls && requestAdapterCtrls.onUpload && requestAdapterCtrls.onUpload(handler)); - }, - response, - fromCache: () => fromCache - }; - } - - const offEventCallback = (offHandler, handlers) => () => { - const index = handlers.indexOf(offHandler); - index >= 0 && handlers.splice(index, 1); - }; - class Method { - constructor(type, context, url, config, data) { - this.dhs = []; - this.uhs = []; - this.fromCache = undefinedValue; - const abortRequest = () => { - abortRequest.a(); - }; - abortRequest.a = noop; - const instance = this; - const contextOptions = getContextOptions(context); - instance.abort = abortRequest; - instance.baseURL = contextOptions.baseURL || ''; - instance.url = url; - instance.type = type; - instance.context = context; - // Merge request-related global configuration into the method object - const contextConcatConfig = {}; - const mergedLocalCacheKey = 'cacheFor'; - const globalLocalCache = isPlainObject(contextOptions[mergedLocalCacheKey]) - ? contextOptions[mergedLocalCacheKey][type] - : undefinedValue; - const hitSource = config && config.hitSource; - // Merge parameters - forEach(['timeout', 'shareRequest'], mergedKey => { - if (contextOptions[mergedKey] !== undefinedValue) { - contextConcatConfig[mergedKey] = contextOptions[mergedKey]; - } - }); - // Merge local cache - if (globalLocalCache !== undefinedValue) { - contextConcatConfig[mergedLocalCacheKey] = globalLocalCache; - } - // Unify hit sources into arrays and convert them into method keys when there are method instances - if (hitSource) { - instance.hitSource = mapItem(isArray(hitSource) ? hitSource : [hitSource], sourceItem => instanceOf(sourceItem, Method) ? getMethodInternalKey(sourceItem) : sourceItem); - deleteAttr(config, 'hitSource'); - } - instance.config = { - ...contextConcatConfig, - headers: {}, - params: {}, - ...(config || {}) - }; - instance.data = data; - instance.meta = config ? config.meta : instance.meta; - // The original key needs to be used externally instead of generating the key in real time. - // The reason is that the parameters of the method may pass in reference type values, but when the reference type value changes externally, the key generated in real time also changes, so it is more accurate to use the initial key. - instance.key = instance.generateKey(); - } - /** - * Bind download progress callback function - * @param progressHandler Download progress callback function - * @version 2.17.0 - * @return unbind function - */ - onDownload(downloadHandler) { - pushItem(this.dhs, downloadHandler); - return offEventCallback(downloadHandler, this.dhs); - } - /** - * Bind upload progress callback function - * @param progressHandler Upload progress callback function - * @version 2.17.0 - * @return unbind function - */ - onUpload(uploadHandler) { - pushItem(this.uhs, uploadHandler); - return offEventCallback(uploadHandler, this.uhs); - } - /** - * Send a request through a method instance and return a promise object - */ - send(forceRequest = falseValue) { - const instance = this; - const { response, onDownload, onUpload, abort, fromCache } = sendRequest(instance, forceRequest); - len(instance.dhs) > 0 && - onDownload((loaded, total) => forEach(instance.dhs, handler => handler({ loaded, total }))); - len(instance.uhs) > 0 && onUpload((loaded, total) => forEach(instance.uhs, handler => handler({ loaded, total }))); - // The interrupt function is bound to the method instance for each request. The user can also interrupt the current request through method instance.abort() - instance.abort.a = abort; - instance.fromCache = undefinedValue; - instance.promise = promiseThen(response(), r => { - instance.fromCache = fromCache(); - return r; - }); - return instance.promise; - } - /** - * Set the method name, if there is already a name it will be overwritten - * @param name method name - */ - setName(name) { - getConfig(this).name = name; - } - generateKey() { - return key(this); - } - /** - * Bind callbacks for resolve and/or reject Promise - * @param onfulfilled The callback to be executed when resolving the Promise - * @param onrejected The callback to be executed when the Promise is rejected - * @returns Returns a Promise for executing any callbacks - */ - then(onfulfilled, onrejected) { - return promiseThen(this.send(), onfulfilled, onrejected); - } - /** - * Bind a callback only for reject Promise - * @param onrejected The callback to be executed when the Promise is rejected - * @returns Returns a Promise that completes the callback - */ - catch(onrejected) { - return promiseCatch(this.send(), onrejected); - } - /** - * Bind a callback that is called when the Promise is resolved (resolve or reject) - * @param onfinally Callback executed when Promise is resolved (resolve or reject). - * @return Returns a Promise that completes the callback. - */ - finally(onfinally) { - return promiseFinally(this.send(), onfinally); - } - } - - /** - * Custom assertion function, throws an error when the expression is false - * @param expression Judgment expression, true or false - * @param msg assert message - */ - const myAssert = createAssert(); - - // local storage will not fail the operation. - const EVENT_SUCCESS_KEY = 'success'; - const memoryAdapter = () => { - let l1Cache = {}; - const l1CacheEmitter = createEventManager(); - const adapter = { - set(key, value) { - l1Cache[key] = value; - l1CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'set', key, value, container: l1Cache }); - }, - get: key => { - const value = l1Cache[key]; - l1CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'get', key, value, container: l1Cache }); - return value; - }, - remove(key) { - deleteAttr(l1Cache, key); - l1CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'remove', key, container: l1Cache }); - }, - clear: () => { - l1Cache = {}; - l1CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'clear', key: '', container: l1Cache }); - }, - emitter: l1CacheEmitter - }; - return adapter; - }; - const localStorageAdapter = () => { - const l2CacheEmitter = createEventManager(); - const instance = localStorage; - const adapter = { - set: (key, value) => { - instance.setItem(key, JSONStringify(value)); - l2CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'set', key, value, container: instance }); - }, - get: key => { - const data = instance.getItem(key); - const value = data ? JSONParse(data) : data; - l2CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'get', key, value, container: instance }); - return value; - }, - remove: key => { - instance.removeItem(key); - l2CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'remove', key, container: instance }); - }, - clear: () => { - instance.clear(); - l2CacheEmitter.emit(EVENT_SUCCESS_KEY, { type: 'clear', key: '', container: instance }); - }, - emitter: l2CacheEmitter - }; - return adapter; - }; - const placeholderAdapter = () => { - const l2CacheNotDefinedAssert = () => { - myAssert(falseValue, 'l2Cache is not defined.'); - }; - return { - set: () => { - l2CacheNotDefinedAssert(); - }, - get: () => { - l2CacheNotDefinedAssert(); - return undefinedValue; - }, - remove: () => { - l2CacheNotDefinedAssert(); - }, - clear: () => { } - }; - }; - - const SetCls = Set; - class MethodSnapshotContainer { - constructor(capacity) { - /** - * Method instance snapshot collection, method instances that have sent requests will be saved - */ - this.records = {}; - this.occupy = 0; - myAssert(capacity >= 0, 'expected snapshots limit to be >= 0'); - this.capacity = capacity; - } - /** - * Save method instance snapshot - * @param methodInstance method instance - */ - save(methodInstance) { - const { name } = getConfig(methodInstance); - const { records, occupy, capacity } = this; - if (name && occupy < capacity) { - // Using the name of the method as the key, save the method instance to the snapshot - const targetSnapshots = (records[name] = records[name] || newInstance(SetCls)); - targetSnapshots.add(methodInstance); - // Statistical quantity - this.occupy += 1; - } - } - /** - * Get a Method instance snapshot, which will filter out the corresponding Method instance based on the matcher - * @param matcher Matching snapshot name, which can be a string or regular expression, or an object with a filter function - * @returns Array of matched Method instance snapshots - */ - match(matcher, matchAll = true) { - // Unify the filter parameters into name matcher and match handler - let nameString; - let nameReg; - let matchHandler; - let nameMatcher = matcher; - if (isPlainObject(matcher)) { - nameMatcher = matcher.name; - matchHandler = matcher.filter; - } - if (instanceOf(nameMatcher, RegExpCls)) { - nameReg = nameMatcher; - } - else if (isString(nameMatcher)) { - nameString = nameMatcher; - } - const { records } = this; - // Get the corresponding method instance snapshot through the deconstructed name matcher and filter handler - let matches = newInstance((SetCls)); - // If the namespace parameter is provided, it will only be searched in this namespace, otherwise it will be searched in all cached data. - if (nameString) { - matches = records[nameString] || matches; - } - else if (nameReg) { - forEach(filterItem(objectKeys(records), methodName => nameReg.test(methodName)), methodName => { - records[methodName].forEach(method => matches.add(method)); - }); - } - const fromMatchesArray = isFn(matchHandler) ? filterItem([...matches], matchHandler) : [...matches]; - return (matchAll ? fromMatchesArray : fromMatchesArray[0]); - } - } - - const typeGet = 'GET'; - const typeHead = 'HEAD'; - const typePost = 'POST'; - const typePut = 'PUT'; - const typePatch = 'PATCH'; - const typeDelete = 'DELETE'; - const typeOptions = 'OPTIONS'; - const defaultAlovaOptions = { - /** - * GET requests are cached for 5 minutes (300000 milliseconds) by default, and other requests are not cached by default. - */ - cacheFor: { - [typeGet]: 300000 - }, - /** - * Share requests default to true - */ - shareRequest: trueValue, - /** - * Number of method snapshots, default is 1000 - */ - snapshots: 1000 - }; - let idCount = 0; - class Alova { - constructor(options) { - var _a, _b; - const instance = this; - instance.id = (options.id || (idCount += 1)).toString(); - // If storage is not specified, local storage is used by default. - instance.l1Cache = options.l1Cache || memoryAdapter(); - instance.l2Cache = - options.l2Cache || (typeof localStorage !== 'undefined' ? localStorageAdapter() : placeholderAdapter()); - // Merge default options - instance.options = { - ...defaultAlovaOptions, - ...options - }; - instance.snapshots = newInstance((MethodSnapshotContainer), (_b = (_a = options.snapshots) !== null && _a !== void 0 ? _a : defaultAlovaOptions.snapshots) !== null && _b !== void 0 ? _b : 0); - } - Get(url, config) { - return newInstance((Method), typeGet, this, url, config); - } - Post(url, data, config) { - return newInstance((Method), typePost, this, url, config, data); - } - Delete(url, data, config) { - return newInstance((Method), typeDelete, this, url, config, data); - } - Put(url, data, config) { - return newInstance((Method), typePut, this, url, config, data); - } - Head(url, config) { - return newInstance((Method), typeHead, this, url, config); - } - Patch(url, data, config) { - return newInstance((Method), typePatch, this, url, config, data); - } - Options(url, config) { - return newInstance((Method), typeOptions, this, url, config); - } - } - let boundStatesHook = undefinedValue; - const usingL1CacheAdapters = []; - const usingL2CacheAdapters = []; - /** - * create an alova instance. - * @param options alova configuration. - * @returns alova instance. - */ - const createAlova = (options) => { - const alovaInstance = newInstance((Alova), options); - const newStatesHook = alovaInstance.options.statesHook; - if (boundStatesHook) { - myAssert(boundStatesHook === newStatesHook, 'expected to use the same `statesHook`'); - } - boundStatesHook = newStatesHook; - const { l1Cache, l2Cache } = alovaInstance; - !usingL1CacheAdapters.includes(l1Cache) && pushItem(usingL1CacheAdapters, l1Cache); - !usingL2CacheAdapters.includes(l2Cache) && pushItem(usingL2CacheAdapters, l2Cache); - return alovaInstance; - }; - - const promiseStatesHook = () => { - myAssert(!!boundStatesHook, '`statesHook` is not set in alova instance'); - return boundStatesHook; - }; - - exports.Method = Method; - exports.createAlova = createAlova; - exports.globalConfig = globalConfig; - exports.hitCacheBySource = hitCacheBySource; - exports.invalidateCache = invalidateCache; - exports.promiseStatesHook = promiseStatesHook; - exports.queryCache = queryCache; - exports.setCache = setCache; - -})); diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/alova.umd.min.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/alova.umd.min.js deleted file mode 100644 index f75a3a6..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/alova.umd.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).alova={})}(this,(function(t){"use strict";const e="undefined",a=Promise,o=Object,s=RegExp,n=void 0,r=null,c=!0,i=!1,l=(t,e,a)=>t.then(e,a),h=(t,e)=>t.finally(e),u=(t,e,a)=>JSON.stringify(t,e,a),d=t=>o.keys(t),p=(t,e)=>t.forEach(e),f=(t,...e)=>t.push(...e),m=(t,e)=>t.map(e),y=(t,e)=>t.filter(e),g=t=>t.length,w=t=>Array.isArray(t),C=(t,e)=>delete t[e],v=t=>typeof t,b=typeof window===e&&(typeof process!==e?"function"==typeof process.cwd:typeof Deno!==e),S="memory",$="restore",k=()=>{},x=t=>t,E=t=>"function"===v(t),T=t=>o.prototype.toString.call(t),D=t=>"[object Object]"===T(t),H=(t,e)=>t instanceof e,M=t=>t?t.getTime():Date.now(),O=t=>t.context,R=t=>t.config,U=t=>t.options,j=t=>t.key,P=t=>{const{cacheFor:e}=R(t),a=t=>{return"number"!==v(e=t)||Number.isNaN(e)?M(t||n):M()+t;var e};let o=S,s=()=>0,r=i,c=n;const l=E(e);if(!l){let i=e;if(D(e)){const{mode:t=S,expire:a,tag:s}=e||{};o=t,r=t===$,c=s?s.toString():n,i=a}s=e=>a(E(i)?i({method:t,mode:e}):i)}return{f:e,c:l,e:s,m:o,s:r,t:c}},A=(t,...e)=>new t(...e),N=(t,e)=>"$a."+t+e,q=(t,e,a)=>{t=t.endsWith("/")?t.slice(0,-1):t,""!==e&&(e=e.match(/^(\/|https?:\/\/)/)?e:`/${e}`);const o=t+e,s=m(y(d(a),(t=>a[t]!==n)),(t=>`${t}=${a[t]}`)).join("&");return s?+o.includes("?")?`${o}&${s}`:`${o}?${s}`:o},F=t=>{if(w(t))return m(t,F);if(D(t)&&t.constructor===o){const e={};return p(d(t),(a=>{e[a]=F(t[a])})),e}return t};class L extends Error{constructor(t,e,a){super(e+(a?`\n\nFor detailed: https://alova.js.org/error#${a}`:"")),this.name=`[alova${t?`/${t}`:""}]`}}const B=()=>{const t={};return{eventMap:t,on(e,a){const o=t[e]=t[e]||[];return f(o,a),()=>{t[e]=y(o,(t=>t!==a))}},off(e,a){const o=t[e];if(o)if(a){const t=o.indexOf(a);t>-1&&o.splice(t,1)}else delete t[e]},emit(e,a){const o=t[e]||[];return m(o,(t=>t(a)))}}};t.globalConfigMap={autoHitCache:"global",ssr:b};const I="color: black; font-size: 12px; font-weight: bolder";var _=(e,a,o,s)=>{const n=console,r=(...t)=>console.log(...t),{url:c}=a,i=o===$,l="%s",h="%s",u=` [HitCache]${c} `,d=()=>Array(g(u)+1).join("^");t.globalConfigMap.ssr?(r(l,u),r(h," Cache ",e),r(h," Mode ",o),i&&r(h," Tag ",s),r(h,d())):(n.groupCollapsed?n.groupCollapsed("%cHitCache","padding: 2px 6px; background: #c4fcd3; color: #53b56d;",c):r(l,u),r("%c[Cache]",I,e),r("%c[Mode]",I,o),i&&r("%c[Tag]",I,s),r("%c[Method]",I,a),n.groupEnd?n.groupEnd():r(h,d()))};const G=t=>`hss.${t}`,J="hsr.",K=t=>J+t,z="$$hsrs",W="__$<>$__",Q=(t,e)=>{t[e]=0},V=async(t,e,o,r,c,i,l)=>{if(r>M()&&o){const h=N(t,e);if(await c.set(h,y([o,r===1/0?n:r,l],Boolean)),i){const t={},e=[];p(i,(a=>{const o=H(a,s),n=o?a.source+(a.flags?W+a.flags:""):a;n&&(o&&!t[n]&&f(e,n),Q(t,o?K(n):G(n)))}));const o=m(d(t),(async t=>{const e=await c.get(t)||{};Q(e,h),await c.set(t,e)})),n=async()=>{if(g(e)){const t=await c.get(z)||[];f(t,...e),await c.set(z,t)}};await a.all([...o,n()])}}},X=async(t,e,a)=>{const o=N(t,e);await a.remove(o)},Y=async(t,e,a,o)=>{const s=await a.get(N(t,e));if(s){const[n,r,c]=s;if(c===o&&(!r||r>M()))return s;await X(t,e,a)}},Z=async(t,e,a,o)=>{const s=await Y(t,e,a,o);return s?s[0]:n},tt=async t=>a.all(t.map((t=>t.clear())));var et=t=>{const{data:e,config:a}=t,s={...a},{headers:n={},params:r={}}=s,c=O(t);s.headers={...n},s.params={...r};return((t,...e)=>o.assign(t,...e))(A(rt,t.type,c,t.url,s,e),{...t,config:s})};const at=async e=>{const{autoHitCache:o}=t.globalConfigMap,{l1Cache:n,l2Cache:r}=O(e),c=j(e),{name:i}=R(e),l={global:[...gt,...wt],self:[n,r],close:[]}[o];l&&g(l)&&await a.all(m(l,(t=>(async(t,e,o)=>{const n=`${e}`,r={},c=G(t);let i;if(r[c]=await o.get(c),e){const t=G(n);r[t]=await o.get(t),i=await o.get(z);const e=[];i&&g(i)&&(p(i,(t=>{const[a,o]=t.split(W);A(s,a,o).test(n)&&f(e,t)})),await a.all(m(e,(async t=>{const e=K(t);r[e]=await o.get(e)}))))}const l=async t=>{try{await o.remove(t);for(const e in r){const a=r[e];a&&C(a,t)}}catch(t){}},h={};await a.all(m(d(r),(async t=>{const e=r[t];if(e){const t=[];for(const a in e)h[a]||(Q(h,a),f(t,l(a)));await a.all(t)}})));const u=g(i||[]);await a.all(m(d(r),(async t=>{const e=r[t];e&&(g(d(e))?await o.set(t,e):(await o.remove(t),t.includes(J)&&i&&(i=y(i,(e=>K(e)!==t)))))}))),u!==g(i||[])&&await o.set(z,i)})(c,i,t))))},ot={};function st(t,e){let o,s=c;const u=A(a,(t=>{o=t}));return{abort:()=>{l(u,(t=>t&&t.abort()))},onDownload:t=>{l(u,(e=>e&&e.onDownload&&e.onDownload(t)))},onUpload:t=>{l(u,(e=>e&&e.onUpload&&e.onUpload(t)))},response:async()=>{const{beforeRequest:u=k,responded:d,requestAdapter:p,cacheLogger:f}=(t=>U(O(t)))(t),m=j(t),{s:y,t:g,m:w,e:v}=P(t),{id:b,l1Cache:M,l2Cache:A,snapshots:N}=O(t),{cacheFor:L}=R(t),{hitSource:B}=t;let I=await(E(L)?L():e?n:Z(b,m,M));if(w===$&&!I&&!e){const t=await Y(b,m,A,g);if(t){const[e,a]=t;await V(b,m,e,a,M,B),I=e}}const G=et(t);await u(G);const{baseURL:J,url:K,type:z,data:W}=G,{params:Q={},headers:X={},transform:tt=x,shareRequest:st}=R(G),nt=ot[b]=ot[b]||{},rt=G.data,ct=(t=>{const e=T(t);return/^\[object (Blob|FormData|ReadableStream|URLSearchParams)\]$/i.test(e)||H(t,ArrayBuffer)})(rt);let it=ct?n:nt[m],lt=x,ht=n,ut=k;if(E(d))lt=d;else if(D(d)){const{onSuccess:t,onError:e,onComplete:a}=d;lt=E(t)?t:lt,ht=E(e)?e:ht,ut=E(a)?a:ut}if(I!==n)return o(),G.fromCache=c,(pt=_,E(dt=f)?dt:[i,r].includes(dt)?k:pt)(I,G,w,g),ut(G),I;var dt,pt;if(s=i,!st||!it){const t=p({url:q(J,K,Q),type:z,data:W,headers:X},G);it=nt[m]=t}o(it);const ft=async(e,o,s=true)=>{const n=await e,r=await tt(n,o||{});N.save(t);try{await at(G)}catch(t){}if((!rt||!ct)&&s)try{await a.all([V(b,m,r,v(S),M,B),y&&V(b,m,r,v($),A,B,g)])}catch(t){}return F(r)};return h(l(a.all([it.response(),it.headers()]),(([t,e])=>(C(nt,m),ft(lt(t,G),e))),(t=>{return C(nt,m),E(ht)?ft(ht(t,G),n,i):(e=t,a.reject(e));var e})),(()=>{ut(G)}))},fromCache:()=>s}}const nt=(t,e)=>()=>{const a=e.indexOf(t);a>=0&&e.splice(a,1)};class rt{constructor(t,e,a,o,s){this.dhs=[],this.uhs=[],this.fromCache=n;const r=()=>{r.a()};r.a=k;const c=this,i=U(e);c.abort=r,c.baseURL=i.baseURL||"",c.url=a,c.type=t,c.context=e;const l={},h="cacheFor",u=D(i[h])?i[h][t]:n,d=o&&o.hitSource;p(["timeout","shareRequest"],(t=>{i[t]!==n&&(l[t]=i[t])})),u!==n&&(l[h]=u),d&&(c.hitSource=m(w(d)?d:[d],(t=>H(t,rt)?j(t):t)),C(o,"hitSource")),c.config={...l,headers:{},params:{},...o||{}},c.data=s,c.meta=o?o.meta:c.meta,c.key=c.generateKey()}onDownload(t){return f(this.dhs,t),nt(t,this.dhs)}onUpload(t){return f(this.uhs,t),nt(t,this.uhs)}send(t=i){const e=this,{response:a,onDownload:o,onUpload:s,abort:r,fromCache:c}=st(e,t);return g(e.dhs)>0&&o(((t,a)=>p(e.dhs,(e=>e({loaded:t,total:a}))))),g(e.uhs)>0&&s(((t,a)=>p(e.uhs,(e=>e({loaded:t,total:a}))))),e.abort.a=r,e.fromCache=n,e.promise=l(a(),(t=>(e.fromCache=c(),t))),e.promise}setName(t){R(this).name=t}generateKey(){return(t=>{const{params:e,headers:a}=R(t);return u([t.type,t.url,e,t.data,a])})(this)}then(t,e){return l(this.send(),t,e)}catch(t){return((t,e)=>t.catch(e))(this.send(),t)}finally(t){return h(this.send(),t)}}const ct=((t="")=>(e,a,o)=>{if(!e)throw A(L,t,a,o)})(),it="success",lt=()=>{const t=B(),e=localStorage,a={set:(a,o)=>{e.setItem(a,u(o)),t.emit(it,{type:"set",key:a,value:o,container:e})},get:a=>{const o=e.getItem(a),s=o?(t=>JSON.parse(t))(o):o;return t.emit(it,{type:"get",key:a,value:s,container:e}),s},remove:a=>{e.removeItem(a),t.emit(it,{type:"remove",key:a,container:e})},clear:()=>{e.clear(),t.emit(it,{type:"clear",key:"",container:e})},emitter:t};return a},ht=Set;class ut{constructor(t){this.records={},this.occupy=0,ct(t>=0,"expected snapshots limit to be >= 0"),this.capacity=t}save(t){const{name:e}=R(t),{records:a,occupy:o,capacity:s}=this;if(e&&oo.test(t))),(t=>{c[t].forEach((t=>i.add(t)))}));const l=E(n)?y([...i],n):[...i];return e?l:l[0]}}const dt="GET",pt={cacheFor:{[dt]:3e5},shareRequest:c,snapshots:1e3};let ft=0;class mt{constructor(t){var e,a;const o=this;o.id=(t.id||(ft+=1)).toString(),o.l1Cache=t.l1Cache||(()=>{let t={};const e=B(),a={set(a,o){t[a]=o,e.emit(it,{type:"set",key:a,value:o,container:t})},get:a=>{const o=t[a];return e.emit(it,{type:"get",key:a,value:o,container:t}),o},remove(a){C(t,a),e.emit(it,{type:"remove",key:a,container:t})},clear:()=>{t={},e.emit(it,{type:"clear",key:"",container:t})},emitter:e};return a})(),o.l2Cache=t.l2Cache||("undefined"!=typeof localStorage?lt():(()=>{const t=()=>{ct(i,"l2Cache is not defined.")};return{set:()=>{t()},get:()=>(t(),n),remove:()=>{t()},clear:()=>{}}})()),o.options={...pt,...t},o.snapshots=A(ut,null!==(a=null!==(e=t.snapshots)&&void 0!==e?e:pt.snapshots)&&void 0!==a?a:0)}Get(t,e){return A(rt,"GET",this,t,e)}Post(t,e,a){return A(rt,"POST",this,t,a,e)}Delete(t,e,a){return A(rt,"DELETE",this,t,a,e)}Put(t,e,a){return A(rt,"PUT",this,t,a,e)}Head(t,e){return A(rt,"HEAD",this,t,e)}Patch(t,e,a){return A(rt,"PATCH",this,t,a,e)}Options(t,e){return A(rt,"OPTIONS",this,t,e)}}let yt=n;const gt=[],wt=[];t.Method=rt,t.createAlova=t=>{const e=A(mt,t),a=e.options.statesHook;yt&&ct(yt===a,"expected to use the same `statesHook`"),yt=a;const{l1Cache:o,l2Cache:s}=e;return!gt.includes(o)&&f(gt,o),!wt.includes(s)&&f(wt,s),e},t.globalConfig=e=>{t.globalConfigMap={...t.globalConfigMap,...e}},t.hitCacheBySource=at,t.invalidateCache=async t=>{if(!t)return void await a.all([tt(gt),tt(wt)]);const e=(w(t)?t:[t]).map((t=>{const{id:e,l1Cache:o,l2Cache:s}=O(t),{c:n,m:r}=P(t);if(n)return;const c=j(t);return a.all([X(e,c,o),r===$?X(e,c,s):a.resolve(i)]);var i}));await a.all(e)},t.promiseStatesHook=()=>(ct(!!yt,"`statesHook` is not set in alova instance"),yt),t.queryCache=async(t,{policy:e="all"}={})=>{if(t&&t.key){const{id:a,l1Cache:o,l2Cache:s}=O(t),r=j(t),{f:c,c:i,s:l,e:h,t:u}=P(t);if(i)return c();let d="l2"!==e?await Z(a,r,o):n;return"l2"===e?d=await Z(a,r,s,u):"all"!==e||d||l&&h($)>M()&&(d=await Z(a,r,s,u)),d}},t.setCache=async(t,e,{policy:o="all"}={})=>{const s=(w(t)?t:[t]).map((async t=>{const{hitSource:s}=t,{id:r,l1Cache:c,l2Cache:i}=O(t),l=j(t),{e:h,s:u,t:d,c:p}=P(t);if(p)return;let f=e;if(E(e)){let t="l2"!==o?await Z(r,l,c):n;if(("l2"===o||"all"===o&&!t&&u&&h($)>M())&&(t=await Z(r,l,i,d)),f=e(t),f===n)return}return a.all(["l2"!==o&&V(r,l,f,h(S),c,s),"l2"===o||"all"===o&&u?V(r,l,f,h($),i,s,d):n])}));return a.all(s)}})); diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/clienthook/index.common.cjs b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/clienthook/index.common.cjs deleted file mode 100644 index e7051ef..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/clienthook/index.common.cjs +++ /dev/null @@ -1,3463 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -'use strict'; - -var shared = require('@alova/shared'); -var alova = require('alova'); - -const defaultVisitorMeta = { - authRole: null -}; -const defaultLoginMeta = { - authRole: 'login' -}; -const defaultLogoutMeta = { - authRole: 'logout' -}; -const defaultRefreshTokenMeta = { - authRole: 'refreshToken' -}; -const checkMethodRole = ({ meta }, metaMatches) => { - if (shared.isPlainObject(meta)) { - for (const key in meta) { - if (Object.prototype.hasOwnProperty.call(meta, key)) { - const matchedMetaItem = metaMatches[key]; - if (shared.instanceOf(matchedMetaItem, RegExp) ? matchedMetaItem.test(meta[key]) : meta[key] === matchedMetaItem) { - return shared.trueValue; - } - } - } - } - return shared.falseValue; -}; -const waitForTokenRefreshed = (method, waitingList) => shared.newInstance(shared.PromiseCls, resolve => { - shared.pushItem(waitingList, { - method, - resolve - }); -}); -const callHandlerIfMatchesMeta = (method, authorizationInterceptor, defaultMeta, response) => { - if (checkMethodRole(method, (authorizationInterceptor === null || authorizationInterceptor === void 0 ? void 0 : authorizationInterceptor.metaMatches) || defaultMeta)) { - const handler = shared.isFn(authorizationInterceptor) - ? authorizationInterceptor - : shared.isPlainObject(authorizationInterceptor) && shared.isFn(authorizationInterceptor.handler) - ? authorizationInterceptor.handler - : shared.noop; - return handler(response, method); - } -}; -const refreshTokenIfExpired = async (method, waitingList, updateRefreshStatus, handlerParams, refreshToken, tokenRefreshing) => { - // When the number of handle params is greater than 2, it means that this function is called from the response, and the original interface needs to be requested again. - const fromResponse = shared.len(handlerParams) >= 2; - let isExpired = refreshToken === null || refreshToken === void 0 ? void 0 : refreshToken.isExpired(...handlerParams); - // Compatible with synchronous and asynchronous functions - if (shared.instanceOf(isExpired, shared.PromiseCls)) { - isExpired = await isExpired; - } - if (isExpired) { - try { - // Make another judgment in the response to prevent multiple requests to refresh the token, intercept and wait for the token sent before the token refresh is completed. - let intentToRefreshToken = shared.trueValue; - if (fromResponse && tokenRefreshing) { - intentToRefreshToken = shared.falseValue; // The requests waiting here indicate that the token is being refreshed. When they pass, there is no need to refresh the token again. - await waitForTokenRefreshed(method, waitingList); - } - if (intentToRefreshToken) { - updateRefreshStatus(shared.trueValue); - // Call refresh token - await (refreshToken === null || refreshToken === void 0 ? void 0 : refreshToken.handler(...handlerParams)); - updateRefreshStatus(shared.falseValue); - // After the token refresh is completed, the requests in the waiting list are notified. - shared.forEach(waitingList, ({ resolve }) => resolve()); - } - if (fromResponse) { - // Because the original interface is being requested again, superposition with the previous request will result in repeated calls to transform, so it is necessary to leave transform empty to remove one call. - const { config } = method; - const methodTransformData = config.transform; - config.transform = shared.undefinedValue; - const resentData = await method; - config.transform = methodTransformData; - return resentData; - } - } - finally { - updateRefreshStatus(shared.falseValue); - shared.splice(waitingList, 0, shared.len(waitingList)); // Clear waiting list - } - } -}; -const onResponded2Record = (onRespondedHandlers) => { - let successHandler = shared.undefinedValue; - let errorHandler = shared.undefinedValue; - let onCompleteHandler = shared.undefinedValue; - if (shared.isFn(onRespondedHandlers)) { - successHandler = onRespondedHandlers; - } - else if (shared.isPlainObject(onRespondedHandlers)) { - const { onSuccess, onError, onComplete } = onRespondedHandlers; - successHandler = shared.isFn(onSuccess) ? onSuccess : successHandler; - errorHandler = shared.isFn(onError) ? onError : errorHandler; - onCompleteHandler = shared.isFn(onComplete) ? onComplete : onCompleteHandler; - } - return { - onSuccess: successHandler, - onError: errorHandler, - onComplete: onCompleteHandler - }; -}; - -/** - * Create a client-side token authentication interceptor - * @param options Configuration parameters - * @returns token authentication interceptor function - */ -const createClientTokenAuthentication = ({ visitorMeta, login, logout, refreshToken, assignToken = shared.noop }) => { - let tokenRefreshing = shared.falseValue; - const waitingList = []; - const onAuthRequired = onBeforeRequest => async (method) => { - const isVisitorRole = checkMethodRole(method, visitorMeta || defaultVisitorMeta); - const isLoginRole = checkMethodRole(method, (login === null || login === void 0 ? void 0 : login.metaMatches) || defaultLoginMeta); - // Ignored, login, and token refresh requests do not perform token authentication. - if (!isVisitorRole && - !isLoginRole && - !checkMethodRole(method, (refreshToken === null || refreshToken === void 0 ? void 0 : refreshToken.metaMatches) || defaultRefreshTokenMeta)) { - // If the token is being refreshed, wait for the refresh to complete before sending a request. - if (tokenRefreshing) { - await waitForTokenRefreshed(method, waitingList); - } - await refreshTokenIfExpired(method, waitingList, refreshing => { - tokenRefreshing = refreshing; - }, [method], refreshToken); - } - // Requests from non-guest and logged-in roles will enter the assignment token function - if (!isVisitorRole && !isLoginRole) { - await assignToken(method); - } - return onBeforeRequest === null || onBeforeRequest === void 0 ? void 0 : onBeforeRequest(method); - }; - const onResponseRefreshToken = originalResponded => { - const respondedRecord = onResponded2Record(originalResponded); - return { - ...respondedRecord, - onSuccess: async (response, method) => { - await callHandlerIfMatchesMeta(method, login, defaultLoginMeta, response); - await callHandlerIfMatchesMeta(method, logout, defaultLogoutMeta, response); - return (respondedRecord.onSuccess || shared.$self)(response, method); - } - }; - }; - return { - waitingList, - onAuthRequired, - onResponseRefreshToken - }; -}; -/** - * Create a server-side token authentication interceptor - * @param options Configuration parameters - * @returns token authentication interceptor function - */ -const createServerTokenAuthentication = ({ visitorMeta, login, logout, refreshTokenOnSuccess, refreshTokenOnError, assignToken = shared.noop }) => { - let tokenRefreshing = shared.falseValue; - const waitingList = []; - const onAuthRequired = onBeforeRequest => async (method) => { - const isVisitorRole = checkMethodRole(method, visitorMeta || defaultVisitorMeta); - const isLoginRole = checkMethodRole(method, (login === null || login === void 0 ? void 0 : login.metaMatches) || defaultLoginMeta); - // Ignored, login, and token refresh requests do not perform token authentication. - if (!isVisitorRole && - !isLoginRole && - !checkMethodRole(method, (refreshTokenOnSuccess === null || refreshTokenOnSuccess === void 0 ? void 0 : refreshTokenOnSuccess.metaMatches) || defaultRefreshTokenMeta) && - !checkMethodRole(method, (refreshTokenOnError === null || refreshTokenOnError === void 0 ? void 0 : refreshTokenOnError.metaMatches) || defaultRefreshTokenMeta)) { - // If the token is being refreshed, wait for the refresh to complete before sending a request. - if (tokenRefreshing) { - await waitForTokenRefreshed(method, waitingList); - } - } - if (!isVisitorRole && !isLoginRole) { - await assignToken(method); - } - return onBeforeRequest === null || onBeforeRequest === void 0 ? void 0 : onBeforeRequest(method); - }; - const onResponseRefreshToken = onRespondedHandlers => { - const respondedRecord = onResponded2Record(onRespondedHandlers); - return { - ...respondedRecord, - onSuccess: async (response, method) => { - if (!checkMethodRole(method, visitorMeta || defaultVisitorMeta) && - !checkMethodRole(method, (login === null || login === void 0 ? void 0 : login.metaMatches) || defaultLoginMeta) && - !checkMethodRole(method, (refreshTokenOnSuccess === null || refreshTokenOnSuccess === void 0 ? void 0 : refreshTokenOnSuccess.metaMatches) || defaultRefreshTokenMeta)) { - const dataResent = await refreshTokenIfExpired(method, waitingList, refreshing => { - tokenRefreshing = refreshing; - }, [response, method], refreshTokenOnSuccess, tokenRefreshing); - if (dataResent) { - return dataResent; - } - } - await callHandlerIfMatchesMeta(method, login, defaultLoginMeta, response); - await callHandlerIfMatchesMeta(method, logout, defaultLogoutMeta, response); - return (respondedRecord.onSuccess || shared.$self)(response, method); - }, - onError: async (error, method) => { - if (!checkMethodRole(method, visitorMeta || defaultVisitorMeta) && - !checkMethodRole(method, (login === null || login === void 0 ? void 0 : login.metaMatches) || defaultLoginMeta) && - !checkMethodRole(method, (refreshTokenOnError === null || refreshTokenOnError === void 0 ? void 0 : refreshTokenOnError.metaMatches) || defaultRefreshTokenMeta)) { - const dataResent = await refreshTokenIfExpired(method, waitingList, refreshing => { - tokenRefreshing = refreshing; - }, [error, method], refreshTokenOnError, tokenRefreshing); - if (dataResent) { - return dataResent; - } - } - return (respondedRecord.onError || shared.noop)(error, method); - } - }; - }; - return { - waitingList, - onAuthRequired, - onResponseRefreshToken - }; -}; - -/** - * Compatible functions, throwing parameters - * @param error mistake - */ -const throwFn = (error) => { - throw error; -}; -function useCallback(onCallbackChange = shared.noop) { - let callbacks = []; - const setCallback = (fn) => { - if (!callbacks.includes(fn)) { - callbacks.push(fn); - onCallbackChange(callbacks); - } - // Return unregister function - return () => { - callbacks = shared.filterItem(callbacks, e => e !== fn); - onCallbackChange(callbacks); - }; - }; - const triggerCallback = (...args) => { - if (callbacks.length > 0) { - return shared.forEach(callbacks, fn => fn(...args)); - } - }; - const removeAllCallback = () => { - callbacks = []; - onCallbackChange(callbacks); - }; - return [setCallback, triggerCallback, removeAllCallback]; -} -/** - * Create a debounce function and trigger the function immediately when delay is 0 - * Scenario: When calling useWatcher and setting immediate to true, the first call must be executed immediately, otherwise it will cause a delayed call - * @param {GeneralFn} fn callback function - * @param {number|(...args: any[]) => number} delay Delay description, dynamic delay can be achieved when set as a function - * @returns Delayed callback function - */ -const debounce = (fn, delay) => { - let timer = shared.nullValue; - return function debounceFn(...args) { - const bindFn = fn.bind(this, ...args); - const delayMill = shared.isNumber(delay) ? delay : delay(...args); - timer && shared.clearTimeoutTimer(timer); - if (delayMill > 0) { - timer = shared.setTimeoutFn(bindFn, delayMill); - } - else { - bindFn(); - } - }; -}; -/** - * Get the request method object - * @param methodHandler Request method handle - * @param args Method call parameters - * @returns request method object - */ -const getHandlerMethod = (methodHandler, args = []) => { - const methodInstance = shared.isFn(methodHandler) ? methodHandler(...args) : methodHandler; - shared.createAssert('scene')(shared.instanceOf(methodInstance, alova.Method), 'hook handler must be a method instance or a function that returns method instance'); - return methodInstance; -}; -/** - * Convert each value of the object and return the new object - * @param obj object - * @param callback callback function - * @returns converted object - */ -const mapObject = (obj, callback) => { - const ret = {}; - for (const key in obj) { - ret[key] = callback(obj[key], key, obj); - } - return ret; -}; -var EnumHookType; -(function (EnumHookType) { - EnumHookType[EnumHookType["USE_REQUEST"] = 1] = "USE_REQUEST"; - EnumHookType[EnumHookType["USE_WATCHER"] = 2] = "USE_WATCHER"; - EnumHookType[EnumHookType["USE_FETCHER"] = 3] = "USE_FETCHER"; -})(EnumHookType || (EnumHookType = {})); -/** - * create simple and unified, framework-independent states creators and handlers. - * @param statesHook states hook from `promiseStatesHook` function of alova - * @param referingObject refering object exported from `promiseStatesHook` function - * @returns simple and unified states creators and handlers - */ -function statesHookHelper(statesHook, referingObject = { trackedKeys: {}, bindError: shared.falseValue }) { - const ref = (initialValue) => (statesHook.ref ? statesHook.ref(initialValue) : { current: initialValue }); - referingObject = ref(referingObject).current; - const exportState = (state) => (statesHook.export || shared.$self)(state, referingObject); - const memorize = (fn) => { - if (!shared.isFn(statesHook.memorize)) { - return fn; - } - const memorizedFn = statesHook.memorize(fn); - memorizedFn.memorized = true; - return memorizedFn; - }; - const { dehydrate } = statesHook; - // For performance reasons, only value is different, and the key is tracked can be updated. - const update = (newValue, state, key) => newValue !== dehydrate(state, key, referingObject) && - referingObject.trackedKeys[key] && - statesHook.update(newValue, state, key, referingObject); - const mapDeps = (deps) => shared.mapItem(deps, item => (shared.instanceOf(item, shared.FrameworkReadableState) ? item.e : item)); - const createdStateList = []; - // key of deps on computed - const depKeys = {}; - return { - create: (initialValue, key) => { - shared.pushItem(createdStateList, key); // record the keys of created states. - return shared.newInstance((shared.FrameworkState), statesHook.create(initialValue, key, referingObject), key, state => dehydrate(state, key, referingObject), exportState, (state, newValue) => update(newValue, state, key)); - }, - computed: (getter, depList, key) => { - // Collect all dependencies in computed - shared.forEach(depList, dep => { - if (dep.k) { - depKeys[dep.k] = true; - } - }); - return shared.newInstance((shared.FrameworkReadableState), statesHook.computed(getter, mapDeps(depList), key, referingObject), key, state => dehydrate(state, key, referingObject), exportState); - }, - effectRequest: (effectRequestParams) => statesHook.effectRequest(effectRequestParams, referingObject), - ref, - watch: (source, callback) => statesHook.watch(mapDeps(source), callback, referingObject), - onMounted: (callback) => statesHook.onMounted(callback, referingObject), - onUnmounted: (callback) => statesHook.onUnmounted(callback, referingObject), - memorize, - /** - * refering object that sharing some value with this object. - */ - __referingObj: referingObject, - /** - * expose provider for specified use hook. - * @param object object that contains state proxy, framework state, operating function and event binder. - * @returns provider component. - */ - exposeProvider: (object) => { - const provider = {}; - const originalStatesMap = {}; - for (const key in object) { - const value = object[key]; - const isValueFunction = shared.isFn(value); - // if it's a memorized function, don't memorize it any more, add it to provider directly. - // if it's start with `on`, that indicates it is an event binder, we should define a new function which return provider object. - // if it's a common function, add it to provider with memorize mode. - // Note that: in some situation, state is a function such as solid's signal, and state value is set to function in react, the state will be detected as a function. so we should check whether the key is in `trackedKeys` - if (isValueFunction && !referingObject.trackedKeys[key]) { - provider[key] = key.startsWith('on') - ? (...args) => { - value(...args); - // eslint-disable-next-line - return completedProvider; - } - : value.memorized - ? value - : memorize(value); - } - else { - const isFrameworkState = shared.instanceOf(value, shared.FrameworkReadableState); - if (isFrameworkState) { - originalStatesMap[key] = value.s; - } - // otherwise, it's a state proxy or framework state, add it to provider with getter mode. - shared.ObjectCls.defineProperty(provider, key, { - get: () => { - // record the key that is being tracked. - referingObject.trackedKeys[key] = shared.trueValue; - return isFrameworkState ? value.e : value; - }, - // set need to set an function, - // otherwise it will throw `TypeError: Cannot set property __referingObj of # which has only a getter` when setting value - set: shared.noop, - enumerable: shared.trueValue, - configurable: shared.trueValue - }); - } - } - const { update: nestedHookUpdate, __proxyState: nestedProxyState } = provider; - // reset the tracked keys and bingError flag, so that the nest hook providers can be initialized. - // Always track the dependencies in computed - referingObject.trackedKeys = { - ...depKeys - }; - referingObject.bindError = shared.falseValue; - const extraProvider = { - // expose referingObject automatically. - __referingObj: referingObject, - // the new updating function that can update the new states and nested hook states. - update: memorize((newStates) => { - shared.objectKeys(newStates).forEach(key => { - if (shared.includes(createdStateList, key)) { - update(newStates[key], originalStatesMap[key], key); - } - else if (key in provider && shared.isFn(nestedHookUpdate)) { - nestedHookUpdate({ - [key]: newStates[key] - }); - } - }); - }), - __proxyState: memorize((key) => { - if (shared.includes(createdStateList, key) && shared.instanceOf(object[key], shared.FrameworkReadableState)) { - // need to tag the key that is being tracked so that it can be updated with `state.v = xxx`. - referingObject.trackedKeys[key] = shared.trueValue; - return object[key]; - } - return nestedProxyState(key); - }) - }; - const completedProvider = shared.objAssign(provider, extraProvider); - return completedProvider; - }, - /** - * transform state proxies to object. - * @param states proxy array of framework states - * @param filterKey filter key of state proxy - * @returns an object that contains the states of target form - */ - objectify: (states, filterKey) => states.reduce((result, item) => { - result[item.k] = filterKey ? item[filterKey] : item; - return result; - }, {}), - transformState2Proxy: (state, key) => shared.newInstance((shared.FrameworkState), state, key, state => dehydrate(state, key, referingObject), exportState, (state, newValue) => update(newValue, state, key)) - }; -} - -const coreAssert = shared.createAssert(''); -const requestHookAssert = shared.createAssert('useRequest'); -const watcherHookAssert = shared.createAssert('useWatcher'); -const fetcherHookAssert = shared.createAssert('useFetcher'); -const coreHookAssert = (hookType) => ({ - [EnumHookType.USE_REQUEST]: requestHookAssert, - [EnumHookType.USE_WATCHER]: watcherHookAssert, - [EnumHookType.USE_FETCHER]: fetcherHookAssert -})[hookType]; -/** - * Assert whether it is a method instance - * @param methodInstance method instance - */ -const assertMethod = (assert, methodInstance) => assert(shared.instanceOf(methodInstance, alova.Method), 'expected a method instance.'); - -const KEY_SUCCESS = 'success'; -const KEY_ERROR = 'error'; -const KEY_COMPLETE = 'complete'; - -var createHook = (ht, c, eventManager, ro) => ({ - /** The method instance of the last request */ - m: shared.undefinedValue, - /** saveStatesFns */ - sf: [], - /** removeStatesFns */ - rf: [], - /** frontStates */ - fs: {}, - /** eventManager */ - em: eventManager, - /** hookType, useRequest=1, useWatcher=2, useFetcher=3 */ - ht, - /** hook config */ - c, - /** referingObject */ - ro, - /** managedStates */ - ms: {} -}); - -// base event -class AlovaEventBase { - constructor(method, args) { - this.method = method; - this.args = args; - } - clone() { - return { ...this }; - } - static spawn(method, args) { - return new AlovaEventBase(method, args); - } -} -class AlovaSuccessEvent extends AlovaEventBase { - constructor(base, data, fromCache) { - super(base.method, base.args); - this.data = data; - this.fromCache = fromCache; - } -} -class AlovaErrorEvent extends AlovaEventBase { - constructor(base, error) { - super(base.method, base.args); - this.error = error; - } -} -class AlovaCompleteEvent extends AlovaEventBase { - constructor(base, status, data, fromCache, error) { - super(base.method, base.args); - this.status = status; - this.data = data; - this.fromCache = status === 'error' ? false : fromCache; - this.error = error; - } -} -// extend event -class AlovaSSEEvent extends AlovaEventBase { - constructor(base, eventSource) { - super(base.method, base.args); - this.eventSource = eventSource; - } -} -class AlovaSSEErrorEvent extends AlovaSSEEvent { - constructor(base, error) { - super(base, base.eventSource); - this.error = error; - } -} -class AlovaSSEMessageEvent extends AlovaSSEEvent { - constructor(base, data) { - super(base, base.eventSource); - this.data = data; - } -} -/** Sq top level events */ -class SQEvent { - constructor(behavior, method, silentMethod) { - this.behavior = behavior; - this.method = method; - this.silentMethod = silentMethod; - } -} -/** Sq global events */ -class GlobalSQEvent extends SQEvent { - constructor(behavior, method, silentMethod, queueName, retryTimes) { - super(behavior, method, silentMethod); - this.queueName = queueName; - this.retryTimes = retryTimes; - } -} -class GlobalSQSuccessEvent extends GlobalSQEvent { - constructor(behavior, method, silentMethod, queueName, retryTimes, data, vDataResponse) { - super(behavior, method, silentMethod, queueName, retryTimes); - this.data = data; - this.vDataResponse = vDataResponse; - } -} -class GlobalSQErrorEvent extends GlobalSQEvent { - constructor(behavior, method, silentMethod, queueName, retryTimes, error, retryDelay) { - super(behavior, method, silentMethod, queueName, retryTimes); - this.error = error; - this.retryDelay = retryDelay; - } -} -class GlobalSQFailEvent extends GlobalSQEvent { - constructor(behavior, method, silentMethod, queueName, retryTimes, error) { - super(behavior, method, silentMethod, queueName, retryTimes); - this.error = error; - } -} -/** Sq event */ -class ScopedSQEvent extends SQEvent { - constructor(behavior, method, silentMethod, args) { - super(behavior, method, silentMethod); - this.args = args; - } -} -class ScopedSQSuccessEvent extends ScopedSQEvent { - constructor(behavior, method, silentMethod, args, data) { - super(behavior, method, silentMethod, args); - this.data = data; - } -} -class ScopedSQErrorEvent extends ScopedSQEvent { - constructor(behavior, method, silentMethod, args, error) { - super(behavior, method, silentMethod, args); - this.error = error; - } -} -class ScopedSQRetryEvent extends ScopedSQEvent { - constructor(behavior, method, silentMethod, args, retryTimes, retryDelay) { - super(behavior, method, silentMethod, args); - this.retryTimes = retryTimes; - this.retryDelay = retryDelay; - } -} -class ScopedSQCompleteEvent extends ScopedSQEvent { - constructor(behavior, method, silentMethod, args, status, data, error) { - super(behavior, method, silentMethod, args); - this.status = status; - this.data = data; - this.error = error; - } -} -class RetriableRetryEvent extends AlovaEventBase { - constructor(base, retryTimes, retryDelay) { - super(base.method, base.args); - this.retryTimes = retryTimes; - this.retryDelay = retryDelay; - } -} -class RetriableFailEvent extends AlovaErrorEvent { - constructor(base, error, retryTimes) { - super(base, error); - this.retryTimes = retryTimes; - } -} - -const defaultMiddleware = (_, next) => next(); - -const stateCache = {}; -/** - * @description Get State cache data - * @param baseURL Base URL - * @param key Request key value - * @returns Cached response data, if not returned {} - */ -const getStateCache = (namespace, key) => { - const cachedState = stateCache[namespace] || {}; - return cachedState[key] || {}; -}; -/** - * @description Set State cache data - * @param baseURL Base URL - * @param key Request key value - * @param data cache data - */ -const setStateCache = (namespace, key, data, hookInstance) => { - const cachedState = (stateCache[namespace] = stateCache[namespace] || {}); - cachedState[key] = { - s: data, - h: hookInstance - }; -}; -/** - * @description Clear State cache data - * @param baseURL Base URL - * @param key Request key value - */ -const removeStateCache = (namespace, key) => { - const cachedState = stateCache[namespace]; - if (cachedState) { - shared.deleteAttr(cachedState, key); - } -}; - -/** - * Unified processing of request logic for useRequest/useWatcher/useFetcher and other request hook functions - * @param hookInstance hook instance - * @param methodHandler Request method object or get function - * @param sendCallingArgs send function parameters - * @returns Request status - */ -function useHookToSendRequest(hookInstance, methodHandler, sendCallingArgs = []) { - const currentHookAssert = coreHookAssert(hookInstance.ht); - let methodInstance = shared.getHandlerMethod(methodHandler, currentHookAssert, sendCallingArgs); - const { fs: frontStates, ht: hookType, c: useHookConfig, ms: managedStates } = hookInstance; - const { loading: loadingState, data: dataState, error: errorState } = frontStates; - const isFetcher = hookType === EnumHookType.USE_FETCHER; - const { force: forceRequest = shared.falseValue, middleware = defaultMiddleware } = useHookConfig; - const alovaInstance = shared.getContext(methodInstance); - const { id } = alovaInstance; - // If it is a silent request, on success will be called directly after the request, on error will not be triggered, and progress will not be updated. - const methodKey = shared.getMethodInternalKey(methodInstance); - const { abortLast = shared.trueValue } = useHookConfig; - const isFirstRequest = !hookInstance.m; - hookInstance.m = methodInstance; - return (async () => { - // Initialize status data, which does not need to be loaded when pulling data, because pulling data does not require returning data. - let removeStates = shared.noop; - let saveStates = shared.noop; - let isNextCalled = shared.falseValue; - let responseHandlePromise = shared.promiseResolve(shared.undefinedValue); - let offDownloadEvent = shared.noop; - let offUploadEvent = shared.noop; - const cachedResponse = await alova.queryCache(methodInstance); - let fromCache = () => !!cachedResponse; - // Whether it is a controlled loading state. When it is true, loading will no longer be set to false in response processing. - let controlledLoading = shared.falseValue; - if (!isFetcher) { - // Store the initial state in cache for subsequent updates - saveStates = frontStates => setStateCache(id, methodKey, frontStates, hookInstance); - saveStates({ ...frontStates, ...managedStates }); - // Setting the state removal function will be passed to the effect request in the hook, and it will be set to be called when the component is unloaded. - removeStates = () => removeStateCache(id, methodKey); - } - // The middleware function next callback function allows you to modify mandatory request parameters and even replace the method instance that is about to send the request. - const guardNext = guardNextConfig => { - isNextCalled = shared.trueValue; - const { force: guardNextForceRequest = forceRequest, method: guardNextReplacingMethod = methodInstance } = guardNextConfig || {}; - const forceRequestFinally = shared.sloughConfig(guardNextForceRequest, [ - shared.newInstance((AlovaEventBase), methodInstance, sendCallingArgs) - ]); - const progressUpdater = (stage) => ({ loaded, total }) => { - frontStates[stage].v = { - loaded, - total - }; - }; - methodInstance = guardNextReplacingMethod; - // The latest controller needs to be saved every time a request is sent - shared.pushItem(hookInstance.sf, saveStates); - shared.pushItem(hookInstance.rf, removeStates); - // Loading will not be changed when the loading state is controlled - // The cache is missed, or loading needs to be set to true when forcing a request. - if (!controlledLoading) { - loadingState.v = !!forceRequestFinally || !cachedResponse; - } - // Determine whether to trigger a progress update based on the tracking status of downloading and uploading - const { downloading: enableDownload, uploading: enableUpload } = hookInstance.ro.trackedKeys; - offDownloadEvent = enableDownload ? methodInstance.onDownload(progressUpdater('downloading')) : offDownloadEvent; - offUploadEvent = enableUpload ? methodInstance.onUpload(progressUpdater('uploading')) : offUploadEvent; - responseHandlePromise = methodInstance.send(forceRequestFinally); - fromCache = () => methodInstance.fromCache || shared.falseValue; - return responseHandlePromise; - }; - // Call middleware function - const commonContext = { - method: methodInstance, - cachedResponse, - config: useHookConfig, - abort: () => methodInstance.abort() - }; - // Whether it is necessary to update the response data and call the response callback - const toUpdateResponse = () => hookType !== EnumHookType.USE_WATCHER || !abortLast || hookInstance.m === methodInstance; - const controlLoading = (control = shared.trueValue) => { - // only reset loading state in first request - if (control && isFirstRequest) { - loadingState.v = shared.falseValue; - } - controlledLoading = control; - }; - // Call middleware function - const middlewareCompletePromise = isFetcher - ? middleware({ - ...commonContext, - args: sendCallingArgs, - fetch: (methodInstance, ...args) => { - assertMethod(currentHookAssert, methodInstance); - return useHookToSendRequest(hookInstance, methodInstance, args); - }, - proxyStates: shared.omit(frontStates, 'data'), - controlLoading - }, guardNext) - : middleware({ - ...commonContext, - args: sendCallingArgs, - send: (...args) => useHookToSendRequest(hookInstance, methodHandler, args), - proxyStates: frontStates, - controlLoading - }, guardNext); - let finallyResponse = shared.undefinedValue; - const baseEvent = (AlovaEventBase).spawn(methodInstance, sendCallingArgs); - try { - // Unified processing of responses - const middlewareReturnedData = await middlewareCompletePromise; - const afterSuccess = (data) => { - // Update cached response data - if (!isFetcher) { - toUpdateResponse() && (dataState.v = data); - } - else if (hookInstance.c.updateState !== shared.falseValue) { - // Update the status in the cache, usually entered in use fetcher - const cachedState = getStateCache(id, methodKey).s; - cachedState && (cachedState.data.v = data); - } - // If the response data needs to be updated, the corresponding callback function is triggered after the request. - if (toUpdateResponse()) { - errorState.v = shared.undefinedValue; - // Loading status will no longer change to false when controlled - !controlledLoading && (loadingState.v = shared.falseValue); - hookInstance.em.emit(KEY_SUCCESS, shared.newInstance((AlovaSuccessEvent), baseEvent, data, fromCache())); - hookInstance.em.emit(KEY_COMPLETE, shared.newInstance((AlovaCompleteEvent), baseEvent, KEY_SUCCESS, data, fromCache(), shared.undefinedValue)); - } - return data; - }; - finallyResponse = - // When no data is returned or undefined is returned in the middleware, get the real response data - // Otherwise, use the returned data and no longer wait for the response promise. At this time, you also need to call the response callback. - middlewareReturnedData !== shared.undefinedValue - ? afterSuccess(middlewareReturnedData) - : isNextCalled - ? // There are two possibilities when middlewareCompletePromise is resolve - // 1. The request is normal - // 2. The request is incorrect, but the error is captured by the middleware function. At this time, the success callback will also be called, that is, afterSuccess(undefinedValue) - await shared.promiseThen(responseHandlePromise, afterSuccess, () => afterSuccess(shared.undefinedValue)) - : // If is next called is not called, no data is returned - shared.undefinedValue; - // When the next function is not called, update loading to false. - !isNextCalled && !controlledLoading && (loadingState.v = shared.falseValue); - } - catch (error) { - if (toUpdateResponse()) { - // Controls the output of error messages - errorState.v = error; - // Loading status will no longer change to false when controlled - !controlledLoading && (loadingState.v = shared.falseValue); - hookInstance.em.emit(KEY_ERROR, shared.newInstance((AlovaErrorEvent), baseEvent, error)); - hookInstance.em.emit(KEY_COMPLETE, shared.newInstance((AlovaCompleteEvent), baseEvent, KEY_ERROR, shared.undefinedValue, fromCache(), error)); - } - throw error; - } - // Unbind download and upload events after responding - offDownloadEvent(); - offUploadEvent(); - return finallyResponse; - })(); -} - -const refCurrent = (ref) => ref.current; -/** - * Create request status and uniformly process consistent logic in useRequest, useWatcher, and useFetcher - * This function will call the creation function of statesHook to create the corresponding request state. - * When the value is empty, it means useFetcher enters, and data status and cache status are not needed at this time. - * @param methodInstance request method object - * @param useHookConfig hook request configuration object - * @param initialData Initial data data - * @param immediate Whether to initiate a request immediately - * @param watchingStates The monitored status, if not passed in, call handleRequest directly. - * @param debounceDelay Delay time for request initiation - * @returns Current request status, operation function and event binding function - */ -function createRequestState(hookType, methodHandler, useHookConfig, initialData, immediate = shared.falseValue, watchingStates, debounceDelay = 0) { - var _a; - // shallow clone config object to avoid passing the same useHookConfig object which may cause vue2 state update error - useHookConfig = { ...useHookConfig }; - const { __referingObj: referingObject = { trackedKeys: {}, bindError: shared.falseValue } } = useHookConfig; - let initialLoading = !!immediate; - let cachedResponse = shared.undefinedValue; - // When sending a request immediately, you need to determine the initial loading value by whether to force the request and whether there is a cache. This has the following two benefits: - // 1. Sending the request immediately under react can save one rendering time - // 2. In the HTML rendered by SSR, the initial view is in the loading state to avoid the loading view flashing when displayed on the client. - if (immediate) { - // An error may be reported when calling the get handler method, and try/catch is required. - try { - const methodInstance = shared.getHandlerMethod(methodHandler, coreHookAssert(hookType)); - const alovaInstance = shared.getContext(methodInstance); - const l1CacheResult = alovaInstance.l1Cache.get(shared.buildNamespacedCacheKey(alovaInstance.id, shared.getMethodInternalKey(methodInstance))); - // The cache is only checked synchronously, so it does not take effect on asynchronous l1Cache adapters. - // It is recommended not to set up the asynchronous l1Cache adapter on the client side - if (l1CacheResult && !shared.instanceOf(l1CacheResult, shared.PromiseCls)) { - const [data, expireTimestamp] = l1CacheResult; - // If there is no expiration time, it means that the data will never expire. Otherwise, you need to determine whether it has expired. - if (!expireTimestamp || expireTimestamp > shared.getTime()) { - cachedResponse = data; - } - } - const forceRequestFinally = shared.sloughConfig((_a = useHookConfig.force) !== null && _a !== void 0 ? _a : shared.falseValue); - initialLoading = !!forceRequestFinally || !cachedResponse; - } - catch (_b) { } - } - const { create, effectRequest, ref, objectify, exposeProvider, transformState2Proxy } = statesHookHelper(alova.promiseStatesHook(), referingObject); - const progress = { - total: 0, - loaded: 0 - }; - // Put the externally incoming supervised states into the front states collection together - const { managedStates = {} } = useHookConfig; - const managedStatesProxy = mapObject(managedStates, (state, key) => transformState2Proxy(state, key)); - const data = create(cachedResponse !== null && cachedResponse !== void 0 ? cachedResponse : (shared.isFn(initialData) ? initialData() : initialData), 'data'); - const loading = create(initialLoading, 'loading'); - const error = create(shared.undefinedValue, 'error'); - const downloading = create({ ...progress }, 'downloading'); - const uploading = create({ ...progress }, 'uploading'); - const frontStates = objectify([data, loading, error, downloading, uploading]); - const eventManager = shared.createEventManager(); - const hookInstance = refCurrent(ref(createHook(hookType, useHookConfig, eventManager, referingObject))); - /** - * ## react ##Every time the function is executed, the following items need to be reset - */ - hookInstance.fs = frontStates; - hookInstance.em = eventManager; - hookInstance.c = useHookConfig; - hookInstance.ms = managedStatesProxy; - const hasWatchingStates = watchingStates !== shared.undefinedValue; - // Initialize request event - // Unified send request function - const handleRequest = (handler = methodHandler, sendCallingArgs) => useHookToSendRequest(hookInstance, handler, sendCallingArgs); - // only call once when multiple values changed at the same time - const onceRunner = refCurrent(ref(shared.createSyncOnceRunner())); - // Call handleRequest in a way that catches the exception - // Catching exceptions prevents exceptions from being thrown out - const wrapEffectRequest = (ro = referingObject, handler) => { - onceRunner(() => { - shared.promiseCatch(handleRequest(handler), error => { - // the error tracking indicates that the error need to throw. - if (!ro.bindError && !ro.trackedKeys.error) { - throw error; - } - }); - }); - }; - /** - * fix: #421 - * Use ref wraps to prevent react from creating new debounce function in every render - * Explicit passing is required because the context will change - */ - const debouncingSendHandler = ref(debounce((_, ro, handler) => wrapEffectRequest(ro, handler), (changedIndex) => shared.isNumber(changedIndex) ? (shared.isArray(debounceDelay) ? debounceDelay[changedIndex] : debounceDelay) : 0)); - // Do not send requests when rendering on the server side - if (!alova.globalConfigMap.ssr) { - effectRequest({ - handler: - // When `watchingStates` is an array, it indicates the watching states (including an empty array). When it is undefined, it indicates the non-watching state. - hasWatchingStates - ? (changedIndex) => debouncingSendHandler.current(changedIndex, referingObject, methodHandler) - : () => wrapEffectRequest(referingObject), - removeStates: () => shared.forEach(hookInstance.rf, fn => fn()), - saveStates: states => shared.forEach(hookInstance.sf, fn => fn(states)), - frontStates: { ...frontStates, ...managedStatesProxy }, - watchingStates, - immediate: immediate !== null && immediate !== void 0 ? immediate : shared.trueValue - }); - } - return exposeProvider({ - ...objectify([data, loading, error, downloading, uploading]), - abort: () => hookInstance.m && hookInstance.m.abort(), - /** - * Manually initiate a request by executing this method - * @param sendCallingArgs Parameters passed in when calling the send function - * @param methodInstance method object - * @param isFetcher Whether to call isFetcher - * @returns Request promise - */ - send: (sendCallingArgs, methodInstance) => handleRequest(methodInstance, sendCallingArgs), - onSuccess(handler) { - eventManager.on(KEY_SUCCESS, handler); - }, - onError(handler) { - // will not throw error when bindError is true. - // it will reset in `exposeProvider` so that ignore the error binding in custom use hooks. - referingObject.bindError = shared.trueValue; - eventManager.on(KEY_ERROR, handler); - }, - onComplete(handler) { - eventManager.on(KEY_COMPLETE, handler); - } - }); -} - -/** - * Fetch request data and cache request method object - */ -function useFetcher(config = {}) { - const props = createRequestState(EnumHookType.USE_FETCHER, shared.noop, config); - const { send } = props; - shared.deleteAttr(props, 'send'); - return shared.objAssign(props, { - /** - * Fetch data fetch will definitely send a request, and if the currently requested data has a corresponding management state, this state will be updated. - * @param matcher Method object - */ - fetch: (matcher, ...args) => { - assertMethod(fetcherHookAssert, matcher); - return send(args, matcher); - } - }); -} - -function useRequest(handler, config = {}) { - const { immediate = shared.trueValue, initialData } = config; - const props = createRequestState(EnumHookType.USE_REQUEST, handler, config, initialData, !!immediate); - const { send } = props; - return shared.objAssign(props, { - send: (...args) => send(args) - }); -} - -function useWatcher(handler, watchingStates, config = {}) { - watcherHookAssert(watchingStates && shared.len(watchingStates) > 0, 'expected at least one watching state'); - const { immediate, debounce = 0, initialData } = config; - const props = createRequestState(EnumHookType.USE_WATCHER, handler, config, initialData, !!immediate, // !!immediate means not send request immediately - watchingStates, debounce); - const { send } = props; - return shared.objAssign(props, { - send: (...args) => send(args) - }); -} - -var createSnapshotMethodsManager = (handler) => { - let methodSnapshots = {}; - return { - snapshots: () => methodSnapshots, - save(methodInstance, force = shared.falseValue) { - const key = shared.getMethodInternalKey(methodInstance); - // Because it is impossible to locate the location of the total data in the cache - // Therefore, this field is maintained redundantly here. - if (!methodSnapshots[key] || force) { - methodSnapshots[key] = { - entity: methodInstance - }; - } - }, - get: (entityOrPage) => methodSnapshots[shared.getMethodInternalKey(shared.instanceOf(entityOrPage, (alova.Method)) ? entityOrPage : handler(entityOrPage))], - remove(key) { - if (key) { - delete methodSnapshots[key]; - } - else { - methodSnapshots = {}; - } - } - }; -}; - -const paginationAssert = shared.createAssert('usePagination'); -const indexAssert = (index, rawData) => paginationAssert(shared.isNumber(index) && index < shared.len(rawData), 'index must be a number that less than list length'); -const parseSendArgs = (args) => [ - args[args.length - 2], // refreshPage - args[args.length - 1], // isRefresh - args.slice(0, args.length - 2) // send args -]; -var usePagination = (handler, config = {}) => { - const { create, computed, ref, watch, exposeProvider, objectify, __referingObj: referingObject } = statesHookHelper(alova.promiseStatesHook()); - const { preloadPreviousPage = shared.trueValue, preloadNextPage = shared.trueValue, total: totalGetter = res => res.total, data: dataGetter = res => res.data, append = shared.falseValue, initialPage = 1, initialPageSize = 10, watchingStates = [], initialData, immediate = shared.trueValue, middleware, force = shared.noop, ...others } = config; - const handlerRef = ref(handler); - const isReset = ref(shared.falseValue); // Used to control whether to reset - // The number of requests during reset. In order to prevent repeated requests during reset, use this parameter to limit requests. - const page = create(initialPage, 'page'); - const pageSize = create(initialPageSize, 'pageSize'); - const data = create((initialData ? dataGetter(initialData) || [] : []), 'data'); - const total = create(initialData ? totalGetter(initialData) : shared.undefinedValue, 'total'); - // Save snapshots of all method instances used by the current hook - const { snapshots: methodSnapshots, get: getSnapshotMethods, save: saveSnapshot, remove: removeSnapshot } = ref(createSnapshotMethodsManager(page => handlerRef.current(page, pageSize.v))).current; - const listDataGetter = (rawData) => dataGetter(rawData) || rawData; - // Initialize fetcher - const fetchStates = useFetcher({ - __referingObj: referingObject, - updateState: shared.falseValue, - force: ({ args }) => args[shared.len(args) - 1] - }); - const { loading, fetch, abort: abortFetch, onSuccess: onFetchSuccess } = fetchStates; - const fetchingRef = ref(loading); - const getHandlerMethod = (refreshPage = page.v, customArgs = []) => { - const handlerMethod = handler(refreshPage, pageSize.v, ...customArgs); - // Define unified additional names to facilitate management - saveSnapshot(handlerMethod); - return handlerMethod; - }; - // When monitoring status changes, reset page to 1 - watch(watchingStates, () => { - page.v = initialPage; - isReset.current = shared.trueValue; - }); - // Compatible with react, store functions that require proxy here - // In this way, the latest operation function can be called in the proxy function and avoid the react closure trap. - const delegationActions = ref({}); - // Calculate data, total, is last page parameters - const pageCount = computed(() => { - const totalVal = total.v; - return totalVal !== shared.undefinedValue ? Math.ceil(totalVal / pageSize.v) : shared.undefinedValue; - }, [pageSize, total], 'pageCount'); - const createDelegationAction = (actionName) => (...args) => delegationActions.current[actionName](...args); - const states = useWatcher((...args) => { - const [refreshPage, , customArgs] = parseSendArgs(args); - return getHandlerMethod(refreshPage, customArgs); - }, [...watchingStates, page.e, pageSize.e], { - __referingObj: referingObject, - immediate, - initialData, - managedStates: objectify([data, page, pageSize, total], 's'), - middleware(ctx, next) { - if (!middleware) { - return next(); - } - return middleware({ - ...ctx, - delegatingActions: { - refresh: createDelegationAction('refresh'), - insert: createDelegationAction('insert'), - remove: createDelegationAction('remove'), - replace: createDelegationAction('replace'), - reload: createDelegationAction('reload'), - getState: (stateKey) => { - const states = { - page, - pageSize, - data, - pageCount, - total, - // eslint-disable-next-line @typescript-eslint/no-use-before-define - isLastPage - }; - return states[stateKey].v; - } - } - }, next); - }, - force: event => event.args[1] || (shared.isFn(force) ? force(event) : force), - ...others - }); - const { send } = states; - const nestedData = states.__proxyState('data'); - // Determine whether data can be preloaded - const canPreload = async (payload) => { - const { rawData = nestedData.v, preloadPage, fetchMethod, forceRequest = shared.falseValue, isNextPage = shared.falseValue } = payload; - const pageCountVal = pageCount.v; - const exceedPageCount = pageCountVal - ? preloadPage > pageCountVal - : isNextPage // If it is judged to preload the next page of data and there is no page count, it is judged by whether the data volume of the last page reaches the page size. - ? shared.len(listDataGetter(rawData)) < pageSize.v - : shared.falseValue; - const isMatchPageScope = preloadPage > 0 && !exceedPageCount; - if (!isMatchPageScope) { - return shared.falseValue; - } - const { e: expireMilliseconds } = shared.getLocalCacheConfigParam(fetchMethod); - const hasCache = await alova.queryCache(fetchMethod); - // If the cache time is less than or equal to the current time, it means that the cache is not set and the data will no longer be pre-pulled at this time. - // Or there is already a cache and it is not pre-fetched. - return expireMilliseconds(shared.MEMORY) <= shared.getTime() ? shared.falseValue : forceRequest || !hasCache; - }; - // Preload next page data - const fetchNextPage = async (rawData, force, customArgs = []) => { - const nextPage = page.v + 1; - const fetchMethod = getHandlerMethod(nextPage, customArgs); - if (preloadNextPage && - (await canPreload({ - rawData, - preloadPage: nextPage, - fetchMethod, - isNextPage: shared.trueValue, - forceRequest: force - }))) { - shared.promiseCatch(fetch(fetchMethod, ...customArgs, force), shared.noop); - } - }; - // Preload previous page data - const fetchPreviousPage = async (rawData, customArgs = []) => { - const prevPage = page.v - 1; - const fetchMethod = getHandlerMethod(prevPage, customArgs); - if (preloadPreviousPage && - (await canPreload({ - rawData, - preloadPage: prevPage, - fetchMethod - }))) { - shared.promiseCatch(fetch(fetchMethod, ...customArgs, shared.undefinedValue), shared.noop); - } - }; - // If the returned data is smaller than the page size, it is considered the last page. - const isLastPage = computed(() => { - const dataRaw = nestedData.v; - if (!dataRaw) { - return shared.trueValue; - } - const statesDataVal = listDataGetter(dataRaw); - const pageVal = page.v; - const pageCountVal = pageCount.v; - const dataLen = shared.isArray(statesDataVal) ? shared.len(statesDataVal) : 0; - return pageCountVal ? pageVal >= pageCountVal : dataLen < pageSize.v; - }, [page, pageCount, nestedData, pageSize], 'isLastPage'); - // Update current page cache - const updateCurrentPageCache = async () => { - const snapshotItem = getSnapshotMethods(page.v); - if (snapshotItem) { - await alova.setCache(snapshotItem.entity, (rawData) => { - // When caching is turned off, raw data is undefined - if (rawData) { - const cachedListData = listDataGetter(rawData) || []; - shared.splice(cachedListData, 0, shared.len(cachedListData), ...data.v); - return rawData; - } - }); - } - }; - onFetchSuccess(({ method, data: rawData }) => { - // When fetch has not responded yet and the page is flipped to the page number corresponding to fetch, the list data needs to be updated manually. - const snapshotItem = getSnapshotMethods(page.v); - if (snapshotItem && shared.getMethodInternalKey(snapshotItem.entity) === shared.getMethodInternalKey(method)) { - // If data is appended, data is updated - const listData = listDataGetter(rawData); // Update data parameters - if (append) { - // The current page data needs to be replaced during pull-down loading. - const dataRaw = data.v; - const pageSizeVal = pageSize.v; - // When performing a removal operation, the number of replacements is less than pageSize, and dataRaw % pageSizeVal will be greater than 0. - // When adding a new operation, the number of replacements is equal to pageSize. At this time, dataRaw % pageSizeVal will be equal to 0. No replacement is needed at this time. - const replaceNumber = shared.len(dataRaw) % pageSizeVal; - if (replaceNumber > 0) { - const rawData = [...data.v]; - shared.splice(rawData, (page.v - 1) * pageSizeVal, replaceNumber, ...listData); - data.v = rawData; - } - } - else { - data.v = listData; - } - } - }); - const awaitResolve = ref(shared.undefinedValue); - const awaitReject = ref(shared.undefinedValue); - states - .onSuccess(({ data: rawData, args, method }) => { - const [refreshPage, isRefresh, customArgs] = parseSendArgs(args); - const { total: cachedTotal } = getSnapshotMethods(method) || {}; - const typedRawData = rawData; - total.v = cachedTotal !== shared.undefinedValue ? cachedTotal : totalGetter(typedRawData); - if (!isRefresh) { - fetchPreviousPage(typedRawData, customArgs); - fetchNextPage(typedRawData, shared.falseValue, customArgs); - } - const pageSizeVal = pageSize.v; - const listData = listDataGetter(typedRawData); // Get array - paginationAssert(shared.isArray(listData), 'Got wrong array, did you return the correct array of list in `data` function'); - // If data is appended, data is updated - if (append) { - // If it is reset, clear the data first - if (isReset.current) { - data.v = []; - } - if (refreshPage === shared.undefinedValue) { - data.v = [...data.v, ...listData]; - } - else if (refreshPage) { - const rawData = [...data.v]; - // If the page is refreshed, the data on that page is replaced. - shared.splice(rawData, (refreshPage - 1) * pageSizeVal, pageSizeVal, ...listData); - data.v = rawData; - } - } - else { - data.v = listData; - } - }) - .onSuccess(({ data }) => { - var _a; - (_a = awaitResolve.current) === null || _a === void 0 ? void 0 : _a.call(awaitResolve, data); - }) - .onError(({ error }) => { - var _a; - (_a = awaitReject.current) === null || _a === void 0 ? void 0 : _a.call(awaitReject, error); - }) - .onComplete(() => { - // Whether the request is successful or not, it must be reset is reset - isReset.current = shared.falseValue; - }); - // Get the location of a list item - const getItemIndex = (item) => { - const index = data.v.indexOf(item); - paginationAssert(index >= 0, 'item is not found in list'); - return index; - }; - const { addQueue: add2AsyncQueue, onComplete: onAsyncQueueRunComplete } = ref(shared.createAsyncQueue()).current; - /** - * Refresh the specified page number data. This function will ignore the cache and force the request to be sent. - * If no page number is passed in, the current page will be refreshed. - * If a list item is passed in, the page where the list item is located will be refreshed, which is only valid in append mode. - * @param pageOrItemPage Refreshed page number or list item - */ - const refresh = async (pageOrItemPage = page.v) => { - let refreshPage = pageOrItemPage; - let awaitPromise = shared.promiseResolve(); - if (append) { - if (!shared.isNumber(pageOrItemPage)) { - const itemIndex = getItemIndex(pageOrItemPage); - refreshPage = Math.floor(itemIndex / pageSize.v) + 1; - } - paginationAssert(refreshPage <= page.v, "refresh page can't greater than page"); - // Update current page data - awaitPromise = send(refreshPage, shared.trueValue); - } - else { - paginationAssert(shared.isNumber(refreshPage), 'unable to calculate refresh page by item in pagination mode'); - // If the number of pages is equal, refresh the current page, otherwise fetch data - awaitPromise = - refreshPage === page.v - ? send(shared.undefinedValue, shared.trueValue) - : fetch(handler(refreshPage, pageSize.v), shared.trueValue); - } - return awaitPromise; - }; - // Delete all related caches except the current page and next page of this usehook - const invalidatePaginationCache = async (all = shared.falseValue) => { - const pageVal = page.v; - const snapshotObj = methodSnapshots(); - let snapshots = shared.objectValues(snapshotObj); - if (all) { - removeSnapshot(); - } - else { - // Filter out data from the previous page, current page, and next page - const excludeSnapshotKeys = shared.mapItem(shared.filterItem([getSnapshotMethods(pageVal - 1), getSnapshotMethods(pageVal), getSnapshotMethods(pageVal + 1)], Boolean), ({ entity }) => shared.getMethodInternalKey(entity)); - snapshots = shared.mapItem(shared.filterItem(shared.objectKeys(snapshotObj), key => !shared.includes(excludeSnapshotKeys, key)), key => { - const item = snapshotObj[key]; - delete snapshotObj[key]; - return item; - }); - } - await alova.invalidateCache(shared.mapItem(snapshots, ({ entity }) => entity)); - }; - // The reason for taking it out separately is that - // No matter how many times insert, remove, or a combination of them is called synchronously, the reset operation only needs to be executed asynchronously once - const resetCache = async () => { - fetchingRef.current && abortFetch(); - // cache invalidation - await invalidatePaginationCache(); - // When the amount of data on the next page does not exceed the page size, the next page is forced to be requested. Because there is a request for sharing, the fetching needs to be performed asynchronously after interrupting the request. - const snapshotItem = getSnapshotMethods(page.v + 1); - if (snapshotItem) { - const cachedListData = listDataGetter((await alova.queryCache(snapshotItem.entity)) || {}) || []; - fetchNextPage(shared.undefinedValue, shared.len(cachedListData) < pageSize.v); - } - }; - // Unified update of total number of items - const updateTotal = (offset) => { - if (offset === 0) { - return; - } - // Update current page - const totalVal = total.v; - if (shared.isNumber(totalVal)) { - const offsetedTotal = Math.max(totalVal + offset, 0); - total.v = offsetedTotal; - const pageVal = page.v; - // Update redundant total field - shared.forEach([getSnapshotMethods(pageVal - 1), getSnapshotMethods(pageVal), getSnapshotMethods(pageVal + 1)], item => { - item && (item.total = offsetedTotal); - }); - } - }; - /** - * Insert a piece of data - * If no index is passed in, it will be inserted at the front by default. - * If a list item is passed in, it will be inserted after the list item. If the list item is not in the list data, an error will be thrown. - * @param item insert - * @param position Insert position (index) or list item - */ - const insert = (item, position = 0) => { - onAsyncQueueRunComplete(resetCache); // The cache needs to be reset at the end of execution - return add2AsyncQueue(async () => { - const index = shared.isNumber(position) ? position : getItemIndex(position) + 1; - let popItem = shared.undefinedValue; - const rawData = [...data.v]; - // Only when the number of items currently displayed is exactly a multiple of page size, you need to remove an item of data to ensure that the number of operating pages is page size. - if (shared.len(rawData) % pageSize.v === 0) { - popItem = rawData.pop(); - } - // If the insertion position is empty, it will be inserted to the front by default. - shared.splice(rawData, index, 0, item); - data.v = rawData; - updateTotal(1); - // The cache of the current page is updated synchronously - await updateCurrentPageCache(); - // If there is a pop item, put it at the head of the next page cache, consistent with the remove operation. - // In this way, the performance will be consistent when insert and remove are called synchronously. - if (popItem) { - const snapshotItem = getSnapshotMethods(page.v + 1); - if (snapshotItem) { - await alova.setCache(snapshotItem.entity, (rawData) => { - if (rawData) { - const cachedListData = listDataGetter(rawData) || []; - cachedListData.unshift(popItem); - cachedListData.pop(); - return rawData; - } - }); - } - } - }); - }; - /** - * Remove a piece of data - * If a list item is passed in, the list item will be removed. If the list item is not in the list data, an error will be thrown. - * @param position Removed index or list item - */ - const remove = (...positions) => { - onAsyncQueueRunComplete(resetCache); // The cache needs to be reset at the end of execution - return add2AsyncQueue(async () => { - const indexes = shared.mapItem(positions, position => { - const index = shared.isNumber(position) ? position : getItemIndex(position); - indexAssert(index, data.v); - return index; - }); - const pageVal = page.v; - const nextPage = pageVal + 1; - const snapshotItem = getSnapshotMethods(nextPage); - const fillingItems = []; // padding data item - if (snapshotItem) { - await alova.setCache(snapshotItem.entity, (rawData) => { - if (rawData) { - const cachedListData = listDataGetter(rawData); - // Start filling data from the head of the list on the next page - if (shared.isArray(cachedListData)) { - shared.pushItem(fillingItems, ...shared.splice(cachedListData, 0, shared.len(indexes))); - } - return rawData; - } - }); - } - const isLastPageVal = isLastPage.v; - const fillingItemsLen = shared.len(fillingItems); - let isLastEmptyPageInNonAppendMode = false; - if (fillingItemsLen > 0 || isLastPageVal) { - // Delete data at the specified index - const newListData = shared.filterItem(data.v, (_, index) => !shared.includes(indexes, index)); - // In page turning mode, if it is the last page and all items have been deleted, then turn one page forward. - isLastEmptyPageInNonAppendMode = !append && isLastPageVal && shared.len(newListData) <= 0; - if (!isLastEmptyPageInNonAppendMode && fillingItemsLen > 0) { - shared.pushItem(newListData, ...fillingItems); - } - data.v = newListData; - } - else if (fillingItemsLen <= 0 && !isLastPageVal) { - // When the last page of data is removed, there is no need to refresh - refresh(pageVal); - } - updateTotal(-shared.len(indexes)); - // The cache of the current page is updated synchronously - return updateCurrentPageCache().then(() => { - if (isLastEmptyPageInNonAppendMode) { - page.v = pageVal - 1; - } - }); - }); - }; - /** - * Replace a piece of data - * If the position passed in is a list item, this list item will be replaced. If the list item is not in the list data, an error will be thrown. - * @param item replacement - * @param position Replace position (index) or list item - */ - const replace = (item, position) => add2AsyncQueue(async () => { - paginationAssert(position !== shared.undefinedValue, 'expect specify the replace position'); - const index = shared.isNumber(position) ? position : getItemIndex(position); - indexAssert(index, data.v); - const rawData = [...data.v]; - shared.splice(rawData, index, 1, item); - data.v = rawData; - // The cache of the current page is updated synchronously - await updateCurrentPageCache(); - }); - /** - * Reload the list starting from page ${initialPage} and clear the cache - */ - const reload = async () => { - await invalidatePaginationCache(shared.trueValue); - isReset.current = shared.trueValue; - page.v === initialPage ? shared.promiseCatch(send(), shared.noop) : (page.v = initialPage); - const { resolve, reject, promise } = shared.usePromise(); - awaitResolve.current = resolve; - awaitReject.current = reject; - return promise; - }; - // Compatible with react, caches the latest operation function each time, avoiding closure traps - delegationActions.current = { - refresh, - insert, - remove, - replace, - reload - }; - /** @Returns */ - return exposeProvider({ - ...states, - ...objectify([data, page, pageCount, pageSize, total, isLastPage]), - send: (...args) => send(...args, shared.undefinedValue, shared.undefinedValue), - fetching: fetchStates.loading, - onFetchSuccess: fetchStates.onSuccess, - onFetchError: fetchStates.onError, - onFetchComplete: fetchStates.onComplete, - refresh, - insert, - remove, - replace, - reload - }); -}; - -/** - * Assert serialHandlers - * @param hookName hook name - * @param serialHandlers Serial request method acquisition function - */ -const assertSerialHandlers = (hookName, serialHandlers) => shared.createAssert(hookName)(shared.isArray(serialHandlers) && shared.len(serialHandlers) > 0, 'please use an array to represent serial requests'); -/** - * Create serial request middleware - * @param serialHandlers Serial request method acquisition function - * @param hookMiddleware use hook middleware - * @returns Serial request middleware - */ -const serialMiddleware = (serialHandlers, hookMiddleware, serialRequestMethods = []) => { - // The first handler is passed to the use hook externally and does not need to be requested again. - serialHandlers.shift(); - return ((ctx, next) => { - hookMiddleware === null || hookMiddleware === void 0 ? void 0 : hookMiddleware(ctx, () => shared.promiseResolve(shared.undefinedValue)); - ctx.controlLoading(); - const loadingState = ctx.proxyStates.loading; - loadingState.v = shared.trueValue; - let serialPromise = next(); - for (const handler of serialHandlers) { - serialPromise = shared.promiseThen(serialPromise, value => { - const methodItem = handler(value, ...ctx.args); - shared.pushItem(serialRequestMethods, methodItem); - return methodItem.send(); - }); - } - return serialPromise.finally(() => { - loadingState.v = shared.falseValue; - }); - }); -}; - -/** - * Serial request hook, each serialHandlers will receive the result of the previous request - * Applicable scenario: Serial request for a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialRequest related data and operation functions - */ -var useSerialRequest = (serialHandlers, config = {}) => { - assertSerialHandlers('useSerialRequest', serialHandlers); - // eslint-disable-next-line - const { ref, __referingObj } = statesHookHelper(alova.promiseStatesHook()); - const methods = ref([]).current; - const exposures = useRequest(serialHandlers[0], { - ...config, - __referingObj, - middleware: serialMiddleware(serialHandlers, config.middleware, methods) - }); - // Decorate the error callback function and set event.method to the instance of the error - exposures.onError = shared.decorateEvent(exposures.onError, (handler, event) => { - event.method = methods[shared.len(methods) - 1]; - handler(event); - }); - return exposures; -}; - -/** - * Serial request hook, each serialHandlers will receive the result of the previous request - * Applicable scenario: After monitoring status changes, serially request a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialRequest related data and operation functions - */ -var useSerialWatcher = (serialHandlers, watchingStates, config = {}) => { - assertSerialHandlers('useSerialWatcher', serialHandlers); - // eslint-disable-next-line - const { ref, __referingObj } = statesHookHelper(alova.promiseStatesHook()); - const methods = ref([]).current; - const exposures = useWatcher(serialHandlers[0], watchingStates, { - ...config, - __referingObj, - middleware: serialMiddleware(serialHandlers, config.middleware, methods) - }); - // Decorate the error callback function and set event.method to the instance of the error - exposures.onError = shared.decorateEvent(exposures.onError, (handler, event) => { - event.method = methods[shared.len(methods) - 1]; - handler(event); - }); - return exposures; -}; - -const STR_VALUE_OF = 'valueOf'; -const DEFAULT_QUEUE_NAME = 'default'; -const BEHAVIOR_SILENT = 'silent'; -const BEHAVIOR_QUEUE = 'queue'; -const BEHAVIOR_STATIC = 'static'; -/** - * Global virtual data collection array - * It will only be an array when the method is created, and undefined at other times - * - * Explanation: The purpose of collecting virtual data is to determine whether virtual data is used in a method instance. - * Includes the following forms: - * useSQRequest((vDataId) => createMethod({ vDataId }) //Reference function parameters - * useSQRequest(() => createMethod({ vDataId }) //Directly reference scope parameters - * - * Or even: - * function createMethod(obj) { - * return alovaInst.Get('/list', { - * params: { status: obj.vDataId ? 1 : 0 } - * }) - * } - * useSQRequest(() => createMethod(obj) //Directly reference scope parameters - * - * Ways to use dummy data include: - * 1. Directly assign values as parameters - * 2. Use dummy data id - * 3. Indirect use of virtual data, such as - * vData ? 1 : 0 - * !!vData - * vData+1 - * etc. as calculation parameters. - */ -let vDataIdCollectBasket; -const setVDataIdCollectBasket = (value) => { - vDataIdCollectBasket = value; -}; -/** - * The dependent alova instance, its storage adapter, request adapter, etc. will be used to access the SilentMethod instance and send silent submissions - */ -let dependentAlovaInstance; -const setDependentAlova = (alovaInst) => { - dependentAlovaInstance = alovaInst; -}; -/** - * Set up a custom serializer - */ -let customSerializers = {}; -const setCustomSerializers = (serializers = {}) => { - customSerializers = serializers; -}; -/** - * silentFactory status - * 0 means not started - * 1 means in progress, changed after calling bootSilentFactory - * 2 indicates that the request failed, that is, when the maximum number of requests is reached according to the retry rules, or when the retry rules are not matched, the request is changed. - */ -let silentFactoryStatus = 0; -const setSilentFactoryStatus = (status) => { - silentFactoryStatus = status; -}; -/** - * The request waiting time in silentQueue, in milliseconds (ms) - * It indicates the waiting time of the silentMethod that is about to send the request - * If not set, or set to 0, the silentMethod request is triggered immediately - * - * Tips: - * 1. When set directly, it is effective for the default queue by default. - * 2. If you need to set other queue settings, you can specify them as objects, such as: - * [ - * Indicates waiting 5000ms for the queue setting request named customName - * { name: 'customName', wait: 5000 }, - * - * //Indicates that in all queues with the prefix prefix, the request setting with method instance name xxx is set to wait 5000ms - * { name: /^prefix/, wait: silentMethod => silentMethod.entity.config.name === 'xxx' ? 5000 : 0 }, - * ] - * - * >>> It only works if the request succeeds, if it fails it will use the retry policy parameters - */ -let queueRequestWaitSetting = []; -const setQueueRequestWaitSetting = (requestWaitSetting = 0) => { - queueRequestWaitSetting = shared.isArray(requestWaitSetting) - ? requestWaitSetting - : [ - { - queue: DEFAULT_QUEUE_NAME, - wait: requestWaitSetting - } - ]; -}; -const BootEventKey = Symbol('GlobalSQBoot'); -const BeforeEventKey = Symbol('GlobalSQBefore'); -const SuccessEventKey = Symbol('GlobalSQSuccess'); -const ErrorEventKey = Symbol('GlobalSQError'); -const FailEventKey$1 = Symbol('GlobalSQFail'); -/** Global silent event management object */ -const globalSQEventManager = shared.createEventManager(); -/** Silent assert */ -const silentAssert = shared.createAssert('useSQRequest'); - -/** - * Update the status of the corresponding method - * @param method request method object - * @param handleUpdate update callback - * @returns Whether the update is successful or not. If the corresponding status is not found, the update will not be successful. - */ -async function updateState(matcher, handleUpdate) { - let updated = shared.falseValue; - // Only process the first method instance that meets the conditions. If there is no instance that meets the conditions, it will not be processed. - if (matcher) { - const { update } = alova.promiseStatesHook(); - const methodKey = shared.getMethodInternalKey(matcher); - const { id } = shared.getContext(matcher); - const { s: frontStates, h: hookInstance } = getStateCache(id, methodKey); - const updateStateCollection = shared.isFn(handleUpdate) - ? { data: handleUpdate } - : handleUpdate; - let updatedDataColumnData = shared.undefinedValue; - if (frontStates) { - // Loop through the updated data and assign it to the supervised state - shared.forEach(shared.objectKeys(updateStateCollection), stateName => { - coreAssert(stateName in frontStates, `state named \`${stateName}\` is not found`); - const targetStateProxy = frontStates[stateName]; - let updatedData = updateStateCollection[stateName](targetStateProxy.v); - // shallow clone the updatedData so that can effect in react. - updatedData = shared.isArray(updatedData) - ? [...updatedData] - : shared.isObject(updatedData) - ? { ...updatedData } - : updatedData; - // Record the updated value of the data field, used to update cached data - if (stateName === 'data') { - updatedDataColumnData = updatedData; - } - // Update directly using update without checking referring object.tracked keys - update(updatedData, frontStates[stateName].s, stateName, hookInstance.ro); - }); - updated = shared.trueValue; - } - // If data is updated, cache and persistent data need to be updated at the same time - if (updatedDataColumnData !== shared.undefinedValue) { - alova.setCache(matcher, updatedDataColumnData); - } - } - return updated; -} - -var dateSerializer = { - forward: data => (shared.instanceOf(data, Date) ? data.getTime() : shared.undefinedValue), - backward: ts => shared.newInstance(Date, ts) -}; - -var regexpSerializer = { - forward: data => (shared.instanceOf(data, RegExp) ? data.source : undefined), - backward: source => shared.newInstance(RegExp, source) -}; - -const createSerializerPerformer = (customSerializers = {}) => { - /** - * Merge built-in serializers and custom serializers - */ - const serializers = { - date: dateSerializer, - regexp: regexpSerializer, - ...customSerializers - }; - /** - * serialized data - */ - const serialize = (payload) => { - if (shared.isObject(payload)) { - payload = shared.walkObject(shared.isArray(payload) ? [...payload] : { ...payload }, value => { - let finallyApplySerializerName = shared.undefinedValue; - // Find a matching serializer and serialize the value. If not found, return the original value. - const serializedValue = shared.objectKeys(serializers).reduce((currentValue, serializerName) => { - if (!finallyApplySerializerName) { - const serializedValueItem = serializers[serializerName].forward(currentValue); - if (serializedValueItem !== shared.undefinedValue) { - finallyApplySerializerName = serializerName; - currentValue = serializedValueItem; - } - } - return currentValue; - }, value); - // You need to use the original value to judge, otherwise packaging classes such as new Number(1) will also be [object Object] - const toStringTag = shared.ObjectCls.prototype.toString.call(value); - if (toStringTag === '[object Object]') { - value = { ...value }; - } - else if (shared.isArray(value)) { - value = [...value]; - } - return finallyApplySerializerName !== shared.undefinedValue ? [finallyApplySerializerName, serializedValue] : value; - }); - } - return payload; - }; - /** - * Deserialize data - */ - const deserialize = (payload) => shared.isObject(payload) - ? shared.walkObject(payload, value => { - if (shared.isArray(value) && shared.len(value) === 2) { - const foundSerializer = serializers[value[0]]; - value = foundSerializer ? foundSerializer.backward(value[1]) : value; - } - return value; - }, shared.falseValue) - : payload; - return { - serialize, - deserialize - }; -}; - -const symbolVDataId = Symbol('vdid'); -const symbolOriginal = Symbol('original'); -const regVDataId = /\[vd:([0-9a-z]+)\]/; - -/** - * Unified vData collection function - * It will be called in the following 4 places - * 1. When accessing sub-properties - * 2. When participating in calculation and triggering [Symbol.toPrimitive] - * 3. When getting the id of vData - * 4. When getting its original value - * - * @param returnValue Return value, if it is a function then call it - * @returns collection function - */ -const vDataCollectUnified = (target) => { - const vDataId = target === null || target === void 0 ? void 0 : target[symbolVDataId]; - vDataId && vDataIdCollectBasket && (vDataIdCollectBasket[vDataId] = shared.undefinedValue); -}; -// export const vDataGetter = (key: string) => vDataCollectGetter((thisObj: any) => thisObj.__proto__[key].call(thisObj)); - -/** - * Dummy data is stringified. If the parameter is not dummy data, the original data is returned. - * @param target dummy data - * @param returnOriginalIfNotVData If it is not virtual data, return the original value. - * @returns Virtual data id or original data - */ -const stringifyVData = (target, returnOriginalIfNotVData = shared.trueValue) => { - vDataCollectUnified(target); - const vDataIdRaw = target === null || target === void 0 ? void 0 : target[symbolVDataId]; - const vDataId = vDataIdRaw ? `[vd:${vDataIdRaw}]` : shared.undefinedValue; - return vDataId || (returnOriginalIfNotVData ? target : shared.undefinedValue); -}; -/** - * Create a getter function for virtual data id collection - * @param valueReturnFn return value function - * @returns getter function - */ -function stringifyWithThis() { - return stringifyVData(this); -} - -/** - * Null wrapper class implementation - */ -const Null = function Null() { }; -Null.prototype = shared.ObjectCls.create(shared.nullValue, { - [STR_VALUE_OF]: shared.valueObject(stringifyWithThis) -}); - -/** - * Undefined wrapper class implementation - */ -const Undefined = function Undefined() { }; -Undefined.prototype = shared.ObjectCls.create(shared.nullValue, { - [STR_VALUE_OF]: shared.valueObject(stringifyWithThis) -}); - -/** - * Create dummy response data - * @returns Virtual response data proxy instance - */ -var createVirtualResponse = (structure, vDataId = shared.uuid()) => { - const transform2VData = (value, vDataIdInner = shared.uuid()) => { - if (value === shared.nullValue) { - value = shared.newInstance(Null); - } - else if (value === shared.undefinedValue) { - value = shared.newInstance(Undefined); - } - else { - const newValue = shared.ObjectCls(value); - shared.defineProperty(newValue, STR_VALUE_OF, stringifyWithThis); - shared.defineProperty(newValue, symbolOriginal, value); - value = newValue; - } - shared.defineProperty(value, symbolVDataId, vDataIdInner); - return value; - }; - const virtualResponse = transform2VData(structure, vDataId); - if (shared.isPlainObject(virtualResponse) || shared.isArray(virtualResponse)) { - shared.walkObject(virtualResponse, value => transform2VData(value)); - } - return virtualResponse; -}; - -/** - * Get original value of variable with dummy data - * This function will also perform vData collection - * @param target target value - * @param deepDehydrate Whether the depth of dehydration value - * @returns target value with primitive type - */ -const dehydrateVDataUnified = (target, deepDehydrate = shared.trueValue) => { - const dehydrateItem = (value) => { - vDataCollectUnified(value); - if (value === null || value === void 0 ? void 0 : value[symbolVDataId]) { - if (shared.instanceOf(value, Undefined)) { - value = shared.undefinedValue; - } - else if (shared.instanceOf(value, Null)) { - value = shared.nullValue; - } - else if (shared.instanceOf(value, Number) || shared.instanceOf(value, String) || shared.instanceOf(value, Boolean)) { - value = value[symbolOriginal]; - } - } - return value; - }; - const newTarget = dehydrateItem(target); - // If it is an object or array, deep traversal is required to obtain the virtual data value. - if (deepDehydrate && (shared.isObject(newTarget) || shared.isArray(newTarget))) { - shared.walkObject(newTarget, value => dehydrateItem(value)); - } - return newTarget; -}; -/** - * The version above where deepDehydrate is true - */ -var dehydrateVData = (target) => dehydrateVDataUnified(target); - -const vDataKey = '__$k'; -const vDataValueKey = '__$v'; -const getAlovaStorage = () => { - // Provide prompt when silent factory is not started - silentAssert(!!dependentAlovaInstance, 'alova instance is not found, Do you forget to set `alova` or call `bootSilentFactory`?'); - return dependentAlovaInstance.l2Cache; -}; -let serializerPerformer = shared.undefinedValue; -const silentMethodIdQueueMapStorageKey = 'alova.SQ'; // Queue collection cache key composed of Silent method instance id -const silentMethodStorageKeyPrefix = 'alova.SM.'; // silentMethod instance cache key prefix -/** - * Persistence of data collections with dummy data and serializable data - * @param key persistence key - * @param payload Persistent data - */ -const storageSetItem = async (key, payload) => { - const storage = getAlovaStorage(); - if (shared.isObject(payload)) { - payload = shared.walkObject(shared.isArray(payload) ? [...payload] : { ...payload }, (value, key, parent) => { - var _a; - if (key === vDataValueKey && parent[vDataKey]) { - return value; - } - // If a silent method instance is serialized, the alova instance is filtered out - if (key === 'context' && ((_a = value === null || value === void 0 ? void 0 : value.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'Alova') { - return shared.undefinedValue; - } - const vDataId = value === null || value === void 0 ? void 0 : value[symbolVDataId]; - let primitiveValue = dehydrateVDataUnified(value, shared.falseValue); - // You need to use the original value to judge, otherwise packaging classes such as new Number(1) will also be [object Object] - const toStringTag = shared.globalToString(primitiveValue); - if (toStringTag === '[object Object]') { - value = { ...value }; - primitiveValue = {}; - } - else if (shared.isArray(value)) { - value = [...value]; - primitiveValue = []; - } - if (vDataId) { - const valueWithVData = { - [vDataKey]: vDataId, - // For objects and arrays, all their internal properties will be put to the outside through `...value`, so the internal ones do not need to be traversed and converted. - // Therefore, empty the array or object to avoid repeated conversions and contamination of the original object. - [vDataValueKey]: primitiveValue, - ...value - }; - // If it is a string type, there will be items like arrays such as 0, 1, and 2 as subscripts and values as characters, and they need to be filtered out. - if (shared.instanceOf(value, String)) { - for (let i = 0; i < shared.len(value); i += 1) { - valueWithVData === null || valueWithVData === void 0 ? true : delete valueWithVData[i]; - } - } - // If it is converted into virtual data, the converted value is assigned to it internally, and is uniformly processed by value in the following logic. - value = valueWithVData; - } - return value; - }); - } - serializerPerformer = serializerPerformer || createSerializerPerformer(customSerializers); - await storage.set(key, serializerPerformer.serialize(payload)); -}; -/** - * Take out the persistent data and convert the data into virtual data and serialized data - * @param key Key to persistent data - */ -const storageGetItem = async (key) => { - const storagedResponse = await getAlovaStorage().get(key); - serializerPerformer = serializerPerformer || createSerializerPerformer(customSerializers); - return shared.isObject(storagedResponse) - ? shared.walkObject(serializerPerformer.deserialize(storagedResponse), value => { - // Convert virtual data format back to virtual data instance - if (shared.isObject(value) && (value === null || value === void 0 ? void 0 : value[vDataKey])) { - const vDataId = value[vDataKey]; - const vDataValue = createVirtualResponse(value[vDataValueKey], vDataId); - shared.forEach(shared.objectKeys(value), key => { - if (!shared.includes([vDataKey, vDataValueKey], key)) { - vDataValue[key] = value[key]; - } - }); - value = vDataValue; - } - return value; - }, shared.falseValue) - : storagedResponse; -}; -/** - * Remove persistent data - * @param key Key to persistent data - */ -const storageRemoveItem = async (key) => { - await getAlovaStorage().remove(key); -}; - -/** - * Serialize and save silentMethod instance - * @param silentMethodInstance silentMethod instance - */ -const persistSilentMethod = (silentMethodInstance) => storageSetItem(silentMethodStorageKeyPrefix + silentMethodInstance.id, silentMethodInstance); -/** - * Put the configuration information of silent request into the corresponding storage - * Logic: Construct a key and use this key to put the configuration information of the silent method into the corresponding storage, and then store the key in the unified management key storage. - * @param silentMethod SilentMethodInstance - * @param queue Operation queue name - */ -const push2PersistentSilentQueue = async (silentMethodInstance, queueName) => { - await persistSilentMethod(silentMethodInstance); - // Save the silent method instance id to queue storage - const silentMethodIdQueueMap = ((await storageGetItem(silentMethodIdQueueMapStorageKey)) || - {}); - const currentQueue = (silentMethodIdQueueMap[queueName] = silentMethodIdQueueMap[queueName] || []); - shared.pushItem(currentQueue, silentMethodInstance.id); - await storageSetItem(silentMethodIdQueueMapStorageKey, silentMethodIdQueueMap); -}; -/** - * Remove or replace silentMethod instances in the cache - * @param queue Operation queue name - * @param targetSilentMethodId Target silentMethod instance id - * @param newSilentMethod The new silentMethod instance to replace. If not passed, it means deleted. - */ -const spliceStorageSilentMethod = async (queueName, targetSilentMethodId, newSilentMethod) => { - // Remove the silent method instance id from the queue - const silentMethodIdQueueMap = ((await storageGetItem(silentMethodIdQueueMapStorageKey)) || - {}); - const currentQueue = silentMethodIdQueueMap[queueName] || []; - const index = currentQueue.findIndex(id => id === targetSilentMethodId); - if (index >= 0) { - if (newSilentMethod) { - shared.splice(currentQueue, index, 1, newSilentMethod.id); - await persistSilentMethod(newSilentMethod); - } - else { - shared.splice(currentQueue, index, 1); - } - await storageRemoveItem(silentMethodStorageKeyPrefix + targetSilentMethodId); - // Delete this queue when it is empty - shared.len(currentQueue) <= 0 && delete silentMethodIdQueueMap[queueName]; - if (shared.len(shared.objectKeys(silentMethodIdQueueMap)) > 0) { - await storageSetItem(silentMethodIdQueueMapStorageKey, silentMethodIdQueueMap); - } - else { - // Remove the queue collection when it is empty - await storageRemoveItem(silentMethodIdQueueMapStorageKey); - } - } -}; - -/** Silent method queue collection */ -let silentQueueMap = {}; -/** - * Merge queueMap into silentMethod queue collection - * @param queueMap silentMethod queue collection - */ -const merge2SilentQueueMap = (queueMap) => { - shared.forEach(shared.objectKeys(queueMap), targetQueueName => { - const currentQueue = (silentQueueMap[targetQueueName] = silentQueueMap[targetQueueName] || []); - shared.pushItem(currentQueue, ...queueMap[targetQueueName]); - }); -}; -/** - * Deeply traverse the target data and replace dummy data with real data - * @param target target data - * @param vDataResponse Collection of dummy data and real data - * @returns Is there any replacement data? - */ -const deepReplaceVData = (target, vDataResponse) => { - // Search for a single value and replace a dummy data object or dummy data id with an actual value - const replaceVData = (value) => { - const vData = stringifyVData(value); - // If directly a dummy data object and in a vDataResponse, replace the Map with the value in the vDataResponse - // If it is a string, it may contain virtual data id and in vDataResponse, it also needs to be replaced with the actual value Map - // The virtual data not in this vDataResponse will remain unchanged. It may be the virtual data Map requested next time. - if (vData in vDataResponse) { - return vDataResponse[vData]; - } - if (shared.isString(value)) { - return value.replace(shared.newInstance(shared.RegExpCls, regVDataId.source, 'g'), mat => mat in vDataResponse ? vDataResponse[mat] : mat); - } - return value; - }; - if (shared.isObject(target) && !stringifyVData(target, shared.falseValue)) { - shared.walkObject(target, replaceVData); - } - else { - target = replaceVData(target); - } - return target; -}; -/** - * Update the method instance in the queue and replace the dummy data with actual data - * @param vDataResponse A collection of virtual IDs and corresponding real data - * @param targetQueue target queue - */ -const updateQueueMethodEntities = (vDataResponse, targetQueue) => shared.PromiseCls.all(shared.mapItem(targetQueue, async (silentMethodItem) => { - // Traverse the entity object deeply. If virtual data or virtual data ID is found, replace it with actual data. - deepReplaceVData(silentMethodItem.entity, vDataResponse); - // If the method instance is updated, re-persist this silent method instance - silentMethodItem.cache && (await persistSilentMethod(silentMethodItem)); -})); -/** - * Replace dummy data with response data - * @param response real response data - * @param virtualResponse dummy response data - * @returns The corresponding real data set composed of virtual data id - */ -const replaceVirtualResponseWithResponse = (virtualResponse, response) => { - let vDataResponse = {}; - const vDataId = stringifyVData(virtualResponse, shared.falseValue); - vDataId && (vDataResponse[vDataId] = response); - if (shared.isObject(virtualResponse)) { - for (const i in virtualResponse) { - vDataResponse = { - ...vDataResponse, - ...replaceVirtualResponseWithResponse(virtualResponse[i], response === null || response === void 0 ? void 0 : response[i]) - }; - } - } - return vDataResponse; -}; -/** - * Start the SilentMethod queue - * 1. Silent submission will be put into the queue and requests will be sent in order. Only after the previous request responds will it continue to send subsequent requests. - * 2. The number of retries is only triggered when there is no response. If the server responds incorrectly or is disconnected, it will not retry. - * 3. When the number of retries is reached and still fails, when nextRound (next round) is set, delay the time specified by nextRound and then request again, otherwise it will try again after refreshing. - * 4. If there is resolveHandler and rejectHandler, they will be called after the request is completed (whether successful or failed) to notify the corresponding request to continue responding. - * - * @param queue SilentMethodqueue - */ -const setSilentMethodActive = (silentMethodInstance, active) => { - if (active) { - silentMethodInstance.active = active; - } - else { - delete silentMethodInstance.active; - } -}; -const defaultBackoffDelay = 1000; -const bootSilentQueue = (queue, queueName) => { - /** - * The callback function is controlled by waiting parameters according to the request. If it is not set or is less than or equal to 0, it will be triggered immediately. - * @param queueName queue name - * @param callback callback function - */ - const emitWithRequestDelay = (queueName) => { - const nextSilentMethod = queue[0]; - if (nextSilentMethod) { - const targetSetting = queueRequestWaitSetting.find(({ queue }) => shared.instanceOf(queue, shared.RegExpCls) ? shared.regexpTest(queue, queueName) : queue === queueName); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - const callback = () => queue[0] && silentMethodRequest(queue[0]); - const delay = (targetSetting === null || targetSetting === void 0 ? void 0 : targetSetting.wait) ? shared.sloughConfig(targetSetting.wait, [nextSilentMethod, queueName]) : 0; - delay && delay > 0 ? shared.setTimeoutFn(callback, delay) : callback(); - } - }; - /** - * Run a single silentMethod instance - * @param silentMethodInstance silentMethod instance - * @param retryTimes Number of retries - */ - const silentMethodRequest = (silentMethodInstance, retryTimes = 0) => { - // Set the current silent method instance to active status - setSilentMethodActive(silentMethodInstance, shared.trueValue); - const { cache, id, behavior, entity, retryError = /.*/, maxRetryTimes = 0, backoff = { delay: defaultBackoffDelay }, resolveHandler = shared.noop, rejectHandler = shared.noop, emitter: methodEmitter, handlerArgs = [], virtualResponse, force } = silentMethodInstance; - // Trigger pre-request event - globalSQEventManager.emit(BeforeEventKey, shared.newInstance((GlobalSQEvent), behavior, entity, silentMethodInstance, queueName, retryTimes)); - shared.promiseThen(entity.send(force), async (data) => { - // The request is successful, remove the successful silent method, and continue with the next request - shared.shift(queue); - // If the request is successful, remove the successful silent method instance from storage and continue with the next request. - cache && (await spliceStorageSilentMethod(queueName, id)); - // If there is a resolve handler, call it to notify the outside - resolveHandler(data); - // Only when there is a virtualResponse, virtual data is traversed and replaced, and global events are triggered. - // Generally, it is silent behavior, but queue behavior is not required. - if (behavior === BEHAVIOR_SILENT) { - // Replace dummy data in subsequent method instances in the queue with real data - // Only after unlocking can you access the hierarchical structure of virtualResponse normally. - const vDataResponse = replaceVirtualResponseWithResponse(virtualResponse, data); - const { targetRefMethod, updateStates } = silentMethodInstance; // It is accurate to obtain it in real time - // If this silentMethod has targetRefMethod, call updateState again to update the data - // This is an implementation of delayed data updates - if (shared.instanceOf(targetRefMethod, alova.Method) && updateStates && shared.len(updateStates) > 0) { - const updateStateCollection = {}; - shared.forEach(updateStates, stateName => { - // After the request is successful, replace the data with dummy data with real data - updateStateCollection[stateName] = dataRaw => deepReplaceVData(dataRaw, vDataResponse); - }); - const updated = updateState(targetRefMethod, updateStateCollection); - // If the status modification is unsuccessful, modify the cached data. - if (!updated) { - await alova.setCache(targetRefMethod, (dataRaw) => deepReplaceVData(dataRaw, vDataResponse)); - } - } - // Perform dummy data replacement on subsequent silent method instances of the current queue - await updateQueueMethodEntities(vDataResponse, queue); - // Trigger global success event - globalSQEventManager.emit(SuccessEventKey, shared.newInstance((GlobalSQSuccessEvent), behavior, entity, silentMethodInstance, queueName, retryTimes, data, vDataResponse)); - } - // Set to inactive state - setSilentMethodActive(silentMethodInstance, shared.falseValue); - // Continue to the next silent method processing - emitWithRequestDelay(queueName); - }, reason => { - if (behavior !== BEHAVIOR_SILENT) { - // When the behavior is not silent and the request fails, rejectHandler is triggered. - // and removed from the queue and will not be retried. - shared.shift(queue); - rejectHandler(reason); - } - else { - // Each request error will trigger an error callback - const runGlobalErrorEvent = (retryDelay) => globalSQEventManager.emit(ErrorEventKey, shared.newInstance((GlobalSQErrorEvent), behavior, entity, silentMethodInstance, queueName, retryTimes, reason, retryDelay)); - // In silent behavior mode, determine whether retry is needed - // Retry is only effective when the response error matches the retryError regular match - const { name: errorName = '', message: errorMsg = '' } = reason || {}; - let regRetryErrorName; - let regRetryErrorMsg; - if (shared.instanceOf(retryError, RegExp)) { - regRetryErrorMsg = retryError; - } - else if (shared.isObject(retryError)) { - regRetryErrorName = retryError.name; - regRetryErrorMsg = retryError.message; - } - const matchRetryError = (regRetryErrorName && shared.regexpTest(regRetryErrorName, errorName)) || - (regRetryErrorMsg && shared.regexpTest(regRetryErrorMsg, errorMsg)); - // If there are still retry times, try again - if (retryTimes < maxRetryTimes && matchRetryError) { - // The next retry times need to be used to calculate the delay time, so +1 is needed here. - const retryDelay = shared.delayWithBackoff(backoff, retryTimes + 1); - runGlobalErrorEvent(retryDelay); - shared.setTimeoutFn(() => { - retryTimes += 1; - silentMethodRequest(silentMethodInstance, retryTimes); - methodEmitter.emit('retry', shared.newInstance((ScopedSQRetryEvent), behavior, entity, silentMethodInstance, handlerArgs, retryTimes, retryDelay)); - }, - // When there are still retry times, use timeout as the next request time. - retryDelay); - } - else { - setSilentFactoryStatus(2); - runGlobalErrorEvent(); - // When the number of failures is reached, or the error message does not match the retry, the failure callback is triggered. - methodEmitter.emit('fallback', shared.newInstance((ScopedSQErrorEvent), behavior, entity, silentMethodInstance, handlerArgs, reason)); - globalSQEventManager.emit(FailEventKey$1, shared.newInstance((GlobalSQFailEvent), behavior, entity, silentMethodInstance, queueName, retryTimes, reason)); - } - } - // Set to inactive state - setSilentMethodActive(silentMethodInstance, shared.falseValue); - }); - }; - emitWithRequestDelay(queueName); -}; -/** - * Put a new silentMethod instance into the queue - * @param silentMethodInstance silentMethod instance - * @param cache Does silentMethod have cache? - * @param targetQueueName target queue name - * @param onBeforePush Events before silentMethod instance push - */ -const pushNewSilentMethod2Queue = async (silentMethodInstance, cache, targetQueueName = DEFAULT_QUEUE_NAME, onBeforePush = () => []) => { - silentMethodInstance.cache = cache; - const currentQueue = (silentQueueMap[targetQueueName] = - silentQueueMap[targetQueueName] || []); - const isNewQueue = shared.len(currentQueue) <= 0; - const beforePushReturns = await Promise.all(onBeforePush()); - const isPush2Queue = !beforePushReturns.some(returns => returns === shared.falseValue); - // Under silent behavior, if there is no fallback event callback bound, it will be persisted. - // If false is returned in onBeforePushQueue, it will no longer be placed in the queue. - if (isPush2Queue) { - cache && (await push2PersistentSilentQueue(silentMethodInstance, targetQueueName)); - shared.pushItem(currentQueue, silentMethodInstance); - // If it is a new queue and the status is started, execute it - isNewQueue && silentFactoryStatus === 1 && bootSilentQueue(currentQueue, targetQueueName); - } - return isPush2Queue; -}; - -/** - * Locate the location of the silentMethod instance - * @param silentMethodInstance silentMethod instance - */ -const getBelongQueuePosition = (silentMethodInstance) => { - let queue = shared.undefinedValue; - let queueName = ''; - let position = 0; - for (const queueNameLoop in silentQueueMap) { - position = silentQueueMap[queueNameLoop].indexOf(silentMethodInstance); - if (position >= 0) { - queue = silentQueueMap[queueNameLoop]; - queueName = queueNameLoop; - break; - } - } - return [queue, queueName, position]; -}; -/** - * silentMethod instance - * Requests that need to enter silentQueue will be packaged into silentMethod instances, which will carry various parameters of the request strategy. - */ -class SilentMethod { - constructor(entity, behavior, emitter, id = shared.uuid(), force, retryError, maxRetryTimes, backoff, resolveHandler, rejectHandler, handlerArgs, vDatas) { - const thisObj = this; - thisObj.entity = entity; - thisObj.behavior = behavior; - thisObj.id = id; - thisObj.emitter = emitter; - thisObj.force = !!force; - thisObj.retryError = retryError; - thisObj.maxRetryTimes = maxRetryTimes; - thisObj.backoff = backoff; - thisObj.resolveHandler = resolveHandler; - thisObj.rejectHandler = rejectHandler; - thisObj.handlerArgs = handlerArgs; - thisObj.vDatas = vDatas; - } - /** - * Allow cache-time persistent updates to the current instance - */ - async save() { - this.cache && (await persistSilentMethod(this)); - } - /** - * Replace the current instance with a new silentMethod instance in the queue - * If there is a persistent cache, the cache will also be updated. - * @param newSilentMethod new silentMethod instance - */ - async replace(newSilentMethod) { - const targetSilentMethod = this; - silentAssert(newSilentMethod.cache === targetSilentMethod.cache, 'the cache of new silentMethod must equal with this silentMethod'); - const [queue, queueName, position] = getBelongQueuePosition(targetSilentMethod); - if (queue) { - shared.splice(queue, position, 1, newSilentMethod); - targetSilentMethod.cache && (await spliceStorageSilentMethod(queueName, targetSilentMethod.id, newSilentMethod)); - } - } - /** - * Remove the current instance. If there is persistent data, it will also be removed synchronously. - */ - async remove() { - const targetSilentMethod = this; - const [queue, queueName, position] = getBelongQueuePosition(targetSilentMethod); - if (queue) { - shared.splice(queue, position, 1); - targetSilentMethod.cache && (await spliceStorageSilentMethod(queueName, targetSilentMethod.id)); - } - } - /** - * Set the method instance corresponding to the delayed update status and the corresponding status name - * It will find the corresponding status data and update vData to the actual data after responding to this silentMethod - * - * @param method method instance - * @param updateStateName Updated status name, the default is data, you can also set multiple - */ - setUpdateState(method, updateStateName = 'data') { - if (method) { - this.targetRefMethod = method; - this.updateStates = shared.isArray(updateStateName) ? updateStateName : [updateStateName]; - } - } -} - -/** - * Deserialize the silentMethod instance according to the name of the serializer. - * @param methodInstance Request method instance - * @returns Request method instance - */ -var convertPayload2SilentMethod = (payload) => { - const { id, behavior, entity, retryError, maxRetryTimes, backoff, resolveHandler, rejectHandler, handlerArgs, targetRefMethod, force } = payload; - // Method class instantiation - const deserializeMethod = (methodPayload) => { - const { type, url, config, data } = methodPayload; - return shared.newInstance(alova.Method, type, dependentAlovaInstance, url, config, data); - }; - const silentMethodInstance = shared.newInstance(SilentMethod, deserializeMethod(entity), behavior, shared.createEventManager(), id, force, retryError, maxRetryTimes, backoff, resolveHandler, rejectHandler, handlerArgs); - silentMethodInstance.cache = shared.trueValue; - // Target ref method deserialization - if (targetRefMethod) { - silentMethodInstance.targetRefMethod = deserializeMethod(targetRefMethod); - } - // Put extra content on the silent method instance - shared.forEach(shared.objectKeys(payload), key => { - if (!shared.includes([ - 'id', - 'behavior', - 'emitter', - 'entity', - 'retryError', - 'maxRetryTimes', - 'backoff', - 'resolveHandler', - 'rejectHandler', - 'handlerArgs', - 'targetRefMethod', - 'force' - ], key)) { - silentMethodInstance[key] = payload[key]; - } - }); - return silentMethodInstance; -}; - -/** - * Load silent queue data from storage - * @returns All queue data - */ -var loadSilentQueueMapFromStorage = async () => { - const silentMethodIdQueueMap = ((await storageGetItem(silentMethodIdQueueMapStorageKey)) || - {}); - const silentQueueMap = {}; - const readingPromises = []; - shared.forEach(shared.objectKeys(silentMethodIdQueueMap), queueName => { - const currentQueue = (silentQueueMap[queueName] = silentQueueMap[queueName] || []); - shared.pushItem(readingPromises, ...shared.mapItem(silentMethodIdQueueMap[queueName], async (silentMethodId) => { - const serializedSilentMethodPayload = await storageGetItem(silentMethodStorageKeyPrefix + silentMethodId); - serializedSilentMethodPayload && - shared.pushItem(currentQueue, convertPayload2SilentMethod(serializedSilentMethodPayload)); - })); - }); - await shared.PromiseCls.all(readingPromises); - return silentQueueMap; -}; - -/** - * Bind silentSubmit startup event - * @param {SilentSubmitBootHandler} handler event callback function - * @returns unbind function - */ -const onSilentSubmitBoot = (handler) => globalSQEventManager.on(BootEventKey, handler); -/** - * Bind silentSubmit success event - * @param {SilentSubmitSuccessHandler} handler event callback function - * @returns unbind function - */ -const onSilentSubmitSuccess = (handler) => globalSQEventManager.on(SuccessEventKey, handler); -/** - * Bind silentSubmit error event - * Every time there is a request error, an error callback is triggered. - * @param {SilentSubmitErrorHandler} handler event callback function - * @returns unbind function - */ -const onSilentSubmitError = (handler) => globalSQEventManager.on(ErrorEventKey, handler); -/** - * Binding silentSubmit failure event - * The failure event will be triggered when the maximum number of requests is reached, or when the error message does not match - * @param {SilentSubmitFailHandler} handler event callback function - * @returns unbind function - */ -const onSilentSubmitFail = (handler) => globalSQEventManager.on(FailEventKey$1, handler); -/** - * Bind silentSubmit to initiate a pre-request event - * @param {BeforeSilentSubmitHandler} handler event callback function - * @returns unbind function - */ -const onBeforeSilentSubmit = (handler) => globalSQEventManager.on(BeforeEventKey, handler); -/** - * Start silent submission, which will load the silent method in the cache and start silent submission - * If no delay time is passed in, the sync starts immediately - * @param {SilentFactoryBootOptions} options Delay in milliseconds - */ -const bootSilentFactory = (options) => { - if (silentFactoryStatus === 0) { - const { alova, delay = 500 } = options; - setDependentAlova(alova); - setCustomSerializers(options.serializers); - setQueueRequestWaitSetting(options.requestWait); - shared.setTimeoutFn(async () => { - // Delayed loading puts the page’s queue at the front - merge2SilentQueueMap(await loadSilentQueueMapFromStorage()); - // Loop start queue silent submission - // Multiple queues are executed in parallel - shared.forEach(shared.objectKeys(silentQueueMap), queueName => { - bootSilentQueue(silentQueueMap[queueName], queueName); - }); - setSilentFactoryStatus(1); // Set status to Started - globalSQEventManager.emit(BootEventKey, shared.undefinedValue); - }, delay); - } -}; - -/** - * A global silentMethod instance that will have a value from before the first success event is triggered to after the last success event is triggered (synchronization period) - * In this way, the current silentMethod instance can be obtained in updateStateEffect in onSuccess. - */ -let currentSilentMethod = shared.undefinedValue; -/** - * Create SilentQueue middleware function - * @param config Configuration object - * @returns middleware function - */ -var createSilentQueueMiddlewares = (handler, config) => { - const { behavior = 'queue', queue = DEFAULT_QUEUE_NAME, retryError, maxRetryTimes, backoff } = config || {}; - const eventEmitter = shared.createEventManager(); - let handlerArgs; - let behaviorFinally; - let queueFinally = DEFAULT_QUEUE_NAME; - let forceRequest = shared.falseValue; - let silentMethodInstance; - /** - * method instance creation function - * @param args Call the function passed in by send - * @returns method instance - */ - const createMethod = (...args) => { - silentAssert(shared.isFn(handler), 'method handler must be a function. eg. useSQRequest(() => method)'); - setVDataIdCollectBasket({}); - handlerArgs = args; - return handler(...args); - }; - // Decorate success/error/complete event - const decorateRequestEvent = (requestExposure) => { - // Set event callback decorator - requestExposure.onSuccess = shared.decorateEvent(requestExposure.onSuccess, (handler, event) => { - currentSilentMethod = silentMethodInstance; - handler(shared.newInstance((ScopedSQSuccessEvent), behaviorFinally, event.method, silentMethodInstance, event.args, event.data)); - }); - requestExposure.onError = shared.decorateEvent(requestExposure.onError, (handler, event) => { - handler(shared.newInstance((ScopedSQErrorEvent), behaviorFinally, event.method, silentMethodInstance, event.args, event.error)); - }); - requestExposure.onComplete = shared.decorateEvent(requestExposure.onComplete, (handler, event) => { - handler(shared.newInstance((ScopedSQCompleteEvent), behaviorFinally, event.method, silentMethodInstance, event.args, event.status, event.data, event.error)); - }); - }; - /** - * middleware function - * @param context Request context, containing request-related values - * @param next continue executing function - * @returns Promise object - */ - const middleware = ({ method, args, cachedResponse, proxyStates, config }, next) => { - const { silentDefaultResponse, vDataCaptured, force = shared.falseValue } = config; - // Because the behavior return value may change, it should be called for each request to re-obtain the return value. - const baseEvent = AlovaEventBase.spawn(method, args); - behaviorFinally = shared.sloughConfig(behavior, [baseEvent]); - queueFinally = shared.sloughConfig(queue, [baseEvent]); - forceRequest = shared.sloughConfig(force, [baseEvent]); - // Empty temporary collection variables - // They need to be cleared before returning - const resetCollectBasket = () => { - setVDataIdCollectBasket((handlerArgs = shared.undefinedValue)); - }; - // If v data captured is set, first determine whether the request-related data contains virtual data. - if (shared.isFn(vDataCaptured)) { - let hasVData = vDataIdCollectBasket && shared.len(shared.objectKeys(vDataIdCollectBasket)) > 0; - if (!hasVData) { - const { url, data } = method; - const { params, headers } = shared.getConfig(method); - shared.walkObject({ url, params, data, headers }, value => { - if (!hasVData && (stringifyVData(value, shared.falseValue) || shared.regexpTest(regVDataId, value))) { - hasVData = shared.trueValue; - } - return value; - }); - } - // If v data captured has return data, use it as the response data, otherwise continue the request - const customResponse = hasVData ? vDataCaptured(method) : shared.undefinedValue; - if (customResponse !== shared.undefinedValue) { - resetCollectBasket(); // Reset when captured by v data captured - return shared.promiseResolve(customResponse); - } - } - if (behaviorFinally !== BEHAVIOR_STATIC) { - // Wait for the method in the queue to complete execution - const createSilentMethodPromise = () => { - const queueResolvePromise = shared.newInstance(shared.PromiseCls, (resolveHandler, rejectHandler) => { - silentMethodInstance = shared.newInstance((SilentMethod), method, behaviorFinally, eventEmitter, shared.undefinedValue, !!forceRequest, retryError, maxRetryTimes, backoff, resolveHandler, rejectHandler, handlerArgs, vDataIdCollectBasket && shared.objectKeys(vDataIdCollectBasket)); - resetCollectBasket(); // Reset when Behavior is queue and silent - }); - // On before push and on pushed events are bound synchronously, so they need to be queued asynchronously to trigger the event normally. - shared.promiseThen(shared.promiseResolve(shared.undefinedValue), async () => { - const createPushEvent = () => shared.newInstance((ScopedSQEvent), behaviorFinally, method, silentMethodInstance, args); - // Put the silent method into the queue and persist it - const isPushed = await pushNewSilentMethod2Queue(silentMethodInstance, - // After the onFallback event is bound, even the silent behavior mode is no longer stored. - // onFallback will be called synchronously, so it needs to be determined asynchronously whether there are fallbackHandlers - shared.len(eventEmitter.eventMap.fallback || []) <= 0 && behaviorFinally === BEHAVIOR_SILENT, queueFinally, - // Execute the callback before putting it into the queue. If false is returned, it will prevent putting it into the queue. - () => eventEmitter.emit('beforePushQueue', createPushEvent())); - // Only after putting it into the queue, the callback after putting it into the queue will be executed. - isPushed && eventEmitter.emit('pushedQueue', createPushEvent()); - }); - return queueResolvePromise; - }; - if (behaviorFinally === BEHAVIOR_QUEUE) { - // Forced request, or loading status needs to be updated when cache is hit - const needSendRequest = forceRequest || !cachedResponse; - if (needSendRequest) { - // Manually set to true - proxyStates.loading.v = shared.trueValue; - } - // When using the cache, use the cache directly, otherwise enter the request queue - return needSendRequest ? createSilentMethodPromise() : shared.promiseThen(shared.promiseResolve(cachedResponse)); - } - const silentMethodPromise = createSilentMethodPromise(); - // Create virtual response data in silent mode. Virtual response data can generate arbitrary virtual data. - const virtualResponse = (silentMethodInstance.virtualResponse = createVirtualResponse(shared.isFn(silentDefaultResponse) ? silentDefaultResponse() : shared.undefinedValue)); - shared.promiseThen(silentMethodPromise, realResponse => { - // Update after obtaining real data - proxyStates.data.v = realResponse; - }); - // In Silent mode, the virtual response value is returned immediately, and then updated when the real data is returned. - return shared.promiseResolve(virtualResponse); - } - resetCollectBasket(); // Reset when Behavior is static - return next(); - }; - return { - c: createMethod, - m: middleware, - d: decorateRequestEvent, - // event binding function - b: { - /** - * Bind fallback event - * @param handler Fallback event callback - */ - onFallback: (handler) => { - eventEmitter.on('fallback', handler); - }, - /** - * Event before binding to queue - * @param handler Event callback before enqueuing - */ - onBeforePushQueue: (handler) => { - eventEmitter.on('beforePushQueue', handler); - }, - /** - * Event after binding to queue - * @param handler Event callback after being queued - */ - onPushedQueue: (handler) => { - eventEmitter.on('pushedQueue', handler); - }, - /** - * retry event - * @param handler Retry event callback - */ - onRetry: (handler) => { - eventEmitter.on('retry', handler); - } - } - }; -}; - -function useSQRequest(handler, config = {}) { - const { exposeProvider, __referingObj: referingObj } = statesHookHelper(alova.promiseStatesHook()); - const { middleware = shared.noop } = config; - const { c: methodCreateHandler, m: silentMiddleware, b: binders, d: decorateEvent } = createSilentQueueMiddlewares(handler, config); - const states = useRequest(methodCreateHandler, { - ...config, - __referingObj: referingObj, - middleware: (ctx, next) => { - const silentMidPromise = silentMiddleware(ctx, next); - middleware(ctx, () => silentMidPromise); - return silentMidPromise; - } - }); - decorateEvent(states); - return exposeProvider({ - ...states, - ...binders - }); -} - -/** - * Determine whether two values are equal in a way that is compatible with virtual data - * @param prevValue Antecedent value - * @param nextValue consequent value - * @returns Are they equal? - */ -var equals = (prevValue, nextValue) => { - // If equal, return directly - if (prevValue === nextValue) { - return shared.trueValue; - } - return stringifyVData(prevValue) === stringifyVData(nextValue); -}; - -/** - * Filter all silentMethod instances that meet the criteria by method name or regular expression - * @param methodNameMatcher method name matcher - * @param queueName Find the queue name, the default is default queue - * @param filterActive Whether to filter out active instances - * @returns array of silentMethod instances - */ -const filterSilentMethods = async (methodNameMatcher, queueName = DEFAULT_QUEUE_NAME, filterActive = shared.falseValue) => { - const matchSilentMethods = (targetQueue = []) => targetQueue.filter(silentMethodItem => { - if (methodNameMatcher === shared.undefinedValue) { - return shared.trueValue; - } - const name = shared.getConfig(silentMethodItem.entity).name || ''; - const retain = shared.instanceOf(methodNameMatcher, RegExp) - ? shared.regexpTest(methodNameMatcher, name) - : name === methodNameMatcher; - return retain && (filterActive ? silentMethodItem.active : shared.trueValue); - }); - return [ - ...matchSilentMethods(silentQueueMap[queueName]), - // If the silent factory is not currently started, you also need to match the silent methods in the persistent storage. - ...(silentFactoryStatus === 0 ? matchSilentMethods((await loadSilentQueueMapFromStorage())[queueName]) : []) - ]; -}; -/** - * Find the first silentMethod instance that meets the condition by method name or regular expression - * @param methodNameMatcher method name matcher - * @param queueName Find the queue name, the default is default queue - * @param filterActive Whether to filter out active instances - * @returns silentMethod instance, undefined when not found - */ -const getSilentMethod = async (methodNameMatcher, queueName = DEFAULT_QUEUE_NAME, filterActive = shared.falseValue) => (await filterSilentMethods(methodNameMatcher, queueName, filterActive))[0]; - -/** - * Determine whether the target data is virtual data - * @param target target data - * @returns Is it virtual data? - */ -var isVData = (target) => !!stringifyVData(target, shared.falseValue) || shared.regexpTest(regVDataId, target); - -/** - * Update the status of the corresponding method - * Unlike updateState, in addition to updating the state immediately, it will also update again after responding in silent mode in order to replace the virtual data with actual data. - * @param method request method object - * @param handleUpdate update callback - */ -const updateStateEffect = async (matcher, handleUpdate) => { - // Save the target method instance to the current silent method instance - if (currentSilentMethod) { - currentSilentMethod.setUpdateState(matcher, shared.isFn(updateState) ? shared.undefinedValue : shared.objectKeys(updateState)); - await currentSilentMethod.save(); - } - return updateState(matcher, handleUpdate); -}; - -const useAutoRequest = (handler, config = {}) => { - let notifiable = shared.trueValue; - const { enableFocus = shared.trueValue, enableVisibility = shared.trueValue, enableNetwork = shared.trueValue, pollingTime = 0, throttle = 1000 } = config; - const { onMounted, onUnmounted, __referingObj: referingObject } = statesHookHelper(alova.promiseStatesHook()); - const states = useRequest(handler, { - ...config, - __referingObj: referingObject - }); - const notify = () => { - if (notifiable) { - states.send(); - if (throttle > 0) { - notifiable = shared.falseValue; - setTimeout(() => { - notifiable = shared.trueValue; - }, throttle); - } - } - }; - let offNetwork = shared.noop; - let offFocus = shared.noop; - let offVisiblity = shared.noop; - let offPolling = shared.noop; - onMounted(() => { - if (!alova.globalConfigMap.ssr) { - offNetwork = enableNetwork ? useAutoRequest.onNetwork(notify, config) : offNetwork; - offFocus = enableFocus ? useAutoRequest.onFocus(notify, config) : offFocus; - offVisiblity = enableVisibility ? useAutoRequest.onVisibility(notify, config) : offVisiblity; - offPolling = pollingTime > 0 ? useAutoRequest.onPolling(notify, config) : offPolling; - } - }); - onUnmounted(() => { - offNetwork(); - offFocus(); - offVisiblity(); - offPolling(); - }); - return states; -}; -const on = (type, handler) => { - window.addEventListener(type, handler); - return () => window.removeEventListener(type, handler); -}; -useAutoRequest.onNetwork = notify => on('online', notify); -useAutoRequest.onFocus = notify => on('focus', notify); -useAutoRequest.onVisibility = notify => { - const handle = () => document.visibilityState === 'visible' && notify(); - return on('visibilitychange', handle); -}; -useAutoRequest.onPolling = (notify, config) => { - const timer = setInterval(notify, config.pollingTime); - return () => clearInterval(timer); -}; - -const hookPrefix$1 = 'useCaptcha'; -const captchaAssert = shared.createAssert(hookPrefix$1); -var useCaptcha = (handler, config = {}) => { - const { initialCountdown, middleware } = config; - captchaAssert(initialCountdown === shared.undefinedValue || initialCountdown > 0, 'initialCountdown must be greater than 0'); - const { create, ref, objectify, exposeProvider, __referingObj: referingObject } = statesHookHelper(alova.promiseStatesHook()); - const countdown = create(0, 'countdown'); - const requestReturned = useRequest(handler, { - ...config, - __referingObj: referingObject, - immediate: shared.falseValue, - managedStates: objectify([countdown], 's'), - // eslint-disable-next-line @typescript-eslint/no-use-before-define - middleware: middleware ? (ctx, next) => middleware({ ...ctx, send }, next) : shared.undefinedValue - }); - const timer = ref(shared.undefinedValue); - const send = (...args) => shared.newInstance(shared.PromiseCls, (resolve, reject) => { - if (countdown.v <= 0) { - requestReturned - .send(...args) - .then(result => { - countdown.v = config.initialCountdown || 60; - timer.current = setInterval(() => { - countdown.v -= 1; - if (countdown.v <= 0) { - clearInterval(timer.current); - } - }, 1000); - resolve(result); - }) - .catch(reason => reject(reason)); - } - else { - reject(shared.newInstance(shared.AlovaError, hookPrefix$1, 'the countdown is not over yet')); - } - }); - return exposeProvider({ - ...requestReturned, - send, - ...objectify([countdown]) - }); -}; - -const RestoreEventKey = Symbol('FormRestore'); -const getStoragedKey = (methodInstance, id) => `alova/form-${id || shared.getMethodInternalKey(methodInstance)}`; -const sharedStates = {}; -const cloneFormData = (form) => { - const shallowClone = (value) => (shared.isArray(value) ? [...value] : shared.isPlainObject(value) ? { ...value } : value); - return shared.walkObject(shallowClone(form), shallowClone); -}; -var useForm = (handler, config = {}) => { - const typedSharedStates = sharedStates; - const { id, initialForm, store, resetAfterSubmiting, immediate = shared.falseValue, middleware } = config; - alova.promiseStatesHook(); - const { create, ref: useFlag$, onMounted, watch, objectify, exposeProvider, __referingObj: referingObject } = statesHookHelper(alova.promiseStatesHook()); - const isStoreObject = shared.isPlainObject(store); - const enableStore = isStoreObject ? store.enable : store; - // If the id in config also has a corresponding shared state, it will also be returned. - // The reason for continuing the execution is to be compatible with the problem that the number of hook executions in react cannot be changed, otherwise it will throw "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - const sharedState = id ? typedSharedStates[id] : shared.undefinedValue; - const form = create(cloneFormData(initialForm), 'form'); - const methodHandler = handler; - const eventManager = shared.createEventManager(); - // Use computed properties to avoid calling methodHandler every time this use hook is executed. - const initialMethodInstance = useFlag$(shared.sloughConfig(methodHandler, [form.v])); - const storageContext = shared.getContext(initialMethodInstance.current).l2Cache; - const storagedKey = getStoragedKey(initialMethodInstance.current, id); - const reseting = useFlag$(shared.falseValue); - const serializerPerformer = useFlag$(createSerializerPerformer(isStoreObject ? store.serializers : shared.undefinedValue)); - // Whether the shared state created by the current hook is initiated. The hook that initiates the creation needs to return the latest state. Otherwise, because the hook is called in react, the latest state cannot be obtained from the hook initiated. - const isCreateShardState = useFlag$(false); - const originalHookProvider = useRequest((...args) => methodHandler(form.v, ...args), { - ...config, - __referingObj: referingObject, - // Middleware function, also supports subscriber middleware - middleware: middleware - ? (ctx, next) => middleware({ - ...ctx, - // eslint-disable-next-line - delegatingActions: { updateForm, reset } - }, next) - : shared.undefinedValue, - // 1. When persistence is required, it will be triggered after data recovery - // 2. When there is a shared state, it means that it has been initialized before (regardless of whether there is an immediate request), and subsequent requests will no longer be automatically initiated. This is to be compatible with the issue of repeated requests when multiple forms initiate requests immediately. - immediate: enableStore || sharedState ? shared.falseValue : immediate - }); - /** - * Reset form data - */ - const reset = () => { - reseting.current = shared.trueValue; - const clonedFormData = cloneFormData(initialForm); - clonedFormData && (form.v = clonedFormData); - enableStore && storageContext.remove(storagedKey); - }; - /** - * Update form data - * @param newForm new form data - */ - const updateForm = (newForm) => { - form.v = { - ...form.v, - ...newForm - }; - }; - const hookProvider = exposeProvider({ - // The first parameter is fixed to form data - ...originalHookProvider, - ...objectify([form]), - updateForm, - reset, - // Persistent data recovery event binding - onRestore(handler) { - eventManager.on(RestoreEventKey, handler); - } - }); - // Only when there is an id, it is saved to sharedStates. - // In react, because a new form will be generated after updating the form, it needs to be resaved every time it is called. - if (id) { - // If there is no shared status yet, it means that the current hook is a created hook. - if (!sharedState) { - isCreateShardState.current = shared.trueValue; - } - // Only the shared state of the created hook is saved - if (isCreateShardState.current) { - typedSharedStates[id] = { - hookProvider: hookProvider, - config - }; - } - } - const { send, onSuccess } = hookProvider; - onMounted(() => { - // Update data when persistence is required - if (enableStore && !sharedState) { - // Get storage and update data - // It needs to be called in onMounted, otherwise it will cause it to be called repeatedly in react. - const storagedForm = serializerPerformer.current.deserialize(storageContext.get(storagedKey)); - // When there is draft data, the data is restored asynchronously, otherwise the on restore event cannot be bound normally. - if (storagedForm) { - form.v = storagedForm; - // Trigger persistent data recovery event - eventManager.emit(RestoreEventKey, shared.undefinedValue); - } - enableStore && immediate && send(...[]); - } - }); - // Monitor changes and store them synchronously. If it is triggered by reset, no further serialization is required. - watch([form], () => { - if (reseting.current || !enableStore) { - reseting.current = shared.falseValue; - return; - } - storageContext.set(storagedKey, serializerPerformer.current.serialize(form.v)); - }); - // If data needs to be cleared after submission, call reset - onSuccess(() => { - resetAfterSubmiting && reset(); - }); - // If there is a saved sharedState, return it - // If it is the shared state created by the current hook, the latest one is returned instead of the cached one. - return sharedState && !isCreateShardState.current ? sharedState.hookProvider : hookProvider; -}; - -const RetryEventKey = Symbol('RetriableRetry'); -const FailEventKey = Symbol('RetriableFail'); -const hookPrefix = 'useRetriableRequest'; -const assert$2 = shared.createAssert(hookPrefix); -var useRetriableRequest = (handler, config = {}) => { - const { retry = 3, backoff = { delay: 1000 }, middleware = shared.noop } = config; - const { ref: useFlag$, exposeProvider, __referingObj: referingObject } = statesHookHelper(alova.promiseStatesHook()); - const eventManager = shared.createEventManager(); - const retryTimes = useFlag$(0); - const stopManuallyError = useFlag$(shared.undefinedValue); // Stop error object, has value when stop is triggered manually - const methodInstanceLastest = useFlag$(shared.undefinedValue); - const argsLatest = useFlag$(shared.undefinedValue); - const requesting = useFlag$(shared.falseValue); // Is it being requested? - const retryTimer = useFlag$(shared.undefinedValue); - const stopPromiseObj = useFlag$(shared.usePromise()); - const emitOnFail = (method, args, error) => { - // On fail needs to be triggered asynchronously, and on error and on complete should be triggered first. - shared.setTimeoutFn(() => { - eventManager.emit(FailEventKey, shared.newInstance((RetriableFailEvent), AlovaEventBase.spawn(method, args), error, retryTimes.current)); - stopManuallyError.current = shared.undefinedValue; - retryTimes.current = 0; // Reset the number of retries - }); - }; - const nestedHookProvider = useRequest(handler, { - ...config, - __referingObj: referingObject, - middleware(ctx, next) { - middleware({ - ...ctx, - delegatingActions: { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - stop - } - }, () => shared.promiseResolve()); - const { proxyStates, args, send, method, controlLoading } = ctx; - controlLoading(); - const { loading } = proxyStates; - const setLoading = (value = shared.falseValue) => { - loading.v = value; - }; - const resolveFail = (error) => { - setLoading(); - proxyStates.error.v = error; - clearTimeout(retryTimer.current); // Clear retry timer - emitOnFail(method, args, error); - }; - if (!loading.v) { - shared.promiseCatch(stopPromiseObj.current.promise, error => { - resolveFail(error); - stopPromiseObj.current = shared.usePromise(); - }); - } - setLoading(shared.trueValue); - requesting.current = shared.trueValue; - methodInstanceLastest.current = method; - argsLatest.current = args; - /** - * Consider this situation: user call stop() and send another request immediately, but now the previous request haven't finished. `next()` will raises the branch on completion. - * - * By using Promise.race(), we can cause the returned promise to be rejected immediately when call `stop()` - */ - return next() - .then(val => { - // set `loading` to false when request is successful - setLoading(); - return val; - }, - // Trigger retry mechanism when request fails - error => { - // There is no manual trigger to stop, and a retry is triggered when the number of retries does not reach the maximum. - if (!stopManuallyError.current && (shared.isNumber(retry) ? retryTimes.current < retry : retry(error, ...args))) { - retryTimes.current += 1; - // Calculate retry delay time - const retryDelay = shared.delayWithBackoff(backoff, retryTimes.current); - // Delay the corresponding time and try again - retryTimer.current = shared.setTimeoutFn(() => { - // trigger retry event - eventManager.emit(RetryEventKey, shared.newInstance((RetriableRetryEvent), AlovaEventBase.spawn(method, args), retryTimes.current, retryDelay)); - // If stopped manually, retry will no longer be triggered. - shared.promiseCatch(send(...args), shared.noop); // Captured errors will no longer be thrown out, otherwise errors will be thrown when retrying. - }, retryDelay); - } - else { - error = stopManuallyError.current || error; // If stop manually error has a value, it means that the stop is triggered through the stop function. - resolveFail(error); - } - // Return reject to execute the subsequent error process - return shared.promiseReject(error); - }) - .finally(() => { - requesting.current = shared.falseValue; - }); - } - }); - /** - * Stop retrying, only valid when called during retrying - * If the request is in progress, trigger an interrupt request and let the request error throw an error. Otherwise, manually modify the status and trigger onFail. - * The onFail event will be triggered immediately after stopping - */ - const stop = () => { - assert$2(nestedHookProvider.__proxyState('loading').v, 'there is no requests being retried'); - stopManuallyError.current = shared.newInstance(shared.AlovaError, hookPrefix, 'stop retry manually'); - if (requesting.current) { - nestedHookProvider.abort(); - } - else { - stopPromiseObj.current.reject(stopManuallyError.current); - } - }; - /** - * Retry event binding - * They will be triggered after the retry is initiated - * @param handler Retry event callback - */ - const onRetry = (handler) => { - eventManager.on(RetryEventKey, event => handler(event)); - }; - /** - * failed event binding - * They will be triggered when there are no more retries, such as when the maximum number of retries is reached, when the retry callback returns false, or when stop is manually called to stop retries. - * The onError event of alova will be triggered every time an error is requested. - * - * Note: If there are no retries, onError, onComplete and onFail will be triggered at the same time. - * - * @param handler Failure event callback - */ - const onFail = (handler) => { - eventManager.on(FailEventKey, event => handler(event)); - }; - return exposeProvider({ - ...nestedHookProvider, - stop, - onRetry, - onFail - }); -}; - -const SSEOpenEventKey = Symbol('SSEOpen'); -const SSEMessageEventKey = Symbol('SSEMessage'); -const SSEErrorEventKey = Symbol('SSEError'); -var SSEHookReadyState; -(function (SSEHookReadyState) { - SSEHookReadyState[SSEHookReadyState["CONNECTING"] = 0] = "CONNECTING"; - SSEHookReadyState[SSEHookReadyState["OPEN"] = 1] = "OPEN"; - SSEHookReadyState[SSEHookReadyState["CLOSED"] = 2] = "CLOSED"; -})(SSEHookReadyState || (SSEHookReadyState = {})); -const assert$1 = shared.createAssert('useSSE'); -const MessageType = { - Open: 'open', - Error: 'error', - Message: 'message' -}; -var useSSE = (handler, config = {}) => { - const { initialData, withCredentials, interceptByGlobalResponded = shared.trueValue, - /** abortLast = trueValue, */ - immediate = shared.falseValue } = config; - // ! Temporarily does not support specifying abortLast - const abortLast = shared.trueValue; - let { memorize } = alova.promiseStatesHook(); - memorize !== null && memorize !== void 0 ? memorize : (memorize = shared.$self); - const { create, ref, onMounted, onUnmounted, objectify, exposeProvider } = statesHookHelper(alova.promiseStatesHook()); - const usingArgs = ref([]); - const eventSource = ref(shared.undefinedValue); - const sendPromiseObject = ref(shared.undefinedValue); - const data = create(initialData, 'data'); - const readyState = create(SSEHookReadyState.CLOSED, 'readyState'); - let methodInstance = getHandlerMethod(handler); - let responseUnified; - const eventManager = shared.createEventManager(); - // UseCallback object that stores custom events, where key is eventName - const customEventMap = ref(new Map()); - const onOpen = (handler) => { - eventManager.on(SSEOpenEventKey, handler); - }; - const onMessage = (handler) => { - eventManager.on(SSEMessageEventKey, handler); - }; - const onError = (handler) => { - eventManager.on(SSEErrorEventKey, handler); - }; - const responseSuccessHandler = ref(shared.$self); - const responseErrorHandler = ref(throwFn); - const responseCompleteHandler = ref(shared.noop); - /** - * Set up a response interceptor, which needs to be called after each send - */ - const setResponseHandler = (instance) => { - // responded removed since 3.0 - const { responded } = shared.getOptions(instance); - responseUnified = responded; - if (shared.isFn(responseUnified)) { - responseSuccessHandler.current = responseUnified; - } - else if (responseUnified && shared.isPlainObject(responseUnified)) { - const { onSuccess: successHandler, onError: errorHandler, onComplete: completeHandler } = responseUnified; - responseSuccessHandler.current = shared.isFn(successHandler) ? successHandler : responseSuccessHandler.current; - responseErrorHandler.current = shared.isFn(errorHandler) ? errorHandler : responseErrorHandler.current; - responseCompleteHandler.current = shared.isFn(completeHandler) ? completeHandler : responseCompleteHandler.current; - } - }; - /** - * Process response tasks and do not cache data on failure - * @param handlerReturns Data returned by the interceptor - * @returns Processed response - */ - const handleResponseTask = async (handlerReturns) => { - const { headers, transform: transformFn = shared.$self } = shared.getConfig(methodInstance); - const returnsData = await handlerReturns; - const transformedData = await transformFn(returnsData, (headers || {})); - data.v = transformedData; - // invalidate cache - alova.hitCacheBySource(methodInstance); - return transformedData; - }; - /** - * Create AlovaSSEHook event - * For specific data processing procedures, please refer to the following link - * @link https://alova.js.org/zh-CN/tutorial/combine-framework/response - */ - const createSSEEvent = async (eventFrom, dataOrError) => { - assert$1(!!eventSource.current, 'EventSource is not initialized'); - const es = eventSource.current; - const baseEvent = new AlovaSSEEvent(AlovaEventBase.spawn(methodInstance, usingArgs.current), es); - if (eventFrom === MessageType.Open) { - return Promise.resolve(baseEvent); - } - const globalSuccess = interceptByGlobalResponded ? responseSuccessHandler.current : shared.$self; - const globalError = interceptByGlobalResponded ? responseErrorHandler.current : throwFn; - const globalFinally = interceptByGlobalResponded ? responseCompleteHandler.current : shared.noop; - const p = shared.promiseFinally(shared.promiseThen(dataOrError, res => handleResponseTask(globalSuccess(res, methodInstance)), error => handleResponseTask(globalError(error, methodInstance))), - // Finally - () => { - globalFinally(methodInstance); - }); - // Regardless, the Promise object returned by the function must be fulfilled - return shared.promiseThen(p, - // Get processed data (data after transform) - res => new AlovaSSEMessageEvent(baseEvent, res), - // There is an error - error => new AlovaSSEErrorEvent(baseEvent, error)); - }; - /** - * Select the required trigger function based on the event. If the event has no errors, the callback function passed in is triggered. - * @param callback Callback function triggered when there is no error - */ - const sendSSEEvent = (callback) => (event) => { - if (event.error === shared.undefinedValue) { - return callback(event); - } - return eventManager.emit(SSEErrorEventKey, event); - }; - // * MARK: Event handling of EventSource - const onCustomEvent = (eventName, callbackHandler) => { - var _a; - const currentMap = customEventMap.current; - if (!currentMap.has(eventName)) { - const useCallbackObject = useCallback(callbacks => { - var _a; - if (callbacks.length === 0) { - (_a = eventSource.current) === null || _a === void 0 ? void 0 : _a.removeEventListener(eventName, useCallbackObject[1]); - customEventMap.current.delete(eventName); - } - }); - const trigger = useCallbackObject[1]; - currentMap.set(eventName, useCallbackObject); - (_a = eventSource.current) === null || _a === void 0 ? void 0 : _a.addEventListener(eventName, event => { - shared.promiseThen(createSSEEvent(eventName, Promise.resolve(event.data)), sendSSEEvent(trigger)); - }); - } - const [onEvent] = currentMap.get(eventName); - return onEvent(callbackHandler); - }; - /** - * Cancel the registration of custom events in useCallback - */ - const offCustomEvent = () => { - customEventMap.current.forEach(([_1, _2, offTrigger]) => { - offTrigger(); - }); - }; - const esOpen = memorize(() => { - var _a; - // resolve the promise returned when using send() - readyState.v = SSEHookReadyState.OPEN; - shared.promiseThen(createSSEEvent(MessageType.Open, Promise.resolve()), event => eventManager.emit(SSEOpenEventKey, event)); - // ! Must be resolved after calling onOpen - (_a = sendPromiseObject.current) === null || _a === void 0 ? void 0 : _a.resolve(); - }); - const esError = memorize((event) => { - var _a, _b; - readyState.v = SSEHookReadyState.CLOSED; - shared.promiseThen(createSSEEvent(MessageType.Error, Promise.reject((_a = event === null || event === void 0 ? void 0 : event.message) !== null && _a !== void 0 ? _a : 'SSE Error')), sendSSEEvent(event => eventManager.emit(SSEMessageEventKey, event))); - (_b = sendPromiseObject.current) === null || _b === void 0 ? void 0 : _b.resolve(); - }); - const esMessage = memorize((event) => { - shared.promiseThen(createSSEEvent(MessageType.Message, Promise.resolve(event.data)), sendSSEEvent(event => eventManager.emit(SSEMessageEventKey, event))); - }); - /** - * Close the registration of the current eventSource - */ - const close = () => { - const es = eventSource.current; - if (!es) { - return; - } - if (sendPromiseObject.current) { - // If the promise is still there when close - sendPromiseObject.current.resolve(); - } - // * MARK: Unbinding event handling - es.close(); - es.removeEventListener(MessageType.Open, esOpen); - es.removeEventListener(MessageType.Error, esError); - es.removeEventListener(MessageType.Message, esMessage); - readyState.v = SSEHookReadyState.CLOSED; - // After eventSource is closed, unregister all custom events - // Otherwise it may cause memory leaks - customEventMap.current.forEach(([_, eventTrigger], eventName) => { - es.removeEventListener(eventName, eventTrigger); - }); - }; - /** - * Send request and initialize eventSource - */ - const connect = (...args) => { - let es = eventSource.current; - let promiseObj = sendPromiseObject.current; - if (es && abortLast) { - // When abortLast === true, close the previous connection and re-establish it - close(); - } - // Set the promise object used by the send function - if (!promiseObj) { - promiseObj = sendPromiseObject.current = shared.usePromise(); - // Clear the promise object after open - promiseObj && - promiseObj.promise.finally(() => { - promiseObj = shared.undefinedValue; - }); - } - usingArgs.current = args; - methodInstance = getHandlerMethod(handler, args); - // Set up response interceptor - setResponseHandler(methodInstance); - const { params } = shared.getConfig(methodInstance); - const { baseURL, url } = methodInstance; - const fullURL = shared.buildCompletedURL(baseURL, url, params); - // Establish connection - es = new EventSource(fullURL, { withCredentials }); - eventSource.current = es; - readyState.v = SSEHookReadyState.CONNECTING; - // * MARK: Register to handle events - // Register to handle event open error message - es.addEventListener(MessageType.Open, esOpen); - es.addEventListener(MessageType.Error, esError); - es.addEventListener(MessageType.Message, esMessage); - // and custom events - // If the on listener is used before connect (send), there will already be events in customEventMap. - customEventMap.current.forEach(([_, eventTrigger], eventName) => { - es === null || es === void 0 ? void 0 : es.addEventListener(eventName, event => { - shared.promiseThen(createSSEEvent(eventName, Promise.resolve(event.data)), sendSSEEvent(eventTrigger)); - }); - }); - return promiseObj.promise; - }; - onUnmounted(() => { - close(); - // The above use of eventSource.removeEventListener just disconnects eventSource and trigger. - // Here is the cancellation of the event registration in the useCallback object - eventManager.off(SSEOpenEventKey); - eventManager.off(SSEMessageEventKey); - eventManager.off(SSEErrorEventKey); - offCustomEvent(); - }); - // * MARK: initialization action - onMounted(() => { - var _a; - if (immediate) { - connect(...[]); - (_a = sendPromiseObject.current) === null || _a === void 0 ? void 0 : _a.promise.catch(() => { }); - } - }); - return exposeProvider({ - send: connect, - close, - on: onCustomEvent, - onMessage, - onError, - onOpen, - eventSource, - ...objectify([readyState, data]) - }); -}; - -let currentHookIndex = 0; -// (id, (hookIndex, Actions)) -const actionsMap = {}; -const isFrontMiddlewareContext = (context) => !!context.send; -const assert = shared.createAssert('subscriber'); -/** - * Operation function delegation middleware - * After using this middleware, you can call the delegated function through accessAction. - * Can delegate multiple identical IDs - * In order to eliminate the hierarchical restrictions of components - * @param id Client ID - * @returns alova middleware function - */ -const actionDelegationMiddleware = (id) => { - const { ref, onUnmounted } = statesHookHelper(alova.promiseStatesHook()); - const hookIndex = ref(currentHookIndex + 1); - if (hookIndex.current > currentHookIndex) { - currentHookIndex += 1; - } - onUnmounted(() => { - var _a; - if ((_a = actionsMap[id]) === null || _a === void 0 ? void 0 : _a[hookIndex.current]) { - // delete action on unmount - delete actionsMap[id][hookIndex.current]; - } - }); - return (context, next) => { - // The middleware will be called repeatedly. If you have already subscribed, you do not need to subscribe again. - const { abort, proxyStates, delegatingActions = {} } = context; - const update = (newStates) => { - for (const key in newStates) { - proxyStates[key] && (proxyStates[key].v = newStates[key]); - } - }; - // Those with the same ID will be saved together in the form of an array - const hooks = (actionsMap[id] = actionsMap[id] || []); - const handler = isFrontMiddlewareContext(context) - ? { - ...delegatingActions, - send: context.send, - abort, - update - } - : { - ...delegatingActions, - fetch: context.fetch, - abort, - update - }; - hooks[hookIndex.current] = handler; - return next(); - }; -}; -/** - * Access the operation function, if there are multiple matches, onMatch will be called with this - * @param id Delegator id, or regular expression - * @param onMatch matching subscribers - * @param silent Default is false. If true, no error will be reported if there is no match - */ -const accessAction = (id, onMatch, silent = false) => { - const matched = []; - if (typeof id === 'symbol' || shared.isString(id) || shared.isNumber(id)) { - actionsMap[id] && shared.pushItem(matched, ...shared.objectValues(actionsMap[id])); - } - else if (shared.instanceOf(id, RegExp)) { - shared.forEach(shared.filterItem(shared.objectKeys(actionsMap), idItem => id.test(idItem)), idItem => { - shared.pushItem(matched, ...shared.objectValues(actionsMap[idItem])); - }); - } - // its opposite expression is too obscure - if (matched.length === 0 && !silent) { - assert(false, `no handler can be matched by using \`${id.toString()}\``); - } - shared.forEach(shared.filterItem(matched, shared.$self), onMatch); -}; - -exports.accessAction = accessAction; -exports.actionDelegationMiddleware = actionDelegationMiddleware; -exports.bootSilentFactory = bootSilentFactory; -exports.createClientTokenAuthentication = createClientTokenAuthentication; -exports.createServerTokenAuthentication = createServerTokenAuthentication; -exports.dehydrateVData = dehydrateVData; -exports.equals = equals; -exports.filterSilentMethods = filterSilentMethods; -exports.getSilentMethod = getSilentMethod; -exports.isVData = isVData; -exports.onBeforeSilentSubmit = onBeforeSilentSubmit; -exports.onSilentSubmitBoot = onSilentSubmitBoot; -exports.onSilentSubmitError = onSilentSubmitError; -exports.onSilentSubmitFail = onSilentSubmitFail; -exports.onSilentSubmitSuccess = onSilentSubmitSuccess; -exports.silentQueueMap = silentQueueMap; -exports.statesHookHelper = statesHookHelper; -exports.stringifyVData = stringifyVData; -exports.updateState = updateState; -exports.updateStateEffect = updateStateEffect; -exports.useAutoRequest = useAutoRequest; -exports.useCaptcha = useCaptcha; -exports.useFetcher = useFetcher; -exports.useForm = useForm; -exports.usePagination = usePagination; -exports.useRequest = useRequest; -exports.useRetriableRequest = useRetriableRequest; -exports.useSQRequest = useSQRequest; -exports.useSSE = useSSE; -exports.useSerialRequest = useSerialRequest; -exports.useSerialWatcher = useSerialWatcher; -exports.useWatcher = useWatcher; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/clienthook/index.esm.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/clienthook/index.esm.js deleted file mode 100644 index f63d80a..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/clienthook/index.esm.js +++ /dev/null @@ -1,3430 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -import { isPlainObject, instanceOf, trueValue, falseValue, newInstance, PromiseCls, pushItem, isFn, noop, len, forEach, undefinedValue, splice, $self, isNumber, clearTimeoutTimer, setTimeoutFn, createAssert, FrameworkState, FrameworkReadableState, ObjectCls, objAssign, nullValue, mapItem, objectKeys, includes, filterItem, deleteAttr, getHandlerMethod as getHandlerMethod$1, getContext, getMethodInternalKey, promiseResolve, omit, promiseThen, sloughConfig, buildNamespacedCacheKey, getTime, createEventManager, createSyncOnceRunner, promiseCatch, isArray, createAsyncQueue, usePromise, getLocalCacheConfigParam, MEMORY, objectValues, decorateEvent, isObject, walkObject, valueObject, uuid, defineProperty, globalToString, RegExpCls, regexpTest, shift, delayWithBackoff, isString, getConfig, AlovaError, promiseReject, promiseFinally, buildCompletedURL, getOptions } from '@alova/shared'; -import { Method, queryCache, promiseStatesHook, globalConfigMap, setCache, invalidateCache, hitCacheBySource } from 'alova'; - -const defaultVisitorMeta = { - authRole: null -}; -const defaultLoginMeta = { - authRole: 'login' -}; -const defaultLogoutMeta = { - authRole: 'logout' -}; -const defaultRefreshTokenMeta = { - authRole: 'refreshToken' -}; -const checkMethodRole = ({ meta }, metaMatches) => { - if (isPlainObject(meta)) { - for (const key in meta) { - if (Object.prototype.hasOwnProperty.call(meta, key)) { - const matchedMetaItem = metaMatches[key]; - if (instanceOf(matchedMetaItem, RegExp) ? matchedMetaItem.test(meta[key]) : meta[key] === matchedMetaItem) { - return trueValue; - } - } - } - } - return falseValue; -}; -const waitForTokenRefreshed = (method, waitingList) => newInstance(PromiseCls, resolve => { - pushItem(waitingList, { - method, - resolve - }); -}); -const callHandlerIfMatchesMeta = (method, authorizationInterceptor, defaultMeta, response) => { - if (checkMethodRole(method, (authorizationInterceptor === null || authorizationInterceptor === void 0 ? void 0 : authorizationInterceptor.metaMatches) || defaultMeta)) { - const handler = isFn(authorizationInterceptor) - ? authorizationInterceptor - : isPlainObject(authorizationInterceptor) && isFn(authorizationInterceptor.handler) - ? authorizationInterceptor.handler - : noop; - return handler(response, method); - } -}; -const refreshTokenIfExpired = async (method, waitingList, updateRefreshStatus, handlerParams, refreshToken, tokenRefreshing) => { - // When the number of handle params is greater than 2, it means that this function is called from the response, and the original interface needs to be requested again. - const fromResponse = len(handlerParams) >= 2; - let isExpired = refreshToken === null || refreshToken === void 0 ? void 0 : refreshToken.isExpired(...handlerParams); - // Compatible with synchronous and asynchronous functions - if (instanceOf(isExpired, PromiseCls)) { - isExpired = await isExpired; - } - if (isExpired) { - try { - // Make another judgment in the response to prevent multiple requests to refresh the token, intercept and wait for the token sent before the token refresh is completed. - let intentToRefreshToken = trueValue; - if (fromResponse && tokenRefreshing) { - intentToRefreshToken = falseValue; // The requests waiting here indicate that the token is being refreshed. When they pass, there is no need to refresh the token again. - await waitForTokenRefreshed(method, waitingList); - } - if (intentToRefreshToken) { - updateRefreshStatus(trueValue); - // Call refresh token - await (refreshToken === null || refreshToken === void 0 ? void 0 : refreshToken.handler(...handlerParams)); - updateRefreshStatus(falseValue); - // After the token refresh is completed, the requests in the waiting list are notified. - forEach(waitingList, ({ resolve }) => resolve()); - } - if (fromResponse) { - // Because the original interface is being requested again, superposition with the previous request will result in repeated calls to transform, so it is necessary to leave transform empty to remove one call. - const { config } = method; - const methodTransformData = config.transform; - config.transform = undefinedValue; - const resentData = await method; - config.transform = methodTransformData; - return resentData; - } - } - finally { - updateRefreshStatus(falseValue); - splice(waitingList, 0, len(waitingList)); // Clear waiting list - } - } -}; -const onResponded2Record = (onRespondedHandlers) => { - let successHandler = undefinedValue; - let errorHandler = undefinedValue; - let onCompleteHandler = undefinedValue; - if (isFn(onRespondedHandlers)) { - successHandler = onRespondedHandlers; - } - else if (isPlainObject(onRespondedHandlers)) { - const { onSuccess, onError, onComplete } = onRespondedHandlers; - successHandler = isFn(onSuccess) ? onSuccess : successHandler; - errorHandler = isFn(onError) ? onError : errorHandler; - onCompleteHandler = isFn(onComplete) ? onComplete : onCompleteHandler; - } - return { - onSuccess: successHandler, - onError: errorHandler, - onComplete: onCompleteHandler - }; -}; - -/** - * Create a client-side token authentication interceptor - * @param options Configuration parameters - * @returns token authentication interceptor function - */ -const createClientTokenAuthentication = ({ visitorMeta, login, logout, refreshToken, assignToken = noop }) => { - let tokenRefreshing = falseValue; - const waitingList = []; - const onAuthRequired = onBeforeRequest => async (method) => { - const isVisitorRole = checkMethodRole(method, visitorMeta || defaultVisitorMeta); - const isLoginRole = checkMethodRole(method, (login === null || login === void 0 ? void 0 : login.metaMatches) || defaultLoginMeta); - // Ignored, login, and token refresh requests do not perform token authentication. - if (!isVisitorRole && - !isLoginRole && - !checkMethodRole(method, (refreshToken === null || refreshToken === void 0 ? void 0 : refreshToken.metaMatches) || defaultRefreshTokenMeta)) { - // If the token is being refreshed, wait for the refresh to complete before sending a request. - if (tokenRefreshing) { - await waitForTokenRefreshed(method, waitingList); - } - await refreshTokenIfExpired(method, waitingList, refreshing => { - tokenRefreshing = refreshing; - }, [method], refreshToken); - } - // Requests from non-guest and logged-in roles will enter the assignment token function - if (!isVisitorRole && !isLoginRole) { - await assignToken(method); - } - return onBeforeRequest === null || onBeforeRequest === void 0 ? void 0 : onBeforeRequest(method); - }; - const onResponseRefreshToken = originalResponded => { - const respondedRecord = onResponded2Record(originalResponded); - return { - ...respondedRecord, - onSuccess: async (response, method) => { - await callHandlerIfMatchesMeta(method, login, defaultLoginMeta, response); - await callHandlerIfMatchesMeta(method, logout, defaultLogoutMeta, response); - return (respondedRecord.onSuccess || $self)(response, method); - } - }; - }; - return { - waitingList, - onAuthRequired, - onResponseRefreshToken - }; -}; -/** - * Create a server-side token authentication interceptor - * @param options Configuration parameters - * @returns token authentication interceptor function - */ -const createServerTokenAuthentication = ({ visitorMeta, login, logout, refreshTokenOnSuccess, refreshTokenOnError, assignToken = noop }) => { - let tokenRefreshing = falseValue; - const waitingList = []; - const onAuthRequired = onBeforeRequest => async (method) => { - const isVisitorRole = checkMethodRole(method, visitorMeta || defaultVisitorMeta); - const isLoginRole = checkMethodRole(method, (login === null || login === void 0 ? void 0 : login.metaMatches) || defaultLoginMeta); - // Ignored, login, and token refresh requests do not perform token authentication. - if (!isVisitorRole && - !isLoginRole && - !checkMethodRole(method, (refreshTokenOnSuccess === null || refreshTokenOnSuccess === void 0 ? void 0 : refreshTokenOnSuccess.metaMatches) || defaultRefreshTokenMeta) && - !checkMethodRole(method, (refreshTokenOnError === null || refreshTokenOnError === void 0 ? void 0 : refreshTokenOnError.metaMatches) || defaultRefreshTokenMeta)) { - // If the token is being refreshed, wait for the refresh to complete before sending a request. - if (tokenRefreshing) { - await waitForTokenRefreshed(method, waitingList); - } - } - if (!isVisitorRole && !isLoginRole) { - await assignToken(method); - } - return onBeforeRequest === null || onBeforeRequest === void 0 ? void 0 : onBeforeRequest(method); - }; - const onResponseRefreshToken = onRespondedHandlers => { - const respondedRecord = onResponded2Record(onRespondedHandlers); - return { - ...respondedRecord, - onSuccess: async (response, method) => { - if (!checkMethodRole(method, visitorMeta || defaultVisitorMeta) && - !checkMethodRole(method, (login === null || login === void 0 ? void 0 : login.metaMatches) || defaultLoginMeta) && - !checkMethodRole(method, (refreshTokenOnSuccess === null || refreshTokenOnSuccess === void 0 ? void 0 : refreshTokenOnSuccess.metaMatches) || defaultRefreshTokenMeta)) { - const dataResent = await refreshTokenIfExpired(method, waitingList, refreshing => { - tokenRefreshing = refreshing; - }, [response, method], refreshTokenOnSuccess, tokenRefreshing); - if (dataResent) { - return dataResent; - } - } - await callHandlerIfMatchesMeta(method, login, defaultLoginMeta, response); - await callHandlerIfMatchesMeta(method, logout, defaultLogoutMeta, response); - return (respondedRecord.onSuccess || $self)(response, method); - }, - onError: async (error, method) => { - if (!checkMethodRole(method, visitorMeta || defaultVisitorMeta) && - !checkMethodRole(method, (login === null || login === void 0 ? void 0 : login.metaMatches) || defaultLoginMeta) && - !checkMethodRole(method, (refreshTokenOnError === null || refreshTokenOnError === void 0 ? void 0 : refreshTokenOnError.metaMatches) || defaultRefreshTokenMeta)) { - const dataResent = await refreshTokenIfExpired(method, waitingList, refreshing => { - tokenRefreshing = refreshing; - }, [error, method], refreshTokenOnError, tokenRefreshing); - if (dataResent) { - return dataResent; - } - } - return (respondedRecord.onError || noop)(error, method); - } - }; - }; - return { - waitingList, - onAuthRequired, - onResponseRefreshToken - }; -}; - -/** - * Compatible functions, throwing parameters - * @param error mistake - */ -const throwFn = (error) => { - throw error; -}; -function useCallback(onCallbackChange = noop) { - let callbacks = []; - const setCallback = (fn) => { - if (!callbacks.includes(fn)) { - callbacks.push(fn); - onCallbackChange(callbacks); - } - // Return unregister function - return () => { - callbacks = filterItem(callbacks, e => e !== fn); - onCallbackChange(callbacks); - }; - }; - const triggerCallback = (...args) => { - if (callbacks.length > 0) { - return forEach(callbacks, fn => fn(...args)); - } - }; - const removeAllCallback = () => { - callbacks = []; - onCallbackChange(callbacks); - }; - return [setCallback, triggerCallback, removeAllCallback]; -} -/** - * Create a debounce function and trigger the function immediately when delay is 0 - * Scenario: When calling useWatcher and setting immediate to true, the first call must be executed immediately, otherwise it will cause a delayed call - * @param {GeneralFn} fn callback function - * @param {number|(...args: any[]) => number} delay Delay description, dynamic delay can be achieved when set as a function - * @returns Delayed callback function - */ -const debounce = (fn, delay) => { - let timer = nullValue; - return function debounceFn(...args) { - const bindFn = fn.bind(this, ...args); - const delayMill = isNumber(delay) ? delay : delay(...args); - timer && clearTimeoutTimer(timer); - if (delayMill > 0) { - timer = setTimeoutFn(bindFn, delayMill); - } - else { - bindFn(); - } - }; -}; -/** - * Get the request method object - * @param methodHandler Request method handle - * @param args Method call parameters - * @returns request method object - */ -const getHandlerMethod = (methodHandler, args = []) => { - const methodInstance = isFn(methodHandler) ? methodHandler(...args) : methodHandler; - createAssert('scene')(instanceOf(methodInstance, Method), 'hook handler must be a method instance or a function that returns method instance'); - return methodInstance; -}; -/** - * Convert each value of the object and return the new object - * @param obj object - * @param callback callback function - * @returns converted object - */ -const mapObject = (obj, callback) => { - const ret = {}; - for (const key in obj) { - ret[key] = callback(obj[key], key, obj); - } - return ret; -}; -var EnumHookType; -(function (EnumHookType) { - EnumHookType[EnumHookType["USE_REQUEST"] = 1] = "USE_REQUEST"; - EnumHookType[EnumHookType["USE_WATCHER"] = 2] = "USE_WATCHER"; - EnumHookType[EnumHookType["USE_FETCHER"] = 3] = "USE_FETCHER"; -})(EnumHookType || (EnumHookType = {})); -/** - * create simple and unified, framework-independent states creators and handlers. - * @param statesHook states hook from `promiseStatesHook` function of alova - * @param referingObject refering object exported from `promiseStatesHook` function - * @returns simple and unified states creators and handlers - */ -function statesHookHelper(statesHook, referingObject = { trackedKeys: {}, bindError: falseValue }) { - const ref = (initialValue) => (statesHook.ref ? statesHook.ref(initialValue) : { current: initialValue }); - referingObject = ref(referingObject).current; - const exportState = (state) => (statesHook.export || $self)(state, referingObject); - const memorize = (fn) => { - if (!isFn(statesHook.memorize)) { - return fn; - } - const memorizedFn = statesHook.memorize(fn); - memorizedFn.memorized = true; - return memorizedFn; - }; - const { dehydrate } = statesHook; - // For performance reasons, only value is different, and the key is tracked can be updated. - const update = (newValue, state, key) => newValue !== dehydrate(state, key, referingObject) && - referingObject.trackedKeys[key] && - statesHook.update(newValue, state, key, referingObject); - const mapDeps = (deps) => mapItem(deps, item => (instanceOf(item, FrameworkReadableState) ? item.e : item)); - const createdStateList = []; - // key of deps on computed - const depKeys = {}; - return { - create: (initialValue, key) => { - pushItem(createdStateList, key); // record the keys of created states. - return newInstance((FrameworkState), statesHook.create(initialValue, key, referingObject), key, state => dehydrate(state, key, referingObject), exportState, (state, newValue) => update(newValue, state, key)); - }, - computed: (getter, depList, key) => { - // Collect all dependencies in computed - forEach(depList, dep => { - if (dep.k) { - depKeys[dep.k] = true; - } - }); - return newInstance((FrameworkReadableState), statesHook.computed(getter, mapDeps(depList), key, referingObject), key, state => dehydrate(state, key, referingObject), exportState); - }, - effectRequest: (effectRequestParams) => statesHook.effectRequest(effectRequestParams, referingObject), - ref, - watch: (source, callback) => statesHook.watch(mapDeps(source), callback, referingObject), - onMounted: (callback) => statesHook.onMounted(callback, referingObject), - onUnmounted: (callback) => statesHook.onUnmounted(callback, referingObject), - memorize, - /** - * refering object that sharing some value with this object. - */ - __referingObj: referingObject, - /** - * expose provider for specified use hook. - * @param object object that contains state proxy, framework state, operating function and event binder. - * @returns provider component. - */ - exposeProvider: (object) => { - const provider = {}; - const originalStatesMap = {}; - for (const key in object) { - const value = object[key]; - const isValueFunction = isFn(value); - // if it's a memorized function, don't memorize it any more, add it to provider directly. - // if it's start with `on`, that indicates it is an event binder, we should define a new function which return provider object. - // if it's a common function, add it to provider with memorize mode. - // Note that: in some situation, state is a function such as solid's signal, and state value is set to function in react, the state will be detected as a function. so we should check whether the key is in `trackedKeys` - if (isValueFunction && !referingObject.trackedKeys[key]) { - provider[key] = key.startsWith('on') - ? (...args) => { - value(...args); - // eslint-disable-next-line - return completedProvider; - } - : value.memorized - ? value - : memorize(value); - } - else { - const isFrameworkState = instanceOf(value, FrameworkReadableState); - if (isFrameworkState) { - originalStatesMap[key] = value.s; - } - // otherwise, it's a state proxy or framework state, add it to provider with getter mode. - ObjectCls.defineProperty(provider, key, { - get: () => { - // record the key that is being tracked. - referingObject.trackedKeys[key] = trueValue; - return isFrameworkState ? value.e : value; - }, - // set need to set an function, - // otherwise it will throw `TypeError: Cannot set property __referingObj of # which has only a getter` when setting value - set: noop, - enumerable: trueValue, - configurable: trueValue - }); - } - } - const { update: nestedHookUpdate, __proxyState: nestedProxyState } = provider; - // reset the tracked keys and bingError flag, so that the nest hook providers can be initialized. - // Always track the dependencies in computed - referingObject.trackedKeys = { - ...depKeys - }; - referingObject.bindError = falseValue; - const extraProvider = { - // expose referingObject automatically. - __referingObj: referingObject, - // the new updating function that can update the new states and nested hook states. - update: memorize((newStates) => { - objectKeys(newStates).forEach(key => { - if (includes(createdStateList, key)) { - update(newStates[key], originalStatesMap[key], key); - } - else if (key in provider && isFn(nestedHookUpdate)) { - nestedHookUpdate({ - [key]: newStates[key] - }); - } - }); - }), - __proxyState: memorize((key) => { - if (includes(createdStateList, key) && instanceOf(object[key], FrameworkReadableState)) { - // need to tag the key that is being tracked so that it can be updated with `state.v = xxx`. - referingObject.trackedKeys[key] = trueValue; - return object[key]; - } - return nestedProxyState(key); - }) - }; - const completedProvider = objAssign(provider, extraProvider); - return completedProvider; - }, - /** - * transform state proxies to object. - * @param states proxy array of framework states - * @param filterKey filter key of state proxy - * @returns an object that contains the states of target form - */ - objectify: (states, filterKey) => states.reduce((result, item) => { - result[item.k] = filterKey ? item[filterKey] : item; - return result; - }, {}), - transformState2Proxy: (state, key) => newInstance((FrameworkState), state, key, state => dehydrate(state, key, referingObject), exportState, (state, newValue) => update(newValue, state, key)) - }; -} - -const coreAssert = createAssert(''); -const requestHookAssert = createAssert('useRequest'); -const watcherHookAssert = createAssert('useWatcher'); -const fetcherHookAssert = createAssert('useFetcher'); -const coreHookAssert = (hookType) => ({ - [EnumHookType.USE_REQUEST]: requestHookAssert, - [EnumHookType.USE_WATCHER]: watcherHookAssert, - [EnumHookType.USE_FETCHER]: fetcherHookAssert -})[hookType]; -/** - * Assert whether it is a method instance - * @param methodInstance method instance - */ -const assertMethod = (assert, methodInstance) => assert(instanceOf(methodInstance, Method), 'expected a method instance.'); - -const KEY_SUCCESS = 'success'; -const KEY_ERROR = 'error'; -const KEY_COMPLETE = 'complete'; - -var createHook = (ht, c, eventManager, ro) => ({ - /** The method instance of the last request */ - m: undefinedValue, - /** saveStatesFns */ - sf: [], - /** removeStatesFns */ - rf: [], - /** frontStates */ - fs: {}, - /** eventManager */ - em: eventManager, - /** hookType, useRequest=1, useWatcher=2, useFetcher=3 */ - ht, - /** hook config */ - c, - /** referingObject */ - ro, - /** managedStates */ - ms: {} -}); - -// base event -class AlovaEventBase { - constructor(method, args) { - this.method = method; - this.args = args; - } - clone() { - return { ...this }; - } - static spawn(method, args) { - return new AlovaEventBase(method, args); - } -} -class AlovaSuccessEvent extends AlovaEventBase { - constructor(base, data, fromCache) { - super(base.method, base.args); - this.data = data; - this.fromCache = fromCache; - } -} -class AlovaErrorEvent extends AlovaEventBase { - constructor(base, error) { - super(base.method, base.args); - this.error = error; - } -} -class AlovaCompleteEvent extends AlovaEventBase { - constructor(base, status, data, fromCache, error) { - super(base.method, base.args); - this.status = status; - this.data = data; - this.fromCache = status === 'error' ? false : fromCache; - this.error = error; - } -} -// extend event -class AlovaSSEEvent extends AlovaEventBase { - constructor(base, eventSource) { - super(base.method, base.args); - this.eventSource = eventSource; - } -} -class AlovaSSEErrorEvent extends AlovaSSEEvent { - constructor(base, error) { - super(base, base.eventSource); - this.error = error; - } -} -class AlovaSSEMessageEvent extends AlovaSSEEvent { - constructor(base, data) { - super(base, base.eventSource); - this.data = data; - } -} -/** Sq top level events */ -class SQEvent { - constructor(behavior, method, silentMethod) { - this.behavior = behavior; - this.method = method; - this.silentMethod = silentMethod; - } -} -/** Sq global events */ -class GlobalSQEvent extends SQEvent { - constructor(behavior, method, silentMethod, queueName, retryTimes) { - super(behavior, method, silentMethod); - this.queueName = queueName; - this.retryTimes = retryTimes; - } -} -class GlobalSQSuccessEvent extends GlobalSQEvent { - constructor(behavior, method, silentMethod, queueName, retryTimes, data, vDataResponse) { - super(behavior, method, silentMethod, queueName, retryTimes); - this.data = data; - this.vDataResponse = vDataResponse; - } -} -class GlobalSQErrorEvent extends GlobalSQEvent { - constructor(behavior, method, silentMethod, queueName, retryTimes, error, retryDelay) { - super(behavior, method, silentMethod, queueName, retryTimes); - this.error = error; - this.retryDelay = retryDelay; - } -} -class GlobalSQFailEvent extends GlobalSQEvent { - constructor(behavior, method, silentMethod, queueName, retryTimes, error) { - super(behavior, method, silentMethod, queueName, retryTimes); - this.error = error; - } -} -/** Sq event */ -class ScopedSQEvent extends SQEvent { - constructor(behavior, method, silentMethod, args) { - super(behavior, method, silentMethod); - this.args = args; - } -} -class ScopedSQSuccessEvent extends ScopedSQEvent { - constructor(behavior, method, silentMethod, args, data) { - super(behavior, method, silentMethod, args); - this.data = data; - } -} -class ScopedSQErrorEvent extends ScopedSQEvent { - constructor(behavior, method, silentMethod, args, error) { - super(behavior, method, silentMethod, args); - this.error = error; - } -} -class ScopedSQRetryEvent extends ScopedSQEvent { - constructor(behavior, method, silentMethod, args, retryTimes, retryDelay) { - super(behavior, method, silentMethod, args); - this.retryTimes = retryTimes; - this.retryDelay = retryDelay; - } -} -class ScopedSQCompleteEvent extends ScopedSQEvent { - constructor(behavior, method, silentMethod, args, status, data, error) { - super(behavior, method, silentMethod, args); - this.status = status; - this.data = data; - this.error = error; - } -} -class RetriableRetryEvent extends AlovaEventBase { - constructor(base, retryTimes, retryDelay) { - super(base.method, base.args); - this.retryTimes = retryTimes; - this.retryDelay = retryDelay; - } -} -class RetriableFailEvent extends AlovaErrorEvent { - constructor(base, error, retryTimes) { - super(base, error); - this.retryTimes = retryTimes; - } -} - -const defaultMiddleware = (_, next) => next(); - -const stateCache = {}; -/** - * @description Get State cache data - * @param baseURL Base URL - * @param key Request key value - * @returns Cached response data, if not returned {} - */ -const getStateCache = (namespace, key) => { - const cachedState = stateCache[namespace] || {}; - return cachedState[key] || {}; -}; -/** - * @description Set State cache data - * @param baseURL Base URL - * @param key Request key value - * @param data cache data - */ -const setStateCache = (namespace, key, data, hookInstance) => { - const cachedState = (stateCache[namespace] = stateCache[namespace] || {}); - cachedState[key] = { - s: data, - h: hookInstance - }; -}; -/** - * @description Clear State cache data - * @param baseURL Base URL - * @param key Request key value - */ -const removeStateCache = (namespace, key) => { - const cachedState = stateCache[namespace]; - if (cachedState) { - deleteAttr(cachedState, key); - } -}; - -/** - * Unified processing of request logic for useRequest/useWatcher/useFetcher and other request hook functions - * @param hookInstance hook instance - * @param methodHandler Request method object or get function - * @param sendCallingArgs send function parameters - * @returns Request status - */ -function useHookToSendRequest(hookInstance, methodHandler, sendCallingArgs = []) { - const currentHookAssert = coreHookAssert(hookInstance.ht); - let methodInstance = getHandlerMethod$1(methodHandler, currentHookAssert, sendCallingArgs); - const { fs: frontStates, ht: hookType, c: useHookConfig, ms: managedStates } = hookInstance; - const { loading: loadingState, data: dataState, error: errorState } = frontStates; - const isFetcher = hookType === EnumHookType.USE_FETCHER; - const { force: forceRequest = falseValue, middleware = defaultMiddleware } = useHookConfig; - const alovaInstance = getContext(methodInstance); - const { id } = alovaInstance; - // If it is a silent request, on success will be called directly after the request, on error will not be triggered, and progress will not be updated. - const methodKey = getMethodInternalKey(methodInstance); - const { abortLast = trueValue } = useHookConfig; - const isFirstRequest = !hookInstance.m; - hookInstance.m = methodInstance; - return (async () => { - // Initialize status data, which does not need to be loaded when pulling data, because pulling data does not require returning data. - let removeStates = noop; - let saveStates = noop; - let isNextCalled = falseValue; - let responseHandlePromise = promiseResolve(undefinedValue); - let offDownloadEvent = noop; - let offUploadEvent = noop; - const cachedResponse = await queryCache(methodInstance); - let fromCache = () => !!cachedResponse; - // Whether it is a controlled loading state. When it is true, loading will no longer be set to false in response processing. - let controlledLoading = falseValue; - if (!isFetcher) { - // Store the initial state in cache for subsequent updates - saveStates = frontStates => setStateCache(id, methodKey, frontStates, hookInstance); - saveStates({ ...frontStates, ...managedStates }); - // Setting the state removal function will be passed to the effect request in the hook, and it will be set to be called when the component is unloaded. - removeStates = () => removeStateCache(id, methodKey); - } - // The middleware function next callback function allows you to modify mandatory request parameters and even replace the method instance that is about to send the request. - const guardNext = guardNextConfig => { - isNextCalled = trueValue; - const { force: guardNextForceRequest = forceRequest, method: guardNextReplacingMethod = methodInstance } = guardNextConfig || {}; - const forceRequestFinally = sloughConfig(guardNextForceRequest, [ - newInstance((AlovaEventBase), methodInstance, sendCallingArgs) - ]); - const progressUpdater = (stage) => ({ loaded, total }) => { - frontStates[stage].v = { - loaded, - total - }; - }; - methodInstance = guardNextReplacingMethod; - // The latest controller needs to be saved every time a request is sent - pushItem(hookInstance.sf, saveStates); - pushItem(hookInstance.rf, removeStates); - // Loading will not be changed when the loading state is controlled - // The cache is missed, or loading needs to be set to true when forcing a request. - if (!controlledLoading) { - loadingState.v = !!forceRequestFinally || !cachedResponse; - } - // Determine whether to trigger a progress update based on the tracking status of downloading and uploading - const { downloading: enableDownload, uploading: enableUpload } = hookInstance.ro.trackedKeys; - offDownloadEvent = enableDownload ? methodInstance.onDownload(progressUpdater('downloading')) : offDownloadEvent; - offUploadEvent = enableUpload ? methodInstance.onUpload(progressUpdater('uploading')) : offUploadEvent; - responseHandlePromise = methodInstance.send(forceRequestFinally); - fromCache = () => methodInstance.fromCache || falseValue; - return responseHandlePromise; - }; - // Call middleware function - const commonContext = { - method: methodInstance, - cachedResponse, - config: useHookConfig, - abort: () => methodInstance.abort() - }; - // Whether it is necessary to update the response data and call the response callback - const toUpdateResponse = () => hookType !== EnumHookType.USE_WATCHER || !abortLast || hookInstance.m === methodInstance; - const controlLoading = (control = trueValue) => { - // only reset loading state in first request - if (control && isFirstRequest) { - loadingState.v = falseValue; - } - controlledLoading = control; - }; - // Call middleware function - const middlewareCompletePromise = isFetcher - ? middleware({ - ...commonContext, - args: sendCallingArgs, - fetch: (methodInstance, ...args) => { - assertMethod(currentHookAssert, methodInstance); - return useHookToSendRequest(hookInstance, methodInstance, args); - }, - proxyStates: omit(frontStates, 'data'), - controlLoading - }, guardNext) - : middleware({ - ...commonContext, - args: sendCallingArgs, - send: (...args) => useHookToSendRequest(hookInstance, methodHandler, args), - proxyStates: frontStates, - controlLoading - }, guardNext); - let finallyResponse = undefinedValue; - const baseEvent = (AlovaEventBase).spawn(methodInstance, sendCallingArgs); - try { - // Unified processing of responses - const middlewareReturnedData = await middlewareCompletePromise; - const afterSuccess = (data) => { - // Update cached response data - if (!isFetcher) { - toUpdateResponse() && (dataState.v = data); - } - else if (hookInstance.c.updateState !== falseValue) { - // Update the status in the cache, usually entered in use fetcher - const cachedState = getStateCache(id, methodKey).s; - cachedState && (cachedState.data.v = data); - } - // If the response data needs to be updated, the corresponding callback function is triggered after the request. - if (toUpdateResponse()) { - errorState.v = undefinedValue; - // Loading status will no longer change to false when controlled - !controlledLoading && (loadingState.v = falseValue); - hookInstance.em.emit(KEY_SUCCESS, newInstance((AlovaSuccessEvent), baseEvent, data, fromCache())); - hookInstance.em.emit(KEY_COMPLETE, newInstance((AlovaCompleteEvent), baseEvent, KEY_SUCCESS, data, fromCache(), undefinedValue)); - } - return data; - }; - finallyResponse = - // When no data is returned or undefined is returned in the middleware, get the real response data - // Otherwise, use the returned data and no longer wait for the response promise. At this time, you also need to call the response callback. - middlewareReturnedData !== undefinedValue - ? afterSuccess(middlewareReturnedData) - : isNextCalled - ? // There are two possibilities when middlewareCompletePromise is resolve - // 1. The request is normal - // 2. The request is incorrect, but the error is captured by the middleware function. At this time, the success callback will also be called, that is, afterSuccess(undefinedValue) - await promiseThen(responseHandlePromise, afterSuccess, () => afterSuccess(undefinedValue)) - : // If is next called is not called, no data is returned - undefinedValue; - // When the next function is not called, update loading to false. - !isNextCalled && !controlledLoading && (loadingState.v = falseValue); - } - catch (error) { - if (toUpdateResponse()) { - // Controls the output of error messages - errorState.v = error; - // Loading status will no longer change to false when controlled - !controlledLoading && (loadingState.v = falseValue); - hookInstance.em.emit(KEY_ERROR, newInstance((AlovaErrorEvent), baseEvent, error)); - hookInstance.em.emit(KEY_COMPLETE, newInstance((AlovaCompleteEvent), baseEvent, KEY_ERROR, undefinedValue, fromCache(), error)); - } - throw error; - } - // Unbind download and upload events after responding - offDownloadEvent(); - offUploadEvent(); - return finallyResponse; - })(); -} - -const refCurrent = (ref) => ref.current; -/** - * Create request status and uniformly process consistent logic in useRequest, useWatcher, and useFetcher - * This function will call the creation function of statesHook to create the corresponding request state. - * When the value is empty, it means useFetcher enters, and data status and cache status are not needed at this time. - * @param methodInstance request method object - * @param useHookConfig hook request configuration object - * @param initialData Initial data data - * @param immediate Whether to initiate a request immediately - * @param watchingStates The monitored status, if not passed in, call handleRequest directly. - * @param debounceDelay Delay time for request initiation - * @returns Current request status, operation function and event binding function - */ -function createRequestState(hookType, methodHandler, useHookConfig, initialData, immediate = falseValue, watchingStates, debounceDelay = 0) { - var _a; - // shallow clone config object to avoid passing the same useHookConfig object which may cause vue2 state update error - useHookConfig = { ...useHookConfig }; - const { __referingObj: referingObject = { trackedKeys: {}, bindError: falseValue } } = useHookConfig; - let initialLoading = !!immediate; - let cachedResponse = undefinedValue; - // When sending a request immediately, you need to determine the initial loading value by whether to force the request and whether there is a cache. This has the following two benefits: - // 1. Sending the request immediately under react can save one rendering time - // 2. In the HTML rendered by SSR, the initial view is in the loading state to avoid the loading view flashing when displayed on the client. - if (immediate) { - // An error may be reported when calling the get handler method, and try/catch is required. - try { - const methodInstance = getHandlerMethod$1(methodHandler, coreHookAssert(hookType)); - const alovaInstance = getContext(methodInstance); - const l1CacheResult = alovaInstance.l1Cache.get(buildNamespacedCacheKey(alovaInstance.id, getMethodInternalKey(methodInstance))); - // The cache is only checked synchronously, so it does not take effect on asynchronous l1Cache adapters. - // It is recommended not to set up the asynchronous l1Cache adapter on the client side - if (l1CacheResult && !instanceOf(l1CacheResult, PromiseCls)) { - const [data, expireTimestamp] = l1CacheResult; - // If there is no expiration time, it means that the data will never expire. Otherwise, you need to determine whether it has expired. - if (!expireTimestamp || expireTimestamp > getTime()) { - cachedResponse = data; - } - } - const forceRequestFinally = sloughConfig((_a = useHookConfig.force) !== null && _a !== void 0 ? _a : falseValue); - initialLoading = !!forceRequestFinally || !cachedResponse; - } - catch (_b) { } - } - const { create, effectRequest, ref, objectify, exposeProvider, transformState2Proxy } = statesHookHelper(promiseStatesHook(), referingObject); - const progress = { - total: 0, - loaded: 0 - }; - // Put the externally incoming supervised states into the front states collection together - const { managedStates = {} } = useHookConfig; - const managedStatesProxy = mapObject(managedStates, (state, key) => transformState2Proxy(state, key)); - const data = create(cachedResponse !== null && cachedResponse !== void 0 ? cachedResponse : (isFn(initialData) ? initialData() : initialData), 'data'); - const loading = create(initialLoading, 'loading'); - const error = create(undefinedValue, 'error'); - const downloading = create({ ...progress }, 'downloading'); - const uploading = create({ ...progress }, 'uploading'); - const frontStates = objectify([data, loading, error, downloading, uploading]); - const eventManager = createEventManager(); - const hookInstance = refCurrent(ref(createHook(hookType, useHookConfig, eventManager, referingObject))); - /** - * ## react ##Every time the function is executed, the following items need to be reset - */ - hookInstance.fs = frontStates; - hookInstance.em = eventManager; - hookInstance.c = useHookConfig; - hookInstance.ms = managedStatesProxy; - const hasWatchingStates = watchingStates !== undefinedValue; - // Initialize request event - // Unified send request function - const handleRequest = (handler = methodHandler, sendCallingArgs) => useHookToSendRequest(hookInstance, handler, sendCallingArgs); - // only call once when multiple values changed at the same time - const onceRunner = refCurrent(ref(createSyncOnceRunner())); - // Call handleRequest in a way that catches the exception - // Catching exceptions prevents exceptions from being thrown out - const wrapEffectRequest = (ro = referingObject, handler) => { - onceRunner(() => { - promiseCatch(handleRequest(handler), error => { - // the error tracking indicates that the error need to throw. - if (!ro.bindError && !ro.trackedKeys.error) { - throw error; - } - }); - }); - }; - /** - * fix: #421 - * Use ref wraps to prevent react from creating new debounce function in every render - * Explicit passing is required because the context will change - */ - const debouncingSendHandler = ref(debounce((_, ro, handler) => wrapEffectRequest(ro, handler), (changedIndex) => isNumber(changedIndex) ? (isArray(debounceDelay) ? debounceDelay[changedIndex] : debounceDelay) : 0)); - // Do not send requests when rendering on the server side - if (!globalConfigMap.ssr) { - effectRequest({ - handler: - // When `watchingStates` is an array, it indicates the watching states (including an empty array). When it is undefined, it indicates the non-watching state. - hasWatchingStates - ? (changedIndex) => debouncingSendHandler.current(changedIndex, referingObject, methodHandler) - : () => wrapEffectRequest(referingObject), - removeStates: () => forEach(hookInstance.rf, fn => fn()), - saveStates: states => forEach(hookInstance.sf, fn => fn(states)), - frontStates: { ...frontStates, ...managedStatesProxy }, - watchingStates, - immediate: immediate !== null && immediate !== void 0 ? immediate : trueValue - }); - } - return exposeProvider({ - ...objectify([data, loading, error, downloading, uploading]), - abort: () => hookInstance.m && hookInstance.m.abort(), - /** - * Manually initiate a request by executing this method - * @param sendCallingArgs Parameters passed in when calling the send function - * @param methodInstance method object - * @param isFetcher Whether to call isFetcher - * @returns Request promise - */ - send: (sendCallingArgs, methodInstance) => handleRequest(methodInstance, sendCallingArgs), - onSuccess(handler) { - eventManager.on(KEY_SUCCESS, handler); - }, - onError(handler) { - // will not throw error when bindError is true. - // it will reset in `exposeProvider` so that ignore the error binding in custom use hooks. - referingObject.bindError = trueValue; - eventManager.on(KEY_ERROR, handler); - }, - onComplete(handler) { - eventManager.on(KEY_COMPLETE, handler); - } - }); -} - -/** - * Fetch request data and cache request method object - */ -function useFetcher(config = {}) { - const props = createRequestState(EnumHookType.USE_FETCHER, noop, config); - const { send } = props; - deleteAttr(props, 'send'); - return objAssign(props, { - /** - * Fetch data fetch will definitely send a request, and if the currently requested data has a corresponding management state, this state will be updated. - * @param matcher Method object - */ - fetch: (matcher, ...args) => { - assertMethod(fetcherHookAssert, matcher); - return send(args, matcher); - } - }); -} - -function useRequest(handler, config = {}) { - const { immediate = trueValue, initialData } = config; - const props = createRequestState(EnumHookType.USE_REQUEST, handler, config, initialData, !!immediate); - const { send } = props; - return objAssign(props, { - send: (...args) => send(args) - }); -} - -function useWatcher(handler, watchingStates, config = {}) { - watcherHookAssert(watchingStates && len(watchingStates) > 0, 'expected at least one watching state'); - const { immediate, debounce = 0, initialData } = config; - const props = createRequestState(EnumHookType.USE_WATCHER, handler, config, initialData, !!immediate, // !!immediate means not send request immediately - watchingStates, debounce); - const { send } = props; - return objAssign(props, { - send: (...args) => send(args) - }); -} - -var createSnapshotMethodsManager = (handler) => { - let methodSnapshots = {}; - return { - snapshots: () => methodSnapshots, - save(methodInstance, force = falseValue) { - const key = getMethodInternalKey(methodInstance); - // Because it is impossible to locate the location of the total data in the cache - // Therefore, this field is maintained redundantly here. - if (!methodSnapshots[key] || force) { - methodSnapshots[key] = { - entity: methodInstance - }; - } - }, - get: (entityOrPage) => methodSnapshots[getMethodInternalKey(instanceOf(entityOrPage, (Method)) ? entityOrPage : handler(entityOrPage))], - remove(key) { - if (key) { - delete methodSnapshots[key]; - } - else { - methodSnapshots = {}; - } - } - }; -}; - -const paginationAssert = createAssert('usePagination'); -const indexAssert = (index, rawData) => paginationAssert(isNumber(index) && index < len(rawData), 'index must be a number that less than list length'); -const parseSendArgs = (args) => [ - args[args.length - 2], // refreshPage - args[args.length - 1], // isRefresh - args.slice(0, args.length - 2) // send args -]; -var usePagination = (handler, config = {}) => { - const { create, computed, ref, watch, exposeProvider, objectify, __referingObj: referingObject } = statesHookHelper(promiseStatesHook()); - const { preloadPreviousPage = trueValue, preloadNextPage = trueValue, total: totalGetter = res => res.total, data: dataGetter = res => res.data, append = falseValue, initialPage = 1, initialPageSize = 10, watchingStates = [], initialData, immediate = trueValue, middleware, force = noop, ...others } = config; - const handlerRef = ref(handler); - const isReset = ref(falseValue); // Used to control whether to reset - // The number of requests during reset. In order to prevent repeated requests during reset, use this parameter to limit requests. - const page = create(initialPage, 'page'); - const pageSize = create(initialPageSize, 'pageSize'); - const data = create((initialData ? dataGetter(initialData) || [] : []), 'data'); - const total = create(initialData ? totalGetter(initialData) : undefinedValue, 'total'); - // Save snapshots of all method instances used by the current hook - const { snapshots: methodSnapshots, get: getSnapshotMethods, save: saveSnapshot, remove: removeSnapshot } = ref(createSnapshotMethodsManager(page => handlerRef.current(page, pageSize.v))).current; - const listDataGetter = (rawData) => dataGetter(rawData) || rawData; - // Initialize fetcher - const fetchStates = useFetcher({ - __referingObj: referingObject, - updateState: falseValue, - force: ({ args }) => args[len(args) - 1] - }); - const { loading, fetch, abort: abortFetch, onSuccess: onFetchSuccess } = fetchStates; - const fetchingRef = ref(loading); - const getHandlerMethod = (refreshPage = page.v, customArgs = []) => { - const handlerMethod = handler(refreshPage, pageSize.v, ...customArgs); - // Define unified additional names to facilitate management - saveSnapshot(handlerMethod); - return handlerMethod; - }; - // When monitoring status changes, reset page to 1 - watch(watchingStates, () => { - page.v = initialPage; - isReset.current = trueValue; - }); - // Compatible with react, store functions that require proxy here - // In this way, the latest operation function can be called in the proxy function and avoid the react closure trap. - const delegationActions = ref({}); - // Calculate data, total, is last page parameters - const pageCount = computed(() => { - const totalVal = total.v; - return totalVal !== undefinedValue ? Math.ceil(totalVal / pageSize.v) : undefinedValue; - }, [pageSize, total], 'pageCount'); - const createDelegationAction = (actionName) => (...args) => delegationActions.current[actionName](...args); - const states = useWatcher((...args) => { - const [refreshPage, , customArgs] = parseSendArgs(args); - return getHandlerMethod(refreshPage, customArgs); - }, [...watchingStates, page.e, pageSize.e], { - __referingObj: referingObject, - immediate, - initialData, - managedStates: objectify([data, page, pageSize, total], 's'), - middleware(ctx, next) { - if (!middleware) { - return next(); - } - return middleware({ - ...ctx, - delegatingActions: { - refresh: createDelegationAction('refresh'), - insert: createDelegationAction('insert'), - remove: createDelegationAction('remove'), - replace: createDelegationAction('replace'), - reload: createDelegationAction('reload'), - getState: (stateKey) => { - const states = { - page, - pageSize, - data, - pageCount, - total, - // eslint-disable-next-line @typescript-eslint/no-use-before-define - isLastPage - }; - return states[stateKey].v; - } - } - }, next); - }, - force: event => event.args[1] || (isFn(force) ? force(event) : force), - ...others - }); - const { send } = states; - const nestedData = states.__proxyState('data'); - // Determine whether data can be preloaded - const canPreload = async (payload) => { - const { rawData = nestedData.v, preloadPage, fetchMethod, forceRequest = falseValue, isNextPage = falseValue } = payload; - const pageCountVal = pageCount.v; - const exceedPageCount = pageCountVal - ? preloadPage > pageCountVal - : isNextPage // If it is judged to preload the next page of data and there is no page count, it is judged by whether the data volume of the last page reaches the page size. - ? len(listDataGetter(rawData)) < pageSize.v - : falseValue; - const isMatchPageScope = preloadPage > 0 && !exceedPageCount; - if (!isMatchPageScope) { - return falseValue; - } - const { e: expireMilliseconds } = getLocalCacheConfigParam(fetchMethod); - const hasCache = await queryCache(fetchMethod); - // If the cache time is less than or equal to the current time, it means that the cache is not set and the data will no longer be pre-pulled at this time. - // Or there is already a cache and it is not pre-fetched. - return expireMilliseconds(MEMORY) <= getTime() ? falseValue : forceRequest || !hasCache; - }; - // Preload next page data - const fetchNextPage = async (rawData, force, customArgs = []) => { - const nextPage = page.v + 1; - const fetchMethod = getHandlerMethod(nextPage, customArgs); - if (preloadNextPage && - (await canPreload({ - rawData, - preloadPage: nextPage, - fetchMethod, - isNextPage: trueValue, - forceRequest: force - }))) { - promiseCatch(fetch(fetchMethod, ...customArgs, force), noop); - } - }; - // Preload previous page data - const fetchPreviousPage = async (rawData, customArgs = []) => { - const prevPage = page.v - 1; - const fetchMethod = getHandlerMethod(prevPage, customArgs); - if (preloadPreviousPage && - (await canPreload({ - rawData, - preloadPage: prevPage, - fetchMethod - }))) { - promiseCatch(fetch(fetchMethod, ...customArgs, undefinedValue), noop); - } - }; - // If the returned data is smaller than the page size, it is considered the last page. - const isLastPage = computed(() => { - const dataRaw = nestedData.v; - if (!dataRaw) { - return trueValue; - } - const statesDataVal = listDataGetter(dataRaw); - const pageVal = page.v; - const pageCountVal = pageCount.v; - const dataLen = isArray(statesDataVal) ? len(statesDataVal) : 0; - return pageCountVal ? pageVal >= pageCountVal : dataLen < pageSize.v; - }, [page, pageCount, nestedData, pageSize], 'isLastPage'); - // Update current page cache - const updateCurrentPageCache = async () => { - const snapshotItem = getSnapshotMethods(page.v); - if (snapshotItem) { - await setCache(snapshotItem.entity, (rawData) => { - // When caching is turned off, raw data is undefined - if (rawData) { - const cachedListData = listDataGetter(rawData) || []; - splice(cachedListData, 0, len(cachedListData), ...data.v); - return rawData; - } - }); - } - }; - onFetchSuccess(({ method, data: rawData }) => { - // When fetch has not responded yet and the page is flipped to the page number corresponding to fetch, the list data needs to be updated manually. - const snapshotItem = getSnapshotMethods(page.v); - if (snapshotItem && getMethodInternalKey(snapshotItem.entity) === getMethodInternalKey(method)) { - // If data is appended, data is updated - const listData = listDataGetter(rawData); // Update data parameters - if (append) { - // The current page data needs to be replaced during pull-down loading. - const dataRaw = data.v; - const pageSizeVal = pageSize.v; - // When performing a removal operation, the number of replacements is less than pageSize, and dataRaw % pageSizeVal will be greater than 0. - // When adding a new operation, the number of replacements is equal to pageSize. At this time, dataRaw % pageSizeVal will be equal to 0. No replacement is needed at this time. - const replaceNumber = len(dataRaw) % pageSizeVal; - if (replaceNumber > 0) { - const rawData = [...data.v]; - splice(rawData, (page.v - 1) * pageSizeVal, replaceNumber, ...listData); - data.v = rawData; - } - } - else { - data.v = listData; - } - } - }); - const awaitResolve = ref(undefinedValue); - const awaitReject = ref(undefinedValue); - states - .onSuccess(({ data: rawData, args, method }) => { - const [refreshPage, isRefresh, customArgs] = parseSendArgs(args); - const { total: cachedTotal } = getSnapshotMethods(method) || {}; - const typedRawData = rawData; - total.v = cachedTotal !== undefinedValue ? cachedTotal : totalGetter(typedRawData); - if (!isRefresh) { - fetchPreviousPage(typedRawData, customArgs); - fetchNextPage(typedRawData, falseValue, customArgs); - } - const pageSizeVal = pageSize.v; - const listData = listDataGetter(typedRawData); // Get array - paginationAssert(isArray(listData), 'Got wrong array, did you return the correct array of list in `data` function'); - // If data is appended, data is updated - if (append) { - // If it is reset, clear the data first - if (isReset.current) { - data.v = []; - } - if (refreshPage === undefinedValue) { - data.v = [...data.v, ...listData]; - } - else if (refreshPage) { - const rawData = [...data.v]; - // If the page is refreshed, the data on that page is replaced. - splice(rawData, (refreshPage - 1) * pageSizeVal, pageSizeVal, ...listData); - data.v = rawData; - } - } - else { - data.v = listData; - } - }) - .onSuccess(({ data }) => { - var _a; - (_a = awaitResolve.current) === null || _a === void 0 ? void 0 : _a.call(awaitResolve, data); - }) - .onError(({ error }) => { - var _a; - (_a = awaitReject.current) === null || _a === void 0 ? void 0 : _a.call(awaitReject, error); - }) - .onComplete(() => { - // Whether the request is successful or not, it must be reset is reset - isReset.current = falseValue; - }); - // Get the location of a list item - const getItemIndex = (item) => { - const index = data.v.indexOf(item); - paginationAssert(index >= 0, 'item is not found in list'); - return index; - }; - const { addQueue: add2AsyncQueue, onComplete: onAsyncQueueRunComplete } = ref(createAsyncQueue()).current; - /** - * Refresh the specified page number data. This function will ignore the cache and force the request to be sent. - * If no page number is passed in, the current page will be refreshed. - * If a list item is passed in, the page where the list item is located will be refreshed, which is only valid in append mode. - * @param pageOrItemPage Refreshed page number or list item - */ - const refresh = async (pageOrItemPage = page.v) => { - let refreshPage = pageOrItemPage; - let awaitPromise = promiseResolve(); - if (append) { - if (!isNumber(pageOrItemPage)) { - const itemIndex = getItemIndex(pageOrItemPage); - refreshPage = Math.floor(itemIndex / pageSize.v) + 1; - } - paginationAssert(refreshPage <= page.v, "refresh page can't greater than page"); - // Update current page data - awaitPromise = send(refreshPage, trueValue); - } - else { - paginationAssert(isNumber(refreshPage), 'unable to calculate refresh page by item in pagination mode'); - // If the number of pages is equal, refresh the current page, otherwise fetch data - awaitPromise = - refreshPage === page.v - ? send(undefinedValue, trueValue) - : fetch(handler(refreshPage, pageSize.v), trueValue); - } - return awaitPromise; - }; - // Delete all related caches except the current page and next page of this usehook - const invalidatePaginationCache = async (all = falseValue) => { - const pageVal = page.v; - const snapshotObj = methodSnapshots(); - let snapshots = objectValues(snapshotObj); - if (all) { - removeSnapshot(); - } - else { - // Filter out data from the previous page, current page, and next page - const excludeSnapshotKeys = mapItem(filterItem([getSnapshotMethods(pageVal - 1), getSnapshotMethods(pageVal), getSnapshotMethods(pageVal + 1)], Boolean), ({ entity }) => getMethodInternalKey(entity)); - snapshots = mapItem(filterItem(objectKeys(snapshotObj), key => !includes(excludeSnapshotKeys, key)), key => { - const item = snapshotObj[key]; - delete snapshotObj[key]; - return item; - }); - } - await invalidateCache(mapItem(snapshots, ({ entity }) => entity)); - }; - // The reason for taking it out separately is that - // No matter how many times insert, remove, or a combination of them is called synchronously, the reset operation only needs to be executed asynchronously once - const resetCache = async () => { - fetchingRef.current && abortFetch(); - // cache invalidation - await invalidatePaginationCache(); - // When the amount of data on the next page does not exceed the page size, the next page is forced to be requested. Because there is a request for sharing, the fetching needs to be performed asynchronously after interrupting the request. - const snapshotItem = getSnapshotMethods(page.v + 1); - if (snapshotItem) { - const cachedListData = listDataGetter((await queryCache(snapshotItem.entity)) || {}) || []; - fetchNextPage(undefinedValue, len(cachedListData) < pageSize.v); - } - }; - // Unified update of total number of items - const updateTotal = (offset) => { - if (offset === 0) { - return; - } - // Update current page - const totalVal = total.v; - if (isNumber(totalVal)) { - const offsetedTotal = Math.max(totalVal + offset, 0); - total.v = offsetedTotal; - const pageVal = page.v; - // Update redundant total field - forEach([getSnapshotMethods(pageVal - 1), getSnapshotMethods(pageVal), getSnapshotMethods(pageVal + 1)], item => { - item && (item.total = offsetedTotal); - }); - } - }; - /** - * Insert a piece of data - * If no index is passed in, it will be inserted at the front by default. - * If a list item is passed in, it will be inserted after the list item. If the list item is not in the list data, an error will be thrown. - * @param item insert - * @param position Insert position (index) or list item - */ - const insert = (item, position = 0) => { - onAsyncQueueRunComplete(resetCache); // The cache needs to be reset at the end of execution - return add2AsyncQueue(async () => { - const index = isNumber(position) ? position : getItemIndex(position) + 1; - let popItem = undefinedValue; - const rawData = [...data.v]; - // Only when the number of items currently displayed is exactly a multiple of page size, you need to remove an item of data to ensure that the number of operating pages is page size. - if (len(rawData) % pageSize.v === 0) { - popItem = rawData.pop(); - } - // If the insertion position is empty, it will be inserted to the front by default. - splice(rawData, index, 0, item); - data.v = rawData; - updateTotal(1); - // The cache of the current page is updated synchronously - await updateCurrentPageCache(); - // If there is a pop item, put it at the head of the next page cache, consistent with the remove operation. - // In this way, the performance will be consistent when insert and remove are called synchronously. - if (popItem) { - const snapshotItem = getSnapshotMethods(page.v + 1); - if (snapshotItem) { - await setCache(snapshotItem.entity, (rawData) => { - if (rawData) { - const cachedListData = listDataGetter(rawData) || []; - cachedListData.unshift(popItem); - cachedListData.pop(); - return rawData; - } - }); - } - } - }); - }; - /** - * Remove a piece of data - * If a list item is passed in, the list item will be removed. If the list item is not in the list data, an error will be thrown. - * @param position Removed index or list item - */ - const remove = (...positions) => { - onAsyncQueueRunComplete(resetCache); // The cache needs to be reset at the end of execution - return add2AsyncQueue(async () => { - const indexes = mapItem(positions, position => { - const index = isNumber(position) ? position : getItemIndex(position); - indexAssert(index, data.v); - return index; - }); - const pageVal = page.v; - const nextPage = pageVal + 1; - const snapshotItem = getSnapshotMethods(nextPage); - const fillingItems = []; // padding data item - if (snapshotItem) { - await setCache(snapshotItem.entity, (rawData) => { - if (rawData) { - const cachedListData = listDataGetter(rawData); - // Start filling data from the head of the list on the next page - if (isArray(cachedListData)) { - pushItem(fillingItems, ...splice(cachedListData, 0, len(indexes))); - } - return rawData; - } - }); - } - const isLastPageVal = isLastPage.v; - const fillingItemsLen = len(fillingItems); - let isLastEmptyPageInNonAppendMode = false; - if (fillingItemsLen > 0 || isLastPageVal) { - // Delete data at the specified index - const newListData = filterItem(data.v, (_, index) => !includes(indexes, index)); - // In page turning mode, if it is the last page and all items have been deleted, then turn one page forward. - isLastEmptyPageInNonAppendMode = !append && isLastPageVal && len(newListData) <= 0; - if (!isLastEmptyPageInNonAppendMode && fillingItemsLen > 0) { - pushItem(newListData, ...fillingItems); - } - data.v = newListData; - } - else if (fillingItemsLen <= 0 && !isLastPageVal) { - // When the last page of data is removed, there is no need to refresh - refresh(pageVal); - } - updateTotal(-len(indexes)); - // The cache of the current page is updated synchronously - return updateCurrentPageCache().then(() => { - if (isLastEmptyPageInNonAppendMode) { - page.v = pageVal - 1; - } - }); - }); - }; - /** - * Replace a piece of data - * If the position passed in is a list item, this list item will be replaced. If the list item is not in the list data, an error will be thrown. - * @param item replacement - * @param position Replace position (index) or list item - */ - const replace = (item, position) => add2AsyncQueue(async () => { - paginationAssert(position !== undefinedValue, 'expect specify the replace position'); - const index = isNumber(position) ? position : getItemIndex(position); - indexAssert(index, data.v); - const rawData = [...data.v]; - splice(rawData, index, 1, item); - data.v = rawData; - // The cache of the current page is updated synchronously - await updateCurrentPageCache(); - }); - /** - * Reload the list starting from page ${initialPage} and clear the cache - */ - const reload = async () => { - await invalidatePaginationCache(trueValue); - isReset.current = trueValue; - page.v === initialPage ? promiseCatch(send(), noop) : (page.v = initialPage); - const { resolve, reject, promise } = usePromise(); - awaitResolve.current = resolve; - awaitReject.current = reject; - return promise; - }; - // Compatible with react, caches the latest operation function each time, avoiding closure traps - delegationActions.current = { - refresh, - insert, - remove, - replace, - reload - }; - /** @Returns */ - return exposeProvider({ - ...states, - ...objectify([data, page, pageCount, pageSize, total, isLastPage]), - send: (...args) => send(...args, undefinedValue, undefinedValue), - fetching: fetchStates.loading, - onFetchSuccess: fetchStates.onSuccess, - onFetchError: fetchStates.onError, - onFetchComplete: fetchStates.onComplete, - refresh, - insert, - remove, - replace, - reload - }); -}; - -/** - * Assert serialHandlers - * @param hookName hook name - * @param serialHandlers Serial request method acquisition function - */ -const assertSerialHandlers = (hookName, serialHandlers) => createAssert(hookName)(isArray(serialHandlers) && len(serialHandlers) > 0, 'please use an array to represent serial requests'); -/** - * Create serial request middleware - * @param serialHandlers Serial request method acquisition function - * @param hookMiddleware use hook middleware - * @returns Serial request middleware - */ -const serialMiddleware = (serialHandlers, hookMiddleware, serialRequestMethods = []) => { - // The first handler is passed to the use hook externally and does not need to be requested again. - serialHandlers.shift(); - return ((ctx, next) => { - hookMiddleware === null || hookMiddleware === void 0 ? void 0 : hookMiddleware(ctx, () => promiseResolve(undefinedValue)); - ctx.controlLoading(); - const loadingState = ctx.proxyStates.loading; - loadingState.v = trueValue; - let serialPromise = next(); - for (const handler of serialHandlers) { - serialPromise = promiseThen(serialPromise, value => { - const methodItem = handler(value, ...ctx.args); - pushItem(serialRequestMethods, methodItem); - return methodItem.send(); - }); - } - return serialPromise.finally(() => { - loadingState.v = falseValue; - }); - }); -}; - -/** - * Serial request hook, each serialHandlers will receive the result of the previous request - * Applicable scenario: Serial request for a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialRequest related data and operation functions - */ -var useSerialRequest = (serialHandlers, config = {}) => { - assertSerialHandlers('useSerialRequest', serialHandlers); - // eslint-disable-next-line - const { ref, __referingObj } = statesHookHelper(promiseStatesHook()); - const methods = ref([]).current; - const exposures = useRequest(serialHandlers[0], { - ...config, - __referingObj, - middleware: serialMiddleware(serialHandlers, config.middleware, methods) - }); - // Decorate the error callback function and set event.method to the instance of the error - exposures.onError = decorateEvent(exposures.onError, (handler, event) => { - event.method = methods[len(methods) - 1]; - handler(event); - }); - return exposures; -}; - -/** - * Serial request hook, each serialHandlers will receive the result of the previous request - * Applicable scenario: After monitoring status changes, serially request a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialRequest related data and operation functions - */ -var useSerialWatcher = (serialHandlers, watchingStates, config = {}) => { - assertSerialHandlers('useSerialWatcher', serialHandlers); - // eslint-disable-next-line - const { ref, __referingObj } = statesHookHelper(promiseStatesHook()); - const methods = ref([]).current; - const exposures = useWatcher(serialHandlers[0], watchingStates, { - ...config, - __referingObj, - middleware: serialMiddleware(serialHandlers, config.middleware, methods) - }); - // Decorate the error callback function and set event.method to the instance of the error - exposures.onError = decorateEvent(exposures.onError, (handler, event) => { - event.method = methods[len(methods) - 1]; - handler(event); - }); - return exposures; -}; - -const STR_VALUE_OF = 'valueOf'; -const DEFAULT_QUEUE_NAME = 'default'; -const BEHAVIOR_SILENT = 'silent'; -const BEHAVIOR_QUEUE = 'queue'; -const BEHAVIOR_STATIC = 'static'; -/** - * Global virtual data collection array - * It will only be an array when the method is created, and undefined at other times - * - * Explanation: The purpose of collecting virtual data is to determine whether virtual data is used in a method instance. - * Includes the following forms: - * useSQRequest((vDataId) => createMethod({ vDataId }) //Reference function parameters - * useSQRequest(() => createMethod({ vDataId }) //Directly reference scope parameters - * - * Or even: - * function createMethod(obj) { - * return alovaInst.Get('/list', { - * params: { status: obj.vDataId ? 1 : 0 } - * }) - * } - * useSQRequest(() => createMethod(obj) //Directly reference scope parameters - * - * Ways to use dummy data include: - * 1. Directly assign values as parameters - * 2. Use dummy data id - * 3. Indirect use of virtual data, such as - * vData ? 1 : 0 - * !!vData - * vData+1 - * etc. as calculation parameters. - */ -let vDataIdCollectBasket; -const setVDataIdCollectBasket = (value) => { - vDataIdCollectBasket = value; -}; -/** - * The dependent alova instance, its storage adapter, request adapter, etc. will be used to access the SilentMethod instance and send silent submissions - */ -let dependentAlovaInstance; -const setDependentAlova = (alovaInst) => { - dependentAlovaInstance = alovaInst; -}; -/** - * Set up a custom serializer - */ -let customSerializers = {}; -const setCustomSerializers = (serializers = {}) => { - customSerializers = serializers; -}; -/** - * silentFactory status - * 0 means not started - * 1 means in progress, changed after calling bootSilentFactory - * 2 indicates that the request failed, that is, when the maximum number of requests is reached according to the retry rules, or when the retry rules are not matched, the request is changed. - */ -let silentFactoryStatus = 0; -const setSilentFactoryStatus = (status) => { - silentFactoryStatus = status; -}; -/** - * The request waiting time in silentQueue, in milliseconds (ms) - * It indicates the waiting time of the silentMethod that is about to send the request - * If not set, or set to 0, the silentMethod request is triggered immediately - * - * Tips: - * 1. When set directly, it is effective for the default queue by default. - * 2. If you need to set other queue settings, you can specify them as objects, such as: - * [ - * Indicates waiting 5000ms for the queue setting request named customName - * { name: 'customName', wait: 5000 }, - * - * //Indicates that in all queues with the prefix prefix, the request setting with method instance name xxx is set to wait 5000ms - * { name: /^prefix/, wait: silentMethod => silentMethod.entity.config.name === 'xxx' ? 5000 : 0 }, - * ] - * - * >>> It only works if the request succeeds, if it fails it will use the retry policy parameters - */ -let queueRequestWaitSetting = []; -const setQueueRequestWaitSetting = (requestWaitSetting = 0) => { - queueRequestWaitSetting = isArray(requestWaitSetting) - ? requestWaitSetting - : [ - { - queue: DEFAULT_QUEUE_NAME, - wait: requestWaitSetting - } - ]; -}; -const BootEventKey = Symbol('GlobalSQBoot'); -const BeforeEventKey = Symbol('GlobalSQBefore'); -const SuccessEventKey = Symbol('GlobalSQSuccess'); -const ErrorEventKey = Symbol('GlobalSQError'); -const FailEventKey$1 = Symbol('GlobalSQFail'); -/** Global silent event management object */ -const globalSQEventManager = createEventManager(); -/** Silent assert */ -const silentAssert = createAssert('useSQRequest'); - -/** - * Update the status of the corresponding method - * @param method request method object - * @param handleUpdate update callback - * @returns Whether the update is successful or not. If the corresponding status is not found, the update will not be successful. - */ -async function updateState(matcher, handleUpdate) { - let updated = falseValue; - // Only process the first method instance that meets the conditions. If there is no instance that meets the conditions, it will not be processed. - if (matcher) { - const { update } = promiseStatesHook(); - const methodKey = getMethodInternalKey(matcher); - const { id } = getContext(matcher); - const { s: frontStates, h: hookInstance } = getStateCache(id, methodKey); - const updateStateCollection = isFn(handleUpdate) - ? { data: handleUpdate } - : handleUpdate; - let updatedDataColumnData = undefinedValue; - if (frontStates) { - // Loop through the updated data and assign it to the supervised state - forEach(objectKeys(updateStateCollection), stateName => { - coreAssert(stateName in frontStates, `state named \`${stateName}\` is not found`); - const targetStateProxy = frontStates[stateName]; - let updatedData = updateStateCollection[stateName](targetStateProxy.v); - // shallow clone the updatedData so that can effect in react. - updatedData = isArray(updatedData) - ? [...updatedData] - : isObject(updatedData) - ? { ...updatedData } - : updatedData; - // Record the updated value of the data field, used to update cached data - if (stateName === 'data') { - updatedDataColumnData = updatedData; - } - // Update directly using update without checking referring object.tracked keys - update(updatedData, frontStates[stateName].s, stateName, hookInstance.ro); - }); - updated = trueValue; - } - // If data is updated, cache and persistent data need to be updated at the same time - if (updatedDataColumnData !== undefinedValue) { - setCache(matcher, updatedDataColumnData); - } - } - return updated; -} - -var dateSerializer = { - forward: data => (instanceOf(data, Date) ? data.getTime() : undefinedValue), - backward: ts => newInstance(Date, ts) -}; - -var regexpSerializer = { - forward: data => (instanceOf(data, RegExp) ? data.source : undefined), - backward: source => newInstance(RegExp, source) -}; - -const createSerializerPerformer = (customSerializers = {}) => { - /** - * Merge built-in serializers and custom serializers - */ - const serializers = { - date: dateSerializer, - regexp: regexpSerializer, - ...customSerializers - }; - /** - * serialized data - */ - const serialize = (payload) => { - if (isObject(payload)) { - payload = walkObject(isArray(payload) ? [...payload] : { ...payload }, value => { - let finallyApplySerializerName = undefinedValue; - // Find a matching serializer and serialize the value. If not found, return the original value. - const serializedValue = objectKeys(serializers).reduce((currentValue, serializerName) => { - if (!finallyApplySerializerName) { - const serializedValueItem = serializers[serializerName].forward(currentValue); - if (serializedValueItem !== undefinedValue) { - finallyApplySerializerName = serializerName; - currentValue = serializedValueItem; - } - } - return currentValue; - }, value); - // You need to use the original value to judge, otherwise packaging classes such as new Number(1) will also be [object Object] - const toStringTag = ObjectCls.prototype.toString.call(value); - if (toStringTag === '[object Object]') { - value = { ...value }; - } - else if (isArray(value)) { - value = [...value]; - } - return finallyApplySerializerName !== undefinedValue ? [finallyApplySerializerName, serializedValue] : value; - }); - } - return payload; - }; - /** - * Deserialize data - */ - const deserialize = (payload) => isObject(payload) - ? walkObject(payload, value => { - if (isArray(value) && len(value) === 2) { - const foundSerializer = serializers[value[0]]; - value = foundSerializer ? foundSerializer.backward(value[1]) : value; - } - return value; - }, falseValue) - : payload; - return { - serialize, - deserialize - }; -}; - -const symbolVDataId = Symbol('vdid'); -const symbolOriginal = Symbol('original'); -const regVDataId = /\[vd:([0-9a-z]+)\]/; - -/** - * Unified vData collection function - * It will be called in the following 4 places - * 1. When accessing sub-properties - * 2. When participating in calculation and triggering [Symbol.toPrimitive] - * 3. When getting the id of vData - * 4. When getting its original value - * - * @param returnValue Return value, if it is a function then call it - * @returns collection function - */ -const vDataCollectUnified = (target) => { - const vDataId = target === null || target === void 0 ? void 0 : target[symbolVDataId]; - vDataId && vDataIdCollectBasket && (vDataIdCollectBasket[vDataId] = undefinedValue); -}; -// export const vDataGetter = (key: string) => vDataCollectGetter((thisObj: any) => thisObj.__proto__[key].call(thisObj)); - -/** - * Dummy data is stringified. If the parameter is not dummy data, the original data is returned. - * @param target dummy data - * @param returnOriginalIfNotVData If it is not virtual data, return the original value. - * @returns Virtual data id or original data - */ -const stringifyVData = (target, returnOriginalIfNotVData = trueValue) => { - vDataCollectUnified(target); - const vDataIdRaw = target === null || target === void 0 ? void 0 : target[symbolVDataId]; - const vDataId = vDataIdRaw ? `[vd:${vDataIdRaw}]` : undefinedValue; - return vDataId || (returnOriginalIfNotVData ? target : undefinedValue); -}; -/** - * Create a getter function for virtual data id collection - * @param valueReturnFn return value function - * @returns getter function - */ -function stringifyWithThis() { - return stringifyVData(this); -} - -/** - * Null wrapper class implementation - */ -const Null = function Null() { }; -Null.prototype = ObjectCls.create(nullValue, { - [STR_VALUE_OF]: valueObject(stringifyWithThis) -}); - -/** - * Undefined wrapper class implementation - */ -const Undefined = function Undefined() { }; -Undefined.prototype = ObjectCls.create(nullValue, { - [STR_VALUE_OF]: valueObject(stringifyWithThis) -}); - -/** - * Create dummy response data - * @returns Virtual response data proxy instance - */ -var createVirtualResponse = (structure, vDataId = uuid()) => { - const transform2VData = (value, vDataIdInner = uuid()) => { - if (value === nullValue) { - value = newInstance(Null); - } - else if (value === undefinedValue) { - value = newInstance(Undefined); - } - else { - const newValue = ObjectCls(value); - defineProperty(newValue, STR_VALUE_OF, stringifyWithThis); - defineProperty(newValue, symbolOriginal, value); - value = newValue; - } - defineProperty(value, symbolVDataId, vDataIdInner); - return value; - }; - const virtualResponse = transform2VData(structure, vDataId); - if (isPlainObject(virtualResponse) || isArray(virtualResponse)) { - walkObject(virtualResponse, value => transform2VData(value)); - } - return virtualResponse; -}; - -/** - * Get original value of variable with dummy data - * This function will also perform vData collection - * @param target target value - * @param deepDehydrate Whether the depth of dehydration value - * @returns target value with primitive type - */ -const dehydrateVDataUnified = (target, deepDehydrate = trueValue) => { - const dehydrateItem = (value) => { - vDataCollectUnified(value); - if (value === null || value === void 0 ? void 0 : value[symbolVDataId]) { - if (instanceOf(value, Undefined)) { - value = undefinedValue; - } - else if (instanceOf(value, Null)) { - value = nullValue; - } - else if (instanceOf(value, Number) || instanceOf(value, String) || instanceOf(value, Boolean)) { - value = value[symbolOriginal]; - } - } - return value; - }; - const newTarget = dehydrateItem(target); - // If it is an object or array, deep traversal is required to obtain the virtual data value. - if (deepDehydrate && (isObject(newTarget) || isArray(newTarget))) { - walkObject(newTarget, value => dehydrateItem(value)); - } - return newTarget; -}; -/** - * The version above where deepDehydrate is true - */ -var dehydrateVData = (target) => dehydrateVDataUnified(target); - -const vDataKey = '__$k'; -const vDataValueKey = '__$v'; -const getAlovaStorage = () => { - // Provide prompt when silent factory is not started - silentAssert(!!dependentAlovaInstance, 'alova instance is not found, Do you forget to set `alova` or call `bootSilentFactory`?'); - return dependentAlovaInstance.l2Cache; -}; -let serializerPerformer = undefinedValue; -const silentMethodIdQueueMapStorageKey = 'alova.SQ'; // Queue collection cache key composed of Silent method instance id -const silentMethodStorageKeyPrefix = 'alova.SM.'; // silentMethod instance cache key prefix -/** - * Persistence of data collections with dummy data and serializable data - * @param key persistence key - * @param payload Persistent data - */ -const storageSetItem = async (key, payload) => { - const storage = getAlovaStorage(); - if (isObject(payload)) { - payload = walkObject(isArray(payload) ? [...payload] : { ...payload }, (value, key, parent) => { - var _a; - if (key === vDataValueKey && parent[vDataKey]) { - return value; - } - // If a silent method instance is serialized, the alova instance is filtered out - if (key === 'context' && ((_a = value === null || value === void 0 ? void 0 : value.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'Alova') { - return undefinedValue; - } - const vDataId = value === null || value === void 0 ? void 0 : value[symbolVDataId]; - let primitiveValue = dehydrateVDataUnified(value, falseValue); - // You need to use the original value to judge, otherwise packaging classes such as new Number(1) will also be [object Object] - const toStringTag = globalToString(primitiveValue); - if (toStringTag === '[object Object]') { - value = { ...value }; - primitiveValue = {}; - } - else if (isArray(value)) { - value = [...value]; - primitiveValue = []; - } - if (vDataId) { - const valueWithVData = { - [vDataKey]: vDataId, - // For objects and arrays, all their internal properties will be put to the outside through `...value`, so the internal ones do not need to be traversed and converted. - // Therefore, empty the array or object to avoid repeated conversions and contamination of the original object. - [vDataValueKey]: primitiveValue, - ...value - }; - // If it is a string type, there will be items like arrays such as 0, 1, and 2 as subscripts and values as characters, and they need to be filtered out. - if (instanceOf(value, String)) { - for (let i = 0; i < len(value); i += 1) { - valueWithVData === null || valueWithVData === void 0 ? true : delete valueWithVData[i]; - } - } - // If it is converted into virtual data, the converted value is assigned to it internally, and is uniformly processed by value in the following logic. - value = valueWithVData; - } - return value; - }); - } - serializerPerformer = serializerPerformer || createSerializerPerformer(customSerializers); - await storage.set(key, serializerPerformer.serialize(payload)); -}; -/** - * Take out the persistent data and convert the data into virtual data and serialized data - * @param key Key to persistent data - */ -const storageGetItem = async (key) => { - const storagedResponse = await getAlovaStorage().get(key); - serializerPerformer = serializerPerformer || createSerializerPerformer(customSerializers); - return isObject(storagedResponse) - ? walkObject(serializerPerformer.deserialize(storagedResponse), value => { - // Convert virtual data format back to virtual data instance - if (isObject(value) && (value === null || value === void 0 ? void 0 : value[vDataKey])) { - const vDataId = value[vDataKey]; - const vDataValue = createVirtualResponse(value[vDataValueKey], vDataId); - forEach(objectKeys(value), key => { - if (!includes([vDataKey, vDataValueKey], key)) { - vDataValue[key] = value[key]; - } - }); - value = vDataValue; - } - return value; - }, falseValue) - : storagedResponse; -}; -/** - * Remove persistent data - * @param key Key to persistent data - */ -const storageRemoveItem = async (key) => { - await getAlovaStorage().remove(key); -}; - -/** - * Serialize and save silentMethod instance - * @param silentMethodInstance silentMethod instance - */ -const persistSilentMethod = (silentMethodInstance) => storageSetItem(silentMethodStorageKeyPrefix + silentMethodInstance.id, silentMethodInstance); -/** - * Put the configuration information of silent request into the corresponding storage - * Logic: Construct a key and use this key to put the configuration information of the silent method into the corresponding storage, and then store the key in the unified management key storage. - * @param silentMethod SilentMethodInstance - * @param queue Operation queue name - */ -const push2PersistentSilentQueue = async (silentMethodInstance, queueName) => { - await persistSilentMethod(silentMethodInstance); - // Save the silent method instance id to queue storage - const silentMethodIdQueueMap = ((await storageGetItem(silentMethodIdQueueMapStorageKey)) || - {}); - const currentQueue = (silentMethodIdQueueMap[queueName] = silentMethodIdQueueMap[queueName] || []); - pushItem(currentQueue, silentMethodInstance.id); - await storageSetItem(silentMethodIdQueueMapStorageKey, silentMethodIdQueueMap); -}; -/** - * Remove or replace silentMethod instances in the cache - * @param queue Operation queue name - * @param targetSilentMethodId Target silentMethod instance id - * @param newSilentMethod The new silentMethod instance to replace. If not passed, it means deleted. - */ -const spliceStorageSilentMethod = async (queueName, targetSilentMethodId, newSilentMethod) => { - // Remove the silent method instance id from the queue - const silentMethodIdQueueMap = ((await storageGetItem(silentMethodIdQueueMapStorageKey)) || - {}); - const currentQueue = silentMethodIdQueueMap[queueName] || []; - const index = currentQueue.findIndex(id => id === targetSilentMethodId); - if (index >= 0) { - if (newSilentMethod) { - splice(currentQueue, index, 1, newSilentMethod.id); - await persistSilentMethod(newSilentMethod); - } - else { - splice(currentQueue, index, 1); - } - await storageRemoveItem(silentMethodStorageKeyPrefix + targetSilentMethodId); - // Delete this queue when it is empty - len(currentQueue) <= 0 && delete silentMethodIdQueueMap[queueName]; - if (len(objectKeys(silentMethodIdQueueMap)) > 0) { - await storageSetItem(silentMethodIdQueueMapStorageKey, silentMethodIdQueueMap); - } - else { - // Remove the queue collection when it is empty - await storageRemoveItem(silentMethodIdQueueMapStorageKey); - } - } -}; - -/** Silent method queue collection */ -let silentQueueMap = {}; -/** - * Merge queueMap into silentMethod queue collection - * @param queueMap silentMethod queue collection - */ -const merge2SilentQueueMap = (queueMap) => { - forEach(objectKeys(queueMap), targetQueueName => { - const currentQueue = (silentQueueMap[targetQueueName] = silentQueueMap[targetQueueName] || []); - pushItem(currentQueue, ...queueMap[targetQueueName]); - }); -}; -/** - * Deeply traverse the target data and replace dummy data with real data - * @param target target data - * @param vDataResponse Collection of dummy data and real data - * @returns Is there any replacement data? - */ -const deepReplaceVData = (target, vDataResponse) => { - // Search for a single value and replace a dummy data object or dummy data id with an actual value - const replaceVData = (value) => { - const vData = stringifyVData(value); - // If directly a dummy data object and in a vDataResponse, replace the Map with the value in the vDataResponse - // If it is a string, it may contain virtual data id and in vDataResponse, it also needs to be replaced with the actual value Map - // The virtual data not in this vDataResponse will remain unchanged. It may be the virtual data Map requested next time. - if (vData in vDataResponse) { - return vDataResponse[vData]; - } - if (isString(value)) { - return value.replace(newInstance(RegExpCls, regVDataId.source, 'g'), mat => mat in vDataResponse ? vDataResponse[mat] : mat); - } - return value; - }; - if (isObject(target) && !stringifyVData(target, falseValue)) { - walkObject(target, replaceVData); - } - else { - target = replaceVData(target); - } - return target; -}; -/** - * Update the method instance in the queue and replace the dummy data with actual data - * @param vDataResponse A collection of virtual IDs and corresponding real data - * @param targetQueue target queue - */ -const updateQueueMethodEntities = (vDataResponse, targetQueue) => PromiseCls.all(mapItem(targetQueue, async (silentMethodItem) => { - // Traverse the entity object deeply. If virtual data or virtual data ID is found, replace it with actual data. - deepReplaceVData(silentMethodItem.entity, vDataResponse); - // If the method instance is updated, re-persist this silent method instance - silentMethodItem.cache && (await persistSilentMethod(silentMethodItem)); -})); -/** - * Replace dummy data with response data - * @param response real response data - * @param virtualResponse dummy response data - * @returns The corresponding real data set composed of virtual data id - */ -const replaceVirtualResponseWithResponse = (virtualResponse, response) => { - let vDataResponse = {}; - const vDataId = stringifyVData(virtualResponse, falseValue); - vDataId && (vDataResponse[vDataId] = response); - if (isObject(virtualResponse)) { - for (const i in virtualResponse) { - vDataResponse = { - ...vDataResponse, - ...replaceVirtualResponseWithResponse(virtualResponse[i], response === null || response === void 0 ? void 0 : response[i]) - }; - } - } - return vDataResponse; -}; -/** - * Start the SilentMethod queue - * 1. Silent submission will be put into the queue and requests will be sent in order. Only after the previous request responds will it continue to send subsequent requests. - * 2. The number of retries is only triggered when there is no response. If the server responds incorrectly or is disconnected, it will not retry. - * 3. When the number of retries is reached and still fails, when nextRound (next round) is set, delay the time specified by nextRound and then request again, otherwise it will try again after refreshing. - * 4. If there is resolveHandler and rejectHandler, they will be called after the request is completed (whether successful or failed) to notify the corresponding request to continue responding. - * - * @param queue SilentMethodqueue - */ -const setSilentMethodActive = (silentMethodInstance, active) => { - if (active) { - silentMethodInstance.active = active; - } - else { - delete silentMethodInstance.active; - } -}; -const defaultBackoffDelay = 1000; -const bootSilentQueue = (queue, queueName) => { - /** - * The callback function is controlled by waiting parameters according to the request. If it is not set or is less than or equal to 0, it will be triggered immediately. - * @param queueName queue name - * @param callback callback function - */ - const emitWithRequestDelay = (queueName) => { - const nextSilentMethod = queue[0]; - if (nextSilentMethod) { - const targetSetting = queueRequestWaitSetting.find(({ queue }) => instanceOf(queue, RegExpCls) ? regexpTest(queue, queueName) : queue === queueName); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - const callback = () => queue[0] && silentMethodRequest(queue[0]); - const delay = (targetSetting === null || targetSetting === void 0 ? void 0 : targetSetting.wait) ? sloughConfig(targetSetting.wait, [nextSilentMethod, queueName]) : 0; - delay && delay > 0 ? setTimeoutFn(callback, delay) : callback(); - } - }; - /** - * Run a single silentMethod instance - * @param silentMethodInstance silentMethod instance - * @param retryTimes Number of retries - */ - const silentMethodRequest = (silentMethodInstance, retryTimes = 0) => { - // Set the current silent method instance to active status - setSilentMethodActive(silentMethodInstance, trueValue); - const { cache, id, behavior, entity, retryError = /.*/, maxRetryTimes = 0, backoff = { delay: defaultBackoffDelay }, resolveHandler = noop, rejectHandler = noop, emitter: methodEmitter, handlerArgs = [], virtualResponse, force } = silentMethodInstance; - // Trigger pre-request event - globalSQEventManager.emit(BeforeEventKey, newInstance((GlobalSQEvent), behavior, entity, silentMethodInstance, queueName, retryTimes)); - promiseThen(entity.send(force), async (data) => { - // The request is successful, remove the successful silent method, and continue with the next request - shift(queue); - // If the request is successful, remove the successful silent method instance from storage and continue with the next request. - cache && (await spliceStorageSilentMethod(queueName, id)); - // If there is a resolve handler, call it to notify the outside - resolveHandler(data); - // Only when there is a virtualResponse, virtual data is traversed and replaced, and global events are triggered. - // Generally, it is silent behavior, but queue behavior is not required. - if (behavior === BEHAVIOR_SILENT) { - // Replace dummy data in subsequent method instances in the queue with real data - // Only after unlocking can you access the hierarchical structure of virtualResponse normally. - const vDataResponse = replaceVirtualResponseWithResponse(virtualResponse, data); - const { targetRefMethod, updateStates } = silentMethodInstance; // It is accurate to obtain it in real time - // If this silentMethod has targetRefMethod, call updateState again to update the data - // This is an implementation of delayed data updates - if (instanceOf(targetRefMethod, Method) && updateStates && len(updateStates) > 0) { - const updateStateCollection = {}; - forEach(updateStates, stateName => { - // After the request is successful, replace the data with dummy data with real data - updateStateCollection[stateName] = dataRaw => deepReplaceVData(dataRaw, vDataResponse); - }); - const updated = updateState(targetRefMethod, updateStateCollection); - // If the status modification is unsuccessful, modify the cached data. - if (!updated) { - await setCache(targetRefMethod, (dataRaw) => deepReplaceVData(dataRaw, vDataResponse)); - } - } - // Perform dummy data replacement on subsequent silent method instances of the current queue - await updateQueueMethodEntities(vDataResponse, queue); - // Trigger global success event - globalSQEventManager.emit(SuccessEventKey, newInstance((GlobalSQSuccessEvent), behavior, entity, silentMethodInstance, queueName, retryTimes, data, vDataResponse)); - } - // Set to inactive state - setSilentMethodActive(silentMethodInstance, falseValue); - // Continue to the next silent method processing - emitWithRequestDelay(queueName); - }, reason => { - if (behavior !== BEHAVIOR_SILENT) { - // When the behavior is not silent and the request fails, rejectHandler is triggered. - // and removed from the queue and will not be retried. - shift(queue); - rejectHandler(reason); - } - else { - // Each request error will trigger an error callback - const runGlobalErrorEvent = (retryDelay) => globalSQEventManager.emit(ErrorEventKey, newInstance((GlobalSQErrorEvent), behavior, entity, silentMethodInstance, queueName, retryTimes, reason, retryDelay)); - // In silent behavior mode, determine whether retry is needed - // Retry is only effective when the response error matches the retryError regular match - const { name: errorName = '', message: errorMsg = '' } = reason || {}; - let regRetryErrorName; - let regRetryErrorMsg; - if (instanceOf(retryError, RegExp)) { - regRetryErrorMsg = retryError; - } - else if (isObject(retryError)) { - regRetryErrorName = retryError.name; - regRetryErrorMsg = retryError.message; - } - const matchRetryError = (regRetryErrorName && regexpTest(regRetryErrorName, errorName)) || - (regRetryErrorMsg && regexpTest(regRetryErrorMsg, errorMsg)); - // If there are still retry times, try again - if (retryTimes < maxRetryTimes && matchRetryError) { - // The next retry times need to be used to calculate the delay time, so +1 is needed here. - const retryDelay = delayWithBackoff(backoff, retryTimes + 1); - runGlobalErrorEvent(retryDelay); - setTimeoutFn(() => { - retryTimes += 1; - silentMethodRequest(silentMethodInstance, retryTimes); - methodEmitter.emit('retry', newInstance((ScopedSQRetryEvent), behavior, entity, silentMethodInstance, handlerArgs, retryTimes, retryDelay)); - }, - // When there are still retry times, use timeout as the next request time. - retryDelay); - } - else { - setSilentFactoryStatus(2); - runGlobalErrorEvent(); - // When the number of failures is reached, or the error message does not match the retry, the failure callback is triggered. - methodEmitter.emit('fallback', newInstance((ScopedSQErrorEvent), behavior, entity, silentMethodInstance, handlerArgs, reason)); - globalSQEventManager.emit(FailEventKey$1, newInstance((GlobalSQFailEvent), behavior, entity, silentMethodInstance, queueName, retryTimes, reason)); - } - } - // Set to inactive state - setSilentMethodActive(silentMethodInstance, falseValue); - }); - }; - emitWithRequestDelay(queueName); -}; -/** - * Put a new silentMethod instance into the queue - * @param silentMethodInstance silentMethod instance - * @param cache Does silentMethod have cache? - * @param targetQueueName target queue name - * @param onBeforePush Events before silentMethod instance push - */ -const pushNewSilentMethod2Queue = async (silentMethodInstance, cache, targetQueueName = DEFAULT_QUEUE_NAME, onBeforePush = () => []) => { - silentMethodInstance.cache = cache; - const currentQueue = (silentQueueMap[targetQueueName] = - silentQueueMap[targetQueueName] || []); - const isNewQueue = len(currentQueue) <= 0; - const beforePushReturns = await Promise.all(onBeforePush()); - const isPush2Queue = !beforePushReturns.some(returns => returns === falseValue); - // Under silent behavior, if there is no fallback event callback bound, it will be persisted. - // If false is returned in onBeforePushQueue, it will no longer be placed in the queue. - if (isPush2Queue) { - cache && (await push2PersistentSilentQueue(silentMethodInstance, targetQueueName)); - pushItem(currentQueue, silentMethodInstance); - // If it is a new queue and the status is started, execute it - isNewQueue && silentFactoryStatus === 1 && bootSilentQueue(currentQueue, targetQueueName); - } - return isPush2Queue; -}; - -/** - * Locate the location of the silentMethod instance - * @param silentMethodInstance silentMethod instance - */ -const getBelongQueuePosition = (silentMethodInstance) => { - let queue = undefinedValue; - let queueName = ''; - let position = 0; - for (const queueNameLoop in silentQueueMap) { - position = silentQueueMap[queueNameLoop].indexOf(silentMethodInstance); - if (position >= 0) { - queue = silentQueueMap[queueNameLoop]; - queueName = queueNameLoop; - break; - } - } - return [queue, queueName, position]; -}; -/** - * silentMethod instance - * Requests that need to enter silentQueue will be packaged into silentMethod instances, which will carry various parameters of the request strategy. - */ -class SilentMethod { - constructor(entity, behavior, emitter, id = uuid(), force, retryError, maxRetryTimes, backoff, resolveHandler, rejectHandler, handlerArgs, vDatas) { - const thisObj = this; - thisObj.entity = entity; - thisObj.behavior = behavior; - thisObj.id = id; - thisObj.emitter = emitter; - thisObj.force = !!force; - thisObj.retryError = retryError; - thisObj.maxRetryTimes = maxRetryTimes; - thisObj.backoff = backoff; - thisObj.resolveHandler = resolveHandler; - thisObj.rejectHandler = rejectHandler; - thisObj.handlerArgs = handlerArgs; - thisObj.vDatas = vDatas; - } - /** - * Allow cache-time persistent updates to the current instance - */ - async save() { - this.cache && (await persistSilentMethod(this)); - } - /** - * Replace the current instance with a new silentMethod instance in the queue - * If there is a persistent cache, the cache will also be updated. - * @param newSilentMethod new silentMethod instance - */ - async replace(newSilentMethod) { - const targetSilentMethod = this; - silentAssert(newSilentMethod.cache === targetSilentMethod.cache, 'the cache of new silentMethod must equal with this silentMethod'); - const [queue, queueName, position] = getBelongQueuePosition(targetSilentMethod); - if (queue) { - splice(queue, position, 1, newSilentMethod); - targetSilentMethod.cache && (await spliceStorageSilentMethod(queueName, targetSilentMethod.id, newSilentMethod)); - } - } - /** - * Remove the current instance. If there is persistent data, it will also be removed synchronously. - */ - async remove() { - const targetSilentMethod = this; - const [queue, queueName, position] = getBelongQueuePosition(targetSilentMethod); - if (queue) { - splice(queue, position, 1); - targetSilentMethod.cache && (await spliceStorageSilentMethod(queueName, targetSilentMethod.id)); - } - } - /** - * Set the method instance corresponding to the delayed update status and the corresponding status name - * It will find the corresponding status data and update vData to the actual data after responding to this silentMethod - * - * @param method method instance - * @param updateStateName Updated status name, the default is data, you can also set multiple - */ - setUpdateState(method, updateStateName = 'data') { - if (method) { - this.targetRefMethod = method; - this.updateStates = isArray(updateStateName) ? updateStateName : [updateStateName]; - } - } -} - -/** - * Deserialize the silentMethod instance according to the name of the serializer. - * @param methodInstance Request method instance - * @returns Request method instance - */ -var convertPayload2SilentMethod = (payload) => { - const { id, behavior, entity, retryError, maxRetryTimes, backoff, resolveHandler, rejectHandler, handlerArgs, targetRefMethod, force } = payload; - // Method class instantiation - const deserializeMethod = (methodPayload) => { - const { type, url, config, data } = methodPayload; - return newInstance(Method, type, dependentAlovaInstance, url, config, data); - }; - const silentMethodInstance = newInstance(SilentMethod, deserializeMethod(entity), behavior, createEventManager(), id, force, retryError, maxRetryTimes, backoff, resolveHandler, rejectHandler, handlerArgs); - silentMethodInstance.cache = trueValue; - // Target ref method deserialization - if (targetRefMethod) { - silentMethodInstance.targetRefMethod = deserializeMethod(targetRefMethod); - } - // Put extra content on the silent method instance - forEach(objectKeys(payload), key => { - if (!includes([ - 'id', - 'behavior', - 'emitter', - 'entity', - 'retryError', - 'maxRetryTimes', - 'backoff', - 'resolveHandler', - 'rejectHandler', - 'handlerArgs', - 'targetRefMethod', - 'force' - ], key)) { - silentMethodInstance[key] = payload[key]; - } - }); - return silentMethodInstance; -}; - -/** - * Load silent queue data from storage - * @returns All queue data - */ -var loadSilentQueueMapFromStorage = async () => { - const silentMethodIdQueueMap = ((await storageGetItem(silentMethodIdQueueMapStorageKey)) || - {}); - const silentQueueMap = {}; - const readingPromises = []; - forEach(objectKeys(silentMethodIdQueueMap), queueName => { - const currentQueue = (silentQueueMap[queueName] = silentQueueMap[queueName] || []); - pushItem(readingPromises, ...mapItem(silentMethodIdQueueMap[queueName], async (silentMethodId) => { - const serializedSilentMethodPayload = await storageGetItem(silentMethodStorageKeyPrefix + silentMethodId); - serializedSilentMethodPayload && - pushItem(currentQueue, convertPayload2SilentMethod(serializedSilentMethodPayload)); - })); - }); - await PromiseCls.all(readingPromises); - return silentQueueMap; -}; - -/** - * Bind silentSubmit startup event - * @param {SilentSubmitBootHandler} handler event callback function - * @returns unbind function - */ -const onSilentSubmitBoot = (handler) => globalSQEventManager.on(BootEventKey, handler); -/** - * Bind silentSubmit success event - * @param {SilentSubmitSuccessHandler} handler event callback function - * @returns unbind function - */ -const onSilentSubmitSuccess = (handler) => globalSQEventManager.on(SuccessEventKey, handler); -/** - * Bind silentSubmit error event - * Every time there is a request error, an error callback is triggered. - * @param {SilentSubmitErrorHandler} handler event callback function - * @returns unbind function - */ -const onSilentSubmitError = (handler) => globalSQEventManager.on(ErrorEventKey, handler); -/** - * Binding silentSubmit failure event - * The failure event will be triggered when the maximum number of requests is reached, or when the error message does not match - * @param {SilentSubmitFailHandler} handler event callback function - * @returns unbind function - */ -const onSilentSubmitFail = (handler) => globalSQEventManager.on(FailEventKey$1, handler); -/** - * Bind silentSubmit to initiate a pre-request event - * @param {BeforeSilentSubmitHandler} handler event callback function - * @returns unbind function - */ -const onBeforeSilentSubmit = (handler) => globalSQEventManager.on(BeforeEventKey, handler); -/** - * Start silent submission, which will load the silent method in the cache and start silent submission - * If no delay time is passed in, the sync starts immediately - * @param {SilentFactoryBootOptions} options Delay in milliseconds - */ -const bootSilentFactory = (options) => { - if (silentFactoryStatus === 0) { - const { alova, delay = 500 } = options; - setDependentAlova(alova); - setCustomSerializers(options.serializers); - setQueueRequestWaitSetting(options.requestWait); - setTimeoutFn(async () => { - // Delayed loading puts the page’s queue at the front - merge2SilentQueueMap(await loadSilentQueueMapFromStorage()); - // Loop start queue silent submission - // Multiple queues are executed in parallel - forEach(objectKeys(silentQueueMap), queueName => { - bootSilentQueue(silentQueueMap[queueName], queueName); - }); - setSilentFactoryStatus(1); // Set status to Started - globalSQEventManager.emit(BootEventKey, undefinedValue); - }, delay); - } -}; - -/** - * A global silentMethod instance that will have a value from before the first success event is triggered to after the last success event is triggered (synchronization period) - * In this way, the current silentMethod instance can be obtained in updateStateEffect in onSuccess. - */ -let currentSilentMethod = undefinedValue; -/** - * Create SilentQueue middleware function - * @param config Configuration object - * @returns middleware function - */ -var createSilentQueueMiddlewares = (handler, config) => { - const { behavior = 'queue', queue = DEFAULT_QUEUE_NAME, retryError, maxRetryTimes, backoff } = config || {}; - const eventEmitter = createEventManager(); - let handlerArgs; - let behaviorFinally; - let queueFinally = DEFAULT_QUEUE_NAME; - let forceRequest = falseValue; - let silentMethodInstance; - /** - * method instance creation function - * @param args Call the function passed in by send - * @returns method instance - */ - const createMethod = (...args) => { - silentAssert(isFn(handler), 'method handler must be a function. eg. useSQRequest(() => method)'); - setVDataIdCollectBasket({}); - handlerArgs = args; - return handler(...args); - }; - // Decorate success/error/complete event - const decorateRequestEvent = (requestExposure) => { - // Set event callback decorator - requestExposure.onSuccess = decorateEvent(requestExposure.onSuccess, (handler, event) => { - currentSilentMethod = silentMethodInstance; - handler(newInstance((ScopedSQSuccessEvent), behaviorFinally, event.method, silentMethodInstance, event.args, event.data)); - }); - requestExposure.onError = decorateEvent(requestExposure.onError, (handler, event) => { - handler(newInstance((ScopedSQErrorEvent), behaviorFinally, event.method, silentMethodInstance, event.args, event.error)); - }); - requestExposure.onComplete = decorateEvent(requestExposure.onComplete, (handler, event) => { - handler(newInstance((ScopedSQCompleteEvent), behaviorFinally, event.method, silentMethodInstance, event.args, event.status, event.data, event.error)); - }); - }; - /** - * middleware function - * @param context Request context, containing request-related values - * @param next continue executing function - * @returns Promise object - */ - const middleware = ({ method, args, cachedResponse, proxyStates, config }, next) => { - const { silentDefaultResponse, vDataCaptured, force = falseValue } = config; - // Because the behavior return value may change, it should be called for each request to re-obtain the return value. - const baseEvent = AlovaEventBase.spawn(method, args); - behaviorFinally = sloughConfig(behavior, [baseEvent]); - queueFinally = sloughConfig(queue, [baseEvent]); - forceRequest = sloughConfig(force, [baseEvent]); - // Empty temporary collection variables - // They need to be cleared before returning - const resetCollectBasket = () => { - setVDataIdCollectBasket((handlerArgs = undefinedValue)); - }; - // If v data captured is set, first determine whether the request-related data contains virtual data. - if (isFn(vDataCaptured)) { - let hasVData = vDataIdCollectBasket && len(objectKeys(vDataIdCollectBasket)) > 0; - if (!hasVData) { - const { url, data } = method; - const { params, headers } = getConfig(method); - walkObject({ url, params, data, headers }, value => { - if (!hasVData && (stringifyVData(value, falseValue) || regexpTest(regVDataId, value))) { - hasVData = trueValue; - } - return value; - }); - } - // If v data captured has return data, use it as the response data, otherwise continue the request - const customResponse = hasVData ? vDataCaptured(method) : undefinedValue; - if (customResponse !== undefinedValue) { - resetCollectBasket(); // Reset when captured by v data captured - return promiseResolve(customResponse); - } - } - if (behaviorFinally !== BEHAVIOR_STATIC) { - // Wait for the method in the queue to complete execution - const createSilentMethodPromise = () => { - const queueResolvePromise = newInstance(PromiseCls, (resolveHandler, rejectHandler) => { - silentMethodInstance = newInstance((SilentMethod), method, behaviorFinally, eventEmitter, undefinedValue, !!forceRequest, retryError, maxRetryTimes, backoff, resolveHandler, rejectHandler, handlerArgs, vDataIdCollectBasket && objectKeys(vDataIdCollectBasket)); - resetCollectBasket(); // Reset when Behavior is queue and silent - }); - // On before push and on pushed events are bound synchronously, so they need to be queued asynchronously to trigger the event normally. - promiseThen(promiseResolve(undefinedValue), async () => { - const createPushEvent = () => newInstance((ScopedSQEvent), behaviorFinally, method, silentMethodInstance, args); - // Put the silent method into the queue and persist it - const isPushed = await pushNewSilentMethod2Queue(silentMethodInstance, - // After the onFallback event is bound, even the silent behavior mode is no longer stored. - // onFallback will be called synchronously, so it needs to be determined asynchronously whether there are fallbackHandlers - len(eventEmitter.eventMap.fallback || []) <= 0 && behaviorFinally === BEHAVIOR_SILENT, queueFinally, - // Execute the callback before putting it into the queue. If false is returned, it will prevent putting it into the queue. - () => eventEmitter.emit('beforePushQueue', createPushEvent())); - // Only after putting it into the queue, the callback after putting it into the queue will be executed. - isPushed && eventEmitter.emit('pushedQueue', createPushEvent()); - }); - return queueResolvePromise; - }; - if (behaviorFinally === BEHAVIOR_QUEUE) { - // Forced request, or loading status needs to be updated when cache is hit - const needSendRequest = forceRequest || !cachedResponse; - if (needSendRequest) { - // Manually set to true - proxyStates.loading.v = trueValue; - } - // When using the cache, use the cache directly, otherwise enter the request queue - return needSendRequest ? createSilentMethodPromise() : promiseThen(promiseResolve(cachedResponse)); - } - const silentMethodPromise = createSilentMethodPromise(); - // Create virtual response data in silent mode. Virtual response data can generate arbitrary virtual data. - const virtualResponse = (silentMethodInstance.virtualResponse = createVirtualResponse(isFn(silentDefaultResponse) ? silentDefaultResponse() : undefinedValue)); - promiseThen(silentMethodPromise, realResponse => { - // Update after obtaining real data - proxyStates.data.v = realResponse; - }); - // In Silent mode, the virtual response value is returned immediately, and then updated when the real data is returned. - return promiseResolve(virtualResponse); - } - resetCollectBasket(); // Reset when Behavior is static - return next(); - }; - return { - c: createMethod, - m: middleware, - d: decorateRequestEvent, - // event binding function - b: { - /** - * Bind fallback event - * @param handler Fallback event callback - */ - onFallback: (handler) => { - eventEmitter.on('fallback', handler); - }, - /** - * Event before binding to queue - * @param handler Event callback before enqueuing - */ - onBeforePushQueue: (handler) => { - eventEmitter.on('beforePushQueue', handler); - }, - /** - * Event after binding to queue - * @param handler Event callback after being queued - */ - onPushedQueue: (handler) => { - eventEmitter.on('pushedQueue', handler); - }, - /** - * retry event - * @param handler Retry event callback - */ - onRetry: (handler) => { - eventEmitter.on('retry', handler); - } - } - }; -}; - -function useSQRequest(handler, config = {}) { - const { exposeProvider, __referingObj: referingObj } = statesHookHelper(promiseStatesHook()); - const { middleware = noop } = config; - const { c: methodCreateHandler, m: silentMiddleware, b: binders, d: decorateEvent } = createSilentQueueMiddlewares(handler, config); - const states = useRequest(methodCreateHandler, { - ...config, - __referingObj: referingObj, - middleware: (ctx, next) => { - const silentMidPromise = silentMiddleware(ctx, next); - middleware(ctx, () => silentMidPromise); - return silentMidPromise; - } - }); - decorateEvent(states); - return exposeProvider({ - ...states, - ...binders - }); -} - -/** - * Determine whether two values are equal in a way that is compatible with virtual data - * @param prevValue Antecedent value - * @param nextValue consequent value - * @returns Are they equal? - */ -var equals = (prevValue, nextValue) => { - // If equal, return directly - if (prevValue === nextValue) { - return trueValue; - } - return stringifyVData(prevValue) === stringifyVData(nextValue); -}; - -/** - * Filter all silentMethod instances that meet the criteria by method name or regular expression - * @param methodNameMatcher method name matcher - * @param queueName Find the queue name, the default is default queue - * @param filterActive Whether to filter out active instances - * @returns array of silentMethod instances - */ -const filterSilentMethods = async (methodNameMatcher, queueName = DEFAULT_QUEUE_NAME, filterActive = falseValue) => { - const matchSilentMethods = (targetQueue = []) => targetQueue.filter(silentMethodItem => { - if (methodNameMatcher === undefinedValue) { - return trueValue; - } - const name = getConfig(silentMethodItem.entity).name || ''; - const retain = instanceOf(methodNameMatcher, RegExp) - ? regexpTest(methodNameMatcher, name) - : name === methodNameMatcher; - return retain && (filterActive ? silentMethodItem.active : trueValue); - }); - return [ - ...matchSilentMethods(silentQueueMap[queueName]), - // If the silent factory is not currently started, you also need to match the silent methods in the persistent storage. - ...(silentFactoryStatus === 0 ? matchSilentMethods((await loadSilentQueueMapFromStorage())[queueName]) : []) - ]; -}; -/** - * Find the first silentMethod instance that meets the condition by method name or regular expression - * @param methodNameMatcher method name matcher - * @param queueName Find the queue name, the default is default queue - * @param filterActive Whether to filter out active instances - * @returns silentMethod instance, undefined when not found - */ -const getSilentMethod = async (methodNameMatcher, queueName = DEFAULT_QUEUE_NAME, filterActive = falseValue) => (await filterSilentMethods(methodNameMatcher, queueName, filterActive))[0]; - -/** - * Determine whether the target data is virtual data - * @param target target data - * @returns Is it virtual data? - */ -var isVData = (target) => !!stringifyVData(target, falseValue) || regexpTest(regVDataId, target); - -/** - * Update the status of the corresponding method - * Unlike updateState, in addition to updating the state immediately, it will also update again after responding in silent mode in order to replace the virtual data with actual data. - * @param method request method object - * @param handleUpdate update callback - */ -const updateStateEffect = async (matcher, handleUpdate) => { - // Save the target method instance to the current silent method instance - if (currentSilentMethod) { - currentSilentMethod.setUpdateState(matcher, isFn(updateState) ? undefinedValue : objectKeys(updateState)); - await currentSilentMethod.save(); - } - return updateState(matcher, handleUpdate); -}; - -const useAutoRequest = (handler, config = {}) => { - let notifiable = trueValue; - const { enableFocus = trueValue, enableVisibility = trueValue, enableNetwork = trueValue, pollingTime = 0, throttle = 1000 } = config; - const { onMounted, onUnmounted, __referingObj: referingObject } = statesHookHelper(promiseStatesHook()); - const states = useRequest(handler, { - ...config, - __referingObj: referingObject - }); - const notify = () => { - if (notifiable) { - states.send(); - if (throttle > 0) { - notifiable = falseValue; - setTimeout(() => { - notifiable = trueValue; - }, throttle); - } - } - }; - let offNetwork = noop; - let offFocus = noop; - let offVisiblity = noop; - let offPolling = noop; - onMounted(() => { - if (!globalConfigMap.ssr) { - offNetwork = enableNetwork ? useAutoRequest.onNetwork(notify, config) : offNetwork; - offFocus = enableFocus ? useAutoRequest.onFocus(notify, config) : offFocus; - offVisiblity = enableVisibility ? useAutoRequest.onVisibility(notify, config) : offVisiblity; - offPolling = pollingTime > 0 ? useAutoRequest.onPolling(notify, config) : offPolling; - } - }); - onUnmounted(() => { - offNetwork(); - offFocus(); - offVisiblity(); - offPolling(); - }); - return states; -}; -const on = (type, handler) => { - window.addEventListener(type, handler); - return () => window.removeEventListener(type, handler); -}; -useAutoRequest.onNetwork = notify => on('online', notify); -useAutoRequest.onFocus = notify => on('focus', notify); -useAutoRequest.onVisibility = notify => { - const handle = () => document.visibilityState === 'visible' && notify(); - return on('visibilitychange', handle); -}; -useAutoRequest.onPolling = (notify, config) => { - const timer = setInterval(notify, config.pollingTime); - return () => clearInterval(timer); -}; - -const hookPrefix$1 = 'useCaptcha'; -const captchaAssert = createAssert(hookPrefix$1); -var useCaptcha = (handler, config = {}) => { - const { initialCountdown, middleware } = config; - captchaAssert(initialCountdown === undefinedValue || initialCountdown > 0, 'initialCountdown must be greater than 0'); - const { create, ref, objectify, exposeProvider, __referingObj: referingObject } = statesHookHelper(promiseStatesHook()); - const countdown = create(0, 'countdown'); - const requestReturned = useRequest(handler, { - ...config, - __referingObj: referingObject, - immediate: falseValue, - managedStates: objectify([countdown], 's'), - // eslint-disable-next-line @typescript-eslint/no-use-before-define - middleware: middleware ? (ctx, next) => middleware({ ...ctx, send }, next) : undefinedValue - }); - const timer = ref(undefinedValue); - const send = (...args) => newInstance(PromiseCls, (resolve, reject) => { - if (countdown.v <= 0) { - requestReturned - .send(...args) - .then(result => { - countdown.v = config.initialCountdown || 60; - timer.current = setInterval(() => { - countdown.v -= 1; - if (countdown.v <= 0) { - clearInterval(timer.current); - } - }, 1000); - resolve(result); - }) - .catch(reason => reject(reason)); - } - else { - reject(newInstance(AlovaError, hookPrefix$1, 'the countdown is not over yet')); - } - }); - return exposeProvider({ - ...requestReturned, - send, - ...objectify([countdown]) - }); -}; - -const RestoreEventKey = Symbol('FormRestore'); -const getStoragedKey = (methodInstance, id) => `alova/form-${id || getMethodInternalKey(methodInstance)}`; -const sharedStates = {}; -const cloneFormData = (form) => { - const shallowClone = (value) => (isArray(value) ? [...value] : isPlainObject(value) ? { ...value } : value); - return walkObject(shallowClone(form), shallowClone); -}; -var useForm = (handler, config = {}) => { - const typedSharedStates = sharedStates; - const { id, initialForm, store, resetAfterSubmiting, immediate = falseValue, middleware } = config; - promiseStatesHook(); - const { create, ref: useFlag$, onMounted, watch, objectify, exposeProvider, __referingObj: referingObject } = statesHookHelper(promiseStatesHook()); - const isStoreObject = isPlainObject(store); - const enableStore = isStoreObject ? store.enable : store; - // If the id in config also has a corresponding shared state, it will also be returned. - // The reason for continuing the execution is to be compatible with the problem that the number of hook executions in react cannot be changed, otherwise it will throw "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - const sharedState = id ? typedSharedStates[id] : undefinedValue; - const form = create(cloneFormData(initialForm), 'form'); - const methodHandler = handler; - const eventManager = createEventManager(); - // Use computed properties to avoid calling methodHandler every time this use hook is executed. - const initialMethodInstance = useFlag$(sloughConfig(methodHandler, [form.v])); - const storageContext = getContext(initialMethodInstance.current).l2Cache; - const storagedKey = getStoragedKey(initialMethodInstance.current, id); - const reseting = useFlag$(falseValue); - const serializerPerformer = useFlag$(createSerializerPerformer(isStoreObject ? store.serializers : undefinedValue)); - // Whether the shared state created by the current hook is initiated. The hook that initiates the creation needs to return the latest state. Otherwise, because the hook is called in react, the latest state cannot be obtained from the hook initiated. - const isCreateShardState = useFlag$(false); - const originalHookProvider = useRequest((...args) => methodHandler(form.v, ...args), { - ...config, - __referingObj: referingObject, - // Middleware function, also supports subscriber middleware - middleware: middleware - ? (ctx, next) => middleware({ - ...ctx, - // eslint-disable-next-line - delegatingActions: { updateForm, reset } - }, next) - : undefinedValue, - // 1. When persistence is required, it will be triggered after data recovery - // 2. When there is a shared state, it means that it has been initialized before (regardless of whether there is an immediate request), and subsequent requests will no longer be automatically initiated. This is to be compatible with the issue of repeated requests when multiple forms initiate requests immediately. - immediate: enableStore || sharedState ? falseValue : immediate - }); - /** - * Reset form data - */ - const reset = () => { - reseting.current = trueValue; - const clonedFormData = cloneFormData(initialForm); - clonedFormData && (form.v = clonedFormData); - enableStore && storageContext.remove(storagedKey); - }; - /** - * Update form data - * @param newForm new form data - */ - const updateForm = (newForm) => { - form.v = { - ...form.v, - ...newForm - }; - }; - const hookProvider = exposeProvider({ - // The first parameter is fixed to form data - ...originalHookProvider, - ...objectify([form]), - updateForm, - reset, - // Persistent data recovery event binding - onRestore(handler) { - eventManager.on(RestoreEventKey, handler); - } - }); - // Only when there is an id, it is saved to sharedStates. - // In react, because a new form will be generated after updating the form, it needs to be resaved every time it is called. - if (id) { - // If there is no shared status yet, it means that the current hook is a created hook. - if (!sharedState) { - isCreateShardState.current = trueValue; - } - // Only the shared state of the created hook is saved - if (isCreateShardState.current) { - typedSharedStates[id] = { - hookProvider: hookProvider, - config - }; - } - } - const { send, onSuccess } = hookProvider; - onMounted(() => { - // Update data when persistence is required - if (enableStore && !sharedState) { - // Get storage and update data - // It needs to be called in onMounted, otherwise it will cause it to be called repeatedly in react. - const storagedForm = serializerPerformer.current.deserialize(storageContext.get(storagedKey)); - // When there is draft data, the data is restored asynchronously, otherwise the on restore event cannot be bound normally. - if (storagedForm) { - form.v = storagedForm; - // Trigger persistent data recovery event - eventManager.emit(RestoreEventKey, undefinedValue); - } - enableStore && immediate && send(...[]); - } - }); - // Monitor changes and store them synchronously. If it is triggered by reset, no further serialization is required. - watch([form], () => { - if (reseting.current || !enableStore) { - reseting.current = falseValue; - return; - } - storageContext.set(storagedKey, serializerPerformer.current.serialize(form.v)); - }); - // If data needs to be cleared after submission, call reset - onSuccess(() => { - resetAfterSubmiting && reset(); - }); - // If there is a saved sharedState, return it - // If it is the shared state created by the current hook, the latest one is returned instead of the cached one. - return sharedState && !isCreateShardState.current ? sharedState.hookProvider : hookProvider; -}; - -const RetryEventKey = Symbol('RetriableRetry'); -const FailEventKey = Symbol('RetriableFail'); -const hookPrefix = 'useRetriableRequest'; -const assert$2 = createAssert(hookPrefix); -var useRetriableRequest = (handler, config = {}) => { - const { retry = 3, backoff = { delay: 1000 }, middleware = noop } = config; - const { ref: useFlag$, exposeProvider, __referingObj: referingObject } = statesHookHelper(promiseStatesHook()); - const eventManager = createEventManager(); - const retryTimes = useFlag$(0); - const stopManuallyError = useFlag$(undefinedValue); // Stop error object, has value when stop is triggered manually - const methodInstanceLastest = useFlag$(undefinedValue); - const argsLatest = useFlag$(undefinedValue); - const requesting = useFlag$(falseValue); // Is it being requested? - const retryTimer = useFlag$(undefinedValue); - const stopPromiseObj = useFlag$(usePromise()); - const emitOnFail = (method, args, error) => { - // On fail needs to be triggered asynchronously, and on error and on complete should be triggered first. - setTimeoutFn(() => { - eventManager.emit(FailEventKey, newInstance((RetriableFailEvent), AlovaEventBase.spawn(method, args), error, retryTimes.current)); - stopManuallyError.current = undefinedValue; - retryTimes.current = 0; // Reset the number of retries - }); - }; - const nestedHookProvider = useRequest(handler, { - ...config, - __referingObj: referingObject, - middleware(ctx, next) { - middleware({ - ...ctx, - delegatingActions: { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - stop - } - }, () => promiseResolve()); - const { proxyStates, args, send, method, controlLoading } = ctx; - controlLoading(); - const { loading } = proxyStates; - const setLoading = (value = falseValue) => { - loading.v = value; - }; - const resolveFail = (error) => { - setLoading(); - proxyStates.error.v = error; - clearTimeout(retryTimer.current); // Clear retry timer - emitOnFail(method, args, error); - }; - if (!loading.v) { - promiseCatch(stopPromiseObj.current.promise, error => { - resolveFail(error); - stopPromiseObj.current = usePromise(); - }); - } - setLoading(trueValue); - requesting.current = trueValue; - methodInstanceLastest.current = method; - argsLatest.current = args; - /** - * Consider this situation: user call stop() and send another request immediately, but now the previous request haven't finished. `next()` will raises the branch on completion. - * - * By using Promise.race(), we can cause the returned promise to be rejected immediately when call `stop()` - */ - return next() - .then(val => { - // set `loading` to false when request is successful - setLoading(); - return val; - }, - // Trigger retry mechanism when request fails - error => { - // There is no manual trigger to stop, and a retry is triggered when the number of retries does not reach the maximum. - if (!stopManuallyError.current && (isNumber(retry) ? retryTimes.current < retry : retry(error, ...args))) { - retryTimes.current += 1; - // Calculate retry delay time - const retryDelay = delayWithBackoff(backoff, retryTimes.current); - // Delay the corresponding time and try again - retryTimer.current = setTimeoutFn(() => { - // trigger retry event - eventManager.emit(RetryEventKey, newInstance((RetriableRetryEvent), AlovaEventBase.spawn(method, args), retryTimes.current, retryDelay)); - // If stopped manually, retry will no longer be triggered. - promiseCatch(send(...args), noop); // Captured errors will no longer be thrown out, otherwise errors will be thrown when retrying. - }, retryDelay); - } - else { - error = stopManuallyError.current || error; // If stop manually error has a value, it means that the stop is triggered through the stop function. - resolveFail(error); - } - // Return reject to execute the subsequent error process - return promiseReject(error); - }) - .finally(() => { - requesting.current = falseValue; - }); - } - }); - /** - * Stop retrying, only valid when called during retrying - * If the request is in progress, trigger an interrupt request and let the request error throw an error. Otherwise, manually modify the status and trigger onFail. - * The onFail event will be triggered immediately after stopping - */ - const stop = () => { - assert$2(nestedHookProvider.__proxyState('loading').v, 'there is no requests being retried'); - stopManuallyError.current = newInstance(AlovaError, hookPrefix, 'stop retry manually'); - if (requesting.current) { - nestedHookProvider.abort(); - } - else { - stopPromiseObj.current.reject(stopManuallyError.current); - } - }; - /** - * Retry event binding - * They will be triggered after the retry is initiated - * @param handler Retry event callback - */ - const onRetry = (handler) => { - eventManager.on(RetryEventKey, event => handler(event)); - }; - /** - * failed event binding - * They will be triggered when there are no more retries, such as when the maximum number of retries is reached, when the retry callback returns false, or when stop is manually called to stop retries. - * The onError event of alova will be triggered every time an error is requested. - * - * Note: If there are no retries, onError, onComplete and onFail will be triggered at the same time. - * - * @param handler Failure event callback - */ - const onFail = (handler) => { - eventManager.on(FailEventKey, event => handler(event)); - }; - return exposeProvider({ - ...nestedHookProvider, - stop, - onRetry, - onFail - }); -}; - -const SSEOpenEventKey = Symbol('SSEOpen'); -const SSEMessageEventKey = Symbol('SSEMessage'); -const SSEErrorEventKey = Symbol('SSEError'); -var SSEHookReadyState; -(function (SSEHookReadyState) { - SSEHookReadyState[SSEHookReadyState["CONNECTING"] = 0] = "CONNECTING"; - SSEHookReadyState[SSEHookReadyState["OPEN"] = 1] = "OPEN"; - SSEHookReadyState[SSEHookReadyState["CLOSED"] = 2] = "CLOSED"; -})(SSEHookReadyState || (SSEHookReadyState = {})); -const assert$1 = createAssert('useSSE'); -const MessageType = { - Open: 'open', - Error: 'error', - Message: 'message' -}; -var useSSE = (handler, config = {}) => { - const { initialData, withCredentials, interceptByGlobalResponded = trueValue, - /** abortLast = trueValue, */ - immediate = falseValue } = config; - // ! Temporarily does not support specifying abortLast - const abortLast = trueValue; - let { memorize } = promiseStatesHook(); - memorize !== null && memorize !== void 0 ? memorize : (memorize = $self); - const { create, ref, onMounted, onUnmounted, objectify, exposeProvider } = statesHookHelper(promiseStatesHook()); - const usingArgs = ref([]); - const eventSource = ref(undefinedValue); - const sendPromiseObject = ref(undefinedValue); - const data = create(initialData, 'data'); - const readyState = create(SSEHookReadyState.CLOSED, 'readyState'); - let methodInstance = getHandlerMethod(handler); - let responseUnified; - const eventManager = createEventManager(); - // UseCallback object that stores custom events, where key is eventName - const customEventMap = ref(new Map()); - const onOpen = (handler) => { - eventManager.on(SSEOpenEventKey, handler); - }; - const onMessage = (handler) => { - eventManager.on(SSEMessageEventKey, handler); - }; - const onError = (handler) => { - eventManager.on(SSEErrorEventKey, handler); - }; - const responseSuccessHandler = ref($self); - const responseErrorHandler = ref(throwFn); - const responseCompleteHandler = ref(noop); - /** - * Set up a response interceptor, which needs to be called after each send - */ - const setResponseHandler = (instance) => { - // responded removed since 3.0 - const { responded } = getOptions(instance); - responseUnified = responded; - if (isFn(responseUnified)) { - responseSuccessHandler.current = responseUnified; - } - else if (responseUnified && isPlainObject(responseUnified)) { - const { onSuccess: successHandler, onError: errorHandler, onComplete: completeHandler } = responseUnified; - responseSuccessHandler.current = isFn(successHandler) ? successHandler : responseSuccessHandler.current; - responseErrorHandler.current = isFn(errorHandler) ? errorHandler : responseErrorHandler.current; - responseCompleteHandler.current = isFn(completeHandler) ? completeHandler : responseCompleteHandler.current; - } - }; - /** - * Process response tasks and do not cache data on failure - * @param handlerReturns Data returned by the interceptor - * @returns Processed response - */ - const handleResponseTask = async (handlerReturns) => { - const { headers, transform: transformFn = $self } = getConfig(methodInstance); - const returnsData = await handlerReturns; - const transformedData = await transformFn(returnsData, (headers || {})); - data.v = transformedData; - // invalidate cache - hitCacheBySource(methodInstance); - return transformedData; - }; - /** - * Create AlovaSSEHook event - * For specific data processing procedures, please refer to the following link - * @link https://alova.js.org/zh-CN/tutorial/combine-framework/response - */ - const createSSEEvent = async (eventFrom, dataOrError) => { - assert$1(!!eventSource.current, 'EventSource is not initialized'); - const es = eventSource.current; - const baseEvent = new AlovaSSEEvent(AlovaEventBase.spawn(methodInstance, usingArgs.current), es); - if (eventFrom === MessageType.Open) { - return Promise.resolve(baseEvent); - } - const globalSuccess = interceptByGlobalResponded ? responseSuccessHandler.current : $self; - const globalError = interceptByGlobalResponded ? responseErrorHandler.current : throwFn; - const globalFinally = interceptByGlobalResponded ? responseCompleteHandler.current : noop; - const p = promiseFinally(promiseThen(dataOrError, res => handleResponseTask(globalSuccess(res, methodInstance)), error => handleResponseTask(globalError(error, methodInstance))), - // Finally - () => { - globalFinally(methodInstance); - }); - // Regardless, the Promise object returned by the function must be fulfilled - return promiseThen(p, - // Get processed data (data after transform) - res => new AlovaSSEMessageEvent(baseEvent, res), - // There is an error - error => new AlovaSSEErrorEvent(baseEvent, error)); - }; - /** - * Select the required trigger function based on the event. If the event has no errors, the callback function passed in is triggered. - * @param callback Callback function triggered when there is no error - */ - const sendSSEEvent = (callback) => (event) => { - if (event.error === undefinedValue) { - return callback(event); - } - return eventManager.emit(SSEErrorEventKey, event); - }; - // * MARK: Event handling of EventSource - const onCustomEvent = (eventName, callbackHandler) => { - var _a; - const currentMap = customEventMap.current; - if (!currentMap.has(eventName)) { - const useCallbackObject = useCallback(callbacks => { - var _a; - if (callbacks.length === 0) { - (_a = eventSource.current) === null || _a === void 0 ? void 0 : _a.removeEventListener(eventName, useCallbackObject[1]); - customEventMap.current.delete(eventName); - } - }); - const trigger = useCallbackObject[1]; - currentMap.set(eventName, useCallbackObject); - (_a = eventSource.current) === null || _a === void 0 ? void 0 : _a.addEventListener(eventName, event => { - promiseThen(createSSEEvent(eventName, Promise.resolve(event.data)), sendSSEEvent(trigger)); - }); - } - const [onEvent] = currentMap.get(eventName); - return onEvent(callbackHandler); - }; - /** - * Cancel the registration of custom events in useCallback - */ - const offCustomEvent = () => { - customEventMap.current.forEach(([_1, _2, offTrigger]) => { - offTrigger(); - }); - }; - const esOpen = memorize(() => { - var _a; - // resolve the promise returned when using send() - readyState.v = SSEHookReadyState.OPEN; - promiseThen(createSSEEvent(MessageType.Open, Promise.resolve()), event => eventManager.emit(SSEOpenEventKey, event)); - // ! Must be resolved after calling onOpen - (_a = sendPromiseObject.current) === null || _a === void 0 ? void 0 : _a.resolve(); - }); - const esError = memorize((event) => { - var _a, _b; - readyState.v = SSEHookReadyState.CLOSED; - promiseThen(createSSEEvent(MessageType.Error, Promise.reject((_a = event === null || event === void 0 ? void 0 : event.message) !== null && _a !== void 0 ? _a : 'SSE Error')), sendSSEEvent(event => eventManager.emit(SSEMessageEventKey, event))); - (_b = sendPromiseObject.current) === null || _b === void 0 ? void 0 : _b.resolve(); - }); - const esMessage = memorize((event) => { - promiseThen(createSSEEvent(MessageType.Message, Promise.resolve(event.data)), sendSSEEvent(event => eventManager.emit(SSEMessageEventKey, event))); - }); - /** - * Close the registration of the current eventSource - */ - const close = () => { - const es = eventSource.current; - if (!es) { - return; - } - if (sendPromiseObject.current) { - // If the promise is still there when close - sendPromiseObject.current.resolve(); - } - // * MARK: Unbinding event handling - es.close(); - es.removeEventListener(MessageType.Open, esOpen); - es.removeEventListener(MessageType.Error, esError); - es.removeEventListener(MessageType.Message, esMessage); - readyState.v = SSEHookReadyState.CLOSED; - // After eventSource is closed, unregister all custom events - // Otherwise it may cause memory leaks - customEventMap.current.forEach(([_, eventTrigger], eventName) => { - es.removeEventListener(eventName, eventTrigger); - }); - }; - /** - * Send request and initialize eventSource - */ - const connect = (...args) => { - let es = eventSource.current; - let promiseObj = sendPromiseObject.current; - if (es && abortLast) { - // When abortLast === true, close the previous connection and re-establish it - close(); - } - // Set the promise object used by the send function - if (!promiseObj) { - promiseObj = sendPromiseObject.current = usePromise(); - // Clear the promise object after open - promiseObj && - promiseObj.promise.finally(() => { - promiseObj = undefinedValue; - }); - } - usingArgs.current = args; - methodInstance = getHandlerMethod(handler, args); - // Set up response interceptor - setResponseHandler(methodInstance); - const { params } = getConfig(methodInstance); - const { baseURL, url } = methodInstance; - const fullURL = buildCompletedURL(baseURL, url, params); - // Establish connection - es = new EventSource(fullURL, { withCredentials }); - eventSource.current = es; - readyState.v = SSEHookReadyState.CONNECTING; - // * MARK: Register to handle events - // Register to handle event open error message - es.addEventListener(MessageType.Open, esOpen); - es.addEventListener(MessageType.Error, esError); - es.addEventListener(MessageType.Message, esMessage); - // and custom events - // If the on listener is used before connect (send), there will already be events in customEventMap. - customEventMap.current.forEach(([_, eventTrigger], eventName) => { - es === null || es === void 0 ? void 0 : es.addEventListener(eventName, event => { - promiseThen(createSSEEvent(eventName, Promise.resolve(event.data)), sendSSEEvent(eventTrigger)); - }); - }); - return promiseObj.promise; - }; - onUnmounted(() => { - close(); - // The above use of eventSource.removeEventListener just disconnects eventSource and trigger. - // Here is the cancellation of the event registration in the useCallback object - eventManager.off(SSEOpenEventKey); - eventManager.off(SSEMessageEventKey); - eventManager.off(SSEErrorEventKey); - offCustomEvent(); - }); - // * MARK: initialization action - onMounted(() => { - var _a; - if (immediate) { - connect(...[]); - (_a = sendPromiseObject.current) === null || _a === void 0 ? void 0 : _a.promise.catch(() => { }); - } - }); - return exposeProvider({ - send: connect, - close, - on: onCustomEvent, - onMessage, - onError, - onOpen, - eventSource, - ...objectify([readyState, data]) - }); -}; - -let currentHookIndex = 0; -// (id, (hookIndex, Actions)) -const actionsMap = {}; -const isFrontMiddlewareContext = (context) => !!context.send; -const assert = createAssert('subscriber'); -/** - * Operation function delegation middleware - * After using this middleware, you can call the delegated function through accessAction. - * Can delegate multiple identical IDs - * In order to eliminate the hierarchical restrictions of components - * @param id Client ID - * @returns alova middleware function - */ -const actionDelegationMiddleware = (id) => { - const { ref, onUnmounted } = statesHookHelper(promiseStatesHook()); - const hookIndex = ref(currentHookIndex + 1); - if (hookIndex.current > currentHookIndex) { - currentHookIndex += 1; - } - onUnmounted(() => { - var _a; - if ((_a = actionsMap[id]) === null || _a === void 0 ? void 0 : _a[hookIndex.current]) { - // delete action on unmount - delete actionsMap[id][hookIndex.current]; - } - }); - return (context, next) => { - // The middleware will be called repeatedly. If you have already subscribed, you do not need to subscribe again. - const { abort, proxyStates, delegatingActions = {} } = context; - const update = (newStates) => { - for (const key in newStates) { - proxyStates[key] && (proxyStates[key].v = newStates[key]); - } - }; - // Those with the same ID will be saved together in the form of an array - const hooks = (actionsMap[id] = actionsMap[id] || []); - const handler = isFrontMiddlewareContext(context) - ? { - ...delegatingActions, - send: context.send, - abort, - update - } - : { - ...delegatingActions, - fetch: context.fetch, - abort, - update - }; - hooks[hookIndex.current] = handler; - return next(); - }; -}; -/** - * Access the operation function, if there are multiple matches, onMatch will be called with this - * @param id Delegator id, or regular expression - * @param onMatch matching subscribers - * @param silent Default is false. If true, no error will be reported if there is no match - */ -const accessAction = (id, onMatch, silent = false) => { - const matched = []; - if (typeof id === 'symbol' || isString(id) || isNumber(id)) { - actionsMap[id] && pushItem(matched, ...objectValues(actionsMap[id])); - } - else if (instanceOf(id, RegExp)) { - forEach(filterItem(objectKeys(actionsMap), idItem => id.test(idItem)), idItem => { - pushItem(matched, ...objectValues(actionsMap[idItem])); - }); - } - // its opposite expression is too obscure - if (matched.length === 0 && !silent) { - assert(false, `no handler can be matched by using \`${id.toString()}\``); - } - forEach(filterItem(matched, $self), onMatch); -}; - -export { accessAction, actionDelegationMiddleware, bootSilentFactory, createClientTokenAuthentication, createServerTokenAuthentication, dehydrateVData, equals, filterSilentMethods, getSilentMethod, isVData, onBeforeSilentSubmit, onSilentSubmitBoot, onSilentSubmitError, onSilentSubmitFail, onSilentSubmitSuccess, silentQueueMap, statesHookHelper, stringifyVData, updateState, updateStateEffect, useAutoRequest, useCaptcha, useFetcher, useForm, usePagination, useRequest, useRetriableRequest, useSQRequest, useSSE, useSerialRequest, useSerialWatcher, useWatcher }; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/clienthook/index.umd.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/clienthook/index.umd.js deleted file mode 100644 index 6428611..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/clienthook/index.umd.js +++ /dev/null @@ -1,3897 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('alova')) : - typeof define === 'function' && define.amd ? define(['exports', 'alova'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.AlovaClientHook = {}, global.alova)); -})(this, (function (exports, alova) { 'use strict'; - - /** - * @alova/shared 1.1.2 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) - */ - - const undefStr = 'undefined'; - // The following unified processing functions or variables added to reduce the amount of compiled code - const PromiseCls = Promise; - const promiseResolve = (value) => PromiseCls.resolve(value); - const promiseReject = (value) => PromiseCls.reject(value); - const ObjectCls = Object; - const RegExpCls = RegExp; - const undefinedValue = undefined; - const nullValue = null; - const trueValue = true; - const falseValue = false; - const promiseThen = (promise, onFulfilled, onrejected) => promise.then(onFulfilled, onrejected); - const promiseCatch = (promise, onrejected) => promise.catch(onrejected); - const promiseFinally = (promise, onfinally) => promise.finally(onfinally); - const setTimeoutFn = (fn, delay = 0) => setTimeout(fn, delay); - const clearTimeoutTimer = (timer) => clearTimeout(timer); - const objectKeys = (obj) => ObjectCls.keys(obj); - const objectValues = (obj) => ObjectCls.values(obj); - const forEach = (ary, fn) => ary.forEach(fn); - const pushItem = (ary, ...item) => ary.push(...item); - const mapItem = (ary, callbackfn) => ary.map(callbackfn); - const filterItem = (ary, predicate) => ary.filter(predicate); - const shift = (ary) => ary.shift(); - const splice = (ary, start, deleteCount = 0, ...items) => ary.splice(start, deleteCount, ...items); - const len = (data) => data.length; - const isArray = (arg) => Array.isArray(arg); - const deleteAttr = (arg, attr) => delete arg[attr]; - const typeOf = (arg) => typeof arg; - const regexpTest = (reg, str) => reg.test(`${str}`); - const includes = (ary, target) => ary.includes(target); - const valueObject = (value, writable = falseValue) => ({ value, writable }); - const defineProperty = (o, key, value, isDescriptor = falseValue) => ObjectCls.defineProperty(o, key, isDescriptor ? value : valueObject(value, falseValue)); - // Whether it is running on the server side, node and bun are judged by process, and deno is judged by Deno. - // Some frameworks (such as Alipay and uniapp) will inject the process object as a global variable. - // Therefore, the process.cwd function unique to the server is used as the basis for judgment. - typeof window === undefStr && - (typeof process !== undefStr ? typeof process.cwd === 'function' : typeof Deno !== undefStr); - /** cache mode */ - // only cache in memory, it's default option - const MEMORY = 'memory'; - // persistent cache, and will be read to memory when page is refreshed, it means that the memory cache always exist until cache is expired. - const STORAGE_RESTORE = 'restore'; - - /** - * Empty function for compatibility processing - */ - const noop = () => { }; - /** - * A function that returns the parameter itself, used for compatibility processing - * Since some systems use self as a reserved word, $self is used to distinguish it. - * @param arg any parameter - * @returns return parameter itself - */ - const $self = (arg) => arg; - /** - * Determine whether the parameter is a function any parameter - * @returns Whether the parameter is a function - */ - const isFn = (arg) => typeOf(arg) === 'function'; - /** - * Determine whether the parameter is a number any parameter - * @returns Whether the parameter is a number - */ - const isNumber = (arg) => typeOf(arg) === 'number' && !Number.isNaN(arg); - /** - * Determine whether the parameter is a string any parameter - * @returns Whether the parameter is a string - */ - const isString = (arg) => typeOf(arg) === 'string'; - /** - * Determine whether the parameter is an object any parameter - * @returns Whether the parameter is an object - */ - const isObject = (arg) => arg !== nullValue && typeOf(arg) === 'object'; - /** - * Global toString any parameter stringified parameters - */ - const globalToString = (arg) => ObjectCls.prototype.toString.call(arg); - /** - * Determine whether it is a normal object any parameter - * @returns Judgment result - */ - const isPlainObject = (arg) => globalToString(arg) === '[object Object]'; - /** - * Determine whether it is an instance of a certain class any parameter - * @returns Judgment result - */ - const instanceOf = (arg, cls) => arg instanceof cls; - /** - * Unified timestamp acquisition function - * @returns Timestamp - */ - const getTime = (date) => (date ? date.getTime() : Date.now()); - /** - * Get the alova instance through the method instance alova example - */ - const getContext = (methodInstance) => methodInstance.context; - /** - * Get method instance configuration data - * @returns Configuration object - */ - const getConfig = (methodInstance) => methodInstance.config; - /** - * Get alova configuration data alova configuration object - */ - const getContextOptions = (alovaInstance) => alovaInstance.options; - /** - * Get alova configuration data through method instance alova configuration object - */ - const getOptions = (methodInstance) => getContextOptions(getContext(methodInstance)); - /** - * Create uuid simple version uuid - */ - const uuid = () => { - const timestamp = new Date().getTime(); - return Math.floor(Math.random() * timestamp).toString(36); - }; - /** - * Get the key value of the method instance method instance - * @returns The key value of this method instance - */ - const getMethodInternalKey = (methodInstance) => methodInstance.key; - /** - * Get the request method object - * @param methodHandler Request method handle - * @param args Method call parameters request method object - */ - const getHandlerMethod$1 = (methodHandler, assert, args = []) => { - const methodInstance = isFn(methodHandler) ? methodHandler(...args) : methodHandler; - assert(!!methodInstance.key, 'hook handler must be a method instance or a function that returns method instance'); - return methodInstance; - }; - const objAssign = (target, ...sources) => ObjectCls.assign(target, ...sources); - /** - * Excludes specified attributes from a data collection and returns a new data collection data collection - * @param keys Excluded keys new data collection - */ - const omit = (obj, ...keys) => { - const result = {}; - for (const key in obj) { - if (!keys.includes(key)) { - result[key] = obj[key]; - } - } - return result; - }; - /** - * the same as `Promise.withResolvers` - * @returns promise with resolvers. - */ - function usePromise() { - let retResolve; - let retReject; - const promise = new Promise((resolve, reject) => { - retResolve = resolve; - retReject = reject; - }); - return { promise, resolve: retResolve, reject: retReject }; - } - /** - * Get cached configuration parameters, fixedly returning an object in the format { e: function, c: any, f: any, m: number, s: boolean, t: string } e is the abbreviation of expire, which returns the cache expiration time point (timestamp) in milliseconds. - * c is controlled, indicating whether it is a controlled cache - * f is the original value of cacheFor, which is used to call to obtain cached data when c is true. - * m is the abbreviation of mode, storage mode - * s is the abbreviation of storage, whether to store it locally - * t is the abbreviation of tag, which stores tags persistently. - * @param methodInstance method instance - * @returns Unified cache parameter object - */ - const getLocalCacheConfigParam = (methodInstance) => { - const { cacheFor } = getConfig(methodInstance); - const getCacheExpireTs = (cacheExpire) => isNumber(cacheExpire) ? getTime() + cacheExpire : getTime(cacheExpire || undefinedValue); - let cacheMode = MEMORY; - let expire = () => 0; - let store = falseValue; - let tag = undefinedValue; - const controlled = isFn(cacheFor); - if (!controlled) { - let expireColumn = cacheFor; - if (isPlainObject(cacheFor)) { - const { mode = MEMORY, expire, tag: configTag } = cacheFor || {}; - cacheMode = mode; - store = mode === STORAGE_RESTORE; - tag = configTag ? configTag.toString() : undefinedValue; - expireColumn = expire; - } - expire = (mode) => getCacheExpireTs(isFn(expireColumn) ? expireColumn({ method: methodInstance, mode }) : expireColumn); - } - return { - f: cacheFor, - c: controlled, - e: expire, - m: cacheMode, - s: store, - t: tag - }; - }; - /** - * Create class instance - * @param Cls Constructor - * @param args Constructor parameters class instance - */ - const newInstance = (Cls, ...args) => new Cls(...args); - /** - * Unified configuration - * @param data - * @returns unified configuration - */ - const sloughConfig = (config, args = []) => isFn(config) ? config(...args) : config; - /** - * Create an executor that calls multiple times synchronously and only executes it once asynchronously - */ - const createSyncOnceRunner = (delay = 0) => { - let timer = undefinedValue; - // Executing multiple calls to this function will execute once asynchronously - return (fn) => { - if (timer) { - clearTimeout(timer); - } - timer = setTimeoutFn(fn, delay); - }; - }; - /** - * Create an asynchronous function queue, the asynchronous function will be executed serially queue add function - */ - const createAsyncQueue = (catchError = falseValue) => { - const queue = []; - let completedHandler = undefinedValue; - let executing = false; - const executeQueue = async () => { - executing = true; - while (len(queue) > 0) { - const asyncFunc = shift(queue); - if (asyncFunc) { - await asyncFunc(); - } - } - completedHandler && completedHandler(); - executing = false; - }; - const addQueue = (asyncFunc) => newInstance((PromiseCls), (resolve, reject) => { - const wrappedFunc = () => promiseThen(asyncFunc(), resolve, err => { - catchError ? resolve(undefinedValue) : reject(err); - }); - pushItem(queue, wrappedFunc); - if (!executing) { - executeQueue(); - } - }); - const onComplete = (fn) => { - completedHandler = fn; - }; - return { - addQueue, - onComplete - }; - }; - /** - * Traverse the target object deeply target audience - * @param callback Traversal callback - * @param preorder Whether to traverse in preorder, the default is true - * @param key The currently traversed key - * @param parent The parent node currently traversed - */ - const walkObject = (target, callback, preorder = trueValue, key, parent) => { - const callCallback = () => { - if (parent && key) { - target = callback(target, key, parent); - if (target !== parent[key]) { - parent[key] = target; - } - } - }; - // Preorder traversal - preorder && callCallback(); - if (isObject(target)) { - for (const i in target) { - if (!instanceOf(target, String)) { - walkObject(target[i], callback, preorder, i, target); - } - } - } - // Postal order traversal - !preorder && callCallback(); - return target; - }; - const cacheKeyPrefix = '$a.'; - /** - * build common cache key. - */ - const buildNamespacedCacheKey = (namespace, key) => cacheKeyPrefix + namespace + key; - /** - * Calculate retry delay time based on avoidance strategy and number of retries avoid parameters - * @param retryTimes Number of retries - * @returns Retry delay time - */ - const delayWithBackoff = (backoff, retryTimes) => { - let { startQuiver, endQuiver } = backoff; - const { delay, multiplier = 1 } = backoff; - let retryDelayFinally = (delay || 0) * multiplier ** (retryTimes - 1); - // If start quiver or end quiver has a value, you need to increase the random jitter value in the specified range - if (startQuiver || endQuiver) { - startQuiver = startQuiver || 0; - endQuiver = endQuiver || 1; - retryDelayFinally += - retryDelayFinally * startQuiver + Math.random() * retryDelayFinally * (endQuiver - startQuiver); - retryDelayFinally = Math.floor(retryDelayFinally); // round delay - } - return retryDelayFinally; - }; - /** - * Build the complete url baseURL path url parameters complete url - */ - const buildCompletedURL = (baseURL, url, params) => { - // If the Base url ends with /, remove / - baseURL = baseURL.endsWith('/') ? baseURL.slice(0, -1) : baseURL; - // If it does not start with /or http protocol, you need to add / - // Compatible with some RESTful usage fix: https://github.com/alovajs/alova/issues/382 - if (url !== '') { - url = url.match(/^(\/|https?:\/\/)/) ? url : `/${url}`; - } - const completeURL = baseURL + url; - // Convert params object to get string - // Filter out those whose value is undefined - const paramsStr = mapItem(filterItem(objectKeys(params), key => params[key] !== undefinedValue), key => `${key}=${params[key]}`).join('&'); - // Splice the get parameters behind the url. Note that the url may already have parameters. - return paramsStr - ? +completeURL.includes('?') - ? `${completeURL}&${paramsStr}` - : `${completeURL}?${paramsStr}` - : completeURL; - }; - - /** - * alova error class - */ - class AlovaError extends Error { - constructor(prefix, message, errorCode) { - super(message + (errorCode ? `\n\nFor detailed: https://alova.js.org/error#${errorCode}` : '')); - this.name = `[alova${prefix ? `/${prefix}` : ''}]`; - } - } - /** - * Custom assertion function that throws an error when the expression is false - * When errorCode is passed in, a link to the error document will be provided to guide the user to correct it. - * @param expression Judgment expression, true or false - * @param message Assert message - */ - const createAssert = (prefix = '') => (expression, message, errorCode) => { - if (!expression) { - throw newInstance(AlovaError, prefix, message, errorCode); - } - }; - - const createEventManager = () => { - const eventMap = {}; - return { - eventMap, - on(type, handler) { - const eventTypeItem = (eventMap[type] = eventMap[type] || []); - pushItem(eventTypeItem, handler); - // return the off function - return () => { - eventMap[type] = filterItem(eventTypeItem, item => item !== handler); - }; - }, - off(type, handler) { - const handlers = eventMap[type]; - if (!handlers) { - return; - } - if (handler) { - const index = handlers.indexOf(handler); - index > -1 && handlers.splice(index, 1); - } - else { - delete eventMap[type]; - } - }, - emit(type, event) { - const handlers = eventMap[type] || []; - return mapItem(handlers, handler => handler(event)); - } - }; - }; - const decorateEvent = (onEvent, decoratedHandler) => { - const emitter = createEventManager(); - const eventType = uuid(); - const eventReturn = onEvent(event => emitter.emit(eventType, event)); - return (handler) => { - emitter.on(eventType, event => { - decoratedHandler(handler, event); - }); - return eventReturn; - }; - }; - - class FrameworkReadableState { - constructor(state, key, dehydrate, exportState) { - this.s = state; - this.k = key; - this.$dhy = dehydrate; - this.$exp = exportState; - } - get v() { - return this.$dhy(this.s); - } - get e() { - return this.$exp(this.s); - } - } - class FrameworkState extends FrameworkReadableState { - constructor(state, key, dehydrate, exportState, update) { - super(state, key, dehydrate, exportState); - this.$upd = update; - } - set v(newValue) { - this.$upd(this.s, newValue); - } - get v() { - return super.v; - } - } - - const defaultVisitorMeta = { - authRole: null - }; - const defaultLoginMeta = { - authRole: 'login' - }; - const defaultLogoutMeta = { - authRole: 'logout' - }; - const defaultRefreshTokenMeta = { - authRole: 'refreshToken' - }; - const checkMethodRole = ({ meta }, metaMatches) => { - if (isPlainObject(meta)) { - for (const key in meta) { - if (Object.prototype.hasOwnProperty.call(meta, key)) { - const matchedMetaItem = metaMatches[key]; - if (instanceOf(matchedMetaItem, RegExp) ? matchedMetaItem.test(meta[key]) : meta[key] === matchedMetaItem) { - return trueValue; - } - } - } - } - return falseValue; - }; - const waitForTokenRefreshed = (method, waitingList) => newInstance(PromiseCls, resolve => { - pushItem(waitingList, { - method, - resolve - }); - }); - const callHandlerIfMatchesMeta = (method, authorizationInterceptor, defaultMeta, response) => { - if (checkMethodRole(method, (authorizationInterceptor === null || authorizationInterceptor === void 0 ? void 0 : authorizationInterceptor.metaMatches) || defaultMeta)) { - const handler = isFn(authorizationInterceptor) - ? authorizationInterceptor - : isPlainObject(authorizationInterceptor) && isFn(authorizationInterceptor.handler) - ? authorizationInterceptor.handler - : noop; - return handler(response, method); - } - }; - const refreshTokenIfExpired = async (method, waitingList, updateRefreshStatus, handlerParams, refreshToken, tokenRefreshing) => { - // When the number of handle params is greater than 2, it means that this function is called from the response, and the original interface needs to be requested again. - const fromResponse = len(handlerParams) >= 2; - let isExpired = refreshToken === null || refreshToken === void 0 ? void 0 : refreshToken.isExpired(...handlerParams); - // Compatible with synchronous and asynchronous functions - if (instanceOf(isExpired, PromiseCls)) { - isExpired = await isExpired; - } - if (isExpired) { - try { - // Make another judgment in the response to prevent multiple requests to refresh the token, intercept and wait for the token sent before the token refresh is completed. - let intentToRefreshToken = trueValue; - if (fromResponse && tokenRefreshing) { - intentToRefreshToken = falseValue; // The requests waiting here indicate that the token is being refreshed. When they pass, there is no need to refresh the token again. - await waitForTokenRefreshed(method, waitingList); - } - if (intentToRefreshToken) { - updateRefreshStatus(trueValue); - // Call refresh token - await (refreshToken === null || refreshToken === void 0 ? void 0 : refreshToken.handler(...handlerParams)); - updateRefreshStatus(falseValue); - // After the token refresh is completed, the requests in the waiting list are notified. - forEach(waitingList, ({ resolve }) => resolve()); - } - if (fromResponse) { - // Because the original interface is being requested again, superposition with the previous request will result in repeated calls to transform, so it is necessary to leave transform empty to remove one call. - const { config } = method; - const methodTransformData = config.transform; - config.transform = undefinedValue; - const resentData = await method; - config.transform = methodTransformData; - return resentData; - } - } - finally { - updateRefreshStatus(falseValue); - splice(waitingList, 0, len(waitingList)); // Clear waiting list - } - } - }; - const onResponded2Record = (onRespondedHandlers) => { - let successHandler = undefinedValue; - let errorHandler = undefinedValue; - let onCompleteHandler = undefinedValue; - if (isFn(onRespondedHandlers)) { - successHandler = onRespondedHandlers; - } - else if (isPlainObject(onRespondedHandlers)) { - const { onSuccess, onError, onComplete } = onRespondedHandlers; - successHandler = isFn(onSuccess) ? onSuccess : successHandler; - errorHandler = isFn(onError) ? onError : errorHandler; - onCompleteHandler = isFn(onComplete) ? onComplete : onCompleteHandler; - } - return { - onSuccess: successHandler, - onError: errorHandler, - onComplete: onCompleteHandler - }; - }; - - /** - * Create a client-side token authentication interceptor - * @param options Configuration parameters - * @returns token authentication interceptor function - */ - const createClientTokenAuthentication = ({ visitorMeta, login, logout, refreshToken, assignToken = noop }) => { - let tokenRefreshing = falseValue; - const waitingList = []; - const onAuthRequired = onBeforeRequest => async (method) => { - const isVisitorRole = checkMethodRole(method, visitorMeta || defaultVisitorMeta); - const isLoginRole = checkMethodRole(method, (login === null || login === void 0 ? void 0 : login.metaMatches) || defaultLoginMeta); - // Ignored, login, and token refresh requests do not perform token authentication. - if (!isVisitorRole && - !isLoginRole && - !checkMethodRole(method, (refreshToken === null || refreshToken === void 0 ? void 0 : refreshToken.metaMatches) || defaultRefreshTokenMeta)) { - // If the token is being refreshed, wait for the refresh to complete before sending a request. - if (tokenRefreshing) { - await waitForTokenRefreshed(method, waitingList); - } - await refreshTokenIfExpired(method, waitingList, refreshing => { - tokenRefreshing = refreshing; - }, [method], refreshToken); - } - // Requests from non-guest and logged-in roles will enter the assignment token function - if (!isVisitorRole && !isLoginRole) { - await assignToken(method); - } - return onBeforeRequest === null || onBeforeRequest === void 0 ? void 0 : onBeforeRequest(method); - }; - const onResponseRefreshToken = originalResponded => { - const respondedRecord = onResponded2Record(originalResponded); - return { - ...respondedRecord, - onSuccess: async (response, method) => { - await callHandlerIfMatchesMeta(method, login, defaultLoginMeta, response); - await callHandlerIfMatchesMeta(method, logout, defaultLogoutMeta, response); - return (respondedRecord.onSuccess || $self)(response, method); - } - }; - }; - return { - waitingList, - onAuthRequired, - onResponseRefreshToken - }; - }; - /** - * Create a server-side token authentication interceptor - * @param options Configuration parameters - * @returns token authentication interceptor function - */ - const createServerTokenAuthentication = ({ visitorMeta, login, logout, refreshTokenOnSuccess, refreshTokenOnError, assignToken = noop }) => { - let tokenRefreshing = falseValue; - const waitingList = []; - const onAuthRequired = onBeforeRequest => async (method) => { - const isVisitorRole = checkMethodRole(method, visitorMeta || defaultVisitorMeta); - const isLoginRole = checkMethodRole(method, (login === null || login === void 0 ? void 0 : login.metaMatches) || defaultLoginMeta); - // Ignored, login, and token refresh requests do not perform token authentication. - if (!isVisitorRole && - !isLoginRole && - !checkMethodRole(method, (refreshTokenOnSuccess === null || refreshTokenOnSuccess === void 0 ? void 0 : refreshTokenOnSuccess.metaMatches) || defaultRefreshTokenMeta) && - !checkMethodRole(method, (refreshTokenOnError === null || refreshTokenOnError === void 0 ? void 0 : refreshTokenOnError.metaMatches) || defaultRefreshTokenMeta)) { - // If the token is being refreshed, wait for the refresh to complete before sending a request. - if (tokenRefreshing) { - await waitForTokenRefreshed(method, waitingList); - } - } - if (!isVisitorRole && !isLoginRole) { - await assignToken(method); - } - return onBeforeRequest === null || onBeforeRequest === void 0 ? void 0 : onBeforeRequest(method); - }; - const onResponseRefreshToken = onRespondedHandlers => { - const respondedRecord = onResponded2Record(onRespondedHandlers); - return { - ...respondedRecord, - onSuccess: async (response, method) => { - if (!checkMethodRole(method, visitorMeta || defaultVisitorMeta) && - !checkMethodRole(method, (login === null || login === void 0 ? void 0 : login.metaMatches) || defaultLoginMeta) && - !checkMethodRole(method, (refreshTokenOnSuccess === null || refreshTokenOnSuccess === void 0 ? void 0 : refreshTokenOnSuccess.metaMatches) || defaultRefreshTokenMeta)) { - const dataResent = await refreshTokenIfExpired(method, waitingList, refreshing => { - tokenRefreshing = refreshing; - }, [response, method], refreshTokenOnSuccess, tokenRefreshing); - if (dataResent) { - return dataResent; - } - } - await callHandlerIfMatchesMeta(method, login, defaultLoginMeta, response); - await callHandlerIfMatchesMeta(method, logout, defaultLogoutMeta, response); - return (respondedRecord.onSuccess || $self)(response, method); - }, - onError: async (error, method) => { - if (!checkMethodRole(method, visitorMeta || defaultVisitorMeta) && - !checkMethodRole(method, (login === null || login === void 0 ? void 0 : login.metaMatches) || defaultLoginMeta) && - !checkMethodRole(method, (refreshTokenOnError === null || refreshTokenOnError === void 0 ? void 0 : refreshTokenOnError.metaMatches) || defaultRefreshTokenMeta)) { - const dataResent = await refreshTokenIfExpired(method, waitingList, refreshing => { - tokenRefreshing = refreshing; - }, [error, method], refreshTokenOnError, tokenRefreshing); - if (dataResent) { - return dataResent; - } - } - return (respondedRecord.onError || noop)(error, method); - } - }; - }; - return { - waitingList, - onAuthRequired, - onResponseRefreshToken - }; - }; - - /** - * Compatible functions, throwing parameters - * @param error mistake - */ - const throwFn = (error) => { - throw error; - }; - function useCallback(onCallbackChange = noop) { - let callbacks = []; - const setCallback = (fn) => { - if (!callbacks.includes(fn)) { - callbacks.push(fn); - onCallbackChange(callbacks); - } - // Return unregister function - return () => { - callbacks = filterItem(callbacks, e => e !== fn); - onCallbackChange(callbacks); - }; - }; - const triggerCallback = (...args) => { - if (callbacks.length > 0) { - return forEach(callbacks, fn => fn(...args)); - } - }; - const removeAllCallback = () => { - callbacks = []; - onCallbackChange(callbacks); - }; - return [setCallback, triggerCallback, removeAllCallback]; - } - /** - * Create a debounce function and trigger the function immediately when delay is 0 - * Scenario: When calling useWatcher and setting immediate to true, the first call must be executed immediately, otherwise it will cause a delayed call - * @param {GeneralFn} fn callback function - * @param {number|(...args: any[]) => number} delay Delay description, dynamic delay can be achieved when set as a function - * @returns Delayed callback function - */ - const debounce = (fn, delay) => { - let timer = nullValue; - return function debounceFn(...args) { - const bindFn = fn.bind(this, ...args); - const delayMill = isNumber(delay) ? delay : delay(...args); - timer && clearTimeoutTimer(timer); - if (delayMill > 0) { - timer = setTimeoutFn(bindFn, delayMill); - } - else { - bindFn(); - } - }; - }; - /** - * Get the request method object - * @param methodHandler Request method handle - * @param args Method call parameters - * @returns request method object - */ - const getHandlerMethod = (methodHandler, args = []) => { - const methodInstance = isFn(methodHandler) ? methodHandler(...args) : methodHandler; - createAssert('scene')(instanceOf(methodInstance, alova.Method), 'hook handler must be a method instance or a function that returns method instance'); - return methodInstance; - }; - /** - * Convert each value of the object and return the new object - * @param obj object - * @param callback callback function - * @returns converted object - */ - const mapObject = (obj, callback) => { - const ret = {}; - for (const key in obj) { - ret[key] = callback(obj[key], key, obj); - } - return ret; - }; - var EnumHookType; - (function (EnumHookType) { - EnumHookType[EnumHookType["USE_REQUEST"] = 1] = "USE_REQUEST"; - EnumHookType[EnumHookType["USE_WATCHER"] = 2] = "USE_WATCHER"; - EnumHookType[EnumHookType["USE_FETCHER"] = 3] = "USE_FETCHER"; - })(EnumHookType || (EnumHookType = {})); - /** - * create simple and unified, framework-independent states creators and handlers. - * @param statesHook states hook from `promiseStatesHook` function of alova - * @param referingObject refering object exported from `promiseStatesHook` function - * @returns simple and unified states creators and handlers - */ - function statesHookHelper(statesHook, referingObject = { trackedKeys: {}, bindError: falseValue }) { - const ref = (initialValue) => (statesHook.ref ? statesHook.ref(initialValue) : { current: initialValue }); - referingObject = ref(referingObject).current; - const exportState = (state) => (statesHook.export || $self)(state, referingObject); - const memorize = (fn) => { - if (!isFn(statesHook.memorize)) { - return fn; - } - const memorizedFn = statesHook.memorize(fn); - memorizedFn.memorized = true; - return memorizedFn; - }; - const { dehydrate } = statesHook; - // For performance reasons, only value is different, and the key is tracked can be updated. - const update = (newValue, state, key) => newValue !== dehydrate(state, key, referingObject) && - referingObject.trackedKeys[key] && - statesHook.update(newValue, state, key, referingObject); - const mapDeps = (deps) => mapItem(deps, item => (instanceOf(item, FrameworkReadableState) ? item.e : item)); - const createdStateList = []; - // key of deps on computed - const depKeys = {}; - return { - create: (initialValue, key) => { - pushItem(createdStateList, key); // record the keys of created states. - return newInstance((FrameworkState), statesHook.create(initialValue, key, referingObject), key, state => dehydrate(state, key, referingObject), exportState, (state, newValue) => update(newValue, state, key)); - }, - computed: (getter, depList, key) => { - // Collect all dependencies in computed - forEach(depList, dep => { - if (dep.k) { - depKeys[dep.k] = true; - } - }); - return newInstance((FrameworkReadableState), statesHook.computed(getter, mapDeps(depList), key, referingObject), key, state => dehydrate(state, key, referingObject), exportState); - }, - effectRequest: (effectRequestParams) => statesHook.effectRequest(effectRequestParams, referingObject), - ref, - watch: (source, callback) => statesHook.watch(mapDeps(source), callback, referingObject), - onMounted: (callback) => statesHook.onMounted(callback, referingObject), - onUnmounted: (callback) => statesHook.onUnmounted(callback, referingObject), - memorize, - /** - * refering object that sharing some value with this object. - */ - __referingObj: referingObject, - /** - * expose provider for specified use hook. - * @param object object that contains state proxy, framework state, operating function and event binder. - * @returns provider component. - */ - exposeProvider: (object) => { - const provider = {}; - const originalStatesMap = {}; - for (const key in object) { - const value = object[key]; - const isValueFunction = isFn(value); - // if it's a memorized function, don't memorize it any more, add it to provider directly. - // if it's start with `on`, that indicates it is an event binder, we should define a new function which return provider object. - // if it's a common function, add it to provider with memorize mode. - // Note that: in some situation, state is a function such as solid's signal, and state value is set to function in react, the state will be detected as a function. so we should check whether the key is in `trackedKeys` - if (isValueFunction && !referingObject.trackedKeys[key]) { - provider[key] = key.startsWith('on') - ? (...args) => { - value(...args); - // eslint-disable-next-line - return completedProvider; - } - : value.memorized - ? value - : memorize(value); - } - else { - const isFrameworkState = instanceOf(value, FrameworkReadableState); - if (isFrameworkState) { - originalStatesMap[key] = value.s; - } - // otherwise, it's a state proxy or framework state, add it to provider with getter mode. - ObjectCls.defineProperty(provider, key, { - get: () => { - // record the key that is being tracked. - referingObject.trackedKeys[key] = trueValue; - return isFrameworkState ? value.e : value; - }, - // set need to set an function, - // otherwise it will throw `TypeError: Cannot set property __referingObj of # which has only a getter` when setting value - set: noop, - enumerable: trueValue, - configurable: trueValue - }); - } - } - const { update: nestedHookUpdate, __proxyState: nestedProxyState } = provider; - // reset the tracked keys and bingError flag, so that the nest hook providers can be initialized. - // Always track the dependencies in computed - referingObject.trackedKeys = { - ...depKeys - }; - referingObject.bindError = falseValue; - const extraProvider = { - // expose referingObject automatically. - __referingObj: referingObject, - // the new updating function that can update the new states and nested hook states. - update: memorize((newStates) => { - objectKeys(newStates).forEach(key => { - if (includes(createdStateList, key)) { - update(newStates[key], originalStatesMap[key], key); - } - else if (key in provider && isFn(nestedHookUpdate)) { - nestedHookUpdate({ - [key]: newStates[key] - }); - } - }); - }), - __proxyState: memorize((key) => { - if (includes(createdStateList, key) && instanceOf(object[key], FrameworkReadableState)) { - // need to tag the key that is being tracked so that it can be updated with `state.v = xxx`. - referingObject.trackedKeys[key] = trueValue; - return object[key]; - } - return nestedProxyState(key); - }) - }; - const completedProvider = objAssign(provider, extraProvider); - return completedProvider; - }, - /** - * transform state proxies to object. - * @param states proxy array of framework states - * @param filterKey filter key of state proxy - * @returns an object that contains the states of target form - */ - objectify: (states, filterKey) => states.reduce((result, item) => { - result[item.k] = filterKey ? item[filterKey] : item; - return result; - }, {}), - transformState2Proxy: (state, key) => newInstance((FrameworkState), state, key, state => dehydrate(state, key, referingObject), exportState, (state, newValue) => update(newValue, state, key)) - }; - } - - const coreAssert = createAssert(''); - const requestHookAssert = createAssert('useRequest'); - const watcherHookAssert = createAssert('useWatcher'); - const fetcherHookAssert = createAssert('useFetcher'); - const coreHookAssert = (hookType) => ({ - [EnumHookType.USE_REQUEST]: requestHookAssert, - [EnumHookType.USE_WATCHER]: watcherHookAssert, - [EnumHookType.USE_FETCHER]: fetcherHookAssert - })[hookType]; - /** - * Assert whether it is a method instance - * @param methodInstance method instance - */ - const assertMethod = (assert, methodInstance) => assert(instanceOf(methodInstance, alova.Method), 'expected a method instance.'); - - const KEY_SUCCESS = 'success'; - const KEY_ERROR = 'error'; - const KEY_COMPLETE = 'complete'; - - var createHook = (ht, c, eventManager, ro) => ({ - /** The method instance of the last request */ - m: undefinedValue, - /** saveStatesFns */ - sf: [], - /** removeStatesFns */ - rf: [], - /** frontStates */ - fs: {}, - /** eventManager */ - em: eventManager, - /** hookType, useRequest=1, useWatcher=2, useFetcher=3 */ - ht, - /** hook config */ - c, - /** referingObject */ - ro, - /** managedStates */ - ms: {} - }); - - // base event - class AlovaEventBase { - constructor(method, args) { - this.method = method; - this.args = args; - } - clone() { - return { ...this }; - } - static spawn(method, args) { - return new AlovaEventBase(method, args); - } - } - class AlovaSuccessEvent extends AlovaEventBase { - constructor(base, data, fromCache) { - super(base.method, base.args); - this.data = data; - this.fromCache = fromCache; - } - } - class AlovaErrorEvent extends AlovaEventBase { - constructor(base, error) { - super(base.method, base.args); - this.error = error; - } - } - class AlovaCompleteEvent extends AlovaEventBase { - constructor(base, status, data, fromCache, error) { - super(base.method, base.args); - this.status = status; - this.data = data; - this.fromCache = status === 'error' ? false : fromCache; - this.error = error; - } - } - // extend event - class AlovaSSEEvent extends AlovaEventBase { - constructor(base, eventSource) { - super(base.method, base.args); - this.eventSource = eventSource; - } - } - class AlovaSSEErrorEvent extends AlovaSSEEvent { - constructor(base, error) { - super(base, base.eventSource); - this.error = error; - } - } - class AlovaSSEMessageEvent extends AlovaSSEEvent { - constructor(base, data) { - super(base, base.eventSource); - this.data = data; - } - } - /** Sq top level events */ - class SQEvent { - constructor(behavior, method, silentMethod) { - this.behavior = behavior; - this.method = method; - this.silentMethod = silentMethod; - } - } - /** Sq global events */ - class GlobalSQEvent extends SQEvent { - constructor(behavior, method, silentMethod, queueName, retryTimes) { - super(behavior, method, silentMethod); - this.queueName = queueName; - this.retryTimes = retryTimes; - } - } - class GlobalSQSuccessEvent extends GlobalSQEvent { - constructor(behavior, method, silentMethod, queueName, retryTimes, data, vDataResponse) { - super(behavior, method, silentMethod, queueName, retryTimes); - this.data = data; - this.vDataResponse = vDataResponse; - } - } - class GlobalSQErrorEvent extends GlobalSQEvent { - constructor(behavior, method, silentMethod, queueName, retryTimes, error, retryDelay) { - super(behavior, method, silentMethod, queueName, retryTimes); - this.error = error; - this.retryDelay = retryDelay; - } - } - class GlobalSQFailEvent extends GlobalSQEvent { - constructor(behavior, method, silentMethod, queueName, retryTimes, error) { - super(behavior, method, silentMethod, queueName, retryTimes); - this.error = error; - } - } - /** Sq event */ - class ScopedSQEvent extends SQEvent { - constructor(behavior, method, silentMethod, args) { - super(behavior, method, silentMethod); - this.args = args; - } - } - class ScopedSQSuccessEvent extends ScopedSQEvent { - constructor(behavior, method, silentMethod, args, data) { - super(behavior, method, silentMethod, args); - this.data = data; - } - } - class ScopedSQErrorEvent extends ScopedSQEvent { - constructor(behavior, method, silentMethod, args, error) { - super(behavior, method, silentMethod, args); - this.error = error; - } - } - class ScopedSQRetryEvent extends ScopedSQEvent { - constructor(behavior, method, silentMethod, args, retryTimes, retryDelay) { - super(behavior, method, silentMethod, args); - this.retryTimes = retryTimes; - this.retryDelay = retryDelay; - } - } - class ScopedSQCompleteEvent extends ScopedSQEvent { - constructor(behavior, method, silentMethod, args, status, data, error) { - super(behavior, method, silentMethod, args); - this.status = status; - this.data = data; - this.error = error; - } - } - class RetriableRetryEvent extends AlovaEventBase { - constructor(base, retryTimes, retryDelay) { - super(base.method, base.args); - this.retryTimes = retryTimes; - this.retryDelay = retryDelay; - } - } - class RetriableFailEvent extends AlovaErrorEvent { - constructor(base, error, retryTimes) { - super(base, error); - this.retryTimes = retryTimes; - } - } - - const defaultMiddleware = (_, next) => next(); - - const stateCache = {}; - /** - * @description Get State cache data - * @param baseURL Base URL - * @param key Request key value - * @returns Cached response data, if not returned {} - */ - const getStateCache = (namespace, key) => { - const cachedState = stateCache[namespace] || {}; - return cachedState[key] || {}; - }; - /** - * @description Set State cache data - * @param baseURL Base URL - * @param key Request key value - * @param data cache data - */ - const setStateCache = (namespace, key, data, hookInstance) => { - const cachedState = (stateCache[namespace] = stateCache[namespace] || {}); - cachedState[key] = { - s: data, - h: hookInstance - }; - }; - /** - * @description Clear State cache data - * @param baseURL Base URL - * @param key Request key value - */ - const removeStateCache = (namespace, key) => { - const cachedState = stateCache[namespace]; - if (cachedState) { - deleteAttr(cachedState, key); - } - }; - - /** - * Unified processing of request logic for useRequest/useWatcher/useFetcher and other request hook functions - * @param hookInstance hook instance - * @param methodHandler Request method object or get function - * @param sendCallingArgs send function parameters - * @returns Request status - */ - function useHookToSendRequest(hookInstance, methodHandler, sendCallingArgs = []) { - const currentHookAssert = coreHookAssert(hookInstance.ht); - let methodInstance = getHandlerMethod$1(methodHandler, currentHookAssert, sendCallingArgs); - const { fs: frontStates, ht: hookType, c: useHookConfig, ms: managedStates } = hookInstance; - const { loading: loadingState, data: dataState, error: errorState } = frontStates; - const isFetcher = hookType === EnumHookType.USE_FETCHER; - const { force: forceRequest = falseValue, middleware = defaultMiddleware } = useHookConfig; - const alovaInstance = getContext(methodInstance); - const { id } = alovaInstance; - // If it is a silent request, on success will be called directly after the request, on error will not be triggered, and progress will not be updated. - const methodKey = getMethodInternalKey(methodInstance); - const { abortLast = trueValue } = useHookConfig; - const isFirstRequest = !hookInstance.m; - hookInstance.m = methodInstance; - return (async () => { - // Initialize status data, which does not need to be loaded when pulling data, because pulling data does not require returning data. - let removeStates = noop; - let saveStates = noop; - let isNextCalled = falseValue; - let responseHandlePromise = promiseResolve(undefinedValue); - let offDownloadEvent = noop; - let offUploadEvent = noop; - const cachedResponse = await alova.queryCache(methodInstance); - let fromCache = () => !!cachedResponse; - // Whether it is a controlled loading state. When it is true, loading will no longer be set to false in response processing. - let controlledLoading = falseValue; - if (!isFetcher) { - // Store the initial state in cache for subsequent updates - saveStates = frontStates => setStateCache(id, methodKey, frontStates, hookInstance); - saveStates({ ...frontStates, ...managedStates }); - // Setting the state removal function will be passed to the effect request in the hook, and it will be set to be called when the component is unloaded. - removeStates = () => removeStateCache(id, methodKey); - } - // The middleware function next callback function allows you to modify mandatory request parameters and even replace the method instance that is about to send the request. - const guardNext = guardNextConfig => { - isNextCalled = trueValue; - const { force: guardNextForceRequest = forceRequest, method: guardNextReplacingMethod = methodInstance } = guardNextConfig || {}; - const forceRequestFinally = sloughConfig(guardNextForceRequest, [ - newInstance((AlovaEventBase), methodInstance, sendCallingArgs) - ]); - const progressUpdater = (stage) => ({ loaded, total }) => { - frontStates[stage].v = { - loaded, - total - }; - }; - methodInstance = guardNextReplacingMethod; - // The latest controller needs to be saved every time a request is sent - pushItem(hookInstance.sf, saveStates); - pushItem(hookInstance.rf, removeStates); - // Loading will not be changed when the loading state is controlled - // The cache is missed, or loading needs to be set to true when forcing a request. - if (!controlledLoading) { - loadingState.v = !!forceRequestFinally || !cachedResponse; - } - // Determine whether to trigger a progress update based on the tracking status of downloading and uploading - const { downloading: enableDownload, uploading: enableUpload } = hookInstance.ro.trackedKeys; - offDownloadEvent = enableDownload ? methodInstance.onDownload(progressUpdater('downloading')) : offDownloadEvent; - offUploadEvent = enableUpload ? methodInstance.onUpload(progressUpdater('uploading')) : offUploadEvent; - responseHandlePromise = methodInstance.send(forceRequestFinally); - fromCache = () => methodInstance.fromCache || falseValue; - return responseHandlePromise; - }; - // Call middleware function - const commonContext = { - method: methodInstance, - cachedResponse, - config: useHookConfig, - abort: () => methodInstance.abort() - }; - // Whether it is necessary to update the response data and call the response callback - const toUpdateResponse = () => hookType !== EnumHookType.USE_WATCHER || !abortLast || hookInstance.m === methodInstance; - const controlLoading = (control = trueValue) => { - // only reset loading state in first request - if (control && isFirstRequest) { - loadingState.v = falseValue; - } - controlledLoading = control; - }; - // Call middleware function - const middlewareCompletePromise = isFetcher - ? middleware({ - ...commonContext, - args: sendCallingArgs, - fetch: (methodInstance, ...args) => { - assertMethod(currentHookAssert, methodInstance); - return useHookToSendRequest(hookInstance, methodInstance, args); - }, - proxyStates: omit(frontStates, 'data'), - controlLoading - }, guardNext) - : middleware({ - ...commonContext, - args: sendCallingArgs, - send: (...args) => useHookToSendRequest(hookInstance, methodHandler, args), - proxyStates: frontStates, - controlLoading - }, guardNext); - let finallyResponse = undefinedValue; - const baseEvent = (AlovaEventBase).spawn(methodInstance, sendCallingArgs); - try { - // Unified processing of responses - const middlewareReturnedData = await middlewareCompletePromise; - const afterSuccess = (data) => { - // Update cached response data - if (!isFetcher) { - toUpdateResponse() && (dataState.v = data); - } - else if (hookInstance.c.updateState !== falseValue) { - // Update the status in the cache, usually entered in use fetcher - const cachedState = getStateCache(id, methodKey).s; - cachedState && (cachedState.data.v = data); - } - // If the response data needs to be updated, the corresponding callback function is triggered after the request. - if (toUpdateResponse()) { - errorState.v = undefinedValue; - // Loading status will no longer change to false when controlled - !controlledLoading && (loadingState.v = falseValue); - hookInstance.em.emit(KEY_SUCCESS, newInstance((AlovaSuccessEvent), baseEvent, data, fromCache())); - hookInstance.em.emit(KEY_COMPLETE, newInstance((AlovaCompleteEvent), baseEvent, KEY_SUCCESS, data, fromCache(), undefinedValue)); - } - return data; - }; - finallyResponse = - // When no data is returned or undefined is returned in the middleware, get the real response data - // Otherwise, use the returned data and no longer wait for the response promise. At this time, you also need to call the response callback. - middlewareReturnedData !== undefinedValue - ? afterSuccess(middlewareReturnedData) - : isNextCalled - ? // There are two possibilities when middlewareCompletePromise is resolve - // 1. The request is normal - // 2. The request is incorrect, but the error is captured by the middleware function. At this time, the success callback will also be called, that is, afterSuccess(undefinedValue) - await promiseThen(responseHandlePromise, afterSuccess, () => afterSuccess(undefinedValue)) - : // If is next called is not called, no data is returned - undefinedValue; - // When the next function is not called, update loading to false. - !isNextCalled && !controlledLoading && (loadingState.v = falseValue); - } - catch (error) { - if (toUpdateResponse()) { - // Controls the output of error messages - errorState.v = error; - // Loading status will no longer change to false when controlled - !controlledLoading && (loadingState.v = falseValue); - hookInstance.em.emit(KEY_ERROR, newInstance((AlovaErrorEvent), baseEvent, error)); - hookInstance.em.emit(KEY_COMPLETE, newInstance((AlovaCompleteEvent), baseEvent, KEY_ERROR, undefinedValue, fromCache(), error)); - } - throw error; - } - // Unbind download and upload events after responding - offDownloadEvent(); - offUploadEvent(); - return finallyResponse; - })(); - } - - const refCurrent = (ref) => ref.current; - /** - * Create request status and uniformly process consistent logic in useRequest, useWatcher, and useFetcher - * This function will call the creation function of statesHook to create the corresponding request state. - * When the value is empty, it means useFetcher enters, and data status and cache status are not needed at this time. - * @param methodInstance request method object - * @param useHookConfig hook request configuration object - * @param initialData Initial data data - * @param immediate Whether to initiate a request immediately - * @param watchingStates The monitored status, if not passed in, call handleRequest directly. - * @param debounceDelay Delay time for request initiation - * @returns Current request status, operation function and event binding function - */ - function createRequestState(hookType, methodHandler, useHookConfig, initialData, immediate = falseValue, watchingStates, debounceDelay = 0) { - var _a; - // shallow clone config object to avoid passing the same useHookConfig object which may cause vue2 state update error - useHookConfig = { ...useHookConfig }; - const { __referingObj: referingObject = { trackedKeys: {}, bindError: falseValue } } = useHookConfig; - let initialLoading = !!immediate; - let cachedResponse = undefinedValue; - // When sending a request immediately, you need to determine the initial loading value by whether to force the request and whether there is a cache. This has the following two benefits: - // 1. Sending the request immediately under react can save one rendering time - // 2. In the HTML rendered by SSR, the initial view is in the loading state to avoid the loading view flashing when displayed on the client. - if (immediate) { - // An error may be reported when calling the get handler method, and try/catch is required. - try { - const methodInstance = getHandlerMethod$1(methodHandler, coreHookAssert(hookType)); - const alovaInstance = getContext(methodInstance); - const l1CacheResult = alovaInstance.l1Cache.get(buildNamespacedCacheKey(alovaInstance.id, getMethodInternalKey(methodInstance))); - // The cache is only checked synchronously, so it does not take effect on asynchronous l1Cache adapters. - // It is recommended not to set up the asynchronous l1Cache adapter on the client side - if (l1CacheResult && !instanceOf(l1CacheResult, PromiseCls)) { - const [data, expireTimestamp] = l1CacheResult; - // If there is no expiration time, it means that the data will never expire. Otherwise, you need to determine whether it has expired. - if (!expireTimestamp || expireTimestamp > getTime()) { - cachedResponse = data; - } - } - const forceRequestFinally = sloughConfig((_a = useHookConfig.force) !== null && _a !== void 0 ? _a : falseValue); - initialLoading = !!forceRequestFinally || !cachedResponse; - } - catch (_b) { } - } - const { create, effectRequest, ref, objectify, exposeProvider, transformState2Proxy } = statesHookHelper(alova.promiseStatesHook(), referingObject); - const progress = { - total: 0, - loaded: 0 - }; - // Put the externally incoming supervised states into the front states collection together - const { managedStates = {} } = useHookConfig; - const managedStatesProxy = mapObject(managedStates, (state, key) => transformState2Proxy(state, key)); - const data = create(cachedResponse !== null && cachedResponse !== void 0 ? cachedResponse : (isFn(initialData) ? initialData() : initialData), 'data'); - const loading = create(initialLoading, 'loading'); - const error = create(undefinedValue, 'error'); - const downloading = create({ ...progress }, 'downloading'); - const uploading = create({ ...progress }, 'uploading'); - const frontStates = objectify([data, loading, error, downloading, uploading]); - const eventManager = createEventManager(); - const hookInstance = refCurrent(ref(createHook(hookType, useHookConfig, eventManager, referingObject))); - /** - * ## react ##Every time the function is executed, the following items need to be reset - */ - hookInstance.fs = frontStates; - hookInstance.em = eventManager; - hookInstance.c = useHookConfig; - hookInstance.ms = managedStatesProxy; - const hasWatchingStates = watchingStates !== undefinedValue; - // Initialize request event - // Unified send request function - const handleRequest = (handler = methodHandler, sendCallingArgs) => useHookToSendRequest(hookInstance, handler, sendCallingArgs); - // only call once when multiple values changed at the same time - const onceRunner = refCurrent(ref(createSyncOnceRunner())); - // Call handleRequest in a way that catches the exception - // Catching exceptions prevents exceptions from being thrown out - const wrapEffectRequest = (ro = referingObject, handler) => { - onceRunner(() => { - promiseCatch(handleRequest(handler), error => { - // the error tracking indicates that the error need to throw. - if (!ro.bindError && !ro.trackedKeys.error) { - throw error; - } - }); - }); - }; - /** - * fix: #421 - * Use ref wraps to prevent react from creating new debounce function in every render - * Explicit passing is required because the context will change - */ - const debouncingSendHandler = ref(debounce((_, ro, handler) => wrapEffectRequest(ro, handler), (changedIndex) => isNumber(changedIndex) ? (isArray(debounceDelay) ? debounceDelay[changedIndex] : debounceDelay) : 0)); - // Do not send requests when rendering on the server side - if (!alova.globalConfigMap.ssr) { - effectRequest({ - handler: - // When `watchingStates` is an array, it indicates the watching states (including an empty array). When it is undefined, it indicates the non-watching state. - hasWatchingStates - ? (changedIndex) => debouncingSendHandler.current(changedIndex, referingObject, methodHandler) - : () => wrapEffectRequest(referingObject), - removeStates: () => forEach(hookInstance.rf, fn => fn()), - saveStates: states => forEach(hookInstance.sf, fn => fn(states)), - frontStates: { ...frontStates, ...managedStatesProxy }, - watchingStates, - immediate: immediate !== null && immediate !== void 0 ? immediate : trueValue - }); - } - return exposeProvider({ - ...objectify([data, loading, error, downloading, uploading]), - abort: () => hookInstance.m && hookInstance.m.abort(), - /** - * Manually initiate a request by executing this method - * @param sendCallingArgs Parameters passed in when calling the send function - * @param methodInstance method object - * @param isFetcher Whether to call isFetcher - * @returns Request promise - */ - send: (sendCallingArgs, methodInstance) => handleRequest(methodInstance, sendCallingArgs), - onSuccess(handler) { - eventManager.on(KEY_SUCCESS, handler); - }, - onError(handler) { - // will not throw error when bindError is true. - // it will reset in `exposeProvider` so that ignore the error binding in custom use hooks. - referingObject.bindError = trueValue; - eventManager.on(KEY_ERROR, handler); - }, - onComplete(handler) { - eventManager.on(KEY_COMPLETE, handler); - } - }); - } - - /** - * Fetch request data and cache request method object - */ - function useFetcher(config = {}) { - const props = createRequestState(EnumHookType.USE_FETCHER, noop, config); - const { send } = props; - deleteAttr(props, 'send'); - return objAssign(props, { - /** - * Fetch data fetch will definitely send a request, and if the currently requested data has a corresponding management state, this state will be updated. - * @param matcher Method object - */ - fetch: (matcher, ...args) => { - assertMethod(fetcherHookAssert, matcher); - return send(args, matcher); - } - }); - } - - function useRequest(handler, config = {}) { - const { immediate = trueValue, initialData } = config; - const props = createRequestState(EnumHookType.USE_REQUEST, handler, config, initialData, !!immediate); - const { send } = props; - return objAssign(props, { - send: (...args) => send(args) - }); - } - - function useWatcher(handler, watchingStates, config = {}) { - watcherHookAssert(watchingStates && len(watchingStates) > 0, 'expected at least one watching state'); - const { immediate, debounce = 0, initialData } = config; - const props = createRequestState(EnumHookType.USE_WATCHER, handler, config, initialData, !!immediate, // !!immediate means not send request immediately - watchingStates, debounce); - const { send } = props; - return objAssign(props, { - send: (...args) => send(args) - }); - } - - var createSnapshotMethodsManager = (handler) => { - let methodSnapshots = {}; - return { - snapshots: () => methodSnapshots, - save(methodInstance, force = falseValue) { - const key = getMethodInternalKey(methodInstance); - // Because it is impossible to locate the location of the total data in the cache - // Therefore, this field is maintained redundantly here. - if (!methodSnapshots[key] || force) { - methodSnapshots[key] = { - entity: methodInstance - }; - } - }, - get: (entityOrPage) => methodSnapshots[getMethodInternalKey(instanceOf(entityOrPage, (alova.Method)) ? entityOrPage : handler(entityOrPage))], - remove(key) { - if (key) { - delete methodSnapshots[key]; - } - else { - methodSnapshots = {}; - } - } - }; - }; - - const paginationAssert = createAssert('usePagination'); - const indexAssert = (index, rawData) => paginationAssert(isNumber(index) && index < len(rawData), 'index must be a number that less than list length'); - const parseSendArgs = (args) => [ - args[args.length - 2], // refreshPage - args[args.length - 1], // isRefresh - args.slice(0, args.length - 2) // send args - ]; - var usePagination = (handler, config = {}) => { - const { create, computed, ref, watch, exposeProvider, objectify, __referingObj: referingObject } = statesHookHelper(alova.promiseStatesHook()); - const { preloadPreviousPage = trueValue, preloadNextPage = trueValue, total: totalGetter = res => res.total, data: dataGetter = res => res.data, append = falseValue, initialPage = 1, initialPageSize = 10, watchingStates = [], initialData, immediate = trueValue, middleware, force = noop, ...others } = config; - const handlerRef = ref(handler); - const isReset = ref(falseValue); // Used to control whether to reset - // The number of requests during reset. In order to prevent repeated requests during reset, use this parameter to limit requests. - const page = create(initialPage, 'page'); - const pageSize = create(initialPageSize, 'pageSize'); - const data = create((initialData ? dataGetter(initialData) || [] : []), 'data'); - const total = create(initialData ? totalGetter(initialData) : undefinedValue, 'total'); - // Save snapshots of all method instances used by the current hook - const { snapshots: methodSnapshots, get: getSnapshotMethods, save: saveSnapshot, remove: removeSnapshot } = ref(createSnapshotMethodsManager(page => handlerRef.current(page, pageSize.v))).current; - const listDataGetter = (rawData) => dataGetter(rawData) || rawData; - // Initialize fetcher - const fetchStates = useFetcher({ - __referingObj: referingObject, - updateState: falseValue, - force: ({ args }) => args[len(args) - 1] - }); - const { loading, fetch, abort: abortFetch, onSuccess: onFetchSuccess } = fetchStates; - const fetchingRef = ref(loading); - const getHandlerMethod = (refreshPage = page.v, customArgs = []) => { - const handlerMethod = handler(refreshPage, pageSize.v, ...customArgs); - // Define unified additional names to facilitate management - saveSnapshot(handlerMethod); - return handlerMethod; - }; - // When monitoring status changes, reset page to 1 - watch(watchingStates, () => { - page.v = initialPage; - isReset.current = trueValue; - }); - // Compatible with react, store functions that require proxy here - // In this way, the latest operation function can be called in the proxy function and avoid the react closure trap. - const delegationActions = ref({}); - // Calculate data, total, is last page parameters - const pageCount = computed(() => { - const totalVal = total.v; - return totalVal !== undefinedValue ? Math.ceil(totalVal / pageSize.v) : undefinedValue; - }, [pageSize, total], 'pageCount'); - const createDelegationAction = (actionName) => (...args) => delegationActions.current[actionName](...args); - const states = useWatcher((...args) => { - const [refreshPage, , customArgs] = parseSendArgs(args); - return getHandlerMethod(refreshPage, customArgs); - }, [...watchingStates, page.e, pageSize.e], { - __referingObj: referingObject, - immediate, - initialData, - managedStates: objectify([data, page, pageSize, total], 's'), - middleware(ctx, next) { - if (!middleware) { - return next(); - } - return middleware({ - ...ctx, - delegatingActions: { - refresh: createDelegationAction('refresh'), - insert: createDelegationAction('insert'), - remove: createDelegationAction('remove'), - replace: createDelegationAction('replace'), - reload: createDelegationAction('reload'), - getState: (stateKey) => { - const states = { - page, - pageSize, - data, - pageCount, - total, - // eslint-disable-next-line @typescript-eslint/no-use-before-define - isLastPage - }; - return states[stateKey].v; - } - } - }, next); - }, - force: event => event.args[1] || (isFn(force) ? force(event) : force), - ...others - }); - const { send } = states; - const nestedData = states.__proxyState('data'); - // Determine whether data can be preloaded - const canPreload = async (payload) => { - const { rawData = nestedData.v, preloadPage, fetchMethod, forceRequest = falseValue, isNextPage = falseValue } = payload; - const pageCountVal = pageCount.v; - const exceedPageCount = pageCountVal - ? preloadPage > pageCountVal - : isNextPage // If it is judged to preload the next page of data and there is no page count, it is judged by whether the data volume of the last page reaches the page size. - ? len(listDataGetter(rawData)) < pageSize.v - : falseValue; - const isMatchPageScope = preloadPage > 0 && !exceedPageCount; - if (!isMatchPageScope) { - return falseValue; - } - const { e: expireMilliseconds } = getLocalCacheConfigParam(fetchMethod); - const hasCache = await alova.queryCache(fetchMethod); - // If the cache time is less than or equal to the current time, it means that the cache is not set and the data will no longer be pre-pulled at this time. - // Or there is already a cache and it is not pre-fetched. - return expireMilliseconds(MEMORY) <= getTime() ? falseValue : forceRequest || !hasCache; - }; - // Preload next page data - const fetchNextPage = async (rawData, force, customArgs = []) => { - const nextPage = page.v + 1; - const fetchMethod = getHandlerMethod(nextPage, customArgs); - if (preloadNextPage && - (await canPreload({ - rawData, - preloadPage: nextPage, - fetchMethod, - isNextPage: trueValue, - forceRequest: force - }))) { - promiseCatch(fetch(fetchMethod, ...customArgs, force), noop); - } - }; - // Preload previous page data - const fetchPreviousPage = async (rawData, customArgs = []) => { - const prevPage = page.v - 1; - const fetchMethod = getHandlerMethod(prevPage, customArgs); - if (preloadPreviousPage && - (await canPreload({ - rawData, - preloadPage: prevPage, - fetchMethod - }))) { - promiseCatch(fetch(fetchMethod, ...customArgs, undefinedValue), noop); - } - }; - // If the returned data is smaller than the page size, it is considered the last page. - const isLastPage = computed(() => { - const dataRaw = nestedData.v; - if (!dataRaw) { - return trueValue; - } - const statesDataVal = listDataGetter(dataRaw); - const pageVal = page.v; - const pageCountVal = pageCount.v; - const dataLen = isArray(statesDataVal) ? len(statesDataVal) : 0; - return pageCountVal ? pageVal >= pageCountVal : dataLen < pageSize.v; - }, [page, pageCount, nestedData, pageSize], 'isLastPage'); - // Update current page cache - const updateCurrentPageCache = async () => { - const snapshotItem = getSnapshotMethods(page.v); - if (snapshotItem) { - await alova.setCache(snapshotItem.entity, (rawData) => { - // When caching is turned off, raw data is undefined - if (rawData) { - const cachedListData = listDataGetter(rawData) || []; - splice(cachedListData, 0, len(cachedListData), ...data.v); - return rawData; - } - }); - } - }; - onFetchSuccess(({ method, data: rawData }) => { - // When fetch has not responded yet and the page is flipped to the page number corresponding to fetch, the list data needs to be updated manually. - const snapshotItem = getSnapshotMethods(page.v); - if (snapshotItem && getMethodInternalKey(snapshotItem.entity) === getMethodInternalKey(method)) { - // If data is appended, data is updated - const listData = listDataGetter(rawData); // Update data parameters - if (append) { - // The current page data needs to be replaced during pull-down loading. - const dataRaw = data.v; - const pageSizeVal = pageSize.v; - // When performing a removal operation, the number of replacements is less than pageSize, and dataRaw % pageSizeVal will be greater than 0. - // When adding a new operation, the number of replacements is equal to pageSize. At this time, dataRaw % pageSizeVal will be equal to 0. No replacement is needed at this time. - const replaceNumber = len(dataRaw) % pageSizeVal; - if (replaceNumber > 0) { - const rawData = [...data.v]; - splice(rawData, (page.v - 1) * pageSizeVal, replaceNumber, ...listData); - data.v = rawData; - } - } - else { - data.v = listData; - } - } - }); - const awaitResolve = ref(undefinedValue); - const awaitReject = ref(undefinedValue); - states - .onSuccess(({ data: rawData, args, method }) => { - const [refreshPage, isRefresh, customArgs] = parseSendArgs(args); - const { total: cachedTotal } = getSnapshotMethods(method) || {}; - const typedRawData = rawData; - total.v = cachedTotal !== undefinedValue ? cachedTotal : totalGetter(typedRawData); - if (!isRefresh) { - fetchPreviousPage(typedRawData, customArgs); - fetchNextPage(typedRawData, falseValue, customArgs); - } - const pageSizeVal = pageSize.v; - const listData = listDataGetter(typedRawData); // Get array - paginationAssert(isArray(listData), 'Got wrong array, did you return the correct array of list in `data` function'); - // If data is appended, data is updated - if (append) { - // If it is reset, clear the data first - if (isReset.current) { - data.v = []; - } - if (refreshPage === undefinedValue) { - data.v = [...data.v, ...listData]; - } - else if (refreshPage) { - const rawData = [...data.v]; - // If the page is refreshed, the data on that page is replaced. - splice(rawData, (refreshPage - 1) * pageSizeVal, pageSizeVal, ...listData); - data.v = rawData; - } - } - else { - data.v = listData; - } - }) - .onSuccess(({ data }) => { - var _a; - (_a = awaitResolve.current) === null || _a === void 0 ? void 0 : _a.call(awaitResolve, data); - }) - .onError(({ error }) => { - var _a; - (_a = awaitReject.current) === null || _a === void 0 ? void 0 : _a.call(awaitReject, error); - }) - .onComplete(() => { - // Whether the request is successful or not, it must be reset is reset - isReset.current = falseValue; - }); - // Get the location of a list item - const getItemIndex = (item) => { - const index = data.v.indexOf(item); - paginationAssert(index >= 0, 'item is not found in list'); - return index; - }; - const { addQueue: add2AsyncQueue, onComplete: onAsyncQueueRunComplete } = ref(createAsyncQueue()).current; - /** - * Refresh the specified page number data. This function will ignore the cache and force the request to be sent. - * If no page number is passed in, the current page will be refreshed. - * If a list item is passed in, the page where the list item is located will be refreshed, which is only valid in append mode. - * @param pageOrItemPage Refreshed page number or list item - */ - const refresh = async (pageOrItemPage = page.v) => { - let refreshPage = pageOrItemPage; - let awaitPromise = promiseResolve(); - if (append) { - if (!isNumber(pageOrItemPage)) { - const itemIndex = getItemIndex(pageOrItemPage); - refreshPage = Math.floor(itemIndex / pageSize.v) + 1; - } - paginationAssert(refreshPage <= page.v, "refresh page can't greater than page"); - // Update current page data - awaitPromise = send(refreshPage, trueValue); - } - else { - paginationAssert(isNumber(refreshPage), 'unable to calculate refresh page by item in pagination mode'); - // If the number of pages is equal, refresh the current page, otherwise fetch data - awaitPromise = - refreshPage === page.v - ? send(undefinedValue, trueValue) - : fetch(handler(refreshPage, pageSize.v), trueValue); - } - return awaitPromise; - }; - // Delete all related caches except the current page and next page of this usehook - const invalidatePaginationCache = async (all = falseValue) => { - const pageVal = page.v; - const snapshotObj = methodSnapshots(); - let snapshots = objectValues(snapshotObj); - if (all) { - removeSnapshot(); - } - else { - // Filter out data from the previous page, current page, and next page - const excludeSnapshotKeys = mapItem(filterItem([getSnapshotMethods(pageVal - 1), getSnapshotMethods(pageVal), getSnapshotMethods(pageVal + 1)], Boolean), ({ entity }) => getMethodInternalKey(entity)); - snapshots = mapItem(filterItem(objectKeys(snapshotObj), key => !includes(excludeSnapshotKeys, key)), key => { - const item = snapshotObj[key]; - delete snapshotObj[key]; - return item; - }); - } - await alova.invalidateCache(mapItem(snapshots, ({ entity }) => entity)); - }; - // The reason for taking it out separately is that - // No matter how many times insert, remove, or a combination of them is called synchronously, the reset operation only needs to be executed asynchronously once - const resetCache = async () => { - fetchingRef.current && abortFetch(); - // cache invalidation - await invalidatePaginationCache(); - // When the amount of data on the next page does not exceed the page size, the next page is forced to be requested. Because there is a request for sharing, the fetching needs to be performed asynchronously after interrupting the request. - const snapshotItem = getSnapshotMethods(page.v + 1); - if (snapshotItem) { - const cachedListData = listDataGetter((await alova.queryCache(snapshotItem.entity)) || {}) || []; - fetchNextPage(undefinedValue, len(cachedListData) < pageSize.v); - } - }; - // Unified update of total number of items - const updateTotal = (offset) => { - if (offset === 0) { - return; - } - // Update current page - const totalVal = total.v; - if (isNumber(totalVal)) { - const offsetedTotal = Math.max(totalVal + offset, 0); - total.v = offsetedTotal; - const pageVal = page.v; - // Update redundant total field - forEach([getSnapshotMethods(pageVal - 1), getSnapshotMethods(pageVal), getSnapshotMethods(pageVal + 1)], item => { - item && (item.total = offsetedTotal); - }); - } - }; - /** - * Insert a piece of data - * If no index is passed in, it will be inserted at the front by default. - * If a list item is passed in, it will be inserted after the list item. If the list item is not in the list data, an error will be thrown. - * @param item insert - * @param position Insert position (index) or list item - */ - const insert = (item, position = 0) => { - onAsyncQueueRunComplete(resetCache); // The cache needs to be reset at the end of execution - return add2AsyncQueue(async () => { - const index = isNumber(position) ? position : getItemIndex(position) + 1; - let popItem = undefinedValue; - const rawData = [...data.v]; - // Only when the number of items currently displayed is exactly a multiple of page size, you need to remove an item of data to ensure that the number of operating pages is page size. - if (len(rawData) % pageSize.v === 0) { - popItem = rawData.pop(); - } - // If the insertion position is empty, it will be inserted to the front by default. - splice(rawData, index, 0, item); - data.v = rawData; - updateTotal(1); - // The cache of the current page is updated synchronously - await updateCurrentPageCache(); - // If there is a pop item, put it at the head of the next page cache, consistent with the remove operation. - // In this way, the performance will be consistent when insert and remove are called synchronously. - if (popItem) { - const snapshotItem = getSnapshotMethods(page.v + 1); - if (snapshotItem) { - await alova.setCache(snapshotItem.entity, (rawData) => { - if (rawData) { - const cachedListData = listDataGetter(rawData) || []; - cachedListData.unshift(popItem); - cachedListData.pop(); - return rawData; - } - }); - } - } - }); - }; - /** - * Remove a piece of data - * If a list item is passed in, the list item will be removed. If the list item is not in the list data, an error will be thrown. - * @param position Removed index or list item - */ - const remove = (...positions) => { - onAsyncQueueRunComplete(resetCache); // The cache needs to be reset at the end of execution - return add2AsyncQueue(async () => { - const indexes = mapItem(positions, position => { - const index = isNumber(position) ? position : getItemIndex(position); - indexAssert(index, data.v); - return index; - }); - const pageVal = page.v; - const nextPage = pageVal + 1; - const snapshotItem = getSnapshotMethods(nextPage); - const fillingItems = []; // padding data item - if (snapshotItem) { - await alova.setCache(snapshotItem.entity, (rawData) => { - if (rawData) { - const cachedListData = listDataGetter(rawData); - // Start filling data from the head of the list on the next page - if (isArray(cachedListData)) { - pushItem(fillingItems, ...splice(cachedListData, 0, len(indexes))); - } - return rawData; - } - }); - } - const isLastPageVal = isLastPage.v; - const fillingItemsLen = len(fillingItems); - let isLastEmptyPageInNonAppendMode = false; - if (fillingItemsLen > 0 || isLastPageVal) { - // Delete data at the specified index - const newListData = filterItem(data.v, (_, index) => !includes(indexes, index)); - // In page turning mode, if it is the last page and all items have been deleted, then turn one page forward. - isLastEmptyPageInNonAppendMode = !append && isLastPageVal && len(newListData) <= 0; - if (!isLastEmptyPageInNonAppendMode && fillingItemsLen > 0) { - pushItem(newListData, ...fillingItems); - } - data.v = newListData; - } - else if (fillingItemsLen <= 0 && !isLastPageVal) { - // When the last page of data is removed, there is no need to refresh - refresh(pageVal); - } - updateTotal(-len(indexes)); - // The cache of the current page is updated synchronously - return updateCurrentPageCache().then(() => { - if (isLastEmptyPageInNonAppendMode) { - page.v = pageVal - 1; - } - }); - }); - }; - /** - * Replace a piece of data - * If the position passed in is a list item, this list item will be replaced. If the list item is not in the list data, an error will be thrown. - * @param item replacement - * @param position Replace position (index) or list item - */ - const replace = (item, position) => add2AsyncQueue(async () => { - paginationAssert(position !== undefinedValue, 'expect specify the replace position'); - const index = isNumber(position) ? position : getItemIndex(position); - indexAssert(index, data.v); - const rawData = [...data.v]; - splice(rawData, index, 1, item); - data.v = rawData; - // The cache of the current page is updated synchronously - await updateCurrentPageCache(); - }); - /** - * Reload the list starting from page ${initialPage} and clear the cache - */ - const reload = async () => { - await invalidatePaginationCache(trueValue); - isReset.current = trueValue; - page.v === initialPage ? promiseCatch(send(), noop) : (page.v = initialPage); - const { resolve, reject, promise } = usePromise(); - awaitResolve.current = resolve; - awaitReject.current = reject; - return promise; - }; - // Compatible with react, caches the latest operation function each time, avoiding closure traps - delegationActions.current = { - refresh, - insert, - remove, - replace, - reload - }; - /** @Returns */ - return exposeProvider({ - ...states, - ...objectify([data, page, pageCount, pageSize, total, isLastPage]), - send: (...args) => send(...args, undefinedValue, undefinedValue), - fetching: fetchStates.loading, - onFetchSuccess: fetchStates.onSuccess, - onFetchError: fetchStates.onError, - onFetchComplete: fetchStates.onComplete, - refresh, - insert, - remove, - replace, - reload - }); - }; - - /** - * Assert serialHandlers - * @param hookName hook name - * @param serialHandlers Serial request method acquisition function - */ - const assertSerialHandlers = (hookName, serialHandlers) => createAssert(hookName)(isArray(serialHandlers) && len(serialHandlers) > 0, 'please use an array to represent serial requests'); - /** - * Create serial request middleware - * @param serialHandlers Serial request method acquisition function - * @param hookMiddleware use hook middleware - * @returns Serial request middleware - */ - const serialMiddleware = (serialHandlers, hookMiddleware, serialRequestMethods = []) => { - // The first handler is passed to the use hook externally and does not need to be requested again. - serialHandlers.shift(); - return ((ctx, next) => { - hookMiddleware === null || hookMiddleware === void 0 ? void 0 : hookMiddleware(ctx, () => promiseResolve(undefinedValue)); - ctx.controlLoading(); - const loadingState = ctx.proxyStates.loading; - loadingState.v = trueValue; - let serialPromise = next(); - for (const handler of serialHandlers) { - serialPromise = promiseThen(serialPromise, value => { - const methodItem = handler(value, ...ctx.args); - pushItem(serialRequestMethods, methodItem); - return methodItem.send(); - }); - } - return serialPromise.finally(() => { - loadingState.v = falseValue; - }); - }); - }; - - /** - * Serial request hook, each serialHandlers will receive the result of the previous request - * Applicable scenario: Serial request for a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialRequest related data and operation functions - */ - var useSerialRequest = (serialHandlers, config = {}) => { - assertSerialHandlers('useSerialRequest', serialHandlers); - // eslint-disable-next-line - const { ref, __referingObj } = statesHookHelper(alova.promiseStatesHook()); - const methods = ref([]).current; - const exposures = useRequest(serialHandlers[0], { - ...config, - __referingObj, - middleware: serialMiddleware(serialHandlers, config.middleware, methods) - }); - // Decorate the error callback function and set event.method to the instance of the error - exposures.onError = decorateEvent(exposures.onError, (handler, event) => { - event.method = methods[len(methods) - 1]; - handler(event); - }); - return exposures; - }; - - /** - * Serial request hook, each serialHandlers will receive the result of the previous request - * Applicable scenario: After monitoring status changes, serially request a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialRequest related data and operation functions - */ - var useSerialWatcher = (serialHandlers, watchingStates, config = {}) => { - assertSerialHandlers('useSerialWatcher', serialHandlers); - // eslint-disable-next-line - const { ref, __referingObj } = statesHookHelper(alova.promiseStatesHook()); - const methods = ref([]).current; - const exposures = useWatcher(serialHandlers[0], watchingStates, { - ...config, - __referingObj, - middleware: serialMiddleware(serialHandlers, config.middleware, methods) - }); - // Decorate the error callback function and set event.method to the instance of the error - exposures.onError = decorateEvent(exposures.onError, (handler, event) => { - event.method = methods[len(methods) - 1]; - handler(event); - }); - return exposures; - }; - - const STR_VALUE_OF = 'valueOf'; - const DEFAULT_QUEUE_NAME = 'default'; - const BEHAVIOR_SILENT = 'silent'; - const BEHAVIOR_QUEUE = 'queue'; - const BEHAVIOR_STATIC = 'static'; - /** - * Global virtual data collection array - * It will only be an array when the method is created, and undefined at other times - * - * Explanation: The purpose of collecting virtual data is to determine whether virtual data is used in a method instance. - * Includes the following forms: - * useSQRequest((vDataId) => createMethod({ vDataId }) //Reference function parameters - * useSQRequest(() => createMethod({ vDataId }) //Directly reference scope parameters - * - * Or even: - * function createMethod(obj) { - * return alovaInst.Get('/list', { - * params: { status: obj.vDataId ? 1 : 0 } - * }) - * } - * useSQRequest(() => createMethod(obj) //Directly reference scope parameters - * - * Ways to use dummy data include: - * 1. Directly assign values as parameters - * 2. Use dummy data id - * 3. Indirect use of virtual data, such as - * vData ? 1 : 0 - * !!vData - * vData+1 - * etc. as calculation parameters. - */ - let vDataIdCollectBasket; - const setVDataIdCollectBasket = (value) => { - vDataIdCollectBasket = value; - }; - /** - * The dependent alova instance, its storage adapter, request adapter, etc. will be used to access the SilentMethod instance and send silent submissions - */ - let dependentAlovaInstance; - const setDependentAlova = (alovaInst) => { - dependentAlovaInstance = alovaInst; - }; - /** - * Set up a custom serializer - */ - let customSerializers = {}; - const setCustomSerializers = (serializers = {}) => { - customSerializers = serializers; - }; - /** - * silentFactory status - * 0 means not started - * 1 means in progress, changed after calling bootSilentFactory - * 2 indicates that the request failed, that is, when the maximum number of requests is reached according to the retry rules, or when the retry rules are not matched, the request is changed. - */ - let silentFactoryStatus = 0; - const setSilentFactoryStatus = (status) => { - silentFactoryStatus = status; - }; - /** - * The request waiting time in silentQueue, in milliseconds (ms) - * It indicates the waiting time of the silentMethod that is about to send the request - * If not set, or set to 0, the silentMethod request is triggered immediately - * - * Tips: - * 1. When set directly, it is effective for the default queue by default. - * 2. If you need to set other queue settings, you can specify them as objects, such as: - * [ - * Indicates waiting 5000ms for the queue setting request named customName - * { name: 'customName', wait: 5000 }, - * - * //Indicates that in all queues with the prefix prefix, the request setting with method instance name xxx is set to wait 5000ms - * { name: /^prefix/, wait: silentMethod => silentMethod.entity.config.name === 'xxx' ? 5000 : 0 }, - * ] - * - * >>> It only works if the request succeeds, if it fails it will use the retry policy parameters - */ - let queueRequestWaitSetting = []; - const setQueueRequestWaitSetting = (requestWaitSetting = 0) => { - queueRequestWaitSetting = isArray(requestWaitSetting) - ? requestWaitSetting - : [ - { - queue: DEFAULT_QUEUE_NAME, - wait: requestWaitSetting - } - ]; - }; - const BootEventKey = Symbol('GlobalSQBoot'); - const BeforeEventKey = Symbol('GlobalSQBefore'); - const SuccessEventKey = Symbol('GlobalSQSuccess'); - const ErrorEventKey = Symbol('GlobalSQError'); - const FailEventKey$1 = Symbol('GlobalSQFail'); - /** Global silent event management object */ - const globalSQEventManager = createEventManager(); - /** Silent assert */ - const silentAssert = createAssert('useSQRequest'); - - /** - * Update the status of the corresponding method - * @param method request method object - * @param handleUpdate update callback - * @returns Whether the update is successful or not. If the corresponding status is not found, the update will not be successful. - */ - async function updateState(matcher, handleUpdate) { - let updated = falseValue; - // Only process the first method instance that meets the conditions. If there is no instance that meets the conditions, it will not be processed. - if (matcher) { - const { update } = alova.promiseStatesHook(); - const methodKey = getMethodInternalKey(matcher); - const { id } = getContext(matcher); - const { s: frontStates, h: hookInstance } = getStateCache(id, methodKey); - const updateStateCollection = isFn(handleUpdate) - ? { data: handleUpdate } - : handleUpdate; - let updatedDataColumnData = undefinedValue; - if (frontStates) { - // Loop through the updated data and assign it to the supervised state - forEach(objectKeys(updateStateCollection), stateName => { - coreAssert(stateName in frontStates, `state named \`${stateName}\` is not found`); - const targetStateProxy = frontStates[stateName]; - let updatedData = updateStateCollection[stateName](targetStateProxy.v); - // shallow clone the updatedData so that can effect in react. - updatedData = isArray(updatedData) - ? [...updatedData] - : isObject(updatedData) - ? { ...updatedData } - : updatedData; - // Record the updated value of the data field, used to update cached data - if (stateName === 'data') { - updatedDataColumnData = updatedData; - } - // Update directly using update without checking referring object.tracked keys - update(updatedData, frontStates[stateName].s, stateName, hookInstance.ro); - }); - updated = trueValue; - } - // If data is updated, cache and persistent data need to be updated at the same time - if (updatedDataColumnData !== undefinedValue) { - alova.setCache(matcher, updatedDataColumnData); - } - } - return updated; - } - - var dateSerializer = { - forward: data => (instanceOf(data, Date) ? data.getTime() : undefinedValue), - backward: ts => newInstance(Date, ts) - }; - - var regexpSerializer = { - forward: data => (instanceOf(data, RegExp) ? data.source : undefined), - backward: source => newInstance(RegExp, source) - }; - - const createSerializerPerformer = (customSerializers = {}) => { - /** - * Merge built-in serializers and custom serializers - */ - const serializers = { - date: dateSerializer, - regexp: regexpSerializer, - ...customSerializers - }; - /** - * serialized data - */ - const serialize = (payload) => { - if (isObject(payload)) { - payload = walkObject(isArray(payload) ? [...payload] : { ...payload }, value => { - let finallyApplySerializerName = undefinedValue; - // Find a matching serializer and serialize the value. If not found, return the original value. - const serializedValue = objectKeys(serializers).reduce((currentValue, serializerName) => { - if (!finallyApplySerializerName) { - const serializedValueItem = serializers[serializerName].forward(currentValue); - if (serializedValueItem !== undefinedValue) { - finallyApplySerializerName = serializerName; - currentValue = serializedValueItem; - } - } - return currentValue; - }, value); - // You need to use the original value to judge, otherwise packaging classes such as new Number(1) will also be [object Object] - const toStringTag = ObjectCls.prototype.toString.call(value); - if (toStringTag === '[object Object]') { - value = { ...value }; - } - else if (isArray(value)) { - value = [...value]; - } - return finallyApplySerializerName !== undefinedValue ? [finallyApplySerializerName, serializedValue] : value; - }); - } - return payload; - }; - /** - * Deserialize data - */ - const deserialize = (payload) => isObject(payload) - ? walkObject(payload, value => { - if (isArray(value) && len(value) === 2) { - const foundSerializer = serializers[value[0]]; - value = foundSerializer ? foundSerializer.backward(value[1]) : value; - } - return value; - }, falseValue) - : payload; - return { - serialize, - deserialize - }; - }; - - const symbolVDataId = Symbol('vdid'); - const symbolOriginal = Symbol('original'); - const regVDataId = /\[vd:([0-9a-z]+)\]/; - - /** - * Unified vData collection function - * It will be called in the following 4 places - * 1. When accessing sub-properties - * 2. When participating in calculation and triggering [Symbol.toPrimitive] - * 3. When getting the id of vData - * 4. When getting its original value - * - * @param returnValue Return value, if it is a function then call it - * @returns collection function - */ - const vDataCollectUnified = (target) => { - const vDataId = target === null || target === void 0 ? void 0 : target[symbolVDataId]; - vDataId && vDataIdCollectBasket && (vDataIdCollectBasket[vDataId] = undefinedValue); - }; - // export const vDataGetter = (key: string) => vDataCollectGetter((thisObj: any) => thisObj.__proto__[key].call(thisObj)); - - /** - * Dummy data is stringified. If the parameter is not dummy data, the original data is returned. - * @param target dummy data - * @param returnOriginalIfNotVData If it is not virtual data, return the original value. - * @returns Virtual data id or original data - */ - const stringifyVData = (target, returnOriginalIfNotVData = trueValue) => { - vDataCollectUnified(target); - const vDataIdRaw = target === null || target === void 0 ? void 0 : target[symbolVDataId]; - const vDataId = vDataIdRaw ? `[vd:${vDataIdRaw}]` : undefinedValue; - return vDataId || (returnOriginalIfNotVData ? target : undefinedValue); - }; - /** - * Create a getter function for virtual data id collection - * @param valueReturnFn return value function - * @returns getter function - */ - function stringifyWithThis() { - return stringifyVData(this); - } - - /** - * Null wrapper class implementation - */ - const Null = function Null() { }; - Null.prototype = ObjectCls.create(nullValue, { - [STR_VALUE_OF]: valueObject(stringifyWithThis) - }); - - /** - * Undefined wrapper class implementation - */ - const Undefined = function Undefined() { }; - Undefined.prototype = ObjectCls.create(nullValue, { - [STR_VALUE_OF]: valueObject(stringifyWithThis) - }); - - /** - * Create dummy response data - * @returns Virtual response data proxy instance - */ - var createVirtualResponse = (structure, vDataId = uuid()) => { - const transform2VData = (value, vDataIdInner = uuid()) => { - if (value === nullValue) { - value = newInstance(Null); - } - else if (value === undefinedValue) { - value = newInstance(Undefined); - } - else { - const newValue = ObjectCls(value); - defineProperty(newValue, STR_VALUE_OF, stringifyWithThis); - defineProperty(newValue, symbolOriginal, value); - value = newValue; - } - defineProperty(value, symbolVDataId, vDataIdInner); - return value; - }; - const virtualResponse = transform2VData(structure, vDataId); - if (isPlainObject(virtualResponse) || isArray(virtualResponse)) { - walkObject(virtualResponse, value => transform2VData(value)); - } - return virtualResponse; - }; - - /** - * Get original value of variable with dummy data - * This function will also perform vData collection - * @param target target value - * @param deepDehydrate Whether the depth of dehydration value - * @returns target value with primitive type - */ - const dehydrateVDataUnified = (target, deepDehydrate = trueValue) => { - const dehydrateItem = (value) => { - vDataCollectUnified(value); - if (value === null || value === void 0 ? void 0 : value[symbolVDataId]) { - if (instanceOf(value, Undefined)) { - value = undefinedValue; - } - else if (instanceOf(value, Null)) { - value = nullValue; - } - else if (instanceOf(value, Number) || instanceOf(value, String) || instanceOf(value, Boolean)) { - value = value[symbolOriginal]; - } - } - return value; - }; - const newTarget = dehydrateItem(target); - // If it is an object or array, deep traversal is required to obtain the virtual data value. - if (deepDehydrate && (isObject(newTarget) || isArray(newTarget))) { - walkObject(newTarget, value => dehydrateItem(value)); - } - return newTarget; - }; - /** - * The version above where deepDehydrate is true - */ - var dehydrateVData = (target) => dehydrateVDataUnified(target); - - const vDataKey = '__$k'; - const vDataValueKey = '__$v'; - const getAlovaStorage = () => { - // Provide prompt when silent factory is not started - silentAssert(!!dependentAlovaInstance, 'alova instance is not found, Do you forget to set `alova` or call `bootSilentFactory`?'); - return dependentAlovaInstance.l2Cache; - }; - let serializerPerformer = undefinedValue; - const silentMethodIdQueueMapStorageKey = 'alova.SQ'; // Queue collection cache key composed of Silent method instance id - const silentMethodStorageKeyPrefix = 'alova.SM.'; // silentMethod instance cache key prefix - /** - * Persistence of data collections with dummy data and serializable data - * @param key persistence key - * @param payload Persistent data - */ - const storageSetItem = async (key, payload) => { - const storage = getAlovaStorage(); - if (isObject(payload)) { - payload = walkObject(isArray(payload) ? [...payload] : { ...payload }, (value, key, parent) => { - var _a; - if (key === vDataValueKey && parent[vDataKey]) { - return value; - } - // If a silent method instance is serialized, the alova instance is filtered out - if (key === 'context' && ((_a = value === null || value === void 0 ? void 0 : value.constructor) === null || _a === void 0 ? void 0 : _a.name) === 'Alova') { - return undefinedValue; - } - const vDataId = value === null || value === void 0 ? void 0 : value[symbolVDataId]; - let primitiveValue = dehydrateVDataUnified(value, falseValue); - // You need to use the original value to judge, otherwise packaging classes such as new Number(1) will also be [object Object] - const toStringTag = globalToString(primitiveValue); - if (toStringTag === '[object Object]') { - value = { ...value }; - primitiveValue = {}; - } - else if (isArray(value)) { - value = [...value]; - primitiveValue = []; - } - if (vDataId) { - const valueWithVData = { - [vDataKey]: vDataId, - // For objects and arrays, all their internal properties will be put to the outside through `...value`, so the internal ones do not need to be traversed and converted. - // Therefore, empty the array or object to avoid repeated conversions and contamination of the original object. - [vDataValueKey]: primitiveValue, - ...value - }; - // If it is a string type, there will be items like arrays such as 0, 1, and 2 as subscripts and values as characters, and they need to be filtered out. - if (instanceOf(value, String)) { - for (let i = 0; i < len(value); i += 1) { - valueWithVData === null || valueWithVData === void 0 ? true : delete valueWithVData[i]; - } - } - // If it is converted into virtual data, the converted value is assigned to it internally, and is uniformly processed by value in the following logic. - value = valueWithVData; - } - return value; - }); - } - serializerPerformer = serializerPerformer || createSerializerPerformer(customSerializers); - await storage.set(key, serializerPerformer.serialize(payload)); - }; - /** - * Take out the persistent data and convert the data into virtual data and serialized data - * @param key Key to persistent data - */ - const storageGetItem = async (key) => { - const storagedResponse = await getAlovaStorage().get(key); - serializerPerformer = serializerPerformer || createSerializerPerformer(customSerializers); - return isObject(storagedResponse) - ? walkObject(serializerPerformer.deserialize(storagedResponse), value => { - // Convert virtual data format back to virtual data instance - if (isObject(value) && (value === null || value === void 0 ? void 0 : value[vDataKey])) { - const vDataId = value[vDataKey]; - const vDataValue = createVirtualResponse(value[vDataValueKey], vDataId); - forEach(objectKeys(value), key => { - if (!includes([vDataKey, vDataValueKey], key)) { - vDataValue[key] = value[key]; - } - }); - value = vDataValue; - } - return value; - }, falseValue) - : storagedResponse; - }; - /** - * Remove persistent data - * @param key Key to persistent data - */ - const storageRemoveItem = async (key) => { - await getAlovaStorage().remove(key); - }; - - /** - * Serialize and save silentMethod instance - * @param silentMethodInstance silentMethod instance - */ - const persistSilentMethod = (silentMethodInstance) => storageSetItem(silentMethodStorageKeyPrefix + silentMethodInstance.id, silentMethodInstance); - /** - * Put the configuration information of silent request into the corresponding storage - * Logic: Construct a key and use this key to put the configuration information of the silent method into the corresponding storage, and then store the key in the unified management key storage. - * @param silentMethod SilentMethodInstance - * @param queue Operation queue name - */ - const push2PersistentSilentQueue = async (silentMethodInstance, queueName) => { - await persistSilentMethod(silentMethodInstance); - // Save the silent method instance id to queue storage - const silentMethodIdQueueMap = ((await storageGetItem(silentMethodIdQueueMapStorageKey)) || - {}); - const currentQueue = (silentMethodIdQueueMap[queueName] = silentMethodIdQueueMap[queueName] || []); - pushItem(currentQueue, silentMethodInstance.id); - await storageSetItem(silentMethodIdQueueMapStorageKey, silentMethodIdQueueMap); - }; - /** - * Remove or replace silentMethod instances in the cache - * @param queue Operation queue name - * @param targetSilentMethodId Target silentMethod instance id - * @param newSilentMethod The new silentMethod instance to replace. If not passed, it means deleted. - */ - const spliceStorageSilentMethod = async (queueName, targetSilentMethodId, newSilentMethod) => { - // Remove the silent method instance id from the queue - const silentMethodIdQueueMap = ((await storageGetItem(silentMethodIdQueueMapStorageKey)) || - {}); - const currentQueue = silentMethodIdQueueMap[queueName] || []; - const index = currentQueue.findIndex(id => id === targetSilentMethodId); - if (index >= 0) { - if (newSilentMethod) { - splice(currentQueue, index, 1, newSilentMethod.id); - await persistSilentMethod(newSilentMethod); - } - else { - splice(currentQueue, index, 1); - } - await storageRemoveItem(silentMethodStorageKeyPrefix + targetSilentMethodId); - // Delete this queue when it is empty - len(currentQueue) <= 0 && delete silentMethodIdQueueMap[queueName]; - if (len(objectKeys(silentMethodIdQueueMap)) > 0) { - await storageSetItem(silentMethodIdQueueMapStorageKey, silentMethodIdQueueMap); - } - else { - // Remove the queue collection when it is empty - await storageRemoveItem(silentMethodIdQueueMapStorageKey); - } - } - }; - - /** Silent method queue collection */ - let silentQueueMap = {}; - /** - * Merge queueMap into silentMethod queue collection - * @param queueMap silentMethod queue collection - */ - const merge2SilentQueueMap = (queueMap) => { - forEach(objectKeys(queueMap), targetQueueName => { - const currentQueue = (silentQueueMap[targetQueueName] = silentQueueMap[targetQueueName] || []); - pushItem(currentQueue, ...queueMap[targetQueueName]); - }); - }; - /** - * Deeply traverse the target data and replace dummy data with real data - * @param target target data - * @param vDataResponse Collection of dummy data and real data - * @returns Is there any replacement data? - */ - const deepReplaceVData = (target, vDataResponse) => { - // Search for a single value and replace a dummy data object or dummy data id with an actual value - const replaceVData = (value) => { - const vData = stringifyVData(value); - // If directly a dummy data object and in a vDataResponse, replace the Map with the value in the vDataResponse - // If it is a string, it may contain virtual data id and in vDataResponse, it also needs to be replaced with the actual value Map - // The virtual data not in this vDataResponse will remain unchanged. It may be the virtual data Map requested next time. - if (vData in vDataResponse) { - return vDataResponse[vData]; - } - if (isString(value)) { - return value.replace(newInstance(RegExpCls, regVDataId.source, 'g'), mat => mat in vDataResponse ? vDataResponse[mat] : mat); - } - return value; - }; - if (isObject(target) && !stringifyVData(target, falseValue)) { - walkObject(target, replaceVData); - } - else { - target = replaceVData(target); - } - return target; - }; - /** - * Update the method instance in the queue and replace the dummy data with actual data - * @param vDataResponse A collection of virtual IDs and corresponding real data - * @param targetQueue target queue - */ - const updateQueueMethodEntities = (vDataResponse, targetQueue) => PromiseCls.all(mapItem(targetQueue, async (silentMethodItem) => { - // Traverse the entity object deeply. If virtual data or virtual data ID is found, replace it with actual data. - deepReplaceVData(silentMethodItem.entity, vDataResponse); - // If the method instance is updated, re-persist this silent method instance - silentMethodItem.cache && (await persistSilentMethod(silentMethodItem)); - })); - /** - * Replace dummy data with response data - * @param response real response data - * @param virtualResponse dummy response data - * @returns The corresponding real data set composed of virtual data id - */ - const replaceVirtualResponseWithResponse = (virtualResponse, response) => { - let vDataResponse = {}; - const vDataId = stringifyVData(virtualResponse, falseValue); - vDataId && (vDataResponse[vDataId] = response); - if (isObject(virtualResponse)) { - for (const i in virtualResponse) { - vDataResponse = { - ...vDataResponse, - ...replaceVirtualResponseWithResponse(virtualResponse[i], response === null || response === void 0 ? void 0 : response[i]) - }; - } - } - return vDataResponse; - }; - /** - * Start the SilentMethod queue - * 1. Silent submission will be put into the queue and requests will be sent in order. Only after the previous request responds will it continue to send subsequent requests. - * 2. The number of retries is only triggered when there is no response. If the server responds incorrectly or is disconnected, it will not retry. - * 3. When the number of retries is reached and still fails, when nextRound (next round) is set, delay the time specified by nextRound and then request again, otherwise it will try again after refreshing. - * 4. If there is resolveHandler and rejectHandler, they will be called after the request is completed (whether successful or failed) to notify the corresponding request to continue responding. - * - * @param queue SilentMethodqueue - */ - const setSilentMethodActive = (silentMethodInstance, active) => { - if (active) { - silentMethodInstance.active = active; - } - else { - delete silentMethodInstance.active; - } - }; - const defaultBackoffDelay = 1000; - const bootSilentQueue = (queue, queueName) => { - /** - * The callback function is controlled by waiting parameters according to the request. If it is not set or is less than or equal to 0, it will be triggered immediately. - * @param queueName queue name - * @param callback callback function - */ - const emitWithRequestDelay = (queueName) => { - const nextSilentMethod = queue[0]; - if (nextSilentMethod) { - const targetSetting = queueRequestWaitSetting.find(({ queue }) => instanceOf(queue, RegExpCls) ? regexpTest(queue, queueName) : queue === queueName); - // eslint-disable-next-line @typescript-eslint/no-use-before-define - const callback = () => queue[0] && silentMethodRequest(queue[0]); - const delay = (targetSetting === null || targetSetting === void 0 ? void 0 : targetSetting.wait) ? sloughConfig(targetSetting.wait, [nextSilentMethod, queueName]) : 0; - delay && delay > 0 ? setTimeoutFn(callback, delay) : callback(); - } - }; - /** - * Run a single silentMethod instance - * @param silentMethodInstance silentMethod instance - * @param retryTimes Number of retries - */ - const silentMethodRequest = (silentMethodInstance, retryTimes = 0) => { - // Set the current silent method instance to active status - setSilentMethodActive(silentMethodInstance, trueValue); - const { cache, id, behavior, entity, retryError = /.*/, maxRetryTimes = 0, backoff = { delay: defaultBackoffDelay }, resolveHandler = noop, rejectHandler = noop, emitter: methodEmitter, handlerArgs = [], virtualResponse, force } = silentMethodInstance; - // Trigger pre-request event - globalSQEventManager.emit(BeforeEventKey, newInstance((GlobalSQEvent), behavior, entity, silentMethodInstance, queueName, retryTimes)); - promiseThen(entity.send(force), async (data) => { - // The request is successful, remove the successful silent method, and continue with the next request - shift(queue); - // If the request is successful, remove the successful silent method instance from storage and continue with the next request. - cache && (await spliceStorageSilentMethod(queueName, id)); - // If there is a resolve handler, call it to notify the outside - resolveHandler(data); - // Only when there is a virtualResponse, virtual data is traversed and replaced, and global events are triggered. - // Generally, it is silent behavior, but queue behavior is not required. - if (behavior === BEHAVIOR_SILENT) { - // Replace dummy data in subsequent method instances in the queue with real data - // Only after unlocking can you access the hierarchical structure of virtualResponse normally. - const vDataResponse = replaceVirtualResponseWithResponse(virtualResponse, data); - const { targetRefMethod, updateStates } = silentMethodInstance; // It is accurate to obtain it in real time - // If this silentMethod has targetRefMethod, call updateState again to update the data - // This is an implementation of delayed data updates - if (instanceOf(targetRefMethod, alova.Method) && updateStates && len(updateStates) > 0) { - const updateStateCollection = {}; - forEach(updateStates, stateName => { - // After the request is successful, replace the data with dummy data with real data - updateStateCollection[stateName] = dataRaw => deepReplaceVData(dataRaw, vDataResponse); - }); - const updated = updateState(targetRefMethod, updateStateCollection); - // If the status modification is unsuccessful, modify the cached data. - if (!updated) { - await alova.setCache(targetRefMethod, (dataRaw) => deepReplaceVData(dataRaw, vDataResponse)); - } - } - // Perform dummy data replacement on subsequent silent method instances of the current queue - await updateQueueMethodEntities(vDataResponse, queue); - // Trigger global success event - globalSQEventManager.emit(SuccessEventKey, newInstance((GlobalSQSuccessEvent), behavior, entity, silentMethodInstance, queueName, retryTimes, data, vDataResponse)); - } - // Set to inactive state - setSilentMethodActive(silentMethodInstance, falseValue); - // Continue to the next silent method processing - emitWithRequestDelay(queueName); - }, reason => { - if (behavior !== BEHAVIOR_SILENT) { - // When the behavior is not silent and the request fails, rejectHandler is triggered. - // and removed from the queue and will not be retried. - shift(queue); - rejectHandler(reason); - } - else { - // Each request error will trigger an error callback - const runGlobalErrorEvent = (retryDelay) => globalSQEventManager.emit(ErrorEventKey, newInstance((GlobalSQErrorEvent), behavior, entity, silentMethodInstance, queueName, retryTimes, reason, retryDelay)); - // In silent behavior mode, determine whether retry is needed - // Retry is only effective when the response error matches the retryError regular match - const { name: errorName = '', message: errorMsg = '' } = reason || {}; - let regRetryErrorName; - let regRetryErrorMsg; - if (instanceOf(retryError, RegExp)) { - regRetryErrorMsg = retryError; - } - else if (isObject(retryError)) { - regRetryErrorName = retryError.name; - regRetryErrorMsg = retryError.message; - } - const matchRetryError = (regRetryErrorName && regexpTest(regRetryErrorName, errorName)) || - (regRetryErrorMsg && regexpTest(regRetryErrorMsg, errorMsg)); - // If there are still retry times, try again - if (retryTimes < maxRetryTimes && matchRetryError) { - // The next retry times need to be used to calculate the delay time, so +1 is needed here. - const retryDelay = delayWithBackoff(backoff, retryTimes + 1); - runGlobalErrorEvent(retryDelay); - setTimeoutFn(() => { - retryTimes += 1; - silentMethodRequest(silentMethodInstance, retryTimes); - methodEmitter.emit('retry', newInstance((ScopedSQRetryEvent), behavior, entity, silentMethodInstance, handlerArgs, retryTimes, retryDelay)); - }, - // When there are still retry times, use timeout as the next request time. - retryDelay); - } - else { - setSilentFactoryStatus(2); - runGlobalErrorEvent(); - // When the number of failures is reached, or the error message does not match the retry, the failure callback is triggered. - methodEmitter.emit('fallback', newInstance((ScopedSQErrorEvent), behavior, entity, silentMethodInstance, handlerArgs, reason)); - globalSQEventManager.emit(FailEventKey$1, newInstance((GlobalSQFailEvent), behavior, entity, silentMethodInstance, queueName, retryTimes, reason)); - } - } - // Set to inactive state - setSilentMethodActive(silentMethodInstance, falseValue); - }); - }; - emitWithRequestDelay(queueName); - }; - /** - * Put a new silentMethod instance into the queue - * @param silentMethodInstance silentMethod instance - * @param cache Does silentMethod have cache? - * @param targetQueueName target queue name - * @param onBeforePush Events before silentMethod instance push - */ - const pushNewSilentMethod2Queue = async (silentMethodInstance, cache, targetQueueName = DEFAULT_QUEUE_NAME, onBeforePush = () => []) => { - silentMethodInstance.cache = cache; - const currentQueue = (silentQueueMap[targetQueueName] = - silentQueueMap[targetQueueName] || []); - const isNewQueue = len(currentQueue) <= 0; - const beforePushReturns = await Promise.all(onBeforePush()); - const isPush2Queue = !beforePushReturns.some(returns => returns === falseValue); - // Under silent behavior, if there is no fallback event callback bound, it will be persisted. - // If false is returned in onBeforePushQueue, it will no longer be placed in the queue. - if (isPush2Queue) { - cache && (await push2PersistentSilentQueue(silentMethodInstance, targetQueueName)); - pushItem(currentQueue, silentMethodInstance); - // If it is a new queue and the status is started, execute it - isNewQueue && silentFactoryStatus === 1 && bootSilentQueue(currentQueue, targetQueueName); - } - return isPush2Queue; - }; - - /** - * Locate the location of the silentMethod instance - * @param silentMethodInstance silentMethod instance - */ - const getBelongQueuePosition = (silentMethodInstance) => { - let queue = undefinedValue; - let queueName = ''; - let position = 0; - for (const queueNameLoop in silentQueueMap) { - position = silentQueueMap[queueNameLoop].indexOf(silentMethodInstance); - if (position >= 0) { - queue = silentQueueMap[queueNameLoop]; - queueName = queueNameLoop; - break; - } - } - return [queue, queueName, position]; - }; - /** - * silentMethod instance - * Requests that need to enter silentQueue will be packaged into silentMethod instances, which will carry various parameters of the request strategy. - */ - class SilentMethod { - constructor(entity, behavior, emitter, id = uuid(), force, retryError, maxRetryTimes, backoff, resolveHandler, rejectHandler, handlerArgs, vDatas) { - const thisObj = this; - thisObj.entity = entity; - thisObj.behavior = behavior; - thisObj.id = id; - thisObj.emitter = emitter; - thisObj.force = !!force; - thisObj.retryError = retryError; - thisObj.maxRetryTimes = maxRetryTimes; - thisObj.backoff = backoff; - thisObj.resolveHandler = resolveHandler; - thisObj.rejectHandler = rejectHandler; - thisObj.handlerArgs = handlerArgs; - thisObj.vDatas = vDatas; - } - /** - * Allow cache-time persistent updates to the current instance - */ - async save() { - this.cache && (await persistSilentMethod(this)); - } - /** - * Replace the current instance with a new silentMethod instance in the queue - * If there is a persistent cache, the cache will also be updated. - * @param newSilentMethod new silentMethod instance - */ - async replace(newSilentMethod) { - const targetSilentMethod = this; - silentAssert(newSilentMethod.cache === targetSilentMethod.cache, 'the cache of new silentMethod must equal with this silentMethod'); - const [queue, queueName, position] = getBelongQueuePosition(targetSilentMethod); - if (queue) { - splice(queue, position, 1, newSilentMethod); - targetSilentMethod.cache && (await spliceStorageSilentMethod(queueName, targetSilentMethod.id, newSilentMethod)); - } - } - /** - * Remove the current instance. If there is persistent data, it will also be removed synchronously. - */ - async remove() { - const targetSilentMethod = this; - const [queue, queueName, position] = getBelongQueuePosition(targetSilentMethod); - if (queue) { - splice(queue, position, 1); - targetSilentMethod.cache && (await spliceStorageSilentMethod(queueName, targetSilentMethod.id)); - } - } - /** - * Set the method instance corresponding to the delayed update status and the corresponding status name - * It will find the corresponding status data and update vData to the actual data after responding to this silentMethod - * - * @param method method instance - * @param updateStateName Updated status name, the default is data, you can also set multiple - */ - setUpdateState(method, updateStateName = 'data') { - if (method) { - this.targetRefMethod = method; - this.updateStates = isArray(updateStateName) ? updateStateName : [updateStateName]; - } - } - } - - /** - * Deserialize the silentMethod instance according to the name of the serializer. - * @param methodInstance Request method instance - * @returns Request method instance - */ - var convertPayload2SilentMethod = (payload) => { - const { id, behavior, entity, retryError, maxRetryTimes, backoff, resolveHandler, rejectHandler, handlerArgs, targetRefMethod, force } = payload; - // Method class instantiation - const deserializeMethod = (methodPayload) => { - const { type, url, config, data } = methodPayload; - return newInstance(alova.Method, type, dependentAlovaInstance, url, config, data); - }; - const silentMethodInstance = newInstance(SilentMethod, deserializeMethod(entity), behavior, createEventManager(), id, force, retryError, maxRetryTimes, backoff, resolveHandler, rejectHandler, handlerArgs); - silentMethodInstance.cache = trueValue; - // Target ref method deserialization - if (targetRefMethod) { - silentMethodInstance.targetRefMethod = deserializeMethod(targetRefMethod); - } - // Put extra content on the silent method instance - forEach(objectKeys(payload), key => { - if (!includes([ - 'id', - 'behavior', - 'emitter', - 'entity', - 'retryError', - 'maxRetryTimes', - 'backoff', - 'resolveHandler', - 'rejectHandler', - 'handlerArgs', - 'targetRefMethod', - 'force' - ], key)) { - silentMethodInstance[key] = payload[key]; - } - }); - return silentMethodInstance; - }; - - /** - * Load silent queue data from storage - * @returns All queue data - */ - var loadSilentQueueMapFromStorage = async () => { - const silentMethodIdQueueMap = ((await storageGetItem(silentMethodIdQueueMapStorageKey)) || - {}); - const silentQueueMap = {}; - const readingPromises = []; - forEach(objectKeys(silentMethodIdQueueMap), queueName => { - const currentQueue = (silentQueueMap[queueName] = silentQueueMap[queueName] || []); - pushItem(readingPromises, ...mapItem(silentMethodIdQueueMap[queueName], async (silentMethodId) => { - const serializedSilentMethodPayload = await storageGetItem(silentMethodStorageKeyPrefix + silentMethodId); - serializedSilentMethodPayload && - pushItem(currentQueue, convertPayload2SilentMethod(serializedSilentMethodPayload)); - })); - }); - await PromiseCls.all(readingPromises); - return silentQueueMap; - }; - - /** - * Bind silentSubmit startup event - * @param {SilentSubmitBootHandler} handler event callback function - * @returns unbind function - */ - const onSilentSubmitBoot = (handler) => globalSQEventManager.on(BootEventKey, handler); - /** - * Bind silentSubmit success event - * @param {SilentSubmitSuccessHandler} handler event callback function - * @returns unbind function - */ - const onSilentSubmitSuccess = (handler) => globalSQEventManager.on(SuccessEventKey, handler); - /** - * Bind silentSubmit error event - * Every time there is a request error, an error callback is triggered. - * @param {SilentSubmitErrorHandler} handler event callback function - * @returns unbind function - */ - const onSilentSubmitError = (handler) => globalSQEventManager.on(ErrorEventKey, handler); - /** - * Binding silentSubmit failure event - * The failure event will be triggered when the maximum number of requests is reached, or when the error message does not match - * @param {SilentSubmitFailHandler} handler event callback function - * @returns unbind function - */ - const onSilentSubmitFail = (handler) => globalSQEventManager.on(FailEventKey$1, handler); - /** - * Bind silentSubmit to initiate a pre-request event - * @param {BeforeSilentSubmitHandler} handler event callback function - * @returns unbind function - */ - const onBeforeSilentSubmit = (handler) => globalSQEventManager.on(BeforeEventKey, handler); - /** - * Start silent submission, which will load the silent method in the cache and start silent submission - * If no delay time is passed in, the sync starts immediately - * @param {SilentFactoryBootOptions} options Delay in milliseconds - */ - const bootSilentFactory = (options) => { - if (silentFactoryStatus === 0) { - const { alova, delay = 500 } = options; - setDependentAlova(alova); - setCustomSerializers(options.serializers); - setQueueRequestWaitSetting(options.requestWait); - setTimeoutFn(async () => { - // Delayed loading puts the page’s queue at the front - merge2SilentQueueMap(await loadSilentQueueMapFromStorage()); - // Loop start queue silent submission - // Multiple queues are executed in parallel - forEach(objectKeys(silentQueueMap), queueName => { - bootSilentQueue(silentQueueMap[queueName], queueName); - }); - setSilentFactoryStatus(1); // Set status to Started - globalSQEventManager.emit(BootEventKey, undefinedValue); - }, delay); - } - }; - - /** - * A global silentMethod instance that will have a value from before the first success event is triggered to after the last success event is triggered (synchronization period) - * In this way, the current silentMethod instance can be obtained in updateStateEffect in onSuccess. - */ - let currentSilentMethod = undefinedValue; - /** - * Create SilentQueue middleware function - * @param config Configuration object - * @returns middleware function - */ - var createSilentQueueMiddlewares = (handler, config) => { - const { behavior = 'queue', queue = DEFAULT_QUEUE_NAME, retryError, maxRetryTimes, backoff } = config || {}; - const eventEmitter = createEventManager(); - let handlerArgs; - let behaviorFinally; - let queueFinally = DEFAULT_QUEUE_NAME; - let forceRequest = falseValue; - let silentMethodInstance; - /** - * method instance creation function - * @param args Call the function passed in by send - * @returns method instance - */ - const createMethod = (...args) => { - silentAssert(isFn(handler), 'method handler must be a function. eg. useSQRequest(() => method)'); - setVDataIdCollectBasket({}); - handlerArgs = args; - return handler(...args); - }; - // Decorate success/error/complete event - const decorateRequestEvent = (requestExposure) => { - // Set event callback decorator - requestExposure.onSuccess = decorateEvent(requestExposure.onSuccess, (handler, event) => { - currentSilentMethod = silentMethodInstance; - handler(newInstance((ScopedSQSuccessEvent), behaviorFinally, event.method, silentMethodInstance, event.args, event.data)); - }); - requestExposure.onError = decorateEvent(requestExposure.onError, (handler, event) => { - handler(newInstance((ScopedSQErrorEvent), behaviorFinally, event.method, silentMethodInstance, event.args, event.error)); - }); - requestExposure.onComplete = decorateEvent(requestExposure.onComplete, (handler, event) => { - handler(newInstance((ScopedSQCompleteEvent), behaviorFinally, event.method, silentMethodInstance, event.args, event.status, event.data, event.error)); - }); - }; - /** - * middleware function - * @param context Request context, containing request-related values - * @param next continue executing function - * @returns Promise object - */ - const middleware = ({ method, args, cachedResponse, proxyStates, config }, next) => { - const { silentDefaultResponse, vDataCaptured, force = falseValue } = config; - // Because the behavior return value may change, it should be called for each request to re-obtain the return value. - const baseEvent = AlovaEventBase.spawn(method, args); - behaviorFinally = sloughConfig(behavior, [baseEvent]); - queueFinally = sloughConfig(queue, [baseEvent]); - forceRequest = sloughConfig(force, [baseEvent]); - // Empty temporary collection variables - // They need to be cleared before returning - const resetCollectBasket = () => { - setVDataIdCollectBasket((handlerArgs = undefinedValue)); - }; - // If v data captured is set, first determine whether the request-related data contains virtual data. - if (isFn(vDataCaptured)) { - let hasVData = vDataIdCollectBasket && len(objectKeys(vDataIdCollectBasket)) > 0; - if (!hasVData) { - const { url, data } = method; - const { params, headers } = getConfig(method); - walkObject({ url, params, data, headers }, value => { - if (!hasVData && (stringifyVData(value, falseValue) || regexpTest(regVDataId, value))) { - hasVData = trueValue; - } - return value; - }); - } - // If v data captured has return data, use it as the response data, otherwise continue the request - const customResponse = hasVData ? vDataCaptured(method) : undefinedValue; - if (customResponse !== undefinedValue) { - resetCollectBasket(); // Reset when captured by v data captured - return promiseResolve(customResponse); - } - } - if (behaviorFinally !== BEHAVIOR_STATIC) { - // Wait for the method in the queue to complete execution - const createSilentMethodPromise = () => { - const queueResolvePromise = newInstance(PromiseCls, (resolveHandler, rejectHandler) => { - silentMethodInstance = newInstance((SilentMethod), method, behaviorFinally, eventEmitter, undefinedValue, !!forceRequest, retryError, maxRetryTimes, backoff, resolveHandler, rejectHandler, handlerArgs, vDataIdCollectBasket && objectKeys(vDataIdCollectBasket)); - resetCollectBasket(); // Reset when Behavior is queue and silent - }); - // On before push and on pushed events are bound synchronously, so they need to be queued asynchronously to trigger the event normally. - promiseThen(promiseResolve(undefinedValue), async () => { - const createPushEvent = () => newInstance((ScopedSQEvent), behaviorFinally, method, silentMethodInstance, args); - // Put the silent method into the queue and persist it - const isPushed = await pushNewSilentMethod2Queue(silentMethodInstance, - // After the onFallback event is bound, even the silent behavior mode is no longer stored. - // onFallback will be called synchronously, so it needs to be determined asynchronously whether there are fallbackHandlers - len(eventEmitter.eventMap.fallback || []) <= 0 && behaviorFinally === BEHAVIOR_SILENT, queueFinally, - // Execute the callback before putting it into the queue. If false is returned, it will prevent putting it into the queue. - () => eventEmitter.emit('beforePushQueue', createPushEvent())); - // Only after putting it into the queue, the callback after putting it into the queue will be executed. - isPushed && eventEmitter.emit('pushedQueue', createPushEvent()); - }); - return queueResolvePromise; - }; - if (behaviorFinally === BEHAVIOR_QUEUE) { - // Forced request, or loading status needs to be updated when cache is hit - const needSendRequest = forceRequest || !cachedResponse; - if (needSendRequest) { - // Manually set to true - proxyStates.loading.v = trueValue; - } - // When using the cache, use the cache directly, otherwise enter the request queue - return needSendRequest ? createSilentMethodPromise() : promiseThen(promiseResolve(cachedResponse)); - } - const silentMethodPromise = createSilentMethodPromise(); - // Create virtual response data in silent mode. Virtual response data can generate arbitrary virtual data. - const virtualResponse = (silentMethodInstance.virtualResponse = createVirtualResponse(isFn(silentDefaultResponse) ? silentDefaultResponse() : undefinedValue)); - promiseThen(silentMethodPromise, realResponse => { - // Update after obtaining real data - proxyStates.data.v = realResponse; - }); - // In Silent mode, the virtual response value is returned immediately, and then updated when the real data is returned. - return promiseResolve(virtualResponse); - } - resetCollectBasket(); // Reset when Behavior is static - return next(); - }; - return { - c: createMethod, - m: middleware, - d: decorateRequestEvent, - // event binding function - b: { - /** - * Bind fallback event - * @param handler Fallback event callback - */ - onFallback: (handler) => { - eventEmitter.on('fallback', handler); - }, - /** - * Event before binding to queue - * @param handler Event callback before enqueuing - */ - onBeforePushQueue: (handler) => { - eventEmitter.on('beforePushQueue', handler); - }, - /** - * Event after binding to queue - * @param handler Event callback after being queued - */ - onPushedQueue: (handler) => { - eventEmitter.on('pushedQueue', handler); - }, - /** - * retry event - * @param handler Retry event callback - */ - onRetry: (handler) => { - eventEmitter.on('retry', handler); - } - } - }; - }; - - function useSQRequest(handler, config = {}) { - const { exposeProvider, __referingObj: referingObj } = statesHookHelper(alova.promiseStatesHook()); - const { middleware = noop } = config; - const { c: methodCreateHandler, m: silentMiddleware, b: binders, d: decorateEvent } = createSilentQueueMiddlewares(handler, config); - const states = useRequest(methodCreateHandler, { - ...config, - __referingObj: referingObj, - middleware: (ctx, next) => { - const silentMidPromise = silentMiddleware(ctx, next); - middleware(ctx, () => silentMidPromise); - return silentMidPromise; - } - }); - decorateEvent(states); - return exposeProvider({ - ...states, - ...binders - }); - } - - /** - * Determine whether two values are equal in a way that is compatible with virtual data - * @param prevValue Antecedent value - * @param nextValue consequent value - * @returns Are they equal? - */ - var equals = (prevValue, nextValue) => { - // If equal, return directly - if (prevValue === nextValue) { - return trueValue; - } - return stringifyVData(prevValue) === stringifyVData(nextValue); - }; - - /** - * Filter all silentMethod instances that meet the criteria by method name or regular expression - * @param methodNameMatcher method name matcher - * @param queueName Find the queue name, the default is default queue - * @param filterActive Whether to filter out active instances - * @returns array of silentMethod instances - */ - const filterSilentMethods = async (methodNameMatcher, queueName = DEFAULT_QUEUE_NAME, filterActive = falseValue) => { - const matchSilentMethods = (targetQueue = []) => targetQueue.filter(silentMethodItem => { - if (methodNameMatcher === undefinedValue) { - return trueValue; - } - const name = getConfig(silentMethodItem.entity).name || ''; - const retain = instanceOf(methodNameMatcher, RegExp) - ? regexpTest(methodNameMatcher, name) - : name === methodNameMatcher; - return retain && (filterActive ? silentMethodItem.active : trueValue); - }); - return [ - ...matchSilentMethods(silentQueueMap[queueName]), - // If the silent factory is not currently started, you also need to match the silent methods in the persistent storage. - ...(silentFactoryStatus === 0 ? matchSilentMethods((await loadSilentQueueMapFromStorage())[queueName]) : []) - ]; - }; - /** - * Find the first silentMethod instance that meets the condition by method name or regular expression - * @param methodNameMatcher method name matcher - * @param queueName Find the queue name, the default is default queue - * @param filterActive Whether to filter out active instances - * @returns silentMethod instance, undefined when not found - */ - const getSilentMethod = async (methodNameMatcher, queueName = DEFAULT_QUEUE_NAME, filterActive = falseValue) => (await filterSilentMethods(methodNameMatcher, queueName, filterActive))[0]; - - /** - * Determine whether the target data is virtual data - * @param target target data - * @returns Is it virtual data? - */ - var isVData = (target) => !!stringifyVData(target, falseValue) || regexpTest(regVDataId, target); - - /** - * Update the status of the corresponding method - * Unlike updateState, in addition to updating the state immediately, it will also update again after responding in silent mode in order to replace the virtual data with actual data. - * @param method request method object - * @param handleUpdate update callback - */ - const updateStateEffect = async (matcher, handleUpdate) => { - // Save the target method instance to the current silent method instance - if (currentSilentMethod) { - currentSilentMethod.setUpdateState(matcher, isFn(updateState) ? undefinedValue : objectKeys(updateState)); - await currentSilentMethod.save(); - } - return updateState(matcher, handleUpdate); - }; - - const useAutoRequest = (handler, config = {}) => { - let notifiable = trueValue; - const { enableFocus = trueValue, enableVisibility = trueValue, enableNetwork = trueValue, pollingTime = 0, throttle = 1000 } = config; - const { onMounted, onUnmounted, __referingObj: referingObject } = statesHookHelper(alova.promiseStatesHook()); - const states = useRequest(handler, { - ...config, - __referingObj: referingObject - }); - const notify = () => { - if (notifiable) { - states.send(); - if (throttle > 0) { - notifiable = falseValue; - setTimeout(() => { - notifiable = trueValue; - }, throttle); - } - } - }; - let offNetwork = noop; - let offFocus = noop; - let offVisiblity = noop; - let offPolling = noop; - onMounted(() => { - if (!alova.globalConfigMap.ssr) { - offNetwork = enableNetwork ? useAutoRequest.onNetwork(notify, config) : offNetwork; - offFocus = enableFocus ? useAutoRequest.onFocus(notify, config) : offFocus; - offVisiblity = enableVisibility ? useAutoRequest.onVisibility(notify, config) : offVisiblity; - offPolling = pollingTime > 0 ? useAutoRequest.onPolling(notify, config) : offPolling; - } - }); - onUnmounted(() => { - offNetwork(); - offFocus(); - offVisiblity(); - offPolling(); - }); - return states; - }; - const on = (type, handler) => { - window.addEventListener(type, handler); - return () => window.removeEventListener(type, handler); - }; - useAutoRequest.onNetwork = notify => on('online', notify); - useAutoRequest.onFocus = notify => on('focus', notify); - useAutoRequest.onVisibility = notify => { - const handle = () => document.visibilityState === 'visible' && notify(); - return on('visibilitychange', handle); - }; - useAutoRequest.onPolling = (notify, config) => { - const timer = setInterval(notify, config.pollingTime); - return () => clearInterval(timer); - }; - - const hookPrefix$1 = 'useCaptcha'; - const captchaAssert = createAssert(hookPrefix$1); - var useCaptcha = (handler, config = {}) => { - const { initialCountdown, middleware } = config; - captchaAssert(initialCountdown === undefinedValue || initialCountdown > 0, 'initialCountdown must be greater than 0'); - const { create, ref, objectify, exposeProvider, __referingObj: referingObject } = statesHookHelper(alova.promiseStatesHook()); - const countdown = create(0, 'countdown'); - const requestReturned = useRequest(handler, { - ...config, - __referingObj: referingObject, - immediate: falseValue, - managedStates: objectify([countdown], 's'), - // eslint-disable-next-line @typescript-eslint/no-use-before-define - middleware: middleware ? (ctx, next) => middleware({ ...ctx, send }, next) : undefinedValue - }); - const timer = ref(undefinedValue); - const send = (...args) => newInstance(PromiseCls, (resolve, reject) => { - if (countdown.v <= 0) { - requestReturned - .send(...args) - .then(result => { - countdown.v = config.initialCountdown || 60; - timer.current = setInterval(() => { - countdown.v -= 1; - if (countdown.v <= 0) { - clearInterval(timer.current); - } - }, 1000); - resolve(result); - }) - .catch(reason => reject(reason)); - } - else { - reject(newInstance(AlovaError, hookPrefix$1, 'the countdown is not over yet')); - } - }); - return exposeProvider({ - ...requestReturned, - send, - ...objectify([countdown]) - }); - }; - - const RestoreEventKey = Symbol('FormRestore'); - const getStoragedKey = (methodInstance, id) => `alova/form-${id || getMethodInternalKey(methodInstance)}`; - const sharedStates = {}; - const cloneFormData = (form) => { - const shallowClone = (value) => (isArray(value) ? [...value] : isPlainObject(value) ? { ...value } : value); - return walkObject(shallowClone(form), shallowClone); - }; - var useForm = (handler, config = {}) => { - const typedSharedStates = sharedStates; - const { id, initialForm, store, resetAfterSubmiting, immediate = falseValue, middleware } = config; - alova.promiseStatesHook(); - const { create, ref: useFlag$, onMounted, watch, objectify, exposeProvider, __referingObj: referingObject } = statesHookHelper(alova.promiseStatesHook()); - const isStoreObject = isPlainObject(store); - const enableStore = isStoreObject ? store.enable : store; - // If the id in config also has a corresponding shared state, it will also be returned. - // The reason for continuing the execution is to be compatible with the problem that the number of hook executions in react cannot be changed, otherwise it will throw "Rendered fewer hooks than expected. This may be caused by an accidental early return statement." - const sharedState = id ? typedSharedStates[id] : undefinedValue; - const form = create(cloneFormData(initialForm), 'form'); - const methodHandler = handler; - const eventManager = createEventManager(); - // Use computed properties to avoid calling methodHandler every time this use hook is executed. - const initialMethodInstance = useFlag$(sloughConfig(methodHandler, [form.v])); - const storageContext = getContext(initialMethodInstance.current).l2Cache; - const storagedKey = getStoragedKey(initialMethodInstance.current, id); - const reseting = useFlag$(falseValue); - const serializerPerformer = useFlag$(createSerializerPerformer(isStoreObject ? store.serializers : undefinedValue)); - // Whether the shared state created by the current hook is initiated. The hook that initiates the creation needs to return the latest state. Otherwise, because the hook is called in react, the latest state cannot be obtained from the hook initiated. - const isCreateShardState = useFlag$(false); - const originalHookProvider = useRequest((...args) => methodHandler(form.v, ...args), { - ...config, - __referingObj: referingObject, - // Middleware function, also supports subscriber middleware - middleware: middleware - ? (ctx, next) => middleware({ - ...ctx, - // eslint-disable-next-line - delegatingActions: { updateForm, reset } - }, next) - : undefinedValue, - // 1. When persistence is required, it will be triggered after data recovery - // 2. When there is a shared state, it means that it has been initialized before (regardless of whether there is an immediate request), and subsequent requests will no longer be automatically initiated. This is to be compatible with the issue of repeated requests when multiple forms initiate requests immediately. - immediate: enableStore || sharedState ? falseValue : immediate - }); - /** - * Reset form data - */ - const reset = () => { - reseting.current = trueValue; - const clonedFormData = cloneFormData(initialForm); - clonedFormData && (form.v = clonedFormData); - enableStore && storageContext.remove(storagedKey); - }; - /** - * Update form data - * @param newForm new form data - */ - const updateForm = (newForm) => { - form.v = { - ...form.v, - ...newForm - }; - }; - const hookProvider = exposeProvider({ - // The first parameter is fixed to form data - ...originalHookProvider, - ...objectify([form]), - updateForm, - reset, - // Persistent data recovery event binding - onRestore(handler) { - eventManager.on(RestoreEventKey, handler); - } - }); - // Only when there is an id, it is saved to sharedStates. - // In react, because a new form will be generated after updating the form, it needs to be resaved every time it is called. - if (id) { - // If there is no shared status yet, it means that the current hook is a created hook. - if (!sharedState) { - isCreateShardState.current = trueValue; - } - // Only the shared state of the created hook is saved - if (isCreateShardState.current) { - typedSharedStates[id] = { - hookProvider: hookProvider, - config - }; - } - } - const { send, onSuccess } = hookProvider; - onMounted(() => { - // Update data when persistence is required - if (enableStore && !sharedState) { - // Get storage and update data - // It needs to be called in onMounted, otherwise it will cause it to be called repeatedly in react. - const storagedForm = serializerPerformer.current.deserialize(storageContext.get(storagedKey)); - // When there is draft data, the data is restored asynchronously, otherwise the on restore event cannot be bound normally. - if (storagedForm) { - form.v = storagedForm; - // Trigger persistent data recovery event - eventManager.emit(RestoreEventKey, undefinedValue); - } - enableStore && immediate && send(...[]); - } - }); - // Monitor changes and store them synchronously. If it is triggered by reset, no further serialization is required. - watch([form], () => { - if (reseting.current || !enableStore) { - reseting.current = falseValue; - return; - } - storageContext.set(storagedKey, serializerPerformer.current.serialize(form.v)); - }); - // If data needs to be cleared after submission, call reset - onSuccess(() => { - resetAfterSubmiting && reset(); - }); - // If there is a saved sharedState, return it - // If it is the shared state created by the current hook, the latest one is returned instead of the cached one. - return sharedState && !isCreateShardState.current ? sharedState.hookProvider : hookProvider; - }; - - const RetryEventKey = Symbol('RetriableRetry'); - const FailEventKey = Symbol('RetriableFail'); - const hookPrefix = 'useRetriableRequest'; - const assert$2 = createAssert(hookPrefix); - var useRetriableRequest = (handler, config = {}) => { - const { retry = 3, backoff = { delay: 1000 }, middleware = noop } = config; - const { ref: useFlag$, exposeProvider, __referingObj: referingObject } = statesHookHelper(alova.promiseStatesHook()); - const eventManager = createEventManager(); - const retryTimes = useFlag$(0); - const stopManuallyError = useFlag$(undefinedValue); // Stop error object, has value when stop is triggered manually - const methodInstanceLastest = useFlag$(undefinedValue); - const argsLatest = useFlag$(undefinedValue); - const requesting = useFlag$(falseValue); // Is it being requested? - const retryTimer = useFlag$(undefinedValue); - const stopPromiseObj = useFlag$(usePromise()); - const emitOnFail = (method, args, error) => { - // On fail needs to be triggered asynchronously, and on error and on complete should be triggered first. - setTimeoutFn(() => { - eventManager.emit(FailEventKey, newInstance((RetriableFailEvent), AlovaEventBase.spawn(method, args), error, retryTimes.current)); - stopManuallyError.current = undefinedValue; - retryTimes.current = 0; // Reset the number of retries - }); - }; - const nestedHookProvider = useRequest(handler, { - ...config, - __referingObj: referingObject, - middleware(ctx, next) { - middleware({ - ...ctx, - delegatingActions: { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - stop - } - }, () => promiseResolve()); - const { proxyStates, args, send, method, controlLoading } = ctx; - controlLoading(); - const { loading } = proxyStates; - const setLoading = (value = falseValue) => { - loading.v = value; - }; - const resolveFail = (error) => { - setLoading(); - proxyStates.error.v = error; - clearTimeout(retryTimer.current); // Clear retry timer - emitOnFail(method, args, error); - }; - if (!loading.v) { - promiseCatch(stopPromiseObj.current.promise, error => { - resolveFail(error); - stopPromiseObj.current = usePromise(); - }); - } - setLoading(trueValue); - requesting.current = trueValue; - methodInstanceLastest.current = method; - argsLatest.current = args; - /** - * Consider this situation: user call stop() and send another request immediately, but now the previous request haven't finished. `next()` will raises the branch on completion. - * - * By using Promise.race(), we can cause the returned promise to be rejected immediately when call `stop()` - */ - return next() - .then(val => { - // set `loading` to false when request is successful - setLoading(); - return val; - }, - // Trigger retry mechanism when request fails - error => { - // There is no manual trigger to stop, and a retry is triggered when the number of retries does not reach the maximum. - if (!stopManuallyError.current && (isNumber(retry) ? retryTimes.current < retry : retry(error, ...args))) { - retryTimes.current += 1; - // Calculate retry delay time - const retryDelay = delayWithBackoff(backoff, retryTimes.current); - // Delay the corresponding time and try again - retryTimer.current = setTimeoutFn(() => { - // trigger retry event - eventManager.emit(RetryEventKey, newInstance((RetriableRetryEvent), AlovaEventBase.spawn(method, args), retryTimes.current, retryDelay)); - // If stopped manually, retry will no longer be triggered. - promiseCatch(send(...args), noop); // Captured errors will no longer be thrown out, otherwise errors will be thrown when retrying. - }, retryDelay); - } - else { - error = stopManuallyError.current || error; // If stop manually error has a value, it means that the stop is triggered through the stop function. - resolveFail(error); - } - // Return reject to execute the subsequent error process - return promiseReject(error); - }) - .finally(() => { - requesting.current = falseValue; - }); - } - }); - /** - * Stop retrying, only valid when called during retrying - * If the request is in progress, trigger an interrupt request and let the request error throw an error. Otherwise, manually modify the status and trigger onFail. - * The onFail event will be triggered immediately after stopping - */ - const stop = () => { - assert$2(nestedHookProvider.__proxyState('loading').v, 'there is no requests being retried'); - stopManuallyError.current = newInstance(AlovaError, hookPrefix, 'stop retry manually'); - if (requesting.current) { - nestedHookProvider.abort(); - } - else { - stopPromiseObj.current.reject(stopManuallyError.current); - } - }; - /** - * Retry event binding - * They will be triggered after the retry is initiated - * @param handler Retry event callback - */ - const onRetry = (handler) => { - eventManager.on(RetryEventKey, event => handler(event)); - }; - /** - * failed event binding - * They will be triggered when there are no more retries, such as when the maximum number of retries is reached, when the retry callback returns false, or when stop is manually called to stop retries. - * The onError event of alova will be triggered every time an error is requested. - * - * Note: If there are no retries, onError, onComplete and onFail will be triggered at the same time. - * - * @param handler Failure event callback - */ - const onFail = (handler) => { - eventManager.on(FailEventKey, event => handler(event)); - }; - return exposeProvider({ - ...nestedHookProvider, - stop, - onRetry, - onFail - }); - }; - - const SSEOpenEventKey = Symbol('SSEOpen'); - const SSEMessageEventKey = Symbol('SSEMessage'); - const SSEErrorEventKey = Symbol('SSEError'); - var SSEHookReadyState; - (function (SSEHookReadyState) { - SSEHookReadyState[SSEHookReadyState["CONNECTING"] = 0] = "CONNECTING"; - SSEHookReadyState[SSEHookReadyState["OPEN"] = 1] = "OPEN"; - SSEHookReadyState[SSEHookReadyState["CLOSED"] = 2] = "CLOSED"; - })(SSEHookReadyState || (SSEHookReadyState = {})); - const assert$1 = createAssert('useSSE'); - const MessageType = { - Open: 'open', - Error: 'error', - Message: 'message' - }; - var useSSE = (handler, config = {}) => { - const { initialData, withCredentials, interceptByGlobalResponded = trueValue, - /** abortLast = trueValue, */ - immediate = falseValue } = config; - // ! Temporarily does not support specifying abortLast - const abortLast = trueValue; - let { memorize } = alova.promiseStatesHook(); - memorize !== null && memorize !== void 0 ? memorize : (memorize = $self); - const { create, ref, onMounted, onUnmounted, objectify, exposeProvider } = statesHookHelper(alova.promiseStatesHook()); - const usingArgs = ref([]); - const eventSource = ref(undefinedValue); - const sendPromiseObject = ref(undefinedValue); - const data = create(initialData, 'data'); - const readyState = create(SSEHookReadyState.CLOSED, 'readyState'); - let methodInstance = getHandlerMethod(handler); - let responseUnified; - const eventManager = createEventManager(); - // UseCallback object that stores custom events, where key is eventName - const customEventMap = ref(new Map()); - const onOpen = (handler) => { - eventManager.on(SSEOpenEventKey, handler); - }; - const onMessage = (handler) => { - eventManager.on(SSEMessageEventKey, handler); - }; - const onError = (handler) => { - eventManager.on(SSEErrorEventKey, handler); - }; - const responseSuccessHandler = ref($self); - const responseErrorHandler = ref(throwFn); - const responseCompleteHandler = ref(noop); - /** - * Set up a response interceptor, which needs to be called after each send - */ - const setResponseHandler = (instance) => { - // responded removed since 3.0 - const { responded } = getOptions(instance); - responseUnified = responded; - if (isFn(responseUnified)) { - responseSuccessHandler.current = responseUnified; - } - else if (responseUnified && isPlainObject(responseUnified)) { - const { onSuccess: successHandler, onError: errorHandler, onComplete: completeHandler } = responseUnified; - responseSuccessHandler.current = isFn(successHandler) ? successHandler : responseSuccessHandler.current; - responseErrorHandler.current = isFn(errorHandler) ? errorHandler : responseErrorHandler.current; - responseCompleteHandler.current = isFn(completeHandler) ? completeHandler : responseCompleteHandler.current; - } - }; - /** - * Process response tasks and do not cache data on failure - * @param handlerReturns Data returned by the interceptor - * @returns Processed response - */ - const handleResponseTask = async (handlerReturns) => { - const { headers, transform: transformFn = $self } = getConfig(methodInstance); - const returnsData = await handlerReturns; - const transformedData = await transformFn(returnsData, (headers || {})); - data.v = transformedData; - // invalidate cache - alova.hitCacheBySource(methodInstance); - return transformedData; - }; - /** - * Create AlovaSSEHook event - * For specific data processing procedures, please refer to the following link - * @link https://alova.js.org/zh-CN/tutorial/combine-framework/response - */ - const createSSEEvent = async (eventFrom, dataOrError) => { - assert$1(!!eventSource.current, 'EventSource is not initialized'); - const es = eventSource.current; - const baseEvent = new AlovaSSEEvent(AlovaEventBase.spawn(methodInstance, usingArgs.current), es); - if (eventFrom === MessageType.Open) { - return Promise.resolve(baseEvent); - } - const globalSuccess = interceptByGlobalResponded ? responseSuccessHandler.current : $self; - const globalError = interceptByGlobalResponded ? responseErrorHandler.current : throwFn; - const globalFinally = interceptByGlobalResponded ? responseCompleteHandler.current : noop; - const p = promiseFinally(promiseThen(dataOrError, res => handleResponseTask(globalSuccess(res, methodInstance)), error => handleResponseTask(globalError(error, methodInstance))), - // Finally - () => { - globalFinally(methodInstance); - }); - // Regardless, the Promise object returned by the function must be fulfilled - return promiseThen(p, - // Get processed data (data after transform) - res => new AlovaSSEMessageEvent(baseEvent, res), - // There is an error - error => new AlovaSSEErrorEvent(baseEvent, error)); - }; - /** - * Select the required trigger function based on the event. If the event has no errors, the callback function passed in is triggered. - * @param callback Callback function triggered when there is no error - */ - const sendSSEEvent = (callback) => (event) => { - if (event.error === undefinedValue) { - return callback(event); - } - return eventManager.emit(SSEErrorEventKey, event); - }; - // * MARK: Event handling of EventSource - const onCustomEvent = (eventName, callbackHandler) => { - var _a; - const currentMap = customEventMap.current; - if (!currentMap.has(eventName)) { - const useCallbackObject = useCallback(callbacks => { - var _a; - if (callbacks.length === 0) { - (_a = eventSource.current) === null || _a === void 0 ? void 0 : _a.removeEventListener(eventName, useCallbackObject[1]); - customEventMap.current.delete(eventName); - } - }); - const trigger = useCallbackObject[1]; - currentMap.set(eventName, useCallbackObject); - (_a = eventSource.current) === null || _a === void 0 ? void 0 : _a.addEventListener(eventName, event => { - promiseThen(createSSEEvent(eventName, Promise.resolve(event.data)), sendSSEEvent(trigger)); - }); - } - const [onEvent] = currentMap.get(eventName); - return onEvent(callbackHandler); - }; - /** - * Cancel the registration of custom events in useCallback - */ - const offCustomEvent = () => { - customEventMap.current.forEach(([_1, _2, offTrigger]) => { - offTrigger(); - }); - }; - const esOpen = memorize(() => { - var _a; - // resolve the promise returned when using send() - readyState.v = SSEHookReadyState.OPEN; - promiseThen(createSSEEvent(MessageType.Open, Promise.resolve()), event => eventManager.emit(SSEOpenEventKey, event)); - // ! Must be resolved after calling onOpen - (_a = sendPromiseObject.current) === null || _a === void 0 ? void 0 : _a.resolve(); - }); - const esError = memorize((event) => { - var _a, _b; - readyState.v = SSEHookReadyState.CLOSED; - promiseThen(createSSEEvent(MessageType.Error, Promise.reject((_a = event === null || event === void 0 ? void 0 : event.message) !== null && _a !== void 0 ? _a : 'SSE Error')), sendSSEEvent(event => eventManager.emit(SSEMessageEventKey, event))); - (_b = sendPromiseObject.current) === null || _b === void 0 ? void 0 : _b.resolve(); - }); - const esMessage = memorize((event) => { - promiseThen(createSSEEvent(MessageType.Message, Promise.resolve(event.data)), sendSSEEvent(event => eventManager.emit(SSEMessageEventKey, event))); - }); - /** - * Close the registration of the current eventSource - */ - const close = () => { - const es = eventSource.current; - if (!es) { - return; - } - if (sendPromiseObject.current) { - // If the promise is still there when close - sendPromiseObject.current.resolve(); - } - // * MARK: Unbinding event handling - es.close(); - es.removeEventListener(MessageType.Open, esOpen); - es.removeEventListener(MessageType.Error, esError); - es.removeEventListener(MessageType.Message, esMessage); - readyState.v = SSEHookReadyState.CLOSED; - // After eventSource is closed, unregister all custom events - // Otherwise it may cause memory leaks - customEventMap.current.forEach(([_, eventTrigger], eventName) => { - es.removeEventListener(eventName, eventTrigger); - }); - }; - /** - * Send request and initialize eventSource - */ - const connect = (...args) => { - let es = eventSource.current; - let promiseObj = sendPromiseObject.current; - if (es && abortLast) { - // When abortLast === true, close the previous connection and re-establish it - close(); - } - // Set the promise object used by the send function - if (!promiseObj) { - promiseObj = sendPromiseObject.current = usePromise(); - // Clear the promise object after open - promiseObj && - promiseObj.promise.finally(() => { - promiseObj = undefinedValue; - }); - } - usingArgs.current = args; - methodInstance = getHandlerMethod(handler, args); - // Set up response interceptor - setResponseHandler(methodInstance); - const { params } = getConfig(methodInstance); - const { baseURL, url } = methodInstance; - const fullURL = buildCompletedURL(baseURL, url, params); - // Establish connection - es = new EventSource(fullURL, { withCredentials }); - eventSource.current = es; - readyState.v = SSEHookReadyState.CONNECTING; - // * MARK: Register to handle events - // Register to handle event open error message - es.addEventListener(MessageType.Open, esOpen); - es.addEventListener(MessageType.Error, esError); - es.addEventListener(MessageType.Message, esMessage); - // and custom events - // If the on listener is used before connect (send), there will already be events in customEventMap. - customEventMap.current.forEach(([_, eventTrigger], eventName) => { - es === null || es === void 0 ? void 0 : es.addEventListener(eventName, event => { - promiseThen(createSSEEvent(eventName, Promise.resolve(event.data)), sendSSEEvent(eventTrigger)); - }); - }); - return promiseObj.promise; - }; - onUnmounted(() => { - close(); - // The above use of eventSource.removeEventListener just disconnects eventSource and trigger. - // Here is the cancellation of the event registration in the useCallback object - eventManager.off(SSEOpenEventKey); - eventManager.off(SSEMessageEventKey); - eventManager.off(SSEErrorEventKey); - offCustomEvent(); - }); - // * MARK: initialization action - onMounted(() => { - var _a; - if (immediate) { - connect(...[]); - (_a = sendPromiseObject.current) === null || _a === void 0 ? void 0 : _a.promise.catch(() => { }); - } - }); - return exposeProvider({ - send: connect, - close, - on: onCustomEvent, - onMessage, - onError, - onOpen, - eventSource, - ...objectify([readyState, data]) - }); - }; - - let currentHookIndex = 0; - // (id, (hookIndex, Actions)) - const actionsMap = {}; - const isFrontMiddlewareContext = (context) => !!context.send; - const assert = createAssert('subscriber'); - /** - * Operation function delegation middleware - * After using this middleware, you can call the delegated function through accessAction. - * Can delegate multiple identical IDs - * In order to eliminate the hierarchical restrictions of components - * @param id Client ID - * @returns alova middleware function - */ - const actionDelegationMiddleware = (id) => { - const { ref, onUnmounted } = statesHookHelper(alova.promiseStatesHook()); - const hookIndex = ref(currentHookIndex + 1); - if (hookIndex.current > currentHookIndex) { - currentHookIndex += 1; - } - onUnmounted(() => { - var _a; - if ((_a = actionsMap[id]) === null || _a === void 0 ? void 0 : _a[hookIndex.current]) { - // delete action on unmount - delete actionsMap[id][hookIndex.current]; - } - }); - return (context, next) => { - // The middleware will be called repeatedly. If you have already subscribed, you do not need to subscribe again. - const { abort, proxyStates, delegatingActions = {} } = context; - const update = (newStates) => { - for (const key in newStates) { - proxyStates[key] && (proxyStates[key].v = newStates[key]); - } - }; - // Those with the same ID will be saved together in the form of an array - const hooks = (actionsMap[id] = actionsMap[id] || []); - const handler = isFrontMiddlewareContext(context) - ? { - ...delegatingActions, - send: context.send, - abort, - update - } - : { - ...delegatingActions, - fetch: context.fetch, - abort, - update - }; - hooks[hookIndex.current] = handler; - return next(); - }; - }; - /** - * Access the operation function, if there are multiple matches, onMatch will be called with this - * @param id Delegator id, or regular expression - * @param onMatch matching subscribers - * @param silent Default is false. If true, no error will be reported if there is no match - */ - const accessAction = (id, onMatch, silent = false) => { - const matched = []; - if (typeof id === 'symbol' || isString(id) || isNumber(id)) { - actionsMap[id] && pushItem(matched, ...objectValues(actionsMap[id])); - } - else if (instanceOf(id, RegExp)) { - forEach(filterItem(objectKeys(actionsMap), idItem => id.test(idItem)), idItem => { - pushItem(matched, ...objectValues(actionsMap[idItem])); - }); - } - // its opposite expression is too obscure - if (matched.length === 0 && !silent) { - assert(false, `no handler can be matched by using \`${id.toString()}\``); - } - forEach(filterItem(matched, $self), onMatch); - }; - - exports.accessAction = accessAction; - exports.actionDelegationMiddleware = actionDelegationMiddleware; - exports.bootSilentFactory = bootSilentFactory; - exports.createClientTokenAuthentication = createClientTokenAuthentication; - exports.createServerTokenAuthentication = createServerTokenAuthentication; - exports.dehydrateVData = dehydrateVData; - exports.equals = equals; - exports.filterSilentMethods = filterSilentMethods; - exports.getSilentMethod = getSilentMethod; - exports.isVData = isVData; - exports.onBeforeSilentSubmit = onBeforeSilentSubmit; - exports.onSilentSubmitBoot = onSilentSubmitBoot; - exports.onSilentSubmitError = onSilentSubmitError; - exports.onSilentSubmitFail = onSilentSubmitFail; - exports.onSilentSubmitSuccess = onSilentSubmitSuccess; - exports.silentQueueMap = silentQueueMap; - exports.statesHookHelper = statesHookHelper; - exports.stringifyVData = stringifyVData; - exports.updateState = updateState; - exports.updateStateEffect = updateStateEffect; - exports.useAutoRequest = useAutoRequest; - exports.useCaptcha = useCaptcha; - exports.useFetcher = useFetcher; - exports.useForm = useForm; - exports.usePagination = usePagination; - exports.useRequest = useRequest; - exports.useRetriableRequest = useRetriableRequest; - exports.useSQRequest = useSQRequest; - exports.useSSE = useSSE; - exports.useSerialRequest = useSerialRequest; - exports.useSerialWatcher = useSerialWatcher; - exports.useWatcher = useWatcher; - -})); diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/clienthook/index.umd.min.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/clienthook/index.umd.min.js deleted file mode 100644 index e527b4c..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/clienthook/index.umd.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("alova")):"function"==typeof define&&define.amd?define(["exports","alova"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).AlovaClientHook={},e.alova)}(this,(function(e,t){"use strict";const r="undefined",n=Promise,o=e=>n.resolve(e),s=Object,a=RegExp,i=void 0,c=null,u=!0,l=!1,d=(e,t,r)=>e.then(t,r),f=(e,t)=>e.catch(t),m=(e,t=0)=>setTimeout(e,t),h=e=>s.keys(e),v=e=>s.values(e),p=(e,t)=>e.forEach(t),g=(e,...t)=>e.push(...t),y=(e,t)=>e.map(t),S=(e,t)=>e.filter(t),w=e=>e.shift(),b=(e,t,r=0,...n)=>e.splice(t,r,...n),E=e=>e.length,x=e=>Array.isArray(e),R=(e,t)=>delete e[t],_=e=>typeof e,k=(e,t)=>e.test(`${t}`),C=(e,t)=>e.includes(t),M=(e,t=l)=>({value:e,writable:t}),T=(e,t,r,n=l)=>s.defineProperty(e,t,n?r:M(r,l));typeof window===r&&typeof process!==r&&process.cwd;const j="memory",P=()=>{},O=e=>e,H=e=>"function"===_(e),q=e=>"number"===_(e)&&!Number.isNaN(e),D=e=>"string"===_(e),F=e=>e!==c&&"object"===_(e),L=e=>s.prototype.toString.call(e),U=e=>"[object Object]"===L(e),A=(e,t)=>e instanceof t,Q=e=>e?e.getTime():Date.now(),$=e=>e.context,N=e=>e.config,z=()=>{const e=(new Date).getTime();return Math.floor(Math.random()*e).toString(36)},W=e=>e.key,G=(e,t,r=[])=>{const n=H(e)?e(...r):e;return t(!!n.key,"hook handler must be a method instance or a function that returns method instance"),n},B=(e,...t)=>s.assign(e,...t),K=(e,...t)=>{const r={};for(const n in e)t.includes(n)||(r[n]=e[n]);return r};function I(){let e,t;return{promise:new Promise(((r,n)=>{e=r,t=n})),resolve:e,reject:t}}const V=e=>{const{cacheFor:t}=N(e);let r=j,n=()=>0,o=l,s=i;const a=H(t);if(!a){let a=t;if(U(t)){const{mode:e=j,expire:n,tag:c}=t||{};r=e,o="restore"===e,s=c?c.toString():i,a=n}n=t=>{return r=H(a)?a({method:e,mode:t}):a,q(r)?Q()+r:Q(r||i);var r}}return{f:t,c:a,e:n,m:r,s:o,t:s}},J=(e,...t)=>new e(...t),X=(e,t=[])=>H(e)?e(...t):e,Y=(e=l)=>{const t=[];let r=i,o=!1;return{addQueue:s=>J(n,((n,a)=>{g(t,(()=>d(s(),n,(t=>{e?n(i):a(t)})))),o||(async()=>{for(o=!0;E(t)>0;){const e=w(t);e&&await e()}r&&r(),o=!1})()})),onComplete:e=>{r=e}}},Z=(e,t,r=u,n,o)=>{const s=()=>{o&&n&&(e=t(e,n,o))!==o[n]&&(o[n]=e)};if(r&&s(),F(e))for(const n in e)A(e,String)||Z(e[n],t,r,n,e);return!r&&s(),e},ee=(e,t)=>{let{startQuiver:r,endQuiver:n}=e;const{delay:o,multiplier:s=1}=e;let a=(o||0)*s**(t-1);return(r||n)&&(r=r||0,n=n||1,a+=a*r+Math.random()*a*(n-r),a=Math.floor(a)),a};class te extends Error{constructor(e,t,r){super(t+(r?`\n\nFor detailed: https://alova.js.org/error#${r}`:"")),this.name=`[alova${e?`/${e}`:""}]`}}const re=(e="")=>(t,r,n)=>{if(!t)throw J(te,e,r,n)},ne=()=>{const e={};return{eventMap:e,on(t,r){const n=e[t]=e[t]||[];return g(n,r),()=>{e[t]=S(n,(e=>e!==r))}},off(t,r){const n=e[t];if(n)if(r){const e=n.indexOf(r);e>-1&&n.splice(e,1)}else delete e[t]},emit(t,r){const n=e[t]||[];return y(n,(e=>e(r)))}}},oe=(e,t)=>{const r=ne(),n=z(),o=e((e=>r.emit(n,e)));return e=>(r.on(n,(r=>{t(e,r)})),o)};class se{constructor(e,t,r,n){this.s=e,this.k=t,this.$dhy=r,this.$exp=n}get v(){return this.$dhy(this.s)}get e(){return this.$exp(this.s)}}class ae extends se{constructor(e,t,r,n,o){super(e,t,r,n),this.$upd=o}set v(e){this.$upd(this.s,e)}get v(){return super.v}}const ie={authRole:null},ce={authRole:"login"},ue={authRole:"logout"},le={authRole:"refreshToken"},de=({meta:e},t)=>{if(U(e))for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)){const n=t[r];if(A(n,RegExp)?n.test(e[r]):e[r]===n)return u}return l},fe=(e,t)=>J(n,(r=>{g(t,{method:e,resolve:r})})),me=(e,t,r,n)=>{if(de(e,(null==t?void 0:t.metaMatches)||r)){return(H(t)?t:U(t)&&H(t.handler)?t.handler:P)(n,e)}},he=async(e,t,r,o,s,a)=>{const c=E(o)>=2;let d=null==s?void 0:s.isExpired(...o);if(A(d,n)&&(d=await d),d)try{let n=u;if(c&&a&&(n=l,await fe(e,t)),n&&(r(u),await(null==s?void 0:s.handler(...o)),r(l),p(t,(({resolve:e})=>e()))),c){const{config:t}=e,r=t.transform;t.transform=i;const n=await e;return t.transform=r,n}}finally{r(l),b(t,0,E(t))}},ve=e=>{let t=i,r=i,n=i;if(H(e))t=e;else if(U(e)){const{onSuccess:o,onError:s,onComplete:a}=e;t=H(o)?o:t,r=H(s)?s:r,n=H(a)?a:n}return{onSuccess:t,onError:r,onComplete:n}},pe=e=>{throw e};const ge=(e,t)=>{let r=c;return function(...n){const o=e.bind(this,...n),s=q(t)?t:t(...n);r&&(e=>{clearTimeout(e)})(r),s>0?r=m(o,s):o()}},ye=(e,r=[])=>{const n=H(e)?e(...r):e;return re("scene")(A(n,t.Method),"hook handler must be a method instance or a function that returns method instance"),n};var Se;function we(e,t={trackedKeys:{},bindError:l}){const r=t=>e.ref?e.ref(t):{current:t};t=r(t).current;const n=r=>(e.export||O)(r,t),o=t=>{if(!H(e.memorize))return t;const r=e.memorize(t);return r.memorized=!0,r},{dehydrate:a}=e,i=(r,n,o)=>r!==a(n,o,t)&&t.trackedKeys[o]&&e.update(r,n,o,t),c=e=>y(e,(e=>A(e,se)?e.e:e)),d=[],f={};return{create:(r,o)=>(g(d,o),J(ae,e.create(r,o,t),o,(e=>a(e,o,t)),n,((e,t)=>i(t,e,o)))),computed:(r,o,s)=>(p(o,(e=>{e.k&&(f[e.k]=!0)})),J(se,e.computed(r,c(o),s,t),s,(e=>a(e,s,t)),n)),effectRequest:r=>e.effectRequest(r,t),ref:r,watch:(r,n)=>e.watch(c(r),n,t),onMounted:r=>e.onMounted(r,t),onUnmounted:r=>e.onUnmounted(r,t),memorize:o,__referingObj:t,exposeProvider:e=>{const r={},n={};for(const a in e){const i=e[a];if(H(i)&&!t.trackedKeys[a])r[a]=a.startsWith("on")?(...e)=>(i(...e),v):i.memorized?i:o(i);else{const e=A(i,se);e&&(n[a]=i.s),s.defineProperty(r,a,{get:()=>(t.trackedKeys[a]=u,e?i.e:i),set:P,enumerable:u,configurable:u})}}const{update:a,__proxyState:c}=r;t.trackedKeys={...f},t.bindError=l;const m={__referingObj:t,update:o((e=>{h(e).forEach((t=>{C(d,t)?i(e[t],n[t],t):t in r&&H(a)&&a({[t]:e[t]})}))})),__proxyState:o((r=>C(d,r)&&A(e[r],se)?(t.trackedKeys[r]=u,e[r]):c(r)))},v=B(r,m);return v},objectify:(e,t)=>e.reduce(((e,r)=>(e[r.k]=t?r[t]:r,e)),{}),transformState2Proxy:(e,r)=>J(ae,e,r,(e=>a(e,r,t)),n,((e,t)=>i(t,e,r)))}}!function(e){e[e.USE_REQUEST=1]="USE_REQUEST",e[e.USE_WATCHER=2]="USE_WATCHER",e[e.USE_FETCHER=3]="USE_FETCHER"}(Se||(Se={}));const be=re(""),Ee=re("useRequest"),xe=re("useWatcher"),Re=re("useFetcher"),_e=e=>({[Se.USE_REQUEST]:Ee,[Se.USE_WATCHER]:xe,[Se.USE_FETCHER]:Re}[e]),ke=(e,r)=>e(A(r,t.Method),"expected a method instance."),Ce="success",Me="error",Te="complete";class je{constructor(e,t){this.method=e,this.args=t}clone(){return{...this}}static spawn(e,t){return new je(e,t)}}class Pe extends je{constructor(e,t,r){super(e.method,e.args),this.data=t,this.fromCache=r}}class Oe extends je{constructor(e,t){super(e.method,e.args),this.error=t}}class He extends je{constructor(e,t,r,n,o){super(e.method,e.args),this.status=t,this.data=r,this.fromCache="error"!==t&&n,this.error=o}}class qe extends je{constructor(e,t){super(e.method,e.args),this.eventSource=t}}class De extends qe{constructor(e,t){super(e,e.eventSource),this.error=t}}class Fe extends qe{constructor(e,t){super(e,e.eventSource),this.data=t}}class Le{constructor(e,t,r){this.behavior=e,this.method=t,this.silentMethod=r}}class Ue extends Le{constructor(e,t,r,n,o){super(e,t,r),this.queueName=n,this.retryTimes=o}}class Ae extends Ue{constructor(e,t,r,n,o,s,a){super(e,t,r,n,o),this.data=s,this.vDataResponse=a}}class Qe extends Ue{constructor(e,t,r,n,o,s,a){super(e,t,r,n,o),this.error=s,this.retryDelay=a}}class $e extends Ue{constructor(e,t,r,n,o,s){super(e,t,r,n,o),this.error=s}}class Ne extends Le{constructor(e,t,r,n){super(e,t,r),this.args=n}}class ze extends Ne{constructor(e,t,r,n,o){super(e,t,r,n),this.data=o}}class We extends Ne{constructor(e,t,r,n,o){super(e,t,r,n),this.error=o}}class Ge extends Ne{constructor(e,t,r,n,o,s){super(e,t,r,n),this.retryTimes=o,this.retryDelay=s}}class Be extends Ne{constructor(e,t,r,n,o,s,a){super(e,t,r,n),this.status=o,this.data=s,this.error=a}}class Ke extends je{constructor(e,t,r){super(e.method,e.args),this.retryTimes=t,this.retryDelay=r}}class Ie extends Oe{constructor(e,t,r){super(e,t),this.retryTimes=r}}const Ve=(e,t)=>t(),Je={},Xe=(e,t)=>(Je[e]||{})[t]||{};function Ye(e,r,n=[]){const s=_e(e.ht);let a=G(r,s,n);const{fs:c,ht:f,c:m,ms:h}=e,{loading:v,data:p,error:y}=c,S=f===Se.USE_FETCHER,{force:w=l,middleware:b=Ve}=m,E=$(a),{id:x}=E,_=W(a),{abortLast:k=u}=m,C=!e.m;return e.m=a,(async()=>{let E=P,M=P,T=l,j=o(i),O=P,H=P;const q=await t.queryCache(a);let D=()=>!!q,F=l;S||(M=t=>((e,t,r,n)=>{(Je[e]=Je[e]||{})[t]={s:r,h:n}})(x,_,t,e),M({...c,...h}),E=()=>((e,t)=>{const r=Je[e];r&&R(r,t)})(x,_));const L=t=>{T=u;const{force:r=w,method:o=a}=t||{},s=X(r,[J(je,a,n)]),i=e=>({loaded:t,total:r})=>{c[e].v={loaded:t,total:r}};a=o,g(e.sf,M),g(e.rf,E),F||(v.v=!!s||!q);const{downloading:d,uploading:f}=e.ro.trackedKeys;return O=d?a.onDownload(i("downloading")):O,H=f?a.onUpload(i("uploading")):H,j=a.send(s),D=()=>a.fromCache||l,j},U={method:a,cachedResponse:q,config:m,abort:()=>a.abort()},A=()=>f!==Se.USE_WATCHER||!k||e.m===a,Q=(e=u)=>{e&&C&&(v.v=l),F=e},$=b(S?{...U,args:n,fetch:(t,...r)=>(ke(s,t),Ye(e,t,r)),proxyStates:K(c,"data"),controlLoading:Q}:{...U,args:n,send:(...t)=>Ye(e,r,t),proxyStates:c,controlLoading:Q},L);let N=i;const z=je.spawn(a,n);try{const t=await $,r=t=>{if(S){if(e.c.updateState!==l){const e=Xe(x,_).s;e&&(e.data.v=t)}}else A()&&(p.v=t);return A()&&(y.v=i,!F&&(v.v=l),e.em.emit(Ce,J(Pe,z,t,D())),e.em.emit(Te,J(He,z,Ce,t,D(),i))),t};N=t!==i?r(t):T?await d(j,r,(()=>r(i))):i,!T&&!F&&(v.v=l)}catch(t){throw A()&&(y.v=t,!F&&(v.v=l),e.em.emit(Me,J(Oe,z,t)),e.em.emit(Te,J(He,z,Me,i,D(),t))),t}return O(),H(),N})()}const Ze=e=>e.current;function et(e,r,o,s,a=l,c,d=0){var h;o={...o};const{__referingObj:v={trackedKeys:{},bindError:l}}=o;let g=!!a,y=i;if(a)try{const t=G(r,_e(e)),s=$(t),a=s.l1Cache.get((S=s.id,w=W(t),"$a."+S+w));if(a&&!A(a,n)){const[e,t]=a;(!t||t>Q())&&(y=e)}g=!!X(null!==(h=o.force)&&void 0!==h?h:l)||!y}catch(e){}var S,w;const{create:b,effectRequest:E,ref:R,objectify:_,exposeProvider:k,transformState2Proxy:C}=we(t.promiseStatesHook(),v),M={total:0,loaded:0},{managedStates:T={}}=o,j=((e,t)=>{const r={};for(const n in e)r[n]=t(e[n],n,e);return r})(T,((e,t)=>C(e,t))),P=b(null!=y?y:H(s)?s():s,"data"),O=b(g,"loading"),D=b(i,"error"),F=b({...M},"downloading"),L=b({...M},"uploading"),U=_([P,O,D,F,L]),N=ne(),z=Ze(R(((e,t,r,n)=>({m:i,sf:[],rf:[],fs:{},em:r,ht:e,c:t,ro:n,ms:{}}))(e,o,N,v)));z.fs=U,z.em=N,z.c=o,z.ms=j;const B=c!==i,K=(e=r,t)=>Ye(z,e,t),I=Ze(R(((e=0)=>{let t=i;return r=>{t&&clearTimeout(t),t=m(r,e)}})())),V=(e=v,t)=>{I((()=>{f(K(t),(t=>{if(!e.bindError&&!e.trackedKeys.error)throw t}))}))},J=R(ge(((e,t,r)=>V(t,r)),(e=>q(e)?x(d)?d[e]:d:0)));return t.globalConfigMap.ssr||E({handler:B?e=>J.current(e,v,r):()=>V(v),removeStates:()=>p(z.rf,(e=>e())),saveStates:e=>p(z.sf,(t=>t(e))),frontStates:{...U,...j},watchingStates:c,immediate:null!=a?a:u}),k({..._([P,O,D,F,L]),abort:()=>z.m&&z.m.abort(),send:(e,t)=>K(t,e),onSuccess(e){N.on(Ce,e)},onError(e){v.bindError=u,N.on(Me,e)},onComplete(e){N.on(Te,e)}})}function tt(e={}){const t=et(Se.USE_FETCHER,P,e),{send:r}=t;return R(t,"send"),B(t,{fetch:(e,...t)=>(ke(Re,e),r(t,e))})}function rt(e,t={}){const{immediate:r=u,initialData:n}=t,o=et(Se.USE_REQUEST,e,t,n,!!r),{send:s}=o;return B(o,{send:(...e)=>s(e)})}function nt(e,t,r={}){xe(t&&E(t)>0,"expected at least one watching state");const{immediate:n,debounce:o=0,initialData:s}=r,a=et(Se.USE_WATCHER,e,r,s,!!n,t,o),{send:i}=a;return B(a,{send:(...e)=>i(e)})}const ot=re("usePagination"),st=(e,t)=>ot(q(e)&&e[e[e.length-2],e[e.length-1],e.slice(0,e.length-2)];const it=(e,t)=>re(e)(x(t)&&E(t)>0,"please use an array to represent serial requests"),ct=(e,t,r=[])=>(e.shift(),(n,s)=>{null==t||t(n,(()=>o(i))),n.controlLoading();const a=n.proxyStates.loading;a.v=u;let c=s();for(const t of e)c=d(c,(e=>{const o=t(e,...n.args);return g(r,o),o.send()}));return c.finally((()=>{a.v=l}))});const ut="valueOf",lt="default",dt="silent";let ft;const mt=e=>{ft=e};let ht;let vt={};let pt=0;const gt=e=>{pt=e};let yt=[];const St=Symbol("GlobalSQBoot"),wt=Symbol("GlobalSQBefore"),bt=Symbol("GlobalSQSuccess"),Et=Symbol("GlobalSQError"),xt=Symbol("GlobalSQFail"),Rt=ne(),_t=re("useSQRequest");async function kt(e,r){let n=l;if(e){const{update:o}=t.promiseStatesHook(),s=W(e),{id:a}=$(e),{s:c,h:l}=Xe(a,s),d=H(r)?{data:r}:r;let f=i;c&&(p(h(d),(e=>{be(e in c,`state named \`${e}\` is not found`);const t=c[e];let r=d[e](t.v);r=x(r)?[...r]:F(r)?{...r}:r,"data"===e&&(f=r),o(r,c[e].s,e,l.ro)})),n=u),f!==i&&t.setCache(e,f)}return n}var Ct={forward:e=>A(e,Date)?e.getTime():i,backward:e=>J(Date,e)},Mt={forward:e=>A(e,RegExp)?e.source:void 0,backward:e=>J(RegExp,e)};const Tt=(e={})=>{const t={date:Ct,regexp:Mt,...e};return{serialize:e=>(F(e)&&(e=Z(x(e)?[...e]:{...e},(e=>{let r=i;const n=h(t).reduce(((e,n)=>{if(!r){const o=t[n].forward(e);o!==i&&(r=n,e=o)}return e}),e);return"[object Object]"===s.prototype.toString.call(e)?e={...e}:x(e)&&(e=[...e]),r!==i?[r,n]:e}))),e),deserialize:e=>F(e)?Z(e,(e=>{if(x(e)&&2===E(e)){const r=t[e[0]];e=r?r.backward(e[1]):e}return e}),l):e}},jt=Symbol("vdid"),Pt=Symbol("original"),Ot=/\[vd:([0-9a-z]+)\]/,Ht=e=>{const t=null==e?void 0:e[jt];t&&ft&&(ft[t]=i)},qt=(e,t=u)=>{Ht(e);const r=null==e?void 0:e[jt];return(r?`[vd:${r}]`:i)||(t?e:i)};function Dt(){return qt(this)}const Ft=function(){};Ft.prototype=s.create(c,{[ut]:M(Dt)});const Lt=function(){};Lt.prototype=s.create(c,{[ut]:M(Dt)});var Ut=(e,t=z())=>{const r=(e,t=z())=>{if(e===c)e=J(Ft);else if(e===i)e=J(Lt);else{const t=s(e);T(t,ut,Dt),T(t,Pt,e),e=t}return T(e,jt,t),e},n=r(e,t);return(U(n)||x(n))&&Z(n,(e=>r(e))),n};const At=(e,t=u)=>{const r=e=>(Ht(e),(null==e?void 0:e[jt])&&(A(e,Lt)?e=i:A(e,Ft)?e=c:(A(e,Number)||A(e,String)||A(e,Boolean))&&(e=e[Pt])),e),n=r(e);return t&&(F(n)||x(n))&&Z(n,(e=>r(e))),n};const Qt="__$k",$t="__$v",Nt=()=>(_t(!!ht,"alova instance is not found, Do you forget to set `alova` or call `bootSilentFactory`?"),ht.l2Cache);let zt=i;const Wt="alova.SQ",Gt="alova.SM.",Bt=async(e,t)=>{const r=Nt();F(t)&&(t=Z(x(t)?[...t]:{...t},((e,t,r)=>{var n;if(t===$t&&r[Qt])return e;if("context"===t&&"Alova"===(null===(n=null==e?void 0:e.constructor)||void 0===n?void 0:n.name))return i;const o=null==e?void 0:e[jt];let s=At(e,l);if("[object Object]"===L(s)?(e={...e},s={}):x(e)&&(e=[...e],s=[]),o){const t={[Qt]:o,[$t]:s,...e};if(A(e,String))for(let r=0;r{const t=await Nt().get(e);return zt=zt||Tt(vt),F(t)?Z(zt.deserialize(t),(e=>{if(F(e)&&(null==e?void 0:e[Qt])){const t=e[Qt],r=Ut(e[$t],t);p(h(e),(t=>{C([Qt,$t],t)||(r[t]=e[t])})),e=r}return e}),l):t},It=async e=>{await Nt().remove(e)},Vt=e=>Bt(Gt+e.id,e),Jt=async(e,t,r)=>{const n=await Kt(Wt)||{},o=n[e]||[],s=o.findIndex((e=>e===t));s>=0&&(r?(b(o,s,1,r.id),await Vt(r)):b(o,s,1),await It(Gt+t),E(o)<=0&&delete n[e],E(h(n))>0?await Bt(Wt,n):await It(Wt))};let Xt={};const Yt=(e,t)=>{const r=e=>{const r=qt(e);return r in t?t[r]:D(e)?e.replace(J(a,Ot.source,"g"),(e=>e in t?t[e]:e)):e};return F(e)&&!qt(e,l)?Z(e,r):e=r(e),e},Zt=(e,t)=>{let r={};const n=qt(e,l);if(n&&(r[n]=t),F(e))for(const n in e)r={...r,...Zt(e[n],null==t?void 0:t[n])};return r},er=(e,t)=>{t?e.active=t:delete e.active},tr=1e3,rr=(e,r)=>{const o=t=>{const r=e[0];if(r){const n=yt.find((({queue:e})=>A(e,a)?k(e,t):e===t)),o=()=>e[0]&&s(e[0]),i=(null==n?void 0:n.wait)?X(n.wait,[r,t]):0;i&&i>0?m(o,i):o()}},s=(a,i=0)=>{er(a,u);const{cache:c,id:f,behavior:h,entity:v,retryError:g=/.*/,maxRetryTimes:S=0,backoff:b={delay:tr},resolveHandler:x=P,rejectHandler:R=P,emitter:_,handlerArgs:C=[],virtualResponse:M,force:T}=a;Rt.emit(wt,J(Ue,h,v,a,r,i)),d(v.send(T),(async s=>{if(w(e),c&&await Jt(r,f),x(s),h===dt){const o=Zt(M,s),{targetRefMethod:c,updateStates:u}=a;if(A(c,t.Method)&&u&&E(u)>0){const e={};p(u,(t=>{e[t]=e=>Yt(e,o)}));kt(c,e)||await t.setCache(c,(e=>Yt(e,o)))}await((e,t)=>n.all(y(t,(async t=>{Yt(t.entity,e),t.cache&&await Vt(t)}))))(o,e),Rt.emit(bt,J(Ae,h,v,a,r,i,s,o))}er(a,l),o(r)}),(t=>{if(h!==dt)w(e),R(t);else{const e=e=>Rt.emit(Et,J(Qe,h,v,a,r,i,t,e)),{name:n="",message:o=""}=t||{};let c,u;A(g,RegExp)?u=g:F(g)&&(c=g.name,u=g.message);const l=c&&k(c,n)||u&&k(u,o);if(i{s(a,i+=1),_.emit("retry",J(Ge,h,v,a,C,i,t))}),t)}else gt(2),e(),_.emit("fallback",J(We,h,v,a,C,t)),Rt.emit(xt,J($e,h,v,a,r,i,t))}er(a,l)}))};o(r)},nr=async(e,t,r=lt,n=()=>[])=>{e.cache=t;const o=Xt[r]=Xt[r]||[],s=E(o)<=0,a=!(await Promise.all(n())).some((e=>e===l));return a&&(t&&await(async(e,t)=>{await Vt(e);const r=await Kt(Wt)||{},n=r[t]=r[t]||[];g(n,e.id),await Bt(Wt,r)})(e,r),g(o,e),s&&1===pt&&rr(o,r)),a},or=e=>{let t=i,r="",n=0;for(const o in Xt)if(n=Xt[o].indexOf(e),n>=0){t=Xt[o],r=o;break}return[t,r,n]};class sr{constructor(e,t,r,n=z(),o,s,a,i,c,u,l,d){const f=this;f.entity=e,f.behavior=t,f.id=n,f.emitter=r,f.force=!!o,f.retryError=s,f.maxRetryTimes=a,f.backoff=i,f.resolveHandler=c,f.rejectHandler=u,f.handlerArgs=l,f.vDatas=d}async save(){this.cache&&await Vt(this)}async replace(e){const t=this;_t(e.cache===t.cache,"the cache of new silentMethod must equal with this silentMethod");const[r,n,o]=or(t);r&&(b(r,o,1,e),t.cache&&await Jt(n,t.id,e))}async remove(){const e=this,[t,r,n]=or(e);t&&(b(t,n,1),e.cache&&await Jt(r,e.id))}setUpdateState(e,t="data"){e&&(this.targetRefMethod=e,this.updateStates=x(t)?t:[t])}}var ar=async()=>{const e=await Kt(Wt)||{},r={},o=[];return p(h(e),(n=>{const s=r[n]=r[n]||[];g(o,...y(e[n],(async e=>{const r=await Kt(Gt+e);r&&g(s,(e=>{const{id:r,behavior:n,entity:o,retryError:s,maxRetryTimes:a,backoff:i,resolveHandler:c,rejectHandler:l,handlerArgs:d,targetRefMethod:f,force:m}=e,v=e=>{const{type:r,url:n,config:o,data:s}=e;return J(t.Method,r,ht,n,o,s)},g=J(sr,v(o),n,ne(),r,m,s,a,i,c,l,d);return g.cache=u,f&&(g.targetRefMethod=v(f)),p(h(e),(t=>{C(["id","behavior","emitter","entity","retryError","maxRetryTimes","backoff","resolveHandler","rejectHandler","handlerArgs","targetRefMethod","force"],t)||(g[t]=e[t])})),g})(r))})))})),await n.all(o),r};let ir=i;var cr=(e,t)=>{const{behavior:r="queue",queue:s=lt,retryError:a,maxRetryTimes:c,backoff:f}=t||{},m=ne();let v,p,g,y=lt,S=l;return{c:(...t)=>(_t(H(e),"method handler must be a function. eg. useSQRequest(() => method)"),mt({}),v=t,e(...t)),m:({method:e,args:t,cachedResponse:w,proxyStates:b,config:x},R)=>{const{silentDefaultResponse:_,vDataCaptured:C,force:M=l}=x,T=je.spawn(e,t);p=X(r,[T]),y=X(s,[T]),S=X(M,[T]);const j=()=>{mt(v=i)};if(H(C)){let t=ft&&E(h(ft))>0;if(!t){const{url:r,data:n}=e,{params:o,headers:s}=N(e);Z({url:r,params:o,data:n,headers:s},(e=>(t||!qt(e,l)&&!k(Ot,e)||(t=u),e)))}const r=t?C(e):i;if(r!==i)return j(),o(r)}if("static"!==p){const r=()=>{const r=J(n,((t,r)=>{g=J(sr,e,p,m,i,!!S,a,c,f,t,r,v,ft&&h(ft)),j()}));return d(o(i),(async()=>{const r=()=>J(Ne,p,e,g,t);await nr(g,E(m.eventMap.fallback||[])<=0&&p===dt,y,(()=>m.emit("beforePushQueue",r())))&&m.emit("pushedQueue",r())})),r};if("queue"===p){const e=S||!w;return e&&(b.loading.v=u),e?r():d(o(w))}const s=r(),l=g.virtualResponse=Ut(H(_)?_():i);return d(s,(e=>{b.data.v=e})),o(l)}return j(),R()},d:e=>{e.onSuccess=oe(e.onSuccess,((e,t)=>{ir=g,e(J(ze,p,t.method,g,t.args,t.data))})),e.onError=oe(e.onError,((e,t)=>{e(J(We,p,t.method,g,t.args,t.error))})),e.onComplete=oe(e.onComplete,((e,t)=>{e(J(Be,p,t.method,g,t.args,t.status,t.data,t.error))}))},b:{onFallback:e=>{m.on("fallback",e)},onBeforePushQueue:e=>{m.on("beforePushQueue",e)},onPushedQueue:e=>{m.on("pushedQueue",e)},onRetry:e=>{m.on("retry",e)}}}};const ur=async(e,t=lt,r=l)=>{const n=(t=[])=>t.filter((t=>{if(e===i)return u;const n=N(t.entity).name||"";return(A(e,RegExp)?k(e,n):n===e)&&(r?t.active:u)}));return[...n(Xt[t]),...0===pt?n((await ar())[t]):[]]};const lr=(e,r={})=>{let n=u;const{enableFocus:o=u,enableVisibility:s=u,enableNetwork:a=u,pollingTime:i=0,throttle:c=1e3}=r,{onMounted:d,onUnmounted:f,__referingObj:m}=we(t.promiseStatesHook()),h=rt(e,{...r,__referingObj:m}),v=()=>{n&&(h.send(),c>0&&(n=l,setTimeout((()=>{n=u}),c)))};let p=P,g=P,y=P,S=P;return d((()=>{t.globalConfigMap.ssr||(p=a?lr.onNetwork(v,r):p,g=o?lr.onFocus(v,r):g,y=s?lr.onVisibility(v,r):y,S=i>0?lr.onPolling(v,r):S)})),f((()=>{p(),g(),y(),S()})),h},dr=(e,t)=>(window.addEventListener(e,t),()=>window.removeEventListener(e,t));lr.onNetwork=e=>dr("online",e),lr.onFocus=e=>dr("focus",e),lr.onVisibility=e=>dr("visibilitychange",(()=>"visible"===document.visibilityState&&e())),lr.onPolling=(e,t)=>{const r=setInterval(e,t.pollingTime);return()=>clearInterval(r)};const fr="useCaptcha",mr=re(fr);const hr=Symbol("FormRestore"),vr={},pr=e=>{const t=e=>x(e)?[...e]:U(e)?{...e}:e;return Z(t(e),t)};const gr=Symbol("RetriableRetry"),yr=Symbol("RetriableFail"),Sr="useRetriableRequest",wr=re(Sr);const br=Symbol("SSEOpen"),Er=Symbol("SSEMessage"),xr=Symbol("SSEError");var Rr;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.OPEN=1]="OPEN",e[e.CLOSED=2]="CLOSED"}(Rr||(Rr={}));const _r=re("useSSE"),kr="open",Cr="error",Mr="message";let Tr=0;const jr={},Pr=re("subscriber");e.accessAction=(e,t,r=!1)=>{const n=[];"symbol"==typeof e||D(e)||q(e)?jr[e]&&g(n,...v(jr[e])):A(e,RegExp)&&p(S(h(jr),(t=>e.test(t))),(e=>{g(n,...v(jr[e]))})),0!==n.length||r||Pr(!1,`no handler can be matched by using \`${e.toString()}\``),p(S(n,O),t)},e.actionDelegationMiddleware=e=>{const{ref:r,onUnmounted:n}=we(t.promiseStatesHook()),o=r(Tr+1);return o.current>Tr&&(Tr+=1),n((()=>{var t;(null===(t=jr[e])||void 0===t?void 0:t[o.current])&&delete jr[e][o.current]})),(t,r)=>{const{abort:n,proxyStates:s,delegatingActions:a={}}=t,i=e=>{for(const t in e)s[t]&&(s[t].v=e[t])},c=jr[e]=jr[e]||[],u=(e=>!!e.send)(t)?{...a,send:t.send,abort:n,update:i}:{...a,fetch:t.fetch,abort:n,update:i};return c[o.current]=u,r()}},e.bootSilentFactory=e=>{if(0===pt){const{alova:t,delay:r=500}=e;ht=t,((e={})=>{vt=e})(e.serializers),((e=0)=>{yt=x(e)?e:[{queue:lt,wait:e}]})(e.requestWait),m((async()=>{var e;e=await ar(),p(h(e),(t=>{const r=Xt[t]=Xt[t]||[];g(r,...e[t])})),p(h(Xt),(e=>{rr(Xt[e],e)})),gt(1),Rt.emit(St,i)}),r)}},e.createClientTokenAuthentication=({visitorMeta:e,login:t,logout:r,refreshToken:n,assignToken:o=P})=>{let s=l;const a=[];return{waitingList:a,onAuthRequired:r=>async i=>{const c=de(i,e||ie),u=de(i,(null==t?void 0:t.metaMatches)||ce);return c||u||de(i,(null==n?void 0:n.metaMatches)||le)||(s&&await fe(i,a),await he(i,a,(e=>{s=e}),[i],n)),c||u||await o(i),null==r?void 0:r(i)},onResponseRefreshToken:e=>{const n=ve(e);return{...n,onSuccess:async(e,o)=>(await me(o,t,ce,e),await me(o,r,ue,e),(n.onSuccess||O)(e,o))}}}},e.createServerTokenAuthentication=({visitorMeta:e,login:t,logout:r,refreshTokenOnSuccess:n,refreshTokenOnError:o,assignToken:s=P})=>{let a=l;const i=[];return{waitingList:i,onAuthRequired:r=>async c=>{const u=de(c,e||ie),l=de(c,(null==t?void 0:t.metaMatches)||ce);return u||l||de(c,(null==n?void 0:n.metaMatches)||le)||de(c,(null==o?void 0:o.metaMatches)||le)||a&&await fe(c,i),u||l||await s(c),null==r?void 0:r(c)},onResponseRefreshToken:s=>{const c=ve(s);return{...c,onSuccess:async(o,s)=>{if(!de(s,e||ie)&&!de(s,(null==t?void 0:t.metaMatches)||ce)&&!de(s,(null==n?void 0:n.metaMatches)||le)){const e=await he(s,i,(e=>{a=e}),[o,s],n,a);if(e)return e}return await me(s,t,ce,o),await me(s,r,ue,o),(c.onSuccess||O)(o,s)},onError:async(r,n)=>{if(!de(n,e||ie)&&!de(n,(null==t?void 0:t.metaMatches)||ce)&&!de(n,(null==o?void 0:o.metaMatches)||le)){const e=await he(n,i,(e=>{a=e}),[r,n],o,a);if(e)return e}return(c.onError||P)(r,n)}}}}},e.dehydrateVData=e=>At(e),e.equals=(e,t)=>e===t?u:qt(e)===qt(t),e.filterSilentMethods=ur,e.getSilentMethod=async(e,t=lt,r=l)=>(await ur(e,t,r))[0],e.isVData=e=>!!qt(e,l)||k(Ot,e),e.onBeforeSilentSubmit=e=>Rt.on(wt,e),e.onSilentSubmitBoot=e=>Rt.on(St,e),e.onSilentSubmitError=e=>Rt.on(Et,e),e.onSilentSubmitFail=e=>Rt.on(xt,e),e.onSilentSubmitSuccess=e=>Rt.on(bt,e),e.silentQueueMap=Xt,e.statesHookHelper=we,e.stringifyVData=qt,e.updateState=kt,e.updateStateEffect=async(e,t)=>(ir&&(ir.setUpdateState(e,H(kt)?i:h(kt)),await ir.save()),kt(e,t)),e.useAutoRequest=lr,e.useCaptcha=(e,r={})=>{const{initialCountdown:o,middleware:s}=r;mr(o===i||o>0,"initialCountdown must be greater than 0");const{create:a,ref:c,objectify:u,exposeProvider:d,__referingObj:f}=we(t.promiseStatesHook()),m=a(0,"countdown"),h=rt(e,{...r,__referingObj:f,immediate:l,managedStates:u([m],"s"),middleware:s?(e,t)=>s({...e,send:p},t):i}),v=c(i),p=(...e)=>J(n,((t,n)=>{m.v<=0?h.send(...e).then((e=>{m.v=r.initialCountdown||60,v.current=setInterval((()=>{m.v-=1,m.v<=0&&clearInterval(v.current)}),1e3),t(e)})).catch((e=>n(e))):n(J(te,fr,"the countdown is not over yet"))}));return d({...h,send:p,...u([m])})},e.useFetcher=tt,e.useForm=(e,r={})=>{const n=vr,{id:o,initialForm:s,store:a,resetAfterSubmiting:c,immediate:d=l,middleware:f}=r;t.promiseStatesHook();const{create:m,ref:h,onMounted:v,watch:p,objectify:g,exposeProvider:y,__referingObj:S}=we(t.promiseStatesHook()),w=U(a),b=w?a.enable:a,E=o?n[o]:i,x=m(pr(s),"form"),R=e,_=ne(),k=h(X(R,[x.v])),C=$(k.current).l2Cache,M=((e,t)=>`alova/form-${t||W(e)}`)(k.current,o),T=h(l),j=h(Tt(w?a.serializers:i)),P=h(!1),O=rt(((...e)=>R(x.v,...e)),{...r,__referingObj:S,middleware:f?(e,t)=>f({...e,delegatingActions:{updateForm:q,reset:H}},t):i,immediate:b||E?l:d}),H=()=>{T.current=u;const e=pr(s);e&&(x.v=e),b&&C.remove(M)},q=e=>{x.v={...x.v,...e}},D=y({...O,...g([x]),updateForm:q,reset:H,onRestore(e){_.on(hr,e)}});o&&(E||(P.current=u),P.current&&(n[o]={hookProvider:D,config:r}));const{send:F,onSuccess:L}=D;return v((()=>{if(b&&!E){const e=j.current.deserialize(C.get(M));e&&(x.v=e,_.emit(hr,i)),b&&d&&F()}})),p([x],(()=>{!T.current&&b?C.set(M,j.current.serialize(x.v)):T.current=l})),L((()=>{c&&H()})),E&&!P.current?E.hookProvider:D},e.usePagination=(e,r={})=>{const{create:n,computed:s,ref:a,watch:c,exposeProvider:d,objectify:m,__referingObj:w}=we(t.promiseStatesHook()),{preloadPreviousPage:R=u,preloadNextPage:_=u,total:k=e=>e.total,data:M=e=>e.data,append:T=l,initialPage:O=1,initialPageSize:D=10,watchingStates:F=[],initialData:L,immediate:U=u,middleware:$,force:N=P,...z}=r,G=a(e),B=a(l),K=n(O,"page"),J=n(D,"pageSize"),X=n(L&&M(L)||[],"data"),Z=n(L?k(L):i,"total"),{snapshots:ee,get:te,save:re,remove:ne}=a((e=>{let r={};return{snapshots:()=>r,save(e,t=l){const n=W(e);r[n]&&!t||(r[n]={entity:e})},get:n=>r[W(A(n,t.Method)?n:e(n))],remove(e){e?delete r[e]:r={}}}})((e=>G.current(e,J.v)))).current,oe=e=>M(e)||e,se=tt({__referingObj:w,updateState:l,force:({args:e})=>e[E(e)-1]}),{loading:ae,fetch:ie,abort:ce,onSuccess:ue}=se,le=a(ae),de=(t=K.v,r=[])=>{const n=e(t,J.v,...r);return re(n),n};c(F,(()=>{K.v=O,B.current=u}));const fe=a({}),me=s((()=>{const e=Z.v;return e!==i?Math.ceil(e/J.v):i}),[J,Z],"pageCount"),he=e=>(...t)=>fe.current[e](...t),ve=nt(((...e)=>{const[t,,r]=at(e);return de(t,r)}),[...F,K.e,J.e],{__referingObj:w,immediate:U,initialData:L,managedStates:m([X,K,J,Z],"s"),middleware:(e,t)=>$?$({...e,delegatingActions:{refresh:he("refresh"),insert:he("insert"),remove:he("remove"),replace:he("replace"),reload:he("reload"),getState:e=>({page:K,pageSize:J,data:X,pageCount:me,total:Z,isLastPage:be}[e].v)}},t):t(),force:e=>e.args[1]||(H(N)?N(e):N),...z}),{send:pe}=ve,ge=ve.__proxyState("data"),ye=async e=>{const{rawData:r=ge.v,preloadPage:n,fetchMethod:o,forceRequest:s=l,isNextPage:a=l}=e,i=me.v,c=i?n>i:a?E(oe(r))0&&!c))return l;const{e:u}=V(o),d=await t.queryCache(o);return u(j)<=Q()?l:s||!d},Se=async(e,t,r=[])=>{const n=K.v+1,o=de(n,r);_&&await ye({rawData:e,preloadPage:n,fetchMethod:o,isNextPage:u,forceRequest:t})&&f(ie(o,...r,t),P)},be=s((()=>{const e=ge.v;if(!e)return u;const t=oe(e),r=K.v,n=me.v,o=x(t)?E(t):0;return n?r>=n:o{const e=te(K.v);e&&await t.setCache(e.entity,(e=>{if(e){const t=oe(e)||[];return b(t,0,E(t),...X.v),e}}))};ue((({method:e,data:t})=>{const r=te(K.v);if(r&&W(r.entity)===W(e)){const e=oe(t);if(T){const t=X.v,r=J.v,n=E(t)%r;if(n>0){const t=[...X.v];b(t,(K.v-1)*r,n,...e),X.v=t}}else X.v=e}}));const xe=a(i),Re=a(i);ve.onSuccess((({data:e,args:t,method:r})=>{const[n,o,s]=at(t),{total:a}=te(r)||{},c=e;Z.v=a!==i?a:k(c),o||((async(e,t=[])=>{const r=K.v-1,n=de(r,t);R&&await ye({rawData:e,preloadPage:r,fetchMethod:n})&&f(ie(n,...t,i),P)})(c,s),Se(c,l,s));const u=J.v,d=oe(c);if(ot(x(d),"Got wrong array, did you return the correct array of list in `data` function"),T){if(B.current&&(X.v=[]),n===i)X.v=[...X.v,...d];else if(n){const e=[...X.v];b(e,(n-1)*u,u,...d),X.v=e}}else X.v=d})).onSuccess((({data:e})=>{var t;null===(t=xe.current)||void 0===t||t.call(xe,e)})).onError((({error:e})=>{var t;null===(t=Re.current)||void 0===t||t.call(Re,e)})).onComplete((()=>{B.current=l}));const _e=e=>{const t=X.v.indexOf(e);return ot(t>=0,"item is not found in list"),t},{addQueue:ke,onComplete:Ce}=a(Y()).current,Me=async(t=K.v)=>{let r=t,n=o();if(T){if(!q(t)){const e=_e(t);r=Math.floor(e/J.v)+1}ot(r<=K.v,"refresh page can't greater than page"),n=pe(r,u)}else ot(q(r),"unable to calculate refresh page by item in pagination mode"),n=r===K.v?pe(i,u):ie(e(r,J.v),u);return n},Te=async(e=l)=>{const r=K.v,n=ee();let o=v(n);if(e)ne();else{const e=y(S([te(r-1),te(r),te(r+1)],Boolean),(({entity:e})=>W(e)));o=y(S(h(n),(t=>!C(e,t))),(e=>{const t=n[e];return delete n[e],t}))}await t.invalidateCache(y(o,(({entity:e})=>e)))},je=async()=>{le.current&&ce(),await Te();const e=te(K.v+1);if(e){const r=oe(await t.queryCache(e.entity)||{})||[];Se(i,E(r){if(0===e)return;const t=Z.v;if(q(t)){const r=Math.max(t+e,0);Z.v=r;const n=K.v;p([te(n-1),te(n),te(n+1)],(e=>{e&&(e.total=r)}))}},Oe=(e,r=0)=>(Ce(je),ke((async()=>{const n=q(r)?r:_e(r)+1;let o=i;const s=[...X.v];if(E(s)%J.v==0&&(o=s.pop()),b(s,n,0,e),X.v=s,Pe(1),await Ee(),o){const e=te(K.v+1);e&&await t.setCache(e.entity,(e=>{if(e){const t=oe(e)||[];return t.unshift(o),t.pop(),e}}))}}))),He=(...e)=>(Ce(je),ke((async()=>{const r=y(e,(e=>{const t=q(e)?e:_e(e);return st(t,X.v),t})),n=K.v,o=te(n+1),s=[];o&&await t.setCache(o.entity,(e=>{if(e){const t=oe(e);return x(t)&&g(s,...b(t,0,E(r))),e}}));const a=be.v,i=E(s);let c=!1;if(i>0||a){const e=S(X.v,((e,t)=>!C(r,t)));c=!T&&a&&E(e)<=0,!c&&i>0&&g(e,...s),X.v=e}else i<=0&&!a&&Me(n);return Pe(-E(r)),Ee().then((()=>{c&&(K.v=n-1)}))}))),qe=(e,t)=>ke((async()=>{ot(t!==i,"expect specify the replace position");const r=q(t)?t:_e(t);st(r,X.v);const n=[...X.v];b(n,r,1,e),X.v=n,await Ee()})),De=async()=>{await Te(u),B.current=u,K.v===O?f(pe(),P):K.v=O;const{resolve:e,reject:t,promise:r}=I();return xe.current=e,Re.current=t,r};return fe.current={refresh:Me,insert:Oe,remove:He,replace:qe,reload:De},d({...ve,...m([X,K,me,J,Z,be]),send:(...e)=>pe(...e,i,i),fetching:se.loading,onFetchSuccess:se.onSuccess,onFetchError:se.onError,onFetchComplete:se.onComplete,refresh:Me,insert:Oe,remove:He,replace:qe,reload:De})},e.useRequest=rt,e.useRetriableRequest=(e,r={})=>{const{retry:s=3,backoff:a={delay:1e3},middleware:c=P}=r,{ref:d,exposeProvider:h,__referingObj:v}=we(t.promiseStatesHook()),p=ne(),g=d(0),y=d(i),S=d(i),w=d(i),b=d(l),E=d(i),x=d(I()),R=rt(e,{...r,__referingObj:v,middleware(e,t){c({...e,delegatingActions:{stop:_}},(()=>o()));const{proxyStates:r,args:d,send:h,method:v,controlLoading:R}=e;R();const{loading:k}=r,C=(e=l)=>{k.v=e},M=e=>{C(),r.error.v=e,clearTimeout(E.current),((e,t,r)=>{m((()=>{p.emit(yr,J(Ie,je.spawn(e,t),r,g.current)),y.current=i,g.current=0}))})(v,d,e)};return k.v||f(x.current.promise,(e=>{M(e),x.current=I()})),C(u),b.current=u,S.current=v,w.current=d,t().then((e=>(C(),e)),(e=>{if(!y.current&&(q(s)?g.current{p.emit(gr,J(Ke,je.spawn(v,d),g.current,e)),f(h(...d),P)}),e)}else e=y.current||e,M(e);return t=e,n.reject(t);var t})).finally((()=>{b.current=l}))}}),_=()=>{wr(R.__proxyState("loading").v,"there is no requests being retried"),y.current=J(te,Sr,"stop retry manually"),b.current?R.abort():x.current.reject(y.current)};return h({...R,stop:_,onRetry:e=>{p.on(gr,(t=>e(t)))},onFail:e=>{p.on(yr,(t=>e(t)))}})},e.useSQRequest=function(e,r={}){const{exposeProvider:n,__referingObj:o}=we(t.promiseStatesHook()),{middleware:s=P}=r,{c:a,m:i,b:c,d:u}=cr(e,r),l=rt(a,{...r,__referingObj:o,middleware:(e,t)=>{const r=i(e,t);return s(e,(()=>r)),r}});return u(l),n({...l,...c})},e.useSSE=(e,r={})=>{const{initialData:n,withCredentials:o,interceptByGlobalResponded:s=u,immediate:a=l}=r,c=u;let{memorize:f}=t.promiseStatesHook();null!=f||(f=O);const{create:m,ref:v,onMounted:g,onUnmounted:w,objectify:b,exposeProvider:E}=we(t.promiseStatesHook()),x=v([]),R=v(i),_=v(i),k=m(n,"data"),C=m(Rr.CLOSED,"readyState");let M,T=ye(e);const j=ne(),q=v(new Map),D=v(O),F=v(pe),L=v(P),A=e=>{const{responded:t}=(e=>$(e).options)(e);if(M=t,H(M))D.current=M;else if(M&&U(M)){const{onSuccess:e,onError:t,onComplete:r}=M;D.current=H(e)?e:D.current,F.current=H(t)?t:F.current,L.current=H(r)?r:L.current}},Q=async e=>{const{headers:r,transform:n=O}=N(T),o=await e,s=await n(o,r||{});return k.v=s,t.hitCacheBySource(T),s},z=async(e,t)=>{_r(!!R.current,"EventSource is not initialized");const r=R.current,n=new qe(je.spawn(T,x.current),r);if(e===kr)return Promise.resolve(n);const o=s?D.current:O,a=s?F.current:pe,i=s?L.current:P,c=(u=d(t,(e=>Q(o(e,T))),(e=>Q(a(e,T)))),l=()=>{i(T)},u.finally(l));var u,l;return d(c,(e=>new Fe(n,e)),(e=>new De(n,e)))},W=e=>t=>t.error===i?e(t):j.emit(xr,t),G=f((()=>{var e;C.v=Rr.OPEN,d(z(kr,Promise.resolve()),(e=>j.emit(br,e))),null===(e=_.current)||void 0===e||e.resolve()})),B=f((e=>{var t,r;C.v=Rr.CLOSED,d(z(Cr,Promise.reject(null!==(t=null==e?void 0:e.message)&&void 0!==t?t:"SSE Error")),W((e=>j.emit(Er,e)))),null===(r=_.current)||void 0===r||r.resolve()})),K=f((e=>{d(z(Mr,Promise.resolve(e.data)),W((e=>j.emit(Er,e))))})),V=()=>{const e=R.current;e&&(_.current&&_.current.resolve(),e.close(),e.removeEventListener(kr,G),e.removeEventListener(Cr,B),e.removeEventListener(Mr,K),C.v=Rr.CLOSED,q.current.forEach((([t,r],n)=>{e.removeEventListener(n,r)})))},J=(...t)=>{let r=R.current,n=_.current;r&&c&&V(),n||(n=_.current=I(),n&&n.promise.finally((()=>{n=i}))),x.current=t,T=ye(e,t),A(T);const{params:s}=N(T),{baseURL:a,url:u}=T,l=((e,t,r)=>{e=e.endsWith("/")?e.slice(0,-1):e,""!==t&&(t=t.match(/^(\/|https?:\/\/)/)?t:`/${t}`);const n=e+t,o=y(S(h(r),(e=>r[e]!==i)),(e=>`${e}=${r[e]}`)).join("&");return o?+n.includes("?")?`${n}&${o}`:`${n}?${o}`:n})(a,u,s);return r=new EventSource(l,{withCredentials:o}),R.current=r,C.v=Rr.CONNECTING,r.addEventListener(kr,G),r.addEventListener(Cr,B),r.addEventListener(Mr,K),q.current.forEach((([e,t],n)=>{null==r||r.addEventListener(n,(e=>{d(z(n,Promise.resolve(e.data)),W(t))}))})),n.promise};return w((()=>{V(),j.off(br),j.off(Er),j.off(xr),q.current.forEach((([e,t,r])=>{r()}))})),g((()=>{var e;a&&(J(),null===(e=_.current)||void 0===e||e.promise.catch((()=>{})))})),E({send:J,close:V,on:(e,t)=>{var r;const n=q.current;if(!n.has(e)){const t=function(e=P){let t=[];return[r=>(t.includes(r)||(t.push(r),e(t)),()=>{t=S(t,(e=>e!==r)),e(t)}),(...e)=>{if(t.length>0)return p(t,(t=>t(...e)))},()=>{t=[],e(t)}]}((r=>{var n;0===r.length&&(null===(n=R.current)||void 0===n||n.removeEventListener(e,t[1]),q.current.delete(e))})),o=t[1];n.set(e,t),null===(r=R.current)||void 0===r||r.addEventListener(e,(t=>{d(z(e,Promise.resolve(t.data)),W(o))}))}const[o]=n.get(e);return o(t)},onMessage:e=>{j.on(Er,e)},onError:e=>{j.on(xr,e)},onOpen:e=>{j.on(br,e)},eventSource:R,...b([C,k])})},e.useSerialRequest=(e,r={})=>{it("useSerialRequest",e);const{ref:n,__referingObj:o}=we(t.promiseStatesHook()),s=n([]).current,a=rt(e[0],{...r,__referingObj:o,middleware:ct(e,r.middleware,s)});return a.onError=oe(a.onError,((e,t)=>{t.method=s[E(s)-1],e(t)})),a},e.useSerialWatcher=(e,r,n={})=>{it("useSerialWatcher",e);const{ref:o,__referingObj:s}=we(t.promiseStatesHook()),a=o([]).current,i=nt(e[0],r,{...n,__referingObj:s,middleware:ct(e,n.middleware,a)});return i.onError=oe(i.onError,((e,t)=>{t.method=a[E(a)-1],e(t)})),i},e.useWatcher=nt})); diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/serverhook/index.common.cjs b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/serverhook/index.common.cjs deleted file mode 100644 index 67491ce..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/serverhook/index.common.cjs +++ /dev/null @@ -1,865 +0,0 @@ -/** - * @alova/server 1.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -'use strict'; - -var shared = require('@alova/shared'); -var alova = require('alova'); -var rateLimiterFlexible = require('rate-limiter-flexible'); - -class HookedMethod extends alova.Method { - constructor(entity, requestHandler) { - super(entity.type, entity.context, entity.url, { ...entity.config }); - this.handler = requestHandler; - shared.objAssign(this, { - config: { ...entity.config }, - uhs: entity.uhs, - dhs: entity.dhs - }); - } - send(forceRequest) { - return this.handler(forceRequest); - } -} - -const createServerHook = (hookHandler) => hookHandler; - -function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -var RateLimiterAbstract_1 = class RateLimiterAbstract { - /** - * - * @param opts Object Defaults { - * points: 4, // Number of points - * duration: 1, // Per seconds - * blockDuration: 0, // Block if consumed more than points in current duration for blockDuration seconds - * execEvenly: false, // Execute allowed actions evenly over duration - * execEvenlyMinDelayMs: duration * 1000 / points, // ms, works with execEvenly=true option - * keyPrefix: 'rlflx', - * } - */ - constructor(opts = {}) { - this.points = opts.points; - this.duration = opts.duration; - this.blockDuration = opts.blockDuration; - this.execEvenly = opts.execEvenly; - this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs; - this.keyPrefix = opts.keyPrefix; - } - - get points() { - return this._points; - } - - set points(value) { - this._points = value >= 0 ? value : 4; - } - - get duration() { - return this._duration; - } - - set duration(value) { - this._duration = typeof value === 'undefined' ? 1 : value; - } - - get msDuration() { - return this.duration * 1000; - } - - get blockDuration() { - return this._blockDuration; - } - - set blockDuration(value) { - this._blockDuration = typeof value === 'undefined' ? 0 : value; - } - - get msBlockDuration() { - return this.blockDuration * 1000; - } - - get execEvenly() { - return this._execEvenly; - } - - set execEvenly(value) { - this._execEvenly = typeof value === 'undefined' ? false : Boolean(value); - } - - get execEvenlyMinDelayMs() { - return this._execEvenlyMinDelayMs; - } - - set execEvenlyMinDelayMs(value) { - this._execEvenlyMinDelayMs = typeof value === 'undefined' ? Math.ceil(this.msDuration / this.points) : value; - } - - get keyPrefix() { - return this._keyPrefix; - } - - set keyPrefix(value) { - if (typeof value === 'undefined') { - value = 'rlflx'; - } - if (typeof value !== 'string') { - throw new Error('keyPrefix must be string'); - } - this._keyPrefix = value; - } - - _getKeySecDuration(options = {}) { - return options && options.customDuration >= 0 - ? options.customDuration - : this.duration; - } - - getKey(key) { - return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key; - } - - parseKey(rlKey) { - return rlKey.substring(this.keyPrefix.length); - } - - consume() { - throw new Error("You have to implement the method 'consume'!"); - } - - penalty() { - throw new Error("You have to implement the method 'penalty'!"); - } - - reward() { - throw new Error("You have to implement the method 'reward'!"); - } - - get() { - throw new Error("You have to implement the method 'get'!"); - } - - set() { - throw new Error("You have to implement the method 'set'!"); - } - - block() { - throw new Error("You have to implement the method 'block'!"); - } - - delete() { - throw new Error("You have to implement the method 'delete'!"); - } -}; - -var BlockedKeys_1$1 = class BlockedKeys { - constructor() { - this._keys = {}; // {'key': 1526279430331} - this._addedKeysAmount = 0; - } - - collectExpired() { - const now = Date.now(); - - Object.keys(this._keys).forEach((key) => { - if (this._keys[key] <= now) { - delete this._keys[key]; - } - }); - - this._addedKeysAmount = Object.keys(this._keys).length; - } - - /** - * Add new blocked key - * - * @param key String - * @param sec Number - */ - add(key, sec) { - this.addMs(key, sec * 1000); - } - - /** - * Add new blocked key for ms - * - * @param key String - * @param ms Number - */ - addMs(key, ms) { - this._keys[key] = Date.now() + ms; - this._addedKeysAmount++; - if (this._addedKeysAmount > 999) { - this.collectExpired(); - } - } - - /** - * 0 means not blocked - * - * @param key - * @returns {number} - */ - msBeforeExpire(key) { - const expire = this._keys[key]; - - if (expire && expire >= Date.now()) { - this.collectExpired(); - const now = Date.now(); - return expire >= now ? expire - now : 0; - } - - return 0; - } - - /** - * If key is not given, delete all data in memory - * - * @param {string|undefined} key - */ - delete(key) { - if (key) { - delete this._keys[key]; - } else { - Object.keys(this._keys).forEach((key) => { - delete this._keys[key]; - }); - } - } -}; - -const BlockedKeys$1 = BlockedKeys_1$1; - -var BlockedKeys_1 = BlockedKeys$1; - -var RateLimiterRes_1 = class RateLimiterRes { - constructor(remainingPoints, msBeforeNext, consumedPoints, isFirstInDuration) { - this.remainingPoints = typeof remainingPoints === 'undefined' ? 0 : remainingPoints; // Remaining points in current duration - this.msBeforeNext = typeof msBeforeNext === 'undefined' ? 0 : msBeforeNext; // Milliseconds before next action - this.consumedPoints = typeof consumedPoints === 'undefined' ? 0 : consumedPoints; // Consumed points in current duration - this.isFirstInDuration = typeof isFirstInDuration === 'undefined' ? false : isFirstInDuration; - } - - get msBeforeNext() { - return this._msBeforeNext; - } - - set msBeforeNext(ms) { - this._msBeforeNext = ms; - return this; - } - - get remainingPoints() { - return this._remainingPoints; - } - - set remainingPoints(p) { - this._remainingPoints = p; - return this; - } - - get consumedPoints() { - return this._consumedPoints; - } - - set consumedPoints(p) { - this._consumedPoints = p; - return this; - } - - get isFirstInDuration() { - return this._isFirstInDuration; - } - - set isFirstInDuration(value) { - this._isFirstInDuration = Boolean(value); - } - - _getDecoratedProperties() { - return { - remainingPoints: this.remainingPoints, - msBeforeNext: this.msBeforeNext, - consumedPoints: this.consumedPoints, - isFirstInDuration: this.isFirstInDuration, - }; - } - - [Symbol.for("nodejs.util.inspect.custom")]() { - return this._getDecoratedProperties(); - } - - toString() { - return JSON.stringify(this._getDecoratedProperties()); - } - - toJSON() { - return this._getDecoratedProperties(); - } -}; - -const RateLimiterAbstract = RateLimiterAbstract_1; -const BlockedKeys = BlockedKeys_1; -const RateLimiterRes = RateLimiterRes_1; - -var RateLimiterStoreAbstract_1 = class RateLimiterStoreAbstract extends RateLimiterAbstract { - /** - * - * @param opts Object Defaults { - * ... see other in RateLimiterAbstract - * - * inMemoryBlockOnConsumed: 40, // Number of points when key is blocked - * inMemoryBlockDuration: 10, // Block duration in seconds - * insuranceLimiter: RateLimiterAbstract - * } - */ - constructor(opts = {}) { - super(opts); - - this.inMemoryBlockOnConsumed = opts.inMemoryBlockOnConsumed; - this.inMemoryBlockDuration = opts.inMemoryBlockDuration; - this.insuranceLimiter = opts.insuranceLimiter; - this._inMemoryBlockedKeys = new BlockedKeys(); - } - - get client() { - return this._client; - } - - set client(value) { - if (typeof value === 'undefined') { - throw new Error('storeClient is not set'); - } - this._client = value; - } - - /** - * Have to be launched after consume - * It blocks key and execute evenly depending on result from store - * - * It uses _getRateLimiterRes function to prepare RateLimiterRes from store result - * - * @param resolve - * @param reject - * @param rlKey - * @param changedPoints - * @param storeResult - * @param {Object} options - * @private - */ - _afterConsume(resolve, reject, rlKey, changedPoints, storeResult, options = {}) { - const res = this._getRateLimiterRes(rlKey, changedPoints, storeResult); - - if (this.inMemoryBlockOnConsumed > 0 && !(this.inMemoryBlockDuration > 0) - && res.consumedPoints >= this.inMemoryBlockOnConsumed - ) { - this._inMemoryBlockedKeys.addMs(rlKey, res.msBeforeNext); - if (res.consumedPoints > this.points) { - return reject(res); - } else { - return resolve(res) - } - } else if (res.consumedPoints > this.points) { - let blockPromise = Promise.resolve(); - // Block only first time when consumed more than points - if (this.blockDuration > 0 && res.consumedPoints <= (this.points + changedPoints)) { - res.msBeforeNext = this.msBlockDuration; - blockPromise = this._block(rlKey, res.consumedPoints, this.msBlockDuration, options); - } - - if (this.inMemoryBlockOnConsumed > 0 && res.consumedPoints >= this.inMemoryBlockOnConsumed) { - // Block key for this.inMemoryBlockDuration seconds - this._inMemoryBlockedKeys.add(rlKey, this.inMemoryBlockDuration); - res.msBeforeNext = this.msInMemoryBlockDuration; - } - - blockPromise - .then(() => { - reject(res); - }) - .catch((err) => { - reject(err); - }); - } else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) { - let delay = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2)); - if (delay < this.execEvenlyMinDelayMs) { - delay = res.consumedPoints * this.execEvenlyMinDelayMs; - } - - setTimeout(resolve, delay, res); - } else { - resolve(res); - } - } - - _handleError(err, funcName, resolve, reject, key, data = false, options = {}) { - if (!(this.insuranceLimiter instanceof RateLimiterAbstract)) { - reject(err); - } else { - this.insuranceLimiter[funcName](key, data, options) - .then((res) => { - resolve(res); - }) - .catch((res) => { - reject(res); - }); - } - } - - getInMemoryBlockMsBeforeExpire(rlKey) { - if (this.inMemoryBlockOnConsumed > 0) { - return this._inMemoryBlockedKeys.msBeforeExpire(rlKey); - } - - return 0; - } - - get inMemoryBlockOnConsumed() { - return this._inMemoryBlockOnConsumed; - } - - set inMemoryBlockOnConsumed(value) { - this._inMemoryBlockOnConsumed = value ? parseInt(value) : 0; - if (this.inMemoryBlockOnConsumed > 0 && this.points > this.inMemoryBlockOnConsumed) { - throw new Error('inMemoryBlockOnConsumed option must be greater or equal "points" option'); - } - } - - get inMemoryBlockDuration() { - return this._inMemoryBlockDuration; - } - - set inMemoryBlockDuration(value) { - this._inMemoryBlockDuration = value ? parseInt(value) : 0; - if (this.inMemoryBlockDuration > 0 && this.inMemoryBlockOnConsumed === 0) { - throw new Error('inMemoryBlockOnConsumed option must be set up'); - } - } - - get msInMemoryBlockDuration() { - return this._inMemoryBlockDuration * 1000; - } - - get insuranceLimiter() { - return this._insuranceLimiter; - } - - set insuranceLimiter(value) { - if (typeof value !== 'undefined' && !(value instanceof RateLimiterAbstract)) { - throw new Error('insuranceLimiter must be instance of RateLimiterAbstract'); - } - this._insuranceLimiter = value; - if (this._insuranceLimiter) { - this._insuranceLimiter.blockDuration = this.blockDuration; - this._insuranceLimiter.execEvenly = this.execEvenly; - } - } - - /** - * Block any key for secDuration seconds - * - * @param key - * @param secDuration - * @param {Object} options - * - * @return Promise - */ - block(key, secDuration, options = {}) { - const msDuration = secDuration * 1000; - return this._block(this.getKey(key), this.points + 1, msDuration, options); - } - - /** - * Set points by key for any duration - * - * @param key - * @param points - * @param secDuration - * @param {Object} options - * - * @return Promise - */ - set(key, points, secDuration, options = {}) { - const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000; - return this._block(this.getKey(key), points, msDuration, options); - } - - /** - * - * @param key - * @param pointsToConsume - * @param {Object} options - * @returns Promise - */ - consume(key, pointsToConsume = 1, options = {}) { - return new Promise((resolve, reject) => { - const rlKey = this.getKey(key); - - const inMemoryBlockMsBeforeExpire = this.getInMemoryBlockMsBeforeExpire(rlKey); - if (inMemoryBlockMsBeforeExpire > 0) { - return reject(new RateLimiterRes(0, inMemoryBlockMsBeforeExpire)); - } - - this._upsert(rlKey, pointsToConsume, this._getKeySecDuration(options) * 1000, false, options) - .then((res) => { - this._afterConsume(resolve, reject, rlKey, pointsToConsume, res); - }) - .catch((err) => { - this._handleError(err, 'consume', resolve, reject, key, pointsToConsume, options); - }); - }); - } - - /** - * - * @param key - * @param points - * @param {Object} options - * @returns Promise - */ - penalty(key, points = 1, options = {}) { - const rlKey = this.getKey(key); - return new Promise((resolve, reject) => { - this._upsert(rlKey, points, this._getKeySecDuration(options) * 1000, false, options) - .then((res) => { - resolve(this._getRateLimiterRes(rlKey, points, res)); - }) - .catch((err) => { - this._handleError(err, 'penalty', resolve, reject, key, points, options); - }); - }); - } - - /** - * - * @param key - * @param points - * @param {Object} options - * @returns Promise - */ - reward(key, points = 1, options = {}) { - const rlKey = this.getKey(key); - return new Promise((resolve, reject) => { - this._upsert(rlKey, -points, this._getKeySecDuration(options) * 1000, false, options) - .then((res) => { - resolve(this._getRateLimiterRes(rlKey, -points, res)); - }) - .catch((err) => { - this._handleError(err, 'reward', resolve, reject, key, points, options); - }); - }); - } - - /** - * - * @param key - * @param {Object} options - * @returns Promise|null - */ - get(key, options = {}) { - const rlKey = this.getKey(key); - return new Promise((resolve, reject) => { - this._get(rlKey, options) - .then((res) => { - if (res === null || typeof res === 'undefined') { - resolve(null); - } else { - resolve(this._getRateLimiterRes(rlKey, 0, res)); - } - }) - .catch((err) => { - this._handleError(err, 'get', resolve, reject, key, options); - }); - }); - } - - /** - * - * @param key - * @param {Object} options - * @returns Promise - */ - delete(key, options = {}) { - const rlKey = this.getKey(key); - return new Promise((resolve, reject) => { - this._delete(rlKey, options) - .then((res) => { - this._inMemoryBlockedKeys.delete(rlKey); - resolve(res); - }) - .catch((err) => { - this._handleError(err, 'delete', resolve, reject, key, options); - }); - }); - } - - /** - * Cleanup keys no-matter expired or not. - */ - deleteInMemoryBlockedAll() { - this._inMemoryBlockedKeys.delete(); - } - - /** - * Get RateLimiterRes object filled depending on storeResult, which specific for exact store - * - * @param rlKey - * @param changedPoints - * @param storeResult - * @private - */ - _getRateLimiterRes(rlKey, changedPoints, storeResult) { // eslint-disable-line no-unused-vars - throw new Error("You have to implement the method '_getRateLimiterRes'!"); - } - - /** - * Block key for this.msBlockDuration milliseconds - * Usually, it just prolongs lifetime of key - * - * @param rlKey - * @param initPoints - * @param msDuration - * @param {Object} options - * - * @return Promise - */ - _block(rlKey, initPoints, msDuration, options = {}) { - return new Promise((resolve, reject) => { - this._upsert(rlKey, initPoints, msDuration, true, options) - .then(() => { - resolve(new RateLimiterRes(0, msDuration > 0 ? msDuration : -1, initPoints)); - }) - .catch((err) => { - this._handleError(err, 'block', resolve, reject, this.parseKey(rlKey), msDuration / 1000, options); - }); - }); - } - - /** - * Have to be implemented in every limiter - * Resolve with raw result from Store OR null if rlKey is not set - * or Reject with error - * - * @param rlKey - * @param {Object} options - * @private - * - * @return Promise - */ - _get(rlKey, options = {}) { // eslint-disable-line no-unused-vars - throw new Error("You have to implement the method '_get'!"); - } - - /** - * Have to be implemented - * Resolve with true OR false if rlKey doesn't exist - * or Reject with error - * - * @param rlKey - * @param {Object} options - * @private - * - * @return Promise - */ - _delete(rlKey, options = {}) { // eslint-disable-line no-unused-vars - throw new Error("You have to implement the method '_delete'!"); - } - - /** - * Have to be implemented - * Resolve with object used for {@link _getRateLimiterRes} to generate {@link RateLimiterRes} - * - * @param {string} rlKey - * @param {number} points - * @param {number} msDuration - * @param {boolean} forceExpire - * @param {Object} options - * @abstract - * - * @return Promise - */ - _upsert(rlKey, points, msDuration, forceExpire = false, options = {}) { - throw new Error("You have to implement the method '_upsert'!"); - } -}; - -var RateLimiterStoreAbstract = /*@__PURE__*/getDefaultExportFromCjs(RateLimiterStoreAbstract_1); - -const assert = shared.createAssert('RateLimit'); -class RateLimiterStore extends RateLimiterStoreAbstract { - constructor(storage, options) { - super(options); - this.storage = storage; - } - /** - * parses raw data from store to RateLimiterRes object. - */ - _getRateLimiterRes(key, changedPoints, result) { - const [consumed = 0, expireTime = 0] = result !== null && result !== void 0 ? result : []; - const msBeforeNext = expireTime > 0 ? Math.max(expireTime - Date.now(), 0) : -1; - const isFirstInDuration = !consumed || changedPoints === consumed; - const currentConsumedPoints = isFirstInDuration ? changedPoints : consumed; - const res = new rateLimiterFlexible.RateLimiterRes(Math.max(0, this.points - currentConsumedPoints), msBeforeNext, isFirstInDuration ? changedPoints : consumed, isFirstInDuration); - return res; - } - async _upsert(key, points, msDuration, forceExpire = false) { - var _a; - key = key.toString(); - const isNeverExpired = msDuration <= 0; - const expireTime = isNeverExpired ? -1 : Date.now() + msDuration; - const newRecord = [points, expireTime]; - if (!forceExpire) { - const [oldPoints = 0, oldExpireTime = 0] = ((_a = (await this.storage.get(key))) !== null && _a !== void 0 ? _a : []); - // if haven't expired yet - if (isNeverExpired || (!isNeverExpired && oldExpireTime > Date.now())) { - newRecord[0] += oldPoints; - } - if (!isNeverExpired && oldExpireTime > Date.now()) { - newRecord[1] = oldExpireTime; - } - } - await this.storage.set(key.toString(), newRecord); - // need to return the record after upsert - return newRecord; - } - /** - * returns raw data by key or null if there is no key or expired. - */ - async _get(key) { - return Promise.resolve(this.storage.get(key.toString())).then(res => { - if (!res) { - return null; - } - const [, expireTime] = res; - // if have expire time and it has expired - if (expireTime > 0 && expireTime <= Date.now()) { - return null; - } - return res; - }); - } - /** - * returns true on deleted, false if key is not found. - */ - async _delete(key) { - try { - await this.storage.remove(key.toString()); - } - catch (_a) { - return false; - } - return true; - } -} -/** - * The method instance modified by rateLimit, its extension method corresponds to the method of creating an instance in rate-limit-flexible, and the key is the key specified by calling rateLimit. - * AlovaServerHook can currently only return unextended method types. It has not been changed to customizable returned extended method types. - */ -class LimitedMethod extends HookedMethod { - constructor(method, limiterKey, limiter) { - super(method, force => this.consume().then(() => method.send(force))); - this.limiter = limiter; - this.keyGetter = shared.isFn(limiterKey) ? () => limiterKey(method) : () => limiterKey; - } - getLimiterKey() { - return this.keyGetter(); - } - /** - * Get RateLimiterRes or null. - */ - get(options) { - return this.limiter.get(this.getLimiterKey(), options); - } - /** - * Set points by key. - */ - set(points, msDuration) { - return this.limiter.set(this.getLimiterKey(), points, msDuration / 1000); - } - /** - * @param points default is 1 - */ - consume(points) { - return this.limiter.consume(this.getLimiterKey(), points); - } - /** - * Increase number of consumed points in current duration. - * @param points penalty points - */ - penalty(points) { - return this.limiter.penalty(this.getLimiterKey(), points); - } - /** - * Decrease number of consumed points in current duration. - * @param points reward points - */ - reward(points) { - return this.limiter.reward(this.getLimiterKey(), points); - } - /** - * Block key for ms. - */ - block(msDuration) { - return this.limiter.block(this.getLimiterKey(), msDuration / 1000); - } - /** - * Reset consumed points. - */ - delete() { - return this.limiter.delete(this.getLimiterKey()); - } -} -function createRateLimiter(options = {}) { - const { points = 4, duration = 4 * 1000, keyPrefix, execEvenly, execEvenlyMinDelayMs, blockDuration } = options; - const limitedMethodWrapper = createServerHook((method, handlerOptions = {}) => { - var _a; - const { key = shared.uuid() } = handlerOptions; - const storage = (_a = options.storage) !== null && _a !== void 0 ? _a : shared.getOptions(method).l2Cache; - assert(!!storage, 'storage is not define'); - const limiter = new RateLimiterStore(storage, { - points, - duration: Math.floor(duration / 1000), - keyPrefix, - execEvenly, - execEvenlyMinDelayMs, - blockDuration: blockDuration ? Math.floor(blockDuration / 1000) : blockDuration, - storeClient: {} - }); - return new LimitedMethod(method, key, limiter); - }); - return limitedMethodWrapper; -} - -const retry = createServerHook((method, options = {}) => { - const { retry = 3, backoff = { delay: 1000 } } = options; - let retryTimes = 0; - return new HookedMethod(method, forceRequest => new Promise((resolve, reject) => { - const sendRequest = () => { - method - .send(forceRequest) - .then(resolve) - .catch(error => { - // when not reach retry times or return true from retry function, it will retry again. - if (shared.isNumber(retry) ? retryTimes < retry : retry(error)) { - retryTimes += 1; - // calculate retry delay time with pram `backoff` and current retry times. - const retryDelay = shared.delayWithBackoff(backoff, retryTimes); - setTimeout(sendRequest, retryDelay); - } - else { - reject(error); - } - }); - }; - sendRequest(); - })); -}); - -exports.HookedMethod = HookedMethod; -exports.createRateLimiter = createRateLimiter; -exports.retry = retry; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/serverhook/index.esm.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/serverhook/index.esm.js deleted file mode 100644 index 1cd3fdc..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/serverhook/index.esm.js +++ /dev/null @@ -1,861 +0,0 @@ -/** - * @alova/server 1.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -import { objAssign, createAssert, uuid, getOptions, isFn, isNumber, delayWithBackoff } from '@alova/shared'; -import { Method } from 'alova'; -import { RateLimiterRes as RateLimiterRes$1 } from 'rate-limiter-flexible'; - -class HookedMethod extends Method { - constructor(entity, requestHandler) { - super(entity.type, entity.context, entity.url, { ...entity.config }); - this.handler = requestHandler; - objAssign(this, { - config: { ...entity.config }, - uhs: entity.uhs, - dhs: entity.dhs - }); - } - send(forceRequest) { - return this.handler(forceRequest); - } -} - -const createServerHook = (hookHandler) => hookHandler; - -function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -var RateLimiterAbstract_1 = class RateLimiterAbstract { - /** - * - * @param opts Object Defaults { - * points: 4, // Number of points - * duration: 1, // Per seconds - * blockDuration: 0, // Block if consumed more than points in current duration for blockDuration seconds - * execEvenly: false, // Execute allowed actions evenly over duration - * execEvenlyMinDelayMs: duration * 1000 / points, // ms, works with execEvenly=true option - * keyPrefix: 'rlflx', - * } - */ - constructor(opts = {}) { - this.points = opts.points; - this.duration = opts.duration; - this.blockDuration = opts.blockDuration; - this.execEvenly = opts.execEvenly; - this.execEvenlyMinDelayMs = opts.execEvenlyMinDelayMs; - this.keyPrefix = opts.keyPrefix; - } - - get points() { - return this._points; - } - - set points(value) { - this._points = value >= 0 ? value : 4; - } - - get duration() { - return this._duration; - } - - set duration(value) { - this._duration = typeof value === 'undefined' ? 1 : value; - } - - get msDuration() { - return this.duration * 1000; - } - - get blockDuration() { - return this._blockDuration; - } - - set blockDuration(value) { - this._blockDuration = typeof value === 'undefined' ? 0 : value; - } - - get msBlockDuration() { - return this.blockDuration * 1000; - } - - get execEvenly() { - return this._execEvenly; - } - - set execEvenly(value) { - this._execEvenly = typeof value === 'undefined' ? false : Boolean(value); - } - - get execEvenlyMinDelayMs() { - return this._execEvenlyMinDelayMs; - } - - set execEvenlyMinDelayMs(value) { - this._execEvenlyMinDelayMs = typeof value === 'undefined' ? Math.ceil(this.msDuration / this.points) : value; - } - - get keyPrefix() { - return this._keyPrefix; - } - - set keyPrefix(value) { - if (typeof value === 'undefined') { - value = 'rlflx'; - } - if (typeof value !== 'string') { - throw new Error('keyPrefix must be string'); - } - this._keyPrefix = value; - } - - _getKeySecDuration(options = {}) { - return options && options.customDuration >= 0 - ? options.customDuration - : this.duration; - } - - getKey(key) { - return this.keyPrefix.length > 0 ? `${this.keyPrefix}:${key}` : key; - } - - parseKey(rlKey) { - return rlKey.substring(this.keyPrefix.length); - } - - consume() { - throw new Error("You have to implement the method 'consume'!"); - } - - penalty() { - throw new Error("You have to implement the method 'penalty'!"); - } - - reward() { - throw new Error("You have to implement the method 'reward'!"); - } - - get() { - throw new Error("You have to implement the method 'get'!"); - } - - set() { - throw new Error("You have to implement the method 'set'!"); - } - - block() { - throw new Error("You have to implement the method 'block'!"); - } - - delete() { - throw new Error("You have to implement the method 'delete'!"); - } -}; - -var BlockedKeys_1$1 = class BlockedKeys { - constructor() { - this._keys = {}; // {'key': 1526279430331} - this._addedKeysAmount = 0; - } - - collectExpired() { - const now = Date.now(); - - Object.keys(this._keys).forEach((key) => { - if (this._keys[key] <= now) { - delete this._keys[key]; - } - }); - - this._addedKeysAmount = Object.keys(this._keys).length; - } - - /** - * Add new blocked key - * - * @param key String - * @param sec Number - */ - add(key, sec) { - this.addMs(key, sec * 1000); - } - - /** - * Add new blocked key for ms - * - * @param key String - * @param ms Number - */ - addMs(key, ms) { - this._keys[key] = Date.now() + ms; - this._addedKeysAmount++; - if (this._addedKeysAmount > 999) { - this.collectExpired(); - } - } - - /** - * 0 means not blocked - * - * @param key - * @returns {number} - */ - msBeforeExpire(key) { - const expire = this._keys[key]; - - if (expire && expire >= Date.now()) { - this.collectExpired(); - const now = Date.now(); - return expire >= now ? expire - now : 0; - } - - return 0; - } - - /** - * If key is not given, delete all data in memory - * - * @param {string|undefined} key - */ - delete(key) { - if (key) { - delete this._keys[key]; - } else { - Object.keys(this._keys).forEach((key) => { - delete this._keys[key]; - }); - } - } -}; - -const BlockedKeys$1 = BlockedKeys_1$1; - -var BlockedKeys_1 = BlockedKeys$1; - -var RateLimiterRes_1 = class RateLimiterRes { - constructor(remainingPoints, msBeforeNext, consumedPoints, isFirstInDuration) { - this.remainingPoints = typeof remainingPoints === 'undefined' ? 0 : remainingPoints; // Remaining points in current duration - this.msBeforeNext = typeof msBeforeNext === 'undefined' ? 0 : msBeforeNext; // Milliseconds before next action - this.consumedPoints = typeof consumedPoints === 'undefined' ? 0 : consumedPoints; // Consumed points in current duration - this.isFirstInDuration = typeof isFirstInDuration === 'undefined' ? false : isFirstInDuration; - } - - get msBeforeNext() { - return this._msBeforeNext; - } - - set msBeforeNext(ms) { - this._msBeforeNext = ms; - return this; - } - - get remainingPoints() { - return this._remainingPoints; - } - - set remainingPoints(p) { - this._remainingPoints = p; - return this; - } - - get consumedPoints() { - return this._consumedPoints; - } - - set consumedPoints(p) { - this._consumedPoints = p; - return this; - } - - get isFirstInDuration() { - return this._isFirstInDuration; - } - - set isFirstInDuration(value) { - this._isFirstInDuration = Boolean(value); - } - - _getDecoratedProperties() { - return { - remainingPoints: this.remainingPoints, - msBeforeNext: this.msBeforeNext, - consumedPoints: this.consumedPoints, - isFirstInDuration: this.isFirstInDuration, - }; - } - - [Symbol.for("nodejs.util.inspect.custom")]() { - return this._getDecoratedProperties(); - } - - toString() { - return JSON.stringify(this._getDecoratedProperties()); - } - - toJSON() { - return this._getDecoratedProperties(); - } -}; - -const RateLimiterAbstract = RateLimiterAbstract_1; -const BlockedKeys = BlockedKeys_1; -const RateLimiterRes = RateLimiterRes_1; - -var RateLimiterStoreAbstract_1 = class RateLimiterStoreAbstract extends RateLimiterAbstract { - /** - * - * @param opts Object Defaults { - * ... see other in RateLimiterAbstract - * - * inMemoryBlockOnConsumed: 40, // Number of points when key is blocked - * inMemoryBlockDuration: 10, // Block duration in seconds - * insuranceLimiter: RateLimiterAbstract - * } - */ - constructor(opts = {}) { - super(opts); - - this.inMemoryBlockOnConsumed = opts.inMemoryBlockOnConsumed; - this.inMemoryBlockDuration = opts.inMemoryBlockDuration; - this.insuranceLimiter = opts.insuranceLimiter; - this._inMemoryBlockedKeys = new BlockedKeys(); - } - - get client() { - return this._client; - } - - set client(value) { - if (typeof value === 'undefined') { - throw new Error('storeClient is not set'); - } - this._client = value; - } - - /** - * Have to be launched after consume - * It blocks key and execute evenly depending on result from store - * - * It uses _getRateLimiterRes function to prepare RateLimiterRes from store result - * - * @param resolve - * @param reject - * @param rlKey - * @param changedPoints - * @param storeResult - * @param {Object} options - * @private - */ - _afterConsume(resolve, reject, rlKey, changedPoints, storeResult, options = {}) { - const res = this._getRateLimiterRes(rlKey, changedPoints, storeResult); - - if (this.inMemoryBlockOnConsumed > 0 && !(this.inMemoryBlockDuration > 0) - && res.consumedPoints >= this.inMemoryBlockOnConsumed - ) { - this._inMemoryBlockedKeys.addMs(rlKey, res.msBeforeNext); - if (res.consumedPoints > this.points) { - return reject(res); - } else { - return resolve(res) - } - } else if (res.consumedPoints > this.points) { - let blockPromise = Promise.resolve(); - // Block only first time when consumed more than points - if (this.blockDuration > 0 && res.consumedPoints <= (this.points + changedPoints)) { - res.msBeforeNext = this.msBlockDuration; - blockPromise = this._block(rlKey, res.consumedPoints, this.msBlockDuration, options); - } - - if (this.inMemoryBlockOnConsumed > 0 && res.consumedPoints >= this.inMemoryBlockOnConsumed) { - // Block key for this.inMemoryBlockDuration seconds - this._inMemoryBlockedKeys.add(rlKey, this.inMemoryBlockDuration); - res.msBeforeNext = this.msInMemoryBlockDuration; - } - - blockPromise - .then(() => { - reject(res); - }) - .catch((err) => { - reject(err); - }); - } else if (this.execEvenly && res.msBeforeNext > 0 && !res.isFirstInDuration) { - let delay = Math.ceil(res.msBeforeNext / (res.remainingPoints + 2)); - if (delay < this.execEvenlyMinDelayMs) { - delay = res.consumedPoints * this.execEvenlyMinDelayMs; - } - - setTimeout(resolve, delay, res); - } else { - resolve(res); - } - } - - _handleError(err, funcName, resolve, reject, key, data = false, options = {}) { - if (!(this.insuranceLimiter instanceof RateLimiterAbstract)) { - reject(err); - } else { - this.insuranceLimiter[funcName](key, data, options) - .then((res) => { - resolve(res); - }) - .catch((res) => { - reject(res); - }); - } - } - - getInMemoryBlockMsBeforeExpire(rlKey) { - if (this.inMemoryBlockOnConsumed > 0) { - return this._inMemoryBlockedKeys.msBeforeExpire(rlKey); - } - - return 0; - } - - get inMemoryBlockOnConsumed() { - return this._inMemoryBlockOnConsumed; - } - - set inMemoryBlockOnConsumed(value) { - this._inMemoryBlockOnConsumed = value ? parseInt(value) : 0; - if (this.inMemoryBlockOnConsumed > 0 && this.points > this.inMemoryBlockOnConsumed) { - throw new Error('inMemoryBlockOnConsumed option must be greater or equal "points" option'); - } - } - - get inMemoryBlockDuration() { - return this._inMemoryBlockDuration; - } - - set inMemoryBlockDuration(value) { - this._inMemoryBlockDuration = value ? parseInt(value) : 0; - if (this.inMemoryBlockDuration > 0 && this.inMemoryBlockOnConsumed === 0) { - throw new Error('inMemoryBlockOnConsumed option must be set up'); - } - } - - get msInMemoryBlockDuration() { - return this._inMemoryBlockDuration * 1000; - } - - get insuranceLimiter() { - return this._insuranceLimiter; - } - - set insuranceLimiter(value) { - if (typeof value !== 'undefined' && !(value instanceof RateLimiterAbstract)) { - throw new Error('insuranceLimiter must be instance of RateLimiterAbstract'); - } - this._insuranceLimiter = value; - if (this._insuranceLimiter) { - this._insuranceLimiter.blockDuration = this.blockDuration; - this._insuranceLimiter.execEvenly = this.execEvenly; - } - } - - /** - * Block any key for secDuration seconds - * - * @param key - * @param secDuration - * @param {Object} options - * - * @return Promise - */ - block(key, secDuration, options = {}) { - const msDuration = secDuration * 1000; - return this._block(this.getKey(key), this.points + 1, msDuration, options); - } - - /** - * Set points by key for any duration - * - * @param key - * @param points - * @param secDuration - * @param {Object} options - * - * @return Promise - */ - set(key, points, secDuration, options = {}) { - const msDuration = (secDuration >= 0 ? secDuration : this.duration) * 1000; - return this._block(this.getKey(key), points, msDuration, options); - } - - /** - * - * @param key - * @param pointsToConsume - * @param {Object} options - * @returns Promise - */ - consume(key, pointsToConsume = 1, options = {}) { - return new Promise((resolve, reject) => { - const rlKey = this.getKey(key); - - const inMemoryBlockMsBeforeExpire = this.getInMemoryBlockMsBeforeExpire(rlKey); - if (inMemoryBlockMsBeforeExpire > 0) { - return reject(new RateLimiterRes(0, inMemoryBlockMsBeforeExpire)); - } - - this._upsert(rlKey, pointsToConsume, this._getKeySecDuration(options) * 1000, false, options) - .then((res) => { - this._afterConsume(resolve, reject, rlKey, pointsToConsume, res); - }) - .catch((err) => { - this._handleError(err, 'consume', resolve, reject, key, pointsToConsume, options); - }); - }); - } - - /** - * - * @param key - * @param points - * @param {Object} options - * @returns Promise - */ - penalty(key, points = 1, options = {}) { - const rlKey = this.getKey(key); - return new Promise((resolve, reject) => { - this._upsert(rlKey, points, this._getKeySecDuration(options) * 1000, false, options) - .then((res) => { - resolve(this._getRateLimiterRes(rlKey, points, res)); - }) - .catch((err) => { - this._handleError(err, 'penalty', resolve, reject, key, points, options); - }); - }); - } - - /** - * - * @param key - * @param points - * @param {Object} options - * @returns Promise - */ - reward(key, points = 1, options = {}) { - const rlKey = this.getKey(key); - return new Promise((resolve, reject) => { - this._upsert(rlKey, -points, this._getKeySecDuration(options) * 1000, false, options) - .then((res) => { - resolve(this._getRateLimiterRes(rlKey, -points, res)); - }) - .catch((err) => { - this._handleError(err, 'reward', resolve, reject, key, points, options); - }); - }); - } - - /** - * - * @param key - * @param {Object} options - * @returns Promise|null - */ - get(key, options = {}) { - const rlKey = this.getKey(key); - return new Promise((resolve, reject) => { - this._get(rlKey, options) - .then((res) => { - if (res === null || typeof res === 'undefined') { - resolve(null); - } else { - resolve(this._getRateLimiterRes(rlKey, 0, res)); - } - }) - .catch((err) => { - this._handleError(err, 'get', resolve, reject, key, options); - }); - }); - } - - /** - * - * @param key - * @param {Object} options - * @returns Promise - */ - delete(key, options = {}) { - const rlKey = this.getKey(key); - return new Promise((resolve, reject) => { - this._delete(rlKey, options) - .then((res) => { - this._inMemoryBlockedKeys.delete(rlKey); - resolve(res); - }) - .catch((err) => { - this._handleError(err, 'delete', resolve, reject, key, options); - }); - }); - } - - /** - * Cleanup keys no-matter expired or not. - */ - deleteInMemoryBlockedAll() { - this._inMemoryBlockedKeys.delete(); - } - - /** - * Get RateLimiterRes object filled depending on storeResult, which specific for exact store - * - * @param rlKey - * @param changedPoints - * @param storeResult - * @private - */ - _getRateLimiterRes(rlKey, changedPoints, storeResult) { // eslint-disable-line no-unused-vars - throw new Error("You have to implement the method '_getRateLimiterRes'!"); - } - - /** - * Block key for this.msBlockDuration milliseconds - * Usually, it just prolongs lifetime of key - * - * @param rlKey - * @param initPoints - * @param msDuration - * @param {Object} options - * - * @return Promise - */ - _block(rlKey, initPoints, msDuration, options = {}) { - return new Promise((resolve, reject) => { - this._upsert(rlKey, initPoints, msDuration, true, options) - .then(() => { - resolve(new RateLimiterRes(0, msDuration > 0 ? msDuration : -1, initPoints)); - }) - .catch((err) => { - this._handleError(err, 'block', resolve, reject, this.parseKey(rlKey), msDuration / 1000, options); - }); - }); - } - - /** - * Have to be implemented in every limiter - * Resolve with raw result from Store OR null if rlKey is not set - * or Reject with error - * - * @param rlKey - * @param {Object} options - * @private - * - * @return Promise - */ - _get(rlKey, options = {}) { // eslint-disable-line no-unused-vars - throw new Error("You have to implement the method '_get'!"); - } - - /** - * Have to be implemented - * Resolve with true OR false if rlKey doesn't exist - * or Reject with error - * - * @param rlKey - * @param {Object} options - * @private - * - * @return Promise - */ - _delete(rlKey, options = {}) { // eslint-disable-line no-unused-vars - throw new Error("You have to implement the method '_delete'!"); - } - - /** - * Have to be implemented - * Resolve with object used for {@link _getRateLimiterRes} to generate {@link RateLimiterRes} - * - * @param {string} rlKey - * @param {number} points - * @param {number} msDuration - * @param {boolean} forceExpire - * @param {Object} options - * @abstract - * - * @return Promise - */ - _upsert(rlKey, points, msDuration, forceExpire = false, options = {}) { - throw new Error("You have to implement the method '_upsert'!"); - } -}; - -var RateLimiterStoreAbstract = /*@__PURE__*/getDefaultExportFromCjs(RateLimiterStoreAbstract_1); - -const assert = createAssert('RateLimit'); -class RateLimiterStore extends RateLimiterStoreAbstract { - constructor(storage, options) { - super(options); - this.storage = storage; - } - /** - * parses raw data from store to RateLimiterRes object. - */ - _getRateLimiterRes(key, changedPoints, result) { - const [consumed = 0, expireTime = 0] = result !== null && result !== void 0 ? result : []; - const msBeforeNext = expireTime > 0 ? Math.max(expireTime - Date.now(), 0) : -1; - const isFirstInDuration = !consumed || changedPoints === consumed; - const currentConsumedPoints = isFirstInDuration ? changedPoints : consumed; - const res = new RateLimiterRes$1(Math.max(0, this.points - currentConsumedPoints), msBeforeNext, isFirstInDuration ? changedPoints : consumed, isFirstInDuration); - return res; - } - async _upsert(key, points, msDuration, forceExpire = false) { - var _a; - key = key.toString(); - const isNeverExpired = msDuration <= 0; - const expireTime = isNeverExpired ? -1 : Date.now() + msDuration; - const newRecord = [points, expireTime]; - if (!forceExpire) { - const [oldPoints = 0, oldExpireTime = 0] = ((_a = (await this.storage.get(key))) !== null && _a !== void 0 ? _a : []); - // if haven't expired yet - if (isNeverExpired || (!isNeverExpired && oldExpireTime > Date.now())) { - newRecord[0] += oldPoints; - } - if (!isNeverExpired && oldExpireTime > Date.now()) { - newRecord[1] = oldExpireTime; - } - } - await this.storage.set(key.toString(), newRecord); - // need to return the record after upsert - return newRecord; - } - /** - * returns raw data by key or null if there is no key or expired. - */ - async _get(key) { - return Promise.resolve(this.storage.get(key.toString())).then(res => { - if (!res) { - return null; - } - const [, expireTime] = res; - // if have expire time and it has expired - if (expireTime > 0 && expireTime <= Date.now()) { - return null; - } - return res; - }); - } - /** - * returns true on deleted, false if key is not found. - */ - async _delete(key) { - try { - await this.storage.remove(key.toString()); - } - catch (_a) { - return false; - } - return true; - } -} -/** - * The method instance modified by rateLimit, its extension method corresponds to the method of creating an instance in rate-limit-flexible, and the key is the key specified by calling rateLimit. - * AlovaServerHook can currently only return unextended method types. It has not been changed to customizable returned extended method types. - */ -class LimitedMethod extends HookedMethod { - constructor(method, limiterKey, limiter) { - super(method, force => this.consume().then(() => method.send(force))); - this.limiter = limiter; - this.keyGetter = isFn(limiterKey) ? () => limiterKey(method) : () => limiterKey; - } - getLimiterKey() { - return this.keyGetter(); - } - /** - * Get RateLimiterRes or null. - */ - get(options) { - return this.limiter.get(this.getLimiterKey(), options); - } - /** - * Set points by key. - */ - set(points, msDuration) { - return this.limiter.set(this.getLimiterKey(), points, msDuration / 1000); - } - /** - * @param points default is 1 - */ - consume(points) { - return this.limiter.consume(this.getLimiterKey(), points); - } - /** - * Increase number of consumed points in current duration. - * @param points penalty points - */ - penalty(points) { - return this.limiter.penalty(this.getLimiterKey(), points); - } - /** - * Decrease number of consumed points in current duration. - * @param points reward points - */ - reward(points) { - return this.limiter.reward(this.getLimiterKey(), points); - } - /** - * Block key for ms. - */ - block(msDuration) { - return this.limiter.block(this.getLimiterKey(), msDuration / 1000); - } - /** - * Reset consumed points. - */ - delete() { - return this.limiter.delete(this.getLimiterKey()); - } -} -function createRateLimiter(options = {}) { - const { points = 4, duration = 4 * 1000, keyPrefix, execEvenly, execEvenlyMinDelayMs, blockDuration } = options; - const limitedMethodWrapper = createServerHook((method, handlerOptions = {}) => { - var _a; - const { key = uuid() } = handlerOptions; - const storage = (_a = options.storage) !== null && _a !== void 0 ? _a : getOptions(method).l2Cache; - assert(!!storage, 'storage is not define'); - const limiter = new RateLimiterStore(storage, { - points, - duration: Math.floor(duration / 1000), - keyPrefix, - execEvenly, - execEvenlyMinDelayMs, - blockDuration: blockDuration ? Math.floor(blockDuration / 1000) : blockDuration, - storeClient: {} - }); - return new LimitedMethod(method, key, limiter); - }); - return limitedMethodWrapper; -} - -const retry = createServerHook((method, options = {}) => { - const { retry = 3, backoff = { delay: 1000 } } = options; - let retryTimes = 0; - return new HookedMethod(method, forceRequest => new Promise((resolve, reject) => { - const sendRequest = () => { - method - .send(forceRequest) - .then(resolve) - .catch(error => { - // when not reach retry times or return true from retry function, it will retry again. - if (isNumber(retry) ? retryTimes < retry : retry(error)) { - retryTimes += 1; - // calculate retry delay time with pram `backoff` and current retry times. - const retryDelay = delayWithBackoff(backoff, retryTimes); - setTimeout(sendRequest, retryDelay); - } - else { - reject(error); - } - }); - }; - sendRequest(); - })); -}); - -export { HookedMethod, createRateLimiter, retry }; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/react.common.cjs b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/react.common.cjs deleted file mode 100644 index 5325a58..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/react.common.cjs +++ /dev/null @@ -1,86 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -'use strict'; - -var shared = require('@alova/shared'); -var react$1 = require('react'); - -const stateToData = (reactState) => (2 in reactState ? reactState[2] : reactState[0]); -const refCurrent = (ref) => ref.current; -const setRef = (ref, newVal) => { - ref.current = newVal; -}; -// the react predefined hooks -var react = { - name: 'React', - create: initialValue => react$1.useState(initialValue), - export: stateToData, - dehydrate: stateToData, - update: (newVal, state) => { - // update value synchronously so that we can access the new value synchronously. - state[2] = newVal; - state[1](newVal); - }, - memorize: fn => { - // use `useCallback` to ensure the same reference, and refer the newest function with `useRef` - const fnRef = react$1.useRef(shared.noop); - setRef(fnRef, fn); - return react$1.useCallback((...args) => refCurrent(fnRef)(...args), []); - }, - ref: initialValue => { - const refObj = react$1.useRef(initialValue); - refCurrent(refObj) === shared.undefinedValue && setRef(refObj, initialValue); - return refObj; - }, - effectRequest({ handler, removeStates, saveStates, immediate, frontStates, watchingStates = [] }) { - // `handler` is called when some states change are detected - const oldStates = react$1.useRef(watchingStates); - react$1.useEffect(() => { - const oldStatesValue = refCurrent(oldStates); - // compare the old and new value, and get the index of changed state - let changedIndex = shared.undefinedValue; - for (const index in watchingStates) { - if (!Object.is(oldStatesValue[index], watchingStates[index])) { - changedIndex = Number(index); - break; - } - } - setRef(oldStates, watchingStates); - if (immediate || shared.isNumber(changedIndex)) { - handler(changedIndex); - } - // remove states when component is unmounted - return removeStates; - }, watchingStates); - // Because react will call usehook again every time it refreshes, the state cache will be invalidated every time - // Therefore, the managed state needs to be updated every time - const needSave = react$1.useRef(false); - react$1.useEffect(() => { - refCurrent(needSave) ? saveStates(frontStates) : setRef(needSave, shared.trueValue); - }); - }, - computed: (getter, depList) => { - const memo = react$1.useMemo(getter, depList); - return [memo, shared.noop]; - }, - watch: (states, callback) => { - // When there is a monitoring state, the state changes and then triggers - const needEmit = react$1.useRef(shared.falseValue); - react$1.useEffect(() => { - needEmit.current ? callback() : (needEmit.current = true); - }, states); - }, - onMounted: callback => { - react$1.useEffect(callback, []); - }, - onUnmounted: callback => { - react$1.useEffect(() => callback, []); - } -}; - -module.exports = react; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/react.esm.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/react.esm.js deleted file mode 100644 index 1a3115d..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/react.esm.js +++ /dev/null @@ -1,84 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -import { noop, undefinedValue, isNumber, falseValue, trueValue } from '@alova/shared'; -import { useState, useRef, useCallback, useEffect, useMemo } from 'react'; - -const stateToData = (reactState) => (2 in reactState ? reactState[2] : reactState[0]); -const refCurrent = (ref) => ref.current; -const setRef = (ref, newVal) => { - ref.current = newVal; -}; -// the react predefined hooks -var react = { - name: 'React', - create: initialValue => useState(initialValue), - export: stateToData, - dehydrate: stateToData, - update: (newVal, state) => { - // update value synchronously so that we can access the new value synchronously. - state[2] = newVal; - state[1](newVal); - }, - memorize: fn => { - // use `useCallback` to ensure the same reference, and refer the newest function with `useRef` - const fnRef = useRef(noop); - setRef(fnRef, fn); - return useCallback((...args) => refCurrent(fnRef)(...args), []); - }, - ref: initialValue => { - const refObj = useRef(initialValue); - refCurrent(refObj) === undefinedValue && setRef(refObj, initialValue); - return refObj; - }, - effectRequest({ handler, removeStates, saveStates, immediate, frontStates, watchingStates = [] }) { - // `handler` is called when some states change are detected - const oldStates = useRef(watchingStates); - useEffect(() => { - const oldStatesValue = refCurrent(oldStates); - // compare the old and new value, and get the index of changed state - let changedIndex = undefinedValue; - for (const index in watchingStates) { - if (!Object.is(oldStatesValue[index], watchingStates[index])) { - changedIndex = Number(index); - break; - } - } - setRef(oldStates, watchingStates); - if (immediate || isNumber(changedIndex)) { - handler(changedIndex); - } - // remove states when component is unmounted - return removeStates; - }, watchingStates); - // Because react will call usehook again every time it refreshes, the state cache will be invalidated every time - // Therefore, the managed state needs to be updated every time - const needSave = useRef(false); - useEffect(() => { - refCurrent(needSave) ? saveStates(frontStates) : setRef(needSave, trueValue); - }); - }, - computed: (getter, depList) => { - const memo = useMemo(getter, depList); - return [memo, noop]; - }, - watch: (states, callback) => { - // When there is a monitoring state, the state changes and then triggers - const needEmit = useRef(falseValue); - useEffect(() => { - needEmit.current ? callback() : (needEmit.current = true); - }, states); - }, - onMounted: callback => { - useEffect(callback, []); - }, - onUnmounted: callback => { - useEffect(() => callback, []); - } -}; - -export { react as default }; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/react.umd.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/react.umd.js deleted file mode 100644 index d25aada..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/react.umd.js +++ /dev/null @@ -1,117 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) : - typeof define === 'function' && define.amd ? define(['react'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.reactHook = factory(global.React)); -})(this, (function (react$1) { 'use strict'; - - /** - * @alova/shared 1.1.2 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) - */ - - const undefStr = 'undefined'; - const undefinedValue = undefined; - const trueValue = true; - const falseValue = false; - const typeOf = (arg) => typeof arg; - // Whether it is running on the server side, node and bun are judged by process, and deno is judged by Deno. - // Some frameworks (such as Alipay and uniapp) will inject the process object as a global variable. - // Therefore, the process.cwd function unique to the server is used as the basis for judgment. - typeof window === undefStr && - (typeof process !== undefStr ? typeof process.cwd === 'function' : typeof Deno !== undefStr); - - /** - * Empty function for compatibility processing - */ - const noop = () => { }; - /** - * Determine whether the parameter is a number any parameter - * @returns Whether the parameter is a number - */ - const isNumber = (arg) => typeOf(arg) === 'number' && !Number.isNaN(arg); - - const stateToData = (reactState) => (2 in reactState ? reactState[2] : reactState[0]); - const refCurrent = (ref) => ref.current; - const setRef = (ref, newVal) => { - ref.current = newVal; - }; - // the react predefined hooks - var react = { - name: 'React', - create: initialValue => react$1.useState(initialValue), - export: stateToData, - dehydrate: stateToData, - update: (newVal, state) => { - // update value synchronously so that we can access the new value synchronously. - state[2] = newVal; - state[1](newVal); - }, - memorize: fn => { - // use `useCallback` to ensure the same reference, and refer the newest function with `useRef` - const fnRef = react$1.useRef(noop); - setRef(fnRef, fn); - return react$1.useCallback((...args) => refCurrent(fnRef)(...args), []); - }, - ref: initialValue => { - const refObj = react$1.useRef(initialValue); - refCurrent(refObj) === undefinedValue && setRef(refObj, initialValue); - return refObj; - }, - effectRequest({ handler, removeStates, saveStates, immediate, frontStates, watchingStates = [] }) { - // `handler` is called when some states change are detected - const oldStates = react$1.useRef(watchingStates); - react$1.useEffect(() => { - const oldStatesValue = refCurrent(oldStates); - // compare the old and new value, and get the index of changed state - let changedIndex = undefinedValue; - for (const index in watchingStates) { - if (!Object.is(oldStatesValue[index], watchingStates[index])) { - changedIndex = Number(index); - break; - } - } - setRef(oldStates, watchingStates); - if (immediate || isNumber(changedIndex)) { - handler(changedIndex); - } - // remove states when component is unmounted - return removeStates; - }, watchingStates); - // Because react will call usehook again every time it refreshes, the state cache will be invalidated every time - // Therefore, the managed state needs to be updated every time - const needSave = react$1.useRef(false); - react$1.useEffect(() => { - refCurrent(needSave) ? saveStates(frontStates) : setRef(needSave, trueValue); - }); - }, - computed: (getter, depList) => { - const memo = react$1.useMemo(getter, depList); - return [memo, noop]; - }, - watch: (states, callback) => { - // When there is a monitoring state, the state changes and then triggers - const needEmit = react$1.useRef(falseValue); - react$1.useEffect(() => { - needEmit.current ? callback() : (needEmit.current = true); - }, states); - }, - onMounted: callback => { - react$1.useEffect(callback, []); - }, - onUnmounted: callback => { - react$1.useEffect(() => callback, []); - } - }; - - return react; - -})); diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/react.umd.min.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/react.umd.min.js deleted file mode 100644 index d05463c..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/react.umd.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).reactHook=t(e.React)}(this,(function(e){"use strict";const t="undefined",n=void 0;typeof window===t&&typeof process!==t&&process.cwd;const o=()=>{},s=e=>2 in e?e[2]:e[0],r=e=>e.current,u=(e,t)=>{e.current=t};return{name:"React",create:t=>e.useState(t),export:s,dehydrate:s,update:(e,t)=>{t[2]=e,t[1](e)},memorize:t=>{const n=e.useRef(o);return u(n,t),e.useCallback(((...e)=>r(n)(...e)),[])},ref:t=>{const o=e.useRef(t);return r(o)===n&&u(o,t),o},effectRequest({handler:t,removeStates:o,saveStates:s,immediate:f,frontStates:c,watchingStates:a=[]}){const i=e.useRef(a);e.useEffect((()=>{const e=r(i);let s=n;for(const t in a)if(!Object.is(e[t],a[t])){s=Number(t);break}var c;return u(i,a),!f&&("number"!==(e=>typeof e)(c=s)||Number.isNaN(c))||t(s),o}),a);const d=e.useRef(!1);e.useEffect((()=>{r(d)?s(c):u(d,true)}))},computed:(t,n)=>[e.useMemo(t,n),o],watch:(t,n)=>{const o=e.useRef(false);e.useEffect((()=>{o.current?n():o.current=!0}),t)},onMounted:t=>{e.useEffect(t,[])},onUnmounted:t=>{e.useEffect((()=>t),[])}}})); diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/solid.common.cjs b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/solid.common.cjs deleted file mode 100644 index 9f28937..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/solid.common.cjs +++ /dev/null @@ -1,48 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -'use strict'; - -var shared = require('@alova/shared'); -var solidJs = require('solid-js'); - -// solid hooks predefined -var solid = { - name: 'Solid', - create: data => solidJs.createSignal(data), - export: state => state[0], - dehydrate: state => state[0](), - update: (newVal, state) => { - state[1](newVal); - }, - effectRequest: ({ handler, removeStates, immediate, watchingStates = [] }) => { - // remove states when component unmounted - solidJs.onCleanup(removeStates); - immediate && handler(); - shared.forEach(watchingStates, (state, i) => { - solidJs.createEffect(solidJs.on(state, () => { - handler(i); - }, { defer: true })); - }); - }, - computed: getter => [solidJs.createMemo(getter), shared.noop], - watch: (states, callback) => { - const curStates = Array.isArray(states) ? states : [states]; - const syncRunner = shared.createSyncOnceRunner(); - solidJs.createEffect(solidJs.on(curStates.map(state => state), () => syncRunner(() => { - callback(); - }), { defer: true })); - }, - onMounted: callback => { - solidJs.onMount(callback); - }, - onUnmounted: callback => { - solidJs.onCleanup(callback); - } -}; - -module.exports = solid; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/solid.esm.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/solid.esm.js deleted file mode 100644 index da88a31..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/solid.esm.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -import { forEach, noop, createSyncOnceRunner } from '@alova/shared'; -import { createSignal, onCleanup, createEffect, on, createMemo, onMount } from 'solid-js'; - -// solid hooks predefined -var solid = { - name: 'Solid', - create: data => createSignal(data), - export: state => state[0], - dehydrate: state => state[0](), - update: (newVal, state) => { - state[1](newVal); - }, - effectRequest: ({ handler, removeStates, immediate, watchingStates = [] }) => { - // remove states when component unmounted - onCleanup(removeStates); - immediate && handler(); - forEach(watchingStates, (state, i) => { - createEffect(on(state, () => { - handler(i); - }, { defer: true })); - }); - }, - computed: getter => [createMemo(getter), noop], - watch: (states, callback) => { - const curStates = Array.isArray(states) ? states : [states]; - const syncRunner = createSyncOnceRunner(); - createEffect(on(curStates.map(state => state), () => syncRunner(() => { - callback(); - }), { defer: true })); - }, - onMounted: callback => { - onMount(callback); - }, - onUnmounted: callback => { - onCleanup(callback); - } -}; - -export { solid as default }; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/solid.umd.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/solid.umd.js deleted file mode 100644 index e9088f3..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/solid.umd.js +++ /dev/null @@ -1,51 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@alova/shared'), require('solid-js')) : - typeof define === 'function' && define.amd ? define(['@alova/shared', 'solid-js'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.solidHook = factory(global.shared, global.Solid)); -})(this, (function (shared, solidJs) { 'use strict'; - - // solid hooks predefined - var solid = { - name: 'Solid', - create: data => solidJs.createSignal(data), - export: state => state[0], - dehydrate: state => state[0](), - update: (newVal, state) => { - state[1](newVal); - }, - effectRequest: ({ handler, removeStates, immediate, watchingStates = [] }) => { - // remove states when component unmounted - solidJs.onCleanup(removeStates); - immediate && handler(); - shared.forEach(watchingStates, (state, i) => { - solidJs.createEffect(solidJs.on(state, () => { - handler(i); - }, { defer: true })); - }); - }, - computed: getter => [solidJs.createMemo(getter), shared.noop], - watch: (states, callback) => { - const curStates = Array.isArray(states) ? states : [states]; - const syncRunner = shared.createSyncOnceRunner(); - solidJs.createEffect(solidJs.on(curStates.map(state => state), () => syncRunner(() => { - callback(); - }), { defer: true })); - }, - onMounted: callback => { - solidJs.onMount(callback); - }, - onUnmounted: callback => { - solidJs.onCleanup(callback); - } - }; - - return solid; - -})); diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/solid.umd.min.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/solid.umd.min.js deleted file mode 100644 index de14769..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/solid.umd.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?module.exports=o(require("@alova/shared"),require("solid-js")):"function"==typeof define&&define.amd?define(["@alova/shared","solid-js"],o):(e="undefined"!=typeof globalThis?globalThis:e||self).solidHook=o(e.shared,e.Solid)}(this,(function(e,o){"use strict";return{name:"Solid",create:e=>o.createSignal(e),export:e=>e[0],dehydrate:e=>e[0](),update:(e,o)=>{o[1](e)},effectRequest:({handler:t,removeStates:n,immediate:a,watchingStates:r=[]})=>{o.onCleanup(n),a&&t(),e.forEach(r,((e,n)=>{o.createEffect(o.on(e,(()=>{t(n)}),{defer:!0}))}))},computed:t=>[o.createMemo(t),e.noop],watch:(t,n)=>{const a=Array.isArray(t)?t:[t],r=e.createSyncOnceRunner();o.createEffect(o.on(a.map((e=>e)),(()=>r((()=>{n()}))),{defer:!0}))},onMounted:e=>{o.onMount(e)},onUnmounted:e=>{o.onCleanup(e)}}})); diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/svelte.common.cjs b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/svelte.common.cjs deleted file mode 100644 index 0b517d1..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/svelte.common.cjs +++ /dev/null @@ -1,63 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -'use strict'; - -var shared = require('@alova/shared'); -var svelte$1 = require('svelte'); -var store = require('svelte/store'); - -// the svelte predefined hooks -var svelte = { - name: 'Svelte', - create: data => store.writable(data), - dehydrate: state => { - let raw; - // The function will be executed once when subscribing, and the unsubscribe function will be called immediately after the value is obtained - state.subscribe(value => { - raw = value; - })(); - return raw; - }, - update: (newVal, state) => { - state.set(newVal); - }, - effectRequest({ handler, removeStates, immediate, watchingStates }) { - // Remove the corresponding state when the component is unmounted - svelte$1.onDestroy(removeStates); - svelte$1.onMount(() => { - immediate && handler(); - }); - shared.forEach(watchingStates || [], (state, i) => { - let needEmit = shared.falseValue; - state.subscribe(() => { - // Svelte's `writable` will trigger once by default, so when immediate is false, you need to filter out the first trigger call - needEmit ? handler(i) : (needEmit = shared.trueValue); - }); - }); - }, - computed: (getter, depList) => store.derived(depList, getter), - watch: (states, callback) => { - let needEmit = shared.falseValue; - const syncRunner = shared.createSyncOnceRunner(); - states.forEach(state => { - state.subscribe(() => { - syncRunner(() => { - needEmit ? callback() : (needEmit = shared.trueValue); - }); - }); - }); - }, - onMounted: callback => { - svelte$1.onMount(callback); - }, - onUnmounted: callback => { - svelte$1.onDestroy(callback); - } -}; - -module.exports = svelte; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/svelte.esm.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/svelte.esm.js deleted file mode 100644 index ecb350c..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/svelte.esm.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -import { forEach, trueValue, createSyncOnceRunner, falseValue } from '@alova/shared'; -import { onDestroy, onMount } from 'svelte'; -import { writable, derived } from 'svelte/store'; - -// the svelte predefined hooks -var svelte = { - name: 'Svelte', - create: data => writable(data), - dehydrate: state => { - let raw; - // The function will be executed once when subscribing, and the unsubscribe function will be called immediately after the value is obtained - state.subscribe(value => { - raw = value; - })(); - return raw; - }, - update: (newVal, state) => { - state.set(newVal); - }, - effectRequest({ handler, removeStates, immediate, watchingStates }) { - // Remove the corresponding state when the component is unmounted - onDestroy(removeStates); - onMount(() => { - immediate && handler(); - }); - forEach(watchingStates || [], (state, i) => { - let needEmit = falseValue; - state.subscribe(() => { - // Svelte's `writable` will trigger once by default, so when immediate is false, you need to filter out the first trigger call - needEmit ? handler(i) : (needEmit = trueValue); - }); - }); - }, - computed: (getter, depList) => derived(depList, getter), - watch: (states, callback) => { - let needEmit = falseValue; - const syncRunner = createSyncOnceRunner(); - states.forEach(state => { - state.subscribe(() => { - syncRunner(() => { - needEmit ? callback() : (needEmit = trueValue); - }); - }); - }); - }, - onMounted: callback => { - onMount(callback); - }, - onUnmounted: callback => { - onDestroy(callback); - } -}; - -export { svelte as default }; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue-demi.common.cjs b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue-demi.common.cjs deleted file mode 100644 index be7308f..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue-demi.common.cjs +++ /dev/null @@ -1,47 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -'use strict'; - -var shared = require('@alova/shared'); -var vueDemi$1 = require('vue-demi'); - -// Vue’s predefined hooks -var vueDemi = { - name: 'VueDemi', - create: data => vueDemi$1.ref(data), - dehydrate: state => state.value, - update: (newVal, state) => { - state.value = newVal; - }, - effectRequest({ handler, removeStates, immediate, watchingStates }) { - // When used inside a component, the corresponding state is removed when the component is unloaded. - if (vueDemi$1.getCurrentInstance()) { - vueDemi$1.onUnmounted(removeStates); - } - immediate && handler(); - shared.forEach(watchingStates || [], (state, i) => { - vueDemi$1.watch(state, () => { - handler(i); - }, { deep: shared.trueValue }); - }); - }, - computed: getter => vueDemi$1.computed(getter), - watch: (states, callback) => { - vueDemi$1.watch(states, callback, { - deep: shared.trueValue - }); - }, - onMounted: callback => { - vueDemi$1.onMounted(callback); - }, - onUnmounted: callback => { - vueDemi$1.onUnmounted(callback); - } -}; - -module.exports = vueDemi; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue-demi.esm.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue-demi.esm.js deleted file mode 100644 index 2fa9609..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue-demi.esm.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -import { forEach, trueValue } from '@alova/shared'; -import { ref, getCurrentInstance, onUnmounted, watch, computed, onMounted } from 'vue-demi'; - -// Vue’s predefined hooks -var vueDemi = { - name: 'VueDemi', - create: data => ref(data), - dehydrate: state => state.value, - update: (newVal, state) => { - state.value = newVal; - }, - effectRequest({ handler, removeStates, immediate, watchingStates }) { - // When used inside a component, the corresponding state is removed when the component is unloaded. - if (getCurrentInstance()) { - onUnmounted(removeStates); - } - immediate && handler(); - forEach(watchingStates || [], (state, i) => { - watch(state, () => { - handler(i); - }, { deep: trueValue }); - }); - }, - computed: getter => computed(getter), - watch: (states, callback) => { - watch(states, callback, { - deep: trueValue - }); - }, - onMounted: callback => { - onMounted(callback); - }, - onUnmounted: callback => { - onUnmounted(callback); - } -}; - -export { vueDemi as default }; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue-demi.umd.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue-demi.umd.js deleted file mode 100644 index 9395a2c..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue-demi.umd.js +++ /dev/null @@ -1,66 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('vue-demi')) : - typeof define === 'function' && define.amd ? define(['vue-demi'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.vueHook = factory(global.Vue)); -})(this, (function (vueDemi$1) { 'use strict'; - - /** - * @alova/shared 1.1.2 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) - */ - - const undefStr = 'undefined'; - const trueValue = true; - const forEach = (ary, fn) => ary.forEach(fn); - // Whether it is running on the server side, node and bun are judged by process, and deno is judged by Deno. - // Some frameworks (such as Alipay and uniapp) will inject the process object as a global variable. - // Therefore, the process.cwd function unique to the server is used as the basis for judgment. - typeof window === undefStr && - (typeof process !== undefStr ? typeof process.cwd === 'function' : typeof Deno !== undefStr); - - // Vue’s predefined hooks - var vueDemi = { - name: 'VueDemi', - create: data => vueDemi$1.ref(data), - dehydrate: state => state.value, - update: (newVal, state) => { - state.value = newVal; - }, - effectRequest({ handler, removeStates, immediate, watchingStates }) { - // When used inside a component, the corresponding state is removed when the component is unloaded. - if (vueDemi$1.getCurrentInstance()) { - vueDemi$1.onUnmounted(removeStates); - } - immediate && handler(); - forEach(watchingStates || [], (state, i) => { - vueDemi$1.watch(state, () => { - handler(i); - }, { deep: trueValue }); - }); - }, - computed: getter => vueDemi$1.computed(getter), - watch: (states, callback) => { - vueDemi$1.watch(states, callback, { - deep: trueValue - }); - }, - onMounted: callback => { - vueDemi$1.onMounted(callback); - }, - onUnmounted: callback => { - vueDemi$1.onUnmounted(callback); - } - }; - - return vueDemi; - -})); diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue-demi.umd.min.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue-demi.umd.min.js deleted file mode 100644 index 1334642..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue-demi.umd.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("vue-demi")):"function"==typeof define&&define.amd?define(["vue-demi"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).vueHook=t(e.Vue)}(this,(function(e){"use strict";const t="undefined",n=!0;return typeof window===t&&typeof process!==t&&process.cwd,{name:"VueDemi",create:t=>e.ref(t),dehydrate:e=>e.value,update:(e,t)=>{t.value=e},effectRequest({handler:t,removeStates:o,immediate:d,watchingStates:u}){var i;e.getCurrentInstance()&&e.onUnmounted(o),d&&t(),i=(o,d)=>{e.watch(o,(()=>{t(d)}),{deep:n})},(u||[]).forEach(i)},computed:t=>e.computed(t),watch:(t,o)=>{e.watch(t,o,{deep:n})},onMounted:t=>{e.onMounted(t)},onUnmounted:t=>{e.onUnmounted(t)}}})); diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue.common.cjs b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue.common.cjs deleted file mode 100644 index 2b0b24b..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue.common.cjs +++ /dev/null @@ -1,52 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -'use strict'; - -var shared = require('@alova/shared'); -var vue$1 = require('vue'); - -// the vue's predefined hooks -var vue = { - name: 'Vue', - create: data => vue$1.ref(data), - dehydrate: state => state.value, - update: (newVal, state) => { - state.value = newVal; - }, - effectRequest({ handler, removeStates, immediate, watchingStates }) { - // if call in component, remove current hook states when unmounting component - if (vue$1.getCurrentInstance()) { - vue$1.onUnmounted(removeStates); - } - immediate && handler(); - shared.forEach(watchingStates || [], (state, i) => { - vue$1.watch(state, () => { - handler(i); - }, { deep: shared.trueValue }); - }); - }, - computed: getter => vue$1.computed(getter), - watch: (states, callback) => { - vue$1.watch(states, callback, { - deep: shared.trueValue - }); - }, - onMounted: callback => { - if (vue$1.getCurrentInstance()) { - vue$1.onMounted(callback); - } - else { - shared.setTimeoutFn(callback, 10); - } - }, - onUnmounted: callback => { - vue$1.getCurrentInstance() && vue$1.onUnmounted(callback); - } -}; - -module.exports = vue; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue.esm.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue.esm.js deleted file mode 100644 index e4b830b..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue.esm.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -import { forEach, trueValue, setTimeoutFn } from '@alova/shared'; -import { ref, getCurrentInstance, onUnmounted, watch, computed, onMounted } from 'vue'; - -// the vue's predefined hooks -var vue = { - name: 'Vue', - create: data => ref(data), - dehydrate: state => state.value, - update: (newVal, state) => { - state.value = newVal; - }, - effectRequest({ handler, removeStates, immediate, watchingStates }) { - // if call in component, remove current hook states when unmounting component - if (getCurrentInstance()) { - onUnmounted(removeStates); - } - immediate && handler(); - forEach(watchingStates || [], (state, i) => { - watch(state, () => { - handler(i); - }, { deep: trueValue }); - }); - }, - computed: getter => computed(getter), - watch: (states, callback) => { - watch(states, callback, { - deep: trueValue - }); - }, - onMounted: callback => { - if (getCurrentInstance()) { - onMounted(callback); - } - else { - setTimeoutFn(callback, 10); - } - }, - onUnmounted: callback => { - getCurrentInstance() && onUnmounted(callback); - } -}; - -export { vue as default }; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue.umd.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue.umd.js deleted file mode 100644 index a734d4c..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue.umd.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * @alova/client 2.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('vue')) : - typeof define === 'function' && define.amd ? define(['vue'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.vueHook = factory(global.Vue)); -})(this, (function (vue$1) { 'use strict'; - - /** - * @alova/shared 1.1.2 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott Hu. All Rights Reserved - * Licensed under MIT (https://github.com/alovajs/alova/blob/main/LICENSE) - */ - - const undefStr = 'undefined'; - const trueValue = true; - const setTimeoutFn = (fn, delay = 0) => setTimeout(fn, delay); - const forEach = (ary, fn) => ary.forEach(fn); - // Whether it is running on the server side, node and bun are judged by process, and deno is judged by Deno. - // Some frameworks (such as Alipay and uniapp) will inject the process object as a global variable. - // Therefore, the process.cwd function unique to the server is used as the basis for judgment. - typeof window === undefStr && - (typeof process !== undefStr ? typeof process.cwd === 'function' : typeof Deno !== undefStr); - - // the vue's predefined hooks - var vue = { - name: 'Vue', - create: data => vue$1.ref(data), - dehydrate: state => state.value, - update: (newVal, state) => { - state.value = newVal; - }, - effectRequest({ handler, removeStates, immediate, watchingStates }) { - // if call in component, remove current hook states when unmounting component - if (vue$1.getCurrentInstance()) { - vue$1.onUnmounted(removeStates); - } - immediate && handler(); - forEach(watchingStates || [], (state, i) => { - vue$1.watch(state, () => { - handler(i); - }, { deep: trueValue }); - }); - }, - computed: getter => vue$1.computed(getter), - watch: (states, callback) => { - vue$1.watch(states, callback, { - deep: trueValue - }); - }, - onMounted: callback => { - if (vue$1.getCurrentInstance()) { - vue$1.onMounted(callback); - } - else { - setTimeoutFn(callback, 10); - } - }, - onUnmounted: callback => { - vue$1.getCurrentInstance() && vue$1.onUnmounted(callback); - } - }; - - return vue; - -})); diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue.umd.min.js b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue.umd.min.js deleted file mode 100644 index 35bc0c2..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/dist/stateshook/vue.umd.min.js +++ /dev/null @@ -1 +0,0 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("vue")):"function"==typeof define&&define.amd?define(["vue"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).vueHook=t(e.Vue)}(this,(function(e){"use strict";const t="undefined",n=!0;return typeof window===t&&typeof process!==t&&process.cwd,{name:"Vue",create:t=>e.ref(t),dehydrate:e=>e.value,update:(e,t)=>{t.value=e},effectRequest({handler:t,removeStates:o,immediate:u,watchingStates:d}){var a;e.getCurrentInstance()&&e.onUnmounted(o),u&&t(),a=(o,u)=>{e.watch(o,(()=>{t(u)}),{deep:n})},(d||[]).forEach(a)},computed:t=>e.computed(t),watch:(t,o)=>{e.watch(t,o,{deep:n})},onMounted:t=>{e.getCurrentInstance()?e.onMounted(t):((e,t=0)=>{setTimeout(e,t)})(t,10)},onUnmounted:t=>{e.getCurrentInstance()&&e.onUnmounted(t)}}})); diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/package.json b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/package.json deleted file mode 100644 index f74491e..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/package.json +++ /dev/null @@ -1,153 +0,0 @@ -{ - "name": "alova", - "version": "3.2.10", - "description": "Request strategy library for MVVM libraries such as Vue.js, React.js and Svelte.js", - "main": "dist/alova.common.cjs", - "module": "dist/alova.esm.js", - "types": "typings/index.d.ts", - "type": "module", - "sideEffects": false, - "homepage": "https://alova.js.org", - "keywords": [ - "react", - "hooks", - "xmlhttprequest", - "vuejs", - "typescript", - "vue", - "reactjs", - "svelte", - "axios", - "request", - "fetch-api", - "vue3", - "react-hooks", - "superagent", - "alova" - ], - "jsdelivr": "dist/alova.umd.min.js", - "unpkg": "dist/alova.umd.min.js", - "author": "Scott Hu", - "license": "MIT", - "repository": { - "type": "git", - "url": "https://github.com/alovajs/alova.git" - }, - "bugs": { - "url": "https://github.com/alovajs/alova/issues" - }, - "files": [ - "dist", - "typings" - ], - "engines": { - "node": ">= 18.0.0" - }, - "exports": { - ".": { - "types": "./typings/index.d.ts", - "require": "./dist/alova.common.cjs", - "default": "./dist/alova.esm.js" - }, - "./client": { - "types": "./typings/clienthook/index.d.ts", - "require": "./dist/clienthook/index.common.cjs", - "default": "./dist/clienthook/index.esm.js" - }, - "./server": { - "types": "./typings/serverhook.d.ts", - "require": "./dist/serverhook/index.common.cjs", - "default": "./dist/serverhook/index.esm.js" - }, - "./fetch": { - "types": { - "require": "./typings/fetch.d.cts", - "default": "./typings/fetch.d.ts" - }, - "require": "./dist/adapter/fetch.common.cjs", - "default": "./dist/adapter/fetch.esm.js" - }, - "./vue": { - "types": "./typings/stateshook/vue.d.ts", - "require": "./dist/stateshook/vue.common.cjs", - "default": "./dist/stateshook/vue.esm.js" - }, - "./vue-demi": { - "types": "./typings/stateshook/vue-demi.d.ts", - "require": "./dist/stateshook/vue-demi.common.cjs", - "default": "./dist/stateshook/vue-demi.esm.js" - }, - "./react": { - "types": "./typings/stateshook/react.d.ts", - "require": "./dist/stateshook/react.common.cjs", - "default": "./dist/stateshook/react.esm.js" - }, - "./svelte": { - "types": "./typings/stateshook/svelte.d.ts", - "require": "./dist/stateshook/svelte.common.cjs", - "default": "./dist/stateshook/svelte.esm.js" - }, - "./solid": { - "types": "./typings/stateshook/solid.d.ts", - "require": "./dist/stateshook/solid.common.cjs", - "default": "./dist/stateshook/solid.esm.js" - } - }, - "typesVersions": { - "*": { - "client": [ - "typings/clienthook/index.d.ts" - ], - "server": [ - "typings/serverhook.d.ts" - ], - "fetch": [ - "typings/fetch.d.ts" - ], - "vue": [ - "typings/stateshook/vue.d.ts" - ], - "vue-demi": [ - "typings/stateshook/vue-demi.d.ts" - ], - "react": [ - "typings/stateshook/react.d.ts" - ], - "svelte": [ - "typings/stateshook/svelte.d.ts" - ], - "solid": [ - "typings/stateshook/solid.d.ts" - ] - } - }, - "dependencies": { - "rate-limiter-flexible": "^5.0.3", - "@alova/shared": "1.1.2" - }, - "devDependencies": { - "@alova/scripts": "1.1.1" - }, - "config": { - "commitizen": { - "path": "./node_modules/cz-conventional-changelog" - } - }, - "scripts": { - "clean": "rimraf ./dist", - "test": "vitest run", - "test:coverage": "vitest run --coverage", - "release": "semantic-release", - "lint": "eslint --ext .ts,.js src", - "lint:fix": "pnpm lint --fix", - "build:core": "alova-scripts build core", - "build:fetch": "alova-scripts build fetch", - "build:client": "pnpm --filter=@alova/client run build", - "build:server": "pnpm --filter=@alova/server run build", - "build": "pnpm clean && alova-scripts build && pnpm build:client && pnpm build:server", - "coveralls": "pnpm test:coverage && coveralls < coverage/lcov.info", - "changelog": "conventional-changelog -p angular -u -i CHANGELOG.md -s -r 0", - "commit": "git-cz && git push", - "format": "prettier . --write" - } -} \ No newline at end of file diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/additional.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/additional.d.ts deleted file mode 100644 index 3ef8b28..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/additional.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -declare module 'rate-limiter-flexible/lib/RateLimiterStoreAbstract.js' { - import { RateLimiterStoreAbstract } from 'rate-limiter-flexible'; - - export default RateLimiterStoreAbstract; -} diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/general.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/general.d.ts deleted file mode 100644 index 0915b17..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/general.d.ts +++ /dev/null @@ -1,282 +0,0 @@ -import type { EventManager, FrameworkReadableState, FrameworkState, IsUnknown } from '@alova/shared'; -import { - AlovaGenerics, - FetchRequestState, - FrontRequestState, - MergedStatesMap, - Method, - Progress, - ReferingObject, - StatesExport -} from 'alova'; -import { ReactHookExportType } from '../stateshook/react'; -import { SolidHookExportType } from '../stateshook/solid'; -import { SvelteHookExportType } from '../stateshook/svelte'; -import { VueHookExportType } from '../stateshook/vue'; -import { VueDemiHookExportType } from '../stateshook/vue-demi'; - -export interface StateMap { - Vue: VueHookExportType; - Solid: SolidHookExportType; - React: ReactHookExportType; - Svelte: SvelteHookExportType; - VueDemi: VueDemiHookExportType; -} -/** - * alova base event - */ -export interface AlovaEvent { - /** - * params from send function - */ - args: [...Args, ...any[]]; - /** - * current method instance - */ - method: Method; -} -/** - * success event object - */ -export interface AlovaSuccessEvent extends AlovaEvent { - /** Whether data from cache */ - fromCache: boolean; - data: AG['Responded']; -} -/** error event object */ -export interface AlovaErrorEvent extends AlovaEvent { - error: any; -} -/** completion event object */ -export interface AlovaCompleteEvent extends AlovaEvent { - /** response status */ - status: 'success' | 'error'; - /** Whether the data from the cache, when the status is error, from cache is always false */ - fromCache: boolean; - data?: AG['Responded']; - error?: any; -} - -/** - * Define the type in a way that supports React and Vue. Other types will be needed later and then change on this basis. - * Use the characteristics of different libraries as parent classes for judgment - */ -export type ExportedState> = SE['name'] extends keyof StateMap - ? StateMap[SE['name']]['StateExport'] - : Responded; -export type ExportedComputed> = SE['name'] extends keyof StateMap - ? StateMap[SE['name']]['ComputedExport'] - : Responded; - -export type StateUpdater, SE extends StatesExport> = (newStates: { - [K in keyof ExportedStates]?: ExportedStates[K] extends ExportedState | ExportedComputed - ? R - : ExportedStates[K]; -}) => void; - -export type AlovaMethodHandler = ( - ...args: Args -) => Method; -export type SuccessHandler = (event: AlovaSuccessEvent) => void; -export type ErrorHandler = (event: AlovaErrorEvent) => void; -export type CompleteHandler = ( - event: AlovaCompleteEvent -) => void; - -/** common hook configuration */ -export interface UseHookConfig { - /** - * force request - * @default false - */ - force?: boolean | ((event: AlovaEvent) => boolean); - - /** - * refering object that sharing some value with this object. - */ - __referingObj?: ReferingObject; - - /** - * other attributes - */ - [attr: string]: any; -} - -export interface AlovaMiddlewareContext { - /** current method instance */ - method: Method; - - /** - * cache data, only has value when hit cache - */ - cachedResponse: AG['Responded'] | undefined; - - /** the config of current use hook */ - config: any; - - /** abort request */ - abort: UseHookExposure['abort']; -} - -/** next function of middleware */ -export interface MiddlewareNextGuardConfig { - force?: UseHookConfig['force']; - method?: Method; -} - -/** - * context parameters of useRequest and useWatcher middleware - */ -export interface AlovaFrontMiddlewareContext - extends AlovaMiddlewareContext { - /** handler to send request */ - send: SendHandler; - - /** args response processing callback parameters, which are passed in by send of use hooks */ - args: [...Args, ...any[]]; - - /** state proxies set */ - proxyStates: FrontRequestState< - FrameworkState, - FrameworkState, - FrameworkState, - FrameworkState, - FrameworkState - >; - - /** - * custom control the state `loading` and doesn't toggle `loading` internally any more. - * call it with param `false` to cancel controlling. - * @JOU-amjs - * @param control whether to control loading, default is `true` - */ - controlLoading: (control?: boolean) => void; - - /** - * pass custom data - */ - [attr: string]: any; -} - -/** - * alova useRequest/useWatcher middleware - */ -export interface AlovaFrontMiddleware { - (context: AlovaFrontMiddlewareContext, next: AlovaGuardNext): any; -} - -/** - * the context param of middleware in useFetcher - */ -export interface AlovaFetcherMiddlewareContext - extends AlovaMiddlewareContext { - /** fetch data */ - fetch(method: Method, ...args: [...Args, ...any[]]): Promise; - - /** args response processing callback parameters, which are passed in by useFetcher’s fetch */ - args: [...Args, ...any[]]; - - /** state proxies set */ - proxyStates: FetchRequestState< - FrameworkState, - FrameworkState, - FrameworkState, - FrameworkState - >; - - /** - * custom control the state `loading` and doesn't toggle `loading` internally any more. - * call it with param `false` to cancel controlling. - * @JOU-amjs - * @param control whether to control loading, default is `true` - */ - controlLoading: (control?: boolean) => void; - - /** - * pass custom data - */ - [attr: string]: any; -} - -/** - * alova useFetcher middleware - */ -export interface AlovaFetcherMiddleware { - (context: AlovaFetcherMiddlewareContext, next: AlovaGuardNext): any; -} - -export type ProxyStateGetter> = ( - key: K -) => HookExportedStates[K] extends ExportedState - ? FrameworkState - : HookExportedStates[K] extends ExportedComputed - ? FrameworkReadableState - : never; - -export interface AlovaGuardNext { - (guardNextConfig?: MiddlewareNextGuardConfig): Promise; -} - -export type SendHandler = (...args: [...Args, ...any[]]) => Promise; -export interface UseHookExportedState - extends FrontRequestState< - ExportedState, - ExportedState, - ExportedState, - ExportedState, - ExportedState - > {} -export interface UseHookExposure< - AG extends AlovaGenerics = AlovaGenerics, - Args extends any[] = any[], - SelfType = unknown -> extends UseHookExportedState { - abort: () => void; - update: StateUpdater, AG['StatesExport']>; - send: SendHandler; - onSuccess(handler: SuccessHandler): IsUnknown; - onError(handler: ErrorHandler): IsUnknown; - onComplete(handler: CompleteHandler): IsUnknown; - __proxyState: ProxyStateGetter>; - __referingObj: ReferingObject; -} - -type EnumHookType = 1 | 2 | 3; -export interface Hook { - /** The method instance of the last request */ - m?: Method; - - /** Save states fns */ - sf: ((frontStates: MergedStatesMap) => void)[]; - - /** Remove states fns */ - rf: (() => void)[]; - - /** Front states */ - fs: FrontRequestState< - FrameworkState, - FrameworkState, - FrameworkState, - FrameworkState, - FrameworkState - >; - - /** event manager */ - em: EventManager<{ - success: AlovaSuccessEvent; - error: AlovaErrorEvent; - complete: AlovaCompleteEvent; - }>; - - /** hookType, useRequest=1, useWatcher=2, useFetcher=3 */ - ht: EnumHookType; - - /** hook config */ - c: UseHookConfig; - - /** refering object */ - ro: ReferingObject; - - /** managed states */ - ms: MergedStatesMap; -} diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/helper.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/helper.d.ts deleted file mode 100644 index add05de..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/helper.d.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { FrameworkReadableState, FrameworkState, GeneralFn, GeneralState } from '@alova/shared'; -import type { AlovaGenerics, EffectRequestParams, ReferingObject, StatesExport, StatesHook } from 'alova'; -import { ExportedComputed, ExportedState } from './general'; - -type ActualStateTranslator> = - StateProxy extends FrameworkState - ? ExportedState - : ExportedComputed; -type CompletedExposingProvider> = { - [K in keyof O]: O[K] extends FrameworkReadableState - ? ActualStateTranslator - : K extends `on${infer eventUnused}` - ? (...args: Parameters) => CompletedExposingProvider - : O[K]; -}; - -/** - * create simple and unified, framework-independent states creators and handlers. - * @param statesHook states hook from `promiseStatesHook` function of alova - * @param referingObject refering object exported from `promiseStatesHook` function - * @returns simple and unified states creators and handlers - */ -// eslint-disable-next-line -export declare function statesHookHelper( - statesHook: StatesHook>, - referingObject?: ReferingObject -): { - create: (initialValue: Data, key: Key) => FrameworkState; - computed: ( - getter: () => Data, - depList: (GeneralState | FrameworkReadableState)[], - key: Key - ) => FrameworkReadableState; - effectRequest: (effectRequestParams: EffectRequestParams) => void; - ref: (initialValue: Data) => { - current: Data; - }; - memorize: (fn: Callback) => Callback; - watch: (source: (GeneralState | FrameworkReadableState)[], callback: () => void) => void; - onMounted: (callback: () => void) => void; - onUnmounted: (callback: () => void) => void; - /** - * refering object that sharing some value with this object. - */ - __referingObj: ReferingObject; - /** - * expose provider for specified use hook. - * @param object object that contains state proxy, framework state, operating function and event binder. - * @returns provider component. - */ - exposeProvider: >( - object: O - ) => CompletedExposingProvider< - AG, - O & { - __referingObj: ReferingObject; - update: (newStates: { [K in keyof O]?: any }) => void; - __proxyState: (key: K) => any; - } - >; - /** - * transform state proxies to object. - * @param states proxy array of framework states - * @param filterKey filter key of state proxy - * @returns an object that contains the states of target form - */ - objectify: [], Key extends 's' | 'v' | 'e' | undefined = undefined>( - states: S, - filterKey?: Key - ) => { - [K in S[number]['k']]: Key extends undefined - ? Extract< - S[number], - { - k: K; - } - > - : Extract< - S[number], - { - k: K; - } - >[NonNullable]; - }; - transformState2Proxy: (state: GeneralState, key: Key) => FrameworkState; -}; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/actionDelegationMiddleware.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/actionDelegationMiddleware.d.ts deleted file mode 100644 index b032273..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/actionDelegationMiddleware.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { AlovaGenerics } from 'alova'; -import { AlovaFetcherMiddlewareContext, AlovaFrontMiddlewareContext, AlovaGuardNext } from '../general'; - -export interface Actions { - [x: string]: (...args: any[]) => any; -} - -/** - * Operation function delegation middleware - * After using this middleware, you can call the delegated function through accessAction. - * Can delegate multiple identical IDs - * In order to eliminate the hierarchical restrictions of components - * @param id Client ID - * @returns alova middleware function - */ -export declare function actionDelegationMiddleware< - AG extends AlovaGenerics = AlovaGenerics, - Args extends any[] = any[] ->( - id: string | number | symbol -): ( - context: (AlovaFrontMiddlewareContext | AlovaFetcherMiddlewareContext) & { - delegatingActions?: Actions; - }, - next: AlovaGuardNext -) => Promise; - -/** - * Access the operation function, if there are multiple matches, onMatch will be called with this - * @param id Delegator id, or regular expression - * @param onMatch matching subscribers - */ -export declare function accessAction( - id: string | number | symbol | RegExp, - onMatch: (matchedSubscriber: Record, index: number) => void -): void; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/tokenAuthentication.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/tokenAuthentication.d.ts deleted file mode 100644 index 07d124b..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/tokenAuthentication.d.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { AlovaGenerics, AlovaOptions, AlovaRequestAdapter, Method, StatesHook } from 'alova'; -import adapterFetch from 'alova/fetch'; - -/** - * Unifiedly obtain the type of AlovaRequestAdapter - */ -export type AlovaRequestAdapterUnified< - RA extends - | AlovaRequestAdapter - | ((...args: any[]) => AlovaRequestAdapter) = AlovaRequestAdapter -> = RA extends AlovaRequestAdapter ? RA : ReturnType; - -// transform types StateHook and AlovaRequestAdapter to an AlovaGenerics -export type StateHookAdapter2AG, RA extends AlovaRequestAdapter> = - Parameters[1] extends Method> - ? AlovaGenerics ? SE : unknown> - : never; - -export type AlovaResponded, RA extends AlovaRequestAdapter> = NonNullable< - AlovaOptions>['responded'] ->; - -export type MetaMatches = Record; -export type ResponseInterceptHandler, RESULT = Promise> = ( - response: ReturnType['response']> extends Promise ? RE : never, - method: Parameters[1] -) => RESULT; -export type ResponseErrorInterceptHandler, RESULT = Promise> = ( - error: any, - method: Parameters[1] -) => RESULT; -export type ResponseAuthorizationInterceptor> = - | ResponseInterceptHandler> - | { - metaMatches?: MetaMatches; - handler: ResponseInterceptHandler>; - }; - -export type RequestHandler, RESULT = Promise> = ( - method: Parameters[1] -) => RESULT; - -export interface TokenAuthenticationOptions> { - /** - * Ignore intercepted methods - */ - visitorMeta?: MetaMatches; - /** - * Login request interceptor - */ - login?: ResponseAuthorizationInterceptor; - - /** - * Logout request interceptor - */ - logout?: ResponseAuthorizationInterceptor; - /** - * Assign token callback function, requests for login ID and visitor ID will not trigger this function - * @param method method instance - */ - assignToken?: (method: Method) => void | Promise; -} -export interface ClientTokenAuthenticationOptions> - extends TokenAuthenticationOptions { - /** - * Determine whether the token has expired in the interceptor before the request, and refresh the token - */ - refreshToken?: { - /** - * Determine whether the token has expired - */ - isExpired: RequestHandler>; - /** - * Refresh token - */ - handler: RequestHandler; - /** - * Customize the method meta that matches the refresh token - */ - metaMatches?: MetaMatches; - }; -} - -export type AlovaBeforeRequest, RA extends AlovaRequestAdapter> = ( - method: Method> -) => void | Promise; - -type BeforeRequestType, RA extends AlovaRequestAdapter> = ( - originalBeforeRequest?: AlovaBeforeRequest -) => AlovaBeforeRequest; -type ResponseType, RA extends AlovaRequestAdapter> = ( - originalResponded?: AlovaResponded -) => AlovaResponded; - -export interface TokenAuthenticationResult, RA extends AlovaRequestAdapter> { - onAuthRequired: BeforeRequestType; - onResponseRefreshToken: ResponseType; - waitingList: { - method: Method>; - resolve: () => void; - }[]; -} - -export interface ServerTokenAuthenticationOptions> - extends TokenAuthenticationOptions { - /** - * Determine whether the token has expired in the request success interceptor and refresh the token - */ - refreshTokenOnSuccess?: { - /** - * Determine whether the token has expired - */ - isExpired: ResponseInterceptHandler>; - /** - * Refresh token - */ - handler: ResponseInterceptHandler; - /** - * Customize the method meta that matches the refresh token - */ - metaMatches?: MetaMatches; - }; - - /** - * Determine whether the token has expired in the request failure interceptor and refresh the token - */ - refreshTokenOnError?: { - /** - * Determine whether the token has expired - */ - isExpired: ResponseErrorInterceptHandler>; - /** - * Refresh token - */ - handler: ResponseErrorInterceptHandler; - /** - * Customize the method meta that matches the refresh token - */ - metaMatches?: MetaMatches; - }; -} - -/** - * Create a client-side token authentication interceptor - * @example - * ```js - * const { onAuthRequired, onResponseRefreshToken } = createClientTokenAuthentication(\/* ... *\/); - * const alova = createAlova({ - * // ... - * beforeRequest: onAuthRequired(method => { - * // ... - * }), - * responded: onResponseRefreshToken({ - * onSuccess(response, method) { - * // ... - * }, - * onError(error, method) { - * // ... - * }, - * }) - * }); - * ``` - * @param options Configuration parameters - * @returns token authentication interceptor function - */ -export declare function createClientTokenAuthentication< - SH extends StatesHook, - RA extends - | AlovaRequestAdapter - | ((...args: any[]) => AlovaRequestAdapter) = typeof adapterFetch ->( - options: ClientTokenAuthenticationOptions> -): TokenAuthenticationResult>; - -/** - * Create a server-side token authentication interceptor - * @example - * ```js - * const { onAuthRequired, onResponseRefreshToken } = createServerTokenAuthentication(\/* ... *\/); - * const alova = createAlova({ - * // ... - * beforeRequest: onAuthRequired(method => { - * // ... - * }), - * responded: onResponseRefreshToken({ - * onSuccess(response, method) { - * // ... - * }, - * onError(error, method) { - * // ... - * }, - * }) - * }); - * ``` - * @param options Configuration parameters - * @returns token authentication interceptor function - */ -export declare function createServerTokenAuthentication< - SH extends StatesHook, - RA extends - | AlovaRequestAdapter - | ((...args: any[]) => AlovaRequestAdapter) = typeof adapterFetch ->( - options: ServerTokenAuthenticationOptions> -): TokenAuthenticationResult>; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/updateState.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/updateState.d.ts deleted file mode 100644 index c82535f..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/updateState.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { AlovaGenerics, Method } from 'alova'; - -export type UpdateStateCollection = { - [key: string | number | symbol]: (data: any) => any; -} & { - data?: (data: Responded) => any; -}; -/** - * cross components to update states by specifing method instance. - * @example - * ```js - * updateState(methodInstance, newData); - * updateState(methodInstance, oldData => { - * oldData.name = 'new name'; - * return oldData; - * }); - * ``` - * @param matcher method instance - * @param handleUpdate new data or update function that returns new data - * @returns is updated - */ -export declare function updateState( - matcher: Method>, - handleUpdate: UpdateStateCollection['data'] | UpdateStateCollection -): Promise; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useAutoRequest.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useAutoRequest.d.ts deleted file mode 100644 index 2c193e6..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useAutoRequest.d.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { AlovaGenerics, Method } from 'alova'; -import { AlovaMethodHandler, UseHookExposure } from '../general'; -import { RequestHookConfig } from './useRequest'; - -/** - * useAutoRequest configuration - */ -export type AutoRequestHookConfig = { - /** - * Polling event, unit is `ms`, 0 means not enabled - * @default 0 - */ - pollingTime?: number; - /** - * Browser display hide or tab switch - * @default true - */ - enableVisibility?: boolean; - /** - * Browser spotlight - * @default true - */ - enableFocus?: boolean; - /** - * Enable network reconnection - * @default true - */ - enableNetwork?: boolean; - /** - * Throttle time, unit ms, means that only one request will be sent if triggered multiple times within the throttling time. - * @default 1000 - */ - throttle?: number; -} & RequestHookConfig; - -export type NotifyHandler = () => void; -export type UnbindHandler = () => void; - -/** - * Under certain conditions, data can be automatically re-pulled to refresh the page. Usage scenarios include: - * 1. Pull the latest data when the browser tab is switched - * 2. Pull the latest data when the browser is focused - * 3. Pull the latest data when the network is reconnected - * 4. Polling request - * One or more of the above trigger conditions can be configured at the same time, and the throttling time can also be configured to prevent multiple requests from being triggered in a short period of time. For example, only one trigger is allowed within 1 second. - * @param handler method instance or get function - * @param config Configuration parameters - * @return useAutoRequest related data and operation functions - */ -export declare function useAutoRequest( - handler: Method | AlovaMethodHandler, - config?: AutoRequestHookConfig -): UseHookExposure; -export declare namespace useAutoRequest { - function onNetwork( - notify: NotifyHandler, - config: AutoRequestHookConfig - ): UnbindHandler; - function onPolling( - notify: NotifyHandler, - config: AutoRequestHookConfig - ): UnbindHandler; - function onVisibility( - notify: NotifyHandler, - config: AutoRequestHookConfig - ): UnbindHandler; - function onFocus( - notify: NotifyHandler, - config: AutoRequestHookConfig - ): UnbindHandler; -} diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useCaptcha.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useCaptcha.d.ts deleted file mode 100644 index 892cba2..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useCaptcha.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { AlovaGenerics, Method } from 'alova'; -import { AlovaMethodHandler, ExportedState, UseHookExposure } from '../general'; -import { RequestHookConfig } from './useRequest'; - -/** - * useCaptcha configuration - */ -export type CaptchaHookConfig = { - /** - * Initial countdown, when the verification code is sent successfully, the countdown will start with this data - * @default 60 - */ - initialCountdown?: number; -} & RequestHookConfig; - -/** - * useCaptcha return value - */ -export interface CaptchaExposure - extends UseHookExposure> { - /** - * The current countdown is -1 every second. When the countdown reaches 0, the verification code can be sent again. - */ - countdown: ExportedState; -} - -/** - * Request hook for verification code sending scenario - * @param handler method instance or get function - * @param Configuration parameters - * @return useCaptcha related data and operation functions - */ -export declare function useCaptcha( - handler: Method | AlovaMethodHandler, - config?: CaptchaHookConfig -): CaptchaExposure; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useFetcher.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useFetcher.d.ts deleted file mode 100644 index 2eb3d3c..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useFetcher.d.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { - Alova, - AlovaGenerics, - FetchRequestState, - Method, - Progress, - ReferingObject, - StatesExport, - StatesHook -} from 'alova'; -import { - AlovaFetcherMiddleware, - ExportedState, - ProxyStateGetter, - StateUpdater, - UseHookConfig, - UseHookExportedState, - UseHookExposure -} from '../general'; - -/** - * specify the alova type - * so that it can return the right states - */ -export type FetcherType> = { - StatesExport: NonNullable extends StatesHook ? SE : any; -}; - -/** useFetcher config export type */ -export interface FetcherHookConfig extends UseHookConfig { - /** - * middleware - */ - middleware?: AlovaFetcherMiddleware; - /** - * whether to update the corresponding states of fetching method instance - */ - updateState?: boolean; -} - -export interface UseFetchExportedState - extends FetchRequestState< - ExportedState, - ExportedState, - ExportedState, - ExportedState - > {} -export interface UseFetchHookExposure extends UseFetchExportedState { - fetch(matcher: Method>, ...args: any[]): Promise; - update: StateUpdater, SE>; - abort: UseHookExposure['abort']; - onSuccess: UseHookExposure['onSuccess']; - onError: UseHookExposure['onError']; - onComplete: UseHookExposure['onComplete']; - __proxyState: ProxyStateGetter>; - __referingObj: ReferingObject; -} - -/** - * prefetch data - * @example - * ```js - * const { loading, error, fetch } = useFetcher(); - * const handleFetch = () => { - * fetch(alova.Get('/api/profile')); - * }; - * ``` - * @param config config - * @returns reactive request data、operate function and event binding function - */ -export declare function useFetcher>( - config?: FetcherHookConfig -): UseFetchHookExposure; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useForm.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useForm.d.ts deleted file mode 100644 index 82fe563..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useForm.d.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { AlovaGenerics, Method } from 'alova'; -import { ExportedState, UseHookExposure } from '../general'; -import { RequestHookConfig } from './useRequest'; -import { DataSerializer } from './useSQRequest'; - -/** - * useForm's handler function type - */ -export type FormHookHandler = ( - form: F, - ...args: Args -) => Method; - -/** - * useForm configuration - */ -export interface StoreDetailConfig { - /** - * Whether to enable persistent data - */ - enable: boolean; - - /** - * Serializer collection, used to customize certain data that cannot be converted directly when converted to serialization - * The key of the collection is serialized as its name. When deserializing, the value of the corresponding name will be passed into the backward function. - * Therefore, when serializing in forward, it is necessary to determine whether it is the specified data and return the converted data, otherwise it will return undefined or not return - * In backward, it can be identified by name, so you only need to deserialize it directly. - * Built-in serializer: - * 1. Date serializer is used to convert dates - * 2. The regexp serializer is used to convert regular expressions - * - * >>> You can override the built-in serializer by setting a serializer with the same name - */ - serializers?: Record; -} -export type FormHookConfig = { - /** - * Initial form data - */ - initialForm?: FormData; - - /** - * form id, data data with the same id is the same reference, and can be used to share the same form data in multi-page forms. - * Single-page forms do not need to specify an id - */ - id?: string | number; - - /** - * Whether to persist data. If set to true, uncommitted data will be persisted in real time. - * @default false - */ - store?: boolean | StoreDetailConfig; - - /** - * Reset data after submission - * @default false - */ - resetAfterSubmiting?: boolean; -} & RequestHookConfig; - -export type RestoreHandler = () => void; -/** - * useForm return value - */ -export interface FormExposure - extends UseHookExposure> { - /** - * form data - */ - form: ExportedState; - - /** - * Persistent data recovery event binding, triggered after data recovery - */ - onRestore(handler: RestoreHandler): this; - - /** - * Update form data, which can be passed in - * @param newForm new form data - */ - updateForm(newForm: Partial | ((oldForm: F) => F)): void; - - /** - * Reset to initialization data, clear if there is persistent data - */ - reset(): void; -} - -/** - * useForm - * Form submission hook, draft function, and data synchronization function for multi-page forms - * - * Applicable scenarios: - * 1. Single form/multiple form submission, draft data persistence, data update and reset - * 2. Conditional search input items can persist search conditions and send form data immediately - * - * @param handler method gets the function, you only need to pass the id when getting the synchronized data - * @param config Configuration parameters - * @return useForm related data and operation functions - */ -export declare function useForm< - AG extends AlovaGenerics, - FormData extends Record, - Args extends any[] = any[] ->( - handler: FormHookHandler, - config?: FormHookConfig -): FormExposure; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/usePagination.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/usePagination.d.ts deleted file mode 100644 index 235161a..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/usePagination.d.ts +++ /dev/null @@ -1,134 +0,0 @@ -import type { IsUnknown } from '@alova/shared'; -import { AlovaGenerics, Method } from 'alova'; -import { - CompleteHandler, - ErrorHandler, - ExportedComputed, - ExportedState, - StateUpdater, - SuccessHandler, - UseHookExposure -} from '../general'; -import { WatcherHookConfig } from './useWatcher'; - -/** - * @description usePagination related - */ -export type ArgGetter = (data: R) => LD | undefined; -export interface PaginationHookConfig extends WatcherHookConfig { - /** - * Whether to preload the previous page - * @default true - */ - preloadPreviousPage?: boolean; - /** - * Whether to preload the next page - * @default true - */ - preloadNextPage?: boolean; - /** - * Specify the total amount of data - * @default response => response.total - */ - total?: ArgGetter; - /** - * Specify paginated array data - * @default response => response.data - */ - data?: ArgGetter; - /** - * Whether to enable append mode - * @default false - */ - append?: boolean; - /** - * Initial page number - * @default 1 - */ - initialPage?: number; - /** - * Initial number of data items per page - * @default 10 - */ - initialPageSize?: number; - /** - * State monitoring triggers requests, implemented using useWatcher - * @default [page, pageSize] - */ - watchingStates?: AG['StatesExport']['Watched'][]; -} -export interface UsePaginationExposure - extends Omit>, 'update'> { - page: ExportedState; - pageSize: ExportedState; - data: ExportedState< - IsUnknown< - ListData[number], - AG['Responded'] extends { - data: any; - } - ? AG['Responded']['data'] - : ListData, - ListData - >, - AG['StatesExport'] - >; - pageCount: ExportedComputed; - total: ExportedComputed; - isLastPage: ExportedComputed; - fetching: ExportedState; - onFetchSuccess(handler: SuccessHandler): UsePaginationExposure; - onFetchError(handler: ErrorHandler): UsePaginationExposure; - onFetchComplete(handler: CompleteHandler): UsePaginationExposure; - update: StateUpdater, AG['StatesExport']>; - - /** - * Refresh the specified page number data. This function will ignore the cache and force the request to be sent. - * If no page number is passed in, the current page will be refreshed. - * If a list item is passed in, the page where the list item is located will be refreshed, which is only valid in append mode. - * @param pageOrItemPage Refreshed page number or list item - */ - refresh(pageOrItemPage?: number | ListData[number]): Promise; - - /** - * Insert a piece of data - * If no index is passed in, it will be inserted at the front by default. - * If a list item is passed in, it will be inserted after the list item. If the list item is not in the list data, an error will be thrown. - * @param item insert - * @param position Insert position (index) or list item - */ - insert(item: ListData extends any[] ? ListData[number] : any, position?: number | ListData[number]): Promise; - - /** - * Remove a piece of data - * If a list item is passed in, the list item will be removed. If the list item is not in the list data, an error will be thrown. - * @param position Removed index or list item - */ - remove(...positions: (number | ListData[number])[]): Promise; - - /** - * Replace a piece of data - * If the position passed in is a list item, this list item will be replaced. If the list item is not in the list data, an error will be thrown. - * @param item replacement - * @param position Replace position (index) or list item - */ - replace(item: ListData extends any[] ? ListData[number] : any, position: number | ListData[number]): void; - - /** - * Reload the list starting from the first page and clear the cache - */ - reload(): Promise; -} - -/** - * anova paging hook - * Automatic management of paging related status, preloading of previous and next pages, automatic maintenance of data addition/editing/removal - * - * @param handler methodCreate function - * @param config pagination hook configuration - * @returns {UsePaginationExposure} - */ -export declare function usePagination( - handler: (page: number, pageSize: number, ...args: Args) => Method, - config?: PaginationHookConfig -): UsePaginationExposure; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useRequest.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useRequest.d.ts deleted file mode 100644 index 4fe9a9f..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useRequest.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -import { AlovaGenerics, Method } from 'alova'; -import { AlovaFrontMiddleware, AlovaMethodHandler, UseHookConfig, UseHookExposure } from '../general'; - -/** Both use request and use watcher have types */ -type InitialDataType = number | string | boolean | object; -export interface FrontRequestHookConfig extends UseHookConfig { - /** Whether to initiate a request immediately */ - immediate?: boolean; - - /** set initial data for request state */ - initialData?: InitialDataType | (() => InitialDataType); - - /** Additional regulatory status, which can be updated via update state */ - managedStates?: Record; - - /** Middleware */ - middleware?: AlovaFrontMiddleware; -} - -/** useRequest config export type */ -export type RequestHookConfig = FrontRequestHookConfig; - -/** - * Automatically manage response status hooks - * @example - * ```js - * const { loading, data, error, send, onSuccess } = useRequest(alova.Get('/api/user')) - * ``` - * @param methodHandler method instance or get function - * @param config Configuration items - * @returns Responsive request data, operation functions and event binding functions - */ -export declare function useRequest( - methodHandler: Method | AlovaMethodHandler, - config?: RequestHookConfig -): UseHookExposure; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useRetriable.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useRetriable.d.ts deleted file mode 100644 index 49d1361..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useRetriable.d.ts +++ /dev/null @@ -1,90 +0,0 @@ -import type { BackoffPolicy } from '@alova/shared'; -import { AlovaGenerics, Method } from 'alova'; -import { AlovaErrorEvent, AlovaEvent, AlovaMethodHandler, UseHookExposure } from '../general'; -import { RequestHookConfig } from './useRequest'; - -/** - * useRetriableRequest配置 - */ -export type RetriableHookConfig = { - /** - * The maximum number of retries can also be set as a function that returns a boolean value to dynamically determine whether to continue retrying. - * @default 3 - */ - retry?: number | ((error: Error, ...args: [...Args, ...any[]]) => boolean); - - /** - * avoidance strategy - */ - backoff?: BackoffPolicy; -} & RequestHookConfig; - -/** - * useRetriableRequest onRetry callback event instance - */ -export interface RetriableRetryEvent extends AlovaEvent { - /** - * Current number of retries - */ - retryTimes: number; - - /** - * Delay time for this retry - */ - retryDelay: number; -} -/** - * useRetriableRequest onFail callback event instance - */ -export interface RetriableFailEvent extends AlovaErrorEvent { - /** - * Number of retries on failure - */ - retryTimes: number; -} -/** - * useRetriableRequest return value - */ -export interface RetriableExposure - extends UseHookExposure> { - /** - * Stop retrying, the call is only valid during the retry period - * The onFail event will be triggered immediately after stopping - * - */ - stop(): void; - - /** - * Retry event binding - * They will be triggered after the retry is initiated - * @param handler Retry event callback - */ - onRetry(handler: (event: RetriableRetryEvent) => void): this; - - /** - * failed event binding - * They will be triggered when there are no more retries, such as when the maximum number of retries is reached, when the retry callback returns false, or when stop is manually called to stop retries. - * The onError event of alova will be triggered every time an error is requested. - * - * Note: If there are no retries, onError, onComplete and onFail will be triggered at the same time. - * - * @param handler Failure event callback - */ - onFail(handler: (event: RetriableFailEvent) => void): this; -} - -/** - * useRetriableRequest - * Request hook with retry function - * Applicable scenarios: - * 1. Retry if the request fails, or retry with custom rules - * 2. Manual stop/start retry - * - * @param handler method instance or get function - * @param config Configuration parameters - * @return useRetriableRequest related data and operation functions - */ -export declare function useRetriableRequest( - handler: Method | AlovaMethodHandler, - config?: RetriableHookConfig -): RetriableExposure; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useSQRequest.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useSQRequest.d.ts deleted file mode 100644 index a38e688..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useSQRequest.d.ts +++ /dev/null @@ -1,497 +0,0 @@ -import type { EventManager } from '@alova/shared'; -import { Alova, AlovaGenerics, Method } from 'alova'; -import { AlovaCompleteEvent, AlovaEvent, AlovaMethodHandler, UseHookExposure } from '../general'; -import { updateState } from './updateState'; -import { RequestHookConfig } from './useRequest'; - -// ========================= -/** Silently commit events */ -// event: -// Globally: -// [GlobalSQEvent] Request events: behavior, silentMethod instance, method instance, retryTimes -// [GlobalSQSuccessEvent] Success events: collection of behavior, silentMethod instance, method instance, retryTimes, response data, virtual data and actual values -// [GlobalSQErrorEvent] Error events: behavior, silentMethod instance, method instance, retryTimes, error object, [?] next retry interval -// [GlobalSQFailEvent] Failure event: behavior, silentMethod instance, method instance, retryTimes, error object - -// Local: -// [ScopedSQSuccessEvent] Success events: behavior, silentMethod instance, method instance, retryTimes, send parameter, response data -// [ScopedSQErrorEvent] Failure events: behavior, silentMethod instance, method instance, retryTimes, send parameter, error object -// [ScopedSQErrorEvent] Fallback events: behavior, silentMethod instance, method instance, retryTimes, send parameter, error object -// [ScopedSQSuccessEvent | ScopedSQErrorEvent] Completion event: behavior, silentMethod instance, method instance, retryTimes, send parameter, [?] error object -// [ScopedSQEvent] Before entering the queue: behavior, silentMethod instance, method instance, send parameter -// [ScopedSQEvent] After entering the queue: behavior, silentMethod instance, method instance, send parameter -/** SQ top level events */ -export interface SQEvent { - /** - * Request behavior corresponding to the event - */ - behavior: SQHookBehavior; - /** - * the current method instance - */ - method: Method; - /** - * The current silentMethod instance has no value when the behavior is static - */ - silentMethod?: SilentMethod; -} -/** Sq global events */ -export interface GlobalSQEvent extends SQEvent { - /** - * Number of retries, no value in beforePush and pushed events - */ - retryTimes: number; - - /** - * The queue name where silentMethod is located - */ - queueName: string; -} -/** Sq global success event */ -export interface GlobalSQSuccessEvent extends GlobalSQEvent { - /** - * response data - */ - data: any; - /** - * A collection of dummy data and actual values - * It only contains the actual values of the dummy data you have used. - */ - vDataResponse: Record; -} -/** Sq global failure event */ -export interface GlobalSQErrorEvent extends GlobalSQEvent { - /** - * Error thrown on failure - */ - error: any; - - /** - * Next retry interval (milliseconds) - */ - retryDelay?: number; -} -/** Sq global failure event */ -export interface GlobalSQFailEvent extends GlobalSQEvent { - /** Error thrown on failure */ - error: any; -} - -/** Sq local event */ -export interface ScopedSQEvent extends SQEvent { - /** - * The parameters passed in when triggering the request through send - */ - args: [...Args, ...any[]]; -} -/** partial success event */ -export interface ScopedSQSuccessEvent - extends ScopedSQEvent { - /** - * response data - */ - data: AG['Responded']; -} -/** local failure event */ -export interface ScopedSQErrorEvent - extends ScopedSQEvent { - /** - * Error thrown on failure - */ - error: any; -} -/** local failure event */ -export interface ScopedSQRetryEvent - extends ScopedSQEvent { - /** - * Number of retries - */ - retryTimes: number; - /** - * Retry interval (milliseconds) - */ - retryDelay: number; -} -/** partial completion event */ -export interface ScopedSQCompleteEvent - extends ScopedSQEvent { - /** - * response status - */ - status: AlovaCompleteEvent['status']; - /** - * response data - */ - data?: AG['Responded']; - /** - * Error thrown on failure - */ - error?: any; -} - -export interface RetryErrorDetailed { - name?: RegExp; - message?: RegExp; -} - -export interface BackoffPolicy { - /** - * Delay time for requesting again, in milliseconds - * @default 1000 - */ - delay?: number; - /** - * Specify the delay multiplier. For example, if the multiplier is set to 1.5 and the delay is 2 seconds, the first retry will be 2 seconds, the second retry will be 3 seconds, and the third retry will be 4.5 seconds. - * @default 1 - */ - multiplier?: number; - - /** - * Jitter starting percentage value for delayed requests, ranging from 0-1 - * When only startQuiver is set, endQuiver defaults to 1 - * For example, set to 0.5, it will add 50% to 100% random time to the current delay time - * If endQuiver has a value, the delay time will be increased by a random value in the range of startQuiver and endQuiver - */ - startQuiver?: number; - - /** - * Jitter end percentage value for delayed requests, ranging from 0-1 - * When only endQuiver is set, startQuiver defaults to 0 - * For example, set to 0.5, it will add a random time of 0% to 50% to the current delay time - * If startQuiver has a value, the delay time will be increased by a random value in the range of startQuiver and endQuiver - */ - endQuiver?: number; -} - -export type ScopedSQEvents = { - fallback: ScopedSQEvent; - retry: ScopedSQRetryEvent; - beforePushQueue: ScopedSQEvent; - pushedQueue: ScopedSQEvent; -}; - -/** - * silentMethod instance - * Requests that need to enter silentQueue will be packaged into silentMethod instances, which will carry various parameters of the request strategy. - */ -export interface SilentMethod { - /** - * silentMethod instance id - */ - readonly id: string; - /** - * The behavior of the instance, queue or silent - */ - readonly behavior: SQHookBehavior; - /** - * method instance - */ - readonly entity: Method; - - /** - * Whether it is a persistent instance - */ - cache: boolean; - - /** - * Retry error rules - * Retries only when the error matches the following expression - * When the value is a regular expression, it will match the message of the error object - * When the value is an object, it can be set to match the name or message of the error object. If both are set, it will be matched in the form of or - * - * When not set, all errors will be retried by default. - */ - readonly retryError?: RegExp | RetryErrorDetailed; - /** - * Number of retries - */ - readonly maxRetryTimes?: number; - /** - * avoidance strategy - */ - readonly backoff?: BackoffPolicy; - - /** - * Fallback event callback, this callback will be called when the number of retries reaches the upper limit but still fails. - */ - readonly emitter: EventManager>; - - /** - * Promise's resolve function, the call will pass the corresponding promise object - */ - readonly resolveHandler?: Parameters>['0']>['0']; - - /** - * Promise's reject function, calling the corresponding promise object will fail - */ - readonly rejectHandler?: Parameters>['0']>['1']; - - /** - * methodHandler call parameters - * If there is dummy data, it will be replaced by actual data after the request is responded to. - */ - readonly handlerArgs?: any[]; - - /** - * The virtual data id used when creating the method - */ - readonly vDatas?: string[]; - - /** - * Virtual response data is saved here through delayUpdateState - */ - virtualResponse?: any; - - /** - * Which states are updated by calling updateStateEffect - */ - updateStates?: string[]; - - /** - * Submitting status update data silently - * When the data is submitted silently, we also need to manually update the submitted data to other states to achieve the purpose of immediately displaying the submitted information. - * In order to make the updated data available after reloading the page, we can use this field to save and persist it with the silentMethod. - * You can obtain this data again wherever you need to use it and display it on the interface. - * - * Note: Generally speaking, you can save persistent data with any attribute name, but an error will be reported in typescript, so reviewData is specified for you as the saving attribute of silent submission status data. - */ - reviewData?: any; - - /** - * Additional persistent data during silent commit - * When the data is actually submitted after silent submission, we may need to access this new data - * When the submitted data does not meet the data required for interface rendering, we can save the additional data to the extraData field when submitting to ensure that it can be obtained next time - * - * Note: Generally speaking, you can save persistent data with any attribute name, but an error will be reported in typescript, so extraData is specified for you as the field for the above function. - */ - extraData?: any; - - /** - * The method instance pointed to by the status update - * The target method instance that will update the state when calling updateStateEffect is stored here. - * The purpose is to allow the submitted data to still find the status that needs to be updated after refreshing the page. - */ - targetRefMethod?: Method; - - /** Is it currently being requested? */ - active?: boolean; - - /** Whether to force the request */ - force: boolean; - - /** - * Allow cache-time persistent updates to the current instance - */ - save(): Promise; - - /** - * Replace the current instance with a new silentMethod instance in the queue - * If there is a persistent cache, the cache will also be updated. - * @param newSilentMethod new silentMethod instance - */ - replace(newSilentMethod: SilentMethod): Promise; - - /** - * Remove the current instance, it will be removed synchronously in the persistent storage - */ - remove(): Promise; - - /** - * Set the method instance corresponding to the delayed update status and the corresponding status name - * It will find the corresponding status data and update vData to the actual data after responding to this silentMethod - * - * @param matcher method instance matcher - * @param updateStateName Updated status name, the default is data, you can also set multiple - */ - setUpdateState(matcher: Method, updateStateName?: string | string[]): void; -} - -// Silent queue hooks related -export type SQHookBehavior = 'static' | 'queue' | 'silent'; -export interface SQHookConfig { - /** - * Hook behavior, optional values are silent, queue, static, default is queue - * Can be set to an optional value, or a callback function that returns an optional value - * silent: Submit silently, the method instance will enter the queue and be persisted, and then trigger onSuccess immediately - * queue: Queue request, the method instance will enter the queue but will not be persisted, onSuccess and onError are triggered normally - * static: static request, the same as ordinary useRequest - * - * Scenario 1. Manual switch - * Scenario 2. When the network status is not good, fall back to static and determine the network status by yourself. - */ - behavior?: SQHookBehavior | ((event: AlovaEvent) => SQHookBehavior); - - /** Retry error rules - * Retry only when the error matches the following expression - * When the value is a regular expression, it will match the message of the error object - * When the value is an object, it can be set to match the name or message of the error object. If both are set, it will be matched in the form of or - */ - retryError?: NonNullable; - - /** Maximum number of retries */ - maxRetryTimes?: NonNullable; - - /** avoidance strategy */ - backoff?: NonNullable; - - /** - * Queue name. If not passed, the default queue will be selected. - * If you need to dynamically allocate the queue for each request, you can set it to a function and return the queue name. - */ - queue?: string | ((event: AlovaEvent) => string); - - /** Default response data when submitting silently */ - silentDefaultResponse?: () => any; - - /** - * It will be called when capturing with dummy data in method - * When this capture callback returns data, this data will be processed as response data instead of sending a request. - * @param {Method} method method instance - * @returns {R} Data in the same format as the response data - */ - vDataCaptured?: (method: Method) => AG['Responded'] | undefined | void; -} - -export type SQRequestHookConfig = SQHookConfig & - RequestHookConfig; -export type FallbackHandler = ( - event: ScopedSQEvent -) => void; -export type RetryHandler = ( - event: ScopedSQRetryEvent -) => void; -export type BeforePushQueueHandler = ( - event: ScopedSQEvent -) => void | boolean | Promise; -export type PushedQueueHandler = ( - event: ScopedSQEvent -) => void; -export type SQHookExposure = Omit< - UseHookExposure, - 'onSuccess' | 'onError' | 'onComplete' -> & { - /** - * Fallback event binding function, which will be triggered in the following situations: - * 1. After retrying the specified number of times without response and stopping continuing the request - * 2. After stopping the request due to network disconnection or corresponding error on the server side - * - * After binding this event, request persistence will be invalid, which means that silently submitted items will be lost on refresh - * It only works under silent behavior - * - * Compare with onComplete event: - * 1. Only triggered when the number of retries is reached and the failure still occurs. - * 2. Triggered before onComplete - */ - onFallback(handler: FallbackHandler): SQHookExposure; - - /** Called before entering the queue, you can filter duplicate silent methods in the queue. It is invalid under static behavior. */ - onBeforePushQueue(handler: BeforePushQueueHandler): SQHookExposure; - - /** Called after being queued, invalid under static behavior */ - onPushedQueue(handler: PushedQueueHandler): SQHookExposure; - - /** Retry event binding */ - onRetry(handler: RetryHandler): SQHookExposure; - - /** @override Rewrite alova's on success event */ - onSuccess(handler: (event: ScopedSQSuccessEvent) => void): SQHookExposure; - - /** @override Rewrite alova's on error event */ - onError(handler: (event: ScopedSQErrorEvent) => void): SQHookExposure; - - /** @override Override alova's on complete event */ - onComplete(handler: (event: ScopedSQCompleteEvent) => void): SQHookExposure; -}; - -export interface DataSerializer { - forward(data: any): any | undefined | void; - backward(data: any): any | undefined | void; -} - -export interface QueueRequestWaitSetting { - queue: string | RegExp; - wait: number | ((silentMethod: SilentMethod, queueName: string) => number | undefined); -} -/** Silent factory startup options */ -export interface SilentFactoryBootOptions { - /** - * alova instance that silentMethod depends on - * The storage adapter, request adapter, etc. of the alova instance will be used to access the SilentMethod instance and send silent commits - */ - alova: Alova; - - /** Delay in milliseconds, default delay is 2000ms when not transmitting */ - delay?: number; - - /** - * Serializer collection, used to customize certain data that cannot be converted directly when converted to serialization - * The key of the collection is serialized as its name. When deserializing, the value of the corresponding name will be passed into the backward function. - * Therefore, when serializing in forward, it is necessary to determine whether it is the specified data and return the converted data, otherwise it will return undefined or not return - * In backward, it can be identified by name, so you only need to deserialize it directly. - * Built-in serializer: - * 1. Date serializer is used to convert dates - * 2. The regexp serializer is used to convert regular expressions - * - * >>> You can override the built-in serializer by setting a serializer with the same name - */ - serializers?: Record; - - /** - * The request waiting time in silentQueue, in milliseconds (ms) - * It indicates the waiting time of the silentMethod that is about to send the request - * If not set, or set to 0, the silentMethod request is triggered immediately - * - * Tips: - * 1. When set directly, it is effective for the default queue by default. - * 2. If you need to set other queue settings, you can specify them as objects, such as: - * [ - * Indicates waiting 5000ms for the queue setting request named customName - * { queue: 'customName', wait: 5000 }, - * - * //Indicates that in all queues with the prefix prefix, the request setting with method instance name xxx is set to wait 5000ms - * { queue: /^prefix/, wait: silentMethod => silentMethod.entity.config.name === 'xxx' ? 5000 : 0 }, - * ] - * - * >>> It only works if the request succeeds, if it fails it will use the retry policy parameters - */ - requestWait?: QueueRequestWaitSetting[] | QueueRequestWaitSetting['wait']; -} - -export type SilentSubmitBootHandler = () => void; -export type BeforeSilentSubmitHandler = (event: GlobalSQEvent) => void; -export type SilentSubmitSuccessHandler = (event: GlobalSQSuccessEvent) => void; -export type SilentSubmitErrorHandler = (event: GlobalSQErrorEvent) => void; -export type SilentSubmitFailHandler = (event: GlobalSQFailEvent) => void; -export type OffEventCallback = () => void; -export type SilentQueueMap = Record[]>; - -/** - * request hook with silentQueue - * silentQueue is the core component to implement silent submission, which will be used to store silentMethod instances, and they will send submissions serially in order - */ -export declare function useSQRequest( - handler: AlovaMethodHandler, - config?: SQRequestHookConfig -): SQHookExposure; -export declare function bootSilentFactory(options: SilentFactoryBootOptions): void; -export declare function onSilentSubmitBoot(handler: SilentSubmitBootHandler): OffEventCallback; -export declare function onSilentSubmitSuccess(handler: SilentSubmitSuccessHandler): OffEventCallback; -export declare function onSilentSubmitError(handler: SilentSubmitErrorHandler): OffEventCallback; -export declare function onSilentSubmitFail(handler: SilentSubmitFailHandler): OffEventCallback; -export declare function onBeforeSilentSubmit(handler: BeforeSilentSubmitHandler): OffEventCallback; -export declare function dehydrateVData(target: T): T; -export declare function stringifyVData(target: any, returnOriginalIfNotVData?: boolean): any; -export declare function isVData(target: any): boolean; -export declare function equals(prevValue: any, nextValue: any): boolean; -export declare function filterSilentMethods( - methodNameMatcher?: string | number | RegExp, - queueName?: string, - filterActive?: boolean -): Promise; -export declare function getSilentMethod( - methodNameMatcher?: string | number | RegExp, - queueName?: string, - filterActive?: boolean -): Promise; -export declare const updateStateEffect: typeof updateState; -export declare const silentQueueMap: SilentQueueMap; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useSSE.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useSSE.d.ts deleted file mode 100644 index eb72eb5..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useSSE.d.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { AlovaGenerics, Method } from 'alova'; -import { AlovaEvent, AlovaMethodHandler, ExportedState } from '../general'; - -type SSEHookReadyState = 0 | 1 | 2; - -export interface AlovaSSEEvent extends AlovaEvent { - method: Method; - eventSource: EventSource; // Event source instance -} -export interface AlovaSSEErrorEvent - extends AlovaSSEEvent { - error: Error; // error object -} -export interface AlovaSSEMessageEvent - extends AlovaSSEEvent { - data: Data; // Data converted by the interceptor for each response -} -export type SSEOnOpenTrigger = ( - event: AlovaSSEEvent -) => void; -export type SSEOnMessageTrigger = ( - event: AlovaSSEMessageEvent -) => void; -export type SSEOnErrorTrigger = ( - event: AlovaSSEErrorEvent -) => void; -export type SSEOn = ( - eventName: string, - handler: (event: AlovaSSEMessageEvent) => void -) => () => void; - -/** - * useSSE() configuration item - */ -export interface SSEHookConfig { - /** - * Will be passed to new EventSource - */ - withCredentials?: boolean; - - /** - * Whether to pass the responded interception of the alova instance - * @default true - */ - interceptByGlobalResponded?: boolean; - - /** - * initial data - */ - initialData?: any; - - /** - * Whether to initiate a request immediately - * @default false - */ - immediate?: boolean; - - /** - * Whether to interrupt the previous request and trigger this request - * @default true - * TODO does not currently support specifying - */ - abortLast?: true; -} - -/** - * useSSE() return type - */ -export interface SSEExposure { - readyState: ExportedState; - data: ExportedState; - eventSource: ExportedState; - /** - * Make the request manually. This method is automatically triggered when using `immediate: true` - * @param args Request parameters will be passed to method - */ - send(...args: [...Args, ...any[]]): Promise; - /** - * close connection - */ - close(): void; - /** - * Register the callback function of EventSource open - * @param callback callback function - * @returns Unregister function - */ - onOpen(callback: SSEOnOpenTrigger): this; - - /** - * Register the callback function for EventSource message - * @param callback callback function - * @returns Unregister function - */ - onMessage(callback: SSEOnMessageTrigger): this; - - /** - * Register the callback function for EventSource error - * @param callback callback function - * @returns Unregister function - */ - onError(callback: SSEOnErrorTrigger): this; - - /** - * @param eventName Event name, default exists `open` | `error` | `message` - * @param handler event handler - */ - on: SSEOn; -} - -/** - * useSSE - * Send requests using Server-sent events - * - * - * @param handler methodget function - * @param config Configuration parameters - * @return useSSE related data and operation functions - */ -export declare function useSSE( - handler: Method | AlovaMethodHandler, - config?: SSEHookConfig -): SSEExposure; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useSerialRequest.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useSerialRequest.d.ts deleted file mode 100644 index 88fa37b..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useSerialRequest.d.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { AlovaGenerics, Method } from 'alova'; -import { AlovaMethodHandler, UseHookExposure } from '../general'; -import { RequestHookConfig } from './useRequest'; - -/** - * useSerialRequest - * Serial request hook, the handlers will receive the result of the previous request - * Applicable scenario: Serial request for a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialRequest related data and operation functions - */ -export declare function useSerialRequest( - serialHandlers: [Method | AlovaMethodHandler, ...AlovaMethodHandler[]], - config?: RequestHookConfig -): UseHookExposure; - -/** - * useSerialRequest(overload) - * Serial request hook, the handlers will receive the result of the previous request - * Applicable scenario: Serial request for a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialRequest related data and operation functions - */ -export declare function useSerialRequest< - AG extends AlovaGenerics, - AG2 extends AlovaGenerics, - Args extends any[] = any[] ->( - serialHandlers: [Method | AlovaMethodHandler, AlovaMethodHandler, ...AlovaMethodHandler[]], - config?: RequestHookConfig -): UseHookExposure; - -/** - * useSerialRequest(overload) - * Serial request hook, the handlers will receive the result of the previous request - * Applicable scenario: Serial request for a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialRequest related data and operation functions - */ -export declare function useSerialRequest< - AG extends AlovaGenerics, - AG2 extends AlovaGenerics, - AG3 extends AlovaGenerics, - Args extends any[] = any[] ->( - serialHandlers: [ - Method | AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - ...AlovaMethodHandler[] - ], - config?: RequestHookConfig -): UseHookExposure; - -/** - * useSerialRequest(overload) - * Serial request hook, the handlers will receive the result of the previous request - * Applicable scenario: Serial request for a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialRequest related data and operation functions - */ -export declare function useSerialRequest< - AG extends AlovaGenerics, - AG2 extends AlovaGenerics, - AG3 extends AlovaGenerics, - AG4 extends AlovaGenerics, - Args extends any[] = any[] ->( - serialHandlers: [ - Method | AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - ...AlovaMethodHandler[] - ], - config?: RequestHookConfig -): UseHookExposure; - -/** - * useSerialRequest(overload) - * Serial request hook, the handlers will receive the result of the previous request - * Applicable scenario: Serial request for a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialRequest related data and operation functions - */ -export declare function useSerialRequest< - AG extends AlovaGenerics, - AG2 extends AlovaGenerics, - AG3 extends AlovaGenerics, - AG4 extends AlovaGenerics, - AG5 extends AlovaGenerics, - Args extends any[] = any[] ->( - serialHandlers: [ - Method | AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - ...AlovaMethodHandler[] - ], - config?: RequestHookConfig -): UseHookExposure; - -/** - * useSerialRequest(overload) - * Serial request hook, the handlers will receive the result of the previous request - * Applicable scenario: Serial request for a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialRequest related data and operation functions - */ -export declare function useSerialRequest< - AG extends AlovaGenerics, - AG2 extends AlovaGenerics, - AG3 extends AlovaGenerics, - AG4 extends AlovaGenerics, - AG5 extends AlovaGenerics, - AG6 extends AlovaGenerics, - Args extends any[] = any[] ->( - serialHandlers: [ - Method | AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - ...AlovaMethodHandler[] - ], - config?: RequestHookConfig -): UseHookExposure; - -/** - * useSerialRequest(overload) - * Serial request hook, the handlers will receive the result of the previous request - * Applicable scenario: Serial request for a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialRequest related data and operation functions - */ -export declare function useSerialRequest< - AG extends AlovaGenerics, - AG2 extends AlovaGenerics, - AG3 extends AlovaGenerics, - AG4 extends AlovaGenerics, - AG5 extends AlovaGenerics, - AG6 extends AlovaGenerics, - AG7 extends AlovaGenerics, - Args extends any[] = any[] ->( - serialHandlers: [ - Method | AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - ...AlovaMethodHandler[] - ], - config?: RequestHookConfig -): UseHookExposure; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useSerialWatcher.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useSerialWatcher.d.ts deleted file mode 100644 index e4ebfc2..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useSerialWatcher.d.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { AlovaGenerics, Method } from 'alova'; -import { AlovaMethodHandler, UseHookExposure } from '../general'; -import { WatcherHookConfig } from './useWatcher'; - -/** - * useSerialWatcher - * Serial request hook, the handlers will receive the result of the previous request - * Applicable scenario: After monitoring status changes, serially request a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialWatcher related data and operation functions - */ -export declare function useSerialWatcher( - serialHandlers: [Method | AlovaMethodHandler, ...AlovaMethodHandler[]], - watchingStates: AG['StatesExport']['Watched'][], - config?: WatcherHookConfig -): UseHookExposure; - -/** - * useSerialWatcher(overload) - * Serial request hook, the handlers will receive the result of the previous request - * Applicable scenario: After monitoring status changes, serially request a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialWatcher related data and operation functions - */ -export declare function useSerialWatcher< - AG extends AlovaGenerics, - AG2 extends AlovaGenerics, - Args extends any[] = any[] ->( - serialHandlers: [Method | AlovaMethodHandler, AlovaMethodHandler, ...AlovaMethodHandler[]], - watchingStates: AG['StatesExport']['Watched'][], - config?: WatcherHookConfig -): UseHookExposure; - -/** - * useSerialWatcher(overload) - * Serial request hook, the handlers will receive the result of the previous request - * Applicable scenario: After monitoring status changes, serially request a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialWatcher related data and operation functions - */ -export declare function useSerialWatcher< - AG extends AlovaGenerics, - AG2 extends AlovaGenerics, - AG3 extends AlovaGenerics, - Args extends any[] = any[] ->( - serialHandlers: [ - Method | AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - ...AlovaMethodHandler[] - ], - watchingStates: AG['StatesExport']['Watched'][], - config?: WatcherHookConfig -): UseHookExposure; - -/** - * useSerialWatcher(overload) - * Serial request hook, the handlers will receive the result of the previous request - * Applicable scenario: After monitoring status changes, serially request a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialWatcher related data and operation functions - */ -export declare function useSerialWatcher< - AG extends AlovaGenerics, - AG2 extends AlovaGenerics, - AG3 extends AlovaGenerics, - AG4 extends AlovaGenerics, - Args extends any[] = any[] ->( - serialHandlers: [ - Method | AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - ...AlovaMethodHandler[] - ], - watchingStates: AG['StatesExport']['Watched'][], - config?: WatcherHookConfig -): UseHookExposure; - -/** - * useSerialWatcher(overload) - * Serial request hook, the handlers will receive the result of the previous request - * Applicable scenario: After monitoring status changes, serially request a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialWatcher related data and operation functions - */ -export declare function useSerialWatcher< - AG extends AlovaGenerics, - AG2 extends AlovaGenerics, - AG3 extends AlovaGenerics, - AG4 extends AlovaGenerics, - AG5 extends AlovaGenerics, - Args extends any[] = any[] ->( - serialHandlers: [ - Method | AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - ...AlovaMethodHandler[] - ], - watchingStates: AG['StatesExport']['Watched'][], - config?: WatcherHookConfig -): UseHookExposure; - -/** - * useSerialWatcher(overload) - * Serial request hook, the handlers will receive the result of the previous request - * Applicable scenario: After monitoring status changes, serially request a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialWatcher related data and operation functions - */ -export declare function useSerialWatcher< - AG extends AlovaGenerics, - AG2 extends AlovaGenerics, - AG3 extends AlovaGenerics, - AG4 extends AlovaGenerics, - AG5 extends AlovaGenerics, - AG6 extends AlovaGenerics, - Args extends any[] = any[] ->( - serialHandlers: [ - Method | AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - ...AlovaMethodHandler[] - ], - watchingStates: AG['StatesExport']['Watched'][], - config?: WatcherHookConfig -): UseHookExposure; - -/** - * useSerialWatcher(overload) - * Serial request hook, the handlers will receive the result of the previous request - * Applicable scenario: After monitoring status changes, serially request a set of interfaces - * @param serialHandlers Serial request callback array - * @param config Configuration parameters - * @return useSerialWatcher related data and operation functions - */ -export declare function useSerialWatcher< - AG extends AlovaGenerics, - AG2 extends AlovaGenerics, - AG3 extends AlovaGenerics, - AG4 extends AlovaGenerics, - AG5 extends AlovaGenerics, - AG6 extends AlovaGenerics, - AG7 extends AlovaGenerics, - Args extends any[] = any[] ->( - serialHandlers: [ - Method | AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - AlovaMethodHandler, - ...AlovaMethodHandler[] - ], - watchingStates: AG['StatesExport']['Watched'][], - config?: WatcherHookConfig -): UseHookExposure; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useWatcher.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useWatcher.d.ts deleted file mode 100644 index 658c092..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/hooks/useWatcher.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { AlovaGenerics, Method } from 'alova'; -import { AlovaMethodHandler, UseHookExposure } from '../general'; -import { FrontRequestHookConfig } from './useRequest'; - -/** useWatcher config export type */ -export interface WatcherHookConfig - extends FrontRequestHookConfig { - /** Request anti-shake time (milliseconds). When passing in the array, you can set the anti-shake time individually in the order of watching states. */ - debounce?: number | number[]; - abortLast?: boolean; -} - -/** - * Request after monitoring specific status value changes - * @example - * ```js - * const { data, loading, error, send, onSuccess } = useWatcher(() => alova.Get('/api/user-list'), [keywords]) - * ``` - * @param methodHandler method instance or get function - * @param watchingStates Listening status array - * @param config Configuration items - * @returns Responsive request data, operation functions and event binding functions - */ -export declare function useWatcher( - methodHandler: Method | AlovaMethodHandler, - watchingStates: AG['StatesExport']['Watched'][], - config?: WatcherHookConfig -): UseHookExposure; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/index.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/index.d.ts deleted file mode 100644 index d7e0035..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/clienthook/index.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -export * from './general'; -export * from './helper'; -export * from './hooks/actionDelegationMiddleware'; -export * from './hooks/tokenAuthentication'; -export * from './hooks/updateState'; -export * from './hooks/useAutoRequest'; -export * from './hooks/useCaptcha'; -export * from './hooks/useFetcher'; -export * from './hooks/useForm'; -export * from './hooks/usePagination'; -export * from './hooks/useRequest'; -export * from './hooks/useRetriable'; -export * from './hooks/useSerialRequest'; -export * from './hooks/useSerialWatcher'; -export * from './hooks/useSQRequest'; -export * from './hooks/useSSE'; -export * from './hooks/useWatcher'; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/fetch.d.cts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/fetch.d.cts deleted file mode 100644 index 3af37ea..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/fetch.d.cts +++ /dev/null @@ -1,13 +0,0 @@ -import { AlovaRequestAdapter } from '.'; - -declare namespace FetchTypes { - type FetchRequestInit = Omit; - - /** - * fetch request adapter - */ - type FetchRequestAdapter = AlovaRequestAdapter; -} - -declare function adapterFetch(): FetchTypes.FetchRequestAdapter; -export = FetchTypes; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/fetch.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/fetch.d.ts deleted file mode 100644 index 8cadc1d..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/fetch.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { AlovaRequestAdapter } from '.'; - -export type FetchRequestInit = Omit; - -/** - * fetch request adapter - */ -export type FetchRequestAdapter = AlovaRequestAdapter; - -declare function adapterFetch(): FetchRequestAdapter; -export default adapterFetch; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/index.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/index.d.ts deleted file mode 100644 index 4081d0d..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/index.d.ts +++ /dev/null @@ -1,802 +0,0 @@ -import { EventManager, FrameworkState } from '@alova/shared'; - -export interface AlovaGenerics< - R = any, - T = any, - RC = any, - RE = any, - RH = any, - L1 extends AlovaGlobalCacheAdapter = any, - L2 extends AlovaGlobalCacheAdapter = any, - SE extends StatesExport = any -> { - Responded: R; - Transformed: T; - RequestConfig: RC; - Response: RE; - ResponseHeader: RH; - L1Cache: L1; - L2Cache: L2; - StatesExport: SE; -} - -type Arg = Record; -export type RequestBody = Arg | string | FormData | Blob | ArrayBuffer | URLSearchParams | ReadableStream; - -/** - * Request elements, information necessary to send a request - */ -export interface RequestElements { - readonly url: string; - readonly type: MethodType; - readonly headers: Arg; - readonly data?: RequestBody; -} -export type ProgressUpdater = (loaded: number, total: number) => void; -export type AlovaRequestAdapter = ( - elements: RequestElements, - method: Method> -) => { - response: () => Promise; - headers: () => Promise; - onDownload?: (handler: ProgressUpdater) => void; - onUpload?: (handler: ProgressUpdater) => void; - abort: () => void; -}; - -export type MethodType = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'OPTIONS' | 'PATCH'; - -/** - * provide user to custom some types - * 1. meta: custom metadata type. - * 2. statesHook: custom the global states hook type. - */ -export interface AlovaCustomTypes { - [customKey: string]: any; -} - -export interface AlovaGlobalCacheAdapter { - /** - * save or update cache - * @param key key - * @param value value - */ - set(key: string, value: any): void | Promise; - - /** - * get value by key - * @param key key - */ - get(key: string): T | undefined | Promise; - - /** - * remove item - * @param key key - */ - remove(key: string): void | Promise; - - /** - * clear all cache. - */ - clear(): void | Promise; -} - -interface CacheEvent { - type: 'set' | 'get' | 'remove' | 'clear'; - key: string; - value?: any; - container: Record; -} -export interface AlovaDefaultCacheAdapter extends AlovaGlobalCacheAdapter { - /** - * the events related to cache action emitter. - */ - readonly emitter: EventManager<{ success: CacheEvent; fail: Omit }>; -} - -/** - * Request cache settings - * expire: expiration time - * 1. When set to a number: if it is greater than 0, the cached data will be returned first, the expiration time unit is milliseconds, if it is less than or equal to 0, it will not be cached, and Infinity will never expire; - * 2. When set to a Date object, it means - * mode: cache mode, optional values are memory, restore - */ -export type CacheExpire = number | Date | null; -export type CacheMode = 'memory' | 'restore'; -export type CacheExpireGetter = (event: { - method: Method; - mode: CacheMode; -}) => CacheExpire; -export type DetailCacheConfig = { - expire: CacheExpire | CacheExpireGetter; - mode?: CacheMode; - - /** Persistent cache tags, the original persistent data will be invalid after the tag is changed. */ - tag?: string | number; -}; -export type CacheConfig = CacheExpire | DetailCacheConfig; -export type CacheController = () => Responded | undefined | Promise; -export interface MethodRequestConfig { - /** - * url parameters - */ - params: Arg; - - /** - * Request header - */ - headers: Arg; -} -export type AlovaMethodConfig = { - /** - * The name of the method object. The corresponding method object can be obtained by name or wildcard in the updateState, invalidateCache, setCache, and fetch functions. - */ - name?: string | number; - - /** - * current outage time - */ - timeout?: number; - - /** - * The response data will not be requested again within the cache time. Get requests are cached for 5 minutes (300000 milliseconds) by default, and other requests are not cached by default. - */ - cacheFor?: CacheConfig> | CacheController; - - /** - * Hit the source method instance. When the source method instance request is successful, the cache of the current method instance will be invalidated. - * As an automatic invalidation function, you only need to set the hit source instead of manually calling invalidateCache to invalidate the cache. - * At the same time, this function is more concise than the invalidateCache method in complex invalidation relationships. - * The value of this field can be set to the method instance, the name of other method instances, name regular matching, or their array - */ - hitSource?: string | RegExp | Method | (string | RegExp | Method)[]; - - /** - * Response data conversion. The converted data will be converted into data state. If there is no converted data, the response data will be used directly as data state. - */ - transform?: (data: Transformed, headers: AG['ResponseHeader']) => Responded | Promise; - - /** - * Request level sharing request switch - * After the sharing request is enabled, the same request will be shared when the same request is initiated at the same time. - * When set here, it will overwrite the global settings. - */ - shareRequest?: boolean; - - /** - * method metadata - */ - meta?: AlovaCustomTypes['meta']; -} & AG['RequestConfig']; -export type AlovaMethodCreateConfig = Partial & - AlovaMethodConfig; - -export type RespondedHandler = (response: AG['Response'], methodInstance: Method) => any; -export type ResponseErrorHandler = ( - error: any, - methodInstance: Method -) => void | Promise; -export type ResponseCompleteHandler = (methodInstance: Method) => any; -export type RespondedHandlerRecord = { - /** - * Global request success hook function - * If an error is thrown in global onSuccess, the global onError will not be triggered, but the onError of the requested location will be triggered. - */ - onSuccess?: RespondedHandler; - - /** - * Global request error hook function. Request error refers to a network request failure. Error codes such as 404 and 500 returned by the server will not enter this hook function. - * When the global onError is specified to capture the error, if no error is thrown, the onSuccess of the requested location will be triggered. - */ - onError?: ResponseErrorHandler; - - /** - * Request completion hook function - * This hook function will be triggered if the request is successful, the cache match is successful, or the request fails. - */ - onComplete?: ResponseCompleteHandler; -}; - -export interface FetchRequestState { - loading: L; - error: E; - downloading: D; - uploading: U; -} -export interface FrontRequestState extends FetchRequestState { - data: R; -} - -export type MergedStatesMap = Record>; -export interface EffectRequestParams { - handler: (...args: any[]) => void; - removeStates: () => void; - saveStates: (frontStates: MergedStatesMap) => void; - frontStates: MergedStatesMap; - watchingStates?: E[]; - immediate: boolean; -} - -export interface ReferingObject { - /** - * the map of tracked state keys - */ - trackedKeys: Record; - /** - * has been bound error event - */ - bindError: boolean; - [key: string]: any; -} -export type StatesExportHelper> = I; - -export interface StatesExport { - name: string; - State: T; - Computed: T; - Watched: T; - StateExport: T; - ComputedExport: T; -} - -export interface StatesHook> { - name: SE['name']; - /** - * Create status - * @param initialValue initial data - * @returns status value - */ - create: (initialValue: any, key: string, referingObject: ReferingObject) => SE['State']; - - /** - * create computed state - * @param initialValue initial data - * @param key attribute name - * @param referingObject refering object - */ - computed: ( - getter: () => any, - deps: (SE['StateExport'] | SE['ComputedExport'])[], - key: string, - referingObject: ReferingObject - ) => SE['Computed']; - - /** - * Values exported for use by developers - * @param state status value - * @param referingObject referring object - * @returns exported value - */ - export?: (state: SE['State'], referingObject: ReferingObject) => SE['StateExport'] | SE['ComputedExport']; - - /** Convert state to normal data */ - dehydrate: (state: SE['State'], key: string, referingObject: ReferingObject) => any; - - /** - * Update status value - * @param newVal new data collection - * @param state original state value - * @param key attribute name - * @param @param referingObject referring object - */ - update: (newVal: any, state: SE['State'], key: string, referingObject: ReferingObject) => void; - - /** - * Controls the function that executes the request. This function will be executed once when useRequest and useWatcher are called. - * Execute once in the fetch function in useFetcher - * When watchingStates is an empty array, execute the handleRequest function once - * When watchingStates is a non-empty array, it is called when the state changes. When immediate is true, it needs to be called immediately. - * Hook is an instance of use hook. Each time use hook is called, a hook instance will be generated. - * It can be executed directly in vue, but in react it needs to be executed in useEffect - * The removeStates function is a function that clears the current state and should be called when the component is unloaded. - */ - effectRequest: (effectParams: EffectRequestParams, referingObject: ReferingObject) => void; - - /** - * Packaging use hooks operation functions such as send and abort - * This is mainly used to optimize the problem that new functions will be generated every time rendering in react to optimize performance. - * @param fn use hook operation function - * @returns Wrapped operation function - */ - memorize?: any>(fn: Callback) => Callback; - - /** - * Create reference object - * @param initialValue initial value - * @returns a reference object containing the initial value - */ - ref?: (initialValue: D) => { current: D }; - - /** - * watch states - * @param source watching source - * @param callback callback when states changes - * @param referingObject refering object - */ - watch: (source: SE['Watched'][], callback: () => void, referingObject: ReferingObject) => void; - - /** - * bind mounted callback. - * @param callback callback on component mounted - * @param referingObject refering object - */ - onMounted: (callback: () => void, referingObject: ReferingObject) => void; - - /** - * bind unmounted callback. - * @param callback callback on component unmounted - * @param referingObject refering object - */ - onUnmounted: (callback: () => void, referingObject: ReferingObject) => void; -} - -export type GlobalCacheConfig = Partial>> | null; -export type CacheLoggerHandler = ( - response: any, - methodInstance: Method, - cacheMode: CacheMode, - tag: DetailCacheConfig['tag'] -) => void | Promise; -/** - * Generic type explanation: - * State: The type of state group created by the create function - * Computed: The computed property value created by the computed function - * Watched: listener type - * Export: The type of status group returned by the export function - * RequestConfig: the request configuration type of requestAdapter, automatically inferred - * Response: response configuration type of type requestAdapter, automatically inferred - * ResponseHeader: response header type of requestAdapter, automatically inferred - */ -export interface AlovaOptions { - /** - * custom alova id - * - * **Recommend to custom it in multiple server scenarios**from 0 in creating order - */ - id?: number | string; - - /** - * base url - */ - baseURL?: string; - - /** - * State hook function, used to define and update the state of the specified MVVM library - */ - statesHook?: StatesHook; - - /** - * request adapter. - * all request of alova will be sent by it. - */ - requestAdapter: AlovaRequestAdapter; - - /** - * global timeout. unit is millisecond. - */ - timeout?: number; - - /** - * Global request local cache settings - * expire: Expiration time. If it is greater than 0, the cached data will be returned first. The expiration time unit is milliseconds. If it is less than or equal to 0, it will not be cached. Infinity will never expire. - * mode: cache mode, optional values are memory, restore - * Get requests are cached for 5 minutes (300000 milliseconds) by default, and other requests are not cached by default. - * @default { GET: 300000 } - */ - cacheFor?: GlobalCacheConfig; - - /** - * memory mode cache adapter. it will be used when caching data with memory mode. - * it's an js's object default. - * you can set your own adapter with sync/async function of set/get/remove. - * see [https://alova.js.org/tutorial/custom/custom-storage-adapter] - */ - l1Cache?: AG['L1Cache']; - - /** - * restore mode cache adapter. it will be used when persist data. - * default behavior: - * -browser/deno: localStorage. - * -nodejs/bun: no adapter.(you can use @alova/cache-file). - * see [https://alova.js.org/tutorial/custom/custom-storage-adapter] - */ - l2Cache?: AG['L2Cache']; - - /** - * global before request hook - */ - beforeRequest?: (method: Method) => void | Promise; - - /** - * A global response hook, which can be passed or set as an object with onSuccess, onError, and onComplete, to represent the request success and request error hooks. - * If an error is thrown in global onSuccess, the global onError will not be triggered, but the onError of the requested location will be triggered. - * When the global onError is specified to capture the error, if no error is thrown, the onSuccess of the requested location will be triggered. - * @version 2.1.0 - */ - responded?: RespondedHandler | RespondedHandlerRecord; - - /** - * Global sharing request switch - * After the sharing request is enabled, the same request will be shared when the same request is initiated at the same time. - * @default true - */ - shareRequest?: boolean; - - /** - * Cache log printing - * When the response cache is hit, matching cache information will be printed on the console by default to remind developers - * When set to false or null, the log will not be printed. - * When set as a custom function, it will custom take over the task of cache matching. - * @version 2.8.0 - * @default true - */ - cacheLogger?: boolean | null | CacheLoggerHandler; - - /** - * limitation of method snapshots. - * it indicates not save snapshot when value is set to 0, and the method matcher will not work. - * @default 1000 - */ - snapshots?: number; -} - -/** progress information */ -export type Progress = { - total: number; - loaded: number; -}; -export type ProgressHandler = (progress: Progress) => void; - -export interface AbortFunction { - (): void; - a: () => void; -} - -/** - * Request method type - */ -export declare class Method extends Promise { - constructor( - type: MethodType, - context: Alova, - url: string, - config?: AlovaMethodCreateConfig, - data?: RequestBody - ); - - /** - * baseURL of alova instance - */ - baseURL: string; - - /** - * Request url - */ - url: string; - - /** - * Request type - */ - type: MethodType; - - /** - * method configuration - */ - config: MethodRequestConfig & AlovaMethodConfig; - - /** - * Request body - */ - data?: RequestBody; - - /** - * Cache hit source - */ - hitSource?: (string | RegExp)[]; - - /** - * alova example - */ - context: Alova; - - /** - * storage key - */ - key: string; - - /** - * download event - * @version 2.17.0 - */ - dhs: ProgressHandler[]; - - /** - * Upload event - * @version 2.17.0 - */ - uhs: ProgressHandler[]; - - /** - * Whether this response data comes from cache - * @version 2.17.0 - */ - fromCache: boolean | undefined; - - /** - * Used to pass additional information in global request and response hook functions - * Any field can be used in js projects - */ - meta?: AlovaCustomTypes['meta']; - - /** - * Request a Promise instance - */ - promise?: Promise; - - /** - * Use this method instance to send the request directly - * @param forceRequest mandatory request - * @returns Request a Promise instance - */ - send(forceRequest?: boolean): Promise; - - /** - * Set name - * @param name name - */ - setName(name: string | number): void; - - /** - * Generate the key of the current method - */ - generateKey(): string; - - /** - * Interrupt requests sent directly by this method instance - */ - abort: AbortFunction; - - /** - * Bind download progress callback function - * @param progressHandler Download progress callback function - * @version 2.17.0 - * @return unbind function - */ - onDownload(progressHandler: ProgressHandler): () => void; - - /** - * Bind upload progress callback function - * @param progressHandler Upload progress callback function - * @version 2.17.0 - * @return unbind function - */ - onUpload(progressHandler: ProgressHandler): () => void; -} - -export class MethodSnapshotContainer { - records: Record>>; - - capacity: number; - - occupy: number; - - save(methodInstance: Method): void; - - /** - * get method snapshots by matcher - * the method snapshots means the method instance that has been requested - * @version 3.0.0 - * @param {MethodFilter} matcher method matcher - * @param {boolean} matchAll is match all, default is true - * @returns {Method[] | Method} method list when `matchAll` is true, otherwise return method instance or undefined - */ - match( - matcher: MethodFilter, - matchAll?: M - ): M extends true ? Method[] : Method | undefined; -} - -export type RespondedAlovaGenerics = Omit< - AG, - 'Responded' | 'Transformed' -> & { - Responded: Responded; - Transformed: Transformed; -}; - -export interface Alova { - id: string; - options: AlovaOptions; - l1Cache: AG['L1Cache']; - l2Cache: AG['L2Cache']; - snapshots: MethodSnapshotContainer; - Get( - url: string, - config?: AlovaMethodCreateConfig - ): Method>; - Post( - url: string, - data?: RequestBody, - config?: AlovaMethodCreateConfig - ): Method>; - Put( - url: string, - data?: RequestBody, - config?: AlovaMethodCreateConfig - ): Method>; - Delete( - url: string, - data?: RequestBody, - config?: AlovaMethodCreateConfig - ): Method>; - Head( - url: string, - config?: AlovaMethodCreateConfig - ): Method>; - Options( - url: string, - config?: AlovaMethodCreateConfig - ): Method>; - Patch( - url: string, - data?: RequestBody, - config?: AlovaMethodCreateConfig - ): Method>; -} - -export interface MethodFilterHandler { - (method: Method, index: number, methods: Method[]): boolean; -} - -export type MethodDetaiedFilter = { - name?: string | RegExp; - filter?: MethodFilterHandler; -}; -export type MethodFilter = string | RegExp | MethodDetaiedFilter; - -/** - * alova global configurations. - */ -export interface AlovaGlobalConfig { - /** - * switch of auto hit cache. - * here is three options: - * -global: invalidate cache cross alova instances. - * -self: only invalidate cache from the same alova instance. - * -close: don't auto invalidate cache any more. - * @default 'global' - */ - autoHitCache?: 'global' | 'self' | 'close'; - /** - * whether the app is running in the server - * If not set or set to `undefined`, alova determines whether it is now running in the server - * @default undefined - */ - ssr?: boolean | undefined; -} - -// ************ exports *************** -/** - * create an alova instance. - * @param options global options - * @returns alova instance - */ -export declare function createAlova< - RequestConfig, - Response, - ResponseHeader, - L1Cache extends AlovaGlobalCacheAdapter = AlovaDefaultCacheAdapter, - L2Cache extends AlovaGlobalCacheAdapter = AlovaDefaultCacheAdapter, - SE extends StatesExport = StatesExport ->( - options: AlovaOptions> -): Alova>; - -/** - * invalidate cache - * @example - * ```js - * // invalidate cache with specific method instance. - * invalidateCache(alova.Get('/api/profile')); - * - * // match method snapshots then invalidate them. - * const methods = alova.snapshots.match('method-name'); - * invalidateCache(methods); - * - * // invalidate all cache. - * invalidateCache(); - * ``` - * @param matcher Array of method instances or method matcher parameters - */ -export declare function invalidateCache(matcher?: Method | Method[]): Promise; - -export interface UpdateOptions { - onMatch?: (method: Method) => void; -} - -export interface CacheSetOptions { - /** - * cache policy. - * -l1: only set l1 cache. - * -l2: only set l2 cache. - * -all: set l1 cache and set l2 cache(method cache mode need to be 'restore'). - * @default 'all' - */ - policy?: 'l1' | 'l2' | 'all'; -} -/** - * set cache manually - * @example - * ```js - * // set static cache - * setCache(methodInstance, newData); - * - * // set cache dynamically - * setCache(methodInstance, oldData => { - * if (oldData.name === 'new name') { - * // it indicates that the cache is not updated when returning undefined - * return; - * } - * old.name = 'new name'; - * return oldData; - * }); - * - * // get methods from snapshots - * const methods = alova.snapshots.match('method-name'); - * setCache(methods, newData); - * ``` - * @param matcher method instance(s) - */ -export declare function setCache( - matcher: Method | Method[], - dataOrUpdater: AG['Responded'] | ((oldCache: AG['Responded']) => AG['Responded'] | undefined | void), - options?: CacheSetOptions -): Promise; - -export interface CacheQueryOptions { - /** - * cache policy. - * -l1: only query l1 cache. - * -l2: only query l2 cache. - * -all: query l1 cache first and query l2 cache if l1 cache not found(method cache mode need to be 'restore'). - * @default 'all' - */ - policy?: 'l1' | 'l2' | 'all'; -} -/** - * query cache data - * @example - * ```js - * const cache = queryCache(alova.Get('/api/profile')); - * ``` - * @param matcher method instance - * @returns cache data, return undefined if not found - */ -export declare function queryCache( - matcher: Method, - options?: CacheQueryOptions -): Promise; - -/** - * hit(invalidate) target caches by source method - * this is the implementation of auto invalidate cache - * @param sourceMethod source method instance - * @example - * ```js - * await hitCacheBySource(alova.Get('/api/profile')); - * ``` - */ -export declare function hitCacheBySource(sourceMethod: Method): Promise; - -export declare const globalConfigMap: Required; - -/** - * Set global configuration configuration - */ -export declare function globalConfig(config: AlovaGlobalConfig): void; - -/** - * get the unified statesHook, and it will throw error if not set. - * @returns the unified statesHook - */ -export declare function promiseStatesHook>(): StatesHook; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/serverhook.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/serverhook.d.ts deleted file mode 100644 index ec3fb40..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/serverhook.d.ts +++ /dev/null @@ -1,136 +0,0 @@ -/** - * @alova/server 1.0.0 (https://alova.js.org) - * Document https://alova.js.org - * Copyright 2025 Scott hu. All Rights Reserved - * Licensed under MIT (git://github.com/alovajs/alova/blob/main/LICENSE) -*/ - -import { AlovaGenerics, Method, AlovaGlobalCacheAdapter } from 'alova'; -import { RateLimiterRes, IRateLimiterStoreOptions } from 'rate-limiter-flexible'; -import RateLimiterStoreAbstract from 'rate-limiter-flexible/lib/RateLimiterStoreAbstract.js'; -import { BackoffPolicy } from '@alova/shared'; - -type RequestHandler = (forceRequest?: boolean) => Promise; -declare class HookedMethod extends Method { - private handler; - constructor(entity: Method, requestHandler: RequestHandler); - send(forceRequest?: boolean): Promise; -} - -type StoreResult = [points: number, expireTime: number]; -interface LimitHandlerOptions { - /** storage key */ - key?: string | ((method: Method) => string); -} -/** - * Rate limit, there can only be a maximum of [points] requests within [duration] seconds - * - * Usage scenarios: - * 1. Request restrictions. For example, when node acts as an intermediate layer to request downstream services, under an API with serious resource consumption, it is restricted through IP to avoid consuming downstream server resources. - * 2. Prevent password brute force cracking. When the downstream server throws login errors multiple times in a row, restrict it by IP or user name. - * 3. As a sending limit for sendCaptcha, it prevents users from frequently sending verification codes. - */ -interface RateLimitOptions { - /** - * The maximum quantity that can be consumed within the duration - * @default 4 - */ - points?: number; - /** - * Points reset time, unit ms - * @default 4000 - */ - duration?: number; - /** - * Namespace, prevents conflicts when multiple limiters use the same storage medium - */ - keyPrefix?: string; - /** - * The following two parameters are consumption interval control - * */ - execEvenly?: boolean; - execEvenlyMinDelayMs?: number; - /** - * After reaching the rate limit, [blockDuration]ms will be extended. For example, if the password is incorrect 5 times within 1 hour, it will be locked for 24 hours. This 24 hours is this parameter. - */ - blockDuration?: number; - /** - * Custom storage adapter, defaults to methodObj.context.l2Cache if not set - */ - storage?: AlovaGlobalCacheAdapter; -} -declare class RateLimiterStore extends RateLimiterStoreAbstract { - protected storage: AlovaGlobalCacheAdapter; - constructor(storage: AlovaGlobalCacheAdapter, options: IRateLimiterStoreOptions); - /** - * parses raw data from store to RateLimiterRes object. - */ - _getRateLimiterRes(key: string | number, changedPoints: number, result: StoreResult): RateLimiterRes; - _upsert(key: string | number, points: number, msDuration: number, forceExpire?: boolean): Promise; - /** - * returns raw data by key or null if there is no key or expired. - */ - _get(key: string | number): Promise<{} | null>; - /** - * returns true on deleted, false if key is not found. - */ - _delete(key: string | number): Promise; -} -/** - * The method instance modified by rateLimit, its extension method corresponds to the method of creating an instance in rate-limit-flexible, and the key is the key specified by calling rateLimit. - * AlovaServerHook can currently only return unextended method types. It has not been changed to customizable returned extended method types. - */ -declare class LimitedMethod extends HookedMethod { - protected limiter: RateLimiterStore; - private keyGetter; - constructor(method: Method, limiterKey: string | ((method: Method) => string), limiter: RateLimiterStore); - private getLimiterKey; - /** - * Get RateLimiterRes or null. - */ - get(options?: { - [key: string]: any; - }): Promise; - /** - * Set points by key. - */ - set(points: number, msDuration: number): Promise; - /** - * @param points default is 1 - */ - consume(points?: number): Promise; - /** - * Increase number of consumed points in current duration. - * @param points penalty points - */ - penalty(points: number): Promise; - /** - * Decrease number of consumed points in current duration. - * @param points reward points - */ - reward(points: number): Promise; - /** - * Block key for ms. - */ - block(msDuration: number): Promise; - /** - * Reset consumed points. - */ - delete(): Promise; -} -declare function createRateLimiter(options?: RateLimitOptions): (method: Method, handlerOptions?: LimitHandlerOptions) => LimitedMethod; - -interface RetryOptions { - /** - * The maximum number of retries. it can also be set as a function that returns a boolean to dynamically determine whether to continue retry. - * @default 3 - */ - retry?: number | ((error: Error) => boolean); - /** - * backoff policy - */ - backoff?: BackoffPolicy; -} -declare const retry: (method: Method, options?: RetryOptions) => HookedMethod; - -export { HookedMethod, createRateLimiter, retry }; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/react.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/react.d.ts deleted file mode 100644 index b4c3d94..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/react.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { StatesExportHelper, StatesHook } from 'alova'; -import { Dispatch, SetStateAction } from 'react'; - -export type ReactHookExportType = StatesExportHelper<{ - name: 'React'; - State: ReactState; - Computed: any[]; - Watched: T; - StateExport: T; - ComputedExport: T; -}>; - -export type ReactState = [D, Dispatch>, D?]; -export type ReactHookType = StatesHook>; -declare const reactHook: ReactHookType; - -export default reactHook; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/solid.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/solid.d.ts deleted file mode 100644 index 42250ef..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/solid.d.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { StatesExportHelper, StatesHook } from 'alova'; -import { Accessor, Setter } from 'solid-js'; - -// define SolidHooks export type -export type SolidHookExportType = StatesExportHelper<{ - name: 'Solid'; - State: SolidState; - Computed: SolidState; - Watched: Accessor; - StateExport: Accessor; - ComputedExport: Accessor; -}>; - -// solid state type -export type SolidState = [Accessor, Setter]; -// solid hook type -export type SolidHookType = StatesHook>; - -declare const solidHook: SolidHookType; -export default solidHook; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/svelte.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/svelte.d.ts deleted file mode 100644 index 3391e1c..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/svelte.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { StatesExportHelper, StatesHook } from 'alova'; -import { Readable, Writable } from 'svelte/store'; - -export type SvelteHookExportType = StatesExportHelper<{ - name: 'Svelte'; - State: Writable; - Computed: Readable; - Watched: Writable; - StateExport: Writable; - ComputedExport: Readable; -}>; - -export type SvelteHookType = StatesHook>; -declare const svelteHook: SvelteHookType; - -export default svelteHook; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/vue-demi.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/vue-demi.d.ts deleted file mode 100644 index 07e0c12..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/vue-demi.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { StatesExportHelper, StatesHook } from 'alova'; -import { ComputedRef, Ref, WatchSource } from 'vue-demi'; - -export type VueDemiHookExportType = StatesExportHelper<{ - name: 'VueDemi'; - State: Ref; - Computed: ComputedRef; - Watched: WatchSource | object; - StateExport: Ref; - ComputedExport: ComputedRef; -}>; - -export type VueHookType = StatesHook>; -declare const vueHook: VueHookType; - -export default vueHook; diff --git a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/vue.d.ts b/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/vue.d.ts deleted file mode 100644 index 97db0be..0000000 --- a/node_modules/.pnpm/alova@3.2.10/node_modules/alova/typings/stateshook/vue.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { StatesExportHelper, StatesHook } from 'alova'; -import { ComputedRef, Ref, WatchSource } from 'vue'; - -export type VueHookExportType = StatesExportHelper<{ - name: 'Vue'; - State: Ref; - Computed: ComputedRef; - Watched: WatchSource | object; - StateExport: Ref; - ComputedExport: ComputedRef; -}>; - -export type VueHookType = StatesHook>; -declare const vueHook: VueHookType; - -export default vueHook; diff --git a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/LICENSE.md b/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/LICENSE.md deleted file mode 100644 index 2027e8d..0000000 --- a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/LICENSE.md +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Evan Wallace - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/README.md b/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/README.md deleted file mode 100644 index 93863d1..0000000 --- a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# esbuild - -This is a JavaScript bundler and minifier. See https://github.com/evanw/esbuild and the [JavaScript API documentation](https://esbuild.github.io/api/) for details. diff --git a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/bin/esbuild b/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/bin/esbuild deleted file mode 100644 index 971ac09..0000000 --- a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/bin/esbuild +++ /dev/null @@ -1,220 +0,0 @@ -#!/usr/bin/env node -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// lib/npm/node-platform.ts -var fs = require("fs"); -var os = require("os"); -var path = require("path"); -var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; -var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; -var packageDarwin_arm64 = "@esbuild/darwin-arm64"; -var packageDarwin_x64 = "@esbuild/darwin-x64"; -var knownWindowsPackages = { - "win32 arm64 LE": "@esbuild/win32-arm64", - "win32 ia32 LE": "@esbuild/win32-ia32", - "win32 x64 LE": "@esbuild/win32-x64" -}; -var knownUnixlikePackages = { - "aix ppc64 BE": "@esbuild/aix-ppc64", - "android arm64 LE": "@esbuild/android-arm64", - "darwin arm64 LE": "@esbuild/darwin-arm64", - "darwin x64 LE": "@esbuild/darwin-x64", - "freebsd arm64 LE": "@esbuild/freebsd-arm64", - "freebsd x64 LE": "@esbuild/freebsd-x64", - "linux arm LE": "@esbuild/linux-arm", - "linux arm64 LE": "@esbuild/linux-arm64", - "linux ia32 LE": "@esbuild/linux-ia32", - "linux mips64el LE": "@esbuild/linux-mips64el", - "linux ppc64 LE": "@esbuild/linux-ppc64", - "linux riscv64 LE": "@esbuild/linux-riscv64", - "linux s390x BE": "@esbuild/linux-s390x", - "linux x64 LE": "@esbuild/linux-x64", - "linux loong64 LE": "@esbuild/linux-loong64", - "netbsd x64 LE": "@esbuild/netbsd-x64", - "openbsd x64 LE": "@esbuild/openbsd-x64", - "sunos x64 LE": "@esbuild/sunos-x64" -}; -var knownWebAssemblyFallbackPackages = { - "android arm LE": "@esbuild/android-arm", - "android x64 LE": "@esbuild/android-x64" -}; -function pkgAndSubpathForCurrentPlatform() { - let pkg; - let subpath; - let isWASM2 = false; - let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; - if (platformKey in knownWindowsPackages) { - pkg = knownWindowsPackages[platformKey]; - subpath = "esbuild.exe"; - } else if (platformKey in knownUnixlikePackages) { - pkg = knownUnixlikePackages[platformKey]; - subpath = "bin/esbuild"; - } else if (platformKey in knownWebAssemblyFallbackPackages) { - pkg = knownWebAssemblyFallbackPackages[platformKey]; - subpath = "bin/esbuild"; - isWASM2 = true; - } else { - throw new Error(`Unsupported platform: ${platformKey}`); - } - return { pkg, subpath, isWASM: isWASM2 }; -} -function pkgForSomeOtherPlatform() { - const libMainJS = require.resolve("esbuild"); - const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS))); - if (path.basename(nodeModulesDirectory) === "node_modules") { - for (const unixKey in knownUnixlikePackages) { - try { - const pkg = knownUnixlikePackages[unixKey]; - if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg; - } catch { - } - } - for (const windowsKey in knownWindowsPackages) { - try { - const pkg = knownWindowsPackages[windowsKey]; - if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg; - } catch { - } - } - } - return null; -} -function downloadedBinPath(pkg, subpath) { - const esbuildLibDir = path.dirname(require.resolve("esbuild")); - return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`); -} -function generateBinPath() { - if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { - if (!fs.existsSync(ESBUILD_BINARY_PATH)) { - console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); - } else { - return { binPath: ESBUILD_BINARY_PATH, isWASM: false }; - } - } - const { pkg, subpath, isWASM: isWASM2 } = pkgAndSubpathForCurrentPlatform(); - let binPath2; - try { - binPath2 = require.resolve(`${pkg}/${subpath}`); - } catch (e) { - binPath2 = downloadedBinPath(pkg, subpath); - if (!fs.existsSync(binPath2)) { - try { - require.resolve(pkg); - } catch { - const otherPkg = pkgForSomeOtherPlatform(); - if (otherPkg) { - let suggestions = ` -Specifically the "${otherPkg}" package is present but this platform -needs the "${pkg}" package instead. People often get into this -situation by installing esbuild on Windows or macOS and copying "node_modules" -into a Docker image that runs Linux, or by copying "node_modules" between -Windows and WSL environments. - -If you are installing with npm, you can try not copying the "node_modules" -directory when you copy the files over, and running "npm ci" or "npm install" -on the destination platform after the copy. Or you could consider using yarn -instead of npm which has built-in support for installing a package on multiple -platforms simultaneously. - -If you are installing with yarn, you can try listing both this platform and the -other platform in your ".yarnrc.yml" file using the "supportedArchitectures" -feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures -Keep in mind that this means multiple copies of esbuild will be present. -`; - if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) { - suggestions = ` -Specifically the "${otherPkg}" package is present but this platform -needs the "${pkg}" package instead. People often get into this -situation by installing esbuild with npm running inside of Rosetta 2 and then -trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta -2 is Apple's on-the-fly x86_64-to-arm64 translation service). - -If you are installing with npm, you can try ensuring that both npm and node are -not running under Rosetta 2 and then reinstalling esbuild. This likely involves -changing how you installed npm and/or node. For example, installing node with -the universal installer here should work: https://nodejs.org/en/download/. Or -you could consider using yarn instead of npm which has built-in support for -installing a package on multiple platforms simultaneously. - -If you are installing with yarn, you can try listing both "arm64" and "x64" -in your ".yarnrc.yml" file using the "supportedArchitectures" feature: -https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures -Keep in mind that this means multiple copies of esbuild will be present. -`; - } - throw new Error(` -You installed esbuild for another platform than the one you're currently using. -This won't work because esbuild is written with native code and needs to -install a platform-specific binary executable. -${suggestions} -Another alternative is to use the "esbuild-wasm" package instead, which works -the same way on all platforms. But it comes with a heavy performance cost and -can sometimes be 10x slower than the "esbuild" package, so you may also not -want to do that. -`); - } - throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild. - -If you are installing esbuild with npm, make sure that you don't specify the -"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature -of "package.json" is used by esbuild to install the correct binary executable -for your current platform.`); - } - throw e; - } - } - if (/\.zip\//.test(binPath2)) { - let pnpapi; - try { - pnpapi = require("pnpapi"); - } catch (e) { - } - if (pnpapi) { - const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation; - const binTargetPath = path.join( - root, - "node_modules", - ".cache", - "esbuild", - `pnpapi-${pkg.replace("/", "-")}-${"0.21.5"}-${path.basename(subpath)}` - ); - if (!fs.existsSync(binTargetPath)) { - fs.mkdirSync(path.dirname(binTargetPath), { recursive: true }); - fs.copyFileSync(binPath2, binTargetPath); - fs.chmodSync(binTargetPath, 493); - } - return { binPath: binTargetPath, isWASM: isWASM2 }; - } - } - return { binPath: binPath2, isWASM: isWASM2 }; -} - -// lib/npm/node-shim.ts -var { binPath, isWASM } = generateBinPath(); -if (isWASM) { - require("child_process").execFileSync("node", [binPath].concat(process.argv.slice(2)), { stdio: "inherit" }); -} else { - require("child_process").execFileSync(binPath, process.argv.slice(2), { stdio: "inherit" }); -} diff --git a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/install.js b/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/install.js deleted file mode 100644 index d97764e..0000000 --- a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/install.js +++ /dev/null @@ -1,285 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); - -// lib/npm/node-platform.ts -var fs = require("fs"); -var os = require("os"); -var path = require("path"); -var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; -var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; -var knownWindowsPackages = { - "win32 arm64 LE": "@esbuild/win32-arm64", - "win32 ia32 LE": "@esbuild/win32-ia32", - "win32 x64 LE": "@esbuild/win32-x64" -}; -var knownUnixlikePackages = { - "aix ppc64 BE": "@esbuild/aix-ppc64", - "android arm64 LE": "@esbuild/android-arm64", - "darwin arm64 LE": "@esbuild/darwin-arm64", - "darwin x64 LE": "@esbuild/darwin-x64", - "freebsd arm64 LE": "@esbuild/freebsd-arm64", - "freebsd x64 LE": "@esbuild/freebsd-x64", - "linux arm LE": "@esbuild/linux-arm", - "linux arm64 LE": "@esbuild/linux-arm64", - "linux ia32 LE": "@esbuild/linux-ia32", - "linux mips64el LE": "@esbuild/linux-mips64el", - "linux ppc64 LE": "@esbuild/linux-ppc64", - "linux riscv64 LE": "@esbuild/linux-riscv64", - "linux s390x BE": "@esbuild/linux-s390x", - "linux x64 LE": "@esbuild/linux-x64", - "linux loong64 LE": "@esbuild/linux-loong64", - "netbsd x64 LE": "@esbuild/netbsd-x64", - "openbsd x64 LE": "@esbuild/openbsd-x64", - "sunos x64 LE": "@esbuild/sunos-x64" -}; -var knownWebAssemblyFallbackPackages = { - "android arm LE": "@esbuild/android-arm", - "android x64 LE": "@esbuild/android-x64" -}; -function pkgAndSubpathForCurrentPlatform() { - let pkg; - let subpath; - let isWASM = false; - let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; - if (platformKey in knownWindowsPackages) { - pkg = knownWindowsPackages[platformKey]; - subpath = "esbuild.exe"; - } else if (platformKey in knownUnixlikePackages) { - pkg = knownUnixlikePackages[platformKey]; - subpath = "bin/esbuild"; - } else if (platformKey in knownWebAssemblyFallbackPackages) { - pkg = knownWebAssemblyFallbackPackages[platformKey]; - subpath = "bin/esbuild"; - isWASM = true; - } else { - throw new Error(`Unsupported platform: ${platformKey}`); - } - return { pkg, subpath, isWASM }; -} -function downloadedBinPath(pkg, subpath) { - const esbuildLibDir = path.dirname(require.resolve("esbuild")); - return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`); -} - -// lib/npm/node-install.ts -var fs2 = require("fs"); -var os2 = require("os"); -var path2 = require("path"); -var zlib = require("zlib"); -var https = require("https"); -var child_process = require("child_process"); -var versionFromPackageJSON = require(path2.join(__dirname, "package.json")).version; -var toPath = path2.join(__dirname, "bin", "esbuild"); -var isToPathJS = true; -function validateBinaryVersion(...command) { - command.push("--version"); - let stdout; - try { - stdout = child_process.execFileSync(command.shift(), command, { - // Without this, this install script strangely crashes with the error - // "EACCES: permission denied, write" but only on Ubuntu Linux when node is - // installed from the Snap Store. This is not a problem when you download - // the official version of node. The problem appears to be that stderr - // (i.e. file descriptor 2) isn't writable? - // - // More info: - // - https://snapcraft.io/ (what the Snap Store is) - // - https://nodejs.org/dist/ (download the official version of node) - // - https://github.com/evanw/esbuild/issues/1711#issuecomment-1027554035 - // - stdio: "pipe" - }).toString().trim(); - } catch (err) { - if (os2.platform() === "darwin" && /_SecTrustEvaluateWithError/.test(err + "")) { - let os3 = "this version of macOS"; - try { - os3 = "macOS " + child_process.execFileSync("sw_vers", ["-productVersion"]).toString().trim(); - } catch { - } - throw new Error(`The "esbuild" package cannot be installed because ${os3} is too outdated. - -The Go compiler (which esbuild relies on) no longer supports ${os3}, -which means the "esbuild" binary executable can't be run. You can either: - - * Update your version of macOS to one that the Go compiler supports - * Use the "esbuild-wasm" package instead of the "esbuild" package - * Build esbuild yourself using an older version of the Go compiler -`); - } - throw err; - } - if (stdout !== versionFromPackageJSON) { - throw new Error(`Expected ${JSON.stringify(versionFromPackageJSON)} but got ${JSON.stringify(stdout)}`); - } -} -function isYarn() { - const { npm_config_user_agent } = process.env; - if (npm_config_user_agent) { - return /\byarn\//.test(npm_config_user_agent); - } - return false; -} -function fetch(url) { - return new Promise((resolve, reject) => { - https.get(url, (res) => { - if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location) - return fetch(res.headers.location).then(resolve, reject); - if (res.statusCode !== 200) - return reject(new Error(`Server responded with ${res.statusCode}`)); - let chunks = []; - res.on("data", (chunk) => chunks.push(chunk)); - res.on("end", () => resolve(Buffer.concat(chunks))); - }).on("error", reject); - }); -} -function extractFileFromTarGzip(buffer, subpath) { - try { - buffer = zlib.unzipSync(buffer); - } catch (err) { - throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`); - } - let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, ""); - let offset = 0; - subpath = `package/${subpath}`; - while (offset < buffer.length) { - let name = str(offset, 100); - let size = parseInt(str(offset + 124, 12), 8); - offset += 512; - if (!isNaN(size)) { - if (name === subpath) return buffer.subarray(offset, offset + size); - offset += size + 511 & ~511; - } - } - throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`); -} -function installUsingNPM(pkg, subpath, binPath) { - const env = { ...process.env, npm_config_global: void 0 }; - const esbuildLibDir = path2.dirname(require.resolve("esbuild")); - const installDir = path2.join(esbuildLibDir, "npm-install"); - fs2.mkdirSync(installDir); - try { - fs2.writeFileSync(path2.join(installDir, "package.json"), "{}"); - child_process.execSync( - `npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${versionFromPackageJSON}`, - { cwd: installDir, stdio: "pipe", env } - ); - const installedBinPath = path2.join(installDir, "node_modules", pkg, subpath); - fs2.renameSync(installedBinPath, binPath); - } finally { - try { - removeRecursive(installDir); - } catch { - } - } -} -function removeRecursive(dir) { - for (const entry of fs2.readdirSync(dir)) { - const entryPath = path2.join(dir, entry); - let stats; - try { - stats = fs2.lstatSync(entryPath); - } catch { - continue; - } - if (stats.isDirectory()) removeRecursive(entryPath); - else fs2.unlinkSync(entryPath); - } - fs2.rmdirSync(dir); -} -function applyManualBinaryPathOverride(overridePath) { - const pathString = JSON.stringify(overridePath); - fs2.writeFileSync(toPath, `#!/usr/bin/env node -require('child_process').execFileSync(${pathString}, process.argv.slice(2), { stdio: 'inherit' }); -`); - const libMain = path2.join(__dirname, "lib", "main.js"); - const code = fs2.readFileSync(libMain, "utf8"); - fs2.writeFileSync(libMain, `var ESBUILD_BINARY_PATH = ${pathString}; -${code}`); -} -function maybeOptimizePackage(binPath) { - if (os2.platform() !== "win32" && !isYarn()) { - const tempPath = path2.join(__dirname, "bin-esbuild"); - try { - fs2.linkSync(binPath, tempPath); - fs2.renameSync(tempPath, toPath); - isToPathJS = false; - fs2.unlinkSync(tempPath); - } catch { - } - } -} -async function downloadDirectlyFromNPM(pkg, subpath, binPath) { - const url = `https://registry.npmjs.org/${pkg}/-/${pkg.replace("@esbuild/", "")}-${versionFromPackageJSON}.tgz`; - console.error(`[esbuild] Trying to download ${JSON.stringify(url)}`); - try { - fs2.writeFileSync(binPath, extractFileFromTarGzip(await fetch(url), subpath)); - fs2.chmodSync(binPath, 493); - } catch (e) { - console.error(`[esbuild] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`); - throw e; - } -} -async function checkAndPreparePackage() { - if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { - if (!fs2.existsSync(ESBUILD_BINARY_PATH)) { - console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); - } else { - applyManualBinaryPathOverride(ESBUILD_BINARY_PATH); - return; - } - } - const { pkg, subpath } = pkgAndSubpathForCurrentPlatform(); - let binPath; - try { - binPath = require.resolve(`${pkg}/${subpath}`); - } catch (e) { - console.error(`[esbuild] Failed to find package "${pkg}" on the file system - -This can happen if you use the "--no-optional" flag. The "optionalDependencies" -package.json feature is used by esbuild to install the correct binary executable -for your current platform. This install script will now attempt to work around -this. If that fails, you need to remove the "--no-optional" flag to use esbuild. -`); - binPath = downloadedBinPath(pkg, subpath); - try { - console.error(`[esbuild] Trying to install package "${pkg}" using npm`); - installUsingNPM(pkg, subpath, binPath); - } catch (e2) { - console.error(`[esbuild] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`); - try { - await downloadDirectlyFromNPM(pkg, subpath, binPath); - } catch (e3) { - throw new Error(`Failed to install package "${pkg}"`); - } - } - } - maybeOptimizePackage(binPath); -} -checkAndPreparePackage().then(() => { - if (isToPathJS) { - validateBinaryVersion(process.execPath, toPath); - } else { - validateBinaryVersion(toPath); - } -}); diff --git a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/lib/main.d.ts b/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/lib/main.d.ts deleted file mode 100644 index d5c6ac9..0000000 --- a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/lib/main.d.ts +++ /dev/null @@ -1,705 +0,0 @@ -export type Platform = 'browser' | 'node' | 'neutral' -export type Format = 'iife' | 'cjs' | 'esm' -export type Loader = 'base64' | 'binary' | 'copy' | 'css' | 'dataurl' | 'default' | 'empty' | 'file' | 'js' | 'json' | 'jsx' | 'local-css' | 'text' | 'ts' | 'tsx' -export type LogLevel = 'verbose' | 'debug' | 'info' | 'warning' | 'error' | 'silent' -export type Charset = 'ascii' | 'utf8' -export type Drop = 'console' | 'debugger' - -interface CommonOptions { - /** Documentation: https://esbuild.github.io/api/#sourcemap */ - sourcemap?: boolean | 'linked' | 'inline' | 'external' | 'both' - /** Documentation: https://esbuild.github.io/api/#legal-comments */ - legalComments?: 'none' | 'inline' | 'eof' | 'linked' | 'external' - /** Documentation: https://esbuild.github.io/api/#source-root */ - sourceRoot?: string - /** Documentation: https://esbuild.github.io/api/#sources-content */ - sourcesContent?: boolean - - /** Documentation: https://esbuild.github.io/api/#format */ - format?: Format - /** Documentation: https://esbuild.github.io/api/#global-name */ - globalName?: string - /** Documentation: https://esbuild.github.io/api/#target */ - target?: string | string[] - /** Documentation: https://esbuild.github.io/api/#supported */ - supported?: Record - /** Documentation: https://esbuild.github.io/api/#platform */ - platform?: Platform - - /** Documentation: https://esbuild.github.io/api/#mangle-props */ - mangleProps?: RegExp - /** Documentation: https://esbuild.github.io/api/#mangle-props */ - reserveProps?: RegExp - /** Documentation: https://esbuild.github.io/api/#mangle-props */ - mangleQuoted?: boolean - /** Documentation: https://esbuild.github.io/api/#mangle-props */ - mangleCache?: Record - /** Documentation: https://esbuild.github.io/api/#drop */ - drop?: Drop[] - /** Documentation: https://esbuild.github.io/api/#drop-labels */ - dropLabels?: string[] - /** Documentation: https://esbuild.github.io/api/#minify */ - minify?: boolean - /** Documentation: https://esbuild.github.io/api/#minify */ - minifyWhitespace?: boolean - /** Documentation: https://esbuild.github.io/api/#minify */ - minifyIdentifiers?: boolean - /** Documentation: https://esbuild.github.io/api/#minify */ - minifySyntax?: boolean - /** Documentation: https://esbuild.github.io/api/#line-limit */ - lineLimit?: number - /** Documentation: https://esbuild.github.io/api/#charset */ - charset?: Charset - /** Documentation: https://esbuild.github.io/api/#tree-shaking */ - treeShaking?: boolean - /** Documentation: https://esbuild.github.io/api/#ignore-annotations */ - ignoreAnnotations?: boolean - - /** Documentation: https://esbuild.github.io/api/#jsx */ - jsx?: 'transform' | 'preserve' | 'automatic' - /** Documentation: https://esbuild.github.io/api/#jsx-factory */ - jsxFactory?: string - /** Documentation: https://esbuild.github.io/api/#jsx-fragment */ - jsxFragment?: string - /** Documentation: https://esbuild.github.io/api/#jsx-import-source */ - jsxImportSource?: string - /** Documentation: https://esbuild.github.io/api/#jsx-development */ - jsxDev?: boolean - /** Documentation: https://esbuild.github.io/api/#jsx-side-effects */ - jsxSideEffects?: boolean - - /** Documentation: https://esbuild.github.io/api/#define */ - define?: { [key: string]: string } - /** Documentation: https://esbuild.github.io/api/#pure */ - pure?: string[] - /** Documentation: https://esbuild.github.io/api/#keep-names */ - keepNames?: boolean - - /** Documentation: https://esbuild.github.io/api/#color */ - color?: boolean - /** Documentation: https://esbuild.github.io/api/#log-level */ - logLevel?: LogLevel - /** Documentation: https://esbuild.github.io/api/#log-limit */ - logLimit?: number - /** Documentation: https://esbuild.github.io/api/#log-override */ - logOverride?: Record - - /** Documentation: https://esbuild.github.io/api/#tsconfig-raw */ - tsconfigRaw?: string | TsconfigRaw -} - -export interface TsconfigRaw { - compilerOptions?: { - alwaysStrict?: boolean - baseUrl?: string - experimentalDecorators?: boolean - importsNotUsedAsValues?: 'remove' | 'preserve' | 'error' - jsx?: 'preserve' | 'react-native' | 'react' | 'react-jsx' | 'react-jsxdev' - jsxFactory?: string - jsxFragmentFactory?: string - jsxImportSource?: string - paths?: Record - preserveValueImports?: boolean - strict?: boolean - target?: string - useDefineForClassFields?: boolean - verbatimModuleSyntax?: boolean - } -} - -export interface BuildOptions extends CommonOptions { - /** Documentation: https://esbuild.github.io/api/#bundle */ - bundle?: boolean - /** Documentation: https://esbuild.github.io/api/#splitting */ - splitting?: boolean - /** Documentation: https://esbuild.github.io/api/#preserve-symlinks */ - preserveSymlinks?: boolean - /** Documentation: https://esbuild.github.io/api/#outfile */ - outfile?: string - /** Documentation: https://esbuild.github.io/api/#metafile */ - metafile?: boolean - /** Documentation: https://esbuild.github.io/api/#outdir */ - outdir?: string - /** Documentation: https://esbuild.github.io/api/#outbase */ - outbase?: string - /** Documentation: https://esbuild.github.io/api/#external */ - external?: string[] - /** Documentation: https://esbuild.github.io/api/#packages */ - packages?: 'external' - /** Documentation: https://esbuild.github.io/api/#alias */ - alias?: Record - /** Documentation: https://esbuild.github.io/api/#loader */ - loader?: { [ext: string]: Loader } - /** Documentation: https://esbuild.github.io/api/#resolve-extensions */ - resolveExtensions?: string[] - /** Documentation: https://esbuild.github.io/api/#main-fields */ - mainFields?: string[] - /** Documentation: https://esbuild.github.io/api/#conditions */ - conditions?: string[] - /** Documentation: https://esbuild.github.io/api/#write */ - write?: boolean - /** Documentation: https://esbuild.github.io/api/#allow-overwrite */ - allowOverwrite?: boolean - /** Documentation: https://esbuild.github.io/api/#tsconfig */ - tsconfig?: string - /** Documentation: https://esbuild.github.io/api/#out-extension */ - outExtension?: { [ext: string]: string } - /** Documentation: https://esbuild.github.io/api/#public-path */ - publicPath?: string - /** Documentation: https://esbuild.github.io/api/#entry-names */ - entryNames?: string - /** Documentation: https://esbuild.github.io/api/#chunk-names */ - chunkNames?: string - /** Documentation: https://esbuild.github.io/api/#asset-names */ - assetNames?: string - /** Documentation: https://esbuild.github.io/api/#inject */ - inject?: string[] - /** Documentation: https://esbuild.github.io/api/#banner */ - banner?: { [type: string]: string } - /** Documentation: https://esbuild.github.io/api/#footer */ - footer?: { [type: string]: string } - /** Documentation: https://esbuild.github.io/api/#entry-points */ - entryPoints?: string[] | Record | { in: string, out: string }[] - /** Documentation: https://esbuild.github.io/api/#stdin */ - stdin?: StdinOptions - /** Documentation: https://esbuild.github.io/plugins/ */ - plugins?: Plugin[] - /** Documentation: https://esbuild.github.io/api/#working-directory */ - absWorkingDir?: string - /** Documentation: https://esbuild.github.io/api/#node-paths */ - nodePaths?: string[]; // The "NODE_PATH" variable from Node.js -} - -export interface StdinOptions { - contents: string | Uint8Array - resolveDir?: string - sourcefile?: string - loader?: Loader -} - -export interface Message { - id: string - pluginName: string - text: string - location: Location | null - notes: Note[] - - /** - * Optional user-specified data that is passed through unmodified. You can - * use this to stash the original error, for example. - */ - detail: any -} - -export interface Note { - text: string - location: Location | null -} - -export interface Location { - file: string - namespace: string - /** 1-based */ - line: number - /** 0-based, in bytes */ - column: number - /** in bytes */ - length: number - lineText: string - suggestion: string -} - -export interface OutputFile { - path: string - contents: Uint8Array - hash: string - /** "contents" as text (changes automatically with "contents") */ - readonly text: string -} - -export interface BuildResult { - errors: Message[] - warnings: Message[] - /** Only when "write: false" */ - outputFiles: OutputFile[] | (ProvidedOptions['write'] extends false ? never : undefined) - /** Only when "metafile: true" */ - metafile: Metafile | (ProvidedOptions['metafile'] extends true ? never : undefined) - /** Only when "mangleCache" is present */ - mangleCache: Record | (ProvidedOptions['mangleCache'] extends Object ? never : undefined) -} - -export interface BuildFailure extends Error { - errors: Message[] - warnings: Message[] -} - -/** Documentation: https://esbuild.github.io/api/#serve-arguments */ -export interface ServeOptions { - port?: number - host?: string - servedir?: string - keyfile?: string - certfile?: string - fallback?: string - onRequest?: (args: ServeOnRequestArgs) => void -} - -export interface ServeOnRequestArgs { - remoteAddress: string - method: string - path: string - status: number - /** The time to generate the response, not to send it */ - timeInMS: number -} - -/** Documentation: https://esbuild.github.io/api/#serve-return-values */ -export interface ServeResult { - port: number - host: string -} - -export interface TransformOptions extends CommonOptions { - /** Documentation: https://esbuild.github.io/api/#sourcefile */ - sourcefile?: string - /** Documentation: https://esbuild.github.io/api/#loader */ - loader?: Loader - /** Documentation: https://esbuild.github.io/api/#banner */ - banner?: string - /** Documentation: https://esbuild.github.io/api/#footer */ - footer?: string -} - -export interface TransformResult { - code: string - map: string - warnings: Message[] - /** Only when "mangleCache" is present */ - mangleCache: Record | (ProvidedOptions['mangleCache'] extends Object ? never : undefined) - /** Only when "legalComments" is "external" */ - legalComments: string | (ProvidedOptions['legalComments'] extends 'external' ? never : undefined) -} - -export interface TransformFailure extends Error { - errors: Message[] - warnings: Message[] -} - -export interface Plugin { - name: string - setup: (build: PluginBuild) => (void | Promise) -} - -export interface PluginBuild { - /** Documentation: https://esbuild.github.io/plugins/#build-options */ - initialOptions: BuildOptions - - /** Documentation: https://esbuild.github.io/plugins/#resolve */ - resolve(path: string, options?: ResolveOptions): Promise - - /** Documentation: https://esbuild.github.io/plugins/#on-start */ - onStart(callback: () => - (OnStartResult | null | void | Promise)): void - - /** Documentation: https://esbuild.github.io/plugins/#on-end */ - onEnd(callback: (result: BuildResult) => - (OnEndResult | null | void | Promise)): void - - /** Documentation: https://esbuild.github.io/plugins/#on-resolve */ - onResolve(options: OnResolveOptions, callback: (args: OnResolveArgs) => - (OnResolveResult | null | undefined | Promise)): void - - /** Documentation: https://esbuild.github.io/plugins/#on-load */ - onLoad(options: OnLoadOptions, callback: (args: OnLoadArgs) => - (OnLoadResult | null | undefined | Promise)): void - - /** Documentation: https://esbuild.github.io/plugins/#on-dispose */ - onDispose(callback: () => void): void - - // This is a full copy of the esbuild library in case you need it - esbuild: { - context: typeof context, - build: typeof build, - buildSync: typeof buildSync, - transform: typeof transform, - transformSync: typeof transformSync, - formatMessages: typeof formatMessages, - formatMessagesSync: typeof formatMessagesSync, - analyzeMetafile: typeof analyzeMetafile, - analyzeMetafileSync: typeof analyzeMetafileSync, - initialize: typeof initialize, - version: typeof version, - } -} - -/** Documentation: https://esbuild.github.io/plugins/#resolve-options */ -export interface ResolveOptions { - pluginName?: string - importer?: string - namespace?: string - resolveDir?: string - kind?: ImportKind - pluginData?: any - with?: Record -} - -/** Documentation: https://esbuild.github.io/plugins/#resolve-results */ -export interface ResolveResult { - errors: Message[] - warnings: Message[] - - path: string - external: boolean - sideEffects: boolean - namespace: string - suffix: string - pluginData: any -} - -export interface OnStartResult { - errors?: PartialMessage[] - warnings?: PartialMessage[] -} - -export interface OnEndResult { - errors?: PartialMessage[] - warnings?: PartialMessage[] -} - -/** Documentation: https://esbuild.github.io/plugins/#on-resolve-options */ -export interface OnResolveOptions { - filter: RegExp - namespace?: string -} - -/** Documentation: https://esbuild.github.io/plugins/#on-resolve-arguments */ -export interface OnResolveArgs { - path: string - importer: string - namespace: string - resolveDir: string - kind: ImportKind - pluginData: any - with: Record -} - -export type ImportKind = - | 'entry-point' - - // JS - | 'import-statement' - | 'require-call' - | 'dynamic-import' - | 'require-resolve' - - // CSS - | 'import-rule' - | 'composes-from' - | 'url-token' - -/** Documentation: https://esbuild.github.io/plugins/#on-resolve-results */ -export interface OnResolveResult { - pluginName?: string - - errors?: PartialMessage[] - warnings?: PartialMessage[] - - path?: string - external?: boolean - sideEffects?: boolean - namespace?: string - suffix?: string - pluginData?: any - - watchFiles?: string[] - watchDirs?: string[] -} - -/** Documentation: https://esbuild.github.io/plugins/#on-load-options */ -export interface OnLoadOptions { - filter: RegExp - namespace?: string -} - -/** Documentation: https://esbuild.github.io/plugins/#on-load-arguments */ -export interface OnLoadArgs { - path: string - namespace: string - suffix: string - pluginData: any - with: Record -} - -/** Documentation: https://esbuild.github.io/plugins/#on-load-results */ -export interface OnLoadResult { - pluginName?: string - - errors?: PartialMessage[] - warnings?: PartialMessage[] - - contents?: string | Uint8Array - resolveDir?: string - loader?: Loader - pluginData?: any - - watchFiles?: string[] - watchDirs?: string[] -} - -export interface PartialMessage { - id?: string - pluginName?: string - text?: string - location?: Partial | null - notes?: PartialNote[] - detail?: any -} - -export interface PartialNote { - text?: string - location?: Partial | null -} - -/** Documentation: https://esbuild.github.io/api/#metafile */ -export interface Metafile { - inputs: { - [path: string]: { - bytes: number - imports: { - path: string - kind: ImportKind - external?: boolean - original?: string - with?: Record - }[] - format?: 'cjs' | 'esm' - with?: Record - } - } - outputs: { - [path: string]: { - bytes: number - inputs: { - [path: string]: { - bytesInOutput: number - } - } - imports: { - path: string - kind: ImportKind | 'file-loader' - external?: boolean - }[] - exports: string[] - entryPoint?: string - cssBundle?: string - } - } -} - -export interface FormatMessagesOptions { - kind: 'error' | 'warning' - color?: boolean - terminalWidth?: number -} - -export interface AnalyzeMetafileOptions { - color?: boolean - verbose?: boolean -} - -export interface WatchOptions { -} - -export interface BuildContext { - /** Documentation: https://esbuild.github.io/api/#rebuild */ - rebuild(): Promise> - - /** Documentation: https://esbuild.github.io/api/#watch */ - watch(options?: WatchOptions): Promise - - /** Documentation: https://esbuild.github.io/api/#serve */ - serve(options?: ServeOptions): Promise - - cancel(): Promise - dispose(): Promise -} - -// This is a TypeScript type-level function which replaces any keys in "In" -// that aren't in "Out" with "never". We use this to reject properties with -// typos in object literals. See: https://stackoverflow.com/questions/49580725 -type SameShape = In & { [Key in Exclude]: never } - -/** - * This function invokes the "esbuild" command-line tool for you. It returns a - * promise that either resolves with a "BuildResult" object or rejects with a - * "BuildFailure" object. - * - * - Works in node: yes - * - Works in browser: yes - * - * Documentation: https://esbuild.github.io/api/#build - */ -export declare function build(options: SameShape): Promise> - -/** - * This is the advanced long-running form of "build" that supports additional - * features such as watch mode and a local development server. - * - * - Works in node: yes - * - Works in browser: no - * - * Documentation: https://esbuild.github.io/api/#build - */ -export declare function context(options: SameShape): Promise> - -/** - * This function transforms a single JavaScript file. It can be used to minify - * JavaScript, convert TypeScript/JSX to JavaScript, or convert newer JavaScript - * to older JavaScript. It returns a promise that is either resolved with a - * "TransformResult" object or rejected with a "TransformFailure" object. - * - * - Works in node: yes - * - Works in browser: yes - * - * Documentation: https://esbuild.github.io/api/#transform - */ -export declare function transform(input: string | Uint8Array, options?: SameShape): Promise> - -/** - * Converts log messages to formatted message strings suitable for printing in - * the terminal. This allows you to reuse the built-in behavior of esbuild's - * log message formatter. This is a batch-oriented API for efficiency. - * - * - Works in node: yes - * - Works in browser: yes - */ -export declare function formatMessages(messages: PartialMessage[], options: FormatMessagesOptions): Promise - -/** - * Pretty-prints an analysis of the metafile JSON to a string. This is just for - * convenience to be able to match esbuild's pretty-printing exactly. If you want - * to customize it, you can just inspect the data in the metafile yourself. - * - * - Works in node: yes - * - Works in browser: yes - * - * Documentation: https://esbuild.github.io/api/#analyze - */ -export declare function analyzeMetafile(metafile: Metafile | string, options?: AnalyzeMetafileOptions): Promise - -/** - * A synchronous version of "build". - * - * - Works in node: yes - * - Works in browser: no - * - * Documentation: https://esbuild.github.io/api/#build - */ -export declare function buildSync(options: SameShape): BuildResult - -/** - * A synchronous version of "transform". - * - * - Works in node: yes - * - Works in browser: no - * - * Documentation: https://esbuild.github.io/api/#transform - */ -export declare function transformSync(input: string | Uint8Array, options?: SameShape): TransformResult - -/** - * A synchronous version of "formatMessages". - * - * - Works in node: yes - * - Works in browser: no - */ -export declare function formatMessagesSync(messages: PartialMessage[], options: FormatMessagesOptions): string[] - -/** - * A synchronous version of "analyzeMetafile". - * - * - Works in node: yes - * - Works in browser: no - * - * Documentation: https://esbuild.github.io/api/#analyze - */ -export declare function analyzeMetafileSync(metafile: Metafile | string, options?: AnalyzeMetafileOptions): string - -/** - * This configures the browser-based version of esbuild. It is necessary to - * call this first and wait for the returned promise to be resolved before - * making other API calls when using esbuild in the browser. - * - * - Works in node: yes - * - Works in browser: yes ("options" is required) - * - * Documentation: https://esbuild.github.io/api/#browser - */ -export declare function initialize(options: InitializeOptions): Promise - -export interface InitializeOptions { - /** - * The URL of the "esbuild.wasm" file. This must be provided when running - * esbuild in the browser. - */ - wasmURL?: string | URL - - /** - * The result of calling "new WebAssembly.Module(buffer)" where "buffer" - * is a typed array or ArrayBuffer containing the binary code of the - * "esbuild.wasm" file. - * - * You can use this as an alternative to "wasmURL" for environments where it's - * not possible to download the WebAssembly module. - */ - wasmModule?: WebAssembly.Module - - /** - * By default esbuild runs the WebAssembly-based browser API in a web worker - * to avoid blocking the UI thread. This can be disabled by setting "worker" - * to false. - */ - worker?: boolean -} - -export let version: string - -// Call this function to terminate esbuild's child process. The child process -// is not terminated and re-created after each API call because it's more -// efficient to keep it around when there are multiple API calls. -// -// In node this happens automatically before the parent node process exits. So -// you only need to call this if you know you will not make any more esbuild -// API calls and you want to clean up resources. -// -// Unlike node, Deno lacks the necessary APIs to clean up child processes -// automatically. You must manually call stop() in Deno when you're done -// using esbuild or Deno will continue running forever. -// -// Another reason you might want to call this is if you are using esbuild from -// within a Deno test. Deno fails tests that create a child process without -// killing it before the test ends, so you have to call this function (and -// await the returned promise) in every Deno test that uses esbuild. -export declare function stop(): Promise - -// Note: These declarations exist to avoid type errors when you omit "dom" from -// "lib" in your "tsconfig.json" file. TypeScript confusingly declares the -// global "WebAssembly" type in "lib.dom.d.ts" even though it has nothing to do -// with the browser DOM and is present in many non-browser JavaScript runtimes -// (e.g. node and deno). Declaring it here allows esbuild's API to be used in -// these scenarios. -// -// There's an open issue about getting this problem corrected (although these -// declarations will need to remain even if this is fixed for backward -// compatibility with older TypeScript versions): -// -// https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/826 -// -declare global { - namespace WebAssembly { - interface Module { - } - } - interface URL { - } -} diff --git a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/lib/main.js b/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/lib/main.js deleted file mode 100644 index 555613c..0000000 --- a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/lib/main.js +++ /dev/null @@ -1,2239 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// lib/npm/node.ts -var node_exports = {}; -__export(node_exports, { - analyzeMetafile: () => analyzeMetafile, - analyzeMetafileSync: () => analyzeMetafileSync, - build: () => build, - buildSync: () => buildSync, - context: () => context, - default: () => node_default, - formatMessages: () => formatMessages, - formatMessagesSync: () => formatMessagesSync, - initialize: () => initialize, - stop: () => stop, - transform: () => transform, - transformSync: () => transformSync, - version: () => version -}); -module.exports = __toCommonJS(node_exports); - -// lib/shared/stdio_protocol.ts -function encodePacket(packet) { - let visit = (value) => { - if (value === null) { - bb.write8(0); - } else if (typeof value === "boolean") { - bb.write8(1); - bb.write8(+value); - } else if (typeof value === "number") { - bb.write8(2); - bb.write32(value | 0); - } else if (typeof value === "string") { - bb.write8(3); - bb.write(encodeUTF8(value)); - } else if (value instanceof Uint8Array) { - bb.write8(4); - bb.write(value); - } else if (value instanceof Array) { - bb.write8(5); - bb.write32(value.length); - for (let item of value) { - visit(item); - } - } else { - let keys = Object.keys(value); - bb.write8(6); - bb.write32(keys.length); - for (let key of keys) { - bb.write(encodeUTF8(key)); - visit(value[key]); - } - } - }; - let bb = new ByteBuffer(); - bb.write32(0); - bb.write32(packet.id << 1 | +!packet.isRequest); - visit(packet.value); - writeUInt32LE(bb.buf, bb.len - 4, 0); - return bb.buf.subarray(0, bb.len); -} -function decodePacket(bytes) { - let visit = () => { - switch (bb.read8()) { - case 0: - return null; - case 1: - return !!bb.read8(); - case 2: - return bb.read32(); - case 3: - return decodeUTF8(bb.read()); - case 4: - return bb.read(); - case 5: { - let count = bb.read32(); - let value2 = []; - for (let i = 0; i < count; i++) { - value2.push(visit()); - } - return value2; - } - case 6: { - let count = bb.read32(); - let value2 = {}; - for (let i = 0; i < count; i++) { - value2[decodeUTF8(bb.read())] = visit(); - } - return value2; - } - default: - throw new Error("Invalid packet"); - } - }; - let bb = new ByteBuffer(bytes); - let id = bb.read32(); - let isRequest = (id & 1) === 0; - id >>>= 1; - let value = visit(); - if (bb.ptr !== bytes.length) { - throw new Error("Invalid packet"); - } - return { id, isRequest, value }; -} -var ByteBuffer = class { - constructor(buf = new Uint8Array(1024)) { - this.buf = buf; - this.len = 0; - this.ptr = 0; - } - _write(delta) { - if (this.len + delta > this.buf.length) { - let clone = new Uint8Array((this.len + delta) * 2); - clone.set(this.buf); - this.buf = clone; - } - this.len += delta; - return this.len - delta; - } - write8(value) { - let offset = this._write(1); - this.buf[offset] = value; - } - write32(value) { - let offset = this._write(4); - writeUInt32LE(this.buf, value, offset); - } - write(bytes) { - let offset = this._write(4 + bytes.length); - writeUInt32LE(this.buf, bytes.length, offset); - this.buf.set(bytes, offset + 4); - } - _read(delta) { - if (this.ptr + delta > this.buf.length) { - throw new Error("Invalid packet"); - } - this.ptr += delta; - return this.ptr - delta; - } - read8() { - return this.buf[this._read(1)]; - } - read32() { - return readUInt32LE(this.buf, this._read(4)); - } - read() { - let length = this.read32(); - let bytes = new Uint8Array(length); - let ptr = this._read(bytes.length); - bytes.set(this.buf.subarray(ptr, ptr + length)); - return bytes; - } -}; -var encodeUTF8; -var decodeUTF8; -var encodeInvariant; -if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined") { - let encoder = new TextEncoder(); - let decoder = new TextDecoder(); - encodeUTF8 = (text) => encoder.encode(text); - decodeUTF8 = (bytes) => decoder.decode(bytes); - encodeInvariant = 'new TextEncoder().encode("")'; -} else if (typeof Buffer !== "undefined") { - encodeUTF8 = (text) => Buffer.from(text); - decodeUTF8 = (bytes) => { - let { buffer, byteOffset, byteLength } = bytes; - return Buffer.from(buffer, byteOffset, byteLength).toString(); - }; - encodeInvariant = 'Buffer.from("")'; -} else { - throw new Error("No UTF-8 codec found"); -} -if (!(encodeUTF8("") instanceof Uint8Array)) - throw new Error(`Invariant violation: "${encodeInvariant} instanceof Uint8Array" is incorrectly false - -This indicates that your JavaScript environment is broken. You cannot use -esbuild in this environment because esbuild relies on this invariant. This -is not a problem with esbuild. You need to fix your environment instead. -`); -function readUInt32LE(buffer, offset) { - return buffer[offset++] | buffer[offset++] << 8 | buffer[offset++] << 16 | buffer[offset++] << 24; -} -function writeUInt32LE(buffer, value, offset) { - buffer[offset++] = value; - buffer[offset++] = value >> 8; - buffer[offset++] = value >> 16; - buffer[offset++] = value >> 24; -} - -// lib/shared/common.ts -var quote = JSON.stringify; -var buildLogLevelDefault = "warning"; -var transformLogLevelDefault = "silent"; -function validateTarget(target) { - validateStringValue(target, "target"); - if (target.indexOf(",") >= 0) throw new Error(`Invalid target: ${target}`); - return target; -} -var canBeAnything = () => null; -var mustBeBoolean = (value) => typeof value === "boolean" ? null : "a boolean"; -var mustBeString = (value) => typeof value === "string" ? null : "a string"; -var mustBeRegExp = (value) => value instanceof RegExp ? null : "a RegExp object"; -var mustBeInteger = (value) => typeof value === "number" && value === (value | 0) ? null : "an integer"; -var mustBeFunction = (value) => typeof value === "function" ? null : "a function"; -var mustBeArray = (value) => Array.isArray(value) ? null : "an array"; -var mustBeObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? null : "an object"; -var mustBeEntryPoints = (value) => typeof value === "object" && value !== null ? null : "an array or an object"; -var mustBeWebAssemblyModule = (value) => value instanceof WebAssembly.Module ? null : "a WebAssembly.Module"; -var mustBeObjectOrNull = (value) => typeof value === "object" && !Array.isArray(value) ? null : "an object or null"; -var mustBeStringOrBoolean = (value) => typeof value === "string" || typeof value === "boolean" ? null : "a string or a boolean"; -var mustBeStringOrObject = (value) => typeof value === "string" || typeof value === "object" && value !== null && !Array.isArray(value) ? null : "a string or an object"; -var mustBeStringOrArray = (value) => typeof value === "string" || Array.isArray(value) ? null : "a string or an array"; -var mustBeStringOrUint8Array = (value) => typeof value === "string" || value instanceof Uint8Array ? null : "a string or a Uint8Array"; -var mustBeStringOrURL = (value) => typeof value === "string" || value instanceof URL ? null : "a string or a URL"; -function getFlag(object, keys, key, mustBeFn) { - let value = object[key]; - keys[key + ""] = true; - if (value === void 0) return void 0; - let mustBe = mustBeFn(value); - if (mustBe !== null) throw new Error(`${quote(key)} must be ${mustBe}`); - return value; -} -function checkForInvalidFlags(object, keys, where) { - for (let key in object) { - if (!(key in keys)) { - throw new Error(`Invalid option ${where}: ${quote(key)}`); - } - } -} -function validateInitializeOptions(options) { - let keys = /* @__PURE__ */ Object.create(null); - let wasmURL = getFlag(options, keys, "wasmURL", mustBeStringOrURL); - let wasmModule = getFlag(options, keys, "wasmModule", mustBeWebAssemblyModule); - let worker = getFlag(options, keys, "worker", mustBeBoolean); - checkForInvalidFlags(options, keys, "in initialize() call"); - return { - wasmURL, - wasmModule, - worker - }; -} -function validateMangleCache(mangleCache) { - let validated; - if (mangleCache !== void 0) { - validated = /* @__PURE__ */ Object.create(null); - for (let key in mangleCache) { - let value = mangleCache[key]; - if (typeof value === "string" || value === false) { - validated[key] = value; - } else { - throw new Error(`Expected ${quote(key)} in mangle cache to map to either a string or false`); - } - } - } - return validated; -} -function pushLogFlags(flags, options, keys, isTTY2, logLevelDefault) { - let color = getFlag(options, keys, "color", mustBeBoolean); - let logLevel = getFlag(options, keys, "logLevel", mustBeString); - let logLimit = getFlag(options, keys, "logLimit", mustBeInteger); - if (color !== void 0) flags.push(`--color=${color}`); - else if (isTTY2) flags.push(`--color=true`); - flags.push(`--log-level=${logLevel || logLevelDefault}`); - flags.push(`--log-limit=${logLimit || 0}`); -} -function validateStringValue(value, what, key) { - if (typeof value !== "string") { - throw new Error(`Expected value for ${what}${key !== void 0 ? " " + quote(key) : ""} to be a string, got ${typeof value} instead`); - } - return value; -} -function pushCommonFlags(flags, options, keys) { - let legalComments = getFlag(options, keys, "legalComments", mustBeString); - let sourceRoot = getFlag(options, keys, "sourceRoot", mustBeString); - let sourcesContent = getFlag(options, keys, "sourcesContent", mustBeBoolean); - let target = getFlag(options, keys, "target", mustBeStringOrArray); - let format = getFlag(options, keys, "format", mustBeString); - let globalName = getFlag(options, keys, "globalName", mustBeString); - let mangleProps = getFlag(options, keys, "mangleProps", mustBeRegExp); - let reserveProps = getFlag(options, keys, "reserveProps", mustBeRegExp); - let mangleQuoted = getFlag(options, keys, "mangleQuoted", mustBeBoolean); - let minify = getFlag(options, keys, "minify", mustBeBoolean); - let minifySyntax = getFlag(options, keys, "minifySyntax", mustBeBoolean); - let minifyWhitespace = getFlag(options, keys, "minifyWhitespace", mustBeBoolean); - let minifyIdentifiers = getFlag(options, keys, "minifyIdentifiers", mustBeBoolean); - let lineLimit = getFlag(options, keys, "lineLimit", mustBeInteger); - let drop = getFlag(options, keys, "drop", mustBeArray); - let dropLabels = getFlag(options, keys, "dropLabels", mustBeArray); - let charset = getFlag(options, keys, "charset", mustBeString); - let treeShaking = getFlag(options, keys, "treeShaking", mustBeBoolean); - let ignoreAnnotations = getFlag(options, keys, "ignoreAnnotations", mustBeBoolean); - let jsx = getFlag(options, keys, "jsx", mustBeString); - let jsxFactory = getFlag(options, keys, "jsxFactory", mustBeString); - let jsxFragment = getFlag(options, keys, "jsxFragment", mustBeString); - let jsxImportSource = getFlag(options, keys, "jsxImportSource", mustBeString); - let jsxDev = getFlag(options, keys, "jsxDev", mustBeBoolean); - let jsxSideEffects = getFlag(options, keys, "jsxSideEffects", mustBeBoolean); - let define = getFlag(options, keys, "define", mustBeObject); - let logOverride = getFlag(options, keys, "logOverride", mustBeObject); - let supported = getFlag(options, keys, "supported", mustBeObject); - let pure = getFlag(options, keys, "pure", mustBeArray); - let keepNames = getFlag(options, keys, "keepNames", mustBeBoolean); - let platform = getFlag(options, keys, "platform", mustBeString); - let tsconfigRaw = getFlag(options, keys, "tsconfigRaw", mustBeStringOrObject); - if (legalComments) flags.push(`--legal-comments=${legalComments}`); - if (sourceRoot !== void 0) flags.push(`--source-root=${sourceRoot}`); - if (sourcesContent !== void 0) flags.push(`--sources-content=${sourcesContent}`); - if (target) { - if (Array.isArray(target)) flags.push(`--target=${Array.from(target).map(validateTarget).join(",")}`); - else flags.push(`--target=${validateTarget(target)}`); - } - if (format) flags.push(`--format=${format}`); - if (globalName) flags.push(`--global-name=${globalName}`); - if (platform) flags.push(`--platform=${platform}`); - if (tsconfigRaw) flags.push(`--tsconfig-raw=${typeof tsconfigRaw === "string" ? tsconfigRaw : JSON.stringify(tsconfigRaw)}`); - if (minify) flags.push("--minify"); - if (minifySyntax) flags.push("--minify-syntax"); - if (minifyWhitespace) flags.push("--minify-whitespace"); - if (minifyIdentifiers) flags.push("--minify-identifiers"); - if (lineLimit) flags.push(`--line-limit=${lineLimit}`); - if (charset) flags.push(`--charset=${charset}`); - if (treeShaking !== void 0) flags.push(`--tree-shaking=${treeShaking}`); - if (ignoreAnnotations) flags.push(`--ignore-annotations`); - if (drop) for (let what of drop) flags.push(`--drop:${validateStringValue(what, "drop")}`); - if (dropLabels) flags.push(`--drop-labels=${Array.from(dropLabels).map((what) => validateStringValue(what, "dropLabels")).join(",")}`); - if (mangleProps) flags.push(`--mangle-props=${mangleProps.source}`); - if (reserveProps) flags.push(`--reserve-props=${reserveProps.source}`); - if (mangleQuoted !== void 0) flags.push(`--mangle-quoted=${mangleQuoted}`); - if (jsx) flags.push(`--jsx=${jsx}`); - if (jsxFactory) flags.push(`--jsx-factory=${jsxFactory}`); - if (jsxFragment) flags.push(`--jsx-fragment=${jsxFragment}`); - if (jsxImportSource) flags.push(`--jsx-import-source=${jsxImportSource}`); - if (jsxDev) flags.push(`--jsx-dev`); - if (jsxSideEffects) flags.push(`--jsx-side-effects`); - if (define) { - for (let key in define) { - if (key.indexOf("=") >= 0) throw new Error(`Invalid define: ${key}`); - flags.push(`--define:${key}=${validateStringValue(define[key], "define", key)}`); - } - } - if (logOverride) { - for (let key in logOverride) { - if (key.indexOf("=") >= 0) throw new Error(`Invalid log override: ${key}`); - flags.push(`--log-override:${key}=${validateStringValue(logOverride[key], "log override", key)}`); - } - } - if (supported) { - for (let key in supported) { - if (key.indexOf("=") >= 0) throw new Error(`Invalid supported: ${key}`); - const value = supported[key]; - if (typeof value !== "boolean") throw new Error(`Expected value for supported ${quote(key)} to be a boolean, got ${typeof value} instead`); - flags.push(`--supported:${key}=${value}`); - } - } - if (pure) for (let fn of pure) flags.push(`--pure:${validateStringValue(fn, "pure")}`); - if (keepNames) flags.push(`--keep-names`); -} -function flagsForBuildOptions(callName, options, isTTY2, logLevelDefault, writeDefault) { - var _a2; - let flags = []; - let entries = []; - let keys = /* @__PURE__ */ Object.create(null); - let stdinContents = null; - let stdinResolveDir = null; - pushLogFlags(flags, options, keys, isTTY2, logLevelDefault); - pushCommonFlags(flags, options, keys); - let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean); - let bundle = getFlag(options, keys, "bundle", mustBeBoolean); - let splitting = getFlag(options, keys, "splitting", mustBeBoolean); - let preserveSymlinks = getFlag(options, keys, "preserveSymlinks", mustBeBoolean); - let metafile = getFlag(options, keys, "metafile", mustBeBoolean); - let outfile = getFlag(options, keys, "outfile", mustBeString); - let outdir = getFlag(options, keys, "outdir", mustBeString); - let outbase = getFlag(options, keys, "outbase", mustBeString); - let tsconfig = getFlag(options, keys, "tsconfig", mustBeString); - let resolveExtensions = getFlag(options, keys, "resolveExtensions", mustBeArray); - let nodePathsInput = getFlag(options, keys, "nodePaths", mustBeArray); - let mainFields = getFlag(options, keys, "mainFields", mustBeArray); - let conditions = getFlag(options, keys, "conditions", mustBeArray); - let external = getFlag(options, keys, "external", mustBeArray); - let packages = getFlag(options, keys, "packages", mustBeString); - let alias = getFlag(options, keys, "alias", mustBeObject); - let loader = getFlag(options, keys, "loader", mustBeObject); - let outExtension = getFlag(options, keys, "outExtension", mustBeObject); - let publicPath = getFlag(options, keys, "publicPath", mustBeString); - let entryNames = getFlag(options, keys, "entryNames", mustBeString); - let chunkNames = getFlag(options, keys, "chunkNames", mustBeString); - let assetNames = getFlag(options, keys, "assetNames", mustBeString); - let inject = getFlag(options, keys, "inject", mustBeArray); - let banner = getFlag(options, keys, "banner", mustBeObject); - let footer = getFlag(options, keys, "footer", mustBeObject); - let entryPoints = getFlag(options, keys, "entryPoints", mustBeEntryPoints); - let absWorkingDir = getFlag(options, keys, "absWorkingDir", mustBeString); - let stdin = getFlag(options, keys, "stdin", mustBeObject); - let write = (_a2 = getFlag(options, keys, "write", mustBeBoolean)) != null ? _a2 : writeDefault; - let allowOverwrite = getFlag(options, keys, "allowOverwrite", mustBeBoolean); - let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject); - keys.plugins = true; - checkForInvalidFlags(options, keys, `in ${callName}() call`); - if (sourcemap) flags.push(`--sourcemap${sourcemap === true ? "" : `=${sourcemap}`}`); - if (bundle) flags.push("--bundle"); - if (allowOverwrite) flags.push("--allow-overwrite"); - if (splitting) flags.push("--splitting"); - if (preserveSymlinks) flags.push("--preserve-symlinks"); - if (metafile) flags.push(`--metafile`); - if (outfile) flags.push(`--outfile=${outfile}`); - if (outdir) flags.push(`--outdir=${outdir}`); - if (outbase) flags.push(`--outbase=${outbase}`); - if (tsconfig) flags.push(`--tsconfig=${tsconfig}`); - if (packages) flags.push(`--packages=${packages}`); - if (resolveExtensions) { - let values = []; - for (let value of resolveExtensions) { - validateStringValue(value, "resolve extension"); - if (value.indexOf(",") >= 0) throw new Error(`Invalid resolve extension: ${value}`); - values.push(value); - } - flags.push(`--resolve-extensions=${values.join(",")}`); - } - if (publicPath) flags.push(`--public-path=${publicPath}`); - if (entryNames) flags.push(`--entry-names=${entryNames}`); - if (chunkNames) flags.push(`--chunk-names=${chunkNames}`); - if (assetNames) flags.push(`--asset-names=${assetNames}`); - if (mainFields) { - let values = []; - for (let value of mainFields) { - validateStringValue(value, "main field"); - if (value.indexOf(",") >= 0) throw new Error(`Invalid main field: ${value}`); - values.push(value); - } - flags.push(`--main-fields=${values.join(",")}`); - } - if (conditions) { - let values = []; - for (let value of conditions) { - validateStringValue(value, "condition"); - if (value.indexOf(",") >= 0) throw new Error(`Invalid condition: ${value}`); - values.push(value); - } - flags.push(`--conditions=${values.join(",")}`); - } - if (external) for (let name of external) flags.push(`--external:${validateStringValue(name, "external")}`); - if (alias) { - for (let old in alias) { - if (old.indexOf("=") >= 0) throw new Error(`Invalid package name in alias: ${old}`); - flags.push(`--alias:${old}=${validateStringValue(alias[old], "alias", old)}`); - } - } - if (banner) { - for (let type in banner) { - if (type.indexOf("=") >= 0) throw new Error(`Invalid banner file type: ${type}`); - flags.push(`--banner:${type}=${validateStringValue(banner[type], "banner", type)}`); - } - } - if (footer) { - for (let type in footer) { - if (type.indexOf("=") >= 0) throw new Error(`Invalid footer file type: ${type}`); - flags.push(`--footer:${type}=${validateStringValue(footer[type], "footer", type)}`); - } - } - if (inject) for (let path3 of inject) flags.push(`--inject:${validateStringValue(path3, "inject")}`); - if (loader) { - for (let ext in loader) { - if (ext.indexOf("=") >= 0) throw new Error(`Invalid loader extension: ${ext}`); - flags.push(`--loader:${ext}=${validateStringValue(loader[ext], "loader", ext)}`); - } - } - if (outExtension) { - for (let ext in outExtension) { - if (ext.indexOf("=") >= 0) throw new Error(`Invalid out extension: ${ext}`); - flags.push(`--out-extension:${ext}=${validateStringValue(outExtension[ext], "out extension", ext)}`); - } - } - if (entryPoints) { - if (Array.isArray(entryPoints)) { - for (let i = 0, n = entryPoints.length; i < n; i++) { - let entryPoint = entryPoints[i]; - if (typeof entryPoint === "object" && entryPoint !== null) { - let entryPointKeys = /* @__PURE__ */ Object.create(null); - let input = getFlag(entryPoint, entryPointKeys, "in", mustBeString); - let output = getFlag(entryPoint, entryPointKeys, "out", mustBeString); - checkForInvalidFlags(entryPoint, entryPointKeys, "in entry point at index " + i); - if (input === void 0) throw new Error('Missing property "in" for entry point at index ' + i); - if (output === void 0) throw new Error('Missing property "out" for entry point at index ' + i); - entries.push([output, input]); - } else { - entries.push(["", validateStringValue(entryPoint, "entry point at index " + i)]); - } - } - } else { - for (let key in entryPoints) { - entries.push([key, validateStringValue(entryPoints[key], "entry point", key)]); - } - } - } - if (stdin) { - let stdinKeys = /* @__PURE__ */ Object.create(null); - let contents = getFlag(stdin, stdinKeys, "contents", mustBeStringOrUint8Array); - let resolveDir = getFlag(stdin, stdinKeys, "resolveDir", mustBeString); - let sourcefile = getFlag(stdin, stdinKeys, "sourcefile", mustBeString); - let loader2 = getFlag(stdin, stdinKeys, "loader", mustBeString); - checkForInvalidFlags(stdin, stdinKeys, 'in "stdin" object'); - if (sourcefile) flags.push(`--sourcefile=${sourcefile}`); - if (loader2) flags.push(`--loader=${loader2}`); - if (resolveDir) stdinResolveDir = resolveDir; - if (typeof contents === "string") stdinContents = encodeUTF8(contents); - else if (contents instanceof Uint8Array) stdinContents = contents; - } - let nodePaths = []; - if (nodePathsInput) { - for (let value of nodePathsInput) { - value += ""; - nodePaths.push(value); - } - } - return { - entries, - flags, - write, - stdinContents, - stdinResolveDir, - absWorkingDir, - nodePaths, - mangleCache: validateMangleCache(mangleCache) - }; -} -function flagsForTransformOptions(callName, options, isTTY2, logLevelDefault) { - let flags = []; - let keys = /* @__PURE__ */ Object.create(null); - pushLogFlags(flags, options, keys, isTTY2, logLevelDefault); - pushCommonFlags(flags, options, keys); - let sourcemap = getFlag(options, keys, "sourcemap", mustBeStringOrBoolean); - let sourcefile = getFlag(options, keys, "sourcefile", mustBeString); - let loader = getFlag(options, keys, "loader", mustBeString); - let banner = getFlag(options, keys, "banner", mustBeString); - let footer = getFlag(options, keys, "footer", mustBeString); - let mangleCache = getFlag(options, keys, "mangleCache", mustBeObject); - checkForInvalidFlags(options, keys, `in ${callName}() call`); - if (sourcemap) flags.push(`--sourcemap=${sourcemap === true ? "external" : sourcemap}`); - if (sourcefile) flags.push(`--sourcefile=${sourcefile}`); - if (loader) flags.push(`--loader=${loader}`); - if (banner) flags.push(`--banner=${banner}`); - if (footer) flags.push(`--footer=${footer}`); - return { - flags, - mangleCache: validateMangleCache(mangleCache) - }; -} -function createChannel(streamIn) { - const requestCallbacksByKey = {}; - const closeData = { didClose: false, reason: "" }; - let responseCallbacks = {}; - let nextRequestID = 0; - let nextBuildKey = 0; - let stdout = new Uint8Array(16 * 1024); - let stdoutUsed = 0; - let readFromStdout = (chunk) => { - let limit = stdoutUsed + chunk.length; - if (limit > stdout.length) { - let swap = new Uint8Array(limit * 2); - swap.set(stdout); - stdout = swap; - } - stdout.set(chunk, stdoutUsed); - stdoutUsed += chunk.length; - let offset = 0; - while (offset + 4 <= stdoutUsed) { - let length = readUInt32LE(stdout, offset); - if (offset + 4 + length > stdoutUsed) { - break; - } - offset += 4; - handleIncomingPacket(stdout.subarray(offset, offset + length)); - offset += length; - } - if (offset > 0) { - stdout.copyWithin(0, offset, stdoutUsed); - stdoutUsed -= offset; - } - }; - let afterClose = (error) => { - closeData.didClose = true; - if (error) closeData.reason = ": " + (error.message || error); - const text = "The service was stopped" + closeData.reason; - for (let id in responseCallbacks) { - responseCallbacks[id](text, null); - } - responseCallbacks = {}; - }; - let sendRequest = (refs, value, callback) => { - if (closeData.didClose) return callback("The service is no longer running" + closeData.reason, null); - let id = nextRequestID++; - responseCallbacks[id] = (error, response) => { - try { - callback(error, response); - } finally { - if (refs) refs.unref(); - } - }; - if (refs) refs.ref(); - streamIn.writeToStdin(encodePacket({ id, isRequest: true, value })); - }; - let sendResponse = (id, value) => { - if (closeData.didClose) throw new Error("The service is no longer running" + closeData.reason); - streamIn.writeToStdin(encodePacket({ id, isRequest: false, value })); - }; - let handleRequest = async (id, request) => { - try { - if (request.command === "ping") { - sendResponse(id, {}); - return; - } - if (typeof request.key === "number") { - const requestCallbacks = requestCallbacksByKey[request.key]; - if (!requestCallbacks) { - return; - } - const callback = requestCallbacks[request.command]; - if (callback) { - await callback(id, request); - return; - } - } - throw new Error(`Invalid command: ` + request.command); - } catch (e) { - const errors = [extractErrorMessageV8(e, streamIn, null, void 0, "")]; - try { - sendResponse(id, { errors }); - } catch { - } - } - }; - let isFirstPacket = true; - let handleIncomingPacket = (bytes) => { - if (isFirstPacket) { - isFirstPacket = false; - let binaryVersion = String.fromCharCode(...bytes); - if (binaryVersion !== "0.21.5") { - throw new Error(`Cannot start service: Host version "${"0.21.5"}" does not match binary version ${quote(binaryVersion)}`); - } - return; - } - let packet = decodePacket(bytes); - if (packet.isRequest) { - handleRequest(packet.id, packet.value); - } else { - let callback = responseCallbacks[packet.id]; - delete responseCallbacks[packet.id]; - if (packet.value.error) callback(packet.value.error, {}); - else callback(null, packet.value); - } - }; - let buildOrContext = ({ callName, refs, options, isTTY: isTTY2, defaultWD: defaultWD2, callback }) => { - let refCount = 0; - const buildKey = nextBuildKey++; - const requestCallbacks = {}; - const buildRefs = { - ref() { - if (++refCount === 1) { - if (refs) refs.ref(); - } - }, - unref() { - if (--refCount === 0) { - delete requestCallbacksByKey[buildKey]; - if (refs) refs.unref(); - } - } - }; - requestCallbacksByKey[buildKey] = requestCallbacks; - buildRefs.ref(); - buildOrContextImpl( - callName, - buildKey, - sendRequest, - sendResponse, - buildRefs, - streamIn, - requestCallbacks, - options, - isTTY2, - defaultWD2, - (err, res) => { - try { - callback(err, res); - } finally { - buildRefs.unref(); - } - } - ); - }; - let transform2 = ({ callName, refs, input, options, isTTY: isTTY2, fs: fs3, callback }) => { - const details = createObjectStash(); - let start = (inputPath) => { - try { - if (typeof input !== "string" && !(input instanceof Uint8Array)) - throw new Error('The input to "transform" must be a string or a Uint8Array'); - let { - flags, - mangleCache - } = flagsForTransformOptions(callName, options, isTTY2, transformLogLevelDefault); - let request = { - command: "transform", - flags, - inputFS: inputPath !== null, - input: inputPath !== null ? encodeUTF8(inputPath) : typeof input === "string" ? encodeUTF8(input) : input - }; - if (mangleCache) request.mangleCache = mangleCache; - sendRequest(refs, request, (error, response) => { - if (error) return callback(new Error(error), null); - let errors = replaceDetailsInMessages(response.errors, details); - let warnings = replaceDetailsInMessages(response.warnings, details); - let outstanding = 1; - let next = () => { - if (--outstanding === 0) { - let result = { - warnings, - code: response.code, - map: response.map, - mangleCache: void 0, - legalComments: void 0 - }; - if ("legalComments" in response) result.legalComments = response == null ? void 0 : response.legalComments; - if (response.mangleCache) result.mangleCache = response == null ? void 0 : response.mangleCache; - callback(null, result); - } - }; - if (errors.length > 0) return callback(failureErrorWithLog("Transform failed", errors, warnings), null); - if (response.codeFS) { - outstanding++; - fs3.readFile(response.code, (err, contents) => { - if (err !== null) { - callback(err, null); - } else { - response.code = contents; - next(); - } - }); - } - if (response.mapFS) { - outstanding++; - fs3.readFile(response.map, (err, contents) => { - if (err !== null) { - callback(err, null); - } else { - response.map = contents; - next(); - } - }); - } - next(); - }); - } catch (e) { - let flags = []; - try { - pushLogFlags(flags, options, {}, isTTY2, transformLogLevelDefault); - } catch { - } - const error = extractErrorMessageV8(e, streamIn, details, void 0, ""); - sendRequest(refs, { command: "error", flags, error }, () => { - error.detail = details.load(error.detail); - callback(failureErrorWithLog("Transform failed", [error], []), null); - }); - } - }; - if ((typeof input === "string" || input instanceof Uint8Array) && input.length > 1024 * 1024) { - let next = start; - start = () => fs3.writeFile(input, next); - } - start(null); - }; - let formatMessages2 = ({ callName, refs, messages, options, callback }) => { - if (!options) throw new Error(`Missing second argument in ${callName}() call`); - let keys = {}; - let kind = getFlag(options, keys, "kind", mustBeString); - let color = getFlag(options, keys, "color", mustBeBoolean); - let terminalWidth = getFlag(options, keys, "terminalWidth", mustBeInteger); - checkForInvalidFlags(options, keys, `in ${callName}() call`); - if (kind === void 0) throw new Error(`Missing "kind" in ${callName}() call`); - if (kind !== "error" && kind !== "warning") throw new Error(`Expected "kind" to be "error" or "warning" in ${callName}() call`); - let request = { - command: "format-msgs", - messages: sanitizeMessages(messages, "messages", null, "", terminalWidth), - isWarning: kind === "warning" - }; - if (color !== void 0) request.color = color; - if (terminalWidth !== void 0) request.terminalWidth = terminalWidth; - sendRequest(refs, request, (error, response) => { - if (error) return callback(new Error(error), null); - callback(null, response.messages); - }); - }; - let analyzeMetafile2 = ({ callName, refs, metafile, options, callback }) => { - if (options === void 0) options = {}; - let keys = {}; - let color = getFlag(options, keys, "color", mustBeBoolean); - let verbose = getFlag(options, keys, "verbose", mustBeBoolean); - checkForInvalidFlags(options, keys, `in ${callName}() call`); - let request = { - command: "analyze-metafile", - metafile - }; - if (color !== void 0) request.color = color; - if (verbose !== void 0) request.verbose = verbose; - sendRequest(refs, request, (error, response) => { - if (error) return callback(new Error(error), null); - callback(null, response.result); - }); - }; - return { - readFromStdout, - afterClose, - service: { - buildOrContext, - transform: transform2, - formatMessages: formatMessages2, - analyzeMetafile: analyzeMetafile2 - } - }; -} -function buildOrContextImpl(callName, buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, options, isTTY2, defaultWD2, callback) { - const details = createObjectStash(); - const isContext = callName === "context"; - const handleError = (e, pluginName) => { - const flags = []; - try { - pushLogFlags(flags, options, {}, isTTY2, buildLogLevelDefault); - } catch { - } - const message = extractErrorMessageV8(e, streamIn, details, void 0, pluginName); - sendRequest(refs, { command: "error", flags, error: message }, () => { - message.detail = details.load(message.detail); - callback(failureErrorWithLog(isContext ? "Context failed" : "Build failed", [message], []), null); - }); - }; - let plugins; - if (typeof options === "object") { - const value = options.plugins; - if (value !== void 0) { - if (!Array.isArray(value)) return handleError(new Error(`"plugins" must be an array`), ""); - plugins = value; - } - } - if (plugins && plugins.length > 0) { - if (streamIn.isSync) return handleError(new Error("Cannot use plugins in synchronous API calls"), ""); - handlePlugins( - buildKey, - sendRequest, - sendResponse, - refs, - streamIn, - requestCallbacks, - options, - plugins, - details - ).then( - (result) => { - if (!result.ok) return handleError(result.error, result.pluginName); - try { - buildOrContextContinue(result.requestPlugins, result.runOnEndCallbacks, result.scheduleOnDisposeCallbacks); - } catch (e) { - handleError(e, ""); - } - }, - (e) => handleError(e, "") - ); - return; - } - try { - buildOrContextContinue(null, (result, done) => done([], []), () => { - }); - } catch (e) { - handleError(e, ""); - } - function buildOrContextContinue(requestPlugins, runOnEndCallbacks, scheduleOnDisposeCallbacks) { - const writeDefault = streamIn.hasFS; - const { - entries, - flags, - write, - stdinContents, - stdinResolveDir, - absWorkingDir, - nodePaths, - mangleCache - } = flagsForBuildOptions(callName, options, isTTY2, buildLogLevelDefault, writeDefault); - if (write && !streamIn.hasFS) throw new Error(`The "write" option is unavailable in this environment`); - const request = { - command: "build", - key: buildKey, - entries, - flags, - write, - stdinContents, - stdinResolveDir, - absWorkingDir: absWorkingDir || defaultWD2, - nodePaths, - context: isContext - }; - if (requestPlugins) request.plugins = requestPlugins; - if (mangleCache) request.mangleCache = mangleCache; - const buildResponseToResult = (response, callback2) => { - const result = { - errors: replaceDetailsInMessages(response.errors, details), - warnings: replaceDetailsInMessages(response.warnings, details), - outputFiles: void 0, - metafile: void 0, - mangleCache: void 0 - }; - const originalErrors = result.errors.slice(); - const originalWarnings = result.warnings.slice(); - if (response.outputFiles) result.outputFiles = response.outputFiles.map(convertOutputFiles); - if (response.metafile) result.metafile = JSON.parse(response.metafile); - if (response.mangleCache) result.mangleCache = response.mangleCache; - if (response.writeToStdout !== void 0) console.log(decodeUTF8(response.writeToStdout).replace(/\n$/, "")); - runOnEndCallbacks(result, (onEndErrors, onEndWarnings) => { - if (originalErrors.length > 0 || onEndErrors.length > 0) { - const error = failureErrorWithLog("Build failed", originalErrors.concat(onEndErrors), originalWarnings.concat(onEndWarnings)); - return callback2(error, null, onEndErrors, onEndWarnings); - } - callback2(null, result, onEndErrors, onEndWarnings); - }); - }; - let latestResultPromise; - let provideLatestResult; - if (isContext) - requestCallbacks["on-end"] = (id, request2) => new Promise((resolve) => { - buildResponseToResult(request2, (err, result, onEndErrors, onEndWarnings) => { - const response = { - errors: onEndErrors, - warnings: onEndWarnings - }; - if (provideLatestResult) provideLatestResult(err, result); - latestResultPromise = void 0; - provideLatestResult = void 0; - sendResponse(id, response); - resolve(); - }); - }); - sendRequest(refs, request, (error, response) => { - if (error) return callback(new Error(error), null); - if (!isContext) { - return buildResponseToResult(response, (err, res) => { - scheduleOnDisposeCallbacks(); - return callback(err, res); - }); - } - if (response.errors.length > 0) { - return callback(failureErrorWithLog("Context failed", response.errors, response.warnings), null); - } - let didDispose = false; - const result = { - rebuild: () => { - if (!latestResultPromise) latestResultPromise = new Promise((resolve, reject) => { - let settlePromise; - provideLatestResult = (err, result2) => { - if (!settlePromise) settlePromise = () => err ? reject(err) : resolve(result2); - }; - const triggerAnotherBuild = () => { - const request2 = { - command: "rebuild", - key: buildKey - }; - sendRequest(refs, request2, (error2, response2) => { - if (error2) { - reject(new Error(error2)); - } else if (settlePromise) { - settlePromise(); - } else { - triggerAnotherBuild(); - } - }); - }; - triggerAnotherBuild(); - }); - return latestResultPromise; - }, - watch: (options2 = {}) => new Promise((resolve, reject) => { - if (!streamIn.hasFS) throw new Error(`Cannot use the "watch" API in this environment`); - const keys = {}; - checkForInvalidFlags(options2, keys, `in watch() call`); - const request2 = { - command: "watch", - key: buildKey - }; - sendRequest(refs, request2, (error2) => { - if (error2) reject(new Error(error2)); - else resolve(void 0); - }); - }), - serve: (options2 = {}) => new Promise((resolve, reject) => { - if (!streamIn.hasFS) throw new Error(`Cannot use the "serve" API in this environment`); - const keys = {}; - const port = getFlag(options2, keys, "port", mustBeInteger); - const host = getFlag(options2, keys, "host", mustBeString); - const servedir = getFlag(options2, keys, "servedir", mustBeString); - const keyfile = getFlag(options2, keys, "keyfile", mustBeString); - const certfile = getFlag(options2, keys, "certfile", mustBeString); - const fallback = getFlag(options2, keys, "fallback", mustBeString); - const onRequest = getFlag(options2, keys, "onRequest", mustBeFunction); - checkForInvalidFlags(options2, keys, `in serve() call`); - const request2 = { - command: "serve", - key: buildKey, - onRequest: !!onRequest - }; - if (port !== void 0) request2.port = port; - if (host !== void 0) request2.host = host; - if (servedir !== void 0) request2.servedir = servedir; - if (keyfile !== void 0) request2.keyfile = keyfile; - if (certfile !== void 0) request2.certfile = certfile; - if (fallback !== void 0) request2.fallback = fallback; - sendRequest(refs, request2, (error2, response2) => { - if (error2) return reject(new Error(error2)); - if (onRequest) { - requestCallbacks["serve-request"] = (id, request3) => { - onRequest(request3.args); - sendResponse(id, {}); - }; - } - resolve(response2); - }); - }), - cancel: () => new Promise((resolve) => { - if (didDispose) return resolve(); - const request2 = { - command: "cancel", - key: buildKey - }; - sendRequest(refs, request2, () => { - resolve(); - }); - }), - dispose: () => new Promise((resolve) => { - if (didDispose) return resolve(); - didDispose = true; - const request2 = { - command: "dispose", - key: buildKey - }; - sendRequest(refs, request2, () => { - resolve(); - scheduleOnDisposeCallbacks(); - refs.unref(); - }); - }) - }; - refs.ref(); - callback(null, result); - }); - } -} -var handlePlugins = async (buildKey, sendRequest, sendResponse, refs, streamIn, requestCallbacks, initialOptions, plugins, details) => { - let onStartCallbacks = []; - let onEndCallbacks = []; - let onResolveCallbacks = {}; - let onLoadCallbacks = {}; - let onDisposeCallbacks = []; - let nextCallbackID = 0; - let i = 0; - let requestPlugins = []; - let isSetupDone = false; - plugins = [...plugins]; - for (let item of plugins) { - let keys = {}; - if (typeof item !== "object") throw new Error(`Plugin at index ${i} must be an object`); - const name = getFlag(item, keys, "name", mustBeString); - if (typeof name !== "string" || name === "") throw new Error(`Plugin at index ${i} is missing a name`); - try { - let setup = getFlag(item, keys, "setup", mustBeFunction); - if (typeof setup !== "function") throw new Error(`Plugin is missing a setup function`); - checkForInvalidFlags(item, keys, `on plugin ${quote(name)}`); - let plugin = { - name, - onStart: false, - onEnd: false, - onResolve: [], - onLoad: [] - }; - i++; - let resolve = (path3, options = {}) => { - if (!isSetupDone) throw new Error('Cannot call "resolve" before plugin setup has completed'); - if (typeof path3 !== "string") throw new Error(`The path to resolve must be a string`); - let keys2 = /* @__PURE__ */ Object.create(null); - let pluginName = getFlag(options, keys2, "pluginName", mustBeString); - let importer = getFlag(options, keys2, "importer", mustBeString); - let namespace = getFlag(options, keys2, "namespace", mustBeString); - let resolveDir = getFlag(options, keys2, "resolveDir", mustBeString); - let kind = getFlag(options, keys2, "kind", mustBeString); - let pluginData = getFlag(options, keys2, "pluginData", canBeAnything); - let importAttributes = getFlag(options, keys2, "with", mustBeObject); - checkForInvalidFlags(options, keys2, "in resolve() call"); - return new Promise((resolve2, reject) => { - const request = { - command: "resolve", - path: path3, - key: buildKey, - pluginName: name - }; - if (pluginName != null) request.pluginName = pluginName; - if (importer != null) request.importer = importer; - if (namespace != null) request.namespace = namespace; - if (resolveDir != null) request.resolveDir = resolveDir; - if (kind != null) request.kind = kind; - else throw new Error(`Must specify "kind" when calling "resolve"`); - if (pluginData != null) request.pluginData = details.store(pluginData); - if (importAttributes != null) request.with = sanitizeStringMap(importAttributes, "with"); - sendRequest(refs, request, (error, response) => { - if (error !== null) reject(new Error(error)); - else resolve2({ - errors: replaceDetailsInMessages(response.errors, details), - warnings: replaceDetailsInMessages(response.warnings, details), - path: response.path, - external: response.external, - sideEffects: response.sideEffects, - namespace: response.namespace, - suffix: response.suffix, - pluginData: details.load(response.pluginData) - }); - }); - }); - }; - let promise = setup({ - initialOptions, - resolve, - onStart(callback) { - let registeredText = `This error came from the "onStart" callback registered here:`; - let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onStart"); - onStartCallbacks.push({ name, callback, note: registeredNote }); - plugin.onStart = true; - }, - onEnd(callback) { - let registeredText = `This error came from the "onEnd" callback registered here:`; - let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onEnd"); - onEndCallbacks.push({ name, callback, note: registeredNote }); - plugin.onEnd = true; - }, - onResolve(options, callback) { - let registeredText = `This error came from the "onResolve" callback registered here:`; - let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onResolve"); - let keys2 = {}; - let filter = getFlag(options, keys2, "filter", mustBeRegExp); - let namespace = getFlag(options, keys2, "namespace", mustBeString); - checkForInvalidFlags(options, keys2, `in onResolve() call for plugin ${quote(name)}`); - if (filter == null) throw new Error(`onResolve() call is missing a filter`); - let id = nextCallbackID++; - onResolveCallbacks[id] = { name, callback, note: registeredNote }; - plugin.onResolve.push({ id, filter: filter.source, namespace: namespace || "" }); - }, - onLoad(options, callback) { - let registeredText = `This error came from the "onLoad" callback registered here:`; - let registeredNote = extractCallerV8(new Error(registeredText), streamIn, "onLoad"); - let keys2 = {}; - let filter = getFlag(options, keys2, "filter", mustBeRegExp); - let namespace = getFlag(options, keys2, "namespace", mustBeString); - checkForInvalidFlags(options, keys2, `in onLoad() call for plugin ${quote(name)}`); - if (filter == null) throw new Error(`onLoad() call is missing a filter`); - let id = nextCallbackID++; - onLoadCallbacks[id] = { name, callback, note: registeredNote }; - plugin.onLoad.push({ id, filter: filter.source, namespace: namespace || "" }); - }, - onDispose(callback) { - onDisposeCallbacks.push(callback); - }, - esbuild: streamIn.esbuild - }); - if (promise) await promise; - requestPlugins.push(plugin); - } catch (e) { - return { ok: false, error: e, pluginName: name }; - } - } - requestCallbacks["on-start"] = async (id, request) => { - let response = { errors: [], warnings: [] }; - await Promise.all(onStartCallbacks.map(async ({ name, callback, note }) => { - try { - let result = await callback(); - if (result != null) { - if (typeof result !== "object") throw new Error(`Expected onStart() callback in plugin ${quote(name)} to return an object`); - let keys = {}; - let errors = getFlag(result, keys, "errors", mustBeArray); - let warnings = getFlag(result, keys, "warnings", mustBeArray); - checkForInvalidFlags(result, keys, `from onStart() callback in plugin ${quote(name)}`); - if (errors != null) response.errors.push(...sanitizeMessages(errors, "errors", details, name, void 0)); - if (warnings != null) response.warnings.push(...sanitizeMessages(warnings, "warnings", details, name, void 0)); - } - } catch (e) { - response.errors.push(extractErrorMessageV8(e, streamIn, details, note && note(), name)); - } - })); - sendResponse(id, response); - }; - requestCallbacks["on-resolve"] = async (id, request) => { - let response = {}, name = "", callback, note; - for (let id2 of request.ids) { - try { - ({ name, callback, note } = onResolveCallbacks[id2]); - let result = await callback({ - path: request.path, - importer: request.importer, - namespace: request.namespace, - resolveDir: request.resolveDir, - kind: request.kind, - pluginData: details.load(request.pluginData), - with: request.with - }); - if (result != null) { - if (typeof result !== "object") throw new Error(`Expected onResolve() callback in plugin ${quote(name)} to return an object`); - let keys = {}; - let pluginName = getFlag(result, keys, "pluginName", mustBeString); - let path3 = getFlag(result, keys, "path", mustBeString); - let namespace = getFlag(result, keys, "namespace", mustBeString); - let suffix = getFlag(result, keys, "suffix", mustBeString); - let external = getFlag(result, keys, "external", mustBeBoolean); - let sideEffects = getFlag(result, keys, "sideEffects", mustBeBoolean); - let pluginData = getFlag(result, keys, "pluginData", canBeAnything); - let errors = getFlag(result, keys, "errors", mustBeArray); - let warnings = getFlag(result, keys, "warnings", mustBeArray); - let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray); - let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray); - checkForInvalidFlags(result, keys, `from onResolve() callback in plugin ${quote(name)}`); - response.id = id2; - if (pluginName != null) response.pluginName = pluginName; - if (path3 != null) response.path = path3; - if (namespace != null) response.namespace = namespace; - if (suffix != null) response.suffix = suffix; - if (external != null) response.external = external; - if (sideEffects != null) response.sideEffects = sideEffects; - if (pluginData != null) response.pluginData = details.store(pluginData); - if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0); - if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0); - if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles"); - if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs"); - break; - } - } catch (e) { - response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] }; - break; - } - } - sendResponse(id, response); - }; - requestCallbacks["on-load"] = async (id, request) => { - let response = {}, name = "", callback, note; - for (let id2 of request.ids) { - try { - ({ name, callback, note } = onLoadCallbacks[id2]); - let result = await callback({ - path: request.path, - namespace: request.namespace, - suffix: request.suffix, - pluginData: details.load(request.pluginData), - with: request.with - }); - if (result != null) { - if (typeof result !== "object") throw new Error(`Expected onLoad() callback in plugin ${quote(name)} to return an object`); - let keys = {}; - let pluginName = getFlag(result, keys, "pluginName", mustBeString); - let contents = getFlag(result, keys, "contents", mustBeStringOrUint8Array); - let resolveDir = getFlag(result, keys, "resolveDir", mustBeString); - let pluginData = getFlag(result, keys, "pluginData", canBeAnything); - let loader = getFlag(result, keys, "loader", mustBeString); - let errors = getFlag(result, keys, "errors", mustBeArray); - let warnings = getFlag(result, keys, "warnings", mustBeArray); - let watchFiles = getFlag(result, keys, "watchFiles", mustBeArray); - let watchDirs = getFlag(result, keys, "watchDirs", mustBeArray); - checkForInvalidFlags(result, keys, `from onLoad() callback in plugin ${quote(name)}`); - response.id = id2; - if (pluginName != null) response.pluginName = pluginName; - if (contents instanceof Uint8Array) response.contents = contents; - else if (contents != null) response.contents = encodeUTF8(contents); - if (resolveDir != null) response.resolveDir = resolveDir; - if (pluginData != null) response.pluginData = details.store(pluginData); - if (loader != null) response.loader = loader; - if (errors != null) response.errors = sanitizeMessages(errors, "errors", details, name, void 0); - if (warnings != null) response.warnings = sanitizeMessages(warnings, "warnings", details, name, void 0); - if (watchFiles != null) response.watchFiles = sanitizeStringArray(watchFiles, "watchFiles"); - if (watchDirs != null) response.watchDirs = sanitizeStringArray(watchDirs, "watchDirs"); - break; - } - } catch (e) { - response = { id: id2, errors: [extractErrorMessageV8(e, streamIn, details, note && note(), name)] }; - break; - } - } - sendResponse(id, response); - }; - let runOnEndCallbacks = (result, done) => done([], []); - if (onEndCallbacks.length > 0) { - runOnEndCallbacks = (result, done) => { - (async () => { - const onEndErrors = []; - const onEndWarnings = []; - for (const { name, callback, note } of onEndCallbacks) { - let newErrors; - let newWarnings; - try { - const value = await callback(result); - if (value != null) { - if (typeof value !== "object") throw new Error(`Expected onEnd() callback in plugin ${quote(name)} to return an object`); - let keys = {}; - let errors = getFlag(value, keys, "errors", mustBeArray); - let warnings = getFlag(value, keys, "warnings", mustBeArray); - checkForInvalidFlags(value, keys, `from onEnd() callback in plugin ${quote(name)}`); - if (errors != null) newErrors = sanitizeMessages(errors, "errors", details, name, void 0); - if (warnings != null) newWarnings = sanitizeMessages(warnings, "warnings", details, name, void 0); - } - } catch (e) { - newErrors = [extractErrorMessageV8(e, streamIn, details, note && note(), name)]; - } - if (newErrors) { - onEndErrors.push(...newErrors); - try { - result.errors.push(...newErrors); - } catch { - } - } - if (newWarnings) { - onEndWarnings.push(...newWarnings); - try { - result.warnings.push(...newWarnings); - } catch { - } - } - } - done(onEndErrors, onEndWarnings); - })(); - }; - } - let scheduleOnDisposeCallbacks = () => { - for (const cb of onDisposeCallbacks) { - setTimeout(() => cb(), 0); - } - }; - isSetupDone = true; - return { - ok: true, - requestPlugins, - runOnEndCallbacks, - scheduleOnDisposeCallbacks - }; -}; -function createObjectStash() { - const map = /* @__PURE__ */ new Map(); - let nextID = 0; - return { - load(id) { - return map.get(id); - }, - store(value) { - if (value === void 0) return -1; - const id = nextID++; - map.set(id, value); - return id; - } - }; -} -function extractCallerV8(e, streamIn, ident) { - let note; - let tried = false; - return () => { - if (tried) return note; - tried = true; - try { - let lines = (e.stack + "").split("\n"); - lines.splice(1, 1); - let location = parseStackLinesV8(streamIn, lines, ident); - if (location) { - note = { text: e.message, location }; - return note; - } - } catch { - } - }; -} -function extractErrorMessageV8(e, streamIn, stash, note, pluginName) { - let text = "Internal error"; - let location = null; - try { - text = (e && e.message || e) + ""; - } catch { - } - try { - location = parseStackLinesV8(streamIn, (e.stack + "").split("\n"), ""); - } catch { - } - return { id: "", pluginName, text, location, notes: note ? [note] : [], detail: stash ? stash.store(e) : -1 }; -} -function parseStackLinesV8(streamIn, lines, ident) { - let at = " at "; - if (streamIn.readFileSync && !lines[0].startsWith(at) && lines[1].startsWith(at)) { - for (let i = 1; i < lines.length; i++) { - let line = lines[i]; - if (!line.startsWith(at)) continue; - line = line.slice(at.length); - while (true) { - let match = /^(?:new |async )?\S+ \((.*)\)$/.exec(line); - if (match) { - line = match[1]; - continue; - } - match = /^eval at \S+ \((.*)\)(?:, \S+:\d+:\d+)?$/.exec(line); - if (match) { - line = match[1]; - continue; - } - match = /^(\S+):(\d+):(\d+)$/.exec(line); - if (match) { - let contents; - try { - contents = streamIn.readFileSync(match[1], "utf8"); - } catch { - break; - } - let lineText = contents.split(/\r\n|\r|\n|\u2028|\u2029/)[+match[2] - 1] || ""; - let column = +match[3] - 1; - let length = lineText.slice(column, column + ident.length) === ident ? ident.length : 0; - return { - file: match[1], - namespace: "file", - line: +match[2], - column: encodeUTF8(lineText.slice(0, column)).length, - length: encodeUTF8(lineText.slice(column, column + length)).length, - lineText: lineText + "\n" + lines.slice(1).join("\n"), - suggestion: "" - }; - } - break; - } - } - } - return null; -} -function failureErrorWithLog(text, errors, warnings) { - let limit = 5; - text += errors.length < 1 ? "" : ` with ${errors.length} error${errors.length < 2 ? "" : "s"}:` + errors.slice(0, limit + 1).map((e, i) => { - if (i === limit) return "\n..."; - if (!e.location) return ` -error: ${e.text}`; - let { file, line, column } = e.location; - let pluginText = e.pluginName ? `[plugin: ${e.pluginName}] ` : ""; - return ` -${file}:${line}:${column}: ERROR: ${pluginText}${e.text}`; - }).join(""); - let error = new Error(text); - for (const [key, value] of [["errors", errors], ["warnings", warnings]]) { - Object.defineProperty(error, key, { - configurable: true, - enumerable: true, - get: () => value, - set: (value2) => Object.defineProperty(error, key, { - configurable: true, - enumerable: true, - value: value2 - }) - }); - } - return error; -} -function replaceDetailsInMessages(messages, stash) { - for (const message of messages) { - message.detail = stash.load(message.detail); - } - return messages; -} -function sanitizeLocation(location, where, terminalWidth) { - if (location == null) return null; - let keys = {}; - let file = getFlag(location, keys, "file", mustBeString); - let namespace = getFlag(location, keys, "namespace", mustBeString); - let line = getFlag(location, keys, "line", mustBeInteger); - let column = getFlag(location, keys, "column", mustBeInteger); - let length = getFlag(location, keys, "length", mustBeInteger); - let lineText = getFlag(location, keys, "lineText", mustBeString); - let suggestion = getFlag(location, keys, "suggestion", mustBeString); - checkForInvalidFlags(location, keys, where); - if (lineText) { - const relevantASCII = lineText.slice( - 0, - (column && column > 0 ? column : 0) + (length && length > 0 ? length : 0) + (terminalWidth && terminalWidth > 0 ? terminalWidth : 80) - ); - if (!/[\x7F-\uFFFF]/.test(relevantASCII) && !/\n/.test(lineText)) { - lineText = relevantASCII; - } - } - return { - file: file || "", - namespace: namespace || "", - line: line || 0, - column: column || 0, - length: length || 0, - lineText: lineText || "", - suggestion: suggestion || "" - }; -} -function sanitizeMessages(messages, property, stash, fallbackPluginName, terminalWidth) { - let messagesClone = []; - let index = 0; - for (const message of messages) { - let keys = {}; - let id = getFlag(message, keys, "id", mustBeString); - let pluginName = getFlag(message, keys, "pluginName", mustBeString); - let text = getFlag(message, keys, "text", mustBeString); - let location = getFlag(message, keys, "location", mustBeObjectOrNull); - let notes = getFlag(message, keys, "notes", mustBeArray); - let detail = getFlag(message, keys, "detail", canBeAnything); - let where = `in element ${index} of "${property}"`; - checkForInvalidFlags(message, keys, where); - let notesClone = []; - if (notes) { - for (const note of notes) { - let noteKeys = {}; - let noteText = getFlag(note, noteKeys, "text", mustBeString); - let noteLocation = getFlag(note, noteKeys, "location", mustBeObjectOrNull); - checkForInvalidFlags(note, noteKeys, where); - notesClone.push({ - text: noteText || "", - location: sanitizeLocation(noteLocation, where, terminalWidth) - }); - } - } - messagesClone.push({ - id: id || "", - pluginName: pluginName || fallbackPluginName, - text: text || "", - location: sanitizeLocation(location, where, terminalWidth), - notes: notesClone, - detail: stash ? stash.store(detail) : -1 - }); - index++; - } - return messagesClone; -} -function sanitizeStringArray(values, property) { - const result = []; - for (const value of values) { - if (typeof value !== "string") throw new Error(`${quote(property)} must be an array of strings`); - result.push(value); - } - return result; -} -function sanitizeStringMap(map, property) { - const result = /* @__PURE__ */ Object.create(null); - for (const key in map) { - const value = map[key]; - if (typeof value !== "string") throw new Error(`key ${quote(key)} in object ${quote(property)} must be a string`); - result[key] = value; - } - return result; -} -function convertOutputFiles({ path: path3, contents, hash }) { - let text = null; - return { - path: path3, - contents, - hash, - get text() { - const binary = this.contents; - if (text === null || binary !== contents) { - contents = binary; - text = decodeUTF8(binary); - } - return text; - } - }; -} - -// lib/npm/node-platform.ts -var fs = require("fs"); -var os = require("os"); -var path = require("path"); -var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH; -var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild"; -var packageDarwin_arm64 = "@esbuild/darwin-arm64"; -var packageDarwin_x64 = "@esbuild/darwin-x64"; -var knownWindowsPackages = { - "win32 arm64 LE": "@esbuild/win32-arm64", - "win32 ia32 LE": "@esbuild/win32-ia32", - "win32 x64 LE": "@esbuild/win32-x64" -}; -var knownUnixlikePackages = { - "aix ppc64 BE": "@esbuild/aix-ppc64", - "android arm64 LE": "@esbuild/android-arm64", - "darwin arm64 LE": "@esbuild/darwin-arm64", - "darwin x64 LE": "@esbuild/darwin-x64", - "freebsd arm64 LE": "@esbuild/freebsd-arm64", - "freebsd x64 LE": "@esbuild/freebsd-x64", - "linux arm LE": "@esbuild/linux-arm", - "linux arm64 LE": "@esbuild/linux-arm64", - "linux ia32 LE": "@esbuild/linux-ia32", - "linux mips64el LE": "@esbuild/linux-mips64el", - "linux ppc64 LE": "@esbuild/linux-ppc64", - "linux riscv64 LE": "@esbuild/linux-riscv64", - "linux s390x BE": "@esbuild/linux-s390x", - "linux x64 LE": "@esbuild/linux-x64", - "linux loong64 LE": "@esbuild/linux-loong64", - "netbsd x64 LE": "@esbuild/netbsd-x64", - "openbsd x64 LE": "@esbuild/openbsd-x64", - "sunos x64 LE": "@esbuild/sunos-x64" -}; -var knownWebAssemblyFallbackPackages = { - "android arm LE": "@esbuild/android-arm", - "android x64 LE": "@esbuild/android-x64" -}; -function pkgAndSubpathForCurrentPlatform() { - let pkg; - let subpath; - let isWASM = false; - let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`; - if (platformKey in knownWindowsPackages) { - pkg = knownWindowsPackages[platformKey]; - subpath = "esbuild.exe"; - } else if (platformKey in knownUnixlikePackages) { - pkg = knownUnixlikePackages[platformKey]; - subpath = "bin/esbuild"; - } else if (platformKey in knownWebAssemblyFallbackPackages) { - pkg = knownWebAssemblyFallbackPackages[platformKey]; - subpath = "bin/esbuild"; - isWASM = true; - } else { - throw new Error(`Unsupported platform: ${platformKey}`); - } - return { pkg, subpath, isWASM }; -} -function pkgForSomeOtherPlatform() { - const libMainJS = require.resolve("esbuild"); - const nodeModulesDirectory = path.dirname(path.dirname(path.dirname(libMainJS))); - if (path.basename(nodeModulesDirectory) === "node_modules") { - for (const unixKey in knownUnixlikePackages) { - try { - const pkg = knownUnixlikePackages[unixKey]; - if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg; - } catch { - } - } - for (const windowsKey in knownWindowsPackages) { - try { - const pkg = knownWindowsPackages[windowsKey]; - if (fs.existsSync(path.join(nodeModulesDirectory, pkg))) return pkg; - } catch { - } - } - } - return null; -} -function downloadedBinPath(pkg, subpath) { - const esbuildLibDir = path.dirname(require.resolve("esbuild")); - return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`); -} -function generateBinPath() { - if (isValidBinaryPath(ESBUILD_BINARY_PATH)) { - if (!fs.existsSync(ESBUILD_BINARY_PATH)) { - console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`); - } else { - return { binPath: ESBUILD_BINARY_PATH, isWASM: false }; - } - } - const { pkg, subpath, isWASM } = pkgAndSubpathForCurrentPlatform(); - let binPath; - try { - binPath = require.resolve(`${pkg}/${subpath}`); - } catch (e) { - binPath = downloadedBinPath(pkg, subpath); - if (!fs.existsSync(binPath)) { - try { - require.resolve(pkg); - } catch { - const otherPkg = pkgForSomeOtherPlatform(); - if (otherPkg) { - let suggestions = ` -Specifically the "${otherPkg}" package is present but this platform -needs the "${pkg}" package instead. People often get into this -situation by installing esbuild on Windows or macOS and copying "node_modules" -into a Docker image that runs Linux, or by copying "node_modules" between -Windows and WSL environments. - -If you are installing with npm, you can try not copying the "node_modules" -directory when you copy the files over, and running "npm ci" or "npm install" -on the destination platform after the copy. Or you could consider using yarn -instead of npm which has built-in support for installing a package on multiple -platforms simultaneously. - -If you are installing with yarn, you can try listing both this platform and the -other platform in your ".yarnrc.yml" file using the "supportedArchitectures" -feature: https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures -Keep in mind that this means multiple copies of esbuild will be present. -`; - if (pkg === packageDarwin_x64 && otherPkg === packageDarwin_arm64 || pkg === packageDarwin_arm64 && otherPkg === packageDarwin_x64) { - suggestions = ` -Specifically the "${otherPkg}" package is present but this platform -needs the "${pkg}" package instead. People often get into this -situation by installing esbuild with npm running inside of Rosetta 2 and then -trying to use it with node running outside of Rosetta 2, or vice versa (Rosetta -2 is Apple's on-the-fly x86_64-to-arm64 translation service). - -If you are installing with npm, you can try ensuring that both npm and node are -not running under Rosetta 2 and then reinstalling esbuild. This likely involves -changing how you installed npm and/or node. For example, installing node with -the universal installer here should work: https://nodejs.org/en/download/. Or -you could consider using yarn instead of npm which has built-in support for -installing a package on multiple platforms simultaneously. - -If you are installing with yarn, you can try listing both "arm64" and "x64" -in your ".yarnrc.yml" file using the "supportedArchitectures" feature: -https://yarnpkg.com/configuration/yarnrc/#supportedArchitectures -Keep in mind that this means multiple copies of esbuild will be present. -`; - } - throw new Error(` -You installed esbuild for another platform than the one you're currently using. -This won't work because esbuild is written with native code and needs to -install a platform-specific binary executable. -${suggestions} -Another alternative is to use the "esbuild-wasm" package instead, which works -the same way on all platforms. But it comes with a heavy performance cost and -can sometimes be 10x slower than the "esbuild" package, so you may also not -want to do that. -`); - } - throw new Error(`The package "${pkg}" could not be found, and is needed by esbuild. - -If you are installing esbuild with npm, make sure that you don't specify the -"--no-optional" or "--omit=optional" flags. The "optionalDependencies" feature -of "package.json" is used by esbuild to install the correct binary executable -for your current platform.`); - } - throw e; - } - } - if (/\.zip\//.test(binPath)) { - let pnpapi; - try { - pnpapi = require("pnpapi"); - } catch (e) { - } - if (pnpapi) { - const root = pnpapi.getPackageInformation(pnpapi.topLevel).packageLocation; - const binTargetPath = path.join( - root, - "node_modules", - ".cache", - "esbuild", - `pnpapi-${pkg.replace("/", "-")}-${"0.21.5"}-${path.basename(subpath)}` - ); - if (!fs.existsSync(binTargetPath)) { - fs.mkdirSync(path.dirname(binTargetPath), { recursive: true }); - fs.copyFileSync(binPath, binTargetPath); - fs.chmodSync(binTargetPath, 493); - } - return { binPath: binTargetPath, isWASM }; - } - } - return { binPath, isWASM }; -} - -// lib/npm/node.ts -var child_process = require("child_process"); -var crypto = require("crypto"); -var path2 = require("path"); -var fs2 = require("fs"); -var os2 = require("os"); -var tty = require("tty"); -var worker_threads; -if (process.env.ESBUILD_WORKER_THREADS !== "0") { - try { - worker_threads = require("worker_threads"); - } catch { - } - let [major, minor] = process.versions.node.split("."); - if ( - // { - if ((!ESBUILD_BINARY_PATH || false) && (path2.basename(__filename) !== "main.js" || path2.basename(__dirname) !== "lib")) { - throw new Error( - `The esbuild JavaScript API cannot be bundled. Please mark the "esbuild" package as external so it's not included in the bundle. - -More information: The file containing the code for esbuild's JavaScript API (${__filename}) does not appear to be inside the esbuild package on the file system, which usually means that the esbuild package was bundled into another file. This is problematic because the API needs to run a binary executable inside the esbuild package which is located using a relative path from the API code to the executable. If the esbuild package is bundled, the relative path will be incorrect and the executable won't be found.` - ); - } - if (false) { - return ["node", [path2.join(__dirname, "..", "bin", "esbuild")]]; - } else { - const { binPath, isWASM } = generateBinPath(); - if (isWASM) { - return ["node", [binPath]]; - } else { - return [binPath, []]; - } - } -}; -var isTTY = () => tty.isatty(2); -var fsSync = { - readFile(tempFile, callback) { - try { - let contents = fs2.readFileSync(tempFile, "utf8"); - try { - fs2.unlinkSync(tempFile); - } catch { - } - callback(null, contents); - } catch (err) { - callback(err, null); - } - }, - writeFile(contents, callback) { - try { - let tempFile = randomFileName(); - fs2.writeFileSync(tempFile, contents); - callback(tempFile); - } catch { - callback(null); - } - } -}; -var fsAsync = { - readFile(tempFile, callback) { - try { - fs2.readFile(tempFile, "utf8", (err, contents) => { - try { - fs2.unlink(tempFile, () => callback(err, contents)); - } catch { - callback(err, contents); - } - }); - } catch (err) { - callback(err, null); - } - }, - writeFile(contents, callback) { - try { - let tempFile = randomFileName(); - fs2.writeFile(tempFile, contents, (err) => err !== null ? callback(null) : callback(tempFile)); - } catch { - callback(null); - } - } -}; -var version = "0.21.5"; -var build = (options) => ensureServiceIsRunning().build(options); -var context = (buildOptions) => ensureServiceIsRunning().context(buildOptions); -var transform = (input, options) => ensureServiceIsRunning().transform(input, options); -var formatMessages = (messages, options) => ensureServiceIsRunning().formatMessages(messages, options); -var analyzeMetafile = (messages, options) => ensureServiceIsRunning().analyzeMetafile(messages, options); -var buildSync = (options) => { - if (worker_threads && !isInternalWorkerThread) { - if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); - return workerThreadService.buildSync(options); - } - let result; - runServiceSync((service) => service.buildOrContext({ - callName: "buildSync", - refs: null, - options, - isTTY: isTTY(), - defaultWD, - callback: (err, res) => { - if (err) throw err; - result = res; - } - })); - return result; -}; -var transformSync = (input, options) => { - if (worker_threads && !isInternalWorkerThread) { - if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); - return workerThreadService.transformSync(input, options); - } - let result; - runServiceSync((service) => service.transform({ - callName: "transformSync", - refs: null, - input, - options: options || {}, - isTTY: isTTY(), - fs: fsSync, - callback: (err, res) => { - if (err) throw err; - result = res; - } - })); - return result; -}; -var formatMessagesSync = (messages, options) => { - if (worker_threads && !isInternalWorkerThread) { - if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); - return workerThreadService.formatMessagesSync(messages, options); - } - let result; - runServiceSync((service) => service.formatMessages({ - callName: "formatMessagesSync", - refs: null, - messages, - options, - callback: (err, res) => { - if (err) throw err; - result = res; - } - })); - return result; -}; -var analyzeMetafileSync = (metafile, options) => { - if (worker_threads && !isInternalWorkerThread) { - if (!workerThreadService) workerThreadService = startWorkerThreadService(worker_threads); - return workerThreadService.analyzeMetafileSync(metafile, options); - } - let result; - runServiceSync((service) => service.analyzeMetafile({ - callName: "analyzeMetafileSync", - refs: null, - metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile), - options, - callback: (err, res) => { - if (err) throw err; - result = res; - } - })); - return result; -}; -var stop = () => { - if (stopService) stopService(); - if (workerThreadService) workerThreadService.stop(); - return Promise.resolve(); -}; -var initializeWasCalled = false; -var initialize = (options) => { - options = validateInitializeOptions(options || {}); - if (options.wasmURL) throw new Error(`The "wasmURL" option only works in the browser`); - if (options.wasmModule) throw new Error(`The "wasmModule" option only works in the browser`); - if (options.worker) throw new Error(`The "worker" option only works in the browser`); - if (initializeWasCalled) throw new Error('Cannot call "initialize" more than once'); - ensureServiceIsRunning(); - initializeWasCalled = true; - return Promise.resolve(); -}; -var defaultWD = process.cwd(); -var longLivedService; -var stopService; -var ensureServiceIsRunning = () => { - if (longLivedService) return longLivedService; - let [command, args] = esbuildCommandAndArgs(); - let child = child_process.spawn(command, args.concat(`--service=${"0.21.5"}`, "--ping"), { - windowsHide: true, - stdio: ["pipe", "pipe", "inherit"], - cwd: defaultWD - }); - let { readFromStdout, afterClose, service } = createChannel({ - writeToStdin(bytes) { - child.stdin.write(bytes, (err) => { - if (err) afterClose(err); - }); - }, - readFileSync: fs2.readFileSync, - isSync: false, - hasFS: true, - esbuild: node_exports - }); - child.stdin.on("error", afterClose); - child.on("error", afterClose); - const stdin = child.stdin; - const stdout = child.stdout; - stdout.on("data", readFromStdout); - stdout.on("end", afterClose); - stopService = () => { - stdin.destroy(); - stdout.destroy(); - child.kill(); - initializeWasCalled = false; - longLivedService = void 0; - stopService = void 0; - }; - let refCount = 0; - child.unref(); - if (stdin.unref) { - stdin.unref(); - } - if (stdout.unref) { - stdout.unref(); - } - const refs = { - ref() { - if (++refCount === 1) child.ref(); - }, - unref() { - if (--refCount === 0) child.unref(); - } - }; - longLivedService = { - build: (options) => new Promise((resolve, reject) => { - service.buildOrContext({ - callName: "build", - refs, - options, - isTTY: isTTY(), - defaultWD, - callback: (err, res) => err ? reject(err) : resolve(res) - }); - }), - context: (options) => new Promise((resolve, reject) => service.buildOrContext({ - callName: "context", - refs, - options, - isTTY: isTTY(), - defaultWD, - callback: (err, res) => err ? reject(err) : resolve(res) - })), - transform: (input, options) => new Promise((resolve, reject) => service.transform({ - callName: "transform", - refs, - input, - options: options || {}, - isTTY: isTTY(), - fs: fsAsync, - callback: (err, res) => err ? reject(err) : resolve(res) - })), - formatMessages: (messages, options) => new Promise((resolve, reject) => service.formatMessages({ - callName: "formatMessages", - refs, - messages, - options, - callback: (err, res) => err ? reject(err) : resolve(res) - })), - analyzeMetafile: (metafile, options) => new Promise((resolve, reject) => service.analyzeMetafile({ - callName: "analyzeMetafile", - refs, - metafile: typeof metafile === "string" ? metafile : JSON.stringify(metafile), - options, - callback: (err, res) => err ? reject(err) : resolve(res) - })) - }; - return longLivedService; -}; -var runServiceSync = (callback) => { - let [command, args] = esbuildCommandAndArgs(); - let stdin = new Uint8Array(); - let { readFromStdout, afterClose, service } = createChannel({ - writeToStdin(bytes) { - if (stdin.length !== 0) throw new Error("Must run at most one command"); - stdin = bytes; - }, - isSync: true, - hasFS: true, - esbuild: node_exports - }); - callback(service); - let stdout = child_process.execFileSync(command, args.concat(`--service=${"0.21.5"}`), { - cwd: defaultWD, - windowsHide: true, - input: stdin, - // We don't know how large the output could be. If it's too large, the - // command will fail with ENOBUFS. Reserve 16mb for now since that feels - // like it should be enough. Also allow overriding this with an environment - // variable. - maxBuffer: +process.env.ESBUILD_MAX_BUFFER || 16 * 1024 * 1024 - }); - readFromStdout(stdout); - afterClose(null); -}; -var randomFileName = () => { - return path2.join(os2.tmpdir(), `esbuild-${crypto.randomBytes(32).toString("hex")}`); -}; -var workerThreadService = null; -var startWorkerThreadService = (worker_threads2) => { - let { port1: mainPort, port2: workerPort } = new worker_threads2.MessageChannel(); - let worker = new worker_threads2.Worker(__filename, { - workerData: { workerPort, defaultWD, esbuildVersion: "0.21.5" }, - transferList: [workerPort], - // From node's documentation: https://nodejs.org/api/worker_threads.html - // - // Take care when launching worker threads from preload scripts (scripts loaded - // and run using the `-r` command line flag). Unless the `execArgv` option is - // explicitly set, new Worker threads automatically inherit the command line flags - // from the running process and will preload the same preload scripts as the main - // thread. If the preload script unconditionally launches a worker thread, every - // thread spawned will spawn another until the application crashes. - // - execArgv: [] - }); - let nextID = 0; - let fakeBuildError = (text) => { - let error = new Error(`Build failed with 1 error: -error: ${text}`); - let errors = [{ id: "", pluginName: "", text, location: null, notes: [], detail: void 0 }]; - error.errors = errors; - error.warnings = []; - return error; - }; - let validateBuildSyncOptions = (options) => { - if (!options) return; - let plugins = options.plugins; - if (plugins && plugins.length > 0) throw fakeBuildError(`Cannot use plugins in synchronous API calls`); - }; - let applyProperties = (object, properties) => { - for (let key in properties) { - object[key] = properties[key]; - } - }; - let runCallSync = (command, args) => { - let id = nextID++; - let sharedBuffer = new SharedArrayBuffer(8); - let sharedBufferView = new Int32Array(sharedBuffer); - let msg = { sharedBuffer, id, command, args }; - worker.postMessage(msg); - let status = Atomics.wait(sharedBufferView, 0, 0); - if (status !== "ok" && status !== "not-equal") throw new Error("Internal error: Atomics.wait() failed: " + status); - let { message: { id: id2, resolve, reject, properties } } = worker_threads2.receiveMessageOnPort(mainPort); - if (id !== id2) throw new Error(`Internal error: Expected id ${id} but got id ${id2}`); - if (reject) { - applyProperties(reject, properties); - throw reject; - } - return resolve; - }; - worker.unref(); - return { - buildSync(options) { - validateBuildSyncOptions(options); - return runCallSync("build", [options]); - }, - transformSync(input, options) { - return runCallSync("transform", [input, options]); - }, - formatMessagesSync(messages, options) { - return runCallSync("formatMessages", [messages, options]); - }, - analyzeMetafileSync(metafile, options) { - return runCallSync("analyzeMetafile", [metafile, options]); - }, - stop() { - worker.terminate(); - workerThreadService = null; - } - }; -}; -var startSyncServiceWorker = () => { - let workerPort = worker_threads.workerData.workerPort; - let parentPort = worker_threads.parentPort; - let extractProperties = (object) => { - let properties = {}; - if (object && typeof object === "object") { - for (let key in object) { - properties[key] = object[key]; - } - } - return properties; - }; - try { - let service = ensureServiceIsRunning(); - defaultWD = worker_threads.workerData.defaultWD; - parentPort.on("message", (msg) => { - (async () => { - let { sharedBuffer, id, command, args } = msg; - let sharedBufferView = new Int32Array(sharedBuffer); - try { - switch (command) { - case "build": - workerPort.postMessage({ id, resolve: await service.build(args[0]) }); - break; - case "transform": - workerPort.postMessage({ id, resolve: await service.transform(args[0], args[1]) }); - break; - case "formatMessages": - workerPort.postMessage({ id, resolve: await service.formatMessages(args[0], args[1]) }); - break; - case "analyzeMetafile": - workerPort.postMessage({ id, resolve: await service.analyzeMetafile(args[0], args[1]) }); - break; - default: - throw new Error(`Invalid command: ${command}`); - } - } catch (reject) { - workerPort.postMessage({ id, reject, properties: extractProperties(reject) }); - } - Atomics.add(sharedBufferView, 0, 1); - Atomics.notify(sharedBufferView, 0, Infinity); - })(); - }); - } catch (reject) { - parentPort.on("message", (msg) => { - let { sharedBuffer, id } = msg; - let sharedBufferView = new Int32Array(sharedBuffer); - workerPort.postMessage({ id, reject, properties: extractProperties(reject) }); - Atomics.add(sharedBufferView, 0, 1); - Atomics.notify(sharedBufferView, 0, Infinity); - }); - } -}; -if (isInternalWorkerThread) { - startSyncServiceWorker(); -} -var node_default = node_exports; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - analyzeMetafile, - analyzeMetafileSync, - build, - buildSync, - context, - formatMessages, - formatMessagesSync, - initialize, - stop, - transform, - transformSync, - version -}); diff --git a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/node_modules/.bin/esbuild b/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/node_modules/.bin/esbuild deleted file mode 100644 index 906754c..0000000 --- a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/node_modules/.bin/esbuild +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*|*MINGW*|*MSYS*) - if command -v cygpath > /dev/null 2>&1; then - basedir=`cygpath -w "$basedir"` - fi - ;; -esac - -if [ -x "$basedir/node" ]; then - exec "$basedir/node" "$basedir/../../bin/esbuild" "$@" -else - exec node "$basedir/../../bin/esbuild" "$@" -fi diff --git a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/node_modules/.bin/esbuild.ps1 b/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/node_modules/.bin/esbuild.ps1 deleted file mode 100644 index b6d3c89..0000000 --- a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/node_modules/.bin/esbuild.ps1 +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env pwsh -$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent - -$exe="" -if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { - # Fix case when both the Windows and Linux builds of Node - # are installed in the same directory - $exe=".exe" -} -$ret=0 -if (Test-Path "$basedir/node$exe") { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "$basedir/node$exe" "$basedir/../../bin/esbuild" $args - } else { - & "$basedir/node$exe" "$basedir/../../bin/esbuild" $args - } - $ret=$LASTEXITCODE -} else { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "node$exe" "$basedir/../../bin/esbuild" $args - } else { - & "node$exe" "$basedir/../../bin/esbuild" $args - } - $ret=$LASTEXITCODE -} -exit $ret diff --git a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/package.json b/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/package.json deleted file mode 100644 index fe253fb..0000000 --- a/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/package.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "name": "esbuild", - "version": "0.21.5", - "description": "An extremely fast JavaScript and CSS bundler and minifier.", - "repository": { - "type": "git", - "url": "git+https://github.com/evanw/esbuild.git" - }, - "scripts": { - "postinstall": "node install.js" - }, - "main": "lib/main.js", - "types": "lib/main.d.ts", - "engines": { - "node": ">=12" - }, - "bin": { - "esbuild": "bin/esbuild" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.21.5", - "@esbuild/android-arm": "0.21.5", - "@esbuild/android-arm64": "0.21.5", - "@esbuild/android-x64": "0.21.5", - "@esbuild/darwin-arm64": "0.21.5", - "@esbuild/darwin-x64": "0.21.5", - "@esbuild/freebsd-arm64": "0.21.5", - "@esbuild/freebsd-x64": "0.21.5", - "@esbuild/linux-arm": "0.21.5", - "@esbuild/linux-arm64": "0.21.5", - "@esbuild/linux-ia32": "0.21.5", - "@esbuild/linux-loong64": "0.21.5", - "@esbuild/linux-mips64el": "0.21.5", - "@esbuild/linux-ppc64": "0.21.5", - "@esbuild/linux-riscv64": "0.21.5", - "@esbuild/linux-s390x": "0.21.5", - "@esbuild/linux-x64": "0.21.5", - "@esbuild/netbsd-x64": "0.21.5", - "@esbuild/openbsd-x64": "0.21.5", - "@esbuild/sunos-x64": "0.21.5", - "@esbuild/win32-arm64": "0.21.5", - "@esbuild/win32-ia32": "0.21.5", - "@esbuild/win32-x64": "0.21.5" - }, - "license": "MIT" -} diff --git a/node_modules/.pnpm/lock.yaml b/node_modules/.pnpm/lock.yaml deleted file mode 100644 index df2daa0..0000000 --- a/node_modules/.pnpm/lock.yaml +++ /dev/null @@ -1,568 +0,0 @@ -lockfileVersion: '9.0' - -settings: - autoInstallPeers: true - excludeLinksFromLockfile: false - -importers: - - .: - dependencies: - alova: - specifier: ^3.2.10 - version: 3.2.10 - devDependencies: - '@wailsio/runtime': - specifier: latest - version: 3.0.0-alpha.66 - vite: - specifier: ^5.0.0 - version: 5.4.19 - -packages: - - '@alova/shared@1.1.2': - resolution: {integrity: sha512-8q/gMHFpzm7XYcaUlsyTCMDRRhFnewwheTeObMjPl1+bFdr+wZuBEHEPYIyd8tyzLwfrqpBeonaMN2tlngM8EA==} - - '@esbuild/aix-ppc64@0.21.5': - resolution: {integrity: sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==} - engines: {node: '>=12'} - cpu: [ppc64] - os: [aix] - - '@esbuild/android-arm64@0.21.5': - resolution: {integrity: sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==} - engines: {node: '>=12'} - cpu: [arm64] - os: [android] - - '@esbuild/android-arm@0.21.5': - resolution: {integrity: sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==} - engines: {node: '>=12'} - cpu: [arm] - os: [android] - - '@esbuild/android-x64@0.21.5': - resolution: {integrity: sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==} - engines: {node: '>=12'} - cpu: [x64] - os: [android] - - '@esbuild/darwin-arm64@0.21.5': - resolution: {integrity: sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==} - engines: {node: '>=12'} - cpu: [arm64] - os: [darwin] - - '@esbuild/darwin-x64@0.21.5': - resolution: {integrity: sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==} - engines: {node: '>=12'} - cpu: [x64] - os: [darwin] - - '@esbuild/freebsd-arm64@0.21.5': - resolution: {integrity: sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==} - engines: {node: '>=12'} - cpu: [arm64] - os: [freebsd] - - '@esbuild/freebsd-x64@0.21.5': - resolution: {integrity: sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==} - engines: {node: '>=12'} - cpu: [x64] - os: [freebsd] - - '@esbuild/linux-arm64@0.21.5': - resolution: {integrity: sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==} - engines: {node: '>=12'} - cpu: [arm64] - os: [linux] - - '@esbuild/linux-arm@0.21.5': - resolution: {integrity: sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==} - engines: {node: '>=12'} - cpu: [arm] - os: [linux] - - '@esbuild/linux-ia32@0.21.5': - resolution: {integrity: sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==} - engines: {node: '>=12'} - cpu: [ia32] - os: [linux] - - '@esbuild/linux-loong64@0.21.5': - resolution: {integrity: sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==} - engines: {node: '>=12'} - cpu: [loong64] - os: [linux] - - '@esbuild/linux-mips64el@0.21.5': - resolution: {integrity: sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==} - engines: {node: '>=12'} - cpu: [mips64el] - os: [linux] - - '@esbuild/linux-ppc64@0.21.5': - resolution: {integrity: sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==} - engines: {node: '>=12'} - cpu: [ppc64] - os: [linux] - - '@esbuild/linux-riscv64@0.21.5': - resolution: {integrity: sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==} - engines: {node: '>=12'} - cpu: [riscv64] - os: [linux] - - '@esbuild/linux-s390x@0.21.5': - resolution: {integrity: sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==} - engines: {node: '>=12'} - cpu: [s390x] - os: [linux] - - '@esbuild/linux-x64@0.21.5': - resolution: {integrity: sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==} - engines: {node: '>=12'} - cpu: [x64] - os: [linux] - - '@esbuild/netbsd-x64@0.21.5': - resolution: {integrity: sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==} - engines: {node: '>=12'} - cpu: [x64] - os: [netbsd] - - '@esbuild/openbsd-x64@0.21.5': - resolution: {integrity: sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==} - engines: {node: '>=12'} - cpu: [x64] - os: [openbsd] - - '@esbuild/sunos-x64@0.21.5': - resolution: {integrity: sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==} - engines: {node: '>=12'} - cpu: [x64] - os: [sunos] - - '@esbuild/win32-arm64@0.21.5': - resolution: {integrity: sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==} - engines: {node: '>=12'} - cpu: [arm64] - os: [win32] - - '@esbuild/win32-ia32@0.21.5': - resolution: {integrity: sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==} - engines: {node: '>=12'} - cpu: [ia32] - os: [win32] - - '@esbuild/win32-x64@0.21.5': - resolution: {integrity: sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==} - engines: {node: '>=12'} - cpu: [x64] - os: [win32] - - '@rollup/rollup-android-arm-eabi@4.40.2': - resolution: {integrity: sha512-JkdNEq+DFxZfUwxvB58tHMHBHVgX23ew41g1OQinthJ+ryhdRk67O31S7sYw8u2lTjHUPFxwar07BBt1KHp/hg==} - cpu: [arm] - os: [android] - - '@rollup/rollup-android-arm64@4.40.2': - resolution: {integrity: sha512-13unNoZ8NzUmnndhPTkWPWbX3vtHodYmy+I9kuLxN+F+l+x3LdVF7UCu8TWVMt1POHLh6oDHhnOA04n8oJZhBw==} - cpu: [arm64] - os: [android] - - '@rollup/rollup-darwin-arm64@4.40.2': - resolution: {integrity: sha512-Gzf1Hn2Aoe8VZzevHostPX23U7N5+4D36WJNHK88NZHCJr7aVMG4fadqkIf72eqVPGjGc0HJHNuUaUcxiR+N/w==} - cpu: [arm64] - os: [darwin] - - '@rollup/rollup-darwin-x64@4.40.2': - resolution: {integrity: sha512-47N4hxa01a4x6XnJoskMKTS8XZ0CZMd8YTbINbi+w03A2w4j1RTlnGHOz/P0+Bg1LaVL6ufZyNprSg+fW5nYQQ==} - cpu: [x64] - os: [darwin] - - '@rollup/rollup-freebsd-arm64@4.40.2': - resolution: {integrity: sha512-8t6aL4MD+rXSHHZUR1z19+9OFJ2rl1wGKvckN47XFRVO+QL/dUSpKA2SLRo4vMg7ELA8pzGpC+W9OEd1Z/ZqoQ==} - cpu: [arm64] - os: [freebsd] - - '@rollup/rollup-freebsd-x64@4.40.2': - resolution: {integrity: sha512-C+AyHBzfpsOEYRFjztcYUFsH4S7UsE9cDtHCtma5BK8+ydOZYgMmWg1d/4KBytQspJCld8ZIujFMAdKG1xyr4Q==} - cpu: [x64] - os: [freebsd] - - '@rollup/rollup-linux-arm-gnueabihf@4.40.2': - resolution: {integrity: sha512-de6TFZYIvJwRNjmW3+gaXiZ2DaWL5D5yGmSYzkdzjBDS3W+B9JQ48oZEsmMvemqjtAFzE16DIBLqd6IQQRuG9Q==} - cpu: [arm] - os: [linux] - libc: [glibc] - - '@rollup/rollup-linux-arm-musleabihf@4.40.2': - resolution: {integrity: sha512-urjaEZubdIkacKc930hUDOfQPysezKla/O9qV+O89enqsqUmQm8Xj8O/vh0gHg4LYfv7Y7UsE3QjzLQzDYN1qg==} - cpu: [arm] - os: [linux] - libc: [musl] - - '@rollup/rollup-linux-arm64-gnu@4.40.2': - resolution: {integrity: sha512-KlE8IC0HFOC33taNt1zR8qNlBYHj31qGT1UqWqtvR/+NuCVhfufAq9fxO8BMFC22Wu0rxOwGVWxtCMvZVLmhQg==} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@rollup/rollup-linux-arm64-musl@4.40.2': - resolution: {integrity: sha512-j8CgxvfM0kbnhu4XgjnCWJQyyBOeBI1Zq91Z850aUddUmPeQvuAy6OiMdPS46gNFgy8gN1xkYyLgwLYZG3rBOg==} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@rollup/rollup-linux-loongarch64-gnu@4.40.2': - resolution: {integrity: sha512-Ybc/1qUampKuRF4tQXc7G7QY9YRyeVSykfK36Y5Qc5dmrIxwFhrOzqaVTNoZygqZ1ZieSWTibfFhQ5qK8jpWxw==} - cpu: [loong64] - os: [linux] - libc: [glibc] - - '@rollup/rollup-linux-powerpc64le-gnu@4.40.2': - resolution: {integrity: sha512-3FCIrnrt03CCsZqSYAOW/k9n625pjpuMzVfeI+ZBUSDT3MVIFDSPfSUgIl9FqUftxcUXInvFah79hE1c9abD+Q==} - cpu: [ppc64] - os: [linux] - libc: [glibc] - - '@rollup/rollup-linux-riscv64-gnu@4.40.2': - resolution: {integrity: sha512-QNU7BFHEvHMp2ESSY3SozIkBPaPBDTsfVNGx3Xhv+TdvWXFGOSH2NJvhD1zKAT6AyuuErJgbdvaJhYVhVqrWTg==} - cpu: [riscv64] - os: [linux] - libc: [glibc] - - '@rollup/rollup-linux-riscv64-musl@4.40.2': - resolution: {integrity: sha512-5W6vNYkhgfh7URiXTO1E9a0cy4fSgfE4+Hl5agb/U1sa0kjOLMLC1wObxwKxecE17j0URxuTrYZZME4/VH57Hg==} - cpu: [riscv64] - os: [linux] - libc: [musl] - - '@rollup/rollup-linux-s390x-gnu@4.40.2': - resolution: {integrity: sha512-B7LKIz+0+p348JoAL4X/YxGx9zOx3sR+o6Hj15Y3aaApNfAshK8+mWZEf759DXfRLeL2vg5LYJBB7DdcleYCoQ==} - cpu: [s390x] - os: [linux] - libc: [glibc] - - '@rollup/rollup-linux-x64-gnu@4.40.2': - resolution: {integrity: sha512-lG7Xa+BmBNwpjmVUbmyKxdQJ3Q6whHjMjzQplOs5Z+Gj7mxPtWakGHqzMqNER68G67kmCX9qX57aRsW5V0VOng==} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@rollup/rollup-linux-x64-musl@4.40.2': - resolution: {integrity: sha512-tD46wKHd+KJvsmije4bUskNuvWKFcTOIM9tZ/RrmIvcXnbi0YK/cKS9FzFtAm7Oxi2EhV5N2OpfFB348vSQRXA==} - cpu: [x64] - os: [linux] - libc: [musl] - - '@rollup/rollup-win32-arm64-msvc@4.40.2': - resolution: {integrity: sha512-Bjv/HG8RRWLNkXwQQemdsWw4Mg+IJ29LK+bJPW2SCzPKOUaMmPEppQlu/Fqk1d7+DX3V7JbFdbkh/NMmurT6Pg==} - cpu: [arm64] - os: [win32] - - '@rollup/rollup-win32-ia32-msvc@4.40.2': - resolution: {integrity: sha512-dt1llVSGEsGKvzeIO76HToiYPNPYPkmjhMHhP00T9S4rDern8P2ZWvWAQUEJ+R1UdMWJ/42i/QqJ2WV765GZcA==} - cpu: [ia32] - os: [win32] - - '@rollup/rollup-win32-x64-msvc@4.40.2': - resolution: {integrity: sha512-bwspbWB04XJpeElvsp+DCylKfF4trJDa2Y9Go8O6A7YLX2LIKGcNK/CYImJN6ZP4DcuOHB4Utl3iCbnR62DudA==} - cpu: [x64] - os: [win32] - - '@types/estree@1.0.7': - resolution: {integrity: sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==} - - '@wailsio/runtime@3.0.0-alpha.66': - resolution: {integrity: sha512-ENLu8rn1griL1gFHJqkq1i+BVxrrA0JPJHYneUJYuf/s54kjuQViW0RKDEe/WTDo56ABpfykrd/T8OYpPUyXUw==} - - alova@3.2.10: - resolution: {integrity: sha512-OHMuSNUbIUEsAq6q5DabISNgFMIXqrC/DPBQv1QJEwxW3fWlYlaF6Vr8b4iqwZnUd2+0rCmFm9GnpKWk7vvx2w==} - engines: {node: '>= 18.0.0'} - - esbuild@0.21.5: - resolution: {integrity: sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==} - engines: {node: '>=12'} - hasBin: true - - fsevents@2.3.3: - resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} - engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} - os: [darwin] - - nanoid@3.3.11: - resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==} - engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} - hasBin: true - - picocolors@1.1.1: - resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} - - postcss@8.5.3: - resolution: {integrity: sha512-dle9A3yYxlBSrt8Fu+IpjGT8SY8hN0mlaA6GY8t0P5PjIOZemULz/E2Bnm/2dcUOena75OTNkHI76uZBNUUq3A==} - engines: {node: ^10 || ^12 || >=14} - - rate-limiter-flexible@5.0.5: - resolution: {integrity: sha512-+/dSQfo+3FYwYygUs/V2BBdwGa9nFtakDwKt4l0bnvNB53TNT++QSFewwHX9qXrZJuMe9j+TUaU21lm5ARgqdQ==} - - rollup@4.40.2: - resolution: {integrity: sha512-tfUOg6DTP4rhQ3VjOO6B4wyrJnGOX85requAXvqYTHsOgb2TFJdZ3aWpT8W2kPoypSGP7dZUyzxJ9ee4buM5Fg==} - engines: {node: '>=18.0.0', npm: '>=8.0.0'} - hasBin: true - - source-map-js@1.2.1: - resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} - engines: {node: '>=0.10.0'} - - vite@5.4.19: - resolution: {integrity: sha512-qO3aKv3HoQC8QKiNSTuUM1l9o/XX3+c+VTgLHbJWHZGeTPVAg2XwazI9UWzoxjIJCGCV2zU60uqMzjeLZuULqA==} - engines: {node: ^18.0.0 || >=20.0.0} - hasBin: true - peerDependencies: - '@types/node': ^18.0.0 || >=20.0.0 - less: '*' - lightningcss: ^1.21.0 - sass: '*' - sass-embedded: '*' - stylus: '*' - sugarss: '*' - terser: ^5.4.0 - peerDependenciesMeta: - '@types/node': - optional: true - less: - optional: true - lightningcss: - optional: true - sass: - optional: true - sass-embedded: - optional: true - stylus: - optional: true - sugarss: - optional: true - terser: - optional: true - -snapshots: - - '@alova/shared@1.1.2': {} - - '@esbuild/aix-ppc64@0.21.5': - optional: true - - '@esbuild/android-arm64@0.21.5': - optional: true - - '@esbuild/android-arm@0.21.5': - optional: true - - '@esbuild/android-x64@0.21.5': - optional: true - - '@esbuild/darwin-arm64@0.21.5': - optional: true - - '@esbuild/darwin-x64@0.21.5': - optional: true - - '@esbuild/freebsd-arm64@0.21.5': - optional: true - - '@esbuild/freebsd-x64@0.21.5': - optional: true - - '@esbuild/linux-arm64@0.21.5': - optional: true - - '@esbuild/linux-arm@0.21.5': - optional: true - - '@esbuild/linux-ia32@0.21.5': - optional: true - - '@esbuild/linux-loong64@0.21.5': - optional: true - - '@esbuild/linux-mips64el@0.21.5': - optional: true - - '@esbuild/linux-ppc64@0.21.5': - optional: true - - '@esbuild/linux-riscv64@0.21.5': - optional: true - - '@esbuild/linux-s390x@0.21.5': - optional: true - - '@esbuild/linux-x64@0.21.5': - optional: true - - '@esbuild/netbsd-x64@0.21.5': - optional: true - - '@esbuild/openbsd-x64@0.21.5': - optional: true - - '@esbuild/sunos-x64@0.21.5': - optional: true - - '@esbuild/win32-arm64@0.21.5': - optional: true - - '@esbuild/win32-ia32@0.21.5': - optional: true - - '@esbuild/win32-x64@0.21.5': - optional: true - - '@rollup/rollup-android-arm-eabi@4.40.2': - optional: true - - '@rollup/rollup-android-arm64@4.40.2': - optional: true - - '@rollup/rollup-darwin-arm64@4.40.2': - optional: true - - '@rollup/rollup-darwin-x64@4.40.2': - optional: true - - '@rollup/rollup-freebsd-arm64@4.40.2': - optional: true - - '@rollup/rollup-freebsd-x64@4.40.2': - optional: true - - '@rollup/rollup-linux-arm-gnueabihf@4.40.2': - optional: true - - '@rollup/rollup-linux-arm-musleabihf@4.40.2': - optional: true - - '@rollup/rollup-linux-arm64-gnu@4.40.2': - optional: true - - '@rollup/rollup-linux-arm64-musl@4.40.2': - optional: true - - '@rollup/rollup-linux-loongarch64-gnu@4.40.2': - optional: true - - '@rollup/rollup-linux-powerpc64le-gnu@4.40.2': - optional: true - - '@rollup/rollup-linux-riscv64-gnu@4.40.2': - optional: true - - '@rollup/rollup-linux-riscv64-musl@4.40.2': - optional: true - - '@rollup/rollup-linux-s390x-gnu@4.40.2': - optional: true - - '@rollup/rollup-linux-x64-gnu@4.40.2': - optional: true - - '@rollup/rollup-linux-x64-musl@4.40.2': - optional: true - - '@rollup/rollup-win32-arm64-msvc@4.40.2': - optional: true - - '@rollup/rollup-win32-ia32-msvc@4.40.2': - optional: true - - '@rollup/rollup-win32-x64-msvc@4.40.2': - optional: true - - '@types/estree@1.0.7': {} - - '@wailsio/runtime@3.0.0-alpha.66': {} - - alova@3.2.10: - dependencies: - '@alova/shared': 1.1.2 - rate-limiter-flexible: 5.0.5 - - esbuild@0.21.5: - optionalDependencies: - '@esbuild/aix-ppc64': 0.21.5 - '@esbuild/android-arm': 0.21.5 - '@esbuild/android-arm64': 0.21.5 - '@esbuild/android-x64': 0.21.5 - '@esbuild/darwin-arm64': 0.21.5 - '@esbuild/darwin-x64': 0.21.5 - '@esbuild/freebsd-arm64': 0.21.5 - '@esbuild/freebsd-x64': 0.21.5 - '@esbuild/linux-arm': 0.21.5 - '@esbuild/linux-arm64': 0.21.5 - '@esbuild/linux-ia32': 0.21.5 - '@esbuild/linux-loong64': 0.21.5 - '@esbuild/linux-mips64el': 0.21.5 - '@esbuild/linux-ppc64': 0.21.5 - '@esbuild/linux-riscv64': 0.21.5 - '@esbuild/linux-s390x': 0.21.5 - '@esbuild/linux-x64': 0.21.5 - '@esbuild/netbsd-x64': 0.21.5 - '@esbuild/openbsd-x64': 0.21.5 - '@esbuild/sunos-x64': 0.21.5 - '@esbuild/win32-arm64': 0.21.5 - '@esbuild/win32-ia32': 0.21.5 - '@esbuild/win32-x64': 0.21.5 - - fsevents@2.3.3: - optional: true - - nanoid@3.3.11: {} - - picocolors@1.1.1: {} - - postcss@8.5.3: - dependencies: - nanoid: 3.3.11 - picocolors: 1.1.1 - source-map-js: 1.2.1 - - rate-limiter-flexible@5.0.5: {} - - rollup@4.40.2: - dependencies: - '@types/estree': 1.0.7 - optionalDependencies: - '@rollup/rollup-android-arm-eabi': 4.40.2 - '@rollup/rollup-android-arm64': 4.40.2 - '@rollup/rollup-darwin-arm64': 4.40.2 - '@rollup/rollup-darwin-x64': 4.40.2 - '@rollup/rollup-freebsd-arm64': 4.40.2 - '@rollup/rollup-freebsd-x64': 4.40.2 - '@rollup/rollup-linux-arm-gnueabihf': 4.40.2 - '@rollup/rollup-linux-arm-musleabihf': 4.40.2 - '@rollup/rollup-linux-arm64-gnu': 4.40.2 - '@rollup/rollup-linux-arm64-musl': 4.40.2 - '@rollup/rollup-linux-loongarch64-gnu': 4.40.2 - '@rollup/rollup-linux-powerpc64le-gnu': 4.40.2 - '@rollup/rollup-linux-riscv64-gnu': 4.40.2 - '@rollup/rollup-linux-riscv64-musl': 4.40.2 - '@rollup/rollup-linux-s390x-gnu': 4.40.2 - '@rollup/rollup-linux-x64-gnu': 4.40.2 - '@rollup/rollup-linux-x64-musl': 4.40.2 - '@rollup/rollup-win32-arm64-msvc': 4.40.2 - '@rollup/rollup-win32-ia32-msvc': 4.40.2 - '@rollup/rollup-win32-x64-msvc': 4.40.2 - fsevents: 2.3.3 - - source-map-js@1.2.1: {} - - vite@5.4.19: - dependencies: - esbuild: 0.21.5 - postcss: 8.5.3 - rollup: 4.40.2 - optionalDependencies: - fsevents: 2.3.3 diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/LICENSE b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/LICENSE deleted file mode 100644 index 37f56aa..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright 2017 Andrey Sitnik - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/README.md b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/README.md deleted file mode 100644 index 35abb57..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# Nano ID - -Nano ID logo by Anton Lovchikov - -**English** | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md) - -A tiny, secure, URL-friendly, unique string ID generator for JavaScript. - -> “An amazing level of senseless perfectionism, -> which is simply impossible not to respect.” - -* **Small.** 130 bytes (minified and gzipped). No dependencies. - [Size Limit] controls the size. -* **Fast.** It is 2 times faster than UUID. -* **Safe.** It uses hardware random generator. Can be used in clusters. -* **Short IDs.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`). - So ID size was reduced from 36 to 21 symbols. -* **Portable.** Nano ID was ported - to [20 programming languages](#other-programming-languages). - -```js -import { nanoid } from 'nanoid' -model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT" -``` - -Supports modern browsers, IE [with Babel], Node.js and React Native. - -[online tool]: https://gitpod.io/#https://github.com/ai/nanoid/ -[with Babel]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/ -[Size Limit]: https://github.com/ai/size-limit - - - Sponsored by Evil Martians - - -## Docs -Read full docs **[here](https://github.com/ai/nanoid#readme)**. diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.browser.cjs b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.browser.cjs deleted file mode 100644 index 80d1871..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.browser.cjs +++ /dev/null @@ -1,69 +0,0 @@ -let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes)) - -let customAlphabet = (alphabet, defaultSize = 21) => { - // First, a bitmask is necessary to generate the ID. The bitmask makes bytes - // values closer to the alphabet size. The bitmask calculates the closest - // `2^31 - 1` number, which exceeds the alphabet size. - // For example, the bitmask for the alphabet size 30 is 31 (00011111). - // `Math.clz32` is not used, because it is not available in browsers. - let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 - // Though, the bitmask solution is not perfect since the bytes exceeding - // the alphabet size are refused. Therefore, to reliably generate the ID, - // the random bytes redundancy has to be satisfied. - - // Note: every hardware random generator call is performance expensive, - // because the system call for entropy collection takes a lot of time. - // So, to avoid additional system calls, extra bytes are requested in advance. - - // Next, a step determines how many random bytes to generate. - // The number of random bytes gets decided upon the ID size, mask, - // alphabet size, and magic number 1.6 (using 1.6 peaks at performance - // according to benchmarks). - - // `-~f => Math.ceil(f)` if f is a float - // `-~i => i + 1` if i is an integer - let step = -~((1.6 * mask * defaultSize) / alphabet.length) - - return async (size = defaultSize) => { - let id = '' - while (true) { - let bytes = crypto.getRandomValues(new Uint8Array(step)) - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = step | 0 - while (i--) { - // Adding `|| ''` refuses a random byte that exceeds the alphabet size. - id += alphabet[bytes[i] & mask] || '' - if (id.length === size) return id - } - } - } -} - -let nanoid = async (size = 21) => { - let id = '' - let bytes = crypto.getRandomValues(new Uint8Array((size |= 0))) - - // A compact alternative for `for (var i = 0; i < step; i++)`. - while (size--) { - // It is incorrect to use bytes exceeding the alphabet size. - // The following mask reduces the random byte in the 0-255 value - // range to the 0-63 value range. Therefore, adding hacks, such - // as empty string fallback or magic numbers, is unneccessary because - // the bitmask trims bytes down to the alphabet size. - let byte = bytes[size] & 63 - if (byte < 36) { - // `0-9a-z` - id += byte.toString(36) - } else if (byte < 62) { - // `A-Z` - id += (byte - 26).toString(36).toUpperCase() - } else if (byte < 63) { - id += '_' - } else { - id += '-' - } - } - return id -} - -module.exports = { nanoid, customAlphabet, random } diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.browser.js b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.browser.js deleted file mode 100644 index fbaa230..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.browser.js +++ /dev/null @@ -1,34 +0,0 @@ -let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes)) -let customAlphabet = (alphabet, defaultSize = 21) => { - let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 - let step = -~((1.6 * mask * defaultSize) / alphabet.length) - return async (size = defaultSize) => { - let id = '' - while (true) { - let bytes = crypto.getRandomValues(new Uint8Array(step)) - let i = step | 0 - while (i--) { - id += alphabet[bytes[i] & mask] || '' - if (id.length === size) return id - } - } - } -} -let nanoid = async (size = 21) => { - let id = '' - let bytes = crypto.getRandomValues(new Uint8Array((size |= 0))) - while (size--) { - let byte = bytes[size] & 63 - if (byte < 36) { - id += byte.toString(36) - } else if (byte < 62) { - id += (byte - 26).toString(36).toUpperCase() - } else if (byte < 63) { - id += '_' - } else { - id += '-' - } - } - return id -} -export { nanoid, customAlphabet, random } diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.cjs b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.cjs deleted file mode 100644 index f1b0ad0..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.cjs +++ /dev/null @@ -1,71 +0,0 @@ -let crypto = require('crypto') - -let { urlAlphabet } = require('../url-alphabet/index.cjs') - -// `crypto.randomFill()` is a little faster than `crypto.randomBytes()`, -// because it is possible to use in combination with `Buffer.allocUnsafe()`. -let random = bytes => - new Promise((resolve, reject) => { - // `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory. - // Memory flushing is unnecessary since the buffer allocation itself resets - // the memory with the new bytes. - crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => { - if (err) { - reject(err) - } else { - resolve(buf) - } - }) - }) - -let customAlphabet = (alphabet, defaultSize = 21) => { - // First, a bitmask is necessary to generate the ID. The bitmask makes bytes - // values closer to the alphabet size. The bitmask calculates the closest - // `2^31 - 1` number, which exceeds the alphabet size. - // For example, the bitmask for the alphabet size 30 is 31 (00011111). - let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 - // Though, the bitmask solution is not perfect since the bytes exceeding - // the alphabet size are refused. Therefore, to reliably generate the ID, - // the random bytes redundancy has to be satisfied. - - // Note: every hardware random generator call is performance expensive, - // because the system call for entropy collection takes a lot of time. - // So, to avoid additional system calls, extra bytes are requested in advance. - - // Next, a step determines how many random bytes to generate. - // The number of random bytes gets decided upon the ID size, mask, - // alphabet size, and magic number 1.6 (using 1.6 peaks at performance - // according to benchmarks). - let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) - - let tick = (id, size = defaultSize) => - random(step).then(bytes => { - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = step - while (i--) { - // Adding `|| ''` refuses a random byte that exceeds the alphabet size. - id += alphabet[bytes[i] & mask] || '' - if (id.length >= size) return id - } - return tick(id, size) - }) - - return size => tick('', size) -} - -let nanoid = (size = 21) => - random((size |= 0)).then(bytes => { - let id = '' - // A compact alternative for `for (var i = 0; i < step; i++)`. - while (size--) { - // It is incorrect to use bytes exceeding the alphabet size. - // The following mask reduces the random byte in the 0-255 value - // range to the 0-63 value range. Therefore, adding hacks, such - // as empty string fallback or magic numbers, is unneccessary because - // the bitmask trims bytes down to the alphabet size. - id += urlAlphabet[bytes[size] & 63] - } - return id - }) - -module.exports = { nanoid, customAlphabet, random } diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.d.ts b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.d.ts deleted file mode 100644 index 9e91965..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.d.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Generate secure URL-friendly unique ID. The non-blocking version. - * - * By default, the ID will have 21 symbols to have a collision probability - * similar to UUID v4. - * - * ```js - * import { nanoid } from 'nanoid/async' - * nanoid().then(id => { - * model.id = id - * }) - * ``` - * - * @param size Size of the ID. The default size is 21. - * @returns A promise with a random string. - */ -export function nanoid(size?: number): Promise - -/** - * A low-level function. - * Generate secure unique ID with custom alphabet. The non-blocking version. - * - * Alphabet must contain 256 symbols or less. Otherwise, the generator - * will not be secure. - * - * @param alphabet Alphabet used to generate the ID. - * @param defaultSize Size of the ID. The default size is 21. - * @returns A function that returns a promise with a random string. - * - * ```js - * import { customAlphabet } from 'nanoid/async' - * const nanoid = customAlphabet('0123456789абвгдеё', 5) - * nanoid().then(id => { - * model.id = id //=> "8ё56а" - * }) - * ``` - */ -export function customAlphabet( - alphabet: string, - defaultSize?: number -): (size?: number) => Promise - -/** - * Generate an array of random bytes collected from hardware noise. - * - * ```js - * import { random } from 'nanoid/async' - * random(5).then(bytes => { - * bytes //=> [10, 67, 212, 67, 89] - * }) - * ``` - * - * @param bytes Size of the array. - * @returns A promise with a random bytes array. - */ -export function random(bytes: number): Promise diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.js b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.js deleted file mode 100644 index cec454a..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.js +++ /dev/null @@ -1,35 +0,0 @@ -import crypto from 'crypto' -import { urlAlphabet } from '../url-alphabet/index.js' -let random = bytes => - new Promise((resolve, reject) => { - crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => { - if (err) { - reject(err) - } else { - resolve(buf) - } - }) - }) -let customAlphabet = (alphabet, defaultSize = 21) => { - let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 - let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) - let tick = (id, size = defaultSize) => - random(step).then(bytes => { - let i = step - while (i--) { - id += alphabet[bytes[i] & mask] || '' - if (id.length >= size) return id - } - return tick(id, size) - }) - return size => tick('', size) -} -let nanoid = (size = 21) => - random((size |= 0)).then(bytes => { - let id = '' - while (size--) { - id += urlAlphabet[bytes[size] & 63] - } - return id - }) -export { nanoid, customAlphabet, random } diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.native.js b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.native.js deleted file mode 100644 index 7c1d6f3..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/index.native.js +++ /dev/null @@ -1,26 +0,0 @@ -import { getRandomBytesAsync } from 'expo-random' -import { urlAlphabet } from '../url-alphabet/index.js' -let random = getRandomBytesAsync -let customAlphabet = (alphabet, defaultSize = 21) => { - let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 - let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) - let tick = (id, size = defaultSize) => - random(step).then(bytes => { - let i = step - while (i--) { - id += alphabet[bytes[i] & mask] || '' - if (id.length >= size) return id - } - return tick(id, size) - }) - return size => tick('', size) -} -let nanoid = (size = 21) => - random((size |= 0)).then(bytes => { - let id = '' - while (size--) { - id += urlAlphabet[bytes[size] & 63] - } - return id - }) -export { nanoid, customAlphabet, random } diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/package.json b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/package.json deleted file mode 100644 index 578cdb4..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/async/package.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "type": "module", - "main": "index.cjs", - "module": "index.js", - "react-native": { - "./index.js": "./index.native.js" - }, - "browser": { - "./index.js": "./index.browser.js", - "./index.cjs": "./index.browser.cjs" - } -} \ No newline at end of file diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/bin/nanoid.cjs b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/bin/nanoid.cjs deleted file mode 100644 index c76db0f..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/bin/nanoid.cjs +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env node - -let { nanoid, customAlphabet } = require('..') - -function print(msg) { - process.stdout.write(msg + '\n') -} - -function error(msg) { - process.stderr.write(msg + '\n') - process.exit(1) -} - -if (process.argv.includes('--help') || process.argv.includes('-h')) { - print(` - Usage - $ nanoid [options] - - Options - -s, --size Generated ID size - -a, --alphabet Alphabet to use - -h, --help Show this help - - Examples - $ nanoid --s 15 - S9sBF77U6sDB8Yg - - $ nanoid --size 10 --alphabet abc - bcabababca`) - process.exit() -} - -let alphabet, size -for (let i = 2; i < process.argv.length; i++) { - let arg = process.argv[i] - if (arg === '--size' || arg === '-s') { - size = Number(process.argv[i + 1]) - i += 1 - if (Number.isNaN(size) || size <= 0) { - error('Size must be positive integer') - } - } else if (arg === '--alphabet' || arg === '-a') { - alphabet = process.argv[i + 1] - i += 1 - } else { - error('Unknown argument ' + arg) - } -} - -if (alphabet) { - let customNanoid = customAlphabet(alphabet, size) - print(customNanoid()) -} else { - print(nanoid(size)) -} diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.browser.cjs b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.browser.cjs deleted file mode 100644 index d21a91f..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.browser.cjs +++ /dev/null @@ -1,72 +0,0 @@ -// This file replaces `index.js` in bundlers like webpack or Rollup, -// according to `browser` config in `package.json`. - -let { urlAlphabet } = require('./url-alphabet/index.cjs') - -let random = bytes => crypto.getRandomValues(new Uint8Array(bytes)) - -let customRandom = (alphabet, defaultSize, getRandom) => { - // First, a bitmask is necessary to generate the ID. The bitmask makes bytes - // values closer to the alphabet size. The bitmask calculates the closest - // `2^31 - 1` number, which exceeds the alphabet size. - // For example, the bitmask for the alphabet size 30 is 31 (00011111). - // `Math.clz32` is not used, because it is not available in browsers. - let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 - // Though, the bitmask solution is not perfect since the bytes exceeding - // the alphabet size are refused. Therefore, to reliably generate the ID, - // the random bytes redundancy has to be satisfied. - - // Note: every hardware random generator call is performance expensive, - // because the system call for entropy collection takes a lot of time. - // So, to avoid additional system calls, extra bytes are requested in advance. - - // Next, a step determines how many random bytes to generate. - // The number of random bytes gets decided upon the ID size, mask, - // alphabet size, and magic number 1.6 (using 1.6 peaks at performance - // according to benchmarks). - - // `-~f => Math.ceil(f)` if f is a float - // `-~i => i + 1` if i is an integer - let step = -~((1.6 * mask * defaultSize) / alphabet.length) - - return (size = defaultSize) => { - let id = '' - while (true) { - let bytes = getRandom(step) - // A compact alternative for `for (var i = 0; i < step; i++)`. - let j = step | 0 - while (j--) { - // Adding `|| ''` refuses a random byte that exceeds the alphabet size. - id += alphabet[bytes[j] & mask] || '' - if (id.length === size) return id - } - } - } -} - -let customAlphabet = (alphabet, size = 21) => - customRandom(alphabet, size, random) - -let nanoid = (size = 21) => - crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => { - // It is incorrect to use bytes exceeding the alphabet size. - // The following mask reduces the random byte in the 0-255 value - // range to the 0-63 value range. Therefore, adding hacks, such - // as empty string fallback or magic numbers, is unneccessary because - // the bitmask trims bytes down to the alphabet size. - byte &= 63 - if (byte < 36) { - // `0-9a-z` - id += byte.toString(36) - } else if (byte < 62) { - // `A-Z` - id += (byte - 26).toString(36).toUpperCase() - } else if (byte > 62) { - id += '-' - } else { - id += '_' - } - return id - }, '') - -module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.browser.js b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.browser.js deleted file mode 100644 index 7d3b876..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.browser.js +++ /dev/null @@ -1,34 +0,0 @@ -import { urlAlphabet } from './url-alphabet/index.js' -let random = bytes => crypto.getRandomValues(new Uint8Array(bytes)) -let customRandom = (alphabet, defaultSize, getRandom) => { - let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 - let step = -~((1.6 * mask * defaultSize) / alphabet.length) - return (size = defaultSize) => { - let id = '' - while (true) { - let bytes = getRandom(step) - let j = step | 0 - while (j--) { - id += alphabet[bytes[j] & mask] || '' - if (id.length === size) return id - } - } - } -} -let customAlphabet = (alphabet, size = 21) => - customRandom(alphabet, size, random) -let nanoid = (size = 21) => - crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => { - byte &= 63 - if (byte < 36) { - id += byte.toString(36) - } else if (byte < 62) { - id += (byte - 26).toString(36).toUpperCase() - } else if (byte > 62) { - id += '-' - } else { - id += '_' - } - return id - }, '') -export { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.cjs b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.cjs deleted file mode 100644 index c20e374..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.cjs +++ /dev/null @@ -1,85 +0,0 @@ -let crypto = require('crypto') - -let { urlAlphabet } = require('./url-alphabet/index.cjs') - -// It is best to make fewer, larger requests to the crypto module to -// avoid system call overhead. So, random numbers are generated in a -// pool. The pool is a Buffer that is larger than the initial random -// request size by this multiplier. The pool is enlarged if subsequent -// requests exceed the maximum buffer size. -const POOL_SIZE_MULTIPLIER = 128 -let pool, poolOffset - -let fillPool = bytes => { - if (!pool || pool.length < bytes) { - pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER) - crypto.randomFillSync(pool) - poolOffset = 0 - } else if (poolOffset + bytes > pool.length) { - crypto.randomFillSync(pool) - poolOffset = 0 - } - poolOffset += bytes -} - -let random = bytes => { - // `|=` convert `bytes` to number to prevent `valueOf` abusing and pool pollution - fillPool((bytes |= 0)) - return pool.subarray(poolOffset - bytes, poolOffset) -} - -let customRandom = (alphabet, defaultSize, getRandom) => { - // First, a bitmask is necessary to generate the ID. The bitmask makes bytes - // values closer to the alphabet size. The bitmask calculates the closest - // `2^31 - 1` number, which exceeds the alphabet size. - // For example, the bitmask for the alphabet size 30 is 31 (00011111). - let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 - // Though, the bitmask solution is not perfect since the bytes exceeding - // the alphabet size are refused. Therefore, to reliably generate the ID, - // the random bytes redundancy has to be satisfied. - - // Note: every hardware random generator call is performance expensive, - // because the system call for entropy collection takes a lot of time. - // So, to avoid additional system calls, extra bytes are requested in advance. - - // Next, a step determines how many random bytes to generate. - // The number of random bytes gets decided upon the ID size, mask, - // alphabet size, and magic number 1.6 (using 1.6 peaks at performance - // according to benchmarks). - let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) - - return (size = defaultSize) => { - let id = '' - while (true) { - let bytes = getRandom(step) - // A compact alternative for `for (let i = 0; i < step; i++)`. - let i = step - while (i--) { - // Adding `|| ''` refuses a random byte that exceeds the alphabet size. - id += alphabet[bytes[i] & mask] || '' - if (id.length === size) return id - } - } - } -} - -let customAlphabet = (alphabet, size = 21) => - customRandom(alphabet, size, random) - -let nanoid = (size = 21) => { - // `|=` convert `size` to number to prevent `valueOf` abusing and pool pollution - fillPool((size |= 0)) - let id = '' - // We are reading directly from the random pool to avoid creating new array - for (let i = poolOffset - size; i < poolOffset; i++) { - // It is incorrect to use bytes exceeding the alphabet size. - // The following mask reduces the random byte in the 0-255 value - // range to the 0-63 value range. Therefore, adding hacks, such - // as empty string fallback or magic numbers, is unneccessary because - // the bitmask trims bytes down to the alphabet size. - id += urlAlphabet[pool[i] & 63] - } - return id -} - -module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.d.cts b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.d.cts deleted file mode 100644 index 3e111a3..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.d.cts +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Generate secure URL-friendly unique ID. - * - * By default, the ID will have 21 symbols to have a collision probability - * similar to UUID v4. - * - * ```js - * import { nanoid } from 'nanoid' - * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" - * ``` - * - * @param size Size of the ID. The default size is 21. - * @returns A random string. - */ -export function nanoid(size?: number): string - -/** - * Generate secure unique ID with custom alphabet. - * - * Alphabet must contain 256 symbols or less. Otherwise, the generator - * will not be secure. - * - * @param alphabet Alphabet used to generate the ID. - * @param defaultSize Size of the ID. The default size is 21. - * @returns A random string generator. - * - * ```js - * const { customAlphabet } = require('nanoid') - * const nanoid = customAlphabet('0123456789абвгдеё', 5) - * nanoid() //=> "8ё56а" - * ``` - */ -export function customAlphabet( - alphabet: string, - defaultSize?: number -): (size?: number) => string - -/** - * Generate unique ID with custom random generator and alphabet. - * - * Alphabet must contain 256 symbols or less. Otherwise, the generator - * will not be secure. - * - * ```js - * import { customRandom } from 'nanoid/format' - * - * const nanoid = customRandom('abcdef', 5, size => { - * const random = [] - * for (let i = 0; i < size; i++) { - * random.push(randomByte()) - * } - * return random - * }) - * - * nanoid() //=> "fbaef" - * ``` - * - * @param alphabet Alphabet used to generate a random string. - * @param size Size of the random string. - * @param random A random bytes generator. - * @returns A random string generator. - */ -export function customRandom( - alphabet: string, - size: number, - random: (bytes: number) => Uint8Array -): () => string - -/** - * URL safe symbols. - * - * ```js - * import { urlAlphabet } from 'nanoid' - * const nanoid = customAlphabet(urlAlphabet, 10) - * nanoid() //=> "Uakgb_J5m9" - * ``` - */ -export const urlAlphabet: string - -/** - * Generate an array of random bytes collected from hardware noise. - * - * ```js - * import { customRandom, random } from 'nanoid' - * const nanoid = customRandom("abcdef", 5, random) - * ``` - * - * @param bytes Size of the array. - * @returns An array of random bytes. - */ -export function random(bytes: number): Uint8Array diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.d.ts b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.d.ts deleted file mode 100644 index 3e111a3..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.d.ts +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Generate secure URL-friendly unique ID. - * - * By default, the ID will have 21 symbols to have a collision probability - * similar to UUID v4. - * - * ```js - * import { nanoid } from 'nanoid' - * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" - * ``` - * - * @param size Size of the ID. The default size is 21. - * @returns A random string. - */ -export function nanoid(size?: number): string - -/** - * Generate secure unique ID with custom alphabet. - * - * Alphabet must contain 256 symbols or less. Otherwise, the generator - * will not be secure. - * - * @param alphabet Alphabet used to generate the ID. - * @param defaultSize Size of the ID. The default size is 21. - * @returns A random string generator. - * - * ```js - * const { customAlphabet } = require('nanoid') - * const nanoid = customAlphabet('0123456789абвгдеё', 5) - * nanoid() //=> "8ё56а" - * ``` - */ -export function customAlphabet( - alphabet: string, - defaultSize?: number -): (size?: number) => string - -/** - * Generate unique ID with custom random generator and alphabet. - * - * Alphabet must contain 256 symbols or less. Otherwise, the generator - * will not be secure. - * - * ```js - * import { customRandom } from 'nanoid/format' - * - * const nanoid = customRandom('abcdef', 5, size => { - * const random = [] - * for (let i = 0; i < size; i++) { - * random.push(randomByte()) - * } - * return random - * }) - * - * nanoid() //=> "fbaef" - * ``` - * - * @param alphabet Alphabet used to generate a random string. - * @param size Size of the random string. - * @param random A random bytes generator. - * @returns A random string generator. - */ -export function customRandom( - alphabet: string, - size: number, - random: (bytes: number) => Uint8Array -): () => string - -/** - * URL safe symbols. - * - * ```js - * import { urlAlphabet } from 'nanoid' - * const nanoid = customAlphabet(urlAlphabet, 10) - * nanoid() //=> "Uakgb_J5m9" - * ``` - */ -export const urlAlphabet: string - -/** - * Generate an array of random bytes collected from hardware noise. - * - * ```js - * import { customRandom, random } from 'nanoid' - * const nanoid = customRandom("abcdef", 5, random) - * ``` - * - * @param bytes Size of the array. - * @returns An array of random bytes. - */ -export function random(bytes: number): Uint8Array diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.js b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.js deleted file mode 100644 index 9bc909d..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/index.js +++ /dev/null @@ -1,45 +0,0 @@ -import crypto from 'crypto' -import { urlAlphabet } from './url-alphabet/index.js' -const POOL_SIZE_MULTIPLIER = 128 -let pool, poolOffset -let fillPool = bytes => { - if (!pool || pool.length < bytes) { - pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER) - crypto.randomFillSync(pool) - poolOffset = 0 - } else if (poolOffset + bytes > pool.length) { - crypto.randomFillSync(pool) - poolOffset = 0 - } - poolOffset += bytes -} -let random = bytes => { - fillPool((bytes |= 0)) - return pool.subarray(poolOffset - bytes, poolOffset) -} -let customRandom = (alphabet, defaultSize, getRandom) => { - let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 - let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length) - return (size = defaultSize) => { - let id = '' - while (true) { - let bytes = getRandom(step) - let i = step - while (i--) { - id += alphabet[bytes[i] & mask] || '' - if (id.length === size) return id - } - } - } -} -let customAlphabet = (alphabet, size = 21) => - customRandom(alphabet, size, random) -let nanoid = (size = 21) => { - fillPool((size |= 0)) - let id = '' - for (let i = poolOffset - size; i < poolOffset; i++) { - id += urlAlphabet[pool[i] & 63] - } - return id -} -export { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/nanoid.js b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/nanoid.js deleted file mode 100644 index ec242ea..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/nanoid.js +++ /dev/null @@ -1 +0,0 @@ -export let nanoid=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce(((t,e)=>t+=(e&=63)<36?e.toString(36):e<62?(e-26).toString(36).toUpperCase():e<63?"_":"-"),""); \ No newline at end of file diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/non-secure/index.cjs b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/non-secure/index.cjs deleted file mode 100644 index d51fcb6..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/non-secure/index.cjs +++ /dev/null @@ -1,34 +0,0 @@ -// This alphabet uses `A-Za-z0-9_-` symbols. -// The order of characters is optimized for better gzip and brotli compression. -// References to the same file (works both for gzip and brotli): -// `'use`, `andom`, and `rict'` -// References to the brotli default dictionary: -// `-26T`, `1983`, `40px`, `75px`, `bush`, `jack`, `mind`, `very`, and `wolf` -let urlAlphabet = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' - -let customAlphabet = (alphabet, defaultSize = 21) => { - return (size = defaultSize) => { - let id = '' - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = size | 0 - while (i--) { - // `| 0` is more compact and faster than `Math.floor()`. - id += alphabet[(Math.random() * alphabet.length) | 0] - } - return id - } -} - -let nanoid = (size = 21) => { - let id = '' - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = size | 0 - while (i--) { - // `| 0` is more compact and faster than `Math.floor()`. - id += urlAlphabet[(Math.random() * 64) | 0] - } - return id -} - -module.exports = { nanoid, customAlphabet } diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/non-secure/index.d.ts b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/non-secure/index.d.ts deleted file mode 100644 index 4965322..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/non-secure/index.d.ts +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Generate URL-friendly unique ID. This method uses the non-secure - * predictable random generator with bigger collision probability. - * - * ```js - * import { nanoid } from 'nanoid/non-secure' - * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" - * ``` - * - * @param size Size of the ID. The default size is 21. - * @returns A random string. - */ -export function nanoid(size?: number): string - -/** - * Generate a unique ID based on a custom alphabet. - * This method uses the non-secure predictable random generator - * with bigger collision probability. - * - * @param alphabet Alphabet used to generate the ID. - * @param defaultSize Size of the ID. The default size is 21. - * @returns A random string generator. - * - * ```js - * import { customAlphabet } from 'nanoid/non-secure' - * const nanoid = customAlphabet('0123456789абвгдеё', 5) - * model.id = //=> "8ё56а" - * ``` - */ -export function customAlphabet( - alphabet: string, - defaultSize?: number -): (size?: number) => string diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/non-secure/index.js b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/non-secure/index.js deleted file mode 100644 index 2ea5827..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/non-secure/index.js +++ /dev/null @@ -1,21 +0,0 @@ -let urlAlphabet = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' -let customAlphabet = (alphabet, defaultSize = 21) => { - return (size = defaultSize) => { - let id = '' - let i = size | 0 - while (i--) { - id += alphabet[(Math.random() * alphabet.length) | 0] - } - return id - } -} -let nanoid = (size = 21) => { - let id = '' - let i = size | 0 - while (i--) { - id += urlAlphabet[(Math.random() * 64) | 0] - } - return id -} -export { nanoid, customAlphabet } diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/non-secure/package.json b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/non-secure/package.json deleted file mode 100644 index 9930d6a..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/non-secure/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "type": "module", - "main": "index.cjs", - "module": "index.js", - "react-native": "index.js" -} \ No newline at end of file diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/package.json b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/package.json deleted file mode 100644 index a3d3f44..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/package.json +++ /dev/null @@ -1,89 +0,0 @@ -{ - "name": "nanoid", - "version": "3.3.11", - "description": "A tiny (116 bytes), secure URL-friendly unique string ID generator", - "keywords": [ - "uuid", - "random", - "id", - "url" - ], - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - }, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/ai" - } - ], - "author": "Andrey Sitnik ", - "license": "MIT", - "repository": "ai/nanoid", - "browser": { - "./index.js": "./index.browser.js", - "./async/index.js": "./async/index.browser.js", - "./async/index.cjs": "./async/index.browser.cjs", - "./index.cjs": "./index.browser.cjs" - }, - "react-native": "index.js", - "bin": "./bin/nanoid.cjs", - "sideEffects": false, - "types": "./index.d.ts", - "type": "module", - "main": "index.cjs", - "module": "index.js", - "exports": { - ".": { - "react-native": "./index.browser.js", - "browser": "./index.browser.js", - "require": { - "types": "./index.d.cts", - "default": "./index.cjs" - }, - "import": { - "types": "./index.d.ts", - "default": "./index.js" - }, - "default": "./index.js" - }, - "./package.json": "./package.json", - "./async/package.json": "./async/package.json", - "./async": { - "browser": "./async/index.browser.js", - "require": { - "types": "./index.d.cts", - "default": "./async/index.cjs" - }, - "import": { - "types": "./index.d.ts", - "default": "./async/index.js" - }, - "default": "./async/index.js" - }, - "./non-secure/package.json": "./non-secure/package.json", - "./non-secure": { - "require": { - "types": "./index.d.cts", - "default": "./non-secure/index.cjs" - }, - "import": { - "types": "./index.d.ts", - "default": "./non-secure/index.js" - }, - "default": "./non-secure/index.js" - }, - "./url-alphabet/package.json": "./url-alphabet/package.json", - "./url-alphabet": { - "require": { - "types": "./index.d.cts", - "default": "./url-alphabet/index.cjs" - }, - "import": { - "types": "./index.d.ts", - "default": "./url-alphabet/index.js" - }, - "default": "./url-alphabet/index.js" - } - } -} diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/url-alphabet/index.cjs b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/url-alphabet/index.cjs deleted file mode 100644 index a332f0b..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/url-alphabet/index.cjs +++ /dev/null @@ -1,7 +0,0 @@ -// This alphabet uses `A-Za-z0-9_-` symbols. -// The order of characters is optimized for better gzip and brotli compression. -// Same as in non-secure/index.js -let urlAlphabet = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' - -module.exports = { urlAlphabet } diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/url-alphabet/index.js b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/url-alphabet/index.js deleted file mode 100644 index c2782e5..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/url-alphabet/index.js +++ /dev/null @@ -1,3 +0,0 @@ -let urlAlphabet = - 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' -export { urlAlphabet } diff --git a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/url-alphabet/package.json b/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/url-alphabet/package.json deleted file mode 100644 index 9930d6a..0000000 --- a/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/url-alphabet/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "type": "module", - "main": "index.cjs", - "module": "index.js", - "react-native": "index.js" -} \ No newline at end of file diff --git a/node_modules/.pnpm/node_modules/.bin/esbuild b/node_modules/.pnpm/node_modules/.bin/esbuild deleted file mode 100644 index 2483c2c..0000000 --- a/node_modules/.pnpm/node_modules/.bin/esbuild +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*|*MINGW*|*MSYS*) - if command -v cygpath > /dev/null 2>&1; then - basedir=`cygpath -w "$basedir"` - fi - ;; -esac - -if [ -z "$NODE_PATH" ]; then - export NODE_PATH="/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/bin/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/esbuild@0.21.5/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/node_modules" -else - export NODE_PATH="/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/bin/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/esbuild@0.21.5/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/node_modules:$NODE_PATH" -fi -if [ -x "$basedir/node" ]; then - exec "$basedir/node" "$basedir/../esbuild/bin/esbuild" "$@" -else - exec node "$basedir/../esbuild/bin/esbuild" "$@" -fi diff --git a/node_modules/.pnpm/node_modules/.bin/esbuild.ps1 b/node_modules/.pnpm/node_modules/.bin/esbuild.ps1 deleted file mode 100644 index 4058a92..0000000 --- a/node_modules/.pnpm/node_modules/.bin/esbuild.ps1 +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env pwsh -$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent - -$exe="" -$pathsep=":" -$env_node_path=$env:NODE_PATH -$new_node_path="F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\esbuild@0.21.5\node_modules\esbuild\bin\node_modules;F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\esbuild@0.21.5\node_modules\esbuild\node_modules;F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\esbuild@0.21.5\node_modules;F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\node_modules" -if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { - # Fix case when both the Windows and Linux builds of Node - # are installed in the same directory - $exe=".exe" - $pathsep=";" -} else { - $new_node_path="/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/bin/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/esbuild@0.21.5/node_modules/esbuild/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/esbuild@0.21.5/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/node_modules" -} -if ([string]::IsNullOrEmpty($env_node_path)) { - $env:NODE_PATH=$new_node_path -} else { - $env:NODE_PATH="$new_node_path$pathsep$env_node_path" -} - -$ret=0 -if (Test-Path "$basedir/node$exe") { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "$basedir/node$exe" "$basedir/../esbuild/bin/esbuild" $args - } else { - & "$basedir/node$exe" "$basedir/../esbuild/bin/esbuild" $args - } - $ret=$LASTEXITCODE -} else { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "node$exe" "$basedir/../esbuild/bin/esbuild" $args - } else { - & "node$exe" "$basedir/../esbuild/bin/esbuild" $args - } - $ret=$LASTEXITCODE -} -$env:NODE_PATH=$env_node_path -exit $ret diff --git a/node_modules/.pnpm/node_modules/.bin/nanoid b/node_modules/.pnpm/node_modules/.bin/nanoid deleted file mode 100644 index c9473fa..0000000 --- a/node_modules/.pnpm/node_modules/.bin/nanoid +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*|*MINGW*|*MSYS*) - if command -v cygpath > /dev/null 2>&1; then - basedir=`cygpath -w "$basedir"` - fi - ;; -esac - -if [ -z "$NODE_PATH" ]; then - export NODE_PATH="/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/bin/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/nanoid@3.3.11/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/node_modules" -else - export NODE_PATH="/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/bin/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/nanoid@3.3.11/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/node_modules:$NODE_PATH" -fi -if [ -x "$basedir/node" ]; then - exec "$basedir/node" "$basedir/../nanoid/bin/nanoid.cjs" "$@" -else - exec node "$basedir/../nanoid/bin/nanoid.cjs" "$@" -fi diff --git a/node_modules/.pnpm/node_modules/.bin/nanoid.ps1 b/node_modules/.pnpm/node_modules/.bin/nanoid.ps1 deleted file mode 100644 index ae64c8c..0000000 --- a/node_modules/.pnpm/node_modules/.bin/nanoid.ps1 +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env pwsh -$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent - -$exe="" -$pathsep=":" -$env_node_path=$env:NODE_PATH -$new_node_path="F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\nanoid@3.3.11\node_modules\nanoid\bin\node_modules;F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\nanoid@3.3.11\node_modules\nanoid\node_modules;F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\nanoid@3.3.11\node_modules;F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\node_modules" -if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { - # Fix case when both the Windows and Linux builds of Node - # are installed in the same directory - $exe=".exe" - $pathsep=";" -} else { - $new_node_path="/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/bin/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/nanoid@3.3.11/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/node_modules" -} -if ([string]::IsNullOrEmpty($env_node_path)) { - $env:NODE_PATH=$new_node_path -} else { - $env:NODE_PATH="$new_node_path$pathsep$env_node_path" -} - -$ret=0 -if (Test-Path "$basedir/node$exe") { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args - } else { - & "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args - } - $ret=$LASTEXITCODE -} else { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args - } else { - & "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args - } - $ret=$LASTEXITCODE -} -$env:NODE_PATH=$env_node_path -exit $ret diff --git a/node_modules/.pnpm/node_modules/.bin/rollup b/node_modules/.pnpm/node_modules/.bin/rollup deleted file mode 100644 index 24e9852..0000000 --- a/node_modules/.pnpm/node_modules/.bin/rollup +++ /dev/null @@ -1,21 +0,0 @@ -#!/bin/sh -basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") - -case `uname` in - *CYGWIN*|*MINGW*|*MSYS*) - if command -v cygpath > /dev/null 2>&1; then - basedir=`cygpath -w "$basedir"` - fi - ;; -esac - -if [ -z "$NODE_PATH" ]; then - export NODE_PATH="/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/rollup@4.40.2/node_modules/rollup/dist/bin/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/rollup@4.40.2/node_modules/rollup/dist/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/rollup@4.40.2/node_modules/rollup/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/rollup@4.40.2/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/node_modules" -else - export NODE_PATH="/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/rollup@4.40.2/node_modules/rollup/dist/bin/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/rollup@4.40.2/node_modules/rollup/dist/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/rollup@4.40.2/node_modules/rollup/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/rollup@4.40.2/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/node_modules:$NODE_PATH" -fi -if [ -x "$basedir/node" ]; then - exec "$basedir/node" "$basedir/../rollup/dist/bin/rollup" "$@" -else - exec node "$basedir/../rollup/dist/bin/rollup" "$@" -fi diff --git a/node_modules/.pnpm/node_modules/.bin/rollup.ps1 b/node_modules/.pnpm/node_modules/.bin/rollup.ps1 deleted file mode 100644 index e50b9c3..0000000 --- a/node_modules/.pnpm/node_modules/.bin/rollup.ps1 +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env pwsh -$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent - -$exe="" -$pathsep=":" -$env_node_path=$env:NODE_PATH -$new_node_path="F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\rollup@4.40.2\node_modules\rollup\dist\bin\node_modules;F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\rollup@4.40.2\node_modules\rollup\dist\node_modules;F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\rollup@4.40.2\node_modules\rollup\node_modules;F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\rollup@4.40.2\node_modules;F:\htmlWork\项目\德基demo\deji_demo\node_modules\.pnpm\node_modules" -if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { - # Fix case when both the Windows and Linux builds of Node - # are installed in the same directory - $exe=".exe" - $pathsep=";" -} else { - $new_node_path="/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/rollup@4.40.2/node_modules/rollup/dist/bin/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/rollup@4.40.2/node_modules/rollup/dist/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/rollup@4.40.2/node_modules/rollup/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/rollup@4.40.2/node_modules:/mnt/f/htmlWork/项目/德基demo/deji_demo/node_modules/.pnpm/node_modules" -} -if ([string]::IsNullOrEmpty($env_node_path)) { - $env:NODE_PATH=$new_node_path -} else { - $env:NODE_PATH="$new_node_path$pathsep$env_node_path" -} - -$ret=0 -if (Test-Path "$basedir/node$exe") { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "$basedir/node$exe" "$basedir/../rollup/dist/bin/rollup" $args - } else { - & "$basedir/node$exe" "$basedir/../rollup/dist/bin/rollup" $args - } - $ret=$LASTEXITCODE -} else { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "node$exe" "$basedir/../rollup/dist/bin/rollup" $args - } else { - & "node$exe" "$basedir/../rollup/dist/bin/rollup" $args - } - $ret=$LASTEXITCODE -} -$env:NODE_PATH=$env_node_path -exit $ret diff --git a/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/LICENSE b/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/LICENSE deleted file mode 100644 index 46c9b95..0000000 --- a/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -ISC License - -Copyright (c) 2021-2024 Oleksii Raspopov, Kostiantyn Denysov, Anton Verinov - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/README.md b/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/README.md deleted file mode 100644 index 8e47aa8..0000000 --- a/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/README.md +++ /dev/null @@ -1,21 +0,0 @@ -# picocolors - -The tiniest and the fastest library for terminal output formatting with ANSI colors. - -```javascript -import pc from "picocolors" - -console.log( - pc.green(`How are ${pc.italic(`you`)} doing?`) -) -``` - -- **No dependencies.** -- **14 times** smaller and **2 times** faster than chalk. -- Used by popular tools like PostCSS, SVGO, Stylelint, and Browserslist. -- Node.js v6+ & browsers support. Support for both CJS and ESM projects. -- TypeScript type declarations included. -- [`NO_COLOR`](https://no-color.org/) friendly. - -## Docs -Read **[full docs](https://github.com/alexeyraspopov/picocolors#readme)** on GitHub. diff --git a/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/package.json b/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/package.json deleted file mode 100644 index 372d4b6..0000000 --- a/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "name": "picocolors", - "version": "1.1.1", - "main": "./picocolors.js", - "types": "./picocolors.d.ts", - "browser": { - "./picocolors.js": "./picocolors.browser.js" - }, - "sideEffects": false, - "description": "The tiniest and the fastest library for terminal output formatting with ANSI colors", - "files": [ - "picocolors.*", - "types.d.ts" - ], - "keywords": [ - "terminal", - "colors", - "formatting", - "cli", - "console" - ], - "author": "Alexey Raspopov", - "repository": "alexeyraspopov/picocolors", - "license": "ISC" -} diff --git a/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.browser.js b/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.browser.js deleted file mode 100644 index 9dcf637..0000000 --- a/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.browser.js +++ /dev/null @@ -1,4 +0,0 @@ -var x=String; -var create=function() {return {isColorSupported:false,reset:x,bold:x,dim:x,italic:x,underline:x,inverse:x,hidden:x,strikethrough:x,black:x,red:x,green:x,yellow:x,blue:x,magenta:x,cyan:x,white:x,gray:x,bgBlack:x,bgRed:x,bgGreen:x,bgYellow:x,bgBlue:x,bgMagenta:x,bgCyan:x,bgWhite:x,blackBright:x,redBright:x,greenBright:x,yellowBright:x,blueBright:x,magentaBright:x,cyanBright:x,whiteBright:x,bgBlackBright:x,bgRedBright:x,bgGreenBright:x,bgYellowBright:x,bgBlueBright:x,bgMagentaBright:x,bgCyanBright:x,bgWhiteBright:x}}; -module.exports=create(); -module.exports.createColors = create; diff --git a/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.d.ts b/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.d.ts deleted file mode 100644 index 94e146a..0000000 --- a/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -import { Colors } from "./types" - -declare const picocolors: Colors & { createColors: (enabled?: boolean) => Colors } - -export = picocolors diff --git a/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js b/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js deleted file mode 100644 index e32df85..0000000 --- a/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js +++ /dev/null @@ -1,75 +0,0 @@ -let p = process || {}, argv = p.argv || [], env = p.env || {} -let isColorSupported = - !(!!env.NO_COLOR || argv.includes("--no-color")) && - (!!env.FORCE_COLOR || argv.includes("--color") || p.platform === "win32" || ((p.stdout || {}).isTTY && env.TERM !== "dumb") || !!env.CI) - -let formatter = (open, close, replace = open) => - input => { - let string = "" + input, index = string.indexOf(close, open.length) - return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close - } - -let replaceClose = (string, close, replace, index) => { - let result = "", cursor = 0 - do { - result += string.substring(cursor, index) + replace - cursor = index + close.length - index = string.indexOf(close, cursor) - } while (~index) - return result + string.substring(cursor) -} - -let createColors = (enabled = isColorSupported) => { - let f = enabled ? formatter : () => String - return { - isColorSupported: enabled, - reset: f("\x1b[0m", "\x1b[0m"), - bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), - dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), - italic: f("\x1b[3m", "\x1b[23m"), - underline: f("\x1b[4m", "\x1b[24m"), - inverse: f("\x1b[7m", "\x1b[27m"), - hidden: f("\x1b[8m", "\x1b[28m"), - strikethrough: f("\x1b[9m", "\x1b[29m"), - - black: f("\x1b[30m", "\x1b[39m"), - red: f("\x1b[31m", "\x1b[39m"), - green: f("\x1b[32m", "\x1b[39m"), - yellow: f("\x1b[33m", "\x1b[39m"), - blue: f("\x1b[34m", "\x1b[39m"), - magenta: f("\x1b[35m", "\x1b[39m"), - cyan: f("\x1b[36m", "\x1b[39m"), - white: f("\x1b[37m", "\x1b[39m"), - gray: f("\x1b[90m", "\x1b[39m"), - - bgBlack: f("\x1b[40m", "\x1b[49m"), - bgRed: f("\x1b[41m", "\x1b[49m"), - bgGreen: f("\x1b[42m", "\x1b[49m"), - bgYellow: f("\x1b[43m", "\x1b[49m"), - bgBlue: f("\x1b[44m", "\x1b[49m"), - bgMagenta: f("\x1b[45m", "\x1b[49m"), - bgCyan: f("\x1b[46m", "\x1b[49m"), - bgWhite: f("\x1b[47m", "\x1b[49m"), - - blackBright: f("\x1b[90m", "\x1b[39m"), - redBright: f("\x1b[91m", "\x1b[39m"), - greenBright: f("\x1b[92m", "\x1b[39m"), - yellowBright: f("\x1b[93m", "\x1b[39m"), - blueBright: f("\x1b[94m", "\x1b[39m"), - magentaBright: f("\x1b[95m", "\x1b[39m"), - cyanBright: f("\x1b[96m", "\x1b[39m"), - whiteBright: f("\x1b[97m", "\x1b[39m"), - - bgBlackBright: f("\x1b[100m", "\x1b[49m"), - bgRedBright: f("\x1b[101m", "\x1b[49m"), - bgGreenBright: f("\x1b[102m", "\x1b[49m"), - bgYellowBright: f("\x1b[103m", "\x1b[49m"), - bgBlueBright: f("\x1b[104m", "\x1b[49m"), - bgMagentaBright: f("\x1b[105m", "\x1b[49m"), - bgCyanBright: f("\x1b[106m", "\x1b[49m"), - bgWhiteBright: f("\x1b[107m", "\x1b[49m"), - } -} - -module.exports = createColors() -module.exports.createColors = createColors diff --git a/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/types.d.ts b/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/types.d.ts deleted file mode 100644 index cd1aec4..0000000 --- a/node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/types.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -export type Formatter = (input: string | number | null | undefined) => string - -export interface Colors { - isColorSupported: boolean - - reset: Formatter - bold: Formatter - dim: Formatter - italic: Formatter - underline: Formatter - inverse: Formatter - hidden: Formatter - strikethrough: Formatter - - black: Formatter - red: Formatter - green: Formatter - yellow: Formatter - blue: Formatter - magenta: Formatter - cyan: Formatter - white: Formatter - gray: Formatter - - bgBlack: Formatter - bgRed: Formatter - bgGreen: Formatter - bgYellow: Formatter - bgBlue: Formatter - bgMagenta: Formatter - bgCyan: Formatter - bgWhite: Formatter - - blackBright: Formatter - redBright: Formatter - greenBright: Formatter - yellowBright: Formatter - blueBright: Formatter - magentaBright: Formatter - cyanBright: Formatter - whiteBright: Formatter - - bgBlackBright: Formatter - bgRedBright: Formatter - bgGreenBright: Formatter - bgYellowBright: Formatter - bgBlueBright: Formatter - bgMagentaBright: Formatter - bgCyanBright: Formatter - bgWhiteBright: Formatter -} diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/LICENSE b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/LICENSE deleted file mode 100644 index da057b4..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright 2013 Andrey Sitnik - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/README.md b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/README.md deleted file mode 100644 index 939a802..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# PostCSS - -Philosopher’s stone, logo of PostCSS - -PostCSS is a tool for transforming styles with JS plugins. -These plugins can lint your CSS, support variables and mixins, -transpile future CSS syntax, inline images, and more. - -PostCSS is used by industry leaders including Wikipedia, Twitter, Alibaba, -and JetBrains. The [Autoprefixer] and [Stylelint] PostCSS plugins is one of the most popular CSS tools. - ---- - -  Made at Evil Martians, product consulting for developer tools. - ---- - -[Abstract Syntax Tree]: https://en.wikipedia.org/wiki/Abstract_syntax_tree -[Evil Martians]: https://evilmartians.com/?utm_source=postcss -[Autoprefixer]: https://github.com/postcss/autoprefixer -[Stylelint]: https://stylelint.io/ -[plugins]: https://github.com/postcss/postcss#plugins - - -## Docs -Read full docs **[here](https://postcss.org/)**. diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/at-rule.d.ts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/at-rule.d.ts deleted file mode 100644 index 89fb505..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/at-rule.d.ts +++ /dev/null @@ -1,140 +0,0 @@ -import Container, { - ContainerProps, - ContainerWithChildren -} from './container.js' - -declare namespace AtRule { - export interface AtRuleRaws extends Record { - /** - * The space symbols after the last child of the node to the end of the node. - */ - after?: string - - /** - * The space between the at-rule name and its parameters. - */ - afterName?: string - - /** - * The space symbols before the node. It also stores `*` - * and `_` symbols before the declaration (IE hack). - */ - before?: string - - /** - * The symbols between the last parameter and `{` for rules. - */ - between?: string - - /** - * The rule’s selector with comments. - */ - params?: { - raw: string - value: string - } - - /** - * Contains `true` if the last child has an (optional) semicolon. - */ - semicolon?: boolean - } - - export interface AtRuleProps extends ContainerProps { - /** Name of the at-rule. */ - name: string - /** Parameters following the name of the at-rule. */ - params?: number | string - /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ - raws?: AtRuleRaws - } - - // eslint-disable-next-line @typescript-eslint/no-use-before-define - export { AtRule_ as default } -} - -/** - * Represents an at-rule. - * - * ```js - * Once (root, { AtRule }) { - * let media = new AtRule({ name: 'media', params: 'print' }) - * media.append(…) - * root.append(media) - * } - * ``` - * - * If it’s followed in the CSS by a `{}` block, this node will have - * a nodes property representing its children. - * - * ```js - * const root = postcss.parse('@charset "UTF-8"; @media print {}') - * - * const charset = root.first - * charset.type //=> 'atrule' - * charset.nodes //=> undefined - * - * const media = root.last - * media.nodes //=> [] - * ``` - */ -declare class AtRule_ extends Container { - /** - * An array containing the layer’s children. - * - * ```js - * const root = postcss.parse('@layer example { a { color: black } }') - * const layer = root.first - * layer.nodes.length //=> 1 - * layer.nodes[0].selector //=> 'a' - * ``` - * - * Can be `undefinded` if the at-rule has no body. - * - * ```js - * const root = postcss.parse('@layer a, b, c;') - * const layer = root.first - * layer.nodes //=> undefined - * ``` - */ - nodes: Container['nodes'] | undefined - parent: ContainerWithChildren | undefined - - raws: AtRule.AtRuleRaws - type: 'atrule' - /** - * The at-rule’s name immediately follows the `@`. - * - * ```js - * const root = postcss.parse('@media print {}') - * const media = root.first - * media.name //=> 'media' - * ``` - */ - get name(): string - set name(value: string) - - /** - * The at-rule’s parameters, the values that follow the at-rule’s name - * but precede any `{}` block. - * - * ```js - * const root = postcss.parse('@media print, screen {}') - * const media = root.first - * media.params //=> 'print, screen' - * ``` - */ - get params(): string - - set params(value: string) - - constructor(defaults?: AtRule.AtRuleProps) - assign(overrides: AtRule.AtRuleProps | object): this - clone(overrides?: Partial): this - cloneAfter(overrides?: Partial): this - cloneBefore(overrides?: Partial): this -} - -declare class AtRule extends AtRule_ {} - -export = AtRule diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/at-rule.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/at-rule.js deleted file mode 100644 index 9486447..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/at-rule.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict' - -let Container = require('./container') - -class AtRule extends Container { - constructor(defaults) { - super(defaults) - this.type = 'atrule' - } - - append(...children) { - if (!this.proxyOf.nodes) this.nodes = [] - return super.append(...children) - } - - prepend(...children) { - if (!this.proxyOf.nodes) this.nodes = [] - return super.prepend(...children) - } -} - -module.exports = AtRule -AtRule.default = AtRule - -Container.registerAtRule(AtRule) diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/comment.d.ts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/comment.d.ts deleted file mode 100644 index 6f1f66f..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/comment.d.ts +++ /dev/null @@ -1,68 +0,0 @@ -import Container from './container.js' -import Node, { NodeProps } from './node.js' - -declare namespace Comment { - export interface CommentRaws extends Record { - /** - * The space symbols before the node. - */ - before?: string - - /** - * The space symbols between `/*` and the comment’s text. - */ - left?: string - - /** - * The space symbols between the comment’s text. - */ - right?: string - } - - export interface CommentProps extends NodeProps { - /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ - raws?: CommentRaws - /** Content of the comment. */ - text: string - } - - // eslint-disable-next-line @typescript-eslint/no-use-before-define - export { Comment_ as default } -} - -/** - * It represents a class that handles - * [CSS comments](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments) - * - * ```js - * Once (root, { Comment }) { - * const note = new Comment({ text: 'Note: …' }) - * root.append(note) - * } - * ``` - * - * Remember that CSS comments inside selectors, at-rule parameters, - * or declaration values will be stored in the `raws` properties - * explained above. - */ -declare class Comment_ extends Node { - parent: Container | undefined - raws: Comment.CommentRaws - type: 'comment' - /** - * The comment's text. - */ - get text(): string - - set text(value: string) - - constructor(defaults?: Comment.CommentProps) - assign(overrides: Comment.CommentProps | object): this - clone(overrides?: Partial): this - cloneAfter(overrides?: Partial): this - cloneBefore(overrides?: Partial): this -} - -declare class Comment extends Comment_ {} - -export = Comment diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/comment.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/comment.js deleted file mode 100644 index c566506..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/comment.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict' - -let Node = require('./node') - -class Comment extends Node { - constructor(defaults) { - super(defaults) - this.type = 'comment' - } -} - -module.exports = Comment -Comment.default = Comment diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/container.d.ts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/container.d.ts deleted file mode 100644 index 9569f34..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/container.d.ts +++ /dev/null @@ -1,480 +0,0 @@ -import AtRule from './at-rule.js' -import Comment from './comment.js' -import Declaration from './declaration.js' -import Node, { ChildNode, ChildProps, NodeProps } from './node.js' -import Rule from './rule.js' - -declare namespace Container { - export class ContainerWithChildren< - Child extends Node = ChildNode - > extends Container_ { - nodes: Child[] - } - - export interface ValueOptions { - /** - * String that’s used to narrow down values and speed up the regexp search. - */ - fast?: string - - /** - * An array of property names. - */ - props?: readonly string[] - } - - export interface ContainerProps extends NodeProps { - nodes?: readonly (ChildProps | Node)[] - } - - /** - * All types that can be passed into container methods to create or add a new - * child node. - */ - export type NewChild = - | ChildProps - | Node - | readonly ChildProps[] - | readonly Node[] - | readonly string[] - | string - | undefined - - // eslint-disable-next-line @typescript-eslint/no-use-before-define - export { Container_ as default } -} - -/** - * The `Root`, `AtRule`, and `Rule` container nodes - * inherit some common methods to help work with their children. - * - * Note that all containers can store any content. If you write a rule inside - * a rule, PostCSS will parse it. - */ -declare abstract class Container_ extends Node { - /** - * An array containing the container’s children. - * - * ```js - * const root = postcss.parse('a { color: black }') - * root.nodes.length //=> 1 - * root.nodes[0].selector //=> 'a' - * root.nodes[0].nodes[0].prop //=> 'color' - * ``` - */ - nodes: Child[] | undefined - - /** - * The container’s first child. - * - * ```js - * rule.first === rules.nodes[0] - * ``` - */ - get first(): Child | undefined - - /** - * The container’s last child. - * - * ```js - * rule.last === rule.nodes[rule.nodes.length - 1] - * ``` - */ - get last(): Child | undefined - /** - * Inserts new nodes to the end of the container. - * - * ```js - * const decl1 = new Declaration({ prop: 'color', value: 'black' }) - * const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) - * rule.append(decl1, decl2) - * - * root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule - * root.append({ selector: 'a' }) // rule - * rule.append({ prop: 'color', value: 'black' }) // declaration - * rule.append({ text: 'Comment' }) // comment - * - * root.append('a {}') - * root.first.append('color: black; z-index: 1') - * ``` - * - * @param nodes New nodes. - * @return This node for methods chain. - */ - append(...nodes: Container.NewChild[]): this - assign(overrides: Container.ContainerProps | object): this - clone(overrides?: Partial): this - - cloneAfter(overrides?: Partial): this - - cloneBefore(overrides?: Partial): this - /** - * Iterates through the container’s immediate children, - * calling `callback` for each child. - * - * Returning `false` in the callback will break iteration. - * - * This method only iterates through the container’s immediate children. - * If you need to recursively iterate through all the container’s descendant - * nodes, use `Container#walk`. - * - * Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe - * if you are mutating the array of child nodes during iteration. - * PostCSS will adjust the current index to match the mutations. - * - * ```js - * const root = postcss.parse('a { color: black; z-index: 1 }') - * const rule = root.first - * - * for (const decl of rule.nodes) { - * decl.cloneBefore({ prop: '-webkit-' + decl.prop }) - * // Cycle will be infinite, because cloneBefore moves the current node - * // to the next index - * } - * - * rule.each(decl => { - * decl.cloneBefore({ prop: '-webkit-' + decl.prop }) - * // Will be executed only for color and z-index - * }) - * ``` - * - * @param callback Iterator receives each node and index. - * @return Returns `false` if iteration was broke. - */ - each( - callback: (node: Child, index: number) => false | void - ): false | undefined - - /** - * Returns `true` if callback returns `true` - * for all of the container’s children. - * - * ```js - * const noPrefixes = rule.every(i => i.prop[0] !== '-') - * ``` - * - * @param condition Iterator returns true or false. - * @return Is every child pass condition. - */ - every( - condition: (node: Child, index: number, nodes: Child[]) => boolean - ): boolean - /** - * Returns a `child`’s index within the `Container#nodes` array. - * - * ```js - * rule.index( rule.nodes[2] ) //=> 2 - * ``` - * - * @param child Child of the current container. - * @return Child index. - */ - index(child: Child | number): number - - /** - * Insert new node after old node within the container. - * - * @param oldNode Child or child’s index. - * @param newNode New node. - * @return This node for methods chain. - */ - insertAfter(oldNode: Child | number, newNode: Container.NewChild): this - - /** - * Traverses the container’s descendant nodes, calling callback - * for each comment node. - * - * Like `Container#each`, this method is safe - * to use if you are mutating arrays during iteration. - * - * ```js - * root.walkComments(comment => { - * comment.remove() - * }) - * ``` - * - * @param callback Iterator receives each node and index. - * @return Returns `false` if iteration was broke. - */ - - /** - * Insert new node before old node within the container. - * - * ```js - * rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop })) - * ``` - * - * @param oldNode Child or child’s index. - * @param newNode New node. - * @return This node for methods chain. - */ - insertBefore(oldNode: Child | number, newNode: Container.NewChild): this - /** - * Inserts new nodes to the start of the container. - * - * ```js - * const decl1 = new Declaration({ prop: 'color', value: 'black' }) - * const decl2 = new Declaration({ prop: 'background-color', value: 'white' }) - * rule.prepend(decl1, decl2) - * - * root.append({ name: 'charset', params: '"UTF-8"' }) // at-rule - * root.append({ selector: 'a' }) // rule - * rule.append({ prop: 'color', value: 'black' }) // declaration - * rule.append({ text: 'Comment' }) // comment - * - * root.append('a {}') - * root.first.append('color: black; z-index: 1') - * ``` - * - * @param nodes New nodes. - * @return This node for methods chain. - */ - prepend(...nodes: Container.NewChild[]): this - - /** - * Add child to the end of the node. - * - * ```js - * rule.push(new Declaration({ prop: 'color', value: 'black' })) - * ``` - * - * @param child New node. - * @return This node for methods chain. - */ - push(child: Child): this - - /** - * Removes all children from the container - * and cleans their parent properties. - * - * ```js - * rule.removeAll() - * rule.nodes.length //=> 0 - * ``` - * - * @return This node for methods chain. - */ - removeAll(): this - - /** - * Removes node from the container and cleans the parent properties - * from the node and its children. - * - * ```js - * rule.nodes.length //=> 5 - * rule.removeChild(decl) - * rule.nodes.length //=> 4 - * decl.parent //=> undefined - * ``` - * - * @param child Child or child’s index. - * @return This node for methods chain. - */ - removeChild(child: Child | number): this - - replaceValues( - pattern: RegExp | string, - replaced: { (substring: string, ...args: any[]): string } | string - ): this - /** - * Passes all declaration values within the container that match pattern - * through callback, replacing those values with the returned result - * of callback. - * - * This method is useful if you are using a custom unit or function - * and need to iterate through all values. - * - * ```js - * root.replaceValues(/\d+rem/, { fast: 'rem' }, string => { - * return 15 * parseInt(string) + 'px' - * }) - * ``` - * - * @param pattern Replace pattern. - * @param {object} options Options to speed up the search. - * @param replaced String to replace pattern or callback - * that returns a new value. The callback - * will receive the same arguments - * as those passed to a function parameter - * of `String#replace`. - * @return This node for methods chain. - */ - replaceValues( - pattern: RegExp | string, - options: Container.ValueOptions, - replaced: { (substring: string, ...args: any[]): string } | string - ): this - - /** - * Returns `true` if callback returns `true` for (at least) one - * of the container’s children. - * - * ```js - * const hasPrefix = rule.some(i => i.prop[0] === '-') - * ``` - * - * @param condition Iterator returns true or false. - * @return Is some child pass condition. - */ - some( - condition: (node: Child, index: number, nodes: Child[]) => boolean - ): boolean - - /** - * Traverses the container’s descendant nodes, calling callback - * for each node. - * - * Like container.each(), this method is safe to use - * if you are mutating arrays during iteration. - * - * If you only need to iterate through the container’s immediate children, - * use `Container#each`. - * - * ```js - * root.walk(node => { - * // Traverses all descendant nodes. - * }) - * ``` - * - * @param callback Iterator receives each node and index. - * @return Returns `false` if iteration was broke. - */ - walk( - callback: (node: ChildNode, index: number) => false | void - ): false | undefined - - /** - * Traverses the container’s descendant nodes, calling callback - * for each at-rule node. - * - * If you pass a filter, iteration will only happen over at-rules - * that have matching names. - * - * Like `Container#each`, this method is safe - * to use if you are mutating arrays during iteration. - * - * ```js - * root.walkAtRules(rule => { - * if (isOld(rule.name)) rule.remove() - * }) - * - * let first = false - * root.walkAtRules('charset', rule => { - * if (!first) { - * first = true - * } else { - * rule.remove() - * } - * }) - * ``` - * - * @param name String or regular expression to filter at-rules by name. - * @param callback Iterator receives each node and index. - * @return Returns `false` if iteration was broke. - */ - walkAtRules( - nameFilter: RegExp | string, - callback: (atRule: AtRule, index: number) => false | void - ): false | undefined - walkAtRules( - callback: (atRule: AtRule, index: number) => false | void - ): false | undefined - - walkComments( - callback: (comment: Comment, indexed: number) => false | void - ): false | undefined - walkComments( - callback: (comment: Comment, indexed: number) => false | void - ): false | undefined - - /** - * Traverses the container’s descendant nodes, calling callback - * for each declaration node. - * - * If you pass a filter, iteration will only happen over declarations - * with matching properties. - * - * ```js - * root.walkDecls(decl => { - * checkPropertySupport(decl.prop) - * }) - * - * root.walkDecls('border-radius', decl => { - * decl.remove() - * }) - * - * root.walkDecls(/^background/, decl => { - * decl.value = takeFirstColorFromGradient(decl.value) - * }) - * ``` - * - * Like `Container#each`, this method is safe - * to use if you are mutating arrays during iteration. - * - * @param prop String or regular expression to filter declarations - * by property name. - * @param callback Iterator receives each node and index. - * @return Returns `false` if iteration was broke. - */ - walkDecls( - propFilter: RegExp | string, - callback: (decl: Declaration, index: number) => false | void - ): false | undefined - walkDecls( - callback: (decl: Declaration, index: number) => false | void - ): false | undefined - /** - * Traverses the container’s descendant nodes, calling callback - * for each rule node. - * - * If you pass a filter, iteration will only happen over rules - * with matching selectors. - * - * Like `Container#each`, this method is safe - * to use if you are mutating arrays during iteration. - * - * ```js - * const selectors = [] - * root.walkRules(rule => { - * selectors.push(rule.selector) - * }) - * console.log(`Your CSS uses ${ selectors.length } selectors`) - * ``` - * - * @param selector String or regular expression to filter rules by selector. - * @param callback Iterator receives each node and index. - * @return Returns `false` if iteration was broke. - */ - walkRules( - selectorFilter: RegExp | string, - callback: (rule: Rule, index: number) => false | void - ): false | undefined - walkRules( - callback: (rule: Rule, index: number) => false | void - ): false | undefined - /** - * An internal method that converts a {@link NewChild} into a list of actual - * child nodes that can then be added to this container. - * - * This ensures that the nodes' parent is set to this container, that they use - * the correct prototype chain, and that they're marked as dirty. - * - * @param mnodes The new node or nodes to add. - * @param sample A node from whose raws the new node's `before` raw should be - * taken. - * @param type This should be set to `'prepend'` if the new nodes will be - * inserted at the beginning of the container. - * @hidden - */ - protected normalize( - nodes: Container.NewChild, - sample: Node | undefined, - type?: 'prepend' | false - ): Child[] -} - -declare class Container< - Child extends Node = ChildNode -> extends Container_ {} - -export = Container diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/container.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/container.js deleted file mode 100644 index edb07cc..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/container.js +++ /dev/null @@ -1,447 +0,0 @@ -'use strict' - -let Comment = require('./comment') -let Declaration = require('./declaration') -let Node = require('./node') -let { isClean, my } = require('./symbols') - -let AtRule, parse, Root, Rule - -function cleanSource(nodes) { - return nodes.map(i => { - if (i.nodes) i.nodes = cleanSource(i.nodes) - delete i.source - return i - }) -} - -function markTreeDirty(node) { - node[isClean] = false - if (node.proxyOf.nodes) { - for (let i of node.proxyOf.nodes) { - markTreeDirty(i) - } - } -} - -class Container extends Node { - get first() { - if (!this.proxyOf.nodes) return undefined - return this.proxyOf.nodes[0] - } - - get last() { - if (!this.proxyOf.nodes) return undefined - return this.proxyOf.nodes[this.proxyOf.nodes.length - 1] - } - - append(...children) { - for (let child of children) { - let nodes = this.normalize(child, this.last) - for (let node of nodes) this.proxyOf.nodes.push(node) - } - - this.markDirty() - - return this - } - - cleanRaws(keepBetween) { - super.cleanRaws(keepBetween) - if (this.nodes) { - for (let node of this.nodes) node.cleanRaws(keepBetween) - } - } - - each(callback) { - if (!this.proxyOf.nodes) return undefined - let iterator = this.getIterator() - - let index, result - while (this.indexes[iterator] < this.proxyOf.nodes.length) { - index = this.indexes[iterator] - result = callback(this.proxyOf.nodes[index], index) - if (result === false) break - - this.indexes[iterator] += 1 - } - - delete this.indexes[iterator] - return result - } - - every(condition) { - return this.nodes.every(condition) - } - - getIterator() { - if (!this.lastEach) this.lastEach = 0 - if (!this.indexes) this.indexes = {} - - this.lastEach += 1 - let iterator = this.lastEach - this.indexes[iterator] = 0 - - return iterator - } - - getProxyProcessor() { - return { - get(node, prop) { - if (prop === 'proxyOf') { - return node - } else if (!node[prop]) { - return node[prop] - } else if ( - prop === 'each' || - (typeof prop === 'string' && prop.startsWith('walk')) - ) { - return (...args) => { - return node[prop]( - ...args.map(i => { - if (typeof i === 'function') { - return (child, index) => i(child.toProxy(), index) - } else { - return i - } - }) - ) - } - } else if (prop === 'every' || prop === 'some') { - return cb => { - return node[prop]((child, ...other) => - cb(child.toProxy(), ...other) - ) - } - } else if (prop === 'root') { - return () => node.root().toProxy() - } else if (prop === 'nodes') { - return node.nodes.map(i => i.toProxy()) - } else if (prop === 'first' || prop === 'last') { - return node[prop].toProxy() - } else { - return node[prop] - } - }, - - set(node, prop, value) { - if (node[prop] === value) return true - node[prop] = value - if (prop === 'name' || prop === 'params' || prop === 'selector') { - node.markDirty() - } - return true - } - } - } - - index(child) { - if (typeof child === 'number') return child - if (child.proxyOf) child = child.proxyOf - return this.proxyOf.nodes.indexOf(child) - } - - insertAfter(exist, add) { - let existIndex = this.index(exist) - let nodes = this.normalize(add, this.proxyOf.nodes[existIndex]).reverse() - existIndex = this.index(exist) - for (let node of nodes) this.proxyOf.nodes.splice(existIndex + 1, 0, node) - - let index - for (let id in this.indexes) { - index = this.indexes[id] - if (existIndex < index) { - this.indexes[id] = index + nodes.length - } - } - - this.markDirty() - - return this - } - - insertBefore(exist, add) { - let existIndex = this.index(exist) - let type = existIndex === 0 ? 'prepend' : false - let nodes = this.normalize( - add, - this.proxyOf.nodes[existIndex], - type - ).reverse() - existIndex = this.index(exist) - for (let node of nodes) this.proxyOf.nodes.splice(existIndex, 0, node) - - let index - for (let id in this.indexes) { - index = this.indexes[id] - if (existIndex <= index) { - this.indexes[id] = index + nodes.length - } - } - - this.markDirty() - - return this - } - - normalize(nodes, sample) { - if (typeof nodes === 'string') { - nodes = cleanSource(parse(nodes).nodes) - } else if (typeof nodes === 'undefined') { - nodes = [] - } else if (Array.isArray(nodes)) { - nodes = nodes.slice(0) - for (let i of nodes) { - if (i.parent) i.parent.removeChild(i, 'ignore') - } - } else if (nodes.type === 'root' && this.type !== 'document') { - nodes = nodes.nodes.slice(0) - for (let i of nodes) { - if (i.parent) i.parent.removeChild(i, 'ignore') - } - } else if (nodes.type) { - nodes = [nodes] - } else if (nodes.prop) { - if (typeof nodes.value === 'undefined') { - throw new Error('Value field is missed in node creation') - } else if (typeof nodes.value !== 'string') { - nodes.value = String(nodes.value) - } - nodes = [new Declaration(nodes)] - } else if (nodes.selector || nodes.selectors) { - nodes = [new Rule(nodes)] - } else if (nodes.name) { - nodes = [new AtRule(nodes)] - } else if (nodes.text) { - nodes = [new Comment(nodes)] - } else { - throw new Error('Unknown node type in node creation') - } - - let processed = nodes.map(i => { - /* c8 ignore next */ - if (!i[my]) Container.rebuild(i) - i = i.proxyOf - if (i.parent) i.parent.removeChild(i) - if (i[isClean]) markTreeDirty(i) - - if (!i.raws) i.raws = {} - if (typeof i.raws.before === 'undefined') { - if (sample && typeof sample.raws.before !== 'undefined') { - i.raws.before = sample.raws.before.replace(/\S/g, '') - } - } - i.parent = this.proxyOf - return i - }) - - return processed - } - - prepend(...children) { - children = children.reverse() - for (let child of children) { - let nodes = this.normalize(child, this.first, 'prepend').reverse() - for (let node of nodes) this.proxyOf.nodes.unshift(node) - for (let id in this.indexes) { - this.indexes[id] = this.indexes[id] + nodes.length - } - } - - this.markDirty() - - return this - } - - push(child) { - child.parent = this - this.proxyOf.nodes.push(child) - return this - } - - removeAll() { - for (let node of this.proxyOf.nodes) node.parent = undefined - this.proxyOf.nodes = [] - - this.markDirty() - - return this - } - - removeChild(child) { - child = this.index(child) - this.proxyOf.nodes[child].parent = undefined - this.proxyOf.nodes.splice(child, 1) - - let index - for (let id in this.indexes) { - index = this.indexes[id] - if (index >= child) { - this.indexes[id] = index - 1 - } - } - - this.markDirty() - - return this - } - - replaceValues(pattern, opts, callback) { - if (!callback) { - callback = opts - opts = {} - } - - this.walkDecls(decl => { - if (opts.props && !opts.props.includes(decl.prop)) return - if (opts.fast && !decl.value.includes(opts.fast)) return - - decl.value = decl.value.replace(pattern, callback) - }) - - this.markDirty() - - return this - } - - some(condition) { - return this.nodes.some(condition) - } - - walk(callback) { - return this.each((child, i) => { - let result - try { - result = callback(child, i) - } catch (e) { - throw child.addToError(e) - } - if (result !== false && child.walk) { - result = child.walk(callback) - } - - return result - }) - } - - walkAtRules(name, callback) { - if (!callback) { - callback = name - return this.walk((child, i) => { - if (child.type === 'atrule') { - return callback(child, i) - } - }) - } - if (name instanceof RegExp) { - return this.walk((child, i) => { - if (child.type === 'atrule' && name.test(child.name)) { - return callback(child, i) - } - }) - } - return this.walk((child, i) => { - if (child.type === 'atrule' && child.name === name) { - return callback(child, i) - } - }) - } - - walkComments(callback) { - return this.walk((child, i) => { - if (child.type === 'comment') { - return callback(child, i) - } - }) - } - - walkDecls(prop, callback) { - if (!callback) { - callback = prop - return this.walk((child, i) => { - if (child.type === 'decl') { - return callback(child, i) - } - }) - } - if (prop instanceof RegExp) { - return this.walk((child, i) => { - if (child.type === 'decl' && prop.test(child.prop)) { - return callback(child, i) - } - }) - } - return this.walk((child, i) => { - if (child.type === 'decl' && child.prop === prop) { - return callback(child, i) - } - }) - } - - walkRules(selector, callback) { - if (!callback) { - callback = selector - - return this.walk((child, i) => { - if (child.type === 'rule') { - return callback(child, i) - } - }) - } - if (selector instanceof RegExp) { - return this.walk((child, i) => { - if (child.type === 'rule' && selector.test(child.selector)) { - return callback(child, i) - } - }) - } - return this.walk((child, i) => { - if (child.type === 'rule' && child.selector === selector) { - return callback(child, i) - } - }) - } -} - -Container.registerParse = dependant => { - parse = dependant -} - -Container.registerRule = dependant => { - Rule = dependant -} - -Container.registerAtRule = dependant => { - AtRule = dependant -} - -Container.registerRoot = dependant => { - Root = dependant -} - -module.exports = Container -Container.default = Container - -/* c8 ignore start */ -Container.rebuild = node => { - if (node.type === 'atrule') { - Object.setPrototypeOf(node, AtRule.prototype) - } else if (node.type === 'rule') { - Object.setPrototypeOf(node, Rule.prototype) - } else if (node.type === 'decl') { - Object.setPrototypeOf(node, Declaration.prototype) - } else if (node.type === 'comment') { - Object.setPrototypeOf(node, Comment.prototype) - } else if (node.type === 'root') { - Object.setPrototypeOf(node, Root.prototype) - } - - node[my] = true - - if (node.nodes) { - node.nodes.forEach(child => { - Container.rebuild(child) - }) - } -} -/* c8 ignore stop */ diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/css-syntax-error.d.ts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/css-syntax-error.d.ts deleted file mode 100644 index e540d84..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/css-syntax-error.d.ts +++ /dev/null @@ -1,248 +0,0 @@ -import { FilePosition } from './input.js' - -declare namespace CssSyntaxError { - /** - * A position that is part of a range. - */ - export interface RangePosition { - /** - * The column number in the input. - */ - column: number - - /** - * The line number in the input. - */ - line: number - } - - // eslint-disable-next-line @typescript-eslint/no-use-before-define - export { CssSyntaxError_ as default } -} - -/** - * The CSS parser throws this error for broken CSS. - * - * Custom parsers can throw this error for broken custom syntax using - * the `Node#error` method. - * - * PostCSS will use the input source map to detect the original error location. - * If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS, - * PostCSS will show the original position in the Sass file. - * - * If you need the position in the PostCSS input - * (e.g., to debug the previous compiler), use `error.input.file`. - * - * ```js - * // Raising error from plugin - * throw node.error('Unknown variable', { plugin: 'postcss-vars' }) - * ``` - * - * ```js - * // Catching and checking syntax error - * try { - * postcss.parse('a{') - * } catch (error) { - * if (error.name === 'CssSyntaxError') { - * error //=> CssSyntaxError - * } - * } - * ``` - */ -declare class CssSyntaxError_ extends Error { - /** - * Source column of the error. - * - * ```js - * error.column //=> 1 - * error.input.column //=> 4 - * ``` - * - * PostCSS will use the input source map to detect the original location. - * If you need the position in the PostCSS input, use `error.input.column`. - */ - column?: number - - /** - * Source column of the error's end, exclusive. Provided if the error pertains - * to a range. - * - * ```js - * error.endColumn //=> 1 - * error.input.endColumn //=> 4 - * ``` - * - * PostCSS will use the input source map to detect the original location. - * If you need the position in the PostCSS input, use `error.input.endColumn`. - */ - endColumn?: number - - /** - * Source line of the error's end, exclusive. Provided if the error pertains - * to a range. - * - * ```js - * error.endLine //=> 3 - * error.input.endLine //=> 4 - * ``` - * - * PostCSS will use the input source map to detect the original location. - * If you need the position in the PostCSS input, use `error.input.endLine`. - */ - endLine?: number - - /** - * Absolute path to the broken file. - * - * ```js - * error.file //=> 'a.sass' - * error.input.file //=> 'a.css' - * ``` - * - * PostCSS will use the input source map to detect the original location. - * If you need the position in the PostCSS input, use `error.input.file`. - */ - file?: string - - /** - * Input object with PostCSS internal information - * about input file. If input has source map - * from previous tool, PostCSS will use origin - * (for example, Sass) source. You can use this - * object to get PostCSS input source. - * - * ```js - * error.input.file //=> 'a.css' - * error.file //=> 'a.sass' - * ``` - */ - input?: FilePosition - - /** - * Source line of the error. - * - * ```js - * error.line //=> 2 - * error.input.line //=> 4 - * ``` - * - * PostCSS will use the input source map to detect the original location. - * If you need the position in the PostCSS input, use `error.input.line`. - */ - line?: number - - /** - * Full error text in the GNU error format - * with plugin, file, line and column. - * - * ```js - * error.message //=> 'a.css:1:1: Unclosed block' - * ``` - */ - message: string - - /** - * Always equal to `'CssSyntaxError'`. You should always check error type - * by `error.name === 'CssSyntaxError'` - * instead of `error instanceof CssSyntaxError`, - * because npm could have several PostCSS versions. - * - * ```js - * if (error.name === 'CssSyntaxError') { - * error //=> CssSyntaxError - * } - * ``` - */ - name: 'CssSyntaxError' - - /** - * Plugin name, if error came from plugin. - * - * ```js - * error.plugin //=> 'postcss-vars' - * ``` - */ - plugin?: string - - /** - * Error message. - * - * ```js - * error.message //=> 'Unclosed block' - * ``` - */ - reason: string - - /** - * Source code of the broken file. - * - * ```js - * error.source //=> 'a { b {} }' - * error.input.source //=> 'a b { }' - * ``` - */ - source?: string - - stack: string - - /** - * Instantiates a CSS syntax error. Can be instantiated for a single position - * or for a range. - * @param message Error message. - * @param lineOrStartPos If for a single position, the line number, or if for - * a range, the inclusive start position of the error. - * @param columnOrEndPos If for a single position, the column number, or if for - * a range, the exclusive end position of the error. - * @param source Source code of the broken file. - * @param file Absolute path to the broken file. - * @param plugin PostCSS plugin name, if error came from plugin. - */ - constructor( - message: string, - lineOrStartPos?: CssSyntaxError.RangePosition | number, - columnOrEndPos?: CssSyntaxError.RangePosition | number, - source?: string, - file?: string, - plugin?: string - ) - - /** - * Returns a few lines of CSS source that caused the error. - * - * If the CSS has an input source map without `sourceContent`, - * this method will return an empty string. - * - * ```js - * error.showSourceCode() //=> " 4 | } - * // 5 | a { - * // > 6 | bad - * // | ^ - * // 7 | } - * // 8 | b {" - * ``` - * - * @param color Whether arrow will be colored red by terminal - * color codes. By default, PostCSS will detect - * color support by `process.stdout.isTTY` - * and `process.env.NODE_DISABLE_COLORS`. - * @return Few lines of CSS source that caused the error. - */ - showSourceCode(color?: boolean): string - - /** - * Returns error position, message and source code of the broken part. - * - * ```js - * error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block - * // > 1 | a { - * // | ^" - * ``` - * - * @return Error position, message and source code. - */ - toString(): string -} - -declare class CssSyntaxError extends CssSyntaxError_ {} - -export = CssSyntaxError diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/css-syntax-error.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/css-syntax-error.js deleted file mode 100644 index 275a4f6..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/css-syntax-error.js +++ /dev/null @@ -1,133 +0,0 @@ -'use strict' - -let pico = require('picocolors') - -let terminalHighlight = require('./terminal-highlight') - -class CssSyntaxError extends Error { - constructor(message, line, column, source, file, plugin) { - super(message) - this.name = 'CssSyntaxError' - this.reason = message - - if (file) { - this.file = file - } - if (source) { - this.source = source - } - if (plugin) { - this.plugin = plugin - } - if (typeof line !== 'undefined' && typeof column !== 'undefined') { - if (typeof line === 'number') { - this.line = line - this.column = column - } else { - this.line = line.line - this.column = line.column - this.endLine = column.line - this.endColumn = column.column - } - } - - this.setMessage() - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, CssSyntaxError) - } - } - - setMessage() { - this.message = this.plugin ? this.plugin + ': ' : '' - this.message += this.file ? this.file : '' - if (typeof this.line !== 'undefined') { - this.message += ':' + this.line + ':' + this.column - } - this.message += ': ' + this.reason - } - - showSourceCode(color) { - if (!this.source) return '' - - let css = this.source - if (color == null) color = pico.isColorSupported - - let aside = text => text - let mark = text => text - let highlight = text => text - if (color) { - let { bold, gray, red } = pico.createColors(true) - mark = text => bold(red(text)) - aside = text => gray(text) - if (terminalHighlight) { - highlight = text => terminalHighlight(text) - } - } - - let lines = css.split(/\r?\n/) - let start = Math.max(this.line - 3, 0) - let end = Math.min(this.line + 2, lines.length) - let maxWidth = String(end).length - - return lines - .slice(start, end) - .map((line, index) => { - let number = start + 1 + index - let gutter = ' ' + (' ' + number).slice(-maxWidth) + ' | ' - if (number === this.line) { - if (line.length > 160) { - let padding = 20 - let subLineStart = Math.max(0, this.column - padding) - let subLineEnd = Math.max( - this.column + padding, - this.endColumn + padding - ) - let subLine = line.slice(subLineStart, subLineEnd) - - let spacing = - aside(gutter.replace(/\d/g, ' ')) + - line - .slice(0, Math.min(this.column - 1, padding - 1)) - .replace(/[^\t]/g, ' ') - - return ( - mark('>') + - aside(gutter) + - highlight(subLine) + - '\n ' + - spacing + - mark('^') - ) - } - - let spacing = - aside(gutter.replace(/\d/g, ' ')) + - line.slice(0, this.column - 1).replace(/[^\t]/g, ' ') - - return ( - mark('>') + - aside(gutter) + - highlight(line) + - '\n ' + - spacing + - mark('^') - ) - } - - return ' ' + aside(gutter) + highlight(line) - }) - .join('\n') - } - - toString() { - let code = this.showSourceCode() - if (code) { - code = '\n\n' + code + '\n' - } - return this.name + ': ' + this.message + code - } -} - -module.exports = CssSyntaxError -CssSyntaxError.default = CssSyntaxError diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/declaration.d.ts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/declaration.d.ts deleted file mode 100644 index d489b42..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/declaration.d.ts +++ /dev/null @@ -1,151 +0,0 @@ -import { ContainerWithChildren } from './container.js' -import Node from './node.js' - -declare namespace Declaration { - export interface DeclarationRaws extends Record { - /** - * The space symbols before the node. It also stores `*` - * and `_` symbols before the declaration (IE hack). - */ - before?: string - - /** - * The symbols between the property and value for declarations. - */ - between?: string - - /** - * The content of the important statement, if it is not just `!important`. - */ - important?: string - - /** - * Declaration value with comments. - */ - value?: { - raw: string - value: string - } - } - - export interface DeclarationProps { - /** Whether the declaration has an `!important` annotation. */ - important?: boolean - /** Name of the declaration. */ - prop: string - /** Information used to generate byte-to-byte equal node string as it was in the origin input. */ - raws?: DeclarationRaws - /** Value of the declaration. */ - value: string - } - - // eslint-disable-next-line @typescript-eslint/no-use-before-define - export { Declaration_ as default } -} - -/** - * It represents a class that handles - * [CSS declarations](https://developer.mozilla.org/en-US/docs/Web/CSS/Syntax#css_declarations) - * - * ```js - * Once (root, { Declaration }) { - * const color = new Declaration({ prop: 'color', value: 'black' }) - * root.append(color) - * } - * ``` - * - * ```js - * const root = postcss.parse('a { color: black }') - * const decl = root.first?.first - * - * decl.type //=> 'decl' - * decl.toString() //=> ' color: black' - * ``` - */ -declare class Declaration_ extends Node { - parent: ContainerWithChildren | undefined - raws: Declaration.DeclarationRaws - - type: 'decl' - - /** - * It represents a specificity of the declaration. - * - * If true, the CSS declaration will have an - * [important](https://developer.mozilla.org/en-US/docs/Web/CSS/important) - * specifier. - * - * ```js - * const root = postcss.parse('a { color: black !important; color: red }') - * - * root.first.first.important //=> true - * root.first.last.important //=> undefined - * ``` - */ - get important(): boolean - set important(value: boolean) - - /** - * The property name for a CSS declaration. - * - * ```js - * const root = postcss.parse('a { color: black }') - * const decl = root.first.first - * - * decl.prop //=> 'color' - * ``` - */ - get prop(): string - - set prop(value: string) - - /** - * The property value for a CSS declaration. - * - * Any CSS comments inside the value string will be filtered out. - * CSS comments present in the source value will be available in - * the `raws` property. - * - * Assigning new `value` would ignore the comments in `raws` - * property while compiling node to string. - * - * ```js - * const root = postcss.parse('a { color: black }') - * const decl = root.first.first - * - * decl.value //=> 'black' - * ``` - */ - get value(): string - set value(value: string) - - /** - * It represents a getter that returns `true` if a declaration starts with - * `--` or `$`, which are used to declare variables in CSS and SASS/SCSS. - * - * ```js - * const root = postcss.parse(':root { --one: 1 }') - * const one = root.first.first - * - * one.variable //=> true - * ``` - * - * ```js - * const root = postcss.parse('$one: 1') - * const one = root.first - * - * one.variable //=> true - * ``` - */ - get variable(): boolean - constructor(defaults?: Declaration.DeclarationProps) - - assign(overrides: Declaration.DeclarationProps | object): this - clone(overrides?: Partial): this - cloneAfter(overrides?: Partial): this - cloneBefore(overrides?: Partial): this -} - -declare class Declaration extends Declaration_ {} - -export = Declaration diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/declaration.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/declaration.js deleted file mode 100644 index 65a03aa..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/declaration.js +++ /dev/null @@ -1,24 +0,0 @@ -'use strict' - -let Node = require('./node') - -class Declaration extends Node { - get variable() { - return this.prop.startsWith('--') || this.prop[0] === '$' - } - - constructor(defaults) { - if ( - defaults && - typeof defaults.value !== 'undefined' && - typeof defaults.value !== 'string' - ) { - defaults = { ...defaults, value: String(defaults.value) } - } - super(defaults) - this.type = 'decl' - } -} - -module.exports = Declaration -Declaration.default = Declaration diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/document.d.ts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/document.d.ts deleted file mode 100644 index f9e8063..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/document.d.ts +++ /dev/null @@ -1,69 +0,0 @@ -import Container, { ContainerProps } from './container.js' -import { ProcessOptions } from './postcss.js' -import Result from './result.js' -import Root from './root.js' - -declare namespace Document { - export interface DocumentProps extends ContainerProps { - nodes?: readonly Root[] - - /** - * Information to generate byte-to-byte equal node string as it was - * in the origin input. - * - * Every parser saves its own properties. - */ - raws?: Record - } - - // eslint-disable-next-line @typescript-eslint/no-use-before-define - export { Document_ as default } -} - -/** - * Represents a file and contains all its parsed nodes. - * - * **Experimental:** some aspects of this node could change within minor - * or patch version releases. - * - * ```js - * const document = htmlParser( - * '' - * ) - * document.type //=> 'document' - * document.nodes.length //=> 2 - * ``` - */ -declare class Document_ extends Container { - nodes: Root[] - parent: undefined - type: 'document' - - constructor(defaults?: Document.DocumentProps) - - assign(overrides: Document.DocumentProps | object): this - clone(overrides?: Partial): this - cloneAfter(overrides?: Partial): this - cloneBefore(overrides?: Partial): this - - /** - * Returns a `Result` instance representing the document’s CSS roots. - * - * ```js - * const root1 = postcss.parse(css1, { from: 'a.css' }) - * const root2 = postcss.parse(css2, { from: 'b.css' }) - * const document = postcss.document() - * document.append(root1) - * document.append(root2) - * const result = document.toResult({ to: 'all.css', map: true }) - * ``` - * - * @param opts Options. - * @return Result with current document’s CSS. - */ - toResult(options?: ProcessOptions): Result -} - -declare class Document extends Document_ {} - -export = Document diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/document.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/document.js deleted file mode 100644 index 4468991..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/document.js +++ /dev/null @@ -1,33 +0,0 @@ -'use strict' - -let Container = require('./container') - -let LazyResult, Processor - -class Document extends Container { - constructor(defaults) { - // type needs to be passed to super, otherwise child roots won't be normalized correctly - super({ type: 'document', ...defaults }) - - if (!this.nodes) { - this.nodes = [] - } - } - - toResult(opts = {}) { - let lazy = new LazyResult(new Processor(), this, opts) - - return lazy.stringify() - } -} - -Document.registerLazyResult = dependant => { - LazyResult = dependant -} - -Document.registerProcessor = dependant => { - Processor = dependant -} - -module.exports = Document -Document.default = Document diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/fromJSON.d.ts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/fromJSON.d.ts deleted file mode 100644 index e1deedb..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/fromJSON.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { JSONHydrator } from './postcss.js' - -interface FromJSON extends JSONHydrator { - default: FromJSON -} - -declare const fromJSON: FromJSON - -export = fromJSON diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/fromJSON.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/fromJSON.js deleted file mode 100644 index c9ac1a8..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/fromJSON.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict' - -let AtRule = require('./at-rule') -let Comment = require('./comment') -let Declaration = require('./declaration') -let Input = require('./input') -let PreviousMap = require('./previous-map') -let Root = require('./root') -let Rule = require('./rule') - -function fromJSON(json, inputs) { - if (Array.isArray(json)) return json.map(n => fromJSON(n)) - - let { inputs: ownInputs, ...defaults } = json - if (ownInputs) { - inputs = [] - for (let input of ownInputs) { - let inputHydrated = { ...input, __proto__: Input.prototype } - if (inputHydrated.map) { - inputHydrated.map = { - ...inputHydrated.map, - __proto__: PreviousMap.prototype - } - } - inputs.push(inputHydrated) - } - } - if (defaults.nodes) { - defaults.nodes = json.nodes.map(n => fromJSON(n, inputs)) - } - if (defaults.source) { - let { inputId, ...source } = defaults.source - defaults.source = source - if (inputId != null) { - defaults.source.input = inputs[inputId] - } - } - if (defaults.type === 'root') { - return new Root(defaults) - } else if (defaults.type === 'decl') { - return new Declaration(defaults) - } else if (defaults.type === 'rule') { - return new Rule(defaults) - } else if (defaults.type === 'comment') { - return new Comment(defaults) - } else if (defaults.type === 'atrule') { - return new AtRule(defaults) - } else { - throw new Error('Unknown node type: ' + json.type) - } -} - -module.exports = fromJSON -fromJSON.default = fromJSON diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/input.d.ts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/input.d.ts deleted file mode 100644 index 260040f..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/input.d.ts +++ /dev/null @@ -1,206 +0,0 @@ -import { CssSyntaxError, ProcessOptions } from './postcss.js' -import PreviousMap from './previous-map.js' - -declare namespace Input { - export interface FilePosition { - /** - * Column of inclusive start position in source file. - */ - column: number - - /** - * Column of exclusive end position in source file. - */ - endColumn?: number - - /** - * Line of exclusive end position in source file. - */ - endLine?: number - - /** - * Absolute path to the source file. - */ - file?: string - - /** - * Line of inclusive start position in source file. - */ - line: number - - /** - * Source code. - */ - source?: string - - /** - * URL for the source file. - */ - url: string - } - - // eslint-disable-next-line @typescript-eslint/no-use-before-define - export { Input_ as default } -} - -/** - * Represents the source CSS. - * - * ```js - * const root = postcss.parse(css, { from: file }) - * const input = root.source.input - * ``` - */ -declare class Input_ { - /** - * Input CSS source. - * - * ```js - * const input = postcss.parse('a{}', { from: file }).input - * input.css //=> "a{}" - * ``` - */ - css: string - - /** - * Input source with support for non-CSS documents. - * - * ```js - * const input = postcss.parse('a{}', { from: file, document: '' }).input - * input.document //=> "" - * input.css //=> "a{}" - * ``` - */ - document: string - - /** - * The absolute path to the CSS source file defined - * with the `from` option. - * - * ```js - * const root = postcss.parse(css, { from: 'a.css' }) - * root.source.input.file //=> '/home/ai/a.css' - * ``` - */ - file?: string - - /** - * The flag to indicate whether or not the source code has Unicode BOM. - */ - hasBOM: boolean - - /** - * The unique ID of the CSS source. It will be created if `from` option - * is not provided (because PostCSS does not know the file path). - * - * ```js - * const root = postcss.parse(css) - * root.source.input.file //=> undefined - * root.source.input.id //=> "" - * ``` - */ - id?: string - - /** - * The input source map passed from a compilation step before PostCSS - * (for example, from Sass compiler). - * - * ```js - * root.source.input.map.consumer().sources //=> ['a.sass'] - * ``` - */ - map: PreviousMap - - /** - * The CSS source identifier. Contains `Input#file` if the user - * set the `from` option, or `Input#id` if they did not. - * - * ```js - * const root = postcss.parse(css, { from: 'a.css' }) - * root.source.input.from //=> "/home/ai/a.css" - * - * const root = postcss.parse(css) - * root.source.input.from //=> "" - * ``` - */ - get from(): string - - /** - * @param css Input CSS source. - * @param opts Process options. - */ - constructor(css: string, opts?: ProcessOptions) - - error( - message: string, - start: - | { - column: number - line: number - } - | { - offset: number - }, - end: - | { - column: number - line: number - } - | { - offset: number - }, - opts?: { plugin?: CssSyntaxError['plugin'] } - ): CssSyntaxError - /** - * Returns `CssSyntaxError` with information about the error and its position. - */ - error( - message: string, - line: number, - column: number, - opts?: { plugin?: CssSyntaxError['plugin'] } - ): CssSyntaxError - error( - message: string, - offset: number, - opts?: { plugin?: CssSyntaxError['plugin'] } - ): CssSyntaxError - /** - * Converts source offset to line and column. - * - * @param offset Source offset. - */ - fromOffset(offset: number): { col: number; line: number } | null - /** - * Reads the input source map and returns a symbol position - * in the input source (e.g., in a Sass file that was compiled - * to CSS before being passed to PostCSS). Optionally takes an - * end position, exclusive. - * - * ```js - * root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 } - * root.source.input.origin(1, 1, 1, 4) - * //=> { file: 'a.css', line: 3, column: 1, endLine: 3, endColumn: 4 } - * ``` - * - * @param line Line for inclusive start position in input CSS. - * @param column Column for inclusive start position in input CSS. - * @param endLine Line for exclusive end position in input CSS. - * @param endColumn Column for exclusive end position in input CSS. - * - * @return Position in input source. - */ - origin( - line: number, - column: number, - endLine?: number, - endColumn?: number - ): false | Input.FilePosition - - /** Converts this to a JSON-friendly object representation. */ - toJSON(): object -} - -declare class Input extends Input_ {} - -export = Input diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/input.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/input.js deleted file mode 100644 index 9773e0f..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/input.js +++ /dev/null @@ -1,251 +0,0 @@ -'use strict' - -let { nanoid } = require('nanoid/non-secure') -let { isAbsolute, resolve } = require('path') -let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') -let { fileURLToPath, pathToFileURL } = require('url') - -let CssSyntaxError = require('./css-syntax-error') -let PreviousMap = require('./previous-map') -let terminalHighlight = require('./terminal-highlight') - -let fromOffsetCache = Symbol('fromOffsetCache') - -let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator) -let pathAvailable = Boolean(resolve && isAbsolute) - -class Input { - get from() { - return this.file || this.id - } - - constructor(css, opts = {}) { - if ( - css === null || - typeof css === 'undefined' || - (typeof css === 'object' && !css.toString) - ) { - throw new Error(`PostCSS received ${css} instead of CSS string`) - } - - this.css = css.toString() - - if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') { - this.hasBOM = true - this.css = this.css.slice(1) - } else { - this.hasBOM = false - } - - this.document = this.css - if (opts.document) this.document = opts.document.toString() - - if (opts.from) { - if ( - !pathAvailable || - /^\w+:\/\//.test(opts.from) || - isAbsolute(opts.from) - ) { - this.file = opts.from - } else { - this.file = resolve(opts.from) - } - } - - if (pathAvailable && sourceMapAvailable) { - let map = new PreviousMap(this.css, opts) - if (map.text) { - this.map = map - let file = map.consumer().file - if (!this.file && file) this.file = this.mapResolve(file) - } - } - - if (!this.file) { - this.id = '' - } - if (this.map) this.map.file = this.from - } - - error(message, line, column, opts = {}) { - let endColumn, endLine, result - - if (line && typeof line === 'object') { - let start = line - let end = column - if (typeof start.offset === 'number') { - let pos = this.fromOffset(start.offset) - line = pos.line - column = pos.col - } else { - line = start.line - column = start.column - } - if (typeof end.offset === 'number') { - let pos = this.fromOffset(end.offset) - endLine = pos.line - endColumn = pos.col - } else { - endLine = end.line - endColumn = end.column - } - } else if (!column) { - let pos = this.fromOffset(line) - line = pos.line - column = pos.col - } - - let origin = this.origin(line, column, endLine, endColumn) - if (origin) { - result = new CssSyntaxError( - message, - origin.endLine === undefined - ? origin.line - : { column: origin.column, line: origin.line }, - origin.endLine === undefined - ? origin.column - : { column: origin.endColumn, line: origin.endLine }, - origin.source, - origin.file, - opts.plugin - ) - } else { - result = new CssSyntaxError( - message, - endLine === undefined ? line : { column, line }, - endLine === undefined ? column : { column: endColumn, line: endLine }, - this.css, - this.file, - opts.plugin - ) - } - - result.input = { column, endColumn, endLine, line, source: this.css } - if (this.file) { - if (pathToFileURL) { - result.input.url = pathToFileURL(this.file).toString() - } - result.input.file = this.file - } - - return result - } - - fromOffset(offset) { - let lastLine, lineToIndex - if (!this[fromOffsetCache]) { - let lines = this.css.split('\n') - lineToIndex = new Array(lines.length) - let prevIndex = 0 - - for (let i = 0, l = lines.length; i < l; i++) { - lineToIndex[i] = prevIndex - prevIndex += lines[i].length + 1 - } - - this[fromOffsetCache] = lineToIndex - } else { - lineToIndex = this[fromOffsetCache] - } - lastLine = lineToIndex[lineToIndex.length - 1] - - let min = 0 - if (offset >= lastLine) { - min = lineToIndex.length - 1 - } else { - let max = lineToIndex.length - 2 - let mid - while (min < max) { - mid = min + ((max - min) >> 1) - if (offset < lineToIndex[mid]) { - max = mid - 1 - } else if (offset >= lineToIndex[mid + 1]) { - min = mid + 1 - } else { - min = mid - break - } - } - } - return { - col: offset - lineToIndex[min] + 1, - line: min + 1 - } - } - - mapResolve(file) { - if (/^\w+:\/\//.test(file)) { - return file - } - return resolve(this.map.consumer().sourceRoot || this.map.root || '.', file) - } - - origin(line, column, endLine, endColumn) { - if (!this.map) return false - let consumer = this.map.consumer() - - let from = consumer.originalPositionFor({ column, line }) - if (!from.source) return false - - let to - if (typeof endLine === 'number') { - to = consumer.originalPositionFor({ column: endColumn, line: endLine }) - } - - let fromUrl - - if (isAbsolute(from.source)) { - fromUrl = pathToFileURL(from.source) - } else { - fromUrl = new URL( - from.source, - this.map.consumer().sourceRoot || pathToFileURL(this.map.mapFile) - ) - } - - let result = { - column: from.column, - endColumn: to && to.column, - endLine: to && to.line, - line: from.line, - url: fromUrl.toString() - } - - if (fromUrl.protocol === 'file:') { - if (fileURLToPath) { - result.file = fileURLToPath(fromUrl) - } else { - /* c8 ignore next 2 */ - throw new Error(`file: protocol is not available in this PostCSS build`) - } - } - - let source = consumer.sourceContentFor(from.source) - if (source) result.source = source - - return result - } - - toJSON() { - let json = {} - for (let name of ['hasBOM', 'css', 'file', 'id']) { - if (this[name] != null) { - json[name] = this[name] - } - } - if (this.map) { - json.map = { ...this.map } - if (json.map.consumerCache) { - json.map.consumerCache = undefined - } - } - return json - } -} - -module.exports = Input -Input.default = Input - -if (terminalHighlight && terminalHighlight.registerInput) { - terminalHighlight.registerInput(Input) -} diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/lazy-result.d.ts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/lazy-result.d.ts deleted file mode 100644 index 2eb7279..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/lazy-result.d.ts +++ /dev/null @@ -1,190 +0,0 @@ -import Document from './document.js' -import { SourceMap } from './postcss.js' -import Processor from './processor.js' -import Result, { Message, ResultOptions } from './result.js' -import Root from './root.js' -import Warning from './warning.js' - -declare namespace LazyResult { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - export { LazyResult_ as default } -} - -/** - * A Promise proxy for the result of PostCSS transformations. - * - * A `LazyResult` instance is returned by `Processor#process`. - * - * ```js - * const lazy = postcss([autoprefixer]).process(css) - * ``` - */ -declare class LazyResult_ - implements PromiseLike> -{ - /** - * Processes input CSS through synchronous and asynchronous plugins - * and calls onRejected for each error thrown in any plugin. - * - * It implements standard Promise API. - * - * ```js - * postcss([autoprefixer]).process(css).then(result => { - * console.log(result.css) - * }).catch(error => { - * console.error(error) - * }) - * ``` - */ - catch: Promise>['catch'] - - /** - * Processes input CSS through synchronous and asynchronous plugins - * and calls onFinally on any error or when all plugins will finish work. - * - * It implements standard Promise API. - * - * ```js - * postcss([autoprefixer]).process(css).finally(() => { - * console.log('processing ended') - * }) - * ``` - */ - finally: Promise>['finally'] - - /** - * Processes input CSS through synchronous and asynchronous plugins - * and calls `onFulfilled` with a Result instance. If a plugin throws - * an error, the `onRejected` callback will be executed. - * - * It implements standard Promise API. - * - * ```js - * postcss([autoprefixer]).process(css, { from: cssPath }).then(result => { - * console.log(result.css) - * }) - * ``` - */ - then: Promise>['then'] - - /** - * An alias for the `css` property. Use it with syntaxes - * that generate non-CSS output. - * - * This property will only work with synchronous plugins. - * If the processor contains any asynchronous plugins - * it will throw an error. - * - * PostCSS runners should always use `LazyResult#then`. - */ - get content(): string - - /** - * Processes input CSS through synchronous plugins, converts `Root` - * to a CSS string and returns `Result#css`. - * - * This property will only work with synchronous plugins. - * If the processor contains any asynchronous plugins - * it will throw an error. - * - * PostCSS runners should always use `LazyResult#then`. - */ - get css(): string - - /** - * Processes input CSS through synchronous plugins - * and returns `Result#map`. - * - * This property will only work with synchronous plugins. - * If the processor contains any asynchronous plugins - * it will throw an error. - * - * PostCSS runners should always use `LazyResult#then`. - */ - get map(): SourceMap - - /** - * Processes input CSS through synchronous plugins - * and returns `Result#messages`. - * - * This property will only work with synchronous plugins. If the processor - * contains any asynchronous plugins it will throw an error. - * - * PostCSS runners should always use `LazyResult#then`. - */ - get messages(): Message[] - - /** - * Options from the `Processor#process` call. - */ - get opts(): ResultOptions - - /** - * Returns a `Processor` instance, which will be used - * for CSS transformations. - */ - get processor(): Processor - - /** - * Processes input CSS through synchronous plugins - * and returns `Result#root`. - * - * This property will only work with synchronous plugins. If the processor - * contains any asynchronous plugins it will throw an error. - * - * PostCSS runners should always use `LazyResult#then`. - */ - get root(): RootNode - - /** - * Returns the default string description of an object. - * Required to implement the Promise interface. - */ - get [Symbol.toStringTag](): string - - /** - * @param processor Processor used for this transformation. - * @param css CSS to parse and transform. - * @param opts Options from the `Processor#process` or `Root#toResult`. - */ - constructor(processor: Processor, css: string, opts: ResultOptions) - - /** - * Run plugin in async way and return `Result`. - * - * @return Result with output content. - */ - async(): Promise> - - /** - * Run plugin in sync way and return `Result`. - * - * @return Result with output content. - */ - sync(): Result - - /** - * Alias for the `LazyResult#css` property. - * - * ```js - * lazy + '' === lazy.css - * ``` - * - * @return Output CSS. - */ - toString(): string - - /** - * Processes input CSS through synchronous plugins - * and calls `Result#warnings`. - * - * @return Warnings from plugins. - */ - warnings(): Warning[] -} - -declare class LazyResult< - RootNode = Document | Root -> extends LazyResult_ {} - -export = LazyResult diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/lazy-result.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/lazy-result.js deleted file mode 100644 index 1ea52b8..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/lazy-result.js +++ /dev/null @@ -1,550 +0,0 @@ -'use strict' - -let Container = require('./container') -let Document = require('./document') -let MapGenerator = require('./map-generator') -let parse = require('./parse') -let Result = require('./result') -let Root = require('./root') -let stringify = require('./stringify') -let { isClean, my } = require('./symbols') -let warnOnce = require('./warn-once') - -const TYPE_TO_CLASS_NAME = { - atrule: 'AtRule', - comment: 'Comment', - decl: 'Declaration', - document: 'Document', - root: 'Root', - rule: 'Rule' -} - -const PLUGIN_PROPS = { - AtRule: true, - AtRuleExit: true, - Comment: true, - CommentExit: true, - Declaration: true, - DeclarationExit: true, - Document: true, - DocumentExit: true, - Once: true, - OnceExit: true, - postcssPlugin: true, - prepare: true, - Root: true, - RootExit: true, - Rule: true, - RuleExit: true -} - -const NOT_VISITORS = { - Once: true, - postcssPlugin: true, - prepare: true -} - -const CHILDREN = 0 - -function isPromise(obj) { - return typeof obj === 'object' && typeof obj.then === 'function' -} - -function getEvents(node) { - let key = false - let type = TYPE_TO_CLASS_NAME[node.type] - if (node.type === 'decl') { - key = node.prop.toLowerCase() - } else if (node.type === 'atrule') { - key = node.name.toLowerCase() - } - - if (key && node.append) { - return [ - type, - type + '-' + key, - CHILDREN, - type + 'Exit', - type + 'Exit-' + key - ] - } else if (key) { - return [type, type + '-' + key, type + 'Exit', type + 'Exit-' + key] - } else if (node.append) { - return [type, CHILDREN, type + 'Exit'] - } else { - return [type, type + 'Exit'] - } -} - -function toStack(node) { - let events - if (node.type === 'document') { - events = ['Document', CHILDREN, 'DocumentExit'] - } else if (node.type === 'root') { - events = ['Root', CHILDREN, 'RootExit'] - } else { - events = getEvents(node) - } - - return { - eventIndex: 0, - events, - iterator: 0, - node, - visitorIndex: 0, - visitors: [] - } -} - -function cleanMarks(node) { - node[isClean] = false - if (node.nodes) node.nodes.forEach(i => cleanMarks(i)) - return node -} - -let postcss = {} - -class LazyResult { - get content() { - return this.stringify().content - } - - get css() { - return this.stringify().css - } - - get map() { - return this.stringify().map - } - - get messages() { - return this.sync().messages - } - - get opts() { - return this.result.opts - } - - get processor() { - return this.result.processor - } - - get root() { - return this.sync().root - } - - get [Symbol.toStringTag]() { - return 'LazyResult' - } - - constructor(processor, css, opts) { - this.stringified = false - this.processed = false - - let root - if ( - typeof css === 'object' && - css !== null && - (css.type === 'root' || css.type === 'document') - ) { - root = cleanMarks(css) - } else if (css instanceof LazyResult || css instanceof Result) { - root = cleanMarks(css.root) - if (css.map) { - if (typeof opts.map === 'undefined') opts.map = {} - if (!opts.map.inline) opts.map.inline = false - opts.map.prev = css.map - } - } else { - let parser = parse - if (opts.syntax) parser = opts.syntax.parse - if (opts.parser) parser = opts.parser - if (parser.parse) parser = parser.parse - - try { - root = parser(css, opts) - } catch (error) { - this.processed = true - this.error = error - } - - if (root && !root[my]) { - /* c8 ignore next 2 */ - Container.rebuild(root) - } - } - - this.result = new Result(processor, root, opts) - this.helpers = { ...postcss, postcss, result: this.result } - this.plugins = this.processor.plugins.map(plugin => { - if (typeof plugin === 'object' && plugin.prepare) { - return { ...plugin, ...plugin.prepare(this.result) } - } else { - return plugin - } - }) - } - - async() { - if (this.error) return Promise.reject(this.error) - if (this.processed) return Promise.resolve(this.result) - if (!this.processing) { - this.processing = this.runAsync() - } - return this.processing - } - - catch(onRejected) { - return this.async().catch(onRejected) - } - - finally(onFinally) { - return this.async().then(onFinally, onFinally) - } - - getAsyncError() { - throw new Error('Use process(css).then(cb) to work with async plugins') - } - - handleError(error, node) { - let plugin = this.result.lastPlugin - try { - if (node) node.addToError(error) - this.error = error - if (error.name === 'CssSyntaxError' && !error.plugin) { - error.plugin = plugin.postcssPlugin - error.setMessage() - } else if (plugin.postcssVersion) { - if (process.env.NODE_ENV !== 'production') { - let pluginName = plugin.postcssPlugin - let pluginVer = plugin.postcssVersion - let runtimeVer = this.result.processor.version - let a = pluginVer.split('.') - let b = runtimeVer.split('.') - - if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) { - // eslint-disable-next-line no-console - console.error( - 'Unknown error from PostCSS plugin. Your current PostCSS ' + - 'version is ' + - runtimeVer + - ', but ' + - pluginName + - ' uses ' + - pluginVer + - '. Perhaps this is the source of the error below.' - ) - } - } - } - } catch (err) { - /* c8 ignore next 3 */ - // eslint-disable-next-line no-console - if (console && console.error) console.error(err) - } - return error - } - - prepareVisitors() { - this.listeners = {} - let add = (plugin, type, cb) => { - if (!this.listeners[type]) this.listeners[type] = [] - this.listeners[type].push([plugin, cb]) - } - for (let plugin of this.plugins) { - if (typeof plugin === 'object') { - for (let event in plugin) { - if (!PLUGIN_PROPS[event] && /^[A-Z]/.test(event)) { - throw new Error( - `Unknown event ${event} in ${plugin.postcssPlugin}. ` + - `Try to update PostCSS (${this.processor.version} now).` - ) - } - if (!NOT_VISITORS[event]) { - if (typeof plugin[event] === 'object') { - for (let filter in plugin[event]) { - if (filter === '*') { - add(plugin, event, plugin[event][filter]) - } else { - add( - plugin, - event + '-' + filter.toLowerCase(), - plugin[event][filter] - ) - } - } - } else if (typeof plugin[event] === 'function') { - add(plugin, event, plugin[event]) - } - } - } - } - } - this.hasListener = Object.keys(this.listeners).length > 0 - } - - async runAsync() { - this.plugin = 0 - for (let i = 0; i < this.plugins.length; i++) { - let plugin = this.plugins[i] - let promise = this.runOnRoot(plugin) - if (isPromise(promise)) { - try { - await promise - } catch (error) { - throw this.handleError(error) - } - } - } - - this.prepareVisitors() - if (this.hasListener) { - let root = this.result.root - while (!root[isClean]) { - root[isClean] = true - let stack = [toStack(root)] - while (stack.length > 0) { - let promise = this.visitTick(stack) - if (isPromise(promise)) { - try { - await promise - } catch (e) { - let node = stack[stack.length - 1].node - throw this.handleError(e, node) - } - } - } - } - - if (this.listeners.OnceExit) { - for (let [plugin, visitor] of this.listeners.OnceExit) { - this.result.lastPlugin = plugin - try { - if (root.type === 'document') { - let roots = root.nodes.map(subRoot => - visitor(subRoot, this.helpers) - ) - - await Promise.all(roots) - } else { - await visitor(root, this.helpers) - } - } catch (e) { - throw this.handleError(e) - } - } - } - } - - this.processed = true - return this.stringify() - } - - runOnRoot(plugin) { - this.result.lastPlugin = plugin - try { - if (typeof plugin === 'object' && plugin.Once) { - if (this.result.root.type === 'document') { - let roots = this.result.root.nodes.map(root => - plugin.Once(root, this.helpers) - ) - - if (isPromise(roots[0])) { - return Promise.all(roots) - } - - return roots - } - - return plugin.Once(this.result.root, this.helpers) - } else if (typeof plugin === 'function') { - return plugin(this.result.root, this.result) - } - } catch (error) { - throw this.handleError(error) - } - } - - stringify() { - if (this.error) throw this.error - if (this.stringified) return this.result - this.stringified = true - - this.sync() - - let opts = this.result.opts - let str = stringify - if (opts.syntax) str = opts.syntax.stringify - if (opts.stringifier) str = opts.stringifier - if (str.stringify) str = str.stringify - - let map = new MapGenerator(str, this.result.root, this.result.opts) - let data = map.generate() - this.result.css = data[0] - this.result.map = data[1] - - return this.result - } - - sync() { - if (this.error) throw this.error - if (this.processed) return this.result - this.processed = true - - if (this.processing) { - throw this.getAsyncError() - } - - for (let plugin of this.plugins) { - let promise = this.runOnRoot(plugin) - if (isPromise(promise)) { - throw this.getAsyncError() - } - } - - this.prepareVisitors() - if (this.hasListener) { - let root = this.result.root - while (!root[isClean]) { - root[isClean] = true - this.walkSync(root) - } - if (this.listeners.OnceExit) { - if (root.type === 'document') { - for (let subRoot of root.nodes) { - this.visitSync(this.listeners.OnceExit, subRoot) - } - } else { - this.visitSync(this.listeners.OnceExit, root) - } - } - } - - return this.result - } - - then(onFulfilled, onRejected) { - if (process.env.NODE_ENV !== 'production') { - if (!('from' in this.opts)) { - warnOnce( - 'Without `from` option PostCSS could generate wrong source map ' + - 'and will not find Browserslist config. Set it to CSS file path ' + - 'or to `undefined` to prevent this warning.' - ) - } - } - return this.async().then(onFulfilled, onRejected) - } - - toString() { - return this.css - } - - visitSync(visitors, node) { - for (let [plugin, visitor] of visitors) { - this.result.lastPlugin = plugin - let promise - try { - promise = visitor(node, this.helpers) - } catch (e) { - throw this.handleError(e, node.proxyOf) - } - if (node.type !== 'root' && node.type !== 'document' && !node.parent) { - return true - } - if (isPromise(promise)) { - throw this.getAsyncError() - } - } - } - - visitTick(stack) { - let visit = stack[stack.length - 1] - let { node, visitors } = visit - - if (node.type !== 'root' && node.type !== 'document' && !node.parent) { - stack.pop() - return - } - - if (visitors.length > 0 && visit.visitorIndex < visitors.length) { - let [plugin, visitor] = visitors[visit.visitorIndex] - visit.visitorIndex += 1 - if (visit.visitorIndex === visitors.length) { - visit.visitors = [] - visit.visitorIndex = 0 - } - this.result.lastPlugin = plugin - try { - return visitor(node.toProxy(), this.helpers) - } catch (e) { - throw this.handleError(e, node) - } - } - - if (visit.iterator !== 0) { - let iterator = visit.iterator - let child - while ((child = node.nodes[node.indexes[iterator]])) { - node.indexes[iterator] += 1 - if (!child[isClean]) { - child[isClean] = true - stack.push(toStack(child)) - return - } - } - visit.iterator = 0 - delete node.indexes[iterator] - } - - let events = visit.events - while (visit.eventIndex < events.length) { - let event = events[visit.eventIndex] - visit.eventIndex += 1 - if (event === CHILDREN) { - if (node.nodes && node.nodes.length) { - node[isClean] = true - visit.iterator = node.getIterator() - } - return - } else if (this.listeners[event]) { - visit.visitors = this.listeners[event] - return - } - } - stack.pop() - } - - walkSync(node) { - node[isClean] = true - let events = getEvents(node) - for (let event of events) { - if (event === CHILDREN) { - if (node.nodes) { - node.each(child => { - if (!child[isClean]) this.walkSync(child) - }) - } - } else { - let visitors = this.listeners[event] - if (visitors) { - if (this.visitSync(visitors, node.toProxy())) return - } - } - } - } - - warnings() { - return this.sync().warnings() - } -} - -LazyResult.registerPostcss = dependant => { - postcss = dependant -} - -module.exports = LazyResult -LazyResult.default = LazyResult - -Root.registerLazyResult(LazyResult) -Document.registerLazyResult(LazyResult) diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/list.d.ts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/list.d.ts deleted file mode 100644 index e262ad3..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/list.d.ts +++ /dev/null @@ -1,60 +0,0 @@ -declare namespace list { - type List = { - /** - * Safely splits comma-separated values (such as those for `transition-*` - * and `background` properties). - * - * ```js - * Once (root, { list }) { - * list.comma('black, linear-gradient(white, black)') - * //=> ['black', 'linear-gradient(white, black)'] - * } - * ``` - * - * @param str Comma-separated values. - * @return Split values. - */ - comma(str: string): string[] - - default: List - - /** - * Safely splits space-separated values (such as those for `background`, - * `border-radius`, and other shorthand properties). - * - * ```js - * Once (root, { list }) { - * list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)'] - * } - * ``` - * - * @param str Space-separated values. - * @return Split values. - */ - space(str: string): string[] - - /** - * Safely splits values. - * - * ```js - * Once (root, { list }) { - * list.split('1px calc(10% + 1px)', [' ', '\n', '\t']) //=> ['1px', 'calc(10% + 1px)'] - * } - * ``` - * - * @param string separated values. - * @param separators array of separators. - * @param last boolean indicator. - * @return Split values. - */ - split( - string: string, - separators: readonly string[], - last: boolean - ): string[] - } -} - -declare const list: list.List - -export = list diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/list.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/list.js deleted file mode 100644 index 1b31f98..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/list.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict' - -let list = { - comma(string) { - return list.split(string, [','], true) - }, - - space(string) { - let spaces = [' ', '\n', '\t'] - return list.split(string, spaces) - }, - - split(string, separators, last) { - let array = [] - let current = '' - let split = false - - let func = 0 - let inQuote = false - let prevQuote = '' - let escape = false - - for (let letter of string) { - if (escape) { - escape = false - } else if (letter === '\\') { - escape = true - } else if (inQuote) { - if (letter === prevQuote) { - inQuote = false - } - } else if (letter === '"' || letter === "'") { - inQuote = true - prevQuote = letter - } else if (letter === '(') { - func += 1 - } else if (letter === ')') { - if (func > 0) func -= 1 - } else if (func === 0) { - if (separators.includes(letter)) split = true - } - - if (split) { - if (current !== '') array.push(current.trim()) - current = '' - split = false - } else { - current += letter - } - } - - if (last || current !== '') array.push(current.trim()) - return array - } -} - -module.exports = list -list.default = list diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/map-generator.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/map-generator.js deleted file mode 100644 index 89069d3..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/map-generator.js +++ /dev/null @@ -1,368 +0,0 @@ -'use strict' - -let { dirname, relative, resolve, sep } = require('path') -let { SourceMapConsumer, SourceMapGenerator } = require('source-map-js') -let { pathToFileURL } = require('url') - -let Input = require('./input') - -let sourceMapAvailable = Boolean(SourceMapConsumer && SourceMapGenerator) -let pathAvailable = Boolean(dirname && resolve && relative && sep) - -class MapGenerator { - constructor(stringify, root, opts, cssString) { - this.stringify = stringify - this.mapOpts = opts.map || {} - this.root = root - this.opts = opts - this.css = cssString - this.originalCSS = cssString - this.usesFileUrls = !this.mapOpts.from && this.mapOpts.absolute - - this.memoizedFileURLs = new Map() - this.memoizedPaths = new Map() - this.memoizedURLs = new Map() - } - - addAnnotation() { - let content - - if (this.isInline()) { - content = - 'data:application/json;base64,' + this.toBase64(this.map.toString()) - } else if (typeof this.mapOpts.annotation === 'string') { - content = this.mapOpts.annotation - } else if (typeof this.mapOpts.annotation === 'function') { - content = this.mapOpts.annotation(this.opts.to, this.root) - } else { - content = this.outputFile() + '.map' - } - let eol = '\n' - if (this.css.includes('\r\n')) eol = '\r\n' - - this.css += eol + '/*# sourceMappingURL=' + content + ' */' - } - - applyPrevMaps() { - for (let prev of this.previous()) { - let from = this.toUrl(this.path(prev.file)) - let root = prev.root || dirname(prev.file) - let map - - if (this.mapOpts.sourcesContent === false) { - map = new SourceMapConsumer(prev.text) - if (map.sourcesContent) { - map.sourcesContent = null - } - } else { - map = prev.consumer() - } - - this.map.applySourceMap(map, from, this.toUrl(this.path(root))) - } - } - - clearAnnotation() { - if (this.mapOpts.annotation === false) return - - if (this.root) { - let node - for (let i = this.root.nodes.length - 1; i >= 0; i--) { - node = this.root.nodes[i] - if (node.type !== 'comment') continue - if (node.text.startsWith('# sourceMappingURL=')) { - this.root.removeChild(i) - } - } - } else if (this.css) { - this.css = this.css.replace(/\n*\/\*#[\S\s]*?\*\/$/gm, '') - } - } - - generate() { - this.clearAnnotation() - if (pathAvailable && sourceMapAvailable && this.isMap()) { - return this.generateMap() - } else { - let result = '' - this.stringify(this.root, i => { - result += i - }) - return [result] - } - } - - generateMap() { - if (this.root) { - this.generateString() - } else if (this.previous().length === 1) { - let prev = this.previous()[0].consumer() - prev.file = this.outputFile() - this.map = SourceMapGenerator.fromSourceMap(prev, { - ignoreInvalidMapping: true - }) - } else { - this.map = new SourceMapGenerator({ - file: this.outputFile(), - ignoreInvalidMapping: true - }) - this.map.addMapping({ - generated: { column: 0, line: 1 }, - original: { column: 0, line: 1 }, - source: this.opts.from - ? this.toUrl(this.path(this.opts.from)) - : '' - }) - } - - if (this.isSourcesContent()) this.setSourcesContent() - if (this.root && this.previous().length > 0) this.applyPrevMaps() - if (this.isAnnotation()) this.addAnnotation() - - if (this.isInline()) { - return [this.css] - } else { - return [this.css, this.map] - } - } - - generateString() { - this.css = '' - this.map = new SourceMapGenerator({ - file: this.outputFile(), - ignoreInvalidMapping: true - }) - - let line = 1 - let column = 1 - - let noSource = '' - let mapping = { - generated: { column: 0, line: 0 }, - original: { column: 0, line: 0 }, - source: '' - } - - let last, lines - this.stringify(this.root, (str, node, type) => { - this.css += str - - if (node && type !== 'end') { - mapping.generated.line = line - mapping.generated.column = column - 1 - if (node.source && node.source.start) { - mapping.source = this.sourcePath(node) - mapping.original.line = node.source.start.line - mapping.original.column = node.source.start.column - 1 - this.map.addMapping(mapping) - } else { - mapping.source = noSource - mapping.original.line = 1 - mapping.original.column = 0 - this.map.addMapping(mapping) - } - } - - lines = str.match(/\n/g) - if (lines) { - line += lines.length - last = str.lastIndexOf('\n') - column = str.length - last - } else { - column += str.length - } - - if (node && type !== 'start') { - let p = node.parent || { raws: {} } - let childless = - node.type === 'decl' || (node.type === 'atrule' && !node.nodes) - if (!childless || node !== p.last || p.raws.semicolon) { - if (node.source && node.source.end) { - mapping.source = this.sourcePath(node) - mapping.original.line = node.source.end.line - mapping.original.column = node.source.end.column - 1 - mapping.generated.line = line - mapping.generated.column = column - 2 - this.map.addMapping(mapping) - } else { - mapping.source = noSource - mapping.original.line = 1 - mapping.original.column = 0 - mapping.generated.line = line - mapping.generated.column = column - 1 - this.map.addMapping(mapping) - } - } - } - }) - } - - isAnnotation() { - if (this.isInline()) { - return true - } - if (typeof this.mapOpts.annotation !== 'undefined') { - return this.mapOpts.annotation - } - if (this.previous().length) { - return this.previous().some(i => i.annotation) - } - return true - } - - isInline() { - if (typeof this.mapOpts.inline !== 'undefined') { - return this.mapOpts.inline - } - - let annotation = this.mapOpts.annotation - if (typeof annotation !== 'undefined' && annotation !== true) { - return false - } - - if (this.previous().length) { - return this.previous().some(i => i.inline) - } - return true - } - - isMap() { - if (typeof this.opts.map !== 'undefined') { - return !!this.opts.map - } - return this.previous().length > 0 - } - - isSourcesContent() { - if (typeof this.mapOpts.sourcesContent !== 'undefined') { - return this.mapOpts.sourcesContent - } - if (this.previous().length) { - return this.previous().some(i => i.withContent()) - } - return true - } - - outputFile() { - if (this.opts.to) { - return this.path(this.opts.to) - } else if (this.opts.from) { - return this.path(this.opts.from) - } else { - return 'to.css' - } - } - - path(file) { - if (this.mapOpts.absolute) return file - if (file.charCodeAt(0) === 60 /* `<` */) return file - if (/^\w+:\/\//.test(file)) return file - let cached = this.memoizedPaths.get(file) - if (cached) return cached - - let from = this.opts.to ? dirname(this.opts.to) : '.' - - if (typeof this.mapOpts.annotation === 'string') { - from = dirname(resolve(from, this.mapOpts.annotation)) - } - - let path = relative(from, file) - this.memoizedPaths.set(file, path) - - return path - } - - previous() { - if (!this.previousMaps) { - this.previousMaps = [] - if (this.root) { - this.root.walk(node => { - if (node.source && node.source.input.map) { - let map = node.source.input.map - if (!this.previousMaps.includes(map)) { - this.previousMaps.push(map) - } - } - }) - } else { - let input = new Input(this.originalCSS, this.opts) - if (input.map) this.previousMaps.push(input.map) - } - } - - return this.previousMaps - } - - setSourcesContent() { - let already = {} - if (this.root) { - this.root.walk(node => { - if (node.source) { - let from = node.source.input.from - if (from && !already[from]) { - already[from] = true - let fromUrl = this.usesFileUrls - ? this.toFileUrl(from) - : this.toUrl(this.path(from)) - this.map.setSourceContent(fromUrl, node.source.input.css) - } - } - }) - } else if (this.css) { - let from = this.opts.from - ? this.toUrl(this.path(this.opts.from)) - : '' - this.map.setSourceContent(from, this.css) - } - } - - sourcePath(node) { - if (this.mapOpts.from) { - return this.toUrl(this.mapOpts.from) - } else if (this.usesFileUrls) { - return this.toFileUrl(node.source.input.from) - } else { - return this.toUrl(this.path(node.source.input.from)) - } - } - - toBase64(str) { - if (Buffer) { - return Buffer.from(str).toString('base64') - } else { - return window.btoa(unescape(encodeURIComponent(str))) - } - } - - toFileUrl(path) { - let cached = this.memoizedFileURLs.get(path) - if (cached) return cached - - if (pathToFileURL) { - let fileURL = pathToFileURL(path).toString() - this.memoizedFileURLs.set(path, fileURL) - - return fileURL - } else { - throw new Error( - '`map.absolute` option is not available in this PostCSS build' - ) - } - } - - toUrl(path) { - let cached = this.memoizedURLs.get(path) - if (cached) return cached - - if (sep === '\\') { - path = path.replace(/\\/g, '/') - } - - let url = encodeURI(path).replace(/[#?]/g, encodeURIComponent) - this.memoizedURLs.set(path, url) - - return url - } -} - -module.exports = MapGenerator diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/no-work-result.d.ts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/no-work-result.d.ts deleted file mode 100644 index 094f30a..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/no-work-result.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -import LazyResult from './lazy-result.js' -import { SourceMap } from './postcss.js' -import Processor from './processor.js' -import Result, { Message, ResultOptions } from './result.js' -import Root from './root.js' -import Warning from './warning.js' - -declare namespace NoWorkResult { - // eslint-disable-next-line @typescript-eslint/no-use-before-define - export { NoWorkResult_ as default } -} - -/** - * A Promise proxy for the result of PostCSS transformations. - * This lazy result instance doesn't parse css unless `NoWorkResult#root` or `Result#root` - * are accessed. See the example below for details. - * A `NoWork` instance is returned by `Processor#process` ONLY when no plugins defined. - * - * ```js - * const noWorkResult = postcss().process(css) // No plugins are defined. - * // CSS is not parsed - * let root = noWorkResult.root // now css is parsed because we accessed the root - * ``` - */ -declare class NoWorkResult_ implements LazyResult { - catch: Promise>['catch'] - finally: Promise>['finally'] - then: Promise>['then'] - get content(): string - get css(): string - get map(): SourceMap - get messages(): Message[] - get opts(): ResultOptions - get processor(): Processor - get root(): Root - get [Symbol.toStringTag](): string - constructor(processor: Processor, css: string, opts: ResultOptions) - async(): Promise> - sync(): Result - toString(): string - warnings(): Warning[] -} - -declare class NoWorkResult extends NoWorkResult_ {} - -export = NoWorkResult diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/no-work-result.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/no-work-result.js deleted file mode 100644 index dd46182..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/no-work-result.js +++ /dev/null @@ -1,138 +0,0 @@ -'use strict' - -let MapGenerator = require('./map-generator') -let parse = require('./parse') -const Result = require('./result') -let stringify = require('./stringify') -let warnOnce = require('./warn-once') - -class NoWorkResult { - get content() { - return this.result.css - } - - get css() { - return this.result.css - } - - get map() { - return this.result.map - } - - get messages() { - return [] - } - - get opts() { - return this.result.opts - } - - get processor() { - return this.result.processor - } - - get root() { - if (this._root) { - return this._root - } - - let root - let parser = parse - - try { - root = parser(this._css, this._opts) - } catch (error) { - this.error = error - } - - if (this.error) { - throw this.error - } else { - this._root = root - return root - } - } - - get [Symbol.toStringTag]() { - return 'NoWorkResult' - } - - constructor(processor, css, opts) { - css = css.toString() - this.stringified = false - - this._processor = processor - this._css = css - this._opts = opts - this._map = undefined - let root - - let str = stringify - this.result = new Result(this._processor, root, this._opts) - this.result.css = css - - let self = this - Object.defineProperty(this.result, 'root', { - get() { - return self.root - } - }) - - let map = new MapGenerator(str, root, this._opts, css) - if (map.isMap()) { - let [generatedCSS, generatedMap] = map.generate() - if (generatedCSS) { - this.result.css = generatedCSS - } - if (generatedMap) { - this.result.map = generatedMap - } - } else { - map.clearAnnotation() - this.result.css = map.css - } - } - - async() { - if (this.error) return Promise.reject(this.error) - return Promise.resolve(this.result) - } - - catch(onRejected) { - return this.async().catch(onRejected) - } - - finally(onFinally) { - return this.async().then(onFinally, onFinally) - } - - sync() { - if (this.error) throw this.error - return this.result - } - - then(onFulfilled, onRejected) { - if (process.env.NODE_ENV !== 'production') { - if (!('from' in this._opts)) { - warnOnce( - 'Without `from` option PostCSS could generate wrong source map ' + - 'and will not find Browserslist config. Set it to CSS file path ' + - 'or to `undefined` to prevent this warning.' - ) - } - } - - return this.async().then(onFulfilled, onRejected) - } - - toString() { - return this._css - } - - warnings() { - return [] - } -} - -module.exports = NoWorkResult -NoWorkResult.default = NoWorkResult diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/node.d.ts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/node.d.ts deleted file mode 100644 index aa7229f..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/node.d.ts +++ /dev/null @@ -1,541 +0,0 @@ -import AtRule = require('./at-rule.js') - -import { AtRuleProps } from './at-rule.js' -import Comment, { CommentProps } from './comment.js' -import Container, { NewChild } from './container.js' -import CssSyntaxError from './css-syntax-error.js' -import Declaration, { DeclarationProps } from './declaration.js' -import Document from './document.js' -import Input from './input.js' -import { Stringifier, Syntax } from './postcss.js' -import Result from './result.js' -import Root from './root.js' -import Rule, { RuleProps } from './rule.js' -import Warning, { WarningOptions } from './warning.js' - -declare namespace Node { - export type ChildNode = AtRule.default | Comment | Declaration | Rule - - export type AnyNode = - | AtRule.default - | Comment - | Declaration - | Document - | Root - | Rule - - export type ChildProps = - | AtRuleProps - | CommentProps - | DeclarationProps - | RuleProps - - export interface Position { - /** - * Source line in file. In contrast to `offset` it starts from 1. - */ - column: number - - /** - * Source column in file. - */ - line: number - - /** - * Source offset in file. It starts from 0. - */ - offset: number - } - - export interface Range { - /** - * End position, exclusive. - */ - end: Position - - /** - * Start position, inclusive. - */ - start: Position - } - - /** - * Source represents an interface for the {@link Node.source} property. - */ - export interface Source { - /** - * The inclusive ending position for the source - * code of a node. - */ - end?: Position - - /** - * The source file from where a node has originated. - */ - input: Input - - /** - * The inclusive starting position for the source - * code of a node. - */ - start?: Position - } - - /** - * Interface represents an interface for an object received - * as parameter by Node class constructor. - */ - export interface NodeProps { - source?: Source - } - - export interface NodeErrorOptions { - /** - * An ending index inside a node's string that should be highlighted as - * source of error. - */ - endIndex?: number - /** - * An index inside a node's string that should be highlighted as source - * of error. - */ - index?: number - /** - * Plugin name that created this error. PostCSS will set it automatically. - */ - plugin?: string - /** - * A word inside a node's string, that should be highlighted as source - * of error. - */ - word?: string - } - - // eslint-disable-next-line @typescript-eslint/no-shadow - class Node extends Node_ {} - export { Node as default } -} - -/** - * It represents an abstract class that handles common - * methods for other CSS abstract syntax tree nodes. - * - * Any node that represents CSS selector or value should - * not extend the `Node` class. - */ -declare abstract class Node_ { - /** - * It represents parent of the current node. - * - * ```js - * root.nodes[0].parent === root //=> true - * ``` - */ - parent: Container | Document | undefined - - /** - * It represents unnecessary whitespace and characters present - * in the css source code. - * - * Information to generate byte-to-byte equal node string as it was - * in the origin input. - * - * The properties of the raws object are decided by parser, - * the default parser uses the following properties: - * - * * `before`: the space symbols before the node. It also stores `*` - * and `_` symbols before the declaration (IE hack). - * * `after`: the space symbols after the last child of the node - * to the end of the node. - * * `between`: the symbols between the property and value - * for declarations, selector and `{` for rules, or last parameter - * and `{` for at-rules. - * * `semicolon`: contains true if the last child has - * an (optional) semicolon. - * * `afterName`: the space between the at-rule name and its parameters. - * * `left`: the space symbols between `/*` and the comment’s text. - * * `right`: the space symbols between the comment’s text - * and */. - * - `important`: the content of the important statement, - * if it is not just `!important`. - * - * PostCSS filters out the comments inside selectors, declaration values - * and at-rule parameters but it stores the origin content in raws. - * - * ```js - * const root = postcss.parse('a {\n color:black\n}') - * root.first.first.raws //=> { before: '\n ', between: ':' } - * ``` - */ - raws: any - - /** - * It represents information related to origin of a node and is required - * for generating source maps. - * - * The nodes that are created manually using the public APIs - * provided by PostCSS will have `source` undefined and - * will be absent in the source map. - * - * For this reason, the plugin developer should consider - * duplicating nodes as the duplicate node will have the - * same source as the original node by default or assign - * source to a node created manually. - * - * ```js - * decl.source.input.from //=> '/home/ai/source.css' - * decl.source.start //=> { line: 10, column: 2 } - * decl.source.end //=> { line: 10, column: 12 } - * ``` - * - * ```js - * // Incorrect method, source not specified! - * const prefixed = postcss.decl({ - * prop: '-moz-' + decl.prop, - * value: decl.value - * }) - * - * // Correct method, source is inherited when duplicating. - * const prefixed = decl.clone({ - * prop: '-moz-' + decl.prop - * }) - * ``` - * - * ```js - * if (atrule.name === 'add-link') { - * const rule = postcss.rule({ - * selector: 'a', - * source: atrule.source - * }) - * - * atrule.parent.insertBefore(atrule, rule) - * } - * ``` - */ - source?: Node.Source - - /** - * It represents type of a node in - * an abstract syntax tree. - * - * A type of node helps in identification of a node - * and perform operation based on it's type. - * - * ```js - * const declaration = new Declaration({ - * prop: 'color', - * value: 'black' - * }) - * - * declaration.type //=> 'decl' - * ``` - */ - type: string - - constructor(defaults?: object) - - /** - * Insert new node after current node to current node’s parent. - * - * Just alias for `node.parent.insertAfter(node, add)`. - * - * ```js - * decl.after('color: black') - * ``` - * - * @param newNode New node. - * @return This node for methods chain. - */ - after( - newNode: Node | Node.ChildProps | readonly Node[] | string | undefined - ): this - - /** - * It assigns properties to an existing node instance. - * - * ```js - * decl.assign({ prop: 'word-wrap', value: 'break-word' }) - * ``` - * - * @param overrides New properties to override the node. - * - * @return `this` for method chaining. - */ - assign(overrides: object): this - - /** - * Insert new node before current node to current node’s parent. - * - * Just alias for `node.parent.insertBefore(node, add)`. - * - * ```js - * decl.before('content: ""') - * ``` - * - * @param newNode New node. - * @return This node for methods chain. - */ - before( - newNode: Node | Node.ChildProps | readonly Node[] | string | undefined - ): this - - /** - * Clear the code style properties for the node and its children. - * - * ```js - * node.raws.before //=> ' ' - * node.cleanRaws() - * node.raws.before //=> undefined - * ``` - * - * @param keepBetween Keep the `raws.between` symbols. - */ - cleanRaws(keepBetween?: boolean): void - - /** - * It creates clone of an existing node, which includes all the properties - * and their values, that includes `raws` but not `type`. - * - * ```js - * decl.raws.before //=> "\n " - * const cloned = decl.clone({ prop: '-moz-' + decl.prop }) - * cloned.raws.before //=> "\n " - * cloned.toString() //=> -moz-transform: scale(0) - * ``` - * - * @param overrides New properties to override in the clone. - * - * @return Duplicate of the node instance. - */ - clone(overrides?: object): this - - /** - * Shortcut to clone the node and insert the resulting cloned node - * after the current node. - * - * @param overrides New properties to override in the clone. - * @return New node. - */ - cloneAfter(overrides?: object): this - - /** - * Shortcut to clone the node and insert the resulting cloned node - * before the current node. - * - * ```js - * decl.cloneBefore({ prop: '-moz-' + decl.prop }) - * ``` - * - * @param overrides Mew properties to override in the clone. - * - * @return New node - */ - cloneBefore(overrides?: object): this - - /** - * It creates an instance of the class `CssSyntaxError` and parameters passed - * to this method are assigned to the error instance. - * - * The error instance will have description for the - * error, original position of the node in the - * source, showing line and column number. - * - * If any previous map is present, it would be used - * to get original position of the source. - * - * The Previous Map here is referred to the source map - * generated by previous compilation, example: Less, - * Stylus and Sass. - * - * This method returns the error instance instead of - * throwing it. - * - * ```js - * if (!variables[name]) { - * throw decl.error(`Unknown variable ${name}`, { word: name }) - * // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black - * // color: $black - * // a - * // ^ - * // background: white - * } - * ``` - * - * @param message Description for the error instance. - * @param options Options for the error instance. - * - * @return Error instance is returned. - */ - error(message: string, options?: Node.NodeErrorOptions): CssSyntaxError - - /** - * Returns the next child of the node’s parent. - * Returns `undefined` if the current node is the last child. - * - * ```js - * if (comment.text === 'delete next') { - * const next = comment.next() - * if (next) { - * next.remove() - * } - * } - * ``` - * - * @return Next node. - */ - next(): Node.ChildNode | undefined - - /** - * Get the position for a word or an index inside the node. - * - * @param opts Options. - * @return Position. - */ - positionBy(opts?: Pick): Node.Position - - /** - * Convert string index to line/column. - * - * @param index The symbol number in the node’s string. - * @return Symbol position in file. - */ - positionInside(index: number): Node.Position - - /** - * Returns the previous child of the node’s parent. - * Returns `undefined` if the current node is the first child. - * - * ```js - * const annotation = decl.prev() - * if (annotation.type === 'comment') { - * readAnnotation(annotation.text) - * } - * ``` - * - * @return Previous node. - */ - prev(): Node.ChildNode | undefined - - /** - * Get the range for a word or start and end index inside the node. - * The start index is inclusive; the end index is exclusive. - * - * @param opts Options. - * @return Range. - */ - rangeBy( - opts?: Pick - ): Node.Range - - /** - * Returns a `raws` value. If the node is missing - * the code style property (because the node was manually built or cloned), - * PostCSS will try to autodetect the code style property by looking - * at other nodes in the tree. - * - * ```js - * const root = postcss.parse('a { background: white }') - * root.nodes[0].append({ prop: 'color', value: 'black' }) - * root.nodes[0].nodes[1].raws.before //=> undefined - * root.nodes[0].nodes[1].raw('before') //=> ' ' - * ``` - * - * @param prop Name of code style property. - * @param defaultType Name of default value, it can be missed - * if the value is the same as prop. - * @return {string} Code style value. - */ - raw(prop: string, defaultType?: string): string - - /** - * It removes the node from its parent and deletes its parent property. - * - * ```js - * if (decl.prop.match(/^-webkit-/)) { - * decl.remove() - * } - * ``` - * - * @return `this` for method chaining. - */ - remove(): this - - /** - * Inserts node(s) before the current node and removes the current node. - * - * ```js - * AtRule: { - * mixin: atrule => { - * atrule.replaceWith(mixinRules[atrule.params]) - * } - * } - * ``` - * - * @param nodes Mode(s) to replace current one. - * @return Current node to methods chain. - */ - replaceWith(...nodes: NewChild[]): this - - /** - * Finds the Root instance of the node’s tree. - * - * ```js - * root.nodes[0].nodes[0].root() === root - * ``` - * - * @return Root parent. - */ - root(): Root - - /** - * Fix circular links on `JSON.stringify()`. - * - * @return Cleaned object. - */ - toJSON(): object - - /** - * It compiles the node to browser readable cascading style sheets string - * depending on it's type. - * - * ```js - * new Rule({ selector: 'a' }).toString() //=> "a {}" - * ``` - * - * @param stringifier A syntax to use in string generation. - * @return CSS string of this node. - */ - toString(stringifier?: Stringifier | Syntax): string - - /** - * It is a wrapper for {@link Result#warn}, providing convenient - * way of generating warnings. - * - * ```js - * Declaration: { - * bad: (decl, { result }) => { - * decl.warn(result, 'Deprecated property: bad') - * } - * } - * ``` - * - * @param result The `Result` instance that will receive the warning. - * @param message Description for the warning. - * @param options Options for the warning. - * - * @return `Warning` instance is returned - */ - warn(result: Result, message: string, options?: WarningOptions): Warning - - /** - * If this node isn't already dirty, marks it and its ancestors as such. This - * indicates to the LazyResult processor that the {@link Root} has been - * modified by the current plugin and may need to be processed again by other - * plugins. - */ - protected markDirty(): void -} - -declare class Node extends Node_ {} - -export = Node diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/node.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/node.js deleted file mode 100644 index 2b865ba..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/node.js +++ /dev/null @@ -1,434 +0,0 @@ -'use strict' - -let CssSyntaxError = require('./css-syntax-error') -let Stringifier = require('./stringifier') -let stringify = require('./stringify') -let { isClean, my } = require('./symbols') - -function cloneNode(obj, parent) { - let cloned = new obj.constructor() - - for (let i in obj) { - if (!Object.prototype.hasOwnProperty.call(obj, i)) { - /* c8 ignore next 2 */ - continue - } - if (i === 'proxyCache') continue - let value = obj[i] - let type = typeof value - - if (i === 'parent' && type === 'object') { - if (parent) cloned[i] = parent - } else if (i === 'source') { - cloned[i] = value - } else if (Array.isArray(value)) { - cloned[i] = value.map(j => cloneNode(j, cloned)) - } else { - if (type === 'object' && value !== null) value = cloneNode(value) - cloned[i] = value - } - } - - return cloned -} - -function sourceOffset(inputCSS, position) { - // Not all custom syntaxes support `offset` in `source.start` and `source.end` - if ( - position && - typeof position.offset !== 'undefined' - ) { - return position.offset; - } - - let column = 1 - let line = 1 - let offset = 0 - - for (let i = 0; i < inputCSS.length; i++) { - if (line === position.line && column === position.column) { - offset = i - break - } - - if (inputCSS[i] === '\n') { - column = 1 - line += 1 - } else { - column += 1 - } - } - - return offset -} - -class Node { - get proxyOf() { - return this - } - - constructor(defaults = {}) { - this.raws = {} - this[isClean] = false - this[my] = true - - for (let name in defaults) { - if (name === 'nodes') { - this.nodes = [] - for (let node of defaults[name]) { - if (typeof node.clone === 'function') { - this.append(node.clone()) - } else { - this.append(node) - } - } - } else { - this[name] = defaults[name] - } - } - } - - addToError(error) { - error.postcssNode = this - if (error.stack && this.source && /\n\s{4}at /.test(error.stack)) { - let s = this.source - error.stack = error.stack.replace( - /\n\s{4}at /, - `$&${s.input.from}:${s.start.line}:${s.start.column}$&` - ) - } - return error - } - - after(add) { - this.parent.insertAfter(this, add) - return this - } - - assign(overrides = {}) { - for (let name in overrides) { - this[name] = overrides[name] - } - return this - } - - before(add) { - this.parent.insertBefore(this, add) - return this - } - - cleanRaws(keepBetween) { - delete this.raws.before - delete this.raws.after - if (!keepBetween) delete this.raws.between - } - - clone(overrides = {}) { - let cloned = cloneNode(this) - for (let name in overrides) { - cloned[name] = overrides[name] - } - return cloned - } - - cloneAfter(overrides = {}) { - let cloned = this.clone(overrides) - this.parent.insertAfter(this, cloned) - return cloned - } - - cloneBefore(overrides = {}) { - let cloned = this.clone(overrides) - this.parent.insertBefore(this, cloned) - return cloned - } - - error(message, opts = {}) { - if (this.source) { - let { end, start } = this.rangeBy(opts) - return this.source.input.error( - message, - { column: start.column, line: start.line }, - { column: end.column, line: end.line }, - opts - ) - } - return new CssSyntaxError(message) - } - - getProxyProcessor() { - return { - get(node, prop) { - if (prop === 'proxyOf') { - return node - } else if (prop === 'root') { - return () => node.root().toProxy() - } else { - return node[prop] - } - }, - - set(node, prop, value) { - if (node[prop] === value) return true - node[prop] = value - if ( - prop === 'prop' || - prop === 'value' || - prop === 'name' || - prop === 'params' || - prop === 'important' || - /* c8 ignore next */ - prop === 'text' - ) { - node.markDirty() - } - return true - } - } - } - - /* c8 ignore next 3 */ - markClean() { - this[isClean] = true - } - - markDirty() { - if (this[isClean]) { - this[isClean] = false - let next = this - while ((next = next.parent)) { - next[isClean] = false - } - } - } - - next() { - if (!this.parent) return undefined - let index = this.parent.index(this) - return this.parent.nodes[index + 1] - } - - positionBy(opts) { - let pos = this.source.start - if (opts.index) { - pos = this.positionInside(opts.index) - } else if (opts.word) { - let inputString = ('document' in this.source.input) - ? this.source.input.document - : this.source.input.css - let stringRepresentation = inputString.slice( - sourceOffset(inputString, this.source.start), - sourceOffset(inputString, this.source.end) - ) - let index = stringRepresentation.indexOf(opts.word) - if (index !== -1) pos = this.positionInside(index) - } - return pos - } - - positionInside(index) { - let column = this.source.start.column - let line = this.source.start.line - let inputString = ('document' in this.source.input) - ? this.source.input.document - : this.source.input.css - let offset = sourceOffset(inputString, this.source.start) - let end = offset + index - - for (let i = offset; i < end; i++) { - if (inputString[i] === '\n') { - column = 1 - line += 1 - } else { - column += 1 - } - } - - return { column, line } - } - - prev() { - if (!this.parent) return undefined - let index = this.parent.index(this) - return this.parent.nodes[index - 1] - } - - rangeBy(opts) { - let start = { - column: this.source.start.column, - line: this.source.start.line - } - let end = this.source.end - ? { - column: this.source.end.column + 1, - line: this.source.end.line - } - : { - column: start.column + 1, - line: start.line - } - - if (opts.word) { - let inputString = ('document' in this.source.input) - ? this.source.input.document - : this.source.input.css - let stringRepresentation = inputString.slice( - sourceOffset(inputString, this.source.start), - sourceOffset(inputString, this.source.end) - ) - let index = stringRepresentation.indexOf(opts.word) - if (index !== -1) { - start = this.positionInside(index) - end = this.positionInside( - index + opts.word.length, - ) - } - } else { - if (opts.start) { - start = { - column: opts.start.column, - line: opts.start.line - } - } else if (opts.index) { - start = this.positionInside(opts.index) - } - - if (opts.end) { - end = { - column: opts.end.column, - line: opts.end.line - } - } else if (typeof opts.endIndex === 'number') { - end = this.positionInside(opts.endIndex) - } else if (opts.index) { - end = this.positionInside(opts.index + 1) - } - } - - if ( - end.line < start.line || - (end.line === start.line && end.column <= start.column) - ) { - end = { column: start.column + 1, line: start.line } - } - - return { end, start } - } - - raw(prop, defaultType) { - let str = new Stringifier() - return str.raw(this, prop, defaultType) - } - - remove() { - if (this.parent) { - this.parent.removeChild(this) - } - this.parent = undefined - return this - } - - replaceWith(...nodes) { - if (this.parent) { - let bookmark = this - let foundSelf = false - for (let node of nodes) { - if (node === this) { - foundSelf = true - } else if (foundSelf) { - this.parent.insertAfter(bookmark, node) - bookmark = node - } else { - this.parent.insertBefore(bookmark, node) - } - } - - if (!foundSelf) { - this.remove() - } - } - - return this - } - - root() { - let result = this - while (result.parent && result.parent.type !== 'document') { - result = result.parent - } - return result - } - - toJSON(_, inputs) { - let fixed = {} - let emitInputs = inputs == null - inputs = inputs || new Map() - let inputsNextIndex = 0 - - for (let name in this) { - if (!Object.prototype.hasOwnProperty.call(this, name)) { - /* c8 ignore next 2 */ - continue - } - if (name === 'parent' || name === 'proxyCache') continue - let value = this[name] - - if (Array.isArray(value)) { - fixed[name] = value.map(i => { - if (typeof i === 'object' && i.toJSON) { - return i.toJSON(null, inputs) - } else { - return i - } - }) - } else if (typeof value === 'object' && value.toJSON) { - fixed[name] = value.toJSON(null, inputs) - } else if (name === 'source') { - let inputId = inputs.get(value.input) - if (inputId == null) { - inputId = inputsNextIndex - inputs.set(value.input, inputsNextIndex) - inputsNextIndex++ - } - fixed[name] = { - end: value.end, - inputId, - start: value.start - } - } else { - fixed[name] = value - } - } - - if (emitInputs) { - fixed.inputs = [...inputs.keys()].map(input => input.toJSON()) - } - - return fixed - } - - toProxy() { - if (!this.proxyCache) { - this.proxyCache = new Proxy(this, this.getProxyProcessor()) - } - return this.proxyCache - } - - toString(stringifier = stringify) { - if (stringifier.stringify) stringifier = stringifier.stringify - let result = '' - stringifier(this, i => { - result += i - }) - return result - } - - warn(result, text, opts) { - let data = { node: this } - for (let i in opts) data[i] = opts[i] - return result.warn(text, data) - } -} - -module.exports = Node -Node.default = Node diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/parse.d.ts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/parse.d.ts deleted file mode 100644 index 4c943a4..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/parse.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { Parser } from './postcss.js' - -interface Parse extends Parser { - default: Parse -} - -declare const parse: Parse - -export = parse diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/parse.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/parse.js deleted file mode 100644 index 00a1037..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/parse.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict' - -let Container = require('./container') -let Input = require('./input') -let Parser = require('./parser') - -function parse(css, opts) { - let input = new Input(css, opts) - let parser = new Parser(input) - try { - parser.parse() - } catch (e) { - if (process.env.NODE_ENV !== 'production') { - if (e.name === 'CssSyntaxError' && opts && opts.from) { - if (/\.scss$/i.test(opts.from)) { - e.message += - '\nYou tried to parse SCSS with ' + - 'the standard CSS parser; ' + - 'try again with the postcss-scss parser' - } else if (/\.sass/i.test(opts.from)) { - e.message += - '\nYou tried to parse Sass with ' + - 'the standard CSS parser; ' + - 'try again with the postcss-sass parser' - } else if (/\.less$/i.test(opts.from)) { - e.message += - '\nYou tried to parse Less with ' + - 'the standard CSS parser; ' + - 'try again with the postcss-less parser' - } - } - } - throw e - } - - return parser.root -} - -module.exports = parse -parse.default = parse - -Container.registerParse(parse) diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/parser.js b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/parser.js deleted file mode 100644 index 64fb5d8..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/parser.js +++ /dev/null @@ -1,611 +0,0 @@ -'use strict' - -let AtRule = require('./at-rule') -let Comment = require('./comment') -let Declaration = require('./declaration') -let Root = require('./root') -let Rule = require('./rule') -let tokenizer = require('./tokenize') - -const SAFE_COMMENT_NEIGHBOR = { - empty: true, - space: true -} - -function findLastWithPosition(tokens) { - for (let i = tokens.length - 1; i >= 0; i--) { - let token = tokens[i] - let pos = token[3] || token[2] - if (pos) return pos - } -} - -class Parser { - constructor(input) { - this.input = input - - this.root = new Root() - this.current = this.root - this.spaces = '' - this.semicolon = false - - this.createTokenizer() - this.root.source = { input, start: { column: 1, line: 1, offset: 0 } } - } - - atrule(token) { - let node = new AtRule() - node.name = token[1].slice(1) - if (node.name === '') { - this.unnamedAtrule(node, token) - } - this.init(node, token[2]) - - let type - let prev - let shift - let last = false - let open = false - let params = [] - let brackets = [] - - while (!this.tokenizer.endOfFile()) { - token = this.tokenizer.nextToken() - type = token[0] - - if (type === '(' || type === '[') { - brackets.push(type === '(' ? ')' : ']') - } else if (type === '{' && brackets.length > 0) { - brackets.push('}') - } else if (type === brackets[brackets.length - 1]) { - brackets.pop() - } - - if (brackets.length === 0) { - if (type === ';') { - node.source.end = this.getPosition(token[2]) - node.source.end.offset++ - this.semicolon = true - break - } else if (type === '{') { - open = true - break - } else if (type === '}') { - if (params.length > 0) { - shift = params.length - 1 - prev = params[shift] - while (prev && prev[0] === 'space') { - prev = params[--shift] - } - if (prev) { - node.source.end = this.getPosition(prev[3] || prev[2]) - node.source.end.offset++ - } - } - this.end(token) - break - } else { - params.push(token) - } - } else { - params.push(token) - } - - if (this.tokenizer.endOfFile()) { - last = true - break - } - } - - node.raws.between = this.spacesAndCommentsFromEnd(params) - if (params.length) { - node.raws.afterName = this.spacesAndCommentsFromStart(params) - this.raw(node, 'params', params) - if (last) { - token = params[params.length - 1] - node.source.end = this.getPosition(token[3] || token[2]) - node.source.end.offset++ - this.spaces = node.raws.between - node.raws.between = '' - } - } else { - node.raws.afterName = '' - node.params = '' - } - - if (open) { - node.nodes = [] - this.current = node - } - } - - checkMissedSemicolon(tokens) { - let colon = this.colon(tokens) - if (colon === false) return - - let founded = 0 - let token - for (let j = colon - 1; j >= 0; j--) { - token = tokens[j] - if (token[0] !== 'space') { - founded += 1 - if (founded === 2) break - } - } - // If the token is a word, e.g. `!important`, `red` or any other valid property's value. - // Then we need to return the colon after that word token. [3] is the "end" colon of that word. - // And because we need it after that one we do +1 to get the next one. - throw this.input.error( - 'Missed semicolon', - token[0] === 'word' ? token[3] + 1 : token[2] - ) - } - - colon(tokens) { - let brackets = 0 - let prev, token, type - for (let [i, element] of tokens.entries()) { - token = element - type = token[0] - - if (type === '(') { - brackets += 1 - } - if (type === ')') { - brackets -= 1 - } - if (brackets === 0 && type === ':') { - if (!prev) { - this.doubleColon(token) - } else if (prev[0] === 'word' && prev[1] === 'progid') { - continue - } else { - return i - } - } - - prev = token - } - return false - } - - comment(token) { - let node = new Comment() - this.init(node, token[2]) - node.source.end = this.getPosition(token[3] || token[2]) - node.source.end.offset++ - - let text = token[1].slice(2, -2) - if (/^\s*$/.test(text)) { - node.text = '' - node.raws.left = text - node.raws.right = '' - } else { - let match = text.match(/^(\s*)([^]*\S)(\s*)$/) - node.text = match[2] - node.raws.left = match[1] - node.raws.right = match[3] - } - } - - createTokenizer() { - this.tokenizer = tokenizer(this.input) - } - - decl(tokens, customProperty) { - let node = new Declaration() - this.init(node, tokens[0][2]) - - let last = tokens[tokens.length - 1] - if (last[0] === ';') { - this.semicolon = true - tokens.pop() - } - - node.source.end = this.getPosition( - last[3] || last[2] || findLastWithPosition(tokens) - ) - node.source.end.offset++ - - while (tokens[0][0] !== 'word') { - if (tokens.length === 1) this.unknownWord(tokens) - node.raws.before += tokens.shift()[1] - } - node.source.start = this.getPosition(tokens[0][2]) - - node.prop = '' - while (tokens.length) { - let type = tokens[0][0] - if (type === ':' || type === 'space' || type === 'comment') { - break - } - node.prop += tokens.shift()[1] - } - - node.raws.between = '' - - let token - while (tokens.length) { - token = tokens.shift() - - if (token[0] === ':') { - node.raws.between += token[1] - break - } else { - if (token[0] === 'word' && /\w/.test(token[1])) { - this.unknownWord([token]) - } - node.raws.between += token[1] - } - } - - if (node.prop[0] === '_' || node.prop[0] === '*') { - node.raws.before += node.prop[0] - node.prop = node.prop.slice(1) - } - - let firstSpaces = [] - let next - while (tokens.length) { - next = tokens[0][0] - if (next !== 'space' && next !== 'comment') break - firstSpaces.push(tokens.shift()) - } - - this.precheckMissedSemicolon(tokens) - - for (let i = tokens.length - 1; i >= 0; i--) { - token = tokens[i] - if (token[1].toLowerCase() === '!important') { - node.important = true - let string = this.stringFrom(tokens, i) - string = this.spacesFromEnd(tokens) + string - if (string !== ' !important') node.raws.important = string - break - } else if (token[1].toLowerCase() === 'important') { - let cache = tokens.slice(0) - let str = '' - for (let j = i; j > 0; j--) { - let type = cache[j][0] - if (str.trim().startsWith('!') && type !== 'space') { - break - } - str = cache.pop()[1] + str - } - if (str.trim().startsWith('!')) { - node.important = true - node.raws.important = str - tokens = cache - } - } - - if (token[0] !== 'space' && token[0] !== 'comment') { - break - } - } - - let hasWord = tokens.some(i => i[0] !== 'space' && i[0] !== 'comment') - - if (hasWord) { - node.raws.between += firstSpaces.map(i => i[1]).join('') - firstSpaces = [] - } - this.raw(node, 'value', firstSpaces.concat(tokens), customProperty) - - if (node.value.includes(':') && !customProperty) { - this.checkMissedSemicolon(tokens) - } - } - - doubleColon(token) { - throw this.input.error( - 'Double colon', - { offset: token[2] }, - { offset: token[2] + token[1].length } - ) - } - - emptyRule(token) { - let node = new Rule() - this.init(node, token[2]) - node.selector = '' - node.raws.between = '' - this.current = node - } - - end(token) { - if (this.current.nodes && this.current.nodes.length) { - this.current.raws.semicolon = this.semicolon - } - this.semicolon = false - - this.current.raws.after = (this.current.raws.after || '') + this.spaces - this.spaces = '' - - if (this.current.parent) { - this.current.source.end = this.getPosition(token[2]) - this.current.source.end.offset++ - this.current = this.current.parent - } else { - this.unexpectedClose(token) - } - } - - endFile() { - if (this.current.parent) this.unclosedBlock() - if (this.current.nodes && this.current.nodes.length) { - this.current.raws.semicolon = this.semicolon - } - this.current.raws.after = (this.current.raws.after || '') + this.spaces - this.root.source.end = this.getPosition(this.tokenizer.position()) - } - - freeSemicolon(token) { - this.spaces += token[1] - if (this.current.nodes) { - let prev = this.current.nodes[this.current.nodes.length - 1] - if (prev && prev.type === 'rule' && !prev.raws.ownSemicolon) { - prev.raws.ownSemicolon = this.spaces - this.spaces = '' - prev.source.end = this.getPosition(token[2]) - prev.source.end.offset += prev.raws.ownSemicolon.length - } - } - } - - // Helpers - - getPosition(offset) { - let pos = this.input.fromOffset(offset) - return { - column: pos.col, - line: pos.line, - offset - } - } - - init(node, offset) { - this.current.push(node) - node.source = { - input: this.input, - start: this.getPosition(offset) - } - node.raws.before = this.spaces - this.spaces = '' - if (node.type !== 'comment') this.semicolon = false - } - - other(start) { - let end = false - let type = null - let colon = false - let bracket = null - let brackets = [] - let customProperty = start[1].startsWith('--') - - let tokens = [] - let token = start - while (token) { - type = token[0] - tokens.push(token) - - if (type === '(' || type === '[') { - if (!bracket) bracket = token - brackets.push(type === '(' ? ')' : ']') - } else if (customProperty && colon && type === '{') { - if (!bracket) bracket = token - brackets.push('}') - } else if (brackets.length === 0) { - if (type === ';') { - if (colon) { - this.decl(tokens, customProperty) - return - } else { - break - } - } else if (type === '{') { - this.rule(tokens) - return - } else if (type === '}') { - this.tokenizer.back(tokens.pop()) - end = true - break - } else if (type === ':') { - colon = true - } - } else if (type === brackets[brackets.length - 1]) { - brackets.pop() - if (brackets.length === 0) bracket = null - } - - token = this.tokenizer.nextToken() - } - - if (this.tokenizer.endOfFile()) end = true - if (brackets.length > 0) this.unclosedBracket(bracket) - - if (end && colon) { - if (!customProperty) { - while (tokens.length) { - token = tokens[tokens.length - 1][0] - if (token !== 'space' && token !== 'comment') break - this.tokenizer.back(tokens.pop()) - } - } - this.decl(tokens, customProperty) - } else { - this.unknownWord(tokens) - } - } - - parse() { - let token - while (!this.tokenizer.endOfFile()) { - token = this.tokenizer.nextToken() - - switch (token[0]) { - case 'space': - this.spaces += token[1] - break - - case ';': - this.freeSemicolon(token) - break - - case '}': - this.end(token) - break - - case 'comment': - this.comment(token) - break - - case 'at-word': - this.atrule(token) - break - - case '{': - this.emptyRule(token) - break - - default: - this.other(token) - break - } - } - this.endFile() - } - - precheckMissedSemicolon(/* tokens */) { - // Hook for Safe Parser - } - - raw(node, prop, tokens, customProperty) { - let token, type - let length = tokens.length - let value = '' - let clean = true - let next, prev - - for (let i = 0; i < length; i += 1) { - token = tokens[i] - type = token[0] - if (type === 'space' && i === length - 1 && !customProperty) { - clean = false - } else if (type === 'comment') { - prev = tokens[i - 1] ? tokens[i - 1][0] : 'empty' - next = tokens[i + 1] ? tokens[i + 1][0] : 'empty' - if (!SAFE_COMMENT_NEIGHBOR[prev] && !SAFE_COMMENT_NEIGHBOR[next]) { - if (value.slice(-1) === ',') { - clean = false - } else { - value += token[1] - } - } else { - clean = false - } - } else { - value += token[1] - } - } - if (!clean) { - let raw = tokens.reduce((all, i) => all + i[1], '') - node.raws[prop] = { raw, value } - } - node[prop] = value - } - - rule(tokens) { - tokens.pop() - - let node = new Rule() - this.init(node, tokens[0][2]) - - node.raws.between = this.spacesAndCommentsFromEnd(tokens) - this.raw(node, 'selector', tokens) - this.current = node - } - - spacesAndCommentsFromEnd(tokens) { - let lastTokenType - let spaces = '' - while (tokens.length) { - lastTokenType = tokens[tokens.length - 1][0] - if (lastTokenType !== 'space' && lastTokenType !== 'comment') break - spaces = tokens.pop()[1] + spaces - } - return spaces - } - - // Errors - - spacesAndCommentsFromStart(tokens) { - let next - let spaces = '' - while (tokens.length) { - next = tokens[0][0] - if (next !== 'space' && next !== 'comment') break - spaces += tokens.shift()[1] - } - return spaces - } - - spacesFromEnd(tokens) { - let lastTokenType - let spaces = '' - while (tokens.length) { - lastTokenType = tokens[tokens.length - 1][0] - if (lastTokenType !== 'space') break - spaces = tokens.pop()[1] + spaces - } - return spaces - } - - stringFrom(tokens, from) { - let result = '' - for (let i = from; i < tokens.length; i++) { - result += tokens[i][1] - } - tokens.splice(from, tokens.length - from) - return result - } - - unclosedBlock() { - let pos = this.current.source.start - throw this.input.error('Unclosed block', pos.line, pos.column) - } - - unclosedBracket(bracket) { - throw this.input.error( - 'Unclosed bracket', - { offset: bracket[2] }, - { offset: bracket[2] + 1 } - ) - } - - unexpectedClose(token) { - throw this.input.error( - 'Unexpected }', - { offset: token[2] }, - { offset: token[2] + 1 } - ) - } - - unknownWord(tokens) { - throw this.input.error( - 'Unknown word ' + tokens[0][1], - { offset: tokens[0][2] }, - { offset: tokens[0][2] + tokens[0][1].length } - ) - } - - unnamedAtrule(node, token) { - throw this.input.error( - 'At-rule without name', - { offset: token[2] }, - { offset: token[2] + token[1].length } - ) - } -} - -module.exports = Parser diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/postcss.d.mts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/postcss.d.mts deleted file mode 100644 index d343f3c..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/postcss.d.mts +++ /dev/null @@ -1,69 +0,0 @@ -export { - // Type-only exports - AcceptedPlugin, - - AnyNode, - atRule, - AtRule, - AtRuleProps, - Builder, - ChildNode, - ChildProps, - comment, - Comment, - CommentProps, - Container, - ContainerProps, - CssSyntaxError, - decl, - Declaration, - DeclarationProps, - // postcss function / namespace - default, - document, - Document, - DocumentProps, - FilePosition, - fromJSON, - Helpers, - Input, - - JSONHydrator, - // This is a class, but it’s not re-exported. That’s why it’s exported as type-only here. - type LazyResult, - list, - Message, - Node, - NodeErrorOptions, - NodeProps, - OldPlugin, - parse, - Parser, - // @ts-expect-error This value exists, but it’s untyped. - plugin, - Plugin, - PluginCreator, - Position, - Postcss, - ProcessOptions, - Processor, - Result, - root, - Root, - RootProps, - rule, - Rule, - RuleProps, - Source, - SourceMap, - SourceMapOptions, - Stringifier, - // Value exports from postcss.mjs - stringify, - Syntax, - TransformCallback, - Transformer, - Warning, - - WarningOptions -} from './postcss.js' diff --git a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/postcss.d.ts b/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/postcss.d.ts deleted file mode 100644 index c5e3605..0000000 --- a/node_modules/.pnpm/postcss@8.5.3/node_modules/postcss/lib/postcss.d.ts +++ /dev/null @@ -1,458 +0,0 @@ -import { RawSourceMap, SourceMapGenerator } from 'source-map-js' - -import AtRule, { AtRuleProps } from './at-rule.js' -import Comment, { CommentProps } from './comment.js' -import Container, { ContainerProps, NewChild } from './container.js' -import CssSyntaxError from './css-syntax-error.js' -import Declaration, { DeclarationProps } from './declaration.js' -import Document, { DocumentProps } from './document.js' -import Input, { FilePosition } from './input.js' -import LazyResult from './lazy-result.js' -import list from './list.js' -import Node, { - AnyNode, - ChildNode, - ChildProps, - NodeErrorOptions, - NodeProps, - Position, - Source -} from './node.js' -import Processor from './processor.js' -import Result, { Message } from './result.js' -import Root, { RootProps } from './root.js' -import Rule, { RuleProps } from './rule.js' -import Warning, { WarningOptions } from './warning.js' - -type DocumentProcessor = ( - document: Document, - helper: postcss.Helpers -) => Promise | void -type RootProcessor = ( - root: Root, - helper: postcss.Helpers -) => Promise | void -type DeclarationProcessor = ( - decl: Declaration, - helper: postcss.Helpers -) => Promise | void -type RuleProcessor = ( - rule: Rule, - helper: postcss.Helpers -) => Promise | void -type AtRuleProcessor = ( - atRule: AtRule, - helper: postcss.Helpers -) => Promise | void -type CommentProcessor = ( - comment: Comment, - helper: postcss.Helpers -) => Promise | void - -interface Processors { - /** - * Will be called on all`AtRule` nodes. - * - * Will be called again on node or children changes. - */ - AtRule?: { [name: string]: AtRuleProcessor } | AtRuleProcessor - - /** - * Will be called on all `AtRule` nodes, when all children will be processed. - * - * Will be called again on node or children changes. - */ - AtRuleExit?: { [name: string]: AtRuleProcessor } | AtRuleProcessor - - /** - * Will be called on all `Comment` nodes. - * - * Will be called again on node or children changes. - */ - Comment?: CommentProcessor - - /** - * Will be called on all `Comment` nodes after listeners - * for `Comment` event. - * - * Will be called again on node or children changes. - */ - CommentExit?: CommentProcessor - - /** - * Will be called on all `Declaration` nodes after listeners - * for `Declaration` event. - * - * Will be called again on node or children changes. - */ - Declaration?: { [prop: string]: DeclarationProcessor } | DeclarationProcessor - - /** - * Will be called on all `Declaration` nodes. - * - * Will be called again on node or children changes. - */ - DeclarationExit?: - | { [prop: string]: DeclarationProcessor } - | DeclarationProcessor - - /** - * Will be called on `Document` node. - * - * Will be called again on children changes. - */ - Document?: DocumentProcessor - - /** - * Will be called on `Document` node, when all children will be processed. - * - * Will be called again on children changes. - */ - DocumentExit?: DocumentProcessor - - /** - * Will be called on `Root` node once. - */ - Once?: RootProcessor - - /** - * Will be called on `Root` node once, when all children will be processed. - */ - OnceExit?: RootProcessor - - /** - * Will be called on `Root` node. - * - * Will be called again on children changes. - */ - Root?: RootProcessor - - /** - * Will be called on `Root` node, when all children will be processed. - * - * Will be called again on children changes. - */ - RootExit?: RootProcessor - - /** - * Will be called on all `Rule` nodes. - * - * Will be called again on node or children changes. - */ - Rule?: RuleProcessor - - /** - * Will be called on all `Rule` nodes, when all children will be processed. - * - * Will be called again on node or children changes. - */ - RuleExit?: RuleProcessor -} - -declare namespace postcss { - export { - AnyNode, - AtRule, - AtRuleProps, - ChildNode, - ChildProps, - Comment, - CommentProps, - Container, - ContainerProps, - CssSyntaxError, - Declaration, - DeclarationProps, - Document, - DocumentProps, - FilePosition, - Input, - LazyResult, - list, - Message, - NewChild, - Node, - NodeErrorOptions, - NodeProps, - Position, - Processor, - Result, - Root, - RootProps, - Rule, - RuleProps, - Source, - Warning, - WarningOptions - } - - export type SourceMap = { - toJSON(): RawSourceMap - } & SourceMapGenerator - - export type Helpers = { postcss: Postcss; result: Result } & Postcss - - export interface Plugin extends Processors { - postcssPlugin: string - prepare?: (result: Result) => Processors - } - - export interface PluginCreator { - (opts?: PluginOptions): Plugin | Processor - postcss: true - } - - export interface Transformer extends TransformCallback { - postcssPlugin: string - postcssVersion: string - } - - export interface TransformCallback { - (root: Root, result: Result): Promise | void - } - - export interface OldPlugin extends Transformer { - (opts?: T): Transformer - postcss: Transformer - } - - export type AcceptedPlugin = - | { - postcss: Processor | TransformCallback - } - | OldPlugin - | Plugin - | PluginCreator - | Processor - | TransformCallback - - export interface Parser { - ( - css: { toString(): string } | string, - opts?: Pick - ): RootNode - } - - export interface Builder { - (part: string, node?: AnyNode, type?: 'end' | 'start'): void - } - - export interface Stringifier { - (node: AnyNode, builder: Builder): void - } - - export interface JSONHydrator { - (data: object): Node - (data: object[]): Node[] - } - - export interface Syntax { - /** - * Function to generate AST by string. - */ - parse?: Parser - - /** - * Class to generate string by AST. - */ - stringify?: Stringifier - } - - export interface SourceMapOptions { - /** - * Use absolute path in generated source map. - */ - absolute?: boolean - - /** - * Indicates that PostCSS should add annotation comments to the CSS. - * By default, PostCSS will always add a comment with a path - * to the source map. PostCSS will not add annotations to CSS files - * that do not contain any comments. - * - * By default, PostCSS presumes that you want to save the source map as - * `opts.to + '.map'` and will use this path in the annotation comment. - * A different path can be set by providing a string value for annotation. - * - * If you have set `inline: true`, annotation cannot be disabled. - */ - annotation?: ((file: string, root: Root) => string) | boolean | string - - /** - * Override `from` in map’s sources. - */ - from?: string - - /** - * Indicates that the source map should be embedded in the output CSS - * as a Base64-encoded comment. By default, it is `true`. - * But if all previous maps are external, not inline, PostCSS will not embed - * the map even if you do not set this option. - * - * If you have an inline source map, the result.map property will be empty, - * as the source map will be contained within the text of `result.css`. - */ - inline?: boolean - - /** - * Source map content from a previous processing step (e.g., Sass). - * - * PostCSS will try to read the previous source map - * automatically (based on comments within the source CSS), but you can use - * this option to identify it manually. - * - * If desired, you can omit the previous map with prev: `false`. - */ - prev?: ((file: string) => string) | boolean | object | string - - /** - * Indicates that PostCSS should set the origin content (e.g., Sass source) - * of the source map. By default, it is true. But if all previous maps do not - * contain sources content, PostCSS will also leave it out even if you - * do not set this option. - */ - sourcesContent?: boolean - } - - export interface ProcessOptions { - /** - * Input file if it is not simple CSS file, but HTML with - - `; -} - -const ERR_LOAD_URL = "ERR_LOAD_URL"; -const ERR_LOAD_PUBLIC_URL = "ERR_LOAD_PUBLIC_URL"; -const ERR_DENIED_ID = "ERR_DENIED_ID"; -const debugLoad = createDebugger("vite:load"); -const debugTransform = createDebugger("vite:transform"); -const debugCache$1 = createDebugger("vite:cache"); -function transformRequest(url, server, options = {}) { - if (server._restartPromise && !options.ssr) throwClosedServerError(); - const cacheKey = (options.ssr ? "ssr:" : options.html ? "html:" : "") + url; - const timestamp = Date.now(); - const pending = server._pendingRequests.get(cacheKey); - if (pending) { - return server.moduleGraph.getModuleByUrl(removeTimestampQuery(url), options.ssr).then((module) => { - if (!module || pending.timestamp > module.lastInvalidationTimestamp) { - return pending.request; - } else { - pending.abort(); - return transformRequest(url, server, options); - } - }); - } - const request = doTransform(url, server, options, timestamp); - let cleared = false; - const clearCache = () => { - if (!cleared) { - server._pendingRequests.delete(cacheKey); - cleared = true; - } - }; - server._pendingRequests.set(cacheKey, { - request, - timestamp, - abort: clearCache - }); - return request.finally(clearCache); -} -async function doTransform(url, server, options, timestamp) { - url = removeTimestampQuery(url); - const { config, pluginContainer } = server; - const ssr = !!options.ssr; - if (ssr && isDepsOptimizerEnabled(config, true)) { - await initDevSsrDepsOptimizer(config, server); - } - let module = await server.moduleGraph.getModuleByUrl(url, ssr); - if (module) { - const cached = await getCachedTransformResult( - url, - module, - server, - ssr, - timestamp - ); - if (cached) return cached; - } - const resolved = module ? void 0 : await pluginContainer.resolveId(url, void 0, { ssr }) ?? void 0; - const id = module?.id ?? resolved?.id ?? url; - module ??= server.moduleGraph.getModuleById(id); - if (module) { - await server.moduleGraph._ensureEntryFromUrl(url, ssr, void 0, resolved); - const cached = await getCachedTransformResult( - url, - module, - server, - ssr, - timestamp - ); - if (cached) return cached; - } - const result = loadAndTransform( - id, - url, - server, - options, - timestamp, - module, - resolved - ); - if (!ssr) { - const depsOptimizer = getDepsOptimizer(config, ssr); - if (!depsOptimizer?.isOptimizedDepFile(id)) { - server._registerRequestProcessing(id, () => result); - } - } - return result; -} -async function getCachedTransformResult(url, module, server, ssr, timestamp) { - const prettyUrl = debugCache$1 ? prettifyUrl(url, server.config.root) : ""; - const softInvalidatedTransformResult = module && await handleModuleSoftInvalidation(module, ssr, timestamp, server); - if (softInvalidatedTransformResult) { - debugCache$1?.(`[memory-hmr] ${prettyUrl}`); - return softInvalidatedTransformResult; - } - const cached = module && (ssr ? module.ssrTransformResult : module.transformResult); - if (cached) { - debugCache$1?.(`[memory] ${prettyUrl}`); - return cached; - } -} -async function loadAndTransform(id, url, server, options, timestamp, mod, resolved) { - const { config, pluginContainer, moduleGraph } = server; - const { logger } = config; - const prettyUrl = debugLoad || debugTransform ? prettifyUrl(url, config.root) : ""; - const ssr = !!options.ssr; - const file = cleanUrl(id); - if (options.allowId && !options.allowId(id)) { - const err = new Error(`Denied ID ${id}`); - err.code = ERR_DENIED_ID; - throw err; - } - let code = null; - let map = null; - const loadStart = debugLoad ? performance$1.now() : 0; - const loadResult = await pluginContainer.load(id, { ssr }); - if (loadResult == null) { - if (options.html && !id.endsWith(".html")) { - return null; - } - if (options.ssr || isFileServingAllowed(file, server)) { - try { - code = await fsp.readFile(file, "utf-8"); - debugLoad?.(`${timeFrom(loadStart)} [fs] ${prettyUrl}`); - } catch (e) { - if (e.code !== "ENOENT") { - if (e.code === "EISDIR") { - e.message = `${e.message} ${file}`; - } - throw e; - } - } - if (code != null) { - ensureWatchedFile(server.watcher, file, config.root); - } - } - if (code) { - try { - const extracted = await extractSourcemapFromFile(code, file); - if (extracted) { - code = extracted.code; - map = extracted.map; - } - } catch (e) { - logger.warn(`Failed to load source map for ${file}. -${e}`, { - timestamp: true - }); - } - } - } else { - debugLoad?.(`${timeFrom(loadStart)} [plugin] ${prettyUrl}`); - if (isObject$1(loadResult)) { - code = loadResult.code; - map = loadResult.map; - } else { - code = loadResult; - } - } - if (code == null) { - const isPublicFile = checkPublicFile(url, config); - let publicDirName = path$n.relative(config.root, config.publicDir); - if (publicDirName[0] !== ".") publicDirName = "/" + publicDirName; - const msg = isPublicFile ? `This file is in ${publicDirName} and will be copied as-is during build without going through the plugin transforms, and therefore should not be imported from source code. It can only be referenced via HTML tags.` : `Does the file exist?`; - const importerMod = server.moduleGraph.idToModuleMap.get(id)?.importers.values().next().value; - const importer = importerMod?.file || importerMod?.url; - const err = new Error( - `Failed to load url ${url} (resolved id: ${id})${importer ? ` in ${importer}` : ""}. ${msg}` - ); - err.code = isPublicFile ? ERR_LOAD_PUBLIC_URL : ERR_LOAD_URL; - throw err; - } - if (server._restartPromise && !ssr) throwClosedServerError(); - mod ??= await moduleGraph._ensureEntryFromUrl(url, ssr, void 0, resolved); - const transformStart = debugTransform ? performance$1.now() : 0; - const transformResult = await pluginContainer.transform(code, id, { - inMap: map, - ssr - }); - const originalCode = code; - if (transformResult == null || isObject$1(transformResult) && transformResult.code == null) { - debugTransform?.( - timeFrom(transformStart) + colors$1.dim(` [skipped] ${prettyUrl}`) - ); - } else { - debugTransform?.(`${timeFrom(transformStart)} ${prettyUrl}`); - code = transformResult.code; - map = transformResult.map; - } - let normalizedMap; - if (typeof map === "string") { - normalizedMap = JSON.parse(map); - } else if (map) { - normalizedMap = map; - } else { - normalizedMap = null; - } - if (normalizedMap && "version" in normalizedMap && mod.file) { - if (normalizedMap.mappings) { - await injectSourcesContent(normalizedMap, mod.file, logger); - } - const sourcemapPath = `${mod.file}.map`; - applySourcemapIgnoreList( - normalizedMap, - sourcemapPath, - config.server.sourcemapIgnoreList, - logger - ); - if (path$n.isAbsolute(mod.file)) { - let modDirname; - for (let sourcesIndex = 0; sourcesIndex < normalizedMap.sources.length; ++sourcesIndex) { - const sourcePath = normalizedMap.sources[sourcesIndex]; - if (sourcePath) { - if (path$n.isAbsolute(sourcePath)) { - modDirname ??= path$n.dirname(mod.file); - normalizedMap.sources[sourcesIndex] = path$n.relative( - modDirname, - sourcePath - ); - } - } - } - } - } - if (server._restartPromise && !ssr) throwClosedServerError(); - const result = ssr && !server.config.experimental.skipSsrTransform ? await server.ssrTransform(code, normalizedMap, url, originalCode) : { - code, - map: normalizedMap, - etag: getEtag(code, { weak: true }) - }; - if (timestamp > mod.lastInvalidationTimestamp) - moduleGraph.updateModuleTransformResult(mod, result, ssr); - return result; -} -async function handleModuleSoftInvalidation(mod, ssr, timestamp, server) { - const transformResult = ssr ? mod.ssrInvalidationState : mod.invalidationState; - if (ssr) mod.ssrInvalidationState = void 0; - else mod.invalidationState = void 0; - if (!transformResult || transformResult === "HARD_INVALIDATED") return; - if (ssr ? mod.ssrTransformResult : mod.transformResult) { - throw new Error( - `Internal server error: Soft-invalidated module "${mod.url}" should not have existing transform result` - ); - } - let result; - if (ssr) { - result = transformResult; - } else { - await init; - const source = transformResult.code; - const s = new MagicString(source); - const [imports] = parse$d(source, mod.id || void 0); - for (const imp of imports) { - let rawUrl = source.slice(imp.s, imp.e); - if (rawUrl === "import.meta") continue; - const hasQuotes = rawUrl[0] === '"' || rawUrl[0] === "'"; - if (hasQuotes) { - rawUrl = rawUrl.slice(1, -1); - } - const urlWithoutTimestamp = removeTimestampQuery(rawUrl); - const hmrUrl = unwrapId$1( - stripBase(removeImportQuery(urlWithoutTimestamp), server.config.base) - ); - for (const importedMod of mod.clientImportedModules) { - if (importedMod.url !== hmrUrl) continue; - if (importedMod.lastHMRTimestamp > 0) { - const replacedUrl = injectQuery( - urlWithoutTimestamp, - `t=${importedMod.lastHMRTimestamp}` - ); - const start = hasQuotes ? imp.s + 1 : imp.s; - const end = hasQuotes ? imp.e - 1 : imp.e; - s.overwrite(start, end, replacedUrl); - } - if (imp.d === -1 && server.config.server.preTransformRequests) { - server.warmupRequest(hmrUrl, { ssr }); - } - break; - } - } - const code = s.toString(); - result = { - ...transformResult, - code, - etag: getEtag(code, { weak: true }) - }; - } - if (timestamp > mod.lastInvalidationTimestamp) - server.moduleGraph.updateModuleTransformResult(mod, result, ssr); - return result; -} - -function analyzeImportedModDifference(mod, rawId, moduleType, metadata) { - if (metadata?.isDynamicImport) return; - if (metadata?.importedNames?.length) { - const missingBindings = metadata.importedNames.filter((s) => !(s in mod)); - if (missingBindings.length) { - const lastBinding = missingBindings[missingBindings.length - 1]; - if (moduleType === "module") { - throw new SyntaxError( - `[vite] The requested module '${rawId}' does not provide an export named '${lastBinding}'` - ); - } else { - throw new SyntaxError(`[vite] Named export '${lastBinding}' not found. The requested module '${rawId}' is a CommonJS module, which may not support all module.exports as named exports. -CommonJS modules can always be imported via the default export, for example using: - -import pkg from '${rawId}'; -const {${missingBindings.join(", ")}} = pkg; -`); - } - } - } -} - -/** - * @param {import('estree').Node} param - * @returns {string[]} - */ -function extract_names(param) { - return extract_identifiers(param).map((node) => node.name); -} - -/** - * @param {import('estree').Node} param - * @param {import('estree').Identifier[]} nodes - * @returns {import('estree').Identifier[]} - */ -function extract_identifiers(param, nodes = []) { - switch (param.type) { - case 'Identifier': - nodes.push(param); - break; - - case 'MemberExpression': - let object = param; - while (object.type === 'MemberExpression') { - object = /** @type {any} */ (object.object); - } - nodes.push(/** @type {any} */ (object)); - break; - - case 'ObjectPattern': - for (const prop of param.properties) { - if (prop.type === 'RestElement') { - extract_identifiers(prop.argument, nodes); - } else { - extract_identifiers(prop.value, nodes); - } - } - - break; - - case 'ArrayPattern': - for (const element of param.elements) { - if (element) extract_identifiers(element, nodes); - } - - break; - - case 'RestElement': - extract_identifiers(param.argument, nodes); - break; - - case 'AssignmentPattern': - extract_identifiers(param.left, nodes); - break; - } - - return nodes; -} - -/** - * @typedef { import('estree').Node} Node - * @typedef {{ - * skip: () => void; - * remove: () => void; - * replace: (node: Node) => void; - * }} WalkerContext - */ - -class WalkerBase { - constructor() { - /** @type {boolean} */ - this.should_skip = false; - - /** @type {boolean} */ - this.should_remove = false; - - /** @type {Node | null} */ - this.replacement = null; - - /** @type {WalkerContext} */ - this.context = { - skip: () => (this.should_skip = true), - remove: () => (this.should_remove = true), - replace: (node) => (this.replacement = node) - }; - } - - /** - * @template {Node} Parent - * @param {Parent | null | undefined} parent - * @param {keyof Parent | null | undefined} prop - * @param {number | null | undefined} index - * @param {Node} node - */ - replace(parent, prop, index, node) { - if (parent && prop) { - if (index != null) { - /** @type {Array} */ (parent[prop])[index] = node; - } else { - /** @type {Node} */ (parent[prop]) = node; - } - } - } - - /** - * @template {Node} Parent - * @param {Parent | null | undefined} parent - * @param {keyof Parent | null | undefined} prop - * @param {number | null | undefined} index - */ - remove(parent, prop, index) { - if (parent && prop) { - if (index !== null && index !== undefined) { - /** @type {Array} */ (parent[prop]).splice(index, 1); - } else { - delete parent[prop]; - } - } - } -} - -/** - * @typedef { import('estree').Node} Node - * @typedef { import('./walker.js').WalkerContext} WalkerContext - * @typedef {( - * this: WalkerContext, - * node: Node, - * parent: Node | null, - * key: string | number | symbol | null | undefined, - * index: number | null | undefined - * ) => void} SyncHandler - */ - -class SyncWalker extends WalkerBase { - /** - * - * @param {SyncHandler} [enter] - * @param {SyncHandler} [leave] - */ - constructor(enter, leave) { - super(); - - /** @type {boolean} */ - this.should_skip = false; - - /** @type {boolean} */ - this.should_remove = false; - - /** @type {Node | null} */ - this.replacement = null; - - /** @type {WalkerContext} */ - this.context = { - skip: () => (this.should_skip = true), - remove: () => (this.should_remove = true), - replace: (node) => (this.replacement = node) - }; - - /** @type {SyncHandler | undefined} */ - this.enter = enter; - - /** @type {SyncHandler | undefined} */ - this.leave = leave; - } - - /** - * @template {Node} Parent - * @param {Node} node - * @param {Parent | null} parent - * @param {keyof Parent} [prop] - * @param {number | null} [index] - * @returns {Node | null} - */ - visit(node, parent, prop, index) { - if (node) { - if (this.enter) { - const _should_skip = this.should_skip; - const _should_remove = this.should_remove; - const _replacement = this.replacement; - this.should_skip = false; - this.should_remove = false; - this.replacement = null; - - this.enter.call(this.context, node, parent, prop, index); - - if (this.replacement) { - node = this.replacement; - this.replace(parent, prop, index, node); - } - - if (this.should_remove) { - this.remove(parent, prop, index); - } - - const skipped = this.should_skip; - const removed = this.should_remove; - - this.should_skip = _should_skip; - this.should_remove = _should_remove; - this.replacement = _replacement; - - if (skipped) return node; - if (removed) return null; - } - - /** @type {keyof Node} */ - let key; - - for (key in node) { - /** @type {unknown} */ - const value = node[key]; - - if (value && typeof value === 'object') { - if (Array.isArray(value)) { - const nodes = /** @type {Array} */ (value); - for (let i = 0; i < nodes.length; i += 1) { - const item = nodes[i]; - if (isNode(item)) { - if (!this.visit(item, node, key, i)) { - // removed - i--; - } - } - } - } else if (isNode(value)) { - this.visit(value, node, key, null); - } - } - } - - if (this.leave) { - const _replacement = this.replacement; - const _should_remove = this.should_remove; - this.replacement = null; - this.should_remove = false; - - this.leave.call(this.context, node, parent, prop, index); - - if (this.replacement) { - node = this.replacement; - this.replace(parent, prop, index, node); - } - - if (this.should_remove) { - this.remove(parent, prop, index); - } - - const removed = this.should_remove; - - this.replacement = _replacement; - this.should_remove = _should_remove; - - if (removed) return null; - } - } - - return node; - } -} - -/** - * Ducktype a node. - * - * @param {unknown} value - * @returns {value is Node} - */ -function isNode(value) { - return ( - value !== null && typeof value === 'object' && 'type' in value && typeof value.type === 'string' - ); -} - -/** - * @typedef {import('estree').Node} Node - * @typedef {import('./sync.js').SyncHandler} SyncHandler - * @typedef {import('./async.js').AsyncHandler} AsyncHandler - */ - -/** - * @param {Node} ast - * @param {{ - * enter?: SyncHandler - * leave?: SyncHandler - * }} walker - * @returns {Node | null} - */ -function walk$1(ast, { enter, leave }) { - const instance = new SyncWalker(enter, leave); - return instance.visit(ast, null); -} - -const ssrModuleExportsKey = `__vite_ssr_exports__`; -const ssrImportKey = `__vite_ssr_import__`; -const ssrDynamicImportKey = `__vite_ssr_dynamic_import__`; -const ssrExportAllKey = `__vite_ssr_exportAll__`; -const ssrImportMetaKey = `__vite_ssr_import_meta__`; -const hashbangRE = /^#!.*\n/; -async function ssrTransform(code, inMap, url, originalCode, options) { - if (options?.json?.stringify && isJSONRequest(url)) { - return ssrTransformJSON(code, inMap); - } - return ssrTransformScript(code, inMap, url, originalCode); -} -async function ssrTransformJSON(code, inMap) { - return { - code: code.replace("export default", `${ssrModuleExportsKey}.default =`), - map: inMap, - deps: [], - dynamicDeps: [] - }; -} -async function ssrTransformScript(code, inMap, url, originalCode) { - const s = new MagicString(code); - let ast; - try { - ast = await parseAstAsync(code); - } catch (err) { - if (!err.loc || !err.loc.line) throw err; - const line = err.loc.line; - throw new Error( - `Parse failure: ${err.message} -At file: ${url} -Contents of line ${line}: ${code.split("\n")[line - 1]}` - ); - } - let uid = 0; - const deps = /* @__PURE__ */ new Set(); - const dynamicDeps = /* @__PURE__ */ new Set(); - const idToImportMap = /* @__PURE__ */ new Map(); - const declaredConst = /* @__PURE__ */ new Set(); - const hoistIndex = hashbangRE.exec(code)?.[0].length ?? 0; - function defineImport(index, source, metadata) { - deps.add(source); - const importId = `__vite_ssr_import_${uid++}__`; - if (metadata && (metadata.importedNames == null || metadata.importedNames.length === 0)) { - metadata = void 0; - } - const metadataStr = metadata ? `, ${JSON.stringify(metadata)}` : ""; - s.appendLeft( - index, - `const ${importId} = await ${ssrImportKey}(${JSON.stringify( - source - )}${metadataStr}); -` - ); - return importId; - } - function defineExport(position, name, local = name) { - s.appendLeft( - position, - ` -Object.defineProperty(${ssrModuleExportsKey}, "${name}", { enumerable: true, configurable: true, get(){ return ${local} }});` - ); - } - const imports = []; - const exports = []; - for (const node of ast.body) { - if (node.type === "ImportDeclaration") { - imports.push(node); - } else if (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportAllDeclaration") { - exports.push(node); - } - } - for (const node of imports) { - const importId = defineImport(hoistIndex, node.source.value, { - importedNames: node.specifiers.map((s2) => { - if (s2.type === "ImportSpecifier") - return s2.imported.type === "Identifier" ? s2.imported.name : ( - // @ts-expect-error TODO: Estree types don't consider arbitrary module namespace specifiers yet - s2.imported.value - ); - else if (s2.type === "ImportDefaultSpecifier") return "default"; - }).filter(isDefined) - }); - s.remove(node.start, node.end); - for (const spec of node.specifiers) { - if (spec.type === "ImportSpecifier") { - if (spec.imported.type === "Identifier") { - idToImportMap.set( - spec.local.name, - `${importId}.${spec.imported.name}` - ); - } else { - idToImportMap.set( - spec.local.name, - `${importId}[${// @ts-expect-error TODO: Estree types don't consider arbitrary module namespace specifiers yet - JSON.stringify(spec.imported.value)}]` - ); - } - } else if (spec.type === "ImportDefaultSpecifier") { - idToImportMap.set(spec.local.name, `${importId}.default`); - } else { - idToImportMap.set(spec.local.name, importId); - } - } - } - for (const node of exports) { - if (node.type === "ExportNamedDeclaration") { - if (node.declaration) { - if (node.declaration.type === "FunctionDeclaration" || node.declaration.type === "ClassDeclaration") { - defineExport(node.end, node.declaration.id.name); - } else { - for (const declaration of node.declaration.declarations) { - const names = extract_names(declaration.id); - for (const name of names) { - defineExport(node.end, name); - } - } - } - s.remove(node.start, node.declaration.start); - } else { - s.remove(node.start, node.end); - if (node.source) { - const importId = defineImport( - node.start, - node.source.value, - { - importedNames: node.specifiers.map((s2) => s2.local.name) - } - ); - for (const spec of node.specifiers) { - const exportedAs = spec.exported.type === "Identifier" ? spec.exported.name : ( - // @ts-expect-error TODO: Estree types don't consider arbitrary module namespace specifiers yet - spec.exported.value - ); - defineExport( - node.start, - exportedAs, - `${importId}.${spec.local.name}` - ); - } - } else { - for (const spec of node.specifiers) { - const local = spec.local.name; - const binding = idToImportMap.get(local); - const exportedAs = spec.exported.type === "Identifier" ? spec.exported.name : ( - // @ts-expect-error TODO: Estree types don't consider arbitrary module namespace specifiers yet - spec.exported.value - ); - defineExport(node.end, exportedAs, binding || local); - } - } - } - } - if (node.type === "ExportDefaultDeclaration") { - const expressionTypes = ["FunctionExpression", "ClassExpression"]; - if ("id" in node.declaration && node.declaration.id && !expressionTypes.includes(node.declaration.type)) { - const { name } = node.declaration.id; - s.remove( - node.start, - node.start + 15 - /* 'export default '.length */ - ); - s.append( - ` -Object.defineProperty(${ssrModuleExportsKey}, "default", { enumerable: true, configurable: true, value: ${name} });` - ); - } else { - s.update( - node.start, - node.start + 14, - `${ssrModuleExportsKey}.default =` - ); - } - } - if (node.type === "ExportAllDeclaration") { - s.remove(node.start, node.end); - const importId = defineImport(node.start, node.source.value); - if (node.exported) { - defineExport(node.start, node.exported.name, `${importId}`); - } else { - s.appendLeft(node.start, `${ssrExportAllKey}(${importId}); -`); - } - } - } - walk(ast, { - onIdentifier(id, parent, parentStack) { - const grandparent = parentStack[1]; - const binding = idToImportMap.get(id.name); - if (!binding) { - return; - } - if (isStaticProperty(parent) && parent.shorthand) { - if (!isNodeInPattern(parent) || isInDestructuringAssignment(parent, parentStack)) { - s.appendLeft(id.end, `: ${binding}`); - } - } else if (parent.type === "PropertyDefinition" && grandparent?.type === "ClassBody" || parent.type === "ClassDeclaration" && id === parent.superClass) { - if (!declaredConst.has(id.name)) { - declaredConst.add(id.name); - const topNode = parentStack[parentStack.length - 2]; - s.prependRight(topNode.start, `const ${id.name} = ${binding}; -`); - } - } else if ( - // don't transform class name identifier - !(parent.type === "ClassExpression" && id === parent.id) - ) { - s.update(id.start, id.end, binding); - } - }, - onImportMeta(node) { - s.update(node.start, node.end, ssrImportMetaKey); - }, - onDynamicImport(node) { - s.update(node.start, node.start + 6, ssrDynamicImportKey); - if (node.type === "ImportExpression" && node.source.type === "Literal") { - dynamicDeps.add(node.source.value); - } - } - }); - let map = s.generateMap({ hires: "boundary" }); - map.sources = [path$n.basename(url)]; - map.sourcesContent = [originalCode]; - if (inMap && inMap.mappings && "sources" in inMap && inMap.sources.length > 0) { - map = combineSourcemaps(url, [ - map, - inMap - ]); - } - return { - code: s.toString(), - map, - deps: [...deps], - dynamicDeps: [...dynamicDeps] - }; -} -const isNodeInPatternWeakSet = /* @__PURE__ */ new WeakSet(); -const setIsNodeInPattern = (node) => isNodeInPatternWeakSet.add(node); -const isNodeInPattern = (node) => isNodeInPatternWeakSet.has(node); -function walk(root, { onIdentifier, onImportMeta, onDynamicImport }) { - const parentStack = []; - const varKindStack = []; - const scopeMap = /* @__PURE__ */ new WeakMap(); - const identifiers = []; - const setScope = (node, name) => { - let scopeIds = scopeMap.get(node); - if (scopeIds && scopeIds.has(name)) { - return; - } - if (!scopeIds) { - scopeIds = /* @__PURE__ */ new Set(); - scopeMap.set(node, scopeIds); - } - scopeIds.add(name); - }; - function isInScope(name, parents) { - return parents.some((node) => node && scopeMap.get(node)?.has(name)); - } - function handlePattern(p, parentScope) { - if (p.type === "Identifier") { - setScope(parentScope, p.name); - } else if (p.type === "RestElement") { - handlePattern(p.argument, parentScope); - } else if (p.type === "ObjectPattern") { - p.properties.forEach((property) => { - if (property.type === "RestElement") { - setScope(parentScope, property.argument.name); - } else { - handlePattern(property.value, parentScope); - } - }); - } else if (p.type === "ArrayPattern") { - p.elements.forEach((element) => { - if (element) { - handlePattern(element, parentScope); - } - }); - } else if (p.type === "AssignmentPattern") { - handlePattern(p.left, parentScope); - } else { - setScope(parentScope, p.name); - } - } - walk$1(root, { - enter(node, parent) { - if (node.type === "ImportDeclaration") { - return this.skip(); - } - if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) { - parentStack.unshift(parent); - } - if (node.type === "VariableDeclaration") { - varKindStack.unshift(node.kind); - } - if (node.type === "MetaProperty" && node.meta.name === "import") { - onImportMeta(node); - } else if (node.type === "ImportExpression") { - onDynamicImport(node); - } - if (node.type === "Identifier") { - if (!isInScope(node.name, parentStack) && isRefIdentifier(node, parent, parentStack)) { - identifiers.push([node, parentStack.slice(0)]); - } - } else if (isFunction$1(node)) { - if (node.type === "FunctionDeclaration") { - const parentScope = findParentScope(parentStack); - if (parentScope) { - setScope(parentScope, node.id.name); - } - } - if (node.type === "FunctionExpression" && node.id) { - setScope(node, node.id.name); - } - node.params.forEach((p) => { - if (p.type === "ObjectPattern" || p.type === "ArrayPattern") { - handlePattern(p, node); - return; - } - walk$1(p.type === "AssignmentPattern" ? p.left : p, { - enter(child, parent2) { - if (parent2?.type === "AssignmentPattern" && parent2?.right === child) { - return this.skip(); - } - if (child.type !== "Identifier") return; - if (isStaticPropertyKey(child, parent2)) return; - if (parent2?.type === "TemplateLiteral" && parent2?.expressions.includes(child) || parent2?.type === "CallExpression" && parent2?.callee === child) { - return; - } - setScope(node, child.name); - } - }); - }); - } else if (node.type === "ClassDeclaration") { - const parentScope = findParentScope(parentStack); - if (parentScope) { - setScope(parentScope, node.id.name); - } - } else if (node.type === "ClassExpression" && node.id) { - setScope(node, node.id.name); - } else if (node.type === "Property" && parent.type === "ObjectPattern") { - setIsNodeInPattern(node); - } else if (node.type === "VariableDeclarator") { - const parentFunction = findParentScope( - parentStack, - varKindStack[0] === "var" - ); - if (parentFunction) { - handlePattern(node.id, parentFunction); - } - } else if (node.type === "CatchClause" && node.param) { - handlePattern(node.param, node); - } - }, - leave(node, parent) { - if (parent && !(parent.type === "IfStatement" && node === parent.alternate)) { - parentStack.shift(); - } - if (node.type === "VariableDeclaration") { - varKindStack.shift(); - } - } - }); - identifiers.forEach(([node, stack]) => { - if (!isInScope(node.name, stack)) onIdentifier(node, stack[0], stack); - }); -} -function isRefIdentifier(id, parent, parentStack) { - if (parent.type === "CatchClause" || (parent.type === "VariableDeclarator" || parent.type === "ClassDeclaration") && parent.id === id) { - return false; - } - if (isFunction$1(parent)) { - if (parent.id === id) { - return false; - } - if (parent.params.includes(id)) { - return false; - } - } - if (parent.type === "MethodDefinition" && !parent.computed) { - return false; - } - if (isStaticPropertyKey(id, parent)) { - return false; - } - if (isNodeInPattern(parent) && parent.value === id) { - return false; - } - if (parent.type === "ArrayPattern" && !isInDestructuringAssignment(parent, parentStack)) { - return false; - } - if (parent.type === "MemberExpression" && parent.property === id && !parent.computed) { - return false; - } - if (parent.type === "ExportSpecifier") { - return false; - } - if (id.name === "arguments") { - return false; - } - return true; -} -const isStaticProperty = (node) => node && node.type === "Property" && !node.computed; -const isStaticPropertyKey = (node, parent) => isStaticProperty(parent) && parent.key === node; -const functionNodeTypeRE = /Function(?:Expression|Declaration)$|Method$/; -function isFunction$1(node) { - return functionNodeTypeRE.test(node.type); -} -const blockNodeTypeRE = /^BlockStatement$|^For(?:In|Of)?Statement$/; -function isBlock(node) { - return blockNodeTypeRE.test(node.type); -} -function findParentScope(parentStack, isVar = false) { - return parentStack.find(isVar ? isFunction$1 : isBlock); -} -function isInDestructuringAssignment(parent, parentStack) { - if (parent && (parent.type === "Property" || parent.type === "ArrayPattern")) { - return parentStack.some((i) => i.type === "AssignmentExpression"); - } - return false; -} - -let offset; -function calculateOffsetOnce() { - if (offset !== void 0) { - return; - } - try { - new Function("throw new Error(1)")(); - } catch (e) { - const match = /:(\d+):\d+\)$/.exec(e.stack.split("\n")[1]); - offset = match ? +match[1] - 1 : 0; - } -} -function ssrRewriteStacktrace(stack, moduleGraph) { - calculateOffsetOnce(); - return stack.split("\n").map((line) => { - return line.replace( - /^ {4}at (?:(\S.*?)\s\()?(.+?):(\d+)(?::(\d+))?\)?/, - (input, varName, id, line2, column) => { - if (!id) return input; - const mod = moduleGraph.idToModuleMap.get(id); - const rawSourceMap = mod?.ssrTransformResult?.map; - if (!rawSourceMap) { - return input; - } - const traced = new TraceMap(rawSourceMap); - const pos = originalPositionFor$1(traced, { - line: Number(line2) - offset, - // stacktrace's column is 1-indexed, but sourcemap's one is 0-indexed - column: Number(column) - 1 - }); - if (!pos.source || pos.line == null || pos.column == null) { - return input; - } - const trimmedVarName = varName.trim(); - const sourceFile = path$n.resolve(path$n.dirname(id), pos.source); - const source = `${sourceFile}:${pos.line}:${pos.column + 1}`; - if (!trimmedVarName || trimmedVarName === "eval") { - return ` at ${source}`; - } else { - return ` at ${trimmedVarName} (${source})`; - } - } - ); - }).join("\n"); -} -function rebindErrorStacktrace(e, stacktrace) { - const { configurable, writable } = Object.getOwnPropertyDescriptor( - e, - "stack" - ); - if (configurable) { - Object.defineProperty(e, "stack", { - value: stacktrace, - enumerable: true, - configurable: true, - writable: true - }); - } else if (writable) { - e.stack = stacktrace; - } -} -const rewroteStacktraces = /* @__PURE__ */ new WeakSet(); -function ssrFixStacktrace(e, moduleGraph) { - if (!e.stack) return; - if (rewroteStacktraces.has(e)) return; - const stacktrace = ssrRewriteStacktrace(e.stack, moduleGraph); - rebindErrorStacktrace(e, stacktrace); - rewroteStacktraces.add(e); -} - -const pendingModules = /* @__PURE__ */ new Map(); -const pendingModuleDependencyGraph = /* @__PURE__ */ new Map(); -const importErrors = /* @__PURE__ */ new WeakMap(); -async function ssrLoadModule(url, server, fixStacktrace) { - url = unwrapId$1(url); - const pending = pendingModules.get(url); - if (pending) { - return pending; - } - const modulePromise = instantiateModule(url, server, fixStacktrace); - pendingModules.set(url, modulePromise); - modulePromise.catch(() => { - }).finally(() => { - pendingModules.delete(url); - }); - return modulePromise; -} -async function instantiateModule(url, server, fixStacktrace) { - const { moduleGraph } = server; - const mod = await moduleGraph.ensureEntryFromUrl(url, true); - if (mod.ssrError) { - throw mod.ssrError; - } - if (mod.ssrModule) { - return mod.ssrModule; - } - const result = mod.ssrTransformResult || await transformRequest(url, server, { ssr: true }); - if (!result) { - throw new Error(`failed to load module for ssr: ${url}`); - } - const ssrModule = { - [Symbol.toStringTag]: "Module" - }; - Object.defineProperty(ssrModule, "__esModule", { value: true }); - mod.ssrModule = ssrModule; - const osNormalizedFilename = isWindows$3 ? path$n.resolve(mod.file) : mod.file; - const ssrImportMeta = { - dirname: path$n.dirname(osNormalizedFilename), - filename: osNormalizedFilename, - // The filesystem URL, matching native Node.js modules - url: pathToFileURL(mod.file).toString() - }; - const { - isProduction, - resolve: { dedupe, preserveSymlinks }, - root, - ssr - } = server.config; - const overrideConditions = ssr.resolve?.externalConditions || []; - const resolveOptions = { - mainFields: ["main"], - conditions: [], - overrideConditions: [...overrideConditions, "production", "development"], - extensions: [".js", ".cjs", ".json"], - dedupe, - preserveSymlinks, - isBuild: false, - isProduction, - root, - ssrConfig: ssr, - legacyProxySsrExternalModules: server.config.legacy?.proxySsrExternalModules, - packageCache: server.config.packageCache - }; - const ssrImport = async (dep, metadata) => { - try { - if (dep[0] !== "." && dep[0] !== "/") { - return await nodeImport(dep, mod.file, resolveOptions, metadata); - } - dep = unwrapId$1(dep); - if (!metadata?.isDynamicImport) { - addPendingModuleDependency(url, dep); - if (checkModuleDependencyExists(dep, url)) { - const depSsrModule = moduleGraph.urlToModuleMap.get(dep)?.ssrModule; - if (!depSsrModule) { - throw new Error( - "[vite] The dependency module is not yet fully initialized due to circular dependency. This is a bug in Vite SSR" - ); - } - return depSsrModule; - } - } - return ssrLoadModule(dep, server, fixStacktrace); - } catch (err) { - importErrors.set(err, { importee: dep }); - throw err; - } - }; - const ssrDynamicImport = (dep) => { - if (dep[0] === ".") { - dep = path$n.posix.resolve(path$n.dirname(url), dep); - } - return ssrImport(dep, { isDynamicImport: true }); - }; - function ssrExportAll(sourceModule) { - for (const key in sourceModule) { - if (key !== "default" && key !== "__esModule") { - Object.defineProperty(ssrModule, key, { - enumerable: true, - configurable: true, - get() { - return sourceModule[key]; - } - }); - } - } - } - let sourceMapSuffix = ""; - if (result.map && "version" in result.map) { - const moduleSourceMap = Object.assign({}, result.map, { - mappings: ";".repeat(asyncFunctionDeclarationPaddingLineCount) + result.map.mappings - }); - sourceMapSuffix = ` -//# ${SOURCEMAPPING_URL}=${genSourceMapUrl(moduleSourceMap)}`; - } - try { - const initModule = new AsyncFunction( - ssrModuleExportsKey, - ssrImportMetaKey, - ssrImportKey, - ssrDynamicImportKey, - ssrExportAllKey, - '"use strict";' + result.code + ` -//# sourceURL=${mod.id}${sourceMapSuffix}` - ); - await initModule( - ssrModule, - ssrImportMeta, - ssrImport, - ssrDynamicImport, - ssrExportAll - ); - } catch (e) { - mod.ssrError = e; - const errorData = importErrors.get(e); - if (e.stack && fixStacktrace) { - ssrFixStacktrace(e, moduleGraph); - } - server.config.logger.error( - colors$1.red( - `Error when evaluating SSR module ${url}:` + (errorData?.importee ? ` failed to import "${errorData.importee}"` : "") + ` -|- ${e.stack} -` - ), - { - timestamp: true, - clear: server.config.clearScreen, - error: e - } - ); - throw e; - } finally { - pendingModuleDependencyGraph.delete(url); - } - return Object.freeze(ssrModule); -} -function addPendingModuleDependency(originUrl, depUrl) { - if (pendingModuleDependencyGraph.has(originUrl)) { - pendingModuleDependencyGraph.get(originUrl).add(depUrl); - } else { - pendingModuleDependencyGraph.set(originUrl, /* @__PURE__ */ new Set([depUrl])); - } -} -function checkModuleDependencyExists(originUrl, targetUrl) { - const visited = /* @__PURE__ */ new Set(); - const stack = [originUrl]; - while (stack.length) { - const currentUrl = stack.pop(); - if (currentUrl === targetUrl) { - return true; - } - if (!visited.has(currentUrl)) { - visited.add(currentUrl); - const dependencies = pendingModuleDependencyGraph.get(currentUrl); - if (dependencies) { - for (const depUrl of dependencies) { - if (!visited.has(depUrl)) { - stack.push(depUrl); - } - } - } - } - } - return false; -} -async function nodeImport(id, importer, resolveOptions, metadata) { - let url; - let filePath; - if (id.startsWith("data:") || isExternalUrl(id) || isBuiltin(id)) { - url = id; - } else { - const resolved = tryNodeResolve( - id, - importer, - { ...resolveOptions, tryEsmOnly: true }, - false, - void 0, - true - ); - if (!resolved) { - const err = new Error( - `Cannot find module '${id}' imported from '${importer}'` - ); - err.code = "ERR_MODULE_NOT_FOUND"; - throw err; - } - filePath = resolved.id; - url = pathToFileURL(resolved.id).toString(); - } - const mod = await import(url); - if (resolveOptions.legacyProxySsrExternalModules) { - return proxyESM(mod); - } else if (filePath) { - analyzeImportedModDifference( - mod, - id, - isFilePathESM(filePath, resolveOptions.packageCache) ? "module" : void 0, - metadata - ); - return mod; - } else { - return mod; - } -} -function proxyESM(mod) { - if (isPrimitive(mod)) return { default: mod }; - let defaultExport = "default" in mod ? mod.default : mod; - if (!isPrimitive(defaultExport) && "__esModule" in defaultExport) { - mod = defaultExport; - if ("default" in defaultExport) { - defaultExport = defaultExport.default; - } - } - return new Proxy(mod, { - get(mod2, prop) { - if (prop === "default") return defaultExport; - return mod2[prop] ?? defaultExport?.[prop]; - } - }); -} -function isPrimitive(value) { - return !value || typeof value !== "object" && typeof value !== "function"; -} - -var isWsl$2 = {exports: {}}; - -const fs$3 = require$$0__default; - -let isDocker$2; - -function hasDockerEnv() { - try { - fs$3.statSync('/.dockerenv'); - return true; - } catch (_) { - return false; - } -} - -function hasDockerCGroup() { - try { - return fs$3.readFileSync('/proc/self/cgroup', 'utf8').includes('docker'); - } catch (_) { - return false; - } -} - -var isDocker_1 = () => { - if (isDocker$2 === undefined) { - isDocker$2 = hasDockerEnv() || hasDockerCGroup(); - } - - return isDocker$2; -}; - -const os = require$$2; -const fs$2 = require$$0__default; -const isDocker$1 = isDocker_1; - -const isWsl$1 = () => { - if (process.platform !== 'linux') { - return false; - } - - if (os.release().toLowerCase().includes('microsoft')) { - if (isDocker$1()) { - return false; - } - - return true; - } - - try { - return fs$2.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ? - !isDocker$1() : false; - } catch (_) { - return false; - } -}; - -if (process.env.__IS_WSL_TEST__) { - isWsl$2.exports = isWsl$1; -} else { - isWsl$2.exports = isWsl$1(); -} - -var isWslExports = isWsl$2.exports; - -var defineLazyProp = (object, propertyName, fn) => { - const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true}); - - Object.defineProperty(object, propertyName, { - configurable: true, - enumerable: true, - get() { - const result = fn(); - define(result); - return result; - }, - set(value) { - define(value); - } - }); - - return object; -}; - -const path$3 = require$$0$4; -const childProcess = require$$2$1; -const {promises: fs$1, constants: fsConstants} = require$$0__default; -const isWsl = isWslExports; -const isDocker = isDocker_1; -const defineLazyProperty = defineLazyProp; - -// Path to included `xdg-open`. -const localXdgOpenPath = path$3.join(__dirname, 'xdg-open'); - -const {platform, arch} = process; - -// Podman detection -const hasContainerEnv = () => { - try { - fs$1.statSync('/run/.containerenv'); - return true; - } catch { - return false; - } -}; - -let cachedResult; -function isInsideContainer() { - if (cachedResult === undefined) { - cachedResult = hasContainerEnv() || isDocker(); - } - - return cachedResult; -} - -/** -Get the mount point for fixed drives in WSL. - -@inner -@returns {string} The mount point. -*/ -const getWslDrivesMountPoint = (() => { - // Default value for "root" param - // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config - const defaultMountPoint = '/mnt/'; - - let mountPoint; - - return async function () { - if (mountPoint) { - // Return memoized mount point value - return mountPoint; - } - - const configFilePath = '/etc/wsl.conf'; - - let isConfigFileExists = false; - try { - await fs$1.access(configFilePath, fsConstants.F_OK); - isConfigFileExists = true; - } catch {} - - if (!isConfigFileExists) { - return defaultMountPoint; - } - - const configContent = await fs$1.readFile(configFilePath, {encoding: 'utf8'}); - const configMountPoint = /(?.*)/g.exec(configContent); - - if (!configMountPoint) { - return defaultMountPoint; - } - - mountPoint = configMountPoint.groups.mountPoint.trim(); - mountPoint = mountPoint.endsWith('/') ? mountPoint : `${mountPoint}/`; - - return mountPoint; - }; -})(); - -const pTryEach = async (array, mapper) => { - let latestError; - - for (const item of array) { - try { - return await mapper(item); // eslint-disable-line no-await-in-loop - } catch (error) { - latestError = error; - } - } - - throw latestError; -}; - -const baseOpen = async options => { - options = { - wait: false, - background: false, - newInstance: false, - allowNonzeroExitCode: false, - ...options - }; - - if (Array.isArray(options.app)) { - return pTryEach(options.app, singleApp => baseOpen({ - ...options, - app: singleApp - })); - } - - let {name: app, arguments: appArguments = []} = options.app || {}; - appArguments = [...appArguments]; - - if (Array.isArray(app)) { - return pTryEach(app, appName => baseOpen({ - ...options, - app: { - name: appName, - arguments: appArguments - } - })); - } - - let command; - const cliArguments = []; - const childProcessOptions = {}; - - if (platform === 'darwin') { - command = 'open'; - - if (options.wait) { - cliArguments.push('--wait-apps'); - } - - if (options.background) { - cliArguments.push('--background'); - } - - if (options.newInstance) { - cliArguments.push('--new'); - } - - if (app) { - cliArguments.push('-a', app); - } - } else if (platform === 'win32' || (isWsl && !isInsideContainer() && !app)) { - const mountPoint = await getWslDrivesMountPoint(); - - command = isWsl ? - `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` : - `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`; - - cliArguments.push( - '-NoProfile', - '-NonInteractive', - '–ExecutionPolicy', - 'Bypass', - '-EncodedCommand' - ); - - if (!isWsl) { - childProcessOptions.windowsVerbatimArguments = true; - } - - const encodedArguments = ['Start']; - - if (options.wait) { - encodedArguments.push('-Wait'); - } - - if (app) { - // Double quote with double quotes to ensure the inner quotes are passed through. - // Inner quotes are delimited for PowerShell interpretation with backticks. - encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList'); - if (options.target) { - appArguments.unshift(options.target); - } - } else if (options.target) { - encodedArguments.push(`"${options.target}"`); - } - - if (appArguments.length > 0) { - appArguments = appArguments.map(arg => `"\`"${arg}\`""`); - encodedArguments.push(appArguments.join(',')); - } - - // Using Base64-encoded command, accepted by PowerShell, to allow special characters. - options.target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64'); - } else { - if (app) { - command = app; - } else { - // When bundled by Webpack, there's no actual package file path and no local `xdg-open`. - const isBundled = !__dirname || __dirname === '/'; - - // Check if local `xdg-open` exists and is executable. - let exeLocalXdgOpen = false; - try { - await fs$1.access(localXdgOpenPath, fsConstants.X_OK); - exeLocalXdgOpen = true; - } catch {} - - const useSystemXdgOpen = process.versions.electron || - platform === 'android' || isBundled || !exeLocalXdgOpen; - command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath; - } - - if (appArguments.length > 0) { - cliArguments.push(...appArguments); - } - - if (!options.wait) { - // `xdg-open` will block the process unless stdio is ignored - // and it's detached from the parent even if it's unref'd. - childProcessOptions.stdio = 'ignore'; - childProcessOptions.detached = true; - } - } - - if (options.target) { - cliArguments.push(options.target); - } - - if (platform === 'darwin' && appArguments.length > 0) { - cliArguments.push('--args', ...appArguments); - } - - const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions); - - if (options.wait) { - return new Promise((resolve, reject) => { - subprocess.once('error', reject); - - subprocess.once('close', exitCode => { - if (!options.allowNonzeroExitCode && exitCode > 0) { - reject(new Error(`Exited with code ${exitCode}`)); - return; - } - - resolve(subprocess); - }); - }); - } - - subprocess.unref(); - - return subprocess; -}; - -const open = (target, options) => { - if (typeof target !== 'string') { - throw new TypeError('Expected a `target`'); - } - - return baseOpen({ - ...options, - target - }); -}; - -const openApp = (name, options) => { - if (typeof name !== 'string') { - throw new TypeError('Expected a `name`'); - } - - const {arguments: appArguments = []} = options || {}; - if (appArguments !== undefined && appArguments !== null && !Array.isArray(appArguments)) { - throw new TypeError('Expected `appArguments` as Array type'); - } - - return baseOpen({ - ...options, - app: { - name, - arguments: appArguments - } - }); -}; - -function detectArchBinary(binary) { - if (typeof binary === 'string' || Array.isArray(binary)) { - return binary; - } - - const {[arch]: archBinary} = binary; - - if (!archBinary) { - throw new Error(`${arch} is not supported`); - } - - return archBinary; -} - -function detectPlatformBinary({[platform]: platformBinary}, {wsl}) { - if (wsl && isWsl) { - return detectArchBinary(wsl); - } - - if (!platformBinary) { - throw new Error(`${platform} is not supported`); - } - - return detectArchBinary(platformBinary); -} - -const apps = {}; - -defineLazyProperty(apps, 'chrome', () => detectPlatformBinary({ - darwin: 'google chrome', - win32: 'chrome', - linux: ['google-chrome', 'google-chrome-stable', 'chromium'] -}, { - 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'] - } -})); - -defineLazyProperty(apps, 'firefox', () => detectPlatformBinary({ - darwin: 'firefox', - win32: 'C:\\Program Files\\Mozilla Firefox\\firefox.exe', - linux: 'firefox' -}, { - wsl: '/mnt/c/Program Files/Mozilla Firefox/firefox.exe' -})); - -defineLazyProperty(apps, 'edge', () => detectPlatformBinary({ - darwin: 'microsoft edge', - win32: 'msedge', - linux: ['microsoft-edge', 'microsoft-edge-dev'] -}, { - wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe' -})); - -open.apps = apps; -open.openApp = openApp; - -var open_1 = open; - -var open$1 = /*@__PURE__*/getDefaultExportFromCjs(open_1); - -var crossSpawn = {exports: {}}; - -var windows; -var hasRequiredWindows; - -function requireWindows () { - if (hasRequiredWindows) return windows; - hasRequiredWindows = 1; - windows = isexe; - isexe.sync = sync; - - var fs = require$$0__default; - - function checkPathExt (path, options) { - var pathext = options.pathExt !== undefined ? - options.pathExt : process.env.PATHEXT; - - if (!pathext) { - return true - } - - pathext = pathext.split(';'); - if (pathext.indexOf('') !== -1) { - return true - } - for (var i = 0; i < pathext.length; i++) { - var p = pathext[i].toLowerCase(); - if (p && path.substr(-p.length).toLowerCase() === p) { - return true - } - } - return false - } - - function checkStat (stat, path, options) { - if (!stat.isSymbolicLink() && !stat.isFile()) { - return false - } - return checkPathExt(path, options) - } - - function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, path, options)); - }); - } - - function sync (path, options) { - return checkStat(fs.statSync(path), path, options) - } - return windows; -} - -var mode; -var hasRequiredMode; - -function requireMode () { - if (hasRequiredMode) return mode; - hasRequiredMode = 1; - mode = isexe; - isexe.sync = sync; - - var fs = require$$0__default; - - function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, options)); - }); - } - - function sync (path, options) { - return checkStat(fs.statSync(path), options) - } - - function checkStat (stat, options) { - return stat.isFile() && checkMode(stat, options) - } - - function checkMode (stat, options) { - var mod = stat.mode; - var uid = stat.uid; - var gid = stat.gid; - - var myUid = options.uid !== undefined ? - options.uid : process.getuid && process.getuid(); - var myGid = options.gid !== undefined ? - options.gid : process.getgid && process.getgid(); - - var u = parseInt('100', 8); - var g = parseInt('010', 8); - var o = parseInt('001', 8); - var ug = u | g; - - var ret = (mod & o) || - (mod & g) && gid === myGid || - (mod & u) && uid === myUid || - (mod & ug) && myUid === 0; - - return ret - } - return mode; -} - -var core; -if (process.platform === 'win32' || commonjsGlobal.TESTING_WINDOWS) { - core = requireWindows(); -} else { - core = requireMode(); -} - -var isexe_1 = isexe$1; -isexe$1.sync = sync; - -function isexe$1 (path, options, cb) { - if (typeof options === 'function') { - cb = options; - options = {}; - } - - if (!cb) { - if (typeof Promise !== 'function') { - throw new TypeError('callback not provided') - } - - return new Promise(function (resolve, reject) { - isexe$1(path, options || {}, function (er, is) { - if (er) { - reject(er); - } else { - resolve(is); - } - }); - }) - } - - core(path, options || {}, function (er, is) { - // ignore EACCES because that just means we aren't allowed to run it - if (er) { - if (er.code === 'EACCES' || options && options.ignoreErrors) { - er = null; - is = false; - } - } - cb(er, is); - }); -} - -function sync (path, options) { - // my kingdom for a filtered catch - try { - return core.sync(path, options || {}) - } catch (er) { - if (options && options.ignoreErrors || er.code === 'EACCES') { - return false - } else { - throw er - } - } -} - -const isWindows = process.platform === 'win32' || - process.env.OSTYPE === 'cygwin' || - process.env.OSTYPE === 'msys'; - -const path$2 = require$$0$4; -const COLON = isWindows ? ';' : ':'; -const isexe = isexe_1; - -const getNotFoundError = (cmd) => - Object.assign(new Error(`not found: ${cmd}`), { code: 'ENOENT' }); - -const getPathInfo = (cmd, opt) => { - const colon = opt.colon || COLON; - - // If it has a slash, then we don't bother searching the pathenv. - // just check the file itself, and that's it. - const pathEnv = cmd.match(/\//) || isWindows && cmd.match(/\\/) ? [''] - : ( - [ - // windows always checks the cwd first - ...(isWindows ? [process.cwd()] : []), - ...(opt.path || process.env.PATH || - /* istanbul ignore next: very unusual */ '').split(colon), - ] - ); - const pathExtExe = isWindows - ? opt.pathExt || process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM' - : ''; - const pathExt = isWindows ? pathExtExe.split(colon) : ['']; - - if (isWindows) { - if (cmd.indexOf('.') !== -1 && pathExt[0] !== '') - pathExt.unshift(''); - } - - return { - pathEnv, - pathExt, - pathExtExe, - } -}; - -const which$1 = (cmd, opt, cb) => { - if (typeof opt === 'function') { - cb = opt; - opt = {}; - } - if (!opt) - opt = {}; - - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); - const found = []; - - const step = i => new Promise((resolve, reject) => { - if (i === pathEnv.length) - return opt.all && found.length ? resolve(found) - : reject(getNotFoundError(cmd)) - - const ppRaw = pathEnv[i]; - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; - - const pCmd = path$2.join(pathPart, cmd); - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd - : pCmd; - - resolve(subStep(p, i, 0)); - }); - - const subStep = (p, i, ii) => new Promise((resolve, reject) => { - if (ii === pathExt.length) - return resolve(step(i + 1)) - const ext = pathExt[ii]; - isexe(p + ext, { pathExt: pathExtExe }, (er, is) => { - if (!er && is) { - if (opt.all) - found.push(p + ext); - else - return resolve(p + ext) - } - return resolve(subStep(p, i, ii + 1)) - }); - }); - - return cb ? step(0).then(res => cb(null, res), cb) : step(0) -}; - -const whichSync = (cmd, opt) => { - opt = opt || {}; - - const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt); - const found = []; - - for (let i = 0; i < pathEnv.length; i ++) { - const ppRaw = pathEnv[i]; - const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw; - - const pCmd = path$2.join(pathPart, cmd); - const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd - : pCmd; - - for (let j = 0; j < pathExt.length; j ++) { - const cur = p + pathExt[j]; - try { - const is = isexe.sync(cur, { pathExt: pathExtExe }); - if (is) { - if (opt.all) - found.push(cur); - else - return cur - } - } catch (ex) {} - } - } - - if (opt.all && found.length) - return found - - if (opt.nothrow) - return null - - throw getNotFoundError(cmd) -}; - -var which_1 = which$1; -which$1.sync = whichSync; - -var pathKey$1 = {exports: {}}; - -const pathKey = (options = {}) => { - const environment = options.env || process.env; - const platform = options.platform || process.platform; - - if (platform !== 'win32') { - return 'PATH'; - } - - return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path'; -}; - -pathKey$1.exports = pathKey; -// TODO: Remove this for the next major release -pathKey$1.exports.default = pathKey; - -var pathKeyExports = pathKey$1.exports; - -const path$1 = require$$0$4; -const which = which_1; -const getPathKey = pathKeyExports; - -function resolveCommandAttempt(parsed, withoutPathExt) { - const env = parsed.options.env || process.env; - const cwd = process.cwd(); - const hasCustomCwd = parsed.options.cwd != null; - // Worker threads do not have process.chdir() - const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; - - // If a custom `cwd` was specified, we need to change the process cwd - // because `which` will do stat calls but does not support a custom cwd - if (shouldSwitchCwd) { - try { - process.chdir(parsed.options.cwd); - } catch (err) { - /* Empty */ - } - } - - let resolved; - - try { - resolved = which.sync(parsed.command, { - path: env[getPathKey({ env })], - pathExt: withoutPathExt ? path$1.delimiter : undefined, - }); - } catch (e) { - /* Empty */ - } finally { - if (shouldSwitchCwd) { - process.chdir(cwd); - } - } - - // If we successfully resolved, ensure that an absolute path is returned - // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it - if (resolved) { - resolved = path$1.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); - } - - return resolved; -} - -function resolveCommand$1(parsed) { - return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); -} - -var resolveCommand_1 = resolveCommand$1; - -var _escape = {}; - -// See http://www.robvanderwoude.com/escapechars.php -const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; - -function escapeCommand(arg) { - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); - - return arg; -} - -function escapeArgument(arg, doubleEscapeMetaChars) { - // Convert to string - arg = `${arg}`; - - // Algorithm below is based on https://qntm.org/cmd - - // Sequence of backslashes followed by a double quote: - // double up all the backslashes and escape the double quote - arg = arg.replace(/(\\*)"/g, '$1$1\\"'); - - // Sequence of backslashes followed by the end of the string - // (which will become a double quote later): - // double up all the backslashes - arg = arg.replace(/(\\*)$/, '$1$1'); - - // All other backslashes occur literally - - // Quote the whole thing: - arg = `"${arg}"`; - - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); - - // Double escape meta chars if necessary - if (doubleEscapeMetaChars) { - arg = arg.replace(metaCharsRegExp, '^$1'); - } - - return arg; -} - -_escape.command = escapeCommand; -_escape.argument = escapeArgument; - -var shebangRegex$1 = /^#!(.*)/; - -const shebangRegex = shebangRegex$1; - -var shebangCommand$1 = (string = '') => { - const match = string.match(shebangRegex); - - if (!match) { - return null; - } - - const [path, argument] = match[0].replace(/#! ?/, '').split(' '); - const binary = path.split('/').pop(); - - if (binary === 'env') { - return argument; - } - - return argument ? `${binary} ${argument}` : binary; -}; - -const fs = require$$0__default; -const shebangCommand = shebangCommand$1; - -function readShebang$1(command) { - // Read the first 150 bytes from the file - const size = 150; - const buffer = Buffer.alloc(size); - - let fd; - - try { - fd = fs.openSync(command, 'r'); - fs.readSync(fd, buffer, 0, size, 0); - fs.closeSync(fd); - } catch (e) { /* Empty */ } - - // Attempt to extract shebang (null is returned if not a shebang) - return shebangCommand(buffer.toString()); -} - -var readShebang_1 = readShebang$1; - -const path = require$$0$4; -const resolveCommand = resolveCommand_1; -const escape$1 = _escape; -const readShebang = readShebang_1; - -const isWin$1 = process.platform === 'win32'; -const isExecutableRegExp = /\.(?:com|exe)$/i; -const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; - -function detectShebang(parsed) { - parsed.file = resolveCommand(parsed); - - const shebang = parsed.file && readShebang(parsed.file); - - if (shebang) { - parsed.args.unshift(parsed.file); - parsed.command = shebang; - - return resolveCommand(parsed); - } - - return parsed.file; -} - -function parseNonShell(parsed) { - if (!isWin$1) { - return parsed; - } - - // Detect & add support for shebangs - const commandFile = detectShebang(parsed); - - // We don't need a shell if the command filename is an executable - const needsShell = !isExecutableRegExp.test(commandFile); - - // If a shell is required, use cmd.exe and take care of escaping everything correctly - // Note that `forceShell` is an hidden option used only in tests - if (parsed.options.forceShell || needsShell) { - // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` - // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument - // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, - // we need to double escape them - const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); - - // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) - // This is necessary otherwise it will always fail with ENOENT in those cases - parsed.command = path.normalize(parsed.command); - - // Escape command & arguments - parsed.command = escape$1.command(parsed.command); - parsed.args = parsed.args.map((arg) => escape$1.argument(arg, needsDoubleEscapeMetaChars)); - - const shellCommand = [parsed.command].concat(parsed.args).join(' '); - - parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; - parsed.command = process.env.comspec || 'cmd.exe'; - parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped - } - - return parsed; -} - -function parse$4(command, args, options) { - // Normalize arguments, similar to nodejs - if (args && !Array.isArray(args)) { - options = args; - args = null; - } - - args = args ? args.slice(0) : []; // Clone array to avoid changing the original - options = Object.assign({}, options); // Clone object to avoid changing the original - - // Build our parsed object - const parsed = { - command, - args, - options, - file: undefined, - original: { - command, - args, - }, - }; - - // Delegate further parsing to shell or non-shell - return options.shell ? parsed : parseNonShell(parsed); -} - -var parse_1 = parse$4; - -const isWin = process.platform === 'win32'; - -function notFoundError(original, syscall) { - return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { - code: 'ENOENT', - errno: 'ENOENT', - syscall: `${syscall} ${original.command}`, - path: original.command, - spawnargs: original.args, - }); -} - -function hookChildProcess(cp, parsed) { - if (!isWin) { - return; - } - - const originalEmit = cp.emit; - - cp.emit = function (name, arg1) { - // If emitting "exit" event and exit code is 1, we need to check if - // the command exists and emit an "error" instead - // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 - if (name === 'exit') { - const err = verifyENOENT(arg1, parsed); - - if (err) { - return originalEmit.call(cp, 'error', err); - } - } - - return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params - }; -} - -function verifyENOENT(status, parsed) { - if (isWin && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawn'); - } - - return null; -} - -function verifyENOENTSync(status, parsed) { - if (isWin && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawnSync'); - } - - return null; -} - -var enoent$1 = { - hookChildProcess, - verifyENOENT, - verifyENOENTSync, - notFoundError, -}; - -const cp = require$$2$1; -const parse$3 = parse_1; -const enoent = enoent$1; - -function spawn(command, args, options) { - // Parse the arguments - const parsed = parse$3(command, args, options); - - // Spawn the child process - const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); - - // Hook into child process "exit" event to emit an error if the command - // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - enoent.hookChildProcess(spawned, parsed); - - return spawned; -} - -function spawnSync(command, args, options) { - // Parse the arguments - const parsed = parse$3(command, args, options); - - // Spawn the child process - const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); - - // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); - - return result; -} - -crossSpawn.exports = spawn; -crossSpawn.exports.spawn = spawn; -crossSpawn.exports.sync = spawnSync; - -crossSpawn.exports._parse = parse$3; -crossSpawn.exports._enoent = enoent; - -var crossSpawnExports = crossSpawn.exports; -var spawn$1 = /*@__PURE__*/getDefaultExportFromCjs(crossSpawnExports); - -function openBrowser(url, opt, logger) { - const browser = process.env.BROWSER || ""; - if (browser.toLowerCase().endsWith(".js")) { - executeNodeScript(browser, url, logger); - } else if (browser.toLowerCase() !== "none") { - const browserArgs = process.env.BROWSER_ARGS ? process.env.BROWSER_ARGS.split(" ") : []; - startBrowserProcess(browser, browserArgs, url, logger); - } -} -function executeNodeScript(scriptPath, url, logger) { - const extraArgs = process.argv.slice(2); - const child = spawn$1(process.execPath, [scriptPath, ...extraArgs, url], { - stdio: "inherit" - }); - child.on("close", (code) => { - if (code !== 0) { - logger.error( - colors$1.red( - ` -The script specified as BROWSER environment variable failed. - -${colors$1.cyan( - scriptPath - )} exited with code ${code}.` - ), - { error: null } - ); - } - }); -} -const supportedChromiumBrowsers = [ - "Google Chrome Canary", - "Google Chrome Dev", - "Google Chrome Beta", - "Google Chrome", - "Microsoft Edge", - "Brave Browser", - "Vivaldi", - "Chromium" -]; -async function startBrowserProcess(browser, browserArgs, url, logger) { - const preferredOSXBrowser = browser === "google chrome" ? "Google Chrome" : browser; - const shouldTryOpenChromeWithAppleScript = process.platform === "darwin" && (!preferredOSXBrowser || supportedChromiumBrowsers.includes(preferredOSXBrowser)); - if (shouldTryOpenChromeWithAppleScript) { - try { - const ps = await execAsync("ps cax"); - const openedBrowser = preferredOSXBrowser && ps.includes(preferredOSXBrowser) ? preferredOSXBrowser : supportedChromiumBrowsers.find((b) => ps.includes(b)); - if (openedBrowser) { - await execAsync( - `osascript openChrome.applescript "${encodeURI( - url - )}" "${openedBrowser}"`, - { - cwd: join$2(VITE_PACKAGE_DIR, "bin") - } - ); - return true; - } - } catch (err) { - } - } - if (process.platform === "darwin" && browser === "open") { - browser = void 0; - } - try { - const options = browser ? { app: { name: browser, arguments: browserArgs } } : {}; - new Promise((_, reject) => { - open$1(url, options).then((subprocess) => { - subprocess.on("error", reject); - }).catch(reject); - }).catch((err) => { - logger.error(err.stack || err.message); - }); - return true; - } catch (err) { - return false; - } -} -function execAsync(command, options) { - return new Promise((resolve, reject) => { - exec(command, options, (error, stdout) => { - if (error) { - reject(error); - } else { - resolve(stdout.toString()); - } - }); - }); -} - -function bindCLIShortcuts(server, opts) { - if (!server.httpServer || !process.stdin.isTTY || process.env.CI) { - return; - } - const isDev = isDevServer(server); - if (isDev) { - server._shortcutsOptions = opts; - } - if (opts?.print) { - server.config.logger.info( - colors$1.dim(colors$1.green(" \u279C")) + colors$1.dim(" press ") + colors$1.bold("h + enter") + colors$1.dim(" to show help") - ); - } - const shortcuts = (opts?.customShortcuts ?? []).concat( - isDev ? BASE_DEV_SHORTCUTS : BASE_PREVIEW_SHORTCUTS - ); - let actionRunning = false; - const onInput = async (input) => { - if (actionRunning) return; - if (input === "h") { - const loggedKeys = /* @__PURE__ */ new Set(); - server.config.logger.info("\n Shortcuts"); - for (const shortcut2 of shortcuts) { - if (loggedKeys.has(shortcut2.key)) continue; - loggedKeys.add(shortcut2.key); - if (shortcut2.action == null) continue; - server.config.logger.info( - colors$1.dim(" press ") + colors$1.bold(`${shortcut2.key} + enter`) + colors$1.dim(` to ${shortcut2.description}`) - ); - } - return; - } - const shortcut = shortcuts.find((shortcut2) => shortcut2.key === input); - if (!shortcut || shortcut.action == null) return; - actionRunning = true; - await shortcut.action(server); - actionRunning = false; - }; - const rl = readline.createInterface({ input: process.stdin }); - rl.on("line", onInput); - server.httpServer.on("close", () => rl.close()); -} -const BASE_DEV_SHORTCUTS = [ - { - key: "r", - description: "restart the server", - async action(server) { - await restartServerWithUrls(server); - } - }, - { - key: "u", - description: "show server url", - action(server) { - server.config.logger.info(""); - server.printUrls(); - } - }, - { - key: "o", - description: "open in browser", - action(server) { - server.openBrowser(); - } - }, - { - key: "c", - description: "clear console", - action(server) { - server.config.logger.clearScreen("error"); - } - }, - { - key: "q", - description: "quit", - async action(server) { - try { - await server.close(); - } finally { - process.exit(); - } - } - } -]; -const BASE_PREVIEW_SHORTCUTS = [ - { - key: "o", - description: "open in browser", - action(server) { - const url = server.resolvedUrls?.local[0] ?? server.resolvedUrls?.network[0]; - if (url) { - openBrowser(url, true, server.config.logger); - } else { - server.config.logger.warn("No URL available to open in browser"); - } - } - }, - { - key: "q", - description: "quit", - async action(server) { - try { - await server.close(); - } finally { - process.exit(); - } - } - } -]; - -function getResolvedOutDirs(root, outDir, outputOptions) { - const resolvedOutDir = path$n.resolve(root, outDir); - if (!outputOptions) return /* @__PURE__ */ new Set([resolvedOutDir]); - return new Set( - arraify(outputOptions).map( - ({ dir }) => dir ? path$n.resolve(root, dir) : resolvedOutDir - ) - ); -} -function resolveEmptyOutDir(emptyOutDir, root, outDirs, logger) { - if (emptyOutDir != null) return emptyOutDir; - for (const outDir of outDirs) { - if (!normalizePath$3(outDir).startsWith(withTrailingSlash(root))) { - logger?.warn( - colors$1.yellow( - ` -${colors$1.bold(`(!)`)} outDir ${colors$1.white( - colors$1.dim(outDir) - )} is not inside project root and will not be emptied. -Use --emptyOutDir to override. -` - ) - ); - return false; - } - } - return true; -} -function resolveChokidarOptions(options, resolvedOutDirs, emptyOutDir, cacheDir) { - const { ignored: ignoredList, ...otherOptions } = options ?? {}; - const ignored = [ - "**/.git/**", - "**/node_modules/**", - "**/test-results/**", - // Playwright - glob.escapePath(cacheDir) + "/**", - ...arraify(ignoredList || []) - ]; - if (emptyOutDir) { - ignored.push( - ...[...resolvedOutDirs].map((outDir) => glob.escapePath(outDir) + "/**") - ); - } - const resolvedWatchOptions = { - ignored, - ignoreInitial: true, - ignorePermissionErrors: true, - ...otherOptions - }; - return resolvedWatchOptions; -} -class NoopWatcher extends EventEmitter$4 { - constructor(options) { - super(); - this.options = options; - } - add() { - return this; - } - unwatch() { - return this; - } - getWatched() { - return {}; - } - ref() { - return this; - } - unref() { - return this; - } - async close() { - } -} -function createNoopWatcher(options) { - return new NoopWatcher(options); -} - -async function fetchModule(server, url, importer, options = {}) { - if (url.startsWith("data:") || isBuiltin(url)) { - return { externalize: url, type: "builtin" }; - } - if (isExternalUrl(url)) { - return { externalize: url, type: "network" }; - } - if (url[0] !== "." && url[0] !== "/") { - const { - isProduction, - resolve: { dedupe, preserveSymlinks }, - root, - ssr - } = server.config; - const overrideConditions = ssr.resolve?.externalConditions || []; - const resolveOptions = { - mainFields: ["main"], - conditions: [], - overrideConditions: [...overrideConditions, "production", "development"], - extensions: [".js", ".cjs", ".json"], - dedupe, - preserveSymlinks, - isBuild: false, - isProduction, - root, - ssrConfig: ssr, - packageCache: server.config.packageCache - }; - const resolved = tryNodeResolve( - url, - importer, - { ...resolveOptions, tryEsmOnly: true }, - false, - void 0, - true - ); - if (!resolved) { - const err = new Error( - `Cannot find module '${url}' imported from '${importer}'` - ); - err.code = "ERR_MODULE_NOT_FOUND"; - throw err; - } - const file = pathToFileURL(resolved.id).toString(); - const type = isFilePathESM(resolved.id, server.config.packageCache) ? "module" : "commonjs"; - return { externalize: file, type }; - } - url = unwrapId$1(url); - let result = await server.transformRequest(url, { ssr: true }); - if (!result) { - throw new Error( - `[vite] transform failed for module '${url}'${importer ? ` imported from '${importer}'` : ""}.` - ); - } - const mod = await server.moduleGraph.getModuleByUrl(url, true); - if (!mod) { - throw new Error( - `[vite] cannot find module '${url}' ${importer ? ` imported from '${importer}'` : ""}.` - ); - } - if (options.inlineSourceMap !== false) { - result = inlineSourceMap(mod, result, options.processSourceMap); - } - if (result.code[0] === "#") - result.code = result.code.replace(/^#!.*/, (s) => " ".repeat(s.length)); - return { code: result.code, file: mod.file }; -} -const OTHER_SOURCE_MAP_REGEXP = new RegExp( - `//# ${SOURCEMAPPING_URL}=data:application/json[^,]+base64,([A-Za-z0-9+/=]+)$`, - "gm" -); -function inlineSourceMap(mod, result, processSourceMap) { - const map = result.map; - let code = result.code; - if (!map || !("version" in map) || code.includes(VITE_RUNTIME_SOURCEMAPPING_SOURCE)) - return result; - OTHER_SOURCE_MAP_REGEXP.lastIndex = 0; - if (OTHER_SOURCE_MAP_REGEXP.test(code)) - code = code.replace(OTHER_SOURCE_MAP_REGEXP, ""); - const sourceMap = processSourceMap?.(map) || map; - result.code = `${code.trimEnd()} -//# sourceURL=${mod.id} -${VITE_RUNTIME_SOURCEMAPPING_SOURCE} -//# ${SOURCEMAPPING_URL}=${genSourceMapUrl(sourceMap)} -`; - return result; -} - -function ssrFetchModule(server, id, importer) { - return fetchModule(server, id, importer, { - processSourceMap(map) { - return Object.assign({}, map, { - mappings: ";".repeat(asyncFunctionDeclarationPaddingLineCount) + map.mappings - }); - } - }); -} - -var bufferUtil$1 = {exports: {}}; - -const BINARY_TYPES$2 = ['nodebuffer', 'arraybuffer', 'fragments']; -const hasBlob$1 = typeof Blob !== 'undefined'; - -if (hasBlob$1) BINARY_TYPES$2.push('blob'); - -var constants = { - BINARY_TYPES: BINARY_TYPES$2, - EMPTY_BUFFER: Buffer.alloc(0), - GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', - hasBlob: hasBlob$1, - kForOnEventAttribute: Symbol('kIsForOnEventAttribute'), - kListener: Symbol('kListener'), - kStatusCode: Symbol('status-code'), - kWebSocket: Symbol('websocket'), - NOOP: () => {} -}; - -const { EMPTY_BUFFER: EMPTY_BUFFER$3 } = constants; - -const FastBuffer$2 = Buffer[Symbol.species]; - -/** - * Merges an array of buffers into a new buffer. - * - * @param {Buffer[]} list The array of buffers to concat - * @param {Number} totalLength The total length of buffers in the list - * @return {Buffer} The resulting buffer - * @public - */ -function concat$1(list, totalLength) { - if (list.length === 0) return EMPTY_BUFFER$3; - if (list.length === 1) return list[0]; - - const target = Buffer.allocUnsafe(totalLength); - let offset = 0; - - for (let i = 0; i < list.length; i++) { - const buf = list[i]; - target.set(buf, offset); - offset += buf.length; - } - - if (offset < totalLength) { - return new FastBuffer$2(target.buffer, target.byteOffset, offset); - } - - return target; -} - -/** - * Masks a buffer using the given mask. - * - * @param {Buffer} source The buffer to mask - * @param {Buffer} mask The mask to use - * @param {Buffer} output The buffer where to store the result - * @param {Number} offset The offset at which to start writing - * @param {Number} length The number of bytes to mask. - * @public - */ -function _mask(source, mask, output, offset, length) { - for (let i = 0; i < length; i++) { - output[offset + i] = source[i] ^ mask[i & 3]; - } -} - -/** - * Unmasks a buffer using the given mask. - * - * @param {Buffer} buffer The buffer to unmask - * @param {Buffer} mask The mask to use - * @public - */ -function _unmask(buffer, mask) { - for (let i = 0; i < buffer.length; i++) { - buffer[i] ^= mask[i & 3]; - } -} - -/** - * Converts a buffer to an `ArrayBuffer`. - * - * @param {Buffer} buf The buffer to convert - * @return {ArrayBuffer} Converted buffer - * @public - */ -function toArrayBuffer$1(buf) { - if (buf.length === buf.buffer.byteLength) { - return buf.buffer; - } - - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length); -} - -/** - * Converts `data` to a `Buffer`. - * - * @param {*} data The data to convert - * @return {Buffer} The buffer - * @throws {TypeError} - * @public - */ -function toBuffer$2(data) { - toBuffer$2.readOnly = true; - - if (Buffer.isBuffer(data)) return data; - - let buf; - - if (data instanceof ArrayBuffer) { - buf = new FastBuffer$2(data); - } else if (ArrayBuffer.isView(data)) { - buf = new FastBuffer$2(data.buffer, data.byteOffset, data.byteLength); - } else { - buf = Buffer.from(data); - toBuffer$2.readOnly = false; - } - - return buf; -} - -bufferUtil$1.exports = { - concat: concat$1, - mask: _mask, - toArrayBuffer: toArrayBuffer$1, - toBuffer: toBuffer$2, - unmask: _unmask -}; - -/* istanbul ignore else */ -if (!process.env.WS_NO_BUFFER_UTIL) { - try { - const bufferUtil = require('bufferutil'); - - bufferUtil$1.exports.mask = function (source, mask, output, offset, length) { - if (length < 48) _mask(source, mask, output, offset, length); - else bufferUtil.mask(source, mask, output, offset, length); - }; - - bufferUtil$1.exports.unmask = function (buffer, mask) { - if (buffer.length < 32) _unmask(buffer, mask); - else bufferUtil.unmask(buffer, mask); - }; - } catch (e) { - // Continue regardless of the error. - } -} - -var bufferUtilExports = bufferUtil$1.exports; - -const kDone = Symbol('kDone'); -const kRun = Symbol('kRun'); - -/** - * A very simple job queue with adjustable concurrency. Adapted from - * https://github.com/STRML/async-limiter - */ -let Limiter$1 = class Limiter { - /** - * Creates a new `Limiter`. - * - * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed - * to run concurrently - */ - constructor(concurrency) { - this[kDone] = () => { - this.pending--; - this[kRun](); - }; - this.concurrency = concurrency || Infinity; - this.jobs = []; - this.pending = 0; - } - - /** - * Adds a job to the queue. - * - * @param {Function} job The job to run - * @public - */ - add(job) { - this.jobs.push(job); - this[kRun](); - } - - /** - * Removes a job from the queue and runs it if possible. - * - * @private - */ - [kRun]() { - if (this.pending === this.concurrency) return; - - if (this.jobs.length) { - const job = this.jobs.shift(); - - this.pending++; - job(this[kDone]); - } - } -}; - -var limiter = Limiter$1; - -const zlib = zlib$1; - -const bufferUtil = bufferUtilExports; -const Limiter = limiter; -const { kStatusCode: kStatusCode$2 } = constants; - -const FastBuffer$1 = Buffer[Symbol.species]; -const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); -const kPerMessageDeflate = Symbol('permessage-deflate'); -const kTotalLength = Symbol('total-length'); -const kCallback = Symbol('callback'); -const kBuffers = Symbol('buffers'); -const kError$1 = Symbol('error'); - -// -// We limit zlib concurrency, which prevents severe memory fragmentation -// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 -// and https://github.com/websockets/ws/issues/1202 -// -// Intentionally global; it's the global thread pool that's an issue. -// -let zlibLimiter; - -/** - * permessage-deflate implementation. - */ -let PerMessageDeflate$4 = class PerMessageDeflate { - /** - * Creates a PerMessageDeflate instance. - * - * @param {Object} [options] Configuration options - * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support - * for, or request, a custom client window size - * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/ - * acknowledge disabling of client context takeover - * @param {Number} [options.concurrencyLimit=10] The number of concurrent - * calls to zlib - * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the - * use of a custom server window size - * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept - * disabling of server context takeover - * @param {Number} [options.threshold=1024] Size (in bytes) below which - * messages should not be compressed if context takeover is disabled - * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on - * deflate - * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on - * inflate - * @param {Boolean} [isServer=false] Create the instance in either server or - * client mode - * @param {Number} [maxPayload=0] The maximum allowed message length - */ - constructor(options, isServer, maxPayload) { - this._maxPayload = maxPayload | 0; - this._options = options || {}; - this._threshold = - this._options.threshold !== undefined ? this._options.threshold : 1024; - this._isServer = !!isServer; - this._deflate = null; - this._inflate = null; - - this.params = null; - - if (!zlibLimiter) { - const concurrency = - this._options.concurrencyLimit !== undefined - ? this._options.concurrencyLimit - : 10; - zlibLimiter = new Limiter(concurrency); - } - } - - /** - * @type {String} - */ - static get extensionName() { - return 'permessage-deflate'; - } - - /** - * Create an extension negotiation offer. - * - * @return {Object} Extension parameters - * @public - */ - offer() { - const params = {}; - - if (this._options.serverNoContextTakeover) { - params.server_no_context_takeover = true; - } - if (this._options.clientNoContextTakeover) { - params.client_no_context_takeover = true; - } - if (this._options.serverMaxWindowBits) { - params.server_max_window_bits = this._options.serverMaxWindowBits; - } - if (this._options.clientMaxWindowBits) { - params.client_max_window_bits = this._options.clientMaxWindowBits; - } else if (this._options.clientMaxWindowBits == null) { - params.client_max_window_bits = true; - } - - return params; - } - - /** - * Accept an extension negotiation offer/response. - * - * @param {Array} configurations The extension negotiation offers/reponse - * @return {Object} Accepted configuration - * @public - */ - accept(configurations) { - configurations = this.normalizeParams(configurations); - - this.params = this._isServer - ? this.acceptAsServer(configurations) - : this.acceptAsClient(configurations); - - return this.params; - } - - /** - * Releases all resources used by the extension. - * - * @public - */ - cleanup() { - if (this._inflate) { - this._inflate.close(); - this._inflate = null; - } - - if (this._deflate) { - const callback = this._deflate[kCallback]; - - this._deflate.close(); - this._deflate = null; - - if (callback) { - callback( - new Error( - 'The deflate stream was closed while data was being processed' - ) - ); - } - } - } - - /** - * Accept an extension negotiation offer. - * - * @param {Array} offers The extension negotiation offers - * @return {Object} Accepted configuration - * @private - */ - acceptAsServer(offers) { - const opts = this._options; - const accepted = offers.find((params) => { - if ( - (opts.serverNoContextTakeover === false && - params.server_no_context_takeover) || - (params.server_max_window_bits && - (opts.serverMaxWindowBits === false || - (typeof opts.serverMaxWindowBits === 'number' && - opts.serverMaxWindowBits > params.server_max_window_bits))) || - (typeof opts.clientMaxWindowBits === 'number' && - !params.client_max_window_bits) - ) { - return false; - } - - return true; - }); - - if (!accepted) { - throw new Error('None of the extension offers can be accepted'); - } - - if (opts.serverNoContextTakeover) { - accepted.server_no_context_takeover = true; - } - if (opts.clientNoContextTakeover) { - accepted.client_no_context_takeover = true; - } - if (typeof opts.serverMaxWindowBits === 'number') { - accepted.server_max_window_bits = opts.serverMaxWindowBits; - } - if (typeof opts.clientMaxWindowBits === 'number') { - accepted.client_max_window_bits = opts.clientMaxWindowBits; - } else if ( - accepted.client_max_window_bits === true || - opts.clientMaxWindowBits === false - ) { - delete accepted.client_max_window_bits; - } - - return accepted; - } - - /** - * Accept the extension negotiation response. - * - * @param {Array} response The extension negotiation response - * @return {Object} Accepted configuration - * @private - */ - acceptAsClient(response) { - const params = response[0]; - - if ( - this._options.clientNoContextTakeover === false && - params.client_no_context_takeover - ) { - throw new Error('Unexpected parameter "client_no_context_takeover"'); - } - - if (!params.client_max_window_bits) { - if (typeof this._options.clientMaxWindowBits === 'number') { - params.client_max_window_bits = this._options.clientMaxWindowBits; - } - } else if ( - this._options.clientMaxWindowBits === false || - (typeof this._options.clientMaxWindowBits === 'number' && - params.client_max_window_bits > this._options.clientMaxWindowBits) - ) { - throw new Error( - 'Unexpected or invalid parameter "client_max_window_bits"' - ); - } - - return params; - } - - /** - * Normalize parameters. - * - * @param {Array} configurations The extension negotiation offers/reponse - * @return {Array} The offers/response with normalized parameters - * @private - */ - normalizeParams(configurations) { - configurations.forEach((params) => { - Object.keys(params).forEach((key) => { - let value = params[key]; - - if (value.length > 1) { - throw new Error(`Parameter "${key}" must have only a single value`); - } - - value = value[0]; - - if (key === 'client_max_window_bits') { - if (value !== true) { - const num = +value; - if (!Number.isInteger(num) || num < 8 || num > 15) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - value = num; - } else if (!this._isServer) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - } else if (key === 'server_max_window_bits') { - const num = +value; - if (!Number.isInteger(num) || num < 8 || num > 15) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - value = num; - } else if ( - key === 'client_no_context_takeover' || - key === 'server_no_context_takeover' - ) { - if (value !== true) { - throw new TypeError( - `Invalid value for parameter "${key}": ${value}` - ); - } - } else { - throw new Error(`Unknown parameter "${key}"`); - } - - params[key] = value; - }); - }); - - return configurations; - } - - /** - * Decompress data. Concurrency limited. - * - * @param {Buffer} data Compressed data - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @public - */ - decompress(data, fin, callback) { - zlibLimiter.add((done) => { - this._decompress(data, fin, (err, result) => { - done(); - callback(err, result); - }); - }); - } - - /** - * Compress data. Concurrency limited. - * - * @param {(Buffer|String)} data Data to compress - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @public - */ - compress(data, fin, callback) { - zlibLimiter.add((done) => { - this._compress(data, fin, (err, result) => { - done(); - callback(err, result); - }); - }); - } - - /** - * Decompress data. - * - * @param {Buffer} data Compressed data - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @private - */ - _decompress(data, fin, callback) { - const endpoint = this._isServer ? 'client' : 'server'; - - if (!this._inflate) { - const key = `${endpoint}_max_window_bits`; - const windowBits = - typeof this.params[key] !== 'number' - ? zlib.Z_DEFAULT_WINDOWBITS - : this.params[key]; - - this._inflate = zlib.createInflateRaw({ - ...this._options.zlibInflateOptions, - windowBits - }); - this._inflate[kPerMessageDeflate] = this; - this._inflate[kTotalLength] = 0; - this._inflate[kBuffers] = []; - this._inflate.on('error', inflateOnError); - this._inflate.on('data', inflateOnData); - } - - this._inflate[kCallback] = callback; - - this._inflate.write(data); - if (fin) this._inflate.write(TRAILER); - - this._inflate.flush(() => { - const err = this._inflate[kError$1]; - - if (err) { - this._inflate.close(); - this._inflate = null; - callback(err); - return; - } - - const data = bufferUtil.concat( - this._inflate[kBuffers], - this._inflate[kTotalLength] - ); - - if (this._inflate._readableState.endEmitted) { - this._inflate.close(); - this._inflate = null; - } else { - this._inflate[kTotalLength] = 0; - this._inflate[kBuffers] = []; - - if (fin && this.params[`${endpoint}_no_context_takeover`]) { - this._inflate.reset(); - } - } - - callback(null, data); - }); - } - - /** - * Compress data. - * - * @param {(Buffer|String)} data Data to compress - * @param {Boolean} fin Specifies whether or not this is the last fragment - * @param {Function} callback Callback - * @private - */ - _compress(data, fin, callback) { - const endpoint = this._isServer ? 'server' : 'client'; - - if (!this._deflate) { - const key = `${endpoint}_max_window_bits`; - const windowBits = - typeof this.params[key] !== 'number' - ? zlib.Z_DEFAULT_WINDOWBITS - : this.params[key]; - - this._deflate = zlib.createDeflateRaw({ - ...this._options.zlibDeflateOptions, - windowBits - }); - - this._deflate[kTotalLength] = 0; - this._deflate[kBuffers] = []; - - this._deflate.on('data', deflateOnData); - } - - this._deflate[kCallback] = callback; - - this._deflate.write(data); - this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { - if (!this._deflate) { - // - // The deflate stream was closed while data was being processed. - // - return; - } - - let data = bufferUtil.concat( - this._deflate[kBuffers], - this._deflate[kTotalLength] - ); - - if (fin) { - data = new FastBuffer$1(data.buffer, data.byteOffset, data.length - 4); - } - - // - // Ensure that the callback will not be called again in - // `PerMessageDeflate#cleanup()`. - // - this._deflate[kCallback] = null; - - this._deflate[kTotalLength] = 0; - this._deflate[kBuffers] = []; - - if (fin && this.params[`${endpoint}_no_context_takeover`]) { - this._deflate.reset(); - } - - callback(null, data); - }); - } -}; - -var permessageDeflate = PerMessageDeflate$4; - -/** - * The listener of the `zlib.DeflateRaw` stream `'data'` event. - * - * @param {Buffer} chunk A chunk of data - * @private - */ -function deflateOnData(chunk) { - this[kBuffers].push(chunk); - this[kTotalLength] += chunk.length; -} - -/** - * The listener of the `zlib.InflateRaw` stream `'data'` event. - * - * @param {Buffer} chunk A chunk of data - * @private - */ -function inflateOnData(chunk) { - this[kTotalLength] += chunk.length; - - if ( - this[kPerMessageDeflate]._maxPayload < 1 || - this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload - ) { - this[kBuffers].push(chunk); - return; - } - - this[kError$1] = new RangeError('Max payload size exceeded'); - this[kError$1].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'; - this[kError$1][kStatusCode$2] = 1009; - this.removeListener('data', inflateOnData); - this.reset(); -} - -/** - * The listener of the `zlib.InflateRaw` stream `'error'` event. - * - * @param {Error} err The emitted error - * @private - */ -function inflateOnError(err) { - // - // There is no need to call `Zlib#close()` as the handle is automatically - // closed when an error is emitted. - // - this[kPerMessageDeflate]._inflate = null; - err[kStatusCode$2] = 1007; - this[kCallback](err); -} - -var validation = {exports: {}}; - -const { isUtf8 } = require$$0$a; - -const { hasBlob } = constants; - -// -// Allowed token characters: -// -// '!', '#', '$', '%', '&', ''', '*', '+', '-', -// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' -// -// tokenChars[32] === 0 // ' ' -// tokenChars[33] === 1 // '!' -// tokenChars[34] === 0 // '"' -// ... -// -// prettier-ignore -const tokenChars$2 = [ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 - 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 - 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 -]; - -/** - * Checks if a status code is allowed in a close frame. - * - * @param {Number} code The status code - * @return {Boolean} `true` if the status code is valid, else `false` - * @public - */ -function isValidStatusCode$2(code) { - return ( - (code >= 1000 && - code <= 1014 && - code !== 1004 && - code !== 1005 && - code !== 1006) || - (code >= 3000 && code <= 4999) - ); -} - -/** - * Checks if a given buffer contains only correct UTF-8. - * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by - * Markus Kuhn. - * - * @param {Buffer} buf The buffer to check - * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false` - * @public - */ -function _isValidUTF8(buf) { - const len = buf.length; - let i = 0; - - while (i < len) { - if ((buf[i] & 0x80) === 0) { - // 0xxxxxxx - i++; - } else if ((buf[i] & 0xe0) === 0xc0) { - // 110xxxxx 10xxxxxx - if ( - i + 1 === len || - (buf[i + 1] & 0xc0) !== 0x80 || - (buf[i] & 0xfe) === 0xc0 // Overlong - ) { - return false; - } - - i += 2; - } else if ((buf[i] & 0xf0) === 0xe0) { - // 1110xxxx 10xxxxxx 10xxxxxx - if ( - i + 2 >= len || - (buf[i + 1] & 0xc0) !== 0x80 || - (buf[i + 2] & 0xc0) !== 0x80 || - (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong - (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF) - ) { - return false; - } - - i += 3; - } else if ((buf[i] & 0xf8) === 0xf0) { - // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - if ( - i + 3 >= len || - (buf[i + 1] & 0xc0) !== 0x80 || - (buf[i + 2] & 0xc0) !== 0x80 || - (buf[i + 3] & 0xc0) !== 0x80 || - (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong - (buf[i] === 0xf4 && buf[i + 1] > 0x8f) || - buf[i] > 0xf4 // > U+10FFFF - ) { - return false; - } - - i += 4; - } else { - return false; - } - } - - return true; -} - -/** - * Determines whether a value is a `Blob`. - * - * @param {*} value The value to be tested - * @return {Boolean} `true` if `value` is a `Blob`, else `false` - * @private - */ -function isBlob$2(value) { - return ( - hasBlob && - typeof value === 'object' && - typeof value.arrayBuffer === 'function' && - typeof value.type === 'string' && - typeof value.stream === 'function' && - (value[Symbol.toStringTag] === 'Blob' || - value[Symbol.toStringTag] === 'File') - ); -} - -validation.exports = { - isBlob: isBlob$2, - isValidStatusCode: isValidStatusCode$2, - isValidUTF8: _isValidUTF8, - tokenChars: tokenChars$2 -}; - -if (isUtf8) { - validation.exports.isValidUTF8 = function (buf) { - return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf); - }; -} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) { - try { - const isValidUTF8 = require('utf-8-validate'); - - validation.exports.isValidUTF8 = function (buf) { - return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf); - }; - } catch (e) { - // Continue regardless of the error. - } -} - -var validationExports = validation.exports; - -const { Writable: Writable$1 } = require$$0$6; - -const PerMessageDeflate$3 = permessageDeflate; -const { - BINARY_TYPES: BINARY_TYPES$1, - EMPTY_BUFFER: EMPTY_BUFFER$2, - kStatusCode: kStatusCode$1, - kWebSocket: kWebSocket$3 -} = constants; -const { concat, toArrayBuffer, unmask } = bufferUtilExports; -const { isValidStatusCode: isValidStatusCode$1, isValidUTF8 } = validationExports; - -const FastBuffer = Buffer[Symbol.species]; - -const GET_INFO = 0; -const GET_PAYLOAD_LENGTH_16 = 1; -const GET_PAYLOAD_LENGTH_64 = 2; -const GET_MASK = 3; -const GET_DATA = 4; -const INFLATING = 5; -const DEFER_EVENT = 6; - -/** - * HyBi Receiver implementation. - * - * @extends Writable - */ -let Receiver$1 = class Receiver extends Writable$1 { - /** - * Creates a Receiver instance. - * - * @param {Object} [options] Options object - * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether - * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted - * multiple times in the same tick - * @param {String} [options.binaryType=nodebuffer] The type for binary data - * @param {Object} [options.extensions] An object containing the negotiated - * extensions - * @param {Boolean} [options.isServer=false] Specifies whether to operate in - * client or server mode - * @param {Number} [options.maxPayload=0] The maximum allowed message length - * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or - * not to skip UTF-8 validation for text and close messages - */ - constructor(options = {}) { - super(); - - this._allowSynchronousEvents = - options.allowSynchronousEvents !== undefined - ? options.allowSynchronousEvents - : true; - this._binaryType = options.binaryType || BINARY_TYPES$1[0]; - this._extensions = options.extensions || {}; - this._isServer = !!options.isServer; - this._maxPayload = options.maxPayload | 0; - this._skipUTF8Validation = !!options.skipUTF8Validation; - this[kWebSocket$3] = undefined; - - this._bufferedBytes = 0; - this._buffers = []; - - this._compressed = false; - this._payloadLength = 0; - this._mask = undefined; - this._fragmented = 0; - this._masked = false; - this._fin = false; - this._opcode = 0; - - this._totalPayloadLength = 0; - this._messageLength = 0; - this._fragments = []; - - this._errored = false; - this._loop = false; - this._state = GET_INFO; - } - - /** - * Implements `Writable.prototype._write()`. - * - * @param {Buffer} chunk The chunk of data to write - * @param {String} encoding The character encoding of `chunk` - * @param {Function} cb Callback - * @private - */ - _write(chunk, encoding, cb) { - if (this._opcode === 0x08 && this._state == GET_INFO) return cb(); - - this._bufferedBytes += chunk.length; - this._buffers.push(chunk); - this.startLoop(cb); - } - - /** - * Consumes `n` bytes from the buffered data. - * - * @param {Number} n The number of bytes to consume - * @return {Buffer} The consumed bytes - * @private - */ - consume(n) { - this._bufferedBytes -= n; - - if (n === this._buffers[0].length) return this._buffers.shift(); - - if (n < this._buffers[0].length) { - const buf = this._buffers[0]; - this._buffers[0] = new FastBuffer( - buf.buffer, - buf.byteOffset + n, - buf.length - n - ); - - return new FastBuffer(buf.buffer, buf.byteOffset, n); - } - - const dst = Buffer.allocUnsafe(n); - - do { - const buf = this._buffers[0]; - const offset = dst.length - n; - - if (n >= buf.length) { - dst.set(this._buffers.shift(), offset); - } else { - dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset); - this._buffers[0] = new FastBuffer( - buf.buffer, - buf.byteOffset + n, - buf.length - n - ); - } - - n -= buf.length; - } while (n > 0); - - return dst; - } - - /** - * Starts the parsing loop. - * - * @param {Function} cb Callback - * @private - */ - startLoop(cb) { - this._loop = true; - - do { - switch (this._state) { - case GET_INFO: - this.getInfo(cb); - break; - case GET_PAYLOAD_LENGTH_16: - this.getPayloadLength16(cb); - break; - case GET_PAYLOAD_LENGTH_64: - this.getPayloadLength64(cb); - break; - case GET_MASK: - this.getMask(); - break; - case GET_DATA: - this.getData(cb); - break; - case INFLATING: - case DEFER_EVENT: - this._loop = false; - return; - } - } while (this._loop); - - if (!this._errored) cb(); - } - - /** - * Reads the first two bytes of a frame. - * - * @param {Function} cb Callback - * @private - */ - getInfo(cb) { - if (this._bufferedBytes < 2) { - this._loop = false; - return; - } - - const buf = this.consume(2); - - if ((buf[0] & 0x30) !== 0x00) { - const error = this.createError( - RangeError, - 'RSV2 and RSV3 must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_RSV_2_3' - ); - - cb(error); - return; - } - - const compressed = (buf[0] & 0x40) === 0x40; - - if (compressed && !this._extensions[PerMessageDeflate$3.extensionName]) { - const error = this.createError( - RangeError, - 'RSV1 must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_RSV_1' - ); - - cb(error); - return; - } - - this._fin = (buf[0] & 0x80) === 0x80; - this._opcode = buf[0] & 0x0f; - this._payloadLength = buf[1] & 0x7f; - - if (this._opcode === 0x00) { - if (compressed) { - const error = this.createError( - RangeError, - 'RSV1 must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_RSV_1' - ); - - cb(error); - return; - } - - if (!this._fragmented) { - const error = this.createError( - RangeError, - 'invalid opcode 0', - true, - 1002, - 'WS_ERR_INVALID_OPCODE' - ); - - cb(error); - return; - } - - this._opcode = this._fragmented; - } else if (this._opcode === 0x01 || this._opcode === 0x02) { - if (this._fragmented) { - const error = this.createError( - RangeError, - `invalid opcode ${this._opcode}`, - true, - 1002, - 'WS_ERR_INVALID_OPCODE' - ); - - cb(error); - return; - } - - this._compressed = compressed; - } else if (this._opcode > 0x07 && this._opcode < 0x0b) { - if (!this._fin) { - const error = this.createError( - RangeError, - 'FIN must be set', - true, - 1002, - 'WS_ERR_EXPECTED_FIN' - ); - - cb(error); - return; - } - - if (compressed) { - const error = this.createError( - RangeError, - 'RSV1 must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_RSV_1' - ); - - cb(error); - return; - } - - if ( - this._payloadLength > 0x7d || - (this._opcode === 0x08 && this._payloadLength === 1) - ) { - const error = this.createError( - RangeError, - `invalid payload length ${this._payloadLength}`, - true, - 1002, - 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH' - ); - - cb(error); - return; - } - } else { - const error = this.createError( - RangeError, - `invalid opcode ${this._opcode}`, - true, - 1002, - 'WS_ERR_INVALID_OPCODE' - ); - - cb(error); - return; - } - - if (!this._fin && !this._fragmented) this._fragmented = this._opcode; - this._masked = (buf[1] & 0x80) === 0x80; - - if (this._isServer) { - if (!this._masked) { - const error = this.createError( - RangeError, - 'MASK must be set', - true, - 1002, - 'WS_ERR_EXPECTED_MASK' - ); - - cb(error); - return; - } - } else if (this._masked) { - const error = this.createError( - RangeError, - 'MASK must be clear', - true, - 1002, - 'WS_ERR_UNEXPECTED_MASK' - ); - - cb(error); - return; - } - - if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; - else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; - else this.haveLength(cb); - } - - /** - * Gets extended payload length (7+16). - * - * @param {Function} cb Callback - * @private - */ - getPayloadLength16(cb) { - if (this._bufferedBytes < 2) { - this._loop = false; - return; - } - - this._payloadLength = this.consume(2).readUInt16BE(0); - this.haveLength(cb); - } - - /** - * Gets extended payload length (7+64). - * - * @param {Function} cb Callback - * @private - */ - getPayloadLength64(cb) { - if (this._bufferedBytes < 8) { - this._loop = false; - return; - } - - const buf = this.consume(8); - const num = buf.readUInt32BE(0); - - // - // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned - // if payload length is greater than this number. - // - if (num > Math.pow(2, 53 - 32) - 1) { - const error = this.createError( - RangeError, - 'Unsupported WebSocket frame: payload length > 2^53 - 1', - false, - 1009, - 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH' - ); - - cb(error); - return; - } - - this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4); - this.haveLength(cb); - } - - /** - * Payload length has been read. - * - * @param {Function} cb Callback - * @private - */ - haveLength(cb) { - if (this._payloadLength && this._opcode < 0x08) { - this._totalPayloadLength += this._payloadLength; - if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { - const error = this.createError( - RangeError, - 'Max payload size exceeded', - false, - 1009, - 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' - ); - - cb(error); - return; - } - } - - if (this._masked) this._state = GET_MASK; - else this._state = GET_DATA; - } - - /** - * Reads mask bytes. - * - * @private - */ - getMask() { - if (this._bufferedBytes < 4) { - this._loop = false; - return; - } - - this._mask = this.consume(4); - this._state = GET_DATA; - } - - /** - * Reads data bytes. - * - * @param {Function} cb Callback - * @private - */ - getData(cb) { - let data = EMPTY_BUFFER$2; - - if (this._payloadLength) { - if (this._bufferedBytes < this._payloadLength) { - this._loop = false; - return; - } - - data = this.consume(this._payloadLength); - - if ( - this._masked && - (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0 - ) { - unmask(data, this._mask); - } - } - - if (this._opcode > 0x07) { - this.controlMessage(data, cb); - return; - } - - if (this._compressed) { - this._state = INFLATING; - this.decompress(data, cb); - return; - } - - if (data.length) { - // - // This message is not compressed so its length is the sum of the payload - // length of all fragments. - // - this._messageLength = this._totalPayloadLength; - this._fragments.push(data); - } - - this.dataMessage(cb); - } - - /** - * Decompresses data. - * - * @param {Buffer} data Compressed data - * @param {Function} cb Callback - * @private - */ - decompress(data, cb) { - const perMessageDeflate = this._extensions[PerMessageDeflate$3.extensionName]; - - perMessageDeflate.decompress(data, this._fin, (err, buf) => { - if (err) return cb(err); - - if (buf.length) { - this._messageLength += buf.length; - if (this._messageLength > this._maxPayload && this._maxPayload > 0) { - const error = this.createError( - RangeError, - 'Max payload size exceeded', - false, - 1009, - 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH' - ); - - cb(error); - return; - } - - this._fragments.push(buf); - } - - this.dataMessage(cb); - if (this._state === GET_INFO) this.startLoop(cb); - }); - } - - /** - * Handles a data message. - * - * @param {Function} cb Callback - * @private - */ - dataMessage(cb) { - if (!this._fin) { - this._state = GET_INFO; - return; - } - - const messageLength = this._messageLength; - const fragments = this._fragments; - - this._totalPayloadLength = 0; - this._messageLength = 0; - this._fragmented = 0; - this._fragments = []; - - if (this._opcode === 2) { - let data; - - if (this._binaryType === 'nodebuffer') { - data = concat(fragments, messageLength); - } else if (this._binaryType === 'arraybuffer') { - data = toArrayBuffer(concat(fragments, messageLength)); - } else if (this._binaryType === 'blob') { - data = new Blob(fragments); - } else { - data = fragments; - } - - if (this._allowSynchronousEvents) { - this.emit('message', data, true); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit('message', data, true); - this._state = GET_INFO; - this.startLoop(cb); - }); - } - } else { - const buf = concat(fragments, messageLength); - - if (!this._skipUTF8Validation && !isValidUTF8(buf)) { - const error = this.createError( - Error, - 'invalid UTF-8 sequence', - true, - 1007, - 'WS_ERR_INVALID_UTF8' - ); - - cb(error); - return; - } - - if (this._state === INFLATING || this._allowSynchronousEvents) { - this.emit('message', buf, false); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit('message', buf, false); - this._state = GET_INFO; - this.startLoop(cb); - }); - } - } - } - - /** - * Handles a control message. - * - * @param {Buffer} data Data to handle - * @return {(Error|RangeError|undefined)} A possible error - * @private - */ - controlMessage(data, cb) { - if (this._opcode === 0x08) { - if (data.length === 0) { - this._loop = false; - this.emit('conclude', 1005, EMPTY_BUFFER$2); - this.end(); - } else { - const code = data.readUInt16BE(0); - - if (!isValidStatusCode$1(code)) { - const error = this.createError( - RangeError, - `invalid status code ${code}`, - true, - 1002, - 'WS_ERR_INVALID_CLOSE_CODE' - ); - - cb(error); - return; - } - - const buf = new FastBuffer( - data.buffer, - data.byteOffset + 2, - data.length - 2 - ); - - if (!this._skipUTF8Validation && !isValidUTF8(buf)) { - const error = this.createError( - Error, - 'invalid UTF-8 sequence', - true, - 1007, - 'WS_ERR_INVALID_UTF8' - ); - - cb(error); - return; - } - - this._loop = false; - this.emit('conclude', code, buf); - this.end(); - } - - this._state = GET_INFO; - return; - } - - if (this._allowSynchronousEvents) { - this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); - this._state = GET_INFO; - } else { - this._state = DEFER_EVENT; - setImmediate(() => { - this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data); - this._state = GET_INFO; - this.startLoop(cb); - }); - } - } - - /** - * Builds an error object. - * - * @param {function(new:Error|RangeError)} ErrorCtor The error constructor - * @param {String} message The error message - * @param {Boolean} prefix Specifies whether or not to add a default prefix to - * `message` - * @param {Number} statusCode The status code - * @param {String} errorCode The exposed error code - * @return {(Error|RangeError)} The error - * @private - */ - createError(ErrorCtor, message, prefix, statusCode, errorCode) { - this._loop = false; - this._errored = true; - - const err = new ErrorCtor( - prefix ? `Invalid WebSocket frame: ${message}` : message - ); - - Error.captureStackTrace(err, this.createError); - err.code = errorCode; - err[kStatusCode$1] = statusCode; - return err; - } -}; - -var receiver = Receiver$1; - -/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex" }] */ -const { randomFillSync } = require$$3$1; - -const PerMessageDeflate$2 = permessageDeflate; -const { EMPTY_BUFFER: EMPTY_BUFFER$1, kWebSocket: kWebSocket$2, NOOP: NOOP$2 } = constants; -const { isBlob: isBlob$1, isValidStatusCode } = validationExports; -const { mask: applyMask, toBuffer: toBuffer$1 } = bufferUtilExports; - -const kByteLength = Symbol('kByteLength'); -const maskBuffer = Buffer.alloc(4); -const RANDOM_POOL_SIZE = 8 * 1024; -let randomPool; -let randomPoolPointer = RANDOM_POOL_SIZE; - -const DEFAULT = 0; -const DEFLATING = 1; -const GET_BLOB_DATA = 2; - -/** - * HyBi Sender implementation. - */ -let Sender$1 = class Sender { - /** - * Creates a Sender instance. - * - * @param {Duplex} socket The connection socket - * @param {Object} [extensions] An object containing the negotiated extensions - * @param {Function} [generateMask] The function used to generate the masking - * key - */ - constructor(socket, extensions, generateMask) { - this._extensions = extensions || {}; - - if (generateMask) { - this._generateMask = generateMask; - this._maskBuffer = Buffer.alloc(4); - } - - this._socket = socket; - - this._firstFragment = true; - this._compress = false; - - this._bufferedBytes = 0; - this._queue = []; - this._state = DEFAULT; - this.onerror = NOOP$2; - this[kWebSocket$2] = undefined; - } - - /** - * Frames a piece of data according to the HyBi WebSocket protocol. - * - * @param {(Buffer|String)} data The data to frame - * @param {Object} options Options object - * @param {Boolean} [options.fin=false] Specifies whether or not to set the - * FIN bit - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Buffer} [options.maskBuffer] The buffer used to store the masking - * key - * @param {Number} options.opcode The opcode - * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be - * modified - * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the - * RSV1 bit - * @return {(Buffer|String)[]} The framed data - * @public - */ - static frame(data, options) { - let mask; - let merge = false; - let offset = 2; - let skipMasking = false; - - if (options.mask) { - mask = options.maskBuffer || maskBuffer; - - if (options.generateMask) { - options.generateMask(mask); - } else { - if (randomPoolPointer === RANDOM_POOL_SIZE) { - /* istanbul ignore else */ - if (randomPool === undefined) { - // - // This is lazily initialized because server-sent frames must not - // be masked so it may never be used. - // - randomPool = Buffer.alloc(RANDOM_POOL_SIZE); - } - - randomFillSync(randomPool, 0, RANDOM_POOL_SIZE); - randomPoolPointer = 0; - } - - mask[0] = randomPool[randomPoolPointer++]; - mask[1] = randomPool[randomPoolPointer++]; - mask[2] = randomPool[randomPoolPointer++]; - mask[3] = randomPool[randomPoolPointer++]; - } - - skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0; - offset = 6; - } - - let dataLength; - - if (typeof data === 'string') { - if ( - (!options.mask || skipMasking) && - options[kByteLength] !== undefined - ) { - dataLength = options[kByteLength]; - } else { - data = Buffer.from(data); - dataLength = data.length; - } - } else { - dataLength = data.length; - merge = options.mask && options.readOnly && !skipMasking; - } - - let payloadLength = dataLength; - - if (dataLength >= 65536) { - offset += 8; - payloadLength = 127; - } else if (dataLength > 125) { - offset += 2; - payloadLength = 126; - } - - const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset); - - target[0] = options.fin ? options.opcode | 0x80 : options.opcode; - if (options.rsv1) target[0] |= 0x40; - - target[1] = payloadLength; - - if (payloadLength === 126) { - target.writeUInt16BE(dataLength, 2); - } else if (payloadLength === 127) { - target[2] = target[3] = 0; - target.writeUIntBE(dataLength, 4, 6); - } - - if (!options.mask) return [target, data]; - - target[1] |= 0x80; - target[offset - 4] = mask[0]; - target[offset - 3] = mask[1]; - target[offset - 2] = mask[2]; - target[offset - 1] = mask[3]; - - if (skipMasking) return [target, data]; - - if (merge) { - applyMask(data, mask, target, offset, dataLength); - return [target]; - } - - applyMask(data, mask, data, 0, dataLength); - return [target, data]; - } - - /** - * Sends a close message to the other peer. - * - * @param {Number} [code] The status code component of the body - * @param {(String|Buffer)} [data] The message component of the body - * @param {Boolean} [mask=false] Specifies whether or not to mask the message - * @param {Function} [cb] Callback - * @public - */ - close(code, data, mask, cb) { - let buf; - - if (code === undefined) { - buf = EMPTY_BUFFER$1; - } else if (typeof code !== 'number' || !isValidStatusCode(code)) { - throw new TypeError('First argument must be a valid error code number'); - } else if (data === undefined || !data.length) { - buf = Buffer.allocUnsafe(2); - buf.writeUInt16BE(code, 0); - } else { - const length = Buffer.byteLength(data); - - if (length > 123) { - throw new RangeError('The message must not be greater than 123 bytes'); - } - - buf = Buffer.allocUnsafe(2 + length); - buf.writeUInt16BE(code, 0); - - if (typeof data === 'string') { - buf.write(data, 2); - } else { - buf.set(data, 2); - } - } - - const options = { - [kByteLength]: buf.length, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 0x08, - readOnly: false, - rsv1: false - }; - - if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, buf, false, options, cb]); - } else { - this.sendFrame(Sender.frame(buf, options), cb); - } - } - - /** - * Sends a ping message to the other peer. - * - * @param {*} data The message to send - * @param {Boolean} [mask=false] Specifies whether or not to mask `data` - * @param {Function} [cb] Callback - * @public - */ - ping(data, mask, cb) { - let byteLength; - let readOnly; - - if (typeof data === 'string') { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else if (isBlob$1(data)) { - byteLength = data.size; - readOnly = false; - } else { - data = toBuffer$1(data); - byteLength = data.length; - readOnly = toBuffer$1.readOnly; - } - - if (byteLength > 125) { - throw new RangeError('The data size must not be greater than 125 bytes'); - } - - const options = { - [kByteLength]: byteLength, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 0x09, - readOnly, - rsv1: false - }; - - if (isBlob$1(data)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data, false, options, cb]); - } else { - this.getBlobData(data, false, options, cb); - } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data, false, options, cb]); - } else { - this.sendFrame(Sender.frame(data, options), cb); - } - } - - /** - * Sends a pong message to the other peer. - * - * @param {*} data The message to send - * @param {Boolean} [mask=false] Specifies whether or not to mask `data` - * @param {Function} [cb] Callback - * @public - */ - pong(data, mask, cb) { - let byteLength; - let readOnly; - - if (typeof data === 'string') { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else if (isBlob$1(data)) { - byteLength = data.size; - readOnly = false; - } else { - data = toBuffer$1(data); - byteLength = data.length; - readOnly = toBuffer$1.readOnly; - } - - if (byteLength > 125) { - throw new RangeError('The data size must not be greater than 125 bytes'); - } - - const options = { - [kByteLength]: byteLength, - fin: true, - generateMask: this._generateMask, - mask, - maskBuffer: this._maskBuffer, - opcode: 0x0a, - readOnly, - rsv1: false - }; - - if (isBlob$1(data)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data, false, options, cb]); - } else { - this.getBlobData(data, false, options, cb); - } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data, false, options, cb]); - } else { - this.sendFrame(Sender.frame(data, options), cb); - } - } - - /** - * Sends a data message to the other peer. - * - * @param {*} data The message to send - * @param {Object} options Options object - * @param {Boolean} [options.binary=false] Specifies whether `data` is binary - * or text - * @param {Boolean} [options.compress=false] Specifies whether or not to - * compress `data` - * @param {Boolean} [options.fin=false] Specifies whether the fragment is the - * last one - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Function} [cb] Callback - * @public - */ - send(data, options, cb) { - const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName]; - let opcode = options.binary ? 2 : 1; - let rsv1 = options.compress; - - let byteLength; - let readOnly; - - if (typeof data === 'string') { - byteLength = Buffer.byteLength(data); - readOnly = false; - } else if (isBlob$1(data)) { - byteLength = data.size; - readOnly = false; - } else { - data = toBuffer$1(data); - byteLength = data.length; - readOnly = toBuffer$1.readOnly; - } - - if (this._firstFragment) { - this._firstFragment = false; - if ( - rsv1 && - perMessageDeflate && - perMessageDeflate.params[ - perMessageDeflate._isServer - ? 'server_no_context_takeover' - : 'client_no_context_takeover' - ] - ) { - rsv1 = byteLength >= perMessageDeflate._threshold; - } - this._compress = rsv1; - } else { - rsv1 = false; - opcode = 0; - } - - if (options.fin) this._firstFragment = true; - - const opts = { - [kByteLength]: byteLength, - fin: options.fin, - generateMask: this._generateMask, - mask: options.mask, - maskBuffer: this._maskBuffer, - opcode, - readOnly, - rsv1 - }; - - if (isBlob$1(data)) { - if (this._state !== DEFAULT) { - this.enqueue([this.getBlobData, data, this._compress, opts, cb]); - } else { - this.getBlobData(data, this._compress, opts, cb); - } - } else if (this._state !== DEFAULT) { - this.enqueue([this.dispatch, data, this._compress, opts, cb]); - } else { - this.dispatch(data, this._compress, opts, cb); - } - } - - /** - * Gets the contents of a blob as binary data. - * - * @param {Blob} blob The blob - * @param {Boolean} [compress=false] Specifies whether or not to compress - * the data - * @param {Object} options Options object - * @param {Boolean} [options.fin=false] Specifies whether or not to set the - * FIN bit - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Buffer} [options.maskBuffer] The buffer used to store the masking - * key - * @param {Number} options.opcode The opcode - * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be - * modified - * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the - * RSV1 bit - * @param {Function} [cb] Callback - * @private - */ - getBlobData(blob, compress, options, cb) { - this._bufferedBytes += options[kByteLength]; - this._state = GET_BLOB_DATA; - - blob - .arrayBuffer() - .then((arrayBuffer) => { - if (this._socket.destroyed) { - const err = new Error( - 'The socket was closed while the blob was being read' - ); - - // - // `callCallbacks` is called in the next tick to ensure that errors - // that might be thrown in the callbacks behave like errors thrown - // outside the promise chain. - // - process.nextTick(callCallbacks, this, err, cb); - return; - } - - this._bufferedBytes -= options[kByteLength]; - const data = toBuffer$1(arrayBuffer); - - if (!compress) { - this._state = DEFAULT; - this.sendFrame(Sender.frame(data, options), cb); - this.dequeue(); - } else { - this.dispatch(data, compress, options, cb); - } - }) - .catch((err) => { - // - // `onError` is called in the next tick for the same reason that - // `callCallbacks` above is. - // - process.nextTick(onError, this, err, cb); - }); - } - - /** - * Dispatches a message. - * - * @param {(Buffer|String)} data The message to send - * @param {Boolean} [compress=false] Specifies whether or not to compress - * `data` - * @param {Object} options Options object - * @param {Boolean} [options.fin=false] Specifies whether or not to set the - * FIN bit - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Boolean} [options.mask=false] Specifies whether or not to mask - * `data` - * @param {Buffer} [options.maskBuffer] The buffer used to store the masking - * key - * @param {Number} options.opcode The opcode - * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be - * modified - * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the - * RSV1 bit - * @param {Function} [cb] Callback - * @private - */ - dispatch(data, compress, options, cb) { - if (!compress) { - this.sendFrame(Sender.frame(data, options), cb); - return; - } - - const perMessageDeflate = this._extensions[PerMessageDeflate$2.extensionName]; - - this._bufferedBytes += options[kByteLength]; - this._state = DEFLATING; - perMessageDeflate.compress(data, options.fin, (_, buf) => { - if (this._socket.destroyed) { - const err = new Error( - 'The socket was closed while data was being compressed' - ); - - callCallbacks(this, err, cb); - return; - } - - this._bufferedBytes -= options[kByteLength]; - this._state = DEFAULT; - options.readOnly = false; - this.sendFrame(Sender.frame(buf, options), cb); - this.dequeue(); - }); - } - - /** - * Executes queued send operations. - * - * @private - */ - dequeue() { - while (this._state === DEFAULT && this._queue.length) { - const params = this._queue.shift(); - - this._bufferedBytes -= params[3][kByteLength]; - Reflect.apply(params[0], this, params.slice(1)); - } - } - - /** - * Enqueues a send operation. - * - * @param {Array} params Send operation parameters. - * @private - */ - enqueue(params) { - this._bufferedBytes += params[3][kByteLength]; - this._queue.push(params); - } - - /** - * Sends a frame. - * - * @param {Buffer[]} list The frame to send - * @param {Function} [cb] Callback - * @private - */ - sendFrame(list, cb) { - if (list.length === 2) { - this._socket.cork(); - this._socket.write(list[0]); - this._socket.write(list[1], cb); - this._socket.uncork(); - } else { - this._socket.write(list[0], cb); - } - } -}; - -var sender = Sender$1; - -/** - * Calls queued callbacks with an error. - * - * @param {Sender} sender The `Sender` instance - * @param {Error} err The error to call the callbacks with - * @param {Function} [cb] The first callback - * @private - */ -function callCallbacks(sender, err, cb) { - if (typeof cb === 'function') cb(err); - - for (let i = 0; i < sender._queue.length; i++) { - const params = sender._queue[i]; - const callback = params[params.length - 1]; - - if (typeof callback === 'function') callback(err); - } -} - -/** - * Handles a `Sender` error. - * - * @param {Sender} sender The `Sender` instance - * @param {Error} err The error - * @param {Function} [cb] The first pending callback - * @private - */ -function onError(sender, err, cb) { - callCallbacks(sender, err, cb); - sender.onerror(err); -} - -const { kForOnEventAttribute: kForOnEventAttribute$1, kListener: kListener$1 } = constants; - -const kCode = Symbol('kCode'); -const kData = Symbol('kData'); -const kError = Symbol('kError'); -const kMessage = Symbol('kMessage'); -const kReason = Symbol('kReason'); -const kTarget = Symbol('kTarget'); -const kType = Symbol('kType'); -const kWasClean = Symbol('kWasClean'); - -/** - * Class representing an event. - */ -let Event$1 = class Event { - /** - * Create a new `Event`. - * - * @param {String} type The name of the event - * @throws {TypeError} If the `type` argument is not specified - */ - constructor(type) { - this[kTarget] = null; - this[kType] = type; - } - - /** - * @type {*} - */ - get target() { - return this[kTarget]; - } - - /** - * @type {String} - */ - get type() { - return this[kType]; - } -}; - -Object.defineProperty(Event$1.prototype, 'target', { enumerable: true }); -Object.defineProperty(Event$1.prototype, 'type', { enumerable: true }); - -/** - * Class representing a close event. - * - * @extends Event - */ -class CloseEvent extends Event$1 { - /** - * Create a new `CloseEvent`. - * - * @param {String} type The name of the event - * @param {Object} [options] A dictionary object that allows for setting - * attributes via object members of the same name - * @param {Number} [options.code=0] The status code explaining why the - * connection was closed - * @param {String} [options.reason=''] A human-readable string explaining why - * the connection was closed - * @param {Boolean} [options.wasClean=false] Indicates whether or not the - * connection was cleanly closed - */ - constructor(type, options = {}) { - super(type); - - this[kCode] = options.code === undefined ? 0 : options.code; - this[kReason] = options.reason === undefined ? '' : options.reason; - this[kWasClean] = options.wasClean === undefined ? false : options.wasClean; - } - - /** - * @type {Number} - */ - get code() { - return this[kCode]; - } - - /** - * @type {String} - */ - get reason() { - return this[kReason]; - } - - /** - * @type {Boolean} - */ - get wasClean() { - return this[kWasClean]; - } -} - -Object.defineProperty(CloseEvent.prototype, 'code', { enumerable: true }); -Object.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true }); -Object.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true }); - -/** - * Class representing an error event. - * - * @extends Event - */ -class ErrorEvent extends Event$1 { - /** - * Create a new `ErrorEvent`. - * - * @param {String} type The name of the event - * @param {Object} [options] A dictionary object that allows for setting - * attributes via object members of the same name - * @param {*} [options.error=null] The error that generated this event - * @param {String} [options.message=''] The error message - */ - constructor(type, options = {}) { - super(type); - - this[kError] = options.error === undefined ? null : options.error; - this[kMessage] = options.message === undefined ? '' : options.message; - } - - /** - * @type {*} - */ - get error() { - return this[kError]; - } - - /** - * @type {String} - */ - get message() { - return this[kMessage]; - } -} - -Object.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true }); -Object.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true }); - -/** - * Class representing a message event. - * - * @extends Event - */ -class MessageEvent extends Event$1 { - /** - * Create a new `MessageEvent`. - * - * @param {String} type The name of the event - * @param {Object} [options] A dictionary object that allows for setting - * attributes via object members of the same name - * @param {*} [options.data=null] The message content - */ - constructor(type, options = {}) { - super(type); - - this[kData] = options.data === undefined ? null : options.data; - } - - /** - * @type {*} - */ - get data() { - return this[kData]; - } -} - -Object.defineProperty(MessageEvent.prototype, 'data', { enumerable: true }); - -/** - * This provides methods for emulating the `EventTarget` interface. It's not - * meant to be used directly. - * - * @mixin - */ -const EventTarget = { - /** - * Register an event listener. - * - * @param {String} type A string representing the event type to listen for - * @param {(Function|Object)} handler The listener to add - * @param {Object} [options] An options object specifies characteristics about - * the event listener - * @param {Boolean} [options.once=false] A `Boolean` indicating that the - * listener should be invoked at most once after being added. If `true`, - * the listener would be automatically removed when invoked. - * @public - */ - addEventListener(type, handler, options = {}) { - for (const listener of this.listeners(type)) { - if ( - !options[kForOnEventAttribute$1] && - listener[kListener$1] === handler && - !listener[kForOnEventAttribute$1] - ) { - return; - } - } - - let wrapper; - - if (type === 'message') { - wrapper = function onMessage(data, isBinary) { - const event = new MessageEvent('message', { - data: isBinary ? data : data.toString() - }); - - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === 'close') { - wrapper = function onClose(code, message) { - const event = new CloseEvent('close', { - code, - reason: message.toString(), - wasClean: this._closeFrameReceived && this._closeFrameSent - }); - - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === 'error') { - wrapper = function onError(error) { - const event = new ErrorEvent('error', { - error, - message: error.message - }); - - event[kTarget] = this; - callListener(handler, this, event); - }; - } else if (type === 'open') { - wrapper = function onOpen() { - const event = new Event$1('open'); - - event[kTarget] = this; - callListener(handler, this, event); - }; - } else { - return; - } - - wrapper[kForOnEventAttribute$1] = !!options[kForOnEventAttribute$1]; - wrapper[kListener$1] = handler; - - if (options.once) { - this.once(type, wrapper); - } else { - this.on(type, wrapper); - } - }, - - /** - * Remove an event listener. - * - * @param {String} type A string representing the event type to remove - * @param {(Function|Object)} handler The listener to remove - * @public - */ - removeEventListener(type, handler) { - for (const listener of this.listeners(type)) { - if (listener[kListener$1] === handler && !listener[kForOnEventAttribute$1]) { - this.removeListener(type, listener); - break; - } - } - } -}; - -var eventTarget = { - CloseEvent, - ErrorEvent, - Event: Event$1, - EventTarget, - MessageEvent -}; - -/** - * Call an event listener - * - * @param {(Function|Object)} listener The listener to call - * @param {*} thisArg The value to use as `this`` when calling the listener - * @param {Event} event The event to pass to the listener - * @private - */ -function callListener(listener, thisArg, event) { - if (typeof listener === 'object' && listener.handleEvent) { - listener.handleEvent.call(listener, event); - } else { - listener.call(thisArg, event); - } -} - -const { tokenChars: tokenChars$1 } = validationExports; - -/** - * Adds an offer to the map of extension offers or a parameter to the map of - * parameters. - * - * @param {Object} dest The map of extension offers or parameters - * @param {String} name The extension or parameter name - * @param {(Object|Boolean|String)} elem The extension parameters or the - * parameter value - * @private - */ -function push(dest, name, elem) { - if (dest[name] === undefined) dest[name] = [elem]; - else dest[name].push(elem); -} - -/** - * Parses the `Sec-WebSocket-Extensions` header into an object. - * - * @param {String} header The field value of the header - * @return {Object} The parsed object - * @public - */ -function parse$2(header) { - const offers = Object.create(null); - let params = Object.create(null); - let mustUnescape = false; - let isEscaping = false; - let inQuotes = false; - let extensionName; - let paramName; - let start = -1; - let code = -1; - let end = -1; - let i = 0; - - for (; i < header.length; i++) { - code = header.charCodeAt(i); - - if (extensionName === undefined) { - if (end === -1 && tokenChars$1[code] === 1) { - if (start === -1) start = i; - } else if ( - i !== 0 && - (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ - ) { - if (end === -1 && start !== -1) end = i; - } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - - if (end === -1) end = i; - const name = header.slice(start, end); - if (code === 0x2c) { - push(offers, name, params); - params = Object.create(null); - } else { - extensionName = name; - } - - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else if (paramName === undefined) { - if (end === -1 && tokenChars$1[code] === 1) { - if (start === -1) start = i; - } else if (code === 0x20 || code === 0x09) { - if (end === -1 && start !== -1) end = i; - } else if (code === 0x3b || code === 0x2c) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - - if (end === -1) end = i; - push(params, header.slice(start, end), true); - if (code === 0x2c) { - push(offers, extensionName, params); - params = Object.create(null); - extensionName = undefined; - } - - start = end = -1; - } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) { - paramName = header.slice(start, i); - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else { - // - // The value of a quoted-string after unescaping must conform to the - // token ABNF, so only token characters are valid. - // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 - // - if (isEscaping) { - if (tokenChars$1[code] !== 1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - if (start === -1) start = i; - else if (!mustUnescape) mustUnescape = true; - isEscaping = false; - } else if (inQuotes) { - if (tokenChars$1[code] === 1) { - if (start === -1) start = i; - } else if (code === 0x22 /* '"' */ && start !== -1) { - inQuotes = false; - end = i; - } else if (code === 0x5c /* '\' */) { - isEscaping = true; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { - inQuotes = true; - } else if (end === -1 && tokenChars$1[code] === 1) { - if (start === -1) start = i; - } else if (start !== -1 && (code === 0x20 || code === 0x09)) { - if (end === -1) end = i; - } else if (code === 0x3b || code === 0x2c) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - - if (end === -1) end = i; - let value = header.slice(start, end); - if (mustUnescape) { - value = value.replace(/\\/g, ''); - mustUnescape = false; - } - push(params, paramName, value); - if (code === 0x2c) { - push(offers, extensionName, params); - params = Object.create(null); - extensionName = undefined; - } - - paramName = undefined; - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } - } - - if (start === -1 || inQuotes || code === 0x20 || code === 0x09) { - throw new SyntaxError('Unexpected end of input'); - } - - if (end === -1) end = i; - const token = header.slice(start, end); - if (extensionName === undefined) { - push(offers, token, params); - } else { - if (paramName === undefined) { - push(params, token, true); - } else if (mustUnescape) { - push(params, paramName, token.replace(/\\/g, '')); - } else { - push(params, paramName, token); - } - push(offers, extensionName, params); - } - - return offers; -} - -/** - * Builds the `Sec-WebSocket-Extensions` header field value. - * - * @param {Object} extensions The map of extensions and parameters to format - * @return {String} A string representing the given object - * @public - */ -function format$1(extensions) { - return Object.keys(extensions) - .map((extension) => { - let configurations = extensions[extension]; - if (!Array.isArray(configurations)) configurations = [configurations]; - return configurations - .map((params) => { - return [extension] - .concat( - Object.keys(params).map((k) => { - let values = params[k]; - if (!Array.isArray(values)) values = [values]; - return values - .map((v) => (v === true ? k : `${k}=${v}`)) - .join('; '); - }) - ) - .join('; '); - }) - .join(', '); - }) - .join(', '); -} - -var extension$1 = { format: format$1, parse: parse$2 }; - -/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex|Readable$", "caughtErrors": "none" }] */ - -const EventEmitter$1 = require$$0$7; -const https$2 = require$$1$1; -const http$3 = require$$1; -const net = require$$4$1; -const tls = require$$4$2; -const { randomBytes, createHash: createHash$1 } = require$$3$1; -const { URL: URL$2 } = require$$0$9; - -const PerMessageDeflate$1 = permessageDeflate; -const Receiver = receiver; -const Sender = sender; -const { isBlob } = validationExports; - -const { - BINARY_TYPES, - EMPTY_BUFFER, - GUID: GUID$1, - kForOnEventAttribute, - kListener, - kStatusCode, - kWebSocket: kWebSocket$1, - NOOP: NOOP$1 -} = constants; -const { - EventTarget: { addEventListener, removeEventListener } -} = eventTarget; -const { format, parse: parse$1 } = extension$1; -const { toBuffer } = bufferUtilExports; - -const closeTimeout = 30 * 1000; -const kAborted = Symbol('kAborted'); -const protocolVersions = [8, 13]; -const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; -const subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/; - -/** - * Class representing a WebSocket. - * - * @extends EventEmitter - */ -let WebSocket$1 = class WebSocket extends EventEmitter$1 { - /** - * Create a new `WebSocket`. - * - * @param {(String|URL)} address The URL to which to connect - * @param {(String|String[])} [protocols] The subprotocols - * @param {Object} [options] Connection options - */ - constructor(address, protocols, options) { - super(); - - this._binaryType = BINARY_TYPES[0]; - this._closeCode = 1006; - this._closeFrameReceived = false; - this._closeFrameSent = false; - this._closeMessage = EMPTY_BUFFER; - this._closeTimer = null; - this._errorEmitted = false; - this._extensions = {}; - this._paused = false; - this._protocol = ''; - this._readyState = WebSocket.CONNECTING; - this._receiver = null; - this._sender = null; - this._socket = null; - - if (address !== null) { - this._bufferedAmount = 0; - this._isServer = false; - this._redirects = 0; - - if (protocols === undefined) { - protocols = []; - } else if (!Array.isArray(protocols)) { - if (typeof protocols === 'object' && protocols !== null) { - options = protocols; - protocols = []; - } else { - protocols = [protocols]; - } - } - - initAsClient(this, address, protocols, options); - } else { - this._autoPong = options.autoPong; - this._isServer = true; - } - } - - /** - * For historical reasons, the custom "nodebuffer" type is used by the default - * instead of "blob". - * - * @type {String} - */ - get binaryType() { - return this._binaryType; - } - - set binaryType(type) { - if (!BINARY_TYPES.includes(type)) return; - - this._binaryType = type; - - // - // Allow to change `binaryType` on the fly. - // - if (this._receiver) this._receiver._binaryType = type; - } - - /** - * @type {Number} - */ - get bufferedAmount() { - if (!this._socket) return this._bufferedAmount; - - return this._socket._writableState.length + this._sender._bufferedBytes; - } - - /** - * @type {String} - */ - get extensions() { - return Object.keys(this._extensions).join(); - } - - /** - * @type {Boolean} - */ - get isPaused() { - return this._paused; - } - - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onclose() { - return null; - } - - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onerror() { - return null; - } - - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onopen() { - return null; - } - - /** - * @type {Function} - */ - /* istanbul ignore next */ - get onmessage() { - return null; - } - - /** - * @type {String} - */ - get protocol() { - return this._protocol; - } - - /** - * @type {Number} - */ - get readyState() { - return this._readyState; - } - - /** - * @type {String} - */ - get url() { - return this._url; - } - - /** - * Set up the socket and the internal resources. - * - * @param {Duplex} socket The network socket between the server and client - * @param {Buffer} head The first packet of the upgraded stream - * @param {Object} options Options object - * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether - * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted - * multiple times in the same tick - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Number} [options.maxPayload=0] The maximum allowed message size - * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or - * not to skip UTF-8 validation for text and close messages - * @private - */ - setSocket(socket, head, options) { - const receiver = new Receiver({ - allowSynchronousEvents: options.allowSynchronousEvents, - binaryType: this.binaryType, - extensions: this._extensions, - isServer: this._isServer, - maxPayload: options.maxPayload, - skipUTF8Validation: options.skipUTF8Validation - }); - - const sender = new Sender(socket, this._extensions, options.generateMask); - - this._receiver = receiver; - this._sender = sender; - this._socket = socket; - - receiver[kWebSocket$1] = this; - sender[kWebSocket$1] = this; - socket[kWebSocket$1] = this; - - receiver.on('conclude', receiverOnConclude); - receiver.on('drain', receiverOnDrain); - receiver.on('error', receiverOnError); - receiver.on('message', receiverOnMessage); - receiver.on('ping', receiverOnPing); - receiver.on('pong', receiverOnPong); - - sender.onerror = senderOnError; - - // - // These methods may not be available if `socket` is just a `Duplex`. - // - if (socket.setTimeout) socket.setTimeout(0); - if (socket.setNoDelay) socket.setNoDelay(); - - if (head.length > 0) socket.unshift(head); - - socket.on('close', socketOnClose); - socket.on('data', socketOnData); - socket.on('end', socketOnEnd); - socket.on('error', socketOnError$1); - - this._readyState = WebSocket.OPEN; - this.emit('open'); - } - - /** - * Emit the `'close'` event. - * - * @private - */ - emitClose() { - if (!this._socket) { - this._readyState = WebSocket.CLOSED; - this.emit('close', this._closeCode, this._closeMessage); - return; - } - - if (this._extensions[PerMessageDeflate$1.extensionName]) { - this._extensions[PerMessageDeflate$1.extensionName].cleanup(); - } - - this._receiver.removeAllListeners(); - this._readyState = WebSocket.CLOSED; - this.emit('close', this._closeCode, this._closeMessage); - } - - /** - * Start a closing handshake. - * - * +----------+ +-----------+ +----------+ - * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - - * | +----------+ +-----------+ +----------+ | - * +----------+ +-----------+ | - * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING - * +----------+ +-----------+ | - * | | | +---+ | - * +------------------------+-->|fin| - - - - - * | +---+ | +---+ - * - - - - -|fin|<---------------------+ - * +---+ - * - * @param {Number} [code] Status code explaining why the connection is closing - * @param {(String|Buffer)} [data] The reason why the connection is - * closing - * @public - */ - close(code, data) { - if (this.readyState === WebSocket.CLOSED) return; - if (this.readyState === WebSocket.CONNECTING) { - const msg = 'WebSocket was closed before the connection was established'; - abortHandshake$1(this, this._req, msg); - return; - } - - if (this.readyState === WebSocket.CLOSING) { - if ( - this._closeFrameSent && - (this._closeFrameReceived || this._receiver._writableState.errorEmitted) - ) { - this._socket.end(); - } - - return; - } - - this._readyState = WebSocket.CLOSING; - this._sender.close(code, data, !this._isServer, (err) => { - // - // This error is handled by the `'error'` listener on the socket. We only - // want to know if the close frame has been sent here. - // - if (err) return; - - this._closeFrameSent = true; - - if ( - this._closeFrameReceived || - this._receiver._writableState.errorEmitted - ) { - this._socket.end(); - } - }); - - setCloseTimer(this); - } - - /** - * Pause the socket. - * - * @public - */ - pause() { - if ( - this.readyState === WebSocket.CONNECTING || - this.readyState === WebSocket.CLOSED - ) { - return; - } - - this._paused = true; - this._socket.pause(); - } - - /** - * Send a ping. - * - * @param {*} [data] The data to send - * @param {Boolean} [mask] Indicates whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when the ping is sent - * @public - */ - ping(data, mask, cb) { - if (this.readyState === WebSocket.CONNECTING) { - throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); - } - - if (typeof data === 'function') { - cb = data; - data = mask = undefined; - } else if (typeof mask === 'function') { - cb = mask; - mask = undefined; - } - - if (typeof data === 'number') data = data.toString(); - - if (this.readyState !== WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - - if (mask === undefined) mask = !this._isServer; - this._sender.ping(data || EMPTY_BUFFER, mask, cb); - } - - /** - * Send a pong. - * - * @param {*} [data] The data to send - * @param {Boolean} [mask] Indicates whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when the pong is sent - * @public - */ - pong(data, mask, cb) { - if (this.readyState === WebSocket.CONNECTING) { - throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); - } - - if (typeof data === 'function') { - cb = data; - data = mask = undefined; - } else if (typeof mask === 'function') { - cb = mask; - mask = undefined; - } - - if (typeof data === 'number') data = data.toString(); - - if (this.readyState !== WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - - if (mask === undefined) mask = !this._isServer; - this._sender.pong(data || EMPTY_BUFFER, mask, cb); - } - - /** - * Resume the socket. - * - * @public - */ - resume() { - if ( - this.readyState === WebSocket.CONNECTING || - this.readyState === WebSocket.CLOSED - ) { - return; - } - - this._paused = false; - if (!this._receiver._writableState.needDrain) this._socket.resume(); - } - - /** - * Send a data message. - * - * @param {*} data The message to send - * @param {Object} [options] Options object - * @param {Boolean} [options.binary] Specifies whether `data` is binary or - * text - * @param {Boolean} [options.compress] Specifies whether or not to compress - * `data` - * @param {Boolean} [options.fin=true] Specifies whether the fragment is the - * last one - * @param {Boolean} [options.mask] Specifies whether or not to mask `data` - * @param {Function} [cb] Callback which is executed when data is written out - * @public - */ - send(data, options, cb) { - if (this.readyState === WebSocket.CONNECTING) { - throw new Error('WebSocket is not open: readyState 0 (CONNECTING)'); - } - - if (typeof options === 'function') { - cb = options; - options = {}; - } - - if (typeof data === 'number') data = data.toString(); - - if (this.readyState !== WebSocket.OPEN) { - sendAfterClose(this, data, cb); - return; - } - - const opts = { - binary: typeof data !== 'string', - mask: !this._isServer, - compress: true, - fin: true, - ...options - }; - - if (!this._extensions[PerMessageDeflate$1.extensionName]) { - opts.compress = false; - } - - this._sender.send(data || EMPTY_BUFFER, opts, cb); - } - - /** - * Forcibly close the connection. - * - * @public - */ - terminate() { - if (this.readyState === WebSocket.CLOSED) return; - if (this.readyState === WebSocket.CONNECTING) { - const msg = 'WebSocket was closed before the connection was established'; - abortHandshake$1(this, this._req, msg); - return; - } - - if (this._socket) { - this._readyState = WebSocket.CLOSING; - this._socket.destroy(); - } - } -}; - -/** - * @constant {Number} CONNECTING - * @memberof WebSocket - */ -Object.defineProperty(WebSocket$1, 'CONNECTING', { - enumerable: true, - value: readyStates.indexOf('CONNECTING') -}); - -/** - * @constant {Number} CONNECTING - * @memberof WebSocket.prototype - */ -Object.defineProperty(WebSocket$1.prototype, 'CONNECTING', { - enumerable: true, - value: readyStates.indexOf('CONNECTING') -}); - -/** - * @constant {Number} OPEN - * @memberof WebSocket - */ -Object.defineProperty(WebSocket$1, 'OPEN', { - enumerable: true, - value: readyStates.indexOf('OPEN') -}); - -/** - * @constant {Number} OPEN - * @memberof WebSocket.prototype - */ -Object.defineProperty(WebSocket$1.prototype, 'OPEN', { - enumerable: true, - value: readyStates.indexOf('OPEN') -}); - -/** - * @constant {Number} CLOSING - * @memberof WebSocket - */ -Object.defineProperty(WebSocket$1, 'CLOSING', { - enumerable: true, - value: readyStates.indexOf('CLOSING') -}); - -/** - * @constant {Number} CLOSING - * @memberof WebSocket.prototype - */ -Object.defineProperty(WebSocket$1.prototype, 'CLOSING', { - enumerable: true, - value: readyStates.indexOf('CLOSING') -}); - -/** - * @constant {Number} CLOSED - * @memberof WebSocket - */ -Object.defineProperty(WebSocket$1, 'CLOSED', { - enumerable: true, - value: readyStates.indexOf('CLOSED') -}); - -/** - * @constant {Number} CLOSED - * @memberof WebSocket.prototype - */ -Object.defineProperty(WebSocket$1.prototype, 'CLOSED', { - enumerable: true, - value: readyStates.indexOf('CLOSED') -}); - -[ - 'binaryType', - 'bufferedAmount', - 'extensions', - 'isPaused', - 'protocol', - 'readyState', - 'url' -].forEach((property) => { - Object.defineProperty(WebSocket$1.prototype, property, { enumerable: true }); -}); - -// -// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. -// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface -// -['open', 'error', 'close', 'message'].forEach((method) => { - Object.defineProperty(WebSocket$1.prototype, `on${method}`, { - enumerable: true, - get() { - for (const listener of this.listeners(method)) { - if (listener[kForOnEventAttribute]) return listener[kListener]; - } - - return null; - }, - set(handler) { - for (const listener of this.listeners(method)) { - if (listener[kForOnEventAttribute]) { - this.removeListener(method, listener); - break; - } - } - - if (typeof handler !== 'function') return; - - this.addEventListener(method, handler, { - [kForOnEventAttribute]: true - }); - } - }); -}); - -WebSocket$1.prototype.addEventListener = addEventListener; -WebSocket$1.prototype.removeEventListener = removeEventListener; - -var websocket = WebSocket$1; - -/** - * Initialize a WebSocket client. - * - * @param {WebSocket} websocket The client to initialize - * @param {(String|URL)} address The URL to which to connect - * @param {Array} protocols The subprotocols - * @param {Object} [options] Connection options - * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any - * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple - * times in the same tick - * @param {Boolean} [options.autoPong=true] Specifies whether or not to - * automatically send a pong in response to a ping - * @param {Function} [options.finishRequest] A function which can be used to - * customize the headers of each http request before it is sent - * @param {Boolean} [options.followRedirects=false] Whether or not to follow - * redirects - * @param {Function} [options.generateMask] The function used to generate the - * masking key - * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the - * handshake request - * @param {Number} [options.maxPayload=104857600] The maximum allowed message - * size - * @param {Number} [options.maxRedirects=10] The maximum number of redirects - * allowed - * @param {String} [options.origin] Value of the `Origin` or - * `Sec-WebSocket-Origin` header - * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable - * permessage-deflate - * @param {Number} [options.protocolVersion=13] Value of the - * `Sec-WebSocket-Version` header - * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or - * not to skip UTF-8 validation for text and close messages - * @private - */ -function initAsClient(websocket, address, protocols, options) { - const opts = { - allowSynchronousEvents: true, - autoPong: true, - protocolVersion: protocolVersions[1], - maxPayload: 100 * 1024 * 1024, - skipUTF8Validation: false, - perMessageDeflate: true, - followRedirects: false, - maxRedirects: 10, - ...options, - socketPath: undefined, - hostname: undefined, - protocol: undefined, - timeout: undefined, - method: 'GET', - host: undefined, - path: undefined, - port: undefined - }; - - websocket._autoPong = opts.autoPong; - - if (!protocolVersions.includes(opts.protocolVersion)) { - throw new RangeError( - `Unsupported protocol version: ${opts.protocolVersion} ` + - `(supported versions: ${protocolVersions.join(', ')})` - ); - } - - let parsedUrl; - - if (address instanceof URL$2) { - parsedUrl = address; - } else { - try { - parsedUrl = new URL$2(address); - } catch (e) { - throw new SyntaxError(`Invalid URL: ${address}`); - } - } - - if (parsedUrl.protocol === 'http:') { - parsedUrl.protocol = 'ws:'; - } else if (parsedUrl.protocol === 'https:') { - parsedUrl.protocol = 'wss:'; - } - - websocket._url = parsedUrl.href; - - const isSecure = parsedUrl.protocol === 'wss:'; - const isIpcUrl = parsedUrl.protocol === 'ws+unix:'; - let invalidUrlMessage; - - if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) { - invalidUrlMessage = - 'The URL\'s protocol must be one of "ws:", "wss:", ' + - '"http:", "https", or "ws+unix:"'; - } else if (isIpcUrl && !parsedUrl.pathname) { - invalidUrlMessage = "The URL's pathname is empty"; - } else if (parsedUrl.hash) { - invalidUrlMessage = 'The URL contains a fragment identifier'; - } - - if (invalidUrlMessage) { - const err = new SyntaxError(invalidUrlMessage); - - if (websocket._redirects === 0) { - throw err; - } else { - emitErrorAndClose(websocket, err); - return; - } - } - - const defaultPort = isSecure ? 443 : 80; - const key = randomBytes(16).toString('base64'); - const request = isSecure ? https$2.request : http$3.request; - const protocolSet = new Set(); - let perMessageDeflate; - - opts.createConnection = - opts.createConnection || (isSecure ? tlsConnect : netConnect); - opts.defaultPort = opts.defaultPort || defaultPort; - opts.port = parsedUrl.port || defaultPort; - opts.host = parsedUrl.hostname.startsWith('[') - ? parsedUrl.hostname.slice(1, -1) - : parsedUrl.hostname; - opts.headers = { - ...opts.headers, - 'Sec-WebSocket-Version': opts.protocolVersion, - 'Sec-WebSocket-Key': key, - Connection: 'Upgrade', - Upgrade: 'websocket' - }; - opts.path = parsedUrl.pathname + parsedUrl.search; - opts.timeout = opts.handshakeTimeout; - - if (opts.perMessageDeflate) { - perMessageDeflate = new PerMessageDeflate$1( - opts.perMessageDeflate !== true ? opts.perMessageDeflate : {}, - false, - opts.maxPayload - ); - opts.headers['Sec-WebSocket-Extensions'] = format({ - [PerMessageDeflate$1.extensionName]: perMessageDeflate.offer() - }); - } - if (protocols.length) { - for (const protocol of protocols) { - if ( - typeof protocol !== 'string' || - !subprotocolRegex.test(protocol) || - protocolSet.has(protocol) - ) { - throw new SyntaxError( - 'An invalid or duplicated subprotocol was specified' - ); - } - - protocolSet.add(protocol); - } - - opts.headers['Sec-WebSocket-Protocol'] = protocols.join(','); - } - if (opts.origin) { - if (opts.protocolVersion < 13) { - opts.headers['Sec-WebSocket-Origin'] = opts.origin; - } else { - opts.headers.Origin = opts.origin; - } - } - if (parsedUrl.username || parsedUrl.password) { - opts.auth = `${parsedUrl.username}:${parsedUrl.password}`; - } - - if (isIpcUrl) { - const parts = opts.path.split(':'); - - opts.socketPath = parts[0]; - opts.path = parts[1]; - } - - let req; - - if (opts.followRedirects) { - if (websocket._redirects === 0) { - websocket._originalIpc = isIpcUrl; - websocket._originalSecure = isSecure; - websocket._originalHostOrSocketPath = isIpcUrl - ? opts.socketPath - : parsedUrl.host; - - const headers = options && options.headers; - - // - // Shallow copy the user provided options so that headers can be changed - // without mutating the original object. - // - options = { ...options, headers: {} }; - - if (headers) { - for (const [key, value] of Object.entries(headers)) { - options.headers[key.toLowerCase()] = value; - } - } - } else if (websocket.listenerCount('redirect') === 0) { - const isSameHost = isIpcUrl - ? websocket._originalIpc - ? opts.socketPath === websocket._originalHostOrSocketPath - : false - : websocket._originalIpc - ? false - : parsedUrl.host === websocket._originalHostOrSocketPath; - - if (!isSameHost || (websocket._originalSecure && !isSecure)) { - // - // Match curl 7.77.0 behavior and drop the following headers. These - // headers are also dropped when following a redirect to a subdomain. - // - delete opts.headers.authorization; - delete opts.headers.cookie; - - if (!isSameHost) delete opts.headers.host; - - opts.auth = undefined; - } - } - - // - // Match curl 7.77.0 behavior and make the first `Authorization` header win. - // If the `Authorization` header is set, then there is nothing to do as it - // will take precedence. - // - if (opts.auth && !options.headers.authorization) { - options.headers.authorization = - 'Basic ' + Buffer.from(opts.auth).toString('base64'); - } - - req = websocket._req = request(opts); - - if (websocket._redirects) { - // - // Unlike what is done for the `'upgrade'` event, no early exit is - // triggered here if the user calls `websocket.close()` or - // `websocket.terminate()` from a listener of the `'redirect'` event. This - // is because the user can also call `request.destroy()` with an error - // before calling `websocket.close()` or `websocket.terminate()` and this - // would result in an error being emitted on the `request` object with no - // `'error'` event listeners attached. - // - websocket.emit('redirect', websocket.url, req); - } - } else { - req = websocket._req = request(opts); - } - - if (opts.timeout) { - req.on('timeout', () => { - abortHandshake$1(websocket, req, 'Opening handshake has timed out'); - }); - } - - req.on('error', (err) => { - if (req === null || req[kAborted]) return; - - req = websocket._req = null; - emitErrorAndClose(websocket, err); - }); - - req.on('response', (res) => { - const location = res.headers.location; - const statusCode = res.statusCode; - - if ( - location && - opts.followRedirects && - statusCode >= 300 && - statusCode < 400 - ) { - if (++websocket._redirects > opts.maxRedirects) { - abortHandshake$1(websocket, req, 'Maximum redirects exceeded'); - return; - } - - req.abort(); - - let addr; - - try { - addr = new URL$2(location, address); - } catch (e) { - const err = new SyntaxError(`Invalid URL: ${location}`); - emitErrorAndClose(websocket, err); - return; - } - - initAsClient(websocket, addr, protocols, options); - } else if (!websocket.emit('unexpected-response', req, res)) { - abortHandshake$1( - websocket, - req, - `Unexpected server response: ${res.statusCode}` - ); - } - }); - - req.on('upgrade', (res, socket, head) => { - websocket.emit('upgrade', res); - - // - // The user may have closed the connection from a listener of the - // `'upgrade'` event. - // - if (websocket.readyState !== WebSocket$1.CONNECTING) return; - - req = websocket._req = null; - - const upgrade = res.headers.upgrade; - - if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { - abortHandshake$1(websocket, socket, 'Invalid Upgrade header'); - return; - } - - const digest = createHash$1('sha1') - .update(key + GUID$1) - .digest('base64'); - - if (res.headers['sec-websocket-accept'] !== digest) { - abortHandshake$1(websocket, socket, 'Invalid Sec-WebSocket-Accept header'); - return; - } - - const serverProt = res.headers['sec-websocket-protocol']; - let protError; - - if (serverProt !== undefined) { - if (!protocolSet.size) { - protError = 'Server sent a subprotocol but none was requested'; - } else if (!protocolSet.has(serverProt)) { - protError = 'Server sent an invalid subprotocol'; - } - } else if (protocolSet.size) { - protError = 'Server sent no subprotocol'; - } - - if (protError) { - abortHandshake$1(websocket, socket, protError); - return; - } - - if (serverProt) websocket._protocol = serverProt; - - const secWebSocketExtensions = res.headers['sec-websocket-extensions']; - - if (secWebSocketExtensions !== undefined) { - if (!perMessageDeflate) { - const message = - 'Server sent a Sec-WebSocket-Extensions header but no extension ' + - 'was requested'; - abortHandshake$1(websocket, socket, message); - return; - } - - let extensions; - - try { - extensions = parse$1(secWebSocketExtensions); - } catch (err) { - const message = 'Invalid Sec-WebSocket-Extensions header'; - abortHandshake$1(websocket, socket, message); - return; - } - - const extensionNames = Object.keys(extensions); - - if ( - extensionNames.length !== 1 || - extensionNames[0] !== PerMessageDeflate$1.extensionName - ) { - const message = 'Server indicated an extension that was not requested'; - abortHandshake$1(websocket, socket, message); - return; - } - - try { - perMessageDeflate.accept(extensions[PerMessageDeflate$1.extensionName]); - } catch (err) { - const message = 'Invalid Sec-WebSocket-Extensions header'; - abortHandshake$1(websocket, socket, message); - return; - } - - websocket._extensions[PerMessageDeflate$1.extensionName] = - perMessageDeflate; - } - - websocket.setSocket(socket, head, { - allowSynchronousEvents: opts.allowSynchronousEvents, - generateMask: opts.generateMask, - maxPayload: opts.maxPayload, - skipUTF8Validation: opts.skipUTF8Validation - }); - }); - - if (opts.finishRequest) { - opts.finishRequest(req, websocket); - } else { - req.end(); - } -} - -/** - * Emit the `'error'` and `'close'` events. - * - * @param {WebSocket} websocket The WebSocket instance - * @param {Error} The error to emit - * @private - */ -function emitErrorAndClose(websocket, err) { - websocket._readyState = WebSocket$1.CLOSING; - // - // The following assignment is practically useless and is done only for - // consistency. - // - websocket._errorEmitted = true; - websocket.emit('error', err); - websocket.emitClose(); -} - -/** - * Create a `net.Socket` and initiate a connection. - * - * @param {Object} options Connection options - * @return {net.Socket} The newly created socket used to start the connection - * @private - */ -function netConnect(options) { - options.path = options.socketPath; - return net.connect(options); -} - -/** - * Create a `tls.TLSSocket` and initiate a connection. - * - * @param {Object} options Connection options - * @return {tls.TLSSocket} The newly created socket used to start the connection - * @private - */ -function tlsConnect(options) { - options.path = undefined; - - if (!options.servername && options.servername !== '') { - options.servername = net.isIP(options.host) ? '' : options.host; - } - - return tls.connect(options); -} - -/** - * Abort the handshake and emit an error. - * - * @param {WebSocket} websocket The WebSocket instance - * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to - * abort or the socket to destroy - * @param {String} message The error message - * @private - */ -function abortHandshake$1(websocket, stream, message) { - websocket._readyState = WebSocket$1.CLOSING; - - const err = new Error(message); - Error.captureStackTrace(err, abortHandshake$1); - - if (stream.setHeader) { - stream[kAborted] = true; - stream.abort(); - - if (stream.socket && !stream.socket.destroyed) { - // - // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if - // called after the request completed. See - // https://github.com/websockets/ws/issues/1869. - // - stream.socket.destroy(); - } - - process.nextTick(emitErrorAndClose, websocket, err); - } else { - stream.destroy(err); - stream.once('error', websocket.emit.bind(websocket, 'error')); - stream.once('close', websocket.emitClose.bind(websocket)); - } -} - -/** - * Handle cases where the `ping()`, `pong()`, or `send()` methods are called - * when the `readyState` attribute is `CLOSING` or `CLOSED`. - * - * @param {WebSocket} websocket The WebSocket instance - * @param {*} [data] The data to send - * @param {Function} [cb] Callback - * @private - */ -function sendAfterClose(websocket, data, cb) { - if (data) { - const length = isBlob(data) ? data.size : toBuffer(data).length; - - // - // The `_bufferedAmount` property is used only when the peer is a client and - // the opening handshake fails. Under these circumstances, in fact, the - // `setSocket()` method is not called, so the `_socket` and `_sender` - // properties are set to `null`. - // - if (websocket._socket) websocket._sender._bufferedBytes += length; - else websocket._bufferedAmount += length; - } - - if (cb) { - const err = new Error( - `WebSocket is not open: readyState ${websocket.readyState} ` + - `(${readyStates[websocket.readyState]})` - ); - process.nextTick(cb, err); - } -} - -/** - * The listener of the `Receiver` `'conclude'` event. - * - * @param {Number} code The status code - * @param {Buffer} reason The reason for closing - * @private - */ -function receiverOnConclude(code, reason) { - const websocket = this[kWebSocket$1]; - - websocket._closeFrameReceived = true; - websocket._closeMessage = reason; - websocket._closeCode = code; - - if (websocket._socket[kWebSocket$1] === undefined) return; - - websocket._socket.removeListener('data', socketOnData); - process.nextTick(resume, websocket._socket); - - if (code === 1005) websocket.close(); - else websocket.close(code, reason); -} - -/** - * The listener of the `Receiver` `'drain'` event. - * - * @private - */ -function receiverOnDrain() { - const websocket = this[kWebSocket$1]; - - if (!websocket.isPaused) websocket._socket.resume(); -} - -/** - * The listener of the `Receiver` `'error'` event. - * - * @param {(RangeError|Error)} err The emitted error - * @private - */ -function receiverOnError(err) { - const websocket = this[kWebSocket$1]; - - if (websocket._socket[kWebSocket$1] !== undefined) { - websocket._socket.removeListener('data', socketOnData); - - // - // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See - // https://github.com/websockets/ws/issues/1940. - // - process.nextTick(resume, websocket._socket); - - websocket.close(err[kStatusCode]); - } - - if (!websocket._errorEmitted) { - websocket._errorEmitted = true; - websocket.emit('error', err); - } -} - -/** - * The listener of the `Receiver` `'finish'` event. - * - * @private - */ -function receiverOnFinish() { - this[kWebSocket$1].emitClose(); -} - -/** - * The listener of the `Receiver` `'message'` event. - * - * @param {Buffer|ArrayBuffer|Buffer[])} data The message - * @param {Boolean} isBinary Specifies whether the message is binary or not - * @private - */ -function receiverOnMessage(data, isBinary) { - this[kWebSocket$1].emit('message', data, isBinary); -} - -/** - * The listener of the `Receiver` `'ping'` event. - * - * @param {Buffer} data The data included in the ping frame - * @private - */ -function receiverOnPing(data) { - const websocket = this[kWebSocket$1]; - - if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP$1); - websocket.emit('ping', data); -} - -/** - * The listener of the `Receiver` `'pong'` event. - * - * @param {Buffer} data The data included in the pong frame - * @private - */ -function receiverOnPong(data) { - this[kWebSocket$1].emit('pong', data); -} - -/** - * Resume a readable stream - * - * @param {Readable} stream The readable stream - * @private - */ -function resume(stream) { - stream.resume(); -} - -/** - * The `Sender` error event handler. - * - * @param {Error} The error - * @private - */ -function senderOnError(err) { - const websocket = this[kWebSocket$1]; - - if (websocket.readyState === WebSocket$1.CLOSED) return; - if (websocket.readyState === WebSocket$1.OPEN) { - websocket._readyState = WebSocket$1.CLOSING; - setCloseTimer(websocket); - } - - // - // `socket.end()` is used instead of `socket.destroy()` to allow the other - // peer to finish sending queued data. There is no need to set a timer here - // because `CLOSING` means that it is already set or not needed. - // - this._socket.end(); - - if (!websocket._errorEmitted) { - websocket._errorEmitted = true; - websocket.emit('error', err); - } -} - -/** - * Set a timer to destroy the underlying raw socket of a WebSocket. - * - * @param {WebSocket} websocket The WebSocket instance - * @private - */ -function setCloseTimer(websocket) { - websocket._closeTimer = setTimeout( - websocket._socket.destroy.bind(websocket._socket), - closeTimeout - ); -} - -/** - * The listener of the socket `'close'` event. - * - * @private - */ -function socketOnClose() { - const websocket = this[kWebSocket$1]; - - this.removeListener('close', socketOnClose); - this.removeListener('data', socketOnData); - this.removeListener('end', socketOnEnd); - - websocket._readyState = WebSocket$1.CLOSING; - - let chunk; - - // - // The close frame might not have been received or the `'end'` event emitted, - // for example, if the socket was destroyed due to an error. Ensure that the - // `receiver` stream is closed after writing any remaining buffered data to - // it. If the readable side of the socket is in flowing mode then there is no - // buffered data as everything has been already written and `readable.read()` - // will return `null`. If instead, the socket is paused, any possible buffered - // data will be read as a single chunk. - // - if ( - !this._readableState.endEmitted && - !websocket._closeFrameReceived && - !websocket._receiver._writableState.errorEmitted && - (chunk = websocket._socket.read()) !== null - ) { - websocket._receiver.write(chunk); - } - - websocket._receiver.end(); - - this[kWebSocket$1] = undefined; - - clearTimeout(websocket._closeTimer); - - if ( - websocket._receiver._writableState.finished || - websocket._receiver._writableState.errorEmitted - ) { - websocket.emitClose(); - } else { - websocket._receiver.on('error', receiverOnFinish); - websocket._receiver.on('finish', receiverOnFinish); - } -} - -/** - * The listener of the socket `'data'` event. - * - * @param {Buffer} chunk A chunk of data - * @private - */ -function socketOnData(chunk) { - if (!this[kWebSocket$1]._receiver.write(chunk)) { - this.pause(); - } -} - -/** - * The listener of the socket `'end'` event. - * - * @private - */ -function socketOnEnd() { - const websocket = this[kWebSocket$1]; - - websocket._readyState = WebSocket$1.CLOSING; - websocket._receiver.end(); - this.end(); -} - -/** - * The listener of the socket `'error'` event. - * - * @private - */ -function socketOnError$1() { - const websocket = this[kWebSocket$1]; - - this.removeListener('error', socketOnError$1); - this.on('error', NOOP$1); - - if (websocket) { - websocket._readyState = WebSocket$1.CLOSING; - this.destroy(); - } -} - -const { tokenChars } = validationExports; - -/** - * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names. - * - * @param {String} header The field value of the header - * @return {Set} The subprotocol names - * @public - */ -function parse(header) { - const protocols = new Set(); - let start = -1; - let end = -1; - let i = 0; - - for (i; i < header.length; i++) { - const code = header.charCodeAt(i); - - if (end === -1 && tokenChars[code] === 1) { - if (start === -1) start = i; - } else if ( - i !== 0 && - (code === 0x20 /* ' ' */ || code === 0x09) /* '\t' */ - ) { - if (end === -1 && start !== -1) end = i; - } else if (code === 0x2c /* ',' */) { - if (start === -1) { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - - if (end === -1) end = i; - - const protocol = header.slice(start, end); - - if (protocols.has(protocol)) { - throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); - } - - protocols.add(protocol); - start = end = -1; - } else { - throw new SyntaxError(`Unexpected character at index ${i}`); - } - } - - if (start === -1 || end !== -1) { - throw new SyntaxError('Unexpected end of input'); - } - - const protocol = header.slice(start, i); - - if (protocols.has(protocol)) { - throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`); - } - - protocols.add(protocol); - return protocols; -} - -var subprotocol$1 = { parse }; - -/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */ - -const EventEmitter = require$$0$7; -const http$2 = require$$1; -const { createHash } = require$$3$1; - -const extension = extension$1; -const PerMessageDeflate = permessageDeflate; -const subprotocol = subprotocol$1; -const WebSocket = websocket; -const { GUID, kWebSocket } = constants; - -const keyRegex = /^[+/0-9A-Za-z]{22}==$/; - -const RUNNING = 0; -const CLOSING = 1; -const CLOSED = 2; - -/** - * Class representing a WebSocket server. - * - * @extends EventEmitter - */ -class WebSocketServer extends EventEmitter { - /** - * Create a `WebSocketServer` instance. - * - * @param {Object} options Configuration options - * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether - * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted - * multiple times in the same tick - * @param {Boolean} [options.autoPong=true] Specifies whether or not to - * automatically send a pong in response to a ping - * @param {Number} [options.backlog=511] The maximum length of the queue of - * pending connections - * @param {Boolean} [options.clientTracking=true] Specifies whether or not to - * track clients - * @param {Function} [options.handleProtocols] A hook to handle protocols - * @param {String} [options.host] The hostname where to bind the server - * @param {Number} [options.maxPayload=104857600] The maximum allowed message - * size - * @param {Boolean} [options.noServer=false] Enable no server mode - * @param {String} [options.path] Accept only connections matching this path - * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable - * permessage-deflate - * @param {Number} [options.port] The port where to bind the server - * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S - * server to use - * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or - * not to skip UTF-8 validation for text and close messages - * @param {Function} [options.verifyClient] A hook to reject connections - * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket` - * class to use. It must be the `WebSocket` class or class that extends it - * @param {Function} [callback] A listener for the `listening` event - */ - constructor(options, callback) { - super(); - - options = { - allowSynchronousEvents: true, - autoPong: true, - maxPayload: 100 * 1024 * 1024, - skipUTF8Validation: false, - perMessageDeflate: false, - handleProtocols: null, - clientTracking: true, - verifyClient: null, - noServer: false, - backlog: null, // use default (511 as implemented in net.js) - server: null, - host: null, - path: null, - port: null, - WebSocket, - ...options - }; - - if ( - (options.port == null && !options.server && !options.noServer) || - (options.port != null && (options.server || options.noServer)) || - (options.server && options.noServer) - ) { - throw new TypeError( - 'One and only one of the "port", "server", or "noServer" options ' + - 'must be specified' - ); - } - - if (options.port != null) { - this._server = http$2.createServer((req, res) => { - const body = http$2.STATUS_CODES[426]; - - res.writeHead(426, { - 'Content-Length': body.length, - 'Content-Type': 'text/plain' - }); - res.end(body); - }); - this._server.listen( - options.port, - options.host, - options.backlog, - callback - ); - } else if (options.server) { - this._server = options.server; - } - - if (this._server) { - const emitConnection = this.emit.bind(this, 'connection'); - - this._removeListeners = addListeners(this._server, { - listening: this.emit.bind(this, 'listening'), - error: this.emit.bind(this, 'error'), - upgrade: (req, socket, head) => { - this.handleUpgrade(req, socket, head, emitConnection); - } - }); - } - - if (options.perMessageDeflate === true) options.perMessageDeflate = {}; - if (options.clientTracking) { - this.clients = new Set(); - this._shouldEmitClose = false; - } - - this.options = options; - this._state = RUNNING; - } - - /** - * Returns the bound address, the address family name, and port of the server - * as reported by the operating system if listening on an IP socket. - * If the server is listening on a pipe or UNIX domain socket, the name is - * returned as a string. - * - * @return {(Object|String|null)} The address of the server - * @public - */ - address() { - if (this.options.noServer) { - throw new Error('The server is operating in "noServer" mode'); - } - - if (!this._server) return null; - return this._server.address(); - } - - /** - * Stop the server from accepting new connections and emit the `'close'` event - * when all existing connections are closed. - * - * @param {Function} [cb] A one-time listener for the `'close'` event - * @public - */ - close(cb) { - if (this._state === CLOSED) { - if (cb) { - this.once('close', () => { - cb(new Error('The server is not running')); - }); - } - - process.nextTick(emitClose, this); - return; - } - - if (cb) this.once('close', cb); - - if (this._state === CLOSING) return; - this._state = CLOSING; - - if (this.options.noServer || this.options.server) { - if (this._server) { - this._removeListeners(); - this._removeListeners = this._server = null; - } - - if (this.clients) { - if (!this.clients.size) { - process.nextTick(emitClose, this); - } else { - this._shouldEmitClose = true; - } - } else { - process.nextTick(emitClose, this); - } - } else { - const server = this._server; - - this._removeListeners(); - this._removeListeners = this._server = null; - - // - // The HTTP/S server was created internally. Close it, and rely on its - // `'close'` event. - // - server.close(() => { - emitClose(this); - }); - } - } - - /** - * See if a given request should be handled by this server instance. - * - * @param {http.IncomingMessage} req Request object to inspect - * @return {Boolean} `true` if the request is valid, else `false` - * @public - */ - shouldHandle(req) { - if (this.options.path) { - const index = req.url.indexOf('?'); - const pathname = index !== -1 ? req.url.slice(0, index) : req.url; - - if (pathname !== this.options.path) return false; - } - - return true; - } - - /** - * Handle a HTTP Upgrade request. - * - * @param {http.IncomingMessage} req The request object - * @param {Duplex} socket The network socket between the server and client - * @param {Buffer} head The first packet of the upgraded stream - * @param {Function} cb Callback - * @public - */ - handleUpgrade(req, socket, head, cb) { - socket.on('error', socketOnError); - - const key = req.headers['sec-websocket-key']; - const upgrade = req.headers.upgrade; - const version = +req.headers['sec-websocket-version']; - - if (req.method !== 'GET') { - const message = 'Invalid HTTP method'; - abortHandshakeOrEmitwsClientError(this, req, socket, 405, message); - return; - } - - if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') { - const message = 'Invalid Upgrade header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - - if (key === undefined || !keyRegex.test(key)) { - const message = 'Missing or invalid Sec-WebSocket-Key header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - - if (version !== 8 && version !== 13) { - const message = 'Missing or invalid Sec-WebSocket-Version header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - - if (!this.shouldHandle(req)) { - abortHandshake(socket, 400); - return; - } - - const secWebSocketProtocol = req.headers['sec-websocket-protocol']; - let protocols = new Set(); - - if (secWebSocketProtocol !== undefined) { - try { - protocols = subprotocol.parse(secWebSocketProtocol); - } catch (err) { - const message = 'Invalid Sec-WebSocket-Protocol header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - } - - const secWebSocketExtensions = req.headers['sec-websocket-extensions']; - const extensions = {}; - - if ( - this.options.perMessageDeflate && - secWebSocketExtensions !== undefined - ) { - const perMessageDeflate = new PerMessageDeflate( - this.options.perMessageDeflate, - true, - this.options.maxPayload - ); - - try { - const offers = extension.parse(secWebSocketExtensions); - - if (offers[PerMessageDeflate.extensionName]) { - perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); - extensions[PerMessageDeflate.extensionName] = perMessageDeflate; - } - } catch (err) { - const message = - 'Invalid or unacceptable Sec-WebSocket-Extensions header'; - abortHandshakeOrEmitwsClientError(this, req, socket, 400, message); - return; - } - } - - // - // Optionally call external client verification handler. - // - if (this.options.verifyClient) { - const info = { - origin: - req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], - secure: !!(req.socket.authorized || req.socket.encrypted), - req - }; - - if (this.options.verifyClient.length === 2) { - this.options.verifyClient(info, (verified, code, message, headers) => { - if (!verified) { - return abortHandshake(socket, code || 401, message, headers); - } - - this.completeUpgrade( - extensions, - key, - protocols, - req, - socket, - head, - cb - ); - }); - return; - } - - if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); - } - - this.completeUpgrade(extensions, key, protocols, req, socket, head, cb); - } - - /** - * Upgrade the connection to WebSocket. - * - * @param {Object} extensions The accepted extensions - * @param {String} key The value of the `Sec-WebSocket-Key` header - * @param {Set} protocols The subprotocols - * @param {http.IncomingMessage} req The request object - * @param {Duplex} socket The network socket between the server and client - * @param {Buffer} head The first packet of the upgraded stream - * @param {Function} cb Callback - * @throws {Error} If called more than once with the same socket - * @private - */ - completeUpgrade(extensions, key, protocols, req, socket, head, cb) { - // - // Destroy the socket if the client has already sent a FIN packet. - // - if (!socket.readable || !socket.writable) return socket.destroy(); - - if (socket[kWebSocket]) { - throw new Error( - 'server.handleUpgrade() was called more than once with the same ' + - 'socket, possibly due to a misconfiguration' - ); - } - - if (this._state > RUNNING) return abortHandshake(socket, 503); - - const digest = createHash('sha1') - .update(key + GUID) - .digest('base64'); - - const headers = [ - 'HTTP/1.1 101 Switching Protocols', - 'Upgrade: websocket', - 'Connection: Upgrade', - `Sec-WebSocket-Accept: ${digest}` - ]; - - const ws = new this.options.WebSocket(null, undefined, this.options); - - if (protocols.size) { - // - // Optionally call external protocol selection handler. - // - const protocol = this.options.handleProtocols - ? this.options.handleProtocols(protocols, req) - : protocols.values().next().value; - - if (protocol) { - headers.push(`Sec-WebSocket-Protocol: ${protocol}`); - ws._protocol = protocol; - } - } - - if (extensions[PerMessageDeflate.extensionName]) { - const params = extensions[PerMessageDeflate.extensionName].params; - const value = extension.format({ - [PerMessageDeflate.extensionName]: [params] - }); - headers.push(`Sec-WebSocket-Extensions: ${value}`); - ws._extensions = extensions; - } - - // - // Allow external modification/inspection of handshake headers. - // - this.emit('headers', headers, req); - - socket.write(headers.concat('\r\n').join('\r\n')); - socket.removeListener('error', socketOnError); - - ws.setSocket(socket, head, { - allowSynchronousEvents: this.options.allowSynchronousEvents, - maxPayload: this.options.maxPayload, - skipUTF8Validation: this.options.skipUTF8Validation - }); - - if (this.clients) { - this.clients.add(ws); - ws.on('close', () => { - this.clients.delete(ws); - - if (this._shouldEmitClose && !this.clients.size) { - process.nextTick(emitClose, this); - } - }); - } - - cb(ws, req); - } -} - -var websocketServer = WebSocketServer; - -/** - * Add event listeners on an `EventEmitter` using a map of - * pairs. - * - * @param {EventEmitter} server The event emitter - * @param {Object.} map The listeners to add - * @return {Function} A function that will remove the added listeners when - * called - * @private - */ -function addListeners(server, map) { - for (const event of Object.keys(map)) server.on(event, map[event]); - - return function removeListeners() { - for (const event of Object.keys(map)) { - server.removeListener(event, map[event]); - } - }; -} - -/** - * Emit a `'close'` event on an `EventEmitter`. - * - * @param {EventEmitter} server The event emitter - * @private - */ -function emitClose(server) { - server._state = CLOSED; - server.emit('close'); -} - -/** - * Handle socket errors. - * - * @private - */ -function socketOnError() { - this.destroy(); -} - -/** - * Close the connection when preconditions are not fulfilled. - * - * @param {Duplex} socket The socket of the upgrade request - * @param {Number} code The HTTP response status code - * @param {String} [message] The HTTP response body - * @param {Object} [headers] Additional HTTP response headers - * @private - */ -function abortHandshake(socket, code, message, headers) { - // - // The socket is writable unless the user destroyed or ended it before calling - // `server.handleUpgrade()` or in the `verifyClient` function, which is a user - // error. Handling this does not make much sense as the worst that can happen - // is that some of the data written by the user might be discarded due to the - // call to `socket.end()` below, which triggers an `'error'` event that in - // turn causes the socket to be destroyed. - // - message = message || http$2.STATUS_CODES[code]; - headers = { - Connection: 'close', - 'Content-Type': 'text/html', - 'Content-Length': Buffer.byteLength(message), - ...headers - }; - - socket.once('finish', socket.destroy); - - socket.end( - `HTTP/1.1 ${code} ${http$2.STATUS_CODES[code]}\r\n` + - Object.keys(headers) - .map((h) => `${h}: ${headers[h]}`) - .join('\r\n') + - '\r\n\r\n' + - message - ); -} - -/** - * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least - * one listener for it, otherwise call `abortHandshake()`. - * - * @param {WebSocketServer} server The WebSocket server - * @param {http.IncomingMessage} req The request object - * @param {Duplex} socket The socket of the upgrade request - * @param {Number} code The HTTP response status code - * @param {String} message The HTTP response body - * @private - */ -function abortHandshakeOrEmitwsClientError(server, req, socket, code, message) { - if (server.listenerCount('wsClientError')) { - const err = new Error(message); - Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError); - - server.emit('wsClientError', err, socket, req); - } else { - abortHandshake(socket, code, message); - } -} - -var WebSocketServerRaw_ = /*@__PURE__*/getDefaultExportFromCjs(websocketServer); - -const allowedHostsServerCache = /* @__PURE__ */ new WeakMap(); -const allowedHostsPreviewCache = /* @__PURE__ */ new WeakMap(); -const isFileOrExtensionProtocolRE = /^(?:file|.+-extension):/i; -function getAdditionalAllowedHosts(resolvedServerOptions, resolvedPreviewOptions) { - const list = []; - if (typeof resolvedServerOptions.host === "string" && resolvedServerOptions.host) { - list.push(resolvedServerOptions.host); - } - if (typeof resolvedServerOptions.hmr === "object" && resolvedServerOptions.hmr.host) { - list.push(resolvedServerOptions.hmr.host); - } - if (typeof resolvedPreviewOptions.host === "string" && resolvedPreviewOptions.host) { - list.push(resolvedPreviewOptions.host); - } - if (resolvedServerOptions.origin) { - try { - const serverOriginUrl = new URL(resolvedServerOptions.origin); - list.push(serverOriginUrl.hostname); - } catch { - } - } - return list; -} -function isHostAllowedWithoutCache(allowedHosts, additionalAllowedHosts, host) { - if (isFileOrExtensionProtocolRE.test(host)) { - return true; - } - const trimmedHost = host.trim(); - if (trimmedHost[0] === "[") { - const endIpv6 = trimmedHost.indexOf("]"); - if (endIpv6 < 0) { - return false; - } - return net$1.isIP(trimmedHost.slice(1, endIpv6)) === 6; - } - const colonPos = trimmedHost.indexOf(":"); - const hostname = colonPos === -1 ? trimmedHost : trimmedHost.slice(0, colonPos); - if (net$1.isIP(hostname) === 4) { - return true; - } - if (hostname === "localhost" || hostname.endsWith(".localhost")) { - return true; - } - for (const additionalAllowedHost of additionalAllowedHosts) { - if (additionalAllowedHost === hostname) { - return true; - } - } - for (const allowedHost of allowedHosts) { - if (allowedHost === hostname) { - return true; - } - if (allowedHost[0] === "." && (allowedHost.slice(1) === hostname || hostname.endsWith(allowedHost))) { - return true; - } - } - return false; -} -function isHostAllowed(config, isPreview, host) { - const allowedHosts = isPreview ? config.preview.allowedHosts : config.server.allowedHosts; - if (allowedHosts === true) { - return true; - } - const cache = isPreview ? allowedHostsPreviewCache : allowedHostsServerCache; - if (!cache.has(config)) { - cache.set(config, /* @__PURE__ */ new Set()); - } - const cachedAllowedHosts = cache.get(config); - if (cachedAllowedHosts.has(host)) { - return true; - } - const result = isHostAllowedWithoutCache( - allowedHosts ?? [], - config.additionalAllowedHosts, - host - ); - if (result) { - cachedAllowedHosts.add(host); - } - return result; -} -function hostCheckMiddleware(config, isPreview) { - return function viteHostCheckMiddleware(req, res, next) { - const hostHeader = req.headers.host; - if (!hostHeader || !isHostAllowed(config, isPreview, hostHeader)) { - const hostname = hostHeader?.replace(/:\d+$/, ""); - const hostnameWithQuotes = JSON.stringify(hostname); - const optionName = `${isPreview ? "preview" : "server"}.allowedHosts`; - res.writeHead(403, { - "Content-Type": "text/plain" - }); - res.end( - `Blocked request. This host (${hostnameWithQuotes}) is not allowed. -To allow this host, add ${hostnameWithQuotes} to \`${optionName}\` in vite.config.js.` - ); - return; - } - return next(); - }; -} - -const WebSocketServerRaw = process.versions.bun ? ( - // @ts-expect-error: Bun defines `import.meta.require` - import.meta.require("ws").WebSocketServer -) : WebSocketServerRaw_; -const HMR_HEADER = "vite-hmr"; -const wsServerEvents = [ - "connection", - "error", - "headers", - "listening", - "message" -]; -function noop$1() { -} -function hasValidToken(config, url) { - const token = url.searchParams.get("token"); - if (!token) return false; - try { - const isValidToken = crypto$2.timingSafeEqual( - Buffer.from(token), - Buffer.from(config.webSocketToken) - ); - return isValidToken; - } catch { - } - return false; -} -function createWebSocketServer(server, config, httpsOptions) { - if (config.server.ws === false) { - return { - name: "ws", - get clients() { - return /* @__PURE__ */ new Set(); - }, - async close() { - }, - on: noop$1, - off: noop$1, - listen: noop$1, - send: noop$1 - }; - } - let wsHttpServer = void 0; - const hmr = isObject$1(config.server.hmr) && config.server.hmr; - const hmrServer = hmr && hmr.server; - const hmrPort = hmr && hmr.port; - const portsAreCompatible = !hmrPort || hmrPort === config.server.port; - const wsServer = hmrServer || portsAreCompatible && server; - let hmrServerWsListener; - const customListeners = /* @__PURE__ */ new Map(); - const clientsMap = /* @__PURE__ */ new WeakMap(); - const port = hmrPort || 24678; - const host = hmr && hmr.host || void 0; - const shouldHandle = (req) => { - const hostHeader = req.headers.host; - if (!hostHeader || !isHostAllowed(config, false, hostHeader)) { - return false; - } - if (config.legacy?.skipWebSocketTokenCheck) { - return true; - } - if (req.headers.origin) { - const parsedUrl = new URL(`http://example.com${req.url}`); - return hasValidToken(config, parsedUrl); - } - return true; - }; - const handleUpgrade = (req, socket, head, _isPing) => { - wss.handleUpgrade(req, socket, head, (ws) => { - wss.emit("connection", ws, req); - }); - }; - const wss = new WebSocketServerRaw({ noServer: true }); - wss.shouldHandle = shouldHandle; - if (wsServer) { - let hmrBase = config.base; - const hmrPath = hmr ? hmr.path : void 0; - if (hmrPath) { - hmrBase = path$n.posix.join(hmrBase, hmrPath); - } - hmrServerWsListener = (req, socket, head) => { - const parsedUrl = new URL(`http://example.com${req.url}`); - if (req.headers["sec-websocket-protocol"] === HMR_HEADER && parsedUrl.pathname === hmrBase) { - handleUpgrade(req, socket, head); - } - }; - wsServer.on("upgrade", hmrServerWsListener); - } else { - const route = (_, res) => { - const statusCode = 426; - const body = STATUS_CODES[statusCode]; - if (!body) - throw new Error(`No body text found for the ${statusCode} status code`); - res.writeHead(statusCode, { - "Content-Length": body.length, - "Content-Type": "text/plain" - }); - res.end(body); - }; - if (httpsOptions) { - wsHttpServer = createServer$2(httpsOptions, route); - } else { - wsHttpServer = createServer$3(route); - } - wsHttpServer.on("upgrade", (req, socket, head) => { - handleUpgrade(req, socket, head); - }); - wsHttpServer.on("error", (e) => { - if (e.code === "EADDRINUSE") { - config.logger.error( - colors$1.red(`WebSocket server error: Port is already in use`), - { error: e } - ); - } else { - config.logger.error( - colors$1.red(`WebSocket server error: -${e.stack || e.message}`), - { error: e } - ); - } - }); - } - wss.on("connection", (socket) => { - socket.on("message", (raw) => { - if (!customListeners.size) return; - let parsed; - try { - parsed = JSON.parse(String(raw)); - } catch { - } - if (!parsed || parsed.type !== "custom" || !parsed.event) return; - const listeners = customListeners.get(parsed.event); - if (!listeners?.size) return; - const client = getSocketClient(socket); - listeners.forEach((listener) => listener(parsed.data, client)); - }); - socket.on("error", (err) => { - config.logger.error(`${colors$1.red(`ws error:`)} -${err.stack}`, { - timestamp: true, - error: err - }); - }); - socket.send(JSON.stringify({ type: "connected" })); - if (bufferedError) { - socket.send(JSON.stringify(bufferedError)); - bufferedError = null; - } - }); - wss.on("error", (e) => { - if (e.code === "EADDRINUSE") { - config.logger.error( - colors$1.red(`WebSocket server error: Port is already in use`), - { error: e } - ); - } else { - config.logger.error( - colors$1.red(`WebSocket server error: -${e.stack || e.message}`), - { error: e } - ); - } - }); - function getSocketClient(socket) { - if (!clientsMap.has(socket)) { - clientsMap.set(socket, { - send: (...args) => { - let payload; - if (typeof args[0] === "string") { - payload = { - type: "custom", - event: args[0], - data: args[1] - }; - } else { - payload = args[0]; - } - socket.send(JSON.stringify(payload)); - }, - socket - }); - } - return clientsMap.get(socket); - } - let bufferedError = null; - return { - name: "ws", - listen: () => { - wsHttpServer?.listen(port, host); - }, - on: (event, fn) => { - if (wsServerEvents.includes(event)) wss.on(event, fn); - else { - if (!customListeners.has(event)) { - customListeners.set(event, /* @__PURE__ */ new Set()); - } - customListeners.get(event).add(fn); - } - }, - off: (event, fn) => { - if (wsServerEvents.includes(event)) { - wss.off(event, fn); - } else { - customListeners.get(event)?.delete(fn); - } - }, - get clients() { - return new Set(Array.from(wss.clients).map(getSocketClient)); - }, - send(...args) { - let payload; - if (typeof args[0] === "string") { - payload = { - type: "custom", - event: args[0], - data: args[1] - }; - } else { - payload = args[0]; - } - if (payload.type === "error" && !wss.clients.size) { - bufferedError = payload; - return; - } - const stringified = JSON.stringify(payload); - wss.clients.forEach((client) => { - if (client.readyState === 1) { - client.send(stringified); - } - }); - }, - close() { - if (hmrServerWsListener && wsServer) { - wsServer.off("upgrade", hmrServerWsListener); - } - return new Promise((resolve, reject) => { - wss.clients.forEach((client) => { - client.terminate(); - }); - wss.close((err) => { - if (err) { - reject(err); - } else { - if (wsHttpServer) { - wsHttpServer.close((err2) => { - if (err2) { - reject(err2); - } else { - resolve(); - } - }); - } else { - resolve(); - } - } - }); - }); - } - }; -} - -function baseMiddleware(rawBase, middlewareMode) { - return function viteBaseMiddleware(req, res, next) { - const url = req.url; - const pathname = cleanUrl(url); - const base = rawBase; - if (pathname.startsWith(base)) { - req.url = stripBase(url, base); - return next(); - } - if (middlewareMode) { - return next(); - } - if (pathname === "/" || pathname === "/index.html") { - res.writeHead(302, { - Location: base + url.slice(pathname.length) - }); - res.end(); - return; - } - const redirectPath = withTrailingSlash(url) !== base ? joinUrlSegments(base, url) : base; - if (req.headers.accept?.includes("text/html")) { - res.writeHead(404, { - "Content-Type": "text/html" - }); - res.end( - `The server is configured with a public base URL of ${base} - did you mean to visit ${redirectPath} instead?` - ); - return; - } else { - res.writeHead(404, { - "Content-Type": "text/plain" - }); - res.end( - `The server is configured with a public base URL of ${base} - did you mean to visit ${redirectPath} instead?` - ); - return; - } - }; -} - -var httpProxy$3 = {exports: {}}; - -var eventemitter3 = {exports: {}}; - -(function (module) { - - var has = Object.prototype.hasOwnProperty - , prefix = '~'; - - /** - * Constructor to create a storage for our `EE` objects. - * An `Events` instance is a plain object whose properties are event names. - * - * @constructor - * @private - */ - function Events() {} - - // - // We try to not inherit from `Object.prototype`. In some engines creating an - // instance in this way is faster than calling `Object.create(null)` directly. - // If `Object.create(null)` is not supported we prefix the event names with a - // character to make sure that the built-in object properties are not - // overridden or used as an attack vector. - // - if (Object.create) { - Events.prototype = Object.create(null); - - // - // This hack is needed because the `__proto__` property is still inherited in - // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. - // - if (!new Events().__proto__) prefix = false; - } - - /** - * Representation of a single event listener. - * - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} [once=false] Specify if the listener is a one-time listener. - * @constructor - * @private - */ - function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; - } - - /** - * Add a listener for a given event. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} once Specify if the listener is a one-time listener. - * @returns {EventEmitter} - * @private - */ - function addListener(emitter, event, fn, context, once) { - if (typeof fn !== 'function') { - throw new TypeError('The listener must be a function'); - } - - var listener = new EE(fn, context || emitter, once) - , evt = prefix ? prefix + event : event; - - if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); - else emitter._events[evt] = [emitter._events[evt], listener]; - - return emitter; - } - - /** - * Clear event by name. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} evt The Event name. - * @private - */ - function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) emitter._events = new Events(); - else delete emitter._events[evt]; - } - - /** - * Minimal `EventEmitter` interface that is molded against the Node.js - * `EventEmitter` interface. - * - * @constructor - * @public - */ - function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; - } - - /** - * Return an array listing the events for which the emitter has registered - * listeners. - * - * @returns {Array} - * @public - */ - EventEmitter.prototype.eventNames = function eventNames() { - var names = [] - , events - , name; - - if (this._eventsCount === 0) return names; - - for (name in (events = this._events)) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); - } - - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); - } - - return names; - }; - - /** - * Return the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Array} The registered listeners. - * @public - */ - EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event - , handlers = this._events[evt]; - - if (!handlers) return []; - if (handlers.fn) return [handlers.fn]; - - for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { - ee[i] = handlers[i].fn; - } - - return ee; - }; - - /** - * Return the number of listeners listening to a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Number} The number of listeners. - * @public - */ - EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event - , listeners = this._events[evt]; - - if (!listeners) return 0; - if (listeners.fn) return 1; - return listeners.length; - }; - - /** - * Calls each of the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Boolean} `true` if the event had listeners, else `false`. - * @public - */ - EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) return false; - - var listeners = this._events[evt] - , len = arguments.length - , args - , i; - - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); - - switch (len) { - case 1: return listeners.fn.call(listeners.context), true; - case 2: return listeners.fn.call(listeners.context, a1), true; - case 3: return listeners.fn.call(listeners.context, a1, a2), true; - case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; - } - - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments[i]; - } - - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length - , j; - - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); - - switch (len) { - case 1: listeners[i].fn.call(listeners[i].context); break; - case 2: listeners[i].fn.call(listeners[i].context, a1); break; - case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; - case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; - default: - if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { - args[j - 1] = arguments[j]; - } - - listeners[i].fn.apply(listeners[i].context, args); - } - } - } - - return true; - }; - - /** - * Add a listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ - EventEmitter.prototype.on = function on(event, fn, context) { - return addListener(this, event, fn, context, false); - }; - - /** - * Add a one-time listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ - EventEmitter.prototype.once = function once(event, fn, context) { - return addListener(this, event, fn, context, true); - }; - - /** - * Remove the listeners of a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {*} context Only remove the listeners that have this context. - * @param {Boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - * @public - */ - EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) return this; - if (!fn) { - clearEvent(this, evt); - return this; - } - - var listeners = this._events[evt]; - - if (listeners.fn) { - if ( - listeners.fn === fn && - (!once || listeners.once) && - (!context || listeners.context === context) - ) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if ( - listeners[i].fn !== fn || - (once && !listeners[i].once) || - (context && listeners[i].context !== context) - ) { - events.push(listeners[i]); - } - } - - // - // Reset the array, or remove it completely if we have no more listeners. - // - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else clearEvent(this, evt); - } - - return this; - }; - - /** - * Remove all listeners, or those of the specified event. - * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public - */ - EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; - } - - return this; - }; - - // - // Alias methods names because people roll like that. - // - EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - EventEmitter.prototype.addListener = EventEmitter.prototype.on; - - // - // Expose the prefix. - // - EventEmitter.prefixed = prefix; - - // - // Allow `EventEmitter` to be imported as module namespace. - // - EventEmitter.EventEmitter = EventEmitter; - - // - // Expose the module. - // - { - module.exports = EventEmitter; - } -} (eventemitter3)); - -var eventemitter3Exports = eventemitter3.exports; - -var common$3 = {}; - -/** - * Check if we're required to add a port number. - * - * @see https://url.spec.whatwg.org/#default-port - * @param {Number|String} port Port number we need to check - * @param {String} protocol Protocol we need to check against. - * @returns {Boolean} Is it a default port for the given protocol - * @api private - */ -var requiresPort = function required(port, protocol) { - protocol = protocol.split(':')[0]; - port = +port; - - if (!port) return false; - - switch (protocol) { - case 'http': - case 'ws': - return port !== 80; - - case 'https': - case 'wss': - return port !== 443; - - case 'ftp': - return port !== 21; - - case 'gopher': - return port !== 70; - - case 'file': - return false; - } - - return port !== 0; -}; - -(function (exports) { - var common = exports, - url = require$$0$9, - required = requiresPort; - - var upgradeHeader = /(^|,)\s*upgrade\s*($|,)/i, - isSSL = /^https|wss/; - - /** - * Simple Regex for testing if protocol is https - */ - common.isSSL = isSSL; - /** - * Copies the right headers from `options` and `req` to - * `outgoing` which is then used to fire the proxied - * request. - * - * Examples: - * - * common.setupOutgoing(outgoing, options, req) - * // => { host: ..., hostname: ...} - * - * @param {Object} Outgoing Base object to be filled with required properties - * @param {Object} Options Config object passed to the proxy - * @param {ClientRequest} Req Request Object - * @param {String} Forward String to select forward or target - *  - * @return {Object} Outgoing Object with all required properties set - * - * @api private - */ - - common.setupOutgoing = function(outgoing, options, req, forward) { - outgoing.port = options[forward || 'target'].port || - (isSSL.test(options[forward || 'target'].protocol) ? 443 : 80); - - ['host', 'hostname', 'socketPath', 'pfx', 'key', - 'passphrase', 'cert', 'ca', 'ciphers', 'secureProtocol'].forEach( - function(e) { outgoing[e] = options[forward || 'target'][e]; } - ); - - outgoing.method = options.method || req.method; - outgoing.headers = Object.assign({}, req.headers); - - if (options.headers){ - Object.assign(outgoing.headers, options.headers); - } - - if (options.auth) { - outgoing.auth = options.auth; - } - - if (options.ca) { - outgoing.ca = options.ca; - } - - if (isSSL.test(options[forward || 'target'].protocol)) { - outgoing.rejectUnauthorized = (typeof options.secure === "undefined") ? true : options.secure; - } - - - outgoing.agent = options.agent || false; - outgoing.localAddress = options.localAddress; - - // - // Remark: If we are false and not upgrading, set the connection: close. This is the right thing to do - // as node core doesn't handle this COMPLETELY properly yet. - // - if (!outgoing.agent) { - outgoing.headers = outgoing.headers || {}; - if (typeof outgoing.headers.connection !== 'string' - || !upgradeHeader.test(outgoing.headers.connection) - ) { outgoing.headers.connection = 'close'; } - } - - - // the final path is target path + relative path requested by user: - var target = options[forward || 'target']; - var targetPath = target && options.prependPath !== false - ? (target.path || '') - : ''; - - // - // Remark: Can we somehow not use url.parse as a perf optimization? - // - var outgoingPath = !options.toProxy - ? (url.parse(req.url).path || '') - : req.url; - - // - // Remark: ignorePath will just straight up ignore whatever the request's - // path is. This can be labeled as FOOT-GUN material if you do not know what - // you are doing and are using conflicting options. - // - outgoingPath = !options.ignorePath ? outgoingPath : ''; - - outgoing.path = common.urlJoin(targetPath, outgoingPath); - - if (options.changeOrigin) { - outgoing.headers.host = - required(outgoing.port, options[forward || 'target'].protocol) && !hasPort(outgoing.host) - ? outgoing.host + ':' + outgoing.port - : outgoing.host; - } - return outgoing; - }; - - /** - * Set the proper configuration for sockets, - * set no delay and set keep alive, also set - * the timeout to 0. - * - * Examples: - * - * common.setupSocket(socket) - * // => Socket - * - * @param {Socket} Socket instance to setup - *  - * @return {Socket} Return the configured socket. - * - * @api private - */ - - common.setupSocket = function(socket) { - socket.setTimeout(0); - socket.setNoDelay(true); - - socket.setKeepAlive(true, 0); - - return socket; - }; - - /** - * Get the port number from the host. Or guess it based on the connection type. - * - * @param {Request} req Incoming HTTP request. - * - * @return {String} The port number. - * - * @api private - */ - common.getPort = function(req) { - var res = req.headers.host ? req.headers.host.match(/:(\d+)/) : ''; - - return res ? - res[1] : - common.hasEncryptedConnection(req) ? '443' : '80'; - }; - - /** - * Check if the request has an encrypted connection. - * - * @param {Request} req Incoming HTTP request. - * - * @return {Boolean} Whether the connection is encrypted or not. - * - * @api private - */ - common.hasEncryptedConnection = function(req) { - return Boolean(req.connection.encrypted || req.connection.pair); - }; - - /** - * OS-agnostic join (doesn't break on URLs like path.join does on Windows)> - * - * @return {String} The generated path. - * - * @api private - */ - - common.urlJoin = function() { - // - // We do not want to mess with the query string. All we want to touch is the path. - // - var args = Array.prototype.slice.call(arguments), - lastIndex = args.length - 1, - last = args[lastIndex], - lastSegs = last.split('?'), - retSegs; - - args[lastIndex] = lastSegs.shift(); - - // - // Join all strings, but remove empty strings so we don't get extra slashes from - // joining e.g. ['', 'am'] - // - retSegs = [ - args.filter(Boolean).join('/') - .replace(/\/+/g, '/') - .replace('http:/', 'http://') - .replace('https:/', 'https://') - ]; - - // Only join the query string if it exists so we don't have trailing a '?' - // on every request - - // Handle case where there could be multiple ? in the URL. - retSegs.push.apply(retSegs, lastSegs); - - return retSegs.join('?') - }; - - /** - * Rewrites or removes the domain of a cookie header - * - * @param {String|Array} Header - * @param {Object} Config, mapping of domain to rewritten domain. - * '*' key to match any domain, null value to remove the domain. - * - * @api private - */ - common.rewriteCookieProperty = function rewriteCookieProperty(header, config, property) { - if (Array.isArray(header)) { - return header.map(function (headerElement) { - return rewriteCookieProperty(headerElement, config, property); - }); - } - return header.replace(new RegExp("(;\\s*" + property + "=)([^;]+)", 'i'), function(match, prefix, previousValue) { - var newValue; - if (previousValue in config) { - newValue = config[previousValue]; - } else if ('*' in config) { - newValue = config['*']; - } else { - //no match, return previous value - return match; - } - if (newValue) { - //replace value - return prefix + newValue; - } else { - //remove value - return ''; - } - }); - }; - - /** - * Check the host and see if it potentially has a port in it (keep it simple) - * - * @returns {Boolean} Whether we have one or not - * - * @api private - */ - function hasPort(host) { - return !!~host.indexOf(':'); - }} (common$3)); - -var url$1 = require$$0$9, - common$2 = common$3; - - -var redirectRegex = /^201|30(1|2|7|8)$/; - -/*! - * Array of passes. - * - * A `pass` is just a function that is executed on `req, res, options` - * so that you can easily add new checks while still keeping the base - * flexible. - */ - -var webOutgoing = { // <-- - - /** - * If is a HTTP 1.0 request, remove chunk headers - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {proxyResponse} Res Response object from the proxy request - * - * @api private - */ - removeChunked: function removeChunked(req, res, proxyRes) { - if (req.httpVersion === '1.0') { - delete proxyRes.headers['transfer-encoding']; - } - }, - - /** - * If is a HTTP 1.0 request, set the correct connection header - * or if connection header not present, then use `keep-alive` - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {proxyResponse} Res Response object from the proxy request - * - * @api private - */ - setConnection: function setConnection(req, res, proxyRes) { - if (req.httpVersion === '1.0') { - proxyRes.headers.connection = req.headers.connection || 'close'; - } else if (req.httpVersion !== '2.0' && !proxyRes.headers.connection) { - proxyRes.headers.connection = req.headers.connection || 'keep-alive'; - } - }, - - setRedirectHostRewrite: function setRedirectHostRewrite(req, res, proxyRes, options) { - if ((options.hostRewrite || options.autoRewrite || options.protocolRewrite) - && proxyRes.headers['location'] - && redirectRegex.test(proxyRes.statusCode)) { - var target = url$1.parse(options.target); - var u = url$1.parse(proxyRes.headers['location']); - - // make sure the redirected host matches the target host before rewriting - if (target.host != u.host) { - return; - } - - if (options.hostRewrite) { - u.host = options.hostRewrite; - } else if (options.autoRewrite) { - u.host = req.headers['host']; - } - if (options.protocolRewrite) { - u.protocol = options.protocolRewrite; - } - - proxyRes.headers['location'] = u.format(); - } - }, - /** - * Copy headers from proxyResponse to response - * set each header in response object. - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {proxyResponse} Res Response object from the proxy request - * @param {Object} Options options.cookieDomainRewrite: Config to rewrite cookie domain - * - * @api private - */ - writeHeaders: function writeHeaders(req, res, proxyRes, options) { - var rewriteCookieDomainConfig = options.cookieDomainRewrite, - rewriteCookiePathConfig = options.cookiePathRewrite, - preserveHeaderKeyCase = options.preserveHeaderKeyCase, - rawHeaderKeyMap, - setHeader = function(key, header) { - if (header == undefined) return; - if (rewriteCookieDomainConfig && key.toLowerCase() === 'set-cookie') { - header = common$2.rewriteCookieProperty(header, rewriteCookieDomainConfig, 'domain'); - } - if (rewriteCookiePathConfig && key.toLowerCase() === 'set-cookie') { - header = common$2.rewriteCookieProperty(header, rewriteCookiePathConfig, 'path'); - } - res.setHeader(String(key).trim(), header); - }; - - if (typeof rewriteCookieDomainConfig === 'string') { //also test for '' - rewriteCookieDomainConfig = { '*': rewriteCookieDomainConfig }; - } - - if (typeof rewriteCookiePathConfig === 'string') { //also test for '' - rewriteCookiePathConfig = { '*': rewriteCookiePathConfig }; - } - - // message.rawHeaders is added in: v0.11.6 - // https://nodejs.org/api/http.html#http_message_rawheaders - if (preserveHeaderKeyCase && proxyRes.rawHeaders != undefined) { - rawHeaderKeyMap = {}; - for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) { - var key = proxyRes.rawHeaders[i]; - rawHeaderKeyMap[key.toLowerCase()] = key; - } - } - - Object.keys(proxyRes.headers).forEach(function(key) { - var header = proxyRes.headers[key]; - if (preserveHeaderKeyCase && rawHeaderKeyMap) { - key = rawHeaderKeyMap[key] || key; - } - setHeader(key, header); - }); - }, - - /** - * Set the statusCode from the proxyResponse - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {proxyResponse} Res Response object from the proxy request - * - * @api private - */ - writeStatusCode: function writeStatusCode(req, res, proxyRes) { - // From Node.js docs: response.writeHead(statusCode[, statusMessage][, headers]) - if(proxyRes.statusMessage) { - res.statusCode = proxyRes.statusCode; - res.statusMessage = proxyRes.statusMessage; - } else { - res.statusCode = proxyRes.statusCode; - } - } - -}; - -var followRedirects$1 = {exports: {}}; - -var debug$6; - -var debug_1 = function () { - if (!debug$6) { - try { - /* eslint global-require: off */ - debug$6 = srcExports$1("follow-redirects"); - } - catch (error) { /* */ } - if (typeof debug$6 !== "function") { - debug$6 = function () { /* */ }; - } - } - debug$6.apply(null, arguments); -}; - -var url = require$$0$9; -var URL$1 = url.URL; -var http$1 = require$$1; -var https$1 = require$$1$1; -var Writable = require$$0$6.Writable; -var assert = require$$4$3; -var debug$5 = debug_1; - -// Whether to use the native URL object or the legacy url module -var useNativeURL = false; -try { - assert(new URL$1()); -} -catch (error) { - useNativeURL = error.code === "ERR_INVALID_URL"; -} - -// URL fields to preserve in copy operations -var preservedUrlFields = [ - "auth", - "host", - "hostname", - "href", - "path", - "pathname", - "port", - "protocol", - "query", - "search", - "hash", -]; - -// Create handlers that pass events from native requests -var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; -var eventHandlers = Object.create(null); -events.forEach(function (event) { - eventHandlers[event] = function (arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); - }; -}); - -// Error types with codes -var InvalidUrlError = createErrorType( - "ERR_INVALID_URL", - "Invalid URL", - TypeError -); -var RedirectionError = createErrorType( - "ERR_FR_REDIRECTION_FAILURE", - "Redirected request failed" -); -var TooManyRedirectsError = createErrorType( - "ERR_FR_TOO_MANY_REDIRECTS", - "Maximum number of redirects exceeded", - RedirectionError -); -var MaxBodyLengthExceededError = createErrorType( - "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", - "Request body larger than maxBodyLength limit" -); -var WriteAfterEndError = createErrorType( - "ERR_STREAM_WRITE_AFTER_END", - "write after end" -); - -// istanbul ignore next -var destroy = Writable.prototype.destroy || noop; - -// An HTTP(S) request that can be redirected -function RedirectableRequest(options, responseCallback) { - // Initialize the request - Writable.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; - - // Attach a callback if passed - if (responseCallback) { - this.on("response", responseCallback); - } - - // React to responses of native requests - var self = this; - this._onNativeResponse = function (response) { - try { - self._processResponse(response); - } - catch (cause) { - self.emit("error", cause instanceof RedirectionError ? - cause : new RedirectionError({ cause: cause })); - } - }; - - // Perform the first request - this._performRequest(); -} -RedirectableRequest.prototype = Object.create(Writable.prototype); - -RedirectableRequest.prototype.abort = function () { - destroyRequest(this._currentRequest); - this._currentRequest.abort(); - this.emit("abort"); -}; - -RedirectableRequest.prototype.destroy = function (error) { - destroyRequest(this._currentRequest, error); - destroy.call(this, error); - return this; -}; - -// Writes buffered data to the current native request -RedirectableRequest.prototype.write = function (data, encoding, callback) { - // Writing is not allowed if end has been called - if (this._ending) { - throw new WriteAfterEndError(); - } - - // Validate input and shift parameters if necessary - if (!isString(data) && !isBuffer(data)) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (isFunction(encoding)) { - callback = encoding; - encoding = null; - } - - // Ignore empty buffers, since writing them doesn't invoke the callback - // https://github.com/nodejs/node/issues/22066 - if (data.length === 0) { - if (callback) { - callback(); - } - return; - } - // Only write when we don't exceed the maximum body length - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data: data, encoding: encoding }); - this._currentRequest.write(data, encoding, callback); - } - // Error when we exceed the maximum body length - else { - this.emit("error", new MaxBodyLengthExceededError()); - this.abort(); - } -}; - -// Ends the current native request -RedirectableRequest.prototype.end = function (data, encoding, callback) { - // Shift parameters if necessary - if (isFunction(data)) { - callback = data; - data = encoding = null; - } - else if (isFunction(encoding)) { - callback = encoding; - encoding = null; - } - - // Write data if needed and end - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } - else { - var self = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function () { - self._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; - } -}; - -// Sets a header value on the current native request -RedirectableRequest.prototype.setHeader = function (name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); -}; - -// Clears a header value on the current native request -RedirectableRequest.prototype.removeHeader = function (name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); -}; - -// Global timeout for all underlying requests -RedirectableRequest.prototype.setTimeout = function (msecs, callback) { - var self = this; - - // Destroys the socket on timeout - function destroyOnTimeout(socket) { - socket.setTimeout(msecs); - socket.removeListener("timeout", socket.destroy); - socket.addListener("timeout", socket.destroy); - } - - // Sets up a timer to trigger a timeout event - function startTimer(socket) { - if (self._timeout) { - clearTimeout(self._timeout); - } - self._timeout = setTimeout(function () { - self.emit("timeout"); - clearTimer(); - }, msecs); - destroyOnTimeout(socket); - } - - // Stops a timeout from triggering - function clearTimer() { - // Clear the timeout - if (self._timeout) { - clearTimeout(self._timeout); - self._timeout = null; - } - - // Clean up all attached listeners - self.removeListener("abort", clearTimer); - self.removeListener("error", clearTimer); - self.removeListener("response", clearTimer); - self.removeListener("close", clearTimer); - if (callback) { - self.removeListener("timeout", callback); - } - if (!self.socket) { - self._currentRequest.removeListener("socket", startTimer); - } - } - - // Attach callback if passed - if (callback) { - this.on("timeout", callback); - } - - // Start the timer if or when the socket is opened - if (this.socket) { - startTimer(this.socket); - } - else { - this._currentRequest.once("socket", startTimer); - } - - // Clean up on events - this.on("socket", destroyOnTimeout); - this.on("abort", clearTimer); - this.on("error", clearTimer); - this.on("response", clearTimer); - this.on("close", clearTimer); - - return this; -}; - -// Proxy all other public ClientRequest methods -[ - "flushHeaders", "getHeader", - "setNoDelay", "setSocketKeepAlive", -].forEach(function (method) { - RedirectableRequest.prototype[method] = function (a, b) { - return this._currentRequest[method](a, b); - }; -}); - -// Proxy all public ClientRequest properties -["aborted", "connection", "socket"].forEach(function (property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function () { return this._currentRequest[property]; }, - }); -}); - -RedirectableRequest.prototype._sanitizeOptions = function (options) { - // Ensure headers are always present - if (!options.headers) { - options.headers = {}; - } - - // Since http.request treats host as an alias of hostname, - // but the url module interprets host as hostname plus port, - // eliminate the host property to avoid confusion. - if (options.host) { - // Use hostname if set, because it has precedence - if (!options.hostname) { - options.hostname = options.host; - } - delete options.host; - } - - // Complete the URL object when necessary - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } - else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); - } - } -}; - - -// Executes the next native request (initial or redirect) -RedirectableRequest.prototype._performRequest = function () { - // Load the native protocol - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - throw new TypeError("Unsupported protocol " + protocol); - } - - // If specified, use the agent corresponding to the protocol - // (HTTP and HTTPS use different types of agents) - if (this._options.agents) { - var scheme = protocol.slice(0, -1); - this._options.agent = this._options.agents[scheme]; - } - - // Create the native request and set up its event handlers - var request = this._currentRequest = - nativeProtocol.request(this._options, this._onNativeResponse); - request._redirectable = this; - for (var event of events) { - request.on(event, eventHandlers[event]); - } - - // RFC7230§5.3.1: When making a request directly to an origin server, […] - // a client MUST send only the absolute path […] as the request-target. - this._currentUrl = /^\//.test(this._options.path) ? - url.format(this._options) : - // When making a request to a proxy, […] - // a client MUST send the target URI in absolute-form […]. - this._options.path; - - // End a redirected request - // (The first request must be ended explicitly with RedirectableRequest#end) - if (this._isRedirect) { - // Write the request entity and end - var i = 0; - var self = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - // Only write if this request has not been redirected yet - /* istanbul ignore else */ - if (request === self._currentRequest) { - // Report any write errors - /* istanbul ignore if */ - if (error) { - self.emit("error", error); - } - // Write the next buffer if there are still left - else if (i < buffers.length) { - var buffer = buffers[i++]; - /* istanbul ignore else */ - if (!request.finished) { - request.write(buffer.data, buffer.encoding, writeNext); - } - } - // End the request if `end` has been called on us - else if (self._ended) { - request.end(); - } - } - }()); - } -}; - -// Processes a response from the current native request -RedirectableRequest.prototype._processResponse = function (response) { - // Store the redirected response - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode: statusCode, - }); - } - - // RFC7231§6.4: The 3xx (Redirection) class of status code indicates - // that further action needs to be taken by the user agent in order to - // fulfill the request. If a Location header field is provided, - // the user agent MAY automatically redirect its request to the URI - // referenced by the Location field value, - // even if the specific status code is not understood. - - // If the response is not a redirect; return it as-is - var location = response.headers.location; - if (!location || this._options.followRedirects === false || - statusCode < 300 || statusCode >= 400) { - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); - - // Clean up - this._requestBodyBuffers = []; - return; - } - - // The response is a redirect, so abort the current request - destroyRequest(this._currentRequest); - // Discard the remainder of the response to avoid waiting for data - response.destroy(); - - // RFC7231§6.4: A client SHOULD detect and intervene - // in cyclical redirections (i.e., "infinite" redirection loops). - if (++this._redirectCount > this._options.maxRedirects) { - throw new TooManyRedirectsError(); - } - - // Store the request headers if applicable - var requestHeaders; - var beforeRedirect = this._options.beforeRedirect; - if (beforeRedirect) { - requestHeaders = Object.assign({ - // The Host header was set by nativeProtocol.request - Host: response.req.getHeader("host"), - }, this._options.headers); - } - - // RFC7231§6.4: Automatic redirection needs to done with - // care for methods not known to be safe, […] - // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change - // the request method from POST to GET for the subsequent request. - var method = this._options.method; - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || - // RFC7231§6.4.4: The 303 (See Other) status code indicates that - // the server is redirecting the user agent to a different resource […] - // A user agent can perform a retrieval request targeting that URI - // (a GET or HEAD request if using HTTP) […] - (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - // Drop a possible entity and headers related to it - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } - - // Drop the Host header, as the redirect might lead to a different host - var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); - - // If the redirect is relative, carry over the host of the last request - var currentUrlParts = parseUrl(this._currentUrl); - var currentHost = currentHostHeader || currentUrlParts.host; - var currentUrl = /^\w+:/.test(location) ? this._currentUrl : - url.format(Object.assign(currentUrlParts, { host: currentHost })); - - // Create the redirected request - var redirectUrl = resolveUrl(location, currentUrl); - debug$5("redirecting to", redirectUrl.href); - this._isRedirect = true; - spreadUrlObject(redirectUrl, this._options); - - // Drop confidential headers when redirecting to a less secure protocol - // or to a different domain that is not a superdomain - if (redirectUrl.protocol !== currentUrlParts.protocol && - redirectUrl.protocol !== "https:" || - redirectUrl.host !== currentHost && - !isSubdomain(redirectUrl.host, currentHost)) { - removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers); - } - - // Evaluate the beforeRedirect callback - if (isFunction(beforeRedirect)) { - var responseDetails = { - headers: response.headers, - statusCode: statusCode, - }; - var requestDetails = { - url: currentUrl, - method: method, - headers: requestHeaders, - }; - beforeRedirect(this._options, responseDetails, requestDetails); - this._sanitizeOptions(this._options); - } - - // Perform the redirected request - this._performRequest(); -}; - -// Wraps the key/value object of protocols with redirect functionality -function wrap(protocols) { - // Default settings - var exports = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024, - }; - - // Wrap each protocol - var nativeProtocols = {}; - Object.keys(protocols).forEach(function (scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); - - // Executes a request, following redirects - function request(input, options, callback) { - // Parse parameters, ensuring that input is an object - if (isURL(input)) { - input = spreadUrlObject(input); - } - else if (isString(input)) { - input = spreadUrlObject(parseUrl(input)); - } - else { - callback = options; - options = validateUrl(input); - input = { protocol: protocol }; - } - if (isFunction(options)) { - callback = options; - options = null; - } - - // Set defaults - options = Object.assign({ - maxRedirects: exports.maxRedirects, - maxBodyLength: exports.maxBodyLength, - }, input, options); - options.nativeProtocols = nativeProtocols; - if (!isString(options.host) && !isString(options.hostname)) { - options.hostname = "::1"; - } - - assert.equal(options.protocol, protocol, "protocol mismatch"); - debug$5("options", options); - return new RedirectableRequest(options, callback); - } - - // Executes a GET request, following redirects - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; - } - - // Expose the properties on the wrapped protocol - Object.defineProperties(wrappedProtocol, { - request: { value: request, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true }, - }); - }); - return exports; -} - -function noop() { /* empty */ } - -function parseUrl(input) { - var parsed; - /* istanbul ignore else */ - if (useNativeURL) { - parsed = new URL$1(input); - } - else { - // Ensure the URL is valid and absolute - parsed = validateUrl(url.parse(input)); - if (!isString(parsed.protocol)) { - throw new InvalidUrlError({ input }); - } - } - return parsed; -} - -function resolveUrl(relative, base) { - /* istanbul ignore next */ - return useNativeURL ? new URL$1(relative, base) : parseUrl(url.resolve(base, relative)); -} - -function validateUrl(input) { - if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { - throw new InvalidUrlError({ input: input.href || input }); - } - if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { - throw new InvalidUrlError({ input: input.href || input }); - } - return input; -} - -function spreadUrlObject(urlObject, target) { - var spread = target || {}; - for (var key of preservedUrlFields) { - spread[key] = urlObject[key]; - } - - // Fix IPv6 hostname - if (spread.hostname.startsWith("[")) { - spread.hostname = spread.hostname.slice(1, -1); - } - // Ensure port is a number - if (spread.port !== "") { - spread.port = Number(spread.port); - } - // Concatenate path - spread.path = spread.search ? spread.pathname + spread.search : spread.pathname; - - return spread; -} - -function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; - } - } - return (lastValue === null || typeof lastValue === "undefined") ? - undefined : String(lastValue).trim(); -} - -function createErrorType(code, message, baseClass) { - // Create constructor - function CustomError(properties) { - Error.captureStackTrace(this, this.constructor); - Object.assign(this, properties || {}); - this.code = code; - this.message = this.cause ? message + ": " + this.cause.message : message; - } - - // Attach constructor and set default properties - CustomError.prototype = new (baseClass || Error)(); - Object.defineProperties(CustomError.prototype, { - constructor: { - value: CustomError, - enumerable: false, - }, - name: { - value: "Error [" + code + "]", - enumerable: false, - }, - }); - return CustomError; -} - -function destroyRequest(request, error) { - for (var event of events) { - request.removeListener(event, eventHandlers[event]); - } - request.on("error", noop); - request.destroy(error); -} - -function isSubdomain(subdomain, domain) { - assert(isString(subdomain) && isString(domain)); - var dot = subdomain.length - domain.length - 1; - return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); -} - -function isString(value) { - return typeof value === "string" || value instanceof String; -} - -function isFunction(value) { - return typeof value === "function"; -} - -function isBuffer(value) { - return typeof value === "object" && ("length" in value); -} - -function isURL(value) { - return URL$1 && value instanceof URL$1; -} - -// Exports -followRedirects$1.exports = wrap({ http: http$1, https: https$1 }); -followRedirects$1.exports.wrap = wrap; - -var followRedirectsExports = followRedirects$1.exports; - -var httpNative = require$$1, - httpsNative = require$$1$1, - web_o = webOutgoing, - common$1 = common$3, - followRedirects = followRedirectsExports; - -web_o = Object.keys(web_o).map(function(pass) { - return web_o[pass]; -}); - -var nativeAgents = { http: httpNative, https: httpsNative }; - -/*! - * Array of passes. - * - * A `pass` is just a function that is executed on `req, res, options` - * so that you can easily add new checks while still keeping the base - * flexible. - */ - - -var webIncoming = { - - /** - * Sets `content-length` to '0' if request is of DELETE type. - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {Object} Options Config object passed to the proxy - * - * @api private - */ - - deleteLength: function deleteLength(req, res, options) { - if((req.method === 'DELETE' || req.method === 'OPTIONS') - && !req.headers['content-length']) { - req.headers['content-length'] = '0'; - delete req.headers['transfer-encoding']; - } - }, - - /** - * Sets timeout in request socket if it was specified in options. - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {Object} Options Config object passed to the proxy - * - * @api private - */ - - timeout: function timeout(req, res, options) { - if(options.timeout) { - req.socket.setTimeout(options.timeout); - } - }, - - /** - * Sets `x-forwarded-*` headers if specified in config. - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {Object} Options Config object passed to the proxy - * - * @api private - */ - - XHeaders: function XHeaders(req, res, options) { - if(!options.xfwd) return; - - var encrypted = req.isSpdy || common$1.hasEncryptedConnection(req); - var values = { - for : req.connection.remoteAddress || req.socket.remoteAddress, - port : common$1.getPort(req), - proto: encrypted ? 'https' : 'http' - }; - - ['for', 'port', 'proto'].forEach(function(header) { - req.headers['x-forwarded-' + header] = - (req.headers['x-forwarded-' + header] || '') + - (req.headers['x-forwarded-' + header] ? ',' : '') + - values[header]; - }); - - req.headers['x-forwarded-host'] = req.headers['x-forwarded-host'] || req.headers['host'] || ''; - }, - - /** - * Does the actual proxying. If `forward` is enabled fires up - * a ForwardStream, same happens for ProxyStream. The request - * just dies otherwise. - * - * @param {ClientRequest} Req Request object - * @param {IncomingMessage} Res Response object - * @param {Object} Options Config object passed to the proxy - * - * @api private - */ - - stream: function stream(req, res, options, _, server, clb) { - - // And we begin! - server.emit('start', req, res, options.target || options.forward); - - var agents = options.followRedirects ? followRedirects : nativeAgents; - var http = agents.http; - var https = agents.https; - - if(options.forward) { - // If forward enable, so just pipe the request - var forwardReq = (options.forward.protocol === 'https:' ? https : http).request( - common$1.setupOutgoing(options.ssl || {}, options, req, 'forward') - ); - - // error handler (e.g. ECONNRESET, ECONNREFUSED) - // Handle errors on incoming request as well as it makes sense to - var forwardError = createErrorHandler(forwardReq, options.forward); - req.on('error', forwardError); - forwardReq.on('error', forwardError); - - (options.buffer || req).pipe(forwardReq); - if(!options.target) { return res.end(); } - } - - // Request initalization - var proxyReq = (options.target.protocol === 'https:' ? https : http).request( - common$1.setupOutgoing(options.ssl || {}, options, req) - ); - - // Enable developers to modify the proxyReq before headers are sent - proxyReq.on('socket', function(socket) { - if(server && !proxyReq.getHeader('expect')) { - server.emit('proxyReq', proxyReq, req, res, options); - } - }); - - // allow outgoing socket to timeout so that we could - // show an error page at the initial request - if(options.proxyTimeout) { - proxyReq.setTimeout(options.proxyTimeout, function() { - proxyReq.abort(); - }); - } - - // Ensure we abort proxy if request is aborted - req.on('aborted', function () { - proxyReq.abort(); - }); - - // handle errors in proxy and incoming request, just like for forward proxy - var proxyError = createErrorHandler(proxyReq, options.target); - req.on('error', proxyError); - proxyReq.on('error', proxyError); - - function createErrorHandler(proxyReq, url) { - return function proxyError(err) { - if (req.socket.destroyed && err.code === 'ECONNRESET') { - server.emit('econnreset', err, req, res, url); - return proxyReq.abort(); - } - - if (clb) { - clb(err, req, res, url); - } else { - server.emit('error', err, req, res, url); - } - } - } - - (options.buffer || req).pipe(proxyReq); - - proxyReq.on('response', function(proxyRes) { - if(server) { server.emit('proxyRes', proxyRes, req, res); } - - if(!res.headersSent && !options.selfHandleResponse) { - for(var i=0; i < web_o.length; i++) { - if(web_o[i](req, res, proxyRes, options)) { break; } - } - } - - if (!res.finished) { - // Allow us to listen when the proxy has completed - proxyRes.on('end', function () { - if (server) server.emit('end', req, res, proxyRes); - }); - // We pipe to the response unless its expected to be handled by the user - if (!options.selfHandleResponse) proxyRes.pipe(res); - } else { - if (server) server.emit('end', req, res, proxyRes); - } - }); - } - -}; - -var http = require$$1, - https = require$$1$1, - common = common$3; - -/*! - * Array of passes. - * - * A `pass` is just a function that is executed on `req, socket, options` - * so that you can easily add new checks while still keeping the base - * flexible. - */ - -/* - * Websockets Passes - * - */ - - -var wsIncoming = { - /** - * WebSocket requests must have the `GET` method and - * the `upgrade:websocket` header - * - * @param {ClientRequest} Req Request object - * @param {Socket} Websocket - * - * @api private - */ - - checkMethodAndHeader : function checkMethodAndHeader(req, socket) { - if (req.method !== 'GET' || !req.headers.upgrade) { - socket.destroy(); - return true; - } - - if (req.headers.upgrade.toLowerCase() !== 'websocket') { - socket.destroy(); - return true; - } - }, - - /** - * Sets `x-forwarded-*` headers if specified in config. - * - * @param {ClientRequest} Req Request object - * @param {Socket} Websocket - * @param {Object} Options Config object passed to the proxy - * - * @api private - */ - - XHeaders : function XHeaders(req, socket, options) { - if(!options.xfwd) return; - - var values = { - for : req.connection.remoteAddress || req.socket.remoteAddress, - port : common.getPort(req), - proto: common.hasEncryptedConnection(req) ? 'wss' : 'ws' - }; - - ['for', 'port', 'proto'].forEach(function(header) { - req.headers['x-forwarded-' + header] = - (req.headers['x-forwarded-' + header] || '') + - (req.headers['x-forwarded-' + header] ? ',' : '') + - values[header]; - }); - }, - - /** - * Does the actual proxying. Make the request and upgrade it - * send the Switching Protocols request and pipe the sockets. - * - * @param {ClientRequest} Req Request object - * @param {Socket} Websocket - * @param {Object} Options Config object passed to the proxy - * - * @api private - */ - stream : function stream(req, socket, options, head, server, clb) { - - var createHttpHeader = function(line, headers) { - return Object.keys(headers).reduce(function (head, key) { - var value = headers[key]; - - if (!Array.isArray(value)) { - head.push(key + ': ' + value); - return head; - } - - for (var i = 0; i < value.length; i++) { - head.push(key + ': ' + value[i]); - } - return head; - }, [line]) - .join('\r\n') + '\r\n\r\n'; - }; - - common.setupSocket(socket); - - if (head && head.length) socket.unshift(head); - - - var proxyReq = (common.isSSL.test(options.target.protocol) ? https : http).request( - common.setupOutgoing(options.ssl || {}, options, req) - ); - - // Enable developers to modify the proxyReq before headers are sent - if (server) { server.emit('proxyReqWs', proxyReq, req, socket, options, head); } - - // Error Handler - proxyReq.on('error', onOutgoingError); - proxyReq.on('response', function (res) { - // if upgrade event isn't going to happen, close the socket - if (!res.upgrade) { - socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers)); - res.pipe(socket); - } - }); - - proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) { - proxySocket.on('error', onOutgoingError); - - // Allow us to listen when the websocket has completed - proxySocket.on('end', function () { - server.emit('close', proxyRes, proxySocket, proxyHead); - }); - - // The pipe below will end proxySocket if socket closes cleanly, but not - // if it errors (eg, vanishes from the net and starts returning - // EHOSTUNREACH). We need to do that explicitly. - socket.on('error', function () { - proxySocket.end(); - }); - - common.setupSocket(proxySocket); - - if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead); - - // - // Remark: Handle writing the headers to the socket when switching protocols - // Also handles when a header is an array - // - socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers)); - - proxySocket.pipe(socket).pipe(proxySocket); - - server.emit('open', proxySocket); - server.emit('proxySocket', proxySocket); //DEPRECATED. - }); - - return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT - - function onOutgoingError(err) { - if (clb) { - clb(err, req, socket); - } else { - server.emit('error', err, req, socket); - } - socket.end(); - } - } -}; - -(function (module) { - var httpProxy = module.exports, - parse_url = require$$0$9.parse, - EE3 = eventemitter3Exports, - http = require$$1, - https = require$$1$1, - web = webIncoming, - ws = wsIncoming; - - httpProxy.Server = ProxyServer; - - /** - * Returns a function that creates the loader for - * either `ws` or `web`'s passes. - * - * Examples: - * - * httpProxy.createRightProxy('ws') - * // => [Function] - * - * @param {String} Type Either 'ws' or 'web' - *  - * @return {Function} Loader Function that when called returns an iterator for the right passes - * - * @api private - */ - - function createRightProxy(type) { - - return function(options) { - return function(req, res /*, [head], [opts] */) { - var passes = (type === 'ws') ? this.wsPasses : this.webPasses, - args = [].slice.call(arguments), - cntr = args.length - 1, - head, cbl; - - /* optional args parse begin */ - if(typeof args[cntr] === 'function') { - cbl = args[cntr]; - - cntr--; - } - - var requestOptions = options; - if( - !(args[cntr] instanceof Buffer) && - args[cntr] !== res - ) { - //Copy global options - requestOptions = Object.assign({}, options); - //Overwrite with request options - Object.assign(requestOptions, args[cntr]); - - cntr--; - } - - if(args[cntr] instanceof Buffer) { - head = args[cntr]; - } - - /* optional args parse end */ - - ['target', 'forward'].forEach(function(e) { - if (typeof requestOptions[e] === 'string') - requestOptions[e] = parse_url(requestOptions[e]); - }); - - if (!requestOptions.target && !requestOptions.forward) { - return this.emit('error', new Error('Must provide a proper URL as target')); - } - - for(var i=0; i < passes.length; i++) { - /** - * Call of passes functions - * pass(req, res, options, head) - * - * In WebSockets case the `res` variable - * refer to the connection socket - * pass(req, socket, options, head) - */ - if(passes[i](req, res, requestOptions, head, this, cbl)) { // passes can return a truthy value to halt the loop - break; - } - } - }; - }; - } - httpProxy.createRightProxy = createRightProxy; - - function ProxyServer(options) { - EE3.call(this); - - options = options || {}; - options.prependPath = options.prependPath === false ? false : true; - - this.web = this.proxyRequest = createRightProxy('web')(options); - this.ws = this.proxyWebsocketRequest = createRightProxy('ws')(options); - this.options = options; - - this.webPasses = Object.keys(web).map(function(pass) { - return web[pass]; - }); - - this.wsPasses = Object.keys(ws).map(function(pass) { - return ws[pass]; - }); - - this.on('error', this.onError, this); - - } - - require$$0$5.inherits(ProxyServer, EE3); - - ProxyServer.prototype.onError = function (err) { - // - // Remark: Replicate node core behavior using EE3 - // so we force people to handle their own errors - // - if(this.listeners('error').length === 1) { - throw err; - } - }; - - ProxyServer.prototype.listen = function(port, hostname) { - var self = this, - closure = function(req, res) { self.web(req, res); }; - - this._server = this.options.ssl ? - https.createServer(this.options.ssl, closure) : - http.createServer(closure); - - if(this.options.ws) { - this._server.on('upgrade', function(req, socket, head) { self.ws(req, socket, head); }); - } - - this._server.listen(port, hostname); - - return this; - }; - - ProxyServer.prototype.close = function(callback) { - var self = this; - if (this._server) { - this._server.close(done); - } - - // Wrap callback to nullify server after all open connections are closed. - function done() { - self._server = null; - if (callback) { - callback.apply(null, arguments); - } - } }; - - ProxyServer.prototype.before = function(type, passName, callback) { - if (type !== 'ws' && type !== 'web') { - throw new Error('type must be `web` or `ws`'); - } - var passes = (type === 'ws') ? this.wsPasses : this.webPasses, - i = false; - - passes.forEach(function(v, idx) { - if(v.name === passName) i = idx; - }); - - if(i === false) throw new Error('No such pass'); - - passes.splice(i, 0, callback); - }; - ProxyServer.prototype.after = function(type, passName, callback) { - if (type !== 'ws' && type !== 'web') { - throw new Error('type must be `web` or `ws`'); - } - var passes = (type === 'ws') ? this.wsPasses : this.webPasses, - i = false; - - passes.forEach(function(v, idx) { - if(v.name === passName) i = idx; - }); - - if(i === false) throw new Error('No such pass'); - - passes.splice(i++, 0, callback); - }; -} (httpProxy$3)); - -var httpProxyExports = httpProxy$3.exports; - -// Use explicit /index.js to help browserify negociation in require '/lib/http-proxy' (!) -var ProxyServer = httpProxyExports.Server; - - -/** - * Creates the proxy server. - * - * Examples: - * - * httpProxy.createProxyServer({ .. }, 8000) - * // => '{ web: [Function], ws: [Function] ... }' - * - * @param {Object} Options Config object passed to the proxy - * - * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests - * - * @api public - */ - - -function createProxyServer(options) { - /* - * `options` is needed and it must have the following layout: - * - * { - * target : - * forward: - * agent : - * ssl : - * ws : - * xfwd : - * secure : - * toProxy: - * prependPath: - * ignorePath: - * localAddress : - * changeOrigin: - * preserveHeaderKeyCase: - * auth : Basic authentication i.e. 'user:password' to compute an Authorization header. - * hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects, Default: null. - * autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false. - * protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null. - * } - * - * NOTE: `options.ws` and `options.ssl` are optional. - * `options.target and `options.forward` cannot be - * both missing - * } - */ - - return new ProxyServer(options); -} - - -ProxyServer.createProxyServer = createProxyServer; -ProxyServer.createServer = createProxyServer; -ProxyServer.createProxy = createProxyServer; - - - - -/** - * Export the proxy "Server" as the main export. - */ -var httpProxy$2 = ProxyServer; - -/*! - * Caron dimonio, con occhi di bragia - * loro accennando, tutte le raccoglie; - * batte col remo qualunque s’adagia - * - * Charon the demon, with the eyes of glede, - * Beckoning to them, collects them all together, - * Beats with his oar whoever lags behind - * - * Dante - The Divine Comedy (Canto III) - */ - -var httpProxy = httpProxy$2; - -var httpProxy$1 = /*@__PURE__*/getDefaultExportFromCjs(httpProxy); - -const debug$4 = createDebugger("vite:proxy"); -const rewriteOriginHeader = (proxyReq, options, config) => { - if (options.rewriteWsOrigin) { - const { target } = options; - if (proxyReq.headersSent) { - config.logger.warn( - colors$1.yellow( - `Unable to rewrite Origin header as headers are already sent.` - ) - ); - return; - } - if (proxyReq.getHeader("origin") && target) { - const changedOrigin = typeof target === "object" ? `${target.protocol}//${target.host}` : target; - proxyReq.setHeader("origin", changedOrigin); - } - } -}; -function proxyMiddleware(httpServer, options, config) { - const proxies = {}; - Object.keys(options).forEach((context) => { - let opts = options[context]; - if (!opts) { - return; - } - if (typeof opts === "string") { - opts = { target: opts, changeOrigin: true }; - } - const proxy = httpProxy$1.createProxyServer(opts); - if (opts.configure) { - opts.configure(proxy, opts); - } - proxy.on("error", (err, req, originalRes) => { - const res = originalRes; - if (!res) { - config.logger.error( - `${colors$1.red(`http proxy error: ${err.message}`)} -${err.stack}`, - { - timestamp: true, - error: err - } - ); - } else if ("req" in res) { - config.logger.error( - `${colors$1.red(`http proxy error: ${originalRes.req.url}`)} -${err.stack}`, - { - timestamp: true, - error: err - } - ); - if (!res.headersSent && !res.writableEnded) { - res.writeHead(500, { - "Content-Type": "text/plain" - }).end(); - } - } else { - config.logger.error(`${colors$1.red(`ws proxy error:`)} -${err.stack}`, { - timestamp: true, - error: err - }); - res.end(); - } - }); - proxy.on("proxyReqWs", (proxyReq, req, socket, options2, head) => { - rewriteOriginHeader(proxyReq, options2, config); - socket.on("error", (err) => { - config.logger.error( - `${colors$1.red(`ws proxy socket error:`)} -${err.stack}`, - { - timestamp: true, - error: err - } - ); - }); - }); - proxy.on("proxyRes", (proxyRes, req, res) => { - res.on("close", () => { - if (!res.writableEnded) { - debug$4?.("destroying proxyRes in proxyRes close event"); - proxyRes.destroy(); - } - }); - }); - proxies[context] = [proxy, { ...opts }]; - }); - if (httpServer) { - httpServer.on("upgrade", (req, socket, head) => { - const url = req.url; - for (const context in proxies) { - if (doesProxyContextMatchUrl(context, url)) { - const [proxy, opts] = proxies[context]; - if (opts.ws || opts.target?.toString().startsWith("ws:") || opts.target?.toString().startsWith("wss:")) { - if (opts.rewrite) { - req.url = opts.rewrite(url); - } - debug$4?.(`${req.url} -> ws ${opts.target}`); - proxy.ws(req, socket, head); - return; - } - } - } - }); - } - return function viteProxyMiddleware(req, res, next) { - const url = req.url; - for (const context in proxies) { - if (doesProxyContextMatchUrl(context, url)) { - const [proxy, opts] = proxies[context]; - const options2 = {}; - if (opts.bypass) { - const bypassResult = opts.bypass(req, res, opts); - if (typeof bypassResult === "string") { - req.url = bypassResult; - debug$4?.(`bypass: ${req.url} -> ${bypassResult}`); - return next(); - } else if (bypassResult === false) { - debug$4?.(`bypass: ${req.url} -> 404`); - res.statusCode = 404; - return res.end(); - } - } - debug$4?.(`${req.url} -> ${opts.target || opts.forward}`); - if (opts.rewrite) { - req.url = opts.rewrite(req.url); - } - proxy.web(req, res, options2); - return; - } - } - next(); - }; -} -function doesProxyContextMatchUrl(context, url) { - return context[0] === "^" && new RegExp(context).test(url) || url.startsWith(context); -} - -const debug$3 = createDebugger("vite:html-fallback"); -function htmlFallbackMiddleware(root, spaFallback, fsUtils = commonFsUtils) { - return function viteHtmlFallbackMiddleware(req, res, next) { - if ( - // Only accept GET or HEAD - req.method !== "GET" && req.method !== "HEAD" || // Exclude default favicon requests - req.url === "/favicon.ico" || // Require Accept: text/html or */* - !(req.headers.accept === void 0 || // equivalent to `Accept: */*` - req.headers.accept === "" || // equivalent to `Accept: */*` - req.headers.accept.includes("text/html") || req.headers.accept.includes("*/*")) - ) { - return next(); - } - const url = cleanUrl(req.url); - const pathname = decodeURIComponent(url); - if (pathname.endsWith(".html")) { - const filePath = path$n.join(root, pathname); - if (fsUtils.existsSync(filePath)) { - debug$3?.(`Rewriting ${req.method} ${req.url} to ${url}`); - req.url = url; - return next(); - } - } else if (pathname[pathname.length - 1] === "/") { - const filePath = path$n.join(root, pathname, "index.html"); - if (fsUtils.existsSync(filePath)) { - const newUrl = url + "index.html"; - debug$3?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`); - req.url = newUrl; - return next(); - } - } else { - const filePath = path$n.join(root, pathname + ".html"); - if (fsUtils.existsSync(filePath)) { - const newUrl = url + ".html"; - debug$3?.(`Rewriting ${req.method} ${req.url} to ${newUrl}`); - req.url = newUrl; - return next(); - } - } - if (spaFallback) { - debug$3?.(`Rewriting ${req.method} ${req.url} to /index.html`); - req.url = "/index.html"; - } - next(); - }; -} - -const debug$2 = createDebugger("vite:send", { - onlyWhenFocused: true -}); -const alias = { - js: "text/javascript", - css: "text/css", - html: "text/html", - json: "application/json" -}; -function send(req, res, content, type, options) { - const { - etag = getEtag(content, { weak: true }), - cacheControl = "no-cache", - headers, - map - } = options; - if (res.writableEnded) { - return; - } - if (req.headers["if-none-match"] === etag) { - res.statusCode = 304; - res.end(); - return; - } - res.setHeader("Content-Type", alias[type] || type); - res.setHeader("Cache-Control", cacheControl); - res.setHeader("Etag", etag); - if (headers) { - for (const name in headers) { - res.setHeader(name, headers[name]); - } - } - if (map && "version" in map && map.mappings) { - if (type === "js" || type === "css") { - content = getCodeWithSourcemap(type, content.toString(), map); - } - } else if (type === "js" && (!map || map.mappings !== "")) { - const code = content.toString(); - if (convertSourceMap.mapFileCommentRegex.test(code)) { - debug$2?.(`Skipped injecting fallback sourcemap for ${req.url}`); - } else { - const urlWithoutTimestamp = removeTimestampQuery(req.url); - const ms = new MagicString(code); - content = getCodeWithSourcemap( - type, - code, - ms.generateMap({ - source: path$n.basename(urlWithoutTimestamp), - hires: "boundary", - includeContent: true - }) - ); - } - } - res.statusCode = 200; - res.end(content); - return; -} - -const debugCache = createDebugger("vite:cache"); -const knownIgnoreList = /* @__PURE__ */ new Set(["/", "/favicon.ico"]); -const trailingQuerySeparatorsRE = /[?&]+$/; -const urlRE = /[?&]url\b/; -const rawRE = /[?&]raw\b/; -const inlineRE = /[?&]inline\b/; -const svgRE = /\.svg\b/; -function deniedServingAccessForTransform(url, server, res, next) { - if (rawRE.test(url) || urlRE.test(url) || inlineRE.test(url) || svgRE.test(url)) { - const servingAccessResult = checkServingAccess(url, server); - if (servingAccessResult === "denied") { - respondWithAccessDenied(url, server, res); - return true; - } - if (servingAccessResult === "fallback") { - next(); - return true; - } - } - return false; -} -function cachedTransformMiddleware(server) { - return function viteCachedTransformMiddleware(req, res, next) { - const ifNoneMatch = req.headers["if-none-match"]; - if (ifNoneMatch) { - const moduleByEtag = server.moduleGraph.getModuleByEtag(ifNoneMatch); - if (moduleByEtag?.transformResult?.etag === ifNoneMatch && moduleByEtag?.url === req.url) { - const maybeMixedEtag = isCSSRequest(req.url); - if (!maybeMixedEtag) { - debugCache?.(`[304] ${prettifyUrl(req.url, server.config.root)}`); - res.statusCode = 304; - return res.end(); - } - } - } - next(); - }; -} -function transformMiddleware(server) { - const { root, publicDir } = server.config; - const publicDirInRoot = publicDir.startsWith(withTrailingSlash(root)); - const publicPath = `${publicDir.slice(root.length)}/`; - return async function viteTransformMiddleware(req, res, next) { - if (req.method !== "GET" || knownIgnoreList.has(req.url)) { - return next(); - } - let url; - try { - url = decodeURI(removeTimestampQuery(req.url)).replace( - NULL_BYTE_PLACEHOLDER, - "\0" - ); - } catch (e) { - return next(e); - } - const withoutQuery = cleanUrl(url); - try { - const isSourceMap = withoutQuery.endsWith(".map"); - if (isSourceMap) { - const depsOptimizer = getDepsOptimizer(server.config, false); - if (depsOptimizer?.isOptimizedDepUrl(url)) { - const sourcemapPath = url.startsWith(FS_PREFIX) ? fsPathFromId(url) : normalizePath$3(path$n.resolve(server.config.root, url.slice(1))); - try { - const map = JSON.parse( - await fsp.readFile(sourcemapPath, "utf-8") - ); - applySourcemapIgnoreList( - map, - sourcemapPath, - server.config.server.sourcemapIgnoreList, - server.config.logger - ); - return send(req, res, JSON.stringify(map), "json", { - headers: server.config.server.headers - }); - } catch (e) { - const dummySourceMap = { - version: 3, - file: sourcemapPath.replace(/\.map$/, ""), - sources: [], - sourcesContent: [], - names: [], - mappings: ";;;;;;;;;" - }; - return send(req, res, JSON.stringify(dummySourceMap), "json", { - cacheControl: "no-cache", - headers: server.config.server.headers - }); - } - } else { - const originalUrl = url.replace(/\.map($|\?)/, "$1"); - const map = (await server.moduleGraph.getModuleByUrl(originalUrl, false))?.transformResult?.map; - if (map) { - return send(req, res, JSON.stringify(map), "json", { - headers: server.config.server.headers - }); - } else { - return next(); - } - } - } - if (publicDirInRoot && url.startsWith(publicPath)) { - warnAboutExplicitPublicPathInUrl(url); - } - const urlWithoutTrailingQuerySeparators = url.replace( - trailingQuerySeparatorsRE, - "" - ); - if (deniedServingAccessForTransform( - urlWithoutTrailingQuerySeparators, - server, - res, - next - )) { - return; - } - if (isJSRequest(url) || isImportRequest(url) || isCSSRequest(url) || isHTMLProxy(url)) { - url = removeImportQuery(url); - url = unwrapId$1(url); - if (isCSSRequest(url)) { - if (req.headers.accept?.includes("text/css") && !isDirectRequest(url)) { - url = injectQuery(url, "direct"); - } - const ifNoneMatch = req.headers["if-none-match"]; - if (ifNoneMatch && (await server.moduleGraph.getModuleByUrl(url, false))?.transformResult?.etag === ifNoneMatch) { - debugCache?.(`[304] ${prettifyUrl(url, server.config.root)}`); - res.statusCode = 304; - return res.end(); - } - } - const result = await transformRequest(url, server, { - html: req.headers.accept?.includes("text/html"), - allowId(id) { - return !deniedServingAccessForTransform(id, server, res, next); - } - }); - if (result) { - const depsOptimizer = getDepsOptimizer(server.config, false); - const type = isDirectCSSRequest(url) ? "css" : "js"; - const isDep = DEP_VERSION_RE.test(url) || depsOptimizer?.isOptimizedDepUrl(url); - return send(req, res, result.code, type, { - etag: result.etag, - // allow browser to cache npm deps! - cacheControl: isDep ? "max-age=31536000,immutable" : "no-cache", - headers: server.config.server.headers, - map: result.map - }); - } - } - } catch (e) { - if (e?.code === ERR_OPTIMIZE_DEPS_PROCESSING_ERROR) { - if (!res.writableEnded) { - res.statusCode = 504; - res.statusMessage = "Optimize Deps Processing Error"; - res.end(); - } - server.config.logger.error(e.message); - return; - } - if (e?.code === ERR_OUTDATED_OPTIMIZED_DEP) { - if (!res.writableEnded) { - res.statusCode = 504; - res.statusMessage = "Outdated Optimize Dep"; - res.end(); - } - return; - } - if (e?.code === ERR_CLOSED_SERVER) { - if (!res.writableEnded) { - res.statusCode = 504; - res.statusMessage = "Outdated Request"; - res.end(); - } - return; - } - if (e?.code === ERR_FILE_NOT_FOUND_IN_OPTIMIZED_DEP_DIR) { - if (!res.writableEnded) { - res.statusCode = 404; - res.end(); - } - server.config.logger.warn(colors$1.yellow(e.message)); - return; - } - if (e?.code === ERR_LOAD_URL) { - return next(); - } - if (e?.code === ERR_DENIED_ID) { - return; - } - return next(e); - } - next(); - }; - function warnAboutExplicitPublicPathInUrl(url) { - let warning; - if (isImportRequest(url)) { - const rawUrl = removeImportQuery(url); - if (urlRE.test(url)) { - warning = `Assets in the public directory are served at the root path. -Instead of ${colors$1.cyan(rawUrl)}, use ${colors$1.cyan( - rawUrl.replace(publicPath, "/") - )}.`; - } else { - warning = `Assets in public directory cannot be imported from JavaScript. -If you intend to import that asset, put the file in the src directory, and use ${colors$1.cyan( - rawUrl.replace(publicPath, "/src/") - )} instead of ${colors$1.cyan(rawUrl)}. -If you intend to use the URL of that asset, use ${colors$1.cyan( - injectQuery(rawUrl.replace(publicPath, "/"), "url") - )}.`; - } - } else { - warning = `Files in the public directory are served at the root path. -Instead of ${colors$1.cyan(url)}, use ${colors$1.cyan( - url.replace(publicPath, "/") - )}.`; - } - server.config.logger.warn(colors$1.yellow(warning)); - } -} - -function createDevHtmlTransformFn(config) { - const [preHooks, normalHooks, postHooks] = resolveHtmlTransforms( - config.plugins, - config.logger - ); - const transformHooks = [ - preImportMapHook(config), - injectCspNonceMetaTagHook(config), - ...preHooks, - htmlEnvHook(config), - devHtmlHook, - ...normalHooks, - ...postHooks, - injectNonceAttributeTagHook(config), - postImportMapHook() - ]; - return (server, url, html, originalUrl) => { - return applyHtmlTransforms(html, transformHooks, { - path: url, - filename: getHtmlFilename(url, server), - server, - originalUrl - }); - }; -} -function getHtmlFilename(url, server) { - if (url.startsWith(FS_PREFIX)) { - return decodeURIComponent(fsPathFromId(url)); - } else { - return decodeURIComponent( - normalizePath$3(path$n.join(server.config.root, url.slice(1))) - ); - } -} -function shouldPreTransform(url, config) { - return !checkPublicFile(url, config) && (isJSRequest(url) || isCSSRequest(url)); -} -const wordCharRE = /\w/; -function isBareRelative(url) { - return wordCharRE.test(url[0]) && !url.includes(":"); -} -const isSrcSet = (attr) => attr.name === "srcset" && attr.prefix === void 0; -const processNodeUrl = (url, useSrcSetReplacer, config, htmlPath, originalUrl, server, isClassicScriptLink) => { - const replacer = (url2) => { - if (server?.moduleGraph) { - const mod = server.moduleGraph.urlToModuleMap.get(url2); - if (mod && mod.lastHMRTimestamp > 0) { - url2 = injectQuery(url2, `t=${mod.lastHMRTimestamp}`); - } - } - if (url2[0] === "/" && url2[1] !== "/" || // #3230 if some request url (localhost:3000/a/b) return to fallback html, the relative assets - // path will add `/a/` prefix, it will caused 404. - // - // skip if url contains `:` as it implies a url protocol or Windows path that we don't want to replace. - // - // rewrite `./index.js` -> `localhost:5173/a/index.js`. - // rewrite `../index.js` -> `localhost:5173/index.js`. - // rewrite `relative/index.js` -> `localhost:5173/a/relative/index.js`. - (url2[0] === "." || isBareRelative(url2)) && originalUrl && originalUrl !== "/" && htmlPath === "/index.html") { - url2 = path$n.posix.join(config.base, url2); - } - if (server && !isClassicScriptLink && shouldPreTransform(url2, config)) { - let preTransformUrl; - if (url2[0] === "/" && url2[1] !== "/") { - preTransformUrl = url2; - } else if (url2[0] === "." || isBareRelative(url2)) { - preTransformUrl = path$n.posix.join( - config.base, - path$n.posix.dirname(htmlPath), - url2 - ); - } - if (preTransformUrl) { - try { - preTransformUrl = decodeURI(preTransformUrl); - } catch (err) { - return url2; - } - preTransformRequest(server, preTransformUrl, config.decodedBase); - } - } - return url2; - }; - const processedUrl = useSrcSetReplacer ? processSrcSetSync(url, ({ url: url2 }) => replacer(url2)) : replacer(url); - return processedUrl; -}; -const devHtmlHook = async (html, { path: htmlPath, filename, server, originalUrl }) => { - const { config, moduleGraph, watcher } = server; - const base = config.base || "/"; - const decodedBase = config.decodedBase || "/"; - let proxyModulePath; - let proxyModuleUrl; - const trailingSlash = htmlPath.endsWith("/"); - if (!trailingSlash && getFsUtils(config).existsSync(filename)) { - proxyModulePath = htmlPath; - proxyModuleUrl = proxyModulePath; - } else { - const validPath = `${htmlPath}${trailingSlash ? "index.html" : ""}`; - proxyModulePath = `\0${validPath}`; - proxyModuleUrl = wrapId$1(proxyModulePath); - } - proxyModuleUrl = joinUrlSegments(decodedBase, proxyModuleUrl); - const s = new MagicString(html); - let inlineModuleIndex = -1; - const proxyCacheUrl = decodeURI( - cleanUrl(proxyModulePath).replace(normalizePath$3(config.root), "") - ); - const styleUrl = []; - const inlineStyles = []; - const addInlineModule = (node, ext) => { - inlineModuleIndex++; - const contentNode = node.childNodes[0]; - const code = contentNode.value; - let map; - if (proxyModulePath[0] !== "\0") { - map = new MagicString(html).snip( - contentNode.sourceCodeLocation.startOffset, - contentNode.sourceCodeLocation.endOffset - ).generateMap({ hires: "boundary" }); - map.sources = [filename]; - map.file = filename; - } - addToHTMLProxyCache(config, proxyCacheUrl, inlineModuleIndex, { code, map }); - const modulePath = `${proxyModuleUrl}?html-proxy&index=${inlineModuleIndex}.${ext}`; - const module = server?.moduleGraph.getModuleById(modulePath); - if (module) { - server?.moduleGraph.invalidateModule(module); - } - s.update( - node.sourceCodeLocation.startOffset, - node.sourceCodeLocation.endOffset, - `