Type-check search utilities and size parsing
Browse filesFiles changed (6)
14 unmodified lines15161718192014 unmodified lines!tests/test_service_worker.cjs!tests/test_speech_static.py!tests/test_speech_plan.cjs!tests/test_search.py!tests/test_prepare_fulltext_index.py!tests/test_ocr_release.py14 unmodified lines151617181920212214 unmodified lines!tests/test_service_worker.cjs!tests/test_speech_static.py!tests/test_speech_plan.cjs!tests/test_search_util_static.py!tests/test_search_utils.cjs!tests/test_search.py!tests/test_prepare_fulltext_index.py!tests/test_ocr_release.py
18 unmodified lines192021222324252627283 unmodified lines32333435363718 unmodified linesCOPY --from=static-check-node /check/jsconfig.service-worker.json ./COPY --from=static-check-node /check/static/sw.js static/sw.jsCOPY static/tts-client.js static/tts-client.jsCOPY pyrightconfig.json app.py build_fulltext_db.py prepare_fulltext_index.py ocr_release.py ./COPY Dockerfile .coveragerc ./COPY tests/__init__.py tests/test_static_checks.py tests/test_coverage_gate.py tests/test_service_worker.cjs tests/COPY tests/test_speech_static.py tests/test_speech_plan.cjs tests/RUN node node_modules/pyright/index.js --project pyrightconfig.jsonRUN mkdir -p data/initial data/sidebar static/iconsRUN printf '{"urls":[]}' > data/initial/manifest.json \3 unmodified lines&& node tests/test_service_worker.cjs \&& python -B -m unittest tests.test_speech_static -v \&& node tests/test_speech_plan.cjs \&& python -m coverage run -m unittest -q tests.test_search.TokenizationTests tests.test_prepare_fulltext_index tests.test_ocr_release tests.test_integration.FulltextIntegrationTests tests.test_typed_contracts tests.test_coverage_gate \&& python -m coverage report --fail-under=6518 unmodified lines1920212223242526272829303 unmodified lines343536373839404118 unmodified linesCOPY --from=static-check-node /check/jsconfig.service-worker.json ./COPY --from=static-check-node /check/static/sw.js static/sw.jsCOPY static/tts-client.js static/tts-client.jsCOPY static/app.js static/app.jsCOPY pyrightconfig.json app.py build_fulltext_db.py prepare_fulltext_index.py ocr_release.py ./COPY Dockerfile .coveragerc ./COPY tests/__init__.py tests/test_static_checks.py tests/test_coverage_gate.py tests/test_service_worker.cjs tests/COPY tests/test_speech_static.py tests/test_speech_plan.cjs tests/COPY tests/test_search_util_static.py tests/test_search_utils.cjs tests/RUN node node_modules/pyright/index.js --project pyrightconfig.jsonRUN mkdir -p data/initial data/sidebar static/iconsRUN printf '{"urls":[]}' > data/initial/manifest.json \3 unmodified lines&& node tests/test_service_worker.cjs \&& python -B -m unittest tests.test_speech_static -v \&& node tests/test_speech_plan.cjs \&& python -B -m unittest tests.test_search_util_static -v \&& node tests/test_search_utils.cjs \&& python -m coverage run -m unittest -q tests.test_search.TokenizationTests tests.test_prepare_fulltext_index tests.test_ocr_release tests.test_integration.FulltextIntegrationTests tests.test_typed_contracts tests.test_coverage_gate \&& python -m coverage report --fail-under=65
203 unmodified lines2042052062072082092102112122132142152162172182192202212222232241 unmodified line22622722822923023128 unmodified lines2602612622632642653 unmodified lines269270271272273274275276277278279203 unmodified linesreturn document.querySelector(selector);}function escapeHTML(value) {return String(value).replace(/[&<>"']/g, function(ch) {return ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[ch];});}function tokenize(text) {return Array.from(new Set(String(text || "").toLowerCase().match(/[a-z0-9]+|[\u4e00-\u9fff\u3400-\u4dbf]+/g) || []));}function wildcardPatternToRegExp(pattern) {const escaped = String(pattern || "").replace(/[.+^${}()|[\]\\]/g, "\\$&");return new RegExp(escaped.replace(/\*/g, ".*").replace(/\?/g, "."), "i");}function formatSize(bytes) {if (!bytes) return "";if (bytes < 1024) return bytes + " B";1 unmodified lineif (bytes < 1073741824) return (bytes / 1048576).toFixed(1).replace(/\.0$/, "") + " MB";return (bytes / 1073741824).toFixed(2).replace(/\.00$/, "") + " GB";}function highlightText(text, query, highlights = null) {const safeText = escapeHTML(text || "");28 unmodified linesreturn STATE.highlightPatterns;}function bytesFromInput(value, unit) {const parsed = parseFloat(value);if (Number.isNaN(parsed) || parsed < 0) return null;3 unmodified linesreturn Math.round(parsed);}function bytesFromUrl(value) {if (value === null || value === "") return null;const parsed = Number(value);return Number.isFinite(parsed) && parsed >= 0 ? Math.round(parsed) : null;}function restoreSizeInput(input, unitSelect, bytes) {if (bytes === null) {203 unmodified lines2042052062072082092102112122132142152162172182192202212222232242252262272282292301 unmodified line23223323423523623723828 unmodified lines2672682692702712722732743 unmodified lines278279280281282283284285286287288289290203 unmodified linesreturn document.querySelector(selector);}// BEGIN STRICT SEARCH UTILITIES/** @param {unknown} value @returns {string} */function escapeHTML(value) {return String(value).replace(/[&<>"']/g, function(ch) {const entities = /** @type {Record<string, string>} */ ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" });return entities[ch];});}/** @param {unknown} text @returns {string[]} */function tokenize(text) {return Array.from(new Set(String(text || "").toLowerCase().match(/[a-z0-9]+|[\u4e00-\u9fff\u3400-\u4dbf]+/g) || []));}/** @param {unknown} pattern @returns {RegExp} */function wildcardPatternToRegExp(pattern) {const escaped = String(pattern || "").replace(/[.+^${}()|[\]\\]/g, "\\$&");return new RegExp(escaped.replace(/\*/g, ".*").replace(/\?/g, "."), "i");}/** @param {number | null | undefined} bytes @returns {string} */function formatSize(bytes) {if (!bytes) return "";if (bytes < 1024) return bytes + " B";1 unmodified lineif (bytes < 1073741824) return (bytes / 1048576).toFixed(1).replace(/\.0$/, "") + " MB";return (bytes / 1073741824).toFixed(2).replace(/\.00$/, "") + " GB";}// END STRICT SEARCH UTILITIESfunction highlightText(text, query, highlights = null) {const safeText = escapeHTML(text || "");28 unmodified linesreturn STATE.highlightPatterns;}// BEGIN STRICT SIZE PARSING/** @param {string} value @param {string} unit @returns {number | null} */function bytesFromInput(value, unit) {const parsed = parseFloat(value);if (Number.isNaN(parsed) || parsed < 0) return null;3 unmodified linesreturn Math.round(parsed);}/** @param {string | null} value @returns {number | null} */function bytesFromUrl(value) {if (value === null || value === "") return null;const parsed = Number(value);return Number.isFinite(parsed) && parsed >= 0 ? Math.round(parsed) : null;}// END STRICT SIZE PARSINGfunction restoreSizeInput(input, unitSelect, bytes) {if (bytes === null) {
12345678910111213141516171819202122232425262728293031323334353637383940414243"""Type-check the actual search utility sections and detect injected errors."""import jsonimport subprocessimport tempfileimport unittestfrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]SECTIONS = (("// BEGIN STRICT SEARCH UTILITIES", "// END STRICT SEARCH UTILITIES"), ("// BEGIN STRICT SIZE PARSING", "// END STRICT SIZE PARSING"))
class SearchUtilityStaticTests(unittest.TestCase): def test_actual_utility_code_is_strict(self): source = (ROOT / "static/app.js").read_text(encoding="utf-8") blocks = [] for begin, end in SECTIONS: self.assertEqual(source.count(begin), 1) self.assertEqual(source.count(end), 1) blocks.append(source[source.index(begin):source.index(end) + len(end)]) block = "\n".join(blocks) self.assertNotIn("@ts-ignore", block) self.assertNotIn("@ts-nocheck", block) with tempfile.TemporaryDirectory(prefix="search-util-types-") as directory: root = Path(directory) entry = root / "utilities.js" entry.write_text(block, encoding="utf-8") (root / "tsconfig.json").write_text(json.dumps({ "compilerOptions": {"allowJs": True, "checkJs": True, "strict": True, "noEmit": True, "target": "ES2022", "lib": ["ES2022", "DOM"]}, "files": ["utilities.js"], })) cmd = ("node", str(ROOT / "node_modules/typescript/bin/tsc"), "-p", str(root / "tsconfig.json"), "--pretty", "false") result = subprocess.run(cmd, text=True, capture_output=True, timeout=60) self.assertEqual(result.returncode, 0, result.stdout + result.stderr) entry.write_text(block.replace("function bytesFromInput(value, unit) {", 'function bytesFromInput(value, unit) {\n unit = 7;', 1), encoding="utf-8") result = subprocess.run(cmd, text=True, capture_output=True, timeout=60) self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr) self.assertIn("error TS", result.stdout)
if __name__ == "__main__": unittest.main()12345678910111213141516171819202122"use strict";const assert = require("node:assert/strict");const fs = require("node:fs");const path = require("node:path");const vm = require("node:vm");const source = fs.readFileSync(path.join(__dirname, "../static/app.js"), "utf8");const sections = [["// BEGIN STRICT SEARCH UTILITIES", "// END STRICT SEARCH UTILITIES"], ["// BEGIN STRICT SIZE PARSING", "// END STRICT SIZE PARSING"]];const code = sections.map(([begin, end]) => { assert.equal(source.split(begin).length, 2); assert.equal(source.split(end).length, 2); return source.slice(source.indexOf(begin), source.indexOf(end) + end.length);}).join("\n");const sandbox = {}; vm.runInNewContext(code, sandbox);assert.equal(sandbox.escapeHTML('<甲&"'), "<甲&"");assert.deepEqual(Array.from(sandbox.tokenize("文化 革命 ABC abc")), ["文化", "革命", "abc"]);assert.ok(sandbox.wildcardPatternToRegExp("手?机").test("手大机"));assert.equal(sandbox.formatSize(1024), "1 KB");assert.equal(sandbox.bytesFromInput("1.5", "KB"), 1536);assert.equal(sandbox.bytesFromInput("-1", "MB"), null);assert.equal(sandbox.bytesFromUrl("Infinity"), null);assert.equal(sandbox.bytesFromUrl("0"), 0);console.log("CCRD search utility escaping, wildcard and size boundaries passed");66 unmodified lines67686970717266 unmodified linesself.assertIn("python -m coverage report --fail-under=65", dockerfile)self.assertIn("unittest tests.test_speech_static", dockerfile)self.assertIn("node tests/test_speech_plan.cjs", dockerfile)if __name__ == "__main__":66 unmodified lines676869707172737466 unmodified linesself.assertIn("python -m coverage report --fail-under=65", dockerfile)self.assertIn("unittest tests.test_speech_static", dockerfile)self.assertIn("node tests/test_speech_plan.cjs", dockerfile)self.assertIn("unittest tests.test_search_util_static", dockerfile)self.assertIn("node tests/test_search_utils.cjs", dockerfile)if __name__ == "__main__":
.dockerignore+2
Dockerfile+4
static/app.js+12-1
tests/test_search_util_static.pyAdded+43
tests/test_search_utils.cjsAdded+22
tests/test_static_checks.py+2