chore: remove the deprecated functional/prefer-readonly-type rule (#3949)

This commit is contained in:
Dolan
2026-11-28 16:47:12 +08:00
committed by GitHub
parent 7871008a0b
commit d15c565e4a
59 changed files with 10 additions and 214 deletions
+3 -37
View File
@@ -1,5 +1,5 @@
import eslint from "@eslint/js";
import type { ESLint, Linter, Rule } from "eslint";
import type { Linter } from "eslint";
import { createTypeScriptImportResolver } from "eslint-import-resolver-typescript";
import { createNodeResolver, importX } from "eslint-plugin-import-x";
import unicorn from "eslint-plugin-unicorn";
@@ -9,39 +9,6 @@ import functional from "eslint-plugin-functional";
import globals from "globals";
import tsEslint from "typescript-eslint";
/**
* A rule that reports what it always has, but offers its fixes as suggestions, which an editor shows, rather than as
* fixes, which `eslint --fix` applies.
*/
const withFixesAsSuggestions = (rule: Rule.RuleModule, description: string): Rule.RuleModule => ({
...rule,
meta: { ...rule.meta, fixable: undefined, hasSuggestions: true },
create: (context) =>
rule.create(
// The context is frozen, so the rule is given one that reports through it
Object.create(context, {
report: {
value: ({ fix, ...descriptor }: Rule.ReportDescriptor): void =>
context.report(fix ? { ...descriptor, suggest: [{ desc: description, fix }] } : descriptor),
},
}) as Rule.RuleContext,
),
});
// functional/prefer-readonly-type's fix makes an array, map, set or field readonly without looking at whether the code
// changes it. Applied by `eslint --fix`, it breaks every push to an array the code builds, and functional/immutable-data
// then has nothing to report there, so `--fix` also removes the comments that allowed the push
const functionalWithSafeFixes: ESLint.Plugin = {
...functional,
rules: {
...functional.rules,
"prefer-readonly-type": withFixesAsSuggestions(
functional.rules["prefer-readonly-type"] as unknown as Rule.RuleModule,
"Make it readonly, if nothing changes it",
),
},
};
const config: Linter.Config<Linter.RulesRecord>[] = [
{
ignores: [
@@ -67,7 +34,7 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
unicorn,
jsdoc,
"prefer-arrow": preferArrow,
functional: functionalWithSafeFixes,
functional,
},
languageOptions: {
@@ -381,7 +348,6 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
"functional/prefer-property-signatures": "error",
"functional/no-mixed-types": "error",
"functional/prefer-readonly-type": "error",
"@typescript-eslint/no-unused-vars": [
"error",
@@ -397,7 +363,7 @@ const config: Linter.Config<Linter.RulesRecord>[] = [
unicorn,
jsdoc,
"prefer-arrow": preferArrow,
functional: functionalWithSafeFixes,
functional,
},
languageOptions: {
globals: {
@@ -54,7 +54,6 @@ const sameFormat = (a: FormattedRun, b: FormattedRun): boolean =>
* joined, and empty ones dropped.
*/
export const readAsWord = (text: TextLike): FormattedText => {
// eslint-disable-next-line functional/prefer-readonly-type
const runs: FormattedRun[] = [];
// Whether the text so far ends with a space, or is at the start of the paragraph or of a line
let atSpace = true;
@@ -91,7 +91,6 @@ const tokensOf = (nodes: readonly HtmlNode[], copied = false): readonly Token[]
export const readHtml = (paragraphs: readonly (readonly HtmlNode[])[]): readonly FormattedText[] => {
const marks = { b: 0, i: 0 };
return paragraphs.map((paragraph) => {
// eslint-disable-next-line functional/prefer-readonly-type
const runs: FormattedRun[] = [];
let lastNode: "text" | "start" | "end" | undefined;
let boundary = false;
+2 -4
View File
@@ -591,7 +591,6 @@ describe("ChartDataPatch", () => {
it("should keep its own copy of the data, so changing the options afterwards changes nothing", async () => {
const categories = ["A", "B"];
const date = new Date("2025-01-01");
// eslint-disable-next-line functional/prefer-readonly-type
const values: (number | null)[] = [1, 2];
const data = { categories, series: [{ name: "S", values }] };
const chartPatch = new ChartDataPatch(data);
@@ -2425,12 +2424,11 @@ describe("ChartDataPatch with the newer chart types and options", () => {
});
it("should keep the groups it was made with, whatever happens to them after", async () => {
// eslint-disable-next-line functional/prefer-readonly-type -- Changed after the patch is made
const categories = [{ name: "2025", categories: ["Q1", "Q2"] as string[] }];
const chartPatch = new ChartDataPatch({ categories, series: [{ name: "S", values: [1, 2] }] });
// eslint-disable-next-line functional/immutable-data
categories[0].categories.push("Q3");
// eslint-disable-next-line functional/immutable-data, functional/prefer-readonly-type -- Changed after the patch is made
// eslint-disable-next-line functional/immutable-data -- Changed after the patch is made
(categories[0] as { name: string }).name = "Changed";
const zip = await patch(await templateOf({ chart: TEMPLATES.column }), { chart: chartPatch });
const [chart] = chartsIn(zip);
@@ -2575,7 +2573,7 @@ describe("ChartDataPatch with the newer chart types and options", () => {
const chartPatch = new ChartDataPatch({ ...prices, high, names });
// eslint-disable-next-line functional/immutable-data
high[0] = 99;
// eslint-disable-next-line functional/immutable-data, functional/prefer-readonly-type -- Changed after the patch is made
// eslint-disable-next-line functional/immutable-data -- Changed after the patch is made
(names as { close: string }).close = "Changed";
const zip = await patch(await templateOf({ chart: HIGH_LOW_CLOSE }), { chart: chartPatch });
const [chart] = chartsIn(zip);
-11
View File
@@ -55,17 +55,11 @@ type DirectoryEntry = {
readonly name: string;
readonly type: typeof STORAGE | typeof STREAM | typeof ROOT_STORAGE;
readonly data?: Uint8Array;
// eslint-disable-next-line functional/prefer-readonly-type
left: number;
// eslint-disable-next-line functional/prefer-readonly-type
right: number;
// eslint-disable-next-line functional/prefer-readonly-type
child: number;
// eslint-disable-next-line functional/prefer-readonly-type
color: typeof RED | typeof BLACK;
// eslint-disable-next-line functional/prefer-readonly-type
start: number;
// eslint-disable-next-line functional/prefer-readonly-type
size: number;
};
@@ -88,7 +82,6 @@ const compareNames = (a: string, b: string): number => {
* @returns The id of the tree's root
*/
const linkTree = (entries: readonly DirectoryEntry[], ids: readonly number[]): number => {
// eslint-disable-next-line functional/prefer-readonly-type
const depths: number[] = [];
const link = (from: number, to: number, depth: number): number => {
if (from > to) {
@@ -124,7 +117,6 @@ const createDirectory = (children: readonly CompoundFileEntry[]): readonly Direc
}
return { name, type, data, left: NO_STREAM, right: NO_STREAM, child: NO_STREAM, color: BLACK, start: 0, size: 0 };
};
// eslint-disable-next-line functional/prefer-readonly-type
const entries: DirectoryEntry[] = [entry("Root Entry", ROOT_STORAGE)];
const addChildren = (parent: DirectoryEntry, storageChildren: readonly CompoundFileEntry[]): void => {
const sorted = [...storageChildren].sort((a, b) => compareNames(a.name, b.name));
@@ -155,7 +147,6 @@ const createDirectory = (children: readonly CompoundFileEntry[]): readonly Direc
*
* @returns The chain's first sector, or END_OF_CHAIN for none
*/
// eslint-disable-next-line functional/prefer-readonly-type
const addChain = (table: number[], count: number, value?: number): number => {
if (count === 0) {
return END_OF_CHAIN;
@@ -201,7 +192,6 @@ export const createCompoundFile = (children: readonly CompoundFileEntry[], { cla
const largeStreams = streams.filter((entry) => entry.data!.length >= MINI_STREAM_CUTOFF);
// The mini stream, with its own table of mini sectors, the mini FAT
// eslint-disable-next-line functional/prefer-readonly-type
const miniFat: number[] = [];
for (const stream of miniStreams) {
// eslint-disable-next-line functional/immutable-data
@@ -212,7 +202,6 @@ export const createCompoundFile = (children: readonly CompoundFileEntry[], { cla
const miniStreamSize = miniFat.length * MINI_SECTOR_SIZE;
// The sectors: the directory, the mini FAT, the mini stream, the large streams, then the FAT, which counts itself
// eslint-disable-next-line functional/prefer-readonly-type
const fat: number[] = [];
const directoryStart = addChain(fat, Math.ceil(entries.length / (SECTOR_SIZE / DIRECTORY_ENTRY_SIZE)));
const miniFatSectors = Math.ceil(miniFat.length / SECTOR_NUMBERS_PER_SECTOR);
-2
View File
@@ -30,10 +30,8 @@ export const createDrawingNumbering = (): ((xml: string) => string) => {
// The new id of each tag that has one, by where the tag starts
const newIds = new Map<number, number>();
// The new ids of the shapes in each drawing the tags are in, by their old ids
// eslint-disable-next-line functional/prefer-readonly-type
const drawings: Map<number, number>[] = [];
// A connector can come before the shapes it joins, so its ends are numbered once every shape has been
// eslint-disable-next-line functional/prefer-readonly-type
const ends: { readonly offset: number; readonly shapes: ReadonlyMap<number, number>; readonly id: number }[] = [];
for (const { 0: tag, 1: closing, 2: name, index: offset } of xml.matchAll(TAG)) {
@@ -38,9 +38,7 @@ import { CustomProperty, type ICustomPropertyOptions } from "./custom-property";
* ```
*/
export class CustomProperties extends XmlComponent {
// eslint-disable-next-line functional/prefer-readonly-type
private nextId: number;
// eslint-disable-next-line functional/prefer-readonly-type
private readonly properties: CustomProperty[] = [];
public constructor(properties: readonly ICustomPropertyOptions[]) {
-1
View File
@@ -63,7 +63,6 @@ export type IBodyOptions = {
* ```
*/
export class Body extends XmlComponent {
// eslint-disable-next-line functional/prefer-readonly-type
private readonly sections: SectionProperties[] = [];
/**
* Section properties that were moved into a paragraph at the end of their section
@@ -27,7 +27,6 @@ export type ElementTree<E> = {
/** The element's name, such as "w:r", or undefined for text, and for a formatted element's attributes */
readonly nameOf: (element: E) => string | undefined;
/** The element's content, which can be changed in place, or undefined when it has none */
// eslint-disable-next-line functional/prefer-readonly-type
readonly contentOf: (element: E) => E[] | undefined;
readonly attributeOf: (element: E, attribute: string) => unknown;
/** The text directly in the element, such as an instruction's */
@@ -46,12 +45,9 @@ export type ElementTree<E> = {
/** A complex field being read: its beginning, its instruction, and whether its result has been reached */
type OpenField<E> = {
readonly begin: E;
// eslint-disable-next-line functional/prefer-readonly-type
instruction: string;
// eslint-disable-next-line functional/prefer-readonly-type
inResult: boolean;
/** The result it is written with */
// eslint-disable-next-line functional/prefer-readonly-type
result?: string;
};
@@ -102,7 +98,6 @@ const numberFieldOf = (instruction: string): NumberField | undefined => {
const parts = (reference ? reference[3] : field[2]).match(/"[^"]*"|\S+/g) ?? [];
let numberFormat: string | undefined;
let picture: string | undefined;
// eslint-disable-next-line functional/prefer-readonly-type
const capitals: string[] = [];
let relative = false;
let written = true;
@@ -211,9 +206,7 @@ const placeIn = (name: string, within: SequencePlace): SequencePlace =>
*/
const fillFields = <E>(
tree: ElementTree<E>,
// eslint-disable-next-line functional/prefer-readonly-type
elements: E[],
// eslint-disable-next-line functional/prefer-readonly-type
open: OpenField<E>[],
filling: FieldFilling<E>,
within: SequencePlace = "counted",
@@ -178,7 +178,6 @@ export const sequenceNumbering = (context: IContext): SequenceNumbering => {
// The SEQ fields of each identifier counted so far
const counted = new Map<string, readonly Counted[]>();
// The paragraph each heading level, from 1, was last at, and the last paragraph whose heading level isn't clear
// eslint-disable-next-line functional/prefer-readonly-type
const headingsAt: number[] = [];
let unclearAt = -1;
let paragraph = -1;
-1
View File
@@ -12,7 +12,6 @@ export class Endnotes extends XmlComponent {
// The endnotes that reference runs bring with them, by their runs, with the ids they are given
private readonly ownNotes = new Map<object, number>();
// The highest id of the endnotes, so the one after it is free
// eslint-disable-next-line functional/prefer-readonly-type
private highestId = 0;
public constructor() {
-3
View File
@@ -179,13 +179,10 @@ type FileBibliography = {
* ```
*/
export class File {
// eslint-disable-next-line functional/prefer-readonly-type
private currentRelationshipId: number = 1;
private readonly documentWrapper: DocumentWrapper;
// eslint-disable-next-line functional/prefer-readonly-type
private readonly headers: IDocumentHeader[] = [];
// eslint-disable-next-line functional/prefer-readonly-type
private readonly footers: IDocumentFooter[] = [];
private readonly coreProperties: CoreProperties;
private readonly numbering: Numbering;
-1
View File
@@ -64,7 +64,6 @@ export class FootNotes extends XmlComponent {
// The footnotes that reference runs bring with them, by their runs, with the ids they are given
private readonly ownNotes = new Map<object, number>();
// The highest id of the footnotes, so the one after it is free
// eslint-disable-next-line functional/prefer-readonly-type
private highestId = 0;
public constructor() {
-1
View File
@@ -73,7 +73,6 @@ describe("Media", () => {
});
it("should take each image's path from the function it is given, as from a package's parts", () => {
// eslint-disable-next-line functional/prefer-readonly-type
const taken: string[] = [];
const media = new Media((extension) => {
// eslint-disable-next-line functional/immutable-data
-1
View File
@@ -132,7 +132,6 @@ export class PackagePart<Relationship extends PackagePartRelationshipType = Rela
export class PackageParts {
private readonly paths = new Map<PackagePart<PackagePartRelationshipType>, string>();
// The paths under word/ that are taken: the package's own, and those given out by takePath
// eslint-disable-next-line functional/prefer-readonly-type
private readonly taken: Set<string>;
// The folders of the parts whose XML is being written, by the relationships the XML is formatted with
private readonly folders = new WeakMap<Relationships, string>();
-1
View File
@@ -386,7 +386,6 @@ export class ParagraphProperties extends IgnoreIfEmptyXmlComponent {
readonly definition?: NumberingDefinition;
};
/** The paragraph's `w:numPr`, which is written again with its list's id each time the paragraph is written */
// eslint-disable-next-line functional/prefer-readonly-type
private numberProperties?: NumberProperties;
/**
@@ -100,7 +100,6 @@ export const recordTableOfContents = (table: IXmlableObject, fillWith: HeadingEn
* from the counter every bookmark shares, the first time it is needed, so a document packed again is written the same.
*/
export class HeadingBookmarkIds {
// eslint-disable-next-line functional/prefer-readonly-type
private readonly ids: number[] = [];
public get(index: number): number {
@@ -186,7 +185,6 @@ const textOfRunContent = (element: unknown): string => {
/** The text of a paragraph. Of a field, only its result is text, not its instruction */
const textOf = (paragraph: Element): string => {
// For each field that has begun, whether its result has
// eslint-disable-next-line functional/prefer-readonly-type
const fields: boolean[] = [];
const read = (element: unknown): string => {
const name = nameOf(element);
-2
View File
@@ -125,9 +125,7 @@ export const resolveColumnWidths = ({
}
const tableWidth = resolveTableWidth(width, availableWidth);
// eslint-disable-next-line functional/prefer-readonly-type
const widths: (number | undefined)[] = Array.from({ length: columnCount }, () => undefined);
// eslint-disable-next-line functional/prefer-readonly-type
const spanningCells: { readonly start: number; readonly span: number; readonly width: number }[] = [];
for (const row of rows) {
@@ -143,7 +143,6 @@ export type ITableCellPropertiesChangeOptions = ITableCellPropertiesOptionsBase
*/
export class TableCellProperties extends IgnoreIfEmptyXmlComponent {
private readonly hasWidth: boolean;
// eslint-disable-next-line functional/prefer-readonly-type
private hasColumnWidth = false;
public constructor(options: ITableCellPropertiesOptions) {
-1
View File
@@ -113,7 +113,6 @@ export class Table extends FileChild {
* from the table and cell widths (re-resolved against the actual page or parent
* cell every time the table is serialized).
*/
// eslint-disable-next-line functional/prefer-readonly-type
private resolvedColumnWidths: readonly number[];
public constructor({
-1
View File
@@ -26,7 +26,6 @@ export type IContext = {
/** Access to document relationships and other document parts. */
readonly viewWrapper: IViewWrapper;
/** Current traversal stack of components (mutable for performance). */
// eslint-disable-next-line functional/prefer-readonly-type
readonly stack: IXmlableObject[];
};
+1 -3
View File
@@ -23,7 +23,6 @@ export const EMPTY_OBJECT = Object.seal({});
/**
* Adds what a child wrote to an element's children, leaving it out when it is undefined.
*/
// eslint-disable-next-line functional/prefer-readonly-type
const addChild = (children: IXmlableObject[], written: unknown): void => {
if (written !== undefined) {
// eslint-disable-next-line functional/immutable-data
@@ -60,7 +59,7 @@ export abstract class XmlComponent extends BaseXmlComponent {
* This array forms the content of the XML element. It can contain other
* XmlComponents, string values (text nodes), or attribute components.
*/
// eslint-disable-next-line functional/prefer-readonly-type, @typescript-eslint/no-explicit-any
// eslint-disable-next-line @typescript-eslint/no-explicit-any
protected root: (BaseXmlComponent | string | any)[];
/**
@@ -105,7 +104,6 @@ export abstract class XmlComponent extends BaseXmlComponent {
// Recursively prepare all children for serialization. A child written as several components, such as a run with
// a run in its children, is written as each of them in turn. Built in place, as an element of a document's body
// can have thousands of children
// eslint-disable-next-line functional/prefer-readonly-type
const children: IXmlableObject[] = [];
for (const comp of this.root) {
// A component from another copy of docx, such as one a plugin was bundled with, isn't an instance of
-1
View File
@@ -31,7 +31,6 @@ export type Link = { readonly href: string } | { readonly anchor: string };
*/
export type Note = {
readonly kind: "footnote" | "endnote";
// eslint-disable-next-line functional/prefer-readonly-type
content?: readonly ParagraphBlock[];
};
-1
View File
@@ -173,7 +173,6 @@ export const substituteVariables = (value: string, variableOf: (name: string) =>
const customPropertiesOf = (own: ReadonlyMap<string, string>, inherited: ReadonlyMap<string, string>): ReadonlyMap<string, string> => {
const resolved = new Map<string, string | undefined>();
// The properties being worked out, each referring to the next, and those found to be in a cycle
// eslint-disable-next-line functional/prefer-readonly-type
const resolving: string[] = [];
const cyclic = new Set<string>();
const resolve = (name: string): string | undefined => {
-3
View File
@@ -71,7 +71,6 @@ const endOfString = (css: string, start: number): number => {
*/
export const indexOfTopLevel = (css: string, start: number, characters: string): number => {
// The brackets that are open, the innermost last
// eslint-disable-next-line functional/prefer-readonly-type
const closing: string[] = [];
let index = start;
while (index < css.length) {
@@ -105,7 +104,6 @@ export const indexOfTopLevel = (css: string, start: number, characters: string):
* bracket without an opening one is skipped over, as is anything after a backslash.
*/
export const splitTopLevel = (css: string, separators: string): readonly string[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const parts: string[] = [];
let start = 0;
let end = indexOfTopLevel(css, start, separators);
@@ -167,7 +165,6 @@ const GROUPING_RULES: ReadonlySet<string> = new Set(["media", "supports", "layer
export const parseStyleSheet = (css: string): readonly StyleRule[] => rulesOf(withoutComments(css));
const rulesOf = (css: string): readonly StyleRule[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const rules: StyleRule[] = [];
let index = 0;
while (index < css.length) {
-3
View File
@@ -17,7 +17,6 @@ export const elementsOf = (element: Element): readonly Element[] => element.chil
* @param skipped - Elements in it whose text is left out
*/
export const textOf = (node: ChildNode, skipped: ReadonlySet<ChildNode> = new Set()): string => {
// eslint-disable-next-line functional/prefer-readonly-type
const stack: ChildNode[] = [node];
let text = "";
while (stack.length > 0) {
@@ -40,9 +39,7 @@ export const textOf = (node: ChildNode, skipped: ReadonlySet<ChildNode> = new Se
/** An element and the elements in it, in order, read without recursion, so no depth of elements is too deep */
export const descendantsOf = (element: Element): readonly Element[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const elements: Element[] = [];
// eslint-disable-next-line functional/prefer-readonly-type
const stack: Element[] = [element];
while (stack.length > 0) {
// eslint-disable-next-line functional/immutable-data
-1
View File
@@ -222,7 +222,6 @@ const escapeXml = (text: string): string => text.replace(/[&<>"]/g, (character)
*/
const svgFileOf = (svg: Element): string => {
let markup = "";
// eslint-disable-next-line functional/prefer-readonly-type
const stack: (ChildNode | string)[] = [svg];
while (stack.length > 0) {
// eslint-disable-next-line functional/immutable-data
-2
View File
@@ -93,10 +93,8 @@ const sameLevel = (a: ListLevel, b: ListLevel): boolean => a.format === b.format
/** A numbering definition being made, with the lists at each of its levels, and which have had items under the last item above */
type Definition = {
// eslint-disable-next-line functional/prefer-readonly-type
readonly levels: Map<number, ListLevel>;
/** The levels that have had items since the last item at the level above them */
// eslint-disable-next-line functional/prefer-readonly-type
readonly used: Set<number>;
};
-1
View File
@@ -57,7 +57,6 @@ const convert = (
readonly endnotes: readonly string[];
readonly warnings: readonly HtmlWarningCode[];
} => {
// eslint-disable-next-line functional/prefer-readonly-type
const warnings: HtmlWarningCode[] = [];
// eslint-disable-next-line functional/immutable-data
const written = formattedWithNotes(htmlToContent(html, { ...options, onWarning: (warning) => warnings.push(warning.code) }));
-1
View File
@@ -101,7 +101,6 @@ const isMark = (link: Element): boolean => /^[[({]?[^\s[\](){}]{1,6}[\])}]?$/u.t
/** The elements an element is in, nearest first, up to the body */
const ancestorsOf = (element: Element, body: Element): readonly Element[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const ancestors: Element[] = [];
let { parent } = element;
while (parent?.type === "tag" && parent !== body) {
-5
View File
@@ -68,7 +68,6 @@ type Conversion = {
/** The HTML's notes, which are Word's footnotes or endnotes */
readonly notes: Notes;
/** The lists of the paragraphs that Word's HTML puts in lists, by their list and level */
// eslint-disable-next-line functional/prefer-readonly-type
readonly wordLists: Map<string, object>;
} & {
readonly warn: (warning: HtmlWarning) => void;
@@ -194,9 +193,7 @@ const hasContent = (content: readonly Inline[]): boolean =>
* given. Bookmarks in inline content with nothing else go in the next paragraph, or the last if there is none after.
*/
const toBlocks = (contents: readonly Content[], format: ParagraphFormat): readonly Block[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const blocks: Block[] = [];
// eslint-disable-next-line functional/prefer-readonly-type
let inline: Inline[] = [];
let bookmarks: readonly Inline[] = [];
const flush = (): void => {
@@ -961,7 +958,6 @@ const readTable = (element: Element, style: ComputedStyle, state: State, convers
let borders = hasBorders(conversion.cascade(element, style.customProperties));
// Each cell's place: its row, its column, and how many it spans
// eslint-disable-next-line functional/prefer-readonly-type
const placedCells: {
readonly row: number;
readonly column: number;
@@ -970,7 +966,6 @@ const readTable = (element: Element, style: ComputedStyle, state: State, convers
readonly columns: number;
readonly rows: number;
}[] = [];
// eslint-disable-next-line functional/prefer-readonly-type
const rowStates: { readonly state: State; readonly header: boolean; readonly cells: number }[] = [];
const taken = new Set<string>();
let width = 0;
-1
View File
@@ -18,7 +18,6 @@ import { writeInline } from "./write-inline";
*/
export const writeBlocks = (blocks: readonly Block[], idOf: () => number): readonly (Paragraph | Table)[] => {
const numbering = numberLists(blocks);
// eslint-disable-next-line functional/prefer-readonly-type
const written: (Paragraph | Table)[] = [];
let pending: "page" | "column" | undefined;
for (const block of blocks) {
-6
View File
@@ -49,7 +49,6 @@ const transformed = (text: string, transform: "lowercase" | "capitalize" | undef
* A line break that ends the paragraph is left out, as it starts a line with nothing on it.
*/
const collapse = (content: readonly WrittenInline[]): readonly Piece[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const pieces: Piece[] = [];
let lineStart = true;
let previous = "";
@@ -146,10 +145,8 @@ const sameFormat = (a: RunFormat, b: RunFormat): boolean => JSON.stringify(a) ==
/** Runs of text, tabs and line breaks, with each stretch of one formatting and revision in one run */
const runsOf = (pieces: readonly RunPiece[], idOf: () => number): readonly ParagraphChild[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const runs: ParagraphChild[] = [];
let breaks = 0;
// eslint-disable-next-line functional/prefer-readonly-type
let children: (string | Tab)[] = [];
let current: Exclude<RunPiece, { readonly type: "break" }> | undefined;
@@ -209,9 +206,7 @@ const runsOf = (pieces: readonly RunPiece[], idOf: () => number): readonly Parag
/** The content of a link, or of the text between links: its runs, with images and other content between them */
const childrenOf = (pieces: readonly Exclude<Piece, { readonly type: "bookmark" }>[], idOf: () => number): readonly ParagraphChild[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const children: ParagraphChild[] = [];
// eslint-disable-next-line functional/prefer-readonly-type
let runs: RunPiece[] = [];
for (const piece of pieces) {
if (piece.type === "atom") {
@@ -235,7 +230,6 @@ const childrenOf = (pieces: readonly Exclude<Piece, { readonly type: "bookmark"
*/
export const writeInline = (content: readonly WrittenInline[], idOf: () => number): readonly ParagraphChild[] => {
const pieces = collapse(content);
// eslint-disable-next-line functional/prefer-readonly-type
const children: ParagraphChild[] = [];
let index = 0;
while (index < pieces.length) {
-9
View File
@@ -237,7 +237,6 @@ const AUTOMATIC_SPACE = 14;
* The lines of paragraphs without page references, by the measurer and widths they were laid out with. They are the same
* each time the pages are laid out again with the page numbers worked out before.
*/
// eslint-disable-next-line functional/prefer-readonly-type
const laidOutLines = new WeakMap<TextMeasurer, WeakMap<ParagraphBlock, Map<string, readonly LaidOutLine[]>>>();
/** How the rows of a table in a footnote are measured: as a line that can't be broken */
@@ -1054,7 +1053,6 @@ export const paginate = (
// Text in a font the measurer doesn't know stops the layout where it is measured. Guessing, it is measured as the
// measurer measures it, as the most similar font it knows, and the lines it is in say so (see `linesOf`)
const measuring = guess ? measurer : stoppingAtUnknownFonts(measurer);
// eslint-disable-next-line functional/prefer-readonly-type
const byParagraph = laidOutLines.get(measurer) ?? new WeakMap<ParagraphBlock, Map<string, readonly LaidOutLine[]>>();
laidOutLines.set(measurer, byParagraph);
/**
@@ -1270,7 +1268,6 @@ export const paginate = (
);
// Tables sized to their text, or with columns widened for long words, by the width they are in
// eslint-disable-next-line functional/prefer-readonly-type
const fittedTables = new Map<TableBlock, Map<number, TableBlock>>();
/**
* A table as it is laid out in a width: with its columns sized to their text, or widened for words longer than its
@@ -1472,7 +1469,6 @@ export const paginate = (
// Where each bookmark and field was placed
const places = new Map<string, PagePlace>();
// The height of each header and footer, by the section it is in, whose number of pages it can show
// eslint-disable-next-line functional/prefer-readonly-type
const headerHeights = new Map<readonly Block[], Map<number, number>>();
let pageCount = 0;
let pageNumber = 0;
@@ -1554,7 +1550,6 @@ export const paginate = (
let pageColumns: number | undefined;
// What has been placed on the pages, which laying out blocks again takes back, the last page whose footnotes are
// placed, the index of the block being placed, and the page the layout stopped on, whose lines might not be Word's
// eslint-disable-next-line functional/prefer-readonly-type
const placements: Placement[] = [];
let finished = 0;
let blockIndex = 0;
@@ -2402,9 +2397,7 @@ export const paginate = (
// The parts of the table rows in footnotes filled on the page, by the rooms they were cut at, one after the other, which
// the search for a row's cut and the notes' heights ask for again and again: filled afresh on each page, as its lines
// may be measured with its page number
// eslint-disable-next-line functional/prefer-readonly-type
type FilledParts = { readonly parts: readonly CellPart[]; readonly after: Map<number, FilledParts> };
// eslint-disable-next-line functional/prefer-readonly-type
let filledNoteParts = { page: 0, rows: new WeakMap<TableRow, Map<number, FilledParts>>() };
/**
@@ -2696,7 +2689,6 @@ export const paginate = (
lines: at.map(({ line, isFirst, left, y, width }) => placedLine(line, block.format, isFirst, left, width, y)),
};
};
// eslint-disable-next-line functional/prefer-readonly-type
const placed: PlacedLine[][] = stack.pieces.map(() => []);
if (stack.fillColumns !== undefined) {
const noteSection = sections[notesInColumns!];
@@ -4114,7 +4106,6 @@ export const paginate = (
const all = [...beside, ...around.map(({ drawing }) => drawing)];
const end = from + linesToBreak(lines, from).length;
const rooms = new Map(earlier);
// eslint-disable-next-line functional/prefer-readonly-type
const rows: Row[] = [];
let y = rowsTop;
let line = from;
-22
View File
@@ -673,12 +673,9 @@ type NoteReader = {
/** A complex field being read */
type OpenField = {
// eslint-disable-next-line functional/prefer-readonly-type
instruction: string;
// eslint-disable-next-line functional/prefer-readonly-type
inResult: boolean;
/** Whether its result depends on the pages, so it is worked out rather than read */
// eslint-disable-next-line functional/prefer-readonly-type
replaced: boolean;
/** Whether its start is deleted in a tracked change, or moved elsewhere, as all of it then is */
readonly deleted?: boolean;
@@ -689,9 +686,7 @@ type OpenField = {
* page references with `\p`, by the bookmarks they refer to
*/
type FieldMarkers = {
// eslint-disable-next-line functional/prefer-readonly-type
count: number;
// eslint-disable-next-line functional/prefer-readonly-type
readonly relative: Map<string, string[]>;
};
@@ -721,10 +716,8 @@ type Reader = {
readonly inEndnote?: boolean;
/** The markers at the fields whose pages are worked out, in the body and its notes */
readonly markers: FieldMarkers;
// eslint-disable-next-line functional/prefer-readonly-type
readonly fields: OpenField[];
/** Where the lists made from each definition are in their counting, by the definition's id */
// eslint-disable-next-line functional/prefer-readonly-type
readonly counters: Map<string, ListCount>;
/** Whether deleted text is read as text, as Word sizes a table's columns by it */
readonly showDeleted?: boolean;
@@ -748,7 +741,6 @@ type Reader = {
* The ids of the footnotes whose references are in text boxes, which Word leaves out, reference and note
* (`word-stops-vml-note.docx` VM26a)
*/
// eslint-disable-next-line functional/prefer-readonly-type
readonly notesInTextBoxes: Set<string>;
/** Why its equations can't be laid out as Word does for the document's maths settings, when they can't */
readonly maths?: string;
@@ -940,7 +932,6 @@ const numberSwitchesOf = (switches: string, decimalSymbol = "."): NumberSwitches
const parts = switches.match(/"[^"]*"|\S+/g) ?? [];
let numberFormat: string | undefined;
let picture: string | undefined;
// eslint-disable-next-line functional/prefer-readonly-type
const capitals: string[] = [];
let relative = false;
let unsupported: string | undefined;
@@ -2022,7 +2013,6 @@ const withFitted = (read: readonly LayoutItem[] | string): readonly LayoutItem[]
if (typeof read === "string") {
return read;
}
// eslint-disable-next-line functional/prefer-readonly-type
const all: LayoutItem[] = [];
for (const item of read) {
const id = FITTED.get(item)?.id;
@@ -2419,7 +2409,6 @@ const readListNumber = (
* as the schema has it (LR1, LR2).
*/
const countIn = (
// eslint-disable-next-line functional/prefer-readonly-type
counters: Map<string, ListCount>,
id: string,
{ levels, starts, definition }: NumberingList,
@@ -2712,7 +2701,6 @@ const readJoinedInline = (
joined: readonly { readonly element: XmlObject; readonly run: RunFormat; readonly marker?: string }[],
reader: Reader,
): readonly LayoutItem[] | string => {
// eslint-disable-next-line functional/prefer-readonly-type
const parts: (readonly LayoutItem[] | string)[] = [];
let from = 0;
let run = paragraphRun;
@@ -3748,7 +3736,6 @@ const readTable = (element: XmlObject, reader: Reader): TableBlock | undefined =
// them, or in the next with any text when it has none. Those before a deleted row and its cells, and in its cells,
// start in the next row laid out. Those after the last, as after a table's last row, aren't placed, so a page
// reference to them is left blank
// eslint-disable-next-line functional/prefer-readonly-type
const tableRows: TableRow[] = [];
let carried: readonly string[] = [];
let unmerged: string | undefined;
@@ -4559,7 +4546,6 @@ const joinRemovedMarks = (
): readonly XmlObject[] => {
const opened = openedAtEnds(elements.filter(isObject), styles, showDeleted);
// The elements after the one being read, as they are joined, from the last: the next is at the end
// eslint-disable-next-line functional/prefer-readonly-type
const after: XmlObject[] = [];
for (const element of [...opened].reverse()) {
const name = nameOf(element);
@@ -4657,7 +4643,6 @@ const readBlocks = (
// Only a table's cells are read in their table's formatting
part: Part = tableFormats === undefined ? "other" : "cell",
): readonly Block[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const blocks: Block[] = [];
let bookmarks: readonly string[] = [];
// The paragraphs left out since the last block, which take no room
@@ -4773,7 +4758,6 @@ const anchorFrames = <Entry extends { readonly block: Block; readonly section: n
): readonly Entry[] => {
const isFramed = (block: Block): block is ParagraphBlock & { readonly frame: FrameProperties } =>
block.type === "paragraph" && block.frame !== undefined && block.unsupported === undefined;
// eslint-disable-next-line functional/prefer-readonly-type
const anchored: Entry[] = [];
let framed: readonly Entry[] = [];
for (const entry of entries) {
@@ -6172,10 +6156,8 @@ export const readContent = (writtenBody: XmlObject, writtenParts: DocumentParts,
};
const footnotes = new Map<string, readonly Block[]>();
const footnoteNumbers = new Map<string, string>();
// eslint-disable-next-line functional/prefer-readonly-type
const endnotes: Block[] = [];
// The section of each of the endnotes' blocks' references
// eslint-disable-next-line functional/prefer-readonly-type
const endnoteBlockSections: number[] = [];
const endnoteNumbers = new Map<Block, string>();
// Each section's properties, which come after its paragraphs, so its notes are numbered as it says as they are read
@@ -6205,7 +6187,6 @@ export const readContent = (writtenBody: XmlObject, writtenParts: DocumentParts,
readonly section: number;
readonly inSection: number;
};
// eslint-disable-next-line functional/prefer-readonly-type
type NoteCounts = Map<NoteKind, NoteCount>;
const countOf = (counts: NoteCounts, kind: NoteKind): NoteCount =>
counts.get(kind) ?? { read: 0, counted: 0, section: sections.length, inSection: 0 };
@@ -6320,11 +6301,8 @@ export const readContent = (writtenBody: XmlObject, writtenParts: DocumentParts,
preview: () => previewFrom(noteCounts),
};
const reader: Reader = { ...readerOf(false), notes: noteReader };
// eslint-disable-next-line functional/prefer-readonly-type
const sections: Section[] = [];
// eslint-disable-next-line functional/prefer-readonly-type
const blocks: { readonly block: Block; readonly section: number }[] = [];
// eslint-disable-next-line functional/prefer-readonly-type
let bookmarks: string[] = [];
// The paragraphs left out since the last block, which take no room
let hidden: readonly ParagraphBlock[] = [];
-2
View File
@@ -65,7 +65,6 @@ const findMatch = (
* Reference: [MS-OVBA] 2.4.1.3.7 Compressing a DecompressedChunk
*/
const compressChunk = (data: Uint8Array, chunkStart: number, chunkEnd: number): readonly number[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const tokens: number[] = [];
let current = chunkStart;
while (current < chunkEnd) {
@@ -109,7 +108,6 @@ const compressChunk = (data: Uint8Array, chunkStart: number, chunkEnd: number):
* Reference: [MS-OVBA] 2.4.1.3.6 Compression algorithm
*/
export const compress = (data: Uint8Array): Uint8Array => {
// eslint-disable-next-line functional/prefer-readonly-type
const output: number[] = [0x01];
for (let chunkStart = 0; chunkStart < data.length; chunkStart += CHUNK_SIZE) {
// eslint-disable-next-line functional/immutable-data
-1
View File
@@ -24,7 +24,6 @@ type Record = { readonly id: number; readonly data: Uint8Array };
const dirRecordsOf = (streams: ReadonlyMap<string, Uint8Array>): readonly Record[] => {
const dir = decompress(streams.get("VBA/dir")!);
const view = new DataView(dir.buffer);
// eslint-disable-next-line functional/prefer-readonly-type
const records: Record[] = [];
for (let offset = 0; offset < dir.length;) {
const id = view.getUint16(offset, true);
-1
View File
@@ -158,7 +158,6 @@ type Piece =
* `a{b}c`.
*/
const atomsToPieces = (atoms: readonly Atom[]): readonly Piece[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const pieces: Piece[] = [];
for (let index = 0; index < atoms.length; index++) {
+1 -11
View File
@@ -42,7 +42,6 @@ const ELEMENTS: Readonly<Record<keyof PatchDocumentProperties, { readonly namesp
};
// The text of a property's element. An empty value clears the property
// eslint-disable-next-line functional/prefer-readonly-type
const textOf = (value: string | number): Element[] => (value === "" ? [] : [{ type: "text", text: String(value) }]);
// An element's name without its namespace prefix, which a document may choose. The core properties' elements each have
@@ -77,13 +76,7 @@ const decode = (bytes: Uint8Array): string => {
* .xml, with its other parts, as it found it, so that is read and moved to its XML parts, to be written in UTF-8 with
* them, rather than written over them as it was.
*/
const readPart = (
// eslint-disable-next-line functional/prefer-readonly-type
parts: Map<string, Element>,
// eslint-disable-next-line functional/prefer-readonly-type
binaryParts: Map<string, Uint8Array>,
path: string,
): Element | undefined => {
const readPart = (parts: Map<string, Element>, binaryParts: Map<string, Uint8Array>, path: string): Element | undefined => {
const bytes = binaryParts.get(path);
if (bytes === undefined) {
return parts.get(path);
@@ -105,7 +98,6 @@ const readPart = (
* The path of the package's core properties part, found from its relationships. A package without one is given a
* relationship to docProps/core.xml.
*/
// eslint-disable-next-line functional/prefer-readonly-type
const corePropertiesPathOf = (parts: Map<string, Element>): string => {
const relationships = parts.get(PACKAGE_RELATIONSHIPS_PATH) ?? createRelationshipFile();
const target = getFirstLevelElements(relationships, "Relationships").find(
@@ -130,9 +122,7 @@ const corePropertiesPathOf = (parts: Map<string, Element>): string => {
* @param addContentTypeOverride - Adds the content type of the part, if it's new
*/
export const patchCoreProperties = (
// eslint-disable-next-line functional/prefer-readonly-type
parts: Map<string, Element>,
// eslint-disable-next-line functional/prefer-readonly-type
binaryParts: Map<string, Uint8Array>,
properties: PatchDocumentProperties,
{ addContentTypeOverride }: { readonly addContentTypeOverride: (contentType: string, partName: string) => void },
-3
View File
@@ -100,7 +100,6 @@ type Call = {
// A drawing patch that records each call, and does what it is given to
class RecordingPatch extends DrawingPatch {
// eslint-disable-next-line functional/prefer-readonly-type
public readonly calls: Call[] = [];
public constructor(private readonly onPatch: (drawing: TemplateDrawing, template: TemplatePackage) => void = () => undefined) {
@@ -484,7 +483,6 @@ describe("drawing-patch", () => {
describe("the template's package", () => {
const relatedPart = async (files: Readonly<Record<string, string | Uint8Array | undefined>>, id = "rId5") => {
// eslint-disable-next-line functional/prefer-readonly-type
const parts: (ReturnType<TemplatePackage["getRelatedPart"]> | "none")[] = [];
await patch(templateWith(files), {
chart: new RecordingPatch(({ part }, template) => {
@@ -1011,7 +1009,6 @@ describe("drawing-patch", () => {
});
it("should accept a drawing patch whose class docx doesn't know, by its type", async () => {
// eslint-disable-next-line functional/prefer-readonly-type
const calls: string[] = [];
await patch(templateWith(), {
chart: {
+1 -10
View File
@@ -140,7 +140,6 @@ const CONTENT_TYPES = "[Content_Types].xml";
/**
* A relationships part's relationships, which can be added to. A part without the `Relationships` element is given one.
*/
// eslint-disable-next-line functional/prefer-readonly-type
const relationshipsIn = (relationships: Element): Element[] => {
if (!relationships.elements?.some((element) => element.name === "Relationships")) {
// eslint-disable-next-line functional/immutable-data
@@ -200,12 +199,7 @@ type TemplateContents = {
* @param parts - The template's XML parts, parsed, by their paths, which are changed in place
* @param binaryParts - The template's other parts, by their paths
*/
const contentsOf = (
// eslint-disable-next-line functional/prefer-readonly-type
parts: Map<string, Element>,
// eslint-disable-next-line functional/prefer-readonly-type
binaryParts: Map<string, Uint8Array>,
): TemplateContents => {
const contentsOf = (parts: Map<string, Element>, binaryParts: Map<string, Uint8Array>): TemplateContents => {
const has = (path: string): boolean => parts.has(path) || binaryParts.has(path);
// The path the package has a part at: as given, with its escapes decoded, or in other capitals, since part names
@@ -299,7 +293,6 @@ const contentsOf = (
* @param context - The context to format XML with
*/
const createTemplatePackage = (
// eslint-disable-next-line functional/prefer-readonly-type
parts: Map<string, Element>,
{ findRelationship, pathOf, removeIfUnreferenced }: TemplateContents,
file: File,
@@ -368,9 +361,7 @@ export const patchDrawings = (
patches,
delimiters,
}: {
// eslint-disable-next-line functional/prefer-readonly-type
readonly parts: Map<string, Element>;
// eslint-disable-next-line functional/prefer-readonly-type
readonly binaryParts: Map<string, Uint8Array>;
readonly file: File;
readonly patches: readonly (readonly [key: string, patch: DrawingPatch])[];
-5
View File
@@ -54,7 +54,6 @@ import { removeShapeTypesIn } from "./vml-shape-types";
* The patcher can accept documents in various formats including buffers,
* arrays, and streams, such as `fs.createReadStream`'s or `Packer.toStream`'s.
*/
// eslint-disable-next-line functional/prefer-readonly-type
export type InputDataType = Buffer | string | number[] | Uint8Array | ArrayBuffer | Blob | NodeJS.ReadableStream | Stream | ZipArchive;
export { PatchType } from "./patch-type";
@@ -349,7 +348,6 @@ export const patchDocument = async <T extends PatchDocumentOutputType = PatchDoc
// Theme colors in patches are written with the hex color they come to in the document's theme
const themeColors = readThemeColors(zipContent);
// The content types of parts that patches add to the package, such as charts
// eslint-disable-next-line functional/prefer-readonly-type
const contentTypeOverrides: { readonly contentType: string; readonly partName: string }[] = [];
const parts = new PackageParts(
{
@@ -377,9 +375,7 @@ export const patchDocument = async <T extends PatchDocumentOutputType = PatchDoc
const map = new Map<string, Element>();
// eslint-disable-next-line functional/prefer-readonly-type
const imageRelationshipAdditions: IImageRelationshipAddition[] = [];
// eslint-disable-next-line functional/prefer-readonly-type
const relationshipAdditions: IRelationshipAddition[] = [];
let hasMedia = false;
@@ -544,7 +540,6 @@ export const patchDocument = async <T extends PatchDocumentOutputType = PatchDoc
}
// The relationships of the patch's hyperlinks, which the part only gets if the placeholder is in it
// eslint-disable-next-line functional/prefer-readonly-type
const hyperlinkRelationships: IRelationshipAddition[] = [];
// TODO: mutates json. Make it immutable
-1
View File
@@ -30,7 +30,6 @@ const isBlob = (data: InputDataType): data is Blob => ["[object Blob]", "[object
*/
const readStream = (stream: TemplateStream): Promise<Uint8Array> =>
new Promise((resolve, reject) => {
// eslint-disable-next-line functional/prefer-readonly-type
const chunks: (Uint8Array | number)[] = [];
stream.on("data", (chunk: unknown) => {
// Not `instanceof Uint8Array`, which is false for a Buffer or Uint8Array from another realm, such as a vm context's
-2
View File
@@ -146,7 +146,6 @@ const withMark = (paragraph: Element, mark: Element): Element => {
const patchNotesOfKind = (
kind: NoteKind,
notes: PatchNotes,
// eslint-disable-next-line functional/prefer-readonly-type
parts: Map<string, Element>,
{ createContext, addContentTypeOverride, renumberBookmarks, renumberDrawings, renumberFitText, renumberLists, useStyles }: NotesHelpers,
): Omit<NotesPatcher, "carry"> & { readonly carry: (reference: object, note: Note) => number } => {
@@ -283,7 +282,6 @@ const patchNotesOfKind = (
*/
export const patchNotes = (
{ footnotes = {}, endnotes = {} }: { readonly footnotes?: PatchNotes; readonly endnotes?: PatchNotes },
// eslint-disable-next-line functional/prefer-readonly-type
parts: Map<string, Element>,
helpers: NotesHelpers,
): NotesPatcher => {
-1
View File
@@ -69,7 +69,6 @@ const highestOf = (ids: readonly number[]): number => ids.reduce((highest, id) =
*/
export const patchNumbering = (
numbering: Numbering,
// eslint-disable-next-line functional/prefer-readonly-type
parts: Map<string, Element>,
{ createContext, addContentTypeOverride }: NumberingHelpers,
): NumberingPatcher => {
+1 -5
View File
@@ -82,11 +82,7 @@ const formatDefaultStyles = (context: IContext, normalSize: number | undefined):
* @param parts - The document's XML parts, parsed, by their paths, whose styles part the styles are added to
* @param createContext - Creates a context to format content for a part with
*/
export const patchStyles = (
// eslint-disable-next-line functional/prefer-readonly-type
parts: Map<string, Element>,
createContext: (path: string) => IContext,
): StylesPatcher => {
export const patchStyles = (parts: Map<string, Element>, createContext: (path: string) => IContext): StylesPatcher => {
const templateElements = getFirstLevelElements(parts.get(STYLES_PATH) ?? {}, "w:styles");
const templateStyles = templateElements.filter((element) => element.name === "w:style");
const templateIds = new Set(templateStyles.map(idOf));
-2
View File
@@ -46,10 +46,8 @@ const elementsToWrapper = (wrapper: ElementWrapper): readonly ElementWrapper[] =
* ```
*/
export const traverse = (node: Element): readonly IRenderedParagraphNode[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const renderedParagraphs: IRenderedParagraphNode[] = [];
// eslint-disable-next-line functional/prefer-readonly-type
const queue: ElementWrapper[] = [
...elementsToWrapper({
element: node,
-2
View File
@@ -55,7 +55,6 @@ export const toJson = (xmlData: string): Element => {
* // Returns XML elements for <w:t>Hello World</w:t>
* ```
*/
// eslint-disable-next-line functional/prefer-readonly-type
export const createTextElementContents = (text: string): Element[] => {
const textJson = toJson(stringifyXmlable(formatter.format(new Text({ text }))));
@@ -101,7 +100,6 @@ export const patchSpaceAttribute = (element: Element): Element => ({
* // Returns array of Relationship elements
* ```
*/
// eslint-disable-next-line functional/prefer-readonly-type
export const getFirstLevelElements = (relationships: Element, id: string): Element[] => {
const parent = relationships.elements?.find((e) => e.name === id);
if (parent === undefined) {
-1
View File
@@ -67,7 +67,6 @@ const NUMBER = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/;
* @throws If the path doesn't start with a move, has an unknown command, or a command has the wrong number of arguments
*/
const tokenize = (path: string): readonly Command[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const commands: Command[] = [];
let index = 0;
let letter: string | undefined;
-2
View File
@@ -78,7 +78,6 @@ export const readCompoundFile = (file: Uint8Array): ReadCompoundFile => {
// The FAT's sectors: the first 109 are listed in the header, and the rest in a chain of DIFAT sectors, each listing
// as many as it has room for after the number of the next
const fatSectorCount = view.getUint32(44, true);
// eslint-disable-next-line functional/prefer-readonly-type
const fatSectors: number[] = [];
for (let index = 0; index < Math.min(fatSectorCount, 109); index++) {
// eslint-disable-next-line functional/immutable-data
@@ -96,7 +95,6 @@ export const readCompoundFile = (file: Uint8Array): ReadCompoundFile => {
Array.from({ length: sectorSize / 4 }, (_, index) => view.getUint32(sectorOffset(sector) + index * 4, true)),
);
const chain = (table: readonly number[], start: number): readonly number[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const sectors: number[] = [];
// No longer than the table, so a chain that loops ends
for (let sector = start; sector !== END_OF_CHAIN && sectors.length < table.length; sector = table[sector]) {
-1
View File
@@ -10,7 +10,6 @@
* Reference: [MS-OVBA] 2.4.1.3.1 Decompression Algorithm
*/
export const decompress = (data: Uint8Array): Uint8Array => {
// eslint-disable-next-line functional/prefer-readonly-type
const output: number[] = [];
// After the signature byte, 0x01
let chunkStart = 1;
-1
View File
@@ -66,7 +66,6 @@ const decodeFace = (encoded: string, drawnIn: string | undefined): ArabicFace =>
if (known) {
return known;
}
// eslint-disable-next-line functional/prefer-readonly-type
const widths: (number | undefined)[] = [];
let last: number | undefined;
for (let at = 0; at < encoded.length;) {
-3
View File
@@ -515,7 +515,6 @@ const ligatureAt = (glyphs: readonly number[], at: number, ligatures: ReadonlyMa
/** Joins glyphs with the ligatures of a lookup: at each glyph, its ligature, and the next glyph after the ligature's */
const joinWith = (glyphs: readonly number[], ligatures: ReadonlyMap<number, readonly Ligature[]>): readonly number[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const joined: number[] = [];
let at = 0;
while (at < glyphs.length) {
@@ -723,7 +722,6 @@ export const createFontFileMeasurer = (faces: readonly FontFace[], fallback: Tex
const em = (size * scale) / 100;
const kerned = isKerned(font) && (face.kernsWithLigatures || !hasLigatures(font));
let width = 0;
// eslint-disable-next-line functional/prefer-readonly-type
let run: number[] = [];
const measureRun = (): void => {
const { glyphs } = hasLigatures(font) ? face.join(run, font.ligatures!) : { glyphs: run };
@@ -803,7 +801,6 @@ export const createFontFileMeasurer = (faces: readonly FontFace[], fallback: Tex
}
// The glyphs as they are joined when they are measured: apart either side of a tab, or of a character the face
// has no glyph for
// eslint-disable-next-line functional/prefer-readonly-type
const runs: number[][] = [[]];
for (const character of text) {
const glyph = character === "\t" ? 0 : face.glyphOf(character.codePointAt(0)!);
-2
View File
@@ -82,7 +82,6 @@ export const indexRules = (rules: readonly LigatureRule[]): RuleIndex => {
return new Map(firsts.map((first) => [first, rules.filter(([letters]) => firstOf(letters) === first).sort(order)]));
};
// eslint-disable-next-line functional/prefer-readonly-type
const indexes = new Map<FaceShaping, Map<Ligatures, RuleIndex | undefined>>();
/**
@@ -158,7 +157,6 @@ export const joinLetters = (characters: readonly string[], rules: RuleIndex, gly
characters.slice(start, start + length).join("") === letters && (next === undefined || characters[start + length] === next)
);
});
// eslint-disable-next-line functional/prefer-readonly-type
const joined: Glyph[] = [];
let at = 0;
while (at < characters.length) {
-9
View File
@@ -409,7 +409,6 @@ const tokenizeText = (items: readonly (TextItem | SoftHyphenItem)[], rules: Line
items.filter((item): item is TextItem => item.type === "text"),
rules,
);
// eslint-disable-next-line functional/prefer-readonly-type
const tokens: { readonly type: "word" | "space"; readonly pieces: Piece[]; hyphens?: Hyphen[] }[] = [];
let index = 0;
// Whether the last character was a soft hyphen in a word, after which its next is measured apart
@@ -458,9 +457,7 @@ const tokenizeText = (items: readonly (TextItem | SoftHyphenItem)[], rules: Line
* Turns a part of a paragraph into tokens.
*/
const tokenize = (items: readonly InlineItem[], rules: LineBreakRules): readonly Token[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const tokens: Token[] = [];
// eslint-disable-next-line functional/prefer-readonly-type
let text: (TextItem | SoftHyphenItem)[] = [];
for (const item of items) {
if (item.type === "text" || item.type === "softHyphen") {
@@ -593,7 +590,6 @@ const widthOf = (pieces: readonly Piece[], measurer: TextMeasurer): number => {
* between the second f and the i of "efficient", its "ff", where "ffi" is without them (stops2/word-stops-text3.ts SH18e).
*/
export const textMeasuredTogether = (items: readonly InlineItem[]): readonly Piece[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const pieces: Piece[] = [];
let joins = false;
for (const item of items) {
@@ -1293,7 +1289,6 @@ const spacedOnGrid = (
items: readonly InlineItem[],
space: number,
): { readonly items: readonly InlineItem[]; readonly unsupported?: string } => {
// eslint-disable-next-line functional/prefer-readonly-type
const spaced: InlineItem[] = [];
let unsupported: string | undefined;
// The last character, its item in what is laid out, its kind and size, and whether it is in an East Asian font
@@ -1410,7 +1405,6 @@ const spacedBesideEastAsian = (
items: readonly InlineItem[],
spacing: { readonly letters: boolean; readonly digits: boolean },
): { readonly items: readonly InlineItem[]; readonly unsupported?: string } => {
// eslint-disable-next-line functional/prefer-readonly-type
const spaced: InlineItem[] = [];
let unsupported: string | undefined;
// The last character, its item in what is laid out and its kind
@@ -1523,7 +1517,6 @@ const withAcross = (items: readonly InlineItem[], measurer: TextMeasurer): reado
/** The two tokens after one, by its index, but for markers */
const nextTwo = (tokens: readonly Token[], index: number): readonly Token[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const next: Token[] = [];
for (let at = index + 1; at < tokens.length && next.length < 2; at++) {
if (tokens[at].type !== "marker") {
@@ -1851,7 +1844,6 @@ export const layoutLines = (
const endsWithBreak = parts.length > 1 && previous.end!.kind === "page" && last.tokens.every((token) => token.type === "marker");
const segments = endsWithBreak ? [...parts.slice(0, -2), { tokens: [...previous.tokens, ...last.tokens], end: previous.end }] : parts;
// eslint-disable-next-line functional/prefer-readonly-type
const lines: LaidOutLine[] = [];
/** The room of a line of its own, from its index, when it has one */
const roomOf = (line: number): LineRoom | undefined => {
@@ -2218,7 +2210,6 @@ export const layoutLines = (
if (token.pieces.some(({ font }) => hasLigatures(font))) {
line = { ...line, unsupported: line.unsupported ?? "a word longer than its line with ligatures" };
}
// eslint-disable-next-line functional/prefer-readonly-type
let onLine: Piece[] = [];
let from = line.position;
for (const character of charactersOf(token.pieces)) {
-3
View File
@@ -305,7 +305,6 @@ const twoDigitsIn = (encoded: string, at: number): number => DIGITS.indexOf(enco
* "*" and two digits repeating it that many more times.
*/
const decodeTokens = <T>(encoded: string, size: number, read: (token: string) => T): readonly (T | undefined)[] => {
// eslint-disable-next-line functional/prefer-readonly-type
const values: (T | undefined)[] = [];
let last: T | undefined;
for (let at = 0; at < encoded.length;) {
@@ -358,9 +357,7 @@ const decodeOwnWidths = (encoded: string): FaceWidths => {
return known;
}
const twoDigitsAt = (at: number): number => twoDigitsIn(encoded, at);
// eslint-disable-next-line functional/prefer-readonly-type
const widths: (number | undefined)[] = [];
// eslint-disable-next-line functional/prefer-readonly-type
const fallbacks: (number | undefined)[] = [];
let token = 0;
for (let at = 0; at < encoded.length;) {
-2
View File
@@ -73,7 +73,6 @@ const parseDeclarationAttributes = (body: string): XmlDeclarationAttributes =>
export const parseXml = (text: string, { keepWhitespaceText = false }: ParseXmlOptions = {}): XmlElement => {
// The tree is built in place, as a document's body can have thousands of children
const document: XmlElement = {};
// eslint-disable-next-line functional/prefer-readonly-type
const open: XmlElement[] = [];
let position = text.charCodeAt(0) === 0xfeff ? 1 : 0;
@@ -213,7 +212,6 @@ const parseStartTag = (text: string, from: number, onElement: (element: XmlEleme
}
// Entries, not an object, so that an attribute such as __proto__ is one of them rather than the object's prototype
// eslint-disable-next-line functional/prefer-readonly-type
const attributes: (readonly [string, string])[] = [];
let position = nameEnd;
for (;;) {
-2
View File
@@ -57,7 +57,6 @@ export type StringifyXmlableOptions = {
* @param isLast - Whether this is the last object written, which isn't followed by a line break
* @param out - The pieces of XML written so far
*/
// eslint-disable-next-line functional/prefer-readonly-type
const write = (data: object, indent: string, indents: string, isLast: boolean, out: string[]): void => {
// An empty object has no name, and writes nothing
const name = Object.keys(data)[0] as string | undefined;
@@ -153,7 +152,6 @@ export const stringifyXmlable = (
declaration === undefined
? ""
: `<?xml version="1.0" encoding="${escapeAll(declaration.encoding || "UTF-8")}"${standalone}?>${indent ? "\n" : ""}`;
// eslint-disable-next-line functional/prefer-readonly-type
const out: string[] = [declarationXml];
items.forEach((item, i) => write(item, indent, "", i === items.length - 1, out));
return out.join("");
+1 -1
View File
@@ -4,7 +4,7 @@
*
* @module
*/
/* eslint-disable functional/prefer-readonly-type -- Changes to a document, such as patches, are made to its tree in place */
// The types aren't readonly, as changes to a document, such as patches, are made to its tree in place
/**
* The attributes of an element, by name.