@xwordly/xword-parser
Version:
Fast, type-safe TypeScript library for parsing crossword puzzles (PUZ, iPUZ, JPZ, XD)
90 lines (88 loc) • 3.16 kB
JavaScript
;
// src/detect.ts
function detectFormatFromContent(content, filename) {
const hints = [];
if (filename) {
const ext = filename.split(".").pop()?.toLowerCase();
if (ext === "puz") {
hints.push({ format: "puz", confidence: "high" });
} else if (ext === "ipuz") {
hints.push({ format: "ipuz", confidence: "high" });
} else if (ext === "jpz") {
hints.push({ format: "jpz", confidence: "high" });
} else if (ext === "xd") {
hints.push({ format: "xd", confidence: "high" });
}
}
if (typeof content === "string") {
const trimmed = content.trim();
if (trimmed.startsWith("ipuz({") || trimmed.startsWith("{") && trimmed.includes('"version"')) {
if (!hints.some((h) => h.format === "ipuz")) {
hints.push({ format: "ipuz", confidence: "high" });
}
}
if (content.includes("<?xml") || content.includes("<crossword") || content.includes("<puzzle")) {
if (!hints.some((h) => h.format === "jpz")) {
hints.push({ format: "jpz", confidence: "high" });
}
}
const lines = content.split("\n");
const hasXdHeaders = lines.some(
(line) => /^(Title|Author|Editor|Copyright|Date|Rebus|Notepad|Notes?):/i.test(line)
);
if (hasXdHeaders) {
if (!hints.some((h) => h.format === "xd")) {
hints.push({ format: "xd", confidence: "high" });
}
}
} else {
if (!hints.some((h) => h.format === "puz")) {
hints.push({ format: "puz", confidence: "medium" });
}
const textContent = content.toString("utf-8");
const trimmed = textContent.trim();
if (trimmed.startsWith("ipuz({") || trimmed.startsWith("{") && trimmed.includes('"version"')) {
if (!hints.some((h) => h.format === "ipuz")) {
hints.push({ format: "ipuz", confidence: "medium" });
}
}
if (textContent.includes("<?xml") || textContent.includes("<crossword") || textContent.includes("<puzzle")) {
if (!hints.some((h) => h.format === "jpz")) {
hints.push({ format: "jpz", confidence: "medium" });
}
}
const lines = textContent.split("\n");
const hasXdHeaders = lines.some(
(line) => /^(Title|Author|Editor|Copyright|Date|Rebus|Notepad|Notes?):/i.test(line)
);
if (hasXdHeaders) {
if (!hints.some((h) => h.format === "xd")) {
hints.push({ format: "xd", confidence: "medium" });
}
}
}
hints.sort((a, b) => {
const confidenceOrder = { high: 0, medium: 1, low: 2 };
return confidenceOrder[a.confidence] - confidenceOrder[b.confidence];
});
return hints;
}
function getOrderedFormatsToTry(content, filename) {
const hints = detectFormatFromContent(content, filename);
const formats = [];
for (const hint of hints) {
if (!formats.includes(hint.format)) {
formats.push(hint.format);
}
}
const allFormats = ["ipuz", "puz", "jpz", "xd"];
for (const format of allFormats) {
if (!formats.includes(format)) {
formats.push(format);
}
}
return formats;
}
exports.getOrderedFormatsToTry = getOrderedFormatsToTry;
//# sourceMappingURL=chunk-TFE3E6Z3.js.map
//# sourceMappingURL=chunk-TFE3E6Z3.js.map