docs: 仓库链接指向本镜像仓库
Build NapCat Artifacts / Type Check & Test (push) Waiting to run

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,63 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _emojiRegex = _interopRequireDefault(require("emoji-regex"));
var _jsxAstUtils = require("jsx-ast-utils");
var _safeRegexTest = _interopRequireDefault(require("safe-regex-test"));
var _schemas = require("../util/schemas");
var _getElementType = _interopRequireDefault(require("../util/getElementType"));
var _isHiddenFromScreenReader = _interopRequireDefault(require("../util/isHiddenFromScreenReader"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
/**
* @fileoverview Enforce emojis are wrapped in <span> and provide screen reader access.
* @author Ethan Cohen
*/
// ----------------------------------------------------------------------------
// Rule Definition
// ----------------------------------------------------------------------------
var errorMessage = 'Emojis should be wrapped in <span>, have role="img", and have an accessible description with aria-label or aria-labelledby.';
var schema = (0, _schemas.generateObjSchema)();
var _default = exports["default"] = {
meta: {
docs: {
description: 'Enforce emojis are wrapped in `<span>` and provide screen reader access.',
url: 'https://github.com/jsx-eslint/eslint-plugin-jsx-a11y/tree/HEAD/docs/rules/accessible-emoji.md'
},
deprecated: true,
schema: [schema]
},
create: function create(context) {
var elementType = (0, _getElementType["default"])(context);
var testEmoji = (0, _safeRegexTest["default"])((0, _emojiRegex["default"])());
return {
JSXOpeningElement: function JSXOpeningElement(node) {
var literalChildValue = node.parent.children.find(function (child) {
return child.type === 'Literal' || child.type === 'JSXText';
});
if (literalChildValue && testEmoji(literalChildValue.value)) {
var elementIsHidden = (0, _isHiddenFromScreenReader["default"])(elementType(node), node.attributes);
if (elementIsHidden) {
return; // emoji is decorative
}
var rolePropValue = (0, _jsxAstUtils.getLiteralPropValue)((0, _jsxAstUtils.getProp)(node.attributes, 'role'));
var ariaLabelProp = (0, _jsxAstUtils.getProp)(node.attributes, 'aria-label');
var arialLabelledByProp = (0, _jsxAstUtils.getProp)(node.attributes, 'aria-labelledby');
var hasLabel = ariaLabelProp !== undefined || arialLabelledByProp !== undefined;
var isSpan = elementType(node) === 'span';
if (hasLabel === false || rolePropValue !== 'img' || isSpan === false) {
context.report({
node,
message: errorMessage
});
}
}
}
};
}
};
module.exports = exports.default;
@@ -0,0 +1 @@
{"version":3,"file":"inline-style-parser.min.js","sources":["../index.js"],"sourcesContent":["// http://www.w3.org/TR/CSS21/grammar.html\n// https://github.com/visionmedia/css-parse/pull/49#issuecomment-30088027\nvar COMMENT_REGEX = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//g;\n\nvar NEWLINE_REGEX = /\\n/g;\nvar WHITESPACE_REGEX = /^\\s*/;\n\n// declaration\nvar PROPERTY_REGEX = /^(\\*?[-#/*\\\\\\w]+(\\[[0-9a-z_-]+\\])?)\\s*/;\nvar COLON_REGEX = /^:\\s*/;\nvar VALUE_REGEX = /^((?:'(?:\\\\'|.)*?'|\"(?:\\\\\"|.)*?\"|\\([^)]*?\\)|[^};])+)/;\nvar SEMICOLON_REGEX = /^[;\\s]*/;\n\n// https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String/Trim#Polyfill\nvar TRIM_REGEX = /^\\s+|\\s+$/g;\n\n// strings\nvar NEWLINE = '\\n';\nvar FORWARD_SLASH = '/';\nvar ASTERISK = '*';\nvar EMPTY_STRING = '';\n\n// types\nvar TYPE_COMMENT = 'comment';\nvar TYPE_DECLARATION = 'declaration';\n\n/**\n * @param {String} style\n * @param {Object} [options]\n * @return {Object[]}\n * @throws {TypeError}\n * @throws {Error}\n */\nexport default function (style, options) {\n if (typeof style !== 'string') {\n throw new TypeError('First argument must be a string');\n }\n\n if (!style) return [];\n\n options = options || {};\n\n /**\n * Positional.\n */\n var lineno = 1;\n var column = 1;\n\n /**\n * Update lineno and column based on `str`.\n *\n * @param {String} str\n */\n function updatePosition(str) {\n var lines = str.match(NEWLINE_REGEX);\n if (lines) lineno += lines.length;\n var i = str.lastIndexOf(NEWLINE);\n column = ~i ? str.length - i : column + str.length;\n }\n\n /**\n * Mark position and patch `node.position`.\n *\n * @return {Function}\n */\n function position() {\n var start = { line: lineno, column: column };\n return function (node) {\n node.position = new Position(start);\n whitespace();\n return node;\n };\n }\n\n /**\n * Store position information for a node.\n *\n * @constructor\n * @property {Object} start\n * @property {Object} end\n * @property {undefined|String} source\n */\n function Position(start) {\n this.start = start;\n this.end = { line: lineno, column: column };\n this.source = options.source;\n }\n\n /**\n * Non-enumerable source string.\n */\n Position.prototype.content = style;\n\n var errorsList = [];\n\n /**\n * Error `msg`.\n *\n * @param {String} msg\n * @throws {Error}\n */\n function error(msg) {\n var err = new Error(\n options.source + ':' + lineno + ':' + column + ': ' + msg\n );\n err.reason = msg;\n err.filename = options.source;\n err.line = lineno;\n err.column = column;\n err.source = style;\n\n if (options.silent) {\n errorsList.push(err);\n } else {\n throw err;\n }\n }\n\n /**\n * Match `re` and return captures.\n *\n * @param {RegExp} re\n * @return {undefined|Array}\n */\n function match(re) {\n var m = re.exec(style);\n if (!m) return;\n var str = m[0];\n updatePosition(str);\n style = style.slice(str.length);\n return m;\n }\n\n /**\n * Parse whitespace.\n */\n function whitespace() {\n match(WHITESPACE_REGEX);\n }\n\n /**\n * Parse comments.\n *\n * @param {Object[]} [rules]\n * @return {Object[]}\n */\n function comments(rules) {\n var c;\n rules = rules || [];\n while ((c = comment())) {\n if (c !== false) {\n rules.push(c);\n }\n }\n return rules;\n }\n\n /**\n * Parse comment.\n *\n * @return {Object}\n * @throws {Error}\n */\n function comment() {\n var pos = position();\n if (FORWARD_SLASH != style.charAt(0) || ASTERISK != style.charAt(1)) return;\n\n var i = 2;\n while (\n EMPTY_STRING != style.charAt(i) &&\n (ASTERISK != style.charAt(i) || FORWARD_SLASH != style.charAt(i + 1))\n ) {\n ++i;\n }\n i += 2;\n\n if (EMPTY_STRING === style.charAt(i - 1)) {\n return error('End of comment missing');\n }\n\n var str = style.slice(2, i - 2);\n column += 2;\n updatePosition(str);\n style = style.slice(i);\n column += 2;\n\n return pos({\n type: TYPE_COMMENT,\n comment: str\n });\n }\n\n /**\n * Parse declaration.\n *\n * @return {Object}\n * @throws {Error}\n */\n function declaration() {\n var pos = position();\n\n // prop\n var prop = match(PROPERTY_REGEX);\n if (!prop) return;\n comment();\n\n // :\n if (!match(COLON_REGEX)) return error(\"property missing ':'\");\n\n // val\n var val = match(VALUE_REGEX);\n\n var ret = pos({\n type: TYPE_DECLARATION,\n property: trim(prop[0].replace(COMMENT_REGEX, EMPTY_STRING)),\n value: val\n ? trim(val[0].replace(COMMENT_REGEX, EMPTY_STRING))\n : EMPTY_STRING\n });\n\n // ;\n match(SEMICOLON_REGEX);\n\n return ret;\n }\n\n /**\n * Parse declarations.\n *\n * @return {Object[]}\n */\n function declaLine truncated
@@ -0,0 +1,185 @@
# import/prefer-default-export
<!-- end auto-generated rule header -->
In exporting files, this rule checks if there is default export or not.
## Rule Details
### rule schema
```javascript
"import/prefer-default-export": [
( "off" | "warn" | "error" ),
{ "target": "single" | "any" } // default is "single"
]
```
### Config Options
There are two options available: `single` and `any`. By default, if you do not specify the option, rule will assume it is `single`.
#### single
**Definition**: When there is only a single export from a module, prefer using default export over named export.
How to setup config file for this rule:
```javascript
// you can manually specify it
"rules": {
"import/prefer-default-export": [
( "off" | "warn" | "error" ),
{ "target": "single" }
]
}
// config setup below will also work
"rules": {
"import/prefer-default-export": "off" | "warn" | "error"
}
```
The following patterns are considered warnings:
```javascript
// bad.js
// There is only a single module export and it's a named export.
export const foo = 'foo';
```
The following patterns are not warnings:
```javascript
// good1.js
// There is a default export.
export const foo = 'foo';
const bar = 'bar';
export default bar;
```
```javascript
// good2.js
// There is more than one named export in the module.
export const foo = 'foo';
export const bar = 'bar';
```
```javascript
// good3.js
// There is more than one named export in the module
const foo = 'foo';
const bar = 'bar';
export { foo, bar }
```
```javascript
// good4.js
// There is a default export.
const foo = 'foo';
export { foo as default }
```
```javascript
// export-star.js
// Any batch export will disable this rule. The remote module is not inspected.
export * from './other-module'
```
#### any
**Definition**: any exporting file must contain a default export.
How to setup config file for this rule:
```javascript
// you have to manually specify it
"rules": {
"import/prefer-default-export": [
( "off" | "warn" | "error" ),
{ "target": "any" }
]
}
```
The following patterns are *not* considered warnings:
```javascript
// good1.js
//has default export
export default function bar() {};
```
```javascript
// good2.js
// has default export
let foo;
export { foo as default }
```
```javascript
// good3.js
//contains multiple exports AND default export
export const a = 5;
export function bar(){};
let foo;
export { foo as default }
```
```javascript
// good4.js
// does not contain any exports => file is not checked by the rule
import * as foo from './foo';
```
```javascript
// export-star.js
// Any batch export will disable this rule. The remote module is not inspected.
export * from './other-module'
```
The following patterns are considered warnings:
```javascript
// bad1.js
//has 2 named exports, but no default export
export const foo = 'foo';
export const bar = 'bar';
```
```javascript
// bad2.js
// does not have default export
let foo, bar;
export { foo, bar }
```
```javascript
// bad3.js
// does not have default export
export { a, b } from "foo.js"
```
```javascript
// bad4.js
// does not have default export
let item;
export const foo = item;
export { item };
```
@@ -0,0 +1,280 @@
/**
* @import {RegExpMatchObject, ReplaceFunction} from 'mdast-util-find-and-replace'
* @import {CompileContext, Extension as FromMarkdownExtension, Handle as FromMarkdownHandle, Transform as FromMarkdownTransform} from 'mdast-util-from-markdown'
* @import {ConstructName, Options as ToMarkdownExtension} from 'mdast-util-to-markdown'
* @import {Link, PhrasingContent} from 'mdast'
*/
import {ccount} from 'ccount'
import {ok as assert} from 'devlop'
import {unicodePunctuation, unicodeWhitespace} from 'micromark-util-character'
import {findAndReplace} from 'mdast-util-find-and-replace'
/** @type {ConstructName} */
const inConstruct = 'phrasing'
/** @type {Array<ConstructName>} */
const notInConstruct = ['autolink', 'link', 'image', 'label']
/**
* Create an extension for `mdast-util-from-markdown` to enable GFM autolink
* literals in markdown.
*
* @returns {FromMarkdownExtension}
* Extension for `mdast-util-to-markdown` to enable GFM autolink literals.
*/
export function gfmAutolinkLiteralFromMarkdown() {
return {
transforms: [transformGfmAutolinkLiterals],
enter: {
literalAutolink: enterLiteralAutolink,
literalAutolinkEmail: enterLiteralAutolinkValue,
literalAutolinkHttp: enterLiteralAutolinkValue,
literalAutolinkWww: enterLiteralAutolinkValue
},
exit: {
literalAutolink: exitLiteralAutolink,
literalAutolinkEmail: exitLiteralAutolinkEmail,
literalAutolinkHttp: exitLiteralAutolinkHttp,
literalAutolinkWww: exitLiteralAutolinkWww
}
}
}
/**
* Create an extension for `mdast-util-to-markdown` to enable GFM autolink
* literals in markdown.
*
* @returns {ToMarkdownExtension}
* Extension for `mdast-util-to-markdown` to enable GFM autolink literals.
*/
export function gfmAutolinkLiteralToMarkdown() {
return {
unsafe: [
{
character: '@',
before: '[+\\-.\\w]',
after: '[\\-.\\w]',
inConstruct,
notInConstruct
},
{
character: '.',
before: '[Ww]',
after: '[\\-.\\w]',
inConstruct,
notInConstruct
},
{
character: ':',
before: '[ps]',
after: '\\/',
inConstruct,
notInConstruct
}
]
}
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterLiteralAutolink(token) {
this.enter({type: 'link', title: null, url: '', children: []}, token)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterLiteralAutolinkValue(token) {
this.config.enter.autolinkProtocol.call(this, token)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitLiteralAutolinkHttp(token) {
this.config.exit.autolinkProtocol.call(this, token)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitLiteralAutolinkWww(token) {
this.config.exit.data.call(this, token)
const node = this.stack[this.stack.length - 1]
assert(node.type === 'link')
node.url = 'http://' + this.sliceSerialize(token)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitLiteralAutolinkEmail(token) {
this.config.exit.autolinkEmail.call(this, token)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitLiteralAutolink(token) {
this.exit(token)
}
/** @type {FromMarkdownTransform} */
function transformGfmAutolinkLiterals(tree) {
findAndReplace(
tree,
[
[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi, findUrl],
[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu, findEmail]
],
{ignore: ['link', 'linkReference']}
)
}
/**
* @type {ReplaceFunction}
* @param {string} _
* @param {string} protocol
* @param {string} domain
* @param {string} path
* @param {RegExpMatchObject} match
* @returns {Array<PhrasingContent> | Link | false}
*/
// eslint-disable-next-line max-params
function findUrl(_, protocol, domain, path, match) {
let prefix = ''
// Not an expected previous character.
if (!previous(match)) {
return false
}
// Treat `www` as part of the domain.
if (/^w/i.test(protocol)) {
domain = protocol + domain
protocol = ''
prefix = 'http://'
}
if (!isCorrectDomain(domain)) {
return false
}
const parts = splitUrl(domain + path)
if (!parts[0]) return false
/** @type {Link} */
const result = {
type: 'link',
title: null,
url: prefix + protocol + parts[0],
children: [{type: 'text', value: protocol + parts[0]}]
}
if (parts[1]) {
return [result, {type: 'text', value: parts[1]}]
}
return result
}
/**
* @type {ReplaceFunction}
* @param {string} _
* @param {string} atext
* @param {string} label
* @param {RegExpMatchObject} match
* @returns {Link | false}
*/
function findEmail(_, atext, label, match) {
if (
// Not an expected previous character.
!previous(match, true) ||
// Label ends in not allowed character.
/[-\d_]$/.test(label)
) {
return false
}
return {
type: 'link',
title: null,
url: 'mailto:' + atext + '@' + label,
children: [{type: 'text', value: atext + '@' + label}]
}
}
/**
* @param {string} domain
* @returns {boolean}
*/
function isCorrectDomain(domain) {
const parts = domain.split('.')
if (
parts.length < 2 ||
(parts[parts.length - 1] &&
(/_/.test(parts[parts.length - 1]) ||
!/[a-zA-Z\d]/.test(parts[parts.length - 1]))) ||
(parts[parts.length - 2] &&
(/_/.test(parts[parts.length - 2]) ||
!/[a-zA-Z\d]/.test(parts[parts.length - 2])))
) {
return false
}
return true
}
/**
* @param {string} url
* @returns {[string, string | undefined]}
*/
function splitUrl(url) {
const trailExec = /[!"&'),.:;<>?\]}]+$/.exec(url)
if (!trailExec) {
return [url, undefined]
}
url = url.slice(0, trailExec.index)
let trail = trailExec[0]
let closingParenIndex = trail.indexOf(')')
const openingParens = ccount(url, '(')
let closingParens = ccount(url, ')')
while (closingParenIndex !== -1 && openingParens > closingParens) {
url += trail.slice(0, closingParenIndex + 1)
trail = trail.slice(closingParenIndex + 1)
closingParenIndex = trail.indexOf(')')
closingParens++
}
return [url, trail]
}
/**
* @param {RegExpMatchObject} match
* @param {boolean | null | undefined} [email=false]
* @returns {boolean}
*/
function previous(match, email) {
const code = match.input.charCodeAt(match.index - 1)
return (
(match.index === 0 ||
unicodeWhitespace(code) ||
unicodePunctuation(code)) &&
// If it’s an email, the previous character should not be a slash.
(!email || code !== 47)
)
}
@@ -0,0 +1,46 @@
/**
* @author Toru Nagashima <https://github.com/mysticatea>
* See LICENSE file in root directory for full license.
*/
"use strict"
const { READ, ReferenceTracker } = require("@eslint-community/eslint-utils")
const { getSourceCode } = require("eslint-compat-utils")
module.exports = {
meta: {
docs: {
description: "disallow the `Math.fround` method.",
category: "ES2015",
recommended: false,
url: "http://eslint-community.github.io/eslint-plugin-es-x/rules/no-math-fround.html",
},
fixable: null,
messages: {
forbidden: "ES2015 '{{name}}' method is forbidden.",
},
schema: [],
type: "problem",
},
create(context) {
return {
"Program:exit"(program) {
const sourceCode = getSourceCode(context)
const tracker = new ReferenceTracker(
sourceCode.getScope(program),
)
for (const { node, path } of tracker.iterateGlobalReferences({
Math: {
fround: { [READ]: true },
},
})) {
context.report({
node,
messageId: "forbidden",
data: { name: path.join(".") },
})
}
},
}
},
}
@@ -0,0 +1 @@
{"version":3,"file":"getSelf.js","sourceRoot":"","sources":["../../../../src/common/calculations/getSelf.ts"],"names":[],"mappings":";;AAAA,0BAEC;AAFD,SAAgB,OAAO,CAAI,IAAO;IAChC,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,423 @@
# `eslint-plugin-react` <sup>[![Version Badge][npm-version-svg]][package-url]</sup>
===================
[![github actions][actions-image]][actions-url]
[![Maintenance Status][status-image]][status-url]
[![NPM version][npm-image]][npm-url]
[![Tidelift][tidelift-image]][tidelift-url]
React specific linting rules for `eslint`
## Installation
```sh
npm install eslint eslint-plugin-react --save-dev
```
It is also possible to install ESLint globally rather than locally (using `npm install -g eslint`). However, this is not recommended, and any plugins or shareable configs that you use must be installed locally in either case.
## Configuration (legacy: `.eslintrc*`) <a id="configuration"></a>
Use [our preset](#recommended) to get reasonable defaults:
```json
"extends": [
"eslint:recommended",
"plugin:react/recommended"
]
```
If you are using the [new JSX transform from React 17](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html#removing-unused-react-imports), extend [`react/jsx-runtime`](https://github.com/jsx-eslint/eslint-plugin-react/blob/c8917b0885094b5e4cc2a6f613f7fb6f16fe932e/index.js#L163-L176) in your eslint config (add `"plugin:react/jsx-runtime"` to `"extends"`) to disable the relevant rules.
You should also specify settings that will be shared across all the plugin rules. ([More about eslint shared settings](https://eslint.org/docs/latest/use/configure/configuration-files#configuring-shared-settings))
```json5
{
"settings": {
"react": {
"createClass": "createReactClass", // Regex for Component Factory to use,
// default to "createReactClass"
"pragma": "React", // Pragma to use, default to "React"
"fragment": "Fragment", // Fragment to use (may be a property of <pragma>), default to "Fragment"
"version": "detect", // React version. "detect" automatically picks the version you have installed.
// You can also use `16.0`, `16.3`, etc, if you want to override the detected value.
// Defaults to the "defaultVersion" setting and warns if missing, and to "detect" in the future
"defaultVersion": "", // Default React version to use when the version you have installed cannot be detected.
// If not provided, defaults to the latest React version.
"flowVersion": "0.53" // Flow version
},
"propWrapperFunctions": [
// The names of any function used to wrap propTypes, e.g. `forbidExtraProps`. If this isn't set, any propTypes wrapped in a function will be skipped.
"forbidExtraProps",
{"property": "freeze", "object": "Object"},
{"property": "myFavoriteWrapper"},
// for rules that check exact prop wrappers
{"property": "forbidExtraProps", "exact": true}
],
"componentWrapperFunctions": [
// The name of any function used to wrap components, e.g. Mobx `observer` function. If this isn't set, components wrapped by these functions will be skipped.
"observer", // `property`
{"property": "styled"}, // `object` is optional
{"property": "observer", "object": "Mobx"},
{"property": "observer", "object": "<pragma>"} // sets `object` to whatever value `settings.react.pragma` is set to
],
"formComponents": [
// Components used as alternatives to <form> for forms, eg. <Form endpoint={ url } />
"CustomForm",
{"name": "SimpleForm", "formAttribute": "endpoint"},
{"name": "Form", "formAttribute": ["registerEndpoint", "loginEndpoint"]}, // allows specifying multiple properties if necessary
],
"linkComponents": [
// Components used as alternatives to <a> for linking, eg. <Link to={ url } />
"Hyperlink",
{"name": "MyLink", "linkAttribute": "to"},
{"name": "Link", "linkAttribute": ["to", "href"]}, // allows specifying multiple properties if necessary
]
}
}
```
If you do not use a preset you will need to specify individual rules and add extra configuration.
Add "react" to the plugins section.
```json
{
"plugins": [
"react"
]
}
```
Enable JSX support.
With `eslint` 2+
```json
{
"parserOptions": {
"ecmaFeatures": {
"jsx": true
}
}
}
```
Enable the rules that you would like to use.
```json
"rules": {
"react/jsx-uses-react": "error",
"react/jsx-uses-vars": "error",
}
```
### Shareable configs
#### Recommended
This plugin exports a `recommended` configuration that enforces React good practices.
To enable this configuration use the `extends` property in your `.eslintrc` config file:
```json
{
"extends": ["eslint:recommended", "plugin:react/recommended"]
}
```
See [`eslint` documentation](https://eslint.org/docs/user-guide/configuring/configuration-files#extending-configuration-files) for more information about extending configuration files.
#### All
This plugin also exports an `all` configuration that includes every available rule.
This pairs well with the `eslint:all` rule.
```json
{
"plugins": [
"react"
],
"extends": ["eslint:all", "plugin:react/all"]
}
```
**Note**: These configurations will import `eslint-plugin-react` and enable JSX in [parser options](https://eslint.org/docs/user-guide/configuring/language-options#specifying-parser-options).
## Configuration (new: `eslint.config.js`)
From [`v8.21.0`](https://github.com/eslint/eslint/releases/tag/v8.21.0), eslint announced a new config system.
In the new system, `.eslintrc*` is no longer used. `eslint.config.js` would be the default config file name.
In eslint `v8`, the legacy system (`.eslintrc*`) would still be supported, while in eslint `v9`, only the new system would be supported.
And from [`v8.23.0`](https://github.com/eslint/eslint/releases/tag/v8.23.0), eslint CLI starts to look up `eslint.config.js`.
**So, if your eslint is `>=8.23.0`, you're 100% ready to use the new config system.**
You might want to check out the official blog posts,
- <https://eslint.org/blog/2022/08/new-config-system-part-1/>
- <https://eslint.org/blog/2022/08/new-config-system-part-2/>
- <https://eslint.org/blog/2022/08/new-config-system-part-3/>
and the [official docs](https://eslint.org/docs/latest/user-guide/configuring/configuration-files-new).
### Plugin
The default export of `eslint-plugin-react` is a plugin object.
```js
const react = require('eslint-plugin-react');
const globals = require('globals');
module.exports = [
…
{
files: ['**/*.{js,jsx,mjs,cjs,ts,tsx}'],
plugins: {
react,
},
languageOptions: {
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
globals: {
...globals.browser,
},
},
rules: {
// ... any rules you want
'react/jsx-uses-react': 'error',
'react/jsx-uses-vars': 'error',
},
// ... others are omitted for brevity
},
…
];
```
### Configuring shared settings
Refer to the [official docs](https://eslint.org/docs/latest/user-guide/configuring/configuration-files-new#configuring-shared-settings).
The schema of the `settings.react` object would be identical to that of what's already described above in the legacy config section.
<!-- markdownlint-disable-next-line no-duplicate-heading -->
### Flat Configs
This plugin exports 3 flat configs:
- `flat.all`
- `flat.recommended`
- `flat['jsx-runtime']`
The flat configs are available via the root plugin import. They will configure the plugin under the `react/` namespace and enable JSX in [`languageOptions.parserOptions`](https://eslint.org/docs/latest/use/configure/language-options#specifying-parser-options).
```js
const reactPlugin = require('eslint-plugin-react');
module.exports = [
…
reactPlugin.configs.flat.recommended, // This is not a plugin object, but a shareable config object
reactPlugin.configs.flat['jsx-runtime'], // Add this if you are using React 17+
…
];
```
You can of course add/override some properties.
**Note**: Our shareable configs does not preconfigure `files` or [`languageOptions.globals`](https://eslint.org/docs/latest/user-guide/configuring/configuration-files-new#configuration-objects).
For most of the cases, you probably want to configure some properties by yourself.
```js
const reactPlugin = require('eslint-plugin-react');
const globals = require('globals');
module.exports = [
…
{
files: ['**/*.{js,mjs,cjs,jsx,mjsx,ts,tsx,mtsx}'],
...reactPlugin.configs.flat.recommended,
languageOptions: {
...reactPlugin.configs.flat.recommended.languageOptions,
globals: {
...globals.serviceworker,
...globals.browser,
},
},
},
…
];
```
The above example is same as the example below, as the new config system is based on chaining.
```js
const reactPlugin = require('eslint-plugin-react');
const globals = require('globals');
module.exports = [
…
{
files: ['**/*.{js,mjs,cjs,jsx,mjsx,ts,tsx,mtsx}'],
...reactPlugin.configs.flat.recommended,
},
{
files: ['**/*.{js,mjs,cjs,jsx,mjsx,ts,tsx,mtsx}'],
languageOptions: {
globals: {
...globals.serviceworker,
...globals.browser,
},
},
},
…
];
```
## List of supported rules
<!-- begin auto-generated rules list -->
💼 [Configurations](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs) enabled in.\
🚫 [Configurations](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs) disabled in.\
🏃 Set in the `jsx-runtime` [configuration](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs).\
☑️ Set in the `recommended` [configuration](https://github.com/jsx-eslint/eslint-plugin-react/#shareable-configs).\
🔧 Automatically fixable by the [`--fix` CLI option](https://eslint.org/docs/user-guide/command-line-interface#--fix).\
💡 Manually fixable by [editor suggestions](https://eslint.org/docs/latest/use/core-concepts#rule-suggestions).\
❌ Deprecated.
| Name                                  | Description | 💼 | 🚫 | 🔧 | 💡 | ❌ |
| :------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------- | :- | :- | :- | :- | :- |
| [boolean-prop-naming](docs/rules/boolean-prop-naming.md) | Enforces consistent naming for boolean props | | | | | |
| [button-has-type](docs/rules/button-has-type.md) | Disallow usage of `button` elements without an explicit `type` attribute | | | | | |
| [checked-requires-onchange-or-readonly](docs/rules/checked-requires-onchange-or-readonly.md) | Enforce using `onChange` or `readonly` attribute when `checked` is used | | | | | |
| [default-props-match-prop-types](docs/rules/default-props-match-prop-types.md) | Enforce all defaultProps have a corresponding non-required PropType | | | | | |
| [destructuring-assignment](docs/rules/destructuring-assignment.md) | Enforce consistent usage of destructuring assignment of props, state, and context | | | 🔧 | | |
| [display-name](docs/rules/display-name.md) | Disallow missing displayName in a React component definition | ☑️ | | | | |
| [forbid-component-props](docs/rules/forbid-component-props.md) | Disallow certain props on components | | | | | |
| [forbid-dom-props](docs/rules/forbid-dom-props.md) | Disallow certain props on DOM Nodes | | | | | |
| [forbid-elements](docs/rules/forbid-elements.md) | Disallow certain elements | | | | | |
| [forbid-foreign-prop-types](docs/rules/forbid-foreign-prop-types.md) | Disallow using another component's propTypes | | | | | |
| [forbid-prop-types](docs/rules/forbid-prop-types.md) | Disallow certain propTypes | | | | | |
| [forward-ref-uses-ref](docs/rules/forward-ref-uses-ref.md) | Require all forwardRef components include a ref parameter | | | | 💡 | |
| [function-component-definition](docs/rules/function-component-definition.md) | Enforce a specific function type for function components | | | 🔧 | | |
| [hook-use-state](docs/rules/hook-use-state.md) | Ensure destructuring and symmetric naming of useState hook value and setter variables | | | | 💡 | |
| [iframe-missing-sandbox](docs/rules/iframe-missing-sandbox.md) | Enforce sandbox attribute on iframe elements | | | | | |
| [jsx-boolean-value](docs/rules/jsx-boolean-value.md) | Enforce boolean attributes notation in JSX | | | 🔧 | | |
| [jsx-child-element-spacing](docs/rules/jsx-child-element-spacing.md) | Enforce or disallow spaces inside of curly braces in JSX attributes and expressions | | | | | |
| [jsx-closing-bracket-location](docs/rules/jsx-closing-bracket-location.md) | Enforce closing bracket location in JSX | | | 🔧 | | |
| [jsx-closing-tag-location](docs/rules/jsx-closing-tag-location.md) | Enforce closing tag location for multiline JSX | | | 🔧 | | |
| [jsx-curly-brace-presence](docs/rules/jsx-curly-brace-presence.md) | Disallow unnecessary JSX expressions when literals alone are sufficient or enforce JSX expressions on literals in JSX children or attributes | | | 🔧 | | |
| [jsx-curly-newline](docs/rules/jsx-curly-newline.md) | Enforce consistent linebreaks in curly braces in JSX attributes and expressions | | | 🔧 | | |
| [jsx-curly-spacing](docs/rules/jsx-curly-spacing.md) | Enforce or disallow spaces inside of curly braces in JSX attributes and expressions | | | 🔧 | | |
| [jsx-equals-spacing](docs/rules/jsx-equals-spacing.md) | Enforce or disallow spaces around equal signs in JSX attributes | | | 🔧 | | |
| [jsx-filename-extension](docs/rules/jsx-filename-extension.md) | Disallow file extensions that may contain JSX | | | | | |
| [jsx-first-prop-new-line](docs/rules/jsx-first-prop-new-line.md) | Enforce proper position of the first property in JSX | | | 🔧 | | |
| [jsx-fragments](docs/rules/jsx-fragments.md) | Enforce shorthand or standard form for React fragments | | | 🔧 | | |
| [jsx-handler-names](docs/rules/jsx-handler-names.md) | Enforce event handler naming conventions in JSX | | | | | |
| [jsx-indent](docs/rules/jsx-indent.md) | Enforce JSX indentation | | | 🔧 | | |
| [jsx-indent-props](docs/rules/jsx-indent-props.md) | Enforce props indentation in JSX | | | 🔧 | | |
| [jsx-key](docs/rules/jsx-key.md) | Disallow missing `key` props in iterators/collection literals | ☑️ | | | | |
| [jsx-max-depth](docs/rules/jsx-max-depth.md) | Enforce JSX maximum depth | | | | | |
| [jsx-max-props-per-line](docs/rules/jsx-max-props-per-line.md) | Enforce maximum of props on a single line in JSX | | | 🔧 | | |
| [jsx-newline](docs/rules/jsx-newline.md) | Require or prevent a new line after jsx elements and expressions. | | | 🔧 | | |
| [jsx-no-bind](docs/rules/jsx-no-bind.md) | Disallow `.bind()` or arrow functions in JSX props | | | | | |
| [jsx-no-comment-textnodes](docs/rules/jsx-no-comment-textnodes.md) | Disallow comments from being inserted as text nodes | ☑️ | | | | |
| [jsx-no-constructed-context-values](docs/rules/jsx-no-constructed-context-values.md) | Disallows JSX context provider values from taking values that will cause needless rerenders | | | | | |
| [jsx-no-duplicate-props](docs/rules/jsx-no-duplicate-props.md) | Disallow duplicate properties in JSX | ☑️ | | | | |
| [jsx-no-leaked-render](docs/rules/jsx-no-leaked-render.md) | Disallow problematic leaked values from being rendered | | | 🔧 | | |
| [jsx-no-literals](docs/rules/jsx-no-literals.md) | Disallow usage of string literals in JSX | | | | | |
| [jsx-no-script-url](docs/rules/jsx-no-script-url.md) | Disallow usage of `javascript:` URLs | | | | | |
| [jsx-no-target-blank](docs/rules/jsx-no-target-blank.md) | Disallow `target="_blank"` attribute without `rel="noreferrer"` | ☑️ | | 🔧 | | |
| [jsx-no-undef](docs/rules/jsx-no-undef.md) | Disallow undeclared variables in JSX | ☑️ | | | | |
| [jsx-no-useless-fragment](docs/rules/jsx-no-useless-fragment.md) | Disallow unnecessary fragments | | | 🔧 | | |
| [jsx-one-expression-per-line](docs/rules/jsx-one-expression-per-line.md) | Require one JSX element per line | | | 🔧 | | |
| [jsx-pascal-case](docs/rules/jsx-pascal-case.md) | Enforce PascalCase for user-defined JSX components | | | | | |
| [jsx-props-no-multi-spaces](docs/rules/jsx-props-no-multi-spaces.md) | Disallow multiple spaces between inline JSX props | | | 🔧 | | |
| [jsx-props-no-spread-multi](docs/rules/jsx-props-no-spread-multi.md) | Disallow JSX prop spreading the same identifier multiple times | | | | | |
| [jsx-props-no-spreading](docs/rules/jsx-props-no-spreading.md) | Disallow JSX prop spreading | | | | | |
| [jsx-sort-default-props](docs/rules/jsx-sort-default-props.md) | Enforce defaultProps declarations alphabetical sorting | | | | | ❌ |
| [jsx-sort-props](docs/rules/jsx-sort-props.md) | Enforce props alphabetical sorting | | | 🔧 | | |
| [jsx-space-before-closing](docs/rules/jsx-space-before-closing.md) | Enforce spacing before closing bracket in JSX | | | 🔧 | | ❌ |
| [jsx-tag-spacing](docs/rules/jsx-tag-spacing.md) | Enforce whitespace in and around the JSX opening and closing brackets | | | 🔧 | | |
| [jsx-uses-react](docs/rules/jsx-uses-react.md) | Disallow React to be incorrectly marked as unused | ☑️ | 🏃 | | | |
| [jsx-uses-vars](docs/rules/jsx-uses-vars.md) | Disallow variables used in JSX to be incorrectly marked as unused | ☑️ | | | | |
| [jsx-wrap-multilines](docs/rules/jsx-wrap-multilines.md) | Disallow missing parentheses around multiline JSX | | | 🔧 | | |
| [no-access-state-in-setstate](docs/rules/no-access-state-in-setstate.md) | Disallow when this.state is accessed within setState | | | | | |
| [no-adjacent-inline-elements](docs/rules/no-adjacent-inline-elements.md) | Disallow adjacent inline elements not separated by whitespace. | | | | | |
| [no-array-index-key](docs/rules/no-array-index-key.md) | Disallow usage of Array index in keys | | | | | |
| [no-arrow-function-lifecycle](docs/rules/no-arrow-function-lifecycle.md) | Lifecycle methods should be methods on the prototype, not class fields | | | 🔧 | | |
| [no-children-prop](docs/rules/no-children-prop.md) | Disallow passing of children as props | ☑️ | | | | |
| [no-danger](docs/rules/no-danger.md) | Disallow usage of dangerous JSX properties | | | | | |
| [no-danger-with-children](docs/rules/no-danger-with-children.md) | Disallow when a DOM element is using both children and dangerouslySetInnerHTML | ☑️ | | | | |
| [no-deprecated](docs/rules/no-deprecated.md) | Disallow usage of deprecated methods | ☑️ | | | | |
| [no-did-mount-set-state](docs/rules/no-did-mount-set-state.md) | Disallow usage of setState in componentDidMount | | | | | |
| [no-did-update-set-state](docs/rules/no-did-update-set-state.md) | Disallow usage of setState in componentDidUpdate | | | | | |
| [no-direct-mutation-state](docs/rules/no-direct-mutation-state.md) | Disallow direct mutation of this.state | ☑️ | | | | |
| [no-find-dom-node](docs/rules/no-find-dom-node.md) | Disallow usage of findDOMNode | ☑️ | | | | |
| [no-invalid-html-attribute](docs/rules/no-invalid-html-attribute.md) | Disallow usage of invalid attributes | | | | 💡 | |
| [no-is-mounted](docs/rules/no-is-mounted.md) | Disallow usage of isMounted | ☑️ | | | | |
| [no-multi-comp](docs/rules/no-multi-comp.md) | Disallow multiple component definition per file | | | | | |
| [no-namespace](docs/rules/no-namespace.md) | Enforce that namespaces are not used in React elements | | | | | |
| [no-object-type-as-default-prop](docs/rules/no-object-type-as-default-prop.md) | Disallow usage of referential-type variables as default param in functional component | | | | | |
| [no-redundant-should-component-update](docs/rules/no-redundant-should-component-update.md) | Disallow usage of shouldComponentUpdate when extending React.PureComponent | | | | | |
| [no-render-return-value](docs/rules/no-render-return-value.md) | Disallow usage of the return value of ReactDOM.render | ☑️ | | | | |
| [no-set-state](docs/rules/no-set-state.md) | Disallow usage of setState | | | | | |
| [no-string-refs](docs/rules/no-string-refs.md) | Disallow using string references | ☑️ | | | | |
| [no-this-in-sfc](docs/rules/no-this-in-sfc.md) | Disallow `this` from being used in stateless functional components | | | | | |
| [no-typos](docs/rules/no-typos.md) | Disallow common typos | | | | | |
| [no-unescaped-entities](docs/rules/no-unescaped-entities.md) | Disallow unescaped HTML entities from appearing in markup | ☑️ | | | 💡 | |
| [no-unknown-property](docs/rules/no-unknown-property.md) | Disallow usage of unknown DOM property | ☑️ | | 🔧 | | |
| [no-unsafe](docs/rules/no-unsafe.md) | Disallow usage of unsafe lifecycle methods | | ☑️ | | | |
| [no-unstable-nested-components](docs/rules/no-unstable-nested-components.md) | Disallow creating unstable components inside components | | | | | |
| [no-unused-class-component-methods](docs/rules/no-unused-class-component-methods.md) | Disallow declaring unused methods of component class | | | | | |
| [no-unused-prop-types](docs/rules/no-unused-prop-types.md) | Disallow definitions of unused propTypes | | | | | |
| [no-unused-state](docs/rules/no-unused-state.md) | Disallow definitions of unused state | | | | | |
| [no-will-update-set-state](docs/rules/no-will-update-set-state.md) | Disallow usage of setState in componentWillUpdate | | | | | |
| [prefer-es6-class](docs/rules/prefer-es6-class.md) | Enforce ES5 or ES6 class for React Components | | | | | |
| [prefer-exact-props](docs/rules/prefer-exact-props.md) | Prefer exact proptype definitions | | | | | |
| [prefer-read-only-props](docs/rules/prefer-read-only-props.md) | Enforce that props are read-only | | | 🔧 | | |
| [prefer-stateless-function](docs/rules/prefer-stateless-function.md) | Enforce stateless components to be written as a pure function | | | | | |
| [prop-types](docs/rules/prop-types.md) | Disallow missing props validation in a React component definition | ☑️ | | | | |
| [react-in-jsx-scope](docs/rules/react-in-jsx-scope.md) | Disallow missing React when using JSX | ☑️ | 🏃 | | | |
| [require-default-props](docs/rules/require-default-props.md) | Enforce a defaultProps definition for every prop that is not a required prop | | | | | |
| [require-optimization](docs/rules/require-optimization.md) | Enforce React components to have a shouldComponentUpdate method | | | | | |
| [require-render-return](docs/rules/require-render-return.md) | Enforce ES5 or ES6 class for returning value in render function | ☑️ | | | | |
| [self-closing-comp](docs/rules/self-closing-comp.md) | Disallow extra closing tags for components without children | | | 🔧 | | |
| [sort-comp](docs/rules/sort-comp.md) | Enforce component methods order | | | | | |
| [sort-default-props](docs/rules/sort-default-props.md) | Enforce defaultProps declarations alphabetical sorting | | | | | |
| [sort-prop-types](docs/rules/sort-prop-types.md) | Enforce propTypes declarations alphabetical sorting | | | 🔧 | | |
| [state-in-constructor](docs/rules/state-in-constructor.md) | Enforce class component state initialization style | | | | | |
| [static-property-placement](docs/rules/static-property-placement.md) | Enforces where React component static properties should be positioned. | | | | | |
| [style-prop-object](docs/rules/style-prop-object.md) | Enforce style prop value is an object | | | | | |
| [void-dom-elements-no-children](docs/rules/void-dom-elements-no-children.md) | Disallow void DOM elements (e.g. `<img />`, `<br />`) from receiving children | | | | | |
<!-- end auto-generated rules list -->
## Other useful plugins
- Rules of Hooks: [eslint-plugin-react-hooks](https://github.com/facebook/react/tree/master/packages/eslint-plugin-react-hooks)
- JSX accessibility: [eslint-plugin-jsx-a11y](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y)
- React Native: [eslint-plugin-react-native](https://github.com/Intellicode/eslint-plugin-react-native)
## License
`eslint-plugin-react` is licensed under the [MIT License](https://opensource.org/licenses/mit-license.php).
[npm-url]: https://npmjs.org/package/eslint-plugin-react
[npm-image]: https://img.shields.io/npm/v/eslint-plugin-react.svg
[status-url]: https://github.com/jsx-eslint/eslint-plugin-react/pulse
[status-image]: https://img.shields.io/github/last-commit/jsx-eslint/eslint-plugin-react.svg
[tidelift-url]: https://tidelift.com/subscription/pkg/npm-eslint-plugin-react?utm_source=npm-eslint-plugin-react&utm_medium=referral&utm_campaign=readme
[tidelift-image]: https://tidelift.com/badges/package/npm/eslint-plugin-react?style=flat
[package-url]: https://npmjs.org/package/eslint-plugin-react
[npm-version-svg]: https://versionbadg.es/jsx-eslint/eslint-plugin-react.svg
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/jsx-eslint/eslint-plugin-react
[actions-url]: https://github.com/jsx-eslint/eslint-plugin-react/actions
@@ -0,0 +1 @@
module.exports={C:{"11":0.02984,"43":0.09449,"52":0.00995,"78":0.00497,"115":0.13924,"118":0.10443,"128":0.04476,"133":0.0547,"134":0.00497,"135":0.00995,"136":0.00995,"137":0.00995,"138":0.00497,"139":0.00497,"140":0.04973,"141":0.01492,"142":0.03481,"143":0.65146,"144":0.5719,_:"2 3 4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 44 45 46 47 48 49 50 51 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 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 116 117 119 120 121 122 123 124 125 126 127 129 130 131 132 145 146 147 3.5 3.6"},D:{"39":0.00497,"40":0.00497,"41":0.00995,"42":0.00497,"43":0.00497,"44":0.00497,"45":0.00995,"46":0.00497,"47":0.00995,"48":0.01492,"49":0.01492,"50":0.00497,"51":0.00497,"52":0.00995,"53":0.00995,"54":0.00497,"55":0.00995,"56":0.00995,"57":0.00995,"58":0.00995,"59":0.00497,"60":0.00497,"66":0.01492,"69":0.00995,"70":0.01492,"77":0.01989,"79":0.06465,"80":0.00497,"81":0.03978,"83":0.03978,"85":0.00497,"86":0.00995,"87":0.02984,"88":0.00497,"91":0.01989,"92":0.01989,"93":0.00995,"97":0.00995,"98":0.03978,"99":0.01492,"100":0.00497,"101":0.00995,"102":0.00995,"103":0.06962,"104":0.02984,"105":0.15416,"106":0.03481,"107":0.01492,"108":0.01989,"109":0.58681,"110":0.11438,"111":0.0746,"112":2.08866,"113":0.04973,"114":0.17903,"115":0.01492,"116":0.0547,"117":0.08951,"118":0.14422,"119":0.03978,"120":0.09946,"121":0.09449,"122":0.11438,"123":0.0547,"124":0.05968,"125":3.33688,"126":6.13171,"127":0.0746,"128":0.11438,"129":0.08454,"130":1.33276,"131":0.15914,"132":0.09449,"133":0.0547,"134":2.59591,"135":0.06465,"136":0.07957,"137":0.25362,"138":0.43762,"139":0.6813,"140":4.47073,"141":9.4487,"142":0.13427,"143":0.00995,_:"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 61 62 63 64 65 67 68 71 72 73 74 75 76 78 84 89 90 94 95 96 144 145"},F:{"91":0.02487,"92":0.04476,"95":0.02487,"120":0.06962,"121":0.08454,"122":0.70119,_:"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 72 73 74 75 76 77 78 79 80 81 82 83 84 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:{"92":0.00995,"109":0.03481,"114":0.01989,"120":0.02984,"121":0.01989,"122":0.01492,"126":0.00995,"127":0.00497,"128":0.00497,"129":0.00497,"130":0.00497,"131":0.01989,"132":0.00995,"133":0.00995,"134":0.02487,"135":0.01492,"136":0.01492,"137":0.01492,"138":0.03481,"139":0.0547,"140":0.73103,"141":3.18272,"142":0.00995,_:"12 13 14 15 16 17 18 79 80 81 83 84 85 86 87 88 89 90 91 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 110 111 112 113 115 116 117 118 119 123 124 125"},E:{"14":0.00995,_:"0 4 5 6 7 8 9 10 11 12 13 15 3.1 3.2 5.1 6.1 7.1 9.1 10.1 11.1 12.1 15.2-15.3 16.0 26.2","13.1":0.01989,"14.1":0.02487,"15.1":0.01492,"15.4":0.00497,"15.5":0.00497,"15.6":0.08454,"16.1":0.00995,"16.2":0.00995,"16.3":0.01989,"16.4":0.00995,"16.5":0.00995,"16.6":0.12433,"17.0":0.00497,"17.1":0.08951,"17.2":0.00995,"17.3":0.00995,"17.4":0.01989,"17.5":0.03481,"17.6":0.12433,"18.0":0.01492,"18.1":0.02487,"18.2":0.01492,"18.3":0.04973,"18.4":0.02984,"18.5-18.6":0.11438,"26.0":0.30833,"26.1":0.00995},G:{"8":0,"3.2":0,"4.0-4.1":0,"4.2-4.3":0.00109,"5.0-5.1":0,"6.0-6.1":0.00434,"7.0-7.1":0.00326,"8.1-8.4":0,"9.0-9.2":0,"9.3":0.00977,"10.0-10.2":0.00109,"10.3":0.01845,"11.0-11.2":0.2735,"11.3-11.4":0.00651,"12.0-12.1":0.00217,"12.2-12.5":0.05318,"13.0-13.1":0,"13.2":0.00543,"13.3":0.00217,"13.4-13.7":0.00868,"14.0-14.4":0.01845,"14.5-14.8":0.01954,"15.0-15.1":0.01845,"15.2-15.3":0.01411,"15.4":0.01628,"15.5":0.01845,"15.6-15.8":0.24094,"16.0":0.03256,"16.1":0.06078,"16.2":0.03147,"16.3":0.05644,"16.4":0.01411,"16.5":0.02496,"16.6-16.7":0.32234,"17.0":0.02279,"17.1":0.03473,"17.2":0.02496,"17.3":0.0369,"17.4":0.06512,"17.5":0.11179,"17.6-17.7":0.28219,"18.0":0.06403,"18.1":0.13241,"18.2":0.07163,"18.3":0.23009,"18.4":0.1183,"18.5-18.6":6.03226,"26.0":0.74562,"26.1":0.02713},P:{"21":0.01088,"22":0.01088,"23":0.02176,"24":0.02176,"25":0.02176,"26":0.04353,"27":0.05441,"28":1.4799,"29":0.1197,_:"4 20 5.0-5.4 6.2-6.4 7.2-7.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"},I:{"0":0.48694,"3":0,"4":0,"2.1":0,"2.2":0,"2.3":0,"4.1":0,"4.2-4.3":0.0001,"4.4":0,"4.4.3-4.4.4":0.00024},K:{"0":0.73913,_:"10 11 12 11.1 11.5 12.1"},A:{"8":0.02165,"9":0.06494,"11":0.28141,_:"6 7 10 5.5"},S:{"2.5":0.01508,_:"3.0-3.1"},J:{_:"7 10"},N:{_:"10 11"},R:{_:"0"},M:{"0":0.29157},Q:{"14.9":0.13573},O:{"0":0.54794},H:{"0":0.03},L:{"0":39.02151}};
@@ -0,0 +1,35 @@
{
"name": "@marijn/find-cluster-break",
"version": "1.0.2",
"type": "module",
"description": "Find the position of grapheme cluster breaks in a string",
"main": "src/index.js",
"exports": {
"import": "./src/index.js",
"require": "./dist/index.cjs"
},
"scripts": {
"test": "mocha test/*.js",
"prepare": "rollup -c"
},
"repository": {
"type": "git",
"url": "git+https://github.com/marijnh/find-cluster-break.git"
},
"keywords": [
"unicode",
"grapheme",
"cluster",
"break"
],
"author": "Marijn Haverbeke <marijn@haverbeke.berlin>",
"license": "MIT",
"bugs": {
"url": "https://github.com/marijnh/find-cluster-break/issues"
},
"homepage": "https://github.com/marijnh/find-cluster-break#readme",
"devDependencies": {
"mocha": "^10.7.3",
"rollup": "^4.28.1"
}
}
@@ -0,0 +1,226 @@
export default `flf2a$ 2 2 8 -1 20
Cyberfont - small
Figlet conversion by Kent Nassen, kentn@cyberspace.org, 8-11-94
From: stock@fwi.uva.nl (Lennert Stock)
Date: 15 Jul 1994 00:04:25 GMT
Here are some fonts. Non-figlet I'm afraid, if you wanna convert them, be
my guest. I posted the isometric fonts before.
------------------------------------------------------------------------------
.x%%%%%%x. .x%%%%%%x.
,%%%%%%%%%%. .%%%%%%%%%%.
,%%%' )' \\) :( \`( \`%%%.
,%x%)________) --------- L e n n e r t S t o c k ( _ __ (%x%.
(%%%~^88P~88P| |~=> .=-~ %%%)
(%%::. .:,\\ .' \`. /,:. .::%%)
\`;%:\`\\. \`-' | | \`-' ./':%:'
\`\`x\`. -===.' stock@fwi.uva.nl -------- \`.===- .'x''
/ \`:\`.__.; :.__.':' \\
.d8b. ..\`. .'.. .d8b.
$@
$@@
/@
. @@
''@
@@
@
@@
@
@@
@
@@
@
@@
'@
@@
@
@@
@
@@
@
@@
@
@@
$ @
,@@
@
--@@
$@
.@@
/@
/ @@
@
@@
@
@@
@
@@
@
@@
@
@@
@
@@
@
@@
@
@@
@
@@
@
@@
.@
.@@
.@
,@@
@
@@
@
@@
@
@@
-,@
. @@
@
@@
____@
|--|@@
___ @
|==]@@
____@
|___@@
___ @
|__>@@
____@
|===@@
____@
|---@@
____@
|__,@@
_ _@
|--|@@
_@
|@@
_@
___|@@
_ _@
|-:_@@
_ @
|___@@
_ _@
|\\/|@@
__ _@
| \\|@@
____@
[__]@@
___ @
|--'@@
__ @
[_,]@@
____@
|--<@@
____@
====@@
___@
| @@
_ _@
|__|@@
_ _@
\\/ @@
_ _@
|/\\|@@
_ _@
_X_@@
_ _@
Y @@
___ @
/__@@
@
@@
\\ @
\\@@
@
@@
@
@@
@
___@@
\`@
@@
____@
|--|@@
___ @
|==]@@
____@
|___@@
___ @
|__>@@
____@
|===@@
____@
|---@@
____@
|__,@@
_ _@
|--|@@
_@
|@@
_@
___|@@
_ _@
|-:_@@
_ @
|___@@
_ _@
|\\/|@@
__ _@
| \\|@@
____@
[__]@@
___ @
|--'@@
__ @
[_,]@@
____@
|--<@@
____@
====@@
___@
| @@
_ _@
|__|@@
_ _@
\\/ @@
_ _@
|/\\|@@
_ _@
_X_@@
_ _@
Y @@
___ @
/__@@
@
@@
|@
|@@
@
@@
@
@@
@
@@
@
@@
@
@@
@
@@
@
@@
@
@@
@
@@
`
@@ -0,0 +1,20 @@
import { MinimatchOptions, MMRegExp } from './index.js';
export type ExtglobType = '!' | '?' | '+' | '*' | '@';
export declare class AST {
#private;
type: ExtglobType | null;
constructor(type: ExtglobType | null, parent?: AST, options?: MinimatchOptions);
get hasMagic(): boolean | undefined;
toString(): string;
push(...parts: (string | AST)[]): void;
toJSON(): any[];
isStart(): boolean;
isEnd(): boolean;
copyIn(part: AST | string): void;
clone(parent: AST): AST;
static fromGlob(pattern: string, options?: MinimatchOptions): AST;
toMMPattern(): MMRegExp | string;
get options(): MinimatchOptions;
toRegExpSource(allowDot?: boolean): [re: string, body: string, hasMagic: boolean, uflag: boolean];
}
//# sourceMappingURL=ast.d.ts.map
@@ -0,0 +1 @@
{"mappings":"AAAA,iBAAiB;IAAG,kBAAkB,CAAC,OAAS,GAAG,KAAK,IAAI,CAAC,cAAW,CAAC;IACvE,qBAAqB,CAAC,gDAAoC,CAAC;IAC3D,UAAU,CAAC,MAAG,CAAC;IACf,eAAe,CAAC,4BAAmB,CAAC;IACpC,iBAAiB,CAAC,MAAM,YAAc,GAAG,UAAU,MAAM,CAAC,KAAK,KAAK,EAAE;YAAC,MAAM,CAAC,6BAAoB,CAAC;YAAE,KAAK,IAAM,GAAG,UAAU,MAAM,CAAC,KAAK,KAAK,EAAE,kBAAY,CAAC;YAAE,OAAO,IAAM,GAAG,UAAU,MAAM,CAAC,KAAK,KAAK,EAAE,kBAAY,CAAC;QAAA,GAAG,CAAC,CAAC;IAC9N,gBAAgB,CAAC,OAAS,GAAG,KAAK,IAAI,CAAC,YAAS,CAAC;AACnD","sources":["packages/@react-aria/grid/intl/tr-TR.json"],"sourcesContent":["{\n \"deselectedItem\": \"{item} seçilmedi.\",\n \"longPressToSelect\": \"Seçim moduna girmek için uzun basın.\",\n \"select\": \"Seç\",\n \"selectedAll\": \"Tüm ögeler seçildi.\",\n \"selectedCount\": \"{count, plural, =0 {Hiçbir öge seçilmedi} one {# öge seçildi} other {# öge seçildi}}.\",\n \"selectedItem\": \"{item} seçildi.\"\n}\n"],"names":[],"version":3,"file":"tr-TR.main.js.map"}
@@ -0,0 +1,177 @@
import {
KeyBinding,
lineNumbers,
highlightActiveLineGutter,
highlightSpecialChars,
drawSelection,
dropCursor,
rectangularSelection,
crosshairCursor,
highlightActiveLine,
keymap,
} from '@codemirror/view';
import { EditorState, Extension } from '@codemirror/state';
import { history, defaultKeymap, historyKeymap } from '@codemirror/commands';
import { highlightSelectionMatches, searchKeymap } from '@codemirror/search';
import { closeBrackets, autocompletion, closeBracketsKeymap, completionKeymap } from '@codemirror/autocomplete';
import {
foldGutter,
indentOnInput,
syntaxHighlighting,
defaultHighlightStyle,
bracketMatching,
indentUnit,
foldKeymap,
} from '@codemirror/language';
import { lintKeymap } from '@codemirror/lint';
export interface BasicSetupOptions extends MinimalSetupOptions {
lineNumbers?: boolean;
highlightActiveLineGutter?: boolean;
foldGutter?: boolean;
dropCursor?: boolean;
allowMultipleSelections?: boolean;
indentOnInput?: boolean;
bracketMatching?: boolean;
closeBrackets?: boolean;
autocompletion?: boolean;
rectangularSelection?: boolean;
crosshairCursor?: boolean;
highlightActiveLine?: boolean;
highlightSelectionMatches?: boolean;
closeBracketsKeymap?: boolean;
searchKeymap?: boolean;
foldKeymap?: boolean;
completionKeymap?: boolean;
lintKeymap?: boolean;
/**
* Facet for overriding the unit by which indentation happens. Should be a string consisting either entirely of spaces or entirely of tabs. When not set, this defaults to 2 spaces
* https://codemirror.net/docs/ref/#language.indentUnit
* @default 2
*/
tabSize?: number;
}
/**
This is an extension value that just pulls together a number of
extensions that you might want in a basic editor. It is meant as a
convenient helper to quickly set up CodeMirror without installing
and importing a lot of separate packages.
Specifically, it includes...
- [the default command bindings](https://codemirror.net/6/docs/ref/#commands.defaultKeymap)
- [line numbers](https://codemirror.net/6/docs/ref/#view.lineNumbers)
- [special character highlighting](https://codemirror.net/6/docs/ref/#view.highlightSpecialChars)
- [the undo history](https://codemirror.net/6/docs/ref/#commands.history)
- [a fold gutter](https://codemirror.net/6/docs/ref/#language.foldGutter)
- [custom selection drawing](https://codemirror.net/6/docs/ref/#view.drawSelection)
- [drop cursor](https://codemirror.net/6/docs/ref/#view.dropCursor)
- [multiple selections](https://codemirror.net/6/docs/ref/#state.EditorState^allowMultipleSelections)
- [reindentation on input](https://codemirror.net/6/docs/ref/#language.indentOnInput)
- [the default highlight style](https://codemirror.net/6/docs/ref/#language.defaultHighlightStyle) (as fallback)
- [bracket matching](https://codemirror.net/6/docs/ref/#language.bracketMatching)
- [bracket closing](https://codemirror.net/6/docs/ref/#autocomplete.closeBrackets)
- [autocompletion](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion)
- [rectangular selection](https://codemirror.net/6/docs/ref/#view.rectangularSelection) and [crosshair cursor](https://codemirror.net/6/docs/ref/#view.crosshairCursor)
- [active line highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLine)
- [active line gutter highlighting](https://codemirror.net/6/docs/ref/#view.highlightActiveLineGutter)
- [selection match highlighting](https://codemirror.net/6/docs/ref/#search.highlightSelectionMatches)
- [search](https://codemirror.net/6/docs/ref/#search.searchKeymap)
- [linting](https://codemirror.net/6/docs/ref/#lint.lintKeymap)
(You'll probably want to add some language package to your setup
too.)
This extension does not allow customization. The idea is that,
once you decide you want to configure your editor more precisely,
you take this package's source (which is just a bunch of imports
and an array literal), copy it into your own code, and adjust it
as desired.
*/
export const basicSetup = (options: BasicSetupOptions = {}): Extension[] => {
const { crosshairCursor: initCrosshairCursor = false } = options;
let keymaps: KeyBinding[] = [];
if (options.closeBracketsKeymap !== false) {
keymaps = keymaps.concat(closeBracketsKeymap);
}
if (options.defaultKeymap !== false) {
keymaps = keymaps.concat(defaultKeymap);
}
if (options.searchKeymap !== false) {
keymaps = keymaps.concat(searchKeymap);
}
if (options.historyKeymap !== false) {
keymaps = keymaps.concat(historyKeymap);
}
if (options.foldKeymap !== false) {
keymaps = keymaps.concat(foldKeymap);
}
if (options.completionKeymap !== false) {
keymaps = keymaps.concat(completionKeymap);
}
if (options.lintKeymap !== false) {
keymaps = keymaps.concat(lintKeymap);
}
const extensions: Extension[] = [];
if (options.lineNumbers !== false) extensions.push(lineNumbers());
if (options.highlightActiveLineGutter !== false) extensions.push(highlightActiveLineGutter());
if (options.highlightSpecialChars !== false) extensions.push(highlightSpecialChars());
if (options.history !== false) extensions.push(history());
if (options.foldGutter !== false) extensions.push(foldGutter());
if (options.drawSelection !== false) extensions.push(drawSelection());
if (options.dropCursor !== false) extensions.push(dropCursor());
if (options.allowMultipleSelections !== false) extensions.push(EditorState.allowMultipleSelections.of(true));
if (options.indentOnInput !== false) extensions.push(indentOnInput());
if (options.syntaxHighlighting !== false)
extensions.push(syntaxHighlighting(defaultHighlightStyle, { fallback: true }));
if (options.bracketMatching !== false) extensions.push(bracketMatching());
if (options.closeBrackets !== false) extensions.push(closeBrackets());
if (options.autocompletion !== false) extensions.push(autocompletion());
if (options.rectangularSelection !== false) extensions.push(rectangularSelection());
if (initCrosshairCursor !== false) extensions.push(crosshairCursor());
if (options.highlightActiveLine !== false) extensions.push(highlightActiveLine());
if (options.highlightSelectionMatches !== false) extensions.push(highlightSelectionMatches());
if (options.tabSize && typeof options.tabSize === 'number')
extensions.push(indentUnit.of(' '.repeat(options.tabSize)));
return extensions.concat([keymap.of(keymaps.flat())]).filter(Boolean);
};
export interface MinimalSetupOptions {
highlightSpecialChars?: boolean;
history?: boolean;
drawSelection?: boolean;
syntaxHighlighting?: boolean;
defaultKeymap?: boolean;
historyKeymap?: boolean;
}
/**
A minimal set of extensions to create a functional editor. Only
includes [the default keymap](https://codemirror.net/6/docs/ref/#commands.defaultKeymap), [undo
history](https://codemirror.net/6/docs/ref/#commands.history), [special character
highlighting](https://codemirror.net/6/docs/ref/#view.highlightSpecialChars), [custom selection
drawing](https://codemirror.net/6/docs/ref/#view.drawSelection), and [default highlight
style](https://codemirror.net/6/docs/ref/#language.defaultHighlightStyle).
*/
export const minimalSetup = (options: MinimalSetupOptions = {}) => {
let keymaps: KeyBinding[] = [];
if (options.defaultKeymap !== false) {
keymaps = keymaps.concat(defaultKeymap);
}
if (options.historyKeymap !== false) {
keymaps = keymaps.concat(historyKeymap);
}
const extensions: Extension[] = [];
if (options.highlightSpecialChars !== false) extensions.push(highlightSpecialChars());
if (options.history !== false) extensions.push(history());
if (options.drawSelection !== false) extensions.push(drawSelection());
if (options.syntaxHighlighting !== false)
extensions.push(syntaxHighlighting(defaultHighlightStyle, { fallback: true }));
return extensions.concat([keymap.of(keymaps.flat())]).filter(Boolean);
};
@@ -0,0 +1,21 @@
#include <ctype.h>
#include <stdio.h>
#include <string.h>
static inline void formatChar(char *str, char ch)
{
// Print some common control codes.
switch (ch) {
case '\r': strcpy(str, "CR "); break;
case '\n': strcpy(str, "LF "); break;
case ' ': strcpy(str, "SP "); break;
case 27: strcpy(str, "^[ "); break;
case 3: strcpy(str, "^C "); break;
default:
if (isgraph(ch))
sprintf(str, "%c ", ch);
else
sprintf(str, "%02x ", ch);
break;
}
}
@@ -0,0 +1,73 @@
import type { MetadataStatement } from '../metadata/mdsTypes.js';
import type { Uint8Array_ } from '../types/index.js';
/**
* Allow MetadataService to accommodate unregistered AAGUIDs (`"permissive"`), or only allow
* registered AAGUIDs (`"strict"`). Currently primarily impacts how `getStatement()` operates
*/
export type VerificationMode = 'permissive' | 'strict';
interface MetadataService {
/**
* Prepare the service to handle remote MDS servers and/or cache local metadata statements.
*
* **Options:**
*
* @param opts.mdsServers An array of URLs to FIDO Alliance Metadata Service
* (version 3.0)-compatible servers. Defaults to the official FIDO MDS server
* @param opts.statements An array of local metadata statements
* @param opts.verificationMode How MetadataService will handle unregistered AAGUIDs. Defaults to
* `"strict"` which throws errors during registration response verification when an
* unregistered AAGUID is encountered. Set to `"permissive"` to allow registration by
* authenticators with unregistered AAGUIDs
*/
initialize(opts?: {
mdsServers?: string[];
statements?: MetadataStatement[];
verificationMode?: VerificationMode;
}): Promise<void>;
/**
* Get a metadata statement for a given AAGUID.
*
* This method will coordinate updating the cache as per the `nextUpdate` property in the initial
* BLOB download.
*/
getStatement(aaguid: string | Uint8Array): Promise<MetadataStatement | undefined>;
}
/**
* An implementation of `MetadataService` that can download and parse BLOBs, and support on-demand
* requesting and caching of individual metadata statements.
*
* https://fidoalliance.org/metadata/
*/
export declare class BaseMetadataService implements MetadataService {
private mdsCache;
private statementCache;
private state;
private verificationMode;
initialize(opts?: {
mdsServers?: string[];
statements?: MetadataStatement[];
verificationMode?: VerificationMode;
}): Promise<void>;
getStatement(aaguid: string | Uint8Array_): Promise<MetadataStatement | undefined>;
/**
* Download and process the latest BLOB from MDS
*/
private downloadBlob;
/**
* A helper method to pause execution until the service is ready
*/
private pauseUntilReady;
/**
* Report service status on change
*/
private setState;
}
/**
* A basic service for coordinating interactions with the FIDO Metadata Service. This includes BLOB
* download and parsing, and on-demand requesting and caching of individual metadata statements.
*
* https://fidoalliance.org/metadata/
*/
export declare const MetadataService: MetadataService;
export {};
//# sourceMappingURL=metadataService.d.ts.map
@@ -0,0 +1,6 @@
module.exports = {
"breadcrumbs": `Migas de pan`
};
//# sourceMappingURL=es-ES.main.js.map
@@ -0,0 +1,5 @@
import { ManagedClassElementMetadata } from '../models/ManagedClassElementMetadata';
import { MaybeClassElementMetadata } from '../models/MaybeClassElementMetadata';
import { MaybeManagedClassElementMetadata } from '../models/MaybeManagedClassElementMetadata';
export declare function buildMaybeClassElementMetadataFromMaybeClassElementMetadata(updateMetadata: (metadata: ManagedClassElementMetadata | MaybeManagedClassElementMetadata) => ManagedClassElementMetadata | MaybeManagedClassElementMetadata): (metadata: MaybeClassElementMetadata | undefined) => ManagedClassElementMetadata | MaybeManagedClassElementMetadata;
//# sourceMappingURL=buildMaybeClassElementMetadataFromMaybeClassElementMetadata.d.ts.map
@@ -0,0 +1,6 @@
<svg viewbox="0 0 18 18">
<path class="ql-stroke" d="M5,8a4,4,0,0,0,8,0"></path>
<line class="ql-stroke" x1="6" x2="12" y1="15" y2="15"></line>
<line class="ql-stroke" x1="9" x2="9" y1="12" y2="15"></line>
<rect class="ql-fill" height="8" rx="2" ry="2" width="4" x="7" y="2"></rect>
</svg>

After

Width:  |  Height:  |  Size: 297 B

@@ -0,0 +1,550 @@
/* eslint no-unused-vars: ["error", { "varsIgnorePattern": "^Duplex$", "caughtErrors": "none" }] */
'use strict';
const EventEmitter = require('events');
const http = require('http');
const { Duplex } = require('stream');
const { createHash } = require('crypto');
const extension = require('./extension');
const PerMessageDeflate = require('./permessage-deflate');
const subprotocol = require('./subprotocol');
const WebSocket = require('./websocket');
const { GUID, kWebSocket } = require('./constants');
const keyRegex = /^[+/0-9A-Za-z]{22}==$/;
const RUNNING = 0;
const CLOSING = 1;
const CLOSED = 2;
/**
* Class representing a WebSocket server.
*
* @extends EventEmitter
*/
class WebSocketServer extends EventEmitter {
/**
* Create a `WebSocketServer` instance.
*
* @param {Object} options Configuration options
* @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether
* any of the `'message'`, `'ping'`, and `'pong'` events can be emitted
* multiple times in the same tick
* @param {Boolean} [options.autoPong=true] Specifies whether or not to
* automatically send a pong in response to a ping
* @param {Number} [options.backlog=511] The maximum length of the queue of
* pending connections
* @param {Boolean} [options.clientTracking=true] Specifies whether or not to
* track clients
* @param {Function} [options.handleProtocols] A hook to handle protocols
* @param {String} [options.host] The hostname where to bind the server
* @param {Number} [options.maxPayload=104857600] The maximum allowed message
* size
* @param {Boolean} [options.noServer=false] Enable no server mode
* @param {String} [options.path] Accept only connections matching this path
* @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
* permessage-deflate
* @param {Number} [options.port] The port where to bind the server
* @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
* server to use
* @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
* not to skip UTF-8 validation for text and close messages
* @param {Function} [options.verifyClient] A hook to reject connections
* @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
* class to use. It must be the `WebSocket` class or class that extends it
* @param {Function} [callback] A listener for the `listening` event
*/
constructor(options, callback) {
super();
options = {
allowSynchronousEvents: true,
autoPong: true,
maxPayload: 100 * 1024 * 1024,
skipUTF8Validation: false,
perMessageDeflate: false,
handleProtocols: null,
clientTracking: true,
verifyClient: null,
noServer: false,
backlog: null, // use default (511 as implemented in net.js)
server: null,
host: null,
path: null,
port: null,
WebSocket,
...options
};
if (
(options.port == null && !options.server && !options.noServer) ||
(options.port != null && (options.server || options.noServer)) ||
(options.server && options.noServer)
) {
throw new TypeError(
'One and only one of the "port", "server", or "noServer" options ' +
'must be specified'
);
}
if (options.port != null) {
this._server = http.createServer((req, res) => {
const body = http.STATUS_CODES[426];
res.writeHead(426, {
'Content-Length': body.length,
'Content-Type': 'text/plain'
});
res.end(body);
});
this._server.listen(
options.port,
options.host,
options.backlog,
callback
);
} else if (options.server) {
this._server = options.server;
}
if (this._server) {
const emitConnection = this.emit.bind(this, 'connection');
this._removeListeners = addListeners(this._server, {
listening: this.emit.bind(this, 'listening'),
error: this.emit.bind(this, 'error'),
upgrade: (req, socket, head) => {
this.handleUpgrade(req, socket, head, emitConnection);
}
});
}
if (options.perMessageDeflate === true) options.perMessageDeflate = {};
if (options.clientTracking) {
this.clients = new Set();
this._shouldEmitClose = false;
}
this.options = options;
this._state = RUNNING;
}
/**
* Returns the bound address, the address family name, and port of the server
* as reported by the operating system if listening on an IP socket.
* If the server is listening on a pipe or UNIX domain socket, the name is
* returned as a string.
*
* @return {(Object|String|null)} The address of the server
* @public
*/
address() {
if (this.options.noServer) {
throw new Error('The server is operating in "noServer" mode');
}
if (!this._server) return null;
return this._server.address();
}
/**
* Stop the server from accepting new connections and emit the `'close'` event
* when all existing connections are closed.
*
* @param {Function} [cb] A one-time listener for the `'close'` event
* @public
*/
close(cb) {
if (this._state === CLOSED) {
if (cb) {
this.once('close', () => {
cb(new Error('The server is not running'));
});
}
process.nextTick(emitClose, this);
return;
}
if (cb) this.once('close', cb);
if (this._state === CLOSING) return;
this._state = CLOSING;
if (this.options.noServer || this.options.server) {
if (this._server) {
this._removeListeners();
this._removeListeners = this._server = null;
}
if (this.clients) {
if (!this.clients.size) {
process.nextTick(emitClose, this);
} else {
this._shouldEmitClose = true;
}
} else {
process.nextTick(emitClose, this);
}
} else {
const server = this._server;
this._removeListeners();
this._removeListeners = this._server = null;
//
// The HTTP/S server was created internally. Close it, and rely on its
// `'close'` event.
//
server.close(() => {
emitClose(this);
});
}
}
/**
* See if a given request should be handled by this server instance.
*
* @param {http.IncomingMessage} req Request object to inspect
* @return {Boolean} `true` if the request is valid, else `false`
* @public
*/
shouldHandle(req) {
if (this.options.path) {
const index = req.url.indexOf('?');
const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
if (pathname !== this.options.path) return false;
}
return true;
}
/**
* Handle a HTTP Upgrade request.
*
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback
* @public
*/
handleUpgrade(req, socket, head, cb) {
socket.on('error', socketOnError);
const key = req.headers['sec-websocket-key'];
const upgrade = req.headers.upgrade;
const version = +req.headers['sec-websocket-version'];
if (req.method !== 'GET') {
const message = 'Invalid HTTP method';
abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
return;
}
if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {
const message = 'Invalid Upgrade header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
if (key === undefined || !keyRegex.test(key)) {
const message = 'Missing or invalid Sec-WebSocket-Key header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
if (version !== 13 && version !== 8) {
const message = 'Missing or invalid Sec-WebSocket-Version header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
'Sec-WebSocket-Version': '13, 8'
});
return;
}
if (!this.shouldHandle(req)) {
abortHandshake(socket, 400);
return;
}
const secWebSocketProtocol = req.headers['sec-websocket-protocol'];
let protocols = new Set();
if (secWebSocketProtocol !== undefined) {
try {
protocols = subprotocol.parse(secWebSocketProtocol);
} catch (err) {
const message = 'Invalid Sec-WebSocket-Protocol header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
}
const secWebSocketExtensions = req.headers['sec-websocket-extensions'];
const extensions = {};
if (
this.options.perMessageDeflate &&
secWebSocketExtensions !== undefined
) {
const perMessageDeflate = new PerMessageDeflate(
this.options.perMessageDeflate,
true,
this.options.maxPayload
);
try {
const offers = extension.parse(secWebSocketExtensions);
if (offers[PerMessageDeflate.extensionName]) {
perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
}
} catch (err) {
const message =
'Invalid or unacceptable Sec-WebSocket-Extensions header';
abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
return;
}
}
//
// Optionally call external client verification handler.
//
if (this.options.verifyClient) {
const info = {
origin:
req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],
secure: !!(req.socket.authorized || req.socket.encrypted),
req
};
if (this.options.verifyClient.length === 2) {
this.options.verifyClient(info, (verified, code, message, headers) => {
if (!verified) {
return abortHandshake(socket, code || 401, message, headers);
}
this.completeUpgrade(
extensions,
key,
protocols,
req,
socket,
head,
cb
);
});
return;
}
if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);
}
this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
}
/**
* Upgrade the connection to WebSocket.
*
* @param {Object} extensions The accepted extensions
* @param {String} key The value of the `Sec-WebSocket-Key` header
* @param {Set} protocols The subprotocols
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The network socket between the server and client
* @param {Buffer} head The first packet of the upgraded stream
* @param {Function} cb Callback
* @throws {Error} If called more than once with the same socket
* @private
*/
completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
//
// Destroy the socket if the client has already sent a FIN packet.
//
if (!socket.readable || !socket.writable) return socket.destroy();
if (socket[kWebSocket]) {
throw new Error(
'server.handleUpgrade() was called more than once with the same ' +
'socket, possibly due to a misconfiguration'
);
}
if (this._state > RUNNING) return abortHandshake(socket, 503);
const digest = createHash('sha1')
.update(key + GUID)
.digest('base64');
const headers = [
'HTTP/1.1 101 Switching Protocols',
'Upgrade: websocket',
'Connection: Upgrade',
`Sec-WebSocket-Accept: ${digest}`
];
const ws = new this.options.WebSocket(null, undefined, this.options);
if (protocols.size) {
//
// Optionally call external protocol selection handler.
//
const protocol = this.options.handleProtocols
? this.options.handleProtocols(protocols, req)
: protocols.values().next().value;
if (protocol) {
headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
ws._protocol = protocol;
}
}
if (extensions[PerMessageDeflate.extensionName]) {
const params = extensions[PerMessageDeflate.extensionName].params;
const value = extension.format({
[PerMessageDeflate.extensionName]: [params]
});
headers.push(`Sec-WebSocket-Extensions: ${value}`);
ws._extensions = extensions;
}
//
// Allow external modification/inspection of handshake headers.
//
this.emit('headers', headers, req);
socket.write(headers.concat('\r\n').join('\r\n'));
socket.removeListener('error', socketOnError);
ws.setSocket(socket, head, {
allowSynchronousEvents: this.options.allowSynchronousEvents,
maxPayload: this.options.maxPayload,
skipUTF8Validation: this.options.skipUTF8Validation
});
if (this.clients) {
this.clients.add(ws);
ws.on('close', () => {
this.clients.delete(ws);
if (this._shouldEmitClose && !this.clients.size) {
process.nextTick(emitClose, this);
}
});
}
cb(ws, req);
}
}
module.exports = WebSocketServer;
/**
* Add event listeners on an `EventEmitter` using a map of <event, listener>
* pairs.
*
* @param {EventEmitter} server The event emitter
* @param {Object.<String, Function>} map The listeners to add
* @return {Function} A function that will remove the added listeners when
* called
* @private
*/
function addListeners(server, map) {
for (const event of Object.keys(map)) server.on(event, map[event]);
return function removeListeners() {
for (const event of Object.keys(map)) {
server.removeListener(event, map[event]);
}
};
}
/**
* Emit a `'close'` event on an `EventEmitter`.
*
* @param {EventEmitter} server The event emitter
* @private
*/
function emitClose(server) {
server._state = CLOSED;
server.emit('close');
}
/**
* Handle socket errors.
*
* @private
*/
function socketOnError() {
this.destroy();
}
/**
* Close the connection when preconditions are not fulfilled.
*
* @param {Duplex} socket The socket of the upgrade request
* @param {Number} code The HTTP response status code
* @param {String} [message] The HTTP response body
* @param {Object} [headers] Additional HTTP response headers
* @private
*/
function abortHandshake(socket, code, message, headers) {
//
// The socket is writable unless the user destroyed or ended it before calling
// `server.handleUpgrade()` or in the `verifyClient` function, which is a user
// error. Handling this does not make much sense as the worst that can happen
// is that some of the data written by the user might be discarded due to the
// call to `socket.end()` below, which triggers an `'error'` event that in
// turn causes the socket to be destroyed.
//
message = message || http.STATUS_CODES[code];
headers = {
Connection: 'close',
'Content-Type': 'text/html',
'Content-Length': Buffer.byteLength(message),
...headers
};
socket.once('finish', socket.destroy);
socket.end(
`HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` +
Object.keys(headers)
.map((h) => `${h}: ${headers[h]}`)
.join('\r\n') +
'\r\n\r\n' +
message
);
}
/**
* Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least
* one listener for it, otherwise call `abortHandshake()`.
*
* @param {WebSocketServer} server The WebSocket server
* @param {http.IncomingMessage} req The request object
* @param {Duplex} socket The socket of the upgrade request
* @param {Number} code The HTTP response status code
* @param {String} message The HTTP response body
* @param {Object} [headers] The HTTP response headers
* @private
*/
function abortHandshakeOrEmitwsClientError(
server,
req,
socket,
code,
message,
headers
) {
if (server.listenerCount('wsClientError')) {
const err = new Error(message);
Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
server.emit('wsClientError', err, socket, req);
} else {
abortHandshake(socket, code, message, headers);
}
}
@@ -0,0 +1,19 @@
export function sleep(time) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve();
}, time);
});
}
export function request(req) {
return new Promise(function (resolve, reject) {
return setTimeout(function () {
if (req === 0) {
reject(new Error('fail'));
}
else {
resolve('success');
}
}, 1000);
});
}
@@ -0,0 +1,428 @@
/**
* The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation
* that is available both as a standalone program or includible in other
* applications. It can be accessed using:
*
* ```js
* import repl from 'node:repl';
* ```
* @see [source](https://github.com/nodejs/node/blob/v22.x/lib/repl.js)
*/
declare module "repl" {
import { AsyncCompleter, Completer, Interface } from "node:readline";
import { Context } from "node:vm";
import { InspectOptions } from "node:util";
interface ReplOptions {
/**
* The input prompt to display.
* @default "> "
*/
prompt?: string | undefined;
/**
* The `Readable` stream from which REPL input will be read.
* @default process.stdin
*/
input?: NodeJS.ReadableStream | undefined;
/**
* The `Writable` stream to which REPL output will be written.
* @default process.stdout
*/
output?: NodeJS.WritableStream | undefined;
/**
* If `true`, specifies that the output should be treated as a TTY terminal, and have
* ANSI/VT100 escape codes written to it.
* Default: checking the value of the `isTTY` property on the output stream upon
* instantiation.
*/
terminal?: boolean | undefined;
/**
* The function to be used when evaluating each given line of input.
* **Default:** an async wrapper for the JavaScript `eval()` function. An `eval` function can
* error with `repl.Recoverable` to indicate the input was incomplete and prompt for
* additional lines. See the [custom evaluation functions](https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#custom-evaluation-functions)
* section for more details.
*/
eval?: REPLEval | undefined;
/**
* Defines if the repl prints output previews or not.
* @default `true` Always `false` in case `terminal` is falsy.
*/
preview?: boolean | undefined;
/**
* If `true`, specifies that the default `writer` function should include ANSI color
* styling to REPL output. If a custom `writer` function is provided then this has no
* effect.
* @default the REPL instance's `terminal` value
*/
useColors?: boolean | undefined;
/**
* If `true`, specifies that the default evaluation function will use the JavaScript
* `global` as the context as opposed to creating a new separate context for the REPL
* instance. The node CLI REPL sets this value to `true`.
* @default false
*/
useGlobal?: boolean | undefined;
/**
* If `true`, specifies that the default writer will not output the return value of a
* command if it evaluates to `undefined`.
* @default false
*/
ignoreUndefined?: boolean | undefined;
/**
* The function to invoke to format the output of each command before writing to `output`.
* @default a wrapper for `util.inspect`
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_customizing_repl_output
*/
writer?: REPLWriter | undefined;
/**
* An optional function used for custom Tab auto completion.
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/readline.html#readline_use_of_the_completer_function
*/
completer?: Completer | AsyncCompleter | undefined;
/**
* A flag that specifies whether the default evaluator executes all JavaScript commands in
* strict mode or default (sloppy) mode.
* Accepted values are:
* - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode.
* - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to
* prefacing every repl statement with `'use strict'`.
*/
replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined;
/**
* Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is
* pressed. This cannot be used together with a custom `eval` function.
* @default false
*/
breakEvalOnSigint?: boolean | undefined;
}
type REPLEval = (
this: REPLServer,
evalCmd: string,
context: Context,
file: string,
cb: (err: Error | null, result: any) => void,
) => void;
type REPLWriter = (this: REPLServer, obj: any) => string;
/**
* This is the default "writer" value, if none is passed in the REPL options,
* and it can be overridden by custom print functions.
*/
const writer: REPLWriter & {
options: InspectOptions;
};
type REPLCommandAction = (this: REPLServer, text: string) => void;
interface REPLCommand {
/**
* Help text to be displayed when `.help` is entered.
*/
help?: string | undefined;
/**
* The function to execute, optionally accepting a single string argument.
*/
action: REPLCommandAction;
}
/**
* Instances of `repl.REPLServer` are created using the {@link start} method
* or directly using the JavaScript `new` keyword.
*
* ```js
* import repl from 'node:repl';
*
* const options = { useColors: true };
*
* const firstInstance = repl.start(options);
* const secondInstance = new repl.REPLServer(options);
* ```
* @since v0.1.91
*/
class REPLServer extends Interface {
/**
* The `vm.Context` provided to the `eval` function to be used for JavaScript
* evaluation.
*/
readonly context: Context;
/**
* @deprecated since v14.3.0 - Use `input` instead.
*/
readonly inputStream: NodeJS.ReadableStream;
/**
* @deprecated since v14.3.0 - Use `output` instead.
*/
readonly outputStream: NodeJS.WritableStream;
/**
* The `Readable` stream from which REPL input will be read.
*/
readonly input: NodeJS.ReadableStream;
/**
* The `Writable` stream to which REPL output will be written.
*/
readonly output: NodeJS.WritableStream;
/**
* The commands registered via `replServer.defineCommand()`.
*/
readonly commands: NodeJS.ReadOnlyDict<REPLCommand>;
/**
* A value indicating whether the REPL is currently in "editor mode".
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_commands_and_special_keys
*/
readonly editorMode: boolean;
/**
* A value indicating whether the `_` variable has been assigned.
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
*/
readonly underscoreAssigned: boolean;
/**
* The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL).
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
*/
readonly last: any;
/**
* A value indicating whether the `_error` variable has been assigned.
*
* @since v9.8.0
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
*/
readonly underscoreErrAssigned: boolean;
/**
* The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL).
*
* @since v9.8.0
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable
*/
readonly lastError: any;
/**
* Specified in the REPL options, this is the function to be used when evaluating each
* given line of input. If not specified in the REPL options, this is an async wrapper
* for the JavaScript `eval()` function.
*/
readonly eval: REPLEval;
/**
* Specified in the REPL options, this is a value indicating whether the default
* `writer` function should include ANSI color styling to REPL output.
*/
readonly useColors: boolean;
/**
* Specified in the REPL options, this is a value indicating whether the default `eval`
* function will use the JavaScript `global` as the context as opposed to creating a new
* separate context for the REPL instance.
*/
readonly useGlobal: boolean;
/**
* Specified in the REPL options, this is a value indicating whether the default `writer`
* function should output the result of a command if it evaluates to `undefined`.
*/
readonly ignoreUndefined: boolean;
/**
* Specified in the REPL options, this is the function to invoke to format the output of
* each command before writing to `outputStream`. If not specified in the REPL options,
* this will be a wrapper for `util.inspect`.
*/
readonly writer: REPLWriter;
/**
* Specified in the REPL options, this is the function to use for custom Tab auto-completion.
*/
readonly completer: Completer | AsyncCompleter;
/**
* Specified in the REPL options, this is a flag that specifies whether the default `eval`
* function should execute all JavaScript commands in strict mode or default (sloppy) mode.
* Possible values are:
* - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode.
* - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to
* prefacing every repl statement with `'use strict'`.
*/
readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT;
/**
* NOTE: According to the documentation:
*
* > Instances of `repl.REPLServer` are created using the `repl.start()` method and
* > _should not_ be created directly using the JavaScript `new` keyword.
*
* `REPLServer` cannot be subclassed due to implementation specifics in NodeJS.
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_class_replserver
*/
private constructor();
/**
* The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands
* to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following
* properties:
*
* The following example shows two new commands added to the REPL instance:
*
* ```js
* import repl from 'node:repl';
*
* const replServer = repl.start({ prompt: '> ' });
* replServer.defineCommand('sayhello', {
* help: 'Say hello',
* action(name) {
* this.clearBufferedCommand();
* console.log(`Hello, ${name}!`);
* this.displayPrompt();
* },
* });
* replServer.defineCommand('saybye', function saybye() {
* console.log('Goodbye!');
* this.close();
* });
* ```
*
* The new commands can then be used from within the REPL instance:
*
* ```console
* > .sayhello Node.js User
* Hello, Node.js User!
* > .saybye
* Goodbye!
* ```
* @since v0.3.0
* @param keyword The command keyword (_without_ a leading `.` character).
* @param cmd The function to invoke when the command is processed.
*/
defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void;
/**
* The `replServer.displayPrompt()` method readies the REPL instance for input
* from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input.
*
* When multi-line input is being entered, an ellipsis is printed rather than the
* 'prompt'.
*
* When `preserveCursor` is `true`, the cursor placement will not be reset to `0`.
*
* The `replServer.displayPrompt` method is primarily intended to be called from
* within the action function for commands registered using the `replServer.defineCommand()` method.
* @since v0.1.91
*/
displayPrompt(preserveCursor?: boolean): void;
/**
* The `replServer.clearBufferedCommand()` method clears any command that has been
* buffered but not yet executed. This method is primarily intended to be
* called from within the action function for commands registered using the `replServer.defineCommand()` method.
* @since v9.0.0
*/
clearBufferedCommand(): void;
/**
* Initializes a history log file for the REPL instance. When executing the
* Node.js binary and using the command-line REPL, a history file is initialized
* by default. However, this is not the case when creating a REPL
* programmatically. Use this method to initialize a history log file when working
* with REPL instances programmatically.
* @since v11.10.0
* @param historyPath the path to the history file
* @param callback called when history writes are ready or upon error
*/
setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void;
/**
* events.EventEmitter
* 1. close - inherited from `readline.Interface`
* 2. line - inherited from `readline.Interface`
* 3. pause - inherited from `readline.Interface`
* 4. resume - inherited from `readline.Interface`
* 5. SIGCONT - inherited from `readline.Interface`
* 6. SIGINT - inherited from `readline.Interface`
* 7. SIGTSTP - inherited from `readline.Interface`
* 8. exit
* 9. reset
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "close", listener: () => void): this;
addListener(event: "line", listener: (input: string) => void): this;
addListener(event: "pause", listener: () => void): this;
addListener(event: "resume", listener: () => void): this;
addListener(event: "SIGCONT", listener: () => void): this;
addListener(event: "SIGINT", listener: () => void): this;
addListener(event: "SIGTSTP", listener: () => void): this;
addListener(event: "exit", listener: () => void): this;
addListener(event: "reset", listener: (context: Context) => void): this;
emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "close"): boolean;
emit(event: "line", input: string): boolean;
emit(event: "pause"): boolean;
emit(event: "resume"): boolean;
emit(event: "SIGCONT"): boolean;
emit(event: "SIGINT"): boolean;
emit(event: "SIGTSTP"): boolean;
emit(event: "exit"): boolean;
emit(event: "reset", context: Context): boolean;
on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this;
on(event: "line", listener: (input: string) => void): this;
on(event: "pause", listener: () => void): this;
on(event: "resume", listener: () => void): this;
on(event: "SIGCONT", listener: () => void): this;
on(event: "SIGINT", listener: () => void): this;
on(event: "SIGTSTP", listener: () => void): this;
on(event: "exit", listener: () => void): this;
on(event: "reset", listener: (context: Context) => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this;
once(event: "line", listener: (input: string) => void): this;
once(event: "pause", listener: () => void): this;
once(event: "resume", listener: () => void): this;
once(event: "SIGCONT", listener: () => void): this;
once(event: "SIGINT", listener: () => void): this;
once(event: "SIGTSTP", listener: () => void): this;
once(event: "exit", listener: () => void): this;
once(event: "reset", listener: (context: Context) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this;
prependListener(event: "line", listener: (input: string) => void): this;
prependListener(event: "pause", listener: () => void): this;
prependListener(event: "resume", listener: () => void): this;
prependListener(event: "SIGCONT", listener: () => void): this;
prependListener(event: "SIGINT", listener: () => void): this;
prependListener(event: "SIGTSTP", listener: () => void): this;
prependListener(event: "exit", listener: () => void): this;
prependListener(event: "reset", listener: (context: Context) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "line", listener: (input: string) => void): this;
prependOnceListener(event: "pause", listener: () => void): this;
prependOnceListener(event: "resume", listener: () => void): this;
prependOnceListener(event: "SIGCONT", listener: () => void): this;
prependOnceListener(event: "SIGINT", listener: () => void): this;
prependOnceListener(event: "SIGTSTP", listener: () => void): this;
prependOnceListener(event: "exit", listener: () => void): this;
prependOnceListener(event: "reset", listener: (context: Context) => void): this;
}
/**
* A flag passed in the REPL options. Evaluates expressions in sloppy mode.
*/
const REPL_MODE_SLOPPY: unique symbol;
/**
* A flag passed in the REPL options. Evaluates expressions in strict mode.
* This is equivalent to prefacing every repl statement with `'use strict'`.
*/
const REPL_MODE_STRICT: unique symbol;
/**
* The `repl.start()` method creates and starts a {@link REPLServer} instance.
*
* If `options` is a string, then it specifies the input prompt:
*
* ```js
* import repl from 'node:repl';
*
* // a Unix style prompt
* repl.start('$ ');
* ```
* @since v0.1.91
*/
function start(options?: string | ReplOptions): REPLServer;
/**
* Indicates a recoverable error that a `REPLServer` can use to support multi-line input.
*
* @see https://nodejs.org/dist/latest-v22.x/docs/api/repl.html#repl_recoverable_errors
*/
class Recoverable extends SyntaxError {
err: Error;
constructor(err: Error);
}
}
declare module "node:repl" {
export * from "repl";
}
@@ -0,0 +1,2 @@
export { HiddenText } from './HiddenText';
export { LiveRegion } from './LiveRegion';
@@ -0,0 +1,34 @@
/*!
* String.prototype.codePointAt v0.2.0 | MIT (c) Mathias Bynens (@mathias)
* http://mths.be/codepointat
*
* code-point | MIT (c) Shinnosuke Watanabe
* https://github.com/shinnn/code-point.js
*/
var getCodePoint = typeof String.prototype.codePointAt === 'function' ? function getCodePoint(str) {
return str.codePointAt(0);
} : function getCodePoint(str) {
var first = str.charCodeAt(0);
if (first >= 0xD800 && first <= 0xDBFF && str.length > 1) {
var second = str.charCodeAt(1);
if (second >= 0xDC00 && second <= 0xDFFF) {
return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
}
}
return first;
};
export default function codePoint(str) {
if (typeof str !== 'string') {
throw new TypeError(String(str) + ' is not a string. Argument must be a string.');
}
if (str.length === 0) {
throw new Error('Argument must be a non-empty string.');
}
return getCodePoint(str);
}
@@ -0,0 +1,31 @@
import type { TSESTree } from '@typescript-eslint/types';
import type { Referencer } from './Referencer';
import { Visitor } from './Visitor';
export declare class TypeVisitor extends Visitor {
#private;
constructor(referencer: Referencer);
static visit(referencer: Referencer, node: TSESTree.Node): void;
protected visitFunctionType(node: TSESTree.TSCallSignatureDeclaration | TSESTree.TSConstructorType | TSESTree.TSConstructSignatureDeclaration | TSESTree.TSFunctionType | TSESTree.TSMethodSignature): void;
protected visitPropertyKey(node: TSESTree.TSMethodSignature | TSESTree.TSPropertySignature): void;
protected Identifier(node: TSESTree.Identifier): void;
protected MemberExpression(node: TSESTree.MemberExpression): void;
protected TSCallSignatureDeclaration(node: TSESTree.TSCallSignatureDeclaration): void;
protected TSConditionalType(node: TSESTree.TSConditionalType): void;
protected TSConstructorType(node: TSESTree.TSConstructorType): void;
protected TSConstructSignatureDeclaration(node: TSESTree.TSConstructSignatureDeclaration): void;
protected TSFunctionType(node: TSESTree.TSFunctionType): void;
protected TSImportType(node: TSESTree.TSImportType): void;
protected TSIndexSignature(node: TSESTree.TSIndexSignature): void;
protected TSInferType(node: TSESTree.TSInferType): void;
protected TSInterfaceDeclaration(node: TSESTree.TSInterfaceDeclaration): void;
protected TSMappedType(node: TSESTree.TSMappedType): void;
protected TSMethodSignature(node: TSESTree.TSMethodSignature): void;
protected TSNamedTupleMember(node: TSESTree.TSNamedTupleMember): void;
protected TSPropertySignature(node: TSESTree.TSPropertySignature): void;
protected TSQualifiedName(node: TSESTree.TSQualifiedName): void;
protected TSTypeAliasDeclaration(node: TSESTree.TSTypeAliasDeclaration): void;
protected TSTypeParameter(node: TSESTree.TSTypeParameter): void;
protected TSTypePredicate(node: TSESTree.TSTypePredicate): void;
protected TSTypeAnnotation(node: TSESTree.TSTypeAnnotation): void;
protected TSTypeQuery(node: TSESTree.TSTypeQuery): void;
}
@@ -0,0 +1,7 @@
var classApplyDescriptorSet = require("./classApplyDescriptorSet.js");
var classPrivateFieldGet2 = require("./classPrivateFieldGet2.js");
function _classPrivateFieldSet(e, t, r) {
var s = classPrivateFieldGet2(t, e);
return classApplyDescriptorSet(e, s, r), r;
}
module.exports = _classPrivateFieldSet, module.exports.__esModule = true, module.exports["default"] = module.exports;
@@ -0,0 +1,29 @@
declare const _default: {
extends: string[];
rules: {
'@typescript-eslint/ban-ts-comment': "error";
'no-array-constructor': "off";
'@typescript-eslint/no-array-constructor': "error";
'@typescript-eslint/no-duplicate-enum-values': "error";
'@typescript-eslint/no-empty-object-type': "error";
'@typescript-eslint/no-explicit-any': "error";
'@typescript-eslint/no-extra-non-null-assertion': "error";
'@typescript-eslint/no-misused-new': "error";
'@typescript-eslint/no-namespace': "error";
'@typescript-eslint/no-non-null-asserted-optional-chain': "error";
'@typescript-eslint/no-require-imports': "error";
'@typescript-eslint/no-this-alias': "error";
'@typescript-eslint/no-unnecessary-type-constraint': "error";
'@typescript-eslint/no-unsafe-declaration-merging': "error";
'@typescript-eslint/no-unsafe-function-type': "error";
'no-unused-expressions': "off";
'@typescript-eslint/no-unused-expressions': "error";
'no-unused-vars': "off";
'@typescript-eslint/no-unused-vars': "error";
'@typescript-eslint/no-wrapper-object-types': "error";
'@typescript-eslint/prefer-as-const': "error";
'@typescript-eslint/prefer-namespace-keyword': "error";
'@typescript-eslint/triple-slash-reference': "error";
};
};
export = _default;
@@ -0,0 +1 @@
{"version":3,"file":"googleDocs.js","names":["normalWeightRegexp","blockTagNames","isBlockElement","element","includes","tagName","normalizeEmptyLines","doc","Array","from","querySelectorAll","filter","br","previousElementSibling","nextElementSibling","forEach","parentNode","removeChild","normalizeFontWeight","node","getAttribute","match","fragment","createDocumentFragment","append","childNodes","replaceChild","normalize","querySelector"],"sources":["../../../../src/modules/normalizeExternalHTML/normalizers/googleDocs.ts"],"sourcesContent":["const normalWeightRegexp = /font-weight:\\s*normal/;\nconst blockTagNames = ['P', 'OL', 'UL'];\n\nconst isBlockElement = (element: Element | null) => {\n return element && blockTagNames.includes(element.tagName);\n};\n\nconst normalizeEmptyLines = (doc: Document) => {\n Array.from(doc.querySelectorAll('br'))\n .filter(\n (br) =>\n isBlockElement(br.previousElementSibling) &&\n isBlockElement(br.nextElementSibling),\n )\n .forEach((br) => {\n br.parentNode?.removeChild(br);\n });\n};\n\nconst normalizeFontWeight = (doc: Document) => {\n Array.from(doc.querySelectorAll('b[style*=\"font-weight\"]'))\n .filter((node) => node.getAttribute('style')?.match(normalWeightRegexp))\n .forEach((node) => {\n const fragment = doc.createDocumentFragment();\n fragment.append(...node.childNodes);\n node.parentNode?.replaceChild(fragment, node);\n });\n};\n\nexport default function normalize(doc: Document) {\n if (doc.querySelector('[id^=\"docs-internal-guid-\"]')) {\n normalizeFontWeight(doc);\n normalizeEmptyLines(doc);\n }\n}\n"],"mappings":"AAAA,MAAMA,kBAAkB,GAAG,uBAAuB;AAClD,MAAMC,aAAa,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC;AAEvC,MAAMC,cAAc,GAAIC,OAAuB,IAAK;EAClD,OAAOA,OAAO,IAAIF,aAAa,CAACG,QAAQ,CAACD,OAAO,CAACE,OAAO,CAAC;AAC3D,CAAC;AAED,MAAMC,mBAAmB,GAAIC,GAAa,IAAK;EAC7CC,KAAK,CAACC,IAAI,CAACF,GAAG,CAACG,gBAAgB,CAAC,IAAI,CAAC,CAAC,CACnCC,MAAM,CACJC,EAAE,IACDV,cAAc,CAACU,EAAE,CAACC,sBAAsB,CAAC,IACzCX,cAAc,CAACU,EAAE,CAACE,kBAAkB,CACxC,CAAC,CACAC,OAAO,CAAEH,EAAE,IAAK;IACfA,EAAE,CAACI,UAAU,EAAEC,WAAW,CAACL,EAAE,CAAC;EAChC,CAAC,CAAC;AACN,CAAC;AAED,MAAMM,mBAAmB,GAAIX,GAAa,IAAK;EAC7CC,KAAK,CAACC,IAAI,CAACF,GAAG,CAACG,gBAAgB,CAAC,yBAAyB,CAAC,CAAC,CACxDC,MAAM,CAAEQ,IAAI,IAAKA,IAAI,CAACC,YAAY,CAAC,OAAO,CAAC,EAAEC,KAAK,CAACrB,kBAAkB,CAAC,CAAC,CACvEe,OAAO,CAAEI,IAAI,IAAK;IACjB,MAAMG,QAAQ,GAAGf,GAAG,CAACgB,sBAAsB,CAAC,CAAC;IAC7CD,QAAQ,CAACE,MAAM,CAAC,GAAGL,IAAI,CAACM,UAAU,CAAC;IACnCN,IAAI,CAACH,UAAU,EAAEU,YAAY,CAACJ,QAAQ,EAAEH,IAAI,CAAC;EAC/C,CAAC,CAAC;AACN,CAAC;AAED,eAAe,SAASQ,SAASA,CAACpB,GAAa,EAAE;EAC/C,IAAIA,GAAG,CAACqB,aAAa,CAAC,6BAA6B,CAAC,EAAE;IACpDV,mBAAmB,CAACX,GAAG,CAAC;IACxBD,mBAAmB,CAACC,GAAG,CAAC;EAC1B;AACF","ignoreList":[]}
@@ -0,0 +1,165 @@
# color-convert
Color-convert is a color conversion library for JavaScript and node.
It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest):
```js
import convert from 'color-convert';
convert.rgb.hsl(140, 200, 100); // [96, 48, 59]
convert.keyword.rgb('blue'); // [0, 0, 255]
const rgbChannels = convert.rgb.channels; // 3
const cmykChannels = convert.cmyk.channels; // 4
const ansiChannels = convert.ansi16.channels; // 1
```
# Install
```sh
npm install color-convert
```
# API
Simply get the property of the _from_ and _to_ conversion that you're looking for.
All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function.
All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha).
```js
import convert from 'color-convert';
// Hex to LAB
convert.hex.lab('DEADBF'); // [ 76, 21, -2 ]
convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ]
// RGB to CMYK
convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ]
convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ]
```
### Arrays
All functions that accept multiple arguments also support passing an array.
Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.)
```js
import convert from 'color-convert';
convert.rgb.hex(123, 45, 67); // '7B2D43'
convert.rgb.hex([123, 45, 67]); // '7B2D43'
```
## Routing
Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex).
Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js).
## Color Space Scales
Conversions rely on an agreed upon 'full-scale' value for each of the channels. Listed here are those values for the most common color spaces
### rgb
channel | full-scale value
---|---
r | 255
g | 255
b | 255
### hsl
channel | full-scale value
---|---
h | 360
s | 100
l | 100
### hsv
channel | full-scale value
---|---
h | 360
s | 100
v | 100
### hwb
channel | full-scale value
---|---
h | 360
w | 100
b | 100
### xyz
channel | full-scale value
---|---
x | 94
y | 99
z | 108
### lab
channel | full-scale value
---|---
l | 100
a | -86, 98
b | -108, 94
### lch
channel | full-scale value
---|---
l | 100
c | 133
h | 360
### oklab
channel | full-scale value
---|---
l | 100
a | -23, 28
b | -31, 20
### oklch
channel | full-scale value
---|---
l | 100
c | 32
h | 360
### cmyk
channel | full-scale value
---|---
c | 100
m | 100
y | 100
k | 100
### hex
channel | full-scale value
---|---
hex | ```0xffffff```
### keyword
channel | value
---|---
name | any key from [color-name](https://github.com/colorjs/color-name/blob/master/index.js)
### apple
channel | full-scale value
---|---
0 | 65535
1 | 65535
2 | 65535
### gray
channel | full-scale value
---|---
gray | 100
# Contribute
If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request.
# License
Copyright &copy; 2011-2016, Heather Arthur.
Copyright &copy; 2016-2021, Josh Junon.
Licensed under the [MIT License](LICENSE).
@@ -0,0 +1,92 @@
'use strict';
var GetIntrinsic = require('get-intrinsic');
var $SyntaxError = require('es-errors/syntax');
var $TypeError = require('es-errors/type');
var isInteger = require('math-intrinsics/isInteger');
var $Uint8Array = GetIntrinsic('%Uint8Array%', true);
var IsBigIntElementType = require('./IsBigIntElementType');
var IsDetachedBuffer = require('./IsDetachedBuffer');
var NumericToRawBytes = require('./NumericToRawBytes');
var isArrayBuffer = require('is-array-buffer');
var isSharedArrayBuffer = require('is-shared-array-buffer');
var hasOwn = require('hasown');
var tableTAO = require('./tables/typed-array-objects');
var defaultEndianness = require('../helpers/defaultEndianness');
var forEach = require('../helpers/forEach');
// https://262.ecma-international.org/15.0/#sec-setvalueinbuffer
/* eslint max-params: 0 */
module.exports = function SetValueInBuffer(arrayBuffer, byteIndex, type, value, isTypedArray, order) {
var isSAB = isSharedArrayBuffer(arrayBuffer);
if (!isArrayBuffer(arrayBuffer) && !isSAB) {
throw new $TypeError('Assertion failed: `arrayBuffer` must be an ArrayBuffer or a SharedArrayBuffer');
}
if (!isInteger(byteIndex) || byteIndex < 0) {
throw new $TypeError('Assertion failed: `byteIndex` must be a non-negative integer');
}
if (typeof type !== 'string' || !hasOwn(tableTAO.size, '$' + type)) {
throw new $TypeError('Assertion failed: `type` must be one of ' + tableTAO.choices);
}
if (typeof value !== 'number' && typeof value !== 'bigint') {
throw new $TypeError('Assertion failed: `value` must be a Number or a BigInt');
}
if (typeof isTypedArray !== 'boolean') {
throw new $TypeError('Assertion failed: `isTypedArray` must be a boolean');
}
if (order !== 'SEQ-CST' && order !== 'UNORDERED' && order !== 'INIT') {
throw new $TypeError('Assertion failed: `order` must be `"SEQ-CST"`, `"UNORDERED"`, or `"INIT"`');
}
if (arguments.length > 6 && typeof arguments[6] !== 'boolean') {
throw new $TypeError('Assertion failed: `isLittleEndian` must be a boolean, if present');
}
if (IsDetachedBuffer(arrayBuffer)) {
throw new $TypeError('Assertion failed: ArrayBuffer is detached'); // step 1
}
// 2. Assert: There are sufficient bytes in arrayBuffer starting at byteIndex to represent a value of type.
if (IsBigIntElementType(type) ? typeof value !== 'bigint' : typeof value !== 'number') { // step 3
throw new $TypeError('Assertion failed: `value` must be a BigInt if type is ~BIGINT64~ or ~BIGUINT64~, otherwise a Number');
}
// 4. Let block be arrayBuffer’s [[ArrayBufferData]] internal slot.
var elementSize = tableTAO.size['$' + type]; // step 5
// 6. If isLittleEndian is not present, set isLittleEndian to either true or false. The choice is implementation dependent and should be the alternative that is most efficient for the implementation. An implementation must use the same value each time this step is executed and the same value must be used for the corresponding step in the GetValueFromBuffer abstract operation.
var isLittleEndian = arguments.length > 6 ? arguments[6] : defaultEndianness === 'little'; // step 6
var rawBytes = NumericToRawBytes(type, value, isLittleEndian); // step 7
if (isSAB) { // step 8
/*
Let execution be the [[CandidateExecution]] field of the surrounding agent's Agent Record.
Let eventList be the [[EventList]] field of the element in execution.[[EventsRecords]] whose [[AgentSignifier]] is AgentSignifier().
If isTypedArray is true and IsNoTearConfiguration(type, order) is true, let noTear be true; otherwise let noTear be false.
Append WriteSharedMemory { [[Order]]: order, [[NoTear]]: noTear, [[Block]]: block, [[ByteIndex]]: byteIndex, [[ElementSize]]: elementSize, [[Payload]]: rawBytes } to eventList.
*/
throw new $SyntaxError('SharedArrayBuffer is not supported by this implementation');
} else {
// 9. Store the individual bytes of rawBytes into block, in order, starting at block[byteIndex].
var arr = new $Uint8Array(arrayBuffer, byteIndex, elementSize);
forEach(rawBytes, function (rawByte, i) {
arr[i] = rawByte;
});
}
// 10. Return NormalCompletion(undefined).
};
@@ -0,0 +1,25 @@
/**
* @file unicode字符转xml字符编码
* @author mengke01(kekee000@gmail.com)
*/
import string from '../../common/string';
/**
* unicode 转xml编码格式
*
* @param {Array.<number>} unicodeList unicode字符列表
* @return {string} xml编码格式
*/
export default function unicode2xml(unicodeList) {
if (typeof unicodeList === 'number') {
unicodeList = [unicodeList];
}
return unicodeList.map(u => {
if (u < 0x20) {
return '';
}
return u >= 0x20 && u <= 255
? string.encodeHTML(String.fromCharCode(u))
: '&#x' + u.toString(16) + ';';
}).join('');
}
@@ -0,0 +1 @@
{"version":3,"file":"address-error.d.ts","sourceRoot":"","sources":["../src/address-error.ts"],"names":[],"mappings":"AAAA,qBAAa,YAAa,SAAQ,KAAK;IACrC,YAAY,CAAC,EAAE,MAAM,CAAC;gBAEV,OAAO,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,MAAM;CAOnD"}
@@ -0,0 +1,241 @@
import {
actionsReducer,
hookWaitFor,
setupApiStore,
} from '@internal/tests/utils/helpers'
import { createSlice } from '@reduxjs/toolkit'
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { act, renderHook } from '@testing-library/react'
interface ResultType {
result: 'complex'
}
interface ArgType {
foo: 'bar'
count: 3
}
const baseQuery = fetchBaseQuery({ baseUrl: 'https://example.com' })
const api = createApi({
baseQuery,
endpoints(build) {
return {
querySuccess: build.query<ResultType, ArgType>({
query: () => '/success',
}),
querySuccess2: build.query({ query: () => '/success' }),
queryFail: build.query({ query: () => '/error' }),
mutationSuccess: build.mutation({
query: () => ({ url: '/success', method: 'POST' }),
}),
mutationSuccess2: build.mutation({
query: () => ({ url: '/success', method: 'POST' }),
}),
mutationFail: build.mutation({
query: () => ({ url: '/error', method: 'POST' }),
}),
}
},
})
const storeRef = setupApiStore(api, {
...actionsReducer,
})
const {
mutationFail,
mutationSuccess,
mutationSuccess2,
queryFail,
querySuccess,
querySuccess2,
} = api.endpoints
test('matches query pending & fulfilled actions for the given endpoint', async () => {
const endpoint = querySuccess2
const otherEndpoint = queryFail
const { result } = renderHook(() => endpoint.useQuery({} as any), {
wrapper: storeRef.wrapper,
})
await hookWaitFor(() => expect(result.current.isLoading).toBeFalsy())
expect(storeRef.store.getState().actions).toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchPending,
endpoint.matchFulfilled,
)
expect(storeRef.store.getState().actions).not.toMatchSequence(
api.internalActions.middlewareRegistered.match,
otherEndpoint.matchPending,
otherEndpoint.matchFulfilled,
)
expect(storeRef.store.getState().actions).not.toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchFulfilled,
api.endpoints.mutationSuccess.matchFulfilled,
endpoint.matchRejected,
)
expect(storeRef.store.getState().actions).not.toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchPending,
endpoint.matchRejected,
)
})
test('matches query pending & rejected actions for the given endpoint', async () => {
const endpoint = queryFail
const { result } = renderHook(() => endpoint.useQuery({}), {
wrapper: storeRef.wrapper,
})
await hookWaitFor(() => expect(result.current.isLoading).toBeFalsy())
expect(storeRef.store.getState().actions).toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchPending,
endpoint.matchRejected,
)
expect(storeRef.store.getState().actions).not.toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchFulfilled,
endpoint.matchRejected,
)
expect(storeRef.store.getState().actions).not.toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchPending,
endpoint.matchFulfilled,
)
})
test('matches lazy query pending & fulfilled actions for given endpoint', async () => {
const endpoint = querySuccess
const { result } = renderHook(() => endpoint.useLazyQuery(), {
wrapper: storeRef.wrapper,
})
act(() => void result.current[0]({} as any))
await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
expect(storeRef.store.getState().actions).toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchPending,
endpoint.matchFulfilled,
)
expect(storeRef.store.getState().actions).not.toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchFulfilled,
endpoint.matchRejected,
)
expect(storeRef.store.getState().actions).not.toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchPending,
endpoint.matchRejected,
)
})
test('matches lazy query pending & rejected actions for given endpoint', async () => {
const endpoint = queryFail
const { result } = renderHook(() => endpoint.useLazyQuery(), {
wrapper: storeRef.wrapper,
})
act(() => void result.current[0]({}))
await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
expect(storeRef.store.getState().actions).toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchPending,
endpoint.matchRejected,
)
expect(storeRef.store.getState().actions).not.toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchFulfilled,
endpoint.matchRejected,
)
expect(storeRef.store.getState().actions).not.toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchPending,
endpoint.matchFulfilled,
)
})
test('matches mutation pending & fulfilled actions for the given endpoint', async () => {
const endpoint = mutationSuccess
const otherEndpoint = mutationSuccess2
const { result } = renderHook(() => endpoint.useMutation(), {
wrapper: storeRef.wrapper,
})
act(() => void result.current[0]({}))
await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
expect(storeRef.store.getState().actions).toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchPending,
endpoint.matchFulfilled,
)
expect(storeRef.store.getState().actions).not.toMatchSequence(
api.internalActions.middlewareRegistered.match,
otherEndpoint.matchPending,
otherEndpoint.matchFulfilled,
)
expect(storeRef.store.getState().actions).not.toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchFulfilled,
endpoint.matchRejected,
)
expect(storeRef.store.getState().actions).not.toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchPending,
endpoint.matchRejected,
)
})
test('matches mutation pending & rejected actions for the given endpoint', async () => {
const endpoint = mutationFail
const { result } = renderHook(() => endpoint.useMutation(), {
wrapper: storeRef.wrapper,
})
act(() => void result.current[0]({}))
await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())
expect(storeRef.store.getState().actions).toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchPending,
endpoint.matchRejected,
)
expect(storeRef.store.getState().actions).not.toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchFulfilled,
endpoint.matchRejected,
)
expect(storeRef.store.getState().actions).not.toMatchSequence(
api.internalActions.middlewareRegistered.match,
endpoint.matchPending,
endpoint.matchFulfilled,
)
})
test('inferred types', () => {
createSlice({
name: 'auth',
initialState: {},
reducers: {},
extraReducers: (builder) => {
builder
.addMatcher(
api.endpoints.querySuccess.matchPending,
(state, action) => {
// @ts-expect-error
console.log(action.error)
},
)
.addMatcher(
api.endpoints.querySuccess.matchFulfilled,
(state, action) => {
// @ts-expect-error
console.log(action.error)
},
)
.addMatcher(
api.endpoints.querySuccess.matchRejected,
(state, action) => {},
)
},
})
})
@@ -0,0 +1,45 @@
{
"name": "@react-aria/ssr",
"version": "3.9.7",
"description": "Spectrum UI components in React",
"license": "Apache-2.0",
"main": "dist/main.js",
"module": "dist/module.js",
"exports": {
"types": "./dist/types.d.ts",
"import": "./dist/import.mjs",
"require": "./dist/main.js"
},
"types": "dist/types.d.ts",
"source": "src/index.ts",
"files": [
"dist",
"src"
],
"sideEffects": false,
"repository": {
"type": "git",
"url": "https://github.com/adobe/react-spectrum"
},
"dependencies": {
"@swc/helpers": "^0.5.0"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1"
},
"publishConfig": {
"access": "public"
},
"engines": {
"node": ">= 12"
},
"targets": {
"main": {
"context": "node"
},
"module": {
"context": "node"
}
},
"gitHead": "71f0ef23053f9e03ee7e97df736e8b083e006849"
}
@@ -0,0 +1,8 @@
var $caa152f7f8e96c85$exports = {};
$caa152f7f8e96c85$exports = {
"breadcrumbs": `Breadcrumb`
};
export {$caa152f7f8e96c85$exports as default};
//# sourceMappingURL=it-IT.module.js.map
@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = transform;
/**
* @file 对轮廓进行transform变换
* @author mengke01(kekee000@gmail.com)
*
* 参考资料:
* http://blog.csdn.net/henren555/article/details/9699449
*
* |X| |a c e| |x|
* |Y| = |b d f| * |y|
* |1| |0 0 1| |1|
*
* X = x * a + y * c + e
* Y = x * b + y * d + f
*/
/**
* 图形仿射矩阵变换
*
* @param {Array.<Object>} contour 轮廓点
* @param {number} a m11
* @param {number} b m12
* @param {number} c m21
* @param {number} d m22
* @param {number} e dx
* @param {number} f dy
* @return {Array.<Object>} contour 轮廓点
*/
function transform(contour, a, b, c, d, e, f) {
var x;
var y;
var p;
for (var i = 0, l = contour.length; i < l; i++) {
p = contour[i];
x = p.x;
y = p.y;
p.x = x * a + y * c + e;
p.y = x * b + y * d + f;
}
return contour;
}
@@ -0,0 +1 @@
{"version":3,"names":["_setPrototypeOf","require","_inherits","subClass","superClass","TypeError","prototype","Object","create","constructor","value","writable","configurable","defineProperty","setPrototypeOf"],"sources":["../../src/helpers/inherits.ts"],"sourcesContent":["/* @minVersion 7.0.0-beta.0 */\n\nimport setPrototypeOf from \"./setPrototypeOf.ts\";\n\nexport default function _inherits(\n subClass: Function,\n superClass: Function | null,\n) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n // We can't use defineProperty to set the prototype in a single step because it\n // doesn't work in Chrome <= 36. https://github.com/babel/babel/issues/14056\n // V8 bug: https://bugs.chromium.org/p/v8/issues/detail?id=3334\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true,\n },\n });\n Object.defineProperty(subClass, \"prototype\", { writable: false });\n if (superClass) setPrototypeOf(subClass, superClass);\n}\n"],"mappings":";;;;;;AAEA,IAAAA,eAAA,GAAAC,OAAA;AAEe,SAASC,SAASA,CAC/BC,QAAkB,EAClBC,UAA2B,EAC3B;EACA,IAAI,OAAOA,UAAU,KAAK,UAAU,IAAIA,UAAU,KAAK,IAAI,EAAE;IAC3D,MAAM,IAAIC,SAAS,CAAC,oDAAoD,CAAC;EAC3E;EAIAF,QAAQ,CAACG,SAAS,GAAGC,MAAM,CAACC,MAAM,CAACJ,UAAU,IAAIA,UAAU,CAACE,SAAS,EAAE;IACrEG,WAAW,EAAE;MACXC,KAAK,EAAEP,QAAQ;MACfQ,QAAQ,EAAE,IAAI;MACdC,YAAY,EAAE;IAChB;EACF,CAAC,CAAC;EACFL,MAAM,CAACM,cAAc,CAACV,QAAQ,EAAE,WAAW,EAAE;IAAEQ,QAAQ,EAAE;EAAM,CAAC,CAAC;EACjE,IAAIP,UAAU,EAAE,IAAAU,uBAAc,EAACX,QAAQ,EAAEC,UAAU,CAAC;AACtD","ignoreList":[]}
@@ -0,0 +1,3 @@
<svg viewBox="0 0 18 18">
<path class="ql-fill" d="M16.73975,13.81445v.43945a.54085.54085,0,0,1-.605.60547H11.855a.58392.58392,0,0,1-.64893-.60547V14.0127c0-2.90527,3.39941-3.42187,3.39941-4.55469a.77675.77675,0,0,0-.84717-.78125,1.17684,1.17684,0,0,0-.83594.38477c-.2749.26367-.561.374-.85791.13184l-.4292-.34082c-.30811-.24219-.38525-.51758-.1543-.81445a2.97155,2.97155,0,0,1,2.45361-1.17676,2.45393,2.45393,0,0,1,2.68408,2.40918c0,2.45312-3.1792,2.92676-3.27832,3.93848h2.79443A.54085.54085,0,0,1,16.73975,13.81445ZM9,3A.99974.99974,0,0,0,8,4V8H3V4A1,1,0,0,0,1,4V14a1,1,0,0,0,2,0V10H8v4a1,1,0,0,0,2,0V4A.99974.99974,0,0,0,9,3Z"/>
</svg>

After

Width:  |  Height:  |  Size: 641 B

@@ -0,0 +1,23 @@
"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("./capitalize"), exports);
__exportStar(require("./intrinsic-from-mapped-key"), exports);
__exportStar(require("./intrinsic"), exports);
__exportStar(require("./lowercase"), exports);
__exportStar(require("./uncapitalize"), exports);
__exportStar(require("./uppercase"), exports);
@@ -0,0 +1 @@
{"version":3,"file":"forbid-elements.d.ts","sourceRoot":"","sources":["forbid-elements.js"],"names":[],"mappings":"wBAsBW,OAAO,QAAQ,EAAE,IAAI,CAAC,UAAU"}
@@ -0,0 +1 @@
{"version":3,"file":"ServiceRedirectionBinding.d.ts","sourceRoot":"","sources":["../../../../src/binding/models/ServiceRedirectionBinding.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC5C,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,MAAM,WAAW,yBAAyB,CAAC,UAAU,CACnD,SAAQ,WAAW,CAAC,OAAO,iBAAiB,CAAC,kBAAkB,EAAE,UAAU,CAAC;IAC5E,uBAAuB,EAAE,iBAAiB,CAAC;CAC5C"}
@@ -0,0 +1,11 @@
import { PluginFunc } from 'dayjs'
declare const plugin: PluginFunc
export = plugin
declare module 'dayjs' {
interface Dayjs {
dayOfYear(): number
dayOfYear(value: number): Dayjs
}
}
@@ -0,0 +1 @@
{"version":3,"file":"updateMetadataTag.d.ts","sourceRoot":"","sources":["../../../../src/metadata/actions/updateMetadataTag.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,2BAA2B,EAAE,MAAM,uCAAuC,CAAC;AACpF,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAC9F,OAAO,EAAE,WAAW,EAAE,MAAM,uBAAuB,CAAC;AAEpD,wBAAgB,iBAAiB,CAC/B,GAAG,EAAE,WAAW,EAChB,KAAK,EAAE,OAAO,GACb,CACD,QAAQ,EAAE,2BAA2B,GAAG,gCAAgC,KACrE,2BAA2B,GAAG,gCAAgC,CAelE"}
@@ -0,0 +1 @@
{"version":3,"file":"tagged.spec.d.ts","sourceRoot":"","sources":["../../../../src/metadata/decorators/tagged.spec.ts"],"names":[],"mappings":""}
@@ -0,0 +1,81 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
const promSchema = z.promise(
z.object({
name: z.string(),
age: z.number(),
})
);
test("promise inference", () => {
type promSchemaType = z.infer<typeof promSchema>;
expectTypeOf<promSchemaType>().toEqualTypeOf<{ name: string; age: number }>();
});
test("promise parsing success", async () => {
// expect(() => promSchema.parse(Promise.resolve({ name: "Bobby", age: 10 }))).toThrow();
const pr = promSchema.parseAsync(Promise.resolve({ name: "Bobby", age: 10 }));
expect(pr).toBeInstanceOf(Promise);
const result = await pr;
expect(result).toMatchInlineSnapshot(`
{
"age": 10,
"name": "Bobby",
}
`);
});
test("promise parsing fail", async () => {
const bad = await promSchema.safeParseAsync(Promise.resolve({ name: "Bobby", age: "10" }));
expect(bad.success).toBe(false);
expect(bad.error).toBeInstanceOf(z.ZodError);
});
test("promise parsing fail 2", async () => {
const result = await promSchema.safeParseAsync(Promise.resolve({ name: "Bobby", age: "10" }));
expect(result.success).toBe(false);
expect(result.error).toBeInstanceOf(z.ZodError);
});
test("promise parsing fail", () => {
const bad = () => promSchema.parse({ then: () => {}, catch: {} });
expect(bad).toThrow();
});
test("sync promise parsing", () => {
expect(() => z.promise(z.string()).parse(Promise.resolve("asfd"))).toThrow();
});
const asyncFunction = z.function({
input: z.tuple([]),
output: promSchema,
});
test("async function pass", async () => {
const validatedFunction = asyncFunction.implementAsync(async () => {
return { name: "jimmy", age: 14 };
});
await expect(validatedFunction()).resolves.toEqual({
name: "jimmy",
age: 14,
});
});
test("async function fail", async () => {
const validatedFunction = asyncFunction.implementAsync(() => {
return Promise.resolve("asdf" as any);
});
await expect(validatedFunction()).rejects.toBeInstanceOf(z.core.$ZodError);
});
test("async promise parsing", () => {
const res = z.promise(z.number()).parseAsync(Promise.resolve(12));
expect(res).toBeInstanceOf(Promise);
});
test("resolves", () => {
const foo = z.literal("foo");
const res = z.promise(foo);
expect(res.unwrap()).toEqual(foo);
});
@@ -0,0 +1,19 @@
// @ts-ignore TS6133
import { test } from "vitest";
import { Mocker } from "./Mocker.js";
test("mocker", () => {
const mocker = new Mocker();
mocker.string;
mocker.number;
mocker.boolean;
mocker.null;
mocker.undefined;
mocker.stringOptional;
mocker.stringNullable;
mocker.numberOptional;
mocker.numberNullable;
mocker.booleanOptional;
mocker.booleanNullable;
});
@@ -0,0 +1,44 @@
import { MS, Y, D, W } from '../../constant';
export default (function (o, c, d) {
var proto = c.prototype;
proto.week = function (week) {
if (week === void 0) {
week = null;
}
if (week !== null) {
return this.add((week - this.week()) * 7, D);
}
var yearStart = this.$locale().yearStart || 1;
if (this.month() === 11 && this.date() > 25) {
// d(this) is for badMutable
var nextYearStartDay = d(this).startOf(Y).add(1, Y).date(yearStart);
var thisEndOfWeek = d(this).endOf(W);
if (nextYearStartDay.isBefore(thisEndOfWeek)) {
return 1;
}
}
var yearStartDay = d(this).startOf(Y).date(yearStart);
var yearStartWeek = yearStartDay.startOf(W).subtract(1, MS);
var diffInWeek = this.diff(yearStartWeek, W, true);
if (diffInWeek < 0) {
return d(this).startOf('week').week();
}
return Math.ceil(diffInWeek);
};
proto.weeks = function (week) {
if (week === void 0) {
week = null;
}
return this.week(week);
};
});
@@ -0,0 +1,87 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _reject2 = require('./internal/reject.js');
var _reject3 = _interopRequireDefault(_reject2);
var _eachOf = require('./eachOf.js');
var _eachOf2 = _interopRequireDefault(_eachOf);
var _awaitify = require('./internal/awaitify.js');
var _awaitify2 = _interopRequireDefault(_awaitify);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test.
*
* @name reject
* @static
* @memberOf module:Collections
* @method
* @see [async.filter]{@link module:Collections.filter}
* @category Collection
* @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over.
* @param {Function} iteratee - An async truth test to apply to each item in
* `coll`.
* The should complete with a boolean value as its `result`.
* Invoked with (item, callback).
* @param {Function} [callback] - A callback which is called after all the
* `iteratee` functions have finished. Invoked with (err, results).
* @returns {Promise} a promise, if no callback is passed
* @example
*
* // dir1 is a directory that contains file1.txt, file2.txt
* // dir2 is a directory that contains file3.txt, file4.txt
* // dir3 is a directory that contains file5.txt
*
* const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt'];
*
* // asynchronous function that checks if a file exists
* function fileExists(file, callback) {
* fs.access(file, fs.constants.F_OK, (err) => {
* callback(null, !err);
* });
* }
*
* // Using callbacks
* async.reject(fileList, fileExists, function(err, results) {
* // [ 'dir3/file6.txt' ]
* // results now equals an array of the non-existing files
* });
*
* // Using Promises
* async.reject(fileList, fileExists)
* .then( results => {
* console.log(results);
* // [ 'dir3/file6.txt' ]
* // results now equals an array of the non-existing files
* }).catch( err => {
* console.log(err);
* });
*
* // Using async/await
* async () => {
* try {
* let results = await async.reject(fileList, fileExists);
* console.log(results);
* // [ 'dir3/file6.txt' ]
* // results now equals an array of the non-existing files
* }
* catch (err) {
* console.log(err);
* }
* }
*
*/
function reject(coll, iteratee, callback) {
return (0, _reject3.default)(_eachOf2.default, coll, iteratee, callback);
}
exports.default = (0, _awaitify2.default)(reject, 3);
module.exports = exports.default;
@@ -0,0 +1 @@
{"name":"@react-stately/checkbox","version":"3.7.2","requiresBuild":false,"files":{"LICENSE":{"checkedAt":1794532105972,"integrity":"sha512-cil7stSp3ik41Hdv2Dj+GMcbvUfs1q+MZ2Yte0804py9i6oJJN/diCiIr/brcQOZ5ZqwAI6dgaHA7l8FZheQBw==","mode":420,"size":11335},"dist/main.js":{"checkedAt":1794532109536,"integrity":"sha512-Ee3ROvpLBWp3l0iNOLa2Za0C1X1zMMNxQ/VhjGharrdQK5dE/34NTr9nVreLNvUMqtOcIFaaMIVqis/3ccxMjQ==","mode":420,"size":974},"dist/module.js":{"checkedAt":1794532109536,"integrity":"sha512-K69TA3M0ICA/pvPaCHo/oxfyATaNvC1iPu3AT0gl7Jof8ql+f/+DDDHcnu18286jhrS2KwrVvHMMZfWVqeIeaw==","mode":420,"size":854},"dist/useCheckboxGroupState.main.js":{"checkedAt":1794532109536,"integrity":"sha512-t3saHvVOg508hyt7sk0eQCm3GnkWtbNqaWGkhHdvluj+Sc/DVFCrCTUT2Ve5ZpkyrWUNgERdQwl+LIR5zZ0QZQ==","mode":420,"size":3628},"dist/useCheckboxGroupState.module.js":{"checkedAt":1794532109536,"integrity":"sha512-nc9TWbOkvHn6TgqnwAKtYy8SyN0kCuqxEkJ+nNTOKbuYY8z9LjLulHdoO0AldQWr2FP3+8TANUrGhQVHkdAWjA==","mode":420,"size":3543},"package.json":{"checkedAt":1794532109537,"integrity":"sha512-UKJoTzexTJ11H8U8ZIH8wLNJ5Pdi3g7vwXHWXlfaE7j7bccdfPMyyEycRw9RD75ar6LWlE2tZCL0P16hMb+LUw==","mode":420,"size":1014},"dist/main.js.map":{"checkedAt":1794532109537,"integrity":"sha512-35RA9ZDTNK+7Mi8mbLzGmHIblWYr3RIc6dcPIZa1OGNy+llruhg4Bvx3e7r7osTnwodVVGS3Ru1Hmii1LDTC5g==","mode":420,"size":1000},"dist/module.js.map":{"checkedAt":1794532109537,"integrity":"sha512-x7Wm5WQlDhecZTA5tH4EYYqf99AptbyDdgv6LAUVtGBpZgN6E4mafDPZp12iuTFNthK+8XiDDesPZwyRUGAn1g==","mode":420,"size":996},"dist/types.d.ts.map":{"checkedAt":1794532109537,"integrity":"sha512-aNT2QU41W7GLTaV94bgWgX9JeLavOXs81Ney1vJEp5uF9o18sBKGAVAVzJ3v+oLDWGbkMfmGDEdSUy++oC1cyw==","mode":420,"size":2063},"dist/useCheckboxGroupState.main.js.map":{"checkedAt":1794532109537,"integrity":"sha512-0yzUjmVL7yt5MHQHWLkcIiOEZ444lGZIrFLUw5iurYZfWjPQGztLJQGGtKcOlXeRbhURotRwLFvSjJwrfdkNbQ==","mode":420,"size":6365},"dist/useCheckboxGroupState.module.js.map":{"checkedAt":1794532109537,"integrity":"sha512-2k+0DWWN8Z4+FAlOTqvhNxGq/WZ6i733ZzaNzIcgAx3R+YMl8qxHka8BAS1Wp0ii53DWD//ZYs4LAmbpiH7q5g==","mode":420,"size":6359},"README.md":{"checkedAt":1794532109537,"integrity":"sha512-/LBn/8l5vcddBGTShGLbO/X0HoizjUmNORY+Wt1GzJ+fk0QLGCTZHrUCmiadAe2kyPjc3LlzJynmDMh2oEjkXQ==","mode":420,"size":141},"dist/import.mjs":{"checkedAt":1794532109538,"integrity":"sha512-IMIin0/TZsHk/PZ4zO5Xip2q+sZQBTK9zKin6Iox2+VO7JpbBOo7J2WLPJThekpD7HbaFwuzDZxiPo4IBAv+Yw==","mode":420,"size":848},"dist/useCheckboxGroupState.mjs":{"checkedAt":1794532109536,"integrity":"sha512-nc9TWbOkvHn6TgqnwAKtYy8SyN0kCuqxEkJ+nNTOKbuYY8z9LjLulHdoO0AldQWr2FP3+8TANUrGhQVHkdAWjA==","mode":420,"size":3543},"src/index.ts":{"checkedAt":1794532109538,"integrity":"sha512-CY4kR5bfbpGWs+b7mC1361FVYMjQP5aSFSPB0DDE45xTDNO4AnN3NVAQkxEZB2yBW2DqBXjIB+adxp0vJRYHdg==","mode":420,"size":813},"dist/types.d.ts":{"checkedAt":1794532109538,"integrity":"sha512-uAsNah9+cBZKUBj6h3T9+Q8yLzntkpBoey3hixgM8+a8Z5hfWFB56/sFfBDB4f0ZhIUz6Ol9WMk9vNYKDbII0w==","mode":420,"size":1926},"src/useCheckboxGroupState.ts":{"checkedAt":1794532109538,"integrity":"sha512-OFILFe8AGQhPl7eEa3wSDsev/X5iK8pAJCsX58qN7npIL09mUoKOAJYQNihDj34sxHPwHER0r57+pCb4QtdfZw==","mode":420,"size":4606}}}
@@ -0,0 +1,146 @@
import type { TagDescription } from '@reduxjs/toolkit/query'
import { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query'
import { waitFor } from '@testing-library/react'
import { delay } from 'msw'
import { setupApiStore } from '../../tests/utils/helpers'
const tagTypes = [
'apple',
'pear',
'banana',
'tomato',
'cat',
'dog',
'giraffe',
] as const
type TagTypes = (typeof tagTypes)[number]
type ProvidedTags = TagDescription<TagTypes>[]
type InvalidatesTags = (ProvidedTags[number] | null | undefined)[]
/** providesTags, invalidatesTags, shouldInvalidate */
const caseMatrix: [ProvidedTags, InvalidatesTags, boolean][] = [
// *****************************
// basic invalidation behavior
// *****************************
// string
[['apple'], ['apple'], true],
[['apple'], ['pear'], false],
// string and type only behave identical
[[{ type: 'apple' }], ['apple'], true],
[[{ type: 'apple' }], ['pear'], false],
[['apple'], [{ type: 'apple' }], true],
[['apple'], [{ type: 'pear' }], false],
// type only invalidates type + id
[[{ type: 'apple', id: 1 }], [{ type: 'apple' }], true],
[[{ type: 'pear', id: 1 }], ['apple'], false],
// type + id never invalidates type only
[['apple'], [{ type: 'apple', id: 1 }], false],
[['pear'], [{ type: 'apple', id: 1 }], false],
// type + id invalidates type + id
[[{ type: 'apple', id: 1 }], [{ type: 'apple', id: 1 }], true],
[[{ type: 'apple', id: 1 }], [{ type: 'apple', id: 2 }], false],
// null and undefined
[['apple'], [null], false],
[['apple'], [undefined], false],
[['apple'], [null, 'apple'], true],
[['apple'], [undefined, 'apple'], true],
// *****************************
// test multiple values in array
// *****************************
[['apple', 'banana', 'tomato'], ['apple'], true],
[['apple'], ['pear', 'banana', 'tomato'], false],
[
[
{ type: 'apple', id: 1 },
{ type: 'apple', id: 3 },
{ type: 'apple', id: 4 },
],
[{ type: 'apple', id: 1 }],
true,
],
[
[{ type: 'apple', id: 1 }],
[
{ type: 'apple', id: 2 },
{ type: 'apple', id: 3 },
{ type: 'apple', id: 4 },
],
false,
],
]
test.each(caseMatrix)(
'\tprovidesTags: %O,\n\tinvalidatesTags: %O,\n\tshould invalidate: %s',
async (providesTags, invalidatesTags, shouldInvalidate) => {
let queryCount = 0
const {
store,
api,
api: {
endpoints: { invalidating, providing, unrelated },
},
} = setupApiStore(
createApi({
baseQuery: fakeBaseQuery(),
tagTypes,
endpoints: (build) => ({
providing: build.query<unknown, void>({
queryFn() {
queryCount++
return { data: {} }
},
providesTags,
}),
unrelated: build.query<unknown, void>({
queryFn() {
return { data: {} }
},
providesTags: ['cat', 'dog', { type: 'giraffe', id: 8 }],
}),
invalidating: build.mutation<unknown, void>({
queryFn() {
return { data: {} }
},
invalidatesTags,
}),
}),
}),
undefined,
{ withoutTestLifecycles: true },
)
store.dispatch(providing.initiate())
store.dispatch(unrelated.initiate())
expect(queryCount).toBe(1)
await waitFor(() => {
expect(api.endpoints.providing.select()(store.getState()).status).toBe(
'fulfilled',
)
expect(api.endpoints.unrelated.select()(store.getState()).status).toBe(
'fulfilled',
)
})
const toInvalidate = api.util.selectInvalidatedBy(
store.getState(),
invalidatesTags,
)
if (shouldInvalidate) {
expect(toInvalidate).toEqual([
{
queryCacheKey: 'providing(undefined)',
endpointName: 'providing',
originalArgs: undefined,
},
])
} else {
expect(toInvalidate).toEqual([])
}
store.dispatch(invalidating.initiate())
expect(queryCount).toBe(1)
await delay(2)
expect(queryCount).toBe(shouldInvalidate ? 2 : 1)
},
)
@@ -0,0 +1,91 @@
"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/utils.ts
var utils_exports = {};
__export(utils_exports, {
forwardRef: () => forwardRef,
isHeroUIEl: () => isHeroUIEl,
mapPropsVariants: () => mapPropsVariants,
mapPropsVariantsWithCommon: () => mapPropsVariantsWithCommon,
toIterator: () => toIterator
});
module.exports = __toCommonJS(utils_exports);
var import_react = require("react");
function forwardRef(component) {
return (0, import_react.forwardRef)(component);
}
var toIterator = (obj) => {
return {
...obj,
[Symbol.iterator]: function() {
const keys = Object.keys(this);
let index = 0;
return {
next: () => {
if (index >= keys.length) {
return { done: true };
}
const key = keys[index];
const value = this[key];
index++;
return { value: { key, value }, done: false };
}
};
}
};
};
var mapPropsVariants = (props, variantKeys, removeVariantProps = true) => {
if (!variantKeys) {
return [props, {}];
}
const picked = variantKeys.reduce((acc, key) => {
if (key in props) {
return { ...acc, [key]: props[key] };
} else {
return acc;
}
}, {});
if (removeVariantProps) {
const omitted = Object.keys(props).filter((key) => !variantKeys.includes(key)).reduce((acc, key) => ({ ...acc, [key]: props[key] }), {});
return [omitted, picked];
} else {
return [props, picked];
}
};
var mapPropsVariantsWithCommon = (originalProps, variantKeys, commonKeys) => {
const props = Object.keys(originalProps).filter((key) => !variantKeys.includes(key) || (commonKeys == null ? void 0 : commonKeys.includes(key))).reduce((acc, key) => ({ ...acc, [key]: originalProps[key] }), {});
const variants = variantKeys.reduce(
(acc, key) => ({ ...acc, [key]: originalProps[key] }),
{}
);
return [props, variants];
};
var isHeroUIEl = (component) => {
var _a, _b, _c;
return !!((_c = (_b = (_a = component.type) == null ? void 0 : _a.render) == null ? void 0 : _b.displayName) == null ? void 0 : _c.includes("HeroUI"));
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
forwardRef,
isHeroUIEl,
mapPropsVariants,
mapPropsVariantsWithCommon,
toIterator
});
@@ -0,0 +1,39 @@
// Macedonian [mk]
import dayjs from '../index';
var locale = {
name: 'mk',
weekdays: 'недела_понеделник_вторник_среда_четврток_петок_сабота'.split('_'),
months: 'јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември'.split('_'),
weekStart: 1,
weekdaysShort: 'нед_пон_вто_сре_чет_пет_саб'.split('_'),
monthsShort: 'јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек'.split('_'),
weekdaysMin: 'нe_пo_вт_ср_че_пе_сa'.split('_'),
ordinal: function ordinal(n) {
return n;
},
formats: {
LT: 'H:mm',
LTS: 'H:mm:ss',
L: 'D.MM.YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY H:mm',
LLLL: 'dddd, D MMMM YYYY H:mm'
},
relativeTime: {
future: 'после %s',
past: 'пред %s',
s: 'неколку секунди',
m: 'минута',
mm: '%d минути',
h: 'час',
hh: '%d часа',
d: 'ден',
dd: '%d дена',
M: 'месец',
MM: '%d месеци',
y: 'година',
yy: '%d години'
}
};
dayjs.locale(locale, null, true);
export default locale;
@@ -0,0 +1,52 @@
/**
* rejection-stream.js: TODO: add file header handler.
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*/
'use strict';
const { Writable } = require('readable-stream');
/**
* TODO: add class description.
* @type {RejectionStream}
* @extends {Writable}
*/
module.exports = class RejectionStream extends Writable {
/**
* Constructor function for the RejectionStream responsible for wrapping a
* TransportStream; only allowing writes of `info` objects with
* `info.rejection` set to true.
* @param {!TransportStream} transport - Stream to filter to rejections
*/
constructor(transport) {
super({ objectMode: true });
if (!transport) {
throw new Error('RejectionStream requires a TransportStream instance.');
}
this.handleRejections = true;
this.transport = transport;
}
/**
* Writes the info object to our transport instance if (and only if) the
* `rejection` property is set on the info.
* @param {mixed} info - TODO: add param description.
* @param {mixed} enc - TODO: add param description.
* @param {mixed} callback - TODO: add param description.
* @returns {mixed} - TODO: add return description.
* @private
*/
_write(info, enc, callback) {
if (info.rejection) {
return this.transport.log(info, callback);
}
callback();
return true;
}
};
@@ -0,0 +1,14 @@
var baseForOwnRight = require('./_baseForOwnRight'),
createBaseEach = require('./_createBaseEach');
/**
* The base implementation of `_.forEachRight` without support for iteratee shorthands.
*
* @private
* @param {Array|Object} collection The collection to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array|Object} Returns `collection`.
*/
var baseEachRight = createBaseEach(baseForOwnRight, true);
module.exports = baseEachRight;
@@ -0,0 +1 @@
{"name":"tinyglobby","version":"0.2.15","requiresBuild":false,"files":{"LICENSE":{"checkedAt":1794532090922,"integrity":"sha512-bWdqVoBO4HOOrUQinnR9DBTX5jfABSug93fBB7PdlSjxn39FVFtfWr2qdLw6+0NrvnDo4ItlavGYOvOEod5aiA==","mode":420,"size":1076},"dist/index.cjs":{"checkedAt":1794532090923,"integrity":"sha512-8Fh+D77bZPZMj0CMEiD7kf9+0u0gZSUeeEvPhEd1e+hvpMySd6LUtWr4chhInkH5fLxaE/u9izQuVS3bzyuUvQ==","mode":420,"size":14186},"dist/index.d.cts":{"checkedAt":1794532090923,"integrity":"sha512-Ie8DQKxvOrUQZdGPbQbiQPvbHeymHZG7OZrTCAQesjMFR/TuSDAnfJvKzXXZEbcN0DbhrfO9toR8KlZ4o1yeJA==","mode":420,"size":4641},"package.json":{"checkedAt":1794532090923,"integrity":"sha512-j4+10k2MGCXGViUQ8TVcFpklhdmLhRJvM21TT2KTf6NOz+8Y4m/0fhxWQNlTEm2NyaH6i1wExPBvkFb5QFA0pg==","mode":420,"size":1818},"README.md":{"checkedAt":1794532090923,"integrity":"sha512-SJ9n8JPfL4HxVADf49gTiO5YUIn1sPHF6F3tdA1tPdweaAf+q5a/dffh96qlIqz9O7LoN2fPuKEI2qIR8XPXpg==","mode":420,"size":932},"dist/index.mjs":{"checkedAt":1794532090923,"integrity":"sha512-1RR9b79VueH4ERW17xTZOlmRXHfHYrFNKZkowOOBc16nT52Z7oDATgDLnNzGMh5oa7jOdZ/0AjQg6T+S0GopLQ==","mode":420,"size":12881},"dist/index.d.mts":{"checkedAt":1794532090923,"integrity":"sha512-Ie8DQKxvOrUQZdGPbQbiQPvbHeymHZG7OZrTCAQesjMFR/TuSDAnfJvKzXXZEbcN0DbhrfO9toR8KlZ4o1yeJA==","mode":420,"size":4641}}}
@@ -0,0 +1,441 @@
export default `flf2a$ 4 4 7 -1 32 0 0 0
Author : Lukasz Tyrala (lt.)
Date : 2004/4/12 12:28:23
Version: 1.2 (full)
URL : http://home.autocom.pl/bjt/lt
e-mail : luty@autocom.pl
--------------------------------------------
..xx.. (C) COPYRIGHTS MMIV by
.xXXXXXXx Lukasz Tyrala (lt.)
/ xXXXXx
.\` xDXXx Permission is hereby given to
C Xx modify this font, as long as
\\ x the modifier's name is placed
\`---/| on a comment line.
lt. | | For comercial use of this font
please contact with me (lt.).
--------------------------------------------
This font has been created using JavE's
FIGlet font export assistant.
---- Have a look at: http://www.jave.de ----
Visit polish a-a usenet at------------------
-----------------------news:pl.rec.ascii-art
$ #
$ #
$ #
$ ##
___ #
| \\ #
|___\\#
|__/ ##
_ _ #
\\|\\| #
#
##
_||| #
|_'_]#
|_'_]#
||| ##
|| #
,||= #
'||=,#
=||' ##
__ #
\\ \\[\\#
\\ \\ #
|]\\/ ##
___ #
| .\\ #
/ .(/#
\\__/\\##
_ #
|/ #
#
##
___ #
| / #
|/ #
|\\ ##
__ #
\\ | #
\\| #
/| ##
#
\\||/#
|_ ]#
/||\\##
__ #
_| | #
|_ _]#
|_| ##
#
#
,-. #
'-/ ##
#
___ #
|___\\#
##
#
#
,-. #
'-' ##
__#
/ /#
/ / #
/_/ ##
____ #
| |#
| \\ |#
|___|##
__#
/ |#
/_ |#
\\|##
____ #
| \\#
'-'_/#
|___]##
____ #
|__ \\#
_[ |#
|___/##
_ #
/ / #
/_ ]#
|/ ##
____ #
| __|#
_\\_ \\#
|___/##
____ #
| __\\#
| .\\#
|___/##
____ #
|__ |#
/ /#
/_/ ##
____ #
| . /#
>.< #
|___/##
____ #
| . \\#
|__ |#
\\__/##
__ #
|_] #
,-. #
'-' ##
__ #
|_] #
,-. #
'-/ ##
__ #
/ / #
\\ \\ #
\\_\\ ##
___ #
|___]#
|__/ #
##
__ #
\\ \\#
/ /#
/_/ ##
____ #
| \\#
|/\\_/#
|] ##
_ #
,'_\`.#
;(_\\/#
\`._, ##
___ #
| \\ #
| . \\#
|/\\_/##
___ #
| .\\ #
| .<_#
|___/##
____ #
| __\\#
| \\__#
|___/##
___ #
| \\ #
| . \\#
|___/##
____ #
| __\\#
| ]_#
|___/##
____ #
| _\\#
| _\\ #
|/ ##
____ #
| _\\#
| [ \\#
|___/##
_ _ #
||_|\\#
| _ |#
|/ |/##
____ #
|___\\#
| / #
|/ ##
____ #
|_ \\#
,_/ /#
\\__/ ##
__ _ #
| V \\#
| <_#
|/\\_/##
__ #
| | #
| |__#
|___/##
_ #
|\\/\\ #
| \\#
|/v\\/##
__ #
| \\|\\#
| \\|#
|/\\_/##
____ #
| |#
| . |#
|___/##
____ #
| . \\#
| __/#
|/ ##
____ #
| |#
| . |#
|___\\##
____ #
| . \\#
| <_#
|/\\_/##
___ #
| _\\ #
[__ \\#
|___/##
____ #
|_ _\\#
|| #
|/ ##
_ #
|| \\ #
||_|\\#
|___/##
_ _ #
|| |\\#
||/ /#
|__/ ##
_ _ #
||| \\#
||\\ /#
|/\\/ ##
_ _ #
|\\/_\\#
_><__#
|/\\_/##
_ #
||_/\\#
| __/#
|/ ##
___ #
|_ \\ #
| __]#
|___/##
___ #
| _] #
||_ #
|__] ##
__ #
\\ \\ #
\\ \\ #
\\_\\##
___ #
|_ | #
_|| #
|__| ##
#
/\\ #
//\\\\ #
##
#
#
____ #
|___]##
_ #
\\| #
#
##
___ #
| \\ #
| . \\#
|/\\_/##
___ #
| .\\ #
| .<_#
|___/##
____ #
| __\\#
| \\__#
|___/##
___ #
| \\ #
| . \\#
|___/##
____ #
| __\\#
| ]_#
|___/##
____ #
| _\\#
| _\\ #
|/ ##
____ #
| _\\#
| [ \\#
|___/##
_ _ #
||_|\\#
| _ |#
|/ |/##
____ #
|___\\#
| / #
|/ ##
____ #
|_ \\#
,_/ /#
\\__/ ##
__ _ #
| V \\#
| <_#
|/\\_/##
__ #
| | #
| |__#
|___/##
_ #
|\\/\\ #
| \\#
|/v\\/##
__ #
| \\|\\#
| \\|#
|/\\_/##
____ #
| |#
| . |#
|___/##
____ #
| . \\#
| __/#
|/ ##
____ #
| |#
| . |#
|___\\##
____ #
| . \\#
| <_#
|/\\_/##
___ #
| _\\ #
[__ \\#
|___/##
____ #
|_ _\\#
|| #
|/ ##
_ #
|| \\ #
||_|\\#
|___/##
_ _ #
|| |\\#
||/ /#
|__/ ##
_ _ #
||| \\#
||\\ /#
|/\\/ ##
_ _ #
|\\/_\\#
_><__#
|/\\_/##
_ #
||_/\\#
| __/#
|/ ##
___ #
|_ \\ #
| __]#
|___/##
{#
#
#
##
__ #
| | #
| | #
|_| ##
}#
#
#
##
#
_,-.,#
|,-.'#
##
___ #
| \\ #
| . \\#
|/\\_/##
____ #
| |#
| . |#
|___/##
_ #
|| \\ #
||_|\\#
|___/##
___ #
| \\ #
| . \\#
|/\\_/##
____ #
| |#
| . |#
|___/##
_ #
|| \\ #
||_|\\#
|___/##
�#
#
#
##`
@@ -0,0 +1 @@
export declare function getOwnerDocument(target: Event['target']): Document;
@@ -0,0 +1,194 @@
{{# def.definitions }}
{{## def._error:_rule:
{{ 'istanbul ignore else'; }}
{{? it.createErrors !== false }}
{
keyword: '{{= $errorKeyword || _rule }}'
, dataPath: (dataPath || '') + {{= it.errorPath }}
, schemaPath: {{=it.util.toQuotedString($errSchemaPath)}}
, params: {{# def._errorParams[_rule] }}
{{? it.opts.messages !== false }}
, message: {{# def._errorMessages[_rule] }}
{{?}}
{{? it.opts.verbose }}
, schema: {{# def._errorSchemas[_rule] }}
, parentSchema: validate.schema{{=it.schemaPath}}
, data: {{=$data}}
{{?}}
}
{{??}}
{}
{{?}}
#}}
{{## def._addError:_rule:
if (vErrors === null) vErrors = [err];
else vErrors.push(err);
errors++;
#}}
{{## def.addError:_rule:
var err = {{# def._error:_rule }};
{{# def._addError:_rule }}
#}}
{{## def.error:_rule:
{{# def.beginDefOut}}
{{# def._error:_rule }}
{{# def.storeDefOut:__err }}
{{? !it.compositeRule && $breakOnError }}
{{ 'istanbul ignore if'; }}
{{? it.async }}
throw new ValidationError([{{=__err}}]);
{{??}}
validate.errors = [{{=__err}}];
return false;
{{?}}
{{??}}
var err = {{=__err}};
{{# def._addError:_rule }}
{{?}}
#}}
{{## def.extraError:_rule:
{{# def.addError:_rule}}
{{? !it.compositeRule && $breakOnError }}
{{ 'istanbul ignore if'; }}
{{? it.async }}
throw new ValidationError(vErrors);
{{??}}
validate.errors = vErrors;
return false;
{{?}}
{{?}}
#}}
{{## def.checkError:_rule:
if (!{{=$valid}}) {
{{# def.error:_rule }}
}
#}}
{{## def.resetErrors:
errors = {{=$errs}};
if (vErrors !== null) {
if ({{=$errs}}) vErrors.length = {{=$errs}};
else vErrors = null;
}
#}}
{{## def.concatSchema:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=$schema}}{{?}}#}}
{{## def.appendSchema:{{?$isData}}' + {{=$schemaValue}}{{??}}{{=$schemaValue}}'{{?}}#}}
{{## def.concatSchemaEQ:{{?$isData}}' + {{=$schemaValue}} + '{{??}}{{=it.util.escapeQuotes($schema)}}{{?}}#}}
{{## def._errorMessages = {
'false schema': "'boolean schema is false'",
$ref: "'can\\\'t resolve reference {{=it.util.escapeQuotes($schema)}}'",
additionalItems: "'should NOT have more than {{=$schema.length}} items'",
additionalProperties: "'{{? it.opts._errorDataPathProperty }}is an invalid additional property{{??}}should NOT have additional properties{{?}}'",
anyOf: "'should match some schema in anyOf'",
const: "'should be equal to constant'",
contains: "'should contain a valid item'",
dependencies: "'should have {{? $deps.length == 1 }}property {{= it.util.escapeQuotes($deps[0]) }}{{??}}properties {{= it.util.escapeQuotes($deps.join(\", \")) }}{{?}} when property {{= it.util.escapeQuotes($property) }} is present'",
'enum': "'should be equal to one of the allowed values'",
format: "'should match format \"{{#def.concatSchemaEQ}}\"'",
'if': "'should match \"' + {{=$ifClause}} + '\" schema'",
_limit: "'should be {{=$opStr}} {{#def.appendSchema}}",
_exclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'",
_limitItems: "'should NOT have {{?$keyword=='maxItems'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} items'",
_limitLength: "'should NOT be {{?$keyword=='maxLength'}}longer{{??}}shorter{{?}} than {{#def.concatSchema}} characters'",
_limitProperties:"'should NOT have {{?$keyword=='maxProperties'}}more{{??}}fewer{{?}} than {{#def.concatSchema}} properties'",
multipleOf: "'should be multiple of {{#def.appendSchema}}",
not: "'should NOT be valid'",
oneOf: "'should match exactly one schema in oneOf'",
pattern: "'should match pattern \"{{#def.concatSchemaEQ}}\"'",
propertyNames: "'property name \\'{{=$invalidName}}\\' is invalid'",
required: "'{{? it.opts._errorDataPathProperty }}is a required property{{??}}should have required property \\'{{=$missingProperty}}\\'{{?}}'",
type: "'should be {{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}'",
uniqueItems: "'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)'",
custom: "'should pass \"{{=$rule.keyword}}\" keyword validation'",
patternRequired: "'should have property matching pattern \\'{{=$missingPattern}}\\''",
switch: "'should pass \"switch\" keyword validation'",
_formatLimit: "'should be {{=$opStr}} \"{{#def.concatSchemaEQ}}\"'",
_formatExclusiveLimit: "'{{=$exclusiveKeyword}} should be boolean'"
} #}}
{{## def.schemaRefOrVal: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=$schema}}{{?}} #}}
{{## def.schemaRefOrQS: {{?$isData}}validate.schema{{=$schemaPath}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}}
{{## def._errorSchemas = {
'false schema': "false",
$ref: "{{=it.util.toQuotedString($schema)}}",
additionalItems: "false",
additionalProperties: "false",
anyOf: "validate.schema{{=$schemaPath}}",
const: "validate.schema{{=$schemaPath}}",
contains: "validate.schema{{=$schemaPath}}",
dependencies: "validate.schema{{=$schemaPath}}",
'enum': "validate.schema{{=$schemaPath}}",
format: "{{#def.schemaRefOrQS}}",
'if': "validate.schema{{=$schemaPath}}",
_limit: "{{#def.schemaRefOrVal}}",
_exclusiveLimit: "validate.schema{{=$schemaPath}}",
_limitItems: "{{#def.schemaRefOrVal}}",
_limitLength: "{{#def.schemaRefOrVal}}",
_limitProperties:"{{#def.schemaRefOrVal}}",
multipleOf: "{{#def.schemaRefOrVal}}",
not: "validate.schema{{=$schemaPath}}",
oneOf: "validate.schema{{=$schemaPath}}",
pattern: "{{#def.schemaRefOrQS}}",
propertyNames: "validate.schema{{=$schemaPath}}",
required: "validate.schema{{=$schemaPath}}",
type: "validate.schema{{=$schemaPath}}",
uniqueItems: "{{#def.schemaRefOrVal}}",
custom: "validate.schema{{=$schemaPath}}",
patternRequired: "validate.schema{{=$schemaPath}}",
switch: "validate.schema{{=$schemaPath}}",
_formatLimit: "{{#def.schemaRefOrQS}}",
_formatExclusiveLimit: "validate.schema{{=$schemaPath}}"
} #}}
{{## def.schemaValueQS: {{?$isData}}{{=$schemaValue}}{{??}}{{=it.util.toQuotedString($schema)}}{{?}} #}}
{{## def._errorParams = {
'false schema': "{}",
$ref: "{ ref: '{{=it.util.escapeQuotes($schema)}}' }",
additionalItems: "{ limit: {{=$schema.length}} }",
additionalProperties: "{ additionalProperty: '{{=$additionalProperty}}' }",
anyOf: "{}",
const: "{ allowedValue: schema{{=$lvl}} }",
contains: "{}",
dependencies: "{ property: '{{= it.util.escapeQuotes($property) }}', missingProperty: '{{=$missingProperty}}', depsCount: {{=$deps.length}}, deps: '{{= it.util.escapeQuotes($deps.length==1 ? $deps[0] : $deps.join(\", \")) }}' }",
'enum': "{ allowedValues: schema{{=$lvl}} }",
format: "{ format: {{#def.schemaValueQS}} }",
'if': "{ failingKeyword: {{=$ifClause}} }",
_limit: "{ comparison: {{=$opExpr}}, limit: {{=$schemaValue}}, exclusive: {{=$exclusive}} }",
_exclusiveLimit: "{}",
_limitItems: "{ limit: {{=$schemaValue}} }",
_limitLength: "{ limit: {{=$schemaValue}} }",
_limitProperties:"{ limit: {{=$schemaValue}} }",
multipleOf: "{ multipleOf: {{=$schemaValue}} }",
not: "{}",
oneOf: "{ passingSchemas: {{=$passingSchemas}} }",
pattern: "{ pattern: {{#def.schemaValueQS}} }",
propertyNames: "{ propertyName: '{{=$invalidName}}' }",
required: "{ missingProperty: '{{=$missingProperty}}' }",
type: "{ type: '{{? $typeIsArray }}{{= $typeSchema.join(\",\") }}{{??}}{{=$typeSchema}}{{?}}' }",
uniqueItems: "{ i: i, j: j }",
custom: "{ keyword: '{{=$rule.keyword}}' }",
patternRequired: "{ missingPattern: '{{=$missingPattern}}' }",
switch: "{ caseIndex: {{=$caseIndex}} }",
_formatLimit: "{ comparison: {{=$opExpr}}, limit: {{#def.schemaValueQS}}, exclusive: {{=$exclusive}} }",
_formatExclusiveLimit: "{}"
} #}}
@@ -0,0 +1,317 @@
# cookie
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Node.js Version][node-image]][node-url]
[![Build Status][ci-image]][ci-url]
[![Coverage Status][coveralls-image]][coveralls-url]
Basic HTTP cookie parser and serializer for HTTP servers.
## Installation
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```sh
$ npm install cookie
```
## API
```js
var cookie = require('cookie');
```
### cookie.parse(str, options)
Parse an HTTP `Cookie` header string and returning an object of all cookie name-value pairs.
The `str` argument is the string representing a `Cookie` header value and `options` is an
optional object containing additional parsing options.
```js
var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2');
// { foo: 'bar', equation: 'E=mc^2' }
```
#### Options
`cookie.parse` accepts these properties in the options object.
##### decode
Specifies a function that will be used to decode a cookie's value. Since the value of a cookie
has a limited character set (and must be a simple string), this function can be used to decode
a previously-encoded cookie value into a JavaScript string or other object.
The default function is the global `decodeURIComponent`, which will decode any URL-encoded
sequences into their byte representations.
**note** if an error is thrown from this function, the original, non-decoded cookie value will
be returned as the cookie's value.
### cookie.serialize(name, value, options)
Serialize a cookie name-value pair into a `Set-Cookie` header string. The `name` argument is the
name for the cookie, the `value` argument is the value to set the cookie to, and the `options`
argument is an optional object containing additional serialization options.
```js
var setCookie = cookie.serialize('foo', 'bar');
// foo=bar
```
#### Options
`cookie.serialize` accepts these properties in the options object.
##### domain
Specifies the value for the [`Domain` `Set-Cookie` attribute][rfc-6265-5.2.3]. By default, no
domain is set, and most clients will consider the cookie to apply to only the current domain.
##### encode
Specifies a function that will be used to encode a cookie's value. Since value of a cookie
has a limited character set (and must be a simple string), this function can be used to encode
a value into a string suited for a cookie's value.
The default function is the global `encodeURIComponent`, which will encode a JavaScript string
into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range.
##### expires
Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute][rfc-6265-5.2.1].
By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and
will delete it on a condition like exiting a web browser application.
**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and
`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,
so if both are set, they should point to the same date and time.
##### httpOnly
Specifies the `boolean` value for the [`HttpOnly` `Set-Cookie` attribute][rfc-6265-5.2.6]. When truthy,
the `HttpOnly` attribute is set, otherwise it is not. By default, the `HttpOnly` attribute is not set.
**note** be careful when setting this to `true`, as compliant clients will not allow client-side
JavaScript to see the cookie in `document.cookie`.
##### maxAge
Specifies the `number` (in seconds) to be the value for the [`Max-Age` `Set-Cookie` attribute][rfc-6265-5.2.2].
The given number will be converted to an integer by rounding down. By default, no maximum age is set.
**note** the [cookie storage model specification][rfc-6265-5.3] states that if both `expires` and
`maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,
so if both are set, they should point to the same date and time.
##### partitioned
Specifies the `boolean` value for the [`Partitioned` `Set-Cookie`](rfc-cutler-httpbis-partitioned-cookies)
attribute. When truthy, the `Partitioned` attribute is set, otherwise it is not. By default, the
`Partitioned` attribute is not set.
**note** This is an attribute that has not yet been fully standardized, and may change in the future.
This also means many clients may ignore this attribute until they understand it.
More information about can be found in [the proposal](https://github.com/privacycg/CHIPS).
##### path
Specifies the value for the [`Path` `Set-Cookie` attribute][rfc-6265-5.2.4]. By default, the path
is considered the ["default path"][rfc-6265-5.1.4].
##### priority
Specifies the `string` to be the value for the [`Priority` `Set-Cookie` attribute][rfc-west-cookie-priority-00-4.1].
- `'low'` will set the `Priority` attribute to `Low`.
- `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set.
- `'high'` will set the `Priority` attribute to `High`.
More information about the different priority levels can be found in
[the specification][rfc-west-cookie-priority-00-4.1].
**note** This is an attribute that has not yet been fully standardized, and may change in the future.
This also means many clients may ignore this attribute until they understand it.
##### sameSite
Specifies the `boolean` or `string` to be the value for the [`SameSite` `Set-Cookie` attribute][rfc-6265bis-09-5.4.7].
- `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
- `false` will not set the `SameSite` attribute.
- `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement.
- `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
- `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
More information about the different enforcement levels can be found in
[the specification][rfc-6265bis-09-5.4.7].
**note** This is an attribute that has not yet been fully standardized, and may change in the future.
This also means many clients may ignore this attribute until they understand it.
##### secure
Specifies the `boolean` value for the [`Secure` `Set-Cookie` attribute][rfc-6265-5.2.5]. When truthy,
the `Secure` attribute is set, otherwise it is not. By default, the `Secure` attribute is not set.
**note** be careful when setting this to `true`, as compliant clients will not send the cookie back to
the server in the future if the browser does not have an HTTPS connection.
## Example
The following example uses this module in conjunction with the Node.js core HTTP server
to prompt a user for their name and display it back on future visits.
```js
var cookie = require('cookie');
var escapeHtml = require('escape-html');
var http = require('http');
var url = require('url');
function onRequest(req, res) {
// Parse the query string
var query = url.parse(req.url, true, true).query;
if (query && query.name) {
// Set a new cookie with the name
res.setHeader('Set-Cookie', cookie.serialize('name', String(query.name), {
httpOnly: true,
maxAge: 60 * 60 * 24 * 7 // 1 week
}));
// Redirect back after setting cookie
res.statusCode = 302;
res.setHeader('Location', req.headers.referer || '/');
res.end();
return;
}
// Parse the cookies on the request
var cookies = cookie.parse(req.headers.cookie || '');
// Get the visitor name set in the cookie
var name = cookies.name;
res.setHeader('Content-Type', 'text/html; charset=UTF-8');
if (name) {
res.write('<p>Welcome back, <b>' + escapeHtml(name) + '</b>!</p>');
} else {
res.write('<p>Hello, new visitor!</p>');
}
res.write('<form method="GET">');
res.write('<input placeholder="enter your name" name="name"> <input type="submit" value="Set Name">');
res.end('</form>');
}
http.createServer(onRequest).listen(3000);
```
## Testing
```sh
$ npm test
```
## Benchmark
```
$ npm run bench
> cookie@0.5.0 bench
> node benchmark/index.js
node@18.18.2
acorn@8.10.0
ada@2.6.0
ares@1.19.1
brotli@1.0.9
cldr@43.1
icu@73.2
llhttp@6.0.11
modules@108
napi@9
nghttp2@1.57.0
nghttp3@0.7.0
ngtcp2@0.8.1
openssl@3.0.10+quic
simdutf@3.2.14
tz@2023c
undici@5.26.3
unicode@15.0
uv@1.44.2
uvwasi@0.0.18
v8@10.2.154.26-node.26
zlib@1.2.13.1-motley
> node benchmark/parse-top.js
cookie.parse - top sites
14 tests completed.
parse accounts.google.com x 2,588,913 ops/sec ±0.74% (186 runs sampled)
parse apple.com x 2,370,002 ops/sec ±0.69% (186 runs sampled)
parse cloudflare.com x 2,213,102 ops/sec ±0.88% (188 runs sampled)
parse docs.google.com x 2,194,157 ops/sec ±1.03% (184 runs sampled)
parse drive.google.com x 2,265,084 ops/sec ±0.79% (187 runs sampled)
parse en.wikipedia.org x 457,099 ops/sec ±0.81% (186 runs sampled)
parse linkedin.com x 504,407 ops/sec ±0.89% (186 runs sampled)
parse maps.google.com x 1,230,959 ops/sec ±0.98% (186 runs sampled)
parse microsoft.com x 926,294 ops/sec ±0.88% (184 runs sampled)
parse play.google.com x 2,311,338 ops/sec ±0.83% (185 runs sampled)
parse support.google.com x 1,508,850 ops/sec ±0.86% (186 runs sampled)
parse www.google.com x 1,022,582 ops/sec ±1.32% (182 runs sampled)
parse youtu.be x 332,136 ops/sec ±1.02% (185 runs sampled)
parse youtube.com x 323,833 ops/sec ±0.77% (183 runs sampled)
> node benchmark/parse.js
cookie.parse - generic
6 tests completed.
simple x 3,214,032 ops/sec ±1.61% (183 runs sampled)
decode x 587,237 ops/sec ±1.16% (187 runs sampled)
unquote x 2,954,618 ops/sec ±1.35% (183 runs sampled)
duplicates x 857,008 ops/sec ±0.89% (187 runs sampled)
10 cookies x 292,133 ops/sec ±0.89% (187 runs sampled)
100 cookies x 22,610 ops/sec ±0.68% (187 runs sampled)
```
## References
- [RFC 6265: HTTP State Management Mechanism][rfc-6265]
- [Same-site Cookies][rfc-6265bis-09-5.4.7]
[rfc-cutler-httpbis-partitioned-cookies]: https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/
[rfc-west-cookie-priority-00-4.1]: https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1
[rfc-6265bis-09-5.4.7]: https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7
[rfc-6265]: https://tools.ietf.org/html/rfc6265
[rfc-6265-5.1.4]: https://tools.ietf.org/html/rfc6265#section-5.1.4
[rfc-6265-5.2.1]: https://tools.ietf.org/html/rfc6265#section-5.2.1
[rfc-6265-5.2.2]: https://tools.ietf.org/html/rfc6265#section-5.2.2
[rfc-6265-5.2.3]: https://tools.ietf.org/html/rfc6265#section-5.2.3
[rfc-6265-5.2.4]: https://tools.ietf.org/html/rfc6265#section-5.2.4
[rfc-6265-5.2.5]: https://tools.ietf.org/html/rfc6265#section-5.2.5
[rfc-6265-5.2.6]: https://tools.ietf.org/html/rfc6265#section-5.2.6
[rfc-6265-5.3]: https://tools.ietf.org/html/rfc6265#section-5.3
## License
[MIT](LICENSE)
[ci-image]: https://badgen.net/github/checks/jshttp/cookie/master?label=ci
[ci-url]: https://github.com/jshttp/cookie/actions/workflows/ci.yml
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/cookie/master
[coveralls-url]: https://coveralls.io/r/jshttp/cookie?branch=master
[node-image]: https://badgen.net/npm/node/cookie
[node-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/cookie
[npm-url]: https://npmjs.org/package/cookie
[npm-version-image]: https://badgen.net/npm/v/cookie
@@ -0,0 +1,148 @@
import { createAction, isActionCreator } from '@reduxjs/toolkit'
describe('createAction', () => {
it('should create an action', () => {
const actionCreator = createAction<string>('A_TYPE')
expect(actionCreator('something')).toEqual({
type: 'A_TYPE',
payload: 'something',
})
})
describe('when stringifying action', () => {
it('should return the action type', () => {
const actionCreator = createAction('A_TYPE')
expect(`${actionCreator}`).toEqual('A_TYPE')
})
})
describe('when passing a prepareAction method only returning a payload', () => {
it('should use the payload returned from the prepareAction method', () => {
const actionCreator = createAction('A_TYPE', (a: number) => ({
payload: a * 2,
}))
expect(actionCreator(5).payload).toBe(10)
})
it('should not have a meta attribute on the resulting Action', () => {
const actionCreator = createAction('A_TYPE', (a: number) => ({
payload: a * 2,
}))
expect('meta' in actionCreator(5)).toBeFalsy()
})
})
describe('when passing a prepareAction method returning a payload and meta', () => {
it('should use the payload returned from the prepareAction method', () => {
const actionCreator = createAction('A_TYPE', (a: number) => ({
payload: a * 2,
meta: a / 2,
}))
expect(actionCreator(5).payload).toBe(10)
})
it('should use the meta returned from the prepareAction method', () => {
const actionCreator = createAction('A_TYPE', (a: number) => ({
payload: a * 2,
meta: a / 2,
}))
expect(actionCreator(10).meta).toBe(5)
})
})
describe('when passing a prepareAction method returning a payload and error', () => {
it('should use the payload returned from the prepareAction method', () => {
const actionCreator = createAction('A_TYPE', (a: number) => ({
payload: a * 2,
error: true,
}))
expect(actionCreator(5).payload).toBe(10)
})
it('should use the error returned from the prepareAction method', () => {
const actionCreator = createAction('A_TYPE', (a: number) => ({
payload: a * 2,
error: true,
}))
expect(actionCreator(10).error).toBe(true)
})
})
describe('when passing a prepareAction method returning a payload, meta and error', () => {
it('should use the payload returned from the prepareAction method', () => {
const actionCreator = createAction('A_TYPE', (a: number) => ({
payload: a * 2,
meta: a / 2,
error: true,
}))
expect(actionCreator(5).payload).toBe(10)
})
it('should use the error returned from the prepareAction method', () => {
const actionCreator = createAction('A_TYPE', (a: number) => ({
payload: a * 2,
meta: a / 2,
error: true,
}))
expect(actionCreator(10).error).toBe(true)
})
it('should use the meta returned from the prepareAction method', () => {
const actionCreator = createAction('A_TYPE', (a: number) => ({
payload: a * 2,
meta: a / 2,
error: true,
}))
expect(actionCreator(10).meta).toBe(5)
})
})
describe('when passing a prepareAction that accepts multiple arguments', () => {
it('should pass all arguments of the resulting actionCreator to prepareAction', () => {
const actionCreator = createAction(
'A_TYPE',
(a: string, b: string, c: string) => ({
payload: a + b + c,
}),
)
expect(actionCreator('1', '2', '3').payload).toBe('123')
})
})
describe('actionCreator.match', () => {
test('should return true for actions generated by own actionCreator', () => {
const actionCreator = createAction('test')
expect(actionCreator.match(actionCreator())).toBe(true)
})
test('should return true for matching actions', () => {
const actionCreator = createAction('test')
expect(actionCreator.match({ type: 'test' })).toBe(true)
})
test('should return false for other actions', () => {
const actionCreator = createAction('test')
expect(actionCreator.match({ type: 'test-abc' })).toBe(false)
})
})
})
const actionCreator = createAction('anAction')
class Action {
type = 'totally an action'
}
describe('isActionCreator', () => {
it('should only return true for action creators', () => {
expect(isActionCreator(actionCreator)).toBe(true)
const notActionCreators = [
{ type: 'an action' },
{ type: 'more props', extra: true },
actionCreator(),
Promise.resolve({ type: 'an action' }),
new Action(),
false,
'a string',
false,
]
for (const notActionCreator of notActionCreators) {
expect(isActionCreator(notActionCreator)).toBe(false)
}
})
})
@@ -0,0 +1,40 @@
var baseDifference = require('./_baseDifference'),
baseFlatten = require('./_baseFlatten'),
baseRest = require('./_baseRest'),
isArrayLikeObject = require('./isArrayLikeObject'),
last = require('./last');
/**
* This method is like `_.difference` except that it accepts `comparator`
* which is invoked to compare elements of `array` to `values`. The order and
* references of result values are determined by the first array. The comparator
* is invoked with two arguments: (arrVal, othVal).
*
* **Note:** Unlike `_.pullAllWith`, this method returns a new array.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The values to exclude.
* @param {Function} [comparator] The comparator invoked per element.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
*
* _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
* // => [{ 'x': 2, 'y': 1 }]
*/
var differenceWith = baseRest(function(array, values) {
var comparator = last(values);
if (isArrayLikeObject(comparator)) {
comparator = undefined;
}
return isArrayLikeObject(array)
? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)
: [];
});
module.exports = differenceWith;
@@ -0,0 +1,39 @@
// Kyrgyz [ky]
import dayjs from '../index';
var locale = {
name: 'ky',
weekdays: 'Жекшемби_Дүйшөмбү_Шейшемби_Шаршемби_Бейшемби_Жума_Ишемби'.split('_'),
months: 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'),
weekStart: 1,
weekdaysShort: 'Жек_Дүй_Шей_Шар_Бей_Жум_Ише'.split('_'),
monthsShort: 'янв_фев_март_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'),
weekdaysMin: 'Жк_Дй_Шй_Шр_Бй_Жм_Иш'.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: '%s ичинде',
past: '%s мурун',
s: 'бирнече секунд',
m: 'бир мүнөт',
mm: '%d мүнөт',
h: 'бир саат',
hh: '%d саат',
d: 'бир күн',
dd: '%d күн',
M: 'бир ай',
MM: '%d ай',
y: 'бир жыл',
yy: '%d жыл'
}
};
dayjs.locale(locale, null, true);
export default locale;
@@ -0,0 +1 @@
{"version":3,"file":"resolveInstanceBindingNode.js","sourceRoot":"","sources":["../../../../src/resolution/actions/resolveInstanceBindingNode.ts"],"names":[],"mappings":";;AAOA,gEA2CC;AAlDD,gDAAgD;AAOhD,SAAgB,0BAA0B,CAIxC,uCAGmC,EACnC,oDAIsC,EACtC,+CAIyB;IAKzB,OAAO,CACL,MAAwB,EACxB,IAAmC,EACb,EAAE;QACxB,MAAM,iBAAiB,GACrB,uCAAuC,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAExD,IAAI,IAAA,kBAAS,EAAC,iBAAiB,CAAC,EAAE,CAAC;YACjC,OAAO,oDAAoD,CACzD,iBAAiB,EACjB,MAAM,EACN,IAAI,CACL,CAAC;QACJ,CAAC;QAED,OAAO,+CAA+C,CACpD,iBAAiB,EACjB,MAAM,EACN,IAAI,CACL,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,28 @@
// Copyright (c) 2015 Ryan Prichard
//
// 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.
#ifndef CONSOLEFONT_H
#define CONSOLEFONT_H
#include <windows.h>
void setSmallFont(HANDLE conout, int columns, bool isNewW10);
#endif // CONSOLEFONT_H
@@ -0,0 +1 @@
{"name":"ajv","version":"6.12.6","requiresBuild":false,"files":{"scripts/info":{"checkedAt":1794532092974,"integrity":"sha512-4EhvDHUq1P6v2DrRFulTGebQeVeujGLdAhvWeBdLh2g9nfQWa+arO7BqSE/mbbiXBEQXaHFdUuYB68jtfksrOQ==","mode":438,"size":289},"LICENSE":{"checkedAt":1794532092974,"integrity":"sha512-pSvNrQ1v8mPbFOC9xj418VpthXfRCGIqlqtD9aM5dt8zZxZsJPaSM0hdVAAb2WLS02W7nwSlHqGH/rtmbFvI6g==","mode":438,"size":1090},"scripts/prepare-tests":{"checkedAt":1794532092975,"integrity":"sha512-F0ODgoWsgSRy778Txg9GXKCLgIY3zzaB2Pe7f/0ALiJ4OesItoYm8itXpVNYJ7cF2YF/fRXrpEchU1fqsOEk9g==","mode":438,"size":269},"scripts/publish-built-version":{"checkedAt":1794532092975,"integrity":"sha512-DaMjYHyZ6Vn0Xk5UbWwySbi04s3bW9v0gUSjJ7apBx3/UPolPd6skBm8r8yaIYGiAwydkBuc/5pjcGO4uCcjZA==","mode":438,"size":842},"scripts/travis-gh-pages":{"checkedAt":1794532092975,"integrity":"sha512-DqRDq25cYN2TGJiD4b0+O8KqznnsINFOW49TuUCM4KvgZFr0BwTGfFjt0GUX0YGmkSxFRT+S4Xfx6R3KNaowBw==","mode":438,"size":874},"lib/dot/coerce.def":{"checkedAt":1794532092975,"integrity":"sha512-j9Wy5x6GKxAMJ6jMxG/NaWqEZDWlA8oB62wJJLADLtiEYJYIZO8Ku+pPdOZR0cWNRdfwmm3ZG5AzsUUdffuTMQ==","mode":438,"size":1979},"lib/dot/defaults.def":{"checkedAt":1794532092975,"integrity":"sha512-DsTfQCTG5Xh+eYQ8GAS2ATpR1RSOXXOq2PZq20CfmMxrwpQ2OrWHX90tszZiuj345TN86Za01/JXql2kPxB74Q==","mode":438,"size":1285},"lib/dot/definitions.def":{"checkedAt":1794532092975,"integrity":"sha512-OsVxnBha3TWxZszm87oyVwMLuvPy8zCM7FhppaChWhd3Ixn5/eUpawYw7xd6Tuto6/ASn0qQRb5eXvD6z0NzoA==","mode":438,"size":4022},"lib/dot/errors.def":{"checkedAt":1794532092975,"integrity":"sha512-j267ngVY6S1KwxzelehINgerY2NQmCRmibNrgkqaLTNyRyvTHUmO8bJDiOiVXbUwJylQBx6PjxVAqznkQ7Q5Sw==","mode":438,"size":8282},"lib/dot/missing.def":{"checkedAt":1794532092975,"integrity":"sha512-B64CwCraCaap2DgBk6VePs0AyMrxb+oCm4iZVi8NsAIqOLbq0IG6rXYv6eRAZWsosOwhqGdOMQg2yqgv7EXDcQ==","mode":438,"size":1194},"lib/dotjs/_limit.js":{"checkedAt":1794532092976,"integrity":"sha512-pMH3xUpUxQjkjR+7HO1D7dff1Fu6P2XtVhluZwZEVhce2WRjxfLO0Nkb08Q8v38UGWHDs7C633ltQuxjkd5Btg==","mode":438,"size":7395},"lib/dotjs/_limitItems.js":{"checkedAt":1794532092976,"integrity":"sha512-tJRdjc0Bos8IcmLW9GfESJFTLf1NyYLjZ93f/ayqPpkOKuMy0ENH3fvdtDuAPopsgu/MrM2KfdvqzPEkADtP/g==","mode":438,"size":2704},"lib/dotjs/_limitLength.js":{"checkedAt":1794532092976,"integrity":"sha512-uYBfrvOVtBPuGptE9G2QhbMmjvG6y8hD3rOpLgo5tor5B9x13nkspp+D+tk9XbebWEd/2ikqgGnHnMaqZAkKVg==","mode":438,"size":2825},"lib/dotjs/_limitProperties.js":{"checkedAt":1794532092976,"integrity":"sha512-ohJBvsjbH7FxNOke8vpA5p8XLvYaNARHWzGFc9iIb/BDhAl/l+iLu+ACvyqf7Yb5bovDSJO897rBOZCWJVNgdA==","mode":438,"size":2742},".tonic_example.js":{"checkedAt":1794532092976,"integrity":"sha512-BbFtQN5Dnta3q/W7b37hF/5QnlV8Orw1gy+++rV61l+wkwnrQnMwgO4YzlV3DRAzDgVPg6V4VmJO1iqDA5fRHw==","mode":438,"size":439},"dist/ajv.bundle.js":{"checkedAt":1794532092977,"integrity":"sha512-km2o1mynU1nR0HonrYrI0TA+QvRMtONwnfA/nl15hnd/WyjZ/FLV7NROHAbzzSjHxIeQPfiJRUSUzevO2Ut0Ng==","mode":438,"size":272665},"lib/ajv.js":{"checkedAt":1794532092977,"integrity":"sha512-qP/QErWxCZ8Y8v3zl+5fHDjkKo0Ydi8hlylYG0Hj4j0iL3t79LBKxM2+2n02WAzwslOW9Yl5yPa+LZ0YYu/BYw==","mode":438,"size":15837},"dist/ajv.min.js":{"checkedAt":1794532092978,"integrity":"sha512-+WCxUYg8L1mFBIyL05WJAJRP2UWCy+6mvpMHQbjPDdlDVcgS4XYyPhw5TVvzf9Dq8DTD/BedPW5745dqUeIP5g==","mode":438,"size":121997},"lib/dotjs/allOf.js":{"checkedAt":1794532092978,"integrity":"sha512-0U9NAfHOH/A7Jssiy3AOjiYHloYzX1EcfhQXWqE/cUvNL3m3Tjy5BAdyZQpgo3M4JH5cWjmUTI7gDiyTyKNzRA==","mode":438,"size":1349},"lib/dotjs/anyOf.js":{"checkedAt":1794532092978,"integrity":"sha512-fGGhxnCJM/U9r9AgSEOtfbEazmQsMfenJOQuj9PlM/je0XOMCSIIThbjE/+eJoFnw9oQApi9n4vBmS0dWcXiqQ==","mode":438,"size":2925},"lib/compile/async.js":{"checkedAt":1794532092978,"integrity":"sha512-G30ILTAyBJGTf186nKWzMrntFb01mxoavqQLKaDfgoO3a4lPvOvdRPgzBpX46hqYbh82iQCOxlFoyZMBdr51Zg==","mode":438,"size":2644},"scripts/bundle.js":{"checkedAt":1794532092978,"integrity":"sha512-AoVmISFOb40vWK5l5Obz+b7k09t3541VmeJbTKcoXgFd8qHY+nMpjjjKL/v10FjBCPXHLXgrc1Ux6mYbBLTYEA==","mode":438,"size":1795},"lib/cache.js":{"checkedAt":1794532092978,"integrity":"sha512-8M5Udd6Mlq2w0cNhPfJkwWltL4M5qxvZIjVVNLLgbVMmQeYTFUlxd/ekJVk9EzgLRGiMcr12Nu4CrEmy8VYxPA==","mode":438,"size":409},"lib/dotjs/comment.js":{"checkedAt":1794532092978,"integrity":"sha512-vX/wX9/g8JBngLetCVaVtJnLGdk/iZHY5VJgecD545d1LtbnM/Z7u4F8PyiLhE/8QCwZ6+0Xssp7/P5lvkgREA==","mode":438,"size":573},"scripts/compile-dots.js":{"checkedAt":1794532092978,"integrity":"sha512-fG7owXhJ1V9bEMVpEl0BNBUwYszIhOWhfvZzAPZseeoUxgYNIOldKdkGSAxiwnnzxDr3VnEfLTuObOBoTvdPJw==","mode":438,"size":2431},"lib/dotjs/const.js":{"checkedAt":1794532092978,"integrity":"sha512-aNkT6RhJ4CqDEmLLbJ5H5Byw1K+xm8zXQB0SL4asW9jA5r2lfVUdsPutvOSmY1GNTop7xQ/Nws5E0sKxaZVJ+A==","mode":438,"size":2113},"lib/dotjs/contains.js":{"checkedAt":1794532092979,"integrity":"sha512-YXa7KJGMiFF3AQ5X/Y1Ox0R9aaJOcvZywSah+kspibfjBultLFJ4oBsOAcBNtQFK+ZG+bTEXk6phoDFj95AUww==","mode":438,"size":3Line truncated
@@ -0,0 +1,65 @@
// Chinese (Hong Kong) [zh-hk]
import dayjs from '../index';
var locale = {
name: 'zh-hk',
months: '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
weekdays: '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
weekdaysShort: '週日_週一_週二_週三_週四_週五_週六'.split('_'),
weekdaysMin: '日_一_二_三_四_五_六'.split('_'),
ordinal: function ordinal(number, period) {
switch (period) {
case 'W':
return number + "\u9031";
default:
return number + "\u65E5";
}
},
formats: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'YYYY/MM/DD',
LL: 'YYYY年M月D日',
LLL: 'YYYY年M月D日 HH:mm',
LLLL: 'YYYY年M月D日dddd HH:mm',
l: 'YYYY/M/D',
ll: 'YYYY年M月D日',
lll: 'YYYY年M月D日 HH:mm',
llll: 'YYYY年M月D日dddd HH:mm'
},
relativeTime: {
future: '%s內',
past: '%s前',
s: '幾秒',
m: '一分鐘',
mm: '%d 分鐘',
h: '一小時',
hh: '%d 小時',
d: '一天',
dd: '%d 天',
M: '一個月',
MM: '%d 個月',
y: '一年',
yy: '%d 年'
},
meridiem: function meridiem(hour, minute) {
var hm = hour * 100 + minute;
if (hm < 600) {
return '凌晨';
} else if (hm < 900) {
return '早上';
} else if (hm < 1100) {
return '上午';
} else if (hm < 1300) {
return '中午';
} else if (hm < 1800) {
return '下午';
}
return '晚上';
}
};
dayjs.locale(locale, null, true);
export default locale;
@@ -0,0 +1,53 @@
{
"name": "fastq",
"version": "1.19.1",
"description": "Fast, in memory work queue",
"main": "queue.js",
"scripts": {
"lint": "standard --verbose | snazzy",
"unit": "nyc --lines 100 --branches 100 --functions 100 --check-coverage --reporter=text tape test/test.js test/promise.js",
"coverage": "nyc --reporter=html --reporter=cobertura --reporter=text tape test/test.js test/promise.js",
"test:report": "npm run lint && npm run unit:report",
"test": "npm run lint && npm run unit",
"typescript": "tsc --project ./test/tsconfig.json",
"legacy": "tape test/test.js"
},
"pre-commit": [
"test",
"typescript"
],
"repository": {
"type": "git",
"url": "git+https://github.com/mcollina/fastq.git"
},
"keywords": [
"fast",
"queue",
"async",
"worker"
],
"author": "Matteo Collina <hello@matteocollina.com>",
"license": "ISC",
"bugs": {
"url": "https://github.com/mcollina/fastq/issues"
},
"homepage": "https://github.com/mcollina/fastq#readme",
"devDependencies": {
"async": "^3.1.0",
"neo-async": "^2.6.1",
"nyc": "^17.0.0",
"pre-commit": "^1.2.2",
"snazzy": "^9.0.0",
"standard": "^16.0.0",
"tape": "^5.0.0",
"typescript": "^5.0.4"
},
"dependencies": {
"reusify": "^1.0.4"
},
"standard": {
"ignore": [
"example.mjs"
]
}
}
@@ -0,0 +1,71 @@
import { CreateType } from '../create/type.mjs';
import { Discard } from '../discard/discard.mjs';
import { TransformKind } from '../symbols/symbols.mjs';
import { Computed } from '../computed/index.mjs';
import { Literal } from '../literal/index.mjs';
import { IndexPropertyKeys } from '../indexed/index.mjs';
import { Intersect } from '../intersect/index.mjs';
import { Union } from '../union/index.mjs';
import { Object } from '../object/index.mjs';
// ------------------------------------------------------------------
// Mapped
// ------------------------------------------------------------------
import { OmitFromMappedKey } from './omit-from-mapped-key.mjs';
import { OmitFromMappedResult } from './omit-from-mapped-result.mjs';
// ------------------------------------------------------------------
// TypeGuard
// ------------------------------------------------------------------
import { IsMappedKey, IsIntersect, IsUnion, IsObject, IsSchema, IsMappedResult, IsLiteralValue, IsRef } from '../guard/kind.mjs';
import { IsArray as IsArrayValue } from '../guard/value.mjs';
// prettier-ignore
function FromIntersect(types, propertyKeys) {
return types.map((type) => OmitResolve(type, propertyKeys));
}
// prettier-ignore
function FromUnion(types, propertyKeys) {
return types.map((type) => OmitResolve(type, propertyKeys));
}
// ------------------------------------------------------------------
// FromProperty
// ------------------------------------------------------------------
// prettier-ignore
function FromProperty(properties, key) {
const { [key]: _, ...R } = properties;
return R;
}
// prettier-ignore
function FromProperties(properties, propertyKeys) {
return propertyKeys.reduce((T, K2) => FromProperty(T, K2), properties);
}
// prettier-ignore
function FromObject(type, propertyKeys, properties) {
const options = Discard(type, [TransformKind, '$id', 'required', 'properties']);
const mappedProperties = FromProperties(properties, propertyKeys);
return Object(mappedProperties, options);
}
// prettier-ignore
function UnionFromPropertyKeys(propertyKeys) {
const result = propertyKeys.reduce((result, key) => IsLiteralValue(key) ? [...result, Literal(key)] : result, []);
return Union(result);
}
// prettier-ignore
function OmitResolve(type, propertyKeys) {
return (IsIntersect(type) ? Intersect(FromIntersect(type.allOf, propertyKeys)) :
IsUnion(type) ? Union(FromUnion(type.anyOf, propertyKeys)) :
IsObject(type) ? FromObject(type, propertyKeys, type.properties) :
Object({}));
}
/** `[Json]` Constructs a type whose keys are picked from the given type */
// prettier-ignore
export function Omit(type, key, options) {
const typeKey = IsArrayValue(key) ? UnionFromPropertyKeys(key) : key;
const propertyKeys = IsSchema(key) ? IndexPropertyKeys(key) : key;
const isTypeRef = IsRef(type);
const isKeyRef = IsRef(key);
return (IsMappedResult(type) ? OmitFromMappedResult(type, propertyKeys, options) :
IsMappedKey(key) ? OmitFromMappedKey(type, key, options) :
(isTypeRef && isKeyRef) ? Computed('Omit', [type, typeKey], options) :
(!isTypeRef && isKeyRef) ? Computed('Omit', [type, typeKey], options) :
(isTypeRef && !isKeyRef) ? Computed('Omit', [type, typeKey], options) :
CreateType({ ...OmitResolve(type, propertyKeys), ...options }));
}
@@ -0,0 +1,5 @@
function isObject(value) {
return {}.toString.call(value).includes('Object');
}
export { isObject as default };
@@ -0,0 +1,15 @@
#!/usr/bin/env node
/* eslint-disable no-var, unicorn/prefer-node-protocol */
var parser = require("..");
var fs = require("fs");
var filename = process.argv[2];
if (!filename) {
console.error("no filename specified");
} else {
var file = fs.readFileSync(filename, "utf8");
var ast = parser.parse(file);
console.log(JSON.stringify(ast, null, " "));
}
@@ -0,0 +1,259 @@
import { validateCertificatePath } from '../helpers/validateCertificatePath.js';
import { convertCertBufferToPEM } from '../helpers/convertCertBufferToPEM.js';
import { convertAAGUIDToString } from '../helpers/convertAAGUIDToString.js';
import { SettingsService } from './settingsService.js';
import { getLogger } from '../helpers/logging.js';
import { convertPEMToBytes } from '../helpers/convertPEMToBytes.js';
import { fetch } from '../helpers/fetch.js';
import { parseJWT } from '../metadata/parseJWT.js';
import { verifyJWT } from '../metadata/verifyJWT.js';
const defaultURLMDS = 'https://mds.fidoalliance.org/'; // v3
var SERVICE_STATE;
(function (SERVICE_STATE) {
SERVICE_STATE[SERVICE_STATE["DISABLED"] = 0] = "DISABLED";
SERVICE_STATE[SERVICE_STATE["REFRESHING"] = 1] = "REFRESHING";
SERVICE_STATE[SERVICE_STATE["READY"] = 2] = "READY";
})(SERVICE_STATE || (SERVICE_STATE = {}));
const log = getLogger('MetadataService');
/**
* An implementation of `MetadataService` that can download and parse BLOBs, and support on-demand
* requesting and caching of individual metadata statements.
*
* https://fidoalliance.org/metadata/
*/
export class BaseMetadataService {
constructor() {
Object.defineProperty(this, "mdsCache", {
enumerable: true,
configurable: true,
writable: true,
value: {}
});
Object.defineProperty(this, "statementCache", {
enumerable: true,
configurable: true,
writable: true,
value: {}
});
Object.defineProperty(this, "state", {
enumerable: true,
configurable: true,
writable: true,
value: SERVICE_STATE.DISABLED
});
Object.defineProperty(this, "verificationMode", {
enumerable: true,
configurable: true,
writable: true,
value: 'strict'
});
}
async initialize(opts = {}) {
const { mdsServers = [defaultURLMDS], statements, verificationMode } = opts;
this.setState(SERVICE_STATE.REFRESHING);
// If metadata statements are provided, load them into the cache first
if (statements?.length) {
let statementsAdded = 0;
statements.forEach((statement) => {
// Only cache statements that are for FIDO2-compatible authenticators
if (statement.aaguid) {
this.statementCache[statement.aaguid] = {
entry: {
metadataStatement: statement,
statusReports: [],
timeOfLastStatusChange: '1970-01-01',
},
url: '',
};
statementsAdded += 1;
}
});
log(`Cached ${statementsAdded} local statements`);
}
// If MDS servers are provided, then process them and add their statements to the cache
if (mdsServers?.length) {
// Get a current count so we know how many new statements we've added from MDS servers
const currentCacheCount = Object.keys(this.statementCache).length;
let numServers = mdsServers.length;
for (const url of mdsServers) {
try {
await this.downloadBlob({
url,
no: 0,
nextUpdate: new Date(0),
});
}
catch (err) {
// Notify of the error and move on
log(`Could not download BLOB from ${url}:`, err);
numServers -= 1;
}
}
// Calculate the difference to get the total number of new statements we successfully added
const newCacheCount = Object.keys(this.statementCache).length;
const cacheDiff = newCacheCount - currentCacheCount;
log(`Cached ${cacheDiff} statements from ${numServers} metadata server(s)`);
}
if (verificationMode) {
this.verificationMode = verificationMode;
}
this.setState(SERVICE_STATE.READY);
}
async getStatement(aaguid) {
if (this.state === SERVICE_STATE.DISABLED) {
return;
}
if (!aaguid) {
return;
}
if (aaguid instanceof Uint8Array) {
aaguid = convertAAGUIDToString(aaguid);
}
// If a cache refresh is in progress then pause this until the service is ready
await this.pauseUntilReady();
// Try to grab a cached statement
const cachedStatement = this.statementCache[aaguid];
if (!cachedStatement) {
if (this.verificationMode === 'strict') {
// FIDO conformance requires RP's to only support registered AAGUID's
throw new Error(`No metadata statement found for aaguid "${aaguid}"`);
}
// Allow registration verification to continue without using metadata
return;
}
// If the statement points to an MDS API, check the MDS' nextUpdate to see if we need to refresh
if (cachedStatement.url) {
const mds = this.mdsCache[cachedStatement.url];
const now = new Date();
if (now > mds.nextUpdate) {
try {
this.setState(SERVICE_STATE.REFRESHING);
await this.downloadBlob(mds);
}
finally {
this.setState(SERVICE_STATE.READY);
}
}
}
const { entry } = cachedStatement;
// Check to see if the this aaguid has a status report with a "compromised" status
for (const report of entry.statusReports) {
const { status } = report;
if (status === 'USER_VERIFICATION_BYPASS' ||
status === 'ATTESTATION_KEY_COMPROMISE' ||
status === 'USER_KEY_REMOTE_COMPROMISE' ||
status === 'USER_KEY_PHYSICAL_COMPROMISE') {
throw new Error(`Detected compromised aaguid "${aaguid}"`);
}
}
return entry.metadataStatement;
}
/**
* Download and process the latest BLOB from MDS
*/
async downloadBlob(mds) {
const { url, no } = mds;
// Get latest "BLOB" (FIDO's terminology, not mine)
const resp = await fetch(url);
const data = await resp.text();
// Parse the JWT
const parsedJWT = parseJWT(data);
const header = parsedJWT[0];
const payload = parsedJWT[1];
if (payload.no <= no) {
// From FIDO MDS docs: "also ignore the file if its number (no) is less or equal to the
// number of the last BLOB cached locally."
throw new Error(`Latest BLOB no. "${payload.no}" is not greater than previous ${no}`);
}
const headerCertsPEM = header.x5c.map(convertCertBufferToPEM);
try {
// Validate the certificate chain
const rootCerts = SettingsService.getRootCertificates({
identifier: 'mds',
});
await validateCertificatePath(headerCertsPEM, rootCerts);
}
catch (error) {
const _error = error;
// From FIDO MDS docs: "ignore the file if the chain cannot be verified or if one of the
// chain certificates is revoked"
throw new Error('BLOB certificate path could not be validated', { cause: _error });
}
// Verify the BLOB JWT signature
const leafCert = headerCertsPEM[0];
const verified = await verifyJWT(data, convertPEMToBytes(leafCert));
if (!verified) {
// From FIDO MDS docs: "The FIDO Server SHOULD ignore the file if the signature is invalid."
throw new Error('BLOB signature could not be verified');
}
// Cache statements for FIDO2 devices
for (const entry of payload.entries) {
// Only cache entries with an `aaguid`
if (entry.aaguid) {
this.statementCache[entry.aaguid] = { entry, url };
}
}
// Remember info about the server so we can refresh later
const [year, month, day] = payload.nextUpdate.split('-');
this.mdsCache[url] = {
...mds,
// Store the payload `no` to make sure we're getting the next BLOB in the sequence
no: payload.no,
// Convert the nextUpdate property into a Date so we can determine when to re-download
nextUpdate: new Date(parseInt(year, 10),
// Months need to be zero-indexed
parseInt(month, 10) - 1, parseInt(day, 10)),
};
}
/**
* A helper method to pause execution until the service is ready
*/
pauseUntilReady() {
if (this.state === SERVICE_STATE.READY) {
return new Promise((resolve) => {
resolve();
});
}
// State isn't ready, so set up polling
const readyPromise = new Promise((resolve, reject) => {
const totalTimeoutMS = 70000;
const intervalMS = 100;
let iterations = totalTimeoutMS / intervalMS;
// Check service state every `intervalMS` milliseconds
const intervalID = globalThis.setInterval(() => {
if (iterations < 1) {
clearInterval(intervalID);
reject(`State did not become ready in ${totalTimeoutMS / 1000} seconds`);
}
else if (this.state === SERVICE_STATE.READY) {
clearInterval(intervalID);
resolve();
}
iterations -= 1;
}, intervalMS);
});
return readyPromise;
}
/**
* Report service status on change
*/
setState(newState) {
this.state = newState;
if (newState === SERVICE_STATE.DISABLED) {
log('MetadataService is DISABLED');
}
else if (newState === SERVICE_STATE.REFRESHING) {
log('MetadataService is REFRESHING');
}
else if (newState === SERVICE_STATE.READY) {
log('MetadataService is READY');
}
}
}
/**
* A basic service for coordinating interactions with the FIDO Metadata Service. This includes BLOB
* download and parsing, and on-demand requesting and caching of individual metadata statements.
*
* https://fidoalliance.org/metadata/
*/
export const MetadataService = new BaseMetadataService();
@@ -0,0 +1,165 @@
import postcss from 'postcss'
import selectorParser from 'postcss-selector-parser'
import { flagEnabled } from '../featureFlags'
let getNode = {
id(node) {
return selectorParser.attribute({
attribute: 'id',
operator: '=',
value: node.value,
quoteMark: '"',
})
},
}
function minimumImpactSelector(nodes) {
let rest = nodes
.filter((node) => {
// Keep non-pseudo nodes
if (node.type !== 'pseudo') return true
// Keep pseudo nodes that have subnodes
// E.g.: `:not()` contains subnodes inside the parentheses
if (node.nodes.length > 0) return true
// Keep pseudo `elements`
// This implicitly means that we ignore pseudo `classes`
return (
node.value.startsWith('::') ||
[':before', ':after', ':first-line', ':first-letter'].includes(node.value)
)
})
.reverse()
let searchFor = new Set(['tag', 'class', 'id', 'attribute'])
let splitPointIdx = rest.findIndex((n) => searchFor.has(n.type))
if (splitPointIdx === -1) return rest.reverse().join('').trim()
let node = rest[splitPointIdx]
let bestNode = getNode[node.type] ? getNode[node.type](node) : node
rest = rest.slice(0, splitPointIdx)
let combinatorIdx = rest.findIndex((n) => n.type === 'combinator' && n.value === '>')
if (combinatorIdx !== -1) {
rest.splice(0, combinatorIdx)
rest.unshift(selectorParser.universal())
}
return [bestNode, ...rest.reverse()].join('').trim()
}
export let elementSelectorParser = selectorParser((selectors) => {
return selectors.map((s) => {
let nodes = s.split((n) => n.type === 'combinator' && n.value === ' ').pop()
return minimumImpactSelector(nodes)
})
})
let cache = new Map()
function extractElementSelector(selector) {
if (!cache.has(selector)) {
cache.set(selector, elementSelectorParser.transformSync(selector))
}
return cache.get(selector)
}
export default function resolveDefaultsAtRules({ tailwindConfig }) {
return (root) => {
let variableNodeMap = new Map()
/** @type {Set<import('postcss').AtRule>} */
let universals = new Set()
root.walkAtRules('defaults', (rule) => {
if (rule.nodes && rule.nodes.length > 0) {
universals.add(rule)
return
}
let variable = rule.params
if (!variableNodeMap.has(variable)) {
variableNodeMap.set(variable, new Set())
}
variableNodeMap.get(variable).add(rule.parent)
rule.remove()
})
if (flagEnabled(tailwindConfig, 'optimizeUniversalDefaults')) {
for (let universal of universals) {
/** @type {Map<string, Set<string>>} */
let selectorGroups = new Map()
let rules = variableNodeMap.get(universal.params) ?? []
for (let rule of rules) {
for (let selector of extractElementSelector(rule.selector)) {
// If selector contains a vendor prefix after a pseudo element or class,
// we consider them separately because merging the declarations into
// a single rule will cause browsers that do not understand the
// vendor prefix to throw out the whole rule
// Additionally if a selector contains `:has` we also consider
// it separately because FF only recently gained support for it
let selectorGroupName =
selector.includes(':-') || selector.includes('::-') || selector.includes(':has')
? selector
: '__DEFAULT__'
let selectors = selectorGroups.get(selectorGroupName) ?? new Set()
selectorGroups.set(selectorGroupName, selectors)
selectors.add(selector)
}
}
if (selectorGroups.size === 0) {
universal.remove()
continue
}
for (let [, selectors] of selectorGroups) {
let universalRule = postcss.rule({
source: universal.source,
})
universalRule.selectors = [...selectors]
universalRule.append(universal.nodes.map((node) => node.clone()))
universal.before(universalRule)
}
universal.remove()
}
} else if (universals.size) {
let universalRule = postcss.rule({
selectors: ['*', '::before', '::after'],
})
for (let universal of universals) {
universalRule.append(universal.nodes)
if (!universalRule.parent) {
universal.before(universalRule)
}
if (!universalRule.source) {
universalRule.source = universal.source
}
universal.remove()
}
let backdropRule = universalRule.clone({
selectors: ['::backdrop'],
})
universalRule.after(backdropRule)
}
}
}
@@ -0,0 +1,40 @@
{
"name": "@dnd-kit/core",
"version": "6.3.1",
"description": "dnd kit – a lightweight React library for building performant and accessible drag and drop experiences",
"author": "Claudéric Demers",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/clauderic/dnd-kit.git",
"directory": "packages/core"
},
"scripts": {
"start": "tsdx watch --tsconfig tsconfig.build.json --verbose --noClean",
"build": "tsdx build --tsconfig tsconfig.build.json",
"test": "tsdx test",
"lint": "tsdx lint",
"prepublish": "npm run build"
},
"main": "dist/index.js",
"module": "dist/core.esm.js",
"typings": "dist/index.d.ts",
"files": [
"README.md",
"CHANGELOG.md",
"LICENSE",
"dist"
],
"peerDependencies": {
"react": ">=16.8.0",
"react-dom": ">=16.8.0"
},
"dependencies": {
"tslib": "^2.0.0",
"@dnd-kit/accessibility": "^3.1.1",
"@dnd-kit/utilities": "^3.2.2"
},
"publishConfig": {
"access": "public"
}
}
@@ -0,0 +1,232 @@
/**
* @fileoverview Rule to flag no-unneeded-ternary
* @author Gyandeep Singh
*/
"use strict";
const astUtils = require("./utils/ast-utils");
// Operators that always result in a boolean value
const BOOLEAN_OPERATORS = new Set([
"==",
"===",
"!=",
"!==",
">",
">=",
"<",
"<=",
"in",
"instanceof",
]);
const OPERATOR_INVERSES = {
"==": "!=",
"!=": "==",
"===": "!==",
"!==": "===",
// Operators like < and >= are not true inverses, since both will return false with NaN.
};
const OR_PRECEDENCE = astUtils.getPrecedence({
type: "LogicalExpression",
operator: "||",
});
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../types').Rule.RuleModule} */
module.exports = {
meta: {
type: "suggestion",
defaultOptions: [{ defaultAssignment: true }],
docs: {
description:
"Disallow ternary operators when simpler alternatives exist",
recommended: false,
frozen: true,
url: "https://eslint.org/docs/latest/rules/no-unneeded-ternary",
},
schema: [
{
type: "object",
properties: {
defaultAssignment: {
type: "boolean",
},
},
additionalProperties: false,
},
],
fixable: "code",
messages: {
unnecessaryConditionalExpression:
"Unnecessary use of boolean literals in conditional expression.",
unnecessaryConditionalAssignment:
"Unnecessary use of conditional expression for default assignment.",
},
},
create(context) {
const [{ defaultAssignment }] = context.options;
const sourceCode = context.sourceCode;
/**
* Test if the node is a boolean literal
* @param {ASTNode} node The node to report.
* @returns {boolean} True if the its a boolean literal
* @private
*/
function isBooleanLiteral(node) {
return node.type === "Literal" && typeof node.value === "boolean";
}
/**
* Creates an expression that represents the boolean inverse of the expression represented by the original node
* @param {ASTNode} node A node representing an expression
* @returns {string} A string representing an inverted expression
*/
function invertExpression(node) {
if (
node.type === "BinaryExpression" &&
Object.hasOwn(OPERATOR_INVERSES, node.operator)
) {
const operatorToken = sourceCode.getFirstTokenBetween(
node.left,
node.right,
token => token.value === node.operator,
);
const text = sourceCode.getText();
return (
text.slice(node.range[0], operatorToken.range[0]) +
OPERATOR_INVERSES[node.operator] +
text.slice(operatorToken.range[1], node.range[1])
);
}
if (
astUtils.getPrecedence(node) <
astUtils.getPrecedence({ type: "UnaryExpression" })
) {
return `!(${astUtils.getParenthesisedText(sourceCode, node)})`;
}
return `!${astUtils.getParenthesisedText(sourceCode, node)}`;
}
/**
* Tests if a given node always evaluates to a boolean value
* @param {ASTNode} node An expression node
* @returns {boolean} True if it is determined that the node will always evaluate to a boolean value
*/
function isBooleanExpression(node) {
return (
(node.type === "BinaryExpression" &&
BOOLEAN_OPERATORS.has(node.operator)) ||
(node.type === "UnaryExpression" && node.operator === "!")
);
}
/**
* Test if the node matches the pattern id ? id : expression
* @param {ASTNode} node The ConditionalExpression to check.
* @returns {boolean} True if the pattern is matched, and false otherwise
* @private
*/
function matchesDefaultAssignment(node) {
return (
node.test.type === "Identifier" &&
node.consequent.type === "Identifier" &&
node.test.name === node.consequent.name
);
}
return {
ConditionalExpression(node) {
if (
isBooleanLiteral(node.alternate) &&
isBooleanLiteral(node.consequent)
) {
context.report({
node,
messageId: "unnecessaryConditionalExpression",
fix(fixer) {
if (
node.consequent.value === node.alternate.value
) {
// Replace `foo ? true : true` with just `true`, but don't replace `foo() ? true : true`
return node.test.type === "Identifier"
? fixer.replaceText(
node,
node.consequent.value.toString(),
)
: null;
}
if (node.alternate.value) {
// Replace `foo() ? false : true` with `!(foo())`
return fixer.replaceText(
node,
invertExpression(node.test),
);
}
// Replace `foo ? true : false` with `foo` if `foo` is guaranteed to be a boolean, or `!!foo` otherwise.
return fixer.replaceText(
node,
isBooleanExpression(node.test)
? astUtils.getParenthesisedText(
sourceCode,
node.test,
)
: `!${invertExpression(node.test)}`,
);
},
});
} else if (
!defaultAssignment &&
matchesDefaultAssignment(node)
) {
context.report({
node,
messageId: "unnecessaryConditionalAssignment",
fix(fixer) {
const shouldParenthesizeAlternate =
(astUtils.getPrecedence(node.alternate) <
OR_PRECEDENCE ||
astUtils.isCoalesceExpression(
node.alternate,
)) &&
!astUtils.isParenthesised(
sourceCode,
node.alternate,
);
const alternateText = shouldParenthesizeAlternate
? `(${sourceCode.getText(node.alternate)})`
: astUtils.getParenthesisedText(
sourceCode,
node.alternate,
);
const testText = astUtils.getParenthesisedText(
sourceCode,
node.test,
);
return fixer.replaceText(
node,
`${testText} || ${alternateText}`,
);
},
});
}
},
};
},
};
@@ -0,0 +1,76 @@
# jsx-a11y/no-noninteractive-element-to-interactive-role
💼 This rule is enabled in the following configs: ☑️ `recommended`, 🔒 `strict`.
<!-- end auto-generated rule header -->
Non-interactive HTML elements indicate _content_ and _containers_ in the user interface. Non-interactive elements include `<main>`, `<area>`, `<h1>` (,`<h2>`, etc), `<img>`, `<li>`, `<ul>` and `<ol>`.
Interactive HTML elements indicate _controls_ in the user interface. Interactive elements include `<a href>`, `<button>`, `<input>`, `<select>`, `<textarea>`.
[WAI-ARIA roles](https://www.w3.org/TR/wai-aria-1.1/#usage_intro) should not be used to convert a non-interactive element to an interactive element. Interactive ARIA roles include `button`, `link`, `checkbox`, `menuitem`, `menuitemcheckbox`, `menuitemradio`, `option`, `radio`, `searchbox`, `switch` and `textbox`.
## How do I resolve this error?
### Case: This element should be a control, like a button
Put the control inside the non-interactive container element.
```jsx
<li>
<div
role="button"
onClick={() => {}}
onKeyPress={() => {}}>
Save
</div>
</li>
```
Or wrap the content inside your interactive element.
```jsx
<div
role="button"
onClick={() => {}}
onKeyPress={() => {}}
tabIndex="0">
<img src="some/file.png" alt="Save" />
</div>
```
## Rule options
The recommended options for this rule allow several common interactive roles to be applied to a non-interactive element. The options are provided as an object keyed by HTML element name; the value is an array of interactive roles that are allowed on the specified element.
```js
{
'no-noninteractive-element-to-interactive-role': [
'error',
{
ul: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'],
ol: ['listbox', 'menu', 'menubar', 'radiogroup', 'tablist', 'tree', 'treegrid'],
li: ['menuitem', 'option', 'row', 'tab', 'treeitem'],
table: ['grid'],
td: ['gridcell'],
},
]
}
```
Under the recommended options, the following code is valid. It would be invalid under the strict rules.
```jsx
<ul role="menu" />
```
## Accessibility guidelines
- [WCAG 4.1.2](https://www.w3.org/WAI/WCAG21/Understanding/name-role-value)
### Resources
- [WAI-ARIA roles](https://www.w3.org/TR/wai-aria-1.1/#usage_intro)
- [WAI-ARIA Authoring Practices Guide - Design Patterns and Widgets](https://www.w3.org/TR/wai-aria-practices-1.1/#aria_ex)
- [Fundamental Keyboard Navigation Conventions](https://www.w3.org/TR/wai-aria-practices-1.1/#kbd_generalnav)
- [Mozilla Developer Network - ARIA Techniques](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_button_role#Keyboard_and_focus)
@@ -0,0 +1,73 @@
{
"name": "tinyglobby",
"version": "0.2.15",
"description": "A fast and minimal alternative to globby and fast-glob",
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.cts",
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./package.json": "./package.json"
},
"sideEffects": false,
"files": [
"dist"
],
"author": "Superchupu",
"license": "MIT",
"keywords": [
"glob",
"patterns",
"fast",
"implementation"
],
"repository": {
"type": "git",
"url": "git+https://github.com/SuperchupuDev/tinyglobby.git"
},
"bugs": {
"url": "https://github.com/SuperchupuDev/tinyglobby/issues"
},
"homepage": "https://superchupu.dev/tinyglobby",
"funding": {
"url": "https://github.com/sponsors/SuperchupuDev"
},
"dependencies": {
"fdir": "^6.5.0",
"picomatch": "^4.0.3"
},
"devDependencies": {
"@biomejs/biome": "^2.2.3",
"@types/node": "^24.3.1",
"@types/picomatch": "^4.0.2",
"fast-glob": "^3.3.3",
"fs-fixture": "^2.8.1",
"glob": "^11.0.3",
"tinybench": "^5.0.1",
"tsdown": "^0.14.2",
"typescript": "^5.9.2"
},
"engines": {
"node": ">=12.0.0"
},
"publishConfig": {
"provenance": true
},
"scripts": {
"bench": "node benchmark/bench.ts",
"bench:setup": "node benchmark/setup.ts",
"build": "tsdown",
"check": "biome check",
"check:fix": "biome check --write --unsafe",
"format": "biome format --write",
"lint": "biome lint",
"test": "node --test \"test/**/*.ts\"",
"test:coverage": "node --test --experimental-test-coverage \"test/**/*.ts\"",
"test:only": "node --test --test-only \"test/**/*.ts\"",
"typecheck": "tsc --noEmit"
}
}
@@ -0,0 +1,87 @@
/* Hand-written tokenizers for JavaScript tokens that can't be
expressed by lezer's built-in tokenizer. */
import {ExternalTokenizer, ContextTracker} from "@lezer/lr"
import {insertSemi, noSemi, noSemiType, incdec, incdecPrefix, questionDot,
spaces, newline, BlockComment, LineComment,
JSXStartTag, Dialect_jsx} from "./parser.terms.js"
const space = [9, 10, 11, 12, 13, 32, 133, 160, 5760, 8192, 8193, 8194, 8195, 8196, 8197, 8198, 8199, 8200,
8201, 8202, 8232, 8233, 8239, 8287, 12288]
const braceR = 125, semicolon = 59, slash = 47, star = 42, plus = 43, minus = 45, lt = 60, comma = 44,
question = 63, dot = 46, bracketL = 91
export const trackNewline = new ContextTracker({
start: false,
shift(context, term) {
return term == LineComment || term == BlockComment || term == spaces ? context : term == newline
},
strict: false
})
export const insertSemicolon = new ExternalTokenizer((input, stack) => {
let {next} = input
if (next == braceR || next == -1 || stack.context)
input.acceptToken(insertSemi)
}, {contextual: true, fallback: true})
export const noSemicolon = new ExternalTokenizer((input, stack) => {
let {next} = input, after
if (space.indexOf(next) > -1) return
if (next == slash && ((after = input.peek(1)) == slash || after == star)) return
if (next != braceR && next != semicolon && next != -1 && !stack.context)
input.acceptToken(noSemi)
}, {contextual: true})
export const noSemicolonType = new ExternalTokenizer((input, stack) => {
if (input.next == bracketL && !stack.context) input.acceptToken(noSemiType)
}, {contextual: true})
export const operatorToken = new ExternalTokenizer((input, stack) => {
let {next} = input
if (next == plus || next == minus) {
input.advance()
if (next == input.next) {
input.advance()
let mayPostfix = !stack.context && stack.canShift(incdec)
input.acceptToken(mayPostfix ? incdec : incdecPrefix)
}
} else if (next == question && input.peek(1) == dot) {
input.advance(); input.advance()
if (input.next < 48 || input.next > 57) // No digit after
input.acceptToken(questionDot)
}
}, {contextual: true})
function identifierChar(ch, start) {
return ch >= 65 && ch <= 90 || ch >= 97 && ch <= 122 || ch == 95 || ch >= 192 ||
!start && ch >= 48 && ch <= 57
}
export const jsx = new ExternalTokenizer((input, stack) => {
if (input.next != lt || !stack.dialectEnabled(Dialect_jsx)) return
input.advance()
if (input.next == slash) return
// Scan for an identifier followed by a comma or 'extends', don't
// treat this as a start tag if present.
let back = 0
while (space.indexOf(input.next) > -1) { input.advance(); back++ }
if (identifierChar(input.next, true)) {
input.advance()
back++
while (identifierChar(input.next, false)) { input.advance(); back++ }
while (space.indexOf(input.next) > -1) { input.advance(); back++ }
if (input.next == comma) return
for (let i = 0;; i++) {
if (i == 7) {
if (!identifierChar(input.next, true)) return
break
}
if (input.next != "extends".charCodeAt(i)) break
input.advance()
back++
}
}
input.acceptToken(JSXStartTag, -back)
})
@@ -0,0 +1,13 @@
export * as core from "../core/index.cjs";
export * from "./schemas.cjs";
export * from "./checks.cjs";
export * from "./errors.cjs";
export * from "./parse.cjs";
export * from "./compat.cjs";
export type { infer, output, input } from "../core/index.cjs";
export { globalRegistry, type GlobalMeta, registry, config, function, $output, $input, $brand, clone, regexes, treeifyError, prettifyError, formatError, flattenError, toJSONSchema, TimePrecision, NEVER, } from "../core/index.cjs";
export * as locales from "../locales/index.cjs";
export { ZodISODateTime, ZodISODate, ZodISOTime, ZodISODuration } from "./iso.cjs";
export * as iso from "./iso.cjs";
export type { ZodCoercedString, ZodCoercedNumber, ZodCoercedBigInt, ZodCoercedBoolean, ZodCoercedDate, } from "./coerce.cjs";
export * as coerce from "./coerce.cjs";
@@ -0,0 +1,3 @@
declare const _exports: import('eslint').Rule.RuleModule;
export = _exports;
//# sourceMappingURL=forbid-foreign-prop-types.d.ts.map
@@ -0,0 +1,445 @@
/**
* @import {
* Construct,
* ContainerState,
* InitialConstruct,
* Initializer,
* Point,
* State,
* TokenizeContext,
* Tokenizer,
* Token
* } from 'micromark-util-types'
*/
/**
* @typedef {[Construct, ContainerState]} StackItem
* Construct and its state.
*/
import {ok as assert} from 'devlop'
import {factorySpace} from 'micromark-factory-space'
import {markdownLineEnding} from 'micromark-util-character'
import {splice} from 'micromark-util-chunked'
import {codes, constants, types} from 'micromark-util-symbol'
/** @type {InitialConstruct} */
export const document = {tokenize: initializeDocument}
/** @type {Construct} */
const containerConstruct = {tokenize: tokenizeContainer}
/**
* @this {TokenizeContext}
* Self.
* @type {Initializer}
* Initializer.
*/
function initializeDocument(effects) {
const self = this
/** @type {Array<StackItem>} */
const stack = []
let continued = 0
/** @type {TokenizeContext | undefined} */
let childFlow
/** @type {Token | undefined} */
let childToken
/** @type {number} */
let lineStartOffset
return start
/** @type {State} */
function start(code) {
// First we iterate through the open blocks, starting with the root
// document, and descending through last children down to the last open
// block.
// Each block imposes a condition that the line must satisfy if the block is
// to remain open.
// For example, a block quote requires a `>` character.
// A paragraph requires a non-blank line.
// In this phase we may match all or just some of the open blocks.
// But we cannot close unmatched blocks yet, because we may have a lazy
// continuation line.
if (continued < stack.length) {
const item = stack[continued]
self.containerState = item[1]
assert(
item[0].continuation,
'expected `continuation` to be defined on container construct'
)
return effects.attempt(
item[0].continuation,
documentContinue,
checkNewContainers
)(code)
}
// Done.
return checkNewContainers(code)
}
/** @type {State} */
function documentContinue(code) {
assert(
self.containerState,
'expected `containerState` to be defined after continuation'
)
continued++
// Note: this field is called `_closeFlow` but it also closes containers.
// Perhaps a good idea to rename it but it’s already used in the wild by
// extensions.
if (self.containerState._closeFlow) {
self.containerState._closeFlow = undefined
if (childFlow) {
closeFlow()
}
// Note: this algorithm for moving events around is similar to the
// algorithm when dealing with lazy lines in `writeToChild`.
const indexBeforeExits = self.events.length
let indexBeforeFlow = indexBeforeExits
/** @type {Point | undefined} */
let point
// Find the flow chunk.
while (indexBeforeFlow--) {
if (
self.events[indexBeforeFlow][0] === 'exit' &&
self.events[indexBeforeFlow][1].type === types.chunkFlow
) {
point = self.events[indexBeforeFlow][1].end
break
}
}
assert(point, 'could not find previous flow chunk')
exitContainers(continued)
// Fix positions.
let index = indexBeforeExits
while (index < self.events.length) {
self.events[index][1].end = {...point}
index++
}
// Inject the exits earlier (they’re still also at the end).
splice(
self.events,
indexBeforeFlow + 1,
0,
self.events.slice(indexBeforeExits)
)
// Discard the duplicate exits.
self.events.length = index
return checkNewContainers(code)
}
return start(code)
}
/** @type {State} */
function checkNewContainers(code) {
// Next, after consuming the continuation markers for existing blocks, we
// look for new block starts (e.g. `>` for a block quote).
// If we encounter a new block start, we close any blocks unmatched in
// step 1 before creating the new block as a child of the last matched
// block.
if (continued === stack.length) {
// No need to `check` whether there’s a container, of `exitContainers`
// would be moot.
// We can instead immediately `attempt` to parse one.
if (!childFlow) {
return documentContinued(code)
}
// If we have concrete content, such as block HTML or fenced code,
// we can’t have containers “pierce” into them, so we can immediately
// start.
if (childFlow.currentConstruct && childFlow.currentConstruct.concrete) {
return flowStart(code)
}
// If we do have flow, it could still be a blank line,
// but we’d be interrupting it w/ a new container if there’s a current
// construct.
// To do: next major: remove `_gfmTableDynamicInterruptHack` (no longer
// needed in micromark-extension-gfm-table@1.0.6).
self.interrupt = Boolean(
childFlow.currentConstruct && !childFlow._gfmTableDynamicInterruptHack
)
}
// Check if there is a new container.
self.containerState = {}
return effects.check(
containerConstruct,
thereIsANewContainer,
thereIsNoNewContainer
)(code)
}
/** @type {State} */
function thereIsANewContainer(code) {
if (childFlow) closeFlow()
exitContainers(continued)
return documentContinued(code)
}
/** @type {State} */
function thereIsNoNewContainer(code) {
self.parser.lazy[self.now().line] = continued !== stack.length
lineStartOffset = self.now().offset
return flowStart(code)
}
/** @type {State} */
function documentContinued(code) {
// Try new containers.
self.containerState = {}
return effects.attempt(
containerConstruct,
containerContinue,
flowStart
)(code)
}
/** @type {State} */
function containerContinue(code) {
assert(
self.currentConstruct,
'expected `currentConstruct` to be defined on tokenizer'
)
assert(
self.containerState,
'expected `containerState` to be defined on tokenizer'
)
continued++
stack.push([self.currentConstruct, self.containerState])
// Try another.
return documentContinued(code)
}
/** @type {State} */
function flowStart(code) {
if (code === codes.eof) {
if (childFlow) closeFlow()
exitContainers(0)
effects.consume(code)
return
}
childFlow = childFlow || self.parser.flow(self.now())
effects.enter(types.chunkFlow, {
_tokenizer: childFlow,
contentType: constants.contentTypeFlow,
previous: childToken
})
return flowContinue(code)
}
/** @type {State} */
function flowContinue(code) {
if (code === codes.eof) {
writeToChild(effects.exit(types.chunkFlow), true)
exitContainers(0)
effects.consume(code)
return
}
if (markdownLineEnding(code)) {
effects.consume(code)
writeToChild(effects.exit(types.chunkFlow))
// Get ready for the next line.
continued = 0
self.interrupt = undefined
return start
}
effects.consume(code)
return flowContinue
}
/**
* @param {Token} token
* Token.
* @param {boolean | undefined} [endOfFile]
* Whether the token is at the end of the file (default: `false`).
* @returns {undefined}
* Nothing.
*/
function writeToChild(token, endOfFile) {
assert(childFlow, 'expected `childFlow` to be defined when continuing')
const stream = self.sliceStream(token)
if (endOfFile) stream.push(null)
token.previous = childToken
if (childToken) childToken.next = token
childToken = token
childFlow.defineSkip(token.start)
childFlow.write(stream)
// Alright, so we just added a lazy line:
//
// ```markdown
// > a
// b.
//
// Or:
//
// > ~~~c
// d
//
// Or:
//
// > | e |
// f
// ```
//
// The construct in the second example (fenced code) does not accept lazy
// lines, so it marked itself as done at the end of its first line, and
// then the content construct parses `d`.
// Most constructs in markdown match on the first line: if the first line
// forms a construct, a non-lazy line can’t “unmake” it.
//
// The construct in the third example is potentially a GFM table, and
// those are *weird*.
// It *could* be a table, from the first line, if the following line
// matches a condition.
// In this case, that second line is lazy, which “unmakes” the first line
// and turns the whole into one content block.
//
// We’ve now parsed the non-lazy and the lazy line, and can figure out
// whether the lazy line started a new flow block.
// If it did, we exit the current containers between the two flow blocks.
if (self.parser.lazy[token.start.line]) {
let index = childFlow.events.length
while (index--) {
if (
// The token starts before the line ending…
childFlow.events[index][1].start.offset < lineStartOffset &&
// …and either is not ended yet…
(!childFlow.events[index][1].end ||
// …or ends after it.
childFlow.events[index][1].end.offset > lineStartOffset)
) {
// Exit: there’s still something open, which means it’s a lazy line
// part of something.
return
}
}
// Note: this algorithm for moving events around is similar to the
// algorithm when closing flow in `documentContinue`.
const indexBeforeExits = self.events.length
let indexBeforeFlow = indexBeforeExits
/** @type {boolean | undefined} */
let seen
/** @type {Point | undefined} */
let point
// Find the previous chunk (the one before the lazy line).
while (indexBeforeFlow--) {
if (
self.events[indexBeforeFlow][0] === 'exit' &&
self.events[indexBeforeFlow][1].type === types.chunkFlow
) {
if (seen) {
point = self.events[indexBeforeFlow][1].end
break
}
seen = true
}
}
assert(point, 'could not find previous flow chunk')
exitContainers(continued)
// Fix positions.
index = indexBeforeExits
while (index < self.events.length) {
self.events[index][1].end = {...point}
index++
}
// Inject the exits earlier (they’re still also at the end).
splice(
self.events,
indexBeforeFlow + 1,
0,
self.events.slice(indexBeforeExits)
)
// Discard the duplicate exits.
self.events.length = index
}
}
/**
* @param {number} size
* Size.
* @returns {undefined}
* Nothing.
*/
function exitContainers(size) {
let index = stack.length
// Exit open containers.
while (index-- > size) {
const entry = stack[index]
self.containerState = entry[1]
assert(
entry[0].exit,
'expected `exit` to be defined on container construct'
)
entry[0].exit.call(self, effects)
}
stack.length = size
}
function closeFlow() {
assert(
self.containerState,
'expected `containerState` to be defined when closing flow'
)
assert(childFlow, 'expected `childFlow` to be defined when closing it')
childFlow.write([codes.eof])
childToken = undefined
childFlow = undefined
self.containerState._closeFlow = undefined
}
}
/**
* @this {TokenizeContext}
* Context.
* @type {Tokenizer}
* Tokenizer.
*/
function tokenizeContainer(effects, ok, nok) {
// Always populated by defaults.
assert(
this.parser.constructs.disable.null,
'expected `disable.null` to be populated'
)
return factorySpace(
effects,
effects.attempt(this.parser.constructs.document, ok, nok),
types.linePrefix,
this.parser.constructs.disable.null.includes('codeIndented')
? undefined
: constants.tabSize
)
}
@@ -0,0 +1 @@
{"version":3,"file":"break.js","names":["EmbedBlot","Break","value","undefined","optimize","prev","next","remove","length","blotName","tagName"],"sources":["../../src/blots/break.ts"],"sourcesContent":["import { EmbedBlot } from 'parchment';\n\nclass Break extends EmbedBlot {\n static value() {\n return undefined;\n }\n\n optimize() {\n if (this.prev || this.next) {\n this.remove();\n }\n }\n\n length() {\n return 0;\n }\n\n value() {\n return '';\n }\n}\nBreak.blotName = 'break';\nBreak.tagName = 'BR';\n\nexport default Break;\n"],"mappings":"AAAA,SAASA,SAAS,QAAQ,WAAW;AAErC,MAAMC,KAAK,SAASD,SAAS,CAAC;EAC5B,OAAOE,KAAKA,CAAA,EAAG;IACb,OAAOC,SAAS;EAClB;EAEAC,QAAQA,CAAA,EAAG;IACT,IAAI,IAAI,CAACC,IAAI,IAAI,IAAI,CAACC,IAAI,EAAE;MAC1B,IAAI,CAACC,MAAM,CAAC,CAAC;IACf;EACF;EAEAC,MAAMA,CAAA,EAAG;IACP,OAAO,CAAC;EACV;EAEAN,KAAKA,CAAA,EAAG;IACN,OAAO,EAAE;EACX;AACF;AACAD,KAAK,CAACQ,QAAQ,GAAG,OAAO;AACxBR,KAAK,CAACS,OAAO,GAAG,IAAI;AAEpB,eAAeT,KAAK","ignoreList":[]}
@@ -0,0 +1,33 @@
export declare const napCatVersion: string;
export interface SemVerInfo {
valid: boolean;
normalized: string;
major: number;
minor: number;
patch: number;
prerelease: string | null;
buildmetadata: string | null;
}
/**
* 解析并验证版本号是否符合 SemVer 2.0 规范
* @param version - 版本字符串 (支持 v 前缀)
* @returns SemVer 解析结果
*/
export declare function parseSemVer(version: string | undefined | null): SemVerInfo;
/**
* 验证版本号是否符合 SemVer 2.0 规范
* @param version - 版本字符串
* @returns 是否有效
*/
export declare function isValidSemVer(version: string | undefined | null): boolean;
/**
* 比较两个 SemVer 版本号
* @param v1 - 版本号1
* @param v2 - 版本号2
* @returns -1 (v1 < v2), 0 (v1 == v2), 1 (v1 > v2)
*/
export declare function compareSemVer(v1: string, v2: string): -1 | 0 | 1;
/**
* 获取解析后的当前版本信息
*/
export declare const napCatVersionInfo: SemVerInfo;
@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isClassProvider = void 0;
function isClassProvider(provider) {
return !!provider.useClass;
}
exports.isClassProvider = isClassProvider;
@@ -0,0 +1,6 @@
import type { ParseSettings } from '../parseSettings';
import type { ASTAndDefiniteProgram } from './shared';
/**
* @returns Returns a new source file and program corresponding to the linted code
*/
export declare function createIsolatedProgram(parseSettings: ParseSettings): ASTAndDefiniteProgram;
@@ -0,0 +1 @@
{"mappings":";AAAA,4BAAiB;IAAG,oBAAoB,CAAC,4eAAoF,CAAC;AAC9H","sources":["packages/@react-aria/menu/intl/uk-UA.json"],"sourcesContent":["{\n \"longPressMessage\": \"Довго або звичайно натисніть комбінацію клавіш Alt і стрілка вниз, щоб відкрити меню\"\n}\n"],"names":[],"version":3,"file":"uk-UA.module.js.map"}
@@ -0,0 +1,6 @@
import type { TSESTree } from '../ts-estree';
export declare const LINEBREAK_MATCHER: RegExp;
/**
* Determines whether two adjacent tokens are on the same line
*/
export declare function isTokenOnSameLine(left: TSESTree.Node | TSESTree.Token, right: TSESTree.Node | TSESTree.Token): boolean;
@@ -0,0 +1 @@
{"mappings":";;;;AAAA;;;;;;;;;;CAUC","sources":["packages/@react-stately/list/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 */\n\nexport type {ListProps, ListState} from './useListState';\nexport type {SingleSelectListProps, SingleSelectListState} from './useSingleSelectListState';\nexport {useListState, UNSTABLE_useFilteredListState} from './useListState';\nexport {useSingleSelectListState} from './useSingleSelectListState';\nexport {ListCollection} from './ListCollection';\n"],"names":[],"version":3,"file":"module.js.map"}
@@ -0,0 +1 @@
{"name":"espree","version":"10.4.0","requiresBuild":false,"files":{"LICENSE":{"checkedAt":1794532093107,"integrity":"sha512-+FMQwEtTjvl+z8BRPdoRPoVowma+EWpWjZ5RBKtK2wIqcYsGNuzumqk6k5cDvASNavxtPZS71/PEVZhhOq1SBw==","mode":420,"size":1322},"dist/espree.cjs":{"checkedAt":1794532093107,"integrity":"sha512-4obpM7CAuRDNlOngrAoER+nmi5Ov+OfaZs1ISP+P/18GRudcOh/PbyvMRB8vPBzBITdbQ4RVWxWkrKURoluDKQ==","mode":420,"size":31219},"espree.js":{"checkedAt":1794532093107,"integrity":"sha512-4IPLpwgkQny4RnOKnGYXhkXfS0hd4OkTM0e1o4NKGD8h6pdQgTqmSgLPVr4Rj8KUrq/XbrR/ZOcPAFCY/6N3Dg==","mode":420,"size":6399},"lib/espree.js":{"checkedAt":1794532093107,"integrity":"sha512-N5ecVGppj1DXUKdvTza+OuwmcPj+beyWMczUMgMsFFFGkMFJHhIaqQoQX4tj5W1KBDFhIxSQgrsiaDh+cFMCLQ==","mode":420,"size":12137},"lib/features.js":{"checkedAt":1794532093108,"integrity":"sha512-W4cul6kH98/a7xQyMOWVziny4L49ASfGL/YdwbpGF+WG9TypyAbaADmOU8jGgVxk7nKOvyhXZ4iQTREXiSvxow==","mode":420,"size":696},"lib/options.js":{"checkedAt":1794532093108,"integrity":"sha512-0I9uuuZ/qft7YV6WCL+io7nIcCQZbwgwxb9kNLFDyMqmj2zWjI3spefULyAkE4WdLMPgsLLjMsUUvZ1Okj1B7Q==","mode":420,"size":3886},"lib/token-translator.js":{"checkedAt":1794532093108,"integrity":"sha512-o8q6vMbC1BXiOQZJCPpOFsyn7a87+gWUoorpi+ujjduoa/yM3EE573At4qpYVMRwjpUSb1q+gMUdNrDsjrRRJQ==","mode":420,"size":8103},"lib/version.js":{"checkedAt":1794532093108,"integrity":"sha512-PG6LTrsBj09TgVUx7QQRe4UpI+ks/FSSrYfjw+iwHV/ZE2EXYG9mKtrA+3xAASFm3153sTInMvoaddopgTeUUA==","mode":420,"size":51},"package.json":{"checkedAt":1794532093108,"integrity":"sha512-bduRuJJcpnNOtWvdkAYcRUvucdjlDFOWj/+J4Y60h9Ghw4sPdYMxb/JbEyqIvVFY8qQgOMOSZI+danqD3V/KoA==","mode":420,"size":2314},"README.md":{"checkedAt":1794532093109,"integrity":"sha512-ildlxKiL9Qe9GnMB1ZxLpl/j6HuyNU4dN8T8bA39GhXWzxvcqXsoF0DS38/19cgEGazAWXRzQ3traV5/FORdTw==","mode":420,"size":14256}}}
@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAAA,qDAA8D;AAArD,wGAAA,YAAY,OAAW;AAIhC,qDAAkD;AAAzC,4GAAA,WAAW,OAAA;AAEpB,6CAA6C;AAApC,uGAAA,UAAU,OAAA;AAEnB,2DAAwD;AAA/C,kHAAA,cAAc,OAAA;AAEvB,mCAA8C;AAArC,wGAAA,gBAAgB,OAAA"}
@@ -0,0 +1 @@
{"mappings":"AAAA,iBAAiB;IAAG,kBAAkB,CAAC,OAAS,CAAC,yBAAI,EAAE,KAAK,IAAI,CAAC,QAAC,CAAC;IACjE,qBAAqB,CAAC,gFAAU,CAAC;IACjC,UAAU,CAAC,gBAAE,CAAC;IACd,eAAe,CAAC,gEAAQ,CAAC;IACzB,iBAAiB,CAAC,MAAM,YAAc,GAAG,UAAU,MAAM,CAAC,KAAK,KAAK,EAAE;YAAC,MAAM,CAAC,wCAAK,CAAC;YAAE,KAAK,IAAM,CAAC,yBAAI,EAAE,UAAU,MAAM,CAAC,KAAK,KAAK,EAAE,yBAAI,CAAC;YAAE,OAAO,IAAM,CAAC,yBAAI,EAAE,UAAU,MAAM,CAAC,KAAK,KAAK,EAAE,yBAAI,CAAC;QAAA,GAAG,QAAC,CAAC;IACvM,gBAAgB,CAAC,OAAS,CAAC,yBAAI,EAAE,KAAK,IAAI,CAAC,QAAC,CAAC;AAC/C","sources":["packages/@react-aria/grid/intl/zh-CN.json"],"sourcesContent":["{\n \"deselectedItem\": \"未选择 {item}。\",\n \"longPressToSelect\": \"长按以进入选择模式。\",\n \"select\": \"选择\",\n \"selectedAll\": \"已选择所有项目。\",\n \"selectedCount\": \"{count, plural, =0 {未选择项目} one {已选择 # 个项目} other {已选择 # 个项目}}。\",\n \"selectedItem\": \"已选择 {item}。\"\n}\n"],"names":[],"version":3,"file":"zh-CN.main.js.map"}
@@ -0,0 +1,432 @@
"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, {
__DO_NOT_USE__ActionTypes: () => actionTypes_default,
applyMiddleware: () => applyMiddleware,
bindActionCreators: () => bindActionCreators,
combineReducers: () => combineReducers,
compose: () => compose,
createStore: () => createStore,
isAction: () => isAction,
isPlainObject: () => isPlainObject,
legacy_createStore: () => legacy_createStore
});
module.exports = __toCommonJS(src_exports);
// src/utils/formatProdErrorMessage.ts
function formatProdErrorMessage(code) {
return `Minified Redux error #${code}; visit https://redux.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
}
// src/utils/symbol-observable.ts
var $$observable = /* @__PURE__ */ (() => typeof Symbol === "function" && Symbol.observable || "@@observable")();
var symbol_observable_default = $$observable;
// src/utils/actionTypes.ts
var randomString = () => Math.random().toString(36).substring(7).split("").join(".");
var ActionTypes = {
INIT: `@@redux/INIT${/* @__PURE__ */ randomString()}`,
REPLACE: `@@redux/REPLACE${/* @__PURE__ */ randomString()}`,
PROBE_UNKNOWN_ACTION: () => `@@redux/PROBE_UNKNOWN_ACTION${randomString()}`
};
var actionTypes_default = ActionTypes;
// src/utils/isPlainObject.ts
function isPlainObject(obj) {
if (typeof obj !== "object" || obj === null)
return false;
let proto = obj;
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto);
}
return Object.getPrototypeOf(obj) === proto || Object.getPrototypeOf(obj) === null;
}
// src/utils/kindOf.ts
function miniKindOf(val) {
if (val === void 0)
return "undefined";
if (val === null)
return "null";
const type = typeof val;
switch (type) {
case "boolean":
case "string":
case "number":
case "symbol":
case "function": {
return type;
}
}
if (Array.isArray(val))
return "array";
if (isDate(val))
return "date";
if (isError(val))
return "error";
const constructorName = ctorName(val);
switch (constructorName) {
case "Symbol":
case "Promise":
case "WeakMap":
case "WeakSet":
case "Map":
case "Set":
return constructorName;
}
return Object.prototype.toString.call(val).slice(8, -1).toLowerCase().replace(/\s/g, "");
}
function ctorName(val) {
return typeof val.constructor === "function" ? val.constructor.name : null;
}
function isError(val) {
return val instanceof Error || typeof val.message === "string" && val.constructor && typeof val.constructor.stackTraceLimit === "number";
}
function isDate(val) {
if (val instanceof Date)
return true;
return typeof val.toDateString === "function" && typeof val.getDate === "function" && typeof val.setDate === "function";
}
function kindOf(val) {
let typeOfVal = typeof val;
if (process.env.NODE_ENV !== "production") {
typeOfVal = miniKindOf(val);
}
return typeOfVal;
}
// src/createStore.ts
function createStore(reducer, preloadedState, enhancer) {
if (typeof reducer !== "function") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(2) : `Expected the root reducer to be a function. Instead, received: '${kindOf(reducer)}'`);
}
if (typeof preloadedState === "function" && typeof enhancer === "function" || typeof enhancer === "function" && typeof arguments[3] === "function") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(0) : "It looks like you are passing several store enhancers to createStore(). This is not supported. Instead, compose them together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.");
}
if (typeof preloadedState === "function" && typeof enhancer === "undefined") {
enhancer = preloadedState;
preloadedState = void 0;
}
if (typeof enhancer !== "undefined") {
if (typeof enhancer !== "function") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(1) : `Expected the enhancer to be a function. Instead, received: '${kindOf(enhancer)}'`);
}
return enhancer(createStore)(reducer, preloadedState);
}
let currentReducer = reducer;
let currentState = preloadedState;
let currentListeners = /* @__PURE__ */ new Map();
let nextListeners = currentListeners;
let listenerIdCounter = 0;
let isDispatching = false;
function ensureCanMutateNextListeners() {
if (nextListeners === currentListeners) {
nextListeners = /* @__PURE__ */ new Map();
currentListeners.forEach((listener, key) => {
nextListeners.set(key, listener);
});
}
}
function getState() {
if (isDispatching) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(3) : "You may not call store.getState() while the reducer is executing. The reducer has already received the state as an argument. Pass it down from the top reducer instead of reading it from the store.");
}
return currentState;
}
function subscribe(listener) {
if (typeof listener !== "function") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(4) : `Expected the listener to be a function. Instead, received: '${kindOf(listener)}'`);
}
if (isDispatching) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(5) : "You may not call store.subscribe() while the reducer is executing. If you would like to be notified after the store has been updated, subscribe from a component and invoke store.getState() in the callback to access the latest state. See https://redux.js.org/api/store#subscribelistener for more details.");
}
let isSubscribed = true;
ensureCanMutateNextListeners();
const listenerId = listenerIdCounter++;
nextListeners.set(listenerId, listener);
return function unsubscribe() {
if (!isSubscribed) {
return;
}
if (isDispatching) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(6) : "You may not unsubscribe from a store listener while the reducer is executing. See https://redux.js.org/api/store#subscribelistener for more details.");
}
isSubscribed = false;
ensureCanMutateNextListeners();
nextListeners.delete(listenerId);
currentListeners = null;
};
}
function dispatch(action) {
if (!isPlainObject(action)) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(7) : `Actions must be plain objects. Instead, the actual type was: '${kindOf(action)}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`);
}
if (typeof action.type === "undefined") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(8) : 'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.');
}
if (typeof action.type !== "string") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(17) : `Action "type" property must be a string. Instead, the actual type was: '${kindOf(action.type)}'. Value was: '${action.type}' (stringified)`);
}
if (isDispatching) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(9) : "Reducers may not dispatch actions.");
}
try {
isDispatching = true;
currentState = currentReducer(currentState, action);
} finally {
isDispatching = false;
}
const listeners = currentListeners = nextListeners;
listeners.forEach((listener) => {
listener();
});
return action;
}
function replaceReducer(nextReducer) {
if (typeof nextReducer !== "function") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(10) : `Expected the nextReducer to be a function. Instead, received: '${kindOf(nextReducer)}`);
}
currentReducer = nextReducer;
dispatch({
type: actionTypes_default.REPLACE
});
}
function observable() {
const outerSubscribe = subscribe;
return {
/**
* The minimal observable subscription method.
* @param observer Any object that can be used as an observer.
* The observer object should have a `next` method.
* @returns An object with an `unsubscribe` method that can
* be used to unsubscribe the observable from the store, and prevent further
* emission of values from the observable.
*/
subscribe(observer) {
if (typeof observer !== "object" || observer === null) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(11) : `Expected the observer to be an object. Instead, received: '${kindOf(observer)}'`);
}
function observeState() {
const observerAsObserver = observer;
if (observerAsObserver.next) {
observerAsObserver.next(getState());
}
}
observeState();
const unsubscribe = outerSubscribe(observeState);
return {
unsubscribe
};
},
[symbol_observable_default]() {
return this;
}
};
}
dispatch({
type: actionTypes_default.INIT
});
const store = {
dispatch,
subscribe,
getState,
replaceReducer,
[symbol_observable_default]: observable
};
return store;
}
function legacy_createStore(reducer, preloadedState, enhancer) {
return createStore(reducer, preloadedState, enhancer);
}
// src/utils/warning.ts
function warning(message) {
if (typeof console !== "undefined" && typeof console.error === "function") {
console.error(message);
}
try {
throw new Error(message);
} catch (e) {
}
}
// src/combineReducers.ts
function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
const reducerKeys = Object.keys(reducers);
const argumentName = action && action.type === actionTypes_default.INIT ? "preloadedState argument passed to createStore" : "previous state received by the reducer";
if (reducerKeys.length === 0) {
return "Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";
}
if (!isPlainObject(inputState)) {
return `The ${argumentName} has unexpected type of "${kindOf(inputState)}". Expected argument to be an object with the following keys: "${reducerKeys.join('", "')}"`;
}
const unexpectedKeys = Object.keys(inputState).filter((key) => !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]);
unexpectedKeys.forEach((key) => {
unexpectedKeyCache[key] = true;
});
if (action && action.type === actionTypes_default.REPLACE)
return;
if (unexpectedKeys.length > 0) {
return `Unexpected ${unexpectedKeys.length > 1 ? "keys" : "key"} "${unexpectedKeys.join('", "')}" found in ${argumentName}. Expected to find one of the known reducer keys instead: "${reducerKeys.join('", "')}". Unexpected keys will be ignored.`;
}
}
function assertReducerShape(reducers) {
Object.keys(reducers).forEach((key) => {
const reducer = reducers[key];
const initialState = reducer(void 0, {
type: actionTypes_default.INIT
});
if (typeof initialState === "undefined") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(12) : `The slice reducer for key "${key}" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);
}
if (typeof reducer(void 0, {
type: actionTypes_default.PROBE_UNKNOWN_ACTION()
}) === "undefined") {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(13) : `The slice reducer for key "${key}" returned undefined when probed with a random type. Don't try to handle '${actionTypes_default.INIT}' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`);
}
});
}
function combineReducers(reducers) {
const reducerKeys = Object.keys(reducers);
const finalReducers = {};
for (let i = 0; i < reducerKeys.length; i++) {
const key = reducerKeys[i];
if (process.env.NODE_ENV !== "production") {
if (typeof reducers[key] === "undefined") {
warning(`No reducer provided for key "${key}"`);
}
}
if (typeof reducers[key] === "function") {
finalReducers[key] = reducers[key];
}
}
const finalReducerKeys = Object.keys(finalReducers);
let unexpectedKeyCache;
if (process.env.NODE_ENV !== "production") {
unexpectedKeyCache = {};
}
let shapeAssertionError;
try {
assertReducerShape(finalReducers);
} catch (e) {
shapeAssertionError = e;
}
return function combination(state = {}, action) {
if (shapeAssertionError) {
throw shapeAssertionError;
}
if (process.env.NODE_ENV !== "production") {
const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
if (warningMessage) {
warning(warningMessage);
}
}
let hasChanged = false;
const nextState = {};
for (let i = 0; i < finalReducerKeys.length; i++) {
const key = finalReducerKeys[i];
const reducer = finalReducers[key];
const previousStateForKey = state[key];
const nextStateForKey = reducer(previousStateForKey, action);
if (typeof nextStateForKey === "undefined") {
const actionType = action && action.type;
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(14) : `When called with an action of type ${actionType ? `"${String(actionType)}"` : "(unknown type)"}, the slice reducer for key "${key}" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`);
}
nextState[key] = nextStateForKey;
hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
}
hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
return hasChanged ? nextState : state;
};
}
// src/bindActionCreators.ts
function bindActionCreator(actionCreator, dispatch) {
return function(...args) {
return dispatch(actionCreator.apply(this, args));
};
}
function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators === "function") {
return bindActionCreator(actionCreators, dispatch);
}
if (typeof actionCreators !== "object" || actionCreators === null) {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(16) : `bindActionCreators expected an object or a function, but instead received: '${kindOf(actionCreators)}'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`);
}
const boundActionCreators = {};
for (const key in actionCreators) {
const actionCreator = actionCreators[key];
if (typeof actionCreator === "function") {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
}
}
return boundActionCreators;
}
// src/compose.ts
function compose(...funcs) {
if (funcs.length === 0) {
return (arg) => arg;
}
if (funcs.length === 1) {
return funcs[0];
}
return funcs.reduce((a, b) => (...args) => a(b(...args)));
}
// src/applyMiddleware.ts
function applyMiddleware(...middlewares) {
return (createStore2) => (reducer, preloadedState) => {
const store = createStore2(reducer, preloadedState);
let dispatch = () => {
throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(15) : "Dispatching while constructing your middleware is not allowed. Other middleware would not be applied to this dispatch.");
};
const middlewareAPI = {
getState: store.getState,
dispatch: (action, ...args) => dispatch(action, ...args)
};
const chain = middlewares.map((middleware) => middleware(middlewareAPI));
dispatch = compose(...chain)(store.dispatch);
return {
...store,
dispatch
};
};
}
// src/utils/isAction.ts
function isAction(action) {
return isPlainObject(action) && "type" in action && typeof action.type === "string";
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
__DO_NOT_USE__ActionTypes,
applyMiddleware,
bindActionCreators,
combineReducers,
compose,
createStore,
isAction,
isPlainObject,
legacy_createStore
});
//# sourceMappingURL=redux.cjs.map
@@ -0,0 +1,2 @@
import type { LibDefinition } from '../variable';
export declare const es2019_array: LibDefinition;
@@ -0,0 +1 @@
{"version":3,"file":"no-string-refs.d.ts","sourceRoot":"","sources":["no-string-refs.js"],"names":[],"mappings":"wBAqBW,OAAO,QAAQ,EAAE,IAAI,CAAC,UAAU"}
@@ -0,0 +1 @@
{"name":"es-set-tostringtag","version":"2.1.0","requiresBuild":false,"files":{".eslintrc":{"checkedAt":1794532089074,"integrity":"sha512-avVQBvEjZuAALik4d1n8WoPRiLLkkHk3sctxqfukG6S1H8uf6yDPtpr43KHC/m5Kvg+S4XoW8YPm8lL0Q1Uecg==","mode":420,"size":138},".nycrc":{"checkedAt":1794532089075,"integrity":"sha512-2vm1RFz8Ajl/OYrfoCWPJIm3Bpnf7Gyn5bha/lZx/cq+We3uMy9xj15XeP6x4wF3jf/pO7KMHAkU9mllm605xg==","mode":420,"size":139},"LICENSE":{"checkedAt":1794532096792,"integrity":"sha512-ejuNvD9EeEm1WqD7r4RVoNKMvgN3tSGqs/oFxTWPMZVEsraknZlROcwbuqU+QaHPXa2muiQzVNyGdLU811D0lA==","mode":420,"size":1073},"index.js":{"checkedAt":1794532096792,"integrity":"sha512-YUvfHFx9vDbwDxaC0NCq0epT+70jZj6FjJyb2s1KvYKO9D7L4g7pNJyXiiyR6upWb8BjbyGVhkTt7x70hxZDEA==","mode":420,"size":1213},"test/index.js":{"checkedAt":1794532096792,"integrity":"sha512-c2alM4yySoYAS72zVEcaOZPBe45FGpXDBkdNeQ8X9/oVzh+KYafMZS5YxIdmiTojlip95OzaRt9YtMJ8vfiGFw==","mode":420,"size":2235},"package.json":{"checkedAt":1794532096792,"integrity":"sha512-RC8PgA/deW5ZEdtuR5X2UdKrQXfmOrQ9SgOIezJM4frf6h7cb7o+0F8Zr7bCDZ3TyUuoc6mkR5PLzvhUCwlFaA==","mode":420,"size":2193},"tsconfig.json":{"checkedAt":1794532089067,"integrity":"sha512-NbUb3qW9MICwZdeqct5d4Wxdg5xq+GcfgyXTW2n32l2aXVPFPDjM2890hHzAu/PQbh7KAUFaFUb/1VgXR7FDSg==","mode":420,"size":116},"CHANGELOG.md":{"checkedAt":1794532096792,"integrity":"sha512-QgNwJbjeIipQLZakqqkbt3Gl9pheeulIYlrB4ZlW0C+RWu+bVlEXVoKnmcAIk/jhxhywqwDQ0XQgnTk9CrD1Bw==","mode":420,"size":4968},"README.md":{"checkedAt":1794532096793,"integrity":"sha512-8JRe3eCP0ZFokjAuAyMUT/85Nc9Z/UP1XPS381B8jvtE86yDDbXKWpTfeOjBkupiyqZGA9BUoRZHd15oyFLHhg==","mode":420,"size":2233},"index.d.ts":{"checkedAt":1794532096793,"integrity":"sha512-AlzVQ51j4AdWcGiXQNj43E9ggoBHYwsglScTAmplv44AIHrU9RUzhIuB6ggOyZtu0zp4cXl7kyBPUehKuii8gA==","mode":420,"size":236}}}
@@ -0,0 +1,271 @@
/**
* @fileoverview Prevent usage of deprecated methods
* @author Yannick Croissant
* @author Scott Feeney
* @author Sergei Startsev
*/
'use strict';
const entries = require('object.entries');
const astUtil = require('../util/ast');
const componentUtil = require('../util/componentUtil');
const docsUrl = require('../util/docsUrl');
const pragmaUtil = require('../util/pragma');
const testReactVersion = require('../util/version').testReactVersion;
const report = require('../util/report');
const getText = require('../util/eslint').getText;
// ------------------------------------------------------------------------------
// Constants
// ------------------------------------------------------------------------------
const MODULES = {
react: ['React'],
'react-addons-perf': ['ReactPerf', 'Perf'],
'react-dom': ['ReactDOM'],
'react-dom/server': ['ReactDOMServer'],
};
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
function getDeprecated(pragma) {
const deprecated = {};
// 0.12.0
deprecated[`${pragma}.renderComponent`] = ['0.12.0', `${pragma}.render`];
deprecated[`${pragma}.renderComponentToString`] = ['0.12.0', `${pragma}.renderToString`];
deprecated[`${pragma}.renderComponentToStaticMarkup`] = ['0.12.0', `${pragma}.renderToStaticMarkup`];
deprecated[`${pragma}.isValidComponent`] = ['0.12.0', `${pragma}.isValidElement`];
deprecated[`${pragma}.PropTypes.component`] = ['0.12.0', `${pragma}.PropTypes.element`];
deprecated[`${pragma}.PropTypes.renderable`] = ['0.12.0', `${pragma}.PropTypes.node`];
deprecated[`${pragma}.isValidClass`] = ['0.12.0'];
deprecated['this.transferPropsTo'] = ['0.12.0', 'spread operator ({...})'];
// 0.13.0
deprecated[`${pragma}.addons.classSet`] = ['0.13.0', 'the npm module classnames'];
deprecated[`${pragma}.addons.cloneWithProps`] = ['0.13.0', `${pragma}.cloneElement`];
// 0.14.0
deprecated[`${pragma}.render`] = ['0.14.0', 'ReactDOM.render'];
deprecated[`${pragma}.unmountComponentAtNode`] = ['0.14.0', 'ReactDOM.unmountComponentAtNode'];
deprecated[`${pragma}.findDOMNode`] = ['0.14.0', 'ReactDOM.findDOMNode'];
deprecated[`${pragma}.renderToString`] = ['0.14.0', 'ReactDOMServer.renderToString'];
deprecated[`${pragma}.renderToStaticMarkup`] = ['0.14.0', 'ReactDOMServer.renderToStaticMarkup'];
// 15.0.0
deprecated[`${pragma}.addons.LinkedStateMixin`] = ['15.0.0'];
deprecated['ReactPerf.printDOM'] = ['15.0.0', 'ReactPerf.printOperations'];
deprecated['Perf.printDOM'] = ['15.0.0', 'Perf.printOperations'];
deprecated['ReactPerf.getMeasurementsSummaryMap'] = ['15.0.0', 'ReactPerf.getWasted'];
deprecated['Perf.getMeasurementsSummaryMap'] = ['15.0.0', 'Perf.getWasted'];
// 15.5.0
deprecated[`${pragma}.createClass`] = ['15.5.0', 'the npm module create-react-class'];
deprecated[`${pragma}.addons.TestUtils`] = ['15.5.0', 'ReactDOM.TestUtils'];
deprecated[`${pragma}.PropTypes`] = ['15.5.0', 'the npm module prop-types'];
// 15.6.0
deprecated[`${pragma}.DOM`] = ['15.6.0', 'the npm module react-dom-factories'];
// 16.9.0
// For now the following life-cycle methods are just legacy, not deprecated:
// `componentWillMount`, `componentWillReceiveProps`, `componentWillUpdate`
// https://github.com/yannickcr/eslint-plugin-react/pull/1750#issuecomment-425975934
deprecated.componentWillMount = [
'16.9.0',
'UNSAFE_componentWillMount',
'https://reactjs.org/docs/react-component.html#unsafe_componentwillmount. '
+ 'Use https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles to automatically update your components.',
];
deprecated.componentWillReceiveProps = [
'16.9.0',
'UNSAFE_componentWillReceiveProps',
'https://reactjs.org/docs/react-component.html#unsafe_componentwillreceiveprops. '
+ 'Use https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles to automatically update your components.',
];
deprecated.componentWillUpdate = [
'16.9.0',
'UNSAFE_componentWillUpdate',
'https://reactjs.org/docs/react-component.html#unsafe_componentwillupdate. '
+ 'Use https://github.com/reactjs/react-codemod#rename-unsafe-lifecycles to automatically update your components.',
];
// 18.0.0
// https://reactjs.org/blog/2022/03/08/react-18-upgrade-guide.html#deprecations
deprecated['ReactDOM.render'] = [
'18.0.0',
'createRoot',
'https://reactjs.org/link/switch-to-createroot',
];
deprecated['ReactDOM.hydrate'] = [
'18.0.0',
'hydrateRoot',
'https://reactjs.org/link/switch-to-createroot',
];
deprecated['ReactDOM.unmountComponentAtNode'] = [
'18.0.0',
'root.unmount',
'https://reactjs.org/link/switch-to-createroot',
];
deprecated['ReactDOMServer.renderToNodeStream'] = [
'18.0.0',
'renderToPipeableStream',
'https://reactjs.org/docs/react-dom-server.html#rendertonodestream',
];
return deprecated;
}
const messages = {
deprecated: '{{oldMethod}} is deprecated since React {{version}}{{newMethod}}{{refs}}',
};
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
docs: {
description: 'Disallow usage of deprecated methods',
category: 'Best Practices',
recommended: true,
url: docsUrl('no-deprecated'),
},
messages,
schema: [],
},
create(context) {
const pragma = pragmaUtil.getFromContext(context);
const deprecated = getDeprecated(pragma);
function isDeprecated(method) {
return (
deprecated
&& deprecated[method]
&& deprecated[method][0]
&& testReactVersion(context, `>= ${deprecated[method][0]}`)
);
}
function checkDeprecation(node, methodName, methodNode) {
if (!isDeprecated(methodName)) {
return;
}
const version = deprecated[methodName][0];
const newMethod = deprecated[methodName][1];
const refs = deprecated[methodName][2];
report(context, messages.deprecated, 'deprecated', {
node: methodNode || node,
data: {
oldMethod: methodName,
version,
newMethod: newMethod ? `, use ${newMethod} instead` : '',
refs: refs ? `, see ${refs}` : '',
},
});
}
function getReactModuleName(node) {
let moduleName = false;
if (!node.init) {
return false;
}
entries(MODULES).some((entry) => {
const key = entry[0];
const moduleNames = entry[1];
if (
node.init.arguments
&& node.init.arguments.length > 0
&& node.init.arguments[0]
&& key === node.init.arguments[0].value
) {
moduleName = MODULES[key][0];
} else {
moduleName = moduleNames.find((name) => name === node.init.name);
}
return moduleName;
});
return moduleName;
}
/**
* Returns life cycle methods if available
* @param {ASTNode} node The AST node being checked.
* @returns {Array} The array of methods.
*/
function getLifeCycleMethods(node) {
const properties = astUtil.getComponentProperties(node);
return properties.map((property) => ({
name: astUtil.getPropertyName(property),
node: astUtil.getPropertyNameNode(property),
}));
}
/**
* Checks life cycle methods
* @param {ASTNode} node The AST node being checked.
*/
function checkLifeCycleMethods(node) {
if (
componentUtil.isES5Component(node, context)
|| componentUtil.isES6Component(node, context)
) {
const methods = getLifeCycleMethods(node);
methods.forEach((method) => checkDeprecation(node, method.name, method.node));
}
}
// --------------------------------------------------------------------------
// Public
// --------------------------------------------------------------------------
return {
MemberExpression(node) {
checkDeprecation(node, getText(context, node));
},
ImportDeclaration(node) {
const isReactImport = typeof MODULES[node.source.value] !== 'undefined';
if (!isReactImport) {
return;
}
node.specifiers.filter(((s) => 'imported' in s && s.imported)).forEach((specifier) => {
// TODO, semver-major: remove `in` check as part of jsdoc->tsdoc migration
checkDeprecation(node, 'imported' in specifier && 'name' in specifier.imported && `${MODULES[node.source.value][0]}.${specifier.imported.name}`, specifier);
});
},
VariableDeclarator(node) {
const reactModuleName = getReactModuleName(node);
const isRequire = node.init
&& 'callee' in node.init
&& node.init.callee
&& 'name' in node.init.callee
&& node.init.callee.name === 'require';
const isReactRequire = node.init
&& 'arguments' in node.init
&& node.init.arguments
&& node.init.arguments.length
&& typeof MODULES['value' in node.init.arguments[0] ? node.init.arguments[0].value : undefined] !== 'undefined';
const isDestructuring = node.id && node.id.type === 'ObjectPattern';
if (
!(isDestructuring && reactModuleName)
&& !(isDestructuring && isRequire && isReactRequire)
) {
return;
}
('properties' in node.id ? node.id.properties : undefined).filter((p) => p.type !== 'RestElement' && p.key).forEach((property) => {
checkDeprecation(
node,
'key' in property && 'name' in property.key && `${reactModuleName || pragma}.${property.key.name}`,
property
);
});
},
ClassDeclaration: checkLifeCycleMethods,
ClassExpression: checkLifeCycleMethods,
ObjectExpression: checkLifeCycleMethods,
};
},
};
@@ -0,0 +1,258 @@
/*
* 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.
*/
import {Context, createContext, useContext, useEffect, useMemo, useRef, useState} from 'react';
import {Validation, ValidationErrors, ValidationFunction, ValidationResult} from '@react-types/shared';
export const VALID_VALIDITY_STATE: ValidityState = {
badInput: false,
customError: false,
patternMismatch: false,
rangeOverflow: false,
rangeUnderflow: false,
stepMismatch: false,
tooLong: false,
tooShort: false,
typeMismatch: false,
valueMissing: false,
valid: true
};
const CUSTOM_VALIDITY_STATE: ValidityState = {
...VALID_VALIDITY_STATE,
customError: true,
valid: false
};
export const DEFAULT_VALIDATION_RESULT: ValidationResult = {
isInvalid: false,
validationDetails: VALID_VALIDITY_STATE,
validationErrors: []
};
export const FormValidationContext: Context<ValidationErrors> = createContext<ValidationErrors>({});
export const privateValidationStateProp: string = '__formValidationState' + Date.now();
interface FormValidationProps<T> extends Validation<T> {
builtinValidation?: ValidationResult,
name?: string | string[],
value: T | null
}
export interface FormValidationState {
/** Realtime validation results, updated as the user edits the value. */
realtimeValidation: ValidationResult,
/** Currently displayed validation results, updated when the user commits their changes. */
displayValidation: ValidationResult,
/** Updates the current validation result. Not displayed to the user until `commitValidation` is called. */
updateValidation(result: ValidationResult): void,
/** Resets the displayed validation state to valid when the user resets the form. */
resetValidation(): void,
/** Commits the realtime validation so it is displayed to the user. */
commitValidation(): void
}
export function useFormValidationState<T>(props: FormValidationProps<T>): FormValidationState {
// Private prop for parent components to pass state to children.
if (props[privateValidationStateProp]) {
let {realtimeValidation, displayValidation, updateValidation, resetValidation, commitValidation} = props[privateValidationStateProp] as FormValidationState;
return {realtimeValidation, displayValidation, updateValidation, resetValidation, commitValidation};
}
// eslint-disable-next-line react-hooks/rules-of-hooks
return useFormValidationStateImpl(props);
}
function useFormValidationStateImpl<T>(props: FormValidationProps<T>): FormValidationState {
let {isInvalid, validationState, name, value, builtinValidation, validate, validationBehavior = 'aria'} = props;
// backward compatibility.
if (validationState) {
isInvalid ||= validationState === 'invalid';
}
// If the isInvalid prop is controlled, update validation result in realtime.
let controlledError: ValidationResult | null = isInvalid !== undefined ? {
isInvalid,
validationErrors: [],
validationDetails: CUSTOM_VALIDITY_STATE
} : null;
// Perform custom client side validation.
let clientError: ValidationResult | null = useMemo(() => {
if (!validate || value == null) {
return null;
}
let validateErrors = runValidate(validate, value);
return getValidationResult(validateErrors);
}, [validate, value]);
if (builtinValidation?.validationDetails.valid) {
builtinValidation = undefined;
}
// Get relevant server errors from the form.
let serverErrors = useContext(FormValidationContext);
let serverErrorMessages = useMemo(() => {
if (name) {
return Array.isArray(name) ? name.flatMap(name => asArray(serverErrors[name])) : asArray(serverErrors[name]);
}
return [];
}, [serverErrors, name]);
// Show server errors when the form gets a new value, and clear when the user changes the value.
let [lastServerErrors, setLastServerErrors] = useState(serverErrors);
let [isServerErrorCleared, setServerErrorCleared] = useState(false);
if (serverErrors !== lastServerErrors) {
setLastServerErrors(serverErrors);
setServerErrorCleared(false);
}
let serverError: ValidationResult | null = useMemo(() =>
getValidationResult(isServerErrorCleared ? [] : serverErrorMessages),
[isServerErrorCleared, serverErrorMessages]
);
// Track the next validation state in a ref until commitValidation is called.
let nextValidation = useRef(DEFAULT_VALIDATION_RESULT);
let [currentValidity, setCurrentValidity] = useState(DEFAULT_VALIDATION_RESULT);
let lastError = useRef(DEFAULT_VALIDATION_RESULT);
let commitValidation = () => {
if (!commitQueued) {
return;
}
setCommitQueued(false);
let error = clientError || builtinValidation || nextValidation.current;
if (!isEqualValidation(error, lastError.current)) {
lastError.current = error;
setCurrentValidity(error);
}
};
let [commitQueued, setCommitQueued] = useState(false);
useEffect(commitValidation);
// realtimeValidation is used to update the native input element's state based on custom validation logic.
// displayValidation is the currently displayed validation state that the user sees (e.g. on input change/form submit).
// With validationBehavior="aria", all errors are displayed in realtime rather than on submit.
let realtimeValidation = controlledError || serverError || clientError || builtinValidation || DEFAULT_VALIDATION_RESULT;
let displayValidation = validationBehavior === 'native'
? controlledError || serverError || currentValidity
: controlledError || serverError || clientError || builtinValidation || currentValidity;
return {
realtimeValidation,
displayValidation,
updateValidation(value) {
// If validationBehavior is 'aria', update in realtime. Otherwise, store in a ref until commit.
if (validationBehavior === 'aria' && !isEqualValidation(currentValidity, value)) {
setCurrentValidity(value);
} else {
nextValidation.current = value;
}
},
resetValidation() {
// Update the currently displayed validation state to valid on form reset,
// even if the native validity says it isn't. It'll show again on the next form submit.
let error = DEFAULT_VALIDATION_RESULT;
if (!isEqualValidation(error, lastError.current)) {
lastError.current = error;
setCurrentValidity(error);
}
// Do not commit validation after the next render. This avoids a condition where
// useSelect calls commitValidation inside an onReset handler.
if (validationBehavior === 'native') {
setCommitQueued(false);
}
setServerErrorCleared(true);
},
commitValidation() {
// Commit validation state so the user sees it on blur/change/submit. Also clear any server errors.
// Wait until after the next render to commit so that the latest value has been validated.
if (validationBehavior === 'native') {
setCommitQueued(true);
}
setServerErrorCleared(true);
}
};
}
function asArray<T>(v: T | T[]): T[] {
if (!v) {
return [];
}
return Array.isArray(v) ? v : [v];
}
function runValidate<T>(validate: ValidationFunction<T>, value: T): string[] {
if (typeof validate === 'function') {
let e = validate(value);
if (e && typeof e !== 'boolean') {
return asArray(e);
}
}
return [];
}
function getValidationResult(errors: string[]): ValidationResult | null {
return errors.length ? {
isInvalid: true,
validationErrors: errors,
validationDetails: CUSTOM_VALIDITY_STATE
} : null;
}
function isEqualValidation(a: ValidationResult | null, b: ValidationResult | null): boolean {
if (a === b) {
return true;
}
return !!a && !!b
&& a.isInvalid === b.isInvalid
&& a.validationErrors.length === b.validationErrors.length
&& a.validationErrors.every((a, i) => a === b.validationErrors[i])
&& Object.entries(a.validationDetails).every(([k, v]) => b.validationDetails[k] === v);
}
export function mergeValidation(...results: ValidationResult[]): ValidationResult {
let errors = new Set<string>();
let isInvalid = false;
let validationDetails = {
...VALID_VALIDITY_STATE
};
for (let v of results) {
for (let e of v.validationErrors) {
errors.add(e);
}
// Only these properties apply for checkboxes.
isInvalid ||= v.isInvalid;
for (let key in validationDetails) {
validationDetails[key] ||= v.validationDetails[key];
}
}
validationDetails.valid = !isInvalid;
return {
isInvalid,
validationErrors: [...errors],
validationDetails
};
}
@@ -0,0 +1,58 @@
/*
* 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 $c87311424ea30a05$var$testUserAgent(re) {
var _window_navigator_userAgentData;
if (typeof window === 'undefined' || window.navigator == null) return false;
return ((_window_navigator_userAgentData = window.navigator['userAgentData']) === null || _window_navigator_userAgentData === void 0 ? void 0 : _window_navigator_userAgentData.brands.some((brand)=>re.test(brand.brand))) || re.test(window.navigator.userAgent);
}
function $c87311424ea30a05$var$testPlatform(re) {
var _window_navigator_userAgentData;
return typeof window !== 'undefined' && window.navigator != null ? re.test(((_window_navigator_userAgentData = window.navigator['userAgentData']) === null || _window_navigator_userAgentData === void 0 ? void 0 : _window_navigator_userAgentData.platform) || window.navigator.platform) : false;
}
function $c87311424ea30a05$var$cached(fn) {
let res = null;
return ()=>{
if (res == null) res = fn();
return res;
};
}
const $c87311424ea30a05$export$9ac100e40613ea10 = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$var$testPlatform(/^Mac/i);
});
const $c87311424ea30a05$export$186c6964ca17d99 = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$var$testPlatform(/^iPhone/i);
});
const $c87311424ea30a05$export$7bef049ce92e4224 = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$var$testPlatform(/^iPad/i) || // iPadOS 13 lies and says it's a Mac, but we can distinguish by detecting touch support.
$c87311424ea30a05$export$9ac100e40613ea10() && navigator.maxTouchPoints > 1;
});
const $c87311424ea30a05$export$fedb369cb70207f1 = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$export$186c6964ca17d99() || $c87311424ea30a05$export$7bef049ce92e4224();
});
const $c87311424ea30a05$export$e1865c3bedcd822b = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$export$9ac100e40613ea10() || $c87311424ea30a05$export$fedb369cb70207f1();
});
const $c87311424ea30a05$export$78551043582a6a98 = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$var$testUserAgent(/AppleWebKit/i) && !$c87311424ea30a05$export$6446a186d09e379e();
});
const $c87311424ea30a05$export$6446a186d09e379e = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$var$testUserAgent(/Chrome/i);
});
const $c87311424ea30a05$export$a11b0059900ceec8 = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$var$testUserAgent(/Android/i);
});
const $c87311424ea30a05$export$b7d78993b74f766d = $c87311424ea30a05$var$cached(function() {
return $c87311424ea30a05$var$testUserAgent(/Firefox/i);
});
export {$c87311424ea30a05$export$9ac100e40613ea10 as isMac, $c87311424ea30a05$export$186c6964ca17d99 as isIPhone, $c87311424ea30a05$export$7bef049ce92e4224 as isIPad, $c87311424ea30a05$export$fedb369cb70207f1 as isIOS, $c87311424ea30a05$export$e1865c3bedcd822b as isAppleDevice, $c87311424ea30a05$export$78551043582a6a98 as isWebKit, $c87311424ea30a05$export$6446a186d09e379e as isChrome, $c87311424ea30a05$export$a11b0059900ceec8 as isAndroid, $c87311424ea30a05$export$b7d78993b74f766d as isFirefox};
//# sourceMappingURL=platform.module.js.map
Loaded 100 of 35554 files, more files were not shown because too many files have changed in this diff. Show more