Export/import: fix lost images and malformed-file crashes

- An image URL used more than once in the same string (e.g. rich text) was
  only replaced once, leaving broken __IMG__ placeholders after import.
- Images that failed to export were still replaced by placeholders that the
  import could never resolve; keep the original URL instead.
- Validate the uploaded file's shape and JSON (was a 500 on bad input).
- Build lookup filters with pb.filter so names/slugs with quotes don't
  create duplicates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KgF3Kf47LjPGHKQHszpUAv
This commit is contained in:
agent 2026-10-06 10:46:24 +00:00
parent ff54adb00c
commit 1eb58c71ba
3 changed files with 394 additions and 374 deletions

View file

@ -1,139 +1,150 @@
import type { CalendarEventRecord, ContentBlock } from '$lib/types';
/**
* The portable export format.
* Images are stored as base64 data-URIs so the file is fully self-contained.
*/
export type SiteExport = {
version: 1;
exportedAt: string;
pages: {
slug: string;
title: string;
blocks: ContentBlock[];
published: boolean;
}[];
globals: {
key: string;
data: Record<string, unknown>;
}[];
events?: Omit<CalendarEventRecord, 'id'>[];
/** Maps original PocketBase file URLs → base64 data-URI */
images: Record<string, string>;
};
/** Regex to match PocketBase file URLs */
const PB_FILE_RE = /https?:\/\/[^/]+\/api\/files\/([^/]+)\/([^/]+)\/([^\s"')]+)/g;
/**
* Extract all PocketBase image URLs from a value (recursive).
*/
export function extractImageUrls(value: unknown, urls = new Set<string>()): Set<string> {
if (typeof value === 'string') {
let match: RegExpExecArray | null;
const re = new RegExp(PB_FILE_RE.source, 'g');
while ((match = re.exec(value)) !== null) {
urls.add(match[0]);
}
} else if (Array.isArray(value)) {
for (const item of value) extractImageUrls(item, urls);
} else if (value && typeof value === 'object') {
for (const v of Object.values(value as Record<string, unknown>)) extractImageUrls(v, urls);
}
return urls;
}
/**
* Replace all PocketBase URLs in a value with a placeholder key.
*/
export function replaceUrlsWithKeys(
value: unknown,
urlToKey: Map<string, string>
): unknown {
if (typeof value === 'string') {
let result = value;
for (const [url, key] of urlToKey) {
result = result.replace(url, `__IMG__${key}__`);
}
return result;
}
if (Array.isArray(value)) {
return value.map((item) => replaceUrlsWithKeys(item, urlToKey));
}
if (value && typeof value === 'object') {
const obj: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
obj[k] = replaceUrlsWithKeys(v, urlToKey);
}
return obj;
}
return value;
}
/**
* Restore image placeholders back to real URLs after import.
*/
export function restorePlaceholders(
value: unknown,
keyToUrl: Map<string, string>
): unknown {
if (typeof value === 'string') {
let result = value;
for (const [key, url] of keyToUrl) {
result = result.replace(`__IMG__${key}__`, url);
}
return result;
}
if (Array.isArray(value)) {
return value.map((item) => restorePlaceholders(item, keyToUrl));
}
if (value && typeof value === 'object') {
const obj: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
obj[k] = restorePlaceholders(v, keyToUrl);
}
return obj;
}
return value;
}
/**
* Generate a short unique key for an image URL.
*/
export function urlToKey(url: string): string {
const parts = url.split('/');
const filename = parts[parts.length - 1] || 'img';
const id = parts[parts.length - 2]?.slice(0, 8) || 'unknown';
return `${id}_${filename}`;
}
/**
* Fetch an image and return it as a base64 data-URI string.
*/
export async function fetchImageAsBase64(url: string): Promise<string> {
const response = await fetch(url);
if (!response.ok) throw new Error(`Failed to fetch image: ${url} (${response.status})`);
const blob = await response.blob();
const buffer = await blob.arrayBuffer();
const bytes = new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
const base64 = btoa(binary);
return `data:${blob.type};base64,${base64}`;
}
/**
* Convert a base64 data-URI back to a File object for upload.
*/
export function dataUriToFile(dataUri: string, filename: string): File {
const [header, base64] = dataUri.split(',');
const mime = header.match(/data:(.*?);/)?.[1] || 'image/png';
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return new File([bytes], filename, { type: mime });
import type { CalendarEventRecord, ContentBlock } from '$lib/types';
/**
* The portable export format.
* Images are stored as base64 data-URIs so the file is fully self-contained.
*/
export type SiteExport = {
version: 1;
exportedAt: string;
pages: {
slug: string;
title: string;
blocks: ContentBlock[];
published: boolean;
}[];
globals: {
key: string;
data: Record<string, unknown>;
}[];
events?: Omit<CalendarEventRecord, 'id'>[];
/** Maps original PocketBase file URLs → base64 data-URI */
images: Record<string, string>;
};
/** Regex to match PocketBase file URLs */
const PB_FILE_RE = /https?:\/\/[^/]+\/api\/files\/([^/]+)\/([^/]+)\/([^\s"')]+)/g;
/**
* Extract all PocketBase image URLs from a value (recursive).
*/
export function extractImageUrls(value: unknown, urls = new Set<string>()): Set<string> {
if (typeof value === 'string') {
let match: RegExpExecArray | null;
const re = new RegExp(PB_FILE_RE.source, 'g');
while ((match = re.exec(value)) !== null) {
urls.add(match[0]);
}
} else if (Array.isArray(value)) {
for (const item of value) extractImageUrls(item, urls);
} else if (value && typeof value === 'object') {
for (const v of Object.values(value as Record<string, unknown>)) extractImageUrls(v, urls);
}
return urls;
}
/**
* Replace all PocketBase URLs in a value with a placeholder key.
*/
export function replaceUrlsWithKeys(
value: unknown,
urlToKey: Map<string, string>
): unknown {
if (typeof value === 'string') {
let result = value;
for (const [url, key] of urlToKey) {
result = result.replaceAll(url, `__IMG__${key}__`);
}
return result;
}
if (Array.isArray(value)) {
return value.map((item) => replaceUrlsWithKeys(item, urlToKey));
}
if (value && typeof value === 'object') {
const obj: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
obj[k] = replaceUrlsWithKeys(v, urlToKey);
}
return obj;
}
return value;
}
/**
* Restore image placeholders back to real URLs after import.
*/
export function restorePlaceholders(
value: unknown,
keyToUrl: Map<string, string>
): unknown {
if (typeof value === 'string') {
let result = value;
for (const [key, url] of keyToUrl) {
result = result.replaceAll(`__IMG__${key}__`, url);
}
return result;
}
if (Array.isArray(value)) {
return value.map((item) => restorePlaceholders(item, keyToUrl));
}
if (value && typeof value === 'object') {
const obj: Record<string, unknown> = {};
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
obj[k] = restorePlaceholders(v, keyToUrl);
}
return obj;
}
return value;
}
/**
* Generate a short unique key for an image URL.
*/
export function urlToKey(url: string): string {
const parts = url.split('/');
const filename = parts[parts.length - 1] || 'img';
const id = parts[parts.length - 2]?.slice(0, 8) || 'unknown';
return `${id}_${filename}`;
}
/**
* Fetch an image and return it as a base64 data-URI string.
*/
export async function fetchImageAsBase64(url: string): Promise<string> {
const response = await fetch(url);
if (!response.ok) throw new Error(`Failed to fetch image: ${url} (${response.status})`);
const blob = await response.blob();
const buffer = await blob.arrayBuffer();
const bytes = new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
const base64 = btoa(binary);
return `data:${blob.type};base64,${base64}`;
}
/** Shape check for an uploaded export file; returns an error message or null. */
export function validateSiteExport(body: unknown): string | null {
if (!body || typeof body !== 'object') return 'The file is not a CMS export.';
const b = body as Partial<SiteExport>;
if (b.version !== 1) return 'Unsupported export version.';
if (!Array.isArray(b.pages) || !Array.isArray(b.globals)) return 'The export is missing pages or globals.';
if (b.events !== undefined && !Array.isArray(b.events)) return 'The export has an invalid events list.';
if (!b.images || typeof b.images !== 'object' || Array.isArray(b.images)) return 'The export is missing its images.';
return null;
}
/**
* Convert a base64 data-URI back to a File object for upload.
*/
export function dataUriToFile(dataUri: string, filename: string): File {
const [header, base64] = dataUri.split(',');
const mime = header.match(/data:(.*?);/)?.[1] || 'image/png';
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return new File([bytes], filename, { type: mime });
}

View file

@ -1,98 +1,101 @@
import { env } from '$env/dynamic/private';
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
extractImageUrls,
fetchImageAsBase64,
replaceUrlsWithKeys,
urlToKey,
type SiteExport
} from '$lib/exportImport';
import { normalizeEvent } from '$lib/calendar';
export const GET: RequestHandler = async ({ locals }) => {
// Fetch all pages
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
// Fetch all globals
const globals = await locals.pb.collection('globals').getFullList();
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
// Collect all image URLs from pages and globals
const allUrls = new Set<string>();
for (const page of pages) {
for (const url of extractImageUrls(page)) allUrls.add(url);
}
for (const g of globals) {
for (const url of extractImageUrls(g)) allUrls.add(url);
}
// Fetch each image as base64. Stored image URLs may use any public host
// (e.g. http://localhost:8080 from before a domain migration, or
// http://db.localhost:8080 after). The app container can only reach
// PocketBase via the internal Docker network URL, so rewrite the host
// of every matched URL to the internal base.
const internalBase = env.POCKETBASE_INTERNAL_URL!;
const images: Record<string, string> = {};
for (const url of allUrls) {
try {
// Replace the host (and optional port) with the internal base.
const fetchUrl = url.replace(/^[a-z]+:\/\/[^/]+/, internalBase);
const key = urlToKey(url);
images[key] = await fetchImageAsBase64(fetchUrl);
} catch (e) {
console.warn(`Could not fetch image: ${url}`, e);
}
}
// Build URL → key mapping
const urlToKeyMap = new Map<string, string>();
for (const url of allUrls) {
urlToKeyMap.set(url, urlToKey(url));
}
// Replace URLs with placeholders in pages
const exportPages = pages.map((p) => ({
slug: p.slug,
title: p.title,
blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks,
published: p.published
}));
// Replace URLs with placeholders in globals
const exportGlobals = globals.map((g) => ({
key: g.key,
data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown>
}));
const exportEvents = events.map((record) => {
const event = normalizeEvent(record);
return {
name: event.name,
start: event.start,
end: event.end,
description: event.description,
color: event.color,
link: event.link,
categories: event.categories,
published: event.published,
allDay: event.allDay
};
});
const exportData: SiteExport = {
version: 1,
exportedAt: new Date().toISOString(),
pages: exportPages,
globals: exportGlobals,
events: exportEvents,
images
};
return json(exportData, {
headers: {
'Content-Disposition': `attachment; filename="cms-export-${new Date().toISOString().slice(0, 10)}.json"`
}
});
import { env } from '$env/dynamic/private';
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
extractImageUrls,
fetchImageAsBase64,
replaceUrlsWithKeys,
urlToKey,
type SiteExport
} from '$lib/exportImport';
import { normalizeEvent } from '$lib/calendar';
export const GET: RequestHandler = async ({ locals }) => {
// Fetch all pages
const pages = await locals.pb.collection('pages').getFullList({ sort: 'slug' });
// Fetch all globals
const globals = await locals.pb.collection('globals').getFullList();
const events = await locals.pb.collection('events').getFullList({ sort: 'start' }).catch(() => []);
// Collect all image URLs from pages and globals
const allUrls = new Set<string>();
for (const page of pages) {
for (const url of extractImageUrls(page)) allUrls.add(url);
}
for (const g of globals) {
for (const url of extractImageUrls(g)) allUrls.add(url);
}
// Fetch each image as base64. Stored image URLs may use any public host
// (e.g. http://localhost:8080 from before a domain migration, or
// http://db.localhost:8080 after). The app container can only reach
// PocketBase via the internal Docker network URL, so rewrite the host
// of every matched URL to the internal base.
const internalBase = env.POCKETBASE_INTERNAL_URL!;
const images: Record<string, string> = {};
for (const url of allUrls) {
try {
// Replace the host (and optional port) with the internal base.
const fetchUrl = url.replace(/^[a-z]+:\/\/[^/]+/, internalBase);
const key = urlToKey(url);
images[key] = await fetchImageAsBase64(fetchUrl);
} catch (e) {
console.warn(`Could not fetch image: ${url}`, e);
}
}
// Build URL → key mapping — only for images that were actually exported.
// A URL whose image couldn't be fetched is left as-is rather than turned
// into a placeholder the import could never resolve.
const urlToKeyMap = new Map<string, string>();
for (const url of allUrls) {
const key = urlToKey(url);
if (key in images) urlToKeyMap.set(url, key);
}
// Replace URLs with placeholders in pages
const exportPages = pages.map((p) => ({
slug: p.slug,
title: p.title,
blocks: replaceUrlsWithKeys(p.blocks, urlToKeyMap) as typeof p.blocks,
published: p.published
}));
// Replace URLs with placeholders in globals
const exportGlobals = globals.map((g) => ({
key: g.key,
data: replaceUrlsWithKeys(g.data, urlToKeyMap) as Record<string, unknown>
}));
const exportEvents = events.map((record) => {
const event = normalizeEvent(record);
return {
name: event.name,
start: event.start,
end: event.end,
description: event.description,
color: event.color,
link: event.link,
categories: event.categories,
published: event.published,
allDay: event.allDay
};
});
const exportData: SiteExport = {
version: 1,
exportedAt: new Date().toISOString(),
pages: exportPages,
globals: exportGlobals,
events: exportEvents,
images
};
return json(exportData, {
headers: {
'Content-Disposition': `attachment; filename="cms-export-${new Date().toISOString().slice(0, 10)}.json"`
}
});
};

View file

@ -1,140 +1,146 @@
import { env } from '$env/dynamic/public';
import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
dataUriToFile,
restorePlaceholders,
type SiteExport
} from '$lib/exportImport';
export const POST: RequestHandler = async ({ request, locals }) => {
const body = (await request.json()) as SiteExport;
if (!body || body.version !== 1) {
throw error(400, 'Invalid or unsupported export file.');
}
const results = {
imagesUploaded: 0,
pagesImported: 0,
globalsImported: 0,
eventsImported: 0,
errors: [] as string[]
};
// 1. Upload images to PocketBase media collection
// Build a map: placeholder key → new PocketBase URL
const keyToUrl = new Map<string, string>();
for (const [key, dataUri] of Object.entries(body.images)) {
try {
// Derive a filename from the key (e.g. "abc12345_logo.png")
const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png';
const file = dataUriToFile(dataUri, filename);
const formData = new FormData();
formData.append('file', file);
formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
const record = await locals.pb.collection('media').create(formData);
const publicUrl = env.PUBLIC_POCKETBASE_URL;
const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
keyToUrl.set(key, newUrl);
results.imagesUploaded++;
} catch (e) {
results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`);
}
}
// 2. Import pages
for (const page of body.pages) {
try {
const blocks = restorePlaceholders(page.blocks, keyToUrl);
// Try to find existing page by slug
let existing;
try {
existing = await locals.pb.collection('pages').getFirstListItem(`slug = "${page.slug}"`);
} catch {
existing = null;
}
if (existing) {
await locals.pb.collection('pages').update(existing.id, {
title: page.title,
blocks,
published: page.published
});
} else {
await locals.pb.collection('pages').create({
slug: page.slug,
title: page.title,
blocks,
published: page.published
});
}
results.pagesImported++;
} catch (e) {
results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`);
}
}
// 3. Import globals
for (const g of body.globals) {
try {
const data = restorePlaceholders(g.data, keyToUrl);
let existing;
try {
existing = await locals.pb.collection('globals').getFirstListItem(`key = "${g.key}"`);
} catch {
existing = null;
}
if (existing) {
await locals.pb.collection('globals').update(existing.id, { data });
} else {
await locals.pb.collection('globals').create({ key: g.key, data });
}
results.globalsImported++;
} catch (e) {
results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`);
}
}
// 4. Import events
for (const event of body.events || []) {
try {
let existing;
try {
existing = await locals.pb.collection('events').getFirstListItem(`name = "${event.name}" && start = "${event.start}"`);
} catch {
existing = null;
}
const payload = {
name: event.name,
start: event.start,
end: event.end || null,
description: event.description || '',
color: event.color || '#8a9a7b',
link: event.link || '',
categories: event.categories || [],
published: Boolean(event.published),
allDay: event.allDay !== false
};
if (existing) {
await locals.pb.collection('events').update(existing.id, payload);
} else {
await locals.pb.collection('events').create(payload);
}
results.eventsImported++;
} catch (e) {
results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`);
}
}
return json(results);
import { env } from '$env/dynamic/public';
import { error, json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import {
dataUriToFile,
restorePlaceholders,
validateSiteExport,
type SiteExport
} from '$lib/exportImport';
export const POST: RequestHandler = async ({ request, locals }) => {
let body: SiteExport;
try {
body = await request.json();
} catch {
throw error(400, 'The file is not valid JSON.');
}
const invalid = validateSiteExport(body);
if (invalid) throw error(400, invalid);
const results = {
imagesUploaded: 0,
pagesImported: 0,
globalsImported: 0,
eventsImported: 0,
errors: [] as string[]
};
// 1. Upload images to PocketBase media collection
// Build a map: placeholder key → new PocketBase URL
const keyToUrl = new Map<string, string>();
for (const [key, dataUri] of Object.entries(body.images)) {
try {
// Derive a filename from the key (e.g. "abc12345_logo.png")
const filename = key.replace(/[^a-zA-Z0-9._-]/g, '_') || 'image.png';
const file = dataUriToFile(dataUri, filename);
const formData = new FormData();
formData.append('file', file);
formData.append('alt', filename.replace(/\.[^/.]+$/, '').replace(/[-_]/g, ' '));
const record = await locals.pb.collection('media').create(formData);
const publicUrl = env.PUBLIC_POCKETBASE_URL;
const newUrl = `${publicUrl}/api/files/${record.collectionId}/${record.id}/${record.file}`;
keyToUrl.set(key, newUrl);
results.imagesUploaded++;
} catch (e) {
results.errors.push(`Failed to upload image "${key}": ${e instanceof Error ? e.message : String(e)}`);
}
}
// 2. Import pages
for (const page of body.pages) {
try {
const blocks = restorePlaceholders(page.blocks, keyToUrl);
// Try to find existing page by slug
let existing;
try {
existing = await locals.pb.collection('pages').getFirstListItem(locals.pb.filter('slug = {:slug}', { slug: page.slug }));
} catch {
existing = null;
}
if (existing) {
await locals.pb.collection('pages').update(existing.id, {
title: page.title,
blocks,
published: page.published
});
} else {
await locals.pb.collection('pages').create({
slug: page.slug,
title: page.title,
blocks,
published: page.published
});
}
results.pagesImported++;
} catch (e) {
results.errors.push(`Failed to import page "${page.slug}": ${e instanceof Error ? e.message : String(e)}`);
}
}
// 3. Import globals
for (const g of body.globals) {
try {
const data = restorePlaceholders(g.data, keyToUrl);
let existing;
try {
existing = await locals.pb.collection('globals').getFirstListItem(locals.pb.filter('key = {:key}', { key: g.key }));
} catch {
existing = null;
}
if (existing) {
await locals.pb.collection('globals').update(existing.id, { data });
} else {
await locals.pb.collection('globals').create({ key: g.key, data });
}
results.globalsImported++;
} catch (e) {
results.errors.push(`Failed to import global "${g.key}": ${e instanceof Error ? e.message : String(e)}`);
}
}
// 4. Import events
for (const event of body.events || []) {
try {
let existing;
try {
existing = await locals.pb
.collection('events')
.getFirstListItem(locals.pb.filter('name = {:name} && start = {:start}', { name: event.name, start: event.start }));
} catch {
existing = null;
}
const payload = {
name: event.name,
start: event.start,
end: event.end || null,
description: event.description || '',
color: event.color || '#8a9a7b',
link: event.link || '',
categories: event.categories || [],
published: Boolean(event.published),
allDay: event.allDay !== false
};
if (existing) {
await locals.pb.collection('events').update(existing.id, payload);
} else {
await locals.pb.collection('events').create(payload);
}
results.eventsImported++;
} catch (e) {
results.errors.push(`Failed to import event "${event.name}": ${e instanceof Error ? e.message : String(e)}`);
}
}
return json(results);
};