Skip to content

Commit

Permalink
feat: encode uuids to readable keys
Browse files Browse the repository at this point in the history
  • Loading branch information
nashaddams committed Jan 11, 2025
0 parents commit f178a67
Show file tree
Hide file tree
Showing 10 changed files with 394 additions and 0 deletions.
14 changes: 14 additions & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
name: publish
on:
push:
branches:
- main
jobs:
publish:
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v4
- run: npx jsr publish
26 changes: 26 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest]
deno: [v2.x]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Deno
uses: denoland/setup-deno@v2
with:
deno-version: ${{ matrix.deno }}
- name: Check formatting
run: deno fmt --check
- name: Lint
run: deno lint
- name: Run tests
run: deno task test
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.DS_Store
dist
docs
cov
cov.lcov
7 changes: 7 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"deno.enable": true,
"editor.defaultFormatter": "denoland.vscode-deno",
"editor.formatOnSave": true,
"files.insertFinalNewline": true,
"files.trimTrailingWhitespace": true
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 nashaddams

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# uuidkey

[![JSR](https://jsr.io/badges/@nashaddams/uuidkey)](https://jsr.io/@nashaddams/uuidkey)
[![JSR score](https://jsr.io/badges/@nashaddams/uuidkey/score)](https://jsr.io/@nashaddams/uuidkey)
[![main](https://github.com/nashaddams/uuidkey/actions/workflows/tests.yml/badge.svg)](https://github.com/nashaddams/uuidkey/actions)

Encode UUIDs to readable keys with
[Crockford base32](https://www.crockford.com/base32.html), inspired by
[`agentstation/uuidkey`](https://github.com/agentstation/uuidkey).

## Usage

```ts
import { decode, encode, generate, validate } from "@nashaddams/uuidkey";

encode("01945655-0794-7259-800b-614c6ea29659"); // -> 06A5CN8-0YA74P8-G05P2K0-DTH9CP8
decode("06A5CN8-0YA74P8-G05P2K0-DTH9CP8"); // -> 01945655-0794-7259-800b-614c6ea29659
validate("06A5CN8-0YA74P8-G05P2K0-DTH9CP8"); // -> true
generate(); // -> { key: "06A5CQ8-SGRQZ7G-KHQWGF0-PM9JZ90", uuid: "0194565d-cc31-7f9e-9c6f-c83cb5132fa4" }
```

See [the docs](https://jsr.io/@nashaddams/uuidkey/doc) for further details.

Alternatively, `uuidkey` can also be run via CLI:

```sh
deno run -R=. jsr:@nashaddams/uuidkey [--help]
```
31 changes: 31 additions & 0 deletions deno.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "@nashaddams/uuidkey",
"version": "0.1.0",
"license": "MIT",
"exports": "./mod.ts",
"imports": {
"@cliffy/command": "jsr:@cliffy/[email protected]",
"@std/assert": "jsr:@std/[email protected]",
"@std/encoding": "jsr:@std/[email protected]",
"@std/uuid": "jsr:@std/[email protected]"
},
"tasks": {
"build": "deno compile -R=. -o dist/audit mod.ts",
"uuidkey": "deno run -R=. mod.ts",
"test": "deno test --coverage=cov",
"coverage:lcov": "deno coverage --exclude=test --lcov cov > cov.lcov",
"coverage:html": "deno coverage --html --exclude=test cov",
"coverage:console": "deno coverage --exclude=test cov",
"coverage": "deno task coverage:lcov && deno task coverage:html && deno task coverage:console",
"doc": "deno doc --html mod.ts && deno doc --lint mod.ts"
},
"publish": {
"include": [
"mod.ts",
"src/**/*.ts",
"LICENSE",
"README.md"
]
},
"lock": false
}
29 changes: 29 additions & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Command } from "@cliffy/command";
import denoJson from "./deno.json" with { type: "json" };
import { decode, encode, generate, validate } from "./src/uuidkey.ts";

if (import.meta.main) {
await new Command()
.name("uuidkey")
.description("Encode UUIDs to readable keys.")
.version(denoJson.version)
.command("encode", "Encode UUID to UUID key.")
.arguments("<uuid:string>")
.action((_, uuid) => console.info(encode(uuid)))
.command("decode", "Decode UUID key to UUID.")
.arguments("<uuidkey:string>")
.action((_, uuidkey) => console.info(decode(uuidkey)))
.command("validate", "Validate UUID key.")
.arguments("<uuidkey:string>")
.action((_, uuidkey) => console.info(validate(uuidkey) ? "YES" : "NO"))
.command("generate", "Generate UUID key and UUID pair.")
.option("--v4", "Use UUIDv4 (default v7).")
.action(({ v4 }) => {
const { key, uuid } = generate(v4 ? "v4" : "v7");
console.info(`${key}\t\tKey`);
console.info(`${uuid}\tUUID${v4 ? "v4" : "v7"}`);
})
.parse();
}

export { decode, encode, generate, validate };
81 changes: 81 additions & 0 deletions src/uuidkey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { decodeHex, encodeHex } from "@std/encoding";
import {
decodeBase32Crockford,
encodeBase32Crockford,
} from "@std/encoding/unstable-base32crockford";
import { validate as validateV4 } from "@std/uuid";
import {
generate as generateV7,
validate as validateV7,
} from "@std/uuid/unstable-v7";

/**
* Validate UUID key.
*
* @param {string} key UUID key
* @returns {boolean} `true` for valid, `false` for invalid UUID key
*/
export const validate = (key: string): boolean => {
return key.length === 31 &&
/[0-9A-Z]{7}-[0-9A-Z]{7}-[0-9A-Z]{7}-[0-9A-Z]{7}/.test(key);
};

/**
* Encode UUID to UUID key.
*
* @param {string} uuid UUIDv7 or UUIDv4
* @returns {string} UUID key
*/
export const encode = (uuid: string): string => {
if (!validateV7(uuid) && !validateV4(uuid)) {
throw new Error(
`Only UUIDv7 and UUIDv4 are supported, e.g. 019452ea-79c3-77b3-b9a7-dba584f57d0b - Received: ${uuid}`,
);
}

const [p1, p2, p3, p4, p5] = uuid.split("-");
return [
encodeBase32Crockford(decodeHex(p1)),
encodeBase32Crockford(decodeHex(`${p2}${p3}`)),
encodeBase32Crockford(decodeHex(`${p4}${p5.substring(0, 4)}`)),
encodeBase32Crockford(decodeHex(`${p5.substring(4)}`)),
].join("-").replaceAll("=", "");
};

/**
* Decode UUID key to UUID.
*
* @param {string} key UUID key
* @returns {string} UUID
*/
export const decode = (key: string): string => {
if (!validate(key)) {
throw new Error(
`Only UUID keys are supported, e.g. 06A55TG-F71QFCR-Q6KXQ98-GKTQT2R - Received: ${key}`,
);
}

const [p1, p2, p3, p4] = key.split("-").map((id) =>
encodeHex(decodeBase32Crockford(`${id}=`))
);
return [
p1,
p2.substring(0, 4),
p2.substring(4),
p3.substring(0, 4),
`${p3.substring(4)}${p4}`,
].join("-");
};

/**
* Generate UUID key and UUID pair.
*
* @param {"v7"|"v4"} version UUID version (default: `v7`)
* @returns {{key: string, uuid: string}} UUID key and UUID
*/
export const generate = (
version: "v7" | "v4" = "v7",
): { key: string; uuid: string } => {
const uuid = version === "v7" ? generateV7() : crypto.randomUUID();
return { key: encode(uuid), uuid };
};
Loading

0 comments on commit f178a67

Please sign in to comment.