@kitcms/core 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +200 -2
- package/bin/kitcms.js +10 -0
- package/dist/vite/index.d.ts +25 -0
- package/dist/vite/index.js +176 -0
- package/package.json +91 -3
- package/src/access/engine.ts +304 -0
- package/src/access/entitlements.ts +46 -0
- package/src/admin/form.ts +167 -0
- package/src/admin/panel.ts +93 -0
- package/src/admin/types.ts +202 -0
- package/src/api/cache.ts +315 -0
- package/src/api/local.ts +1034 -0
- package/src/api/populate.ts +70 -0
- package/src/api/types.ts +266 -0
- package/src/auth/better-auth.ts +133 -0
- package/src/auth/cookies.ts +37 -0
- package/src/auth/guard.ts +51 -0
- package/src/auth/module-admin.ts +119 -0
- package/src/auth/module.ts +61 -0
- package/src/auth/rate-limit.ts +105 -0
- package/src/auth/session.ts +28 -0
- package/src/auth/users.ts +280 -0
- package/src/cli/__fixtures__/app/src/kitcms.config.ts +10 -0
- package/src/cli/__fixtures__/app/wrangler.jsonc +5 -0
- package/src/cli/args.ts +124 -0
- package/src/cli/cli.tsconfig.json +6 -0
- package/src/cli/commands.ts +160 -0
- package/src/cli/generate-types.ts +157 -0
- package/src/cli/index.ts +1 -0
- package/src/cli/load-config.ts +47 -0
- package/src/cli/run.ts +61 -0
- package/src/cli/seed.ts +132 -0
- package/src/client.ts +18 -0
- package/src/config/collection.ts +411 -0
- package/src/config/fields.ts +371 -0
- package/src/config/hooks.ts +186 -0
- package/src/config/infer.ts +84 -0
- package/src/config/plugin.ts +183 -0
- package/src/config/sanitize.ts +1186 -0
- package/src/config/sanitized.ts +272 -0
- package/src/config/where.ts +78 -0
- package/src/db/adapter.ts +162 -0
- package/src/db/d1.ts +463 -0
- package/src/db/session.ts +39 -0
- package/src/db/where.ts +258 -0
- package/src/email/index.ts +147 -0
- package/src/errors.ts +97 -0
- package/src/fields/defaults.ts +117 -0
- package/src/fields/test-fixtures.ts +41 -0
- package/src/fields/traverse.ts +82 -0
- package/src/fields/validate.ts +264 -0
- package/src/hooks/run.ts +52 -0
- package/src/index.ts +49 -0
- package/src/order/key.ts +129 -0
- package/src/refs/extract.ts +31 -0
- package/src/richtext/html.ts +171 -0
- package/src/richtext/index.ts +3 -0
- package/src/richtext/valid.ts +37 -0
- package/src/rpc/index.ts +357 -0
- package/src/runtime.ts +63 -0
- package/src/schema/codegen.ts +66 -0
- package/src/schema/drizzle.ts +80 -0
- package/src/schema/spec.ts +99 -0
- package/src/schema/tables.ts +170 -0
- package/src/seed.ts +214 -0
- package/src/storage/adapter.ts +40 -0
- package/src/storage/r2.ts +51 -0
- package/src/sveltekit/admin.ts +714 -0
- package/src/sveltekit/api.ts +205 -0
- package/src/sveltekit/base.ts +28 -0
- package/src/sveltekit/index.ts +177 -0
- package/src/sveltekit/paths.ts +33 -0
- package/src/sveltekit/plugins.ts +180 -0
- package/src/sveltekit/rest.ts +263 -0
- package/src/ulid.ts +11 -0
- package/src/upload/handler.ts +125 -0
- package/src/upload/serve.ts +102 -0
- package/src/upload/sniff.ts +187 -0
- package/src/vite/index.ts +199 -0
- package/src/vite/tsconfig.build.json +10 -0
- package/src/vite/tsconfig.json +5 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kitcms contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,201 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @kitcms/core
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Config, field definitions, the Local API, access rules, hooks, D1 storage, R2 uploads, Better Auth, the SvelteKit integration, the Service Binding RPC entrypoint and the `kitcms` CLI. You define collections in code; kitcms creates the D1 schema from that code and serves them through `locals.cms` and the admin UI.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pnpm add @kitcms/core @kitcms/ui
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Pair it with `@sveltejs/kit` (v3), `@sveltejs/adapter-cloudflare`, `@sveltejs/vite-plugin-svelte`, `vite`, `wrangler` and `@cloudflare/vite-plugin`. `pnpm create kitcms@latest` sets all of this up.
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
Define the config (`src/kitcms.config.ts`, from `templates/blank`):
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { collection, defineConfig, fields as f } from '@kitcms/core';
|
|
17
|
+
|
|
18
|
+
export default defineConfig({
|
|
19
|
+
admin: { title: 'My site' },
|
|
20
|
+
collections: [
|
|
21
|
+
collection({
|
|
22
|
+
slug: 'media',
|
|
23
|
+
upload: { mimeTypes: ['image/*', 'application/pdf'] },
|
|
24
|
+
access: { read: () => true },
|
|
25
|
+
fields: { alt: f.text() },
|
|
26
|
+
}),
|
|
27
|
+
collection({
|
|
28
|
+
slug: 'pages',
|
|
29
|
+
admin: { useAsTitle: 'title', defaultColumns: ['title', 'slug', 'status', 'updatedAt'] },
|
|
30
|
+
access: {
|
|
31
|
+
// Published pages are public; signed-in users also see drafts.
|
|
32
|
+
read: ({ req }) => (req.user ? true : { status: { equals: 'published' } }),
|
|
33
|
+
},
|
|
34
|
+
fields: {
|
|
35
|
+
title: f.text({ required: true }),
|
|
36
|
+
slug: f.slug({ from: 'title', unique: true, admin: { position: 'sidebar' } }),
|
|
37
|
+
status: f.select({
|
|
38
|
+
options: ['draft', 'published'],
|
|
39
|
+
defaultValue: 'draft',
|
|
40
|
+
required: true,
|
|
41
|
+
admin: { position: 'sidebar' },
|
|
42
|
+
}),
|
|
43
|
+
body: f.textarea(),
|
|
44
|
+
},
|
|
45
|
+
}),
|
|
46
|
+
],
|
|
47
|
+
});
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Fields: `text`, `textarea`, `email`, `slug`, `number`, `checkbox`, `select`, `date`, `richText`, `json`, `relationship`, `upload`, `group`, `array`, `blocks`, plus the layout-only `row`, `collapsible` and `tabs`.
|
|
51
|
+
|
|
52
|
+
Register the config type and wire the Worker (`src/app.d.ts`, `src/hooks.server.ts`):
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
// src/app.d.ts
|
|
56
|
+
import type config from './kitcms.config';
|
|
57
|
+
|
|
58
|
+
declare module '@kitcms/core' {
|
|
59
|
+
interface Register {
|
|
60
|
+
config: typeof config;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
// src/hooks.server.ts
|
|
67
|
+
import { kitcms } from '@kitcms/core/sveltekit';
|
|
68
|
+
import config from './kitcms.config';
|
|
69
|
+
|
|
70
|
+
export const handle = kitcms({ config }).handle;
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
After that, `locals.cms` is typed and runs every read as the request's user:
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
// src/routes/+page.server.ts
|
|
77
|
+
import type { PageServerLoad } from './$types';
|
|
78
|
+
|
|
79
|
+
export const load: PageServerLoad = async ({ locals }) => {
|
|
80
|
+
const { docs } = await locals.cms.find('pages', { sort: '-updatedAt', limit: 20 });
|
|
81
|
+
return { pages: docs };
|
|
82
|
+
};
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Build with the Vite plugin and the Cloudflare adapter (`vite.config.ts`):
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
import { sveltekit } from '@sveltejs/kit/vite';
|
|
89
|
+
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
|
|
90
|
+
import { kitcms, kitcmsAdapter } from '@kitcms/core/vite';
|
|
91
|
+
import { defineConfig } from 'vite';
|
|
92
|
+
|
|
93
|
+
export default defineConfig({
|
|
94
|
+
plugins: [sveltekit({ preprocess: vitePreprocess(), adapter: kitcmsAdapter() }), kitcms()],
|
|
95
|
+
});
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The RPC entrypoint lives in `src/kitcms.rpc.ts`. It is only needed for headless consumers (see `@kitcms/client`):
|
|
99
|
+
|
|
100
|
+
```ts
|
|
101
|
+
import { createKitcmsRPC } from '@kitcms/core/rpc';
|
|
102
|
+
import config from './kitcms.config';
|
|
103
|
+
|
|
104
|
+
export class KitcmsRPC extends createKitcmsRPC(config) {}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## Drafts and versions
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
collection({ slug: 'pages', versions: { drafts: { autosave: true }, max: 20 }, fields: { /* ... */ } });
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
- The table holds the **published** state. Reads without `draft: true` only return published documents (also when populating relationships); `draft: true` needs a signed-in user or `overrideAccess`.
|
|
114
|
+
- `cms.update(..., { draft: true })` saves a draft version; `cms.update(...)` without it publishes the latest draft merged with `data`. `cms.unpublish(collection, id)` takes a document offline.
|
|
115
|
+
- `cms.findVersions`, `findVersionByID`, `restoreVersion` (and the `...Global...` variants) need read **and** update access to the document.
|
|
116
|
+
- `versions: true` keeps history only (no drafts, no `_status`).
|
|
117
|
+
|
|
118
|
+
## Admin branding
|
|
119
|
+
|
|
120
|
+
`admin.branding` white-labels the admin. Everything is optional and validated when the config loads:
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
admin: {
|
|
124
|
+
title: 'My site',
|
|
125
|
+
branding: {
|
|
126
|
+
logo: 'https://cdn.example.com/logo.svg', // https://, a /-relative path, or a base64 data:image/ URL
|
|
127
|
+
colors: { accent: '#0b7285', accentText: '#ffffff' }, // CSS colors: hex, rgb(), hsl(), oklch(), oklab() or a named color
|
|
128
|
+
},
|
|
129
|
+
},
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
- `colors.accent` and `colors.accentText` are set as the `--kc-accent` and `--kc-accent-text` CSS variables on the admin root. Set both or neither. Hover and focus states follow the accent. Without them the default theme is used, including dark mode.
|
|
133
|
+
- `logo` is shown in the admin header (next to the title) and above the sign-in and first-user forms. The title is always shown as text.
|
|
134
|
+
|
|
135
|
+
## REST API
|
|
136
|
+
|
|
137
|
+
A JSON fallback for browsers and third parties that can't use a Service Binding. On Cloudflare, prefer Service Binding RPC (`@kitcms/client`) (no public surface, no auth round trip). It is served by the generated `src/routes/(kitcms)/api/[...path]/+server.ts` (`export { GET, POST, PATCH, DELETE } from '@kitcms/core/sveltekit/api'`; re-run the scaffold or add `PATCH, DELETE` to existing apps).
|
|
138
|
+
|
|
139
|
+
| Route | Action |
|
|
140
|
+
|---|---|
|
|
141
|
+
| `GET /api/collections/:slug` | `find` (paginated) |
|
|
142
|
+
| `POST /api/collections/:slug` | `create` (201). Not for `upload` or auth collections (405) |
|
|
143
|
+
| `GET / PATCH / DELETE /api/collections/:slug/:id` | `findByID` (404 when missing) / `update` / `delete` |
|
|
144
|
+
| `POST /api/collections/:slug/:id/move` | body `{ "before": id }` or `{ "after": id }` (orderable collections) |
|
|
145
|
+
| `POST /api/collections/:slug/:id/unpublish` | take a published doc offline (drafts) |
|
|
146
|
+
| `GET / PATCH /api/globals/:slug` | `findGlobal` / `updateGlobal` |
|
|
147
|
+
|
|
148
|
+
Read params: `where` (JSON object, same syntax as the Local API), `sort` (`-createdAt`), `limit`, `page`, `depth` (0-2), `pagination=false`, `draft=true` (signed-in only). Numbers must be plain integers, or the response is `400`. Write params: `depth`, `draft=true` (save as draft). Bodies must be `application/json` (415), at most 1 MiB (413) and a JSON object (400).
|
|
149
|
+
|
|
150
|
+
Auth: the caller is the session user (Better Auth cookie) or anonymous. It goes through the same access rules, hooks and validation as the Local API, and nothing in the request can bypass them. Anonymous writes reach the pipeline and are denied by the default rules. Every `POST`/`PATCH`/`DELETE` also needs a same-origin `Origin` header (CSRF), or the response is `403`.
|
|
151
|
+
|
|
152
|
+
Errors are `{ "error": string, "code": string, "errors"?: FieldError[], "references"?: [...] }` with the kitcms status (validation 400, forbidden 403, not found 404, still referenced 409). Unexpected failures return `500 { "error": "Internal error" }`. Responses send `cache-control: no-store`.
|
|
153
|
+
|
|
154
|
+
Turn it off with `defineConfig({ rest: false })`: every `/api/collections/*` and `/api/globals/*` route then returns 404 (admin, upload and media routes are unaffected).
|
|
155
|
+
|
|
156
|
+
## Edge cache (optional)
|
|
157
|
+
|
|
158
|
+
`defineConfig({ cache: { ttl: 60 } })` caches anonymous published reads of the Local API (`find`, `findOne`, `findByID`, `count`, `findGlobal`) in the Workers Cache API, per data centre. This covers public pages, anonymous RPC and anonymous REST. Signed-in users, drafts, `overrideAccess` and calls that pass `req` or `context` are never cached.
|
|
159
|
+
|
|
160
|
+
Every write (from any caller) replaces a generation token, so the data centre that handled the write serves fresh content immediately. Other data centres keep their entries until `ttl` seconds pass. Keys include a fingerprint of your schema, so a deploy with a changed schema never reads old entries.
|
|
161
|
+
|
|
162
|
+
The Cache API does nothing on `*.workers.dev`; use a custom domain. If the cache is unavailable, reads fall back to D1.
|
|
163
|
+
|
|
164
|
+
## D1 read replication (optional)
|
|
165
|
+
|
|
166
|
+
kitcms already uses the D1 Sessions API on every request, so read replication works without code changes. Turn it on for your database in the Cloudflare dashboard (**D1 → your database → Settings → Read replication**).
|
|
167
|
+
|
|
168
|
+
- Anonymous requests (public pages, anonymous REST and RPC reads) read from the nearest replica.
|
|
169
|
+
- Signed-in users carry a bookmark in an `HttpOnly` cookie (`kitcms-d1`), so editors always see their own saves.
|
|
170
|
+
- RPC calls with `as: 'system'` start on the primary, since they may write and then read.
|
|
171
|
+
|
|
172
|
+
With replication off, every session reads from the primary, the same as before. Replication mainly helps visitors far from the primary when the edge cache misses. The templates also enable Smart Placement (`"placement": { "mode": "smart" }` in `wrangler.jsonc`), which can run the Worker near the database when that is faster.
|
|
173
|
+
|
|
174
|
+
## CLI
|
|
175
|
+
|
|
176
|
+
The `kitcms` bin (from `@kitcms/core`) runs these commands. Each one reads the config from `src/kitcms.config.ts` or `kitcms.config.ts`, or from `--config <path>`:
|
|
177
|
+
|
|
178
|
+
```
|
|
179
|
+
Usage: kitcms <command> [options]
|
|
180
|
+
|
|
181
|
+
Commands:
|
|
182
|
+
generate:schema Write drizzle/schema.ts from the kitcms config
|
|
183
|
+
generate:types [--out <path>] Write kitcms-types.d.ts (document types for @kitcms/client)
|
|
184
|
+
migrate:create <name> Generate schema, then create a SQL migration in ./migrations
|
|
185
|
+
migrate [--remote] Apply migrations with wrangler (local D1 by default)
|
|
186
|
+
migrate:status [--remote] List migrations with wrangler
|
|
187
|
+
info Show config, collections, bindings and migrations_dir check
|
|
188
|
+
|
|
189
|
+
Options:
|
|
190
|
+
--config <path> Path to the kitcms config (default: src/kitcms.config.ts or kitcms.config.ts)
|
|
191
|
+
--out <path> Output file for generate:types (default: kitcms-types.d.ts)
|
|
192
|
+
--remote Target the remote D1 database (migrate, migrate:status)
|
|
193
|
+
--help, -h Show this help
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
## Notes
|
|
197
|
+
|
|
198
|
+
- Workers Paid is required. Password hashing (scrypt) uses more CPU than the free plan allows.
|
|
199
|
+
- Don't set `declaration` in the app's tsconfig. With large configs `declaration: true` fails with TS7056.
|
|
200
|
+
|
|
201
|
+
Status: pre-release (0.x), Cloudflare Workers + D1 + R2 only.
|
package/bin/kitcms.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The package ships TypeScript sources (no build step), and Node does not strip types inside
|
|
3
|
+
// node_modules. Vite's module runner (already required to load the user's config) transpiles
|
|
4
|
+
// the CLI on the fly, so this works from node_modules with no extra dependency.
|
|
5
|
+
import { runnerImport } from 'vite';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
const entry = fileURLToPath(new URL('../src/cli/index.ts', import.meta.url));
|
|
9
|
+
const { module } = await runnerImport(entry, { root: process.cwd(), configFile: false, logLevel: 'error' });
|
|
10
|
+
process.exitCode = await module.run(process.argv.slice(2), process.cwd());
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import cloudflare from '@sveltejs/adapter-cloudflare';
|
|
2
|
+
import type { Adapter } from '@sveltejs/kit';
|
|
3
|
+
import type { PluginOption } from 'vite';
|
|
4
|
+
export declare const RPC_ENTRY_NAME = "kitcms-rpc";
|
|
5
|
+
export interface KitcmsViteOptions {
|
|
6
|
+
/** The RPC entry module (exports `KitcmsRPC`). Default `src/kitcms.rpc.ts`; `false` disables RPC. */
|
|
7
|
+
rpcEntry?: string | false;
|
|
8
|
+
/**
|
|
9
|
+
* Serve `KitcmsRPC` under `vite dev` through `@cloudflare/vite-plugin` (see the comment block at
|
|
10
|
+
* the top of this file). Default false. Requires the optional peer `@cloudflare/vite-plugin`.
|
|
11
|
+
*/
|
|
12
|
+
devRpc?: boolean;
|
|
13
|
+
/** Wrangler config used to derive the dev RPC worker config. Default: wrangler's own lookup. */
|
|
14
|
+
wranglerConfig?: string;
|
|
15
|
+
/** Worker name of the dev RPC worker. Default `<wrangler name>-rpc` (see the header comment). */
|
|
16
|
+
devRpcName?: string;
|
|
17
|
+
}
|
|
18
|
+
export declare function kitcms(options?: KitcmsViteOptions): PluginOption[];
|
|
19
|
+
type CloudflareAdapterOptions = NonNullable<Parameters<typeof cloudflare>[0]>;
|
|
20
|
+
/**
|
|
21
|
+
* adapter-cloudflare + the RPC facade. When the app has no RPC entry, it behaves exactly like
|
|
22
|
+
* adapter-cloudflare.
|
|
23
|
+
*/
|
|
24
|
+
export declare function kitcmsAdapter(options?: CloudflareAdapterOptions): Adapter;
|
|
25
|
+
export {};
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
// @kitcms/core/vite: build-time pieces (Node only, never imported by runtime code). Decision 14:
|
|
3
|
+
// the SvelteKit Worker also exports the `KitcmsRPC` entrypoint.
|
|
4
|
+
//
|
|
5
|
+
// // vite.config.ts
|
|
6
|
+
// import { sveltekit } from '@sveltejs/kit/vite';
|
|
7
|
+
// import { kitcms, kitcmsAdapter } from '@kitcms/core/vite';
|
|
8
|
+
// export default defineConfig({
|
|
9
|
+
// plugins: [sveltekit({ adapter: kitcmsAdapter() }), kitcms()],
|
|
10
|
+
// });
|
|
11
|
+
//
|
|
12
|
+
// 1. `kitcms()` adds `src/kitcms.rpc.ts` as an extra input of SvelteKit's `ssr` environment, so it
|
|
13
|
+
// is compiled by Vite (aliases, `.svelte` imports) and SHARES CHUNKS with the app: config, the
|
|
14
|
+
// CMS instance and caches are one module graph.
|
|
15
|
+
// 2. `kitcmsAdapter()` wraps adapter-cloudflare: it moves the generated worker to
|
|
16
|
+
// `_sveltekit_worker.js`, writes a facade at wrangler `main` that re-exports both the default
|
|
17
|
+
// handler and the RPC entrypoint, and keeps the moved file out of the static assets.
|
|
18
|
+
// Verified in Phase 0 locally and in production (§2.2).
|
|
19
|
+
//
|
|
20
|
+
// OPT-IN dev-time RPC (`kitcms({ devRpc: true })`, off by default, Decision 16):
|
|
21
|
+
// Under `vite dev` SvelteKit SSR runs in Node with adapter-cloudflare's platform proxy, so the
|
|
22
|
+
// `KitcmsRPC` entrypoint is NOT served and a consumer Worker cannot call it. With `devRpc` the
|
|
23
|
+
// plugin adds `@cloudflare/vite-plugin` (`apply: 'serve'`, after `sveltekit()`) running a tiny
|
|
24
|
+
// generated worker (`.svelte-kit/kitcms/dev-rpc-worker.ts`, re-exporting `KitcmsRPC` from your RPC
|
|
25
|
+
// entry) in a second workerd (`rpc` Vite environment) with HMR. The dev wrangler config is your
|
|
26
|
+
// own wrangler config with only `main` (and `assets`) overridden, so D1/R2 bindings are shared.
|
|
27
|
+
// Costs: +0.3-0.5 s dev start, one more workerd, and the site and RPC have SEPARATE module state
|
|
28
|
+
// in dev. `@cloudflare/vite-plugin` is an optional peer dependency: install it yourself, pinned
|
|
29
|
+
// with the same `wrangler` version where possible.
|
|
30
|
+
// Consumer setup (verified): the dev RPC worker registers as `<wrangler name>-rpc` (override with
|
|
31
|
+
// `devRpcName`), NOT under the app's own name: the app's platform proxy registers the app name
|
|
32
|
+
// without the entrypoint and wins, so the consumer then fails with "does not export an entrypoint
|
|
33
|
+
// named KitcmsRPC". So in dev the consumer binds `{ service: "<name>-rpc", entrypoint: "KitcmsRPC" }`.
|
|
34
|
+
// Registry skew: the plugin's miniflare registers in `.../cloudflare/dev-registry/v5`, wrangler
|
|
35
|
+
// 4.162 reads `.../.wrangler/registry`. Until versions align, start BOTH processes with the same
|
|
36
|
+
// `CLOUDFLARE_DEV_REGISTRY_PATH=<dir> WRANGLER_REGISTRY_PATH=<dir>`.
|
|
37
|
+
import fs from 'node:fs';
|
|
38
|
+
import path from 'node:path';
|
|
39
|
+
import cloudflare from '@sveltejs/adapter-cloudflare';
|
|
40
|
+
export const RPC_ENTRY_NAME = 'kitcms-rpc';
|
|
41
|
+
const DEFAULT_RPC_ENTRY = 'src/kitcms.rpc.ts';
|
|
42
|
+
export function kitcms(options = {}) {
|
|
43
|
+
const plugins = [rpcEntryPlugin(options)];
|
|
44
|
+
// Order matters: `@cloudflare/vite-plugin` must come AFTER `sveltekit()` (before it, its
|
|
45
|
+
// catch-all middleware swallows every route), and kitcms() is listed after sveltekit().
|
|
46
|
+
if (options.devRpc && options.rpcEntry !== false)
|
|
47
|
+
plugins.push(devRpcPlugins(options));
|
|
48
|
+
return plugins;
|
|
49
|
+
}
|
|
50
|
+
/** Loads `@cloudflare/vite-plugin` lazily (only when `devRpc` is on); Vite awaits promised plugins. */
|
|
51
|
+
async function devRpcPlugins(options) {
|
|
52
|
+
const entry = resolveEntry(options);
|
|
53
|
+
if (!entry) {
|
|
54
|
+
throw new Error(`kitcms: devRpc needs an RPC entry (${options.rpcEntry || DEFAULT_RPC_ENTRY})`);
|
|
55
|
+
}
|
|
56
|
+
let mod;
|
|
57
|
+
try {
|
|
58
|
+
mod = await import('@cloudflare/vite-plugin');
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
throw new Error('kitcms: `devRpc: true` needs the optional peer dependency `@cloudflare/vite-plugin` (pnpm add -D @cloudflare/vite-plugin).');
|
|
62
|
+
}
|
|
63
|
+
const dir = path.resolve('.svelte-kit', 'kitcms');
|
|
64
|
+
const worker = path.join(dir, 'dev-rpc-worker.ts');
|
|
65
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
66
|
+
const rel = path.relative(dir, entry).split(path.sep).join('/');
|
|
67
|
+
const source = `// Generated by @kitcms/core (devRpc). Do not edit.\n` +
|
|
68
|
+
`export { KitcmsRPC } from ${JSON.stringify(rel)};\n` +
|
|
69
|
+
`export default { fetch: () => new Response('kitcms dev RPC worker', { status: 404 }) };\n`;
|
|
70
|
+
if (!fs.existsSync(worker) || fs.readFileSync(worker, 'utf8') !== source) {
|
|
71
|
+
fs.writeFileSync(worker, source);
|
|
72
|
+
}
|
|
73
|
+
const plugins = mod.cloudflare({
|
|
74
|
+
configPath: options.wranglerConfig,
|
|
75
|
+
viteEnvironment: { name: 'rpc' },
|
|
76
|
+
config: (user) => ({
|
|
77
|
+
name: options.devRpcName ?? `${user.name}-rpc`,
|
|
78
|
+
main: worker,
|
|
79
|
+
assets: undefined,
|
|
80
|
+
}),
|
|
81
|
+
});
|
|
82
|
+
// Dev only: the production build keeps using kitcmsAdapter()'s facade.
|
|
83
|
+
return (Array.isArray(plugins) ? plugins : [plugins]).map((p) => ({ ...p, apply: 'serve' }));
|
|
84
|
+
}
|
|
85
|
+
const KITCMS_PACKAGES = [
|
|
86
|
+
'@kitcms/core',
|
|
87
|
+
'@kitcms/ui',
|
|
88
|
+
'@kitcms/client',
|
|
89
|
+
'@kitcms/plugin-seo',
|
|
90
|
+
'@kitcms/plugin-enquiries',
|
|
91
|
+
'@kitcms/plugin-entitlements',
|
|
92
|
+
];
|
|
93
|
+
function rpcEntryPlugin(options) {
|
|
94
|
+
let entry;
|
|
95
|
+
return {
|
|
96
|
+
name: 'kitcms:rpc-entry',
|
|
97
|
+
enforce: 'post',
|
|
98
|
+
// One copy of Kit and Svelte, even when @kitcms/* are linked from another checkout
|
|
99
|
+
// (`link:` / workspaces): a second @sveltejs/kit makes thrown `redirect()`/`error()`
|
|
100
|
+
// unrecognisable, so /admin answered 500 instead of redirecting.
|
|
101
|
+
// @kitcms/* ship TypeScript sources, so Vite must compile them as app source, as it already
|
|
102
|
+
// does for workspace links. Installed from npm they'd otherwise be pre-bundled (the Svelte
|
|
103
|
+
// optimizer parses `.svelte.ts` as plain JS, and the SSR optimizer splits core's entries into
|
|
104
|
+
// separate bundles with separate module state) or externalized (Node can't strip types
|
|
105
|
+
// under node_modules).
|
|
106
|
+
config: () => ({
|
|
107
|
+
resolve: { dedupe: ['@sveltejs/kit', 'svelte'] },
|
|
108
|
+
optimizeDeps: { exclude: KITCMS_PACKAGES },
|
|
109
|
+
ssr: { noExternal: [/^@kitcms\//], optimizeDeps: { exclude: KITCMS_PACKAGES } },
|
|
110
|
+
}),
|
|
111
|
+
configResolved(config) {
|
|
112
|
+
if (options.rpcEntry === false)
|
|
113
|
+
return;
|
|
114
|
+
const file = path.resolve(config.root, options.rpcEntry ?? DEFAULT_RPC_ENTRY);
|
|
115
|
+
if (fs.existsSync(file))
|
|
116
|
+
entry = file;
|
|
117
|
+
else if (options.rpcEntry)
|
|
118
|
+
throw new Error(`kitcms: RPC entry not found: ${file}`);
|
|
119
|
+
},
|
|
120
|
+
configEnvironment(name, config) {
|
|
121
|
+
if (name !== 'ssr' || !config.build?.rolldownOptions?.input)
|
|
122
|
+
return;
|
|
123
|
+
const input = config.build.rolldownOptions.input;
|
|
124
|
+
if (typeof input !== 'object' || Array.isArray(input)) {
|
|
125
|
+
throw new Error('kitcms: unexpected SvelteKit SSR input shape (SvelteKit changed?)');
|
|
126
|
+
}
|
|
127
|
+
// configEnvironment runs before configResolved, so resolve the default here too.
|
|
128
|
+
const file = entry ?? resolveEntry(options);
|
|
129
|
+
if (file)
|
|
130
|
+
input[RPC_ENTRY_NAME] = file;
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
function resolveEntry(options) {
|
|
135
|
+
if (options.rpcEntry === false)
|
|
136
|
+
return undefined;
|
|
137
|
+
const file = path.resolve(options.rpcEntry ?? DEFAULT_RPC_ENTRY);
|
|
138
|
+
return fs.existsSync(file) ? file : undefined;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* adapter-cloudflare + the RPC facade. When the app has no RPC entry, it behaves exactly like
|
|
142
|
+
* adapter-cloudflare.
|
|
143
|
+
*/
|
|
144
|
+
export function kitcmsAdapter(options = {}) {
|
|
145
|
+
// Keep the inner adapter's other hooks (`emulate` = the dev platform proxy, `supports`).
|
|
146
|
+
const inner = cloudflare(options);
|
|
147
|
+
return {
|
|
148
|
+
...inner,
|
|
149
|
+
name: 'kitcms-adapter-cloudflare',
|
|
150
|
+
async adapt(builder) {
|
|
151
|
+
await inner.adapt(builder);
|
|
152
|
+
const rpc = path.join(builder.getServerDirectory(), `${RPC_ENTRY_NAME}.js`);
|
|
153
|
+
if (!fs.existsSync(rpc))
|
|
154
|
+
return; // no RPC entry: plain adapter-cloudflare
|
|
155
|
+
const { unstable_readConfig } = (await import('wrangler'));
|
|
156
|
+
const main = unstable_readConfig({ config: options.config }).main;
|
|
157
|
+
if (!main)
|
|
158
|
+
throw new Error('kitcms: wrangler `main` is required to export KitcmsRPC');
|
|
159
|
+
const dir = path.dirname(main);
|
|
160
|
+
const moved = path.join(dir, '_sveltekit_worker.js');
|
|
161
|
+
fs.renameSync(main, moved);
|
|
162
|
+
const rel = (p) => {
|
|
163
|
+
const r = path.relative(dir, p).split(path.sep).join('/');
|
|
164
|
+
return r.startsWith('.') ? r : `./${r}`;
|
|
165
|
+
};
|
|
166
|
+
fs.writeFileSync(main, `export { default } from ${JSON.stringify(rel(moved))};\n` +
|
|
167
|
+
`export * from ${JSON.stringify(rel(rpc))};\n`);
|
|
168
|
+
// The worker dir may double as the assets dir: never upload the moved file as an asset.
|
|
169
|
+
const ignore = path.join(dir, '.assetsignore');
|
|
170
|
+
if (fs.existsSync(ignore))
|
|
171
|
+
fs.appendFileSync(ignore, '\n_sveltekit_worker.js\n');
|
|
172
|
+
else
|
|
173
|
+
fs.writeFileSync(ignore, '_sveltekit_worker.js\n');
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,94 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kitcms/core",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/Norden-Tenzin/kitcms.git",
|
|
8
|
+
"directory": "packages/core"
|
|
9
|
+
},
|
|
10
|
+
"homepage": "https://kitcms.dev",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/Norden-Tenzin/kitcms/issues"
|
|
13
|
+
},
|
|
14
|
+
"type": "module",
|
|
15
|
+
"sideEffects": false,
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./src/index.ts",
|
|
19
|
+
"default": "./src/index.ts"
|
|
20
|
+
},
|
|
21
|
+
"./sveltekit": {
|
|
22
|
+
"types": "./src/sveltekit/index.ts",
|
|
23
|
+
"default": "./src/sveltekit/index.ts"
|
|
24
|
+
},
|
|
25
|
+
"./rpc": {
|
|
26
|
+
"types": "./src/rpc/index.ts",
|
|
27
|
+
"default": "./src/rpc/index.ts"
|
|
28
|
+
},
|
|
29
|
+
"./sveltekit/admin": {
|
|
30
|
+
"types": "./src/sveltekit/admin.ts",
|
|
31
|
+
"default": "./src/sveltekit/admin.ts"
|
|
32
|
+
},
|
|
33
|
+
"./client": {
|
|
34
|
+
"types": "./src/client.ts",
|
|
35
|
+
"default": "./src/client.ts"
|
|
36
|
+
},
|
|
37
|
+
"./sveltekit/api": {
|
|
38
|
+
"types": "./src/sveltekit/api.ts",
|
|
39
|
+
"default": "./src/sveltekit/api.ts"
|
|
40
|
+
},
|
|
41
|
+
"./richtext": {
|
|
42
|
+
"types": "./src/richtext/index.ts",
|
|
43
|
+
"default": "./src/richtext/index.ts"
|
|
44
|
+
},
|
|
45
|
+
"./vite": {
|
|
46
|
+
"types": "./dist/vite/index.d.ts",
|
|
47
|
+
"default": "./dist/vite/index.js"
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
"bin": {
|
|
51
|
+
"kitcms": "./bin/kitcms.js"
|
|
52
|
+
},
|
|
53
|
+
"files": [
|
|
54
|
+
"src",
|
|
55
|
+
"bin",
|
|
56
|
+
"dist",
|
|
57
|
+
"!src/**/*.test.ts"
|
|
58
|
+
],
|
|
59
|
+
"peerDependencies": {
|
|
60
|
+
"@sveltejs/adapter-cloudflare": "^8",
|
|
61
|
+
"@sveltejs/kit": "^3",
|
|
62
|
+
"@sveltejs/vite-plugin-svelte": "^7",
|
|
63
|
+
"vite": "^8",
|
|
64
|
+
"wrangler": "^4",
|
|
65
|
+
"@cloudflare/vite-plugin": "^1.69.0"
|
|
66
|
+
},
|
|
67
|
+
"devDependencies": {
|
|
68
|
+
"@cloudflare/vite-plugin": "^1.69.1",
|
|
69
|
+
"@sveltejs/adapter-cloudflare": "^8.0.2",
|
|
70
|
+
"@sveltejs/kit": "^3.2.0",
|
|
71
|
+
"@sveltejs/vite-plugin-svelte": "^7.3.1",
|
|
72
|
+
"@types/node": "^26.6.6",
|
|
73
|
+
"miniflare": "5.20261113.0-beta",
|
|
74
|
+
"vite": "^8.3.8",
|
|
75
|
+
"wrangler": "^4.162.0"
|
|
76
|
+
},
|
|
77
|
+
"dependencies": {
|
|
78
|
+
"better-auth": "^1.7.25",
|
|
79
|
+
"drizzle-kit": "^0.31.11",
|
|
80
|
+
"drizzle-orm": "^0.45.4"
|
|
81
|
+
},
|
|
82
|
+
"peerDependenciesMeta": {
|
|
83
|
+
"wrangler": {
|
|
84
|
+
"optional": true
|
|
85
|
+
},
|
|
86
|
+
"@cloudflare/vite-plugin": {
|
|
87
|
+
"optional": true
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
"scripts": {
|
|
91
|
+
"typecheck": "tsc --noEmit && tsc -p test/tsconfig.json && tsc -p src/cli/cli.tsconfig.json && tsc -p src/vite/tsconfig.json",
|
|
92
|
+
"build:vite": "tsc -p src/vite/tsconfig.build.json"
|
|
93
|
+
}
|
|
6
94
|
}
|