@kidecms/core 0.33.0 → 0.34.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.
@@ -30,14 +30,8 @@ import { toggleHeading } from "../lib/editor-commands";
30
30
  import { openPreviewChannel } from "../lib/preview-channel";
31
31
  import SharedSectionEditSheet from "./SharedSectionEditSheet";
32
32
  import { useSharedSection } from "../lib/use-shared-section";
33
- import {
34
- LinkDialog,
35
- fetchLinkGroups,
36
- cmsNodeToTiptap,
37
- tiptapNodeToCms,
38
- type CmsNode,
39
- type LinkGroup,
40
- } from "./RichTextEditor";
33
+ import { LinkDialog, fetchLinkGroups, type LinkGroup } from "./RichTextEditor";
34
+ import { cmsNodeToTiptap, tiptapNodeToCms, starterKitOptions, type CmsNode } from "./richtext-tiptap";
41
35
  import { SubField, humanize, type BlockTypesMeta, type SubFieldMeta } from "./block-fields";
42
36
  import type { LinkableCollection } from "./InternalLinkPicker";
43
37
  import { blockNodeSpec, BLOCK_NODE_NAME, SHARED_BLOCK_TYPE, type BlockNodeOptions } from "./content-block-spec";
@@ -495,8 +489,7 @@ export default function ContentEditor({
495
489
  setBaseline(JSON.stringify(tiptapToContent(editor.getJSON())));
496
490
  },
497
491
  extensions: [
498
- // StarterKit bundles its own Link; disabled so the configured one below is the only registration.
499
- StarterKit.configure({ link: false }),
492
+ StarterKit.configure(starterKitOptions),
500
493
  EditorImage,
501
494
  Link.configure({
502
495
  openOnClick: false,
@@ -29,135 +29,7 @@ import { cn } from "../lib/utils";
29
29
  import { toggleHeading } from "../lib/editor-commands";
30
30
  import { openPreviewChannel } from "../lib/preview-channel";
31
31
  import ImageBrowseDialog from "./ImageBrowseDialog";
32
-
33
- // -----------------------------------------------
34
- // CMS AST ↔ Tiptap JSON conversion
35
- // -----------------------------------------------
36
-
37
- export type CmsNode = {
38
- type: string;
39
- value?: string;
40
- level?: number;
41
- ordered?: boolean;
42
- bold?: boolean;
43
- italic?: boolean;
44
- children?: CmsNode[];
45
- [key: string]: unknown;
46
- };
47
-
48
- export type CmsDocument = {
49
- type: "root";
50
- children: CmsNode[];
51
- };
52
-
53
- export const cmsNodeToTiptap = (node: CmsNode): any => {
54
- if (node.type === "text") {
55
- const marks: any[] = [];
56
- if (node.bold) marks.push({ type: "bold" });
57
- if (node.italic) marks.push({ type: "italic" });
58
- if (node.href) marks.push({ type: "link", attrs: { href: node.href, target: node.target ?? null } });
59
- return { type: "text", text: node.value ?? "", ...(marks.length > 0 ? { marks } : {}) };
60
- }
61
- if (node.type === "paragraph") {
62
- const content = (node.children ?? []).map(cmsNodeToTiptap).filter(Boolean);
63
- return { type: "paragraph", ...(content.length > 0 ? { content } : {}) };
64
- }
65
- if (node.type === "heading") {
66
- const content = (node.children ?? []).map(cmsNodeToTiptap).filter(Boolean);
67
- return {
68
- type: "heading",
69
- attrs: { level: node.level ?? 2 },
70
- ...(content.length > 0 ? { content } : {}),
71
- };
72
- }
73
- if (node.type === "list") {
74
- const content = (node.children ?? []).map(cmsNodeToTiptap).filter(Boolean);
75
- return {
76
- type: node.ordered ? "orderedList" : "bulletList",
77
- ...(content.length > 0 ? { content } : {}),
78
- };
79
- }
80
- if (node.type === "list-item") {
81
- const content = (node.children ?? []).map(cmsNodeToTiptap).filter(Boolean);
82
- // Tiptap expects list items to contain paragraphs
83
- const wrapped = content.map((c: any) => (c.type === "paragraph" ? c : { type: "paragraph", content: [c] }));
84
- return { type: "listItem", ...(wrapped.length > 0 ? { content: wrapped } : {}) };
85
- }
86
- if (node.type === "quote") {
87
- const content = (node.children ?? []).map(cmsNodeToTiptap).filter(Boolean);
88
- return { type: "blockquote", ...(content.length > 0 ? { content } : {}) };
89
- }
90
- if (node.type === "image") {
91
- return { type: "image", attrs: { src: node.src ?? "", alt: node.alt ?? "", title: node.title ?? "" } };
92
- }
93
- return null;
94
- };
95
-
96
- const cmsToTiptap = (doc: CmsDocument | null | undefined): any => {
97
- if (!doc || doc.type !== "root") {
98
- return { type: "doc", content: [{ type: "paragraph" }] };
99
- }
100
- const content = doc.children.map(cmsNodeToTiptap).filter(Boolean);
101
- return { type: "doc", content: content.length > 0 ? content : [{ type: "paragraph" }] };
102
- };
103
-
104
- export const tiptapNodeToCms = (node: any): CmsNode | null => {
105
- if (node.type === "text") {
106
- const result: CmsNode = { type: "text", value: node.text ?? "" };
107
- if (node.marks) {
108
- for (const mark of node.marks) {
109
- if (mark.type === "bold") result.bold = true;
110
- if (mark.type === "italic") result.italic = true;
111
- if (mark.type === "link") {
112
- result.href = mark.attrs?.href ?? "";
113
- if (mark.attrs?.target) result.target = mark.attrs.target;
114
- }
115
- }
116
- }
117
- return result;
118
- }
119
- if (node.type === "paragraph") {
120
- return {
121
- type: "paragraph",
122
- children: (node.content ?? []).map(tiptapNodeToCms).filter(Boolean),
123
- };
124
- }
125
- if (node.type === "heading") {
126
- return {
127
- type: "heading",
128
- level: node.attrs?.level ?? 2,
129
- children: (node.content ?? []).map(tiptapNodeToCms).filter(Boolean),
130
- };
131
- }
132
- if (node.type === "bulletList" || node.type === "orderedList") {
133
- return {
134
- type: "list",
135
- ordered: node.type === "orderedList",
136
- children: (node.content ?? []).map(tiptapNodeToCms).filter(Boolean),
137
- };
138
- }
139
- if (node.type === "listItem") {
140
- return {
141
- type: "list-item",
142
- children: (node.content ?? []).map(tiptapNodeToCms).filter(Boolean),
143
- };
144
- }
145
- if (node.type === "blockquote") {
146
- return {
147
- type: "quote",
148
- children: (node.content ?? []).map(tiptapNodeToCms).filter(Boolean),
149
- };
150
- }
151
- if (node.type === "image") {
152
- return { type: "image", src: node.attrs?.src ?? "", alt: node.attrs?.alt ?? "", title: node.attrs?.title ?? "" };
153
- }
154
- return null;
155
- };
156
-
157
- const tiptapToCms = (json: any): CmsDocument => ({
158
- type: "root",
159
- children: (json.content ?? []).map(tiptapNodeToCms).filter(Boolean),
160
- });
32
+ import { starterKitOptions, cmsToTiptap, tiptapToCms } from "./richtext-tiptap";
161
33
 
162
34
  // -----------------------------------------------
163
35
  // Toolbar button
@@ -458,8 +330,7 @@ export default function RichTextEditor({ name, initialValue, rows = 10, onChange
458
330
  setBaseline(JSON.stringify(tiptapToCms(editor.getJSON())));
459
331
  },
460
332
  extensions: [
461
- // StarterKit bundles its own Link; disabled so the configured one below is the only registration.
462
- StarterKit.configure({ link: false }),
333
+ StarterKit.configure(starterKitOptions),
463
334
  EditorImage,
464
335
  Markdown,
465
336
  Link.configure({
@@ -0,0 +1,164 @@
1
+ import type { StarterKitOptions } from "@tiptap/starter-kit";
2
+
3
+ // Link is configured separately by each editor. The rest have no CMS AST equivalent and would vanish on save.
4
+ export const starterKitOptions: Partial<StarterKitOptions> = {
5
+ link: false,
6
+ strike: false,
7
+ code: false,
8
+ underline: false,
9
+ codeBlock: false,
10
+ horizontalRule: false,
11
+ };
12
+
13
+ export type CmsNode = {
14
+ type: string;
15
+ value?: string;
16
+ level?: number;
17
+ ordered?: boolean;
18
+ bold?: boolean;
19
+ italic?: boolean;
20
+ children?: CmsNode[];
21
+ [key: string]: unknown;
22
+ };
23
+
24
+ export type CmsDocument = {
25
+ type: "root";
26
+ children: CmsNode[];
27
+ };
28
+
29
+ export const cmsNodeToTiptap = (node: CmsNode): any => {
30
+ if (node.type === "text") {
31
+ const marks: any[] = [];
32
+ if (node.bold) marks.push({ type: "bold" });
33
+ if (node.italic) marks.push({ type: "italic" });
34
+ if (node.href) marks.push({ type: "link", attrs: { href: node.href, target: node.target ?? null } });
35
+ return { type: "text", text: node.value ?? "", ...(marks.length > 0 ? { marks } : {}) };
36
+ }
37
+ if (node.type === "paragraph") {
38
+ const content = cmsChildrenToTiptap(node.children);
39
+ return { type: "paragraph", ...(content.length > 0 ? { content } : {}) };
40
+ }
41
+ if (node.type === "heading") {
42
+ const content = cmsChildrenToTiptap(node.children);
43
+ return {
44
+ type: "heading",
45
+ attrs: { level: node.level ?? 2 },
46
+ ...(content.length > 0 ? { content } : {}),
47
+ };
48
+ }
49
+ if (node.type === "list") {
50
+ const content = cmsChildrenToTiptap(node.children);
51
+ return {
52
+ type: node.ordered ? "orderedList" : "bulletList",
53
+ ...(content.length > 0 ? { content } : {}),
54
+ };
55
+ }
56
+ if (node.type === "list-item") {
57
+ const content = cmsChildrenToTiptap(node.children);
58
+ // Tiptap expects list items to contain paragraphs; consecutive inline nodes share one.
59
+ const wrapped: any[] = [];
60
+ let inline: any = null;
61
+ for (const c of content) {
62
+ if (c.type === "paragraph") {
63
+ wrapped.push(c);
64
+ inline = null;
65
+ } else if (inline) {
66
+ inline.content.push(c);
67
+ } else {
68
+ inline = { type: "paragraph", content: [c] };
69
+ wrapped.push(inline);
70
+ }
71
+ }
72
+ return { type: "listItem", ...(wrapped.length > 0 ? { content: wrapped } : {}) };
73
+ }
74
+ if (node.type === "quote") {
75
+ const content = cmsChildrenToTiptap(node.children);
76
+ return { type: "blockquote", ...(content.length > 0 ? { content } : {}) };
77
+ }
78
+ if (node.type === "image") {
79
+ return { type: "image", attrs: { src: node.src ?? "", alt: node.alt ?? "", title: node.title ?? "" } };
80
+ }
81
+ return null;
82
+ };
83
+
84
+ // Line breaks are stored as "\n" inside text values; Tiptap needs hardBreak nodes.
85
+ const cmsChildrenToTiptap = (children: CmsNode[] = []): any[] =>
86
+ children
87
+ .flatMap((child) => {
88
+ const value = String(child.value ?? "");
89
+ if (child.type !== "text" || !value.includes("\n")) return [cmsNodeToTiptap(child)];
90
+ return value
91
+ .split("\n")
92
+ .flatMap((line, i) => [
93
+ ...(i > 0 ? [{ type: "hardBreak" }] : []),
94
+ ...(line ? [cmsNodeToTiptap({ ...child, value: line })] : []),
95
+ ]);
96
+ })
97
+ .filter(Boolean);
98
+
99
+ export const cmsToTiptap = (doc: CmsDocument | null | undefined): any => {
100
+ if (!doc || doc.type !== "root") {
101
+ return { type: "doc", content: [{ type: "paragraph" }] };
102
+ }
103
+ const content = doc.children.map(cmsNodeToTiptap).filter(Boolean);
104
+ return { type: "doc", content: content.length > 0 ? content : [{ type: "paragraph" }] };
105
+ };
106
+
107
+ export const tiptapNodeToCms = (node: any): CmsNode | null => {
108
+ if (node.type === "text") {
109
+ const result: CmsNode = { type: "text", value: node.text ?? "" };
110
+ if (node.marks) {
111
+ for (const mark of node.marks) {
112
+ if (mark.type === "bold") result.bold = true;
113
+ if (mark.type === "italic") result.italic = true;
114
+ if (mark.type === "link") {
115
+ result.href = mark.attrs?.href ?? "";
116
+ if (mark.attrs?.target) result.target = mark.attrs.target;
117
+ }
118
+ }
119
+ }
120
+ return result;
121
+ }
122
+ if (node.type === "hardBreak") return { type: "text", value: "\n" };
123
+ if (node.type === "paragraph") {
124
+ return {
125
+ type: "paragraph",
126
+ children: (node.content ?? []).map(tiptapNodeToCms).filter(Boolean),
127
+ };
128
+ }
129
+ if (node.type === "heading") {
130
+ return {
131
+ type: "heading",
132
+ level: node.attrs?.level ?? 2,
133
+ children: (node.content ?? []).map(tiptapNodeToCms).filter(Boolean),
134
+ };
135
+ }
136
+ if (node.type === "bulletList" || node.type === "orderedList") {
137
+ return {
138
+ type: "list",
139
+ ordered: node.type === "orderedList",
140
+ children: (node.content ?? []).map(tiptapNodeToCms).filter(Boolean),
141
+ };
142
+ }
143
+ if (node.type === "listItem") {
144
+ return {
145
+ type: "list-item",
146
+ children: (node.content ?? []).map(tiptapNodeToCms).filter(Boolean),
147
+ };
148
+ }
149
+ if (node.type === "blockquote") {
150
+ return {
151
+ type: "quote",
152
+ children: (node.content ?? []).map(tiptapNodeToCms).filter(Boolean),
153
+ };
154
+ }
155
+ if (node.type === "image") {
156
+ return { type: "image", src: node.attrs?.src ?? "", alt: node.attrs?.alt ?? "", title: node.attrs?.title ?? "" };
157
+ }
158
+ return null;
159
+ };
160
+
161
+ export const tiptapToCms = (json: any): CmsDocument => ({
162
+ type: "root",
163
+ children: (json.content ?? []).map(tiptapNodeToCms).filter(Boolean),
164
+ });
package/core/image.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ImagePreset } from "./define";
2
+ import { getStorage } from "./runtime";
2
3
 
3
4
  const ALLOWED_WIDTHS = [320, 480, 640, 768, 960, 1024, 1280, 1536, 1920];
4
5
  const ALLOWED_FORMATS = ["webp", "avif", "jpeg", "png"] as const;
@@ -175,18 +176,17 @@ export async function transformImage(
175
176
  const sharpModule = "sharp";
176
177
  const sharp = (await import(/* @vite-ignore */ sharpModule)).default;
177
178
 
178
- // Must match the storage adapter: the source lives wherever uploads are written.
179
- const uploadsDir = process.env.CMS_UPLOADS_DIR
180
- ? path.resolve(process.env.CMS_UPLOADS_DIR)
181
- : path.join(process.cwd(), "public", "uploads");
179
+ // Read through the storage adapter so the source can live on disk or in an object store.
180
+ // The adapter rejects traversal by throwing; that's the same miss as an absent file.
181
+ let source: ArrayBuffer | null;
182
+ try {
183
+ source = await getStorage().getFile(src);
184
+ } catch {
185
+ source = null;
186
+ }
187
+ if (!source) return null;
182
188
  const cacheDir = path.join(process.cwd(), ".cms-cache", "img");
183
189
 
184
- // Resolve the source safely under uploadsDir, rejecting traversal.
185
- const rel = src.replace(/^\/+/, "").replace(/^uploads(?:\/|$)/, "");
186
- const filePath = path.resolve(uploadsDir, rel);
187
- if (filePath !== uploadsDir && !filePath.startsWith(uploadsDir + path.sep)) return null;
188
- if (!existsSync(filePath)) return null;
189
-
190
190
  const resolvedFormat: Format = ALLOWED_FORMATS.includes(options.format as Format)
191
191
  ? (options.format as Format)
192
192
  : "webp";
@@ -213,7 +213,7 @@ export async function transformImage(
213
213
  };
214
214
  }
215
215
 
216
- let pipeline = sharp(readFileSync(filePath));
216
+ let pipeline = sharp(Buffer.from(source));
217
217
 
218
218
  if (autoCrop) {
219
219
  pipeline = pipeline.resize(resolvedWidth!, resolvedHeight!, {
package/core/values.ts CHANGED
@@ -309,7 +309,7 @@ export const resolveLinkUrl = async (
309
309
 
310
310
  const renderNode = (node: RichTextNode): string => {
311
311
  if (node.type === "text") {
312
- let content = escapeHtml(String(node.value ?? ""));
312
+ let content = escapeHtml(String(node.value ?? "")).replaceAll("\n", "<br />");
313
313
  if (node.bold) content = `<strong>${content}</strong>`;
314
314
  if (node.italic) content = `<em>${content}</em>`;
315
315
  if (node.href) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kidecms/core",
3
- "version": "0.33.0",
3
+ "version": "0.34.0",
4
4
  "description": "Kide CMS runtime — core library, admin UI, routes, and middleware for Astro. Shipped as TypeScript source.",
5
5
  "keywords": [
6
6
  "cms",
@@ -73,6 +73,7 @@
73
73
  "@tiptap/starter-kit": "3.31.3",
74
74
  "@tiptap/suggestion": "3.31.3",
75
75
  "ai": "^6.0.286",
76
+ "aws4fetch": "^1.0.20",
76
77
  "better-auth": "1.7.7",
77
78
  "class-variance-authority": "^0.7.1",
78
79
  "clsx": "^2.1.1",
@@ -0,0 +1,79 @@
1
+ import { AwsClient } from "aws4fetch";
2
+
3
+ import { readEnv } from "../../core/runtime";
4
+
5
+ // Any S3-compatible object store: AWS S3, UpCloud Object Storage, Hetzner, MinIO, R2's S3 API...
6
+ // Credentials come from env so they never land in the repo; read per call so .env reloads apply.
7
+ type S3Config = { client: AwsClient; baseUrl: string; prefix: string };
8
+
9
+ let cached: { key: string; config: S3Config } | null = null;
10
+
11
+ function getConfig(): S3Config {
12
+ const env = (name: string) => readEnv(name)?.trim() || undefined;
13
+ const bucket = env("S3_BUCKET");
14
+ const accessKeyId = env("S3_ACCESS_KEY_ID");
15
+ const secretAccessKey = env("S3_SECRET_ACCESS_KEY");
16
+ if (!bucket || !accessKeyId || !secretAccessKey) {
17
+ throw new Error("S3 storage needs S3_BUCKET, S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY.");
18
+ }
19
+ const region = env("S3_REGION") ?? "us-east-1";
20
+ const endpoint = env("S3_ENDPOINT")?.replace(/\/+$/, "");
21
+ const prefix = (env("S3_PREFIX") ?? "").replace(/^\/+|\/+$/g, "");
22
+
23
+ const key = [bucket, accessKeyId, secretAccessKey, region, endpoint, prefix].join("\0");
24
+ if (cached?.key === key) return cached.config;
25
+
26
+ // Custom endpoints get path-style URLs (universally supported); AWS itself gets virtual-hosted.
27
+ const baseUrl = endpoint ? `${endpoint}/${bucket}` : `https://${bucket}.s3.${region}.amazonaws.com`;
28
+ const client = new AwsClient({ accessKeyId, secretAccessKey, region, service: "s3" });
29
+ const config = { client, baseUrl, prefix };
30
+ cached = { key, config };
31
+ return config;
32
+ }
33
+
34
+ // "/uploads/a.jpg" → "<prefix>/uploads/a.jpg". Dot segments would be normalized away by URL
35
+ // parsing and could address keys outside the prefix, so they're rejected outright.
36
+ function objectUrl(storagePath: string): { client: AwsClient; url: string } {
37
+ const segments = storagePath.split("/").filter(Boolean);
38
+ if (segments.length === 0 || segments.some((s) => s === "." || s === "..")) {
39
+ throw new Error(`Invalid storage path: ${storagePath}`);
40
+ }
41
+ const { client, baseUrl, prefix } = getConfig();
42
+ const key = [...(prefix ? prefix.split("/") : []), ...segments].map(encodeURIComponent).join("/");
43
+ return { client, url: `${baseUrl}/${key}` };
44
+ }
45
+
46
+ async function request(storagePath: string, init: RequestInit): Promise<Response | null> {
47
+ const { client, url } = objectUrl(storagePath);
48
+ const res = await client.fetch(url, init);
49
+ if (res.status === 404) {
50
+ await res.body?.cancel();
51
+ return null;
52
+ }
53
+ if (!res.ok) {
54
+ const detail = await res.text().catch(() => "");
55
+ throw new Error(`S3 ${init.method} ${storagePath} failed: ${res.status} ${detail.slice(0, 200)}`);
56
+ }
57
+ return res;
58
+ }
59
+
60
+ export async function putFile(storagePath: string, data: ArrayBuffer | Uint8Array): Promise<void> {
61
+ await request(storagePath, { method: "PUT", body: data as BodyInit });
62
+ }
63
+
64
+ export async function getFile(storagePath: string): Promise<ArrayBuffer | null> {
65
+ const res = await request(storagePath, { method: "GET" });
66
+ return res ? res.arrayBuffer() : null;
67
+ }
68
+
69
+ export async function getFileStream(storagePath: string): Promise<{ body: ReadableStream; size: number } | null> {
70
+ const res = await request(storagePath, { method: "GET" });
71
+ if (!res?.body) return null;
72
+ return { body: res.body, size: Number(res.headers.get("content-length") ?? 0) };
73
+ }
74
+
75
+ export async function deleteFile(storagePath: string): Promise<void> {
76
+ // S3 DELETE is idempotent (204 for missing keys); a 404 here means the bucket is wrong.
77
+ const res = await request(storagePath, { method: "DELETE" });
78
+ if (!res) throw new Error(`S3 bucket not found while deleting ${storagePath}`);
79
+ }