feat: implement typst template system with validation (task 6)
Adds comprehensive template management system for Typst PDF export: • TemplateManager: Built-in and custom template support with 4 embedded templates • TemplateSubstitution: Variable processing with Typst character escaping • TemplateValidator: Syntax validation, structure checks, and feature detection • Complete TypeScript type definitions for template system Supports Typst 0.11+ features and provides robust error handling. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
6 files changed
+1647
-6
No files matched your search
@@ -0,0 +1,13 @@
|
||||
// Template System Exports
|
||||
export { TemplateManager } from './template-manager';
|
||||
export { TemplateSubstitution } from './template-substitution';
|
||||
export { TemplateValidator } from './template-validator';
|
||||
|
||||
// Type Exports
|
||||
export type {
|
||||
Template,
|
||||
TemplateVariable,
|
||||
TemplateMetadata,
|
||||
TemplateValidationResult,
|
||||
SubstitutionContext
|
||||
} from './types';
|
||||
@@ -0,0 +1,863 @@
|
||||
import { App, normalizePath, TFile, TFolder, Notice } from 'obsidian';
|
||||
import { Template, TemplateVariable, TemplateMetadata, TemplateValidationResult, SubstitutionContext } from './types';
|
||||
import { TemplateSubstitution } from './template-substitution';
|
||||
import { TemplateValidator } from './template-validator';
|
||||
|
||||
/**
|
||||
* Manages Typst templates, including built-in and custom user templates
|
||||
*/
|
||||
export class TemplateManager {
|
||||
private app: App;
|
||||
private builtInTemplates: Map<string, string> = new Map();
|
||||
private customTemplates: Map<string, Template> = new Map();
|
||||
private customTemplateDirectory: string = 'Typst Templates';
|
||||
|
||||
constructor(app: App, customTemplateDirectory?: string) {
|
||||
this.app = app;
|
||||
if (customTemplateDirectory) {
|
||||
this.customTemplateDirectory = customTemplateDirectory;
|
||||
}
|
||||
this.initializeBuiltInTemplates();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize built-in Typst templates with modern 0.11+ syntax
|
||||
*/
|
||||
private initializeBuiltInTemplates(): void {
|
||||
// Default template - basic document
|
||||
this.builtInTemplates.set('default.typ', `#set page(
|
||||
paper: "a4",
|
||||
margin: (x: 2.5cm, y: 2cm)
|
||||
)
|
||||
#set text(
|
||||
font: "Liberation Serif",
|
||||
size: 12pt,
|
||||
lang: "en"
|
||||
)
|
||||
#set par(justify: true, leading: 0.65em)
|
||||
#set heading(numbering: "1.")
|
||||
|
||||
#if "$title$" != "" [
|
||||
#align(center, text(18pt, weight: "bold")[$title$])
|
||||
#v(1em)
|
||||
]
|
||||
|
||||
#if "$author$" != "" [
|
||||
#align(center, text(14pt)[$author$])
|
||||
#v(0.5em)
|
||||
]
|
||||
|
||||
#if "$date$" != "" [
|
||||
#align(center, text(12pt)[$date$])
|
||||
#v(2em)
|
||||
]
|
||||
|
||||
$body$`);
|
||||
|
||||
// Article template - academic paper style
|
||||
this.builtInTemplates.set('article.typ', `#set page(
|
||||
paper: "a4",
|
||||
margin: (x: 2.5cm, y: 2cm),
|
||||
numbering: "1"
|
||||
)
|
||||
#set text(
|
||||
font: "Liberation Serif",
|
||||
size: 11pt,
|
||||
lang: "en"
|
||||
)
|
||||
#set par(justify: true, leading: 0.65em, first-line-indent: 1.2em)
|
||||
#set heading(numbering: "1.")
|
||||
|
||||
#show heading.where(level: 1): it => block(
|
||||
width: 100%,
|
||||
below: 1.5em,
|
||||
above: 2em,
|
||||
)[
|
||||
#set align(center)
|
||||
#set text(16pt, weight: "bold")
|
||||
#it.body
|
||||
]
|
||||
|
||||
#show heading.where(level: 2): it => block(
|
||||
width: 100%,
|
||||
below: 1em,
|
||||
above: 1.5em,
|
||||
)[
|
||||
#set text(13pt, weight: "bold")
|
||||
#it
|
||||
]
|
||||
|
||||
#if "$title$" != "" [
|
||||
#align(center, text(20pt, weight: "bold")[$title$])
|
||||
#v(1em)
|
||||
]
|
||||
|
||||
#if "$author$" != "" [
|
||||
#align(center, text(14pt)[$author$])
|
||||
#v(0.5em)
|
||||
]
|
||||
|
||||
#if "$date$" != "" [
|
||||
#align(center, text(12pt)[$date$])
|
||||
#v(2em)
|
||||
]
|
||||
|
||||
$body$`);
|
||||
|
||||
// Report template - formal report style
|
||||
this.builtInTemplates.set('report.typ', `#set page(
|
||||
paper: "a4",
|
||||
margin: (x: 2.5cm, y: 2.5cm),
|
||||
numbering: "1",
|
||||
header: context {
|
||||
if counter(page).get().first() > 1 [
|
||||
#align(right)[$title$]
|
||||
#line(length: 100%)
|
||||
]
|
||||
}
|
||||
)
|
||||
#set text(
|
||||
font: "Liberation Serif",
|
||||
size: 12pt,
|
||||
lang: "en"
|
||||
)
|
||||
#set par(justify: true, leading: 0.65em)
|
||||
#set heading(numbering: "1.")
|
||||
|
||||
#show heading.where(level: 1): it => pagebreak(weak: true) + block(
|
||||
width: 100%,
|
||||
below: 2em,
|
||||
above: 0pt,
|
||||
)[
|
||||
#set align(center)
|
||||
#set text(18pt, weight: "bold")
|
||||
#counter(heading).display()
|
||||
#h(0.5em)
|
||||
#it.body
|
||||
]
|
||||
|
||||
#show heading.where(level: 2): it => block(
|
||||
width: 100%,
|
||||
below: 1em,
|
||||
above: 1.5em,
|
||||
)[
|
||||
#set text(14pt, weight: "bold")
|
||||
#it
|
||||
]
|
||||
|
||||
// Title page
|
||||
#page()[
|
||||
#align(center + horizon)[
|
||||
#if "$title$" != "" [
|
||||
#text(24pt, weight: "bold")[$title$]
|
||||
#v(2em)
|
||||
]
|
||||
|
||||
#if "$author$" != "" [
|
||||
#text(16pt)[$author$]
|
||||
#v(1em)
|
||||
]
|
||||
|
||||
#if "$date$" != "" [
|
||||
#text(14pt)[$date$]
|
||||
]
|
||||
]
|
||||
]
|
||||
|
||||
$body$`);
|
||||
|
||||
// Single-page template - auto-adjusting height
|
||||
this.builtInTemplates.set('single-page.typ', `#set page(
|
||||
paper: "a4",
|
||||
margin: (x: 2.5cm, y: 2cm),
|
||||
height: auto
|
||||
)
|
||||
#set text(
|
||||
font: "Liberation Serif",
|
||||
size: 12pt,
|
||||
lang: "en"
|
||||
)
|
||||
#set par(justify: true, leading: 0.65em)
|
||||
#set heading(numbering: "1.")
|
||||
|
||||
#show heading.where(level: 1): it => block(
|
||||
width: 100%,
|
||||
below: 1.5em,
|
||||
above: 1.5em,
|
||||
)[
|
||||
#set text(16pt, weight: "bold")
|
||||
#it
|
||||
]
|
||||
|
||||
#show heading.where(level: 2): it => block(
|
||||
width: 100%,
|
||||
below: 1em,
|
||||
above: 1em,
|
||||
)[
|
||||
#set text(14pt, weight: "bold")
|
||||
#it
|
||||
]
|
||||
|
||||
#if "$title$" != "" [
|
||||
#align(center, text(18pt, weight: "bold")[$title$])
|
||||
#v(1em)
|
||||
]
|
||||
|
||||
#if "$author$" != "" [
|
||||
#align(center, text(14pt)[$author$])
|
||||
#v(0.5em)
|
||||
]
|
||||
|
||||
#if "$date$" != "" [
|
||||
#align(center, text(12pt)[$date$])
|
||||
#v(2em)
|
||||
]
|
||||
|
||||
$body$`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get available template names
|
||||
*/
|
||||
getAvailableTemplates(): string[] {
|
||||
const builtIn = Array.from(this.builtInTemplates.keys());
|
||||
const custom = Array.from(this.customTemplates.keys()).map(name => `${name}.typ`);
|
||||
return [...builtIn, ...custom];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get template content by name
|
||||
*/
|
||||
getTemplate(templateName: string): string | null {
|
||||
// Check built-in templates first
|
||||
if (this.builtInTemplates.has(templateName)) {
|
||||
return this.builtInTemplates.get(templateName) || null;
|
||||
}
|
||||
|
||||
// Check custom templates
|
||||
const customKey = templateName.replace('.typ', '');
|
||||
if (this.customTemplates.has(customKey)) {
|
||||
const template = this.customTemplates.get(customKey);
|
||||
// For custom templates, we'll need to load the file content
|
||||
// This will be implemented in the next subtask
|
||||
return template?.filePath || null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a template exists
|
||||
*/
|
||||
hasTemplate(templateName: string): boolean {
|
||||
return this.builtInTemplates.has(templateName) ||
|
||||
this.customTemplates.has(templateName.replace('.typ', ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get template metadata
|
||||
*/
|
||||
getTemplateInfo(templateName: string): Partial<Template> | null {
|
||||
if (this.builtInTemplates.has(templateName)) {
|
||||
return {
|
||||
name: templateName.replace('.typ', ''),
|
||||
variables: this.extractVariables(this.builtInTemplates.get(templateName) || ''),
|
||||
metadata: {
|
||||
author: 'Obsidian Typst PDF Export',
|
||||
version: '1.0.0',
|
||||
description: this.getBuiltInDescription(templateName),
|
||||
compatibility: ['0.11.0', '0.12.0']
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const customKey = templateName.replace('.typ', '');
|
||||
if (this.customTemplates.has(customKey)) {
|
||||
return this.customTemplates.get(customKey) || null;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract variables from template content
|
||||
*/
|
||||
private extractVariables(templateContent: string): Record<string, any> {
|
||||
const variables: Record<string, any> = {};
|
||||
const variablePattern = /\$(\w+)\$/g;
|
||||
let match;
|
||||
|
||||
while ((match = variablePattern.exec(templateContent)) !== null) {
|
||||
const varName = match[1];
|
||||
variables[varName] = {
|
||||
type: 'string',
|
||||
defaultValue: '',
|
||||
description: this.getVariableDescription(varName),
|
||||
required: this.isVariableRequired(varName, templateContent)
|
||||
};
|
||||
}
|
||||
|
||||
return variables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get description for common template variables
|
||||
*/
|
||||
private getVariableDescription(varName: string): string {
|
||||
const descriptions: Record<string, string> = {
|
||||
'title': 'Document title',
|
||||
'author': 'Document author',
|
||||
'date': 'Document date',
|
||||
'body': 'Main document content',
|
||||
'font': 'Font family',
|
||||
'fontSize': 'Font size',
|
||||
'pageSize': 'Page size (e.g., a4, us-letter)',
|
||||
'margins': 'Page margins'
|
||||
};
|
||||
|
||||
return descriptions[varName] || `Template variable: ${varName}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a variable is required based on template usage
|
||||
*/
|
||||
private isVariableRequired(varName: string, templateContent: string): boolean {
|
||||
// Body is always required
|
||||
if (varName === 'body') return true;
|
||||
|
||||
// Check if variable is used in conditional blocks
|
||||
const conditionalPattern = new RegExp(`#if.*\\$${varName}\\$.*!=.*""`, 'g');
|
||||
return !conditionalPattern.test(templateContent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get built-in template descriptions
|
||||
*/
|
||||
private getBuiltInDescription(templateName: string): string {
|
||||
const descriptions: Record<string, string> = {
|
||||
'default.typ': 'Basic document template with title, author, and date',
|
||||
'article.typ': 'Academic article template with proper formatting',
|
||||
'report.typ': 'Formal report template with title page and headers',
|
||||
'single-page.typ': 'Single page template with auto-adjusting height'
|
||||
};
|
||||
|
||||
return descriptions[templateName] || 'Built-in Typst template';
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover and load custom templates from the configured directory
|
||||
*/
|
||||
async discoverCustomTemplates(): Promise<void> {
|
||||
try {
|
||||
const templateFolder = this.app.vault.getAbstractFileByPath(this.customTemplateDirectory);
|
||||
|
||||
if (!templateFolder || !(templateFolder instanceof TFolder)) {
|
||||
// Create the template directory if it doesn't exist
|
||||
await this.createTemplateDirectory();
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear existing custom templates
|
||||
this.customTemplates.clear();
|
||||
|
||||
// Process all .typ files in the directory
|
||||
const typFiles = templateFolder.children.filter(
|
||||
(file): file is TFile => file instanceof TFile && file.extension === 'typ'
|
||||
);
|
||||
|
||||
for (const file of typFiles) {
|
||||
await this.loadCustomTemplate(file);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error discovering custom templates:', error);
|
||||
new Notice('Failed to discover custom templates');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load a custom template from a file
|
||||
*/
|
||||
private async loadCustomTemplate(file: TFile): Promise<void> {
|
||||
try {
|
||||
const content = await this.app.vault.read(file);
|
||||
const templateName = file.basename;
|
||||
|
||||
// Extract metadata from template comments
|
||||
const metadata = this.extractTemplateMetadata(content, file);
|
||||
|
||||
// Extract variables from template
|
||||
const variables = this.extractTemplateVariables(content);
|
||||
|
||||
const template: Template = {
|
||||
name: templateName,
|
||||
filePath: file.path,
|
||||
variables,
|
||||
metadata
|
||||
};
|
||||
|
||||
this.customTemplates.set(templateName, template);
|
||||
|
||||
} catch (error) {
|
||||
console.error(`Error loading custom template ${file.path}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract metadata from template comments
|
||||
*/
|
||||
private extractTemplateMetadata(content: string, file: TFile): TemplateMetadata {
|
||||
const metadata: TemplateMetadata = {
|
||||
compatibility: ['0.11.0', '0.12.0']
|
||||
};
|
||||
|
||||
// Look for metadata in comments at the top of the file
|
||||
const lines = content.split('\n');
|
||||
let inMetadataBlock = false;
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
|
||||
// Check for metadata block start
|
||||
if (trimmed.startsWith('/*') && trimmed.includes('@template-meta')) {
|
||||
inMetadataBlock = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check for metadata block end
|
||||
if (trimmed.includes('*/')) {
|
||||
inMetadataBlock = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (inMetadataBlock) {
|
||||
// Parse metadata lines
|
||||
const metaMatch = trimmed.match(/^\s*\*?\s*@(\w+):\s*(.+)$/);
|
||||
if (metaMatch) {
|
||||
const [, key, value] = metaMatch;
|
||||
switch (key) {
|
||||
case 'author':
|
||||
metadata.author = value.trim();
|
||||
break;
|
||||
case 'version':
|
||||
metadata.version = value.trim();
|
||||
break;
|
||||
case 'description':
|
||||
metadata.description = value.trim();
|
||||
break;
|
||||
case 'compatibility':
|
||||
metadata.compatibility = value.split(',').map(v => v.trim());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Set defaults if not found
|
||||
if (!metadata.description) {
|
||||
metadata.description = `Custom template: ${file.basename}`;
|
||||
}
|
||||
if (!metadata.author) {
|
||||
metadata.author = 'Custom';
|
||||
}
|
||||
if (!metadata.version) {
|
||||
metadata.version = '1.0.0';
|
||||
}
|
||||
|
||||
return metadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract variables from template with enhanced detection
|
||||
*/
|
||||
private extractTemplateVariables(content: string): Record<string, TemplateVariable> {
|
||||
const variables: Record<string, TemplateVariable> = {};
|
||||
const foundVariables = TemplateSubstitution.extractVariables(content);
|
||||
|
||||
for (const varName of foundVariables) {
|
||||
variables[varName] = {
|
||||
type: this.inferVariableType(varName),
|
||||
defaultValue: this.getDefaultValueForVariable(varName),
|
||||
description: this.getVariableDescription(varName),
|
||||
required: this.isVariableRequired(varName, content)
|
||||
};
|
||||
}
|
||||
|
||||
return variables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer variable type based on name patterns
|
||||
*/
|
||||
private inferVariableType(varName: string): 'string' | 'number' | 'boolean' {
|
||||
const numberPatterns = /^(size|width|height|margin|count|number|page)/i;
|
||||
const booleanPatterns = /^(show|hide|enable|disable|is|has)/i;
|
||||
|
||||
if (numberPatterns.test(varName)) return 'number';
|
||||
if (booleanPatterns.test(varName)) return 'boolean';
|
||||
return 'string';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default value based on variable type and name
|
||||
*/
|
||||
private getDefaultValueForVariable(varName: string): any {
|
||||
const type = this.inferVariableType(varName);
|
||||
|
||||
if (type === 'boolean') return false;
|
||||
if (type === 'number') {
|
||||
if (varName.includes('size')) return 12;
|
||||
if (varName.includes('margin')) return 2.5;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// String defaults
|
||||
const stringDefaults: Record<string, string> = {
|
||||
'title': '',
|
||||
'author': '',
|
||||
'date': new Date().toLocaleDateString(),
|
||||
'font': 'Liberation Serif',
|
||||
'fontSize': '12pt',
|
||||
'pageSize': 'a4',
|
||||
'margins': '2.5cm',
|
||||
'body': ''
|
||||
};
|
||||
|
||||
return stringDefaults[varName] || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the template directory if it doesn't exist
|
||||
*/
|
||||
private async createTemplateDirectory(): Promise<void> {
|
||||
try {
|
||||
await this.app.vault.createFolder(this.customTemplateDirectory);
|
||||
|
||||
// Create a sample template
|
||||
const sampleTemplate = `/*
|
||||
@template-meta
|
||||
@author: Your Name
|
||||
@version: 1.0.0
|
||||
@description: Sample custom template
|
||||
@compatibility: 0.11.0, 0.12.0
|
||||
*/
|
||||
|
||||
#set page(
|
||||
paper: "a4",
|
||||
margin: (x: 2.5cm, y: 2cm)
|
||||
)
|
||||
#set text(
|
||||
font: "$font$",
|
||||
size: 12pt,
|
||||
lang: "en"
|
||||
)
|
||||
#set par(justify: true)
|
||||
|
||||
#if "$title$" != "" [
|
||||
#align(center, text(16pt, weight: "bold")[$title$])
|
||||
#v(1em)
|
||||
]
|
||||
|
||||
$body$`;
|
||||
|
||||
const samplePath = normalizePath(`${this.customTemplateDirectory}/sample.typ`);
|
||||
await this.app.vault.create(samplePath, sampleTemplate);
|
||||
|
||||
new Notice(`Created template directory at: ${this.customTemplateDirectory}`);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error creating template directory:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get custom template directory path
|
||||
*/
|
||||
getCustomTemplateDirectory(): string {
|
||||
return this.customTemplateDirectory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set custom template directory and refresh templates
|
||||
*/
|
||||
async setCustomTemplateDirectory(directory: string): Promise<void> {
|
||||
this.customTemplateDirectory = directory;
|
||||
await this.discoverCustomTemplates();
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh custom templates (re-scan directory)
|
||||
*/
|
||||
async refreshCustomTemplates(): Promise<void> {
|
||||
await this.discoverCustomTemplates();
|
||||
new Notice('Custom templates refreshed');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get template content by name (enhanced to handle custom templates)
|
||||
*/
|
||||
async getTemplateContent(templateName: string): Promise<string | null> {
|
||||
// Check built-in templates first
|
||||
if (this.builtInTemplates.has(templateName)) {
|
||||
return this.builtInTemplates.get(templateName) || null;
|
||||
}
|
||||
|
||||
// Check custom templates
|
||||
const customKey = templateName.replace('.typ', '');
|
||||
if (this.customTemplates.has(customKey)) {
|
||||
const template = this.customTemplates.get(customKey);
|
||||
if (template) {
|
||||
try {
|
||||
const file = this.app.vault.getAbstractFileByPath(template.filePath) as TFile;
|
||||
if (file) {
|
||||
return await this.app.vault.read(file);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error reading custom template ${template.filePath}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if custom templates directory exists
|
||||
*/
|
||||
customTemplateDirectoryExists(): boolean {
|
||||
const folder = this.app.vault.getAbstractFileByPath(this.customTemplateDirectory);
|
||||
return folder instanceof TFolder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a template by name
|
||||
*/
|
||||
async validateTemplate(templateName: string, context?: SubstitutionContext): Promise<TemplateValidationResult> {
|
||||
const templateContent = await this.getTemplateContent(templateName);
|
||||
|
||||
if (!templateContent) {
|
||||
return {
|
||||
isValid: false,
|
||||
errors: [`Template '${templateName}' not found`],
|
||||
warnings: [],
|
||||
variables: []
|
||||
};
|
||||
}
|
||||
|
||||
return TemplateValidator.validateTemplate(templateContent, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate all templates and return a summary
|
||||
*/
|
||||
async validateAllTemplates(): Promise<{
|
||||
builtInResults: Map<string, TemplateValidationResult>;
|
||||
customResults: Map<string, TemplateValidationResult>;
|
||||
summary: {
|
||||
totalTemplates: number;
|
||||
validTemplates: number;
|
||||
invalidTemplates: number;
|
||||
templatesWithWarnings: number;
|
||||
};
|
||||
}> {
|
||||
const builtInResults = new Map<string, TemplateValidationResult>();
|
||||
const customResults = new Map<string, TemplateValidationResult>();
|
||||
|
||||
// Validate built-in templates
|
||||
for (const [templateName, content] of this.builtInTemplates) {
|
||||
const result = TemplateValidator.validateTemplate(content);
|
||||
builtInResults.set(templateName, result);
|
||||
}
|
||||
|
||||
// Validate custom templates
|
||||
for (const [templateName, template] of this.customTemplates) {
|
||||
try {
|
||||
const content = await this.getTemplateContent(templateName + '.typ');
|
||||
if (content) {
|
||||
const result = TemplateValidator.validateTemplate(content);
|
||||
customResults.set(templateName, result);
|
||||
}
|
||||
} catch (error) {
|
||||
customResults.set(templateName, {
|
||||
isValid: false,
|
||||
errors: [`Error loading template: ${error.message}`],
|
||||
warnings: [],
|
||||
variables: []
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate summary
|
||||
const allResults = [...builtInResults.values(), ...customResults.values()];
|
||||
const summary = {
|
||||
totalTemplates: allResults.length,
|
||||
validTemplates: allResults.filter(r => r.isValid).length,
|
||||
invalidTemplates: allResults.filter(r => !r.isValid).length,
|
||||
templatesWithWarnings: allResults.filter(r => r.warnings.length > 0).length
|
||||
};
|
||||
|
||||
return { builtInResults, customResults, summary };
|
||||
}
|
||||
|
||||
/**
|
||||
* Process template with variable substitution and validation
|
||||
*/
|
||||
async processTemplate(templateName: string, context: SubstitutionContext): Promise<{
|
||||
content: string;
|
||||
validation: TemplateValidationResult;
|
||||
}> {
|
||||
const templateContent = await this.getTemplateContent(templateName);
|
||||
|
||||
if (!templateContent) {
|
||||
throw new Error(`Template '${templateName}' not found`);
|
||||
}
|
||||
|
||||
// Validate template with context
|
||||
const validation = TemplateValidator.validateTemplate(templateContent, context);
|
||||
|
||||
if (!validation.isValid) {
|
||||
const errorMsg = `Template validation failed: ${validation.errors.join(', ')}`;
|
||||
throw new Error(errorMsg);
|
||||
}
|
||||
|
||||
// Substitute variables
|
||||
const processedContent = TemplateSubstitution.substitute(templateContent, context);
|
||||
|
||||
return {
|
||||
content: processedContent,
|
||||
validation
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview template processing without throwing errors
|
||||
*/
|
||||
async previewTemplate(templateName: string, context: SubstitutionContext): Promise<{
|
||||
content: string;
|
||||
validation: TemplateValidationResult;
|
||||
substitutions: { variable: string; value: string }[];
|
||||
}> {
|
||||
const templateContent = await this.getTemplateContent(templateName);
|
||||
|
||||
if (!templateContent) {
|
||||
return {
|
||||
content: '',
|
||||
validation: {
|
||||
isValid: false,
|
||||
errors: [`Template '${templateName}' not found`],
|
||||
warnings: [],
|
||||
variables: []
|
||||
},
|
||||
substitutions: []
|
||||
};
|
||||
}
|
||||
|
||||
// Validate template
|
||||
const validation = TemplateValidator.validateTemplate(templateContent, context);
|
||||
|
||||
// Preview substitution
|
||||
const { preview, substitutions } = TemplateSubstitution.previewSubstitution(templateContent, context);
|
||||
|
||||
return {
|
||||
content: preview,
|
||||
validation,
|
||||
substitutions
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get detailed template analysis
|
||||
*/
|
||||
async analyzeTemplate(templateName: string): Promise<{
|
||||
info: Partial<Template>;
|
||||
analysis: {
|
||||
totalVariables: number;
|
||||
uniqueVariables: string[];
|
||||
requiredVariables: string[];
|
||||
optionalVariables: string[];
|
||||
variableFrequency: Record<string, number>;
|
||||
};
|
||||
validation: TemplateValidationResult;
|
||||
}> {
|
||||
const templateContent = await this.getTemplateContent(templateName);
|
||||
const info = this.getTemplateInfo(templateName);
|
||||
|
||||
if (!templateContent) {
|
||||
throw new Error(`Template '${templateName}' not found`);
|
||||
}
|
||||
|
||||
const analysis = TemplateSubstitution.analyzeTemplate(templateContent);
|
||||
const validation = TemplateValidator.validateTemplate(templateContent);
|
||||
|
||||
return {
|
||||
info: info || {},
|
||||
analysis,
|
||||
validation
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check template health and compatibility
|
||||
*/
|
||||
async checkTemplateHealth(templateName: string): Promise<{
|
||||
isHealthy: boolean;
|
||||
issues: string[];
|
||||
recommendations: string[];
|
||||
compatibility: {
|
||||
typstVersion: string[];
|
||||
features: string[];
|
||||
};
|
||||
}> {
|
||||
const templateContent = await this.getTemplateContent(templateName);
|
||||
|
||||
if (!templateContent) {
|
||||
return {
|
||||
isHealthy: false,
|
||||
issues: [`Template '${templateName}' not found`],
|
||||
recommendations: [],
|
||||
compatibility: { typstVersion: [], features: [] }
|
||||
};
|
||||
}
|
||||
|
||||
const validation = TemplateValidator.validateTemplate(templateContent);
|
||||
const issues: string[] = [...validation.errors, ...validation.warnings];
|
||||
const recommendations: string[] = [];
|
||||
|
||||
// Add specific recommendations based on analysis
|
||||
if (!templateContent.includes('#set page')) {
|
||||
recommendations.push('Consider adding page setup (#set page) for better layout control');
|
||||
}
|
||||
|
||||
if (!templateContent.includes('#set text')) {
|
||||
recommendations.push('Consider adding text configuration (#set text) for consistent typography');
|
||||
}
|
||||
|
||||
if (validation.variables.length === 1 && validation.variables[0] === 'body') {
|
||||
recommendations.push('Template only uses body variable. Consider adding title, author, or date variables for more flexibility');
|
||||
}
|
||||
|
||||
// Detect compatibility requirements
|
||||
const typstVersions = ['0.11.0', '0.12.0'];
|
||||
const features: string[] = [];
|
||||
|
||||
if (templateContent.includes('height: auto')) {
|
||||
features.push('Dynamic page height');
|
||||
}
|
||||
if (templateContent.includes('#context')) {
|
||||
features.push('Context blocks');
|
||||
}
|
||||
if (templateContent.includes('scope: "parent"')) {
|
||||
features.push('Parent scope placement');
|
||||
}
|
||||
|
||||
return {
|
||||
isHealthy: validation.isValid && validation.warnings.length === 0,
|
||||
issues,
|
||||
recommendations,
|
||||
compatibility: {
|
||||
typstVersion: typstVersions,
|
||||
features
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { SubstitutionContext, TemplateValidationResult } from './types';
|
||||
|
||||
/**
|
||||
* Handles variable substitution in Typst templates
|
||||
*/
|
||||
export class TemplateSubstitution {
|
||||
|
||||
/**
|
||||
* Substitute variables in template content
|
||||
*/
|
||||
static substitute(templateContent: string, context: SubstitutionContext): string {
|
||||
let result = templateContent;
|
||||
|
||||
// Extract all variables from template
|
||||
const variables = this.extractVariables(templateContent);
|
||||
|
||||
// Process each variable
|
||||
for (const variable of variables) {
|
||||
const value = context[variable] || this.getDefaultValue(variable);
|
||||
const escapedValue = this.escapeTypstValue(value);
|
||||
|
||||
// Replace all instances of the variable
|
||||
const variablePattern = new RegExp(`\\$${variable}\\$`, 'g');
|
||||
result = result.replace(variablePattern, escapedValue);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract all variables from template content
|
||||
*/
|
||||
static extractVariables(templateContent: string): string[] {
|
||||
const variables: string[] = [];
|
||||
const variablePattern = /\$(\w+)\$/g;
|
||||
let match;
|
||||
|
||||
while ((match = variablePattern.exec(templateContent)) !== null) {
|
||||
const varName = match[1];
|
||||
if (!variables.includes(varName)) {
|
||||
variables.push(varName);
|
||||
}
|
||||
}
|
||||
|
||||
return variables;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate template and check for missing variables
|
||||
*/
|
||||
static validate(templateContent: string, context: SubstitutionContext): TemplateValidationResult {
|
||||
const result: TemplateValidationResult = {
|
||||
isValid: true,
|
||||
errors: [],
|
||||
warnings: [],
|
||||
variables: []
|
||||
};
|
||||
|
||||
// Extract variables from template
|
||||
const templateVariables = this.extractVariables(templateContent);
|
||||
result.variables = templateVariables;
|
||||
|
||||
// Check for required variables
|
||||
const requiredVariables = ['body']; // body is always required
|
||||
|
||||
for (const variable of requiredVariables) {
|
||||
if (templateVariables.includes(variable) && !context[variable]) {
|
||||
result.errors.push(`Required variable '${variable}' is missing`);
|
||||
result.isValid = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for undefined variables
|
||||
for (const variable of templateVariables) {
|
||||
if (!context[variable] && !this.hasDefaultValue(variable)) {
|
||||
result.warnings.push(`Variable '${variable}' is undefined and has no default value`);
|
||||
}
|
||||
}
|
||||
|
||||
// Basic syntax validation
|
||||
try {
|
||||
this.validateTypstSyntax(templateContent);
|
||||
} catch (error) {
|
||||
result.errors.push(`Template syntax error: ${error.message}`);
|
||||
result.isValid = false;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get default value for common variables
|
||||
*/
|
||||
private static getDefaultValue(variable: string): string {
|
||||
const defaults: Record<string, string> = {
|
||||
'title': '',
|
||||
'author': '',
|
||||
'date': new Date().toLocaleDateString(),
|
||||
'font': 'Liberation Serif',
|
||||
'fontSize': '12pt',
|
||||
'pageSize': 'a4',
|
||||
'margins': '2.5cm',
|
||||
'body': ''
|
||||
};
|
||||
|
||||
return defaults[variable] || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if variable has a default value
|
||||
*/
|
||||
private static hasDefaultValue(variable: string): boolean {
|
||||
const defaults = ['title', 'author', 'date', 'font', 'fontSize', 'pageSize', 'margins'];
|
||||
return defaults.includes(variable);
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape special characters for Typst
|
||||
*/
|
||||
private static escapeTypstValue(value: string): string {
|
||||
if (!value) return '';
|
||||
|
||||
// Escape special Typst characters
|
||||
return value
|
||||
.replace(/\\/g, '\\\\') // Escape backslashes
|
||||
.replace(/\$/g, '\\$') // Escape dollar signs
|
||||
.replace(/#/g, '\\#') // Escape hash symbols
|
||||
.replace(/\[/g, '\\[') // Escape square brackets
|
||||
.replace(/\]/g, '\\]')
|
||||
.replace(/\{/g, '\\{') // Escape curly braces
|
||||
.replace(/\}/g, '\\}')
|
||||
.replace(/</g, '\\<') // Escape angle brackets
|
||||
.replace(/>/g, '\\>');
|
||||
}
|
||||
|
||||
/**
|
||||
* Basic Typst syntax validation
|
||||
*/
|
||||
private static validateTypstSyntax(templateContent: string): void {
|
||||
const errors: string[] = [];
|
||||
|
||||
// Check for balanced brackets
|
||||
const brackets = [
|
||||
{ open: '{', close: '}', name: 'curly braces' },
|
||||
{ open: '[', close: ']', name: 'square brackets' },
|
||||
{ open: '(', close: ')', name: 'parentheses' }
|
||||
];
|
||||
|
||||
for (const bracket of brackets) {
|
||||
const openCount = (templateContent.match(new RegExp(`\\${bracket.open}`, 'g')) || []).length;
|
||||
const closeCount = (templateContent.match(new RegExp(`\\${bracket.close}`, 'g')) || []).length;
|
||||
|
||||
if (openCount !== closeCount) {
|
||||
errors.push(`Unbalanced ${bracket.name}: ${openCount} opening, ${closeCount} closing`);
|
||||
}
|
||||
}
|
||||
|
||||
// Check for malformed function calls
|
||||
const malformedFunctionPattern = /#\w+\s*\(/g;
|
||||
let match;
|
||||
while ((match = malformedFunctionPattern.exec(templateContent)) !== null) {
|
||||
// This is a basic check - in practice, we'd need a more sophisticated parser
|
||||
const functionCall = match[0];
|
||||
if (!this.isValidTypstFunction(functionCall)) {
|
||||
errors.push(`Potentially malformed function call: ${functionCall}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
throw new Error(errors.join('; '));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a function call looks valid (basic heuristic)
|
||||
*/
|
||||
private static isValidTypstFunction(functionCall: string): boolean {
|
||||
const knownFunctions = [
|
||||
'set', 'show', 'let', 'if', 'for', 'while', 'import', 'include',
|
||||
'text', 'page', 'par', 'heading', 'align', 'block', 'box', 'grid',
|
||||
'table', 'image', 'link', 'counter', 'context', 'place', 'lorem'
|
||||
];
|
||||
|
||||
const functionName = functionCall.replace('#', '').replace(/\s*\($/, '');
|
||||
return knownFunctions.includes(functionName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Preview substitution without applying it
|
||||
*/
|
||||
static previewSubstitution(templateContent: string, context: SubstitutionContext): {
|
||||
preview: string;
|
||||
substitutions: { variable: string; value: string }[];
|
||||
} {
|
||||
const variables = this.extractVariables(templateContent);
|
||||
const substitutions = variables.map(variable => ({
|
||||
variable,
|
||||
value: context[variable] || this.getDefaultValue(variable)
|
||||
}));
|
||||
|
||||
const preview = this.substitute(templateContent, context);
|
||||
|
||||
return { preview, substitutions };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get variable usage statistics from template
|
||||
*/
|
||||
static analyzeTemplate(templateContent: string): {
|
||||
totalVariables: number;
|
||||
uniqueVariables: string[];
|
||||
requiredVariables: string[];
|
||||
optionalVariables: string[];
|
||||
variableFrequency: Record<string, number>;
|
||||
} {
|
||||
const allVariables = [];
|
||||
const variablePattern = /\$(\w+)\$/g;
|
||||
let match;
|
||||
|
||||
// Count all variable occurrences
|
||||
while ((match = variablePattern.exec(templateContent)) !== null) {
|
||||
allVariables.push(match[1]);
|
||||
}
|
||||
|
||||
const uniqueVariables = [...new Set(allVariables)];
|
||||
const requiredVariables = ['body'];
|
||||
const optionalVariables = uniqueVariables.filter(v => !requiredVariables.includes(v));
|
||||
|
||||
// Count frequency
|
||||
const variableFrequency: Record<string, number> = {};
|
||||
for (const variable of allVariables) {
|
||||
variableFrequency[variable] = (variableFrequency[variable] || 0) + 1;
|
||||
}
|
||||
|
||||
return {
|
||||
totalVariables: allVariables.length,
|
||||
uniqueVariables,
|
||||
requiredVariables: requiredVariables.filter(v => uniqueVariables.includes(v)),
|
||||
optionalVariables,
|
||||
variableFrequency
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,464 @@
|
||||
import { TemplateValidationResult, SubstitutionContext } from './types';
|
||||
import { TemplateSubstitution } from './template-substitution';
|
||||
|
||||
/**
|
||||
* Comprehensive template validation system
|
||||
*/
|
||||
export class TemplateValidator {
|
||||
|
||||
/**
|
||||
* Validate template content comprehensively
|
||||
*/
|
||||
static validateTemplate(templateContent: string, context?: SubstitutionContext): TemplateValidationResult {
|
||||
const result: TemplateValidationResult = {
|
||||
isValid: true,
|
||||
errors: [],
|
||||
warnings: [],
|
||||
variables: []
|
||||
};
|
||||
|
||||
// Extract variables
|
||||
result.variables = TemplateSubstitution.extractVariables(templateContent);
|
||||
|
||||
// Perform various validation checks
|
||||
this.validateSyntax(templateContent, result);
|
||||
this.validateStructure(templateContent, result);
|
||||
this.validateVariables(templateContent, result, context);
|
||||
this.validateTypstFeatures(templateContent, result);
|
||||
this.validatePageSetup(templateContent, result);
|
||||
|
||||
// Set overall validity
|
||||
result.isValid = result.errors.length === 0;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate basic Typst syntax
|
||||
*/
|
||||
private static validateSyntax(templateContent: string, result: TemplateValidationResult): void {
|
||||
// Check for balanced brackets and parentheses
|
||||
this.validateBrackets(templateContent, result);
|
||||
|
||||
// Check for malformed function calls
|
||||
this.validateFunctionCalls(templateContent, result);
|
||||
|
||||
// Check for invalid characters in variable names
|
||||
this.validateVariableNames(templateContent, result);
|
||||
|
||||
// Check for unclosed strings
|
||||
this.validateStrings(templateContent, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate bracket balance
|
||||
*/
|
||||
private static validateBrackets(templateContent: string, result: TemplateValidationResult): void {
|
||||
const brackets = [
|
||||
{ open: '{', close: '}', name: 'curly braces', stack: [] as number[] },
|
||||
{ open: '[', close: ']', name: 'square brackets', stack: [] as number[] },
|
||||
{ open: '(', close: ')', name: 'parentheses', stack: [] as number[] }
|
||||
];
|
||||
|
||||
const lines = templateContent.split('\n');
|
||||
|
||||
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
|
||||
const line = lines[lineIndex];
|
||||
|
||||
for (let charIndex = 0; charIndex < line.length; charIndex++) {
|
||||
const char = line[charIndex];
|
||||
|
||||
for (const bracket of brackets) {
|
||||
if (char === bracket.open) {
|
||||
bracket.stack.push(lineIndex + 1);
|
||||
} else if (char === bracket.close) {
|
||||
if (bracket.stack.length === 0) {
|
||||
result.errors.push(
|
||||
`Unmatched closing ${bracket.name} at line ${lineIndex + 1}, column ${charIndex + 1}`
|
||||
);
|
||||
} else {
|
||||
bracket.stack.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check for unclosed brackets
|
||||
for (const bracket of brackets) {
|
||||
for (const lineNum of bracket.stack) {
|
||||
result.errors.push(`Unclosed ${bracket.name} starting at line ${lineNum}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate function calls
|
||||
*/
|
||||
private static validateFunctionCalls(templateContent: string, result: TemplateValidationResult): void {
|
||||
const functionPattern = /#(\w+)\s*\(/g;
|
||||
const knownFunctions = [
|
||||
'set', 'show', 'let', 'if', 'for', 'while', 'import', 'include',
|
||||
'text', 'page', 'par', 'heading', 'align', 'block', 'box', 'grid',
|
||||
'table', 'image', 'link', 'counter', 'context', 'place', 'lorem',
|
||||
'v', 'h', 'linebreak', 'pagebreak', 'smallcaps', 'emph', 'strong'
|
||||
];
|
||||
|
||||
let match;
|
||||
while ((match = functionPattern.exec(templateContent)) !== null) {
|
||||
const functionName = match[1];
|
||||
|
||||
if (!knownFunctions.includes(functionName)) {
|
||||
const lineNum = templateContent.substring(0, match.index).split('\n').length;
|
||||
result.warnings.push(
|
||||
`Unknown function '${functionName}' at line ${lineNum}. This may be a custom function or newer Typst feature.`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate variable names
|
||||
*/
|
||||
private static validateVariableNames(templateContent: string, result: TemplateValidationResult): void {
|
||||
const variablePattern = /\$(\w*[^a-zA-Z0-9_]\w*|\d+\w*)\$/g;
|
||||
let match;
|
||||
|
||||
while ((match = variablePattern.exec(templateContent)) !== null) {
|
||||
const varName = match[1];
|
||||
const lineNum = templateContent.substring(0, match.index).split('\n').length;
|
||||
|
||||
if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(varName)) {
|
||||
result.errors.push(
|
||||
`Invalid variable name '${varName}' at line ${lineNum}. Variable names must start with a letter or underscore and contain only letters, numbers, and underscores.`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate string literals
|
||||
*/
|
||||
private static validateStrings(templateContent: string, result: TemplateValidationResult): void {
|
||||
// Check for unclosed string literals
|
||||
const stringPattern = /"([^"\\]|\\.)*"/g;
|
||||
const allQuotes = templateContent.match(/"/g);
|
||||
|
||||
if (allQuotes && allQuotes.length % 2 !== 0) {
|
||||
result.errors.push('Unclosed string literal detected');
|
||||
}
|
||||
|
||||
// Check for unclosed content blocks
|
||||
let bracketCount = 0;
|
||||
let inString = false;
|
||||
let escaped = false;
|
||||
|
||||
for (let i = 0; i < templateContent.length; i++) {
|
||||
const char = templateContent[i];
|
||||
|
||||
if (escaped) {
|
||||
escaped = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === '\\') {
|
||||
escaped = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (char === '"') {
|
||||
inString = !inString;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!inString) {
|
||||
if (char === '[') bracketCount++;
|
||||
else if (char === ']') bracketCount--;
|
||||
}
|
||||
}
|
||||
|
||||
if (bracketCount !== 0) {
|
||||
result.errors.push(`Unbalanced content blocks: ${Math.abs(bracketCount)} ${bracketCount > 0 ? 'unclosed' : 'extra closing'} bracket(s)`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate template structure
|
||||
*/
|
||||
private static validateStructure(templateContent: string, result: TemplateValidationResult): void {
|
||||
// Check for body variable (required for all templates)
|
||||
if (!templateContent.includes('$body$')) {
|
||||
result.errors.push("Template must contain a '$body$' variable to include the main content");
|
||||
}
|
||||
|
||||
// Warn about missing common structural elements
|
||||
const commonElements = ['#set page', '#set text', '#set par'];
|
||||
const missingElements = commonElements.filter(element => !templateContent.includes(element));
|
||||
|
||||
if (missingElements.length > 0) {
|
||||
result.warnings.push(
|
||||
`Template may be missing common setup: ${missingElements.join(', ')}. This is not an error but may result in default formatting.`
|
||||
);
|
||||
}
|
||||
|
||||
// Check for potentially problematic patterns
|
||||
this.validateProblematicPatterns(templateContent, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate potentially problematic patterns
|
||||
*/
|
||||
private static validateProblematicPatterns(templateContent: string, result: TemplateValidationResult): void {
|
||||
const problematicPatterns = [
|
||||
{
|
||||
pattern: /#set\s+page\s*\([^)]*height:\s*auto[^)]*\)/,
|
||||
message: "Templates with 'height: auto' may not work well with multi-page documents",
|
||||
type: 'warning' as const
|
||||
},
|
||||
{
|
||||
pattern: /#pagebreak\(\s*weak:\s*false\s*\)/,
|
||||
message: "Hard page breaks may cause layout issues in generated documents",
|
||||
type: 'warning' as const
|
||||
},
|
||||
{
|
||||
pattern: /#import\s+[^:]*:/,
|
||||
message: "Import statements may fail if the imported module is not available",
|
||||
type: 'warning' as const
|
||||
},
|
||||
{
|
||||
pattern: /\$\w+\$\s*\$\w+\$/,
|
||||
message: "Adjacent variables without spacing may cause formatting issues",
|
||||
type: 'warning' as const
|
||||
}
|
||||
];
|
||||
|
||||
for (const { pattern, message, type } of problematicPatterns) {
|
||||
if (pattern.test(templateContent)) {
|
||||
if (type === 'error') {
|
||||
result.errors.push(message);
|
||||
} else {
|
||||
result.warnings.push(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate variables and their usage
|
||||
*/
|
||||
private static validateVariables(templateContent: string, result: TemplateValidationResult, context?: SubstitutionContext): void {
|
||||
const variables = result.variables;
|
||||
|
||||
// Check for empty variables
|
||||
if (variables.length === 0) {
|
||||
result.warnings.push('Template contains no variables. This may be intentional for static templates.');
|
||||
}
|
||||
|
||||
// Check for duplicate variables (not an error, just inefficient)
|
||||
const variableCounts = new Map<string, number>();
|
||||
const variablePattern = /\$(\w+)\$/g;
|
||||
let match;
|
||||
|
||||
while ((match = variablePattern.exec(templateContent)) !== null) {
|
||||
const varName = match[1];
|
||||
variableCounts.set(varName, (variableCounts.get(varName) || 0) + 1);
|
||||
}
|
||||
|
||||
// Warn about variables used only once (might be typos)
|
||||
for (const [varName, count] of variableCounts) {
|
||||
if (count === 1 && varName !== 'body') {
|
||||
result.warnings.push(`Variable '${varName}' is used only once. Verify this is intentional.`);
|
||||
}
|
||||
}
|
||||
|
||||
// If context is provided, validate against it
|
||||
if (context) {
|
||||
this.validateAgainstContext(variables, context, result);
|
||||
}
|
||||
|
||||
// Check for common variable name typos
|
||||
this.validateCommonVariables(variables, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate variables against substitution context
|
||||
*/
|
||||
private static validateAgainstContext(variables: string[], context: SubstitutionContext, result: TemplateValidationResult): void {
|
||||
const requiredVars = variables.filter(v => v === 'body');
|
||||
const optionalVars = variables.filter(v => v !== 'body');
|
||||
|
||||
// Check required variables
|
||||
for (const varName of requiredVars) {
|
||||
if (!context[varName]) {
|
||||
result.errors.push(`Required variable '${varName}' is missing from context`);
|
||||
}
|
||||
}
|
||||
|
||||
// Warn about missing optional variables
|
||||
for (const varName of optionalVars) {
|
||||
if (!context[varName] && !this.hasImplicitDefault(varName)) {
|
||||
result.warnings.push(`Optional variable '${varName}' is not provided and has no default value`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if variable has an implicit default
|
||||
*/
|
||||
private static hasImplicitDefault(varName: string): boolean {
|
||||
const defaultVars = ['title', 'author', 'date', 'font', 'fontSize', 'pageSize', 'margins'];
|
||||
return defaultVars.includes(varName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate common variable names for typos
|
||||
*/
|
||||
private static validateCommonVariables(variables: string[], result: TemplateValidationResult): void {
|
||||
const commonVars = ['title', 'author', 'date', 'body', 'font', 'fontSize', 'pageSize', 'margins'];
|
||||
const typoMap = {
|
||||
'titel': 'title',
|
||||
'autor': 'author',
|
||||
'authur': 'author',
|
||||
'dat': 'date',
|
||||
'boby': 'body',
|
||||
'bdy': 'body',
|
||||
'fontsize': 'fontSize',
|
||||
'font_size': 'fontSize',
|
||||
'pagesize': 'pageSize',
|
||||
'page_size': 'pageSize',
|
||||
'margin': 'margins'
|
||||
};
|
||||
|
||||
for (const variable of variables) {
|
||||
if (typoMap[variable]) {
|
||||
result.warnings.push(
|
||||
`Variable '${variable}' might be a typo. Did you mean '${typoMap[variable]}'?`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate Typst-specific features
|
||||
*/
|
||||
private static validateTypstFeatures(templateContent: string, result: TemplateValidationResult): void {
|
||||
// Check for version-specific features
|
||||
this.validateVersionFeatures(templateContent, result);
|
||||
|
||||
// Check for proper page setup
|
||||
this.validatePageFeatures(templateContent, result);
|
||||
|
||||
// Check for text formatting
|
||||
this.validateTextFeatures(templateContent, result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate version-specific features
|
||||
*/
|
||||
private static validateVersionFeatures(templateContent: string, result: TemplateValidationResult): void {
|
||||
const v011Features = [
|
||||
{ pattern: /height:\s*auto/, feature: 'height: auto (Typst 0.11+)' },
|
||||
{ pattern: /#context/, feature: 'context blocks (Typst 0.11+)' },
|
||||
{ pattern: /scope:\s*"parent"/, feature: 'scope: "parent" (Typst 0.11+)' }
|
||||
];
|
||||
|
||||
for (const { pattern, feature } of v011Features) {
|
||||
if (pattern.test(templateContent)) {
|
||||
result.warnings.push(`Template uses ${feature}. Ensure Typst version 0.11+ is available.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate page setup features
|
||||
*/
|
||||
private static validatePageFeatures(templateContent: string, result: TemplateValidationResult): void {
|
||||
// Check for conflicting page settings
|
||||
if (templateContent.includes('height: auto') && templateContent.includes('columns:')) {
|
||||
result.warnings.push('Using both "height: auto" and columns may cause unexpected layout behavior');
|
||||
}
|
||||
|
||||
// Check for invalid paper sizes
|
||||
const paperSizePattern = /paper:\s*"([^"]+)"/g;
|
||||
const validPaperSizes = ['a4', 'a3', 'a5', 'us-letter', 'us-legal', 'iso-b4', 'iso-b5'];
|
||||
let match;
|
||||
|
||||
while ((match = paperSizePattern.exec(templateContent)) !== null) {
|
||||
const paperSize = match[1];
|
||||
if (!validPaperSizes.includes(paperSize)) {
|
||||
result.warnings.push(`Unknown paper size '${paperSize}'. Valid sizes: ${validPaperSizes.join(', ')}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate text formatting features
|
||||
*/
|
||||
private static validateTextFeatures(templateContent: string, result: TemplateValidationResult): void {
|
||||
// Check for deprecated font syntax
|
||||
if (templateContent.match(/font:\s*\([^)]*\)/)) {
|
||||
result.warnings.push('Using tuple syntax for fonts. Consider using string syntax for better compatibility.');
|
||||
}
|
||||
|
||||
// Check for missing language setting
|
||||
if (!templateContent.includes('lang:') && !templateContent.includes('language:')) {
|
||||
result.warnings.push('Template does not specify language. Consider adding "lang: \\"en\\"" or appropriate language code.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate page setup comprehensively
|
||||
*/
|
||||
private static validatePageSetup(templateContent: string, result: TemplateValidationResult): void {
|
||||
// Check for margin specification
|
||||
if (templateContent.includes('#set page') && !templateContent.match(/margin:\s*[^,\)]+/)) {
|
||||
result.warnings.push('Page setup found but no margins specified. Consider setting margins for better layout control.');
|
||||
}
|
||||
|
||||
// Check for header/footer balance
|
||||
const hasHeader = templateContent.includes('header:');
|
||||
const hasFooter = templateContent.includes('footer:');
|
||||
const hasNumbering = templateContent.includes('numbering:');
|
||||
|
||||
if ((hasHeader || hasFooter) && !hasNumbering) {
|
||||
result.warnings.push('Template has header/footer but no page numbering. Consider adding numbering for better navigation.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Quick validation for basic template structure
|
||||
*/
|
||||
static quickValidate(templateContent: string): boolean {
|
||||
// Basic checks for template usability
|
||||
if (!templateContent.trim()) return false;
|
||||
if (!templateContent.includes('$body$')) return false;
|
||||
|
||||
// Check for basic syntax errors
|
||||
const openBraces = (templateContent.match(/\{/g) || []).length;
|
||||
const closeBraces = (templateContent.match(/\}/g) || []).length;
|
||||
const openBrackets = (templateContent.match(/\[/g) || []).length;
|
||||
const closeBrackets = (templateContent.match(/\]/g) || []).length;
|
||||
|
||||
return openBraces === closeBraces && openBrackets === closeBrackets;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get validation summary
|
||||
*/
|
||||
static getValidationSummary(result: TemplateValidationResult): string {
|
||||
const { isValid, errors, warnings, variables } = result;
|
||||
|
||||
let summary = `Template validation ${isValid ? 'passed' : 'failed'}\n`;
|
||||
summary += `Found ${variables.length} variables: ${variables.join(', ')}\n`;
|
||||
|
||||
if (errors.length > 0) {
|
||||
summary += `\nErrors (${errors.length}):\n${errors.map(e => `• ${e}`).join('\n')}`;
|
||||
}
|
||||
|
||||
if (warnings.length > 0) {
|
||||
summary += `\nWarnings (${warnings.length}):\n${warnings.map(w => `• ${w}`).join('\n')}`;
|
||||
}
|
||||
|
||||
return summary;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Template variable configuration
|
||||
*/
|
||||
export interface TemplateVariable {
|
||||
type: 'string' | 'number' | 'boolean';
|
||||
defaultValue: any;
|
||||
description?: string;
|
||||
required: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Template metadata
|
||||
*/
|
||||
export interface TemplateMetadata {
|
||||
author?: string;
|
||||
version?: string;
|
||||
description?: string;
|
||||
compatibility: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Typst template definition
|
||||
*/
|
||||
export interface Template {
|
||||
/** Display name of the template */
|
||||
name: string;
|
||||
/** File path to the template */
|
||||
filePath: string;
|
||||
/** Template variables and their types */
|
||||
variables: Record<string, TemplateVariable>;
|
||||
/** Template metadata */
|
||||
metadata: TemplateMetadata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Template validation result
|
||||
*/
|
||||
export interface TemplateValidationResult {
|
||||
isValid: boolean;
|
||||
errors: string[];
|
||||
warnings: string[];
|
||||
variables: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Variable substitution context
|
||||
*/
|
||||
export interface SubstitutionContext {
|
||||
title?: string;
|
||||
author?: string;
|
||||
date?: string;
|
||||
body: string;
|
||||
font?: string;
|
||||
fontSize?: string;
|
||||
pageSize?: string;
|
||||
margins?: string;
|
||||
[key: string]: string | undefined;
|
||||
}
|
||||
Reference in new issue
Block a user