From eb68777a47834cf6ec5dafffe8b7089ec6358ed2 Mon Sep 17 00:00:00 2001 From: Maksym Stoianov Date: Wed, 18 Nov 2026 01:36:38 +0100 Subject: [PATCH 1/2] refactor: clear all ESLint warnings npx eslint . goes from 285 warnings to 0 (OpenSSF Best Practices warnings_fixed), with no change to the library's behaviour or to the generated documentation. - lines-around-comment moves to @stylistic/lines-around-comment with allowInterface/Enum/Type/ModuleStart, so it no longer fights Prettier. - security/detect-object-injection off (keys come from code; CodeQL covers prototype pollution); scripts/docs tooling may use non-literal regexes. - Complex conditions and template-string calculations moved into named variables; deep nesting split into helpers; regexes rewritten into equivalent safe-regex forms (checked against random inputs). - Expanded single-line JSDoc, added test return types, removed unused imports, dead code and stale eslint-disable directives; renderPage takes an options object. Two justified inline no-console disables remain in catch blocks whose errors would otherwise be silent. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Maksym Stoianov --- config/eslint/custom-rules.ts | 15 +- config/eslint/scripts.ts | 10 +- config/eslint/security.ts | 6 +- docs/content/authored/_entry.mjs | 8 +- docs/content/authored/a1.mjs | 4 +- docs/content/authored/html.mjs | 4 +- docs/content/authored/last-functions.mjs | 4 +- docs/content/authored/object.mjs | 4 +- docs/content/authored/path-misc.mjs | 4 +- docs/content/authored/rest.mjs | 8 +- docs/content/authored/sheet-conditional.mjs | 4 +- docs/content/authored/sheet-guards.mjs | 4 +- docs/content/authored/sheet-read.mjs | 4 +- docs/content/authored/sheet-write.mjs | 4 +- docs/content/authored/string.mjs | 4 +- docs/content/authored/string2.mjs | 4 +- docs/content/authored/string3.mjs | 8 +- docs/content/authored/time-json.mjs | 4 +- docs/content/authored/types.mjs | 4 +- package-lock.json | 61 +++++++ package.json | 1 + scripts/docs/author-batch.mjs | 5 +- scripts/docs/author-exceptions.mjs | 5 +- scripts/docs/author-guards.mjs | 31 ++-- scripts/docs/finalize-site.mjs | 74 +++++--- scripts/docs/generate-topics.mjs | 158 ++++++++++++------ scripts/docs/site.mjs | 32 +--- scripts/docs/sync-jsdoc-examples.mjs | 8 +- scripts/docs/sync-jsdoc-links.mjs | 27 ++- scripts/docs/verify-examples.mjs | 101 ++++++----- scripts/docs/write-help-versions.mjs | 10 +- scripts/lib/three-way-merge.mjs | 4 +- scripts/merge-module-index.mjs | 4 +- scripts/merge-reference-tables.mjs | 4 +- src/appsscript/admin/isAdmin.ts | 2 + src/appsscript/base/getByteSize.ts | 2 +- src/appsscript/sheet/appendColumns.ts | 34 ++-- .../sheet/deleteColumnsByConditional.ts | 4 +- .../sheet/deleteRowsByConditional.ts | 4 +- src/appsscript/sheet/doGridRangesIntersect.ts | 17 +- src/appsscript/sheet/highlightHtml.ts | 15 +- src/appsscript/sheet/isCellGridRange.ts | 7 +- .../sheet/isGridRangeContainedIn.ts | 11 +- .../sheet/isGridRangeSameDimensions.ts | 7 +- src/appsscript/sheet/isValidSheetName.ts | 12 +- src/appsscript/sheet/isValidSpreadsheetId.ts | 4 +- src/appsscript/sheet/parseA1Notation.ts | 120 ++++++------- src/appsscript/sheet/prependColumns.ts | 8 +- src/appsscript/sheet/prependRows.ts | 8 +- .../sheet/requireGridRangeContainedIn.ts | 23 ++- .../sheet/requireGridRangeSameDimensions.ts | 24 ++- .../sheet/requireValidSpreadsheetId.ts | 4 +- src/appsscript/sheet/sortSheets.ts | 2 + src/appsscript/sheet/toA1Notation.ts | 37 ++-- .../sheet/updateSheetNameInA1Notation.ts | 4 +- .../slide/convertMarkdownToRichText.ts | 10 +- src/html/encodeHtml.ts | 8 +- src/json/parseJson.ts | 66 ++++---- src/json/stringifyJson.ts | 8 +- src/lang/base/index.ts | 2 + src/lang/string/index.ts | 1 + src/lang/string/isEmail.ts | 2 +- test/appsscript/admin/nonAdmin.test.ts | 4 +- test/appsscript/admin/requireAdmin.test.ts | 4 +- test/appsscript/sheet/getSchema.test.ts | 1 + .../sheet/isValidSpreadsheetId.test.ts | 4 +- .../sheet/nonGridRangeContainedIn.test.ts | 1 + .../appsscript/sheet/nonRichTextValue.test.ts | 4 +- test/appsscript/sheet/nonSpreadsheet.test.ts | 5 +- test/appsscript/sheet/nonTextStyle.test.ts | 4 +- .../sheet/nonValidSpreadsheetId.test.ts | 4 +- test/appsscript/sheet/prependColumn.test.ts | 3 +- test/appsscript/sheet/prependColumns.test.ts | 3 +- test/appsscript/sheet/prependRow.test.ts | 3 +- test/appsscript/sheet/prependRows.test.ts | 3 +- .../sheet/requireGridRangeContainedIn.test.ts | 1 + .../sheet/requireRichTextValue.test.ts | 4 +- .../appsscript/sheet/requireTextStyle.test.ts | 4 +- .../sheet/requireValidSpreadsheetId.test.ts | 4 +- .../slide/convertRichTextToMarkdown.test.ts | 4 +- test/appsscript/slide/nonPresentation.test.ts | 8 +- test/appsscript/slide/nonSlide.test.ts | 8 +- .../slide/nonValidPresentationId.test.ts | 4 +- .../slide/requirePresentation.test.ts | 4 +- .../slide/requireValidPresentationId.test.ts | 4 +- test/appsscript/ui/nonHtmlOutput.test.ts | 8 +- test/appsscript/ui/nonTextOutput.test.ts | 4 +- test/appsscript/ui/nonUi.test.ts | 4 +- test/appsscript/ui/requireHtmlOutput.test.ts | 4 +- test/appsscript/ui/requireTextOutput.test.ts | 4 +- test/appsscript/ui/requireUi.test.ts | 4 +- test/lang/base/isScalar.test.ts | 2 - test/lang/base/requireFunctionLike.test.ts | 2 +- test/lang/base/requireNonBoolean.test.ts | 1 - test/lang/base/requireNonObject.test.ts | 2 +- test/lang/base/requireNonScalar.test.ts | 2 +- test/lang/base/requireNonString.test.ts | 1 - 97 files changed, 788 insertions(+), 416 deletions(-) diff --git a/config/eslint/custom-rules.ts b/config/eslint/custom-rules.ts index 7519ac9f..daa50c85 100644 --- a/config/eslint/custom-rules.ts +++ b/config/eslint/custom-rules.ts @@ -1,9 +1,11 @@ +import stylistic from "@stylistic/eslint-plugin"; import jsdoc from "eslint-plugin-jsdoc"; export default { files: ["**/*.{js,mjs,cjs,ts,tsx}"], plugins: { - jsdoc + jsdoc, + "@stylistic": stylistic }, rules: { "@typescript-eslint/no-unused-vars": "warn", @@ -68,14 +70,21 @@ export default { next: "*" } ], - "lines-around-comment": [ + // The @stylistic variant understands TypeScript bodies (interfaces, + // enums, type literals, modules), so it does not fight Prettier there. + "lines-around-comment": "off", + "@stylistic/lines-around-comment": [ "warn", { beforeBlockComment: true, allowBlockStart: true, allowObjectStart: true, allowArrayStart: true, - allowClassStart: true + allowClassStart: true, + allowInterfaceStart: true, + allowEnumStart: true, + allowTypeStart: true, + allowModuleStart: true } ], "max-depth": ["warn", 4], diff --git a/config/eslint/scripts.ts b/config/eslint/scripts.ts index b6e3fbf2..e1a0b480 100644 --- a/config/eslint/scripts.ts +++ b/config/eslint/scripts.ts @@ -1,12 +1,13 @@ /** - * Overrides for the maintenance scripts under `scripts/`. + * Overrides for the maintenance scripts under `scripts/` and the authoring + * inputs they load from `docs/` (`docs/content/authored/*.mjs`). * * These are build and integration-test files rather than library sources: * they are plain JavaScript, they run on a console, and the Apps Script ones * reach for the library through the shared global scope. */ export default { - files: ["scripts/**/*.{js,mjs,cjs}"], + files: ["scripts/**/*.{js,mjs,cjs}", "docs/**/*.{js,mjs,cjs}"], rules: { // A build script reports its progress; that is its interface. "no-console": "off", @@ -17,6 +18,11 @@ export default { // A bundler exists to read and write computed paths. "security/detect-non-literal-fs-filename": "off", + // The patterns parse repository sources and are built from constants + // in these files, never from outside input. + "security/detect-unsafe-regex": "off", + "security/detect-non-literal-regexp": "off", + // The lookups here are into objects these files declare themselves. "security/detect-object-injection": "off" } diff --git a/config/eslint/security.ts b/config/eslint/security.ts index 0201f027..40fed626 100644 --- a/config/eslint/security.ts +++ b/config/eslint/security.ts @@ -11,6 +11,10 @@ export default { security }, rules: { - ...security.configs.recommended.rules + ...security.configs.recommended.rules, + + // Flags every `obj[key]`. The keys here come from code, not from request + // input, and CodeQL already covers prototype pollution. + "security/detect-object-injection": "off" } }; diff --git a/docs/content/authored/_entry.mjs b/docs/content/authored/_entry.mjs index 18c96a19..2b6e5ee3 100644 --- a/docs/content/authored/_entry.mjs +++ b/docs/content/authored/_entry.mjs @@ -1,4 +1,6 @@ -/** Assembles one prose entry from a table keyed by field, then by language. */ +/** + * Assembles one prose entry from a table keyed by field, then by language. + */ const LANGUAGE_CODES = ["en", "ru", "uk", "de", "fr"]; @@ -28,7 +30,9 @@ export function entry({ return result; } -/** Short-hand for a value that is only described in one sentence per language. */ +/** + * Short-hand for a value that is only described in one sentence per language. + */ export function code(body) { return [{ body: ["```javascript", body, "```"].join("\n") }]; } diff --git a/docs/content/authored/a1.mjs b/docs/content/authored/a1.mjs index 35f13c34..5b100862 100644 --- a/docs/content/authored/a1.mjs +++ b/docs/content/authored/a1.mjs @@ -1,4 +1,6 @@ -/** Prose for the A1-notation and column-letter helpers. */ +/** + * Prose for the A1-notation and column-letter helpers. + */ import { code, entry } from "./_entry.mjs"; diff --git a/docs/content/authored/html.mjs b/docs/content/authored/html.mjs index 63294c85..cf9894c0 100644 --- a/docs/content/authored/html.mjs +++ b/docs/content/authored/html.mjs @@ -1,4 +1,6 @@ -/** Prose for the HTML and XML helpers. */ +/** + * Prose for the HTML and XML helpers. + */ import { code, entry } from "./_entry.mjs"; diff --git a/docs/content/authored/last-functions.mjs b/docs/content/authored/last-functions.mjs index 4d4246ca..c8a567b4 100644 --- a/docs/content/authored/last-functions.mjs +++ b/docs/content/authored/last-functions.mjs @@ -1,4 +1,6 @@ -/** Prose for the last of the Apps Script helpers. */ +/** + * Prose for the last of the Apps Script helpers. + */ import { code, entry } from "./_entry.mjs"; diff --git a/docs/content/authored/object.mjs b/docs/content/authored/object.mjs index 4b359f6a..7bee0358 100644 --- a/docs/content/authored/object.mjs +++ b/docs/content/authored/object.mjs @@ -1,4 +1,6 @@ -/** Prose for the object helpers and the JSON pair. */ +/** + * Prose for the object helpers and the JSON pair. + */ import { code, entry } from "./_entry.mjs"; diff --git a/docs/content/authored/path-misc.mjs b/docs/content/authored/path-misc.mjs index 83f2c31d..a8f11605 100644 --- a/docs/content/authored/path-misc.mjs +++ b/docs/content/authored/path-misc.mjs @@ -1,4 +1,6 @@ -/** Prose for the path helpers and the odds and ends. */ +/** + * Prose for the path helpers and the odds and ends. + */ import { code, entry } from "./_entry.mjs"; diff --git a/docs/content/authored/rest.mjs b/docs/content/authored/rest.mjs index cca88228..f0a345da 100644 --- a/docs/content/authored/rest.mjs +++ b/docs/content/authored/rest.mjs @@ -1,10 +1,14 @@ -/** Prose for the remaining functions and classes. */ +/** + * Prose for the remaining functions and classes. + */ import { code, entry } from "./_entry.mjs"; const NONE = { en: "", ru: "", uk: "", de: "", fr: "" }; -/** A shorter form for entries that need one paragraph and no parameters table beyond the obvious. */ +/** + * A shorter form for entries that need one paragraph and no parameters table beyond the obvious. + */ function simple({ seeAlso, examples, diff --git a/docs/content/authored/sheet-conditional.mjs b/docs/content/authored/sheet-conditional.mjs index fd13c318..ea2a0e18 100644 --- a/docs/content/authored/sheet-conditional.mjs +++ b/docs/content/authored/sheet-conditional.mjs @@ -1,4 +1,6 @@ -/** Prose for the conditional row and column operations, and the lookups. */ +/** + * Prose for the conditional row and column operations, and the lookups. + */ import { code, entry } from "./_entry.mjs"; diff --git a/docs/content/authored/sheet-guards.mjs b/docs/content/authored/sheet-guards.mjs index 143841be..a89d58ec 100644 --- a/docs/content/authored/sheet-guards.mjs +++ b/docs/content/authored/sheet-guards.mjs @@ -1,4 +1,6 @@ -/** Prose for the two-argument grid-range guards, the admin family and the leftovers. */ +/** + * Prose for the two-argument grid-range guards, the admin family and the leftovers. + */ import { code, entry } from "./_entry.mjs"; diff --git a/docs/content/authored/sheet-read.mjs b/docs/content/authored/sheet-read.mjs index 20bd21bf..64c73bbd 100644 --- a/docs/content/authored/sheet-read.mjs +++ b/docs/content/authored/sheet-read.mjs @@ -1,4 +1,6 @@ -/** Prose for reading a sheet, its schema and its formulas. */ +/** + * Prose for reading a sheet, its schema and its formulas. + */ import { code, entry } from "./_entry.mjs"; diff --git a/docs/content/authored/sheet-write.mjs b/docs/content/authored/sheet-write.mjs index a290c725..ca8190af 100644 --- a/docs/content/authored/sheet-write.mjs +++ b/docs/content/authored/sheet-write.mjs @@ -1,4 +1,6 @@ -/** Prose for the row and column operations on a sheet. */ +/** + * Prose for the row and column operations on a sheet. + */ import { code, entry } from "./_entry.mjs"; diff --git a/docs/content/authored/string.mjs b/docs/content/authored/string.mjs index 586e426b..65dc090e 100644 --- a/docs/content/authored/string.mjs +++ b/docs/content/authored/string.mjs @@ -1,4 +1,6 @@ -/** Prose for the string helpers. Example code is shared by every language. */ +/** + * Prose for the string helpers. Example code is shared by every language. + */ export const FUNCTIONS = { toCamelCase: { diff --git a/docs/content/authored/string2.mjs b/docs/content/authored/string2.mjs index 5f7bd4ba..84be1f3b 100644 --- a/docs/content/authored/string2.mjs +++ b/docs/content/authored/string2.mjs @@ -1,4 +1,6 @@ -/** Prose for the remaining string helpers. */ +/** + * Prose for the remaining string helpers. + */ const CASE_OPTION = { en: "`trim` trims the string and collapses runs of whitespace into single spaces.", diff --git a/docs/content/authored/string3.mjs b/docs/content/authored/string3.mjs index bca9a157..bba00fe2 100644 --- a/docs/content/authored/string3.mjs +++ b/docs/content/authored/string3.mjs @@ -1,8 +1,12 @@ -/** Prose for the remaining string helpers: escaping, templating and versions. */ +/** + * Prose for the remaining string helpers: escaping, templating and versions. + */ const L = ["en", "ru", "uk", "de", "fr"]; -/** Assembles one entry from a table keyed by field, then by language. */ +/** + * Assembles one entry from a table keyed by field, then by language. + */ export function entry({ examples, seeAlso, diff --git a/docs/content/authored/time-json.mjs b/docs/content/authored/time-json.mjs index 37696560..e454db38 100644 --- a/docs/content/authored/time-json.mjs +++ b/docs/content/authored/time-json.mjs @@ -1,4 +1,6 @@ -/** Prose for the JSON pair, the time helpers and the path helpers. */ +/** + * Prose for the JSON pair, the time helpers and the path helpers. + */ import { code, entry } from "./_entry.mjs"; diff --git a/docs/content/authored/types.mjs b/docs/content/authored/types.mjs index 2f7d5247..f99f85cb 100644 --- a/docs/content/authored/types.mjs +++ b/docs/content/authored/types.mjs @@ -1,4 +1,6 @@ -/** Prose for the types, interfaces and classes the package exports. */ +/** + * Prose for the types, interfaces and classes the package exports. + */ import { code, entry } from "./_entry.mjs"; diff --git a/package-lock.json b/package-lock.json index 2e732bbd..ab3f4ce5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -22,6 +22,7 @@ "@eslint/js": "^9.39.2", "@eslint/json": "^0.14.0", "@eslint/markdown": "^7.5.1", + "@stylistic/eslint-plugin": "^6.0.1", "@types/eslint-plugin-security": "^3.0.1", "@types/google-apps-script": "^2.0.15", "@types/node": "^25.0.9", @@ -734,6 +735,66 @@ "dev": true, "license": "MIT" }, + "node_modules/@stylistic/eslint-plugin": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@stylistic/eslint-plugin/-/eslint-plugin-6.0.1.tgz", + "integrity": "sha512-7nyi2RmGIuzBYGq5C8cFaoQsh+COfo6oHMWCygzg2iaqJJ4RDThaKCMYRkkOUAQWv80R7sbBbpuKZfulH7bFcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.10.1", + "@typescript-eslint/types": "^8.72.2", + "@typescript-eslint/visitor-keys": "^8.72.2", + "espree": "^11.2.0", + "picomatch": "^4.0.7" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "peerDependencies": { + "eslint": "^9.0.0 || ^10.0.0", + "oxlint": "^1.55.0" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + }, + "oxlint": { + "optional": true + } + } + }, + "node_modules/@stylistic/eslint-plugin/node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@stylistic/eslint-plugin/node_modules/espree": { + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz", + "integrity": "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.16.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^5.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, "node_modules/@types/chai": { "version": "5.2.3", "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", diff --git a/package.json b/package.json index 9496149e..99dab1f5 100644 --- a/package.json +++ b/package.json @@ -105,6 +105,7 @@ "@eslint/js": "^9.39.2", "@eslint/json": "^0.14.0", "@eslint/markdown": "^7.5.1", + "@stylistic/eslint-plugin": "^6.0.1", "@types/eslint-plugin-security": "^3.0.1", "@types/google-apps-script": "^2.0.15", "@types/node": "^25.0.9", diff --git a/scripts/docs/author-batch.mjs b/scripts/docs/author-batch.mjs index 9342bbd2..66644b21 100644 --- a/scripts/docs/author-batch.mjs +++ b/scripts/docs/author-batch.mjs @@ -60,7 +60,10 @@ for (const file of readdirSync(AUTHORED).sort()) { const dir = join(ROOT, "docs/content", language.code, "functions"); mkdirSync(dir, { recursive: true }); - writeFileSync(join(dir, `${name}.json`), `${JSON.stringify(content, null, 2)}\n`); + + const json = JSON.stringify(content, null, 2); + + writeFileSync(join(dir, `${name}.json`), `${json}\n`); written += 1; } } diff --git a/scripts/docs/author-exceptions.mjs b/scripts/docs/author-exceptions.mjs index 354927a3..f196e752 100644 --- a/scripts/docs/author-exceptions.mjs +++ b/scripts/docs/author-exceptions.mjs @@ -260,7 +260,10 @@ for (const [name, data] of Object.entries(CLASSES)) { const dir = join(ROOT, "docs/content", language.code, "functions"); mkdirSync(dir, { recursive: true }); - writeFileSync(join(dir, `${name}.json`), `${JSON.stringify(content, null, 2)}\n`); + + const json = JSON.stringify(content, null, 2); + + writeFileSync(join(dir, `${name}.json`), `${json}\n`); written += 1; } } diff --git a/scripts/docs/author-guards.mjs b/scripts/docs/author-guards.mjs index 1e5d3c4e..5ae326f6 100644 --- a/scripts/docs/author-guards.mjs +++ b/scripts/docs/author-guards.mjs @@ -70,8 +70,8 @@ const TEMPLATES = { requireNonSummary: (s) => `Returns the value after checking that it is not ${s.non}.`, family: "`isX` and `nonX` answer a question and never interrupt control flow; `requireX` and `requireNonX` hand the value back or throw. The scheme is explained in [](validation-conventions.md).", - negation: (name) => - `\`${name}(value)\` is the same test as \`!${name.replace(/^non/, "is")}(value)\`, written so that a guard clause reads as a sentence rather than as a negation.`, + negation: (name, positive) => + `\`${name}(value)\` is the same test as \`!${positive}(value)\`, written so that a guard clause reads as a sentence rather than as a negation.`, valueParam: "The value to check.", validateParam: "The value to validate.", messageParam: () => "The message of the exception. A default is used when omitted.", @@ -98,8 +98,8 @@ const TEMPLATES = { requireNonSummary: (s) => `Возвращает значение, убедившись, что оно не является ${s.non}.`, family: "`isX` и `nonX` отвечают на вопрос и никогда не прерывают выполнение; `requireX` и `requireNonX` возвращают значение или выбрасывают исключение. Схема разобрана в [](validation-conventions.md).", - negation: (name) => - `\`${name}(value)\` — та же проверка, что и \`!${name.replace(/^non/, "is")}(value)\`, записанная так, чтобы охранное условие читалось как утверждение, а не как отрицание.`, + negation: (name, positive) => + `\`${name}(value)\` — та же проверка, что и \`!${positive}(value)\`, записанная так, чтобы охранное условие читалось как утверждение, а не как отрицание.`, valueParam: "Проверяемое значение.", validateParam: "Значение, которое нужно проверить.", messageParam: () => @@ -128,8 +128,8 @@ const TEMPLATES = { requireNonSummary: (s) => `Повертає значення, переконавшись, що воно не є ${s.non}.`, family: "`isX` та `nonX` відповідають на питання й ніколи не переривають виконання; `requireX` і `requireNonX` повертають значення або викидають виняток. Схему розібрано в [](validation-conventions.md).", - negation: (name) => - `\`${name}(value)\` — та сама перевірка, що й \`!${name.replace(/^non/, "is")}(value)\`, записана так, щоб охоронна умова читалася як твердження, а не як заперечення.`, + negation: (name, positive) => + `\`${name}(value)\` — та сама перевірка, що й \`!${positive}(value)\`, записана так, щоб охоронна умова читалася як твердження, а не як заперечення.`, valueParam: "Значення, що перевіряється.", validateParam: "Значення, яке потрібно перевірити.", messageParam: () => @@ -158,8 +158,8 @@ const TEMPLATES = { `Gibt den Wert zurück, nachdem geprüft wurde, dass er nicht ${s.non} ist.`, family: "`isX` und `nonX` beantworten eine Frage und unterbrechen den Ablauf nie; `requireX` und `requireNonX` geben den Wert zurück oder werfen. Das Schema erklärt [](validation-conventions.md).", - negation: (name) => - `\`${name}(value)\` ist dieselbe Prüfung wie \`!${name.replace(/^non/, "is")}(value)\`, so geschrieben, dass eine Wächterklausel sich wie ein Satz liest und nicht wie eine Verneinung.`, + negation: (name, positive) => + `\`${name}(value)\` ist dieselbe Prüfung wie \`!${positive}(value)\`, so geschrieben, dass eine Wächterklausel sich wie ein Satz liest und nicht wie eine Verneinung.`, valueParam: "Der zu prüfende Wert.", validateParam: "Der zu validierende Wert.", messageParam: () => @@ -188,8 +188,8 @@ const TEMPLATES = { requireNonSummary: (s) => `Renvoie la valeur après avoir vérifié qu'elle n'est pas ${s.non}.`, family: "`isX` et `nonX` répondent à une question sans jamais interrompre le flot ; `requireX` et `requireNonX` rendent la valeur ou lèvent. Le schéma est expliqué dans [](validation-conventions.md).", - negation: (name) => - `\`${name}(value)\` est le même test que \`!${name.replace(/^non/, "is")}(value)\`, écrit pour qu'une clause de garde se lise comme une phrase plutôt que comme une négation.`, + negation: (name, positive) => + `\`${name}(value)\` est le même test que \`!${positive}(value)\`, écrit pour qu'une clause de garde se lise comme une phrase plutôt que comme une négation.`, valueParam: "La valeur à vérifier.", validateParam: "La valeur à valider.", messageParam: () => "Le message de l'exception. À défaut, un message par défaut est utilisé.", @@ -301,7 +301,11 @@ for (const [module, subjects] of Object.entries(MODULES)) { if (present.non) { write(language.code, members.non, { summary: t.nonSummary(s), - description: [t.negation(members.non), s.note, t.family], + description: [ + t.negation(members.non, members.non.replace(/^non/, "is")), + s.note, + t.family + ], params: { value: t.valueParam }, returns: t.nonReturns(s), throws: {}, @@ -396,7 +400,10 @@ function write(code, name, content) { const dir = join(ROOT, "docs/content", code, "functions"); mkdirSync(dir, { recursive: true }); - writeFileSync(join(dir, `${name}.json`), `${JSON.stringify(content, null, 2)}\n`); + + const json = JSON.stringify(content, null, 2); + + writeFileSync(join(dir, `${name}.json`), `${json}\n`); written.push(`${code}/${name}`); } diff --git a/scripts/docs/finalize-site.mjs b/scripts/docs/finalize-site.mjs index 09991f3f..7b5af539 100644 --- a/scripts/docs/finalize-site.mjs +++ b/scripts/docs/finalize-site.mjs @@ -46,7 +46,9 @@ function pagesOf(dir, base = dir) { const full = join(dir, entry); if (statSync(full).isDirectory()) { - if (SKIP.has(entry) || (dir === base && CODES.has(entry))) { + const isLanguageRoot = dir === base && CODES.has(entry); + + if (SKIP.has(entry) || isLanguageRoot) { continue; } @@ -90,13 +92,19 @@ function injections(language) { * that runs none, both still see every translation. */ function languageRow(language, page, present) { - const links = present.map((other) => - other === language - ? `${other.name}` - : `${other.name}` - ); + const links = present.map((other) => { + if (other === language) { + return `${other.name}`; + } + + const href = urlOf(other, page); + + return `${other.name}`; + }); + + const row = links.join(' '); - return ``; + return ``; } const pages = pagesOf(root); @@ -121,10 +129,11 @@ for (const page of pages) { } const alternates = present - .map( - (language) => - `` - ) + .map((language) => { + const href = urlOf(language, page); + + return ``; + }) .join("\n "); const xDefault = ``; @@ -143,13 +152,25 @@ for (const page of pages) { const injected = injections(language); if (injected.head && !html.includes("SoftwareSourceCode")) { - html = `${html.slice(0, html.indexOf(""))}${injected.head}\n${html.slice(html.indexOf(""))}`; + const headEnd = html.indexOf(""); + + const beforeHead = html.slice(0, headEnd); + + const fromHead = html.slice(headEnd); + + html = `${beforeHead}${injected.head}\n${fromHead}`; } if (!html.includes('rel="alternate" hreflang=')) { - const canonical = ``; + const href = urlOf(language, page); + + const canonical = ``; - html = `${html.slice(0, at)} ${canonical}\n ${alternates}\n ${xDefault}\n${html.slice(at)}`; + const beforeHead = html.slice(0, at); + + const fromHead = html.slice(at); + + html = `${beforeHead} ${canonical}\n ${alternates}\n ${xDefault}\n${fromHead}`; linked += 1; } @@ -167,7 +188,13 @@ for (const page of pages) { if (article) { const at = html.indexOf(article[0]) + article[0].length; - html = `${html.slice(0, at)}${languageRow(language, page, present)}${html.slice(at)}`; + const row = languageRow(language, page, present); + + const before = html.slice(0, at); + + const after = html.slice(at); + + html = `${before}${row}${after}`; } } @@ -182,7 +209,11 @@ for (const page of pages) { const at = article === -1 ? html.lastIndexOf("") : article; if (at !== -1) { - html = `${html.slice(0, at)}${notice}\n${html.slice(at)}`; + const before = html.slice(0, at); + + const after = html.slice(at); + + html = `${before}${notice}\n${after}`; } } @@ -200,12 +231,15 @@ const sitemap = [ for (const { page, present } of entries) { for (const language of present) { sitemap.push(" "); - sitemap.push(` ${urlOf(language, page)}`); + + const loc = urlOf(language, page); + + sitemap.push(` ${loc}`); for (const other of present) { - sitemap.push( - ` ` - ); + const href = urlOf(other, page); + + sitemap.push(` `); } sitemap.push(` `); diff --git a/scripts/docs/generate-topics.mjs b/scripts/docs/generate-topics.mjs index 710f3646..c97fd1d3 100644 --- a/scripts/docs/generate-topics.mjs +++ b/scripts/docs/generate-topics.mjs @@ -26,7 +26,6 @@ import { mkdirSync, readdirSync, readFileSync, - rmSync, statSync, writeFileSync } from "node:fs"; @@ -164,11 +163,19 @@ function commentToText(comment) { } return comment - .map((part) => - ts.isJSDocLink(part) || ts.isJSDocLinkCode(part) || ts.isJSDocLinkPlain(part) - ? `{@link ${part.name?.getText() ?? ""}${part.text ?? ""}}` - : part.text - ) + .map((part) => { + const isLink = ts.isJSDocLink(part) || ts.isJSDocLinkCode(part) || ts.isJSDocLinkPlain(part); + + if (!isLink) { + return part.text; + } + + const name = part.name?.getText() ?? ""; + + const text = part.text ?? ""; + + return `{@link ${name}${text}}`; + }) .join(""); } @@ -225,12 +232,13 @@ function thrownClasses(nodes) { } const visit = (child) => { - if ( + const throwsNew = ts.isThrowStatement(child) && child.expression && ts.isNewExpression(child.expression) && - child.expression.expression - ) { + child.expression.expression; + + if (throwsNew) { const name = child.expression.expression.getText(); if (!found.includes(name)) { @@ -361,12 +369,14 @@ function signatureOf(nodes, source, kind) { const end = node.body ? node.body.getStart(source, false) : node.getEnd(); - return `${source.text + const declaration = source.text .slice(start, end) .trim() .replace(/\s*\{$/, "") .replace(/^export\s+/, "") - .replace(/\s+/g, " ")};`; + .replace(/\s+/g, " "); + + return `${declaration};`; }) .join("\n"); } @@ -499,7 +509,7 @@ function escapeCell(text) { return text.replace(/\\/g, "\\\\").replace(/\|/g, "\\|").replace(/\s+/g, " ").trim(); } -function renderPage(entry, language, content, sourceContent, pages, thrownBy) { +function renderPage({ entry, language, content, sourceContent, pages, thrownBy }) { const strings = language.strings; const jsdoc = entry.jsdoc; @@ -521,18 +531,23 @@ function renderPage(entry, language, content, sourceContent, pages, thrownBy) { lines.push(""); lines.push(`# ${entry.name}`); lines.push(""); - lines.push(`${summary.replace(/[<>]/g, "")}`); + + const plainSummary = summary.replace(/[<>]/g, ""); + + const title = entry.kind === "function" ? `${entry.name}()` : entry.name; + + const since = jsdoc.since ? ` · ${strings.since}: ${jsdoc.since}` : ""; + + const deprecated = jsdoc.deprecated ? ` · ${strings.deprecated}` : ""; + + lines.push(`${plainSummary}`); lines.push(""); lines.push( - `${entry.kind === "function" ? `${entry.name}()` : entry.name} — ${summary.replace(/[<>]/g, "")} @bootgs/utils, ${language.name}.` + `${title} — ${plainSummary} @bootgs/utils, ${language.name}.` ); lines.push(""); lines.push(""); - lines.push( - `

${strings.module}: ${entry.module}${jsdoc.since ? ` · ${strings.since}: ${jsdoc.since}` : ""}${ - jsdoc.deprecated ? ` · ${strings.deprecated}` : "" - }

` - ); + lines.push(`

${strings.module}: ${entry.module}${since}${deprecated}

`); lines.push("
"); lines.push(""); @@ -542,9 +557,9 @@ function renderPage(entry, language, content, sourceContent, pages, thrownBy) { } if (jsdoc.deprecated) { - lines.push( - `> **${strings.deprecated}.** ${resolveLinks(jsdoc.deprecated, pages).replace(/\n/g, " ")}` - ); + const reason = resolveLinks(jsdoc.deprecated, pages).replace(/\n/g, " "); + + lines.push(`> **${strings.deprecated}.** ${reason}`); lines.push(""); } @@ -577,11 +592,19 @@ function renderPage(entry, language, content, sourceContent, pages, thrownBy) { flags.push(`\`= ${param.default}\``); } - lines.push( - `| \`${param.rest ? "..." : ""}${param.name}\`${flags.length ? ` ${flags.join(" ")}` : ""} | ${ - param.type ? `\`${escapeCell(param.type)}\`` : "—" - } | ${escapeCell(resolveLinks(described, pages)) || "—"} |` - ); + const spread = param.rest ? "..." : ""; + + const flagList = flags.join(" "); + + const flagText = flags.length ? ` ${flagList}` : ""; + + const escapedType = param.type ? escapeCell(param.type) : ""; + + const typeCell = param.type ? `\`${escapedType}\`` : "—"; + + const descriptionCell = escapeCell(resolveLinks(described, pages)) || "—"; + + lines.push(`| \`${spread}${param.name}\`${flagText} | ${typeCell} | ${descriptionCell} |`); } lines.push(""); @@ -598,7 +621,10 @@ function renderPage(entry, language, content, sourceContent, pages, thrownBy) { lines.push(`## ${strings.returns}`); lines.push(""); - lines.push(shown ? `\`${shown}\`${described ? ` — ${described}` : ""}` : described); + + const suffix = described ? ` — ${described}` : ""; + + lines.push(shown ? `\`${shown}\`${suffix}` : described); if (predicate) { lines.push(""); @@ -658,9 +684,13 @@ function renderPage(entry, language, content, sourceContent, pages, thrownBy) { pending.push(...(thrownBy.get(called)?.calls ?? [])); } - if (reachable.size > 0 && !reachable.has(type) && !BUILT_IN_ERRORS.has(type)) { + const isKnownType = reachable.has(type) || BUILT_IN_ERRORS.has(type); + + if (reachable.size > 0 && !isKnownType) { + const reachableList = [...reachable].join(", "); + console.warn( - ` ${entry.name}: prose says it throws ${type}; reachable from the code: ${[...reachable].join(", ")}` + ` ${entry.name}: prose says it throws ${type}; reachable from the code: ${reachableList}` ); } @@ -676,7 +706,11 @@ function renderPage(entry, language, content, sourceContent, pages, thrownBy) { for (const [type, whens] of conditions) { for (const when of whens) { - lines.push(`| \`${escapeCell(type)}\` | ${escapeCell(resolveLinks(when, pages)) || "—"} |`); + const typeCell = escapeCell(type); + + const whenCell = escapeCell(resolveLinks(when, pages)) || "—"; + + lines.push(`| \`${typeCell}\` | ${whenCell} |`); } } @@ -728,7 +762,9 @@ function renderPage(entry, language, content, sourceContent, pages, thrownBy) { .replace(/^\((.*)\)$/s, "$1"); if (caption && !example.title) { - lines.push(`_${caption.replace(/\s+/g, " ")}_`); + const flatCaption = caption.replace(/\s+/g, " "); + + lines.push(`_${flatCaption}_`); lines.push(""); } @@ -749,7 +785,9 @@ function renderPage(entry, language, content, sourceContent, pages, thrownBy) { const short = String(target).replace(/^.*[.#]/, ""); - if (!pages.has(short) || short === entry.name || seen.has(short)) { + const isSkipped = short === entry.name || seen.has(short); + + if (!pages.has(short) || isSkipped) { continue; } @@ -776,7 +814,11 @@ function renderPage(entry, language, content, sourceContent, pages, thrownBy) { const [, label, url] = link; - if (url.toLowerCase().endsWith(`/${entry.name.toLowerCase()}.html`) || seen.has(url)) { + const ownSlug = entry.name.toLowerCase(); + + const ownPage = `/${ownSlug}.html`; + + if (url.toLowerCase().endsWith(ownPage) || seen.has(url)) { continue; } @@ -855,11 +897,15 @@ function localiseTables(english, translated, language, summaries) { const cells = row.split("|").slice(1, -1); if (index === 0) { - return `| ${cells.map((cell) => label(cell.trim(), strings)).join(" | ")} |`; + const headings = cells.map((cell) => label(cell.trim(), strings)).join(" | "); + + return `| ${headings} |`; } if (index === 1) { - return `|${cells.map(() => " :--- ").join("|")}|`; + const alignments = cells.map(() => " :--- ").join("|"); + + return `|${alignments}|`; } if (cells.length < 2) { @@ -871,14 +917,20 @@ function localiseTables(english, translated, language, summaries) { const summary = name ? summaries.get(name) : null; if (!summary) { - return `|${cells.join("|")}|`; + const joined = cells.join("|"); + + return `|${joined}|`; } const localised = cells.slice(); - localised[localised.length - 1] = ` ${escapeCell(summary)} `; + const escapedSummary = escapeCell(summary); - return `|${localised.join("|")}|`; + localised[localised.length - 1] = ` ${escapedSummary} `; + + const joined = localised.join("|"); + + return `|${joined}|`; }) .join("\n") ); @@ -1012,9 +1064,11 @@ for (const language of LANGUAGES) { ) : translation; + const trimmedBody = body.trim(); + emit( join(topics, name), - await pretty(`${MARKER} Translated topic. -->\n\n${body.trim()}\n`, join(topics, name)) + await pretty(`${MARKER} Translated topic. -->\n\n${trimmedBody}\n`, join(topics, name)) ); continue; @@ -1024,11 +1078,13 @@ for (const language of LANGUAGES) { const withNotice = english.replace(/^(# .*\n)/, `$1\n> ${language.strings.englishNotice}\n`); + const trimmedNotice = withNotice.trim(); + untranslated.push(name); emit( join(topics, name), await pretty( - `${MARKER} Untranslated topic, shown in English. -->\n\n${withNotice.trim()}\n`, + `${MARKER} Untranslated topic, shown in English. -->\n\n${trimmedNotice}\n`, join(topics, name) ) ); @@ -1063,7 +1119,10 @@ for (const language of LANGUAGES) { emit( target, - await pretty(renderPage(entry, language, content, english, pages, thrownBy), target) + await pretty( + renderPage({ entry, language, content, sourceContent: english, pages, thrownBy }), + target + ) ); } @@ -1071,10 +1130,9 @@ for (const language of LANGUAGES) { } // 4. The reference tables of the source project point at the pages. -const tableLink = new RegExp( - `\\[\`(\\w+)\`\\]\\(${REPO.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/src/[^)]+\\)`, - "g" -); +const escapedRepo = REPO.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + +const tableLink = new RegExp(`\\[\`(\\w+)\`\\]\\(${escapedRepo}/src/[^)]+\\)`, "g"); for (const topic of new Set(entries.map((entry) => entry.referenceTopic))) { const path = join(sourceRoot, "topics", topic); @@ -1130,7 +1188,9 @@ for (const language of LANGUAGES) { const total = entries.length + (language === SOURCE_LANGUAGE ? 0 : 15); - coverage.push(`| ${language.name} | ${total} | ${total - gaps.length} | ${gaps.length} |`); + const covered = total - gaps.length; + + coverage.push(`| ${language.name} | ${total} | ${covered} | ${gaps.length} |`); } coverage.push(""); @@ -1157,7 +1217,9 @@ if (CHECK && stale.length > 0) { } if (stale.length > 20) { - console.error(` … and ${stale.length - 20} more`); + const remaining = stale.length - 20; + + console.error(` … and ${remaining} more`); } process.exit(1); diff --git a/scripts/docs/site.mjs b/scripts/docs/site.mjs index 2badf3fc..237390b3 100644 --- a/scripts/docs/site.mjs +++ b/scripts/docs/site.mjs @@ -7,30 +7,8 @@ * language switcher is made once and lands in all five sites. */ -import { readFileSync } from "node:fs"; -import { fileURLToPath } from "node:url"; - import { LANGUAGES, SITE } from "./languages.mjs"; -/** - * The widget script, with this language's labels substituted in. - */ -function widget(language) { - const source = readFileSync( - fileURLToPath(new URL("./assets/search-widget.js", import.meta.url)), - "utf8" - ); - - const strings = JSON.stringify({ - hint: language.strings.searchHint, - missing: language.strings.searchMissing, - matches: language.strings.searchMatches, - empty: language.strings.searchEmpty - }); - - return source.replace("__ASU_STRINGS__", strings); -} - const ARTWORK = "https://darynamikhailenko.com/?utm_source=docs&utm_medium=footer&utm_campaign=apps-script-utils&utm_content=banner-artist-credit"; @@ -77,6 +55,12 @@ function settings(language, depth = 2) { } export function buildProfiles(language) { + const languageLinks = LANGUAGES.map( + (other) => ` ${other.name}` + ).join("\n"); + + const variables = settings(language); + return ` @@ -84,7 +68,7 @@ export function buildProfiles(language) { xsi:noNamespaceSchemaLocation="https://resources.jetbrains.com/writerside/1.0/build-profiles.xsd"> -${settings(language)} +${variables}
@@ -92,7 +76,7 @@ ${settings(language)} 2025–2026 Maksym Stoianov. Licensed under Apache-2.0. GitHub npm -${LANGUAGES.map((other) => ` ${other.name}`).join("\n")} +${languageLinks} Banner artwork: Daryna Mikhailenko
diff --git a/scripts/docs/sync-jsdoc-examples.mjs b/scripts/docs/sync-jsdoc-examples.mjs index 8f9ad956..cc4bac72 100644 --- a/scripts/docs/sync-jsdoc-examples.mjs +++ b/scripts/docs/sync-jsdoc-examples.mjs @@ -134,7 +134,9 @@ for (const file of listSources(SRC).sort()) { const blocks = statement.jsDoc ?? []; - if (!name || blocks.length === 0 || documented.has(name)) { + const isUndocumented = !name || blocks.length === 0; + + if (isUndocumented || documented.has(name)) { continue; } @@ -217,7 +219,9 @@ if (CHECK && stale.length > 0) { } if (stale.length > 20) { - console.error(` … and ${stale.length - 20} more`); + const remaining = stale.length - 20; + + console.error(` … and ${remaining} more`); } process.exit(1); diff --git a/scripts/docs/sync-jsdoc-links.mjs b/scripts/docs/sync-jsdoc-links.mjs index 16ce3668..caf4fa25 100644 --- a/scripts/docs/sync-jsdoc-links.mjs +++ b/scripts/docs/sync-jsdoc-links.mjs @@ -89,9 +89,11 @@ function referencesOf(text) { continue; } + const slug = kebab(klass); + urls.set( `Class ${klass}`, - `https://developers.google.com/apps-script/reference/${segment}/${kebab(klass)}` + `https://developers.google.com/apps-script/reference/${segment}/${slug}` ); } @@ -103,15 +105,18 @@ function isExported(node) { } function nameOf(statement) { - if ((ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) && statement.name) { + const isFunctionOrClass = ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement); + + if (isFunctionOrClass && statement.name) { return statement.name.getText(); } - if ( + const isTypeLike = ts.isInterfaceDeclaration(statement) || ts.isTypeAliasDeclaration(statement) || - ts.isEnumDeclaration(statement) - ) { + ts.isEnumDeclaration(statement); + + if (isTypeLike) { return statement.name.getText(); } @@ -142,7 +147,9 @@ for (const file of listSources(SRC).sort()) { const blocks = statement.jsDoc ?? []; - if (!name || blocks.length === 0 || documented.has(name)) { + const isUndocumented = !name || blocks.length === 0; + + if (isUndocumented || documented.has(name)) { continue; } @@ -155,7 +162,9 @@ for (const file of listSources(SRC).sort()) { // Writerside publishes every page in lower case, and GitHub Pages is // case-sensitive, so the link has to be lower case or it 404s. - const page = `${SITE}/${name.toLowerCase()}.html`; + const slug = name.toLowerCase(); + + const page = `${SITE}/${slug}.html`; const wanted = new Map([[`${name} on the documentation site`, page]]); @@ -265,7 +274,9 @@ if (CHECK && stale.length > 0) { } if (stale.length > 20) { - console.error(` … and ${stale.length - 20} more`); + const remaining = stale.length - 20; + + console.error(` … and ${remaining} more`); } process.exit(1); diff --git a/scripts/docs/verify-examples.mjs b/scripts/docs/verify-examples.mjs index 28c6b881..9b875db9 100644 --- a/scripts/docs/verify-examples.mjs +++ b/scripts/docs/verify-examples.mjs @@ -107,71 +107,80 @@ const used = new Set(); let skipped = 0; -for (const file of readdirSync(CONTENT).sort()) { - const content = JSON.parse(readFileSync(join(CONTENT, file), "utf8")); +/** + * Turns one example line into a test, or counts it as skipped when it cannot + * be checked. + */ +function addAssertion(name, line) { + const title = JSON.stringify(`${name}: ${line}`); - const name = file.replace(/\.json$/, ""); + const thrown = line.match(THROWS); - for (const example of content.examples ?? []) { - const body = example.body ?? ""; + const thrownArgs = thrown ? thrown[1].replace(/^[A-Za-z_$][\w$]*\(/, "").replace(/\)$/, "") : ""; - for (const block of body.matchAll(/```javascript\n([\s\S]*?)```/g)) { - for (const raw of block[1].split("\n")) { - const line = raw.trim(); + if (thrown && !evaluable(thrownArgs)) { + skipped += 1; - if (!line || line.startsWith("//")) { - continue; - } + return; + } - const thrown = line.match(THROWS); + if (thrown) { + assertions.push( + ` it(${title}, () => {\n expect(() => ${thrown[1]}).toThrow(${thrown[2]});\n });` + ); + used.add(thrown[2]); - if (thrown && !evaluable(thrown[1].replace(/^[A-Za-z_$][\w$]*\(/, "").replace(/\)$/, ""))) { - skipped += 1; + return; + } - continue; - } + const result = line.match(RESULT); - if (thrown) { - assertions.push( - ` it(${JSON.stringify(`${name}: ${line}`)}, () => {\n` + - ` expect(() => ${thrown[1]}).toThrow(${thrown[2]});\n });` - ); - used.add(thrown[2]); + if (!result) { + skipped += 1; - continue; - } + return; + } - const result = line.match(RESULT); + const expected = parseExpected(result[2]); - if (!result) { - skipped += 1; + const args = result[1].replace(/^[A-Za-z_$][\w$]*\(/, "").replace(/\)$/, ""); - continue; - } + if (expected === null || !evaluable(args)) { + skipped += 1; - const expected = parseExpected(result[2]); + return; + } + + // `requireX(value) // => value` documents identity, not a deep copy. + const call = result[1].match(/^([A-Za-z_$][\w$]*)\((.*)\)$/); - const args = result[1].replace(/^[A-Za-z_$][\w$]*\(/, "").replace(/\)$/, ""); + const identity = call && call[2].trim() === expected.trim(); - if (expected === null || !evaluable(args)) { - skipped += 1; + assertions.push( + identity + ? ` it(${title}, () => {\n` + + ` const value = ${expected};\n` + + ` expect(${call[1]}(value)).toBe(value);\n });` + : ` it(${title}, () => {\n expect(${result[1]}).toStrictEqual(${expected});\n });` + ); +} + +for (const file of readdirSync(CONTENT).sort()) { + const content = JSON.parse(readFileSync(join(CONTENT, file), "utf8")); - continue; - } + const name = file.replace(/\.json$/, ""); - // `requireX(value) // => value` documents identity, not a deep copy. - const call = result[1].match(/^([A-Za-z_$][\w$]*)\((.*)\)$/); + for (const example of content.examples ?? []) { + const body = example.body ?? ""; - const identity = call && call[2].trim() === expected.trim(); + for (const block of body.matchAll(/```javascript\n([\s\S]*?)```/g)) { + const lines = block[1] + .split("\n") + .map((raw) => raw.trim()) + .filter((line) => line && !line.startsWith("//")); - assertions.push( - identity - ? ` it(${JSON.stringify(`${name}: ${line}`)}, () => {\n` + - ` const value = ${expected};\n` + - ` expect(${call[1]}(value)).toBe(value);\n });` - : ` it(${JSON.stringify(`${name}: ${line}`)}, () => {\n` + - ` expect(${result[1]}).toStrictEqual(${expected});\n });` - ); + for (const line of lines) { + addAssertion(name, line); } } } diff --git a/scripts/docs/write-help-versions.mjs b/scripts/docs/write-help-versions.mjs index 466f235f..3342638d 100644 --- a/scripts/docs/write-help-versions.mjs +++ b/scripts/docs/write-help-versions.mjs @@ -53,8 +53,10 @@ const versions = [ })) ]; -writeFileSync(join(dir, "help-versions.json"), `${JSON.stringify(versions, null, 2)}\n`); +const versionsJson = JSON.stringify(versions, null, 2); -console.log( - `help-versions.json: ${versions.length} version(s) — ${versions.map((entry) => entry.version).join(", ")}` -); +writeFileSync(join(dir, "help-versions.json"), `${versionsJson}\n`); + +const versionList = versions.map((entry) => entry.version).join(", "); + +console.log(`help-versions.json: ${versions.length} version(s) — ${versionList}`); diff --git a/scripts/lib/three-way-merge.mjs b/scripts/lib/three-way-merge.mjs index bc93bead..3ee7f1ea 100644 --- a/scripts/lib/three-way-merge.mjs +++ b/scripts/lib/three-way-merge.mjs @@ -71,7 +71,9 @@ export function mergeEntries(ancestor, ours, theirs, compare) { const changedByThem = t.text !== entry.text; - if (changedByUs && changedByThem && o.text !== t.text) { + const changedByBoth = changedByUs && changedByThem; + + if (changedByBoth && o.text !== t.text) { return null; } diff --git a/scripts/merge-module-index.mjs b/scripts/merge-module-index.mjs index 6771776a..e96c6bef 100644 --- a/scripts/merge-module-index.mjs +++ b/scripts/merge-module-index.mjs @@ -177,7 +177,9 @@ function main() { const t = parse(theirs); - if (!a || !o || !t) { + const unparsed = !a || !o || !t; + + if (unparsed) { return fallback(); } diff --git a/scripts/merge-reference-tables.mjs b/scripts/merge-reference-tables.mjs index e38eaeb3..8d0dee4e 100644 --- a/scripts/merge-reference-tables.mjs +++ b/scripts/merge-reference-tables.mjs @@ -197,7 +197,9 @@ function main() { const t = parse(theirs); - if (!a || !o || !t) { + const unparsed = !a || !o || !t; + + if (unparsed) { return fallback(); } diff --git a/src/appsscript/admin/isAdmin.ts b/src/appsscript/admin/isAdmin.ts index 0b8196bd..a07f4920 100644 --- a/src/appsscript/admin/isAdmin.ts +++ b/src/appsscript/admin/isAdmin.ts @@ -34,6 +34,8 @@ export function isAdmin(): boolean { return !!user.isAdmin; } catch (err: unknown) { + // The error is swallowed into `false`; the Apps Script log is its only trace. + // eslint-disable-next-line no-console console.warn(`[Error]: ${err}`); } diff --git a/src/appsscript/base/getByteSize.ts b/src/appsscript/base/getByteSize.ts index 10ca35e8..8db7748d 100644 --- a/src/appsscript/base/getByteSize.ts +++ b/src/appsscript/base/getByteSize.ts @@ -29,6 +29,6 @@ export function getByteSize(value: string): number { // .replace(/[\u{0800}-\u{D7FF}\u{E000}-\u{FFFF}]/u, '0') // 0000 - .replace(/[\u{D800}-\u{DFFF}]/u, "00").length + .replace(/[\uD800-\uDFFF]/u, "00").length ); } diff --git a/src/appsscript/sheet/appendColumns.ts b/src/appsscript/sheet/appendColumns.ts index 152d14a7..5c07d3b7 100644 --- a/src/appsscript/sheet/appendColumns.ts +++ b/src/appsscript/sheet/appendColumns.ts @@ -4,6 +4,26 @@ import { isConsistent2DArray, isNil } from "../../lang"; import { isRange } from "./isRange"; import { isSheet } from "./isSheet"; +/** + * Returns how many leading columns of the cells hold data: the position of + * the rightmost non-blank cell across all rows, or 0 when every cell is blank. + */ +function countFilledColumns(cells: unknown[][]): number { + let filled = 0; + + for (const row of cells) { + for (let column = row.length; column > filled; column--) { + if (!isBlank(row[column - 1])) { + filled = column; + + break; + } + } + } + + return filled; +} + /** * A cell counts as data unless it is empty: `0` and `false` are values a caller put there. */ @@ -106,19 +126,7 @@ export function appendColumns( let columnPosition: number; if (within) { - const cells = within.getValues(); - - let filled = 0; - - for (const row of cells) { - for (let column = row.length; column > filled; column--) { - if (!isBlank(row[column - 1])) { - filled = column; - - break; - } - } - } + const filled = countFilledColumns(within.getValues()); columnPosition = within.getColumn() + filled - 1; } else { diff --git a/src/appsscript/sheet/deleteColumnsByConditional.ts b/src/appsscript/sheet/deleteColumnsByConditional.ts index 7e1f1129..35c197d1 100644 --- a/src/appsscript/sheet/deleteColumnsByConditional.ts +++ b/src/appsscript/sheet/deleteColumnsByConditional.ts @@ -187,7 +187,9 @@ export function deleteColumnsByConditional( const selected: number[] = selectColumns(values, predicate, headerColumn, range.getColumn()); - if (!within && selected.length > 0 && selected.length === sheet.getMaxColumns()) { + const deletesFromWholeSheet = !within && selected.length > 0; + + if (deletesFromWholeSheet && selected.length === sheet.getMaxColumns()) { throw new IllegalArgumentException( "Refusing to delete every column: a sheet must keep at least one." ); diff --git a/src/appsscript/sheet/deleteRowsByConditional.ts b/src/appsscript/sheet/deleteRowsByConditional.ts index 0bea14dc..71545451 100644 --- a/src/appsscript/sheet/deleteRowsByConditional.ts +++ b/src/appsscript/sheet/deleteRowsByConditional.ts @@ -167,7 +167,9 @@ export function deleteRowsByConditional( const selected: number[] = selectRows(values, predicate, headerRow, range.getRow()); - if (!within && selected.length > 0 && selected.length === sheet.getMaxRows()) { + const deletesFromWholeSheet = !within && selected.length > 0; + + if (deletesFromWholeSheet && selected.length === sheet.getMaxRows()) { throw new IllegalArgumentException( "Refusing to delete every row: a sheet must keep at least one." ); diff --git a/src/appsscript/sheet/doGridRangesIntersect.ts b/src/appsscript/sheet/doGridRangesIntersect.ts index fd933126..78d1c8c6 100644 --- a/src/appsscript/sheet/doGridRangesIntersect.ts +++ b/src/appsscript/sheet/doGridRangesIntersect.ts @@ -52,14 +52,15 @@ export function doGridRangesIntersect(gridRange1: GridRange, gridRange2: GridRan : true; if (!sheetIdsMatch || !sheetNamesMatch) { - if ( - (isValidSheetId(gridRange1.sheetId) && - isValidSheetId(gridRange2.sheetId) && - !sheetIdsMatch) || - (isValidSheetName(gridRange1.sheetName) && - isValidSheetName(gridRange2.sheetName) && - !sheetNamesMatch) - ) { + const sheetIdsConflict = + isValidSheetId(gridRange1.sheetId) && isValidSheetId(gridRange2.sheetId) && !sheetIdsMatch; + + const sheetNamesConflict = + isValidSheetName(gridRange1.sheetName) && + isValidSheetName(gridRange2.sheetName) && + !sheetNamesMatch; + + if (sheetIdsConflict || sheetNamesConflict) { return false; } } diff --git a/src/appsscript/sheet/highlightHtml.ts b/src/appsscript/sheet/highlightHtml.ts index f29f00a1..4933810d 100644 --- a/src/appsscript/sheet/highlightHtml.ts +++ b/src/appsscript/sheet/highlightHtml.ts @@ -190,17 +190,20 @@ export function highlightHtml( const startIndex = match.index; - if (fullMatchText.startsWith("")) { + const isComment = fullMatchText.startsWith(""); + + const isTag = + fullMatchText.startsWith("<") || + fullMatchText.startsWith(""); + + if (isComment) { richTextBuilder.setTextStyle( startIndex, startIndex + fullMatchText.length, textStyles.comment ); - } else if ( - fullMatchText.startsWith("<") || - fullMatchText.startsWith("") - ) { + } else if (isTag) { richTextBuilder.setTextStyle( match.index, match.index + fullMatchText.length, diff --git a/src/appsscript/sheet/isCellGridRange.ts b/src/appsscript/sheet/isCellGridRange.ts index 4285acf7..7c8a772f 100644 --- a/src/appsscript/sheet/isCellGridRange.ts +++ b/src/appsscript/sheet/isCellGridRange.ts @@ -30,12 +30,13 @@ export function isCellGridRange(gridRange: GridRange): boolean { const { startRowIndex, endRowIndex, startColumnIndex, endColumnIndex } = gridRange; - if ( + const hasAllBounds = nonNil(startRowIndex) && nonNil(endRowIndex) && nonNil(startColumnIndex) && - nonNil(endColumnIndex) - ) { + nonNil(endColumnIndex); + + if (hasAllBounds) { const isSingleRow = endRowIndex - startRowIndex === 1; const isSingleColumn = endColumnIndex - startColumnIndex === 1; diff --git a/src/appsscript/sheet/isGridRangeContainedIn.ts b/src/appsscript/sheet/isGridRangeContainedIn.ts index 8c2e77a3..e4ca3c26 100644 --- a/src/appsscript/sheet/isGridRangeContainedIn.ts +++ b/src/appsscript/sheet/isGridRangeContainedIn.ts @@ -45,10 +45,13 @@ export function isGridRangeContainedIn( : true; if (!sheetIdsMatch || !sheetNamesMatch) { - if ( - (containerGridRange.sheetId != null && gridRange.sheetId != null && !sheetIdsMatch) || - (containerGridRange.sheetName != null && gridRange.sheetName != null && !sheetNamesMatch) - ) { + const sheetIdsConflict = + containerGridRange.sheetId != null && gridRange.sheetId != null && !sheetIdsMatch; + + const sheetNamesConflict = + containerGridRange.sheetName != null && gridRange.sheetName != null && !sheetNamesMatch; + + if (sheetIdsConflict || sheetNamesConflict) { return false; } } diff --git a/src/appsscript/sheet/isGridRangeSameDimensions.ts b/src/appsscript/sheet/isGridRangeSameDimensions.ts index fcae6a91..b5cebf8b 100644 --- a/src/appsscript/sheet/isGridRangeSameDimensions.ts +++ b/src/appsscript/sheet/isGridRangeSameDimensions.ts @@ -32,12 +32,13 @@ export function isGridRangeSameDimensions(range1: GridRange, range2: GridRange): const getDimensions = (gridRange: GridRange): { height: number; width: number } | null => { const { startRowIndex, endRowIndex, startColumnIndex, endColumnIndex } = gridRange; - if ( + const hasMissingBound = isNil(startRowIndex) || isNil(endRowIndex) || isNil(startColumnIndex) || - isNil(endColumnIndex) - ) { + isNil(endColumnIndex); + + if (hasMissingBound) { return null; } diff --git a/src/appsscript/sheet/isValidSheetName.ts b/src/appsscript/sheet/isValidSheetName.ts index daf77357..71d6763e 100644 --- a/src/appsscript/sheet/isValidSheetName.ts +++ b/src/appsscript/sheet/isValidSheetName.ts @@ -1,13 +1,19 @@ // SPDX-License-Identifier: Apache-2.0 import { isString } from "../../lang"; -/** Google Sheets rejects these characters anywhere in a sheet name. */ +/** + * Google Sheets rejects these characters anywhere in a sheet name. + */ const FORBIDDEN_CHARACTERS = /[\\/?*[\]]/; -/** Google Sheets caps a sheet name at 100 characters. */ +/** + * Google Sheets caps a sheet name at 100 characters. + */ const MAX_LENGTH = 100; -/** Google Sheets reserves this name, regardless of case. */ +/** + * Google Sheets reserves this name, regardless of case. + */ const RESERVED_NAME = "history"; /** diff --git a/src/appsscript/sheet/isValidSpreadsheetId.ts b/src/appsscript/sheet/isValidSpreadsheetId.ts index cfa264df..376451fd 100644 --- a/src/appsscript/sheet/isValidSpreadsheetId.ts +++ b/src/appsscript/sheet/isValidSpreadsheetId.ts @@ -1,7 +1,9 @@ // SPDX-License-Identifier: Apache-2.0 import { isString } from "../../lang"; -/** Drive file ids are at least 25 characters from an unreserved alphabet. */ +/** + * Drive file ids are at least 25 characters from an unreserved alphabet. + */ const PATTERN = /^[a-zA-Z0-9-_]{25,}$/; /** diff --git a/src/appsscript/sheet/parseA1Notation.ts b/src/appsscript/sheet/parseA1Notation.ts index 33dc2b1f..a3840d59 100644 --- a/src/appsscript/sheet/parseA1Notation.ts +++ b/src/appsscript/sheet/parseA1Notation.ts @@ -5,11 +5,13 @@ import { getColumnIndexByLetter } from "./getColumnIndexByLetter"; import { getColumnLetterByIndex } from "./getColumnLetterByIndex"; import type { GridRange } from "./types"; +// Optional parts are written as `(?:...|)` rather than `(...)?`: the same +// match, without a quantifier around a quantified group. const SHEET_AND_RANGE_REGEX = - /^(?:'(?[^']*(?:''[^']*)*)'|"(?[^"]*(?:""[^"]*)*)"|(?[A-Z][A-Z0-9_]*))!(?.*)$/i; + /^(?:'(?(?:[^']|'')*)'|"(?(?:[^"]|"")*)"|(?[A-Z][A-Z0-9_]*))!(?.*)$/i; const A1_RANGE_REGEX = - /^(?[A-Z]*)(?\d*)(?::(?[A-Z]*)(?\d*))?$/i; + /^(?[A-Z]*)(?\d*)(?::(?[A-Z]*)(?\d*)|)$/i; /** * Parses an A1 notation string into a GridRange object. @@ -84,13 +86,19 @@ export function parseA1Notation(a1Notation: string): GridRange { let eCol = endCol ? getColumnIndexByLetter(endCol) : null; if (hasColon) { + const hasBothCols = nonNull(sCol) && nonNull(eCol); + + const isOpenEnded = nonNull(sRow) && hasBothCols && isNull(eRow); + + const isOpenStarted = isNull(sRow) && hasBothCols && nonNull(eRow); + if (isNull(sRow) && isNull(eRow)) { sRow = 0; } else if (isNull(sCol) && isNull(eCol)) { sCol = 0; - } else if (nonNull(sRow) && nonNull(sCol) && nonNull(eCol) && isNull(eRow)) { + } else if (isOpenEnded) { // Keep eRow as null (unbounded) - } else if (isNull(sRow) && nonNull(sCol) && nonNull(eCol) && nonNull(eRow)) { + } else if (isOpenStarted) { sRow = 0; } } else { @@ -109,12 +117,16 @@ export function parseA1Notation(a1Notation: string): GridRange { } // Normalize: ensure start <= end if both are present - if (nonNull(sRow) && nonNull(eRow) && sRow > eRow) { - [sRow, eRow] = [eRow, sRow]; + if (nonNull(sRow) && nonNull(eRow)) { + if (sRow > eRow) { + [sRow, eRow] = [eRow, sRow]; + } } - if (nonNull(sCol) && nonNull(eCol) && sCol > eCol) { - [sCol, eCol] = [eCol, sCol]; + if (nonNull(sCol) && nonNull(eCol)) { + if (sCol > eCol) { + [sCol, eCol] = [eCol, sCol]; + } } const startRowIndex = sRow; @@ -205,79 +217,69 @@ function generateCanonicalA1(params: { const sRowNum = nonNull(startRowIndex) ? startRowIndex + 1 : ""; - // Single cell case - if ( - !hasColon && + const isSingleCell = nonNull(startColumnIndex) && nonNull(startRowIndex) && nonNull(endColumnIndex) && nonNull(endRowIndex) && startColumnIndex === endColumnIndex - 1 && - startRowIndex === endRowIndex - 1 - ) { - return `${sColLetter}${sRowNum}`; - } + startRowIndex === endRowIndex - 1; - // Single column case (B -> B:B) - if ( - !hasColon && + const isWholeColumns = nonNull(startColumnIndex) && nonNull(endColumnIndex) && startRowIndex === 0 && - isNull(endRowIndex) - ) { - return `${sColLetter}:${sColLetter}`; - } + isNull(endRowIndex); - // Single row case (5 -> 5:5) - if ( - !hasColon && + const isWholeRows = nonNull(startRowIndex) && nonNull(endRowIndex) && startColumnIndex === 0 && - isNull(endColumnIndex) - ) { + isNull(endColumnIndex); + + const hasStartCell = Boolean(startCol && startRow); + + const hasEndCell = Boolean(endCol && endRow); + + const hasColumnsOnly = Boolean(startCol && endCol && !startRow && !endRow); + + const hasRowsOnly = Boolean(startRow && endRow && !startCol && !endCol); + + const hasOpenEnd = Boolean(startCol && startRow && endCol && !endRow); + + const hasOpenStart = Boolean(startCol && endCol && endRow && !startRow); + + // Single cell case + if (!hasColon && isSingleCell) { + return `${sColLetter}${sRowNum}`; + } + + // Single column case (B -> B:B) + if (!hasColon && isWholeColumns) { + return `${sColLetter}:${sColLetter}`; + } + + // Single row case (5 -> 5:5) + if (!hasColon && isWholeRows) { return `${sRowNum}:${sRowNum}`; } // B2:B2 -> B2 - if ( - hasColon && - nonNull(startColumnIndex) && - nonNull(startRowIndex) && - nonNull(endColumnIndex) && - nonNull(endRowIndex) && - startColumnIndex === endColumnIndex - 1 && - startRowIndex === endRowIndex - 1 - ) { + if (hasColon && isSingleCell) { return `${sColLetter}${sRowNum}`; } // Column range (A:B) - if ( - hasColon && - nonNull(startColumnIndex) && - nonNull(endColumnIndex) && - startRowIndex === 0 && - isNull(endRowIndex) && - startCol && - endCol && - !startRow && - !endRow - ) { + const isColumnRange = isWholeColumns && hasColumnsOnly; + + if (hasColon && isColumnRange) { const eColLetter = getColumnLetterByIndex(endColumnIndex - 1); return `${sColLetter}:${eColLetter}`; } // Special GAS Cases for B:B if it was parsed from B - if ( - !hasColon && - nonNull(startColumnIndex) && - nonNull(endColumnIndex) && - startRowIndex === 0 && - isNull(endRowIndex) - ) { + if (!hasColon && isWholeColumns) { return `${sColLetter}:${sColLetter}`; } @@ -286,23 +288,23 @@ function generateCanonicalA1(params: { const eRowNum = nonNull(endRowIndex) ? endRowIndex : ""; - if (startCol && startRow && endCol && endRow) { + if (hasStartCell && hasEndCell) { return `${sColLetter}${sRowNum}:${eColLetter}${eRowNum}`; } - if (startCol && endCol && !startRow && !endRow) { + if (hasColumnsOnly) { return `${sColLetter}:${eColLetter}`; } - if (startRow && endRow && !startCol && !endCol) { + if (hasRowsOnly) { return `${sRowNum}:${eRowNum}`; } - if (startCol && startRow && endCol && !endRow) { + if (hasOpenEnd) { return `${sColLetter}${sRowNum}:${eColLetter}`; } - if (startCol && endCol && endRow && !startRow) { + if (hasOpenStart) { return `${sColLetter}:${eColLetter}${eRowNum}`; } } diff --git a/src/appsscript/sheet/prependColumns.ts b/src/appsscript/sheet/prependColumns.ts index f55a3865..3e7a829e 100644 --- a/src/appsscript/sheet/prependColumns.ts +++ b/src/appsscript/sheet/prependColumns.ts @@ -108,11 +108,9 @@ export function prependColumns( // Inserting at or before the boundary pushes it along with the data; // put it back when the caller asked to prepend before it. - if ( - !effectiveOptions.afterFrozenColumns && - frozenColumns > 0 && - columnPosition <= frozenColumns - ) { + const insertedInFrozen = frozenColumns > 0 && columnPosition <= frozenColumns; + + if (!effectiveOptions.afterFrozenColumns && insertedInFrozen) { sheet.setFrozenColumns(frozenColumns); } } diff --git a/src/appsscript/sheet/prependRows.ts b/src/appsscript/sheet/prependRows.ts index 186e5470..9ce51c73 100644 --- a/src/appsscript/sheet/prependRows.ts +++ b/src/appsscript/sheet/prependRows.ts @@ -107,11 +107,9 @@ export function prependRows( // Inserting at or above the boundary pushes it along with the data; // put it back when the caller asked to prepend before it. - if ( - effectiveOptions.afterFrozenRows === false && - frozenRows > 0 && - rowPosition <= frozenRows - ) { + const insertedInFrozen = frozenRows > 0 && rowPosition <= frozenRows; + + if (effectiveOptions.afterFrozenRows === false && insertedInFrozen) { sheet.setFrozenRows(frozenRows); } } diff --git a/src/appsscript/sheet/requireGridRangeContainedIn.ts b/src/appsscript/sheet/requireGridRangeContainedIn.ts index 8c1bb105..5d33a519 100644 --- a/src/appsscript/sheet/requireGridRangeContainedIn.ts +++ b/src/appsscript/sheet/requireGridRangeContainedIn.ts @@ -3,13 +3,23 @@ import { InvalidGridRangeException } from "../../exception"; import { isGridRangeContainedIn } from "./isGridRangeContainedIn"; import type { GridRange } from "./types"; -/** Renders a grid range as `rows a–b, columns c–d`, leaving open bounds as `…`. */ +/** + * Renders a grid range as `rows a–b, columns c–d`, leaving open bounds as `…`. + */ function describeBounds(gridRange: GridRange): string { const { startRowIndex, endRowIndex, startColumnIndex, endColumnIndex } = gridRange ?? {}; const bound = (value: number | null | undefined): string => (value == null ? "…" : `${value}`); - return `rows ${bound(startRowIndex)}–${bound(endRowIndex)}, columns ${bound(startColumnIndex)}–${bound(endColumnIndex)}`; + const startRow = bound(startRowIndex); + + const endRow = bound(endRowIndex); + + const startColumn = bound(startColumnIndex); + + const endColumn = bound(endColumnIndex); + + return `rows ${startRow}–${endRow}, columns ${startColumn}–${endColumn}`; } /** @@ -48,10 +58,11 @@ export function requireGridRangeContainedIn( message?: string ): GridRange { if (!isGridRangeContainedIn(gridRange, containerGridRange)) { - throw new InvalidGridRangeException( - message ?? - `Expected ${describeBounds(gridRange)} to lie within ${describeBounds(containerGridRange)}.` - ); + const inner = describeBounds(gridRange); + + const outer = describeBounds(containerGridRange); + + throw new InvalidGridRangeException(message ?? `Expected ${inner} to lie within ${outer}.`); } return gridRange; diff --git a/src/appsscript/sheet/requireGridRangeSameDimensions.ts b/src/appsscript/sheet/requireGridRangeSameDimensions.ts index ae41c4df..74bdf855 100644 --- a/src/appsscript/sheet/requireGridRangeSameDimensions.ts +++ b/src/appsscript/sheet/requireGridRangeSameDimensions.ts @@ -3,20 +3,27 @@ import { InvalidGridRangeException } from "../../exception"; import { isGridRangeSameDimensions } from "./isGridRangeSameDimensions"; import type { GridRange } from "./types"; -/** Renders a grid range as `rows × columns`, or `unknown` when a bound is missing. */ +/** + * Renders a grid range as `rows × columns`, or `unknown` when a bound is missing. + */ function describeShape(gridRange: GridRange): string { const { startRowIndex, endRowIndex, startColumnIndex, endColumnIndex } = gridRange ?? {}; - if ( + const hasMissingBound = startRowIndex == null || endRowIndex == null || startColumnIndex == null || - endColumnIndex == null - ) { + endColumnIndex == null; + + if (hasMissingBound) { return "unknown"; } - return `${endRowIndex - startRowIndex} × ${endColumnIndex - startColumnIndex}`; + const rows = endRowIndex - startRowIndex; + + const columns = endColumnIndex - startColumnIndex; + + return `${rows} × ${columns}`; } /** @@ -52,9 +59,12 @@ export function requireGridRangeSameDimensions( message?: string ): void { if (!isGridRangeSameDimensions(range1, range2)) { + const shape1 = describeShape(range1); + + const shape2 = describeShape(range2); + throw new InvalidGridRangeException( - message ?? - `Expected grid ranges of equal dimensions, but received ${describeShape(range1)} and ${describeShape(range2)}.` + message ?? `Expected grid ranges of equal dimensions, but received ${shape1} and ${shape2}.` ); } } diff --git a/src/appsscript/sheet/requireValidSpreadsheetId.ts b/src/appsscript/sheet/requireValidSpreadsheetId.ts index 164623e4..d294fda4 100644 --- a/src/appsscript/sheet/requireValidSpreadsheetId.ts +++ b/src/appsscript/sheet/requireValidSpreadsheetId.ts @@ -3,7 +3,9 @@ import { IllegalArgumentException } from "../../exception"; import { isString } from "../../lang"; import { isValidSpreadsheetId } from "./isValidSpreadsheetId"; -/** Recognises a value that is a Sheets URL rather than an id. */ +/** + * Recognises a value that is a Sheets URL rather than an id. + */ const SHEETS_URL = /docs\.google\.com\/spreadsheets/; /** diff --git a/src/appsscript/sheet/sortSheets.ts b/src/appsscript/sheet/sortSheets.ts index 0d5b4004..c03908bd 100644 --- a/src/appsscript/sheet/sortSheets.ts +++ b/src/appsscript/sheet/sortSheets.ts @@ -58,6 +58,8 @@ export function sortSheets( } }); } catch (err: unknown) { + // The error is swallowed; the Apps Script log is its only trace. + // eslint-disable-next-line no-console console.error(`Failed to sort sheets: ${err}`); } } diff --git a/src/appsscript/sheet/toA1Notation.ts b/src/appsscript/sheet/toA1Notation.ts index b0a4a075..388d31f2 100644 --- a/src/appsscript/sheet/toA1Notation.ts +++ b/src/appsscript/sheet/toA1Notation.ts @@ -75,16 +75,27 @@ export function toA1Notation(gridRange: GridRange): string { ? getColumnLetterByIndex((endColumnIndex as number) - 1) : ""; - if ( - hasStartCol && - hasStartRow && - hasEndCol && - hasEndRow && + const hasStartCell = hasStartCol && hasStartRow; + + const hasEndCell = hasEndCol && hasEndRow; + + const isSingleCell = + hasStartCell && + hasEndCell && (endColumnIndex as number) === (startColumnIndex as number) + 1 && - (endRowIndex as number) === (startRowIndex as number) + 1 - ) { + (endRowIndex as number) === (startRowIndex as number) + 1; + + const isFullColumns = hasStartCell && (startRowIndex as number) === 0 && !hasEndRow; + + const isFullRows = hasStartCell && (startColumnIndex as number) === 0 && !hasEndCol; + + const isOpenEnded = hasStartCell && hasEndCol && !hasEndRow; + + const isBounded = hasStartCell && hasEndCell; + + if (isSingleCell) { rangePart = `${a1StartColLetter}${a1StartRowNumber}`; - } else if (hasStartCol && hasStartRow && (startRowIndex as number) === 0 && !hasEndRow) { + } else if (isFullColumns) { if (hasEndCol && (endColumnIndex as number) > (startColumnIndex as number) + 1) { rangePart = `${a1StartColLetter}:${a1EndColLetter}`; } else if (hasEndCol && (endColumnIndex as number) === (startColumnIndex as number) + 1) { @@ -96,7 +107,7 @@ export function toA1Notation(gridRange: GridRange): string { `Invalid or incomplete GridRange object for full column A1 notation conversion.` ); } - } else if (hasStartRow && hasStartCol && (startColumnIndex as number) === 0 && !hasEndCol) { + } else if (isFullRows) { if (hasEndRow && (endRowIndex as number) > (startRowIndex as number) + 1) { rangePart = `${a1StartRowNumber}:${a1EndRowNumber}`; } else if (hasEndRow && (endRowIndex as number) === (startRowIndex as number) + 1) { @@ -108,9 +119,9 @@ export function toA1Notation(gridRange: GridRange): string { `Invalid or incomplete GridRange object for full row A1 notation conversion.` ); } - } else if (hasStartCol && hasStartRow && hasEndCol && !hasEndRow) { + } else if (isOpenEnded) { rangePart = `${a1StartColLetter}${a1StartRowNumber}:${a1EndColLetter}`; - } else if (hasStartCol && hasStartRow && hasEndCol && hasEndRow) { + } else if (isBounded) { rangePart = `${a1StartColLetter}${a1StartRowNumber}:${a1EndColLetter}${a1EndRowNumber}`; } else { throw new Error(`Invalid or incomplete GridRange object for A1 notation conversion.`); @@ -127,7 +138,9 @@ export function toA1Notation(gridRange: GridRange): string { } else if (!sheetName.includes('"')) { fullA1Notation += `"${sheetName}"!`; } else { - fullA1Notation += `'${sheetName.replace(/'/g, "''")}'!`; + const escapedSheetName = sheetName.replace(/'/g, "''"); + + fullA1Notation += `'${escapedSheetName}'!`; } } else { fullA1Notation += `${sheetName}!`; diff --git a/src/appsscript/sheet/updateSheetNameInA1Notation.ts b/src/appsscript/sheet/updateSheetNameInA1Notation.ts index aedb4402..56d4e5fc 100644 --- a/src/appsscript/sheet/updateSheetNameInA1Notation.ts +++ b/src/appsscript/sheet/updateSheetNameInA1Notation.ts @@ -56,5 +56,7 @@ export function updateSheetNameInA1Notation(a1Notation: string, sheetName?: stri return `"${sheetName}"!${range}`; } - return `'${sheetName.replace(/'/g, "''")}'!${range}`; + const escapedSheetName = sheetName.replace(/'/g, "''"); + + return `'${escapedSheetName}'!${range}`; } diff --git a/src/appsscript/slide/convertMarkdownToRichText.ts b/src/appsscript/slide/convertMarkdownToRichText.ts index dc5c95f2..7689ab21 100644 --- a/src/appsscript/slide/convertMarkdownToRichText.ts +++ b/src/appsscript/slide/convertMarkdownToRichText.ts @@ -84,9 +84,13 @@ export function convertMarkdownToRichText(text: string, theme: Theme = {}): Rich for (const rule of rules) { const match = rule.regex.exec(input); - if (match && (closestMatch === null || match.index < closestMatch.index)) { - closestMatch = match; - activeRule = rule; + if (match) { + const isCloser = closestMatch === null || match.index < closestMatch.index; + + if (isCloser) { + closestMatch = match; + activeRule = rule; + } } } diff --git a/src/html/encodeHtml.ts b/src/html/encodeHtml.ts index 2cd8dfad..3f8575da 100755 --- a/src/html/encodeHtml.ts +++ b/src/html/encodeHtml.ts @@ -23,10 +23,14 @@ export function encodeHtml(value: string): string { function (full, char, next) { if (char !== "&" || next !== "#") { if (/[\u00A0-\u9999<>&]/.test(next)) { - next = `&#${next.charCodeAt(0)};`; + const nextCode = next.charCodeAt(0); + + next = `&#${nextCode};`; } - return `&#${char.charCodeAt(0)};${next}`; + const charCode = char.charCodeAt(0); + + return `&#${charCode};${next}`; } return full; diff --git a/src/json/parseJson.ts b/src/json/parseJson.ts index eb204a73..7811add4 100644 --- a/src/json/parseJson.ts +++ b/src/json/parseJson.ts @@ -74,7 +74,7 @@ export function parseJson(value: string): object { token === "true" || token === "false" || token === "null" || - /^-?\d+(\.\d+)?([eE][+-]?\d+)?$/.test(token) || + /^-?\d+(?:\.\d+|)(?:[eE][+-]?\d+|)$/.test(token) || quotedString.test(token); const tokens = []; @@ -111,21 +111,19 @@ export function parseJson(value: string): object { } if (char === '"' || char === "'") { - if (isString) { - if (char === quoteType) { - isString = false; - currentToken += '"'; - tokens.push(currentToken); - currentToken = ""; - } else { - // A double quote inside a single-quoted string has to be escaped - // once the string is re-quoted with double quotes. - currentToken += char === '"' ? '\\"' : char; - } - } else { + if (!isString) { isString = true; quoteType = char; currentToken += '"'; + } else if (char === quoteType) { + isString = false; + currentToken += '"'; + tokens.push(currentToken); + currentToken = ""; + } else { + // A double quote inside a single-quoted string has to be escaped + // once the string is re-quoted with double quotes. + currentToken += char === '"' ? '\\"' : char; } } else if (isString) { currentToken += char; @@ -157,36 +155,36 @@ export function parseJson(value: string): object { let expectingKey = false; for (let i = 0; i < tokens.length; i++) { - const token = tokens[i]; - - if (token === "{" || token === "[") { - correctedTokens.push(token); - expectingKey = token === "{"; - expectingValue = token === "["; - } else if (token === "}" || token === "]") { - correctedTokens.push(token); + const lexeme = tokens[i]; + + if (lexeme === "{" || lexeme === "[") { + correctedTokens.push(lexeme); + expectingKey = lexeme === "{"; + expectingValue = lexeme === "["; + } else if (lexeme === "}" || lexeme === "]") { + correctedTokens.push(lexeme); expectingValue = false; expectingKey = false; - } else if (token === ":") { - correctedTokens.push(token); + } else if (lexeme === ":") { + correctedTokens.push(lexeme); expectingValue = true; expectingKey = false; - } else if (token === ",") { - correctedTokens.push(token); + } else if (lexeme === ",") { + correctedTokens.push(lexeme); expectingKey = correctedTokens[correctedTokens.length - 2] === "}"; expectingValue = !expectingKey; - } else if (expectingKey && isValidKey(token)) { - correctedTokens.push(toKey(token)); + } else if (expectingKey && isValidKey(lexeme)) { + correctedTokens.push(toKey(lexeme)); expectingKey = false; - } else if (expectingValue && isValidValue(token)) { - correctedTokens.push(token); + } else if (expectingValue && isValidValue(lexeme)) { + correctedTokens.push(lexeme); expectingValue = false; - } else if (isValidKey(token)) { - correctedTokens.push(toKey(token)); - } else if (isValidValue(token)) { - correctedTokens.push(token); + } else if (isValidKey(lexeme)) { + correctedTokens.push(toKey(lexeme)); + } else if (isValidValue(lexeme)) { + correctedTokens.push(lexeme); } else { - throw new Error(`Invalid token: ${token}`); + throw new Error(`Invalid token: ${lexeme}`); } } diff --git a/src/json/stringifyJson.ts b/src/json/stringifyJson.ts index 345586b4..3261bd0f 100644 --- a/src/json/stringifyJson.ts +++ b/src/json/stringifyJson.ts @@ -24,7 +24,9 @@ export function stringifyJson(value: unknown): string { } if (Array.isArray(value)) { - return `[${value.map((element) => stringifyJson(element)).join(",")}]`; + const elements = value.map((element) => stringifyJson(element)).join(","); + + return `[${elements}]`; } const keys = Object.keys(value).sort(); @@ -37,5 +39,7 @@ export function stringifyJson(value: unknown): string { return `${stringifiedKey}:${stringifiedValue}`; }); - return `{${pairs.join(",")}}`; + const members = pairs.join(","); + + return `{${members}}`; } diff --git a/src/lang/base/index.ts b/src/lang/base/index.ts index 8efa1c1d..0cb4ace6 100644 --- a/src/lang/base/index.ts +++ b/src/lang/base/index.ts @@ -102,6 +102,7 @@ export * from "./requireRegExp"; export * from "./requireScalar"; export * from "./requireString"; + export * from "./requireSymbol"; export * from "./requireUndefined"; @@ -125,6 +126,7 @@ export * from "./requireNonNil"; export * from "./requireNonNull"; export * from "./requireState"; + export * from "./requireNonNumber"; export * from "./requireNonNumberLike"; diff --git a/src/lang/string/index.ts b/src/lang/string/index.ts index c8bf04ae..8da7865c 100644 --- a/src/lang/string/index.ts +++ b/src/lang/string/index.ts @@ -24,6 +24,7 @@ export * from "./requireNonEmptyString"; export * from "./nonEmptyString"; export * from "./requireValidEmail"; + export * from "./requireValidLocale"; export * from "./requireValidSlug"; diff --git a/src/lang/string/isEmail.ts b/src/lang/string/isEmail.ts index c0a39b0e..39ca7e6b 100644 --- a/src/lang/string/isEmail.ts +++ b/src/lang/string/isEmail.ts @@ -37,7 +37,7 @@ export function isEmail(email: unknown): email is string { return false; } - const USERNAME_PATTERN = /^[a-zA-Z0-9](?:[a-zA-Z0-9._-]*[a-zA-Z0-9])?$/; + const USERNAME_PATTERN = /^(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$/; const plusIndex = usernamePart.indexOf("+"); diff --git a/test/appsscript/admin/nonAdmin.test.ts b/test/appsscript/admin/nonAdmin.test.ts index 2e95ac7e..012086e7 100644 --- a/test/appsscript/admin/nonAdmin.test.ts +++ b/test/appsscript/admin/nonAdmin.test.ts @@ -3,7 +3,9 @@ import { afterEach, describe, expect, it, vi } from "vitest"; type Mutable = Record; -/** Installs stand-ins for the Apps Script globals `isAdmin` reaches for. */ +/** + * Installs stand-ins for the Apps Script globals `isAdmin` reaches for. + */ function mockDirectory(isAdminFlag: boolean | undefined, email = "user@example.com"): void { (globalThis as Mutable).Session = { getActiveUser: () => ({ getEmail: () => email }) diff --git a/test/appsscript/admin/requireAdmin.test.ts b/test/appsscript/admin/requireAdmin.test.ts index 17df70e5..cd262ffd 100644 --- a/test/appsscript/admin/requireAdmin.test.ts +++ b/test/appsscript/admin/requireAdmin.test.ts @@ -4,7 +4,9 @@ import { afterEach, describe, expect, it, vi } from "vitest"; type Mutable = Record; -/** Installs stand-ins for the Apps Script globals `isAdmin` reaches for. */ +/** + * Installs stand-ins for the Apps Script globals `isAdmin` reaches for. + */ function mockDirectory(isAdminFlag: boolean | undefined, email = "user@example.com"): void { (globalThis as Mutable).Session = { getActiveUser: () => ({ getEmail: () => email }) diff --git a/test/appsscript/sheet/getSchema.test.ts b/test/appsscript/sheet/getSchema.test.ts index d0d166e8..28947ec2 100644 --- a/test/appsscript/sheet/getSchema.test.ts +++ b/test/appsscript/sheet/getSchema.test.ts @@ -64,6 +64,7 @@ describe("getSchema", () => { it("should prefer the current key over the legacy key", () => { const legacy = { version: 1, headerRow: 1, columns: [{ name: "Legacy" }] }; + const current = { version: 1, headerRow: 1, columns: [{ name: "Current" }] }; const sheet = sheetMock( diff --git a/test/appsscript/sheet/isValidSpreadsheetId.test.ts b/test/appsscript/sheet/isValidSpreadsheetId.test.ts index 97a28447..04cb70e0 100644 --- a/test/appsscript/sheet/isValidSpreadsheetId.test.ts +++ b/test/appsscript/sheet/isValidSpreadsheetId.test.ts @@ -1,7 +1,9 @@ import { isValidSpreadsheetId } from "@/appsscript"; import { describe, expect, it } from "vitest"; -/** 44 characters, the usual shape of a Drive file id. */ +/** + * 44 characters, the usual shape of a Drive file id. + */ const validId = "1AbCdEfGhIjKlMnOpQrStUvWxYz0123456789AbCdEfG"; describe("isValidSpreadsheetId", () => { diff --git a/test/appsscript/sheet/nonGridRangeContainedIn.test.ts b/test/appsscript/sheet/nonGridRangeContainedIn.test.ts index d2f93e78..dcbae320 100644 --- a/test/appsscript/sheet/nonGridRangeContainedIn.test.ts +++ b/test/appsscript/sheet/nonGridRangeContainedIn.test.ts @@ -2,6 +2,7 @@ import { nonGridRangeContainedIn } from "@/appsscript"; import { describe, expect, it } from "vitest"; const outer = { startRowIndex: 0, endRowIndex: 10, startColumnIndex: 0, endColumnIndex: 5 }; + const inner = { startRowIndex: 2, endRowIndex: 4, startColumnIndex: 1, endColumnIndex: 3 }; describe("nonGridRangeContainedIn", () => { diff --git a/test/appsscript/sheet/nonRichTextValue.test.ts b/test/appsscript/sheet/nonRichTextValue.test.ts index 826e0230..06aa2b7a 100644 --- a/test/appsscript/sheet/nonRichTextValue.test.ts +++ b/test/appsscript/sheet/nonRichTextValue.test.ts @@ -1,7 +1,9 @@ import { nonRichTextValue } from "@/appsscript"; import { describe, expect, it } from "vitest"; -/** Apps Script service objects report their class name from `toString()`. */ +/** + * Apps Script service objects report their class name from `toString()`. + */ const richTextMock = { toString: (): string => "RichTextValue" }; describe("nonRichTextValue", () => { diff --git a/test/appsscript/sheet/nonSpreadsheet.test.ts b/test/appsscript/sheet/nonSpreadsheet.test.ts index dce9ff92..5e24047f 100644 --- a/test/appsscript/sheet/nonSpreadsheet.test.ts +++ b/test/appsscript/sheet/nonSpreadsheet.test.ts @@ -1,8 +1,11 @@ import { nonSpreadsheet } from "@/appsscript"; import { describe, expect, it } from "vitest"; -/** Apps Script service objects report their class name from `toString()`. */ +/** + * Apps Script service objects report their class name from `toString()`. + */ const spreadsheetMock = { toString: (): string => "Spreadsheet" }; + const sheetMock = { toString: (): string => "Sheet" }; describe("nonSpreadsheet", () => { diff --git a/test/appsscript/sheet/nonTextStyle.test.ts b/test/appsscript/sheet/nonTextStyle.test.ts index 16852920..676fe337 100644 --- a/test/appsscript/sheet/nonTextStyle.test.ts +++ b/test/appsscript/sheet/nonTextStyle.test.ts @@ -1,7 +1,9 @@ import { nonTextStyle } from "@/appsscript"; import { describe, expect, it } from "vitest"; -/** Apps Script service objects report their class name from `toString()`. */ +/** + * Apps Script service objects report their class name from `toString()`. + */ const textStyleMock = { toString: (): string => "TextStyle" }; describe("nonTextStyle", () => { diff --git a/test/appsscript/sheet/nonValidSpreadsheetId.test.ts b/test/appsscript/sheet/nonValidSpreadsheetId.test.ts index e4298b73..7045c251 100644 --- a/test/appsscript/sheet/nonValidSpreadsheetId.test.ts +++ b/test/appsscript/sheet/nonValidSpreadsheetId.test.ts @@ -1,7 +1,9 @@ import { nonValidSpreadsheetId } from "@/appsscript"; import { describe, expect, it } from "vitest"; -/** 44 characters, the usual shape of a Drive file id. */ +/** + * 44 characters, the usual shape of a Drive file id. + */ const validId = "1AbCdEfGhIjKlMnOpQrStUvWxYz0123456789AbCdEfG"; describe("nonValidSpreadsheetId", () => { diff --git a/test/appsscript/sheet/prependColumn.test.ts b/test/appsscript/sheet/prependColumn.test.ts index 769ed455..a367b810 100644 --- a/test/appsscript/sheet/prependColumn.test.ts +++ b/test/appsscript/sheet/prependColumn.test.ts @@ -53,8 +53,7 @@ function rangeMock( sheet: GoogleAppsScript.Spreadsheet.Sheet, row: number, column: number, - numRows = 10, - numColumns = 4 + { numRows = 10, numColumns = 4 }: { numRows?: number; numColumns?: number } = {} ): GoogleAppsScript.Spreadsheet.Range { return { toString: () => "Range", diff --git a/test/appsscript/sheet/prependColumns.test.ts b/test/appsscript/sheet/prependColumns.test.ts index d6b7bd98..ced26a48 100644 --- a/test/appsscript/sheet/prependColumns.test.ts +++ b/test/appsscript/sheet/prependColumns.test.ts @@ -63,8 +63,7 @@ function rangeMock( sheet: GoogleAppsScript.Spreadsheet.Sheet, row: number, column: number, - numRows = 10, - numColumns = 4 + { numRows = 10, numColumns = 4 }: { numRows?: number; numColumns?: number } = {} ): GoogleAppsScript.Spreadsheet.Range { return { toString: () => "Range", diff --git a/test/appsscript/sheet/prependRow.test.ts b/test/appsscript/sheet/prependRow.test.ts index 9d904482..f4800bb7 100644 --- a/test/appsscript/sheet/prependRow.test.ts +++ b/test/appsscript/sheet/prependRow.test.ts @@ -56,8 +56,7 @@ function rangeMock( sheet: GoogleAppsScript.Spreadsheet.Sheet, row: number, column: number, - numRows = 10, - numColumns = 4 + { numRows = 10, numColumns = 4 }: { numRows?: number; numColumns?: number } = {} ): GoogleAppsScript.Spreadsheet.Range { return { toString: () => "Range", diff --git a/test/appsscript/sheet/prependRows.test.ts b/test/appsscript/sheet/prependRows.test.ts index bf93cbc2..a7e59c21 100644 --- a/test/appsscript/sheet/prependRows.test.ts +++ b/test/appsscript/sheet/prependRows.test.ts @@ -56,8 +56,7 @@ function rangeMock( sheet: GoogleAppsScript.Spreadsheet.Sheet, row: number, column: number, - numRows = 10, - numColumns = 4 + { numRows = 10, numColumns = 4 }: { numRows?: number; numColumns?: number } = {} ): GoogleAppsScript.Spreadsheet.Range { return { toString: () => "Range", diff --git a/test/appsscript/sheet/requireGridRangeContainedIn.test.ts b/test/appsscript/sheet/requireGridRangeContainedIn.test.ts index 8aa7b9a2..b04ebc45 100644 --- a/test/appsscript/sheet/requireGridRangeContainedIn.test.ts +++ b/test/appsscript/sheet/requireGridRangeContainedIn.test.ts @@ -3,6 +3,7 @@ import { InvalidGridRangeException } from "@/exception"; import { describe, expect, it } from "vitest"; const outer = { startRowIndex: 0, endRowIndex: 10, startColumnIndex: 0, endColumnIndex: 5 }; + const inner = { startRowIndex: 2, endRowIndex: 4, startColumnIndex: 1, endColumnIndex: 3 }; describe("requireGridRangeContainedIn", () => { diff --git a/test/appsscript/sheet/requireRichTextValue.test.ts b/test/appsscript/sheet/requireRichTextValue.test.ts index 74f8a569..1a9915b2 100644 --- a/test/appsscript/sheet/requireRichTextValue.test.ts +++ b/test/appsscript/sheet/requireRichTextValue.test.ts @@ -2,7 +2,9 @@ import { requireRichTextValue } from "@/appsscript"; import { IllegalArgumentException } from "@/exception"; import { describe, expect, it } from "vitest"; -/** Apps Script service objects report their class name from `toString()`. */ +/** + * Apps Script service objects report their class name from `toString()`. + */ const richTextMock = { toString: (): string => "RichTextValue" }; describe("requireRichTextValue", () => { diff --git a/test/appsscript/sheet/requireTextStyle.test.ts b/test/appsscript/sheet/requireTextStyle.test.ts index 008e3e34..dca5bedb 100644 --- a/test/appsscript/sheet/requireTextStyle.test.ts +++ b/test/appsscript/sheet/requireTextStyle.test.ts @@ -2,7 +2,9 @@ import { requireTextStyle } from "@/appsscript"; import { IllegalArgumentException } from "@/exception"; import { describe, expect, it } from "vitest"; -/** Apps Script service objects report their class name from `toString()`. */ +/** + * Apps Script service objects report their class name from `toString()`. + */ const textStyleMock = { toString: (): string => "TextStyle" }; describe("requireTextStyle", () => { diff --git a/test/appsscript/sheet/requireValidSpreadsheetId.test.ts b/test/appsscript/sheet/requireValidSpreadsheetId.test.ts index a51a7436..588bb4c7 100644 --- a/test/appsscript/sheet/requireValidSpreadsheetId.test.ts +++ b/test/appsscript/sheet/requireValidSpreadsheetId.test.ts @@ -2,7 +2,9 @@ import { requireValidSpreadsheetId } from "@/appsscript"; import { IllegalArgumentException } from "@/exception"; import { describe, expect, it } from "vitest"; -/** 44 characters, the usual shape of a Drive file id. */ +/** + * 44 characters, the usual shape of a Drive file id. + */ const validId = "1AbCdEfGhIjKlMnOpQrStUvWxYz0123456789AbCdEfG"; describe("requireValidSpreadsheetId", () => { diff --git a/test/appsscript/slide/convertRichTextToMarkdown.test.ts b/test/appsscript/slide/convertRichTextToMarkdown.test.ts index 4d51eb08..30ff963b 100644 --- a/test/appsscript/slide/convertRichTextToMarkdown.test.ts +++ b/test/appsscript/slide/convertRichTextToMarkdown.test.ts @@ -110,7 +110,9 @@ describe("convertRichTextToMarkdown", () => { ]; for (const text of cases) { - it(`should return the original text for ${JSON.stringify(text)}`, () => { + const quoted = JSON.stringify(text); + + it(`should return the original text for ${quoted}`, () => { expect(convertRichTextToMarkdown(convertMarkdownToRichText(text))).toBe(text); }); } diff --git a/test/appsscript/slide/nonPresentation.test.ts b/test/appsscript/slide/nonPresentation.test.ts index 52c32aa2..64bbc006 100644 --- a/test/appsscript/slide/nonPresentation.test.ts +++ b/test/appsscript/slide/nonPresentation.test.ts @@ -1,13 +1,17 @@ import { nonPresentation } from "@/appsscript"; import { describe, expect, it } from "vitest"; -/** A stand-in carrying the two methods `isPresentation` probes for. */ +/** + * A stand-in carrying the two methods `isPresentation` probes for. + */ const presentationMock = { getId: (): string => "1AbCdEfGhIjKlMnOpQrStUvWxYz", getSlides: (): unknown[] => [] }; -/** A `Slide` carries a different pair of methods. */ +/** + * A `Slide` carries a different pair of methods. + */ const slideMock = { getObjectId: (): string => "p1", getPageElementById: (): unknown => undefined diff --git a/test/appsscript/slide/nonSlide.test.ts b/test/appsscript/slide/nonSlide.test.ts index 3ce399a2..c0ff9849 100644 --- a/test/appsscript/slide/nonSlide.test.ts +++ b/test/appsscript/slide/nonSlide.test.ts @@ -1,13 +1,17 @@ import { nonSlide } from "@/appsscript"; import { describe, expect, it } from "vitest"; -/** A stand-in carrying the two methods `isSlide` probes for. */ +/** + * A stand-in carrying the two methods `isSlide` probes for. + */ const slideMock = { getObjectId: (): string => "p1", getPageElementById: (): unknown => undefined }; -/** A `Presentation` carries a different pair of methods. */ +/** + * A `Presentation` carries a different pair of methods. + */ const presentationMock = { getId: (): string => "abc", getSlides: (): unknown[] => [] diff --git a/test/appsscript/slide/nonValidPresentationId.test.ts b/test/appsscript/slide/nonValidPresentationId.test.ts index 533b2e24..7d3f9b5d 100644 --- a/test/appsscript/slide/nonValidPresentationId.test.ts +++ b/test/appsscript/slide/nonValidPresentationId.test.ts @@ -1,7 +1,9 @@ import { nonValidPresentationId } from "@/appsscript"; import { describe, expect, it } from "vitest"; -/** 44 characters, the usual shape of a Drive file id. */ +/** + * 44 characters, the usual shape of a Drive file id. + */ const validId = "1AbCdEfGhIjKlMnOpQrStUvWxYz0123456789AbCdEfG"; describe("nonValidPresentationId", () => { diff --git a/test/appsscript/slide/requirePresentation.test.ts b/test/appsscript/slide/requirePresentation.test.ts index 1e12942c..08394677 100644 --- a/test/appsscript/slide/requirePresentation.test.ts +++ b/test/appsscript/slide/requirePresentation.test.ts @@ -2,7 +2,9 @@ import { requirePresentation } from "@/appsscript"; import { InvalidPresentationException } from "@/exception"; import { describe, expect, it } from "vitest"; -/** A stand-in carrying the two methods `isPresentation` probes for. */ +/** + * A stand-in carrying the two methods `isPresentation` probes for. + */ const presentationMock = { getId: (): string => "1AbCdEfGhIjKlMnOpQrStUvWxYz", getSlides: (): unknown[] => [] diff --git a/test/appsscript/slide/requireValidPresentationId.test.ts b/test/appsscript/slide/requireValidPresentationId.test.ts index 408ca607..9ed97678 100644 --- a/test/appsscript/slide/requireValidPresentationId.test.ts +++ b/test/appsscript/slide/requireValidPresentationId.test.ts @@ -2,7 +2,9 @@ import { requireValidPresentationId } from "@/appsscript"; import { IllegalArgumentException } from "@/exception"; import { describe, expect, it } from "vitest"; -/** 44 characters, the usual shape of a Drive file id. */ +/** + * 44 characters, the usual shape of a Drive file id. + */ const validId = "1AbCdEfGhIjKlMnOpQrStUvWxYz0123456789AbCdEfG"; describe("requireValidPresentationId", () => { diff --git a/test/appsscript/ui/nonHtmlOutput.test.ts b/test/appsscript/ui/nonHtmlOutput.test.ts index 45a77639..e7cd9a95 100644 --- a/test/appsscript/ui/nonHtmlOutput.test.ts +++ b/test/appsscript/ui/nonHtmlOutput.test.ts @@ -1,7 +1,9 @@ import { nonHtmlOutput } from "@/appsscript"; import { describe, expect, it } from "vitest"; -/** A stand-in carrying the three methods `isHtmlOutput` probes for. */ +/** + * A stand-in carrying the three methods `isHtmlOutput` probes for. + */ const htmlOutputMock = { getContent: (): string => "", setTitle: (): unknown => undefined, @@ -21,7 +23,9 @@ describe("nonHtmlOutput", () => { describe("Incorrect input data", () => { it("should return true when any probed method is missing", () => { - const { setTitle: _omitted, ...withoutSetTitle } = htmlOutputMock; + const withoutSetTitle: Partial = { ...htmlOutputMock }; + + delete withoutSetTitle.setTitle; expect(nonHtmlOutput(withoutSetTitle)).toBe(true); expect(nonHtmlOutput({ getContent: (): string => "" })).toBe(true); diff --git a/test/appsscript/ui/nonTextOutput.test.ts b/test/appsscript/ui/nonTextOutput.test.ts index 92420515..c9928fbb 100644 --- a/test/appsscript/ui/nonTextOutput.test.ts +++ b/test/appsscript/ui/nonTextOutput.test.ts @@ -1,7 +1,9 @@ import { nonTextOutput } from "@/appsscript"; import { describe, expect, it } from "vitest"; -/** A stand-in carrying the two methods `isTextOutput` probes for. */ +/** + * A stand-in carrying the two methods `isTextOutput` probes for. + */ const textOutputMock = { getMimeType: (): unknown => undefined, getContent: (): string => "" diff --git a/test/appsscript/ui/nonUi.test.ts b/test/appsscript/ui/nonUi.test.ts index 80603fa2..7d562f7f 100644 --- a/test/appsscript/ui/nonUi.test.ts +++ b/test/appsscript/ui/nonUi.test.ts @@ -1,7 +1,9 @@ import { nonUi } from "@/appsscript"; import { describe, expect, it } from "vitest"; -/** `isUi` identifies its target by the string an Apps Script `Ui` reports. */ +/** + * `isUi` identifies its target by the string an Apps Script `Ui` reports. + */ const uiMock = { toString: (): string => "Ui" }; diff --git a/test/appsscript/ui/requireHtmlOutput.test.ts b/test/appsscript/ui/requireHtmlOutput.test.ts index be4c3cd5..8ba063ea 100644 --- a/test/appsscript/ui/requireHtmlOutput.test.ts +++ b/test/appsscript/ui/requireHtmlOutput.test.ts @@ -2,7 +2,9 @@ import { requireHtmlOutput } from "@/appsscript"; import { IllegalArgumentException } from "@/exception"; import { describe, expect, it } from "vitest"; -/** A stand-in carrying the three methods `isHtmlOutput` probes for. */ +/** + * A stand-in carrying the three methods `isHtmlOutput` probes for. + */ const htmlOutputMock = { getContent: (): string => "", setTitle: (): unknown => undefined, diff --git a/test/appsscript/ui/requireTextOutput.test.ts b/test/appsscript/ui/requireTextOutput.test.ts index ef157e9f..ba5ef135 100644 --- a/test/appsscript/ui/requireTextOutput.test.ts +++ b/test/appsscript/ui/requireTextOutput.test.ts @@ -2,7 +2,9 @@ import { requireTextOutput } from "@/appsscript"; import { IllegalArgumentException } from "@/exception"; import { describe, expect, it } from "vitest"; -/** A stand-in carrying the two methods `isTextOutput` probes for. */ +/** + * A stand-in carrying the two methods `isTextOutput` probes for. + */ const textOutputMock = { getMimeType: (): unknown => undefined, getContent: (): string => "" diff --git a/test/appsscript/ui/requireUi.test.ts b/test/appsscript/ui/requireUi.test.ts index a0572f3c..962bfb02 100644 --- a/test/appsscript/ui/requireUi.test.ts +++ b/test/appsscript/ui/requireUi.test.ts @@ -2,7 +2,9 @@ import { requireUi } from "@/appsscript"; import { IllegalArgumentException } from "@/exception"; import { describe, expect, it } from "vitest"; -/** `isUi` identifies its target by the string an Apps Script `Ui` reports. */ +/** + * `isUi` identifies its target by the string an Apps Script `Ui` reports. + */ const uiMock = { toString: (): string => "Ui" }; diff --git a/test/lang/base/isScalar.test.ts b/test/lang/base/isScalar.test.ts index fbf7e489..7d8be0a0 100644 --- a/test/lang/base/isScalar.test.ts +++ b/test/lang/base/isScalar.test.ts @@ -45,9 +45,7 @@ describe("isScalar", () => { }); it("should return false for boxed primitives", () => { - // eslint-disable-next-line no-new-wrappers expect(isScalar(new String("abc"))).toBe(false); - // eslint-disable-next-line no-new-wrappers expect(isScalar(new Number(1))).toBe(false); }); }); diff --git a/test/lang/base/requireFunctionLike.test.ts b/test/lang/base/requireFunctionLike.test.ts index e0b514fe..547dc061 100644 --- a/test/lang/base/requireFunctionLike.test.ts +++ b/test/lang/base/requireFunctionLike.test.ts @@ -5,7 +5,7 @@ import { describe, expect, it } from "vitest"; describe("requireFunctionLike", () => { describe("Correct input data", () => { it("should return the same function reference", () => { - const input = () => 1; + const input = (): number => 1; expect(requireFunctionLike(input)).toBe(input); }); diff --git a/test/lang/base/requireNonBoolean.test.ts b/test/lang/base/requireNonBoolean.test.ts index bea93d36..8cd4134b 100644 --- a/test/lang/base/requireNonBoolean.test.ts +++ b/test/lang/base/requireNonBoolean.test.ts @@ -17,7 +17,6 @@ describe("requireNonBoolean", () => { }); it("should accept a boxed Boolean object", () => { - // eslint-disable-next-line no-new-wrappers const boxed = new Boolean(true); expect(requireNonBoolean(boxed)).toBe(boxed); diff --git a/test/lang/base/requireNonObject.test.ts b/test/lang/base/requireNonObject.test.ts index 7f54ad44..d5766274 100644 --- a/test/lang/base/requireNonObject.test.ts +++ b/test/lang/base/requireNonObject.test.ts @@ -17,7 +17,7 @@ describe("requireNonObject", () => { }); it("should accept functions", () => { - const fn = () => 1; + const fn = (): number => 1; expect(requireNonObject(fn)).toBe(fn); expect(requireNonObject(class Sample {})).toBeTypeOf("function"); diff --git a/test/lang/base/requireNonScalar.test.ts b/test/lang/base/requireNonScalar.test.ts index 63e1df09..f55b4da1 100644 --- a/test/lang/base/requireNonScalar.test.ts +++ b/test/lang/base/requireNonScalar.test.ts @@ -22,7 +22,7 @@ describe("requireNonScalar", () => { }); it("should accept functions", () => { - const fn = () => 1; + const fn = (): number => 1; expect(requireNonScalar(fn)).toBe(fn); }); diff --git a/test/lang/base/requireNonString.test.ts b/test/lang/base/requireNonString.test.ts index bb96e635..94fff3ab 100644 --- a/test/lang/base/requireNonString.test.ts +++ b/test/lang/base/requireNonString.test.ts @@ -22,7 +22,6 @@ describe("requireNonString", () => { }); it("should accept a boxed String object", () => { - // eslint-disable-next-line no-new-wrappers const boxed = new String("abc"); expect(requireNonString(boxed)).toBe(boxed); From d77bdcc32e97944bf4628a6e991ce01da3e41c4b Mon Sep 17 00:00:00 2001 From: Maksym Stoianov Date: Wed, 18 Nov 2026 11:19:22 +0100 Subject: [PATCH 2/2] test: give the git merge-driver tests a 30 s timeout They run real git merges in a temporary repository and time out at the 5 s default when the machine is busy, failing pre-push and CI at random. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Maksym Stoianov --- test/scripts/merge-module-index.test.ts | 6 +++++- test/scripts/merge-reference-tables.test.ts | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/test/scripts/merge-module-index.test.ts b/test/scripts/merge-module-index.test.ts index b69a7112..ab286145 100644 --- a/test/scripts/merge-module-index.test.ts +++ b/test/scripts/merge-module-index.test.ts @@ -63,7 +63,11 @@ afterEach(() => { } }); -describe("merge-module-index", () => { +/** + * Each case runs real git merges in a temporary repository; under parallel load they can take + * longer than Vitest's 5 s default. + */ +describe("merge-module-index", { timeout: 30_000 }, () => { describe("Placeholders that carry a signature", () => { it("should merge two sides each flipping a different one", () => { const { status, text } = merge( diff --git a/test/scripts/merge-reference-tables.test.ts b/test/scripts/merge-reference-tables.test.ts index 3d9149af..2eedf6ea 100644 --- a/test/scripts/merge-reference-tables.test.ts +++ b/test/scripts/merge-reference-tables.test.ts @@ -111,7 +111,11 @@ const DINGO = row("dingo"); const ZEBRA = row("zebra"); -describe("merge-reference-tables", () => { +/** + * Each case runs real git merges in a temporary repository; under parallel load they can take + * longer than Vitest's 5 s default. + */ +describe("merge-reference-tables", { timeout: 30_000 }, () => { describe("A table one side adds", () => { const base = section("Alpha", [AARDVARK]) + "\n" + section("Beta");