feat: Add ability to detect patches which are present in a file (#2633)
* feat: Add ability to detect patches which are present in a file * chore: export patchDetector function * fix: Make sure we don't attempt to call toJson on binary content --------- Co-authored-by: Christopher Fox <cfox@homebound.com>
This commit is contained in:
30
src/patcher/patch-detector.ts
Normal file
30
src/patcher/patch-detector.ts
Normal file
@ -0,0 +1,30 @@
|
||||
import JSZip from "jszip";
|
||||
import { toJson } from "./util";
|
||||
import { traverse } from "./traverser";
|
||||
import { InputDataType } from "./from-docx";
|
||||
|
||||
type PatchDetectorOptions = {
|
||||
readonly data: InputDataType;
|
||||
};
|
||||
|
||||
/** Detects which patches are needed/present in a template */
|
||||
export const patchDetector = async ({ data }: PatchDetectorOptions): Promise<readonly string[]> => {
|
||||
const zipContent = await JSZip.loadAsync(data);
|
||||
const patches = new Set<string>();
|
||||
|
||||
for (const [key, value] of Object.entries(zipContent.files)) {
|
||||
if (!key.endsWith(".xml") && !key.endsWith(".rels")) {
|
||||
continue;
|
||||
}
|
||||
if (key.startsWith("word/") && !key.endsWith(".xml.rels")) {
|
||||
const json = toJson(await value.async("text"));
|
||||
traverse(json).forEach((p) => findPatchKeys(p.text).forEach((patch) => patches.add(patch)));
|
||||
}
|
||||
}
|
||||
return Array.from(patches);
|
||||
};
|
||||
|
||||
const findPatchKeys = (text: string): readonly string[] => {
|
||||
const pattern = /(?<=\{\{).+?(?=\}\})/gs;
|
||||
return text.match(pattern) ?? [];
|
||||
};
|
Reference in New Issue
Block a user