This commit is contained in:
2025-05-09 05:30:08 +02:00
parent 7bb10e7df4
commit 73367bad9e
5322 changed files with 1266973 additions and 313 deletions

View File

@@ -0,0 +1,114 @@
/**
* @fileoverview Rule to disallow assignments to native objects or read-only global variables
* @author Ilya Volodin
* @deprecated in ESLint v3.3.0
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description:
"Disallow assignments to native objects or read-only global variables",
recommended: false,
url: "https://eslint.org/docs/latest/rules/no-native-reassign",
},
deprecated: {
message: "Renamed rule.",
url: "https://eslint.org/blog/2016/08/eslint-v3.3.0-released/#deprecated-rules",
deprecatedSince: "3.3.0",
availableUntil: null,
replacedBy: [
{
rule: {
name: "no-global-assign",
url: "https://eslint.org/docs/rules/no-global-assign",
},
},
],
},
schema: [
{
type: "object",
properties: {
exceptions: {
type: "array",
items: { type: "string" },
uniqueItems: true,
},
},
additionalProperties: false,
},
],
messages: {
nativeReassign:
"Read-only global '{{name}}' should not be modified.",
},
},
create(context) {
const config = context.options[0];
const exceptions = (config && config.exceptions) || [];
const sourceCode = context.sourceCode;
/**
* Reports write references.
* @param {Reference} reference A reference to check.
* @param {int} index The index of the reference in the references.
* @param {Reference[]} references The array that the reference belongs to.
* @returns {void}
*/
function checkReference(reference, index, references) {
const identifier = reference.identifier;
if (
reference.init === false &&
reference.isWrite() &&
/*
* Destructuring assignments can have multiple default value,
* so possibly there are multiple writeable references for the same identifier.
*/
(index === 0 || references[index - 1].identifier !== identifier)
) {
context.report({
node: identifier,
messageId: "nativeReassign",
data: identifier,
});
}
}
/**
* Reports write references if a given variable is read-only builtin.
* @param {Variable} variable A variable to check.
* @returns {void}
*/
function checkVariable(variable) {
if (
variable.writeable === false &&
!exceptions.includes(variable.name)
) {
variable.references.forEach(checkReference);
}
}
return {
Program(node) {
const globalScope = sourceCode.getScope(node);
globalScope.variables.forEach(checkVariable);
},
};
},
};

View File

@@ -0,0 +1,978 @@
import { beforeAll, describe, expect, it, vi } from 'vitest';
import { createRef } from 'react';
import { fireEvent, render } from '@testing-library/react';
import { pdfjs } from './index.test.js';
import Page from './Page.js';
import LinkService from './LinkService.js';
import failingPdf from '../../../__mocks__/_failing_pdf.js';
import silentlyFailingPdf from '../../../__mocks__/_silently_failing_pdf.js';
import { loadPDF, makeAsyncCallback, muteConsole, restoreConsole } from '../../../test-utils.js';
import DocumentContext from './DocumentContext.js';
import type { PDFDocumentProxy, PDFPageProxy } from 'pdfjs-dist';
import type { DocumentContextType, PageCallback } from './shared/types.js';
const pdfFile = loadPDF('./../../__mocks__/_pdf.pdf');
const pdfFile2 = loadPDF('./../../__mocks__/_pdf2.pdf');
const pdfFile4 = loadPDF('./../../__mocks__/_pdf4.pdf');
function renderWithContext(children: React.ReactNode, context: Partial<DocumentContextType>) {
const { rerender, ...otherResult } = render(
<DocumentContext.Provider value={context as DocumentContextType}>
{children}
</DocumentContext.Provider>,
);
return {
...otherResult,
rerender: (
nextChildren: React.ReactNode,
nextContext: Partial<DocumentContextType> = context,
) =>
rerender(
<DocumentContext.Provider value={nextContext as DocumentContextType}>
{nextChildren}
</DocumentContext.Provider>,
),
};
}
describe('Page', () => {
const linkService = new LinkService();
// Loaded PDF file
let pdf: PDFDocumentProxy;
let pdf2: PDFDocumentProxy;
let pdf4: PDFDocumentProxy;
// Object with basic loaded page information that shall match after successful loading
const desiredLoadedPage: Partial<PDFPageProxy> = {};
const desiredLoadedPage2: Partial<PDFPageProxy> = {};
const desiredLoadedPage3: Partial<PDFPageProxy> = {};
// Callbacks used in registerPage and unregisterPage callbacks
let registerPageArguments: [number, HTMLDivElement];
let unregisterPageArguments: [number];
beforeAll(async () => {
pdf = await pdfjs.getDocument({ data: pdfFile.arrayBuffer }).promise;
const page = await pdf.getPage(1);
desiredLoadedPage._pageIndex = page._pageIndex;
desiredLoadedPage._pageInfo = page._pageInfo;
const page2 = await pdf.getPage(2);
desiredLoadedPage2._pageIndex = page2._pageIndex;
desiredLoadedPage2._pageInfo = page2._pageInfo;
pdf2 = await pdfjs.getDocument({ data: pdfFile2.arrayBuffer }).promise;
const page3 = await pdf2.getPage(1);
desiredLoadedPage3._pageIndex = page3._pageIndex;
desiredLoadedPage3._pageInfo = page3._pageInfo;
registerPageArguments = [page._pageIndex, expect.any(HTMLDivElement)];
unregisterPageArguments = [page._pageIndex];
pdf4 = await pdfjs.getDocument({ data: pdfFile4.arrayBuffer }).promise;
});
describe('loading', () => {
it('loads a page and calls onLoadSuccess callback properly when placed inside Document', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
renderWithContext(<Page onLoadSuccess={onLoadSuccess} pageIndex={0} />, {
linkService,
pdf,
});
expect.assertions(1);
await expect(onLoadSuccessPromise).resolves.toMatchObject([desiredLoadedPage]);
});
it('loads a page and calls onLoadSuccess callback properly when pdf prop is passed', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
render(
<Page
onLoadSuccess={onLoadSuccess}
pageIndex={0}
pdf={pdf}
renderAnnotationLayer={false}
/>,
);
expect.assertions(1);
await expect(onLoadSuccessPromise).resolves.toMatchObject([desiredLoadedPage]);
});
it('returns all desired parameters in onLoadSuccess callback', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } =
makeAsyncCallback<[PageCallback]>();
renderWithContext(<Page onLoadSuccess={onLoadSuccess} pageIndex={0} />, {
linkService,
pdf,
});
expect.assertions(5);
const [page] = await onLoadSuccessPromise;
expect(page.width).toBeDefined();
expect(page.height).toBeDefined();
expect(page.originalWidth).toBeDefined();
expect(page.originalHeight).toBeDefined();
// Example of a method that got stripped away in the past
expect(page.getTextContent).toBeInstanceOf(Function);
});
it('calls onLoadError when failed to load a page', async () => {
const { func: onLoadError, promise: onLoadErrorPromise } = makeAsyncCallback();
muteConsole();
renderWithContext(<Page onLoadError={onLoadError} pageIndex={0} />, {
linkService,
pdf: failingPdf,
});
expect.assertions(1);
await expect(onLoadErrorPromise).resolves.toMatchObject([expect.any(Error)]);
restoreConsole();
});
it('loads page when given pageIndex', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
renderWithContext(<Page onLoadSuccess={onLoadSuccess} pageIndex={0} />, {
linkService,
pdf,
});
expect.assertions(1);
const [page] = await onLoadSuccessPromise;
expect(page).toMatchObject(desiredLoadedPage);
});
it('loads page when given pageNumber', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
renderWithContext(<Page onLoadSuccess={onLoadSuccess} pageNumber={1} />, {
linkService,
pdf,
});
expect.assertions(1);
const [page] = await onLoadSuccessPromise;
expect(page).toMatchObject(desiredLoadedPage);
});
it('loads page of a given number when given conflicting pageNumber and pageIndex', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
renderWithContext(<Page onLoadSuccess={onLoadSuccess} pageIndex={1} pageNumber={1} />, {
linkService,
pdf,
});
expect.assertions(1);
const [page] = await onLoadSuccessPromise;
expect(page).toMatchObject(desiredLoadedPage);
});
it('calls registerPage when loaded a page', async () => {
const { func: registerPage, promise: registerPagePromise } = makeAsyncCallback();
renderWithContext(<Page pageIndex={0} />, {
linkService,
pdf,
registerPage,
});
expect.assertions(1);
await expect(registerPagePromise).resolves.toMatchObject(registerPageArguments);
});
it('calls unregisterPage on unmount', async () => {
const { func: unregisterPage, promise: nuregisterPagePromise } = makeAsyncCallback();
const { unmount } = renderWithContext(<Page pageIndex={0} />, {
linkService,
pdf,
unregisterPage,
});
unmount();
expect.assertions(1);
await expect(nuregisterPagePromise).resolves.toMatchObject(unregisterPageArguments);
});
it('replaces a page properly when pdf is changed', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
const { rerender } = renderWithContext(<Page onLoadSuccess={onLoadSuccess} pageIndex={0} />, {
linkService,
pdf,
});
expect.assertions(2);
await expect(onLoadSuccessPromise).resolves.toMatchObject([desiredLoadedPage]);
const { func: onLoadSuccess2, promise: onLoadSuccessPromise2 } = makeAsyncCallback();
rerender(<Page onLoadSuccess={onLoadSuccess2} pageIndex={0} />, {
linkService,
pdf: pdf2,
});
await expect(onLoadSuccessPromise2).resolves.toMatchObject([desiredLoadedPage3]);
});
it('replaces a page properly when pageNumber is changed', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
const { rerender } = renderWithContext(<Page onLoadSuccess={onLoadSuccess} pageIndex={0} />, {
linkService,
pdf,
});
expect.assertions(2);
await expect(onLoadSuccessPromise).resolves.toMatchObject([desiredLoadedPage]);
const { func: onLoadSuccess2, promise: onLoadSuccessPromise2 } = makeAsyncCallback();
rerender(<Page onLoadSuccess={onLoadSuccess2} pageIndex={1} />, {
linkService,
pdf,
});
await expect(onLoadSuccessPromise2).resolves.toMatchObject([desiredLoadedPage2]);
});
it('throws an error when placed outside Document without pdf prop passed', () => {
muteConsole();
expect(() => render(<Page pageIndex={0} />)).toThrow();
restoreConsole();
});
});
describe('rendering', () => {
it('applies className to its wrapper when given a string', () => {
const className = 'testClassName';
const { container } = renderWithContext(<Page className={className} pageIndex={0} />, {
linkService,
pdf,
});
const wrapper = container.querySelector('.react-pdf__Page');
expect(wrapper).toHaveClass(className);
});
it('passes container element to inputRef properly', () => {
const inputRef = createRef<HTMLDivElement>();
renderWithContext(<Page inputRef={inputRef} pageIndex={1} />, {
linkService,
pdf: silentlyFailingPdf,
});
expect(inputRef.current).toBeInstanceOf(HTMLDivElement);
});
it('passes canvas element to Canvas properly', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
const canvasRef = createRef<HTMLCanvasElement>();
const { container } = renderWithContext(
<Page canvasRef={canvasRef} onLoadSuccess={onLoadSuccess} pageIndex={0} />,
{
linkService,
pdf,
},
);
expect.assertions(1);
await onLoadSuccessPromise;
const pageCanvas = container.querySelector('.react-pdf__Page__canvas');
expect(canvasRef.current).toBe(pageCanvas);
});
it('renders "No page specified." when given neither pageIndex nor pageNumber', () => {
muteConsole();
const { container } = renderWithContext(<Page />, {
linkService,
pdf,
});
const noData = container.querySelector('.react-pdf__message');
expect(noData).toBeInTheDocument();
expect(noData).toHaveTextContent('No page specified.');
restoreConsole();
});
it('renders custom no data message when given nothing and noData is given', () => {
muteConsole();
const { container } = renderWithContext(<Page noData="Nothing here" />, {
linkService,
pdf,
});
const noData = container.querySelector('.react-pdf__message');
expect(noData).toBeInTheDocument();
expect(noData).toHaveTextContent('Nothing here');
restoreConsole();
});
it('renders custom no data message when given nothing and noData is given as a function', () => {
muteConsole();
const { container } = renderWithContext(<Page noData={() => 'Nothing here'} />, {
linkService,
pdf,
});
const noData = container.querySelector('.react-pdf__message');
expect(noData).toBeInTheDocument();
expect(noData).toHaveTextContent('Nothing here');
restoreConsole();
});
it('renders "Loading page…" when loading a page', async () => {
const { container } = renderWithContext(<Page pageIndex={0} />, {
linkService,
pdf,
});
const loading = container.querySelector('.react-pdf__message');
expect(loading).toBeInTheDocument();
expect(loading).toHaveTextContent('Loading page…');
});
it('renders custom loading message when loading a page and loading prop is given', async () => {
const { container } = renderWithContext(<Page loading="Loading" pageIndex={0} />, {
linkService,
pdf,
});
const loading = container.querySelector('.react-pdf__message');
expect(loading).toBeInTheDocument();
expect(loading).toHaveTextContent('Loading');
});
it('renders custom loading message when loading a page and loading prop is given as a function', async () => {
const { container } = renderWithContext(<Page loading={() => 'Loading'} pageIndex={0} />, {
linkService,
pdf,
});
const loading = container.querySelector('.react-pdf__message');
expect(loading).toBeInTheDocument();
expect(loading).toHaveTextContent('Loading');
});
it('ignores pageIndex when given pageIndex and pageNumber', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
renderWithContext(<Page onLoadSuccess={onLoadSuccess} pageIndex={1} pageNumber={1} />, {
linkService,
pdf,
});
expect.assertions(1);
const [page] = await onLoadSuccessPromise;
expect(page).toMatchObject(desiredLoadedPage);
});
it('requests page to be rendered with default rotation when given nothing', async () => {
const { func: onRenderSuccess, promise: onRenderSuccessPromise } =
makeAsyncCallback<[PageCallback]>();
const { container } = renderWithContext(
<Page onRenderSuccess={onRenderSuccess} pageIndex={0} />,
{
linkService,
pdf,
},
);
const [page] = await onRenderSuccessPromise;
const pageCanvas = container.querySelector('.react-pdf__Page__canvas') as HTMLCanvasElement;
const { width, height } = window.getComputedStyle(pageCanvas);
const viewport = page.getViewport({ scale: 1 });
// Expect the canvas layer not to be rotated
expect(Number.parseInt(width, 10)).toBe(Math.floor(viewport.width));
expect(Number.parseInt(height, 10)).toBe(Math.floor(viewport.height));
});
it('requests page to be rendered with given rotation when given rotate prop', async () => {
const { func: onRenderSuccess, promise: onRenderSuccessPromise } =
makeAsyncCallback<[PageCallback]>();
const rotate = 90;
const { container } = renderWithContext(
<Page onRenderSuccess={onRenderSuccess} pageIndex={0} rotate={rotate} />,
{
linkService,
pdf,
},
);
const [page] = await onRenderSuccessPromise;
const pageCanvas = container.querySelector('.react-pdf__Page__canvas') as HTMLCanvasElement;
const { width, height } = window.getComputedStyle(pageCanvas);
const viewport = page.getViewport({ scale: 1, rotation: rotate });
// Expect the canvas layer to be rotated
expect(Number.parseInt(width, 10)).toBe(Math.floor(viewport.width));
expect(Number.parseInt(height, 10)).toBe(Math.floor(viewport.height));
});
it('requests page to be rendered in canvas mode by default', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
const { container } = renderWithContext(
<Page onLoadSuccess={onLoadSuccess} pageIndex={0} />,
{
linkService,
pdf,
},
);
expect.assertions(1);
await onLoadSuccessPromise;
const pageCanvas = container.querySelector('.react-pdf__Page__canvas');
expect(pageCanvas).toBeInTheDocument();
});
it('requests page not to be rendered when given renderMode = "none"', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
const { container } = renderWithContext(
<Page onLoadSuccess={onLoadSuccess} pageIndex={0} renderMode="none" />,
{
linkService,
pdf,
},
);
expect.assertions(1);
await onLoadSuccessPromise;
const pageCanvas = container.querySelector('.react-pdf__Page__canvas');
expect(pageCanvas).not.toBeInTheDocument();
});
it('requests page to be rendered in canvas mode when given renderMode = "canvas"', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
const { container } = renderWithContext(
<Page onLoadSuccess={onLoadSuccess} pageIndex={0} renderMode="canvas" />,
{
linkService,
pdf,
},
);
expect.assertions(1);
await onLoadSuccessPromise;
const pageCanvas = container.querySelector('.react-pdf__Page__canvas');
expect(pageCanvas).toBeInTheDocument();
});
it('requests page to be rendered in custom mode when given renderMode = "custom"', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
function CustomRenderer() {
return <div className="custom-renderer" />;
}
const { container } = renderWithContext(
<Page
customRenderer={CustomRenderer}
onLoadSuccess={onLoadSuccess}
pageIndex={0}
renderMode="custom"
/>,
{
linkService,
pdf,
},
);
expect.assertions(1);
await onLoadSuccessPromise;
const customRenderer = container.querySelector('.custom-renderer');
expect(customRenderer).toBeInTheDocument();
});
it('requests text content to be rendered by default', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
const { container } = renderWithContext(
<Page onLoadSuccess={onLoadSuccess} pageIndex={0} />,
{
linkService,
pdf,
},
);
expect.assertions(1);
await onLoadSuccessPromise;
const textLayer = container.querySelector('.react-pdf__Page__textContent');
expect(textLayer).toBeInTheDocument();
});
it('requests text content to be rendered when given renderTextLayer = true', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
const { container } = renderWithContext(
<Page onLoadSuccess={onLoadSuccess} pageIndex={0} renderTextLayer />,
{
linkService,
pdf,
},
);
expect.assertions(1);
await onLoadSuccessPromise;
const textLayer = container.querySelector('.react-pdf__Page__textContent');
expect(textLayer).toBeInTheDocument();
});
it('does not request text content to be rendered when given renderTextLayer = false', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
const { container } = renderWithContext(
<Page onLoadSuccess={onLoadSuccess} pageIndex={0} renderTextLayer={false} />,
{
linkService,
pdf,
},
);
expect.assertions(1);
await onLoadSuccessPromise;
const textLayer = container.querySelector('.react-pdf__Page__textContent');
expect(textLayer).not.toBeInTheDocument();
});
it('renders TextLayer when given renderMode = "canvas"', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
const { container } = renderWithContext(
<Page onLoadSuccess={onLoadSuccess} pageIndex={0} renderMode="canvas" renderTextLayer />,
{
linkService,
pdf,
},
);
expect.assertions(1);
await onLoadSuccessPromise;
const textLayer = container.querySelector('.react-pdf__Page__textContent');
expect(textLayer).toBeInTheDocument();
});
it('renders TextLayer when given renderMode = "custom"', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
function CustomRenderer() {
return <div className="custom-renderer" />;
}
const { container } = renderWithContext(
<Page
customRenderer={CustomRenderer}
onLoadSuccess={onLoadSuccess}
pageIndex={0}
renderMode="custom"
renderTextLayer
/>,
{
linkService,
pdf,
},
);
expect.assertions(1);
await onLoadSuccessPromise;
const textLayer = container.querySelector('.react-pdf__Page__textContent');
expect(textLayer).toBeInTheDocument();
});
it('requests annotations to be rendered by default', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
const { container } = renderWithContext(
<Page onLoadSuccess={onLoadSuccess} pageIndex={0} />,
{
linkService,
pdf,
},
);
expect.assertions(1);
await onLoadSuccessPromise;
const annotationLayer = container.querySelector('.react-pdf__Page__annotations');
expect(annotationLayer).toBeInTheDocument();
});
it('requests annotations to be rendered when given renderAnnotationLayer = true', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
const { container } = renderWithContext(
<Page onLoadSuccess={onLoadSuccess} pageIndex={0} renderAnnotationLayer />,
{
linkService,
pdf,
},
);
expect.assertions(1);
await onLoadSuccessPromise;
const annotationLayer = container.querySelector('.react-pdf__Page__annotations');
expect(annotationLayer).toBeInTheDocument();
});
it('does not request annotations to be rendered when given renderAnnotationLayer = false', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } = makeAsyncCallback();
const { container } = renderWithContext(
<Page onLoadSuccess={onLoadSuccess} pageIndex={0} renderAnnotationLayer={false} />,
{
linkService,
pdf,
},
);
expect.assertions(1);
await onLoadSuccessPromise;
const annotationLayer = container.querySelector('.react-pdf__Page__annotations');
expect(annotationLayer).not.toBeInTheDocument();
});
});
it('requests page to be rendered without forms by default', async () => {
const { func: onRenderAnnotationLayerSuccess, promise: onRenderAnnotationLayerSuccessPromise } =
makeAsyncCallback();
const { container } = renderWithContext(
<Page
onRenderAnnotationLayerSuccess={onRenderAnnotationLayerSuccess}
pageIndex={0}
renderMode="none"
/>,
{
linkService,
pdf: pdf4,
},
);
expect.assertions(1);
await onRenderAnnotationLayerSuccessPromise;
const textWidgetAnnotation = container.querySelector('.textWidgetAnnotation');
expect(textWidgetAnnotation).toBeFalsy();
});
it('requests page to be rendered with forms given renderForms = true', async () => {
const { func: onRenderAnnotationLayerSuccess, promise: onRenderAnnotationLayerSuccessPromise } =
makeAsyncCallback();
const { container } = renderWithContext(
<Page
onRenderAnnotationLayerSuccess={onRenderAnnotationLayerSuccess}
pageIndex={0}
renderForms
renderMode="none"
/>,
{
linkService,
pdf: pdf4,
},
);
expect.assertions(1);
await onRenderAnnotationLayerSuccessPromise;
const textWidgetAnnotation = container.querySelector('.textWidgetAnnotation');
expect(textWidgetAnnotation).toBeTruthy();
});
it('requests page to be rendered at its original size given nothing', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } =
makeAsyncCallback<[PageCallback]>();
renderWithContext(<Page onLoadSuccess={onLoadSuccess} pageIndex={0} />, {
linkService,
pdf,
});
expect.assertions(1);
const [page] = await onLoadSuccessPromise;
expect(page.width).toEqual(page.originalWidth);
});
it('requests page to be rendered with a proper scale when given scale', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } =
makeAsyncCallback<[PageCallback]>();
const scale = 1.5;
renderWithContext(<Page onLoadSuccess={onLoadSuccess} pageIndex={0} scale={scale} />, {
linkService,
pdf,
});
expect.assertions(1);
const [page] = await onLoadSuccessPromise;
expect(page.width).toEqual(page.originalWidth * scale);
});
it('requests page to be rendered with a proper scale when given width', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } =
makeAsyncCallback<[PageCallback]>();
const width = 600;
renderWithContext(<Page onLoadSuccess={onLoadSuccess} pageIndex={0} width={width} />, {
linkService,
pdf,
});
expect.assertions(1);
const [page] = await onLoadSuccessPromise;
expect(page.width).toEqual(width);
});
it('requests page to be rendered with a proper scale when given width and scale (multiplies)', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } =
makeAsyncCallback<[PageCallback]>();
const width = 600;
const scale = 1.5;
renderWithContext(
<Page onLoadSuccess={onLoadSuccess} pageIndex={0} scale={scale} width={width} />,
{
linkService,
pdf,
},
);
expect.assertions(1);
const [page] = await onLoadSuccessPromise;
expect(page.width).toBeCloseTo(width * scale);
});
it('requests page to be rendered with a proper scale when given height', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } =
makeAsyncCallback<[PageCallback]>();
const height = 850;
renderWithContext(<Page height={height} onLoadSuccess={onLoadSuccess} pageIndex={0} />, {
linkService,
pdf,
});
expect.assertions(1);
const [page] = await onLoadSuccessPromise;
expect(page.height).toEqual(height);
});
it('requests page to be rendered with a proper scale when given height and scale (multiplies)', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } =
makeAsyncCallback<[PageCallback]>();
const height = 850;
const scale = 1.5;
renderWithContext(
<Page height={height} onLoadSuccess={onLoadSuccess} pageIndex={0} scale={scale} />,
{
linkService,
pdf,
},
);
expect.assertions(1);
const [page] = await onLoadSuccessPromise;
expect(page.height).toBeCloseTo(height * scale);
});
it('requests page to be rendered with a proper scale when given width and height (ignores height)', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } =
makeAsyncCallback<[PageCallback]>();
const width = 600;
const height = 100;
renderWithContext(
<Page height={height} onLoadSuccess={onLoadSuccess} pageIndex={0} width={width} />,
{
linkService,
pdf,
},
);
expect.assertions(2);
const [page] = await onLoadSuccessPromise;
expect(page.width).toEqual(width);
// Expect proportions to be correct even though invalid height was provided
expect(page.height).toEqual(page.originalHeight * (page.width / page.originalWidth));
});
it('requests page to be rendered with a proper scale when given width, height and scale (ignores height, multiplies)', async () => {
const { func: onLoadSuccess, promise: onLoadSuccessPromise } =
makeAsyncCallback<[PageCallback]>();
const width = 600;
const height = 100;
const scale = 1.5;
renderWithContext(
<Page
height={height}
onLoadSuccess={onLoadSuccess}
pageIndex={0}
scale={scale}
width={width}
/>,
{
linkService,
pdf,
},
);
expect.assertions(2);
const [page] = await onLoadSuccessPromise;
expect(page.width).toBeCloseTo(width * scale);
// Expect proportions to be correct even though invalid height was provided
expect(page.height).toEqual(page.originalHeight * (page.width / page.originalWidth));
});
it('calls onClick callback when clicked a page (sample of mouse events family)', () => {
const onClick = vi.fn();
const { container } = renderWithContext(<Page onClick={onClick} />, {
linkService,
pdf,
});
const page = container.querySelector('.react-pdf__Page') as HTMLDivElement;
fireEvent.click(page);
expect(onClick).toHaveBeenCalled();
});
it('calls onTouchStart callback when touched a page (sample of touch events family)', () => {
const onTouchStart = vi.fn();
const { container } = renderWithContext(<Page onTouchStart={onTouchStart} />, {
linkService,
pdf,
});
const page = container.querySelector('.react-pdf__Page') as HTMLDivElement;
fireEvent.touchStart(page);
expect(onTouchStart).toHaveBeenCalled();
});
});

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"2":"K D E F A B mC"},B:{"1":"0 9 P Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I","2":"C L M G N","132":"O"},C:{"1":"0 9 TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC oC pC","2":"1 2 3 4 5 6 7 8 nC LC J PB K D E F A B C L M G N O P QB RB SB qC rC"},D:{"1":"0 9 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC","2":"1 2 3 4 5 6 7 8 J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB","132":"nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB"},E:{"1":"F A B C L M G wC TC FC GC xC yC zC UC VC HC 0C IC WC XC YC ZC aC 1C JC bC cC dC eC fC 2C KC gC hC iC jC 3C","2":"J PB K D E sC SC tC uC vC"},F:{"1":"0 pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z","2":"1 2 3 4 5 6 7 8 F B C G N O P QB RB SB TB UB VB WB XB YB ZB 4C 5C 6C 7C FC kC 8C GC","132":"aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB"},G:{"1":"ED FD GD HD ID JD KD LD MD ND OD PD QD RD SD UC VC HC TD IC WC XC YC ZC aC UD JC bC cC dC eC fC VD KC gC hC iC jC","2":"E SC 9C lC AD BD CD DD"},H:{"2":"WD"},I:{"1":"I","2":"LC J XD YD ZD aD lC bD cD"},J:{"2":"D A"},K:{"1":"H","2":"A B C FC kC GC"},L:{"1":"I"},M:{"1":"EC"},N:{"2":"A B"},O:{"1":"HC"},P:{"1":"1 2 3 4 5 6 7 8 hD TC iD jD kD lD mD IC JC KC nD","2":"J","132":"dD eD fD gD"},Q:{"1":"oD"},R:{"1":"pD"},S:{"1":"qD rD"}},B:1,C:"relList (DOMTokenList)",D:true};

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"1":"F A B","2":"K D E mC"},B:{"1":"0 9 C L M G N O P Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I"},C:{"1":"0 1 2 3 4 5 6 7 8 9 nC LC J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC oC pC qC rC"},D:{"1":"0 1 2 3 4 5 6 7 8 9 J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC"},E:{"1":"J PB K D E F A B C L M G sC SC tC uC vC wC TC FC GC xC yC zC UC VC HC 0C IC WC XC YC ZC aC 1C JC bC cC dC eC fC 2C KC gC hC iC jC 3C"},F:{"1":"0 1 2 3 4 5 6 7 8 F B C G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 4C 5C 6C 7C FC kC 8C GC"},G:{"1":"E SC 9C lC AD BD CD DD ED FD GD HD ID JD KD LD MD ND OD PD QD RD SD UC VC HC TD IC WC XC YC ZC aC UD JC bC cC dC eC fC VD KC gC hC iC jC"},H:{"1":"WD"},I:{"1":"LC J I XD YD ZD aD lC bD cD"},J:{"1":"D A"},K:{"1":"A B C H FC kC GC"},L:{"1":"I"},M:{"1":"EC"},N:{"1":"A B"},O:{"1":"HC"},P:{"1":"1 2 3 4 5 6 7 8 J dD eD fD gD hD TC iD jD kD lD mD IC JC KC nD"},Q:{"1":"oD"},R:{"1":"pD"},S:{"1":"qD rD"}},B:1,C:"naturalWidth & naturalHeight image properties",D:true};

View File

@@ -0,0 +1,79 @@
/* -*- Mode: js; js-indent-level: 2; -*- */
/*
* Copyright 2014 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
var util = require('./util');
/**
* Determine whether mappingB is after mappingA with respect to generated
* position.
*/
function generatedPositionAfter(mappingA, mappingB) {
// Optimized for most common case
var lineA = mappingA.generatedLine;
var lineB = mappingB.generatedLine;
var columnA = mappingA.generatedColumn;
var columnB = mappingB.generatedColumn;
return lineB > lineA || lineB == lineA && columnB >= columnA ||
util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
}
/**
* A data structure to provide a sorted view of accumulated mappings in a
* performance conscious manner. It trades a neglibable overhead in general
* case for a large speedup in case of mappings being added in order.
*/
function MappingList() {
this._array = [];
this._sorted = true;
// Serves as infimum
this._last = {generatedLine: -1, generatedColumn: 0};
}
/**
* Iterate through internal items. This method takes the same arguments that
* `Array.prototype.forEach` takes.
*
* NOTE: The order of the mappings is NOT guaranteed.
*/
MappingList.prototype.unsortedForEach =
function MappingList_forEach(aCallback, aThisArg) {
this._array.forEach(aCallback, aThisArg);
};
/**
* Add the given source mapping.
*
* @param Object aMapping
*/
MappingList.prototype.add = function MappingList_add(aMapping) {
if (generatedPositionAfter(this._last, aMapping)) {
this._last = aMapping;
this._array.push(aMapping);
} else {
this._sorted = false;
this._array.push(aMapping);
}
};
/**
* Returns the flat, sorted array of mappings. The mappings are sorted by
* generated position.
*
* WARNING: This method returns internal data without copying, for
* performance. The return value must NOT be mutated, and should be treated as
* an immutable borrow. If you want to take ownership, you must make your own
* copy.
*/
MappingList.prototype.toArray = function MappingList_toArray() {
if (!this._sorted) {
this._array.sort(util.compareByGeneratedPositionsInflated);
this._sorted = true;
}
return this._array;
};
exports.MappingList = MappingList;

View File

@@ -0,0 +1,424 @@
/**
* @license React
* react-dom.development.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
"use strict";
"production" !== process.env.NODE_ENV &&
(function () {
function noop() {}
function testStringCoercion(value) {
return "" + value;
}
function createPortal$1(children, containerInfo, implementation) {
var key =
3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null;
try {
testStringCoercion(key);
var JSCompiler_inline_result = !1;
} catch (e) {
JSCompiler_inline_result = !0;
}
JSCompiler_inline_result &&
(console.error(
"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
("function" === typeof Symbol &&
Symbol.toStringTag &&
key[Symbol.toStringTag]) ||
key.constructor.name ||
"Object"
),
testStringCoercion(key));
return {
$$typeof: REACT_PORTAL_TYPE,
key: null == key ? null : "" + key,
children: children,
containerInfo: containerInfo,
implementation: implementation
};
}
function getCrossOriginStringAs(as, input) {
if ("font" === as) return "";
if ("string" === typeof input)
return "use-credentials" === input ? input : "";
}
function getValueDescriptorExpectingObjectForWarning(thing) {
return null === thing
? "`null`"
: void 0 === thing
? "`undefined`"
: "" === thing
? "an empty string"
: 'something with type "' + typeof thing + '"';
}
function getValueDescriptorExpectingEnumForWarning(thing) {
return null === thing
? "`null`"
: void 0 === thing
? "`undefined`"
: "" === thing
? "an empty string"
: "string" === typeof thing
? JSON.stringify(thing)
: "number" === typeof thing
? "`" + thing + "`"
: 'something with type "' + typeof thing + '"';
}
function resolveDispatcher() {
var dispatcher = ReactSharedInternals.H;
null === dispatcher &&
console.error(
"Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem."
);
return dispatcher;
}
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
"function" ===
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart &&
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());
var React = require("react"),
Internals = {
d: {
f: noop,
r: function () {
throw Error(
"Invalid form element. requestFormReset must be passed a form that was rendered by React."
);
},
D: noop,
C: noop,
L: noop,
m: noop,
X: noop,
S: noop,
M: noop
},
p: 0,
findDOMNode: null
},
REACT_PORTAL_TYPE = Symbol.for("react.portal"),
ReactSharedInternals =
React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;
("function" === typeof Map &&
null != Map.prototype &&
"function" === typeof Map.prototype.forEach &&
"function" === typeof Set &&
null != Set.prototype &&
"function" === typeof Set.prototype.clear &&
"function" === typeof Set.prototype.forEach) ||
console.error(
"React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills"
);
exports.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE =
Internals;
exports.createPortal = function (children, container) {
var key =
2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null;
if (
!container ||
(1 !== container.nodeType &&
9 !== container.nodeType &&
11 !== container.nodeType)
)
throw Error("Target container is not a DOM element.");
return createPortal$1(children, container, null, key);
};
exports.flushSync = function (fn) {
var previousTransition = ReactSharedInternals.T,
previousUpdatePriority = Internals.p;
try {
if (((ReactSharedInternals.T = null), (Internals.p = 2), fn))
return fn();
} finally {
(ReactSharedInternals.T = previousTransition),
(Internals.p = previousUpdatePriority),
Internals.d.f() &&
console.error(
"flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task."
);
}
};
exports.preconnect = function (href, options) {
"string" === typeof href && href
? null != options && "object" !== typeof options
? console.error(
"ReactDOM.preconnect(): Expected the `options` argument (second) to be an object but encountered %s instead. The only supported option at this time is `crossOrigin` which accepts a string.",
getValueDescriptorExpectingEnumForWarning(options)
)
: null != options &&
"string" !== typeof options.crossOrigin &&
console.error(
"ReactDOM.preconnect(): Expected the `crossOrigin` option (second argument) to be a string but encountered %s instead. Try removing this option or passing a string value instead.",
getValueDescriptorExpectingObjectForWarning(options.crossOrigin)
)
: console.error(
"ReactDOM.preconnect(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.",
getValueDescriptorExpectingObjectForWarning(href)
);
"string" === typeof href &&
(options
? ((options = options.crossOrigin),
(options =
"string" === typeof options
? "use-credentials" === options
? options
: ""
: void 0))
: (options = null),
Internals.d.C(href, options));
};
exports.prefetchDNS = function (href) {
if ("string" !== typeof href || !href)
console.error(
"ReactDOM.prefetchDNS(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.",
getValueDescriptorExpectingObjectForWarning(href)
);
else if (1 < arguments.length) {
var options = arguments[1];
"object" === typeof options && options.hasOwnProperty("crossOrigin")
? console.error(
"ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. It looks like the you are attempting to set a crossOrigin property for this DNS lookup hint. Browsers do not perform DNS queries using CORS and setting this attribute on the resource hint has no effect. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.",
getValueDescriptorExpectingEnumForWarning(options)
)
: console.error(
"ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.",
getValueDescriptorExpectingEnumForWarning(options)
);
}
"string" === typeof href && Internals.d.D(href);
};
exports.preinit = function (href, options) {
"string" === typeof href && href
? null == options || "object" !== typeof options
? console.error(
"ReactDOM.preinit(): Expected the `options` argument (second) to be an object with an `as` property describing the type of resource to be preinitialized but encountered %s instead.",
getValueDescriptorExpectingEnumForWarning(options)
)
: "style" !== options.as &&
"script" !== options.as &&
console.error(
'ReactDOM.preinit(): Expected the `as` property in the `options` argument (second) to contain a valid value describing the type of resource to be preinitialized but encountered %s instead. Valid values for `as` are "style" and "script".',
getValueDescriptorExpectingEnumForWarning(options.as)
)
: console.error(
"ReactDOM.preinit(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.",
getValueDescriptorExpectingObjectForWarning(href)
);
if (
"string" === typeof href &&
options &&
"string" === typeof options.as
) {
var as = options.as,
crossOrigin = getCrossOriginStringAs(as, options.crossOrigin),
integrity =
"string" === typeof options.integrity ? options.integrity : void 0,
fetchPriority =
"string" === typeof options.fetchPriority
? options.fetchPriority
: void 0;
"style" === as
? Internals.d.S(
href,
"string" === typeof options.precedence
? options.precedence
: void 0,
{
crossOrigin: crossOrigin,
integrity: integrity,
fetchPriority: fetchPriority
}
)
: "script" === as &&
Internals.d.X(href, {
crossOrigin: crossOrigin,
integrity: integrity,
fetchPriority: fetchPriority,
nonce: "string" === typeof options.nonce ? options.nonce : void 0
});
}
};
exports.preinitModule = function (href, options) {
var encountered = "";
("string" === typeof href && href) ||
(encountered +=
" The `href` argument encountered was " +
getValueDescriptorExpectingObjectForWarning(href) +
".");
void 0 !== options && "object" !== typeof options
? (encountered +=
" The `options` argument encountered was " +
getValueDescriptorExpectingObjectForWarning(options) +
".")
: options &&
"as" in options &&
"script" !== options.as &&
(encountered +=
" The `as` option encountered was " +
getValueDescriptorExpectingEnumForWarning(options.as) +
".");
if (encountered)
console.error(
"ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property.%s",
encountered
);
else
switch (
((encountered =
options && "string" === typeof options.as ? options.as : "script"),
encountered)
) {
case "script":
break;
default:
(encountered =
getValueDescriptorExpectingEnumForWarning(encountered)),
console.error(
'ReactDOM.preinitModule(): Currently the only supported "as" type for this function is "script" but received "%s" instead. This warning was generated for `href` "%s". In the future other module types will be supported, aligning with the import-attributes proposal. Learn more here: (https://github.com/tc39/proposal-import-attributes)',
encountered,
href
);
}
if ("string" === typeof href)
if ("object" === typeof options && null !== options) {
if (null == options.as || "script" === options.as)
(encountered = getCrossOriginStringAs(
options.as,
options.crossOrigin
)),
Internals.d.M(href, {
crossOrigin: encountered,
integrity:
"string" === typeof options.integrity
? options.integrity
: void 0,
nonce:
"string" === typeof options.nonce ? options.nonce : void 0
});
} else null == options && Internals.d.M(href);
};
exports.preload = function (href, options) {
var encountered = "";
("string" === typeof href && href) ||
(encountered +=
" The `href` argument encountered was " +
getValueDescriptorExpectingObjectForWarning(href) +
".");
null == options || "object" !== typeof options
? (encountered +=
" The `options` argument encountered was " +
getValueDescriptorExpectingObjectForWarning(options) +
".")
: ("string" === typeof options.as && options.as) ||
(encountered +=
" The `as` option encountered was " +
getValueDescriptorExpectingObjectForWarning(options.as) +
".");
encountered &&
console.error(
'ReactDOM.preload(): Expected two arguments, a non-empty `href` string and an `options` object with an `as` property valid for a `<link rel="preload" as="..." />` tag.%s',
encountered
);
if (
"string" === typeof href &&
"object" === typeof options &&
null !== options &&
"string" === typeof options.as
) {
encountered = options.as;
var crossOrigin = getCrossOriginStringAs(
encountered,
options.crossOrigin
);
Internals.d.L(href, encountered, {
crossOrigin: crossOrigin,
integrity:
"string" === typeof options.integrity ? options.integrity : void 0,
nonce: "string" === typeof options.nonce ? options.nonce : void 0,
type: "string" === typeof options.type ? options.type : void 0,
fetchPriority:
"string" === typeof options.fetchPriority
? options.fetchPriority
: void 0,
referrerPolicy:
"string" === typeof options.referrerPolicy
? options.referrerPolicy
: void 0,
imageSrcSet:
"string" === typeof options.imageSrcSet
? options.imageSrcSet
: void 0,
imageSizes:
"string" === typeof options.imageSizes
? options.imageSizes
: void 0,
media: "string" === typeof options.media ? options.media : void 0
});
}
};
exports.preloadModule = function (href, options) {
var encountered = "";
("string" === typeof href && href) ||
(encountered +=
" The `href` argument encountered was " +
getValueDescriptorExpectingObjectForWarning(href) +
".");
void 0 !== options && "object" !== typeof options
? (encountered +=
" The `options` argument encountered was " +
getValueDescriptorExpectingObjectForWarning(options) +
".")
: options &&
"as" in options &&
"string" !== typeof options.as &&
(encountered +=
" The `as` option encountered was " +
getValueDescriptorExpectingObjectForWarning(options.as) +
".");
encountered &&
console.error(
'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `<link rel="modulepreload" as="..." />` tag.%s',
encountered
);
"string" === typeof href &&
(options
? ((encountered = getCrossOriginStringAs(
options.as,
options.crossOrigin
)),
Internals.d.m(href, {
as:
"string" === typeof options.as && "script" !== options.as
? options.as
: void 0,
crossOrigin: encountered,
integrity:
"string" === typeof options.integrity
? options.integrity
: void 0
}))
: Internals.d.m(href));
};
exports.requestFormReset = function (form) {
Internals.d.r(form);
};
exports.unstable_batchedUpdates = function (fn, a) {
return fn(a);
};
exports.useFormState = function (action, initialState, permalink) {
return resolveDispatcher().useFormState(action, initialState, permalink);
};
exports.useFormStatus = function () {
return resolveDispatcher().useHostTransitionStatus();
};
exports.version = "19.1.0";
"undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ &&
"function" ===
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop &&
__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error());
})();

View File

@@ -0,0 +1,20 @@
# vite ⚡
> Next Generation Frontend Tooling
- 💡 Instant Server Start
- ⚡️ Lightning Fast HMR
- 🛠️ Rich Features
- 📦 Optimized Build
- 🔩 Universal Plugin Interface
- 🔑 Fully Typed APIs
Vite (French word for "fast", pronounced `/vit/`) is a new breed of frontend build tool that significantly improves the frontend development experience. It consists of two major parts:
- A dev server that serves your source files over [native ES modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules), with [rich built-in features](https://vite.dev/guide/features.html) and astonishingly fast [Hot Module Replacement (HMR)](https://vite.dev/guide/features.html#hot-module-replacement).
- A [build command](https://vite.dev/guide/build.html) that bundles your code with [Rollup](https://rollupjs.org), pre-configured to output highly optimized static assets for production.
In addition, Vite is highly extensible via its [Plugin API](https://vite.dev/guide/api-plugin.html) and [JavaScript API](https://vite.dev/guide/api-javascript.html) with full typing support.
[Read the Docs to Learn More](https://vite.dev).

View File

@@ -0,0 +1,84 @@
'use strict';
module.exports = function generate_not(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
$it.level++;
var $nextValid = 'valid' + $it.level;
if ((it.opts.strictKeywords ? (typeof $schema == 'object' && Object.keys($schema).length > 0) || $schema === false : it.util.schemaHasRules($schema, it.RULES.all))) {
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
out += ' var ' + ($errs) + ' = errors; ';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
$it.createErrors = false;
var $allErrorsOption;
if ($it.opts.allErrors) {
$allErrorsOption = $it.opts.allErrors;
$it.opts.allErrors = false;
}
out += ' ' + (it.validate($it)) + ' ';
$it.createErrors = true;
if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
it.compositeRule = $it.compositeRule = $wasComposite;
out += ' if (' + ($nextValid) + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = ''; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT be valid\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) {
/* istanbul ignore if */
if (it.async) {
out += ' throw new ValidationError([' + (__err) + ']); ';
} else {
out += ' validate.errors = [' + (__err) + ']; return false; ';
}
} else {
out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
if (it.opts.allErrors) {
out += ' } ';
}
} else {
out += ' var err = '; /* istanbul ignore else */
if (it.createErrors !== false) {
out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
if (it.opts.messages !== false) {
out += ' , message: \'should NOT be valid\' ';
}
if (it.opts.verbose) {
out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
}
out += ' } ';
} else {
out += ' {} ';
}
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if ($breakOnError) {
out += ' if (false) { ';
}
}
return out;
}

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"1":"A B","2":"mC","8":"K D E F"},B:{"1":"0 9 C L M G N O P Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I"},C:{"1":"0 1 2 3 4 5 6 7 8 9 J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC oC pC qC rC","8":"nC LC"},D:{"1":"0 1 2 3 4 5 6 7 8 9 J PB K D E F A B C L M G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB MC wB NC xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z AB BB CB DB EB FB GB HB IB JB KB LB MB NB OB I PC EC QC RC"},E:{"1":"J PB K D E F A B C L M G tC uC vC wC TC FC GC xC yC zC UC VC HC 0C IC WC XC YC ZC aC 1C JC bC cC dC eC fC 2C KC gC hC iC jC 3C","8":"sC SC"},F:{"1":"0 1 2 3 4 5 6 7 8 B C G N O P QB RB SB TB UB VB WB XB YB ZB aB bB cB dB eB fB gB hB iB jB kB lB mB nB oB pB qB rB sB tB uB vB wB xB yB zB 0B 1B 2B 3B 4B 5B 6B 7B 8B 9B AC BC CC DC Q H R OC S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 7C FC kC 8C GC","2":"F 4C","8":"5C 6C"},G:{"1":"E AD BD CD DD ED FD GD HD ID JD KD LD MD ND OD PD QD RD SD UC VC HC TD IC WC XC YC ZC aC UD JC bC cC dC eC fC VD KC gC hC iC jC","2":"SC 9C lC"},H:{"2":"WD"},I:{"1":"I XD bD cD","2":"LC J YD ZD aD lC"},J:{"1":"D A"},K:{"1":"B C H FC kC GC","8":"A"},L:{"1":"I"},M:{"1":"EC"},N:{"1":"A B"},O:{"1":"HC"},P:{"1":"1 2 3 4 5 6 7 8 J dD eD fD gD hD TC iD jD kD lD mD IC JC KC nD"},Q:{"1":"oD"},R:{"1":"pD"},S:{"1":"qD rD"}},B:1,C:"Web Workers",D:true};

View File

@@ -0,0 +1,238 @@
/**
* @fileoverview Rule to flag when IIFE is not wrapped in parens
* @author Ilya Volodin
* @deprecated in ESLint v8.53.0
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
const eslintUtils = require("@eslint-community/eslint-utils");
//----------------------------------------------------------------------
// Helpers
//----------------------------------------------------------------------
/**
* Check if the given node is callee of a `NewExpression` node
* @param {ASTNode} node node to check
* @returns {boolean} True if the node is callee of a `NewExpression` node
* @private
*/
function isCalleeOfNewExpression(node) {
const maybeCallee =
node.parent.type === "ChainExpression" ? node.parent : node;
return (
maybeCallee.parent.type === "NewExpression" &&
maybeCallee.parent.callee === maybeCallee
);
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
deprecated: {
message: "Formatting rules are being moved out of ESLint core.",
url: "https://eslint.org/blog/2023/10/deprecating-formatting-rules/",
deprecatedSince: "8.53.0",
availableUntil: "10.0.0",
replacedBy: [
{
message:
"ESLint Stylistic now maintains deprecated stylistic core rules.",
url: "https://eslint.style/guide/migration",
plugin: {
name: "@stylistic/eslint-plugin-js",
url: "https://eslint.style/packages/js",
},
rule: {
name: "wrap-iife",
url: "https://eslint.style/rules/js/wrap-iife",
},
},
],
},
type: "layout",
docs: {
description:
"Require parentheses around immediate `function` invocations",
recommended: false,
url: "https://eslint.org/docs/latest/rules/wrap-iife",
},
schema: [
{
enum: ["outside", "inside", "any"],
},
{
type: "object",
properties: {
functionPrototypeMethods: {
type: "boolean",
default: false,
},
},
additionalProperties: false,
},
],
fixable: "code",
messages: {
wrapInvocation:
"Wrap an immediate function invocation in parentheses.",
wrapExpression: "Wrap only the function expression in parens.",
moveInvocation:
"Move the invocation into the parens that contain the function.",
},
},
create(context) {
const style = context.options[0] || "outside";
const includeFunctionPrototypeMethods =
context.options[1] && context.options[1].functionPrototypeMethods;
const sourceCode = context.sourceCode;
/**
* Check if the node is wrapped in any (). All parens count: grouping parens and parens for constructs such as if()
* @param {ASTNode} node node to evaluate
* @returns {boolean} True if it is wrapped in any parens
* @private
*/
function isWrappedInAnyParens(node) {
return astUtils.isParenthesised(sourceCode, node);
}
/**
* Check if the node is wrapped in grouping (). Parens for constructs such as if() don't count
* @param {ASTNode} node node to evaluate
* @returns {boolean} True if it is wrapped in grouping parens
* @private
*/
function isWrappedInGroupingParens(node) {
return eslintUtils.isParenthesized(1, node, sourceCode);
}
/**
* Get the function node from an IIFE
* @param {ASTNode} node node to evaluate
* @returns {ASTNode} node that is the function expression of the given IIFE, or null if none exist
*/
function getFunctionNodeFromIIFE(node) {
const callee = astUtils.skipChainExpression(node.callee);
if (callee.type === "FunctionExpression") {
return callee;
}
if (
includeFunctionPrototypeMethods &&
callee.type === "MemberExpression" &&
callee.object.type === "FunctionExpression" &&
(astUtils.getStaticPropertyName(callee) === "call" ||
astUtils.getStaticPropertyName(callee) === "apply")
) {
return callee.object;
}
return null;
}
return {
CallExpression(node) {
const innerNode = getFunctionNodeFromIIFE(node);
if (!innerNode) {
return;
}
const isCallExpressionWrapped = isWrappedInAnyParens(node),
isFunctionExpressionWrapped =
isWrappedInAnyParens(innerNode);
if (!isCallExpressionWrapped && !isFunctionExpressionWrapped) {
context.report({
node,
messageId: "wrapInvocation",
fix(fixer) {
const nodeToSurround =
style === "inside" ? innerNode : node;
return fixer.replaceText(
nodeToSurround,
`(${sourceCode.getText(nodeToSurround)})`,
);
},
});
} else if (style === "inside" && !isFunctionExpressionWrapped) {
context.report({
node,
messageId: "wrapExpression",
fix(fixer) {
// The outer call expression will always be wrapped at this point.
if (
isWrappedInGroupingParens(node) &&
!isCalleeOfNewExpression(node)
) {
/*
* Parenthesize the function expression and remove unnecessary grouping parens around the call expression.
* Replace the range between the end of the function expression and the end of the call expression.
* for example, in `(function(foo) {}(bar))`, the range `(bar))` should get replaced with `)(bar)`.
*/
const parenAfter =
sourceCode.getTokenAfter(node);
return fixer.replaceTextRange(
[innerNode.range[1], parenAfter.range[1]],
`)${sourceCode.getText().slice(innerNode.range[1], parenAfter.range[0])}`,
);
}
/*
* Call expression is wrapped in mandatory parens such as if(), or in necessary grouping parens.
* These parens cannot be removed, so just parenthesize the function expression.
*/
return fixer.replaceText(
innerNode,
`(${sourceCode.getText(innerNode)})`,
);
},
});
} else if (style === "outside" && !isCallExpressionWrapped) {
context.report({
node,
messageId: "moveInvocation",
fix(fixer) {
/*
* The inner function expression will always be wrapped at this point.
* It's only necessary to replace the range between the end of the function expression
* and the call expression. For example, in `(function(foo) {})(bar)`, the range `)(bar)`
* should get replaced with `(bar))`.
*/
const parenAfter =
sourceCode.getTokenAfter(innerNode);
return fixer.replaceTextRange(
[parenAfter.range[0], node.range[1]],
`${sourceCode.getText().slice(parenAfter.range[1], node.range[1])})`,
);
},
});
}
},
};
},
};

View File

@@ -0,0 +1,30 @@
import postcss from './postcss.js'
export default postcss
export const stringify = postcss.stringify
export const fromJSON = postcss.fromJSON
export const plugin = postcss.plugin
export const parse = postcss.parse
export const list = postcss.list
export const document = postcss.document
export const comment = postcss.comment
export const atRule = postcss.atRule
export const rule = postcss.rule
export const decl = postcss.decl
export const root = postcss.root
export const CssSyntaxError = postcss.CssSyntaxError
export const Declaration = postcss.Declaration
export const Container = postcss.Container
export const Processor = postcss.Processor
export const Document = postcss.Document
export const Comment = postcss.Comment
export const Warning = postcss.Warning
export const AtRule = postcss.AtRule
export const Result = postcss.Result
export const Input = postcss.Input
export const Rule = postcss.Rule
export const Root = postcss.Root
export const Node = postcss.Node

View File

@@ -0,0 +1,166 @@
# lru cache
A cache object that deletes the least-recently-used items.
[![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache)
## Installation:
```javascript
npm install lru-cache --save
```
## Usage:
```javascript
var LRU = require("lru-cache")
, options = { max: 500
, length: function (n, key) { return n * 2 + key.length }
, dispose: function (key, n) { n.close() }
, maxAge: 1000 * 60 * 60 }
, cache = new LRU(options)
, otherCache = new LRU(50) // sets just the max size
cache.set("key", "value")
cache.get("key") // "value"
// non-string keys ARE fully supported
// but note that it must be THE SAME object, not
// just a JSON-equivalent object.
var someObject = { a: 1 }
cache.set(someObject, 'a value')
// Object keys are not toString()-ed
cache.set('[object Object]', 'a different value')
assert.equal(cache.get(someObject), 'a value')
// A similar object with same keys/values won't work,
// because it's a different object identity
assert.equal(cache.get({ a: 1 }), undefined)
cache.reset() // empty the cache
```
If you put more stuff in it, then items will fall out.
If you try to put an oversized thing in it, then it'll fall out right
away.
## Options
* `max` The maximum size of the cache, checked by applying the length
function to all values in the cache. Not setting this is kind of
silly, since that's the whole purpose of this lib, but it defaults
to `Infinity`. Setting it to a non-number or negative number will
throw a `TypeError`. Setting it to 0 makes it be `Infinity`.
* `maxAge` Maximum age in ms. Items are not pro-actively pruned out
as they age, but if you try to get an item that is too old, it'll
drop it and return undefined instead of giving it to you.
Setting this to a negative value will make everything seem old!
Setting it to a non-number will throw a `TypeError`.
* `length` Function that is used to calculate the length of stored
items. If you're storing strings or buffers, then you probably want
to do something like `function(n, key){return n.length}`. The default is
`function(){return 1}`, which is fine if you want to store `max`
like-sized things. The item is passed as the first argument, and
the key is passed as the second argumnet.
* `dispose` Function that is called on items when they are dropped
from the cache. This can be handy if you want to close file
descriptors or do other cleanup tasks when items are no longer
accessible. Called with `key, value`. It's called *before*
actually removing the item from the internal cache, so if you want
to immediately put it back in, you'll have to do that in a
`nextTick` or `setTimeout` callback or it won't do anything.
* `stale` By default, if you set a `maxAge`, it'll only actually pull
stale items out of the cache when you `get(key)`. (That is, it's
not pre-emptively doing a `setTimeout` or anything.) If you set
`stale:true`, it'll return the stale value before deleting it. If
you don't set this, then it'll return `undefined` when you try to
get a stale entry, as if it had already been deleted.
* `noDisposeOnSet` By default, if you set a `dispose()` method, then
it'll be called whenever a `set()` operation overwrites an existing
key. If you set this option, `dispose()` will only be called when a
key falls out of the cache, not when it is overwritten.
* `updateAgeOnGet` When using time-expiring entries with `maxAge`,
setting this to `true` will make each item's effective time update
to the current time whenever it is retrieved from cache, causing it
to not expire. (It can still fall out of cache based on recency of
use, of course.)
## API
* `set(key, value, maxAge)`
* `get(key) => value`
Both of these will update the "recently used"-ness of the key.
They do what you think. `maxAge` is optional and overrides the
cache `maxAge` option if provided.
If the key is not found, `get()` will return `undefined`.
The key and val can be any value.
* `peek(key)`
Returns the key value (or `undefined` if not found) without
updating the "recently used"-ness of the key.
(If you find yourself using this a lot, you *might* be using the
wrong sort of data structure, but there are some use cases where
it's handy.)
* `del(key)`
Deletes a key out of the cache.
* `reset()`
Clear the cache entirely, throwing away all values.
* `has(key)`
Check if a key is in the cache, without updating the recent-ness
or deleting it for being stale.
* `forEach(function(value,key,cache), [thisp])`
Just like `Array.prototype.forEach`. Iterates over all the keys
in the cache, in order of recent-ness. (Ie, more recently used
items are iterated over first.)
* `rforEach(function(value,key,cache), [thisp])`
The same as `cache.forEach(...)` but items are iterated over in
reverse order. (ie, less recently used items are iterated over
first.)
* `keys()`
Return an array of the keys in the cache.
* `values()`
Return an array of the values in the cache.
* `length`
Return total length of objects in cache taking into account
`length` options function.
* `itemCount`
Return total quantity of objects currently in cache. Note, that
`stale` (see options) items are returned as part of this item
count.
* `dump()`
Return an array of the cache entries ready for serialization and usage
with 'destinationCache.load(arr)`.
* `load(cacheEntriesArray)`
Loads another cache entries array, obtained with `sourceCache.dump()`,
into the cache. The destination cache is reset before loading new entries
* `prune()`
Manually iterates over the entire cache proactively pruning old entries

View File

@@ -0,0 +1,150 @@
/*!
* @description Recursive object extending
* @author Viacheslav Lotsmanov <lotsmanov89@gmail.com>
* @license MIT
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2018 Viacheslav Lotsmanov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
'use strict';
function isSpecificValue(val) {
return (
val instanceof Buffer
|| val instanceof Date
|| val instanceof RegExp
) ? true : false;
}
function cloneSpecificValue(val) {
if (val instanceof Buffer) {
var x = Buffer.alloc
? Buffer.alloc(val.length)
: new Buffer(val.length);
val.copy(x);
return x;
} else if (val instanceof Date) {
return new Date(val.getTime());
} else if (val instanceof RegExp) {
return new RegExp(val);
} else {
throw new Error('Unexpected situation');
}
}
/**
* Recursive cloning array.
*/
function deepCloneArray(arr) {
var clone = [];
arr.forEach(function (item, index) {
if (typeof item === 'object' && item !== null) {
if (Array.isArray(item)) {
clone[index] = deepCloneArray(item);
} else if (isSpecificValue(item)) {
clone[index] = cloneSpecificValue(item);
} else {
clone[index] = deepExtend({}, item);
}
} else {
clone[index] = item;
}
});
return clone;
}
function safeGetProperty(object, property) {
return property === '__proto__' ? undefined : object[property];
}
/**
* Extening object that entered in first argument.
*
* Returns extended object or false if have no target object or incorrect type.
*
* If you wish to clone source object (without modify it), just use empty new
* object as first argument, like this:
* deepExtend({}, yourObj_1, [yourObj_N]);
*/
var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) {
if (arguments.length < 1 || typeof arguments[0] !== 'object') {
return false;
}
if (arguments.length < 2) {
return arguments[0];
}
var target = arguments[0];
// convert arguments to array and cut off target object
var args = Array.prototype.slice.call(arguments, 1);
var val, src, clone;
args.forEach(function (obj) {
// skip argument if isn't an object, is null, or is an array
if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) {
return;
}
Object.keys(obj).forEach(function (key) {
src = safeGetProperty(target, key); // source value
val = safeGetProperty(obj, key); // new value
// recursion prevention
if (val === target) {
return;
/**
* if new value isn't object then just overwrite by new value
* instead of extending.
*/
} else if (typeof val !== 'object' || val === null) {
target[key] = val;
return;
// just clone arrays (and recursive clone objects inside)
} else if (Array.isArray(val)) {
target[key] = deepCloneArray(val);
return;
// custom cloning and overwrite for specific objects
} else if (isSpecificValue(val)) {
target[key] = cloneSpecificValue(val);
return;
// overwrite by new value if source isn't object or array
} else if (typeof src !== 'object' || src === null || Array.isArray(src)) {
target[key] = deepExtend({}, val);
return;
// source value and new value is objects both, extending...
} else {
target[key] = deepExtend(src, val);
return;
}
});
});
return target;
};

View File

@@ -0,0 +1,142 @@
export { ObjectSchema } from "@eslint/object-schema";
export type PropertyDefinition = import("@eslint/object-schema").PropertyDefinition;
export type ObjectDefinition = import("@eslint/object-schema").ObjectDefinition;
export type ConfigObject = import("./types.cts").ConfigObject;
export type IMinimatchStatic = import("minimatch").IMinimatchStatic;
export type IMinimatch = import("minimatch").IMinimatch;
export type PathImpl = typeof import("@jsr/std__path");
export type ObjectSchemaInstance = import("@eslint/object-schema").ObjectSchema;
/**
* Represents an array of config objects and provides method for working with
* those config objects.
*/
export class ConfigArray extends Array<any> {
[x: symbol]: (config: any) => any;
/**
* Creates a new instance of ConfigArray.
* @param {Iterable|Function|Object} configs An iterable yielding config
* objects, or a config function, or a config object.
* @param {Object} options The options for the ConfigArray.
* @param {string} [options.basePath="/"] The absolute path of the config file directory.
* Defaults to `"/"`.
* @param {boolean} [options.normalized=false] Flag indicating if the
* configs have already been normalized.
* @param {Object} [options.schema] The additional schema
* definitions to use for the ConfigArray schema.
* @param {Array<string>} [options.extraConfigTypes] List of config types supported.
*/
constructor(configs: Iterable<any> | Function | any, { basePath, normalized, schema: customSchema, extraConfigTypes, }?: {
basePath?: string;
normalized?: boolean;
schema?: any;
extraConfigTypes?: Array<string>;
});
/**
* The path of the config file that this array was loaded from.
* This is used to calculate filename matches.
* @property basePath
* @type {string}
*/
basePath: string;
/**
* The supported config types.
* @type {Array<string>}
*/
extraConfigTypes: Array<string>;
/**
* Returns the `files` globs from every config object in the array.
* This can be used to determine which files will be matched by a
* config array or to use as a glob pattern when no patterns are provided
* for a command line interface.
* @returns {Array<string|Function>} An array of matchers.
*/
get files(): Array<string | Function>;
/**
* Returns ignore matchers that should always be ignored regardless of
* the matching `files` fields in any configs. This is necessary to mimic
* the behavior of things like .gitignore and .eslintignore, allowing a
* globbing operation to be faster.
* @returns {string[]} An array of string patterns and functions to be ignored.
*/
get ignores(): string[];
/**
* Indicates if the config array has been normalized.
* @returns {boolean} True if the config array is normalized, false if not.
*/
isNormalized(): boolean;
/**
* Normalizes a config array by flattening embedded arrays and executing
* config functions.
* @param {Object} [context] The context object for config functions.
* @returns {Promise<ConfigArray>} The current ConfigArray instance.
*/
normalize(context?: any): Promise<ConfigArray>;
/**
* Normalizes a config array by flattening embedded arrays and executing
* config functions.
* @param {Object} [context] The context object for config functions.
* @returns {ConfigArray} The current ConfigArray instance.
*/
normalizeSync(context?: any): ConfigArray;
/**
* Returns the config object for a given file path and a status that can be used to determine why a file has no config.
* @param {string} filePath The path of a file to get a config for.
* @returns {{ config?: Object, status: "ignored"|"external"|"unconfigured"|"matched" }}
* An object with an optional property `config` and property `status`.
* `config` is the config object for the specified file as returned by {@linkcode ConfigArray.getConfig},
* `status` a is one of the constants returned by {@linkcode ConfigArray.getConfigStatus}.
*/
getConfigWithStatus(filePath: string): {
config?: any;
status: "ignored" | "external" | "unconfigured" | "matched";
};
/**
* Returns the config object for a given file path.
* @param {string} filePath The path of a file to get a config for.
* @returns {Object|undefined} The config object for this file or `undefined`.
*/
getConfig(filePath: string): any | undefined;
/**
* Determines whether a file has a config or why it doesn't.
* @param {string} filePath The path of the file to check.
* @returns {"ignored"|"external"|"unconfigured"|"matched"} One of the following values:
* * `"ignored"`: the file is ignored
* * `"external"`: the file is outside the base path
* * `"unconfigured"`: the file is not matched by any config
* * `"matched"`: the file has a matching config
*/
getConfigStatus(filePath: string): "ignored" | "external" | "unconfigured" | "matched";
/**
* Determines if the given filepath is ignored based on the configs.
* @param {string} filePath The path of a file to check.
* @returns {boolean} True if the path is ignored, false if not.
* @deprecated Use `isFileIgnored` instead.
*/
isIgnored(filePath: string): boolean;
/**
* Determines if the given filepath is ignored based on the configs.
* @param {string} filePath The path of a file to check.
* @returns {boolean} True if the path is ignored, false if not.
*/
isFileIgnored(filePath: string): boolean;
/**
* Determines if the given directory is ignored based on the configs.
* This checks only default `ignores` that don't have `files` in the
* same config. A pattern such as `/foo` be considered to ignore the directory
* while a pattern such as `/foo/**` is not considered to ignore the
* directory because it is matching files.
* @param {string} directoryPath The path of a directory to check.
* @returns {boolean} True if the directory is ignored, false if not. Will
* return true for any directory that is not inside of `basePath`.
* @throws {Error} When the `ConfigArray` is not normalized.
*/
isDirectoryIgnored(directoryPath: string): boolean;
#private;
}
export namespace ConfigArraySymbol {
let isNormalized: symbol;
let configCache: symbol;
let schema: symbol;
let finalizeConfig: symbol;
let preprocessConfig: symbol;
}

View File

@@ -0,0 +1,412 @@
const stateIndexKey = "__TSR_index";
const popStateEvent = "popstate";
const beforeUnloadEvent = "beforeunload";
function createHistory(opts) {
let location = opts.getLocation();
const subscribers = /* @__PURE__ */ new Set();
const notify = (action) => {
location = opts.getLocation();
subscribers.forEach((subscriber) => subscriber({ location, action }));
};
const handleIndexChange = (action) => {
if (opts.notifyOnIndexChange ?? true) notify(action);
else location = opts.getLocation();
};
const tryNavigation = async ({
task,
navigateOpts,
...actionInfo
}) => {
var _a, _b;
const ignoreBlocker = (navigateOpts == null ? void 0 : navigateOpts.ignoreBlocker) ?? false;
if (ignoreBlocker) {
task();
return;
}
const blockers = ((_a = opts.getBlockers) == null ? void 0 : _a.call(opts)) ?? [];
const isPushOrReplace = actionInfo.type === "PUSH" || actionInfo.type === "REPLACE";
if (typeof document !== "undefined" && blockers.length && isPushOrReplace) {
for (const blocker of blockers) {
const nextLocation = parseHref(actionInfo.path, actionInfo.state);
const isBlocked = await blocker.blockerFn({
currentLocation: location,
nextLocation,
action: actionInfo.type
});
if (isBlocked) {
(_b = opts.onBlocked) == null ? void 0 : _b.call(opts);
return;
}
}
}
task();
};
return {
get location() {
return location;
},
get length() {
return opts.getLength();
},
subscribers,
subscribe: (cb) => {
subscribers.add(cb);
return () => {
subscribers.delete(cb);
};
},
push: (path, state, navigateOpts) => {
const currentIndex = location.state[stateIndexKey];
state = assignKeyAndIndex(currentIndex + 1, state);
tryNavigation({
task: () => {
opts.pushState(path, state);
notify({ type: "PUSH" });
},
navigateOpts,
type: "PUSH",
path,
state
});
},
replace: (path, state, navigateOpts) => {
const currentIndex = location.state[stateIndexKey];
state = assignKeyAndIndex(currentIndex, state);
tryNavigation({
task: () => {
opts.replaceState(path, state);
notify({ type: "REPLACE" });
},
navigateOpts,
type: "REPLACE",
path,
state
});
},
go: (index, navigateOpts) => {
tryNavigation({
task: () => {
opts.go(index);
handleIndexChange({ type: "GO", index });
},
navigateOpts,
type: "GO"
});
},
back: (navigateOpts) => {
tryNavigation({
task: () => {
opts.back((navigateOpts == null ? void 0 : navigateOpts.ignoreBlocker) ?? false);
handleIndexChange({ type: "BACK" });
},
navigateOpts,
type: "BACK"
});
},
forward: (navigateOpts) => {
tryNavigation({
task: () => {
opts.forward((navigateOpts == null ? void 0 : navigateOpts.ignoreBlocker) ?? false);
handleIndexChange({ type: "FORWARD" });
},
navigateOpts,
type: "FORWARD"
});
},
canGoBack: () => location.state[stateIndexKey] !== 0,
createHref: (str) => opts.createHref(str),
block: (blocker) => {
var _a;
if (!opts.setBlockers) return () => {
};
const blockers = ((_a = opts.getBlockers) == null ? void 0 : _a.call(opts)) ?? [];
opts.setBlockers([...blockers, blocker]);
return () => {
var _a2, _b;
const blockers2 = ((_a2 = opts.getBlockers) == null ? void 0 : _a2.call(opts)) ?? [];
(_b = opts.setBlockers) == null ? void 0 : _b.call(opts, blockers2.filter((b) => b !== blocker));
};
},
flush: () => {
var _a;
return (_a = opts.flush) == null ? void 0 : _a.call(opts);
},
destroy: () => {
var _a;
return (_a = opts.destroy) == null ? void 0 : _a.call(opts);
},
notify
};
}
function assignKeyAndIndex(index, state) {
if (!state) {
state = {};
}
return {
...state,
key: createRandomKey(),
[stateIndexKey]: index
};
}
function createBrowserHistory(opts) {
var _a;
const win = (opts == null ? void 0 : opts.window) ?? (typeof document !== "undefined" ? window : void 0);
const originalPushState = win.history.pushState;
const originalReplaceState = win.history.replaceState;
let blockers = [];
const _getBlockers = () => blockers;
const _setBlockers = (newBlockers) => blockers = newBlockers;
const createHref = (opts == null ? void 0 : opts.createHref) ?? ((path) => path);
const parseLocation = (opts == null ? void 0 : opts.parseLocation) ?? (() => parseHref(
`${win.location.pathname}${win.location.search}${win.location.hash}`,
win.history.state
));
if (!((_a = win.history.state) == null ? void 0 : _a.key)) {
win.history.replaceState(
{
[stateIndexKey]: 0,
key: createRandomKey()
},
""
);
}
let currentLocation = parseLocation();
let rollbackLocation;
let nextPopIsGo = false;
let ignoreNextPop = false;
let skipBlockerNextPop = false;
let ignoreNextBeforeUnload = false;
const getLocation = () => currentLocation;
let next;
let scheduled;
const flush = () => {
if (!next) {
return;
}
history._ignoreSubscribers = true;
(next.isPush ? win.history.pushState : win.history.replaceState)(
next.state,
"",
next.href
);
history._ignoreSubscribers = false;
next = void 0;
scheduled = void 0;
rollbackLocation = void 0;
};
const queueHistoryAction = (type, destHref, state) => {
const href = createHref(destHref);
if (!scheduled) {
rollbackLocation = currentLocation;
}
currentLocation = parseHref(destHref, state);
next = {
href,
state,
isPush: (next == null ? void 0 : next.isPush) || type === "push"
};
if (!scheduled) {
scheduled = Promise.resolve().then(() => flush());
}
};
const onPushPop = (type) => {
currentLocation = parseLocation();
history.notify({ type });
};
const onPushPopEvent = async () => {
if (ignoreNextPop) {
ignoreNextPop = false;
return;
}
const nextLocation = parseLocation();
const delta = nextLocation.state[stateIndexKey] - currentLocation.state[stateIndexKey];
const isForward = delta === 1;
const isBack = delta === -1;
const isGo = !isForward && !isBack || nextPopIsGo;
nextPopIsGo = false;
const action = isGo ? "GO" : isBack ? "BACK" : "FORWARD";
const notify = isGo ? {
type: "GO",
index: delta
} : {
type: isBack ? "BACK" : "FORWARD"
};
if (skipBlockerNextPop) {
skipBlockerNextPop = false;
} else {
const blockers2 = _getBlockers();
if (typeof document !== "undefined" && blockers2.length) {
for (const blocker of blockers2) {
const isBlocked = await blocker.blockerFn({
currentLocation,
nextLocation,
action
});
if (isBlocked) {
ignoreNextPop = true;
win.history.go(1);
history.notify(notify);
return;
}
}
}
}
currentLocation = parseLocation();
history.notify(notify);
};
const onBeforeUnload = (e) => {
if (ignoreNextBeforeUnload) {
ignoreNextBeforeUnload = false;
return;
}
let shouldBlock = false;
const blockers2 = _getBlockers();
if (typeof document !== "undefined" && blockers2.length) {
for (const blocker of blockers2) {
const shouldHaveBeforeUnload = blocker.enableBeforeUnload ?? true;
if (shouldHaveBeforeUnload === true) {
shouldBlock = true;
break;
}
if (typeof shouldHaveBeforeUnload === "function" && shouldHaveBeforeUnload() === true) {
shouldBlock = true;
break;
}
}
}
if (shouldBlock) {
e.preventDefault();
return e.returnValue = "";
}
return;
};
const history = createHistory({
getLocation,
getLength: () => win.history.length,
pushState: (href, state) => queueHistoryAction("push", href, state),
replaceState: (href, state) => queueHistoryAction("replace", href, state),
back: (ignoreBlocker) => {
if (ignoreBlocker) skipBlockerNextPop = true;
ignoreNextBeforeUnload = true;
return win.history.back();
},
forward: (ignoreBlocker) => {
if (ignoreBlocker) skipBlockerNextPop = true;
ignoreNextBeforeUnload = true;
win.history.forward();
},
go: (n) => {
nextPopIsGo = true;
win.history.go(n);
},
createHref: (href) => createHref(href),
flush,
destroy: () => {
win.history.pushState = originalPushState;
win.history.replaceState = originalReplaceState;
win.removeEventListener(beforeUnloadEvent, onBeforeUnload, {
capture: true
});
win.removeEventListener(popStateEvent, onPushPopEvent);
},
onBlocked: () => {
if (rollbackLocation && currentLocation !== rollbackLocation) {
currentLocation = rollbackLocation;
}
},
getBlockers: _getBlockers,
setBlockers: _setBlockers,
notifyOnIndexChange: false
});
win.addEventListener(beforeUnloadEvent, onBeforeUnload, { capture: true });
win.addEventListener(popStateEvent, onPushPopEvent);
win.history.pushState = function(...args) {
const res = originalPushState.apply(win.history, args);
if (!history._ignoreSubscribers) onPushPop("PUSH");
return res;
};
win.history.replaceState = function(...args) {
const res = originalReplaceState.apply(win.history, args);
if (!history._ignoreSubscribers) onPushPop("REPLACE");
return res;
};
return history;
}
function createHashHistory(opts) {
const win = (opts == null ? void 0 : opts.window) ?? (typeof document !== "undefined" ? window : void 0);
return createBrowserHistory({
window: win,
parseLocation: () => {
const hashSplit = win.location.hash.split("#").slice(1);
const pathPart = hashSplit[0] ?? "/";
const searchPart = win.location.search;
const hashEntries = hashSplit.slice(1);
const hashPart = hashEntries.length === 0 ? "" : `#${hashEntries.join("#")}`;
const hashHref = `${pathPart}${searchPart}${hashPart}`;
return parseHref(hashHref, win.history.state);
},
createHref: (href) => `${win.location.pathname}${win.location.search}#${href}`
});
}
function createMemoryHistory(opts = {
initialEntries: ["/"]
}) {
const entries = opts.initialEntries;
let index = opts.initialIndex ? Math.min(Math.max(opts.initialIndex, 0), entries.length - 1) : entries.length - 1;
const states = entries.map(
(_entry, index2) => assignKeyAndIndex(index2, void 0)
);
const getLocation = () => parseHref(entries[index], states[index]);
return createHistory({
getLocation,
getLength: () => entries.length,
pushState: (path, state) => {
if (index < entries.length - 1) {
entries.splice(index + 1);
states.splice(index + 1);
}
states.push(state);
entries.push(path);
index = Math.max(entries.length - 1, 0);
},
replaceState: (path, state) => {
states[index] = state;
entries[index] = path;
},
back: () => {
index = Math.max(index - 1, 0);
},
forward: () => {
index = Math.min(index + 1, entries.length - 1);
},
go: (n) => {
index = Math.min(Math.max(index + n, 0), entries.length - 1);
},
createHref: (path) => path
});
}
function parseHref(href, state) {
const hashIndex = href.indexOf("#");
const searchIndex = href.indexOf("?");
return {
href,
pathname: href.substring(
0,
hashIndex > 0 ? searchIndex > 0 ? Math.min(hashIndex, searchIndex) : hashIndex : searchIndex > 0 ? searchIndex : href.length
),
hash: hashIndex > -1 ? href.substring(hashIndex) : "",
search: searchIndex > -1 ? href.slice(searchIndex, hashIndex === -1 ? void 0 : hashIndex) : "",
state: state || { [stateIndexKey]: 0, key: createRandomKey() }
};
}
function createRandomKey() {
return (Math.random() + 1).toString(36).substring(7);
}
export {
createBrowserHistory,
createHashHistory,
createHistory,
createMemoryHistory,
parseHref
};
//# sourceMappingURL=index.js.map