cogens 0.0.0-stage → 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/LICENSE +22 -0
- package/NOTICE +25 -0
- package/README.md +385 -2
- package/editor/editor-dark.css +2 -0
- package/editor/editor.css +9 -0
- package/editor/entry.js +28 -0
- package/migrations/0001_entries.sql +43 -0
- package/migrations/auth/0001_sessions.sql +50 -0
- package/migrations/koguma-upgrade.sql +13 -0
- package/package.json +86 -4
- package/scripts/build-admin-editor.ts +155 -0
- package/scripts/print-migration.ts +50 -0
- package/src/admin/app.ts +608 -0
- package/src/admin/assets.ts +52 -0
- package/src/admin/fields.ts +172 -0
- package/src/admin/forms.ts +64 -0
- package/src/admin/index.ts +16 -0
- package/src/admin/rules.ts +63 -0
- package/src/admin/types.ts +99 -0
- package/src/admin/views.ts +360 -0
- package/src/auth/handoff.ts +56 -0
- package/src/auth/index.ts +29 -0
- package/src/auth/password.ts +201 -0
- package/src/auth/principal.ts +40 -0
- package/src/auth/session.ts +143 -0
- package/src/core/access/ability.ts +86 -0
- package/src/core/access/can.ts +66 -0
- package/src/core/access/compile.ts +62 -0
- package/src/core/access/permits.ts +45 -0
- package/src/core/access/when.ts +59 -0
- package/src/core/access/where.ts +95 -0
- package/src/core/columns.ts +7 -0
- package/src/core/config/define.ts +206 -0
- package/src/core/config/field.ts +119 -0
- package/src/core/errors.ts +99 -0
- package/src/core/index.ts +44 -0
- package/src/core/media/index.ts +132 -0
- package/src/core/principal.ts +49 -0
- package/src/core/store/assets.ts +2 -0
- package/src/core/store/cms.ts +199 -0
- package/src/core/store/content.ts +453 -0
- package/src/core/store/sql.ts +239 -0
- package/src/core/store/types.ts +100 -0
- package/src/core/testing/index.ts +75 -0
- package/src/testing/db.ts +53 -0
- package/src/testing/index.ts +9 -0
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* contentType, group, defineConfig, Infer: the schema definition API. A type
|
|
3
|
+
* names its fields and, beyond Koguma's, whether its entries are owned, which
|
|
4
|
+
* fields are indexed, who may do what (`access`), what a child mirrors of its
|
|
5
|
+
* parent, and hooks around writes.
|
|
6
|
+
*/
|
|
7
|
+
import { ConfigError } from '../errors.ts';
|
|
8
|
+
import type { AccessFn } from '../access/can.ts';
|
|
9
|
+
import type { AfterWriteContext, WriteContext } from '../store/types.ts';
|
|
10
|
+
import { FieldBuilder, type FieldMeta } from './field.ts';
|
|
11
|
+
|
|
12
|
+
export interface GroupConfig {
|
|
13
|
+
groupId: string;
|
|
14
|
+
name: string;
|
|
15
|
+
helpText?: string;
|
|
16
|
+
collapsed?: boolean;
|
|
17
|
+
fields: Record<string, FieldBuilder<any, any>>;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function group(opts: {
|
|
21
|
+
id: string;
|
|
22
|
+
name: string;
|
|
23
|
+
helpText?: string;
|
|
24
|
+
collapsed?: boolean;
|
|
25
|
+
fields: Record<string, FieldBuilder<any, any>>;
|
|
26
|
+
}): GroupConfig {
|
|
27
|
+
return { groupId: opts.id, name: opts.name, helpText: opts.helpText, collapsed: opts.collapsed, fields: opts.fields };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** An action the admin offers on one entry of an external collection. */
|
|
31
|
+
export interface ServiceAction {
|
|
32
|
+
id: string;
|
|
33
|
+
label: string;
|
|
34
|
+
/** The confirmation text shown before the action runs. */
|
|
35
|
+
confirm: string;
|
|
36
|
+
method: 'POST' | 'DELETE';
|
|
37
|
+
/** Path template; `:id` is the entry's id. */
|
|
38
|
+
path: string;
|
|
39
|
+
/** A content type to pick an entry of first; the body sent is `{ from: <this id>, into: <picked id> }`. */
|
|
40
|
+
target?: string;
|
|
41
|
+
destructive?: boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** An external collection: a read-only view over a table of the host's own, never stored as entries. */
|
|
45
|
+
export interface ServiceConfig {
|
|
46
|
+
readOnly: true;
|
|
47
|
+
actions?: ServiceAction[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Names a column or a condition keyword may not be used as a field name for. */
|
|
51
|
+
export const RESERVED_FIELD_NAMES = [
|
|
52
|
+
'id',
|
|
53
|
+
'type',
|
|
54
|
+
'content_type',
|
|
55
|
+
'owner_id',
|
|
56
|
+
'slug',
|
|
57
|
+
'status',
|
|
58
|
+
'parent_id',
|
|
59
|
+
'parent_status',
|
|
60
|
+
'sort_key',
|
|
61
|
+
'publish_at',
|
|
62
|
+
'created_at',
|
|
63
|
+
'updated_at',
|
|
64
|
+
'data',
|
|
65
|
+
'and',
|
|
66
|
+
'or',
|
|
67
|
+
'in'
|
|
68
|
+
] as const;
|
|
69
|
+
|
|
70
|
+
const FIELD_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;
|
|
71
|
+
const TYPE_ID = /^[a-z][A-Za-z0-9_-]*$/;
|
|
72
|
+
|
|
73
|
+
export type Fields = Record<string, FieldBuilder<any, any>>;
|
|
74
|
+
|
|
75
|
+
export interface ContentType<F extends Fields = Fields> {
|
|
76
|
+
readonly id: string;
|
|
77
|
+
readonly name: string;
|
|
78
|
+
readonly displayField: string;
|
|
79
|
+
readonly singleton?: boolean;
|
|
80
|
+
/** Entries have an owner; the type must then have an `access` function. */
|
|
81
|
+
readonly owned: boolean;
|
|
82
|
+
/** Fields conditions may name; each becomes a generated column (print-migration.ts prints it). */
|
|
83
|
+
readonly indexed: readonly string[];
|
|
84
|
+
/** The slug is unique among this type's entries. */
|
|
85
|
+
readonly uniqueSlug: boolean;
|
|
86
|
+
/** The id of the type this type's entries are children of (`parent_id` names the entry). */
|
|
87
|
+
readonly parent?: string;
|
|
88
|
+
/** What a child copies from its parent in the same write that changes it. */
|
|
89
|
+
readonly mirrors: readonly 'status'[];
|
|
90
|
+
readonly access?: AccessFn<any>;
|
|
91
|
+
readonly beforeWrite?: (context: WriteContext<any>) => void | Promise<void>;
|
|
92
|
+
readonly afterWrite?: (context: AfterWriteContext<any>) => void | Promise<void>;
|
|
93
|
+
readonly service?: ServiceConfig;
|
|
94
|
+
/** Every field, flat. */
|
|
95
|
+
readonly fields: F;
|
|
96
|
+
readonly fieldMeta: Record<string, FieldMeta>;
|
|
97
|
+
readonly groups: GroupConfig[];
|
|
98
|
+
/** The fields of a type declared without groups. */
|
|
99
|
+
readonly flatFields: Fields;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export interface ContentTypeOptions<F extends Fields | GroupConfig[]> {
|
|
103
|
+
id: string;
|
|
104
|
+
name: string;
|
|
105
|
+
displayField: string;
|
|
106
|
+
singleton?: boolean;
|
|
107
|
+
owned?: boolean;
|
|
108
|
+
indexed?: readonly string[];
|
|
109
|
+
uniqueSlug?: boolean;
|
|
110
|
+
parent?: string;
|
|
111
|
+
mirrors?: readonly 'status'[];
|
|
112
|
+
access?: AccessFn<any>;
|
|
113
|
+
beforeWrite?: (context: WriteContext<any>) => void | Promise<void>;
|
|
114
|
+
afterWrite?: (context: AfterWriteContext<any>) => void | Promise<void>;
|
|
115
|
+
service?: ServiceConfig;
|
|
116
|
+
fields: F;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function contentType<F extends Fields | GroupConfig[]>(
|
|
120
|
+
opts: ContentTypeOptions<F>
|
|
121
|
+
): ContentType<F extends GroupConfig[] ? Fields : Extract<F, Fields>> {
|
|
122
|
+
if (!TYPE_ID.test(opts.id)) throw new ConfigError(`Type id "${opts.id}" must start with a lowercase letter and use letters, digits, - and _.`, opts.id);
|
|
123
|
+
|
|
124
|
+
const all: Fields = {};
|
|
125
|
+
const groups: GroupConfig[] = [];
|
|
126
|
+
let flatFields: Fields = {};
|
|
127
|
+
if (Array.isArray(opts.fields)) {
|
|
128
|
+
for (const g of opts.fields) {
|
|
129
|
+
groups.push(g);
|
|
130
|
+
Object.assign(all, g.fields);
|
|
131
|
+
}
|
|
132
|
+
} else {
|
|
133
|
+
flatFields = opts.fields as Fields;
|
|
134
|
+
Object.assign(all, flatFields);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
for (const name of Object.keys(all)) {
|
|
138
|
+
if ((RESERVED_FIELD_NAMES as readonly string[]).includes(name)) {
|
|
139
|
+
throw new ConfigError(
|
|
140
|
+
`Field "${name}" of type "${opts.id}" collides with a built-in name (${RESERVED_FIELD_NAMES.join(', ')}); the built-in column of that name is used instead.`,
|
|
141
|
+
opts.id,
|
|
142
|
+
name
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
if (!FIELD_NAME.test(name)) {
|
|
146
|
+
throw new ConfigError(`Field "${name}" of type "${opts.id}" must start with a letter and use letters, digits and _.`, opts.id, name);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const indexed = opts.indexed ?? [];
|
|
150
|
+
for (const name of indexed) {
|
|
151
|
+
if (!(name in all)) throw new ConfigError(`Type "${opts.id}" indexes "${name}", which is not one of its fields.`, opts.id, name);
|
|
152
|
+
}
|
|
153
|
+
if (new Set(indexed).size !== indexed.length) {
|
|
154
|
+
throw new ConfigError(`Type "${opts.id}" lists an indexed field twice.`, opts.id);
|
|
155
|
+
}
|
|
156
|
+
if (opts.mirrors?.length && opts.parent === undefined) {
|
|
157
|
+
throw new ConfigError(`Type "${opts.id}" mirrors its parent's status but names no parent.`, opts.id);
|
|
158
|
+
}
|
|
159
|
+
if (opts.displayField !== undefined && !(opts.displayField in all) && Object.keys(all).length > 0) {
|
|
160
|
+
throw new ConfigError(`Type "${opts.id}" shows "${opts.displayField}", which is not one of its fields.`, opts.id, opts.displayField);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const fieldMeta: Record<string, FieldMeta> = {};
|
|
164
|
+
for (const [name, builder] of Object.entries(all)) fieldMeta[name] = builder.meta;
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
id: opts.id,
|
|
168
|
+
name: opts.name,
|
|
169
|
+
displayField: opts.displayField,
|
|
170
|
+
singleton: opts.singleton,
|
|
171
|
+
owned: opts.owned ?? false,
|
|
172
|
+
indexed,
|
|
173
|
+
uniqueSlug: opts.uniqueSlug ?? false,
|
|
174
|
+
parent: opts.parent,
|
|
175
|
+
mirrors: opts.mirrors ?? [],
|
|
176
|
+
access: opts.access,
|
|
177
|
+
beforeWrite: opts.beforeWrite,
|
|
178
|
+
afterWrite: opts.afterWrite,
|
|
179
|
+
service: opts.service,
|
|
180
|
+
fields: all as never,
|
|
181
|
+
fieldMeta,
|
|
182
|
+
groups,
|
|
183
|
+
flatFields
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export interface CmsConfig {
|
|
188
|
+
siteName: string;
|
|
189
|
+
contentTypes: ContentType<any>[];
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function defineConfig(config: CmsConfig): CmsConfig {
|
|
193
|
+
return config;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ── Infer ────────────────────────────────────────────────────────────
|
|
197
|
+
|
|
198
|
+
type Flatten<T> = { [K in keyof T]: T[K] } & {};
|
|
199
|
+
type RequiredKeys<F extends Fields> = { [K in keyof F]: F[K] extends FieldBuilder<any, true> ? K : never }[keyof F];
|
|
200
|
+
type OptionalKeys<F extends Fields> = Exclude<keyof F, RequiredKeys<F>>;
|
|
201
|
+
|
|
202
|
+
/** The type of an entry's `data`: required fields present, the rest optional. */
|
|
203
|
+
export type Infer<T extends ContentType<any>> =
|
|
204
|
+
T extends ContentType<infer F>
|
|
205
|
+
? Flatten<{ [K in RequiredKeys<F>]: F[K]['_type'] } & { [K in OptionalKeys<F>]?: F[K]['_type'] | null }>
|
|
206
|
+
: never;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* field.* builders: the content fields of a type. Each holds its label, its kind
|
|
3
|
+
* for the admin and a JSON Schema (draft 7) for @cfworker/json-schema, which
|
|
4
|
+
* validates without `new Function`, so it runs in a Worker.
|
|
5
|
+
*
|
|
6
|
+
* field.text('Title').required().max(100)
|
|
7
|
+
* field.number('Revision').system()
|
|
8
|
+
*/
|
|
9
|
+
import type { Schema } from '@cfworker/json-schema';
|
|
10
|
+
|
|
11
|
+
export type FieldType =
|
|
12
|
+
| 'text'
|
|
13
|
+
| 'longText'
|
|
14
|
+
| 'markdown'
|
|
15
|
+
| 'url'
|
|
16
|
+
| 'email'
|
|
17
|
+
| 'boolean'
|
|
18
|
+
| 'number'
|
|
19
|
+
| 'date'
|
|
20
|
+
| 'select'
|
|
21
|
+
| 'reference'
|
|
22
|
+
| 'references'
|
|
23
|
+
| 'files'
|
|
24
|
+
| 'json';
|
|
25
|
+
|
|
26
|
+
export interface FieldMeta {
|
|
27
|
+
label: string;
|
|
28
|
+
fieldType: FieldType;
|
|
29
|
+
required: boolean;
|
|
30
|
+
/** A system field is writable only by a caller whose rule lists it by name. */
|
|
31
|
+
system: boolean;
|
|
32
|
+
refContentType?: string;
|
|
33
|
+
options?: string[];
|
|
34
|
+
/** Stored when a create leaves the field out; set by the store, so a system field may have one. */
|
|
35
|
+
default?: unknown;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** `T` is the stored value's type and `R` whether the field is required (a phantom, for `Infer`). */
|
|
39
|
+
export class FieldBuilder<T = unknown, R extends boolean = false> {
|
|
40
|
+
declare readonly _type: T;
|
|
41
|
+
declare readonly _required: R;
|
|
42
|
+
|
|
43
|
+
constructor(
|
|
44
|
+
readonly meta: FieldMeta,
|
|
45
|
+
readonly schema: Schema
|
|
46
|
+
) {}
|
|
47
|
+
|
|
48
|
+
/** The value must be present on create (an update may leave it out). */
|
|
49
|
+
required(): FieldBuilder<T, true> {
|
|
50
|
+
return new FieldBuilder<T, true>({ ...this.meta, required: true }, this.schema);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Writable only by a caller whose rule lists the field by name. */
|
|
54
|
+
system(): FieldBuilder<T, R> {
|
|
55
|
+
return new FieldBuilder<T, R>({ ...this.meta, system: true }, this.schema);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The value a create stores when the field is left out. The store applies it whoever creates, so a system field
|
|
60
|
+
* the creator may not write (a flag a rule reads, such as `retired: 0`) still starts with a value.
|
|
61
|
+
*/
|
|
62
|
+
default(value: T): FieldBuilder<T, R> {
|
|
63
|
+
return new FieldBuilder<T, R>({ ...this.meta, default: value }, this.schema);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Maximum length (text), value (number) or count (list). */
|
|
67
|
+
max(value: number): FieldBuilder<T, R> {
|
|
68
|
+
const key = this.schema.type === 'string' ? 'maxLength' : this.schema.type === 'number' ? 'maximum' : 'maxItems';
|
|
69
|
+
return new FieldBuilder<T, R>(this.meta, { ...this.schema, [key]: value });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Minimum length (text), value (number) or count (list). */
|
|
73
|
+
min(value: number): FieldBuilder<T, R> {
|
|
74
|
+
const key = this.schema.type === 'string' ? 'minLength' : this.schema.type === 'number' ? 'minimum' : 'minItems';
|
|
75
|
+
return new FieldBuilder<T, R>(this.meta, { ...this.schema, [key]: value });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const make = <T>(label: string, fieldType: FieldType, schema: Schema, extra: Partial<FieldMeta> = {}) =>
|
|
80
|
+
new FieldBuilder<T, false>({ label, fieldType, required: false, system: false, ...extra }, schema);
|
|
81
|
+
|
|
82
|
+
export interface StoredFile {
|
|
83
|
+
name: string;
|
|
84
|
+
size: number;
|
|
85
|
+
url: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export const field = {
|
|
89
|
+
text: (label: string) => make<string>(label, 'text', { type: 'string' }),
|
|
90
|
+
longText: (label: string) => make<string>(label, 'longText', { type: 'string' }),
|
|
91
|
+
/** Markdown, stored as a string. */
|
|
92
|
+
markdown: (label: string) => make<string>(label, 'markdown', { type: 'string' }),
|
|
93
|
+
url: (label: string) => make<string>(label, 'url', { type: 'string', format: 'uri' }),
|
|
94
|
+
email: (label: string) => make<string>(label, 'email', { type: 'string', format: 'email' }),
|
|
95
|
+
boolean: (label: string) => make<boolean>(label, 'boolean', { type: 'boolean' }),
|
|
96
|
+
number: (label: string) => make<number>(label, 'number', { type: 'number' }),
|
|
97
|
+
/** An ISO 8601 date and time. */
|
|
98
|
+
date: (label: string) => make<string>(label, 'date', { type: 'string', format: 'date-time' }),
|
|
99
|
+
select: <const O extends readonly string[]>(label: string, opts: { options: O }) =>
|
|
100
|
+
make<O[number]>(label, 'select', { type: 'string', enum: [...opts.options] }, { options: [...opts.options] }),
|
|
101
|
+
/** The id of an entry of another type. */
|
|
102
|
+
ref: (contentType: string, label: string) =>
|
|
103
|
+
make<string>(label, 'reference', { type: 'string' }, { refContentType: contentType }),
|
|
104
|
+
/** Ids of entries of another type, in order. */
|
|
105
|
+
refs: (contentType: string, label: string) =>
|
|
106
|
+
make<string[]>(label, 'references', { type: 'array', items: { type: 'string' } }, { refContentType: contentType }),
|
|
107
|
+
/** A read-only list of stored files, `{ name, size, url }` each. */
|
|
108
|
+
files: (label: string) =>
|
|
109
|
+
make<StoredFile[]>(label, 'files', {
|
|
110
|
+
type: 'array',
|
|
111
|
+
items: {
|
|
112
|
+
type: 'object',
|
|
113
|
+
properties: { name: { type: 'string' }, size: { type: 'number' }, url: { type: 'string' } },
|
|
114
|
+
required: ['name', 'size', 'url']
|
|
115
|
+
}
|
|
116
|
+
}),
|
|
117
|
+
/** Any JSON value. */
|
|
118
|
+
json: <T = unknown>(label: string) => make<T>(label, 'json', {})
|
|
119
|
+
};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/** The typed errors the store throws. A read the caller may not make never throws; it answers null or an empty list. */
|
|
2
|
+
|
|
3
|
+
export type Operation = 'create' | 'read' | 'update' | 'delete' | 'publish';
|
|
4
|
+
|
|
5
|
+
/** A write the caller's rules refuse. `field` is set when a field rule caused it. */
|
|
6
|
+
export class Forbidden extends Error {
|
|
7
|
+
override readonly name = 'Forbidden';
|
|
8
|
+
constructor(
|
|
9
|
+
readonly operation: Operation | 'unpublish',
|
|
10
|
+
readonly type: string,
|
|
11
|
+
readonly field?: string
|
|
12
|
+
) {
|
|
13
|
+
super(
|
|
14
|
+
field === undefined
|
|
15
|
+
? `Forbidden: ${operation} on ${type}.`
|
|
16
|
+
: `Forbidden: ${operation} on ${type} may not write the field "${field}".`
|
|
17
|
+
);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The host's configuration is wrong; the message names the type and, where there is one, the field. */
|
|
22
|
+
export class ConfigError extends Error {
|
|
23
|
+
override readonly name = 'ConfigError';
|
|
24
|
+
constructor(
|
|
25
|
+
message: string,
|
|
26
|
+
readonly type?: string,
|
|
27
|
+
readonly field?: string
|
|
28
|
+
) {
|
|
29
|
+
super(message);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A condition the compiler refuses: an unknown operator, a field that is not indexed, or too many values. */
|
|
34
|
+
export class ConditionError extends Error {
|
|
35
|
+
override readonly name = 'ConditionError';
|
|
36
|
+
constructor(
|
|
37
|
+
message: string,
|
|
38
|
+
readonly field?: string
|
|
39
|
+
) {
|
|
40
|
+
super(message);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** The data does not fit the type's fields, or names a field the type does not have. */
|
|
45
|
+
export class ValidationError extends Error {
|
|
46
|
+
override readonly name = 'ValidationError';
|
|
47
|
+
constructor(
|
|
48
|
+
readonly type: string,
|
|
49
|
+
readonly issues: { field: string; message: string }[]
|
|
50
|
+
) {
|
|
51
|
+
super(`Invalid ${type}: ${issues.map(i => `${i.field}: ${i.message}`).join('; ')}`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A before-write hook refused the write. */
|
|
56
|
+
export class WriteRefused extends Error {
|
|
57
|
+
override readonly name = 'WriteRefused';
|
|
58
|
+
constructor(
|
|
59
|
+
readonly type: string,
|
|
60
|
+
message: string
|
|
61
|
+
) {
|
|
62
|
+
super(message);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A unique constraint (the id, or a unique slug) was already taken. */
|
|
67
|
+
export class Conflict extends Error {
|
|
68
|
+
override readonly name = 'Conflict';
|
|
69
|
+
constructor(
|
|
70
|
+
readonly type: string,
|
|
71
|
+
readonly field: 'id' | 'slug'
|
|
72
|
+
) {
|
|
73
|
+
super(`Conflict: a ${type} with this ${field} already exists.`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Publishing a parent would update more children than one atomic write may. */
|
|
78
|
+
export class TooManyChildren extends Error {
|
|
79
|
+
override readonly name = 'TooManyChildren';
|
|
80
|
+
constructor(
|
|
81
|
+
readonly type: string,
|
|
82
|
+
readonly count: number,
|
|
83
|
+
readonly limit: number
|
|
84
|
+
) {
|
|
85
|
+
super(`${type} has ${count} children that mirror its status; the limit for one write is ${limit}. Nothing was changed.`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** A bulk write names more entries than one write may hold. */
|
|
90
|
+
export class TooManyEntries extends Error {
|
|
91
|
+
override readonly name = 'TooManyEntries';
|
|
92
|
+
constructor(
|
|
93
|
+
readonly type: string,
|
|
94
|
+
readonly count: number,
|
|
95
|
+
readonly limit: number
|
|
96
|
+
) {
|
|
97
|
+
super(`${count} ${type} entries in one write; the limit is ${limit}. Nothing was changed.`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* cogens: the content store. A content type declares who owns it and who may
|
|
3
|
+
* create, read, update, delete and publish it; every read and write names its
|
|
4
|
+
* caller (`cms.content.as(principal)`), and a read the caller may not make
|
|
5
|
+
* answers as a missing row.
|
|
6
|
+
*
|
|
7
|
+
* Imports nothing of the host's, and nothing but `hono`, `@casl/ability` and
|
|
8
|
+
* `@cfworker/json-schema` (test/boundary.test.ts). No export names a
|
|
9
|
+
* type of the decision engine under `can`.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export { contentType, defineConfig, group, RESERVED_FIELD_NAMES } from './config/define.ts';
|
|
13
|
+
export type {
|
|
14
|
+
CmsConfig, ContentType, ContentTypeOptions, Fields, GroupConfig, Infer, ServiceAction, ServiceConfig
|
|
15
|
+
} from './config/define.ts';
|
|
16
|
+
export { field, FieldBuilder } from './config/field.ts';
|
|
17
|
+
export type { FieldMeta, FieldType, StoredFile } from './config/field.ts';
|
|
18
|
+
|
|
19
|
+
export { OPERATIONS } from './access/can.ts';
|
|
20
|
+
export type { AccessContext, AccessFn, Can, Grant, GrantOptions } from './access/can.ts';
|
|
21
|
+
export { MAX_IN_VALUES } from './access/where.ts';
|
|
22
|
+
export type { Scalar, Where } from './access/where.ts';
|
|
23
|
+
export { permits } from './access/permits.ts';
|
|
24
|
+
export type { PackedRules, PackedTypeRules } from './access/permits.ts';
|
|
25
|
+
|
|
26
|
+
export { admin, anonymous, system } from './principal.ts';
|
|
27
|
+
export type { AdminPrincipal, AnonymousPrincipal, HostPrincipal, Principal, SystemPrincipal } from './principal.ts';
|
|
28
|
+
|
|
29
|
+
export { createCms } from './store/cms.ts';
|
|
30
|
+
export type { Cms, CmsOptions } from './store/cms.ts';
|
|
31
|
+
export type {
|
|
32
|
+
AfterWriteContext, Compare, ContentApi, CreateInput, Entry, ListOptions, OrderBy, Status, TypeRef, UpdateEachChange, UpdatePatch, UpdateResult,
|
|
33
|
+
When, WriteContext, WriteOptions
|
|
34
|
+
} from './store/types.ts';
|
|
35
|
+
|
|
36
|
+
export type { Asset, MediaApi, MediaOptions, UploadInput } from './media/index.ts';
|
|
37
|
+
|
|
38
|
+
export {
|
|
39
|
+
ConditionError, ConfigError, Conflict, Forbidden, TooManyChildren, TooManyEntries, ValidationError, WriteRefused
|
|
40
|
+
} from './errors.ts';
|
|
41
|
+
export type { Operation } from './errors.ts';
|
|
42
|
+
|
|
43
|
+
export { policyMatrix, PolicyMismatch } from './testing/index.ts';
|
|
44
|
+
export type { PolicyMatrixOptions, Expectation } from './testing/index.ts';
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Media, reduced to upload, list and delete, each through the same access check
|
|
3
|
+
* as an entry: a host passes an `access` function for assets (the operations
|
|
4
|
+
* create, read and delete, conditions over `owner_id` and `id`), and with none a
|
|
5
|
+
* caller can do nothing. Files live in R2; the row holds the name, type and size.
|
|
6
|
+
*/
|
|
7
|
+
import { compileAny, type ColumnOf } from '../access/compile.ts';
|
|
8
|
+
import { RuleSet } from '../access/ability.ts';
|
|
9
|
+
import { runAccess, type AccessFn } from '../access/can.ts';
|
|
10
|
+
import { ConditionError, Forbidden, ValidationError } from '../errors.ts';
|
|
11
|
+
import type { HostPrincipal, Principal } from '../principal.ts';
|
|
12
|
+
import { deleteAsset, insertAsset, selectAssets } from '../store/assets.ts';
|
|
13
|
+
|
|
14
|
+
export interface MediaOptions {
|
|
15
|
+
bucket: R2Bucket;
|
|
16
|
+
/** Who may create, read and delete assets. */
|
|
17
|
+
access: AccessFn<any>;
|
|
18
|
+
/** Largest upload, in bytes; 10 MB when absent. */
|
|
19
|
+
maxBytes?: number;
|
|
20
|
+
newId?: () => string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface Asset {
|
|
24
|
+
id: string;
|
|
25
|
+
owner_id: string | null;
|
|
26
|
+
name: string;
|
|
27
|
+
content_type: string;
|
|
28
|
+
size: number;
|
|
29
|
+
/** The R2 key the file is stored under. */
|
|
30
|
+
key: string;
|
|
31
|
+
created_at: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface UploadInput {
|
|
35
|
+
name: string;
|
|
36
|
+
contentType: string;
|
|
37
|
+
body: ArrayBuffer | Uint8Array | Blob;
|
|
38
|
+
ownerId?: string | null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface MediaApi {
|
|
42
|
+
upload(input: UploadInput): Promise<Asset>;
|
|
43
|
+
list(): Promise<Asset[]>;
|
|
44
|
+
get(id: string): Promise<Asset | null>;
|
|
45
|
+
remove(id: string): Promise<void>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const TYPE = 'asset';
|
|
49
|
+
const columnOf: ColumnOf = field => (field === 'owner_id' || field === 'id' ? field : null);
|
|
50
|
+
const DEFAULT_MAX = 10 * 1024 * 1024;
|
|
51
|
+
|
|
52
|
+
export function createMedia(db: D1Database, options: MediaOptions, ensureReady: () => Promise<void>) {
|
|
53
|
+
const newId = options.newId ?? (() => crypto.randomUUID());
|
|
54
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX;
|
|
55
|
+
|
|
56
|
+
/** Assets answer to the same engine, as a type named `asset` with no fields of its own. */
|
|
57
|
+
function as(principal: Principal<HostPrincipal>): MediaApi {
|
|
58
|
+
const rules = new RuleSet(TYPE, runAccess(options.access, principal));
|
|
59
|
+
const condition = (operation: 'create' | 'read' | 'delete') => {
|
|
60
|
+
try {
|
|
61
|
+
const compiled = compileAny(rules.grants.filter(g => g.operation === operation).map(g => g.where), columnOf);
|
|
62
|
+
return compiled && { sql: `(${compiled.sql})`, params: compiled.params };
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (error instanceof ConditionError) throw new ConditionError(`Media: ${error.message}`, error.field);
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
const toAsset = (row: Awaited<ReturnType<typeof selectAssets>>[number]): Asset => ({
|
|
69
|
+
id: row.id,
|
|
70
|
+
owner_id: row.owner_id,
|
|
71
|
+
name: String(row.data.name ?? ''),
|
|
72
|
+
content_type: String(row.data.content_type ?? ''),
|
|
73
|
+
size: Number(row.data.size ?? 0),
|
|
74
|
+
key: String(row.data.key ?? ''),
|
|
75
|
+
created_at: row.created_at
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
return {
|
|
79
|
+
async upload(input) {
|
|
80
|
+
const ownerId = input.ownerId ?? null;
|
|
81
|
+
if (!rules.allows('create', { owner_id: ownerId })) throw new Forbidden('create', TYPE);
|
|
82
|
+
const bytes = input.body instanceof Blob ? await input.body.arrayBuffer() : input.body;
|
|
83
|
+
if (bytes.byteLength > maxBytes) {
|
|
84
|
+
throw new ValidationError(TYPE, [{ field: 'body', message: `is ${bytes.byteLength} bytes; the limit is ${maxBytes}.` }]);
|
|
85
|
+
}
|
|
86
|
+
if (input.name.trim() === '') throw new ValidationError(TYPE, [{ field: 'name', message: 'is required.' }]);
|
|
87
|
+
await ensureReady();
|
|
88
|
+
const id = newId();
|
|
89
|
+
const key = `media/${id}`;
|
|
90
|
+
await options.bucket.put(key, bytes, { httpMetadata: { contentType: input.contentType } });
|
|
91
|
+
try {
|
|
92
|
+
await insertAsset(db, {
|
|
93
|
+
id,
|
|
94
|
+
owner_id: ownerId,
|
|
95
|
+
data: { name: input.name, content_type: input.contentType, size: bytes.byteLength, key }
|
|
96
|
+
}).run();
|
|
97
|
+
} catch (error) {
|
|
98
|
+
await options.bucket.delete(key);
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
return toAsset((await selectAssets(db, { sql: '1', params: [] }, id))[0]!);
|
|
102
|
+
},
|
|
103
|
+
|
|
104
|
+
async list() {
|
|
105
|
+
const access = condition('read');
|
|
106
|
+
if (!access) return [];
|
|
107
|
+
await ensureReady();
|
|
108
|
+
return (await selectAssets(db, access)).map(toAsset);
|
|
109
|
+
},
|
|
110
|
+
|
|
111
|
+
async get(id) {
|
|
112
|
+
const access = condition('read');
|
|
113
|
+
if (!access) return null;
|
|
114
|
+
await ensureReady();
|
|
115
|
+
const row = (await selectAssets(db, access, id))[0];
|
|
116
|
+
return row ? toAsset(row) : null;
|
|
117
|
+
},
|
|
118
|
+
|
|
119
|
+
async remove(id) {
|
|
120
|
+
const access = condition('delete');
|
|
121
|
+
if (!access) throw new Forbidden('delete', TYPE);
|
|
122
|
+
await ensureReady();
|
|
123
|
+
const row = (await selectAssets(db, access, id))[0];
|
|
124
|
+
if (!row) throw new Forbidden('delete', TYPE);
|
|
125
|
+
await deleteAsset(db, id, access).run();
|
|
126
|
+
await options.bucket.delete(String(row.data.key ?? `media/${id}`));
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return { as };
|
|
132
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The caller. The host decides who is calling and passes a principal; the store
|
|
3
|
+
* never reads a cookie or a header. Three kinds are built in, and a host adds
|
|
4
|
+
* its own through the type parameter, with whatever claims its rules use.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export interface HostPrincipal {
|
|
8
|
+
readonly kind: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface AdminPrincipal {
|
|
12
|
+
readonly kind: 'admin';
|
|
13
|
+
/** The operator's id, for the host's own records; the store gives it no meaning. */
|
|
14
|
+
readonly id?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Background work, naming its job. */
|
|
18
|
+
export interface SystemPrincipal {
|
|
19
|
+
readonly kind: 'system';
|
|
20
|
+
readonly job: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface AnonymousPrincipal {
|
|
24
|
+
readonly kind: 'anonymous';
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export type Principal<H extends HostPrincipal = never> = AdminPrincipal | SystemPrincipal | AnonymousPrincipal | H;
|
|
28
|
+
|
|
29
|
+
export const anonymous: AnonymousPrincipal = Object.freeze({ kind: 'anonymous' });
|
|
30
|
+
|
|
31
|
+
export function admin(id?: string): AdminPrincipal {
|
|
32
|
+
return Object.freeze(id === undefined ? { kind: 'admin' as const } : { kind: 'admin' as const, id });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function system(job: string): SystemPrincipal {
|
|
36
|
+
if (typeof job !== 'string' || job.trim() === '') throw new TypeError('A system principal must name its job.');
|
|
37
|
+
return Object.freeze({ kind: 'system' as const, job });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Checks the shape of a principal a host built, so a typo is an error and not an anonymous caller. */
|
|
41
|
+
export function assertPrincipal(principal: unknown): asserts principal is HostPrincipal {
|
|
42
|
+
if (typeof principal !== 'object' || principal === null || typeof (principal as HostPrincipal).kind !== 'string') {
|
|
43
|
+
throw new TypeError('A principal is an object with a `kind`.');
|
|
44
|
+
}
|
|
45
|
+
const p = principal as { kind: string; job?: unknown };
|
|
46
|
+
if (p.kind === 'system' && (typeof p.job !== 'string' || p.job.trim() === '')) {
|
|
47
|
+
throw new TypeError('A system principal must name its job.');
|
|
48
|
+
}
|
|
49
|
+
}
|