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.
Files changed (46) hide show
  1. package/LICENSE +22 -0
  2. package/NOTICE +25 -0
  3. package/README.md +385 -2
  4. package/editor/editor-dark.css +2 -0
  5. package/editor/editor.css +9 -0
  6. package/editor/entry.js +28 -0
  7. package/migrations/0001_entries.sql +43 -0
  8. package/migrations/auth/0001_sessions.sql +50 -0
  9. package/migrations/koguma-upgrade.sql +13 -0
  10. package/package.json +86 -4
  11. package/scripts/build-admin-editor.ts +155 -0
  12. package/scripts/print-migration.ts +50 -0
  13. package/src/admin/app.ts +608 -0
  14. package/src/admin/assets.ts +52 -0
  15. package/src/admin/fields.ts +172 -0
  16. package/src/admin/forms.ts +64 -0
  17. package/src/admin/index.ts +16 -0
  18. package/src/admin/rules.ts +63 -0
  19. package/src/admin/types.ts +99 -0
  20. package/src/admin/views.ts +360 -0
  21. package/src/auth/handoff.ts +56 -0
  22. package/src/auth/index.ts +29 -0
  23. package/src/auth/password.ts +201 -0
  24. package/src/auth/principal.ts +40 -0
  25. package/src/auth/session.ts +143 -0
  26. package/src/core/access/ability.ts +86 -0
  27. package/src/core/access/can.ts +66 -0
  28. package/src/core/access/compile.ts +62 -0
  29. package/src/core/access/permits.ts +45 -0
  30. package/src/core/access/when.ts +59 -0
  31. package/src/core/access/where.ts +95 -0
  32. package/src/core/columns.ts +7 -0
  33. package/src/core/config/define.ts +206 -0
  34. package/src/core/config/field.ts +119 -0
  35. package/src/core/errors.ts +99 -0
  36. package/src/core/index.ts +44 -0
  37. package/src/core/media/index.ts +132 -0
  38. package/src/core/principal.ts +49 -0
  39. package/src/core/store/assets.ts +2 -0
  40. package/src/core/store/cms.ts +199 -0
  41. package/src/core/store/content.ts +453 -0
  42. package/src/core/store/sql.ts +239 -0
  43. package/src/core/store/types.ts +100 -0
  44. package/src/core/testing/index.ts +75 -0
  45. package/src/testing/db.ts +53 -0
  46. package/src/testing/index.ts +9 -0
package/package.json CHANGED
@@ -1,6 +1,88 @@
1
1
  {
2
2
  "name": "cogens",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "A light multi-tenant content store for Cloudflare Workers: every entry may have an owner and every query passes an access check. Forked from Koguma.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "author": "Vikram Rojo",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/vikramrojo/cogens.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/vikramrojo/cogens/issues"
14
+ },
15
+ "homepage": "https://github.com/vikramrojo/cogens#readme",
16
+ "keywords": [
17
+ "cms",
18
+ "cloudflare",
19
+ "workers",
20
+ "d1",
21
+ "hono",
22
+ "multi-tenant",
23
+ "access-control",
24
+ "casl",
25
+ "content-store"
26
+ ],
27
+ "engines": {
28
+ "bun": ">=1.4.4"
29
+ },
30
+ "packageManager": "bun@1.4.4",
31
+ "exports": {
32
+ ".": "./src/core/index.ts",
33
+ "./admin": "./src/admin/index.ts",
34
+ "./auth": "./src/auth/index.ts",
35
+ "./testing": "./src/testing/index.ts",
36
+ "./migrations-tool": "./scripts/print-migration.ts",
37
+ "./scripts/*": "./scripts/*",
38
+ "./package.json": "./package.json",
39
+ "./migrations/*": "./migrations/*"
40
+ },
41
+ "bin": {
42
+ "cogens-print-migration": "./scripts/print-migration.ts"
43
+ },
44
+ "files": [
45
+ "src",
46
+ "migrations",
47
+ "scripts",
48
+ "editor",
49
+ "LICENSE",
50
+ "NOTICE",
51
+ "README.md"
52
+ ],
53
+ "scripts": {
54
+ "test": "bun test",
55
+ "typecheck": "tsc --noEmit -p tsconfig.json && tsc --noEmit -p tsconfig.scripts.json",
56
+ "print-migration": "bun run scripts/print-migration.ts",
57
+ "build:editor": "bun run scripts/build-admin-editor.ts",
58
+ "example:migrate": "wrangler d1 migrations apply DB --local -c examples/worker/wrangler.jsonc",
59
+ "example:dev": "wrangler dev -c examples/worker/wrangler.jsonc"
60
+ },
61
+ "dependencies": {
62
+ "@casl/ability": "7.1.3",
63
+ "@cfworker/json-schema": "^4.1.1",
64
+ "hono": "~4.12.2"
65
+ },
66
+ "peerDependencies": {
67
+ "@milkdown/crepe": "^7.23.0",
68
+ "miniflare": "^4.20260301.1"
69
+ },
70
+ "peerDependenciesMeta": {
71
+ "miniflare": {
72
+ "optional": true
73
+ },
74
+ "@milkdown/crepe": {
75
+ "optional": true
76
+ }
77
+ },
78
+ "devDependencies": {
79
+ "@cloudflare/workers-types": "^4.20260304.0",
80
+ "@milkdown/crepe": "^7.23.0",
81
+ "@types/bun": "^1.3.0",
82
+ "@types/node": "^22.0.0",
83
+ "miniflare": "^4.20260301.1",
84
+ "remark-directive": "^4.0.0",
85
+ "typescript": "^5.7.0",
86
+ "wrangler": "^4.71.0"
87
+ }
88
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Builds the admin's markdown editor (Milkdown Crepe, as one static module) and
3
+ * writes it where the host serves its static files:
4
+ *
5
+ * bun run node_modules/cogens/scripts/build-admin-editor.ts <outDir> [--plugins <module>]
6
+ *
7
+ * writes <outDir>/admin-editor.js, admin-editor.css, admin-editor-dark.css and
8
+ * admin-editor.LICENSES.txt (the licence texts of every package in the bundle,
9
+ * which the module's banner names). Those are the names `createAdmin` links by
10
+ * default (`DEFAULT_ASSETS`), at the root of the host's static folder; serve
11
+ * them elsewhere and pass `assets` to `createAdmin`.
12
+ *
13
+ * `--plugins <module>` names a host file whose default export is a function
14
+ * `(builder, context) => void | Promise<void>`. The bundle calls it with the
15
+ * Crepe builder (`builder.editor` is the Milkdown editor) and `context = { type, field }`
16
+ * (the content type id and field name of the text area) before the editor is
17
+ * created, and the path resolves from the current working directory, so the host can add remark plugins, nodes and node views. The
18
+ * module imports its own Milkdown packages from the host's node_modules.
19
+ * Without it the editor has no syntax of the host's.
20
+ *
21
+ * The build needs `@milkdown/crepe`, an optional peer dependency of cogens:
22
+ * add it to the host (`bun add -d @milkdown/crepe`). Nothing in the Worker
23
+ * imports the editor or Crepe.
24
+ */
25
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
26
+ import { tmpdir } from 'node:os';
27
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
28
+
29
+ const HERE = join(import.meta.dir, '..', 'editor');
30
+
31
+ /** The package folder an input path belongs to: the part up to the last `node_modules/<name>` (or `<@scope/name>`). */
32
+ function packageRoot(input: string): string | null {
33
+ const marker = 'node_modules/';
34
+ const at = input.lastIndexOf(marker);
35
+ if (at < 0) return null;
36
+ const rest = input.slice(at + marker.length).split('/');
37
+ const name = rest[0]!.startsWith('@') ? `${rest[0]}/${rest[1]}` : rest[0]!;
38
+ return input.slice(0, at + marker.length) + name;
39
+ }
40
+
41
+ const PLUGIN_MODULE = 'cogens-editor-plugin';
42
+
43
+ /** Resolves the entry's `cogens-editor-plugin` import to the host's module, or to an empty one. */
44
+ function pluginResolver(plugin: string | null): Bun.BunPlugin {
45
+ return {
46
+ name: 'cogens-editor-plugin',
47
+ setup(build) {
48
+ build.onResolve({ filter: /^cogens-editor-plugin$/ }, () =>
49
+ plugin ? { path: plugin } : { path: PLUGIN_MODULE, namespace: 'cogens-empty' });
50
+ build.onLoad({ filter: /.*/, namespace: 'cogens-empty' }, () => ({ contents: 'export default undefined;', loader: 'js' }));
51
+ }
52
+ };
53
+ }
54
+
55
+ type Notice = { name: string; version: string; license: string; text: string };
56
+
57
+ async function notices(entries: string[], out: string, plugin: string | null): Promise<void> {
58
+ const roots = new Set<string>();
59
+ for (const entry of entries) {
60
+ const result = await Bun.build({ entrypoints: [entry], target: 'browser', minify: true, metafile: true, plugins: [pluginResolver(plugin)] });
61
+ if (!result.success || !result.metafile) throw new Error(`Could not bundle ${entry}: ${result.logs.join('\n')}`);
62
+ for (const input of Object.keys(result.metafile.inputs)) {
63
+ const root = packageRoot(isAbsolute(input) ? input : resolve(process.cwd(), input));
64
+ if (root) roots.add(root);
65
+ }
66
+ }
67
+ const list: Notice[] = [];
68
+ for (const dir of roots) {
69
+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { name: string; version: string; license?: string };
70
+ if (pkg.name === 'cogens') continue; // this package's own editor files, under the host's node_modules
71
+ const file = readdirSync(dir).find(f => /^(licen[sc]e|copying)(\.|$)/i.test(f));
72
+ if (!file) throw new Error(`${pkg.name} ${pkg.version} has no licence file in ${dir}; add its text here by hand before shipping.`);
73
+ list.push({ name: pkg.name, version: pkg.version, license: pkg.license ?? 'see text', text: readFileSync(join(dir, file), 'utf8').trim() });
74
+ }
75
+ list.sort((a, b) => a.name.localeCompare(b.name));
76
+ const header = [
77
+ 'Third-party notices for admin-editor.js, admin-editor.css and admin-editor-dark.css',
78
+ "(cogens's admin markdown editor, Milkdown Crepe and the packages it bundles).",
79
+ `${list.length} packages. Written by scripts/build-admin-editor.ts; do not edit by hand.`,
80
+ 'DOMPurify is dual-licensed MPL-2.0 or Apache-2.0 and is used here under Apache-2.0.'
81
+ ].join('\n');
82
+ const body = list.map(n => `${'='.repeat(78)}\n${n.name} ${n.version} (${n.license})\n${'='.repeat(78)}\n\n${n.text}\n`).join('\n');
83
+ writeFileSync(out, `${header}\n\n${body}`);
84
+ console.log(`${out}: ${list.length} packages`);
85
+ }
86
+
87
+ async function build(entry: string, outDir: string, name: string, options: Record<string, unknown>): Promise<void> {
88
+ const result = await Bun.build({ entrypoints: [entry], outdir: outDir, naming: name, minify: true, ...options });
89
+ if (!result.success) throw new Error(`Could not build ${name}:\n${result.logs.join('\n')}`);
90
+ }
91
+
92
+ /**
93
+ * The folder of `@milkdown/crepe` as the host installed it. Its style sheets are not in the package's `exports`, so a
94
+ * bare `@import` cannot name them; editor.css and editor-dark.css write `%CREPE%` and this puts the real folder there.
95
+ */
96
+ function crepeFolder(): string {
97
+ let dir = dirname(Bun.resolveSync('@milkdown/crepe', HERE));
98
+ while (!existsSync(join(dir, 'package.json')) || JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).name !== '@milkdown/crepe') {
99
+ const up = dirname(dir);
100
+ if (up === dir) throw new Error('@milkdown/crepe is not installed. Add it: bun add -d @milkdown/crepe');
101
+ dir = up;
102
+ }
103
+ return dir;
104
+ }
105
+
106
+ /** A copy of one of the editor's style sheets with `%CREPE%` filled in, in a folder the caller removes. */
107
+ function stylesheet(name: string, scratch: string): string {
108
+ const out = join(scratch, name);
109
+ writeFileSync(out, readFileSync(join(HERE, name), 'utf8').replaceAll('%CREPE%', crepeFolder()));
110
+ return out;
111
+ }
112
+
113
+ const args = process.argv.slice(2);
114
+ const flag = args.indexOf('--plugins');
115
+ let pluginArg: string | null = null;
116
+ if (flag >= 0) {
117
+ pluginArg = args[flag + 1] ?? null;
118
+ if (!pluginArg) {
119
+ console.error('--plugins needs a module path.');
120
+ process.exit(1);
121
+ }
122
+ args.splice(flag, 2);
123
+ }
124
+ const outArg = args[0];
125
+ if (!outArg) {
126
+ console.error('Usage: bun run scripts/build-admin-editor.ts <outDir> [--plugins <module>]');
127
+ process.exit(1);
128
+ }
129
+ const plugin = pluginArg ? resolve(process.cwd(), pluginArg) : null;
130
+ if (plugin && !existsSync(plugin)) {
131
+ console.error(`Plugin module not found: ${plugin}`);
132
+ process.exit(1);
133
+ }
134
+ const out = resolve(process.cwd(), outArg);
135
+ mkdirSync(out, { recursive: true });
136
+
137
+ await build(join(HERE, 'entry.js'), out, 'admin-editor.js', {
138
+ format: 'esm',
139
+ target: 'browser',
140
+ banner: '/*! Third-party notices: /admin-editor.LICENSES.txt */',
141
+ plugins: [pluginResolver(plugin)]
142
+ });
143
+ const scratch = mkdtempSync(join(tmpdir(), 'cogens-editor-'));
144
+ try {
145
+ const light = stylesheet('editor.css', scratch);
146
+ const dark = stylesheet('editor-dark.css', scratch);
147
+ await build(light, out, 'admin-editor.css', {});
148
+ await build(dark, out, 'admin-editor-dark.css', {});
149
+ await notices([join(HERE, 'entry.js'), light, dark], join(out, 'admin-editor.LICENSES.txt'), plugin);
150
+ } finally {
151
+ rmSync(scratch, { recursive: true, force: true });
152
+ }
153
+ for (const f of ['admin-editor.js', 'admin-editor.css', 'admin-editor-dark.css', 'admin-editor.LICENSES.txt']) {
154
+ if (!existsSync(join(out, f))) throw new Error(`${f} was not written.`);
155
+ }
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Prints the SQL a config's content types need in `entries`: a virtual generated
4
+ * column and an index for each indexed field, and a unique index on the slug for
5
+ * the types that ask for one. The host's own migration holds these lines and startup checks the columns exist.
6
+ *
7
+ * bunx cogens-print-migration site.config.ts
8
+ * bun run node_modules/cogens/scripts/print-migration.ts site.config.ts
9
+ *
10
+ * The config file's default export is `{ contentTypes }` (what `defineConfig` returns).
11
+ */
12
+ import type { ContentType } from '../src/core/config/define.ts';
13
+ import { indexedColumn } from '../src/core/columns.ts';
14
+
15
+ /** `ALTER TABLE ... ADD COLUMN` allows only VIRTUAL generated columns; SQLite can index them. */
16
+ export function migrationLines(types: readonly ContentType<any>[]): string[] {
17
+ const lines: string[] = [];
18
+ const done = new Set<string>();
19
+ for (const type of types) {
20
+ if (type.service) continue;
21
+ for (const field of type.indexed) {
22
+ const column = indexedColumn(field);
23
+ if (done.has(column)) continue;
24
+ done.add(column);
25
+ lines.push(`ALTER TABLE entries ADD COLUMN ${column} GENERATED ALWAYS AS (json_extract(data, '$.${field}')) VIRTUAL;`);
26
+ lines.push(`CREATE INDEX IF NOT EXISTS idx_entries_${column} ON entries(content_type, ${column});`);
27
+ }
28
+ }
29
+ const unique = types.filter(t => !t.service && t.uniqueSlug).map(t => `'${t.id}'`);
30
+ if (unique.length > 0) {
31
+ lines.push(
32
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_entries_unique_slug ON entries(content_type, slug) WHERE slug IS NOT NULL AND content_type IN (${unique.join(', ')});`
33
+ );
34
+ }
35
+ return lines;
36
+ }
37
+
38
+ // Run under Bun; the declarations keep this file free of Node's types, which a Worker build does not have.
39
+ declare const process: { argv: string[]; cwd(): string; exit(code: number): never };
40
+
41
+ if ((import.meta as { main?: boolean }).main) {
42
+ const path = process.argv[2];
43
+ if (!path) {
44
+ console.error('Usage: bunx cogens-print-migration <config file>');
45
+ process.exit(1);
46
+ }
47
+ const module = await import(new URL(path, `file://${process.cwd()}/`).href);
48
+ const config = module.default as { contentTypes: ContentType<any>[] };
49
+ console.log(migrationLines(config.contentTypes).join('\n'));
50
+ }