@wry-smile/lexid 0.0.0-stage → 0.1.0

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/package.json CHANGED
@@ -1,6 +1,100 @@
1
1
  {
2
2
  "name": "@wry-smile/lexid",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Composable human-readable identifiers powered by semantic dictionaries and secure randomness.",
5
+ "keywords": [
6
+ "dictionary",
7
+ "human-readable-id",
8
+ "identifier",
9
+ "random-name",
10
+ "slug",
11
+ "typescript"
12
+ ],
13
+ "homepage": "https://github.com/wry-smile/lexid#readme",
14
+ "bugs": "https://github.com/wry-smile/lexid/issues",
15
+ "license": "MIT",
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/wry-smile/lexid.git"
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "skills",
23
+ "README.md",
24
+ "README.zh-CN.md",
25
+ "LICENSE"
26
+ ],
27
+ "type": "module",
28
+ "sideEffects": false,
29
+ "types": "./dist/index.d.mts",
30
+ "exports": {
31
+ ".": {
32
+ "import": {
33
+ "types": "./dist/index.d.mts",
34
+ "default": "./dist/index.mjs"
35
+ },
36
+ "require": {
37
+ "types": "./dist/index.d.cts",
38
+ "default": "./dist/index.cjs"
39
+ }
40
+ },
41
+ "./dictionaries": {
42
+ "import": {
43
+ "types": "./dist/dictionaries.d.mts",
44
+ "default": "./dist/dictionaries.mjs"
45
+ },
46
+ "require": {
47
+ "types": "./dist/dictionaries.d.cts",
48
+ "default": "./dist/dictionaries.cjs"
49
+ }
50
+ },
51
+ "./patterns": {
52
+ "import": {
53
+ "types": "./dist/patterns.d.mts",
54
+ "default": "./dist/patterns.mjs"
55
+ },
56
+ "require": {
57
+ "types": "./dist/patterns.d.cts",
58
+ "default": "./dist/patterns.cjs"
59
+ }
60
+ },
61
+ "./random": {
62
+ "import": {
63
+ "types": "./dist/random.d.mts",
64
+ "default": "./dist/random.mjs"
65
+ },
66
+ "require": {
67
+ "types": "./dist/random.d.cts",
68
+ "default": "./dist/random.cjs"
69
+ }
70
+ }
71
+ },
72
+ "publishConfig": {
73
+ "access": "public"
74
+ },
75
+ "devDependencies": {
76
+ "@types/node": "^22.0.0",
77
+ "bumpp": "^12.3.0",
78
+ "oxfmt": "^0.80.0",
79
+ "oxlint": "^1.95.0",
80
+ "tsdown": "^0.21.0",
81
+ "typescript": "~5.9.3",
82
+ "vitest": "^4.0.0",
83
+ "yaml": "^2.8.0"
84
+ },
85
+ "engines": {
86
+ "node": ">=22"
87
+ },
88
+ "scripts": {
89
+ "build": "tsdown",
90
+ "typecheck": "tsc --noEmit",
91
+ "test": "vitest run",
92
+ "test:watch": "vitest",
93
+ "test:package": "node tests/pack-smoke.mjs",
94
+ "format": "oxfmt --write",
95
+ "format:check": "oxfmt --check",
96
+ "lint": "oxlint --deny-warnings",
97
+ "release": "bumpp --no-push",
98
+ "release:publish": "pnpm publish"
99
+ }
6
100
  }
@@ -0,0 +1,65 @@
1
+ ---
2
+ name: lexid
3
+ description: Integrate the LexID TypeScript library into Node.js or browser projects that need human-readable resource identifiers, service or instance names, URL slugs, semantic naming patterns, or custom dictionaries.
4
+ ---
5
+
6
+ # LexID Library Integration
7
+
8
+ Use LexID in Node.js 22+ or ES2022-capable browsers for new resource identifiers,
9
+ containers, service names, workspace slugs, and test fixtures. Use ESM in browsers.
10
+ The library uses `crypto.getRandomValues()`, which works on plain HTTP. Use a slugifier
11
+ for transforming existing text.
12
+
13
+ Use the host project's package manager to add the library when needed, for
14
+ example `pnpm add @wry-smile/lexid` after it is published. Reuse any existing LexID
15
+ dependency. Skill installation provides integration documentation only.
16
+
17
+ ```ts
18
+ import { lexid } from '@wry-smile/lexid'
19
+
20
+ const instanceName = lexid()
21
+ ```
22
+
23
+ ## Choose an API
24
+
25
+ | Need | API or composition |
26
+ | ------------------------------------------------------ | -------------------------------------------------------------------------------------- |
27
+ | Default semantic identifier | `lexid()` |
28
+ | Fixed order or custom segment count | `lexid({ segments })` |
29
+ | Four or five total segments | `pickPattern(fourSegmentPatterns)` or `pickPattern(fiveSegmentPatterns)` as `segments` |
30
+ | Fixed word, positional constraint, or mixed dictionary | Single-element array, `Array.filter`, or array spread |
31
+ | Custom templates | `pickPattern(patterns)` as `segments` |
32
+ | Custom separator or suffix | `separator` or a synchronous `suffix` callback |
33
+ | Batch or format check | `lexids(count, options)` or `isLexid(value, options)` |
34
+ | Standalone secure sampling | `random` from `@wry-smile/lexid/random` |
35
+
36
+ ## Customize with arrays and functions
37
+
38
+ Pass ordered arrays of candidate words to `segments`. The suffix adds one
39
+ segment. Compose frozen built-in dictionaries using filtering and spreading.
40
+ Check that filtered dictionaries have candidates, or use `pickPattern` to skip
41
+ templates containing empty dictionaries. Supply fixed words in single-element
42
+ arrays and keep each candidate intact.
43
+
44
+ ## Common mistakes
45
+
46
+ `segments: 5` is invalid. Pass `pickPattern(fiveSegmentPatterns)` to obtain
47
+ five total segments. Apply filters directly to the dictionary arrays. Supply
48
+ a callback such as `({ random }) => random.numeric(8)` for a numeric suffix.
49
+ For a custom separator or length limit, use matching options in `isLexid`.
50
+
51
+ ## Security and uniqueness
52
+
53
+ Use identifiers as public names. Generate passwords, access tokens, session
54
+ tokens, and secrets with tools designed for credentials. Keep sensitive data
55
+ out of identifiers and enforce authorization separately. Enforce uniqueness through a
56
+ database constraint and bounded retries for identifier collisions. Custom
57
+ suffix randomness depends on the callback implementation.
58
+
59
+ ## References
60
+
61
+ - [API contracts](references/api.md)
62
+ - [Dictionary categories and composition](references/dictionaries.md)
63
+ - [Default and custom patterns](references/patterns.md)
64
+ - [Business constraints and suffix callbacks](references/customization.md)
65
+ - [Application integration examples](references/examples.md)
@@ -0,0 +1,64 @@
1
+ # Public API
2
+
3
+ The root entry exports the functions, data, and types below. Use
4
+ `@wry-smile/lexid/dictionaries`, `@wry-smile/lexid/patterns`, and `@wry-smile/lexid/random` to import those
5
+ modules independently. Both ESM and CommonJS are supported.
6
+
7
+ | Export | Contract |
8
+ | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
9
+ | `lexid(options?: LexidOptions): string` | Samples an ordered set of word dictionaries and appends a suffix. Defaults to a uniformly chosen built-in template. |
10
+ | `lexids(count: number, options?: LexidOptions): string[]` | Generates independently per entry, with a fresh default pattern and suffix invocation per entry. Count must be a nonnegative safe integer and fit in a JavaScript array. Zero returns an empty array. Duplicates are possible. |
11
+ | `isLexid(value: string, options?: LexidValidateOptions): boolean` | Checks at least one lowercase ASCII word, one lowercase ASCII alphanumeric suffix, separators, and total length. Invalid values return false. Invalid options throw. |
12
+ | `pickPattern(patterns: Patterns): Pattern` | Uniformly selects an original nonempty template with nonempty dictionary arrays. Throws if no eligible pattern exists. The generator validates the words. |
13
+ | `defaultSuffix: SuffixGenerator` | Generates six lowercase alphanumeric characters with the context's random tools. |
14
+ | `defaultPatterns`, `fourSegmentPatterns`, `fiveSegmentPatterns` | Frozen collections of frozen dictionary combinations. |
15
+ | Dictionary exports | Frozen arrays of lowercase ASCII words. See [dictionary categories](dictionaries.md). |
16
+
17
+ ```ts
18
+ import type {
19
+ Dictionary,
20
+ LexidOptions,
21
+ LexidValidateOptions,
22
+ Pattern,
23
+ Patterns,
24
+ RandomUtils,
25
+ Segments,
26
+ SuffixContext,
27
+ SuffixGenerator,
28
+ } from '@wry-smile/lexid'
29
+
30
+ const sample: Dictionary = ['worker']
31
+ const segments: Segments = [sample]
32
+ const pattern: Pattern = segments
33
+ const patterns: Patterns = [pattern]
34
+ const suffix: SuffixGenerator = ({ random }: SuffixContext) => random.numeric(8)
35
+ const format: LexidValidateOptions = { separator: '_', maxLength: 40 }
36
+ const options: LexidOptions = { segments, suffix, ...format }
37
+ const sampleDigit = (random: RandomUtils) => random.int(10)
38
+ void [patterns, options, sampleDigit]
39
+ ```
40
+
41
+ `Dictionary` is `readonly string[]`. `Segments` and `Pattern` are
42
+ `readonly Dictionary[]`. `Patterns` is `readonly Pattern[]`. Both options
43
+ types accept a separator (default `-`, also accepts `_`, `.`, and `~`)
44
+ and a positive safe integer maximum length (default 63). Generation options
45
+ also accept `segments` and a synchronous `suffix` callback.
46
+
47
+ The generator checks every candidate, including holes in arrays. It invokes the
48
+ suffix once after selecting words, passing a frozen context with a frozen word
49
+ snapshot and the public `random` object. Empty or malformed suffixes and
50
+ oversized results throw. Callback exceptions propagate directly.
51
+
52
+ | Random method | Contract |
53
+ | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
54
+ | `int(max: number): number` | Uniform integer in `[0, max)`, with integer `max` from 1 through `2**48 - 1`. |
55
+ | `pick<T>(items: readonly T[]): T` | Uniform array index. Rejects empty or sparse arrays. Repeated values retain their weight. |
56
+ | `string(alphabet: string, length: number): string` | Samples from a nonempty alphabet deduplicated by Unicode code point. Length is a nonnegative safe integer counted in code points. |
57
+ | `numeric(length: number): string` | Uses digits 0–9. |
58
+ | `alphabetic(length: number): string` | Uses lowercase ASCII a–z. |
59
+ | `alphanumeric(length: number): string` | Uses lowercase ASCII letters and digits. |
60
+ | `hexadecimal(length: number): string` | Uses digits and lowercase a–f. |
61
+
62
+ Invalid argument types and formats generally throw `TypeError`. Invalid
63
+ numeric ranges, overlong identifiers, and collections with no eligible
64
+ pattern throw `RangeError`.
@@ -0,0 +1,32 @@
1
+ # Customization
2
+
3
+ Use one or more dictionaries and expect `segments.length + 1` total segments.
4
+ A one-word dictionary fixes that segment. Filter words by position or length
5
+ using normal array methods. Restrict the longest allowed candidate per segment
6
+ and budget for the separators and suffix when every result must fit.
7
+
8
+ ```ts
9
+ import { adjectives, isLexid, lexid, lexids, technologies } from '@wry-smile/lexid'
10
+ import type { LexidOptions } from '@wry-smile/lexid'
11
+
12
+ const options: LexidOptions = {
13
+ segments: [
14
+ adjectives.filter((word) => word.startsWith('s') && word.length <= 6),
15
+ technologies.filter((word) => word[1] === 'l'),
16
+ ['worker'],
17
+ ],
18
+ separator: '_',
19
+ maxLength: 40,
20
+ suffix: ({ words, random }) =>
21
+ words.map((word) => word.charAt(0)).join('') + random.string('23456789abcdef', 6),
22
+ }
23
+
24
+ const name = lexid(options)
25
+ isLexid(name, options)
26
+ lexids(5, options)
27
+ ```
28
+
29
+ Choose `-` for ordinary DNS-label-compatible identifiers with the default
30
+ length cap. The other supported separators are `_`, `.`, and `~`. Custom
31
+ suffixes can combine fixed characters, initials, and random characters. Return
32
+ a nonempty lowercase ASCII alphanumeric string synchronously.
@@ -0,0 +1,33 @@
1
+ # Dictionaries
2
+
3
+ Import the named exports from `@wry-smile/lexid` or `@wry-smile/lexid/dictionaries`.
4
+
5
+ | Category | Dictionary exports |
6
+ | ------------------- | ------------------------------------------------------------------------------ |
7
+ | Language | `adjectives`, `nouns`, `verbs`, `adverbs`, `modifiers` |
8
+ | Wildlife | `animals`, `birds`, `insects` |
9
+ | Plants | `plants`, `flowers`, `trees` |
10
+ | Outdoors | `nature`, `elements`, `space`, `weather`, `directions`, `seasons`, `geography` |
11
+ | Technology | `technologies`, `domains`, `categories`, `instruments` |
12
+ | Visual and cultural | `colors`, `materials`, `gemstones`, `mythology`, `music`, `architecture` |
13
+
14
+ Each built-in list is independently maintained, sorted, frozen, and contains
15
+ unique lowercase ASCII words. Prefer familiar, public-facing words of 3–12
16
+ characters. Common shorter words can be valid. Check licensing and attribution
17
+ before importing external word lists.
18
+
19
+ Custom dictionaries can contain any nonempty lowercase ASCII words. Duplicate
20
+ values in custom lists act as weights.
21
+
22
+ ```ts
23
+ import { lexid } from '@wry-smile/lexid'
24
+ import { adjectives, animals, birds } from '@wry-smile/lexid/dictionaries'
25
+
26
+ lexid({
27
+ segments: [
28
+ adjectives.filter((word) => word.startsWith('s')),
29
+ [...animals, ...birds],
30
+ ['gateway', 'worker'],
31
+ ],
32
+ })
33
+ ```
@@ -0,0 +1,54 @@
1
+ # Integration examples
2
+
3
+ ## Node.js instances, workspaces, routes, and test data
4
+
5
+ ```ts
6
+ import { adjectives, domains, isLexid, lexid, lexids, technologies } from '@wry-smile/lexid'
7
+
8
+ const instanceName = lexid()
9
+ const serviceName = lexid({ segments: [adjectives, technologies, ['worker']] })
10
+ const workspace = lexid({ segments: [adjectives, domains] })
11
+ const workspacePath = isLexid(workspace) ? `/workspaces/${workspace}` : undefined
12
+ const testNames = lexids(20)
13
+ void [instanceName, serviceName, workspacePath, testNames]
14
+ ```
15
+
16
+ ## NestJS service and storage
17
+
18
+ Define a naming provider and register it in the Nest module that creates
19
+ resources. The example is a dependency-free provider object. Import it into
20
+ the module's `providers` array and inject `namingProvider.provide` where needed.
21
+
22
+ ```ts
23
+ import { lexid } from '@wry-smile/lexid'
24
+
25
+ const namingProvider = {
26
+ provide: Symbol('resource-name'),
27
+ useValue: () => lexid(),
28
+ }
29
+ void namingProvider
30
+ ```
31
+
32
+ Apply a database UNIQUE constraint to the identifier column. Retry only
33
+ collisions from that constraint, with a bounded attempt count.
34
+
35
+ ```ts
36
+ import { lexid } from '@wry-smile/lexid'
37
+
38
+ async function createWorkspace(
39
+ insert: (id: string) => Promise<void>,
40
+ isIdentifierCollision: (error: unknown) => boolean,
41
+ ): Promise<string> {
42
+ for (let attempt = 0; attempt < 3; attempt++) {
43
+ const id = lexid()
44
+ try {
45
+ await insert(id)
46
+ return id
47
+ } catch (error) {
48
+ if (!isIdentifierCollision(error) || attempt === 2) throw error
49
+ }
50
+ }
51
+ throw new Error('Could not allocate workspace identifier')
52
+ }
53
+ void createWorkspace
54
+ ```
@@ -0,0 +1,32 @@
1
+ # Semantic patterns
2
+
3
+ A pattern is an ordered array of dictionaries. `fourSegmentPatterns` has
4
+ three dictionaries per pattern and `fiveSegmentPatterns` has four. The suffix
5
+ completes the identifier. Default styles include colors and wildlife,
6
+ materials and objects, and technologies and domains. `defaultPatterns`
7
+ combines both sets. Selection is uniform across eligible patterns.
8
+
9
+ ```ts
10
+ import { adjectives, domains, lexid } from '@wry-smile/lexid'
11
+ import { fiveSegmentPatterns, fourSegmentPatterns, pickPattern } from '@wry-smile/lexid/patterns'
12
+
13
+ lexid({ segments: pickPattern(fourSegmentPatterns) })
14
+ lexid({ segments: pickPattern(fiveSegmentPatterns) })
15
+ lexid({
16
+ segments: pickPattern([
17
+ [adjectives, domains],
18
+ [['local'], ['worker']],
19
+ ]),
20
+ })
21
+
22
+ const candidates = fiveSegmentPatterns.map((pattern) =>
23
+ pattern.map((dictionary, index) =>
24
+ index === 0 ? dictionary.filter((word) => word.startsWith('s')) : dictionary,
25
+ ),
26
+ )
27
+ lexid({ segments: pickPattern(candidates) })
28
+ ```
29
+
30
+ Filter before choosing a template. `pickPattern` skips empty templates and
31
+ templates containing empty dictionaries. Handle its error if all candidates
32
+ are eliminated.