docs: 仓库链接指向本镜像仓库
Build NapCat Artifacts / Windows Loader Test (push) Canceled after 0s
Build NapCat Artifacts / Type Check & Test (push) Canceled after 0s
Build NapCat Artifacts / Build NapCat.Framework (push) Canceled after 0s
Build NapCat Artifacts / Build NapCat.Shell (push) Canceled after 0s

This commit is contained in:
TanTan committed 2026-11-13 09:25:58 +08:00
1 parent f954252a34
commit e311ca3275
35554 files changed
+6229626 -4

No files matched your search

@@ -0,0 +1,5 @@
var convert = require('./convert'),
func = convert('startsWith', require('../startsWith'));
func.placeholder = require('./placeholder');
module.exports = func;
@@ -0,0 +1,2 @@
import type { ClientRect } from '../../types';
export declare function inverseTransform(rect: ClientRect, transform: string, transformOrigin: string): ClientRect;
@@ -0,0 +1,87 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.safeParseAsync = exports._safeParseAsync = exports.safeParse = exports._safeParse = exports.parseAsync = exports._parseAsync = exports.parse = exports._parse = void 0;
const core = __importStar(require("./core.cjs"));
const errors = __importStar(require("./errors.cjs"));
const util = __importStar(require("./util.cjs"));
const _parse = (_Err) => (schema, value, _ctx, _params) => {
const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
const result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new core.$ZodAsyncError();
}
if (result.issues.length) {
const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));
util.captureStackTrace(e, _params?.callee);
throw e;
}
return result.value;
};
exports._parse = _parse;
exports.parse = (0, exports._parse)(errors.$ZodRealError);
const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
if (result.issues.length) {
const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));
util.captureStackTrace(e, params?.callee);
throw e;
}
return result.value;
};
exports._parseAsync = _parseAsync;
exports.parseAsync = (0, exports._parseAsync)(errors.$ZodRealError);
const _safeParse = (_Err) => (schema, value, _ctx) => {
const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
const result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise) {
throw new core.$ZodAsyncError();
}
return result.issues.length
? {
success: false,
error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),
}
: { success: true, data: result.value };
};
exports._safeParse = _safeParse;
exports.safeParse = (0, exports._safeParse)(errors.$ZodRealError);
const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
let result = schema._zod.run({ value, issues: [] }, ctx);
if (result instanceof Promise)
result = await result;
return result.issues.length
? {
success: false,
error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),
}
: { success: true, data: result.value };
};
exports._safeParseAsync = _safeParseAsync;
exports.safeParseAsync = (0, exports._safeParseAsync)(errors.$ZodRealError);
@@ -0,0 +1,47 @@
# unbox-primitive <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
[![github actions][actions-image]][actions-url]
[![coverage][codecov-image]][codecov-url]
[![dependency status][deps-svg]][deps-url]
[![dev dependency status][dev-deps-svg]][dev-deps-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]
[![npm badge][npm-badge-png]][package-url]
Unbox a boxed JS primitive value. This module works cross-realm/iframe, does not depend on `instanceof` or mutable properties, and works despite ES6 Symbol.toStringTag.
## Example
```js
var unboxPrimitive = require('unbox-primitive');
var assert = require('assert');
assert.equal(unboxPrimitive(new Boolean(false)), false);
assert.equal(unboxPrimitive(new String('f')), 'f');
assert.equal(unboxPrimitive(new Number(42)), 42);
const s = Symbol();
assert.equal(unboxPrimitive(Object(s)), s);
assert.equal(unboxPrimitive(new BigInt(42)), 42n);
// any primitive, or non-boxed-primitive object, will throw
```
## Tests
Simply clone the repo, `npm install`, and run `npm test`
[package-url]: https://npmjs.org/package/unbox-primitive
[npm-version-svg]: https://versionbadg.es/ljharb/unbox-primitive.svg
[deps-svg]: https://david-dm.org/ljharb/unbox-primitive.svg
[deps-url]: https://david-dm.org/ljharb/unbox-primitive
[dev-deps-svg]: https://david-dm.org/ljharb/unbox-primitive/dev-status.svg
[dev-deps-url]: https://david-dm.org/ljharb/unbox-primitive#info=devDependencies
[npm-badge-png]: https://nodei.co/npm/unbox-primitive.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/unbox-primitive.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/unbox-primitive.svg
[downloads-url]: https://npm-stat.com/charts.html?package=unbox-primitive
[codecov-image]: https://codecov.io/gh/ljharb/unbox-primitive/branch/main/graphs/badge.svg
[codecov-url]: https://app.codecov.io/gh/ljharb/unbox-primitive/
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/unbox-primitive
[actions-url]: https://github.com/ljharb/unbox-primitive/actions
@@ -0,0 +1,33 @@
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max,
nativeMin = Math.min;
/**
* Gets the view, applying any `transforms` to the `start` and `end` positions.
*
* @private
* @param {number} start The start of the view.
* @param {number} end The end of the view.
* @param {Array} transforms The transformations to apply to the view.
* @returns {Object} Returns an object containing the `start` and `end`
* positions of the view.
*/
function getView(start, end, transforms) {
var index = -1,
length = transforms.length;
while (++index < length) {
var data = transforms[index],
size = data.size;
switch (data.type) {
case 'drop': start += size; break;
case 'dropRight': end -= size; break;
case 'take': end = nativeMin(end, start + size); break;
case 'takeRight': start = nativeMax(start, end - size); break;
}
}
return { 'start': start, 'end': end };
}
module.exports = getView;
@@ -0,0 +1,76 @@
import {createRectInit, getContentRect} from './utils/geometry.js';
/**
* Class that is responsible for computations of the content rectangle of
* provided DOM element and for keeping track of it's changes.
*/
export default class ResizeObservation {
/**
* Reference to the observed element.
*
* @type {Element}
*/
target;
/**
* Broadcasted width of content rectangle.
*
* @type {number}
*/
broadcastWidth = 0;
/**
* Broadcasted height of content rectangle.
*
* @type {number}
*/
broadcastHeight = 0;
/**
* Reference to the last observed content rectangle.
*
* @private {DOMRectInit}
*/
contentRect_ = createRectInit(0, 0, 0, 0);
/**
* Creates an instance of ResizeObservation.
*
* @param {Element} target - Element to be observed.
*/
constructor(target) {
this.target = target;
}
/**
* Updates content rectangle and tells whether it's width or height properties
* have changed since the last broadcast.
*
* @returns {boolean}
*/
isActive() {
const rect = getContentRect(this.target);
this.contentRect_ = rect;
return (
rect.width !== this.broadcastWidth ||
rect.height !== this.broadcastHeight
);
}
/**
* Updates 'broadcastWidth' and 'broadcastHeight' properties with a data
* from the corresponding properties of the last observed content rectangle.
*
* @returns {DOMRectInit} Last observed content rectangle.
*/
broadcastRect() {
const rect = this.contentRect_;
this.broadcastWidth = rect.width;
this.broadcastHeight = rect.height;
return rect;
}
}
@@ -0,0 +1,23 @@
The MIT License (MIT)
Copyright (c) 2014 Stefan Thomas
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.
@@ -0,0 +1,3 @@
import { useEffect } from 'react';
declare const useIsomorphicLayoutEffect: typeof useEffect;
export default useIsomorphicLayoutEffect;
@@ -0,0 +1,38 @@
// Haitian Creole (Haiti) [ht]
import dayjs from '../index';
var locale = {
name: 'ht',
weekdays: 'dimanch_lendi_madi_mèkredi_jedi_vandredi_samdi'.split('_'),
months: 'janvye_fevriye_mas_avril_me_jen_jiyè_out_septanm_oktòb_novanm_desanm'.split('_'),
weekdaysShort: 'dim._len._mad._mèk._jed._van._sam.'.split('_'),
monthsShort: 'jan._fev._mas_avr._me_jen_jiyè._out_sept._okt._nov._des.'.split('_'),
weekdaysMin: 'di_le_ma_mè_je_va_sa'.split('_'),
ordinal: function ordinal(n) {
return n;
},
formats: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'DD/MM/YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd D MMMM YYYY HH:mm'
},
relativeTime: {
future: 'nan %s',
past: 'sa gen %s',
s: 'kèk segond',
m: 'yon minit',
mm: '%d minit',
h: 'inèdtan',
hh: '%d zè',
d: 'yon jou',
dd: '%d jou',
M: 'yon mwa',
MM: '%d mwa',
y: 'yon ane',
yy: '%d ane'
}
};
dayjs.locale(locale, null, true);
export default locale;
@@ -0,0 +1,51 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _helperPluginUtils = require("@babel/helper-plugin-utils");
var _core = require("@babel/core");
const TRACE_ID = "__source";
const FILE_NAME_VAR = "_jsxFileName";
const createNodeFromNullish = (val, fn) => val == null ? _core.types.nullLiteral() : fn(val);
var _default = exports.default = (0, _helperPluginUtils.declare)(api => {
api.assertVersion(7);
function makeTrace(fileNameIdentifier, {
line,
column
}) {
const fileLineLiteral = createNodeFromNullish(line, _core.types.numericLiteral);
const fileColumnLiteral = createNodeFromNullish(column, c => _core.types.numericLiteral(c + 1));
return _core.template.expression.ast`{
fileName: ${fileNameIdentifier},
lineNumber: ${fileLineLiteral},
columnNumber: ${fileColumnLiteral},
}`;
}
const isSourceAttr = attr => _core.types.isJSXAttribute(attr) && attr.name.name === TRACE_ID;
return {
name: "transform-react-jsx-source",
visitor: {
JSXOpeningElement(path, state) {
const {
node
} = path;
if (!node.loc || path.node.attributes.some(isSourceAttr)) {
return;
}
if (!state.fileNameIdentifier) {
const fileNameId = path.scope.generateUidIdentifier(FILE_NAME_VAR);
state.fileNameIdentifier = fileNameId;
path.scope.getProgramParent().push({
id: fileNameId,
init: _core.types.stringLiteral(state.filename || "")
});
}
node.attributes.push(_core.types.jsxAttribute(_core.types.jsxIdentifier(TRACE_ID), _core.types.jsxExpressionContainer(makeTrace(_core.types.cloneNode(state.fileNameIdentifier), node.loc.start))));
}
}
};
});
//# sourceMappingURL=index.js.map
@@ -0,0 +1,11 @@
import { AST, Rule } from 'eslint';
declare function parse(
path: string,
content: string,
context: Rule.RuleContext
): AST.Program | null | undefined;
export default parse;
@@ -0,0 +1,221 @@
import { Any } from '../any/index.mjs';
import { Array } from '../array/index.mjs';
import { Boolean } from '../boolean/index.mjs';
import { Composite } from '../composite/index.mjs';
import { Const } from '../const/index.mjs';
import { Enum } from '../enum/index.mjs';
import { Exclude } from '../exclude/index.mjs';
import { Extends } from '../extends/index.mjs';
import { Extract } from '../extract/index.mjs';
import { Index } from '../indexed/index.mjs';
import { Integer } from '../integer/index.mjs';
import { Intersect } from '../intersect/index.mjs';
import { Capitalize, Uncapitalize, Lowercase, Uppercase } from '../intrinsic/index.mjs';
import { KeyOf } from '../keyof/index.mjs';
import { Literal } from '../literal/index.mjs';
import { Mapped } from '../mapped/index.mjs';
import { Never } from '../never/index.mjs';
import { Not } from '../not/index.mjs';
import { Null } from '../null/index.mjs';
import { Module } from '../module/index.mjs';
import { Number } from '../number/index.mjs';
import { Object } from '../object/index.mjs';
import { Omit } from '../omit/index.mjs';
import { Optional } from '../optional/index.mjs';
import { Partial } from '../partial/index.mjs';
import { Pick } from '../pick/index.mjs';
import { Readonly } from '../readonly/index.mjs';
import { ReadonlyOptional } from '../readonly-optional/index.mjs';
import { Record } from '../record/index.mjs';
import { Recursive } from '../recursive/index.mjs';
import { Ref } from '../ref/index.mjs';
import { Required } from '../required/index.mjs';
import { Rest } from '../rest/index.mjs';
import { String } from '../string/index.mjs';
import { TemplateLiteral } from '../template-literal/index.mjs';
import { Transform } from '../transform/index.mjs';
import { Tuple } from '../tuple/index.mjs';
import { Union } from '../union/index.mjs';
import { Unknown } from '../unknown/index.mjs';
import { Unsafe } from '../unsafe/index.mjs';
/** Json Type Builder with Static Resolution for TypeScript */
export class JsonTypeBuilder {
// ------------------------------------------------------------------------
// Modifiers
// ------------------------------------------------------------------------
/** `[Json]` Creates a Readonly and Optional property */
ReadonlyOptional(type) {
return ReadonlyOptional(type);
}
/** `[Json]` Creates a Readonly property */
Readonly(type, enable) {
return Readonly(type, enable ?? true);
}
/** `[Json]` Creates a Optional property */
Optional(type, enable) {
return Optional(type, enable ?? true);
}
// ------------------------------------------------------------------------
// Types
// ------------------------------------------------------------------------
/** `[Json]` Creates an Any type */
Any(options) {
return Any(options);
}
/** `[Json]` Creates an Array type */
Array(items, options) {
return Array(items, options);
}
/** `[Json]` Creates a Boolean type */
Boolean(options) {
return Boolean(options);
}
/** `[Json]` Intrinsic function to Capitalize LiteralString types */
Capitalize(schema, options) {
return Capitalize(schema, options);
}
/** `[Json]` Creates a Composite object type */
Composite(schemas, options) {
return Composite(schemas, options); // (error) TS 5.4.0-dev - review TComposite implementation
}
/** `[JavaScript]` Creates a readonly const type from the given value. */
Const(value, options) {
return Const(value, options);
}
/** `[Json]` Creates a Enum type */
Enum(item, options) {
return Enum(item, options);
}
/** `[Json]` Constructs a type by excluding from unionType all union members that are assignable to excludedMembers */
Exclude(unionType, excludedMembers, options) {
return Exclude(unionType, excludedMembers, options);
}
/** `[Json]` Creates a Conditional type */
Extends(L, R, T, F, options) {
return Extends(L, R, T, F, options);
}
/** `[Json]` Constructs a type by extracting from type all union members that are assignable to union */
Extract(type, union, options) {
return Extract(type, union, options);
}
/** `[Json]` Returns an Indexed property type for the given keys */
Index(type, key, options) {
return Index(type, key, options);
}
/** `[Json]` Creates an Integer type */
Integer(options) {
return Integer(options);
}
/** `[Json]` Creates an Intersect type */
Intersect(types, options) {
return Intersect(types, options);
}
/** `[Json]` Creates a KeyOf type */
KeyOf(type, options) {
return KeyOf(type, options);
}
/** `[Json]` Creates a Literal type */
Literal(literalValue, options) {
return Literal(literalValue, options);
}
/** `[Json]` Intrinsic function to Lowercase LiteralString types */
Lowercase(type, options) {
return Lowercase(type, options);
}
/** `[Json]` Creates a Mapped object type */
Mapped(key, map, options) {
return Mapped(key, map, options);
}
/** `[Json]` Creates a Type Definition Module. */
Module(properties) {
return Module(properties);
}
/** `[Json]` Creates a Never type */
Never(options) {
return Never(options);
}
/** `[Json]` Creates a Not type */
Not(type, options) {
return Not(type, options);
}
/** `[Json]` Creates a Null type */
Null(options) {
return Null(options);
}
/** `[Json]` Creates a Number type */
Number(options) {
return Number(options);
}
/** `[Json]` Creates an Object type */
Object(properties, options) {
return Object(properties, options);
}
/** `[Json]` Constructs a type whose keys are omitted from the given type */
Omit(schema, selector, options) {
return Omit(schema, selector, options);
}
/** `[Json]` Constructs a type where all properties are optional */
Partial(type, options) {
return Partial(type, options);
}
/** `[Json]` Constructs a type whose keys are picked from the given type */
Pick(type, key, options) {
return Pick(type, key, options);
}
/** `[Json]` Creates a Record type */
Record(key, value, options) {
return Record(key, value, options);
}
/** `[Json]` Creates a Recursive type */
Recursive(callback, options) {
return Recursive(callback, options);
}
/** `[Json]` Creates a Ref type. The referenced type must contain a $id */
Ref(...args) {
return Ref(args[0], args[1]);
}
/** `[Json]` Constructs a type where all properties are required */
Required(type, options) {
return Required(type, options);
}
/** `[Json]` Extracts interior Rest elements from Tuple, Intersect and Union types */
Rest(type) {
return Rest(type);
}
/** `[Json]` Creates a String type */
String(options) {
return String(options);
}
/** `[Json]` Creates a TemplateLiteral type */
TemplateLiteral(unresolved, options) {
return TemplateLiteral(unresolved, options);
}
/** `[Json]` Creates a Transform type */
Transform(type) {
return Transform(type);
}
/** `[Json]` Creates a Tuple type */
Tuple(types, options) {
return Tuple(types, options);
}
/** `[Json]` Intrinsic function to Uncapitalize LiteralString types */
Uncapitalize(type, options) {
return Uncapitalize(type, options);
}
/** `[Json]` Creates a Union type */
Union(types, options) {
return Union(types, options);
}
/** `[Json]` Creates an Unknown type */
Unknown(options) {
return Unknown(options);
}
/** `[Json]` Creates a Unsafe type that will infers as the generic argument T */
Unsafe(options) {
return Unsafe(options);
}
/** `[Json]` Intrinsic function to Uppercase LiteralString types */
Uppercase(schema, options) {
return Uppercase(schema, options);
}
}
@@ -0,0 +1,121 @@
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import {CollectionBuilderContext} from './useTableState';
import {PartialNode} from '@react-stately/collections';
import React, {JSX, ReactElement} from 'react';
import {RowProps} from '@react-types/table';
function Row<T>(props: RowProps<T>): ReactElement | null { // eslint-disable-line @typescript-eslint/no-unused-vars
return null;
}
Row.getCollectionNode = function* getCollectionNode<T>(props: RowProps<T>, context: CollectionBuilderContext<T>): Generator<PartialNode<T>> {
let {children, textValue, UNSTABLE_childItems} = props;
yield {
type: 'item',
props: props,
textValue,
'aria-label': props['aria-label'],
hasChildNodes: true,
*childNodes() {
// Process cells first
if (context.showDragButtons) {
yield {
type: 'cell',
key: 'header-drag', // this is combined with the row key by CollectionBuilder
props: {
isDragButtonCell: true
}
};
}
if (context.showSelectionCheckboxes && context.selectionMode !== 'none') {
yield {
type: 'cell',
key: 'header', // this is combined with the row key by CollectionBuilder
props: {
isSelectionCell: true
}
};
}
if (typeof children === 'function') {
for (let column of context.columns) {
yield {
type: 'cell',
element: children(column.key),
key: column.key // this is combined with the row key by CollectionBuilder
};
}
if (UNSTABLE_childItems) {
for (let child of UNSTABLE_childItems) {
// Note: in order to reuse the render function of TableBody for our child rows, we just need to yield a type and a value here. CollectionBuilder will then look up
// the parent renderer and use that to build the full node of this child row, using the value provided here to generate the cells
yield {
type: 'item',
value: child
};
}
}
} else {
let cells: PartialNode<T>[] = [];
let childRows: PartialNode<T>[] = [];
let columnCount = 0;
React.Children.forEach(children, node => {
if (node.type === Row) {
if (cells.length < context.columns.length) {
throw new Error('All of a Row\'s child Cells must be positioned before any child Rows.');
}
childRows.push({
type: 'item',
element: node
});
} else {
cells.push({
type: 'cell',
element: node
});
columnCount += node.props.colSpan ?? 1;
}
});
if (columnCount !== context.columns.length) {
throw new Error(`Cell count must match column count. Found ${columnCount} cells and ${context.columns.length} columns.`);
}
yield* cells;
yield* childRows;
}
},
shouldInvalidate(newContext: CollectionBuilderContext<T>) {
// Invalidate all rows if the columns changed.
return newContext.columns.length !== context.columns.length ||
newContext.columns.some((c, i) => c.key !== context.columns[i].key) ||
newContext.showSelectionCheckboxes !== context.showSelectionCheckboxes ||
newContext.showDragButtons !== context.showDragButtons ||
newContext.selectionMode !== context.selectionMode;
}
};
};
/**
* A Row represents a single item in a Table and contains Cell elements for each column.
* Cells can be statically defined as children, or generated dynamically using a function
* based on the columns defined in the TableHeader.
*/
// We don't want getCollectionNode to show up in the type definition
let _Row = Row as <T>(props: RowProps<T>) => JSX.Element;
export {_Row as Row};
@@ -0,0 +1,9 @@
{
"extends": "@ljharb/tsconfig",
"compilerOptions": {
"target": "ES2021",
},
"exclude": [
"coverage"
]
}
@@ -0,0 +1,9 @@
import type { BasicTarget } from '../utils/domTarget';
type Position = {
left: number;
top: number;
};
export type Target = BasicTarget<Element | Document>;
export type ScrollListenController = (val: Position) => boolean;
declare function useScroll(target?: Target, shouldUpdate?: ScrollListenController): Position | undefined;
export default useScroll;
@@ -0,0 +1,121 @@
# eslint-visitor-keys
[![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys)
[![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys)
[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/eslint/js/actions)
Constants and utilities about visitor keys to traverse AST.
## 💿 Installation
Use [npm] to install.
```bash
$ npm install eslint-visitor-keys
```
### Requirements
- [Node.js] `^18.18.0`, `^20.9.0`, or `>=21.1.0`
## 📖 Usage
To use in an ESM file:
```js
import * as evk from "eslint-visitor-keys"
```
To use in a CommonJS file:
```js
const evk = require("eslint-visitor-keys")
```
### evk.KEYS
> type: `{ [type: string]: string[] | undefined }`
Visitor keys. This keys are frozen.
This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes.
For example:
```
console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"]
```
### evk.getKeys(node)
> type: `(node: object) => string[]`
Get the visitor keys of a given AST node.
This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`.
This will be used to traverse unknown nodes.
For example:
```js
const node = {
type: "AssignmentExpression",
left: { type: "Identifier", name: "foo" },
right: { type: "Literal", value: 0 }
}
console.log(evk.getKeys(node)) // → ["type", "left", "right"]
```
### evk.unionWith(additionalKeys)
> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }`
Make the union set with `evk.KEYS` and the given keys.
- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that.
- It removes duplicated keys as keeping the first one.
For example:
```js
console.log(evk.unionWith({
MethodDefinition: ["decorators"]
})) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... }
```
## 📰 Change log
See [GitHub releases](https://github.com/eslint/js/releases).
## 🍻 Contributing
Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/).
### Development commands
- `npm test` runs tests and measures code coverage.
- `npm run lint` checks source codes with ESLint.
- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser.
[npm]: https://www.npmjs.com/
[Node.js]: https://nodejs.org/
[ESTree]: https://github.com/estree/estree
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
<!--sponsorsstart-->
## Sponsors
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
<h3>Diamond Sponsors</h3>
<p><a href="https://www.ag-grid.com/"><img src="https://images.opencollective.com/ag-grid/bec0580/logo.png" alt="AG Grid" height="128"></a></p><h3>Platinum Sponsors</h3>
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="128"></a></p><h3>Gold Sponsors</h3>
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a> <a href="https://trunk.io/"><img src="https://images.opencollective.com/trunkio/fb92d60/avatar.png" alt="trunk.io" height="96"></a> <a href="https://shopify.engineering/"><img src="https://avatars.githubusercontent.com/u/8085" alt="Shopify" height="96"></a></p><h3>Silver Sponsors</h3>
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/e6d15e1/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a> <a href="https://americanexpress.io"><img src="https://avatars.githubusercontent.com/u/3853301" alt="American Express" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
<p><a href="https://sentry.io"><img src="https://github.com/getsentry.png" alt="Sentry" height="32"></a> <a href="https://syntax.fm"><img src="https://github.com/syntaxfm.png" alt="Syntax" height="32"></a> <a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://nolebase.ayaka.io"><img src="https://avatars.githubusercontent.com/u/11081491" alt="Neko" height="32"></a> <a href="https://nx.dev"><img src="https://avatars.githubusercontent.com/u/23692104" alt="Nx" height="32"></a> <a href="https://opensource.mercedes-benz.com/"><img src="https://avatars.githubusercontent.com/u/34240465" alt="Mercedes-Benz Group" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="LambdaTest" height="32"></a></p>
<h3>Technology Sponsors</h3>
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
<!--sponsorsend-->
@@ -0,0 +1,88 @@
{
"name": "sucrase",
"version": "3.35.0",
"description": "Super-fast alternative to Babel for when you can target modern JS runtimes",
"author": "Alan Pierce <alangpierce@gmail.com>",
"license": "MIT",
"main": "dist/index.js",
"module": "dist/esm/index.js",
"types": "dist/types/index.d.ts",
"bin": {
"sucrase": "./bin/sucrase",
"sucrase-node": "./bin/sucrase-node"
},
"scripts": {
"build": "sucrase-node script/build.ts",
"fast-build": "sucrase-node script/build.ts --fast",
"clean": "rm -rf ./build ./dist ./dist-self-build ./dist-types ./example-runner/example-repos ./spec-compliance-tests/test262/test262-checkout ./spec-compliance-tests/babel-tests/babel-tests-checkout",
"generate": "sucrase-node generator/generate.ts",
"benchmark": "cd benchmark && yarn && sucrase-node ./benchmark.ts",
"benchmark-compare": "sucrase-node ./benchmark/compare-performance.ts",
"microbenchmark": "sucrase-node benchmark/microbenchmark.ts",
"lint": "sucrase-node script/lint.ts",
"lint-fix": "sucrase-node script/lint.ts --fix",
"profile": "node --inspect-brk ./node_modules/.bin/sucrase-node ./benchmark/profile",
"profile-project": "node --inspect-brk ./node_modules/.bin/sucrase-node ./benchmark/benchmark-project.ts --profile",
"prepublishOnly": "yarn clean && yarn build",
"release": "sucrase-node script/release.ts",
"run-examples": "sucrase-node example-runner/example-runner.ts",
"test": "yarn lint && yarn test-only",
"test-only": "mocha './test/**/*.ts'",
"integration-test": "cd integration-test && yarn && yarn link @sucrase/jest-plugin && mocha --timeout 10000 ./integration-tests.ts",
"test262": "sucrase-node spec-compliance-tests/test262/run-test262.ts",
"check-babel-tests": "sucrase-node spec-compliance-tests/babel-tests/check-babel-tests.ts",
"test-with-coverage": "nyc mocha './test/**/*.ts'",
"report-coverage": "nyc report --reporter=text-lcov > coverage.lcov && codecov"
},
"repository": {
"type": "git",
"url": "https://github.com/alangpierce/sucrase.git"
},
"keywords": [
"babel",
"jsx",
"typescript",
"flow"
],
"bugs": {
"url": "https://github.com/alangpierce/sucrase/issues"
},
"devDependencies": {
"@babel/core": "^7.22.5",
"@jridgewell/trace-mapping": "^0.3.18",
"@types/mocha": "^9.1.1",
"@types/mz": "^2.7.4",
"@types/node": "^20.3.2",
"@typescript-eslint/eslint-plugin": "^5.60.1",
"@typescript-eslint/parser": "^5.60.1",
"chalk": "^4",
"codecov": "^3.8.3",
"eslint": "^8.43.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-import": "~2.26",
"eslint-plugin-prettier": "^4.2.1",
"mocha": "^10.2.0",
"nyc": "^15.1.0",
"prettier": "^2.8.8",
"sucrase": "^3.34.0",
"test262-harness": "^10.0.0",
"ts-interface-builder": "^0.3.3",
"typescript": "~5.0"
},
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.2",
"commander": "^4.0.0",
"glob": "^10.3.10",
"lines-and-columns": "^1.1.6",
"mz": "^2.7.0",
"pirates": "^4.0.1",
"ts-interface-checker": "^0.1.9"
},
"engines": {
"node": ">=16 || 14 >=14.17"
},
"resolutions": {
"**/eshost/socket.io": "4.7.0"
}
}
@@ -0,0 +1,81 @@
import { SourceMapConsumer } from 'source-map-js'
import { ProcessOptions } from './postcss.js'
declare namespace PreviousMap {
// eslint-disable-next-line @typescript-eslint/no-use-before-define
export { PreviousMap_ as default }
}
/**
* Source map information from input CSS.
* For example, source map after Sass compiler.
*
* This class will automatically find source map in input CSS or in file system
* near input file (according `from` option).
*
* ```js
* const root = parse(css, { from: 'a.sass.css' })
* root.input.map //=> PreviousMap
* ```
*/
declare class PreviousMap_ {
/**
* `sourceMappingURL` content.
*/
annotation?: string
/**
* The CSS source identifier. Contains `Input#file` if the user
* set the `from` option, or `Input#id` if they did not.
*/
file?: string
/**
* Was source map inlined by data-uri to input CSS.
*/
inline: boolean
/**
* Path to source map file.
*/
mapFile?: string
/**
* The directory with source map file, if source map is in separated file.
*/
root?: string
/**
* Source map file content.
*/
text?: string
/**
* @param css Input CSS source.
* @param opts Process options.
*/
constructor(css: string, opts?: ProcessOptions)
/**
* Create a instance of `SourceMapGenerator` class
* from the `source-map` library to work with source map information.
*
* It is lazy method, so it will create object only on first call
* and then it will use cache.
*
* @return Object with source map information.
*/
consumer(): SourceMapConsumer
/**
* Does source map contains `sourcesContent` with input source text.
*
* @return Is `sourcesContent` present.
*/
withContent(): boolean
}
declare class PreviousMap extends PreviousMap_ {}
export = PreviousMap
@@ -0,0 +1,159 @@
/**
* @fileoverview A rule to set the maximum depth block can be nested in a function.
* @author Ian Christian Myers
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Enforce a maximum depth that blocks can be nested",
recommended: false,
url: "https://eslint.org/docs/latest/rules/max-depth",
},
schema: [
{
oneOf: [
{
type: "integer",
minimum: 0,
},
{
type: "object",
properties: {
maximum: {
type: "integer",
minimum: 0,
},
max: {
type: "integer",
minimum: 0,
},
},
additionalProperties: false,
},
],
},
],
messages: {
tooDeeply:
"Blocks are nested too deeply ({{depth}}). Maximum allowed is {{maxDepth}}.",
},
},
create(context) {
//--------------------------------------------------------------------------
// Helpers
//--------------------------------------------------------------------------
const functionStack = [],
option = context.options[0];
let maxDepth = 4;
if (
typeof option === "object" &&
(Object.hasOwn(option, "maximum") || Object.hasOwn(option, "max"))
) {
maxDepth = option.maximum || option.max;
}
if (typeof option === "number") {
maxDepth = option;
}
/**
* When parsing a new function, store it in our function stack
* @returns {void}
* @private
*/
function startFunction() {
functionStack.push(0);
}
/**
* When parsing is done then pop out the reference
* @returns {void}
* @private
*/
function endFunction() {
functionStack.pop();
}
/**
* Save the block and Evaluate the node
* @param {ASTNode} node node to evaluate
* @returns {void}
* @private
*/
function pushBlock(node) {
const len = ++functionStack[functionStack.length - 1];
if (len > maxDepth) {
context.report({
node,
messageId: "tooDeeply",
data: { depth: len, maxDepth },
});
}
}
/**
* Pop the saved block
* @returns {void}
* @private
*/
function popBlock() {
functionStack[functionStack.length - 1]--;
}
//--------------------------------------------------------------------------
// Public API
//--------------------------------------------------------------------------
return {
Program: startFunction,
FunctionDeclaration: startFunction,
FunctionExpression: startFunction,
ArrowFunctionExpression: startFunction,
StaticBlock: startFunction,
IfStatement(node) {
if (node.parent.type !== "IfStatement") {
pushBlock(node);
}
},
SwitchStatement: pushBlock,
TryStatement: pushBlock,
DoWhileStatement: pushBlock,
WhileStatement: pushBlock,
WithStatement: pushBlock,
ForStatement: pushBlock,
ForInStatement: pushBlock,
ForOfStatement: pushBlock,
"IfStatement:exit": popBlock,
"SwitchStatement:exit": popBlock,
"TryStatement:exit": popBlock,
"DoWhileStatement:exit": popBlock,
"WhileStatement:exit": popBlock,
"WithStatement:exit": popBlock,
"ForStatement:exit": popBlock,
"ForInStatement:exit": popBlock,
"ForOfStatement:exit": popBlock,
"FunctionDeclaration:exit": endFunction,
"FunctionExpression:exit": endFunction,
"ArrowFunctionExpression:exit": endFunction,
"StaticBlock:exit": endFunction,
"Program:exit": endFunction,
};
},
};
@@ -0,0 +1,97 @@
var $37ePF$reactariafocus = require("@react-aria/focus");
var $37ePF$reactariautils = require("@react-aria/utils");
var $37ePF$react = require("react");
var $37ePF$reactariai18n = require("@react-aria/i18n");
function $parcel$export(e, n, v, s) {
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
}
$parcel$export(module.exports, "useToolbar", () => $b132ee173e26a273$export$fa142eb1681c520);
/*
* Copyright 2023 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
function $b132ee173e26a273$export$fa142eb1681c520(props, ref) {
const { 'aria-label': ariaLabel, 'aria-labelledby': ariaLabelledBy, orientation: orientation = 'horizontal' } = props;
let [isInToolbar, setInToolbar] = (0, $37ePF$react.useState)(false);
// should be safe because re-calling set state with the same value it already has is a no-op
// this will allow us to react should a parent re-render and change its role though
// eslint-disable-next-line react-hooks/exhaustive-deps
(0, $37ePF$reactariautils.useLayoutEffect)(()=>{
var _ref_current_parentElement;
setInToolbar(!!(ref.current && ((_ref_current_parentElement = ref.current.parentElement) === null || _ref_current_parentElement === void 0 ? void 0 : _ref_current_parentElement.closest('[role="toolbar"]'))));
});
const { direction: direction } = (0, $37ePF$reactariai18n.useLocale)();
const shouldReverse = direction === 'rtl' && orientation === 'horizontal';
let focusManager = (0, $37ePF$reactariafocus.createFocusManager)(ref);
const onKeyDown = (e)=>{
// don't handle portalled events
if (!e.currentTarget.contains(e.target)) return;
if (orientation === 'horizontal' && e.key === 'ArrowRight' || orientation === 'vertical' && e.key === 'ArrowDown') {
if (shouldReverse) focusManager.focusPrevious();
else focusManager.focusNext();
} else if (orientation === 'horizontal' && e.key === 'ArrowLeft' || orientation === 'vertical' && e.key === 'ArrowUp') {
if (shouldReverse) focusManager.focusNext();
else focusManager.focusPrevious();
} else if (e.key === 'Tab') {
// When the tab key is pressed, we want to move focus
// out of the entire toolbar. To do this, move focus
// to the first or last focusable child, and let the
// browser handle the Tab key as usual from there.
e.stopPropagation();
lastFocused.current = document.activeElement;
if (e.shiftKey) focusManager.focusFirst();
else focusManager.focusLast();
return;
} else // if we didn't handle anything, return early so we don't preventDefault
return;
// Prevent arrow keys from being handled by nested action groups.
e.stopPropagation();
e.preventDefault();
};
// Record the last focused child when focus moves out of the toolbar.
const lastFocused = (0, $37ePF$react.useRef)(null);
const onBlur = (e)=>{
if (!e.currentTarget.contains(e.relatedTarget) && !lastFocused.current) lastFocused.current = e.target;
};
// Restore focus to the last focused child when focus returns into the toolbar.
// If the element was removed, do nothing, either the first item in the first group,
// or the last item in the last group will be focused, depending on direction.
const onFocus = (e)=>{
var _ref_current;
if (lastFocused.current && !e.currentTarget.contains(e.relatedTarget) && ((_ref_current = ref.current) === null || _ref_current === void 0 ? void 0 : _ref_current.contains(e.target))) {
var _lastFocused_current;
(_lastFocused_current = lastFocused.current) === null || _lastFocused_current === void 0 ? void 0 : _lastFocused_current.focus();
lastFocused.current = null;
}
};
return {
toolbarProps: {
...(0, $37ePF$reactariautils.filterDOMProps)(props, {
labelable: true
}),
role: !isInToolbar ? 'toolbar' : 'group',
'aria-orientation': orientation,
'aria-label': ariaLabel,
'aria-labelledby': ariaLabel == null ? ariaLabelledBy : undefined,
onKeyDownCapture: !isInToolbar ? onKeyDown : undefined,
onFocusCapture: !isInToolbar ? onFocus : undefined,
onBlurCapture: !isInToolbar ? onBlur : undefined
}
};
}
//# sourceMappingURL=useToolbar.main.js.map
@@ -0,0 +1 @@
{"version":3,"file":"issue_1416.test.d.ts","sourceRoot":"","sources":["../../../../src/test/bugs/issue_1416.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,12 @@
# `@typescript-eslint/type-utils`
> Type utilities for working with TypeScript within ESLint rules.
[![NPM Version](https://img.shields.io/npm/v/@typescript-eslint/utils.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils)
[![NPM Downloads](https://img.shields.io/npm/dm/@typescript-eslint/utils.svg?style=flat-square)](https://www.npmjs.com/package/@typescript-eslint/utils)
The utilities in this package are separated from `@typescript-eslint/utils` so that that package does not require a dependency on `typescript`.
> See https://typescript-eslint.io for general documentation on typescript-eslint, the tooling that allows you to run ESLint and Prettier on TypeScript code.
<!-- Local path for docs: docs/packages/Type_Utils.mdx -->
@@ -0,0 +1,34 @@
var baseInvoke = require('./_baseInvoke'),
baseRest = require('./_baseRest');
/**
* Creates a function that invokes the method at `path` of a given object.
* Any additional arguments are provided to the invoked method.
*
* @static
* @memberOf _
* @since 3.7.0
* @category Util
* @param {Array|string} path The path of the method to invoke.
* @param {...*} [args] The arguments to invoke the method with.
* @returns {Function} Returns the new invoker function.
* @example
*
* var objects = [
* { 'a': { 'b': _.constant(2) } },
* { 'a': { 'b': _.constant(1) } }
* ];
*
* _.map(objects, _.method('a.b'));
* // => [2, 1]
*
* _.map(objects, _.method(['a', 'b']));
* // => [2, 1]
*/
var method = baseRest(function(path, args) {
return function(object) {
return baseInvoke(object, path, args);
};
});
module.exports = method;
@@ -0,0 +1,567 @@
"use client";
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
Menu: () => menu_default,
MenuItem: () => menu_item_base_default,
MenuSection: () => menu_section_base_default,
useMenu: () => useMenu
});
module.exports = __toCommonJS(src_exports);
// src/menu.tsx
var import_system4 = require("@heroui/system");
var import_theme4 = require("@heroui/theme");
// src/use-menu.ts
var import_system = require("@heroui/system");
var import_menu = require("@react-aria/menu");
var import_theme = require("@heroui/theme");
var import_tree = require("@react-stately/tree");
var import_react_utils = require("@heroui/react-utils");
var import_react = require("react");
var import_shared_utils = require("@heroui/shared-utils");
function useMenu(props) {
var _a;
const globalContext = (0, import_system.useProviderContext)();
const {
as,
ref,
variant,
color,
children,
disableAnimation = (_a = globalContext == null ? void 0 : globalContext.disableAnimation) != null ? _a : false,
onAction,
closeOnSelect,
itemClasses,
className,
state: propState,
topContent,
bottomContent,
hideEmptyContent = false,
hideSelectedIcon = false,
emptyContent = "No items.",
menuProps: userMenuProps,
onClose,
classNames,
...otherProps
} = props;
const Component = as || "ul";
const domRef = (0, import_react_utils.useDOMRef)(ref);
const shouldFilterDOMProps = typeof Component === "string";
const innerState = (0, import_tree.useTreeState)({ ...otherProps, ...userMenuProps, children });
const state = propState || innerState;
const { menuProps } = (0, import_menu.useMenu)({ ...otherProps, ...userMenuProps, onAction }, state, domRef);
const slots = (0, import_react.useMemo)(() => (0, import_theme.menu)({ className }), [className]);
const baseStyles = (0, import_shared_utils.clsx)(classNames == null ? void 0 : classNames.base, className);
const getBaseProps = (props2 = {}) => {
return {
ref: domRef,
"data-slot": "base",
className: slots.base({ class: baseStyles }),
...(0, import_react_utils.filterDOMProps)(otherProps, {
enabled: shouldFilterDOMProps
}),
...props2
};
};
const getListProps = (props2 = {}) => {
return {
"data-slot": "list",
className: slots.list({ class: classNames == null ? void 0 : classNames.list }),
...menuProps,
...props2
};
};
const getEmptyContentProps = (props2 = {}) => {
return {
children: emptyContent,
className: slots.emptyContent({ class: classNames == null ? void 0 : classNames.emptyContent }),
...props2
};
};
return {
Component,
state,
variant,
color,
disableAnimation,
onClose,
topContent,
bottomContent,
closeOnSelect,
className,
itemClasses,
getBaseProps,
getListProps,
hideEmptyContent,
hideSelectedIcon,
getEmptyContentProps
};
}
// src/menu-section.tsx
var import_theme3 = require("@heroui/theme");
var import_menu3 = require("@react-aria/menu");
var import_react4 = require("react");
var import_system3 = require("@heroui/system");
var import_utils2 = require("@react-aria/utils");
var import_shared_utils3 = require("@heroui/shared-utils");
var import_divider = require("@heroui/divider");
// src/menu-item.tsx
var import_react3 = require("react");
// src/use-menu-item.ts
var import_react2 = require("react");
var import_theme2 = require("@heroui/theme");
var import_system2 = require("@heroui/system");
var import_focus = require("@react-aria/focus");
var import_shared_utils2 = require("@heroui/shared-utils");
var import_menu2 = require("@react-aria/menu");
var import_interactions = require("@react-aria/interactions");
var import_utils = require("@react-aria/utils");
var import_use_is_mobile = require("@heroui/use-is-mobile");
var import_react_utils2 = require("@heroui/react-utils");
function useMenuItem(originalProps) {
var _a, _b;
const globalContext = (0, import_system2.useProviderContext)();
const [props, variantProps] = (0, import_system2.mapPropsVariants)(originalProps, import_theme2.menuItem.variantKeys);
const {
as,
item,
state,
shortcut,
description,
startContent,
endContent,
isVirtualized,
selectedIcon,
className,
classNames,
onAction,
autoFocus,
onPress,
onPressStart,
onPressUp,
onPressEnd,
onPressChange,
onHoverStart: hoverStartProp,
onHoverChange,
onHoverEnd,
hideSelectedIcon = false,
isReadOnly = false,
closeOnSelect,
onClose,
onClick: deprecatedOnClick,
...otherProps
} = props;
const disableAnimation = (_b = (_a = originalProps.disableAnimation) != null ? _a : globalContext == null ? void 0 : globalContext.disableAnimation) != null ? _b : false;
const domRef = (0, import_react2.useRef)(null);
const Component = as || ((otherProps == null ? void 0 : otherProps.href) ? "a" : "li");
const shouldFilterDOMProps = typeof Component === "string";
const { rendered, key } = item;
const isDisabledProp = state.disabledKeys.has(key) || originalProps.isDisabled;
const isSelectable = state.selectionManager.selectionMode !== "none";
const isMobile = (0, import_use_is_mobile.useIsMobile)();
const { isFocusVisible, focusProps } = (0, import_focus.useFocusRing)({
autoFocus
});
if (deprecatedOnClick && typeof deprecatedOnClick === "function") {
(0, import_shared_utils2.warn)(
"onClick is deprecated, please use onPress instead. See: https://github.com/heroui-inc/heroui/issues/4292",
"MenuItem"
);
}
const handlePress = (0, import_react2.useCallback)(
(e) => {
deprecatedOnClick == null ? void 0 : deprecatedOnClick(e);
onPress == null ? void 0 : onPress(e);
},
[deprecatedOnClick, onPress]
);
const {
isPressed,
isFocused,
isSelected,
isDisabled,
menuItemProps,
labelProps,
descriptionProps,
keyboardShortcutProps
} = (0, import_menu2.useMenuItem)(
{
key,
onClose,
isDisabled: isDisabledProp,
onPress: handlePress,
onPressStart,
onPressUp,
onPressEnd,
onPressChange,
"aria-label": props["aria-label"],
closeOnSelect,
isVirtualized,
onAction
},
state,
domRef
);
let { hoverProps, isHovered } = (0, import_interactions.useHover)({
isDisabled,
onHoverStart(e) {
if (!(0, import_interactions.isFocusVisible)()) {
state.selectionManager.setFocused(true);
state.selectionManager.setFocusedKey(key);
}
hoverStartProp == null ? void 0 : hoverStartProp(e);
},
onHoverChange,
onHoverEnd
});
let itemProps = menuItemProps;
const slots = (0, import_react2.useMemo)(
() => (0, import_theme2.menuItem)({
...variantProps,
isDisabled,
disableAnimation,
hasTitleTextChild: typeof rendered === "string",
hasDescriptionTextChild: typeof description === "string"
}),
[(0, import_shared_utils2.objectToDeps)(variantProps), isDisabled, disableAnimation, rendered, description]
);
const baseStyles = (0, import_shared_utils2.clsx)(classNames == null ? void 0 : classNames.base, className);
if (isReadOnly) {
itemProps = (0, import_shared_utils2.removeEvents)(itemProps);
}
const getItemProps = (props2 = {}) => ({
ref: domRef,
...(0, import_utils.mergeProps)(
isReadOnly ? {} : focusProps,
(0, import_react_utils2.filterDOMProps)(otherProps, {
enabled: shouldFilterDOMProps
}),
itemProps,
hoverProps,
props2
),
"data-focus": (0, import_shared_utils2.dataAttr)(isFocused),
"data-selectable": (0, import_shared_utils2.dataAttr)(isSelectable),
"data-hover": (0, import_shared_utils2.dataAttr)(isMobile ? isHovered || isPressed : isHovered),
"data-disabled": (0, import_shared_utils2.dataAttr)(isDisabled),
"data-selected": (0, import_shared_utils2.dataAttr)(isSelected),
"data-pressed": (0, import_shared_utils2.dataAttr)(isPressed),
"data-focus-visible": (0, import_shared_utils2.dataAttr)(isFocusVisible),
className: slots.base({ class: (0, import_shared_utils2.clsx)(baseStyles, props2.className) })
});
const getLabelProps = (props2 = {}) => ({
...(0, import_utils.mergeProps)(labelProps, props2),
className: slots.title({ class: classNames == null ? void 0 : classNames.title })
});
const getDescriptionProps = (props2 = {}) => ({
...(0, import_utils.mergeProps)(descriptionProps, props2),
className: slots.description({ class: classNames == null ? void 0 : classNames.description })
});
const getKeyboardShortcutProps = (props2 = {}) => ({
...(0, import_utils.mergeProps)(keyboardShortcutProps, props2),
className: slots.shortcut({ class: classNames == null ? void 0 : classNames.shortcut })
});
const getSelectedIconProps = (0, import_react2.useCallback)(
(props2 = {}) => {
return {
"aria-hidden": (0, import_shared_utils2.dataAttr)(true),
"data-disabled": (0, import_shared_utils2.dataAttr)(isDisabled),
className: slots.selectedIcon({ class: classNames == null ? void 0 : classNames.selectedIcon }),
...props2
};
},
[isDisabled, slots, classNames]
);
return {
Component,
domRef,
slots,
classNames,
isSelectable,
isSelected,
isDisabled,
rendered,
shortcut,
description,
startContent,
endContent,
selectedIcon,
disableAnimation,
getItemProps,
getLabelProps,
hideSelectedIcon,
getDescriptionProps,
getKeyboardShortcutProps,
getSelectedIconProps
};
}
// src/menu-selected-icon.tsx
var import_jsx_runtime = require("react/jsx-runtime");
function MenuSelectedIcon(props) {
const { isSelected, disableAnimation, ...otherProps } = props;
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
"svg",
{
"aria-hidden": "true",
"data-selected": isSelected,
role: "presentation",
viewBox: "0 0 17 18",
...otherProps,
children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
"polyline",
{
fill: "none",
points: "1 9 7 14 15 4",
stroke: "currentColor",
strokeDasharray: 22,
strokeDashoffset: isSelected ? 44 : 66,
strokeLinecap: "round",
strokeLinejoin: "round",
strokeWidth: 1.5,
style: !disableAnimation ? {
transition: "stroke-dashoffset 200ms ease"
} : {}
}
)
}
);
}
// src/menu-item.tsx
var import_jsx_runtime2 = require("react/jsx-runtime");
var MenuItem = (props) => {
const {
Component,
slots,
classNames,
rendered,
shortcut,
description,
isSelectable,
isSelected,
isDisabled,
selectedIcon,
startContent,
endContent,
disableAnimation,
hideSelectedIcon,
getItemProps,
getLabelProps,
getDescriptionProps,
getKeyboardShortcutProps,
getSelectedIconProps
} = useMenuItem(props);
const selectedContent = (0, import_react3.useMemo)(() => {
const defaultIcon = /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(MenuSelectedIcon, { disableAnimation, isSelected });
if (typeof selectedIcon === "function") {
return selectedIcon({ icon: defaultIcon, isSelected, isDisabled });
}
if (selectedIcon)
return selectedIcon;
return defaultIcon;
}, [selectedIcon, isSelected, isDisabled, disableAnimation]);
return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(Component, { ...getItemProps(), children: [
startContent,
description ? /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: slots.wrapper({ class: classNames == null ? void 0 : classNames.wrapper }), children: [
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { ...getLabelProps(), children: rendered }),
/* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { ...getDescriptionProps(), children: description })
] }) : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { ...getLabelProps(), children: rendered }),
shortcut && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("kbd", { ...getKeyboardShortcutProps(), children: shortcut }),
isSelectable && !hideSelectedIcon && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { ...getSelectedIconProps(), children: selectedContent }),
endContent
] });
};
MenuItem.displayName = "HeroUI.MenuItem";
var menu_item_default = MenuItem;
// src/menu-section.tsx
var import_jsx_runtime3 = require("react/jsx-runtime");
var MenuSection = (0, import_system3.forwardRef)(
({
item,
state,
as,
variant,
color,
disableAnimation,
onAction,
closeOnSelect,
className,
classNames,
showDivider = false,
hideSelectedIcon,
dividerProps = {},
itemClasses,
title,
...otherProps
}, _) => {
const Component = as || "li";
const slots = (0, import_react4.useMemo)(() => (0, import_theme3.menuSection)(), []);
const baseStyles = (0, import_shared_utils3.clsx)(classNames == null ? void 0 : classNames.base, className);
const dividerStyles = (0, import_shared_utils3.clsx)(classNames == null ? void 0 : classNames.divider, dividerProps == null ? void 0 : dividerProps.className);
const { itemProps, headingProps, groupProps } = (0, import_menu3.useMenuSection)({
heading: item.rendered,
"aria-label": item["aria-label"]
});
return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
Component,
{
"data-slot": "base",
...(0, import_utils2.mergeProps)(itemProps, otherProps),
className: slots.base({ class: baseStyles }),
children: [
item.rendered && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
"span",
{
...headingProps,
className: slots.heading({ class: classNames == null ? void 0 : classNames.heading }),
"data-slot": "heading",
children: item.rendered
}
),
/* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(
"ul",
{
...groupProps,
className: slots.group({ class: classNames == null ? void 0 : classNames.group }),
"data-has-title": !!item.rendered,
"data-slot": "group",
children: [
[...item.childNodes].map((node) => {
const { key: nodeKey, props: nodeProps } = node;
let menuItem2 = /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
menu_item_default,
{
classNames: itemClasses,
closeOnSelect,
color,
disableAnimation,
hideSelectedIcon,
item: node,
state,
variant,
onAction,
...nodeProps
},
nodeKey
);
if (node.wrapper) {
menuItem2 = node.wrapper(menuItem2);
}
return menuItem2;
}),
showDivider && /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(
import_divider.Divider,
{
as: "li",
className: slots.divider({
class: dividerStyles
}),
...dividerProps
}
)
]
}
)
]
}
);
}
);
MenuSection.displayName = "HeroUI.MenuSection";
var menu_section_default = MenuSection;
// src/menu.tsx
var import_jsx_runtime4 = require("react/jsx-runtime");
var Menu = (0, import_system4.forwardRef)(function Menu2(props, ref) {
const {
Component,
state,
closeOnSelect,
color,
disableAnimation,
hideSelectedIcon,
hideEmptyContent,
variant,
onClose,
topContent,
bottomContent,
itemClasses,
getBaseProps,
getListProps,
getEmptyContentProps
} = useMenu({ ...props, ref });
const content = /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)(Component, { ...getListProps(), children: [
!state.collection.size && !hideEmptyContent && /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("li", { children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)("div", { ...getEmptyContentProps() }) }),
[...state.collection].map((item) => {
const itemProps = {
closeOnSelect,
color,
disableAnimation,
item,
state,
variant,
onClose,
hideSelectedIcon,
...item.props
};
const mergedItemClasses = (0, import_theme4.mergeClasses)(itemClasses, itemProps == null ? void 0 : itemProps.classNames);
if (item.type === "section") {
return /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(menu_section_default, { ...itemProps, itemClasses: mergedItemClasses }, item.key);
}
let menuItem2 = /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(menu_item_default, { ...itemProps, classNames: mergedItemClasses }, item.key);
if (item.wrapper) {
menuItem2 = item.wrapper(menuItem2);
}
return menuItem2;
})
] });
return /* @__PURE__ */ (0, import_jsx_runtime4.jsxs)("div", { ...getBaseProps(), children: [
topContent,
content,
bottomContent
] });
});
var menu_default = Menu;
// src/base/menu-item-base.tsx
var import_aria_utils = require("@heroui/aria-utils");
var MenuItemBase = import_aria_utils.BaseItem;
var menu_item_base_default = MenuItemBase;
// src/base/menu-section-base.tsx
var import_aria_utils2 = require("@heroui/aria-utils");
var MenuSectionBase = import_aria_utils2.BaseSection;
var menu_section_base_default = MenuSectionBase;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Menu,
MenuItem,
MenuSection,
useMenu
});
@@ -0,0 +1,40 @@
import areInputsEqual from './are-inputs-equal';
// Using ReadonlyArray<T> rather than readonly T as it works with TS v3
export type EqualityFn = (newArgs: any[], lastArgs: any[]) => boolean;
function memoizeOne<
// Need to use 'any' rather than 'unknown' here as it has
// The correct Generic narrowing behaviour.
ResultFn extends (this: any, ...newArgs: any[]) => ReturnType<ResultFn>
>(resultFn: ResultFn, isEqual: EqualityFn = areInputsEqual): ResultFn {
let lastThis: unknown;
let lastArgs: unknown[] = [];
let lastResult: ReturnType<ResultFn>;
let calledOnce: boolean = false;
// breaking cache when context (this) or arguments change
function memoized(this: unknown, ...newArgs: unknown[]): ReturnType<ResultFn> {
if (calledOnce && lastThis === this && isEqual(newArgs, lastArgs)) {
return lastResult;
}
// Throwing during an assignment aborts the assignment: https://codepen.io/alexreardon/pen/RYKoaz
// Doing the lastResult assignment first so that if it throws
// nothing will be overwritten
lastResult = resultFn.apply(this, newArgs);
calledOnce = true;
lastThis = this;
lastArgs = newArgs;
return lastResult;
}
return memoized as ResultFn;
}
// default export
export default memoizeOne;
// disabled for now as mixing named and
// default exports is problematic with CommonJS
// export { memoizeOne };
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2014 Yannick Croissant
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.
@@ -0,0 +1,30 @@
{
"maxdepth": 4,
"maxstatements": 200,
"maxcomplexity": 12,
"maxlen": 80,
"maxparams": 5,
"curly": true,
"eqeqeq": true,
"immed": true,
"latedef": false,
"noarg": true,
"noempty": true,
"nonew": true,
"undef": true,
"unused": "vars",
"trailing": true,
"quotmark": true,
"expr": true,
"asi": true,
"browser": false,
"esnext": true,
"devel": false,
"node": false,
"nonstandard": false,
"predef": ["require", "module", "__dirname", "__filename"]
}
@@ -0,0 +1,61 @@
import {Primitive} from './primitive';
/**
Convert `object`s, `Map`s, `Set`s, and `Array`s and all of their keys/elements into immutable structures recursively.
This is useful when a deeply nested structure needs to be exposed as completely immutable, for example, an imported JSON module or when receiving an API response that is passed around.
Please upvote [this issue](https://github.com/microsoft/TypeScript/issues/13923) if you want to have this type as a built-in in TypeScript.
@example
```
// data.json
{
"foo": ["bar"]
}
// main.ts
import {ReadonlyDeep} from 'type-fest';
import dataJson = require('./data.json');
const data: ReadonlyDeep<typeof dataJson> = dataJson;
export default data;
// test.ts
import data from './main';
data.foo.push('bar');
//=> error TS2339: Property 'push' does not exist on type 'readonly string[]'
```
@category Utilities
*/
export type ReadonlyDeep<T> = T extends Primitive | ((...arguments: any[]) => unknown)
? T
: T extends ReadonlyMap<infer KeyType, infer ValueType>
? ReadonlyMapDeep<KeyType, ValueType>
: T extends ReadonlySet<infer ItemType>
? ReadonlySetDeep<ItemType>
: T extends object
? ReadonlyObjectDeep<T>
: unknown;
/**
Same as `ReadonlyDeep`, but accepts only `ReadonlyMap`s as inputs. Internal helper for `ReadonlyDeep`.
*/
interface ReadonlyMapDeep<KeyType, ValueType>
extends ReadonlyMap<ReadonlyDeep<KeyType>, ReadonlyDeep<ValueType>> {}
/**
Same as `ReadonlyDeep`, but accepts only `ReadonlySet`s as inputs. Internal helper for `ReadonlyDeep`.
*/
interface ReadonlySetDeep<ItemType>
extends ReadonlySet<ReadonlyDeep<ItemType>> {}
/**
Same as `ReadonlyDeep`, but accepts only `object`s as inputs. Internal helper for `ReadonlyDeep`.
*/
type ReadonlyObjectDeep<ObjectType extends object> = {
readonly [KeyType in keyof ObjectType]: ReadonlyDeep<ObjectType[KeyType]>
};
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const registry_base_1 = require("./registry-base");
class Registry extends registry_base_1.default {
}
exports.default = Registry;
@@ -0,0 +1,24 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./finite"), exports);
__exportStar(require("./generate"), exports);
__exportStar(require("./syntax"), exports);
__exportStar(require("./parse"), exports);
__exportStar(require("./pattern"), exports);
__exportStar(require("./union"), exports);
__exportStar(require("./template-literal"), exports);
@@ -0,0 +1,232 @@
# Metadata Reflection API
NOTE: Now that both [Decorators](https://github.com/tc39/proposal-decorators) and
[Decorator Metadata](https://github.com/tc39/proposal-decorator-metadata) have achieved Stage 3 within TC39, the API
proposed below is no longer being considered for standardization. However, this package will continue to support
projects that leverage TypeScript's legacy `--experimentalDecorators` option as some projects may not be able to migrate
to use standard decorators.
* [Detailed proposal][metadata-spec]
## Installation
```
npm install reflect-metadata
```
## Usage
### ES Modules in NodeJS/Browser, TypeScript/Babel, Bundlers
```ts
// - Modifies global `Reflect` object (or defines one in ES5 runtimes).
// - Supports ESM and CommonJS.
// - Contains internal polyfills for `Map`, `Set`, and `WeakMap` for older runtimes.
import "reflect-metadata";
// - Modifies global `Reflect` object (or defines one in ES5 runtimes).
// - Supports ESM and CommonJS.
// - Requires runtime support for `"exports"` in `package.json`.
// - Does not include internal polyfills.
import "reflect-metadata/lite";
```
### CommonJS
```ts
// - Modifies global `Reflect` object (or defines one in ES5 runtimes).
// - Contains internal polyfills for `Map`, `Set`, and `WeakMap` for older runtimes.
require("reflect-metadata");
// - Modifies global `Reflect` object (or defines one in ES5 runtimes).
// - Requires runtime support for `"exports"` in `package.json`.
// - Does not include internal polyfills.
require("reflect-metadata/lite");
```
### In the Browser via `<script>`
**HTML**
```html
<!-- Modifies global `Reflect` object (or defines one in ES5 runtimes). -->
<!-- Contains internal polyfills for `Map`, `Set`, and `WeakMap` for older runtimes. -->
<script src="path/to/reflect-metadata/Reflect.js"></script>
<!-- Modifies global `Reflect` object (or defines one in ES5 runtimes). -->
<!-- Does not include internal polyfills. -->
<script src="path/to/reflect-metadata/ReflectLite.js"></script>
```
**Script**
```js
// - Makes types available in your editor.
/// <reference path="path/to/reflect-metadata/standalone.d.ts" />
```
## Background
* Decorators add the ability to augment a class and its members as the class is defined, through a declarative syntax.
* [Traceur][traceur] attaches annotations to a static property on the class.
* Languages like C# (.NET), and Java support attributes or annotations that add metadata to types, along with a reflective API for reading metadata.
## Goals
* A number of use cases (Composition/Dependency Injection, Runtime Type Assertions, Reflection/Mirroring, Testing) want the ability to add additional metadata to a class in a consistent manner.
* A consistent approach is needed for various tools and libraries to be able to reason over metadata.
* Metadata-producing decorators (nee. "Annotations") need to be generally composable with mutating decorators.
* Metadata should be available not only on an object but also through a Proxy, with related traps.
* Defining new metadata-producing decorators should not be arduous or over-complex for a developer.
* Metadata should be consistent with other language and runtime features of ECMAScript.
## Syntax
* Declarative definition of metadata:
```JavaScript
class C {
@Reflect.metadata(metadataKey, metadataValue)
method() {
}
}
```
* Imperative definition of metadata:
```JavaScript
Reflect.defineMetadata(metadataKey, metadataValue, C.prototype, "method");
```
* Imperative introspection of metadata:
```JavaScript
let obj = new C();
let metadataValue = Reflect.getMetadata(metadataKey, obj, "method");
```
## Semantics
* Object has a new \[\[Metadata\]\] internal property that will contain a Map whose keys are property keys (or **undefined**) and whose values are Maps of metadata keys to metadata values.
* Object will have a number of new internal methods for \[\[DefineOwnMetadata\]\], \[\[GetOwnMetadata\]\], \[\[HasOwnMetadata\]\], etc.
* These internal methods can be overridden by a Proxy to support additional traps.
* These internal methods will by default call a set of abstract operations to define and read metadata.
* The Reflect object will expose the MOP operations to allow imperative access to metadata.
* Metadata defined on class declaration *C* is stored in *C*.\[\[Metadata\]\], with **undefined** as the key.
* Metadata defined on static members of class declaration *C* are stored in *C*.\[\[Metadata\]\], with the property key as the key.
* Metadata defined on instance members of class declaration *C* are stored in *C*.prototype.\[\[Metadata\]\], with the property key as the key.
## API
```JavaScript
// define metadata on an object or property
Reflect.defineMetadata(metadataKey, metadataValue, target);
Reflect.defineMetadata(metadataKey, metadataValue, target, propertyKey);
// check for presence of a metadata key on the prototype chain of an object or property
let result = Reflect.hasMetadata(metadataKey, target);
let result = Reflect.hasMetadata(metadataKey, target, propertyKey);
// check for presence of an own metadata key of an object or property
let result = Reflect.hasOwnMetadata(metadataKey, target);
let result = Reflect.hasOwnMetadata(metadataKey, target, propertyKey);
// get metadata value of a metadata key on the prototype chain of an object or property
let result = Reflect.getMetadata(metadataKey, target);
let result = Reflect.getMetadata(metadataKey, target, propertyKey);
// get metadata value of an own metadata key of an object or property
let result = Reflect.getOwnMetadata(metadataKey, target);
let result = Reflect.getOwnMetadata(metadataKey, target, propertyKey);
// get all metadata keys on the prototype chain of an object or property
let result = Reflect.getMetadataKeys(target);
let result = Reflect.getMetadataKeys(target, propertyKey);
// get all own metadata keys of an object or property
let result = Reflect.getOwnMetadataKeys(target);
let result = Reflect.getOwnMetadataKeys(target, propertyKey);
// delete metadata from an object or property
let result = Reflect.deleteMetadata(metadataKey, target);
let result = Reflect.deleteMetadata(metadataKey, target, propertyKey);
// apply metadata via a decorator to a constructor
@Reflect.metadata(metadataKey, metadataValue)
class C {
// apply metadata via a decorator to a method (property)
@Reflect.metadata(metadataKey, metadataValue)
method() {
}
}
```
## Alternatives
* Use properties rather than a separate API.
* Obvious downside is that this can be a lot of code:
```JavaScript
function ParamTypes(...types) {
return (target, propertyKey) => {
const symParamTypes = Symbol.for("design:paramtypes");
if (propertyKey === undefined) {
target[symParamTypes] = types;
}
else {
const symProperties = Symbol.for("design:properties");
let properties, property;
if (Object.prototype.hasOwnProperty.call(target, symProperties)) {
properties = target[symProperties];
}
else {
properties = target[symProperties] = {};
}
if (Object.prototype.hasOwnProperty.call(properties, propertyKey)) {
property = properties[propertyKey];
}
else {
property = properties[propertyKey] = {};
}
property[symParamTypes] = types;
}
};
}
```
## Notes
* Though it may seem counterintuitive, the methods on Reflect place the parameters for the metadata key and metadata value before the target or property key. This is due to the fact that the property key is the only optional parameter in the argument list. This also makes the methods easier to curry with Function#bind. This also helps reduce the overall footprint and complexity of a metadata-producing decorator that could target both a class or a property:
```JavaScript
function ParamTypes(...types) {
// as propertyKey is effectively optional, its easier to use here
return (target, propertyKey) => { Reflect.defineMetadata("design:paramtypes", types, target, propertyKey); }
// vs. having multiple overloads with the target and key in the front:
//
// return (target, propertyKey) => {
// if (propertyKey === undefined) {
// Reflect.defineMetadata(target, "design:paramtypes", types);
// }
// else {
// Reflect.defineMetadata(target, propertyKey, "design:paramtypes", types);
// }
// }
//
// vs. having a different methods for the class or a property:
//
// return (target, propertyKey) => {
// if (propertyKey === undefined) {
// Reflect.defineMetadata(target, "design:paramtypes", types);
// }
// else {
// Reflect.definePropertyMetadata(target, propertyKey, "design:paramtypes", types);
// }
// }
}
```
* To enable experimental support for metadata decorators in your TypeScript project, you must add `"experimentalDecorators": true` to your tsconfig.json file.
* To enable experimental support for auto-generated type metadata in your TypeScript project, you must add `"emitDecoratorMetadata": true` to your tsconfig.json file.
* Please note that auto-generated type metadata may have issues with circular or forward references for types.
## Issues
* A poorly written mutating decorator for a class constructor could cause metadata to become lost if the prototype chain is not maintained. Though, not maintaining the prototype chain in a mutating decorator for a class constructor would have other negative side effects as well. @rbuckton
* This is mitigated if the mutating decorator returns a class expression that extends from the target, or returns a proxy for the decorator. @rbuckton
* Metadata for a method is attached to the class (or prototype) via the property key. It would not then be available if trying to read metadata on the function of the method (e.g. "tearing-off" the method from the class). @rbuckton
[metadata-spec]: https://rbuckton.github.io/reflect-metadata
[traceur]: https://github.com/google/traceur-compiler
@@ -0,0 +1 @@
{"version":3,"names":["_index","require","BLOCK_SCOPED_SYMBOL","Symbol","for","isVar","node","isVariableDeclaration","kind"],"sources":["../../src/validators/isVar.ts"],"sourcesContent":["import { isVariableDeclaration } from \"./generated/index.ts\";\nimport type * as t from \"../index.ts\";\n\nif (!process.env.BABEL_8_BREAKING) {\n // eslint-disable-next-line no-var\n var BLOCK_SCOPED_SYMBOL = Symbol.for(\"var used to be block scoped\");\n}\n\n/**\n * Check if the input `node` is a variable declaration.\n */\nexport default function isVar(node: t.Node | null | undefined): boolean {\n if (process.env.BABEL_8_BREAKING) {\n return isVariableDeclaration(node) && node.kind === \"var\";\n } else {\n return (\n isVariableDeclaration(node, { kind: \"var\" }) &&\n !(\n // @ts-expect-error document private properties\n node[BLOCK_SCOPED_SYMBOL]\n )\n );\n }\n}\n"],"mappings":";;;;;;AAAA,IAAAA,MAAA,GAAAC,OAAA;AAGmC;EAEjC,IAAIC,mBAAmB,GAAGC,MAAM,CAACC,GAAG,CAAC,6BAA6B,CAAC;AACrE;AAKe,SAASC,KAAKA,CAACC,IAA+B,EAAW;EAG/D;IACL,OACE,IAAAC,4BAAqB,EAACD,IAAI,EAAE;MAAEE,IAAI,EAAE;IAAM,CAAC,CAAC,IAC5C,CAEEF,IAAI,CAACJ,mBAAmB,CACzB;EAEL;AACF","ignoreList":[]}
@@ -0,0 +1,27 @@
/**
* @import {Info, Space} from 'property-information'
*/
import {Schema} from './schema.js'
/**
* @param {ReadonlyArray<Schema>} definitions
* Definitions.
* @param {Space | undefined} [space]
* Space.
* @returns {Schema}
* Schema.
*/
export function merge(definitions, space) {
/** @type {Record<string, Info>} */
const property = {}
/** @type {Record<string, string>} */
const normal = {}
for (const definition of definitions) {
Object.assign(property, definition.property)
Object.assign(normal, definition.normal)
}
return new Schema(property, normal, space)
}
@@ -0,0 +1 @@
{"version":3,"file":"base-url.replacer.js","sourceRoot":"","sources":["../../src/replacers/base-url.replacer.ts"],"names":[],"mappings":";;AAQA,gDAAiD;AACjD,+BAAyC;AAEzC,oCAA0C;AAE1C,SAAwB,oBAAoB,CAAC,EAC3C,IAAI,EACJ,IAAI,EACJ,MAAM,EACiB;;IACvB,MAAM,cAAc,GAAG,MAAA,MAAA,IAAI,CAAC,KAAK,CAAC,IAAA,sBAAc,GAAE,CAAC,0CAAE,MAAM,0CAAE,IAAI,CAAC;IAClE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,sCAAsC,EAAE,cAAc,CAAC,CAAC;IAC5E,MAAM,CAAC,MAAM,CAAC,MAAM,CAClB,OAAO,cAAc,IAAI,QAAQ,EACjC,uCAAuC,IAAI,EAAE,CAC9C,CAAC;IAGF,IAAI,cAAc,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;QAClC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,sCAAsC,CAAC,CAAC;QAC5D,OAAO,IAAI,CAAC;KACb;IAGD,IACE,MAAM,CAAC,SAAS,CAAC,mBAAmB,CAAC,GAAG,MAAM,CAAC,OAAO,IAAI,cAAc,EAAE,CAAC,EAC3E;QACA,IAAI,YAAY,GAAW,aAAa,CACtC,IAAA,eAAQ,EACN,IAAA,cAAO,EAAC,IAAI,CAAC,EACb,MAAM,CAAC,SAAS;aACb,oBAAoB,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,CAAC;aACxC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CACtB,CACF,CAAC;QACF,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;YACjC,YAAY,GAAG,IAAI,GAAG,YAAY,CAAC;SACpC;QACD,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,oCAAoC,EAAE,YAAY,CAAC,CAAC;QAExE,MAAM,KAAK,GAAG,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;QAC3C,MAAM,eAAe,GACnB,IAAI,CAAC,SAAS,CAAC,CAAC,EAAE,KAAK,CAAC,GAAG,YAAY,GAAG,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;QACxE,MAAM,CAAC,MAAM,CAAC,KAAK,CACjB,uCAAuC,EACvC,eAAe,CAChB,CAAC;QAEF,MAAM,UAAU,GAAG,eAAe,CAAC,KAAK,CAAC,IAAA,sBAAc,GAAE,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC;QACvE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,kCAAkC,EAAE,UAAU,CAAC,CAAC;QACpE,OAAO,eAAe,CAAC,OAAO,CAAC,UAAU,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC,CAAC;KACvE;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAhDD,uCAgDC","sourcesContent":["/**\n * @file\n *\n * The baseUrl replacer replaces the import statement\n * with the baseUrl + import statement location.\n */\n\n/** */\nimport normalizePath = require('normalize-path');\nimport { dirname, relative } from 'path';\nimport { AliasReplacerArguments } from '../interfaces';\nimport { newStringRegex } from '../utils';\n\nexport default function replaceBaseUrlImport({\n orig,\n file,\n config\n}: AliasReplacerArguments): string {\n const requiredModule = orig.match(newStringRegex())?.groups?.path;\n config.output.debug('base-url replacer - requiredModule: ', requiredModule);\n config.output.assert(\n typeof requiredModule == 'string',\n `Unexpected import statement pattern ${orig}`\n );\n\n // Check if import is already resolved.\n if (requiredModule.startsWith('.')) {\n config.output.debug('base-url replacer - already resolved');\n return orig;\n }\n\n // If there are files matching the target, resolve the path.\n if (\n config.pathCache.existsResolvedAlias(`${config.outPath}/${requiredModule}`)\n ) {\n let relativePath: string = normalizePath(\n relative(\n dirname(file),\n config.pathCache\n .getAbsoluteAliasPath(config.outPath, '')\n .replace('---', '')\n )\n );\n if (!relativePath.startsWith('.')) {\n relativePath = './' + relativePath;\n }\n config.output.debug('base-url replacer - relativePath: ', relativePath);\n\n const index = orig.indexOf(requiredModule);\n const newImportScript =\n orig.substring(0, index) + relativePath + '/' + orig.substring(index);\n config.output.debug(\n 'base-url replacer - newImportScript: ',\n newImportScript\n );\n\n const modulePath = newImportScript.match(newStringRegex()).groups.path;\n config.output.debug('base-url replacer - modulePath: ', modulePath);\n return newImportScript.replace(modulePath, normalizePath(modulePath));\n }\n return orig;\n}\n"]}
@@ -0,0 +1,387 @@
/**
* This is a fork of https://github.com/DefinitelyTyped/DefinitelyTyped/blob/13f63c2eb8d7479caf01ab8d72f9e3683368a8f5/types/json-schema/index.d.ts
* We intentionally fork this because:
* - ESLint ***ONLY*** supports JSONSchema v4
* - We want to provide stricter types
*/
/**
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1
*/
export type JSONSchema4TypeName = 'any' | 'array' | 'boolean' | 'integer' | 'null' | 'number' | 'object' | 'string';
/**
* @see https://tools.ietf.org/html/draft-zyp-json-schema-04#section-3.5
*/
export type JSONSchema4Type = boolean | number | string | null;
export type JSONSchema4TypeExtended = JSONSchema4Array | JSONSchema4Object | JSONSchema4Type;
export interface JSONSchema4Object {
[key: string]: JSONSchema4TypeExtended;
}
export interface JSONSchema4Array extends Array<JSONSchema4TypeExtended> {
}
/**
* Meta schema
*
* Recommended values:
* - 'http://json-schema.org/schema#'
* - 'http://json-schema.org/hyper-schema#'
* - 'http://json-schema.org/draft-04/schema#'
* - 'http://json-schema.org/draft-04/hyper-schema#'
* - 'http://json-schema.org/draft-03/schema#'
* - 'http://json-schema.org/draft-03/hyper-schema#'
*
* @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5
*/
export type JSONSchema4Version = string;
/**
* JSON Schema V4
* @see https://tools.ietf.org/html/draft-zyp-json-schema-04
*/
export type JSONSchema4 = JSONSchema4AllOfSchema | JSONSchema4AnyOfSchema | JSONSchema4AnySchema | JSONSchema4ArraySchema | JSONSchema4BooleanSchema | JSONSchema4MultiSchema | JSONSchema4NullSchema | JSONSchema4NumberSchema | JSONSchema4ObjectSchema | JSONSchema4OneOfSchema | JSONSchema4RefSchema | JSONSchema4StringSchema;
interface JSONSchema4Base {
/**
* Reusable definitions that can be referenced via `$ref`
*/
$defs?: Record<string, JSONSchema4> | undefined;
/**
* Path to a schema defined in `definitions`/`$defs` that will form the base
* for this schema.
*
* If you are defining an "array" schema (`schema: [ ... ]`) for your rule
* then you should prefix this with `items/0` so that the validator can find
* your definitions.
*
* eg: `'#/items/0/definitions/myDef'`
*
* Otherwise if you are defining an "object" schema (`schema: { ... }`) for
* your rule you can directly reference your definitions
*
* eg: `'#/definitions/myDef'`
*/
$ref?: string | undefined;
$schema?: JSONSchema4Version | undefined;
/**
* (AND) Must be valid against all of the sub-schemas
*/
allOf?: JSONSchema4[] | undefined;
/**
* (OR) Must be valid against any of the sub-schemas
*/
anyOf?: JSONSchema4[] | undefined;
/**
* The default value for the item if not present
*/
default?: JSONSchema4TypeExtended | undefined;
/**
* Reusable definitions that can be referenced via `$ref`
*/
definitions?: Record<string, JSONSchema4> | undefined;
/**
* This attribute is a string that provides a full description of the of
* purpose the instance property.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.22
*/
description?: string | undefined;
/**
* The value of this property MUST be another schema which will provide
* a base schema which the current schema will inherit from. The
* inheritance rules are such that any instance that is valid according
* to the current schema MUST be valid according to the referenced
* schema. This MAY also be an array, in which case, the instance MUST
* be valid for all the schemas in the array. A schema that extends
* another schema MAY define additional attributes, constrain existing
* attributes, or add other constraints.
*
* Conceptually, the behavior of extends can be seen as validating an
* instance against all constraints in the extending schema as well as
* the extended schema(s).
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.26
*/
extends?: string | string[] | undefined;
id?: string | undefined;
/**
* (NOT) Must not be valid against the given schema
*/
not?: JSONSchema4 | undefined;
/**
* (XOR) Must be valid against exactly one of the sub-schemas
*/
oneOf?: JSONSchema4[] | undefined;
/**
* This attribute indicates if the instance must have a value, and not
* be undefined. This is false by default, making the instance
* optional.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.7
*/
required?: boolean | string[] | undefined;
/**
* This attribute is a string that provides a short description of the
* instance property.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.21
*/
title?: string | undefined;
/**
* A single type, or a union of simple types
*/
type?: JSONSchema4TypeName | JSONSchema4TypeName[] | undefined;
}
export interface JSONSchema4RefSchema extends JSONSchema4Base {
$ref: string;
type?: undefined;
}
export interface JSONSchema4AllOfSchema extends JSONSchema4Base {
allOf: JSONSchema4[];
type?: undefined;
}
export interface JSONSchema4AnyOfSchema extends JSONSchema4Base {
anyOf: JSONSchema4[];
type?: undefined;
}
export interface JSONSchema4OneOfSchema extends JSONSchema4Base {
oneOf: JSONSchema4[];
type?: undefined;
}
export interface JSONSchema4MultiSchema extends Omit<JSONSchema4ObjectSchema, 'enum' | 'type'>, Omit<JSONSchema4ArraySchema, 'enum' | 'type'>, Omit<JSONSchema4StringSchema, 'enum' | 'type'>, Omit<JSONSchema4NumberSchema, 'enum' | 'type'>, Omit<JSONSchema4BooleanSchema, 'enum' | 'type'>, Omit<JSONSchema4NullSchema, 'enum' | 'type'>, Omit<JSONSchema4AnySchema, 'enum' | 'type'> {
/**
* This provides an enumeration of all possible values that are valid
* for the instance property. This MUST be an array, and each item in
* the array represents a possible value for the instance value. If
* this attribute is defined, the instance value MUST be one of the
* values in the array in order for the schema to be valid.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.19
*/
enum?: JSONSchema4Type[];
type: JSONSchema4TypeName[];
}
/**
* @see https://json-schema.org/understanding-json-schema/reference/object.html
*/
export interface JSONSchema4ObjectSchema extends JSONSchema4Base {
/**
* This attribute defines a schema for all properties that are not
* explicitly defined in an object type definition. If specified, the
* value MUST be a schema or a boolean. If false is provided, no
* additional properties are allowed beyond the properties defined in
* the schema. The default value is an empty schema which allows any
* value for additional properties.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.4
*/
additionalProperties?: boolean | JSONSchema4 | undefined;
/**
* The `dependencies` keyword conditionally applies a sub-schema when a given
* property is present. This schema is applied in the same way `allOf` applies
* schemas. Nothing is merged or extended. Both schemas apply independently.
*/
dependencies?: Record<string, JSONSchema4 | string[]> | undefined;
/**
* The maximum number of properties allowed for record-style schemas
*/
maxProperties?: number | undefined;
/**
* The minimum number of properties required for record-style schemas
*/
minProperties?: number | undefined;
/**
* This attribute is an object that defines the schema for a set of
* property names of an object instance. The name of each property of
* this attribute's object is a regular expression pattern in the ECMA
* 262/Perl 5 format, while the value is a schema. If the pattern
* matches the name of a property on the instance object, the value of
* the instance's property MUST be valid against the pattern name's
* schema value.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.3
*/
patternProperties?: Record<string, JSONSchema4> | undefined;
/**
* This attribute is an object with property definitions that define the
* valid values of instance object property values. When the instance
* value is an object, the property values of the instance object MUST
* conform to the property definitions in this object. In this object,
* each property definition's value MUST be a schema, and the property's
* name MUST be the name of the instance property that it defines. The
* instance property value MUST be valid according to the schema from
* the property definition. Properties are considered unordered, the
* order of the instance properties MAY be in any order.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.2
*/
properties?: Record<string, JSONSchema4> | undefined;
type: 'object';
}
/**
* @see https://json-schema.org/understanding-json-schema/reference/array.html
*/
export interface JSONSchema4ArraySchema extends JSONSchema4Base {
/**
* May only be defined when "items" is defined, and is a tuple of JSONSchemas.
*
* This provides a definition for additional items in an array instance
* when tuple definitions of the items is provided. This can be false
* to indicate additional items in the array are not allowed, or it can
* be a schema that defines the schema of the additional items.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.6
*/
additionalItems?: boolean | JSONSchema4 | undefined;
/**
* This attribute defines the allowed items in an instance array, and
* MUST be a schema or an array of schemas. The default value is an
* empty schema which allows any value for items in the instance array.
*
* When this attribute value is a schema and the instance value is an
* array, then all the items in the array MUST be valid according to the
* schema.
*
* When this attribute value is an array of schemas and the instance
* value is an array, each position in the instance array MUST conform
* to the schema in the corresponding position for this array. This
* called tuple typing. When tuple typing is used, additional items are
* allowed, disallowed, or constrained by the "additionalItems"
* (Section 5.6) attribute using the same rules as
* "additionalProperties" (Section 5.4) for objects.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.5
*/
items?: JSONSchema4 | JSONSchema4[] | undefined;
/**
* Defines the maximum length of an array
*/
maxItems?: number | undefined;
/**
* Defines the minimum length of an array
*/
minItems?: number | undefined;
type: 'array';
/**
* Enforces that all items in the array are unique
*/
uniqueItems?: boolean | undefined;
}
/**
* @see https://json-schema.org/understanding-json-schema/reference/string.html
*/
export interface JSONSchema4StringSchema extends JSONSchema4Base {
enum?: string[] | undefined;
/**
* The `format` keyword allows for basic semantic identification of certain
* kinds of string values that are commonly used.
*
* For example, because JSON doesn’t have a “DateTime” type, dates need to be
* encoded as strings. `format` allows the schema author to indicate that the
* string value should be interpreted as a date.
*
* ajv v6 provides a few built-in formats - all other strings will cause AJV
* to throw during schema compilation
*/
format?: 'date' | 'date-time' | 'email' | 'hostname' | 'ipv4' | 'ipv6' | 'json-pointer' | 'json-pointer-uri-fragment' | 'regex' | 'relative-json-pointer' | 'time' | 'uri' | 'uri-reference' | 'uri-template' | 'url' | 'uuid' | undefined;
/**
* The maximum allowed length for the string
*/
maxLength?: number | undefined;
/**
* The minimum allowed length for the string
*/
minLength?: number | undefined;
/**
* The `pattern` keyword is used to restrict a string to a particular regular
* expression. The regular expression syntax is the one defined in JavaScript
* (ECMA 262 specifically) with Unicode support.
*
* When defining the regular expressions, it’s important to note that the
* string is considered valid if the expression matches anywhere within the
* string. For example, the regular expression "p" will match any string with
* a p in it, such as "apple" not just a string that is simply "p". Therefore,
* it is usually less confusing, as a matter of course, to surround the
* regular expression in ^...$, for example, "^p$", unless there is a good
* reason not to do so.
*/
pattern?: string | undefined;
type: 'string';
}
/**
* @see https://json-schema.org/understanding-json-schema/reference/numeric.html
*/
export interface JSONSchema4NumberSchema extends JSONSchema4Base {
/**
* This provides an enumeration of all possible values that are valid
* for the instance property. This MUST be an array, and each item in
* the array represents a possible value for the instance value. If
* this attribute is defined, the instance value MUST be one of the
* values in the array in order for the schema to be valid.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.19
*/
enum?: number[] | undefined;
/**
* The exclusive minimum allowed value for the number
* - `true` = `x < maximum`
* - `false` = `x <= maximum`
*
* Default is `false`
*/
exclusiveMaximum?: boolean | undefined;
/**
* Indicates whether or not `minimum` is the inclusive or exclusive minimum
* - `true` = `x > minimum`
* - `false` = `x ≥ minimum`
*
* Default is `false`
*/
exclusiveMinimum?: boolean | undefined;
/**
* The maximum allowed value for the number
*/
maximum?: number | undefined;
/**
* The minimum allowed value for the number
*/
minimum?: number | undefined;
/**
* Numbers can be restricted to a multiple of a given number, using the
* `multipleOf` keyword. It may be set to any positive number.
*/
multipleOf?: number | undefined;
type: 'integer' | 'number';
}
/**
* @see https://json-schema.org/understanding-json-schema/reference/boolean.html
*/
export interface JSONSchema4BooleanSchema extends JSONSchema4Base {
/**
* This provides an enumeration of all possible values that are valid
* for the instance property. This MUST be an array, and each item in
* the array represents a possible value for the instance value. If
* this attribute is defined, the instance value MUST be one of the
* values in the array in order for the schema to be valid.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.19
*/
enum?: boolean[] | undefined;
type: 'boolean';
}
/**
* @see https://json-schema.org/understanding-json-schema/reference/null.html
*/
export interface JSONSchema4NullSchema extends JSONSchema4Base {
/**
* This provides an enumeration of all possible values that are valid
* for the instance property. This MUST be an array, and each item in
* the array represents a possible value for the instance value. If
* this attribute is defined, the instance value MUST be one of the
* values in the array in order for the schema to be valid.
*
* @see https://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.19
*/
enum?: null[] | undefined;
type: 'null';
}
export interface JSONSchema4AnySchema extends JSONSchema4Base {
type: 'any';
}
export {};
@@ -0,0 +1,43 @@
import arrayMap from './_arrayMap.js';
import baseAt from './_baseAt.js';
import basePullAt from './_basePullAt.js';
import compareAscending from './_compareAscending.js';
import flatRest from './_flatRest.js';
import isIndex from './_isIndex.js';
/**
* Removes elements from `array` corresponding to `indexes` and returns an
* array of removed elements.
*
* **Note:** Unlike `_.at`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 3.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {...(number|number[])} [indexes] The indexes of elements to remove.
* @returns {Array} Returns the new array of removed elements.
* @example
*
* var array = ['a', 'b', 'c', 'd'];
* var pulled = _.pullAt(array, [1, 3]);
*
* console.log(array);
* // => ['a', 'c']
*
* console.log(pulled);
* // => ['b', 'd']
*/
var pullAt = flatRest(function(array, indexes) {
var length = array == null ? 0 : array.length,
result = baseAt(array, indexes);
basePullAt(array, arrayMap(indexes, function(index) {
return isIndex(index, length) ? +index : index;
}).sort(compareAscending));
return result;
});
export default pullAt;
@@ -0,0 +1,34 @@
{
"root": true,
"extends": "@ljharb",
"rules": {
"new-cap": [2, {
"capIsNewExceptions": [
"ArraySpeciesCreate",
"Call",
"CreateDataPropertyOrThrow",
"FlattenIntoArray",
"Get",
"HasProperty",
"IsArray",
"IsCallable",
"Set",
"ToLength",
"ToObject",
"ToString",
]
}],
"no-magic-numbers": 0,
},
"overrides": [
{
"files": "test/**",
"rules": {
"no-invalid-this": [1],
},
},
],
}
@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.js"],"names":[],"mappings":"AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,sCAXW,OAAO,MAEP,KAAK,QAEL,SAAS,QAET,MAAM,GAAG,SAAS,GAEhB,KAAK,CA6BjB;6BAjE2C,sBAAsB;2BAAtB,sBAAsB;+BAAtB,sBAAsB"}
@@ -0,0 +1,9 @@
"use strict";
const { ESLint } = require("./eslint");
const { LegacyESLint } = require("./legacy-eslint");
module.exports = {
ESLint,
LegacyESLint,
};
@@ -0,0 +1 @@
{"name":"quill","version":"2.0.3","requiresBuild":false,"files":{"LICENSE":{"checkedAt":1794532111761,"integrity":"sha512-UhMzRxQMXgT9TNAbOfQmfYUGC+UTNIYUGDWTPFB3dmkFPJOczS1CWFq5WUnqvExGSWlV8hX4Xj/sNAlADKaI/w==","mode":420,"size":1561},"dist/quill.bubble.css":{"checkedAt":1794532111762,"integrity":"sha512-M4MnXUIUNxrSVaIonML/fbjmK8/i1LW/4OdyZ06FXfsI3l5q/7YUAsITFSSGIfR9KYmLc9itY/owdWn8gwc6sg==","mode":420,"size":25216},"dist/quill.core.css":{"checkedAt":1794532111762,"integrity":"sha512-elqNRbGk26LSBeqmaEoW+UoKdyLEyGRx0lpJmomYrFfp3UsHRoZ/OsmuZ95YQPz8aqYab/zz7jHOvzGkfMJTLg==","mode":420,"size":10229},"dist/quill.snow.css":{"checkedAt":1794532111762,"integrity":"sha512-GecPBCy3NWcWxFkCGUZd3mxtm8E0/pqYBLYF4zS3RxSs2ZjlKaswY4vd1D8N+YJXV5EwTbogvpBRIwWr6IPQ6g==","mode":420,"size":24606},"formats/align.js":{"checkedAt":1794532111762,"integrity":"sha512-IzamnOKf0MZ1nGfXLzsfSnCwQHbksAu9gBaG3MRPneshcP4HGx4kbc4TSMvavpv3vhxWaVdwriCJsZ0JuW1ytQ==","mode":420,"size":456},"formats/background.js":{"checkedAt":1794532111762,"integrity":"sha512-nIuBIRDTXP4SQWFosXZDDklN6X/Nq6S209TTduvKC7U9lHKIMXfJkS9ftMcqkT24n6pofdcXgSNk8xVWDOZtqg==","mode":420,"size":382},"themes/base.js":{"checkedAt":1794532111762,"integrity":"sha512-/GHzsSonzjpnWOS3ZKMqlqzCYKAWEM/lppJfSbex5r1as5xVUMXLE9gAz2F2wHejvXC0+tjWSiJMD35UskBdsA==","mode":420,"size":9010},"blots/block.js":{"checkedAt":1794532111763,"integrity":"sha512-NmrsUyH7svTDp57xeaKyWotvLNy2BjheFjoHNpPD2RXynALkBxw8ABVoFVNnjLInP4xf+rhNne9IWwUn/yzytA==","mode":420,"size":5461},"formats/blockquote.js":{"checkedAt":1794532111763,"integrity":"sha512-Wyx3G/RD8Mg/fAkr2Jl+hvCAKO/hth72UKcKhmF3LrrbnpuV+V8Km/yL2MZG6Aq3jOFNCMs81UJchbI6x6/CyA==","mode":420,"size":206},"formats/bold.js":{"checkedAt":1794532111763,"integrity":"sha512-dSlNHa6qGbRxyUSM4REMdtB7g6RrrA9I617mFiC773un4a45D8NDoFTBpXVLk0CnX1ral8nemg98mQzOtgWlmQ==","mode":420,"size":449},"blots/break.js":{"checkedAt":1794532111763,"integrity":"sha512-9WrhKFKqHMzY1acLrSgQfmAQuKxjcsC9NRGItJJtolB/Mp3HAsC51GjfliyOgm1lcY6tNOvcUbRcR1E/iuA8EA==","mode":420,"size":363},"themes/bubble.js":{"checkedAt":1794532111763,"integrity":"sha512-me15eThCssXhLkNscFnQMWdIE7UWrHiQD19Ak2gyHItYLh5Fu/epyiLOwT+kzeZfUAefKMLINQZcafdeA4tf5g==","mode":420,"size":4090},"modules/clipboard.js":{"checkedAt":1794532111763,"integrity":"sha512-rgPkFQ+CnbK5PgkwmOZUtyP7qjHiErzKCcIC+ILLmSZJar9m+OKUd+xICGClXPDsYRRXKW6vdxYQId9aL/QRRw==","mode":420,"size":16935},"formats/code.js":{"checkedAt":1794532111763,"integrity":"sha512-gGJYYVowsAvczWWF6NilpB8tWWYccH84VdRidc1wnRM7ITPwd87Y8vm5WTBoSpUahRm20/Lu+9mTlmGvj30KWA==","mode":420,"size":1630},"ui/color-picker.js":{"checkedAt":1794532111764,"integrity":"sha512-qQlXdmYfOrreYOm7ubav7dENZhmMMNToAXK9sutJELZYNetUxZo/AR6K6HG7ShGqUPKPmdwtuvLmV/jqK+fndQ==","mode":420,"size":961},"formats/color.js":{"checkedAt":1794532111764,"integrity":"sha512-rhn6oPTy6hZPi8ffFkMHPWEuVYGF+wI9Ys/HrA7MoqCj8Kb4x8vP2UMjKU55UTV3BeryuiaIivp6ubxl/k1lpQ==","mode":420,"size":689},"core/composition.js":{"checkedAt":1794532111764,"integrity":"sha512-NYKmFhuYmh4UmbknasLl39lrORzTp7kP+Fe9WmeuTPS6K26GtlFjsjPEqLUwF1M9n8rOkltzEDTHFzm4/AwYqA==","mode":420,"size":1471},"blots/container.js":{"checkedAt":1794532111764,"integrity":"sha512-6Bu5EI3txDC03jQcI34fv2GVpbx1ykkrYsIZ52JuIbPDeUdkR/hDO5T/MhpP1YwVsnDkHn1Ct8DHPV+KfE2//g==","mode":420,"size":147},"core.js":{"checkedAt":1794532111764,"integrity":"sha512-4JCZ4uRE6RKhc96ZMcCq6RKB854UKgOQdEeMS4he5bvDH+eqOCKyr4U67wNrVAi8DMy7StPwDUDe+n1Q4+Ob2w==","mode":420,"size":1347},"core/utils/createRegistryWithFormats.js":{"checkedAt":1794532111764,"integrity":"sha512-iLZ+Cu9A6C/J+IeOFrq7dvoeNAa7WxoZm+GSWA5whr27QyNblC3ROyCNGzK5MkvgjheCfKhn8wH2bd9793P6Ew==","mode":420,"size":1075},"blots/cursor.js":{"checkedAt":1794532111764,"integrity":"sha512-qHa7PeyBklA2h8zGGd3zs6988ggQbOyAl8eabryxKoe3wea6KPlqqA4A2yJSnzSeJJhSUpfz2VWooseAceuWcw==","mode":420,"size":5740},"formats/direction.js":{"checkedAt":1794532111765,"integrity":"sha512-cLsh2YqLVx4ZYw48q/VqnBbz5upDbSfJLHe1yBYEuCUIEwANCzvgqhZXBe/ALIPY7aNXtfTfhzb2/DtkK5Wz4w==","mode":420,"size":474},"core/editor.js":{"checkedAt":1794532111765,"integrity":"sha512-XbEepbWthdYPNtM+SAxjqEdGL/x3ko4XH3BITebnR/IBthrvGRtoKligErk2faGdtGOTpZZjo4nTDGu4PZ1/fg==","mode":420,"size":14948},"blots/embed.js":{"checkedAt":1794532111765,"integrity":"sha512-yP+JZUIvGaloVQC146bJF+d6ngr1ThfUeDuEyWjpx/S+tvVKT8RjTh1x5Y4Uay/18hR9AQ/0lYOCisRWo/6eqA==","mode":420,"size":2370},"core/emitter.js":{"checkedAt":1794532111765,"integrity":"sha512-3UiX3MWEgDI8Zbwp363iADAc/+QdG6w2tZDadbuNPoVxeAuq/HUG7m+RFGoP00ofJKUbcY/0HPG0zsxkEsSdAA==","mode":420,"size":2427},"formats/font.js":{"checkedAt":1794532111765,"integrity":"sha512-OU5Q/qJHSpoejx0Kxsr+9K3xKZCZ9aD/jeSnHzcezm/ekPMoxKHcDy0Cz4E15vIy3oQmHfJ/ulaZvfVgc2GkFg==","mode":420,"size":478},"formats/formula.js":{"checkedAt":1794532111765,"integrity":"sha512-KdIGdy3s13sQM1AmdixRn3eUzr4e1ZxsGis9y8C2jFQCJMCCiuww0U+6/RDN+/rPcmyAf99f1KuDTg3y/Kw9fQ==","mode":420,"size":826},"modules/normalizeExternalHTML/normalizers/googleDocLine truncated
@@ -0,0 +1,560 @@
var $ = Object.defineProperty;
var C = (s) => {
throw TypeError(s);
};
var D = (s, n, t) => n in s ? $(s, n, { enumerable: !0, configurable: !0, writable: !0, value: t }) : s[n] = t;
var O = (s, n, t) => D(s, typeof n != "symbol" ? n + "" : n, t), q = (s, n, t) => n.has(s) || C("Cannot " + t);
var d = (s, n, t) => (q(s, n, "read from private field"), t ? t.call(s) : n.get(s)), k = (s, n, t) => n.has(s) ? C("Cannot add the same private member more than once") : n instanceof WeakSet ? n.add(s) : n.set(s, t), f = (s, n, t, e) => (q(s, n, "write to private field"), e ? e.call(s, t) : n.set(s, t), t);
var F = (s, n, t, e) => ({
set _(r) {
f(s, n, r, t);
},
get _() {
return d(s, n, e);
}
});
// node_modules/.pnpm/yocto-queue@1.0.0/node_modules/yocto-queue/index.js
var M = class {
constructor(n) {
O(this, "value");
O(this, "next");
this.value = n;
}
}, m, w, E, g = class {
constructor() {
k(this, m);
k(this, w);
k(this, E);
this.clear();
}
enqueue(n) {
let t = new M(n);
d(this, m) ? (d(this, w).next = t, f(this, w, t)) : (f(this, m, t), f(this, w, t)), F(this, E)._++;
}
dequeue() {
let n = d(this, m);
if (n)
return f(this, m, d(this, m).next), F(this, E)._--, n.value;
}
clear() {
f(this, m, void 0), f(this, w, void 0), f(this, E, 0);
}
get size() {
return d(this, E);
}
*[Symbol.iterator]() {
let n = d(this, m);
for (; n; )
yield n.value, n = n.next;
}
};
m = new WeakMap(), w = new WeakMap(), E = new WeakMap();
// node_modules/.pnpm/p-limit@4.0.0/node_modules/p-limit/index.js
function y(s) {
if (!((Number.isInteger(s) || s === Number.POSITIVE_INFINITY) && s > 0))
throw new TypeError("Expected `concurrency` to be a number from 1 and up");
let n = new g(), t = 0, e = () => {
t--, n.size > 0 && n.dequeue()();
}, r = async (h, p, a) => {
t++;
let l = (async () => h(...a))();
p(l);
try {
await l;
} catch (T) {
}
e();
}, i = (h, p, a) => {
n.enqueue(r.bind(void 0, h, p, a)), (async () => (await Promise.resolve(), t < s && n.size > 0 && n.dequeue()()))();
}, c = (h, ...p) => new Promise((a) => {
i(h, a, p);
});
return Object.defineProperties(c, {
activeCount: {
get: () => t
},
pendingCount: {
get: () => n.size
},
clearQueue: {
value: () => {
n.clear();
}
}
}), c;
}
// src/event.ts
function o(s, n = null) {
let t = new Event(s);
return n && Object.defineProperty(t, "task", {
value: n,
enumerable: !0,
writable: !1,
configurable: !1
}), t;
}
// src/constants.ts
var G = {
1: 12.71,
2: 4.303,
3: 3.182,
4: 2.776,
5: 2.571,
6: 2.447,
7: 2.365,
8: 2.306,
9: 2.262,
10: 2.228,
11: 2.201,
12: 2.179,
13: 2.16,
14: 2.145,
15: 2.131,
16: 2.12,
17: 2.11,
18: 2.101,
19: 2.093,
20: 2.086,
21: 2.08,
22: 2.074,
23: 2.069,
24: 2.064,
25: 2.06,
26: 2.056,
27: 2.052,
28: 2.048,
29: 2.045,
30: 2.042,
31: 2.0399,
32: 2.0378,
33: 2.0357,
34: 2.0336,
35: 2.0315,
36: 2.0294,
37: 2.0273,
38: 2.0252,
39: 2.0231,
40: 2.021,
41: 2.0198,
42: 2.0186,
43: 2.0174,
44: 2.0162,
45: 2.015,
46: 2.0138,
47: 2.0126,
48: 2.0114,
49: 2.0102,
50: 2.009,
51: 2.0081,
52: 2.0072,
53: 2.0063,
54: 2.0054,
55: 2.0045,
56: 2.0036,
57: 2.0027,
58: 2.0018,
59: 2.0009,
60: 2,
61: 1.9995,
62: 1.999,
63: 1.9985,
64: 1.998,
65: 1.9975,
66: 1.997,
67: 1.9965,
68: 1.996,
69: 1.9955,
70: 1.995,
71: 1.9945,
72: 1.994,
73: 1.9935,
74: 1.993,
75: 1.9925,
76: 1.992,
77: 1.9915,
78: 1.991,
79: 1.9905,
80: 1.99,
81: 1.9897,
82: 1.9894,
83: 1.9891,
84: 1.9888,
85: 1.9885,
86: 1.9882,
87: 1.9879,
88: 1.9876,
89: 1.9873,
90: 1.987,
91: 1.9867,
92: 1.9864,
93: 1.9861,
94: 1.9858,
95: 1.9855,
96: 1.9852,
97: 1.9849,
98: 1.9846,
99: 1.9843,
100: 1.984,
101: 1.9838,
102: 1.9836,
103: 1.9834,
104: 1.9832,
105: 1.983,
106: 1.9828,
107: 1.9826,
108: 1.9824,
109: 1.9822,
110: 1.982,
111: 1.9818,
112: 1.9816,
113: 1.9814,
114: 1.9812,
115: 1.9819,
116: 1.9808,
117: 1.9806,
118: 1.9804,
119: 1.9802,
120: 1.98,
infinity: 1.96
}, N = G;
// src/utils.ts
var J = (s) => s / 1e6, U = () => J(Number(process.hrtime.bigint())), B = () => performance.now();
function W(s) {
return s !== null && typeof s == "object" && typeof s.then == "function";
}
var S = (s, n) => s.reduce((e, r) => e + (r - n) ** 2, 0) / (s.length - 1) || 0, X = (async () => {
}).constructor, Z = (s) => s.constructor === X, z = async (s) => {
if (Z(s.fn))
return !0;
try {
if (s.opts.beforeEach != null)
try {
await s.opts.beforeEach.call(s);
} catch (e) {
}
let n = s.fn(), t = W(n);
if (t)
try {
await n;
} catch (e) {
}
if (s.opts.afterEach != null)
try {
await s.opts.afterEach.call(s);
} catch (e) {
}
return t;
} catch (n) {
return !1;
}
};
// src/task.ts
var b = class extends EventTarget {
constructor(t, e, r, i = {}) {
super();
/*
* the number of times the task
* function has been executed
*/
this.runs = 0;
this.bench = t, this.name = e, this.fn = r, this.opts = i;
}
async loop(t, e) {
var T;
let r = this.bench.concurrency === "task", { threshold: i } = this.bench, c = 0, h = [];
if (this.opts.beforeAll != null)
try {
await this.opts.beforeAll.call(this);
} catch (u) {
return { error: u };
}
let p = await z(this), a = async () => {
this.opts.beforeEach != null && await this.opts.beforeEach.call(this);
let u = 0;
if (p) {
let v = this.bench.now();
await this.fn.call(this), u = this.bench.now() - v;
} else {
let v = this.bench.now();
this.fn.call(this), u = this.bench.now() - v;
}
h.push(u), c += u, this.opts.afterEach != null && await this.opts.afterEach.call(this);
}, l = y(i);
try {
let u = [];
for (; (c < t || h.length + l.activeCount + l.pendingCount < e) && !((T = this.bench.signal) != null && T.aborted); )
r ? u.push(l(a)) : await a();
u.length && await Promise.all(u);
} catch (u) {
return { error: u };
}
if (this.opts.afterAll != null)
try {
await this.opts.afterAll.call(this);
} catch (u) {
return { error: u };
}
return { samples: h };
}
/**
* run the current task and write the results in `Task.result` object
*/
async run() {
var r, i;
if ((r = this.result) != null && r.error)
return this;
this.dispatchEvent(o("start", this)), await this.bench.setup(this, "run");
let { samples: t, error: e } = await this.loop(this.bench.time, this.bench.iterations);
if (this.bench.teardown(this, "run"), t) {
let c = t.reduce((L, A) => L + A, 0);
this.runs = t.length, t.sort((L, A) => L - A);
let h = c / this.runs, p = 1e3 / h, a = t.length, l = a - 1, T = t[0], u = t[l], v = c / t.length || 0, P = S(t, v), R = Math.sqrt(P), I = R / Math.sqrt(a), _ = N[String(Math.round(l) || 1)] || N.infinity, K = I * _, j = K / v * 100, H = t[Math.ceil(a * 0.75) - 1], V = t[Math.ceil(a * 0.99) - 1], Q = t[Math.ceil(a * 0.995) - 1], Y = t[Math.ceil(a * 0.999) - 1];
if ((i = this.bench.signal) != null && i.aborted)
return this;
this.setResult({
totalTime: c,
min: T,
max: u,
hz: p,
period: h,
samples: t,
mean: v,
variance: P,
sd: R,
sem: I,
df: l,
critical: _,
moe: K,
rme: j,
p75: H,
p99: V,
p995: Q,
p999: Y
});
}
if (e) {
if (this.setResult({ error: e }), this.bench.throws)
throw e;
this.dispatchEvent(o("error", this)), this.bench.dispatchEvent(o("error", this));
}
return this.dispatchEvent(o("cycle", this)), this.bench.dispatchEvent(o("cycle", this)), this.dispatchEvent(o("complete", this)), this;
}
/**
* warmup the current task
*/
async warmup() {
var e;
if ((e = this.result) != null && e.error)
return;
this.dispatchEvent(o("warmup", this)), await this.bench.setup(this, "warmup");
let { error: t } = await this.loop(this.bench.warmupTime, this.bench.warmupIterations);
if (this.bench.teardown(this, "warmup"), t && (this.setResult({ error: t }), this.bench.throws))
throw t;
}
addEventListener(t, e, r) {
super.addEventListener(t, e, r);
}
removeEventListener(t, e, r) {
super.removeEventListener(t, e, r);
}
/**
* change the result object values
*/
setResult(t) {
this.result = { ...this.result, ...t }, Object.freeze(this.result);
}
/**
* reset the task to make the `Task.runs` a zero-value and remove the `Task.result`
* object
*/
reset() {
this.dispatchEvent(o("reset", this)), this.runs = 0, this.result = void 0;
}
};
// src/bench.ts
var x = class extends EventTarget {
constructor(t = {}) {
var e, r, i, c, h, p, a, l;
super();
/*
* @private the task map
*/
this._tasks = /* @__PURE__ */ new Map();
this._todos = /* @__PURE__ */ new Map();
/**
* Executes tasks concurrently based on the specified concurrency mode.
*
* - When `mode` is set to `null` (default), concurrency is disabled.
* - When `mode` is set to 'task', each task's iterations (calls of a task function) run concurrently.
* - When `mode` is set to 'bench', different tasks within the bench run concurrently.
*/
this.concurrency = null;
/**
* The maximum number of concurrent tasks to run. Defaults to Infinity.
*/
this.threshold = 1 / 0;
this.warmupTime = 100;
this.warmupIterations = 5;
this.time = 500;
this.iterations = 10;
this.now = B;
this.now = (e = t.now) != null ? e : this.now, this.warmupTime = (r = t.warmupTime) != null ? r : this.warmupTime, this.warmupIterations = (i = t.warmupIterations) != null ? i : this.warmupIterations, this.time = (c = t.time) != null ? c : this.time, this.iterations = (h = t.iterations) != null ? h : this.iterations, this.signal = t.signal, this.throws = (p = t.throws) != null ? p : !1, this.setup = (a = t.setup) != null ? a : () => {
}, this.teardown = (l = t.teardown) != null ? l : () => {
}, this.signal && this.signal.addEventListener(
"abort",
() => {
this.dispatchEvent(o("abort"));
},
{ once: !0 }
);
}
runTask(t) {
var e;
return (e = this.signal) != null && e.aborted ? t : t.run();
}
/**
* run the added tasks that were registered using the
* {@link add} method.
* Note: This method does not do any warmup. Call {@link warmup} for that.
*/
async run() {
if (this.concurrency === "bench")
return this.runConcurrently(this.threshold, this.concurrency);
this.dispatchEvent(o("start"));
let t = [];
for (let e of [...this._tasks.values()])
t.push(await this.runTask(e));
return this.dispatchEvent(o("complete")), t;
}
/**
* See Bench.{@link concurrency}
*/
async runConcurrently(t = 1 / 0, e = "bench") {
if (this.threshold = t, this.concurrency = e, e === "task")
return this.run();
this.dispatchEvent(o("start"));
let r = y(t), i = [];
for (let h of [...this._tasks.values()])
i.push(r(() => this.runTask(h)));
let c = await Promise.all(i);
return this.dispatchEvent(o("complete")), c;
}
/**
* warmup the benchmark tasks.
* This is not run by default by the {@link run} method.
*/
async warmup() {
if (this.concurrency === "bench") {
await this.warmupConcurrently(this.threshold, this.concurrency);
return;
}
this.dispatchEvent(o("warmup"));
for (let [, t] of this._tasks)
await t.warmup();
}
/**
* warmup the benchmark tasks concurrently.
* This is not run by default by the {@link runConcurrently} method.
*/
async warmupConcurrently(t = 1 / 0, e = "bench") {
if (this.threshold = t, this.concurrency = e, e === "task") {
await this.warmup();
return;
}
this.dispatchEvent(o("warmup"));
let r = y(t), i = [];
for (let [, c] of this._tasks)
i.push(r(() => c.warmup()));
await Promise.all(i);
}
/**
* reset each task and remove its result
*/
reset() {
this.dispatchEvent(o("reset")), this._tasks.forEach((t) => {
t.reset();
});
}
/**
* add a benchmark task to the task map
*/
add(t, e, r = {}) {
let i = new b(this, t, e, r);
return this._tasks.set(t, i), this.dispatchEvent(o("add", i)), this;
}
/**
* add a benchmark todo to the todo map
*/
// eslint-disable-next-line @typescript-eslint/no-empty-function
todo(t, e = () => {
}, r = {}) {
let i = new b(this, t, e, r);
return this._todos.set(t, i), this.dispatchEvent(o("todo", i)), this;
}
/**
* remove a benchmark task from the task map
*/
remove(t) {
let e = this.getTask(t);
return e && (this.dispatchEvent(o("remove", e)), this._tasks.delete(t)), this;
}
addEventListener(t, e, r) {
super.addEventListener(t, e, r);
}
removeEventListener(t, e, r) {
super.removeEventListener(t, e, r);
}
/**
* table of the tasks results
*/
table(t) {
return this.tasks.map((e) => {
if (e.result) {
if (e.result.error)
throw e.result.error;
return (t == null ? void 0 : t(e)) || {
"Task Name": e.name,
"ops/sec": e.result.error ? "NaN" : parseInt(e.result.hz.toString(), 10).toLocaleString(),
"Average Time (ns)": e.result.error ? "NaN" : e.result.mean * 1e3 * 1e3,
Margin: e.result.error ? "NaN" : `\xB1${e.result.rme.toFixed(2)}%`,
Samples: e.result.error ? "NaN" : e.result.samples.length
};
}
return null;
});
}
/**
* (getter) tasks results as an array
*/
get results() {
return [...this._tasks.values()].map((t) => t.result);
}
/**
* (getter) tasks as an array
*/
get tasks() {
return [...this._tasks.values()];
}
get todos() {
return [...this._todos.values()];
}
/**
* get a task based on the task name
*/
getTask(t) {
return this._tasks.get(t);
}
};
export {
x as Bench,
b as Task,
U as hrtimeNow,
B as now
};
@@ -0,0 +1,110 @@
'use strict';
var utils = require('../utils.js');
require('eslint-visitor-keys');
require('espree');
require('estraverse');
var arrowSpacing = utils.createRule({
name: "arrow-spacing",
package: "js",
meta: {
type: "layout",
docs: {
description: "Enforce consistent spacing before and after the arrow in arrow functions"
},
fixable: "whitespace",
schema: [
{
type: "object",
properties: {
before: {
type: "boolean",
default: true
},
after: {
type: "boolean",
default: true
}
},
additionalProperties: false
}
],
messages: {
expectedBefore: "Missing space before =>.",
unexpectedBefore: "Unexpected space before =>.",
expectedAfter: "Missing space after =>.",
unexpectedAfter: "Unexpected space after =>."
}
},
create(context) {
const rule = Object.assign({}, context.options[0]);
rule.before = rule.before !== false;
rule.after = rule.after !== false;
const sourceCode = context.sourceCode;
function getTokens(node) {
const arrow = sourceCode.getTokenBefore(node.body, utils.isArrowToken);
return {
before: sourceCode.getTokenBefore(arrow),
arrow,
after: sourceCode.getTokenAfter(arrow)
};
}
function countSpaces(tokens) {
const before = tokens.arrow.range[0] - tokens.before.range[1];
const after = tokens.after.range[0] - tokens.arrow.range[1];
return { before, after };
}
function spaces(node) {
const tokens = getTokens(node);
const countSpace = countSpaces(tokens);
if (rule.before) {
if (countSpace.before === 0) {
context.report({
node: tokens.before,
messageId: "expectedBefore",
fix(fixer) {
return fixer.insertTextBefore(tokens.arrow, " ");
}
});
}
} else {
if (countSpace.before > 0) {
context.report({
node: tokens.before,
messageId: "unexpectedBefore",
fix(fixer) {
return fixer.removeRange([tokens.before.range[1], tokens.arrow.range[0]]);
}
});
}
}
if (rule.after) {
if (countSpace.after === 0) {
context.report({
node: tokens.after,
messageId: "expectedAfter",
fix(fixer) {
return fixer.insertTextAfter(tokens.arrow, " ");
}
});
}
} else {
if (countSpace.after > 0) {
context.report({
node: tokens.after,
messageId: "unexpectedAfter",
fix(fixer) {
return fixer.removeRange([tokens.arrow.range[1], tokens.after.range[0]]);
}
});
}
}
}
return {
ArrowFunctionExpression: spaces
};
}
});
module.exports = arrowSpacing;
@@ -0,0 +1 @@
module.exports={C:{"37":0.00783,"46":0.00391,"47":0.01174,"94":0.00391,"111":0.01174,"115":0.02739,"127":0.00391,"128":0.00783,"131":0.06261,"137":0.00391,"142":0.01174,"143":0.34826,"144":0.12913,_:"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 38 39 40 41 42 43 44 45 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 112 113 114 116 117 118 119 120 121 122 123 124 125 126 129 130 132 133 134 135 136 138 139 140 141 145 146 147 3.5 3.6"},D:{"39":0.00783,"40":0.00391,"41":0.00391,"42":0.00391,"43":0.00391,"44":0.00391,"45":0.00391,"46":0.00783,"47":0.00783,"48":0.00783,"49":0.01565,"50":0.01174,"51":0.00391,"52":0.00783,"53":0.00391,"54":0.00391,"55":0.00783,"56":0.00391,"57":0.00391,"58":0.00391,"59":0.00783,"67":0.00391,"69":0.00391,"72":0.02739,"74":0.00391,"75":0.01174,"77":0.01174,"78":0.01174,"80":0.00391,"83":0.00391,"86":0.00391,"87":0.00391,"89":0.00391,"90":0.00391,"93":0.03913,"95":0.00391,"96":0.00391,"97":0.00783,"98":0.30913,"99":0.11348,"100":0.00391,"103":0.01957,"108":0.0313,"109":0.47347,"114":0.00783,"116":0.06261,"119":0.01957,"120":0.00391,"122":0.01565,"123":0.00391,"124":0.00783,"125":3.26344,"126":0.01957,"127":0.13304,"128":0.05478,"129":0.00391,"130":0.00391,"131":0.03913,"132":0.02348,"133":0.01565,"134":0.05478,"135":0.31304,"136":0.01565,"137":0.12522,"138":0.16043,"139":0.38347,"140":5.07907,"141":12.12639,"142":0.12913,"143":0.00783,_:"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 60 61 62 63 64 65 66 68 70 71 73 76 79 81 84 85 88 91 92 94 101 102 104 105 106 107 110 111 112 113 115 117 118 121 144 145"},F:{"72":0.00391,"84":0.00783,"91":0.19174,"92":0.10174,"95":0.01957,"120":0.03913,"121":0.03522,"122":0.28565,_:"9 11 12 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 52 53 54 55 56 57 58 60 62 63 64 65 66 67 68 69 70 71 73 74 75 76 77 78 79 80 81 82 83 85 86 87 88 89 90 93 94 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 9.5-9.6 10.0-10.1 10.5 10.6 11.1 11.5 11.6 12.1"},B:{"18":0.02348,"84":0.00391,"92":0.00391,"98":0.0313,"99":0.01565,"100":0.00391,"103":0.00391,"109":0.01174,"112":0.00391,"113":0.01565,"114":0.15261,"115":0.00391,"116":0.01957,"117":0.00391,"118":0.00391,"119":0.01957,"120":0.01174,"121":0.00391,"122":0.01565,"123":0.00783,"124":0.03522,"125":0.01174,"126":0.00391,"127":0.01957,"129":0.05087,"130":0.00391,"131":0.01174,"132":0.00391,"133":0.01174,"134":0.00783,"135":0.01174,"136":0.01957,"137":0.02348,"138":0.03522,"139":0.09391,"140":0.56347,"141":3.36518,"142":0.00783,_:"12 13 14 15 16 17 79 80 81 83 85 86 87 88 89 90 91 93 94 95 96 97 101 102 104 105 106 107 108 110 111 128"},E:{_:"0 4 5 6 7 8 9 10 11 12 13 14 15 3.1 3.2 5.1 6.1 7.1 9.1 10.1 12.1 13.1 15.1 15.4 16.0 16.1 17.0 17.3 26.2","11.1":0.00391,"14.1":0.01957,"15.2-15.3":0.00391,"15.5":0.00391,"15.6":0.02348,"16.2":0.00783,"16.3":0.00391,"16.4":0.00391,"16.5":0.01174,"16.6":0.05087,"17.1":0.01565,"17.2":0.00783,"17.4":0.00391,"17.5":0.02348,"17.6":0.06261,"18.0":0.00391,"18.1":0.01174,"18.2":0.03913,"18.3":0.04696,"18.4":0.01957,"18.5-18.6":0.12522,"26.0":0.34826,"26.1":0.00391},G:{"8":0,"3.2":0,"4.0-4.1":0,"4.2-4.3":0.00067,"5.0-5.1":0,"6.0-6.1":0.00267,"7.0-7.1":0.002,"8.1-8.4":0,"9.0-9.2":0,"9.3":0.006,"10.0-10.2":0.00067,"10.3":0.01133,"11.0-11.2":0.16794,"11.3-11.4":0.004,"12.0-12.1":0.00133,"12.2-12.5":0.03265,"13.0-13.1":0,"13.2":0.00333,"13.3":0.00133,"13.4-13.7":0.00533,"14.0-14.4":0.01133,"14.5-14.8":0.012,"15.0-15.1":0.01133,"15.2-15.3":0.00866,"15.4":0.01,"15.5":0.01133,"15.6-15.8":0.14794,"16.0":0.01999,"16.1":0.03732,"16.2":0.01933,"16.3":0.03465,"16.4":0.00866,"16.5":0.01533,"16.6-16.7":0.19793,"17.0":0.01399,"17.1":0.02133,"17.2":0.01533,"17.3":0.02266,"17.4":0.03999,"17.5":0.06864,"17.6-17.7":0.17327,"18.0":0.03932,"18.1":0.0813,"18.2":0.04398,"18.3":0.14128,"18.4":0.07264,"18.5-18.6":3.70395,"26.0":0.45783,"26.1":0.01666},P:{"4":0.02062,"22":0.01031,"23":0.01031,"25":0.01031,"26":0.01031,"27":0.13402,"28":0.64946,"29":0.12371,_:"20 21 24 6.2-6.4 8.2 9.2 10.1 11.1-11.2 12.0 13.0 14.0 15.0 16.0 17.0 18.0 19.0","5.0-5.4":0.02062,"7.2-7.4":0.02062},I:{"0":0.00608,"3":0,"4":0,"2.1":0,"2.2":0,"2.3":0,"4.1":0,"4.2-4.3":0,"4.4":0,"4.4.3-4.4.4":0},K:{"0":0.71815,_:"10 11 12 11.1 11.5 12.1"},A:{"6":0.0137,"10":0.0137,_:"7 8 9 11 5.5"},S:{_:"2.5 3.0-3.1"},J:{_:"7 10"},N:{_:"10 11"},R:{_:"0"},M:{"0":0.06086},Q:{_:"14.9"},O:{"0":0.6512},H:{"0":0},L:{"0":59.17746}};
@@ -0,0 +1 @@
{"version":3,"names":["findConfigUpwards","rootDir","findPackageData","filepath","directories","pkg","isPackage","findRelativeConfig","pkgData","envName","caller","config","ignore","findRootConfig","dirname","loadConfig","name","Error","resolveShowConfigPath","ROOT_CONFIG_FILENAMES","exports","resolvePlugin","resolvePreset","loadPlugin","loadPreset"],"sources":["../../../src/config/files/index-browser.ts"],"sourcesContent":["/* c8 ignore start */\n\nimport type { Handler } from \"gensync\";\n\nimport type {\n ConfigFile,\n IgnoreFile,\n RelativeConfig,\n FilePackageData,\n} from \"./types.ts\";\n\nimport type { CallerMetadata } from \"../validation/options.ts\";\n\nexport type { ConfigFile, IgnoreFile, RelativeConfig, FilePackageData };\n\nexport function findConfigUpwards(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n rootDir: string,\n): string | null {\n return null;\n}\n\n// eslint-disable-next-line require-yield\nexport function* findPackageData(filepath: string): Handler<FilePackageData> {\n return {\n filepath,\n directories: [],\n pkg: null,\n isPackage: false,\n };\n}\n\n// eslint-disable-next-line require-yield\nexport function* findRelativeConfig(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n pkgData: FilePackageData,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler<RelativeConfig> {\n return { config: null, ignore: null };\n}\n\n// eslint-disable-next-line require-yield\nexport function* findRootConfig(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dirname: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler<ConfigFile | null> {\n return null;\n}\n\n// eslint-disable-next-line require-yield\nexport function* loadConfig(\n name: string,\n dirname: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n envName: string,\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n caller: CallerMetadata | undefined,\n): Handler<ConfigFile> {\n throw new Error(`Cannot load ${name} relative to ${dirname} in a browser`);\n}\n\n// eslint-disable-next-line require-yield\nexport function* resolveShowConfigPath(\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n dirname: string,\n): Handler<string | null> {\n return null;\n}\n\nexport const ROOT_CONFIG_FILENAMES: string[] = [];\n\ntype Resolved =\n | { loader: \"require\"; filepath: string }\n | { loader: \"import\"; filepath: string };\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function resolvePlugin(name: string, dirname: string): Resolved | null {\n return null;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport function resolvePreset(name: string, dirname: string): Resolved | null {\n return null;\n}\n\nexport function loadPlugin(\n name: string,\n dirname: string,\n): Handler<{\n filepath: string;\n value: unknown;\n}> {\n throw new Error(\n `Cannot load plugin ${name} relative to ${dirname} in a browser`,\n );\n}\n\nexport function loadPreset(\n name: string,\n dirname: string,\n): Handler<{\n filepath: string;\n value: unknown;\n}> {\n throw new Error(\n `Cannot load preset ${name} relative to ${dirname} in a browser`,\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAeO,SAASA,iBAAiBA,CAE/BC,OAAe,EACA;EACf,OAAO,IAAI;AACb;AAGO,UAAUC,eAAeA,CAACC,QAAgB,EAA4B;EAC3E,OAAO;IACLA,QAAQ;IACRC,WAAW,EAAE,EAAE;IACfC,GAAG,EAAE,IAAI;IACTC,SAAS,EAAE;EACb,CAAC;AACH;AAGO,UAAUC,kBAAkBA,CAEjCC,OAAwB,EAExBC,OAAe,EAEfC,MAAkC,EACT;EACzB,OAAO;IAAEC,MAAM,EAAE,IAAI;IAAEC,MAAM,EAAE;EAAK,CAAC;AACvC;AAGO,UAAUC,cAAcA,CAE7BC,OAAe,EAEfL,OAAe,EAEfC,MAAkC,EACN;EAC5B,OAAO,IAAI;AACb;AAGO,UAAUK,UAAUA,CACzBC,IAAY,EACZF,OAAe,EAEfL,OAAe,EAEfC,MAAkC,EACb;EACrB,MAAM,IAAIO,KAAK,CAAC,eAAeD,IAAI,gBAAgBF,OAAO,eAAe,CAAC;AAC5E;AAGO,UAAUI,qBAAqBA,CAEpCJ,OAAe,EACS;EACxB,OAAO,IAAI;AACb;AAEO,MAAMK,qBAA+B,GAAAC,OAAA,CAAAD,qBAAA,GAAG,EAAE;AAO1C,SAASE,aAAaA,CAACL,IAAY,EAAEF,OAAe,EAAmB;EAC5E,OAAO,IAAI;AACb;AAGO,SAASQ,aAAaA,CAACN,IAAY,EAAEF,OAAe,EAAmB;EAC5E,OAAO,IAAI;AACb;AAEO,SAASS,UAAUA,CACxBP,IAAY,EACZF,OAAe,EAId;EACD,MAAM,IAAIG,KAAK,CACb,sBAAsBD,IAAI,gBAAgBF,OAAO,eACnD,CAAC;AACH;AAEO,SAASU,UAAUA,CACxBR,IAAY,EACZF,OAAe,EAId;EACD,MAAM,IAAIG,KAAK,CACb,sBAAsBD,IAAI,gBAAgBF,OAAO,eACnD,CAAC;AACH;AAAC","ignoreList":[]}
@@ -0,0 +1,99 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return getModuleDependencies;
}
});
const _fs = /*#__PURE__*/ _interop_require_default(require("fs"));
const _path = /*#__PURE__*/ _interop_require_default(require("path"));
function _interop_require_default(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
let jsExtensions = [
".js",
".cjs",
".mjs"
];
// Given the current file `a.ts`, we want to make sure that when importing `b` that we resolve
// `b.ts` before `b.js`
//
// E.g.:
//
// a.ts
// b // .ts
// c // .ts
// a.js
// b // .js or .ts
let jsResolutionOrder = [
"",
".js",
".cjs",
".mjs",
".ts",
".cts",
".mts",
".jsx",
".tsx"
];
let tsResolutionOrder = [
"",
".ts",
".cts",
".mts",
".tsx",
".js",
".cjs",
".mjs",
".jsx"
];
function resolveWithExtension(file, extensions) {
// Try to find `./a.ts`, `./a.ts`, ... from `./a`
for (let ext of extensions){
let full = `${file}${ext}`;
if (_fs.default.existsSync(full) && _fs.default.statSync(full).isFile()) {
return full;
}
}
// Try to find `./a/index.js` from `./a`
for (let ext of extensions){
let full = `${file}/index${ext}`;
if (_fs.default.existsSync(full)) {
return full;
}
}
return null;
}
function* _getModuleDependencies(filename, base, seen, ext = _path.default.extname(filename)) {
// Try to find the file
let absoluteFile = resolveWithExtension(_path.default.resolve(base, filename), jsExtensions.includes(ext) ? jsResolutionOrder : tsResolutionOrder);
if (absoluteFile === null) return; // File doesn't exist
// Prevent infinite loops when there are circular dependencies
if (seen.has(absoluteFile)) return; // Already seen
seen.add(absoluteFile);
// Mark the file as a dependency
yield absoluteFile;
// Resolve new base for new imports/requires
base = _path.default.dirname(absoluteFile);
ext = _path.default.extname(absoluteFile);
let contents = _fs.default.readFileSync(absoluteFile, "utf-8");
// Find imports/requires
for (let match of [
...contents.matchAll(/import[\s\S]*?['"](.{3,}?)['"]/gi),
...contents.matchAll(/import[\s\S]*from[\s\S]*?['"](.{3,}?)['"]/gi),
...contents.matchAll(/require\(['"`](.+)['"`]\)/gi)
]){
// Bail out if it's not a relative file
if (!match[1].startsWith(".")) continue;
yield* _getModuleDependencies(match[1], base, seen, ext);
}
}
function getModuleDependencies(absoluteFilePath) {
if (absoluteFilePath === null) return new Set();
return new Set(_getModuleDependencies(absoluteFilePath, _path.default.dirname(absoluteFilePath), new Set()));
}
@@ -0,0 +1,113 @@
'use strict';
/**
*
* @param {array} node
* @param {any} options
* @returns
*/
function prettify(node, options){
return compress( node, options);
}
/**
*
* @param {array} arr
* @param {object} options
* @param {string} jPath
* @returns object
*/
function compress(arr, options, jPath){
let text;
const compressedObj = {};
for (let i = 0; i < arr.length; i++) {
const tagObj = arr[i];
const property = propName(tagObj);
let newJpath = "";
if(jPath === undefined) newJpath = property;
else newJpath = jPath + "." + property;
if(property === options.textNodeName){
if(text === undefined) text = tagObj[property];
else text += "" + tagObj[property];
}else if(property === undefined){
continue;
}else if(tagObj[property]){
let val = compress(tagObj[property], options, newJpath);
const isLeaf = isLeafTag(val, options);
if(tagObj[":@"]){
assignAttributes( val, tagObj[":@"], newJpath, options);
}else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){
val = val[options.textNodeName];
}else if(Object.keys(val).length === 0){
if(options.alwaysCreateTextNode) val[options.textNodeName] = "";
else val = "";
}
if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) {
if(!Array.isArray(compressedObj[property])) {
compressedObj[property] = [ compressedObj[property] ];
}
compressedObj[property].push(val);
}else{
//TODO: if a node is not an array, then check if it should be an array
//also determine if it is a leaf node
if (options.isArray(property, newJpath, isLeaf )) {
compressedObj[property] = [val];
}else{
compressedObj[property] = val;
}
}
}
}
// if(text && text.length > 0) compressedObj[options.textNodeName] = text;
if(typeof text === "string"){
if(text.length > 0) compressedObj[options.textNodeName] = text;
}else if(text !== undefined) compressedObj[options.textNodeName] = text;
return compressedObj;
}
function propName(obj){
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
if(key !== ":@") return key;
}
}
function assignAttributes(obj, attrMap, jpath, options){
if (attrMap) {
const keys = Object.keys(attrMap);
const len = keys.length; //don't make it inline
for (let i = 0; i < len; i++) {
const atrrName = keys[i];
if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) {
obj[atrrName] = [ attrMap[atrrName] ];
} else {
obj[atrrName] = attrMap[atrrName];
}
}
}
}
function isLeafTag(obj, options){
const { textNodeName } = options;
const propCount = Object.keys(obj).length;
if (propCount === 0) {
return true;
}
if (
propCount === 1 &&
(obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)
) {
return true;
}
return false;
}
exports.prettify = prettify;
@@ -0,0 +1,8 @@
import { defineInjectionTokenMetadata } from "../reflection-helpers";
function injectWithTransform(token, transformer, ...args) {
return defineInjectionTokenMetadata(token, {
transformToken: transformer,
args: args
});
}
export default injectWithTransform;
@@ -0,0 +1 @@
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t(require("dayjs")):"function"==typeof define&&define.amd?define(["dayjs"],t):(e="undefined"!=typeof globalThis?globalThis:e||self).dayjs_locale_nn=t(e.dayjs)}(this,(function(e){"use strict";function t(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=t(e),a={name:"nn",weekdays:"sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag".split("_"),weekdaysShort:"sun_mån_tys_ons_tor_fre_lau".split("_"),weekdaysMin:"su_må_ty_on_to_fr_la".split("_"),months:"januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"),monthsShort:"jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"),ordinal:function(e){return e+"."},weekStart:1,relativeTime:{future:"om %s",past:"for %s sidan",s:"nokre sekund",m:"eitt minutt",mm:"%d minutt",h:"ein time",hh:"%d timar",d:"ein dag",dd:"%d dagar",M:"ein månad",MM:"%d månadar",y:"eitt år",yy:"%d år"},formats:{LT:"HH:mm",LTS:"HH:mm:ss",L:"DD.MM.YYYY",LL:"D. MMMM YYYY",LLL:"D. MMMM YYYY [kl.] H:mm",LLLL:"dddd D. MMMM YYYY [kl.] HH:mm"}};return n.default.locale(a,null,!0),a}));
@@ -0,0 +1,6 @@
import { CreateType } from '../create/type.mjs';
import { Kind } from '../symbols/index.mjs';
/** `[JavaScript]` Creates a Constructor type */
export function Constructor(parameters, returns, options) {
return CreateType({ [Kind]: 'Constructor', type: 'Constructor', parameters, returns }, options);
}
@@ -0,0 +1,415 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _keywords = require('../parser/tokenizer/keywords');
var _types = require('../parser/tokenizer/types');
var _elideImportEquals = require('../util/elideImportEquals'); var _elideImportEquals2 = _interopRequireDefault(_elideImportEquals);
var _getDeclarationInfo = require('../util/getDeclarationInfo'); var _getDeclarationInfo2 = _interopRequireDefault(_getDeclarationInfo);
var _getImportExportSpecifierInfo = require('../util/getImportExportSpecifierInfo'); var _getImportExportSpecifierInfo2 = _interopRequireDefault(_getImportExportSpecifierInfo);
var _getNonTypeIdentifiers = require('../util/getNonTypeIdentifiers');
var _isExportFrom = require('../util/isExportFrom'); var _isExportFrom2 = _interopRequireDefault(_isExportFrom);
var _removeMaybeImportAttributes = require('../util/removeMaybeImportAttributes');
var _shouldElideDefaultExport = require('../util/shouldElideDefaultExport'); var _shouldElideDefaultExport2 = _interopRequireDefault(_shouldElideDefaultExport);
var _Transformer = require('./Transformer'); var _Transformer2 = _interopRequireDefault(_Transformer);
/**
* Class for editing import statements when we are keeping the code as ESM. We still need to remove
* type-only imports in TypeScript and Flow.
*/
class ESMImportTransformer extends _Transformer2.default {
constructor(
tokens,
nameManager,
helperManager,
reactHotLoaderTransformer,
isTypeScriptTransformEnabled,
isFlowTransformEnabled,
keepUnusedImports,
options,
) {
super();this.tokens = tokens;this.nameManager = nameManager;this.helperManager = helperManager;this.reactHotLoaderTransformer = reactHotLoaderTransformer;this.isTypeScriptTransformEnabled = isTypeScriptTransformEnabled;this.isFlowTransformEnabled = isFlowTransformEnabled;this.keepUnusedImports = keepUnusedImports;;
this.nonTypeIdentifiers =
isTypeScriptTransformEnabled && !keepUnusedImports
? _getNonTypeIdentifiers.getNonTypeIdentifiers.call(void 0, tokens, options)
: new Set();
this.declarationInfo =
isTypeScriptTransformEnabled && !keepUnusedImports
? _getDeclarationInfo2.default.call(void 0, tokens)
: _getDeclarationInfo.EMPTY_DECLARATION_INFO;
this.injectCreateRequireForImportRequire = Boolean(options.injectCreateRequireForImportRequire);
}
process() {
// TypeScript `import foo = require('foo');` should always just be translated to plain require.
if (this.tokens.matches3(_types.TokenType._import, _types.TokenType.name, _types.TokenType.eq)) {
return this.processImportEquals();
}
if (
this.tokens.matches4(_types.TokenType._import, _types.TokenType.name, _types.TokenType.name, _types.TokenType.eq) &&
this.tokens.matchesContextualAtIndex(this.tokens.currentIndex() + 1, _keywords.ContextualKeyword._type)
) {
// import type T = require('T')
this.tokens.removeInitialToken();
// This construct is always exactly 8 tokens long, so remove the 7 remaining tokens.
for (let i = 0; i < 7; i++) {
this.tokens.removeToken();
}
return true;
}
if (this.tokens.matches2(_types.TokenType._export, _types.TokenType.eq)) {
this.tokens.replaceToken("module.exports");
return true;
}
if (
this.tokens.matches5(_types.TokenType._export, _types.TokenType._import, _types.TokenType.name, _types.TokenType.name, _types.TokenType.eq) &&
this.tokens.matchesContextualAtIndex(this.tokens.currentIndex() + 2, _keywords.ContextualKeyword._type)
) {
// export import type T = require('T')
this.tokens.removeInitialToken();
// This construct is always exactly 9 tokens long, so remove the 8 remaining tokens.
for (let i = 0; i < 8; i++) {
this.tokens.removeToken();
}
return true;
}
if (this.tokens.matches1(_types.TokenType._import)) {
return this.processImport();
}
if (this.tokens.matches2(_types.TokenType._export, _types.TokenType._default)) {
return this.processExportDefault();
}
if (this.tokens.matches2(_types.TokenType._export, _types.TokenType.braceL)) {
return this.processNamedExports();
}
if (
this.tokens.matches2(_types.TokenType._export, _types.TokenType.name) &&
this.tokens.matchesContextualAtIndex(this.tokens.currentIndex() + 1, _keywords.ContextualKeyword._type)
) {
// export type {a};
// export type {a as b};
// export type {a} from './b';
// export type * from './b';
// export type * as ns from './b';
this.tokens.removeInitialToken();
this.tokens.removeToken();
if (this.tokens.matches1(_types.TokenType.braceL)) {
while (!this.tokens.matches1(_types.TokenType.braceR)) {
this.tokens.removeToken();
}
this.tokens.removeToken();
} else {
// *
this.tokens.removeToken();
if (this.tokens.matches1(_types.TokenType._as)) {
// as
this.tokens.removeToken();
// ns
this.tokens.removeToken();
}
}
// Remove type re-export `... } from './T'`
if (
this.tokens.matchesContextual(_keywords.ContextualKeyword._from) &&
this.tokens.matches1AtIndex(this.tokens.currentIndex() + 1, _types.TokenType.string)
) {
this.tokens.removeToken();
this.tokens.removeToken();
_removeMaybeImportAttributes.removeMaybeImportAttributes.call(void 0, this.tokens);
}
return true;
}
return false;
}
processImportEquals() {
const importName = this.tokens.identifierNameAtIndex(this.tokens.currentIndex() + 1);
if (this.shouldAutomaticallyElideImportedName(importName)) {
// If this name is only used as a type, elide the whole import.
_elideImportEquals2.default.call(void 0, this.tokens);
} else if (this.injectCreateRequireForImportRequire) {
// We're using require in an environment (Node ESM) that doesn't provide
// it as a global, so generate a helper to import it.
// import -> const
this.tokens.replaceToken("const");
// Foo
this.tokens.copyToken();
// =
this.tokens.copyToken();
// require
this.tokens.replaceToken(this.helperManager.getHelperName("require"));
} else {
// Otherwise, just switch `import` to `const`.
this.tokens.replaceToken("const");
}
return true;
}
processImport() {
if (this.tokens.matches2(_types.TokenType._import, _types.TokenType.parenL)) {
// Dynamic imports don't need to be transformed.
return false;
}
const snapshot = this.tokens.snapshot();
const allImportsRemoved = this.removeImportTypeBindings();
if (allImportsRemoved) {
this.tokens.restoreToSnapshot(snapshot);
while (!this.tokens.matches1(_types.TokenType.string)) {
this.tokens.removeToken();
}
this.tokens.removeToken();
_removeMaybeImportAttributes.removeMaybeImportAttributes.call(void 0, this.tokens);
if (this.tokens.matches1(_types.TokenType.semi)) {
this.tokens.removeToken();
}
}
return true;
}
/**
* Remove type bindings from this import, leaving the rest of the import intact.
*
* Return true if this import was ONLY types, and thus is eligible for removal. This will bail out
* of the replacement operation, so we can return early here.
*/
removeImportTypeBindings() {
this.tokens.copyExpectedToken(_types.TokenType._import);
if (
this.tokens.matchesContextual(_keywords.ContextualKeyword._type) &&
!this.tokens.matches1AtIndex(this.tokens.currentIndex() + 1, _types.TokenType.comma) &&
!this.tokens.matchesContextualAtIndex(this.tokens.currentIndex() + 1, _keywords.ContextualKeyword._from)
) {
// This is an "import type" statement, so exit early.
return true;
}
if (this.tokens.matches1(_types.TokenType.string)) {
// This is a bare import, so we should proceed with the import.
this.tokens.copyToken();
return false;
}
// Skip the "module" token in import reflection.
if (
this.tokens.matchesContextual(_keywords.ContextualKeyword._module) &&
this.tokens.matchesContextualAtIndex(this.tokens.currentIndex() + 2, _keywords.ContextualKeyword._from)
) {
this.tokens.copyToken();
}
let foundNonTypeImport = false;
let foundAnyNamedImport = false;
let needsComma = false;
// Handle default import.
if (this.tokens.matches1(_types.TokenType.name)) {
if (this.shouldAutomaticallyElideImportedName(this.tokens.identifierName())) {
this.tokens.removeToken();
if (this.tokens.matches1(_types.TokenType.comma)) {
this.tokens.removeToken();
}
} else {
foundNonTypeImport = true;
this.tokens.copyToken();
if (this.tokens.matches1(_types.TokenType.comma)) {
// We're in a statement like:
// import A, * as B from './A';
// or
// import A, {foo} from './A';
// where the `A` is being kept. The comma should be removed if an only
// if the next part of the import statement is elided, but that's hard
// to determine at this point in the code. Instead, always remove it
// and set a flag to add it back if necessary.
needsComma = true;
this.tokens.removeToken();
}
}
}
if (this.tokens.matches1(_types.TokenType.star)) {
if (this.shouldAutomaticallyElideImportedName(this.tokens.identifierNameAtRelativeIndex(2))) {
this.tokens.removeToken();
this.tokens.removeToken();
this.tokens.removeToken();
} else {
if (needsComma) {
this.tokens.appendCode(",");
}
foundNonTypeImport = true;
this.tokens.copyExpectedToken(_types.TokenType.star);
this.tokens.copyExpectedToken(_types.TokenType.name);
this.tokens.copyExpectedToken(_types.TokenType.name);
}
} else if (this.tokens.matches1(_types.TokenType.braceL)) {
if (needsComma) {
this.tokens.appendCode(",");
}
this.tokens.copyToken();
while (!this.tokens.matches1(_types.TokenType.braceR)) {
foundAnyNamedImport = true;
const specifierInfo = _getImportExportSpecifierInfo2.default.call(void 0, this.tokens);
if (
specifierInfo.isType ||
this.shouldAutomaticallyElideImportedName(specifierInfo.rightName)
) {
while (this.tokens.currentIndex() < specifierInfo.endIndex) {
this.tokens.removeToken();
}
if (this.tokens.matches1(_types.TokenType.comma)) {
this.tokens.removeToken();
}
} else {
foundNonTypeImport = true;
while (this.tokens.currentIndex() < specifierInfo.endIndex) {
this.tokens.copyToken();
}
if (this.tokens.matches1(_types.TokenType.comma)) {
this.tokens.copyToken();
}
}
}
this.tokens.copyExpectedToken(_types.TokenType.braceR);
}
if (this.keepUnusedImports) {
return false;
}
if (this.isTypeScriptTransformEnabled) {
return !foundNonTypeImport;
} else if (this.isFlowTransformEnabled) {
// In Flow, unlike TS, `import {} from 'foo';` preserves the import.
return foundAnyNamedImport && !foundNonTypeImport;
} else {
return false;
}
}
shouldAutomaticallyElideImportedName(name) {
return (
this.isTypeScriptTransformEnabled &&
!this.keepUnusedImports &&
!this.nonTypeIdentifiers.has(name)
);
}
processExportDefault() {
if (
_shouldElideDefaultExport2.default.call(void 0,
this.isTypeScriptTransformEnabled,
this.keepUnusedImports,
this.tokens,
this.declarationInfo,
)
) {
// If the exported value is just an identifier and should be elided by TypeScript
// rules, then remove it entirely. It will always have the form `export default e`,
// where `e` is an identifier.
this.tokens.removeInitialToken();
this.tokens.removeToken();
this.tokens.removeToken();
return true;
}
const alreadyHasName =
this.tokens.matches4(_types.TokenType._export, _types.TokenType._default, _types.TokenType._function, _types.TokenType.name) ||
// export default async function
(this.tokens.matches5(_types.TokenType._export, _types.TokenType._default, _types.TokenType.name, _types.TokenType._function, _types.TokenType.name) &&
this.tokens.matchesContextualAtIndex(
this.tokens.currentIndex() + 2,
_keywords.ContextualKeyword._async,
)) ||
this.tokens.matches4(_types.TokenType._export, _types.TokenType._default, _types.TokenType._class, _types.TokenType.name) ||
this.tokens.matches5(_types.TokenType._export, _types.TokenType._default, _types.TokenType._abstract, _types.TokenType._class, _types.TokenType.name);
if (!alreadyHasName && this.reactHotLoaderTransformer) {
// This is a plain "export default E" statement and we need to assign E to a variable.
// Change "export default E" to "let _default; export default _default = E"
const defaultVarName = this.nameManager.claimFreeName("_default");
this.tokens.replaceToken(`let ${defaultVarName}; export`);
this.tokens.copyToken();
this.tokens.appendCode(` ${defaultVarName} =`);
this.reactHotLoaderTransformer.setExtractedDefaultExportName(defaultVarName);
return true;
}
return false;
}
/**
* Handle a statement with one of these forms:
* export {a, type b};
* export {c, type d} from 'foo';
*
* In both cases, any explicit type exports should be removed. In the first
* case, we also need to handle implicit export elision for names declared as
* types. In the second case, we must NOT do implicit named export elision,
* but we must remove the runtime import if all exports are type exports.
*/
processNamedExports() {
if (!this.isTypeScriptTransformEnabled) {
return false;
}
this.tokens.copyExpectedToken(_types.TokenType._export);
this.tokens.copyExpectedToken(_types.TokenType.braceL);
const isReExport = _isExportFrom2.default.call(void 0, this.tokens);
let foundNonTypeExport = false;
while (!this.tokens.matches1(_types.TokenType.braceR)) {
const specifierInfo = _getImportExportSpecifierInfo2.default.call(void 0, this.tokens);
if (
specifierInfo.isType ||
(!isReExport && this.shouldElideExportedName(specifierInfo.leftName))
) {
// Type export, so remove all tokens, including any comma.
while (this.tokens.currentIndex() < specifierInfo.endIndex) {
this.tokens.removeToken();
}
if (this.tokens.matches1(_types.TokenType.comma)) {
this.tokens.removeToken();
}
} else {
// Non-type export, so copy all tokens, including any comma.
foundNonTypeExport = true;
while (this.tokens.currentIndex() < specifierInfo.endIndex) {
this.tokens.copyToken();
}
if (this.tokens.matches1(_types.TokenType.comma)) {
this.tokens.copyToken();
}
}
}
this.tokens.copyExpectedToken(_types.TokenType.braceR);
if (!this.keepUnusedImports && isReExport && !foundNonTypeExport) {
// This is a type-only re-export, so skip evaluating the other module. Technically this
// leaves the statement as `export {}`, but that's ok since that's a no-op.
this.tokens.removeToken();
this.tokens.removeToken();
_removeMaybeImportAttributes.removeMaybeImportAttributes.call(void 0, this.tokens);
}
return true;
}
/**
* ESM elides all imports with the rule that we only elide if we see that it's
* a type and never see it as a value. This is in contrast to CJS, which
* elides imports that are completely unknown.
*/
shouldElideExportedName(name) {
return (
this.isTypeScriptTransformEnabled &&
!this.keepUnusedImports &&
this.declarationInfo.typeDeclarations.has(name) &&
!this.declarationInfo.valueDeclarations.has(name)
);
}
} exports.default = ESMImportTransformer;
@@ -0,0 +1,30 @@
var freeGlobal = require('./_freeGlobal');
/** Detect free variable `exports`. */
var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
/** Detect free variable `module`. */
var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
/** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports;
/** Detect free variable `process` from Node.js. */
var freeProcess = moduleExports && freeGlobal.process;
/** Used to access faster Node.js helpers. */
var nodeUtil = (function() {
try {
// Use `util.types` for Node.js 10+.
var types = freeModule && freeModule.require && freeModule.require('util').types;
if (types) {
return types;
}
// Legacy `process.binding('util')` for Node.js < 10.
return freeProcess && freeProcess.binding && freeProcess.binding('util');
} catch (e) {}
}());
module.exports = nodeUtil;
@@ -0,0 +1,16 @@
var baseGet = require('./_baseGet'),
baseSlice = require('./_baseSlice');
/**
* Gets the parent value at `path` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {Array} path The path to get the parent value of.
* @returns {*} Returns the parent value.
*/
function parent(object, path) {
return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
}
module.exports = parent;
@@ -0,0 +1,343 @@
//#region rolldown:runtime
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
//#endregion
const node_path = __toESM(require("node:path"));
const node_url = __toESM(require("node:url"));
const node_fs = __toESM(require("node:fs"));
const vite = __toESM(require("vite"));
const __rolldown_pluginutils = __toESM(require("@rolldown/pluginutils"));
//#region ../common/refresh-utils.ts
const runtimePublicPath = "/@react-refresh";
const reactCompRE = /extends\s+(?:React\.)?(?:Pure)?Component/;
const refreshContentRE = /\$RefreshReg\$\(/;
const preambleCode = `import { injectIntoGlobalHook } from "__BASE__${runtimePublicPath.slice(1)}";
injectIntoGlobalHook(window);
window.$RefreshReg$ = () => {};
window.$RefreshSig$ = () => (type) => type;`;
const getPreambleCode = (base) => preambleCode.replace("__BASE__", base);
const avoidSourceMapOption = Symbol();
function addRefreshWrapper(code, map, pluginName, id, reactRefreshHost = "") {
const hasRefresh = refreshContentRE.test(code);
const onlyReactComp = !hasRefresh && reactCompRE.test(code);
const normalizedMap = map === avoidSourceMapOption ? null : map;
if (!hasRefresh && !onlyReactComp) return {
code,
map: normalizedMap
};
const avoidSourceMap = map === avoidSourceMapOption;
const newMap = typeof normalizedMap === "string" ? JSON.parse(normalizedMap) : normalizedMap;
let newCode = code;
if (hasRefresh) {
const refreshHead = removeLineBreaksIfNeeded(`let prevRefreshReg;
let prevRefreshSig;
if (import.meta.hot && !inWebWorker) {
if (!window.$RefreshReg$) {
throw new Error(
"${pluginName} can't detect preamble. Something is wrong."
);
}
prevRefreshReg = window.$RefreshReg$;
prevRefreshSig = window.$RefreshSig$;
window.$RefreshReg$ = RefreshRuntime.getRefreshReg(${JSON.stringify(id)});
window.$RefreshSig$ = RefreshRuntime.createSignatureFunctionForTransform;
}
`, avoidSourceMap);
newCode = `${refreshHead}${newCode}
if (import.meta.hot && !inWebWorker) {
window.$RefreshReg$ = prevRefreshReg;
window.$RefreshSig$ = prevRefreshSig;
}
`;
if (newMap) newMap.mappings = ";".repeat(16) + newMap.mappings;
}
const sharedHead = removeLineBreaksIfNeeded(`import * as RefreshRuntime from "${reactRefreshHost}${runtimePublicPath}";
const inWebWorker = typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope;
`, avoidSourceMap);
newCode = `${sharedHead}${newCode}
if (import.meta.hot && !inWebWorker) {
RefreshRuntime.__hmr_import(import.meta.url).then((currentExports) => {
RefreshRuntime.registerExportsForReactRefresh(${JSON.stringify(id)}, currentExports);
import.meta.hot.accept((nextExports) => {
if (!nextExports) return;
const invalidateMessage = RefreshRuntime.validateRefreshBoundaryAndEnqueueUpdate(${JSON.stringify(id)}, currentExports, nextExports);
if (invalidateMessage) import.meta.hot.invalidate(invalidateMessage);
});
});
}
`;
if (newMap) newMap.mappings = ";;;" + newMap.mappings;
return {
code: newCode,
map: newMap
};
}
function removeLineBreaksIfNeeded(code, enabled) {
return enabled ? code.replace(/\n/g, "") : code;
}
//#endregion
//#region ../common/warning.ts
const silenceUseClientWarning = (userConfig) => ({ rollupOptions: { onwarn(warning, defaultHandler) {
var _userConfig$build;
if (warning.code === "MODULE_LEVEL_DIRECTIVE" && (warning.message.includes("use client") || warning.message.includes("use server"))) return;
if (warning.code === "SOURCEMAP_ERROR" && warning.message.includes("resolve original location") && warning.pos === 0) return;
if ((_userConfig$build = userConfig.build) === null || _userConfig$build === void 0 || (_userConfig$build = _userConfig$build.rollupOptions) === null || _userConfig$build === void 0 ? void 0 : _userConfig$build.onwarn) userConfig.build.rollupOptions.onwarn(warning, defaultHandler);
else defaultHandler(warning);
} } });
//#endregion
//#region src/index.ts
const _dirname = (0, node_path.dirname)((0, node_url.fileURLToPath)(require("url").pathToFileURL(__filename).href));
const refreshRuntimePath = (0, node_path.join)(_dirname, "refresh-runtime.js");
let babel;
async function loadBabel() {
if (!babel) babel = await import("@babel/core");
return babel;
}
const defaultIncludeRE = /\.[tj]sx?$/;
const tsRE = /\.tsx?$/;
function viteReact(opts = {}) {
var _opts$babel;
const include = opts.include ?? defaultIncludeRE;
const exclude = opts.exclude;
const filter = (0, vite.createFilter)(include, exclude);
const jsxImportSource = opts.jsxImportSource ?? "react";
const jsxImportRuntime = `${jsxImportSource}/jsx-runtime`;
const jsxImportDevRuntime = `${jsxImportSource}/jsx-dev-runtime`;
let runningInVite = false;
let isProduction = true;
let projectRoot = process.cwd();
let skipFastRefresh = true;
let runPluginOverrides;
let staticBabelOptions;
const importReactRE = /\bimport\s+(?:\*\s+as\s+)?React\b/;
const viteBabel = {
name: "vite:react-babel",
enforce: "pre",
config() {
if (opts.jsxRuntime === "classic") if ("rolldownVersion" in vite) return { oxc: { jsx: {
runtime: "classic",
development: false
} } };
else return { esbuild: { jsx: "transform" } };
else return {
esbuild: {
jsx: "automatic",
jsxImportSource: opts.jsxImportSource
},
optimizeDeps: "rolldownVersion" in vite ? { rollupOptions: { jsx: { mode: "automatic" } } } : { esbuildOptions: { jsx: "automatic" } }
};
},
configResolved(config) {
runningInVite = true;
projectRoot = config.root;
isProduction = config.isProduction;
skipFastRefresh = isProduction || config.command === "build" || config.server.hmr === false;
if ("jsxPure" in opts) config.logger.warnOnce("[@vitejs/plugin-react] jsxPure was removed. You can configure esbuild.jsxSideEffects directly.");
const hooks = config.plugins.map((plugin) => {
var _plugin$api;
return (_plugin$api = plugin.api) === null || _plugin$api === void 0 ? void 0 : _plugin$api.reactBabel;
}).filter(defined);
if ("rolldownVersion" in vite && !opts.babel && !hooks.length && !opts.disableOxcRecommendation) config.logger.warn("[vite:react-babel] We recommend switching to `@vitejs/plugin-react-oxc` for improved performance. More information at https://vite.dev/rolldown");
if (hooks.length > 0) runPluginOverrides = (babelOptions, context) => {
hooks.forEach((hook) => hook(babelOptions, context, config));
};
else if (typeof opts.babel !== "function") {
staticBabelOptions = createBabelOptions(opts.babel);
if (canSkipBabel(staticBabelOptions.plugins, staticBabelOptions) && skipFastRefresh && (opts.jsxRuntime === "classic" ? isProduction : true)) delete viteBabel.transform;
}
},
options(options) {
if (!runningInVite) {
options.jsx = {
mode: opts.jsxRuntime,
importSource: opts.jsxImportSource
};
return options;
}
},
transform: {
filter: { id: {
include: (0, __rolldown_pluginutils.makeIdFiltersToMatchWithQuery)(include),
exclude: [...exclude ? (0, __rolldown_pluginutils.makeIdFiltersToMatchWithQuery)(ensureArray(exclude)) : [], /\/node_modules\//]
} },
async handler(code, id, options) {
if (id.includes("/node_modules/")) return;
const [filepath] = id.split("?");
if (!filter(filepath)) return;
const ssr = (options === null || options === void 0 ? void 0 : options.ssr) === true;
const babelOptions = (() => {
if (staticBabelOptions) return staticBabelOptions;
const newBabelOptions = createBabelOptions(typeof opts.babel === "function" ? opts.babel(id, { ssr }) : opts.babel);
runPluginOverrides === null || runPluginOverrides === void 0 || runPluginOverrides(newBabelOptions, {
id,
ssr
});
return newBabelOptions;
})();
const plugins = [...babelOptions.plugins];
const isJSX = filepath.endsWith("x");
const useFastRefresh = !skipFastRefresh && !ssr && (isJSX || (opts.jsxRuntime === "classic" ? importReactRE.test(code) : code.includes(jsxImportDevRuntime) || code.includes(jsxImportRuntime)));
if (useFastRefresh) plugins.push([await loadPlugin("react-refresh/babel"), { skipEnvCheck: true }]);
if (opts.jsxRuntime === "classic" && isJSX) {
if (!isProduction) plugins.push(await loadPlugin("@babel/plugin-transform-react-jsx-self"), await loadPlugin("@babel/plugin-transform-react-jsx-source"));
}
if (canSkipBabel(plugins, babelOptions)) return;
const parserPlugins = [...babelOptions.parserOpts.plugins];
if (!filepath.endsWith(".ts")) parserPlugins.push("jsx");
if (tsRE.test(filepath)) parserPlugins.push("typescript");
const babel$1 = await loadBabel();
const result = await babel$1.transformAsync(code, {
...babelOptions,
root: projectRoot,
filename: id,
sourceFileName: filepath,
retainLines: getReactCompilerPlugin(plugins) != null ? false : !isProduction && isJSX && opts.jsxRuntime !== "classic",
parserOpts: {
...babelOptions.parserOpts,
sourceType: "module",
allowAwaitOutsideFunction: true,
plugins: parserPlugins
},
generatorOpts: {
...babelOptions.generatorOpts,
importAttributesKeyword: "with",
decoratorsBeforeExport: true
},
plugins,
sourceMaps: true
});
if (result) {
if (!useFastRefresh) return {
code: result.code,
map: result.map
};
return addRefreshWrapper(result.code, result.map, "@vitejs/plugin-react", id, opts.reactRefreshHost);
}
}
}
};
const dependencies = [
"react",
"react-dom",
jsxImportDevRuntime,
jsxImportRuntime
];
const staticBabelPlugins = typeof opts.babel === "object" ? ((_opts$babel = opts.babel) === null || _opts$babel === void 0 ? void 0 : _opts$babel.plugins) ?? [] : [];
const reactCompilerPlugin = getReactCompilerPlugin(staticBabelPlugins);
if (reactCompilerPlugin != null) {
const reactCompilerRuntimeModule = getReactCompilerRuntimeModule(reactCompilerPlugin);
dependencies.push(reactCompilerRuntimeModule);
}
const viteReactRefresh = {
name: "vite:react-refresh",
enforce: "pre",
config: (userConfig) => ({
build: silenceUseClientWarning(userConfig),
optimizeDeps: { include: dependencies },
resolve: { dedupe: ["react", "react-dom"] }
}),
resolveId: {
filter: { id: (0, __rolldown_pluginutils.exactRegex)(runtimePublicPath) },
handler(id) {
if (id === runtimePublicPath) return id;
}
},
load: {
filter: { id: (0, __rolldown_pluginutils.exactRegex)(runtimePublicPath) },
handler(id) {
if (id === runtimePublicPath) return (0, node_fs.readFileSync)(refreshRuntimePath, "utf-8").replace(/__README_URL__/g, "https://github.com/vitejs/vite-plugin-react/tree/main/packages/plugin-react");
}
},
transformIndexHtml(_, config) {
if (!skipFastRefresh) return [{
tag: "script",
attrs: { type: "module" },
children: getPreambleCode(config.server.config.base)
}];
}
};
return [viteBabel, viteReactRefresh];
}
viteReact.preambleCode = preambleCode;
function canSkipBabel(plugins, babelOptions) {
return !(plugins.length || babelOptions.presets.length || babelOptions.configFile || babelOptions.babelrc);
}
const loadedPlugin = /* @__PURE__ */ new Map();
function loadPlugin(path) {
const cached = loadedPlugin.get(path);
if (cached) return cached;
const promise = import(path).then((module$1) => {
const value = module$1.default || module$1;
loadedPlugin.set(path, value);
return value;
});
loadedPlugin.set(path, promise);
return promise;
}
function createBabelOptions(rawOptions) {
var _babelOptions$parserO;
const babelOptions = {
babelrc: false,
configFile: false,
...rawOptions
};
babelOptions.plugins || (babelOptions.plugins = []);
babelOptions.presets || (babelOptions.presets = []);
babelOptions.overrides || (babelOptions.overrides = []);
babelOptions.parserOpts || (babelOptions.parserOpts = {});
(_babelOptions$parserO = babelOptions.parserOpts).plugins || (_babelOptions$parserO.plugins = []);
return babelOptions;
}
function defined(value) {
return value !== void 0;
}
function getReactCompilerPlugin(plugins) {
return plugins.find((p) => p === "babel-plugin-react-compiler" || Array.isArray(p) && p[0] === "babel-plugin-react-compiler");
}
function getReactCompilerRuntimeModule(plugin) {
let moduleName = "react/compiler-runtime";
if (Array.isArray(plugin)) {
var _plugin$, _plugin$2, _plugin$3;
if (((_plugin$ = plugin[1]) === null || _plugin$ === void 0 ? void 0 : _plugin$.target) === "17" || ((_plugin$2 = plugin[1]) === null || _plugin$2 === void 0 ? void 0 : _plugin$2.target) === "18") moduleName = "react-compiler-runtime";
else if (typeof ((_plugin$3 = plugin[1]) === null || _plugin$3 === void 0 ? void 0 : _plugin$3.runtimeModule) === "string") {
var _plugin$4;
moduleName = (_plugin$4 = plugin[1]) === null || _plugin$4 === void 0 ? void 0 : _plugin$4.runtimeModule;
}
}
return moduleName;
}
function ensureArray(value) {
return Array.isArray(value) ? value : [value];
}
//#endregion
module.exports = viteReact;
module.exports.default = module.exports
@@ -0,0 +1 @@
{"version":3,"file":"MethodDecoratorInfo.js","sourceRoot":"","sources":["../../../../src/decorator/models/MethodDecoratorInfo.ts"],"names":[],"mappings":""}
@@ -0,0 +1 @@
{"mappings":";;AAAA;;;;;;;;;;CAUC","sources":["packages/@react-aria/link/src/index.ts"],"sourcesContent":["/*\n * Copyright 2020 Adobe. All rights reserved.\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\nexport type {AriaLinkOptions, LinkAria} from './useLink';\nexport {useLink} from './useLink';\n"],"names":[],"version":3,"file":"module.js.map"}
@@ -0,0 +1,72 @@
# path-type [![Build Status](https://travis-ci.org/sindresorhus/path-type.svg?branch=master)](https://travis-ci.org/sindresorhus/path-type)
> Check if a path is a file, directory, or symlink
## Install
```
$ npm install path-type
```
## Usage
```js
const {isFile} = require('path-type');
(async () => {
console.log(await isFile('package.json'));
//=> true
})();
```
## API
### isFile(path)
Check whether the passed `path` is a file.
Returns a `Promise<boolean>`.
#### path
Type: `string`
The path to check.
### isDirectory(path)
Check whether the passed `path` is a directory.
Returns a `Promise<boolean>`.
### isSymlink(path)
Check whether the passed `path` is a symlink.
Returns a `Promise<boolean>`.
### isFileSync(path)
Synchronously check whether the passed `path` is a file.
Returns a `boolean`.
### isDirectorySync(path)
Synchronously check whether the passed `path` is a directory.
Returns a `boolean`.
### isSymlinkSync(path)
Synchronously check whether the passed `path` is a symlink.
Returns a `boolean`.
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
@@ -0,0 +1,96 @@
{
"name": "object.assign",
"version": "4.1.7",
"author": "Jordan Harband",
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"description": "ES6 spec-compliant Object.assign shim. From https://github.com/es-shims/es6-shim",
"license": "MIT",
"main": "index.js",
"scripts": {
"prepack": "npmignore --auto --commentLines=autogenerated",
"pretest": "npm run lint && es-shim-api --bound",
"test": "npm run tests-only && npm run test:ses",
"posttest": "npx npm@'>=10.2' audit --production",
"tests-only": "npm run test:implementation && npm run test:shim",
"test:native": "nyc node test/native",
"test:shim": "nyc node test/shimmed",
"test:implementation": "nyc node test",
"test:ses": "node test/ses-compat",
"lint": "eslint .",
"build": "mkdir -p dist && browserify browserShim.js > dist/browser.js",
"prepublishOnly": "safe-publish-latest && npm run build",
"prepublish": "not-in-publish || npm run prepublishOnly"
},
"repository": {
"type": "git",
"url": "git://github.com/ljharb/object.assign.git"
},
"keywords": [
"Object.assign",
"assign",
"ES6",
"extend",
"$.extend",
"jQuery",
"_.extend",
"Underscore",
"es-shim API",
"polyfill",
"shim"
],
"dependencies": {
"call-bind": "^1.0.8",
"call-bound": "^1.0.3",
"define-properties": "^1.2.1",
"es-object-atoms": "^1.0.0",
"has-symbols": "^1.1.0",
"object-keys": "^1.1.1"
},
"devDependencies": {
"@es-shims/api": "^2.5.1",
"@ljharb/eslint-config": "^21.1.1",
"browserify": "^16.5.2",
"eslint": "=8.8.0",
"for-each": "^0.3.3",
"functions-have-names": "^1.2.3",
"has-strict-mode": "^1.0.1",
"hasown": "^2.0.2",
"mock-property": "^1.1.0",
"npmignore": "^0.3.1",
"nyc": "^10.3.2",
"safe-publish-latest": "^2.0.0",
"ses": "^1.10.0",
"tape": "^5.9.0"
},
"testling": {
"files": "test/index.js",
"browsers": [
"iexplore/6.0..latest",
"firefox/3.0..6.0",
"firefox/15.0..latest",
"firefox/nightly",
"chrome/4.0..10.0",
"chrome/20.0..latest",
"chrome/canary",
"opera/10.0..latest",
"opera/next",
"safari/4.0..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2"
]
},
"engines": {
"node": ">= 0.4"
},
"publishConfig": {
"ignore": [
".github/workflows",
"bower.json",
"browserShim.js",
"!dist/"
]
}
}
@@ -0,0 +1 @@
{"version":3,"names":["_optionAssertions","require","VALIDATORS","name","assertString","manipulateOptions","assertFunction","pre","post","inherits","visitor","assertVisitorMap","parserOverride","generatorOverride","loc","value","obj","assertObject","Object","keys","forEach","prop","assertVisitorHandler","enter","exit","Error","msg","key","handler","validatePluginObject","rootPath","type","source","validator","optLoc","parent","invalidPluginPropertyError","code"],"sources":["../../../src/config/validation/plugins.ts"],"sourcesContent":["import {\n assertString,\n assertFunction,\n assertObject,\n msg,\n} from \"./option-assertions.ts\";\n\nimport type {\n ValidatorSet,\n Validator,\n OptionPath,\n RootPath,\n} from \"./option-assertions.ts\";\nimport type { parse, ParserOptions } from \"@babel/parser\";\nimport type { Visitor } from \"@babel/traverse\";\nimport type { ResolvedOptions } from \"./options.ts\";\nimport type { File, PluginAPI, PluginPass } from \"../../index.ts\";\nimport type { GeneratorOptions, GeneratorResult } from \"@babel/generator\";\nimport type babelGenerator from \"@babel/generator\";\n\n// Note: The casts here are just meant to be static assertions to make sure\n// that the assertion functions actually assert that the value's type matches\n// the declared types.\nconst VALIDATORS: ValidatorSet = {\n name: assertString as Validator<PluginObject[\"name\"]>,\n manipulateOptions: assertFunction as Validator<\n PluginObject[\"manipulateOptions\"]\n >,\n pre: assertFunction as Validator<PluginObject[\"pre\"]>,\n post: assertFunction as Validator<PluginObject[\"post\"]>,\n inherits: assertFunction as Validator<PluginObject[\"inherits\"]>,\n visitor: assertVisitorMap as Validator<PluginObject[\"visitor\"]>,\n\n parserOverride: assertFunction as Validator<PluginObject[\"parserOverride\"]>,\n generatorOverride: assertFunction as Validator<\n PluginObject[\"generatorOverride\"]\n >,\n};\n\nfunction assertVisitorMap(loc: OptionPath, value: unknown): Visitor {\n const obj = assertObject(loc, value);\n if (obj) {\n Object.keys(obj).forEach(prop => {\n if (prop !== \"_exploded\" && prop !== \"_verified\") {\n assertVisitorHandler(prop, obj[prop]);\n }\n });\n\n if (obj.enter || obj.exit) {\n throw new Error(\n `${msg(\n loc,\n )} cannot contain catch-all \"enter\" or \"exit\" handlers. Please target individual nodes.`,\n );\n }\n }\n return obj as Visitor;\n}\n\nfunction assertVisitorHandler(\n key: string,\n value: unknown,\n): asserts value is VisitorHandler {\n if (value && typeof value === \"object\") {\n Object.keys(value).forEach((handler: string) => {\n if (handler !== \"enter\" && handler !== \"exit\") {\n throw new Error(\n `.visitor[\"${key}\"] may only have .enter and/or .exit handlers.`,\n );\n }\n });\n } else if (typeof value !== \"function\") {\n throw new Error(`.visitor[\"${key}\"] must be a function`);\n }\n}\n\ntype VisitorHandler =\n | Function\n | {\n enter?: Function;\n exit?: Function;\n };\n\nexport type PluginObject<S extends PluginPass = PluginPass> = {\n name?: string;\n manipulateOptions?: (\n options: ResolvedOptions,\n parserOpts: ParserOptions,\n ) => void;\n pre?: (this: S, file: File) => void | Promise<void>;\n post?: (this: S, file: File) => void | Promise<void>;\n inherits?: (\n api: PluginAPI,\n options: unknown,\n dirname: string,\n ) => PluginObject;\n visitor?: Visitor<S>;\n parserOverride?: (\n ...args: [...Parameters<typeof parse>, typeof parse]\n ) => ReturnType<typeof parse>;\n generatorOverride?: (\n ast: File[\"ast\"],\n generatorOpts: GeneratorOptions,\n code: File[\"code\"],\n generate: typeof babelGenerator,\n ) => GeneratorResult;\n};\n\nexport function validatePluginObject(obj: {\n [key: string]: unknown;\n}): PluginObject {\n const rootPath: RootPath = {\n type: \"root\",\n source: \"plugin\",\n };\n Object.keys(obj).forEach((key: string) => {\n const validator = VALIDATORS[key];\n\n if (validator) {\n const optLoc: OptionPath = {\n type: \"option\",\n name: key,\n parent: rootPath,\n };\n validator(optLoc, obj[key]);\n } else {\n const invalidPluginPropertyError = new Error(\n `.${key} is not a valid Plugin property`,\n );\n // @ts-expect-error todo(flow->ts) consider adding BabelConfigError with code field\n invalidPluginPropertyError.code = \"BABEL_UNKNOWN_PLUGIN_PROPERTY\";\n throw invalidPluginPropertyError;\n }\n });\n\n return obj as any;\n}\n"],"mappings":";;;;;;AAAA,IAAAA,iBAAA,GAAAC,OAAA;AAuBA,MAAMC,UAAwB,GAAG;EAC/BC,IAAI,EAAEC,8BAA+C;EACrDC,iBAAiB,EAAEC,gCAElB;EACDC,GAAG,EAAED,gCAAgD;EACrDE,IAAI,EAAEF,gCAAiD;EACvDG,QAAQ,EAAEH,gCAAqD;EAC/DI,OAAO,EAAEC,gBAAsD;EAE/DC,cAAc,EAAEN,gCAA2D;EAC3EO,iBAAiB,EAAEP;AAGrB,CAAC;AAED,SAASK,gBAAgBA,CAACG,GAAe,EAAEC,KAAc,EAAWLine truncated
@@ -0,0 +1,7 @@
'use strict';
var implementation = require('./implementation');
module.exports = function getPolyfill() {
return Object.groupBy || implementation;
};
@@ -0,0 +1,116 @@
var $87beb89ab4a308fd$exports = require("./utils.main.js");
var $bOFHO$reactariautils = require("@react-aria/utils");
var $bOFHO$reactstatelycollections = require("@react-stately/collections");
var $bOFHO$reactariainteractions = require("@react-aria/interactions");
var $bOFHO$reactariaselection = require("@react-aria/selection");
function $parcel$export(e, n, v, s) {
Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
}
$parcel$export(module.exports, "useOption", () => $c164f9f79f4cef2d$export$497855f14858aa34);
/*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
function $c164f9f79f4cef2d$export$497855f14858aa34(props, state, ref) {
var _item_props, _item_props1;
let { key: key } = props;
let data = (0, $87beb89ab4a308fd$exports.listData).get(state);
var _props_isDisabled;
let isDisabled = (_props_isDisabled = props.isDisabled) !== null && _props_isDisabled !== void 0 ? _props_isDisabled : state.selectionManager.isDisabled(key);
var _props_isSelected;
let isSelected = (_props_isSelected = props.isSelected) !== null && _props_isSelected !== void 0 ? _props_isSelected : state.selectionManager.isSelected(key);
var _props_shouldSelectOnPressUp;
let shouldSelectOnPressUp = (_props_shouldSelectOnPressUp = props.shouldSelectOnPressUp) !== null && _props_shouldSelectOnPressUp !== void 0 ? _props_shouldSelectOnPressUp : data === null || data === void 0 ? void 0 : data.shouldSelectOnPressUp;
var _props_shouldFocusOnHover;
let shouldFocusOnHover = (_props_shouldFocusOnHover = props.shouldFocusOnHover) !== null && _props_shouldFocusOnHover !== void 0 ? _props_shouldFocusOnHover : data === null || data === void 0 ? void 0 : data.shouldFocusOnHover;
var _props_shouldUseVirtualFocus;
let shouldUseVirtualFocus = (_props_shouldUseVirtualFocus = props.shouldUseVirtualFocus) !== null && _props_shouldUseVirtualFocus !== void 0 ? _props_shouldUseVirtualFocus : data === null || data === void 0 ? void 0 : data.shouldUseVirtualFocus;
var _props_isVirtualized;
let isVirtualized = (_props_isVirtualized = props.isVirtualized) !== null && _props_isVirtualized !== void 0 ? _props_isVirtualized : data === null || data === void 0 ? void 0 : data.isVirtualized;
let labelId = (0, $bOFHO$reactariautils.useSlotId)();
let descriptionId = (0, $bOFHO$reactariautils.useSlotId)();
let optionProps = {
role: 'option',
'aria-disabled': isDisabled || undefined,
'aria-selected': state.selectionManager.selectionMode !== 'none' ? isSelected : undefined
};
// Safari with VoiceOver on macOS misreads options with aria-labelledby or aria-label as simply "text".
// We should not map slots to the label and description on Safari and instead just have VoiceOver read the textContent.
// https://bugs.webkit.org/show_bug.cgi?id=209279
if (!((0, $bOFHO$reactariautils.isMac)() && (0, $bOFHO$reactariautils.isWebKit)())) {
optionProps['aria-label'] = props['aria-label'];
optionProps['aria-labelledby'] = labelId;
optionProps['aria-describedby'] = descriptionId;
}
let item = state.collection.getItem(key);
if (isVirtualized) {
let index = Number(item === null || item === void 0 ? void 0 : item.index);
optionProps['aria-posinset'] = Number.isNaN(index) ? undefined : index + 1;
optionProps['aria-setsize'] = (0, $bOFHO$reactstatelycollections.getItemCount)(state.collection);
}
let onAction = (data === null || data === void 0 ? void 0 : data.onAction) ? ()=>{
var _data_onAction;
return data === null || data === void 0 ? void 0 : (_data_onAction = data.onAction) === null || _data_onAction === void 0 ? void 0 : _data_onAction.call(data, key);
} : undefined;
let { itemProps: itemProps, isPressed: isPressed, isFocused: isFocused, hasAction: hasAction, allowsSelection: allowsSelection } = (0, $bOFHO$reactariaselection.useSelectableItem)({
selectionManager: state.selectionManager,
key: key,
ref: ref,
shouldSelectOnPressUp: shouldSelectOnPressUp,
allowsDifferentPressOrigin: shouldSelectOnPressUp && shouldFocusOnHover,
isVirtualized: isVirtualized,
shouldUseVirtualFocus: shouldUseVirtualFocus,
isDisabled: isDisabled,
onAction: onAction || (item === null || item === void 0 ? void 0 : (_item_props = item.props) === null || _item_props === void 0 ? void 0 : _item_props.onAction) ? (0, $bOFHO$reactariautils.chain)(item === null || item === void 0 ? void 0 : (_item_props1 = item.props) === null || _item_props1 === void 0 ? void 0 : _item_props1.onAction, onAction) : undefined,
linkBehavior: data === null || data === void 0 ? void 0 : data.linkBehavior
});
let { hoverProps: hoverProps } = (0, $bOFHO$reactariainteractions.useHover)({
isDisabled: isDisabled || !shouldFocusOnHover,
onHoverStart () {
if (!(0, $bOFHO$reactariainteractions.isFocusVisible)()) {
state.selectionManager.setFocused(true);
state.selectionManager.setFocusedKey(key);
}
}
});
let domProps = (0, $bOFHO$reactariautils.filterDOMProps)(item === null || item === void 0 ? void 0 : item.props);
delete domProps.id;
let linkProps = (0, $bOFHO$reactariautils.useLinkProps)(item === null || item === void 0 ? void 0 : item.props);
return {
optionProps: {
...optionProps,
...(0, $bOFHO$reactariautils.mergeProps)(domProps, itemProps, hoverProps, linkProps),
id: (0, $87beb89ab4a308fd$exports.getItemId)(state, key)
},
labelProps: {
id: labelId
},
descriptionProps: {
id: descriptionId
},
isFocused: isFocused,
isFocusVisible: isFocused && (0, $bOFHO$reactariainteractions.isFocusVisible)(),
isSelected: isSelected,
isDisabled: isDisabled,
isPressed: isPressed,
allowsSelection: allowsSelection,
hasAction: hasAction
};
}
//# sourceMappingURL=useOption.main.js.map
@@ -0,0 +1,219 @@
export var IconsManifest = [
{
"id": "ci",
"name": "Circum Icons",
"projectUrl": "https://circumicons.com/",
"license": "MPL-2.0 license",
"licenseUrl": "https://github.com/Klarr-Agency/Circum-Icons/blob/main/LICENSE"
},
{
"id": "fa",
"name": "Font Awesome 5",
"projectUrl": "https://fontawesome.com/",
"license": "CC BY 4.0 License",
"licenseUrl": "https://creativecommons.org/licenses/by/4.0/"
},
{
"id": "fa6",
"name": "Font Awesome 6",
"projectUrl": "https://fontawesome.com/",
"license": "CC BY 4.0 License",
"licenseUrl": "https://creativecommons.org/licenses/by/4.0/"
},
{
"id": "io",
"name": "Ionicons 4",
"projectUrl": "https://ionicons.com/",
"license": "MIT",
"licenseUrl": "https://github.com/ionic-team/ionicons/blob/master/LICENSE"
},
{
"id": "io5",
"name": "Ionicons 5",
"projectUrl": "https://ionicons.com/",
"license": "MIT",
"licenseUrl": "https://github.com/ionic-team/ionicons/blob/master/LICENSE"
},
{
"id": "md",
"name": "Material Design icons",
"projectUrl": "http://google.github.io/material-design-icons/",
"license": "Apache License Version 2.0",
"licenseUrl": "https://github.com/google/material-design-icons/blob/master/LICENSE"
},
{
"id": "ti",
"name": "Typicons",
"projectUrl": "http://s-ings.com/typicons/",
"license": "CC BY-SA 3.0",
"licenseUrl": "https://creativecommons.org/licenses/by-sa/3.0/"
},
{
"id": "go",
"name": "Github Octicons icons",
"projectUrl": "https://octicons.github.com/",
"license": "MIT",
"licenseUrl": "https://github.com/primer/octicons/blob/master/LICENSE"
},
{
"id": "fi",
"name": "Feather",
"projectUrl": "https://feathericons.com/",
"license": "MIT",
"licenseUrl": "https://github.com/feathericons/feather/blob/master/LICENSE"
},
{
"id": "lu",
"name": "Lucide",
"projectUrl": "https://lucide.dev/",
"license": "ISC",
"licenseUrl": "https://github.com/lucide-icons/lucide/blob/main/LICENSE"
},
{
"id": "gi",
"name": "Game Icons",
"projectUrl": "https://game-icons.net/",
"license": "CC BY 3.0",
"licenseUrl": "https://creativecommons.org/licenses/by/3.0/"
},
{
"id": "wi",
"name": "Weather Icons",
"projectUrl": "https://erikflowers.github.io/weather-icons/",
"license": "SIL OFL 1.1",
"licenseUrl": "http://scripts.sil.org/OFL"
},
{
"id": "di",
"name": "Devicons",
"projectUrl": "https://vorillaz.github.io/devicons/",
"license": "MIT",
"licenseUrl": "https://opensource.org/licenses/MIT"
},
{
"id": "ai",
"name": "Ant Design Icons",
"projectUrl": "https://github.com/ant-design/ant-design-icons",
"license": "MIT",
"licenseUrl": "https://opensource.org/licenses/MIT"
},
{
"id": "bs",
"name": "Bootstrap Icons",
"projectUrl": "https://github.com/twbs/icons",
"license": "MIT",
"licenseUrl": "https://opensource.org/licenses/MIT"
},
{
"id": "ri",
"name": "Remix Icon",
"projectUrl": "https://github.com/Remix-Design/RemixIcon",
"license": "Apache License Version 2.0",
"licenseUrl": "http://www.apache.org/licenses/"
},
{
"id": "fc",
"name": "Flat Color Icons",
"projectUrl": "https://github.com/icons8/flat-color-icons",
"license": "MIT",
"licenseUrl": "https://opensource.org/licenses/MIT"
},
{
"id": "gr",
"name": "Grommet-Icons",
"projectUrl": "https://github.com/grommet/grommet-icons",
"license": "Apache License Version 2.0",
"licenseUrl": "http://www.apache.org/licenses/"
},
{
"id": "hi",
"name": "Heroicons",
"projectUrl": "https://github.com/tailwindlabs/heroicons",
"license": "MIT",
"licenseUrl": "https://opensource.org/licenses/MIT"
},
{
"id": "hi2",
"name": "Heroicons 2",
"projectUrl": "https://github.com/tailwindlabs/heroicons",
"license": "MIT",
"licenseUrl": "https://opensource.org/licenses/MIT"
},
{
"id": "si",
"name": "Simple Icons",
"projectUrl": "https://simpleicons.org/",
"license": "CC0 1.0 Universal",
"licenseUrl": "https://creativecommons.org/publicdomain/zero/1.0/"
},
{
"id": "sl",
"name": "Simple Line Icons",
"projectUrl": "https://thesabbir.github.io/simple-line-icons/",
"license": "MIT",
"licenseUrl": "https://opensource.org/licenses/MIT"
},
{
"id": "im",
"name": "IcoMoon Free",
"projectUrl": "https://github.com/Keyamoon/IcoMoon-Free",
"license": "CC BY 4.0 License",
"licenseUrl": "https://github.com/Keyamoon/IcoMoon-Free/blob/master/License.txt"
},
{
"id": "bi",
"name": "BoxIcons",
"projectUrl": "https://github.com/atisawd/boxicons",
"license": "MIT",
"licenseUrl": "https://github.com/atisawd/boxicons/blob/master/LICENSE"
},
{
"id": "cg",
"name": "css.gg",
"projectUrl": "https://github.com/astrit/css.gg",
"license": "MIT",
"licenseUrl": "https://opensource.org/licenses/MIT"
},
{
"id": "vsc",
"name": "VS Code Icons",
"projectUrl": "https://github.com/microsoft/vscode-codicons",
"license": "CC BY 4.0",
"licenseUrl": "https://creativecommons.org/licenses/by/4.0/"
},
{
"id": "tb",
"name": "Tabler Icons",
"projectUrl": "https://github.com/tabler/tabler-icons",
"license": "MIT",
"licenseUrl": "https://opensource.org/licenses/MIT"
},
{
"id": "tfi",
"name": "Themify Icons",
"projectUrl": "https://github.com/lykmapipo/themify-icons",
"license": "MIT",
"licenseUrl": "https://github.com/thecreation/standard-icons/blob/master/modules/themify-icons/LICENSE"
},
{
"id": "rx",
"name": "Radix Icons",
"projectUrl": "https://icons.radix-ui.com",
"license": "MIT",
"licenseUrl": "https://github.com/radix-ui/icons/blob/master/LICENSE"
},
{
"id": "pi",
"name": "Phosphor Icons",
"projectUrl": "https://github.com/phosphor-icons/core",
"license": "MIT",
"licenseUrl": "https://github.com/phosphor-icons/core/blob/main/LICENSE"
},
{
"id": "lia",
"name": "Icons8 Line Awesome",
"projectUrl": "https://icons8.com/line-awesome",
"license": "MIT",
"licenseUrl": "https://github.com/icons8/line-awesome/blob/master/LICENSE.md"
}
]
@@ -0,0 +1,126 @@
import type { $ZodStringFormats } from "../core/checks.js";
import type * as errors from "../core/errors.js";
import * as util from "../core/util.js";
const error: () => errors.$ZodErrorMap = () => {
const Sizable: Record<string, { unit: string; verb: string }> = {
string: { unit: "znaków", verb: "mieć" },
file: { unit: "bajtów", verb: "mieć" },
array: { unit: "elementów", verb: "mieć" },
set: { unit: "elementów", verb: "mieć" },
};
function getSizing(origin: string): { unit: string; verb: string } | null {
return Sizable[origin] ?? null;
}
const parsedType = (data: any): string => {
const t = typeof data;
switch (t) {
case "number": {
return Number.isNaN(data) ? "NaN" : "liczba";
}
case "object": {
if (Array.isArray(data)) {
return "tablica";
}
if (data === null) {
return "null";
}
if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
return data.constructor.name;
}
}
}
return t;
};
const Nouns: {
[k in $ZodStringFormats | (string & {})]?: string;
} = {
regex: "wyrażenie",
email: "adres email",
url: "URL",
emoji: "emoji",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "data i godzina w formacie ISO",
date: "data w formacie ISO",
time: "godzina w formacie ISO",
duration: "czas trwania ISO",
ipv4: "adres IPv4",
ipv6: "adres IPv6",
cidrv4: "zakres IPv4",
cidrv6: "zakres IPv6",
base64: "ciąg znaków zakodowany w formacie base64",
base64url: "ciąg znaków zakodowany w formacie base64url",
json_string: "ciąg znaków w formacie JSON",
e164: "liczba E.164",
jwt: "JWT",
template_literal: "wejście",
};
return (issue) => {
switch (issue.code) {
case "invalid_type":
return `Nieprawidłowe dane wejściowe: oczekiwano ${issue.expected}, otrzymano ${parsedType(issue.input)}`;
case "invalid_value":
if (issue.values.length === 1)
return `Nieprawidłowe dane wejściowe: oczekiwano ${util.stringifyPrimitive(issue.values[0])}`;
return `Nieprawidłowa opcja: oczekiwano jednej z wartości ${util.joinValues(issue.values, "|")}`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Za duża wartość: oczekiwano, że ${issue.origin ?? "wartość"} będzie mieć ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementów"}`;
}
return `Zbyt duż(y/a/e): oczekiwano, że ${issue.origin ?? "wartość"} będzie wynosić ${adj}${issue.maximum.toString()}`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `Za mała wartość: oczekiwano, że ${issue.origin ?? "wartość"} będzie mieć ${adj}${issue.minimum.toString()} ${sizing.unit ?? "elementów"}`;
}
return `Zbyt mał(y/a/e): oczekiwano, że ${issue.origin ?? "wartość"} będzie wynosić ${adj}${issue.minimum.toString()}`;
}
case "invalid_format": {
const _issue = issue as errors.$ZodStringFormatIssues;
if (_issue.format === "starts_with")
return `Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`;
if (_issue.format === "ends_with") return `Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`;
if (_issue.format === "includes") return `Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`;
if (_issue.format === "regex") return `Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`;
return `Nieprawidłow(y/a/e) ${Nouns[_issue.format] ?? issue.format}`;
}
case "not_multiple_of":
return `Nieprawidłowa liczba: musi być wielokrotnością ${issue.divisor}`;
case "unrecognized_keys":
return `Nierozpoznane klucze${issue.keys.length > 1 ? "s" : ""}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `Nieprawidłowy klucz w ${issue.origin}`;
case "invalid_union":
return "Nieprawidłowe dane wejściowe";
case "invalid_element":
return `Nieprawidłowa wartość w ${issue.origin}`;
default:
return `Nieprawidłowe dane wejściowe`;
}
};
};
export default function (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}
@@ -0,0 +1,17 @@
import copyObject from './_copyObject.js';
import keys from './keys.js';
/**
* The base implementation of `_.assign` without support for multiple sources
* or `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return object && copyObject(source, keys(source), object);
}
export default baseAssign;
@@ -0,0 +1 @@
{"name":"isarray","version":"2.0.5","requiresBuild":false,"files":{"package.json":{"checkedAt":1794532097172,"integrity":"sha512-b+O/YxxOP53G2mtjFeYycMVEyJwaBigr8ZreQ+H1Ko6LDb4kBblW4c8PtXnkebDq7pSLMcuu2vNu+DEs6/GhhQ==","mode":420,"size":991},"index.js":{"checkedAt":1794532097172,"integrity":"sha512-C7ocRFcqFHF++0lOjwDWfqn/QMxJ2c3bJtpiCUWI7dD1fiWtU7K4t5j/8G2BaJu1Coe96HcbB3eKhW71Fct2rw==","mode":420,"size":132},"LICENSE":{"checkedAt":1794532092735,"integrity":"sha512-CwBouL62hk27aXHZ/hZdLV/UILzW17u9j0JYnrmBv5XYVN8tFsIdN46m1I9WI0XS9m3g/RcTTf+oSV60lubf8A==","mode":420,"size":1096},"README.md":{"checkedAt":1794532097173,"integrity":"sha512-zRf7JcIuwL/Fyay0ftwCYvS+hM2ZpInoK+i4yMpyAtjzvakPbGFDlVMFBNwo9DUYRQAJAuumeErxVPGyExdz/Q==","mode":420,"size":1211}}}
@@ -0,0 +1 @@
{"name":"micromark-extension-gfm-tagfilter","version":"2.0.0","requiresBuild":false,"files":{"license":{"checkedAt":1794532116188,"integrity":"sha512-fzvkEDDVqhfCJpKNt4nSfCdql95dXnYBu6QTwaEDV5dX/EtSGYys2u3y/9LaRjp4jUgB4qbz5csHGjJjcZAb2Q==","mode":420,"size":1099},"index.js":{"checkedAt":1794532116188,"integrity":"sha512-cdJ3BoFf1mdGx6Hnudm6bGlPvVJVbXANZBgqd5Lef+H+cTgcRf/cgxvkc/7IcSwFcSJAoFhJt+LonTWZlT/Enw==","mode":420,"size":48},"lib/index.js":{"checkedAt":1794532116189,"integrity":"sha512-aqVquVAErPfdVToLn0Kp5ljEixejzjF2DfJJasatB0u3nyWpG/4VpEAhGxEjLDoH+Hj9bPOMLtqTfZcP+OUwqA==","mode":420,"size":1482},"package.json":{"checkedAt":1794532116189,"integrity":"sha512-J3CAA4wuzydP8WIxMGLxlN8WZiulSJCpUVIwOge1ET67VvtTAjRNYH/slxAy8ZwHOLMqs4DNpIdwLWlMXAElwA==","mode":420,"size":2148},"readme.md":{"checkedAt":1794532116189,"integrity":"sha512-5HI8IPsdz4f2zCfWhi0mRFdyECig6VMpgfGNEfz05OMm7ZCHe+pwd0daY0KPpZx6pZszDow8RD5XXHJ09SEVvw==","mode":420,"size":6573},"index.d.ts":{"checkedAt":1794532116188,"integrity":"sha512-cdJ3BoFf1mdGx6Hnudm6bGlPvVJVbXANZBgqd5Lef+H+cTgcRf/cgxvkc/7IcSwFcSJAoFhJt+LonTWZlT/Enw==","mode":420,"size":48},"lib/index.d.ts":{"checkedAt":1794532116189,"integrity":"sha512-l3PapGPBaWCTiPtbDXBm+pJCioqBFBe5MrpIvIIJIAP1jDMAUaYxn+DE/SfacKHAhWZTp+agzxSKkwzctH4L3Q==","mode":420,"size":562}}}
@@ -0,0 +1,2 @@
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"mixed", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>;
export default _default;
@@ -0,0 +1,16 @@
var Uint8Array = require('./_Uint8Array');
/**
* Creates a clone of `arrayBuffer`.
*
* @private
* @param {ArrayBuffer} arrayBuffer The array buffer to clone.
* @returns {ArrayBuffer} Returns the cloned array buffer.
*/
function cloneArrayBuffer(arrayBuffer) {
var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
new Uint8Array(result).set(new Uint8Array(arrayBuffer));
return result;
}
module.exports = cloneArrayBuffer;
@@ -0,0 +1,24 @@
// src/chevron-left.tsx
import { jsx } from "react/jsx-runtime";
var ChevronLeftIcon = (props) => /* @__PURE__ */ jsx(
"svg",
{
"aria-hidden": "true",
fill: "none",
focusable: "false",
height: "1em",
role: "presentation",
stroke: "currentColor",
strokeLinecap: "round",
strokeLinejoin: "round",
strokeWidth: "1.5",
viewBox: "0 0 24 24",
width: "1em",
...props,
children: /* @__PURE__ */ jsx("path", { d: "m15 18-6-6 6-6" })
}
);
export {
ChevronLeftIcon
};
@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
renderHook: true
};
exports.renderHook = void 0;
var _tslib = require("tslib");
var _react = require("react");
var _react2 = require("@testing-library/react");
Object.keys(_react2).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _react2[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _react2[key];
}
});
});
var Wrapper = process.env.REACT_MODE === 'strict' ? _react.StrictMode : undefined;
var customRender = exports.renderHook = function customRender(ui, options) {
return (0, _react2.renderHook)(ui, (0, _tslib.__assign)({
wrapper: Wrapper
}, options));
};
@@ -0,0 +1,24 @@
# @heroui/system-rsc
A Quick description of the component
> This is an internal utility, not intended for public usage.
## Installation
```sh
yarn add @heroui/system-rsc
# or
npm i @heroui/system-rsc
```
## Contribution
Yes please! See the
[contributing guidelines](https://github.com/frontio-ai/heroui/blob/master/CONTRIBUTING.md)
for details.
## License
This project is licensed under the terms of the
[MIT license](https://github.com/frontio-ai/heroui/blob/master/LICENSE).
@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=ClassElementMetadata.js.map
@@ -0,0 +1,41 @@
'use strict';var _path = require('path');var _path2 = _interopRequireDefault(_path);
var _contextCompat = require('eslint-module-utils/contextCompat');
var _moduleVisitor = require('eslint-module-utils/moduleVisitor');var _moduleVisitor2 = _interopRequireDefault(_moduleVisitor);
var _importType = require('../core/importType');
var _docsUrl = require('../docsUrl');var _docsUrl2 = _interopRequireDefault(_docsUrl);function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { 'default': obj };}
module.exports = {
meta: {
type: 'suggestion',
docs: {
category: 'Static analysis',
description: 'Forbid import of modules using absolute paths.',
url: (0, _docsUrl2['default'])('no-absolute-path') },
fixable: 'code',
schema: [(0, _moduleVisitor.makeOptionsSchema)()] },
create: function () {function create(context) {
function reportIfAbsolute(source) {
if ((0, _importType.isAbsolute)(source.value)) {
context.report({
node: source,
message: 'Do not import modules using an absolute path',
fix: function () {function fix(fixer) {
// node.js and web imports work with posix style paths ("/")
var relativePath = _path2['default'].posix.relative(_path2['default'].dirname((0, _contextCompat.getPhysicalFilename)(context)), source.value);
if (!relativePath.startsWith('.')) {
relativePath = './' + String(relativePath);
}
return fixer.replaceText(source, JSON.stringify(relativePath));
}return fix;}() });
}
}
var options = Object.assign({ esmodule: true, commonjs: true }, context.options[0]);
return (0, _moduleVisitor2['default'])(reportIfAbsolute, options);
}return create;}() };
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9ydWxlcy9uby1hYnNvbHV0ZS1wYXRoLmpzIl0sIm5hbWVzIjpbIm1vZHVsZSIsImV4cG9ydHMiLCJtZXRhIiwidHlwZSIsImRvY3MiLCJjYXRlZ29yeSIsImRlc2NyaXB0aW9uIiwidXJsIiwiZml4YWJsZSIsInNjaGVtYSIsImNyZWF0ZSIsImNvbnRleHQiLCJyZXBvcnRJZkFic29sdXRlIiwic291cmNlIiwidmFsdWUiLCJyZXBvcnQiLCJub2RlIiwibWVzc2FnZSIsImZpeCIsImZpeGVyIiwicmVsYXRpdmVQYXRoIiwicGF0aCIsInBvc2l4IiwicmVsYXRpdmUiLCJkaXJuYW1lIiwic3RhcnRzV2l0aCIsInJlcGxhY2VUZXh0IiwiSlNPTiIsInN0cmluZ2lmeSIsIm9wdGlvbnMiLCJlc21vZHVsZSIsImNvbW1vbmpzIl0sIm1hcHBpbmdzIjoiYUFBQSw0QjtBQUNBO0FBQ0Esa0U7O0FBRUE7QUFDQSxxQzs7QUFFQUEsT0FBT0MsT0FBUCxHQUFpQjtBQUNmQyxRQUFNO0FBQ0pDLFVBQU0sWUFERjtBQUVKQyxVQUFNO0FBQ0pDLGdCQUFVLGlCQUROO0FBRUpDLG1CQUFhLGdEQUZUO0FBR0pDLFdBQUssMEJBQVEsa0JBQVIsQ0FIRCxFQUZGOztBQU9KQyxhQUFTLE1BUEw7QUFRSkMsWUFBUSxDQUFDLHVDQUFELENBUkosRUFEUzs7O0FBWWZDLFFBWmUsK0JBWVJDLE9BWlEsRUFZQztBQUNkLGVBQVNDLGdCQUFULENBQTBCQyxNQUExQixFQUFrQztBQUNoQyxZQUFJLDRCQUFXQSxPQUFPQyxLQUFsQixDQUFKLEVBQThCO0FBQzVCSCxrQkFBUUksTUFBUixDQUFlO0FBQ2JDLGtCQUFNSCxNQURPO0FBRWJJLHFCQUFTLDhDQUZJO0FBR2JDLGVBSGEsNEJBR1RDLEtBSFMsRUFHRjtBQUNUO0FBQ0Esb0JBQUlDLGVBQWVDLGtCQUFLQyxLQUFMLENBQVdDLFFBQVgsQ0FBb0JGLGtCQUFLRyxPQUFMLENBQWEsd0NBQW9CYixPQUFwQixDQUFiLENBQXBCLEVBQWdFRSxPQUFPQyxLQUF2RSxDQUFuQjtBQUNBLG9CQUFJLENBQUNNLGFBQWFLLFVBQWIsQ0FBd0IsR0FBeEIsQ0FBTCxFQUFtQztBQUNqQ0wsK0NBQW9CQSxZQUFwQjtBQUNEO0FBQ0QsdUJBQU9ELE1BQU1PLFdBQU4sQ0FBa0JiLE1BQWxCLEVBQTBCYyxLQUFLQyxTQUFMLENBQWVSLFlBQWYsQ0FBMUIsQ0FBUDtBQUNELGVBVlksZ0JBQWY7O0FBWUQ7QUFDRjs7QUFFRCxVQUFNUywwQkFBWUMsVUFBVSxJQUF0QixFQUE0QkMsVUFBVSxJQUF0QyxJQUErQ3BCLFFBQVFrQixPQUFSLENBQWdCLENBQWhCLENBQS9DLENBQU47QUFDQSxhQUFPLGdDQUFjakIsZ0JBQWQsRUFBZ0NpQixPQUFoQyxDQUFQO0FBQ0QsS0FoQ2MsbUJBQWpCIiwiZmlsZSI6Im5vLWFic29sdXRlLXBhdGguanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgcGF0aCBmcm9tICdwYXRoJztcbmltcG9ydCB7IGdldFBoeXNpY2FsRmlsZW5hbWUgfSBmcm9tICdlc2xpbnQtbW9kdWxlLXV0aWxzL2NvbnRleHRDb21wYXQnO1xuaW1wb3J0IG1vZHVsZVZpc2l0b3IsIHsgbWFrZU9wdGlvbnNTY2hlbWEgfSBmcm9tICdlc2xpbnQtbW9kdWxlLXV0aWxzL21vZHVsZVZpc2l0b3InO1xuXG5pbXBvcnQgeyBpc0Fic29sdXRlIH0gZnJvbSAnLi4vY29yZS9pbXBvcnRUeXBlJztcbmltcG9ydCBkb2NzVXJsIGZyb20gJy4uL2RvY3NVcmwnO1xuXG5tb2R1bGUuZXhwb3J0cyA9IHtcbiAgbWV0YToge1xuICAgIHR5cGU6ICdzdWdnZXN0aW9uJyxcbiAgICBkb2NzOiB7XG4gICAgICBjYXRlZ29yeTogJ1N0YXRpYyBhbmFseXNpcycsXG4gICAgICBkZXNjcmlwdGlvbjogJ0ZvcmJpZCBpbXBvcnQgb2YgbW9kdWxlcyB1c2luZyBhYnNvbHV0ZSBwYXRocy4nLFxuICAgICAgdXJsOiBkb2NzVXJsKCduby1hYnNvbHV0ZS1wYXRoJyksXG4gICAgfSxcbiAgICBmaXhhYmxlOiAnY29kZScsXG4gICAgc2NoZW1hOiBbbWFrZU9wdGlvbnNTY2hlbWEoKV0sXG4gIH0sXG5cbiAgY3JlYXRlKGNvbnRleHQpIHtcbiAgICBmdW5jdGlvbiByZXBvcnRJZkFic29sdXRlKHNvdXJjZSkge1xuICAgICAgaWYgKGlzQWJzb2x1dGUoc291cmNlLnZhbHVlKSkge1xuICAgICAgICBjb250ZXh0LnJlcG9ydCh7XG4gICAgICAgICAgbm9kZTogc291cmNlLFxuICAgICAgICAgIG1lc3NhZ2U6ICdEbyBub3QgaW1wb3J0IG1vZHVsZXMgdXNpbmcgYW4gYWJzb2x1dGUgcGF0aCcsXG4gICAgICAgICAgZml4KGZpeGVyKSB7XG4gICAgICAgICAgICAvLyBub2RlLmpzIGFuZCB3ZWIgaW1wb3J0cyB3b3JrIHdpdGggcG9zaXggc3R5bGUgcGF0aHMgKFwiL1wiKVxuICAgICAgICAgICAgbGV0IHJlbGF0aXZlUGF0aCA9IHBhdGgucG9zaXgucmVsYXRpdmUocGF0aC5kaXJuYW1lKGdldFBoeXNpY2FsRmlsZW5hbWUoY29udGV4dCkpLCBzb3VyY2UudmFsdWUpO1xuICAgICAgICAgICAgaWYgKCFyZWxhdGl2ZVBhdGguc3RhcnRzV2l0aCgnLicpKSB7XG4gICAgICAgICAgICAgIHJlbGF0aXZlUGF0aCA9IGAuLyR7cmVsYXRpdmVQYXRofWA7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgICByZXR1cm4gZml4ZXIucmVwbGFjZVRleHQoc291cmNlLCBKU09OLnN0cmluZ2lmeShyZWxhdGl2ZVBhdGgpKTtcbiAgICAgICAgICB9LFxuICAgICAgICB9KTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICBjb25zdCBvcHRpb25zID0geyBlc21vZHVsZTogdHJ1ZSwgY29tbW9uanM6IHRydWUsIC4uLmNvbnRleHQub3B0aW9uc1swXSB9O1xuICAgIHJldHVybiBtb2R1bGVWaXNpdG9yKHJlcG9ydElmQWJzb2x1dGUsIG9wdGlvbnMpO1xuICB9LFxufTtcbiJdfQ==
@@ -0,0 +1,12 @@
import { createClassGroupUtils } from './class-group-utils'
import { createLruCache } from './lru-cache'
import { createParseClassName } from './parse-class-name'
import { GenericConfig } from './types'
export type ConfigUtils = ReturnType<typeof createConfigUtils>
export const createConfigUtils = (config: GenericConfig) => ({
cache: createLruCache<string, string>(config.cacheSize),
parseClassName: createParseClassName(config),
...createClassGroupUtils(config),
})
@@ -0,0 +1,93 @@
/**
* List of lowercase HTML “block” tag names.
*
* The list, when parsing HTML (flow), results in more relaxed rules (condition
* 6).
* Because they are known blocks, the HTML-like syntax doesn’t have to be
* strictly parsed.
* For tag names not in this list, a more strict algorithm (condition 7) is used
* to detect whether the HTML-like syntax is seen as HTML (flow) or not.
*
* This is copied from:
* <https://spec.commonmark.org/0.30/#html-blocks>.
*
* > 👉 **Note**: `search` was added in `CommonMark@0.31`.
*/
export const htmlBlockNames = [
'address',
'article',
'aside',
'base',
'basefont',
'blockquote',
'body',
'caption',
'center',
'col',
'colgroup',
'dd',
'details',
'dialog',
'dir',
'div',
'dl',
'dt',
'fieldset',
'figcaption',
'figure',
'footer',
'form',
'frame',
'frameset',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'head',
'header',
'hr',
'html',
'iframe',
'legend',
'li',
'link',
'main',
'menu',
'menuitem',
'nav',
'noframes',
'ol',
'optgroup',
'option',
'p',
'param',
'search',
'section',
'summary',
'table',
'tbody',
'td',
'tfoot',
'th',
'thead',
'title',
'tr',
'track',
'ul'
]
/**
* List of lowercase HTML “raw” tag names.
*
* The list, when parsing HTML (flow), results in HTML that can include lines
* without exiting, until a closing tag also in this list is found (condition
* 1).
*
* This module is copied from:
* <https://spec.commonmark.org/0.30/#html-blocks>.
*
* > 👉 **Note**: `textarea` was added in `CommonMark@0.30`.
*/
export const htmlRawNames = ['pre', 'script', 'style', 'textarea']
@@ -0,0 +1,2 @@
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"bannedFunctionType", [], import("../../rules").ESLintPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>;
export default _default;
@@ -0,0 +1,37 @@
/**
* @flow
*/
import type { JSXAttributeMockType } from './JSXAttributeMock';
export type JSXElementMockType = {
type: 'JSXElement',
openingElement: {
type: 'JSXOpeningElement',
name: {
type: 'JSXIdentifier',
name: string,
},
attributes: Array<JSXAttributeMockType>,
},
children: Array<Node>,
};
export default function JSXElementMock(
tagName: string,
attributes: Array<JSXAttributeMockType> = [],
children?: Array<Node> = [],
): JSXElementMockType {
return {
type: 'JSXElement',
openingElement: {
type: 'JSXOpeningElement',
name: {
type: 'JSXIdentifier',
name: tagName,
},
attributes,
},
children,
};
}
@@ -0,0 +1,2 @@
declare const _default: import("@typescript-eslint/utils/ts-eslint").RuleModule<"member", [], import("../utils/create-rule.ts").ImportXPluginDocs, import("@typescript-eslint/utils/ts-eslint").RuleListener>;
export default _default;
@@ -0,0 +1,463 @@
'use strict'
const log = require('npmlog')
const execFile = require('child_process').execFile
const fs = require('fs')
const path = require('path').win32
const logWithPrefix = require('./util').logWithPrefix
const regSearchKeys = require('./util').regSearchKeys
function findVisualStudio (nodeSemver, configMsvsVersion, callback) {
const finder = new VisualStudioFinder(nodeSemver, configMsvsVersion,
callback)
finder.findVisualStudio()
}
function VisualStudioFinder (nodeSemver, configMsvsVersion, callback) {
this.nodeSemver = nodeSemver
this.configMsvsVersion = configMsvsVersion
this.callback = callback
this.errorLog = []
this.validVersions = []
}
VisualStudioFinder.prototype = {
log: logWithPrefix(log, 'find VS'),
regSearchKeys: regSearchKeys,
// Logs a message at verbose level, but also saves it to be displayed later
// at error level if an error occurs. This should help diagnose the problem.
addLog: function addLog (message) {
this.log.verbose(message)
this.errorLog.push(message)
},
findVisualStudio: function findVisualStudio () {
this.configVersionYear = null
this.configPath = null
if (this.configMsvsVersion) {
this.addLog('msvs_version was set from command line or npm config')
if (this.configMsvsVersion.match(/^\d{4}$/)) {
this.configVersionYear = parseInt(this.configMsvsVersion, 10)
this.addLog(
`- looking for Visual Studio version ${this.configVersionYear}`)
} else {
this.configPath = path.resolve(this.configMsvsVersion)
this.addLog(
`- looking for Visual Studio installed in "${this.configPath}"`)
}
} else {
this.addLog('msvs_version not set from command line or npm config')
}
if (process.env.VCINSTALLDIR) {
this.envVcInstallDir =
path.resolve(process.env.VCINSTALLDIR, '..')
this.addLog('running in VS Command Prompt, installation path is:\n' +
`"${this.envVcInstallDir}"\n- will only use this version`)
} else {
this.addLog('VCINSTALLDIR not set, not running in VS Command Prompt')
}
this.findVisualStudio2017OrNewer((info) => {
if (info) {
return this.succeed(info)
}
this.findVisualStudio2015((info) => {
if (info) {
return this.succeed(info)
}
this.findVisualStudio2013((info) => {
if (info) {
return this.succeed(info)
}
this.fail()
})
})
})
},
succeed: function succeed (info) {
this.log.info(`using VS${info.versionYear} (${info.version}) found at:` +
`\n"${info.path}"` +
'\nrun with --verbose for detailed information')
process.nextTick(this.callback.bind(null, null, info))
},
fail: function fail () {
if (this.configMsvsVersion && this.envVcInstallDir) {
this.errorLog.push(
'msvs_version does not match this VS Command Prompt or the',
'installation cannot be used.')
} else if (this.configMsvsVersion) {
// If msvs_version was specified but finding VS failed, print what would
// have been accepted
this.errorLog.push('')
if (this.validVersions) {
this.errorLog.push('valid versions for msvs_version:')
this.validVersions.forEach((version) => {
this.errorLog.push(`- "${version}"`)
})
} else {
this.errorLog.push('no valid versions for msvs_version were found')
}
}
const errorLog = this.errorLog.join('\n')
// For Windows 80 col console, use up to the column before the one marked
// with X (total 79 chars including logger prefix, 62 chars usable here):
// X
const infoLog = [
'**************************************************************',
'You need to install the latest version of Visual Studio',
'including the "Desktop development with C++" workload.',
'For more information consult the documentation at:',
'https://github.com/nodejs/node-gyp#on-windows',
'**************************************************************'
].join('\n')
this.log.error(`\n${errorLog}\n\n${infoLog}\n`)
process.nextTick(this.callback.bind(null, new Error(
'Could not find any Visual Studio installation to use')))
},
// Invoke the PowerShell script to get information about Visual Studio 2017
// or newer installations
findVisualStudio2017OrNewer: function findVisualStudio2017OrNewer (cb) {
var ps = path.join(process.env.SystemRoot, 'System32',
'WindowsPowerShell', 'v1.0', 'powershell.exe')
var csFile = path.join(__dirname, 'Find-VisualStudio.cs')
var psArgs = [
'-ExecutionPolicy',
'Unrestricted',
'-NoProfile',
'-Command',
'&{Add-Type -Path \'' + csFile + '\';' + '[VisualStudioConfiguration.Main]::PrintJson()}'
]
this.log.silly('Running', ps, psArgs)
var child = execFile(ps, psArgs, { encoding: 'utf8' },
(err, stdout, stderr) => {
this.parseData(err, stdout, stderr, cb)
})
child.stdin.end()
},
// Parse the output of the PowerShell script and look for an installation
// of Visual Studio 2017 or newer to use
parseData: function parseData (err, stdout, stderr, cb) {
this.log.silly('PS stderr = %j', stderr)
const failPowershell = () => {
this.addLog(
'could not use PowerShell to find Visual Studio 2017 or newer, try re-running with \'--loglevel silly\' for more details')
cb(null)
}
if (err) {
this.log.silly('PS err = %j', err && (err.stack || err))
return failPowershell()
}
var vsInfo
try {
vsInfo = JSON.parse(stdout)
} catch (e) {
this.log.silly('PS stdout = %j', stdout)
this.log.silly(e)
return failPowershell()
}
if (!Array.isArray(vsInfo)) {
this.log.silly('PS stdout = %j', stdout)
return failPowershell()
}
vsInfo = vsInfo.map((info) => {
this.log.silly(`processing installation: "${info.path}"`)
info.path = path.resolve(info.path)
var ret = this.getVersionInfo(info)
ret.path = info.path
ret.msBuild = this.getMSBuild(info, ret.versionYear)
ret.toolset = this.getToolset(info, ret.versionYear)
ret.sdk = this.getSDK(info)
return ret
})
this.log.silly('vsInfo:', vsInfo)
// Remove future versions or errors parsing version number
vsInfo = vsInfo.filter((info) => {
if (info.versionYear) {
return true
}
this.addLog(`unknown version "${info.version}" found at "${info.path}"`)
return false
})
// Sort to place newer versions first
vsInfo.sort((a, b) => b.versionYear - a.versionYear)
for (var i = 0; i < vsInfo.length; ++i) {
const info = vsInfo[i]
this.addLog(`checking VS${info.versionYear} (${info.version}) found ` +
`at:\n"${info.path}"`)
if (info.msBuild) {
this.addLog('- found "Visual Studio C++ core features"')
} else {
this.addLog('- "Visual Studio C++ core features" missing')
continue
}
if (info.toolset) {
this.addLog(`- found VC++ toolset: ${info.toolset}`)
} else {
this.addLog('- missing any VC++ toolset')
continue
}
if (info.sdk) {
this.addLog(`- found Windows SDK: ${info.sdk}`)
} else {
this.addLog('- missing any Windows SDK')
continue
}
if (!this.checkConfigVersion(info.versionYear, info.path)) {
continue
}
return cb(info)
}
this.addLog(
'could not find a version of Visual Studio 2017 or newer to use')
cb(null)
},
// Helper - process version information
getVersionInfo: function getVersionInfo (info) {
const match = /^(\d+)\.(\d+)\..*/.exec(info.version)
if (!match) {
this.log.silly('- failed to parse version:', info.version)
return {}
}
this.log.silly('- version match = %j', match)
var ret = {
version: info.version,
versionMajor: parseInt(match[1], 10),
versionMinor: parseInt(match[2], 10)
}
if (ret.versionMajor === 15) {
ret.versionYear = 2017
return ret
}
if (ret.versionMajor === 16) {
ret.versionYear = 2019
return ret
}
if (ret.versionMajor === 17) {
ret.versionYear = 2022
return ret
}
this.log.silly('- unsupported version:', ret.versionMajor)
return {}
},
msBuildPathExists: function msBuildPathExists (path) {
return fs.existsSync(path)
},
// Helper - process MSBuild information
getMSBuild: function getMSBuild (info, versionYear) {
const pkg = 'Microsoft.VisualStudio.VC.MSBuild.Base'
const msbuildPath = path.join(info.path, 'MSBuild', 'Current', 'Bin', 'MSBuild.exe')
const msbuildPathArm64 = path.join(info.path, 'MSBuild', 'Current', 'Bin', 'arm64', 'MSBuild.exe')
if (info.packages.indexOf(pkg) !== -1) {
this.log.silly('- found VC.MSBuild.Base')
if (versionYear === 2017) {
return path.join(info.path, 'MSBuild', '15.0', 'Bin', 'MSBuild.exe')
}
if (versionYear === 2019) {
return msbuildPath
}
}
/**
* Visual Studio 2022 doesn't have the MSBuild package.
* Support for compiling _on_ ARM64 was added in MSVC 14.32.31326,
* so let's leverage it if the user has an ARM64 device.
*/
if (process.arch === 'arm64' && this.msBuildPathExists(msbuildPathArm64)) {
return msbuildPathArm64
} else if (this.msBuildPathExists(msbuildPath)) {
return msbuildPath
}
return null
},
// Helper - process toolset information
getToolset: function getToolset (info, versionYear) {
const pkg = 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64'
const express = 'Microsoft.VisualStudio.WDExpress'
if (info.packages.indexOf(pkg) !== -1) {
this.log.silly('- found VC.Tools.x86.x64')
} else if (info.packages.indexOf(express) !== -1) {
this.log.silly('- found Visual Studio Express (looking for toolset)')
} else {
return null
}
if (versionYear === 2017) {
return 'v141'
} else if (versionYear === 2019) {
return 'v142'
} else if (versionYear === 2022) {
return 'v143'
}
this.log.silly('- invalid versionYear:', versionYear)
return null
},
// Helper - process Windows SDK information
getSDK: function getSDK (info) {
const win8SDK = 'Microsoft.VisualStudio.Component.Windows81SDK'
const win10SDKPrefix = 'Microsoft.VisualStudio.Component.Windows10SDK.'
const win11SDKPrefix = 'Microsoft.VisualStudio.Component.Windows11SDK.'
var Win10or11SDKVer = 0
info.packages.forEach((pkg) => {
if (!pkg.startsWith(win10SDKPrefix) && !pkg.startsWith(win11SDKPrefix)) {
return
}
const parts = pkg.split('.')
if (parts.length > 5 && parts[5] !== 'Desktop') {
this.log.silly('- ignoring non-Desktop Win10/11SDK:', pkg)
return
}
const foundSdkVer = parseInt(parts[4], 10)
if (isNaN(foundSdkVer)) {
// Microsoft.VisualStudio.Component.Windows10SDK.IpOverUsb
this.log.silly('- failed to parse Win10/11SDK number:', pkg)
return
}
this.log.silly('- found Win10/11SDK:', foundSdkVer)
Win10or11SDKVer = Math.max(Win10or11SDKVer, foundSdkVer)
})
if (Win10or11SDKVer !== 0) {
return `10.0.${Win10or11SDKVer}.0`
} else if (info.packages.indexOf(win8SDK) !== -1) {
this.log.silly('- found Win8SDK')
return '8.1'
}
return null
},
// Find an installation of Visual Studio 2015 to use
findVisualStudio2015: function findVisualStudio2015 (cb) {
if (this.nodeSemver.major >= 19) {
this.addLog(
'not looking for VS2015 as it is only supported up to Node.js 18')
return cb(null)
}
return this.findOldVS({
version: '14.0',
versionMajor: 14,
versionMinor: 0,
versionYear: 2015,
toolset: 'v140'
}, cb)
},
// Find an installation of Visual Studio 2013 to use
findVisualStudio2013: function findVisualStudio2013 (cb) {
if (this.nodeSemver.major >= 9) {
this.addLog(
'not looking for VS2013 as it is only supported up to Node.js 8')
return cb(null)
}
return this.findOldVS({
version: '12.0',
versionMajor: 12,
versionMinor: 0,
versionYear: 2013,
toolset: 'v120'
}, cb)
},
// Helper - common code for VS2013 and VS2015
findOldVS: function findOldVS (info, cb) {
const regVC7 = ['HKLM\\Software\\Microsoft\\VisualStudio\\SxS\\VC7',
'HKLM\\Software\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VC7']
const regMSBuild = 'HKLM\\Software\\Microsoft\\MSBuild\\ToolsVersions'
this.addLog(`looking for Visual Studio ${info.versionYear}`)
this.regSearchKeys(regVC7, info.version, [], (err, res) => {
if (err) {
this.addLog('- not found')
return cb(null)
}
const vsPath = path.resolve(res, '..')
this.addLog(`- found in "${vsPath}"`)
const msBuildRegOpts = process.arch === 'ia32' ? [] : ['/reg:32']
this.regSearchKeys([`${regMSBuild}\\${info.version}`],
'MSBuildToolsPath', msBuildRegOpts, (err, res) => {
if (err) {
this.addLog(
'- could not find MSBuild in registry for this version')
return cb(null)
}
const msBuild = path.join(res, 'MSBuild.exe')
this.addLog(`- MSBuild in "${msBuild}"`)
if (!this.checkConfigVersion(info.versionYear, vsPath)) {
return cb(null)
}
info.path = vsPath
info.msBuild = msBuild
info.sdk = null
cb(info)
})
})
},
// After finding a usable version of Visual Studio:
// - add it to validVersions to be displayed at the end if a specific
// version was requested and not found;
// - check if this is the version that was requested.
// - check if this matches the Visual Studio Command Prompt
checkConfigVersion: function checkConfigVersion (versionYear, vsPath) {
this.validVersions.push(versionYear)
this.validVersions.push(vsPath)
if (this.configVersionYear && this.configVersionYear !== versionYear) {
this.addLog('- msvs_version does not match this version')
return false
}
if (this.configPath &&
path.relative(this.configPath, vsPath) !== '') {
this.addLog('- msvs_version does not point to this installation')
return false
}
if (this.envVcInstallDir &&
path.relative(this.envVcInstallDir, vsPath) !== '') {
this.addLog('- does not match this Visual Studio Command Prompt')
return false
}
return true
}
}
module.exports = findVisualStudio
module.exports.test = {
VisualStudioFinder: VisualStudioFinder,
findVisualStudio: findVisualStudio
}
@@ -0,0 +1,2 @@
import type { LibDefinition } from '../variable';
export declare const es2023_intl: LibDefinition;
@@ -0,0 +1,24 @@
'use strict'
var util = require('util')
var User = exports.User = function User (msg) {
var err = new Error(msg)
Error.captureStackTrace(err, User)
err.code = 'EGAUGE'
return err
}
exports.MissingTemplateValue = function MissingTemplateValue (item, values) {
var err = new User(util.format('Missing template value "%s"', item.type))
Error.captureStackTrace(err, MissingTemplateValue)
err.template = item
err.values = values
return err
}
exports.Internal = function Internal (msg) {
var err = new Error(msg)
Error.captureStackTrace(err, Internal)
err.code = 'EGAUGEINTERNAL'
return err
}
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2014-2017, Jon Schlinkert.
Copyright (c) 2009-2014, TJ Holowaychuk
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.
@@ -0,0 +1,47 @@
import setupTrackingContext from './lib/setupTrackingContext'
import processTailwindFeatures from './processTailwindFeatures'
import { env } from './lib/sharedState'
import { findAtConfigPath } from './lib/findAtConfigPath'
module.exports = function tailwindcss(configOrPath) {
return {
postcssPlugin: 'tailwindcss',
plugins: [
env.DEBUG &&
function (root) {
console.log('\n')
console.time('JIT TOTAL')
return root
},
async function (root, result) {
// Use the path for the `@config` directive if it exists, otherwise use the
// path for the file being processed
configOrPath = findAtConfigPath(root, result) ?? configOrPath
let context = setupTrackingContext(configOrPath)
if (root.type === 'document') {
let roots = root.nodes.filter((node) => node.type === 'root')
for (const root of roots) {
if (root.type === 'root') {
await processTailwindFeatures(context)(root, result)
}
}
return
}
await processTailwindFeatures(context)(root, result)
},
env.DEBUG &&
function (root) {
console.timeEnd('JIT TOTAL')
console.log('\n')
return root
},
].filter(Boolean),
}
}
module.exports.postcss = true
@@ -0,0 +1 @@
!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?module.exports=i():"function"==typeof define&&define.amd?define(i):(t="undefined"!=typeof globalThis?globalThis:t||self).dayjs_plugin_badMutable=i()}(this,(function(){"use strict";return function(t,i){var n=i.prototype;n.$g=function(t,i,n){return this.$utils().u(t)?this[i]:this.$set(n,t)},n.set=function(t,i){return this.$set(t,i)};var e=n.startOf;n.startOf=function(t,i){return this.$d=e.bind(this)(t,i).toDate(),this.init(),this};var s=n.add;n.add=function(t,i){return this.$d=s.bind(this)(t,i).toDate(),this.init(),this};var o=n.locale;n.locale=function(t,i){return t?(this.$L=o.bind(this)(t,i).$L,this):this.$L};var r=n.daysInMonth;n.daysInMonth=function(){return r.bind(this.clone())()};var u=n.isSame;n.isSame=function(t,i){return u.bind(this.clone())(t,i)};var f=n.isBefore;n.isBefore=function(t,i){return f.bind(this.clone())(t,i)};var d=n.isAfter;n.isAfter=function(t,i){return d.bind(this.clone())(t,i)}}}));
@@ -0,0 +1,26 @@
import { OctetString } from "@peculiar/asn1-schema";
import { ContentType, ContentEncryptionAlgorithmIdentifier } from "./types";
/**
* ```asn
* EncryptedContent ::= OCTET STRING
* ```
*/
export declare class EncryptedContent {
value?: OctetString;
constructedValue?: OctetString[];
constructor(params?: Partial<EncryptedContent>);
}
/**
* ```asn
* EncryptedContentInfo ::= SEQUENCE {
* contentType ContentType,
* contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier,
* encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL }
* ```
*/
export declare class EncryptedContentInfo {
contentType: ContentType;
contentEncryptionAlgorithm: ContentEncryptionAlgorithmIdentifier;
encryptedContent?: EncryptedContent;
constructor(params?: Partial<EncryptedContentInfo>);
}
@@ -0,0 +1 @@
var u=Object.defineProperty;var r=t=>u(t,"__esModule",{value:!0});var y=(t,o)=>{r(t);for(var s in o)u(t,s,{get:o[s],enumerable:!0})};y(exports,{default:()=>b,stableHash:()=>c});const i=new WeakMap;let p=0;function c(t){const o=typeof t,s=t&&t.constructor,f=s==Date;if(Object(t)===t&&!f&&s!=RegExp){let e=i.get(t);if(e)return e;e=++p+"~",i.set(t,e);let n;if(s==Array){for(e="@",n=0;n<t.length;n++)e+=c(t[n])+",";i.set(t,e)}else if(s==Object){e="#";const l=Object.keys(t).sort();for(;(n=l.pop())!==void 0;)t[n]!==void 0&&(e+=n+":"+c(t[n])+",");i.set(t,e)}return e}return f?t.toJSON():o=="symbol"?t.toString():o=="string"?JSON.stringify(t):""+t}var b=c;
@@ -0,0 +1,348 @@
# @jridgewell/trace-mapping
> Trace the original position through a source map
`trace-mapping` allows you to take the line and column of an output file and trace it to the
original location in the source file through a source map.
You may already be familiar with the [`source-map`][source-map] package's `SourceMapConsumer`. This
provides the same `originalPositionFor` and `generatedPositionFor` API, without requiring WASM.
## Installation
```sh
npm install @jridgewell/trace-mapping
```
## Usage
```typescript
import {
TraceMap,
originalPositionFor,
generatedPositionFor,
sourceContentFor,
isIgnored,
} from '@jridgewell/trace-mapping';
const tracer = new TraceMap({
version: 3,
sources: ['input.js'],
sourcesContent: ['content of input.js'],
names: ['foo'],
mappings: 'KAyCIA',
ignoreList: [],
});
// Lines start at line 1, columns at column 0.
const traced = originalPositionFor(tracer, { line: 1, column: 5 });
assert.deepEqual(traced, {
source: 'input.js',
line: 42,
column: 4,
name: 'foo',
});
const content = sourceContentFor(tracer, traced.source);
assert.strictEqual(content, 'content for input.js');
const generated = generatedPositionFor(tracer, {
source: 'input.js',
line: 42,
column: 4,
});
assert.deepEqual(generated, {
line: 1,
column: 5,
});
const ignored = isIgnored(tracer, 'input.js');
assert.equal(ignored, false);
```
We also provide a lower level API to get the actual segment that matches our line and column. Unlike
`originalPositionFor`, `traceSegment` uses a 0-base for `line`:
```typescript
import { traceSegment } from '@jridgewell/trace-mapping';
// line is 0-base.
const traced = traceSegment(tracer, /* line */ 0, /* column */ 5);
// Segments are [outputColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]
// Again, line is 0-base and so is sourceLine
assert.deepEqual(traced, [5, 0, 41, 4, 0]);
```
### SectionedSourceMaps
The sourcemap spec defines a special `sections` field that's designed to handle concatenation of
output code with associated sourcemaps. This type of sourcemap is rarely used (no major build tool
produces it), but if you are hand coding a concatenation you may need it. We provide an `AnyMap`
helper that can receive either a regular sourcemap or a `SectionedSourceMap` and returns a
`TraceMap` instance:
```typescript
import { AnyMap } from '@jridgewell/trace-mapping';
const fooOutput = 'foo';
const barOutput = 'bar';
const output = [fooOutput, barOutput].join('\n');
const sectioned = new AnyMap({
version: 3,
sections: [
{
// 0-base line and column
offset: { line: 0, column: 0 },
// fooOutput's sourcemap
map: {
version: 3,
sources: ['foo.js'],
names: ['foo'],
mappings: 'AAAAA',
},
},
{
// barOutput's sourcemap will not affect the first line, only the second
offset: { line: 1, column: 0 },
map: {
version: 3,
sources: ['bar.js'],
names: ['bar'],
mappings: 'AAAAA',
},
},
],
});
const traced = originalPositionFor(sectioned, {
line: 2,
column: 0,
});
assert.deepEqual(traced, {
source: 'bar.js',
line: 1,
column: 0,
name: 'bar',
});
```
## Benchmarks
```
node v20.10.0
amp.js.map - 45120 segments
Memory Usage:
trace-mapping decoded 414164 bytes
trace-mapping encoded 6274352 bytes
source-map-js 10968904 bytes
source-map-0.6.1 17587160 bytes
source-map-0.8.0 8812155 bytes
Chrome dev tools 8672912 bytes
Smallest memory usage is trace-mapping decoded
Init speed:
trace-mapping: decoded JSON input x 205 ops/sec ±0.19% (88 runs sampled)
trace-mapping: encoded JSON input x 405 ops/sec ±1.47% (88 runs sampled)
trace-mapping: decoded Object input x 4,645 ops/sec ±0.15% (98 runs sampled)
trace-mapping: encoded Object input x 458 ops/sec ±1.63% (91 runs sampled)
source-map-js: encoded Object input x 75.48 ops/sec ±1.64% (67 runs sampled)
source-map-0.6.1: encoded Object input x 39.37 ops/sec ±1.44% (53 runs sampled)
Chrome dev tools: encoded Object input x 150 ops/sec ±1.76% (79 runs sampled)
Fastest is trace-mapping: decoded Object input
Trace speed (random):
trace-mapping: decoded originalPositionFor x 44,946 ops/sec ±0.16% (99 runs sampled)
trace-mapping: encoded originalPositionFor x 37,995 ops/sec ±1.81% (89 runs sampled)
source-map-js: encoded originalPositionFor x 9,230 ops/sec ±1.36% (93 runs sampled)
source-map-0.6.1: encoded originalPositionFor x 8,057 ops/sec ±0.84% (96 runs sampled)
source-map-0.8.0: encoded originalPositionFor x 28,198 ops/sec ±1.12% (91 runs sampled)
Chrome dev tools: encoded originalPositionFor x 46,276 ops/sec ±1.35% (95 runs sampled)
Fastest is Chrome dev tools: encoded originalPositionFor
Trace speed (ascending):
trace-mapping: decoded originalPositionFor x 204,406 ops/sec ±0.19% (97 runs sampled)
trace-mapping: encoded originalPositionFor x 196,695 ops/sec ±0.24% (99 runs sampled)
source-map-js: encoded originalPositionFor x 11,948 ops/sec ±0.94% (99 runs sampled)
source-map-0.6.1: encoded originalPositionFor x 10,730 ops/sec ±0.36% (100 runs sampled)
source-map-0.8.0: encoded originalPositionFor x 51,427 ops/sec ±0.21% (98 runs sampled)
Chrome dev tools: encoded originalPositionFor x 162,615 ops/sec ±0.18% (98 runs sampled)
Fastest is trace-mapping: decoded originalPositionFor
***
babel.min.js.map - 347793 segments
Memory Usage:
trace-mapping decoded 18504 bytes
trace-mapping encoded 35428008 bytes
source-map-js 51676808 bytes
source-map-0.6.1 63367136 bytes
source-map-0.8.0 43158400 bytes
Chrome dev tools 50721552 bytes
Smallest memory usage is trace-mapping decoded
Init speed:
trace-mapping: decoded JSON input x 17.82 ops/sec ±6.35% (35 runs sampled)
trace-mapping: encoded JSON input x 31.57 ops/sec ±7.50% (43 runs sampled)
trace-mapping: decoded Object input x 867 ops/sec ±0.74% (94 runs sampled)
trace-mapping: encoded Object input x 33.83 ops/sec ±7.66% (46 runs sampled)
source-map-js: encoded Object input x 6.58 ops/sec ±3.31% (20 runs sampled)
source-map-0.6.1: encoded Object input x 4.23 ops/sec ±3.43% (15 runs sampled)
Chrome dev tools: encoded Object input x 22.14 ops/sec ±3.79% (41 runs sampled)
Fastest is trace-mapping: decoded Object input
Trace speed (random):
trace-mapping: decoded originalPositionFor x 78,234 ops/sec ±1.48% (29 runs sampled)
trace-mapping: encoded originalPositionFor x 60,761 ops/sec ±1.35% (21 runs sampled)
source-map-js: encoded originalPositionFor x 51,448 ops/sec ±2.17% (89 runs sampled)
source-map-0.6.1: encoded originalPositionFor x 47,221 ops/sec ±1.99% (15 runs sampled)
source-map-0.8.0: encoded originalPositionFor x 84,002 ops/sec ±1.45% (27 runs sampled)
Chrome dev tools: encoded originalPositionFor x 106,457 ops/sec ±1.38% (37 runs sampled)
Fastest is Chrome dev tools: encoded originalPositionFor
Trace speed (ascending):
trace-mapping: decoded originalPositionFor x 930,943 ops/sec ±0.25% (99 runs sampled)
trace-mapping: encoded originalPositionFor x 843,545 ops/sec ±0.34% (97 runs sampled)
source-map-js: encoded originalPositionFor x 114,510 ops/sec ±1.37% (36 runs sampled)
source-map-0.6.1: encoded originalPositionFor x 87,412 ops/sec ±0.72% (92 runs sampled)
source-map-0.8.0: encoded originalPositionFor x 197,709 ops/sec ±0.89% (59 runs sampled)
Chrome dev tools: encoded originalPositionFor x 688,983 ops/sec ±0.33% (98 runs sampled)
Fastest is trace-mapping: decoded originalPositionFor
***
preact.js.map - 1992 segments
Memory Usage:
trace-mapping decoded 33136 bytes
trace-mapping encoded 254240 bytes
source-map-js 837488 bytes
source-map-0.6.1 961928 bytes
source-map-0.8.0 54384 bytes
Chrome dev tools 709680 bytes
Smallest memory usage is trace-mapping decoded
Init speed:
trace-mapping: decoded JSON input x 3,709 ops/sec ±0.13% (99 runs sampled)
trace-mapping: encoded JSON input x 6,447 ops/sec ±0.22% (101 runs sampled)
trace-mapping: decoded Object input x 83,062 ops/sec ±0.23% (100 runs sampled)
trace-mapping: encoded Object input x 14,980 ops/sec ±0.28% (100 runs sampled)
source-map-js: encoded Object input x 2,544 ops/sec ±0.16% (99 runs sampled)
source-map-0.6.1: encoded Object input x 1,221 ops/sec ±0.37% (97 runs sampled)
Chrome dev tools: encoded Object input x 4,241 ops/sec ±0.39% (93 runs sampled)
Fastest is trace-mapping: decoded Object input
Trace speed (random):
trace-mapping: decoded originalPositionFor x 91,028 ops/sec ±0.14% (94 runs sampled)
trace-mapping: encoded originalPositionFor x 84,348 ops/sec ±0.26% (98 runs sampled)
source-map-js: encoded originalPositionFor x 26,998 ops/sec ±0.23% (98 runs sampled)
source-map-0.6.1: encoded originalPositionFor x 18,049 ops/sec ±0.26% (100 runs sampled)
source-map-0.8.0: encoded originalPositionFor x 41,916 ops/sec ±0.28% (98 runs sampled)
Chrome dev tools: encoded originalPositionFor x 88,616 ops/sec ±0.14% (98 runs sampled)
Fastest is trace-mapping: decoded originalPositionFor
Trace speed (ascending):
trace-mapping: decoded originalPositionFor x 319,960 ops/sec ±0.16% (100 runs sampled)
trace-mapping: encoded originalPositionFor x 302,153 ops/sec ±0.18% (100 runs sampled)
source-map-js: encoded originalPositionFor x 35,574 ops/sec ±0.19% (100 runs sampled)
source-map-0.6.1: encoded originalPositionFor x 19,943 ops/sec ±0.12% (101 runs sampled)
source-map-0.8.0: encoded originalPositionFor x 54,648 ops/sec ±0.20% (99 runs sampled)
Chrome dev tools: encoded originalPositionFor x 278,319 ops/sec ±0.17% (102 runs sampled)
Fastest is trace-mapping: decoded originalPositionFor
***
react.js.map - 5726 segments
Memory Usage:
trace-mapping decoded 10872 bytes
trace-mapping encoded 681512 bytes
source-map-js 2563944 bytes
source-map-0.6.1 2150864 bytes
source-map-0.8.0 88680 bytes
Chrome dev tools 1149576 bytes
Smallest memory usage is trace-mapping decoded
Init speed:
trace-mapping: decoded JSON input x 1,887 ops/sec ±0.28% (99 runs sampled)
trace-mapping: encoded JSON input x 4,749 ops/sec ±0.48% (97 runs sampled)
trace-mapping: decoded Object input x 74,236 ops/sec ±0.11% (99 runs sampled)
trace-mapping: encoded Object input x 5,752 ops/sec ±0.38% (100 runs sampled)
source-map-js: encoded Object input x 806 ops/sec ±0.19% (97 runs sampled)
source-map-0.6.1: encoded Object input x 418 ops/sec ±0.33% (94 runs sampled)
Chrome dev tools: encoded Object input x 1,524 ops/sec ±0.57% (92 runs sampled)
Fastest is trace-mapping: decoded Object input
Trace speed (random):
trace-mapping: decoded originalPositionFor x 620,201 ops/sec ±0.33% (96 runs sampled)
trace-mapping: encoded originalPositionFor x 579,548 ops/sec ±0.35% (97 runs sampled)
source-map-js: encoded originalPositionFor x 230,983 ops/sec ±0.62% (54 runs sampled)
source-map-0.6.1: encoded originalPositionFor x 158,145 ops/sec ±0.80% (46 runs sampled)
source-map-0.8.0: encoded originalPositionFor x 343,801 ops/sec ±0.55% (96 runs sampled)
Chrome dev tools: encoded originalPositionFor x 659,649 ops/sec ±0.49% (98 runs sampled)
Fastest is Chrome dev tools: encoded originalPositionFor
Trace speed (ascending):
trace-mapping: decoded originalPositionFor x 2,368,079 ops/sec ±0.32% (98 runs sampled)
trace-mapping: encoded originalPositionFor x 2,134,039 ops/sec ±2.72% (87 runs sampled)
source-map-js: encoded originalPositionFor x 290,120 ops/sec ±2.49% (82 runs sampled)
source-map-0.6.1: encoded originalPositionFor x 187,613 ops/sec ±0.86% (49 runs sampled)
source-map-0.8.0: encoded originalPositionFor x 479,569 ops/sec ±0.65% (96 runs sampled)
Chrome dev tools: encoded originalPositionFor x 2,048,414 ops/sec ±0.24% (98 runs sampled)
Fastest is trace-mapping: decoded originalPositionFor
***
vscode.map - 2141001 segments
Memory Usage:
trace-mapping decoded 5206584 bytes
trace-mapping encoded 208370336 bytes
source-map-js 278493008 bytes
source-map-0.6.1 391564048 bytes
source-map-0.8.0 257508787 bytes
Chrome dev tools 291053000 bytes
Smallest memory usage is trace-mapping decoded
Init speed:
trace-mapping: decoded JSON input x 1.63 ops/sec ±33.88% (9 runs sampled)
trace-mapping: encoded JSON input x 3.29 ops/sec ±36.13% (13 runs sampled)
trace-mapping: decoded Object input x 103 ops/sec ±0.93% (77 runs sampled)
trace-mapping: encoded Object input x 5.42 ops/sec ±28.54% (19 runs sampled)
source-map-js: encoded Object input x 1.07 ops/sec ±13.84% (7 runs sampled)
source-map-0.6.1: encoded Object input x 0.60 ops/sec ±2.43% (6 runs sampled)
Chrome dev tools: encoded Object input x 2.61 ops/sec ±22.00% (11 runs sampled)
Fastest is trace-mapping: decoded Object input
Trace speed (random):
trace-mapping: decoded originalPositionFor x 257,019 ops/sec ±0.97% (93 runs sampled)
trace-mapping: encoded originalPositionFor x 179,163 ops/sec ±0.83% (92 runs sampled)
source-map-js: encoded originalPositionFor x 73,337 ops/sec ±1.35% (87 runs sampled)
source-map-0.6.1: encoded originalPositionFor x 38,797 ops/sec ±1.66% (88 runs sampled)
source-map-0.8.0: encoded originalPositionFor x 107,758 ops/sec ±1.94% (45 runs sampled)
Chrome dev tools: encoded originalPositionFor x 188,550 ops/sec ±1.85% (79 runs sampled)
Fastest is trace-mapping: decoded originalPositionFor
Trace speed (ascending):
trace-mapping: decoded originalPositionFor x 447,621 ops/sec ±3.64% (94 runs sampled)
trace-mapping: encoded originalPositionFor x 323,698 ops/sec ±5.20% (88 runs sampled)
source-map-js: encoded originalPositionFor x 78,387 ops/sec ±1.69% (89 runs sampled)
source-map-0.6.1: encoded originalPositionFor x 41,016 ops/sec ±3.01% (25 runs sampled)
source-map-0.8.0: encoded originalPositionFor x 124,204 ops/sec ±0.90% (92 runs sampled)
Chrome dev tools: encoded originalPositionFor x 230,087 ops/sec ±2.61% (93 runs sampled)
Fastest is trace-mapping: decoded originalPositionFor
```
[source-map]: https://www.npmjs.com/package/source-map
@@ -0,0 +1,17 @@
import { clamp } from 'motion-utils';
const number = {
test: (v) => typeof v === "number",
parse: parseFloat,
transform: (v) => v,
};
const alpha = {
...number,
transform: (v) => clamp(0, 1, v),
};
const scale = {
...number,
default: 1,
};
export { alpha, number, scale };
@@ -0,0 +1,5 @@
import type { ZodErrorMap } from "./ZodError.js";
import defaultErrorMap from "./locales/en.js";
export { defaultErrorMap };
export declare function setErrorMap(map: ZodErrorMap): void;
export declare function getErrorMap(): ZodErrorMap;
@@ -0,0 +1,95 @@
# is-windows [![NPM version](https://img.shields.io/npm/v/is-windows.svg?style=flat)](https://www.npmjs.com/package/is-windows) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-windows.svg?style=flat)](https://npmjs.org/package/is-windows) [![NPM total downloads](https://img.shields.io/npm/dt/is-windows.svg?style=flat)](https://npmjs.org/package/is-windows) [![Linux Build Status](https://img.shields.io/travis/jonschlinkert/is-windows.svg?style=flat&label=Travis)](https://travis-ci.org/jonschlinkert/is-windows)
> Returns true if the platform is windows. UMD module, works with node.js, commonjs, browser, AMD, electron, etc.
Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support.
## Install
Install with [npm](https://www.npmjs.com/):
```sh
$ npm install --save is-windows
```
## Heads up!
As of `v0.2.0` this module always returns a function.
## Node.js usage
```js
var isWindows = require('is-windows');
console.log(isWindows());
//=> returns true if the platform is windows
```
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
</details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
$ npm install && npm test
```
</details>
<details>
<summary><strong>Building docs</strong></summary>
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
$ npm install -g verbose/verb#dev verb-generate-readme && verb
```
</details>
### Related projects
You might also be interested in these projects:
* [is-absolute](https://www.npmjs.com/package/is-absolute): Returns true if a file path is absolute. Does not rely on the path module… [more](https://github.com/jonschlinkert/is-absolute) | [homepage](https://github.com/jonschlinkert/is-absolute "Returns true if a file path is absolute. Does not rely on the path module and can be used as a polyfill for node.js native `path.isAbolute`.")
* [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet")
* [is-relative](https://www.npmjs.com/package/is-relative): Returns `true` if the path appears to be relative. | [homepage](https://github.com/jonschlinkert/is-relative "Returns `true` if the path appears to be relative.")
* [isobject](https://www.npmjs.com/package/isobject): Returns true if the value is an object and not an array or null. | [homepage](https://github.com/jonschlinkert/isobject "Returns true if the value is an object and not an array or null.")
* [window-size](https://www.npmjs.com/package/window-size): Reliable way to get the height and width of terminal/console, since it's not calculated or… [more](https://github.com/jonschlinkert/window-size) | [homepage](https://github.com/jonschlinkert/window-size "Reliable way to get the height and width of terminal/console, since it's not calculated or updated the same way on all platforms, environments and node.js versions.")
### Contributors
| **Commits** | **Contributor** |
| --- | --- |
| 11 | [jonschlinkert](https://github.com/jonschlinkert) |
| 4 | [doowb](https://github.com/doowb) |
| 1 | [SimenB](https://github.com/SimenB) |
| 1 | [gucong3000](https://github.com/gucong3000) |
### Author
**Jon Schlinkert**
* [linkedin/in/jonschlinkert](https://linkedin.com/in/jonschlinkert)
* [github/jonschlinkert](https://github.com/jonschlinkert)
* [twitter/jonschlinkert](https://twitter.com/jonschlinkert)
### License
Copyright © 2018, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
***
_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.6.0, on February 14, 2018._
@@ -0,0 +1,3 @@
import { DecoratorInfo } from '../models/DecoratorInfo';
export declare function stringifyDecoratorInfo(decoratorTargetInfo: DecoratorInfo): string;
//# sourceMappingURL=stringifyDecoratorInfo.d.ts.map
@@ -0,0 +1,13 @@
const $431fbd86ca7dc216$export$b204af158042fbac = (el)=>{
var _el_ownerDocument;
return (_el_ownerDocument = el === null || el === void 0 ? void 0 : el.ownerDocument) !== null && _el_ownerDocument !== void 0 ? _el_ownerDocument : document;
};
const $431fbd86ca7dc216$export$f21a1ffae260145a = (el)=>{
if (el && 'window' in el && el.window === el) return el;
const doc = $431fbd86ca7dc216$export$b204af158042fbac(el);
return doc.defaultView || window;
};
export {$431fbd86ca7dc216$export$b204af158042fbac as getOwnerDocument, $431fbd86ca7dc216$export$f21a1ffae260145a as getOwnerWindow};
//# sourceMappingURL=domHelpers.module.js.map
@@ -0,0 +1,108 @@
// Copyright 2013 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Sliding window over the input data.
#ifndef BROTLI_ENC_RINGBUFFER_H_
#define BROTLI_ENC_RINGBUFFER_H_
#include <stddef.h>
#include <stdint.h>
#include "./port.h"
namespace brotli {
// A RingBuffer(window_bits, tail_bits) contains `1 << window_bits' bytes of
// data in a circular manner: writing a byte writes it to
// `position() % (1 << window_bits)'. For convenience, the RingBuffer array
// contains another copy of the first `1 << tail_bits' bytes:
// buffer_[i] == buffer_[i + (1 << window_bits)] if i < (1 << tail_bits).
class RingBuffer {
public:
RingBuffer(int window_bits, int tail_bits)
: window_bits_(window_bits),
mask_((1 << window_bits) - 1),
tail_size_(1 << tail_bits),
pos_(0) {
static const int kSlackForFourByteHashingEverywhere = 3;
const int buflen = (1 << window_bits_) + tail_size_;
buffer_ = new uint8_t[buflen + kSlackForFourByteHashingEverywhere];
for (int i = 0; i < kSlackForFourByteHashingEverywhere; ++i) {
buffer_[buflen + i] = 0;
}
}
~RingBuffer() {
delete [] buffer_;
}
// Push bytes into the ring buffer.
void Write(const uint8_t *bytes, size_t n) {
const size_t masked_pos = pos_ & mask_;
// The length of the writes is limited so that we do not need to worry
// about a write
WriteTail(bytes, n);
if (PREDICT_TRUE(masked_pos + n <= (1 << window_bits_))) {
// A single write fits.
memcpy(&buffer_[masked_pos], bytes, n);
} else {
// Split into two writes.
// Copy into the end of the buffer, including the tail buffer.
memcpy(&buffer_[masked_pos], bytes,
std::min(n, ((1 << window_bits_) + tail_size_) - masked_pos));
// Copy into the begining of the buffer
memcpy(&buffer_[0], bytes + ((1 << window_bits_) - masked_pos),
n - ((1 << window_bits_) - masked_pos));
}
pos_ += n;
}
void Reset() {
pos_ = 0;
}
// Logical cursor position in the ring buffer.
size_t position() const { return pos_; }
// Bit mask for getting the physical position for a logical position.
size_t mask() const { return mask_; }
uint8_t *start() { return &buffer_[0]; }
const uint8_t *start() const { return &buffer_[0]; }
private:
void WriteTail(const uint8_t *bytes, size_t n) {
const size_t masked_pos = pos_ & mask_;
if (PREDICT_FALSE(masked_pos < tail_size_)) {
// Just fill the tail buffer with the beginning data.
const size_t p = (1 << window_bits_) + masked_pos;
memcpy(&buffer_[p], bytes, std::min(n, tail_size_ - masked_pos));
}
}
// Size of the ringbuffer is (1 << window_bits) + tail_size_.
const int window_bits_;
const size_t mask_;
const size_t tail_size_;
// Position to write in the ring buffer.
size_t pos_;
// The actual ring buffer containing the data and the copy of the beginning
// as a tail.
uint8_t *buffer_;
};
} // namespace brotli
#endif // BROTLI_ENC_RINGBUFFER_H_
@@ -0,0 +1,24 @@
{
"root": true,
"extends": "@ljharb",
"rules": {
"complexity": 0,
"id-length": 0,
"new-cap": ["error", {
"capIsNewExceptions": [
"GetIntrinsic",
],
}],
},
"overrides": [
{
"files": "test/**",
"rules": {
"max-lines-per-function": "off",
},
},
],
}
@@ -0,0 +1 @@
{"name":"unified","version":"11.0.5","requiresBuild":false,"files":{"license":{"checkedAt":1794532115465,"integrity":"sha512-ZotpKAIe5HmaXBvKi/aq3uIOzPEkR2cTMeTYcq2M04vOTjiQcZ20T3Dl+c1EryaxT0N5hlEkJg501CfmBUEqkQ==","mode":420,"size":1099},"lib/callable-instance.js":{"checkedAt":1794532115465,"integrity":"sha512-MQQ+R94z+3JvEIBQnxLyc9cFfxUrkOoHAOGADCQqiBFdFwwfJWwS+ICOHq6jXUt9vgxbmuEb96D/USG0aymC+A==","mode":420,"size":1401},"index.js":{"checkedAt":1794532115465,"integrity":"sha512-RNu1rBuMUfH9YkSCg9B8vgU80RgYhUiRLap3psBf8xvu2V551sby5MPHVgv8swoenBgqWrIPq2TXrjNuXH1lVQ==","mode":420,"size":81},"lib/index.js":{"checkedAt":1794532115465,"integrity":"sha512-CMrt8CUjMt3lbICr559LrnkIYMmSQfWBnTUdVKE171FGlvVvFf3HTLRwFQXAgB+4ZOAjamsJ0lmv5m3I0QR8xw==","mode":420,"size":40285},"package.json":{"checkedAt":1794532115466,"integrity":"sha512-gjasdCozows9ENFT8gdxnYa7JdqUo9iS5gpc2FYXQu7kAM3uwbZRlj7usbU4PI6gmZpaxIn3NGRAivunuYg3nw==","mode":420,"size":3064},"lib/callable-instance.d.ts.map":{"checkedAt":1794532115466,"integrity":"sha512-s/ASFVs3FtyBNe1lF7iAhq8/o5nbCsx/1TekuOE4xwiI9gidnVKTXtGRykA3yP2IOun4hJrP2z6o9EVYhkFzvQ==","mode":420,"size":155},"lib/index.d.ts.map":{"checkedAt":1794532115466,"integrity":"sha512-TfYXvdm49MtrXb5b/ejv8X8iD0YRPJPL1KYjO0CGq2LSMb3npy/4b2qHjxTEogJVGcjoV6U9PXkrSlK2Q5EZgw==","mode":420,"size":5349},"readme.md":{"checkedAt":1794532115466,"integrity":"sha512-ICJCSErSCiF5Lkg3oUVBg2E94tKR1stK0N4C7wdDUjacwB4wpcDo2OHM+nUOGs29pfremJMkKCHmaGoQbEnppw==","mode":420,"size":49441},"lib/callable-instance.d.ts":{"checkedAt":1794532115466,"integrity":"sha512-hdwAPh0vy20REYETzvBnPOhnxtyv7bt6eEhw81rCNLvHlJG24Z4OP2LcK1iC8UdVBHN4PlaYhmOPeEgwf95XmQ==","mode":420,"size":190},"index.d.ts":{"checkedAt":1794532115466,"integrity":"sha512-HLtU4oAySO6lhtb4mu01lDyf2kXczCatEWxdzyhq2L5rnKyeWHsitZ8pd2kk7D8NfUXAWZXMK4G/0bYMZHN9/w==","mode":420,"size":2886},"lib/index.d.ts":{"checkedAt":1794532115466,"integrity":"sha512-FHxoN8T1o7vlJPZlyz6MJJCvWvMCNN6lNguMh3E79CsKsNcPx2ylCFb9DCYOfGd7+gNHLff5/drRdFVthUI8FA==","mode":420,"size":41981}}}
@@ -0,0 +1,53 @@
"use strict";
var Targets_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Targets = exports.Target = exports.TargetCert = void 0;
const tslib_1 = require("tslib");
const asn1_schema_1 = require("@peculiar/asn1-schema");
const asn1_x509_1 = require("@peculiar/asn1-x509");
const issuer_serial_1 = require("./issuer_serial");
const object_digest_info_1 = require("./object_digest_info");
class TargetCert {
constructor(params = {}) {
this.targetCertificate = new issuer_serial_1.IssuerSerial();
Object.assign(this, params);
}
}
exports.TargetCert = TargetCert;
tslib_1.__decorate([
(0, asn1_schema_1.AsnProp)({ type: issuer_serial_1.IssuerSerial })
], TargetCert.prototype, "targetCertificate", void 0);
tslib_1.__decorate([
(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.GeneralName, optional: true })
], TargetCert.prototype, "targetName", void 0);
tslib_1.__decorate([
(0, asn1_schema_1.AsnProp)({ type: object_digest_info_1.ObjectDigestInfo, optional: true })
], TargetCert.prototype, "certDigestInfo", void 0);
let Target = class Target {
constructor(params = {}) {
Object.assign(this, params);
}
};
exports.Target = Target;
tslib_1.__decorate([
(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.GeneralName, context: 0, implicit: true })
], Target.prototype, "targetName", void 0);
tslib_1.__decorate([
(0, asn1_schema_1.AsnProp)({ type: asn1_x509_1.GeneralName, context: 1, implicit: true })
], Target.prototype, "targetGroup", void 0);
tslib_1.__decorate([
(0, asn1_schema_1.AsnProp)({ type: TargetCert, context: 2, implicit: true })
], Target.prototype, "targetCert", void 0);
exports.Target = Target = tslib_1.__decorate([
(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Choice })
], Target);
let Targets = Targets_1 = class Targets extends asn1_schema_1.AsnArray {
constructor(items) {
super(items);
Object.setPrototypeOf(this, Targets_1.prototype);
}
};
exports.Targets = Targets;
exports.Targets = Targets = Targets_1 = tslib_1.__decorate([
(0, asn1_schema_1.AsnType)({ type: asn1_schema_1.AsnTypeTypes.Sequence, itemType: Target })
], Targets);
@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var docTipRole = {
abstract: false,
accessibleNameRequired: false,
baseConcepts: [],
childrenPresentational: false,
nameFrom: ['author'],
prohibitedProps: [],
props: {
'aria-disabled': null,
'aria-errormessage': null,
'aria-expanded': null,
'aria-haspopup': null,
'aria-invalid': null
},
relatedConcepts: [{
concept: {
name: 'help [EPUB-SSV]'
},
module: 'EPUB'
}],
requireContextRole: [],
requiredContextRole: [],
requiredOwnedElements: [],
requiredProps: {},
superClass: [['roletype', 'structure', 'section', 'note']]
};
var _default = exports.default = docTipRole;
@@ -0,0 +1,57 @@
import { useRef } from 'react';
import isPlainObject from 'lodash/isPlainObject';
import useCreation from '../useCreation';
import useUpdate from '../useUpdate';
// k:v 原对象:代理过的对象
var proxyMap = new WeakMap();
// k:v 代理过的对象:原对象
var rawMap = new WeakMap();
function observer(initialVal, cb) {
var existingProxy = proxyMap.get(initialVal);
// 添加缓存 防止重新构建proxy
if (existingProxy) {
return existingProxy;
}
// 防止代理已经代理过的对象
// https://github.com/alibaba/hooks/issues/839
if (rawMap.has(initialVal)) {
return initialVal;
}
var proxy = new Proxy(initialVal, {
get: function (target, key, receiver) {
var res = Reflect.get(target, key, receiver);
// https://github.com/alibaba/hooks/issues/1317
var descriptor = Reflect.getOwnPropertyDescriptor(target, key);
if (!(descriptor === null || descriptor === void 0 ? void 0 : descriptor.configurable) && !(descriptor === null || descriptor === void 0 ? void 0 : descriptor.writable)) {
return res;
}
// Only proxy plain object or array,
// otherwise it will cause: https://github.com/alibaba/hooks/issues/2080
return isPlainObject(res) || Array.isArray(res) ? observer(res, cb) : res;
},
set: function (target, key, val) {
var ret = Reflect.set(target, key, val);
cb();
return ret;
},
deleteProperty: function (target, key) {
var ret = Reflect.deleteProperty(target, key);
cb();
return ret;
},
});
proxyMap.set(initialVal, proxy);
rawMap.set(proxy, initialVal);
return proxy;
}
function useReactive(initialState) {
var update = useUpdate();
var stateRef = useRef(initialState);
var state = useCreation(function () {
return observer(stateRef.current, function () {
update();
});
}, []);
return state;
}
export default useReactive;
@@ -0,0 +1,25 @@
import type { ITokenizer } from 'strtok3';
import { type IFileHeader, type ILocalFileHeader } from "./ZipToken.js";
export type InflateFileFilterResult = {
handler: InflatedDataHandler | false;
stop?: boolean;
};
export type { ILocalFileHeader } from './ZipToken.js';
/**
* Return false when to ignore the file, return `InflatedDataHandler` to handle extracted data
*/
export type InflateFileFilter = (file: ILocalFileHeader) => InflateFileFilterResult;
export type InflatedDataHandler = (fileData: Uint8Array) => Promise<void>;
export declare class ZipHandler {
private tokenizer;
private syncBuffer;
constructor(tokenizer: ITokenizer);
isZip(): Promise<boolean>;
private peekSignature;
findEndOfCentralDirectoryLocator(): Promise<number>;
readCentralDirectory(): Promise<IFileHeader[] | undefined>;
unzip(fileCb: InflateFileFilter): Promise<void>;
private iterateOverCentralDirectory;
private inflate;
private readLocalFileHeader;
}
Loaded 100 of 35554 files, more files were not shown because too many files have changed in this diff. Show more