import { describe, expect, it, vi } from 'vitest' import { bundleUrl, hasPreviewCookie, runLoader, type LoaderEnv } from '../src/loader-core' function env(href: string, cookie = '', scriptSrc?: string) { const jar = { value: cookie } const e = { location: { href, protocol: new URL(href).protocol, replace: vi.fn() }, cookie: { get: () => jar.value, set: (v: string) => void (jar.value = v) }, scriptSrc, load: vi.fn(() => Promise.resolve({})), } satisfies LoaderEnv return { e, jar } } describe('cms-client loader', () => { it('does nothing for visitors', () => { const { e } = env('https://k6n.net/') expect(runLoader(e)).toBe('idle') expect(e.load).not.toHaveBeenCalled() }) it('loads the editor bundle next to the script when the preview cookie is set', () => { const { e } = env('https://k6n.net/', 'a=b; cms_preview=1', 'https://k6n.net/editor/cms-client.js') expect(runLoader(e)).toBe('loaded') expect(e.load).toHaveBeenCalledWith('https://k6n.net/editor/onpage-editor.js') }) it('?cms_preview=1 sets the cookie, strips the param and reloads', () => { const { e, jar } = env('https://k6n.net/a?x=1&cms_preview=1') expect(runLoader(e)).toBe('redirected') expect(jar.value).toMatch(/^cms_preview=1; path=\/; SameSite=Lax; Secure$/) expect(e.location.replace).toHaveBeenCalledWith('https://k6n.net/a?x=1') expect(e.load).not.toHaveBeenCalled() }) it('?cms_preview=0 clears the cookie (no Secure on http)', () => { const { e, jar } = env('http://localhost/a?cms_preview=0', 'cms_preview=1') runLoader(e) expect(jar.value).toBe('cms_preview=; path=/; max-age=0; SameSite=Lax') expect(e.location.replace).toHaveBeenCalledWith('http://localhost/a') }) it('helpers', () => { expect(hasPreviewCookie('cms_preview=1')).toBe(true) expect(hasPreviewCookie('xcms_preview=1')).toBe(false) expect(hasPreviewCookie('cms_preview=0')).toBe(false) expect(bundleUrl()).toBe('/editor/onpage-editor.js') }) })