Skip to content
Merged
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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,9 @@
]
},
"scripts": {
"build": "esbuild src/extension.ts --bundle --platform=node --format=cjs --external:vscode --outfile=dist/extension.js && esbuild src/xhtml.ts --bundle --platform=node --format=cjs --outfile=dist/xhtml.js && esbuild src/epub.ts --bundle --platform=node --format=cjs --external:vscode --outfile=dist/epub.js && esbuild src/state-manager.ts --bundle --platform=node --format=cjs --outfile=dist/state-manager.js && esbuild src/archive.ts --bundle --platform=node --format=cjs --outfile=dist/archive.js",
"build": "esbuild src/vscode/extension.ts --bundle --platform=node --format=cjs --external:vscode --outfile=dist/extension.js && esbuild src/core/xhtml.ts --bundle --platform=node --format=cjs --outfile=dist/xhtml.js && esbuild src/core/epub.ts --bundle --platform=node --format=cjs --external:vscode --outfile=dist/epub.js && esbuild src/core/state-manager.ts --bundle --platform=node --format=cjs --outfile=dist/state-manager.js && esbuild src/core/archive.ts --bundle --platform=node --format=cjs --outfile=dist/archive.js",
"check": "tsc --noEmit",
"check:core": "tsc -p tsconfig.core.json --noEmit",
"test": "npm run build && node --test test/*.test.mjs",
"watch": "npm run build -- --watch"
},
Expand Down
File renamed without changes.
98 changes: 59 additions & 39 deletions src/epub.ts β†’ src/core/epub.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,48 @@
import type * as vscodeTypes from 'vscode';
export interface ResourceUri {
path: string;
fsPath?: string;
scheme?: string;
toString(): string;
with?(change: { path?: string }): ResourceUri;
}

let vscodeModule: typeof import('vscode') | undefined;
try {
vscodeModule = require('vscode');
} catch {
// Allow running in pure Node.js environments (e.g. unit tests)
export function createResourceUri(filePath: string): ResourceUri {
const normalized = filePath.replace(/\\/g, '/');
return {
path: normalized,
fsPath: filePath,
scheme: 'file',
toString: () => normalized,
with: (change: { path?: string }) => createResourceUri(change.path ?? normalized)
};
}

export interface EpubManifestItem {
id: string;
href: string;
mediaType: string;
properties?: string;
uri: vscodeTypes.Uri;
uri: ResourceUri;
}

export interface EpubSpineItem {
idref: string;
linear?: boolean;
href: string;
uri: vscodeTypes.Uri;
uri: ResourceUri;
}

export interface EpubTocItem {
id?: string;
label: string;
href: string;
uri: vscodeTypes.Uri;
uri: ResourceUri;
}

export interface EpubPackage {
containerRoot: vscodeTypes.Uri;
opfUri: vscodeTypes.Uri;
opfDir: vscodeTypes.Uri;
containerRoot: ResourceUri;
opfUri: ResourceUri;
opfDir: ResourceUri;
title: string;
creator?: string;
language?: string;
Expand All @@ -44,28 +54,37 @@ export interface EpubPackage {
/**
* Ascends from the given source file directory to locate a META-INF/container.xml file.
*/
export async function locateEpubContainer(source: vscodeTypes.Uri): Promise<vscodeTypes.Uri | undefined> {
if (!vscodeModule) {
return undefined;
}
export async function locateEpubContainer(
source: ResourceUri,
fileExists?: (candidate: ResourceUri) => Promise<boolean>
): Promise<ResourceUri | undefined> {
const checkExists = fileExists ?? (async (candidate: ResourceUri) => {
try {
const fs = await import('node:fs/promises');
const targetPath = candidate.fsPath || candidate.path;
await fs.stat(targetPath);
return true;
} catch {
return false;
}
});

let current = parentUri(source);
const root = vscodeModule.workspace.workspaceFolders?.[0]?.uri;

for (let i = 0; i < 6; i++) {
const candidate = joinPath(current, 'META-INF', 'container.xml');
try {
await vscodeModule.workspace.fs.stat(candidate);
return current;
} catch {
const parent = parentUri(current);
if (parent.toString() === current.toString()) {
break;
}
if (root && current.toString() === root.toString()) {
break;
if (await checkExists(candidate)) {
return current;
}
current = parent;
} catch {
// ignore
}
const parent = parentUri(current);
if (parent.toString() === current.toString()) {
break;
}
current = parent;
}
return undefined;
}
Expand All @@ -81,7 +100,7 @@ export function parseContainerXml(xml: string): string | undefined {
/**
* Safely parses the OPF Package Document into metadata, manifest, and spine.
*/
export function parseOpfXml(xml: string, opfUri: vscodeTypes.Uri, containerRoot: vscodeTypes.Uri): EpubPackage {
export function parseOpfXml(xml: string, opfUri: ResourceUri, containerRoot: ResourceUri): EpubPackage {
const opfDir = parentUri(opfUri);

// Metadata
Expand Down Expand Up @@ -162,7 +181,7 @@ export function parseOpfXml(xml: string, opfUri: vscodeTypes.Uri, containerRoot:
/**
* Parses EPUB 3 Navigation Document XHTML into TOC items.
*/
export function parseNavHtml(html: string, baseDir: vscodeTypes.Uri): EpubTocItem[] {
export function parseNavHtml(html: string, baseDir: ResourceUri): EpubTocItem[] {
const items: EpubTocItem[] = [];
// Find <nav> with epub:type="toc" or id="toc", or fallback to any nav
const navMatch = /<nav\b(?=[^>]*\b(?:epub:type=["'][^"']*toc|id=["']toc))\b[^>]*>([\s\S]*?)<\/nav>/i.exec(html)
Expand Down Expand Up @@ -197,7 +216,7 @@ export function parseNavHtml(html: string, baseDir: vscodeTypes.Uri): EpubTocIte
/**
* Parses EPUB 2 NCX XML into TOC items.
*/
export function parseNcxXml(xml: string, baseDir: vscodeTypes.Uri): EpubTocItem[] {
export function parseNcxXml(xml: string, baseDir: ResourceUri): EpubTocItem[] {
const items: EpubTocItem[] = [];
const navPointRegex = /<navPoint\b[^>]*>([\s\S]*?)<\/navPoint>/gi;
let pointMatch: RegExpExecArray | null;
Expand Down Expand Up @@ -230,7 +249,7 @@ export function parseNcxXml(xml: string, baseDir: vscodeTypes.Uri): EpubTocItem[
*/
export async function loadEpubToc(
epub: EpubPackage,
readFileText: (uri: vscodeTypes.Uri) => Promise<string>
readFileText: (uri: ResourceUri) => Promise<string>
): Promise<EpubTocItem[]> {
// 1. Try finding nav item in manifest with properties="nav"
for (const item of epub.manifest.values()) {
Expand Down Expand Up @@ -296,21 +315,22 @@ function decodeXmlEntities(text: string): string {
.replace(/&#([0-9]+);/g, (_, dec) => String.fromCharCode(parseInt(dec, 10)));
}

function parentUri(uri: vscodeTypes.Uri): vscodeTypes.Uri {
export function parentUri(uri: ResourceUri): ResourceUri {
const path = uri.path.slice(0, uri.path.lastIndexOf('/'));
return uri.with ? uri.with({ path }) : ({ ...uri, path } as vscodeTypes.Uri);
return uri.with ? uri.with({ path }) : {
...uri,
path,
toString: () => path
};
}

function joinPath(base: vscodeTypes.Uri, ...segments: string[]): vscodeTypes.Uri {
if (vscodeModule) {
return vscodeModule.Uri.joinPath(base, ...segments);
}
export function joinPath(base: ResourceUri, ...segments: string[]): ResourceUri {
const cleanBase = base.path.replace(/\/+$/, '');
const cleanSegments = segments.map((s) => s.replace(/^\/+|\/+$/g, '')).filter(Boolean);
const newPath = cleanBase + '/' + cleanSegments.join('/');
return {
return base.with ? base.with({ path: newPath }) : {
...base,
path: newPath,
toString: () => newPath
} as vscodeTypes.Uri;
};
}
30 changes: 25 additions & 5 deletions src/reader-shell.ts β†’ src/core/reader-shell.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import * as vscode from 'vscode';
import * as path from 'node:path';
import { randomBytes } from 'node:crypto';
import { ReaderPreferences, ReadingLocation, DEFAULT_PREFERENCES } from './state-manager';
import { ResourceUri } from './epub';

export interface ReaderTocItem {
label: string;
Expand Down Expand Up @@ -89,19 +90,24 @@ const PHOSPHOR = {
x: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="14" height="14" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="20" aria-hidden="true"><line x1="200" y1="56" x2="56" y2="200"/><line x1="200" y1="200" x2="56" y2="56"/></svg>`
};

export interface ReaderWebviewLike {
cspSource: string;
}

export function readerShell(
content: string,
source: vscode.Uri,
source: ResourceUri | string,
fragment: string | undefined,
webview: vscode.Webview,
webview: ReaderWebviewLike,
navInfo?: ReaderNavInfo,
preferences?: ReaderPreferences,
initialLocation?: ReadingLocation,
resetToTop = false,
startAtBottom = false
): string {
const nonce = randomBytes(16).toString('base64');
const title = escapeHtml(vscode.workspace.asRelativePath(source, false) || source.fsPath);
const sourcePath = typeof source === 'string' ? source : (source.fsPath || source.path);
const title = escapeHtml(navInfo?.bookTitle ? `${navInfo.bookTitle} - ${path.basename(sourcePath)}` : path.basename(sourcePath));
const initialFragment = escapeHtml(fragment ?? '');

const prefs: ReaderPreferences = {
Expand Down Expand Up @@ -1505,7 +1511,21 @@ export function readerShell(
history.scrollRestoration = 'manual';
}

const vscode = acquireVsCodeApi();
const vscode = typeof acquireVsCodeApi === 'function' ? acquireVsCodeApi() : {
postMessage: function(msg) {
if (window.parent && window.parent !== window) {
window.parent.postMessage(msg, '*');
} else {
fetch('/api/message', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(msg)
}).catch(function(err) {
console.warn('Sidecar message dispatch failed:', err);
});
}
}
};
const popover = document.getElementById('footnote-popover');
const caret = document.getElementById('footnote-caret');
const noteContent = document.getElementById('footnote-content');
Expand Down
77 changes: 76 additions & 1 deletion src/state-manager.ts β†’ src/core/state-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,82 @@ export class NavigationHistory {

export interface MementoLike {
get<T>(key: string, defaultValue?: T): T;
update(key: string, value: unknown): Thenable<void> | Promise<void>;
update(key: string, value: unknown): Promise<void> | PromiseLike<void>;
}

export type StateStorageAdapter = MementoLike;

export class InMemoryStorageAdapter implements StateStorageAdapter {
private data = new Map<string, unknown>();

get<T>(key: string, defaultValue?: T): T {
if (this.data.has(key)) {
return this.data.get(key) as T;
}
return defaultValue as T;
}

async update(key: string, value: unknown): Promise<void> {
if (value === undefined) {
this.data.delete(key);
} else {
this.data.set(key, value);
}
}
}

export class JsonFileStorageAdapter implements StateStorageAdapter {
private inMemory = new Map<string, unknown>();
private loaded = false;

constructor(private readonly filePath: string) {}

private async load(): Promise<void> {
if (this.loaded) return;
try {
const fs = await import('node:fs/promises');
const raw = await fs.readFile(this.filePath, 'utf-8');
const parsed = JSON.parse(raw);
for (const [k, v] of Object.entries(parsed)) {
this.inMemory.set(k, v);
}
} catch {
// file might not exist yet, ignore
}
this.loaded = true;
}

private async persist(): Promise<void> {
try {
const fs = await import('node:fs/promises');
const path = await import('node:path');
await fs.mkdir(path.dirname(this.filePath), { recursive: true });
const obj: Record<string, unknown> = {};
for (const [k, v] of this.inMemory.entries()) {
obj[k] = v;
}
await fs.writeFile(this.filePath, JSON.stringify(obj, null, 2), 'utf-8');
} catch (err) {
console.warn('Failed to persist state storage to JSON file:', err);
}
}

get<T>(key: string, defaultValue?: T): T {
if (this.inMemory.has(key)) {
return this.inMemory.get(key) as T;
}
return defaultValue as T;
}

async update(key: string, value: unknown): Promise<void> {
await this.load();
if (value === undefined) {
this.inMemory.delete(key);
} else {
this.inMemory.set(key, value);
}
await this.persist();
}
}

export const DEFAULT_PREFERENCES: ReaderPreferences = {
Expand Down
File renamed without changes.
Loading
Loading