Compare commits
18 Commits
Author | SHA1 | Date | |
---|---|---|---|
a168b03caf | |||
75160b7dbc | |||
af887a0bfb | |||
7626c20f08 | |||
6998616445 | |||
627757ff6d | |||
0a775f919b | |||
7063b80bdd | |||
f3049160b6 | |||
e21273ddb2 | |||
8d3b427c1b | |||
87857a01c5 | |||
535e579b43 | |||
2934f86530 | |||
0693397164 | |||
2a878b7962 | |||
7b2d4ba119 | |||
1a4e732fd5 |
25
.github/workflows/build.yaml
vendored
25
.github/workflows/build.yaml
vendored
@ -9,34 +9,19 @@ 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
|
|
||||||
uses: ztimson/actions/cache@develop
|
|
||||||
with:
|
|
||||||
key: node_modules
|
|
||||||
pattern: node_modules
|
|
||||||
|
|
||||||
- name: Upload to Registry
|
- name: Upload to Registry
|
||||||
uses: ztimson/actions/npm/publish@develop
|
uses: ztimson/actions/npm/publish@develop
|
||||||
|
|
||||||
|
10
package.json
10
package.json
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@ztimson/utils",
|
"name": "@ztimson/utils",
|
||||||
"version": "0.12.1",
|
"version": "0.14.6",
|
||||||
"description": "Utility library",
|
"description": "Utility library",
|
||||||
"author": "Zak Timson",
|
"author": "Zak Timson",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
@ -9,13 +9,13 @@
|
|||||||
"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": {
|
"exports": {
|
||||||
".": {
|
".": {
|
||||||
"import": "./dist/utils.mjs",
|
"import": "./dist/index.mjs",
|
||||||
"require": "./dist/utils.cjs",
|
"require": "./dist/index.cjs",
|
||||||
"types": "./dist/index.d.ts"
|
"types": "./dist/index.d.ts"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
@ -1,8 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
54
src/files.ts
Normal file
54
src/files.ts
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
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.upload.addEventListener('load', (resp) => res(<any>resp));
|
||||||
|
xhr.upload.addEventListener('error', (err) => rej(err));
|
||||||
|
|
||||||
|
xhr.open('POST', options.url);
|
||||||
|
Object.entries(options.headers || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value));
|
||||||
|
xhr.send(formData);
|
||||||
|
});
|
||||||
|
}
|
119
src/http.ts
Normal file
119
src/http.ts
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
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 = {
|
||||||
|
url?: string;
|
||||||
|
fragment?: string;
|
||||||
|
query?: {key: string, value: string}[] | {[key: string]: string};
|
||||||
|
method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
|
||||||
|
body?: any;
|
||||||
|
headers?: {[key: string | symbol]: string | null | undefined};
|
||||||
|
[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();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = new Response(stream);
|
||||||
|
const content = resp.headers.get('Content-Type')?.toLowerCase();
|
||||||
|
if(content?.includes('json')) resp.data = <T>await data.json();
|
||||||
|
else if(content?.includes('text')) resp.data = <T>await data.text();
|
||||||
|
else if(content?.includes('form')) resp.data = <T>await data.formData();
|
||||||
|
else if(content?.includes('application')) resp.data = <T>await data.blob();
|
||||||
|
else resp.data = <any>null;
|
||||||
|
|
||||||
|
if(resp.ok) res(resp);
|
||||||
|
else rej(resp);
|
||||||
|
})
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -1,8 +1,9 @@
|
|||||||
export * from './array';
|
export * from './array';
|
||||||
export * from './aset';
|
export * from './aset';
|
||||||
export * from './download';
|
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 './math';
|
||||||
export * from './misc';
|
export * from './misc';
|
||||||
@ -10,4 +11,3 @@ export * from './objects';
|
|||||||
export * from './promise-progress';
|
export * from './promise-progress';
|
||||||
export * from './string';
|
export * from './string';
|
||||||
export * from './time';
|
export * from './time';
|
||||||
export * from './xhr';
|
|
||||||
|
@ -43,16 +43,16 @@ export function deepCopy<T>(value: T): T {
|
|||||||
* @return {any} The des
|
* @return {any} The des
|
||||||
*/
|
*/
|
||||||
export function deepMerge<T>(target: any, ...sources: any[]): T {
|
export function deepMerge<T>(target: any, ...sources: any[]): T {
|
||||||
for(const source of sources) {
|
sources.forEach(s => {
|
||||||
for(const key in source) {
|
for(const key in s) {
|
||||||
if(source[key] && typeof source[key] == 'object' && !Array.isArray(source[key])) {
|
if(s[key] && typeof s[key] == 'object' && !Array.isArray(s[key])) {
|
||||||
if(!target[key]) target[key] = {};
|
if(!target[key]) target[key] = {};
|
||||||
deepMerge(target[key], source[key]);
|
deepMerge(target[key], s[key]);
|
||||||
} else {
|
} else {
|
||||||
target[key] = source[key];
|
target[key] = s[key];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
return target;
|
return target;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -15,12 +15,38 @@ export class PromiseProgress<T> extends Promise<T> {
|
|||||||
super((resolve, reject) => executor(
|
super((resolve, reject) => executor(
|
||||||
(value: T) => resolve(value),
|
(value: T) => resolve(value),
|
||||||
(reason: any) => reject(reason),
|
(reason: any) => reject(reason),
|
||||||
(progress: number) => this.progress = progress
|
(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) {
|
onProgress(callback: ProgressCallback) {
|
||||||
this.listeners.push(callback);
|
this.listeners.push(callback);
|
||||||
return this;
|
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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
90
src/xhr.ts
90
src/xhr.ts
@ -1,90 +0,0 @@
|
|||||||
import {clean} from './objects';
|
|
||||||
|
|
||||||
export type Interceptor = (request: Response, next: () => void) => void;
|
|
||||||
|
|
||||||
export type RequestOptions = {
|
|
||||||
url?: string;
|
|
||||||
fragment?: string;
|
|
||||||
query?: {key: string, value: string}[] | {[key: string]: 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');
|
|
||||||
let url = (opts.url?.startsWith('http') ? opts.url : (this.opts.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 && !(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()));
|
|
||||||
}
|
|
||||||
|
|
||||||
const decode = async () => {
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
const payload = await decode();
|
|
||||||
if(resp.ok) return payload;
|
|
||||||
const text = resp.statusText || (typeof payload == 'string' ? payload : null);
|
|
||||||
throw (text ? new Error(text) : payload);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
@ -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