Compare commits

...

8 Commits

Author SHA1 Message Date
1eff60e7dd Fixed build
All checks were successful
Build / Build NPM Project (push) Successful in 22s
Build / Tag Version (push) Successful in 5s
2024-06-16 08:36:45 -04:00
1d9ad2ef63 Fixed module exports?
All checks were successful
Build / Build NPM Project (push) Successful in 38s
Build / Tag Version (push) Successful in 5s
Build / Publish (push) Successful in 7s
2024-06-16 08:29:49 -04:00
973a884b3e Added query & fragment to xhr
All checks were successful
Build / Build NPM Project (push) Successful in 38s
Build / Tag Version (push) Successful in 5s
Build / Publish (push) Successful in 7s
2024-06-15 22:29:37 -04:00
6f60f8bd94 Changed XHR error handling
All checks were successful
Build / Build NPM Project (push) Successful in 1m13s
Build / Tag Version (push) Successful in 16s
Build / Publish (push) Successful in 22s
2024-05-31 13:42:28 -04:00
07606cd996 Removed custom errors from xhr helper
All checks were successful
Build / Build NPM Project (push) Successful in 1m14s
Build / Tag Version (push) Successful in 16s
Build / Publish (push) Successful in 23s
2024-05-31 12:37:01 -04:00
3ca956e531 Fixed fetch errors
All checks were successful
Build / Build NPM Project (push) Successful in 1m27s
Build / Tag Version (push) Successful in 18s
Build / Publish (push) Successful in 26s
2024-05-31 10:04:51 -04:00
9350c837e5 Added math functions
All checks were successful
Build / Build NPM Project (push) Successful in 1m29s
Build / Tag Version (push) Successful in 19s
Build / Publish (push) Successful in 26s
2024-05-27 13:51:41 -04:00
86196c3feb Added promise progress
All checks were successful
Build / Build NPM Project (push) Successful in 17s
Build / Tag Version (push) Successful in 4s
Build / Publish (push) Successful in 7s
2024-04-27 23:09:12 -04:00
10 changed files with 109 additions and 129 deletions

View File

@ -37,11 +37,15 @@ jobs:
key: node_modules key: node_modules
pattern: node_modules pattern: node_modules
- name: Cache Artifacts - name: Upload to Registry
uses: ztimson/actions/cache@develop uses: ztimson/actions/npm/publish@develop
- name: Upload to NPM
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 +63,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
View File

@ -1,12 +1,12 @@
{ {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.4.0", "version": "0.10.4",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.4.0", "version": "0.10.4",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@types/jest": "^29.5.12", "@types/jest": "^29.5.12",

View File

@ -1,6 +1,6 @@
{ {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.8.2", "version": "0.11.2",
"description": "Utility library", "description": "Utility library",
"author": "Zak Timson", "author": "Zak Timson",
"license": "MIT", "license": "MIT",
@ -12,6 +12,12 @@
"main": "./dist/utils.cjs", "main": "./dist/utils.cjs",
"module": "./dist/utils.mjs", "module": "./dist/utils.mjs",
"types": "./dist/index.d.ts", "types": "./dist/index.d.ts",
"exports": {
".": {
"require": "./dist/utils.cjs",
"import": "./dist/utils.mjs"
}
},
"scripts": { "scripts": {
"build": "npx tsc && npx vite build", "build": "npx tsc && npx vite build",
"test": "npx jest", "test": "npx jest",

View File

@ -1,11 +1,3 @@
import {TypedEmitter, TypedEvents} from './emitter';
export type DownloadEvents = TypedEvents & {
complete: (blob: Blob) => any;
failed: (error: Error) => any;
progress: (progress: number) => any;
}
export function download(href: any, name: string) { export function download(href: any, name: string) {
const a = document.createElement('a'); const a = document.createElement('a');
a.href = href; a.href = href;
@ -14,40 +6,3 @@ export function download(href: any, name: string) {
a.click(); a.click();
document.body.removeChild(a); document.body.removeChild(a);
} }
/**
* Download a URL using fetch so progress can be tracked. Uses Typed Emitter to emit a "progress" &
* "complete" event.
*
* @param {string} url
* @param {string} downloadName
* @return {TypedEmitter<DownloadEvents>}
*/
export function downloadProgress(url: string, downloadName?: string) {
const progress = new TypedEmitter<DownloadEvents>();
fetch(url).then(response => {
if(!response.ok) return progress.emit('failed', new Error(response.statusText));
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);
if(downloadName) {
const url = URL.createObjectURL(blob);
download(url, downloadName);
URL.revokeObjectURL(url);
}
progress.emit('complete', blob);
} else {
const chunk = result.value;
chunks.push(chunk);
loaded += chunk.length;
progress.emit('progress', loaded / total);
reader.read().then(processResult);
}
});
}).catch(err => progress.emit('failed', err));
return progress;
}

View File

@ -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;

View File

@ -4,9 +4,10 @@ export * from './download';
export * from './emitter'; export * from './emitter';
export * from './errors'; export * from './errors';
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 './upload';
export * from './xhr'; export * from './xhr';

45
src/math.ts Normal file
View 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]));
}

26
src/promise-progress.ts Normal file
View File

@ -0,0 +1,26 @@
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
));
}
onProgress(callback: ProgressCallback) {
this.listeners.push(callback);
return this;
}
}

View File

@ -1,30 +0,0 @@
import {TypedEmitter, TypedEvents} from './emitter';
export type UploadEvents = TypedEvents & {
complete: () => any;
failed: (err: Error) => any;
progress: (progress: number) => any;
}
export function uploadProgress(files : File | File[], url: string) {
const xhr = new XMLHttpRequest();
const progress = new TypedEmitter<UploadEvents>();
const formData = new FormData();
(Array.isArray(files) ? files : [files])
.forEach(f => formData.append('file', f));
xhr.upload.addEventListener("progress", (event) => {
if(event.lengthComputable) progress.emit('progress', event.loaded / event.total);
});
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if(xhr.status >= 200 && xhr.status < 300) progress.emit('complete');
else progress.emit('failed', new Error(xhr.responseText));
}
};
xhr.open("POST", url, true);
xhr.send(formData);
return progress;
}

View File

@ -1,10 +1,11 @@
import {TypedEmitter, TypedEvents} from './emitter.ts';
import {clean} from './objects'; import {clean} from './objects';
export type Interceptor = (request: Response, next: () => void) => void; export type Interceptor = (request: Response, next: () => void) => void;
export type RequestOptions = { export type RequestOptions = {
url?: string; url?: string;
fragment?: string;
query?: {key: string, value: string}[] | {[key: string]: string};
method?: 'GET' | 'POST' | 'PATCH' | 'DELETE'; method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
body?: any; body?: any;
headers?: {[key: string | symbol]: string | null | undefined}; headers?: {[key: string | symbol]: string | null | undefined};
@ -48,7 +49,13 @@ export class XHR {
async request<T>(opts: RequestOptions = {}): Promise<T> { async request<T>(opts: RequestOptions = {}): Promise<T> {
if(!this.opts.url && !opts.url) throw new Error('URL needs to be set'); 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'); 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 // Prep headers
const headers = <any>clean({ const headers = <any>clean({
@ -68,10 +75,16 @@ export class XHR {
await new Promise<void>(res => fn(resp, () => res())); await new Promise<void>(res => fn(resp, () => res()));
} }
if(!resp.ok) throw new Error(resp.statusText); 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('application/json')) return await resp.json();
if(!opts.skipConverting && resp.headers.get('Content-Type')?.startsWith('text/plain')) return await <any>resp.text(); if(!opts.skipConverting && resp.headers.get('Content-Type')?.startsWith('text/plain')) return await <any>resp.text();
return resp; 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);
}); });
} }
} }