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,8 @@
// This file is generated automatically by `scripts/build/fp.ts`. Please, don't change it.
import { addQuarters as fn } from "../addQuarters.mjs";
import { convertToFP } from "./_lib/convertToFP.mjs";
export const addQuarters = convertToFP(fn, 2);
// Fallback for modularized imports:
export default addQuarters;

View File

@@ -0,0 +1,23 @@
const blacklistedKeys = ['validate', 'customComponents'];
const sanitizeField = incomingField => {
const field = {
...incomingField
} // shallow copy, as we only need to remove top-level keys
;
for (const key of blacklistedKeys) {
delete field[key];
}
return field;
};
/**
* Takes in FormState and removes fields that are not serializable.
* Returns FormState without blacklisted keys.
*/
export const reduceToSerializableFields = fields => {
const result = {};
for (const key in fields) {
result[key] = sanitizeField(fields[key]);
}
return result;
};
//# sourceMappingURL=reduceToSerializableFields.js.map

View File

@@ -0,0 +1,54 @@
import { jsx as _jsx } from "react/jsx-runtime";
import { isReactServerComponentOrFunction, serverProps } from 'payload/shared';
import React from 'react';
/**
* Creates a higher-order component (HOC) that merges predefined properties (`toMergeIntoProps`)
* with any properties passed to the resulting component.
*
* Use this when you want to pre-specify some props for a component, while also allowing users to
* pass in their own props. The HOC ensures the passed props and predefined props are combined before
* rendering the original component.
*
* @example
* const PredefinedComponent = getMergedPropsComponent({
* Component: OriginalComponent,
* toMergeIntoProps: { someExtraValue: 5 }
* });
* // Using <PredefinedComponent customProp="value" /> will result in
* // <OriginalComponent customProp="value" someExtraValue={5} />
*
* @returns A higher-order component with combined properties.
*
* @param Component - The original component to wrap.
* @param sanitizeServerOnlyProps - If true, server-only props will be removed from the merged props. @default true if the component is not a server component, false otherwise.
* @param toMergeIntoProps - The properties to merge into the passed props.
*/
export function withMergedProps({
Component,
sanitizeServerOnlyProps,
toMergeIntoProps
}) {
if (sanitizeServerOnlyProps === undefined) {
sanitizeServerOnlyProps = !isReactServerComponentOrFunction(Component);
}
// A wrapper around the args.Component to inject the args.toMergeArgs as props, which are merged with the passed props
const MergedPropsComponent = passedProps => {
const mergedProps = simpleMergeProps(passedProps, toMergeIntoProps);
if (sanitizeServerOnlyProps) {
serverProps.forEach(prop => {
delete mergedProps[prop];
});
}
return /*#__PURE__*/_jsx(Component, {
...mergedProps
});
};
return MergedPropsComponent;
}
function simpleMergeProps(props, toMerge) {
return {
...props,
...toMerge
};
}
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"request.cjs","names":["extractData","result: { response: unknown; message: string; errors: any; data?: any }"],"sources":["../../src/utils/request.ts"],"sourcesContent":["import type { FetchInterface } from '../index.js';\nimport { extractData } from './extract-data.js';\n\n/**\n * Request helper providing default settings\n *\n * @param url The request URL\n * @param options The request options\n *\n * @returns The API result if successful\n */\nexport const request = async <Output = any>(\n\turl: string,\n\toptions: RequestInit,\n\tfetcher: FetchInterface = globalThis.fetch,\n): Promise<Output> => {\n\toptions.headers =\n\t\ttypeof options.headers === 'object' && !Array.isArray(options.headers)\n\t\t\t? (options.headers as Record<string, string>)\n\t\t\t: {};\n\n\treturn fetcher(url, options).then((response) => {\n\t\treturn extractData(response).catch((reason) => {\n\t\t\tconst result: { response: unknown; message: string; errors: any; data?: any } = {\n\t\t\t\tmessage: '',\n\t\t\t\terrors: reason && typeof reason === 'object' && 'errors' in reason ? reason.errors : reason,\n\t\t\t\tresponse,\n\t\t\t};\n\n\t\t\tif (reason && typeof reason === 'object' && 'data' in reason) result.data = reason.data;\n\n\t\t\tif (Array.isArray(result.errors) && result.errors[0]?.message) {\n\t\t\t\tresult.message = result.errors[0].message;\n\t\t\t}\n\n\t\t\treturn Promise.reject(result);\n\t\t});\n\t});\n};\n"],"mappings":"sCAWa,EAAU,MACtB,EACA,EACA,EAA0B,WAAW,SAErC,EAAQ,QACP,OAAO,EAAQ,SAAY,UAAY,CAAC,MAAM,QAAQ,EAAQ,QAAQ,CAClE,EAAQ,QACT,EAAE,CAEC,EAAQ,EAAK,EAAQ,CAAC,KAAM,GAC3BA,EAAAA,YAAY,EAAS,CAAC,MAAO,GAAW,CAC9C,IAAMC,EAA0E,CAC/E,QAAS,GACT,OAAQ,GAAU,OAAO,GAAW,UAAY,WAAY,EAAS,EAAO,OAAS,EACrF,WACA,CAQD,OANI,GAAU,OAAO,GAAW,UAAY,SAAU,IAAQ,EAAO,KAAO,EAAO,MAE/E,MAAM,QAAQ,EAAO,OAAO,EAAI,EAAO,OAAO,IAAI,UACrD,EAAO,QAAU,EAAO,OAAO,GAAG,SAG5B,QAAQ,OAAO,EAAO,EAC5B,CACD"}

View File

@@ -0,0 +1,21 @@
/**
* @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 University = createLucideIcon("University", [
["circle", { cx: "12", cy: "10", r: "1", key: "1gnqs8" }],
["path", { d: "M22 20V8h-4l-6-4-6 4H2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2", key: "1qj5sn" }],
["path", { d: "M6 17v.01", key: "roodi6" }],
["path", { d: "M6 13v.01", key: "67c122" }],
["path", { d: "M18 17v.01", key: "12ktxm" }],
["path", { d: "M18 13v.01", key: "tn1rt1" }],
["path", { d: "M14 22v-5a2 2 0 0 0-2-2a2 2 0 0 0-2 2v5", key: "11g7fi" }]
]);
export { University as default };
//# sourceMappingURL=university.js.map

View File

@@ -0,0 +1,35 @@
import { getRoundingMethod } from "./_lib/getRoundingMethod.mjs";
import { differenceInMonths } from "./differenceInMonths.mjs";
/**
* The {@link differenceInQuarters} function options.
*/
/**
* @name differenceInQuarters
* @category Quarter Helpers
* @summary Get the number of quarters between the given dates.
*
* @description
* Get the number of quarters between the given dates.
*
* @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).
*
* @param dateLeft - The later date
* @param dateRight - The earlier date
* @param options - An object with options.
*
* @returns The number of full quarters
*
* @example
* // How many full quarters are between 31 December 2013 and 2 July 2014?
* const result = differenceInQuarters(new Date(2014, 6, 2), new Date(2013, 11, 31))
* //=> 2
*/
export function differenceInQuarters(dateLeft, dateRight, options) {
const diff = differenceInMonths(dateLeft, dateRight) / 3;
return getRoundingMethod(options?.roundingMethod)(diff);
}
// Fallback for modularized imports:
export default differenceInQuarters;

View File

@@ -0,0 +1,29 @@
import { GraphQLScalarType, Kind } from 'graphql';
import { createGraphQLError } from '../error.js';
import { processValue } from './utilities.js';
export const GraphQLNegativeInt = /*#__PURE__*/ new GraphQLScalarType({
name: 'NegativeInt',
description: 'Integers that will have a value less than 0.',
serialize(value) {
return processValue(value, 'NegativeInt');
},
parseValue(value) {
return processValue(value, 'NegativeInt');
},
parseLiteral(ast) {
if (ast.kind !== Kind.INT) {
throw createGraphQLError(`Can only validate integers as negative integers but got a: ${ast.kind}`, {
nodes: ast,
});
}
return processValue(ast.value, 'NegativeInt');
},
extensions: {
codegenScalarType: 'number',
jsonSchema: {
title: 'NegativeInt',
type: 'integer',
maximum: 0,
},
},
});

View File

@@ -0,0 +1,25 @@
'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import React from 'react';
import './index.scss';
const baseClass = 'gutter';
export const Gutter = props => {
const {
children,
className,
left = true,
negativeLeft = false,
negativeRight = false,
ref,
right = true
} = props;
const shouldPadLeft = left && !negativeLeft;
const shouldPadRight = right && !negativeRight;
return /*#__PURE__*/_jsx("div", {
className: [baseClass, shouldPadLeft && `${baseClass}--left`, shouldPadRight && `${baseClass}--right`, negativeLeft && `${baseClass}--negative-left`, negativeRight && `${baseClass}--negative-right`, className].filter(Boolean).join(' '),
ref: ref,
children: children
});
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,17 @@
import css from './css';
import ownerDocument from './ownerDocument';
var isHTMLElement = function isHTMLElement(e) {
return !!e && 'offsetParent' in e;
};
export default function offsetParent(node) {
var doc = ownerDocument(node);
var parent = node && node.offsetParent;
while (isHTMLElement(parent) && parent.nodeName !== 'HTML' && css(parent, 'position') === 'static') {
parent = parent.offsetParent;
}
return parent || doc.documentElement;
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"environment.js","sourceRoot":"","sources":["../../../../src/platform/browser/environment.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,MAAM,UAAU,gBAAgB,CAAC,CAAS;IACxC,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,CAAS;IACzC,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,CAAS;IACxC,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,CAAS;IAC5C,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\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\nexport function getStringFromEnv(_: string): string | undefined {\n return undefined;\n}\n\nexport function getBooleanFromEnv(_: string): boolean | undefined {\n return undefined;\n}\n\nexport function getNumberFromEnv(_: string): number | undefined {\n return undefined;\n}\n\nexport function getStringListFromEnv(_: string): string[] | undefined {\n return undefined;\n}\n"]}

View File

@@ -0,0 +1 @@
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/trace/internal/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAGH,uDAAmD;AAEnD,SAAgB,gBAAgB,CAAC,aAAsB;IACrD,OAAO,IAAI,gCAAc,CAAC,aAAa,CAAC,CAAC;AAC3C,CAAC;AAFD,4CAEC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\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\nimport { TraceState } from '../trace_state';\nimport { TraceStateImpl } from './tracestate-impl';\n\nexport function createTraceState(rawTraceState?: string): TraceState {\n return new TraceStateImpl(rawTraceState);\n}\n"]}

View File

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

View File

@@ -0,0 +1,775 @@
import type * as checks from "./checks.js";
import type { $ZodConfig } from "./core.js";
import type * as errors from "./errors.js";
import type * as schemas from "./schemas.js";
// json
export type JSONType = string | number | boolean | null | JSONType[] | { [key: string]: JSONType };
export type JWTAlgorithm =
| "HS256"
| "HS384"
| "HS512"
| "RS256"
| "RS384"
| "RS512"
| "ES256"
| "ES384"
| "ES512"
| "PS256"
| "PS384"
| "PS512"
| "EdDSA"
| (string & {});
export type IPVersion = "v4" | "v6";
export type MimeTypes =
| "application/json"
| "application/xml"
| "application/x-www-form-urlencoded"
| "application/javascript"
| "application/pdf"
| "application/zip"
| "application/vnd.ms-excel"
| "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
| "application/msword"
| "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
| "application/vnd.ms-powerpoint"
| "application/vnd.openxmlformats-officedocument.presentationml.presentation"
| "application/octet-stream"
| "application/graphql"
| "text/html"
| "text/plain"
| "text/css"
| "text/javascript"
| "text/csv"
| "image/png"
| "image/jpeg"
| "image/gif"
| "image/svg+xml"
| "image/webp"
| "audio/mpeg"
| "audio/ogg"
| "audio/wav"
| "audio/webm"
| "video/mp4"
| "video/webm"
| "video/ogg"
| "font/woff"
| "font/woff2"
| "font/ttf"
| "font/otf"
| "multipart/form-data"
| (string & {});
export type ParsedTypes =
| "string"
| "number"
| "bigint"
| "boolean"
| "symbol"
| "undefined"
| "object"
| "function"
| "file"
| "date"
| "array"
| "map"
| "set"
| "nan"
| "null"
| "promise";
// utils
export type AssertEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2 ? true : false;
export type AssertNotEqual<T, U> = (<V>() => V extends T ? 1 : 2) extends <V>() => V extends U ? 1 : 2 ? false : true;
export type AssertExtends<T, U> = T extends U ? T : never;
export type IsAny<T> = 0 extends 1 & T ? true : false;
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export type OmitKeys<T, K extends string> = Pick<T, Exclude<keyof T, K>>;
export type MakePartial<T, K extends keyof T> = Omit<T, K> & InexactPartial<Pick<T, K>>;
export type MakeRequired<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
export type Exactly<T, X> = T & Record<Exclude<keyof X, keyof T>, never>;
export type NoUndefined<T> = T extends undefined ? never : T;
export type Whatever = {} | undefined | null;
export type LoosePartial<T extends object> = InexactPartial<T> & {
[k: string]: unknown;
};
export type Mask<Keys extends PropertyKey> = { [K in Keys]?: true };
export type Writeable<T> = { -readonly [P in keyof T]: T[P] } & {};
export type InexactPartial<T> = {
[P in keyof T]?: T[P] | undefined;
};
export type EmptyObject = Record<string, never>;
export type BuiltIn =
| (((...args: any[]) => any) | (new (...args: any[]) => any))
| { readonly [Symbol.toStringTag]: string }
| Date
| Error
| Generator
| Promise<unknown>
| RegExp;
export type MakeReadonly<T> = T extends Map<infer K, infer V>
? ReadonlyMap<K, V>
: T extends Set<infer V>
? ReadonlySet<V>
: T extends [infer Head, ...infer Tail]
? readonly [Head, ...Tail]
: T extends Array<infer V>
? ReadonlyArray<V>
: T extends BuiltIn
? T
: Readonly<T>;
export type SomeObject = Record<PropertyKey, any>;
export type Identity<T> = T;
export type Flatten<T> = Identity<{ [k in keyof T]: T[k] }>;
export type Mapped<T> = { [k in keyof T]: T[k] };
export type Prettify<T> = {
[K in keyof T]: T[K];
} & {};
export type NoNeverKeys<T> = {
[k in keyof T]: [T[k]] extends [never] ? never : k;
}[keyof T];
export type NoNever<T> = Identity<{
[k in NoNeverKeys<T>]: k extends keyof T ? T[k] : never;
}>;
export type Extend<A extends SomeObject, B extends SomeObject> = Flatten<
// fast path when there is no keys overlap
keyof A & keyof B extends never
? A & B
: {
[K in keyof A as K extends keyof B ? never : K]: A[K];
} & {
[K in keyof B]: B[K];
}
>;
export type TupleItems = ReadonlyArray<schemas.SomeType>;
export type AnyFunc = (...args: any[]) => any;
export type IsProp<T, K extends keyof T> = T[K] extends AnyFunc ? never : K;
export type MaybeAsync<T> = T | Promise<T>;
export type KeyOf<T> = keyof OmitIndexSignature<T>;
export type OmitIndexSignature<T> = {
[K in keyof T as string extends K ? never : K extends string ? K : never]: T[K];
};
export type ExtractIndexSignature<T> = {
[K in keyof T as string extends K ? K : K extends string ? never : K]: T[K];
};
export type Keys<T extends object> = keyof OmitIndexSignature<T>;
export type SchemaClass<T extends schemas.SomeType> = {
new (def: T["_zod"]["def"]): T;
};
export type EnumValue = string | number; // | bigint | boolean | symbol;
export type EnumLike = Readonly<Record<string, EnumValue>>;
export type ToEnum<T extends EnumValue> = Flatten<{ [k in T]: k }>;
export type KeysEnum<T extends object> = ToEnum<Exclude<keyof T, symbol>>;
export type KeysArray<T extends object> = Flatten<(keyof T & string)[]>;
export type Literal = string | number | bigint | boolean | null | undefined;
export type LiteralArray = Array<Literal>;
export type Primitive = string | number | symbol | bigint | boolean | null | undefined;
export type PrimitiveArray = Array<Primitive>;
export type HasSize = { size: number };
export type HasLength = { length: number }; // string | Array<unknown> | Set<unknown> | File;
export type Numeric = number | bigint | Date;
export type SafeParseResult<T> = SafeParseSuccess<T> | SafeParseError<T>;
export type SafeParseSuccess<T> = { success: true; data: T; error?: never };
export type SafeParseError<T> = {
success: false;
data?: never;
error: errors.$ZodError<T>;
};
export type PropValues = Record<string, Set<Primitive>>;
export type PrimitiveSet = Set<Primitive>;
// functions
export function assertEqual<A, B>(val: AssertEqual<A, B>): AssertEqual<A, B> {
return val;
}
export function assertNotEqual<A, B>(val: AssertNotEqual<A, B>): AssertNotEqual<A, B> {
return val;
}
export function assertIs<T>(_arg: T): void {}
export function assertNever(_x: never): never {
throw new Error();
}
export function assert<T>(_: any): asserts _ is T {}
export function getEnumValues(entries: EnumLike): EnumValue[] {
const numericValues = Object.values(entries).filter((v) => typeof v === "number");
const values = Object.entries(entries)
.filter(([k, _]) => numericValues.indexOf(+k) === -1)
.map(([_, v]) => v);
return values;
}
export function joinValues<T extends Primitive[]>(array: T, separator = "|"): string {
return array.map((val) => stringifyPrimitive(val)).join(separator);
}
export function jsonStringifyReplacer(_: string, value: any): any {
if (typeof value === "bigint") return value.toString();
return value;
}
export function cached<T>(getter: () => T): { value: T } {
const set = false;
return {
get value() {
if (!set) {
const value = getter();
Object.defineProperty(this, "value", { value });
return value;
}
throw new Error("cached value already set");
},
};
}
export function nullish(input: any): boolean {
return input === null || input === undefined;
}
export function cleanRegex(source: string): string {
const start = source.startsWith("^") ? 1 : 0;
const end = source.endsWith("$") ? source.length - 1 : source.length;
return source.slice(start, end);
}
export function floatSafeRemainder(val: number, step: number): number {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
return (valInt % stepInt) / 10 ** decCount;
}
export function defineLazy<T, K extends keyof T>(object: T, key: K, getter: () => T[K]): void {
const set = false;
Object.defineProperty(object, key, {
get() {
if (!set) {
const value = getter();
object[key] = value;
return value;
}
throw new Error("cached value already set");
},
set(v) {
Object.defineProperty(object, key, {
value: v,
// configurable: true,
});
// object[key] = v;
},
configurable: true,
});
}
export function assignProp<T extends object, K extends PropertyKey>(
target: T,
prop: K,
value: K extends keyof T ? T[K] : any
): void {
Object.defineProperty(target, prop, {
value,
writable: true,
enumerable: true,
configurable: true,
});
}
export function getElementAtPath(obj: any, path: (string | number)[] | null | undefined): any {
if (!path) return obj;
return path.reduce((acc, key) => acc?.[key], obj);
}
export function promiseAllObject<T extends object>(promisesObj: T): Promise<{ [k in keyof T]: Awaited<T[k]> }> {
const keys = Object.keys(promisesObj);
const promises = keys.map((key) => (promisesObj as any)[key]);
return Promise.all(promises).then((results) => {
const resolvedObj: any = {};
for (let i = 0; i < keys.length; i++) {
resolvedObj[keys[i]!] = results[i];
}
return resolvedObj;
});
}
export function randomString(length = 10): string {
const chars = "abcdefghijklmnopqrstuvwxyz";
let str = "";
for (let i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
export function esc(str: string): string {
return JSON.stringify(str);
}
export const captureStackTrace: (targetObject: object, constructorOpt?: Function) => void = Error.captureStackTrace
? Error.captureStackTrace
: (..._args) => {};
export function isObject(data: any): data is Record<PropertyKey, unknown> {
return typeof data === "object" && data !== null && !Array.isArray(data);
}
export const allowsEval: { value: boolean } = cached(() => {
if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
return false;
}
try {
const F = Function;
new F("");
return true;
} catch (_) {
return false;
}
});
export function isPlainObject(o: any): o is Record<PropertyKey, unknown> {
if (isObject(o) === false) return false;
// modified constructor
const ctor = o.constructor;
if (ctor === undefined) return true;
// modified prototype
const prot = ctor.prototype;
if (isObject(prot) === false) return false;
// ctor doesn't have static `isPrototypeOf`
if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
return false;
}
return true;
}
export function numKeys(data: any): number {
let keyCount = 0;
for (const key in data) {
if (Object.prototype.hasOwnProperty.call(data, key)) {
keyCount++;
}
}
return keyCount;
}
export const getParsedType = (data: any): ParsedTypes => {
const t = typeof data;
switch (t) {
case "undefined":
return "undefined";
case "string":
return "string";
case "number":
return Number.isNaN(data) ? "nan" : "number";
case "boolean":
return "boolean";
case "function":
return "function";
case "bigint":
return "bigint";
case "symbol":
return "symbol";
case "object":
if (Array.isArray(data)) {
return "array";
}
if (data === null) {
return "null";
}
if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
return "promise";
}
if (typeof Map !== "undefined" && data instanceof Map) {
return "map";
}
if (typeof Set !== "undefined" && data instanceof Set) {
return "set";
}
if (typeof Date !== "undefined" && data instanceof Date) {
return "date";
}
if (typeof File !== "undefined" && data instanceof File) {
return "file";
}
return "object";
default:
throw new Error(`Unknown data type: ${t}`);
}
};
export const propertyKeyTypes: Set<string> = new Set(["string", "number", "symbol"]);
export const primitiveTypes: Set<string> = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
export function escapeRegex(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
// zod-specific utils
export function clone<T extends schemas.$ZodType>(inst: T, def?: T["_zod"]["def"], params?: { parent: boolean }): T {
const cl = new inst._zod.constr(def ?? inst._zod.def);
if (!def || params?.parent) cl._zod.parent = inst;
return cl as any;
}
export type EmptyToNever<T> = keyof T extends never ? never : T;
export type Normalize<T> = T extends undefined
? never
: T extends Record<any, any>
? Flatten<
{
[k in keyof Omit<T, "error" | "message">]: T[k];
} & ("error" extends keyof T
? {
error?: Exclude<T["error"], string>;
// path?: PropertyKey[] | undefined;
// message?: string | undefined;
}
: unknown)
>
: never;
export function normalizeParams<T>(_params: T): Normalize<T> {
const params: any = _params;
if (!params) return {} as any;
if (typeof params === "string") return { error: () => params } as any;
if (params?.message !== undefined) {
if (params?.error !== undefined) throw new Error("Cannot specify both `message` and `error` params");
params.error = params.message;
}
delete params.message;
if (typeof params.error === "string") return { ...params, error: () => params.error } as any;
return params;
}
export function createTransparentProxy<T extends object>(getter: () => T): T {
let target: T;
return new Proxy(
{},
{
get(_, prop, receiver) {
target ??= getter();
return Reflect.get(target, prop, receiver);
},
set(_, prop, value, receiver) {
target ??= getter();
return Reflect.set(target, prop, value, receiver);
},
has(_, prop) {
target ??= getter();
return Reflect.has(target, prop);
},
deleteProperty(_, prop) {
target ??= getter();
return Reflect.deleteProperty(target, prop);
},
ownKeys(_) {
target ??= getter();
return Reflect.ownKeys(target);
},
getOwnPropertyDescriptor(_, prop) {
target ??= getter();
return Reflect.getOwnPropertyDescriptor(target, prop);
},
defineProperty(_, prop, descriptor) {
target ??= getter();
return Reflect.defineProperty(target, prop, descriptor);
},
}
) as T;
}
export function stringifyPrimitive(value: any): string {
if (typeof value === "bigint") return value.toString() + "n";
if (typeof value === "string") return `"${value}"`;
return `${value}`;
}
export function optionalKeys(shape: schemas.$ZodShape): string[] {
return Object.keys(shape).filter((k) => {
return shape[k]!._zod.optin === "optional" && shape[k]!._zod.optout === "optional";
});
}
export type CleanKey<T extends PropertyKey> = T extends `?${infer K}` ? K : T extends `${infer K}?` ? K : T;
export type ToCleanMap<T extends schemas.$ZodLooseShape> = {
[k in keyof T]: k extends `?${infer K}` ? K : k extends `${infer K}?` ? K : k;
};
export type FromCleanMap<T extends schemas.$ZodLooseShape> = {
[k in keyof T as k extends `?${infer K}` ? K : k extends `${infer K}?` ? K : k]: k;
};
export const NUMBER_FORMAT_RANGES: Record<checks.$ZodNumberFormats, [number, number]> = {
safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],
int32: [-2147483648, 2147483647],
uint32: [0, 4294967295],
float32: [-3.4028234663852886e38, 3.4028234663852886e38],
float64: [-Number.MAX_VALUE, Number.MAX_VALUE],
};
export const BIGINT_FORMAT_RANGES: Record<checks.$ZodBigIntFormats, [bigint, bigint]> = {
int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")],
uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")],
};
export function pick(schema: schemas.$ZodObject, mask: Record<string, unknown>): any {
const newShape: Writeable<schemas.$ZodShape> = {};
const currDef = schema._zod.def; //.shape;
for (const key in mask) {
if (!(key in currDef.shape)) {
throw new Error(`Unrecognized key: "${key}"`);
}
if (!mask[key]) continue;
// pick key
newShape[key] = currDef.shape[key]!;
}
return clone(schema, {
...schema._zod.def,
shape: newShape,
checks: [],
}) as any;
}
export function omit(schema: schemas.$ZodObject, mask: object): any {
const newShape: Writeable<schemas.$ZodShape> = { ...schema._zod.def.shape };
const currDef = schema._zod.def; //.shape;
for (const key in mask) {
if (!(key in currDef.shape)) {
throw new Error(`Unrecognized key: "${key}"`);
}
if (!(mask as any)[key]) continue;
delete newShape[key];
}
return clone(schema, {
...schema._zod.def,
shape: newShape,
checks: [],
});
}
export function extend(schema: schemas.$ZodObject, shape: schemas.$ZodShape): any {
if (!isPlainObject(shape)) {
throw new Error("Invalid input to extend: expected a plain object");
}
const def = {
...schema._zod.def,
get shape() {
const _shape = { ...schema._zod.def.shape, ...shape };
assignProp(this, "shape", _shape); // self-caching
return _shape;
},
checks: [], // delete existing checks
} as any;
return clone(schema, def) as any;
}
export function merge(a: schemas.$ZodObject, b: schemas.$ZodObject): any {
return clone(a, {
...a._zod.def,
get shape() {
const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
assignProp(this, "shape", _shape); // self-caching
return _shape;
},
catchall: b._zod.def.catchall,
checks: [], // delete existing checks
}) as any;
}
export function partial(
Class: SchemaClass<schemas.$ZodOptional> | null,
schema: schemas.$ZodObject,
mask: object | undefined
): any {
const oldShape = schema._zod.def.shape;
const shape: Writeable<schemas.$ZodShape> = { ...oldShape };
if (mask) {
for (const key in mask) {
if (!(key in oldShape)) {
throw new Error(`Unrecognized key: "${key}"`);
}
if (!(mask as any)[key]) continue;
// if (oldShape[key]!._zod.optin === "optional") continue;
shape[key] = Class
? new Class({
type: "optional",
innerType: oldShape[key]!,
})
: oldShape[key]!;
}
} else {
for (const key in oldShape) {
// if (oldShape[key]!._zod.optin === "optional") continue;
shape[key] = Class
? new Class({
type: "optional",
innerType: oldShape[key]!,
})
: oldShape[key]!;
}
}
return clone(schema, {
...schema._zod.def,
shape,
checks: [],
}) as any;
}
export function required(
Class: SchemaClass<schemas.$ZodNonOptional>,
schema: schemas.$ZodObject,
mask: object | undefined
): any {
const oldShape = schema._zod.def.shape;
const shape: Writeable<schemas.$ZodShape> = { ...oldShape };
if (mask) {
for (const key in mask) {
if (!(key in shape)) {
throw new Error(`Unrecognized key: "${key}"`);
}
if (!(mask as any)[key]) continue;
// overwrite with non-optional
shape[key] = new Class({
type: "nonoptional",
innerType: oldShape[key]!,
});
}
} else {
for (const key in oldShape) {
// overwrite with non-optional
shape[key] = new Class({
type: "nonoptional",
innerType: oldShape[key]!,
});
}
}
return clone(schema, {
...schema._zod.def,
shape,
// optional: [],
checks: [],
}) as any;
}
export type Constructor<T, Def extends any[] = any[]> = new (...args: Def) => T;
export function aborted(x: schemas.ParsePayload, startIndex = 0): boolean {
for (let i = startIndex; i < x.issues.length; i++) {
if (x.issues[i]?.continue !== true) return true;
}
return false;
}
export function prefixIssues(path: PropertyKey, issues: errors.$ZodRawIssue[]): errors.$ZodRawIssue[] {
return issues.map((iss) => {
(iss as any).path ??= [];
(iss as any).path.unshift(path);
return iss;
});
}
export function unwrapMessage(message: string | { message: string } | undefined | null): string | undefined {
return typeof message === "string" ? message : message?.message;
}
export function finalizeIssue(
iss: errors.$ZodRawIssue,
ctx: schemas.ParseContextInternal | undefined,
config: $ZodConfig
): errors.$ZodIssue {
const full = { ...iss, path: iss.path ?? [] } as errors.$ZodIssue;
// for backwards compatibility
if (!iss.message) {
const message =
unwrapMessage(iss.inst?._zod.def?.error?.(iss as never)) ??
unwrapMessage(ctx?.error?.(iss as never)) ??
unwrapMessage(config.customError?.(iss)) ??
unwrapMessage(config.localeError?.(iss)) ??
"Invalid input";
(full as any).message = message;
}
// delete (full as any).def;
delete (full as any).inst;
delete (full as any).continue;
if (!ctx?.reportInput) {
delete (full as any).input;
}
return full;
}
export function getSizableOrigin(input: any): "set" | "map" | "file" | "unknown" {
if (input instanceof Set) return "set";
if (input instanceof Map) return "map";
if (input instanceof File) return "file";
return "unknown";
}
export function getLengthableOrigin(input: any): "array" | "string" | "unknown" {
if (Array.isArray(input)) return "array";
if (typeof input === "string") return "string";
return "unknown";
}
////////// REFINES //////////
export function issue(_iss: string, input: any, inst: any): errors.$ZodRawIssue;
export function issue(_iss: errors.$ZodRawIssue): errors.$ZodRawIssue;
export function issue(...args: [string | errors.$ZodRawIssue, any?, any?]): errors.$ZodRawIssue {
const [iss, input, inst] = args;
if (typeof iss === "string") {
return {
message: iss,
code: "custom",
input,
inst,
};
}
return { ...iss };
}
export function cleanEnum(obj: Record<string, EnumValue>): EnumValue[] {
return Object.entries(obj)
.filter(([k, _]) => {
// return true if NaN, meaning it's not a number, thus a string key
return Number.isNaN(Number.parseInt(k, 10));
})
.map((el) => el[1]);
}
// instanceof
export abstract class Class {
constructor(..._args: any[]) {}
}

View File

@@ -0,0 +1,308 @@
# Chokidar [![Weekly downloads](https://img.shields.io/npm/dw/chokidar.svg)](https://github.com/paulmillr/chokidar) [![Yearly downloads](https://img.shields.io/npm/dy/chokidar.svg)](https://github.com/paulmillr/chokidar)
> Minimal and efficient cross-platform file watching library
[![NPM](https://nodei.co/npm/chokidar.png)](https://www.npmjs.com/package/chokidar)
## Why?
Node.js `fs.watch`:
* Doesn't report filenames on MacOS.
* Doesn't report events at all when using editors like Sublime on MacOS.
* Often reports events twice.
* Emits most changes as `rename`.
* Does not provide an easy way to recursively watch file trees.
* Does not support recursive watching on Linux.
Node.js `fs.watchFile`:
* Almost as bad at event handling.
* Also does not provide any recursive watching.
* Results in high CPU utilization.
Chokidar resolves these problems.
Initially made for **[Brunch](https://brunch.io/)** (an ultra-swift web app build tool), it is now used in
[Microsoft's Visual Studio Code](https://github.com/microsoft/vscode),
[gulp](https://github.com/gulpjs/gulp/),
[karma](https://karma-runner.github.io/),
[PM2](https://github.com/Unitech/PM2),
[browserify](http://browserify.org/),
[webpack](https://webpack.github.io/),
[BrowserSync](https://www.browsersync.io/),
and [many others](https://www.npmjs.com/browse/depended/chokidar).
It has proven itself in production environments.
Version 3 is out! Check out our blog post about it: [Chokidar 3: How to save 32TB of traffic every week](https://paulmillr.com/posts/chokidar-3-save-32tb-of-traffic/)
## How?
Chokidar does still rely on the Node.js core `fs` module, but when using
`fs.watch` and `fs.watchFile` for watching, it normalizes the events it
receives, often checking for truth by getting file stats and/or dir contents.
On MacOS, chokidar by default uses a native extension exposing the Darwin
`FSEvents` API. This provides very efficient recursive watching compared with
implementations like `kqueue` available on most \*nix platforms. Chokidar still
does have to do some work to normalize the events received that way as well.
On most other platforms, the `fs.watch`-based implementation is the default, which
avoids polling and keeps CPU usage down. Be advised that chokidar will initiate
watchers recursively for everything within scope of the paths that have been
specified, so be judicious about not wasting system resources by watching much
more than needed.
## Getting started
Install with npm:
```sh
npm install chokidar
```
Then `require` and use it in your code:
```javascript
const chokidar = require('chokidar');
// One-liner for current directory
chokidar.watch('.').on('all', (event, path) => {
console.log(event, path);
});
```
## API
```javascript
// Example of a more typical implementation structure
// Initialize watcher.
const watcher = chokidar.watch('file, dir, glob, or array', {
ignored: /(^|[\/\\])\../, // ignore dotfiles
persistent: true
});
// Something to use when events are received.
const log = console.log.bind(console);
// Add event listeners.
watcher
.on('add', path => log(`File ${path} has been added`))
.on('change', path => log(`File ${path} has been changed`))
.on('unlink', path => log(`File ${path} has been removed`));
// More possible events.
watcher
.on('addDir', path => log(`Directory ${path} has been added`))
.on('unlinkDir', path => log(`Directory ${path} has been removed`))
.on('error', error => log(`Watcher error: ${error}`))
.on('ready', () => log('Initial scan complete. Ready for changes'))
.on('raw', (event, path, details) => { // internal
log('Raw event info:', event, path, details);
});
// 'add', 'addDir' and 'change' events also receive stat() results as second
// argument when available: https://nodejs.org/api/fs.html#fs_class_fs_stats
watcher.on('change', (path, stats) => {
if (stats) console.log(`File ${path} changed size to ${stats.size}`);
});
// Watch new files.
watcher.add('new-file');
watcher.add(['new-file-2', 'new-file-3', '**/other-file*']);
// Get list of actual paths being watched on the filesystem
var watchedPaths = watcher.getWatched();
// Un-watch some files.
await watcher.unwatch('new-file*');
// Stop watching.
// The method is async!
watcher.close().then(() => console.log('closed'));
// Full list of options. See below for descriptions.
// Do not use this example!
chokidar.watch('file', {
persistent: true,
ignored: '*.txt',
ignoreInitial: false,
followSymlinks: true,
cwd: '.',
disableGlobbing: false,
usePolling: false,
interval: 100,
binaryInterval: 300,
alwaysStat: false,
depth: 99,
awaitWriteFinish: {
stabilityThreshold: 2000,
pollInterval: 100
},
ignorePermissionErrors: false,
atomic: true // or a custom 'atomicity delay', in milliseconds (default 100)
});
```
`chokidar.watch(paths, [options])`
* `paths` (string or array of strings). Paths to files, dirs to be watched
recursively, or glob patterns.
- Note: globs must not contain windows separators (`\`),
because that's how they work by the standard —
you'll need to replace them with forward slashes (`/`).
- Note 2: for additional glob documentation, check out low-level
library: [picomatch](https://github.com/micromatch/picomatch).
* `options` (object) Options object as defined below:
#### Persistence
* `persistent` (default: `true`). Indicates whether the process
should continue to run as long as files are being watched. If set to
`false` when using `fsevents` to watch, no more events will be emitted
after `ready`, even if the process continues to run.
#### Path filtering
* `ignored` ([anymatch](https://github.com/es128/anymatch)-compatible definition)
Defines files/paths to be ignored. The whole relative or absolute path is
tested, not just filename. If a function with two arguments is provided, it
gets called twice per path - once with a single argument (the path), second
time with two arguments (the path and the
[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats)
object of that path).
* `ignoreInitial` (default: `false`). If set to `false` then `add`/`addDir` events are also emitted for matching paths while
instantiating the watching as chokidar discovers these file paths (before the `ready` event).
* `followSymlinks` (default: `true`). When `false`, only the
symlinks themselves will be watched for changes instead of following
the link references and bubbling events through the link's path.
* `cwd` (no default). The base directory from which watch `paths` are to be
derived. Paths emitted with events will be relative to this.
* `disableGlobbing` (default: `false`). If set to `true` then the strings passed to `.watch()` and `.add()` are treated as
literal path names, even if they look like globs.
#### Performance
* `usePolling` (default: `false`).
Whether to use fs.watchFile (backed by polling), or fs.watch. If polling
leads to high CPU utilization, consider setting this to `false`. It is
typically necessary to **set this to `true` to successfully watch files over
a network**, and it may be necessary to successfully watch files in other
non-standard situations. Setting to `true` explicitly on MacOS overrides the
`useFsEvents` default. You may also set the CHOKIDAR_USEPOLLING env variable
to true (1) or false (0) in order to override this option.
* _Polling-specific settings_ (effective when `usePolling: true`)
* `interval` (default: `100`). Interval of file system polling, in milliseconds. You may also
set the CHOKIDAR_INTERVAL env variable to override this option.
* `binaryInterval` (default: `300`). Interval of file system
polling for binary files.
([see list of binary extensions](https://github.com/sindresorhus/binary-extensions/blob/master/binary-extensions.json))
* `useFsEvents` (default: `true` on MacOS). Whether to use the
`fsevents` watching interface if available. When set to `true` explicitly
and `fsevents` is available this supercedes the `usePolling` setting. When
set to `false` on MacOS, `usePolling: true` becomes the default.
* `alwaysStat` (default: `false`). If relying upon the
[`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats)
object that may get passed with `add`, `addDir`, and `change` events, set
this to `true` to ensure it is provided even in cases where it wasn't
already available from the underlying watch events.
* `depth` (default: `undefined`). If set, limits how many levels of
subdirectories will be traversed.
* `awaitWriteFinish` (default: `false`).
By default, the `add` event will fire when a file first appears on disk, before
the entire file has been written. Furthermore, in some cases some `change`
events will be emitted while the file is being written. In some cases,
especially when watching for large files there will be a need to wait for the
write operation to finish before responding to a file creation or modification.
Setting `awaitWriteFinish` to `true` (or a truthy value) will poll file size,
holding its `add` and `change` events until the size does not change for a
configurable amount of time. The appropriate duration setting is heavily
dependent on the OS and hardware. For accurate detection this parameter should
be relatively high, making file watching much less responsive.
Use with caution.
* *`options.awaitWriteFinish` can be set to an object in order to adjust
timing params:*
* `awaitWriteFinish.stabilityThreshold` (default: 2000). Amount of time in
milliseconds for a file size to remain constant before emitting its event.
* `awaitWriteFinish.pollInterval` (default: 100). File size polling interval, in milliseconds.
#### Errors
* `ignorePermissionErrors` (default: `false`). Indicates whether to watch files
that don't have read permissions if possible. If watching fails due to `EPERM`
or `EACCES` with this set to `true`, the errors will be suppressed silently.
* `atomic` (default: `true` if `useFsEvents` and `usePolling` are `false`).
Automatically filters out artifacts that occur when using editors that use
"atomic writes" instead of writing directly to the source file. If a file is
re-added within 100 ms of being deleted, Chokidar emits a `change` event
rather than `unlink` then `add`. If the default of 100 ms does not work well
for you, you can override it by setting `atomic` to a custom value, in
milliseconds.
### Methods & Events
`chokidar.watch()` produces an instance of `FSWatcher`. Methods of `FSWatcher`:
* `.add(path / paths)`: Add files, directories, or glob patterns for tracking.
Takes an array of strings or just one string.
* `.on(event, callback)`: Listen for an FS event.
Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`,
`raw`, `error`.
Additionally `all` is available which gets emitted with the underlying event
name and path for every event other than `ready`, `raw`, and `error`. `raw` is internal, use it carefully.
* `.unwatch(path / paths)`: Stop watching files, directories, or glob patterns.
Takes an array of strings or just one string.
* `.close()`: **async** Removes all listeners from watched files. Asynchronous, returns Promise. Use with `await` to ensure bugs don't happen.
* `.getWatched()`: Returns an object representing all the paths on the file
system being watched by this `FSWatcher` instance. The object's keys are all the
directories (using absolute paths unless the `cwd` option was used), and the
values are arrays of the names of the items contained in each directory.
## CLI
If you need a CLI interface for your file watching, check out
[chokidar-cli](https://github.com/open-cli-tools/chokidar-cli), allowing you to
execute a command on each change, or get a stdio stream of change events.
## Install Troubleshooting
* `npm WARN optional dep failed, continuing fsevents@n.n.n`
* This message is normal part of how `npm` handles optional dependencies and is
not indicative of a problem. Even if accompanied by other related error messages,
Chokidar should function properly.
* `TypeError: fsevents is not a constructor`
* Update chokidar by doing `rm -rf node_modules package-lock.json yarn.lock && npm install`, or update your dependency that uses chokidar.
* Chokidar is producing `ENOSP` error on Linux, like this:
* `bash: cannot set terminal process group (-1): Inappropriate ioctl for device bash: no job control in this shell`
`Error: watch /home/ ENOSPC`
* This means Chokidar ran out of file handles and you'll need to increase their count by executing the following command in Terminal:
`echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p`
## Changelog
For more detailed changelog, see [`full_changelog.md`](.github/full_changelog.md).
- **v3.5 (Jan 6, 2021):** Support for ARM Macs with Apple Silicon. Fixes for deleted symlinks.
- **v3.4 (Apr 26, 2020):** Support for directory-based symlinks. Fixes for macos file replacement.
- **v3.3 (Nov 2, 2019):** `FSWatcher#close()` method became async. That fixes IO race conditions related to close method.
- **v3.2 (Oct 1, 2019):** Improve Linux RAM usage by 50%. Race condition fixes. Windows glob fixes. Improve stability by using tight range of dependency versions.
- **v3.1 (Sep 16, 2019):** dotfiles are no longer filtered out by default. Use `ignored` option if needed. Improve initial Linux scan time by 50%.
- **v3 (Apr 30, 2019):** massive CPU & RAM consumption improvements; reduces deps / package size by a factor of 17x and bumps Node.js requirement to v8.16 and higher.
- **v2 (Dec 29, 2017):** Globs are now posix-style-only; without windows support. Tons of bugfixes.
- **v1 (Apr 7, 2015):** Glob support, symlink support, tons of bugfixes. Node 0.8+ is supported
- **v0.1 (Apr 20, 2012):** Initial release, extracted from [Brunch](https://github.com/brunch/brunch/blob/9847a065aea300da99bd0753f90354cde9de1261/src/helpers.coffee#L66)
## Also
Why was chokidar named this way? What's the meaning behind it?
>Chowkidar is a transliteration of a Hindi word meaning 'watchman, gatekeeper', चौकीदार. This ultimately comes from Sanskrit _ चतुष्क_ (crossway, quadrangle, consisting-of-four). This word is also used in other languages like Urdu as (چوکیدار) which is widely used in Pakistan and India.
## License
MIT (c) Paul Miller (<https://paulmillr.com>), see [LICENSE](LICENSE) file.

View File

@@ -0,0 +1,60 @@
import type { ContextOptions, DateArg } from "./types.js";
/**
* The {@link differenceInBusinessDays} function options.
*/
export interface DifferenceInBusinessDaysOptions extends ContextOptions<Date> {}
/**
* @name differenceInBusinessDays
* @category Day Helpers
* @summary Get the number of business days between the given dates.
*
* @description
* Get the number of business day periods between the given dates.
* Business days being days that aren't in the weekend.
* Like `differenceInCalendarDays`, the function removes the times from
* the dates before calculating the difference.
*
* @param laterDate - The later date
* @param earlierDate - The earlier date
* @param options - An object with options
*
* @returns The number of business days
*
* @example
* // How many business days are between
* // 10 January 2014 and 20 July 2014?
* const result = differenceInBusinessDays(
* new Date(2014, 6, 20),
* new Date(2014, 0, 10)
* )
* //=> 136
*
* // How many business days are between
* // 30 November 2021 and 1 November 2021?
* const result = differenceInBusinessDays(
* new Date(2021, 10, 30),
* new Date(2021, 10, 1)
* )
* //=> 21
*
* // How many business days are between
* // 1 November 2021 and 1 December 2021?
* const result = differenceInBusinessDays(
* new Date(2021, 10, 1),
* new Date(2021, 11, 1)
* )
* //=> -22
*
* // How many business days are between
* // 1 November 2021 and 1 November 2021 ?
* const result = differenceInBusinessDays(
* new Date(2021, 10, 1),
* new Date(2021, 10, 1)
* )
* //=> 0
*/
export declare function differenceInBusinessDays(
laterDate: DateArg<Date> & {},
earlierDate: DateArg<Date> & {},
options?: DifferenceInBusinessDaysOptions | undefined,
): number;

View File

@@ -0,0 +1,52 @@
#!/usr/bin/env node
var which = require("../")
if (process.argv.length < 3)
usage()
function usage () {
console.error('usage: which [-as] program ...')
process.exit(1)
}
var all = false
var silent = false
var dashdash = false
var args = process.argv.slice(2).filter(function (arg) {
if (dashdash || !/^-/.test(arg))
return true
if (arg === '--') {
dashdash = true
return false
}
var flags = arg.substr(1).split('')
for (var f = 0; f < flags.length; f++) {
var flag = flags[f]
switch (flag) {
case 's':
silent = true
break
case 'a':
all = true
break
default:
console.error('which: illegal option -- ' + flag)
usage()
}
}
return false
})
process.exit(args.reduce(function (pv, current) {
try {
var f = which.sync(current, { all: all })
if (all)
f = f.join('\n')
if (!silent)
console.log(f)
return pv;
} catch (e) {
return 1;
}
}, 0))

View File

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

View File

@@ -0,0 +1 @@
export type ElementOf<Type extends readonly any[]> = Type extends readonly (infer Values)[] ? Values : never;

View File

@@ -0,0 +1,8 @@
{
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"printWidth": 100,
"trailingComma": "all"
}

View File

@@ -0,0 +1,5 @@
export function withPayload(nextConfig?: import("next").NextConfig, options?: {
devBundleServerPackages?: boolean;
}): import("next").NextConfig;
export default withPayload;
//# sourceMappingURL=withPayload.d.ts.map

View File

@@ -0,0 +1,7 @@
/** Internal global with common properties and Sentry extensions */
/** Get's the global object for the current JavaScript runtime */
const GLOBAL_OBJ = globalThis ;
export { GLOBAL_OBJ };
//# sourceMappingURL=worldwide.js.map

View File

@@ -0,0 +1,147 @@
'use client';
import { getTranslation } from '@payloadcms/translations';
import { formatDocTitle } from '../../utilities/formatDocTitle/index.js';
const reduceToIDs = options => options.reduce((ids, option) => {
if (option.options) {
return [...ids, ...reduceToIDs(option.options)];
}
return [...ids, {
id: option.value,
relationTo: option.relationTo
}];
}, []);
const sortOptions = options => options.sort((a, b) => {
if (typeof a?.label?.localeCompare === 'function' && typeof b?.label?.localeCompare === 'function') {
return a.label.localeCompare(b.label);
}
return 0;
});
export const optionsReducer = (state, action) => {
switch (action.type) {
case 'ADD':
{
const {
collection,
config,
docs,
i18n,
ids = [],
sort
} = action;
const relation = collection.slug;
const loadedIDs = reduceToIDs(state);
const newOptions = [...state];
const optionsToAddTo = newOptions.find(optionGroup => optionGroup.label === collection.labels.plural);
const newSubOptions = docs.reduce((docSubOptions, doc) => {
if (loadedIDs.filter(item => item.id === doc.id && item.relationTo === relation).length === 0) {
loadedIDs.push({
id: doc.id,
relationTo: relation
});
const docTitle = formatDocTitle({
collectionConfig: collection,
data: doc,
dateFormat: config.admin.dateFormat,
fallback: `${i18n.t('general:untitled')} - ID: ${doc.id}`,
i18n
});
return [...docSubOptions, {
label: docTitle,
relationTo: relation,
value: doc.id
}];
}
return docSubOptions;
}, []);
ids.forEach(id => {
if (loadedIDs.filter(item => item.id === id && item.relationTo === relation).length === 0) {
loadedIDs.push({
id,
relationTo: relation
});
newSubOptions.push({
allowEdit: false,
label: `${i18n.t('general:untitled')} - ID: ${id}`,
relationTo: relation,
value: id
});
}
});
if (optionsToAddTo) {
const subOptions = [...optionsToAddTo.options, ...newSubOptions];
optionsToAddTo.options = sort ? sortOptions(subOptions) : subOptions;
} else {
newOptions.push({
label: getTranslation(collection.labels.plural, i18n),
options: sort ? sortOptions(newSubOptions) : newSubOptions
});
}
return newOptions;
}
case 'CLEAR':
{
const exemptValues = action.exemptValues ? Array.isArray(action.exemptValues) ? action.exemptValues : [action.exemptValues] : [];
const clearedStateWithExemptValues = state.filter(optionGroup => {
const clearedOptions = optionGroup.options.filter(option => {
if (exemptValues) {
return exemptValues.some(exemptValue => {
return exemptValue && option.value === exemptValue.value;
});
}
return false;
});
optionGroup.options = clearedOptions;
return clearedOptions.length > 0;
});
return clearedStateWithExemptValues;
}
case 'REMOVE':
{
const {
id,
collection
} = action;
const newOptions = [...state];
const indexOfGroup = newOptions.findIndex(optionGroup => optionGroup.label === collection.labels.plural);
if (indexOfGroup === -1) {
return newOptions;
}
newOptions[indexOfGroup] = {
...newOptions[indexOfGroup],
options: newOptions[indexOfGroup].options.filter(option => option.value !== id)
};
return newOptions;
}
case 'UPDATE':
{
const {
collection,
config,
doc,
i18n
} = action;
const relation = collection.slug;
const newOptions = [...state];
const docTitle = formatDocTitle({
collectionConfig: collection,
data: doc,
dateFormat: config.admin.dateFormat,
fallback: `${i18n.t('general:untitled')} - ID: ${doc.id}`,
i18n
});
const foundOptionGroup = newOptions.find(optionGroup => optionGroup.label === collection.labels.plural);
const foundOption = foundOptionGroup?.options?.find(option => option.value === doc.id);
if (foundOption) {
foundOption.label = docTitle;
foundOption.relationTo = relation;
}
return newOptions;
}
default:
{
return state;
}
}
};
//# sourceMappingURL=optionsReducer.js.map

View File

@@ -0,0 +1,22 @@
const { dirname, resolve } = require('path');
const { readdir, stat } = require('fs');
const { promisify } = require('util');
const toStats = promisify(stat);
const toRead = promisify(readdir);
module.exports = async function (start, callback) {
let dir = resolve('.', start);
let tmp, stats = await toStats(dir);
if (!stats.isDirectory()) {
dir = dirname(dir);
}
while (true) {
tmp = await callback(dir, await toRead(dir));
if (tmp) return resolve(dir, tmp);
dir = dirname(tmp = dir);
if (tmp === dir) break;
}
}

View File

@@ -0,0 +1,9 @@
export { default as IntlProvider } from './IntlProvider.js';
export { default as useTranslations } from './useTranslations.js';
export { default as useLocale } from './useLocale.js';
export { default as useNow } from './useNow.js';
export { default as useTimeZone } from './useTimeZone.js';
export { default as useMessages } from './useMessages.js';
export { default as useFormatter } from './useFormatter.js';
/** @private -- Only for usage in `next-intl` currently */
export { default as _useExtracted } from './useExtracted.js';

View File

@@ -0,0 +1 @@
{"version":3,"file":"arrow-left.js","sources":["../../../src/icons/arrow-left.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name ArrowLeft\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJtMTIgMTktNy03IDctNyIgLz4KICA8cGF0aCBkPSJNMTkgMTJINSIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/arrow-left\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 ArrowLeft = createLucideIcon('ArrowLeft', [\n ['path', { d: 'm12 19-7-7 7-7', key: '1l729n' }],\n ['path', { d: 'M19 12H5', key: 'x3x0zl' }],\n]);\n\nexport default ArrowLeft;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAY,iBAAiB,WAAa,CAAA,CAAA,CAAA;AAAA,CAAA,CAC9C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAkB,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,CAC/C,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;AAC3C,CAAC,CAAA,CAAA;;"}

View File

@@ -0,0 +1,74 @@
# pump
pump is a small node module that pipes streams together and destroys all of them if one of them closes.
```
npm install pump
```
[![build status](http://img.shields.io/travis/mafintosh/pump.svg?style=flat)](http://travis-ci.org/mafintosh/pump)
## What problem does it solve?
When using standard `source.pipe(dest)` source will _not_ be destroyed if dest emits close or an error.
You are also not able to provide a callback to tell when then pipe has finished.
pump does these two things for you
## Usage
Simply pass the streams you want to pipe together to pump and add an optional callback
``` js
var pump = require('pump')
var fs = require('fs')
var source = fs.createReadStream('/dev/random')
var dest = fs.createWriteStream('/dev/null')
pump(source, dest, function(err) {
console.log('pipe finished', err)
})
setTimeout(function() {
dest.destroy() // when dest is closed pump will destroy source
}, 1000)
```
You can use pump to pipe more than two streams together as well
``` js
var transform = someTransformStream()
pump(source, transform, anotherTransform, dest, function(err) {
console.log('pipe finished', err)
})
```
If `source`, `transform`, `anotherTransform` or `dest` closes all of them will be destroyed.
Similarly to `stream.pipe()`, `pump()` returns the last stream passed in, so you can do:
```
return pump(s1, s2) // returns s2
```
Note that `pump` attaches error handlers to the streams to do internal error handling, so if `s2` emits an
error in the above scenario, it will not trigger a `proccess.on('uncaughtException')` if you do not listen for it.
If you want to return a stream that combines *both* s1 and s2 to a single stream use
[pumpify](https://github.com/mafintosh/pumpify) instead.
## License
MIT
## Related
`pump` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one.
## For enterprise
Available as part of the Tidelift Subscription.
The maintainers of pump and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-pump?utm_source=npm-pump&utm_medium=referral&utm_campaign=enterprise)

View File

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

View File

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

View File

@@ -0,0 +1,31 @@
import { NestedPartial, UnpackList } from "../../../types/utils.cjs";
import { CollectionType } from "../../../types/schema.cjs";
import { ApplyQueryFields } from "../../../types/output.cjs";
import { Query } from "../../../types/query.cjs";
import { RestCommand } from "../../types.cjs";
//#region src/rest/commands/create/items.d.ts
type CreateItemOutput<Schema, Collection extends keyof Schema, TQuery extends Query<Schema, Schema[Collection]>> = ApplyQueryFields<Schema, CollectionType<Schema, Collection>, TQuery['fields']>;
/**
* Create new items in the given collection.
*
* @param collection The collection of the item
* @param items The items to create
* @param query Optional return data query
*
* @returns Returns the item objects of the item that were created.
*/
declare const createItems: <Schema, Collection extends keyof Schema, const TQuery extends Query<Schema, Schema[Collection]>>(collection: Collection, items: NestedPartial<UnpackList<Schema[Collection]>>[], query?: TQuery) => RestCommand<CreateItemOutput<Schema, Collection, TQuery>[], Schema>;
/**
* Create a new item in the given collection.
*
* @param collection The collection of the item
* @param item The item to create
* @param query Optional return data query
*
* @returns Returns the item objects of the item that were created.
*/
declare const createItem: <Schema, Collection extends keyof Schema, const TQuery extends Query<Schema, Schema[Collection]>>(collection: Collection, item: NestedPartial<UnpackList<Schema[Collection]>>, query?: TQuery) => RestCommand<CreateItemOutput<Schema, Collection, TQuery>, Schema>;
//#endregion
export { CreateItemOutput, createItem, createItems };
//# sourceMappingURL=items.d.cts.map

View File

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

View File

@@ -0,0 +1,27 @@
import type { Mechanism, WrappedFunction } from '@sentry/core';
import { GLOBAL_OBJ } from '@sentry/core';
export declare const WINDOW: typeof GLOBAL_OBJ & Window;
/**
* @hidden
*/
export declare function shouldIgnoreOnError(): boolean;
/**
* @hidden
*/
export declare function ignoreNextOnError(): void;
type WrappableFunction = Function;
export declare function wrap<T extends WrappableFunction>(fn: T, options?: {
mechanism?: Mechanism;
}): WrappedFunction<T>;
export declare function wrap<NonFunction>(fn: NonFunction, options?: {
mechanism?: Mechanism;
}): NonFunction;
/**
* Get HTTP request data from the current page.
*/
export declare function getHttpRequestData(): {
url: string;
headers: Record<string, string>;
};
export {};
//# sourceMappingURL=helpers.d.ts.map

View File

@@ -0,0 +1,38 @@
'use strict'
const { test } = require('tap')
const { join } = require('path')
const ThreadStream = require('..')
const { file } = require('./helper')
const MAX = 1000
let str = ''
for (let i = 0; i < 10; i++) {
str += 'hello'
}
test('base', function (t) {
const dest = file()
const stream = new ThreadStream({
filename: join(__dirname, 'to-file.js'),
workerData: { dest }
})
let runs = 0
function benchThreadStream () {
if (++runs === 1000) {
stream.end()
return
}
for (let i = 0; i < MAX; i++) {
stream.write(str)
}
setImmediate(benchThreadStream)
}
benchThreadStream()
stream.on('finish', function () {
t.end()
})
})

View File

@@ -0,0 +1,22 @@
import { _ as _unsupported_iterable_to_array } from "./_unsupported_iterable_to_array.js";
function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
if (it) return (it = it.call(o)).next.bind(it);
// Fallback for engines without symbol support
if (Array.isArray(o) || (it = _unsupported_iterable_to_array(o)) || allowArrayLike && o && typeof o.length === "number") {
if (it) o = it;
var i = 0;
return function() {
if (i >= o.length) return { done: true };
return { done: false, value: o[i++] };
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
export { _create_for_of_iterator_helper_loose as _ };

View File

@@ -0,0 +1,6 @@
/**
* Runs the passed callback during the next idle period, or immediately
* if the browser's visibility state is (or becomes) hidden.
*/
export declare const whenIdleOrHidden: (cb: () => void) => void;
//# sourceMappingURL=whenIdleOrHidden.d.ts.map

View File

@@ -0,0 +1,134 @@
"use strict";
exports.match = void 0;
var _index = require("../../_lib/buildMatchFn.cjs");
var _index2 = require("../../_lib/buildMatchPatternFn.cjs");
const matchOrdinalNumberPattern = /^(\d+)\./i;
const parseOrdinalNumberPattern = /\d+/i;
const matchEraPatterns = {
narrow: /^(pr\.n\.e\.|AD)/i,
abbreviated: /^(pr\.\s?Hr\.|po\.\s?Hr\.)/i,
wide: /^(Pre Hrista|pre nove ere|Posle Hrista|nova era)/i,
};
const parseEraPatterns = {
any: [/^pr/i, /^(po|nova)/i],
};
const matchQuarterPatterns = {
narrow: /^[1234]/i,
abbreviated: /^[1234]\.\s?kv\.?/i,
wide: /^[1234]\. kvartal/i,
};
const parseQuarterPatterns = {
any: [/1/i, /2/i, /3/i, /4/i],
};
const matchMonthPatterns = {
narrow: /^(10|11|12|[123456789])\./i,
abbreviated: /^(jan|feb|mar|apr|maj|jun|jul|avg|sep|okt|nov|dec)/i,
wide: /^((januar|januara)|(februar|februara)|(mart|marta)|(april|aprila)|(maj|maja)|(jun|juna)|(jul|jula)|(avgust|avgusta)|(septembar|septembra)|(oktobar|oktobra)|(novembar|novembra)|(decembar|decembra))/i,
};
const parseMonthPatterns = {
narrow: [
/^1/i,
/^2/i,
/^3/i,
/^4/i,
/^5/i,
/^6/i,
/^7/i,
/^8/i,
/^9/i,
/^10/i,
/^11/i,
/^12/i,
],
any: [
/^ja/i,
/^f/i,
/^mar/i,
/^ap/i,
/^maj/i,
/^jun/i,
/^jul/i,
/^avg/i,
/^s/i,
/^o/i,
/^n/i,
/^d/i,
],
};
const matchDayPatterns = {
narrow: /^[npusčc]/i,
short: /^(ned|pon|uto|sre|(čet|cet)|pet|sub)/i,
abbreviated: /^(ned|pon|uto|sre|(čet|cet)|pet|sub)/i,
wide: /^(nedelja|ponedeljak|utorak|sreda|(četvrtak|cetvrtak)|petak|subota)/i,
};
const parseDayPatterns = {
narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i],
};
const matchDayPeriodPatterns = {
any: /^(am|pm|ponoc|ponoć|(po)?podne|uvece|uveče|noću|posle podne|ujutru)/i,
};
const parseDayPeriodPatterns = {
any: {
am: /^a/i,
pm: /^p/i,
midnight: /^pono/i,
noon: /^pod/i,
morning: /jutro/i,
afternoon: /(posle\s|po)+podne/i,
evening: /(uvece|uveče)/i,
night: /(nocu|noću)/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,7 @@
"use strict";
exports.format = void 0;
var _index = require("../format.cjs");
var _index2 = require("./_lib/convertToFP.cjs"); // This file is generated automatically by `scripts/build/fp.ts`. Please, don't change it.
const format = (exports.format = (0, _index2.convertToFP)(_index.format, 2));

View File

@@ -0,0 +1,24 @@
import type { CollectionPermission, FieldPermissions, FieldsPermissions, GlobalPermission } from '../../auth/types.js';
import type { DefaultDocumentIDType } from '../../index.js';
import type { AllOperations, JsonObject, PayloadRequest } from '../../types/index.js';
import type { BlockReferencesPermissions } from './getEntityPermissions.js';
import { type Field } from '../../fields/config/types.js';
/**
* Build up permissions object and run access functions for each field of an entity
* This function is synchronous and collects all async work into the promises array
*/
export declare const populateFieldPermissions: ({ id, blockReferencesPermissions, data, fields, operations, parentPermissionsObject, permissionsObject, promises, req, }: {
blockReferencesPermissions: BlockReferencesPermissions;
data: JsonObject | undefined;
fields: Field[];
id?: DefaultDocumentIDType;
/**
* Operations to check access for
*/
operations: AllOperations[];
parentPermissionsObject: CollectionPermission | FieldPermissions | GlobalPermission;
permissionsObject: FieldsPermissions;
promises: Promise<void>[];
req: PayloadRequest;
}) => void;
//# sourceMappingURL=populateFieldPermissions.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}

View File

@@ -0,0 +1,5 @@
var convert = require('./convert'),
func = convert('uniqWith', require('../uniqWith'));
func.placeholder = require('./placeholder');
module.exports = func;

View File

@@ -0,0 +1,4 @@
export declare function invariant(
condition: unknown,
message?: string,
): asserts condition;

View File

@@ -0,0 +1,74 @@
/**
* The value of `this` in the context of a {@link LegacyImporter} or {@link
* LegacyFunction} callback.
*
* @category Legacy
* @deprecated This is only used by the legacy {@link render} and {@link
* renderSync} APIs. Use {@link compile}, {@link compileString}, {@link
* compileAsync}, and {@link compileStringAsync} instead.
*/
export interface LegacyPluginThis {
/**
* A partial representation of the options passed to {@link render} or {@link
* renderSync}.
*/
options: {
/** The same {@link LegacyPluginThis} instance that contains this object. */
context: LegacyPluginThis;
/**
* The value passed to {@link LegacyFileOptions.file} or {@link
* LegacyStringOptions.file}.
*/
file?: string;
/** The value passed to {@link LegacyStringOptions.data}. */
data?: string;
/**
* The value passed to {@link LegacySharedOptions.includePaths} separated by
* `";"` on Windows or `":"` on other operating systems. This always
* includes the current working directory as the first entry.
*/
includePaths: string;
/** Always the number 10. */
precision: 10;
/** Always the number 1. */
style: 1;
/** 1 if {@link LegacySharedOptions.indentType} was `"tab"`, 0 otherwise. */
indentType: 1 | 0;
/**
* The value passed to {@link LegacySharedOptions.indentWidth}, or `2`
* otherwise.
*/
indentWidth: number;
/**
* The value passed to {@link LegacySharedOptions.linefeed}, or `"\n"`
* otherwise.
*/
linefeed: '\r' | '\r\n' | '\n' | '\n\r';
/** A partially-constructed {@link LegacyResult} object. */
result: {
/** Partial information about the compilation in progress. */
stats: {
/**
* The number of milliseconds between 1 January 1970 at 00:00:00 UTC and
* the time at which Sass compilation began.
*/
start: number;
/**
* {@link LegacyFileOptions.file} if it was passed, otherwise the string
* `"data"`.
*/
entry: string;
};
};
};
}

View File

@@ -0,0 +1,263 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const carrier = require('../carrier.js');
const dsn = require('./dsn.js');
const normalize = require('./normalize.js');
const worldwide = require('./worldwide.js');
/**
* Creates an envelope.
* Make sure to always explicitly provide the generic to this function
* so that the envelope types resolve correctly.
*/
function createEnvelope(headers, items = []) {
return [headers, items] ;
}
/**
* Add an item to an envelope.
* Make sure to always explicitly provide the generic to this function
* so that the envelope types resolve correctly.
*/
function addItemToEnvelope(envelope, newItem) {
const [headers, items] = envelope;
return [headers, [...items, newItem]] ;
}
/**
* Convenience function to loop through the items and item types of an envelope.
* (This function was mostly created because working with envelope types is painful at the moment)
*
* If the callback returns true, the rest of the items will be skipped.
*/
function forEachEnvelopeItem(
envelope,
callback,
) {
const envelopeItems = envelope[1];
for (const envelopeItem of envelopeItems) {
const envelopeItemType = envelopeItem[0].type;
const result = callback(envelopeItem, envelopeItemType);
if (result) {
return true;
}
}
return false;
}
/**
* Returns true if the envelope contains any of the given envelope item types
*/
function envelopeContainsItemType(envelope, types) {
return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));
}
/**
* Encode a string to UTF8 array.
*/
function encodeUTF8(input) {
const carrier$1 = carrier.getSentryCarrier(worldwide.GLOBAL_OBJ);
return carrier$1.encodePolyfill ? carrier$1.encodePolyfill(input) : new TextEncoder().encode(input);
}
/**
* Decode a UTF8 array to string.
*/
function decodeUTF8(input) {
const carrier$1 = carrier.getSentryCarrier(worldwide.GLOBAL_OBJ);
return carrier$1.decodePolyfill ? carrier$1.decodePolyfill(input) : new TextDecoder().decode(input);
}
/**
* Serializes an envelope.
*/
function serializeEnvelope(envelope) {
const [envHeaders, items] = envelope;
// Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data
let parts = JSON.stringify(envHeaders);
function append(next) {
if (typeof parts === 'string') {
parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts), next];
} else {
parts.push(typeof next === 'string' ? encodeUTF8(next) : next);
}
}
for (const item of items) {
const [itemHeaders, payload] = item;
append(`\n${JSON.stringify(itemHeaders)}\n`);
if (typeof payload === 'string' || payload instanceof Uint8Array) {
append(payload);
} else {
let stringifiedPayload;
try {
stringifiedPayload = JSON.stringify(payload);
} catch {
// In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.stringify()` still
// fails, we try again after normalizing it again with infinite normalization depth. This of course has a
// performance impact but in this case a performance hit is better than throwing.
stringifiedPayload = JSON.stringify(normalize.normalize(payload));
}
append(stringifiedPayload);
}
}
return typeof parts === 'string' ? parts : concatBuffers(parts);
}
function concatBuffers(buffers) {
const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);
const merged = new Uint8Array(totalLength);
let offset = 0;
for (const buffer of buffers) {
merged.set(buffer, offset);
offset += buffer.length;
}
return merged;
}
/**
* Parses an envelope
*/
function parseEnvelope(env) {
let buffer = typeof env === 'string' ? encodeUTF8(env) : env;
function readBinary(length) {
const bin = buffer.subarray(0, length);
// Replace the buffer with the remaining data excluding trailing newline
buffer = buffer.subarray(length + 1);
return bin;
}
function readJson() {
let i = buffer.indexOf(0xa);
// If we couldn't find a newline, we must have found the end of the buffer
if (i < 0) {
i = buffer.length;
}
return JSON.parse(decodeUTF8(readBinary(i))) ;
}
const envelopeHeader = readJson();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const items = [];
while (buffer.length) {
const itemHeader = readJson();
const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;
items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);
}
return [envelopeHeader, items];
}
/**
* Creates envelope item for a single span
*/
function createSpanEnvelopeItem(spanJson) {
const spanHeaders = {
type: 'span',
};
return [spanHeaders, spanJson];
}
/**
* Creates attachment envelope items
*/
function createAttachmentEnvelopeItem(attachment) {
const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data) : attachment.data;
return [
{
type: 'attachment',
length: buffer.length,
filename: attachment.filename,
content_type: attachment.contentType,
attachment_type: attachment.attachmentType,
},
buffer,
];
}
const ITEM_TYPE_TO_DATA_CATEGORY_MAP = {
session: 'session',
sessions: 'session',
attachment: 'attachment',
transaction: 'transaction',
event: 'error',
client_report: 'internal',
user_report: 'default',
profile: 'profile',
profile_chunk: 'profile',
replay_event: 'replay',
replay_recording: 'replay',
check_in: 'monitor',
feedback: 'feedback',
span: 'span',
raw_security: 'security',
log: 'log_item',
metric: 'metric',
trace_metric: 'metric',
};
/**
* Maps the type of an envelope item to a data category.
*/
function envelopeItemTypeToDataCategory(type) {
return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];
}
/** Extracts the minimal SDK info from the metadata or an events */
function getSdkMetadataForEnvelopeHeader(metadataOrEvent) {
if (!metadataOrEvent?.sdk) {
return;
}
const { name, version } = metadataOrEvent.sdk;
return { name, version };
}
/**
* Creates event envelope headers, based on event, sdk info and tunnel
* Note: This function was extracted from the core package to make it available in Replay
*/
function createEventEnvelopeHeaders(
event,
sdkInfo,
tunnel,
dsn$1,
) {
const dynamicSamplingContext = event.sdkProcessingMetadata?.dynamicSamplingContext;
return {
event_id: event.event_id ,
sent_at: new Date().toISOString(),
...(sdkInfo && { sdk: sdkInfo }),
...(!!tunnel && dsn$1 && { dsn: dsn.dsnToString(dsn$1) }),
...(dynamicSamplingContext && {
trace: dynamicSamplingContext,
}),
};
}
exports.addItemToEnvelope = addItemToEnvelope;
exports.createAttachmentEnvelopeItem = createAttachmentEnvelopeItem;
exports.createEnvelope = createEnvelope;
exports.createEventEnvelopeHeaders = createEventEnvelopeHeaders;
exports.createSpanEnvelopeItem = createSpanEnvelopeItem;
exports.envelopeContainsItemType = envelopeContainsItemType;
exports.envelopeItemTypeToDataCategory = envelopeItemTypeToDataCategory;
exports.forEachEnvelopeItem = forEachEnvelopeItem;
exports.getSdkMetadataForEnvelopeHeader = getSdkMetadataForEnvelopeHeader;
exports.parseEnvelope = parseEnvelope;
exports.serializeEnvelope = serializeEnvelope;
//# sourceMappingURL=envelope.js.map

View File

@@ -0,0 +1,59 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const core = require('@sentry/core');
const debugBuild = require('../debug-build.js');
const helpers = require('../helpers.js');
/**
* Returns true if the SDK is running in an embedded browser extension.
* Stand-alone browser extensions (which do not share the same data as the main browser page) are fine.
*/
function checkAndWarnIfIsEmbeddedBrowserExtension() {
if (_isEmbeddedBrowserExtension()) {
if (debugBuild.DEBUG_BUILD) {
core.consoleSandbox(() => {
// eslint-disable-next-line no-console
console.error(
'[Sentry] You cannot use Sentry.init() in a browser extension, see: https://docs.sentry.io/platforms/javascript/best-practices/browser-extensions/',
);
});
}
return true;
}
return false;
}
function _isEmbeddedBrowserExtension() {
if (typeof helpers.WINDOW.window === 'undefined') {
// No need to show the error if we're not in a browser window environment (e.g. service workers)
return false;
}
const _window = helpers.WINDOW ;
// Running the SDK in NW.js, which appears like a browser extension but isn't, is also fine
// see: https://github.com/getsentry/sentry-javascript/issues/12668
if (_window.nw) {
return false;
}
const extensionObject = _window['chrome'] || _window['browser'];
if (!extensionObject?.runtime?.id) {
return false;
}
const href = core.getLocationHref();
const extensionProtocols = ['chrome-extension', 'moz-extension', 'ms-browser-extension', 'safari-web-extension'];
// Running the SDK in a dedicated extension page and calling Sentry.init is fine; no risk of data leakage
const isDedicatedExtensionPage =
helpers.WINDOW === helpers.WINDOW.top && extensionProtocols.some(protocol => href.startsWith(`${protocol}://`));
return !isDedicatedExtensionPage;
}
exports.checkAndWarnIfIsEmbeddedBrowserExtension = checkAndWarnIfIsEmbeddedBrowserExtension;
//# sourceMappingURL=detectBrowserExtension.js.map

View File

@@ -0,0 +1,12 @@
import { ReportDialogOptions } from './report-dialog';
import { DsnComponents, DsnLike } from './types-hoist/dsn';
import { SdkInfo } from './types-hoist/sdkinfo';
/**
* Returns the envelope endpoint URL with auth in the query string.
*
* Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.
*/
export declare function getEnvelopeEndpointWithUrlEncodedAuth(dsn: DsnComponents, tunnel?: string, sdkInfo?: SdkInfo): string;
/** Returns the url to the report dialog endpoint. */
export declare function getReportDialogEndpoint(dsnLike: DsnLike, dialogOptions: ReportDialogOptions): string;
//# sourceMappingURL=api.d.ts.map

View File

@@ -0,0 +1,13 @@
import { Scope } from '../scope';
import { Span } from '../types-hoist/span';
/** Store the scope & isolation scope for a span, which can the be used when it is finished. */
export declare function setCapturedScopesOnSpan(span: Span | undefined, scope: Scope, isolationScope: Scope): void;
/**
* Grabs the scope and isolation scope off a span that were active when the span was started.
* If WeakRef was used and scopes have been garbage collected, returns undefined for those scopes.
*/
export declare function getCapturedScopesOnSpan(span: Span): {
scope?: Scope;
isolationScope?: Scope;
};
//# sourceMappingURL=utils.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../src/cacheWrapper.ts"],"names":["cacheWrapper","cache","key","fn","cached","get","undefined","result","set","cacheWrapperSync"],"mappings":";;;;;;;;AAEA,eAAeA,YAAf,CACEC,KADF,EAEEC,GAFF,EAGEC,EAHF,EAI8B;AAC5B,QAAMC,MAAM,GAAGH,KAAK,CAACI,GAAN,CAAUH,GAAV,CAAf;;AACA,MAAIE,MAAM,KAAKE,SAAf,EAA0B;AACxB,WAAOF,MAAP;AACD;;AAED,QAAMG,MAAM,GAAG,MAAMJ,EAAE,EAAvB;AACAF,EAAAA,KAAK,CAACO,GAAN,CAAUN,GAAV,EAAeK,MAAf;AACA,SAAOA,MAAP;AACD;;AAED,SAASE,gBAAT,CACER,KADF,EAEEC,GAFF,EAGEC,EAHF,EAIqB;AACnB,QAAMC,MAAM,GAAGH,KAAK,CAACI,GAAN,CAAUH,GAAV,CAAf;;AACA,MAAIE,MAAM,KAAKE,SAAf,EAA0B;AACxB,WAAOF,MAAP;AACD;;AAED,QAAMG,MAAM,GAAGJ,EAAE,EAAjB;AACAF,EAAAA,KAAK,CAACO,GAAN,CAAUN,GAAV,EAAeK,MAAf;AACA,SAAOA,MAAP;AACD","sourcesContent":["import { Cache, CosmiconfigResult } from './types';\n\nasync function cacheWrapper(\n cache: Cache,\n key: string,\n fn: () => Promise<CosmiconfigResult>,\n): Promise<CosmiconfigResult> {\n const cached = cache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n\n const result = await fn();\n cache.set(key, result);\n return result;\n}\n\nfunction cacheWrapperSync(\n cache: Cache,\n key: string,\n fn: () => CosmiconfigResult,\n): CosmiconfigResult {\n const cached = cache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n\n const result = fn();\n cache.set(key, result);\n return result;\n}\n\nexport { cacheWrapper, cacheWrapperSync };\n"],"file":"cacheWrapper.js"}

View File

@@ -0,0 +1,25 @@
import { debug } from '@sentry/core';
import type { NetworkMetaWarning } from './types';
export declare const ORIGINAL_REQ_BODY: unique symbol;
/**
* Serializes FormData.
*
* This is a bit simplified, but gives us a decent estimate.
* This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13'.
*
*/
export declare function serializeFormData(formData: FormData): string;
/** Get the string representation of a body. */
export declare function getBodyString(body: unknown, _debug?: typeof debug): [string | undefined, NetworkMetaWarning?];
/**
* Parses the fetch arguments to extract the request payload.
*
* In case of a Request object, this function attempts to retrieve the original body by looking for a Sentry-patched symbol.
*/
export declare function getFetchRequestArgBody(fetchArgs?: unknown[]): RequestInit['body'] | undefined;
/**
* Parses XMLHttpRequest response headers into a Record.
* Extracted from replay internals to be reusable.
*/
export declare function parseXhrResponseHeaders(xhr: XMLHttpRequest): Record<string, string>;
//# sourceMappingURL=networkUtils.d.ts.map

View File

@@ -0,0 +1,279 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { OriginalSource, RawSource } = require("webpack-sources");
const Module = require("./Module");
const {
JAVASCRIPT_TYPE,
JAVASCRIPT_TYPES
} = require("./ModuleSourceTypeConstants");
const { JAVASCRIPT_MODULE_TYPE_DYNAMIC } = require("./ModuleTypeConstants");
const RuntimeGlobals = require("./RuntimeGlobals");
const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency");
const StaticExportsDependency = require("./dependencies/StaticExportsDependency");
const makeSerializable = require("./util/makeSerializable");
/** @typedef {import("../declarations/plugins/DllReferencePlugin").DllReferencePluginOptions} DllReferencePluginOptions */
/** @typedef {import("./config/defaults").WebpackOptionsNormalizedWithDefaults} WebpackOptions */
/** @typedef {import("./Compilation")} Compilation */
/** @typedef {import("./Dependency").UpdateHashContext} UpdateHashContext */
/** @typedef {import("./Generator").SourceTypes} SourceTypes */
/** @typedef {import("./LibManifestPlugin").ManifestModuleData} ManifestModuleData */
/** @typedef {import("./Module").ModuleId} ModuleId */
/** @typedef {import("./Module").BuildCallback} BuildCallback */
/** @typedef {import("./Module").BuildMeta} BuildMeta */
/** @typedef {import("./Module").CodeGenerationContext} CodeGenerationContext */
/** @typedef {import("./Module").CodeGenerationResult} CodeGenerationResult */
/** @typedef {import("./Module").LibIdentOptions} LibIdentOptions */
/** @typedef {import("./Module").LibIdent} LibIdent */
/** @typedef {import("./Module").NeedBuildCallback} NeedBuildCallback */
/** @typedef {import("./Module").NeedBuildContext} NeedBuildContext */
/** @typedef {import("./Module").Sources} Sources */
/** @typedef {import("./Module").RuntimeRequirements} RuntimeRequirements */
/** @typedef {import("./RequestShortener")} RequestShortener */
/** @typedef {import("./ResolverFactory").ResolverWithOptions} ResolverWithOptions */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectDeserializerContext} ObjectDeserializerContext */
/** @typedef {import("./serialization/ObjectMiddleware").ObjectSerializerContext} ObjectSerializerContext */
/** @typedef {import("./dependencies/StaticExportsDependency").Exports} Exports */
/** @typedef {import("./util/Hash")} Hash */
/** @typedef {import("./util/fs").InputFileSystem} InputFileSystem */
/** @typedef {string} DelegatedModuleSourceRequest */
/** @typedef {NonNullable<DllReferencePluginOptions["type"]>} DelegatedModuleType */
/**
* @typedef {object} DelegatedModuleData
* @property {BuildMeta=} buildMeta build meta
* @property {Exports=} exports exports
* @property {ModuleId} id module id
*/
const RUNTIME_REQUIREMENTS = new Set([
RuntimeGlobals.module,
RuntimeGlobals.require
]);
class DelegatedModule extends Module {
/**
* @param {DelegatedModuleSourceRequest} sourceRequest source request
* @param {DelegatedModuleData} data data
* @param {DelegatedModuleType} type type
* @param {string} userRequest user request
* @param {string | Module} originalRequest original request
*/
constructor(sourceRequest, data, type, userRequest, originalRequest) {
super(JAVASCRIPT_MODULE_TYPE_DYNAMIC, null);
// Info from Factory
this.sourceRequest = sourceRequest;
this.request = data.id;
this.delegationType = type;
this.userRequest = userRequest;
this.originalRequest = originalRequest;
this.delegateData = data;
// Build info
/** @type {undefined | DelegatedSourceDependency} */
this.delegatedSourceDependency = undefined;
}
/**
* @returns {SourceTypes} types available (do not mutate)
*/
getSourceTypes() {
return JAVASCRIPT_TYPES;
}
/**
* @param {LibIdentOptions} options options
* @returns {LibIdent | null} an identifier for library inclusion
*/
libIdent(options) {
return typeof this.originalRequest === "string"
? this.originalRequest
: this.originalRequest.libIdent(options);
}
/**
* @returns {string} a unique identifier of the module
*/
identifier() {
return `delegated ${JSON.stringify(this.request)} from ${
this.sourceRequest
}`;
}
/**
* @param {RequestShortener} requestShortener the request shortener
* @returns {string} a user readable identifier of the module
*/
readableIdentifier(requestShortener) {
return `delegated ${this.userRequest} from ${this.sourceRequest}`;
}
/**
* @param {NeedBuildContext} context context info
* @param {NeedBuildCallback} callback callback function, returns true, if the module needs a rebuild
* @returns {void}
*/
needBuild(context, callback) {
return callback(null, !this.buildMeta);
}
/**
* @param {WebpackOptions} options webpack options
* @param {Compilation} compilation the compilation
* @param {ResolverWithOptions} resolver the resolver
* @param {InputFileSystem} fs the file system
* @param {BuildCallback} callback callback function
* @returns {void}
*/
build(options, compilation, resolver, fs, callback) {
const delegateData = /** @type {ManifestModuleData} */ (this.delegateData);
this.buildMeta = { ...delegateData.buildMeta };
this.buildInfo = {};
this.dependencies.length = 0;
this.delegatedSourceDependency = new DelegatedSourceDependency(
this.sourceRequest
);
this.addDependency(this.delegatedSourceDependency);
this.addDependency(
new StaticExportsDependency(delegateData.exports || true, false)
);
callback();
}
/**
* @param {CodeGenerationContext} context context for code generation
* @returns {CodeGenerationResult} result
*/
codeGeneration({ runtimeTemplate, moduleGraph, chunkGraph }) {
const dep = /** @type {DelegatedSourceDependency} */ (this.dependencies[0]);
const sourceModule = moduleGraph.getModule(dep);
/** @type {string} */
let str;
if (!sourceModule) {
str = runtimeTemplate.throwMissingModuleErrorBlock({
request: this.sourceRequest
});
} else {
str = `module.exports = (${runtimeTemplate.moduleExports({
module: sourceModule,
chunkGraph,
request: dep.request,
/** @type {RuntimeRequirements} */
runtimeRequirements: new Set()
})})`;
switch (this.delegationType) {
case "require":
str += `(${JSON.stringify(this.request)})`;
break;
case "object":
str += `[${JSON.stringify(this.request)}]`;
break;
}
str += ";";
}
/** @type {Sources} */
const sources = new Map();
if (this.useSourceMap || this.useSimpleSourceMap) {
sources.set(JAVASCRIPT_TYPE, new OriginalSource(str, this.identifier()));
} else {
sources.set(JAVASCRIPT_TYPE, new RawSource(str));
}
return {
sources,
runtimeRequirements: RUNTIME_REQUIREMENTS
};
}
/**
* @param {string=} type the source type for which the size should be estimated
* @returns {number} the estimated size of the module (must be non-zero)
*/
size(type) {
return 42;
}
/**
* @param {Hash} hash the hash used to track dependencies
* @param {UpdateHashContext} context context
* @returns {void}
*/
updateHash(hash, context) {
hash.update(this.delegationType);
hash.update(JSON.stringify(this.request));
super.updateHash(hash, context);
}
/**
* @param {ObjectSerializerContext} context context
*/
serialize(context) {
const { write } = context;
// constructor
write(this.sourceRequest);
write(this.delegateData);
write(this.delegationType);
write(this.userRequest);
write(this.originalRequest);
super.serialize(context);
}
/**
* @param {ObjectDeserializerContext} context context\
* @returns {DelegatedModule} DelegatedModule
*/
static deserialize(context) {
const { read } = context;
const obj = new DelegatedModule(
read(), // sourceRequest
read(), // delegateData
read(), // delegationType
read(), // userRequest
read() // originalRequest
);
obj.deserialize(context);
return obj;
}
/**
* Assuming this module is in the cache. Update the (cached) module with
* the fresh module from the factory. Usually updates internal references
* and properties.
* @param {Module} module fresh module
* @returns {void}
*/
updateCacheModule(module) {
super.updateCacheModule(module);
const m = /** @type {DelegatedModule} */ (module);
this.delegationType = m.delegationType;
this.userRequest = m.userRequest;
this.originalRequest = m.originalRequest;
this.delegateData = m.delegateData;
}
/**
* Assuming this module is in the cache. Remove internal references to allow freeing some memory.
*/
cleanupForCache() {
super.cleanupForCache();
this.delegateData =
/** @type {EXPECTED_ANY} */
(undefined);
}
}
makeSerializable(DelegatedModule, "webpack/lib/DelegatedModule");
module.exports = DelegatedModule;

View File

@@ -0,0 +1,2 @@
function e(e){return`directus_access.directus_activity.directus_collections.directus_comments.directus_fields.directus_files.directus_folders.directus_migrations.directus_permissions.directus_policies.directus_presets.directus_relations.directus_revisions.directus_roles.directus_sessions.directus_settings.directus_users.directus_dashboards.directus_panels.directus_notifications.directus_shares.directus_flows.directus_operations.directus_translations.directus_versions.directus_extensions.directus_deployments.directus_deployment_projects.directus_deployment_runs`.split(`.`).includes(e)}exports.isSystemCollection=e;
//# sourceMappingURL=is-system-collection.cjs.map

View File

@@ -0,0 +1,31 @@
import { millisecondsInMinute } from "./constants.js";
/**
* @name millisecondsToMinutes
* @category Conversion Helpers
* @summary Convert milliseconds to minutes.
*
* @description
* Convert a number of milliseconds to a full number of minutes.
*
* @param milliseconds - The number of milliseconds to be converted
*
* @returns The number of milliseconds converted in minutes
*
* @example
* // Convert 60000 milliseconds to minutes:
* const result = millisecondsToMinutes(60000)
* //=> 1
*
* @example
* // It uses floor rounding:
* const result = millisecondsToMinutes(119999)
* //=> 1
*/
export function millisecondsToMinutes(milliseconds) {
const minutes = milliseconds / millisecondsInMinute;
return Math.trunc(minutes);
}
// Fallback for modularized imports:
export default millisecondsToMinutes;

View File

@@ -0,0 +1,150 @@
import type { AttributionReportOpts, LoadState, Metric, ReportOpts } from './base';
export interface INPReportOpts extends ReportOpts {
durationThreshold?: number;
}
export interface INPAttributionReportOpts extends AttributionReportOpts {
durationThreshold?: number;
}
/**
* An INP-specific version of the Metric object.
*/
export interface INPMetric extends Metric {
name: 'INP';
entries: PerformanceEventTiming[];
}
export interface INPLongestScriptSummary {
/**
* The longest Long Animation Frame script entry that intersects the INP
* interaction.
*/
entry: PerformanceScriptTiming;
/**
* The INP subpart where the longest script ran.
*/
subpart: 'input-delay' | 'processing-duration' | 'presentation-delay';
/**
* The amount of time the longest script intersected the INP duration.
*/
intersectingDuration: number;
}
/**
* An object containing potentially-helpful debugging information that
* can be sent along with the INP value for the current page visit in order
* to help identify issues happening to real-users in the field.
*/
export interface INPAttribution {
/**
* By default, a selector identifying the element that the user first
* interacted with as part of the frame where the INP candidate interaction
* occurred. If this value is an empty string, that generally means the
* element was removed from the DOM after the interaction. If the
* `generateTarget` configuration option was passed, then this will instead
* be the return value of that function, falling back to the default if that
* returns null or undefined.
*/
interactionTarget: string;
/**
* The time when the user first interacted during the frame where the INP
* candidate interaction occurred (if more than one interaction occurred
* within the frame, only the first time is reported).
*/
interactionTime: DOMHighResTimeStamp;
/**
* The type of interaction, based on the event type of the `event` entry
* that corresponds to the interaction (i.e. the first `event` entry
* containing an `interactionId` dispatched in a given animation frame).
* For "pointerdown", "pointerup", or "click" events this will be "pointer",
* and for "keydown" or "keyup" events this will be "keyboard".
*/
interactionType: 'pointer' | 'keyboard';
/**
* The best-guess timestamp of the next paint after the interaction.
* In general, this timestamp is the same as the `startTime + duration` of
* the event timing entry. However, since duration values are rounded to the
* nearest 8ms (and can be rounded down), this value is clamped to always be
* reported after the processing times.
*/
nextPaintTime: DOMHighResTimeStamp;
/**
* An array of Event Timing entries that were processed within the same
* animation frame as the INP candidate interaction.
*/
processedEventEntries: PerformanceEventTiming[];
/**
* The time from when the user interacted with the page until when the
* browser was first able to start processing event listeners for that
* interaction. This time captures the delay before event processing can
* begin due to the main thread being busy with other work.
*/
inputDelay: number;
/**
* The time from when the first event listener started running in response to
* the user interaction until when all event listener processing has finished.
*/
processingDuration: number;
/**
* The time from when the browser finished processing all event listeners for
* the user interaction until the next frame is presented on the screen and
* visible to the user. This time includes work on the main thread (such as
* `requestAnimationFrame()` callbacks, `ResizeObserver` and
* `IntersectionObserver` callbacks, and style/layout calculation) as well
* as off-main-thread work (such as compositor, GPU, and raster work).
*/
presentationDelay: number;
/**
* The loading state of the document at the time when the interaction
* corresponding to INP occurred (see `LoadState` for details). If the
* interaction occurred while the document was loading and executing script
* (e.g. usually in the `dom-interactive` phase) it can result in long delays.
*/
loadState: LoadState;
/**
* If the browser supports the Long Animation Frame API, this array will
* include any `long-animation-frame` entries that intersect with the INP
* candidate interaction's `startTime` and the `processingEnd` time of the
* last event processed within that animation frame. If the browser does not
* support the Long Animation Frame API or no `long-animation-frame` entries
* are detected, this array will be empty.
*/
longAnimationFrameEntries: PerformanceLongAnimationFrameTiming[];
/**
* Summary information about the longest script entry intersecting the INP
* duration. Note, only script entries above 5 milliseconds are reported by
* the Long Animation Frame API.
*/
longestScript?: INPLongestScriptSummary;
/**
* The total duration of Long Animation Frame scripts that intersect the INP
* duration excluding any forced style and layout (that is included in
* totalStyleAndLayout). Note, this is limited to scripts > 5 milliseconds.
*/
totalScriptDuration?: number;
/**
* The total style and layout duration from any Long Animation Frames
* intersecting the INP interaction. This includes any end-of-frame style and
* layout duration + any forced style and layout duration.
*/
totalStyleAndLayoutDuration?: number;
/**
* The off main-thread presentation delay from the end of the last Long
* Animation Frame (where available) until the INP end point.
*/
totalPaintDuration?: number;
/**
* The total unattributed time not included in any of the previous totals.
* This includes scripts < 5 milliseconds and other timings not attributed
* by Long Animation Frame (including when a frame is < 50ms and so has no
* Long Animation Frame).
* When no Long Animation Frames are present this will be undefined, rather
* than everything being unattributed to make it clearer when it's expected
* to be small.
*/
totalUnattributedDuration?: number;
}
/**
* An INP-specific version of the Metric object with attribution.
*/
export interface INPMetricWithAttribution extends INPMetric {
attribution: INPAttribution;
}
//# sourceMappingURL=inp.d.ts.map

View File

@@ -0,0 +1,40 @@
import type { SanitizedCollectionConfig } from './../collections/config/types.js';
type CookieOptions = {
domain?: string;
expires?: Date;
httpOnly?: boolean;
maxAge?: number;
name: string;
path?: string;
returnCookieAsObject: boolean;
sameSite?: 'Lax' | 'None' | 'Strict';
secure?: boolean;
value?: string;
};
type CookieObject = {
domain?: string;
expires?: string;
httpOnly?: boolean;
maxAge?: number;
name: string;
path?: string;
sameSite?: 'Lax' | 'None' | 'Strict';
secure?: boolean;
value: string | undefined;
};
export declare const generateCookie: <ReturnCookieAsObject = boolean>(args: CookieOptions) => ReturnCookieAsObject extends true ? CookieObject : string;
type GetCookieExpirationArgs = {
seconds: number;
};
export declare const getCookieExpiration: ({ seconds }: GetCookieExpirationArgs) => Date;
type GeneratePayloadCookieArgs = {
collectionAuthConfig: SanitizedCollectionConfig['auth'];
cookiePrefix: string;
returnCookieAsObject?: boolean;
token: string;
};
export declare const generatePayloadCookie: <T extends GeneratePayloadCookieArgs>({ collectionAuthConfig, cookiePrefix, returnCookieAsObject, token, }: T) => T["returnCookieAsObject"] extends true ? CookieObject : string;
export declare const generateExpiredPayloadCookie: <T extends Omit<GeneratePayloadCookieArgs, "token">>({ collectionAuthConfig, cookiePrefix, returnCookieAsObject, }: T) => T["returnCookieAsObject"] extends true ? CookieObject : string;
export declare function parseCookies(headers: Request['headers']): Map<string, string>;
export {};
//# sourceMappingURL=cookies.d.ts.map

View File

@@ -0,0 +1,264 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports._replaceWith = _replaceWith;
exports.replaceExpressionWithStatements = replaceExpressionWithStatements;
exports.replaceInline = replaceInline;
exports.replaceWith = replaceWith;
exports.replaceWithMultiple = replaceWithMultiple;
exports.replaceWithSourceString = replaceWithSourceString;
var _codeFrame = require("@babel/code-frame");
var _index = require("../index.js");
var _index2 = require("./index.js");
var _cache = require("../cache.js");
var _modification = require("./modification.js");
var _parser = require("@babel/parser");
var _t = require("@babel/types");
var _context = require("./context.js");
const {
FUNCTION_TYPES,
arrowFunctionExpression,
assignmentExpression,
awaitExpression,
blockStatement,
buildUndefinedNode,
callExpression,
cloneNode,
conditionalExpression,
expressionStatement,
getBindingIdentifiers,
identifier,
inheritLeadingComments,
inheritTrailingComments,
inheritsComments,
isBlockStatement,
isEmptyStatement,
isExpression,
isExpressionStatement,
isIfStatement,
isProgram,
isStatement,
isVariableDeclaration,
removeComments,
returnStatement,
sequenceExpression,
validate,
yieldExpression
} = _t;
function replaceWithMultiple(nodes) {
var _getCachedPaths;
_context.resync.call(this);
const verifiedNodes = _modification._verifyNodeList.call(this, nodes);
inheritLeadingComments(verifiedNodes[0], this.node);
inheritTrailingComments(verifiedNodes[verifiedNodes.length - 1], this.node);
(_getCachedPaths = (0, _cache.getCachedPaths)(this)) == null || _getCachedPaths.delete(this.node);
this.node = this.container[this.key] = null;
const paths = this.insertAfter(nodes);
if (this.node) {
this.requeue();
} else {
this.remove();
}
return paths;
}
function replaceWithSourceString(replacement) {
_context.resync.call(this);
let ast;
try {
replacement = `(${replacement})`;
ast = (0, _parser.parse)(replacement);
} catch (err) {
const loc = err.loc;
if (loc) {
err.message += " - make sure this is an expression.\n" + (0, _codeFrame.codeFrameColumns)(replacement, {
start: {
line: loc.line,
column: loc.column + 1
}
});
err.code = "BABEL_REPLACE_SOURCE_ERROR";
}
throw err;
}
const expressionAST = ast.program.body[0].expression;
_index.default.removeProperties(expressionAST);
return this.replaceWith(expressionAST);
}
function replaceWith(replacementPath) {
_context.resync.call(this);
if (this.removed) {
throw new Error("You can't replace this node, we've already removed it");
}
let replacement = replacementPath instanceof _index2.default ? replacementPath.node : replacementPath;
if (!replacement) {
throw new Error("You passed `path.replaceWith()` a falsy node, use `path.remove()` instead");
}
if (this.node === replacement) {
return [this];
}
if (this.isProgram() && !isProgram(replacement)) {
throw new Error("You can only replace a Program root node with another Program node");
}
if (Array.isArray(replacement)) {
throw new Error("Don't use `path.replaceWith()` with an array of nodes, use `path.replaceWithMultiple()`");
}
if (typeof replacement === "string") {
throw new Error("Don't use `path.replaceWith()` with a source string, use `path.replaceWithSourceString()`");
}
let nodePath = "";
if (this.isNodeType("Statement") && isExpression(replacement)) {
if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement) && !this.parentPath.isExportDefaultDeclaration()) {
replacement = expressionStatement(replacement);
nodePath = "expression";
}
}
if (this.isNodeType("Expression") && isStatement(replacement)) {
if (!this.canHaveVariableDeclarationOrExpression() && !this.canSwapBetweenExpressionAndStatement(replacement)) {
return this.replaceExpressionWithStatements([replacement]);
}
}
const oldNode = this.node;
if (oldNode) {
inheritsComments(replacement, oldNode);
removeComments(oldNode);
}
_replaceWith.call(this, replacement);
this.type = replacement.type;
_context.setScope.call(this);
this.requeue();
return [nodePath ? this.get(nodePath) : this];
}
function _replaceWith(node) {
var _getCachedPaths2;
if (!this.container) {
throw new ReferenceError("Container is falsy");
}
if (this.inList) {
validate(this.parent, this.key, [node]);
} else {
validate(this.parent, this.key, node);
}
this.debug(`Replace with ${node == null ? void 0 : node.type}`);
(_getCachedPaths2 = (0, _cache.getCachedPaths)(this)) == null || _getCachedPaths2.set(node, this).delete(this.node);
this.node = node;
this.container[this.key] = node;
}
function replaceExpressionWithStatements(nodes) {
_context.resync.call(this);
const declars = [];
const nodesAsSingleExpression = gatherSequenceExpressions(nodes, declars);
if (nodesAsSingleExpression) {
for (const id of declars) this.scope.push({
id
});
return this.replaceWith(nodesAsSingleExpression)[0].get("expressions");
}
const functionParent = this.getFunctionParent();
const isParentAsync = functionParent == null ? void 0 : functionParent.node.async;
const isParentGenerator = functionParent == null ? void 0 : functionParent.node.generator;
const container = arrowFunctionExpression([], blockStatement(nodes));
this.replaceWith(callExpression(container, []));
const callee = this.get("callee");
callee.get("body").scope.hoistVariables(id => this.scope.push({
id
}));
const completionRecords = callee.getCompletionRecords();
for (const path of completionRecords) {
if (!path.isExpressionStatement()) continue;
const loop = path.findParent(path => path.isLoop());
if (loop) {
let uid = loop.getData("expressionReplacementReturnUid");
if (!uid) {
uid = callee.scope.generateDeclaredUidIdentifier("ret");
callee.get("body").pushContainer("body", returnStatement(cloneNode(uid)));
loop.setData("expressionReplacementReturnUid", uid);
} else {
uid = identifier(uid.name);
}
path.get("expression").replaceWith(assignmentExpression("=", cloneNode(uid), path.node.expression));
} else {
path.replaceWith(returnStatement(path.node.expression));
}
}
callee.arrowFunctionToExpression();
const newCallee = callee;
const needToAwaitFunction = isParentAsync && _index.default.hasType(newCallee.node.body, "AwaitExpression", FUNCTION_TYPES);
const needToYieldFunction = isParentGenerator && _index.default.hasType(newCallee.node.body, "YieldExpression", FUNCTION_TYPES);
if (needToAwaitFunction) {
newCallee.set("async", true);
if (!needToYieldFunction) {
this.replaceWith(awaitExpression(this.node));
}
}
if (needToYieldFunction) {
newCallee.set("generator", true);
this.replaceWith(yieldExpression(this.node, true));
}
return newCallee.get("body.body");
}
function gatherSequenceExpressions(nodes, declars) {
const exprs = [];
let ensureLastUndefined = true;
for (const node of nodes) {
if (!isEmptyStatement(node)) {
ensureLastUndefined = false;
}
if (isExpression(node)) {
exprs.push(node);
} else if (isExpressionStatement(node)) {
exprs.push(node.expression);
} else if (isVariableDeclaration(node)) {
if (node.kind !== "var") return;
for (const declar of node.declarations) {
const bindings = getBindingIdentifiers(declar);
for (const key of Object.keys(bindings)) {
declars.push(cloneNode(bindings[key]));
}
if (declar.init) {
exprs.push(assignmentExpression("=", declar.id, declar.init));
}
}
ensureLastUndefined = true;
} else if (isIfStatement(node)) {
const consequent = node.consequent ? gatherSequenceExpressions([node.consequent], declars) : buildUndefinedNode();
const alternate = node.alternate ? gatherSequenceExpressions([node.alternate], declars) : buildUndefinedNode();
if (!consequent || !alternate) return;
exprs.push(conditionalExpression(node.test, consequent, alternate));
} else if (isBlockStatement(node)) {
const body = gatherSequenceExpressions(node.body, declars);
if (!body) return;
exprs.push(body);
} else if (isEmptyStatement(node)) {
if (nodes.indexOf(node) === 0) {
ensureLastUndefined = true;
}
} else {
return;
}
}
if (ensureLastUndefined) exprs.push(buildUndefinedNode());
if (exprs.length === 1) {
return exprs[0];
} else {
return sequenceExpression(exprs);
}
}
function replaceInline(nodes) {
_context.resync.call(this);
if (Array.isArray(nodes)) {
if (Array.isArray(this.container)) {
nodes = _modification._verifyNodeList.call(this, nodes);
const paths = _modification._containerInsertAfter.call(this, nodes);
this.remove();
return paths;
} else {
return this.replaceWithMultiple(nodes);
}
} else {
return this.replaceWith(nodes);
}
}
//# sourceMappingURL=replacement.js.map

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/resolvers/collections/docAccess.ts"],"sourcesContent":["import type {\n Collection,\n PayloadRequest,\n SanitizedCollectionPermission,\n SanitizedGlobalPermission,\n} from 'payload'\n\nimport { docAccessOperation, isolateObjectProperty } from 'payload'\n\nimport type { Context } from '../types.js'\n\nexport type Resolver = (\n _: unknown,\n args: {\n id: number | string\n },\n context: {\n req: PayloadRequest\n },\n) => Promise<SanitizedCollectionPermission | SanitizedGlobalPermission>\n\nexport function docAccessResolver(collection: Collection): Resolver {\n async function resolver(_, args, context: Context) {\n return docAccessOperation({\n id: args.id,\n collection,\n req: isolateObjectProperty(context.req, 'transactionID'),\n })\n }\n\n return resolver\n}\n"],"names":["docAccessOperation","isolateObjectProperty","docAccessResolver","collection","resolver","_","args","context","id","req"],"mappings":"AAOA,SAASA,kBAAkB,EAAEC,qBAAqB,QAAQ,UAAS;AAcnE,OAAO,SAASC,kBAAkBC,UAAsB;IACtD,eAAeC,SAASC,CAAC,EAAEC,IAAI,EAAEC,OAAgB;QAC/C,OAAOP,mBAAmB;YACxBQ,IAAIF,KAAKE,EAAE;YACXL;YACAM,KAAKR,sBAAsBM,QAAQE,GAAG,EAAE;QAC1C;IACF;IAEA,OAAOL;AACT"}

View File

@@ -0,0 +1,43 @@
/**
* 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.
*
*/
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import * as React from '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.
*
*/
/**
*
* Use this plugin to access the editor instance outside of the
* LexicalComposer. This can help with things like buttons or other
* UI components that need to update or read EditorState but need to
* be positioned outside the LexicalComposer in the React tree.
*/
function EditorRefPlugin({
editorRef
}) {
const [editor] = useLexicalComposerContext();
React.useEffect(() => {
if (typeof editorRef === 'function') {
editorRef(editor);
} else if (typeof editorRef === 'object') {
editorRef.current = editor;
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [editor]);
return null;
}
export { EditorRefPlugin };

View File

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

View File

@@ -0,0 +1,2 @@
export { addRequestBreadcrumb, addTracePropagationHeadersToOutgoingRequest, getRequestOptions, } from '../../utils/outgoingHttpRequest';
//# sourceMappingURL=outgoing-requests.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../src/fields/hooks/beforeValidate/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAA;AACrF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAA;AAC7E,OAAO,KAAK,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAEzE,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAGvD,KAAK,IAAI,CAAC,CAAC,SAAS,UAAU,IAAI;IAChC,UAAU,EAAE,IAAI,GAAG,yBAAyB,CAAA;IAC5C,OAAO,EAAE,cAAc,CAAA;IACvB,IAAI,EAAE,CAAC,CAAA;IACP,GAAG,CAAC,EAAE,CAAC,CAAA;IACP,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,MAAM,EAAE,IAAI,GAAG,qBAAqB,CAAA;IACpC,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;IACpB,SAAS,EAAE,QAAQ,GAAG,QAAQ,CAAA;IAC9B,cAAc,EAAE,OAAO,CAAA;IACvB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,cAAc,GAAU,CAAC,SAAS,UAAU,iGAUtD,IAAI,CAAC,CAAC,CAAC,KAAG,OAAO,CAAC,CAAC,CAqBrB,CAAA"}

View File

@@ -0,0 +1,17 @@
/*
* 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.
*/
export {};
//# sourceMappingURL=tracer_options.js.map

View File

@@ -0,0 +1,15 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const feedback = require('@sentry-internal/feedback');
const lazyLoadIntegration = require('./utils/lazyLoadIntegration.js');
/**
* An integration to add user feedback to your application,
* while loading most of the code lazily only when it's needed.
*/
const feedbackAsyncIntegration = feedback.buildFeedbackIntegration({
lazyLoadIntegration: lazyLoadIntegration.lazyLoadIntegration,
});
exports.feedbackAsyncIntegration = feedbackAsyncIntegration;
//# sourceMappingURL=feedbackAsync.js.map

View File

@@ -0,0 +1,38 @@
import type { ContextOptions, DateArg } from "./types.js";
/**
* The {@link max} function options.
*/
export interface MaxOptions<DateType extends Date = Date>
extends ContextOptions<DateType> {}
/**
* @name max
* @category Common Helpers
* @summary Return the latest of the given dates.
*
* @description
* Return the latest of the given dates.
*
* @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 dates - The dates to compare
*
* @returns The latest of the dates
*
* @example
* // Which of these dates is the latest?
* const result = max([
* new Date(1989, 6, 10),
* new Date(1987, 1, 11),
* new Date(1995, 6, 2),
* new Date(1990, 0, 1)
* ])
* //=> Sun Jul 02 1995 00:00:00
*/
export declare function max<
DateType extends Date,
ResultDate extends Date = DateType,
>(
dates: DateArg<DateType>[],
options?: MaxOptions<ResultDate> | undefined,
): ResultDate;

View File

@@ -0,0 +1,80 @@
import type { AnySchema, AnySchemaObject, AnyValidateFunction, EvaluatedProperties, EvaluatedItems } from "../types";
import type Ajv from "../core";
import type { InstanceOptions } from "../core";
import { CodeGen, Name, Code, ValueScopeName } from "./codegen";
import { LocalRefs } from "./resolve";
import { JSONType } from "./rules";
export type SchemaRefs = {
[Ref in string]?: SchemaEnv | AnySchema;
};
export interface SchemaCxt {
readonly gen: CodeGen;
readonly allErrors?: boolean;
readonly data: Name;
readonly parentData: Name;
readonly parentDataProperty: Code | number;
readonly dataNames: Name[];
readonly dataPathArr: (Code | number)[];
readonly dataLevel: number;
dataTypes: JSONType[];
definedProperties: Set<string>;
readonly topSchemaRef: Code;
readonly validateName: Name;
evaluated?: Name;
readonly ValidationError?: Name;
readonly schema: AnySchema;
readonly schemaEnv: SchemaEnv;
readonly rootId: string;
baseId: string;
readonly schemaPath: Code;
readonly errSchemaPath: string;
readonly errorPath: Code;
readonly propertyName?: Name;
readonly compositeRule?: boolean;
props?: EvaluatedProperties | Name;
items?: EvaluatedItems | Name;
jtdDiscriminator?: string;
jtdMetadata?: boolean;
readonly createErrors?: boolean;
readonly opts: InstanceOptions;
readonly self: Ajv;
}
export interface SchemaObjCxt extends SchemaCxt {
readonly schema: AnySchemaObject;
}
interface SchemaEnvArgs {
readonly schema: AnySchema;
readonly schemaId?: "$id" | "id";
readonly root?: SchemaEnv;
readonly baseId?: string;
readonly schemaPath?: string;
readonly localRefs?: LocalRefs;
readonly meta?: boolean;
}
export declare class SchemaEnv implements SchemaEnvArgs {
readonly schema: AnySchema;
readonly schemaId?: "$id" | "id";
readonly root: SchemaEnv;
baseId: string;
schemaPath?: string;
localRefs?: LocalRefs;
readonly meta?: boolean;
readonly $async?: boolean;
readonly refs: SchemaRefs;
readonly dynamicAnchors: {
[Ref in string]?: true;
};
validate?: AnyValidateFunction;
validateName?: ValueScopeName;
serialize?: (data: unknown) => string;
serializeName?: ValueScopeName;
parse?: (data: string) => unknown;
parseName?: ValueScopeName;
constructor(env: SchemaEnvArgs);
}
export declare function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv;
export declare function resolveRef(this: Ajv, root: SchemaEnv, baseId: string, ref: string): AnySchema | SchemaEnv | undefined;
export declare function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void;
export declare function resolveSchema(this: Ajv, root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
ref: string): SchemaEnv | undefined;
export {};

View File

@@ -0,0 +1 @@
{"version":3,"file":"insertArrays.d.ts","sourceRoot":"","sources":["../../src/upsertRow/insertArrays.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAA;AACnE,OAAO,KAAK,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAErE,KAAK,IAAI,GAAG;IACV,OAAO,EAAE,cAAc,CAAA;IACvB,MAAM,EAAE;QACN,CAAC,SAAS,EAAE,MAAM,GAAG,gBAAgB,EAAE,CAAA;KACxC,EAAE,CAAA;IACH,EAAE,EAAE,cAAc,CAAC,SAAS,CAAC,GAAG,kBAAkB,CAAA;IAClD,UAAU,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAA;IACrC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,CAAA;CAC1C,CAAA;AAYD,eAAO,MAAM,YAAY,kDAMtB,IAAI,KAAG,OAAO,CAAC,IAAI,CAgGrB,CAAA"}

View File

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

View File

@@ -0,0 +1,16 @@
/**
* @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 Music3 = createLucideIcon("Music3", [
["circle", { cx: "12", cy: "18", r: "4", key: "m3r9ws" }],
["path", { d: "M16 18V2", key: "40x2m5" }]
]);
export { Music3 as default };
//# sourceMappingURL=music-3.js.map

View File

@@ -0,0 +1,29 @@
/**
* Selects distinct records from a table only if there are joins that need to be used, otherwise return null
*/ export const selectDistinct = ({ adapter, db, forceRun, hasAggregates, joins, query: queryModifier = ({ query })=>query, selectFields, tableName, where })=>{
if (forceRun || Object.keys(joins).length > 0) {
let query;
const table = adapter.tables[tableName];
// With hasAggregate we use groupBy so we don't need to use selectDistinct in that case
// @ts-expect-error - Drizzle types are not accurate here
let selectFunc = hasAggregates ? db.select : db.selectDistinct;
// bind this otherwise we get TypeError: Cannot read properties of undefined (reading 'session')
selectFunc = selectFunc.bind(db);
query = selectFunc(selectFields).from(table).$dynamic();
if (where) {
query = query.where(where);
}
joins.forEach(({ type, condition, table })=>{
query = query[type ?? 'leftJoin'](table, condition);
});
if (hasAggregates && '_selected' in selectFields) {
// @ts-expect-error - Drizzle types are not accurate here
query = query.groupBy(selectFields['_selected']);
}
return queryModifier({
query
});
}
};
//# sourceMappingURL=selectDistinct.js.map

View File

@@ -0,0 +1,15 @@
import type {CodeKeywordDefinition} from "../../types"
import type {KeywordCxt} from "../../compile/validate"
import {validateProperties, error} from "./properties"
const def: CodeKeywordDefinition = {
keyword: "optionalProperties",
schemaType: "object",
error,
code(cxt: KeywordCxt) {
if (cxt.parentSchema.properties) return
validateProperties(cxt)
},
}
export default def

View File

@@ -0,0 +1 @@
{"version":3,"file":"FileRetrievalError.d.ts","sourceRoot":"","sources":["../../src/errors/FileRetrievalError.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAA;AAIzD,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAExC,qBAAa,kBAAmB,SAAQ,QAAQ;gBAClC,CAAC,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,MAAM;CAQ5C"}

View File

@@ -0,0 +1,66 @@
import { createRequire } from 'module';
import path from 'path';
import { transform } from '@swc/core';
import { getDefaultProjectRoot, normalizePathToPosix } from '../utils.js';
import LRUCache from './LRUCache.js';
const require$1 = createRequire(import.meta.url);
class MessageExtractor {
compileCache = new LRUCache(750);
constructor(opts) {
this.isDevelopment = opts.isDevelopment ?? false;
this.projectRoot = opts.projectRoot ?? getDefaultProjectRoot();
this.sourceMap = opts.sourceMap ?? false;
}
async extract(absoluteFilePath, source) {
const cacheKey = [source, absoluteFilePath].join('!');
const cached = this.compileCache.get(cacheKey);
if (cached) return cached;
// Shortcut parsing if hook is not used. The Turbopack integration already
// pre-filters this, but for webpack this feature doesn't exist, so we need
// to do it here.
if (!source.includes('useExtracted') && !source.includes('getExtracted')) {
return {
messages: [],
code: source
};
}
const filePath = normalizePathToPosix(path.relative(this.projectRoot, absoluteFilePath));
const result = await transform(source, {
jsc: {
target: 'esnext',
parser: {
syntax: 'typescript',
tsx: true,
decorators: true
},
experimental: {
cacheRoot: 'node_modules/.cache/swc',
disableBuiltinTransformsForInternalTesting: true,
disableAllLints: true,
plugins: [[require$1.resolve('next-intl-swc-plugin-extractor'), {
isDevelopment: this.isDevelopment,
filePath
}]]
}
},
sourceMaps: this.sourceMap,
sourceFileName: filePath,
filename: filePath
});
// TODO: Improve the typing of @swc/core
const output = result.output;
const messages = JSON.parse(JSON.parse(output).results);
const extractionResult = {
code: result.code,
map: result.map,
messages
};
this.compileCache.set(cacheKey, extractionResult);
return extractionResult;
}
}
export { MessageExtractor as default };

View File

@@ -0,0 +1,3 @@
import type { Decimal } from "decimal.js";
import { type NumberFormatInternal } from "../types/number.js";
export declare function FormatNumeric(internalSlots: NumberFormatInternal, x: Decimal): string;

View File

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

View File

@@ -0,0 +1,38 @@
/**
* @name compareDesc
* @category Common Helpers
* @summary Compare the two dates reverse chronologically and return -1, 0 or 1.
*
* @description
* Compare the two dates and return -1 if the first date is after the second,
* 1 if the first date is before the second or 0 if dates are equal.
*
* @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).
*
* @param dateLeft - The first date to compare
* @param dateRight - The second date to compare
*
* @returns The result of the comparison
*
* @example
* // Compare 11 February 1987 and 10 July 1989 reverse chronologically:
* const result = compareDesc(new Date(1987, 1, 11), new Date(1989, 6, 10))
* //=> 1
*
* @example
* // Sort the array of dates in reverse chronological order:
* const result = [
* new Date(1995, 6, 2),
* new Date(1987, 1, 11),
* new Date(1989, 6, 10)
* ].sort(compareDesc)
* //=> [
* // Sun Jul 02 1995 00:00:00,
* // Mon Jul 10 1989 00:00:00,
* // Wed Feb 11 1987 00:00:00
* // ]
*/
export declare function compareDesc<DateType extends Date>(
dateLeft: DateType | number | string,
dateRight: DateType | number | string,
): number;

View File

@@ -0,0 +1,43 @@
var baseToString = require('./_baseToString'),
castSlice = require('./_castSlice'),
charsStartIndex = require('./_charsStartIndex'),
stringToArray = require('./_stringToArray'),
toString = require('./toString');
/** Used to match leading whitespace. */
var reTrimStart = /^\s+/;
/**
* Removes leading whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimStart(' abc ');
* // => 'abc '
*
* _.trimStart('-_-abc-_-', '_-');
* // => 'abc-_-'
*/
function trimStart(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrimStart, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
start = charsStartIndex(strSymbols, stringToArray(chars));
return castSlice(strSymbols, start).join('');
}
module.exports = trimStart;

View File

@@ -0,0 +1 @@
{"version":3,"file":"getColumns.js","names":["flattenTopLevelFields","fieldAffectsData","filterFieldsWithPermissions","getInitialColumns","getColumns","clientConfig","collectionConfig","collectionSlug","columns","i18n","permissions","isPolymorphic","Array","isArray","fields","collection","clientCollectionConfig","collections","find","each","slug","field","fieldPermissions","some","name","push","length","filter","column","keepPresentationalFields","moveSubFieldsToTop","accessor","undefined","admin","useAsTitle","defaultColumns"],"sources":["../../src/utilities/getColumns.ts"],"sourcesContent":["import type { I18nClient } from '@payloadcms/translations'\nimport type {\n ClientCollectionConfig,\n ClientConfig,\n ColumnPreference,\n SanitizedPermissions,\n} from 'payload'\n\nimport { flattenTopLevelFields } from 'payload'\nimport { fieldAffectsData } from 'payload/shared'\n\nimport { filterFieldsWithPermissions } from '../providers/TableColumns/buildColumnState/filterFieldsWithPermissions.js'\nimport { getInitialColumns } from '../providers/TableColumns/getInitialColumns.js'\n\nexport const getColumns = ({\n clientConfig,\n collectionConfig,\n collectionSlug,\n columns,\n i18n,\n permissions,\n}: {\n clientConfig: ClientConfig\n collectionConfig?: ClientCollectionConfig\n collectionSlug: string | string[]\n columns: ColumnPreference[]\n i18n: I18nClient\n permissions?: SanitizedPermissions\n}) => {\n const isPolymorphic = Array.isArray(collectionSlug)\n\n const fields = !isPolymorphic ? (collectionConfig?.fields ?? []) : []\n\n if (isPolymorphic) {\n for (const collection of collectionSlug) {\n const clientCollectionConfig = clientConfig.collections.find(\n (each) => each.slug === collection,\n )\n\n for (const field of filterFieldsWithPermissions({\n fieldPermissions: permissions?.collections?.[collection]?.fields || true,\n fields: clientCollectionConfig.fields,\n })) {\n if (fieldAffectsData(field)) {\n if (fields.some((each) => fieldAffectsData(each) && each.name === field.name)) {\n continue\n }\n }\n\n fields.push(field)\n }\n }\n }\n\n return columns?.length\n ? columns?.filter((column) =>\n flattenTopLevelFields(fields, {\n i18n,\n keepPresentationalFields: true,\n moveSubFieldsToTop: true,\n })?.some((field) => {\n const accessor =\n 'accessor' in field ? field.accessor : 'name' in field ? field.name : undefined\n return accessor === column.accessor\n }),\n )\n : getInitialColumns(\n isPolymorphic\n ? fields\n : filterFieldsWithPermissions({\n fieldPermissions:\n typeof collectionSlug === 'string' &&\n permissions?.collections?.[collectionSlug]?.fields\n ? permissions.collections[collectionSlug].fields\n : true,\n fields,\n }),\n collectionConfig?.admin?.useAsTitle,\n isPolymorphic ? [] : collectionConfig?.admin?.defaultColumns,\n )\n}\n"],"mappings":"AAQA,SAASA,qBAAqB,QAAQ;AACtC,SAASC,gBAAgB,QAAQ;AAEjC,SAASC,2BAA2B,QAAQ;AAC5C,SAASC,iBAAiB,QAAQ;AAElC,OAAO,MAAMC,UAAA,GAAaA,CAAC;EACzBC,YAAY;EACZC,gBAAgB;EAChBC,cAAc;EACdC,OAAO;EACPC,IAAI;EACJC;AAAW,CAQZ;EACC,MAAMC,aAAA,GAAgBC,KAAA,CAAMC,OAAO,CAACN,cAAA;EAEpC,MAAMO,MAAA,GAAS,CAACH,aAAA,GAAiBL,gBAAA,EAAkBQ,MAAA,IAAU,EAAE,GAAI,EAAE;EAErE,IAAIH,aAAA,EAAe;IACjB,KAAK,MAAMI,UAAA,IAAcR,cAAA,EAAgB;MACvC,MAAMS,sBAAA,GAAyBX,YAAA,CAAaY,WAAW,CAACC,IAAI,CACzDC,IAAA,IAASA,IAAA,CAAKC,IAAI,KAAKL,UAAA;MAG1B,KAAK,MAAMM,KAAA,IAASnB,2BAAA,CAA4B;QAC9CoB,gBAAA,EAAkBZ,WAAA,EAAaO,WAAA,GAAcF,UAAA,CAAW,EAAED,MAAA,IAAU;QACpEA,MAAA,EAAQE,sBAAA,CAAuBF;MACjC,IAAI;QACF,IAAIb,gBAAA,CAAiBoB,KAAA,GAAQ;UAC3B,IAAIP,MAAA,CAAOS,IAAI,CAAEJ,IAAA,IAASlB,gBAAA,CAAiBkB,IAAA,KAASA,IAAA,CAAKK,IAAI,KAAKH,KAAA,CAAMG,IAAI,GAAG;YAC7E;UACF;QACF;QAEAV,MAAA,CAAOW,IAAI,CAACJ,KAAA;MACd;IACF;EACF;EAEA,OAAOb,OAAA,EAASkB,MAAA,GACZlB,OAAA,EAASmB,MAAA,CAAQC,MAAA,IACf5B,qBAAA,CAAsBc,MAAA,EAAQ;IAC5BL,IAAA;IACAoB,wBAAA,EAA0B;IAC1BC,kBAAA,EAAoB;EACtB,IAAIP,IAAA,CAAMF,KAAA;IACR,MAAMU,QAAA,GACJ,cAAcV,KAAA,GAAQA,KAAA,CAAMU,QAAQ,GAAG,UAAUV,KAAA,GAAQA,KAAA,CAAMG,IAAI,GAAGQ,SAAA;IACxE,OAAOD,QAAA,KAAaH,MAAA,CAAOG,QAAQ;EACrC,MAEF5B,iBAAA,CACEQ,aAAA,GACIG,MAAA,GACAZ,2BAAA,CAA4B;IAC1BoB,gBAAA,EACE,OAAOf,cAAA,KAAmB,YAC1BG,WAAA,EAAaO,WAAA,GAAcV,cAAA,CAAe,EAAEO,MAAA,GACxCJ,WAAA,CAAYO,WAAW,CAACV,cAAA,CAAe,CAACO,MAAM,GAC9C;IACNA;EACF,IACJR,gBAAA,EAAkB2B,KAAA,EAAOC,UAAA,EACzBvB,aAAA,GAAgB,EAAE,GAAGL,gBAAA,EAAkB2B,KAAA,EAAOE,cAAA;AAEtD","ignoreList":[]}

View File

@@ -0,0 +1,168 @@
import type {AnySchema, SchemaMap} from "../types"
import type {SchemaCxt} from "../compile"
import type {KeywordCxt} from "../compile/validate"
import {CodeGen, _, and, or, not, nil, strConcat, getProperty, Code, Name} from "../compile/codegen"
import {alwaysValidSchema, Type} from "../compile/util"
import N from "../compile/names"
import {useFunc} from "../compile/util"
export function checkReportMissingProp(cxt: KeywordCxt, prop: string): void {
const {gen, data, it} = cxt
gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
cxt.setParams({missingProperty: _`${prop}`}, true)
cxt.error()
})
}
export function checkMissingProp(
{gen, data, it: {opts}}: KeywordCxt,
properties: string[],
missing: Name
): Code {
return or(
...properties.map((prop) =>
and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`)
)
)
}
export function reportMissingProp(cxt: KeywordCxt, missing: Name): void {
cxt.setParams({missingProperty: missing}, true)
cxt.error()
}
export function hasPropFunc(gen: CodeGen): Name {
return gen.scopeValue("func", {
// eslint-disable-next-line @typescript-eslint/unbound-method
ref: Object.prototype.hasOwnProperty,
code: _`Object.prototype.hasOwnProperty`,
})
}
export function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code {
return _`${hasPropFunc(gen)}.call(${data}, ${property})`
}
export function propertyInData(
gen: CodeGen,
data: Name,
property: Name | string,
ownProperties?: boolean
): Code {
const cond = _`${data}${getProperty(property)} !== undefined`
return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond
}
export function noPropertyInData(
gen: CodeGen,
data: Name,
property: Name | string,
ownProperties?: boolean
): Code {
const cond = _`${data}${getProperty(property)} === undefined`
return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond
}
export function allSchemaProperties(schemaMap?: SchemaMap): string[] {
return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []
}
export function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] {
return allSchemaProperties(schemaMap).filter(
(p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema)
)
}
export function callValidateCode(
{schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt,
func: Code,
context: Code,
passSchema?: boolean
): Code {
const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data
const valCxt: [Name, Code | number][] = [
[N.instancePath, strConcat(N.instancePath, errorPath)],
[N.parentData, it.parentData],
[N.parentDataProperty, it.parentDataProperty],
[N.rootData, N.rootData],
]
if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors])
const args = _`${dataAndSchema}, ${gen.object(...valCxt)}`
return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})`
}
const newRegExp = _`new RegExp`
export function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name {
const u = opts.unicodeRegExp ? "u" : ""
const {regExp} = opts.code
const rx = regExp(pattern, u)
return gen.scopeValue("pattern", {
key: rx.toString(),
ref: rx,
code: _`${regExp.code === "new RegExp" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`,
})
}
export function validateArray(cxt: KeywordCxt): Name {
const {gen, data, keyword, it} = cxt
const valid = gen.name("valid")
if (it.allErrors) {
const validArr = gen.let("valid", true)
validateItems(() => gen.assign(validArr, false))
return validArr
}
gen.var(valid, true)
validateItems(() => gen.break())
return valid
function validateItems(notValid: () => void): void {
const len = gen.const("len", _`${data}.length`)
gen.forRange("i", 0, len, (i) => {
cxt.subschema(
{
keyword,
dataProp: i,
dataPropType: Type.Num,
},
valid
)
gen.if(not(valid), notValid)
})
}
}
export function validateUnion(cxt: KeywordCxt): void {
const {gen, schema, keyword, it} = cxt
/* istanbul ignore if */
if (!Array.isArray(schema)) throw new Error("ajv implementation error")
const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch))
if (alwaysValid && !it.opts.unevaluated) return
const valid = gen.let("valid", false)
const schValid = gen.name("_valid")
gen.block(() =>
schema.forEach((_sch: AnySchema, i: number) => {
const schCxt = cxt.subschema(
{
keyword,
schemaProp: i,
compositeRule: true,
},
schValid
)
gen.assign(valid, _`${valid} || ${schValid}`)
const merged = cxt.mergeValidEvaluated(schCxt, schValid)
// can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)
// or if all properties and items were evaluated (it.props === true && it.items === true)
if (!merged) gen.if(not(valid))
})
)
cxt.result(
valid,
() => cxt.reset(),
() => cxt.error(true)
)
}

View File

@@ -0,0 +1,106 @@
{
"name": "signal-exit",
"version": "4.1.0",
"description": "when you want to fire an event no matter how a process exits.",
"main": "./dist/cjs/index.js",
"module": "./dist/mjs/index.js",
"browser": "./dist/mjs/browser.js",
"types": "./dist/mjs/index.d.ts",
"exports": {
".": {
"import": {
"types": "./dist/mjs/index.d.ts",
"default": "./dist/mjs/index.js"
},
"require": {
"types": "./dist/cjs/index.d.ts",
"default": "./dist/cjs/index.js"
}
},
"./signals": {
"import": {
"types": "./dist/mjs/signals.d.ts",
"default": "./dist/mjs/signals.js"
},
"require": {
"types": "./dist/cjs/signals.d.ts",
"default": "./dist/cjs/signals.js"
}
},
"./browser": {
"import": {
"types": "./dist/mjs/browser.d.ts",
"default": "./dist/mjs/browser.js"
},
"require": {
"types": "./dist/cjs/browser.d.ts",
"default": "./dist/cjs/browser.js"
}
}
},
"files": [
"dist"
],
"engines": {
"node": ">=14"
},
"repository": {
"type": "git",
"url": "https://github.com/tapjs/signal-exit.git"
},
"keywords": [
"signal",
"exit"
],
"author": "Ben Coe <ben@npmjs.com>",
"license": "ISC",
"devDependencies": {
"@types/cross-spawn": "^6.0.2",
"@types/node": "^18.15.11",
"@types/signal-exit": "^3.0.1",
"@types/tap": "^15.0.8",
"c8": "^7.13.0",
"prettier": "^2.8.6",
"tap": "^16.3.4",
"ts-node": "^10.9.1",
"typedoc": "^0.23.28",
"typescript": "^5.0.2"
},
"scripts": {
"preversion": "npm test",
"postversion": "npm publish",
"prepublishOnly": "git push origin --follow-tags",
"preprepare": "rm -rf dist",
"prepare": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json && bash ./scripts/fixup.sh",
"pretest": "npm run prepare",
"presnap": "npm run prepare",
"test": "c8 tap",
"snap": "c8 tap",
"format": "prettier --write . --loglevel warn",
"typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts"
},
"prettier": {
"semi": false,
"printWidth": 75,
"tabWidth": 2,
"useTabs": false,
"singleQuote": true,
"jsxSingleQuote": false,
"bracketSameLine": true,
"arrowParens": "avoid",
"endOfLine": "lf"
},
"tap": {
"coverage": false,
"jobs": 1,
"node-arg": [
"--no-warnings",
"--loader",
"ts-node/esm"
],
"ts": false
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
}
}

View File

@@ -0,0 +1,9 @@
/**
* @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.
*/
export { default } from './square-library.js';
//# sourceMappingURL=library-square.js.map

View File

@@ -0,0 +1,829 @@
import { expect, expectTypeOf, test } from "vitest";
import * as z from "zod/v4";
import type { util } from "zod/v4/core";
test("z.boolean", () => {
const a = z.boolean();
expect(z.parse(a, true)).toEqual(true);
expect(z.parse(a, false)).toEqual(false);
expect(() => z.parse(a, 123)).toThrow();
expect(() => z.parse(a, "true")).toThrow();
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<boolean>();
});
test("z.bigint", () => {
const a = z.bigint();
expect(z.parse(a, BigInt(123))).toEqual(BigInt(123));
expect(() => z.parse(a, 123)).toThrow();
expect(() => z.parse(a, "123")).toThrow();
});
test("z.symbol", () => {
const a = z.symbol();
const sym = Symbol();
expect(z.parse(a, sym)).toEqual(sym);
expect(() => z.parse(a, "symbol")).toThrow();
});
test("z.date", () => {
const a = z.date();
const date = new Date();
expect(z.parse(a, date)).toEqual(date);
expect(() => z.parse(a, "date")).toThrow();
});
test("z.coerce.string", () => {
const a = z.coerce.string();
expect(z.parse(a, 123)).toEqual("123");
expect(z.parse(a, true)).toEqual("true");
expect(z.parse(a, null)).toEqual("null");
expect(z.parse(a, undefined)).toEqual("undefined");
});
test("z.coerce.number", () => {
const a = z.coerce.number();
expect(z.parse(a, "123")).toEqual(123);
expect(z.parse(a, "123.45")).toEqual(123.45);
expect(z.parse(a, true)).toEqual(1);
expect(z.parse(a, false)).toEqual(0);
expect(() => z.parse(a, "abc")).toThrow();
});
test("z.coerce.boolean", () => {
const a = z.coerce.boolean();
// test booleans
expect(z.parse(a, true)).toEqual(true);
expect(z.parse(a, false)).toEqual(false);
expect(z.parse(a, "true")).toEqual(true);
expect(z.parse(a, "false")).toEqual(true);
expect(z.parse(a, 1)).toEqual(true);
expect(z.parse(a, 0)).toEqual(false);
expect(z.parse(a, {})).toEqual(true);
expect(z.parse(a, [])).toEqual(true);
expect(z.parse(a, undefined)).toEqual(false);
expect(z.parse(a, null)).toEqual(false);
expect(z.parse(a, "")).toEqual(false);
});
test("z.coerce.bigint", () => {
const a = z.coerce.bigint();
expect(z.parse(a, "123")).toEqual(BigInt(123));
expect(z.parse(a, 123)).toEqual(BigInt(123));
expect(() => z.parse(a, "abc")).toThrow();
});
test("z.coerce.date", () => {
const a = z.coerce.date();
const date = new Date();
expect(z.parse(a, date.toISOString())).toEqual(date);
expect(z.parse(a, date.getTime())).toEqual(date);
expect(() => z.parse(a, "invalid date")).toThrow();
});
test("z.iso.datetime", () => {
const d1 = "2021-01-01T00:00:00Z";
const d2 = "2021-01-01T00:00:00.123Z";
const d3 = "2021-01-01T00:00:00";
const d4 = "2021-01-01T00:00:00+07:00";
const d5 = "bad data";
// local: false, offset: false, precision: null
const a = z.iso.datetime();
expect(z.safeParse(a, d1).success).toEqual(true);
expect(z.safeParse(a, d2).success).toEqual(true);
expect(z.safeParse(a, d3).success).toEqual(false);
expect(z.safeParse(a, d4).success).toEqual(false);
expect(z.safeParse(a, d5).success).toEqual(false);
const b = z.iso.datetime({ local: true });
expect(z.safeParse(b, d1).success).toEqual(true);
expect(z.safeParse(b, d2).success).toEqual(true);
expect(z.safeParse(b, d3).success).toEqual(true);
expect(z.safeParse(b, d4).success).toEqual(false);
expect(z.safeParse(b, d5).success).toEqual(false);
const c = z.iso.datetime({ offset: true });
expect(z.safeParse(c, d1).success).toEqual(true);
expect(z.safeParse(c, d2).success).toEqual(true);
expect(z.safeParse(c, d3).success).toEqual(false);
expect(z.safeParse(c, d4).success).toEqual(true);
expect(z.safeParse(c, d5).success).toEqual(false);
const d = z.iso.datetime({ precision: 3 });
expect(z.safeParse(d, d1).success).toEqual(false);
expect(z.safeParse(d, d2).success).toEqual(true);
expect(z.safeParse(d, d3).success).toEqual(false);
expect(z.safeParse(d, d4).success).toEqual(false);
expect(z.safeParse(d, d5).success).toEqual(false);
});
test("z.iso.date", () => {
const d1 = "2021-01-01";
const d2 = "bad data";
const a = z.iso.date();
expect(z.safeParse(a, d1).success).toEqual(true);
expect(z.safeParse(a, d2).success).toEqual(false);
const b = z.string().check(z.iso.date());
expect(z.safeParse(b, d1).success).toEqual(true);
expect(z.safeParse(b, d2).success).toEqual(false);
});
test("z.iso.time", () => {
const d1 = "00:00:00";
const d2 = "00:00:00.123";
const d3 = "bad data";
const a = z.iso.time();
expect(z.safeParse(a, d1).success).toEqual(true);
expect(z.safeParse(a, d2).success).toEqual(true);
expect(z.safeParse(a, d3).success).toEqual(false);
const b = z.iso.time({ precision: 3 });
expect(z.safeParse(b, d1).success).toEqual(false);
expect(z.safeParse(b, d2).success).toEqual(true);
expect(z.safeParse(b, d3).success).toEqual(false);
const c = z.string().check(z.iso.time());
expect(z.safeParse(c, d1).success).toEqual(true);
expect(z.safeParse(c, d2).success).toEqual(true);
expect(z.safeParse(c, d3).success).toEqual(false);
});
test("z.iso.duration", () => {
const d1 = "P3Y6M4DT12H30M5S";
const d2 = "bad data";
const a = z.iso.duration();
expect(z.safeParse(a, d1).success).toEqual(true);
expect(z.safeParse(a, d2).success).toEqual(false);
const b = z.string().check(z.iso.duration());
expect(z.safeParse(b, d1).success).toEqual(true);
expect(z.safeParse(b, d2).success).toEqual(false);
});
test("z.undefined", () => {
const a = z.undefined();
expect(z.parse(a, undefined)).toEqual(undefined);
expect(() => z.parse(a, "undefined")).toThrow();
});
test("z.null", () => {
const a = z.null();
expect(z.parse(a, null)).toEqual(null);
expect(() => z.parse(a, "null")).toThrow();
});
test("z.any", () => {
const a = z.any();
expect(z.parse(a, "hello")).toEqual("hello");
expect(z.parse(a, 123)).toEqual(123);
expect(z.parse(a, true)).toEqual(true);
expect(z.parse(a, null)).toEqual(null);
expect(z.parse(a, undefined)).toEqual(undefined);
z.parse(a, {});
z.parse(a, []);
z.parse(a, Symbol());
z.parse(a, new Date());
});
test("z.unknown", () => {
const a = z.unknown();
expect(z.parse(a, "hello")).toEqual("hello");
expect(z.parse(a, 123)).toEqual(123);
expect(z.parse(a, true)).toEqual(true);
expect(z.parse(a, null)).toEqual(null);
expect(z.parse(a, undefined)).toEqual(undefined);
z.parse(a, {});
z.parse(a, []);
z.parse(a, Symbol());
z.parse(a, new Date());
});
test("z.never", () => {
const a = z.never();
expect(() => z.parse(a, "hello")).toThrow();
});
test("z.void", () => {
const a = z.void();
expect(z.parse(a, undefined)).toEqual(undefined);
expect(() => z.parse(a, null)).toThrow();
});
test("z.array", () => {
const a = z.array(z.string());
expect(z.parse(a, ["hello", "world"])).toEqual(["hello", "world"]);
expect(() => z.parse(a, [123])).toThrow();
expect(() => z.parse(a, "hello")).toThrow();
});
test("z.union", () => {
const a = z.union([z.string(), z.number()]);
expect(z.parse(a, "hello")).toEqual("hello");
expect(z.parse(a, 123)).toEqual(123);
expect(() => z.parse(a, true)).toThrow();
});
test("z.intersection", () => {
const a = z.intersection(z.object({ a: z.string() }), z.object({ b: z.number() }));
expect(z.parse(a, { a: "hello", b: 123 })).toEqual({ a: "hello", b: 123 });
expect(() => z.parse(a, { a: "hello" })).toThrow();
expect(() => z.parse(a, { b: 123 })).toThrow();
expect(() => z.parse(a, "hello")).toThrow();
});
test("z.tuple", () => {
const a = z.tuple([z.string(), z.number()]);
expect(z.parse(a, ["hello", 123])).toEqual(["hello", 123]);
expect(() => z.parse(a, ["hello", "world"])).toThrow();
expect(() => z.parse(a, [123, 456])).toThrow();
expect(() => z.parse(a, "hello")).toThrow();
// tuple with rest
const b = z.tuple([z.string(), z.number(), z.optional(z.string())], z.boolean());
type b = z.output<typeof b>;
expectTypeOf<b>().toEqualTypeOf<[string, number, string?, ...boolean[]]>();
const datas = [
["hello", 123],
["hello", 123, "world"],
["hello", 123, "world", true],
["hello", 123, "world", true, false, true],
];
for (const data of datas) {
expect(z.parse(b, data)).toEqual(data);
}
expect(() => z.parse(b, ["hello", 123, 123])).toThrow();
expect(() => z.parse(b, ["hello", 123, "world", 123])).toThrow();
// tuple with readonly args
const cArgs = [z.string(), z.number(), z.optional(z.string())] as const;
const c = z.tuple(cArgs, z.boolean());
type c = z.output<typeof c>;
expectTypeOf<c>().toEqualTypeOf<[string, number, string?, ...boolean[]]>();
// type c = z.output<typeof c>;
});
test("z.record", () => {
// record schema with enum keys
const a = z.record(z.string(), z.string());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<Record<string, string>>();
const b = z.record(z.union([z.string(), z.number(), z.symbol()]), z.string());
type b = z.output<typeof b>;
expectTypeOf<b>().toEqualTypeOf<Record<string | number | symbol, string>>();
expect(z.parse(b, { a: "hello", 1: "world", [Symbol.for("asdf")]: "symbol" })).toEqual({
a: "hello",
1: "world",
[Symbol.for("asdf")]: "symbol",
});
// enum keys
const c = z.record(z.enum(["a", "b", "c"]), z.string());
type c = z.output<typeof c>;
expectTypeOf<c>().toEqualTypeOf<Record<"a" | "b" | "c", string>>();
expect(z.parse(c, { a: "hello", b: "world", c: "world" })).toEqual({
a: "hello",
b: "world",
c: "world",
});
// missing keys
expect(() => z.parse(c, { a: "hello", b: "world" })).toThrow();
// extra keys
expect(() => z.parse(c, { a: "hello", b: "world", c: "world", d: "world" })).toThrow();
// partial enum
const d = z.record(z.enum(["a", "b"]).or(z.never()), z.string());
type d = z.output<typeof d>;
expectTypeOf<d>().toEqualTypeOf<Record<"a" | "b", string>>();
});
test("z.map", () => {
const a = z.map(z.string(), z.number());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<Map<string, number>>();
expect(z.parse(a, new Map([["hello", 123]]))).toEqual(new Map([["hello", 123]]));
expect(() => z.parse(a, new Map([["hello", "world"]]))).toThrow();
expect(() => z.parse(a, new Map([[1243, "world"]]))).toThrow();
expect(() => z.parse(a, "hello")).toThrow();
const r1 = z.safeParse(a, new Map([[123, 123]]));
expect(r1.error?.issues[0].code).toEqual("invalid_type");
expect(r1.error?.issues[0].path).toEqual([123]);
const r2: any = z.safeParse(a, new Map([[BigInt(123), 123]]));
expect(r2.error!.issues[0].code).toEqual("invalid_key");
expect(r2.error!.issues[0].path).toEqual([]);
const r3: any = z.safeParse(a, new Map([["hello", "world"]]));
expect(r3.error!.issues[0].code).toEqual("invalid_type");
expect(r3.error!.issues[0].path).toEqual(["hello"]);
});
test("z.map invalid_element", () => {
const a = z.map(z.bigint(), z.number());
const r1 = z.safeParse(a, new Map([[BigInt(123), BigInt(123)]]));
expect(r1.error!.issues[0].code).toEqual("invalid_element");
expect(r1.error!.issues[0].path).toEqual([]);
});
test("z.map async", async () => {
const a = z.map(z.string().check(z.refine(async () => true)), z.number().check(z.refine(async () => true)));
const d1 = new Map([["hello", 123]]);
expect(await z.parseAsync(a, d1)).toEqual(d1);
await expect(z.parseAsync(a, new Map([[123, 123]]))).rejects.toThrow();
await expect(z.parseAsync(a, new Map([["hi", "world"]]))).rejects.toThrow();
await expect(z.parseAsync(a, new Map([[1243, "world"]]))).rejects.toThrow();
await expect(z.parseAsync(a, "hello")).rejects.toThrow();
const r = await z.safeParseAsync(a, new Map([[123, 123]]));
expect(r.success).toEqual(false);
expect(r.error!.issues[0].code).toEqual("invalid_type");
expect(r.error!.issues[0].path).toEqual([123]);
});
test("z.set", () => {
const a = z.set(z.string());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<Set<string>>();
expect(z.parse(a, new Set(["hello", "world"]))).toEqual(new Set(["hello", "world"]));
expect(() => z.parse(a, new Set([123]))).toThrow();
expect(() => z.parse(a, ["hello", "world"])).toThrow();
expect(() => z.parse(a, "hello")).toThrow();
const b = z.set(z.number());
expect(z.parse(b, new Set([1, 2, 3]))).toEqual(new Set([1, 2, 3]));
expect(() => z.parse(b, new Set(["hello"]))).toThrow();
expect(() => z.parse(b, [1, 2, 3])).toThrow();
expect(() => z.parse(b, 123)).toThrow();
});
test("z.enum", () => {
const a = z.enum(["A", "B", "C"]);
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<"A" | "B" | "C">();
expect(z.parse(a, "A")).toEqual("A");
expect(z.parse(a, "B")).toEqual("B");
expect(z.parse(a, "C")).toEqual("C");
expect(() => z.parse(a, "D")).toThrow();
expect(() => z.parse(a, 123)).toThrow();
expect(a.enum.A).toEqual("A");
expect(a.enum.B).toEqual("B");
expect(a.enum.C).toEqual("C");
expect((a.enum as any).D).toEqual(undefined);
});
test("z.enum - native", () => {
enum NativeEnum {
A = "A",
B = "B",
C = "C",
}
const a = z.enum(NativeEnum);
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<NativeEnum>();
expect(z.parse(a, NativeEnum.A)).toEqual(NativeEnum.A);
expect(z.parse(a, NativeEnum.B)).toEqual(NativeEnum.B);
expect(z.parse(a, NativeEnum.C)).toEqual(NativeEnum.C);
expect(() => z.parse(a, "D")).toThrow();
expect(() => z.parse(a, 123)).toThrow();
// test a.enum
a;
expect(a.enum.A).toEqual(NativeEnum.A);
expect(a.enum.B).toEqual(NativeEnum.B);
expect(a.enum.C).toEqual(NativeEnum.C);
});
test("z.nativeEnum", () => {
enum NativeEnum {
A = "A",
B = "B",
C = "C",
}
const a = z.nativeEnum(NativeEnum);
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<NativeEnum>();
expect(z.parse(a, NativeEnum.A)).toEqual(NativeEnum.A);
expect(z.parse(a, NativeEnum.B)).toEqual(NativeEnum.B);
expect(z.parse(a, NativeEnum.C)).toEqual(NativeEnum.C);
expect(() => z.parse(a, "D")).toThrow();
expect(() => z.parse(a, 123)).toThrow();
// test a.enum
a;
expect(a.enum.A).toEqual(NativeEnum.A);
expect(a.enum.B).toEqual(NativeEnum.B);
expect(a.enum.C).toEqual(NativeEnum.C);
});
test("z.literal", () => {
const a = z.literal("hello");
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<"hello">();
expect(z.parse(a, "hello")).toEqual("hello");
expect(() => z.parse(a, "world")).toThrow();
expect(() => z.parse(a, 123)).toThrow();
});
test("z.file", () => {
const a = z.file();
const file = new File(["content"], "filename.txt", { type: "text/plain" });
expect(z.parse(a, file)).toEqual(file);
expect(() => z.parse(a, "file")).toThrow();
expect(() => z.parse(a, 123)).toThrow();
});
test("z.transform", () => {
const a = z.pipe(
z.string(),
z.transform((val) => val.toUpperCase())
);
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string>();
expect(z.parse(a, "hello")).toEqual("HELLO");
expect(() => z.parse(a, 123)).toThrow();
});
test("z.transform async", async () => {
const a = z.pipe(
z.string(),
z.transform(async (val) => val.toUpperCase())
);
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string>();
expect(await z.parseAsync(a, "hello")).toEqual("HELLO");
await expect(() => z.parseAsync(a, 123)).rejects.toThrow();
});
test("z.preprocess", () => {
const a = z.pipe(
z.transform((val) => String(val).toUpperCase()),
z.string()
);
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string>();
expect(z.parse(a, 123)).toEqual("123");
expect(z.parse(a, true)).toEqual("TRUE");
expect(z.parse(a, BigInt(1234))).toEqual("1234");
// expect(() => z.parse(a, Symbol("asdf"))).toThrow();
});
// test("z.preprocess async", () => {
// const a = z.preprocess(async (val) => String(val), z.string());
// type a = z.output<typeof a>;
// expectTypeOf<a>().toEqualTypeOf<string>();
// expect(z.parse(a, 123)).toEqual("123");
// expect(z.parse(a, true)).toEqual("true");
// expect(() => z.parse(a, {})).toThrow();
// });
test("z.optional", () => {
const a = z.optional(z.string());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string | undefined>();
expect(z.parse(a, "hello")).toEqual("hello");
expect(z.parse(a, undefined)).toEqual(undefined);
expect(() => z.parse(a, 123)).toThrow();
});
test("z.nullable", () => {
const a = z.nullable(z.string());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string | null>();
expect(z.parse(a, "hello")).toEqual("hello");
expect(z.parse(a, null)).toEqual(null);
expect(() => z.parse(a, 123)).toThrow();
});
test("z.default", () => {
const a = z._default(z.string(), "default");
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string>();
expect(z.parse(a, undefined)).toEqual("default");
expect(z.parse(a, "hello")).toEqual("hello");
expect(() => z.parse(a, 123)).toThrow();
const b = z._default(z.string(), () => "default");
expect(z.parse(b, undefined)).toEqual("default");
expect(z.parse(b, "hello")).toEqual("hello");
expect(() => z.parse(b, 123)).toThrow();
});
test("z.catch", () => {
const a = z.catch(z.string(), "default");
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string>();
expect(z.parse(a, "hello")).toEqual("hello");
expect(z.parse(a, 123)).toEqual("default");
const b = z.catch(z.string(), () => "default");
expect(z.parse(b, "hello")).toEqual("hello");
expect(z.parse(b, 123)).toEqual("default");
const c = z.catch(z.string(), (ctx) => {
return `${ctx.error.issues.length}issues`;
});
expect(z.parse(c, 1234)).toEqual("1issues");
});
test("z.nan", () => {
const a = z.nan();
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<number>();
expect(z.parse(a, Number.NaN)).toEqual(Number.NaN);
expect(() => z.parse(a, 123)).toThrow();
expect(() => z.parse(a, "NaN")).toThrow();
});
test("z.pipe", () => {
const a = z.pipe(
z.pipe(
z.string(),
z.transform((val) => val.length)
),
z.number()
);
type a_in = z.input<typeof a>;
expectTypeOf<a_in>().toEqualTypeOf<string>();
type a_out = z.output<typeof a>;
expectTypeOf<a_out>().toEqualTypeOf<number>();
expect(z.parse(a, "123")).toEqual(3);
expect(z.parse(a, "hello")).toEqual(5);
expect(() => z.parse(a, 123)).toThrow();
});
test("z.readonly", () => {
const a = z.readonly(z.string());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<Readonly<string>>();
expect(z.parse(a, "hello")).toEqual("hello");
expect(() => z.parse(a, 123)).toThrow();
});
test("z.templateLiteral", () => {
const a = z.templateLiteral([z.string(), z.number()]);
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<`${string}${number}`>();
expect(z.parse(a, "hello123")).toEqual("hello123");
expect(() => z.parse(a, "hello")).toThrow();
expect(() => z.parse(a, 123)).toThrow();
// multipart
const b = z.templateLiteral([z.string(), z.number(), z.string()]);
type b = z.output<typeof b>;
expectTypeOf<b>().toEqualTypeOf<`${string}${number}${string}`>();
expect(z.parse(b, "hello123world")).toEqual("hello123world");
expect(z.parse(b, "123")).toEqual("123");
expect(() => z.parse(b, "hello")).toThrow();
expect(() => z.parse(b, 123)).toThrow();
// include boolean
const c = z.templateLiteral([z.string(), z.boolean()]);
type c = z.output<typeof c>;
expectTypeOf<c>().toEqualTypeOf<`${string}${boolean}`>();
expect(z.parse(c, "hellotrue")).toEqual("hellotrue");
expect(z.parse(c, "hellofalse")).toEqual("hellofalse");
expect(() => z.parse(c, "hello")).toThrow();
expect(() => z.parse(c, 123)).toThrow();
// include literal prefix
const d = z.templateLiteral([z.literal("hello"), z.number()]);
type d = z.output<typeof d>;
expectTypeOf<d>().toEqualTypeOf<`hello${number}`>();
expect(z.parse(d, "hello123")).toEqual("hello123");
expect(() => z.parse(d, 123)).toThrow();
expect(() => z.parse(d, "world123")).toThrow();
// include literal union
const e = z.templateLiteral([z.literal(["aa", "bb"]), z.number()]);
type e = z.output<typeof e>;
expectTypeOf<e>().toEqualTypeOf<`aa${number}` | `bb${number}`>();
expect(z.parse(e, "aa123")).toEqual("aa123");
expect(z.parse(e, "bb123")).toEqual("bb123");
expect(() => z.parse(e, "cc123")).toThrow();
expect(() => z.parse(e, 123)).toThrow();
});
// this returns both a schema and a check
test("z.custom schema", () => {
const a = z.custom((val) => {
return typeof val === "string";
});
expect(z.parse(a, "hello")).toEqual("hello");
expect(() => z.parse(a, 123)).toThrow();
});
test("z.custom check", () => {
// @ts-expect-error Inference not possible, use z.refine()
z.date().check(z.custom((val) => val.getTime() > 0));
});
test("z.check", () => {
// this is a more flexible version of z.custom that accepts an arbitrary _parse logic
// the function should return base.$ZodResult
const a = z.any().check(
z.check<string>((ctx) => {
if (typeof ctx.value === "string") return;
ctx.issues.push({
code: "custom",
origin: "custom",
message: "Expected a string",
input: ctx.value,
});
})
);
expect(z.safeParse(a, "hello")).toMatchObject({
success: true,
data: "hello",
});
expect(z.safeParse(a, 123)).toMatchObject({
success: false,
error: { issues: [{ code: "custom", message: "Expected a string" }] },
});
});
test("z.instanceof", () => {
class A {}
const a = z.instanceof(A);
expect(z.parse(a, new A())).toBeInstanceOf(A);
expect(() => z.parse(a, {})).toThrow();
});
test("z.refine", () => {
const a = z.number().check(
z.refine((val) => val > 3),
z.refine((val) => val < 10)
);
expect(z.parse(a, 5)).toEqual(5);
expect(() => z.parse(a, 2)).toThrow();
expect(() => z.parse(a, 11)).toThrow();
expect(() => z.parse(a, "hi")).toThrow();
});
// test("z.superRefine", () => {
// const a = z.number([
// z.superRefine((val, ctx) => {
// if (val < 3) {
// return ctx.addIssue({
// code: "custom",
// origin: "custom",
// message: "Too small",
// input: val,
// });
// }
// if (val > 10) {
// return ctx.addIssue("Too big");
// }
// }),
// ]);
// expect(z.parse(a, 5)).toEqual(5);
// expect(() => z.parse(a, 2)).toThrow();
// expect(() => z.parse(a, 11)).toThrow();
// expect(() => z.parse(a, "hi")).toThrow();
// });
test("z.transform", () => {
const a = z.transform((val: number) => {
return `${val}`;
});
type a_in = z.input<typeof a>;
expectTypeOf<a_in>().toEqualTypeOf<number>();
type a_out = z.output<typeof a>;
expectTypeOf<a_out>().toEqualTypeOf<string>();
expect(z.parse(a, 123)).toEqual("123");
});
test("z.$brand()", () => {
const a = z.string().brand<"my-brand">();
type a = z.output<typeof a>;
const branded = (_: a) => {};
// @ts-expect-error
branded("asdf");
});
test("z.lazy", () => {
const a = z.lazy(() => z.string());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string>();
expect(z.parse(a, "hello")).toEqual("hello");
expect(() => z.parse(a, 123)).toThrow();
});
// schema that validates JSON-like data
test("z.json", () => {
const a = z.json();
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<util.JSONType>();
expect(z.parse(a, "hello")).toEqual("hello");
expect(z.parse(a, 123)).toEqual(123);
expect(z.parse(a, true)).toEqual(true);
expect(z.parse(a, null)).toEqual(null);
expect(z.parse(a, {})).toEqual({});
expect(z.parse(a, { a: "hello" })).toEqual({ a: "hello" });
expect(z.parse(a, [1, 2, 3])).toEqual([1, 2, 3]);
expect(z.parse(a, [{ a: "hello" }])).toEqual([{ a: "hello" }]);
// fail cases
expect(() => z.parse(a, new Date())).toThrow();
expect(() => z.parse(a, Symbol())).toThrow();
expect(() => z.parse(a, { a: new Date() })).toThrow();
expect(() => z.parse(a, undefined)).toThrow();
expect(() => z.parse(a, { a: undefined })).toThrow();
});
// promise
test("z.promise", async () => {
const a = z.promise(z.string());
type a = z.output<typeof a>;
expectTypeOf<a>().toEqualTypeOf<string>();
expect(await z.safeParseAsync(a, Promise.resolve("hello"))).toMatchObject({
success: true,
data: "hello",
});
expect(await z.safeParseAsync(a, Promise.resolve(123))).toMatchObject({
success: false,
});
const b = z.string();
expect(() => z.parse(b, Promise.resolve("hello"))).toThrow();
});
// test("type assertions", () => {
// const schema = z.pipe(
// z.string(),
// z.transform((val) => val.length)
// );
// schema.assertInput<string>();
// // @ts-expect-error
// schema.assertInput<number>();
// schema.assertOutput<number>();
// // @ts-expect-error
// schema.assertOutput<string>();
// });
test("isPlainObject", () => {
expect(z.core.util.isPlainObject({})).toEqual(true);
expect(z.core.util.isPlainObject(Object.create(null))).toEqual(true);
expect(z.core.util.isPlainObject([])).toEqual(false);
expect(z.core.util.isPlainObject(new Date())).toEqual(false);
expect(z.core.util.isPlainObject(null)).toEqual(false);
expect(z.core.util.isPlainObject(undefined)).toEqual(false);
expect(z.core.util.isPlainObject("string")).toEqual(false);
expect(z.core.util.isPlainObject(123)).toEqual(false);
expect(z.core.util.isPlainObject(Symbol())).toEqual(false);
});
test("def typing", () => {
z.string().def.type satisfies "string";
z.number().def.type satisfies "number";
z.bigint().def.type satisfies "bigint";
z.boolean().def.type satisfies "boolean";
z.date().def.type satisfies "date";
z.symbol().def.type satisfies "symbol";
z.undefined().def.type satisfies "undefined";
z.string().nullable().def.type satisfies "nullable";
z.null().def.type satisfies "null";
z.any().def.type satisfies "any";
z.unknown().def.type satisfies "unknown";
z.never().def.type satisfies "never";
z.void().def.type satisfies "void";
z.array(z.string()).def.type satisfies "array";
z.object({ key: z.string() }).def.type satisfies "object";
z.union([z.string(), z.number()]).def.type satisfies "union";
z.intersection(z.string(), z.number()).def.type satisfies "intersection";
z.tuple([z.string(), z.number()]).def.type satisfies "tuple";
z.record(z.string(), z.number()).def.type satisfies "record";
z.map(z.string(), z.number()).def.type satisfies "map";
z.set(z.string()).def.type satisfies "set";
z.literal("example").def.type satisfies "literal";
z.enum(["a", "b", "c"]).def.type satisfies "enum";
z.promise(z.string()).def.type satisfies "promise";
z.lazy(() => z.string()).def.type satisfies "lazy";
z.string().optional().def.type satisfies "optional";
z.string().default("default").def.type satisfies "default";
z.templateLiteral([z.literal("a"), z.literal("b")]).def.type satisfies "template_literal";
z.custom<string>((val) => typeof val === "string").def.type satisfies "custom";
z.transform((val) => val as string).def.type satisfies "transform";
z.string().optional().nonoptional().def.type satisfies "nonoptional";
z.object({ key: z.string() }).readonly().def.type satisfies "readonly";
z.nan().def.type satisfies "nan";
z.unknown().pipe(z.number()).def.type satisfies "pipe";
z.success(z.string()).def.type satisfies "success";
z.string().catch("fallback").def.type satisfies "catch";
z.file().def.type satisfies "file";
});

View File

@@ -0,0 +1,23 @@
import type { ColumnBuilderBaseConfig } from "../../column-builder.js";
import type { ColumnBaseConfig } from "../../column.js";
import { entityKind } from "../../entity.js";
import { GelColumn } from "./common.js";
import { GelIntColumnBaseBuilder } from "./int.common.js";
export type GelSmallIntBuilderInitial<TName extends string> = GelSmallIntBuilder<{
name: TName;
dataType: 'number';
columnType: 'GelSmallInt';
data: number;
driverParam: number;
enumValues: undefined;
}>;
export declare class GelSmallIntBuilder<T extends ColumnBuilderBaseConfig<'number', 'GelSmallInt'>> extends GelIntColumnBaseBuilder<T> {
static readonly [entityKind]: string;
constructor(name: T['name']);
}
export declare class GelSmallInt<T extends ColumnBaseConfig<'number', 'GelSmallInt'>> extends GelColumn<T> {
static readonly [entityKind]: string;
getSQLType(): string;
}
export declare function smallint(): GelSmallIntBuilderInitial<''>;
export declare function smallint<TName extends string>(name: TName): GelSmallIntBuilderInitial<TName>;

View File

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

View File

@@ -0,0 +1,65 @@
import { ValidationError } from 'payload';
/**
* Handles unique constraint violation errors from PostgreSQL and SQLite,
* converting them to Payload ValidationErrors.
* Re-throws non-constraint errors unchanged.
*/ export const handleUpsertError = ({ id, adapter, collectionSlug, error: caughtError, globalSlug, req, tableName })=>{
let error = caughtError;
if (typeof caughtError === 'object' && caughtError !== null && 'cause' in caughtError) {
error = caughtError.cause;
}
// PostgreSQL: 23505, SQLite: SQLITE_CONSTRAINT_UNIQUE
if (error?.code === '23505' || error?.code === 'SQLITE_CONSTRAINT_UNIQUE') {
let fieldName = null;
if (error.code === '23505') {
// PostgreSQL - extract field name from constraint
if (adapter.fieldConstraints?.[tableName]?.[error.constraint]) {
fieldName = adapter.fieldConstraints[tableName][error.constraint];
} else {
const replacement = `${tableName}_`;
if (error.constraint?.includes(replacement)) {
const replacedConstraint = error.constraint.replace(replacement, '');
if (replacedConstraint && adapter.fieldConstraints[tableName]?.[replacedConstraint]) {
fieldName = adapter.fieldConstraints[tableName][replacedConstraint];
}
}
}
if (!fieldName && error.detail) {
// Extract from detail: "Key (field)=(value) already exists."
const regex = /Key \(([^)]+)\)=\(([^)]+)\)/;
const match = error.detail.match(regex);
if (match && match[1]) {
fieldName = match[1];
}
}
} else if (error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
// SQLite - extract from message: "UNIQUE constraint failed: table.field"
const regex = /UNIQUE constraint failed: ([^.]+)\.([^.]+)/;
const match = error.message?.match(regex);
if (match && match[2]) {
if (adapter.fieldConstraints[tableName]) {
fieldName = adapter.fieldConstraints[tableName][`${match[2]}_idx`];
}
if (!fieldName) {
fieldName = match[2];
}
}
}
throw new ValidationError({
id,
collection: collectionSlug,
errors: [
{
message: req?.t ? req.t('error:valueMustBeUnique') : 'Value must be unique',
path: fieldName
}
],
global: globalSlug,
req
}, req?.t);
}
// Re-throw non-constraint errors
throw caughtError;
};
//# sourceMappingURL=handleUpsertError.js.map

View File

@@ -0,0 +1,20 @@
/**
* Returns the width of a single character in terminal columns.
* @param ucs - The Unicode code point of the character
* @returns The width of the character in terminal columns:
* - 0 for null character
* - -1 for control characters
* - 0 for non-spacing characters
* - 1 for normal characters
* - 2 for wide characters (East Asian)
*/
declare function wcwidth(ucs: number): number;
/**
* Returns the width of a string in terminal columns.
* @param pwcs - The string to measure
* @returns The width of the string in terminal columns, or -1 if the string contains control characters
*/
declare function wcswidth(pwcs: string): number;
export { wcwidth, wcswidth };

View File

@@ -0,0 +1 @@
{"version":3,"file":"handleOnSpanStart.d.ts","sourceRoot":"","sources":["../../../src/server/handleOnSpanStart.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,cAAc,CAAC;AAiBzC;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,IAAI,GAAG,IAAI,CAiElD"}

View File

@@ -0,0 +1,3 @@
import type { Vocabulary } from "../types";
declare const draft7Vocabularies: Vocabulary[];
export default draft7Vocabularies;

View File

@@ -0,0 +1,2 @@
const e=require(`../../utils/throw-if-empty.cjs`),t=(t,n)=>()=>(e.throwIfEmpty(t,`ID cannot be empty`),{path:`/versions/${t}/save`,method:`POST`,body:JSON.stringify(n)}),n=t=>()=>(e.throwIfEmpty(t,`ID cannot be empty`),{path:`/versions/${t}/compare`,method:`GET`}),r=(t,n,r)=>()=>(e.throwIfEmpty(t,`ID cannot be empty`),{path:`/versions/${t}/promote`,method:`POST`,body:JSON.stringify(r?{mainHash:n,fields:r}:{mainHash:n})});exports.compareContentVersion=n,exports.promoteContentVersion=r,exports.saveToContentVersion=t;
//# sourceMappingURL=versions.cjs.map

View File

@@ -0,0 +1,4 @@
export declare const endOfQuarter: import("./types.js").FPFn1<
Date,
import("../fp.js").DateArg<Date>
>;

View File

@@ -0,0 +1,9 @@
/**
* @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.
*/
export { default } from './lock-keyhole-open.js';
//# sourceMappingURL=unlock-keyhole.js.map

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