@0001-labs/idv1 1.0.3 → 1.0.5
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 +9 -3
- package/bin/idv1.mjs +2 -2
- package/package.json +5 -5
- package/src/directory.ts +8 -0
- package/src/{shapes.ts → identifier.ts} +18 -1
- package/src/idv1.ts +111 -0
- package/src/namespace.ts +17 -0
- package/src/taxonomy.ts +23 -0
- package/src/util/capacity.ts +16 -0
- package/src/util/explorer.css +10 -0
- package/src/util/explorer.ts +197 -0
- package/src/{scanCode.ts → util/scan.ts} +112 -44
- package/src/architecture.ts +0 -129
- package/src/index.ts +0 -6
- package/src/junction.ts +0 -18
- package/src/scanCodeDrawing.ts +0 -72
- package/src/space.ts +0 -16
- /package/src/{words.ts → util/blockedWords.ts} +0 -0
package/README.md
CHANGED
|
@@ -17,23 +17,29 @@ const parsed = parseCode(candidate)
|
|
|
17
17
|
|
|
18
18
|
`codeCandidate(kind)` draws with Web Crypto and returns the corresponding branded ID. All generators use mixed-case ASCII letters. Account and Project accept an optional exact two-letter prefix, preserving case: `codeCandidate('project', { letters: 'AR' })`. Candidates obey word filters; Project also excludes blocked digit pairs. A bounded draw fails after 1,000 attempts. An injected `random` must return finite numbers in `[0, 1)`. These are candidate generators, not allocators: claim a candidate in its namespace and store it next to the record's UUID. A code is a short handle for agents, not a permanent identity; when a pool runs out it resets and its codes are issued again.
|
|
19
19
|
|
|
20
|
-
`
|
|
20
|
+
`ID_CAPACITY` counts the five structural pools before generation filters; `TOTAL_ID_CAPACITY` is their sum. Event is part of the main API, without a separate expanded classifier. Scan encoding retains its checksum and payload format, accepts exactly the same six-character IDs, and all scanner paths support all five shapes. Scan results are branded IDs; use `parseCode` to read their kind.
|
|
21
21
|
|
|
22
22
|
## The idv1 command
|
|
23
23
|
|
|
24
24
|
A codebase that uses IDv1 keeps one `.id` file at its root: its namespaces and taxonomies, each with its shorthand and real name, then its parts and the facts between them ([format](https://idv1.0001.dev/docs/annotate)). The `idv1` command reads it from any folder below:
|
|
25
25
|
|
|
26
26
|
```sh
|
|
27
|
-
npx idv1
|
|
27
|
+
npx idv1 directory # namespaces, taxonomies, the parts as a tree, the facts
|
|
28
28
|
npx idv1 status # counts by shape and taxonomy, and whether it is healthy
|
|
29
29
|
npx idv1 health # every broken rule; exits 1 so it can run in a build
|
|
30
30
|
npx idv1 resolve co14Ch # one id, a -SH- qualified id or a junction, with its facts
|
|
31
31
|
```
|
|
32
32
|
|
|
33
|
-
It runs on Node 22.18 or later. The same functions are exported for apps: `
|
|
33
|
+
It runs on Node 22.18 or later. The same functions are exported for apps: `readDirectory`, `directoryHealth`, `resolveCode`, `taxonomyOf`, `describeDirectory`, `describeStatus` and `runDirectoryCommand`.
|
|
34
34
|
|
|
35
35
|
The package ships TypeScript source. Bundlers and `tsx` read it as is; for a plain Node script, import `@0001-labs/idv1/register` first, then load the code that imports the package with `await import()`.
|
|
36
36
|
|
|
37
|
+
## Explorer utility
|
|
38
|
+
|
|
39
|
+
Import `createExplorer` and `mountExplorer` from `@0001-labs/idv1/explorer`, and `@0001-labs/idv1/explorer.css` for the browser view. Supply `ExplorerData`: namespace names, shapes, taxonomies, identifiers, nodes and their links. The utility owns drill-down, counts, identifier resolution, taxonomy highlighting, keyboard navigation and URL history. It contains no application records or network requests.
|
|
40
|
+
|
|
41
|
+
`createExplorer(data)` returns `entries(path)`, `title(path)` and `stepName(path, depth)` for any renderer. `mountExplorer(element, data)` renders that model and returns a cleanup function. Theme it with the `--idv1-explorer-*` CSS variables; its host owns loading and authorization.
|
|
42
|
+
|
|
37
43
|
## Upgrading from 0.3.x to Release 1
|
|
38
44
|
|
|
39
45
|
Release 1 uses five shapes. Here `L` is an ASCII letter and `N` is a digit.
|
package/bin/idv1.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { existsSync, readFileSync } from 'node:fs'
|
|
3
3
|
import { dirname, join, resolve } from 'node:path'
|
|
4
4
|
import '../register.mjs'
|
|
5
|
-
const {
|
|
5
|
+
const { runDirectoryCommand } = await import('../src/idv1.ts')
|
|
6
6
|
|
|
7
7
|
const [command, ...args] = process.argv.slice(2)
|
|
8
8
|
let dir = resolve(process.cwd())
|
|
@@ -12,6 +12,6 @@ if (!existsSync(file)) {
|
|
|
12
12
|
console.error('No .id file here or above. See https://idv1.0001.dev/docs/annotate')
|
|
13
13
|
process.exit(2)
|
|
14
14
|
}
|
|
15
|
-
const { code, out } =
|
|
15
|
+
const { code, out } = runDirectoryCommand(command, args, readFileSync(file, 'utf8'), path => existsSync(join(dir, path)))
|
|
16
16
|
console.log(out)
|
|
17
17
|
process.exit(code)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0001-labs/idv1",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.5",
|
|
4
4
|
"description": "Six-character IDs for agents: five shapes, taxonomy and namespaces, and a CLI that reads a codebase's .id file.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -19,8 +19,10 @@
|
|
|
19
19
|
],
|
|
20
20
|
"type": "module",
|
|
21
21
|
"exports": {
|
|
22
|
-
".": "./src/
|
|
23
|
-
"./register": "./register.mjs"
|
|
22
|
+
".": "./src/directory.ts",
|
|
23
|
+
"./register": "./register.mjs",
|
|
24
|
+
"./explorer": "./src/util/explorer.ts",
|
|
25
|
+
"./explorer.css": "./src/util/explorer.css"
|
|
24
26
|
},
|
|
25
27
|
"engines": {
|
|
26
28
|
"node": ">=22.18"
|
|
@@ -29,7 +31,6 @@
|
|
|
29
31
|
"@types/node": "^22.13.1",
|
|
30
32
|
"tsrs": "0.18.0-ts7.1.0-dev.20260929",
|
|
31
33
|
"typescript": "^6.0.3",
|
|
32
|
-
"vite": "npm:@voidzero-dev/vite-plus-core@1.3.0",
|
|
33
34
|
"vite-plus": "1.3.0"
|
|
34
35
|
},
|
|
35
36
|
"devEngines": {
|
|
@@ -46,7 +47,6 @@
|
|
|
46
47
|
},
|
|
47
48
|
"scripts": {
|
|
48
49
|
"check": "vp exec tsrs --noEmit",
|
|
49
|
-
"test": "vp test run",
|
|
50
50
|
"release": "node scripts/release.mjs",
|
|
51
51
|
"release:pilot": "node scripts/release-pilot.mjs"
|
|
52
52
|
}
|
package/src/directory.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type { AccountId, ListId, ProjectId, ItemId, EventId } from './identifier'
|
|
2
|
+
export * from './identifier'
|
|
3
|
+
export type { Namespace } from './namespace'
|
|
4
|
+
export { taxonomyOf, type Taxonomy } from './taxonomy'
|
|
5
|
+
export * from './util/capacity'
|
|
6
|
+
export * from './util/blockedWords'
|
|
7
|
+
export * from './util/scan'
|
|
8
|
+
export * from './idv1'
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { blockedCodeLetters, blockedProjectCode } from './
|
|
1
|
+
import { blockedCodeLetters, blockedProjectCode } from './util/blockedWords'
|
|
2
2
|
|
|
3
3
|
export const LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
|
|
4
4
|
export const CAPITALS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
|
|
@@ -105,3 +105,20 @@ export function accountCodeCaseVariants(code: string): string[] {
|
|
|
105
105
|
const [first, second] = [code[0], code[1]].map(letter => [...new Set([letter.toUpperCase(), letter.toLowerCase()])])
|
|
106
106
|
return first.flatMap(a => second.map(b => a + b + code.slice(2)))
|
|
107
107
|
}
|
|
108
|
+
|
|
109
|
+
export const JUNCTION_SEPARATOR = '-'
|
|
110
|
+
|
|
111
|
+
export function junction(...codes: string[]): string {
|
|
112
|
+
if (codes.length < 2) throw new Error('A junction joins two codes or more.')
|
|
113
|
+
for (const code of codes) if (!codeKind(code)) throw new Error(`${code} is no IDv1 code.`)
|
|
114
|
+
return codes.join(JUNCTION_SEPARATOR)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function junctionParts(value: string): { code: string; kind: CodeKind }[] | null {
|
|
118
|
+
const codes = value.split(JUNCTION_SEPARATOR)
|
|
119
|
+
if (codes.length < 2) return null
|
|
120
|
+
const parts = codes.map(code => ({ code, kind: codeKind(code) }))
|
|
121
|
+
return parts.every((part): part is { code: string; kind: CodeKind } => part.kind !== null) ? parts : null
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export const isJunction = (value: string): boolean => junctionParts(value) !== null
|
package/src/idv1.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { JUNCTION_SEPARATOR, parseCode, type CodeKind } from './identifier'
|
|
2
|
+
import { blockedCodeLetters, blockedProjectCode } from './util/blockedWords'
|
|
3
|
+
import { namespaceHealth, namespaceOf, type Namespace } from './namespace'
|
|
4
|
+
import { taxonomyHealth, taxonomyOf, type Taxonomy } from './taxonomy'
|
|
5
|
+
|
|
6
|
+
export type { Namespace } from './namespace'
|
|
7
|
+
export { taxonomyOf, type Taxonomy } from './taxonomy'
|
|
8
|
+
export type Part = { id: string; shape: CodeKind; name: string; path: string | null }
|
|
9
|
+
export type Directory = { namespaces: Namespace[]; taxonomies: Taxonomy[]; parts: Part[]; facts: string[] }
|
|
10
|
+
export type Resolved = { id: string; shape: CodeKind | null; namespace?: Namespace; taxonomy?: Taxonomy; part?: Part; facts: string[] }
|
|
11
|
+
|
|
12
|
+
const SHAPES: CodeKind[] = ['account', 'list', 'project', 'item', 'event']
|
|
13
|
+
const list = <T>(value: unknown): T[] => (Array.isArray(value) ? value : []) as T[]
|
|
14
|
+
|
|
15
|
+
export function readDirectory(text: string): Directory {
|
|
16
|
+
const value = JSON.parse(text) as Partial<Directory>
|
|
17
|
+
return { namespaces: list(value.namespaces), taxonomies: list(value.taxonomies), parts: list(value.parts), facts: list(value.facts) }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function directoryHealth(directory: Directory, exists: (path: string) => boolean = () => true): string[] {
|
|
21
|
+
const problems: string[] = []
|
|
22
|
+
const seen = (values: string[], what: string) => values.forEach((value, index) => { if (values.indexOf(value) !== index) problems.push(`${what} ${value} is declared twice`) })
|
|
23
|
+
problems.push(...namespaceHealth(directory.namespaces), ...taxonomyHealth(directory.taxonomies))
|
|
24
|
+
seen(directory.namespaces.map(namespace => namespace.shorthand), 'Namespace')
|
|
25
|
+
seen(directory.taxonomies.map(taxonomy => taxonomy.shorthand), 'Taxonomy')
|
|
26
|
+
seen(directory.parts.map(part => part.id), 'Id')
|
|
27
|
+
const ids = new Set(directory.parts.map(part => part.id))
|
|
28
|
+
for (const part of directory.parts) {
|
|
29
|
+
const shape = parseCode(part.id)?.kind
|
|
30
|
+
if (shape !== part.shape) problems.push(`${part.id} reads as ${shape ?? 'no shape'}, not ${part.shape}`)
|
|
31
|
+
else if (shape === 'project' ? blockedProjectCode(part.id) : blockedCodeLetters(part.id)) problems.push(`${part.id} uses blocked letters or digits`)
|
|
32
|
+
if (!part.name) problems.push(`${part.id} has no name`)
|
|
33
|
+
if (part.path && !exists(part.path)) problems.push(`${part.id}: ${part.path} is gone`)
|
|
34
|
+
}
|
|
35
|
+
for (const fact of directory.facts) {
|
|
36
|
+
const [subject, relation, object, extra] = fact.split(' ')
|
|
37
|
+
if (extra !== undefined || !/^r[A-Za-z]{5}$/.test(relation ?? '')) problems.push(`Not a fact: ${fact}`)
|
|
38
|
+
else for (const id of [subject, object]) if (!ids.has(id)) problems.push(`Unknown id ${id} in: ${fact}`)
|
|
39
|
+
}
|
|
40
|
+
return problems
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function resolveCode(directory: Directory, value: string): Resolved[] {
|
|
44
|
+
const qualified = /^-([A-Z]{2})-(.+)$/.exec(value)
|
|
45
|
+
const ids = (qualified ? qualified[2] : value).split(JUNCTION_SEPARATOR)
|
|
46
|
+
return ids.map(id => {
|
|
47
|
+
const shape = parseCode(id)?.kind ?? null
|
|
48
|
+
const namespace = namespaceOf(directory, id, qualified?.[1])
|
|
49
|
+
const facts = directory.facts.filter(fact => { const [subject, , object] = fact.split(' '); return subject === id || object === id })
|
|
50
|
+
return { id, shape, namespace, taxonomy: shape ? taxonomyOf(directory, id) : undefined, part: directory.parts.find(part => part.id === id), facts }
|
|
51
|
+
})
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const nameOf = (directory: Directory, id: string) => directory.parts.find(part => part.id === id)?.name ?? id
|
|
55
|
+
const readFact = (directory: Directory, fact: string) => { const [subject, relation, object] = fact.split(' '); return `${subject} ${relation} ${object} ${nameOf(directory, subject)} → ${nameOf(directory, object)}` }
|
|
56
|
+
|
|
57
|
+
export function describeResolved(directory: Directory, resolved: Resolved[]): string {
|
|
58
|
+
return resolved.map(({ id, shape, namespace, taxonomy, part, facts }) => [
|
|
59
|
+
`${id} ${part?.name ?? (shape ? 'not in .id' : 'not a code')}`,
|
|
60
|
+
` shape ${shape ?? '—'}`,
|
|
61
|
+
...(taxonomy ? [` taxonomy ${taxonomy.shorthand} · ${taxonomy.name}`] : []),
|
|
62
|
+
...(namespace ? [` namespace ${namespace.shorthand} · ${namespace.name}`] : []),
|
|
63
|
+
...(part?.path ? [` path ${part.path}`] : []),
|
|
64
|
+
...facts.map(fact => ` fact ${readFact(directory, fact)}`),
|
|
65
|
+
].join('\n')).join('\n\n')
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function describeStatus(directory: Directory, problems: string[]): string {
|
|
69
|
+
const count = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
|
|
70
|
+
const shapes = SHAPES.map(shape => [shape, directory.parts.filter(part => part.shape === shape).length] as const).filter(([, n]) => n)
|
|
71
|
+
return [
|
|
72
|
+
`${count(directory.parts.length, 'part')} · ${count(directory.facts.length, 'fact')} · ${count(directory.namespaces.length, 'namespace')} · ${count(directory.taxonomies.length, 'taxonomy', 'taxonomies')}`,
|
|
73
|
+
problems.length ? `${count(problems.length, 'problem')}: run idv1 health` : 'healthy',
|
|
74
|
+
'',
|
|
75
|
+
...shapes.map(([shape, n]) => ` ${shape.padEnd(9)}${n}`),
|
|
76
|
+
...directory.taxonomies.map(taxonomy => ` ${taxonomy.shorthand.padEnd(9)}${directory.parts.filter(part => taxonomyOf(directory, part.id) === taxonomy).length} ${taxonomy.name}`),
|
|
77
|
+
].join('\n')
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function describeDirectory(directory: Directory): string {
|
|
81
|
+
const contains = directory.facts.map(fact => fact.split(' ')).filter(([, relation]) => relation === 'rHasPt')
|
|
82
|
+
const children = (id: string) => contains.filter(([subject]) => subject === id).map(([, , object]) => object)
|
|
83
|
+
const roots = directory.parts.filter(part => !contains.some(([, , object]) => object === part.id))
|
|
84
|
+
const line = (part: Part | undefined, id: string, depth: number) => `${' '.repeat(depth)}${id} ${part?.name ?? '?'}${part && taxonomyOf(directory, id) ? ` (${taxonomyOf(directory, id)!.name})` : ''}${part?.path ? ` ${part.path}` : ''}`
|
|
85
|
+
const tree = (id: string, depth: number, trail: Set<string>): string[] => trail.has(id) ? [] : [line(directory.parts.find(part => part.id === id), id, depth), ...children(id).flatMap(child => tree(child, depth + 1, new Set([...trail, id])))]
|
|
86
|
+
return [
|
|
87
|
+
'Namespaces',
|
|
88
|
+
...directory.namespaces.map(({ shorthand, name }) => ` ${shorthand} ${name}`),
|
|
89
|
+
'',
|
|
90
|
+
'Taxonomies',
|
|
91
|
+
...directory.taxonomies.map(({ shorthand, name, shape, pattern }) => ` ${shorthand} ${name} ${shape} ${pattern}`),
|
|
92
|
+
'',
|
|
93
|
+
'Parts',
|
|
94
|
+
...roots.flatMap(part => tree(part.id, 1, new Set())),
|
|
95
|
+
'',
|
|
96
|
+
'Facts',
|
|
97
|
+
...directory.facts.filter(fact => fact.split(' ')[1] !== 'rHasPt').map(fact => ` ${readFact(directory, fact)}`),
|
|
98
|
+
].join('\n')
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function runDirectoryCommand(command: string | undefined, args: string[], text: string, exists?: (path: string) => boolean): { code: number; out: string } {
|
|
102
|
+
const directory = readDirectory(text)
|
|
103
|
+
const problems = directoryHealth(directory, exists)
|
|
104
|
+
switch (command) {
|
|
105
|
+
case 'health': return { code: problems.length ? 1 : 0, out: problems.length ? problems.join('\n') : 'healthy' }
|
|
106
|
+
case 'status': return { code: 0, out: describeStatus(directory, problems) }
|
|
107
|
+
case 'resolve': return args.length ? { code: 0, out: args.map(value => describeResolved(directory, resolveCode(directory, value))).join('\n\n') } : { code: 2, out: 'idv1 resolve <id | junction | -NS-id>' }
|
|
108
|
+
case 'directory': case undefined: return { code: 0, out: describeDirectory(directory) }
|
|
109
|
+
default: return { code: 2, out: 'idv1 directory | status | health | resolve <id>' }
|
|
110
|
+
}
|
|
111
|
+
}
|
package/src/namespace.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { parseCode } from './identifier'
|
|
2
|
+
|
|
3
|
+
export type Namespace = { shorthand: string; name: string }
|
|
4
|
+
|
|
5
|
+
export function namespaceOf({ namespaces }: { namespaces: Namespace[] }, id: string, qualified?: string): Namespace | undefined {
|
|
6
|
+
const shorthand = qualified ?? (parseCode(id)?.kind === 'project' ? id.slice(0, 2) : undefined)
|
|
7
|
+
return namespaces.find(namespace => namespace.shorthand === shorthand) ?? (namespaces.length === 1 ? namespaces[0] : undefined)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function namespaceHealth(namespaces: Namespace[]): string[] {
|
|
11
|
+
const problems: string[] = []
|
|
12
|
+
for (const { shorthand, name } of namespaces) {
|
|
13
|
+
if (!/^[A-Z]{2}$/.test(shorthand)) problems.push(`Namespace ${shorthand} is not two capitals`)
|
|
14
|
+
if (!name) problems.push(`Namespace ${shorthand} has no name`)
|
|
15
|
+
}
|
|
16
|
+
return problems
|
|
17
|
+
}
|
package/src/taxonomy.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { CODE_PATTERN, parseCode, type CodeKind } from './identifier'
|
|
2
|
+
|
|
3
|
+
export type Taxonomy = { shorthand: string; name: string; shape: CodeKind; pattern: string }
|
|
4
|
+
|
|
5
|
+
export function taxonomyOf(directory: { taxonomies: Taxonomy[] }, id: string): Taxonomy | undefined {
|
|
6
|
+
const shape = parseCode(id)?.kind
|
|
7
|
+
return directory.taxonomies.find(taxonomy => {
|
|
8
|
+
const at = taxonomy.pattern.replace(/\s/g, '').indexOf(taxonomy.shorthand)
|
|
9
|
+
return taxonomy.shape === shape && at >= 0 && id.slice(at, at + 2) === taxonomy.shorthand
|
|
10
|
+
})
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function taxonomyHealth(taxonomies: Taxonomy[]): string[] {
|
|
14
|
+
const problems: string[] = []
|
|
15
|
+
for (const { shorthand, name, shape, pattern } of taxonomies) {
|
|
16
|
+
if (!/^[a-z]{2}$/.test(shorthand)) problems.push(`Taxonomy ${shorthand} is not two small letters`)
|
|
17
|
+
if (!name) problems.push(`Taxonomy ${shorthand} has no name`)
|
|
18
|
+
if (!Object.keys(CODE_PATTERN).includes(shape)) problems.push(`Taxonomy ${shorthand} has no shape`)
|
|
19
|
+
const compact = String(pattern ?? '').replace(/\s/g, '')
|
|
20
|
+
if (compact.length !== 6 || !compact.includes(shorthand)) problems.push(`Taxonomy ${shorthand} has no six-character pattern holding ${shorthand}`)
|
|
21
|
+
}
|
|
22
|
+
return problems
|
|
23
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
const LETTERS = 52
|
|
2
|
+
const DIGITS = 10
|
|
3
|
+
export const TOTAL_ID_CAPACITY = (LETTERS + DIGITS) ** 6
|
|
4
|
+
const accounts = LETTERS ** 2 * DIGITS ** 4
|
|
5
|
+
const lists = DIGITS ** 2 * LETTERS ** 4
|
|
6
|
+
const projects = LETTERS ** 4 * DIGITS ** 2
|
|
7
|
+
const items = LETTERS ** 2 * DIGITS ** 2 * ((LETTERS + DIGITS) ** 2 - DIGITS ** 2)
|
|
8
|
+
|
|
9
|
+
export const ID_CAPACITY = { accounts, lists, projects, items, events: TOTAL_ID_CAPACITY - accounts - lists - projects - items } as const
|
|
10
|
+
export type IdCapacityKind = keyof typeof ID_CAPACITY
|
|
11
|
+
|
|
12
|
+
export function idUsage(kind: IdCapacityKind, used: number): { used: number; capacity: number; left: number; percent: number } {
|
|
13
|
+
const capacity = ID_CAPACITY[kind]
|
|
14
|
+
if (!Number.isSafeInteger(used) || used < 0) throw new RangeError('Usage must be a nonnegative safe integer.')
|
|
15
|
+
return { used, capacity, left: Math.max(0, capacity - used), percent: (used / capacity) * 100 }
|
|
16
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
.explorer { --unit: var(--idv1-explorer-unit, 20px); --cell: calc(var(--unit) / 2); --ink: var(--idv1-explorer-ink, #fff); --rule: color-mix(in oklab, var(--ink) 22%, transparent); color-scheme: dark; min-height: calc(6 * var(--unit)); background-color: var(--idv1-explorer-paper, #282828); color: var(--ink); font-family: var(--idv1-explorer-font, sans-serif); font-size: var(--idv1-explorer-size, 14px); }
|
|
2
|
+
.explorer-path { display: flex; flex-wrap: wrap; column-gap: calc(var(--unit) / 2); }
|
|
3
|
+
.explorer-rows { display: flex; flex-direction: column; }
|
|
4
|
+
.explorer-taxonomy { color: var(--idv1-explorer-accent, #fec20d); }
|
|
5
|
+
.explorer-row { display: grid; grid-template-columns: calc(8 * var(--cell)) minmax(0, 1fr) auto calc(4 * var(--cell)); column-gap: calc(var(--unit) / 2); margin: 0; color: inherit; text-decoration: none; }
|
|
6
|
+
.explorer-step, .explorer-title, .explorer-row > span, p.explorer-row { box-sizing: border-box; display: block; height: var(--unit); padding-top: calc(var(--unit) / 5); line-height: calc(var(--unit) * 4 / 5); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; color: inherit; text-decoration: none; }
|
|
7
|
+
.explorer-row > .explorer-mono { font-family: var(--idv1-explorer-mono, monospace); font-variant-numeric: tabular-nums; white-space: pre; text-overflow: clip; letter-spacing: calc(var(--cell) - 1ch); padding-inline-start: calc((var(--cell) - 1ch) / 2); box-shadow: inset 0 0 0 1px var(--rule); background-image: linear-gradient(to right, var(--rule) 2px, transparent 2px), linear-gradient(to right, color-mix(in oklab, var(--ink) 9%, transparent) 1px, transparent 1px); background-size: var(--unit) 100%, var(--cell) 100%; }
|
|
8
|
+
.explorer-title { margin-inline-start: auto; }
|
|
9
|
+
.explorer-dim, .explorer-step:not(:last-of-type) { color: color-mix(in oklab, var(--ink) 55%, transparent); }
|
|
10
|
+
.explorer :is(a:hover, a:focus-visible) { background-color: color-mix(in oklab, var(--ink) 14%, transparent); outline: none; }
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
export type ExplorerNode = { qualifiedId: string; namespace: string; shape: string; label: string; group: string; at?: number };
|
|
2
|
+
export type ExplorerLink = { subject: string; relation: string; object: string };
|
|
3
|
+
export type ExplorerTaxonomy = { tag: string; name: string; shape: string; pattern: string };
|
|
4
|
+
export type ExplorerShape = { name: string; label: string; pattern: string };
|
|
5
|
+
export type ExplorerIdentifier = { namespace: string; code: string; name: string; shape: string; on?: string };
|
|
6
|
+
export type ExplorerData = {
|
|
7
|
+
name: string;
|
|
8
|
+
namespace: string;
|
|
9
|
+
namespaces: { pair: string; name: string }[];
|
|
10
|
+
nodes: ExplorerNode[];
|
|
11
|
+
links: ExplorerLink[];
|
|
12
|
+
taxonomy: ExplorerTaxonomy[];
|
|
13
|
+
shapes: ExplorerShape[];
|
|
14
|
+
identifiers: ExplorerIdentifier[];
|
|
15
|
+
};
|
|
16
|
+
type Node = ExplorerNode;
|
|
17
|
+
type Taxonomy = ExplorerTaxonomy;
|
|
18
|
+
type Identifier = ExplorerIdentifier;
|
|
19
|
+
export type ExplorerEntry = { path: string[]; id: string; label: string; kind: string; count: number };
|
|
20
|
+
type Entry = ExplorerEntry;
|
|
21
|
+
|
|
22
|
+
export function createExplorer(data: ExplorerData) {
|
|
23
|
+
const { taxonomy, shapes, identifiers } = data;
|
|
24
|
+
const nodes = new Map(data.nodes.map(node => [node.qualifiedId, node]));
|
|
25
|
+
const children = new Map<string, string[]>();
|
|
26
|
+
const parents = new Map<string, string[]>();
|
|
27
|
+
const add = (map: Map<string, string[]>, parent: string, child: string) => {
|
|
28
|
+
const list = map.get(parent) ?? [];
|
|
29
|
+
if (!list.includes(child)) map.set(parent, [...list, child]);
|
|
30
|
+
};
|
|
31
|
+
for (const { subject, relation, object } of data.links) {
|
|
32
|
+
if (!nodes.has(subject) || !nodes.has(object)) continue;
|
|
33
|
+
if (['part of', 'defined by', 'member of'].includes(relation)) {
|
|
34
|
+
add(children, object, subject);
|
|
35
|
+
add(parents, subject, object);
|
|
36
|
+
} else if (relation === 'uses') {
|
|
37
|
+
add(children, subject, object);
|
|
38
|
+
add(children, object, subject);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const namespaces = () => [...new Set([...nodes.values()].map(node => node.namespace))]
|
|
42
|
+
.sort((a, b) => (a === data.namespace ? -1 : b === data.namespace ? 1 : a.localeCompare(b)));
|
|
43
|
+
const topLevel = (namespace: string) => [...nodes.values()].filter(node => node.namespace === namespace && node.at === undefined
|
|
44
|
+
&& !(parents.get(node.qualifiedId) ?? []).some(parent => nodes.get(parent)?.namespace === namespace));
|
|
45
|
+
const owner = (namespace: string) => data.namespaces.find(entry => entry.pair === namespace);
|
|
46
|
+
const short = (id: string) => id.length === 2 ? id : id.slice(1, 3) + id.slice(4);
|
|
47
|
+
const byKind = (a: Node, b: Node) => (b.at ?? 0) - (a.at ?? 0) || a.group.localeCompare(b.group) || a.label.localeCompare(b.label);
|
|
48
|
+
|
|
49
|
+
const tagged = (entry: Taxonomy) => [...nodes.values()].filter(node =>
|
|
50
|
+
node.shape === entry.shape && node.qualifiedId.slice(4).slice(entry.pattern.indexOf(entry.tag)).startsWith(entry.tag));
|
|
51
|
+
const identifierKey = (entry: Identifier) => `-${entry.namespace}-${entry.code}`;
|
|
52
|
+
const named = (id: string) => {
|
|
53
|
+
const entry = identifiers.find(entry => identifierKey(entry) === id);
|
|
54
|
+
const target = entry && 'on' in entry && entry.on ? `-${entry.namespace}-${entry.on}` : id;
|
|
55
|
+
return [...nodes.values()].filter(node => node.qualifiedId === target);
|
|
56
|
+
};
|
|
57
|
+
const lists: Record<string, string> = { shapes: 'Shapes', namespaces: 'Namespaces', taxonomies: 'Taxonomies', identifiers: 'Identifiers' };
|
|
58
|
+
const shapeName = (name: string) => shapes.find(kind => kind.name === name)?.label ?? name;
|
|
59
|
+
const ofShape = (name: string) => [...nodes.values()].filter(node => node.shape === name);
|
|
60
|
+
const scope = (path: string[]) => { const at = path.at(-1); return !at || lists[at] ? data.namespace : at.length === 2 ? at : at.includes(':') ? '' : nodes.get(at)?.namespace ?? ''; };
|
|
61
|
+
const idIn = (id: string, namespace: string) => id.length > 2 && id.slice(1, 3) === namespace ? id.slice(4) : short(id);
|
|
62
|
+
const kindOf = (node: Node) => taxonomy.find(entry => entry.shape === node.shape && node.qualifiedId.slice(4).slice(entry.pattern.indexOf(entry.tag)).startsWith(entry.tag))?.name ?? shapeName(node.shape);
|
|
63
|
+
const rowsOf = (path: string[], list: Node[]): Entry[] => list.sort(byKind).map(node => ({
|
|
64
|
+
path: [...path, node.qualifiedId], id: idIn(node.qualifiedId, scope(path)), label: node.label, kind: kindOf(node), count: children.get(node.qualifiedId)?.length ?? 0,
|
|
65
|
+
}));
|
|
66
|
+
|
|
67
|
+
function entries(path: string[]): Entry[] {
|
|
68
|
+
const at = path.at(-1);
|
|
69
|
+
if (!at) return [
|
|
70
|
+
{ path: ['shapes'], id: '', label: 'Shapes', kind: '', count: shapes.length },
|
|
71
|
+
{ path: ['namespaces'], id: '', label: 'Namespaces', kind: '', count: namespaces().length },
|
|
72
|
+
{ path: ['taxonomies'], id: '', label: 'Taxonomies', kind: '', count: taxonomy.length },
|
|
73
|
+
{ path: ['identifiers'], id: '', label: 'Identifiers', kind: '', count: identifiers.length },
|
|
74
|
+
];
|
|
75
|
+
if (at === 'namespaces') return namespaces().map(namespace => ({
|
|
76
|
+
path: [namespace], id: namespace, label: owner(namespace)?.name ?? namespace, kind: 'Namespace', count: topLevel(namespace).length,
|
|
77
|
+
}));
|
|
78
|
+
if (at === 'shapes') return shapes.map(kind => ({ path: [`sh:${kind.name}`], id: kind.pattern, label: kind.label, kind: 'Shape', count: ofShape(kind.name).length }));
|
|
79
|
+
if (at === 'taxonomies') return taxonomy.map(entry => ({
|
|
80
|
+
path: [`tx:${entry.tag}`], id: entry.pattern, label: entry.name, kind: shapeName(entry.shape), count: tagged(entry).length,
|
|
81
|
+
}));
|
|
82
|
+
if (at === 'identifiers') return identifiers.map(entry => ({
|
|
83
|
+
path: [`id:${identifierKey(entry)}`], id: idIn(identifierKey(entry), scope(path)), label: entry.name, kind: named(identifierKey(entry))[0] ? kindOf(named(identifierKey(entry))[0]) : shapeName(entry.shape), count: named(identifierKey(entry)).length,
|
|
84
|
+
}));
|
|
85
|
+
if (at.startsWith('id:')) return rowsOf(path, named(at.slice(3)));
|
|
86
|
+
if (at.startsWith('sh:')) return rowsOf(path, ofShape(at.slice(3)));
|
|
87
|
+
if (at.startsWith('tx:')) { const entry = taxonomy.find(item => item.tag === at.slice(3)); return entry ? rowsOf(path, tagged(entry)) : []; }
|
|
88
|
+
if (at.length === 2) return rowsOf(path, topLevel(at));
|
|
89
|
+
return rowsOf(path, (children.get(at) ?? []).flatMap(id => nodes.get(id) ?? []));
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const stepName = (path: string[], depth: number) => { const step = path[depth - 1]; return lists[step] ?? (step.startsWith('sh:') ? shapeName(step.slice(3)) : step.startsWith('tx:') ? step.slice(3) : step.startsWith('id:') ? idIn(step.slice(3), scope(path.slice(0, depth - 1))) : idIn(step, scope(path.slice(0, depth - 1)))); };
|
|
93
|
+
function title(path: string[]) {
|
|
94
|
+
const at = path.at(-1);
|
|
95
|
+
if (!at) return data.name;
|
|
96
|
+
if (lists[at]) return lists[at];
|
|
97
|
+
if (at.startsWith('sh:')) return `${shapeName(at.slice(3))} · Shape`;
|
|
98
|
+
if (at.startsWith('tx:')) return `${taxonomy.find(entry => entry.tag === at.slice(3))?.name ?? at.slice(3)} · Taxonomy`;
|
|
99
|
+
if (at.startsWith('id:')) return `${identifiers.find(entry => identifierKey(entry) === at.slice(3))?.name ?? at.slice(3)} · Identifier`;
|
|
100
|
+
if (at.length === 2) return `${owner(at)?.name ?? at} · Namespace`;
|
|
101
|
+
const node = nodes.get(at);
|
|
102
|
+
return node ? `${node.label} · ${kindOf(node)}` : '';
|
|
103
|
+
}
|
|
104
|
+
return { entries, title, stepName };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function mountExplorer(surface: HTMLElement, data: ExplorerData) {
|
|
108
|
+
const document = surface.ownerDocument;
|
|
109
|
+
const window = document.defaultView!;
|
|
110
|
+
const abort = new AbortController();
|
|
111
|
+
const { entries, title, stepName } = createExplorer(data);
|
|
112
|
+
const taxonomy = data.taxonomy;
|
|
113
|
+
surface.classList.add('explorer');
|
|
114
|
+
const pathLine = document.createElement('nav');
|
|
115
|
+
pathLine.className = 'explorer-path';
|
|
116
|
+
pathLine.setAttribute('aria-label', 'Path');
|
|
117
|
+
const rows = document.createElement('div');
|
|
118
|
+
rows.className = 'explorer-rows';
|
|
119
|
+
surface.replaceChildren(pathLine, rows);
|
|
120
|
+
const readPath = () => (new URLSearchParams(window.location.search).get('path') ?? '').split(',').filter(Boolean);
|
|
121
|
+
const href = (path: string[]) => path.length ? `?path=${path.join(',')}` : window.location.pathname;
|
|
122
|
+
|
|
123
|
+
function link(path: string[], className: string, parts: [string, string][]) {
|
|
124
|
+
const anchor = document.createElement('a');
|
|
125
|
+
anchor.className = className;
|
|
126
|
+
anchor.href = href(path);
|
|
127
|
+
anchor.dataset.path = path.join(',');
|
|
128
|
+
for (const [text, part] of parts) {
|
|
129
|
+
const span = document.createElement('span');
|
|
130
|
+
span.className = part;
|
|
131
|
+
span.textContent = text;
|
|
132
|
+
const pattern = part === 'explorer-mono' && taxonomy.find(entry => entry.pattern === text.trim());
|
|
133
|
+
if (pattern) {
|
|
134
|
+
const start = text.indexOf(pattern.tag);
|
|
135
|
+
const letters = document.createElement('span');
|
|
136
|
+
letters.className = 'explorer-taxonomy';
|
|
137
|
+
letters.textContent = pattern.tag;
|
|
138
|
+
span.replaceChildren(text.slice(0, start), letters, text.slice(start + pattern.tag.length));
|
|
139
|
+
}
|
|
140
|
+
anchor.append(span);
|
|
141
|
+
}
|
|
142
|
+
return anchor;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function render(focusFirst = false) {
|
|
146
|
+
const path = readPath();
|
|
147
|
+
const corner = document.createElement('span');
|
|
148
|
+
corner.className = 'explorer-title';
|
|
149
|
+
corner.textContent = title(path);
|
|
150
|
+
pathLine.replaceChildren(...[data.name, ...path].map((step, depth) =>
|
|
151
|
+
link(path.slice(0, depth), 'explorer-step', [[`${depth ? stepName(path, depth) : step} /`, '']])), corner);
|
|
152
|
+
const list = entries(path);
|
|
153
|
+
rows.replaceChildren(...list.map(entry => link(entry.path, 'explorer-row', [
|
|
154
|
+
[entry.id.padEnd(8), 'explorer-mono'],
|
|
155
|
+
[entry.label, ''],
|
|
156
|
+
[entry.kind, 'explorer-dim'],
|
|
157
|
+
[entry.count ? `${String(entry.count).padStart(3)}/` : ' ', 'explorer-mono explorer-dim'],
|
|
158
|
+
])));
|
|
159
|
+
if (!list.length) {
|
|
160
|
+
const empty = document.createElement('p');
|
|
161
|
+
empty.className = 'explorer-row explorer-dim';
|
|
162
|
+
empty.textContent = 'Nothing recorded inside.';
|
|
163
|
+
rows.append(empty);
|
|
164
|
+
}
|
|
165
|
+
if (focusFirst) (rows.querySelector<HTMLElement>('a') ?? pathLine.lastElementChild as HTMLElement)?.focus();
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function go(path: string[]) {
|
|
169
|
+
window.history.pushState(null, '', href(path));
|
|
170
|
+
render(true);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
surface.addEventListener('click', event => {
|
|
174
|
+
const anchor = (event.target as HTMLElement).closest<HTMLAnchorElement>('a[data-path]');
|
|
175
|
+
if (!anchor || event.metaKey || event.ctrlKey || event.shiftKey) return;
|
|
176
|
+
event.preventDefault();
|
|
177
|
+
go(anchor.dataset.path!.split(',').filter(Boolean));
|
|
178
|
+
}, { signal: abort.signal });
|
|
179
|
+
surface.addEventListener('keydown', event => {
|
|
180
|
+
const links = [...rows.querySelectorAll<HTMLElement>('a')];
|
|
181
|
+
const at = links.indexOf(document.activeElement as HTMLElement);
|
|
182
|
+
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
|
|
183
|
+
event.preventDefault();
|
|
184
|
+
links[Math.max(0, Math.min(links.length - 1, at + (event.key === 'ArrowDown' ? 1 : -1)))]?.focus();
|
|
185
|
+
} else if (event.key === 'ArrowRight' && at >= 0) {
|
|
186
|
+
event.preventDefault();
|
|
187
|
+
links[at].click();
|
|
188
|
+
} else if ((event.key === 'ArrowLeft' || event.key === 'Backspace') && readPath().length) {
|
|
189
|
+
event.preventDefault();
|
|
190
|
+
go(readPath().slice(0, -1));
|
|
191
|
+
}
|
|
192
|
+
}, { signal: abort.signal });
|
|
193
|
+
window.addEventListener('popstate', () => render(true), { signal: abort.signal });
|
|
194
|
+
|
|
195
|
+
render();
|
|
196
|
+
return () => { abort.abort(); surface.replaceChildren(); };
|
|
197
|
+
}
|
|
@@ -1,11 +1,79 @@
|
|
|
1
|
-
import { ALPHABET, isAccountCode, isListCode, parseCode, type Id } from '
|
|
2
|
-
import { scanCodeChecksum, scanCodeColumns, scanCodeRows } from './scanCodeDrawing'
|
|
3
|
-
export { CODE_END_RADIUS, encodeScanCode, scanCodeColumns, scanCodePath, scanCodeRows } from './scanCodeDrawing'
|
|
1
|
+
import { ALPHABET, isAccountCode, isListCode, parseCode, type Id } from '../identifier'
|
|
4
2
|
|
|
5
3
|
const alphabet = ALPHABET
|
|
4
|
+
export const scanColumns = 16
|
|
5
|
+
export const scanRows = 4
|
|
6
|
+
export const CODE_END_RADIUS = 0.1
|
|
7
|
+
|
|
8
|
+
function scanChecksum(bytes: readonly number[]): number {
|
|
9
|
+
let crc = 0xffff
|
|
10
|
+
for (const byte of bytes) {
|
|
11
|
+
crc ^= byte << 8
|
|
12
|
+
for (let bit = 0; bit < 8; bit++) crc = ((crc << 1) ^ (crc & 0x8000 ? 0x1021 : 0)) & 0xffff
|
|
13
|
+
}
|
|
14
|
+
return crc
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function encodeScan(id: string): boolean[] | null {
|
|
18
|
+
if (!parseCode(id)) return null
|
|
19
|
+
let value = 0
|
|
20
|
+
for (const character of id) value = value * 62 + alphabet.indexOf(character)
|
|
21
|
+
const bytes = [3]
|
|
22
|
+
for (let shift = 32; shift >= 0; shift -= 8) bytes.push(Math.floor(value / 2 ** shift) & 255)
|
|
23
|
+
const crc = scanChecksum(bytes)
|
|
24
|
+
bytes.push(crc >> 8, crc & 255)
|
|
25
|
+
return bytes.flatMap(byte => Array.from({ length: 8 }, (_, bit) => !!(byte & (1 << (7 - bit)))))
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function scanPath(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 {
|
|
29
|
+
const round = (value: number) => Math.round(value * 1e4) / 1e4
|
|
30
|
+
const inked = (row: number, column: number) =>
|
|
31
|
+
row >= 0 && row < scanRows && column >= 0 && column < scanColumns && ink(bits[row * scanColumns + column])
|
|
32
|
+
const r = Math.min(Math.max(radius, 0), 0.5) * cell
|
|
33
|
+
let d = ''
|
|
34
|
+
for (let row = 0; row < scanRows; row++) {
|
|
35
|
+
for (let column = 0; column < scanColumns;) {
|
|
36
|
+
if (!inked(row, column)) { column++; continue }
|
|
37
|
+
const start = column
|
|
38
|
+
while (column < scanColumns && inked(row, column)) column++
|
|
39
|
+
const left = x + start * cell, right = x + column * cell, top = y + row * cell, bottom = top + cell
|
|
40
|
+
if (!r) {
|
|
41
|
+
d += `M${round(left)} ${round(top)}h${round(right - left)}v${round(cell)}h${round(left - right)}z`
|
|
42
|
+
continue
|
|
43
|
+
}
|
|
44
|
+
const end = (facing: number, inside: number) => !inked(facing, inside) ? r : 0
|
|
45
|
+
const tl = end(row - 1, start)
|
|
46
|
+
const tr = end(row - 1, column - 1)
|
|
47
|
+
const br = end(row + 1, column - 1)
|
|
48
|
+
const bl = end(row + 1, start)
|
|
49
|
+
const arc = (radius: number, toX: number, toY: number) => radius ? `A${round(radius)} ${round(radius)} 0 0 1 ${round(toX)} ${round(toY)}` : ''
|
|
50
|
+
d += `M${round(left + tl)} ${round(top)}H${round(right - tr)}${arc(tr, right, top + tr)}`
|
|
51
|
+
d += `V${round(bottom - br)}${arc(br, right - br, bottom)}`
|
|
52
|
+
d += `H${round(left + bl)}${arc(bl, left, bottom - bl)}`
|
|
53
|
+
d += `V${round(top + tl)}${arc(tl, left + tl, top)}Z`
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (!r) return d
|
|
57
|
+
for (let row = 0; row < scanRows; row++) {
|
|
58
|
+
for (let column = 0; column < scanColumns; column++) {
|
|
59
|
+
if (inked(row, column)) continue
|
|
60
|
+
const left = x + column * cell, top = y + row * cell
|
|
61
|
+
for (const [dy, dx] of [[-1, -1], [-1, 1], [1, 1], [1, -1]] as const) {
|
|
62
|
+
if (!inked(row + dy, column) || !inked(row, column + dx) || !inked(row + dy, column + dx)) continue
|
|
63
|
+
const cornerX = left + (dx > 0 ? cell : 0), cornerY = top + (dy > 0 ? cell : 0)
|
|
64
|
+
const alongX = cornerX - dx * r, alongY = cornerY - dy * r
|
|
65
|
+
const sweep = dx * dy > 0 ? 0 : 1
|
|
66
|
+
d += `M${round(cornerX)} ${round(cornerY)}H${round(alongX)}A${round(r)} ${round(r)} 0 0 ${sweep} ${round(cornerX)} ${round(alongY)}Z`
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return d
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
6
74
|
const idSpace = 62 ** 6
|
|
7
75
|
|
|
8
|
-
export function
|
|
76
|
+
export function decodeScan(bits: readonly boolean[]): Id | null {
|
|
9
77
|
if (bits.length !== 64) return null
|
|
10
78
|
const bytes: number[] = []
|
|
11
79
|
for (let offset = 0; offset < 64; offset += 8) {
|
|
@@ -13,7 +81,7 @@ export function decodeScanCode(bits: readonly boolean[]): Id | null {
|
|
|
13
81
|
for (let bit = 0; bit < 8; bit++) byte = (byte << 1) | (bits[offset + bit] ? 1 : 0)
|
|
14
82
|
bytes.push(byte)
|
|
15
83
|
}
|
|
16
|
-
if (bytes[0] !== 3 ||
|
|
84
|
+
if (bytes[0] !== 3 || scanChecksum(bytes.slice(0, 6)) !== ((bytes[6] << 8) | bytes[7])) return null
|
|
17
85
|
let value = 0
|
|
18
86
|
for (const byte of bytes.slice(1, 6)) value = value * 256 + byte
|
|
19
87
|
if (value >= idSpace) return null
|
|
@@ -39,7 +107,7 @@ const insetRect = (rect: ScanRect, dx: number, dy: number): ScanRect => ({
|
|
|
39
107
|
const offsetRect = (rect: ScanRect, dx: number, dy: number): ScanRect => ({ ...rect, x: rect.x + dx, y: rect.y + dy })
|
|
40
108
|
const clamp = (value: number, low: number, high: number) => Math.max(low, Math.min(high, value))
|
|
41
109
|
|
|
42
|
-
export function
|
|
110
|
+
export function sampleScan(width: number, height: number, luminance: Luminance, rect?: ScanRect): Id | null {
|
|
43
111
|
if (width < 80 || height < 20) return null
|
|
44
112
|
const guideWidth = rect?.width ?? width * 0.8
|
|
45
113
|
const guideHeight = rect?.height ?? guideWidth / 4
|
|
@@ -48,10 +116,10 @@ export function sampleScanCode(width: number, height: number, luminance: Luminan
|
|
|
48
116
|
const top = rect?.y ?? (height - guideHeight) / 2
|
|
49
117
|
const radius = guideWidth / 16 < 6 ? 0 : 1
|
|
50
118
|
const levels: number[] = []
|
|
51
|
-
for (let y = 0; y <
|
|
52
|
-
for (let x = 0; x <
|
|
53
|
-
const px = Math.trunc(left + (x + 0.5) * guideWidth /
|
|
54
|
-
const py = Math.trunc(top + (y + 0.5) * guideHeight /
|
|
119
|
+
for (let y = 0; y < scanRows; y++) {
|
|
120
|
+
for (let x = 0; x < scanColumns; x++) {
|
|
121
|
+
const px = Math.trunc(left + (x + 0.5) * guideWidth / scanColumns)
|
|
122
|
+
const py = Math.trunc(top + (y + 0.5) * guideHeight / scanRows)
|
|
55
123
|
let level = 0
|
|
56
124
|
for (let dy = -radius; dy <= radius; dy++) {
|
|
57
125
|
for (let dx = -radius; dx <= radius; dx++) level += luminance(clamp(px + dx, 0, width - 1), clamp(py + dy, 0, height - 1))
|
|
@@ -62,7 +130,7 @@ export function sampleScanCode(width: number, height: number, luminance: Luminan
|
|
|
62
130
|
const low = Math.min(...levels), high = Math.max(...levels)
|
|
63
131
|
if (high - low <= 8) return null
|
|
64
132
|
const mid = (low + high) / 2
|
|
65
|
-
return
|
|
133
|
+
return decodeScan(levels.map(level => level < mid)) ?? decodeScan(levels.map(level => level > mid))
|
|
66
134
|
}
|
|
67
135
|
|
|
68
136
|
function partedLevels(levels: readonly number[]): number | null {
|
|
@@ -83,17 +151,17 @@ function partedLevels(levels: readonly number[]): number | null {
|
|
|
83
151
|
|
|
84
152
|
function levelledColumns(levels: readonly number[], lightest: boolean): number[] {
|
|
85
153
|
const ground: number[] = []
|
|
86
|
-
for (let column = 0; column <
|
|
154
|
+
for (let column = 0; column < scanColumns; column++) {
|
|
87
155
|
let found = lightest ? -Infinity : Infinity
|
|
88
|
-
for (let near = Math.max(0, column - 1); near <= Math.min(
|
|
89
|
-
for (let row = 0; row <
|
|
90
|
-
const level = levels[row *
|
|
156
|
+
for (let near = Math.max(0, column - 1); near <= Math.min(scanColumns - 1, column + 1); near++) {
|
|
157
|
+
for (let row = 0; row < scanRows; row++) {
|
|
158
|
+
const level = levels[row * scanColumns + near]
|
|
91
159
|
found = lightest ? Math.max(found, level) : Math.min(found, level)
|
|
92
160
|
}
|
|
93
161
|
}
|
|
94
162
|
ground.push(found)
|
|
95
163
|
}
|
|
96
|
-
return levels.map((level, index) => level - ground[index %
|
|
164
|
+
return levels.map((level, index) => level - ground[index % scanColumns])
|
|
97
165
|
}
|
|
98
166
|
|
|
99
167
|
const WRITTEN_SHARES = [0.8, 0.2, 0.95, 0.05] as const
|
|
@@ -102,20 +170,20 @@ export type ScanCorners = readonly [x0: number, y0: number, x1: number, y1: numb
|
|
|
102
170
|
|
|
103
171
|
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]
|
|
104
172
|
|
|
105
|
-
export function
|
|
173
|
+
export function sampleWrittenScan(width: number, height: number, luminance: Luminance, place: ScanRect | ScanCorners): Id | null {
|
|
106
174
|
const [x0, y0, x1, y1, x2, y2, x3, y3] = 'width' in place ? rectCorners(place) : place
|
|
107
|
-
const cell = Math.min(Math.hypot(x1 - x0, y1 - y0), Math.hypot(x2 - x3, y2 - y3)) /
|
|
175
|
+
const cell = Math.min(Math.hypot(x1 - x0, y1 - y0), Math.hypot(x2 - x3, y2 - y3)) / scanColumns
|
|
108
176
|
if (cell < 5) return null
|
|
109
177
|
const sampled = (inner: number): number[][] => {
|
|
110
178
|
const across = Math.max(2, Math.min(7, Math.floor(cell * inner)))
|
|
111
179
|
const cells: number[][] = []
|
|
112
|
-
for (let row = 0; row <
|
|
113
|
-
for (let column = 0; column <
|
|
180
|
+
for (let row = 0; row < scanRows; row++) {
|
|
181
|
+
for (let column = 0; column < scanColumns; column++) {
|
|
114
182
|
const values: number[] = []
|
|
115
183
|
for (let j = 0; j < across; j++) {
|
|
116
|
-
const v = (row + (1 - inner) / 2 + (inner * (j + 0.5)) / across) /
|
|
184
|
+
const v = (row + (1 - inner) / 2 + (inner * (j + 0.5)) / across) / scanRows
|
|
117
185
|
for (let i = 0; i < across; i++) {
|
|
118
|
-
const u = (column + (1 - inner) / 2 + (inner * (i + 0.5)) / across) /
|
|
186
|
+
const u = (column + (1 - inner) / 2 + (inner * (i + 0.5)) / across) / scanColumns
|
|
119
187
|
const px = Math.round((1 - v) * ((1 - u) * x0 + u * x1) + v * ((1 - u) * x3 + u * x2))
|
|
120
188
|
const py = Math.round((1 - v) * ((1 - u) * y0 + u * y1) + v * ((1 - u) * y3 + u * y2))
|
|
121
189
|
values.push(luminance(clamp(px, 0, width - 1), clamp(py, 0, height - 1)))
|
|
@@ -128,7 +196,7 @@ export function sampleWrittenScanCode(width: number, height: number, luminance:
|
|
|
128
196
|
return cells
|
|
129
197
|
}
|
|
130
198
|
const taken = (dark: readonly boolean[]): Id | null => {
|
|
131
|
-
const id =
|
|
199
|
+
const id = decodeScan(dark as boolean[]) ?? decodeScan(dark.map(bit => !bit))
|
|
132
200
|
return id
|
|
133
201
|
}
|
|
134
202
|
const middles = sampled(0.6)
|
|
@@ -141,31 +209,31 @@ export function sampleWrittenScanCode(width: number, height: number, luminance:
|
|
|
141
209
|
if (id) return id
|
|
142
210
|
}
|
|
143
211
|
}
|
|
144
|
-
return
|
|
212
|
+
return sampleCutScan((u, v) => {
|
|
145
213
|
const px = Math.round((1 - v) * ((1 - u) * x0 + u * x1) + v * ((1 - u) * x3 + u * x2))
|
|
146
214
|
const py = Math.round((1 - v) * ((1 - u) * y0 + u * y1) + v * ((1 - u) * y3 + u * y2))
|
|
147
215
|
return luminance(clamp(px, 0, width - 1), clamp(py, 0, height - 1))
|
|
148
216
|
}, cell, taken)
|
|
149
217
|
}
|
|
150
218
|
|
|
151
|
-
function
|
|
219
|
+
function sampleCutScan(at: (u: number, v: number) => number, cell: number, taken: (dark: readonly boolean[]) => Id | null): Id | null {
|
|
152
220
|
const n = Math.max(4, Math.min(8, Math.round(cell * 0.8)))
|
|
153
|
-
const count =
|
|
221
|
+
const count = scanColumns * scanRows, each = n * n
|
|
154
222
|
const light = new Float32Array(count * each)
|
|
155
|
-
for (let row = 0; row <
|
|
156
|
-
for (let column = 0; column <
|
|
157
|
-
const base = (row *
|
|
223
|
+
for (let row = 0; row < scanRows; row++) {
|
|
224
|
+
for (let column = 0; column < scanColumns; column++) {
|
|
225
|
+
const base = (row * scanColumns + column) * each
|
|
158
226
|
for (let j = 0; j < n; j++) {
|
|
159
|
-
for (let i = 0; i < n; i++) light[base + j * n + i] = at((column + 0.05 + (0.9 * (i + 0.5)) / n) /
|
|
227
|
+
for (let i = 0; i < n; i++) light[base + j * n + i] = at((column + 0.05 + (0.9 * (i + 0.5)) / n) / scanColumns, (row + 0.05 + (0.9 * (j + 0.5)) / n) / scanRows)
|
|
160
228
|
}
|
|
161
229
|
}
|
|
162
230
|
}
|
|
163
231
|
const share = new Float32Array(count)
|
|
164
|
-
for (let column = 0; column <
|
|
232
|
+
for (let column = 0; column < scanColumns; column++) {
|
|
165
233
|
const near: number[] = []
|
|
166
|
-
for (let other = Math.max(0, column - 1); other <= Math.min(
|
|
167
|
-
for (let row = 0; row <
|
|
168
|
-
const base = (row *
|
|
234
|
+
for (let other = Math.max(0, column - 1); other <= Math.min(scanColumns - 1, column + 1); other++) {
|
|
235
|
+
for (let row = 0; row < scanRows; row++) {
|
|
236
|
+
const base = (row * scanColumns + other) * each
|
|
169
237
|
for (let index = 0; index < each; index++) near.push(light[base + index])
|
|
170
238
|
}
|
|
171
239
|
}
|
|
@@ -173,8 +241,8 @@ function sampleCutScanCode(at: (u: number, v: number) => number, cell: number, t
|
|
|
173
241
|
const low = near[Math.floor(near.length * 0.1)], high = near[Math.floor(near.length * 0.9)]
|
|
174
242
|
if (high - low <= 16) return null
|
|
175
243
|
const cut = (low + high) / 2
|
|
176
|
-
for (let row = 0; row <
|
|
177
|
-
const index = row *
|
|
244
|
+
for (let row = 0; row < scanRows; row++) {
|
|
245
|
+
const index = row * scanColumns + column
|
|
178
246
|
let dark = 0
|
|
179
247
|
for (let k = 0; k < each; k++) if (light[index * each + k] < cut) dark++
|
|
180
248
|
share[index] = dark / each
|
|
@@ -211,7 +279,7 @@ function lineThrough(points: readonly (readonly [number, number])[]): { a: numbe
|
|
|
211
279
|
return { a: middle(points.map(([t, value]) => value - b * t)), b }
|
|
212
280
|
}
|
|
213
281
|
|
|
214
|
-
export function
|
|
282
|
+
export function locateWrittenScan(width: number, height: number, luminance: Luminance, chroma: Chroma): ScanFound | null {
|
|
215
283
|
const step = 2, columns = Math.floor(width / step), rows = Math.floor(height / step)
|
|
216
284
|
if (columns < 40 || rows < 10) return null
|
|
217
285
|
const size = columns * rows
|
|
@@ -286,7 +354,7 @@ export function locateWrittenScanCode(width: number, height: number, luminance:
|
|
|
286
354
|
const middleY = (corners[0][1] + corners[1][1] + corners[2][1] + corners[3][1]) / 4
|
|
287
355
|
for (const scale of [1, 0.97, 1.03]) {
|
|
288
356
|
const place = corners.flatMap(([x, y]) => [middleX + (x - middleX) * scale, middleY + (y - middleY) * scale]) as unknown as ScanCorners
|
|
289
|
-
const id =
|
|
357
|
+
const id = sampleWrittenScan(width, height, luminance, place)
|
|
290
358
|
if (id) return { id, rect: { x: left * step, y: top * step, width: w * step, height: h * step } }
|
|
291
359
|
}
|
|
292
360
|
}
|
|
@@ -294,7 +362,7 @@ export function locateWrittenScanCode(width: number, height: number, luminance:
|
|
|
294
362
|
return null
|
|
295
363
|
}
|
|
296
364
|
|
|
297
|
-
export function
|
|
365
|
+
export function scanRegions(width: number, height: number, foreground: Chroma): ScanRect[] {
|
|
298
366
|
const step = 2, columns = Math.floor(width / step), rows = Math.floor(height / step)
|
|
299
367
|
if (columns <= 0 || rows <= 0) return []
|
|
300
368
|
const mask = new Uint8Array(columns * rows)
|
|
@@ -396,14 +464,14 @@ export function locateScanFrame(width: number, height: number, luminance: Lumina
|
|
|
396
464
|
for (const dy of [0, -1, 1]) {
|
|
397
465
|
for (const dx of [0, -1, 1]) {
|
|
398
466
|
const at = offsetRect(rect, dx, dy)
|
|
399
|
-
const id =
|
|
467
|
+
const id = sampleScan(width, height, luminance, at)
|
|
400
468
|
if (id) return { id, rect: at }
|
|
401
469
|
}
|
|
402
470
|
}
|
|
403
471
|
}
|
|
404
472
|
return null
|
|
405
473
|
}
|
|
406
|
-
const colored =
|
|
474
|
+
const colored = scanRegions(width, height, (x, y) => luminance(x, y) > 70 && chroma(x, y))
|
|
407
475
|
for (const bounds of colored) {
|
|
408
476
|
const id = read(bounds)
|
|
409
477
|
if (id) return id
|
|
@@ -418,7 +486,7 @@ export function locateScanFrame(width: number, height: number, luminance: Lumina
|
|
|
418
486
|
}
|
|
419
487
|
for (const threshold of [(darkest + lightest) / 2, 60, 130, 200]) {
|
|
420
488
|
for (const light of [true, false]) {
|
|
421
|
-
const candidates =
|
|
489
|
+
const candidates = scanRegions(width, height, (x, y) => (light ? luminance(x, y) > threshold : luminance(x, y) < threshold))
|
|
422
490
|
for (const bounds of candidates) {
|
|
423
491
|
const id = read(bounds)
|
|
424
492
|
if (id) return id
|
|
@@ -428,13 +496,13 @@ export function locateScanFrame(width: number, height: number, luminance: Lumina
|
|
|
428
496
|
const w = width * 0.8
|
|
429
497
|
const guide = read({ x: (width - w) / 2, y: (height - w / 4) / 2, width: w, height: w / 4 })
|
|
430
498
|
if (guide) return guide
|
|
431
|
-
const field =
|
|
499
|
+
const field = locateWrittenScan(width, height, luminance, chroma)
|
|
432
500
|
if (field) return field
|
|
433
501
|
for (const bounds of tried) {
|
|
434
502
|
if (bounds.width < 80) continue
|
|
435
503
|
for (const fraction of [0, 0.03]) {
|
|
436
504
|
const rect = insetRect(bounds, bounds.width * fraction, bounds.height * fraction)
|
|
437
|
-
const id =
|
|
505
|
+
const id = sampleWrittenScan(width, height, luminance, rect)
|
|
438
506
|
if (id) return { id, rect }
|
|
439
507
|
}
|
|
440
508
|
}
|
package/src/architecture.ts
DELETED
|
@@ -1,129 +0,0 @@
|
|
|
1
|
-
import { parseCode, type CodeKind } from './shapes'
|
|
2
|
-
import { blockedCodeLetters, blockedProjectCode } from './words'
|
|
3
|
-
import { JUNCTION_SEPARATOR } from './junction'
|
|
4
|
-
|
|
5
|
-
export type Namespace = { shorthand: string; name: string }
|
|
6
|
-
export type Taxonomy = { shorthand: string; name: string; shape: CodeKind; pattern: string }
|
|
7
|
-
export type Part = { id: string; shape: CodeKind; name: string; path: string | null }
|
|
8
|
-
export type Architecture = { namespaces: Namespace[]; taxonomies: Taxonomy[]; parts: Part[]; facts: string[] }
|
|
9
|
-
export type Resolved = { id: string; shape: CodeKind | null; namespace?: Namespace; taxonomy?: Taxonomy; part?: Part; facts: string[] }
|
|
10
|
-
|
|
11
|
-
const SHAPES: CodeKind[] = ['account', 'list', 'project', 'item', 'event']
|
|
12
|
-
const list = <T>(value: unknown): T[] => (Array.isArray(value) ? value : []) as T[]
|
|
13
|
-
|
|
14
|
-
export function readArchitecture(text: string): Architecture {
|
|
15
|
-
const value = JSON.parse(text) as Partial<Architecture>
|
|
16
|
-
return { namespaces: list(value.namespaces), taxonomies: list(value.taxonomies), parts: list(value.parts), facts: list(value.facts) }
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
export function taxonomyOf(architecture: Architecture, id: string): Taxonomy | undefined {
|
|
20
|
-
const shape = parseCode(id)?.kind
|
|
21
|
-
return architecture.taxonomies.find(taxonomy => {
|
|
22
|
-
const at = taxonomy.pattern.replace(/\s/g, '').indexOf(taxonomy.shorthand)
|
|
23
|
-
return taxonomy.shape === shape && at >= 0 && id.slice(at, at + 2) === taxonomy.shorthand
|
|
24
|
-
})
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export function architectureHealth(architecture: Architecture, exists: (path: string) => boolean = () => true): string[] {
|
|
28
|
-
const problems: string[] = []
|
|
29
|
-
const seen = (values: string[], what: string) => values.forEach((value, index) => { if (values.indexOf(value) !== index) problems.push(`${what} ${value} is declared twice`) })
|
|
30
|
-
for (const { shorthand, name } of architecture.namespaces) {
|
|
31
|
-
if (!/^[A-Z]{2}$/.test(shorthand)) problems.push(`Namespace ${shorthand} is not two capitals`)
|
|
32
|
-
if (!name) problems.push(`Namespace ${shorthand} has no name`)
|
|
33
|
-
}
|
|
34
|
-
for (const { shorthand, name, shape, pattern } of architecture.taxonomies) {
|
|
35
|
-
if (!/^[a-z]{2}$/.test(shorthand)) problems.push(`Taxonomy ${shorthand} is not two small letters`)
|
|
36
|
-
if (!name) problems.push(`Taxonomy ${shorthand} has no name`)
|
|
37
|
-
if (!SHAPES.includes(shape)) problems.push(`Taxonomy ${shorthand} has no shape`)
|
|
38
|
-
const compact = String(pattern ?? '').replace(/\s/g, '')
|
|
39
|
-
if (compact.length !== 6 || !compact.includes(shorthand)) problems.push(`Taxonomy ${shorthand} has no six-character pattern holding ${shorthand}`)
|
|
40
|
-
}
|
|
41
|
-
seen(architecture.namespaces.map(namespace => namespace.shorthand), 'Namespace')
|
|
42
|
-
seen(architecture.taxonomies.map(taxonomy => taxonomy.shorthand), 'Taxonomy')
|
|
43
|
-
seen(architecture.parts.map(part => part.id), 'Id')
|
|
44
|
-
const ids = new Set(architecture.parts.map(part => part.id))
|
|
45
|
-
for (const part of architecture.parts) {
|
|
46
|
-
const shape = parseCode(part.id)?.kind
|
|
47
|
-
if (shape !== part.shape) problems.push(`${part.id} reads as ${shape ?? 'no shape'}, not ${part.shape}`)
|
|
48
|
-
else if (shape === 'project' ? blockedProjectCode(part.id) : blockedCodeLetters(part.id)) problems.push(`${part.id} uses blocked letters or digits`)
|
|
49
|
-
if (!part.name) problems.push(`${part.id} has no name`)
|
|
50
|
-
if (part.path && !exists(part.path)) problems.push(`${part.id}: ${part.path} is gone`)
|
|
51
|
-
}
|
|
52
|
-
for (const fact of architecture.facts) {
|
|
53
|
-
const [subject, relation, object, extra] = fact.split(' ')
|
|
54
|
-
if (extra !== undefined || !/^r[A-Za-z]{5}$/.test(relation ?? '')) problems.push(`Not a fact: ${fact}`)
|
|
55
|
-
else for (const id of [subject, object]) if (!ids.has(id)) problems.push(`Unknown id ${id} in: ${fact}`)
|
|
56
|
-
}
|
|
57
|
-
return problems
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
export function resolveCode(architecture: Architecture, value: string): Resolved[] {
|
|
61
|
-
const qualified = /^-([A-Z]{2})-(.+)$/.exec(value)
|
|
62
|
-
const ids = (qualified ? qualified[2] : value).split(JUNCTION_SEPARATOR)
|
|
63
|
-
return ids.map(id => {
|
|
64
|
-
const shape = parseCode(id)?.kind ?? null
|
|
65
|
-
const shorthand = qualified?.[1] ?? (shape === 'project' ? id.slice(0, 2) : undefined)
|
|
66
|
-
const namespace = architecture.namespaces.find(namespace => namespace.shorthand === shorthand) ?? (architecture.namespaces.length === 1 ? architecture.namespaces[0] : undefined)
|
|
67
|
-
const facts = architecture.facts.filter(fact => { const [subject, , object] = fact.split(' '); return subject === id || object === id })
|
|
68
|
-
return { id, shape, namespace, taxonomy: shape ? taxonomyOf(architecture, id) : undefined, part: architecture.parts.find(part => part.id === id), facts }
|
|
69
|
-
})
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
const nameOf = (architecture: Architecture, id: string) => architecture.parts.find(part => part.id === id)?.name ?? id
|
|
73
|
-
const readFact = (architecture: Architecture, fact: string) => { const [subject, relation, object] = fact.split(' '); return `${subject} ${relation} ${object} ${nameOf(architecture, subject)} → ${nameOf(architecture, object)}` }
|
|
74
|
-
|
|
75
|
-
export function describeResolved(architecture: Architecture, resolved: Resolved[]): string {
|
|
76
|
-
return resolved.map(({ id, shape, namespace, taxonomy, part, facts }) => [
|
|
77
|
-
`${id} ${part?.name ?? (shape ? 'not in .id' : 'not a code')}`,
|
|
78
|
-
` shape ${shape ?? '—'}`,
|
|
79
|
-
...(taxonomy ? [` taxonomy ${taxonomy.shorthand} · ${taxonomy.name}`] : []),
|
|
80
|
-
...(namespace ? [` namespace ${namespace.shorthand} · ${namespace.name}`] : []),
|
|
81
|
-
...(part?.path ? [` path ${part.path}`] : []),
|
|
82
|
-
...facts.map(fact => ` fact ${readFact(architecture, fact)}`),
|
|
83
|
-
].join('\n')).join('\n\n')
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
export function describeStatus(architecture: Architecture, problems: string[]): string {
|
|
87
|
-
const count = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`
|
|
88
|
-
const shapes = SHAPES.map(shape => [shape, architecture.parts.filter(part => part.shape === shape).length] as const).filter(([, n]) => n)
|
|
89
|
-
return [
|
|
90
|
-
`${count(architecture.parts.length, 'part')} · ${count(architecture.facts.length, 'fact')} · ${count(architecture.namespaces.length, 'namespace')} · ${count(architecture.taxonomies.length, 'taxonomy', 'taxonomies')}`,
|
|
91
|
-
problems.length ? `${count(problems.length, 'problem')}: run idv1 health` : 'healthy',
|
|
92
|
-
'',
|
|
93
|
-
...shapes.map(([shape, n]) => ` ${shape.padEnd(9)}${n}`),
|
|
94
|
-
...architecture.taxonomies.map(taxonomy => ` ${taxonomy.shorthand.padEnd(9)}${architecture.parts.filter(part => taxonomyOf(architecture, part.id) === taxonomy).length} ${taxonomy.name}`),
|
|
95
|
-
].join('\n')
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
export function describeArchitecture(architecture: Architecture): string {
|
|
99
|
-
const contains = architecture.facts.map(fact => fact.split(' ')).filter(([, relation]) => relation === 'rHasPt')
|
|
100
|
-
const children = (id: string) => contains.filter(([subject]) => subject === id).map(([, , object]) => object)
|
|
101
|
-
const roots = architecture.parts.filter(part => !contains.some(([, , object]) => object === part.id))
|
|
102
|
-
const line = (part: Part | undefined, id: string, depth: number) => `${' '.repeat(depth)}${id} ${part?.name ?? '?'}${part && taxonomyOf(architecture, id) ? ` (${taxonomyOf(architecture, id)!.name})` : ''}${part?.path ? ` ${part.path}` : ''}`
|
|
103
|
-
const tree = (id: string, depth: number, trail: Set<string>): string[] => trail.has(id) ? [] : [line(architecture.parts.find(part => part.id === id), id, depth), ...children(id).flatMap(child => tree(child, depth + 1, new Set([...trail, id])))]
|
|
104
|
-
return [
|
|
105
|
-
'Namespaces',
|
|
106
|
-
...architecture.namespaces.map(({ shorthand, name }) => ` ${shorthand} ${name}`),
|
|
107
|
-
'',
|
|
108
|
-
'Taxonomies',
|
|
109
|
-
...architecture.taxonomies.map(({ shorthand, name, shape, pattern }) => ` ${shorthand} ${name} ${shape} ${pattern}`),
|
|
110
|
-
'',
|
|
111
|
-
'Parts',
|
|
112
|
-
...roots.flatMap(part => tree(part.id, 1, new Set())),
|
|
113
|
-
'',
|
|
114
|
-
'Facts',
|
|
115
|
-
...architecture.facts.filter(fact => fact.split(' ')[1] !== 'rHasPt').map(fact => ` ${readFact(architecture, fact)}`),
|
|
116
|
-
].join('\n')
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
export function runArchitectureCommand(command: string | undefined, args: string[], text: string, exists?: (path: string) => boolean): { code: number; out: string } {
|
|
120
|
-
const architecture = readArchitecture(text)
|
|
121
|
-
const problems = architectureHealth(architecture, exists)
|
|
122
|
-
switch (command) {
|
|
123
|
-
case 'health': return { code: problems.length ? 1 : 0, out: problems.length ? problems.join('\n') : 'healthy' }
|
|
124
|
-
case 'status': return { code: 0, out: describeStatus(architecture, problems) }
|
|
125
|
-
case 'resolve': return args.length ? { code: 0, out: args.map(value => describeResolved(architecture, resolveCode(architecture, value))).join('\n\n') } : { code: 2, out: 'idv1 resolve <id | junction | -NS-id>' }
|
|
126
|
-
case 'architecture': case undefined: return { code: 0, out: describeArchitecture(architecture) }
|
|
127
|
-
default: return { code: 2, out: 'idv1 architecture | status | health | resolve <id>' }
|
|
128
|
-
}
|
|
129
|
-
}
|
package/src/index.ts
DELETED
package/src/junction.ts
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import { codeKind, type CodeKind } from './shapes'
|
|
2
|
-
|
|
3
|
-
export const JUNCTION_SEPARATOR = '-'
|
|
4
|
-
|
|
5
|
-
export function junction(...codes: string[]): string {
|
|
6
|
-
if (codes.length < 2) throw new Error('A junction joins two codes or more.')
|
|
7
|
-
for (const code of codes) if (!codeKind(code)) throw new Error(`${code} is no IDv1 code.`)
|
|
8
|
-
return codes.join(JUNCTION_SEPARATOR)
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
export function junctionParts(value: string): { code: string; kind: CodeKind }[] | null {
|
|
12
|
-
const codes = value.split(JUNCTION_SEPARATOR)
|
|
13
|
-
if (codes.length < 2) return null
|
|
14
|
-
const parts = codes.map(code => ({ code, kind: codeKind(code) }))
|
|
15
|
-
return parts.every((part): part is { code: string; kind: CodeKind } => part.kind !== null) ? parts : null
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
export const isJunction = (value: string): boolean => junctionParts(value) !== null
|
package/src/scanCodeDrawing.ts
DELETED
|
@@ -1,72 +0,0 @@
|
|
|
1
|
-
import { ALPHABET, parseCode } from './shapes'
|
|
2
|
-
const alphabet = ALPHABET
|
|
3
|
-
|
|
4
|
-
export const scanCodeColumns = 16
|
|
5
|
-
export const scanCodeRows = 4
|
|
6
|
-
export const CODE_END_RADIUS = 0.1
|
|
7
|
-
|
|
8
|
-
export function scanCodeChecksum(bytes: readonly number[]): number {
|
|
9
|
-
let crc = 0xffff
|
|
10
|
-
for (const byte of bytes) {
|
|
11
|
-
crc ^= byte << 8
|
|
12
|
-
for (let bit = 0; bit < 8; bit++) crc = ((crc << 1) ^ (crc & 0x8000 ? 0x1021 : 0)) & 0xffff
|
|
13
|
-
}
|
|
14
|
-
return crc
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
export function encodeScanCode(id: string): boolean[] | null {
|
|
18
|
-
if (!parseCode(id)) return null
|
|
19
|
-
let value = 0
|
|
20
|
-
for (const character of id) value = value * 62 + alphabet.indexOf(character)
|
|
21
|
-
const bytes = [3]
|
|
22
|
-
for (let shift = 32; shift >= 0; shift -= 8) bytes.push(Math.floor(value / 2 ** shift) & 255)
|
|
23
|
-
const crc = scanCodeChecksum(bytes)
|
|
24
|
-
bytes.push(crc >> 8, crc & 255)
|
|
25
|
-
return bytes.flatMap(byte => Array.from({ length: 8 }, (_, bit) => !!(byte & (1 << (7 - bit)))))
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
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 {
|
|
29
|
-
const round = (value: number) => Math.round(value * 1e4) / 1e4
|
|
30
|
-
const inked = (row: number, column: number) =>
|
|
31
|
-
row >= 0 && row < scanCodeRows && column >= 0 && column < scanCodeColumns && ink(bits[row * scanCodeColumns + column])
|
|
32
|
-
const r = Math.min(Math.max(radius, 0), 0.5) * cell
|
|
33
|
-
let d = ''
|
|
34
|
-
for (let row = 0; row < scanCodeRows; row++) {
|
|
35
|
-
for (let column = 0; column < scanCodeColumns;) {
|
|
36
|
-
if (!inked(row, column)) { column++; continue }
|
|
37
|
-
const start = column
|
|
38
|
-
while (column < scanCodeColumns && inked(row, column)) column++
|
|
39
|
-
const left = x + start * cell, right = x + column * cell, top = y + row * cell, bottom = top + cell
|
|
40
|
-
if (!r) {
|
|
41
|
-
d += `M${round(left)} ${round(top)}h${round(right - left)}v${round(cell)}h${round(left - right)}z`
|
|
42
|
-
continue
|
|
43
|
-
}
|
|
44
|
-
const end = (facing: number, inside: number) => !inked(facing, inside) ? r : 0
|
|
45
|
-
const tl = end(row - 1, start)
|
|
46
|
-
const tr = end(row - 1, column - 1)
|
|
47
|
-
const br = end(row + 1, column - 1)
|
|
48
|
-
const bl = end(row + 1, start)
|
|
49
|
-
const arc = (radius: number, toX: number, toY: number) => radius ? `A${round(radius)} ${round(radius)} 0 0 1 ${round(toX)} ${round(toY)}` : ''
|
|
50
|
-
d += `M${round(left + tl)} ${round(top)}H${round(right - tr)}${arc(tr, right, top + tr)}`
|
|
51
|
-
d += `V${round(bottom - br)}${arc(br, right - br, bottom)}`
|
|
52
|
-
d += `H${round(left + bl)}${arc(bl, left, bottom - bl)}`
|
|
53
|
-
d += `V${round(top + tl)}${arc(tl, left + tl, top)}Z`
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
if (!r) return d
|
|
57
|
-
for (let row = 0; row < scanCodeRows; row++) {
|
|
58
|
-
for (let column = 0; column < scanCodeColumns; column++) {
|
|
59
|
-
if (inked(row, column)) continue
|
|
60
|
-
const left = x + column * cell, top = y + row * cell
|
|
61
|
-
for (const [dy, dx] of [[-1, -1], [-1, 1], [1, 1], [1, -1]] as const) {
|
|
62
|
-
if (!inked(row + dy, column) || !inked(row, column + dx) || !inked(row + dy, column + dx)) continue
|
|
63
|
-
const cornerX = left + (dx > 0 ? cell : 0), cornerY = top + (dy > 0 ? cell : 0)
|
|
64
|
-
const alongX = cornerX - dx * r, alongY = cornerY - dy * r
|
|
65
|
-
const sweep = dx * dy > 0 ? 0 : 1
|
|
66
|
-
d += `M${round(cornerX)} ${round(cornerY)}H${round(alongX)}A${round(r)} ${round(r)} 0 0 ${sweep} ${round(cornerX)} ${round(alongY)}Z`
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
return d
|
|
71
|
-
}
|
|
72
|
-
|
package/src/space.ts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
const LETTERS = 52
|
|
2
|
-
const DIGITS = 10
|
|
3
|
-
export const TOTAL_ID_SPACE = (LETTERS + DIGITS) ** 6
|
|
4
|
-
const accounts = LETTERS ** 2 * DIGITS ** 4
|
|
5
|
-
const lists = DIGITS ** 2 * LETTERS ** 4
|
|
6
|
-
const projects = LETTERS ** 4 * DIGITS ** 2
|
|
7
|
-
const items = LETTERS ** 2 * DIGITS ** 2 * ((LETTERS + DIGITS) ** 2 - DIGITS ** 2)
|
|
8
|
-
|
|
9
|
-
export const ID_SPACE = { accounts, lists, projects, items, events: TOTAL_ID_SPACE - accounts - lists - projects - items } as const
|
|
10
|
-
export type IdSpaceKind = keyof typeof ID_SPACE
|
|
11
|
-
|
|
12
|
-
export function idUsage(kind: IdSpaceKind, used: number): { used: number; space: number; left: number; percent: number } {
|
|
13
|
-
const space = ID_SPACE[kind]
|
|
14
|
-
if (!Number.isSafeInteger(used) || used < 0) throw new RangeError('Usage must be a nonnegative safe integer.')
|
|
15
|
-
return { used, space, left: Math.max(0, space - used), percent: (used / space) * 100 }
|
|
16
|
-
}
|
|
File without changes
|