fix(products): fix breadcrumbs and product filtering (backport from main)
Some checks failed
Build & Deploy / 🔍 Prepare (push) Successful in 20s
Build & Deploy / 🧪 QA (push) Failing after 34s
Build & Deploy / 🏗️ Build (push) Has started running
Build & Deploy / 🚀 Deploy (push) Has been cancelled
Build & Deploy / 🧪 Smoke Test (push) Has been cancelled
Build & Deploy / ⚡ Lighthouse (push) Has been cancelled
Build & Deploy / 🔔 Notify (push) Has been cancelled

This commit is contained in:
2026-02-24 16:04:21 +01:00
parent 915eb61613
commit 5397309103
43805 changed files with 4324295 additions and 3 deletions

View File

@@ -0,0 +1,11 @@
"use strict";
exports.normalizeDates = normalizeDates;
var _index = require("../constructFrom.cjs");
function normalizeDates(context, ...dates) {
const normalize = _index.constructFrom.bind(
null,
context || dates.find((date) => typeof date === "object"),
);
return dates.map(normalize);
}

View File

@@ -0,0 +1,17 @@
/**
* @license lucide-react v0.441.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const Shrub = createLucideIcon("Shrub", [
["path", { d: "M12 22v-7l-2-2", key: "eqv9mc" }],
["path", { d: "M17 8v.8A6 6 0 0 1 13.8 20H10A6.5 6.5 0 0 1 7 8a5 5 0 0 1 10 0Z", key: "ubcgy" }],
["path", { d: "m14 14-2 2", key: "847xa2" }]
]);
export { Shrub as default };
//# sourceMappingURL=shrub.js.map

View File

@@ -0,0 +1,7 @@
import type { Session } from '../types';
/** If the session should be refreshed or not. */
export declare function shouldRefreshSession(session: Session, { sessionIdleExpire, maxReplayDuration }: {
sessionIdleExpire: number;
maxReplayDuration: number;
}): boolean;
//# sourceMappingURL=shouldRefreshSession.d.ts.map

View File

@@ -0,0 +1,33 @@
var baseIteratee = require('./_baseIteratee'),
basePullAll = require('./_basePullAll');
/**
* This method is like `_.pullAll` except that it accepts `iteratee` which is
* invoked for each element of `array` and `values` to generate the criterion
* by which they're compared. The iteratee is invoked with one argument: (value).
*
* **Note:** Unlike `_.differenceBy`, this method mutates `array`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {Array} array The array to modify.
* @param {Array} values The values to remove.
* @param {Function} [iteratee=_.identity] The iteratee invoked per element.
* @returns {Array} Returns `array`.
* @example
*
* var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
*
* _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
* console.log(array);
* // => [{ 'x': 2 }]
*/
function pullAllBy(array, values, iteratee) {
return (array && array.length && values && values.length)
? basePullAll(array, values, baseIteratee(iteratee, 2))
: array;
}
module.exports = pullAllBy;

View File

@@ -0,0 +1,17 @@
/**
* @license lucide-react v0.441.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const FileCheck = createLucideIcon("FileCheck", [
["path", { d: "M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z", key: "1rqfz7" }],
["path", { d: "M14 2v4a2 2 0 0 0 2 2h4", key: "tnqrlb" }],
["path", { d: "m9 15 2 2 4-4", key: "1grp1n" }]
]);
export { FileCheck as default };
//# sourceMappingURL=file-check.js.map

View File

@@ -0,0 +1,88 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { STAGE_BASIC } = require("../OptimizationStages");
/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../ChunkGroup")} ChunkGroup */
/** @typedef {import("../Compiler")} Compiler */
const PLUGIN_NAME = "EnsureChunkConditionsPlugin";
class EnsureChunkConditionsPlugin {
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler) {
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
/**
* @param {Iterable<Chunk>} chunks the chunks
*/
const handler = (chunks) => {
const chunkGraph = compilation.chunkGraph;
// These sets are hoisted here to save memory
// They are cleared at the end of every loop
/** @type {Set<Chunk>} */
const sourceChunks = new Set();
/** @type {Set<ChunkGroup>} */
const chunkGroups = new Set();
for (const module of compilation.modules) {
if (!module.hasChunkCondition()) continue;
for (const chunk of chunkGraph.getModuleChunksIterable(module)) {
if (!module.chunkCondition(chunk, compilation)) {
sourceChunks.add(chunk);
for (const group of chunk.groupsIterable) {
chunkGroups.add(group);
}
}
}
if (sourceChunks.size === 0) continue;
/** @type {Set<Chunk>} */
const targetChunks = new Set();
chunkGroupLoop: for (const chunkGroup of chunkGroups) {
// Can module be placed in a chunk of this group?
for (const chunk of chunkGroup.chunks) {
if (module.chunkCondition(chunk, compilation)) {
targetChunks.add(chunk);
continue chunkGroupLoop;
}
}
// We reached the entrypoint: fail
if (chunkGroup.isInitial()) {
throw new Error(
`Cannot fulfil chunk condition of ${module.identifier()}`
);
}
// Try placing in all parents
for (const group of chunkGroup.parentsIterable) {
chunkGroups.add(group);
}
}
for (const sourceChunk of sourceChunks) {
chunkGraph.disconnectChunkAndModule(sourceChunk, module);
}
for (const targetChunk of targetChunks) {
chunkGraph.connectChunkAndModule(targetChunk, module);
}
sourceChunks.clear();
chunkGroups.clear();
}
};
compilation.hooks.optimizeChunks.tap(
{
name: PLUGIN_NAME,
stage: STAGE_BASIC
},
handler
);
});
}
}
module.exports = EnsureChunkConditionsPlugin;

View File

@@ -0,0 +1 @@
{"version":3,"file":"anyOf.js","sourceRoot":"","sources":["../../../lib/vocabularies/applicator/anyOf.ts"],"names":[],"mappings":";;AACA,kCAAqC;AAIrC,MAAM,GAAG,GAA0B;IACjC,OAAO,EAAE,OAAO;IAChB,UAAU,EAAE,OAAO;IACnB,WAAW,EAAE,IAAI;IACjB,IAAI,EAAE,oBAAa;IACnB,KAAK,EAAE,EAAC,OAAO,EAAE,8BAA8B,EAAC;CACjD,CAAA;AAED,kBAAe,GAAG,CAAA"}

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/elements/ReactSelect/MultiValueRemove/index.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAA;AAEzD,OAAO,KAAK,EAAE,EAAE,KAAK,GAAG,EAAE,MAAM,OAAO,CAAA;AAEvC,OAAO,KAAK,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,aAAa,CAAA;AAKvD,OAAO,cAAc,CAAA;AAIrB,eAAO,MAAM,gBAAgB,EAAE,KAAK,CAAC,EAAE,CACrC;IACE,UAAU,EAAE,GAAG,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CAAA;CAC5C,GAAG,qBAAqB,CAAC,UAAU,CAAC,CAkCtC,CAAA"}

View File

@@ -0,0 +1,20 @@
"use strict";
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _create_class(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
exports._ = _create_class;

View File

@@ -0,0 +1,39 @@
"use strict";
exports.nextDay = nextDay;
var _index = require("./addDays.cjs");
var _index2 = require("./getDay.cjs");
/**
* The {@link nextDay} function options.
*/
/**
* @name nextDay
* @category Weekday Helpers
* @summary When is the next day of the week? 0-6 the day of the week, 0 represents Sunday.
*
* @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
* @typeParam ResultDate - The result `Date` type, it is the type returned from the context function if it is passed, or inferred from the arguments.
*
* @param date - The date to check
* @param day - Day of the week
* @param options - An object with options
*
* @returns The date is the next day of the week
*
* @example
* // When is the next Monday after Mar, 20, 2020?
* const result = nextDay(new Date(2020, 2, 20), 1)
* //=> Mon Mar 23 2020 00:00:00
*
* @example
* // When is the next Tuesday after Mar, 21, 2020?
* const result = nextDay(new Date(2020, 2, 21), 2)
* //=> Tue Mar 24 2020 00:00:00
*/
function nextDay(date, day, options) {
let delta = day - (0, _index2.getDay)(date, options);
if (delta <= 0) delta += 7;
return (0, _index.addDays)(date, delta, options);
}

View File

@@ -0,0 +1,52 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.addComment = addComment;
exports.addComments = addComments;
exports.shareCommentsWithSiblings = shareCommentsWithSiblings;
var _t = require("@babel/types");
const {
addComment: _addComment,
addComments: _addComments
} = _t;
function shareCommentsWithSiblings() {
if (typeof this.key === "string") return;
const node = this.node;
if (!node) return;
const trailing = node.trailingComments;
const leading = node.leadingComments;
if (!trailing && !leading) return;
const prev = this.getSibling(this.key - 1);
const next = this.getSibling(this.key + 1);
const hasPrev = Boolean(prev.node);
const hasNext = Boolean(next.node);
if (hasPrev) {
if (leading) {
prev.addComments("trailing", removeIfExisting(leading, prev.node.trailingComments));
}
if (trailing && !hasNext) prev.addComments("trailing", trailing);
}
if (hasNext) {
if (trailing) {
next.addComments("leading", removeIfExisting(trailing, next.node.leadingComments));
}
if (leading && !hasPrev) next.addComments("leading", leading);
}
}
function removeIfExisting(list, toRemove) {
if (!(toRemove != null && toRemove.length)) return list;
const set = new Set(toRemove);
return list.filter(el => {
return !set.has(el);
});
}
function addComment(type, content, line) {
_addComment(this.node, type, content, line);
}
function addComments(type, comments) {
_addComments(this.node, type, comments);
}
//# sourceMappingURL=comments.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getFormattedLocale.js","names":["getFormattedLocale","language","formattedLocales","en","my","ua","zh","formattedLocale"],"sources":["../../../src/elements/DatePicker/getFormattedLocale.ts"],"sourcesContent":["'use client'\nexport const getFormattedLocale = (language = 'enUS') => {\n const formattedLocales = {\n en: 'enUS',\n my: 'enUS', // Burmese is not currently supported\n ua: 'uk',\n zh: 'zhCN',\n }\n\n const formattedLocale = formattedLocales[language] || language\n\n return formattedLocale\n}\n"],"mappings":"AAAA;;AACA,OAAO,MAAMA,kBAAA,GAAqBA,CAACC,QAAA,GAAW,MAAM;EAClD,MAAMC,gBAAA,GAAmB;IACvBC,EAAA,EAAI;IACJC,EAAA,EAAI;IACJC,EAAA,EAAI;IACJC,EAAA,EAAI;EACN;EAEA,MAAMC,eAAA,GAAkBL,gBAAgB,CAACD,QAAA,CAAS,IAAIA,QAAA;EAEtD,OAAOM,eAAA;AACT","ignoreList":[]}

View File

@@ -0,0 +1,182 @@
import { APIError, canAccessAdmin, formatErrors } from 'payload';
import { applyLocaleFiltering, isNumber } from 'payload/shared';
import { getClientConfig } from './getClientConfig.js';
import { getColumns } from './getColumns.js';
import { renderFilters, renderTable } from './renderTable.js';
import { upsertPreferences } from './upsertPreferences.js';
export const buildTableStateHandler = async args => {
const {
req
} = args;
try {
const res = await buildTableState(args);
return res;
} catch (err) {
req.payload.logger.error({
err,
msg: `There was an error building form state`
});
if (err.message === 'Could not find field schema for given path') {
return {
message: err.message
};
}
if (err.message === 'Unauthorized') {
return null;
}
return formatErrors(err);
}
};
const buildTableState = async args => {
const {
collectionSlug,
columns: columnsFromArgs,
data: dataFromArgs,
enableRowSelections,
orderableFieldName,
parent,
permissions,
query,
renderRowTypes,
req,
req: {
i18n,
payload,
payload: {
config
},
user
},
tableAppearance
} = args;
await canAccessAdmin({
req
});
const clientConfig = getClientConfig({
config,
i18n,
importMap: payload.importMap,
user
});
await applyLocaleFiltering({
clientConfig,
config,
req
});
let collectionConfig;
let clientCollectionConfig;
if (!Array.isArray(collectionSlug)) {
if (req.payload.collections[collectionSlug]) {
collectionConfig = req.payload.collections[collectionSlug].config;
clientCollectionConfig = clientConfig.collections.find(collection => collection.slug === collectionSlug);
}
}
const collectionPreferences = await upsertPreferences({
key: Array.isArray(collectionSlug) ? `${parent.collectionSlug}-${parent.joinPath}` : `collection-${collectionSlug}`,
req,
value: {
columns: columnsFromArgs,
limit: isNumber(query?.limit) ? Number(query.limit) : undefined,
sort: query?.sort
}
});
let data = dataFromArgs;
// lookup docs, if desired, i.e. within `join` field which initialize with `depth: 0`
if (!data?.docs || query) {
if (Array.isArray(collectionSlug)) {
if (!parent) {
throw new APIError('Unexpected array of collectionSlug, parent must be provided');
}
const select = {};
let currentSelectRef = select;
const segments = parent.joinPath.split('.');
for (let i = 0; i < segments.length; i++) {
currentSelectRef[segments[i]] = i === segments.length - 1 ? true : {};
currentSelectRef = currentSelectRef[segments[i]];
}
const joinQuery = {
sort: query?.sort,
where: query?.where
};
if (query) {
if (!Number.isNaN(Number(query.limit))) {
joinQuery.limit = Number(query.limit);
}
if (!Number.isNaN(Number(query.page))) {
joinQuery.limit = Number(query.limit);
}
}
let parentDoc = await payload.findByID({
id: parent.id,
collection: parent.collectionSlug,
depth: 1,
joins: {
[parent.joinPath]: joinQuery
},
overrideAccess: false,
select,
user: req.user
});
for (let i = 0; i < segments.length; i++) {
if (i === segments.length - 1) {
data = parentDoc[segments[i]];
} else {
parentDoc = parentDoc[segments[i]];
}
}
} else {
data = await payload.find({
collection: collectionSlug,
depth: 0,
draft: true,
limit: query?.limit,
locale: req.locale,
overrideAccess: false,
page: query?.page,
sort: query?.sort,
user: req.user,
where: query?.where
});
}
}
const {
columnState,
Table
} = renderTable({
clientCollectionConfig,
clientConfig,
collectionConfig,
collections: Array.isArray(collectionSlug) ? collectionSlug : undefined,
columns: getColumns({
clientConfig,
collectionConfig: clientCollectionConfig,
collectionSlug,
columns: columnsFromArgs,
i18n: req.i18n,
permissions
}),
data,
enableRowSelections,
fieldPermissions: Array.isArray(collectionSlug) ? true : permissions.collections[collectionSlug].fields,
i18n: req.i18n,
orderableFieldName,
payload,
query,
renderRowTypes,
req,
tableAppearance,
useAsTitle: Array.isArray(collectionSlug) ? payload.collections[collectionSlug[0]]?.config?.admin?.useAsTitle : collectionConfig?.admin?.useAsTitle
});
let renderedFilters;
if (collectionConfig) {
renderedFilters = renderFilters(collectionConfig.fields, req.payload.importMap);
}
return {
data,
preferences: collectionPreferences,
renderedFilters,
state: columnState,
Table
};
};
//# sourceMappingURL=buildTableState.js.map

View File

@@ -0,0 +1,115 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true,
});
exports.buildASTSchema = buildASTSchema;
exports.buildSchema = buildSchema;
var _devAssert = require('../jsutils/devAssert.js');
var _kinds = require('../language/kinds.js');
var _parser = require('../language/parser.js');
var _directives = require('../type/directives.js');
var _schema = require('../type/schema.js');
var _validate = require('../validation/validate.js');
var _extendSchema = require('./extendSchema.js');
/**
* This takes the ast of a schema document produced by the parse function in
* src/language/parser.js.
*
* If no schema definition is provided, then it will look for types named Query,
* Mutation and Subscription.
*
* Given that AST it constructs a GraphQLSchema. The resulting schema
* has no resolve methods, so execution will use default resolvers.
*/
function buildASTSchema(documentAST, options) {
(documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT) ||
(0, _devAssert.devAssert)(false, 'Must provide valid Document AST.');
if (
(options === null || options === void 0 ? void 0 : options.assumeValid) !==
true &&
(options === null || options === void 0
? void 0
: options.assumeValidSDL) !== true
) {
(0, _validate.assertValidSDL)(documentAST);
}
const emptySchemaConfig = {
description: undefined,
types: [],
directives: [],
extensions: Object.create(null),
extensionASTNodes: [],
assumeValid: false,
};
const config = (0, _extendSchema.extendSchemaImpl)(
emptySchemaConfig,
documentAST,
options,
);
if (config.astNode == null) {
for (const type of config.types) {
switch (type.name) {
// Note: While this could make early assertions to get the correctly
// typed values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
case 'Query':
// @ts-expect-error validated in `validateSchema`
config.query = type;
break;
case 'Mutation':
// @ts-expect-error validated in `validateSchema`
config.mutation = type;
break;
case 'Subscription':
// @ts-expect-error validated in `validateSchema`
config.subscription = type;
break;
}
}
}
const directives = [
...config.directives, // If specified directives were not explicitly declared, add them.
..._directives.specifiedDirectives.filter((stdDirective) =>
config.directives.every(
(directive) => directive.name !== stdDirective.name,
),
),
];
return new _schema.GraphQLSchema({ ...config, directives });
}
/**
* A helper function to build a GraphQLSchema directly from a source
* document.
*/
function buildSchema(source, options) {
const document = (0, _parser.parse)(source, {
noLocation:
options === null || options === void 0 ? void 0 : options.noLocation,
allowLegacyFragmentVariables:
options === null || options === void 0
? void 0
: options.allowLegacyFragmentVariables,
});
return buildASTSchema(document, {
assumeValidSDL:
options === null || options === void 0 ? void 0 : options.assumeValidSDL,
assumeValid:
options === null || options === void 0 ? void 0 : options.assumeValid,
});
}

View File

@@ -0,0 +1,29 @@
import type { FormState, SanitizedCollectionConfig, UploadEdits } from 'payload';
import React from 'react';
import './index.scss';
export declare const editDrawerSlug = "edit-upload";
export declare const sizePreviewSlug = "preview-sizes";
type UploadActionsArgs = {
readonly customActions?: React.ReactNode[];
readonly enableAdjustments: boolean;
readonly enablePreviewSizes: boolean;
readonly mimeType: string;
};
export declare const UploadActions: ({ customActions, enableAdjustments, enablePreviewSizes, mimeType, }: UploadActionsArgs) => React.JSX.Element;
export type UploadProps = {
readonly collectionSlug: string;
readonly customActions?: React.ReactNode[];
readonly initialState?: FormState;
readonly onChange?: (file?: File) => void;
readonly uploadConfig: SanitizedCollectionConfig['upload'];
readonly UploadControls?: React.ReactNode;
};
export declare const Upload: React.FC<UploadProps>;
export type UploadProps_v4 = {
readonly resetUploadEdits?: () => void;
readonly updateUploadEdits?: (args: UploadEdits) => void;
readonly uploadEdits?: UploadEdits;
} & UploadProps;
export declare const Upload_v4: React.FC<UploadProps_v4>;
export {};
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,428 @@
# Commander.js
[![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js)
[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)
[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)
[![Join the chat at https://gitter.im/tj/commander.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander).
[API documentation](http://tj.github.com/commander.js/)
## Installation
$ npm install commander
## Option parsing
Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq-sauce', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);
console.log('you ordered a pizza with:');
if (program.peppers) console.log(' - peppers');
if (program.pineapple) console.log(' - pineapple');
if (program.bbqSauce) console.log(' - bbq');
console.log(' - %s cheese', program.cheese);
```
Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.
Note that multi-word options starting with `--no` prefix negate the boolean value of the following word. For example, `--no-sauce` sets the value of `program.sauce` to false.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.option('--no-sauce', 'Remove sauce')
.parse(process.argv);
console.log('you ordered a pizza');
if (program.sauce) console.log(' with sauce');
else console.log(' without sauce');
```
To get string arguments from options you will need to use angle brackets <> for required inputs or square brackets [] for optional inputs.
e.g. ```.option('-m --myarg [myVar]', 'my super cool description')```
Then to access the input if it was passed in.
e.g. ```var myInput = program.myarg```
**NOTE**: If you pass a argument without using brackets the example above will return true and not the value passed in.
## Version option
Calling the `version` implicitly adds the `-V` and `--version` options to the command.
When either of these options is present, the command prints the version number and exits.
$ ./examples/pizza -V
0.0.1
If you want your program to respond to the `-v` option instead of the `-V` option, simply pass custom flags to the `version` method using the same syntax as the `option` method.
```js
program
.version('0.0.1', '-v, --version')
```
The version flags can be named anything, but the long option is required.
## Command-specific options
You can attach options to a command.
```js
#!/usr/bin/env node
var program = require('commander');
program
.command('rm <dir>')
.option('-r, --recursive', 'Remove recursively')
.action(function (dir, cmd) {
console.log('remove ' + dir + (cmd.recursive ? ' recursively' : ''))
})
program.parse(process.argv)
```
A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.
## Coercion
```js
function range(val) {
return val.split('..').map(Number);
}
function list(val) {
return val.split(',');
}
function collect(val, memo) {
memo.push(val);
return memo;
}
function increaseVerbosity(v, total) {
return total + 1;
}
program
.version('0.1.0')
.usage('[options] <file ...>')
.option('-i, --integer <n>', 'An integer argument', parseInt)
.option('-f, --float <n>', 'A float argument', parseFloat)
.option('-r, --range <a>..<b>', 'A range', range)
.option('-l, --list <items>', 'A list', list)
.option('-o, --optional [value]', 'An optional value')
.option('-c, --collect [value]', 'A repeatable value', collect, [])
.option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
.parse(process.argv);
console.log(' int: %j', program.integer);
console.log(' float: %j', program.float);
console.log(' optional: %j', program.optional);
program.range = program.range || [];
console.log(' range: %j..%j', program.range[0], program.range[1]);
console.log(' list: %j', program.list);
console.log(' collect: %j', program.collect);
console.log(' verbosity: %j', program.verbose);
console.log(' args: %j', program.args);
```
## Regular Expression
```js
program
.version('0.1.0')
.option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')
.option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)
.parse(process.argv);
console.log(' size: %j', program.size);
console.log(' drink: %j', program.drink);
```
## Variadic arguments
The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to
append `...` to the argument name. Here is an example:
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.command('rmdir <dir> [otherDirs...]')
.action(function (dir, otherDirs) {
console.log('rmdir %s', dir);
if (otherDirs) {
otherDirs.forEach(function (oDir) {
console.log('rmdir %s', oDir);
});
}
});
program.parse(process.argv);
```
An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed
to your action as demonstrated above.
## Specify the argument syntax
```js
#!/usr/bin/env node
var program = require('commander');
program
.version('0.1.0')
.arguments('<cmd> [env]')
.action(function (cmd, env) {
cmdValue = cmd;
envValue = env;
});
program.parse(process.argv);
if (typeof cmdValue === 'undefined') {
console.error('no command given!');
process.exit(1);
}
console.log('command:', cmdValue);
console.log('environment:', envValue || "no environment given");
```
Angled brackets (e.g. `<cmd>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input.
## Git-style sub-commands
```js
// file: ./examples/pm
var program = require('commander');
program
.version('0.1.0')
.command('install [name]', 'install one or more packages')
.command('search [query]', 'search with optional query')
.command('list', 'list packages installed', {isDefault: true})
.parse(process.argv);
```
When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools.
The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`.
Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the subcommand from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.
If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
### `--harmony`
You can enable `--harmony` option in two ways:
* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version dont support this pattern.
* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process.
## Automated --help
The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
```
$ ./examples/pizza --help
Usage: pizza [options]
An application for pizzas ordering
Options:
-h, --help output usage information
-V, --version output the version number
-p, --peppers Add peppers
-P, --pineapple Add pineapple
-b, --bbq Add bbq sauce
-c, --cheese <type> Add the specified type of cheese [marble]
-C, --no-cheese You do not want any cheese
```
## Custom help
You can display arbitrary `-h, --help` information
by listening for "--help". Commander will automatically
exit once you are done so that the remainder of your program
does not execute causing undesired behaviors, for example
in the following executable "stuff" will not output when
`--help` is used.
```js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var program = require('commander');
program
.version('0.1.0')
.option('-f, --foo', 'enable some foo')
.option('-b, --bar', 'enable some bar')
.option('-B, --baz', 'enable some baz');
// must be before .parse() since
// node's emit() is immediate
program.on('--help', function(){
console.log('')
console.log('Examples:');
console.log(' $ custom-help --help');
console.log(' $ custom-help -h');
});
program.parse(process.argv);
console.log('stuff');
```
Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:
```
Usage: custom-help [options]
Options:
-h, --help output usage information
-V, --version output the version number
-f, --foo enable some foo
-b, --bar enable some bar
-B, --baz enable some baz
Examples:
$ custom-help --help
$ custom-help -h
```
## .outputHelp(cb)
Output help information without exiting.
Optional callback cb allows post-processing of help text before it is displayed.
If you want to display help by default (e.g. if no command was provided), you can use something like:
```js
var program = require('commander');
var colors = require('colors');
program
.version('0.1.0')
.command('getstream [url]', 'get stream URL')
.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp(make_red);
}
function make_red(txt) {
return colors.red(txt); //display the help text in red on the console
}
```
## .help(cb)
Output help information and exit immediately.
Optional callback cb allows post-processing of help text before it is displayed.
## Custom event listeners
You can execute custom actions by listening to command and option events.
```js
program.on('option:verbose', function () {
process.env.VERBOSE = this.verbose;
});
// error on unknown commands
program.on('command:*', function () {
console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args.join(' '));
process.exit(1);
});
```
## Examples
```js
var program = require('commander');
program
.version('0.1.0')
.option('-C, --chdir <path>', 'change the working directory')
.option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
.option('-T, --no-tests', 'ignore test hook');
program
.command('setup [env]')
.description('run setup commands for all envs')
.option("-s, --setup_mode [mode]", "Which setup mode to use")
.action(function(env, options){
var mode = options.setup_mode || "normal";
env = env || 'all';
console.log('setup for %s env(s) with %s mode', env, mode);
});
program
.command('exec <cmd>')
.alias('ex')
.description('execute the given remote cmd')
.option("-e, --exec_mode <mode>", "Which exec mode to use")
.action(function(cmd, options){
console.log('exec "%s" using %s mode', cmd, options.exec_mode);
}).on('--help', function() {
console.log('');
console.log('Examples:');
console.log('');
console.log(' $ deploy exec sequential');
console.log(' $ deploy exec async');
});
program
.command('*')
.action(function(env){
console.log('deploying "%s"', env);
});
program.parse(process.argv);
```
More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
## License
[MIT](https://github.com/tj/commander.js/blob/master/LICENSE)

View File

@@ -0,0 +1,92 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { ConcatSource } = require("webpack-sources");
const AbstractLibraryPlugin = require("./AbstractLibraryPlugin");
/** @typedef {import("webpack-sources").Source} Source */
/** @typedef {import("../../declarations/WebpackOptions").LibraryOptions} LibraryOptions */
/** @typedef {import("../../declarations/WebpackOptions").LibraryType} LibraryType */
/** @typedef {import("../Chunk")} Chunk */
/** @typedef {import("../Compilation").ChunkHashContext} ChunkHashContext */
/** @typedef {import("../javascript/JavascriptModulesPlugin").RenderContext} RenderContext */
/** @typedef {import("../util/Hash")} Hash */
/**
* @template T
* @typedef {import("./AbstractLibraryPlugin").LibraryContext<T>} LibraryContext<T>
*/
/**
* @typedef {object} JsonpLibraryPluginOptions
* @property {LibraryType} type
*/
/**
* @typedef {object} JsonpLibraryPluginParsed
* @property {string} name
*/
/**
* @typedef {JsonpLibraryPluginParsed} T
* @extends {AbstractLibraryPlugin<JsonpLibraryPluginParsed>}
*/
class JsonpLibraryPlugin extends AbstractLibraryPlugin {
/**
* @param {JsonpLibraryPluginOptions} options the plugin options
*/
constructor(options) {
super({
pluginName: "JsonpLibraryPlugin",
type: options.type
});
}
/**
* @param {LibraryOptions} library normalized library option
* @returns {T} preprocess as needed by overriding
*/
parseOptions(library) {
const { name } = library;
if (typeof name !== "string") {
throw new Error(
`Jsonp library name must be a simple string. ${AbstractLibraryPlugin.COMMON_LIBRARY_NAME_MESSAGE}`
);
}
const _name = /** @type {string} */ (name);
return {
name: _name
};
}
/**
* @param {Source} source source
* @param {RenderContext} renderContext render context
* @param {LibraryContext<T>} libraryContext context
* @returns {Source} source with library export
*/
render(source, { chunk }, { options, compilation }) {
const name = compilation.getPath(options.name, {
chunk
});
return new ConcatSource(`${name}(`, source, ")");
}
/**
* @param {Chunk} chunk the chunk
* @param {Hash} hash hash
* @param {ChunkHashContext} chunkHashContext chunk hash context
* @param {LibraryContext<T>} libraryContext context
* @returns {void}
*/
chunkHash(chunk, hash, chunkHashContext, { options, compilation }) {
hash.update("JsonpLibraryPlugin");
hash.update(compilation.getPath(options.name, { chunk }));
}
}
module.exports = JsonpLibraryPlugin;

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/transform/write/types.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,gBAAgB,GAAG;IAC7B,MAAM,EAAE;QACN,CAAC,SAAS,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAAA;KACxC,CAAA;IACD,YAAY,EAAE;QACZ,CAAC,SAAS,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAAA;KACxC,CAAA;IACD,OAAO,EAAE;QACP,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAC1C,CAAA;IACD,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAC7B,CAAA;AAED,MAAM,MAAM,gBAAgB,GAAG;IAC7B,MAAM,EAAE;QACN,CAAC,SAAS,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAAA;KACxC,CAAA;IACD,YAAY,EAAE;QACZ,CAAC,SAAS,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAAA;KACxC,CAAA;IACD,OAAO,EAAE;QACP,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAC1C,CAAA;IACD,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAC7B,CAAA;AAED,MAAM,MAAM,oBAAoB,GAAG;IACjC,YAAY,CAAC,EAAE,GAAG,CAAA;IAClB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,MAAM,CAAA;IACZ,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB,CAAA;AAED,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,MAAM,CAAA;IACZ,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,KAAK,EAAE,GAAG,CAAA;CACX,CAAA;AAED,MAAM,MAAM,YAAY,GAAG;IACzB,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AAED,MAAM,MAAM,cAAc,GAAG;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AAED,MAAM,MAAM,WAAW,GAAG;IACxB,MAAM,EAAE;QACN,CAAC,SAAS,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAAA;KACxC,CAAA;IACD,YAAY,EAAE;QACZ,CAAC,SAAS,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAAA;KACxC,CAAA;IACD,MAAM,EAAE;QACN,CAAC,SAAS,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAAA;KACxC,CAAA;IACD,cAAc,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;IAC3B,OAAO,EAAE;QACP,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAC1C,CAAA;IACD,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;IAClC,eAAe,EAAE,cAAc,EAAE,CAAA;IACjC,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;IACxC,qBAAqB,EAAE,oBAAoB,EAAE,CAAA;IAC7C,qBAAqB,EAAE,oBAAoB,EAAE,CAAA;IAC7C,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;IAC5B,OAAO,EAAE;QACP,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;KAC/C,CAAA;IACD,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;IAChC,aAAa,EAAE,YAAY,EAAE,CAAA;CAC9B,CAAA"}

View File

@@ -0,0 +1,2 @@
export { openFeatureIntegration, OpenFeatureIntegrationHook } from './integration';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getClientSchemaMap.js","names":["cache","buildClientFieldSchemaMap","cachedClientSchemaMap","global","_payload_clientSchemaMap","getClientSchemaMap","args","collectionSlug","config","globalSlug","i18n","payload","schemaMap","_payload_doNotCacheClientSchemaMap","Map","cachedEntityClientFieldMap","get","clientFieldSchemaMap","entityClientFieldMap","set"],"sources":["../../src/utilities/getClientSchemaMap.ts"],"sourcesContent":["import type { I18n, I18nClient } from '@payloadcms/translations'\nimport type { ClientConfig, ClientFieldSchemaMap, FieldSchemaMap, Payload } from 'payload'\n\nimport { cache } from 'react'\n\nimport { buildClientFieldSchemaMap } from './buildClientFieldSchemaMap/index.js'\n\nlet cachedClientSchemaMap = global._payload_clientSchemaMap\n\nif (!cachedClientSchemaMap) {\n cachedClientSchemaMap = global._payload_clientSchemaMap = null\n}\n\nexport const getClientSchemaMap = cache(\n (args: {\n collectionSlug?: string\n config: ClientConfig\n globalSlug?: string\n i18n: I18nClient\n payload: Payload\n schemaMap: FieldSchemaMap\n }): ClientFieldSchemaMap => {\n const { collectionSlug, config, globalSlug, i18n, payload, schemaMap } = args\n\n if (!cachedClientSchemaMap || global._payload_doNotCacheClientSchemaMap) {\n cachedClientSchemaMap = new Map()\n }\n\n let cachedEntityClientFieldMap = cachedClientSchemaMap.get(collectionSlug || globalSlug)\n\n if (cachedEntityClientFieldMap) {\n return cachedEntityClientFieldMap\n }\n\n cachedEntityClientFieldMap = new Map()\n\n const { clientFieldSchemaMap: entityClientFieldMap } = buildClientFieldSchemaMap({\n collectionSlug,\n config,\n globalSlug,\n i18n: i18n as I18n,\n payload,\n schemaMap,\n })\n\n cachedClientSchemaMap.set(collectionSlug || globalSlug, entityClientFieldMap)\n\n global._payload_clientSchemaMap = cachedClientSchemaMap\n\n global._payload_doNotCacheClientSchemaMap = false\n\n return entityClientFieldMap\n },\n)\n"],"mappings":"AAGA,SAASA,KAAK,QAAQ;AAEtB,SAASC,yBAAyB,QAAQ;AAE1C,IAAIC,qBAAA,GAAwBC,MAAA,CAAOC,wBAAwB;AAE3D,IAAI,CAACF,qBAAA,EAAuB;EAC1BA,qBAAA,GAAwBC,MAAA,CAAOC,wBAAwB,GAAG;AAC5D;AAEA,OAAO,MAAMC,kBAAA,GAAqBL,KAAA,CAC/BM,IAAA;EAQC,MAAM;IAAEC,cAAc;IAAEC,MAAM;IAAEC,UAAU;IAAEC,IAAI;IAAEC,OAAO;IAAEC;EAAS,CAAE,GAAGN,IAAA;EAEzE,IAAI,CAACJ,qBAAA,IAAyBC,MAAA,CAAOU,kCAAkC,EAAE;IACvEX,qBAAA,GAAwB,IAAIY,GAAA;EAC9B;EAEA,IAAIC,0BAAA,GAA6Bb,qBAAA,CAAsBc,GAAG,CAACT,cAAA,IAAkBE,UAAA;EAE7E,IAAIM,0BAAA,EAA4B;IAC9B,OAAOA,0BAAA;EACT;EAEAA,0BAAA,GAA6B,IAAID,GAAA;EAEjC,MAAM;IAAEG,oBAAA,EAAsBC;EAAoB,CAAE,GAAGjB,yBAAA,CAA0B;IAC/EM,cAAA;IACAC,MAAA;IACAC,UAAA;IACAC,IAAA,EAAMA,IAAA;IACNC,OAAA;IACAC;EACF;EAEAV,qBAAA,CAAsBiB,GAAG,CAACZ,cAAA,IAAkBE,UAAA,EAAYS,oBAAA;EAExDf,MAAA,CAAOC,wBAAwB,GAAGF,qBAAA;EAElCC,MAAA,CAAOU,kCAAkC,GAAG;EAE5C,OAAOK,oBAAA;AACT","ignoreList":[]}

View File

@@ -0,0 +1,33 @@
// Returns a wrapper function that returns a wrapped callback
// The wrapper function should do some stuff, and return a
// presumably different callback function.
// This makes sure that own properties are retained, so that
// decorations and such are not lost along the way.
module.exports = wrappy
function wrappy (fn, cb) {
if (fn && cb) return wrappy(fn)(cb)
if (typeof fn !== 'function')
throw new TypeError('need wrapper function')
Object.keys(fn).forEach(function (k) {
wrapper[k] = fn[k]
})
return wrapper
function wrapper() {
var args = new Array(arguments.length)
for (var i = 0; i < args.length; i++) {
args[i] = arguments[i]
}
var ret = fn.apply(this, args)
var cb = args[args.length-1]
if (typeof ret === 'function' && ret !== cb) {
Object.keys(cb).forEach(function (k) {
ret[k] = cb[k]
})
}
return ret
}
}

View File

@@ -0,0 +1,68 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { cleanUp } = require("./ErrorHelpers");
const WebpackError = require("./WebpackError");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
class ModuleWarning extends WebpackError {
/**
* @param {Error} warning error thrown
* @param {{ from?: string | null }} info additional info
*/
constructor(warning, { from = null } = {}) {
let message = "Module Warning";
message += from ? ` (from ${from}):\n` : ": ";
if (warning && typeof warning === "object" && warning.message) {
message += warning.message;
} else if (warning) {
message += String(warning);
}
super(message);
/** @type {string} */
this.name = "ModuleWarning";
this.warning = warning;
this.details =
warning && typeof warning === "object" && warning.stack
? cleanUp(warning.stack, this.message)
: undefined;
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
write(this.warning);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context
*/
deserialize(context) {
const { read } = context;
this.warning = read();
super.deserialize(context);
}
}
makeSerializable(ModuleWarning, "webpack/lib/ModuleWarning");
/** @type {typeof ModuleWarning} */
module.exports = ModuleWarning;

View File

@@ -0,0 +1,9 @@
import React from 'react';
import './index.scss';
export declare const NavToggler: React.FC<{
children?: React.ReactNode;
className?: string;
id?: string;
tabIndex?: number;
}>;
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"getDocumentPermissions.js","names":["hasSavePermission","getHasSavePermission","isEditing","getIsEditing","docAccessOperation","docAccessOperationGlobal","logError","hasDraftsEnabled","getDocumentPermissions","args","id","collectionConfig","data","globalConfig","req","docPermissions","hasPublishPermission","collection","config","_status","update","err","payload","collectionSlug","slug","globalSlug"],"sources":["../../../src/views/Document/getDocumentPermissions.tsx"],"sourcesContent":["import type {\n Data,\n PayloadRequest,\n SanitizedCollectionConfig,\n SanitizedDocumentPermissions,\n SanitizedGlobalConfig,\n} from 'payload'\n\nimport {\n hasSavePermission as getHasSavePermission,\n isEditing as getIsEditing,\n} from '@payloadcms/ui/shared'\nimport { docAccessOperation, docAccessOperationGlobal, logError } from 'payload'\nimport { hasDraftsEnabled } from 'payload/shared'\n\nexport const getDocumentPermissions = async (args: {\n collectionConfig?: SanitizedCollectionConfig\n data: Data\n globalConfig?: SanitizedGlobalConfig\n /**\n * When called for creating a new document, id is not provided.\n */\n id?: number | string\n req: PayloadRequest\n}): Promise<{\n docPermissions: SanitizedDocumentPermissions\n hasPublishPermission: boolean\n hasSavePermission: boolean\n}> => {\n const { id, collectionConfig, data = {}, globalConfig, req } = args\n\n let docPermissions: SanitizedDocumentPermissions\n let hasPublishPermission = false\n\n if (collectionConfig) {\n try {\n docPermissions = await docAccessOperation({\n id,\n collection: {\n config: collectionConfig,\n },\n data: {\n ...data,\n _status: 'draft',\n },\n req,\n })\n\n if (hasDraftsEnabled(collectionConfig)) {\n hasPublishPermission = (\n await docAccessOperation({\n id,\n collection: {\n config: collectionConfig,\n },\n data: {\n ...data,\n _status: 'published',\n },\n req,\n })\n ).update\n }\n } catch (err) {\n logError({ err, payload: req.payload })\n }\n }\n\n if (globalConfig) {\n try {\n docPermissions = await docAccessOperationGlobal({\n data,\n globalConfig,\n req,\n })\n\n if (hasDraftsEnabled(globalConfig)) {\n hasPublishPermission = (\n await docAccessOperationGlobal({\n data: {\n ...data,\n _status: 'published',\n },\n globalConfig,\n req,\n })\n ).update\n }\n } catch (err) {\n logError({ err, payload: req.payload })\n }\n }\n\n const hasSavePermission = getHasSavePermission({\n collectionSlug: collectionConfig?.slug,\n docPermissions,\n globalSlug: globalConfig?.slug,\n isEditing: getIsEditing({\n id,\n collectionSlug: collectionConfig?.slug,\n globalSlug: globalConfig?.slug,\n }),\n })\n\n return {\n docPermissions,\n hasPublishPermission,\n hasSavePermission,\n }\n}\n"],"mappings":"AAQA,SACEA,iBAAA,IAAqBC,oBAAoB,EACzCC,SAAA,IAAaC,YAAY,QACpB;AACP,SAASC,kBAAkB,EAAEC,wBAAwB,EAAEC,QAAQ,QAAQ;AACvE,SAASC,gBAAgB,QAAQ;AAEjC,OAAO,MAAMC,sBAAA,GAAyB,MAAOC,IAAA;EAc3C,MAAM;IAAEC,EAAE;IAAEC,gBAAgB;IAAEC,IAAA,GAAO,CAAC,CAAC;IAAEC,YAAY;IAAEC;EAAG,CAAE,GAAGL,IAAA;EAE/D,IAAIM,cAAA;EACJ,IAAIC,oBAAA,GAAuB;EAE3B,IAAIL,gBAAA,EAAkB;IACpB,IAAI;MACFI,cAAA,GAAiB,MAAMX,kBAAA,CAAmB;QACxCM,EAAA;QACAO,UAAA,EAAY;UACVC,MAAA,EAAQP;QACV;QACAC,IAAA,EAAM;UACJ,GAAGA,IAAI;UACPO,OAAA,EAAS;QACX;QACAL;MACF;MAEA,IAAIP,gBAAA,CAAiBI,gBAAA,GAAmB;QACtCK,oBAAA,GAAuB,CACrB,MAAMZ,kBAAA,CAAmB;UACvBM,EAAA;UACAO,UAAA,EAAY;YACVC,MAAA,EAAQP;UACV;UACAC,IAAA,EAAM;YACJ,GAAGA,IAAI;YACPO,OAAA,EAAS;UACX;UACAL;QACF,EAAC,EACDM,MAAM;MACV;IACF,EAAE,OAAOC,GAAA,EAAK;MACZf,QAAA,CAAS;QAAEe,GAAA;QAAKC,OAAA,EAASR,GAAA,CAAIQ;MAAQ;IACvC;EACF;EAEA,IAAIT,YAAA,EAAc;IAChB,IAAI;MACFE,cAAA,GAAiB,MAAMV,wBAAA,CAAyB;QAC9CO,IAAA;QACAC,YAAA;QACAC;MACF;MAEA,IAAIP,gBAAA,CAAiBM,YAAA,GAAe;QAClCG,oBAAA,GAAuB,CACrB,MAAMX,wBAAA,CAAyB;UAC7BO,IAAA,EAAM;YACJ,GAAGA,IAAI;YACPO,OAAA,EAAS;UACX;UACAN,YAAA;UACAC;QACF,EAAC,EACDM,MAAM;MACV;IACF,EAAE,OAAOC,GAAA,EAAK;MACZf,QAAA,CAAS;QAAEe,GAAA;QAAKC,OAAA,EAASR,GAAA,CAAIQ;MAAQ;IACvC;EACF;EAEA,MAAMtB,iBAAA,GAAoBC,oBAAA,CAAqB;IAC7CsB,cAAA,EAAgBZ,gBAAA,EAAkBa,IAAA;IAClCT,cAAA;IACAU,UAAA,EAAYZ,YAAA,EAAcW,IAAA;IAC1BtB,SAAA,EAAWC,YAAA,CAAa;MACtBO,EAAA;MACAa,cAAA,EAAgBZ,gBAAA,EAAkBa,IAAA;MAClCC,UAAA,EAAYZ,YAAA,EAAcW;IAC5B;EACF;EAEA,OAAO;IACLT,cAAA;IACAC,oBAAA;IACAhB;EACF;AACF","ignoreList":[]}

View File

@@ -0,0 +1,75 @@
import type {CodeKeywordDefinition, KeywordErrorDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {_, nil, or, Code} from "../../compile/codegen"
import validTimestamp from "../../runtime/timestamp"
import {useFunc} from "../../compile/util"
import {checkMetadata} from "./metadata"
import {typeErrorMessage, typeErrorParams, _JTDTypeError} from "./error"
export type JTDTypeError = _JTDTypeError<"type", JTDType, JTDType>
export type IntType = "int8" | "uint8" | "int16" | "uint16" | "int32" | "uint32"
export const intRange: {[T in IntType]: [number, number, number]} = {
int8: [-128, 127, 3],
uint8: [0, 255, 3],
int16: [-32768, 32767, 5],
uint16: [0, 65535, 5],
int32: [-2147483648, 2147483647, 10],
uint32: [0, 4294967295, 10],
}
export type JTDType = "boolean" | "string" | "timestamp" | "float32" | "float64" | IntType
const error: KeywordErrorDefinition = {
message: (cxt) => typeErrorMessage(cxt, cxt.schema),
params: (cxt) => typeErrorParams(cxt, cxt.schema),
}
function timestampCode(cxt: KeywordCxt): Code {
const {gen, data, it} = cxt
const {timestamp, allowDate} = it.opts
if (timestamp === "date") return _`${data} instanceof Date `
const vts = useFunc(gen, validTimestamp)
const allowDateArg = allowDate ? _`, true` : nil
const validString = _`typeof ${data} == "string" && ${vts}(${data}${allowDateArg})`
return timestamp === "string" ? validString : or(_`${data} instanceof Date`, validString)
}
const def: CodeKeywordDefinition = {
keyword: "type",
schemaType: "string",
error,
code(cxt: KeywordCxt) {
checkMetadata(cxt)
const {data, schema, parentSchema, it} = cxt
let cond: Code
switch (schema) {
case "boolean":
case "string":
cond = _`typeof ${data} == ${schema}`
break
case "timestamp": {
cond = timestampCode(cxt)
break
}
case "float32":
case "float64":
cond = _`typeof ${data} == "number"`
break
default: {
const sch = schema as IntType
cond = _`typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)`
if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) {
if (sch === "uint32") cond = _`${cond} && ${data} >= 0`
} else {
const [min, max] = intRange[sch]
cond = _`${cond} && ${data} >= ${min} && ${data} <= ${max}`
}
}
}
cxt.pass(parentSchema.nullable ? or(_`${data} === null`, cond) : cond)
},
}
export default def

View File

@@ -0,0 +1,3 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9saWIvZWxlbWVudC1vZi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0IHR5cGUgRWxlbWVudE9mPFR5cGUgZXh0ZW5kcyByZWFkb25seSBhbnlbXT4gPSBUeXBlIGV4dGVuZHMgcmVhZG9ubHkgKGluZmVyIFZhbHVlcylbXSA/IFZhbHVlcyA6IG5ldmVyO1xuIl19

View File

@@ -0,0 +1,32 @@
var listCacheClear = require('./_listCacheClear'),
listCacheDelete = require('./_listCacheDelete'),
listCacheGet = require('./_listCacheGet'),
listCacheHas = require('./_listCacheHas'),
listCacheSet = require('./_listCacheSet');
/**
* Creates an list cache object.
*
* @private
* @constructor
* @param {Array} [entries] The key-value pairs to cache.
*/
function ListCache(entries) {
var index = -1,
length = entries == null ? 0 : entries.length;
this.clear();
while (++index < length) {
var entry = entries[index];
this.set(entry[0], entry[1]);
}
}
// Add methods to `ListCache`.
ListCache.prototype.clear = listCacheClear;
ListCache.prototype['delete'] = listCacheDelete;
ListCache.prototype.get = listCacheGet;
ListCache.prototype.has = listCacheHas;
ListCache.prototype.set = listCacheSet;
module.exports = ListCache;

View File

@@ -0,0 +1,8 @@
// This file is generated automatically by `scripts/build/fp.ts`. Please, don't change it.
import { getDay as fn } from "../getDay.mjs";
import { convertToFP } from "./_lib/convertToFP.mjs";
export const getDay = convertToFP(fn, 1);
// Fallback for modularized imports:
export default getDay;

View File

@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.listStyleImage = void 0;
var image_1 = require("../types/image");
exports.listStyleImage = {
name: 'list-style-image',
initialValue: 'none',
type: 0 /* VALUE */,
prefix: false,
parse: function (context, token) {
if (token.type === 20 /* IDENT_TOKEN */ && token.value === 'none') {
return null;
}
return image_1.image.parse(context, token);
}
};
//# sourceMappingURL=list-style-image.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"parseSearchParams.d.ts","sourceRoot":"","sources":["../../src/utilities/parseSearchParams.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAA;AAEjE,OAAO,KAAK,EAAE,MAAM,QAAQ,CAAA;AAE5B;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,YAAY,EAAE,uBAAuB,GAAG,EAAE,CAAC,QAAQ,CAOpF"}

View File

@@ -0,0 +1,9 @@
import type { Locale } from "./types.js";
/**
* @category Locales
* @summary Western Frisian locale (Netherlands).
* @language West Frisian
* @iso-639-2 fry
* @author Damon Asberg [@damon02](https://github.com/damon02)
*/
export declare const fy: Locale;

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/elements/Pagination/ClickableArrow/index.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,OAAO,CAAA;AAGzB,OAAO,cAAc,CAAA;AAIrB,MAAM,MAAM,mBAAmB,GAAG;IAChC,SAAS,CAAC,EAAE,MAAM,GAAG,OAAO,CAAA;IAC5B,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,UAAU,CAAC,EAAE,MAAM,IAAI,CAAA;CACxB,CAAA;AAED,eAAO,MAAM,cAAc,EAAE,KAAK,CAAC,EAAE,CAAC,mBAAmB,CAqBxD,CAAA"}

View File

@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _index = require("../generated/index.js");
var _default = exports.default = createTypeAnnotationBasedOnTypeof;
function createTypeAnnotationBasedOnTypeof(type) {
switch (type) {
case "string":
return (0, _index.stringTypeAnnotation)();
case "number":
return (0, _index.numberTypeAnnotation)();
case "undefined":
return (0, _index.voidTypeAnnotation)();
case "boolean":
return (0, _index.booleanTypeAnnotation)();
case "function":
return (0, _index.genericTypeAnnotation)((0, _index.identifier)("Function"));
case "object":
return (0, _index.genericTypeAnnotation)((0, _index.identifier)("Object"));
case "symbol":
return (0, _index.genericTypeAnnotation)((0, _index.identifier)("Symbol"));
case "bigint":
return (0, _index.anyTypeAnnotation)();
}
throw new Error("Invalid typeof value: " + type);
}
//# sourceMappingURL=createTypeAnnotationBasedOnTypeof.js.map

View File

@@ -0,0 +1,9 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dynamicAnchor_1 = require("./dynamicAnchor");
const dynamicRef_1 = require("./dynamicRef");
const recursiveAnchor_1 = require("./recursiveAnchor");
const recursiveRef_1 = require("./recursiveRef");
const dynamic = [dynamicAnchor_1.default, dynamicRef_1.default, recursiveAnchor_1.default, recursiveRef_1.default];
exports.default = dynamic;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,43 @@
# postgres-array [![tests](https://github.com/bendrucker/postgres-array/workflows/tests/badge.svg)](https://github.com/bendrucker/postgres-array/actions?query=workflow%3Atests)
> Parse postgres array columns
## Install
```
npm install --save postgres-array
```
## Usage
```js
const { parse } = require('postgres-array')
parse('{1,2,3}', (value) => parseInt(value, 10))
//=> [1, 2, 3]
```
## API
#### `parse(input, [transform])` -> `array`
##### input
*Required*
Type: `string`
A Postgres array string.
##### transform
Type: `function`
Default: `identity`
A function that transforms non-null values inserted into the array.
## License
MIT © [Ben Drucker](http://bendrucker.me)

View File

@@ -0,0 +1,90 @@
"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);
var date_exports = {};
__export(date_exports, {
MySqlDate: () => MySqlDate,
MySqlDateBuilder: () => MySqlDateBuilder,
MySqlDateString: () => MySqlDateString,
MySqlDateStringBuilder: () => MySqlDateStringBuilder,
date: () => date
});
module.exports = __toCommonJS(date_exports);
var import_entity = require("../../entity.cjs");
var import_utils = require("../../utils.cjs");
var import_common = require("./common.cjs");
class MySqlDateBuilder extends import_common.MySqlColumnBuilder {
static [import_entity.entityKind] = "MySqlDateBuilder";
constructor(name) {
super(name, "date", "MySqlDate");
}
/** @internal */
build(table) {
return new MySqlDate(table, this.config);
}
}
class MySqlDate extends import_common.MySqlColumn {
static [import_entity.entityKind] = "MySqlDate";
constructor(table, config) {
super(table, config);
}
getSQLType() {
return `date`;
}
mapFromDriverValue(value) {
return new Date(value);
}
}
class MySqlDateStringBuilder extends import_common.MySqlColumnBuilder {
static [import_entity.entityKind] = "MySqlDateStringBuilder";
constructor(name) {
super(name, "string", "MySqlDateString");
}
/** @internal */
build(table) {
return new MySqlDateString(
table,
this.config
);
}
}
class MySqlDateString extends import_common.MySqlColumn {
static [import_entity.entityKind] = "MySqlDateString";
constructor(table, config) {
super(table, config);
}
getSQLType() {
return `date`;
}
}
function date(a, b) {
const { name, config } = (0, import_utils.getColumnNameAndConfig)(a, b);
if (config?.mode === "string") {
return new MySqlDateStringBuilder(name);
}
return new MySqlDateBuilder(name);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
MySqlDate,
MySqlDateBuilder,
MySqlDateString,
MySqlDateStringBuilder,
date
});
//# sourceMappingURL=date.cjs.map

View File

@@ -0,0 +1,460 @@
/*
Copied from https://github.com/mathiasbynens/punycode.js/blob/ef3505c8abb5143a00d53ce59077c9f7f4b2ac47/punycode.js
Copyright Mathias Bynens <https://mathiasbynens.be/>
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.
*/
/* eslint callback-return: 0, no-bitwise: 0, eqeqeq: 0, prefer-arrow-callback: 0, object-shorthand: 0 */
'use strict';
/** Highest positive signed 32-bit float value */
const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
const base = 36;
const tMin = 1;
const tMax = 26;
const skew = 38;
const damp = 700;
const initialBias = 72;
const initialN = 128; // 0x80
const delimiter = '-'; // '\x2D'
/** Regular expressions */
const regexPunycode = /^xn--/;
const regexNonASCII = /[^\0-\x7F]/; // Note: U+007F DEL is excluded too.
const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
/** Error messages */
const errors = {
overflow: 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
};
/** Convenience shortcuts */
const baseMinusTMin = base - tMin;
const floor = Math.floor;
const stringFromCharCode = String.fromCharCode;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, callback) {
const result = [];
let length = array.length;
while (length--) {
result[length] = callback(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {String} A new string of characters returned by the callback
* function.
*/
function mapDomain(domain, callback) {
const parts = domain.split('@');
let result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
domain = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
domain = domain.replace(regexSeparators, '\x2E');
const labels = domain.split('.');
const encoded = map(labels, callback).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
const output = [];
let counter = 0;
const length = string.length;
while (counter < length) {
const value = string.charCodeAt(counter++);
if (value >= 0xd800 && value <= 0xdbff && counter < length) {
// It's a high surrogate, and there is a next character.
const extra = string.charCodeAt(counter++);
if ((extra & 0xfc00) == 0xdc00) {
// Low surrogate.
output.push(((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000);
} else {
// It's an unmatched surrogate; only append this code unit, in case the
// next code unit is the high surrogate of a surrogate pair.
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
const ucs2encode = codePoints => String.fromCodePoint(...codePoints);
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
const basicToDigit = function (codePoint) {
if (codePoint >= 0x30 && codePoint < 0x3a) {
return 26 + (codePoint - 0x30);
}
if (codePoint >= 0x41 && codePoint < 0x5b) {
return codePoint - 0x41;
}
if (codePoint >= 0x61 && codePoint < 0x7b) {
return codePoint - 0x61;
}
return base;
};
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
const digitToBasic = function (digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
};
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
const adapt = function (delta, numPoints, firstTime) {
let k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (; /* no initialization */ delta > (baseMinusTMin * tMax) >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + ((baseMinusTMin + 1) * delta) / (delta + skew));
};
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
const decode = function (input) {
// Don't use UCS-2.
const output = [];
const inputLength = input.length;
let i = 0;
let n = initialN;
let bias = initialBias;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
let basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (let j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (let index = basic > 0 ? basic + 1 : 0; index < inputLength /* no final expression */; ) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
const oldi = i;
for (let w = 1, k = base /* no condition */; ; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
const digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base) {
error('invalid-input');
}
if (digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (digit < t) {
break;
}
const baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
const out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output.
output.splice(i++, 0, n);
}
return String.fromCodePoint(...output);
};
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
const encode = function (input) {
const output = [];
// Convert the input in UCS-2 to an array of Unicode code points.
input = ucs2decode(input);
// Cache the length.
const inputLength = input.length;
// Initialize the state.
let n = initialN;
let delta = 0;
let bias = initialBias;
// Handle the basic code points.
for (const currentValue of input) {
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
const basicLength = output.length;
let handledCPCount = basicLength;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string with a delimiter unless it's empty.
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
let m = maxInt;
for (const currentValue of input) {
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow.
const handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (const currentValue of input) {
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue === n) {
// Represent delta as a generalized variable-length integer.
let q = delta;
for (let k = base /* no condition */; ; k += base) {
const t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (q < t) {
break;
}
const qMinusT = q - t;
const baseMinusT = base - t;
output.push(stringFromCharCode(digitToBasic(t + (qMinusT % baseMinusT), 0)));
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount === basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
};
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
const toUnicode = function (input) {
return mapDomain(input, function (string) {
return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
});
};
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
const toASCII = function (input) {
return mapDomain(input, function (string) {
return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
});
};
/*--------------------------------------------------------------------------*/
/** Define the public API */
const punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
version: '2.3.1',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
ucs2: {
decode: ucs2decode,
encode: ucs2encode
},
decode: decode,
encode: encode,
toASCII: toASCII,
toUnicode: toUnicode
};
module.exports = punycode;

View File

@@ -0,0 +1,888 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.serializeBase64 = exports.TrieBuilder = exports.BITS_32 = exports.BITS_16 = void 0;
var Trie_1 = require("./Trie");
var base64_arraybuffer_1 = require("base64-arraybuffer");
/**
* Trie2 constants, defining shift widths, index array lengths, etc.
*
* These are needed for the runtime macros but users can treat these as
* implementation details and skip to the actual public API further below.
*/
// const UTRIE2_OPTIONS_VALUE_BITS_MASK = 0x000f;
/** Number of code points per index-1 table entry. 2048=0x800 */
var UTRIE2_CP_PER_INDEX_1_ENTRY = 1 << Trie_1.UTRIE2_SHIFT_1;
/** The alignment size of a data block. Also the granularity for compaction. */
var UTRIE2_DATA_GRANULARITY = 1 << Trie_1.UTRIE2_INDEX_SHIFT;
/* Fixed layout of the first part of the index array. ------------------- */
/**
* The BMP part of the index-2 table is fixed and linear and starts at offset 0.
* Length=2048=0x800=0x10000>>UTRIE2_SHIFT_2.
*/
var UTRIE2_INDEX_2_OFFSET = 0;
var UTRIE2_MAX_INDEX_1_LENGTH = 0x100000 >> Trie_1.UTRIE2_SHIFT_1;
/*
* Fixed layout of the first part of the data array. -----------------------
* Starts with 4 blocks (128=0x80 entries) for ASCII.
*/
/**
* The illegal-UTF-8 data block follows the ASCII block, at offset 128=0x80.
* Used with linear access for single bytes 0..0xbf for simple error handling.
* Length 64=0x40, not UTRIE2_DATA_BLOCK_LENGTH.
*/
var UTRIE2_BAD_UTF8_DATA_OFFSET = 0x80;
/** The start of non-linear-ASCII data blocks, at offset 192=0xc0. */
var UTRIE2_DATA_START_OFFSET = 0xc0;
/* Building a Trie2 ---------------------------------------------------------- */
/*
* These definitions are mostly needed by utrie2_builder.c, but also by
* utrie2_get32() and utrie2_enum().
*/
/*
* At build time, leave a gap in the index-2 table,
* at least as long as the maximum lengths of the 2-byte UTF-8 index-2 table
* and the supplementary index-1 table.
* Round up to UTRIE2_INDEX_2_BLOCK_LENGTH for proper compacting.
*/
var UNEWTRIE2_INDEX_GAP_OFFSET = Trie_1.UTRIE2_INDEX_2_BMP_LENGTH;
var UNEWTRIE2_INDEX_GAP_LENGTH = (Trie_1.UTRIE2_UTF8_2B_INDEX_2_LENGTH + UTRIE2_MAX_INDEX_1_LENGTH + Trie_1.UTRIE2_INDEX_2_MASK) & ~Trie_1.UTRIE2_INDEX_2_MASK;
/**
* Maximum length of the build-time index-2 array.
* Maximum number of Unicode code points (0x110000) shifted right by UTRIE2_SHIFT_2,
* plus the part of the index-2 table for lead surrogate code points,
* plus the build-time index gap,
* plus the null index-2 block.
*/
var UNEWTRIE2_MAX_INDEX_2_LENGTH = (0x110000 >> Trie_1.UTRIE2_SHIFT_2) +
Trie_1.UTRIE2_LSCP_INDEX_2_LENGTH +
UNEWTRIE2_INDEX_GAP_LENGTH +
Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH;
var UNEWTRIE2_INDEX_1_LENGTH = 0x110000 >> Trie_1.UTRIE2_SHIFT_1;
/**
* Maximum length of the build-time data array.
* One entry per 0x110000 code points, plus the illegal-UTF-8 block and the null block,
* plus values for the 0x400 surrogate code units.
*/
var UNEWTRIE2_MAX_DATA_LENGTH = 0x110000 + 0x40 + 0x40 + 0x400;
/* Start with allocation of 16k data entries. */
var UNEWTRIE2_INITIAL_DATA_LENGTH = 1 << 14;
/* Grow about 8x each time. */
var UNEWTRIE2_MEDIUM_DATA_LENGTH = 1 << 17;
/** The null index-2 block, following the gap in the index-2 table. */
var UNEWTRIE2_INDEX_2_NULL_OFFSET = UNEWTRIE2_INDEX_GAP_OFFSET + UNEWTRIE2_INDEX_GAP_LENGTH;
/** The start of allocated index-2 blocks. */
var UNEWTRIE2_INDEX_2_START_OFFSET = UNEWTRIE2_INDEX_2_NULL_OFFSET + Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH;
/**
* The null data block.
* Length 64=0x40 even if UTRIE2_DATA_BLOCK_LENGTH is smaller,
* to work with 6-bit trail bytes from 2-byte UTF-8.
*/
var UNEWTRIE2_DATA_NULL_OFFSET = UTRIE2_DATA_START_OFFSET;
/** The start of allocated data blocks. */
var UNEWTRIE2_DATA_START_OFFSET = UNEWTRIE2_DATA_NULL_OFFSET + 0x40;
/**
* The start of data blocks for U+0800 and above.
* Below, compaction uses a block length of 64 for 2-byte UTF-8.
* From here on, compaction uses UTRIE2_DATA_BLOCK_LENGTH.
* Data values for 0x780 code points beyond ASCII.
*/
var UNEWTRIE2_DATA_0800_OFFSET = UNEWTRIE2_DATA_START_OFFSET + 0x780;
/**
* Maximum length of the runtime index array.
* Limited by its own 16-bit index values, and by uint16_t UTrie2Header.indexLength.
* (The actual maximum length is lower,
* (0x110000>>UTRIE2_SHIFT_2)+UTRIE2_UTF8_2B_INDEX_2_LENGTH+UTRIE2_MAX_INDEX_1_LENGTH.)
*/
var UTRIE2_MAX_INDEX_LENGTH = 0xffff;
/**
* Maximum length of the runtime data array.
* Limited by 16-bit index values that are left-shifted by UTRIE2_INDEX_SHIFT,
* and by uint16_t UTrie2Header.shiftedDataLength.
*/
var UTRIE2_MAX_DATA_LENGTH = 0xffff << Trie_1.UTRIE2_INDEX_SHIFT;
exports.BITS_16 = 16;
exports.BITS_32 = 32;
var isHighSurrogate = function (c) { return c >= 0xd800 && c <= 0xdbff; };
var equalInt = function (a, s, t, length) {
for (var i = 0; i < length; i++) {
if (a[s + i] !== a[t + i]) {
return false;
}
}
return true;
};
var TrieBuilder = /** @class */ (function () {
function TrieBuilder(initialValue, errorValue) {
if (initialValue === void 0) { initialValue = 0; }
if (errorValue === void 0) { errorValue = 0; }
this.initialValue = initialValue;
this.errorValue = errorValue;
this.highStart = 0x110000;
this.data = new Uint32Array(UNEWTRIE2_INITIAL_DATA_LENGTH);
this.dataCapacity = UNEWTRIE2_INITIAL_DATA_LENGTH;
this.highStart = 0x110000;
this.firstFreeBlock = 0; /* no free block in the list */
this.isCompacted = false;
this.index1 = new Uint32Array(UNEWTRIE2_INDEX_1_LENGTH);
this.index2 = new Uint32Array(UNEWTRIE2_MAX_INDEX_2_LENGTH);
/*
* Multi-purpose per-data-block table.
*
* Before compacting:
*
* Per-data-block reference counters/free-block list.
* 0: unused
* >0: reference counter (number of index-2 entries pointing here)
* <0: next free data block in free-block list
*
* While compacting:
*
* Map of adjusted indexes, used in compactData() and compactIndex2().
* Maps from original indexes to new ones.
*/
this.map = new Uint32Array(UNEWTRIE2_MAX_DATA_LENGTH >> Trie_1.UTRIE2_SHIFT_2);
/*
* preallocate and reset
* - ASCII
* - the bad-UTF-8-data block
* - the null data block
*/
var i, j;
for (i = 0; i < 0x80; ++i) {
this.data[i] = initialValue;
}
for (; i < 0xc0; ++i) {
this.data[i] = errorValue;
}
for (i = UNEWTRIE2_DATA_NULL_OFFSET; i < UNEWTRIE2_DATA_START_OFFSET; ++i) {
this.data[i] = initialValue;
}
this.dataNullOffset = UNEWTRIE2_DATA_NULL_OFFSET;
this.dataLength = UNEWTRIE2_DATA_START_OFFSET;
/* set the index-2 indexes for the 2=0x80>>UTRIE2_SHIFT_2 ASCII data blocks */
for (i = 0, j = 0; j < 0x80; ++i, j += Trie_1.UTRIE2_DATA_BLOCK_LENGTH) {
this.index2[i] = j;
this.map[i] = 1;
}
/* reference counts for the bad-UTF-8-data block */
for (; j < 0xc0; ++i, j += Trie_1.UTRIE2_DATA_BLOCK_LENGTH) {
this.map[i] = 0;
}
/*
* Reference counts for the null data block: all blocks except for the ASCII blocks.
* Plus 1 so that we don't drop this block during compaction.
* Plus as many as needed for lead surrogate code points.
*/
/* i==newTrie->dataNullOffset */
this.map[i++] = (0x110000 >> Trie_1.UTRIE2_SHIFT_2) - (0x80 >> Trie_1.UTRIE2_SHIFT_2) + 1 + Trie_1.UTRIE2_LSCP_INDEX_2_LENGTH;
j += Trie_1.UTRIE2_DATA_BLOCK_LENGTH;
for (; j < UNEWTRIE2_DATA_START_OFFSET; ++i, j += Trie_1.UTRIE2_DATA_BLOCK_LENGTH) {
this.map[i] = 0;
}
/*
* set the remaining indexes in the BMP index-2 block
* to the null data block
*/
for (i = 0x80 >> Trie_1.UTRIE2_SHIFT_2; i < Trie_1.UTRIE2_INDEX_2_BMP_LENGTH; ++i) {
this.index2[i] = UNEWTRIE2_DATA_NULL_OFFSET;
}
/*
* Fill the index gap with impossible values so that compaction
* does not overlap other index-2 blocks with the gap.
*/
for (i = 0; i < UNEWTRIE2_INDEX_GAP_LENGTH; ++i) {
this.index2[UNEWTRIE2_INDEX_GAP_OFFSET + i] = -1;
}
/* set the indexes in the null index-2 block */
for (i = 0; i < Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH; ++i) {
this.index2[UNEWTRIE2_INDEX_2_NULL_OFFSET + i] = UNEWTRIE2_DATA_NULL_OFFSET;
}
this.index2NullOffset = UNEWTRIE2_INDEX_2_NULL_OFFSET;
this.index2Length = UNEWTRIE2_INDEX_2_START_OFFSET;
/* set the index-1 indexes for the linear index-2 block */
for (i = 0, j = 0; i < Trie_1.UTRIE2_OMITTED_BMP_INDEX_1_LENGTH; ++i, j += Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH) {
this.index1[i] = j;
}
/* set the remaining index-1 indexes to the null index-2 block */
for (; i < UNEWTRIE2_INDEX_1_LENGTH; ++i) {
this.index1[i] = UNEWTRIE2_INDEX_2_NULL_OFFSET;
}
/*
* Preallocate and reset data for U+0080..U+07ff,
* for 2-byte UTF-8 which will be compacted in 64-blocks
* even if UTRIE2_DATA_BLOCK_LENGTH is smaller.
*/
for (i = 0x80; i < 0x800; i += Trie_1.UTRIE2_DATA_BLOCK_LENGTH) {
this.set(i, initialValue);
}
}
/**
* Set a value for a code point.
*
* @param c the code point
* @param value the value
*/
TrieBuilder.prototype.set = function (c, value) {
if (c < 0 || c > 0x10ffff) {
throw new Error('Invalid code point.');
}
this._set(c, true, value);
return this;
};
/**
* Set a value in a range of code points [start..end].
* All code points c with start<=c<=end will get the value if
* overwrite is TRUE or if the old value is the initial value.
*
* @param start the first code point to get the value
* @param end the last code point to get the value (inclusive)
* @param value the value
* @param overwrite flag for whether old non-initial values are to be overwritten
*/
TrieBuilder.prototype.setRange = function (start, end, value, overwrite) {
if (overwrite === void 0) { overwrite = false; }
/*
* repeat value in [start..end]
* mark index values for repeat-data blocks by setting bit 31 of the index values
* fill around existing values if any, if(overwrite)
*/
var block, rest, repeatBlock;
if (start > 0x10ffff || start < 0 || end > 0x10ffff || end < 0 || start > end) {
throw new Error('Invalid code point range.');
}
if (!overwrite && value === this.initialValue) {
return this; /* nothing to do */
}
if (this.isCompacted) {
throw new Error('Trie was already compacted');
}
var limit = end + 1;
if ((start & Trie_1.UTRIE2_DATA_MASK) !== 0) {
/* set partial block at [start..following block boundary[ */
block = this.getDataBlock(start, true);
var nextStart = (start + Trie_1.UTRIE2_DATA_BLOCK_LENGTH) & ~Trie_1.UTRIE2_DATA_MASK;
if (nextStart <= limit) {
this.fillBlock(block, start & Trie_1.UTRIE2_DATA_MASK, Trie_1.UTRIE2_DATA_BLOCK_LENGTH, value, this.initialValue, overwrite);
start = nextStart;
}
else {
this.fillBlock(block, start & Trie_1.UTRIE2_DATA_MASK, limit & Trie_1.UTRIE2_DATA_MASK, value, this.initialValue, overwrite);
return this;
}
}
/* number of positions in the last, partial block */
rest = limit & Trie_1.UTRIE2_DATA_MASK;
/* round down limit to a block boundary */
limit &= ~Trie_1.UTRIE2_DATA_MASK;
/* iterate over all-value blocks */
repeatBlock = value === this.initialValue ? this.dataNullOffset : -1;
while (start < limit) {
var i2 = void 0;
var setRepeatBlock = false;
if (value === this.initialValue && this.isInNullBlock(start, true)) {
start += Trie_1.UTRIE2_DATA_BLOCK_LENGTH; /* nothing to do */
continue;
}
/* get index value */
i2 = this.getIndex2Block(start, true);
i2 += (start >> Trie_1.UTRIE2_SHIFT_2) & Trie_1.UTRIE2_INDEX_2_MASK;
block = this.index2[i2];
if (this.isWritableBlock(block)) {
/* already allocated */
if (overwrite && block >= UNEWTRIE2_DATA_0800_OFFSET) {
/*
* We overwrite all values, and it's not a
* protected (ASCII-linear or 2-byte UTF-8) block:
* replace with the repeatBlock.
*/
setRepeatBlock = true;
}
else {
/* !overwrite, or protected block: just write the values into this block */
this.fillBlock(block, 0, Trie_1.UTRIE2_DATA_BLOCK_LENGTH, value, this.initialValue, overwrite);
}
}
else if (this.data[block] !== value && (overwrite || block === this.dataNullOffset)) {
/*
* Set the repeatBlock instead of the null block or previous repeat block:
*
* If !isWritableBlock() then all entries in the block have the same value
* because it's the null block or a range block (the repeatBlock from a previous
* call to utrie2_setRange32()).
* No other blocks are used multiple times before compacting.
*
* The null block is the only non-writable block with the initialValue because
* of the repeatBlock initialization above. (If value==initialValue, then
* the repeatBlock will be the null data block.)
*
* We set our repeatBlock if the desired value differs from the block's value,
* and if we overwrite any data or if the data is all initial values
* (which is the same as the block being the null block, see above).
*/
setRepeatBlock = true;
}
if (setRepeatBlock) {
if (repeatBlock >= 0) {
this.setIndex2Entry(i2, repeatBlock);
}
else {
/* create and set and fill the repeatBlock */
repeatBlock = this.getDataBlock(start, true);
this.writeBlock(repeatBlock, value);
}
}
start += Trie_1.UTRIE2_DATA_BLOCK_LENGTH;
}
if (rest > 0) {
/* set partial block at [last block boundary..limit[ */
block = this.getDataBlock(start, true);
this.fillBlock(block, 0, rest, value, this.initialValue, overwrite);
}
return this;
};
/**
* Get the value for a code point as stored in the Trie2.
*
* @param codePoint the code point
* @return the value
*/
TrieBuilder.prototype.get = function (codePoint) {
if (codePoint < 0 || codePoint > 0x10ffff) {
return this.errorValue;
}
else {
return this._get(codePoint, true);
}
};
TrieBuilder.prototype._get = function (c, fromLSCP) {
var i2;
if (c >= this.highStart && (!(c >= 0xd800 && c < 0xdc00) || fromLSCP)) {
return this.data[this.dataLength - UTRIE2_DATA_GRANULARITY];
}
if (c >= 0xd800 && c < 0xdc00 && fromLSCP) {
i2 = Trie_1.UTRIE2_LSCP_INDEX_2_OFFSET - (0xd800 >> Trie_1.UTRIE2_SHIFT_2) + (c >> Trie_1.UTRIE2_SHIFT_2);
}
else {
i2 = this.index1[c >> Trie_1.UTRIE2_SHIFT_1] + ((c >> Trie_1.UTRIE2_SHIFT_2) & Trie_1.UTRIE2_INDEX_2_MASK);
}
var block = this.index2[i2];
return this.data[block + (c & Trie_1.UTRIE2_DATA_MASK)];
};
TrieBuilder.prototype.freeze = function (valueBits) {
if (valueBits === void 0) { valueBits = exports.BITS_32; }
var i;
var allIndexesLength;
var dataMove; /* >0 if the data is moved to the end of the index array */
/* compact if necessary */
if (!this.isCompacted) {
this.compactTrie();
}
allIndexesLength = this.highStart <= 0x10000 ? Trie_1.UTRIE2_INDEX_1_OFFSET : this.index2Length;
if (valueBits === exports.BITS_16) {
// dataMove = allIndexesLength;
dataMove = 0;
}
else {
dataMove = 0;
}
/* are indexLength and dataLength within limits? */
if (
/* for unshifted indexLength */
allIndexesLength > UTRIE2_MAX_INDEX_LENGTH ||
/* for unshifted dataNullOffset */
dataMove + this.dataNullOffset > 0xffff ||
/* for unshifted 2-byte UTF-8 index-2 values */
dataMove + UNEWTRIE2_DATA_0800_OFFSET > 0xffff ||
/* for shiftedDataLength */
dataMove + this.dataLength > UTRIE2_MAX_DATA_LENGTH) {
throw new Error('Trie data is too large.');
}
var index = new Uint16Array(allIndexesLength);
/* write the index-2 array values shifted right by UTRIE2_INDEX_SHIFT, after adding dataMove */
var destIdx = 0;
for (i = 0; i < Trie_1.UTRIE2_INDEX_2_BMP_LENGTH; i++) {
index[destIdx++] = (this.index2[i] + dataMove) >> Trie_1.UTRIE2_INDEX_SHIFT;
}
/* write UTF-8 2-byte index-2 values, not right-shifted */
for (i = 0; i < 0xc2 - 0xc0; ++i) {
/* C0..C1 */
index[destIdx++] = dataMove + UTRIE2_BAD_UTF8_DATA_OFFSET;
}
for (; i < 0xe0 - 0xc0; ++i) {
/* C2..DF */
index[destIdx++] = dataMove + this.index2[i << (6 - Trie_1.UTRIE2_SHIFT_2)];
}
if (this.highStart > 0x10000) {
var index1Length = (this.highStart - 0x10000) >> Trie_1.UTRIE2_SHIFT_1;
var index2Offset = Trie_1.UTRIE2_INDEX_2_BMP_LENGTH + Trie_1.UTRIE2_UTF8_2B_INDEX_2_LENGTH + index1Length;
/* write 16-bit index-1 values for supplementary code points */
for (i = 0; i < index1Length; i++) {
index[destIdx++] = UTRIE2_INDEX_2_OFFSET + this.index1[i + Trie_1.UTRIE2_OMITTED_BMP_INDEX_1_LENGTH];
}
/*
* write the index-2 array values for supplementary code points,
* shifted right by UTRIE2_INDEX_SHIFT, after adding dataMove
*/
for (i = 0; i < this.index2Length - index2Offset; i++) {
index[destIdx++] = (dataMove + this.index2[index2Offset + i]) >> Trie_1.UTRIE2_INDEX_SHIFT;
}
}
/* write the 16/32-bit data array */
switch (valueBits) {
case exports.BITS_16:
/* write 16-bit data values */
var data16 = new Uint16Array(this.dataLength);
for (i = 0; i < this.dataLength; i++) {
data16[i] = this.data[i];
}
return new Trie_1.Trie(this.initialValue, this.errorValue, this.highStart, dataMove + this.dataLength - UTRIE2_DATA_GRANULARITY, index, data16);
case exports.BITS_32:
/* write 32-bit data values */
var data32 = new Uint32Array(this.dataLength);
for (i = 0; i < this.dataLength; i++) {
data32[i] = this.data[i];
}
return new Trie_1.Trie(this.initialValue, this.errorValue, this.highStart, dataMove + this.dataLength - UTRIE2_DATA_GRANULARITY, index, data32);
default:
throw new Error('Bits should be either 16 or 32');
}
};
/*
* Find the start of the last range in the trie by enumerating backward.
* Indexes for supplementary code points higher than this will be omitted.
*/
TrieBuilder.prototype.findHighStart = function (highValue) {
var value;
var i2, j, i2Block, prevI2Block, block, prevBlock;
/* set variables for previous range */
if (highValue === this.initialValue) {
prevI2Block = this.index2NullOffset;
prevBlock = this.dataNullOffset;
}
else {
prevI2Block = -1;
prevBlock = -1;
}
var prev = 0x110000;
/* enumerate index-2 blocks */
var i1 = UNEWTRIE2_INDEX_1_LENGTH;
var c = prev;
while (c > 0) {
i2Block = this.index1[--i1];
if (i2Block === prevI2Block) {
/* the index-2 block is the same as the previous one, and filled with highValue */
c -= UTRIE2_CP_PER_INDEX_1_ENTRY;
continue;
}
prevI2Block = i2Block;
if (i2Block === this.index2NullOffset) {
/* this is the null index-2 block */
if (highValue !== this.initialValue) {
return c;
}
c -= UTRIE2_CP_PER_INDEX_1_ENTRY;
}
else {
/* enumerate data blocks for one index-2 block */
for (i2 = Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH; i2 > 0;) {
block = this.index2[i2Block + --i2];
if (block === prevBlock) {
/* the block is the same as the previous one, and filled with highValue */
c -= Trie_1.UTRIE2_DATA_BLOCK_LENGTH;
continue;
}
prevBlock = block;
if (block === this.dataNullOffset) {
/* this is the null data block */
if (highValue !== this.initialValue) {
return c;
}
c -= Trie_1.UTRIE2_DATA_BLOCK_LENGTH;
}
else {
for (j = Trie_1.UTRIE2_DATA_BLOCK_LENGTH; j > 0;) {
value = this.data[block + --j];
if (value !== highValue) {
return c;
}
--c;
}
}
}
}
}
/* deliver last range */
return 0;
};
/*
* Compact a build-time trie.
*
* The compaction
* - removes blocks that are identical with earlier ones
* - overlaps adjacent blocks as much as possible (if overlap==TRUE)
* - moves blocks in steps of the data granularity
* - moves and overlaps blocks that overlap with multiple values in the overlap region
*
* It does not
* - try to move and overlap blocks that are not already adjacent
*/
TrieBuilder.prototype.compactData = function () {
var start, movedStart;
var blockLength, overlap;
var i, mapIndex, blockCount;
/* do not compact linear-ASCII data */
var newStart = UTRIE2_DATA_START_OFFSET;
for (start = 0, i = 0; start < newStart; start += Trie_1.UTRIE2_DATA_BLOCK_LENGTH, ++i) {
this.map[i] = start;
}
/*
* Start with a block length of 64 for 2-byte UTF-8,
* then switch to UTRIE2_DATA_BLOCK_LENGTH.
*/
blockLength = 64;
blockCount = blockLength >> Trie_1.UTRIE2_SHIFT_2;
for (start = newStart; start < this.dataLength;) {
/*
* start: index of first entry of current block
* newStart: index where the current block is to be moved
* (right after current end of already-compacted data)
*/
if (start === UNEWTRIE2_DATA_0800_OFFSET) {
blockLength = Trie_1.UTRIE2_DATA_BLOCK_LENGTH;
blockCount = 1;
}
/* skip blocks that are not used */
if (this.map[start >> Trie_1.UTRIE2_SHIFT_2] <= 0) {
/* advance start to the next block */
start += blockLength;
/* leave newStart with the previous block! */
continue;
}
/* search for an identical block */
movedStart = this.findSameDataBlock(newStart, start, blockLength);
if (movedStart >= 0) {
/* found an identical block, set the other block's index value for the current block */
for (i = blockCount, mapIndex = start >> Trie_1.UTRIE2_SHIFT_2; i > 0; --i) {
this.map[mapIndex++] = movedStart;
movedStart += Trie_1.UTRIE2_DATA_BLOCK_LENGTH;
}
/* advance start to the next block */
start += blockLength;
/* leave newStart with the previous block! */
continue;
}
/* see if the beginning of this block can be overlapped with the end of the previous block */
/* look for maximum overlap (modulo granularity) with the previous, adjacent block */
for (overlap = blockLength - UTRIE2_DATA_GRANULARITY; overlap > 0 && !equalInt(this.data, newStart - overlap, start, overlap); overlap -= UTRIE2_DATA_GRANULARITY) { }
if (overlap > 0 || newStart < start) {
/* some overlap, or just move the whole block */
movedStart = newStart - overlap;
for (i = blockCount, mapIndex = start >> Trie_1.UTRIE2_SHIFT_2; i > 0; --i) {
this.map[mapIndex++] = movedStart;
movedStart += Trie_1.UTRIE2_DATA_BLOCK_LENGTH;
}
/* move the non-overlapping indexes to their new positions */
start += overlap;
for (i = blockLength - overlap; i > 0; --i) {
this.data[newStart++] = this.data[start++];
}
}
else {
/* no overlap && newStart==start */
for (i = blockCount, mapIndex = start >> Trie_1.UTRIE2_SHIFT_2; i > 0; --i) {
this.map[mapIndex++] = start;
start += Trie_1.UTRIE2_DATA_BLOCK_LENGTH;
}
newStart = start;
}
}
/* now adjust the index-2 table */
for (i = 0; i < this.index2Length; ++i) {
if (i === UNEWTRIE2_INDEX_GAP_OFFSET) {
/* Gap indexes are invalid (-1). Skip over the gap. */
i += UNEWTRIE2_INDEX_GAP_LENGTH;
}
this.index2[i] = this.map[this.index2[i] >> Trie_1.UTRIE2_SHIFT_2];
}
this.dataNullOffset = this.map[this.dataNullOffset >> Trie_1.UTRIE2_SHIFT_2];
/* ensure dataLength alignment */
while ((newStart & (UTRIE2_DATA_GRANULARITY - 1)) !== 0) {
this.data[newStart++] = this.initialValue;
}
this.dataLength = newStart;
};
TrieBuilder.prototype.findSameDataBlock = function (dataLength, otherBlock, blockLength) {
var block = 0;
/* ensure that we do not even partially get past dataLength */
dataLength -= blockLength;
for (; block <= dataLength; block += UTRIE2_DATA_GRANULARITY) {
if (equalInt(this.data, block, otherBlock, blockLength)) {
return block;
}
}
return -1;
};
TrieBuilder.prototype.compactTrie = function () {
var highValue = this.get(0x10ffff);
/* find highStart and round it up */
var localHighStart = this.findHighStart(highValue);
localHighStart = (localHighStart + (UTRIE2_CP_PER_INDEX_1_ENTRY - 1)) & ~(UTRIE2_CP_PER_INDEX_1_ENTRY - 1);
if (localHighStart === 0x110000) {
highValue = this.errorValue;
}
/*
* Set trie->highStart only after utrie2_get32(trie, highStart).
* Otherwise utrie2_get32(trie, highStart) would try to read the highValue.
*/
this.highStart = localHighStart;
if (this.highStart < 0x110000) {
/* Blank out [highStart..10ffff] to release associated data blocks. */
var suppHighStart = this.highStart <= 0x10000 ? 0x10000 : this.highStart;
this.setRange(suppHighStart, 0x10ffff, this.initialValue, true);
}
this.compactData();
if (this.highStart > 0x10000) {
this.compactIndex2();
}
/*
* Store the highValue in the data array and round up the dataLength.
* Must be done after compactData() because that assumes that dataLength
* is a multiple of UTRIE2_DATA_BLOCK_LENGTH.
*/
this.data[this.dataLength++] = highValue;
while ((this.dataLength & (UTRIE2_DATA_GRANULARITY - 1)) !== 0) {
this.data[this.dataLength++] = this.initialValue;
}
this.isCompacted = true;
};
TrieBuilder.prototype.compactIndex2 = function () {
var i, start, movedStart, overlap;
/* do not compact linear-BMP index-2 blocks */
var newStart = Trie_1.UTRIE2_INDEX_2_BMP_LENGTH;
for (start = 0, i = 0; start < newStart; start += Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH, ++i) {
this.map[i] = start;
}
/* Reduce the index table gap to what will be needed at runtime. */
newStart += Trie_1.UTRIE2_UTF8_2B_INDEX_2_LENGTH + ((this.highStart - 0x10000) >> Trie_1.UTRIE2_SHIFT_1);
for (start = UNEWTRIE2_INDEX_2_NULL_OFFSET; start < this.index2Length;) {
/*
* start: index of first entry of current block
* newStart: index where the current block is to be moved
* (right after current end of already-compacted data)
*/
/* search for an identical block */
if ((movedStart = this.findSameIndex2Block(newStart, start)) >= 0) {
/* found an identical block, set the other block's index value for the current block */
this.map[start >> Trie_1.UTRIE2_SHIFT_1_2] = movedStart;
/* advance start to the next block */
start += Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH;
/* leave newStart with the previous block! */
continue;
}
/* see if the beginning of this block can be overlapped with the end of the previous block */
/* look for maximum overlap with the previous, adjacent block */
for (overlap = Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH - 1; overlap > 0 && !equalInt(this.index2, newStart - overlap, start, overlap); --overlap) { }
if (overlap > 0 || newStart < start) {
/* some overlap, or just move the whole block */
this.map[start >> Trie_1.UTRIE2_SHIFT_1_2] = newStart - overlap;
/* move the non-overlapping indexes to their new positions */
start += overlap;
for (i = Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH - overlap; i > 0; --i) {
this.index2[newStart++] = this.index2[start++];
}
}
else {
/* no overlap && newStart==start */ this.map[start >> Trie_1.UTRIE2_SHIFT_1_2] = start;
start += Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH;
newStart = start;
}
}
/* now adjust the index-1 table */
for (i = 0; i < UNEWTRIE2_INDEX_1_LENGTH; ++i) {
this.index1[i] = this.map[this.index1[i] >> Trie_1.UTRIE2_SHIFT_1_2];
}
this.index2NullOffset = this.map[this.index2NullOffset >> Trie_1.UTRIE2_SHIFT_1_2];
/*
* Ensure data table alignment:
* Needs to be granularity-aligned for 16-bit trie
* (so that dataMove will be down-shiftable),
* and 2-aligned for uint32_t data.
*/
while ((newStart & ((UTRIE2_DATA_GRANULARITY - 1) | 1)) !== 0) {
/* Arbitrary value: 0x3fffc not possible for real data. */
this.index2[newStart++] = 0x0000ffff << Trie_1.UTRIE2_INDEX_SHIFT;
}
this.index2Length = newStart;
};
TrieBuilder.prototype.findSameIndex2Block = function (index2Length, otherBlock) {
/* ensure that we do not even partially get past index2Length */
index2Length -= Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH;
for (var block = 0; block <= index2Length; ++block) {
if (equalInt(this.index2, block, otherBlock, Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH)) {
return block;
}
}
return -1;
};
TrieBuilder.prototype._set = function (c, forLSCP, value) {
if (this.isCompacted) {
throw new Error('Trie was already compacted');
}
var block = this.getDataBlock(c, forLSCP);
this.data[block + (c & Trie_1.UTRIE2_DATA_MASK)] = value;
return this;
};
TrieBuilder.prototype.writeBlock = function (block, value) {
var limit = block + Trie_1.UTRIE2_DATA_BLOCK_LENGTH;
while (block < limit) {
this.data[block++] = value;
}
};
TrieBuilder.prototype.isInNullBlock = function (c, forLSCP) {
var i2 = isHighSurrogate(c) && forLSCP
? Trie_1.UTRIE2_LSCP_INDEX_2_OFFSET - (0xd800 >> Trie_1.UTRIE2_SHIFT_2) + (c >> Trie_1.UTRIE2_SHIFT_2)
: this.index1[c >> Trie_1.UTRIE2_SHIFT_1] + ((c >> Trie_1.UTRIE2_SHIFT_2) & Trie_1.UTRIE2_INDEX_2_MASK);
var block = this.index2[i2];
return block === this.dataNullOffset;
};
TrieBuilder.prototype.fillBlock = function (block, start, limit, value, initialValue, overwrite) {
var pLimit = block + limit;
if (overwrite) {
for (var i = block + start; i < pLimit; i++) {
this.data[i] = value;
}
}
else {
for (var i = block + start; i < pLimit; i++) {
if (this.data[i] === initialValue) {
this.data[i] = value;
}
}
}
};
TrieBuilder.prototype.setIndex2Entry = function (i2, block) {
++this.map[block >> Trie_1.UTRIE2_SHIFT_2]; /* increment first, in case block==oldBlock! */
var oldBlock = this.index2[i2];
if (0 === --this.map[oldBlock >> Trie_1.UTRIE2_SHIFT_2]) {
this.releaseDataBlock(oldBlock);
}
this.index2[i2] = block;
};
TrieBuilder.prototype.releaseDataBlock = function (block) {
/* put this block at the front of the free-block chain */
this.map[block >> Trie_1.UTRIE2_SHIFT_2] = -this.firstFreeBlock;
this.firstFreeBlock = block;
};
TrieBuilder.prototype.getDataBlock = function (c, forLSCP) {
var i2 = this.getIndex2Block(c, forLSCP);
i2 += (c >> Trie_1.UTRIE2_SHIFT_2) & Trie_1.UTRIE2_INDEX_2_MASK;
var oldBlock = this.index2[i2];
if (this.isWritableBlock(oldBlock)) {
return oldBlock;
}
/* allocate a new data block */
var newBlock = this.allocDataBlock(oldBlock);
this.setIndex2Entry(i2, newBlock);
return newBlock;
};
TrieBuilder.prototype.isWritableBlock = function (block) {
return block !== this.dataNullOffset && 1 === this.map[block >> Trie_1.UTRIE2_SHIFT_2];
};
TrieBuilder.prototype.getIndex2Block = function (c, forLSCP) {
if (c >= 0xd800 && c < 0xdc00 && forLSCP) {
return Trie_1.UTRIE2_LSCP_INDEX_2_OFFSET;
}
var i1 = c >> Trie_1.UTRIE2_SHIFT_1;
var i2 = this.index1[i1];
if (i2 === this.index2NullOffset) {
i2 = this.allocIndex2Block();
this.index1[i1] = i2;
}
return i2;
};
TrieBuilder.prototype.allocDataBlock = function (copyBlock) {
var newBlock;
if (this.firstFreeBlock !== 0) {
/* get the first free block */
newBlock = this.firstFreeBlock;
this.firstFreeBlock = -this.map[newBlock >> Trie_1.UTRIE2_SHIFT_2];
}
else {
/* get a new block from the high end */
newBlock = this.dataLength;
var newTop = newBlock + Trie_1.UTRIE2_DATA_BLOCK_LENGTH;
if (newTop > this.dataCapacity) {
var capacity = void 0;
/* out of memory in the data array */
if (this.dataCapacity < UNEWTRIE2_MEDIUM_DATA_LENGTH) {
capacity = UNEWTRIE2_MEDIUM_DATA_LENGTH;
}
else if (this.dataCapacity < UNEWTRIE2_MAX_DATA_LENGTH) {
capacity = UNEWTRIE2_MAX_DATA_LENGTH;
}
else {
/*
* Should never occur.
* Either UNEWTRIE2_MAX_DATA_LENGTH is incorrect,
* or the code writes more values than should be possible.
*/
throw new Error('Internal error in Trie creation.');
}
var newData = new Uint32Array(capacity);
newData.set(this.data.subarray(0, this.dataLength));
this.data = newData;
this.dataCapacity = capacity;
}
this.dataLength = newTop;
}
this.data.set(this.data.subarray(copyBlock, copyBlock + Trie_1.UTRIE2_DATA_BLOCK_LENGTH), newBlock);
this.map[newBlock >> Trie_1.UTRIE2_SHIFT_2] = 0;
return newBlock;
};
TrieBuilder.prototype.allocIndex2Block = function () {
var newBlock = this.index2Length;
var newTop = newBlock + Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH;
if (newTop > this.index2.length) {
throw new Error('Internal error in Trie creation.');
/*
* Should never occur.
* Either UTRIE2_MAX_BUILD_TIME_INDEX_LENGTH is incorrect,
* or the code writes more values than should be possible.
*/
}
this.index2Length = newTop;
this.index2.set(this.index2.subarray(this.index2NullOffset, this.index2NullOffset + Trie_1.UTRIE2_INDEX_2_BLOCK_LENGTH), newBlock);
return newBlock;
};
return TrieBuilder;
}());
exports.TrieBuilder = TrieBuilder;
var serializeBase64 = function (trie) {
var index = trie.index;
var data = trie.data;
if (!(index instanceof Uint16Array) || !(data instanceof Uint16Array || data instanceof Uint32Array)) {
throw new Error('TrieBuilder serializer only support TypedArrays');
}
var headerLength = Uint32Array.BYTES_PER_ELEMENT * 6;
var bufferLength = headerLength + index.byteLength + data.byteLength;
var buffer = new ArrayBuffer(Math.ceil(bufferLength / 4) * 4);
var view32 = new Uint32Array(buffer);
var view16 = new Uint16Array(buffer);
view32[0] = trie.initialValue;
view32[1] = trie.errorValue;
view32[2] = trie.highStart;
view32[3] = trie.highValueIndex;
view32[4] = index.byteLength;
// $FlowFixMe
view32[5] = data.BYTES_PER_ELEMENT;
view16.set(index, headerLength / Uint16Array.BYTES_PER_ELEMENT);
if (data.BYTES_PER_ELEMENT === Uint16Array.BYTES_PER_ELEMENT) {
view16.set(data, (headerLength + index.byteLength) / Uint16Array.BYTES_PER_ELEMENT);
}
else {
view32.set(data, Math.ceil((headerLength + index.byteLength) / Uint32Array.BYTES_PER_ELEMENT));
}
return [base64_arraybuffer_1.encode(new Uint8Array(buffer)), buffer.byteLength];
};
exports.serializeBase64 = serializeBase64;
//# sourceMappingURL=TrieBuilder.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"addFeedbackBreadcrumb.d.ts","sourceRoot":"","sources":["../../../../../src/coreHandlers/util/addFeedbackBreadcrumb.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAElD,OAAO,KAAK,EAA8B,eAAe,EAAE,MAAM,aAAa,CAAC;AAE/E;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,eAAe,EAAE,KAAK,EAAE,aAAa,GAAG,IAAI,CA6BzF"}

View File

@@ -0,0 +1,35 @@
var baseClone = require('./_baseClone'),
baseConforms = require('./_baseConforms');
/** Used to compose bitmasks for cloning. */
var CLONE_DEEP_FLAG = 1;
/**
* Creates a function that invokes the predicate properties of `source` with
* the corresponding property values of a given object, returning `true` if
* all predicates return truthy, else `false`.
*
* **Note:** The created function is equivalent to `_.conformsTo` with
* `source` partially applied.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Util
* @param {Object} source The object of property predicates to conform to.
* @returns {Function} Returns the new spec function.
* @example
*
* var objects = [
* { 'a': 2, 'b': 1 },
* { 'a': 1, 'b': 2 }
* ];
*
* _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
* // => [{ 'a': 1, 'b': 2 }]
*/
function conforms(source) {
return baseConforms(baseClone(source, CLONE_DEEP_FLAG));
}
module.exports = conforms;

View File

@@ -0,0 +1 @@
{"version":3,"file":"LCPEntryManager.js","sources":["../../../../../src/metrics/web-vitals/lib/LCPEntryManager.ts"],"sourcesContent":["/*\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport class LCPEntryManager {\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility\n _onBeforeProcessingEntry?: (entry: LargestContentfulPaint) => void;\n\n // eslint-disable-next-line @typescript-eslint/explicit-member-accessibility, jsdoc/require-jsdoc\n _processEntry(entry: LargestContentfulPaint) {\n this._onBeforeProcessingEntry?.(entry);\n }\n}\n"],"names":[],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACO,MAAM,eAAA,CAAgB;AAC7B;;AAGA;AACA,EAAE,aAAa,CAAC,KAAK,EAA0B;AAC/C,IAAI,IAAI,CAAC,wBAAwB,GAAG,KAAK,CAAC;AAC1C,EAAE;AACF;;;;"}

View File

@@ -0,0 +1,5 @@
export declare const isWeekendWithOptions: import("./types.js").FPFn2<
boolean,
import("../isWeekend.js").IsWeekendOptions | undefined,
string | number | Date
>;

View File

@@ -0,0 +1,712 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Compiler = require("./Compiler");
const MultiCompiler = require("./MultiCompiler");
const NormalModule = require("./NormalModule");
const createSchemaValidation = require("./util/create-schema-validation");
const { contextify } = require("./util/identifier");
/** @typedef {import("tapable").Tap} Tap */
/**
* @template T, R, AdditionalOptions
* @typedef {import("tapable").Hook<T, R, AdditionalOptions>} Hook
*/
/** @typedef {import("../declarations/plugins/ProgressPlugin").ProgressPluginArgument} ProgressPluginArgument */
/** @typedef {import("./Compilation").FactorizeModuleOptions} FactorizeModuleOptions */
/** @typedef {import("./Dependency")} Dependency */
/** @typedef {import("./Entrypoint").EntryOptions} EntryOptions */
/** @typedef {import("./Module")} Module */
/** @typedef {import("./ModuleFactory").ModuleFactoryResult} ModuleFactoryResult */
/** @typedef {import("./logging/Logger").Logger} Logger */
/**
* @template T, K, R
* @typedef {import("./util/AsyncQueue")<T, K, R>} AsyncQueue
*/
/**
* @typedef {object} CountsData
* @property {number} modulesCount modules count
* @property {number} dependenciesCount dependencies count
*/
const validate = createSchemaValidation(
require("../schemas/plugins/ProgressPlugin.check"),
() => require("../schemas/plugins/ProgressPlugin.json"),
{
name: "Progress Plugin",
baseDataPath: "options"
}
);
/**
* @param {number} a a
* @param {number} b b
* @param {number} c c
* @returns {number} median
*/
const median3 = (a, b, c) => a + b + c - Math.max(a, b, c) - Math.min(a, b, c);
/** @typedef {(percentage: number, msg: string, ...args: string[]) => void} HandlerFn */
/**
* @param {boolean | null | undefined} profile need profile
* @param {Logger} logger logger
* @returns {HandlerFn} default handler
*/
const createDefaultHandler = (profile, logger) => {
/** @type {{ value: string | undefined, time: number }[]} */
const lastStateInfo = [];
/** @type {HandlerFn} */
const defaultHandler = (percentage, msg, ...args) => {
if (profile) {
if (percentage === 0) {
lastStateInfo.length = 0;
}
const fullState = [msg, ...args];
const state = fullState.map((s) => s.replace(/\d+\/\d+ /g, ""));
const now = Date.now();
const len = Math.max(state.length, lastStateInfo.length);
for (let i = len; i >= 0; i--) {
const stateItem = i < state.length ? state[i] : undefined;
const lastStateItem =
i < lastStateInfo.length ? lastStateInfo[i] : undefined;
if (lastStateItem) {
if (stateItem !== lastStateItem.value) {
const diff = now - lastStateItem.time;
if (lastStateItem.value) {
let reportState = lastStateItem.value;
if (i > 0) {
reportState = `${lastStateInfo[i - 1].value} > ${reportState}`;
}
const stateMsg = `${" | ".repeat(i)}${diff} ms ${reportState}`;
const d = diff;
// This depends on timing so we ignore it for coverage
/* eslint-disable no-lone-blocks */
/* istanbul ignore next */
{
if (d > 10000) {
logger.error(stateMsg);
} else if (d > 1000) {
logger.warn(stateMsg);
} else if (d > 10) {
logger.info(stateMsg);
} else if (d > 5) {
logger.log(stateMsg);
} else {
logger.debug(stateMsg);
}
}
/* eslint-enable no-lone-blocks */
}
if (stateItem === undefined) {
lastStateInfo.length = i;
} else {
lastStateItem.value = stateItem;
lastStateItem.time = now;
lastStateInfo.length = i + 1;
}
}
} else {
lastStateInfo[i] = {
value: stateItem,
time: now
};
}
}
}
logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args);
if (percentage === 1 || (!msg && args.length === 0)) logger.status();
};
return defaultHandler;
};
const SKIPPED_QUEUE_CONTEXTS = ["import-module", "load-module"];
/**
* @callback ReportProgress
* @param {number} p percentage
* @param {...string} args additional arguments
* @returns {void}
*/
/** @type {WeakMap<Compiler, ReportProgress | undefined>} */
const progressReporters = new WeakMap();
const PLUGIN_NAME = "ProgressPlugin";
class ProgressPlugin {
/**
* @param {Compiler} compiler the current compiler
* @returns {ReportProgress | undefined} a progress reporter, if any
*/
static getReporter(compiler) {
return progressReporters.get(compiler);
}
/**
* @param {ProgressPluginArgument} options options
*/
constructor(options = {}) {
if (typeof options === "function") {
options = {
handler: options
};
}
validate(options);
options = { ...ProgressPlugin.defaultOptions, ...options };
this.profile = options.profile;
this.handler = options.handler;
this.modulesCount = options.modulesCount;
this.dependenciesCount = options.dependenciesCount;
this.showEntries = options.entries;
this.showModules = options.modules;
this.showDependencies = options.dependencies;
this.showActiveModules = options.activeModules;
this.percentBy = options.percentBy;
}
/**
* @param {Compiler | MultiCompiler} compiler webpack compiler
* @returns {void}
*/
apply(compiler) {
const handler =
this.handler ||
createDefaultHandler(
this.profile,
compiler.getInfrastructureLogger("webpack.Progress")
);
if (compiler instanceof MultiCompiler) {
this._applyOnMultiCompiler(compiler, handler);
} else if (compiler instanceof Compiler) {
this._applyOnCompiler(compiler, handler);
}
}
/**
* @param {MultiCompiler} compiler webpack multi-compiler
* @param {HandlerFn} handler function that executes for every progress step
* @returns {void}
*/
_applyOnMultiCompiler(compiler, handler) {
const states = compiler.compilers.map(
() => /** @type {[number, ...string[]]} */ ([0])
);
for (const [idx, item] of compiler.compilers.entries()) {
new ProgressPlugin((p, msg, ...args) => {
states[idx] = [p, msg, ...args];
let sum = 0;
for (const [p] of states) sum += p;
handler(sum / states.length, `[${idx}] ${msg}`, ...args);
}).apply(item);
}
}
/**
* @param {Compiler} compiler webpack compiler
* @param {HandlerFn} handler function that executes for every progress step
* @returns {void}
*/
_applyOnCompiler(compiler, handler) {
const showEntries = this.showEntries;
const showModules = this.showModules;
const showDependencies = this.showDependencies;
const showActiveModules = this.showActiveModules;
let lastActiveModule = "";
let currentLoader = "";
let lastModulesCount = 0;
let lastDependenciesCount = 0;
let lastEntriesCount = 0;
let modulesCount = 0;
let skippedModulesCount = 0;
let dependenciesCount = 0;
let skippedDependenciesCount = 0;
let entriesCount = 1;
let doneModules = 0;
let doneDependencies = 0;
let doneEntries = 0;
/** @type {Set<string>} */
const activeModules = new Set();
let lastUpdate = 0;
const updateThrottled = () => {
if (lastUpdate + 500 < Date.now()) update();
};
const update = () => {
/** @type {string[]} */
const items = [];
const percentByModules =
doneModules /
Math.max(lastModulesCount || this.modulesCount || 1, modulesCount);
const percentByEntries =
doneEntries /
Math.max(lastEntriesCount || this.dependenciesCount || 1, entriesCount);
const percentByDependencies =
doneDependencies /
Math.max(lastDependenciesCount || 1, dependenciesCount);
/** @type {number} */
let percentageFactor;
switch (this.percentBy) {
case "entries":
percentageFactor = percentByEntries;
break;
case "dependencies":
percentageFactor = percentByDependencies;
break;
case "modules":
percentageFactor = percentByModules;
break;
default:
percentageFactor = median3(
percentByModules,
percentByEntries,
percentByDependencies
);
}
const percentage = 0.1 + percentageFactor * 0.55;
if (currentLoader) {
items.push(
`import loader ${contextify(
compiler.context,
currentLoader,
compiler.root
)}`
);
} else {
/** @type {string[]} */
const statItems = [];
if (showEntries) {
statItems.push(`${doneEntries}/${entriesCount} entries`);
}
if (showDependencies) {
statItems.push(
`${doneDependencies}/${dependenciesCount} dependencies`
);
}
if (showModules) {
statItems.push(`${doneModules}/${modulesCount} modules`);
}
if (showActiveModules) {
statItems.push(`${activeModules.size} active`);
}
if (statItems.length > 0) {
items.push(statItems.join(" "));
}
if (showActiveModules) {
items.push(lastActiveModule);
}
}
handler(percentage, "building", ...items);
lastUpdate = Date.now();
};
/**
* @template T
* @param {AsyncQueue<FactorizeModuleOptions, string, Module | ModuleFactoryResult>} factorizeQueue async queue
* @param {T} _item item
*/
const factorizeAdd = (factorizeQueue, _item) => {
if (SKIPPED_QUEUE_CONTEXTS.includes(factorizeQueue.getContext())) {
skippedDependenciesCount++;
}
dependenciesCount++;
if (dependenciesCount < 50 || dependenciesCount % 100 === 0) {
updateThrottled();
}
};
const factorizeDone = () => {
doneDependencies++;
if (doneDependencies < 50 || doneDependencies % 100 === 0) {
updateThrottled();
}
};
/**
* @template T
* @param {AsyncQueue<Module, string, Module>} addModuleQueue async queue
* @param {T} _item item
*/
const moduleAdd = (addModuleQueue, _item) => {
if (SKIPPED_QUEUE_CONTEXTS.includes(addModuleQueue.getContext())) {
skippedModulesCount++;
}
modulesCount++;
if (modulesCount < 50 || modulesCount % 100 === 0) updateThrottled();
};
// only used when showActiveModules is set
/**
* @param {Module} module the module
*/
const moduleBuild = (module) => {
const ident = module.identifier();
if (ident) {
activeModules.add(ident);
lastActiveModule = ident;
update();
}
};
/**
* @param {Dependency} entry entry dependency
* @param {EntryOptions} options options object
*/
const entryAdd = (entry, options) => {
entriesCount++;
if (entriesCount < 5 || entriesCount % 10 === 0) updateThrottled();
};
/**
* @param {Module} module the module
*/
const moduleDone = (module) => {
doneModules++;
if (showActiveModules) {
const ident = module.identifier();
if (ident) {
activeModules.delete(ident);
if (lastActiveModule === ident) {
lastActiveModule = "";
for (const m of activeModules) {
lastActiveModule = m;
}
update();
return;
}
}
}
if (doneModules < 50 || doneModules % 100 === 0) updateThrottled();
};
/**
* @param {Dependency} entry entry dependency
* @param {EntryOptions} options options object
*/
const entryDone = (entry, options) => {
doneEntries++;
update();
};
const cache = compiler.getCache(PLUGIN_NAME).getItemCache("counts", null);
/** @type {Promise<CountsData> | undefined} */
let cacheGetPromise;
compiler.hooks.beforeCompile.tap(PLUGIN_NAME, () => {
if (!cacheGetPromise) {
cacheGetPromise = cache.getPromise().then(
(data) => {
if (data) {
lastModulesCount = lastModulesCount || data.modulesCount;
lastDependenciesCount =
lastDependenciesCount || data.dependenciesCount;
}
return data;
},
(_err) => {
// Ignore error
}
);
}
});
compiler.hooks.afterCompile.tapPromise(PLUGIN_NAME, (compilation) => {
if (compilation.compiler.isChild()) return Promise.resolve();
return /** @type {Promise<CountsData>} */ (cacheGetPromise).then(
async (oldData) => {
const realModulesCount = modulesCount - skippedModulesCount;
const realDependenciesCount =
dependenciesCount - skippedDependenciesCount;
if (
!oldData ||
oldData.modulesCount !== realModulesCount ||
oldData.dependenciesCount !== realDependenciesCount
) {
await cache.storePromise({
modulesCount: realModulesCount,
dependenciesCount: realDependenciesCount
});
}
}
);
});
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
if (compilation.compiler.isChild()) return;
lastModulesCount = modulesCount;
lastEntriesCount = entriesCount;
lastDependenciesCount = dependenciesCount;
modulesCount =
skippedModulesCount =
dependenciesCount =
skippedDependenciesCount =
entriesCount =
0;
doneModules = doneDependencies = doneEntries = 0;
compilation.factorizeQueue.hooks.added.tap(PLUGIN_NAME, (item) =>
factorizeAdd(compilation.factorizeQueue, item)
);
compilation.factorizeQueue.hooks.result.tap(PLUGIN_NAME, factorizeDone);
compilation.addModuleQueue.hooks.added.tap(PLUGIN_NAME, (item) =>
moduleAdd(compilation.addModuleQueue, item)
);
compilation.processDependenciesQueue.hooks.result.tap(
PLUGIN_NAME,
moduleDone
);
if (showActiveModules) {
compilation.hooks.buildModule.tap(PLUGIN_NAME, moduleBuild);
}
compilation.hooks.addEntry.tap(PLUGIN_NAME, entryAdd);
compilation.hooks.failedEntry.tap(PLUGIN_NAME, entryDone);
compilation.hooks.succeedEntry.tap(PLUGIN_NAME, entryDone);
// @ts-expect-error avoid dynamic require if bundled with webpack
if (typeof __webpack_require__ !== "function") {
/** @type {Set<string>} */
const requiredLoaders = new Set();
NormalModule.getCompilationHooks(compilation).beforeLoaders.tap(
PLUGIN_NAME,
(loaders) => {
for (const loader of loaders) {
if (
loader.type !== "module" &&
!requiredLoaders.has(loader.loader)
) {
requiredLoaders.add(loader.loader);
currentLoader = loader.loader;
update();
require(loader.loader);
}
}
if (currentLoader) {
currentLoader = "";
update();
}
}
);
}
const hooks = {
finishModules: "finish module graph",
seal: "plugins",
optimizeDependencies: "dependencies optimization",
afterOptimizeDependencies: "after dependencies optimization",
beforeChunks: "chunk graph",
afterChunks: "after chunk graph",
optimize: "optimizing",
optimizeModules: "module optimization",
afterOptimizeModules: "after module optimization",
optimizeChunks: "chunk optimization",
afterOptimizeChunks: "after chunk optimization",
optimizeTree: "module and chunk tree optimization",
afterOptimizeTree: "after module and chunk tree optimization",
optimizeChunkModules: "chunk modules optimization",
afterOptimizeChunkModules: "after chunk modules optimization",
reviveModules: "module reviving",
beforeModuleIds: "before module ids",
moduleIds: "module ids",
optimizeModuleIds: "module id optimization",
afterOptimizeModuleIds: "module id optimization",
reviveChunks: "chunk reviving",
beforeChunkIds: "before chunk ids",
chunkIds: "chunk ids",
optimizeChunkIds: "chunk id optimization",
afterOptimizeChunkIds: "after chunk id optimization",
recordModules: "record modules",
recordChunks: "record chunks",
beforeModuleHash: "module hashing",
beforeCodeGeneration: "code generation",
beforeRuntimeRequirements: "runtime requirements",
beforeHash: "hashing",
afterHash: "after hashing",
recordHash: "record hash",
beforeModuleAssets: "module assets processing",
beforeChunkAssets: "chunk assets processing",
processAssets: "asset processing",
afterProcessAssets: "after asset optimization",
record: "recording",
afterSeal: "after seal"
};
const numberOfHooks = Object.keys(hooks).length;
for (const [idx, name] of Object.keys(hooks).entries()) {
const title = hooks[/** @type {keyof typeof hooks} */ (name)];
const percentage = (idx / numberOfHooks) * 0.25 + 0.7;
compilation.hooks[/** @type {keyof typeof hooks} */ (name)].intercept({
name: PLUGIN_NAME,
call() {
handler(percentage, "sealing", title);
},
done() {
progressReporters.set(compiler, undefined);
handler(percentage, "sealing", title);
},
result() {
handler(percentage, "sealing", title);
},
error() {
handler(percentage, "sealing", title);
},
tap(tap) {
// p is percentage from 0 to 1
// args is any number of messages in a hierarchical matter
progressReporters.set(compilation.compiler, (p, ...args) => {
handler(percentage, "sealing", title, tap.name, ...args);
});
handler(percentage, "sealing", title, tap.name);
}
});
}
});
compiler.hooks.make.intercept({
name: PLUGIN_NAME,
call() {
handler(0.1, "building");
},
done() {
handler(0.65, "building");
}
});
/**
* @template {Hook<EXPECTED_ANY, EXPECTED_ANY, EXPECTED_ANY>} T
* @param {T} hook hook
* @param {number} progress progress from 0 to 1
* @param {string} category category
* @param {string} name name
*/
const interceptHook = (hook, progress, category, name) => {
hook.intercept({
name: PLUGIN_NAME,
call() {
handler(progress, category, name);
},
done() {
progressReporters.set(compiler, undefined);
handler(progress, category, name);
},
result() {
handler(progress, category, name);
},
error() {
handler(progress, category, name);
},
/**
* @param {Tap} tap tap
*/
tap(tap) {
progressReporters.set(compiler, (p, ...args) => {
handler(progress, category, name, tap.name, ...args);
});
handler(progress, category, name, tap.name);
}
});
};
compiler.cache.hooks.endIdle.intercept({
name: PLUGIN_NAME,
call() {
handler(0, "");
}
});
interceptHook(compiler.cache.hooks.endIdle, 0.01, "cache", "end idle");
compiler.hooks.beforeRun.intercept({
name: PLUGIN_NAME,
call() {
handler(0, "");
}
});
interceptHook(compiler.hooks.beforeRun, 0.01, "setup", "before run");
interceptHook(compiler.hooks.run, 0.02, "setup", "run");
interceptHook(compiler.hooks.watchRun, 0.03, "setup", "watch run");
interceptHook(
compiler.hooks.normalModuleFactory,
0.04,
"setup",
"normal module factory"
);
interceptHook(
compiler.hooks.contextModuleFactory,
0.05,
"setup",
"context module factory"
);
interceptHook(
compiler.hooks.beforeCompile,
0.06,
"setup",
"before compile"
);
interceptHook(compiler.hooks.compile, 0.07, "setup", "compile");
interceptHook(compiler.hooks.thisCompilation, 0.08, "setup", "compilation");
interceptHook(compiler.hooks.compilation, 0.09, "setup", "compilation");
interceptHook(compiler.hooks.finishMake, 0.69, "building", "finish");
interceptHook(compiler.hooks.emit, 0.95, "emitting", "emit");
interceptHook(compiler.hooks.afterEmit, 0.98, "emitting", "after emit");
interceptHook(compiler.hooks.done, 0.99, "done", "plugins");
compiler.hooks.done.intercept({
name: PLUGIN_NAME,
done() {
handler(0.99, "");
}
});
interceptHook(
compiler.cache.hooks.storeBuildDependencies,
0.99,
"cache",
"store build dependencies"
);
interceptHook(compiler.cache.hooks.shutdown, 0.99, "cache", "shutdown");
interceptHook(compiler.cache.hooks.beginIdle, 0.99, "cache", "begin idle");
interceptHook(
compiler.hooks.watchClose,
0.99,
"end",
"closing watch compilation"
);
compiler.cache.hooks.beginIdle.intercept({
name: PLUGIN_NAME,
done() {
handler(1, "");
}
});
compiler.cache.hooks.shutdown.intercept({
name: PLUGIN_NAME,
done() {
handler(1, "");
}
});
}
}
ProgressPlugin.defaultOptions = {
profile: false,
modulesCount: 5000,
dependenciesCount: 10000,
modules: true,
dependencies: true,
activeModules: false,
entries: true
};
ProgressPlugin.createDefaultHandler = createDefaultHandler;
module.exports = ProgressPlugin;

View File

@@ -0,0 +1,80 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.isWrapped = exports.safeExecuteInTheMiddleAsync = exports.safeExecuteInTheMiddle = void 0;
/**
* function to execute patched function and being able to catch errors
* @param execute - function to be executed
* @param onFinish - callback to run when execute finishes
*/
function safeExecuteInTheMiddle(execute, onFinish, preventThrowingError) {
let error;
let result;
try {
result = execute();
}
catch (e) {
error = e;
}
finally {
onFinish(error, result);
if (error && !preventThrowingError) {
// eslint-disable-next-line no-unsafe-finally
throw error;
}
// eslint-disable-next-line no-unsafe-finally
return result;
}
}
exports.safeExecuteInTheMiddle = safeExecuteInTheMiddle;
/**
* Async function to execute patched function and being able to catch errors
* @param execute - function to be executed
* @param onFinish - callback to run when execute finishes
*/
async function safeExecuteInTheMiddleAsync(execute, onFinish, preventThrowingError) {
let error;
let result;
try {
result = await execute();
}
catch (e) {
error = e;
}
finally {
await onFinish(error, result);
if (error && !preventThrowingError) {
// eslint-disable-next-line no-unsafe-finally
throw error;
}
// eslint-disable-next-line no-unsafe-finally
return result;
}
}
exports.safeExecuteInTheMiddleAsync = safeExecuteInTheMiddleAsync;
/**
* Checks if certain function has been already wrapped
* @param func
*/
function isWrapped(func) {
return (typeof func === 'function' &&
typeof func.__original === 'function' &&
typeof func.__unwrap === 'function' &&
func.__wrapped === true);
}
exports.isWrapped = isWrapped;
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1,41 @@
import { sql } from '@vercel/postgres';
import type { Cache } from "../cache/core/cache.js";
import { entityKind } from "../entity.js";
import type { Logger } from "../logger.js";
import { PgDatabase } from "../pg-core/db.js";
import { PgDialect } from "../pg-core/index.js";
import { type RelationalSchemaConfig, type TablesRelationalConfig } from "../relations.js";
import { type DrizzleConfig } from "../utils.js";
import { type VercelPgClient, type VercelPgQueryResultHKT, VercelPgSession } from "./session.js";
export interface VercelPgDriverOptions {
logger?: Logger;
cache?: Cache;
}
export declare class VercelPgDriver {
private client;
private dialect;
private options;
static readonly [entityKind]: string;
constructor(client: VercelPgClient, dialect: PgDialect, options?: VercelPgDriverOptions);
createSession(schema: RelationalSchemaConfig<TablesRelationalConfig> | undefined): VercelPgSession<Record<string, unknown>, TablesRelationalConfig>;
}
export declare class VercelPgDatabase<TSchema extends Record<string, unknown> = Record<string, never>> extends PgDatabase<VercelPgQueryResultHKT, TSchema> {
static readonly [entityKind]: string;
}
export declare function drizzle<TSchema extends Record<string, unknown> = Record<string, never>, TClient extends VercelPgClient = typeof sql>(...params: [] | [
TClient
] | [
TClient,
DrizzleConfig<TSchema>
] | [
(DrizzleConfig<TSchema> & ({
client?: TClient;
}))
]): VercelPgDatabase<TSchema> & {
$client: VercelPgClient extends TClient ? typeof sql : TClient;
};
export declare namespace drizzle {
function mock<TSchema extends Record<string, unknown> = Record<string, never>>(config?: DrizzleConfig<TSchema>): VercelPgDatabase<TSchema> & {
$client: '$client is not available on drizzle.mock()';
};
}

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../src/utilities/getTranslation.ts"],"sourcesContent":["import type { JSX } from 'react'\n\nimport type { I18n, I18nClient, TFunction } from '../types.js'\n\ntype LabelType =\n | (() => JSX.Element)\n | ((args: { i18n: I18nClient; t: TFunction }) => string)\n | JSX.Element\n | Record<string, string>\n | string\n\nexport const getTranslation = <T extends LabelType>(\n label: T,\n /**\n * @todo type as I18nClient in 4.0\n */\n i18n: Pick<I18n<any, any>, 'fallbackLanguage' | 'language' | 't'>,\n): T extends JSX.Element ? JSX.Element : string => {\n // If it's a Record, look for translation. If string or React Element, pass through\n if (typeof label === 'object' && !Object.prototype.hasOwnProperty.call(label, '$$typeof')) {\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n if (label[i18n.language]) {\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n return label[i18n.language]\n }\n\n let fallbacks: string[] = []\n if (typeof i18n.fallbackLanguage === 'string') {\n fallbacks = [i18n.fallbackLanguage]\n } else if (Array.isArray(i18n.fallbackLanguage)) {\n fallbacks = i18n.fallbackLanguage\n }\n\n const fallbackLang = fallbacks.find((language) => label[language as keyof typeof label])\n\n // @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve\n return fallbackLang && label[fallbackLang] ? label[fallbackLang] : label[Object.keys(label)[0]]\n }\n\n if (typeof label === 'function') {\n return label({ i18n: i18n as I18nClient, t: i18n.t }) as unknown as T extends JSX.Element\n ? JSX.Element\n : string\n }\n\n // If it's a React Element or string, then we should just pass it through\n return label as unknown as T extends JSX.Element ? JSX.Element : string\n}\n"],"names":["getTranslation","label","i18n","Object","prototype","hasOwnProperty","call","language","fallbacks","fallbackLanguage","Array","isArray","fallbackLang","find","keys","t"],"mappings":"AAWA,OAAO,MAAMA,iBAAiB,CAC5BC,OACA;;GAEC,GACDC;IAEA,mFAAmF;IACnF,IAAI,OAAOD,UAAU,YAAY,CAACE,OAAOC,SAAS,CAACC,cAAc,CAACC,IAAI,CAACL,OAAO,aAAa;QACzF,oFAAoF;QACpF,IAAIA,KAAK,CAACC,KAAKK,QAAQ,CAAC,EAAE;YACxB,oFAAoF;YACpF,OAAON,KAAK,CAACC,KAAKK,QAAQ,CAAC;QAC7B;QAEA,IAAIC,YAAsB,EAAE;QAC5B,IAAI,OAAON,KAAKO,gBAAgB,KAAK,UAAU;YAC7CD,YAAY;gBAACN,KAAKO,gBAAgB;aAAC;QACrC,OAAO,IAAIC,MAAMC,OAAO,CAACT,KAAKO,gBAAgB,GAAG;YAC/CD,YAAYN,KAAKO,gBAAgB;QACnC;QAEA,MAAMG,eAAeJ,UAAUK,IAAI,CAAC,CAACN,WAAaN,KAAK,CAACM,SAA+B;QAEvF,oFAAoF;QACpF,OAAOK,gBAAgBX,KAAK,CAACW,aAAa,GAAGX,KAAK,CAACW,aAAa,GAAGX,KAAK,CAACE,OAAOW,IAAI,CAACb,MAAM,CAAC,EAAE,CAAC;IACjG;IAEA,IAAI,OAAOA,UAAU,YAAY;QAC/B,OAAOA,MAAM;YAAEC,MAAMA;YAAoBa,GAAGb,KAAKa,CAAC;QAAC;IAGrD;IAEA,yEAAyE;IACzE,OAAOd;AACT,EAAC"}

View File

@@ -0,0 +1,5 @@
import { IImage } from './interface.mjs';
declare const TGA: IImage;
export { TGA };

View File

@@ -0,0 +1,4 @@
import type { MigrationConfig } from "../migrator.cjs";
import type { PgRemoteDatabase } from "./driver.cjs";
export type ProxyMigrator = (migrationQueries: string[]) => Promise<void>;
export declare function migrate<TSchema extends Record<string, unknown>>(db: PgRemoteDatabase<TSchema>, callback: ProxyMigrator, config: MigrationConfig): Promise<void>;

View File

@@ -0,0 +1 @@
{"version":3,"file":"screen-share.js","sources":["../../../src/icons/screen-share.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name ScreenShare\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTMgM0g0YTIgMiAwIDAgMC0yIDJ2MTBhMiAyIDAgMCAwIDIgMmgxNmEyIDIgMCAwIDAgMi0ydi0zIiAvPgogIDxwYXRoIGQ9Ik04IDIxaDgiIC8+CiAgPHBhdGggZD0iTTEyIDE3djQiIC8+CiAgPHBhdGggZD0ibTE3IDggNS01IiAvPgogIDxwYXRoIGQ9Ik0xNyAzaDV2NSIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/screen-share\n * @see https://lucide.dev/guide/packages/lucide-react - Documentation\n *\n * @param {Object} props - Lucide icons props and any valid SVG attribute\n * @returns {JSX.Element} JSX Element\n *\n */\nconst ScreenShare = createLucideIcon('ScreenShare', [\n ['path', { d: 'M13 3H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-3', key: 'i8wdob' }],\n ['path', { d: 'M8 21h8', key: '1ev6f3' }],\n ['path', { d: 'M12 17v4', key: '1riwvh' }],\n ['path', { d: 'm17 8 5-5', key: 'fqif7o' }],\n ['path', { d: 'M17 3h5v5', key: '1o3tu8' }],\n]);\n\nexport default ScreenShare;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAc,iBAAiB,aAAe,CAAA,CAAA,CAAA;AAAA,CAAA,CAClD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAA8D,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC3F,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAW,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACxC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAY,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CACzC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAa,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC1C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAa,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC5C,CAAC,CAAA,CAAA;;"}

View File

@@ -0,0 +1,3 @@
export { nl } from '@payloadcms/translations/languages/nl';
//# sourceMappingURL=nl.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"Success.d.ts","sourceRoot":"","sources":["../../../../src/providers/ToastContainer/icons/Success.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,OAAO,CAAA;AAEzB,eAAO,MAAM,OAAO,EAAE,KAAK,CAAC,EAe3B,CAAA"}

View File

@@ -0,0 +1,31 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
'use strict';
var LexicalComposerContext = require('@lexical/react/LexicalComposerContext');
var utils = require('@lexical/utils');
var react = require('react');
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
*/
function SelectionAlwaysOnDisplay() {
const [editor] = LexicalComposerContext.useLexicalComposerContext();
react.useEffect(() => {
return utils.selectionAlwaysOnDisplay(editor);
}, [editor]);
return null;
}
exports.SelectionAlwaysOnDisplay = SelectionAlwaysOnDisplay;

View File

@@ -0,0 +1,51 @@
import type { ColumnBuilderBaseConfig } from "../../column-builder.js";
import type { ColumnBaseConfig } from "../../column.js";
import { entityKind } from "../../entity.js";
import type { AnyMySqlTable } from "../table.js";
import { type Equal } from "../../utils.js";
import { MySqlColumn, MySqlColumnBuilder } from "./common.js";
export type MySqlDateBuilderInitial<TName extends string> = MySqlDateBuilder<{
name: TName;
dataType: 'date';
columnType: 'MySqlDate';
data: Date;
driverParam: string | number;
enumValues: undefined;
}>;
export declare class MySqlDateBuilder<T extends ColumnBuilderBaseConfig<'date', 'MySqlDate'>> extends MySqlColumnBuilder<T> {
static readonly [entityKind]: string;
constructor(name: T['name']);
}
export declare class MySqlDate<T extends ColumnBaseConfig<'date', 'MySqlDate'>> extends MySqlColumn<T> {
static readonly [entityKind]: string;
constructor(table: AnyMySqlTable<{
name: T['tableName'];
}>, config: MySqlDateBuilder<T>['config']);
getSQLType(): string;
mapFromDriverValue(value: string): Date;
}
export type MySqlDateStringBuilderInitial<TName extends string> = MySqlDateStringBuilder<{
name: TName;
dataType: 'string';
columnType: 'MySqlDateString';
data: string;
driverParam: string | number;
enumValues: undefined;
}>;
export declare class MySqlDateStringBuilder<T extends ColumnBuilderBaseConfig<'string', 'MySqlDateString'>> extends MySqlColumnBuilder<T> {
static readonly [entityKind]: string;
constructor(name: T['name']);
}
export declare class MySqlDateString<T extends ColumnBaseConfig<'string', 'MySqlDateString'>> extends MySqlColumn<T> {
static readonly [entityKind]: string;
constructor(table: AnyMySqlTable<{
name: T['tableName'];
}>, config: MySqlDateStringBuilder<T>['config']);
getSQLType(): string;
}
export interface MySqlDateConfig<TMode extends 'date' | 'string' = 'date' | 'string'> {
mode?: TMode;
}
export declare function date(): MySqlDateBuilderInitial<''>;
export declare function date<TMode extends MySqlDateConfig['mode'] & {}>(config?: MySqlDateConfig<TMode>): Equal<TMode, 'string'> extends true ? MySqlDateStringBuilderInitial<''> : MySqlDateBuilderInitial<''>;
export declare function date<TName extends string, TMode extends MySqlDateConfig['mode'] & {}>(name: TName, config?: MySqlDateConfig<TMode>): Equal<TMode, 'string'> extends true ? MySqlDateStringBuilderInitial<TName> : MySqlDateBuilderInitial<TName>;

View File

@@ -0,0 +1,13 @@
var test = require('tape');
var resolve = require('../');
var path = require('path');
test('subdirs', function (t) {
t.plan(2);
var dir = path.join(__dirname, '/subdirs');
resolve('a/b/c/x.json', { basedir: dir }, function (err, res) {
t.ifError(err);
t.equal(res, path.join(dir, 'node_modules/a/b/c/x.json'));
});
});

View File

@@ -0,0 +1,2 @@
export * from './globalThis';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,6 @@
var overArg = require('./_overArg');
/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeKeys = overArg(Object.keys, Object);
module.exports = nativeKeys;

View File

@@ -0,0 +1,6 @@
// This is a magic string replaced by rollup
const SDK_VERSION = "10.39.0" ;
export { SDK_VERSION };
//# sourceMappingURL=version.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"LogoutClient.d.ts","sourceRoot":"","sources":["../../../src/views/Logout/LogoutClient.tsx"],"names":[],"mappings":"AAYA,OAAO,KAAoB,MAAM,OAAO,CAAA;AAExC,OAAO,cAAc,CAAA;AAIrB;;;;;;;;;GASG;AACH,eAAO,MAAM,YAAY,EAAE,KAAK,CAAC,EAAE,CAAC;IAClC,UAAU,EAAE,MAAM,CAAA;IAClB,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,QAAQ,EAAE,MAAM,CAAA;CACjB,CA2DA,CAAA"}

View File

@@ -0,0 +1,17 @@
{
"$schema": "https://json-schema.org/draft/2019-09/schema",
"$id": "https://json-schema.org/draft/2019-09/meta/content",
"$vocabulary": {
"https://json-schema.org/draft/2019-09/vocab/content": true
},
"$recursiveAnchor": true,
"title": "Content vocabulary meta-schema",
"type": ["object", "boolean"],
"properties": {
"contentMediaType": {"type": "string"},
"contentEncoding": {"type": "string"},
"contentSchema": {"$recursiveRef": "#"}
}
}

View File

@@ -0,0 +1,9 @@
// This file is generated automatically by `scripts/build/fp.ts`. Please, don't change it.
import { subISOWeekYears as fn } from "../subISOWeekYears.js";
import { convertToFP } from "./_lib/convertToFP.js";
export const subISOWeekYearsWithOptions = convertToFP(fn, 3);
// Fallback for modularized imports:
export default subISOWeekYearsWithOptions;

View File

@@ -0,0 +1,100 @@
'use client';
import { c as _c } from "react/compiler-runtime";
import { jsx as _jsx } from "react/jsx-runtime";
import React from 'react';
import { SortDownIcon } from '../../icons/Sort/index.js';
import { useListQuery } from '../../providers/ListQuery/index.js';
import './index.scss';
import { useTranslation } from '../../providers/Translation/index.js';
const baseClass = 'sort-header';
function useSort() {
const $ = _c(7);
const {
handleSortChange,
orderableFieldName,
query
} = useListQuery();
const querySort = Array.isArray(query.sort) ? query.sort[0] : query.sort;
const isActive = querySort === orderableFieldName;
let t0;
if ($[0] !== handleSortChange || $[1] !== isActive || $[2] !== orderableFieldName) {
t0 = () => {
if (isActive) {
return;
}
handleSortChange(orderableFieldName);
};
$[0] = handleSortChange;
$[1] = isActive;
$[2] = orderableFieldName;
$[3] = t0;
} else {
t0 = $[3];
}
const handleSortPress = t0;
let t1;
if ($[4] !== handleSortPress || $[5] !== isActive) {
t1 = {
handleSortPress,
isActive
};
$[4] = handleSortPress;
$[5] = isActive;
$[6] = t1;
} else {
t1 = $[6];
}
return t1;
}
export const SortHeader = props => {
const $ = _c(7);
const {
appearance
} = props;
const {
handleSortPress,
isActive
} = useSort();
const {
t
} = useTranslation();
const t0 = appearance && `${baseClass}--appearance-${appearance}`;
let t1;
if ($[0] !== t0) {
t1 = [baseClass, t0].filter(Boolean);
$[0] = t0;
$[1] = t1;
} else {
t1 = $[1];
}
const t2 = t1.join(" ");
let t3;
if ($[2] !== handleSortPress || $[3] !== isActive || $[4] !== t || $[5] !== t2) {
t3 = _jsx("div", {
className: t2,
children: _jsx("div", {
className: `${baseClass}__buttons`,
children: _jsx("button", {
"aria-label": t("general:sortByLabelDirection", {
direction: t("general:ascending"),
label: "Order"
}),
className: `${baseClass}__button ${isActive ? `${baseClass}--active` : ""}`,
onClick: handleSortPress,
type: "button",
children: _jsx(SortDownIcon, {})
})
})
});
$[2] = handleSortPress;
$[3] = isActive;
$[4] = t;
$[5] = t2;
$[6] = t3;
} else {
t3 = $[6];
}
return t3;
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = _AwaitValue;
function _AwaitValue(value) {
this.wrapped = value;
}
//# sourceMappingURL=AwaitValue.js.map

View File

@@ -0,0 +1,22 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.PACKAGE_NAME = exports.PACKAGE_VERSION = void 0;
// this is autogenerated file, see scripts/version-update.js
exports.PACKAGE_VERSION = '0.57.0';
exports.PACKAGE_NAME = '@opentelemetry/instrumentation-mongoose';
//# sourceMappingURL=version.js.map

View File

@@ -0,0 +1,9 @@
// This file is generated automatically by `scripts/build/fp.ts`. Please, don't change it.
import { setWeekYear as fn } from "../setWeekYear.js";
import { convertToFP } from "./_lib/convertToFP.js";
export const setWeekYearWithOptions = convertToFP(fn, 3);
// Fallback for modularized imports:
export default setWeekYearWithOptions;

View File

@@ -0,0 +1,17 @@
/**
* This method returns `undefined`.
*
* @static
* @memberOf _
* @since 2.3.0
* @category Util
* @example
*
* _.times(2, _.noop);
* // => [undefined, undefined]
*/
function noop() {
// No operation performed.
}
module.exports = noop;

View File

@@ -0,0 +1,7 @@
/*
* This file was automatically generated.
* DO NOT MODIFY BY HAND.
* Run `yarn fix:special` to update
*/
declare const check: (options: import("../../../declarations/plugins/schemes/VirtualUrlPlugin").VirtualUrlPluginOptions) => boolean;
export = check;

View File

@@ -0,0 +1,27 @@
{
"name": "@swc/counter",
"packageManager": "pnpm@8.6.7",
"main": "index.js",
"version": "0.1.3",
"description": "Downloade counter for the swc project",
"sideEffects": false,
"repository": {
"type": "git",
"url": "git+https://github.com/swc-project/pkgs.git"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/",
"access": "public"
},
"keywords": [
"swc",
"download",
"counter"
],
"author": "강동윤 <kdy1997.dev@gmail.com>",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/swc-project/swc/issues"
},
"homepage": "https://swc.rs"
}

View File

@@ -0,0 +1,17 @@
export interface Options {
/**
* Whether breadcrumbs should be recorded for requests
* Defaults to true
*/
breadcrumbs: boolean;
/**
* Function determining whether or not to create spans to track outgoing requests to the given URL.
* By default, spans will be created for all outgoing requests.
*/
shouldCreateSpanForRequest?: (url: string) => boolean;
}
/**
* Creates spans and attaches tracing headers to fetch requests on WinterCG runtimes.
*/
export declare const winterCGFetchIntegration: (options?: Partial<Options> | undefined) => import("@sentry/core").Integration;
//# sourceMappingURL=wintercg-fetch.d.ts.map

View File

@@ -0,0 +1,335 @@
import { OPENAI_OPERATIONS, GEN_AI_REQUEST_MODEL_ATTRIBUTE, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, GEN_AI_REQUEST_TOP_P_ATTRIBUTE, GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_STREAM_ATTRIBUTE, GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE, GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE, GEN_AI_CONVERSATION_ID_ATTRIBUTE, GEN_AI_RESPONSE_ID_ATTRIBUTE, OPENAI_RESPONSE_ID_ATTRIBUTE, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, OPENAI_RESPONSE_MODEL_ATTRIBUTE, OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE, GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE } from '../ai/gen-ai-attributes.js';
import { INSTRUMENTED_METHODS } from './constants.js';
/**
* Maps OpenAI method paths to OpenTelemetry semantic convention operation names
* @see https://opentelemetry.io/docs/specs/semconv/gen-ai/gen-ai-spans/#llm-request-spans
*/
function getOperationName(methodPath) {
if (methodPath.includes('chat.completions')) {
return OPENAI_OPERATIONS.CHAT;
}
if (methodPath.includes('responses')) {
return OPENAI_OPERATIONS.CHAT;
}
if (methodPath.includes('embeddings')) {
return OPENAI_OPERATIONS.EMBEDDINGS;
}
if (methodPath.includes('conversations')) {
return OPENAI_OPERATIONS.CHAT;
}
return methodPath.split('.').pop() || 'unknown';
}
/**
* Get the span operation for OpenAI methods
* Following Sentry's convention: "gen_ai.{operation_name}"
*/
function getSpanOperation(methodPath) {
return `gen_ai.${getOperationName(methodPath)}`;
}
/**
* Check if a method path should be instrumented
*/
function shouldInstrument(methodPath) {
return INSTRUMENTED_METHODS.includes(methodPath );
}
/**
* Build method path from current traversal
*/
function buildMethodPath(currentPath, prop) {
return currentPath ? `${currentPath}.${prop}` : prop;
}
/**
* Check if response is a Chat Completion object
*/
function isChatCompletionResponse(response) {
return (
response !== null &&
typeof response === 'object' &&
'object' in response &&
(response ).object === 'chat.completion'
);
}
/**
* Check if response is a Responses API object
*/
function isResponsesApiResponse(response) {
return (
response !== null &&
typeof response === 'object' &&
'object' in response &&
(response ).object === 'response'
);
}
/**
* Check if response is an Embeddings API object
*/
function isEmbeddingsResponse(response) {
if (response === null || typeof response !== 'object' || !('object' in response)) {
return false;
}
const responseObject = response ;
return (
responseObject.object === 'list' &&
typeof responseObject.model === 'string' &&
responseObject.model.toLowerCase().includes('embedding')
);
}
/**
* Check if response is a Conversations API object
* @see https://platform.openai.com/docs/api-reference/conversations
*/
function isConversationResponse(response) {
return (
response !== null &&
typeof response === 'object' &&
'object' in response &&
(response ).object === 'conversation'
);
}
/**
* Check if streaming event is from the Responses API
*/
function isResponsesApiStreamEvent(event) {
return (
event !== null &&
typeof event === 'object' &&
'type' in event &&
typeof (event ).type === 'string' &&
((event ).type ).startsWith('response.')
);
}
/**
* Check if streaming event is a chat completion chunk
*/
function isChatCompletionChunk(event) {
return (
event !== null &&
typeof event === 'object' &&
'object' in event &&
(event ).object === 'chat.completion.chunk'
);
}
/**
* Add attributes for Chat Completion responses
*/
function addChatCompletionAttributes(
span,
response,
recordOutputs,
) {
setCommonResponseAttributes(span, response.id, response.model, response.created);
if (response.usage) {
setTokenUsageAttributes(
span,
response.usage.prompt_tokens,
response.usage.completion_tokens,
response.usage.total_tokens,
);
}
if (Array.isArray(response.choices)) {
const finishReasons = response.choices
.map(choice => choice.finish_reason)
.filter((reason) => reason !== null);
if (finishReasons.length > 0) {
span.setAttributes({
[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(finishReasons),
});
}
// Extract tool calls from all choices (only if recordOutputs is true)
if (recordOutputs) {
const toolCalls = response.choices
.map(choice => choice.message?.tool_calls)
.filter(calls => Array.isArray(calls) && calls.length > 0)
.flat();
if (toolCalls.length > 0) {
span.setAttributes({
[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(toolCalls),
});
}
}
}
}
/**
* Add attributes for Responses API responses
*/
function addResponsesApiAttributes(span, response, recordOutputs) {
setCommonResponseAttributes(span, response.id, response.model, response.created_at);
if (response.status) {
span.setAttributes({
[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify([response.status]),
});
}
if (response.usage) {
setTokenUsageAttributes(
span,
response.usage.input_tokens,
response.usage.output_tokens,
response.usage.total_tokens,
);
}
// Extract function calls from output (only if recordOutputs is true)
if (recordOutputs) {
const responseWithOutput = response ;
if (Array.isArray(responseWithOutput.output) && responseWithOutput.output.length > 0) {
// Filter for function_call type objects in the output array
const functionCalls = responseWithOutput.output.filter(
(item) =>
typeof item === 'object' && item !== null && (item ).type === 'function_call',
);
if (functionCalls.length > 0) {
span.setAttributes({
[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(functionCalls),
});
}
}
}
}
/**
* Add attributes for Embeddings API responses
*/
function addEmbeddingsAttributes(span, response) {
span.setAttributes({
[OPENAI_RESPONSE_MODEL_ATTRIBUTE]: response.model,
[GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: response.model,
});
if (response.usage) {
setTokenUsageAttributes(span, response.usage.prompt_tokens, undefined, response.usage.total_tokens);
}
}
/**
* Add attributes for Conversations API responses
* @see https://platform.openai.com/docs/api-reference/conversations
*/
function addConversationAttributes(span, response) {
const { id, created_at } = response;
span.setAttributes({
[OPENAI_RESPONSE_ID_ATTRIBUTE]: id,
[GEN_AI_RESPONSE_ID_ATTRIBUTE]: id,
// The conversation id is used to link messages across API calls
[GEN_AI_CONVERSATION_ID_ATTRIBUTE]: id,
});
if (created_at) {
span.setAttributes({
[OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(created_at * 1000).toISOString(),
});
}
}
/**
* Set token usage attributes
* @param span - The span to add attributes to
* @param promptTokens - The number of prompt tokens
* @param completionTokens - The number of completion tokens
* @param totalTokens - The number of total tokens
*/
function setTokenUsageAttributes(
span,
promptTokens,
completionTokens,
totalTokens,
) {
if (promptTokens !== undefined) {
span.setAttributes({
[OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: promptTokens,
[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: promptTokens,
});
}
if (completionTokens !== undefined) {
span.setAttributes({
[OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: completionTokens,
[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: completionTokens,
});
}
if (totalTokens !== undefined) {
span.setAttributes({
[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: totalTokens,
});
}
}
/**
* Set common response attributes
* @param span - The span to add attributes to
* @param id - The response id
* @param model - The response model
* @param timestamp - The response timestamp
*/
function setCommonResponseAttributes(span, id, model, timestamp) {
span.setAttributes({
[OPENAI_RESPONSE_ID_ATTRIBUTE]: id,
[GEN_AI_RESPONSE_ID_ATTRIBUTE]: id,
});
span.setAttributes({
[OPENAI_RESPONSE_MODEL_ATTRIBUTE]: model,
[GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: model,
});
span.setAttributes({
[OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(timestamp * 1000).toISOString(),
});
}
/**
* Extract conversation ID from request parameters
* Supports both Conversations API and previous_response_id chaining
* @see https://platform.openai.com/docs/guides/conversation-state
*/
function extractConversationId(params) {
// Conversations API: conversation parameter (e.g., "conv_...")
if ('conversation' in params && typeof params.conversation === 'string') {
return params.conversation;
}
// Responses chaining: previous_response_id links to parent response
if ('previous_response_id' in params && typeof params.previous_response_id === 'string') {
return params.previous_response_id;
}
return undefined;
}
/**
* Extract request parameters including model settings and conversation context
*/
function extractRequestParameters(params) {
const attributes = {
[GEN_AI_REQUEST_MODEL_ATTRIBUTE]: params.model ?? 'unknown',
};
if ('temperature' in params) attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = params.temperature;
if ('top_p' in params) attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = params.top_p;
if ('frequency_penalty' in params) attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE] = params.frequency_penalty;
if ('presence_penalty' in params) attributes[GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE] = params.presence_penalty;
if ('stream' in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream;
if ('encoding_format' in params) attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = params.encoding_format;
if ('dimensions' in params) attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = params.dimensions;
// Capture conversation ID for linking messages across API calls
const conversationId = extractConversationId(params);
if (conversationId) {
attributes[GEN_AI_CONVERSATION_ID_ATTRIBUTE] = conversationId;
}
return attributes;
}
export { addChatCompletionAttributes, addConversationAttributes, addEmbeddingsAttributes, addResponsesApiAttributes, buildMethodPath, extractRequestParameters, getOperationName, getSpanOperation, isChatCompletionChunk, isChatCompletionResponse, isConversationResponse, isEmbeddingsResponse, isResponsesApiResponse, isResponsesApiStreamEvent, setCommonResponseAttributes, setTokenUsageAttributes, shouldInstrument };
//# sourceMappingURL=utils.js.map

View File

@@ -0,0 +1,43 @@
import * as React$1 from 'react';
type As<DefaultTag extends React.ElementType, T1 extends React.ElementType, T2 extends React.ElementType = T1, T3 extends React.ElementType = T1, T4 extends React.ElementType = T1, T5 extends React.ElementType = T1> = (React.ComponentPropsWithRef<DefaultTag> & {
as?: DefaultTag;
}) | (React.ComponentPropsWithRef<T1> & {
as: T1;
}) | (React.ComponentPropsWithRef<T2> & {
as: T2;
}) | (React.ComponentPropsWithRef<T3> & {
as: T3;
}) | (React.ComponentPropsWithRef<T4> & {
as: T4;
}) | (React.ComponentPropsWithRef<T5> & {
as: T5;
});
interface Margin {
m?: number | string;
mx?: number | string;
my?: number | string;
mt?: number | string;
mr?: number | string;
mb?: number | string;
ml?: number | string;
}
type HeadingAs = As<"h1", "h2", "h3", "h4", "h5", "h6">;
type HeadingProps = HeadingAs & Margin;
declare const Heading: React$1.ForwardRefExoticComponent<(Omit<Readonly<React$1.ClassAttributes<HTMLHeadingElement> & React$1.HTMLAttributes<HTMLHeadingElement> & {
as?: "h1" | undefined;
} & Margin>, "ref"> | Omit<Readonly<React$1.ClassAttributes<HTMLHeadingElement> & React$1.HTMLAttributes<HTMLHeadingElement> & {
as: "h2";
} & Margin>, "ref"> | Omit<Readonly<React$1.ClassAttributes<HTMLHeadingElement> & React$1.HTMLAttributes<HTMLHeadingElement> & {
as: "h3";
} & Margin>, "ref"> | Omit<Readonly<React$1.ClassAttributes<HTMLHeadingElement> & React$1.HTMLAttributes<HTMLHeadingElement> & {
as: "h4";
} & Margin>, "ref"> | Omit<Readonly<React$1.ClassAttributes<HTMLHeadingElement> & React$1.HTMLAttributes<HTMLHeadingElement> & {
as: "h5";
} & Margin>, "ref"> | Omit<Readonly<React$1.ClassAttributes<HTMLHeadingElement> & React$1.HTMLAttributes<HTMLHeadingElement> & {
as: "h6";
} & Margin>, "ref">) & React$1.RefAttributes<HTMLHeadingElement>>;
export { Heading, type HeadingAs, type HeadingProps };

View File

@@ -0,0 +1 @@
export { _ as default } from "../esm/_iterable_to_array_limit.js";

View File

@@ -0,0 +1,9 @@
// This file is generated automatically by `scripts/build/fp.ts`. Please, don't change it.
import { isFriday as fn } from "../isFriday.js";
import { convertToFP } from "./_lib/convertToFP.js";
export const isFriday = convertToFP(fn, 1);
// Fallback for modularized imports:
export default isFriday;

View File

@@ -0,0 +1,10 @@
"use strict";
exports.isFirstDayOfMonth = void 0;
var _index = require("../isFirstDayOfMonth.cjs");
var _index2 = require("./_lib/convertToFP.cjs"); // This file is generated automatically by `scripts/build/fp.ts`. Please, don't change it.
const isFirstDayOfMonth = (exports.isFirstDayOfMonth = (0, _index2.convertToFP)(
_index.isFirstDayOfMonth,
1,
));

View File

@@ -0,0 +1,37 @@
Prism.languages.nix = {
'comment': {
pattern: /\/\*[\s\S]*?\*\/|#.*/,
greedy: true
},
'string': {
pattern: /"(?:[^"\\]|\\[\s\S])*"|''(?:(?!'')[\s\S]|''(?:'|\\|\$\{))*''/,
greedy: true,
inside: {
'interpolation': {
// The lookbehind ensures the ${} is not preceded by \ or ''
pattern: /(^|(?:^|(?!'').)[^\\])\$\{(?:[^{}]|\{[^}]*\})*\}/,
lookbehind: true,
inside: null // see below
}
}
},
'url': [
/\b(?:[a-z]{3,7}:\/\/)[\w\-+%~\/.:#=?&]+/,
{
pattern: /([^\/])(?:[\w\-+%~.:#=?&]*(?!\/\/)[\w\-+%~\/.:#=?&])?(?!\/\/)\/[\w\-+%~\/.:#=?&]*/,
lookbehind: true
}
],
'antiquotation': {
pattern: /\$(?=\{)/,
alias: 'important'
},
'number': /\b\d+\b/,
'keyword': /\b(?:assert|builtins|else|if|in|inherit|let|null|or|then|with)\b/,
'function': /\b(?:abort|add|all|any|attrNames|attrValues|baseNameOf|compareVersions|concatLists|currentSystem|deepSeq|derivation|dirOf|div|elem(?:At)?|fetch(?:Tarball|url)|filter(?:Source)?|fromJSON|genList|getAttr|getEnv|hasAttr|hashString|head|import|intersectAttrs|is(?:Attrs|Bool|Function|Int|List|Null|String)|length|lessThan|listToAttrs|map|mul|parseDrvName|pathExists|read(?:Dir|File)|removeAttrs|replaceStrings|seq|sort|stringLength|sub(?:string)?|tail|throw|to(?:File|JSON|Path|String|XML)|trace|typeOf)\b|\bfoldl'\B/,
'boolean': /\b(?:false|true)\b/,
'operator': /[=!<>]=?|\+\+?|\|\||&&|\/\/|->?|[?@]/,
'punctuation': /[{}()[\].,:;]/
};
Prism.languages.nix.string.inside.interpolation.inside = Prism.languages.nix;

View File

@@ -0,0 +1 @@
export { useDerivedTransform } from './useDerivedTransform';

View File

@@ -0,0 +1,6 @@
import type { SchemaObject } from "../../types";
export type SchemaObjectMap = {
[Ref in string]?: SchemaObject;
};
export declare const jtdForms: readonly ["elements", "values", "discriminator", "properties", "optionalProperties", "enum", "type", "ref"];
export type JTDForm = (typeof jtdForms)[number];

View File

@@ -0,0 +1,8 @@
import type { TFunction } from '@payloadcms/translations';
import { APIError } from './APIError.js';
export declare class UnverifiedEmail extends APIError {
constructor({ t }: {
t?: TFunction;
});
}
//# sourceMappingURL=UnverifiedEmail.d.ts.map

View File

@@ -0,0 +1,13 @@
import { entityKind } from "../entity.cjs";
export interface GelRoleConfig {
createDb?: boolean;
createRole?: boolean;
inherit?: boolean;
}
export declare class GelRole implements GelRoleConfig {
readonly name: string;
static readonly [entityKind]: string;
constructor(name: string, config?: GelRoleConfig);
existing(): this;
}
export declare function gelRole(name: string, config?: GelRoleConfig): GelRole;

View File

@@ -0,0 +1,105 @@
"use strict";
exports.formatDistance = void 0;
const formatDistanceLocale = {
lessThanXSeconds: {
one: "کمتر از یک ثانیه",
other: "کمتر از {{count}} ثانیه",
},
xSeconds: {
one: "1 ثانیه",
other: "{{count}} ثانیه",
},
halfAMinute: "نیم دقیقه",
lessThanXMinutes: {
one: "کمتر از یک دقیقه",
other: "کمتر از {{count}} دقیقه",
},
xMinutes: {
one: "1 دقیقه",
other: "{{count}} دقیقه",
},
aboutXHours: {
one: "حدود 1 ساعت",
other: "حدود {{count}} ساعت",
},
xHours: {
one: "1 ساعت",
other: "{{count}} ساعت",
},
xDays: {
one: "1 روز",
other: "{{count}} روز",
},
aboutXWeeks: {
one: "حدود 1 هفته",
other: "حدود {{count}} هفته",
},
xWeeks: {
one: "1 هفته",
other: "{{count}} هفته",
},
aboutXMonths: {
one: "حدود 1 ماه",
other: "حدود {{count}} ماه",
},
xMonths: {
one: "1 ماه",
other: "{{count}} ماه",
},
aboutXYears: {
one: "حدود 1 سال",
other: "حدود {{count}} سال",
},
xYears: {
one: "1 سال",
other: "{{count}} سال",
},
overXYears: {
one: "بیشتر از 1 سال",
other: "بیشتر از {{count}} سال",
},
almostXYears: {
one: "نزدیک 1 سال",
other: "نزدیک {{count}} سال",
},
};
const formatDistance = (token, count, options) => {
let result;
const tokenValue = formatDistanceLocale[token];
if (typeof tokenValue === "string") {
result = tokenValue;
} else if (count === 1) {
result = tokenValue.one;
} else {
result = tokenValue.other.replace("{{count}}", String(count));
}
if (options?.addSuffix) {
if (options.comparison && options.comparison > 0) {
return "در " + result;
} else {
return result + " قبل";
}
}
return result;
};
exports.formatDistance = formatDistance;

View File

@@ -0,0 +1,53 @@
@import '../../scss/styles.scss';
@layer payload-default {
.paginator {
display: flex;
&__page {
cursor: pointer;
&--is-current {
background: var(--theme-elevation-100);
color: var(--theme-elevation-400);
cursor: default;
}
&--is-last-page {
margin-right: 0;
}
}
.clickable-arrow--right {
margin-right: base(0.25);
}
&__page {
@extend %btn-reset;
width: base(1.5);
height: base(1.5);
display: flex;
justify-content: center;
align-content: center;
outline: 0;
border-radius: var(--style-radius-s);
padding: base(0.5);
color: var(--theme-elevation-800);
line-height: 0.9;
&:focus-visible {
outline: var(--accessibility-outline);
}
}
&__page,
&__separator {
margin-right: base(0.25);
}
&__separator {
align-self: center;
color: var(--theme-elevation-400);
}
}
}

View File

@@ -0,0 +1,654 @@
'use strict';
const fs = require('fs');
const sysPath = require('path');
const { promisify } = require('util');
const isBinaryPath = require('is-binary-path');
const {
isWindows,
isLinux,
EMPTY_FN,
EMPTY_STR,
KEY_LISTENERS,
KEY_ERR,
KEY_RAW,
HANDLER_KEYS,
EV_CHANGE,
EV_ADD,
EV_ADD_DIR,
EV_ERROR,
STR_DATA,
STR_END,
BRACE_START,
STAR
} = require('./constants');
const THROTTLE_MODE_WATCH = 'watch';
const open = promisify(fs.open);
const stat = promisify(fs.stat);
const lstat = promisify(fs.lstat);
const close = promisify(fs.close);
const fsrealpath = promisify(fs.realpath);
const statMethods = { lstat, stat };
// TODO: emit errors properly. Example: EMFILE on Macos.
const foreach = (val, fn) => {
if (val instanceof Set) {
val.forEach(fn);
} else {
fn(val);
}
};
const addAndConvert = (main, prop, item) => {
let container = main[prop];
if (!(container instanceof Set)) {
main[prop] = container = new Set([container]);
}
container.add(item);
};
const clearItem = cont => key => {
const set = cont[key];
if (set instanceof Set) {
set.clear();
} else {
delete cont[key];
}
};
const delFromSet = (main, prop, item) => {
const container = main[prop];
if (container instanceof Set) {
container.delete(item);
} else if (container === item) {
delete main[prop];
}
};
const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
/**
* @typedef {String} Path
*/
// fs_watch helpers
// object to hold per-process fs_watch instances
// (may be shared across chokidar FSWatcher instances)
/**
* @typedef {Object} FsWatchContainer
* @property {Set} listeners
* @property {Set} errHandlers
* @property {Set} rawEmitters
* @property {fs.FSWatcher=} watcher
* @property {Boolean=} watcherUnusable
*/
/**
* @type {Map<String,FsWatchContainer>}
*/
const FsWatchInstances = new Map();
/**
* Instantiates the fs_watch interface
* @param {String} path to be watched
* @param {Object} options to be passed to fs_watch
* @param {Function} listener main event handler
* @param {Function} errHandler emits info about errors
* @param {Function} emitRaw emits raw event data
* @returns {fs.FSWatcher} new fsevents instance
*/
function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
const handleEvent = (rawEvent, evPath) => {
listener(path);
emitRaw(rawEvent, evPath, {watchedPath: path});
// emit based on events occurring for files from a directory's watcher in
// case the file's watcher misses it (and rely on throttling to de-dupe)
if (evPath && path !== evPath) {
fsWatchBroadcast(
sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath)
);
}
};
try {
return fs.watch(path, options, handleEvent);
} catch (error) {
errHandler(error);
}
}
/**
* Helper for passing fs_watch event data to a collection of listeners
* @param {Path} fullPath absolute path bound to fs_watch instance
* @param {String} type listener type
* @param {*=} val1 arguments to be passed to listeners
* @param {*=} val2
* @param {*=} val3
*/
const fsWatchBroadcast = (fullPath, type, val1, val2, val3) => {
const cont = FsWatchInstances.get(fullPath);
if (!cont) return;
foreach(cont[type], (listener) => {
listener(val1, val2, val3);
});
};
/**
* Instantiates the fs_watch interface or binds listeners
* to an existing one covering the same file system entry
* @param {String} path
* @param {String} fullPath absolute path
* @param {Object} options to be passed to fs_watch
* @param {Object} handlers container for event listener functions
*/
const setFsWatchListener = (path, fullPath, options, handlers) => {
const {listener, errHandler, rawEmitter} = handlers;
let cont = FsWatchInstances.get(fullPath);
/** @type {fs.FSWatcher=} */
let watcher;
if (!options.persistent) {
watcher = createFsWatchInstance(
path, options, listener, errHandler, rawEmitter
);
return watcher.close.bind(watcher);
}
if (cont) {
addAndConvert(cont, KEY_LISTENERS, listener);
addAndConvert(cont, KEY_ERR, errHandler);
addAndConvert(cont, KEY_RAW, rawEmitter);
} else {
watcher = createFsWatchInstance(
path,
options,
fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS),
errHandler, // no need to use broadcast here
fsWatchBroadcast.bind(null, fullPath, KEY_RAW)
);
if (!watcher) return;
watcher.on(EV_ERROR, async (error) => {
const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
cont.watcherUnusable = true; // documented since Node 10.4.1
// Workaround for https://github.com/joyent/node/issues/4337
if (isWindows && error.code === 'EPERM') {
try {
const fd = await open(path, 'r');
await close(fd);
broadcastErr(error);
} catch (err) {}
} else {
broadcastErr(error);
}
});
cont = {
listeners: listener,
errHandlers: errHandler,
rawEmitters: rawEmitter,
watcher
};
FsWatchInstances.set(fullPath, cont);
}
// const index = cont.listeners.indexOf(listener);
// removes this instance's listeners and closes the underlying fs_watch
// instance if there are no more listeners left
return () => {
delFromSet(cont, KEY_LISTENERS, listener);
delFromSet(cont, KEY_ERR, errHandler);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
// Check to protect against issue gh-730.
// if (cont.watcherUnusable) {
cont.watcher.close();
// }
FsWatchInstances.delete(fullPath);
HANDLER_KEYS.forEach(clearItem(cont));
cont.watcher = undefined;
Object.freeze(cont);
}
};
};
// fs_watchFile helpers
// object to hold per-process fs_watchFile instances
// (may be shared across chokidar FSWatcher instances)
const FsWatchFileInstances = new Map();
/**
* Instantiates the fs_watchFile interface or binds listeners
* to an existing one covering the same file system entry
* @param {String} path to be watched
* @param {String} fullPath absolute path
* @param {Object} options options to be passed to fs_watchFile
* @param {Object} handlers container for event listener functions
* @returns {Function} closer
*/
const setFsWatchFileListener = (path, fullPath, options, handlers) => {
const {listener, rawEmitter} = handlers;
let cont = FsWatchFileInstances.get(fullPath);
/* eslint-disable no-unused-vars, prefer-destructuring */
let listeners = new Set();
let rawEmitters = new Set();
const copts = cont && cont.options;
if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
// "Upgrade" the watcher to persistence or a quicker interval.
// This creates some unlikely edge case issues if the user mixes
// settings in a very weird way, but solving for those cases
// doesn't seem worthwhile for the added complexity.
listeners = cont.listeners;
rawEmitters = cont.rawEmitters;
fs.unwatchFile(fullPath);
cont = undefined;
}
/* eslint-enable no-unused-vars, prefer-destructuring */
if (cont) {
addAndConvert(cont, KEY_LISTENERS, listener);
addAndConvert(cont, KEY_RAW, rawEmitter);
} else {
// TODO
// listeners.add(listener);
// rawEmitters.add(rawEmitter);
cont = {
listeners: listener,
rawEmitters: rawEmitter,
options,
watcher: fs.watchFile(fullPath, options, (curr, prev) => {
foreach(cont.rawEmitters, (rawEmitter) => {
rawEmitter(EV_CHANGE, fullPath, {curr, prev});
});
const currmtime = curr.mtimeMs;
if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) {
foreach(cont.listeners, (listener) => listener(path, curr));
}
})
};
FsWatchFileInstances.set(fullPath, cont);
}
// const index = cont.listeners.indexOf(listener);
// Removes this instance's listeners and closes the underlying fs_watchFile
// instance if there are no more listeners left.
return () => {
delFromSet(cont, KEY_LISTENERS, listener);
delFromSet(cont, KEY_RAW, rawEmitter);
if (isEmptySet(cont.listeners)) {
FsWatchFileInstances.delete(fullPath);
fs.unwatchFile(fullPath);
cont.options = cont.watcher = undefined;
Object.freeze(cont);
}
};
};
/**
* @mixin
*/
class NodeFsHandler {
/**
* @param {import("../index").FSWatcher} fsW
*/
constructor(fsW) {
this.fsw = fsW;
this._boundHandleError = (error) => fsW._handleError(error);
}
/**
* Watch file for changes with fs_watchFile or fs_watch.
* @param {String} path to file or dir
* @param {Function} listener on fs change
* @returns {Function} closer for the watcher instance
*/
_watchWithNodeFs(path, listener) {
const opts = this.fsw.options;
const directory = sysPath.dirname(path);
const basename = sysPath.basename(path);
const parent = this.fsw._getWatchedDir(directory);
parent.add(basename);
const absolutePath = sysPath.resolve(path);
const options = {persistent: opts.persistent};
if (!listener) listener = EMPTY_FN;
let closer;
if (opts.usePolling) {
options.interval = opts.enableBinaryInterval && isBinaryPath(basename) ?
opts.binaryInterval : opts.interval;
closer = setFsWatchFileListener(path, absolutePath, options, {
listener,
rawEmitter: this.fsw._emitRaw
});
} else {
closer = setFsWatchListener(path, absolutePath, options, {
listener,
errHandler: this._boundHandleError,
rawEmitter: this.fsw._emitRaw
});
}
return closer;
}
/**
* Watch a file and emit add event if warranted.
* @param {Path} file Path
* @param {fs.Stats} stats result of fs_stat
* @param {Boolean} initialAdd was the file added at watch instantiation?
* @returns {Function} closer for the watcher instance
*/
_handleFile(file, stats, initialAdd) {
if (this.fsw.closed) {
return;
}
const dirname = sysPath.dirname(file);
const basename = sysPath.basename(file);
const parent = this.fsw._getWatchedDir(dirname);
// stats is always present
let prevStats = stats;
// if the file is already being watched, do nothing
if (parent.has(basename)) return;
const listener = async (path, newStats) => {
if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
if (!newStats || newStats.mtimeMs === 0) {
try {
const newStats = await stat(file);
if (this.fsw.closed) return;
// Check that change event was not fired because of changed only accessTime.
const at = newStats.atimeMs;
const mt = newStats.mtimeMs;
if (!at || at <= mt || mt !== prevStats.mtimeMs) {
this.fsw._emit(EV_CHANGE, file, newStats);
}
if (isLinux && prevStats.ino !== newStats.ino) {
this.fsw._closeFile(path)
prevStats = newStats;
this.fsw._addPathCloser(path, this._watchWithNodeFs(file, listener));
} else {
prevStats = newStats;
}
} catch (error) {
// Fix issues where mtime is null but file is still present
this.fsw._remove(dirname, basename);
}
// add is about to be emitted if file not already tracked in parent
} else if (parent.has(basename)) {
// Check that change event was not fired because of changed only accessTime.
const at = newStats.atimeMs;
const mt = newStats.mtimeMs;
if (!at || at <= mt || mt !== prevStats.mtimeMs) {
this.fsw._emit(EV_CHANGE, file, newStats);
}
prevStats = newStats;
}
}
// kick off the watcher
const closer = this._watchWithNodeFs(file, listener);
// emit an add event if we're supposed to
if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
if (!this.fsw._throttle(EV_ADD, file, 0)) return;
this.fsw._emit(EV_ADD, file, stats);
}
return closer;
}
/**
* Handle symlinks encountered while reading a dir.
* @param {Object} entry returned by readdirp
* @param {String} directory path of dir being read
* @param {String} path of this item
* @param {String} item basename of this item
* @returns {Promise<Boolean>} true if no more processing is needed for this entry.
*/
async _handleSymlink(entry, directory, path, item) {
if (this.fsw.closed) {
return;
}
const full = entry.fullPath;
const dir = this.fsw._getWatchedDir(directory);
if (!this.fsw.options.followSymlinks) {
// watch symlink directly (don't follow) and detect changes
this.fsw._incrReadyCount();
let linkPath;
try {
linkPath = await fsrealpath(path);
} catch (e) {
this.fsw._emitReady();
return true;
}
if (this.fsw.closed) return;
if (dir.has(item)) {
if (this.fsw._symlinkPaths.get(full) !== linkPath) {
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV_CHANGE, path, entry.stats);
}
} else {
dir.add(item);
this.fsw._symlinkPaths.set(full, linkPath);
this.fsw._emit(EV_ADD, path, entry.stats);
}
this.fsw._emitReady();
return true;
}
// don't follow the same symlink more than once
if (this.fsw._symlinkPaths.has(full)) {
return true;
}
this.fsw._symlinkPaths.set(full, true);
}
_handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
// Normalize the directory name on Windows
directory = sysPath.join(directory, EMPTY_STR);
if (!wh.hasGlob) {
throttler = this.fsw._throttle('readdir', directory, 1000);
if (!throttler) return;
}
const previous = this.fsw._getWatchedDir(wh.path);
const current = new Set();
let stream = this.fsw._readdirp(directory, {
fileFilter: entry => wh.filterPath(entry),
directoryFilter: entry => wh.filterDir(entry),
depth: 0
}).on(STR_DATA, async (entry) => {
if (this.fsw.closed) {
stream = undefined;
return;
}
const item = entry.path;
let path = sysPath.join(directory, item);
current.add(item);
if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) {
return;
}
if (this.fsw.closed) {
stream = undefined;
return;
}
// Files that present in current directory snapshot
// but absent in previous are added to watch list and
// emit `add` event.
if (item === target || !target && !previous.has(item)) {
this.fsw._incrReadyCount();
// ensure relativeness of path is preserved in case of watcher reuse
path = sysPath.join(dir, sysPath.relative(dir, path));
this._addToNodeFs(path, initialAdd, wh, depth + 1);
}
}).on(EV_ERROR, this._boundHandleError);
return new Promise(resolve =>
stream.once(STR_END, () => {
if (this.fsw.closed) {
stream = undefined;
return;
}
const wasThrottled = throttler ? throttler.clear() : false;
resolve();
// Files that absent in current directory snapshot
// but present in previous emit `remove` event
// and are removed from @watched[directory].
previous.getChildren().filter((item) => {
return item !== directory &&
!current.has(item) &&
// in case of intersecting globs;
// a path may have been filtered out of this readdir, but
// shouldn't be removed because it matches a different glob
(!wh.hasGlob || wh.filterPath({
fullPath: sysPath.resolve(directory, item)
}));
}).forEach((item) => {
this.fsw._remove(directory, item);
});
stream = undefined;
// one more time for any missed in case changes came in extremely quickly
if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
})
);
}
/**
* Read directory to add / remove files from `@watched` list and re-read it on change.
* @param {String} dir fs path
* @param {fs.Stats} stats
* @param {Boolean} initialAdd
* @param {Number} depth relative to user-supplied path
* @param {String} target child path targeted for watch
* @param {Object} wh Common watch helpers for this path
* @param {String} realpath
* @returns {Promise<Function>} closer for the watcher instance.
*/
async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir));
const tracked = parentDir.has(sysPath.basename(dir));
if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) {
if (!wh.hasGlob || wh.globFilter(dir)) this.fsw._emit(EV_ADD_DIR, dir, stats);
}
// ensure dir is tracked (harmless if redundant)
parentDir.add(sysPath.basename(dir));
this.fsw._getWatchedDir(dir);
let throttler;
let closer;
const oDepth = this.fsw.options.depth;
if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
if (!target) {
await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
if (this.fsw.closed) return;
}
closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
// if current directory is removed, do nothing
if (stats && stats.mtimeMs === 0) return;
this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
});
}
return closer;
}
/**
* Handle added file, directory, or glob pattern.
* Delegates call to _handleFile / _handleDir after checks.
* @param {String} path to file or ir
* @param {Boolean} initialAdd was the file added at watch instantiation?
* @param {Object} priorWh depth relative to user-supplied path
* @param {Number} depth Child path actually targeted for watch
* @param {String=} target Child path actually targeted for watch
* @returns {Promise}
*/
async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
const ready = this.fsw._emitReady;
if (this.fsw._isIgnored(path) || this.fsw.closed) {
ready();
return false;
}
const wh = this.fsw._getWatchHelpers(path, depth);
if (!wh.hasGlob && priorWh) {
wh.hasGlob = priorWh.hasGlob;
wh.globFilter = priorWh.globFilter;
wh.filterPath = entry => priorWh.filterPath(entry);
wh.filterDir = entry => priorWh.filterDir(entry);
}
// evaluate what is at the path we're being asked to watch
try {
const stats = await statMethods[wh.statMethod](wh.watchPath);
if (this.fsw.closed) return;
if (this.fsw._isIgnored(wh.watchPath, stats)) {
ready();
return false;
}
const follow = this.fsw.options.followSymlinks && !path.includes(STAR) && !path.includes(BRACE_START);
let closer;
if (stats.isDirectory()) {
const absPath = sysPath.resolve(path);
const targetPath = follow ? await fsrealpath(path) : path;
if (this.fsw.closed) return;
closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
if (this.fsw.closed) return;
// preserve this symlink's target path
if (absPath !== targetPath && targetPath !== undefined) {
this.fsw._symlinkPaths.set(absPath, targetPath);
}
} else if (stats.isSymbolicLink()) {
const targetPath = follow ? await fsrealpath(path) : path;
if (this.fsw.closed) return;
const parent = sysPath.dirname(wh.watchPath);
this.fsw._getWatchedDir(parent).add(wh.watchPath);
this.fsw._emit(EV_ADD, wh.watchPath, stats);
closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
if (this.fsw.closed) return;
// preserve this symlink's target path
if (targetPath !== undefined) {
this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath);
}
} else {
closer = this._handleFile(wh.watchPath, stats, initialAdd);
}
ready();
this.fsw._addPathCloser(path, closer);
return false;
} catch (error) {
if (this.fsw._handleError(error)) {
ready();
return path;
}
}
}
}
module.exports = NodeFsHandler;

View File

@@ -0,0 +1,14 @@
import { isWillChangeMotionValue } from './is.mjs';
function addValueToWillChange(visualElement, key) {
const willChange = visualElement.getValue("willChange");
/**
* It could be that a user has set willChange to a regular MotionValue,
* in which case we can't add the value to it.
*/
if (isWillChangeMotionValue(willChange)) {
return willChange.add(key);
}
}
export { addValueToWillChange };

View File

@@ -0,0 +1,3 @@
import type { CountVersions } from 'payload';
export declare const countVersions: CountVersions;
//# sourceMappingURL=countVersions.d.ts.map

View File

@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_COLOR_MAP = void 0;
exports.DEFAULT_COLOR_MAP = {
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
white: '\x1b[37m',
white_bold: '\x1b[01m',
reset: '\x1b[0m',
};
class ColoredConsoleLine {
constructor(colorMap = exports.DEFAULT_COLOR_MAP) {
this.text = '';
this.colorMap = colorMap;
}
addCharsWithColor(color, text) {
const colorAnsi = this.colorMap[color];
this.text +=
colorAnsi !== undefined
? `${colorAnsi}${text}${this.colorMap.reset}`
: text;
}
renderConsole() {
return this.text;
}
}
exports.default = ColoredConsoleLine;

View File

@@ -0,0 +1,63 @@
(function (Prism) {
Prism.languages.latte = {
'comment': /^\{\*[\s\S]*/,
'latte-tag': {
// https://latte.nette.org/en/tags
pattern: /(^\{(?:\/(?=[a-z]))?)(?:[=_]|[a-z]\w*\b(?!\())/i,
lookbehind: true,
alias: 'important'
},
'delimiter': {
pattern: /^\{\/?|\}$/,
alias: 'punctuation'
},
'php': {
pattern: /\S(?:[\s\S]*\S)?/,
alias: 'language-php',
inside: Prism.languages.php
}
};
var markupLatte = Prism.languages.extend('markup', {});
Prism.languages.insertBefore('inside', 'attr-value', {
'n-attr': {
pattern: /n:[\w-]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s'">=]+))?/,
inside: {
'attr-name': {
pattern: /^[^\s=]+/,
alias: 'important'
},
'attr-value': {
pattern: /=[\s\S]+/,
inside: {
'punctuation': [
/^=/,
{
pattern: /^(\s*)["']|["']$/,
lookbehind: true
}
],
'php': {
pattern: /\S(?:[\s\S]*\S)?/,
inside: Prism.languages.php
}
}
},
}
},
}, markupLatte.tag);
Prism.hooks.add('before-tokenize', function (env) {
if (env.language !== 'latte') {
return;
}
var lattePattern = /\{\*[\s\S]*?\*\}|\{[^'"\s{}*](?:[^"'/{}]|\/(?![*/])|("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|\/\*(?:[^*]|\*(?!\/))*\*\/)*\}/g;
Prism.languages['markup-templating'].buildPlaceholders(env, 'latte', lattePattern);
env.grammar = markupLatte;
});
Prism.hooks.add('after-tokenize', function (env) {
Prism.languages['markup-templating'].tokenizePlaceholders(env, 'latte');
});
}(Prism));

View File

@@ -0,0 +1,9 @@
// This file is generated automatically by `scripts/build/fp.ts`. Please, don't change it.
import { isWednesday as fn } from "../isWednesday.js";
import { convertToFP } from "./_lib/convertToFP.js";
export const isWednesdayWithOptions = convertToFP(fn, 2);
// Fallback for modularized imports:
export default isWednesdayWithOptions;

View File

@@ -0,0 +1,37 @@
"use strict";
exports.Hour1To24Parser = void 0;
var _constants = require("../constants.cjs");
var _Parser = require("../Parser.cjs");
var _utils = require("../utils.cjs");
class Hour1To24Parser extends _Parser.Parser {
priority = 70;
parse(dateString, token, match) {
switch (token) {
case "k":
return (0, _utils.parseNumericPattern)(
_constants.numericPatterns.hour24h,
dateString,
);
case "ko":
return match.ordinalNumber(dateString, { unit: "hour" });
default:
return (0, _utils.parseNDigits)(token.length, dateString);
}
}
validate(_date, value) {
return value >= 1 && value <= 24;
}
set(date, _flags, value) {
const hours = value <= 24 ? value % 24 : value;
date.setHours(hours, 0, 0, 0);
return date;
}
incompatibleTokens = ["a", "b", "h", "H", "K", "t", "T"];
}
exports.Hour1To24Parser = Hour1To24Parser;

View File

@@ -0,0 +1,342 @@
import { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js';
import { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js';
import { AuthenticationError, LockedAuth, UnverifiedEmail, ValidationError } from '../../errors/index.js';
import { afterRead } from '../../fields/hooks/afterRead/index.js';
import { commitTransaction, Forbidden, initTransaction } from '../../index.js';
import { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js';
import { killTransaction } from '../../utilities/killTransaction.js';
import { sanitizeInternalFields } from '../../utilities/sanitizeInternalFields.js';
import { getFieldsToSign } from '../getFieldsToSign.js';
import { getLoginOptions } from '../getLoginOptions.js';
import { isUserLocked } from '../isUserLocked.js';
import { jwtSign } from '../jwt.js';
import { addSessionToUser, revokeSession } from '../sessions.js';
import { authenticateLocalStrategy } from '../strategies/local/authenticate.js';
import { incrementLoginAttempts } from '../strategies/local/incrementLoginAttempts.js';
import { resetLoginAttempts } from '../strategies/local/resetLoginAttempts.js';
/**
* Throws an error if the user is locked or does not exist.
* This does not check the login attempts, only the lock status. Whoever increments login attempts
* is responsible for locking the user properly, not whoever checks the login permission.
*/ export const checkLoginPermission = ({ loggingInWithUsername, req, user })=>{
if (!user) {
throw new AuthenticationError(req.t, Boolean(loggingInWithUsername));
}
if (isUserLocked(new Date(user.lockUntil))) {
throw new LockedAuth(req.t);
}
};
export const loginOperation = async (incomingArgs)=>{
let args = incomingArgs;
if (args.collection.config.auth.disableLocalStrategy) {
throw new Forbidden(args.req.t);
}
// /////////////////////////////////////
// beforeOperation - Collection
// /////////////////////////////////////
args = await buildBeforeOperation({
args,
collection: args.collection.config,
operation: 'login',
overrideAccess: args.overrideAccess
});
const { collection: { config: collectionConfig }, data, depth, overrideAccess = false, req, req: { fallbackLocale, locale, payload, payload: { secret } }, showHiddenFields } = args;
// /////////////////////////////////////
// Login
// /////////////////////////////////////
const { email: unsanitizedEmail, password } = data;
const loginWithUsername = collectionConfig.auth.loginWithUsername;
const sanitizedEmail = typeof unsanitizedEmail === 'string' ? unsanitizedEmail.toLowerCase().trim() : null;
const sanitizedUsername = 'username' in data && typeof data?.username === 'string' ? data.username.toLowerCase().trim() : null;
const { canLoginWithEmail, canLoginWithUsername } = getLoginOptions(loginWithUsername);
// cannot login with email, did not provide username
if (!canLoginWithEmail && !sanitizedUsername) {
throw new ValidationError({
collection: collectionConfig.slug,
errors: [
{
message: req.i18n.t('validation:required'),
path: 'username'
}
]
});
}
// cannot login with username, did not provide email
if (!canLoginWithUsername && !sanitizedEmail) {
throw new ValidationError({
collection: collectionConfig.slug,
errors: [
{
message: req.i18n.t('validation:required'),
path: 'email'
}
]
});
}
// can login with either email or username, did not provide either
if (!sanitizedUsername && !sanitizedEmail) {
throw new ValidationError({
collection: collectionConfig.slug,
errors: [
{
message: req.i18n.t('validation:required'),
path: 'email'
},
{
message: req.i18n.t('validation:required'),
path: 'username'
}
]
});
}
// did not provide password for login
if (typeof password !== 'string' || password.trim() === '') {
throw new ValidationError({
collection: collectionConfig.slug,
errors: [
{
message: req.i18n.t('validation:required'),
path: 'password'
}
]
});
}
let whereConstraint = {};
const emailConstraint = {
email: {
equals: sanitizedEmail
}
};
const usernameConstraint = {
username: {
equals: sanitizedUsername
}
};
if (canLoginWithEmail && canLoginWithUsername && (sanitizedUsername || sanitizedEmail)) {
if (sanitizedUsername) {
whereConstraint = {
or: [
usernameConstraint,
{
email: {
equals: sanitizedUsername
}
}
]
};
} else {
whereConstraint = {
or: [
emailConstraint,
{
username: {
equals: sanitizedEmail
}
}
]
};
}
} else if (canLoginWithEmail && sanitizedEmail) {
whereConstraint = emailConstraint;
} else if (canLoginWithUsername && sanitizedUsername) {
whereConstraint = usernameConstraint;
}
// Exclude trashed users
whereConstraint = appendNonTrashedFilter({
enableTrash: collectionConfig.trash,
trash: false,
where: whereConstraint
});
let user = await payload.db.findOne({
collection: collectionConfig.slug,
req,
where: whereConstraint
});
checkLoginPermission({
loggingInWithUsername: Boolean(canLoginWithUsername && sanitizedUsername),
req,
user
});
user.collection = collectionConfig.slug;
user._strategy = 'local-jwt';
const authResult = await authenticateLocalStrategy({
doc: user,
password
});
user = sanitizeInternalFields(user);
const maxLoginAttemptsEnabled = args.collection.config.auth.maxLoginAttempts > 0;
if (!authResult) {
if (maxLoginAttemptsEnabled) {
await incrementLoginAttempts({
collection: collectionConfig,
payload: req.payload,
user
});
// Re-check login permissions and max attempts after incrementing attempts, in case parallel updates occurred
checkLoginPermission({
loggingInWithUsername: Boolean(canLoginWithUsername && sanitizedUsername),
req,
user
});
}
throw new AuthenticationError(req.t);
}
if (collectionConfig.auth.verify && user._verified === false) {
throw new UnverifiedEmail({
t: req.t
});
}
// Authentication successful - start transaction for remaining operations
const shouldCommit = await initTransaction(args.req);
let sid;
try {
/*
* Correct password accepted - recheck that the account didn't
* get locked by parallel bad attempts in the meantime.
*/ if (maxLoginAttemptsEnabled) {
const { lockUntil, loginAttempts } = await payload.db.findOne({
collection: collectionConfig.slug,
req,
select: {
lockUntil: true,
loginAttempts: true
},
where: {
id: {
equals: user.id
}
}
});
user.lockUntil = lockUntil;
user.loginAttempts = loginAttempts;
checkLoginPermission({
req,
user
});
}
const fieldsToSignArgs = {
collectionConfig,
email: sanitizedEmail,
user
};
const session = await addSessionToUser({
collectionConfig,
payload,
req,
user
});
sid = session.sid;
if (sid) {
fieldsToSignArgs.sid = sid;
}
const fieldsToSign = getFieldsToSign(fieldsToSignArgs);
if (maxLoginAttemptsEnabled) {
await resetLoginAttempts({
collection: collectionConfig,
doc: user,
payload: req.payload,
req
});
}
// /////////////////////////////////////
// beforeLogin - Collection
// /////////////////////////////////////
if (collectionConfig.hooks?.beforeLogin?.length) {
for (const hook of collectionConfig.hooks.beforeLogin){
user = await hook({
collection: args.collection?.config,
context: args.req.context,
req: args.req,
user
}) || user;
}
}
const { exp, token } = await jwtSign({
fieldsToSign,
secret,
tokenExpiration: collectionConfig.auth.tokenExpiration
});
req.user = user;
// /////////////////////////////////////
// afterLogin - Collection
// /////////////////////////////////////
if (collectionConfig.hooks?.afterLogin?.length) {
for (const hook of collectionConfig.hooks.afterLogin){
user = await hook({
collection: args.collection?.config,
context: args.req.context,
req: args.req,
token,
user
}) || user;
}
}
// /////////////////////////////////////
// afterRead - Fields
// /////////////////////////////////////
user = await afterRead({
collection: collectionConfig,
context: req.context,
depth: depth,
doc: user,
// @ts-expect-error - vestiges of when tsconfig was not strict. Feel free to improve
draft: undefined,
fallbackLocale: fallbackLocale,
global: null,
locale: locale,
overrideAccess,
req,
showHiddenFields: showHiddenFields
});
// /////////////////////////////////////
// afterRead - Collection
// /////////////////////////////////////
if (collectionConfig.hooks?.afterRead?.length) {
for (const hook of collectionConfig.hooks.afterRead){
user = await hook({
collection: args.collection?.config,
context: req.context,
doc: user,
overrideAccess,
req
}) || user;
}
}
let result = {
exp,
token,
user
};
// /////////////////////////////////////
// afterOperation - Collection
// /////////////////////////////////////
result = await buildAfterOperation({
args,
collection: args.collection?.config,
operation: 'login',
overrideAccess: args.overrideAccess,
result
});
if (shouldCommit) {
await commitTransaction(req);
}
// /////////////////////////////////////
// Return results
// /////////////////////////////////////
return result;
} catch (error) {
if (sid) {
await revokeSession({
collectionConfig,
payload,
req,
sid,
user
});
}
await killTransaction(args.req);
throw error;
}
};
//# sourceMappingURL=login.js.map

View File

@@ -0,0 +1,188 @@
"use strict";
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AbstractAsyncHooksContextManager = void 0;
const events_1 = require("events");
const ADD_LISTENER_METHODS = [
'addListener',
'on',
'once',
'prependListener',
'prependOnceListener',
];
class AbstractAsyncHooksContextManager {
/**
* Binds a the certain context or the active one to the target function and then returns the target
* @param context A context (span) to be bind to target
* @param target a function or event emitter. When target or one of its callbacks is called,
* the provided context will be used as the active context for the duration of the call.
*/
bind(context, target) {
if (target instanceof events_1.EventEmitter) {
return this._bindEventEmitter(context, target);
}
if (typeof target === 'function') {
return this._bindFunction(context, target);
}
return target;
}
_bindFunction(context, target) {
const manager = this;
const contextWrapper = function (...args) {
return manager.with(context, () => target.apply(this, args));
};
Object.defineProperty(contextWrapper, 'length', {
enumerable: false,
configurable: true,
writable: false,
value: target.length,
});
/**
* It isn't possible to tell Typescript that contextWrapper is the same as T
* so we forced to cast as any here.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return contextWrapper;
}
/**
* By default, EventEmitter call their callback with their context, which we do
* not want, instead we will bind a specific context to all callbacks that
* go through it.
* @param context the context we want to bind
* @param ee EventEmitter an instance of EventEmitter to patch
*/
_bindEventEmitter(context, ee) {
const map = this._getPatchMap(ee);
if (map !== undefined)
return ee;
this._createPatchMap(ee);
// patch methods that add a listener to propagate context
ADD_LISTENER_METHODS.forEach(methodName => {
if (ee[methodName] === undefined)
return;
ee[methodName] = this._patchAddListener(ee, ee[methodName], context);
});
// patch methods that remove a listener
if (typeof ee.removeListener === 'function') {
ee.removeListener = this._patchRemoveListener(ee, ee.removeListener);
}
if (typeof ee.off === 'function') {
ee.off = this._patchRemoveListener(ee, ee.off);
}
// patch method that remove all listeners
if (typeof ee.removeAllListeners === 'function') {
ee.removeAllListeners = this._patchRemoveAllListeners(ee, ee.removeAllListeners);
}
return ee;
}
/**
* Patch methods that remove a given listener so that we match the "patched"
* version of that listener (the one that propagate context).
* @param ee EventEmitter instance
* @param original reference to the patched method
*/
_patchRemoveListener(ee, original) {
const contextManager = this;
return function (event, listener) {
const events = contextManager._getPatchMap(ee)?.[event];
if (events === undefined) {
return original.call(this, event, listener);
}
const patchedListener = events.get(listener);
return original.call(this, event, patchedListener || listener);
};
}
/**
* Patch methods that remove all listeners so we remove our
* internal references for a given event.
* @param ee EventEmitter instance
* @param original reference to the patched method
*/
_patchRemoveAllListeners(ee, original) {
const contextManager = this;
return function (event) {
const map = contextManager._getPatchMap(ee);
if (map !== undefined) {
if (arguments.length === 0) {
contextManager._createPatchMap(ee);
}
else if (map[event] !== undefined) {
delete map[event];
}
}
return original.apply(this, arguments);
};
}
/**
* Patch methods on an event emitter instance that can add listeners so we
* can force them to propagate a given context.
* @param ee EventEmitter instance
* @param original reference to the patched method
* @param [context] context to propagate when calling listeners
*/
_patchAddListener(ee, original, context) {
const contextManager = this;
return function (event, listener) {
/**
* This check is required to prevent double-wrapping the listener.
* The implementation for ee.once wraps the listener and calls ee.on.
* Without this check, we would wrap that wrapped listener.
* This causes an issue because ee.removeListener depends on the onceWrapper
* to properly remove the listener. If we wrap their wrapper, we break
* that detection.
*/
if (contextManager._wrapped) {
return original.call(this, event, listener);
}
let map = contextManager._getPatchMap(ee);
if (map === undefined) {
map = contextManager._createPatchMap(ee);
}
let listeners = map[event];
if (listeners === undefined) {
listeners = new WeakMap();
map[event] = listeners;
}
const patchedListener = contextManager.bind(context, listener);
// store a weak reference of the user listener to ours
listeners.set(listener, patchedListener);
/**
* See comment at the start of this function for the explanation of this property.
*/
contextManager._wrapped = true;
try {
return original.call(this, event, patchedListener);
}
finally {
contextManager._wrapped = false;
}
};
}
_createPatchMap(ee) {
const map = Object.create(null);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
ee[this._kOtListeners] = map;
return map;
}
_getPatchMap(ee) {
return ee[this._kOtListeners];
}
_kOtListeners = Symbol('OtListeners');
_wrapped = false;
}
exports.AbstractAsyncHooksContextManager = AbstractAsyncHooksContextManager;
//# sourceMappingURL=AbstractAsyncHooksContextManager.js.map

View File

@@ -0,0 +1,137 @@
"use strict";
exports.match = void 0;
var _index = require("../../_lib/buildMatchFn.js");
var _index2 = require("../../_lib/buildMatchPatternFn.js");
const matchOrdinalNumberPattern = /^(\d+)\.?/i;
const parseOrdinalNumberPattern = /\d+/i;
const matchEraPatterns = {
narrow: /^(ie\.|isz\.)/i,
abbreviated: /^(i\.\s?e\.?|b?\s?c\s?e|i\.\s?sz\.?)/i,
wide: /^(Krisztus előtt|időszámításunk előtt|időszámításunk szerint|i\. sz\.)/i,
};
const parseEraPatterns = {
narrow: [/ie/i, /isz/i],
abbreviated: [/^(i\.?\s?e\.?|b\s?ce)/i, /^(i\.?\s?sz\.?|c\s?e)/i],
any: [/előtt/i, /(szerint|i. sz.)/i],
};
const matchQuarterPatterns = {
narrow: /^[1234]\.?/i,
abbreviated: /^[1234]?\.?\s?n\.év/i,
wide: /^([1234]|I|II|III|IV)?\.?\s?negyedév/i,
};
const parseQuarterPatterns = {
any: [/1|I$/i, /2|II$/i, /3|III/i, /4|IV/i],
};
const matchMonthPatterns = {
narrow: /^[jfmaásond]|sz/i,
abbreviated:
/^(jan\.?|febr\.?|márc\.?|ápr\.?|máj\.?|jún\.?|júl\.?|aug\.?|szept\.?|okt\.?|nov\.?|dec\.?)/i,
wide: /^(január|február|március|április|május|június|július|augusztus|szeptember|október|november|december)/i,
};
const parseMonthPatterns = {
narrow: [
/^j/i,
/^f/i,
/^m/i,
/^a|á/i,
/^m/i,
/^j/i,
/^j/i,
/^a/i,
/^s|sz/i,
/^o/i,
/^n/i,
/^d/i,
],
any: [
/^ja/i,
/^f/i,
/^már/i,
/^áp/i,
/^máj/i,
/^jún/i,
/^júl/i,
/^au/i,
/^s/i,
/^o/i,
/^n/i,
/^d/i,
],
};
const matchDayPatterns = {
narrow: /^([vhkpc]|sz|cs|sz)/i,
short: /^([vhkp]|sze|cs|szo)/i,
abbreviated: /^([vhkp]|sze|cs|szo)/i,
wide: /^(vasárnap|hétfő|kedd|szerda|csütörtök|péntek|szombat)/i,
};
const parseDayPatterns = {
narrow: [/^v/i, /^h/i, /^k/i, /^sz/i, /^c/i, /^p/i, /^sz/i],
any: [/^v/i, /^h/i, /^k/i, /^sze/i, /^c/i, /^p/i, /^szo/i],
};
const matchDayPeriodPatterns = {
any: /^((de|du)\.?|éjfél|délután|dél|reggel|este|éjjel)/i,
};
const parseDayPeriodPatterns = {
any: {
am: /^de\.?/i,
pm: /^du\.?/i,
midnight: /^éjf/i,
noon: /^dé/i,
morning: /reg/i,
afternoon: /^délu\.?/i,
evening: /es/i,
night: /éjj/i,
},
};
const match = (exports.match = {
ordinalNumber: (0, _index2.buildMatchPatternFn)({
matchPattern: matchOrdinalNumberPattern,
parsePattern: parseOrdinalNumberPattern,
valueCallback: (value) => parseInt(value, 10),
}),
era: (0, _index.buildMatchFn)({
matchPatterns: matchEraPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseEraPatterns,
defaultParseWidth: "any",
}),
quarter: (0, _index.buildMatchFn)({
matchPatterns: matchQuarterPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseQuarterPatterns,
defaultParseWidth: "any",
valueCallback: (index) => index + 1,
}),
month: (0, _index.buildMatchFn)({
matchPatterns: matchMonthPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseMonthPatterns,
defaultParseWidth: "any",
}),
day: (0, _index.buildMatchFn)({
matchPatterns: matchDayPatterns,
defaultMatchWidth: "wide",
parsePatterns: parseDayPatterns,
defaultParseWidth: "any",
}),
dayPeriod: (0, _index.buildMatchFn)({
matchPatterns: matchDayPeriodPatterns,
defaultMatchWidth: "any",
parsePatterns: parseDayPeriodPatterns,
defaultParseWidth: "any",
}),
});

View File

@@ -0,0 +1,11 @@
"use strict";
var _assert_this_initialized = require("./_assert_this_initialized.cjs");
var _type_of = require("./_type_of.cjs");
function _possible_constructor_return(self, call) {
if (call && (_type_of._(call) === "object" || typeof call === "function")) return call;
return _assert_this_initialized._(self);
}
exports._ = _possible_constructor_return;

Some files were not shown because too many files have changed in this diff Show More