Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/brave-paths-follow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@open-slide/core': patch
---

Keep dev authoring APIs (folders, editing, notes, comments, assets, server actions) under the configured `base` so they work behind subpath hosting.
3 changes: 2 additions & 1 deletion packages/core/src/app/components/image-placeholder.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { type CSSProperties, type HTMLAttributes, useRef, useState } from 'react';
import { toast } from 'sonner';
import { uploadWithAutoRename } from '@/lib/assets';
import { devApiUrl } from '@/lib/dev-api';
import { useLocale } from '@/lib/use-locale';

export type ImagePlaceholderProps = {
Expand Down Expand Up @@ -206,7 +207,7 @@ function pickImageFile(files: FileList): File | null {
async function handleDrop(slideId: string, file: File, line: number, column: number) {
const { ok, entry } = await uploadWithAutoRename(slideId, file);
if (!ok || !entry) throw new Error('upload failed');
const res = await fetch('/__edit', {
const res = await fetch(devApiUrl('/__edit'), {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
Expand Down
5 changes: 3 additions & 2 deletions packages/core/src/app/components/sidebar/sidebar-footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { devApiUrl } from '@/lib/dev-api';
import { format, useLocale } from '@/lib/use-locale';
import { useRestartServer } from '@/lib/use-restart-server';

Expand All @@ -23,7 +24,7 @@ export function SidebarFooter() {
useEffect(() => {
if (!import.meta.env.DEV) return;
let cancelled = false;
fetch('/__update-check')
fetch(devApiUrl('/__update-check'))
.then((res) => (res.ok ? (res.json() as Promise<UpdateCheck>) : null))
.then((data) => {
if (!cancelled && data?.outdated) setUpdate(data);
Expand All @@ -43,7 +44,7 @@ export function SidebarFooter() {
setUpdateStatus('running');
setOpen(true);
try {
const res = await fetch('/__update-package', { method: 'POST' });
const res = await fetch(devApiUrl('/__update-package'), { method: 'POST' });
if (!res.ok) throw new Error('update failed');
setUpdateStatus('done');
toast.success(t.home.updatePackageDone);
Expand Down
7 changes: 4 additions & 3 deletions packages/core/src/app/components/style-panel/use-design.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { DesignSystem } from '../../lib/design';
import { devApiUrl } from '../../lib/dev-api';

type FetchedState = {
design: DesignSystem | null;
Expand Down Expand Up @@ -28,7 +29,7 @@ export function useDesign(slideId: string): UseDesignReturn {
const id = slideIdRef.current;
if (!id) return;
try {
const res = await fetch(`/__design?slideId=${encodeURIComponent(id)}`);
const res = await fetch(devApiUrl(`/__design?slideId=${encodeURIComponent(id)}`));
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const body = (await res.json()) as {
design: DesignSystem;
Expand All @@ -55,7 +56,7 @@ export function useDesign(slideId: string): UseDesignReturn {
const id = slideIdRef.current;
if (!id) return { ok: false, error: 'no slide id' };
try {
const res = await fetch(`/__design?slideId=${encodeURIComponent(id)}`, {
const res = await fetch(devApiUrl(`/__design?slideId=${encodeURIComponent(id)}`), {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ patch }),
Expand Down Expand Up @@ -87,7 +88,7 @@ export function useDesign(slideId: string): UseDesignReturn {
const id = slideIdRef.current;
if (!id) return { ok: false, error: 'no slide id' };
try {
const res = await fetch(`/__design/reset?slideId=${encodeURIComponent(id)}`, {
const res = await fetch(devApiUrl(`/__design/reset?slideId=${encodeURIComponent(id)}`), {
method: 'POST',
});
const body = (await res.json()) as { ok?: boolean; error?: string; design?: DesignSystem };
Expand Down
19 changes: 10 additions & 9 deletions packages/core/src/app/lib/assets.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useState } from 'react';
import { devApiUrl } from './dev-api';

export type AssetEntry = {
name: string;
Expand All @@ -13,7 +14,7 @@ export type AssetEntry = {
export type UploadOptions = { overwrite?: boolean };

export async function listAssets(slideId: string): Promise<AssetEntry[]> {
const res = await fetch(`/__assets/${slideId}`);
const res = await fetch(devApiUrl(`/__assets/${slideId}`));
if (!res.ok) throw new Error(`GET /__assets/${slideId} ${res.status}`);
const data = (await res.json()) as { assets?: AssetEntry[] };
return data.assets ?? [];
Expand All @@ -25,7 +26,7 @@ export async function uploadAsset(
opts: UploadOptions = {},
): Promise<Response> {
const qs = opts.overwrite ? '?overwrite=1' : '';
return fetch(`/__assets/${slideId}/${encodeURIComponent(file.name)}${qs}`, {
return fetch(devApiUrl(`/__assets/${slideId}/${encodeURIComponent(file.name)}${qs}`), {
method: 'POST',
headers: {
'content-type': file.type || 'application/octet-stream',
Expand All @@ -36,21 +37,21 @@ export async function uploadAsset(
}

async function renameAsset(slideId: string, from: string, to: string): Promise<Response> {
return fetch(`/__assets/${slideId}/${encodeURIComponent(from)}`, {
return fetch(devApiUrl(`/__assets/${slideId}/${encodeURIComponent(from)}`), {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ name: to }),
});
}

async function deleteAsset(slideId: string, name: string): Promise<Response> {
return fetch(`/__assets/${slideId}/${encodeURIComponent(name)}`, { method: 'DELETE' });
return fetch(devApiUrl(`/__assets/${slideId}/${encodeURIComponent(name)}`), { method: 'DELETE' });
}

export type AssetUsage = { slideId: string; count: number };

export async function listAssetUsages(slideId: string, name: string): Promise<AssetUsage[]> {
const res = await fetch(`/__assets/${slideId}/${encodeURIComponent(name)}/usages`);
const res = await fetch(devApiUrl(`/__assets/${slideId}/${encodeURIComponent(name)}/usages`));
if (!res.ok) return [];
const data = (await res.json().catch(() => null)) as { usages?: AssetUsage[] } | null;
return data?.usages ?? [];
Expand All @@ -60,7 +61,7 @@ export async function revertAssetUsage(
slideId: string,
assetPath: string,
): Promise<{ ok: boolean; status: number }> {
const res = await fetch('/__edit/revert-asset', {
const res = await fetch(devApiUrl('/__edit/revert-asset'), {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ slideId, assetPath }),
Expand Down Expand Up @@ -93,7 +94,7 @@ export async function uploadWithAutoRename(
createdAt: body?.createdAt ?? now,
mtime: body?.mtime ?? now,
mime: body?.mime ?? uploaded.type ?? 'application/octet-stream',
url: body?.url ?? `/__assets/${slideId}/${encodeURIComponent(uploaded.name)}`,
url: body?.url ?? devApiUrl(`/__assets/${slideId}/${encodeURIComponent(uploaded.name)}`),
unused: body?.unused ?? false,
};
return { ok: true, status: res.status, entry };
Expand Down Expand Up @@ -137,7 +138,7 @@ export async function searchSvgl(query: string, signal?: AbortSignal): Promise<S
const params = new URLSearchParams();
if (q) params.set('q', q);
else params.set('limit', '24');
const res = await fetch(`/__svgl/search?${params.toString()}`, { signal });
const res = await fetch(devApiUrl(`/__svgl/search?${params.toString()}`), { signal });
// svgl returns 404 when a search has no matches — treat it as an empty list,
// not an error.
if (res.status === 404) return [];
Expand All @@ -146,7 +147,7 @@ export async function searchSvgl(query: string, signal?: AbortSignal): Promise<S
}

export function svgProxyUrl(routeUrl: string): string {
return `/__svgl/svg?u=${encodeURIComponent(routeUrl)}`;
return devApiUrl(`/__svgl/svg?u=${encodeURIComponent(routeUrl)}`);
}

export async function fetchSvgAsFile(routeUrl: string, filename: string): Promise<File> {
Expand Down
76 changes: 76 additions & 0 deletions packages/core/src/app/lib/dev-api.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { devApiUrl, joinBase } from './dev-api.ts';

describe('joinBase', () => {
it('leaves paths untouched for the root base', () => {
expect(joinBase('/', '/__folders')).toBe('/__folders');
expect(joinBase('/', '/__slides/intro')).toBe('/__slides/intro');
});

it('prefixes paths with a nested base', () => {
expect(joinBase('/my-slides/', '/__folders')).toBe('/my-slides/__folders');
expect(joinBase('/my-slides/', '/__slides/intro/reorder')).toBe(
'/my-slides/__slides/intro/reorder',
);
});

it('handles a nested base without a trailing slash', () => {
expect(joinBase('/my-slides', '/__folders')).toBe('/my-slides/__folders');
});

it('handles a deeply nested base', () => {
expect(joinBase('/team/decks/', '/__edit')).toBe('/team/decks/__edit');
});

it('falls back to root for empty or relative bases', () => {
expect(joinBase('', '/__folders')).toBe('/__folders');
expect(joinBase('./', '/__folders')).toBe('/__folders');
});

it('preserves query strings', () => {
expect(joinBase('/my-slides/', '/__design?slideId=a')).toBe('/my-slides/__design?slideId=a');
});
});

describe('devApiUrl', () => {
afterEach(() => {
vi.unstubAllEnvs();
});

it('returns root-absolute URLs when BASE_URL is /', () => {
vi.stubEnv('BASE_URL', '/');
expect(devApiUrl('/__folders')).toBe('/__folders');
});

it('keeps URLs beneath a configured base', () => {
vi.stubEnv('BASE_URL', '/my-slides/');
expect(devApiUrl('/__folders')).toBe('/my-slides/__folders');
expect(devApiUrl('/__edit')).toBe('/my-slides/__edit');
expect(devApiUrl('/__notes')).toBe('/my-slides/__notes');
});
});

describe('app sources', () => {
it('never fetch root-absolute /__ dev API URLs directly', async () => {
const appRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const offenders: string[] = [];
const walk = async (dir: string): Promise<void> => {
for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
await walk(full);
} else if (/\.(ts|tsx)$/.test(entry.name) && !entry.name.endsWith('.test.ts')) {
const source = await fs.readFile(full, 'utf8');
if (/fetch\(\s*['"`]\/__/.test(source)) {
offenders.push(path.relative(appRoot, full));
}
}
}
};
await walk(appRoot);
expect(offenders, 'route these fetches through devApiUrl() so they honor BASE_URL').toEqual([]);
});
});
12 changes: 12 additions & 0 deletions packages/core/src/app/lib/dev-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export function joinBase(base: string, path: string): string {
if (!base.startsWith('/')) return path;
const trimmed = base.replace(/\/+$/, '');
return trimmed + path;
}

// Dev-server API URLs must stay beneath the configured `base` so authoring
// still works when the app is hosted at a subpath (e.g. behind a reverse
// proxy). Route every `/__*` fetch through here instead of hardcoding paths.
export function devApiUrl(path: string): string {
return joinBase(import.meta.env.BASE_URL ?? '/', path);
}
19 changes: 10 additions & 9 deletions packages/core/src/app/lib/folders.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import buildManifest from 'virtual:open-slide/folders';
import { useCallback, useEffect, useState } from 'react';
import { devApiUrl } from './dev-api';
import type { Folder, FolderIcon, FoldersManifest } from './sdk';

const EMPTY: FoldersManifest = { folders: [], assignments: {} };
Expand All @@ -10,7 +11,7 @@ async function getManifest(): Promise<FoldersManifest> {
// is no server, so fall back to the bundled snapshot from the virtual
// module (populated at build time from slides/.folders.json).
if (import.meta.env.DEV) {
const res = await fetch('/__folders');
const res = await fetch(devApiUrl('/__folders'));
if (!res.ok) throw new Error(`GET /__folders ${res.status}`);
const raw = (await res.json()) as Partial<FoldersManifest>;
return {
Expand All @@ -25,7 +26,7 @@ async function getManifest(): Promise<FoldersManifest> {
}

async function patchSlideName(slideId: string, name: string): Promise<void> {
const res = await fetch(`/__slides/${slideId}`, {
const res = await fetch(devApiUrl(`/__slides/${slideId}`), {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ name }),
Expand All @@ -39,20 +40,20 @@ async function duplicateSlideReq(slideId: string, newId?: string): Promise<strin
init.headers = { 'content-type': 'application/json' };
init.body = JSON.stringify({ newId });
}
const res = await fetch(`/__slides/${slideId}/duplicate`, init);
const res = await fetch(devApiUrl(`/__slides/${slideId}/duplicate`), init);
if (!res.ok) throw new Error(`POST /__slides/${slideId}/duplicate ${res.status}`);
const body = (await res.json()) as { slideId?: unknown };
if (typeof body.slideId !== 'string') throw new Error('duplicate response missing slideId');
return body.slideId;
}

async function deleteSlideReq(slideId: string): Promise<void> {
const res = await fetch(`/__slides/${slideId}`, { method: 'DELETE' });
const res = await fetch(devApiUrl(`/__slides/${slideId}`), { method: 'DELETE' });
if (!res.ok) throw new Error(`DELETE /__slides/${slideId} ${res.status}`);
}

async function postFolder(name: string, icon: FolderIcon): Promise<Folder> {
const res = await fetch('/__folders', {
const res = await fetch(devApiUrl('/__folders'), {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ name, icon }),
Expand All @@ -65,7 +66,7 @@ async function patchFolder(
id: string,
patch: { name?: string; icon?: FolderIcon },
): Promise<Folder> {
const res = await fetch(`/__folders/${id}`, {
const res = await fetch(devApiUrl(`/__folders/${id}`), {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(patch),
Expand All @@ -75,12 +76,12 @@ async function patchFolder(
}

async function deleteFolder(id: string): Promise<void> {
const res = await fetch(`/__folders/${id}`, { method: 'DELETE' });
const res = await fetch(devApiUrl(`/__folders/${id}`), { method: 'DELETE' });
if (!res.ok) throw new Error(`DELETE /__folders/${id} ${res.status}`);
}

async function putAssign(slideId: string, folderId: string | null): Promise<void> {
const res = await fetch('/__folders/assign', {
const res = await fetch(devApiUrl('/__folders/assign'), {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ slideId, folderId }),
Expand All @@ -89,7 +90,7 @@ async function putAssign(slideId: string, folderId: string | null): Promise<void
}

async function putReorder(ids: string[]): Promise<void> {
const res = await fetch('/__folders/reorder', {
const res = await fetch(devApiUrl('/__folders/reorder'), {
method: 'PUT',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ ids }),
Expand Down
14 changes: 9 additions & 5 deletions packages/core/src/app/lib/inspector/use-comments.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useState } from 'react';
import { devApiUrl } from '../dev-api';

export type SlideComment = {
id: string;
Expand All @@ -17,7 +18,7 @@ export function useComments(slideId: string) {
const refetch = useCallback(async () => {
if (!slideId) return;
try {
const res = await fetch(`/__comments?slideId=${encodeURIComponent(slideId)}`);
const res = await fetch(devApiUrl(`/__comments?slideId=${encodeURIComponent(slideId)}`));
if (!res.ok) {
setError(`GET /__comments → ${res.status}`);
return;
Expand All @@ -32,7 +33,7 @@ export function useComments(slideId: string) {

const add = useCallback(
async (line: number, column: number, text: string) => {
const res = await fetch('/__comments/add', {
const res = await fetch(devApiUrl('/__comments/add'), {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ slideId, line, column, text }),
Expand All @@ -48,9 +49,12 @@ export function useComments(slideId: string) {

const remove = useCallback(
async (id: string) => {
const res = await fetch(`/__comments/${id}?slideId=${encodeURIComponent(slideId)}`, {
method: 'DELETE',
});
const res = await fetch(
devApiUrl(`/__comments/${id}?slideId=${encodeURIComponent(slideId)}`),
{
method: 'DELETE',
},
);
if (!res.ok) throw new Error(`DELETE /__comments/${id} → ${res.status}`);
await refetch();
},
Expand Down
Loading