@vllnt/convex-slugs 0.2.0-canary.eb878e4 → 0.2.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/CHANGELOG.md CHANGED
@@ -4,34 +4,20 @@ All notable changes to this project are documented here. The format is based on
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
5
5
  adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
- ## [0.2.0] - Unreleased
8
-
9
- ### Breaking
10
-
11
- Inputs that 0.1.0 accepted now throw a `ConvexError`:
12
-
13
- - `INVALID_OPTIONS` from `new Slugs(...)`: an empty `defaultScope`, a
14
- `minLength` or `maxLength` that is not an integer (for example `1.5` or
15
- `NaN`), a negative `minLength`, `minLength > maxLength`, or `maxLength < 1`.
16
- A `NaN` `maxLength` used to disable the length cap.
17
- - `INVALID_ARGUMENT` from the component mutations `reserve`, `release` and
18
- `rename`: an empty `scope`, an empty `resourceRef` (`reserve`), or `bounds`
19
- that are not integers or have `minLength > maxLength`. Rows that 0.1.0 stored
20
- under scope `""` can no longer be released or renamed.
7
+ ## [0.2.0] - 2026-11-28
21
8
 
22
9
  ### Fixed
23
10
 
24
11
  - `rename` no longer leaves a self-redirect when a slug is renamed back to an
25
12
  earlier name (A→B, then B→A left `redirectFor(A) === A` on a live slug). A
26
- redirect starting at the new live name is now removed.
27
- - Reserved words are normalized like slugs, so `reservedWords: ["Admin"]` blocks
28
- `admin` (previously never matched when `foldCase` was on).
13
+ redirect starting at the new live name is now removed. Rows 0.1.0 already
14
+ wrote stay until that slug is renamed again or released: call `resolve`
15
+ before `redirectFor`, as the README's `profileBySlug` example does.
29
16
  - A `pattern` with the `g` or `y` flag gives the same verdict on every call
30
17
  instead of alternating.
31
18
  - `@vllnt/convex-slugs/test` type-checks for consumers under `nodenext` and
32
19
  `bundler` resolution (`vite/client` reference, `.js` suffixes on relative
33
20
  imports).
34
- - Test files are no longer included in the published package.
35
21
  - `register` from `@vllnt/convex-slugs/test` accepts a `convex-test` instance
36
22
  built from the host app's schema, as the README shows; it used to require the
37
23
  component's own schema type.
@@ -40,27 +26,60 @@ Inputs that 0.1.0 accepted now throw a `ConvexError`:
40
26
 
41
27
  - The npm package ships `docs/API.md`, `CHANGELOG.md` and `llms.txt`, so the
42
28
  docs in `node_modules/@vllnt/convex-slugs/` match the installed version.
43
- `llms.txt` links to the shipped files with relative paths. `docs/API.md` now
44
- lists every entry point, the React hooks and the `register` test helper.
29
+ `llms.txt` links to the shipped files with relative paths. `docs/API.md` lists
30
+ every entry point, the React hooks and the `register` test helper.
45
31
 
46
32
  ### Changed
47
33
 
48
- - Docs: README install command targets the stable release, "Testing your app",
49
- error table, concurrency and normalization limits.
50
- - Release flow: npm trusted publishing with provenance; `@latest` only from a
51
- `vX.Y.Z` tag on `main`. Pinned CI actions, pnpm 10 with a release-age gate,
52
- low-memory dev defaults.
53
- - Release flow: every push to `main` that changes the package or its shipped
54
- docs publishes a `canary`; `pnpm test:package` in CI fails when a required
55
- file is missing from the packed tarball.
56
- - `package.json` `homepage` points to
34
+ The first four entries reject input that 0.1.0 accepted; each says what to do:
35
+
36
+ - `new Slugs(...)` throws a `ConvexError` with code `INVALID_OPTIONS` for an
37
+ empty `defaultScope`, a `minLength` or `maxLength` that is not an integer
38
+ (for example `1.5`, `NaN` or `Infinity`), a negative `minLength`,
39
+ `minLength > maxLength`, or `maxLength < 1`. A `NaN` or `Infinity`
40
+ `maxLength` used to disable the length cap. A `new Slugs` at module top level
41
+ throws when Convex loads that file, so every function in it fails. Fix the
42
+ options; for "no client limit" use `maxLength: 1024`, the component's cap.
43
+ - The component mutations `reserve`, `release` and `rename` throw a
44
+ `ConvexError` with code `INVALID_ARGUMENT` for an empty `scope`, an empty
45
+ `resourceRef` (`reserve`), or `bounds` that are not integers or have
46
+ `minLength > maxLength`. Rows that 0.1.0 stored under scope `""` can no longer
47
+ be released or renamed. Pass a non-empty `scope` (or omit it for
48
+ `defaultScope`) and a non-empty `resourceRef`.
49
+ - `reserve` and `rename` cap what they write at 1024 UTF-16 code units
50
+ (`string.length`), whatever `maxLength` or `bounds` say. A longer slug or
51
+ `toSlug` returns `{ ok: false, reason: "SLUG_INVALID" }`; a longer `scope`
52
+ (`reserve`, `rename`) or `resourceRef` (`reserve`) throws `INVALID_ARGUMENT`.
53
+ Shorten such values; `new Slugs` still accepts a `maxLength` over 1024, but
54
+ the component rejects the longer slugs. Rows stored over the cap before 0.2.0
55
+ stay readable, and `release` still removes them. Updating such a row: `rename`
56
+ from an over-cap slug to a shorter one works; `reserve` or `rename` onto an
57
+ over-cap slug returns `SLUG_INVALID` and leaves the row; `reserve` and
58
+ `rename` in an over-cap scope throw `INVALID_ARGUMENT`; a row with an over-cap
59
+ `resourceRef` keeps it when renamed.
60
+ - Reserved words are normalized like slugs (NFC, `trim()`, and lowercase unless
61
+ `foldCase: false`), so `reservedWords: ["Admin"]` now blocks `admin` with
62
+ `SLUG_RESERVED` (0.1.0 never matched it while `foldCase` was on). Remove a
63
+ word from `reservedWords` if it must stay claimable.
64
+ - `engines.node` is now `>=20` (was `>=18`): the lowest supported `convex`,
65
+ 1.45, needs Node.js 20, and convex 1.49 and newer need Node.js 22. Use
66
+ Node.js 20 or later. The peer range stays `convex@^1.45.0`.
67
+ - Release flow: `@latest` now comes only from a pushed `vX.Y.Z` tag on `main`
68
+ (was a manual workflow run with a version-bump input). A `canary` now
69
+ publishes on every push to `main` (was only pushes touching `src/`,
70
+ `package.json`, the lockfile or the publish workflow, and only while a
71
+ repository variable enabled it).
72
+ - Docs: README, `docs/API.md` and `llms.txt` rewritten to cover every export,
73
+ reason and error code, limit and gotcha; TSDoc on every public export.
74
+ - `package.json`: `description` is now "Convex component for unique slugs,
75
+ handles and usernames per scope, with rename redirects, a TypeScript client
76
+ and React hooks.", `keywords` list 11 search terms, and `homepage` points to
57
77
  https://oss.vllnt.com/packages/convex-slugs.
58
- - Docs: README "Related packages" lists only packages this one works with in
59
- code, which is none; the hint to use `@vllnt/convex-tokens` for secret keys
60
- moved to the intro.
61
- - Release flow: canary and stable publishes run `pnpm test:package` first; it
62
- type-checks every entry point and imports every runtime entry point,
63
- including `./react` with React 18.
78
+ - Internal: CI, release and docs checks, tooling and more tests.
79
+
80
+ ### Removed
81
+
82
+ - Test files are no longer included in the published package.
64
83
 
65
84
  ## [0.1.0] - 2026-09-01
66
85
 
package/README.md CHANGED
@@ -1,68 +1,37 @@
1
- <!-- Badges -->
1
+ # @vllnt/convex-slugs
2
2
 
3
- [![Convex Component](https://img.shields.io/badge/convex-component-EE342F.svg)](https://www.convex.dev/components)
4
- [![npm](https://img.shields.io/npm/v/@vllnt/convex-slugs.svg)](https://www.npmjs.com/package/@vllnt/convex-slugs)
5
- [![CI](https://github.com/vllnt/convex-slugs/actions/workflows/ci.yml/badge.svg)](https://github.com/vllnt/convex-slugs/actions/workflows/ci.yml)
6
- [![license](https://img.shields.io/npm/l/@vllnt/convex-slugs.svg)](./LICENSE)
3
+ Convex component for unique slugs, handles and usernames per scope, with rename redirects, a TypeScript client and React hooks.
7
4
 
8
- # @vllnt/convex-slugs
5
+ ![Slug Registry — @vllnt/convex-slugs](https://raw.githubusercontent.com/vllnt/convex-slugs/main/.github/assets/thumbnail.png)
9
6
 
10
- Unique slug and handle registry with rename redirects, as a Convex component.
7
+ ## For coding agents
11
8
 
12
- ```ts
13
- const slugs = new Slugs(components.slugs);
14
- await slugs.reserve(ctx, "ada", userId); // { ok: true } | { ok: false, reason }
15
- const ref = await slugs.resolve(ctx, "ada"); // resourceRef | null
16
- ```
9
+ Docs for the installed version are in `node_modules/@vllnt/convex-slugs/`:
10
+ `docs/API.md`, `llms.txt`, `CHANGELOG.md` and the TypeScript `src/`. Read them
11
+ before writing code against this package.
12
+
13
+ ## When to use
14
+
15
+ - Use it when each public name (article slug, `@handle`, username, workspace
16
+ slug) must be unique inside a scope, even under concurrent claims.
17
+ - Use it when renaming must keep old URLs working through a redirect.
18
+ - Use it when you need lookups both ways: slug to resource and resource to slug.
19
+ - Do not use it when the key must stay secret (share links, magic links,
20
+ invites): a slug is meant to be public (it appears in URLs). Use
21
+ [`@vllnt/convex-tokens`](https://oss.vllnt.com/packages/convex-tokens).
17
22
 
18
- Reserve a unique string (slug, `@handle`, username) against an opaque
19
- `resourceRef`, enforce uniqueness inside a scope, resolve it back, release it,
20
- and **redirect on rename**. Domain-neutral: article slugs, profile handles,
21
- workspace slugs — any public-URL key. For secret keys (share links, magic links)
22
- use [`@vllnt/convex-tokens`](https://oss.vllnt.com/packages/convex-tokens)
23
- instead: a slug is public and anyone can resolve it.
24
-
25
- ## Features
26
-
27
- - **Atomic uniqueness** per `(scope, slug)` — rides the Convex mutation
28
- transaction, no double-reserve.
29
- - **Scopes** — global by default, or namespace per tenant / locale / type.
30
- - **Rename + redirects** — renaming records an old → new redirect for link
31
- preservation.
32
- - **Chain-safe redirects** — chains collapse (A→B→C ⇒ `redirectFor(A) === C`),
33
- one row per source.
34
- - **Reverse lookup** — find the slug currently held by a `resourceRef`.
35
- - **Case folding + NFC** — case-insensitive (opt-out); NFC unifies canonically
36
- equivalent Unicode spellings, not all look-alike characters.
37
- - **Configurable input rules** — length bounds, charset `pattern`,
38
- `reservedWords`; typed rejection reasons.
39
- - **Typed write rejections** — expected conflicts return
40
- `{ ok: false, reason }`; invalid configuration and Convex/runtime failures can
41
- still throw.
42
-
43
- ## Installation
23
+ ## Install
44
24
 
45
25
  ```bash
46
26
  pnpm add @vllnt/convex-slugs
47
27
  ```
48
28
 
49
- Requires `convex@^1.45.0`; React `>=18` is optional for `./react` only. The
50
- command installs the stable release. Prereleases are published under the
51
- `canary` tag (`@vllnt/convex-slugs@canary`); pin a resolved canary version for
52
- reproducible installs.
53
-
54
- ### For coding agents
55
-
56
- The docs are bundled in the package at `node_modules/@vllnt/convex-slugs/docs/`,
57
- next to `llms.txt`, `CHANGELOG.md`, `src/` and `dist/`. They match the installed
58
- version. Read them before writing code against this package.
59
-
60
- ## Usage
29
+ ## Quick start
61
30
 
62
31
  ```ts
63
32
  // convex/convex.config.ts
64
- import { defineApp } from "convex/server";
65
33
  import slugs from "@vllnt/convex-slugs/convex.config";
34
+ import { defineApp } from "convex/server";
66
35
 
67
36
  const app = defineApp();
68
37
  app.use(slugs);
@@ -70,115 +39,325 @@ export default app;
70
39
  ```
71
40
 
72
41
  ```ts
73
- // convex/handles.ts — host owns auth; pass an opaque resourceRef in.
42
+ // convex/handles.ts
43
+ import { Slugs } from "@vllnt/convex-slugs";
44
+ import { ConvexError, v } from "convex/values";
45
+
74
46
  import { components } from "./_generated/api";
75
47
  import { mutation, query } from "./_generated/server";
76
- import { v } from "convex/values";
77
- import { Slugs } from "@vllnt/convex-slugs";
78
48
 
79
49
  const slugs = new Slugs(components.slugs);
80
50
 
81
51
  export const claim = mutation({
82
52
  args: { handle: v.string() },
53
+ returns: v.object({ ok: v.boolean(), reason: v.optional(v.string()) }),
83
54
  handler: async (ctx, { handle }) => {
84
- const identity = await ctx.auth.getUserIdentity();
85
- if (!identity) throw new Error("Unauthenticated");
86
- return slugs.reserve(ctx, handle, identity.tokenIdentifier);
55
+ const user = await ctx.auth.getUserIdentity();
56
+ if (user === null) throw new ConvexError("not signed in");
57
+ return slugs.reserve(ctx, handle, user.subject);
87
58
  },
88
59
  });
89
60
 
90
61
  export const lookup = query({
91
- args: { slug: v.string(), scope: v.optional(v.string()) },
92
- handler: (ctx, { slug }) => slugs.resolve(ctx, slug, "global"),
62
+ args: { slug: v.string() },
63
+ returns: v.union(v.string(), v.null()),
64
+ handler: (ctx, { slug }) => slugs.resolve(ctx, slug),
93
65
  });
94
66
  ```
95
67
 
96
- Client defaults: `defaultScope: "global"`, `foldCase: true`, `minLength: 1`,
97
- `maxLength: 256`, `reservedWords: []`; `pattern` is optional. Configure these in
98
- `new Slugs(component, options)`; see [the API reference](docs/API.md).
68
+ Run `npx convex dev` once to generate `components.slugs`. The component never
69
+ reads auth: the host picks the `resourceRef` (here the user's `subject`) and
70
+ decides who may claim, rename or release a slug. `lookup` is a public query, so
71
+ every caller sees the `resourceRef` it returns; see [Security](#security).
99
72
 
100
- ## API Reference
101
-
102
- | Method | Kind | Result |
103
- | ------------------------------------------- | -------- | --------------------------------------------------------------------------------------------- |
104
- | `reserve(ctx, slug, resourceRef, scope?)` | mutation | `{ ok: true }` or `{ ok: false, reason }` (`SLUG_INVALID` \| `SLUG_RESERVED` \| `SLUG_TAKEN`) |
105
- | `release(ctx, slug, scope?)` | mutation | `null` (idempotent) |
106
- | `rename(ctx, fromSlug, toSlug, scope?)` | mutation | `{ ok }` (`SLUG_INVALID` \| `SLUG_RESERVED` \| `SLUG_NOT_FOUND` \| `SLUG_TAKEN`) |
107
- | `resolve(ctx, slug, scope?)` | query | `resourceRef \| null` |
108
- | `redirectFor(ctx, slug, scope?)` | query | `toSlug \| null` |
109
- | `slugForResource(ctx, resourceRef, scope?)` | query | `slug \| null` |
73
+ ## API
110
74
 
111
75
  Full reference: [docs/API.md](docs/API.md).
112
76
 
113
- ## React
77
+ | Export | Import from | What it does |
78
+ | -------------------------------------------------------------------------- | ------------------------------------------ | --------------------------------------------------------------------------------------------------------------- |
79
+ | [`Slugs`](docs/API.md#slugs) | `@vllnt/convex-slugs` | Host client: `new Slugs(components.slugs, options?)` |
80
+ | [`reserve(ctx, slug, resourceRef, scope?)`](docs/API.md#reserve) | `Slugs` method, mutation | Claim a free slug; returns `{ ok, reason? }` |
81
+ | [`release(ctx, slug, scope?)`](docs/API.md#release) | `Slugs` method, mutation | Free a slug and the redirects pointing at it; returns `null` |
82
+ | [`rename(ctx, fromSlug, toSlug, scope?)`](docs/API.md#rename) | `Slugs` method, mutation | Move a held slug and record `fromSlug` -> `toSlug` |
83
+ | [`resolve(ctx, slug, scope?)`](docs/API.md#resolve) | `Slugs` method, query | The `resourceRef` holding `slug`, or `null` |
84
+ | [`redirectFor(ctx, slug, scope?)`](docs/API.md#redirectfor) | `Slugs` method, query | The live slug a renamed-away `slug` points to, or `null` |
85
+ | [`slugForResource(ctx, resourceRef, scope?)`](docs/API.md#slugforresource) | `Slugs` method, query | The slug held by `resourceRef`, or `null` |
86
+ | [`SlugsComponent`](docs/API.md#slugscomponent) | `@vllnt/convex-slugs` (type) | Type of `components.slugs` |
87
+ | [`SlugsOptions`](docs/API.md#slugsoptions) | `@vllnt/convex-slugs` (type) | `{ defaultScope?, foldCase?, minLength?, maxLength?, pattern?, reservedWords? }` |
88
+ | [`SlugWriteResult`](docs/API.md#slugwriteresult) | `@vllnt/convex-slugs` (type) | Result of `reserve` and `rename` |
89
+ | [`useSlugAvailable`](docs/API.md#useslugavailable) | `@vllnt/convex-slugs/react` | `useSlugAvailable(lookupRef, { slug, scope? })`: live "is it free?"; pass `scope` only if your query accepts it |
90
+ | [`useResolve`](docs/API.md#useresolve) | `@vllnt/convex-slugs/react` | `useResolve(lookupRef, { slug, scope? })`: live holder or `null`; pass `scope` only if your query accepts it |
91
+ | [`default` (component config)](docs/API.md#convexconfig) | `@vllnt/convex-slugs/convex.config` | Pass to `app.use(...)` |
92
+ | [`register`](docs/API.md#register) | `@vllnt/convex-slugs/test` | `register(t, name?)`: mount the component in `convex-test` |
93
+ | [`ComponentApi`](docs/API.md#componentapi) | `@vllnt/convex-slugs/_generated/component` | Generated type of the mounted component |
94
+
95
+ ## Common tasks
96
+
97
+ Rename the signed-in user's handle, then serve old URLs with a redirect:
114
98
 
115
- Optional, tree-shakeable hooks from `@vllnt/convex-slugs/react` — thin wrappers
116
- over `useQuery`; `react` is an optional peer dep. Each takes the host's
117
- re-exported `resolve` query reference.
99
+ ```ts
100
+ // convex/profiles.ts
101
+ import { Slugs } from "@vllnt/convex-slugs";
102
+ import { ConvexError, v } from "convex/values";
118
103
 
119
- ```tsx
120
- import { useSlugAvailable } from "@vllnt/convex-slugs/react";
121
- import { api } from "../convex/_generated/api";
104
+ import { components } from "./_generated/api";
105
+ import { mutation, query } from "./_generated/server";
106
+
107
+ const slugs = new Slugs(components.slugs);
122
108
 
123
- // `available` is undefined while loading, true when free, false when held.
124
- const { available, resourceRef } = useSlugAvailable(api.handles.lookup, {
125
- slug,
109
+ export const changeHandle = mutation({
110
+ args: { handle: v.string() },
111
+ returns: v.object({ ok: v.boolean(), reason: v.optional(v.string()) }),
112
+ handler: async (ctx, { handle }) => {
113
+ const user = await ctx.auth.getUserIdentity();
114
+ if (user === null) throw new ConvexError("not signed in");
115
+ const current = await slugs.slugForResource(ctx, user.subject);
116
+ if (current === null) return slugs.reserve(ctx, handle, user.subject);
117
+ return slugs.rename(ctx, current, handle);
118
+ },
119
+ });
120
+
121
+ export const profileBySlug = query({
122
+ args: { slug: v.string() },
123
+ returns: v.union(
124
+ v.object({ resourceRef: v.string() }),
125
+ v.object({ redirectTo: v.string() }),
126
+ v.null(),
127
+ ),
128
+ handler: async (ctx, { slug }) => {
129
+ const resourceRef = await slugs.resolve(ctx, slug);
130
+ if (resourceRef !== null) return { resourceRef };
131
+ const redirectTo = await slugs.redirectFor(ctx, slug);
132
+ return redirectTo === null ? null : { redirectTo };
133
+ },
126
134
  });
127
135
  ```
128
136
 
129
- | Hook | Returns |
130
- | ------------------------------------------------ | ----------------------------------------------------------------------------------------------- |
131
- | `useSlugAvailable(resolveRef, { slug, scope? })` | `{ available, resourceRef }` — `available` `undefined` while loading, `true` free, `false` held |
132
- | `useResolve(resolveRef, { slug, scope? })` | `resourceRef \| null \| undefined` (`undefined` while loading) |
137
+ Give each workspace its own article slugs, with a charset, a length cap and
138
+ reserved words. Call this from host code that has already checked the caller
139
+ may publish in the workspace:
140
+
141
+ ```ts
142
+ // convex/articles.ts
143
+ import { Slugs } from "@vllnt/convex-slugs";
144
+ import { v } from "convex/values";
145
+
146
+ import { components } from "./_generated/api";
147
+ import { internalMutation } from "./_generated/server";
133
148
 
134
- Availability is a lookup hint, not a reservation or validation of length,
135
- pattern, or reserved words. A concurrent claim can win; always check `reserve`'s
136
- result. The example intentionally exposes public handles in the global scope
137
- only.
149
+ const articles = new Slugs(components.slugs, {
150
+ defaultScope: "articles",
151
+ maxLength: 80,
152
+ pattern: /^[a-z0-9]+(?:-[a-z0-9]+)*$/,
153
+ reservedWords: ["new", "edit", "settings"],
154
+ });
138
155
 
139
- ## Security
156
+ export const publish = internalMutation({
157
+ args: { workspaceId: v.string(), articleId: v.string(), slug: v.string() },
158
+ returns: v.object({ ok: v.boolean(), reason: v.optional(v.string()) }),
159
+ handler: (ctx, { workspaceId, articleId, slug }) =>
160
+ articles.reserve(ctx, slug, articleId, `articles:${workspaceId}`),
161
+ });
162
+
163
+ export const unpublish = internalMutation({
164
+ args: { workspaceId: v.string(), slug: v.string() },
165
+ returns: v.null(),
166
+ handler: (ctx, { workspaceId, slug }) =>
167
+ articles.release(ctx, slug, `articles:${workspaceId}`),
168
+ });
169
+ ```
140
170
 
141
- - **Auth-agnostic** — the host authenticates the caller, decides who may claim a
142
- handle, and passes an opaque `resourceRef`.
143
- - **Management authorization** — before `release` or `rename`, verify ownership
144
- in the host. Authentication alone does not authorize changing another
145
- subject's slug.
146
- - **Opaque refs only** — `resourceRef` and `scope` are arbitrary strings; tables
147
- are sandboxed (reached only via the client).
148
- - **Boundary re-guard** — the component re-guards length at the trust boundary
149
- even if a caller bypasses the client.
150
- - **Uniqueness under concurrency** — each `reserve`/`rename` is one Convex
151
- mutation (serializable): of simultaneous claims on a slug, one succeeds and
152
- the rest get `SLUG_TAKEN`.
153
-
154
- See [docs/API.md](docs/API.md).
171
+ Show whether a handle is free while the user types. The hook takes your own
172
+ public query that returns `string | null`, here `lookup` from the Quick start:
155
173
 
156
- ## Testing
174
+ ```tsx
175
+ // src/HandleField.tsx
176
+ import { useSlugAvailable } from "@vllnt/convex-slugs/react";
177
+ import { useState } from "react";
157
178
 
158
- ```bash
159
- pnpm test # single run
160
- pnpm test:coverage # enforced 100% on covered files
179
+ import { api } from "../convex/_generated/api";
180
+
181
+ export function HandleField() {
182
+ const [handle, setHandle] = useState("");
183
+ const { available } = useSlugAvailable(api.handles.lookup, { slug: handle });
184
+ return (
185
+ <label>
186
+ Handle
187
+ <input
188
+ value={handle}
189
+ onChange={(event) => {
190
+ setHandle(event.target.value);
191
+ }}
192
+ />
193
+ {available === false ? " is taken" : null}
194
+ </label>
195
+ );
196
+ }
161
197
  ```
162
198
 
163
- Tests run against the real component runtime via `convex-test`
164
- (`@edge-runtime/vm`), not mocks.
199
+ ## Errors and fixes
200
+
201
+ `reserve` and `rename` do not throw for expected rejections. They return
202
+ `{ ok: false, reason }`:
203
+
204
+ | `reason` | Cause | Fix |
205
+ | ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
206
+ | `SLUG_INVALID` | After normalization the slug is empty, outside `minLength`..`maxLength`, fails `pattern`, or is over the component's cap of 1024 UTF-16 code units (`string.length`) | Show the rule to the user; for `rename` only `toSlug` is checked. Keep `maxLength` at 1024 or less so the client rule matches the cap |
207
+ | `SLUG_RESERVED` | The normalized slug is in `reservedWords` | Ask for another slug |
208
+ | `SLUG_TAKEN` | The slug is held in the scope (by anyone, including the same `resourceRef`), or `rename` got `fromSlug === toSlug` after normalization | Ask for another slug; for `rename`, skip the call when both names normalize to the same slug |
209
+ | `SLUG_NOT_FOUND` | `rename` got a `fromSlug` that is not held in the scope | Read the current slug with `slugForResource` and rename that one |
210
+
211
+ Invalid input throws a `ConvexError` whose `data` is `{ code, message }`; the
212
+ host sees the code as `error.data.code`. `reserve` and `rename` check the slug in
213
+ the client first, so a slug that fails those checks returns `SLUG_INVALID` (or
214
+ `SLUG_RESERVED`) before the component sees an empty scope.
215
+
216
+ | Code | Message | Cause | Fix |
217
+ | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------- |
218
+ | `INVALID_OPTIONS` | `Slugs options: defaultScope must be non-empty; minLength and maxLength must be integers with 0 <= minLength <= maxLength and maxLength >= 1` | `new Slugs(...)` got an empty `defaultScope`, a non-integer or negative `minLength`, a non-integer `maxLength`, or `maxLength` below `max(1, minLength)` | Fix the options. A `new Slugs` at module top level throws when Convex loads that file, so every function in it fails |
219
+ | `INVALID_ARGUMENT` | `scope and resourceRef must be non-empty, and at most 1024 UTF-16 code units on reserve and rename; bounds must be integers with min <= max` | `reserve`, `release` or `rename` got `scope: ""`, or `reserve` got `resourceRef: ""`; `reserve` or `rename` got a `scope`, or `reserve` a `resourceRef`, over 1024 UTF-16 code units; or a direct component call passed `bounds` that are not integers with `minLength <= maxLength` | Pass a non-empty scope (or omit it for `defaultScope`) and a non-empty `resourceRef`, each at most 1024 UTF-16 code units |
220
+
221
+ Arguments of the wrong type are rejected by Convex argument validation before
222
+ the component runs.
223
+
224
+ ## Limits and gotchas
225
+
226
+ - Slugs are normalized before every write and lookup: Unicode NFC, then
227
+ `trim()`, then `toLowerCase()` unless `foldCase: false`. `" Ada "` and `"ada"`
228
+ are the same slug by default. NFC does not merge look-alike characters from
229
+ different scripts, compatibility forms (NFKC) or zero-width characters; use
230
+ `pattern` to restrict the alphabet.
231
+ - `minLength` and `maxLength` count UTF-16 code units of the normalized slug
232
+ (a single emoji such as 😀 counts 2; flags and joined emoji count more).
233
+ Defaults: `minLength: 1`, `maxLength: 256`,
234
+ `defaultScope: "global"`, `foldCase: true`, `reservedWords: []`, no
235
+ `pattern`. An empty slug is always `SLUG_INVALID`, even with `minLength: 0`.
236
+ - The component caps what `reserve` and `rename` write at 1024 UTF-16 code
237
+ units (`string.length`, counted like `maxLength`), whatever `maxLength` or
238
+ `bounds` say: a longer slug returns `SLUG_INVALID`, and a longer `scope` or
239
+ `resourceRef` throws `INVALID_ARGUMENT`. For example 512 😀 (1024 units)
240
+ passes and 513 (1026 units) is rejected. `new Slugs` still accepts a
241
+ `maxLength` over 1024, but slugs longer than 1024 are rejected by the
242
+ component. `release` and the queries are not capped.
243
+ - Rows that a version before 0.2.0 stored with a slug, `scope` or
244
+ `resourceRef` over 1024 units stay readable with `resolve`, `redirectFor`
245
+ and `slugForResource`, and `release` removes them. `rename` from such a slug
246
+ to a shorter one works and records the redirect; `reserve` or `rename` onto
247
+ such a slug returns `SLUG_INVALID`; `reserve` and `rename` in such a scope
248
+ throw `INVALID_ARGUMENT`. A row with a long `resourceRef` keeps it when
249
+ renamed.
250
+ - `pattern` and `reservedWords` run against the normalized slug, so with
251
+ `foldCase: true` a pattern of `/^[a-z]+$/` accepts `"ADA"`.
252
+ - `release` is idempotent and always returns `null`: releasing a slug that is
253
+ not held does nothing and does not tell you so. It does not check who holds
254
+ the slug.
255
+ - `reserve` does not limit one slug per `resourceRef`; one resource can hold
256
+ several slugs, and `slugForResource` then returns one of them.
257
+ - Reserving a name that was renamed away deletes its redirect: old links stop
258
+ redirecting and resolve to the new holder.
259
+ - `resolve` of an old name returns `null` after a rename. Call `redirectFor` to
260
+ find the live slug, then `resolve` that. Redirect chains are collapsed, so
261
+ one `redirectFor` call is enough.
262
+ - `useSlugAvailable` and `useResolve` are a hint. They do not check length,
263
+ `pattern` or reserved words, an empty slug reads as available, and another
264
+ user can claim the slug before `reserve` runs. Always check `reserve`'s
265
+ result.
266
+ - Scopes are separate namespaces and are not checked against a list: a wrong
267
+ scope returns `null` from every query. Changing `foldCase` or `defaultScope`
268
+ later does not migrate stored rows.
269
+ - Rows that 0.1.0 stored under scope `""` can still be read with `resolve`,
270
+ `redirectFor` and `slugForResource`, but `reserve`, `release` and `rename`
271
+ reject `scope: ""` with `INVALID_ARGUMENT`.
272
+ - There is no list, search or history API. The component stores only the
273
+ current holder of each slug and one redirect per old name.
274
+
275
+ ## Compatibility
276
+
277
+ - Peer dependency: `convex@^1.45.0`. CI runs the unit tests on the locked convex
278
+ version (1.51.0), and type-checks and runs the packed package against convex
279
+ 1.45.0.
280
+ - Node.js: `engines.node` is `>=20`. convex 1.45 to 1.48 require Node.js 20 or
281
+ later; convex 1.49 and newer require Node.js 22 or later. ES modules only.
282
+ - `Slugs` runs in Convex queries, mutations and actions: it only calls
283
+ `ctx.runQuery` and `ctx.runMutation`.
284
+ - React: optional peer `react@>=18`, used only by `@vllnt/convex-slugs/react`.
285
+ The hooks call `useQuery` from `convex/react`, so they need a
286
+ `ConvexProvider` above them. The packed package is type-checked and imported
287
+ with React 18.3.
288
+ - `@vllnt/convex-slugs/test` needs `convex-test`, `vitest`, `vite` and
289
+ `@edge-runtime/vm`, with the Vitest config shown under Testing.
290
+
291
+ ## Testing
292
+
293
+ Mount the component in your own `convex-test` suite with `register`. Use the
294
+ Vitest settings `convex-test` recommends (edge runtime, `convex-test` inlined):
165
295
 
166
- ### Testing your app
296
+ ```ts
297
+ // vitest.config.mts
298
+ import { defineConfig } from "vitest/config";
167
299
 
168
- `@vllnt/convex-slugs/test` exports `register(t, name = "slugs")` to mount the
169
- component in a `convex-test` instance. It needs `convex-test` and `vitest` (with
170
- Vite's `import.meta.glob`) in the consuming app:
300
+ export default defineConfig({
301
+ test: {
302
+ environment: "edge-runtime",
303
+ server: { deps: { inline: ["convex-test"] } },
304
+ },
305
+ });
306
+ ```
171
307
 
172
308
  ```ts
309
+ // convex/handles.test.ts
173
310
  /// <reference types="vite/client" />
174
- import { convexTest } from "convex-test";
175
311
  import { register } from "@vllnt/convex-slugs/test";
312
+ import { convexTest } from "convex-test";
313
+ import { expect, test } from "vitest";
314
+
315
+ import { api } from "./_generated/api";
176
316
  import schema from "./schema";
177
317
 
178
- const t = convexTest(schema, import.meta.glob("./**/*.ts"));
179
- register(t);
318
+ test("a handle can be claimed once, in any case", async () => {
319
+ const t = convexTest(schema, import.meta.glob("./**/*.ts"));
320
+ register(t);
321
+ const ada = t.withIdentity({ subject: "user-ada" });
322
+ const bob = t.withIdentity({ subject: "user-bob" });
323
+ expect(await ada.mutation(api.handles.claim, { handle: "Ada" })).toEqual({
324
+ ok: true,
325
+ });
326
+ expect(await bob.mutation(api.handles.claim, { handle: "ADA" })).toEqual({
327
+ ok: false,
328
+ reason: "SLUG_TAKEN",
329
+ });
330
+ expect(await t.query(api.handles.lookup, { slug: "ada" })).toBe("user-ada");
331
+ });
180
332
  ```
181
333
 
334
+ `register(t, name)` takes the mount name when you used
335
+ `app.use(slugs, { name })`.
336
+
337
+ This repository's own tests run on the simulated `convex-test` runtime
338
+ (`pnpm test:coverage`, 100% coverage enforced), including concurrent claims of
339
+ one slug.
340
+
341
+ ## Security
342
+
343
+ - The component does not authenticate. The host must authorize every call:
344
+ check that the caller owns a slug before `rename` or `release`, and derive
345
+ `resourceRef` and `scope` on the server; never accept them from the client.
346
+ - `resolve` returns the `resourceRef`. A public query that forwards it shows
347
+ that value to every caller, so use refs you are willing to publish.
348
+ - Scopes are namespaces, not access control.
349
+ - The tables are reachable only through the component's functions, and those
350
+ are callable only from the host's own functions. A host that calls
351
+ `components.slugs` directly instead of through `Slugs` skips normalization,
352
+ `pattern` and reserved words; the component then only rejects an empty slug
353
+ and one outside the `bounds` the caller passes or over the 1024-unit cap.
354
+ - Each `reserve` and `rename` is one Convex mutation (serializable): of
355
+ simultaneous claims on one slug, one succeeds and the others get
356
+ `SLUG_TAKEN`.
357
+
358
+ Report vulnerabilities as described in
359
+ [SECURITY.md](https://github.com/vllnt/convex-slugs/blob/main/SECURITY.md).
360
+
182
361
  ## Related packages
183
362
 
184
363
  None. This package has no dependency, shared test or example with another
@@ -189,17 +368,22 @@ package.
189
368
  See
190
369
  [CONTRIBUTING.md](https://github.com/vllnt/convex-slugs/blob/main/CONTRIBUTING.md).
191
370
 
192
- ## Author
371
+ ## Links
193
372
 
194
- Built by [bntvllnt](https://github.com/bntvllnt) ·
195
- [bntvllnt.com](https://bntvllnt.com) · [X @bntvllnt](https://x.com/bntvllnt)
196
-
197
- If this is useful, [sponsor the work](https://github.com/sponsors/bntvllnt).
373
+ - Docs and changelog: [oss.vllnt.com/packages/convex-slugs](https://oss.vllnt.com/packages/convex-slugs) · [release feed](https://oss.vllnt.com/packages/convex-slugs/rss.xml)
374
+ - All @vllnt packages: [oss.vllnt.com](https://oss.vllnt.com) · [search packages and docs on index.vllnt.com](https://index.vllnt.com)
375
+ - Source and issues: [GitHub](https://github.com/vllnt/convex-slugs) · [issues](https://github.com/vllnt/convex-slugs/issues) · [npm](https://www.npmjs.com/package/@vllnt/convex-slugs)
376
+ - Questions and updates: [Discord](https://bntvllnt.com/discord) · [X @bntvllnt](https://x.com/bntvllnt)
377
+ - Company and author: [vllnt.com](https://vllnt.com) · [bntvllnt.com](https://bntvllnt.com) · [GitHub @bntvllnt](https://github.com/bntvllnt) · [LinkedIn](https://linkedin.com/in/bntvllnt)
378
+ - Sponsor: [GitHub Sponsors](https://github.com/sponsors/bntvllnt)
198
379
 
199
380
  ## License
200
381
 
201
- MIT — see [LICENSE](LICENSE).
382
+ MIT. See [LICENSE](LICENSE).
383
+
384
+ [![npm](https://img.shields.io/npm/v/@vllnt/convex-slugs.svg)](https://www.npmjs.com/package/@vllnt/convex-slugs)
385
+ [![CI](https://github.com/vllnt/convex-slugs/actions/workflows/ci.yml/badge.svg)](https://github.com/vllnt/convex-slugs/actions/workflows/ci.yml)
202
386
 
203
387
  ---
204
388
 
205
- Part of vllnt oss: https://oss.vllnt.com
389
+ Part of [vllnt open source](https://oss.vllnt.com) · [Package page](https://oss.vllnt.com/packages/convex-slugs) · [vllnt.com](https://vllnt.com) · Built by [bntvllnt](https://bntvllnt.com)