@0001-labs/idv1 0.3.1 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +48 -82
- package/package.json +3 -3
- package/src/advanced.ts +0 -45
- package/src/scanCode.ts +0 -88
- package/src/scanCodeDrawing.ts +0 -28
- package/src/shapes.ts +0 -75
- package/src/space.ts +0 -11
- package/src/words.ts +0 -29
package/README.md
CHANGED
|
@@ -1,106 +1,72 @@
|
|
|
1
1
|
# IDv1
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An ID system for short, memorable IDs that are easy to keep unique.
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
| Product | four letters, two digits | `AbCd12` | 731 million |
|
|
9
|
-
| List | two digits, four letters | `12ABCD` | 46 million |
|
|
10
|
-
| Item | two letters, two digits, two letters or digits that are not both digits | `Ab12Cd` | 1 billion |
|
|
11
|
-
|
|
12
|
-
- **Capitals matter.** `Ab12Cd` and `ab12cd` are two codes.
|
|
13
|
-
- **An account's letters come from the person's name**, a capital and a small one: Leo is `Le0125`, Henrik `He0422`. A name without two Latin letters takes them from the email address, and failing that at random. The digits are drawn until the code is free.
|
|
14
|
-
- **A product's code is scanned, never typed.** Whoever signs up with a product's code may keep it as their account's code, so it is an account's shape too. Codes whose letters spell a rude or awkward word in any language the products speak, capitals aside, are drawn again (`words.ts`).
|
|
15
|
-
- **New lists draw four capitals.** Older lists may hold small letters, and every check reads both.
|
|
16
|
-
- **An item never ends in two digits**, or it would be an account.
|
|
17
|
-
- **A code does not change by itself.** A product may give an account a chosen code, as when it should match the code its owner has elsewhere.
|
|
18
|
-
- **Some codes are kept for a person or a role.** `RESERVED_ACCOUNT_CODES` names them, `RESERVED_ACCOUNT_EMAILS` says whose they are, and no product draws them for anyone else: Joachim is `Jo4712` (jaa90@icloud.com) and `Jo0001` (joachim@0001.dev), the onboarding test account is `On0001` (joachim+onboarding@0001.dev, `On4713` before) and the test account is `Te0001` (joachim+test@0001.dev). A product gives the code `reservedAccountCode(email)` returns before drawing one, so the same person is the same code in every product and easy to leave out of the figures.
|
|
19
|
-
|
|
20
|
-
## Which shape for what you build
|
|
21
|
-
|
|
22
|
-
Pick the shape by what the thing is, not by what a product calls it, so the same kind of thing has the same shape in every product and a code is easy to place on sight:
|
|
23
|
-
|
|
24
|
-
| What it is | Shape | Called in products | Example |
|
|
25
|
-
|---|---|---|---|
|
|
26
|
-
| A person | account | user, member, owner | `Jo4712` |
|
|
27
|
-
| Something that holds things | list | list, category, board, collection, folder, project | `12ABCD` |
|
|
28
|
-
| One thing kept | item | item, clip, listing, note, a piece of inspiration | `Ab12Cd` |
|
|
29
|
-
| A thing in the world with a code printed on it | product | product, tag, sticker | `AbCd12` |
|
|
30
|
-
|
|
31
|
-
Two products agree without asking each other: a category in one is a list's shape like a list in another, and a piece of inspiration is an item's shape like an item anywhere.
|
|
5
|
+
```sh
|
|
6
|
+
npm install @0001-labs/idv1
|
|
7
|
+
```
|
|
32
8
|
|
|
33
9
|
```ts
|
|
34
|
-
import { codeCandidate, codeKind
|
|
10
|
+
import { codeCandidate, codeKind } from '@0001-labs/idv1'
|
|
35
11
|
|
|
36
|
-
codeCandidate('
|
|
37
|
-
|
|
38
|
-
codeCandidate('account', { letters: nameLetters('Leo Andersen') }) // a person: Le0125
|
|
39
|
-
isCodeOf('list', '47KQWE') // true
|
|
40
|
-
codeKind('Ab12Cd') // 'item'
|
|
12
|
+
const candidate = codeCandidate('item')
|
|
13
|
+
codeKind(candidate) // 'item'
|
|
41
14
|
```
|
|
42
15
|
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
The four shapes hold about 2.5 billion codes, enough for every person, list and item, but not for every event a product records or every visit to it. The expanded version, `@0001-labs/idv1/advanced`, keeps six characters of the same 62 letters and digits and takes every code the four shapes leave free: any order at all, so long as it is none of them.
|
|
46
|
-
|
|
47
|
-
| Version | What | Shape | How many |
|
|
48
|
-
|---|---|---|---|
|
|
49
|
-
| Standard | account, product, list, item | the four shapes above | 2.5 billion, read as they are read |
|
|
50
|
-
| Advanced | event | any six letters or digits that make none of the four shapes, such as `k3Rw9Q` | 54.3 billion |
|
|
51
|
-
| Both | every code | six of 62 | 56.8 billion (62⁶) |
|
|
16
|
+
Use a unique constraint or a transaction to claim the candidate in your app.
|
|
52
17
|
|
|
53
|
-
|
|
54
|
-
- **It is drawn uniformly from cryptographic random numbers** (`secureRandom`), again while it makes a shape or spells a blocked word. Nobody types it and it never opens anything when scanned, though the scannable code can carry it.
|
|
55
|
-
- **Whether one is free is still the product's to check.** With 54 billion to draw from, two events rarely meet, but a product that keeps them by code looks before it keeps one.
|
|
18
|
+
## Templates
|
|
56
19
|
|
|
57
|
-
|
|
58
|
-
import { ADVANCED_SPACE, advancedCodeKind, eventCodeCandidate, isEventCode } from '@0001-labs/idv1/advanced'
|
|
20
|
+
Every code is six letters and digits, and its shape alone says what it names:
|
|
59
21
|
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
A product copies it alone with Sync 1's `advanced` export (`advanced.ts` with the `shapes.ts` and `words.ts` it reads against), or whole with `ids`.
|
|
22
|
+
| Shape | Pattern | Example | For |
|
|
23
|
+
|---|---|---|---|
|
|
24
|
+
| Account | `LLnnnn` | `Jo4712` | a person |
|
|
25
|
+
| Product | `LLLLnn` | `ABCD12` | a thing with a code printed on it |
|
|
26
|
+
| List | `nnLLLL` | `12ABCD` | something that holds things |
|
|
27
|
+
| Item | `LLnnXX` | `Ab12Cd` | one thing kept |
|
|
67
28
|
|
|
68
|
-
|
|
29
|
+
`L` is a letter, `n` a digit, and an item's last two are letters or digits but never both digits, or it would be an account. `codeCandidate(kind)` draws a code at random in a shape. An app can go further and lay a template over a shape, fixing some characters so a code also says which kind of thing in that app it is and which thing it names.
|
|
69
30
|
|
|
70
|
-
|
|
31
|
+
### Building a template
|
|
71
32
|
|
|
72
|
-
|
|
33
|
+
- **A fixed prefix per kind.** A list's two digits can mark the kind: `01ABCD` for projects, `02ABCD` for one kind, `03ABCD` for another.
|
|
34
|
+
- **Letters that read as the name.** The letters come from the thing's name, then vary letter by letter until the code is free: a project called Design system 1 is `01DESI`.
|
|
35
|
+
- **An owner's two letters lead an item.** An item starts with its owner's two letters, and the first digit can mark the kind inside that owner: `Ds10Bu` is a component of Design system 1, `Ez20Li` one of an app's tools.
|
|
36
|
+
- **People and agents take an account's shape.** Two letters from the name and four digits, `Le0125`, whether the account is a person or an agent.
|
|
73
37
|
|
|
74
|
-
|
|
75
|
-
- `src/space.ts` — `ID_SPACE`, how many codes of each kind there can be, and `idUsage`
|
|
76
|
-
- `src/words.ts` — the words and digits a product's code must never spell
|
|
77
|
-
- `src/advanced.ts` — the expanded version: an event's code, `eventCodeCandidate`, `advancedCodeKind` and `ADVANCED_SPACE`
|
|
78
|
-
- `src/scanCode.ts`, `src/scanCodeDrawing.ts` — the scannable code
|
|
79
|
-
- `tests/` — the shapes, the counts, the expanded version and the scannable code
|
|
38
|
+
A fixed character spends space. A list prefix leaves 26⁴ = 456,976 codes in capitals; an item template with fixed owner letters and a fixed kind digit leaves 10 × 26 × 26 = 6,760 per owner and kind if its last pair is a capital and a small letter. Fix only what a reader needs.
|
|
80
39
|
|
|
81
|
-
|
|
40
|
+
### Different apps, different templates
|
|
82
41
|
|
|
83
|
-
|
|
84
|
-
vp add @0001-labs/idv1
|
|
85
|
-
```
|
|
42
|
+
**Ezo draws.** People make millions of lists and items whose titles change, so nothing in those codes is meant to be read:
|
|
86
43
|
|
|
87
|
-
|
|
88
|
-
|
|
44
|
+
| Kind | Template | How |
|
|
45
|
+
|---|---|---|
|
|
46
|
+
| Account | `LLnnnn` | the person's name letters, then four drawn digits |
|
|
47
|
+
| Product | `LLLLnn` | drawn, again if the letters or digits are blocked |
|
|
48
|
+
| List | `nnLLLL` | drawn, in capitals |
|
|
49
|
+
| Item | `LLnnXX` | drawn |
|
|
89
50
|
|
|
90
|
-
|
|
91
|
-
const code = accountCodeCandidate(nameLetters('Leo Andersen')) // Le0125, say
|
|
92
|
-
```
|
|
51
|
+
**System derives.** An inventory of a few hundred named parts wants codes a reader can place on sight, so each kind has a template and the letters come from the name:
|
|
93
52
|
|
|
94
|
-
|
|
53
|
+
| Kind | Shape | Template | Example |
|
|
54
|
+
|---|---|---|---|
|
|
55
|
+
| Projects | list | `01ABCD` | `01DESI` |
|
|
56
|
+
| Stack | list | `02ABCD` | `02CONV` |
|
|
57
|
+
| Integrations | list | `03ABCD` | `03CLOU` |
|
|
58
|
+
| Components | item | owner, `1n`, name | `Ds10Bu` |
|
|
59
|
+
| MCP tools | item | owner, `2n`, name | `Ez20Li` |
|
|
60
|
+
| Engineers and agents | account | `Ab1234` | `Le0125` |
|
|
61
|
+
| Harnesses | product | `ABCD01` | `CLAU01` |
|
|
95
62
|
|
|
96
|
-
|
|
63
|
+
An app with many short-lived things should draw; one naming a small catalogue can derive. Either way a code, once given, stays when the name changes.
|
|
97
64
|
|
|
98
|
-
|
|
99
|
-
vp install
|
|
100
|
-
vp run check
|
|
101
|
-
vp test run
|
|
102
|
-
```
|
|
65
|
+
### Rules every template keeps
|
|
103
66
|
|
|
104
|
-
|
|
67
|
+
- **Six characters**, letters `A–Z a–z` and digits only.
|
|
68
|
+
- **Its shape.** Every code a template makes passes `isCodeOf(shape, code)`, and `codeKind(code)` reads it back as that shape.
|
|
69
|
+
- **No blocked words or digits.** Check all of a code's letters together with `blockedCodeLetters`, and a product's last two digits against `BLOCKED_CODE_DIGITS`, before taking a candidate.
|
|
70
|
+
- **Never two shapes for one code.** A template sits inside one shape, two templates in one app never make the same code, and a code names one thing: claim it with a unique constraint.
|
|
105
71
|
|
|
106
|
-
MIT
|
|
72
|
+
[MIT license](LICENSE)
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0001-labs/idv1",
|
|
3
|
-
"version": "0.3.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.3.2",
|
|
4
|
+
"description": "An ID system for short, memorable IDs that are easy to keep unique.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
8
|
-
"url": "https://github.com/0001-labs/
|
|
8
|
+
"url": "git+https://github.com/0001-labs/idv1.git"
|
|
9
9
|
},
|
|
10
10
|
"files": [
|
|
11
11
|
"src/",
|
package/src/advanced.ts
CHANGED
|
@@ -1,52 +1,23 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* IDv1 Advanced: the codes the four shapes leave free, for things there are
|
|
3
|
-
* far more of than accounts, lists or items, such as every event a product
|
|
4
|
-
* records or every visit to it. Still six characters of the same 62 letters
|
|
5
|
-
* and digits, capitals mattering, but in any order, so long as the code is
|
|
6
|
-
* none of the four shapes: `k3Rw9Q`, `7xP2mB`, `Q8z1aT`. One look still
|
|
7
|
-
* tells it apart from an account, a product, a list or an item, since none of
|
|
8
|
-
* them can be an event's code.
|
|
9
|
-
*
|
|
10
|
-
* - Six characters of 62 make 62⁶, 56.8 billion codes.
|
|
11
|
-
* - The four shapes, read as they are read (lists with small letters too),
|
|
12
|
-
* take 2.5 billion of them.
|
|
13
|
-
* - That leaves 54.3 billion for events, before the blocked words: 54 times
|
|
14
|
-
* as many as there are items, and enough for a product to give each event
|
|
15
|
-
* its own code for a long while.
|
|
16
|
-
*
|
|
17
|
-
* Nobody types an event's code and it is never scanned to open anything, so
|
|
18
|
-
* it is drawn uniformly, from the browser's or the server's cryptographic
|
|
19
|
-
* random numbers unless a test passes its own. Codes that spell a blocked word
|
|
20
|
-
* anywhere in them, capitals aside, are drawn again (`blockedCodeLetters` in
|
|
21
|
-
* words.ts), since an event's code may still be shown to someone.
|
|
22
|
-
*/
|
|
23
|
-
|
|
24
1
|
import { CODE_PATTERN, codeKind, type CodeKind } from './shapes'
|
|
25
2
|
import { blockedCodeLetters } from './words'
|
|
26
3
|
|
|
27
|
-
/** Every kind, the four shapes and an event. */
|
|
28
4
|
export type AdvancedCodeKind = CodeKind | 'event'
|
|
29
5
|
|
|
30
|
-
/** Any six of IDv1's characters, the outline every code has. */
|
|
31
6
|
export const ANY_CODE = /^[A-Za-z0-9]{6}$/
|
|
32
7
|
|
|
33
8
|
const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
|
|
34
9
|
|
|
35
|
-
/** An event's code: six letters or digits that make none of the four shapes. */
|
|
36
10
|
export const isEventCode = (value: string): boolean => ANY_CODE.test(value) && codeKind(value) === null
|
|
37
11
|
|
|
38
|
-
/** What a code names by its shape alone, events included, or null when it is no IDv1 code. */
|
|
39
12
|
export function advancedCodeKind(value: string): AdvancedCodeKind | null {
|
|
40
13
|
return codeKind(value) ?? (ANY_CODE.test(value) ? 'event' : null)
|
|
41
14
|
}
|
|
42
15
|
|
|
43
|
-
/** Whether a code has the shape of the kind a product expects, events included: `isAdvancedCodeOf('event', 'k3Rw9Q')`. */
|
|
44
16
|
export const isAdvancedCodeOf = (kind: AdvancedCodeKind, value: string): boolean =>
|
|
45
17
|
kind === 'event' ? isEventCode(value) : CODE_PATTERN[kind].test(value)
|
|
46
18
|
|
|
47
19
|
type Random = () => number
|
|
48
20
|
|
|
49
|
-
/** A number in [0, 1) from the platform's cryptographic random numbers, Math.random where there are none. */
|
|
50
21
|
export function secureRandom(): number {
|
|
51
22
|
const crypto = globalThis.crypto
|
|
52
23
|
if (!crypto?.getRandomValues) return Math.random()
|
|
@@ -55,12 +26,6 @@ export function secureRandom(): number {
|
|
|
55
26
|
return value[0] / 2 ** 32
|
|
56
27
|
}
|
|
57
28
|
|
|
58
|
-
/**
|
|
59
|
-
* An event's code to try: six characters drawn uniformly, again while they
|
|
60
|
-
* make one of the four shapes or spell a blocked word. Whether one is free is
|
|
61
|
-
* the product's to check, as with every other kind; with 54 billion to draw
|
|
62
|
-
* from, two events a product keeps will rarely meet.
|
|
63
|
-
*/
|
|
64
29
|
export function eventCodeCandidate(random: Random = secureRandom): string {
|
|
65
30
|
for (let attempt = 0; attempt < 1000; attempt++) {
|
|
66
31
|
let code = ''
|
|
@@ -70,16 +35,6 @@ export function eventCodeCandidate(random: Random = secureRandom): string {
|
|
|
70
35
|
throw new Error('No event code could be drawn.')
|
|
71
36
|
}
|
|
72
37
|
|
|
73
|
-
/**
|
|
74
|
-
* How many codes each version of IDv1 has room for. The standard version is
|
|
75
|
-
* `ID_SPACE` in space.ts, by kind, as its candidates draw them; the expanded
|
|
76
|
-
* version counts every six-character code, and events are what the four
|
|
77
|
-
* shapes leave, read as they are read (a list's small letters included).
|
|
78
|
-
*
|
|
79
|
-
* - All six-character codes: 62⁶, 56,800,235,584.
|
|
80
|
-
* - The four shapes as read: 52²·10⁴ + 52⁴·10² + 10²·52⁴ + 52²·10²·(62² − 10²), 2,501,740,800.
|
|
81
|
-
* - Events: the rest, 54,298,494,784, before the blocked words.
|
|
82
|
-
*/
|
|
83
38
|
export const ADVANCED_SPACE = (() => {
|
|
84
39
|
const letters = 52
|
|
85
40
|
const digits = 10
|
package/src/scanCode.ts
CHANGED
|
@@ -5,7 +5,6 @@ export { CODE_END_RADIUS, encodeScanCode, scanCodeColumns, scanCodePath, scanCod
|
|
|
5
5
|
const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
|
|
6
6
|
const idSpace = 62 ** 6
|
|
7
7
|
|
|
8
|
-
/** Validates the format byte and CRC; any single corrupted cell yields null. */
|
|
9
8
|
export function decodeScanCode(bits: readonly boolean[]): string | null {
|
|
10
9
|
if (bits.length !== 64) return null
|
|
11
10
|
const bytes: number[] = []
|
|
@@ -27,9 +26,7 @@ export function decodeScanCode(bits: readonly boolean[]): string | null {
|
|
|
27
26
|
}
|
|
28
27
|
|
|
29
28
|
export const isListScanId = (id: string): boolean => isListCode(id)
|
|
30
|
-
/** A person's code: a name's `LLnnnn` or a product's `LLLLnn` (`shapes.ts`). */
|
|
31
29
|
export const isUserScanId = (id: string): boolean => isAccountCode(id)
|
|
32
|
-
/** Scanning opens lists and profiles; item codes are not scannable. */
|
|
33
30
|
export const isSupportedScanId = (id: string): boolean => isListScanId(id) || isUserScanId(id)
|
|
34
31
|
|
|
35
32
|
export type ScanRect = { x: number; y: number; width: number; height: number }
|
|
@@ -42,7 +39,6 @@ const insetRect = (rect: ScanRect, dx: number, dy: number): ScanRect => ({
|
|
|
42
39
|
const offsetRect = (rect: ScanRect, dx: number, dy: number): ScanRect => ({ ...rect, x: rect.x + dx, y: rect.y + dy })
|
|
43
40
|
const clamp = (value: number, low: number, high: number) => Math.max(low, Math.min(high, value))
|
|
44
41
|
|
|
45
|
-
/** Reads only 576 luminance samples from the guide rectangle (default: centered, 80% wide, 4:1). */
|
|
46
42
|
export function sampleScanCode(width: number, height: number, luminance: Luminance, rect?: ScanRect): string | null {
|
|
47
43
|
if (width < 80 || height < 20) return null
|
|
48
44
|
const guideWidth = rect?.width ?? width * 0.8
|
|
@@ -69,11 +65,6 @@ export function sampleScanCode(width: number, height: number, luminance: Luminan
|
|
|
69
65
|
return decodeScanCode(levels.map(level => level < mid)) ?? decodeScanCode(levels.map(level => level > mid))
|
|
70
66
|
}
|
|
71
67
|
|
|
72
|
-
/**
|
|
73
|
-
* Where sixty-four levels part into two tones: the cut that leaves each side
|
|
74
|
-
* closest to its own middle, so a cell buried under a letter does not move
|
|
75
|
-
* it as the middle of the darkest and the lightest would.
|
|
76
|
-
*/
|
|
77
68
|
function partedLevels(levels: readonly number[]): number | null {
|
|
78
69
|
const sorted = [...levels].sort((a, b) => a - b)
|
|
79
70
|
if (sorted[sorted.length - 1] - sorted[0] <= 8) return null
|
|
@@ -90,12 +81,6 @@ function partedLevels(levels: readonly number[]): number | null {
|
|
|
90
81
|
return cut
|
|
91
82
|
}
|
|
92
83
|
|
|
93
|
-
/**
|
|
94
|
-
* The levels measured from the field's own tone where each column stands:
|
|
95
|
-
* the lightest (or, under light words, the darkest) of a column and its
|
|
96
|
-
* neighbours. A field whose colour turns across it, a spectrum month's
|
|
97
|
-
* header cell, or a shadow over half the code then parts as a plain one does.
|
|
98
|
-
*/
|
|
99
84
|
function levelledColumns(levels: readonly number[], lightest: boolean): number[] {
|
|
100
85
|
const ground: number[] = []
|
|
101
86
|
for (let column = 0; column < scanCodeColumns; column++) {
|
|
@@ -111,31 +96,16 @@ function levelledColumns(levels: readonly number[], lightest: boolean): number[]
|
|
|
111
96
|
return levels.map((level, index) => level - ground[index % scanCodeColumns])
|
|
112
97
|
}
|
|
113
98
|
|
|
114
|
-
/** The share of a cell's samples its own tone is read at: its lighter part under dark words, its darker under light ones. */
|
|
115
99
|
const WRITTEN_SHARES = [0.8, 0.2, 0.95, 0.05] as const
|
|
116
100
|
|
|
117
|
-
/** A code's four corners in the frame: top left, top right, bottom right, bottom left. */
|
|
118
101
|
export type ScanCorners = readonly [x0: number, y0: number, x1: number, y1: number, x2: number, y2: number, x3: number, y3: number]
|
|
119
102
|
|
|
120
103
|
const rectCorners = (rect: ScanRect): ScanCorners => [rect.x, rect.y, rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height, rect.x, rect.y + rect.height]
|
|
121
104
|
|
|
122
|
-
/**
|
|
123
|
-
* Reads a code that has words written over it: a calendar's header cell is
|
|
124
|
-
* its sheet's code, two tones of the cell's colour, with Jan 2027 printed on
|
|
125
|
-
* top. The middle of a cell may then lie under a letter, so every cell is
|
|
126
|
-
* read from many points across its middle and the words' ink left out: dark
|
|
127
|
-
* words leave a cell's lighter part its own, light words its darker part.
|
|
128
|
-
* The two tones are parted where they cluster (`partedLevels`), plain and
|
|
129
|
-
* then levelled column by column (`levelledColumns`). The code is given by
|
|
130
|
-
* its rectangle, or by its four corners where the page is held askew. So
|
|
131
|
-
* many readings of one place ask more of the check than one does, so only an
|
|
132
|
-
* ID a scan can open is taken.
|
|
133
|
-
*/
|
|
134
105
|
export function sampleWrittenScanCode(width: number, height: number, luminance: Luminance, place: ScanRect | ScanCorners): string | null {
|
|
135
106
|
const [x0, y0, x1, y1, x2, y2, x3, y3] = 'width' in place ? rectCorners(place) : place
|
|
136
107
|
const cell = Math.min(Math.hypot(x1 - x0, y1 - y0), Math.hypot(x2 - x3, y2 - y3)) / scanCodeColumns
|
|
137
108
|
if (cell < 5) return null
|
|
138
|
-
// The cells, each read from many points across `inner` of it, darkest first.
|
|
139
109
|
const sampled = (inner: number): number[][] => {
|
|
140
110
|
const across = Math.max(2, Math.min(7, Math.floor(cell * inner)))
|
|
141
111
|
const cells: number[][] = []
|
|
@@ -161,8 +131,6 @@ export function sampleWrittenScanCode(width: number, height: number, luminance:
|
|
|
161
131
|
const id = decodeScanCode(dark as boolean[]) ?? decodeScanCode(dark.map(bit => !bit))
|
|
162
132
|
return id && isSupportedScanId(id) ? id : null
|
|
163
133
|
}
|
|
164
|
-
// Words printed whole over the code: the middle of each cell, where a
|
|
165
|
-
// neighbour's tone never reaches, read at its lighter and its darker parts.
|
|
166
134
|
const middles = sampled(0.6)
|
|
167
135
|
for (const share of WRITTEN_SHARES) {
|
|
168
136
|
const read = middles.map(values => values[Math.round((values.length - 1) * share)])
|
|
@@ -180,16 +148,6 @@ export function sampleWrittenScanCode(width: number, height: number, luminance:
|
|
|
180
148
|
}, cell, taken)
|
|
181
149
|
}
|
|
182
150
|
|
|
183
|
-
/**
|
|
184
|
-
* Words cut out of the code itself, two colours and no more: the words
|
|
185
|
-
* change sides cell by cell, ink on the cell's colour and the cell's colour
|
|
186
|
-
* on the ink, so a cell is the colour most of it is. Where a letter takes
|
|
187
|
-
* about half a cell neither colour is most of it; such cells, a few at the
|
|
188
|
-
* most, are read both ways, fewest changed first, and the check says which
|
|
189
|
-
* reading is the code.
|
|
190
|
-
*
|
|
191
|
-
* `at` gives the light at a place in the code, 0 to 1 across and down.
|
|
192
|
-
*/
|
|
193
151
|
function sampleCutScanCode(at: (u: number, v: number) => number, cell: number, taken: (dark: readonly boolean[]) => string | null): string | null {
|
|
194
152
|
const n = Math.max(4, Math.min(8, Math.round(cell * 0.8)))
|
|
195
153
|
const count = scanCodeColumns * scanCodeRows, each = n * n
|
|
@@ -202,7 +160,6 @@ function sampleCutScanCode(at: (u: number, v: number) => number, cell: number, t
|
|
|
202
160
|
}
|
|
203
161
|
}
|
|
204
162
|
}
|
|
205
|
-
// Dark or light is judged against a column and its neighbours, since a cell's colour may turn across the code.
|
|
206
163
|
const share = new Float32Array(count)
|
|
207
164
|
for (let column = 0; column < scanCodeColumns; column++) {
|
|
208
165
|
const near: number[] = []
|
|
@@ -237,11 +194,9 @@ function sampleCutScanCode(at: (u: number, v: number) => number, cell: number, t
|
|
|
237
194
|
return null
|
|
238
195
|
}
|
|
239
196
|
|
|
240
|
-
/** How near half of a cell the words may take before it is read both ways. */
|
|
241
197
|
const WRITTEN_UNSURE = 0.2
|
|
242
198
|
const ones = (value: number): number => { let count = 0; for (; value; value &= value - 1) count++; return count }
|
|
243
199
|
|
|
244
|
-
/** A line through points that mostly lie on it: `b` the middle of every pair's slope, `a` the middle of what is left, so a stray point moves neither. */
|
|
245
200
|
function lineThrough(points: readonly (readonly [number, number])[]): { a: number; b: number } | null {
|
|
246
201
|
if (points.length < 3) return null
|
|
247
202
|
const middle = (values: number[]) => values.sort((p, q) => p - q)[Math.floor(values.length / 2)]
|
|
@@ -256,15 +211,6 @@ function lineThrough(points: readonly (readonly [number, number])[]): { a: numbe
|
|
|
256
211
|
return { a: middle(points.map(([t, value]) => value - b * t)), b }
|
|
257
212
|
}
|
|
258
213
|
|
|
259
|
-
/**
|
|
260
|
-
* Finds a code under words anywhere in the frame and reads it. Its cell is a
|
|
261
|
-
* field of colour on its paper, four to one: every other pixel is weighed,
|
|
262
|
-
* the pixels that stand apart from the paper (by their colour, or by their
|
|
263
|
-
* light against the frame's commonest and its lightest tones) are gathered
|
|
264
|
-
* into the fields that touch, and a field of a code's shape has a line laid
|
|
265
|
-
* along each of its four edges, so a page held askew is read along its own
|
|
266
|
-
* corners and not the frame's (`sampleWrittenScanCode`).
|
|
267
|
-
*/
|
|
268
214
|
export function locateWrittenScanCode(width: number, height: number, luminance: Luminance, chroma: Chroma): ScanFound | null {
|
|
269
215
|
const step = 2, columns = Math.floor(width / step), rows = Math.floor(height / step)
|
|
270
216
|
if (columns < 40 || rows < 10) return null
|
|
@@ -274,7 +220,6 @@ export function locateWrittenScanCode(width: number, height: number, luminance:
|
|
|
274
220
|
for (let y = 0, index = 0; y < rows; y++) {
|
|
275
221
|
for (let x = 0; x < columns; x++, index++) histogram[levels[index] = clamp(Math.round(luminance(x * step, y * step)), 0, 255)]++
|
|
276
222
|
}
|
|
277
|
-
// The paper: the commonest tone in the frame, and where a wall or a desk is commoner, the tone a tenth of the frame is lighter than.
|
|
278
223
|
let paper = 0
|
|
279
224
|
for (let level = 1; level < 256; level++) if (histogram[level] > histogram[paper]) paper = level
|
|
280
225
|
let light = 255
|
|
@@ -283,7 +228,6 @@ export function locateWrittenScanCode(width: number, height: number, luminance:
|
|
|
283
228
|
for (const ground of Math.abs(paper - light) > 8 ? [paper, light] : [paper]) {
|
|
284
229
|
for (const apart of [14, 30]) masks.push(index => Math.abs(levels[index] - ground) > apart)
|
|
285
230
|
}
|
|
286
|
-
// 0 unseen, -1 not of the mask, else the field it belongs to.
|
|
287
231
|
const fields = new Int32Array(size)
|
|
288
232
|
const stack = new Int32Array(size)
|
|
289
233
|
for (const mask of masks) {
|
|
@@ -309,11 +253,9 @@ export function locateWrittenScanCode(width: number, height: number, luminance:
|
|
|
309
253
|
if (mask(next)) { fields[next] = field; stack[depth++] = next } else fields[next] = -1
|
|
310
254
|
}
|
|
311
255
|
}
|
|
312
|
-
// A code's shape, however the page leans: about four to one, and mostly filled, its words the only holes.
|
|
313
256
|
const w = right - left + 1, h = bottom - top + 1
|
|
314
257
|
if (w * step < 80 || h * step < 16 || w / h < 2.6 || w / h > 5 || count < w * h * 0.5) continue
|
|
315
258
|
const of = (x: number, y: number) => fields[y * columns + x] === field
|
|
316
|
-
// A line along each edge, from where the field begins a tenth in from its corners, which are rounded.
|
|
317
259
|
const edge = (along: number, from: number, to: number, crosswise: boolean): number | null => {
|
|
318
260
|
const direction = to > from ? 1 : -1
|
|
319
261
|
for (let at = from; at !== to + direction; at += direction) {
|
|
@@ -335,7 +277,6 @@ export function locateWrittenScanCode(width: number, height: number, luminance:
|
|
|
335
277
|
const leftLine = points(7, top, h, y => edge(y, left, right, true))
|
|
336
278
|
const rightLine = points(7, top, h, y => edge(y, right, left, true))
|
|
337
279
|
if (!topLine || !bottomLine || !leftLine || !rightLine) continue
|
|
338
|
-
// Where an edge along (y = a + b·x) meets an edge down (x = a + b·y).
|
|
339
280
|
const meet = (alongLine: { a: number; b: number }, downLine: { a: number; b: number }): [number, number] => {
|
|
340
281
|
const x = (downLine.a + downLine.b * alongLine.a) / (1 - downLine.b * alongLine.b)
|
|
341
282
|
return [x, alongLine.a + alongLine.b * x]
|
|
@@ -343,7 +284,6 @@ export function locateWrittenScanCode(width: number, height: number, luminance:
|
|
|
343
284
|
const corners = [meet(topLine, leftLine), meet(topLine, rightLine), meet(bottomLine, rightLine), meet(bottomLine, leftLine)]
|
|
344
285
|
const middleX = (corners[0][0] + corners[1][0] + corners[2][0] + corners[3][0]) / 4
|
|
345
286
|
const middleY = (corners[0][1] + corners[1][1] + corners[2][1] + corners[3][1]) / 4
|
|
346
|
-
// The field's edge is soft in a photograph: read it as found, then a little in and a little out.
|
|
347
287
|
for (const scale of [1, 0.97, 1.03]) {
|
|
348
288
|
const place = corners.flatMap(([x, y]) => [middleX + (x - middleX) * scale, middleY + (y - middleY) * scale]) as unknown as ScanCorners
|
|
349
289
|
const id = sampleWrittenScanCode(width, height, luminance, place)
|
|
@@ -354,7 +294,6 @@ export function locateWrittenScanCode(width: number, height: number, luminance:
|
|
|
354
294
|
return null
|
|
355
295
|
}
|
|
356
296
|
|
|
357
|
-
/** Groups disconnected accent cells into horizontal 4:1 code regions, without a finder border. */
|
|
358
297
|
export function scanCodeRegions(width: number, height: number, foreground: Chroma): ScanRect[] {
|
|
359
298
|
const step = 2, columns = Math.floor(width / step), rows = Math.floor(height / step)
|
|
360
299
|
if (columns <= 0 || rows <= 0) return []
|
|
@@ -377,15 +316,6 @@ export function scanCodeRegions(width: number, height: number, foreground: Chrom
|
|
|
377
316
|
seen.add(key)
|
|
378
317
|
result.push({ x: left * step, y: top * step, width: w, height: h })
|
|
379
318
|
}
|
|
380
|
-
/**
|
|
381
|
-
* A code standing beside something else on its rows, the year large on a
|
|
382
|
-
* calendar's cover or a product's name before a sheet's code, is not the whole
|
|
383
|
-
* of its band: the band is as tall as its tallest thing. So each run
|
|
384
|
-
* across a band is looked at again by itself: drawn in to the rows and
|
|
385
|
-
* columns its own ink stands on, parted where it has a gap wider than it
|
|
386
|
-
* is now tall, and each part looked at the same way; and where a part is
|
|
387
|
-
* still wider than a code, the code may be its left or its right end.
|
|
388
|
-
*/
|
|
389
319
|
const cut = (left: number, top: number, right: number, bottom: number, depth: number) => {
|
|
390
320
|
const inked = (x: number, from: number, to: number) => { for (let row = from; row <= to; row++) if (mask[row * columns + x]) return true; return false }
|
|
391
321
|
const lined = (row: number) => { let count = 0; for (let x = left; x <= right; x++) if (mask[row * columns + x] && ++count >= 2) return true; return false }
|
|
@@ -397,7 +327,6 @@ export function scanCodeRegions(width: number, height: number, foreground: Chrom
|
|
|
397
327
|
if (h * step < 8 || (right - left + 1) * step < 48) return
|
|
398
328
|
take(left, top, right, bottom)
|
|
399
329
|
if (depth <= 0) return
|
|
400
|
-
// Parted across, where a gap is wider than the part is tall.
|
|
401
330
|
const parts: [number, number][] = []
|
|
402
331
|
let from = left, last = left
|
|
403
332
|
for (let x = left + 1; x <= right; x++) {
|
|
@@ -407,7 +336,6 @@ export function scanCodeRegions(width: number, height: number, foreground: Chrom
|
|
|
407
336
|
}
|
|
408
337
|
parts.push([from, last])
|
|
409
338
|
if (parts.length > 1) { for (const [start, end] of parts) cut(start, top, end, bottom, depth - 1); return }
|
|
410
|
-
// Parted down, where more than three rows stand empty.
|
|
411
339
|
const bands: [number, number][] = []
|
|
412
340
|
let first = top, lastRow = top
|
|
413
341
|
for (let row = top + 1; row <= bottom; row++) {
|
|
@@ -417,7 +345,6 @@ export function scanCodeRegions(width: number, height: number, foreground: Chrom
|
|
|
417
345
|
}
|
|
418
346
|
bands.push([first, lastRow])
|
|
419
347
|
if (bands.length > 1) { for (const [start, end] of bands) cut(left, start, right, end, depth - 1); return }
|
|
420
|
-
// Wider than a code: the code may be either end of it.
|
|
421
348
|
if ((right - left + 1) / h > 4.6) {
|
|
422
349
|
cut(right - 4 * h + 1, top, right, bottom, 0)
|
|
423
350
|
cut(left, top, left + 4 * h - 1, bottom, 0)
|
|
@@ -454,23 +381,18 @@ export function scanCodeRegions(width: number, height: number, foreground: Chrom
|
|
|
454
381
|
return result
|
|
455
382
|
}
|
|
456
383
|
|
|
457
|
-
/** A code read from a frame, and the rectangle it was read from. */
|
|
458
384
|
export type ScanFound = { id: string; rect: ScanRect }
|
|
459
385
|
|
|
460
|
-
/** Locates and decodes an upright code anywhere in a camera frame; mirrors the native reader. */
|
|
461
386
|
export function readScanFrame(width: number, height: number, luminance: Luminance, chroma: Chroma): string | null {
|
|
462
387
|
return locateScanFrame(width, height, luminance, chroma)?.id ?? null
|
|
463
388
|
}
|
|
464
389
|
|
|
465
|
-
/** As `readScanFrame`, saying where in the frame the code stands. */
|
|
466
390
|
export function locateScanFrame(width: number, height: number, luminance: Luminance, chroma: Chroma): ScanFound | null {
|
|
467
|
-
// Every rectangle tried, kept for a second look past words.
|
|
468
391
|
const tried: ScanRect[] = []
|
|
469
392
|
const read = (bounds: ScanRect): ScanFound | null => {
|
|
470
393
|
tried.push(bounds)
|
|
471
394
|
for (const fraction of [0, 0.05]) {
|
|
472
395
|
const rect = insetRect(bounds, bounds.width * fraction, bounds.height * fraction)
|
|
473
|
-
// Detection samples every second pixel; refine its origin before reading tiny cells.
|
|
474
396
|
for (const dy of [0, -1, 1]) {
|
|
475
397
|
for (const dx of [0, -1, 1]) {
|
|
476
398
|
const at = offsetRect(rect, dx, dy)
|
|
@@ -481,13 +403,11 @@ export function locateScanFrame(width: number, height: number, luminance: Lumina
|
|
|
481
403
|
}
|
|
482
404
|
return null
|
|
483
405
|
}
|
|
484
|
-
// The page itself may be chromatic too; exclude its dark pixels from the accent mask.
|
|
485
406
|
const colored = scanCodeRegions(width, height, (x, y) => luminance(x, y) > 70 && chroma(x, y))
|
|
486
407
|
for (const bounds of colored) {
|
|
487
408
|
const id = read(bounds)
|
|
488
409
|
if (id) return id
|
|
489
410
|
}
|
|
490
|
-
// Neutral accents have no chroma. Locate their light/dark rectangle using luminance.
|
|
491
411
|
let darkest = 255, lightest = 0
|
|
492
412
|
for (let y = 0; y < height; y += 8) {
|
|
493
413
|
for (let x = 0; x < width; x += 8) {
|
|
@@ -508,10 +428,6 @@ export function locateScanFrame(width: number, height: number, luminance: Lumina
|
|
|
508
428
|
const w = width * 0.8
|
|
509
429
|
const guide = read({ x: (width - w) / 2, y: (height - w / 4) / 2, width: w, height: w / 4 })
|
|
510
430
|
if (guide) return guide
|
|
511
|
-
// Nothing read plainly: a code under words, a calendar's header cell. As a
|
|
512
|
-
// field of colour on its paper first (`locateWrittenScanCode`); then, where
|
|
513
|
-
// its cells stand on a cell as white as the paper, in the rectangles its
|
|
514
|
-
// ink was found in.
|
|
515
431
|
const field = locateWrittenScanCode(width, height, luminance, chroma)
|
|
516
432
|
if (field) return field
|
|
517
433
|
for (const bounds of tried) {
|
|
@@ -525,12 +441,10 @@ export function locateScanFrame(width: number, height: number, luminance: Lumina
|
|
|
525
441
|
return null
|
|
526
442
|
}
|
|
527
443
|
|
|
528
|
-
/** Reads an upright RGBA frame, deriving luminance and chroma the way the native YCbCr reader does. */
|
|
529
444
|
export function readRgbaScanFrame(rgba: Uint8Array | Uint8ClampedArray, width: number, height: number): string | null {
|
|
530
445
|
return locateRgbaScanFrame(rgba, width, height)?.id ?? null
|
|
531
446
|
}
|
|
532
447
|
|
|
533
|
-
/** The luminance of an RGBA frame, as the reader weighs it. */
|
|
534
448
|
export function rgbaLuminance(rgba: Uint8Array | Uint8ClampedArray, width: number): Luminance {
|
|
535
449
|
return (x, y) => {
|
|
536
450
|
const p = (y * width + x) * 4
|
|
@@ -538,7 +452,6 @@ export function rgbaLuminance(rgba: Uint8Array | Uint8ClampedArray, width: numbe
|
|
|
538
452
|
}
|
|
539
453
|
}
|
|
540
454
|
|
|
541
|
-
/** As `readRgbaScanFrame`, saying where in the frame the code stands. */
|
|
542
455
|
export function locateRgbaScanFrame(rgba: Uint8Array | Uint8ClampedArray, width: number, height: number): ScanFound | null {
|
|
543
456
|
if (rgba.length < width * height * 4) return null
|
|
544
457
|
const luminance = rgbaLuminance(rgba, width)
|
|
@@ -552,7 +465,6 @@ export function locateRgbaScanFrame(rgba: Uint8Array | Uint8ClampedArray, width:
|
|
|
552
465
|
return locateScanFrame(width, height, luminance, chroma)
|
|
553
466
|
}
|
|
554
467
|
|
|
555
|
-
/** Accepts an ID only after three consecutive matching frames. */
|
|
556
468
|
export class StableScan {
|
|
557
469
|
private last: string | null = null
|
|
558
470
|
private count = 0
|
package/src/scanCodeDrawing.ts
CHANGED
|
@@ -1,9 +1,7 @@
|
|
|
1
|
-
/** Encoding and SVG artwork; camera pixel sampling stays in scanCode.ts. */
|
|
2
1
|
const alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
|
|
3
2
|
|
|
4
3
|
export const scanCodeColumns = 16
|
|
5
4
|
export const scanCodeRows = 4
|
|
6
|
-
/** The joined code's corners, a tenth of a cell: half an item cell's, 2 of its 20. */
|
|
7
5
|
export const CODE_END_RADIUS = 0.1
|
|
8
6
|
|
|
9
7
|
export function scanCodeChecksum(bytes: readonly number[]): number {
|
|
@@ -15,7 +13,6 @@ export function scanCodeChecksum(bytes: readonly number[]): number {
|
|
|
15
13
|
return crc
|
|
16
14
|
}
|
|
17
15
|
|
|
18
|
-
/** Format 3: 16 × 4 upright cells, matching the iOS scanner and playground. */
|
|
19
16
|
export function encodeScanCode(id: string): boolean[] | null {
|
|
20
17
|
if (!/^[A-Za-z0-9]{6}$/.test(id)) return null
|
|
21
18
|
let value = 0
|
|
@@ -27,23 +24,6 @@ export function encodeScanCode(id: string): boolean[] | null {
|
|
|
27
24
|
return bytes.flatMap(byte => Array.from({ length: 8 }, (_, bit) => !!(byte & (1 << (7 - bit)))))
|
|
28
25
|
}
|
|
29
26
|
|
|
30
|
-
/**
|
|
31
|
-
* A code's inked cells as one SVG path, each row's run of neighbours one
|
|
32
|
-
* rectangle. Drawn as separate squares, every square's edge is softened on
|
|
33
|
-
* its own and a hairline of the backing shows where two meet; one path is
|
|
34
|
-
* softened only at its outline. `ink` says which cells are inked (a list's
|
|
35
|
-
* code inks its clear bits), `cell` is a cell's size and `x`, `y` where the
|
|
36
|
-
* code's corner stands.
|
|
37
|
-
*
|
|
38
|
-
* With a `radius` (a share of a cell) every corner is rounded, the ink's and
|
|
39
|
-
* the backing's alike, as item cells are: a run's corner is rounded when
|
|
40
|
-
* nothing inked stands against it above or below (a lone dot round all
|
|
41
|
-
* round, whatever touches it across a corner), and stays square where the
|
|
42
|
-
* shape carries on into the next row; and where the ink turns an inside
|
|
43
|
-
* corner the backing's corner is rounded by filling it with ink. The reader
|
|
44
|
-
* samples the middle of each cell, so corners rounded by less than half a
|
|
45
|
-
* cell never change what it reads.
|
|
46
|
-
*/
|
|
47
27
|
export function scanCodePath(bits: readonly boolean[], { ink = (bit: boolean) => !bit, cell = 1, x = 0, y = 0, radius = 0 }: { ink?: (bit: boolean) => boolean; cell?: number; x?: number; y?: number; radius?: number } = {}): string {
|
|
48
28
|
const round = (value: number) => Math.round(value * 1e4) / 1e4
|
|
49
29
|
const inked = (row: number, column: number) =>
|
|
@@ -60,9 +40,6 @@ export function scanCodePath(bits: readonly boolean[], { ink = (bit: boolean) =>
|
|
|
60
40
|
d += `M${round(left)} ${round(top)}h${round(right - left)}v${round(cell)}h${round(left - right)}z`
|
|
61
41
|
continue
|
|
62
42
|
}
|
|
63
|
-
// A corner is rounded wherever the ink stops both ways, straight across
|
|
64
|
-
// and along: a lone dot is round at every corner, even where another
|
|
65
|
-
// touches it across a corner.
|
|
66
43
|
const end = (facing: number, inside: number) => !inked(facing, inside) ? r : 0
|
|
67
44
|
const tl = end(row - 1, start)
|
|
68
45
|
const tr = end(row - 1, column - 1)
|
|
@@ -76,10 +53,6 @@ export function scanCodePath(bits: readonly boolean[], { ink = (bit: boolean) =>
|
|
|
76
53
|
}
|
|
77
54
|
}
|
|
78
55
|
if (!r) return d
|
|
79
|
-
// The backing's corners round too: where the ink turns an inside corner,
|
|
80
|
-
// three cells of it round a clear one, the clear cell's corner is filled
|
|
81
|
-
// with ink to the same radius. Where the ink only touches across a corner,
|
|
82
|
-
// the ink's own corners are rounded instead.
|
|
83
56
|
for (let row = 0; row < scanCodeRows; row++) {
|
|
84
57
|
for (let column = 0; column < scanCodeColumns; column++) {
|
|
85
58
|
if (inked(row, column)) continue
|
|
@@ -88,7 +61,6 @@ export function scanCodePath(bits: readonly boolean[], { ink = (bit: boolean) =>
|
|
|
88
61
|
if (!inked(row + dy, column) || !inked(row, column + dx) || !inked(row + dy, column + dx)) continue
|
|
89
62
|
const cornerX = left + (dx > 0 ? cell : 0), cornerY = top + (dy > 0 ? cell : 0)
|
|
90
63
|
const alongX = cornerX - dx * r, alongY = cornerY - dy * r
|
|
91
|
-
// From the corner along the cell's edge, round the arc to its other edge, and back.
|
|
92
64
|
const sweep = dx * dy > 0 ? 0 : 1
|
|
93
65
|
d += `M${round(cornerX)} ${round(cornerY)}H${round(alongX)}A${round(r)} ${round(r)} 0 0 ${sweep} ${round(cornerX)} ${round(alongY)}Z`
|
|
94
66
|
}
|
package/src/shapes.ts
CHANGED
|
@@ -1,35 +1,11 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* IDv1: short codes whose shape says what they name, so one address,
|
|
3
|
-
* `example.com/<code>`, can be an account, a list or an item and never two of
|
|
4
|
-
* them. Every code is six characters. Capitals matter: Ab12Cd and ab12cd are
|
|
5
|
-
* two codes.
|
|
6
|
-
*
|
|
7
|
-
* - An account is two letters and four digits, the letters from the person's
|
|
8
|
-
* name: Jo4712.
|
|
9
|
-
* - A product is four letters and two digits: AbCd12. It is always scanned,
|
|
10
|
-
* never typed, and whoever signs up with a product's code may hold it as
|
|
11
|
-
* their account's code, so it is an account's shape too.
|
|
12
|
-
* - A list is two digits and four letters: 12ABCD. New lists draw capitals
|
|
13
|
-
* only; older ones may hold small letters, and both are read.
|
|
14
|
-
* - An item is two letters, two digits and two letters or digits, not both
|
|
15
|
-
* digits (that would be an account): Ab12Cd.
|
|
16
|
-
*
|
|
17
|
-
* No two shapes can be the same code.
|
|
18
|
-
*/
|
|
19
|
-
|
|
20
1
|
export const LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
|
|
21
2
|
export const CAPITALS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
|
22
3
|
export const DIGITS = '0123456789'
|
|
23
4
|
|
|
24
|
-
/** An account's code made from a name: Jo4712. */
|
|
25
5
|
export const NAME_CODE = /^[A-Za-z]{2}\d{4}$/
|
|
26
|
-
/** A product's code: AbCd12. */
|
|
27
6
|
export const PRODUCT_CODE = /^[A-Za-z]{4}\d{2}$/
|
|
28
|
-
/** Any code an account may hold: a name's or a product's. */
|
|
29
7
|
export const ACCOUNT_CODE = /^(?:[A-Za-z]{2}\d{4}|[A-Za-z]{4}\d{2})$/
|
|
30
|
-
/** A list's code: 12ABCD, small letters read too. */
|
|
31
8
|
export const LIST_CODE = /^\d{2}[A-Za-z]{4}$/
|
|
32
|
-
/** An item's code: Ab12Cd, with at least one letter in the last two. */
|
|
33
9
|
export const ITEM_CODE = /^[A-Za-z]{2}\d{2}(?:[A-Za-z][A-Za-z0-9]|\d[A-Za-z])$/
|
|
34
10
|
|
|
35
11
|
import { blockedProductCode } from './words'
|
|
@@ -41,7 +17,6 @@ export const isProductCode = (value: string): boolean => PRODUCT_CODE.test(value
|
|
|
41
17
|
export const isListCode = (value: string): boolean => LIST_CODE.test(value)
|
|
42
18
|
export const isItemCode = (value: string): boolean => ITEM_CODE.test(value)
|
|
43
19
|
|
|
44
|
-
/** What a code names by its shape alone, or null when it is no IDv1 code. A product's shape reads as `product`. */
|
|
45
20
|
export function codeKind(value: string): CodeKind | null {
|
|
46
21
|
if (NAME_CODE.test(value)) return 'account'
|
|
47
22
|
if (PRODUCT_CODE.test(value)) return 'product'
|
|
@@ -53,10 +28,8 @@ export function codeKind(value: string): CodeKind | null {
|
|
|
53
28
|
type Random = () => number
|
|
54
29
|
const pick = (chars: string, random: Random) => chars[Math.floor(random() * chars.length)]
|
|
55
30
|
|
|
56
|
-
/** Letters a Latin alphabet writes with a mark or as one of its own, as plain ones. */
|
|
57
31
|
const PLAIN: Record<string, string> = { ø: 'o', æ: 'a', œ: 'o', ß: 's', ð: 'd', þ: 't', ł: 'l', đ: 'd', ı: 'i' }
|
|
58
32
|
|
|
59
|
-
/** The plain Latin letters of a word, in order: Åse is ase, Øystein oystein. */
|
|
60
33
|
function latinLetters(value: string): string {
|
|
61
34
|
return [...value.normalize('NFKD').toLowerCase()]
|
|
62
35
|
.map(letter => PLAIN[letter] ?? letter)
|
|
@@ -64,11 +37,6 @@ function latinLetters(value: string): string {
|
|
|
64
37
|
.replace(/[^a-z]/g, '')
|
|
65
38
|
}
|
|
66
39
|
|
|
67
|
-
/**
|
|
68
|
-
* The two letters an account's code starts with: from the first name, a
|
|
69
|
-
* capital and a small one (Leo is Le, Henrik He), else from the email
|
|
70
|
-
* address, else none, and the caller draws them at random.
|
|
71
|
-
*/
|
|
72
40
|
export function nameLetters(name: string, email = ''): string | null {
|
|
73
41
|
const words = name.trim().split(/\s+/)
|
|
74
42
|
for (const source of [words[0] ?? '', name, email.split('@')[0] ?? '']) {
|
|
@@ -78,13 +46,6 @@ export function nameLetters(name: string, email = ''): string | null {
|
|
|
78
46
|
return null
|
|
79
47
|
}
|
|
80
48
|
|
|
81
|
-
/**
|
|
82
|
-
* The codes to try are drawn at random and kept when nothing holds them yet;
|
|
83
|
-
* whether one is free is the product's to check. `random` gives numbers in
|
|
84
|
-
* [0, 1), Math.random unless a test passes its own.
|
|
85
|
-
*/
|
|
86
|
-
|
|
87
|
-
/** An account's code: the name's letters (or two at random) and four digits. */
|
|
88
49
|
export function accountCodeCandidate(letters: string | null, random: Random = Math.random): string {
|
|
89
50
|
const start = letters ?? pick(LETTERS, random) + pick(LETTERS, random)
|
|
90
51
|
for (;;) {
|
|
@@ -93,20 +54,10 @@ export function accountCodeCandidate(letters: string | null, random: Random = Ma
|
|
|
93
54
|
}
|
|
94
55
|
}
|
|
95
56
|
|
|
96
|
-
/**
|
|
97
|
-
* Account codes kept for one person or role in every product, never drawn for
|
|
98
|
-
* anyone else, so the same account is the same code everywhere and easy to
|
|
99
|
-
* leave out of a product's figures: Joachim is Jo4712 (jaa90@icloud.com) and
|
|
100
|
-
* Jo0001 (joachim@0001.dev), the onboarding test account, which walks through
|
|
101
|
-
* a product as a newcomer would, is On0001 (joachim+onboarding@0001.dev), and
|
|
102
|
-
* the test account is Te0001 (joachim+test@0001.dev). A product gives the code
|
|
103
|
-
* to the account whose email `reservedAccountCode` names.
|
|
104
|
-
*/
|
|
105
57
|
export const RESERVED_ACCOUNT_CODES = { owner: 'Jo4712', studio: 'Jo0001', onboarding: 'On0001', test: 'Te0001' } as const satisfies Record<string, string>
|
|
106
58
|
|
|
107
59
|
export type ReservedRole = keyof typeof RESERVED_ACCOUNT_CODES
|
|
108
60
|
|
|
109
|
-
/** The email each reserved code belongs to, lower case. */
|
|
110
61
|
export const RESERVED_ACCOUNT_EMAILS = {
|
|
111
62
|
'jaa90@icloud.com': 'owner',
|
|
112
63
|
'joachim@0001.dev': 'studio',
|
|
@@ -114,29 +65,18 @@ export const RESERVED_ACCOUNT_EMAILS = {
|
|
|
114
65
|
'joachim+test@0001.dev': 'test',
|
|
115
66
|
} as const satisfies Record<string, ReservedRole>
|
|
116
67
|
|
|
117
|
-
/** Codes a role once had, still never drawn for anyone else: the onboarding test account was On4713 before On0001. */
|
|
118
68
|
export const FORMER_RESERVED_ACCOUNT_CODES = ['On4713'] as const
|
|
119
69
|
|
|
120
|
-
// Built on first use rather than when the module loads, so a page that only reads codes leaves the
|
|
121
|
-
// reserved ones out of its bundle: a bundler keeps a top-level `new Set(…)` in case it has side effects.
|
|
122
70
|
let reserved: Set<string> | undefined
|
|
123
71
|
|
|
124
|
-
/** Whether a code, in any of its capitals, is kept for a person or role, now or before. */
|
|
125
72
|
export const isReservedAccountCode = (code: string): boolean =>
|
|
126
73
|
(reserved ??= new Set([...Object.values(RESERVED_ACCOUNT_CODES), ...FORMER_RESERVED_ACCOUNT_CODES].map(kept => kept.toLowerCase()))).has(code.toLowerCase())
|
|
127
74
|
|
|
128
|
-
/** The code kept for an email, else null: a product gives it before drawing one. */
|
|
129
75
|
export function reservedAccountCode(email: string | null | undefined): string | null {
|
|
130
76
|
const key = email?.trim().toLowerCase() as keyof typeof RESERVED_ACCOUNT_EMAILS | undefined
|
|
131
77
|
return key && key in RESERVED_ACCOUNT_EMAILS ? RESERVED_ACCOUNT_CODES[RESERVED_ACCOUNT_EMAILS[key]] : null
|
|
132
78
|
}
|
|
133
79
|
|
|
134
|
-
/**
|
|
135
|
-
* A product's code: four letters, capital or small, and two digits. Nobody
|
|
136
|
-
* types one, it is always scanned, so codes differing only in capitals are
|
|
137
|
-
* different codes. Letters that spell a rude or awkward word, capitals aside,
|
|
138
|
-
* and awkward digits are drawn again (`blockedProductCode` in words.ts).
|
|
139
|
-
*/
|
|
140
80
|
export function productCodeCandidate(random: Random = Math.random): string {
|
|
141
81
|
for (let attempt = 0; attempt < 1000; attempt++) {
|
|
142
82
|
const code = Array.from({ length: 4 }, () => pick(LETTERS, random)).join('') + String(Math.floor(random() * 100)).padStart(2, '0')
|
|
@@ -145,32 +85,21 @@ export function productCodeCandidate(random: Random = Math.random): string {
|
|
|
145
85
|
throw new Error('No product code could be drawn.')
|
|
146
86
|
}
|
|
147
87
|
|
|
148
|
-
/** A list's code: two digits and four capitals. */
|
|
149
88
|
export function listCodeCandidate(random: Random = Math.random): string {
|
|
150
89
|
return pick(DIGITS, random) + pick(DIGITS, random) + Array.from({ length: 4 }, () => pick(CAPITALS, random)).join('')
|
|
151
90
|
}
|
|
152
91
|
|
|
153
|
-
/** An item's code: two letters, two digits, then two letters or digits with at least one letter. */
|
|
154
92
|
export function itemCodeCandidate(random: Random = Math.random): string {
|
|
155
93
|
const start = pick(LETTERS, random) + pick(LETTERS, random) + pick(DIGITS, random) + pick(DIGITS, random)
|
|
156
94
|
const first = pick(LETTERS + DIGITS, random)
|
|
157
95
|
const second = pick(LETTERS + DIGITS, random)
|
|
158
|
-
// At least one letter among the last two, or it would be an account's shape.
|
|
159
96
|
return start + (/\d/.test(first) && /\d/.test(second) ? pick(LETTERS, random) : first) + second
|
|
160
97
|
}
|
|
161
98
|
|
|
162
|
-
/** The pattern each kind is read by. */
|
|
163
99
|
export const CODE_PATTERN: Record<CodeKind, RegExp> = { account: ACCOUNT_CODE, product: PRODUCT_CODE, list: LIST_CODE, item: ITEM_CODE }
|
|
164
100
|
|
|
165
|
-
/** Whether a code has the shape of the kind a product expects: `isCodeOf('list', '12ABCD')`. */
|
|
166
101
|
export const isCodeOf = (kind: CodeKind, value: string): boolean => CODE_PATTERN[kind].test(value)
|
|
167
102
|
|
|
168
|
-
/**
|
|
169
|
-
* A code to try for any kind, so a product picks the shape by what it names
|
|
170
|
-
* and never by its pattern: `codeCandidate('list')` for a category,
|
|
171
|
-
* `codeCandidate('item')` for one thing kept. An account takes the name's
|
|
172
|
-
* letters (`nameLetters`), or two at random.
|
|
173
|
-
*/
|
|
174
103
|
export function codeCandidate(kind: CodeKind, options: { letters?: string | null; random?: Random } = {}): string {
|
|
175
104
|
const random = options.random ?? Math.random
|
|
176
105
|
if (kind === 'account') return accountCodeCandidate(options.letters ?? null, random)
|
|
@@ -179,10 +108,6 @@ export function codeCandidate(kind: CodeKind, options: { letters?: string | null
|
|
|
179
108
|
return itemCodeCandidate(random)
|
|
180
109
|
}
|
|
181
110
|
|
|
182
|
-
/**
|
|
183
|
-
* Every way a name-shaped code's two letters can be written, for a product
|
|
184
|
-
* that must keep a code free in all its capitals (Jo4712, jo4712, JO4712, jO4712).
|
|
185
|
-
*/
|
|
186
111
|
export function accountCodeCaseVariants(code: string): string[] {
|
|
187
112
|
const [first, second] = [code[0], code[1]].map(letter => [...new Set([letter.toUpperCase(), letter.toLowerCase()])])
|
|
188
113
|
return first.flatMap(a => second.map(b => a + b + code.slice(2)))
|
package/src/space.ts
CHANGED
|
@@ -1,13 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* How many IDv1 codes of each kind there can be, as the candidates in
|
|
3
|
-
* `shapes.ts` draw them, so a product can show how much of each is used and
|
|
4
|
-
* how much is left.
|
|
5
|
-
*
|
|
6
|
-
* - Accounts made from a name, LLnnnn: 52² × 10⁴, 27 million.
|
|
7
|
-
* - Products, LLLLnn: 52⁴ × 10², 731 million, before the blocked words.
|
|
8
|
-
* - Lists, nnLLLL with capitals: 10² × 26⁴, 46 million.
|
|
9
|
-
* - Items, LLnnXX with a letter in the last two: 52² × 10² × (62² − 10²), 1 billion.
|
|
10
|
-
*/
|
|
11
1
|
const LETTERS = 52
|
|
12
2
|
const CAPITALS = 26
|
|
13
3
|
const DIGITS = 10
|
|
@@ -21,7 +11,6 @@ export const ID_SPACE = {
|
|
|
21
11
|
|
|
22
12
|
export type IdSpaceKind = keyof typeof ID_SPACE
|
|
23
13
|
|
|
24
|
-
/** The share used, as a percentage, and how many are left. */
|
|
25
14
|
export function idUsage(kind: IdSpaceKind, used: number): { used: number; space: number; left: number; percent: number } {
|
|
26
15
|
const space = ID_SPACE[kind]
|
|
27
16
|
return { used, space, left: Math.max(0, space - used), percent: (used / space) * 100 }
|
package/src/words.ts
CHANGED
|
@@ -1,53 +1,24 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Words a paper product's code must never spell. A product's code is four
|
|
3
|
-
* letters and two digits (`productCodeCandidate` in shapes.ts),
|
|
4
|
-
* printed on every page and on the wrapper, and the account code of whoever signs up
|
|
5
|
-
* with it, so its four letters are read as a word whether anyone means them
|
|
6
|
-
* to be or not. A code is passed over when its letters, capitals aside, hold
|
|
7
|
-
* one of these anywhere in them (`blockedCodeLetters`): FUCK12, xFuk34 and
|
|
8
|
-
* Pass56 are all skipped, the last for the word inside it, which costs a few
|
|
9
|
-
* harmless codes and nothing else.
|
|
10
|
-
*
|
|
11
|
-
* Rude, crude or hurtful words, and a few merely awkward ones, in English,
|
|
12
|
-
* Danish, Japanese romaji, and the other languages the app speaks or a shop
|
|
13
|
-
* sells in. Three-letter entries catch a word inside a longer run, so they
|
|
14
|
-
* are kept to ones that are rude almost wherever they stand. The list is
|
|
15
|
-
* small on purpose: skipping a code costs nothing, since there are 731
|
|
16
|
-
* million of them.
|
|
17
|
-
*/
|
|
18
1
|
export const BLOCKED_CODE_WORDS: readonly string[] = [
|
|
19
|
-
// English
|
|
20
2
|
'fuck', 'fuk', 'fck', 'fux', 'shit', 'sht', 'crap', 'turd', 'piss', 'cunt', 'twat', 'dick', 'dik', 'cock', 'knob',
|
|
21
3
|
'wank', 'jizz', 'cum', 'porn', 'sex', 'anal', 'anus', 'arse', 'ass', 'butt', 'boob', 'tit', 'puss', 'slut',
|
|
22
4
|
'whor', 'hoe', 'bich', 'btch', 'bitc', 'damn', 'hell', 'suck', 'fart', 'puke', 'barf', 'poo', 'smeg', 'dumb', 'ugly',
|
|
23
5
|
'fat', 'kill', 'dead', 'rape', 'hate', 'nazi', 'hitl', 'heil', 'kkk', 'isis', 'fag', 'nig', 'nigg', 'coon', 'spic',
|
|
24
6
|
'kike', 'gook', 'paki', 'dyke', 'homo', 'tard',
|
|
25
|
-
// Words naming who someone is, which a code handed to a stranger should never say.
|
|
26
7
|
'jew', 'gay',
|
|
27
|
-
// Danish
|
|
28
8
|
'lort', 'pik', 'pis', 'fis', 'fiss', 'kuss', 'knep', 'hore', 'lude', 'skid', 'nege', 'fand', 'svin', 'klam',
|
|
29
|
-
// Japanese, in romaji
|
|
30
9
|
'baka', 'aho', 'kuso', 'unko', 'mank', 'chnk', 'ecch', 'etch', 'ero', 'hent', 'kasu', 'kuzu',
|
|
31
10
|
'busu', 'debu', 'hage', 'kich', 'yari', 'oppa',
|
|
32
|
-
// German, Swedish, Spanish, French, Italian, Portuguese, Korean, Chinese
|
|
33
11
|
'fick', 'fotz', 'hure', 'kack', 'arsc', 'fitt', 'kuk', 'hora', 'knul', 'puta', 'puto', 'cono', 'culo', 'mier', 'jode',
|
|
34
12
|
'pene', 'verg', 'merd', 'pute', 'bite', 'salo', 'cazz', 'figa', 'porr', 'ssib', 'shib', 'tmd', 'cao',
|
|
35
13
|
] as const
|
|
36
14
|
|
|
37
|
-
/**
|
|
38
|
-
* Two digits awkward on a pad: 42 and 49 read as 死に (to die) and 死苦
|
|
39
|
-
* (suffering) in Japanese, where the pads are made and many are sold, and 69
|
|
40
|
-
* in English. Codes ending in them are passed over too.
|
|
41
|
-
*/
|
|
42
15
|
export const BLOCKED_CODE_DIGITS: readonly string[] = ['42', '49', '69'] as const
|
|
43
16
|
|
|
44
|
-
/** Whether a run of letters spells a blocked word anywhere in it, capitals aside. */
|
|
45
17
|
export function blockedCodeLetters(letters: string): boolean {
|
|
46
18
|
const small = letters.toLowerCase()
|
|
47
19
|
return BLOCKED_CODE_WORDS.some(word => small.includes(word))
|
|
48
20
|
}
|
|
49
21
|
|
|
50
|
-
/** Whether a product code, `LLLLnn`, is one never to print: a blocked word in its letters, or awkward digits. */
|
|
51
22
|
export function blockedProductCode(code: string): boolean {
|
|
52
23
|
return blockedCodeLetters(code.slice(0, 4)) || BLOCKED_CODE_DIGITS.includes(code.slice(4))
|
|
53
24
|
}
|