Compare commits

...

6 Commits

Author SHA1 Message Date
d29d0d5121 PathEvent caching fix
All checks were successful
Build / Publish Docs (push) Successful in 1m47s
Build / Build NPM Project (push) Successful in 34s
Build / Tag Version (push) Successful in 9s
2026-07-14 20:21:05 -04:00
5b3bbdf02c Added node support for uploadWithProgress
All checks were successful
Build / Publish Docs (push) Successful in 54s
Build / Build NPM Project (push) Successful in 38s
Build / Tag Version (push) Successful in 9s
2026-07-13 22:16:58 -04:00
6b379270a9 Fixed path event dir property
All checks were successful
Build / Publish Docs (push) Successful in 1m3s
Build / Build NPM Project (push) Successful in 36s
Build / Tag Version (push) Successful in 9s
2026-06-15 09:55:38 -04:00
28716c7b5a Added titleCase helper
All checks were successful
Build / Publish Docs (push) Successful in 2m20s
Build / Build NPM Project (push) Successful in 2m29s
Build / Tag Version (push) Successful in 9s
2026-04-15 21:59:42 -04:00
d530f6abdf Cross timezone day of week fix
All checks were successful
Build / Build NPM Project (push) Successful in 53s
Build / Tag Version (push) Successful in 11s
Build / Publish Docs (push) Successful in 40s
2026-04-11 23:19:10 -04:00
cbee6a4509 Timezone abbreviation support
All checks were successful
Build / Publish Docs (push) Successful in 1m48s
Build / Build NPM Project (push) Successful in 2m48s
Build / Tag Version (push) Successful in 10s
2026-04-11 16:29:53 -04:00
7 changed files with 7094 additions and 38 deletions

1
.gitignore vendored
View File

@@ -10,6 +10,7 @@ uploads
public/momentum*js public/momentum*js
junit.xml junit.xml
/docs/ /docs/
main.mjs
# Logs # Logs
*.log *.log

6927
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{ {
"name": "@ztimson/utils", "name": "@ztimson/utils",
"version": "0.29.1", "version": "0.29.7",
"description": "Utility library", "description": "Utility library",
"author": "Zak Timson", "author": "Zak Timson",
"license": "MIT", "license": "MIT",

View File

@@ -83,6 +83,7 @@ export function timestampFilename(name?: string, date: Date | number | string =
/** /**
* Upload file to URL with progress callback using PromiseProgress * Upload file to URL with progress callback using PromiseProgress
* Works in both browser (with progress) and Node.js (fallback without progress)
* *
* @param {{url: string, files: File[], headers?: {[p: string]: string}, withCredentials?: boolean}} options * @param {{url: string, files: File[], headers?: {[p: string]: string}, withCredentials?: boolean}} options
* @return {PromiseProgress<T>} Promise of request with `onProgress` callback * @return {PromiseProgress<T>} Promise of request with `onProgress` callback
@@ -93,10 +94,12 @@ export function uploadWithProgress<T>(options: {
headers?: {[key: string]: string}; headers?: {[key: string]: string};
withCredentials?: boolean; withCredentials?: boolean;
}): PromiseProgress<T> { }): PromiseProgress<T> {
// Browser environment - use XMLHttpRequest for progress
if (typeof XMLHttpRequest !== 'undefined') {
return new PromiseProgress<T>((res, rej, prog) => { return new PromiseProgress<T>((res, rej, prog) => {
const xhr = new XMLHttpRequest(); const xhr = new XMLHttpRequest();
const formData = new FormData(); const formData = new FormData();
options.files.forEach(f => formData.append('file', f)); options.files.forEach(f => formData.append('files', f));
xhr.withCredentials = !!options.withCredentials; xhr.withCredentials = !!options.withCredentials;
xhr.upload.addEventListener('progress', (event) => event.lengthComputable ? prog(event.loaded / event.total) : null); xhr.upload.addEventListener('progress', (event) => event.lengthComputable ? prog(event.loaded / event.total) : null);
@@ -108,4 +111,23 @@ export function uploadWithProgress<T>(options: {
Object.entries(options.headers || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value)); Object.entries(options.headers || {}).forEach(([key, value]) => xhr.setRequestHeader(key, value));
xhr.send(formData); xhr.send(formData);
}); });
}
// Node.js environment - fallback to fetch without progress
return new PromiseProgress<T>(async (res, rej) => {
try {
const formData = new FormData();
options.files.forEach(f => formData.append('files', f));
const response = await fetch(options.url, {method: 'POST', headers: options.headers || {}, body: formData});
if(!response.ok) {
const error = await response.text();
rej(JSONAttemptParse(error));
} else {
const result = await response.text();
res(<T>JSONAttemptParse(result));
}
} catch (error) {
rej(error);
}
});
} }

View File

@@ -76,8 +76,18 @@ export class PathEvent {
/** Whether this path contains glob patterns */ /** Whether this path contains glob patterns */
hasGlob!: boolean; hasGlob!: boolean;
/** Internal cache for PathEvent instances to avoid redundant parsing */ /** Internal cache for parsed path data (plain objects, not instances) */
private static pathEventCache: Map<string, PathEvent> = new Map(); private static pathEventCache: Map<string, {
module: string;
fullPath: string;
dir: string;
path: string;
name: string;
methods: Method[];
hasGlob: boolean;
}> = new Map();
/** Max size for path cache before LRU eviction */
private static readonly MAX_PATH_CACHE_SIZE = 1000;
/** Cache for compiled permissions (path + required permissions → result) */ /** Cache for compiled permissions (path + required permissions → result) */
private static permissionCache: Map<string, PathEvent> = new Map(); private static permissionCache: Map<string, PathEvent> = new Map();
/** Max size for permission cache before LRU eviction */ /** Max size for permission cache before LRU eviction */
@@ -111,8 +121,20 @@ export class PathEvent {
return; return;
} }
// Check cache and reconstruct from plain object
if(PathEvent.pathEventCache.has(e)) { if(PathEvent.pathEventCache.has(e)) {
Object.assign(this, PathEvent.pathEventCache.get(e)!); const cached = PathEvent.pathEventCache.get(e)!;
// Move to end (LRU - most recently used)
PathEvent.pathEventCache.delete(e);
PathEvent.pathEventCache.set(e, cached);
this.module = cached.module;
this.fullPath = cached.fullPath;
this.dir = cached.dir;
this.path = cached.path;
this.name = cached.name;
this.methods = new ASet(cached.methods);
this.hasGlob = cached.hasGlob;
return; return;
} }
@@ -128,19 +150,49 @@ export class PathEvent {
this.name = ''; this.name = '';
this.methods = new ASet<Method>(p === '*' ? ['*'] : <any>method.split('')); this.methods = new ASet<Method>(p === '*' ? ['*'] : <any>method.split(''));
this.hasGlob = true; this.hasGlob = true;
PathEvent.pathEventCache.set(e, this);
// LRU eviction
if(PathEvent.pathEventCache.size >= PathEvent.MAX_PATH_CACHE_SIZE) {
const firstKey = PathEvent.pathEventCache.keys().next().value;
if(firstKey) PathEvent.pathEventCache.delete(firstKey);
}
PathEvent.pathEventCache.set(e, {
module: this.module,
fullPath: this.fullPath,
dir: this.dir,
path: this.path,
name: this.name,
methods: [...this.methods],
hasGlob: this.hasGlob
});
return; return;
} }
let temp = p.split('/').filter(p => !!p); let temp = p.split('/').filter(p => !!p);
this.module = temp.splice(0, 1)[0] || ''; this.module = temp.splice(0, 1)[0] || '';
this.path = temp.join('/'); this.path = temp.join('/');
this.dir = temp.length > 2 ? temp.slice(0, -1).join('/') : ''; this.dir = temp.length > 1 ? temp.slice(0, -1).join('/') : '';
this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`; this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`;
this.name = temp.pop() || ''; this.name = temp.pop() || '';
this.hasGlob = this.fullPath.includes('*'); this.hasGlob = this.fullPath.includes('*');
this.methods = new ASet(<any>method.split('')); this.methods = new ASet(<any>method.split(''));
PathEvent.pathEventCache.set(e, this);
// LRU eviction
if(PathEvent.pathEventCache.size >= PathEvent.MAX_PATH_CACHE_SIZE) {
const firstKey = PathEvent.pathEventCache.keys().next().value;
if(firstKey) PathEvent.pathEventCache.delete(firstKey);
}
PathEvent.pathEventCache.set(e, {
module: this.module,
fullPath: this.fullPath,
dir: this.dir,
path: this.path,
name: this.name,
methods: [...this.methods],
hasGlob: this.hasGlob
});
} }
/** /**

View File

@@ -241,7 +241,6 @@ export function snakeCase(str?: string): string {
return wordSegments(str).map(w => w.toLowerCase()).join("_"); return wordSegments(str).map(w => w.toLowerCase()).join("_");
} }
/** /**
* Splice a string together (Similar to Array.splice) * Splice a string together (Similar to Array.splice)
* *
@@ -257,6 +256,20 @@ export function strSplice(str: string, start: number, deleteCount: number, inser
return before + insert + after; return before + insert + after;
} }
function titleCase(str: string) {
// Normalize separators: replace underscores and hyphens with spaces
let normalizedStr = str.replace(/(_|-)/g, ' ');
// Handle CamelCase/PascalCase boundaries: insert a space before capital letters
normalizedStr = normalizedStr.replace(/([a-z])([A-Z])/g, '$1 $2');
// Lowercase the whole string, split by any whitespace, and capitalize each word
let words = normalizedStr.toLowerCase().split(/\s+/).filter(Boolean);
const titledWords = words.map(word => {
if (word.length === 0) return '';
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
});
return titledWords.join(' ');
}
/** /**
* Find all substrings that match a given pattern. * Find all substrings that match a given pattern.
* *

View File

@@ -78,19 +78,62 @@ export function dayOfYear(date: Date): number {
* *
* @param {string} format How date string will be formatted, default: `YYYY-MM-DD H:mm A` * @param {string} format How date string will be formatted, default: `YYYY-MM-DD H:mm A`
* @param {Date | number | string} date Date or timestamp, defaults to now * @param {Date | number | string} date Date or timestamp, defaults to now
* @param tz Set timezone offset * @param tz Set timezone offset in: hours (-4) or minutes (430) or IANA string (America/New_York)
* @return {string} Formated date * @return {string} Formated date
*/ */
export function formatDate(format: string = 'YYYY-MM-DD H:mm', date: Date | number | string = new Date(), tz: string | number = 'local'): string { export function formatDate(format: string = 'YYYY-MM-DD H:mm', date: Date | number | string = new Date(), tz: string | number = 'local'): string {
if (typeof date === 'number' || typeof date === 'string') date = new Date(date); if (typeof date === 'number' || typeof date === 'string') date = new Date(date);
if (isNaN(date.getTime())) throw new Error('Invalid date input'); if (isNaN(date.getTime())) throw new Error('Invalid date input');
const numericTz = typeof tz === 'number';
const localTz = tz === 'local' || (!numericTz && tz.toLowerCase?.() === 'local'); const TIMEZONE_MAP = [
const tzName = localTz ? Intl.DateTimeFormat().resolvedOptions().timeZone : numericTz ? 'UTC' : tz; { name: 'IDLW', iana: 'Etc/GMT+12', offset: -720 },
{ name: 'SST', iana: 'Pacific/Pago_Pago', offset: -660 },
{ name: 'HST', iana: 'Pacific/Honolulu', offset: -600 },
{ name: 'AKST', iana: 'America/Anchorage', offset: -540 },
{ name: 'PST', iana: 'America/Los_Angeles', offset: -480 },
{ name: 'MST', iana: 'America/Denver', offset: -420 },
{ name: 'CST', iana: 'America/Chicago', offset: -360 },
{ name: 'EST', iana: 'America/New_York', offset: -300 },
{ name: 'AST', iana: 'America/Halifax', offset: -240 },
{ name: 'BRT', iana: 'America/Sao_Paulo', offset: -180 },
{ name: 'MAT', iana: 'Atlantic/South_Georgia', offset: -120 },
{ name: 'AZOT', iana: 'Atlantic/Azores', offset: -60 },
{ name: 'UTC', iana: 'UTC', offset: 0 },
{ name: 'CET', iana: 'Europe/Paris', offset: 60 },
{ name: 'EET', iana: 'Europe/Athens', offset: 120 },
{ name: 'MSK', iana: 'Europe/Moscow', offset: 180 },
{ name: 'GST', iana: 'Asia/Dubai', offset: 240 },
{ name: 'PKT', iana: 'Asia/Karachi', offset: 300 },
{ name: 'IST', iana: 'Asia/Kolkata', offset: 330 },
{ name: 'BST', iana: 'Asia/Dhaka', offset: 360 },
{ name: 'ICT', iana: 'Asia/Bangkok', offset: 420 },
{ name: 'CST', iana: 'Asia/Shanghai', offset: 480 },
{ name: 'JST', iana: 'Asia/Tokyo', offset: 540 },
{ name: 'AEST', iana: 'Australia/Sydney', offset: 600 },
{ name: 'SBT', iana: 'Pacific/Guadalcanal', offset: 660 },
{ name: 'TOT', iana: 'Pacific/Tongatapu', offset: 780 },
{ name: 'LINT', iana: 'Pacific/Kiritimati', offset: 840 },
];
let numericTz = typeof tz === 'number';
const localTz = tz === 'local' || (!numericTz && tz.toString().toLowerCase?.() === 'local');
let tzName = localTz ? Intl.DateTimeFormat().resolvedOptions().timeZone : numericTz ? 'UTC' : tz;
let offsetMinutes = 0;
if (numericTz) {
// Convert hours to minutes if offset is small (likely hours)
offsetMinutes = Math.abs(tz as number) < 24 ? (tz as number) * 60 : (tz as number);
// Find closest matching timezone
const closest = TIMEZONE_MAP.reduce((prev, curr) =>
Math.abs(curr.offset - offsetMinutes) < Math.abs(prev.offset - offsetMinutes) ? curr : prev
);
tzName = closest.iana;
}
if (!numericTz && tzName !== 'UTC') { if (!numericTz && tzName !== 'UTC') {
try { try {
new Intl.DateTimeFormat('en-US', { timeZone: tzName }).format(); new Intl.DateTimeFormat('en-US', { timeZone: <string>tzName }).format();
} catch { } catch {
throw new Error(`Invalid timezone: ${tzName}`); throw new Error(`Invalid timezone: ${tzName}`);
} }
@@ -99,9 +142,10 @@ export function formatDate(format: string = 'YYYY-MM-DD H:mm', date: Date | numb
let zonedDate = new Date(date); let zonedDate = new Date(date);
let get: (fn: 'FullYear' | 'Month' | 'Date' | 'Day' | 'Hours' | 'Minutes' | 'Seconds' | 'Milliseconds') => number; let get: (fn: 'FullYear' | 'Month' | 'Date' | 'Day' | 'Hours' | 'Minutes' | 'Seconds' | 'Milliseconds') => number;
const partsMap: Record<string, string> = {}; const partsMap: Record<string, string> = {};
if (!numericTz && tzName !== 'UTC') { if (!numericTz && tzName !== 'UTC') {
const parts = new Intl.DateTimeFormat('en-US', { const parts = new Intl.DateTimeFormat('en-US', {
timeZone: tzName, timeZone: <string>tzName,
year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'long', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'long',
hour: '2-digit', minute: '2-digit', second: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit',
hour12: false hour12: false
@@ -111,7 +155,7 @@ export function formatDate(format: string = 'YYYY-MM-DD H:mm', date: Date | numb
}); });
const monthValue = parseInt(partsMap.month) - 1; const monthValue = parseInt(partsMap.month) - 1;
const dayOfWeekValue = new Date(`${partsMap.year}-${partsMap.month}-${partsMap.day}`).getDay(); const dayOfWeekValue = new Date(Date.UTC(parseInt(partsMap.year), parseInt(partsMap.month) - 1, parseInt(partsMap.day))).getUTCDay();
const hourValue = parseInt(partsMap.hour); const hourValue = parseInt(partsMap.hour);
get = (fn: 'FullYear' | 'Month' | 'Date' | 'Day' | 'Hours' | 'Minutes' | 'Seconds' | 'Milliseconds'): number => { get = (fn: 'FullYear' | 'Month' | 'Date' | 'Day' | 'Hours' | 'Minutes' | 'Seconds' | 'Milliseconds'): number => {
@@ -127,8 +171,7 @@ export function formatDate(format: string = 'YYYY-MM-DD H:mm', date: Date | numb
} }
}; };
} else { } else {
const offset = numericTz ? tz as number : 0; zonedDate = new Date(date.getTime() + offsetMinutes * 60 * 1000);
zonedDate = new Date(date.getTime() + offset * 60 * 60 * 1000);
get = (fn: 'FullYear' | 'Month' | 'Date' | 'Day' | 'Hours' | 'Minutes' | 'Seconds' | 'Milliseconds'): number => zonedDate[`getUTC${fn}`](); get = (fn: 'FullYear' | 'Month' | 'Date' | 'Day' | 'Hours' | 'Minutes' | 'Seconds' | 'Milliseconds'): number => zonedDate[`getUTC${fn}`]();
} }
@@ -139,14 +182,13 @@ export function formatDate(format: string = 'YYYY-MM-DD H:mm', date: Date | numb
} }
function getTZOffset(): string { function getTZOffset(): string {
if (numericTz) { if(numericTz) {
const total = (tz as number) * 60; const hours = Math.floor(Math.abs(offsetMinutes) / 60);
const hours = Math.floor(Math.abs(total) / 60); const mins = Math.abs(offsetMinutes) % 60;
const mins = Math.abs(total) % 60; return `${offsetMinutes >= 0 ? '+' : '-'}${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
return `${tz >= 0 ? '+' : '-'}${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
} }
try { try {
const offset = new Intl.DateTimeFormat('en-US', {timeZone: tzName, timeZoneName: 'longOffset', hour: '2-digit', minute: '2-digit',}) const offset = new Intl.DateTimeFormat('en-US', {timeZone: <string>tzName, timeZoneName: 'longOffset', hour: '2-digit', minute: '2-digit',})
.formatToParts(<Date>date).find(p => p.type === 'timeZoneName')?.value.match(/([+-]\d{2}:\d{2})/)?.[1]; .formatToParts(<Date>date).find(p => p.type === 'timeZoneName')?.value.match(/([+-]\d{2}:\d{2})/)?.[1];
if (offset) return offset; if (offset) return offset;
} catch {} } catch {}
@@ -154,12 +196,11 @@ export function formatDate(format: string = 'YYYY-MM-DD H:mm', date: Date | numb
} }
function getTZAbbr(): string { function getTZAbbr(): string {
if (numericTz && tz === 0) return 'UTC';
try { try {
return new Intl.DateTimeFormat('en-US', { timeZone: tzName, timeZoneName: 'short' }) return new Intl.DateTimeFormat('en-US', { timeZone: <string>tzName, timeZoneName: 'short' })
.formatToParts(<Date>date).find(p => p.type === 'timeZoneName')?.value || ''; .formatToParts(<Date>date).find(p => p.type === 'timeZoneName')?.value || '';
} catch { } catch {
return tzName; return <string>tzName;
} }
} }