@klnap/payload-typeid 0.1.1 → 0.3.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 +28 -0
- package/README.md +191 -127
- package/dist/index.d.ts +1 -1
- package/dist/index.js +176 -44
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,33 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- fde3889: On PostgreSQL, install database guards for managed tables: generate a TypeID for raw SQL inserts without an ID, reject IDs with the wrong prefix or shape, and reject changes to an existing ID. Guards run on every Payload start and do not apply to other adapters.
|
|
8
|
+
- ee07f97: Manage every collection by default. Registering `typeId()` gives each collection a TypeID prefix derived from its slug using Payload's singularization. Set `custom.typeId` to a string to override, or to `false` to opt out. Central `typeId({ collections })` entries apply when a collection omits `custom.typeId`.
|
|
9
|
+
|
|
10
|
+
Breaking: this replaces the explicit opt-in from 0.2.0. Registering the plugin changes the ID type of every collection that does not opt out. Migrate existing data or set `custom.typeId: false` on those collections before upgrading.
|
|
11
|
+
|
|
12
|
+
## 0.2.0
|
|
13
|
+
|
|
14
|
+
### Minor Changes
|
|
15
|
+
|
|
16
|
+
- 0407e99: Make TypeID management explicit opt-in. `typeId()` no longer changes every collection; a collection is managed only when `custom.typeId` or `typeId({ collections })` enables it.
|
|
17
|
+
|
|
18
|
+
Breaking changes:
|
|
19
|
+
- Rename the model-level key from `custom.typeid` to `custom.typeId`. The obsolete key now throws a configuration error.
|
|
20
|
+
- Accept `true`, a prefix string, `false`, or omission. `true` derives a singular prefix from the collection slug (`articles` to `article`, `article-authors` to `article_author`). A string uses the exact prefix. `false` or omission leaves the native ID strategy unchanged.
|
|
21
|
+
- Model-level settings override central settings, including `true` and `false`.
|
|
22
|
+
- Reject `true` and prefix strings on Globals. Globals accept `false` or omission only.
|
|
23
|
+
- Reject slugs whose derived prefix is ambiguous, such as `APIKeys` or `users-2fa`, and recommend an explicit prefix.
|
|
24
|
+
|
|
25
|
+
Existing collections that relied on the previous default are no longer managed. Enabling TypeIDs on a collection with existing records changes its ID and relationship column types; migrate data before enabling it.
|
|
26
|
+
|
|
27
|
+
### Patch Changes
|
|
28
|
+
|
|
29
|
+
- 4648121: Shorten the README to the essentials: installation, quick start, configuration, utilities, limits, and compatibility.
|
|
30
|
+
|
|
3
31
|
## 0.1.1
|
|
4
32
|
|
|
5
33
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
# @klnap/payload-typeid
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Readable, type-prefixed document IDs for Payload CMS. An ID is a prefix plus a UUIDv7 in a compact suffix:
|
|
4
|
+
|
|
5
|
+
```text
|
|
6
|
+
article_01m8d47saaepfr8kaw7mqdxs1h
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
It is the document's one native Payload ID. The package adds no second identifier and no runtime dependencies.
|
|
10
|
+
|
|
11
|
+
## What changes
|
|
12
|
+
|
|
13
|
+
Registering `typeId()` manages **every collection** with a TypeID prefix derived from its slug. You do not need to configure each collection. Opt out or override where needed.
|
|
14
|
+
|
|
15
|
+
| Collection | Without `typeId()` | With `typeId()` |
|
|
16
|
+
| -------------------------------------- | ------------------- | ------------------------------------ |
|
|
17
|
+
| `articles` | Payload's native ID | `article_01m8d47saaepfr8kaw7mqdxs1h` |
|
|
18
|
+
| `users` | Payload's native ID | `user_…` |
|
|
19
|
+
| `articles` with `custom.typeId: "art"` | Payload's native ID | `art_…` |
|
|
20
|
+
| `users` with `custom.typeId: false` | Payload's native ID | Payload's native ID |
|
|
21
|
+
|
|
22
|
+
Globals are not affected: they keep Payload's ID strategy.
|
|
23
|
+
|
|
24
|
+
**Upgrading an existing project is a data migration.** Every managed collection changes its ID type and its relationship columns. Existing documents keep their IDs until you migrate them. Before you register `typeId()` on a project with data, either migrate that data or set `custom.typeId: false` on each collection you do not want to change. See [Enabling on existing data](#enabling-on-existing-data).
|
|
25
|
+
|
|
26
|
+
## Installation
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
bun add @klnap/payload-typeid
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
npm install @klnap/payload-typeid
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Quick start
|
|
4
37
|
|
|
5
38
|
```ts
|
|
6
39
|
import { buildConfig, type CollectionConfig } from "payload";
|
|
@@ -8,64 +41,127 @@ import { typeId } from "@klnap/payload-typeid";
|
|
|
8
41
|
|
|
9
42
|
const Articles: CollectionConfig = {
|
|
10
43
|
slug: "articles",
|
|
11
|
-
custom: { typeid: "article" },
|
|
12
|
-
fields: [],
|
|
13
|
-
};
|
|
14
|
-
|
|
15
|
-
const Authors: CollectionConfig = {
|
|
16
|
-
slug: "authors",
|
|
17
|
-
custom: { typeid: "author" },
|
|
18
44
|
fields: [],
|
|
19
45
|
};
|
|
20
46
|
|
|
21
|
-
const
|
|
22
|
-
slug: "
|
|
23
|
-
custom: { typeid: "category" },
|
|
47
|
+
const Users: CollectionConfig = {
|
|
48
|
+
slug: "users",
|
|
24
49
|
fields: [],
|
|
25
50
|
};
|
|
26
51
|
|
|
27
52
|
export default buildConfig({
|
|
28
|
-
collections: [Articles,
|
|
53
|
+
collections: [Articles, Users],
|
|
29
54
|
plugins: [typeId()],
|
|
30
55
|
});
|
|
31
56
|
```
|
|
32
57
|
|
|
33
|
-
|
|
58
|
+
`articles` gets `article_…` IDs and `users` gets `user_…` IDs, with no per-collection configuration. Register `typeId()` after plugins that add collections, so it sees the final collection list.
|
|
34
59
|
|
|
35
|
-
|
|
36
|
-
article_01m8d47saaepfr8kaw7mqdxs1h
|
|
37
|
-
author_01m8d47sabf8ca5x5s9smzr0qz
|
|
38
|
-
category_01m8d47sabeyjvrxppjadz5h5w
|
|
39
|
-
```
|
|
60
|
+
## How it works
|
|
40
61
|
|
|
41
|
-
|
|
62
|
+
The plugin uses Payload's native custom ID mechanism, a top-level field named `id`. It does not change the database adapter. For each managed collection, it:
|
|
42
63
|
|
|
43
|
-
|
|
64
|
+
- prepends an `id` text field whose `defaultValue` generates a TypeID with the collection's prefix;
|
|
65
|
+
- adds a `beforeChange` hook that keeps the generated ID on create, keeps the stored ID on update, and generates a fresh ID on duplicate;
|
|
66
|
+
- adds a `beforeOperation` guard that rejects `customID` and `data.id` on create and `data.id` on update, because the plugin owns the ID.
|
|
44
67
|
|
|
45
|
-
|
|
68
|
+
The plugin runs last (`order` is the maximum), so its `id` field and hooks apply after other plugins.
|
|
46
69
|
|
|
47
|
-
|
|
48
|
-
- Choose semantic prefixes on each collection or centrally in plugin options.
|
|
49
|
-
- Exclude collections while preserving their configured ID strategy.
|
|
50
|
-
- Generate new UUIDv7 IDs on document creation and duplication.
|
|
51
|
-
- Generate, validate, parse, and convert TypeIDs with the exported utilities.
|
|
52
|
-
- Add no third-party runtime dependencies.
|
|
70
|
+
## Configuration
|
|
53
71
|
|
|
54
|
-
|
|
72
|
+
Each collection's prefix is resolved in this order. The first value that is set wins:
|
|
55
73
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
74
|
+
1. `custom.typeId` on the collection.
|
|
75
|
+
2. The central `typeId({ collections })` entry for its slug.
|
|
76
|
+
3. The default: a prefix derived from the slug.
|
|
59
77
|
|
|
60
|
-
|
|
61
|
-
|
|
78
|
+
### On the collection: `custom.typeId`
|
|
79
|
+
|
|
80
|
+
| Value | Effect |
|
|
81
|
+
| ------- | ----------------------------------------------------------------------------- |
|
|
82
|
+
| `"art"` | Use exactly this prefix. Use it when the derived prefix is not what you want. |
|
|
83
|
+
| `true` | Derive the prefix from the slug. Same as omitting the value. |
|
|
84
|
+
| `false` | Opt out: keep Payload's native ID strategy for this collection. |
|
|
85
|
+
| omitted | Use the central entry, or derive the prefix from the slug. |
|
|
86
|
+
|
|
87
|
+
### Centrally: `typeId({ collections })`
|
|
88
|
+
|
|
89
|
+
```ts
|
|
90
|
+
typeId({
|
|
91
|
+
collections: {
|
|
92
|
+
articles: "article",
|
|
93
|
+
authors: "writer",
|
|
94
|
+
users: false,
|
|
95
|
+
},
|
|
96
|
+
});
|
|
62
97
|
```
|
|
63
98
|
|
|
64
|
-
|
|
99
|
+
Keys are collection slugs that must exist in `config.collections`. An unknown slug throws during setup. A central value applies only when the collection's `custom.typeId` is omitted.
|
|
100
|
+
|
|
101
|
+
### Examples
|
|
102
|
+
|
|
103
|
+
| Collection `custom.typeId` | Central entry | Result |
|
|
104
|
+
| -------------------------- | ------------- | -------------------------------- |
|
|
105
|
+
| `"art"` | `"article"` | `art_…` |
|
|
106
|
+
| omitted | `"article"` | `article_…` |
|
|
107
|
+
| `false` | `"article"` | Native ID (opt-out) |
|
|
108
|
+
| omitted | `false` | Native ID (opt-out) |
|
|
109
|
+
| omitted | omitted | Derived prefix, e.g. `article_…` |
|
|
110
|
+
|
|
111
|
+
A collection-level value always wins. `false` at either level opts the collection out.
|
|
112
|
+
|
|
113
|
+
### Globals
|
|
65
114
|
|
|
66
|
-
|
|
115
|
+
Globals keep Payload's ID strategy. They accept only `false` or omission. `true` or a prefix string on a Global throws during setup, because Payload does not expose configurable Global document IDs.
|
|
67
116
|
|
|
68
|
-
|
|
117
|
+
### Obsolete key
|
|
118
|
+
|
|
119
|
+
`custom.typeid` (lowercase `d`) throws on collections and Globals. Rename it to `custom.typeId`.
|
|
120
|
+
|
|
121
|
+
## Prefix derivation
|
|
122
|
+
|
|
123
|
+
When no explicit prefix applies, the prefix comes from the slug with Payload's own singularization, `formatLabels` from `payload`, the same function Payload uses for admin labels:
|
|
124
|
+
|
|
125
|
+
1. Replace `_` with `-` in the slug, so underscores and hyphens both separate words.
|
|
126
|
+
2. Pass the result through `formatLabels`, which singularizes the last word.
|
|
127
|
+
3. Join the words with `_` and lowercase the result.
|
|
128
|
+
|
|
129
|
+
Regular plural nouns derive cleanly:
|
|
130
|
+
|
|
131
|
+
| Slug | Derived prefix |
|
|
132
|
+
| ----------------- | ---------------- |
|
|
133
|
+
| `articles` | `article` |
|
|
134
|
+
| `article-authors` | `article_author` |
|
|
135
|
+
| `ArticleAuthors` | `article_author` |
|
|
136
|
+
| `audit-logs` | `audit_log` |
|
|
137
|
+
| `users` | `user` |
|
|
138
|
+
|
|
139
|
+
Irregular or uncountable names derive to correct English that may read oddly in an ID. Payload's English rules decide the result:
|
|
140
|
+
|
|
141
|
+
| Slug | Derived prefix | Recommendation |
|
|
142
|
+
| -------- | -------------- | ---------------------------------------------------------- |
|
|
143
|
+
| `people` | `person` | Acceptable. Set `"person"` if you prefer an explicit name. |
|
|
144
|
+
| `data` | `datum` | Set an explicit prefix such as `"dataset"`. |
|
|
145
|
+
| `dice` | `die` | Set an explicit prefix such as `"roll"`. |
|
|
146
|
+
|
|
147
|
+
Derivation depends on Payload's English rules. A future Payload release could change a derived prefix, and new IDs would follow the new rule. Set explicit prefixes for any collection whose IDs you store, log, or expose.
|
|
148
|
+
|
|
149
|
+
The plugin rejects a slug whose label contains characters other than letters, or whose multi-word label contains a single letter, because those cannot be split reliably. Because derivation is the default, such a slug fails setup for the whole project until you set a prefix or `false` on it:
|
|
150
|
+
|
|
151
|
+
| Slug | Result |
|
|
152
|
+
| ----------- | ----------------------------------------------- |
|
|
153
|
+
| `APIKeys` | Rejected. The label splits into single letters. |
|
|
154
|
+
| `users-2fa` | Rejected. The label contains a digit. |
|
|
155
|
+
|
|
156
|
+
## Prefix rules
|
|
157
|
+
|
|
158
|
+
Explicit prefixes must be 1–63 lowercase ASCII letters or underscores, starting and ending with a letter. Two managed collections that resolve to the same prefix throw during setup, so give one of them an explicit prefix.
|
|
159
|
+
|
|
160
|
+
A managed collection cannot define its own top-level field named `id`. Either set `custom.typeId: false` on it or rename that field before enabling TypeIDs.
|
|
161
|
+
|
|
162
|
+
## Using IDs
|
|
163
|
+
|
|
164
|
+
Create and read documents as usual. Do not pass `id` or `customID`:
|
|
69
165
|
|
|
70
166
|
```ts
|
|
71
167
|
const article = await payload.create({
|
|
@@ -73,42 +169,41 @@ const article = await payload.create({
|
|
|
73
169
|
data: { title: "Getting started with Payload CMS" },
|
|
74
170
|
});
|
|
75
171
|
|
|
76
|
-
|
|
77
|
-
collection: "articles",
|
|
78
|
-
id: article.id,
|
|
79
|
-
});
|
|
172
|
+
await payload.findByID({ collection: "articles", id: article.id });
|
|
80
173
|
```
|
|
81
174
|
|
|
82
|
-
|
|
175
|
+
Passing `customID` or `data.id` on create throws. Passing `data.id` on update throws, because the ID does not change.
|
|
176
|
+
|
|
177
|
+
Relationships use the native ID. Set `relationTo` as usual and pass the related document's `id`.
|
|
83
178
|
|
|
84
|
-
|
|
179
|
+
### Duplicating documents
|
|
180
|
+
|
|
181
|
+
`payload.duplicate()` gives the copy a **new** TypeID with the same prefix. The original keeps its ID. The repository's PostgreSQL integration test checks this on every supported Payload version.
|
|
85
182
|
|
|
86
183
|
```ts
|
|
87
|
-
{
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
relationTo: "categories",
|
|
91
|
-
}
|
|
184
|
+
const copy = await payload.duplicate({ collection: "articles", id: article.id });
|
|
185
|
+
copy.id !== article.id; // true
|
|
186
|
+
copy.id.startsWith("article_"); // true
|
|
92
187
|
```
|
|
93
188
|
|
|
94
|
-
|
|
189
|
+
### Errors
|
|
95
190
|
|
|
96
|
-
|
|
97
|
-
const category = await payload.create({
|
|
98
|
-
collection: "categories",
|
|
99
|
-
data: { title: "Development" },
|
|
100
|
-
});
|
|
191
|
+
Setup and write errors come from the plugin. Each message names the fix:
|
|
101
192
|
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
193
|
+
| Message (starts with) | Cause and fix |
|
|
194
|
+
| ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
|
|
195
|
+
| `... uses the obsolete custom.typeid key` | Rename `custom.typeid` to `custom.typeId`. |
|
|
196
|
+
| `Invalid TypeID configuration ... custom.typeId must be true, false, a prefix string` | The value has another type. Use one of the accepted values. |
|
|
197
|
+
| `Collection "x" cannot derive a TypeID prefix from its slug` | The slug is ambiguous. Set `custom.typeId` to an explicit string, or `false`. |
|
|
198
|
+
| `Collections "a" and "b" resolve to duplicate TypeID prefix` | Two collections share a prefix. Set an explicit prefix on one of them. |
|
|
199
|
+
| `Global "x" cannot use custom.typeId` | Globals accept only `false` or omission. |
|
|
200
|
+
| `TypeID collections references unknown collection` | A central key is not a collection slug in `config.collections`. |
|
|
201
|
+
| `Collection "x" already has a collection-level field named "id"` | Rename that field, or set `custom.typeId: false` on the collection. |
|
|
202
|
+
| `Collection "x" owns its IDs; omit customID and data.id when creating` | Remove `customID` and `data.id` from the create call. |
|
|
203
|
+
| `Collection "x" IDs are immutable; omit data.id when updating` | Remove `data.id` from the update call. |
|
|
204
|
+
| `Register typeId() only once` | Keep a single `typeId()` entry in `plugins`. |
|
|
110
205
|
|
|
111
|
-
|
|
206
|
+
## Utilities
|
|
112
207
|
|
|
113
208
|
```ts
|
|
114
209
|
import {
|
|
@@ -121,91 +216,60 @@ import {
|
|
|
121
216
|
} from "@klnap/payload-typeid";
|
|
122
217
|
|
|
123
218
|
const id: TypeID<"article"> = generateTypeId("article");
|
|
124
|
-
isTypeId(id); // true
|
|
125
219
|
isTypeId(id, "article"); // true
|
|
126
220
|
isTypeId(id, "category"); // false
|
|
127
221
|
|
|
128
222
|
const uuid = "0188bac7-4afa-78aa-bc3b-bd1eef28d881";
|
|
129
|
-
|
|
130
|
-
parseTypeId(converted).uuid === uuid; // true
|
|
131
|
-
toUUID(converted) === uuid; // true
|
|
223
|
+
toUUID(fromUUID("article", uuid)) === uuid; // true
|
|
132
224
|
```
|
|
133
225
|
|
|
134
|
-
| Export | Description
|
|
135
|
-
| ---------------------------------- |
|
|
136
|
-
| `typeId(options?)` | Creates the Payload plugin.
|
|
137
|
-
| `generateTypeId(prefix)` | Generates a UUIDv7
|
|
138
|
-
| `isTypeId(value, expectedPrefix?)` | Validates a TypeID and optionally its prefix.
|
|
139
|
-
| `parseTypeId(value)` | Returns the prefix and canonical UUID.
|
|
140
|
-
| `fromUUID(prefix, uuid)` | Encodes a canonical UUID as a TypeID.
|
|
141
|
-
| `toUUID(value)` | Converts a TypeID to its canonical UUID.
|
|
142
|
-
| `TypeID<Prefix>` | Compile-time
|
|
143
|
-
| `TypeIdOptions` | Options accepted by `typeId()`.
|
|
144
|
-
|
|
145
|
-
Codec utilities accept empty prefixes and UUIDs of any version. Invalid inputs make `parseTypeId`, `fromUUID`, and `toUUID` throw `TypeError`; `isTypeId` returns `false`. `TypeID<Prefix>` is a compile-time aid, not runtime validation. Payload-generated document types expose `id: string`.
|
|
146
|
-
|
|
147
|
-
## Configuration
|
|
148
|
-
|
|
149
|
-
Set a semantic prefix or exclude a collection in its own Payload config:
|
|
226
|
+
| Export | Description |
|
|
227
|
+
| ---------------------------------- | --------------------------------------------- |
|
|
228
|
+
| `typeId(options?)` | Creates the Payload plugin. |
|
|
229
|
+
| `generateTypeId(prefix)` | Generates a TypeID with a new UUIDv7. |
|
|
230
|
+
| `isTypeId(value, expectedPrefix?)` | Validates a TypeID and optionally its prefix. |
|
|
231
|
+
| `parseTypeId(value)` | Returns the prefix and canonical UUID. |
|
|
232
|
+
| `fromUUID(prefix, uuid)` | Encodes a canonical UUID as a TypeID. |
|
|
233
|
+
| `toUUID(value)` | Converts a TypeID to its canonical UUID. |
|
|
234
|
+
| `TypeID<Prefix>` | Compile-time type. Not runtime validation. |
|
|
235
|
+
| `TypeIdOptions` | Options accepted by `typeId()`. |
|
|
150
236
|
|
|
151
|
-
|
|
152
|
-
import type { CollectionConfig } from "payload";
|
|
237
|
+
`parseTypeId`, `fromUUID`, and `toUUID` throw `TypeError` on invalid input. `isTypeId` returns `false`.
|
|
153
238
|
|
|
154
|
-
|
|
155
|
-
slug: "articles",
|
|
156
|
-
custom: { typeid: "article" },
|
|
157
|
-
fields: [],
|
|
158
|
-
};
|
|
239
|
+
## Enabling on existing data
|
|
159
240
|
|
|
160
|
-
|
|
161
|
-
slug: "users",
|
|
162
|
-
custom: { typeid: false },
|
|
163
|
-
fields: [],
|
|
164
|
-
};
|
|
165
|
-
```
|
|
241
|
+
Registering `typeId()` on a project with data changes the ID column type of every managed collection and of every relationship that points to it. Existing IDs and relationship values are not migrated automatically.
|
|
166
242
|
|
|
167
|
-
|
|
243
|
+
Choose one before you deploy:
|
|
168
244
|
|
|
169
|
-
|
|
245
|
+
1. **Migrate.** Back up the database. Write a migration that assigns a TypeID to each existing document and rewrites relationship values to match. Deploy it together with the plugin.
|
|
246
|
+
2. **Opt out.** Set `custom.typeId: false` on each existing collection you do not want to change. Only new collections get TypeIDs.
|
|
170
247
|
|
|
171
|
-
|
|
172
|
-
typeId({
|
|
173
|
-
collections: {
|
|
174
|
-
articles: "article",
|
|
175
|
-
authors: "author",
|
|
176
|
-
users: false,
|
|
177
|
-
},
|
|
178
|
-
});
|
|
179
|
-
```
|
|
248
|
+
The database guards below run on writes that bypass Payload hooks. Existing data that does not match them blocks startup until it is migrated.
|
|
180
249
|
|
|
181
|
-
|
|
250
|
+
## Database guards (PostgreSQL)
|
|
182
251
|
|
|
183
|
-
|
|
252
|
+
Payload hooks do not run for raw SQL, so the plugin installs the ID rules in the database as well. For each managed table, on every Payload start:
|
|
184
253
|
|
|
185
|
-
|
|
254
|
+
- **Generation:** an `INSERT` without `id` receives a TypeID with the table's prefix. The SQL encoder matches `generateTypeId`, and the test suite checks that the two agree.
|
|
255
|
+
- **Validation:** a `CHECK` constraint rejects any `id` that is not `prefix_` followed by 26 Base32 characters, with the first character in `0`–`7`. A wrong prefix is rejected too.
|
|
256
|
+
- **Immutability:** a trigger rejects any `UPDATE` that changes `id`. Other columns can still be updated.
|
|
186
257
|
|
|
187
|
-
|
|
258
|
+
The guards are idempotent and survive a repeated `push`; the test suite runs twice against the same database to check this. Limits:
|
|
188
259
|
|
|
189
|
-
|
|
260
|
+
- **PostgreSQL only.** Other adapters log a warning at startup and keep only application-level rules.
|
|
261
|
+
- **Existing data.** The `CHECK` applies to all rows. If a managed table already holds IDs that do not match, startup fails and no guard is installed. Migrate those rows first (see [Enabling on existing data](#enabling-on-existing-data)).
|
|
262
|
+
- **Scope.** Versions tables (`_<table>_v`) and relationship join tables are not guarded; their IDs belong to Payload.
|
|
263
|
+
- **Fields.** The guards check only `id`. Other constraints and field rules are not changed.
|
|
190
264
|
|
|
191
265
|
## Compatibility
|
|
192
266
|
|
|
193
|
-
| Area
|
|
194
|
-
|
|
|
195
|
-
| Payload CMS
|
|
196
|
-
| Database
|
|
197
|
-
| Node.js
|
|
198
|
-
| Module format
|
|
199
|
-
|
|
200
|
-
Use the latest stable Payload 3.x for security fixes. The peer range describes compatibility, not a recommendation to run older releases.
|
|
201
|
-
|
|
202
|
-
## Documentation
|
|
203
|
-
|
|
204
|
-
- [Payload plugins](https://payloadcms.com/docs/plugins/overview)
|
|
205
|
-
- [Payload custom ID fields](https://payloadcms.com/docs/fields/default-fields#custom-id-fields)
|
|
206
|
-
- [Payload Globals](https://payloadcms.com/docs/configuration/globals)
|
|
207
|
-
- [TypeID specification](https://github.com/jetify-com/typeid/blob/main/spec/README.md)
|
|
208
|
-
- [UUIDv7 in RFC 9562](https://www.rfc-editor.org/rfc/rfc9562.html#section-5.7)
|
|
267
|
+
| Area | Support |
|
|
268
|
+
| ------------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
|
269
|
+
| Payload CMS | Peer range `^3.1.1`. PostgreSQL integration tests pass on `3.1.1`, `3.68.4`, `3.71.0`, and `3.94.2`. Payload 4 is unverified. |
|
|
270
|
+
| Database | PostgreSQL 16, with the default serial strategy and `idType: "uuid"`. Other adapters are unverified. |
|
|
271
|
+
| Node.js | `>=22.14.0`. Payload's own engine range applies too; Payload `3.94.2` requires `^22.23.5 \|\| ^24.22.3 \|\| >=26.13.1`. |
|
|
272
|
+
| Module format | ESM only. |
|
|
209
273
|
|
|
210
274
|
## License
|
|
211
275
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type Plugin } from "payload";
|
|
2
2
|
export type TypeID<Prefix extends string = string> = string extends Prefix ? string : Prefix extends "" ? string : `${Prefix}_${string}`;
|
|
3
3
|
export interface TypeIdOptions {
|
|
4
|
-
collections?: Record<string,
|
|
4
|
+
collections?: Record<string, boolean | string>;
|
|
5
5
|
}
|
|
6
6
|
interface ParsedTypeID<Prefix extends string = string> {
|
|
7
7
|
prefix: Prefix;
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,106 @@
|
|
|
1
1
|
import { Buffer } from "node:buffer";
|
|
2
2
|
import { randomBytes } from "node:crypto";
|
|
3
|
-
import { flattenAllFields, } from "payload";
|
|
3
|
+
import { flattenAllFields, formatLabels, } from "payload";
|
|
4
|
+
const identifierPattern = /^[a-z_][a-z0-9_]*$/;
|
|
5
|
+
const prefixSafePattern = /^[a-z]([a-z_]{0,61}[a-z])?$/;
|
|
6
|
+
// Mirrors encodeUuid/decodeSuffix: a 128-bit value as 26 Base32 characters, most significant first.
|
|
7
|
+
const encodeFunction = `
|
|
8
|
+
CREATE OR REPLACE FUNCTION payload_typeid_encode(hex text) RETURNS text
|
|
9
|
+
LANGUAGE plpgsql IMMUTABLE AS $$
|
|
10
|
+
DECLARE
|
|
11
|
+
value numeric := 0;
|
|
12
|
+
remainder integer;
|
|
13
|
+
result text := '';
|
|
14
|
+
alphabet text := '0123456789abcdefghjkmnpqrstvwxyz';
|
|
15
|
+
BEGIN
|
|
16
|
+
FOR i IN 1..32 LOOP
|
|
17
|
+
value := value * 16 + ('x' || substr(hex, i, 1))::bit(4)::int;
|
|
18
|
+
END LOOP;
|
|
19
|
+
FOR i IN 1..26 LOOP
|
|
20
|
+
remainder := (value % 32)::integer;
|
|
21
|
+
result := substr(alphabet, remainder + 1, 1) || result;
|
|
22
|
+
value := (value - remainder) / 32;
|
|
23
|
+
END LOOP;
|
|
24
|
+
RETURN result;
|
|
25
|
+
END $$;`;
|
|
26
|
+
// UUIDv7 as described by RFC 9562: 48-bit milliseconds, version 7, RFC variant, random bits.
|
|
27
|
+
const uuidV7Function = `
|
|
28
|
+
CREATE OR REPLACE FUNCTION payload_typeid_uuid_v7_hex() RETURNS text
|
|
29
|
+
LANGUAGE plpgsql VOLATILE AS $$
|
|
30
|
+
DECLARE
|
|
31
|
+
millis bigint := floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint;
|
|
32
|
+
random_hex text := replace(gen_random_uuid()::text, '-', '');
|
|
33
|
+
BEGIN
|
|
34
|
+
RETURN lpad(to_hex(millis), 12, '0')
|
|
35
|
+
|| '7' || substr(random_hex, 14, 3)
|
|
36
|
+
|| to_hex((('x' || substr(random_hex, 17, 1))::bit(4)::int & 3) | 8)
|
|
37
|
+
|| substr(random_hex, 18, 15);
|
|
38
|
+
END $$;`;
|
|
39
|
+
// Generates an ID when none is supplied, and rejects any change to an existing ID.
|
|
40
|
+
const guardFunction = `
|
|
41
|
+
CREATE OR REPLACE FUNCTION payload_typeid_guard() RETURNS trigger
|
|
42
|
+
LANGUAGE plpgsql AS $$
|
|
43
|
+
BEGIN
|
|
44
|
+
IF TG_OP = 'UPDATE' THEN
|
|
45
|
+
IF NEW.id IS DISTINCT FROM OLD.id THEN
|
|
46
|
+
RAISE EXCEPTION 'TypeID document IDs are immutable (table %)', TG_TABLE_NAME
|
|
47
|
+
USING ERRCODE = 'check_violation';
|
|
48
|
+
END IF;
|
|
49
|
+
RETURN NEW;
|
|
50
|
+
END IF;
|
|
51
|
+
IF NEW.id IS NULL THEN
|
|
52
|
+
NEW.id := TG_ARGV[0] || '_' || payload_typeid_encode(payload_typeid_uuid_v7_hex());
|
|
53
|
+
END IF;
|
|
54
|
+
RETURN NEW;
|
|
55
|
+
END $$;`;
|
|
56
|
+
// Payload's Postgres table name for a collection slug: camelCase and hyphens become underscores.
|
|
57
|
+
function tableNameForSlug(slug) {
|
|
58
|
+
return slug
|
|
59
|
+
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
|
|
60
|
+
.replace(/([a-z\d])([A-Z])/g, "$1_$2")
|
|
61
|
+
.replace(/[-\s]+/g, "_")
|
|
62
|
+
.toLowerCase();
|
|
63
|
+
}
|
|
64
|
+
/** SQL that installs the ID functions, a per-table CHECK constraint, and a per-table trigger. */
|
|
65
|
+
function typeIdDatabaseSql(guards) {
|
|
66
|
+
const statements = [encodeFunction, uuidV7Function, guardFunction];
|
|
67
|
+
for (const { table, prefix } of guards) {
|
|
68
|
+
if (!identifierPattern.test(table) || !prefixSafePattern.test(prefix)) {
|
|
69
|
+
throw new TypeError(`Refusing to guard unsafe table or prefix "${table}" / "${prefix}".`);
|
|
70
|
+
}
|
|
71
|
+
const constraint = `payload_typeid_${table}_id_check`;
|
|
72
|
+
const trigger = `payload_typeid_${table}_guard`;
|
|
73
|
+
statements.push(`ALTER TABLE "${table}" DROP CONSTRAINT IF EXISTS "${constraint}";`, `ALTER TABLE "${table}" ADD CONSTRAINT "${constraint}" CHECK (id ~ '^${prefix}_[0-7][0-9a-hjkmnp-tv-z]{25}$');`, `DROP TRIGGER IF EXISTS "${trigger}" ON "${table}";`, `CREATE TRIGGER "${trigger}" BEFORE INSERT OR UPDATE ON "${table}" FOR EACH ROW EXECUTE FUNCTION payload_typeid_guard('${prefix}');`);
|
|
74
|
+
}
|
|
75
|
+
return statements.join("\n");
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Installs the database guards on the Postgres adapter. Other adapters get a warning instead:
|
|
79
|
+
* the guards are SQL and cannot be applied to them.
|
|
80
|
+
*/
|
|
81
|
+
async function installTypeIdDatabaseGuards(payload, guards) {
|
|
82
|
+
if (guards.length === 0)
|
|
83
|
+
return;
|
|
84
|
+
if (payload.db.name !== "postgres") {
|
|
85
|
+
payload.logger.warn(`payload-typeid: database guards are only installed on PostgreSQL; the "${payload.db.name}" adapter keeps application-level rules only.`);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const pool = payload.db.pool;
|
|
89
|
+
const tables = guards.map(({ slug, prefix }) => {
|
|
90
|
+
const defaultName = tableNameForSlug(slug);
|
|
91
|
+
const tableNameMap = payload.db
|
|
92
|
+
.tableNameMap;
|
|
93
|
+
const table = tableNameMap?.get(defaultName) ?? defaultName;
|
|
94
|
+
return { slug, prefix, table };
|
|
95
|
+
});
|
|
96
|
+
for (const { slug, table } of tables) {
|
|
97
|
+
const { rows } = await pool.query("SELECT to_regclass($1) AS relation", [`"${table}"`]);
|
|
98
|
+
if (!rows[0]?.relation) {
|
|
99
|
+
throw new TypeError(`payload-typeid: no table "${table}" for collection "${slug}". Set the collection's dbName or rename it before enabling TypeIDs.`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
await pool.query(typeIdDatabaseSql(tables.map(({ table, prefix }) => ({ table, prefix }))));
|
|
103
|
+
}
|
|
4
104
|
const prefixPattern = /^([a-z]([a-z_]{0,61}[a-z])?)?$/;
|
|
5
105
|
const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
6
106
|
const typeIdAlphabet = "0123456789abcdefghjkmnpqrstvwxyz";
|
|
@@ -91,12 +191,18 @@ export function generateTypeId(prefix) {
|
|
|
91
191
|
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
92
192
|
return fromUUID(prefix, uuidFromBytes(bytes));
|
|
93
193
|
}
|
|
94
|
-
function
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
194
|
+
function deriveCollectionPrefix(slug) {
|
|
195
|
+
// Hyphens and underscores are word separators; Payload's formatLabels splits only on hyphens and whitespace.
|
|
196
|
+
const singular = formatLabels(slug.replaceAll("_", "-")).singular;
|
|
197
|
+
const words = singular.split(" ");
|
|
198
|
+
// Acronyms such as "APIKeys" split into single letters, so they cannot be derived reliably.
|
|
199
|
+
const derivable = singular !== "" &&
|
|
200
|
+
words.every((word) => /^[A-Za-z]+$/.test(word)) &&
|
|
201
|
+
!(words.length > 1 && words.some((word) => word.length === 1));
|
|
202
|
+
if (!derivable) {
|
|
203
|
+
throw new TypeError(`Collection "${slug}" cannot derive a TypeID prefix from its slug. Set custom.typeId or collections["${slug}"] to an explicit prefix string.`);
|
|
204
|
+
}
|
|
205
|
+
return words.join("_").toLowerCase();
|
|
100
206
|
}
|
|
101
207
|
function hasCustomID(fields) {
|
|
102
208
|
return flattenAllFields({ fields }).some((field) => "name" in field && field.name === "id");
|
|
@@ -153,6 +259,28 @@ function withIDOwnership(collection, prefix) {
|
|
|
153
259
|
},
|
|
154
260
|
};
|
|
155
261
|
}
|
|
262
|
+
function readSetting(value, owner) {
|
|
263
|
+
if (value === undefined || typeof value === "boolean" || typeof value === "string") {
|
|
264
|
+
return value;
|
|
265
|
+
}
|
|
266
|
+
throw new TypeError(`Invalid TypeID configuration for ${owner}: custom.typeId must be true, false, a prefix string, or undefined.`);
|
|
267
|
+
}
|
|
268
|
+
function assertCurrentKey(custom, owner) {
|
|
269
|
+
if (custom && Object.hasOwn(custom, "typeid")) {
|
|
270
|
+
throw new TypeError(`${owner} uses the obsolete custom.typeid key; rename it to custom.typeId.`);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
function validateCollectionPrefix(slug, prefix) {
|
|
274
|
+
if (prefix === "") {
|
|
275
|
+
throw new TypeError(`Collection "${slug}" resolved to an empty TypeID prefix; provide a non-empty prefix string.`);
|
|
276
|
+
}
|
|
277
|
+
try {
|
|
278
|
+
validatePrefix(prefix);
|
|
279
|
+
}
|
|
280
|
+
catch (error) {
|
|
281
|
+
throw new TypeError(`Invalid TypeID prefix for collection "${slug}": ${error instanceof Error ? error.message : String(error)} Provide a valid prefix string.`, { cause: error });
|
|
282
|
+
}
|
|
283
|
+
}
|
|
156
284
|
export function typeId(options = {}) {
|
|
157
285
|
const plugin = (config) => {
|
|
158
286
|
if (typeof options !== "object" || options === null || Array.isArray(options)) {
|
|
@@ -167,63 +295,67 @@ export function typeId(options = {}) {
|
|
|
167
295
|
const overrides = options.collections;
|
|
168
296
|
if (overrides !== undefined &&
|
|
169
297
|
(typeof overrides !== "object" || overrides === null || Array.isArray(overrides))) {
|
|
170
|
-
throw new TypeError("TypeID collections must be a record of collection slugs to
|
|
298
|
+
throw new TypeError("TypeID collections must be a record of collection slugs to true, false, or prefix strings.");
|
|
171
299
|
}
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
const prefixes = new Map();
|
|
176
|
-
for (const global of config.globals ?? []) {
|
|
177
|
-
const typeIdOption = global.custom?.typeid;
|
|
178
|
-
if (typeIdOption !== undefined && typeIdOption !== false) {
|
|
179
|
-
throw new TypeError(`Global "${global.slug}" cannot use a TypeID prefix because Payload Globals do not expose configurable document IDs.`);
|
|
300
|
+
for (const [slug, setting] of Object.entries(overrides ?? {})) {
|
|
301
|
+
if (typeof setting !== "boolean" && typeof setting !== "string") {
|
|
302
|
+
throw new TypeError(`TypeID collections["${slug}"] must be true, false, or a prefix string.`);
|
|
180
303
|
}
|
|
181
304
|
}
|
|
182
|
-
|
|
305
|
+
const collections = config.collections ?? [];
|
|
306
|
+
const collectionSlugs = new Set(collections.map(({ slug }) => slug));
|
|
307
|
+
for (const slug of Object.keys(overrides ?? {})) {
|
|
183
308
|
if (!collectionSlugs.has(slug)) {
|
|
184
|
-
throw new TypeError(`TypeID
|
|
309
|
+
throw new TypeError(`TypeID collections references unknown collection "${slug}".`);
|
|
185
310
|
}
|
|
186
|
-
|
|
187
|
-
|
|
311
|
+
}
|
|
312
|
+
for (const global of config.globals ?? []) {
|
|
313
|
+
assertCurrentKey(global.custom, `Global "${global.slug}"`);
|
|
314
|
+
const setting = readSetting(global.custom?.typeId, `Global "${global.slug}"`);
|
|
315
|
+
if (setting !== undefined && setting !== false) {
|
|
316
|
+
throw new TypeError(`Global "${global.slug}" cannot use custom.typeId ${JSON.stringify(setting)} because Payload Globals do not expose configurable document IDs. Use false or omit custom.typeId.`);
|
|
188
317
|
}
|
|
189
318
|
}
|
|
319
|
+
// Resolve opt-out first so shadowed central settings never reach prefix validation.
|
|
320
|
+
// Precedence: model custom.typeId > central collections entry > default (derived prefix).
|
|
321
|
+
const managed = [];
|
|
190
322
|
for (const collection of collections) {
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
}
|
|
195
|
-
const centralTypeId = overrides && Object.hasOwn(overrides, collection.slug)
|
|
323
|
+
assertCurrentKey(collection.custom, `Collection "${collection.slug}"`);
|
|
324
|
+
const modelSetting = readSetting(collection.custom?.typeId, `collection "${collection.slug}"`);
|
|
325
|
+
const centralSetting = overrides && Object.hasOwn(overrides, collection.slug)
|
|
196
326
|
? overrides[collection.slug]
|
|
197
327
|
: undefined;
|
|
198
|
-
const
|
|
199
|
-
if (
|
|
328
|
+
const setting = modelSetting ?? centralSetting ?? true;
|
|
329
|
+
if (setting === false)
|
|
200
330
|
continue;
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
throw new TypeError(`Collection "${collection.slug}" resolved to an empty TypeID prefix; provide an override.`);
|
|
210
|
-
}
|
|
331
|
+
managed.push({ collection, setting });
|
|
332
|
+
}
|
|
333
|
+
const prefixes = new Map();
|
|
334
|
+
const replacements = new Map();
|
|
335
|
+
const guards = [];
|
|
336
|
+
for (const { collection, setting } of managed) {
|
|
337
|
+
const prefix = setting === true ? deriveCollectionPrefix(collection.slug) : setting;
|
|
338
|
+
validateCollectionPrefix(collection.slug, prefix);
|
|
211
339
|
const existing = prefixes.get(prefix);
|
|
212
340
|
if (existing) {
|
|
213
|
-
throw new TypeError(`Collections "${existing}" and "${collection.slug}" resolve to duplicate TypeID prefix "${prefix}".
|
|
341
|
+
throw new TypeError(`Collections "${existing}" and "${collection.slug}" resolve to duplicate TypeID prefix "${prefix}". Set an explicit prefix on one of them with custom.typeId or collections.`);
|
|
214
342
|
}
|
|
215
343
|
prefixes.set(prefix, collection.slug);
|
|
216
|
-
resolved.set(collection.slug, prefix);
|
|
217
344
|
if (hasCustomID(collection.fields)) {
|
|
218
|
-
throw new TypeError(`Collection "${collection.slug}" already has a collection-level field named "id". Set
|
|
345
|
+
throw new TypeError(`Collection "${collection.slug}" already has a collection-level field named "id". Set custom.typeId = false or rename that field before enabling TypeID.`);
|
|
219
346
|
}
|
|
347
|
+
replacements.set(collection.slug, withIDOwnership(collection, prefix));
|
|
348
|
+
guards.push({ slug: collection.slug, prefix });
|
|
220
349
|
}
|
|
350
|
+
const onInit = config.onInit;
|
|
221
351
|
return {
|
|
222
352
|
...config,
|
|
223
|
-
collections: collections.map((collection) =>
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
353
|
+
collections: collections.map((collection) => replacements.get(collection.slug) ?? collection),
|
|
354
|
+
// Database guards run after Payload has created its tables, so the CHECK and triggers apply to them.
|
|
355
|
+
onInit: async (payload) => {
|
|
356
|
+
await onInit?.(payload);
|
|
357
|
+
await installTypeIdDatabaseGuards(payload, guards);
|
|
358
|
+
},
|
|
227
359
|
};
|
|
228
360
|
};
|
|
229
361
|
plugin.slug = "payload-typeid";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAIL,gBAAgB,GAEjB,MAAM,SAAS,CAAC;AAiBjB,MAAM,aAAa,GAAG,gCAAgC,CAAC;AACvD,MAAM,WAAW,GAAG,iEAAiE,CAAC;AACtF,MAAM,cAAc,GAAG,kCAAkC,CAAC;AAC1D,MAAM,OAAO,GAAG,CAAC,EAAE,IAAI,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C3F,CAAC;YACJ,CAAC;YACD,MAAM,QAAQ,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;YACtC,IAAI,QAAQ,EAAE,CAAC;gBACb,MAAM,IAAI,SAAS,CACjB,gBAAgB,QAAQ,UAAU,UAAU,CAAC,IAAI,yCAAyC,MAAM,0DAA0D,CAC3J,CAAC;YACJ,CAAC;YACD,QAAQ,CAAC,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC;YACtC,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;YACtC,IAAI,WAAW,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC;gBACnC,MAAM,IAAI,SAAS,CACjB,eAAe,UAAU,CAAC,IAAI,uEAAuE,UAAU,CAAC,IAAI,yDAAyD,CAC9K,CAAC;YACJ,CAAC;QACH,CAAC;QAED,OAAO;YACL,GAAG,MAAM;YACT,WAAW,EAAE,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE;gBAC1C,MAAM,MAAM,GAAG,QAAQ,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;gBAC7C,OAAO,MAAM,CAAC,CAAC,CAAC,eAAe,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC;YACnE,CAAC,CAAC;SACH,CAAC;IACJ,CAAC,CAAC;IAEF,MAAM,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,gBAAgB,CAAC;IACvC,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Buffer } from \"node:buffer\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n type CollectionConfig,\n type Config,\n type Field,\n flattenAllFields,\n type Plugin,\n} from \"payload\";\n\nexport type TypeID<Prefix extends string = string> = string extends Prefix\n ? string\n : Prefix extends \"\"\n ? string\n : `${Prefix}_${string}`;\n\nexport interface TypeIdOptions {\n collections?: Record<string, string | false>;\n}\n\ninterface ParsedTypeID<Prefix extends string = string> {\n prefix: Prefix;\n uuid: string;\n}\n\nconst prefixPattern = /^([a-z]([a-z_]{0,61}[a-z])?)?$/;\nconst uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst typeIdAlphabet = \"0123456789abcdefghjkmnpqrstvwxyz\";\nconst maxUuid = (1n << 128n) - 1n;\n\nfunction validatePrefix(prefix: string): void {\n if (!prefixPattern.test(prefix)) {\n throw new TypeError(\n `Invalid TypeID prefix \"${prefix}\". Prefixes must be empty or 1–63 lowercase ASCII letters and underscores, starting and ending with a letter.`,\n );\n }\n}\n\nfunction uuidFromBytes(bytes: Uint8Array): string {\n const hex = Buffer.from(bytes).toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nfunction encodeUuid(uuid: string): string {\n let value = BigInt(`0x${uuid.replaceAll(\"-\", \"\")}`);\n let suffix = \"\";\n for (let index = 0; index < 26; index += 1) {\n suffix = typeIdAlphabet[Number(value & 31n)] + suffix;\n value >>= 5n;\n }\n return suffix;\n}\n\nfunction decodeSuffix(suffix: string): string {\n let value = 0n;\n for (const character of suffix) {\n const digit = typeIdAlphabet.indexOf(character);\n if (digit === -1)\n throw new TypeError(\"Suffix contains a character outside the TypeID alphabet.\");\n value = (value << 5n) | BigInt(digit);\n }\n if (value > maxUuid) throw new TypeError(\"Suffix exceeds the 128-bit UUID range.\");\n return value.toString(16).padStart(32, \"0\");\n}\n\nexport function fromUUID<const Prefix extends string>(\n prefix: Prefix,\n uuid: string,\n): TypeID<Prefix> {\n validatePrefix(prefix);\n if (!uuidPattern.test(uuid)) {\n throw new TypeError(`Invalid UUID \"${uuid}\". Expected a canonical 36-character UUID.`);\n }\n return `${prefix ? `${prefix}_` : \"\"}${encodeUuid(uuid)}` as TypeID<Prefix>;\n}\n\nexport function parseTypeId<const Prefix extends string = string>(\n value: string,\n): ParsedTypeID<Prefix> {\n if (typeof value !== \"string\") throw new TypeError(\"TypeID must be a string.\");\n const separator = value.lastIndexOf(\"_\");\n const prefix = separator === -1 ? \"\" : value.slice(0, separator);\n const suffix = separator === -1 ? value : value.slice(separator + 1);\n try {\n validatePrefix(prefix);\n if (separator !== -1 && prefix === \"\") {\n throw new TypeError(\"An empty prefix must not include a separator.\");\n }\n if (suffix.length !== 26) throw new TypeError(\"Suffix must contain exactly 26 characters.\");\n const hex = decodeSuffix(suffix);\n return {\n prefix: prefix as Prefix,\n uuid: `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`,\n };\n } catch (error) {\n throw new TypeError(\n `Invalid TypeID \"${value}\": ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n}\n\nexport function toUUID(value: string): string {\n return parseTypeId(value).uuid;\n}\n\nexport function isTypeId<Prefix extends string = string>(\n value: unknown,\n expectedPrefix?: Prefix,\n): value is TypeID<Prefix> {\n if (typeof value !== \"string\") return false;\n try {\n const parsed = parseTypeId(value);\n return expectedPrefix === undefined || parsed.prefix === expectedPrefix;\n } catch {\n return false;\n }\n}\n\nexport function generateTypeId<const Prefix extends string>(prefix: Prefix): TypeID<Prefix> {\n validatePrefix(prefix);\n const bytes = randomBytes(16);\n let timestamp = BigInt(Date.now());\n for (let index = 5; index >= 0; index -= 1) {\n bytes[index] = Number(timestamp & 0xffn);\n timestamp >>= 8n;\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x70;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n return fromUUID(prefix, uuidFromBytes(bytes));\n}\n\nfunction normalizePrefix(slug: string): string {\n return slug\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replaceAll(\"-\", \"_\")\n .toLowerCase();\n}\n\nfunction hasCustomID(fields: Field[]): boolean {\n return flattenAllFields({ fields }).some((field) => \"name\" in field && field.name === \"id\");\n}\n\nfunction createIDField(prefix: string): Field {\n return {\n name: \"id\",\n type: \"text\",\n required: true,\n admin: { hidden: true, readOnly: true },\n access: {\n create: () => true,\n update: () => false,\n },\n defaultValue: () => generateTypeId(prefix),\n hooks: {\n beforeChange: [\n ({ operation, originalDoc, value }) => {\n if (operation === \"create\") return value || generateTypeId(prefix);\n return originalDoc?.id ?? value;\n },\n ],\n beforeDuplicate: [() => generateTypeId(prefix)],\n },\n };\n}\n\nfunction withIDOwnership(collection: CollectionConfig, prefix: string): CollectionConfig {\n const beforeOperation = collection.hooks?.beforeOperation ?? [];\n return {\n ...collection,\n // Payload stops custom ID discovery when it reaches structural fields.\n fields: [createIDField(prefix), ...collection.fields],\n hooks: {\n ...collection.hooks,\n beforeOperation: [\n ...beforeOperation,\n ({ operation, args }) => {\n if (operation === \"create\") {\n const createArgs = args as { customID?: unknown; data?: Record<string, unknown> };\n if (createArgs.customID !== undefined || createArgs.data?.id !== undefined) {\n throw new TypeError(\n `Collection \"${collection.slug}\" owns its IDs; omit customID and data.id when creating documents.`,\n );\n }\n }\n if (operation === \"update\") {\n const updateArgs = args as { data?: Record<string, unknown> };\n if (updateArgs.data?.id !== undefined) {\n throw new TypeError(\n `Collection \"${collection.slug}\" IDs are immutable; omit data.id when updating documents.`,\n );\n }\n }\n return args;\n },\n ],\n },\n };\n}\n\nexport function typeId(options: TypeIdOptions = {}): Plugin {\n const plugin: Plugin = (config: Config) => {\n if (typeof options !== \"object\" || options === null || Array.isArray(options)) {\n throw new TypeError(\"TypeID options must be an object.\");\n }\n if (Object.keys(options).some((key) => key !== \"collections\")) {\n throw new TypeError('TypeID options only support \"collections\".');\n }\n if ((config.plugins?.filter(({ slug }) => slug === \"payload-typeid\").length ?? 0) > 1) {\n throw new TypeError(\"Register typeId() only once in the Payload plugins array.\");\n }\n\n const overrides = options.collections;\n if (\n overrides !== undefined &&\n (typeof overrides !== \"object\" || overrides === null || Array.isArray(overrides))\n ) {\n throw new TypeError(\n \"TypeID collections must be a record of collection slugs to prefixes or false.\",\n );\n }\n\n const collections = config.collections ?? [];\n const collectionSlugs = new Set(collections.map(({ slug }) => slug));\n const resolved = new Map<string, string>();\n const prefixes = new Map<string, string>();\n for (const global of config.globals ?? []) {\n const typeIdOption = global.custom?.typeid;\n if (typeIdOption !== undefined && typeIdOption !== false) {\n throw new TypeError(\n `Global \"${global.slug}\" cannot use a TypeID prefix because Payload Globals do not expose configurable document IDs.`,\n );\n }\n }\n for (const [slug, prefix] of Object.entries(overrides ?? {})) {\n if (!collectionSlugs.has(slug)) {\n throw new TypeError(`TypeID override references unknown collection \"${slug}\".`);\n }\n if (prefix !== false && typeof prefix !== \"string\") {\n throw new TypeError(`TypeID override for \"${slug}\" must be a prefix string or false.`);\n }\n }\n\n for (const collection of collections) {\n const modelTypeId = collection.custom?.typeid;\n if (modelTypeId !== undefined && modelTypeId !== false && typeof modelTypeId !== \"string\") {\n throw new TypeError(\n `Invalid TypeID configuration for collection \"${collection.slug}\": custom.typeid must be a prefix string, false, or undefined.`,\n );\n }\n const centralTypeId =\n overrides && Object.hasOwn(overrides, collection.slug)\n ? overrides[collection.slug]\n : undefined;\n const effectiveTypeId = modelTypeId !== undefined ? modelTypeId : centralTypeId;\n if (effectiveTypeId === false) continue;\n const prefix =\n typeof effectiveTypeId === \"string\" ? effectiveTypeId : normalizePrefix(collection.slug);\n try {\n validatePrefix(prefix);\n } catch (error) {\n throw new TypeError(\n `Invalid TypeID prefix for collection \"${collection.slug}\": ${error instanceof Error ? error.message : String(error)} Provide a valid collections[\"${collection.slug}\"] override or disable this collection.`,\n { cause: error },\n );\n }\n if (!prefix) {\n throw new TypeError(\n `Collection \"${collection.slug}\" resolved to an empty TypeID prefix; provide an override.`,\n );\n }\n const existing = prefixes.get(prefix);\n if (existing) {\n throw new TypeError(\n `Collections \"${existing}\" and \"${collection.slug}\" resolve to duplicate TypeID prefix \"${prefix}\". Provide distinct overrides or disable one collection.`,\n );\n }\n prefixes.set(prefix, collection.slug);\n resolved.set(collection.slug, prefix);\n if (hasCustomID(collection.fields)) {\n throw new TypeError(\n `Collection \"${collection.slug}\" already has a collection-level field named \"id\". Set collections[\"${collection.slug}\"] = false or rename that field before enabling TypeID.`,\n );\n }\n }\n\n return {\n ...config,\n collections: collections.map((collection) => {\n const prefix = resolved.get(collection.slug);\n return prefix ? withIDOwnership(collection, prefix) : collection;\n }),\n };\n };\n\n plugin.slug = \"payload-typeid\";\n plugin.order = Number.MAX_SAFE_INTEGER;\n return plugin;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAIL,gBAAgB,EAEhB,YAAY,GAEb,MAAM,SAAS,CAAC;AAOjB,MAAM,iBAAiB,GAAG,oBAAoB,CAAC;AAC/C,MAAM,iBAAiB,GAAG,6BAA6B,CAAC;AAExD,oGAAoG;AACpG,MAAM,cAAc,GAAG;;;;;;;;;;;;;;;;;;QAkBf,CAAC;AAET,6FAA6F;AAC7F,MAAM,cAAc,GAAG;;;;;;;;;;;QAWf,CAAC;AAET,mFAAmF;AACnF,MAAM,aAAa,GAAG;;;;;;;;;;;;;;;QAed,CAAC;AAET,iGAAiG;AACjG,SAAS,gBAAgB,CAAC,IAAY;IACpC,OAAO,IAAI;SACR,OAAO,CAAC,uBAAuB,EAAE,OAAO,CAAC;SACzC,OAAO,CAAC,mBAAmB,EAAE,OAAO,CAAC;SACrC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC;SACvB,WAAW,EAAE,CAAC;AACnB,CAAC;AAED,iGAAiG;AACjG,SAAS,iBAAiB,CAAC,MAAwD;IAC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AC;IAC/B,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,gBAAgB,CAAC;IACvC,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Buffer } from \"node:buffer\";\nimport { randomBytes } from \"node:crypto\";\nimport {\n type CollectionConfig,\n type Config,\n type Field,\n flattenAllFields,\n type Payload,\n formatLabels,\n type Plugin,\n} from \"payload\";\n\ninterface TypeIdTableGuard {\n slug: string;\n prefix: string;\n}\n\nconst identifierPattern = /^[a-z_][a-z0-9_]*$/;\nconst prefixSafePattern = /^[a-z]([a-z_]{0,61}[a-z])?$/;\n\n// Mirrors encodeUuid/decodeSuffix: a 128-bit value as 26 Base32 characters, most significant first.\nconst encodeFunction = `\nCREATE OR REPLACE FUNCTION payload_typeid_encode(hex text) RETURNS text\nLANGUAGE plpgsql IMMUTABLE AS $$\nDECLARE\n value numeric := 0;\n remainder integer;\n result text := '';\n alphabet text := '0123456789abcdefghjkmnpqrstvwxyz';\nBEGIN\n FOR i IN 1..32 LOOP\n value := value * 16 + ('x' || substr(hex, i, 1))::bit(4)::int;\n END LOOP;\n FOR i IN 1..26 LOOP\n remainder := (value % 32)::integer;\n result := substr(alphabet, remainder + 1, 1) || result;\n value := (value - remainder) / 32;\n END LOOP;\n RETURN result;\nEND $$;`;\n\n// UUIDv7 as described by RFC 9562: 48-bit milliseconds, version 7, RFC variant, random bits.\nconst uuidV7Function = `\nCREATE OR REPLACE FUNCTION payload_typeid_uuid_v7_hex() RETURNS text\nLANGUAGE plpgsql VOLATILE AS $$\nDECLARE\n millis bigint := floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint;\n random_hex text := replace(gen_random_uuid()::text, '-', '');\nBEGIN\n RETURN lpad(to_hex(millis), 12, '0')\n || '7' || substr(random_hex, 14, 3)\n || to_hex((('x' || substr(random_hex, 17, 1))::bit(4)::int & 3) | 8)\n || substr(random_hex, 18, 15);\nEND $$;`;\n\n// Generates an ID when none is supplied, and rejects any change to an existing ID.\nconst guardFunction = `\nCREATE OR REPLACE FUNCTION payload_typeid_guard() RETURNS trigger\nLANGUAGE plpgsql AS $$\nBEGIN\n IF TG_OP = 'UPDATE' THEN\n IF NEW.id IS DISTINCT FROM OLD.id THEN\n RAISE EXCEPTION 'TypeID document IDs are immutable (table %)', TG_TABLE_NAME\n USING ERRCODE = 'check_violation';\n END IF;\n RETURN NEW;\n END IF;\n IF NEW.id IS NULL THEN\n NEW.id := TG_ARGV[0] || '_' || payload_typeid_encode(payload_typeid_uuid_v7_hex());\n END IF;\n RETURN NEW;\nEND $$;`;\n\n// Payload's Postgres table name for a collection slug: camelCase and hyphens become underscores.\nfunction tableNameForSlug(slug: string): string {\n return slug\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1_$2\")\n .replace(/([a-z\\d])([A-Z])/g, \"$1_$2\")\n .replace(/[-\\s]+/g, \"_\")\n .toLowerCase();\n}\n\n/** SQL that installs the ID functions, a per-table CHECK constraint, and a per-table trigger. */\nfunction typeIdDatabaseSql(guards: ReadonlyArray<{ table: string; prefix: string }>): string {\n const statements = [encodeFunction, uuidV7Function, guardFunction];\n for (const { table, prefix } of guards) {\n if (!identifierPattern.test(table) || !prefixSafePattern.test(prefix)) {\n throw new TypeError(`Refusing to guard unsafe table or prefix \"${table}\" / \"${prefix}\".`);\n }\n const constraint = `payload_typeid_${table}_id_check`;\n const trigger = `payload_typeid_${table}_guard`;\n statements.push(\n `ALTER TABLE \"${table}\" DROP CONSTRAINT IF EXISTS \"${constraint}\";`,\n `ALTER TABLE \"${table}\" ADD CONSTRAINT \"${constraint}\" CHECK (id ~ '^${prefix}_[0-7][0-9a-hjkmnp-tv-z]{25}$');`,\n `DROP TRIGGER IF EXISTS \"${trigger}\" ON \"${table}\";`,\n `CREATE TRIGGER \"${trigger}\" BEFORE INSERT OR UPDATE ON \"${table}\" FOR EACH ROW EXECUTE FUNCTION payload_typeid_guard('${prefix}');`,\n );\n }\n return statements.join(\"\\n\");\n}\n\ntype PostgresPool = { query(text: string, values?: unknown[]): Promise<{ rows: unknown[] }> };\n\n/**\n * Installs the database guards on the Postgres adapter. Other adapters get a warning instead:\n * the guards are SQL and cannot be applied to them.\n */\nasync function installTypeIdDatabaseGuards(\n payload: Payload,\n guards: ReadonlyArray<TypeIdTableGuard>,\n): Promise<void> {\n if (guards.length === 0) return;\n if (payload.db.name !== \"postgres\") {\n payload.logger.warn(\n `payload-typeid: database guards are only installed on PostgreSQL; the \"${payload.db.name}\" adapter keeps application-level rules only.`,\n );\n return;\n }\n\n const pool = (payload.db as unknown as { pool: PostgresPool }).pool;\n const tables = guards.map(({ slug, prefix }) => {\n const defaultName = tableNameForSlug(slug);\n const tableNameMap = (payload.db as unknown as { tableNameMap?: Map<string, string> })\n .tableNameMap;\n const table = tableNameMap?.get(defaultName) ?? defaultName;\n return { slug, prefix, table };\n });\n\n for (const { slug, table } of tables) {\n const { rows } = await pool.query(\"SELECT to_regclass($1) AS relation\", [`\"${table}\"`]);\n if (!(rows[0] as { relation: unknown } | undefined)?.relation) {\n throw new TypeError(\n `payload-typeid: no table \"${table}\" for collection \"${slug}\". Set the collection's dbName or rename it before enabling TypeIDs.`,\n );\n }\n }\n\n await pool.query(typeIdDatabaseSql(tables.map(({ table, prefix }) => ({ table, prefix }))));\n}\n\nexport type TypeID<Prefix extends string = string> = string extends Prefix\n ? string\n : Prefix extends \"\"\n ? string\n : `${Prefix}_${string}`;\n\nexport interface TypeIdOptions {\n collections?: Record<string, boolean | string>;\n}\n\ninterface ParsedTypeID<Prefix extends string = string> {\n prefix: Prefix;\n uuid: string;\n}\n\nconst prefixPattern = /^([a-z]([a-z_]{0,61}[a-z])?)?$/;\nconst uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst typeIdAlphabet = \"0123456789abcdefghjkmnpqrstvwxyz\";\nconst maxUuid = (1n << 128n) - 1n;\n\nfunction validatePrefix(prefix: string): void {\n if (!prefixPattern.test(prefix)) {\n throw new TypeError(\n `Invalid TypeID prefix \"${prefix}\". Prefixes must be empty or 1–63 lowercase ASCII letters and underscores, starting and ending with a letter.`,\n );\n }\n}\n\nfunction uuidFromBytes(bytes: Uint8Array): string {\n const hex = Buffer.from(bytes).toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nfunction encodeUuid(uuid: string): string {\n let value = BigInt(`0x${uuid.replaceAll(\"-\", \"\")}`);\n let suffix = \"\";\n for (let index = 0; index < 26; index += 1) {\n suffix = typeIdAlphabet[Number(value & 31n)] + suffix;\n value >>= 5n;\n }\n return suffix;\n}\n\nfunction decodeSuffix(suffix: string): string {\n let value = 0n;\n for (const character of suffix) {\n const digit = typeIdAlphabet.indexOf(character);\n if (digit === -1)\n throw new TypeError(\"Suffix contains a character outside the TypeID alphabet.\");\n value = (value << 5n) | BigInt(digit);\n }\n if (value > maxUuid) throw new TypeError(\"Suffix exceeds the 128-bit UUID range.\");\n return value.toString(16).padStart(32, \"0\");\n}\n\nexport function fromUUID<const Prefix extends string>(\n prefix: Prefix,\n uuid: string,\n): TypeID<Prefix> {\n validatePrefix(prefix);\n if (!uuidPattern.test(uuid)) {\n throw new TypeError(`Invalid UUID \"${uuid}\". Expected a canonical 36-character UUID.`);\n }\n return `${prefix ? `${prefix}_` : \"\"}${encodeUuid(uuid)}` as TypeID<Prefix>;\n}\n\nexport function parseTypeId<const Prefix extends string = string>(\n value: string,\n): ParsedTypeID<Prefix> {\n if (typeof value !== \"string\") throw new TypeError(\"TypeID must be a string.\");\n const separator = value.lastIndexOf(\"_\");\n const prefix = separator === -1 ? \"\" : value.slice(0, separator);\n const suffix = separator === -1 ? value : value.slice(separator + 1);\n try {\n validatePrefix(prefix);\n if (separator !== -1 && prefix === \"\") {\n throw new TypeError(\"An empty prefix must not include a separator.\");\n }\n if (suffix.length !== 26) throw new TypeError(\"Suffix must contain exactly 26 characters.\");\n const hex = decodeSuffix(suffix);\n return {\n prefix: prefix as Prefix,\n uuid: `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`,\n };\n } catch (error) {\n throw new TypeError(\n `Invalid TypeID \"${value}\": ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n}\n\nexport function toUUID(value: string): string {\n return parseTypeId(value).uuid;\n}\n\nexport function isTypeId<Prefix extends string = string>(\n value: unknown,\n expectedPrefix?: Prefix,\n): value is TypeID<Prefix> {\n if (typeof value !== \"string\") return false;\n try {\n const parsed = parseTypeId(value);\n return expectedPrefix === undefined || parsed.prefix === expectedPrefix;\n } catch {\n return false;\n }\n}\n\nexport function generateTypeId<const Prefix extends string>(prefix: Prefix): TypeID<Prefix> {\n validatePrefix(prefix);\n const bytes = randomBytes(16);\n let timestamp = BigInt(Date.now());\n for (let index = 5; index >= 0; index -= 1) {\n bytes[index] = Number(timestamp & 0xffn);\n timestamp >>= 8n;\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x70;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n return fromUUID(prefix, uuidFromBytes(bytes));\n}\n\nfunction deriveCollectionPrefix(slug: string): string {\n // Hyphens and underscores are word separators; Payload's formatLabels splits only on hyphens and whitespace.\n const singular = formatLabels(slug.replaceAll(\"_\", \"-\")).singular;\n const words = singular.split(\" \");\n // Acronyms such as \"APIKeys\" split into single letters, so they cannot be derived reliably.\n const derivable =\n singular !== \"\" &&\n words.every((word) => /^[A-Za-z]+$/.test(word)) &&\n !(words.length > 1 && words.some((word) => word.length === 1));\n if (!derivable) {\n throw new TypeError(\n `Collection \"${slug}\" cannot derive a TypeID prefix from its slug. Set custom.typeId or collections[\"${slug}\"] to an explicit prefix string.`,\n );\n }\n return words.join(\"_\").toLowerCase();\n}\n\nfunction hasCustomID(fields: Field[]): boolean {\n return flattenAllFields({ fields }).some((field) => \"name\" in field && field.name === \"id\");\n}\n\nfunction createIDField(prefix: string): Field {\n return {\n name: \"id\",\n type: \"text\",\n required: true,\n admin: { hidden: true, readOnly: true },\n access: {\n create: () => true,\n update: () => false,\n },\n defaultValue: () => generateTypeId(prefix),\n hooks: {\n beforeChange: [\n ({ operation, originalDoc, value }) => {\n if (operation === \"create\") return value || generateTypeId(prefix);\n return originalDoc?.id ?? value;\n },\n ],\n beforeDuplicate: [() => generateTypeId(prefix)],\n },\n };\n}\n\nfunction withIDOwnership(collection: CollectionConfig, prefix: string): CollectionConfig {\n const beforeOperation = collection.hooks?.beforeOperation ?? [];\n return {\n ...collection,\n // Payload stops custom ID discovery when it reaches structural fields.\n fields: [createIDField(prefix), ...collection.fields],\n hooks: {\n ...collection.hooks,\n beforeOperation: [\n ...beforeOperation,\n ({ operation, args }) => {\n if (operation === \"create\") {\n const createArgs = args as { customID?: unknown; data?: Record<string, unknown> };\n if (createArgs.customID !== undefined || createArgs.data?.id !== undefined) {\n throw new TypeError(\n `Collection \"${collection.slug}\" owns its IDs; omit customID and data.id when creating documents.`,\n );\n }\n }\n if (operation === \"update\") {\n const updateArgs = args as { data?: Record<string, unknown> };\n if (updateArgs.data?.id !== undefined) {\n throw new TypeError(\n `Collection \"${collection.slug}\" IDs are immutable; omit data.id when updating documents.`,\n );\n }\n }\n return args;\n },\n ],\n },\n };\n}\n\nfunction readSetting(value: unknown, owner: string): boolean | string | undefined {\n if (value === undefined || typeof value === \"boolean\" || typeof value === \"string\") {\n return value;\n }\n throw new TypeError(\n `Invalid TypeID configuration for ${owner}: custom.typeId must be true, false, a prefix string, or undefined.`,\n );\n}\n\nfunction assertCurrentKey(custom: Record<string, unknown> | undefined, owner: string): void {\n if (custom && Object.hasOwn(custom, \"typeid\")) {\n throw new TypeError(\n `${owner} uses the obsolete custom.typeid key; rename it to custom.typeId.`,\n );\n }\n}\n\nfunction validateCollectionPrefix(slug: string, prefix: string): void {\n if (prefix === \"\") {\n throw new TypeError(\n `Collection \"${slug}\" resolved to an empty TypeID prefix; provide a non-empty prefix string.`,\n );\n }\n try {\n validatePrefix(prefix);\n } catch (error) {\n throw new TypeError(\n `Invalid TypeID prefix for collection \"${slug}\": ${error instanceof Error ? error.message : String(error)} Provide a valid prefix string.`,\n { cause: error },\n );\n }\n}\n\nexport function typeId(options: TypeIdOptions = {}): Plugin {\n const plugin: Plugin = (config: Config) => {\n if (typeof options !== \"object\" || options === null || Array.isArray(options)) {\n throw new TypeError(\"TypeID options must be an object.\");\n }\n if (Object.keys(options).some((key) => key !== \"collections\")) {\n throw new TypeError('TypeID options only support \"collections\".');\n }\n if ((config.plugins?.filter(({ slug }) => slug === \"payload-typeid\").length ?? 0) > 1) {\n throw new TypeError(\"Register typeId() only once in the Payload plugins array.\");\n }\n\n const overrides = options.collections;\n if (\n overrides !== undefined &&\n (typeof overrides !== \"object\" || overrides === null || Array.isArray(overrides))\n ) {\n throw new TypeError(\n \"TypeID collections must be a record of collection slugs to true, false, or prefix strings.\",\n );\n }\n for (const [slug, setting] of Object.entries(overrides ?? {})) {\n if (typeof setting !== \"boolean\" && typeof setting !== \"string\") {\n throw new TypeError(\n `TypeID collections[\"${slug}\"] must be true, false, or a prefix string.`,\n );\n }\n }\n\n const collections = config.collections ?? [];\n const collectionSlugs = new Set(collections.map(({ slug }) => slug));\n for (const slug of Object.keys(overrides ?? {})) {\n if (!collectionSlugs.has(slug)) {\n throw new TypeError(`TypeID collections references unknown collection \"${slug}\".`);\n }\n }\n\n for (const global of config.globals ?? []) {\n assertCurrentKey(global.custom, `Global \"${global.slug}\"`);\n const setting = readSetting(global.custom?.typeId, `Global \"${global.slug}\"`);\n if (setting !== undefined && setting !== false) {\n throw new TypeError(\n `Global \"${global.slug}\" cannot use custom.typeId ${JSON.stringify(setting)} because Payload Globals do not expose configurable document IDs. Use false or omit custom.typeId.`,\n );\n }\n }\n\n // Resolve opt-out first so shadowed central settings never reach prefix validation.\n // Precedence: model custom.typeId > central collections entry > default (derived prefix).\n const managed: Array<{ collection: CollectionConfig; setting: true | string }> = [];\n for (const collection of collections) {\n assertCurrentKey(collection.custom, `Collection \"${collection.slug}\"`);\n const modelSetting = readSetting(\n collection.custom?.typeId,\n `collection \"${collection.slug}\"`,\n );\n const centralSetting =\n overrides && Object.hasOwn(overrides, collection.slug)\n ? overrides[collection.slug]\n : undefined;\n const setting = modelSetting ?? centralSetting ?? true;\n if (setting === false) continue;\n managed.push({ collection, setting });\n }\n\n const prefixes = new Map<string, string>();\n const replacements = new Map<string, CollectionConfig>();\n const guards: TypeIdTableGuard[] = [];\n for (const { collection, setting } of managed) {\n const prefix = setting === true ? deriveCollectionPrefix(collection.slug) : setting;\n validateCollectionPrefix(collection.slug, prefix);\n\n const existing = prefixes.get(prefix);\n if (existing) {\n throw new TypeError(\n `Collections \"${existing}\" and \"${collection.slug}\" resolve to duplicate TypeID prefix \"${prefix}\". Set an explicit prefix on one of them with custom.typeId or collections.`,\n );\n }\n prefixes.set(prefix, collection.slug);\n\n if (hasCustomID(collection.fields)) {\n throw new TypeError(\n `Collection \"${collection.slug}\" already has a collection-level field named \"id\". Set custom.typeId = false or rename that field before enabling TypeID.`,\n );\n }\n replacements.set(collection.slug, withIDOwnership(collection, prefix));\n guards.push({ slug: collection.slug, prefix });\n }\n\n const onInit = config.onInit;\n return {\n ...config,\n collections: collections.map((collection) => replacements.get(collection.slug) ?? collection),\n // Database guards run after Payload has created its tables, so the CHECK and triggers apply to them.\n onInit: async (payload) => {\n await onInit?.(payload);\n await installTypeIdDatabaseGuards(payload, guards);\n },\n };\n };\n\n plugin.slug = \"payload-typeid\";\n plugin.order = Number.MAX_SAFE_INTEGER;\n return plugin;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@klnap/payload-typeid",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Type-prefixed UUIDv7 primary keys for Payload CMS.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"private": false,
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
"prepublishOnly": "node -e \"if (require('./package.json').private) throw new Error('This package is private and cannot be published')\"",
|
|
57
57
|
"changeset": "changeset",
|
|
58
58
|
"changeset:version": "changeset version",
|
|
59
|
-
"changeset:version-check": "bun run changeset:version && bun run check"
|
|
59
|
+
"changeset:version-check": "bun run changeset:version && bunx biome format --write CHANGELOG.md && bun run check"
|
|
60
60
|
},
|
|
61
61
|
"peerDependencies": {
|
|
62
62
|
"payload": "^3.1.1"
|