-
Notifications
You must be signed in to change notification settings - Fork 431
Expand file tree
/
Copy pathoutput-typst.ts
More file actions
390 lines (353 loc) · 10.7 KB
/
output-typst.ts
File metadata and controls
390 lines (353 loc) · 10.7 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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
/*
* 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 { runAnalyze, toTomlPath } from "../../core/typst-gather.ts";
import { asArray } from "../../core/array.ts";
import { ProjectContext } from "../../project/types.ts";
import { validatePdfStandards } from "../../core/verapdf.ts";
export interface NeededPackage {
namespace: string;
name: string;
version: string;
}
// Collect all package source directories (built-in + extensions)
async function collectPackageSources(
inputDir: string,
projectDir: string,
): Promise<string[]> {
const sources: string[] = [];
// 1. Built-in packages
const builtinPackages = resourcePath("formats/typst/packages");
if (existsSync(builtinPackages)) {
sources.push(builtinPackages);
}
// 2. Extension packages
const extensionDirs = inputExtensionDirs(inputDir, projectDir);
const subtreePath = builtinSubtreeExtensions();
for (const extDir of extensionDirs) {
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)) {
sources.push(packagesDir);
}
}
}
return sources;
}
// Build the TOML config string for typst-gather analyze
export function buildAnalyzeToml(
typstInput: string,
packageSources: string[],
): string {
const discoverPath = toTomlPath(typstInput);
const cachePaths = packageSources.map((p) => `"${toTomlPath(p)}"`).join(", ");
return [
`discover = ["${discoverPath}"]`,
`package-cache = [${cachePaths}]`,
].join("\n");
}
// Run typst-gather analyze on the .typ file to determine needed packages
async function analyzeNeededPackages(
typstInput: string,
packageSources: string[],
): Promise<NeededPackage[] | null> {
const tomlConfig = buildAnalyzeToml(typstInput, packageSources);
try {
const result = await runAnalyze(tomlConfig);
return result.imports.map(({ namespace, name, version }) => ({
namespace,
name,
version,
}));
} catch {
// Fallback: if analyze fails, stage everything (current behavior)
warning("typst-gather analyze failed; staging all packages as fallback");
return null;
}
}
// Stage only the needed packages from source dirs into the cache dir.
// Last write wins — extensions (listed after built-in) override built-in packages.
export function stageSelectedPackages(
sources: string[],
cacheDir: string,
needed: NeededPackage[] | null,
): void {
if (needed === null) {
stageAllPackages(sources, cacheDir);
return;
}
for (const pkg of needed) {
const relPath = join(pkg.namespace, pkg.name, pkg.version);
const destPath = join(cacheDir, relPath);
for (const source of sources) {
const srcPath = join(source, relPath);
if (existsSync(srcPath)) {
ensureDirSync(dirname(destPath));
copySync(srcPath, destPath, { overwrite: true });
}
}
}
}
// Fallback: copy all packages from all sources. Last write wins at the
// package directory level. Built-in listed first, extensions after.
export function stageAllPackages(sources: string[], cacheDir: string): void {
for (const source of sources) {
for (const nsEntry of Deno.readDirSync(source)) {
if (!nsEntry.isDirectory) continue;
const nsSrc = join(source, nsEntry.name);
const nsDest = join(cacheDir, nsEntry.name);
ensureDirSync(nsDest);
for (const pkgEntry of Deno.readDirSync(nsSrc)) {
const pkgSrc = join(nsSrc, pkgEntry.name);
const pkgDest = join(nsDest, pkgEntry.name);
copySync(pkgSrc, pkgDest, { overwrite: true });
}
}
}
}
// Stage typst packages to .quarto/typst-packages/
// First stages built-in packages, then extension packages (which can override)
async function stageTypstPackages(
inputDir: string,
typstInput: string,
projectDir?: string,
): Promise<string | undefined> {
if (!projectDir) {
return undefined;
}
const packageSources = await collectPackageSources(inputDir, projectDir);
if (packageSources.length === 0) {
return undefined;
}
const neededPackages = await analyzeNeededPackages(
typstInput,
packageSources,
);
const cacheDir = projectScratchPath(projectDir, "typst/packages");
stageSelectedPackages(packageSources, cacheDir, neededPackages);
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(
inputDir,
typstInput,
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;
}