Compare commits
47 Commits
Author | SHA1 | Date | |
---|---|---|---|
afb6ca0803 | |||
e699f8a634 | |||
c7dd91e9cd | |||
20f36cc573 | |||
57446ef09a | |||
6d13df39f5 | |||
2d63db0ebb | |||
535fc0271e | |||
d587b92ea4 | |||
26c6084052 | |||
874bba59d3 | |||
948fba3a2c | |||
a168b03caf | |||
75160b7dbc | |||
af887a0bfb | |||
7626c20f08 | |||
6998616445 | |||
627757ff6d | |||
0a775f919b | |||
7063b80bdd | |||
f3049160b6 | |||
e21273ddb2 | |||
8d3b427c1b | |||
87857a01c5 | |||
535e579b43 | |||
2934f86530 | |||
0693397164 | |||
2a878b7962 | |||
7b2d4ba119 | |||
1a4e732fd5 | |||
3a039c935f | |||
ac5b0b8b41 | |||
3f85c9cf7d | |||
1eff60e7dd | |||
1d9ad2ef63 | |||
973a884b3e | |||
6f60f8bd94 | |||
07606cd996 | |||
3ca956e531 | |||
9350c837e5 | |||
86196c3feb | |||
0985ff145e | |||
7cd717fc7d | |||
2fe8cdb96a | |||
34c2df7a1a | |||
1d5509a078 | |||
9f57b93a9f |
63
.github/workflows/build.yaml
vendored
63
.github/workflows/build.yaml
vendored
@ -9,39 +9,28 @@ jobs:
|
|||||||
build:
|
build:
|
||||||
name: Build NPM Project
|
name: Build NPM Project
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
container:
|
container: node:20-alpine
|
||||||
image: node
|
|
||||||
volumes:
|
|
||||||
- '/mnt/swarm/gitea/runner/cache:/cache'
|
|
||||||
steps:
|
steps:
|
||||||
- name: Clone Repository
|
- name: Clone Repository
|
||||||
uses: ztimson/actions/clone@develop
|
uses: ztimson/actions/clone@develop
|
||||||
|
|
||||||
- name: Restore node_modules
|
- name: Install & Build
|
||||||
uses: ztimson/actions/cache/restore@develop
|
run: |
|
||||||
with:
|
npm i
|
||||||
key: node_modules
|
npm run build
|
||||||
|
|
||||||
- name: Install Dependencies
|
|
||||||
run: npm i
|
|
||||||
|
|
||||||
- name: Build Project
|
|
||||||
run: npm run build
|
|
||||||
|
|
||||||
- name: Test
|
- name: Test
|
||||||
run: npm run test:coverage
|
run: npm run test:coverage
|
||||||
|
|
||||||
- name: Cache node_modules
|
- name: Upload to Registry
|
||||||
uses: ztimson/actions/cache@develop
|
uses: ztimson/actions/npm/publish@develop
|
||||||
with:
|
|
||||||
key: node_modules
|
|
||||||
pattern: node_modules
|
|
||||||
|
|
||||||
- name: Cache Artifacts
|
- name: Upload to NPM
|
||||||
uses: ztimson/actions/cache@develop
|
uses: ztimson/actions/npm/publish@develop
|
||||||
with:
|
with:
|
||||||
key: dist
|
owner: ztimson
|
||||||
pattern: dist
|
registry: https://registry.npmjs.org/
|
||||||
|
token: ${{secrets.NPM_TOKEN}}
|
||||||
tag:
|
tag:
|
||||||
name: Tag Version
|
name: Tag Version
|
||||||
needs: build
|
needs: build
|
||||||
@ -59,31 +48,3 @@ jobs:
|
|||||||
uses: ztimson/actions/tag@develop
|
uses: ztimson/actions/tag@develop
|
||||||
with:
|
with:
|
||||||
tag: ${{env.VERSION}}
|
tag: ${{env.VERSION}}
|
||||||
|
|
||||||
publish:
|
|
||||||
name: Publish
|
|
||||||
needs: build
|
|
||||||
if: ${{github.ref_name}} == 'release'
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
container:
|
|
||||||
image: node
|
|
||||||
volumes:
|
|
||||||
- '/mnt/swarm/gitea/runner/cache:/cache'
|
|
||||||
steps:
|
|
||||||
- name: Clone Repository
|
|
||||||
uses: ztimson/actions/clone@develop
|
|
||||||
|
|
||||||
- name: Restore Artifacts
|
|
||||||
uses: ztimson/actions/cache/restore@develop
|
|
||||||
with:
|
|
||||||
key: dist
|
|
||||||
|
|
||||||
- name: Upload to Registry
|
|
||||||
uses: ztimson/actions/npm/publish@develop
|
|
||||||
|
|
||||||
- name: Upload to NPM
|
|
||||||
uses: ztimson/actions/npm/publish@develop
|
|
||||||
with:
|
|
||||||
owner: ztimson
|
|
||||||
registry: https://registry.npmjs.org/
|
|
||||||
token: ${{secrets.NPM_TOKEN}}
|
|
||||||
|
4
package-lock.json
generated
4
package-lock.json
generated
@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "@ztimson/utils",
|
"name": "@ztimson/utils",
|
||||||
"version": "0.4.0",
|
"version": "0.15.3",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@ztimson/utils",
|
"name": "@ztimson/utils",
|
||||||
"version": "0.4.0",
|
"version": "0.15.3",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/jest": "^29.5.12",
|
"@types/jest": "^29.5.12",
|
||||||
|
13
package.json
13
package.json
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ztimson/utils",
|
"name": "@ztimson/utils",
|
||||||
"version": "0.6.0",
|
"version": "0.15.4",
|
||||||
"description": "Utility library",
|
"description": "Utility library",
|
||||||
"author": "Zak Timson",
|
"author": "Zak Timson",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
@ -9,9 +9,16 @@
|
|||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://git.zakscode.com/ztimson/js-utilities"
|
"url": "https://git.zakscode.com/ztimson/js-utilities"
|
||||||
},
|
},
|
||||||
"main": "./dist/utils.cjs",
|
"main": "./dist/index.cjs",
|
||||||
"module": "./dist/utils.mjs",
|
"module": "./dist/index.mjs",
|
||||||
"types": "./dist/index.d.ts",
|
"types": "./dist/index.d.ts",
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"import": "./dist/index.mjs",
|
||||||
|
"require": "./dist/index.cjs",
|
||||||
|
"types": "./dist/index.d.ts"
|
||||||
|
}
|
||||||
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "npx tsc && npx vite build",
|
"build": "npx tsc && npx vite build",
|
||||||
"test": "npx jest",
|
"test": "npx jest",
|
||||||
|
67
src/aset.ts
67
src/aset.ts
@ -1,57 +1,108 @@
|
|||||||
|
/**
|
||||||
|
* An array which functions as a set. It guarantees unique elements
|
||||||
|
* and provides set functions for comparisons
|
||||||
|
*/
|
||||||
export class ASet<T> extends Array {
|
export class ASet<T> extends Array {
|
||||||
|
/** Number of elements in set */
|
||||||
get size() {
|
get size() {
|
||||||
return this.length;
|
return this.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Array to create set from, duplicate values will be removed
|
||||||
|
* @param {T[]} elements Elements which will be added to set
|
||||||
|
*/
|
||||||
constructor(elements: T[] = []) {
|
constructor(elements: T[] = []) {
|
||||||
super();
|
super();
|
||||||
if(!!elements?.['forEach'])
|
if(!!elements?.['forEach'])
|
||||||
elements.forEach(el => this.add(el));
|
elements.forEach(el => this.add(el));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add single element to set if unique
|
||||||
|
* @param {T} el Element to add
|
||||||
|
*/
|
||||||
add(el: T) {
|
add(el: T) {
|
||||||
if(!this.has(el)) this.push(el);
|
if(!this.has(el)) this.push(el);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete element from set
|
||||||
|
* @param {T} el Element that will be deleted
|
||||||
|
*/
|
||||||
delete(el: T) {
|
delete(el: T) {
|
||||||
const index = this.indexOf(el);
|
const index = this.indexOf(el);
|
||||||
if(index != -1) this.slice(index, 1);
|
if(index != -1) this.slice(index, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create list of elements this set has which the comparison set does not
|
||||||
|
* @param {ASet<T>} set Set to compare against
|
||||||
|
* @return {ASet<T>} Different elements
|
||||||
|
*/
|
||||||
difference(set: ASet<T>) {
|
difference(set: ASet<T>) {
|
||||||
return new ASet<T>(this.reduce((acc, el) => {
|
return new ASet<T>(this.filter(el => !set.has(el)));
|
||||||
if(!set.has(el)) acc.push(el);
|
|
||||||
return acc;
|
|
||||||
}, []));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if set includes element
|
||||||
|
* @param {T} el Element to look for
|
||||||
|
* @return {boolean} True if element was found, false otherwise
|
||||||
|
*/
|
||||||
has(el: T) {
|
has(el: T) {
|
||||||
return this.indexOf(el) != -1;
|
return this.indexOf(el) != -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create list of elements this set has in common with the comparison set
|
||||||
|
* @param {ASet<T>} set Set to compare against
|
||||||
|
* @return {boolean} Set of common elements
|
||||||
|
*/
|
||||||
intersection(set: ASet<T>) {
|
intersection(set: ASet<T>) {
|
||||||
return new ASet<T>(this.reduce((acc, el) => {
|
return new ASet<T>(this.filter(el => set.has(el)));
|
||||||
if(set.has(el)) acc.push(el);
|
|
||||||
return acc;
|
|
||||||
}, []));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if this set has no elements in common with the comparison set
|
||||||
|
* @param {ASet<T>} set Set to compare against
|
||||||
|
* @return {boolean} True if nothing in common, false otherwise
|
||||||
|
*/
|
||||||
isDisjointFrom(set: ASet<T>) {
|
isDisjointFrom(set: ASet<T>) {
|
||||||
return this.intersection(set).size == 0;
|
return this.intersection(set).size == 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if all elements in this set are included in the comparison set
|
||||||
|
* @param {ASet<T>} set Set to compare against
|
||||||
|
* @return {boolean} True if all elements are included, false otherwise
|
||||||
|
*/
|
||||||
isSubsetOf(set: ASet<T>) {
|
isSubsetOf(set: ASet<T>) {
|
||||||
return this.findIndex(el => !set.has(el)) == -1;
|
return this.findIndex(el => !set.has(el)) == -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if all elements from comparison set are included in this set
|
||||||
|
* @param {ASet<T>} set Set to compare against
|
||||||
|
* @return {boolean} True if all elements are included, false otherwise
|
||||||
|
*/
|
||||||
isSuperset(set: ASet<T>) {
|
isSuperset(set: ASet<T>) {
|
||||||
return set.findIndex(el => !this.has(el)) == -1;
|
return set.findIndex(el => !this.has(el)) == -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create list of elements that are only in one set but not both (XOR)
|
||||||
|
* @param {ASet<T>} set Set to compare against
|
||||||
|
* @return {ASet<T>} New set of unique elements
|
||||||
|
*/
|
||||||
symmetricDifference(set: ASet<T>) {
|
symmetricDifference(set: ASet<T>) {
|
||||||
return new ASet([...this.difference(set), ...set.difference(this)]);
|
return new ASet([...this.difference(set), ...set.difference(this)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create joined list of elements included in this & the comparison set
|
||||||
|
* @param {ASet<T>} set Set join
|
||||||
|
* @return {ASet<T>} New set of both previous sets combined
|
||||||
|
*/
|
||||||
union(set: ASet<T> | Array<T>) {
|
union(set: ASet<T> | Array<T>) {
|
||||||
return new ASet([...this, ...set]);
|
return new ASet([...this, ...set]);
|
||||||
}
|
}
|
||||||
|
@ -1,46 +0,0 @@
|
|||||||
import {TypedEmitter, TypedEvents} from './emitter.ts';
|
|
||||||
|
|
||||||
export type downloadEvents = TypedEvents & {
|
|
||||||
complete: (blob: Blob) => any;
|
|
||||||
progress: (progress: number) => any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function download(href: any, name: string) {
|
|
||||||
const a = document.createElement('a');
|
|
||||||
a.href = href;
|
|
||||||
a.download = name;
|
|
||||||
document.body.appendChild(a);
|
|
||||||
a.click();
|
|
||||||
document.body.removeChild(a);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function downloadStream(url: string, name?: string) {
|
|
||||||
const emitter = new TypedEmitter<downloadEvents>();
|
|
||||||
fetch(url).then(response => {
|
|
||||||
const contentLength = response.headers.get('Content-Length') || '0';
|
|
||||||
const total = parseInt(contentLength, 10);
|
|
||||||
let chunks: any[] = [], loaded = 0;
|
|
||||||
const reader = response.body?.getReader();
|
|
||||||
reader?.read().then(function processResult(result) {
|
|
||||||
if(result.done) {
|
|
||||||
const blob = new Blob(chunks);
|
|
||||||
emitter.emit('progress', 1);
|
|
||||||
if(name) {
|
|
||||||
const url = URL.createObjectURL(blob);
|
|
||||||
download(url, name);
|
|
||||||
URL.revokeObjectURL(url);
|
|
||||||
}
|
|
||||||
emitter.emit('complete', blob);
|
|
||||||
return;
|
|
||||||
} else {
|
|
||||||
const chunk = result.value;
|
|
||||||
chunks.push(chunk);
|
|
||||||
loaded += chunk.length;
|
|
||||||
const progress = Math.round((loaded / total) * 100);
|
|
||||||
emitter.emit('progress', progress);
|
|
||||||
reader.read().then(processResult);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
|
||||||
return emitter;
|
|
||||||
}
|
|
134
src/errors.ts
134
src/errors.ts
@ -1,15 +1,3 @@
|
|||||||
import {XHR} from './xhr';
|
|
||||||
|
|
||||||
XHR.addInterceptor((resp: Response, next: () => void) => {
|
|
||||||
if(resp.status == 200) return next();
|
|
||||||
if(resp.status == 400) throw new BadRequestError(resp.statusText);
|
|
||||||
if(resp.status == 401) throw new UnauthorizedError(resp.statusText);
|
|
||||||
if(resp.status == 403) throw new ForbiddenError(resp.statusText);
|
|
||||||
if(resp.status == 404) throw new NotFoundError(resp.statusText);
|
|
||||||
if(resp.status == 500) throw new InternalServerError(resp.statusText);
|
|
||||||
throw new CustomError(resp.statusText, resp.status);
|
|
||||||
});
|
|
||||||
|
|
||||||
export class CustomError extends Error {
|
export class CustomError extends Error {
|
||||||
static code = 500;
|
static code = 500;
|
||||||
|
|
||||||
@ -65,6 +53,18 @@ export class UnauthorizedError extends CustomError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class PaymentRequiredError extends CustomError {
|
||||||
|
static code = 402;
|
||||||
|
|
||||||
|
constructor(message: string = 'Payment Required') {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
static instanceof(err: Error) {
|
||||||
|
return (<any>err).constructor.code == this.code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export class ForbiddenError extends CustomError {
|
export class ForbiddenError extends CustomError {
|
||||||
static code = 403;
|
static code = 403;
|
||||||
|
|
||||||
@ -89,6 +89,30 @@ export class NotFoundError extends CustomError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class MethodNotAllowedError extends CustomError {
|
||||||
|
static code = 405;
|
||||||
|
|
||||||
|
constructor(message: string = 'Method Not Allowed') {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
static instanceof(err: Error) {
|
||||||
|
return (<any>err).constructor.code == this.code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class NotAcceptableError extends CustomError {
|
||||||
|
static code = 406;
|
||||||
|
|
||||||
|
constructor(message: string = 'Not Acceptable') {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
static instanceof(err: Error) {
|
||||||
|
return (<any>err).constructor.code == this.code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export class InternalServerError extends CustomError {
|
export class InternalServerError extends CustomError {
|
||||||
static code = 500;
|
static code = 500;
|
||||||
|
|
||||||
@ -100,3 +124,89 @@ export class InternalServerError extends CustomError {
|
|||||||
return (<any>err).constructor.code == this.code;
|
return (<any>err).constructor.code == this.code;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class NotImplementedError extends CustomError {
|
||||||
|
static code = 501;
|
||||||
|
|
||||||
|
constructor(message: string = 'Not Implemented') {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
static instanceof(err: Error) {
|
||||||
|
return (<any>err).constructor.code == this.code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BadGatewayError extends CustomError {
|
||||||
|
static code = 502;
|
||||||
|
|
||||||
|
constructor(message: string = 'Bad Gateway') {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
static instanceof(err: Error) {
|
||||||
|
return (<any>err).constructor.code == this.code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ServiceUnavailableError extends CustomError {
|
||||||
|
static code = 503;
|
||||||
|
|
||||||
|
constructor(message: string = 'Service Unavailable') {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
static instanceof(err: Error) {
|
||||||
|
return (<any>err).constructor.code == this.code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class GatewayTimeoutError extends CustomError {
|
||||||
|
static code = 504;
|
||||||
|
|
||||||
|
constructor(message: string = 'Gateway Timeout') {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
static instanceof(err: Error) {
|
||||||
|
return (<any>err).constructor.code == this.code;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create the correct error object from a status code
|
||||||
|
* @param {number} code Will be converted to respective error (ex. 404 -> NotFoundError)
|
||||||
|
* @param {string} message Override default error message
|
||||||
|
* @return {CustomError} The proper error type
|
||||||
|
*/
|
||||||
|
export function errorFromCode(code: number, message?: string) {
|
||||||
|
if(code >= 200 && code < 300) return null;
|
||||||
|
switch(code) {
|
||||||
|
case 400:
|
||||||
|
return new BadRequestError(message);
|
||||||
|
case 401:
|
||||||
|
return new UnauthorizedError(message);
|
||||||
|
case 402:
|
||||||
|
return new PaymentRequiredError(message);
|
||||||
|
case 403:
|
||||||
|
return new ForbiddenError(message);
|
||||||
|
case 404:
|
||||||
|
return new NotFoundError(message);
|
||||||
|
case 405:
|
||||||
|
return new MethodNotAllowedError(message);
|
||||||
|
case 406:
|
||||||
|
return new NotAcceptableError(message);
|
||||||
|
case 500:
|
||||||
|
return new InternalServerError(message);
|
||||||
|
case 501:
|
||||||
|
return new NotImplementedError(message);
|
||||||
|
case 502:
|
||||||
|
return new BadGatewayError(message);
|
||||||
|
case 503:
|
||||||
|
return new ServiceUnavailableError(message);
|
||||||
|
case 504:
|
||||||
|
return new GatewayTimeoutError(message);
|
||||||
|
default:
|
||||||
|
return new CustomError(message, code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
56
src/files.ts
Normal file
56
src/files.ts
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
import {deepCopy, JSONAttemptParse} from './objects.ts';
|
||||||
|
import {PromiseProgress} from './promise-progress';
|
||||||
|
|
||||||
|
export function download(href: any, name: string) {
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = href;
|
||||||
|
a.download = name;
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
document.body.removeChild(a);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function downloadBlob(blob: Blob, name: string) {
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
download(url, name);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fileBrowser(options: {accept?: string, multiple?: boolean} = {}): Promise<File[]> {
|
||||||
|
return new Promise(res => {
|
||||||
|
const input = document.createElement('input');
|
||||||
|
input.type = 'file';
|
||||||
|
input.accept = options.accept || '*';
|
||||||
|
input.style.display='none';
|
||||||
|
input.multiple = !!options.multiple;
|
||||||
|
input.onblur = input.onchange = async () => {
|
||||||
|
res(Array.from(<any>input.files));
|
||||||
|
input.remove();
|
||||||
|
}
|
||||||
|
document.body.appendChild(input);
|
||||||
|
input.click();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function uploadWithProgress<T>(options: {
|
||||||
|
url: string;
|
||||||
|
files: File[];
|
||||||
|
headers?: {[key: string]: string};
|
||||||
|
withCredentials?: boolean;
|
||||||
|
}): PromiseProgress<T> {
|
||||||
|
return new PromiseProgress<T>((res, rej, prog) => {
|
||||||
|
const xhr = new XMLHttpRequest();
|
||||||
|
const formData = new FormData();
|
||||||
|
options.files.forEach(f => formData.append('file', f));
|
||||||
|
|
||||||
|
xhr.withCredentials = !!options.withCredentials;
|
||||||
|
xhr.upload.addEventListener('progress', (event) => event.lengthComputable ? prog(event.loaded / event.total) : null);
|
||||||
|
xhr.addEventListener('loadend', () => res(<T>JSONAttemptParse(xhr.responseText)));
|
||||||
|
xhr.addEventListener('error', () => rej(JSONAttemptParse(xhr.responseText)));
|
||||||
|
xhr.addEventListener('timeout', () => rej({error: 'Request timed out'}));
|
||||||
|
|
||||||
|
xhr.open('POST', options.url);
|
||||||
|
Object.entries(options.headers || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value));
|
||||||
|
xhr.send(formData);
|
||||||
|
});
|
||||||
|
}
|
121
src/http.ts
Normal file
121
src/http.ts
Normal file
@ -0,0 +1,121 @@
|
|||||||
|
import {clean} from './objects';
|
||||||
|
import {PromiseProgress} from './promise-progress';
|
||||||
|
|
||||||
|
export type DecodedResponse<T> = Response & {data: T | null}
|
||||||
|
|
||||||
|
export type HttpInterceptor = (response: Response, next: () => void) => void;
|
||||||
|
|
||||||
|
export type HttpRequestOptions = {
|
||||||
|
body?: any;
|
||||||
|
decode?: boolean;
|
||||||
|
fragment?: string;
|
||||||
|
headers?: {[key: string | symbol]: string | null | undefined};
|
||||||
|
method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
|
||||||
|
query?: {key: string, value: string}[] | {[key: string]: string};
|
||||||
|
url?: string;
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type HttpDefaults = {
|
||||||
|
headers?: {[key: string | symbol]: string | null | undefined};
|
||||||
|
interceptors?: HttpInterceptor[];
|
||||||
|
url?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Http {
|
||||||
|
private static interceptors: {[key: string]: HttpInterceptor} = {};
|
||||||
|
|
||||||
|
static headers: {[key: string]: string | null | undefined} = {};
|
||||||
|
|
||||||
|
private interceptors: {[key: string]: HttpInterceptor} = {}
|
||||||
|
|
||||||
|
headers: {[key: string]: string | null | undefined} = {}
|
||||||
|
url!: string | null;
|
||||||
|
|
||||||
|
constructor(defaults: HttpDefaults = {}) {
|
||||||
|
this.url = defaults.url ?? null;
|
||||||
|
this.headers = defaults.headers || {};
|
||||||
|
if(defaults.interceptors) {
|
||||||
|
defaults.interceptors.forEach(i => Http.addInterceptor(i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static addInterceptor(fn: HttpInterceptor): () => void {
|
||||||
|
const key = Object.keys(Http.interceptors).length.toString();
|
||||||
|
Http.interceptors[key] = fn;
|
||||||
|
return () => { Http.interceptors[key] = <any>null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
addInterceptor(fn: HttpInterceptor): () => void {
|
||||||
|
const key = Object.keys(this.interceptors).length.toString();
|
||||||
|
this.interceptors[key] = fn;
|
||||||
|
return () => { this.interceptors[key] = <any>null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
request<T>(opts: HttpRequestOptions = {}): PromiseProgress<DecodedResponse<T>> {
|
||||||
|
if(!this.url && !opts.url) throw new Error('URL needs to be set');
|
||||||
|
let url = (opts.url?.startsWith('http') ? opts.url : (this.url || '') + (opts.url || '')).replace(/([^:]\/)\/+/g, '$1');
|
||||||
|
if(opts.fragment) url.includes('#') ? url.replace(/#.*(\?|\n)/g, (match, arg1) => `#${opts.fragment}${arg1}`) : url += '#' + opts.fragment;
|
||||||
|
if(opts.query) {
|
||||||
|
const q = Array.isArray(opts.query) ? opts.query :
|
||||||
|
Object.keys(opts.query).map(k => ({key: k, value: (<any>opts.query)[k]}))
|
||||||
|
url += (url.includes('?') ? '&' : '?') + q.map(q => `${q.key}=${q.value}`).join('&');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prep headers
|
||||||
|
const headers = <any>clean({
|
||||||
|
'Content-Type': !opts.body ? undefined : (opts.body instanceof FormData ? 'multipart/form-data' : 'application/json'),
|
||||||
|
...Http.headers,
|
||||||
|
...this.headers,
|
||||||
|
...opts.headers
|
||||||
|
});
|
||||||
|
|
||||||
|
if(typeof opts.body == 'object' && opts.body != null && headers['Content-Type'] == 'application/json')
|
||||||
|
opts.body = JSON.stringify(opts.body);
|
||||||
|
|
||||||
|
// Send request
|
||||||
|
return new PromiseProgress((res, rej, prog) => {
|
||||||
|
fetch(url, {
|
||||||
|
headers,
|
||||||
|
method: opts.method || (opts.body ? 'POST' : 'GET'),
|
||||||
|
body: opts.body
|
||||||
|
}).then(async (resp: any) => {
|
||||||
|
for(let fn of [...Object.values(Http.interceptors), ...Object.values(this.interceptors)]) {
|
||||||
|
await new Promise<void>(res => fn(resp, () => res()));
|
||||||
|
}
|
||||||
|
|
||||||
|
const contentLength = resp.headers.get('Content-Length');
|
||||||
|
const total = contentLength ? parseInt(contentLength, 10) : 0;
|
||||||
|
let loaded = 0;
|
||||||
|
|
||||||
|
const reader = resp.body?.getReader();
|
||||||
|
const stream = new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
function push() {
|
||||||
|
reader?.read().then((event: any) => {
|
||||||
|
if(event.done) return controller.close();
|
||||||
|
loaded += event.value.byteLength;
|
||||||
|
prog(loaded / total);
|
||||||
|
controller.enqueue(event.value);
|
||||||
|
push();
|
||||||
|
}).catch((error: any) => controller.error(error));
|
||||||
|
}
|
||||||
|
push();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
resp.data = new Response(stream);
|
||||||
|
if(opts.decode == null || opts.decode) {
|
||||||
|
const content = resp.headers.get('Content-Type')?.toLowerCase();
|
||||||
|
if(content?.includes('form')) resp.data = <T>await resp.data.formData();
|
||||||
|
else if(content?.includes('json')) resp.data = <T>await resp.data.json();
|
||||||
|
else if(content?.includes('text')) resp.data = <T>await resp.data.text();
|
||||||
|
else if(content?.includes('application')) resp.data = <T>await resp.data.blob();
|
||||||
|
}
|
||||||
|
|
||||||
|
if(resp.ok) res(resp);
|
||||||
|
else rej(resp);
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -1,11 +1,13 @@
|
|||||||
export * from './array';
|
export * from './array';
|
||||||
export * from './aset';
|
export * from './aset';
|
||||||
export * from './download.ts';
|
export * from './files';
|
||||||
export * from './emitter';
|
export * from './emitter';
|
||||||
export * from './errors';
|
export * from './errors';
|
||||||
|
export * from './http';
|
||||||
export * from './logger';
|
export * from './logger';
|
||||||
|
export * from './math';
|
||||||
export * from './misc';
|
export * from './misc';
|
||||||
export * from './objects';
|
export * from './objects';
|
||||||
|
export * from './promise-progress';
|
||||||
export * from './string';
|
export * from './string';
|
||||||
export * from './time';
|
export * from './time';
|
||||||
export * from './xhr';
|
|
||||||
|
45
src/math.ts
Normal file
45
src/math.ts
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
/**
|
||||||
|
* Convert decimal number to fraction
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```js
|
||||||
|
* dec2Frac(1.25) // Outputs: "1 1/4"
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @param {number} num Number to convert
|
||||||
|
* @return {string} Fraction with remainder
|
||||||
|
*/
|
||||||
|
export function dec2Frac(num: number) {
|
||||||
|
const gcd = (a: number, b: number): number => {
|
||||||
|
if (b < 0.0000001) return a;
|
||||||
|
return gcd(b, ~~(a % b));
|
||||||
|
};
|
||||||
|
|
||||||
|
const len = num.toString().length - 2;
|
||||||
|
let denominator = Math.pow(10, len);
|
||||||
|
let numerator = num * denominator;
|
||||||
|
const divisor = gcd(numerator, denominator);
|
||||||
|
numerator = ~~(numerator / divisor);
|
||||||
|
denominator = ~~(denominator / divisor)
|
||||||
|
const remainder = ~~(numerator / denominator);
|
||||||
|
numerator -= remainder * denominator;
|
||||||
|
return `${remainder ? remainder + ' ' : ''}${~~(numerator)}/${~~(denominator)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert fraction to decimal number
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```js
|
||||||
|
* fracToDec('1 1/4') // Outputs: 1.25
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* @param {string} frac Fraction to convert
|
||||||
|
* @return {number} Faction as a decimal
|
||||||
|
*/
|
||||||
|
export function fracToDec(frac: string) {
|
||||||
|
let split = frac.split(' ');
|
||||||
|
const whole = split.length == 2 ? Number(split[0]) : 0;
|
||||||
|
split = (<string>split.pop()).split('/');
|
||||||
|
return whole + (Number(split[0]) / Number(split[1]));
|
||||||
|
}
|
12
src/misc.ts
12
src/misc.ts
@ -1,17 +1,5 @@
|
|||||||
import {md5} from './string';
|
import {md5} from './string';
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert data into a form encoded format.
|
|
||||||
*
|
|
||||||
* @param {any} data - data to convert
|
|
||||||
* @returns {string} - Ecodeded form data
|
|
||||||
*/
|
|
||||||
export function formEncode(data: any): string {
|
|
||||||
return Object.entries(data).map(([key, value]) =>
|
|
||||||
encodeURIComponent(key) + '=' + encodeURIComponent(<any>value)
|
|
||||||
).join('&');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get profile image from Gravatar
|
* Get profile image from Gravatar
|
||||||
*
|
*
|
||||||
|
@ -35,6 +35,27 @@ export function deepCopy<T>(value: T): T {
|
|||||||
return JSON.parse(JSON.stringify(value));
|
return JSON.parse(JSON.stringify(value));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merge any number of objects into the target
|
||||||
|
*
|
||||||
|
* @param target Destination of all properties
|
||||||
|
* @param sources Objects that will copied into target
|
||||||
|
* @return {any} The des
|
||||||
|
*/
|
||||||
|
export function deepMerge<T>(target: any, ...sources: any[]): T {
|
||||||
|
sources.forEach(s => {
|
||||||
|
for(const key in s) {
|
||||||
|
if(s[key] && typeof s[key] == 'object' && !Array.isArray(s[key])) {
|
||||||
|
if(!target[key]) target[key] = {};
|
||||||
|
deepMerge(target[key], s[key]);
|
||||||
|
} else {
|
||||||
|
target[key] = s[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return target;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get/set a property of an object using dot notation
|
* Get/set a property of an object using dot notation
|
||||||
*
|
*
|
||||||
@ -98,6 +119,17 @@ export function flattenObj(obj: any, parent?: any, result: any = {}) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert object to FormData
|
||||||
|
* @param target - Object to convert
|
||||||
|
* @return {FormData} - Form object
|
||||||
|
*/
|
||||||
|
export function formData(target: any): FormData {
|
||||||
|
const data = new FormData();
|
||||||
|
Object.entries(target).forEach(([key, value]) => data.append(key, <any>value));
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check that an object has the following values
|
* Check that an object has the following values
|
||||||
*
|
*
|
||||||
@ -154,7 +186,12 @@ export function mixin(target: any, constructors: any[]) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function sanitizedJSON(obj: any, space?: number) {
|
export function JSONAttemptParse<T>(json: string): T | string {
|
||||||
|
try { return JSON.parse(json); }
|
||||||
|
catch { return json; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function JSONSanitized(obj: any, space?: number) {
|
||||||
let cache: any[] = [];
|
let cache: any[] = [];
|
||||||
return JSON.parse(JSON.stringify(obj, (key, value) => {
|
return JSON.parse(JSON.stringify(obj, (key, value) => {
|
||||||
if (typeof value === 'object' && value !== null) {
|
if (typeof value === 'object' && value !== null) {
|
||||||
@ -164,3 +201,15 @@ export function sanitizedJSON(obj: any, space?: number) {
|
|||||||
return value;
|
return value;
|
||||||
}, space));
|
}, space));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert object into URL encoded string
|
||||||
|
*
|
||||||
|
* @param {any} data - data to convert
|
||||||
|
* @returns {string} - Encoded form data
|
||||||
|
*/
|
||||||
|
export function urlEncode(data: any): string {
|
||||||
|
return Object.entries(data).map(([key, value]) =>
|
||||||
|
encodeURIComponent(key) + '=' + encodeURIComponent(<any>value)
|
||||||
|
).join('&');
|
||||||
|
}
|
||||||
|
52
src/promise-progress.ts
Normal file
52
src/promise-progress.ts
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
export type ProgressCallback = (progress: number) => any;
|
||||||
|
|
||||||
|
export class PromiseProgress<T> extends Promise<T> {
|
||||||
|
private listeners: ProgressCallback[] = [];
|
||||||
|
|
||||||
|
private _progress = 0;
|
||||||
|
get progress() { return this._progress; }
|
||||||
|
set progress(p: number) {
|
||||||
|
if(p == this._progress) return;
|
||||||
|
this._progress = p;
|
||||||
|
this.listeners.forEach(l => l(p));
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(executor: (resolve: (value: T) => any, reject: (reason: any) => void, progress: (progress: number) => any) => void) {
|
||||||
|
super((resolve, reject) => executor(
|
||||||
|
(value: T) => resolve(value),
|
||||||
|
(reason: any) => reject(reason),
|
||||||
|
(progress: number) => this.progress = progress,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
static from<T>(promise: Promise<T>): PromiseProgress<T> {
|
||||||
|
if(promise instanceof PromiseProgress) return promise;
|
||||||
|
return new PromiseProgress<T>((res, rej) => promise
|
||||||
|
.then((...args) => res(...args))
|
||||||
|
.catch((...args) => rej(...args)));
|
||||||
|
}
|
||||||
|
|
||||||
|
private from(promise: Promise<T>): PromiseProgress<T> {
|
||||||
|
const newPromise = PromiseProgress.from(promise);
|
||||||
|
this.onProgress(p => newPromise.progress = p);
|
||||||
|
return newPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
onProgress(callback: ProgressCallback) {
|
||||||
|
this.listeners.push(callback);
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
then(res?: (v: T) => any, rej?: (err: any) => any): PromiseProgress<any> {
|
||||||
|
const resp = super.then(res, rej);
|
||||||
|
return this.from(resp);
|
||||||
|
}
|
||||||
|
|
||||||
|
catch(rej?: (err: any) => any): PromiseProgress<any> {
|
||||||
|
return this.from(super.catch(rej));
|
||||||
|
}
|
||||||
|
|
||||||
|
finally(res?: () => any): PromiseProgress<any> {
|
||||||
|
return this.from(super.finally(res));
|
||||||
|
}
|
||||||
|
}
|
70
src/time.ts
70
src/time.ts
@ -1,32 +1,3 @@
|
|||||||
/**
|
|
||||||
* Calculate the number of milliseconds until date/time
|
|
||||||
*
|
|
||||||
* @param {Date | number} date - Target
|
|
||||||
* @returns {number} - Number of milliseconds until target
|
|
||||||
*/
|
|
||||||
export function timeUntil(date: Date | number): number {
|
|
||||||
return (date instanceof Date ? date.getTime() : date) - (new Date()).getTime();
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Use in conjunction with `await` to pause an async script
|
|
||||||
*
|
|
||||||
* @example
|
|
||||||
* ```ts
|
|
||||||
* async () => {
|
|
||||||
* ...
|
|
||||||
* await sleep(1000) // Pause for 1 second
|
|
||||||
* ...
|
|
||||||
* }
|
|
||||||
* ```
|
|
||||||
*
|
|
||||||
* @param {number} ms - Time to pause for in milliseconds
|
|
||||||
* @returns {Promise<unknown>} - Resolves promise when it's time to resume
|
|
||||||
*/
|
|
||||||
export function sleep(ms: number) {
|
|
||||||
return new Promise(res => setTimeout(res, ms));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatDate(date: Date | number | string) {
|
export function formatDate(date: Date | number | string) {
|
||||||
const d = date instanceof Date ? date : new Date(date);
|
const d = date instanceof Date ? date : new Date(date);
|
||||||
return new Intl.DateTimeFormat("en-us", {
|
return new Intl.DateTimeFormat("en-us", {
|
||||||
@ -38,3 +9,44 @@ export function formatDate(date: Date | number | string) {
|
|||||||
hour12: true
|
hour12: true
|
||||||
}).format(d);
|
}).format(d);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Use in conjunction with `await` to pause an async script
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```js
|
||||||
|
* await sleep(1000) // Pause for 1 second
|
||||||
|
* ```
|
||||||
|
* @param {number} ms - Time to pause for in milliseconds
|
||||||
|
* @returns {Promise<unknown>} - Resolves promise when it's time to resume
|
||||||
|
*/
|
||||||
|
export function sleep(ms: number): Promise<void> {
|
||||||
|
return new Promise(res => setTimeout(res, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sleep while function returns true
|
||||||
|
*
|
||||||
|
* @example
|
||||||
|
* ```js
|
||||||
|
* let loading = true;
|
||||||
|
* setTimeout(() => wait = false, 1000);
|
||||||
|
* await sleepUntil(() => loading); // Won't continue until loading flag is false
|
||||||
|
* ```
|
||||||
|
* @param {() => boolean} fn Return true to continue
|
||||||
|
* @param {number} checkInterval Run function ever x milliseconds
|
||||||
|
* @return {Promise<void>} Callback when sleep is over
|
||||||
|
*/
|
||||||
|
export async function sleepUntil(fn : () => boolean, checkInterval=100): Promise<void> {
|
||||||
|
while(fn()) await sleep(checkInterval);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculate the number of milliseconds until date/time
|
||||||
|
*
|
||||||
|
* @param {Date | number} date - Target
|
||||||
|
* @returns {number} - Number of milliseconds until target
|
||||||
|
*/
|
||||||
|
export function timeUntil(date: Date | number): number {
|
||||||
|
return (date instanceof Date ? date.getTime() : date) - (new Date()).getTime();
|
||||||
|
}
|
||||||
|
77
src/xhr.ts
77
src/xhr.ts
@ -1,77 +0,0 @@
|
|||||||
import {TypedEmitter, TypedEvents} from './emitter.ts';
|
|
||||||
import {clean} from './objects';
|
|
||||||
|
|
||||||
export type Interceptor = (request: Response, next: () => void) => void;
|
|
||||||
|
|
||||||
export type RequestOptions = {
|
|
||||||
url?: string;
|
|
||||||
method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
|
|
||||||
body?: any;
|
|
||||||
headers?: {[key: string | symbol]: string | null | undefined};
|
|
||||||
skipConverting?: boolean;
|
|
||||||
[key: string]: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export type XhrOptions = {
|
|
||||||
headers?: {[key: string | symbol]: string | null | undefined};
|
|
||||||
interceptors?: Interceptor[];
|
|
||||||
url?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export class XHR {
|
|
||||||
private static interceptors: {[key: string]: Interceptor} = {};
|
|
||||||
|
|
||||||
static headers: {[key: string]: string | null | undefined} = {};
|
|
||||||
|
|
||||||
private interceptors: {[key: string]: Interceptor} = {}
|
|
||||||
|
|
||||||
headers: {[key: string]: string | null | undefined} = {}
|
|
||||||
|
|
||||||
constructor(public readonly opts: XhrOptions = {}) {
|
|
||||||
this.headers = opts.headers || {};
|
|
||||||
if(opts.interceptors) {
|
|
||||||
opts.interceptors.forEach(i => XHR.addInterceptor(i));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static addInterceptor(fn: Interceptor): () => void {
|
|
||||||
const key = Object.keys(XHR.interceptors).length.toString();
|
|
||||||
XHR.interceptors[key] = fn;
|
|
||||||
return () => { XHR.interceptors[key] = <any>null; }
|
|
||||||
}
|
|
||||||
|
|
||||||
addInterceptor(fn: Interceptor): () => void {
|
|
||||||
const key = Object.keys(this.interceptors).length.toString();
|
|
||||||
this.interceptors[key] = fn;
|
|
||||||
return () => { this.interceptors[key] = <any>null; }
|
|
||||||
}
|
|
||||||
|
|
||||||
async request<T>(opts: RequestOptions = {}): Promise<T> {
|
|
||||||
if(!this.opts.url && !opts.url) throw new Error('URL needs to be set');
|
|
||||||
const url = (opts.url?.startsWith('http') ? opts.url : (this.opts.url || '') + (opts.url || '')).replace(/([^:]\/)\/+/g, '$1');
|
|
||||||
|
|
||||||
// Prep headers
|
|
||||||
const headers = <any>clean({
|
|
||||||
'Content-Type': (opts.body && !(opts.body instanceof FormData)) ? 'application/json' : undefined,
|
|
||||||
...XHR.headers,
|
|
||||||
...this.headers,
|
|
||||||
...opts.headers
|
|
||||||
});
|
|
||||||
|
|
||||||
// Send request
|
|
||||||
return fetch(url, {
|
|
||||||
headers,
|
|
||||||
method: opts.method || (opts.body ? 'POST' : 'GET'),
|
|
||||||
body: (headers['Content-Type']?.startsWith('application/json') && opts.body) ? JSON.stringify(opts.body) : opts.body
|
|
||||||
}).then(async resp => {
|
|
||||||
for(let fn of [...Object.values(XHR.interceptors), ...Object.values(this.interceptors)]) {
|
|
||||||
await new Promise<void>(res => fn(resp, () => res()));
|
|
||||||
}
|
|
||||||
|
|
||||||
if(!resp.ok) throw new Error(resp.statusText);
|
|
||||||
if(!opts.skipConverting && resp.headers.get('Content-Type')?.startsWith('application/json')) return await resp.json();
|
|
||||||
if(!opts.skipConverting && resp.headers.get('Content-Type')?.startsWith('text/plain')) return await <any>resp.text();
|
|
||||||
return resp;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
@ -8,8 +8,8 @@ export default defineConfig({
|
|||||||
entry: resolve(process.cwd(), 'src/index.ts'),
|
entry: resolve(process.cwd(), 'src/index.ts'),
|
||||||
name: 'utils',
|
name: 'utils',
|
||||||
fileName: (module, entryName) => {
|
fileName: (module, entryName) => {
|
||||||
if(module == 'es') return 'utils.mjs';
|
if(module == 'es') return 'index.mjs';
|
||||||
if(module == 'umd') return 'utils.cjs';
|
if(module == 'umd') return 'index.cjs';
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
emptyOutDir: true,
|
emptyOutDir: true,
|
||||||
|
Reference in New Issue
Block a user