-
Notifications
You must be signed in to change notification settings - Fork 432
Expand file tree
/
Copy pathoutput-typst.ts
More file actions
306 lines (279 loc) · 8.56 KB
/
output-typst.ts
File metadata and controls
306 lines (279 loc) · 8.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
/*
* output-typst.ts
*
* Copyright (C) 2020-2022 Posit Software, PBC
*/
import {
dirname,
isAbsolute,
join,
normalize,
relative,
resolve,
} from "../../deno_ral/path.ts";
import {
copySync,
ensureDirSync,
existsSync,
safeRemoveSync,
} from "../../deno_ral/fs.ts";
import {
builtinSubtreeExtensions,
inputExtensionDirs,
readExtensions,
readSubtreeExtensions,
} from "../../extension/extension.ts";
import { projectScratchPath } from "../../project/project-scratch.ts";
import { resourcePath } from "../../core/resources.ts";
import {
kFontPaths,
kKeepTyp,
kOutputExt,
kOutputFile,
kPdfStandard,
kVariant,
pdfStandardEnv,
} from "../../config/constants.ts";
import { error, warning } from "../../deno_ral/log.ts";
import { ErrorEx } from "../../core/lib/error.ts";
import { Format } from "../../config/types.ts";
import { writeFileToStdout } from "../../core/console.ts";
import { dirAndStem, expandPath } from "../../core/path.ts";
import { kStdOut, replacePandocOutputArg } from "./flags.ts";
import { OutputRecipe, RenderOptions } from "./types.ts";
import { normalizeOutputPath } from "./output-shared.ts";
import {
typstCompile,
TypstCompileOptions,
validateRequiredTypstVersion,
} from "../../core/typst.ts";
import { asArray } from "../../core/array.ts";
import { ProjectContext } from "../../project/types.ts";
import { validatePdfStandards } from "../../core/verapdf.ts";
// Stage typst packages to .quarto/typst-packages/
// First stages built-in packages, then extension packages (which can override)
async function stageTypstPackages(
input: string,
projectDir?: string,
): Promise<string | undefined> {
if (!projectDir) {
return undefined;
}
const packageSources: string[] = [];
// 1. Add built-in packages from quarto resources
const builtinPackages = resourcePath("formats/typst/packages");
if (existsSync(builtinPackages)) {
packageSources.push(builtinPackages);
}
// 2. Add packages from extensions (can override built-in)
const extensionDirs = inputExtensionDirs(input, projectDir);
const subtreePath = builtinSubtreeExtensions();
for (const extDir of extensionDirs) {
// Use readSubtreeExtensions for subtree directory, readExtensions for others
const extensions = extDir === subtreePath
? await readSubtreeExtensions(extDir)
: await readExtensions(extDir);
for (const ext of extensions) {
const packagesDir = join(ext.path, "typst/packages");
if (existsSync(packagesDir)) {
packageSources.push(packagesDir);
}
}
}
if (packageSources.length === 0) {
return undefined;
}
// Stage to .quarto/typst/packages/
const cacheDir = projectScratchPath(projectDir, "typst/packages");
// Copy contents of each source directory (merging namespaces like "preview", "local")
for (const source of packageSources) {
for (const entry of Deno.readDirSync(source)) {
const srcPath = join(source, entry.name);
const destPath = join(cacheDir, entry.name);
if (!existsSync(destPath)) {
copySync(srcPath, destPath);
} else if (entry.isDirectory) {
// Merge directory contents (e.g., merge packages within "preview" namespace)
for (const subEntry of Deno.readDirSync(srcPath)) {
const subSrcPath = join(srcPath, subEntry.name);
const subDestPath = join(destPath, subEntry.name);
if (!existsSync(subDestPath)) {
copySync(subSrcPath, subDestPath);
}
}
}
}
}
return cacheDir;
}
export function useTypstPdfOutputRecipe(
format: Format,
) {
return format.pandoc.to === "typst" &&
format.render[kOutputExt] === "pdf";
}
export function typstPdfOutputRecipe(
input: string,
finalOutput: string,
options: RenderOptions,
format: Format,
project?: ProjectContext,
): OutputRecipe {
// calculate output and args for pandoc (this is an intermediate file
// which we will then compile to a pdf and rename to .typ)
const [inputDir, inputStem] = dirAndStem(input);
const output = inputStem + ".typ";
let args = options.pandocArgs || [];
const pandoc = { ...format.pandoc };
if (options.flags?.output) {
args = replacePandocOutputArg(args, output);
} else {
pandoc[kOutputFile] = output;
}
// when pandoc is done, we need to run the pdf generator and then copy the
// output to the user's requested destination
const complete = async () => {
// input file is pandoc's output
const typstInput = join(inputDir, output);
// run typst
await validateRequiredTypstVersion();
const pdfOutput = join(inputDir, inputStem + ".pdf");
const typstOptions: TypstCompileOptions = {
quiet: options.flags?.quiet,
fontPaths: (asArray(format.metadata?.[kFontPaths]) as string[]).map(
(p) => isAbsolute(p) ? p : resolve(inputDir, p),
),
pdfStandard: normalizePdfStandardForTypst(
asArray(
format.render?.[kPdfStandard] ?? format.metadata?.[kPdfStandard] ??
pdfStandardEnv(),
),
),
};
if (project?.dir) {
typstOptions.rootDir = project.dir;
// Stage extension typst packages
const packagePath = await stageTypstPackages(input, project.dir);
if (packagePath) {
typstOptions.packagePath = packagePath;
}
}
const result = await typstCompile(
typstInput,
pdfOutput,
typstOptions,
);
if (!result.success) {
if (result.stderr) {
error(result.stderr);
}
throw new ErrorEx("Error", "Typst compilation failed", false, false);
}
// Validate PDF against specified standards using verapdf (if available)
const pdfStandards = asArray(
format.render?.[kPdfStandard] ?? format.metadata?.[kPdfStandard] ??
pdfStandardEnv(),
) as string[];
if (pdfStandards.length > 0) {
await validatePdfStandards(pdfOutput, pdfStandards, {
quiet: options.flags?.quiet,
});
}
// keep typ if requested
if (!format.render[kKeepTyp]) {
safeRemoveSync(typstInput);
}
// copy (or write for stdout) compiled pdf to final output location
if (finalOutput) {
if (finalOutput === kStdOut) {
writeFileToStdout(pdfOutput);
safeRemoveSync(pdfOutput);
} else {
const outputPdf = expandPath(finalOutput);
if (normalize(pdfOutput) !== normalize(outputPdf)) {
// ensure the target directory exists
ensureDirSync(dirname(outputPdf));
Deno.renameSync(pdfOutput, outputPdf);
}
}
// final output needs to either absolute or input dir relative
// (however it may be working dir relative when it is passed in)
return normalizeOutputPath(typstInput, finalOutput);
} else {
return normalizeOutputPath(typstInput, pdfOutput);
}
};
const pdfOutput = finalOutput
? finalOutput === kStdOut
? undefined
: normalizeOutputPath(input, finalOutput)
: normalizeOutputPath(input, join(inputDir, inputStem + ".pdf"));
// return recipe
const recipe: OutputRecipe = {
output,
keepYaml: false,
args,
format: { ...format, pandoc },
complete,
finalOutput: pdfOutput ? relative(inputDir, pdfOutput) : undefined,
};
// if we have some variant declared, resolve it
// (use for opt-out citations extension)
if (format.render?.[kVariant]) {
const to = format.pandoc.to;
const variant = format.render[kVariant];
recipe.format = {
...recipe.format,
pandoc: {
...recipe.format.pandoc,
to: `${to}${variant}`,
},
};
}
return recipe;
}
// Typst-supported PDF standards
const kTypstSupportedStandards = new Set([
"1.4",
"1.5",
"1.6",
"1.7",
"2.0",
"a-1b",
"a-1a",
"a-2b",
"a-2u",
"a-2a",
"a-3b",
"a-3u",
"a-3a",
"a-4",
"a-4f",
"a-4e",
"ua-1",
]);
function normalizePdfStandardForTypst(standards: unknown[]): string[] {
const result: string[] = [];
for (const s of standards) {
// Convert to string - YAML may parse versions like 2.0 as integer 2
let str: string;
if (typeof s === "number") {
// Handle YAML numeric parsing: integer 2 -> "2.0", float 1.4 -> "1.4"
str = Number.isInteger(s) ? `${s}.0` : String(s);
} else if (typeof s === "string") {
str = s;
} else {
continue;
}
// Normalize: lowercase, remove any "pdf" prefix
const normalized = str.toLowerCase().replace(/^pdf[/-]?/, "");
if (kTypstSupportedStandards.has(normalized)) {
result.push(normalized);
} else {
warning(
`PDF standard '${s}' is not supported by Typst and will be ignored`,
);
}
}
return result;
}