diff --git a/dist/utils/date.util.cjs b/dist/utils/date.util.cjs index f16e708..0ab1066 100644 --- a/dist/utils/date.util.cjs +++ b/dist/utils/date.util.cjs @@ -22,6 +22,9 @@ __export(date_util_exports, { ONE_DAY: () => ONE_DAY, daysBetween: () => daysBetween, formatDate: () => formatDate, + getDayBegin: () => getDayBegin, + getMonthBegin: () => getMonthBegin, + getNDayAgo: () => getNDayAgo, nextday: () => nextday, yesterday: () => yesterday }); @@ -48,11 +51,33 @@ function daysBetween(date1, date2) { const diffInDays = Math.round(diffInMs / ONE_DAY); return diffInDays; } +var getDayBegin = (date) => { + const year = date.getFullYear(); + const month = date.getMonth(); + const day = date.getDate(); + return new Date(year, month, day); +}; +var getNDayAgo = (n, begin) => { + const date = new Date(Date.now() - n * 24 * 60 * 60 * 1e3); + if (begin) { + return getDayBegin(date); + } else { + return date; + } +}; +var getMonthBegin = (date) => { + const year = date.getFullYear(); + const month = date.getMonth(); + return new Date(year, month, 1); +}; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { ONE_DAY, daysBetween, formatDate, + getDayBegin, + getMonthBegin, + getNDayAgo, nextday, yesterday }); diff --git a/dist/utils/date.util.cjs.map b/dist/utils/date.util.cjs.map index 4e896d2..e564596 100644 --- a/dist/utils/date.util.cjs.map +++ b/dist/utils/date.util.cjs.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/utils/date.util.ts"],"sourcesContent":["export const ONE_DAY = 24 * 60 * 60 * 1000\n\n// format the date to the format we want\nexport const formatDate = (date: Date): string => {\n const year = date.getFullYear()\n const month = (date.getMonth() + 1 + '').padStart(2, '0')\n const day = (date.getDate() + '').padStart(2, '0')\n return `${year}${month}${day}`\n}\n\n// get formated datestring of yesterday\nexport const yesterday = (date?: Date) => {\n date = date || new Date()\n date.setDate(date.getDate() - 1)\n return date\n}\n\nexport const nextday = (date?: Date) => {\n date = date || new Date()\n date.setDate(date.getDate() + 1)\n return date\n}\n\n// calc days between two Date\nexport function daysBetween(date1: Date, date2: Date) {\n // hours*minutes*seconds*milliseconds\n const diffInMs = Math.abs(date1.getTime() - date2.getTime())\n const diffInDays = Math.round(diffInMs / ONE_DAY)\n return diffInDays\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,IAAM,UAAU,KAAK,KAAK,KAAK;AAG/B,IAAM,aAAa,CAAC,SAAuB;AAChD,QAAM,OAAO,KAAK,YAAY;AAC9B,QAAM,SAAS,KAAK,SAAS,IAAI,IAAI,IAAI,SAAS,GAAG,GAAG;AACxD,QAAM,OAAO,KAAK,QAAQ,IAAI,IAAI,SAAS,GAAG,GAAG;AACjD,SAAO,GAAG,IAAI,GAAG,KAAK,GAAG,GAAG;AAC9B;AAGO,IAAM,YAAY,CAAC,SAAgB;AACxC,SAAO,QAAQ,oBAAI,KAAK;AACxB,OAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC;AAC/B,SAAO;AACT;AAEO,IAAM,UAAU,CAAC,SAAgB;AACtC,SAAO,QAAQ,oBAAI,KAAK;AACxB,OAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC;AAC/B,SAAO;AACT;AAGO,SAAS,YAAY,OAAa,OAAa;AAEpD,QAAM,WAAW,KAAK,IAAI,MAAM,QAAQ,IAAI,MAAM,QAAQ,CAAC;AAC3D,QAAM,aAAa,KAAK,MAAM,WAAW,OAAO;AAChD,SAAO;AACT;","names":[]} \ No newline at end of file +{"version":3,"sources":["../../src/utils/date.util.ts"],"sourcesContent":["export const ONE_DAY = 24 * 60 * 60 * 1000\n\n// format the date to the format we want\nexport const formatDate = (date: Date): string => {\n const year = date.getFullYear()\n const month = (date.getMonth() + 1 + '').padStart(2, '0')\n const day = (date.getDate() + '').padStart(2, '0')\n return `${year}${month}${day}`\n}\n\n// get formated datestring of yesterday\nexport const yesterday = (date?: Date) => {\n date = date || new Date()\n date.setDate(date.getDate() - 1)\n return date\n}\n\nexport const nextday = (date?: Date) => {\n date = date || new Date()\n date.setDate(date.getDate() + 1)\n return date\n}\n\n// calc days between two Date\nexport function daysBetween(date1: Date, date2: Date) {\n // hours*minutes*seconds*milliseconds\n const diffInMs = Math.abs(date1.getTime() - date2.getTime())\n const diffInDays = Math.round(diffInMs / ONE_DAY)\n return diffInDays\n}\n\n// get begin of one day\nexport const getDayBegin = (date: Date): Date => {\n const year = date.getFullYear()\n const month = date.getMonth()\n const day = date.getDate()\n return new Date(year, month, day)\n}\n\n// get begin of n day ago\nexport const getNDayAgo = (n: number, begin: boolean): Date => {\n const date = new Date(Date.now() - n * 24 * 60 * 60 * 1000)\n if (begin) {\n return getDayBegin(date)\n } else {\n return date\n }\n}\n\n// get begin of this month\nexport const getMonthBegin = (date: Date): Date => {\n const year = date.getFullYear()\n const month = date.getMonth()\n return new Date(year, month, 1)\n}"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAO,IAAM,UAAU,KAAK,KAAK,KAAK;AAG/B,IAAM,aAAa,CAAC,SAAuB;AAChD,QAAM,OAAO,KAAK,YAAY;AAC9B,QAAM,SAAS,KAAK,SAAS,IAAI,IAAI,IAAI,SAAS,GAAG,GAAG;AACxD,QAAM,OAAO,KAAK,QAAQ,IAAI,IAAI,SAAS,GAAG,GAAG;AACjD,SAAO,GAAG,IAAI,GAAG,KAAK,GAAG,GAAG;AAC9B;AAGO,IAAM,YAAY,CAAC,SAAgB;AACxC,SAAO,QAAQ,oBAAI,KAAK;AACxB,OAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC;AAC/B,SAAO;AACT;AAEO,IAAM,UAAU,CAAC,SAAgB;AACtC,SAAO,QAAQ,oBAAI,KAAK;AACxB,OAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC;AAC/B,SAAO;AACT;AAGO,SAAS,YAAY,OAAa,OAAa;AAEpD,QAAM,WAAW,KAAK,IAAI,MAAM,QAAQ,IAAI,MAAM,QAAQ,CAAC;AAC3D,QAAM,aAAa,KAAK,MAAM,WAAW,OAAO;AAChD,SAAO;AACT;AAGO,IAAM,cAAc,CAAC,SAAqB;AAC/C,QAAM,OAAO,KAAK,YAAY;AAC9B,QAAM,QAAQ,KAAK,SAAS;AAC5B,QAAM,MAAM,KAAK,QAAQ;AACzB,SAAO,IAAI,KAAK,MAAM,OAAO,GAAG;AAClC;AAGO,IAAM,aAAa,CAAC,GAAW,UAAyB;AAC7D,QAAM,OAAO,IAAI,KAAK,KAAK,IAAI,IAAI,IAAI,KAAK,KAAK,KAAK,GAAI;AAC1D,MAAI,OAAO;AACT,WAAO,YAAY,IAAI;AAAA,EACzB,OAAO;AACL,WAAO;AAAA,EACT;AACF;AAGO,IAAM,gBAAgB,CAAC,SAAqB;AACjD,QAAM,OAAO,KAAK,YAAY;AAC9B,QAAM,QAAQ,KAAK,SAAS;AAC5B,SAAO,IAAI,KAAK,MAAM,OAAO,CAAC;AAChC;","names":[]} \ No newline at end of file diff --git a/dist/utils/date.util.d.cts b/dist/utils/date.util.d.cts index 91d384d..38f5464 100644 --- a/dist/utils/date.util.d.cts +++ b/dist/utils/date.util.d.cts @@ -3,5 +3,8 @@ declare const formatDate: (date: Date) => string; declare const yesterday: (date?: Date) => Date; declare const nextday: (date?: Date) => Date; declare function daysBetween(date1: Date, date2: Date): number; +declare const getDayBegin: (date: Date) => Date; +declare const getNDayAgo: (n: number, begin: boolean) => Date; +declare const getMonthBegin: (date: Date) => Date; -export { ONE_DAY, daysBetween, formatDate, nextday, yesterday }; +export { ONE_DAY, daysBetween, formatDate, getDayBegin, getMonthBegin, getNDayAgo, nextday, yesterday }; diff --git a/dist/utils/date.util.d.ts b/dist/utils/date.util.d.ts index 91d384d..38f5464 100644 --- a/dist/utils/date.util.d.ts +++ b/dist/utils/date.util.d.ts @@ -3,5 +3,8 @@ declare const formatDate: (date: Date) => string; declare const yesterday: (date?: Date) => Date; declare const nextday: (date?: Date) => Date; declare function daysBetween(date1: Date, date2: Date): number; +declare const getDayBegin: (date: Date) => Date; +declare const getNDayAgo: (n: number, begin: boolean) => Date; +declare const getMonthBegin: (date: Date) => Date; -export { ONE_DAY, daysBetween, formatDate, nextday, yesterday }; +export { ONE_DAY, daysBetween, formatDate, getDayBegin, getMonthBegin, getNDayAgo, nextday, yesterday }; diff --git a/dist/utils/date.util.js b/dist/utils/date.util.js index dafc4fe..4a5d32d 100644 --- a/dist/utils/date.util.js +++ b/dist/utils/date.util.js @@ -21,10 +21,32 @@ function daysBetween(date1, date2) { const diffInDays = Math.round(diffInMs / ONE_DAY); return diffInDays; } +var getDayBegin = (date) => { + const year = date.getFullYear(); + const month = date.getMonth(); + const day = date.getDate(); + return new Date(year, month, day); +}; +var getNDayAgo = (n, begin) => { + const date = new Date(Date.now() - n * 24 * 60 * 60 * 1e3); + if (begin) { + return getDayBegin(date); + } else { + return date; + } +}; +var getMonthBegin = (date) => { + const year = date.getFullYear(); + const month = date.getMonth(); + return new Date(year, month, 1); +}; export { ONE_DAY, daysBetween, formatDate, + getDayBegin, + getMonthBegin, + getNDayAgo, nextday, yesterday }; diff --git a/dist/utils/date.util.js.map b/dist/utils/date.util.js.map index df36732..4c5388f 100644 --- a/dist/utils/date.util.js.map +++ b/dist/utils/date.util.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/utils/date.util.ts"],"sourcesContent":["export const ONE_DAY = 24 * 60 * 60 * 1000\n\n// format the date to the format we want\nexport const formatDate = (date: Date): string => {\n const year = date.getFullYear()\n const month = (date.getMonth() + 1 + '').padStart(2, '0')\n const day = (date.getDate() + '').padStart(2, '0')\n return `${year}${month}${day}`\n}\n\n// get formated datestring of yesterday\nexport const yesterday = (date?: Date) => {\n date = date || new Date()\n date.setDate(date.getDate() - 1)\n return date\n}\n\nexport const nextday = (date?: Date) => {\n date = date || new Date()\n date.setDate(date.getDate() + 1)\n return date\n}\n\n// calc days between two Date\nexport function daysBetween(date1: Date, date2: Date) {\n // hours*minutes*seconds*milliseconds\n const diffInMs = Math.abs(date1.getTime() - date2.getTime())\n const diffInDays = Math.round(diffInMs / ONE_DAY)\n return diffInDays\n}\n"],"mappings":";AAAO,IAAM,UAAU,KAAK,KAAK,KAAK;AAG/B,IAAM,aAAa,CAAC,SAAuB;AAChD,QAAM,OAAO,KAAK,YAAY;AAC9B,QAAM,SAAS,KAAK,SAAS,IAAI,IAAI,IAAI,SAAS,GAAG,GAAG;AACxD,QAAM,OAAO,KAAK,QAAQ,IAAI,IAAI,SAAS,GAAG,GAAG;AACjD,SAAO,GAAG,IAAI,GAAG,KAAK,GAAG,GAAG;AAC9B;AAGO,IAAM,YAAY,CAAC,SAAgB;AACxC,SAAO,QAAQ,oBAAI,KAAK;AACxB,OAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC;AAC/B,SAAO;AACT;AAEO,IAAM,UAAU,CAAC,SAAgB;AACtC,SAAO,QAAQ,oBAAI,KAAK;AACxB,OAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC;AAC/B,SAAO;AACT;AAGO,SAAS,YAAY,OAAa,OAAa;AAEpD,QAAM,WAAW,KAAK,IAAI,MAAM,QAAQ,IAAI,MAAM,QAAQ,CAAC;AAC3D,QAAM,aAAa,KAAK,MAAM,WAAW,OAAO;AAChD,SAAO;AACT;","names":[]} \ No newline at end of file +{"version":3,"sources":["../../src/utils/date.util.ts"],"sourcesContent":["export const ONE_DAY = 24 * 60 * 60 * 1000\n\n// format the date to the format we want\nexport const formatDate = (date: Date): string => {\n const year = date.getFullYear()\n const month = (date.getMonth() + 1 + '').padStart(2, '0')\n const day = (date.getDate() + '').padStart(2, '0')\n return `${year}${month}${day}`\n}\n\n// get formated datestring of yesterday\nexport const yesterday = (date?: Date) => {\n date = date || new Date()\n date.setDate(date.getDate() - 1)\n return date\n}\n\nexport const nextday = (date?: Date) => {\n date = date || new Date()\n date.setDate(date.getDate() + 1)\n return date\n}\n\n// calc days between two Date\nexport function daysBetween(date1: Date, date2: Date) {\n // hours*minutes*seconds*milliseconds\n const diffInMs = Math.abs(date1.getTime() - date2.getTime())\n const diffInDays = Math.round(diffInMs / ONE_DAY)\n return diffInDays\n}\n\n// get begin of one day\nexport const getDayBegin = (date: Date): Date => {\n const year = date.getFullYear()\n const month = date.getMonth()\n const day = date.getDate()\n return new Date(year, month, day)\n}\n\n// get begin of n day ago\nexport const getNDayAgo = (n: number, begin: boolean): Date => {\n const date = new Date(Date.now() - n * 24 * 60 * 60 * 1000)\n if (begin) {\n return getDayBegin(date)\n } else {\n return date\n }\n}\n\n// get begin of this month\nexport const getMonthBegin = (date: Date): Date => {\n const year = date.getFullYear()\n const month = date.getMonth()\n return new Date(year, month, 1)\n}"],"mappings":";AAAO,IAAM,UAAU,KAAK,KAAK,KAAK;AAG/B,IAAM,aAAa,CAAC,SAAuB;AAChD,QAAM,OAAO,KAAK,YAAY;AAC9B,QAAM,SAAS,KAAK,SAAS,IAAI,IAAI,IAAI,SAAS,GAAG,GAAG;AACxD,QAAM,OAAO,KAAK,QAAQ,IAAI,IAAI,SAAS,GAAG,GAAG;AACjD,SAAO,GAAG,IAAI,GAAG,KAAK,GAAG,GAAG;AAC9B;AAGO,IAAM,YAAY,CAAC,SAAgB;AACxC,SAAO,QAAQ,oBAAI,KAAK;AACxB,OAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC;AAC/B,SAAO;AACT;AAEO,IAAM,UAAU,CAAC,SAAgB;AACtC,SAAO,QAAQ,oBAAI,KAAK;AACxB,OAAK,QAAQ,KAAK,QAAQ,IAAI,CAAC;AAC/B,SAAO;AACT;AAGO,SAAS,YAAY,OAAa,OAAa;AAEpD,QAAM,WAAW,KAAK,IAAI,MAAM,QAAQ,IAAI,MAAM,QAAQ,CAAC;AAC3D,QAAM,aAAa,KAAK,MAAM,WAAW,OAAO;AAChD,SAAO;AACT;AAGO,IAAM,cAAc,CAAC,SAAqB;AAC/C,QAAM,OAAO,KAAK,YAAY;AAC9B,QAAM,QAAQ,KAAK,SAAS;AAC5B,QAAM,MAAM,KAAK,QAAQ;AACzB,SAAO,IAAI,KAAK,MAAM,OAAO,GAAG;AAClC;AAGO,IAAM,aAAa,CAAC,GAAW,UAAyB;AAC7D,QAAM,OAAO,IAAI,KAAK,KAAK,IAAI,IAAI,IAAI,KAAK,KAAK,KAAK,GAAI;AAC1D,MAAI,OAAO;AACT,WAAO,YAAY,IAAI;AAAA,EACzB,OAAO;AACL,WAAO;AAAA,EACT;AACF;AAGO,IAAM,gBAAgB,CAAC,SAAqB;AACjD,QAAM,OAAO,KAAK,YAAY;AAC9B,QAAM,QAAQ,KAAK,SAAS;AAC5B,SAAO,IAAI,KAAK,MAAM,OAAO,CAAC;AAChC;","names":[]} \ No newline at end of file diff --git a/dist/utils/net.util.cjs b/dist/utils/net.util.cjs index 320ef82..359e3c7 100644 --- a/dist/utils/net.util.cjs +++ b/dist/utils/net.util.cjs @@ -1,6 +1,8 @@ +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) @@ -14,6 +16,14 @@ var __copyProps = (to, from, except, desc) => { } 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); // src/utils/net.util.ts @@ -39,9 +49,10 @@ var ZError = class { }; // src/utils/net.util.ts +var import_node_fetch = __toESM(require("node-fetch"), 1); var TIMEOUT_ERROR = new Error("timeout"); async function successfulFetch(request, options) { - const response = await fetch(request, options); + const response = await (0, import_node_fetch.default)(request, options); if (!response.ok) { throw new Error(`Fetch failed with status '${response.status}' for request '${request}'`); } diff --git a/dist/utils/net.util.cjs.map b/dist/utils/net.util.cjs.map index 106a90f..275f7ab 100644 --- a/dist/utils/net.util.cjs.map +++ b/dist/utils/net.util.cjs.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/utils/net.util.ts","../../src/common/ZError.ts"],"sourcesContent":["import { ZError } from 'common/ZError'\n\nconst TIMEOUT_ERROR = new Error('timeout')\n\nconst hexRe = /^[0-9A-Fa-f]+$/gu\n\n/**\n * Execute fetch and verify that the response was successful.\n *\n * @param request - Request information.\n * @param options - Fetch options.\n * @returns The fetch response.\n */\nexport async function successfulFetch(request: string, options?: RequestInit) {\n const response = await fetch(request, options)\n if (!response.ok) {\n throw new Error(`Fetch failed with status '${response.status}' for request '${request}'`)\n }\n return response\n}\n\n/**\n * Execute fetch and return object response.\n *\n * @param request - The request information.\n * @param options - The fetch options.\n * @returns The fetch response JSON data.\n */\nexport async function handleFetch(request: string, options?: RequestInit) {\n const response = await successfulFetch(request, options)\n const object = await response.json()\n return object\n}\n\n/**\n * Execute fetch and return object response, log if known error thrown, otherwise rethrow error.\n *\n * @param request - the request options object\n * @param request.url - The request url to query.\n * @param request.options - The fetch options.\n * @param request.timeout - Timeout to fail request\n * @param request.errorCodesToCatch - array of error codes for errors we want to catch in a particular context\n * @returns The fetch response JSON data or undefined (if error occurs).\n */\nexport async function fetchWithErrorHandling({\n url,\n options,\n timeout,\n errorCodesToCatch,\n}: {\n url: string\n options?: RequestInit\n timeout?: number\n errorCodesToCatch?: number[]\n}) {\n let result\n try {\n if (timeout) {\n result = Promise.race([\n await handleFetch(url, options),\n new Promise((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR)\n }, timeout),\n ),\n ])\n } else {\n result = await handleFetch(url, options)\n }\n } catch (e) {\n logOrRethrowError(e, errorCodesToCatch)\n }\n return result\n}\n\n/**\n * Fetch that fails after timeout.\n *\n * @param url - Url to fetch.\n * @param options - Options to send with the request.\n * @param timeout - Timeout to fail request.\n * @returns Promise resolving the request.\n */\nexport async function timeoutFetch(url: string, options?: RequestInit, timeout = 500): Promise {\n return Promise.race([\n successfulFetch(url, options),\n new Promise((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR)\n }, timeout),\n ),\n ])\n}\n\n/**\n * Utility method to log if error is a common fetch error and otherwise rethrow it.\n *\n * @param error - Caught error that we should either rethrow or log to console\n * @param codesToCatch - array of error codes for errors we want to catch and log in a particular context\n */\nfunction logOrRethrowError(error: any, codesToCatch: number[] = []) {\n if (!error) {\n return\n }\n\n const includesErrorCodeToCatch = codesToCatch.some(code =>\n error.message.includes(`Fetch failed with status '${code}'`),\n )\n\n if (\n error instanceof Error &&\n (includesErrorCodeToCatch || error.message.includes('Failed to fetch') || error === TIMEOUT_ERROR)\n ) {\n console.error(error)\n } else {\n throw error\n }\n}\n\nexport function generateHeader() {\n let random = function (start, end) {\n return (Math.random() * (end - start) + start) | 0\n }\n let getIp = function () {\n return `${random(1, 254)}.${random(1, 254)}.${random(1, 254)}.${random(1, 254)}`\n }\n let time = Date.now()\n let useragent = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${\n (70 + Math.random() * 10) | 0\n }.0.4324.${(Math.random() * 100) | 0} Safari/537.36`\n const ip = getIp()\n return {\n 'Refresh-Token': (time -= 5000),\n 'Cache-Control': 'no-cache',\n 'User-Agent': useragent,\n 'X-Forwarded-For': ip,\n 'X-Real-IP': ip,\n 'Content-Type': 'application/json',\n }\n}\n\nexport const checkParamsNeeded = (...args) => {\n args.forEach(arg => {\n if (!arg) {\n throw new ZError(10, 'params mismatch')\n }\n })\n}\n\n/**\n * 生成 key1=val1&key2=val2的字符串\n * @param {object} data 需要处理的对象\n * @param {boolean} sort 是否按key生序重排\n * @param {boolean} ignoreNull 是否过滤空值(空格或者null值不参与拼接)\n * @param splitChar 连接的字符, 默认是&\n * @param equalChar =\n */\nexport function generateKVStr({\n data = {},\n sort = false,\n encode = false,\n ignoreNull = true,\n splitChar = '&',\n equalChar = '=',\n uri = '',\n}: {\n data?: any\n sort?: boolean\n encode?: boolean\n ignoreNull?: boolean\n splitChar?: string\n equalChar?: string\n uri?: string\n}) {\n const keys = Object.keys(data)\n sort && keys.sort()\n let result = ''\n let i = 0\n for (let key of keys) {\n if (ignoreNull && !data[key]) {\n continue\n }\n if (i++ > 0) result += splitChar\n if (encode) {\n result += `${key}${equalChar}${encodeURIComponent(data[key])}`\n } else {\n result += `${key}${equalChar}${data[key]}`\n }\n }\n if (uri) {\n const joinChar = uri.search(/\\?/) === -1 ? '?' : '&'\n result = uri + joinChar + result\n }\n return result\n}\n\n/**\n * 将key1=val&key2=val的字符串组装成对象\n * @param str key1=val&key2=val的字符串\n * @param splitChar 连接的字符, 默认是&\n * @param equalChar =\n */\nexport function keyValToObject(str: string, splitChar: string = '&', equalChar = '='): {} {\n let result: any = {}\n if (!str) {\n return result\n }\n let arrs = str.split(splitChar)\n for (let sub of arrs) {\n let subArr = sub.split(equalChar)\n result[subArr[0]] = subArr[1]\n }\n return result\n}\n","export class ZError implements Error {\n code: string\n statusCode?: number\n message: string\n name: string\n\n constructor(statusCode: number, message: string) {\n this.statusCode = statusCode\n this.message = message\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,SAAN,MAA8B;AAAA,EAMnC,YAAY,YAAoB,SAAiB;AAC/C,SAAK,aAAa;AAClB,SAAK,UAAU;AAAA,EACjB;AACF;;;ADRA,IAAM,gBAAgB,IAAI,MAAM,SAAS;AAWzC,eAAsB,gBAAgB,SAAiB,SAAuB;AAC5E,QAAM,WAAW,MAAM,MAAM,SAAS,OAAO;AAC7C,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,IAAI,MAAM,6BAA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AAG,GAAG,SAAS,GAAG,KAAK,GAAG,CAAC;AAAA,IAC1C;AAAA,EACF;AACA,MAAI,KAAK;AACP,UAAM,WAAW,IAAI,OAAO,IAAI,MAAM,KAAK,MAAM;AACjD,aAAS,MAAM,WAAW;AAAA,EAC5B;AACA,SAAO;AACT;AAQO,SAAS,eAAe,KAAa,YAAoB,KAAK,YAAY,KAAS;AACxF,MAAI,SAAc,CAAC;AACnB,MAAI,CAAC,KAAK;AACR,WAAO;AAAA,EACT;AACA,MAAI,OAAO,IAAI,MAAM,SAAS;AAC9B,WAAS,OAAO,MAAM;AACpB,QAAI,SAAS,IAAI,MAAM,SAAS;AAChC,WAAO,OAAO,CAAC,CAAC,IAAI,OAAO,CAAC;AAAA,EAC9B;AACA,SAAO;AACT;","names":[]} \ No newline at end of file +{"version":3,"sources":["../../src/utils/net.util.ts","../../src/common/ZError.ts"],"sourcesContent":["import { ZError } from 'common/ZError'\nimport fetch, { Response, RequestInit } from 'node-fetch'\n\nconst TIMEOUT_ERROR = new Error('timeout')\n\nconst hexRe = /^[0-9A-Fa-f]+$/gu\n\n/**\n * Execute fetch and verify that the response was successful.\n *\n * @param request - Request information.\n * @param options - Fetch options.\n * @returns The fetch response.\n */\nexport async function successfulFetch(request: string, options?: RequestInit) {\n const response = await fetch(request, options)\n if (!response.ok) {\n throw new Error(`Fetch failed with status '${response.status}' for request '${request}'`)\n }\n return response\n}\n\n/**\n * Execute fetch and return object response.\n *\n * @param request - The request information.\n * @param options - The fetch options.\n * @returns The fetch response JSON data.\n */\nexport async function handleFetch(request: string, options?: RequestInit) {\n const response = await successfulFetch(request, options)\n const object = await response.json()\n return object\n}\n\n/**\n * Execute fetch and return object response, log if known error thrown, otherwise rethrow error.\n *\n * @param request - the request options object\n * @param request.url - The request url to query.\n * @param request.options - The fetch options.\n * @param request.timeout - Timeout to fail request\n * @param request.errorCodesToCatch - array of error codes for errors we want to catch in a particular context\n * @returns The fetch response JSON data or undefined (if error occurs).\n */\nexport async function fetchWithErrorHandling({\n url,\n options,\n timeout,\n errorCodesToCatch,\n}: {\n url: string\n options?: RequestInit\n timeout?: number\n errorCodesToCatch?: number[]\n}) {\n let result\n try {\n if (timeout) {\n result = Promise.race([\n await handleFetch(url, options),\n new Promise((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR)\n }, timeout),\n ),\n ])\n } else {\n result = await handleFetch(url, options)\n }\n } catch (e) {\n logOrRethrowError(e, errorCodesToCatch)\n }\n return result\n}\n\n/**\n * Fetch that fails after timeout.\n *\n * @param url - Url to fetch.\n * @param options - Options to send with the request.\n * @param timeout - Timeout to fail request.\n * @returns Promise resolving the request.\n */\nexport async function timeoutFetch(url: string, options?: RequestInit, timeout = 500): Promise {\n return Promise.race([\n successfulFetch(url, options),\n new Promise((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR)\n }, timeout),\n ),\n ])\n}\n\n/**\n * Utility method to log if error is a common fetch error and otherwise rethrow it.\n *\n * @param error - Caught error that we should either rethrow or log to console\n * @param codesToCatch - array of error codes for errors we want to catch and log in a particular context\n */\nfunction logOrRethrowError(error: any, codesToCatch: number[] = []) {\n if (!error) {\n return\n }\n\n const includesErrorCodeToCatch = codesToCatch.some(code =>\n error.message.includes(`Fetch failed with status '${code}'`),\n )\n\n if (\n error instanceof Error &&\n (includesErrorCodeToCatch || error.message.includes('Failed to fetch') || error === TIMEOUT_ERROR)\n ) {\n console.error(error)\n } else {\n throw error\n }\n}\n\nexport function generateHeader() {\n let random = function (start, end) {\n return (Math.random() * (end - start) + start) | 0\n }\n let getIp = function () {\n return `${random(1, 254)}.${random(1, 254)}.${random(1, 254)}.${random(1, 254)}`\n }\n let time = Date.now()\n let useragent = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${\n (70 + Math.random() * 10) | 0\n }.0.4324.${(Math.random() * 100) | 0} Safari/537.36`\n const ip = getIp()\n return {\n 'Refresh-Token': (time -= 5000),\n 'Cache-Control': 'no-cache',\n 'User-Agent': useragent,\n 'X-Forwarded-For': ip,\n 'X-Real-IP': ip,\n 'Content-Type': 'application/json',\n }\n}\n\nexport const checkParamsNeeded = (...args) => {\n args.forEach(arg => {\n if (!arg) {\n throw new ZError(10, 'params mismatch')\n }\n })\n}\n\n/**\n * 生成 key1=val1&key2=val2的字符串\n * @param {object} data 需要处理的对象\n * @param {boolean} sort 是否按key生序重排\n * @param {boolean} ignoreNull 是否过滤空值(空格或者null值不参与拼接)\n * @param splitChar 连接的字符, 默认是&\n * @param equalChar =\n */\nexport function generateKVStr({\n data = {},\n sort = false,\n encode = false,\n ignoreNull = true,\n splitChar = '&',\n equalChar = '=',\n uri = '',\n}: {\n data?: any\n sort?: boolean\n encode?: boolean\n ignoreNull?: boolean\n splitChar?: string\n equalChar?: string\n uri?: string\n}) {\n const keys = Object.keys(data)\n sort && keys.sort()\n let result = ''\n let i = 0\n for (let key of keys) {\n if (ignoreNull && !data[key]) {\n continue\n }\n if (i++ > 0) result += splitChar\n if (encode) {\n result += `${key}${equalChar}${encodeURIComponent(data[key])}`\n } else {\n result += `${key}${equalChar}${data[key]}`\n }\n }\n if (uri) {\n const joinChar = uri.search(/\\?/) === -1 ? '?' : '&'\n result = uri + joinChar + result\n }\n return result\n}\n\n/**\n * 将key1=val&key2=val的字符串组装成对象\n * @param str key1=val&key2=val的字符串\n * @param splitChar 连接的字符, 默认是&\n * @param equalChar =\n */\nexport function keyValToObject(str: string, splitChar: string = '&', equalChar = '='): {} {\n let result: any = {}\n if (!str) {\n return result\n }\n let arrs = str.split(splitChar)\n for (let sub of arrs) {\n let subArr = sub.split(equalChar)\n result[subArr[0]] = subArr[1]\n }\n return result\n}\n","export class ZError implements Error {\n code: string\n statusCode?: number\n message: string\n name: string\n\n constructor(statusCode: number, message: string) {\n this.statusCode = statusCode\n this.message = message\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAA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,EACZ,MAAM;AACR,GAQG;AACD,QAAM,OAAO,OAAO,KAAK,IAAI;AAC7B,UAAQ,KAAK,KAAK;AAClB,MAAI,SAAS;AACb,MAAI,IAAI;AACR,WAAS,OAAO,MAAM;AACpB,QAAI,cAAc,CAAC,KAAK,GAAG,GAAG;AAC5B;AAAA,IACF;AACA,QAAI,MAAM;AAAG,gBAAU;AACvB,QAAI,QAAQ;AACV,gBAAU,GAAG,GAAG,GAAG,SAAS,GAAG,mBAAmB,KAAK,GAAG,CAAC,CAAC;AAAA,IAC9D,OAAO;AACL,gBAAU,GAAG,GAAG,GAAG,SAAS,GAAG,KAAK,GAAG,CAAC;AAAA,IAC1C;AAAA,EACF;AACA,MAAI,KAAK;AACP,UAAM,WAAW,IAAI,OAAO,IAAI,MAAM,KAAK,MAAM;AACjD,aAAS,MAAM,WAAW;AAAA,EAC5B;AACA,SAAO;AACT;AAQO,SAAS,eAAe,KAAa,YAAoB,KAAK,YAAY,KAAS;AACxF,MAAI,SAAc,CAAC;AACnB,MAAI,CAAC,KAAK;AACR,WAAO;AAAA,EACT;AACA,MAAI,OAAO,IAAI,MAAM,SAAS;AAC9B,WAAS,OAAO,MAAM;AACpB,QAAI,SAAS,IAAI,MAAM,SAAS;AAChC,WAAO,OAAO,CAAC,CAAC,IAAI,OAAO,CAAC;AAAA,EAC9B;AACA,SAAO;AACT;","names":["fetch"]} \ No newline at end of file diff --git a/dist/utils/net.util.d.cts b/dist/utils/net.util.d.cts index b8b2f01..b9dd7b5 100644 --- a/dist/utils/net.util.d.cts +++ b/dist/utils/net.util.d.cts @@ -1,3 +1,5 @@ +import fetch, { RequestInit, Response } from 'node-fetch'; + /** * Execute fetch and verify that the response was successful. * @@ -5,7 +7,7 @@ * @param options - Fetch options. * @returns The fetch response. */ -declare function successfulFetch(request: string, options?: RequestInit): Promise; +declare function successfulFetch(request: string, options?: RequestInit): Promise; /** * Execute fetch and return object response. * diff --git a/dist/utils/net.util.d.ts b/dist/utils/net.util.d.ts index b8b2f01..b9dd7b5 100644 --- a/dist/utils/net.util.d.ts +++ b/dist/utils/net.util.d.ts @@ -1,3 +1,5 @@ +import fetch, { RequestInit, Response } from 'node-fetch'; + /** * Execute fetch and verify that the response was successful. * @@ -5,7 +7,7 @@ * @param options - Fetch options. * @returns The fetch response. */ -declare function successfulFetch(request: string, options?: RequestInit): Promise; +declare function successfulFetch(request: string, options?: RequestInit): Promise; /** * Execute fetch and return object response. * diff --git a/dist/utils/net.util.js b/dist/utils/net.util.js index 5f17998..4ad31d0 100644 --- a/dist/utils/net.util.js +++ b/dist/utils/net.util.js @@ -7,6 +7,7 @@ var ZError = class { }; // src/utils/net.util.ts +import fetch from "node-fetch"; var TIMEOUT_ERROR = new Error("timeout"); async function successfulFetch(request, options) { const response = await fetch(request, options); diff --git a/dist/utils/net.util.js.map b/dist/utils/net.util.js.map index efdddfb..02f21a1 100644 --- a/dist/utils/net.util.js.map +++ b/dist/utils/net.util.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/common/ZError.ts","../../src/utils/net.util.ts"],"sourcesContent":["export class ZError implements Error {\n code: string\n statusCode?: number\n message: string\n name: string\n\n constructor(statusCode: number, message: string) {\n this.statusCode = statusCode\n this.message = message\n }\n}\n","import { ZError } from 'common/ZError'\n\nconst TIMEOUT_ERROR = new Error('timeout')\n\nconst hexRe = /^[0-9A-Fa-f]+$/gu\n\n/**\n * Execute fetch and verify that the response was successful.\n *\n * @param request - Request information.\n * @param options - Fetch options.\n * @returns The fetch response.\n */\nexport async function successfulFetch(request: string, options?: RequestInit) {\n const response = await fetch(request, options)\n if (!response.ok) {\n throw new Error(`Fetch failed with status '${response.status}' for request '${request}'`)\n }\n return response\n}\n\n/**\n * Execute fetch and return object response.\n *\n * @param request - The request information.\n * @param options - The fetch options.\n * @returns The fetch response JSON data.\n */\nexport async function handleFetch(request: string, options?: RequestInit) {\n const response = await successfulFetch(request, options)\n const object = await response.json()\n return object\n}\n\n/**\n * Execute fetch and return object response, log if known error thrown, otherwise rethrow error.\n *\n * @param request - the request options object\n * @param request.url - The request url to query.\n * @param request.options - The fetch options.\n * @param request.timeout - Timeout to fail request\n * @param request.errorCodesToCatch - array of error codes for errors we want to catch in a particular context\n * @returns The fetch response JSON data or undefined (if error occurs).\n */\nexport async function fetchWithErrorHandling({\n url,\n options,\n timeout,\n errorCodesToCatch,\n}: {\n url: string\n options?: RequestInit\n timeout?: number\n errorCodesToCatch?: number[]\n}) {\n let result\n try {\n if (timeout) {\n result = Promise.race([\n await handleFetch(url, options),\n new Promise((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR)\n }, timeout),\n ),\n ])\n } else {\n result = await handleFetch(url, options)\n }\n } catch (e) {\n logOrRethrowError(e, errorCodesToCatch)\n }\n return result\n}\n\n/**\n * Fetch that fails after timeout.\n *\n * @param url - Url to fetch.\n * @param options - Options to send with the request.\n * @param timeout - Timeout to fail request.\n * @returns Promise resolving the request.\n */\nexport async function timeoutFetch(url: string, options?: RequestInit, timeout = 500): Promise {\n return Promise.race([\n successfulFetch(url, options),\n new Promise((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR)\n }, timeout),\n ),\n ])\n}\n\n/**\n * Utility method to log if error is a common fetch error and otherwise rethrow it.\n *\n * @param error - Caught error that we should either rethrow or log to console\n * @param codesToCatch - array of error codes for errors we want to catch and log in a particular context\n */\nfunction logOrRethrowError(error: any, codesToCatch: number[] = []) {\n if (!error) {\n return\n }\n\n const includesErrorCodeToCatch = codesToCatch.some(code =>\n error.message.includes(`Fetch failed with status '${code}'`),\n )\n\n if (\n error instanceof Error &&\n (includesErrorCodeToCatch || error.message.includes('Failed to fetch') || error === TIMEOUT_ERROR)\n ) {\n console.error(error)\n } else {\n throw error\n }\n}\n\nexport function generateHeader() {\n let random = function (start, end) {\n return (Math.random() * (end - start) + start) | 0\n }\n let getIp = function () {\n return `${random(1, 254)}.${random(1, 254)}.${random(1, 254)}.${random(1, 254)}`\n }\n let time = Date.now()\n let useragent = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${\n (70 + Math.random() * 10) | 0\n }.0.4324.${(Math.random() * 100) | 0} Safari/537.36`\n const ip = getIp()\n return {\n 'Refresh-Token': (time -= 5000),\n 'Cache-Control': 'no-cache',\n 'User-Agent': useragent,\n 'X-Forwarded-For': ip,\n 'X-Real-IP': ip,\n 'Content-Type': 'application/json',\n }\n}\n\nexport const checkParamsNeeded = (...args) => {\n args.forEach(arg => {\n if (!arg) {\n throw new ZError(10, 'params mismatch')\n }\n })\n}\n\n/**\n * 生成 key1=val1&key2=val2的字符串\n * @param {object} data 需要处理的对象\n * @param {boolean} sort 是否按key生序重排\n * @param {boolean} ignoreNull 是否过滤空值(空格或者null值不参与拼接)\n * @param splitChar 连接的字符, 默认是&\n * @param equalChar =\n */\nexport function generateKVStr({\n data = {},\n sort = false,\n encode = false,\n ignoreNull = true,\n splitChar = '&',\n equalChar = '=',\n uri = '',\n}: {\n data?: any\n sort?: boolean\n encode?: boolean\n ignoreNull?: boolean\n splitChar?: string\n equalChar?: string\n uri?: string\n}) {\n const keys = Object.keys(data)\n sort && keys.sort()\n let result = ''\n let i = 0\n for (let key of keys) {\n if (ignoreNull && !data[key]) {\n continue\n }\n if (i++ > 0) result += splitChar\n if (encode) {\n result += `${key}${equalChar}${encodeURIComponent(data[key])}`\n } else {\n result += `${key}${equalChar}${data[key]}`\n }\n }\n if (uri) {\n const joinChar = uri.search(/\\?/) === -1 ? '?' : '&'\n result = uri + joinChar + result\n }\n return result\n}\n\n/**\n * 将key1=val&key2=val的字符串组装成对象\n * @param str key1=val&key2=val的字符串\n * @param splitChar 连接的字符, 默认是&\n * @param equalChar =\n */\nexport function keyValToObject(str: string, splitChar: string = '&', equalChar = '='): {} {\n let result: any = {}\n if (!str) {\n return result\n }\n let arrs = str.split(splitChar)\n for (let sub of arrs) {\n let subArr = sub.split(equalChar)\n result[subArr[0]] = subArr[1]\n }\n return result\n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;AAC7B,UAAQ,KAAK,KAAK;AAClB,MAAI,SAAS;AACb,MAAI,IAAI;AACR,WAAS,OAAO,MAAM;AACpB,QAAI,cAAc,CAAC,KAAK,GAAG,GAAG;AAC5B;AAAA,IACF;AACA,QAAI,MAAM;AAAG,gBAAU;AACvB,QAAI,QAAQ;AACV,gBAAU,GAAG,GAAG,GAAG,SAAS,GAAG,mBAAmB,KAAK,GAAG,CAAC,CAAC;AAAA,IAC9D,OAAO;AACL,gBAAU,GAAG,GAAG,GAAG,SAAS,GAAG,KAAK,GAAG,CAAC;AAAA,IAC1C;AAAA,EACF;AACA,MAAI,KAAK;AACP,UAAM,WAAW,IAAI,OAAO,IAAI,MAAM,KAAK,MAAM;AACjD,aAAS,MAAM,WAAW;AAAA,EAC5B;AACA,SAAO;AACT;AAQO,SAAS,eAAe,KAAa,YAAoB,KAAK,YAAY,KAAS;AACxF,MAAI,SAAc,CAAC;AACnB,MAAI,CAAC,KAAK;AACR,WAAO;AAAA,EACT;AACA,MAAI,OAAO,IAAI,MAAM,SAAS;AAC9B,WAAS,OAAO,MAAM;AACpB,QAAI,SAAS,IAAI,MAAM,SAAS;AAChC,WAAO,OAAO,CAAC,CAAC,IAAI,OAAO,CAAC;AAAA,EAC9B;AACA,SAAO;AACT;","names":[]} \ No newline at end of file +{"version":3,"sources":["../../src/common/ZError.ts","../../src/utils/net.util.ts"],"sourcesContent":["export class ZError implements Error {\n code: string\n statusCode?: number\n message: string\n name: string\n\n constructor(statusCode: number, message: string) {\n this.statusCode = statusCode\n this.message = message\n }\n}\n","import { ZError } from 'common/ZError'\nimport fetch, { Response, RequestInit } from 'node-fetch'\n\nconst TIMEOUT_ERROR = new Error('timeout')\n\nconst hexRe = /^[0-9A-Fa-f]+$/gu\n\n/**\n * Execute fetch and verify that the response was successful.\n *\n * @param request - Request information.\n * @param options - Fetch options.\n * @returns The fetch response.\n */\nexport async function successfulFetch(request: string, options?: RequestInit) {\n const response = await fetch(request, options)\n if (!response.ok) {\n throw new Error(`Fetch failed with status '${response.status}' for request '${request}'`)\n }\n return response\n}\n\n/**\n * Execute fetch and return object response.\n *\n * @param request - The request information.\n * @param options - The fetch options.\n * @returns The fetch response JSON data.\n */\nexport async function handleFetch(request: string, options?: RequestInit) {\n const response = await successfulFetch(request, options)\n const object = await response.json()\n return object\n}\n\n/**\n * Execute fetch and return object response, log if known error thrown, otherwise rethrow error.\n *\n * @param request - the request options object\n * @param request.url - The request url to query.\n * @param request.options - The fetch options.\n * @param request.timeout - Timeout to fail request\n * @param request.errorCodesToCatch - array of error codes for errors we want to catch in a particular context\n * @returns The fetch response JSON data or undefined (if error occurs).\n */\nexport async function fetchWithErrorHandling({\n url,\n options,\n timeout,\n errorCodesToCatch,\n}: {\n url: string\n options?: RequestInit\n timeout?: number\n errorCodesToCatch?: number[]\n}) {\n let result\n try {\n if (timeout) {\n result = Promise.race([\n await handleFetch(url, options),\n new Promise((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR)\n }, timeout),\n ),\n ])\n } else {\n result = await handleFetch(url, options)\n }\n } catch (e) {\n logOrRethrowError(e, errorCodesToCatch)\n }\n return result\n}\n\n/**\n * Fetch that fails after timeout.\n *\n * @param url - Url to fetch.\n * @param options - Options to send with the request.\n * @param timeout - Timeout to fail request.\n * @returns Promise resolving the request.\n */\nexport async function timeoutFetch(url: string, options?: RequestInit, timeout = 500): Promise {\n return Promise.race([\n successfulFetch(url, options),\n new Promise((_, reject) =>\n setTimeout(() => {\n reject(TIMEOUT_ERROR)\n }, timeout),\n ),\n ])\n}\n\n/**\n * Utility method to log if error is a common fetch error and otherwise rethrow it.\n *\n * @param error - Caught error that we should either rethrow or log to console\n * @param codesToCatch - array of error codes for errors we want to catch and log in a particular context\n */\nfunction logOrRethrowError(error: any, codesToCatch: number[] = []) {\n if (!error) {\n return\n }\n\n const includesErrorCodeToCatch = codesToCatch.some(code =>\n error.message.includes(`Fetch failed with status '${code}'`),\n )\n\n if (\n error instanceof Error &&\n (includesErrorCodeToCatch || error.message.includes('Failed to fetch') || error === TIMEOUT_ERROR)\n ) {\n console.error(error)\n } else {\n throw error\n }\n}\n\nexport function generateHeader() {\n let random = function (start, end) {\n return (Math.random() * (end - start) + start) | 0\n }\n let getIp = function () {\n return `${random(1, 254)}.${random(1, 254)}.${random(1, 254)}.${random(1, 254)}`\n }\n let time = Date.now()\n let useragent = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${\n (70 + Math.random() * 10) | 0\n }.0.4324.${(Math.random() * 100) | 0} Safari/537.36`\n const ip = getIp()\n return {\n 'Refresh-Token': (time -= 5000),\n 'Cache-Control': 'no-cache',\n 'User-Agent': useragent,\n 'X-Forwarded-For': ip,\n 'X-Real-IP': ip,\n 'Content-Type': 'application/json',\n }\n}\n\nexport const checkParamsNeeded = (...args) => {\n args.forEach(arg => {\n if (!arg) {\n throw new ZError(10, 'params mismatch')\n }\n })\n}\n\n/**\n * 生成 key1=val1&key2=val2的字符串\n * @param {object} data 需要处理的对象\n * @param {boolean} sort 是否按key生序重排\n * @param {boolean} ignoreNull 是否过滤空值(空格或者null值不参与拼接)\n * @param splitChar 连接的字符, 默认是&\n * @param equalChar =\n */\nexport function generateKVStr({\n data = {},\n sort = false,\n encode = false,\n ignoreNull = true,\n splitChar = '&',\n equalChar = '=',\n uri = '',\n}: {\n data?: any\n sort?: boolean\n encode?: boolean\n ignoreNull?: boolean\n splitChar?: string\n equalChar?: string\n uri?: string\n}) {\n const keys = Object.keys(data)\n sort && keys.sort()\n let result = ''\n let i = 0\n for (let key of keys) {\n if (ignoreNull && !data[key]) {\n continue\n }\n if (i++ > 0) result += splitChar\n if (encode) {\n result += `${key}${equalChar}${encodeURIComponent(data[key])}`\n } else {\n result += `${key}${equalChar}${data[key]}`\n }\n }\n if (uri) {\n const joinChar = uri.search(/\\?/) === -1 ? '?' : '&'\n result = uri + joinChar + result\n }\n return result\n}\n\n/**\n * 将key1=val&key2=val的字符串组装成对象\n * @param str key1=val&key2=val的字符串\n * @param splitChar 连接的字符, 默认是&\n * @param equalChar =\n */\nexport function keyValToObject(str: string, splitChar: string = '&', equalChar = '='): {} {\n let result: any = {}\n if (!str) {\n return result\n }\n let arrs = str.split(splitChar)\n for (let sub of arrs) {\n let subArr = sub.split(equalChar)\n result[subArr[0]] = subArr[1]\n }\n return result\n}\n"],"mappings":";AAAO,IAAM,SAAN,MAA8B;AAAA,EAMnC,YAAY,YAAoB,SAAiB;AAC/C,SAAK,aAAa;AAClB,SAAK,UAAU;AAAA,EACjB;AACF;;;ACTA,OAAO,WAAsC;AAE7C,IAAM,gBAAgB,IAAI,MAAM,SAAS;AAWzC,eAAsB,gBAAgB,SAAiB,SAAuB;AAC5E,QAAM,WAAW,MAAM,MAAM,SAAS,OAAO;AAC7C,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,IAAI,MAAM,6BAA6B,SAAS,MAAM,kBAAkB,OAAO,GAAG;AAAA,EAC1F;AACA,SAAO;AACT;AASA,eAAsB,YAAY,SAAiB,SAAuB;AACxE,QAAM,WAAW,MAAM,gBAAgB,SAAS,OAAO;AACvD,QAAM,SAAS,MAAM,SAAS,KAAK;AACnC,SAAO;AACT;AAYA,eAAsB,uBAAuB;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAKG;AACD,MAAI;AACJ,MAAI;AACF,QAAI,SAAS;AACX,eAAS,QAAQ,KAAK;AAAA,QACpB,MAAM,YAAY,KAAK,OAAO;AAAA,QAC9B,IAAI;AAAA,UAAkB,CAAC,GAAG,WACxB,WAAW,MAAM;AACf,mBAAO,aAAa;AAAA,UACtB,GAAG,OAAO;AAAA,QACZ;AAAA,MACF,CAAC;AAAA,IACH,OAAO;AACL,eAAS,MAAM,YAAY,KAAK,OAAO;AAAA,IACzC;AAAA,EACF,SAAS,GAAG;AACV,sBAAkB,GAAG,iBAAiB;AAAA,EACxC;AACA,SAAO;AACT;AAUA,eAAsB,aAAa,KA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