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,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = isValidIdentifier;
var _helperValidatorIdentifier = require("@babel/helper-validator-identifier");
function isValidIdentifier(name, reserved = true) {
if (typeof name !== "string") return false;
if (reserved) {
if ((0, _helperValidatorIdentifier.isKeyword)(name) || (0, _helperValidatorIdentifier.isStrictReservedWord)(name, true)) {
return false;
}
}
return (0, _helperValidatorIdentifier.isIdentifierName)(name);
}
//# sourceMappingURL=isValidIdentifier.js.map

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _assertThisInitialized;
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
//# sourceMappingURL=assertThisInitialized.js.map

View File

@@ -0,0 +1,100 @@
/**
* @fileoverview Rule to disallow a negated condition
* @author Alberto Rodríguez
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Disallow negated conditions",
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/no-negated-condition",
},
schema: [],
messages: {
unexpectedNegated: "Unexpected negated condition.",
},
},
create(context) {
/**
* Determines if a given node is an if-else without a condition on the else
* @param {ASTNode} node The node to check.
* @returns {boolean} True if the node has an else without an if.
* @private
*/
function hasElseWithoutCondition(node) {
return node.alternate && node.alternate.type !== "IfStatement";
}
/**
* Determines if a given node is a negated unary expression
* @param {Object} test The test object to check.
* @returns {boolean} True if the node is a negated unary expression.
* @private
*/
function isNegatedUnaryExpression(test) {
return test.type === "UnaryExpression" && test.operator === "!";
}
/**
* Determines if a given node is a negated binary expression
* @param {Test} test The test to check.
* @returns {boolean} True if the node is a negated binary expression.
* @private
*/
function isNegatedBinaryExpression(test) {
return (
test.type === "BinaryExpression" &&
(test.operator === "!=" || test.operator === "!==")
);
}
/**
* Determines if a given node has a negated if expression
* @param {ASTNode} node The node to check.
* @returns {boolean} True if the node has a negated if expression.
* @private
*/
function isNegatedIf(node) {
return (
isNegatedUnaryExpression(node.test) ||
isNegatedBinaryExpression(node.test)
);
}
return {
IfStatement(node) {
if (!hasElseWithoutCondition(node)) {
return;
}
if (isNegatedIf(node)) {
context.report({
node,
messageId: "unexpectedNegated",
});
}
},
ConditionalExpression(node) {
if (isNegatedIf(node)) {
context.report({
node,
messageId: "unexpectedNegated",
});
}
},
};
},
};

View File

@@ -0,0 +1,4 @@
import { jsx as _jsx } from "react/jsx-runtime";
export default function Message({ children, type }) {
return _jsx("div", { className: `react-pdf__message react-pdf__message--${type}`, children: children });
}

View File

@@ -0,0 +1,19 @@
# @babel/helper-plugin-utils
> General utilities for plugins to use
See our website [@babel/helper-plugin-utils](https://babeljs.io/docs/babel-helper-plugin-utils) for more information.
## Install
Using npm:
```sh
npm install --save @babel/helper-plugin-utils
```
or using yarn:
```sh
yarn add @babel/helper-plugin-utils
```

View File

@@ -0,0 +1,319 @@
/**
* @fileoverview Rule to enforce sorted `import` declarations within modules
* @author Christian Schuller
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "suggestion",
defaultOptions: [
{
allowSeparatedGroups: false,
ignoreCase: false,
ignoreDeclarationSort: false,
ignoreMemberSort: false,
memberSyntaxSortOrder: ["none", "all", "multiple", "single"],
},
],
docs: {
description: "Enforce sorted `import` declarations within modules",
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/sort-imports",
},
schema: [
{
type: "object",
properties: {
ignoreCase: {
type: "boolean",
},
memberSyntaxSortOrder: {
type: "array",
items: {
enum: ["none", "all", "multiple", "single"],
},
uniqueItems: true,
minItems: 4,
maxItems: 4,
},
ignoreDeclarationSort: {
type: "boolean",
},
ignoreMemberSort: {
type: "boolean",
},
allowSeparatedGroups: {
type: "boolean",
},
},
additionalProperties: false,
},
],
fixable: "code",
messages: {
sortImportsAlphabetically:
"Imports should be sorted alphabetically.",
sortMembersAlphabetically:
"Member '{{memberName}}' of the import declaration should be sorted alphabetically.",
unexpectedSyntaxOrder:
"Expected '{{syntaxA}}' syntax before '{{syntaxB}}' syntax.",
},
},
create(context) {
const [
{
ignoreCase,
ignoreDeclarationSort,
ignoreMemberSort,
memberSyntaxSortOrder,
allowSeparatedGroups,
},
] = context.options;
const sourceCode = context.sourceCode;
let previousDeclaration = null;
/**
* Gets the used member syntax style.
*
* import "my-module.js" --> none
* import * as myModule from "my-module.js" --> all
* import {myMember} from "my-module.js" --> single
* import {foo, bar} from "my-module.js" --> multiple
* @param {ASTNode} node the ImportDeclaration node.
* @returns {string} used member parameter style, ["all", "multiple", "single"]
*/
function usedMemberSyntax(node) {
if (node.specifiers.length === 0) {
return "none";
}
if (node.specifiers[0].type === "ImportNamespaceSpecifier") {
return "all";
}
if (node.specifiers.length === 1) {
return "single";
}
return "multiple";
}
/**
* Gets the group by member parameter index for given declaration.
* @param {ASTNode} node the ImportDeclaration node.
* @returns {number} the declaration group by member index.
*/
function getMemberParameterGroupIndex(node) {
return memberSyntaxSortOrder.indexOf(usedMemberSyntax(node));
}
/**
* Gets the local name of the first imported module.
* @param {ASTNode} node the ImportDeclaration node.
* @returns {?string} the local name of the first imported module.
*/
function getFirstLocalMemberName(node) {
if (node.specifiers[0]) {
return node.specifiers[0].local.name;
}
return null;
}
/**
* Calculates number of lines between two nodes. It is assumed that the given `left` node appears before
* the given `right` node in the source code. Lines are counted from the end of the `left` node till the
* start of the `right` node. If the given nodes are on the same line, it returns `0`, same as if they were
* on two consecutive lines.
* @param {ASTNode} left node that appears before the given `right` node.
* @param {ASTNode} right node that appears after the given `left` node.
* @returns {number} number of lines between nodes.
*/
function getNumberOfLinesBetween(left, right) {
return Math.max(right.loc.start.line - left.loc.end.line - 1, 0);
}
return {
ImportDeclaration(node) {
if (!ignoreDeclarationSort) {
if (
previousDeclaration &&
allowSeparatedGroups &&
getNumberOfLinesBetween(previousDeclaration, node) > 0
) {
// reset declaration sort
previousDeclaration = null;
}
if (previousDeclaration) {
const currentMemberSyntaxGroupIndex =
getMemberParameterGroupIndex(node),
previousMemberSyntaxGroupIndex =
getMemberParameterGroupIndex(
previousDeclaration,
);
let currentLocalMemberName =
getFirstLocalMemberName(node),
previousLocalMemberName =
getFirstLocalMemberName(previousDeclaration);
if (ignoreCase) {
previousLocalMemberName =
previousLocalMemberName &&
previousLocalMemberName.toLowerCase();
currentLocalMemberName =
currentLocalMemberName &&
currentLocalMemberName.toLowerCase();
}
/*
* When the current declaration uses a different member syntax,
* then check if the ordering is correct.
* Otherwise, make a default string compare (like rule sort-vars to be consistent) of the first used local member name.
*/
if (
currentMemberSyntaxGroupIndex !==
previousMemberSyntaxGroupIndex
) {
if (
currentMemberSyntaxGroupIndex <
previousMemberSyntaxGroupIndex
) {
context.report({
node,
messageId: "unexpectedSyntaxOrder",
data: {
syntaxA:
memberSyntaxSortOrder[
currentMemberSyntaxGroupIndex
],
syntaxB:
memberSyntaxSortOrder[
previousMemberSyntaxGroupIndex
],
},
});
}
} else {
if (
previousLocalMemberName &&
currentLocalMemberName &&
currentLocalMemberName < previousLocalMemberName
) {
context.report({
node,
messageId: "sortImportsAlphabetically",
});
}
}
}
previousDeclaration = node;
}
if (!ignoreMemberSort) {
const importSpecifiers = node.specifiers.filter(
specifier => specifier.type === "ImportSpecifier",
);
const getSortableName = ignoreCase
? specifier => specifier.local.name.toLowerCase()
: specifier => specifier.local.name;
const firstUnsortedIndex = importSpecifiers
.map(getSortableName)
.findIndex(
(name, index, array) => array[index - 1] > name,
);
if (firstUnsortedIndex !== -1) {
context.report({
node: importSpecifiers[firstUnsortedIndex],
messageId: "sortMembersAlphabetically",
data: {
memberName:
importSpecifiers[firstUnsortedIndex].local
.name,
},
fix(fixer) {
if (
importSpecifiers.some(
specifier =>
sourceCode.getCommentsBefore(
specifier,
).length ||
sourceCode.getCommentsAfter(
specifier,
).length,
)
) {
// If there are comments in the ImportSpecifier list, don't rearrange the specifiers.
return null;
}
return fixer.replaceTextRange(
[
importSpecifiers[0].range[0],
importSpecifiers.at(-1).range[1],
],
importSpecifiers
// Clone the importSpecifiers array to avoid mutating it
.slice()
// Sort the array into the desired order
.sort((specifierA, specifierB) => {
const aName =
getSortableName(specifierA);
const bName =
getSortableName(specifierB);
return aName > bName ? 1 : -1;
})
// Build a string out of the sorted list of import specifiers and the text between the originals
.reduce(
(sourceText, specifier, index) => {
const textAfterSpecifier =
index ===
importSpecifiers.length - 1
? ""
: sourceCode
.getText()
.slice(
importSpecifiers[
index
].range[1],
importSpecifiers[
index +
1
].range[0],
);
return (
sourceText +
sourceCode.getText(
specifier,
) +
textAfterSpecifier
);
},
"",
),
);
},
});
}
}
},
};
},
};

View File

@@ -0,0 +1 @@
{"version":3,"names":["_shallowEqual","require","_isType","_isPlaceholderType","_index","is","type","node","opts","matches","isType","FLIPPED_ALIAS_KEYS","isPlaceholderType","expectedNode","undefined","shallowEqual"],"sources":["../../src/validators/is.ts"],"sourcesContent":["import shallowEqual from \"../utils/shallowEqual.ts\";\nimport isType from \"./isType.ts\";\nimport isPlaceholderType from \"./isPlaceholderType.ts\";\nimport { FLIPPED_ALIAS_KEYS } from \"../definitions/index.ts\";\nimport type * as t from \"../index.ts\";\n\nexport default function is<T extends t.Node[\"type\"]>(\n type: T,\n node: t.Node | null | undefined,\n opts?: undefined,\n): node is Extract<t.Node, { type: T }>;\n\nexport default function is<\n T extends t.Node[\"type\"],\n P extends Extract<t.Node, { type: T }>,\n>(type: T, n: t.Node | null | undefined, required: Partial<P>): n is P;\n\nexport default function is<P extends t.Node>(\n type: string,\n node: t.Node | null | undefined,\n opts: Partial<P>,\n): node is P;\n\nexport default function is(\n type: string,\n node: t.Node | null | undefined,\n opts?: Partial<t.Node>,\n): node is t.Node;\n/**\n * Returns whether `node` is of given `type`.\n *\n * For better performance, use this instead of `is[Type]` when `type` is unknown.\n */\nexport default function is(\n type: string,\n node: t.Node | null | undefined,\n opts?: Partial<t.Node>,\n): node is t.Node {\n if (!node) return false;\n\n const matches = isType(node.type, type);\n if (!matches) {\n if (!opts && node.type === \"Placeholder\" && type in FLIPPED_ALIAS_KEYS) {\n // We can only return true if the placeholder doesn't replace a real node,\n // but it replaces a category of nodes (an alias).\n //\n // t.is(\"Identifier\", node) gives some guarantees about node's shape, so we\n // can't say that Placeholder(expectedNode: \"Identifier\") is an identifier\n // because it doesn't have the same properties.\n // On the other hand, t.is(\"Expression\", node) doesn't say anything about\n // the shape of node because Expression can be many different nodes: we can,\n // and should, safely report expression placeholders as Expressions.\n return isPlaceholderType(node.expectedNode, type);\n }\n return false;\n }\n\n if (opts === undefined) {\n return true;\n } else {\n return shallowEqual(node, opts);\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,aAAA,GAAAC,OAAA;AACA,IAAAC,OAAA,GAAAD,OAAA;AACA,IAAAE,kBAAA,GAAAF,OAAA;AACA,IAAAG,MAAA,GAAAH,OAAA;AA8Be,SAASI,EAAEA,CACxBC,IAAY,EACZC,IAA+B,EAC/BC,IAAsB,EACN;EAChB,IAAI,CAACD,IAAI,EAAE,OAAO,KAAK;EAEvB,MAAME,OAAO,GAAG,IAAAC,eAAM,EAACH,IAAI,CAACD,IAAI,EAAEA,IAAI,CAAC;EACvC,IAAI,CAACG,OAAO,EAAE;IACZ,IAAI,CAACD,IAAI,IAAID,IAAI,CAACD,IAAI,KAAK,aAAa,IAAIA,IAAI,IAAIK,yBAAkB,EAAE;MAUtE,OAAO,IAAAC,0BAAiB,EAACL,IAAI,CAACM,YAAY,EAAEP,IAAI,CAAC;IACnD;IACA,OAAO,KAAK;EACd;EAEA,IAAIE,IAAI,KAAKM,SAAS,EAAE;IACtB,OAAO,IAAI;EACb,CAAC,MAAM;IACL,OAAO,IAAAC,qBAAY,EAACR,IAAI,EAAEC,IAAI,CAAC;EACjC;AACF","ignoreList":[]}

View File

@@ -0,0 +1,128 @@
import { beforeAll, describe, expect, it, vi } from 'vitest';
import { fireEvent, getAllByRole, render, screen } from '@testing-library/react';
import { pdfjs } from './index.test.js';
import OutlineItem from './OutlineItem.js';
import { loadPDF, makeAsyncCallback } from '../../../test-utils.js';
import DocumentContext from './DocumentContext.js';
import OutlineContext from './OutlineContext.js';
import type { PDFDocumentProxy } from 'pdfjs-dist';
import type { DocumentContextType, OutlineContextType } from './shared/types.js';
const pdfFile = loadPDF('./../../__mocks__/_pdf.pdf');
type PDFOutline = Awaited<ReturnType<PDFDocumentProxy['getOutline']>>;
type PDFOutlineItem = PDFOutline[number];
function renderWithContext(
children: React.ReactNode,
documentContext: Partial<DocumentContextType>,
outlineContext: Partial<OutlineContextType>,
) {
const { rerender, ...otherResult } = render(
<DocumentContext.Provider value={documentContext as DocumentContextType}>
<OutlineContext.Provider value={outlineContext as OutlineContextType}>
{children}
</OutlineContext.Provider>
</DocumentContext.Provider>,
);
return {
...otherResult,
rerender: (
nextChildren: React.ReactNode,
nextDocumentContext: Partial<DocumentContextType> = documentContext,
nextOutlineContext: Partial<OutlineContextType> = outlineContext,
) =>
rerender(
<DocumentContext.Provider value={nextDocumentContext as DocumentContextType}>
<OutlineContext.Provider value={nextOutlineContext as OutlineContextType}>
{nextChildren}
</OutlineContext.Provider>
</DocumentContext.Provider>,
),
};
}
describe('OutlineItem', () => {
// Loaded PDF file
let pdf: PDFDocumentProxy;
// Object with basic loaded outline item information
let outlineItem: PDFOutlineItem;
beforeAll(async () => {
pdf = await pdfjs.getDocument({ data: pdfFile.arrayBuffer }).promise;
const outlineItems = await pdf.getOutline();
[outlineItem] = outlineItems as [PDFOutlineItem];
});
describe('rendering', () => {
it('renders an item properly', () => {
const onItemClick = vi.fn();
renderWithContext(<OutlineItem item={outlineItem} />, { pdf }, { onItemClick });
const item = screen.getAllByRole('listitem')[0];
expect(item).toHaveTextContent(outlineItem.title);
});
it("renders item's subitems properly", () => {
const onItemClick = vi.fn();
renderWithContext(<OutlineItem item={outlineItem} />, { pdf }, { onItemClick });
const item = screen.getAllByRole('listitem')[0] as HTMLElement;
const subitems = getAllByRole(item, 'listitem');
expect(subitems).toHaveLength(outlineItem.items.length);
});
it('calls onItemClick with proper arguments when clicked a link', async () => {
const { func: onItemClick, promise: onItemClickPromise } = makeAsyncCallback();
renderWithContext(<OutlineItem item={outlineItem} />, { pdf }, { onItemClick });
const item = screen.getAllByRole('listitem')[0] as HTMLElement;
const link = getAllByRole(item, 'link')[0] as HTMLAnchorElement;
fireEvent.click(link);
await onItemClickPromise;
expect(onItemClick).toHaveBeenCalled();
});
it('calls onItemClick with proper arguments multiple times when clicked a link multiple times', async () => {
const { func: onItemClick, promise: onItemClickPromise } = makeAsyncCallback();
const { rerender } = renderWithContext(
<OutlineItem item={outlineItem} />,
{ pdf },
{ onItemClick },
);
const item = screen.getAllByRole('listitem')[0] as HTMLElement;
const link = getAllByRole(item, 'link')[0] as HTMLAnchorElement;
fireEvent.click(link);
await onItemClickPromise;
expect(onItemClick).toHaveBeenCalledTimes(1);
const { func: onItemClick2, promise: onItemClickPromise2 } = makeAsyncCallback();
rerender(<OutlineItem item={outlineItem} />, { pdf }, { onItemClick: onItemClick2 });
fireEvent.click(link);
await onItemClickPromise2;
expect(onItemClick2).toHaveBeenCalledTimes(1);
});
});
});

View File

@@ -0,0 +1 @@
{"version":3,"file":"useSearch.js","sources":["../../src/useSearch.tsx"],"sourcesContent":["import { useMatch } from './useMatch'\nimport type {\n StructuralSharingOption,\n ValidateSelected,\n} from './structuralSharing'\nimport type {\n AnyRouter,\n RegisteredRouter,\n ResolveUseSearch,\n StrictOrFrom,\n ThrowConstraint,\n ThrowOrOptional,\n UseSearchResult,\n} from '@tanstack/router-core'\n\nexport interface UseSearchBaseOptions<\n TRouter extends AnyRouter,\n TFrom,\n TStrict extends boolean,\n TThrow extends boolean,\n TSelected,\n TStructuralSharing,\n> {\n select?: (\n state: ResolveUseSearch<TRouter, TFrom, TStrict>,\n ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>\n shouldThrow?: TThrow\n}\n\nexport type UseSearchOptions<\n TRouter extends AnyRouter,\n TFrom,\n TStrict extends boolean,\n TThrow extends boolean,\n TSelected,\n TStructuralSharing,\n> = StrictOrFrom<TRouter, TFrom, TStrict> &\n UseSearchBaseOptions<\n TRouter,\n TFrom,\n TStrict,\n TThrow,\n TSelected,\n TStructuralSharing\n > &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>\n\nexport type UseSearchRoute<out TFrom> = <\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseSearchBaseOptions<\n TRouter,\n TFrom,\n /* TStrict */ true,\n /* TThrow */ true,\n TSelected,\n TStructuralSharing\n > &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n) => UseSearchResult<TRouter, TFrom, true, TSelected>\n\nexport function useSearch<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string | undefined = undefined,\n TStrict extends boolean = true,\n TThrow extends boolean = true,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts: UseSearchOptions<\n TRouter,\n TFrom,\n TStrict,\n ThrowConstraint<TStrict, TThrow>,\n TSelected,\n TStructuralSharing\n >,\n): ThrowOrOptional<\n UseSearchResult<TRouter, TFrom, TStrict, TSelected>,\n TThrow\n> {\n return useMatch({\n from: opts.from!,\n strict: opts.strict,\n shouldThrow: opts.shouldThrow,\n structuralSharing: opts.structuralSharing,\n select: (match: any) => {\n return opts.select ? opts.select(match.search) : match.search\n },\n }) as any\n}\n"],"names":[],"mappings":";AA+DO,SAAS,UAQd,MAWA;AACA,SAAO,SAAS;AAAA,IACd,MAAM,KAAK;AAAA,IACX,QAAQ,KAAK;AAAA,IACb,aAAa,KAAK;AAAA,IAClB,mBAAmB,KAAK;AAAA,IACxB,QAAQ,CAAC,UAAe;AACtB,aAAO,KAAK,SAAS,KAAK,OAAO,MAAM,MAAM,IAAI,MAAM;AAAA,IAAA;AAAA,EACzD,CACD;AACH;"}

View File

@@ -0,0 +1 @@
module.exports={C:{"52":0.08609,"55":0.00662,"56":0.01324,"68":0.00662,"72":0.00662,"78":0.00662,"84":0.00662,"98":0.01324,"102":0.00662,"103":0.00662,"105":0.00662,"106":0.01324,"107":0.01324,"108":0.01324,"109":0.00662,"110":0.01324,"111":0.00662,"113":0.01987,"115":0.86748,"120":0.00662,"122":0.00662,"123":0.01324,"125":0.01987,"126":0.00662,"127":0.00662,"128":0.10595,"129":0.00662,"130":0.01987,"131":0.02649,"132":0.00662,"133":0.03311,"134":0.03973,"135":0.37083,"136":1.85416,"137":0.00662,_:"2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 53 54 57 58 59 60 61 62 63 64 65 66 67 69 70 71 73 74 75 76 77 79 80 81 82 83 85 86 87 88 89 90 91 92 93 94 95 96 97 99 100 101 104 112 114 116 117 118 119 121 124 138 139 140 3.5 3.6"},D:{"26":0.00662,"39":0.00662,"40":0.00662,"41":0.00662,"42":0.00662,"43":0.00662,"44":0.00662,"45":0.00662,"46":0.00662,"47":0.00662,"48":0.00662,"49":0.0596,"50":0.00662,"51":0.00662,"52":0.00662,"53":0.00662,"54":0.00662,"55":0.00662,"56":0.00662,"57":0.00662,"58":0.00662,"59":0.00662,"60":0.00662,"61":0.01324,"67":0.00662,"70":0.01324,"71":0.01324,"79":0.02649,"80":0.01987,"81":0.00662,"83":0.00662,"84":0.00662,"85":0.01987,"86":0.01324,"87":0.01324,"88":0.00662,"89":0.00662,"90":0.01324,"92":0.00662,"93":0.00662,"94":0.01324,"95":0.00662,"96":0.00662,"97":0.04635,"98":0.00662,"99":0.00662,"100":0.00662,"101":0.01324,"102":0.02649,"103":0.03311,"104":0.25164,"105":0.03311,"106":0.10595,"107":0.12582,"108":0.17217,"109":3.5229,"110":0.08609,"111":0.07946,"112":0.09271,"113":0.00662,"114":0.01324,"115":0.00662,"116":0.08609,"117":0.00662,"118":0.09271,"119":0.02649,"120":0.04635,"121":0.08609,"122":0.09271,"123":0.15893,"124":0.10595,"125":0.1192,"126":0.07284,"127":0.25164,"128":0.86086,"129":0.06622,"130":0.09933,"131":0.46354,"132":0.62909,"133":8.30399,"134":20.14412,"135":0.01987,"136":0.01324,_:"4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 33 34 35 36 37 38 62 63 64 65 66 68 69 72 73 74 75 76 77 78 91 137 138"},F:{"36":0.01987,"76":0.00662,"77":0.00662,"79":0.02649,"83":0.01324,"84":0.02649,"85":0.03311,"86":0.05298,"87":0.07946,"88":0.04635,"89":0.00662,"92":0.00662,"93":0.00662,"94":0.00662,"95":0.81451,"98":0.00662,"99":0.00662,"106":0.01324,"108":0.00662,"114":0.01324,"115":0.00662,"116":0.46354,"117":3.87387,_:"9 11 12 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 60 62 63 64 65 66 67 68 69 70 71 72 73 74 75 78 80 81 82 90 91 96 97 100 101 102 103 104 105 107 109 110 111 112 113 9.5-9.6 10.0-10.1 10.5 10.6 11.1 11.5 11.6 12.1"},B:{"18":0.00662,"92":0.01324,"102":0.00662,"103":0.00662,"106":0.00662,"107":0.02649,"108":0.01987,"109":0.04635,"110":0.01324,"111":0.00662,"114":0.01324,"116":0.00662,"122":0.00662,"126":0.00662,"128":0.00662,"130":0.01987,"131":0.02649,"132":0.03973,"133":3.19843,"134":10.2641,_:"12 13 14 15 16 17 79 80 81 83 84 85 86 87 88 89 90 91 93 94 95 96 97 98 99 100 101 104 105 112 113 115 117 118 119 120 121 123 124 125 127 129"},E:{"14":0.00662,_:"0 4 5 6 7 8 9 10 11 12 13 15 3.1 3.2 6.1 7.1 9.1 10.1 11.1 15.4 15.5","5.1":0.02649,"12.1":0.00662,"13.1":0.01987,"14.1":0.02649,"15.1":0.00662,"15.2-15.3":0.00662,"15.6":0.07284,"16.0":0.00662,"16.1":0.01324,"16.2":0.00662,"16.3":0.01987,"16.4":0.00662,"16.5":0.01987,"16.6":0.09271,"17.0":0.01324,"17.1":0.04635,"17.2":0.01324,"17.3":0.02649,"17.4":0.03973,"17.5":0.06622,"17.6":0.15231,"18.0":0.03311,"18.1":0.06622,"18.2":0.03311,"18.3":0.7218,"18.4":0.01324},G:{"8":0,"3.2":0,"4.0-4.1":0,"4.2-4.3":0.00171,"5.0-5.1":0,"6.0-6.1":0.00513,"7.0-7.1":0.00342,"8.1-8.4":0,"9.0-9.2":0.00256,"9.3":0.01196,"10.0-10.2":0.00085,"10.3":0.01965,"11.0-11.2":0.09056,"11.3-11.4":0.00598,"12.0-12.1":0.00342,"12.2-12.5":0.08458,"13.0-13.1":0.00171,"13.2":0.00256,"13.3":0.00342,"13.4-13.7":0.01196,"14.0-14.4":0.0299,"14.5-14.8":0.03588,"15.0-15.1":0.01965,"15.2-15.3":0.01965,"15.4":0.02392,"15.5":0.02734,"15.6-15.8":0.33659,"16.0":0.04784,"16.1":0.09824,"16.2":0.05126,"16.3":0.08885,"16.4":0.01965,"16.5":0.03673,"16.6-16.7":0.39896,"17.0":0.02392,"17.1":0.04271,"17.2":0.03246,"17.3":0.04528,"17.4":0.09056,"17.5":0.20161,"17.6-17.7":0.58519,"18.0":0.16402,"18.1":0.5365,"18.2":0.24006,"18.3":5.01728,"18.4":0.07432},P:{"4":0.0215,"20":0.01075,"21":0.01075,"22":0.01075,"23":0.01075,"24":0.03225,"25":0.01075,"26":0.04301,"27":0.80636,_:"5.0-5.4 6.2-6.4 8.2 9.2 10.1 11.1-11.2 12.0 13.0 14.0 15.0 16.0 19.0","7.2-7.4":0.0215,"17.0":0.01075,"18.0":0.01075},I:{"0":0.02023,"3":0,"4":0,"2.1":0,"2.2":0,"2.3":0,"4.1":0,"4.2-4.3":0.00001,"4.4":0,"4.4.3-4.4.4":0.00002},K:{"0":0.94922,_:"10 11 12 11.1 11.5 12.1"},A:{"8":0.00828,"11":0.09105,_:"6 7 9 10 5.5"},S:{_:"2.5 3.0-3.1"},J:{_:"7 10"},N:{_:"10 11"},R:{_:"0"},M:{"0":0.12836},Q:{"14.9":0.01013},O:{"0":0.07094},H:{"0":0},L:{"0":23.20392}};

View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = inherit;
function inherit(key, child, parent) {
if (child && parent) {
child[key] = Array.from(new Set([].concat(child[key], parent[key]).filter(Boolean)));
}
}
//# sourceMappingURL=inherit.js.map

View File

@@ -0,0 +1,20 @@
var Ajv = require('ajv');
var ajv = new Ajv({allErrors: true});
var schema = {
"properties": {
"foo": { "type": "string" },
"bar": { "type": "number", "maximum": 3 }
}
};
var validate = ajv.compile(schema);
test({"foo": "abc", "bar": 2});
test({"foo": 2, "bar": 4});
function test(data) {
var valid = validate(data);
if (valid) console.log('Valid!');
else console.log('Invalid: ' + ajv.errorsText(validate.errors));
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"ScrollRestoration.js","sources":["../../src/ScrollRestoration.tsx"],"sourcesContent":["import {\n defaultGetScrollRestorationKey,\n getCssSelector,\n scrollRestorationCache,\n setupScrollRestoration,\n} from '@tanstack/router-core'\nimport { useRouter } from './useRouter'\nimport type {\n ParsedLocation,\n ScrollRestorationEntry,\n ScrollRestorationOptions,\n} from '@tanstack/router-core'\n\nfunction useScrollRestoration() {\n const router = useRouter()\n setupScrollRestoration(router, true)\n}\n\n/**\n * @deprecated use createRouter's `scrollRestoration` option instead\n */\nexport function ScrollRestoration(_props: ScrollRestorationOptions) {\n useScrollRestoration()\n\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n \"The ScrollRestoration component is deprecated. Use createRouter's `scrollRestoration` option instead.\",\n )\n }\n\n return null\n}\n\nexport function useElementScrollRestoration(\n options: (\n | {\n id: string\n getElement?: () => Window | Element | undefined | null\n }\n | {\n id?: string\n getElement: () => Window | Element | undefined | null\n }\n ) & {\n getKey?: (location: ParsedLocation) => string\n },\n): ScrollRestorationEntry | undefined {\n useScrollRestoration()\n\n const router = useRouter()\n const getKey = options.getKey || defaultGetScrollRestorationKey\n\n let elementSelector = ''\n\n if (options.id) {\n elementSelector = `[data-scroll-restoration-id=\"${options.id}\"]`\n } else {\n const element = options.getElement?.()\n if (!element) {\n return\n }\n elementSelector =\n element instanceof Window ? 'window' : getCssSelector(element)\n }\n\n const restoreKey = getKey(router.latestLocation)\n const byKey = scrollRestorationCache.state[restoreKey]\n return byKey?.[elementSelector]\n}\n"],"names":[],"mappings":";;AAaA,SAAS,uBAAuB;AAC9B,QAAM,SAAS,UAAU;AACzB,yBAAuB,QAAQ,IAAI;AACrC;AAKO,SAAS,kBAAkB,QAAkC;AAC7C,uBAAA;AAEjB,MAAA,QAAQ,IAAI,aAAa,eAAe;AAClC,YAAA;AAAA,MACN;AAAA,IACF;AAAA,EAAA;AAGK,SAAA;AACT;AAEO,SAAS,4BACd,SAYoC;;AACf,uBAAA;AAErB,QAAM,SAAS,UAAU;AACnB,QAAA,SAAS,QAAQ,UAAU;AAEjC,MAAI,kBAAkB;AAEtB,MAAI,QAAQ,IAAI;AACI,sBAAA,gCAAgC,QAAQ,EAAE;AAAA,EAAA,OACvD;AACC,UAAA,WAAU,aAAQ,eAAR;AAChB,QAAI,CAAC,SAAS;AACZ;AAAA,IAAA;AAEF,sBACE,mBAAmB,SAAS,WAAW,eAAe,OAAO;AAAA,EAAA;AAG3D,QAAA,aAAa,OAAO,OAAO,cAAc;AACzC,QAAA,QAAQ,uBAAuB,MAAM,UAAU;AACrD,SAAO,+BAAQ;AACjB;"}

View File

@@ -0,0 +1,63 @@
/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-ignore `sass` may not be installed
import type DartSass from 'sass'
// @ts-ignore `sass-embedded` may not be installed
import type SassEmbedded from 'sass-embedded'
// @ts-ignore `less` may not be installed
import type Less from 'less'
// @ts-ignore `stylus` may not be installed
import type Stylus from 'stylus'
/* eslint-enable @typescript-eslint/ban-ts-comment */
// https://github.com/type-challenges/type-challenges/issues/29285
type IsAny<T> = boolean extends (T extends never ? true : false) ? true : false
type DartSassLegacyStringOptionsAsync = DartSass.LegacyStringOptions<'async'>
type SassEmbeddedLegacyStringOptionsAsync =
SassEmbedded.LegacyStringOptions<'async'>
type SassLegacyStringOptionsAsync =
IsAny<DartSassLegacyStringOptionsAsync> extends false
? DartSassLegacyStringOptionsAsync
: SassEmbeddedLegacyStringOptionsAsync
export type SassLegacyPreprocessBaseOptions = Omit<
SassLegacyStringOptionsAsync,
| 'data'
| 'file'
| 'outFile'
| 'sourceMap'
| 'omitSourceMapUrl'
| 'sourceMapEmbed'
| 'sourceMapRoot'
>
type DartSassStringOptionsAsync = DartSass.StringOptions<'async'>
type SassEmbeddedStringOptionsAsync = SassEmbedded.StringOptions<'async'>
type SassStringOptionsAsync =
IsAny<DartSassStringOptionsAsync> extends false
? DartSassStringOptionsAsync
: SassEmbeddedStringOptionsAsync
export type SassModernPreprocessBaseOptions = Omit<
SassStringOptionsAsync,
'url' | 'sourceMap'
>
export type LessPreprocessorBaseOptions = Omit<
Less.Options,
'sourceMap' | 'filename'
>
export type StylusPreprocessorBaseOptions = Omit<
Stylus.RenderOptions,
'filename'
> & { define?: Record<string, any> }
declare global {
// LESS' types somewhat references this which doesn't make sense in Node,
// so we have to shim it
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
interface HTMLLinkElement {}
}

View File

@@ -0,0 +1,269 @@
/**
* @fileoverview Define common types for input completion.
* @author Toru Nagashima <https://github.com/mysticatea>
*/
"use strict";
/** @type {any} */
module.exports = {};
/** @typedef {boolean | "off" | "readable" | "readonly" | "writable" | "writeable"} GlobalConf */
/** @typedef {0 | 1 | 2 | "off" | "warn" | "error"} SeverityConf */
/** @typedef {SeverityConf | [SeverityConf, ...any[]]} RuleConf */
/**
* @typedef {Object} EcmaFeatures
* @property {boolean} [globalReturn] Enabling `return` statements at the top-level.
* @property {boolean} [jsx] Enabling JSX syntax.
* @property {boolean} [impliedStrict] Enabling strict mode always.
*/
/**
* @typedef {Object} ParserOptions
* @property {EcmaFeatures} [ecmaFeatures] The optional features.
* @property {3|5|6|7|8|9|10|11|12|13|14|15|16|2015|2016|2017|2018|2019|2020|2021|2022|2023|2024|2025} [ecmaVersion] The ECMAScript version (or revision number).
* @property {"script"|"module"} [sourceType] The source code type.
* @property {boolean} [allowReserved] Allowing the use of reserved words as identifiers in ES3.
*/
/**
* @typedef {Object} LanguageOptions
* @property {number|"latest"} [ecmaVersion] The ECMAScript version (or revision number).
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {"script"|"module"|"commonjs"} [sourceType] The source code type.
* @property {string|Object} [parser] The parser to use.
* @property {Object} [parserOptions] The parser options to use.
*/
/**
* @typedef {Object} ConfigData
* @property {Record<string, boolean>} [env] The environment settings.
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {string | string[]} [ignorePatterns] The glob patterns that ignore to lint.
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
* @property {OverrideConfigData[]} [overrides] The override settings per kind of files.
* @property {string} [parser] The path to a parser or the package name of a parser.
* @property {ParserOptions} [parserOptions] The parser options.
* @property {string[]} [plugins] The plugin specifiers.
* @property {string} [processor] The processor specifier.
* @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments.
* @property {boolean} [root] The root flag.
* @property {Record<string, RuleConf>} [rules] The rule settings.
* @property {Object} [settings] The shared settings.
*/
/**
* @typedef {Object} OverrideConfigData
* @property {Record<string, boolean>} [env] The environment settings.
* @property {string | string[]} [excludedFiles] The glob patterns for excluded files.
* @property {string | string[]} [extends] The path to other config files or the package name of shareable configs.
* @property {string | string[]} files The glob patterns for target files.
* @property {Record<string, GlobalConf>} [globals] The global variable settings.
* @property {boolean} [noInlineConfig] The flag that disables directive comments.
* @property {OverrideConfigData[]} [overrides] The override settings per kind of files.
* @property {string} [parser] The path to a parser or the package name of a parser.
* @property {ParserOptions} [parserOptions] The parser options.
* @property {string[]} [plugins] The plugin specifiers.
* @property {string} [processor] The processor specifier.
* @property {boolean} [reportUnusedDisableDirectives] The flag to report unused `eslint-disable` comments.
* @property {Record<string, RuleConf>} [rules] The rule settings.
* @property {Object} [settings] The shared settings.
*/
/**
* @typedef {Object} ParseResult
* @property {Object} ast The AST.
* @property {ScopeManager} [scopeManager] The scope manager of the AST.
* @property {Record<string, any>} [services] The services that the parser provides.
* @property {Record<string, string[]>} [visitorKeys] The visitor keys of the AST.
*/
/**
* @typedef {Object} Parser
* @property {(text:string, options:ParserOptions) => Object} parse The definition of global variables.
* @property {(text:string, options:ParserOptions) => ParseResult} [parseForESLint] The parser options that will be enabled under this environment.
*/
/**
* @typedef {Object} Environment
* @property {Record<string, GlobalConf>} [globals] The definition of global variables.
* @property {ParserOptions} [parserOptions] The parser options that will be enabled under this environment.
*/
/**
* @typedef {Object} LintMessage
* @property {number|undefined} column The 1-based column number.
* @property {number} [endColumn] The 1-based column number of the end location.
* @property {number} [endLine] The 1-based line number of the end location.
* @property {boolean} [fatal] If `true` then this is a fatal error.
* @property {{range:[number,number], text:string}} [fix] Information for autofix.
* @property {number|undefined} line The 1-based line number.
* @property {string} message The error message.
* @property {string} [messageId] The ID of the message in the rule's meta.
* @property {(string|null)} nodeType Type of node
* @property {string|null} ruleId The ID of the rule which makes this message.
* @property {0|1|2} severity The severity of this message.
* @property {Array<{desc?: string, messageId?: string, fix: {range: [number, number], text: string}}>} [suggestions] Information for suggestions.
*/
/**
* @typedef {Object} SuppressedLintMessage
* @property {number|undefined} column The 1-based column number.
* @property {number} [endColumn] The 1-based column number of the end location.
* @property {number} [endLine] The 1-based line number of the end location.
* @property {boolean} [fatal] If `true` then this is a fatal error.
* @property {{range:[number,number], text:string}} [fix] Information for autofix.
* @property {number|undefined} line The 1-based line number.
* @property {string} message The error message.
* @property {string} [messageId] The ID of the message in the rule's meta.
* @property {(string|null)} nodeType Type of node
* @property {string|null} ruleId The ID of the rule which makes this message.
* @property {0|1|2} severity The severity of this message.
* @property {Array<{kind: string, justification: string}>} suppressions The suppression info.
* @property {Array<{desc?: string, messageId?: string, fix: {range: [number, number], text: string}}>} [suggestions] Information for suggestions.
*/
/**
* @typedef {Object} SuggestionResult
* @property {string} desc A short description.
* @property {string} [messageId] Id referencing a message for the description.
* @property {{ text: string, range: number[] }} fix fix result info
*/
/**
* @typedef {Object} Processor
* @property {(text:string, filename:string) => Array<string | { text:string, filename:string }>} [preprocess] The function to extract code blocks.
* @property {(messagesList:LintMessage[][], filename:string) => LintMessage[]} [postprocess] The function to merge messages.
* @property {boolean} [supportsAutofix] If `true` then it means the processor supports autofix.
*/
/**
* @typedef {Object} RuleMetaDocs
* @property {string} description The description of the rule.
* @property {boolean} recommended If `true` then the rule is included in `eslint:recommended` preset.
* @property {string} url The URL of the rule documentation.
*/
/**
* @typedef {Object} DeprecatedInfo
* @property {string} [message] General message presented to the user
* @property {string} [url] URL to more information about this deprecation in general
* @property {ReplacedByInfo[]} [replacedBy] Potential replacements for the rule
* @property {string} [deprecatedSince] Version since the rule is deprecated
* @property {?string} [availableUntil] Version until it is available or null if indefinite
*/
/**
* @typedef {Object} ReplacedByInfo
* @property {string} [message] General message presented to the user
* @property {string} [url] URL to more information about this replacement in general
* @property {{ name?: string, url?: string }} [plugin] Use "eslint" for a core rule. Omit if the rule is in the same plugin.
* @property {{ name?: string, url?: string }} [rule] Name and information of the replacement rule
*/
/**
* @typedef {Object} RuleMeta
* @property {boolean|DeprecatedInfo} [deprecated] If `true` then the rule has been deprecated.
* @property {Array} [defaultOptions] Default options for the rule.
* @property {RuleMetaDocs} docs The document information of the rule.
* @property {"code"|"whitespace"} [fixable] The autofix type.
* @property {boolean} [hasSuggestions] If `true` then the rule provides suggestions.
* @property {Record<string,string>} [messages] The messages the rule reports.
* @property {string[]} [replacedBy] The IDs of the alternative rules.
* @property {Array|Object} schema The option schema of the rule.
* @property {"problem"|"suggestion"|"layout"} type The rule type.
*/
/**
* @typedef {Object} Rule
* @property {Function} create The factory of the rule.
* @property {RuleMeta} meta The meta data of the rule.
*/
/**
* @typedef {Object} Plugin
* @property {Record<string, ConfigData>} [configs] The definition of plugin configs.
* @property {Record<string, Environment>} [environments] The definition of plugin environments.
* @property {Record<string, Processor>} [processors] The definition of plugin processors.
* @property {Record<string, Rule>} [rules] The definition of plugin rules.
*/
/**
* Information of deprecated rules.
* @typedef {Object} DeprecatedRuleInfo
* @property {string} ruleId The rule ID.
* @property {string[]} replacedBy The rule IDs that replace this deprecated rule.
* @property {DeprecatedInfo} [info] The raw deprecated info provided by rule. Unset if `deprecated` is a boolean.
*/
/**
* A linting result.
* @typedef {Object} LintResult
* @property {string} filePath The path to the file that was linted.
* @property {LintMessage[]} messages All of the messages for the result.
* @property {SuppressedLintMessage[]} suppressedMessages All of the suppressed messages for the result.
* @property {number} errorCount Number of errors for the result.
* @property {number} fatalErrorCount Number of fatal errors for the result.
* @property {number} warningCount Number of warnings for the result.
* @property {number} fixableErrorCount Number of fixable errors for the result.
* @property {number} fixableWarningCount Number of fixable warnings for the result.
* @property {Stats} [stats] The performance statistics collected with the `stats` flag.
* @property {string} [source] The source code of the file that was linted.
* @property {string} [output] The source code of the file that was linted, with as many fixes applied as possible.
* @property {DeprecatedRuleInfo[]} usedDeprecatedRules The list of used deprecated rules.
*/
/**
* Performance statistics
* @typedef {Object} Stats
* @property {number} fixPasses The number of times ESLint has applied at least one fix after linting.
* @property {Times} times The times spent on (parsing, fixing, linting) a file.
*/
/**
* Performance Times for each ESLint pass
* @typedef {Object} Times
* @property {TimePass[]} passes Time passes
*/
/**
* @typedef {Object} TimePass
* @property {ParseTime} parse The parse object containing all parse time information.
* @property {Record<string, RuleTime>} [rules] The rules object containing all lint time information for each rule.
* @property {FixTime} fix The parse object containing all fix time information.
* @property {number} total The total time that is spent on (parsing, fixing, linting) a file.
*/
/**
* @typedef {Object} ParseTime
* @property {number} total The total time that is spent when parsing a file.
*/
/**
* @typedef {Object} RuleTime
* @property {number} total The total time that is spent on a rule.
*/
/**
* @typedef {Object} FixTime
* @property {number} total The total time that is spent on applying fixes to the code.
*/
/**
* Information provided when the maximum warning threshold is exceeded.
* @typedef {Object} MaxWarningsExceeded
* @property {number} maxWarnings Number of warnings to trigger nonzero exit code.
* @property {number} foundWarnings Number of warnings found while linting.
*/
/**
* Metadata about results for formatters.
* @typedef {Object} ResultsMeta
* @property {MaxWarningsExceeded} [maxWarningsExceeded] Present if the maxWarnings threshold was exceeded.
*/
/**
* A formatter function.
* @callback FormatterFunction
* @param {LintResult[]} results The list of linting results.
* @param {{cwd: string, maxWarningsExceeded?: MaxWarningsExceeded, rulesMeta: Record<string, RuleMeta>}} context A context object.
* @returns {string | Promise<string>} Formatted text.
*/

View File

@@ -0,0 +1,398 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "buildDynamicImport", {
enumerable: true,
get: function () {
return _dynamicImport.buildDynamicImport;
}
});
exports.buildNamespaceInitStatements = buildNamespaceInitStatements;
exports.ensureStatementsHoisted = ensureStatementsHoisted;
Object.defineProperty(exports, "getModuleName", {
enumerable: true,
get: function () {
return _getModuleName.default;
}
});
Object.defineProperty(exports, "hasExports", {
enumerable: true,
get: function () {
return _normalizeAndLoadMetadata.hasExports;
}
});
Object.defineProperty(exports, "isModule", {
enumerable: true,
get: function () {
return _helperModuleImports.isModule;
}
});
Object.defineProperty(exports, "isSideEffectImport", {
enumerable: true,
get: function () {
return _normalizeAndLoadMetadata.isSideEffectImport;
}
});
exports.rewriteModuleStatementsAndPrepareHeader = rewriteModuleStatementsAndPrepareHeader;
Object.defineProperty(exports, "rewriteThis", {
enumerable: true,
get: function () {
return _rewriteThis.default;
}
});
exports.wrapInterop = wrapInterop;
var _assert = require("assert");
var _core = require("@babel/core");
var _helperModuleImports = require("@babel/helper-module-imports");
var _rewriteThis = require("./rewrite-this.js");
var _rewriteLiveReferences = require("./rewrite-live-references.js");
var _normalizeAndLoadMetadata = require("./normalize-and-load-metadata.js");
var Lazy = require("./lazy-modules.js");
var _dynamicImport = require("./dynamic-import.js");
var _getModuleName = require("./get-module-name.js");
{
exports.getDynamicImportSource = require("./dynamic-import").getDynamicImportSource;
}
function rewriteModuleStatementsAndPrepareHeader(path, {
exportName,
strict,
allowTopLevelThis,
strictMode,
noInterop,
importInterop = noInterop ? "none" : "babel",
lazy,
getWrapperPayload = Lazy.toGetWrapperPayload(lazy != null ? lazy : false),
wrapReference = Lazy.wrapReference,
esNamespaceOnly,
filename,
constantReexports = arguments[1].loose,
enumerableModuleMeta = arguments[1].loose,
noIncompleteNsImportDetection
}) {
(0, _normalizeAndLoadMetadata.validateImportInteropOption)(importInterop);
_assert((0, _helperModuleImports.isModule)(path), "Cannot process module statements in a script");
path.node.sourceType = "script";
const meta = (0, _normalizeAndLoadMetadata.default)(path, exportName, {
importInterop,
initializeReexports: constantReexports,
getWrapperPayload,
esNamespaceOnly,
filename
});
if (!allowTopLevelThis) {
(0, _rewriteThis.default)(path);
}
(0, _rewriteLiveReferences.default)(path, meta, wrapReference);
if (strictMode !== false) {
const hasStrict = path.node.directives.some(directive => {
return directive.value.value === "use strict";
});
if (!hasStrict) {
path.unshiftContainer("directives", _core.types.directive(_core.types.directiveLiteral("use strict")));
}
}
const headers = [];
if ((0, _normalizeAndLoadMetadata.hasExports)(meta) && !strict) {
headers.push(buildESModuleHeader(meta, enumerableModuleMeta));
}
const nameList = buildExportNameListDeclaration(path, meta);
if (nameList) {
meta.exportNameListName = nameList.name;
headers.push(nameList.statement);
}
headers.push(...buildExportInitializationStatements(path, meta, wrapReference, constantReexports, noIncompleteNsImportDetection));
return {
meta,
headers
};
}
function ensureStatementsHoisted(statements) {
statements.forEach(header => {
header._blockHoist = 3;
});
}
function wrapInterop(programPath, expr, type) {
if (type === "none") {
return null;
}
if (type === "node-namespace") {
return _core.types.callExpression(programPath.hub.addHelper("interopRequireWildcard"), [expr, _core.types.booleanLiteral(true)]);
} else if (type === "node-default") {
return null;
}
let helper;
if (type === "default") {
helper = "interopRequireDefault";
} else if (type === "namespace") {
helper = "interopRequireWildcard";
} else {
throw new Error(`Unknown interop: ${type}`);
}
return _core.types.callExpression(programPath.hub.addHelper(helper), [expr]);
}
function buildNamespaceInitStatements(metadata, sourceMetadata, constantReexports = false, wrapReference = Lazy.wrapReference) {
var _wrapReference;
const statements = [];
const srcNamespaceId = _core.types.identifier(sourceMetadata.name);
for (const localName of sourceMetadata.importsNamespace) {
if (localName === sourceMetadata.name) continue;
statements.push(_core.template.statement`var NAME = SOURCE;`({
NAME: localName,
SOURCE: _core.types.cloneNode(srcNamespaceId)
}));
}
const srcNamespace = (_wrapReference = wrapReference(srcNamespaceId, sourceMetadata.wrap)) != null ? _wrapReference : srcNamespaceId;
if (constantReexports) {
statements.push(...buildReexportsFromMeta(metadata, sourceMetadata, true, wrapReference));
}
for (const exportName of sourceMetadata.reexportNamespace) {
statements.push((!_core.types.isIdentifier(srcNamespace) ? _core.template.statement`
Object.defineProperty(EXPORTS, "NAME", {
enumerable: true,
get: function() {
return NAMESPACE;
}
});
` : _core.template.statement`EXPORTS.NAME = NAMESPACE;`)({
EXPORTS: metadata.exportName,
NAME: exportName,
NAMESPACE: _core.types.cloneNode(srcNamespace)
}));
}
if (sourceMetadata.reexportAll) {
const statement = buildNamespaceReexport(metadata, _core.types.cloneNode(srcNamespace), constantReexports);
statement.loc = sourceMetadata.reexportAll.loc;
statements.push(statement);
}
return statements;
}
const ReexportTemplate = {
constant: ({
exports,
exportName,
namespaceImport
}) => _core.template.statement.ast`
${exports}.${exportName} = ${namespaceImport};
`,
constantComputed: ({
exports,
exportName,
namespaceImport
}) => _core.template.statement.ast`
${exports}["${exportName}"] = ${namespaceImport};
`,
spec: ({
exports,
exportName,
namespaceImport
}) => _core.template.statement.ast`
Object.defineProperty(${exports}, "${exportName}", {
enumerable: true,
get: function() {
return ${namespaceImport};
},
});
`
};
function buildReexportsFromMeta(meta, metadata, constantReexports, wrapReference) {
var _wrapReference2;
let namespace = _core.types.identifier(metadata.name);
namespace = (_wrapReference2 = wrapReference(namespace, metadata.wrap)) != null ? _wrapReference2 : namespace;
const {
stringSpecifiers
} = meta;
return Array.from(metadata.reexports, ([exportName, importName]) => {
let namespaceImport = _core.types.cloneNode(namespace);
if (importName === "default" && metadata.interop === "node-default") {} else if (stringSpecifiers.has(importName)) {
namespaceImport = _core.types.memberExpression(namespaceImport, _core.types.stringLiteral(importName), true);
} else {
namespaceImport = _core.types.memberExpression(namespaceImport, _core.types.identifier(importName));
}
const astNodes = {
exports: meta.exportName,
exportName,
namespaceImport
};
if (constantReexports || _core.types.isIdentifier(namespaceImport)) {
if (stringSpecifiers.has(exportName)) {
return ReexportTemplate.constantComputed(astNodes);
} else {
return ReexportTemplate.constant(astNodes);
}
} else {
return ReexportTemplate.spec(astNodes);
}
});
}
function buildESModuleHeader(metadata, enumerableModuleMeta = false) {
return (enumerableModuleMeta ? _core.template.statement`
EXPORTS.__esModule = true;
` : _core.template.statement`
Object.defineProperty(EXPORTS, "__esModule", {
value: true,
});
`)({
EXPORTS: metadata.exportName
});
}
function buildNamespaceReexport(metadata, namespace, constantReexports) {
return (constantReexports ? _core.template.statement`
Object.keys(NAMESPACE).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
VERIFY_NAME_LIST;
if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return;
EXPORTS[key] = NAMESPACE[key];
});
` : _core.template.statement`
Object.keys(NAMESPACE).forEach(function(key) {
if (key === "default" || key === "__esModule") return;
VERIFY_NAME_LIST;
if (key in EXPORTS && EXPORTS[key] === NAMESPACE[key]) return;
Object.defineProperty(EXPORTS, key, {
enumerable: true,
get: function() {
return NAMESPACE[key];
},
});
});
`)({
NAMESPACE: namespace,
EXPORTS: metadata.exportName,
VERIFY_NAME_LIST: metadata.exportNameListName ? (0, _core.template)`
if (Object.prototype.hasOwnProperty.call(EXPORTS_LIST, key)) return;
`({
EXPORTS_LIST: metadata.exportNameListName
}) : null
});
}
function buildExportNameListDeclaration(programPath, metadata) {
const exportedVars = Object.create(null);
for (const data of metadata.local.values()) {
for (const name of data.names) {
exportedVars[name] = true;
}
}
let hasReexport = false;
for (const data of metadata.source.values()) {
for (const exportName of data.reexports.keys()) {
exportedVars[exportName] = true;
}
for (const exportName of data.reexportNamespace) {
exportedVars[exportName] = true;
}
hasReexport = hasReexport || !!data.reexportAll;
}
if (!hasReexport || Object.keys(exportedVars).length === 0) return null;
const name = programPath.scope.generateUidIdentifier("exportNames");
delete exportedVars.default;
return {
name: name.name,
statement: _core.types.variableDeclaration("var", [_core.types.variableDeclarator(name, _core.types.valueToNode(exportedVars))])
};
}
function buildExportInitializationStatements(programPath, metadata, wrapReference, constantReexports = false, noIncompleteNsImportDetection = false) {
const initStatements = [];
for (const [localName, data] of metadata.local) {
if (data.kind === "import") {} else if (data.kind === "hoisted") {
initStatements.push([data.names[0], buildInitStatement(metadata, data.names, _core.types.identifier(localName))]);
} else if (!noIncompleteNsImportDetection) {
for (const exportName of data.names) {
initStatements.push([exportName, null]);
}
}
}
for (const data of metadata.source.values()) {
if (!constantReexports) {
const reexportsStatements = buildReexportsFromMeta(metadata, data, false, wrapReference);
const reexports = [...data.reexports.keys()];
for (let i = 0; i < reexportsStatements.length; i++) {
initStatements.push([reexports[i], reexportsStatements[i]]);
}
}
if (!noIncompleteNsImportDetection) {
for (const exportName of data.reexportNamespace) {
initStatements.push([exportName, null]);
}
}
}
initStatements.sort(([a], [b]) => {
if (a < b) return -1;
if (b < a) return 1;
return 0;
});
const results = [];
if (noIncompleteNsImportDetection) {
for (const [, initStatement] of initStatements) {
results.push(initStatement);
}
} else {
const chunkSize = 100;
for (let i = 0; i < initStatements.length; i += chunkSize) {
let uninitializedExportNames = [];
for (let j = 0; j < chunkSize && i + j < initStatements.length; j++) {
const [exportName, initStatement] = initStatements[i + j];
if (initStatement !== null) {
if (uninitializedExportNames.length > 0) {
results.push(buildInitStatement(metadata, uninitializedExportNames, programPath.scope.buildUndefinedNode()));
uninitializedExportNames = [];
}
results.push(initStatement);
} else {
uninitializedExportNames.push(exportName);
}
}
if (uninitializedExportNames.length > 0) {
results.push(buildInitStatement(metadata, uninitializedExportNames, programPath.scope.buildUndefinedNode()));
}
}
}
return results;
}
const InitTemplate = {
computed: ({
exports,
name,
value
}) => _core.template.expression.ast`${exports}["${name}"] = ${value}`,
default: ({
exports,
name,
value
}) => _core.template.expression.ast`${exports}.${name} = ${value}`,
define: ({
exports,
name,
value
}) => _core.template.expression.ast`
Object.defineProperty(${exports}, "${name}", {
enumerable: true,
value: void 0,
writable: true
})["${name}"] = ${value}`
};
function buildInitStatement(metadata, exportNames, initExpr) {
const {
stringSpecifiers,
exportName: exports
} = metadata;
return _core.types.expressionStatement(exportNames.reduce((value, name) => {
const params = {
exports,
name,
value
};
if (name === "__proto__") {
return InitTemplate.define(params);
}
if (stringSpecifiers.has(name)) {
return InitTemplate.computed(params);
}
return InitTemplate.default(params);
}, initExpr));
}
//# sourceMappingURL=index.js.map