Compare commits
	
		
			193 Commits
		
	
	
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 057528b0c5 | |||
| 1595aea529 | |||
| 08503de552 | |||
| a9a9b04a5a | |||
| a7b19900da | |||
| 34227e5c4b | |||
| 7e8352ed2a | |||
| 751177c981 | |||
| 5849a97c21 | |||
| fcae9e107e | |||
| 5bb5067abc | |||
| 2064880673 | |||
| fdefdf354d | |||
| 31998c01d6 | |||
| c5270fbd7e | |||
| bfe9493d23 | |||
| 1b6fe42f78 | |||
| c3d8d75ba3 | |||
| e2d756fe28 | |||
| 52f64f9e78 | |||
| 4caf0e5048 | |||
| 55b871f4c1 | |||
| fb077775b6 | |||
| 2d2b2b8216 | |||
| b473ade178 | |||
| b3223661dd | |||
| c36af83918 | |||
| 9ec70430a5 | |||
| 397b165e55 | |||
| c1577c2106 | |||
| 2b12916246 | |||
| 5efb045f22 | |||
| 7119390681 | |||
| fd95c0c697 | |||
| 1ab8e6424b | |||
| 035a1d35cb | |||
| e78120b067 | |||
| 71552aa243 | |||
| ce3878e18b | |||
| 388a09718b | |||
| 59bce9d28d | |||
| 387e6b2512 | |||
| d748d740ea | |||
| c8f44584a2 | |||
| 8b84d170a6 | |||
| 37df7e6090 | |||
| a8b6fdd5a6 | |||
| 3e899e6ae4 | |||
| 08fa5b6783 | |||
| 529f1e2b30 | |||
| 87ef246760 | |||
| 10ac6101f4 | |||
| b5d534dc8c | |||
| d140b2edd1 | |||
| 56f6681492 | |||
| 64945a647c | |||
| adafd61c83 | |||
| 7747dc5558 | |||
| 947bdbc6d4 | |||
| e2b8c35535 | |||
| 3b7d28de4b | |||
| 8f7e816571 | |||
| 8c1fb2d8cb | |||
| 91dc17667e | |||
| 11cfc67650 | |||
| 4ed23e1502 | |||
| e3bbd13ed8 | |||
| 1877bac7ce | |||
| c06538a725 | |||
| a08b0c4eea | |||
| 1b03ae875b | |||
| af1da75a82 | |||
| e19768688d | |||
| 6d706d4c15 | |||
| 97f2bcce2e | |||
| 2a7fa18c0e | |||
| fec373ca4c | |||
| cf122ef9e8 | |||
| 76b570b3fe | |||
| 4fecf10d11 | |||
| 028b9c0f4c | |||
| d938996a66 | |||
| cdcaeda67c | |||
| 482c90b53b | |||
| 7500ba502f | |||
| edc059d17d | |||
| 48cfbee46e | |||
| 26cc18ffb3 | |||
| 3fd5c5ed57 | |||
| 2e4559d805 | |||
| 95f8d5762c | |||
| 3bc82fab45 | |||
| 6b15848896 | |||
| 9a0f32323e | |||
| f952abc95a | |||
| 21fc1378b8 | |||
| a03567eba3 | |||
| f9fc4fb7ff | |||
| ff16f3bf9b | |||
| e0085ecb6f | |||
| 1c2c18b65d | |||
| cd5741d6ab | |||
| 5b9e0714ce | |||
| a3b34ef03f | |||
| f755d8f5b8 | |||
| 35c471eef4 | |||
| fe9fdb9384 | |||
| a5d7a35fdc | |||
| cb117273a7 | |||
| 3bda688b1e | |||
| 446b1aa9db | |||
| 30be1c5a91 | |||
| 6b328e64ba | |||
| 435be31347 | |||
| 2522635815 | |||
| e8fdca8236 | |||
| 67ae86d69b | |||
| 87db4d4755 | |||
| 0fb1e13ba0 | |||
| ff4401934c | |||
| ce3c8d012a | |||
| a86e8350ee | |||
| 7b4e17e4c4 | |||
| fa66820c76 | |||
| 49a2df8cd4 | |||
| ccf3fcb043 | |||
| 341ef37205 | |||
| 0eab2630ad | |||
| 2f59a9d02e | |||
| ce2f32dd45 | |||
| ce40b5b1e7 | |||
| 2500bcdcf1 | |||
| db18c010aa | |||
| b292d5ed17 | |||
| a1ea8cdf67 | |||
| fbbe3c99ef | |||
| 1c1a3f6a6e | |||
| 2dce1ad9ac | |||
| cebfd2c508 | |||
| 7c5cf3535d | |||
| 847b493772 | |||
| b1005227ab | |||
| 3a389de72e | |||
| 151465aa65 | |||
| b103b6f786 | |||
| 3b486310de | |||
| 8699fb49ff | |||
| fdb29e7984 | |||
| 274c22bb83 | |||
| b21f462d35 | |||
| 0f10aebfd2 | |||
| 1af23ac544 | |||
| 494cfaaccd | |||
| 23df6ad265 | |||
| 2fda11f3b7 | |||
| 379de273c4 | |||
| c51239d12b | |||
| e4229296c1 | |||
| b93ed45521 | |||
| 3e8f5cc00b | |||
| 54a2880391 | |||
| b7aeee4706 | |||
| b3eab0d6c9 | |||
| ad4194a981 | |||
| e1f22a01a6 | |||
| 91c0858d9f | |||
| 8094b6507f | |||
| e40f410830 | |||
| c1043e65e2 | |||
| 67d9928a61 | |||
| e6636d373b | |||
| 811d797e1b | |||
| 0909c4f648 | |||
| 8384d6a299 | |||
| 19251244d2 | |||
| 51549db3d9 | |||
| 3bf8c7bd09 | |||
| e8e56a3f72 | |||
| 98f867ed4e | |||
| 94cea19728 | |||
| 3896949fc1 | |||
| a0f0699a85 | |||
| adcd6eaf79 | |||
| afb6ca0803 | |||
| e699f8a634 | |||
| c7dd91e9cd | |||
| 20f36cc573 | |||
| 57446ef09a | |||
| 6d13df39f5 | |||
| 2d63db0ebb | |||
| 535fc0271e | |||
| d587b92ea4 | |||
| 26c6084052 | 
@@ -13,3 +13,7 @@ quote_type = single
 | 
			
		||||
[*.md]
 | 
			
		||||
max_line_length = off
 | 
			
		||||
trim_trailing_whitespace = false
 | 
			
		||||
 | 
			
		||||
[*.{yaml,yml}]
 | 
			
		||||
indent_style = space
 | 
			
		||||
indent_size = 2
 | 
			
		||||
							
								
								
									
										40
									
								
								.github/workflows/build.yaml
									
									
									
									
										vendored
									
									
								
							
							
						
						
									
										40
									
								
								.github/workflows/build.yaml
									
									
									
									
										vendored
									
									
								
							@@ -48,3 +48,43 @@ jobs:
 | 
			
		||||
        uses: ztimson/actions/tag@develop
 | 
			
		||||
        with:
 | 
			
		||||
          tag: ${{env.VERSION}}
 | 
			
		||||
  docs:
 | 
			
		||||
    name: Publish Docs
 | 
			
		||||
    runs-on: ubuntu-latest
 | 
			
		||||
    container: docker:dind
 | 
			
		||||
    steps:
 | 
			
		||||
      - name: Clone Repository
 | 
			
		||||
        uses: ztimson/actions/clone@develop
 | 
			
		||||
 | 
			
		||||
      - name: Build Image
 | 
			
		||||
        run: |
 | 
			
		||||
          REGISTRY=$(echo ${{github.server_url}} | sed s%http://%% | sed s%https://%%)
 | 
			
		||||
          docker build -t "$REGISTRY/${{github.repository}}:${{github.ref_name}}" .
 | 
			
		||||
 | 
			
		||||
      - name: Build Image
 | 
			
		||||
        run: |
 | 
			
		||||
          echo "CHECKSUM: ${{env.CHECKSUM}}"
 | 
			
		||||
          REGISTRY=$(echo ${{github.server_url}} | sed s%http://%% | sed s%https://%%)
 | 
			
		||||
          docker build -t "$REGISTRY/${{github.repository}}:${{github.ref_name}}" --build-arg LICENSE_KEY="${{secrets.LICENSE_KEY}}" --build-arg UPDATE_TOKEN="${{secrets.UPDATE_TOKEN}}" .
 | 
			
		||||
 | 
			
		||||
      - name: Publish Branch Tag
 | 
			
		||||
        run: |
 | 
			
		||||
          REGISTRY=$(echo ${{github.server_url}} | sed s%http://%% | sed s%https://%%)
 | 
			
		||||
          docker login -u ${{github.repository_owner}} -p ${{secrets.DEPLOY_TOKEN}} $REGISTRY
 | 
			
		||||
          docker push "$REGISTRY/${{github.repository}}:${{github.ref_name}}"
 | 
			
		||||
 | 
			
		||||
      - name: Publish Version Tag
 | 
			
		||||
        run: |
 | 
			
		||||
          if [ "${{github.ref_name}}" = "master" ]; then
 | 
			
		||||
            REGISTRY=$(echo ${{github.server_url}} | sed s%http://%% | sed s%https://%%)
 | 
			
		||||
            docker tag "$REGISTRY/${{github.repository}}:${{github.ref_name}}" "$REGISTRY/${{github.repository}}:${{env.VERSION}}"
 | 
			
		||||
            docker push "$REGISTRY/${{github.repository}}:${{env.VERSION}}"
 | 
			
		||||
          fi
 | 
			
		||||
 | 
			
		||||
      - name: Publish Latest Tag
 | 
			
		||||
        run: |
 | 
			
		||||
          if [ "${{github.ref_name}}" = "master" ]; then
 | 
			
		||||
            REGISTRY=$(echo ${{github.server_url}} | sed s%http://%% | sed s%https://%%)
 | 
			
		||||
            docker tag "$REGISTRY/${{github.repository}}:${{github.ref_name}}" "$REGISTRY/${{github.repository}}:latest"
 | 
			
		||||
            docker push "$REGISTRY/${{github.repository}}:latest"
 | 
			
		||||
          fi
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										5
									
								
								.gitmodules
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						
									
										5
									
								
								.gitmodules
									
									
									
									
										vendored
									
									
										Normal file
									
								
							@@ -0,0 +1,5 @@
 | 
			
		||||
[submodule "docs"]
 | 
			
		||||
	path = docs
 | 
			
		||||
	url = ../utils.wiki.git
 | 
			
		||||
	branch = master
 | 
			
		||||
	ignore = all
 | 
			
		||||
							
								
								
									
										12
									
								
								.npmignore
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								.npmignore
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,12 @@
 | 
			
		||||
src
 | 
			
		||||
tests
 | 
			
		||||
.editorconfig
 | 
			
		||||
.gitignore
 | 
			
		||||
.gitmodules
 | 
			
		||||
.npmignore
 | 
			
		||||
CODEOWNERS
 | 
			
		||||
Dockerfile
 | 
			
		||||
index.html
 | 
			
		||||
jest.config.js
 | 
			
		||||
tsconfig.json
 | 
			
		||||
vite.config.js
 | 
			
		||||
							
								
								
									
										13
									
								
								Dockerfile
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										13
									
								
								Dockerfile
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,13 @@
 | 
			
		||||
# Build application
 | 
			
		||||
FROM node:alpine as build
 | 
			
		||||
 | 
			
		||||
RUN mkdir /app
 | 
			
		||||
WORKDIR /app
 | 
			
		||||
COPY . .
 | 
			
		||||
RUN if [ ! -d "node_modules" ]; then npm i; fi && \
 | 
			
		||||
    if [ ! -d "dist" ]; then npm run docs; fi
 | 
			
		||||
 | 
			
		||||
# Use Nginx to serve
 | 
			
		||||
FROM nginx:1.23-alpine
 | 
			
		||||
 | 
			
		||||
COPY --from=build /app/docs /usr/share/nginx/html
 | 
			
		||||
							
								
								
									
										91
									
								
								README.md
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										91
									
								
								README.md
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,91 @@
 | 
			
		||||
<!-- Header -->
 | 
			
		||||
<div id="top" align="center">
 | 
			
		||||
  <br />
 | 
			
		||||
 | 
			
		||||
  <!-- Logo -->
 | 
			
		||||
  <img src="https://git.zakscode.com/repo-avatars/77dbab78e5fb3302dc9e751c4d6315a64df8d3a714d5cd5719b0dc39e6619119" alt="Logo" width="200" height="200">
 | 
			
		||||
 | 
			
		||||
  <!-- Title -->
 | 
			
		||||
### @ztimson/utils
 | 
			
		||||
 | 
			
		||||
  <!-- Description -->
 | 
			
		||||
Javascript/Typescript Utilities
 | 
			
		||||
 | 
			
		||||
  <!-- Repo badges -->
 | 
			
		||||
[](https://git.zakscode.com/ztimson/utils/tags)
 | 
			
		||||
[](https://git.zakscode.com/ztimson/utils/pulls)
 | 
			
		||||
[](https://git.zakscode.com/ztimson/utils/issues)
 | 
			
		||||
 | 
			
		||||
  <!-- Links -->
 | 
			
		||||
 | 
			
		||||
  ---
 | 
			
		||||
  <div>
 | 
			
		||||
    <a href="https://utils.docs.zakscode.com" target="_blank">Documentation</a>
 | 
			
		||||
    • <a href="https://git.zakscode.com/ztimson/utils/releases" target="_blank">Release Notes</a>
 | 
			
		||||
    • <a href="https://git.zakscode.com/ztimson/utils/issues/new?template=.github%2fissue_template%2fbug.md" target="_blank">Report a Bug</a>
 | 
			
		||||
    • <a href="https://git.zakscode.com/ztimson/utils/issues/new?template=.github%2fissue_template%2fenhancement.md" target="_blank">Request a Feature</a>
 | 
			
		||||
  </div>
 | 
			
		||||
 | 
			
		||||
  ---
 | 
			
		||||
</div>
 | 
			
		||||
 | 
			
		||||
## Table of Contents
 | 
			
		||||
- [@ztimson/utils](#top)
 | 
			
		||||
	- [About](#about)
 | 
			
		||||
		- [Built With](#built-with)
 | 
			
		||||
	- [Setup](#setup)
 | 
			
		||||
		- [Production](#production)
 | 
			
		||||
		- [Development](#development)
 | 
			
		||||
	- [Documentation](https://utils.docs.zakscode.com/)
 | 
			
		||||
	- [License](#license)
 | 
			
		||||
 | 
			
		||||
## About
 | 
			
		||||
 | 
			
		||||
A collection of utilities to make life a little easier
 | 
			
		||||
 | 
			
		||||
### Built With
 | 
			
		||||
[](https://typescriptlang.org/)
 | 
			
		||||
 | 
			
		||||
## Setup
 | 
			
		||||
 | 
			
		||||
<details>
 | 
			
		||||
<summary>
 | 
			
		||||
  <h3 id="production" style="display: inline">
 | 
			
		||||
    Production
 | 
			
		||||
  </h3>
 | 
			
		||||
</summary>
 | 
			
		||||
 | 
			
		||||
#### Prerequisites
 | 
			
		||||
- [Node.js](https://nodejs.org/en/download)
 | 
			
		||||
 | 
			
		||||
#### Instructions
 | 
			
		||||
1. Install persist: `npm i @ztimosn/utils`
 | 
			
		||||
 | 
			
		||||
</details>
 | 
			
		||||
 | 
			
		||||
<details>
 | 
			
		||||
<summary>
 | 
			
		||||
  <h3 id="development" style="display: inline">
 | 
			
		||||
    Development
 | 
			
		||||
  </h3>
 | 
			
		||||
</summary>
 | 
			
		||||
 | 
			
		||||
#### Prerequisites
 | 
			
		||||
- [Node.js](https://nodejs.org/en/download)
 | 
			
		||||
 | 
			
		||||
#### Instructions
 | 
			
		||||
1. Install the dependencies: `npm i`
 | 
			
		||||
2. Build library: `npm build`
 | 
			
		||||
3. Run unit tests: `npm test`
 | 
			
		||||
 | 
			
		||||
</details>
 | 
			
		||||
 | 
			
		||||
## Documentation
 | 
			
		||||
 | 
			
		||||
[Available Here](https://utils.docs.zakscode.com/)
 | 
			
		||||
 | 
			
		||||
## License
 | 
			
		||||
 | 
			
		||||
Copyright © 2023 Zakary Timson | Available under MIT Licensing
 | 
			
		||||
 | 
			
		||||
See the [license](_media/LICENSE) for more information.
 | 
			
		||||
							
								
								
									
										1
									
								
								docs
									
									
									
									
									
										Submodule
									
								
							
							
								
								
								
								
								
							
						
						
									
										1
									
								
								docs
									
									
									
									
									
										Submodule
									
								
							 Submodule docs added at dbf5d8cd07
									
								
							
							
								
								
									
										102
									
								
								index.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										102
									
								
								index.html
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,102 @@
 | 
			
		||||
<!DOCTYPE html>
 | 
			
		||||
<html>
 | 
			
		||||
	<head>
 | 
			
		||||
		<title>Console Styling Playground</title>
 | 
			
		||||
	</head>
 | 
			
		||||
	<body>
 | 
			
		||||
		<h1>Open Chrome DevTools Console to see magic! (Ctrl+Shift+J or Cmd+Option+J)</h1>
 | 
			
		||||
 | 
			
		||||
		<script>
 | 
			
		||||
			// Console Styling Playground
 | 
			
		||||
			class ConsoleStyler {
 | 
			
		||||
				// Basic badge with customizable colors
 | 
			
		||||
				badge(text, bgColor = '#007bff', textColor = 'white') {
 | 
			
		||||
					console.log(
 | 
			
		||||
						`%c ${text} `,
 | 
			
		||||
						`background-color: ${bgColor};
 | 
			
		||||
                 color: ${textColor};
 | 
			
		||||
                 border-radius: 12px;
 | 
			
		||||
                 padding: 2px 8px;
 | 
			
		||||
                 font-weight: bold;`
 | 
			
		||||
					);
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				// Multi-style log with different sections
 | 
			
		||||
				richLog() {
 | 
			
		||||
					console.log(
 | 
			
		||||
						'%cSystem%c Operation %cDetails',
 | 
			
		||||
						'background-color: #f0f0f0; color: black; padding: 2px 5px; border-radius: 3px;',
 | 
			
		||||
						'color: blue; font-weight: bold;',
 | 
			
		||||
						'color: green;'
 | 
			
		||||
					);
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				// Grouped logs with nested information
 | 
			
		||||
				groupedLog(title, items) {
 | 
			
		||||
					console.group(title);
 | 
			
		||||
					items.forEach(item => {
 | 
			
		||||
						console.log(item);
 | 
			
		||||
					});
 | 
			
		||||
					console.groupEnd();
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				// Table view for structured data
 | 
			
		||||
				tableLog(data) {
 | 
			
		||||
					console.table(data);
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				// Performance tracking
 | 
			
		||||
				timeTrack(label, operation) {
 | 
			
		||||
					console.time(label);
 | 
			
		||||
					operation();
 | 
			
		||||
					console.timeEnd(label);
 | 
			
		||||
				}
 | 
			
		||||
 | 
			
		||||
				// Demonstration method
 | 
			
		||||
				demo() {
 | 
			
		||||
					// Different styled badges
 | 
			
		||||
					this.badge('NEW', '#28a745');  // Green
 | 
			
		||||
					this.badge('WARNING', '#ffc107', 'black');  // Yellow
 | 
			
		||||
					this.badge('ERROR', '#dc3545');  // Red
 | 
			
		||||
					this.badge('CUSTOM', '#6f42c1');  // Purple
 | 
			
		||||
 | 
			
		||||
					// Rich multi-style log
 | 
			
		||||
					this.richLog();
 | 
			
		||||
 | 
			
		||||
					// Grouped logs
 | 
			
		||||
					this.groupedLog('User Details', [
 | 
			
		||||
						{ name: 'John Doe', age: 30, role: 'Admin' },
 | 
			
		||||
						{ name: 'Jane Smith', age: 25, role: 'User' }
 | 
			
		||||
					]);
 | 
			
		||||
 | 
			
		||||
					// Table logging
 | 
			
		||||
					this.tableLog([
 | 
			
		||||
						{ name: 'John', age: 30, active: true },
 | 
			
		||||
						{ name: 'Jane', age: 25, active: false }
 | 
			
		||||
					]);
 | 
			
		||||
 | 
			
		||||
					// Performance tracking
 | 
			
		||||
					this.timeTrack('Complex Operation', () => {
 | 
			
		||||
						let sum = 0;
 | 
			
		||||
						for(let i = 0; i < 1000000; i++) {
 | 
			
		||||
							sum += i;
 | 
			
		||||
						}
 | 
			
		||||
						console.log('Sum:', sum);
 | 
			
		||||
					});
 | 
			
		||||
 | 
			
		||||
					// Advanced: Conditional styling
 | 
			
		||||
					const logLevel = 'warn';
 | 
			
		||||
					console.log(
 | 
			
		||||
						`%c[${logLevel.toUpperCase()}]%c Detailed message`,
 | 
			
		||||
						`color: ${logLevel === 'warn' ? 'orange' : 'red'}; font-weight: bold;`,
 | 
			
		||||
						'color: black;'
 | 
			
		||||
					);
 | 
			
		||||
				}
 | 
			
		||||
			}
 | 
			
		||||
 | 
			
		||||
			// Create instance and run demo
 | 
			
		||||
			const styler = new ConsoleStyler();
 | 
			
		||||
			styler.demo();
 | 
			
		||||
		</script>
 | 
			
		||||
	</body>
 | 
			
		||||
</html>
 | 
			
		||||
							
								
								
									
										5005
									
								
								package-lock.json
									
									
									
										generated
									
									
									
								
							
							
						
						
									
										5005
									
								
								package-lock.json
									
									
									
										generated
									
									
									
								
							
										
											
												File diff suppressed because it is too large
												Load Diff
											
										
									
								
							
							
								
								
									
										14
									
								
								package.json
									
									
									
									
									
								
							
							
						
						
									
										14
									
								
								package.json
									
									
									
									
									
								
							@@ -1,6 +1,6 @@
 | 
			
		||||
{
 | 
			
		||||
	"name": "@ztimson/utils",
 | 
			
		||||
	"version": "0.14.8",
 | 
			
		||||
	"version": "0.27.9",
 | 
			
		||||
	"description": "Utility library",
 | 
			
		||||
	"author": "Zak Timson",
 | 
			
		||||
	"license": "MIT",
 | 
			
		||||
@@ -14,25 +14,31 @@
 | 
			
		||||
	"types": "./dist/index.d.ts",
 | 
			
		||||
	"exports": {
 | 
			
		||||
		".": {
 | 
			
		||||
			"types": "./dist/index.d.ts",
 | 
			
		||||
			"import": "./dist/index.mjs",
 | 
			
		||||
			"require": "./dist/index.cjs",
 | 
			
		||||
			"types": "./dist/index.d.ts"
 | 
			
		||||
			"require": "./dist/index.cjs"
 | 
			
		||||
		}
 | 
			
		||||
	},
 | 
			
		||||
	"scripts": {
 | 
			
		||||
		"build": "npx tsc && npx vite build",
 | 
			
		||||
		"docs": "typedoc --cleanOutputDir false --out ./docs --entryPoints src/**/*.ts --readme none",
 | 
			
		||||
		"test": "npx jest",
 | 
			
		||||
		"test:coverage": "npx jest --coverage",
 | 
			
		||||
		"watch": "npx vite build --watch"
 | 
			
		||||
	},
 | 
			
		||||
	"dependencies": {
 | 
			
		||||
		"var-persist": "^1.0.1"
 | 
			
		||||
	},
 | 
			
		||||
	"devDependencies": {
 | 
			
		||||
		"@types/jest": "^29.5.12",
 | 
			
		||||
		"fake-indexeddb": "^6.0.1",
 | 
			
		||||
		"jest": "^29.7.0",
 | 
			
		||||
		"jest-junit": "^16.0.0",
 | 
			
		||||
		"ts-jest": "^29.1.2",
 | 
			
		||||
		"typedoc": "^0.26.7",
 | 
			
		||||
		"typescript": "^5.3.3",
 | 
			
		||||
		"vite": "^5.0.12",
 | 
			
		||||
		"vite-plugin-dts": "^3.7.2"
 | 
			
		||||
		"vite-plugin-dts": "^4.5.3"
 | 
			
		||||
	},
 | 
			
		||||
	"files": [
 | 
			
		||||
		"dist"
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										142
									
								
								src/arg-parser.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										142
									
								
								src/arg-parser.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,142 @@
 | 
			
		||||
export type Arg<T = any> = {
 | 
			
		||||
	/** Argument/property name */
 | 
			
		||||
	name: string;
 | 
			
		||||
	/** Argument description for help page */
 | 
			
		||||
	desc: string;
 | 
			
		||||
	/** Available shorthands */
 | 
			
		||||
	flags?: string[];
 | 
			
		||||
	/** Argument is not required */
 | 
			
		||||
	optional?: boolean;
 | 
			
		||||
	/** Default value if argument is not used */
 | 
			
		||||
	default?: T;
 | 
			
		||||
	/** Collects any unmatched arguments */
 | 
			
		||||
	extras?: boolean;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export class ArgParser {
 | 
			
		||||
	commands: ArgParser[] = [];
 | 
			
		||||
	args: Arg[] = [];
 | 
			
		||||
	flags: Arg[] = [];
 | 
			
		||||
	defaults!: {[key: string]: any};
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Create a unix-like argument parser to extract flags from the argument list. Can also create help messages.
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param {string} name Script name
 | 
			
		||||
	 * @param {string} desc Help description
 | 
			
		||||
	 * @param {(ArgParser | Arg[]} argList Array of CLI arguments
 | 
			
		||||
	 * @param {string[]} examples Additional examples to display
 | 
			
		||||
	 */
 | 
			
		||||
	constructor(public readonly name: string,
 | 
			
		||||
				public readonly desc: string,
 | 
			
		||||
				public readonly argList: (ArgParser | Arg)[] = [],
 | 
			
		||||
				public readonly examples: string[] = []
 | 
			
		||||
	) {
 | 
			
		||||
		// Arguments
 | 
			
		||||
		this.commands = argList.filter(arg => arg instanceof ArgParser);
 | 
			
		||||
		this.args = <Arg[]>argList.filter(arg => !(arg instanceof ArgParser) && !arg.flags?.length);
 | 
			
		||||
		this.flags = <Arg[]>[...argList.filter(arg => !(arg instanceof ArgParser) && arg.flags && arg.flags.length),
 | 
			
		||||
			{name: 'help', desc: 'Display command\'s help message', flags: ['-h', '--help'], default: false}];
 | 
			
		||||
		this.defaults = argList.reduce((acc, arg: any) => ({...acc, [arg.name]: arg['extras'] ? [] : (arg.default ?? null)}), {});
 | 
			
		||||
 | 
			
		||||
		// Examples
 | 
			
		||||
		this.examples = <string[]>[
 | 
			
		||||
			...examples,
 | 
			
		||||
			`[OPTIONS] ${this.args.map(arg => (arg.optional ? `[${arg.name.toUpperCase()}]` : arg.name.toUpperCase()) + (arg.extras ? '...' : '')).join(' ')}`,
 | 
			
		||||
			this.commands.length ? `[OPTIONS] COMMAND` : null,
 | 
			
		||||
			`--help ${this.commands.length ? '[COMMAND]' : ''}`
 | 
			
		||||
		].filter(e => !!e);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Parse an array into an arguments dictionary using the configuration.
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param {string[]} args Array of arguments to be parsed
 | 
			
		||||
	 * @returns {object} Dictionary of arguments with defaults applied
 | 
			
		||||
	 */
 | 
			
		||||
	parse(args: string[]) {
 | 
			
		||||
		// Parse arguments
 | 
			
		||||
		let extras = [], parsed: any = {...this.defaults, '_error': []}, queue = [...args];
 | 
			
		||||
		while(queue.length) {
 | 
			
		||||
			let arg = queue.splice(0, 1)[0];
 | 
			
		||||
			if(arg[0] == '-') { // Flags
 | 
			
		||||
				// Check for combined shorthand
 | 
			
		||||
				if(arg[1] != '-' && arg.length > 2) {
 | 
			
		||||
					queue = [...arg.substring(2).split('').map(a => `-${a}`), ...queue];
 | 
			
		||||
					arg = `-${arg[1]}`;
 | 
			
		||||
				}
 | 
			
		||||
				// Find & add flag
 | 
			
		||||
				const combined = arg.split('=');
 | 
			
		||||
				const argDef = this.flags.find(flag => flag.flags?.includes(combined[0] || arg));
 | 
			
		||||
				if(argDef == null) { // Not found, add to extras
 | 
			
		||||
					extras.push(arg);
 | 
			
		||||
					continue;
 | 
			
		||||
				}
 | 
			
		||||
				const value = combined[1] != null ? combined [1] :
 | 
			
		||||
					argDef.default === false ? true :
 | 
			
		||||
					argDef.default === true ? false :
 | 
			
		||||
					queue.splice(queue.findIndex(q => q[0] != '-'), 1)[0] ||
 | 
			
		||||
					argDef.default;
 | 
			
		||||
				if(value == null) parsed['_error'].push(`Option missing value: ${argDef.name || combined[0]}`);
 | 
			
		||||
				parsed[argDef.name] = value;
 | 
			
		||||
			} else { // Command
 | 
			
		||||
				const c = this.commands.find(command => command.name == arg);
 | 
			
		||||
				if(!!c) {
 | 
			
		||||
					const parsedCommand = c.parse(queue.splice(0, queue.length));
 | 
			
		||||
					Object.keys(parsedCommand).forEach(key => {
 | 
			
		||||
						if(parsed[key] != parsedCommand[key] && parsedCommand[key] == c.defaults[key])
 | 
			
		||||
							delete parsedCommand[key];
 | 
			
		||||
					});
 | 
			
		||||
					parsed = {
 | 
			
		||||
						...parsed,
 | 
			
		||||
						...parsedCommand,
 | 
			
		||||
						_command: c.name
 | 
			
		||||
					};
 | 
			
		||||
				} else extras.push(arg); // Not found, add to extras
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
		// Arguments
 | 
			
		||||
		this.args.filter(arg => !arg.extras).forEach(arg => {
 | 
			
		||||
			if(!arg.optional && !extras.length) parsed['_error'].push(`Argument missing: ${arg.name.toUpperCase()}`);
 | 
			
		||||
			if(extras.length) parsed[arg.name] = extras.splice(0, 1)[0];
 | 
			
		||||
		});
 | 
			
		||||
		// Extras
 | 
			
		||||
		const extraKey = this.args.find(arg => arg.extras)?.name || '_extra';
 | 
			
		||||
		parsed[extraKey] = extras;
 | 
			
		||||
		return parsed;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Create help message from the provided description & argument list.
 | 
			
		||||
	 *
 | 
			
		||||
	 * @returns {string} Help message
 | 
			
		||||
	 * @param opts Help options: command - display a commands help, message - override help description
 | 
			
		||||
	 */
 | 
			
		||||
	help(opts: {command?: string, message?: string} = {}): string {
 | 
			
		||||
		const spacer = (text: string) => Array(24 - text.length || 1).fill(' ').join('');
 | 
			
		||||
 | 
			
		||||
		// Help with specific command
 | 
			
		||||
		if(opts.command) {
 | 
			
		||||
			const argParser = this.commands.find(parser => parser.name == opts.command);
 | 
			
		||||
			if(!argParser) throw new Error(`${opts.command.toUpperCase()} is not a command`)
 | 
			
		||||
			return argParser.help({...opts, command: undefined});
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		// Description
 | 
			
		||||
		let msg = `\n\n${opts.message || this.desc}`;
 | 
			
		||||
		// Examples
 | 
			
		||||
		msg += '\n\nUsage:\t' + this.examples.map(ex => `${this.name} ${ex}`).join('\n\t');
 | 
			
		||||
		// Arguments
 | 
			
		||||
		if(this.args.length) msg += '\n\n\t' + this.args.map(arg =>
 | 
			
		||||
			`${arg.name.toUpperCase()}${spacer(arg.name)}${arg.desc}`).join('\n\t');
 | 
			
		||||
		// Flags
 | 
			
		||||
		msg += '\n\nOptions:\n\t' + this.flags.map(flag => {
 | 
			
		||||
			const flags = flag.flags?.join(', ') || '';
 | 
			
		||||
			return `${flags}${spacer(flags)}${flag.desc}`;
 | 
			
		||||
		}).join('\n\t');
 | 
			
		||||
		// Commands
 | 
			
		||||
		if(this.commands.length) msg += '\n\nCommands:\n\t' + this.commands.map(command =>
 | 
			
		||||
			`${command.name}${spacer(command.name)}${command.desc}`).join('\n\t');
 | 
			
		||||
		return `${msg}\n\n`;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										61
									
								
								src/array.ts
									
									
									
									
									
								
							
							
						
						
									
										61
									
								
								src/array.ts
									
									
									
									
									
								
							@@ -1,15 +1,35 @@
 | 
			
		||||
import {ASet} from './aset.ts';
 | 
			
		||||
import {dotNotation, isEqual} from './objects';
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Only add element to array if it isn't already included
 | 
			
		||||
 *
 | 
			
		||||
 * @example
 | 
			
		||||
 * ```js
 | 
			
		||||
 * const arr = addUnique([1, 2, 3], 3);
 | 
			
		||||
 * console.log(arr); // Output: [1, 2, 3]
 | 
			
		||||
 * ```
 | 
			
		||||
 *
 | 
			
		||||
 * @param {T[]} array Target array element will be added to
 | 
			
		||||
 * @param {T} el Unique element to add
 | 
			
		||||
 * @return {T[]} Array with element if it was unique
 | 
			
		||||
 * @deprecated Use ASet to create unique arrays
 | 
			
		||||
 */
 | 
			
		||||
export function addUnique<T>(array: T[], el: T): T[] {
 | 
			
		||||
	if(array.indexOf(el) === -1) array.push(el);
 | 
			
		||||
	return array;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Find all unique elements in arrays
 | 
			
		||||
 *
 | 
			
		||||
 * @param {any[]} a First array to compare
 | 
			
		||||
 * @param {any[]} b Second array to compare
 | 
			
		||||
 * @return {any[]} Unique elements
 | 
			
		||||
 * @deprecated Use ASet to perform Set operations on arrays
 | 
			
		||||
 */
 | 
			
		||||
export function arrayDiff(a: any[], b: any[]): any[] {
 | 
			
		||||
	return makeUnique([
 | 
			
		||||
		...a.filter(v1 => !b.includes((v2: any) => isEqual(v1, v2))),
 | 
			
		||||
		...b.filter(v1 => !a.includes((v2: any) => isEqual(v1, v2))),
 | 
			
		||||
	]);
 | 
			
		||||
	return new ASet(a).symmetricDifference(new ASet(b));
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
@@ -33,6 +53,25 @@ export function caseInsensitiveSort(prop: string) {
 | 
			
		||||
	};
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Shorthand to find objects with a property value
 | 
			
		||||
 *
 | 
			
		||||
 * @example
 | 
			
		||||
 * ```js
 | 
			
		||||
 * const found = [
 | 
			
		||||
 *   {name: 'Batman'},
 | 
			
		||||
 *   {name: 'Superman'},
 | 
			
		||||
 * ].filter(findByProp('name', 'Batman'));
 | 
			
		||||
 * ```
 | 
			
		||||
 *
 | 
			
		||||
 * @param {string} prop Property to compare (Dot nation supported)
 | 
			
		||||
 * @param value Value property must have
 | 
			
		||||
 * @return {(v: any) => boolean} Function used by `filter` or `find`
 | 
			
		||||
 */
 | 
			
		||||
export function findByProp(prop: string, value: any) {
 | 
			
		||||
	return (v: any) => isEqual(dotNotation(v, prop), value);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Recursively flatten nested arrays
 | 
			
		||||
 *
 | 
			
		||||
@@ -91,10 +130,13 @@ export function sortByProp(prop: string, reverse = false) {
 | 
			
		||||
	};
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export function findByProp(prop: string, value: any) {
 | 
			
		||||
	return (v: any) => isEqual(v[prop], value);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Make sure every element in array is unique
 | 
			
		||||
 *
 | 
			
		||||
 * @param {any[]} arr Array that will be filtered in place
 | 
			
		||||
 * @return {any[]} Original array
 | 
			
		||||
 * @deprecated Please use ASet to create a guaranteed unique array
 | 
			
		||||
 */
 | 
			
		||||
export function makeUnique(arr: any[]) {
 | 
			
		||||
	for(let i = arr.length - 1; i >= 0; i--) {
 | 
			
		||||
		if(arr.slice(0, i).find(n => isEqual(n, arr[i]))) arr.splice(i, 1);
 | 
			
		||||
@@ -103,7 +145,8 @@ export function makeUnique(arr: any[]) {
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Make sure value is an array, if it isn't wrap it in one.
 | 
			
		||||
 * Make sure value is an array, if it isn't wrap it in one
 | 
			
		||||
 *
 | 
			
		||||
 * @param {T[] | T} value Value that should be an array
 | 
			
		||||
 * @returns {T[]} Value in an array
 | 
			
		||||
 */
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										102
									
								
								src/aset.ts
									
									
									
									
									
								
							
							
						
						
									
										102
									
								
								src/aset.ts
									
									
									
									
									
								
							@@ -1,57 +1,133 @@
 | 
			
		||||
import {isEqual} from './objects.ts';
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * An array which functions as a set. It guarantees unique elements
 | 
			
		||||
 * and provides set functions for comparisons
 | 
			
		||||
 */
 | 
			
		||||
export class ASet<T> extends Array {
 | 
			
		||||
	/** Number of elements in set */
 | 
			
		||||
	get size() {
 | 
			
		||||
		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[] = []) {
 | 
			
		||||
		super();
 | 
			
		||||
		if(!!elements?.['forEach'])
 | 
			
		||||
			elements.forEach(el => this.add(el));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	add(el: T) {
 | 
			
		||||
		if(!this.has(el)) this.push(el);
 | 
			
		||||
	/**
 | 
			
		||||
	 * Add elements to set if unique
 | 
			
		||||
	 * @param items
 | 
			
		||||
	 */
 | 
			
		||||
	add(...items: T[]) {
 | 
			
		||||
		items.filter(el => !this.has(el)).forEach(el => this.push(el));
 | 
			
		||||
		return this;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	delete(el: T) {
 | 
			
		||||
	/**
 | 
			
		||||
	 * Remove all elements
 | 
			
		||||
	 */
 | 
			
		||||
	clear() {
 | 
			
		||||
		this.splice(0, this.length);
 | 
			
		||||
		return this;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Delete elements from set
 | 
			
		||||
	 * @param items Elements that will be deleted
 | 
			
		||||
	 */
 | 
			
		||||
	delete(...items: T[]) {
 | 
			
		||||
		items.forEach(el => {
 | 
			
		||||
			const index = this.indexOf(el);
 | 
			
		||||
		if(index != -1) this.slice(index, 1);
 | 
			
		||||
			if(index != -1) this.splice(index, 1);
 | 
			
		||||
		})
 | 
			
		||||
		return this;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * 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>) {
 | 
			
		||||
		return new ASet<T>(this.reduce((acc, el) => {
 | 
			
		||||
			if(!set.has(el)) acc.push(el);
 | 
			
		||||
			return acc;
 | 
			
		||||
		}, []));
 | 
			
		||||
		return new ASet<T>(this.filter(el => !set.has(el)));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Check if set includes element
 | 
			
		||||
	 * @param {T} el Element to look for
 | 
			
		||||
	 * @return {boolean} True if element was found, false otherwise
 | 
			
		||||
	 */
 | 
			
		||||
	has(el: T) {
 | 
			
		||||
		return this.indexOf(el) != -1;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	intersection(set: ASet<T>) {
 | 
			
		||||
		return new ASet<T>(this.reduce((acc, el) => {
 | 
			
		||||
			if(set.has(el)) acc.push(el);
 | 
			
		||||
			return acc;
 | 
			
		||||
		}, []));
 | 
			
		||||
	/**
 | 
			
		||||
	 * Find index number of element, or -1 if it doesn't exist. Matches by equality not reference
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param {T} search Element to find
 | 
			
		||||
	 * @param {number} fromIndex Starting index position
 | 
			
		||||
	 * @return {number} Element index number or -1 if missing
 | 
			
		||||
	 */
 | 
			
		||||
	indexOf(search: T, fromIndex?: number): number {
 | 
			
		||||
		return super.findIndex((el: T) => isEqual(el, search), fromIndex);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * 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>) {
 | 
			
		||||
		return new ASet<T>(this.filter(el => set.has(el)));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * 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>) {
 | 
			
		||||
		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>) {
 | 
			
		||||
		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>) {
 | 
			
		||||
		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>) {
 | 
			
		||||
		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>) {
 | 
			
		||||
		return new ASet([...this, ...set]);
 | 
			
		||||
	}
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										303
									
								
								src/cache.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										303
									
								
								src/cache.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,303 @@
 | 
			
		||||
import {Database, Table} from './database.ts';
 | 
			
		||||
import {JSONSanitize} from './json.ts';
 | 
			
		||||
import {deepCopy, includes} from './objects.ts';
 | 
			
		||||
 | 
			
		||||
export type CacheOptions = {
 | 
			
		||||
	/** Delete keys automatically after x amount of seconds */
 | 
			
		||||
	ttl?: number;
 | 
			
		||||
	/** Storage to persist cache */
 | 
			
		||||
	persistentStorage?: {storage: Storage | Database, key: string} | string;
 | 
			
		||||
	/** Keep or delete cached items once expired, defaults to delete */
 | 
			
		||||
	expiryPolicy?: 'delete' | 'keep';
 | 
			
		||||
	/** Least Recently Used size limit */
 | 
			
		||||
	sizeLimit?: number;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export type CachedValue<T> = T & {_expired?: boolean};
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Map of data which tracks whether it is a complete collection & offers optional expiry of cached values
 | 
			
		||||
 */
 | 
			
		||||
export class Cache<K extends string | number | symbol, T> {
 | 
			
		||||
	private _loading!: Function;
 | 
			
		||||
	private store: Map<K, T> = new Map();
 | 
			
		||||
	private timers: Map<K, NodeJS.Timeout> = new Map();
 | 
			
		||||
	private lruOrder: K[] = [];
 | 
			
		||||
 | 
			
		||||
	/** Support index lookups */
 | 
			
		||||
	[key: string | number | symbol]: CachedValue<T> | any;
 | 
			
		||||
	/** Whether cache is complete */
 | 
			
		||||
	complete = false;
 | 
			
		||||
	/** Await initial loading */
 | 
			
		||||
	loading = new Promise<void>(r => this._loading = r);
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Create new cache
 | 
			
		||||
	 * @param {keyof T} key Default property to use as primary key
 | 
			
		||||
	 * @param options
 | 
			
		||||
	 */
 | 
			
		||||
	constructor(public readonly key?: keyof T, public readonly options: CacheOptions = {}) {
 | 
			
		||||
		// Persistent storage
 | 
			
		||||
		if(this.options.persistentStorage != null) {
 | 
			
		||||
			if(typeof this.options.persistentStorage == 'string')
 | 
			
		||||
				this.options.persistentStorage = {storage: localStorage, key: this.options.persistentStorage};
 | 
			
		||||
 | 
			
		||||
			if(this.options.persistentStorage?.storage?.database != undefined) {
 | 
			
		||||
				(async () => {
 | 
			
		||||
					const persists: any = this.options.persistentStorage;
 | 
			
		||||
					const table: Table<any, any> = await persists.storage.createTable({name: persists.key, key: this.key});
 | 
			
		||||
					const rows = await table.getAll();
 | 
			
		||||
					for(const row of rows) this.store.set(this.getKey(row), row);
 | 
			
		||||
					this._loading();
 | 
			
		||||
				})();
 | 
			
		||||
			} else if((<any>this.options.persistentStorage?.storage)?.getItem != undefined) {
 | 
			
		||||
				const {storage, key} = <{storage: Storage, key: string}>this.options.persistentStorage;
 | 
			
		||||
				const stored = storage.getItem(key);
 | 
			
		||||
				if(stored != null) {
 | 
			
		||||
					try {
 | 
			
		||||
						const obj = JSON.parse(stored);
 | 
			
		||||
						for(const k of Object.keys(obj)) this.store.set(<any>k, obj[k]);
 | 
			
		||||
					} catch { /* ignore */ }
 | 
			
		||||
				}
 | 
			
		||||
				this._loading();
 | 
			
		||||
			}
 | 
			
		||||
		} else {
 | 
			
		||||
			this._loading();
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		// Handle index lookups
 | 
			
		||||
		return new Proxy(this, {
 | 
			
		||||
			get: (target: this, prop: string | symbol) => {
 | 
			
		||||
				if(prop in target) return (target as any)[prop];
 | 
			
		||||
				return this.get(prop as K, true);
 | 
			
		||||
			},
 | 
			
		||||
			set: (target: this, prop: string | symbol, value: any) => {
 | 
			
		||||
				if(prop in target) (target as any)[prop] = value;
 | 
			
		||||
				else this.set(prop as K, value);
 | 
			
		||||
				return true;
 | 
			
		||||
			}
 | 
			
		||||
		});
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	private getKey(value: T): K {
 | 
			
		||||
		if(!this.key) throw new Error('No key defined');
 | 
			
		||||
		if((value as any)[this.key] === undefined) throw new Error(`${this.key.toString()} Doesn't exist on ${JSON.stringify(value, null, 2)}`);
 | 
			
		||||
		return <K>(value as any)[this.key];
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	private save(key?: K) {
 | 
			
		||||
		const persists: {storage: any, key: string} = <any>this.options.persistentStorage;
 | 
			
		||||
		if(!!persists?.storage) {
 | 
			
		||||
			if(persists.storage?.database != undefined) {
 | 
			
		||||
				(<Database>persists.storage).createTable({name: persists.key, key: <string>this.key}).then(table => {
 | 
			
		||||
					if(key !== undefined) {
 | 
			
		||||
						const value = this.get(key, true);
 | 
			
		||||
						if(value != null) table.set(value, key);
 | 
			
		||||
						else table.delete(key);
 | 
			
		||||
					} else {
 | 
			
		||||
						table.clear();
 | 
			
		||||
						this.all(true).forEach(row => table.add(row));
 | 
			
		||||
					}
 | 
			
		||||
				});
 | 
			
		||||
			} else if(persists.storage?.setItem != undefined) {
 | 
			
		||||
				const obj: Record<any, any> = {};
 | 
			
		||||
				for(const [k, v] of this.store.entries()) obj[k as any] = v;
 | 
			
		||||
				persists.storage.setItem(persists.key, JSONSanitize(obj));
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	private clearTimer(key: K) {
 | 
			
		||||
		const t = this.timers.get(key);
 | 
			
		||||
		if(t) { clearTimeout(t); this.timers.delete(key); }
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	private touchLRU(key: K) {
 | 
			
		||||
		if(!this.options.sizeLimit || this.options.sizeLimit <= 0) return;
 | 
			
		||||
		const idx = this.lruOrder.indexOf(key);
 | 
			
		||||
		if(idx >= 0) this.lruOrder.splice(idx, 1);
 | 
			
		||||
		this.lruOrder.push(key);
 | 
			
		||||
		while(this.lruOrder.length > (this.options.sizeLimit || 0)) {
 | 
			
		||||
			const lru = this.lruOrder.shift();
 | 
			
		||||
			if(lru !== undefined) this.delete(lru);
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Get all cached items
 | 
			
		||||
	 * @return {T[]} Array of items
 | 
			
		||||
	 */
 | 
			
		||||
	all(expired?: boolean): CachedValue<T>[] {
 | 
			
		||||
		const out: CachedValue<T>[] = [];
 | 
			
		||||
		for(const v of this.store.values()) {
 | 
			
		||||
			const val: any = v;
 | 
			
		||||
			if(expired || !val?._expired) out.push(deepCopy<any>(val));
 | 
			
		||||
		}
 | 
			
		||||
		return out;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Add a new item to the cache. Like set, but finds key automatically
 | 
			
		||||
	 * @param {T} value Item to add to cache
 | 
			
		||||
	 * @param {number | undefined} ttl Override default expiry
 | 
			
		||||
	 * @return {this}
 | 
			
		||||
	 */
 | 
			
		||||
	add(value: T, ttl = this.ttl): this {
 | 
			
		||||
		const key = this.getKey(value);
 | 
			
		||||
		this.set(key, value, ttl);
 | 
			
		||||
		return this;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Add several rows to the cache
 | 
			
		||||
	 * @param {T[]} rows Several items that will be cached using the default key
 | 
			
		||||
	 * @param complete Mark cache as complete & reliable, defaults to true
 | 
			
		||||
	 * @return {this}
 | 
			
		||||
	 */
 | 
			
		||||
	addAll(rows: T[], complete = true): this {
 | 
			
		||||
		this.clear();
 | 
			
		||||
		rows.forEach(r => this.add(r));
 | 
			
		||||
		this.complete = complete;
 | 
			
		||||
		return this;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Remove all keys from cache
 | 
			
		||||
	 */
 | 
			
		||||
	clear(): this {
 | 
			
		||||
		this.complete = false;
 | 
			
		||||
		for (const [k, t] of this.timers) clearTimeout(t);
 | 
			
		||||
		this.timers.clear();
 | 
			
		||||
		this.lruOrder = [];
 | 
			
		||||
		this.store.clear();
 | 
			
		||||
		this.save();
 | 
			
		||||
		return this;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Delete an item from the cache
 | 
			
		||||
	 * @param {K} key Item's primary key
 | 
			
		||||
	 */
 | 
			
		||||
	delete(key: K): this {
 | 
			
		||||
		this.clearTimer(key);
 | 
			
		||||
		const idx = this.lruOrder.indexOf(key);
 | 
			
		||||
		if(idx >= 0) this.lruOrder.splice(idx, 1);
 | 
			
		||||
		this.store.delete(key);
 | 
			
		||||
		this.save(key);
 | 
			
		||||
		return this;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Return cache as an array of key-value pairs
 | 
			
		||||
	 * @return {[K, T][]} Key-value pairs array
 | 
			
		||||
	 */
 | 
			
		||||
	entries(expired?: boolean): [K, CachedValue<T>][] {
 | 
			
		||||
		const out: [K, CachedValue<T>][] = [];
 | 
			
		||||
		for(const [k, v] of this.store.entries()) {
 | 
			
		||||
			const val: any = v;
 | 
			
		||||
			if(expired || !val?._expired) out.push([k, deepCopy<any>(val)]);
 | 
			
		||||
		}
 | 
			
		||||
		return out;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Manually expire a cached item
 | 
			
		||||
	 * @param {K} key Key to expire
 | 
			
		||||
	 */
 | 
			
		||||
	expire(key: K): this {
 | 
			
		||||
		this.complete = false;
 | 
			
		||||
		if(this.options.expiryPolicy == 'keep') {
 | 
			
		||||
			const v: any = this.store.get(key);
 | 
			
		||||
			if(v) {
 | 
			
		||||
				v._expired = true;
 | 
			
		||||
				this.store.set(key, v);
 | 
			
		||||
				this.save(key);
 | 
			
		||||
			}
 | 
			
		||||
		} else this.delete(key);
 | 
			
		||||
		return this;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Find the first cached item to match a filter
 | 
			
		||||
	 * @param {Partial<T>} filter Partial item to match
 | 
			
		||||
	 * @param {Boolean} expired Include expired items, defaults to false
 | 
			
		||||
	 * @returns {T | undefined} Cached item or undefined if nothing matched
 | 
			
		||||
	 */
 | 
			
		||||
	find(filter: Partial<T>, expired?: boolean): T | undefined {
 | 
			
		||||
		for(const v of this.store.values()) {
 | 
			
		||||
			const row: any = v;
 | 
			
		||||
			if((expired || !row._expired) && includes(row, filter)) return deepCopy<any>(row);
 | 
			
		||||
		}
 | 
			
		||||
		return undefined;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Get item from the cache
 | 
			
		||||
	 * @param {K} key Key to lookup
 | 
			
		||||
	 * @param expired Include expired items
 | 
			
		||||
	 * @return {T} Cached item
 | 
			
		||||
	 */
 | 
			
		||||
	get(key: K, expired?: boolean): CachedValue<T> | null {
 | 
			
		||||
		const raw = this.store.get(key);
 | 
			
		||||
		if(raw == null) return null;
 | 
			
		||||
		const cached: any = deepCopy<any>(raw);
 | 
			
		||||
		this.touchLRU(key);
 | 
			
		||||
		if(expired || !cached?._expired) return cached;
 | 
			
		||||
		return null;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Get a list of cached keys
 | 
			
		||||
	 * @return {K[]} Array of keys
 | 
			
		||||
	 */
 | 
			
		||||
	keys(expired?: boolean): K[] {
 | 
			
		||||
		const out: K[] = [];
 | 
			
		||||
		for(const [k, v] of this.store.entries()) {
 | 
			
		||||
			const val: any = v;
 | 
			
		||||
			if(expired || !val?._expired) out.push(k);
 | 
			
		||||
		}
 | 
			
		||||
		return out;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Get map of cached items
 | 
			
		||||
	 * @return {Record<K, T>}
 | 
			
		||||
	 */
 | 
			
		||||
	map(expired?: boolean): Record<K, CachedValue<T>> {
 | 
			
		||||
		const copy: any = {};
 | 
			
		||||
		for(const [k, v] of this.store.entries()) {
 | 
			
		||||
			const val: any = v;
 | 
			
		||||
			if(expired || !val?._expired) copy[k as any] = deepCopy<any>(val);
 | 
			
		||||
		}
 | 
			
		||||
		return copy;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Add an item to the cache manually specifying the key
 | 
			
		||||
	 * @param {K} key Key item will be cached under
 | 
			
		||||
	 * @param {T} value Item to cache
 | 
			
		||||
	 * @param {number | undefined} ttl Override default expiry in seconds
 | 
			
		||||
	 * @return {this}
 | 
			
		||||
	 */
 | 
			
		||||
	set(key: K, value: T, ttl = this.options.ttl): this {
 | 
			
		||||
		if(this.options.expiryPolicy == 'keep') delete (<any>value)._expired;
 | 
			
		||||
		this.clearTimer(key);
 | 
			
		||||
		this.store.set(key, value);
 | 
			
		||||
		this.touchLRU(key);
 | 
			
		||||
		this.save(key);
 | 
			
		||||
		if(ttl) {
 | 
			
		||||
			const t = setTimeout(() => {
 | 
			
		||||
				this.expire(key);
 | 
			
		||||
				this.save(key);
 | 
			
		||||
			}, (ttl || 0) * 1000);
 | 
			
		||||
			this.timers.set(key, t);
 | 
			
		||||
		}
 | 
			
		||||
		return this;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Get all cached items
 | 
			
		||||
	 * @return {T[]} Array of items
 | 
			
		||||
	 */
 | 
			
		||||
	values = this.all
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										12
									
								
								src/color.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										12
									
								
								src/color.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,12 @@
 | 
			
		||||
/**
 | 
			
		||||
 * Determine if either black or white provides more contrast to the provided color
 | 
			
		||||
 * @param {string} background Color to compare against
 | 
			
		||||
 * @return {"white" | "black"} Color with the most contrast
 | 
			
		||||
 */
 | 
			
		||||
export function contrast(background: string): 'white' | 'black' {
 | 
			
		||||
	const exploded = background?.match(background.length >= 6 ? /[0-9a-fA-F]{2}/g : /[0-9a-fA-F]/g);
 | 
			
		||||
	if(!exploded || exploded?.length < 3) return 'black';
 | 
			
		||||
	const [r, g, b] = exploded.map(hex => parseInt(hex.length == 1 ? `${hex}${hex}` : hex, 16));
 | 
			
		||||
	const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
 | 
			
		||||
	return luminance > 0.5 ? 'black' : 'white';
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										89
									
								
								src/csv.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										89
									
								
								src/csv.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,89 @@
 | 
			
		||||
import {makeArray} from './array.ts';
 | 
			
		||||
import {ASet} from './aset.ts';
 | 
			
		||||
import {JSONSanitize} from './json.ts';
 | 
			
		||||
import {dotNotation, flattenObj} from './objects.ts';
 | 
			
		||||
import {LETTER_LIST} from './string.ts';
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Parse a CSV string into an array of objects
 | 
			
		||||
 *
 | 
			
		||||
 * @param csv String with CSV
 | 
			
		||||
 * @param hasHeaders First line of CSV contains headers
 | 
			
		||||
 * @return {T[]} Array of parsed objects
 | 
			
		||||
 */
 | 
			
		||||
export function fromCsv<T = any>(csv: string, hasHeaders = true): T[] {
 | 
			
		||||
	function parseLine(line: string): (string | null)[] {
 | 
			
		||||
		const columns: string[] = [];
 | 
			
		||||
		let current = '', inQuotes = false;
 | 
			
		||||
		for (let i = 0; i < line.length; i++) {
 | 
			
		||||
			const char = line[i];
 | 
			
		||||
			const nextChar = line[i + 1];
 | 
			
		||||
			if (char === '"') {
 | 
			
		||||
				if (inQuotes && nextChar === '"') {
 | 
			
		||||
					current += '"'; // Handle escaped quotes
 | 
			
		||||
					i++;
 | 
			
		||||
				} else inQuotes = !inQuotes;
 | 
			
		||||
			} else if (char === ',' && !inQuotes) {
 | 
			
		||||
				columns.push(current.trim()); // Trim column values
 | 
			
		||||
				current = '';
 | 
			
		||||
			} else current += char;
 | 
			
		||||
		}
 | 
			
		||||
		columns.push(current.trim()); // Trim last column value
 | 
			
		||||
		return columns.map(col => col.replace(/^"|"$/g, '').replace(/""/g, '"'));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	// Normalize line endings and split rows
 | 
			
		||||
	const rows = [];
 | 
			
		||||
	let currentRow = '', inQuotes = false;
 | 
			
		||||
	for (const char of csv.replace(/\r\n/g, '\n')) { // Normalize \r\n to \n
 | 
			
		||||
		if (char === '"') inQuotes = !inQuotes;
 | 
			
		||||
		if (char === '\n' && !inQuotes) {
 | 
			
		||||
			rows.push(currentRow.trim()); // Trim row
 | 
			
		||||
			currentRow = '';
 | 
			
		||||
		} else currentRow += char;
 | 
			
		||||
	}
 | 
			
		||||
	if (currentRow) rows.push(currentRow.trim()); // Trim last row
 | 
			
		||||
 | 
			
		||||
	// Extract headers
 | 
			
		||||
	let headers: any = hasHeaders ? rows.splice(0, 1)[0] : null;
 | 
			
		||||
	if (headers) headers = headers.match(/(?:[^,"']+|"(?:[^"]|"")*"|'(?:[^']|'')*')+/g)?.map((h: any) => h.trim());
 | 
			
		||||
 | 
			
		||||
	// Parse rows
 | 
			
		||||
	return <T[]>rows.map(r => {
 | 
			
		||||
		const props = parseLine(r);
 | 
			
		||||
		const h = headers || (Array(props.length).fill(null).map((_, i) => {
 | 
			
		||||
			let letter = '';
 | 
			
		||||
			const first = i / 26;
 | 
			
		||||
			if (first > 1) letter += LETTER_LIST[Math.floor(first - 1)];
 | 
			
		||||
			letter += LETTER_LIST[i % 26];
 | 
			
		||||
			return letter;
 | 
			
		||||
		}));
 | 
			
		||||
		return h.reduce((acc: any, h: any, i: number) => {
 | 
			
		||||
			dotNotation(acc, h, props[i]);
 | 
			
		||||
			return acc;
 | 
			
		||||
		}, {});
 | 
			
		||||
	});
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Convert an array of objects to a CSV string
 | 
			
		||||
 *
 | 
			
		||||
 * @param {any[]} target Array of objects to create CSV from
 | 
			
		||||
 * @param {boolean} flatten Should nested object be flattened or treated as values
 | 
			
		||||
 * @return {string} CSV string
 | 
			
		||||
 */
 | 
			
		||||
export function toCsv(target: any, flatten=true) {
 | 
			
		||||
	const t = makeArray(target);
 | 
			
		||||
	const headers = new ASet(t.reduce((acc, row) => [...acc, ...Object.keys(flatten ? flattenObj(row) : row)], []));
 | 
			
		||||
	return [
 | 
			
		||||
		headers.join(','),
 | 
			
		||||
		...t.map(row => headers.map((h: string) => {
 | 
			
		||||
			const value = dotNotation<any>(row, h);
 | 
			
		||||
			if(value == null) return '';
 | 
			
		||||
			if(typeof value == 'object') return `"${JSONSanitize(value).replaceAll('"', '""')}"`;
 | 
			
		||||
			if(typeof value == 'string' &&  /[\n",]/g.test(value)) return `"${value.replaceAll('"', '""')}"`;
 | 
			
		||||
			return value;
 | 
			
		||||
		}).join(','))
 | 
			
		||||
	].join('\n');
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										204
									
								
								src/database.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										204
									
								
								src/database.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,204 @@
 | 
			
		||||
import {findByProp} from './array.ts';
 | 
			
		||||
import {ASet} from './aset.ts';
 | 
			
		||||
import {sleepWhile} from './time.ts';
 | 
			
		||||
 | 
			
		||||
export type TableOptions = {
 | 
			
		||||
	name: string;
 | 
			
		||||
	key?: string;
 | 
			
		||||
	autoIncrement?: boolean;
 | 
			
		||||
};
 | 
			
		||||
 | 
			
		||||
class AsyncLock {
 | 
			
		||||
	private p = Promise.resolve();
 | 
			
		||||
	run<T>(fn: () => Promise<T>): Promise<T> {
 | 
			
		||||
		const res = this.p.then(fn, fn);
 | 
			
		||||
		this.p = res.then(() => {}, () => {});
 | 
			
		||||
		return res;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export class Database {
 | 
			
		||||
	private schemaLock = new AsyncLock();
 | 
			
		||||
	private upgrading = false;
 | 
			
		||||
 | 
			
		||||
	connection!: Promise<IDBDatabase>;
 | 
			
		||||
	tables!: TableOptions[];
 | 
			
		||||
 | 
			
		||||
	get ready() { return !this.upgrading; }
 | 
			
		||||
 | 
			
		||||
	constructor(public readonly database: string, tables?: (string | TableOptions)[], public version?: number) {
 | 
			
		||||
		this.connection = new Promise((resolve, reject) => {
 | 
			
		||||
			let req: IDBOpenDBRequest;
 | 
			
		||||
			try { req = indexedDB.open(this.database, this.version); }
 | 
			
		||||
			catch (err) { return reject(err); }
 | 
			
		||||
 | 
			
		||||
			this.tables = !tables ? [] : tables.map(t => {
 | 
			
		||||
				t = typeof t == 'object' ? t : {name: t};
 | 
			
		||||
				return {...t, name: t.name.toString()};
 | 
			
		||||
			});
 | 
			
		||||
 | 
			
		||||
			req.onerror = () => reject(req.error);
 | 
			
		||||
 | 
			
		||||
			req.onsuccess = () => {
 | 
			
		||||
				let db: IDBDatabase;
 | 
			
		||||
				try { db = req.result; }
 | 
			
		||||
				catch (err) { return reject(err); }
 | 
			
		||||
 | 
			
		||||
				const existing = Array.from(db.objectStoreNames);
 | 
			
		||||
				if(!tables) {
 | 
			
		||||
					this.tables = existing.map(t => {
 | 
			
		||||
						try {
 | 
			
		||||
							const tx = db.transaction(t, 'readonly');
 | 
			
		||||
							const store = tx.objectStore(t);
 | 
			
		||||
							return {name: t, key: <string>store.keyPath};
 | 
			
		||||
						} catch {
 | 
			
		||||
							return {name: t}; // 🛡️ fallback
 | 
			
		||||
						}
 | 
			
		||||
					});
 | 
			
		||||
				}
 | 
			
		||||
				const desired = new ASet((tables || []).map(t => typeof t == 'string' ? t : t.name));
 | 
			
		||||
				if(tables && desired.symmetricDifference(new ASet(existing)).length) {
 | 
			
		||||
					db.close();
 | 
			
		||||
					Object.assign(this, new Database(this.database, this.tables, db.version + 1));
 | 
			
		||||
					this.connection.then(resolve);
 | 
			
		||||
				} else {
 | 
			
		||||
					this.version = db.version;
 | 
			
		||||
					resolve(db);
 | 
			
		||||
				}
 | 
			
		||||
				this.upgrading = false;
 | 
			
		||||
			};
 | 
			
		||||
 | 
			
		||||
			req.onupgradeneeded = () => {
 | 
			
		||||
				this.upgrading = true;
 | 
			
		||||
				let db: IDBDatabase;
 | 
			
		||||
				try { db = req.result; }
 | 
			
		||||
				catch { return; }
 | 
			
		||||
				try {
 | 
			
		||||
					const existingTables = new ASet(Array.from(db.objectStoreNames));
 | 
			
		||||
					if(tables) {
 | 
			
		||||
						const desired = new ASet((tables || []).map(t => typeof t == 'string' ? t : t.name));
 | 
			
		||||
						existingTables.difference(desired).forEach(name => db.deleteObjectStore(name));
 | 
			
		||||
						desired.difference(existingTables).forEach(name => {
 | 
			
		||||
							const t = this.tables.find(findByProp('name', name));
 | 
			
		||||
							db.createObjectStore(name, {
 | 
			
		||||
								keyPath: t?.key,
 | 
			
		||||
								autoIncrement: t?.autoIncrement || !t?.key,
 | 
			
		||||
							});
 | 
			
		||||
						});
 | 
			
		||||
					}
 | 
			
		||||
				} catch { }
 | 
			
		||||
			};
 | 
			
		||||
		});
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	waitForUpgrade = () => sleepWhile(() => this.upgrading);
 | 
			
		||||
 | 
			
		||||
	async createTable<K extends IDBValidKey = any, T = any>(table: string | TableOptions): Promise<Table<K, T>> {
 | 
			
		||||
		return this.schemaLock.run(async () => {
 | 
			
		||||
			if(typeof table == 'string') table = { name: table };
 | 
			
		||||
			const conn = await this.connection;
 | 
			
		||||
			if(!this.includes(table.name)) {
 | 
			
		||||
				const newDb = new Database(this.database, [...this.tables, table], (this.version ?? 0) + 1);
 | 
			
		||||
				conn.close();
 | 
			
		||||
				this.connection = newDb.connection;
 | 
			
		||||
				await this.connection;
 | 
			
		||||
				Object.assign(this, newDb);
 | 
			
		||||
			}
 | 
			
		||||
			return this.table<K, T>(table.name);
 | 
			
		||||
		});
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	async deleteTable(table: string | TableOptions): Promise<void> {
 | 
			
		||||
		return this.schemaLock.run(async () => {
 | 
			
		||||
			if(typeof table == 'string') table = { name: table };
 | 
			
		||||
			if(!this.includes(table.name)) return;
 | 
			
		||||
			const conn = await this.connection;
 | 
			
		||||
			const newDb = new Database(this.database, this.tables.filter(t => t.name != (<TableOptions>table).name), (this.version ?? 0) + 1);
 | 
			
		||||
			conn.close();
 | 
			
		||||
			this.connection = newDb.connection;
 | 
			
		||||
			await this.connection;
 | 
			
		||||
			Object.assign(this, newDb);
 | 
			
		||||
		});
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	includes(name: any): boolean {
 | 
			
		||||
		return !!this.tables.find(t => t.name == (typeof name == 'object' ? name.name : name.toString()));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	table<K extends IDBValidKey = any, T = any>(name: any): Table<K, T> {
 | 
			
		||||
		return new Table<K, T>(this, name.toString());
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export class Table<K extends IDBValidKey = any, T = any> {
 | 
			
		||||
	constructor(private readonly database: Database, public readonly name: string, public readonly key: keyof T | string = 'id') {
 | 
			
		||||
		this.database.connection.then(() => {
 | 
			
		||||
			const exists = !!this.database.tables.find(findByProp('name', this.name));
 | 
			
		||||
			if(!exists) this.database.createTable(this.name);
 | 
			
		||||
		});
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	async tx<R>(table: string, fn: (store: IDBObjectStore) => IDBRequest, readonly = false): Promise<R> {
 | 
			
		||||
		await this.database.waitForUpgrade();
 | 
			
		||||
		const db = await this.database.connection;
 | 
			
		||||
		const tx = db.transaction(table, readonly ? 'readonly' : 'readwrite');
 | 
			
		||||
		return new Promise<R>((resolve, reject) => {
 | 
			
		||||
			const request = fn(tx.objectStore(table));
 | 
			
		||||
			request.onsuccess = () => resolve(request.result as R);
 | 
			
		||||
			request.onerror = () => reject(request.error);
 | 
			
		||||
		});
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	add(value: T, key?: K): Promise<void> {
 | 
			
		||||
		return this.tx(this.name, store => store.add(value, key));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	all = this.getAll;
 | 
			
		||||
 | 
			
		||||
	clear(): Promise<void> {
 | 
			
		||||
		return this.tx(this.name, store => store.clear());
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	count(): Promise<number> {
 | 
			
		||||
		return this.tx(this.name, store => store.count(), true);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	create = this.add;
 | 
			
		||||
 | 
			
		||||
	delete(key: K): Promise<void> {
 | 
			
		||||
		return this.tx(this.name, store => store.delete(key));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	get(key: K): Promise<T> {
 | 
			
		||||
		return this.tx(this.name, store => store.get(key), true);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	getAll(): Promise<T[]> {
 | 
			
		||||
		return this.tx(this.name, store => store.getAll(), true);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	getAllKeys(): Promise<K[]> {
 | 
			
		||||
		return this.tx(this.name, store => store.getAllKeys(), true);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	put(value: T, key?: string): Promise<void> {
 | 
			
		||||
		return this.tx(this.name, store => {
 | 
			
		||||
			if(store.keyPath) return store.put(value);
 | 
			
		||||
			return store.put(value, key);
 | 
			
		||||
		});
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	read(): Promise<T[]>;
 | 
			
		||||
	read(key: K): Promise<T>;
 | 
			
		||||
	read(key?: K): Promise<T | T[]> {
 | 
			
		||||
		return key ? this.get(key) : this.getAll();
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	set(value: T, key?: K): Promise<void> {
 | 
			
		||||
		if(key) (<any>value)[this.key] = key;
 | 
			
		||||
		if(!(<any>value)[this.key]) return this.add(value);
 | 
			
		||||
		return this.put(value);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	update = this.set;
 | 
			
		||||
}
 | 
			
		||||
@@ -1,29 +1,33 @@
 | 
			
		||||
export type Listener = (...args: any[]) => any;
 | 
			
		||||
export type TypedEvents = {[k in string | symbol]: Listener} & {'*': (event: string, ...args: any[]) => any};
 | 
			
		||||
export type TypedListener = (...args: any[]) => any;
 | 
			
		||||
export type TypedEvents = {[k in string | symbol]: TypedListener} & {'*': (event: string, ...args: any[]) => any};
 | 
			
		||||
 | 
			
		||||
export type NamespaceEvents<Namespace extends string, Events extends TypedEvents> = {
 | 
			
		||||
	[K in keyof Events as `${Namespace}:${Extract<K, string>}`]: Events[K];
 | 
			
		||||
};
 | 
			
		||||
 | 
			
		||||
export class TypedEmitter<T extends TypedEvents = TypedEvents> {
 | 
			
		||||
	private static listeners: {[key: string]: Listener[]} = {};
 | 
			
		||||
	private static listeners: {[key: string]: TypedListener[]} = {};
 | 
			
		||||
 | 
			
		||||
	private listeners: { [key in keyof T]?: Listener[] } = {};
 | 
			
		||||
	private listeners: { [key in keyof T]?: TypedListener[] } = {};
 | 
			
		||||
 | 
			
		||||
	static emit(event: any, ...args: any[]) {
 | 
			
		||||
		(this.listeners['*'] || []).forEach(l => l(event, ...args));
 | 
			
		||||
		(this.listeners[event.toString()] || []).forEach(l => l(...args));
 | 
			
		||||
	};
 | 
			
		||||
 | 
			
		||||
	static off(event: any, listener: Listener) {
 | 
			
		||||
	static off(event: any, listener: TypedListener) {
 | 
			
		||||
		const e = event.toString();
 | 
			
		||||
		this.listeners[e] = (this.listeners[e] || []).filter(l => l === listener);
 | 
			
		||||
		this.listeners[e] = (this.listeners[e] || []).filter(l => l != listener);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static on(event: any, listener: Listener) {
 | 
			
		||||
	static on(event: any, listener: TypedListener) {
 | 
			
		||||
		const e = event.toString();
 | 
			
		||||
		if(!this.listeners[e]) this.listeners[e] = [];
 | 
			
		||||
		this.listeners[e]?.push(listener);
 | 
			
		||||
		return () => this.off(event, listener);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	static once(event: any, listener?: Listener): Promise<any> {
 | 
			
		||||
	static once(event: any, listener?: TypedListener): Promise<any> {
 | 
			
		||||
		return new Promise(res => {
 | 
			
		||||
			const unsubscribe = this.on(event, <any>((...args: any) => {
 | 
			
		||||
				res(args.length == 1 ? args[0] : args);
 | 
			
		||||
@@ -39,7 +43,7 @@ export class TypedEmitter<T extends TypedEvents = TypedEvents> {
 | 
			
		||||
	};
 | 
			
		||||
 | 
			
		||||
	off<K extends keyof T = string>(event: K, listener: T[K]) {
 | 
			
		||||
		this.listeners[event] = (this.listeners[event] || []).filter(l => l === listener);
 | 
			
		||||
		this.listeners[event] = (this.listeners[event] || []).filter(l => l != listener);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	on<K extends keyof T = string>(event: K, listener: T[K]) {
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										121
									
								
								src/errors.ts
									
									
									
									
									
								
							
							
						
						
									
										121
									
								
								src/errors.ts
									
									
									
									
									
								
							@@ -53,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 {
 | 
			
		||||
	static code = 403;
 | 
			
		||||
 | 
			
		||||
@@ -77,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 {
 | 
			
		||||
	static code = 500;
 | 
			
		||||
 | 
			
		||||
@@ -88,3 +124,88 @@ export class InternalServerError extends CustomError {
 | 
			
		||||
		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) {
 | 
			
		||||
	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);
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										79
									
								
								src/files.ts
									
									
									
									
									
								
							
							
						
						
									
										79
									
								
								src/files.ts
									
									
									
									
									
								
							@@ -1,20 +1,42 @@
 | 
			
		||||
import {makeArray} from './array.ts';
 | 
			
		||||
import {JSONAttemptParse} from './json.ts';
 | 
			
		||||
import {PromiseProgress} from './promise-progress';
 | 
			
		||||
import {formatDate} from './time.ts';
 | 
			
		||||
 | 
			
		||||
export function download(href: any, name: string) {
 | 
			
		||||
/**
 | 
			
		||||
 * Download blob as a file
 | 
			
		||||
 *
 | 
			
		||||
 * @param {Blob} blob File as a blob
 | 
			
		||||
 * @param {string} name Name blob will be downloaded as
 | 
			
		||||
 */
 | 
			
		||||
export function downloadFile(blob: Blob | string | string[], name: string) {
 | 
			
		||||
	if(!(blob instanceof Blob)) blob = new Blob(makeArray(blob));
 | 
			
		||||
	const url = URL.createObjectURL(blob);
 | 
			
		||||
	downloadUrl(url, name);
 | 
			
		||||
	URL.revokeObjectURL(url);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Download a file from a URL
 | 
			
		||||
 *
 | 
			
		||||
 * @param href URL that will be downloaded
 | 
			
		||||
 * @param {string} name Override download name
 | 
			
		||||
 */
 | 
			
		||||
export function downloadUrl(href: any, name?: string) {
 | 
			
		||||
	const a = document.createElement('a');
 | 
			
		||||
	a.href = href;
 | 
			
		||||
	a.download = name;
 | 
			
		||||
	a.download = name || href.split('/').pop();
 | 
			
		||||
	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);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Open filebrowser & return selected file
 | 
			
		||||
 *
 | 
			
		||||
 * @param {{accept?: string, multiple?: boolean}} options accept - selectable mimetypes, multiple - Allow selecting more than 1 file
 | 
			
		||||
 * @return {Promise<File[]>} Array of selected files
 | 
			
		||||
 */
 | 
			
		||||
export function fileBrowser(options: {accept?: string, multiple?: boolean} = {}): Promise<File[]> {
 | 
			
		||||
	return new Promise(res => {
 | 
			
		||||
		const input = document.createElement('input');
 | 
			
		||||
@@ -31,6 +53,40 @@ export function fileBrowser(options: {accept?: string, multiple?: boolean} = {})
 | 
			
		||||
	});
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Extract text from a file
 | 
			
		||||
 *
 | 
			
		||||
 * @param file File to extract text from
 | 
			
		||||
 * @return {Promise<string | null>} File contents
 | 
			
		||||
 */
 | 
			
		||||
export function fileText(file: any): Promise<string | null> {
 | 
			
		||||
	return new Promise((resolve, reject) => {
 | 
			
		||||
		const reader = new FileReader();
 | 
			
		||||
		reader.onload = () => resolve(<string>reader.result);
 | 
			
		||||
		reader.onerror = () => reject(reader.error);
 | 
			
		||||
		reader.readAsText(file);
 | 
			
		||||
	});
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Create timestamp intended for filenames from a date
 | 
			
		||||
 *
 | 
			
		||||
 * @param {string} name Name of file, `{{TIMESTAMP}}` will be replaced
 | 
			
		||||
 * @param {Date | number | string} date Date to use for timestamp
 | 
			
		||||
 * @return {string} Interpolated filename, or the raw timestamp if name was omitted
 | 
			
		||||
 */
 | 
			
		||||
export function timestampFilename(name?: string, date: Date | number | string = new Date()) {
 | 
			
		||||
	if(typeof date == 'number' || typeof date == 'string') date = new Date(date);
 | 
			
		||||
	const timestamp = formatDate('YYYY-MM-DD_HH-mm', date);
 | 
			
		||||
	return name ? name.replace('{{TIMESTAMP}}', timestamp) : timestamp;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Upload file to URL with progress callback using PromiseProgress
 | 
			
		||||
 *
 | 
			
		||||
 * @param {{url: string, files: File[], headers?: {[p: string]: string}, withCredentials?: boolean}} options
 | 
			
		||||
 * @return {PromiseProgress<T>} Promise of request with `onProgress` callback
 | 
			
		||||
 */
 | 
			
		||||
export function uploadWithProgress<T>(options: {
 | 
			
		||||
	url: string;
 | 
			
		||||
	files: File[];
 | 
			
		||||
@@ -42,10 +98,11 @@ export function uploadWithProgress<T>(options: {
 | 
			
		||||
		const formData = new FormData();
 | 
			
		||||
		options.files.forEach(f => formData.append('file', 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('load', (resp) => res(<any>resp));
 | 
			
		||||
		xhr.upload.addEventListener('error', (err) => rej(err));
 | 
			
		||||
		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));
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										51
									
								
								src/http.ts
									
									
									
									
									
								
							
							
						
						
									
										51
									
								
								src/http.ts
									
									
									
									
									
								
							@@ -10,7 +10,7 @@ export type HttpRequestOptions = {
 | 
			
		||||
	decode?: boolean;
 | 
			
		||||
	fragment?: string;
 | 
			
		||||
	headers?: {[key: string | symbol]: string | null | undefined};
 | 
			
		||||
	method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
 | 
			
		||||
	method?: 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';
 | 
			
		||||
	query?: {key: string, value: string}[] | {[key: string]: string};
 | 
			
		||||
	url?: string;
 | 
			
		||||
	[key: string]: any;
 | 
			
		||||
@@ -22,6 +22,28 @@ export type HttpDefaults = {
 | 
			
		||||
	url?: string;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
class HttpResponse<T = any> extends Response {
 | 
			
		||||
	data?: T
 | 
			
		||||
	ok!: boolean;
 | 
			
		||||
	redirected!: boolean;
 | 
			
		||||
	type!: ResponseType;
 | 
			
		||||
	url!: string;
 | 
			
		||||
 | 
			
		||||
	constructor(resp: Response, stream: ReadableStream) {
 | 
			
		||||
		const body = [204, 205, 304].includes(resp.status) ? null : stream;
 | 
			
		||||
		super(body, {
 | 
			
		||||
			headers: resp.headers,
 | 
			
		||||
			status: resp.status,
 | 
			
		||||
			statusText: resp.statusText,
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		this.ok = resp.ok;
 | 
			
		||||
		this.redirected = resp.redirected;
 | 
			
		||||
		this.type = resp.type;
 | 
			
		||||
		this.url = resp.url;
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export class Http {
 | 
			
		||||
	private static interceptors: {[key: string]: HttpInterceptor} = {};
 | 
			
		||||
 | 
			
		||||
@@ -54,8 +76,9 @@ export class Http {
 | 
			
		||||
 | 
			
		||||
	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;
 | 
			
		||||
		let url = opts.url?.startsWith('http') ? opts.url : (this.url || '') + (opts.url || '');
 | 
			
		||||
		url = url.replaceAll(/([^:]\/)\/+/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]}))
 | 
			
		||||
@@ -75,6 +98,7 @@ export class Http {
 | 
			
		||||
 | 
			
		||||
		// Send request
 | 
			
		||||
		return new PromiseProgress((res, rej, prog) => {
 | 
			
		||||
			try {
 | 
			
		||||
				fetch(url, {
 | 
			
		||||
					headers,
 | 
			
		||||
					method: opts.method || (opts.body ? 'POST' : 'GET'),
 | 
			
		||||
@@ -104,24 +128,21 @@ export class Http {
 | 
			
		||||
						}
 | 
			
		||||
					});
 | 
			
		||||
 | 
			
		||||
				const data = new Response(stream);
 | 
			
		||||
				resp.body = data.body;
 | 
			
		||||
				resp.blob = data.blob;
 | 
			
		||||
				resp.formData = data.formData;
 | 
			
		||||
				resp.json = data.json;
 | 
			
		||||
				resp.text = data.text;
 | 
			
		||||
 | 
			
		||||
					resp = new HttpResponse<T>(resp, stream);
 | 
			
		||||
					if(opts.decode !== false) {
 | 
			
		||||
						const content = resp.headers.get('Content-Type')?.toLowerCase();
 | 
			
		||||
					if(content?.includes('application')) resp.data = <T>await data.blob();
 | 
			
		||||
					else if(content?.includes('form')) resp.data = <T>await data.formData();
 | 
			
		||||
					else if(content?.includes('json')) resp.data = <T>await data.json();
 | 
			
		||||
					else if(content?.includes('text')) resp.data = <T>await data.text();
 | 
			
		||||
						if(content?.includes('form')) resp.data = <T>await resp.formData();
 | 
			
		||||
						else if(content?.includes('json')) resp.data = <T>await resp.json();
 | 
			
		||||
						else if(content?.includes('text')) resp.data = <T>await resp.text();
 | 
			
		||||
						else if(content?.includes('application')) resp.data = <T>await resp.blob();
 | 
			
		||||
					}
 | 
			
		||||
 | 
			
		||||
					if(resp.ok) res(resp);
 | 
			
		||||
					else rej(resp);
 | 
			
		||||
			})
 | 
			
		||||
				}).catch(err => rej(err));
 | 
			
		||||
			} catch(err) {
 | 
			
		||||
				rej(err);
 | 
			
		||||
			}
 | 
			
		||||
		});
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										11
									
								
								src/index.ts
									
									
									
									
									
								
							
							
						
						
									
										11
									
								
								src/index.ts
									
									
									
									
									
								
							@@ -1,13 +1,24 @@
 | 
			
		||||
export * from './arg-parser';
 | 
			
		||||
export * from './array';
 | 
			
		||||
export * from './aset';
 | 
			
		||||
export * from './cache';
 | 
			
		||||
export * from './color';
 | 
			
		||||
export * from './csv';
 | 
			
		||||
export * from './database';
 | 
			
		||||
export * from './files';
 | 
			
		||||
export * from './emitter';
 | 
			
		||||
export * from './errors';
 | 
			
		||||
export * from './http';
 | 
			
		||||
export * from './json';
 | 
			
		||||
export * from './jwt';
 | 
			
		||||
export * from './logger';
 | 
			
		||||
export * from './math';
 | 
			
		||||
export * from './misc';
 | 
			
		||||
export * from './objects';
 | 
			
		||||
export * from './path-events';
 | 
			
		||||
export * from './promise-progress';
 | 
			
		||||
export * from './search';
 | 
			
		||||
export * from './string';
 | 
			
		||||
export * from './time';
 | 
			
		||||
export * from './types';
 | 
			
		||||
export * from 'var-persist';
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										40
									
								
								src/json.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										40
									
								
								src/json.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,40 @@
 | 
			
		||||
/**
 | 
			
		||||
 * Parse JSON but return the original string if it fails
 | 
			
		||||
 *
 | 
			
		||||
 * @param {any} json JSON string to parse
 | 
			
		||||
 * @param fallback Fallback value if unable to parse, defaults to original string
 | 
			
		||||
 * @return {string | T} Object if successful, original string otherwise
 | 
			
		||||
 */
 | 
			
		||||
export function JSONAttemptParse<T1, T2>(json: T2, fallback?: T1): T1 | T2 {
 | 
			
		||||
	try { return JSON.parse(<any>json); }
 | 
			
		||||
	catch { return fallback ?? json; }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Stringifies objects & skips primitives
 | 
			
		||||
 *
 | 
			
		||||
 * @param {any} obj Object to convert to serializable value
 | 
			
		||||
 * @return {string | T} Serialized value
 | 
			
		||||
 */
 | 
			
		||||
export function JSONSerialize<T1>(obj: T1): T1 | string {
 | 
			
		||||
	if(typeof obj == 'object' && obj != null) return JSONSanitize(obj);
 | 
			
		||||
	return obj;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Convert an object to a JSON string avoiding any circular references.
 | 
			
		||||
 *
 | 
			
		||||
 * @param obj Object to convert to JSON
 | 
			
		||||
 * @param {number} space Format the JSON with spaces
 | 
			
		||||
 * @return {string} JSON string
 | 
			
		||||
 */
 | 
			
		||||
export function JSONSanitize(obj: any, space?: number): string {
 | 
			
		||||
	const cache: any[] = [];
 | 
			
		||||
	return JSON.stringify(obj, (key, value) => {
 | 
			
		||||
		if(typeof value === 'object' && value !== null) {
 | 
			
		||||
			if(cache.includes(value)) return '[Circular]';
 | 
			
		||||
			cache.push(value);
 | 
			
		||||
		}
 | 
			
		||||
		return value;
 | 
			
		||||
	}, space);
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										31
									
								
								src/jwt.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										31
									
								
								src/jwt.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,31 @@
 | 
			
		||||
import {JSONAttemptParse} from './json.ts';
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Creates a JSON Web Token (JWT) using the provided payload.
 | 
			
		||||
 *
 | 
			
		||||
 * @param {object} payload The payload to include in the JWT.
 | 
			
		||||
 * @param signature Add a JWT signature
 | 
			
		||||
 * @return {string} The generated JWT string.
 | 
			
		||||
 */
 | 
			
		||||
export function createJwt(payload: object, signature = 'unsigned'): string {
 | 
			
		||||
	const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" }))
 | 
			
		||||
		.toString('base64url');
 | 
			
		||||
	const body = Buffer.from(JSON.stringify(payload))
 | 
			
		||||
		.toString('base64url');
 | 
			
		||||
	// Signature is irrelevant for decodeJwt
 | 
			
		||||
	return `${header}.${body}.${signature}`;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Decode a JSON Web Token (JWT) payload, this will not check for tampering so be careful
 | 
			
		||||
 *
 | 
			
		||||
 * @param {string} token JWT to decode
 | 
			
		||||
 * @return {unknown} JWT payload
 | 
			
		||||
 */
 | 
			
		||||
export function decodeJwt<T>(token: string): T {
 | 
			
		||||
	const base64 = token.split('.')[1]
 | 
			
		||||
		.replace(/-/g, '+').replace(/_/g, '/');
 | 
			
		||||
	return <T>JSONAttemptParse(decodeURIComponent(atob(base64).split('').map(function(c) {
 | 
			
		||||
		return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
 | 
			
		||||
	}).join('')));
 | 
			
		||||
}
 | 
			
		||||
@@ -1,4 +1,5 @@
 | 
			
		||||
import {TypedEmitter, TypedEvents} from './emitter';
 | 
			
		||||
import {JSONSanitize} from './json.ts';
 | 
			
		||||
 | 
			
		||||
export const CliEffects = {
 | 
			
		||||
	CLEAR: "\x1b[0m",
 | 
			
		||||
@@ -41,6 +42,8 @@ export const CliBackground = {
 | 
			
		||||
	GREY: "\x1b[100m",
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export type LogLevels = 'debug' | 'log' | 'info' | 'warn' | 'error';
 | 
			
		||||
 | 
			
		||||
export enum LOG_LEVEL {
 | 
			
		||||
	ERROR = 0,
 | 
			
		||||
	WARN = 1,
 | 
			
		||||
@@ -64,49 +67,41 @@ export class Logger extends TypedEmitter<LoggerEvents> {
 | 
			
		||||
		super();
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	private pad(text: any, length: number, char: string, end = false) {
 | 
			
		||||
		const t = text.toString();
 | 
			
		||||
		const l = length - t.length;
 | 
			
		||||
		if(l <= 0) return t;
 | 
			
		||||
		const padding = Array(~~(l / char.length)).fill(char).join('');
 | 
			
		||||
		return !end ? padding + t : t + padding;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	private format(...text: string[]): string {
 | 
			
		||||
	protected format(...text: any[]): string {
 | 
			
		||||
		const now = new Date();
 | 
			
		||||
		const timestamp = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} ${this.pad(now.getHours().toString(), 2, '0')}:${this.pad(now.getMinutes().toString(), 2, '0')}:${this.pad(now.getSeconds().toString(), 2, '0')}.${this.pad(now.getMilliseconds().toString(), 3, '0', true)}`;
 | 
			
		||||
		return `${timestamp}${this.namespace ? ` [${this.namespace}]` : ''} ${text.join(' ')}`;
 | 
			
		||||
		const timestamp = `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()} ${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}.${now.getMilliseconds().toString().padEnd(3, '0')}`;
 | 
			
		||||
		return `${timestamp}${this.namespace ? ` [${this.namespace}]` : ''} ${text.map(t => typeof t == 'string' ? t : JSONSanitize(t, 2)).join(' ')}`;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	debug(...args: string[]) {
 | 
			
		||||
	debug(...args: any[]) {
 | 
			
		||||
		if(Logger.LOG_LEVEL < LOG_LEVEL.DEBUG) return;
 | 
			
		||||
		const str = this.format(...args);
 | 
			
		||||
		Logger.emit(LOG_LEVEL.DEBUG, str);
 | 
			
		||||
		console.debug(CliForeground.LIGHT_GREY + str + CliEffects.CLEAR);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	log(...args: string[]) {
 | 
			
		||||
	log(...args: any[]) {
 | 
			
		||||
		if(Logger.LOG_LEVEL < LOG_LEVEL.LOG) return;
 | 
			
		||||
		const str = this.format(...args);
 | 
			
		||||
		Logger.emit(LOG_LEVEL.LOG, str);
 | 
			
		||||
		console.log(CliEffects.CLEAR + str);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	info(...args: string[]) {
 | 
			
		||||
	info(...args: any[]) {
 | 
			
		||||
		if(Logger.LOG_LEVEL < LOG_LEVEL.INFO) return;
 | 
			
		||||
		const str = this.format(...args);
 | 
			
		||||
		Logger.emit(LOG_LEVEL.INFO, str);
 | 
			
		||||
		console.info(CliForeground.BLUE + str + CliEffects.CLEAR);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	warn(...args: string[]) {
 | 
			
		||||
	warn(...args: any[]) {
 | 
			
		||||
		if(Logger.LOG_LEVEL < LOG_LEVEL.WARN) return;
 | 
			
		||||
		const str = this.format(...args);
 | 
			
		||||
		Logger.emit(LOG_LEVEL.WARN, str);
 | 
			
		||||
		console.warn(CliForeground.YELLOW + str + CliEffects.CLEAR);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	error(...args: string[]) {
 | 
			
		||||
	error(...args: any[]) {
 | 
			
		||||
		if(Logger.LOG_LEVEL < LOG_LEVEL.ERROR) return;
 | 
			
		||||
		const str = this.format(...args);
 | 
			
		||||
		Logger.emit(LOG_LEVEL.ERROR, str);
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										49
									
								
								src/math.ts
									
									
									
									
									
								
							
							
						
						
									
										49
									
								
								src/math.ts
									
									
									
									
									
								
							@@ -7,25 +7,30 @@
 | 
			
		||||
 * ```
 | 
			
		||||
 *
 | 
			
		||||
 * @param {number} num Number to convert
 | 
			
		||||
 * @param maxDen
 | 
			
		||||
 * @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)}`;
 | 
			
		||||
export function dec2Frac(num: number, maxDen=1000): string {
 | 
			
		||||
	let sign = Math.sign(num);
 | 
			
		||||
	num = Math.abs(num);
 | 
			
		||||
	if (Number.isInteger(num)) return (sign * num) + "";
 | 
			
		||||
	let closest = { n: 0, d: 1, diff: Math.abs(num) };
 | 
			
		||||
	for (let d = 1; d <= maxDen; d++) {
 | 
			
		||||
		let n = Math.round(num * d);
 | 
			
		||||
		let diff = Math.abs(num - n / d);
 | 
			
		||||
		if (diff < closest.diff) {
 | 
			
		||||
			closest = { n, d, diff };
 | 
			
		||||
			if (diff < 1e-8) break; // Close enough
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	let integer = Math.floor(closest.n / closest.d);
 | 
			
		||||
	let numerator = closest.n - integer * closest.d;
 | 
			
		||||
	return (sign < 0 ? '-' : '') +
 | 
			
		||||
		(integer ? integer + ' ' : '') +
 | 
			
		||||
		(numerator ? numerator + '/' + closest.d : '');
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Convert fraction to decimal number
 | 
			
		||||
 *
 | 
			
		||||
@@ -43,3 +48,17 @@ export function fracToDec(frac: string) {
 | 
			
		||||
	split = (<string>split.pop()).split('/');
 | 
			
		||||
	return whole + (Number(split[0]) / Number(split[1]));
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Add a suffix to a number:
 | 
			
		||||
 * 1 = 1st
 | 
			
		||||
 * 2 = 2nd
 | 
			
		||||
 * 3 = 3rd
 | 
			
		||||
 * N = Nth
 | 
			
		||||
 * @param {number} n
 | 
			
		||||
 * @returns {string}
 | 
			
		||||
 */
 | 
			
		||||
export function numSuffix(n: number): string {
 | 
			
		||||
	const s = ['th', 'st', 'nd', 'rd'], v = n % 100;
 | 
			
		||||
	return `${n}${s[(v - 20) % 10] || s[v] || s[0]}`;
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										130
									
								
								src/misc.ts
									
									
									
									
									
								
							
							
						
						
									
										130
									
								
								src/misc.ts
									
									
									
									
									
								
							@@ -1,15 +1,67 @@
 | 
			
		||||
import {LogLevels} from './logger.ts';
 | 
			
		||||
import {PathEvent} from './path-events.ts';
 | 
			
		||||
import {md5} from './string';
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Convert data into a form encoded format.
 | 
			
		||||
 *
 | 
			
		||||
 * @param {any} data - data to convert
 | 
			
		||||
 * @returns {string} - Ecodeded form data
 | 
			
		||||
 * Compare version numbers
 | 
			
		||||
 * @param {string} target
 | 
			
		||||
 * @param {string} vs
 | 
			
		||||
 * @return {number} -1 = target is lower, 0 = equal, 1 = higher
 | 
			
		||||
 */
 | 
			
		||||
export function formEncode(data: any): string {
 | 
			
		||||
	return Object.entries(data).map(([key, value]) =>
 | 
			
		||||
		encodeURIComponent(key) + '=' + encodeURIComponent(<any>value)
 | 
			
		||||
	).join('&');
 | 
			
		||||
export function compareVersions(target: string, vs: string): -1 | 0 | 1 {
 | 
			
		||||
	const [tMajor, tMinor, tPatch] = target.split('.').map(v => +v.replace(/[^0-9]/g, ''));
 | 
			
		||||
	const [vMajor, vMinor, vPatch] = vs.split('.').map(v => +v.replace(/[^0-9]/g, ''));
 | 
			
		||||
	return (tMajor > vMajor || tMinor > vMinor || tPatch > vPatch) ? 1 :
 | 
			
		||||
		(tMajor < vMajor || tMinor < vMinor || tPatch < vPatch) ? -1 : 0;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Create a console object to intercept logs with optional passthrough
 | 
			
		||||
 * @param {null | {debug: Function, log: Function, info: Function, warn: Function, error: Function}} out Passthrough logs, null to silence
 | 
			
		||||
 * @param {{[K in LogLevels]?: LogLevels | "none"}} map Map log levels: {log: 'debug', warn: 'error'} = Suppress debug logs, elevate warnings
 | 
			
		||||
 * @returns {{debug: Function, log: Function, info: Function, warn: Function, error: Function, stderr: string[], stdout: string[]}}
 | 
			
		||||
 */
 | 
			
		||||
export function consoleInterceptor(
 | 
			
		||||
	out: null | {debug: Function, log: Function, info: Function, warn: Function, error: Function} = console,
 | 
			
		||||
	map?: {[K in LogLevels]?: LogLevels | 'none'}
 | 
			
		||||
): {debug: Function, log: Function, info: Function, warn: Function, error: Function, output: {debug: any[], log: any[], info: any[], warn: any[], error: any[], stderr: any[], stdout: any[]}} {
 | 
			
		||||
	const logs: any = {debug: [], log: [], info: [], warn: [], error: [], stderr: [], stdout: [],}
 | 
			
		||||
	const cWrapper = (type: 'debug' | 'log' | 'info' | 'warn' | 'error') => ((...args: any[]) => {
 | 
			
		||||
		if(out) out[type](...args);
 | 
			
		||||
		logs[type].push(...args);
 | 
			
		||||
		if(type == 'error') logs.stderr.push(...args);
 | 
			
		||||
		else logs.stdout.push(...args);
 | 
			
		||||
	});
 | 
			
		||||
	return {
 | 
			
		||||
		debug: map?.debug != 'none' ? cWrapper(map?.debug || 'debug') : () => {},
 | 
			
		||||
		log: map?.log != 'none' ? cWrapper(map?.log || 'log') : () => {},
 | 
			
		||||
		info: map?.info != 'none' ? cWrapper(map?.info || 'info') : () => {},
 | 
			
		||||
		warn: map?.warn != 'none' ? cWrapper(map?.warn || 'warn') : () => {},
 | 
			
		||||
		error: map?.error != 'none' ? cWrapper(map?.error || 'error') : () => {},
 | 
			
		||||
		output: logs
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Escape any regex special characters to avoid misinterpretation during search
 | 
			
		||||
 * @param {string} value String which should be escaped
 | 
			
		||||
 * @return {string} New escaped sequence
 | 
			
		||||
 */
 | 
			
		||||
export function escapeRegex(value: string) {
 | 
			
		||||
	return value.replace(/[.*+?^${}()|\[\]\\]/g, '\\$&');
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Run a stringified function with arguments asynchronously
 | 
			
		||||
 * @param {object} args Map of key/value arguments
 | 
			
		||||
 * @param {string} fn Function as string
 | 
			
		||||
 * @param {boolean} async Run with async (returns a promise)
 | 
			
		||||
 * @return {T | Promise<T>} Function return result
 | 
			
		||||
 */
 | 
			
		||||
export function fn<T>(args: object, fn: string, async: boolean = false): T {
 | 
			
		||||
	const keys = Object.keys(args);
 | 
			
		||||
	return new Function(...keys, `return (${async ? 'async ' : ''}(${keys.join(',')}) => { ${fn} })(${keys.join(',')})`)(...keys.map(k => (<any>args)[k]));
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
@@ -24,41 +76,37 @@ export function gravatar(email: string, def='mp') {
 | 
			
		||||
	return `https://www.gravatar.com/avatar/${md5(email)}?d=${def}`;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/** Parts of a URL */
 | 
			
		||||
export type ParsedUrl = {
 | 
			
		||||
	protocol?: string,
 | 
			
		||||
	subdomain?: string,
 | 
			
		||||
	domain: string,
 | 
			
		||||
	host: string,
 | 
			
		||||
	port?: number,
 | 
			
		||||
	path?: string,
 | 
			
		||||
	query?: {[name: string]: string}
 | 
			
		||||
	fragment?: string
 | 
			
		||||
/**
 | 
			
		||||
 * Convert IPv6 to v4 because who uses that, NAT4Life
 | 
			
		||||
 * @param {string} ip IPv6 address, e.g. 2001:0db8:85a3:0000:0000:8a2e:0370:7334
 | 
			
		||||
 * @returns {string | null} IPv4 address, e.g. 172.16.58.3
 | 
			
		||||
 */
 | 
			
		||||
export function ipV6ToV4(ip: string) {
 | 
			
		||||
	if(!ip) return null;
 | 
			
		||||
	const ipv4 = ip.split(':').splice(-1)[0];
 | 
			
		||||
	if(ipv4 == '1') return '127.0.0.1';
 | 
			
		||||
	return ipv4;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 *
 | 
			
		||||
 * @param {string} url
 | 
			
		||||
 * @returns {RegExpExecArray}
 | 
			
		||||
 * Check if IP is reserved, e.g. localhost, private IPs, etc.
 | 
			
		||||
 * @param {string} ip
 | 
			
		||||
 * @returns {boolean}
 | 
			
		||||
 */
 | 
			
		||||
export function urlParser(url: string): ParsedUrl {
 | 
			
		||||
	const processed = new RegExp(
 | 
			
		||||
		'(?:(?<protocol>[\\w\\d]+)\\:\\/\\/)?(?:(?<user>.+)\\@)?(?<host>(?<domain>[^:\\/\\?#@\\n]+)(?:\\:(?<port>\\d*))?)(?<path>\\/.*?)?(?:\\?(?<query>.*?))?(?:#(?<fragment>.*?))?$',
 | 
			
		||||
		'gm').exec(url);
 | 
			
		||||
	const groups: ParsedUrl = <any>processed?.groups ?? {};
 | 
			
		||||
	const domains = groups.domain.split('.');
 | 
			
		||||
	if(groups['port'] != null) groups.port = Number(groups.port);
 | 
			
		||||
	if(domains.length > 2) {
 | 
			
		||||
		groups.domain = domains.splice(-2, 2).join('.');
 | 
			
		||||
		groups.subdomain = domains.join('.');
 | 
			
		||||
	}
 | 
			
		||||
	if(groups.query) {
 | 
			
		||||
		const split = (<any>groups.query).split('&'), query: any = {};
 | 
			
		||||
		split.forEach((q: any) => {
 | 
			
		||||
			const [key, val] = q.split('=');
 | 
			
		||||
			query[key] = val;
 | 
			
		||||
		});
 | 
			
		||||
		groups.query = query;
 | 
			
		||||
	}
 | 
			
		||||
	return groups;
 | 
			
		||||
export function reservedIp(ip: string): boolean {
 | 
			
		||||
	if(ip == 'localhost' || ip == '127.0.0.1') return true;
 | 
			
		||||
	return /\b(10\.(?:[0-9]{1,3}\.){2}[0-9]{1,3})\b|\b(172\.(?:1[6-9]|2[0-9]|3[0-1])\.(?:[0-9]{1,3}\.)[0-9]{1,3})\b|\b(192\.168\.(?:[0-9]{1,3}\.)[0-9]{1,3})\b/.test(ip);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Represents a function that listens for events and handles them accordingly.
 | 
			
		||||
 *
 | 
			
		||||
 * @param {PathEvent} event - The event object containing data related to the triggered event.
 | 
			
		||||
 * @param {...any} args - Additional arguments that may be passed to the listener.
 | 
			
		||||
 * @returns {any} The return value of the listener, which can vary based on implementation.
 | 
			
		||||
 */
 | 
			
		||||
export type Listener = (event: PathEvent, ...args: any[]) => any;
 | 
			
		||||
 | 
			
		||||
/** Represents a function that can be called to unsubscribe from an event, stream, or observer */
 | 
			
		||||
export type Unsubscribe = () => void;
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										165
									
								
								src/objects.ts
									
									
									
									
									
								
							
							
						
						
									
										165
									
								
								src/objects.ts
									
									
									
									
									
								
							@@ -1,3 +1,54 @@
 | 
			
		||||
import {JSONSanitize} from './json.ts';
 | 
			
		||||
 | 
			
		||||
export type Delta = { [key: string]: any | Delta | null };
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Applies deltas to `target`.
 | 
			
		||||
 * @param base starting point
 | 
			
		||||
 * @param deltas List of deltas to apply
 | 
			
		||||
 * @returns Mutated target
 | 
			
		||||
 */
 | 
			
		||||
export function applyDeltas(base: any, ...deltas: any[]): any {
 | 
			
		||||
	function applyDelta(base: any, delta: any): any {
 | 
			
		||||
		if(delta === null) return null;
 | 
			
		||||
		if(typeof base !== 'object' || base === null) return delta === undefined ? base : delta;
 | 
			
		||||
		const result = Array.isArray(base) ? [...base] : { ...base };
 | 
			
		||||
		for(const key in delta) {
 | 
			
		||||
			const val = delta[key];
 | 
			
		||||
			if(val === undefined) delete result[key];
 | 
			
		||||
			else if(typeof val === 'object' && val !== null && !Array.isArray(val)) result[key] = applyDelta(result[key], val);
 | 
			
		||||
			else result[key] = val;
 | 
			
		||||
		}
 | 
			
		||||
		return result;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	for(const d of deltas.flat()) base = applyDelta(base, d?.delta ?? d);
 | 
			
		||||
	return base;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Creates a nested delta that reverts `target` back to `old`.
 | 
			
		||||
 * @param old - Original object
 | 
			
		||||
 * @param updated - Modified object
 | 
			
		||||
 * @returns New changes
 | 
			
		||||
 */
 | 
			
		||||
export function calcDelta(old: any, updated: any): any {
 | 
			
		||||
	if(updated == null) return null; // full delete
 | 
			
		||||
	const delta: any = {};
 | 
			
		||||
	const isObj = (v: any) => v && typeof v === 'object' && !Array.isArray(v);
 | 
			
		||||
	for (const key of new Set([...(old ? Object.keys(old) : []), ...(updated ? Object.keys(updated) : [])])) {
 | 
			
		||||
		const oldVal = old?.[key];
 | 
			
		||||
		const newVal = updated?.[key];
 | 
			
		||||
		if(isObj(oldVal) && isObj(newVal)) {
 | 
			
		||||
			const nested = calcDelta(oldVal, newVal);
 | 
			
		||||
			if(nested !== null && Object.keys(nested).length > 0) delta[key] = nested;
 | 
			
		||||
		} else if(JSON.stringify(oldVal) !== JSON.stringify(newVal)) {
 | 
			
		||||
			delta[key] = newVal;
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	return Object.keys(delta).length === 0 ? {} : delta;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Removes any null values from an object in-place
 | 
			
		||||
 *
 | 
			
		||||
@@ -14,7 +65,7 @@
 | 
			
		||||
export function clean<T>(obj: T, undefinedOnly = false): Partial<T> {
 | 
			
		||||
	if(obj == null) throw new Error("Cannot clean a NULL value");
 | 
			
		||||
	if(Array.isArray(obj)) {
 | 
			
		||||
		obj = <any>obj.filter(o => o != null);
 | 
			
		||||
		obj = <any>obj.filter(o => undefinedOnly ? o !== undefined : o != null);
 | 
			
		||||
	} else {
 | 
			
		||||
		Object.entries(obj).forEach(([key, value]) => {
 | 
			
		||||
			if((undefinedOnly && value === undefined) || (!undefinedOnly && value == null)) delete (<any>obj)[key];
 | 
			
		||||
@@ -27,12 +78,12 @@ export function clean<T>(obj: T, undefinedOnly = false): Partial<T> {
 | 
			
		||||
 * Create a deep copy of an object (vs. a shallow copy of references)
 | 
			
		||||
 *
 | 
			
		||||
 * Should be replaced by `structuredClone` once released.
 | 
			
		||||
 *
 | 
			
		||||
 * @param {T} value Object to copy
 | 
			
		||||
 * @returns {T} Type
 | 
			
		||||
 */
 | 
			
		||||
export function deepCopy<T>(value: T): T {
 | 
			
		||||
	return JSON.parse(JSON.stringify(value));
 | 
			
		||||
	try {return structuredClone(value); }
 | 
			
		||||
	catch { return JSON.parse(JSONSanitize(value)); }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
@@ -92,7 +143,25 @@ export function dotNotation<T>(obj: any, prop: string, set?: T): T | undefined {
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Recursively flatten a nested object, while maintaining key structure.
 | 
			
		||||
 * Convert object into URL encoded query string
 | 
			
		||||
 *
 | 
			
		||||
 * @example
 | 
			
		||||
 * ```js
 | 
			
		||||
 * const query = encodeQuery({page: 1, size: 20});
 | 
			
		||||
 * console.log(query); // Output: "page=1&size=20"
 | 
			
		||||
 * ```
 | 
			
		||||
 *
 | 
			
		||||
 * @param {any} data - data to convert
 | 
			
		||||
 * @returns {string} - Encoded form data
 | 
			
		||||
 */
 | 
			
		||||
export function encodeQuery(data: any): string {
 | 
			
		||||
	return Object.entries(data).map(([key, value]) =>
 | 
			
		||||
		encodeURIComponent(key) + '=' + encodeURIComponent(<any>value)
 | 
			
		||||
	).join('&');
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Recursively flatten a nested object, while maintaining key structure
 | 
			
		||||
 *
 | 
			
		||||
 * @example
 | 
			
		||||
 * ```ts
 | 
			
		||||
@@ -108,8 +177,8 @@ export function dotNotation<T>(obj: any, prop: string, set?: T): T | undefined {
 | 
			
		||||
export function flattenObj(obj: any, parent?: any, result: any = {}) {
 | 
			
		||||
	if(typeof obj === "object" && !Array.isArray(obj)) {
 | 
			
		||||
		for(const key of Object.keys(obj)) {
 | 
			
		||||
			const propName = parent ? parent + '.' + key : key;
 | 
			
		||||
			if(typeof obj[key] === 'object') {
 | 
			
		||||
			const propName = parent ? `${parent}.${key}` : key;
 | 
			
		||||
			if(typeof obj[key] === 'object' && obj[key] != null && !Array.isArray(obj[key])) {
 | 
			
		||||
				flattenObj(obj[key], propName, result);
 | 
			
		||||
			} else {
 | 
			
		||||
				result[propName] = obj[key];
 | 
			
		||||
@@ -119,6 +188,18 @@ 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
 | 
			
		||||
 *
 | 
			
		||||
@@ -147,21 +228,59 @@ export function includes(target: any, values: any, allowMissing = false): boolea
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Deep check if two objects are equal
 | 
			
		||||
 * Deep check if two items are equal.
 | 
			
		||||
 * Handles primitives, objects, arrays, functions, Date, RegExp, and circular references.
 | 
			
		||||
 *
 | 
			
		||||
 * @param {any} a - first item to compare
 | 
			
		||||
 * @param {any} b - second item to compare
 | 
			
		||||
 * @param {WeakMap<object, object>} [seen] - Internal parameter to track circular references
 | 
			
		||||
 * @returns {boolean} True if they match
 | 
			
		||||
 */
 | 
			
		||||
export function isEqual(a: any, b: any): boolean {
 | 
			
		||||
	const ta = typeof a, tb = typeof b;
 | 
			
		||||
	if((ta != 'object' || a == null) || (tb != 'object' || b == null))
 | 
			
		||||
		return ta == 'function' && tb == 'function' ? a.toString() == b.toString() : a === b;
 | 
			
		||||
	const keys = Object.keys(a);
 | 
			
		||||
	if(keys.length != Object.keys(b).length) return false;
 | 
			
		||||
	return Object.keys(a).every(key => isEqual(a[key], b[key]));
 | 
			
		||||
export function isEqual(a: any, b: any, seen = new WeakMap<object, object>()): boolean {
 | 
			
		||||
	// Simple cases
 | 
			
		||||
	if(a === b) return true;
 | 
			
		||||
	if(a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
 | 
			
		||||
	if(a instanceof RegExp && b instanceof RegExp) return a.source === b.source && a.flags === b.flags;
 | 
			
		||||
 | 
			
		||||
	// Null checks
 | 
			
		||||
	if(typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
 | 
			
		||||
		if(Number.isNaN(a) && Number.isNaN(b)) return true;
 | 
			
		||||
		if(typeof a === 'function' && typeof b === 'function') return a.toString() === b.toString()
 | 
			
		||||
		return false;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	// Circular references
 | 
			
		||||
	if(seen.has(a)) return seen.get(a) === b;
 | 
			
		||||
	seen.set(a, b);
 | 
			
		||||
	const isArrayA = Array.isArray(a);
 | 
			
		||||
	const isArrayB = Array.isArray(b);
 | 
			
		||||
 | 
			
		||||
	// Array checks
 | 
			
		||||
	if(isArrayA && isArrayB) {
 | 
			
		||||
		if(a.length !== b.length) return false;
 | 
			
		||||
		for(let i = 0; i < a.length; i++) {
 | 
			
		||||
			if(!isEqual(a[i], b[i], seen)) return false;
 | 
			
		||||
		}
 | 
			
		||||
		return true;
 | 
			
		||||
	}
 | 
			
		||||
	if(isArrayA !== isArrayB) return false;
 | 
			
		||||
 | 
			
		||||
	// Key & value deep comparison
 | 
			
		||||
	const keysA = Object.keys(a);
 | 
			
		||||
	const keysB = Object.keys(b);
 | 
			
		||||
	if(keysA.length !== keysB.length) return false;
 | 
			
		||||
	for(const key of keysA) {
 | 
			
		||||
		if(!Object.prototype.hasOwnProperty.call(b, key) || !isEqual(a[key], b[key], seen)) return false;
 | 
			
		||||
	}
 | 
			
		||||
	return true;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Experimental: Combine multiple object prototypes into one
 | 
			
		||||
 *
 | 
			
		||||
 * @param target Object that will have prototypes added
 | 
			
		||||
 * @param {any[]} constructors Additionally prototypes that should be merged into target
 | 
			
		||||
 */
 | 
			
		||||
export function mixin(target: any, constructors: any[]) {
 | 
			
		||||
	constructors.forEach(c => {
 | 
			
		||||
		Object.getOwnPropertyNames(c.prototype).forEach((name) => {
 | 
			
		||||
@@ -175,13 +294,13 @@ export function mixin(target: any, constructors: any[]) {
 | 
			
		||||
	});
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export function sanitizedJSON(obj: any, space?: number) {
 | 
			
		||||
	let cache: any[] = [];
 | 
			
		||||
	return JSON.parse(JSON.stringify(obj, (key, value) => {
 | 
			
		||||
		if (typeof value === 'object' && value !== null) {
 | 
			
		||||
			if (cache.includes(value)) return;
 | 
			
		||||
			cache.push(value);
 | 
			
		||||
		}
 | 
			
		||||
		return value;
 | 
			
		||||
	}, space));
 | 
			
		||||
/**
 | 
			
		||||
 * Run a map function on each property
 | 
			
		||||
 * @param obj Object that will be iterated
 | 
			
		||||
 * @param {(key: string, value: any) => any} fn Transformer function - receives key & value
 | 
			
		||||
 * @returns {{}}
 | 
			
		||||
 */
 | 
			
		||||
export function objectMap<T>(obj: any, fn: (key: string, value: any) => any): T {
 | 
			
		||||
	return <any>Object.entries(obj).map(([key, value]: [string, any]) => [key, fn(key, value)])
 | 
			
		||||
		.reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										351
									
								
								src/path-events.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										351
									
								
								src/path-events.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,351 @@
 | 
			
		||||
import {makeArray} from './array.ts';
 | 
			
		||||
import {ASet} from './aset.ts';
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Available methods:
 | 
			
		||||
 * * - All/Wildcard
 | 
			
		||||
 * n - None
 | 
			
		||||
 * c - Create
 | 
			
		||||
 * r - Read
 | 
			
		||||
 * u - Update
 | 
			
		||||
 * d - Delete
 | 
			
		||||
 * x - Execute
 | 
			
		||||
 */
 | 
			
		||||
export type Method = '*' | 'n' | 'c' | 'r' | 'u' | 'd' | 'x';
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Shorthand for creating Event from a string
 | 
			
		||||
 *
 | 
			
		||||
 * @example
 | 
			
		||||
 * ```ts
 | 
			
		||||
 * const event: Event = PE`users/system:*`;
 | 
			
		||||
 * ```
 | 
			
		||||
 *
 | 
			
		||||
 * @param {TemplateStringsArray} str String that will be parsed into Event
 | 
			
		||||
 * @param {string} args
 | 
			
		||||
 * @return {PathEvent} Event object
 | 
			
		||||
 */
 | 
			
		||||
export function PE(str: TemplateStringsArray, ...args: any[]) {
 | 
			
		||||
	const combined = [];
 | 
			
		||||
	for(let i = 0; i < str.length || i < args.length; i++) {
 | 
			
		||||
		if(str[i]) combined.push(str[i]);
 | 
			
		||||
		if(args[i]) combined.push(args[i]);
 | 
			
		||||
	}
 | 
			
		||||
	return new PathEvent(combined.join('/'));
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Shorthand for creating Event strings, ensures paths are correct
 | 
			
		||||
 *
 | 
			
		||||
 * @param {TemplateStringsArray} str
 | 
			
		||||
 * @param {string} args
 | 
			
		||||
 * @return {string}
 | 
			
		||||
 * @constructor
 | 
			
		||||
 */
 | 
			
		||||
export function PES(str: TemplateStringsArray, ...args: any[]) {
 | 
			
		||||
	let combined = [];
 | 
			
		||||
	for(let i = 0; i < str.length || i < args.length; i++) {
 | 
			
		||||
		if(str[i]) combined.push(str[i]);
 | 
			
		||||
		if(args[i]) combined.push(args[i]);
 | 
			
		||||
	}
 | 
			
		||||
	const [paths, methods] = combined.join('/').split(':');
 | 
			
		||||
	return PathEvent.toString(paths, <any>methods?.split(''));
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export class PathError extends Error { }
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * A  event broken down into its core components for easy processing
 | 
			
		||||
 * Event Structure: `module/path/name:property:method`
 | 
			
		||||
 * Example: `users/system:crud` or `storage/some/path/file.txt:r`
 | 
			
		||||
 */
 | 
			
		||||
export class PathEvent {
 | 
			
		||||
	/** First directory in path */
 | 
			
		||||
	module!: string;
 | 
			
		||||
	/** Entire path, including the module & name */
 | 
			
		||||
	fullPath!: string;
 | 
			
		||||
	/** Path including the name, excluding the module */
 | 
			
		||||
	path!: string;
 | 
			
		||||
	/** Last sagment of path */
 | 
			
		||||
	name!: string;
 | 
			
		||||
	/** List of methods */
 | 
			
		||||
	methods!: ASet<Method>;
 | 
			
		||||
 | 
			
		||||
	/** Internal cache for PathEvent instances to avoid redundant parsing */
 | 
			
		||||
	private static pathEventCache: Map<string, PathEvent> = new Map();
 | 
			
		||||
 | 
			
		||||
	/** All/Wildcard specified */
 | 
			
		||||
	get all(): boolean { return this.methods.has('*') }
 | 
			
		||||
	set all(v: boolean) { v ? this.methods = new ASet<Method>(['*']) : this.methods.delete('*'); }
 | 
			
		||||
	/** None specified */
 | 
			
		||||
	get none(): boolean { return this.methods.has('n') }
 | 
			
		||||
	set none(v: boolean) { v ? this.methods = new ASet<Method>(['n']) : this.methods.delete('n'); }
 | 
			
		||||
	/** Create method specified */
 | 
			
		||||
	get create(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('c')) }
 | 
			
		||||
	set create(v: boolean) { v ? this.methods.delete('n').delete('*').add('c') : this.methods.delete('c'); }
 | 
			
		||||
	/** Read method specified */
 | 
			
		||||
	get read(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('r')) }
 | 
			
		||||
	set read(v: boolean) { v ? this.methods.delete('n').delete('*').add('r') : this.methods.delete('r'); }
 | 
			
		||||
	/** Update method specified */
 | 
			
		||||
	get update(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('u')) }
 | 
			
		||||
	set update(v: boolean) { v ? this.methods.delete('n').delete('*').add('u') : this.methods.delete('u'); }
 | 
			
		||||
	/** Delete method specified */
 | 
			
		||||
	get delete(): boolean { return !this.methods.has('n') && (this.methods.has('*') || this.methods.has('d')) }
 | 
			
		||||
	set delete(v: boolean) { v ? this.methods.delete('n').delete('*').add('d') : this.methods.delete('d'); }
 | 
			
		||||
 | 
			
		||||
	constructor(e: string | PathEvent) {
 | 
			
		||||
		if(typeof e == 'object') {
 | 
			
		||||
			Object.assign(this, e);
 | 
			
		||||
			return;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		// Check cache first
 | 
			
		||||
		if (PathEvent.pathEventCache.has(e)) {
 | 
			
		||||
			Object.assign(this, PathEvent.pathEventCache.get(e)!);
 | 
			
		||||
			return;
 | 
			
		||||
		}
 | 
			
		||||
 | 
			
		||||
		let [p, scope, method] = e.replaceAll(/\/{2,}/g, '/').split(':');
 | 
			
		||||
		if(!method) method = scope || '*';
 | 
			
		||||
		if(p == '*' || (!p && method == '*')) {
 | 
			
		||||
			p = '';
 | 
			
		||||
			method = '*';
 | 
			
		||||
		}
 | 
			
		||||
		let temp = p.split('/').filter(p => !!p);
 | 
			
		||||
		this.module = temp.splice(0, 1)[0] || '';
 | 
			
		||||
		this.path = temp.join('/');
 | 
			
		||||
		this.fullPath = `${this.module}${this.module && this.path ? '/' : ''}${this.path}`;
 | 
			
		||||
		this.name = temp.pop() || '';
 | 
			
		||||
		this.methods = new ASet(<any>method.split(''));
 | 
			
		||||
 | 
			
		||||
		// Store in cache
 | 
			
		||||
		PathEvent.pathEventCache.set(e, this);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/** Clear the cache of all PathEvents */
 | 
			
		||||
	static clearCache(): void {
 | 
			
		||||
		PathEvent.pathEventCache.clear();
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Combine multiple events into one parsed object. Longest path takes precedent, but all subsequent methods are
 | 
			
		||||
	 * combined until a "none" is reached
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param {string | PathEvent} paths Events as strings or pre-parsed
 | 
			
		||||
	 * @return {PathEvent} Final combined permission
 | 
			
		||||
	 */
 | 
			
		||||
	static combine(...paths: (string | PathEvent)[]): PathEvent {
 | 
			
		||||
		let hitNone = false;
 | 
			
		||||
		const combined = paths.map(p => p instanceof PathEvent ? p : new PathEvent(p))
 | 
			
		||||
			.toSorted((p1, p2) => {
 | 
			
		||||
				const l1 = p1.fullPath.length, l2 = p2.fullPath.length;
 | 
			
		||||
				return l1 < l2 ? 1 : (l1 > l2 ? -1 : 0);
 | 
			
		||||
			}).reduce((acc, p) => {
 | 
			
		||||
				if(acc && !acc.fullPath.startsWith(p.fullPath)) return acc;
 | 
			
		||||
				if(p.none) hitNone = true;
 | 
			
		||||
				if(!acc) return p;
 | 
			
		||||
				if(hitNone) return acc;
 | 
			
		||||
				acc.methods = new ASet([...acc.methods, ...p.methods]);
 | 
			
		||||
				return acc;
 | 
			
		||||
			}, <any>null);
 | 
			
		||||
		return combined;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Filter a set of paths based on the target
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered
 | 
			
		||||
	 * @param filter {...PathEvent} Must container one of
 | 
			
		||||
	 * @return {boolean} Whether there is any overlap
 | 
			
		||||
	 */
 | 
			
		||||
	static filter(target: string | PathEvent | (string | PathEvent)[], ...filter: (string | PathEvent)[]): PathEvent[] {
 | 
			
		||||
		const parsedTarget = makeArray(target).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
 | 
			
		||||
		const parsedFilter = makeArray(filter).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
 | 
			
		||||
		return parsedTarget.filter(t => !!parsedFilter.find(r => {
 | 
			
		||||
			const wildcard = r.fullPath == '*' || t.fullPath == '*';
 | 
			
		||||
			const p1 = r.fullPath.includes('*') ? r.fullPath.slice(0, r.fullPath.indexOf('*')) : r.fullPath;
 | 
			
		||||
			const p2 = t.fullPath.includes('*') ? t.fullPath.slice(0, t.fullPath.indexOf('*')) : t.fullPath;
 | 
			
		||||
			const scope = p1.startsWith(p2) || p2.startsWith(p1);
 | 
			
		||||
			const methods = r.all || t.all || r.methods.intersection(t.methods).length;
 | 
			
		||||
			return (wildcard || scope) && methods;
 | 
			
		||||
		}));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Squash 2 sets of paths & return true if any overlap is found
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed
 | 
			
		||||
	 * @param has Target must have at least one of these path
 | 
			
		||||
	 * @return {boolean} Whether there is any overlap
 | 
			
		||||
	 */
 | 
			
		||||
	static has(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): boolean {
 | 
			
		||||
		const parsedTarget = makeArray(target).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
 | 
			
		||||
		const parsedRequired = makeArray(has).map(pe => pe instanceof PathEvent ? pe : new PathEvent(pe));
 | 
			
		||||
		return !!parsedRequired.find(r => !!parsedTarget.find(t => {
 | 
			
		||||
			const wildcard = r.fullPath == '*' || t.fullPath == '*';
 | 
			
		||||
			const p1 = r.fullPath.includes('*') ? r.fullPath.slice(0, r.fullPath.indexOf('*')) : r.fullPath;
 | 
			
		||||
			const p2 = t.fullPath.includes('*') ? t.fullPath.slice(0, t.fullPath.indexOf('*')) : t.fullPath;
 | 
			
		||||
			const scope = p1.startsWith(p2); // Note: Original had || p2.startsWith(p1) here, but has implies target has required.
 | 
			
		||||
			const methods = r.all || t.all || r.methods.intersection(t.methods).length;
 | 
			
		||||
			return (wildcard || scope) && methods;
 | 
			
		||||
		}));
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Squash 2 sets of paths & return true if the target has all paths
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param {string | PathEvent | (string | PathEvent)[]} target Array of Events as strings or pre-parsed
 | 
			
		||||
	 * @param has Target must have all these paths
 | 
			
		||||
	 * @return {boolean} Whether there is any overlap
 | 
			
		||||
	 */
 | 
			
		||||
	static hasAll(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): boolean {
 | 
			
		||||
		return has.filter(h => PathEvent.has(target, h)).length == has.length;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Same as `has` but raises an error if there is no overlap
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param {string | string[]} target Array of Events as strings or pre-parsed
 | 
			
		||||
	 * @param has Target must have at least one of these path
 | 
			
		||||
	 */
 | 
			
		||||
	static hasFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void {
 | 
			
		||||
		if(!PathEvent.has(target, ...has)) throw new PathError(`Requires one of: ${makeArray(has).join(', ')}`);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Same as `hasAll` but raises an error if the target is missing any paths
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param {string | string[]} target Array of Events as strings or pre-parsed
 | 
			
		||||
	 * @param has Target must have all these paths
 | 
			
		||||
	 */
 | 
			
		||||
	static hasAllFatal(target: string | PathEvent | (string | PathEvent)[], ...has: (string | PathEvent)[]): void {
 | 
			
		||||
		if(!PathEvent.hasAll(target, ...has)) throw new PathError(`Requires all: ${makeArray(has).join(', ')}`);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Create event string from its components
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param {string | string[]} path Event path
 | 
			
		||||
	 * @param {Method} methods Event method
 | 
			
		||||
	 * @return {string} String representation of Event
 | 
			
		||||
	 */
 | 
			
		||||
	static toString(path: string | string[], methods: Method | Method[]): string {
 | 
			
		||||
		let p = makeArray(path).filter(p => !!p).join('/');
 | 
			
		||||
		p = p?.trim().replaceAll(/\/{2,}/g, '/').replaceAll(/(^\/|\/$)/g, '');
 | 
			
		||||
		if(methods?.length) p += `:${makeArray(methods).map(m => m.toLowerCase()).join('')}`;
 | 
			
		||||
		return p;
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Squash 2 sets of paths & return true if any overlap is found
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param has Target must have at least one of these path
 | 
			
		||||
	 * @return {boolean} Whether there is any overlap
 | 
			
		||||
	 */
 | 
			
		||||
	has(...has: (string | PathEvent)[]): boolean {
 | 
			
		||||
		return PathEvent.has(this, ...has);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Squash 2 sets of paths & return true if the target has all paths
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param has Target must have all these paths
 | 
			
		||||
	 * @return {boolean} Whether there is any overlap
 | 
			
		||||
	 */
 | 
			
		||||
	hasAll(...has: (string | PathEvent)[]): boolean {
 | 
			
		||||
		return PathEvent.hasAll(this, ...has);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Same as `has` but raises an error if there is no overlap
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param has Target must have at least one of these path
 | 
			
		||||
	 */
 | 
			
		||||
	hasFatal(...has: (string | PathEvent)[]): void {
 | 
			
		||||
		return PathEvent.hasFatal(this, ...has);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Same as `hasAll` but raises an error if the target is missing any paths
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param has Target must have all these paths
 | 
			
		||||
	 */
 | 
			
		||||
	hasAllFatal(...has: (string | PathEvent)[]): void {
 | 
			
		||||
		return PathEvent.hasAllFatal(this, ...has);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Filter a set of paths based on this event
 | 
			
		||||
	 *
 | 
			
		||||
	 * @param {string | PathEvent | (string | PathEvent)[]} target Array of events that will filtered
 | 
			
		||||
	 * @return {boolean} Whether there is any overlap
 | 
			
		||||
	 */
 | 
			
		||||
	filter(target: string | PathEvent | (string | PathEvent)[]): PathEvent[] {
 | 
			
		||||
		return PathEvent.filter(target, this);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	/**
 | 
			
		||||
	 * Create event string from its components
 | 
			
		||||
	 *
 | 
			
		||||
	 * @return {string} String representation of Event
 | 
			
		||||
	 */
 | 
			
		||||
	toString() {
 | 
			
		||||
		return PathEvent.toString(this.fullPath, this.methods);
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export type PathListener = (event: PathEvent, ...args: any[]) => any;
 | 
			
		||||
export type PathUnsubscribe = () => void;
 | 
			
		||||
 | 
			
		||||
export type Event = string | PathEvent;
 | 
			
		||||
export interface IPathEventEmitter {
 | 
			
		||||
	emit(event: Event, ...args: any[]): void;
 | 
			
		||||
	off(listener: PathListener): void;
 | 
			
		||||
	on(event: Event | Event[], listener: PathListener): PathUnsubscribe;
 | 
			
		||||
	once(event: Event | Event[], listener?: PathListener): Promise<any>;
 | 
			
		||||
	relayEvents(emitter: PathEventEmitter): void;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Event emitter that uses paths allowing listeners to listen to different combinations of modules, paths & methods
 | 
			
		||||
 */
 | 
			
		||||
export class PathEventEmitter implements IPathEventEmitter{
 | 
			
		||||
	private listeners: [PathEvent, PathListener][] = [];
 | 
			
		||||
 | 
			
		||||
	constructor(public readonly prefix: string = '') { }
 | 
			
		||||
 | 
			
		||||
	emit(event: Event, ...args: any[]) {
 | 
			
		||||
		const parsed = event instanceof PathEvent ? event : new PathEvent(`${this.prefix}/${event}`);
 | 
			
		||||
		this.listeners.filter(l => PathEvent.has(l[0], parsed))
 | 
			
		||||
			.forEach(async l => l[1](parsed, ...args));
 | 
			
		||||
	};
 | 
			
		||||
 | 
			
		||||
	off(listener: PathListener) {
 | 
			
		||||
		this.listeners = this.listeners.filter(l => l[1] != listener);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	on(event: Event | Event[], listener: PathListener): PathUnsubscribe {
 | 
			
		||||
		makeArray(event).forEach(e => {
 | 
			
		||||
			if(typeof e == 'string' && e[0] == '*' && this.prefix) e = e.slice(1);
 | 
			
		||||
			this.listeners.push([
 | 
			
		||||
				e instanceof PathEvent ? e : new PathEvent(`${this.prefix}/${e}`),
 | 
			
		||||
				listener
 | 
			
		||||
			])
 | 
			
		||||
		});
 | 
			
		||||
		return () => this.off(listener);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	once(event: Event | Event[], listener?: PathListener): Promise<any> {
 | 
			
		||||
		return new Promise(res => {
 | 
			
		||||
			const unsubscribe = this.on(event, (event: PathEvent, ...args: any[]) => {
 | 
			
		||||
				res(args.length < 2 ? args[0] : args);
 | 
			
		||||
				if(listener) listener(event, ...args);
 | 
			
		||||
				unsubscribe();
 | 
			
		||||
			});
 | 
			
		||||
		});
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	relayEvents(emitter: IPathEventEmitter) {
 | 
			
		||||
		emitter.on('*', (event, ...args) => this.emit(event, ...args));
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@@ -1,5 +1,25 @@
 | 
			
		||||
export type ProgressCallback = (progress: number) => any;
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * A promise that fires the `onProgress` callback on incremental progress
 | 
			
		||||
 *
 | 
			
		||||
 * @example
 | 
			
		||||
 * ```js
 | 
			
		||||
 * const promise = new Promise((resolve, reject, progress) => {
 | 
			
		||||
 *   const max = 10;
 | 
			
		||||
 * 	 for(let i = 0; i < max; i++) progress(i / max);
 | 
			
		||||
 * 	 resolve(1);
 | 
			
		||||
 * });
 | 
			
		||||
 *
 | 
			
		||||
 * console.log(promise.progress);
 | 
			
		||||
 *
 | 
			
		||||
 * promise.onProgress(console.log)
 | 
			
		||||
 *        .then(console.log)
 | 
			
		||||
 *        .catch(console.error)
 | 
			
		||||
 *        .finally(...);
 | 
			
		||||
 *
 | 
			
		||||
 * ```
 | 
			
		||||
 */
 | 
			
		||||
export class PromiseProgress<T> extends Promise<T> {
 | 
			
		||||
	private listeners: ProgressCallback[] = [];
 | 
			
		||||
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										71
									
								
								src/search.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										71
									
								
								src/search.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,71 @@
 | 
			
		||||
import {JSONAttemptParse, JSONSerialize} from './json.ts';
 | 
			
		||||
import {dotNotation} from './objects.ts';
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Filters an array of objects based on a search term and optional regex checking.
 | 
			
		||||
 *
 | 
			
		||||
 * @param {Array} rows Array of objects to filter
 | 
			
		||||
 * @param {string} search The logic string or regext to filter on
 | 
			
		||||
 * @param {boolean} [regex=false] Treat search expression as regex
 | 
			
		||||
 * @param {Function} [transform=(r) => r] - Transform rows before filtering
 | 
			
		||||
 * @return {Array} The filtered array of objects that matched search
 | 
			
		||||
 */
 | 
			
		||||
export function search(rows: any[], search: string, regex?: boolean, transform: Function = (r: any) => r) {
 | 
			
		||||
	if(!rows) return [];
 | 
			
		||||
	return rows.filter(r => {
 | 
			
		||||
		// Empty search
 | 
			
		||||
		if(!search) return true;
 | 
			
		||||
		const value = transform(r);
 | 
			
		||||
		// Regex search
 | 
			
		||||
		if(regex) {
 | 
			
		||||
			return !!Object.values(value).filter((v: any) => {
 | 
			
		||||
				try { return RegExp(search, 'gm').test(v.toString()); }
 | 
			
		||||
				catch { return false; }
 | 
			
		||||
			}).length
 | 
			
		||||
		} else {
 | 
			
		||||
			return logicTest(value, search);
 | 
			
		||||
		}
 | 
			
		||||
	});
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Test an object against a logic condition. By default values are checked
 | 
			
		||||
 * @param {string} condition
 | 
			
		||||
 * @param {object} target
 | 
			
		||||
 * @return {boolean}
 | 
			
		||||
 */
 | 
			
		||||
export function logicTest(target: object, condition: string): boolean {
 | 
			
		||||
	const evalBoolean = (a: any, op: string, b: any): boolean => {
 | 
			
		||||
		switch(op) {
 | 
			
		||||
			case '=':
 | 
			
		||||
			case '==': return a == b;
 | 
			
		||||
			case '!=': return a != b;
 | 
			
		||||
			case '+=': return a?.toString().includes(b);
 | 
			
		||||
			case '-=': return !a?.toString().includes(b);
 | 
			
		||||
			case '>': return a > b;
 | 
			
		||||
			case '>=': return a >= b;
 | 
			
		||||
			case '<': return a < b;
 | 
			
		||||
			case '<=': return a <= b;
 | 
			
		||||
			default: return false;
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	const or = condition.split('||').map(p => p.trim()).filter(p => !!p);
 | 
			
		||||
	return -1 != or.findIndex(p => {
 | 
			
		||||
		// Make sure all ANDs pass
 | 
			
		||||
		const and = p.split('&&').map(p => p.trim()).filter(p => !!p);
 | 
			
		||||
		return and.filter(p => {
 | 
			
		||||
			// Boolean operator
 | 
			
		||||
			const prop = /(\S+)\s*(==?|!=|\+=|-=|>=|>|<=|<)\s*(\S+)/g.exec(p);
 | 
			
		||||
			if(prop) {
 | 
			
		||||
				const key = Object.keys(target).find(k => k.toLowerCase() == prop[1].toLowerCase());
 | 
			
		||||
				return evalBoolean(dotNotation<any>(target, key || prop[1]),  prop[2], JSONAttemptParse(prop[3]));
 | 
			
		||||
			}
 | 
			
		||||
			// Case-sensitive
 | 
			
		||||
			const v = Object.values(target).map(JSONSerialize).join('');
 | 
			
		||||
			if(/[A-Z]/g.test(condition)) return v.includes(p);
 | 
			
		||||
			// Case-insensitive
 | 
			
		||||
			return v.toLowerCase().includes(p);
 | 
			
		||||
		}).length == and.length;
 | 
			
		||||
	});
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										215
									
								
								src/string.ts
									
									
									
									
									
								
							
							
						
						
									
										215
									
								
								src/string.ts
									
									
									
									
									
								
							@@ -1,44 +1,83 @@
 | 
			
		||||
export function countChars(text: string, pattern: RegExp) {
 | 
			
		||||
	return text.length - text.replaceAll(pattern, '').length;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export function createHex(length: number) {
 | 
			
		||||
	return Array(length).fill(null).map(() => Math.round(Math.random() * 0xF).toString(16)).join('');
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * String of all letters
 | 
			
		||||
 *
 | 
			
		||||
 */
 | 
			
		||||
const LETTER_LIST = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
 | 
			
		||||
export const LETTER_LIST = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * String of all numbers
 | 
			
		||||
 *
 | 
			
		||||
 */
 | 
			
		||||
const NUMBER_LIST = '0123456789';
 | 
			
		||||
export const NUMBER_LIST = '0123456789';
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * String of all symbols
 | 
			
		||||
 */
 | 
			
		||||
const SYMBOL_LIST = '~`!@#$%^&*()_-+={[}]|\\:;"\'<,>.?/';
 | 
			
		||||
export const SYMBOL_LIST = '~`!@#$%^&*()_-+={[}]|\\:;"\'<,>.?/';
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * String of all letters, numbers & symbols
 | 
			
		||||
 */
 | 
			
		||||
const CHAR_LIST = LETTER_LIST + NUMBER_LIST + SYMBOL_LIST;
 | 
			
		||||
export const CHAR_LIST = LETTER_LIST + LETTER_LIST.toLowerCase() + NUMBER_LIST + SYMBOL_LIST;
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Converts text to camelCase
 | 
			
		||||
 */
 | 
			
		||||
export function camelCase(str?: string): string {
 | 
			
		||||
	if(!str) return '';
 | 
			
		||||
	const pascal = pascalCase(str);
 | 
			
		||||
	return pascal.charAt(0).toLowerCase() + pascal.slice(1);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Convert number of bytes into a human-readable size
 | 
			
		||||
 *
 | 
			
		||||
 * @param {number} bytes Number of bytes
 | 
			
		||||
 * @param {number} decimals Decimal places to preserve
 | 
			
		||||
 * @return {string} Formated size
 | 
			
		||||
 */
 | 
			
		||||
export function formatBytes(bytes: number, decimals = 2) {
 | 
			
		||||
	if (bytes === 0) return '0 Bytes';
 | 
			
		||||
	const k = 1024;
 | 
			
		||||
	const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
 | 
			
		||||
	const i = Math.floor(Math.log(bytes) / Math.log(k));
 | 
			
		||||
	return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + ' ' + sizes[i];
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Convert milliseconds to human-readable duration
 | 
			
		||||
 * @param {string} ms milliseconds
 | 
			
		||||
 * @param {boolean} short Use unit initial instead of word
 | 
			
		||||
 * @return {string} formated duration
 | 
			
		||||
 */
 | 
			
		||||
export function formatMs(ms: number, short = false): string {
 | 
			
		||||
	if (isNaN(ms) || ms < 0) return "Invalid input";
 | 
			
		||||
	const seconds = ms / 1000;
 | 
			
		||||
	const minutes = seconds / 60;
 | 
			
		||||
	const hours = minutes / 60;
 | 
			
		||||
	const days = hours / 24;
 | 
			
		||||
	if (days >= 1) return `${days.toFixed(1)} ${short ? 'd' : 'days'}`;
 | 
			
		||||
	else if (hours >= 1) return `${hours.toFixed(1)} ${short ? 'h' : 'hours'}`;
 | 
			
		||||
	else if (minutes >= 1) return `${minutes.toFixed(1)} ${short ? 'm' : 'minutes'}`;
 | 
			
		||||
	else return `${seconds.toFixed(1)} ${short ? 's' : 'seconds'}`;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Extract numbers from a string & create a formated phone number: +1 (123) 456-7890
 | 
			
		||||
 *
 | 
			
		||||
 * @param {string} number String that will be parsed for numbers
 | 
			
		||||
 * @return {string} Formated phone number
 | 
			
		||||
 */
 | 
			
		||||
export function formatPhoneNumber(number: string) {
 | 
			
		||||
	const parts = /(\+?1)?.*?(\d{3}).*?(\d{3}).*?(\d{4})/g.exec(number);
 | 
			
		||||
	if(!parts) throw new Error(`Number cannot be parsed: ${number}`);
 | 
			
		||||
	return `${parts[1] ?? ''} (${parts[2]}) ${parts[3]}-${parts[4]}`.trim();
 | 
			
		||||
	return `${parts[1] ? '+1' : ''} (${parts[2]}) ${parts[3]}-${parts[4]}`.trim();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Insert a string into another string at a given position
 | 
			
		||||
 *
 | 
			
		||||
 * @example
 | 
			
		||||
 * ```
 | 
			
		||||
 * ```js
 | 
			
		||||
 * console.log(insertAt('Hello world!', ' glorious', 5);
 | 
			
		||||
 * // Output: Hello glorious world!
 | 
			
		||||
 * ```
 | 
			
		||||
@@ -47,17 +86,65 @@ export function formatPhoneNumber(number: string) {
 | 
			
		||||
 * @param {string} str - Value that will be injected to parent
 | 
			
		||||
 * @param {number} index - Position to inject string at
 | 
			
		||||
 * @returns {string} - New string
 | 
			
		||||
 * @deprecated use `strSplice()`
 | 
			
		||||
 */
 | 
			
		||||
export function insertAt(target: string, str: string, index: number): String {
 | 
			
		||||
	return `${target.slice(0, index)}${str}${target.slice(index + 1)}`;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export function pad(text: any, length: number, char: string, start = true) {
 | 
			
		||||
	const t = text.toString();
 | 
			
		||||
	const l = length - t.length;
 | 
			
		||||
	if(l <= 0) return t;
 | 
			
		||||
	const padding = Array(~~(l / char.length)).fill(char).join('');
 | 
			
		||||
	return start ? padding + t : t + padding;
 | 
			
		||||
/**
 | 
			
		||||
 * Converts text to kebab-case
 | 
			
		||||
 */
 | 
			
		||||
export function kebabCase(str?: string): string {
 | 
			
		||||
	if(!str) return '';
 | 
			
		||||
	return wordSegments(str).map(w => w.toLowerCase()).join("-");
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Add padding to string
 | 
			
		||||
 *
 | 
			
		||||
 * @example
 | 
			
		||||
 * ```js
 | 
			
		||||
 * const now = new Date();
 | 
			
		||||
 * const padded = now.getHours() + ':' + pad(now.getMinutes(), 2, '0');
 | 
			
		||||
 * console.log(padded); // Output: "2:05"
 | 
			
		||||
 * ```
 | 
			
		||||
 *
 | 
			
		||||
 * @param text Text that will be padded
 | 
			
		||||
 * @param {number} length Target length
 | 
			
		||||
 * @param {string} char Character to use as padding, defaults to space
 | 
			
		||||
 * @param {boolean} start Will pad start of text if true, or the end if false
 | 
			
		||||
 * @return {string} Padded string
 | 
			
		||||
 * @deprecated Please use `String.padStart` & `String.padEnd`
 | 
			
		||||
 */
 | 
			
		||||
export function pad(text: any, length: number, char: string = ' ', start = true) {
 | 
			
		||||
	if(start) return text.toString().padStart(length, char);
 | 
			
		||||
	return text.toString().padEnd(length, char);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Convert text to PascalCase
 | 
			
		||||
 * @param {string} str
 | 
			
		||||
 * @return {string}
 | 
			
		||||
 */
 | 
			
		||||
export function pascalCase(str?: string): string {
 | 
			
		||||
	if(!str) return '';
 | 
			
		||||
	return wordSegments(str)
 | 
			
		||||
		.map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())
 | 
			
		||||
		.join('');
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Generate a random hexadecimal value
 | 
			
		||||
 *
 | 
			
		||||
 * @param {number} length Number of hexadecimal place values
 | 
			
		||||
 * @return {string} Hexadecimal number as a string
 | 
			
		||||
 */
 | 
			
		||||
export function randomHex(length: number) {
 | 
			
		||||
	return Array(length).fill(null).map(() => Math.round(Math.random() * 0xF).toString(16)).join('');
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
@@ -113,6 +200,30 @@ export function randomStringBuilder(length: number, letters = false, numbers = f
 | 
			
		||||
	}).join('');
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Converts text to snake_case
 | 
			
		||||
 */
 | 
			
		||||
export function snakeCase(str?: string): string {
 | 
			
		||||
	if(!str) return '';
 | 
			
		||||
	return wordSegments(str).map(w => w.toLowerCase()).join("_");
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Splice a string together (Similar to Array.splice)
 | 
			
		||||
 *
 | 
			
		||||
 * @param {string} str String that will be modified
 | 
			
		||||
 * @param {number} start Start index of splice
 | 
			
		||||
 * @param {number} deleteCount Number of characters to remove in splice
 | 
			
		||||
 * @param {string} insert Insert new string into splice
 | 
			
		||||
 * @return {string} Returned spliced string
 | 
			
		||||
 */
 | 
			
		||||
export function strSplice(str: string, start: number, deleteCount: number, insert = '') {
 | 
			
		||||
	const before = str.slice(0, start);
 | 
			
		||||
	const after = str.slice(start + deleteCount);
 | 
			
		||||
	return before + insert + after;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Find all substrings that match a given pattern.
 | 
			
		||||
 *
 | 
			
		||||
@@ -141,8 +252,51 @@ export function matchAll(value: string, regex: RegExp | string): RegExpExecArray
 | 
			
		||||
	return ret;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/** Parts of a URL */
 | 
			
		||||
export type ParsedUrl = {
 | 
			
		||||
	protocol?: string,
 | 
			
		||||
	subdomain?: string,
 | 
			
		||||
	domain: string,
 | 
			
		||||
	host: string,
 | 
			
		||||
	port?: number,
 | 
			
		||||
	path?: string,
 | 
			
		||||
	query?: {[name: string]: string}
 | 
			
		||||
	fragment?: string
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Break a URL string into its parts for easy parsing
 | 
			
		||||
 *
 | 
			
		||||
 * @param {string} url URL string that will be parsed
 | 
			
		||||
 * @returns {RegExpExecArray} Parts of URL
 | 
			
		||||
 * @deprecated Use built-in URL object: `new URL('...')`;
 | 
			
		||||
 */
 | 
			
		||||
export function parseUrl(url: string): ParsedUrl {
 | 
			
		||||
	const processed = new RegExp(
 | 
			
		||||
		'(?:(?<protocol>[\\w\\d]+)\\:\\/\\/)?(?:(?<user>.+)\\@)?(?<host>(?<domain>[^:\\/\\?#@\\n]+)(?:\\:(?<port>\\d*))?)(?<path>\\/.*?)?(?:\\?(?<query>.*?))?(?:#(?<fragment>.*?))?$',
 | 
			
		||||
		'gm').exec(url);
 | 
			
		||||
	const groups: ParsedUrl = <any>processed?.groups ?? {};
 | 
			
		||||
	const domains = groups.domain.split('.');
 | 
			
		||||
	if(groups['port'] != null) groups.port = Number(groups.port);
 | 
			
		||||
	if(domains.length > 2) {
 | 
			
		||||
		groups.domain = domains.splice(-2, 2).join('.');
 | 
			
		||||
		groups.subdomain = domains.join('.');
 | 
			
		||||
	}
 | 
			
		||||
	if(groups.query) {
 | 
			
		||||
		const split = (<any>groups.query).split('&'), query: any = {};
 | 
			
		||||
		split.forEach((q: any) => {
 | 
			
		||||
			const [key, val] = q.split('=');
 | 
			
		||||
			query[key] = val;
 | 
			
		||||
		});
 | 
			
		||||
		groups.query = query;
 | 
			
		||||
	}
 | 
			
		||||
	return groups;
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Create MD5 hash using native javascript
 | 
			
		||||
 *
 | 
			
		||||
 * @param d String to hash
 | 
			
		||||
 * @returns {string} Hashed string
 | 
			
		||||
 */
 | 
			
		||||
@@ -161,6 +315,23 @@ export function md5(d: string)  {
 | 
			
		||||
	function bit_rol(d:any,_:any){return d<<_|d>>>32-_
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Splits a string into logical word segments
 | 
			
		||||
 */
 | 
			
		||||
export function wordSegments(str?: string): string[] {
 | 
			
		||||
	if (!str) return [];
 | 
			
		||||
	return str
 | 
			
		||||
		.replace(/([a-z])([A-Z])/g, "$1 $2")
 | 
			
		||||
		.replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
 | 
			
		||||
		.replace(/([0-9]+)([a-zA-Z])/g, "$1 $2")
 | 
			
		||||
		.replace(/([a-zA-Z])([0-9]+)/g, "$1 $2")
 | 
			
		||||
		.replace(/[_\-\s]+/g, " ")
 | 
			
		||||
		.trim()
 | 
			
		||||
		.split(/\s+/)
 | 
			
		||||
		.filter(Boolean);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Check if email is valid
 | 
			
		||||
 *
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										303
									
								
								src/time.ts
									
									
									
									
									
								
							
							
						
						
									
										303
									
								
								src/time.ts
									
									
									
									
									
								
							@@ -1,3 +1,249 @@
 | 
			
		||||
/**
 | 
			
		||||
 * Like setInterval but will adjust the timeout value to account for runtime
 | 
			
		||||
 * @param {Function} cb Callback function that will be ran
 | 
			
		||||
 * @param {number} ms Run function ever x seconds
 | 
			
		||||
 * @return {() => void}
 | 
			
		||||
 */
 | 
			
		||||
export function adjustedInterval(cb: Function, ms: number) {
 | 
			
		||||
	let cancel = false, timeout: any = null;
 | 
			
		||||
	const p = async () => {
 | 
			
		||||
		if (cancel) return;
 | 
			
		||||
		const start = new Date().getTime();
 | 
			
		||||
		await cb();
 | 
			
		||||
		const end = new Date().getTime();
 | 
			
		||||
		timeout = setTimeout(() => p(), ms - (end - start) || 1);
 | 
			
		||||
	};
 | 
			
		||||
	p();
 | 
			
		||||
	return () => {
 | 
			
		||||
		cancel = true;
 | 
			
		||||
		if(timeout) clearTimeout(timeout);
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export function dayOfWeek(d: number): string {
 | 
			
		||||
	return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d];
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export function dayOfYear(date: Date): number {
 | 
			
		||||
	const start = new Date(Date.UTC(date.getUTCFullYear(), 0, 1));
 | 
			
		||||
	return Math.ceil((date.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Format date
 | 
			
		||||
 *
 | 
			
		||||
 * Year:
 | 
			
		||||
 * - YYYY = 2025 (4-digit year)
 | 
			
		||||
 * - YY = 25 (2-digit year)
 | 
			
		||||
 *
 | 
			
		||||
 * Month:
 | 
			
		||||
 * - MMMM = January (full month name)
 | 
			
		||||
 * - MMM = Jan (abbreviated month name)
 | 
			
		||||
 * - MM = 01 (zero-padded month number)
 | 
			
		||||
 * - M = 1 (month number)
 | 
			
		||||
 *
 | 
			
		||||
 * Day:
 | 
			
		||||
 * - DDD = 123 (day of year)
 | 
			
		||||
 * - DD = 01 (zero-padded day)
 | 
			
		||||
 * - Do = 1st (day with ordinal suffix)
 | 
			
		||||
 * - D = 1 (day number)
 | 
			
		||||
 * - dddd = Monday (full day name)
 | 
			
		||||
 * - ddd = Mon (abbreviated day name)
 | 
			
		||||
 *
 | 
			
		||||
 * Hour:
 | 
			
		||||
 * - HH = 13 (24-hour format, zero-padded)
 | 
			
		||||
 * - H = 13 (24-hour format)
 | 
			
		||||
 * - hh = 01 (12-hour format, zero-padded)
 | 
			
		||||
 * - h = 1 (12-hour format)
 | 
			
		||||
 *
 | 
			
		||||
 * Minute:
 | 
			
		||||
 * - mm = 05 (zero-padded minutes)
 | 
			
		||||
 * - m = 5 (minutes)
 | 
			
		||||
 *
 | 
			
		||||
 * Second:
 | 
			
		||||
 * - ss = 09 (zero-padded seconds)
 | 
			
		||||
 * - s = 9 (seconds)
 | 
			
		||||
 *
 | 
			
		||||
 * Millisecond:
 | 
			
		||||
 * - SSS = 123 (3-digit milliseconds)
 | 
			
		||||
 *
 | 
			
		||||
 * AM/PM:
 | 
			
		||||
 * - A = AM/PM (uppercase)
 | 
			
		||||
 * - a = am/pm (lowercase)
 | 
			
		||||
 *
 | 
			
		||||
 * Timezone:
 | 
			
		||||
 * - ZZ = +0500 (timezone offset without colon)
 | 
			
		||||
 * - Z = +05:00 (timezone offset with colon)
 | 
			
		||||
 * - z = EST (timezone abbreviation)
 | 
			
		||||
 *
 | 
			
		||||
 * @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 tz Set timezone offset
 | 
			
		||||
 * @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 {
 | 
			
		||||
	if (typeof date === 'number' || typeof date === 'string') date = new Date(date);
 | 
			
		||||
	if (isNaN(date.getTime())) throw new Error('Invalid date input');
 | 
			
		||||
	const numericTz = typeof tz === 'number';
 | 
			
		||||
	const localTz = tz === 'local' || (!numericTz && tz.toLowerCase?.() === 'local');
 | 
			
		||||
	const tzName = localTz ? Intl.DateTimeFormat().resolvedOptions().timeZone : numericTz ? 'UTC' : tz;
 | 
			
		||||
 | 
			
		||||
	if (!numericTz && tzName !== 'UTC') {
 | 
			
		||||
		try {
 | 
			
		||||
			new Intl.DateTimeFormat('en-US', { timeZone: tzName }).format();
 | 
			
		||||
		} catch {
 | 
			
		||||
			throw new Error(`Invalid timezone: ${tzName}`);
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	let zonedDate = new Date(date);
 | 
			
		||||
	let get: (fn: 'FullYear' | 'Month' | 'Date' | 'Day' | 'Hours' | 'Minutes' | 'Seconds' | 'Milliseconds') => number;
 | 
			
		||||
	const partsMap: Record<string, string> = {};
 | 
			
		||||
	if (!numericTz && tzName !== 'UTC') {
 | 
			
		||||
		const parts = new Intl.DateTimeFormat('en-US', {
 | 
			
		||||
			timeZone: tzName,
 | 
			
		||||
			year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'long',
 | 
			
		||||
			hour: '2-digit', minute: '2-digit', second: '2-digit',
 | 
			
		||||
			hour12: false
 | 
			
		||||
		}).formatToParts(date);
 | 
			
		||||
		parts.forEach(p => {
 | 
			
		||||
			partsMap[p.type] = p.value;
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		const monthValue = parseInt(partsMap.month) - 1;
 | 
			
		||||
		const dayOfWeekValue = new Date(`${partsMap.year}-${partsMap.month}-${partsMap.day}`).getDay();
 | 
			
		||||
		const hourValue = parseInt(partsMap.hour);
 | 
			
		||||
 | 
			
		||||
		get = (fn: 'FullYear' | 'Month' | 'Date' | 'Day' | 'Hours' | 'Minutes' | 'Seconds' | 'Milliseconds'): number => {
 | 
			
		||||
			switch (fn) {
 | 
			
		||||
				case 'FullYear': return parseInt(partsMap.year);
 | 
			
		||||
				case 'Month': return monthValue;
 | 
			
		||||
				case 'Date': return parseInt(partsMap.day);
 | 
			
		||||
				case 'Day': return dayOfWeekValue;
 | 
			
		||||
				case 'Hours': return hourValue;
 | 
			
		||||
				case 'Minutes': return parseInt(partsMap.minute);
 | 
			
		||||
				case 'Seconds': return parseInt(partsMap.second);
 | 
			
		||||
				default: return 0;
 | 
			
		||||
			}
 | 
			
		||||
		};
 | 
			
		||||
	} else {
 | 
			
		||||
		const offset = numericTz ? tz as number : 0;
 | 
			
		||||
		zonedDate = new Date(date.getTime() + offset * 60 * 60 * 1000);
 | 
			
		||||
		get = (fn: 'FullYear' | 'Month' | 'Date' | 'Day' | 'Hours' | 'Minutes' | 'Seconds' | 'Milliseconds'): number => zonedDate[`getUTC${fn}`]();
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function numSuffix(n: number): string {
 | 
			
		||||
		const s = ["th", "st", "nd", "rd"];
 | 
			
		||||
		const v = n % 100;
 | 
			
		||||
		return n + (s[(v - 20) % 10] || s[v] || s[0]);
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function getTZOffset(): string {
 | 
			
		||||
		if (numericTz) {
 | 
			
		||||
			const total = (tz as number) * 60;
 | 
			
		||||
			const hours = Math.floor(Math.abs(total) / 60);
 | 
			
		||||
			const mins = Math.abs(total) % 60;
 | 
			
		||||
			return `${tz >= 0 ? '+' : '-'}${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
 | 
			
		||||
		}
 | 
			
		||||
		try {
 | 
			
		||||
			const offset = new Intl.DateTimeFormat('en-US', {timeZone: tzName, timeZoneName: 'longOffset', hour: '2-digit', minute: '2-digit',})
 | 
			
		||||
				.formatToParts(<Date>date).find(p => p.type === 'timeZoneName')?.value.match(/([+-]\d{2}:\d{2})/)?.[1];
 | 
			
		||||
			if (offset) return offset;
 | 
			
		||||
		} catch {}
 | 
			
		||||
		return '+00:00';
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	function getTZAbbr(): string {
 | 
			
		||||
		if (numericTz && tz === 0) return 'UTC';
 | 
			
		||||
		try {
 | 
			
		||||
			return new Intl.DateTimeFormat('en-US', { timeZone: tzName, timeZoneName: 'short' })
 | 
			
		||||
				.formatToParts(<Date>date).find(p => p.type === 'timeZoneName')?.value || '';
 | 
			
		||||
		} catch {
 | 
			
		||||
			return tzName;
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	const tokens: Record<string, string> = {
 | 
			
		||||
		YYYY: get('FullYear').toString(),
 | 
			
		||||
		YY: get('FullYear').toString().slice(2),
 | 
			
		||||
		MMMM: month(get('Month')),
 | 
			
		||||
		MMM: month(get('Month')).slice(0, 3),
 | 
			
		||||
		MM: (get('Month') + 1).toString().padStart(2, '0'),
 | 
			
		||||
		M: (get('Month') + 1).toString(),
 | 
			
		||||
		DDD: dayOfYear(zonedDate).toString(),
 | 
			
		||||
		DD: get('Date').toString().padStart(2, '0'),
 | 
			
		||||
		Do: numSuffix(get('Date')),
 | 
			
		||||
		D: get('Date').toString(),
 | 
			
		||||
		dddd: dayOfWeek(get('Day')),
 | 
			
		||||
		ddd: dayOfWeek(get('Day')).slice(0, 3),
 | 
			
		||||
		HH: get('Hours').toString().padStart(2, '0'),
 | 
			
		||||
		H: get('Hours').toString(),
 | 
			
		||||
		hh: (get('Hours') % 12 || 12).toString().padStart(2, '0'),
 | 
			
		||||
		h: (get('Hours') % 12 || 12).toString(),
 | 
			
		||||
		mm: get('Minutes').toString().padStart(2, '0'),
 | 
			
		||||
		m: get('Minutes').toString(),
 | 
			
		||||
		ss: get('Seconds').toString().padStart(2, '0'),
 | 
			
		||||
		s: get('Seconds').toString(),
 | 
			
		||||
		SSS: (zonedDate[`getUTC${'Milliseconds'}`]()).toString().padStart(3, '0'),
 | 
			
		||||
		A: get('Hours') >= 12 ? 'PM' : 'AM',
 | 
			
		||||
		a: get('Hours') >= 12 ? 'pm' : 'am',
 | 
			
		||||
		ZZ: getTZOffset().replace(':', ''),
 | 
			
		||||
		Z: getTZOffset(),
 | 
			
		||||
		z: getTZAbbr(),
 | 
			
		||||
	};
 | 
			
		||||
 | 
			
		||||
	return format.replace(/YYYY|YY|MMMM|MMM|MM|M|DDD|DD|Do|D|dddd|ddd|HH|H|hh|h|mm|m|ss|s|SSS|A|a|ZZ|Z|z/g, token => tokens[token]);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Run a function immediately & repeat every x ms
 | 
			
		||||
 *
 | 
			
		||||
 * @param {() => any} fn Callback function
 | 
			
		||||
 * @param {number} interval Repeat in ms
 | 
			
		||||
 * @return {number} Clear Interval ID
 | 
			
		||||
 */
 | 
			
		||||
export function instantInterval(fn: () => any, interval: number) {
 | 
			
		||||
	fn();
 | 
			
		||||
	return setInterval(fn, interval);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
export function month(m: number): string {
 | 
			
		||||
	return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][m];
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * 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 sleepWhile(() => loading); // Won't continue until loading flag is false
 | 
			
		||||
 * ```
 | 
			
		||||
 *
 | 
			
		||||
 * @param {() => boolean | Promise<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 sleepWhile(fn : () => boolean | Promise<boolean>, checkInterval = 100): Promise<void> {
 | 
			
		||||
	while(await fn()) await sleep(checkInterval);
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
/**
 | 
			
		||||
 * Calculate the number of milliseconds until date/time
 | 
			
		||||
 *
 | 
			
		||||
@@ -8,33 +254,34 @@ 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) {
 | 
			
		||||
	const d = date instanceof Date ? date : new Date(date);
 | 
			
		||||
	return new Intl.DateTimeFormat("en-us", {
 | 
			
		||||
		weekday: "long",
 | 
			
		||||
		month: "short",
 | 
			
		||||
		day: "numeric",
 | 
			
		||||
		hour: "numeric",
 | 
			
		||||
		minute: "numeric",
 | 
			
		||||
		hour12: true
 | 
			
		||||
	}).format(d);
 | 
			
		||||
/**
 | 
			
		||||
 * Convert a timezone string (e.g., "America/Toronto") to its current UTC offset in minutes.
 | 
			
		||||
 * @param {string} tz - Timezone string, e.g. "America/Toronto"
 | 
			
		||||
 * @param {Date} [date=new Date()] - The date for which you want the offset (default is now)
 | 
			
		||||
 * @returns {number} - Offset in minutes (e.g., -240)
 | 
			
		||||
 */
 | 
			
		||||
export function timezoneOffset(tz: string, date: Date = new Date()): number {
 | 
			
		||||
	const dtf = new Intl.DateTimeFormat('en-US', {
 | 
			
		||||
		timeZone: tz,
 | 
			
		||||
		hour12: false,
 | 
			
		||||
		year: 'numeric',
 | 
			
		||||
		month: '2-digit',
 | 
			
		||||
		day: '2-digit',
 | 
			
		||||
		hour: '2-digit',
 | 
			
		||||
		minute: '2-digit',
 | 
			
		||||
		second: '2-digit',
 | 
			
		||||
	});
 | 
			
		||||
	const parts = dtf.formatToParts(date);
 | 
			
		||||
	const get = (type: string) => Number(parts.find(v => v.type === type)?.value);
 | 
			
		||||
	const y = get('year');
 | 
			
		||||
	const mo = get('month');
 | 
			
		||||
	const d = get('day');
 | 
			
		||||
	const h = get('hour');
 | 
			
		||||
	const m = get('minute');
 | 
			
		||||
	const s = get('second');
 | 
			
		||||
 | 
			
		||||
	const asUTC = Date.UTC(y, mo - 1, d, h, m, s);
 | 
			
		||||
	const asLocal = date.getTime();
 | 
			
		||||
	return Math.round((asLocal - asUTC) / 60000);
 | 
			
		||||
}
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										4
									
								
								src/types.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										4
									
								
								src/types.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,4 @@
 | 
			
		||||
/** Mark all properties as writable */
 | 
			
		||||
export type Writable<T> = {
 | 
			
		||||
	-readonly [P in keyof T]: T[P]
 | 
			
		||||
};
 | 
			
		||||
							
								
								
									
										121
									
								
								tests/arg-parser.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										121
									
								
								tests/arg-parser.spec.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,121 @@
 | 
			
		||||
import { Arg, ArgParser } from '../src';
 | 
			
		||||
 | 
			
		||||
describe('ArgParser', () => {
 | 
			
		||||
	const basicArgs: Arg[] = [
 | 
			
		||||
		{ name: 'input', desc: 'Input file' },
 | 
			
		||||
		{ name: 'output', desc: 'Output file', default: 'out.txt' },
 | 
			
		||||
		{ name: 'verbose', desc: 'Enable verbose mode', flags: ['-v', '--verbose'], default: false }
 | 
			
		||||
	];
 | 
			
		||||
 | 
			
		||||
	const commandArg = new ArgParser(
 | 
			
		||||
		'subcmd',
 | 
			
		||||
		'A sub command',
 | 
			
		||||
		[{ name: 'foo', desc: 'Foo argument', optional: false }]
 | 
			
		||||
	);
 | 
			
		||||
 | 
			
		||||
	describe('constructor', () => {
 | 
			
		||||
		it('should add commands and update examples', () => {
 | 
			
		||||
			const parser = new ArgParser('main', 'desc', [commandArg, ...basicArgs], ['custom-example']);
 | 
			
		||||
			expect(parser.commands[0].name).toBe('subcmd');
 | 
			
		||||
			expect(parser.examples.some(e => typeof e === 'string' && e.includes('[OPTIONS] COMMAND'))).toBe(true);
 | 
			
		||||
			expect(parser.examples).toEqual(expect.arrayContaining([
 | 
			
		||||
				'custom-example',
 | 
			
		||||
				expect.stringContaining('[OPTIONS]')
 | 
			
		||||
			]));
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('parse', () => {
 | 
			
		||||
		it('should parse args and flags', () => {
 | 
			
		||||
			const parser = new ArgParser('mycmd', 'desc', basicArgs);
 | 
			
		||||
			const result = parser.parse(['file1.txt', '-v']);
 | 
			
		||||
			expect(result.input).toBe('file1.txt');
 | 
			
		||||
			expect(result.output).toBe('out.txt');
 | 
			
		||||
			expect(result.verbose).toBe(true);
 | 
			
		||||
			expect(result._extra).toEqual([]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should handle missing required args and collect errors', () => {
 | 
			
		||||
			const parser = new ArgParser('mycmd', 'desc', basicArgs);
 | 
			
		||||
			const result = parser.parse([]);
 | 
			
		||||
			expect(result._error).toContain('Argument missing: INPUT');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should handle default values correctly', () => {
 | 
			
		||||
			const parser = new ArgParser('mycmd', 'desc', basicArgs);
 | 
			
		||||
			const result = parser.parse(['file1.txt']);
 | 
			
		||||
			expect(result.output).toBe('out.txt');
 | 
			
		||||
			expect(result.verbose).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should parse flags with value assignment', () => {
 | 
			
		||||
			const args: Arg[] = [
 | 
			
		||||
				{ name: 'mode', desc: 'Mode', flags: ['-m', '--mode'], default: 'defaultMode' }
 | 
			
		||||
			];
 | 
			
		||||
			const parser = new ArgParser('mycmd', 'desc', args);
 | 
			
		||||
			const result = parser.parse(['--mode=prod']);
 | 
			
		||||
			expect(result.mode).toBe('prod');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should support extras collection', () => {
 | 
			
		||||
			const args: Arg[] = [
 | 
			
		||||
				{ name: 'main', desc: 'main', extras: true }
 | 
			
		||||
			];
 | 
			
		||||
			const parser = new ArgParser('cmd', 'desc', args);
 | 
			
		||||
			const result = parser.parse(['a', 'b', 'c']);
 | 
			
		||||
			expect(result.main).toEqual(['a', 'b', 'c']);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should handle unknown flags and put them to extras', () => {
 | 
			
		||||
			const parser = new ArgParser('mycmd', 'desc', basicArgs);
 | 
			
		||||
			const result = parser.parse(['file.txt', 'test', '--unknown']);
 | 
			
		||||
			expect(result._extra).toContain('--unknown');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should handle subcommands and delegate parsing', () => {
 | 
			
		||||
			const mainParser = new ArgParser('main', 'desc', [commandArg]);
 | 
			
		||||
			const result = mainParser.parse(['subcmd', 'fooVal']);
 | 
			
		||||
			expect(result._command).toBe('subcmd');
 | 
			
		||||
			expect(result.foo).toBe('fooVal');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should parse combined short flags', () => {
 | 
			
		||||
			const args: Arg[] = [
 | 
			
		||||
				{ name: 'a', desc: 'Flag A', flags: ['-a'], default: false },
 | 
			
		||||
				{ name: 'b', desc: 'Flag B', flags: ['-b'], default: false }
 | 
			
		||||
			];
 | 
			
		||||
			const parser = new ArgParser('mycmd', 'desc', args);
 | 
			
		||||
			const result = parser.parse(['-ab']);
 | 
			
		||||
			expect(result.a).toBe(true);
 | 
			
		||||
			expect(result.b).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('help', () => {
 | 
			
		||||
		it('should generate help with options and args', () => {
 | 
			
		||||
			const parser = new ArgParser('mycmd', 'desc', basicArgs);
 | 
			
		||||
			const helpMsg = parser.help();
 | 
			
		||||
			expect(helpMsg).toContain('Input file');
 | 
			
		||||
			expect(helpMsg).toContain('Enable verbose mode');
 | 
			
		||||
			expect(helpMsg).toContain('-h, --help');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should generate help for a subcommand', () => {
 | 
			
		||||
			const mainParser = new ArgParser('main', 'desc', [commandArg]);
 | 
			
		||||
			const helpMsg = mainParser.help({ command: 'subcmd' });
 | 
			
		||||
			expect(helpMsg).toContain('Foo argument');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should throw error for non-existent command', () => {
 | 
			
		||||
			const mainParser = new ArgParser('main', 'desc', [commandArg]);
 | 
			
		||||
			expect(() => mainParser.help({ command: 'notreal' })).toThrow();
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should allow custom message override', () => {
 | 
			
		||||
			const parser = new ArgParser('mycmd', 'desc', basicArgs);
 | 
			
		||||
			const helpMsg = parser.help({ message: 'Custom!' });
 | 
			
		||||
			expect(helpMsg).toContain('Custom!');
 | 
			
		||||
			expect(helpMsg).not.toContain('desc');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
@@ -1,82 +1,85 @@
 | 
			
		||||
import {addUnique, caseInsensitiveSort, flattenArr, sortByProp} from '../src';
 | 
			
		||||
import {addUnique, arrayDiff, caseInsensitiveSort, findByProp, flattenArr, makeArray, makeUnique, sortByProp,} from '../src';
 | 
			
		||||
 | 
			
		||||
describe('Array Utilities', () => {
 | 
			
		||||
	describe('addUnique', () => {
 | 
			
		||||
		const arr = [1, 2];
 | 
			
		||||
 | 
			
		||||
		test('non-unique', () => {
 | 
			
		||||
			addUnique(arr, 1);
 | 
			
		||||
			expect(arr).toStrictEqual([1, 2]);
 | 
			
		||||
		it('does not add duplicate value', () => {
 | 
			
		||||
			const arr = [1, 2, 3];
 | 
			
		||||
			addUnique(arr, 2);
 | 
			
		||||
			expect(arr).toEqual([1, 2, 3]);
 | 
			
		||||
		});
 | 
			
		||||
		test('unique', () => {
 | 
			
		||||
		it('adds unique value', () => {
 | 
			
		||||
			const arr = [1, 2];
 | 
			
		||||
			addUnique(arr, 3);
 | 
			
		||||
			expect(arr).toStrictEqual([1, 2, 3]);
 | 
			
		||||
			expect(arr).toEqual([1, 2, 3]);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('arrayDiff', () => {
 | 
			
		||||
		it('returns unique elements present only in one array', () => {
 | 
			
		||||
			expect(arrayDiff([1, 2, 3], [3, 4, 5]).toSorted()).toEqual([1, 2, 4, 5]);
 | 
			
		||||
		});
 | 
			
		||||
		it('returns empty array if arrays have the same elements', () => {
 | 
			
		||||
			expect(arrayDiff([1, 2], [1, 2])).toEqual([]);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('caseInseFsitiveSort', () => {
 | 
			
		||||
		it('sorts objects by string property case-insensitively', () => {
 | 
			
		||||
			const arr = [{n: 'b'}, {n: 'A'}, {n: 'c'}];
 | 
			
		||||
			arr.sort(caseInsensitiveSort('n'));
 | 
			
		||||
			expect(arr.map(i => i.n)).toEqual(['A', 'b', 'c']);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('findByProp', () => {
 | 
			
		||||
		it('filters objects by property value', () => {
 | 
			
		||||
			const arr = [{name: 'foo'}, {name: 'bar'}];
 | 
			
		||||
			const found = arr.filter(findByProp('name', 'foo'));
 | 
			
		||||
			expect(found).toEqual([{name: 'foo'}]);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('flattenArr', () => {
 | 
			
		||||
		test('flat array', () => expect(flattenArr([1, 2])).toStrictEqual([1, 2]));
 | 
			
		||||
		test('2D array', () => expect(flattenArr([[1, 2], [3, 4]])).toStrictEqual([1, 2, 3, 4]));
 | 
			
		||||
		test('3D array', () => expect(flattenArr([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8]));
 | 
			
		||||
		test('mixed array', () => expect(flattenArr([1, 2, [3, 4], [[5, 6], [7, 8]]])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8]));
 | 
			
		||||
		it('flattens deeply nested arrays', () => {
 | 
			
		||||
			const arr = [1, [2, [3, [4]], 5], 6];
 | 
			
		||||
			expect(flattenArr(arr)).toEqual([1, 2, 3, 4, 5, 6]);
 | 
			
		||||
		});
 | 
			
		||||
		it('flattens flat array as-is', () => {
 | 
			
		||||
			expect(flattenArr([1, 2, 3])).toEqual([1, 2, 3]);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('sortByProp', () => {
 | 
			
		||||
		test('random letters', () => {
 | 
			
		||||
			let unsorted: any = Array(100).fill(null)
 | 
			
		||||
				.map(() => String.fromCharCode(Math.round(Math.random() * 25) + 97));
 | 
			
		||||
			const sorted = unsorted.sort((a: any, b: any) => {
 | 
			
		||||
				if(a > b) return 1;
 | 
			
		||||
				if(a < b) return -1;
 | 
			
		||||
				return 0;
 | 
			
		||||
			}).map((l: any) => ({a: l}));
 | 
			
		||||
			unsorted = unsorted.map((l: any) => ({a: l}));
 | 
			
		||||
			expect(unsorted.sort(sortByProp('a'))).toStrictEqual(sorted);
 | 
			
		||||
		it('sorts by numeric property', () => {
 | 
			
		||||
			const arr = [{a: 3}, {a: 1}, {a: 2}];
 | 
			
		||||
			arr.sort(sortByProp('a'));
 | 
			
		||||
			expect(arr.map(i => i.a)).toEqual([1, 2, 3]);
 | 
			
		||||
		});
 | 
			
		||||
		test('random letters reversed', () => {
 | 
			
		||||
			let unsorted: any = Array(100).fill(null)
 | 
			
		||||
				.map(() => String.fromCharCode(Math.round(Math.random() * 25) + 97));
 | 
			
		||||
			const sorted = unsorted.sort((a: any, b: any) => {
 | 
			
		||||
				if(a > b) return -1;
 | 
			
		||||
				if(a < b) return 1;
 | 
			
		||||
				return 0;
 | 
			
		||||
			}).map((n: any) => ({a: n}));
 | 
			
		||||
			unsorted = unsorted.map((n: any) => ({a: n}));
 | 
			
		||||
			expect(unsorted.sort(sortByProp('a', true))).toStrictEqual(sorted);
 | 
			
		||||
		});
 | 
			
		||||
		test('random numbers', () => {
 | 
			
		||||
			let unsorted: any = Array(100).fill(null).map(() => Math.round(Math.random() * 100));
 | 
			
		||||
			const sorted = unsorted.sort((a: any, b: any) => a - b).map((n: any) => ({a: n}));
 | 
			
		||||
			unsorted = unsorted.map((n: any) => ({a: n}));
 | 
			
		||||
			expect(unsorted.sort(sortByProp('a'))).toStrictEqual(sorted);
 | 
			
		||||
		});
 | 
			
		||||
		test('random numbers reversed', () => {
 | 
			
		||||
			let unsorted: any = Array(100).fill(null).map(() => Math.round(Math.random() * 100));
 | 
			
		||||
			const sorted = unsorted.sort((a: any, b: any) => b - a).map((n: any) => ({a: n}));
 | 
			
		||||
			unsorted = unsorted.map((n: any) => ({a: n}));
 | 
			
		||||
			expect(unsorted.sort(sortByProp('a', true))).toStrictEqual(sorted);
 | 
			
		||||
		it('sorts by string property reversed', () => {
 | 
			
		||||
			const arr = [{a: 'apple'}, {a: 'banana'}, {a: 'pear'}];
 | 
			
		||||
			arr.sort(sortByProp('a', true));
 | 
			
		||||
			expect(arr.map(i => i.a)).toEqual(['pear', 'banana', 'apple']);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('caseInsensitiveSort', () => {
 | 
			
		||||
		test('non-string property', () => {
 | 
			
		||||
			const unsorted: any = [{a: 'Apple', b: 123}, {a: 'Carrot', b: 789}, {a: 'banana', b: 456}];
 | 
			
		||||
			const sorted: any = unsorted.map((u: any) => ({...u}));
 | 
			
		||||
			expect(unsorted.sort(caseInsensitiveSort('b'))).toStrictEqual(sorted);
 | 
			
		||||
	describe('makeUnique', () => {
 | 
			
		||||
		it('removes duplicate primitives', () => {
 | 
			
		||||
			const arr = [1, 2, 2, 3, 1];
 | 
			
		||||
			expect(makeUnique(arr)).toEqual([1, 2, 3]);
 | 
			
		||||
		});
 | 
			
		||||
		test('simple strings', () => {
 | 
			
		||||
			const unsorted: any = [{a: 'Apple'}, {a: 'Carrot'}, {a: 'banana'}];
 | 
			
		||||
			const sorted: any = unsorted.sort((first: any, second: any) => {
 | 
			
		||||
				return first.a.toLowerCase().localeCompare(second.a.toLowerCase());
 | 
			
		||||
			}).map((u: any) => ({...u}));
 | 
			
		||||
			expect(unsorted.sort(caseInsensitiveSort('a'))).toStrictEqual(sorted);
 | 
			
		||||
		it('removes duplicate objects', () => {
 | 
			
		||||
			const obj = {a: 1};
 | 
			
		||||
			const arr = [obj, obj, {a: 1}];
 | 
			
		||||
			expect(makeUnique(arr)).toHaveLength(1);
 | 
			
		||||
		});
 | 
			
		||||
		test('alphanumeric strings', () => {
 | 
			
		||||
			const unsorted: any = [{a: '4pple'}, {a: 'Carrot'}, {a: 'b4n4n4'}];
 | 
			
		||||
			const sorted: any = unsorted.sort((first: any, second: any) => {
 | 
			
		||||
				return first.a.toLowerCase().localeCompare(second.a.toLowerCase());
 | 
			
		||||
			}).map((u: any) => ({...u}));
 | 
			
		||||
			expect(unsorted.sort(caseInsensitiveSort('a'))).toStrictEqual(sorted);
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('makeArray', () => {
 | 
			
		||||
		it('wraps non-arrays in array', () => {
 | 
			
		||||
			expect(makeArray(1)).toEqual([1]);
 | 
			
		||||
		});
 | 
			
		||||
		it('returns array as-is', () => {
 | 
			
		||||
			expect(makeArray([1, 2])).toEqual([1, 2]);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										148
									
								
								tests/aset.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										148
									
								
								tests/aset.spec.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,148 @@
 | 
			
		||||
import {ASet} from '../src';
 | 
			
		||||
 | 
			
		||||
describe('ASet', () => {
 | 
			
		||||
	describe('constructor', () => {
 | 
			
		||||
		it('should create a set with unique elements', () => {
 | 
			
		||||
			const set = new ASet([1, 2, 2, 3]);
 | 
			
		||||
			expect(set.size).toBe(3);
 | 
			
		||||
			expect(set.sort()).toEqual([1, 2, 3]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should create an empty set by default', () => {
 | 
			
		||||
			const set = new ASet();
 | 
			
		||||
			expect(set.size).toBe(0);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('add', () => {
 | 
			
		||||
		it('should add unique elements', () => {
 | 
			
		||||
			const set = new ASet([1]);
 | 
			
		||||
			set.add(2, 3, 1);
 | 
			
		||||
			expect(set.sort()).toEqual([1, 2, 3]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should return this', () => {
 | 
			
		||||
			const set = new ASet();
 | 
			
		||||
			expect(set.add(1)).toBe(set);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('clear', () => {
 | 
			
		||||
		it('should remove all elements', () => {
 | 
			
		||||
			const set = new ASet([1, 2]);
 | 
			
		||||
			set.clear();
 | 
			
		||||
			expect(set.size).toBe(0);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should return this', () => {
 | 
			
		||||
			const set = new ASet([1]);
 | 
			
		||||
			expect(set.clear()).toBe(set);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('delete', () => {
 | 
			
		||||
		it('should remove specified elements', () => {
 | 
			
		||||
			const set = new ASet([1, 2, 3]);
 | 
			
		||||
			set.delete(2, 4);
 | 
			
		||||
			expect(set.sort()).toEqual([1, 3]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should return this', () => {
 | 
			
		||||
			const set = new ASet([1]);
 | 
			
		||||
			expect(set.delete(1)).toBe(set);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('difference', () => {
 | 
			
		||||
		it('should return elements unique to this set', () => {
 | 
			
		||||
			const setA = new ASet([1, 2, 3]);
 | 
			
		||||
			const setB = new ASet([2, 4]);
 | 
			
		||||
			expect(setA.difference(setB).sort()).toEqual([1, 3]);
 | 
			
		||||
			expect(setB.difference(setA).sort()).toEqual([4]);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('has', () => {
 | 
			
		||||
		it('should check if element exists in set', () => {
 | 
			
		||||
			const set = new ASet([1, 2]);
 | 
			
		||||
			expect(set.has(1)).toBe(true);
 | 
			
		||||
			expect(set.has(99)).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('indexOf', () => {
 | 
			
		||||
		it('should return correct index for primitive and object', () => {
 | 
			
		||||
			const set = new ASet([{a: 1}, {b: 2}]);
 | 
			
		||||
			expect(set.indexOf({a: 1})).toBe(0);
 | 
			
		||||
			expect(set.indexOf(<any>{missing: 1})).toBe(-1);
 | 
			
		||||
 | 
			
		||||
			const numbers = new ASet([1, 2, 3]);
 | 
			
		||||
			expect(numbers.indexOf(2)).toBe(1);
 | 
			
		||||
			expect(numbers.indexOf(10)).toBe(-1);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('intersection', () => {
 | 
			
		||||
		it('should return elements common to both sets', () => {
 | 
			
		||||
			const setA = new ASet([1, 2, 3]);
 | 
			
		||||
			const setB = new ASet([2, 3, 4]);
 | 
			
		||||
			expect(setA.intersection(setB).sort()).toEqual([2, 3]);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('isDisjointFrom', () => {
 | 
			
		||||
		it('should check for no common elements', () => {
 | 
			
		||||
			const setA = new ASet([1, 2]);
 | 
			
		||||
			const setB = new ASet([3, 4]);
 | 
			
		||||
			const setC = new ASet([2, 3]);
 | 
			
		||||
			expect(setA.isDisjointFrom(setB)).toBe(true);
 | 
			
		||||
			expect(setA.isDisjointFrom(setC)).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('isSubsetOf', () => {
 | 
			
		||||
		it('should check if set is subset', () => {
 | 
			
		||||
			const a = new ASet([1, 2]);
 | 
			
		||||
			const b = new ASet([1, 2, 3]);
 | 
			
		||||
			expect(a.isSubsetOf(b)).toBe(true);
 | 
			
		||||
			expect(b.isSubsetOf(a)).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('isSuperset', () => {
 | 
			
		||||
		it('should check if set is superset', () => {
 | 
			
		||||
			const a = new ASet([1, 2, 3]);
 | 
			
		||||
			const b = new ASet([1, 2]);
 | 
			
		||||
			expect(a.isSuperset(b)).toBe(true);
 | 
			
		||||
			expect(b.isSuperset(a)).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('symmetricDifference', () => {
 | 
			
		||||
		it('should return elements only in one set (XOR)', () => {
 | 
			
		||||
			const a = new ASet([1, 2, 3]);
 | 
			
		||||
			const b = new ASet([3, 4]);
 | 
			
		||||
			expect(a.symmetricDifference(b).sort()).toEqual([1, 2, 4]);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('union', () => {
 | 
			
		||||
		it('should return union of two sets', () => {
 | 
			
		||||
			const a = new ASet([1, 2]);
 | 
			
		||||
			const b = new ASet([2, 3]);
 | 
			
		||||
			expect(a.union(b).sort()).toEqual([1, 2, 3]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should work with arrays', () => {
 | 
			
		||||
			const a = new ASet([1]);
 | 
			
		||||
			expect(a.union([2, 1, 3]).sort()).toEqual([1, 2, 3]);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('size', () => {
 | 
			
		||||
		it('should return number of unique elements', () => {
 | 
			
		||||
			const set = new ASet([1, 1, 2, 3, 3]);
 | 
			
		||||
			expect(set.size).toBe(3);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
							
								
								
									
										194
									
								
								tests/cache.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										194
									
								
								tests/cache.spec.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,194 @@
 | 
			
		||||
import { Cache } from '../src';
 | 
			
		||||
 | 
			
		||||
describe('Cache', () => {
 | 
			
		||||
	type TestItem = { id: string; value: string };
 | 
			
		||||
 | 
			
		||||
	let cache: Cache<string | symbol, TestItem>;
 | 
			
		||||
	let storageMock: Storage;
 | 
			
		||||
	let storageGetItemSpy: jest.SpyInstance;
 | 
			
		||||
	let storageSetItemSpy: jest.SpyInstance;
 | 
			
		||||
 | 
			
		||||
	beforeEach(() => {
 | 
			
		||||
		jest.useFakeTimers();
 | 
			
		||||
 | 
			
		||||
		storageMock = {
 | 
			
		||||
			constructor: { name: 'Storage' as any },
 | 
			
		||||
			getItem: jest.fn(),
 | 
			
		||||
			setItem: jest.fn(),
 | 
			
		||||
			removeItem: jest.fn(),
 | 
			
		||||
			clear: jest.fn(),
 | 
			
		||||
			key: jest.fn(),
 | 
			
		||||
			length: 0,
 | 
			
		||||
		};
 | 
			
		||||
 | 
			
		||||
		// Spies
 | 
			
		||||
		storageGetItemSpy = jest.spyOn(storageMock, 'getItem');
 | 
			
		||||
		storageSetItemSpy = jest.spyOn(storageMock, 'setItem');
 | 
			
		||||
 | 
			
		||||
		cache = new Cache<string | symbol, TestItem>('id', {
 | 
			
		||||
			persistentStorage: { storage: storageMock, key: 'cache' },
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		jest.clearAllMocks();
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	afterEach(() => {
 | 
			
		||||
		jest.useRealTimers();
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('adds and gets an item', () => {
 | 
			
		||||
		const item = { id: '1', value: 'a' };
 | 
			
		||||
		cache.add(item);
 | 
			
		||||
		expect(cache.get('1')).toEqual(item);
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('skips expired items by default but fetches if requested', () => {
 | 
			
		||||
		const item = { id: '2', value: 'b' };
 | 
			
		||||
		cache.set('2', item);
 | 
			
		||||
		cache.options.expiryPolicy = 'keep';
 | 
			
		||||
		cache.expire('2');
 | 
			
		||||
		expect(cache.get('2')).toBeNull();
 | 
			
		||||
		expect(cache.get('2', true)).toEqual({ ...item, _expired: true });
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('supports property access and setting via Proxy', () => {
 | 
			
		||||
		(cache as any)['3'] = { id: '3', value: 'c' };
 | 
			
		||||
		expect((cache as any)['3']).toEqual({ id: '3', value: 'c' });
 | 
			
		||||
		expect(cache.get('3')).toEqual({ id: '3', value: 'c' });
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('removes an item and persists', () => {
 | 
			
		||||
		cache.add({ id: '4', value: 'd' });
 | 
			
		||||
		cache.delete('4');
 | 
			
		||||
		expect(cache.get('4')).toBeNull();
 | 
			
		||||
		expect(storageSetItemSpy).toHaveBeenCalled();
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('clears the cache & cancels TTL timers', () => {
 | 
			
		||||
		cache.set('1', { id: '1', value: 'x' }, 1);
 | 
			
		||||
		cache.clear();
 | 
			
		||||
		// Even after timers advance, nothing should appear or throw
 | 
			
		||||
		jest.advanceTimersByTime(1500);
 | 
			
		||||
		expect(cache.get('1', true)).toBeNull();
 | 
			
		||||
		expect(cache.complete).toBe(false);
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('bulk adds, marks complete', () => {
 | 
			
		||||
		const items = [
 | 
			
		||||
			{ id: 'a', value: '1' },
 | 
			
		||||
			{ id: 'b', value: '2' },
 | 
			
		||||
		];
 | 
			
		||||
		cache.addAll(items);
 | 
			
		||||
		expect(cache.all().length).toBe(2);
 | 
			
		||||
		expect(cache.complete).toBe(true);
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('returns correct keys, entries, map, and values()', () => {
 | 
			
		||||
		cache.add({ id: 'x', value: 'foo' });
 | 
			
		||||
		cache.add({ id: 'y', value: 'bar' });
 | 
			
		||||
		expect(cache.keys().sort()).toEqual(['x', 'y']);
 | 
			
		||||
		expect(cache.entries().map(e => e[0]).sort()).toEqual(['x', 'y']);
 | 
			
		||||
		const m = cache.map();
 | 
			
		||||
		expect(Object.keys(m)).toEqual(expect.arrayContaining(['x', 'y']));
 | 
			
		||||
		expect(m['x'].value).toBe('foo');
 | 
			
		||||
		// CHANGE: values() was a snapshot field before; now it’s a method
 | 
			
		||||
		expect(cache.values().map(v => v.id).sort()).toEqual(['x', 'y']);
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('persists and restores from storage', () => {
 | 
			
		||||
		(storageMock.getItem as jest.Mock).mockReturnValueOnce(
 | 
			
		||||
			JSON.stringify({ z: { id: 'z', value: 'from-storage' } }),
 | 
			
		||||
		);
 | 
			
		||||
		const c = new Cache<string, TestItem>('id', {
 | 
			
		||||
			persistentStorage: { storage: storageMock, key: 'cache' },
 | 
			
		||||
		});
 | 
			
		||||
		expect(c.get('z')).toEqual({ id: 'z', value: 'from-storage' });
 | 
			
		||||
		// ensure it used the right storage key
 | 
			
		||||
		expect(storageGetItemSpy).toHaveBeenCalledWith('cache');
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('expiryPolicy "delete" removes expired items completely', () => {
 | 
			
		||||
		cache.options.expiryPolicy = 'delete';
 | 
			
		||||
		cache.add({ id: 'del1', value: 'gone' });
 | 
			
		||||
		cache.expire('del1');
 | 
			
		||||
		expect(cache.get('del1', true)).toBeNull();
 | 
			
		||||
		expect(cache.get('del1')).toBeNull();
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('expiryPolicy "keep" marks as expired but does not delete', () => {
 | 
			
		||||
		cache.options.expiryPolicy = 'keep';
 | 
			
		||||
		cache.add({ id: 'keep1', value: 'kept' });
 | 
			
		||||
		cache.expire('keep1');
 | 
			
		||||
		expect(cache.get('keep1')).toBeNull();
 | 
			
		||||
		const val = cache.get('keep1', true);
 | 
			
		||||
		expect(val && val._expired).toBe(true);
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('TTL expiration deletes by default', () => {
 | 
			
		||||
		cache.add({ id: 'ttl1', value: 'tick' }, 1);
 | 
			
		||||
		jest.advanceTimersByTime(999);
 | 
			
		||||
		expect(cache.get('ttl1')).toEqual({ id: 'ttl1', value: 'tick' });
 | 
			
		||||
		jest.advanceTimersByTime(2);
 | 
			
		||||
		expect(cache.get('ttl1')).toBeNull();
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('TTL overwrite cancels previous timer', () => {
 | 
			
		||||
		cache.add({ id: 'ow', value: 'v1' }, 1);
 | 
			
		||||
		jest.advanceTimersByTime(500);
 | 
			
		||||
		cache.add({ id: 'ow', value: 'v2' }, 1);
 | 
			
		||||
		jest.advanceTimersByTime(600);
 | 
			
		||||
		expect(cache.get('ow')).toEqual({ id: 'ow', value: 'v2' });
 | 
			
		||||
		jest.advanceTimersByTime(500);
 | 
			
		||||
		expect(cache.get('ow')).toBeNull();
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('find() returns first match respecting expired flag', () => {
 | 
			
		||||
		cache.options.expiryPolicy = 'keep';
 | 
			
		||||
		cache.add({ id: 'f1', value: 'hello' });
 | 
			
		||||
		cache.add({ id: 'f2', value: 'world' });
 | 
			
		||||
		cache.expire('f1');
 | 
			
		||||
		expect(cache.find({ value: 'hello' })).toBeUndefined();
 | 
			
		||||
		expect(cache.find({ value: 'hello' }, true)).toEqual({ id: 'f1', value: 'hello', _expired: true });
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('symbol keys are supported when using set/get directly', () => {
 | 
			
		||||
		const s = Symbol('k');
 | 
			
		||||
		// NOTE: can’t use add() without a primary key; set works fine
 | 
			
		||||
		cache.set(s, { id: 'sym', value: 'ok' });
 | 
			
		||||
		expect(cache.get(s as any)).toEqual({ id: 'sym', value: 'ok' });
 | 
			
		||||
		// ensure keys() includes the symbol
 | 
			
		||||
		const keys = cache.keys(true);
 | 
			
		||||
		expect(keys.includes(s as any)).toBe(true);
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('LRU: evicts least-recently-used when over capacity', () => {
 | 
			
		||||
		const lruCache = new Cache<string, TestItem>('id', {
 | 
			
		||||
			sizeLimit: 2,
 | 
			
		||||
			persistentStorage: { storage: storageMock, key: 'cache' },
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		lruCache.add({ id: 'A', value: '1' });
 | 
			
		||||
		lruCache.add({ id: 'B', value: '2' });
 | 
			
		||||
		// touch A to make it MRU
 | 
			
		||||
		expect(lruCache.get('A')).toEqual({ id: 'A', value: '1' });
 | 
			
		||||
		// add C → should evict least-recently-used (B)
 | 
			
		||||
		lruCache.add({ id: 'C', value: '3' });
 | 
			
		||||
 | 
			
		||||
		expect(lruCache.get('B')).toBeNull();
 | 
			
		||||
		expect(lruCache.get('A')).toEqual({ id: 'A', value: '1' });
 | 
			
		||||
		expect(lruCache.get('C')).toEqual({ id: 'C', value: '3' });
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('delete() removes from LRU and cancels timer', () => {
 | 
			
		||||
		const lruCache = new Cache<string, TestItem>('id', { sizeLimit: 2 });
 | 
			
		||||
		lruCache.set('A', { id: 'A', value: '1' }, 1);
 | 
			
		||||
		lruCache.delete('A');
 | 
			
		||||
		jest.advanceTimersByTime(1200);
 | 
			
		||||
		expect(lruCache.get('A', true)).toBeNull();
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('throws when adding item missing the primary key', () => {
 | 
			
		||||
		const c = new Cache<'id', any>('id');
 | 
			
		||||
		expect(() => c.add({ nope: 'missing' } as any)).toThrow(/Doesn't exist/);
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
							
								
								
									
										40
									
								
								tests/color.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										40
									
								
								tests/color.spec.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,40 @@
 | 
			
		||||
import {contrast} from '../src';
 | 
			
		||||
 | 
			
		||||
describe('contrast', () => {
 | 
			
		||||
	it('should return "black" for white background', () => {
 | 
			
		||||
		expect(contrast('ffffff')).toBe('black');
 | 
			
		||||
		expect(contrast('#ffffff'.replace('#', ''))).toBe('black'); // simulate trimmed hash
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('should return "white" for black background', () => {
 | 
			
		||||
		expect(contrast('000000')).toBe('white');
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('should return "white" for a dark color', () => {
 | 
			
		||||
		expect(contrast('123456')).toBe('white');
 | 
			
		||||
		expect(contrast('222222')).toBe('white');
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('should return "black" for a light color', () => {
 | 
			
		||||
		expect(contrast('ffff99')).toBe('black');
 | 
			
		||||
		expect(contrast('cccccc')).toBe('black');
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('should handle short hex color codes (3 chars)', () => {
 | 
			
		||||
		expect(contrast('fff')).toBe('black');
 | 
			
		||||
		expect(contrast('000')).toBe('white');
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('should return "black" for invalid input', () => {
 | 
			
		||||
		expect(contrast('')).toBe('black');
 | 
			
		||||
		expect(contrast('zzzzzz')).toBe('black');
 | 
			
		||||
		expect(contrast('not-a-color')).toBe('black');
 | 
			
		||||
		expect(contrast(undefined as unknown as string)).toBe('black');
 | 
			
		||||
		expect(contrast(null as unknown as string)).toBe('black');
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('should handle hex codes with hash prefix if removed', () => {
 | 
			
		||||
		expect(contrast('ededed')).toBe('black');
 | 
			
		||||
		expect(contrast('343434')).toBe('white');
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
							
								
								
									
										90
									
								
								tests/csv.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										90
									
								
								tests/csv.spec.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,90 @@
 | 
			
		||||
import {fromCsv, toCsv} from '../src';
 | 
			
		||||
 | 
			
		||||
describe('CSV Utilities', () => {
 | 
			
		||||
	describe('fromCsv', () => {
 | 
			
		||||
		it('parses CSV with headers', () => {
 | 
			
		||||
			const input = `name,age,city
 | 
			
		||||
John,30,New York
 | 
			
		||||
Jane,25,Los Angeles`;
 | 
			
		||||
			const expected = [
 | 
			
		||||
				{name: 'John', age: '30', city: 'New York'},
 | 
			
		||||
				{name: 'Jane', age: '25', city: 'Los Angeles'},
 | 
			
		||||
			];
 | 
			
		||||
			expect(fromCsv(input)).toEqual(expected);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('parses CSV without headers', () => {
 | 
			
		||||
			const input = `apple,red,1
 | 
			
		||||
banana,yellow,2`;
 | 
			
		||||
			const expected = [
 | 
			
		||||
				{A: 'apple', B: 'red', C: '1'},
 | 
			
		||||
				{A: 'banana', B: 'yellow', C: '2'},
 | 
			
		||||
			];
 | 
			
		||||
			expect(fromCsv(input, false)).toEqual(expected);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles quoted fields and commas', () => {
 | 
			
		||||
			const input = `name,description
 | 
			
		||||
"Widget, Large","A large, useful widget"
 | 
			
		||||
Gadget,"A ""versatile"" gadget"`;
 | 
			
		||||
			const expected = [
 | 
			
		||||
				{name: 'Widget, Large', description: 'A large, useful widget'},
 | 
			
		||||
				{name: 'Gadget', description: 'A "versatile" gadget'},
 | 
			
		||||
			];
 | 
			
		||||
			expect(fromCsv(input)).toEqual(expected);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles empty fields', () => {
 | 
			
		||||
			const input = `id,name,score
 | 
			
		||||
1,Tom,97
 | 
			
		||||
2,,89
 | 
			
		||||
3,Alice,`;
 | 
			
		||||
			const expected = [
 | 
			
		||||
				{id: '1', name: 'Tom', score: '97'},
 | 
			
		||||
				{id: '2', name: '', score: '89'},
 | 
			
		||||
				{id: '3', name: 'Alice', score: ''},
 | 
			
		||||
			];
 | 
			
		||||
			expect(fromCsv(input)).toEqual(expected);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('toCsv', () => {
 | 
			
		||||
		it('converts array of objects to CSV', () => {
 | 
			
		||||
			const arr = [
 | 
			
		||||
				{name: 'John', age: 30, city: 'New York'},
 | 
			
		||||
				{name: 'Jane', age: 25, city: 'Los Angeles'},
 | 
			
		||||
			];
 | 
			
		||||
			const csv = toCsv(arr);
 | 
			
		||||
			expect(csv).toContain('name,age,city');
 | 
			
		||||
			expect(csv).toContain('John,30,New York');
 | 
			
		||||
			expect(csv).toContain('Jane,25,Los Angeles');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('quotes fields with commas and quotes', () => {
 | 
			
		||||
			const arr = [
 | 
			
		||||
				{val: 'Comma, included', remark: 'needs, quotes'},
 | 
			
		||||
				{val: 'Quote "double"', remark: 'embedded "quotes"'},
 | 
			
		||||
			];
 | 
			
		||||
			const csv = toCsv(arr);
 | 
			
		||||
			expect(csv).toContain('"Comma, included","needs, quotes"');
 | 
			
		||||
			expect(csv).toContain('"Quote ""double""","embedded ""quotes"""');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles nested objects when flatten = true', () => {
 | 
			
		||||
			const arr = [
 | 
			
		||||
				{id: 1, info: {name: 'Alice', age: 20}},
 | 
			
		||||
				{id: 2, info: {name: 'Bob', age: 22}}
 | 
			
		||||
			];
 | 
			
		||||
			const csv = toCsv(arr, true);
 | 
			
		||||
			expect(csv).toMatch(/id,info\.name,info\.age/);
 | 
			
		||||
			expect(csv).toMatch(/1,Alice,20/);
 | 
			
		||||
			expect(csv).toMatch(/2,Bob,22/);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles objects with array fields', () => {
 | 
			
		||||
			const arr = [{name: 'Joe', tags: ['a', 'b']}];
 | 
			
		||||
			const csv = toCsv(arr);
 | 
			
		||||
			expect(csv).toContain('Joe,"[""a"",""b""]"');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
							
								
								
									
										118
									
								
								tests/emitter.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										118
									
								
								tests/emitter.spec.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,118 @@
 | 
			
		||||
import {TypedEmitter} from '../src';
 | 
			
		||||
 | 
			
		||||
describe('TypedEmitter', () => {
 | 
			
		||||
	describe('Instance', () => {
 | 
			
		||||
		type Events = {
 | 
			
		||||
			foo: (data: string) => void;
 | 
			
		||||
			bar: (x: number, y: number) => void;
 | 
			
		||||
			'*': (event: string, ...args: any[]) => void;
 | 
			
		||||
		};
 | 
			
		||||
		let emitter: TypedEmitter<Events>;
 | 
			
		||||
 | 
			
		||||
		beforeEach(() => {
 | 
			
		||||
			emitter = new TypedEmitter<Events>();
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('calls the correct listener on emit', () => {
 | 
			
		||||
			const fooHandler = jest.fn();
 | 
			
		||||
			emitter.on('foo', fooHandler);
 | 
			
		||||
 | 
			
		||||
			emitter.emit('foo', 'hello');
 | 
			
		||||
			expect(fooHandler).toHaveBeenCalledWith('hello');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('does NOT call listener after off', () => {
 | 
			
		||||
			const fooHandler = jest.fn();
 | 
			
		||||
			emitter.on('foo', fooHandler);
 | 
			
		||||
			emitter.off('foo', fooHandler);
 | 
			
		||||
			emitter.emit('foo', 'test');
 | 
			
		||||
			expect(fooHandler).not.toHaveBeenCalled();
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('returns unsubscribe function that removes handler', () => {
 | 
			
		||||
			const handler = jest.fn();
 | 
			
		||||
			const unsubscribe = emitter.on('foo', handler);
 | 
			
		||||
			unsubscribe();
 | 
			
		||||
			emitter.emit('foo', 'x');
 | 
			
		||||
			expect(handler).not.toHaveBeenCalled();
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('calls wildcard listener for all events', () => {
 | 
			
		||||
			const wildcard = jest.fn();
 | 
			
		||||
			emitter.on('*', wildcard);
 | 
			
		||||
 | 
			
		||||
			emitter.emit('foo', 'data');
 | 
			
		||||
			emitter.emit('bar', 1, 2);
 | 
			
		||||
 | 
			
		||||
			expect(wildcard).toHaveBeenCalledWith('foo', 'data');
 | 
			
		||||
			expect(wildcard).toHaveBeenCalledWith('bar', 1, 2);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('once() resolves with argument and auto-unsubscribes', async () => {
 | 
			
		||||
			const p = emitter.once('foo');
 | 
			
		||||
			emitter.emit('foo', 'only-once');
 | 
			
		||||
			expect(await p).toBe('only-once');
 | 
			
		||||
 | 
			
		||||
			// no more handlers
 | 
			
		||||
			const cb = jest.fn();
 | 
			
		||||
			emitter.on('foo', cb);
 | 
			
		||||
			emitter.emit('foo', 'again');
 | 
			
		||||
			expect(cb).toHaveBeenCalledWith('again');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('once() calls optional listener and Promise resolves', async () => {
 | 
			
		||||
			const listener = jest.fn();
 | 
			
		||||
			const oncePromise = emitter.once('bar', listener);
 | 
			
		||||
 | 
			
		||||
			emitter.emit('bar', 1, 2);
 | 
			
		||||
 | 
			
		||||
			expect(listener).toHaveBeenCalledWith(1, 2);
 | 
			
		||||
			expect(await oncePromise).toEqual([1, 2]);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('Static', () => {
 | 
			
		||||
		beforeEach(() => {
 | 
			
		||||
			// Clear static listeners between tests
 | 
			
		||||
			(TypedEmitter as any).listeners = {};
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('calls static listeners with emit', () => {
 | 
			
		||||
			const spy = jest.fn();
 | 
			
		||||
			TypedEmitter.on('event', spy);
 | 
			
		||||
 | 
			
		||||
			TypedEmitter.emit('event', 1, 'a');
 | 
			
		||||
			expect(spy).toHaveBeenCalledWith(1, 'a');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('wildcard static listeners receive all event types', () => {
 | 
			
		||||
			const spy = jest.fn();
 | 
			
		||||
			TypedEmitter.on('*', spy);
 | 
			
		||||
 | 
			
		||||
			TypedEmitter.emit('xy', 123);
 | 
			
		||||
			expect(spy).toHaveBeenCalledWith('xy', 123);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('only calls listener once with once()', async () => {
 | 
			
		||||
			const handler = jest.fn();
 | 
			
		||||
			const p = TypedEmitter.once('ping', handler);
 | 
			
		||||
 | 
			
		||||
			TypedEmitter.emit('ping', 'pong');
 | 
			
		||||
 | 
			
		||||
			expect(handler).toHaveBeenCalledWith('pong');
 | 
			
		||||
			await expect(p).resolves.toBe('pong');
 | 
			
		||||
 | 
			
		||||
			handler.mockClear();
 | 
			
		||||
			TypedEmitter.emit('ping', 'other');
 | 
			
		||||
			expect(handler).not.toHaveBeenCalled();
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('removes static listener with off', () => {
 | 
			
		||||
			const h = jest.fn();
 | 
			
		||||
			TypedEmitter.on('offevent', h);
 | 
			
		||||
			TypedEmitter.off('offevent', h);
 | 
			
		||||
			TypedEmitter.emit('offevent', 42);
 | 
			
		||||
			expect(h).not.toHaveBeenCalled();
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
							
								
								
									
										112
									
								
								tests/errors.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										112
									
								
								tests/errors.spec.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,112 @@
 | 
			
		||||
import {
 | 
			
		||||
	CustomError,
 | 
			
		||||
	BadRequestError,
 | 
			
		||||
	UnauthorizedError,
 | 
			
		||||
	PaymentRequiredError,
 | 
			
		||||
	ForbiddenError,
 | 
			
		||||
	NotFoundError,
 | 
			
		||||
	MethodNotAllowedError,
 | 
			
		||||
	NotAcceptableError,
 | 
			
		||||
	InternalServerError,
 | 
			
		||||
	NotImplementedError,
 | 
			
		||||
	BadGatewayError,
 | 
			
		||||
	ServiceUnavailableError,
 | 
			
		||||
	GatewayTimeoutError,
 | 
			
		||||
	errorFromCode
 | 
			
		||||
} from '../src';
 | 
			
		||||
 | 
			
		||||
describe('CustomError Hierarchy', () => {
 | 
			
		||||
	it('CustomError basic properties and code getter/setter', () => {
 | 
			
		||||
		const err = new CustomError('Test', 501);
 | 
			
		||||
		expect(err.message).toBe('Test');
 | 
			
		||||
		expect(err.code).toBe(501);
 | 
			
		||||
		err.code = 404;
 | 
			
		||||
		expect(err.code).toBe(404);
 | 
			
		||||
		// default code if not provided
 | 
			
		||||
		const noCodeError = new CustomError('No code');
 | 
			
		||||
		expect(noCodeError.code).toBe(500);
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('CustomError static from method copies properties and stack', () => {
 | 
			
		||||
		const orig: any = new Error('oops');
 | 
			
		||||
		orig.code = 402;
 | 
			
		||||
		orig.stack = 'FAKE_STACK';
 | 
			
		||||
		const custom = CustomError.from(orig);
 | 
			
		||||
		expect(custom).toBeInstanceOf(CustomError);
 | 
			
		||||
		expect(custom.message).toBe('oops');
 | 
			
		||||
		expect(custom.code).toBe(500);
 | 
			
		||||
		expect(custom.stack).toBe('FAKE_STACK');
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('CustomError instanceof works', () => {
 | 
			
		||||
		expect(CustomError.instanceof(new CustomError())).toBe(true);
 | 
			
		||||
		expect(CustomError.instanceof(new Error())).toBe(false);
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	it('CustomError toString returns message', () => {
 | 
			
		||||
		const err = new CustomError('foo');
 | 
			
		||||
		expect(err.toString()).toBe('foo');
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	const cases = [
 | 
			
		||||
		[BadRequestError, 400, 'Bad Request'],
 | 
			
		||||
		[UnauthorizedError, 401, 'Unauthorized'],
 | 
			
		||||
		[PaymentRequiredError, 402, 'Payment Required'],
 | 
			
		||||
		[ForbiddenError, 403, 'Forbidden'],
 | 
			
		||||
		[NotFoundError, 404, 'Not Found'],
 | 
			
		||||
		[MethodNotAllowedError, 405, 'Method Not Allowed'],
 | 
			
		||||
		[NotAcceptableError, 406, 'Not Acceptable'],
 | 
			
		||||
		[InternalServerError, 500, 'Internal Server Error'],
 | 
			
		||||
		[NotImplementedError, 501, 'Not Implemented'],
 | 
			
		||||
		[BadGatewayError, 502, 'Bad Gateway'],
 | 
			
		||||
		[ServiceUnavailableError, 503, 'Service Unavailable'],
 | 
			
		||||
		[GatewayTimeoutError, 504, 'Gateway Timeout'],
 | 
			
		||||
	] as const;
 | 
			
		||||
 | 
			
		||||
	describe.each(cases)(
 | 
			
		||||
		'%p (code=%i, defaultMessage="%s")',
 | 
			
		||||
		(ErrClass, code, defMsg) => {
 | 
			
		||||
			it('has static code, default message, and instanceof', () => {
 | 
			
		||||
				const e = new ErrClass();
 | 
			
		||||
				expect(e).toBeInstanceOf(ErrClass);
 | 
			
		||||
				expect(e.code).toBe(code);
 | 
			
		||||
				expect(e.message).toBe(defMsg);
 | 
			
		||||
				expect(ErrClass.instanceof(e)).toBe(true);
 | 
			
		||||
			});
 | 
			
		||||
 | 
			
		||||
			it('supports custom messages', () => {
 | 
			
		||||
				const msg = 'Custom msg';
 | 
			
		||||
				const e = new ErrClass(msg);
 | 
			
		||||
				expect(e.message).toBe(msg);
 | 
			
		||||
			});
 | 
			
		||||
		}
 | 
			
		||||
	);
 | 
			
		||||
 | 
			
		||||
	describe('errorFromCode', () => {
 | 
			
		||||
		it.each(cases)(
 | 
			
		||||
			'returns %p for code %i',
 | 
			
		||||
			(ErrClass, code, defMsg) => {
 | 
			
		||||
				const err = errorFromCode(code);
 | 
			
		||||
				expect(err).toBeInstanceOf(ErrClass);
 | 
			
		||||
				expect(err.code).toBe(code);
 | 
			
		||||
				expect(err.message).toBe(defMsg);
 | 
			
		||||
			}
 | 
			
		||||
		);
 | 
			
		||||
		it('overrides message if provided', () => {
 | 
			
		||||
			const err = errorFromCode(404, 'Nope');
 | 
			
		||||
			expect(err).toBeInstanceOf(NotFoundError);
 | 
			
		||||
			expect(err.message).toBe('Nope');
 | 
			
		||||
		});
 | 
			
		||||
		it('fallbacks to CustomError for unknown codes', () => {
 | 
			
		||||
			const err = errorFromCode(999, 'xyz');
 | 
			
		||||
			expect(err).toBeInstanceOf(CustomError);
 | 
			
		||||
			expect(err.code).toBe(999);
 | 
			
		||||
			expect(err.message).toBe('xyz');
 | 
			
		||||
		});
 | 
			
		||||
		it('handles missing message gracefully', () => {
 | 
			
		||||
			const err = errorFromCode(555);
 | 
			
		||||
			expect(err).toBeInstanceOf(CustomError);
 | 
			
		||||
			expect(err.code).toBe(555);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
							
								
								
									
										33
									
								
								tests/json.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										33
									
								
								tests/json.spec.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,33 @@
 | 
			
		||||
import {JSONAttemptParse, JSONSanitize, JSONSerialize} from '../src';
 | 
			
		||||
 | 
			
		||||
describe('JSON Utilities', () => {
 | 
			
		||||
	describe('JSONAttemptParse', () => {
 | 
			
		||||
		it('parses valid JSON', () => {
 | 
			
		||||
			expect(JSONAttemptParse('{"a":1}')).toEqual({ a: 1 });
 | 
			
		||||
		});
 | 
			
		||||
		it('returns original string on error', () => {
 | 
			
		||||
			expect(JSONAttemptParse('not json')).toBe('not json');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('JSONSerialize', () => {
 | 
			
		||||
		it('serializes objects', () => {
 | 
			
		||||
			expect(JSONSerialize({ a: 1 })).toBe(JSON.stringify({ a: 1 }));
 | 
			
		||||
		});
 | 
			
		||||
		it('leaves primitives as is', () => {
 | 
			
		||||
			expect(JSONSerialize('test')).toBe('test');
 | 
			
		||||
			expect(JSONSerialize(123)).toBe(123);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('JSONSanitize', () => {
 | 
			
		||||
		it('stringifies objects', () => {
 | 
			
		||||
			expect(JSONSanitize({ a: 1 })).toBe(JSON.stringify({ a: 1 }));
 | 
			
		||||
		});
 | 
			
		||||
		it('does not throw on circular refs', () => {
 | 
			
		||||
			const obj: any = {};
 | 
			
		||||
			obj.self = obj;
 | 
			
		||||
			expect(() => JSONSanitize(obj)).not.toThrow();
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
							
								
								
									
										61
									
								
								tests/jwt.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										61
									
								
								tests/jwt.spec.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,61 @@
 | 
			
		||||
import { createJwt, decodeJwt } from '../src';
 | 
			
		||||
 | 
			
		||||
describe('JWT Utilities', () => {
 | 
			
		||||
	describe('createJwt', () => {
 | 
			
		||||
		it('should create a valid JWT string with default signature', () => {
 | 
			
		||||
			const payload = { foo: 'bar', num: 123 };
 | 
			
		||||
			const jwt = createJwt(payload);
 | 
			
		||||
			const parts = jwt.split('.');
 | 
			
		||||
			expect(parts).toHaveLength(3);
 | 
			
		||||
 | 
			
		||||
			// Header should decode to HS256 + JWT
 | 
			
		||||
			const header = JSON.parse(Buffer.from(parts[0], 'base64url').toString());
 | 
			
		||||
			expect(header).toEqual({ alg: "HS256", typ: "JWT" });
 | 
			
		||||
 | 
			
		||||
			// Body should match the payload
 | 
			
		||||
			const body = JSON.parse(Buffer.from(parts[1], 'base64url').toString());
 | 
			
		||||
			expect(body).toEqual(payload);
 | 
			
		||||
 | 
			
		||||
			// Signature should be 'unsigned'
 | 
			
		||||
			expect(parts[2]).toBe('unsigned');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should allow custom signature', () => {
 | 
			
		||||
			const jwt = createJwt({ test: 1 }, 'mysignature');
 | 
			
		||||
			expect(jwt.split('.')[2]).toBe('mysignature');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('decodeJwt', () => {
 | 
			
		||||
		it('should decode a JWT payload', () => {
 | 
			
		||||
			const payload = { user: 'alice', age: 30 };
 | 
			
		||||
			const jwt = createJwt(payload);
 | 
			
		||||
			const decoded = decodeJwt<typeof payload>(jwt);
 | 
			
		||||
			expect(decoded).toEqual(payload);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should decode payload with different types', () => {
 | 
			
		||||
			const payload = { arr: [1,2,3], flag: true, val: null };
 | 
			
		||||
			const jwt = createJwt(payload);
 | 
			
		||||
			const decoded = decodeJwt<typeof payload>(jwt);
 | 
			
		||||
			expect(decoded).toEqual(payload);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should throw or return null for malformed tokens', () => {
 | 
			
		||||
			// Not enough parts
 | 
			
		||||
			expect(() => decodeJwt('foo.bar')).toThrow();
 | 
			
		||||
			// Bad base64
 | 
			
		||||
			expect(() => decodeJwt('a.b@d.c')).toThrow();
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should decode JWT even if signature is missing', () => {
 | 
			
		||||
			// Two-part JWT (not standard, but let's see what happens)
 | 
			
		||||
			const payload = { ok: true };
 | 
			
		||||
			const header = Buffer.from(JSON.stringify({ alg: "HS256", typ: "JWT" })).toString('base64url');
 | 
			
		||||
			const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
 | 
			
		||||
			const jwt = `${header}.${body}`;
 | 
			
		||||
			const decoded = decodeJwt<typeof payload>(jwt + '.');
 | 
			
		||||
			expect(decoded).toEqual(payload);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
							
								
								
									
										51
									
								
								tests/math.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										51
									
								
								tests/math.spec.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,51 @@
 | 
			
		||||
import { dec2Frac, fracToDec } from '../src';
 | 
			
		||||
 | 
			
		||||
describe('Math Utilities', () => {
 | 
			
		||||
	describe('dec2Frac', () => {
 | 
			
		||||
		it('should convert decimal to fraction with whole and remainder', () => {
 | 
			
		||||
			expect(dec2Frac(1.25)).toBe('1 1/4');
 | 
			
		||||
			expect(dec2Frac(2.5)).toBe('2 1/2');
 | 
			
		||||
			expect(dec2Frac(3.75)).toBe('3 3/4');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should convert integer to fraction with denominator', () => {
 | 
			
		||||
			expect(dec2Frac(4)).toBe('4');
 | 
			
		||||
			expect(dec2Frac(0)).toBe('0');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should convert proper fraction (less than 1)', () => {
 | 
			
		||||
			expect(dec2Frac(0.75)).toBe('3/4');
 | 
			
		||||
			expect(dec2Frac(0.5)).toBe('1/2');
 | 
			
		||||
			expect(dec2Frac(0.1)).toBe('1/10');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should handle repeating decimals gracefully', () => {
 | 
			
		||||
			expect(dec2Frac(0.333333)).toBe('1/3');
 | 
			
		||||
			expect(dec2Frac(0.666666)).toBe('2/3');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('fracToDec', () => {
 | 
			
		||||
		it('should convert mixed fraction to decimal', () => {
 | 
			
		||||
			expect(fracToDec('1 1/4')).toBeCloseTo(1.25);
 | 
			
		||||
			expect(fracToDec('2 1/2')).toBeCloseTo(2.5);
 | 
			
		||||
			expect(fracToDec('3 3/4')).toBeCloseTo(3.75);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should convert fraction without whole part to decimal', () => {
 | 
			
		||||
			expect(fracToDec('3/4')).toBeCloseTo(0.75);
 | 
			
		||||
			expect(fracToDec('1/2')).toBeCloseTo(0.5);
 | 
			
		||||
			expect(fracToDec('1/10')).toBeCloseTo(0.1);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should convert whole number fraction', () => {
 | 
			
		||||
			expect(fracToDec('4 0/1')).toBeCloseTo(4);
 | 
			
		||||
			expect(fracToDec('0/1')).toBeCloseTo(0);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should handle zero correctly', () => {
 | 
			
		||||
			expect(fracToDec('0/1')).toBeCloseTo(0);
 | 
			
		||||
			expect(fracToDec('0 0/1')).toBeCloseTo(0);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
@@ -1,36 +1,44 @@
 | 
			
		||||
import {sleep, urlParser} from '../src';
 | 
			
		||||
import {fn, gravatar, escapeRegex, md5} from '../src';
 | 
			
		||||
 | 
			
		||||
describe('Miscellanies Utilities', () => {
 | 
			
		||||
	describe('sleep', () => {
 | 
			
		||||
		test('wait until', async () => {
 | 
			
		||||
			const wait = ~~(Math.random() * 500);
 | 
			
		||||
			const time = new Date().getTime();
 | 
			
		||||
			await sleep(wait);
 | 
			
		||||
			expect(new Date().getTime()).toBeGreaterThanOrEqual(time + wait);
 | 
			
		||||
describe('Misc Utilities', () => {
 | 
			
		||||
	describe('fn', () => {
 | 
			
		||||
		it('should execute a stringified function with arguments', () => {
 | 
			
		||||
			const result = fn({ x: 2, y: 3 }, 'return x + y;');
 | 
			
		||||
			expect(result).toBe(5);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should execute an async function if async=true', async () => {
 | 
			
		||||
			const asyncFn = 'return await Promise.resolve(x * y);';
 | 
			
		||||
			const result = await fn({ x: 3, y: 4 }, asyncFn, true);
 | 
			
		||||
			expect(result).toBe(12);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('should work with no arguments', () => {
 | 
			
		||||
			const result = fn({}, 'return 42;');
 | 
			
		||||
			expect(result).toBe(42);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('urlParser', () => {
 | 
			
		||||
		test('localhost w/ port', () => {
 | 
			
		||||
			const parsed = urlParser('http://localhost:4200/some/path?q1=test1&q2=test2#frag');
 | 
			
		||||
			expect(parsed.protocol).toStrictEqual('http');
 | 
			
		||||
			expect(parsed.host).toStrictEqual('localhost:4200');
 | 
			
		||||
			expect(parsed.domain).toStrictEqual('localhost');
 | 
			
		||||
			expect(parsed.port).toStrictEqual(4200);
 | 
			
		||||
			expect(parsed.path).toStrictEqual('/some/path');
 | 
			
		||||
			expect(parsed.query).toStrictEqual({q1: 'test1', q2: 'test2'});
 | 
			
		||||
			expect(parsed.fragment).toStrictEqual('frag');
 | 
			
		||||
	describe('gravatar', () => {
 | 
			
		||||
		it('should return empty string if email is falsy', () => {
 | 
			
		||||
			expect(gravatar('')).toBe('');
 | 
			
		||||
		});
 | 
			
		||||
		it('should build correct gravatar url', () => {
 | 
			
		||||
			const email = 'test@example.com';
 | 
			
		||||
			expect(gravatar(email)).toContain(`https://www.gravatar.com/avatar/${md5(email)}`);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
		test('advanced URL', () => {
 | 
			
		||||
			const parsed = urlParser('https://sub.domain.example.com/some/path?q1=test1&q2=test2#frag');
 | 
			
		||||
			expect(parsed.protocol).toStrictEqual('https');
 | 
			
		||||
			expect(parsed.host).toStrictEqual('sub.domain.example.com');
 | 
			
		||||
			expect(parsed.domain).toStrictEqual('example.com');
 | 
			
		||||
			expect(parsed.subdomain).toStrictEqual('sub.domain');
 | 
			
		||||
			expect(parsed.path).toStrictEqual('/some/path');
 | 
			
		||||
			expect(parsed.query).toStrictEqual({q1: 'test1', q2: 'test2'});
 | 
			
		||||
			expect(parsed.fragment).toStrictEqual('frag');
 | 
			
		||||
	describe('escapeRegex', () => {
 | 
			
		||||
		it('should escape all special regex characters', () => {
 | 
			
		||||
			const special = '.*+?^${}()|[]\\';
 | 
			
		||||
			const escaped = escapeRegex(special);
 | 
			
		||||
			expect(escaped).toBe('\\.\\*\\+\\?\\^\\$\\{\\}\\(\\)\\|\\[\\]\\\\');
 | 
			
		||||
		});
 | 
			
		||||
		it('should return original string if nothing to escape', () => {
 | 
			
		||||
			const normal = 'abc123';
 | 
			
		||||
			const escaped = escapeRegex(normal);
 | 
			
		||||
			expect(escaped).toBe('abc123');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
 
 | 
			
		||||
@@ -1,111 +1,133 @@
 | 
			
		||||
import {clean, deepCopy, dotNotation, flattenObj, includes, isEqual} from "../src";
 | 
			
		||||
 | 
			
		||||
describe('Object Utilities', () => {
 | 
			
		||||
	const TEST_OBJECT = {
 | 
			
		||||
		a: 1,
 | 
			
		||||
		b: [
 | 
			
		||||
			[2, 3],
 | 
			
		||||
			[4, 5]
 | 
			
		||||
		],
 | 
			
		||||
		c: {
 | 
			
		||||
			d: [
 | 
			
		||||
				[{e: 6, f: 7}]
 | 
			
		||||
			],
 | 
			
		||||
		},
 | 
			
		||||
		g: {h: 8},
 | 
			
		||||
		i: () => 9
 | 
			
		||||
	};
 | 
			
		||||
import {
 | 
			
		||||
	clean, deepCopy, deepMerge, dotNotation, encodeQuery, flattenObj, formData, includes, isEqual, mixin,
 | 
			
		||||
} from '../src';
 | 
			
		||||
 | 
			
		||||
describe('Object utilities', () => {
 | 
			
		||||
	describe('clean', () => {
 | 
			
		||||
		test('remove null properties', () => {
 | 
			
		||||
			const a = {a: 1, b: null, c: undefined};
 | 
			
		||||
			const final = {a: 1};
 | 
			
		||||
			expect(clean(a)).toEqual(final);
 | 
			
		||||
		it('removes null values', () => {
 | 
			
		||||
			const obj = { a: 1, b: null, c: undefined, d: 0 };
 | 
			
		||||
			expect(clean({ ...obj })).toEqual({ a: 1, c: undefined, d: 0 });
 | 
			
		||||
		});
 | 
			
		||||
		test('remove undefined properties', () => {
 | 
			
		||||
			const a = {a: 1, b: null, c: undefined};
 | 
			
		||||
			const final = {a: 1, b: null};
 | 
			
		||||
			expect(clean(a, true)).toEqual(final);
 | 
			
		||||
		it('throws on null input', () => {
 | 
			
		||||
			expect(() => clean(null as any)).toThrow();
 | 
			
		||||
		});
 | 
			
		||||
		it('removes undefined only when specified', () => {
 | 
			
		||||
			const obj = { a: 1, b: undefined, c: null };
 | 
			
		||||
			expect(clean({ ...obj }, true)).toEqual({ a: 1, c: null });
 | 
			
		||||
		});
 | 
			
		||||
		it('works for arrays', () => {
 | 
			
		||||
			expect(clean([1, null, 2, undefined, 3] as any)).toEqual([1, 2, 3]);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('deepCopy', () => {
 | 
			
		||||
		const copy = deepCopy(TEST_OBJECT);
 | 
			
		||||
		test('Array of arrays', () => {
 | 
			
		||||
			const a = [[1, 2], [3, 4]];
 | 
			
		||||
			const b = deepCopy(a);
 | 
			
		||||
			b[0][1] = 5;
 | 
			
		||||
			expect(a).not.toEqual(b);
 | 
			
		||||
		it('creates a deep copy', () => {
 | 
			
		||||
			const obj = { a: { b: 2 } };
 | 
			
		||||
			const copy = deepCopy(obj);
 | 
			
		||||
			expect(copy).toEqual(obj);
 | 
			
		||||
			expect(copy).not.toBe(obj);
 | 
			
		||||
			expect(copy.a).not.toBe(obj.a);
 | 
			
		||||
		});
 | 
			
		||||
		test('Change array inside object', () => {
 | 
			
		||||
			copy.b[1] = [1, 1, 1];
 | 
			
		||||
			expect(copy.b[1]).not.toEqual(TEST_OBJECT.b[1]);
 | 
			
		||||
	});
 | 
			
		||||
		test('Change object inside object', () => {
 | 
			
		||||
			copy.g = {h: Math.random()};
 | 
			
		||||
			expect(copy.g).not.toEqual(TEST_OBJECT.g);
 | 
			
		||||
 | 
			
		||||
	describe('deepMerge', () => {
 | 
			
		||||
		it('merges deeply nested objects', () => {
 | 
			
		||||
			const tgt = { a: { b: 1 }, d: 7 };
 | 
			
		||||
			const src = { a: { c: 2 }, d: 8 };
 | 
			
		||||
			expect(deepMerge({ ...tgt }, src)).toEqual({ a: { b: 1, c: 2 }, d: 8 });
 | 
			
		||||
		});
 | 
			
		||||
		test('Change object property inside nested array', () => {
 | 
			
		||||
			copy.c.d[0][0].e = -1;
 | 
			
		||||
			expect(copy.c.d[0][0].e).not.toEqual(TEST_OBJECT.c.d[0][0].e);
 | 
			
		||||
		it('merges multiple sources', () => {
 | 
			
		||||
			const t = { a: 1 };
 | 
			
		||||
			const s1 = { b: 2 };
 | 
			
		||||
			const s2 = { c: 3 };
 | 
			
		||||
			expect(deepMerge({ ...t }, s1, s2)).toEqual({ a: 1, b: 2, c: 3 });
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('dotNotation', () => {
 | 
			
		||||
		test('no object or properties', () => {
 | 
			
		||||
			expect(dotNotation(undefined, 'z')).toStrictEqual(undefined);
 | 
			
		||||
			expect(dotNotation(TEST_OBJECT, '')).toStrictEqual(undefined);
 | 
			
		||||
		it('gets nested value', () => {
 | 
			
		||||
			const obj = { a: { b: { c: 3 } } };
 | 
			
		||||
			expect(dotNotation(obj, 'a.b.c')).toBe(3);
 | 
			
		||||
		});
 | 
			
		||||
		test('invalid property', () => expect(dotNotation(TEST_OBJECT, 'z')).toBeUndefined());
 | 
			
		||||
		test('by property', () => expect(dotNotation(TEST_OBJECT, 'a')).toBe(TEST_OBJECT.a));
 | 
			
		||||
		test('by key', () => expect(dotNotation(TEST_OBJECT, '["a"]')).toBe(TEST_OBJECT['a']));
 | 
			
		||||
		test('by key (single quote)', () => expect(dotNotation(TEST_OBJECT, '[\'a\']')).toBe(TEST_OBJECT['a']));
 | 
			
		||||
		test('by key (double quote)', () => expect(dotNotation(TEST_OBJECT, '["a"]')).toBe(TEST_OBJECT['a']));
 | 
			
		||||
		test('by index', () => expect(dotNotation(TEST_OBJECT, 'b[0]')).toBe(TEST_OBJECT.b[0]));
 | 
			
		||||
		test('by index (2d)', () => expect(dotNotation(TEST_OBJECT, 'b[1][1]')).toBe(TEST_OBJECT.b[1][1]));
 | 
			
		||||
		test('everything combined', () => expect(dotNotation(TEST_OBJECT, 'c["d"][0][0].e'))
 | 
			
		||||
			.toBe(TEST_OBJECT.c['d'][0][0].e));
 | 
			
		||||
		test('set value', () => {
 | 
			
		||||
			const COPY = JSON.parse(JSON.stringify(TEST_OBJECT));
 | 
			
		||||
			dotNotation(COPY, 'c["d"][0][0].e', 'test');
 | 
			
		||||
			expect(COPY['c']['d'][0][0]['e']).toBe('test');
 | 
			
		||||
		it('sets nested value', () => {
 | 
			
		||||
			const obj = { a: { b: { c: 3 } } };
 | 
			
		||||
			dotNotation(obj, 'a.b.c', 10);
 | 
			
		||||
			expect(obj.a.b.c).toBe(10);
 | 
			
		||||
		});
 | 
			
		||||
		test('set new value', () => {
 | 
			
		||||
			const COPY = JSON.parse(JSON.stringify(TEST_OBJECT));
 | 
			
		||||
			dotNotation(COPY, 'c.x.y.z', 'test');
 | 
			
		||||
			expect(COPY['c']['x']['y']['z']).toBe('test');
 | 
			
		||||
		it('returns undefined for non-existent path', () => {
 | 
			
		||||
			expect(dotNotation({ a: 1 }, 'a.b.c')).toBeUndefined();
 | 
			
		||||
		});
 | 
			
		||||
		it('creates nested object when setting', () => {
 | 
			
		||||
			const obj: any = {};
 | 
			
		||||
			dotNotation(obj, 'd.e.f', 5);
 | 
			
		||||
			expect(obj.d.e.f).toBe(5);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('encodeQuery', () => {
 | 
			
		||||
		it('encodes simple objects', () => {
 | 
			
		||||
			expect(encodeQuery({ a: 1, b: 'test' })).toBe('a=1&b=test');
 | 
			
		||||
		});
 | 
			
		||||
		it('handles special characters', () => {
 | 
			
		||||
			expect(encodeQuery({ a: 'hello world' })).toBe('a=hello%20world');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('flattenObj', () => {
 | 
			
		||||
		it('flattens nested objects', () => {
 | 
			
		||||
			const obj = { a: { b: 2 }, c: 3 };
 | 
			
		||||
			expect(flattenObj(obj)).toEqual({ 'a.b': 2, c: 3 });
 | 
			
		||||
		});
 | 
			
		||||
		it('handles multiple nesting', () => {
 | 
			
		||||
			const obj = { a: { b: { c: 4 } } };
 | 
			
		||||
			expect(flattenObj(obj)).toEqual({ 'a.b.c': 4 });
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('formData', () => {
 | 
			
		||||
		it('converts object to FormData', () => {
 | 
			
		||||
			const obj = { a: '1', b: 'foo' };
 | 
			
		||||
			const fd = formData(obj);
 | 
			
		||||
			expect(fd.get('a')).toBe('1');
 | 
			
		||||
			expect(fd.get('b')).toBe('foo');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('includes', () => {
 | 
			
		||||
		test('simple', () => expect(includes(TEST_OBJECT, {a: 1})).toBeTruthy());
 | 
			
		||||
		test('nested', () => expect(includes(TEST_OBJECT, {g: {h: 8}})).toBeTruthy());
 | 
			
		||||
		test('array', () => expect(includes(TEST_OBJECT, {b: [[2]]})).toBeTruthy());
 | 
			
		||||
		test('nested array', () => expect(includes(TEST_OBJECT, {a: 1, c: {d: [[{e: 6}]]}})).toBeTruthy());
 | 
			
		||||
		test('wong nested array', () => expect(includes(TEST_OBJECT, {a: 1, c: {d: [{e: 7}]}})).toBeFalsy());
 | 
			
		||||
		test('wrong value', () => expect(includes(TEST_OBJECT, {a: 1, b: 2})).toBeFalsy());
 | 
			
		||||
		test('missing value', () => expect(includes(TEST_OBJECT, {a: 1, i: 10})).toBeFalsy());
 | 
			
		||||
		it('checks if all values included', () => {
 | 
			
		||||
			expect(includes({ a: 2, b: 3 }, { a: 2 })).toBeTruthy();
 | 
			
		||||
			expect(includes({ a: 2, b: 3 }, { c: 1 })).toBeFalsy();
 | 
			
		||||
		});
 | 
			
		||||
		it('handles arrays of values', () => {
 | 
			
		||||
			expect(includes([{ a: 1 }], [{ a: 1 }])).toBeTruthy();
 | 
			
		||||
			expect(includes([{ a: 1 }], [{ a: 2 }])).toBeFalsy();
 | 
			
		||||
		});
 | 
			
		||||
		it('allows missing when specified', () => {
 | 
			
		||||
			expect(includes(undefined, { a: 2 }, true)).toBeTruthy();
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('isEqual', () => {
 | 
			
		||||
		test('boolean equal', () => expect(isEqual(true, true)).toBeTruthy());
 | 
			
		||||
		test('boolean not-equal', () => expect(isEqual(true, false)).toBeFalsy());
 | 
			
		||||
		test('number equal', () => expect(isEqual(1, 1)).toBeTruthy());
 | 
			
		||||
		test('number not-equal', () => expect(isEqual(1, 0)).toBeFalsy());
 | 
			
		||||
		test('string equal', () => expect(isEqual('abc', 'abc')).toBeTruthy());
 | 
			
		||||
		test('string not-equal', () => expect(isEqual('abc', '')).toBeFalsy());
 | 
			
		||||
		test('array equal', () => expect(isEqual([true, 1, 'a'], [true, 1, 'a'])).toBeTruthy());
 | 
			
		||||
		test('array not-equal', () => expect(isEqual([true, 1, 'a'], [1])).toBeFalsy());
 | 
			
		||||
		test('object equal', () => expect(isEqual({a: 1, b: 2}, {a: 1, b: 2})).toBeTruthy());
 | 
			
		||||
		test('object not-equal', () => expect(isEqual({a: 1, b: 2}, {a: 1})).toBeFalsy());
 | 
			
		||||
		test('complex', () => expect(isEqual(TEST_OBJECT, TEST_OBJECT)).toBeTruthy());
 | 
			
		||||
		it('returns true for deeply equal objects', () => {
 | 
			
		||||
			expect(isEqual({ a: 1, b: { c: 3 } }, { a: 1, b: { c: 3 } })).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
		it('returns false for non-equal objects', () => {
 | 
			
		||||
			expect(isEqual({ a: 1 }, { a: 2 })).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
		it('compares functions by string', () => {
 | 
			
		||||
			expect(isEqual(() => 1, () => 1)).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('flattenObj', () => {
 | 
			
		||||
		test('simple nested object', () => expect(flattenObj({a: {b: {c: 1}}})).toEqual({"a.b.c": 1}));
 | 
			
		||||
		test('already flat object', () => expect(flattenObj(TEST_OBJECT['g'])).toEqual(TEST_OBJECT['g']));
 | 
			
		||||
		test('non-object input', () => expect(flattenObj(TEST_OBJECT['b'])).toBeUndefined());
 | 
			
		||||
		test('complex nested object', () => expect(flattenObj({a: 1, b: {c: 2}, d: {e: {f: {g: 3}}}}))
 | 
			
		||||
			.toEqual({"a": 1, "b.c": 2, "d.e.f.g": 3}));
 | 
			
		||||
	describe('mixin', () => {
 | 
			
		||||
		it('merges prototypes', () => {
 | 
			
		||||
			class A { foo() { return 1; } }
 | 
			
		||||
			class B { bar() { return 2; } }
 | 
			
		||||
			class C {}
 | 
			
		||||
			mixin(C, [A, B]);
 | 
			
		||||
			const c = new (C as any)();
 | 
			
		||||
			expect(c.foo()).toBe(1);
 | 
			
		||||
			expect(c.bar()).toBe(2);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										202
									
								
								tests/path-events.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										202
									
								
								tests/path-events.spec.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,202 @@
 | 
			
		||||
import {PathError, PathEvent, PathEventEmitter, PE, PES} from '../src';
 | 
			
		||||
 | 
			
		||||
describe('Path Events', () => {
 | 
			
		||||
	beforeEach(() => {
 | 
			
		||||
		PathEvent.clearCache();
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('PE', () => {
 | 
			
		||||
		it('creates PathEvent from template string', () => {
 | 
			
		||||
			const e = PE`users/system:cr`;
 | 
			
		||||
			expect(e).toBeInstanceOf(PathEvent);
 | 
			
		||||
			expect(e.fullPath).toBe('users/system');
 | 
			
		||||
			expect(e.create).toBe(true);
 | 
			
		||||
			expect(e.read).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles interpolation', () => {
 | 
			
		||||
			const path = 'users/system';
 | 
			
		||||
			const meth = 'r';
 | 
			
		||||
			const e = PE`${path}:${meth}`;
 | 
			
		||||
			expect(e.fullPath).toBe('users/system');
 | 
			
		||||
			expect(e.read).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('PES', () => {
 | 
			
		||||
		it('creates string for event', () => {
 | 
			
		||||
			expect(PES`users/system:cr`).toBe('users/system:cr');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('PathEvent', () => {
 | 
			
		||||
		it('parses event string', () => {
 | 
			
		||||
			const pe = new PathEvent('users/system:cr');
 | 
			
		||||
			expect(pe.module).toBe('users');
 | 
			
		||||
			expect(pe.fullPath).toBe('users/system');
 | 
			
		||||
			expect(pe.name).toBe('system');
 | 
			
		||||
			expect(pe.create).toBe(true);
 | 
			
		||||
			expect(pe.read).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('parses wildcard', () => {
 | 
			
		||||
			const pe = new PathEvent('*');
 | 
			
		||||
			expect(pe.all).toBe(true);
 | 
			
		||||
			expect(pe.fullPath).toBe('');
 | 
			
		||||
			expect(pe.methods.has('*')).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('parses none method', () => {
 | 
			
		||||
			const pe = new PathEvent('users/system:n');
 | 
			
		||||
			expect(pe.none).toBe(true);
 | 
			
		||||
			pe.none = false;
 | 
			
		||||
			expect(pe.none).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('setters for methods', () => {
 | 
			
		||||
			const pe = new PathEvent('users/system:r');
 | 
			
		||||
			pe.create = true;
 | 
			
		||||
			expect(pe.methods.has('c')).toBe(true);
 | 
			
		||||
			pe.update = true;
 | 
			
		||||
			expect(pe.methods.has('u')).toBe(true);
 | 
			
		||||
			pe.delete = true;
 | 
			
		||||
			expect(pe.methods.has('d')).toBe(true);
 | 
			
		||||
			pe.read = false;
 | 
			
		||||
			expect(pe.methods.has('r')).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('combine merges longest path and methods', () => {
 | 
			
		||||
			const a = new PathEvent('users/sys:cr');
 | 
			
		||||
			const b = new PathEvent('users/sys:u');
 | 
			
		||||
			const c = PathEvent.combine(a, b);
 | 
			
		||||
			expect(c.fullPath).toBe('users/sys');
 | 
			
		||||
			expect(c.methods.has('c')).toBe(true);
 | 
			
		||||
			expect(c.methods.has('r')).toBe(true);
 | 
			
		||||
			expect(c.methods.has('u')).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('combine stops at none', () => {
 | 
			
		||||
			const a = new PathEvent('data/collection/doc:c');
 | 
			
		||||
			const b = new PathEvent('data/collection:r');
 | 
			
		||||
			const c = new PathEvent('data:n');
 | 
			
		||||
			const d = PathEvent.combine(a, b, c);
 | 
			
		||||
			expect(d.fullPath).toBe(a.fullPath);
 | 
			
		||||
			expect(d.create).toBe(true);
 | 
			
		||||
			expect(d.read).toBe(true);
 | 
			
		||||
			expect(d.update).toBe(false);
 | 
			
		||||
			expect(d.none).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('filter finds overlap by path and methods', () => {
 | 
			
		||||
			const events = [
 | 
			
		||||
				new PathEvent('users/sys:cr'),
 | 
			
		||||
				new PathEvent('users/sys:r'),
 | 
			
		||||
				new PathEvent('files/sys:r')
 | 
			
		||||
			];
 | 
			
		||||
			const filtered = PathEvent.filter(events, 'users/sys:r');
 | 
			
		||||
			expect(filtered.length).toBe(2);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('filter handles wildcard', () => {
 | 
			
		||||
			const events = [
 | 
			
		||||
				new PathEvent('*'),
 | 
			
		||||
				new PathEvent('users/sys:r')
 | 
			
		||||
			];
 | 
			
		||||
			const filtered = PathEvent.filter(events, 'users/sys:r');
 | 
			
		||||
			expect(filtered.length).toBe(2);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('has returns true for overlapping', () => {
 | 
			
		||||
			const events = [new PathEvent('users/sys:cr')];
 | 
			
		||||
			expect(PathEvent.has(events, 'users/sys:r')).toBeTruthy();
 | 
			
		||||
			expect(PathEvent.has(events, 'users/nope:r')).toBeFalsy();
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('hasAll returns true only if all overlap', () => {
 | 
			
		||||
			const events = [
 | 
			
		||||
				new PathEvent('users/sys:cr'),
 | 
			
		||||
				new PathEvent('users/sys:u'),
 | 
			
		||||
			];
 | 
			
		||||
			expect(PathEvent.hasAll(events, 'users/sys:c', 'users/sys:u')).toBe(true);
 | 
			
		||||
			expect(PathEvent.hasAll(events, 'users/sys:c', 'users/sys:no')).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('hasFatal throws if not found', () => {
 | 
			
		||||
			expect(() => PathEvent.hasFatal('users/sys:r', 'users/other:r')).toThrow(PathError);
 | 
			
		||||
			expect(() => PathEvent.hasFatal('users/sys:r', 'users/sys:r')).not.toThrow();
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('hasAllFatal throws if missing', () => {
 | 
			
		||||
			expect(() => PathEvent.hasAllFatal(['users/sys:r'], 'users/sys:r', 'users/sys:c')).toThrow(PathError);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('toString creates correct event string', () => {
 | 
			
		||||
			const s = PathEvent.toString('users/sys', ['c', 'r']);
 | 
			
		||||
			expect(s).toBe('users/sys:cr');
 | 
			
		||||
			const pe = new PathEvent('users/sys:cr');
 | 
			
		||||
			expect(pe.toString()).toBe('users/sys:cr');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('filter instance filters as expected', () => {
 | 
			
		||||
			const pe = new PathEvent('users/sys:r');
 | 
			
		||||
			const arr = ['users/sys:r', 'users/other:r'];
 | 
			
		||||
			const filtered = pe.filter(arr);
 | 
			
		||||
			expect(filtered[0].fullPath).toBe('users/sys');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('PathEventEmitter', () => {
 | 
			
		||||
		it('wildcard', done => {
 | 
			
		||||
			const emitter = new PathEventEmitter();
 | 
			
		||||
			emitter.on('*', (event) => {
 | 
			
		||||
				expect(event.fullPath).toBe('system');
 | 
			
		||||
				done();
 | 
			
		||||
			});
 | 
			
		||||
			emitter.emit('system:c');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('scoped', done => {
 | 
			
		||||
			const emitter = new PathEventEmitter('users');
 | 
			
		||||
			emitter.on(':cud', (event) => {
 | 
			
		||||
				expect(event.fullPath).toBe('users/system');
 | 
			
		||||
				done();
 | 
			
		||||
			});
 | 
			
		||||
			emitter.emit('system:u');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('calls listener on matching emit', done => {
 | 
			
		||||
			const emitter = new PathEventEmitter();
 | 
			
		||||
			const fn = jest.fn((event) => {
 | 
			
		||||
				expect(event.fullPath).toBe('users/sys');
 | 
			
		||||
				done();
 | 
			
		||||
			});
 | 
			
		||||
			emitter.on('users/sys:r', fn);
 | 
			
		||||
			emitter.emit('users/sys:r');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('off removes listener', () => {
 | 
			
		||||
			const emitter = new PathEventEmitter();
 | 
			
		||||
			const fn = jest.fn();
 | 
			
		||||
			emitter.on('users/sys:r', fn);
 | 
			
		||||
			emitter.off(fn);
 | 
			
		||||
			emitter.emit('users/sys:r');
 | 
			
		||||
			expect(fn).not.toHaveBeenCalled();
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('on returns unsubscribe function', () => {
 | 
			
		||||
			const emitter = new PathEventEmitter();
 | 
			
		||||
			const fn = jest.fn();
 | 
			
		||||
			const unsub = emitter.on('users/sys:r', fn);
 | 
			
		||||
			unsub();
 | 
			
		||||
			emitter.emit('users/sys:r');
 | 
			
		||||
			expect(fn).not.toHaveBeenCalled();
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('emit supports prefix', () => {
 | 
			
		||||
			const emitter = new PathEventEmitter('foo');
 | 
			
		||||
			emitter.once('*', (event) =>
 | 
			
		||||
				expect(event.fullPath).toBe('foo/bar'));
 | 
			
		||||
			emitter.emit('bar:r');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
							
								
								
									
										142
									
								
								tests/search.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										142
									
								
								tests/search.spec.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,142 @@
 | 
			
		||||
import {logicTest, search} from '../src';
 | 
			
		||||
 | 
			
		||||
const rows = [
 | 
			
		||||
	{id: 1, name: 'Alice', age: 30},
 | 
			
		||||
	{id: 2, name: 'Bob', age: 24},
 | 
			
		||||
	{id: 3, name: 'Carol', age: 30},
 | 
			
		||||
	{id: 4, name: 'David', age: 35},
 | 
			
		||||
];
 | 
			
		||||
 | 
			
		||||
describe('Search Utilities', () => {
 | 
			
		||||
	describe('search', () => {
 | 
			
		||||
		it('returns empty array for null rows', () => {
 | 
			
		||||
			expect(search(null as any, 'test')).toEqual([]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('returns all rows if search is empty', () => {
 | 
			
		||||
			expect(search(rows, '')).toEqual(rows);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('filters based on a simple property string', () => {
 | 
			
		||||
			expect(search(rows, 'Alice')).toEqual([rows[0]]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('filters using regex when regex=true', () => {
 | 
			
		||||
			expect(search(rows, '^B', true)).toEqual([rows[1]]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('applies the transform function before filtering', () => {
 | 
			
		||||
			const transform = (r: any) => ({...r, name: r.name.toLowerCase()});
 | 
			
		||||
			expect(search(rows, 'alice', false, transform)).toEqual([rows[0]]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('uses logicTest for non-regex search', () => {
 | 
			
		||||
			expect(search(rows, 'age == 30')).toEqual([rows[0], rows[2]]);
 | 
			
		||||
			expect(search(rows, 'id = 2')).toEqual([rows[1]]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('returns all if search is falsy and regex enabled', () => {
 | 
			
		||||
			expect(search(rows, '', true)).toEqual(rows);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles regex search with special characters', () => {
 | 
			
		||||
			expect(search(rows, '^[AC]', true)).toEqual([rows[0], rows[2]]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('ignores case when regex is applied', () => {
 | 
			
		||||
			expect(search(rows, 'ALICE', true)).toEqual([]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('performs partial matches for properties when regex=false', () => {
 | 
			
		||||
			expect(search(rows, 'Da')).toEqual([rows[3]]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles empty array input gracefully', () => {
 | 
			
		||||
			expect(search([], 'test')).toEqual([]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles numeric values with comparison logic in strings', () => {
 | 
			
		||||
			expect(search(rows, 'age < 31')).toEqual([rows[0], rows[1], rows[2]]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		// New test cases for `+` and `-` operators
 | 
			
		||||
		it('filters rows using the + operator', () => {
 | 
			
		||||
			expect(search(rows, 'name += Al')).toEqual([rows[0]]);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('filters rows using the - operator', () => {
 | 
			
		||||
			expect(search(rows, 'name -= Al')).toEqual([rows[1], rows[2], rows[3]]);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('logicTest', () => {
 | 
			
		||||
		const obj = {x: 10, y: 5, name: 'Alpha'};
 | 
			
		||||
 | 
			
		||||
		it('handles equality and inequality', () => {
 | 
			
		||||
			expect(logicTest(obj, 'x == 10')).toBe(true);
 | 
			
		||||
			expect(logicTest(obj, 'y != 5')).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles comparison operators', () => {
 | 
			
		||||
			expect(logicTest(obj, 'x > 5')).toBe(true);
 | 
			
		||||
			expect(logicTest(obj, 'y <= 10')).toBe(true);
 | 
			
		||||
			expect(logicTest(obj, 'x < 5')).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('supports case insensitive property search', () => {
 | 
			
		||||
			expect(logicTest(obj, 'alpha')).toBeTruthy();
 | 
			
		||||
			expect(logicTest(obj, 'ALPHA')).toBeFalsy();
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles logical AND/OR expressions', () => {
 | 
			
		||||
			expect(logicTest(obj, 'x == 10 && y == 5')).toBe(true);
 | 
			
		||||
			expect(logicTest(obj, 'x == 10 || y == 100')).toBe(true);
 | 
			
		||||
			expect(logicTest(obj, 'x == 1 && y == 5')).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('returns false for unsupported operators', () => {
 | 
			
		||||
			expect(logicTest(obj, 'x === 10')).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles invalid condition strings gracefully', () => {
 | 
			
		||||
			expect(logicTest(obj, 'invalid condition')).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('supports numeric operations with ranges', () => {
 | 
			
		||||
			expect(logicTest(obj, 'x > 5 && x < 15')).toBe(true);
 | 
			
		||||
			expect(logicTest(obj, 'x > 15')).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles mixed case keys gracefully', () => {
 | 
			
		||||
			const mixedCaseObj = {TestKey: 123};
 | 
			
		||||
			expect(logicTest(mixedCaseObj, 'TestKey == 123')).toBe(true);
 | 
			
		||||
			expect(logicTest(mixedCaseObj, 'testkey == 123')).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('returns false if condition operators are missing', () => {
 | 
			
		||||
			expect(logicTest(obj, 'x 10')).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		// New test cases for `+` and `-` operators
 | 
			
		||||
		it('handles the + operator for inclusion', () => {
 | 
			
		||||
			expect(logicTest(obj, 'name += Alpha')).toBe(true);
 | 
			
		||||
			expect(logicTest(obj, 'name += Alp')).toBe(true);
 | 
			
		||||
			expect(logicTest(obj, 'name += Bet')).toBe(false);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles the - operator for exclusion', () => {
 | 
			
		||||
			expect(logicTest(obj, 'name -= Alpha')).toBe(false);
 | 
			
		||||
			expect(logicTest(obj, 'name -= Alp')).toBe(false);
 | 
			
		||||
			expect(logicTest(obj, 'name -= Bet')).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('includes partial matches correctly with +', () => {
 | 
			
		||||
			expect(logicTest(obj, 'name += lph')).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('excludes partial matches correctly with -', () => {
 | 
			
		||||
			expect(logicTest(obj, 'name -= lph')).toBe(false);
 | 
			
		||||
			expect(logicTest(obj, 'name -= xyz')).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
@@ -1,50 +1,168 @@
 | 
			
		||||
import {matchAll, randomString, randomStringBuilder} from "../src";
 | 
			
		||||
import {
 | 
			
		||||
	camelCase,
 | 
			
		||||
	CHAR_LIST,
 | 
			
		||||
	formatBytes,
 | 
			
		||||
	formatPhoneNumber,
 | 
			
		||||
	insertAt, kebabCase,
 | 
			
		||||
	LETTER_LIST, matchAll, md5,
 | 
			
		||||
	NUMBER_LIST, pad, parseUrl, pascalCase, randomHex, randomString, randomStringBuilder, snakeCase, strSplice,
 | 
			
		||||
	SYMBOL_LIST
 | 
			
		||||
} from '../src';
 | 
			
		||||
 | 
			
		||||
describe('String Utilities', () => {
 | 
			
		||||
	describe('randomString', () => {
 | 
			
		||||
		test('length', () => expect(randomString(32).length).toStrictEqual(32));
 | 
			
		||||
		test('distribution', () => {
 | 
			
		||||
			const charList = '123';
 | 
			
		||||
			const random = randomString(32, charList);
 | 
			
		||||
			expect(random.split('').filter(c => c == '1').length).toBeGreaterThan(0);
 | 
			
		||||
			expect(random.split('').filter(c => c == '2').length).toBeGreaterThan(0);
 | 
			
		||||
			expect(random.split('').filter(c => c == '3').length).toBeGreaterThan(0);
 | 
			
		||||
	test('LETTER_LIST, NUMBER_LIST, SYMBOL_LIST, CHAR_LIST', () => {
 | 
			
		||||
		expect(LETTER_LIST).toBe('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
 | 
			
		||||
		expect(NUMBER_LIST).toBe('0123456789');
 | 
			
		||||
		expect(SYMBOL_LIST).toContain('@');
 | 
			
		||||
		expect(CHAR_LIST).toContain('A');
 | 
			
		||||
		expect(CHAR_LIST).toContain('a');
 | 
			
		||||
		expect(CHAR_LIST).toContain('5');
 | 
			
		||||
		expect(CHAR_LIST).toContain('!');
 | 
			
		||||
	});
 | 
			
		||||
		test('binary', () => {
 | 
			
		||||
			const randomByte = randomString(8, '01');
 | 
			
		||||
			expect(randomByte.split('').filter(c => c == '0').length).toBeGreaterThan(0);
 | 
			
		||||
			expect(randomByte.split('').filter(c => c == '1').length).toBeGreaterThan(0);
 | 
			
		||||
			expect(randomByte.length).toStrictEqual(8);
 | 
			
		||||
 | 
			
		||||
	describe('camelCase', () => {
 | 
			
		||||
		it('converts to camelCase', () => {
 | 
			
		||||
			expect(camelCase('hello_world')).toBe('helloWorld');
 | 
			
		||||
			expect(camelCase('Hello world test')).toBe('helloWorldTest');
 | 
			
		||||
		});
 | 
			
		||||
		it('returns empty string if value is falsy', () => {
 | 
			
		||||
			expect(camelCase()).toBe('');
 | 
			
		||||
			expect(camelCase('')).toBe('');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('formatBytes', () => {
 | 
			
		||||
		it('correctly formats bytes', () => {
 | 
			
		||||
			expect(formatBytes(0)).toBe('0 Bytes');
 | 
			
		||||
			expect(formatBytes(1024)).toBe('1 KB');
 | 
			
		||||
			expect(formatBytes(1024 * 1024)).toBe('1 MB');
 | 
			
		||||
			expect(formatBytes(1234, 1)).toBe('1.2 KB');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('formatPhoneNumber', () => {
 | 
			
		||||
		it('formats plain phone numbers', () => {
 | 
			
		||||
			expect(formatPhoneNumber('1234567890')).toBe('(123) 456-7890');
 | 
			
		||||
			expect(formatPhoneNumber('+11234567890')).toBe('+1 (123) 456-7890');
 | 
			
		||||
			expect(formatPhoneNumber('1 123 456 7890')).toBe('+1 (123) 456-7890');
 | 
			
		||||
		});
 | 
			
		||||
		it('throws for invalid phone strings', () => {
 | 
			
		||||
			expect(() => formatPhoneNumber('abc')).toThrow();
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('insertAt', () => {
 | 
			
		||||
		it('inserts a string at a given index', () => {
 | 
			
		||||
			expect(insertAt('Hello!', 'X', 5)).toBe('HelloX');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('kebabCase', () => {
 | 
			
		||||
		it('converts to kebab-case', () => {
 | 
			
		||||
			expect(kebabCase('hello world')).toBe('hello-world');
 | 
			
		||||
			expect(kebabCase('HelloWorld')).toContain('hello-world');
 | 
			
		||||
			expect(kebabCase('')).toBe('');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('pad', () => {
 | 
			
		||||
		it('pads start by default', () => {
 | 
			
		||||
			expect(pad('1', 2, '0')).toBe('01');
 | 
			
		||||
		});
 | 
			
		||||
		it('pads end if start is false', () => {
 | 
			
		||||
			expect(pad('1', 3, '0', false)).toBe('100');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('pascalCase', () => {
 | 
			
		||||
		it('converts to PascalCase', () => {
 | 
			
		||||
			expect(pascalCase('hello_world')).toBe('HelloWorld');
 | 
			
		||||
			expect(pascalCase('')).toBe('');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('randomHex', () => {
 | 
			
		||||
		it('creates a random hex string of correct length', () => {
 | 
			
		||||
			expect(randomHex(8)).toHaveLength(8);
 | 
			
		||||
			expect(/^[a-f0-9]{8}$/i.test(randomHex(8))).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('randomString', () => {
 | 
			
		||||
		it('creates a random string from CHAR_LIST of correct length', () => {
 | 
			
		||||
			const s = randomString(10);
 | 
			
		||||
			expect(s).toHaveLength(10);
 | 
			
		||||
			// letters, numbers, symbols all included in CHAR_LIST
 | 
			
		||||
		});
 | 
			
		||||
		it('uses provided pool', () => {
 | 
			
		||||
			expect(['0','1']).toContain(randomString(1, '01'));
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('randomStringBuilder', () => {
 | 
			
		||||
		test('length', () => {
 | 
			
		||||
			const len = ~~(Math.random() * 32);
 | 
			
		||||
			expect(randomStringBuilder(len, true).length).toStrictEqual(len);
 | 
			
		||||
		it('creates with just letters', () => {
 | 
			
		||||
			expect(/^[A-Z]+$/.test(randomStringBuilder(5, true, false, false))).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
		test('no length', () => {
 | 
			
		||||
			expect(randomStringBuilder(0, true)).toStrictEqual('');
 | 
			
		||||
		it('creates with just numbers', () => {
 | 
			
		||||
			expect(/^[0-9]+$/.test(randomStringBuilder(5, false, true, false))).toBe(true);
 | 
			
		||||
		});
 | 
			
		||||
		test('letters only', () =>
 | 
			
		||||
			expect(/^[a-zA-Z]{10}$/g.test(randomStringBuilder(10, true))).toBeTruthy());
 | 
			
		||||
		test('numbers only', () =>
 | 
			
		||||
			expect(/^[0-9]{10}$/g.test(<any>randomStringBuilder(10, false, true))).toBeTruthy());
 | 
			
		||||
		test('symbols only', () =>
 | 
			
		||||
			expect(/^[^a-zA-Z0-9]{10}$/g.test(randomStringBuilder(10, false, false, true))).toBeTruthy());
 | 
			
		||||
		test('everything', () => {
 | 
			
		||||
			const randomString = randomStringBuilder(30, true, true, true);
 | 
			
		||||
			expect(/[a-zA-Z]/g.test(randomString)).toBeTruthy();
 | 
			
		||||
			expect(/[0-9]/g.test(randomString)).toBeTruthy();
 | 
			
		||||
			expect(/[^a-zA-Z0-9]/g.test(randomString)).toBeTruthy();
 | 
			
		||||
		it('creates with just symbols', () => {
 | 
			
		||||
			expect(SYMBOL_LIST).toContain(randomStringBuilder(1, false, false, true));
 | 
			
		||||
		});
 | 
			
		||||
		it('throws if all false', () => {
 | 
			
		||||
			expect(() => randomStringBuilder(5, false, false, false)).toThrow();
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('snakeCase', () => {
 | 
			
		||||
		it('converts to snake_case', () => {
 | 
			
		||||
			expect(snakeCase('helloWorld')).toContain('hello_world');
 | 
			
		||||
			expect(snakeCase('')).toBe('');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('strSplice', () => {
 | 
			
		||||
		it('splices string as expected', () => {
 | 
			
		||||
			expect(strSplice('abcdef', 2, 2, 'ZZ')).toBe('abZZef');
 | 
			
		||||
			expect(strSplice('abcdef', 1, 0, 'Z')).toBe('aZbcdef');
 | 
			
		||||
		});
 | 
			
		||||
		test('no pool', () =>
 | 
			
		||||
			expect(() => randomStringBuilder(10, false, false, false)).toThrow());
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('matchAll', () => {
 | 
			
		||||
		test('using string', () => expect(matchAll('fooBar fooBar FooBar', 'fooBar').length).toBe(2));
 | 
			
		||||
		test('using regex', () => expect(matchAll('fooBar fooBar FooBar', /fooBar/g).length).toBe(2));
 | 
			
		||||
		test('using malformed regex', () => expect(() => matchAll('fooBar fooBar FooBar', /fooBar/)).toThrow());
 | 
			
		||||
		it('returns expected matches', () => {
 | 
			
		||||
			const matches = matchAll('a1 b2 c3', /\d/g);
 | 
			
		||||
			expect(matches.length).toBe(3);
 | 
			
		||||
			expect(matches[0][0]).toBe('1');
 | 
			
		||||
		});
 | 
			
		||||
		it('throws for non-global regex', () => {
 | 
			
		||||
			expect(() => matchAll('abc', /a/)).toThrow();
 | 
			
		||||
		});
 | 
			
		||||
		it('accepts regex string', () => {
 | 
			
		||||
			const matches = matchAll('a1a2', '\\d');
 | 
			
		||||
			expect(matches.length).toBe(2);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('parseUrl', () => {
 | 
			
		||||
		it('parses a full url', () => {
 | 
			
		||||
			const url = parseUrl('https://sub.example.com:8000/path?a=1&b=2#frag');
 | 
			
		||||
			expect(url.protocol).toBe('https');
 | 
			
		||||
			expect(url.subdomain).toBe('sub');
 | 
			
		||||
			expect(url.domain).toBe('example.com');
 | 
			
		||||
			expect(url.port).toBe(8000);
 | 
			
		||||
			expect(url.path).toBe('/path');
 | 
			
		||||
			expect(url.query).toEqual({ a: '1', b: '2' });
 | 
			
		||||
			expect(url.fragment).toBe('frag');
 | 
			
		||||
		});
 | 
			
		||||
		it('parses domain without subdomain', () => {
 | 
			
		||||
			const url = parseUrl('https://example.com');
 | 
			
		||||
			expect(url.domain).toBe('example.com');
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('md5', () => {
 | 
			
		||||
		it('hashes string to hex', () => {
 | 
			
		||||
			expect(md5('test')).toMatch(/^[a-f0-9]+$/i);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
 
 | 
			
		||||
							
								
								
									
										108
									
								
								tests/time.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										108
									
								
								tests/time.spec.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,108 @@
 | 
			
		||||
import {adjustedInterval, formatDate, instantInterval, sleep, sleepWhile, timeUntil} from '../src';
 | 
			
		||||
 | 
			
		||||
jest.useFakeTimers();
 | 
			
		||||
 | 
			
		||||
describe('Time Utilities', () => {
 | 
			
		||||
	describe('adjustedInterval', () => {
 | 
			
		||||
		it('calls callback at roughly correct intervals, considering execution time', async () => {
 | 
			
		||||
			const cb = jest.fn(() => new Promise(res => setTimeout(res, 5)));
 | 
			
		||||
			const stop = adjustedInterval(cb, 50);
 | 
			
		||||
 | 
			
		||||
			expect(cb).toHaveBeenCalledTimes(1);
 | 
			
		||||
 | 
			
		||||
			await jest.advanceTimersByTimeAsync(50);
 | 
			
		||||
			expect(cb).toHaveBeenCalledTimes(2);
 | 
			
		||||
 | 
			
		||||
			await jest.advanceTimersByTimeAsync(100);
 | 
			
		||||
			expect(cb).toHaveBeenCalledTimes(4);
 | 
			
		||||
 | 
			
		||||
			stop();
 | 
			
		||||
			await jest.advanceTimersByTimeAsync(100);
 | 
			
		||||
			expect(cb).toHaveBeenCalledTimes(4);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('formatDate', () => {
 | 
			
		||||
		it('formats current date correctly with default format', () => {
 | 
			
		||||
			const result = formatDate('YYYY-MM-DD', new Date('2023-01-15T10:30:30.000Z'), 0);
 | 
			
		||||
			expect(result).toBe('2023-01-15');
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles formatting for given timestamp', () => {
 | 
			
		||||
			const timestamp = Date.UTC(2023, 1, 1, 18, 5, 5, 123); // Feb 1, 2023 18:05:05.123 UTC
 | 
			
		||||
			const formatted = formatDate('YYYY MM DD HH mm ss SSS A Z', timestamp, 'UTC');
 | 
			
		||||
			expect(formatted).toMatch(/^2023 02 01 18 05 05 123 PM \+00:00/i);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('throws for unknown timezone', () => {
 | 
			
		||||
			expect(() => formatDate('YYYY', new Date(), '???')).toThrowError(/Invalid timezone/);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles timezone by offset number', () => {
 | 
			
		||||
			const dt = new Date('2020-01-01T00:00:00.000Z');
 | 
			
		||||
			const str = formatDate('HH:mm z', dt, 1);
 | 
			
		||||
			expect(str).toMatch(/01:00/);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('handles Do, MMMM, dddd tokens', () => {
 | 
			
		||||
			const dt = new Date('2021-03-03T09:00:00Z');
 | 
			
		||||
			const result = formatDate('Do MMMM dddd', dt, 0);
 | 
			
		||||
			expect(result).toMatch(/^3rd March Wednesday$/);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('instantInterval', () => {
 | 
			
		||||
		it('calls function immediately then at intervals', () => {
 | 
			
		||||
			const cb = jest.fn();
 | 
			
		||||
			const id = instantInterval(cb, 1000);
 | 
			
		||||
			expect(cb).toHaveBeenCalledTimes(1);
 | 
			
		||||
 | 
			
		||||
			jest.advanceTimersByTime(1000);
 | 
			
		||||
			expect(cb).toHaveBeenCalledTimes(2);
 | 
			
		||||
 | 
			
		||||
			clearInterval(id);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('sleep', () => {
 | 
			
		||||
		it('waits the given ms', async () => {
 | 
			
		||||
			const time = Date.now(), wait = 100;
 | 
			
		||||
			const promise = sleep(wait);
 | 
			
		||||
			jest.advanceTimersByTime(wait);
 | 
			
		||||
			await promise;
 | 
			
		||||
			expect(Date.now()).toBeGreaterThanOrEqual(time + wait);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('sleepWhile', () => {
 | 
			
		||||
		it('resolves once condition is false', async () => {
 | 
			
		||||
			const time = Date.now(), wait = 300;
 | 
			
		||||
			let flag = true;
 | 
			
		||||
			const promise = sleepWhile(() => flag, 100);
 | 
			
		||||
			setTimeout(() => { flag = false; }, wait);
 | 
			
		||||
			await jest.advanceTimersByTimeAsync(wait);
 | 
			
		||||
			await promise;
 | 
			
		||||
			expect(Date.now()).toBeGreaterThanOrEqual(time + wait);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
 | 
			
		||||
	describe('timeUntil', () => {
 | 
			
		||||
		it('returns milliseconds until given date', () => {
 | 
			
		||||
			const now = Date.now();
 | 
			
		||||
			const future = now + 1000;
 | 
			
		||||
			jest.spyOn(Date, 'now').mockReturnValue(now);
 | 
			
		||||
 | 
			
		||||
			const result = timeUntil(future);
 | 
			
		||||
			expect(result).toBe(1000);
 | 
			
		||||
		});
 | 
			
		||||
 | 
			
		||||
		it('accepts Date object', () => {
 | 
			
		||||
			const now = new Date();
 | 
			
		||||
			const t = new Date(now.getTime() + 450);
 | 
			
		||||
			jest.spyOn(global, 'Date').mockImplementation(() => now as any);
 | 
			
		||||
 | 
			
		||||
			const result = timeUntil(t);
 | 
			
		||||
			expect(result).toBe(450);
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
							
								
								
									
										18
									
								
								tests/type.spec.ts
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										18
									
								
								tests/type.spec.ts
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,18 @@
 | 
			
		||||
import {Writable} from '../src';
 | 
			
		||||
 | 
			
		||||
describe('Type Utilities', () => {
 | 
			
		||||
	describe('Writable', () => {
 | 
			
		||||
		it('should create a writable version of a readonly type', () => {
 | 
			
		||||
			type ReadonlyPerson = {
 | 
			
		||||
				readonly name: string;
 | 
			
		||||
				readonly age: number;
 | 
			
		||||
			};
 | 
			
		||||
			type WritablePerson = Writable<ReadonlyPerson>;
 | 
			
		||||
			// Typescript: WritablePerson's properties should not be readonly
 | 
			
		||||
			const person: WritablePerson = { name: 'Alice', age: 40 };
 | 
			
		||||
			person.name = 'Bob'; // Should not error in TypeScript
 | 
			
		||||
			person.age = 41;     // Should not error in TypeScript
 | 
			
		||||
			expect(person).toEqual({ name: 'Bob', age: 41 });
 | 
			
		||||
		});
 | 
			
		||||
	});
 | 
			
		||||
});
 | 
			
		||||
@@ -1,7 +1,7 @@
 | 
			
		||||
{
 | 
			
		||||
	"include": ["src"],
 | 
			
		||||
	"compilerOptions": {
 | 
			
		||||
		"target": "ES2020",
 | 
			
		||||
		"target": "ESNext",
 | 
			
		||||
		"useDefineForClassFields": true,
 | 
			
		||||
		"module": "ESNext",
 | 
			
		||||
		"lib": ["ESNext", "DOM", "DOM.Iterable"],
 | 
			
		||||
 
 | 
			
		||||
@@ -13,7 +13,7 @@ export default defineConfig({
 | 
			
		||||
			}
 | 
			
		||||
		},
 | 
			
		||||
		emptyOutDir: true,
 | 
			
		||||
		minify: true,
 | 
			
		||||
		minify: false,
 | 
			
		||||
		sourcemap: true
 | 
			
		||||
	},
 | 
			
		||||
	plugins: [dts()],
 | 
			
		||||
 
 | 
			
		||||
		Reference in New Issue
	
	Block a user