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 @@
{"version":3,"sources":["../../../src/gel-core/columns/text.ts"],"sourcesContent":["import type { ColumnBuilderBaseConfig, ColumnBuilderRuntimeConfig, MakeColumnConfig } from '~/column-builder.ts';\nimport type { ColumnBaseConfig } from '~/column.ts';\nimport { entityKind } from '~/entity.ts';\nimport type { AnyGelTable } from '~/gel-core/table.ts';\nimport { GelColumn, GelColumnBuilder } from './common.ts';\n\ntype GelTextBuilderInitial<TName extends string> = GelTextBuilder<{\n\tname: TName;\n\tdataType: 'string';\n\tcolumnType: 'GelText';\n\tdata: string;\n\tdriverParam: string;\n\tenumValues: undefined;\n}>;\n\nexport class GelTextBuilder<\n\tT extends ColumnBuilderBaseConfig<'string', 'GelText'>,\n> extends GelColumnBuilder<T> {\n\tstatic override readonly [entityKind]: string = 'GelTextBuilder';\n\n\tconstructor(\n\t\tname: T['name'],\n\t) {\n\t\tsuper(name, 'string', 'GelText');\n\t}\n\n\t/** @internal */\n\toverride build<TTableName extends string>(\n\t\ttable: AnyGelTable<{ name: TTableName }>,\n\t): GelText<MakeColumnConfig<T, TTableName>> {\n\t\treturn new GelText<MakeColumnConfig<T, TTableName>>(table, this.config as ColumnBuilderRuntimeConfig<any, any>);\n\t}\n}\n\nexport class GelText<T extends ColumnBaseConfig<'string', 'GelText'>>\n\textends GelColumn<T, { enumValues: T['enumValues'] }>\n{\n\tstatic override readonly [entityKind]: string = 'GelText';\n\n\toverride readonly enumValues = this.config.enumValues;\n\n\tgetSQLType(): string {\n\t\treturn 'text';\n\t}\n}\n\nexport function text(): GelTextBuilderInitial<''>;\nexport function text<TName extends string>(name: TName): GelTextBuilderInitial<TName>;\nexport function text(name?: string): any {\n\treturn new GelTextBuilder(name ?? '');\n}\n"],"mappings":"AAEA,SAAS,kBAAkB;AAE3B,SAAS,WAAW,wBAAwB;AAWrC,MAAM,uBAEH,iBAAoB;AAAA,EAC7B,QAA0B,UAAU,IAAY;AAAA,EAEhD,YACC,MACC;AACD,UAAM,MAAM,UAAU,SAAS;AAAA,EAChC;AAAA;AAAA,EAGS,MACR,OAC2C;AAC3C,WAAO,IAAI,QAAyC,OAAO,KAAK,MAA8C;AAAA,EAC/G;AACD;AAEO,MAAM,gBACJ,UACT;AAAA,EACC,QAA0B,UAAU,IAAY;AAAA,EAE9B,aAAa,KAAK,OAAO;AAAA,EAE3C,aAAqB;AACpB,WAAO;AAAA,EACR;AACD;AAIO,SAAS,KAAK,MAAoB;AACxC,SAAO,IAAI,eAAe,QAAQ,EAAE;AACrC;","names":[]}

View File

@@ -0,0 +1,29 @@
import { DirectusDashboard } from "../../../schema/dashboard.js";
import { NestedPartial } from "../../../types/utils.js";
import { ApplyQueryFields } from "../../../types/output.js";
import { Query } from "../../../types/query.js";
import { RestCommand } from "../../types.js";
//#region src/rest/commands/create/dashboards.d.ts
type CreateDashboardOutput<Schema, TQuery extends Query<Schema, Item>, Item extends object = DirectusDashboard<Schema>> = ApplyQueryFields<Schema, Item, TQuery['fields']>;
/**
* Create multiple new dashboards.
*
* @param items The items to create
* @param query Optional return data query
*
* @returns Returns the dashboard object for the created dashboards.
*/
declare const createDashboards: <Schema, const TQuery extends Query<Schema, DirectusDashboard<Schema>>>(items: NestedPartial<DirectusDashboard<Schema>>[], query?: TQuery) => RestCommand<CreateDashboardOutput<Schema, TQuery>[], Schema>;
/**
* Create a new dashboard.
*
* @param item The dashboard to create
* @param query Optional return data query
*
* @returns Returns the dashboard object for the created dashboard.
*/
declare const createDashboard: <Schema, const TQuery extends Query<Schema, DirectusDashboard<Schema>>>(item: NestedPartial<DirectusDashboard<Schema>>, query?: TQuery) => RestCommand<CreateDashboardOutput<Schema, TQuery>, Schema>;
//#endregion
export { CreateDashboardOutput, createDashboard, createDashboards };
//# sourceMappingURL=dashboards.d.ts.map

View File

@@ -0,0 +1,7 @@
import React from 'react';
export declare const RenderComponent: React.FC<{
readonly Component?: React.ComponentType | React.ComponentType[];
readonly Fallback?: React.ComponentType;
readonly props?: object;
}>;
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,17 @@
'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import React from 'react';
import { RenderVersionFieldsToDiff } from '../../RenderVersionFieldsToDiff.js';
const baseClass = 'row-diff';
export const Row = ({
baseVersionField
}) => {
return /*#__PURE__*/_jsx("div", {
className: baseClass,
children: /*#__PURE__*/_jsx(RenderVersionFieldsToDiff, {
versionFields: baseVersionField.fields
})
});
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,209 @@
import { GraphQLBoolean, GraphQLInt, GraphQLNonNull, GraphQLString } from 'graphql';
import pluralize from 'pluralize';
const { singular } = pluralize;
import { buildVersionGlobalFields, toWords } from 'payload';
import { hasDraftsEnabled } from 'payload/shared';
import { docAccessResolver } from '../resolvers/globals/docAccess.js';
import { findOne } from '../resolvers/globals/findOne.js';
import { findVersionByID } from '../resolvers/globals/findVersionByID.js';
import { findVersions } from '../resolvers/globals/findVersions.js';
import { restoreVersion } from '../resolvers/globals/restoreVersion.js';
import { update } from '../resolvers/globals/update.js';
import { formatName } from '../utilities/formatName.js';
import { buildMutationInputType } from './buildMutationInputType.js';
import { buildObjectType } from './buildObjectType.js';
import { buildPaginatedListType } from './buildPaginatedListType.js';
import { buildPolicyType } from './buildPoliciesType.js';
import { buildWhereInputType } from './buildWhereInputType.js';
export function initGlobals({ config, graphqlResult }) {
Object.keys(graphqlResult.globals.config).forEach((slug)=>{
const global = graphqlResult.globals.config[slug];
const { fields, graphQL } = global;
if (graphQL === false) {
return;
}
const formattedName = graphQL?.name ? graphQL.name : singular(toWords(global.slug, true));
const forceNullableObjectType = hasDraftsEnabled(global);
if (!graphqlResult.globals.graphQL) {
graphqlResult.globals.graphQL = {};
}
const updateMutationInputType = buildMutationInputType({
name: formattedName,
config,
fields,
graphqlResult,
parentIsLocalized: false,
parentName: formattedName
});
graphqlResult.globals.graphQL[slug] = {
type: buildObjectType({
name: formattedName,
config,
fields,
forceNullable: forceNullableObjectType,
graphqlResult,
parentName: formattedName
}),
mutationInputType: updateMutationInputType ? new GraphQLNonNull(updateMutationInputType) : null
};
const queriesEnabled = typeof global.graphQL !== 'object' || !global.graphQL.disableQueries;
const mutationsEnabled = typeof global.graphQL !== 'object' || !global.graphQL.disableMutations;
if (queriesEnabled) {
graphqlResult.Query.fields[formattedName] = {
type: graphqlResult.globals.graphQL[slug].type,
args: {
draft: {
type: GraphQLBoolean
},
...config.localization ? {
fallbackLocale: {
type: graphqlResult.types.fallbackLocaleInputType
},
locale: {
type: graphqlResult.types.localeInputType
}
} : {},
select: {
type: GraphQLBoolean
}
},
resolve: findOne(global)
};
graphqlResult.Query.fields[`docAccess${formattedName}`] = {
type: buildPolicyType({
type: 'global',
entity: global,
scope: 'docAccess',
typeSuffix: 'DocAccess'
}),
resolve: docAccessResolver(global)
};
}
if (mutationsEnabled) {
graphqlResult.Mutation.fields[`update${formattedName}`] = {
type: graphqlResult.globals.graphQL[slug].type,
args: {
...updateMutationInputType ? {
data: {
type: graphqlResult.globals.graphQL[slug].mutationInputType
}
} : {},
draft: {
type: GraphQLBoolean
},
...config.localization ? {
locale: {
type: graphqlResult.types.localeInputType
}
} : {}
},
resolve: update(global)
};
}
if (global.versions) {
const idType = config.db.defaultIDType === 'number' ? GraphQLInt : GraphQLString;
const versionGlobalFields = [
...buildVersionGlobalFields(config, global),
{
name: 'id',
type: config.db.defaultIDType
},
{
name: 'createdAt',
type: 'date',
label: 'Created At'
},
{
name: 'updatedAt',
type: 'date',
label: 'Updated At'
}
];
graphqlResult.globals.graphQL[slug].versionType = buildObjectType({
name: `${formattedName}Version`,
config,
fields: versionGlobalFields,
forceNullable: forceNullableObjectType,
graphqlResult,
parentName: `${formattedName}Version`
});
if (queriesEnabled) {
graphqlResult.Query.fields[`version${formatName(formattedName)}`] = {
type: graphqlResult.globals.graphQL[slug].versionType,
args: {
id: {
type: idType
},
draft: {
type: GraphQLBoolean
},
...config.localization ? {
fallbackLocale: {
type: graphqlResult.types.fallbackLocaleInputType
},
locale: {
type: graphqlResult.types.localeInputType
}
} : {},
select: {
type: GraphQLBoolean
}
},
resolve: findVersionByID(global)
};
graphqlResult.Query.fields[`versions${formattedName}`] = {
type: buildPaginatedListType(`versions${formatName(formattedName)}`, graphqlResult.globals.graphQL[slug].versionType),
args: {
where: {
type: buildWhereInputType({
name: `versions${formattedName}`,
fields: versionGlobalFields,
parentName: `versions${formattedName}`
})
},
...config.localization ? {
fallbackLocale: {
type: graphqlResult.types.fallbackLocaleInputType
},
locale: {
type: graphqlResult.types.localeInputType
}
} : {},
limit: {
type: GraphQLInt
},
page: {
type: GraphQLInt
},
pagination: {
type: GraphQLBoolean
},
select: {
type: GraphQLBoolean
},
sort: {
type: GraphQLString
}
},
resolve: findVersions(global)
};
}
if (mutationsEnabled) {
graphqlResult.Mutation.fields[`restoreVersion${formatName(formattedName)}`] = {
type: graphqlResult.globals.graphQL[slug].type,
args: {
id: {
type: idType
},
draft: {
type: GraphQLBoolean
}
},
resolve: restoreVersion(global)
};
}
}
});
}
//# sourceMappingURL=initGlobals.js.map

View File

@@ -0,0 +1,40 @@
import { isSpanContextValid, wrapSpanContext } from '../trace/spancontext-utils';
import { Tracer } from '../trace/tracer';
import { TracerProvider } from '../trace/tracer_provider';
import { deleteSpan, getActiveSpan, getSpan, getSpanContext, setSpan, setSpanContext } from '../trace/context-utils';
/**
* Singleton object which represents the entry point to the OpenTelemetry Tracing API
*/
export declare class TraceAPI {
private static _instance?;
private _proxyTracerProvider;
/** Empty private constructor prevents end users from constructing a new instance of the API */
private constructor();
/** Get the singleton instance of the Trace API */
static getInstance(): TraceAPI;
/**
* Set the current global tracer.
*
* @returns true if the tracer provider was successfully registered, else false
*/
setGlobalTracerProvider(provider: TracerProvider): boolean;
/**
* Returns the global tracer provider.
*/
getTracerProvider(): TracerProvider;
/**
* Returns a tracer from the global tracer provider.
*/
getTracer(name: string, version?: string): Tracer;
/** Remove the global tracer provider */
disable(): void;
wrapSpanContext: typeof wrapSpanContext;
isSpanContextValid: typeof isSpanContextValid;
deleteSpan: typeof deleteSpan;
getSpan: typeof getSpan;
getActiveSpan: typeof getActiveSpan;
getSpanContext: typeof getSpanContext;
setSpan: typeof setSpan;
setSpanContext: typeof setSpanContext;
}
//# sourceMappingURL=trace.d.ts.map

View File

@@ -0,0 +1,11 @@
import { MergeCoreCollection } from "../types/schema.js";
//#region src/schema/folder.d.ts
type DirectusFolder<Schema = any> = MergeCoreCollection<Schema, 'directus_folders', {
id: string;
name: string;
parent: DirectusFolder<Schema> | string | null;
}>;
//#endregion
export { DirectusFolder };
//# sourceMappingURL=folder.d.ts.map

View File

@@ -0,0 +1,67 @@
/**
* 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.
*
* @flow strict
*/
import type {
EditorState,
LexicalEditor,
NodeKey,
RangeSelection,
} from 'lexical';
type OffsetElementNode = {
child: null | OffsetNode,
end: number,
key: NodeKey,
next: null | OffsetNode,
parent: null | OffsetElementNode,
prev: null | OffsetNode,
start: number,
type: 'element',
};
type OffsetTextNode = {
child: null,
end: number,
key: NodeKey,
next: null | OffsetNode,
parent: null | OffsetElementNode,
prev: null | OffsetNode,
start: number,
type: 'text',
};
type OffsetInlineNode = {
child: null,
end: number,
key: NodeKey,
next: null | OffsetNode,
parent: null | OffsetElementNode,
prev: null | OffsetNode,
start: number,
type: 'inline',
};
type OffsetNode = OffsetElementNode | OffsetTextNode | OffsetInlineNode;
type OffsetMap = Map<NodeKey, OffsetNode>;
declare export class OffsetView {
_offsetMap: OffsetMap;
_firstNode: null | OffsetNode;
_blockOffsetSize: number;
constructor(
offsetMap: OffsetMap,
firstNode: null | OffsetNode,
blockOffsetSize: number,
): void;
createSelectionFromOffsets(
originalStart: number,
originalEnd: number,
diffOffsetView?: OffsetView,
): null | RangeSelection;
getOffsetsFromSelection(selection: RangeSelection): [number, number];
}
declare export function $createOffsetView(
editor: LexicalEditor,
blockOffsetSize?: number,
editorState?: EditorState,
): OffsetView;

View File

@@ -0,0 +1,18 @@
/**
* @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 RectangleEllipsis = createLucideIcon("RectangleEllipsis", [
["rect", { width: "20", height: "12", x: "2", y: "6", rx: "2", key: "9lu3g6" }],
["path", { d: "M12 12h.01", key: "1mp3jc" }],
["path", { d: "M17 12h.01", key: "1m0b6t" }],
["path", { d: "M7 12h.01", key: "eqddd0" }]
]);
export { RectangleEllipsis as default };
//# sourceMappingURL=rectangle-ellipsis.js.map

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 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","260":"C","514":"L M G"},C:{"1":"0 1 2 3 4 5 6 7 8 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 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 4C 5C","194":"fB gB hB iB jB kB"},D:{"1":"0 1 2 3 4 5 6 7 8 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 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","260":"hB iB jB kB"},E:{"2":"J bB K D 6C bC 7C 8C","260":"E 9C","1028":"F A AD cC","3076":"B C L M G 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"},F:{"1":"0 1 2 3 4 5 6 7 8 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 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 JD KD LD MD PC xC ND QC","260":"AB BB CB DB"},G:{"2":"bC OD yC PD QD RD","260":"E SD","1028":"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"},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:1,C:"Srcset and sizes attributes",D:true};

View File

@@ -0,0 +1 @@
{"version":3,"file":"sword.js","sources":["../../../src/icons/sword.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Sword\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cG9seWxpbmUgcG9pbnRzPSIxNC41IDE3LjUgMyA2IDMgMyA2IDMgMTcuNSAxNC41IiAvPgogIDxsaW5lIHgxPSIxMyIgeDI9IjE5IiB5MT0iMTkiIHkyPSIxMyIgLz4KICA8bGluZSB4MT0iMTYiIHgyPSIyMCIgeTE9IjE2IiB5Mj0iMjAiIC8+CiAgPGxpbmUgeDE9IjE5IiB4Mj0iMjEiIHkxPSIyMSIgeTI9IjE5IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/sword\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 Sword = createLucideIcon('Sword', [\n ['polyline', { points: '14.5 17.5 3 6 3 3 6 3 17.5 14.5', key: '1hfsw2' }],\n ['line', { x1: '13', x2: '19', y1: '19', y2: '13', key: '1vrmhu' }],\n ['line', { x1: '16', x2: '20', y1: '16', y2: '20', key: '1bron3' }],\n ['line', { x1: '19', x2: '21', y1: '21', y2: '19', key: '13pww6' }],\n]);\n\nexport default Sword;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,iBAAiB,OAAS,CAAA,CAAA,CAAA;AAAA,CAAA,CACtC,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAY,CAAA,CAAA,CAAA,CAAE,QAAQ,CAAmC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CACzE,CAAA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAE,CAAA,CAAA,CAAA,EAAI,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAM,CAAA,CAAA,CAAA,CAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAM,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAClE,CAAA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAE,CAAA,CAAA,CAAA,EAAI,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAM,CAAA,CAAA,CAAA,CAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAM,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAClE,CAAA,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAE,CAAA,CAAA,CAAA,EAAI,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAI,CAAM,CAAA,CAAA,CAAA,CAAA,CAAA,EAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAM,CAAA,CAAA,CAAA,CAAA,CAAI,CAAA,CAAA,CAAA,CAAA,CAAM,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AACpE,CAAC,CAAA,CAAA;;"}

View File

@@ -0,0 +1,29 @@
/**
* 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 { registerLexicalTextEntity } from '@lexical/text';
import { mergeRegister } from '@lexical/utils';
import { useEffect } 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.
*
*/
function useLexicalTextEntity(getMatch, targetNode, createNode) {
const [editor] = useLexicalComposerContext();
useEffect(() => {
return mergeRegister(...registerLexicalTextEntity(editor, getMatch, targetNode, createNode));
}, [createNode, editor, getMatch, targetNode]);
}
export { useLexicalTextEntity };

View File

@@ -0,0 +1,194 @@
"use client";
import { createMotionComponent } from './create.mjs';
/**
* HTML components
*/
const MotionA = /*@__PURE__*/ createMotionComponent("a");
const MotionAbbr = /*@__PURE__*/ createMotionComponent("abbr");
const MotionAddress = /*@__PURE__*/ createMotionComponent("address");
const MotionArea = /*@__PURE__*/ createMotionComponent("area");
const MotionArticle = /*@__PURE__*/ createMotionComponent("article");
const MotionAside = /*@__PURE__*/ createMotionComponent("aside");
const MotionAudio = /*@__PURE__*/ createMotionComponent("audio");
const MotionB = /*@__PURE__*/ createMotionComponent("b");
const MotionBase = /*@__PURE__*/ createMotionComponent("base");
const MotionBdi = /*@__PURE__*/ createMotionComponent("bdi");
const MotionBdo = /*@__PURE__*/ createMotionComponent("bdo");
const MotionBig = /*@__PURE__*/ createMotionComponent("big");
const MotionBlockquote =
/*@__PURE__*/ createMotionComponent("blockquote");
const MotionBody = /*@__PURE__*/ createMotionComponent("body");
const MotionButton = /*@__PURE__*/ createMotionComponent("button");
const MotionCanvas = /*@__PURE__*/ createMotionComponent("canvas");
const MotionCaption = /*@__PURE__*/ createMotionComponent("caption");
const MotionCite = /*@__PURE__*/ createMotionComponent("cite");
const MotionCode = /*@__PURE__*/ createMotionComponent("code");
const MotionCol = /*@__PURE__*/ createMotionComponent("col");
const MotionColgroup = /*@__PURE__*/ createMotionComponent("colgroup");
const MotionData = /*@__PURE__*/ createMotionComponent("data");
const MotionDatalist = /*@__PURE__*/ createMotionComponent("datalist");
const MotionDd = /*@__PURE__*/ createMotionComponent("dd");
const MotionDel = /*@__PURE__*/ createMotionComponent("del");
const MotionDetails = /*@__PURE__*/ createMotionComponent("details");
const MotionDfn = /*@__PURE__*/ createMotionComponent("dfn");
const MotionDialog = /*@__PURE__*/ createMotionComponent("dialog");
const MotionDiv = /*@__PURE__*/ createMotionComponent("div");
const MotionDl = /*@__PURE__*/ createMotionComponent("dl");
const MotionDt = /*@__PURE__*/ createMotionComponent("dt");
const MotionEm = /*@__PURE__*/ createMotionComponent("em");
const MotionEmbed = /*@__PURE__*/ createMotionComponent("embed");
const MotionFieldset = /*@__PURE__*/ createMotionComponent("fieldset");
const MotionFigcaption =
/*@__PURE__*/ createMotionComponent("figcaption");
const MotionFigure = /*@__PURE__*/ createMotionComponent("figure");
const MotionFooter = /*@__PURE__*/ createMotionComponent("footer");
const MotionForm = /*@__PURE__*/ createMotionComponent("form");
const MotionH1 = /*@__PURE__*/ createMotionComponent("h1");
const MotionH2 = /*@__PURE__*/ createMotionComponent("h2");
const MotionH3 = /*@__PURE__*/ createMotionComponent("h3");
const MotionH4 = /*@__PURE__*/ createMotionComponent("h4");
const MotionH5 = /*@__PURE__*/ createMotionComponent("h5");
const MotionH6 = /*@__PURE__*/ createMotionComponent("h6");
const MotionHead = /*@__PURE__*/ createMotionComponent("head");
const MotionHeader = /*@__PURE__*/ createMotionComponent("header");
const MotionHgroup = /*@__PURE__*/ createMotionComponent("hgroup");
const MotionHr = /*@__PURE__*/ createMotionComponent("hr");
const MotionHtml = /*@__PURE__*/ createMotionComponent("html");
const MotionI = /*@__PURE__*/ createMotionComponent("i");
const MotionIframe = /*@__PURE__*/ createMotionComponent("iframe");
const MotionImg = /*@__PURE__*/ createMotionComponent("img");
const MotionInput = /*@__PURE__*/ createMotionComponent("input");
const MotionIns = /*@__PURE__*/ createMotionComponent("ins");
const MotionKbd = /*@__PURE__*/ createMotionComponent("kbd");
const MotionKeygen = /*@__PURE__*/ createMotionComponent("keygen");
const MotionLabel = /*@__PURE__*/ createMotionComponent("label");
const MotionLegend = /*@__PURE__*/ createMotionComponent("legend");
const MotionLi = /*@__PURE__*/ createMotionComponent("li");
const MotionLink = /*@__PURE__*/ createMotionComponent("link");
const MotionMain = /*@__PURE__*/ createMotionComponent("main");
const MotionMap = /*@__PURE__*/ createMotionComponent("map");
const MotionMark = /*@__PURE__*/ createMotionComponent("mark");
const MotionMenu = /*@__PURE__*/ createMotionComponent("menu");
const MotionMenuitem = /*@__PURE__*/ createMotionComponent("menuitem");
const MotionMeter = /*@__PURE__*/ createMotionComponent("meter");
const MotionNav = /*@__PURE__*/ createMotionComponent("nav");
const MotionObject = /*@__PURE__*/ createMotionComponent("object");
const MotionOl = /*@__PURE__*/ createMotionComponent("ol");
const MotionOptgroup = /*@__PURE__*/ createMotionComponent("optgroup");
const MotionOption = /*@__PURE__*/ createMotionComponent("option");
const MotionOutput = /*@__PURE__*/ createMotionComponent("output");
const MotionP = /*@__PURE__*/ createMotionComponent("p");
const MotionParam = /*@__PURE__*/ createMotionComponent("param");
const MotionPicture = /*@__PURE__*/ createMotionComponent("picture");
const MotionPre = /*@__PURE__*/ createMotionComponent("pre");
const MotionProgress = /*@__PURE__*/ createMotionComponent("progress");
const MotionQ = /*@__PURE__*/ createMotionComponent("q");
const MotionRp = /*@__PURE__*/ createMotionComponent("rp");
const MotionRt = /*@__PURE__*/ createMotionComponent("rt");
const MotionRuby = /*@__PURE__*/ createMotionComponent("ruby");
const MotionS = /*@__PURE__*/ createMotionComponent("s");
const MotionSamp = /*@__PURE__*/ createMotionComponent("samp");
const MotionScript = /*@__PURE__*/ createMotionComponent("script");
const MotionSection = /*@__PURE__*/ createMotionComponent("section");
const MotionSelect = /*@__PURE__*/ createMotionComponent("select");
const MotionSmall = /*@__PURE__*/ createMotionComponent("small");
const MotionSource = /*@__PURE__*/ createMotionComponent("source");
const MotionSpan = /*@__PURE__*/ createMotionComponent("span");
const MotionStrong = /*@__PURE__*/ createMotionComponent("strong");
const MotionStyle = /*@__PURE__*/ createMotionComponent("style");
const MotionSub = /*@__PURE__*/ createMotionComponent("sub");
const MotionSummary = /*@__PURE__*/ createMotionComponent("summary");
const MotionSup = /*@__PURE__*/ createMotionComponent("sup");
const MotionTable = /*@__PURE__*/ createMotionComponent("table");
const MotionTbody = /*@__PURE__*/ createMotionComponent("tbody");
const MotionTd = /*@__PURE__*/ createMotionComponent("td");
const MotionTextarea = /*@__PURE__*/ createMotionComponent("textarea");
const MotionTfoot = /*@__PURE__*/ createMotionComponent("tfoot");
const MotionTh = /*@__PURE__*/ createMotionComponent("th");
const MotionThead = /*@__PURE__*/ createMotionComponent("thead");
const MotionTime = /*@__PURE__*/ createMotionComponent("time");
const MotionTitle = /*@__PURE__*/ createMotionComponent("title");
const MotionTr = /*@__PURE__*/ createMotionComponent("tr");
const MotionTrack = /*@__PURE__*/ createMotionComponent("track");
const MotionU = /*@__PURE__*/ createMotionComponent("u");
const MotionUl = /*@__PURE__*/ createMotionComponent("ul");
const MotionVideo = /*@__PURE__*/ createMotionComponent("video");
const MotionWbr = /*@__PURE__*/ createMotionComponent("wbr");
const MotionWebview = /*@__PURE__*/ createMotionComponent("webview");
/**
* SVG components
*/
const MotionAnimate = /*@__PURE__*/ createMotionComponent("animate");
const MotionCircle = /*@__PURE__*/ createMotionComponent("circle");
const MotionDefs = /*@__PURE__*/ createMotionComponent("defs");
const MotionDesc = /*@__PURE__*/ createMotionComponent("desc");
const MotionEllipse = /*@__PURE__*/ createMotionComponent("ellipse");
const MotionG = /*@__PURE__*/ createMotionComponent("g");
const MotionImage = /*@__PURE__*/ createMotionComponent("image");
const MotionLine = /*@__PURE__*/ createMotionComponent("line");
const MotionFilter = /*@__PURE__*/ createMotionComponent("filter");
const MotionMarker = /*@__PURE__*/ createMotionComponent("marker");
const MotionMask = /*@__PURE__*/ createMotionComponent("mask");
const MotionMetadata = /*@__PURE__*/ createMotionComponent("metadata");
const MotionPath = /*@__PURE__*/ createMotionComponent("path");
const MotionPattern = /*@__PURE__*/ createMotionComponent("pattern");
const MotionPolygon = /*@__PURE__*/ createMotionComponent("polygon");
const MotionPolyline = /*@__PURE__*/ createMotionComponent("polyline");
const MotionRect = /*@__PURE__*/ createMotionComponent("rect");
const MotionStop = /*@__PURE__*/ createMotionComponent("stop");
const MotionSvg = /*@__PURE__*/ createMotionComponent("svg");
const MotionSymbol = /*@__PURE__*/ createMotionComponent("symbol");
const MotionText = /*@__PURE__*/ createMotionComponent("text");
const MotionTspan = /*@__PURE__*/ createMotionComponent("tspan");
const MotionUse = /*@__PURE__*/ createMotionComponent("use");
const MotionView = /*@__PURE__*/ createMotionComponent("view");
const MotionClipPath = /*@__PURE__*/ createMotionComponent("clipPath");
const MotionFeBlend = /*@__PURE__*/ createMotionComponent("feBlend");
const MotionFeColorMatrix =
/*@__PURE__*/ createMotionComponent("feColorMatrix");
const MotionFeComponentTransfer = /*@__PURE__*/ createMotionComponent("feComponentTransfer");
const MotionFeComposite =
/*@__PURE__*/ createMotionComponent("feComposite");
const MotionFeConvolveMatrix =
/*@__PURE__*/ createMotionComponent("feConvolveMatrix");
const MotionFeDiffuseLighting =
/*@__PURE__*/ createMotionComponent("feDiffuseLighting");
const MotionFeDisplacementMap =
/*@__PURE__*/ createMotionComponent("feDisplacementMap");
const MotionFeDistantLight =
/*@__PURE__*/ createMotionComponent("feDistantLight");
const MotionFeDropShadow =
/*@__PURE__*/ createMotionComponent("feDropShadow");
const MotionFeFlood = /*@__PURE__*/ createMotionComponent("feFlood");
const MotionFeFuncA = /*@__PURE__*/ createMotionComponent("feFuncA");
const MotionFeFuncB = /*@__PURE__*/ createMotionComponent("feFuncB");
const MotionFeFuncG = /*@__PURE__*/ createMotionComponent("feFuncG");
const MotionFeFuncR = /*@__PURE__*/ createMotionComponent("feFuncR");
const MotionFeGaussianBlur =
/*@__PURE__*/ createMotionComponent("feGaussianBlur");
const MotionFeImage = /*@__PURE__*/ createMotionComponent("feImage");
const MotionFeMerge = /*@__PURE__*/ createMotionComponent("feMerge");
const MotionFeMergeNode =
/*@__PURE__*/ createMotionComponent("feMergeNode");
const MotionFeMorphology =
/*@__PURE__*/ createMotionComponent("feMorphology");
const MotionFeOffset = /*@__PURE__*/ createMotionComponent("feOffset");
const MotionFePointLight =
/*@__PURE__*/ createMotionComponent("fePointLight");
const MotionFeSpecularLighting =
/*@__PURE__*/ createMotionComponent("feSpecularLighting");
const MotionFeSpotLight =
/*@__PURE__*/ createMotionComponent("feSpotLight");
const MotionFeTile = /*@__PURE__*/ createMotionComponent("feTile");
const MotionFeTurbulence =
/*@__PURE__*/ createMotionComponent("feTurbulence");
const MotionForeignObject =
/*@__PURE__*/ createMotionComponent("foreignObject");
const MotionLinearGradient =
/*@__PURE__*/ createMotionComponent("linearGradient");
const MotionRadialGradient =
/*@__PURE__*/ createMotionComponent("radialGradient");
const MotionTextPath = /*@__PURE__*/ createMotionComponent("textPath");
export { MotionA, MotionAbbr, MotionAddress, MotionAnimate, MotionArea, MotionArticle, MotionAside, MotionAudio, MotionB, MotionBase, MotionBdi, MotionBdo, MotionBig, MotionBlockquote, MotionBody, MotionButton, MotionCanvas, MotionCaption, MotionCircle, MotionCite, MotionClipPath, MotionCode, MotionCol, MotionColgroup, MotionData, MotionDatalist, MotionDd, MotionDefs, MotionDel, MotionDesc, MotionDetails, MotionDfn, MotionDialog, MotionDiv, MotionDl, MotionDt, MotionEllipse, MotionEm, MotionEmbed, MotionFeBlend, MotionFeColorMatrix, MotionFeComponentTransfer, MotionFeComposite, MotionFeConvolveMatrix, MotionFeDiffuseLighting, MotionFeDisplacementMap, MotionFeDistantLight, MotionFeDropShadow, MotionFeFlood, MotionFeFuncA, MotionFeFuncB, MotionFeFuncG, MotionFeFuncR, MotionFeGaussianBlur, MotionFeImage, MotionFeMerge, MotionFeMergeNode, MotionFeMorphology, MotionFeOffset, MotionFePointLight, MotionFeSpecularLighting, MotionFeSpotLight, MotionFeTile, MotionFeTurbulence, MotionFieldset, MotionFigcaption, MotionFigure, MotionFilter, MotionFooter, MotionForeignObject, MotionForm, MotionG, MotionH1, MotionH2, MotionH3, MotionH4, MotionH5, MotionH6, MotionHead, MotionHeader, MotionHgroup, MotionHr, MotionHtml, MotionI, MotionIframe, MotionImage, MotionImg, MotionInput, MotionIns, MotionKbd, MotionKeygen, MotionLabel, MotionLegend, MotionLi, MotionLine, MotionLinearGradient, MotionLink, MotionMain, MotionMap, MotionMark, MotionMarker, MotionMask, MotionMenu, MotionMenuitem, MotionMetadata, MotionMeter, MotionNav, MotionObject, MotionOl, MotionOptgroup, MotionOption, MotionOutput, MotionP, MotionParam, MotionPath, MotionPattern, MotionPicture, MotionPolygon, MotionPolyline, MotionPre, MotionProgress, MotionQ, MotionRadialGradient, MotionRect, MotionRp, MotionRt, MotionRuby, MotionS, MotionSamp, MotionScript, MotionSection, MotionSelect, MotionSmall, MotionSource, MotionSpan, MotionStop, MotionStrong, MotionStyle, MotionSub, MotionSummary, MotionSup, MotionSvg, MotionSymbol, MotionTable, MotionTbody, MotionTd, MotionText, MotionTextPath, MotionTextarea, MotionTfoot, MotionTh, MotionThead, MotionTime, MotionTitle, MotionTr, MotionTrack, MotionTspan, MotionU, MotionUl, MotionUse, MotionVideo, MotionView, MotionWbr, MotionWebview };

View File

@@ -0,0 +1,31 @@
'use client';
import { c as _c } from "react/compiler-runtime";
import { useEffect, useState } from 'react';
export function useDebounce(value, delay) {
const $ = _c(4);
const [debouncedValue, setDebouncedValue] = useState(value);
let t0;
let t1;
if ($[0] !== delay || $[1] !== value) {
t0 = () => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
};
t1 = [value, delay];
$[0] = delay;
$[1] = value;
$[2] = t0;
$[3] = t1;
} else {
t0 = $[2];
t1 = $[3];
}
useEffect(t0, t1);
return debouncedValue;
}
//# sourceMappingURL=useDebounce.js.map

View File

@@ -0,0 +1,69 @@
export const transformRelationship = ({ field, locale, ref, relations, withinArrayOrBlockLocale })=>{
let result;
if (!('hasMany' in field) || field.hasMany === false) {
let relation = relations[0];
if (withinArrayOrBlockLocale) {
relation = relations.find((rel)=>rel.locale === withinArrayOrBlockLocale);
}
if (relation) {
// Handle hasOne Poly
if (Array.isArray(field.relationTo)) {
const matchedRelation = Object.entries(relation).find(([key, val])=>{
return val !== null && ![
'id',
'locale',
'order',
'parent',
'path'
].includes(key);
});
if (matchedRelation) {
const relationTo = matchedRelation[0].replace('ID', '');
result = {
relationTo,
value: matchedRelation[1]
};
}
}
}
} else {
const transformedRelations = [];
relations.forEach((relation)=>{
let matchedLocale = true;
if (withinArrayOrBlockLocale) {
matchedLocale = relation.locale === withinArrayOrBlockLocale;
}
// Handle hasMany
if (!Array.isArray(field.relationTo)) {
const relatedData = relation[`${field.relationTo}ID`];
if (relatedData && matchedLocale) {
transformedRelations.push(relatedData);
}
} else {
// Handle hasMany Poly
const matchedRelation = Object.entries(relation).find(([key, val])=>val !== null && ![
'id',
'locale',
'order',
'parent',
'path'
].includes(key) && matchedLocale);
if (matchedRelation) {
const relationTo = matchedRelation[0].replace('ID', '');
transformedRelations.push({
relationTo,
value: matchedRelation[1]
});
}
}
});
result = transformedRelations;
}
if (locale) {
ref[field.name][locale] = result;
} else {
ref[field.name] = result;
}
};
//# sourceMappingURL=relationship.js.map

View File

@@ -0,0 +1,82 @@
const translations = {
about: "körülbelül",
over: "több mint",
almost: "majdnem",
lessthan: "kevesebb mint",
};
const withoutSuffixes = {
xseconds: " másodperc",
halfaminute: "fél perc",
xminutes: " perc",
xhours: " óra",
xdays: " nap",
xweeks: " hét",
xmonths: " hónap",
xyears: " év",
};
const withSuffixes = {
xseconds: {
"-1": " másodperccel ezelőtt",
1: " másodperc múlva",
0: " másodperce",
},
halfaminute: {
"-1": "fél perccel ezelőtt",
1: "fél perc múlva",
0: "fél perce",
},
xminutes: {
"-1": " perccel ezelőtt",
1: " perc múlva",
0: " perce",
},
xhours: {
"-1": " órával ezelőtt",
1: " óra múlva",
0: " órája",
},
xdays: {
"-1": " nappal ezelőtt",
1: " nap múlva",
0: " napja",
},
xweeks: {
"-1": " héttel ezelőtt",
1: " hét múlva",
0: " hete",
},
xmonths: {
"-1": " hónappal ezelőtt",
1: " hónap múlva",
0: " hónapja",
},
xyears: {
"-1": " évvel ezelőtt",
1: " év múlva",
0: " éve",
},
};
export const formatDistance = (token, count, options) => {
const adverb = token.match(/about|over|almost|lessthan/i);
const unit = adverb ? token.replace(adverb[0], "") : token;
const addSuffix = options?.addSuffix === true;
const key = unit.toLowerCase();
const comparison = options?.comparison || 0;
const translated = addSuffix
? withSuffixes[key][comparison]
: withoutSuffixes[key];
let result = key === "halfaminute" ? translated : count + translated;
if (adverb) {
const adv = adverb[0].toLowerCase();
result = translations[adv] + " " + result;
}
return result;
};

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../src/libsql/web/index.ts"],"sourcesContent":["import { type Client, type Config, createClient } from '@libsql/client/web';\nimport { type DrizzleConfig, isConfig } from '~/utils.ts';\nimport { construct, type LibSQLDatabase } from '../driver-core.ts';\n\nexport function drizzle<\n\tTSchema extends Record<string, unknown> = Record<string, never>,\n\tTClient extends Client = Client,\n>(\n\t...params: [\n\t\tTClient | string,\n\t] | [\n\t\tTClient | string,\n\t\tDrizzleConfig<TSchema>,\n\t] | [\n\t\t(\n\t\t\t& DrizzleConfig<TSchema>\n\t\t\t& ({\n\t\t\t\tconnection: string | Config;\n\t\t\t} | {\n\t\t\t\tclient: TClient;\n\t\t\t})\n\t\t),\n\t]\n): LibSQLDatabase<TSchema> & {\n\t$client: TClient;\n} {\n\tif (typeof params[0] === 'string') {\n\t\tconst instance = createClient({\n\t\t\turl: params[0],\n\t\t});\n\n\t\treturn construct(instance, params[1]) as any;\n\t}\n\n\tif (isConfig(params[0])) {\n\t\tconst { connection, client, ...drizzleConfig } = params[0] as\n\t\t\t& { connection?: Config; client?: TClient }\n\t\t\t& DrizzleConfig<TSchema>;\n\n\t\tif (client) return construct(client, drizzleConfig) as any;\n\n\t\tconst instance = typeof connection === 'string' ? createClient({ url: connection }) : createClient(connection!);\n\n\t\treturn construct(instance, drizzleConfig) as any;\n\t}\n\n\treturn construct(params[0] as TClient, params[1] as DrizzleConfig<TSchema> | undefined) as any;\n}\n\nexport namespace drizzle {\n\texport function mock<TSchema extends Record<string, unknown> = Record<string, never>>(\n\t\tconfig?: DrizzleConfig<TSchema>,\n\t): LibSQLDatabase<TSchema> & {\n\t\t$client: '$client is not available on drizzle.mock()';\n\t} {\n\t\treturn construct({} as any, config) as any;\n\t}\n}\n"],"mappings":"AAAA,SAAmC,oBAAoB;AACvD,SAA6B,gBAAgB;AAC7C,SAAS,iBAAsC;AAExC,SAAS,WAIZ,QAiBF;AACD,MAAI,OAAO,OAAO,CAAC,MAAM,UAAU;AAClC,UAAM,WAAW,aAAa;AAAA,MAC7B,KAAK,OAAO,CAAC;AAAA,IACd,CAAC;AAED,WAAO,UAAU,UAAU,OAAO,CAAC,CAAC;AAAA,EACrC;AAEA,MAAI,SAAS,OAAO,CAAC,CAAC,GAAG;AACxB,UAAM,EAAE,YAAY,QAAQ,GAAG,cAAc,IAAI,OAAO,CAAC;AAIzD,QAAI,OAAQ,QAAO,UAAU,QAAQ,aAAa;AAElD,UAAM,WAAW,OAAO,eAAe,WAAW,aAAa,EAAE,KAAK,WAAW,CAAC,IAAI,aAAa,UAAW;AAE9G,WAAO,UAAU,UAAU,aAAa;AAAA,EACzC;AAEA,SAAO,UAAU,OAAO,CAAC,GAAc,OAAO,CAAC,CAAuC;AACvF;AAAA,CAEO,CAAUA,aAAV;AACC,WAAS,KACf,QAGC;AACD,WAAO,UAAU,CAAC,GAAU,MAAM;AAAA,EACnC;AANO,EAAAA,SAAS;AAAA,GADA;","names":["drizzle"]}

View File

@@ -0,0 +1,18 @@
/**
* @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 Cherry = createLucideIcon("Cherry", [
["path", { d: "M2 17a5 5 0 0 0 10 0c0-2.76-2.5-5-5-3-2.5-2-5 .24-5 3Z", key: "cvxqlc" }],
["path", { d: "M12 17a5 5 0 0 0 10 0c0-2.76-2.5-5-5-3-2.5-2-5 .24-5 3Z", key: "1ostrc" }],
["path", { d: "M7 14c3.22-2.91 4.29-8.75 5-12 1.66 2.38 4.94 9 5 12", key: "hqx58h" }],
["path", { d: "M22 9c-4.29 0-7.14-2.33-10-7 5.71 0 10 4.67 10 7Z", key: "eykp1o" }]
]);
export { Cherry as default };
//# sourceMappingURL=cherry.js.map

View File

@@ -0,0 +1,6 @@
{
"name": "react-transition-group/TransitionGroup",
"private": true,
"main": "../cjs/TransitionGroup.js",
"module": "../esm/TransitionGroup.js"
}

View File

@@ -0,0 +1 @@
module.exports={A:{A:{"2":"K D E F A B zC"},B:{"2":"0 1 2 3 4 5 6 7 8 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 x y z JB KB LB MB NB OB PB QB RB SB TB UB VB WB XB YB ZB aB I"},C:{"2":"0 1 2 3 4 5 6 7 8 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 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 4C 5C"},D:{"2":"0 1 2 3 4 5 6 7 8 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 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"},E:{"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 fC gC hC iC jC FD TC kC lC mC nC oC GD UC pC qC rC sC HD tC uC vC wC ID"},F:{"2":"0 1 2 3 4 5 6 7 8 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 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 JD KD LD MD PC xC ND QC"},G:{"2":"bC OD yC PD","129":"E QD RD SD 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"},H:{"2":"mD"},I:{"1":"VC J I qD yC rD sD","2":"nD","257":"oD pD"},J:{"1":"A","16":"D"},K:{"1":"H","2":"A B C PC xC QC"},L:{"1":"I"},M:{"1":"OC"},N:{"2":"A B"},O:{"516":"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:{"16":"4D"},R:{"1":"5D"},S:{"2":"6D 7D"}},B:2,C:"HTML Media Capture",D:true};

View File

@@ -0,0 +1,170 @@
import { buildLocalizeFn } from "../../_lib/buildLocalizeFn.mjs";
const eraValues = {
narrow: ["ម.គស", "គស"],
abbreviated: ["មុនគ.ស", "គ.ស"],
wide: ["មុនគ្រិស្តសករាជ", "នៃគ្រិស្តសករាជ"],
};
const quarterValues = {
narrow: ["1", "2", "3", "4"],
abbreviated: ["Q1", "Q2", "Q3", "Q4"],
wide: ["ត្រីមាសទី 1", "ត្រីមាសទី 2", "ត្រីមាសទី 3", "ត្រីមាសទី 4"],
};
const monthValues = {
narrow: [
"ម.ក",
"ក.ម",
"មិ",
"ម.ស",
"ឧ.ស",
"ម.ថ",
"ក.ដ",
"សី",
"កញ",
"តុ",
"វិ",
"ធ",
],
abbreviated: [
"មករា",
"កុម្ភៈ",
"មីនា",
"មេសា",
"ឧសភា",
"មិថុនា",
"កក្កដា",
"សីហា",
"កញ្ញា",
"តុលា",
"វិច្ឆិកា",
"ធ្នូ",
],
wide: [
"មករា",
"កុម្ភៈ",
"មីនា",
"មេសា",
"ឧសភា",
"មិថុនា",
"កក្កដា",
"សីហា",
"កញ្ញា",
"តុលា",
"វិច្ឆិកា",
"ធ្នូ",
],
};
const dayValues = {
narrow: ["អា", "ច", "អ", "ព", "ព្រ", "សុ", "ស"],
short: ["អា", "ច", "អ", "ព", "ព្រ", "សុ", "ស"],
abbreviated: ["អា", "ច", "អ", "ព", "ព្រ", "សុ", "ស"],
wide: ["អាទិត្យ", "ចន្ទ", "អង្គារ", "ពុធ", "ព្រហស្បតិ៍", "សុក្រ", "សៅរ៍"],
};
const dayPeriodValues = {
narrow: {
am: "ព្រឹក",
pm: "ល្ងាច",
midnight: "​ពេលកណ្ដាលអធ្រាត្រ",
noon: "ពេលថ្ងៃត្រង់",
morning: "ពេលព្រឹក",
afternoon: "ពេលរសៀល",
evening: "ពេលល្ងាច",
night: "ពេលយប់",
},
abbreviated: {
am: "ព្រឹក",
pm: "ល្ងាច",
midnight: "​ពេលកណ្ដាលអធ្រាត្រ",
noon: "ពេលថ្ងៃត្រង់",
morning: "ពេលព្រឹក",
afternoon: "ពេលរសៀល",
evening: "ពេលល្ងាច",
night: "ពេលយប់",
},
wide: {
am: "ព្រឹក",
pm: "ល្ងាច",
midnight: "​ពេលកណ្ដាលអធ្រាត្រ",
noon: "ពេលថ្ងៃត្រង់",
morning: "ពេលព្រឹក",
afternoon: "ពេលរសៀល",
evening: "ពេលល្ងាច",
night: "ពេលយប់",
},
};
const formattingDayPeriodValues = {
narrow: {
am: "ព្រឹក",
pm: "ល្ងាច",
midnight: "​ពេលកណ្ដាលអធ្រាត្រ",
noon: "ពេលថ្ងៃត្រង់",
morning: "ពេលព្រឹក",
afternoon: "ពេលរសៀល",
evening: "ពេលល្ងាច",
night: "ពេលយប់",
},
abbreviated: {
am: "ព្រឹក",
pm: "ល្ងាច",
midnight: "​ពេលកណ្ដាលអធ្រាត្រ",
noon: "ពេលថ្ងៃត្រង់",
morning: "ពេលព្រឹក",
afternoon: "ពេលរសៀល",
evening: "ពេលល្ងាច",
night: "ពេលយប់",
},
wide: {
am: "ព្រឹក",
pm: "ល្ងាច",
midnight: "​ពេលកណ្ដាលអធ្រាត្រ",
noon: "ពេលថ្ងៃត្រង់",
morning: "ពេលព្រឹក",
afternoon: "ពេលរសៀល",
evening: "ពេលល្ងាច",
night: "ពេលយប់",
},
};
const ordinalNumber = (dirtyNumber, _) => {
const number = Number(dirtyNumber);
return number.toString();
};
export const localize = {
ordinalNumber,
era: buildLocalizeFn({
values: eraValues,
defaultWidth: "wide",
}),
quarter: buildLocalizeFn({
values: quarterValues,
defaultWidth: "wide",
argumentCallback: (quarter) => quarter - 1,
}),
month: buildLocalizeFn({
values: monthValues,
defaultWidth: "wide",
}),
day: buildLocalizeFn({
values: dayValues,
defaultWidth: "wide",
}),
dayPeriod: buildLocalizeFn({
values: dayPeriodValues,
defaultWidth: "wide",
formattingValues: formattingDayPeriodValues,
defaultFormattingWidth: "wide",
}),
};

View File

@@ -0,0 +1 @@
{"version":3,"file":"infinity.js","sources":["../../../src/icons/infinity.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Infinity\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJNMTIgMTJjLTItMi42Ny00LTQtNi00YTQgNCAwIDEgMCAwIDhjMiAwIDQtMS4zMyA2LTRabTAgMGMyIDIuNjcgNCA0IDYgNGE0IDQgMCAwIDAgMC04Yy0yIDAtNCAxLjMzLTYgNFoiIC8+Cjwvc3ZnPgo=) - https://lucide.dev/icons/infinity\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 Infinity = createLucideIcon('Infinity', [\n [\n 'path',\n {\n d: 'M12 12c-2-2.67-4-4-6-4a4 4 0 1 0 0 8c2 0 4-1.33 6-4Zm0 0c2 2.67 4 4 6 4a4 4 0 0 0 0-8c-2 0-4 1.33-6 4Z',\n key: '1z0uae',\n },\n ],\n]);\n\nexport default Infinity;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAW,iBAAiB,UAAY,CAAA,CAAA,CAAA;AAAA,CAC5C,CAAA,CAAA;AAAA,CAAA,CAAA,CAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACA,CAAA,CAAA,CAAA,CAAA;AAAA,CACE,CAAA,CAAA,CAAA,CAAA,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACH,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,EAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AAAA,CACP,CAAA,CAAA,CAAA,CAAA;AAAA,CACF,CAAA,CAAA;AACF,CAAC,CAAA,CAAA;;"}

View File

@@ -0,0 +1,17 @@
/**
* @license lucide-react v0.441.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/
import createLucideIcon from '../createLucideIcon.js';
const Italic = createLucideIcon("Italic", [
["line", { x1: "19", x2: "10", y1: "4", y2: "4", key: "15jd3p" }],
["line", { x1: "14", x2: "5", y1: "20", y2: "20", key: "bu0au3" }],
["line", { x1: "15", x2: "9", y1: "4", y2: "20", key: "uljnxc" }]
]);
export { Italic as default };
//# sourceMappingURL=italic.js.map

View File

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

View File

@@ -0,0 +1,217 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var picocolors = require('picocolors');
var jsTokens = require('js-tokens');
var helperValidatorIdentifier = require('@babel/helper-validator-identifier');
function isColorSupported() {
return (typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? false : picocolors.isColorSupported
);
}
const compose = (f, g) => v => f(g(v));
function buildDefs(colors) {
return {
keyword: colors.cyan,
capitalized: colors.yellow,
jsxIdentifier: colors.yellow,
punctuator: colors.yellow,
number: colors.magenta,
string: colors.green,
regex: colors.magenta,
comment: colors.gray,
invalid: compose(compose(colors.white, colors.bgRed), colors.bold),
gutter: colors.gray,
marker: compose(colors.red, colors.bold),
message: compose(colors.red, colors.bold),
reset: colors.reset
};
}
const defsOn = buildDefs(picocolors.createColors(true));
const defsOff = buildDefs(picocolors.createColors(false));
function getDefs(enabled) {
return enabled ? defsOn : defsOff;
}
const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]);
const NEWLINE$1 = /\r\n|[\n\r\u2028\u2029]/;
const BRACKET = /^[()[\]{}]$/;
let tokenize;
const JSX_TAG = /^[a-z][\w-]*$/i;
const getTokenType = function (token, offset, text) {
if (token.type === "name") {
const tokenValue = token.value;
if (helperValidatorIdentifier.isKeyword(tokenValue) || helperValidatorIdentifier.isStrictReservedWord(tokenValue, true) || sometimesKeywords.has(tokenValue)) {
return "keyword";
}
if (JSX_TAG.test(tokenValue) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) === "</")) {
return "jsxIdentifier";
}
const firstChar = String.fromCodePoint(tokenValue.codePointAt(0));
if (firstChar !== firstChar.toLowerCase()) {
return "capitalized";
}
}
if (token.type === "punctuator" && BRACKET.test(token.value)) {
return "bracket";
}
if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
return "punctuator";
}
return token.type;
};
tokenize = function* (text) {
let match;
while (match = jsTokens.default.exec(text)) {
const token = jsTokens.matchToToken(match);
yield {
type: getTokenType(token, match.index, text),
value: token.value
};
}
};
function highlight(text) {
if (text === "") return "";
const defs = getDefs(true);
let highlighted = "";
for (const {
type,
value
} of tokenize(text)) {
if (type in defs) {
highlighted += value.split(NEWLINE$1).map(str => defs[type](str)).join("\n");
} else {
highlighted += value;
}
}
return highlighted;
}
let deprecationWarningShown = false;
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
function getMarkerLines(loc, source, opts, startLineBaseZero) {
const startLoc = Object.assign({
column: 0,
line: -1
}, loc.start);
const endLoc = Object.assign({}, startLoc, loc.end);
const {
linesAbove = 2,
linesBelow = 3
} = opts || {};
const startLine = startLoc.line - startLineBaseZero;
const startColumn = startLoc.column;
const endLine = endLoc.line - startLineBaseZero;
const endColumn = endLoc.column;
let start = Math.max(startLine - (linesAbove + 1), 0);
let end = Math.min(source.length, endLine + linesBelow);
if (startLine === -1) {
start = 0;
}
if (endLine === -1) {
end = source.length;
}
const lineDiff = endLine - startLine;
const markerLines = {};
if (lineDiff) {
for (let i = 0; i <= lineDiff; i++) {
const lineNumber = i + startLine;
if (!startColumn) {
markerLines[lineNumber] = true;
} else if (i === 0) {
const sourceLength = source[lineNumber - 1].length;
markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
} else if (i === lineDiff) {
markerLines[lineNumber] = [0, endColumn];
} else {
const sourceLength = source[lineNumber - i].length;
markerLines[lineNumber] = [0, sourceLength];
}
}
} else {
if (startColumn === endColumn) {
if (startColumn) {
markerLines[startLine] = [startColumn, 0];
} else {
markerLines[startLine] = true;
}
} else {
markerLines[startLine] = [startColumn, endColumn - startColumn];
}
}
return {
start,
end,
markerLines
};
}
function codeFrameColumns(rawLines, loc, opts = {}) {
const shouldHighlight = opts.forceColor || isColorSupported() && opts.highlightCode;
const startLineBaseZero = (opts.startLine || 1) - 1;
const defs = getDefs(shouldHighlight);
const lines = rawLines.split(NEWLINE);
const {
start,
end,
markerLines
} = getMarkerLines(loc, lines, opts, startLineBaseZero);
const hasColumns = loc.start && typeof loc.start.column === "number";
const numberMaxWidth = String(end + startLineBaseZero).length;
const highlightedLines = shouldHighlight ? highlight(rawLines) : rawLines;
let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => {
const number = start + 1 + index;
const paddedNumber = ` ${number + startLineBaseZero}`.slice(-numberMaxWidth);
const gutter = ` ${paddedNumber} |`;
const hasMarker = markerLines[number];
const lastMarkerLine = !markerLines[number + 1];
if (hasMarker) {
let markerLine = "";
if (Array.isArray(hasMarker)) {
const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
const numberOfMarkers = hasMarker[1] || 1;
markerLine = ["\n ", defs.gutter(gutter.replace(/\d/g, " ")), " ", markerSpacing, defs.marker("^").repeat(numberOfMarkers)].join("");
if (lastMarkerLine && opts.message) {
markerLine += " " + defs.message(opts.message);
}
}
return [defs.marker(">"), defs.gutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
} else {
return ` ${defs.gutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`;
}
}).join("\n");
if (opts.message && !hasColumns) {
frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
}
if (shouldHighlight) {
return defs.reset(frame);
} else {
return frame;
}
}
function index (rawLines, lineNumber, colNumber, opts = {}) {
if (!deprecationWarningShown) {
deprecationWarningShown = true;
const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
if (process.emitWarning) {
process.emitWarning(message, "DeprecationWarning");
} else {
const deprecationError = new Error(message);
deprecationError.name = "DeprecationWarning";
console.warn(new Error(message));
}
}
colNumber = Math.max(colNumber, 0);
const location = {
start: {
column: colNumber,
line: lineNumber
}
};
return codeFrameColumns(rawLines, location, opts);
}
exports.codeFrameColumns = codeFrameColumns;
exports.default = index;
exports.highlight = highlight;
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,63 @@
"use strict";
exports.eachDayOfInterval = eachDayOfInterval;
var _index = require("./toDate.js");
/**
* The {@link eachDayOfInterval} function options.
*/
/**
* @name eachDayOfInterval
* @category Interval Helpers
* @summary Return the array of dates within the specified time interval.
*
* @description
* Return the array of dates within the specified time interval.
*
* @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 interval - The interval.
* @param options - An object with options.
*
* @returns The array with starts of days from the day of the interval start to the day of the interval end
*
* @example
* // Each day between 6 October 2014 and 10 October 2014:
* const result = eachDayOfInterval({
* start: new Date(2014, 9, 6),
* end: new Date(2014, 9, 10)
* })
* //=> [
* // Mon Oct 06 2014 00:00:00,
* // Tue Oct 07 2014 00:00:00,
* // Wed Oct 08 2014 00:00:00,
* // Thu Oct 09 2014 00:00:00,
* // Fri Oct 10 2014 00:00:00
* // ]
*/
function eachDayOfInterval(interval, options) {
const startDate = (0, _index.toDate)(interval.start);
const endDate = (0, _index.toDate)(interval.end);
let reversed = +startDate > +endDate;
const endTime = reversed ? +startDate : +endDate;
const currentDate = reversed ? endDate : startDate;
currentDate.setHours(0, 0, 0, 0);
let step = options?.step ?? 1;
if (!step) return [];
if (step < 0) {
step = -step;
reversed = !reversed;
}
const dates = [];
while (+currentDate <= endTime) {
dates.push((0, _index.toDate)(currentDate));
currentDate.setDate(currentDate.getDate() + step);
currentDate.setHours(0, 0, 0, 0);
}
return reversed ? dates.reverse() : dates;
}

View File

@@ -0,0 +1,53 @@
import type { ColumnBuilderBaseConfig } from "../../column-builder.cjs";
import type { ColumnBaseConfig } from "../../column.cjs";
import { entityKind } from "../../entity.cjs";
import { SingleStoreColumnBuilderWithAutoIncrement, SingleStoreColumnWithAutoIncrement } from "./common.cjs";
export type SingleStoreBigInt53BuilderInitial<TName extends string> = SingleStoreBigInt53Builder<{
name: TName;
dataType: 'number';
columnType: 'SingleStoreBigInt53';
data: number;
driverParam: number | string;
enumValues: undefined;
}>;
export declare class SingleStoreBigInt53Builder<T extends ColumnBuilderBaseConfig<'number', 'SingleStoreBigInt53'>> extends SingleStoreColumnBuilderWithAutoIncrement<T, {
unsigned: boolean;
}> {
static readonly [entityKind]: string;
constructor(name: T['name'], unsigned?: boolean);
}
export declare class SingleStoreBigInt53<T extends ColumnBaseConfig<'number', 'SingleStoreBigInt53'>> extends SingleStoreColumnWithAutoIncrement<T, {
unsigned: boolean;
}> {
static readonly [entityKind]: string;
getSQLType(): string;
mapFromDriverValue(value: number | string): number;
}
export type SingleStoreBigInt64BuilderInitial<TName extends string> = SingleStoreBigInt64Builder<{
name: TName;
dataType: 'bigint';
columnType: 'SingleStoreBigInt64';
data: bigint;
driverParam: string;
enumValues: undefined;
generated: undefined;
}>;
export declare class SingleStoreBigInt64Builder<T extends ColumnBuilderBaseConfig<'bigint', 'SingleStoreBigInt64'>> extends SingleStoreColumnBuilderWithAutoIncrement<T, {
unsigned: boolean;
}> {
static readonly [entityKind]: string;
constructor(name: T['name'], unsigned?: boolean);
}
export declare class SingleStoreBigInt64<T extends ColumnBaseConfig<'bigint', 'SingleStoreBigInt64'>> extends SingleStoreColumnWithAutoIncrement<T, {
unsigned: boolean;
}> {
static readonly [entityKind]: string;
getSQLType(): string;
mapFromDriverValue(value: string): bigint;
}
export interface SingleStoreBigIntConfig<T extends 'number' | 'bigint' = 'number' | 'bigint'> {
mode: T;
unsigned?: boolean;
}
export declare function bigint<TMode extends SingleStoreBigIntConfig['mode']>(config: SingleStoreBigIntConfig<TMode>): TMode extends 'number' ? SingleStoreBigInt53BuilderInitial<''> : SingleStoreBigInt64BuilderInitial<''>;
export declare function bigint<TName extends string, TMode extends SingleStoreBigIntConfig['mode']>(name: TName, config: SingleStoreBigIntConfig<TMode>): TMode extends 'number' ? SingleStoreBigInt53BuilderInitial<TName> : SingleStoreBigInt64BuilderInitial<TName>;

View File

@@ -0,0 +1,396 @@
var Buffer = require('buffer').Buffer;
function OffsetBuffer() {
this.offset = 0;
this.size = 0;
this.buffers = [];
}
module.exports = OffsetBuffer;
OffsetBuffer.prototype.isEmpty = function isEmpty() {
return this.size === 0;
};
OffsetBuffer.prototype.clone = function clone(size) {
var r = new OffsetBuffer();
r.offset = this.offset;
r.size = size;
r.buffers = this.buffers.slice();
return r;
};
OffsetBuffer.prototype.toChunks = function toChunks() {
if (this.size === 0)
return [];
// We are going to slice it anyway
if (this.offset !== 0) {
this.buffers[0] = this.buffers[0].slice(this.offset);
this.offset = 0;
}
var chunks = [ ];
var off = 0;
for (var i = 0; off <= this.size && i < this.buffers.length; i++) {
var buf = this.buffers[i];
off += buf.length;
// Slice off last buffer
if (off > this.size) {
buf = buf.slice(0, buf.length - (off - this.size));
this.buffers[i] = buf;
}
chunks.push(buf);
}
// If some buffers were skipped - trim length
if (i < this.buffers.length)
this.buffers.length = i;
return chunks;
};
OffsetBuffer.prototype.toString = function toString(enc) {
return this.toChunks().map(function(c) {
return c.toString(enc);
}).join('');
};
OffsetBuffer.prototype.use = function use(buf, off, n) {
this.buffers = [ buf ];
this.offset = off;
this.size = n;
};
OffsetBuffer.prototype.push = function push(data) {
// Ignore empty writes
if (data.length === 0)
return;
this.size += data.length;
this.buffers.push(data);
};
OffsetBuffer.prototype.has = function has(n) {
return this.size >= n;
};
OffsetBuffer.prototype.skip = function skip(n) {
if (this.size === 0)
return;
this.size -= n;
// Fast case, skip bytes in a first buffer
if (this.offset + n < this.buffers[0].length) {
this.offset += n;
return;
}
var left = n - (this.buffers[0].length - this.offset);
this.offset = 0;
for (var shift = 1; left > 0 && shift < this.buffers.length; shift++) {
var buf = this.buffers[shift];
if (buf.length > left) {
this.offset = left;
break;
}
left -= buf.length;
}
this.buffers = this.buffers.slice(shift);
};
OffsetBuffer.prototype.copy = function copy(target, targetOff, off, n) {
if (this.size === 0)
return;
if (off !== 0)
throw new Error('Unsupported offset in .copy()');
var toff = targetOff;
var first = this.buffers[0];
var toCopy = Math.min(n, first.length - this.offset);
first.copy(target, toff, this.offset, this.offset + toCopy);
toff += toCopy;
var left = n - toCopy;
for (var i = 1; left > 0 && i < this.buffers.length; i++) {
var buf = this.buffers[i];
var toCopy = Math.min(left, buf.length);
buf.copy(target, toff, 0, toCopy);
toff += toCopy;
left -= toCopy;
}
};
OffsetBuffer.prototype.take = function take(n) {
if (n === 0)
return new Buffer(0);
this.size -= n;
// Fast cases
var first = this.buffers[0].length - this.offset;
if (first === n) {
var r = this.buffers.shift();
if (this.offset !== 0) {
r = r.slice(this.offset);
this.offset = 0;
}
return r;
} else if (first > n) {
var r = this.buffers[0].slice(this.offset, this.offset + n);
this.offset += n;
return r;
}
// Allocate and fill buffer
var out = new Buffer(n);
var toOff = 0;
var startOff = this.offset;
for (var i = 0; toOff !== n && i < this.buffers.length; i++) {
var buf = this.buffers[i];
var toCopy = Math.min(buf.length - startOff, n - toOff);
buf.copy(out, toOff, startOff, startOff + toCopy);
if (startOff + toCopy < buf.length) {
this.offset = startOff + toCopy;
break;
} else {
toOff += toCopy;
startOff = 0;
}
}
this.buffers = this.buffers.slice(i);
if (this.buffers.length === 0)
this.offset = 0;
return out;
};
OffsetBuffer.prototype.peekUInt8 = function peekUInt8() {
return this.buffers[0][this.offset];
};
OffsetBuffer.prototype.readUInt8 = function readUInt8() {
this.size -= 1;
var first = this.buffers[0];
var r = first[this.offset];
if (++this.offset === first.length) {
this.offset = 0;
this.buffers.shift();
}
return r;
};
OffsetBuffer.prototype.readUInt16LE = function readUInt16LE() {
var first = this.buffers[0];
this.size -= 2;
var r;
var shift;
// Fast case - first buffer has all bytes
if (first.length - this.offset >= 2) {
r = first.readUInt16LE(this.offset);
shift = 0;
this.offset += 2;
// One byte here - one byte there
} else {
r = first[this.offset] | (this.buffers[1][0] << 8);
shift = 1;
this.offset = 1;
}
if (this.offset === this.buffers[shift].length) {
this.offset = 0;
shift++;
}
if (shift !== 0)
this.buffers = this.buffers.slice(shift);
return r;
};
OffsetBuffer.prototype.readUInt24LE = function readUInt24LE() {
var first = this.buffers[0];
var r;
var shift;
var firstHas = first.length - this.offset;
// Fast case - first buffer has all bytes
if (firstHas >= 3) {
r = first.readUInt16LE(this.offset) | (first[this.offset + 2] << 16);
shift = 0;
this.offset += 3;
// First buffer has 2 of 3 bytes
} else if (firstHas >= 2) {
r = first.readUInt16LE(this.offset) | (this.buffers[1][0] << 16);
shift = 1;
this.offset = 1;
// Slow case: First buffer has 1 of 3 bytes
} else {
r = first[this.offset];
this.offset = 0;
this.buffers.shift();
this.size -= 1;
r |= this.readUInt16LE() << 8;
return r;
}
this.size -= 3;
if (this.offset === this.buffers[shift].length) {
this.offset = 0;
shift++;
}
if (shift !== 0)
this.buffers = this.buffers.slice(shift);
return r;
};
OffsetBuffer.prototype.readUInt32LE = function readUInt32LE() {
var first = this.buffers[0];
var r;
var shift;
var firstHas = first.length - this.offset;
// Fast case - first buffer has all bytes
if (firstHas >= 4) {
r = first.readUInt32LE(this.offset);
shift = 0;
this.offset += 4;
// First buffer has 3 of 4 bytes
} else if (firstHas >= 3) {
r = (first.readUInt16LE(this.offset) |
(first[this.offset + 2] << 16)) +
(this.buffers[1][0] * 0x1000000);
shift = 1;
this.offset = 1;
// Slow case: First buffer has 2 of 4 bytes
} else if (firstHas >= 2) {
r = first.readUInt16LE(this.offset);
this.offset = 0;
this.buffers.shift();
this.size -= 2;
r += this.readUInt16LE() * 0x10000;
return r;
// Slow case: First buffer has 1 of 4 bytes
} else {
r = first[this.offset];
this.offset = 0;
this.buffers.shift();
this.size -= 1;
r += this.readUInt24LE() * 0x100;
return r;
}
this.size -= 4;
if (this.offset === this.buffers[shift].length) {
this.offset = 0;
shift++;
}
if (shift !== 0)
this.buffers = this.buffers.slice(shift);
return r;
};
OffsetBuffer.prototype.readUInt16BE = function readUInt16BE() {
var r = this.readUInt16LE();
return ((r & 0xff) << 8) | (r >> 8);
};
OffsetBuffer.prototype.readUInt24BE = function readUInt24BE() {
var r = this.readUInt24LE();
return ((r & 0xff) << 16) | (((r >> 8) & 0xff) << 8) | (r >> 16);
};
OffsetBuffer.prototype.readUInt32BE = function readUInt32BE() {
var r = this.readUInt32LE();
return (((r & 0xff) << 24) |
(((r >>> 8) & 0xff) << 16) |
(((r >>> 16) & 0xff) << 8) |
(r >>> 24)) >>> 0;
};
// Signed number APIs
function signedInt8(num) {
if (num >= 0x80)
return -(0xff ^ num) - 1;
else
return num;
}
OffsetBuffer.prototype.peekInt8 = function peekInt8() {
return signedInt8(this.peekUInt8());
};
OffsetBuffer.prototype.readInt8 = function readInt8() {
return signedInt8(this.readUInt8());
};
function signedInt16(num) {
if (num >= 0x8000)
return -(0xffff ^ num) - 1;
else
return num;
}
OffsetBuffer.prototype.readInt16BE = function readInt16BE() {
return signedInt16(this.readUInt16BE());
};
OffsetBuffer.prototype.readInt16LE = function readInt16LE() {
return signedInt16(this.readUInt16LE());
};
function signedInt24(num) {
if (num >= 0x800000)
return -(0xffffff ^ num) - 1;
else
return num;
}
OffsetBuffer.prototype.readInt24BE = function readInt24BE() {
return signedInt24(this.readUInt24BE());
};
OffsetBuffer.prototype.readInt24LE = function readInt24LE() {
return signedInt24(this.readUInt24LE());
};
function signedInt32(num) {
if (num >= 0x80000000)
return -(0xffffffff ^ num) - 1;
else
return num;
}
OffsetBuffer.prototype.readInt32BE = function readInt32BE() {
return signedInt32(this.readUInt32BE());
};
OffsetBuffer.prototype.readInt32LE = function readInt32LE() {
return signedInt32(this.readUInt32LE());
};

View File

@@ -0,0 +1,377 @@
import {memoize, omit} from 'lodash'
import {DEFAULT_OPTIONS, Options} from './index'
import {
AST,
ASTWithStandaloneName,
hasComment,
hasStandaloneName,
T_ANY,
TArray,
TEnum,
TInterface,
TIntersection,
TNamedInterface,
TUnion,
T_UNKNOWN,
} from './types/AST'
import {log, toSafeString} from './utils'
export function generate(ast: AST, options = DEFAULT_OPTIONS): string {
return (
[
options.bannerComment,
declareNamedTypes(ast, options, ast.standaloneName!),
declareNamedInterfaces(ast, options, ast.standaloneName!),
declareEnums(ast, options),
]
.filter(Boolean)
.join('\n\n') + '\n'
) // trailing newline
}
function declareEnums(ast: AST, options: Options, processed = new Set<AST>()): string {
if (processed.has(ast)) {
return ''
}
processed.add(ast)
let type = ''
switch (ast.type) {
case 'ENUM':
return generateStandaloneEnum(ast, options) + '\n'
case 'ARRAY':
return declareEnums(ast.params, options, processed)
case 'UNION':
case 'INTERSECTION':
return ast.params.reduce((prev, ast) => prev + declareEnums(ast, options, processed), '')
case 'TUPLE':
type = ast.params.reduce((prev, ast) => prev + declareEnums(ast, options, processed), '')
if (ast.spreadParam) {
type += declareEnums(ast.spreadParam, options, processed)
}
return type
case 'INTERFACE':
return getSuperTypesAndParams(ast).reduce((prev, ast) => prev + declareEnums(ast, options, processed), '')
default:
return ''
}
}
function declareNamedInterfaces(ast: AST, options: Options, rootASTName: string, processed = new Set<AST>()): string {
if (processed.has(ast)) {
return ''
}
processed.add(ast)
let type = ''
switch (ast.type) {
case 'ARRAY':
type = declareNamedInterfaces((ast as TArray).params, options, rootASTName, processed)
break
case 'INTERFACE':
type = [
hasStandaloneName(ast) &&
(ast.standaloneName === rootASTName || options.declareExternallyReferenced) &&
generateStandaloneInterface(ast, options),
getSuperTypesAndParams(ast)
.map(ast => declareNamedInterfaces(ast, options, rootASTName, processed))
.filter(Boolean)
.join('\n'),
]
.filter(Boolean)
.join('\n')
break
case 'INTERSECTION':
case 'TUPLE':
case 'UNION':
type = ast.params
.map(_ => declareNamedInterfaces(_, options, rootASTName, processed))
.filter(Boolean)
.join('\n')
if (ast.type === 'TUPLE' && ast.spreadParam) {
type += declareNamedInterfaces(ast.spreadParam, options, rootASTName, processed)
}
break
default:
type = ''
}
return type
}
function declareNamedTypes(ast: AST, options: Options, rootASTName: string, processed = new Set<AST>()): string {
if (processed.has(ast)) {
return ''
}
processed.add(ast)
switch (ast.type) {
case 'ARRAY':
return [
declareNamedTypes(ast.params, options, rootASTName, processed),
hasStandaloneName(ast) ? generateStandaloneType(ast, options) : undefined,
]
.filter(Boolean)
.join('\n')
case 'ENUM':
return ''
case 'INTERFACE':
return getSuperTypesAndParams(ast)
.map(
ast =>
(ast.standaloneName === rootASTName || options.declareExternallyReferenced) &&
declareNamedTypes(ast, options, rootASTName, processed),
)
.filter(Boolean)
.join('\n')
case 'INTERSECTION':
case 'TUPLE':
case 'UNION':
return [
hasStandaloneName(ast) ? generateStandaloneType(ast, options) : undefined,
ast.params
.map(ast => declareNamedTypes(ast, options, rootASTName, processed))
.filter(Boolean)
.join('\n'),
'spreadParam' in ast && ast.spreadParam
? declareNamedTypes(ast.spreadParam, options, rootASTName, processed)
: undefined,
]
.filter(Boolean)
.join('\n')
default:
if (hasStandaloneName(ast)) {
return generateStandaloneType(ast, options)
}
return ''
}
}
function generateTypeUnmemoized(ast: AST, options: Options): string {
const type = generateRawType(ast, options)
if (options.strictIndexSignatures && ast.keyName === '[k: string]') {
return `${type} | undefined`
}
return type
}
export const generateType = memoize(generateTypeUnmemoized)
function generateRawType(ast: AST, options: Options): string {
log('magenta', 'generator', ast)
if (hasStandaloneName(ast)) {
return toSafeString(ast.standaloneName)
}
switch (ast.type) {
case 'ANY':
return 'any'
case 'ARRAY':
return (() => {
const type = generateType(ast.params, options)
return type.endsWith('"') ? '(' + type + ')[]' : type + '[]'
})()
case 'BOOLEAN':
return 'boolean'
case 'INTERFACE':
return generateInterface(ast, options)
case 'INTERSECTION':
return generateSetOperation(ast, options)
case 'LITERAL':
return JSON.stringify(ast.params)
case 'NEVER':
return 'never'
case 'NUMBER':
return 'number'
case 'NULL':
return 'null'
case 'OBJECT':
return 'object'
case 'REFERENCE':
return ast.params
case 'STRING':
return 'string'
case 'TUPLE':
return (() => {
const minItems = ast.minItems
const maxItems = ast.maxItems || -1
let spreadParam = ast.spreadParam
const astParams = [...ast.params]
if (minItems > 0 && minItems > astParams.length && ast.spreadParam === undefined) {
// this is a valid state, and JSONSchema doesn't care about the item type
if (maxItems < 0) {
// no max items and no spread param, so just spread any
spreadParam = options.unknownAny ? T_UNKNOWN : T_ANY
}
}
if (maxItems > astParams.length && ast.spreadParam === undefined) {
// this is a valid state, and JSONSchema doesn't care about the item type
// fill the tuple with any elements
for (let i = astParams.length; i < maxItems; i += 1) {
astParams.push(options.unknownAny ? T_UNKNOWN : T_ANY)
}
}
function addSpreadParam(params: string[]): string[] {
if (spreadParam) {
const spread = '...(' + generateType(spreadParam, options) + ')[]'
params.push(spread)
}
return params
}
function paramsToString(params: string[]): string {
return '[' + params.join(', ') + ']'
}
const paramsList = astParams.map(param => generateType(param, options))
if (paramsList.length > minItems) {
/*
if there are more items than the min, we return a union of tuples instead of
using the optional element operator. This is done because it is more typesafe.
// optional element operator
type A = [string, string?, string?]
const a: A = ['a', undefined, 'c'] // no error
// union of tuples
type B = [string] | [string, string] | [string, string, string]
const b: B = ['a', undefined, 'c'] // TS error
*/
const cumulativeParamsList: string[] = paramsList.slice(0, minItems)
const typesToUnion: string[] = []
if (cumulativeParamsList.length > 0) {
// actually has minItems, so add the initial state
typesToUnion.push(paramsToString(cumulativeParamsList))
} else {
// no minItems means it's acceptable to have an empty tuple type
typesToUnion.push(paramsToString([]))
}
for (let i = minItems; i < paramsList.length; i += 1) {
cumulativeParamsList.push(paramsList[i])
if (i === paramsList.length - 1) {
// only the last item in the union should have the spread parameter
addSpreadParam(cumulativeParamsList)
}
typesToUnion.push(paramsToString(cumulativeParamsList))
}
return typesToUnion.join('|')
}
// no max items so only need to return one type
return paramsToString(addSpreadParam(paramsList))
})()
case 'UNION':
return generateSetOperation(ast, options)
case 'UNKNOWN':
return 'unknown'
case 'CUSTOM_TYPE':
return ast.params
}
}
/**
* Generate a Union or Intersection
*/
function generateSetOperation(ast: TIntersection | TUnion, options: Options): string {
const members = (ast as TUnion).params.map(_ => generateType(_, options))
const separator = ast.type === 'UNION' ? '|' : '&'
return members.length === 1 ? members[0] : '(' + members.join(' ' + separator + ' ') + ')'
}
function generateInterface(ast: TInterface, options: Options): string {
return (
`{` +
'\n' +
ast.params
.filter(_ => !_.isPatternProperty && !_.isUnreachableDefinition)
.map(
({isRequired, keyName, ast}) =>
[isRequired, keyName, ast, generateType(ast, options)] as [boolean, string, AST, string],
)
.map(
([isRequired, keyName, ast, type]) =>
(hasComment(ast) && !ast.standaloneName ? generateComment(ast.comment, ast.deprecated) + '\n' : '') +
escapeKeyName(keyName) +
(isRequired ? '' : '?') +
': ' +
type,
)
.join('\n') +
'\n' +
'}'
)
}
function generateComment(comment?: string, deprecated?: boolean): string {
const commentLines = ['/**']
if (deprecated) {
commentLines.push(' * @deprecated')
}
if (typeof comment !== 'undefined') {
commentLines.push(...comment.split('\n').map(_ => ' * ' + _))
}
commentLines.push(' */')
return commentLines.join('\n')
}
function generateStandaloneEnum(ast: TEnum, options: Options): string {
return (
(hasComment(ast) ? generateComment(ast.comment, ast.deprecated) + '\n' : '') +
'export ' +
(options.enableConstEnums ? 'const ' : '') +
`enum ${toSafeString(ast.standaloneName)} {` +
'\n' +
ast.params.map(({ast, keyName}) => keyName + ' = ' + generateType(ast, options)).join(',\n') +
'\n' +
'}'
)
}
function generateStandaloneInterface(ast: TNamedInterface, options: Options): string {
return (
(hasComment(ast) ? generateComment(ast.comment, ast.deprecated) + '\n' : '') +
`export interface ${toSafeString(ast.standaloneName)} ` +
(ast.superTypes.length > 0
? `extends ${ast.superTypes.map(superType => toSafeString(superType.standaloneName)).join(', ')} `
: '') +
generateInterface(ast, options)
)
}
function generateStandaloneType(ast: ASTWithStandaloneName, options: Options): string {
return (
(hasComment(ast) ? generateComment(ast.comment) + '\n' : '') +
`export type ${toSafeString(ast.standaloneName)} = ${generateType(
omit<AST>(ast, 'standaloneName') as AST /* TODO */,
options,
)}`
)
}
function escapeKeyName(keyName: string): string {
if (keyName.length && /[A-Za-z_$]/.test(keyName.charAt(0)) && /^[\w$]+$/.test(keyName)) {
return keyName
}
if (keyName === '[k: string]') {
return keyName
}
return JSON.stringify(keyName)
}
function getSuperTypesAndParams(ast: TInterface): AST[] {
return ast.params.map(param => param.ast).concat(ast.superTypes)
}

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 './axis-3d.js';
//# sourceMappingURL=axis-3-d.js.map

View File

@@ -0,0 +1,761 @@
# Immutable collections for JavaScript
[![Build Status](https://github.com/immutable-js/immutable-js/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/immutable-js/immutable-js/actions/workflows/ci.yml?query=branch%3Amain) [Chat on slack](https://immutable-js.slack.com)
[Read the docs](https://immutable-js.com/docs/) and eat your vegetables.
Docs are automatically generated from [README.md][] and [immutable.d.ts][].
Please contribute! Also, don't miss the [wiki][] which contains articles on
additional specific topics. Can't find something? Open an [issue][].
**Table of contents:**
- [Introduction](#introduction)
- [Getting started](#getting-started)
- [The case for Immutability](#the-case-for-immutability)
- [JavaScript-first API](#javascript-first-api)
- [Nested Structures](#nested-structures)
- [Equality treats Collections as Values](#equality-treats-collections-as-values)
- [Batching Mutations](#batching-mutations)
- [Lazy Seq](#lazy-seq)
- [Additional Tools and Resources](#additional-tools-and-resources)
- [Contributing](#contributing)
## Introduction
[Immutable][] data cannot be changed once created, leading to much simpler
application development, no defensive copying, and enabling advanced memoization
and change detection techniques with simple logic. [Persistent][] data presents
a mutative API which does not update the data in-place, but instead always
yields new updated data.
Immutable.js provides many Persistent Immutable data structures including:
`List`, `Stack`, `Map`, `OrderedMap`, `Set`, `OrderedSet` and `Record`.
These data structures are highly efficient on modern JavaScript VMs by using
structural sharing via [hash maps tries][] and [vector tries][] as popularized
by Clojure and Scala, minimizing the need to copy or cache data.
Immutable.js also provides a lazy `Seq`, allowing efficient
chaining of collection methods like `map` and `filter` without creating
intermediate representations. Create some `Seq` with `Range` and `Repeat`.
Want to hear more? Watch the presentation about Immutable.js:
[![Immutable Data and React](website/public/Immutable-Data-and-React-YouTube.png)](https://youtu.be/I7IdS-PbEgI)
[README.md]: https://github.com/immutable-js/immutable-js/blob/main/README.md
[immutable.d.ts]: https://github.com/immutable-js/immutable-js/blob/main/type-definitions/immutable.d.ts
[wiki]: https://github.com/immutable-js/immutable-js/wiki
[issue]: https://github.com/immutable-js/immutable-js/issues
[Persistent]: https://en.wikipedia.org/wiki/Persistent_data_structure
[Immutable]: https://en.wikipedia.org/wiki/Immutable_object
[hash maps tries]: https://en.wikipedia.org/wiki/Hash_array_mapped_trie
[vector tries]: https://hypirion.com/musings/understanding-persistent-vector-pt-1
## Getting started
Install `immutable` using npm.
```shell
# using npm
npm install immutable
# using Yarn
yarn add immutable
# using pnpm
pnpm add immutable
# using Bun
bun add immutable
```
Then require it into any module.
<!-- runkit:activate -->
```js
const { Map } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = map1.set('b', 50);
map1.get('b') + ' vs. ' + map2.get('b'); // 2 vs. 50
```
### Browser
Immutable.js has no dependencies, which makes it predictable to include in a Browser.
It's highly recommended to use a module bundler like [webpack](https://webpack.github.io/),
[rollup](https://rollupjs.org/), or
[browserify](https://browserify.org/). The `immutable` npm module works
without any additional consideration. All examples throughout the documentation
will assume use of this kind of tool.
Alternatively, Immutable.js may be directly included as a script tag. Download
or link to a CDN such as [CDNJS](https://cdnjs.com/libraries/immutable)
or [jsDelivr](https://www.jsdelivr.com/package/npm/immutable).
Use a script tag to directly add `Immutable` to the global scope:
```html
<script src="immutable.min.js"></script>
<script>
var map1 = Immutable.Map({ a: 1, b: 2, c: 3 });
var map2 = map1.set('b', 50);
map1.get('b'); // 2
map2.get('b'); // 50
</script>
```
Or use an AMD-style loader (such as [RequireJS](https://requirejs.org/)):
```js
require(['./immutable.min.js'], function (Immutable) {
var map1 = Immutable.Map({ a: 1, b: 2, c: 3 });
var map2 = map1.set('b', 50);
map1.get('b'); // 2
map2.get('b'); // 50
});
```
### Flow & TypeScript
Use these Immutable collections and sequences as you would use native
collections in your [Flowtype](https://flowtype.org/) or [TypeScript](https://typescriptlang.org) programs while still taking
advantage of type generics, error detection, and auto-complete in your IDE.
Installing `immutable` via npm brings with it type definitions for Flow (v0.55.0 or higher)
and TypeScript (v2.1.0 or higher), so you shouldn't need to do anything at all!
#### Using TypeScript with Immutable.js v4
Immutable.js type definitions embrace ES2015. While Immutable.js itself supports
legacy browsers and environments, its type definitions require TypeScript's 2015
lib. Include either `"target": "es2015"` or `"lib": "es2015"` in your
`tsconfig.json`, or provide `--target es2015` or `--lib es2015` to the
`tsc` command.
<!-- runkit:activate -->
```js
const { Map } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = map1.set('b', 50);
map1.get('b') + ' vs. ' + map2.get('b'); // 2 vs. 50
```
#### Using TypeScript with Immutable.js v3 and earlier:
Previous versions of Immutable.js include a reference file which you can include
via relative path to the type definitions at the top of your file.
```js
///<reference path='./node_modules/immutable/dist/immutable.d.ts'/>
import Immutable from 'immutable';
var map1: Immutable.Map<string, number>;
map1 = Immutable.Map({ a: 1, b: 2, c: 3 });
var map2 = map1.set('b', 50);
map1.get('b'); // 2
map2.get('b'); // 50
```
## The case for Immutability
Much of what makes application development difficult is tracking mutation and
maintaining state. Developing with immutable data encourages you to think
differently about how data flows through your application.
Subscribing to data events throughout your application creates a huge overhead of
book-keeping which can hurt performance, sometimes dramatically, and creates
opportunities for areas of your application to get out of sync with each other
due to easy to make programmer error. Since immutable data never changes,
subscribing to changes throughout the model is a dead-end and new data can only
ever be passed from above.
This model of data flow aligns well with the architecture of [React][]
and especially well with an application designed using the ideas of [Flux][].
When data is passed from above rather than being subscribed to, and you're only
interested in doing work when something has changed, you can use equality.
Immutable collections should be treated as _values_ rather than _objects_. While
objects represent some thing which could change over time, a value represents
the state of that thing at a particular instance of time. This principle is most
important to understanding the appropriate use of immutable data. In order to
treat Immutable.js collections as values, it's important to use the
`Immutable.is()` function or `.equals()` method to determine _value equality_
instead of the `===` operator which determines object _reference identity_.
<!-- runkit:activate -->
```js
const { Map } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = Map({ a: 1, b: 2, c: 3 });
map1.equals(map2); // true
map1 === map2; // false
```
Note: As a performance optimization Immutable.js attempts to return the existing
collection when an operation would result in an identical collection, allowing
for using `===` reference equality to determine if something definitely has not
changed. This can be extremely useful when used within a memoization function
which would prefer to re-run the function if a deeper equality check could
potentially be more costly. The `===` equality check is also used internally by
`Immutable.is` and `.equals()` as a performance optimization.
<!-- runkit:activate -->
```js
const { Map } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = map1.set('b', 2); // Set to same value
map1 === map2; // true
```
If an object is immutable, it can be "copied" simply by making another reference
to it instead of copying the entire object. Because a reference is much smaller
than the object itself, this results in memory savings and a potential boost in
execution speed for programs which rely on copies (such as an undo-stack).
<!-- runkit:activate -->
```js
const { Map } = require('immutable');
const map = Map({ a: 1, b: 2, c: 3 });
const mapCopy = map; // Look, "copies" are free!
```
[React]: https://reactjs.org/
[Flux]: https://facebook.github.io/flux/docs/in-depth-overview/
## JavaScript-first API
While Immutable.js is inspired by Clojure, Scala, Haskell and other functional
programming environments, it's designed to bring these powerful concepts to
JavaScript, and therefore has an Object-Oriented API that closely mirrors that
of [ES2015][] [Array][], [Map][], and [Set][].
[es2015]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_6_support_in_Mozilla
[array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
[map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
[set]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
The difference for the immutable collections is that methods which would mutate
the collection, like `push`, `set`, `unshift` or `splice`, instead return a new
immutable collection. Methods which return new arrays, like `slice` or `concat`,
instead return new immutable collections.
<!-- runkit:activate -->
```js
const { List } = require('immutable');
const list1 = List([1, 2]);
const list2 = list1.push(3, 4, 5);
const list3 = list2.unshift(0);
const list4 = list1.concat(list2, list3);
assert.equal(list1.size, 2);
assert.equal(list2.size, 5);
assert.equal(list3.size, 6);
assert.equal(list4.size, 13);
assert.equal(list4.get(0), 1);
```
Almost all of the methods on [Array][] will be found in similar form on
`Immutable.List`, those of [Map][] found on `Immutable.Map`, and those of [Set][]
found on `Immutable.Set`, including collection operations like `forEach()`
and `map()`.
<!-- runkit:activate -->
```js
const { Map } = require('immutable');
const alpha = Map({ a: 1, b: 2, c: 3, d: 4 });
alpha.map((v, k) => k.toUpperCase()).join();
// 'A,B,C,D'
```
### Convert from raw JavaScript objects and arrays.
Designed to inter-operate with your existing JavaScript, Immutable.js
accepts plain JavaScript Arrays and Objects anywhere a method expects a
`Collection`.
<!-- runkit:activate -->
```js
const { Map, List } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3, d: 4 });
const map2 = Map({ c: 10, a: 20, t: 30 });
const obj = { d: 100, o: 200, g: 300 };
const map3 = map1.merge(map2, obj);
// Map { a: 20, b: 2, c: 10, d: 100, t: 30, o: 200, g: 300 }
const list1 = List([1, 2, 3]);
const list2 = List([4, 5, 6]);
const array = [7, 8, 9];
const list3 = list1.concat(list2, array);
// List [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
```
This is possible because Immutable.js can treat any JavaScript Array or Object
as a Collection. You can take advantage of this in order to get sophisticated
collection methods on JavaScript Objects, which otherwise have a very sparse
native API. Because Seq evaluates lazily and does not cache intermediate
results, these operations can be extremely efficient.
<!-- runkit:activate -->
```js
const { Seq } = require('immutable');
const myObject = { a: 1, b: 2, c: 3 };
Seq(myObject)
.map(x => x * x)
.toObject();
// { a: 1, b: 4, c: 9 }
```
Keep in mind, when using JS objects to construct Immutable Maps, that
JavaScript Object properties are always strings, even if written in a quote-less
shorthand, while Immutable Maps accept keys of any type.
<!-- runkit:activate -->
```js
const { fromJS } = require('immutable');
const obj = { 1: 'one' };
console.log(Object.keys(obj)); // [ "1" ]
console.log(obj['1'], obj[1]); // "one", "one"
const map = fromJS(obj);
console.log(map.get('1'), map.get(1)); // "one", undefined
```
Property access for JavaScript Objects first converts the key to a string, but
since Immutable Map keys can be of any type the argument to `get()` is
not altered.
### Converts back to raw JavaScript objects.
All Immutable.js Collections can be converted to plain JavaScript Arrays and
Objects shallowly with `toArray()` and `toObject()` or deeply with `toJS()`.
All Immutable Collections also implement `toJSON()` allowing them to be passed
to `JSON.stringify` directly. They also respect the custom `toJSON()` methods of
nested objects.
<!-- runkit:activate -->
```js
const { Map, List } = require('immutable');
const deep = Map({ a: 1, b: 2, c: List([3, 4, 5]) });
console.log(deep.toObject()); // { a: 1, b: 2, c: List [ 3, 4, 5 ] }
console.log(deep.toArray()); // [ 1, 2, List [ 3, 4, 5 ] ]
console.log(deep.toJS()); // { a: 1, b: 2, c: [ 3, 4, 5 ] }
JSON.stringify(deep); // '{"a":1,"b":2,"c":[3,4,5]}'
```
### Embraces ES2015
Immutable.js supports all JavaScript environments, including legacy
browsers (even IE11). However it also takes advantage of features added to
JavaScript in [ES2015][], the latest standard version of JavaScript, including
[Iterators][], [Arrow Functions][], [Classes][], and [Modules][]. It's inspired
by the native [Map][] and [Set][] collections added to ES2015.
All examples in the Documentation are presented in ES2015. To run in all
browsers, they need to be translated to ES5.
```js
// ES2015
const mapped = foo.map(x => x * x);
// ES5
var mapped = foo.map(function (x) {
return x * x;
});
```
All Immutable.js collections are [Iterable][iterators], which allows them to be
used anywhere an Iterable is expected, such as when spreading into an Array.
<!-- runkit:activate -->
```js
const { List } = require('immutable');
const aList = List([1, 2, 3]);
const anArray = [0, ...aList, 4, 5]; // [ 0, 1, 2, 3, 4, 5 ]
```
Note: A Collection is always iterated in the same order, however that order may
not always be well defined, as is the case for the `Map` and `Set`.
[Iterators]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol
[Arrow Functions]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
[Classes]: https://wiki.ecmascript.org/doku.php?id=strawman:maximally_minimal_classes
[Modules]: https://www.2ality.com/2014/09/es6-modules-final.html
## Nested Structures
The collections in Immutable.js are intended to be nested, allowing for deep
trees of data, similar to JSON.
<!-- runkit:activate -->
```js
const { fromJS } = require('immutable');
const nested = fromJS({ a: { b: { c: [3, 4, 5] } } });
// Map { a: Map { b: Map { c: List [ 3, 4, 5 ] } } }
```
A few power-tools allow for reading and operating on nested data. The
most useful are `mergeDeep`, `getIn`, `setIn`, and `updateIn`, found on `List`,
`Map` and `OrderedMap`.
<!-- runkit:activate -->
```js
const { fromJS } = require('immutable');
const nested = fromJS({ a: { b: { c: [3, 4, 5] } } });
const nested2 = nested.mergeDeep({ a: { b: { d: 6 } } });
// Map { a: Map { b: Map { c: List [ 3, 4, 5 ], d: 6 } } }
console.log(nested2.getIn(['a', 'b', 'd'])); // 6
const nested3 = nested2.updateIn(['a', 'b', 'd'], value => value + 1);
console.log(nested3);
// Map { a: Map { b: Map { c: List [ 3, 4, 5 ], d: 7 } } }
const nested4 = nested3.updateIn(['a', 'b', 'c'], list => list.push(6));
// Map { a: Map { b: Map { c: List [ 3, 4, 5, 6 ], d: 7 } } }
```
## Equality treats Collections as Values
Immutable.js collections are treated as pure data _values_. Two immutable
collections are considered _value equal_ (via `.equals()` or `is()`) if they
represent the same collection of values. This differs from JavaScript's typical
_reference equal_ (via `===` or `==`) for Objects and Arrays which only
determines if two variables represent references to the same object instance.
Consider the example below where two identical `Map` instances are not
_reference equal_ but are _value equal_.
<!-- runkit:activate -->
```js
// First consider:
const obj1 = { a: 1, b: 2, c: 3 };
const obj2 = { a: 1, b: 2, c: 3 };
obj1 !== obj2; // two different instances are always not equal with ===
const { Map, is } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = Map({ a: 1, b: 2, c: 3 });
map1 !== map2; // two different instances are not reference-equal
map1.equals(map2); // but are value-equal if they have the same values
is(map1, map2); // alternatively can use the is() function
```
Value equality allows Immutable.js collections to be used as keys in Maps or
values in Sets, and retrieved with different but equivalent collections:
<!-- runkit:activate -->
```js
const { Map, Set } = require('immutable');
const map1 = Map({ a: 1, b: 2, c: 3 });
const map2 = Map({ a: 1, b: 2, c: 3 });
const set = Set().add(map1);
set.has(map2); // true because these are value-equal
```
Note: `is()` uses the same measure of equality as [Object.is][] for scalar
strings and numbers, but uses value equality for Immutable collections,
determining if both are immutable and all keys and values are equal
using the same measure of equality.
[object.is]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
#### Performance tradeoffs
While value equality is useful in many circumstances, it has different
performance characteristics than reference equality. Understanding these
tradeoffs may help you decide which to use in each case, especially when used
to memoize some operation.
When comparing two collections, value equality may require considering every
item in each collection, on an `O(N)` time complexity. For large collections of
values, this could become a costly operation. Though if the two are not equal
and hardly similar, the inequality is determined very quickly. In contrast, when
comparing two collections with reference equality, only the initial references
to memory need to be compared which is not based on the size of the collections,
which has an `O(1)` time complexity. Checking reference equality is always very
fast, however just because two collections are not reference-equal does not rule
out the possibility that they may be value-equal.
#### Return self on no-op optimization
When possible, Immutable.js avoids creating new objects for updates where no
change in _value_ occurred, to allow for efficient _reference equality_ checking
to quickly determine if no change occurred.
<!-- runkit:activate -->
```js
const { Map } = require('immutable');
const originalMap = Map({ a: 1, b: 2, c: 3 });
const updatedMap = originalMap.set('b', 2);
updatedMap === originalMap; // No-op .set() returned the original reference.
```
However updates which do result in a change will return a new reference. Each
of these operations occur independently, so two similar updates will not return
the same reference:
<!-- runkit:activate -->
```js
const { Map } = require('immutable');
const originalMap = Map({ a: 1, b: 2, c: 3 });
const updatedMap = originalMap.set('b', 1000);
// New instance, leaving the original immutable.
updatedMap !== originalMap;
const anotherUpdatedMap = originalMap.set('b', 1000);
// Despite both the results of the same operation, each created a new reference.
anotherUpdatedMap !== updatedMap;
// However the two are value equal.
anotherUpdatedMap.equals(updatedMap);
```
## Batching Mutations
> If a tree falls in the woods, does it make a sound?
>
> If a pure function mutates some local data in order to produce an immutable
> return value, is that ok?
>
> — Rich Hickey, Clojure
Applying a mutation to create a new immutable object results in some overhead,
which can add up to a minor performance penalty. If you need to apply a series
of mutations locally before returning, Immutable.js gives you the ability to
create a temporary mutable (transient) copy of a collection and apply a batch of
mutations in a performant manner by using `withMutations`. In fact, this is
exactly how Immutable.js applies complex mutations itself.
As an example, building `list2` results in the creation of 1, not 3, new
immutable Lists.
<!-- runkit:activate -->
```js
const { List } = require('immutable');
const list1 = List([1, 2, 3]);
const list2 = list1.withMutations(function (list) {
list.push(4).push(5).push(6);
});
assert.equal(list1.size, 3);
assert.equal(list2.size, 6);
```
Note: Immutable.js also provides `asMutable` and `asImmutable`, but only
encourages their use when `withMutations` will not suffice. Use caution to not
return a mutable copy, which could result in undesired behavior.
_Important!_: Only a select few methods can be used in `withMutations` including
`set`, `push` and `pop`. These methods can be applied directly against a
persistent data-structure where other methods like `map`, `filter`, `sort`,
and `splice` will always return new immutable data-structures and never mutate
a mutable collection.
## Lazy Seq
`Seq` describes a lazy operation, allowing them to efficiently chain
use of all the higher-order collection methods (such as `map` and `filter`)
by not creating intermediate collections.
**Seq is immutable** — Once a Seq is created, it cannot be
changed, appended to, rearranged or otherwise modified. Instead, any mutative
method called on a `Seq` will return a new `Seq`.
**Seq is lazy** — `Seq` does as little work as necessary to respond to any
method call. Values are often created during iteration, including implicit
iteration when reducing or converting to a concrete data structure such as
a `List` or JavaScript `Array`.
For example, the following performs no work, because the resulting
`Seq`'s values are never iterated:
```js
const { Seq } = require('immutable');
const oddSquares = Seq([1, 2, 3, 4, 5, 6, 7, 8])
.filter(x => x % 2 !== 0)
.map(x => x * x);
```
Once the `Seq` is used, it performs only the work necessary. In this
example, no intermediate arrays are ever created, filter is called three
times, and map is only called once:
```js
oddSquares.get(1); // 9
```
Any collection can be converted to a lazy Seq with `Seq()`.
<!-- runkit:activate -->
```js
const { Map, Seq } = require('immutable');
const map = Map({ a: 1, b: 2, c: 3 });
const lazySeq = Seq(map);
```
`Seq` allows for the efficient chaining of operations, allowing for the
expression of logic that can otherwise be very tedious:
```js
lazySeq
.flip()
.map(key => key.toUpperCase())
.flip();
// Seq { A: 1, B: 2, C: 3 }
```
As well as expressing logic that would otherwise seem memory or time
limited, for example `Range` is a special kind of Lazy sequence.
<!-- runkit:activate -->
```js
const { Range } = require('immutable');
Range(1, Infinity)
.skip(1000)
.map(n => -n)
.filter(n => n % 2 === 0)
.take(2)
.reduce((r, n) => r * n, 1);
// 1006008
```
## Comparison of filter(), groupBy(), and partition()
The `filter()`, `groupBy()`, and `partition()` methods are similar in that they
all divide a collection into parts based on applying a function to each element.
All three call the predicate or grouping function once for each item in the
input collection. All three return zero or more collections of the same type as
their input. The returned collections are always distinct from the input
(according to `===`), even if the contents are identical.
Of these methods, `filter()` is the only one that is lazy and the only one which
discards items from the input collection. It is the simplest to use, and the
fact that it returns exactly one collection makes it easy to combine with other
methods to form a pipeline of operations.
The `partition()` method is similar to an eager version of `filter()`, but it
returns two collections; the first contains the items that would have been
discarded by `filter()`, and the second contains the items that would have been
kept. It always returns an array of exactly two collections, which can make it
easier to use than `groupBy()`. Compared to making two separate calls to
`filter()`, `partition()` makes half as many calls it the predicate passed to
it.
The `groupBy()` method is a more generalized version of `partition()` that can
group by an arbitrary function rather than just a predicate. It returns a map
with zero or more entries, where the keys are the values returned by the
grouping function, and the values are nonempty collections of the corresponding
arguments. Although `groupBy()` is more powerful than `partition()`, it can be
harder to use because it is not always possible predict in advance how many
entries the returned map will have and what their keys will be.
| Summary | `filter` | `partition` | `groupBy` |
|:------------------------------|:---------|:------------|:---------------|
| ease of use | easiest | moderate | hardest |
| generality | least | moderate | most |
| laziness | lazy | eager | eager |
| # of returned sub-collections | 1 | 2 | 0 or more |
| sub-collections may be empty | yes | yes | no |
| can discard items | yes | no | no |
| wrapping container | none | array | Map/OrderedMap |
## Additional Tools and Resources
- [Atom-store](https://github.com/jameshopkins/atom-store/)
- A Clojure-inspired atom implementation in Javascript with configurability
for external persistance.
- [Chai Immutable](https://github.com/astorije/chai-immutable)
- If you are using the [Chai Assertion Library](https://chaijs.com/), this
provides a set of assertions to use against Immutable.js collections.
- [Fantasy-land](https://github.com/fantasyland/fantasy-land)
- Specification for interoperability of common algebraic structures in JavaScript.
- [Immutagen](https://github.com/pelotom/immutagen)
- A library for simulating immutable generators in JavaScript.
- [Immutable-cursor](https://github.com/redbadger/immutable-cursor)
- Immutable cursors incorporating the Immutable.js interface over
Clojure-inspired atom.
- [Immutable-ext](https://github.com/DrBoolean/immutable-ext)
- Fantasyland extensions for immutablejs
- [Immutable-js-tools](https://github.com/madeinfree/immutable-js-tools)
- Util tools for immutable.js
- [Immutable-Redux](https://github.com/gajus/redux-immutable)
- redux-immutable is used to create an equivalent function of Redux
combineReducers that works with Immutable.js state.
- [Immutable-Treeutils](https://github.com/lukasbuenger/immutable-treeutils)
- Functional tree traversal helpers for ImmutableJS data structures.
- [Irecord](https://github.com/ericelliott/irecord)
- An immutable store that exposes an RxJS observable. Great for React.
- [Mudash](https://github.com/brianneisler/mudash)
- Lodash wrapper providing Immutable.JS support.
- [React-Immutable-PropTypes](https://github.com/HurricaneJames/react-immutable-proptypes)
- PropType validators that work with Immutable.js.
- [Redux-Immutablejs](https://github.com/indexiatech/redux-immutablejs)
- Redux Immutable facilities.
- [Rxstate](https://github.com/yamalight/rxstate)
- Simple opinionated state management library based on RxJS and Immutable.js.
- [Transit-Immutable-js](https://github.com/glenjamin/transit-immutable-js)
- Transit serialisation for Immutable.js.
- See also: [Transit-js](https://github.com/cognitect/transit-js)
Have an additional tool designed to work with Immutable.js?
Submit a PR to add it to this list in alphabetical order.
## Contributing
Use [Github issues](https://github.com/immutable-js/immutable-js/issues) for requests.
We actively welcome pull requests, learn how to [contribute](https://github.com/immutable-js/immutable-js/blob/main/.github/CONTRIBUTING.md).
Immutable.js is maintained within the [Contributor Covenant's Code of Conduct](https://www.contributor-covenant.org/version/2/0/code_of_conduct/).
### Changelog
Changes are tracked as [Github releases](https://github.com/immutable-js/immutable-js/releases).
### License
Immutable.js is [MIT-licensed](./LICENSE).
### Thanks
[Phil Bagwell](https://www.youtube.com/watch?v=K2NYwP90bNs), for his inspiration
and research in persistent data structures.
[Hugh Jackson](https://github.com/hughfdjackson/), for providing the npm package
name. If you're looking for his unsupported package, see [this repository](https://github.com/hughfdjackson/immutable).

View File

@@ -0,0 +1,331 @@
# lru-cache
A cache object that deletes the least-recently-used items.
Specify a max number of the most recently used items that you
want to keep, and this cache will keep that many of the most
recently accessed items.
This is not primarily a TTL cache, and does not make strong TTL
guarantees. There is no preemptive pruning of expired items by
default, but you _may_ set a TTL on the cache or on a single
`set`. If you do so, it will treat expired items as missing, and
delete them when fetched. If you are more interested in TTL
caching than LRU caching, check out
[@isaacs/ttlcache](http://npm.im/@isaacs/ttlcache).
As of version 7, this is one of the most performant LRU
implementations available in JavaScript, and supports a wide
diversity of use cases. However, note that using some of the
features will necessarily impact performance, by causing the
cache to have to do more work. See the "Performance" section
below.
## Installation
```bash
npm install lru-cache --save
```
## Usage
```js
// hybrid module, either works
import { LRUCache } from 'lru-cache'
// or:
const { LRUCache } = require('lru-cache')
// or in minified form for web browsers:
import { LRUCache } from 'http://unpkg.com/lru-cache@9/dist/mjs/index.min.mjs'
// At least one of 'max', 'ttl', or 'maxSize' is required, to prevent
// unsafe unbounded storage.
//
// In most cases, it's best to specify a max for performance, so all
// the required memory allocation is done up-front.
//
// All the other options are optional, see the sections below for
// documentation on what each one does. Most of them can be
// overridden for specific items in get()/set()
const options = {
max: 500,
// for use with tracking overall storage size
maxSize: 5000,
sizeCalculation: (value, key) => {
return 1
},
// for use when you need to clean up something when objects
// are evicted from the cache
dispose: (value, key) => {
freeFromMemoryOrWhatever(value)
},
// how long to live in ms
ttl: 1000 * 60 * 5,
// return stale items before removing from cache?
allowStale: false,
updateAgeOnGet: false,
updateAgeOnHas: false,
// async method to use for cache.fetch(), for
// stale-while-revalidate type of behavior
fetchMethod: async (
key,
staleValue,
{ options, signal, context }
) => {},
}
const cache = new LRUCache(options)
cache.set('key', 'value')
cache.get('key') // "value"
// non-string keys ARE fully supported
// but note that it must be THE SAME object, not
// just a JSON-equivalent object.
var someObject = { a: 1 }
cache.set(someObject, 'a value')
// Object keys are not toString()-ed
cache.set('[object Object]', 'a different value')
assert.equal(cache.get(someObject), 'a value')
// A similar object with same keys/values won't work,
// because it's a different object identity
assert.equal(cache.get({ a: 1 }), undefined)
cache.clear() // empty the cache
```
If you put more stuff in the cache, then less recently used items
will fall out. That's what an LRU cache is.
For full description of the API and all options, please see [the
LRUCache typedocs](https://isaacs.github.io/node-lru-cache/)
## Storage Bounds Safety
This implementation aims to be as flexible as possible, within
the limits of safe memory consumption and optimal performance.
At initial object creation, storage is allocated for `max` items.
If `max` is set to zero, then some performance is lost, and item
count is unbounded. Either `maxSize` or `ttl` _must_ be set if
`max` is not specified.
If `maxSize` is set, then this creates a safe limit on the
maximum storage consumed, but without the performance benefits of
pre-allocation. When `maxSize` is set, every item _must_ provide
a size, either via the `sizeCalculation` method provided to the
constructor, or via a `size` or `sizeCalculation` option provided
to `cache.set()`. The size of every item _must_ be a positive
integer.
If neither `max` nor `maxSize` are set, then `ttl` tracking must
be enabled. Note that, even when tracking item `ttl`, items are
_not_ preemptively deleted when they become stale, unless
`ttlAutopurge` is enabled. Instead, they are only purged the
next time the key is requested. Thus, if `ttlAutopurge`, `max`,
and `maxSize` are all not set, then the cache will potentially
grow unbounded.
In this case, a warning is printed to standard error. Future
versions may require the use of `ttlAutopurge` if `max` and
`maxSize` are not specified.
If you truly wish to use a cache that is bound _only_ by TTL
expiration, consider using a `Map` object, and calling
`setTimeout` to delete entries when they expire. It will perform
much better than an LRU cache.
Here is an implementation you may use, under the same
[license](./LICENSE) as this package:
```js
// a storage-unbounded ttl cache that is not an lru-cache
const cache = {
data: new Map(),
timers: new Map(),
set: (k, v, ttl) => {
if (cache.timers.has(k)) {
clearTimeout(cache.timers.get(k))
}
cache.timers.set(
k,
setTimeout(() => cache.delete(k), ttl)
)
cache.data.set(k, v)
},
get: k => cache.data.get(k),
has: k => cache.data.has(k),
delete: k => {
if (cache.timers.has(k)) {
clearTimeout(cache.timers.get(k))
}
cache.timers.delete(k)
return cache.data.delete(k)
},
clear: () => {
cache.data.clear()
for (const v of cache.timers.values()) {
clearTimeout(v)
}
cache.timers.clear()
},
}
```
If that isn't to your liking, check out
[@isaacs/ttlcache](http://npm.im/@isaacs/ttlcache).
## Storing Undefined Values
This cache never stores undefined values, as `undefined` is used
internally in a few places to indicate that a key is not in the
cache.
You may call `cache.set(key, undefined)`, but this is just
an alias for `cache.delete(key)`. Note that this has the effect
that `cache.has(key)` will return _false_ after setting it to
undefined.
```js
cache.set(myKey, undefined)
cache.has(myKey) // false!
```
If you need to track `undefined` values, and still note that the
key is in the cache, an easy workaround is to use a sigil object
of your own.
```js
import { LRUCache } from 'lru-cache'
const undefinedValue = Symbol('undefined')
const cache = new LRUCache(...)
const mySet = (key, value) =>
cache.set(key, value === undefined ? undefinedValue : value)
const myGet = (key, value) => {
const v = cache.get(key)
return v === undefinedValue ? undefined : v
}
```
## Performance
As of January 2022, version 7 of this library is one of the most
performant LRU cache implementations in JavaScript.
Benchmarks can be extremely difficult to get right. In
particular, the performance of set/get/delete operations on
objects will vary _wildly_ depending on the type of key used. V8
is highly optimized for objects with keys that are short strings,
especially integer numeric strings. Thus any benchmark which
tests _solely_ using numbers as keys will tend to find that an
object-based approach performs the best.
Note that coercing _anything_ to strings to use as object keys is
unsafe, unless you can be 100% certain that no other type of
value will be used. For example:
```js
const myCache = {}
const set = (k, v) => (myCache[k] = v)
const get = k => myCache[k]
set({}, 'please hang onto this for me')
set('[object Object]', 'oopsie')
```
Also beware of "Just So" stories regarding performance. Garbage
collection of large (especially: deep) object graphs can be
incredibly costly, with several "tipping points" where it
increases exponentially. As a result, putting that off until
later can make it much worse, and less predictable. If a library
performs well, but only in a scenario where the object graph is
kept shallow, then that won't help you if you are using large
objects as keys.
In general, when attempting to use a library to improve
performance (such as a cache like this one), it's best to choose
an option that will perform well in the sorts of scenarios where
you'll actually use it.
This library is optimized for repeated gets and minimizing
eviction time, since that is the expected need of a LRU. Set
operations are somewhat slower on average than a few other
options, in part because of that optimization. It is assumed
that you'll be caching some costly operation, ideally as rarely
as possible, so optimizing set over get would be unwise.
If performance matters to you:
1. If it's at all possible to use small integer values as keys,
and you can guarantee that no other types of values will be
used as keys, then do that, and use a cache such as
[lru-fast](https://npmjs.com/package/lru-fast), or
[mnemonist's
LRUCache](https://yomguithereal.github.io/mnemonist/lru-cache)
which uses an Object as its data store.
2. Failing that, if at all possible, use short non-numeric
strings (ie, less than 256 characters) as your keys, and use
[mnemonist's
LRUCache](https://yomguithereal.github.io/mnemonist/lru-cache).
3. If the types of your keys will be anything else, especially
long strings, strings that look like floats, objects, or some
mix of types, or if you aren't sure, then this library will
work well for you.
If you do not need the features that this library provides
(like asynchronous fetching, a variety of TTL staleness
options, and so on), then [mnemonist's
LRUMap](https://yomguithereal.github.io/mnemonist/lru-map) is
a very good option, and just slightly faster than this module
(since it does considerably less).
4. Do not use a `dispose` function, size tracking, or especially
ttl behavior, unless absolutely needed. These features are
convenient, and necessary in some use cases, and every attempt
has been made to make the performance impact minimal, but it
isn't nothing.
## Breaking Changes in Version 7
This library changed to a different algorithm and internal data
structure in version 7, yielding significantly better
performance, albeit with some subtle changes as a result.
If you were relying on the internals of LRUCache in version 6 or
before, it probably will not work in version 7 and above.
## Breaking Changes in Version 8
- The `fetchContext` option was renamed to `context`, and may no
longer be set on the cache instance itself.
- Rewritten in TypeScript, so pretty much all the types moved
around a lot.
- The AbortController/AbortSignal polyfill was removed. For this
reason, **Node version 16.14.0 or higher is now required**.
- Internal properties were moved to actual private class
properties.
- Keys and values must not be `null` or `undefined`.
- Minified export available at `'lru-cache/min'`, for both CJS
and MJS builds.
## Breaking Changes in Version 9
- Named export only, no default export.
- AbortController polyfill returned, albeit with a warning when
used.
## Breaking Changes in Version 10
- `cache.fetch()` return type is now `Promise<V | undefined>`
instead of `Promise<V | void>`. This is an irrelevant change
practically speaking, but can require changes for TypeScript
users.
For more info, see the [change log](CHANGELOG.md).

View File

@@ -0,0 +1,8 @@
import type { Attachment } from '../attachment';
export type FeedbackFormData = {
name: string;
email: string;
message: string;
attachments: Attachment[] | undefined;
};
//# sourceMappingURL=form.d.ts.map

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-2022 KillyMXI <killy@mxii.eu.org>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,56 @@
'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { getTranslation } from '@payloadcms/translations';
import React from 'react';
import { useForm } from '../../forms/Form/context.js';
import { useEditDepth } from '../../providers/EditDepth/index.js';
import { useLocale } from '../../providers/Locale/index.js';
import { useTranslation } from '../../providers/Translation/index.js';
import { generateFieldID } from '../../utilities/generateFieldID.js';
import './index.scss';
export const FieldLabel = props => {
const {
as: t0,
hideLocale: t1,
htmlFor: htmlForFromProps,
label,
localized: t2,
path,
required: t3,
unstyled: t4
} = props;
const ElementFromProps = t0 === undefined ? "label" : t0;
const hideLocale = t1 === undefined ? false : t1;
const localized = t2 === undefined ? false : t2;
const required = t3 === undefined ? false : t3;
const unstyled = t4 === undefined ? false : t4;
const {
uuid
} = useForm();
const editDepth = useEditDepth();
const htmlFor = htmlForFromProps || generateFieldID(path, editDepth, uuid);
const {
i18n
} = useTranslation();
const {
code,
label: localLabel
} = useLocale();
const Element = ElementFromProps === "label" ? htmlFor ? "label" : "span" : ElementFromProps || "span";
if (label) {
return _jsxs(Element, {
className: `field-label${unstyled ? " unstyled" : ""}`,
htmlFor,
children: [getTranslation(label, i18n), required && !unstyled && _jsx("span", {
className: "required",
children: "*"
}), localized && !hideLocale && _jsxs("span", {
className: "localized",
children: ["\u2014 ", typeof localLabel === "string" ? localLabel : code]
})]
});
}
return null;
};
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,8 @@
@import '../../../scss/styles.scss';
@layer payload-default {
.upload {
position: relative;
max-width: 100%;
}
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.js","names":[],"sources":["../../../src/forms/RenderFields/types.ts"],"sourcesContent":["import type { ClientComponentProps, ClientField, SanitizedFieldPermissions } from 'payload'\n\nexport type RenderFieldsProps = {\n readonly className?: string\n readonly fields: ClientField[]\n readonly margins?: 'small' | false\n readonly parentIndexPath: string\n readonly parentPath: string\n readonly parentSchemaPath: string\n readonly permissions:\n | {\n [fieldName: string]: SanitizedFieldPermissions\n }\n | SanitizedFieldPermissions\n readonly readOnly?: boolean\n} & Pick<ClientComponentProps, 'forceRender'>\n"],"mappings":"AAEA","ignoreList":[]}

View File

@@ -0,0 +1 @@
{"version":3,"sources":["../../../../src/bin/generateImportMap/utilities/getFromImportMap.ts"],"sourcesContent":["import type { PayloadComponent } from '../../../config/types.js'\nimport type { ImportMap } from '../index.js'\n\nimport { parsePayloadComponent } from './parsePayloadComponent.js'\n\nexport const getFromImportMap = <TOutput>(args: {\n importMap: ImportMap\n PayloadComponent: PayloadComponent\n schemaPath?: string\n silent?: boolean\n}): TOutput => {\n const { importMap, PayloadComponent, schemaPath, silent } = args\n\n const { exportName, path } = parsePayloadComponent(PayloadComponent)\n\n const key = path + '#' + exportName\n\n const importMapEntry = importMap[key]\n\n if (!importMapEntry && !silent) {\n // eslint-disable-next-line no-console\n console.error(\n `getFromImportMap: PayloadComponent not found in importMap`,\n {\n key,\n PayloadComponent,\n schemaPath,\n },\n 'You may need to run the `payload generate:importmap` command to generate the importMap ahead of runtime.',\n )\n }\n\n return importMapEntry\n}\n"],"names":["parsePayloadComponent","getFromImportMap","args","importMap","PayloadComponent","schemaPath","silent","exportName","path","key","importMapEntry","console","error"],"mappings":"AAGA,SAASA,qBAAqB,QAAQ,6BAA4B;AAElE,OAAO,MAAMC,mBAAmB,CAAUC;IAMxC,MAAM,EAAEC,SAAS,EAAEC,gBAAgB,EAAEC,UAAU,EAAEC,MAAM,EAAE,GAAGJ;IAE5D,MAAM,EAAEK,UAAU,EAAEC,IAAI,EAAE,GAAGR,sBAAsBI;IAEnD,MAAMK,MAAMD,OAAO,MAAMD;IAEzB,MAAMG,iBAAiBP,SAAS,CAACM,IAAI;IAErC,IAAI,CAACC,kBAAkB,CAACJ,QAAQ;QAC9B,sCAAsC;QACtCK,QAAQC,KAAK,CACX,CAAC,yDAAyD,CAAC,EAC3D;YACEH;YACAL;YACAC;QACF,GACA;IAEJ;IAEA,OAAOK;AACT,EAAC"}

View File

@@ -0,0 +1,17 @@
Prism.languages.applescript = {
'comment': [
// Allow one level of nesting
/\(\*(?:\(\*(?:[^*]|\*(?!\)))*\*\)|(?!\(\*)[\s\S])*?\*\)/,
/--.+/,
/#.+/
],
'string': /"(?:\\.|[^"\\\r\n])*"/,
'number': /(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e-?\d+)?\b/i,
'operator': [
/[&=≠≤≥*+\-\/÷^]|[<>]=?/,
/\b(?:(?:begin|end|start)s? with|(?:contains?|(?:does not|doesn't) contain)|(?:is|isn't|is not) (?:contained by|in)|(?:(?:is|isn't|is not) )?(?:greater|less) than(?: or equal)?(?: to)?|(?:comes|(?:does not|doesn't) come) (?:after|before)|(?:is|isn't|is not) equal(?: to)?|(?:(?:does not|doesn't) equal|equal to|equals|is not|isn't)|(?:a )?(?:ref(?: to)?|reference to)|(?:and|as|div|mod|not|or))\b/
],
'keyword': /\b(?:about|above|after|against|apart from|around|aside from|at|back|before|beginning|behind|below|beneath|beside|between|but|by|considering|continue|copy|does|eighth|else|end|equal|error|every|exit|false|fifth|first|for|fourth|from|front|get|given|global|if|ignoring|in|instead of|into|is|it|its|last|local|me|middle|my|ninth|of|on|onto|out of|over|prop|property|put|repeat|return|returning|second|set|seventh|since|sixth|some|tell|tenth|that|the|then|third|through|thru|timeout|times|to|transaction|true|try|until|where|while|whose|with|without)\b/,
'class-name': /\b(?:POSIX file|RGB color|alias|application|boolean|centimeters|centimetres|class|constant|cubic centimeters|cubic centimetres|cubic feet|cubic inches|cubic meters|cubic metres|cubic yards|date|degrees Celsius|degrees Fahrenheit|degrees Kelvin|feet|file|gallons|grams|inches|integer|kilograms|kilometers|kilometres|list|liters|litres|meters|metres|miles|number|ounces|pounds|quarts|real|record|reference|script|square feet|square kilometers|square kilometres|square meters|square metres|square miles|square yards|text|yards)\b/,
'punctuation': /[{}():,¬«»《》]/
};

View File

@@ -0,0 +1,20 @@
/**
* @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 Snowflake = createLucideIcon("Snowflake", [
["line", { x1: "2", x2: "22", y1: "12", y2: "12", key: "1dnqot" }],
["line", { x1: "12", x2: "12", y1: "2", y2: "22", key: "7eqyqh" }],
["path", { d: "m20 16-4-4 4-4", key: "rquw4f" }],
["path", { d: "m4 8 4 4-4 4", key: "12s3z9" }],
["path", { d: "m16 4-4 4-4-4", key: "1tumq1" }],
["path", { d: "m8 20 4-4 4 4", key: "9p200w" }]
]);
export { Snowflake as default };
//# sourceMappingURL=snowflake.js.map

View File

@@ -0,0 +1,29 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var view_common_exports = {};
__export(view_common_exports, {
GelViewConfig: () => GelViewConfig
});
module.exports = __toCommonJS(view_common_exports);
const GelViewConfig = Symbol.for("drizzle:GelViewConfig");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
GelViewConfig
});
//# sourceMappingURL=view-common.cjs.map

View File

@@ -0,0 +1,5 @@
export declare const endOfHourWithOptions: import("./types.js").FPFn2<
Date,
import("../endOfHour.js").EndOfHourOptions<Date> | undefined,
import("../fp.js").DateArg<Date>
>;

View File

@@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const codegen_1 = require("../../compile/codegen");
const util_1 = require("../../compile/util");
const error = {
message: "property name must be valid",
params: ({ params }) => (0, codegen_1._) `{propertyName: ${params.propertyName}}`,
};
const def = {
keyword: "propertyNames",
type: "object",
schemaType: ["object", "boolean"],
error,
code(cxt) {
const { gen, schema, data, it } = cxt;
if ((0, util_1.alwaysValidSchema)(it, schema))
return;
const valid = gen.name("valid");
gen.forIn("key", data, (key) => {
cxt.setParams({ propertyName: key });
cxt.subschema({
keyword: "propertyNames",
data: key,
dataTypes: ["string"],
propertyName: key,
compositeRule: true,
}, valid);
gen.if((0, codegen_1.not)(valid), () => {
cxt.error(true);
if (!it.allErrors)
gen.break();
});
});
cxt.ok(valid);
},
};
exports.default = def;
//# sourceMappingURL=propertyNames.js.map

View File

@@ -0,0 +1,542 @@
/**
* @license React
* react.production.js
*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
"use strict";
var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"),
REACT_PORTAL_TYPE = Symbol.for("react.portal"),
REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"),
REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"),
REACT_PROFILER_TYPE = Symbol.for("react.profiler"),
REACT_CONSUMER_TYPE = Symbol.for("react.consumer"),
REACT_CONTEXT_TYPE = Symbol.for("react.context"),
REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"),
REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"),
REACT_MEMO_TYPE = Symbol.for("react.memo"),
REACT_LAZY_TYPE = Symbol.for("react.lazy"),
REACT_ACTIVITY_TYPE = Symbol.for("react.activity"),
MAYBE_ITERATOR_SYMBOL = Symbol.iterator;
function getIteratorFn(maybeIterable) {
if (null === maybeIterable || "object" !== typeof maybeIterable) return null;
maybeIterable =
(MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL]) ||
maybeIterable["@@iterator"];
return "function" === typeof maybeIterable ? maybeIterable : null;
}
var ReactNoopUpdateQueue = {
isMounted: function () {
return !1;
},
enqueueForceUpdate: function () {},
enqueueReplaceState: function () {},
enqueueSetState: function () {}
},
assign = Object.assign,
emptyObject = {};
function Component(props, context, updater) {
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
}
Component.prototype.isReactComponent = {};
Component.prototype.setState = function (partialState, callback) {
if (
"object" !== typeof partialState &&
"function" !== typeof partialState &&
null != partialState
)
throw Error(
"takes an object of state variables to update or a function which returns an object of state variables."
);
this.updater.enqueueSetState(this, partialState, callback, "setState");
};
Component.prototype.forceUpdate = function (callback) {
this.updater.enqueueForceUpdate(this, callback, "forceUpdate");
};
function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;
function PureComponent(props, context, updater) {
this.props = props;
this.context = context;
this.refs = emptyObject;
this.updater = updater || ReactNoopUpdateQueue;
}
var pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
pureComponentPrototype.constructor = PureComponent;
assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = !0;
var isArrayImpl = Array.isArray;
function noop() {}
var ReactSharedInternals = { H: null, A: null, T: null, S: null },
hasOwnProperty = Object.prototype.hasOwnProperty;
function ReactElement(type, key, props) {
var refProp = props.ref;
return {
$$typeof: REACT_ELEMENT_TYPE,
type: type,
key: key,
ref: void 0 !== refProp ? refProp : null,
props: props
};
}
function cloneAndReplaceKey(oldElement, newKey) {
return ReactElement(oldElement.type, newKey, oldElement.props);
}
function isValidElement(object) {
return (
"object" === typeof object &&
null !== object &&
object.$$typeof === REACT_ELEMENT_TYPE
);
}
function escape(key) {
var escaperLookup = { "=": "=0", ":": "=2" };
return (
"$" +
key.replace(/[=:]/g, function (match) {
return escaperLookup[match];
})
);
}
var userProvidedKeyEscapeRegex = /\/+/g;
function getElementKey(element, index) {
return "object" === typeof element && null !== element && null != element.key
? escape("" + element.key)
: index.toString(36);
}
function resolveThenable(thenable) {
switch (thenable.status) {
case "fulfilled":
return thenable.value;
case "rejected":
throw thenable.reason;
default:
switch (
("string" === typeof thenable.status
? thenable.then(noop, noop)
: ((thenable.status = "pending"),
thenable.then(
function (fulfilledValue) {
"pending" === thenable.status &&
((thenable.status = "fulfilled"),
(thenable.value = fulfilledValue));
},
function (error) {
"pending" === thenable.status &&
((thenable.status = "rejected"), (thenable.reason = error));
}
)),
thenable.status)
) {
case "fulfilled":
return thenable.value;
case "rejected":
throw thenable.reason;
}
}
throw thenable;
}
function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) {
var type = typeof children;
if ("undefined" === type || "boolean" === type) children = null;
var invokeCallback = !1;
if (null === children) invokeCallback = !0;
else
switch (type) {
case "bigint":
case "string":
case "number":
invokeCallback = !0;
break;
case "object":
switch (children.$$typeof) {
case REACT_ELEMENT_TYPE:
case REACT_PORTAL_TYPE:
invokeCallback = !0;
break;
case REACT_LAZY_TYPE:
return (
(invokeCallback = children._init),
mapIntoArray(
invokeCallback(children._payload),
array,
escapedPrefix,
nameSoFar,
callback
)
);
}
}
if (invokeCallback)
return (
(callback = callback(children)),
(invokeCallback =
"" === nameSoFar ? "." + getElementKey(children, 0) : nameSoFar),
isArrayImpl(callback)
? ((escapedPrefix = ""),
null != invokeCallback &&
(escapedPrefix =
invokeCallback.replace(userProvidedKeyEscapeRegex, "$&/") + "/"),
mapIntoArray(callback, array, escapedPrefix, "", function (c) {
return c;
}))
: null != callback &&
(isValidElement(callback) &&
(callback = cloneAndReplaceKey(
callback,
escapedPrefix +
(null == callback.key ||
(children && children.key === callback.key)
? ""
: ("" + callback.key).replace(
userProvidedKeyEscapeRegex,
"$&/"
) + "/") +
invokeCallback
)),
array.push(callback)),
1
);
invokeCallback = 0;
var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":";
if (isArrayImpl(children))
for (var i = 0; i < children.length; i++)
(nameSoFar = children[i]),
(type = nextNamePrefix + getElementKey(nameSoFar, i)),
(invokeCallback += mapIntoArray(
nameSoFar,
array,
escapedPrefix,
type,
callback
));
else if (((i = getIteratorFn(children)), "function" === typeof i))
for (
children = i.call(children), i = 0;
!(nameSoFar = children.next()).done;
)
(nameSoFar = nameSoFar.value),
(type = nextNamePrefix + getElementKey(nameSoFar, i++)),
(invokeCallback += mapIntoArray(
nameSoFar,
array,
escapedPrefix,
type,
callback
));
else if ("object" === type) {
if ("function" === typeof children.then)
return mapIntoArray(
resolveThenable(children),
array,
escapedPrefix,
nameSoFar,
callback
);
array = String(children);
throw Error(
"Objects are not valid as a React child (found: " +
("[object Object]" === array
? "object with keys {" + Object.keys(children).join(", ") + "}"
: array) +
"). If you meant to render a collection of children, use an array instead."
);
}
return invokeCallback;
}
function mapChildren(children, func, context) {
if (null == children) return children;
var result = [],
count = 0;
mapIntoArray(children, result, "", "", function (child) {
return func.call(context, child, count++);
});
return result;
}
function lazyInitializer(payload) {
if (-1 === payload._status) {
var ctor = payload._result;
ctor = ctor();
ctor.then(
function (moduleObject) {
if (0 === payload._status || -1 === payload._status)
(payload._status = 1), (payload._result = moduleObject);
},
function (error) {
if (0 === payload._status || -1 === payload._status)
(payload._status = 2), (payload._result = error);
}
);
-1 === payload._status && ((payload._status = 0), (payload._result = ctor));
}
if (1 === payload._status) return payload._result.default;
throw payload._result;
}
var reportGlobalError =
"function" === typeof reportError
? reportError
: function (error) {
if (
"object" === typeof window &&
"function" === typeof window.ErrorEvent
) {
var event = new window.ErrorEvent("error", {
bubbles: !0,
cancelable: !0,
message:
"object" === typeof error &&
null !== error &&
"string" === typeof error.message
? String(error.message)
: String(error),
error: error
});
if (!window.dispatchEvent(event)) return;
} else if (
"object" === typeof process &&
"function" === typeof process.emit
) {
process.emit("uncaughtException", error);
return;
}
console.error(error);
},
Children = {
map: mapChildren,
forEach: function (children, forEachFunc, forEachContext) {
mapChildren(
children,
function () {
forEachFunc.apply(this, arguments);
},
forEachContext
);
},
count: function (children) {
var n = 0;
mapChildren(children, function () {
n++;
});
return n;
},
toArray: function (children) {
return (
mapChildren(children, function (child) {
return child;
}) || []
);
},
only: function (children) {
if (!isValidElement(children))
throw Error(
"React.Children.only expected to receive a single React element child."
);
return children;
}
};
exports.Activity = REACT_ACTIVITY_TYPE;
exports.Children = Children;
exports.Component = Component;
exports.Fragment = REACT_FRAGMENT_TYPE;
exports.Profiler = REACT_PROFILER_TYPE;
exports.PureComponent = PureComponent;
exports.StrictMode = REACT_STRICT_MODE_TYPE;
exports.Suspense = REACT_SUSPENSE_TYPE;
exports.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE =
ReactSharedInternals;
exports.__COMPILER_RUNTIME = {
__proto__: null,
c: function (size) {
return ReactSharedInternals.H.useMemoCache(size);
}
};
exports.cache = function (fn) {
return function () {
return fn.apply(null, arguments);
};
};
exports.cacheSignal = function () {
return null;
};
exports.cloneElement = function (element, config, children) {
if (null === element || void 0 === element)
throw Error(
"The argument must be a React element, but you passed " + element + "."
);
var props = assign({}, element.props),
key = element.key;
if (null != config)
for (propName in (void 0 !== config.key && (key = "" + config.key), config))
!hasOwnProperty.call(config, propName) ||
"key" === propName ||
"__self" === propName ||
"__source" === propName ||
("ref" === propName && void 0 === config.ref) ||
(props[propName] = config[propName]);
var propName = arguments.length - 2;
if (1 === propName) props.children = children;
else if (1 < propName) {
for (var childArray = Array(propName), i = 0; i < propName; i++)
childArray[i] = arguments[i + 2];
props.children = childArray;
}
return ReactElement(element.type, key, props);
};
exports.createContext = function (defaultValue) {
defaultValue = {
$$typeof: REACT_CONTEXT_TYPE,
_currentValue: defaultValue,
_currentValue2: defaultValue,
_threadCount: 0,
Provider: null,
Consumer: null
};
defaultValue.Provider = defaultValue;
defaultValue.Consumer = {
$$typeof: REACT_CONSUMER_TYPE,
_context: defaultValue
};
return defaultValue;
};
exports.createElement = function (type, config, children) {
var propName,
props = {},
key = null;
if (null != config)
for (propName in (void 0 !== config.key && (key = "" + config.key), config))
hasOwnProperty.call(config, propName) &&
"key" !== propName &&
"__self" !== propName &&
"__source" !== propName &&
(props[propName] = config[propName]);
var childrenLength = arguments.length - 2;
if (1 === childrenLength) props.children = children;
else if (1 < childrenLength) {
for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++)
childArray[i] = arguments[i + 2];
props.children = childArray;
}
if (type && type.defaultProps)
for (propName in ((childrenLength = type.defaultProps), childrenLength))
void 0 === props[propName] &&
(props[propName] = childrenLength[propName]);
return ReactElement(type, key, props);
};
exports.createRef = function () {
return { current: null };
};
exports.forwardRef = function (render) {
return { $$typeof: REACT_FORWARD_REF_TYPE, render: render };
};
exports.isValidElement = isValidElement;
exports.lazy = function (ctor) {
return {
$$typeof: REACT_LAZY_TYPE,
_payload: { _status: -1, _result: ctor },
_init: lazyInitializer
};
};
exports.memo = function (type, compare) {
return {
$$typeof: REACT_MEMO_TYPE,
type: type,
compare: void 0 === compare ? null : compare
};
};
exports.startTransition = function (scope) {
var prevTransition = ReactSharedInternals.T,
currentTransition = {};
ReactSharedInternals.T = currentTransition;
try {
var returnValue = scope(),
onStartTransitionFinish = ReactSharedInternals.S;
null !== onStartTransitionFinish &&
onStartTransitionFinish(currentTransition, returnValue);
"object" === typeof returnValue &&
null !== returnValue &&
"function" === typeof returnValue.then &&
returnValue.then(noop, reportGlobalError);
} catch (error) {
reportGlobalError(error);
} finally {
null !== prevTransition &&
null !== currentTransition.types &&
(prevTransition.types = currentTransition.types),
(ReactSharedInternals.T = prevTransition);
}
};
exports.unstable_useCacheRefresh = function () {
return ReactSharedInternals.H.useCacheRefresh();
};
exports.use = function (usable) {
return ReactSharedInternals.H.use(usable);
};
exports.useActionState = function (action, initialState, permalink) {
return ReactSharedInternals.H.useActionState(action, initialState, permalink);
};
exports.useCallback = function (callback, deps) {
return ReactSharedInternals.H.useCallback(callback, deps);
};
exports.useContext = function (Context) {
return ReactSharedInternals.H.useContext(Context);
};
exports.useDebugValue = function () {};
exports.useDeferredValue = function (value, initialValue) {
return ReactSharedInternals.H.useDeferredValue(value, initialValue);
};
exports.useEffect = function (create, deps) {
return ReactSharedInternals.H.useEffect(create, deps);
};
exports.useEffectEvent = function (callback) {
return ReactSharedInternals.H.useEffectEvent(callback);
};
exports.useId = function () {
return ReactSharedInternals.H.useId();
};
exports.useImperativeHandle = function (ref, create, deps) {
return ReactSharedInternals.H.useImperativeHandle(ref, create, deps);
};
exports.useInsertionEffect = function (create, deps) {
return ReactSharedInternals.H.useInsertionEffect(create, deps);
};
exports.useLayoutEffect = function (create, deps) {
return ReactSharedInternals.H.useLayoutEffect(create, deps);
};
exports.useMemo = function (create, deps) {
return ReactSharedInternals.H.useMemo(create, deps);
};
exports.useOptimistic = function (passthrough, reducer) {
return ReactSharedInternals.H.useOptimistic(passthrough, reducer);
};
exports.useReducer = function (reducer, initialArg, init) {
return ReactSharedInternals.H.useReducer(reducer, initialArg, init);
};
exports.useRef = function (initialValue) {
return ReactSharedInternals.H.useRef(initialValue);
};
exports.useState = function (initialState) {
return ReactSharedInternals.H.useState(initialState);
};
exports.useSyncExternalStore = function (
subscribe,
getSnapshot,
getServerSnapshot
) {
return ReactSharedInternals.H.useSyncExternalStore(
subscribe,
getSnapshot,
getServerSnapshot
);
};
exports.useTransition = function () {
return ReactSharedInternals.H.useTransition();
};
exports.version = "19.2.4";

View File

@@ -0,0 +1,41 @@
"use strict";
exports.formatLong = void 0;
var _index = require("../../_lib/buildFormatLongFn.js");
const dateFormats = {
full: "EEEE, d 'de' MMMM 'de' y",
long: "d 'de' MMMM 'de' y",
medium: "d MMM y",
short: "dd/MM/y",
};
const timeFormats = {
full: "HH:mm:ss zzzz",
long: "HH:mm:ss z",
medium: "HH:mm:ss",
short: "HH:mm",
};
const dateTimeFormats = {
full: "{{date}} 'a las' {{time}}",
long: "{{date}} 'a las' {{time}}",
medium: "{{date}}, {{time}}",
short: "{{date}}, {{time}}",
};
const formatLong = (exports.formatLong = {
date: (0, _index.buildFormatLongFn)({
formats: dateFormats,
defaultWidth: "full",
}),
time: (0, _index.buildFormatLongFn)({
formats: timeFormats,
defaultWidth: "full",
}),
dateTime: (0, _index.buildFormatLongFn)({
formats: dateTimeFormats,
defaultWidth: "full",
}),
});

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2014 Evan Wallace
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,8 @@
import { createHmac } from 'node:crypto';
import { concat, uint64be } from '../lib/buffer_utils.js';
export default function cbcTag(aad, iv, ciphertext, macSize, macKey, keySize) {
const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
const hmac = createHmac(`sha${macSize}`, macKey);
hmac.update(macData);
return hmac.digest().slice(0, keySize >> 3);
}

View File

@@ -0,0 +1,164 @@
import { buildLocalizeFn } from "../../_lib/buildLocalizeFn.js";
const eraValues = {
narrow: ["aC", "dC"],
abbreviated: ["a.C.", "d.C."],
wide: ["antes de Cristo", "depois de Cristo"],
};
const quarterValues = {
narrow: ["1", "2", "3", "4"],
abbreviated: ["T1", "T2", "T3", "T4"],
wide: ["1º trimestre", "2º trimestre", "3º trimestre", "4º trimestre"],
};
const monthValues = {
narrow: ["j", "f", "m", "a", "m", "j", "j", "a", "s", "o", "n", "d"],
abbreviated: [
"jan",
"fev",
"mar",
"abr",
"mai",
"jun",
"jul",
"ago",
"set",
"out",
"nov",
"dez",
],
wide: [
"janeiro",
"fevereiro",
"março",
"abril",
"maio",
"junho",
"julho",
"agosto",
"setembro",
"outubro",
"novembro",
"dezembro",
],
};
const dayValues = {
narrow: ["d", "s", "t", "q", "q", "s", "s"],
short: ["dom", "seg", "ter", "qua", "qui", "sex", "sáb"],
abbreviated: ["dom", "seg", "ter", "qua", "qui", "sex", "sáb"],
wide: [
"domingo",
"segunda-feira",
"terça-feira",
"quarta-feira",
"quinta-feira",
"sexta-feira",
"sábado",
],
};
const dayPeriodValues = {
narrow: {
am: "AM",
pm: "PM",
midnight: "meia-noite",
noon: "meio-dia",
morning: "manhã",
afternoon: "tarde",
evening: "noite",
night: "madrugada",
},
abbreviated: {
am: "AM",
pm: "PM",
midnight: "meia-noite",
noon: "meio-dia",
morning: "manhã",
afternoon: "tarde",
evening: "noite",
night: "madrugada",
},
wide: {
am: "AM",
pm: "PM",
midnight: "meia-noite",
noon: "meio-dia",
morning: "manhã",
afternoon: "tarde",
evening: "noite",
night: "madrugada",
},
};
const formattingDayPeriodValues = {
narrow: {
am: "AM",
pm: "PM",
midnight: "meia-noite",
noon: "meio-dia",
morning: "da manhã",
afternoon: "da tarde",
evening: "da noite",
night: "da madrugada",
},
abbreviated: {
am: "AM",
pm: "PM",
midnight: "meia-noite",
noon: "meio-dia",
morning: "da manhã",
afternoon: "da tarde",
evening: "da noite",
night: "da madrugada",
},
wide: {
am: "AM",
pm: "PM",
midnight: "meia-noite",
noon: "meio-dia",
morning: "da manhã",
afternoon: "da tarde",
evening: "da noite",
night: "da madrugada",
},
};
const ordinalNumber = (dirtyNumber, _options) => {
const number = Number(dirtyNumber);
return number + "º";
};
export const localize = {
ordinalNumber,
era: buildLocalizeFn({
values: eraValues,
defaultWidth: "wide",
}),
quarter: buildLocalizeFn({
values: quarterValues,
defaultWidth: "wide",
argumentCallback: (quarter) => quarter - 1,
}),
month: buildLocalizeFn({
values: monthValues,
defaultWidth: "wide",
}),
day: buildLocalizeFn({
values: dayValues,
defaultWidth: "wide",
}),
dayPeriod: buildLocalizeFn({
values: dayPeriodValues,
defaultWidth: "wide",
formattingValues: formattingDayPeriodValues,
defaultFormattingWidth: "wide",
}),
};

View File

@@ -0,0 +1 @@
{"version":3,"names":["circleSet","Set","depth","deepClone","value","cache","allowCircle","has","get","clear","Error","add","cloned","Array","isArray","length","set","i","keys","Object","key","delete","_default","Map","_","structuredClone"],"sources":["../../../src/transformation/util/clone-deep.ts"],"sourcesContent":["const circleSet = new Set();\nlet depth = 0;\n// https://github.com/babel/babel/pull/14583#discussion_r882828856\nfunction deepClone(\n value: any,\n cache: Map<any, any>,\n allowCircle: boolean,\n): any {\n if (value !== null) {\n if (allowCircle) {\n if (cache.has(value)) return cache.get(value);\n } else if (++depth > 250) {\n if (circleSet.has(value)) {\n depth = 0;\n circleSet.clear();\n throw new Error(\"Babel-deepClone: Cycles are not allowed in AST\");\n }\n circleSet.add(value);\n }\n let cloned: any;\n if (Array.isArray(value)) {\n cloned = new Array(value.length);\n if (allowCircle) cache.set(value, cloned);\n for (let i = 0; i < value.length; i++) {\n cloned[i] =\n typeof value[i] !== \"object\"\n ? value[i]\n : deepClone(value[i], cache, allowCircle);\n }\n } else {\n cloned = {};\n if (allowCircle) cache.set(value, cloned);\n const keys = Object.keys(value);\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i];\n cloned[key] =\n typeof value[key] !== \"object\"\n ? value[key]\n : deepClone(\n value[key],\n cache,\n allowCircle ||\n key === \"leadingComments\" ||\n key === \"innerComments\" ||\n key === \"trailingComments\" ||\n key === \"extra\",\n );\n }\n }\n if (!allowCircle) {\n if (depth-- > 250) circleSet.delete(value);\n }\n return cloned;\n }\n return value;\n}\n\nexport default function <T>(value: T): T {\n if (typeof value !== \"object\") return value;\n\n if (process.env.BABEL_8_BREAKING) {\n if (!process.env.IS_PUBLISH && depth > 0) {\n throw new Error(\"depth > 0\");\n }\n return deepClone(value, new Map(), false);\n } else {\n try {\n return deepClone(value, new Map(), true);\n } catch (_) {\n return structuredClone(value);\n }\n }\n}\n"],"mappings":";;;;;;AAAA,MAAMA,SAAS,GAAG,IAAIC,GAAG,CAAC,CAAC;AAC3B,IAAIC,KAAK,GAAG,CAAC;AAEb,SAASC,SAASA,CAChBC,KAAU,EACVC,KAAoB,EACpBC,WAAoB,EACf;EACL,IAAIF,KAAK,KAAK,IAAI,EAAE;IAClB,IAAIE,WAAW,EAAE;MACf,IAAID,KAAK,CAACE,GAAG,CAACH,KAAK,CAAC,EAAE,OAAOC,KAAK,CAACG,GAAG,CAACJ,KAAK,CAAC;IAC/C,CAAC,MAAM,IAAI,EAAEF,KAAK,GAAG,GAAG,EAAE;MACxB,IAAIF,SAAS,CAACO,GAAG,CAACH,KAAK,CAAC,EAAE;QACxBF,KAAK,GAAG,CAAC;QACTF,SAAS,CAACS,KAAK,CAAC,CAAC;QACjB,MAAM,IAAIC,KAAK,CAAC,gDAAgD,CAAC;MACnE;MACAV,SAAS,CAACW,GAAG,CAACP,KAAK,CAAC;IACtB;IACA,IAAIQ,MAAW;IACf,IAAIC,KAAK,CAACC,OAAO,CAACV,KAAK,CAAC,EAAE;MACxBQ,MAAM,GAAG,IAAIC,KAAK,CAACT,KAAK,CAACW,MAAM,CAAC;MAChC,IAAIT,WAAW,EAAED,KAAK,CAACW,GAAG,CAACZ,KAAK,EAAEQ,MAAM,CAAC;MACzC,KAAK,IAAIK,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGb,KAAK,CAACW,MAAM,EAAEE,CAAC,EAAE,EAAE;QACrCL,MAAM,CAACK,CAAC,CAAC,GACP,OAAOb,KAAK,CAACa,CAAC,CAAC,KAAK,QAAQ,GACxBb,KAAK,CAACa,CAAC,CAAC,GACRd,SAAS,CAACC,KAAK,CAACa,CAAC,CAAC,EAAEZ,KAAK,EAAEC,WAAW,CAAC;MAC/C;IACF,CAAC,MAAM;MACLM,MAAM,GAAG,CAAC,CAAC;MACX,IAAIN,WAAW,EAAED,KAAK,CAACW,GAAG,CAACZ,KAAK,EAAEQ,MAAM,CAAC;MACzC,MAAMM,IAAI,GAAGC,MAAM,CAACD,IAAI,CAACd,KAAK,CAAC;MAC/B,KAAK,IAAIa,CAAC,GAAG,CAAC,EAAEA,CAAC,GAAGC,IAAI,CAACH,MAAM,EAAEE,CAAC,EAAE,EAAE;QACpC,MAAMG,GAAG,GAAGF,IAAI,CAACD,CAAC,CAAC;QACnBL,MAAM,CAACQ,GAAG,CAAC,GACT,OAAOhB,KAAK,CAACgB,GAAG,CAAC,KAAK,QAAQ,GAC1BhB,KAAK,CAACgB,GAAG,CAAC,GACVjB,SAAS,CACPC,KAAK,CAACgB,GAAG,CAAC,EACVf,KAAK,EACLC,WAAW,IACTc,GAAG,KAAK,iBAAiB,IACzBA,GAAG,KAAK,eAAe,IACvBA,GAAG,KAAK,kBAAkB,IAC1BA,GAAG,KAAK,OACZ,CAAC;MACT;IACF;IACA,IAAI,CAACd,WAAW,EAAE;MAChB,IAAIJ,KAAK,EAAE,GAAG,GAAG,EAAEF,SAAS,CAACqB,MAAM,CAACjB,KAAK,CAAC;IAC5C;IACA,OAAOQ,MAAM;EACf;EACA,OAAOR,KAAK;AACd;AAEe,SAAAkB,SAAalB,KAAQ,EAAK;EACvC,IAAI,OAAOA,KAAK,KAAK,QAAQ,EAAE,OAAOA,KAAK;EAQzC,IAAI;IACF,OAAOD,SAAS,CAACC,KAAK,EAAE,IAAImB,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC;EAC1C,CAAC,CAAC,OAAOC,CAAC,EAAE;IACV,OAAOC,eAAe,CAACrB,KAAK,CAAC;EAC/B;AAEJ;AAAC","ignoreList":[]}

View File

@@ -0,0 +1 @@
{"version":3,"file":"autoLoaderUtils.js","sourceRoot":"","sources":["../../src/autoLoaderUtils.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAMH;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CACpC,gBAAmC,EACnC,cAA+B,EAC/B,aAA6B,EAC7B,cAA+B;IAE/B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,gBAAgB,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;QACvD,MAAM,eAAe,GAAG,gBAAgB,CAAC,CAAC,CAAC,CAAC;QAC5C,IAAI,cAAc,EAAE;YAClB,eAAe,CAAC,iBAAiB,CAAC,cAAc,CAAC,CAAC;SACnD;QACD,IAAI,aAAa,EAAE;YACjB,eAAe,CAAC,gBAAgB,CAAC,aAAa,CAAC,CAAC;SACjD;QACD,IAAI,cAAc,IAAI,eAAe,CAAC,iBAAiB,EAAE;YACvD,eAAe,CAAC,iBAAiB,CAAC,cAAc,CAAC,CAAC;SACnD;QACD,6DAA6D;QAC7D,oEAAoE;QACpE,mEAAmE;QACnE,yCAAyC;QACzC,IAAI,CAAC,eAAe,CAAC,SAAS,EAAE,CAAC,OAAO,EAAE;YACxC,eAAe,CAAC,MAAM,EAAE,CAAC;SAC1B;KACF;AACH,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,uBAAuB,CACrC,gBAAmC;IAEnC,gBAAgB,CAAC,OAAO,CAAC,eAAe,CAAC,EAAE,CAAC,eAAe,CAAC,OAAO,EAAE,CAAC,CAAC;AACzE,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\nimport { TracerProvider, MeterProvider } from '@opentelemetry/api';\nimport { Instrumentation } from './types';\nimport { LoggerProvider } from '@opentelemetry/api-logs';\n\n/**\n * Enable instrumentations\n * @param instrumentations\n * @param tracerProvider\n * @param meterProvider\n */\nexport function enableInstrumentations(\n instrumentations: Instrumentation[],\n tracerProvider?: TracerProvider,\n meterProvider?: MeterProvider,\n loggerProvider?: LoggerProvider\n): void {\n for (let i = 0, j = instrumentations.length; i < j; i++) {\n const instrumentation = instrumentations[i];\n if (tracerProvider) {\n instrumentation.setTracerProvider(tracerProvider);\n }\n if (meterProvider) {\n instrumentation.setMeterProvider(meterProvider);\n }\n if (loggerProvider && instrumentation.setLoggerProvider) {\n instrumentation.setLoggerProvider(loggerProvider);\n }\n // instrumentations have been already enabled during creation\n // so enable only if user prevented that by setting enabled to false\n // this is to prevent double enabling but when calling register all\n // instrumentations should be now enabled\n if (!instrumentation.getConfig().enabled) {\n instrumentation.enable();\n }\n }\n}\n\n/**\n * Disable instrumentations\n * @param instrumentations\n */\nexport function disableInstrumentations(\n instrumentations: Instrumentation[]\n): void {\n instrumentations.forEach(instrumentation => instrumentation.disable());\n}\n"]}

View File

@@ -0,0 +1,100 @@
/**
* Session-scoped data storage for stateful transports (with sessionId)
* @internal Using sessionId as key handles wrapper transport patterns
*/
const sessionToSessionData = new Map();
/**
* Transport-scoped data storage fallback for stateless transports (no sessionId)
* @internal WeakMap allows automatic cleanup when transport is garbage collected
*/
const statelessSessionData = new WeakMap();
/**
* Gets session data for a transport, checking sessionId first then fallback
* @internal
*/
function getSessionData(transport) {
const sessionId = transport.sessionId;
if (sessionId) {
return sessionToSessionData.get(sessionId);
}
return statelessSessionData.get(transport);
}
/**
* Sets session data for a transport, using sessionId when available
* @internal
*/
function setSessionData(transport, data) {
const sessionId = transport.sessionId;
if (sessionId) {
sessionToSessionData.set(sessionId, data);
} else {
statelessSessionData.set(transport, data);
}
}
/**
* Stores session data for a transport
* @param transport - MCP transport instance
* @param sessionData - Session data to store
*/
function storeSessionDataForTransport(transport, sessionData) {
// For stateful transports, always store (sessionId is the key)
// For stateless transports, also store (transport instance is the key)
setSessionData(transport, sessionData);
}
/**
* Updates session data for a transport (merges with existing data)
* @param transport - MCP transport instance
* @param partialSessionData - Partial session data to merge with existing data
*/
function updateSessionDataForTransport(transport, partialSessionData) {
const existingData = getSessionData(transport) || {};
setSessionData(transport, { ...existingData, ...partialSessionData });
}
/**
* Retrieves client information for a transport
* @param transport - MCP transport instance
* @returns Client information if available
*/
function getClientInfoForTransport(transport) {
return getSessionData(transport)?.clientInfo;
}
/**
* Retrieves protocol version for a transport
* @param transport - MCP transport instance
* @returns Protocol version if available
*/
function getProtocolVersionForTransport(transport) {
return getSessionData(transport)?.protocolVersion;
}
/**
* Retrieves full session data for a transport
* @param transport - MCP transport instance
* @returns Complete session data if available
*/
function getSessionDataForTransport(transport) {
return getSessionData(transport);
}
/**
* Cleans up session data for a specific transport (when that transport closes)
* @param transport - MCP transport instance
*/
function cleanupSessionDataForTransport(transport) {
const sessionId = transport.sessionId;
if (sessionId) {
sessionToSessionData.delete(sessionId);
}
// Note: WeakMap entries are automatically cleaned up when transport is GC'd
// No explicit delete needed for statelessSessionData
}
export { cleanupSessionDataForTransport, getClientInfoForTransport, getProtocolVersionForTransport, getSessionDataForTransport, storeSessionDataForTransport, updateSessionDataForTransport };
//# sourceMappingURL=sessionManagement.js.map

View File

@@ -0,0 +1,3 @@
import type { Where } from '../../types/index.js';
export declare const appendVersionToQueryKey: (query?: Where) => Where;
//# sourceMappingURL=appendVersionToQueryKey.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/providers/DocumentInfo/index.tsx"],"names":[],"mappings":"AAKA,OAAO,KAAgF,MAAM,OAAO,CAAA;AAEpG,OAAO,KAAK,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAgBxE,mBAAmB,YAAY,CAAA;AAE/B,eAAO,MAAM,eAAe,QAAO,mBAAmC,CAAA;AA+YtE,eAAO,MAAM,oBAAoB,EAAE,KAAK,CAAC,EAAE,CACzC;IACE,QAAQ,CAAC,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAA;CACnC,GAAG,iBAAiB,CAOtB,CAAA"}

View File

@@ -0,0 +1,7 @@
{
"name": "dom-helpers/remove",
"private": true,
"main": "../cjs/remove.js",
"module": "../esm/remove.js",
"types": "../esm/remove.d.ts"
}

View File

@@ -0,0 +1,58 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var _extends = require('@babel/runtime/helpers/extends');
var React = require('react');
var Select = require('../../dist/Select-36d15f93.cjs.prod.js');
var useStateManager = require('../../dist/useStateManager-ce23061c.cjs.prod.js');
var useCreatable = require('../../dist/useCreatable-33af2ae1.cjs.prod.js');
require('@babel/runtime/helpers/objectSpread2');
require('@babel/runtime/helpers/classCallCheck');
require('@babel/runtime/helpers/createClass');
require('@babel/runtime/helpers/inherits');
require('@babel/runtime/helpers/createSuper');
require('@babel/runtime/helpers/toConsumableArray');
require('../../dist/index-665c4ed8.cjs.prod.js');
require('@emotion/react');
require('@babel/runtime/helpers/slicedToArray');
require('@babel/runtime/helpers/objectWithoutProperties');
require('@babel/runtime/helpers/typeof');
require('@babel/runtime/helpers/taggedTemplateLiteral');
require('@babel/runtime/helpers/defineProperty');
require('react-dom');
require('@floating-ui/dom');
require('use-isomorphic-layout-effect');
require('memoize-one');
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var React__namespace = /*#__PURE__*/_interopNamespace(React);
var CreatableSelect = /*#__PURE__*/React.forwardRef(function (props, ref) {
var creatableProps = useStateManager.useStateManager(props);
var selectProps = useCreatable.useCreatable(creatableProps);
return /*#__PURE__*/React__namespace.createElement(Select.Select, _extends({
ref: ref
}, selectProps));
});
var CreatableSelect$1 = CreatableSelect;
exports.useCreatable = useCreatable.useCreatable;
exports["default"] = CreatableSelect$1;

View File

@@ -0,0 +1,22 @@
#!/bin/bash
# This script is run by Craft after a release is created.
# We currently use it to bump the platform-specific optional dependencies to their new versions
# in the package-lock.json, immediately after a release is created. This is needed for CI to
# pass after the release is created.c
set -eux
OLD_VERSION="${1}"
NEW_VERSION="${2}"
git checkout master
# We need to update the package-lock.json to include the new version of the optional dependencies.
npm install --package-lock-only --ignore-scripts
git add package-lock.json
# Only commit if there are changes
git diff --staged --quiet || git commit -m "build(npm): 🤖 Bump optional dependencies to ${NEW_VERSION}"
git pull --rebase
git push

View File

@@ -0,0 +1,88 @@
import type * as JSONSchema from "./json-schema.js";
import { $ZodRegistry } from "./registries.js";
import type * as schemas from "./schemas.js";
interface JSONSchemaGeneratorParams {
/** A registry used to look up metadata for each schema. Any schema with an `id` property will be extracted as a $def.
* @default globalRegistry */
metadata?: $ZodRegistry<Record<string, any>>;
/** The JSON Schema version to target.
* - `"draft-2020-12"` — Default. JSON Schema Draft 2020-12
* - `"draft-7"` — JSON Schema Draft 7 */
target?: "draft-7" | "draft-2020-12";
/** How to handle unrepresentable types.
* - `"throw"` — Default. Unrepresentable types throw an error
* - `"any"` — Unrepresentable types become `{}` */
unrepresentable?: "throw" | "any";
/** Arbitrary custom logic that can be used to modify the generated JSON Schema. */
override?: (ctx: {
zodSchema: schemas.$ZodTypes;
jsonSchema: JSONSchema.BaseSchema;
path: (string | number)[];
}) => void;
/** Whether to extract the `"input"` or `"output"` type. Relevant to transforms, Error converting schema to JSONz, defaults, coerced primitives, etc.
* - `"output"` — Default. Convert the output schema.
* - `"input"` — Convert the input schema. */
io?: "input" | "output";
}
interface ProcessParams {
schemaPath: schemas.$ZodType[];
path: (string | number)[];
}
interface EmitParams {
/** How to handle cycles.
* - `"ref"` — Default. Cycles will be broken using $defs
* - `"throw"` — Cycles will throw an error if encountered */
cycles?: "ref" | "throw";
reused?: "ref" | "inline";
external?: {
/** */
registry: $ZodRegistry<{
id?: string | undefined;
}>;
uri?: ((id: string) => string) | undefined;
defs: Record<string, JSONSchema.BaseSchema>;
} | undefined;
}
interface Seen {
/** JSON Schema result for this Zod schema */
schema: JSONSchema.BaseSchema;
/** A cached version of the schema that doesn't get overwritten during ref resolution */
def?: JSONSchema.BaseSchema;
defId?: string | undefined;
/** Number of times this schema was encountered during traversal */
count: number;
/** Cycle path */
cycle?: (string | number)[] | undefined;
isParent?: boolean | undefined;
ref?: schemas.$ZodType | undefined | null;
/** JSON Schema property path for this schema */
path?: (string | number)[] | undefined;
}
export declare class JSONSchemaGenerator {
metadataRegistry: $ZodRegistry<Record<string, any>>;
target: "draft-7" | "draft-2020-12";
unrepresentable: "throw" | "any";
override: (ctx: {
zodSchema: schemas.$ZodTypes;
jsonSchema: JSONSchema.BaseSchema;
path: (string | number)[];
}) => void;
io: "input" | "output";
counter: number;
seen: Map<schemas.$ZodType, Seen>;
constructor(params?: JSONSchemaGeneratorParams);
process(schema: schemas.$ZodType, _params?: ProcessParams): JSONSchema.BaseSchema;
emit(schema: schemas.$ZodType, _params?: EmitParams): JSONSchema.BaseSchema;
}
interface ToJSONSchemaParams extends Omit<JSONSchemaGeneratorParams & EmitParams, "external"> {
}
interface RegistryToJSONSchemaParams extends Omit<JSONSchemaGeneratorParams & EmitParams, "external"> {
uri?: (id: string) => string;
}
export declare function toJSONSchema(schema: schemas.$ZodType, _params?: ToJSONSchemaParams): JSONSchema.BaseSchema;
export declare function toJSONSchema(registry: $ZodRegistry<{
id?: string | undefined;
}>, _params?: RegistryToJSONSchemaParams): {
schemas: Record<string, JSONSchema.BaseSchema>;
};
export {};

View File

@@ -0,0 +1,48 @@
import { hasDraftsEnabled } from '../utilities/getVersionsConfig.js';
export const getLatestGlobalVersion = async ({ slug, config, locale, payload, published, req, where })=>{
let latestVersion;
const whereQuery = published ? {
'version._status': {
equals: 'published'
}
} : {
latest: {
equals: true
}
};
if (hasDraftsEnabled(config)) {
latestVersion = (await payload.db.findGlobalVersions({
global: slug,
limit: 1,
locale: locale || req?.locale || undefined,
pagination: false,
req,
where: whereQuery
})).docs[0];
}
const global = await payload.db.findGlobal({
slug,
locale,
req,
where
});
const globalExists = Boolean(global);
if (!latestVersion) {
return {
global,
globalExists
};
}
if (!latestVersion.version.createdAt) {
latestVersion.version.createdAt = latestVersion.createdAt;
}
if (!latestVersion.version.updatedAt) {
latestVersion.version.updatedAt = latestVersion.updatedAt;
}
return {
global: latestVersion.version,
globalExists
};
};
//# sourceMappingURL=getLatestGlobalVersion.js.map

View File

@@ -0,0 +1,252 @@
'use strict'
const {
Readable,
Duplex,
PassThrough
} = require('node:stream')
const assert = require('node:assert')
const { AsyncResource } = require('node:async_hooks')
const {
InvalidArgumentError,
InvalidReturnValueError,
RequestAbortedError
} = require('../core/errors')
const util = require('../core/util')
const { addSignal, removeSignal } = require('./abort-signal')
function noop () {}
const kResume = Symbol('resume')
class PipelineRequest extends Readable {
constructor () {
super({ autoDestroy: true })
this[kResume] = null
}
_read () {
const { [kResume]: resume } = this
if (resume) {
this[kResume] = null
resume()
}
}
_destroy (err, callback) {
this._read()
callback(err)
}
}
class PipelineResponse extends Readable {
constructor (resume) {
super({ autoDestroy: true })
this[kResume] = resume
}
_read () {
this[kResume]()
}
_destroy (err, callback) {
if (!err && !this._readableState.endEmitted) {
err = new RequestAbortedError()
}
callback(err)
}
}
class PipelineHandler extends AsyncResource {
constructor (opts, handler) {
if (!opts || typeof opts !== 'object') {
throw new InvalidArgumentError('invalid opts')
}
if (typeof handler !== 'function') {
throw new InvalidArgumentError('invalid handler')
}
const { signal, method, opaque, onInfo, responseHeaders } = opts
if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') {
throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget')
}
if (method === 'CONNECT') {
throw new InvalidArgumentError('invalid method')
}
if (onInfo && typeof onInfo !== 'function') {
throw new InvalidArgumentError('invalid onInfo callback')
}
super('UNDICI_PIPELINE')
this.opaque = opaque || null
this.responseHeaders = responseHeaders || null
this.handler = handler
this.abort = null
this.context = null
this.onInfo = onInfo || null
this.req = new PipelineRequest().on('error', noop)
this.ret = new Duplex({
readableObjectMode: opts.objectMode,
autoDestroy: true,
read: () => {
const { body } = this
if (body?.resume) {
body.resume()
}
},
write: (chunk, encoding, callback) => {
const { req } = this
if (req.push(chunk, encoding) || req._readableState.destroyed) {
callback()
} else {
req[kResume] = callback
}
},
destroy: (err, callback) => {
const { body, req, res, ret, abort } = this
if (!err && !ret._readableState.endEmitted) {
err = new RequestAbortedError()
}
if (abort && err) {
abort()
}
util.destroy(body, err)
util.destroy(req, err)
util.destroy(res, err)
removeSignal(this)
callback(err)
}
}).on('prefinish', () => {
const { req } = this
// Node < 15 does not call _final in same tick.
req.push(null)
})
this.res = null
addSignal(this, signal)
}
onConnect (abort, context) {
const { res } = this
if (this.reason) {
abort(this.reason)
return
}
assert(!res, 'pipeline cannot be retried')
this.abort = abort
this.context = context
}
onHeaders (statusCode, rawHeaders, resume) {
const { opaque, handler, context } = this
if (statusCode < 200) {
if (this.onInfo) {
const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
this.onInfo({ statusCode, headers })
}
return
}
this.res = new PipelineResponse(resume)
let body
try {
this.handler = null
const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders)
body = this.runInAsyncScope(handler, null, {
statusCode,
headers,
opaque,
body: this.res,
context
})
} catch (err) {
this.res.on('error', noop)
throw err
}
if (!body || typeof body.on !== 'function') {
throw new InvalidReturnValueError('expected Readable')
}
body
.on('data', (chunk) => {
const { ret, body } = this
if (!ret.push(chunk) && body.pause) {
body.pause()
}
})
.on('error', (err) => {
const { ret } = this
util.destroy(ret, err)
})
.on('end', () => {
const { ret } = this
ret.push(null)
})
.on('close', () => {
const { ret } = this
if (!ret._readableState.ended) {
util.destroy(ret, new RequestAbortedError())
}
})
this.body = body
}
onData (chunk) {
const { res } = this
return res.push(chunk)
}
onComplete (trailers) {
const { res } = this
res.push(null)
}
onError (err) {
const { ret } = this
this.handler = null
util.destroy(ret, err)
}
}
function pipeline (opts, handler) {
try {
const pipelineHandler = new PipelineHandler(opts, handler)
this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler)
return pipelineHandler.ret
} catch (err) {
return new PassThrough().destroy(err)
}
}
module.exports = pipeline

View File

@@ -0,0 +1,2 @@
export declare function getMachineId(): Promise<string | undefined>;
//# sourceMappingURL=getMachineId-linux.d.ts.map

View File

@@ -0,0 +1,51 @@
import type {LinkedJSONSchema} from './types/JSONSchema'
import {Intersection, Parent, Types} from './types/JSONSchema'
import {typesOfSchema} from './typesOfSchema'
export function applySchemaTyping(schema: LinkedJSONSchema) {
const types = typesOfSchema(schema)
Object.defineProperty(schema, Types, {
enumerable: false,
value: types,
writable: false,
})
if (types.size === 1) {
return
}
// Some schemas can be understood as multiple possible types (see related
// comment in `typesOfSchema.ts`). In such cases, we generate an `ALL_OF`
// intersection that will ultimately be used to generate a union type.
//
// The original schema's name, title, and description are hoisted to the
// new intersection schema to prevent duplication.
//
// If the original schema also contained its own `ALL_OF` property, it is
// also hoiested to the new intersection schema.
const intersection = {
[Parent]: schema,
[Types]: new Set(['ALL_OF']),
$id: schema.$id,
description: schema.description,
name: schema.name,
title: schema.title,
allOf: schema.allOf ?? [],
required: [],
additionalProperties: false,
}
types.delete('ALL_OF')
delete schema.allOf
delete schema.$id
delete schema.description
delete schema.name
delete schema.title
Object.defineProperty(schema, Intersection, {
enumerable: false,
value: intersection,
writable: false,
})
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","names":["React","baseClass","Gutter","props","children","className","left","negativeLeft","negativeRight","ref","right","shouldPadLeft","shouldPadRight","_jsx","filter","Boolean","join"],"sources":["../../../src/elements/Gutter/index.tsx"],"sourcesContent":["'use client'\nimport React from 'react'\n\nimport './index.scss'\n\nexport type GutterProps = {\n children: React.ReactNode\n className?: string\n left?: boolean\n negativeLeft?: boolean\n negativeRight?: boolean\n ref?: React.RefObject<HTMLDivElement>\n right?: boolean\n}\n\nconst baseClass = 'gutter'\n\nexport const Gutter: React.FC<GutterProps> = (props) => {\n const {\n children,\n className,\n left = true,\n negativeLeft = false,\n negativeRight = false,\n ref,\n right = true,\n } = props\n\n const shouldPadLeft = left && !negativeLeft\n const shouldPadRight = right && !negativeRight\n\n return (\n <div\n className={[\n baseClass,\n shouldPadLeft && `${baseClass}--left`,\n shouldPadRight && `${baseClass}--right`,\n negativeLeft && `${baseClass}--negative-left`,\n negativeRight && `${baseClass}--negative-right`,\n className,\n ]\n .filter(Boolean)\n .join(' ')}\n ref={ref}\n >\n {children}\n </div>\n )\n}\n"],"mappings":"AAAA;;;AACA,OAAOA,KAAA,MAAW;AAElB,OAAO;AAYP,MAAMC,SAAA,GAAY;AAElB,OAAO,MAAMC,MAAA,GAAiCC,KAAA;EAC5C,MAAM;IACJC,QAAQ;IACRC,SAAS;IACTC,IAAA,GAAO,IAAI;IACXC,YAAA,GAAe,KAAK;IACpBC,aAAA,GAAgB,KAAK;IACrBC,GAAG;IACHC,KAAA,GAAQ;EAAI,CACb,GAAGP,KAAA;EAEJ,MAAMQ,aAAA,GAAgBL,IAAA,IAAQ,CAACC,YAAA;EAC/B,MAAMK,cAAA,GAAiBF,KAAA,IAAS,CAACF,aAAA;EAEjC,oBACEK,IAAA,CAAC;IACCR,SAAA,EAAW,CACTJ,SAAA,EACAU,aAAA,IAAiB,GAAGV,SAAA,QAAiB,EACrCW,cAAA,IAAkB,GAAGX,SAAA,SAAkB,EACvCM,YAAA,IAAgB,GAAGN,SAAA,iBAA0B,EAC7CO,aAAA,IAAiB,GAAGP,SAAA,kBAA2B,EAC/CI,SAAA,CACD,CACES,MAAM,CAACC,OAAA,EACPC,IAAI,CAAC;IACRP,GAAA,EAAKA,GAAA;cAEJL;;AAGP","ignoreList":[]}

View File

@@ -0,0 +1,256 @@
import { CheckOptions as TabbableCheckOptions } from 'tabbable';
declare module 'focus-trap' {
export type FocusTargetValue = HTMLElement | SVGElement | string;
export type FocusTargetValueOrFalse = FocusTargetValue | false;
/**
* A DOM node, a selector string (which will be passed to
* `document.querySelector()` to find the DOM node), or a function that
* returns a DOM node.
*/
export type FocusTarget = FocusTargetValue | (() => FocusTargetValue);
/**
* A DOM node, a selector string (which will be passed to
* `document.querySelector()` to find the DOM node), `false` to explicitly indicate
* an opt-out, or a function that returns a DOM node or `false`.
*/
export type FocusTargetOrFalse = FocusTargetValueOrFalse | (() => FocusTargetValueOrFalse);
type MouseEventToBoolean = (event: MouseEvent | TouchEvent) => boolean;
type KeyboardEventToBoolean = (event: KeyboardEvent) => boolean;
/** tabbable options supported by focus-trap. */
export interface FocusTrapTabbableOptions extends TabbableCheckOptions {
}
export interface Options {
/**
* A function that will be called **before** sending focus to the
* target element upon activation.
*/
onActivate?: () => void;
/**
* A function that will be called **after** focus has been sent to the
* target element upon activation.
*/
onPostActivate?: () => void;
/**
* A function that will be called immediately after the trap's state is updated to be paused.
*/
onPause?: () => void;
/**
* A function that will be called after the trap has been completely paused and is no longer
* managing/trapping focus.
*/
onPostPause?: () => void;
/**
* A function that will be called immediately after the trap's state is updated to be active
* again, but prior to updating its knowledge of what nodes are tabbable within its containers,
* and prior to actively managing/trapping focus.
*/
onUnpause?: () => void;
/**
* A function that will be called after the trap has been completely unpaused and is once
* again managing/trapping focus.
*/
onPostUnpause?: () => void;
/**
* A function for determining if it is safe to send focus to the focus trap
* or not.
*
* It should return a promise that only resolves once all the listed `containers`
* are able to receive focus.
*
* The purpose of this is to prevent early focus-trap activation on animated
* dialogs that fade in and out. When a dialog fades in, there is a brief delay
* between the activation of the trap and the trap element being focusable.
*/
checkCanFocusTrap?: (
containers: Array<HTMLElement | SVGElement>
) => Promise<void>;
/**
* A function that will be called **before** sending focus to the
* trigger element upon deactivation.
*/
onDeactivate?: () => void;
/**
* A function that will be called after the trap is deactivated, after `onDeactivate`.
* If `returnFocus` was set, it will be called **after** focus has been sent to the trigger
* element upon deactivation; otherwise, it will be called after deactivation completes.
*/
onPostDeactivate?: () => void;
/**
* A function for determining if it is safe to send focus back to the `trigger` element.
*
* It should return a promise that only resolves once `trigger` is focusable.
*
* The purpose of this is to prevent the focus being sent to an animated trigger element too early.
* If a trigger element fades in upon trap deactivation, there is a brief delay between the deactivation
* of the trap and when the trigger element is focusable.
*
* `trigger` will be either the node that had focus prior to the trap being activated,
* or the result of the `setReturnFocus` option, if configured.
*
* This handler is **not** called if the `returnFocusOnDeactivate` configuration option
* (or the `returnFocus` deactivation option) is falsy.
*/
checkCanReturnFocus?: (trigger: HTMLElement | SVGElement) => Promise<void>;
/**
* By default, when a focus trap is activated the first element in the
* focus trap's tab order will receive focus. With this option you can
* specify a different element to receive that initial focus, or use `false`
* for no initially focused element at all.
*
* NOTE: Setting this option to `false` (or a function that returns `false`)
* will prevent the `fallbackFocus` option from being used.
*
* Setting this option to `undefined` (or a function that returns `undefined`)
* will result in the default behavior.
*/
initialFocus?: FocusTargetOrFalse | undefined | (() => void);
/**
* By default, an error will be thrown if the focus trap contains no
* elements in its tab order. With this option you can specify a
* fallback element to programmatically receive focus if no other
* tabbable elements are found. For example, you may want a popover's
* `<div>` to receive focus if the popover's content includes no
* tabbable elements. *Make sure the fallback element has a negative
* `tabindex` so it can be programmatically focused.
*
* NOTE: If `initialFocus` is `false` (or a function that returns `false`),
* this function will not be called when the trap is activated, and no element
* will be initially focused. This function may still be called while the trap
* is active if things change such that there are no longer any tabbable nodes
* in the trap.
*/
fallbackFocus?: FocusTarget;
/**
* Default: `true`. If `false`, when the trap is deactivated,
* focus will *not* return to the element that had focus before activation.
*/
returnFocusOnDeactivate?: boolean;
/**
* By default, focus trap on deactivation will return to the element
* that was focused before activation.
*/
setReturnFocus?:
| FocusTargetValueOrFalse
| ((
nodeFocusedBeforeActivation: HTMLElement | SVGElement
) => FocusTargetValueOrFalse);
/**
* Default: `true`. If `false` or returns `false`, the `Escape` key will not trigger
* deactivation of the focus trap. This can be useful if you want
* to force the user to make a decision instead of allowing an easy
* way out. Note that if a function is given, it's only called if the ESC key
* was pressed.
*/
escapeDeactivates?: boolean | KeyboardEventToBoolean;
/**
* If `true` or returns `true`, a click outside the focus trap will
* deactivate the focus trap and allow the click event to do its thing (i.e.
* to pass-through to the element that was clicked). This option **takes
* precedence** over `allowOutsideClick` when it's set to `true`, causing
* that option to be ignored. Default: `false`.
*/
clickOutsideDeactivates?: boolean | MouseEventToBoolean;
/**
* If set and is or returns `true`, a click outside the focus trap will not
* be prevented, even when `clickOutsideDeactivates` is `false`. When
* `clickOutsideDeactivates` is `true`, this option is **ignored** (i.e.
* if it's a function, it will not be called). Use this option to control
* if (and even which) clicks are allowed outside the trap in conjunction
* with `clickOutsideDeactivates: false`. Default: `false`.
*/
allowOutsideClick?: boolean | MouseEventToBoolean;
/**
* By default, focus() will scroll to the element if not in viewport.
* It can produce unintended effects like scrolling back to the top of a modal.
* If set to `true`, no scroll will happen.
*/
preventScroll?: boolean;
/**
* Default: `true`. Delays the autofocus when the focus trap is activated.
* This prevents elements within the focusable element from capturing
* the event that triggered the focus trap activation.
*/
delayInitialFocus?: boolean;
/**
* Default: `window.document`. Document where the focus trap will be active.
* This allows to use FocusTrap in an iFrame context.
*/
document?: Document;
/**
* Specific tabbable options configurable on focus-trap.
*/
tabbableOptions?: FocusTrapTabbableOptions;
/**
* Define the global trap stack. This makes it possible to share the same stack
* in multiple instances of `focus-trap` in the same page such that
* auto-activation/pausing of traps is properly coordinated among all instances
* as activating a trap when another is already active should result in the other
* being auto-paused. By default, each instance will have its own internal stack,
* leading to conflicts if they each try to trap the focus at the same time.
*/
trapStack?: Array<FocusTrap>;
/**
* Determines if the given keyboard event is a "tab forward" event that will move
* the focus to the next trapped element in tab order. Defaults to the `TAB` key.
* Use this to override the trap's behavior if you want to use arrow keys to control
* keyboard navigation within the trap, for example. Also see `isKeyBackward()` option.
*/
isKeyForward?: KeyboardEventToBoolean;
/**
* Determines if the given keyboard event is a "tab backward" event that will move
* the focus to the previous trapped element in tab order. Defaults to the `SHIFT+TAB` key.
* Use this to override the trap's behavior if you want to use arrow keys to control
* keyboard navigation within the trap, for example. Also see `isKeyForward()` option.
*/
isKeyBackward?: KeyboardEventToBoolean;
}
type ActivateOptions = Pick<Options, 'onActivate' | 'onPostActivate' | 'checkCanFocusTrap'>;
type PauseOptions = Pick<Options, 'onPause' | 'onPostPause'>;
type UnpauseOptions = Pick<Options, 'onUnpause' | 'onPostUnpause'>;
interface DeactivateOptions extends Pick<Options, 'onDeactivate' | 'onPostDeactivate' | 'checkCanReturnFocus'> {
returnFocus?: boolean;
}
export interface FocusTrap {
active: boolean,
paused: boolean,
activate(activateOptions?: ActivateOptions): FocusTrap;
deactivate(deactivateOptions?: DeactivateOptions): FocusTrap;
pause(pauseOptions?: PauseOptions): FocusTrap;
unpause(unpauseOptions?: UnpauseOptions): FocusTrap;
updateContainerElements(containerElements: HTMLElement | SVGElement | string | Array<HTMLElement | SVGElement | string>): FocusTrap;
}
/**
* Returns a new focus trap on `element`.
*
* @param element
* The element to be the focus trap, or a selector that will be used to
* find the element.
*/
export function createFocusTrap(
element: HTMLElement | SVGElement | string | Array<HTMLElement | SVGElement | string>,
userOptions?: Options
): FocusTrap;
}

View File

@@ -0,0 +1,118 @@
const color = require('kleur');
const Prompt = require('./prompt');
const { style, clear } = require('../util');
const { cursor, erase } = require('sisteransi');
/**
* TogglePrompt Base Element
* @param {Object} opts Options
* @param {String} opts.message Message
* @param {Boolean} [opts.initial=false] Default value
* @param {String} [opts.active='no'] Active label
* @param {String} [opts.inactive='off'] Inactive label
* @param {Stream} [opts.stdin] The Readable stream to listen to
* @param {Stream} [opts.stdout] The Writable stream to write readline data to
*/
class TogglePrompt extends Prompt {
constructor(opts={}) {
super(opts);
this.msg = opts.message;
this.value = !!opts.initial;
this.active = opts.active || 'on';
this.inactive = opts.inactive || 'off';
this.initialValue = this.value;
this.render();
}
reset() {
this.value = this.initialValue;
this.fire();
this.render();
}
exit() {
this.abort();
}
abort() {
this.done = this.aborted = true;
this.fire();
this.render();
this.out.write('\n');
this.close();
}
submit() {
this.done = true;
this.aborted = false;
this.fire();
this.render();
this.out.write('\n');
this.close();
}
deactivate() {
if (this.value === false) return this.bell();
this.value = false;
this.render();
}
activate() {
if (this.value === true) return this.bell();
this.value = true;
this.render();
}
delete() {
this.deactivate();
}
left() {
this.deactivate();
}
right() {
this.activate();
}
down() {
this.deactivate();
}
up() {
this.activate();
}
next() {
this.value = !this.value;
this.fire();
this.render();
}
_(c, key) {
if (c === ' ') {
this.value = !this.value;
} else if (c === '1') {
this.value = true;
} else if (c === '0') {
this.value = false;
} else return this.bell();
this.render();
}
render() {
if (this.closed) return;
if (this.firstRender) this.out.write(cursor.hide);
else this.out.write(clear(this.outputText, this.out.columns));
super.render();
this.outputText = [
style.symbol(this.done, this.aborted),
color.bold(this.msg),
style.delimiter(this.done),
this.value ? this.inactive : color.cyan().underline(this.inactive),
color.gray('/'),
this.value ? color.cyan().underline(this.active) : this.active
].join(' ');
this.out.write(erase.line + cursor.to(0) + this.outputText);
}
}
module.exports = TogglePrompt;

View File

@@ -0,0 +1,133 @@
import type { $ZodStringFormats } from "../core/checks.js";
import type * as errors from "../core/errors.js";
import * as util from "../core/util.js";
const error: () => errors.$ZodErrorMap = () => {
const Sizable: Record<string, { unit: string; verb: string }> = {
string: { unit: "توکي", verb: "ولري" },
file: { unit: "بایټس", verb: "ولري" },
array: { unit: "توکي", verb: "ولري" },
set: { unit: "توکي", verb: "ولري" },
};
function getSizing(origin: string): { unit: string; verb: string } | null {
return Sizable[origin] ?? null;
}
const parsedType = (data: any): string => {
const t = typeof data;
switch (t) {
case "number": {
return Number.isNaN(data) ? "NaN" : "عدد";
}
case "object": {
if (Array.isArray(data)) {
return "ارې";
}
if (data === null) {
return "null";
}
if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) {
return data.constructor.name;
}
}
}
return t;
};
const Nouns: {
[k in $ZodStringFormats | (string & {})]?: string;
} = {
regex: "ورودي",
email: "بریښنالیک",
url: "یو آر ال",
emoji: "ایموجي",
uuid: "UUID",
uuidv4: "UUIDv4",
uuidv6: "UUIDv6",
nanoid: "nanoid",
guid: "GUID",
cuid: "cuid",
cuid2: "cuid2",
ulid: "ULID",
xid: "XID",
ksuid: "KSUID",
datetime: "نیټه او وخت",
date: "نېټه",
time: "وخت",
duration: "موده",
ipv4: "د IPv4 پته",
ipv6: "د IPv6 پته",
cidrv4: "د IPv4 ساحه",
cidrv6: "د IPv6 ساحه",
base64: "base64-encoded متن",
base64url: "base64url-encoded متن",
json_string: "JSON متن",
e164: "د E.164 شمېره",
jwt: "JWT",
template_literal: "ورودي",
};
return (issue) => {
switch (issue.code) {
case "invalid_type":
return `ناسم ورودي: باید ${issue.expected} وای, مګر ${parsedType(issue.input)} ترلاسه شو`;
case "invalid_value":
if (issue.values.length === 1) {
return `ناسم ورودي: باید ${util.stringifyPrimitive(issue.values[0])} وای`;
}
return `ناسم انتخاب: باید یو له ${util.joinValues(issue.values, "|")} څخه وای`;
case "too_big": {
const adj = issue.inclusive ? "<=" : "<";
const sizing = getSizing(issue.origin);
if (sizing) {
return `ډیر لوی: ${issue.origin ?? "ارزښت"} باید ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عنصرونه"} ولري`;
}
return `ډیر لوی: ${issue.origin ?? "ارزښت"} باید ${adj}${issue.maximum.toString()} وي`;
}
case "too_small": {
const adj = issue.inclusive ? ">=" : ">";
const sizing = getSizing(issue.origin);
if (sizing) {
return `ډیر کوچنی: ${issue.origin} باید ${adj}${issue.minimum.toString()} ${sizing.unit} ولري`;
}
return `ډیر کوچنی: ${issue.origin} باید ${adj}${issue.minimum.toString()} وي`;
}
case "invalid_format": {
const _issue = issue as errors.$ZodStringFormatIssues;
if (_issue.format === "starts_with") {
return `ناسم متن: باید د "${_issue.prefix}" سره پیل شي`;
}
if (_issue.format === "ends_with") {
return `ناسم متن: باید د "${_issue.suffix}" سره پای ته ورسيږي`;
}
if (_issue.format === "includes") {
return `ناسم متن: باید "${_issue.includes}" ولري`;
}
if (_issue.format === "regex") {
return `ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`;
}
return `${Nouns[_issue.format] ?? issue.format} ناسم دی`;
}
case "not_multiple_of":
return `ناسم عدد: باید د ${issue.divisor} مضرب وي`;
case "unrecognized_keys":
return `ناسم ${issue.keys.length > 1 ? "کلیډونه" : "کلیډ"}: ${util.joinValues(issue.keys, ", ")}`;
case "invalid_key":
return `ناسم کلیډ په ${issue.origin} کې`;
case "invalid_union":
return `ناسمه ورودي`;
case "invalid_element":
return `ناسم عنصر په ${issue.origin} کې`;
default:
return `ناسمه ورودي`;
}
};
};
export default function (): { localeError: errors.$ZodErrorMap } {
return {
localeError: error(),
};
}

View File

@@ -0,0 +1 @@
{"version":3,"file":"extractHeightFromImage.d.ts","sourceRoot":"","sources":["../../../src/uploads/image-resizing/extractHeightFromImage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,IAAI,aAAa,EAAE,MAAM,OAAO,CAAA;AAEtD;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,aAAa,EAAE,aAAa,GAAG,MAAM,CAK3E"}

View File

@@ -0,0 +1,9 @@
/**
* Shallow merge two objects.
* Does not mutate the passed in objects.
* Undefined/empty values in the merge object will overwrite existing values.
*
* By default, this merges 2 levels deep.
*/
export declare function merge<T>(initialObj: T, mergeObj: T, levels?: number): T;
//# sourceMappingURL=merge.d.ts.map

View File

@@ -0,0 +1,66 @@
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/** A simple Least Recently Used map */
class LRUMap {
constructor( _maxSize) {this._maxSize = _maxSize;
this._cache = new Map();
}
/** Get the current size of the cache */
get size() {
return this._cache.size;
}
/** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */
get(key) {
const value = this._cache.get(key);
if (value === undefined) {
return undefined;
}
// Remove and re-insert to update the order
this._cache.delete(key);
this._cache.set(key, value);
return value;
}
/** Insert an entry and evict an older entry if we've reached maxSize */
set(key, value) {
if (this._cache.size >= this._maxSize) {
// keys() returns an iterator in insertion order so keys().next() gives us the oldest key
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const nextKey = this._cache.keys().next().value;
this._cache.delete(nextKey);
}
this._cache.set(key, value);
}
/** Remove an entry and return the entry if it was in the cache */
remove(key) {
const value = this._cache.get(key);
if (value) {
this._cache.delete(key);
}
return value;
}
/** Clear all entries */
clear() {
this._cache.clear();
}
/** Get all the keys */
keys() {
return Array.from(this._cache.keys());
}
/** Get all the values */
values() {
const values = [];
this._cache.forEach(value => values.push(value));
return values;
}
}
exports.LRUMap = LRUMap;
//# sourceMappingURL=lru.js.map

View File

@@ -0,0 +1,126 @@
# md-to-react-email
Read the documentation [here](https://md2re.codeskills.dev/)
## Description
md-to-react-email is a lightweight utility for converting [Markdown](https://www.markdownguide.org/) into valid JSX that can be used in [React-email](https://react.email) or [JSX-email](https://jsx.email) templates. This tool simplifies the process of creating responsive and customizable email templates by leveraging the power of React and Markdown.
**Note**: Starting from `version 4`, `md-to-react-email` uses [`Marked`](https://marked.js.org/) for markdown transformation. see all changes [here](/CHANGELOG.md)
### Support
The following markdown flavors are supported
- Offical markdown flavour
## Installation
Install from your command line.
#### With yarn
```sh
yarn add md-to-react-email
```
#### With npm
```sh
npm install md-to-react-email
```
## Features
### Functions:
- `camelToKebabCase`: converts strings from camelcase ['thisIsCamelCase'] to kebab case ['this-is-kebab-case']
- `parseCssInJsToInlineCss`: converts css styles from css-in-js to inline css e.g fontSize: "18px" => font-size: 18px;
- `parseMarkdownToJSX`: parses markdown to valid JSX for the client (i.e the browser)
### Components:
- `EmailMarkdown`: a react component that takes in markdown input and parses it directly in your code base
## Usage:
- Directly as [`React-email`](https://react.email) or [`JSX-email`](https://jsx.email) component
```
import {EmailMarkdown} from "md-to-react-email"
export default function EmailTemplate() {
return (
<Email>
<Head />
<Section>
<EmailMarkdown markdown={`# Hello, World!`} />
</Section>
</Email>
)
}
```
- Directly into react-email template
```
import {parseMarkdownToJSX} from "md-to-react-email"
const markdown = `# Hello World`
const parsedReactMail = parseMarkdownToJSX({markdown})
console.log(parsedReactMail) // `<h1 style="...valid inline CSS...">Hello, World!</h1>`
```
## Components
md-to-react-email contains pre-defined react and html components for the email template structure and styling. You can modify these components to customize the look and feel of your email template.
The following components are available for customization:
- Headers (h1 - h6)
- BlockQuotes
- Text: paragraphs, bold and italic text
- Links
- Code: Code blocks and inline code
- Lists: ul, ol, li
- Image
- Line-breaks (br)
- Horizontal-rule (hr)
- Table: table, thead, tbody, th, td, tr
- Strikethrough
## Supported Email Clients
The provided React components and default styling are designed to work well across various email clients and providers. However, due to the inconsistent support for modern web standards in different email clients, it's recommended to test your email templates in multiple clients to ensure compatibility.
The following email clients are known to be supported:
- Gmail
- Apple Mail
- Outlook (desktop and web)
- Yahoo Mail
- HEY Mail
- Super Human
| <img src="https://react.email/static/icons/gmail.svg" width="48px" height="48px" alt="Gmail logo"> | <img src="https://react.email/static/icons/apple-mail.svg" width="48px" height="48px" alt="Apple Mail"> | <img src="https://react.email/static/icons/outlook.svg" width="48px" height="48px" alt="Outlook logo"> | <img src="https://react.email/static/icons/yahoo-mail.svg" width="48px" height="48px" alt="Yahoo! Mail logo"> | <img src="https://react.email/static/icons/hey.svg" width="48px" height="48px" alt="HEY logo"> | <img src="https://react.email/static/icons/superhuman.svg" width="48px" height="48px" alt="Superhuman logo"> |
| -------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| Gmail ✔ | Apple Mail ✔ | Outlook ✔ | Yahoo! Mail ✔ | HEY ✔ | Superhuman ✔ |
## Contributing
Contributions to md-to-react-email are welcome! If you find a bug, have suggestions for improvements, or want to add new features, feel free to open an issue or submit a pull request. Please make sure to follow the existing coding style and conventions.
When submitting a pull request, provide a clear description of the changes made and ensure that all tests pass. Adding appropriate tests for new features or bug fixes is highly appreciated.
## Bugs and Feature Requests
For bugs and feature requests, [please create an issue](https://github.com/codeskills-dev/md-to-react-mail/issues/new/choose).
## Author
- Paul Ehikhuemen ([@pauloe_me](https://twitter.com/pauloe_me))
## License
`md-to-react-email` is licensed under the MIT License.

View File

@@ -0,0 +1 @@
const e="NODE_ENV".trim(),s="development"===process.env[e],o=process.argv.includes("build"),r=s||o;export{s as isDevelopment,r as isDevelopmentOrNextBuild,o as isNextBuild};

View File

@@ -0,0 +1,22 @@
/**
* @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 ScanQrCode = createLucideIcon("ScanQrCode", [
["path", { d: "M17 12v4a1 1 0 0 1-1 1h-4", key: "uk4fdo" }],
["path", { d: "M17 3h2a2 2 0 0 1 2 2v2", key: "4qcy5o" }],
["path", { d: "M17 8V7", key: "q2g9wo" }],
["path", { d: "M21 17v2a2 2 0 0 1-2 2h-2", key: "6vwrx8" }],
["path", { d: "M3 7V5a2 2 0 0 1 2-2h2", key: "aa7l1z" }],
["path", { d: "M7 17h.01", key: "19xn7k" }],
["path", { d: "M7 21H5a2 2 0 0 1-2-2v-2", key: "ioqczr" }],
["rect", { x: "7", y: "7", width: "5", height: "5", rx: "1", key: "m9kyts" }]
]);
export { ScanQrCode as default };
//# sourceMappingURL=scan-qr-code.js.map

View File

@@ -0,0 +1,40 @@
# @jridgewell/resolve-uri
> Resolve a URI relative to an optional base URI
Resolve any combination of absolute URIs, protocol-realtive URIs, absolute paths, or relative paths.
## Installation
```sh
npm install @jridgewell/resolve-uri
```
## Usage
```typescript
function resolve(input: string, base?: string): string;
```
```js
import resolve from '@jridgewell/resolve-uri';
resolve('foo', 'https://example.com'); // => 'https://example.com/foo'
```
| Input | Base | Resolution | Explanation |
|-----------------------|-------------------------|--------------------------------|--------------------------------------------------------------|
| `https://example.com` | _any_ | `https://example.com/` | Input is normalized only |
| `//example.com` | `https://base.com/` | `https://example.com/` | Input inherits the base's protocol |
| `//example.com` | _rest_ | `//example.com/` | Input is normalized only |
| `/example` | `https://base.com/` | `https://base.com/example` | Input inherits the base's origin |
| `/example` | `//base.com/` | `//base.com/example` | Input inherits the base's host and remains protocol relative |
| `/example` | _rest_ | `/example` | Input is normalized only |
| `example` | `https://base.com/dir/` | `https://base.com/dir/example` | Input is joined with the base |
| `example` | `https://base.com/file` | `https://base.com/example` | Input is joined with the base without its file |
| `example` | `//base.com/dir/` | `//base.com/dir/example` | Input is joined with the base's last directory |
| `example` | `//base.com/file` | `//base.com/example` | Input is joined with the base without its file |
| `example` | `/base/dir/` | `/base/dir/example` | Input is joined with the base's last directory |
| `example` | `/base/file` | `/base/example` | Input is joined with the base without its file |
| `example` | `base/dir/` | `base/dir/example` | Input is joined with the base's last directory |
| `example` | `base/file` | `base/example` | Input is joined with the base without its file |

View File

@@ -0,0 +1 @@
{"version":3,"file":"chevrons-up-down.js","sources":["../../../src/icons/chevrons-up-down.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name ChevronsUpDown\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8cGF0aCBkPSJtNyAxNSA1IDUgNS01IiAvPgogIDxwYXRoIGQ9Im03IDkgNS01IDUgNSIgLz4KPC9zdmc+Cg==) - https://lucide.dev/icons/chevrons-up-down\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 ChevronsUpDown = createLucideIcon('ChevronsUpDown', [\n ['path', { d: 'm7 15 5 5 5-5', key: '1hf1tw' }],\n ['path', { d: 'm7 9 5-5 5 5', key: 'sgt6xg' }],\n]);\n\nexport default ChevronsUpDown;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAiB,iBAAiB,gBAAkB,CAAA,CAAA,CAAA;AAAA,CAAA,CACxD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAiB,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,CAC9C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAgB,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC/C,CAAC,CAAA,CAAA;;"}

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"file":"scale-3d.js","sources":["../../../src/icons/scale-3d.ts"],"sourcesContent":["import createLucideIcon from '../createLucideIcon';\n\n/**\n * @component @name Scale3d\n * @description Lucide SVG icon component, renders SVG Element with children.\n *\n * @preview ![img](data:image/svg+xml;base64,PHN2ZyAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogIHdpZHRoPSIyNCIKICBoZWlnaHQ9IjI0IgogIHZpZXdCb3g9IjAgMCAyNCAyNCIKICBmaWxsPSJub25lIgogIHN0cm9rZT0iIzAwMCIgc3R5bGU9ImJhY2tncm91bmQtY29sb3I6ICNmZmY7IGJvcmRlci1yYWRpdXM6IDJweCIKICBzdHJva2Utd2lkdGg9IjIiCiAgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIgogIHN0cm9rZS1saW5lam9pbj0icm91bmQiCj4KICA8Y2lyY2xlIGN4PSIxOSIgY3k9IjE5IiByPSIyIiAvPgogIDxjaXJjbGUgY3g9IjUiIGN5PSI1IiByPSIyIiAvPgogIDxwYXRoIGQ9Ik01IDd2MTJoMTIiIC8+CiAgPHBhdGggZD0ibTUgMTkgNi02IiAvPgo8L3N2Zz4K) - https://lucide.dev/icons/scale-3d\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 Scale3d = createLucideIcon('Scale3d', [\n ['circle', { cx: '19', cy: '19', r: '2', key: '17f5cg' }],\n ['circle', { cx: '5', cy: '5', r: '2', key: '1gwv83' }],\n ['path', { d: 'M5 7v12h12', key: 'vtaa4r' }],\n ['path', { d: 'm5 19 6-6', key: 'jh6hbb' }],\n]);\n\nexport default Scale3d;\n"],"names":[],"mappings":";;;;;;;;;AAaM,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAU,iBAAiB,SAAW,CAAA,CAAA,CAAA;AAAA,CAC1C,CAAA,CAAC,QAAU,CAAA,CAAA,CAAA,CAAE,EAAI,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAM,CAAI,CAAA,CAAA,CAAA,IAAA,CAAM,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,GAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAU,CAAA,CAAA;AAAA,CACxD,CAAA,CAAC,QAAU,CAAA,CAAA,CAAA,CAAE,EAAI,CAAA,CAAA,CAAA,CAAA,CAAA,EAAK,CAAI,CAAA,CAAA,CAAA,GAAA,CAAK,CAAA,CAAG,EAAA,CAAA,CAAA,CAAA,CAAA,CAAK,GAAK,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,EAAU,CAAA,CAAA;AAAA,CAAA,CACtD,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAc,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA,CAAA;AAAA,CAAA,CAC3C,CAAC,CAAA,CAAA,CAAA,CAAA,CAAA,CAAQ,CAAA,CAAA,CAAA,CAAE,GAAG,CAAa,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAA,CAAK,UAAU,CAAA;AAC5C,CAAC,CAAA,CAAA;;"}

View File

@@ -0,0 +1,39 @@
'use strict'
const { test } = require('tap')
const { join } = require('node:path')
const { fork } = require('node:child_process')
const { once } = require('./helper')
const writer = require('flush-write-stream')
const pino = require('..')
test('do not use SonicBoom is someone tampered with process.stdout.write', async ({ not }) => {
let actual = ''
const child = fork(join(__dirname, 'fixtures', 'stdout-hack-protection.js'), { silent: true })
child.stdout.pipe(writer((s, enc, cb) => {
actual += s
cb()
}))
await once(child, 'close')
not(actual.match(/^hack/), null)
})
test('do not use SonicBoom is someone has passed process.stdout to pino', async ({ equal }) => {
const logger = pino(process.stdout)
equal(logger[pino.symbols.streamSym], process.stdout)
})
test('do not crash if process.stdout has no fd', async ({ teardown }) => {
const fd = process.stdout.fd
delete process.stdout.fd
teardown(function () { process.stdout.fd = fd })
pino()
})
test('use fd=1 if process.stdout has no fd in pino.destination() (worker case)', async ({ teardown }) => {
const fd = process.stdout.fd
delete process.stdout.fd
teardown(function () { process.stdout.fd = fd })
pino.destination()
})

View File

@@ -0,0 +1,742 @@
'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import { dequal } from 'dequal/lite'; // lite: no need for Map and Set support
import { useRouter } from 'next/navigation.js';
import { serialize } from 'object-to-formdata';
import { deepCopyObjectSimpleWithoutReactComponents, getDataByPath as getDataByPathFunc, getSiblingData as getSiblingDataFunc, hasDraftValidationEnabled, reduceFieldsToValues, wait } from 'payload/shared';
import React, { useCallback, useEffect, useReducer, useRef, useState } from 'react';
import { toast } from 'sonner';
import { FieldErrorsToast } from '../../elements/Toasts/fieldErrors.js';
import { useDebouncedEffect } from '../../hooks/useDebouncedEffect.js';
import { useEffectEvent } from '../../hooks/useEffectEvent.js';
import { useQueue } from '../../hooks/useQueue.js';
import { useThrottledEffect } from '../../hooks/useThrottledEffect.js';
import { useAuth } from '../../providers/Auth/index.js';
import { useConfig } from '../../providers/Config/index.js';
import { useDocumentInfo } from '../../providers/DocumentInfo/index.js';
import { useLocale } from '../../providers/Locale/index.js';
import { useOperation } from '../../providers/Operation/index.js';
import { useRouteTransition } from '../../providers/RouteTransition/index.js';
import { useServerFunctions } from '../../providers/ServerFunctions/index.js';
import { useTranslation } from '../../providers/Translation/index.js';
import { useUploadHandlers } from '../../providers/UploadHandlers/index.js';
import { abortAndIgnore, handleAbortRef } from '../../utilities/abortAndIgnore.js';
import { requests } from '../../utilities/api.js';
import { BackgroundProcessingContext, DocumentFormContext, FormContext, FormFieldsContext, FormWatchContext, InitializingContext, ModifiedContext, ProcessingContext, SubmittedContext, useDocumentForm } from './context.js';
import { errorMessages } from './errorMessages.js';
import { fieldReducer } from './fieldReducer.js';
import { initContextState } from './initContextState.js';
const baseClass = 'form';
export const Form = props => {
const {
id,
collectionSlug,
docConfig,
docPermissions,
getDocPreferences,
globalSlug
} = useDocumentInfo();
const validateDrafts = hasDraftValidationEnabled(docConfig);
const {
action,
beforeSubmit,
children,
className,
disabled: disabledFromProps,
disableSuccessStatus,
disableValidationOnSubmit,
// fields: fieldsFromProps = collection?.fields || global?.fields,
el,
handleResponse,
initialState,
isDocumentForm,
isInitializing: initializingFromProps,
onChange,
onSubmit,
onSuccess,
redirect,
submitted: submittedFromProps,
uuid,
waitForAutocomplete
} = props;
const method = 'method' in props ? props?.method : undefined;
const router = useRouter();
const documentForm = useDocumentForm();
const {
code: locale
} = useLocale();
const {
i18n,
t
} = useTranslation();
const {
refreshCookie,
user
} = useAuth();
const operation = useOperation();
const {
queueTask
} = useQueue();
const {
getFormState
} = useServerFunctions();
const {
startRouteTransition
} = useRouteTransition();
const {
getUploadHandler
} = useUploadHandlers();
const {
config
} = useConfig();
const [disabled, setDisabled] = useState(disabledFromProps || false);
const [isMounted, setIsMounted] = useState(false);
const [submitted, setSubmitted] = useState(false);
/**
* Tracks wether the form state passes validation.
* For example the state could be submitted but invalid as field errors have been returned.
*/
const [isValid, setIsValid] = useState(true);
const [initializing, setInitializing] = useState(initializingFromProps);
const [processing, setProcessing] = useState(false);
/**
* Determines whether the form is processing asynchronously in the background, e.g. autosave is running.
* Useful to determine whether to disable the form or queue other processes while in flight, e.g. disable manual submits while an autosave is running.
*/
const [backgroundProcessing, _setBackgroundProcessing] = useState(false);
/**
* A ref that can be read within the `setModified` interceptor.
* Dependents of this state can read it immediately without needing to wait for a render cycle.
*/
const backgroundProcessingRef = useRef(backgroundProcessing);
/**
* Flag to track if the form was modified _during a submission_, e.g. while autosave is running.
* Useful in order to avoid resetting `modified` to false wrongfully after a submit.
* For example, if the user modifies a field while the a background process (autosave) is running,
* we need to ensure that after the submit completes, the `modified` state remains true.
*/
const modifiedWhileProcessingRef = useRef(false);
/**
* Intercept the `setBackgroundProcessing` method to keep the ref in sync.
* See the `backgroundProcessingRef` for more details.
*/
const setBackgroundProcessing = useCallback(backgroundProcessing_0 => {
backgroundProcessingRef.current = backgroundProcessing_0;
_setBackgroundProcessing(backgroundProcessing_0);
}, []);
const [modified, _setModified] = useState(false);
/**
* Intercept the `setModified` method to track whether the event happened during background processing.
* See the `modifiedWhileProcessingRef` ref for more details.
*/
const setModified = useCallback(modified_0 => {
if (backgroundProcessingRef.current) {
modifiedWhileProcessingRef.current = true;
}
_setModified(modified_0);
}, []);
const formRef = useRef(null);
const contextRef = useRef({});
const abortResetFormRef = useRef(null);
const isFirstRenderRef = useRef(true);
const fieldsReducer = useReducer(fieldReducer, {}, () => initialState);
const [formState, dispatchFields] = fieldsReducer;
contextRef.current.fields = formState;
const prevFormState = useRef(formState);
const validateForm = useCallback(async () => {
const validatedFieldState = {};
let isValid_0 = true;
const data = contextRef.current.getData();
const validationPromises = Object.entries(contextRef.current.fields).map(async ([path, field]) => {
const validatedField = field;
const pathSegments = path ? path.split('.') : [];
if (field.passesCondition !== false) {
let validationResult = validatedField.valid;
if ('validate' in field && typeof field.validate === 'function') {
let valueToValidate = field.value;
if (field?.rows && Array.isArray(field.rows)) {
valueToValidate = contextRef.current.getDataByPath(path);
}
validationResult = await field.validate(valueToValidate, {
...field,
id,
collectionSlug,
// If there is a parent document form, we can get the data from that form
blockData: undefined,
data: documentForm?.getData ? documentForm.getData() : data,
event: 'submit',
operation,
path: pathSegments,
preferences: {},
req: {
payload: {
config
},
t,
user
},
siblingData: contextRef.current.getSiblingData(path)
});
if (typeof validationResult === 'string') {
validatedField.errorMessage = validationResult;
validatedField.valid = false;
} else {
validatedField.valid = true;
validatedField.errorMessage = undefined;
}
}
if (validatedField.valid === false) {
isValid_0 = false;
}
}
validatedFieldState[path] = validatedField;
});
await Promise.all(validationPromises);
if (!dequal(contextRef.current.fields, validatedFieldState)) {
dispatchFields({
type: 'REPLACE_STATE',
state: validatedFieldState
});
}
setIsValid(isValid_0);
return isValid_0;
}, [collectionSlug, config, dispatchFields, id, operation, t, user, documentForm]);
const submit = useCallback(async (options, e) => {
const {
acceptValues = true,
action: actionArg = action,
context,
disableFormWhileProcessing = true,
disableSuccessStatus: disableSuccessStatusFromArgs,
method: methodToUse = method,
overrides: overridesFromArgs = {},
skipValidation
} = options || {};
const disableToast = disableSuccessStatusFromArgs ?? disableSuccessStatus;
if (disabled) {
if (e) {
e.preventDefault();
}
return;
}
// create new toast promise which will resolve manually later
let errorToast, successToast;
const promise = new Promise((resolve, reject) => {
successToast = resolve;
errorToast = reject;
});
const hasFormSubmitAction = actionArg || typeof action === 'string' || typeof action === 'function';
if (redirect || disableToast || !hasFormSubmitAction) {
// Do not show submitting toast, as the promise toast may never disappear under these conditions.
// Instead, make successToast() or errorToast() throw toast.success / toast.error
successToast = data_0 => toast.success(data_0);
errorToast = data_1 => toast.error(data_1);
} else {
toast.promise(promise, {
error: data_2 => {
return data_2;
},
loading: t('general:submitting'),
success: data_3 => {
return data_3;
}
});
}
if (e) {
e.stopPropagation();
e.preventDefault();
}
if (disableFormWhileProcessing) {
setProcessing(true);
setDisabled(true);
}
if (waitForAutocomplete) {
await wait(100);
}
const data_4 = reduceFieldsToValues(contextRef.current.fields, true);
const serializableFormState = deepCopyObjectSimpleWithoutReactComponents(contextRef.current.fields, {
excludeFiles: true
});
// Execute server side validations
if (Array.isArray(beforeSubmit)) {
let revalidatedFormState;
await beforeSubmit.reduce(async (priorOnChange, beforeSubmitFn) => {
await priorOnChange;
const result = await beforeSubmitFn({
formState: serializableFormState
});
revalidatedFormState = result;
}, Promise.resolve());
const isValid_1 = Object.entries(revalidatedFormState).every(([, field_0]) => field_0.valid !== false);
setIsValid(isValid_1);
if (!isValid_1) {
setProcessing(false);
setSubmitted(true);
setDisabled(false);
return dispatchFields({
type: 'REPLACE_STATE',
state: revalidatedFormState
});
}
}
const isValid_2 = skipValidation || disableValidationOnSubmit ? true : await contextRef.current.validateForm();
setIsValid(isValid_2);
// If not valid, prevent submission
if (!isValid_2) {
errorToast(t('error:correctInvalidFields'));
setProcessing(false);
setSubmitted(true);
setDisabled(false);
return;
}
let overrides = {};
if (typeof overridesFromArgs === 'function') {
overrides = overridesFromArgs(contextRef.current.fields);
} else if (typeof overridesFromArgs === 'object') {
overrides = overridesFromArgs;
}
// If submit handler comes through via props, run that
if (onSubmit) {
for (const [key, value] of Object.entries(overrides)) {
data_4[key] = value;
}
onSubmit(contextRef.current.fields, data_4);
}
if (!hasFormSubmitAction) {
// No action provided, so we should return. An example where this happens are lexical link drawers. Upon submitting the drawer, we
// want to close it without submitting the form. Stuff like validation would be handled by lexical before this, through beforeSubmit
setProcessing(false);
setSubmitted(true);
setDisabled(false);
return;
}
try {
const formData = await contextRef.current.createFormData(overrides, {
data: data_4,
mergeOverrideData: Boolean(typeof overridesFromArgs !== 'function')
});
let res;
if (typeof actionArg === 'string') {
res = await requests[methodToUse.toLowerCase()](actionArg, {
body: formData,
headers: {
'Accept-Language': i18n.language
}
});
} else if (typeof action === 'function') {
res = await action(formData);
}
if (!modifiedWhileProcessingRef.current) {
setModified(false);
} else {
modifiedWhileProcessingRef.current = false;
}
setDisabled(false);
if (typeof handleResponse === 'function') {
handleResponse(res, successToast, errorToast);
return;
}
const contentType = res.headers.get('content-type');
const isJSON = contentType && contentType.indexOf('application/json') !== -1;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let json = {};
if (isJSON) {
json = await res.json();
}
if (res.status < 400) {
if (typeof onSuccess === 'function') {
const newFormState = await onSuccess(json, {
context,
formState: serializableFormState
});
if (newFormState) {
dispatchFields({
type: 'MERGE_SERVER_STATE',
acceptValues,
prevStateRef: prevFormState,
serverState: newFormState
});
}
}
setSubmitted(false);
setProcessing(false);
if (redirect) {
startRouteTransition(() => router.push(redirect));
} else if (!disableToast) {
successToast(json.message || t('general:submissionSuccessful'));
}
} else {
setProcessing(false);
setSubmitted(true);
// When there was an error submitting a draft,
// set the form state to unsubmitted, to not trigger visible form validation on changes after the failed submit.
// Also keep the form as modified so the save button remains enabled for retry.
if (overridesFromArgs['_status'] === 'draft') {
setModified(true);
if (!validateDrafts) {
setSubmitted(false);
}
}
contextRef.current = {
...contextRef.current
}; // triggers rerender of all components that subscribe to form
if (json.message) {
errorToast(json.message);
return;
}
if (Array.isArray(json.errors)) {
const [fieldErrors, nonFieldErrors] = json.errors.reduce(([fieldErrs, nonFieldErrs], err_0) => {
const newFieldErrs = [];
const newNonFieldErrs = [];
if (err_0?.message) {
newNonFieldErrs.push(err_0);
}
if (Array.isArray(err_0?.data?.errors)) {
err_0.data?.errors.forEach(dataError => {
if (dataError?.path) {
newFieldErrs.push(dataError);
} else {
newNonFieldErrs.push(dataError);
}
});
}
return [[...fieldErrs, ...newFieldErrs], [...nonFieldErrs, ...newNonFieldErrs]];
}, [[], []]);
setIsValid(false);
dispatchFields({
type: 'ADD_SERVER_ERRORS',
errors: fieldErrors
});
nonFieldErrors.forEach(err_1 => {
errorToast(/*#__PURE__*/_jsx(FieldErrorsToast, {
errorMessage: err_1.message || t('error:unknown')
}));
});
return;
}
const message = errorMessages?.[res.status] || res?.statusText || t('error:unknown');
errorToast(message);
}
return {
formState: contextRef.current.fields,
res
};
} catch (err) {
console.error('Error submitting form', err); // eslint-disable-line no-console
setProcessing(false);
setSubmitted(true);
setDisabled(false);
errorToast(err.message);
}
}, [beforeSubmit, startRouteTransition, action, disableSuccessStatus, disableValidationOnSubmit, disabled, dispatchFields, handleResponse, method, onSubmit, onSuccess, redirect, router, t, i18n, validateDrafts, waitForAutocomplete, setModified, setSubmitted]);
const getFields = useCallback(() => contextRef.current.fields, []);
const getField = useCallback(path_0 => contextRef.current.fields[path_0], []);
const getData = useCallback(() => reduceFieldsToValues(contextRef.current.fields, true), []);
const getSiblingData = useCallback(path_1 => getSiblingDataFunc(contextRef.current.fields, path_1), []);
const getDataByPath = useCallback(path_2 => getDataByPathFunc(contextRef.current.fields, path_2), []);
const createFormData = useCallback(async (overrides_0, {
data: dataFromArgs,
mergeOverrideData = true
}) => {
let data_5 = dataFromArgs || reduceFieldsToValues(contextRef.current.fields, true);
let file = data_5?.file;
if (docConfig && 'upload' in docConfig && docConfig.upload && file) {
delete data_5.file;
const handler = getUploadHandler({
collectionSlug
});
if (typeof handler === 'function') {
let filename = file.name;
const clientUploadContext = await handler({
file,
updateFilename: value_0 => {
filename = value_0;
}
});
file = JSON.stringify({
clientUploadContext,
collectionSlug,
filename,
mimeType: file.type,
size: file.size
});
}
}
if (mergeOverrideData) {
data_5 = {
...data_5,
...overrides_0
};
} else {
data_5 = overrides_0;
}
const dataToSerialize = {
_payload: JSON.stringify(data_5)
};
if (docConfig && 'upload' in docConfig && docConfig.upload && file) {
dataToSerialize.file = file;
}
// nullAsUndefineds is important to allow uploads and relationship fields to clear themselves
const formData_0 = serialize(dataToSerialize, {
indices: true,
nullsAsUndefineds: false
});
return formData_0;
}, [collectionSlug, docConfig, getUploadHandler]);
const reset = useCallback(async data_6 => {
const controller = handleAbortRef(abortResetFormRef);
const docPreferences = await getDocPreferences();
const {
state: newState
} = await getFormState({
id,
collectionSlug,
data: data_6,
docPermissions,
docPreferences,
globalSlug,
locale,
operation,
renderAllFields: true,
schemaPath: collectionSlug ? collectionSlug : globalSlug,
signal: controller.signal,
skipValidation: true
});
contextRef.current = {
...initContextState
};
setModified(false);
dispatchFields({
type: 'REPLACE_STATE',
state: newState
});
abortResetFormRef.current = null;
}, [collectionSlug, dispatchFields, globalSlug, id, operation, getFormState, docPermissions, getDocPreferences, locale, setModified]);
const replaceState = useCallback(state => {
contextRef.current = {
...initContextState
};
setModified(false);
dispatchFields({
type: 'REPLACE_STATE',
state
});
}, [dispatchFields, setModified]);
const addFieldRow = useCallback(({
blockType,
path: path_3,
rowIndex: rowIndexArg,
subFieldState
}) => {
const newRows = getDataByPath(path_3) || [];
const rowIndex = rowIndexArg === undefined ? newRows.length : rowIndexArg;
// dispatch ADD_ROW adds a blank row to local form state.
// This performs no form state request, as the debounced onChange effect will do that for us.
dispatchFields({
type: 'ADD_ROW',
blockType,
path: path_3,
rowIndex,
subFieldState
});
setModified(true);
}, [dispatchFields, getDataByPath, setModified]);
const moveFieldRow = useCallback(({
moveFromIndex,
moveToIndex,
path: path_4
}) => {
dispatchFields({
type: 'MOVE_ROW',
moveFromIndex,
moveToIndex,
path: path_4
});
setModified(true);
}, [dispatchFields, setModified]);
const removeFieldRow = useCallback(({
path: path_5,
rowIndex: rowIndex_0
}) => {
dispatchFields({
type: 'REMOVE_ROW',
path: path_5,
rowIndex: rowIndex_0
});
setModified(true);
}, [dispatchFields, setModified]);
const replaceFieldRow = useCallback(({
blockType: blockType_0,
path: path_6,
rowIndex: rowIndexArg_0,
subFieldState: subFieldState_0
}) => {
const currentRows = getDataByPath(path_6);
const rowIndex_1 = rowIndexArg_0 === undefined ? currentRows.length : rowIndexArg_0;
dispatchFields({
type: 'REPLACE_ROW',
blockType: blockType_0,
path: path_6,
rowIndex: rowIndex_1,
subFieldState: subFieldState_0
});
setModified(true);
}, [dispatchFields, getDataByPath, setModified]);
useEffect(() => {
const abortOnChange = abortResetFormRef.current;
return () => {
abortAndIgnore(abortOnChange);
};
}, []);
useEffect(() => {
if (initializingFromProps !== undefined) {
setInitializing(initializingFromProps);
}
}, [initializingFromProps]);
contextRef.current.submit = submit;
contextRef.current.getFields = getFields;
contextRef.current.getField = getField;
contextRef.current.getData = getData;
contextRef.current.getSiblingData = getSiblingData;
contextRef.current.getDataByPath = getDataByPath;
contextRef.current.validateForm = validateForm;
contextRef.current.createFormData = createFormData;
contextRef.current.setModified = setModified;
contextRef.current.setProcessing = setProcessing;
contextRef.current.setBackgroundProcessing = setBackgroundProcessing;
contextRef.current.setSubmitted = setSubmitted;
contextRef.current.setIsValid = setIsValid;
contextRef.current.disabled = disabled;
contextRef.current.setDisabled = setDisabled;
contextRef.current.formRef = formRef;
contextRef.current.reset = reset;
contextRef.current.replaceState = replaceState;
contextRef.current.dispatchFields = dispatchFields;
contextRef.current.addFieldRow = addFieldRow;
contextRef.current.removeFieldRow = removeFieldRow;
contextRef.current.moveFieldRow = moveFieldRow;
contextRef.current.replaceFieldRow = replaceFieldRow;
contextRef.current.uuid = uuid;
contextRef.current.initializing = initializing;
contextRef.current.isValid = isValid;
useEffect(() => {
setIsMounted(true);
}, []);
useEffect(() => {
if (typeof disabledFromProps === 'boolean') {
setDisabled(disabledFromProps);
}
}, [disabledFromProps]);
useEffect(() => {
if (typeof submittedFromProps === 'boolean') {
setSubmitted(submittedFromProps);
}
}, [submittedFromProps]);
useEffect(() => {
if (initialState) {
contextRef.current = {
...initContextState
};
dispatchFields({
type: 'REPLACE_STATE',
optimize: false,
sanitize: true,
state: initialState
});
}
}, [initialState, dispatchFields]);
useThrottledEffect(() => {
refreshCookie();
}, 15000, [formState]);
const handleLocaleChange = useEffectEvent(() => {
contextRef.current = {
...contextRef.current
}; // triggers rerender of all components that subscribe to form
setModified(false);
});
useEffect(() => {
handleLocaleChange();
}, [locale]);
const classes = [className, baseClass].filter(Boolean).join(' ');
const executeOnChange = useEffectEvent(submitted_0 => {
queueTask(async () => {
if (Array.isArray(onChange)) {
let serverState;
for (const onChangeFn of onChange) {
// Edit view default onChange is in packages/ui/src/views/Edit/index.tsx. This onChange usually sends a form state request
serverState = await onChangeFn({
formState: deepCopyObjectSimpleWithoutReactComponents(formState, {
excludeFiles: true
}),
submitted: submitted_0
});
}
dispatchFields({
type: 'MERGE_SERVER_STATE',
prevStateRef: prevFormState,
serverState
});
}
});
});
useDebouncedEffect(() => {
if ((isFirstRenderRef.current || !dequal(formState, prevFormState.current)) && modified) {
executeOnChange(submitted);
}
prevFormState.current = formState;
isFirstRenderRef.current = false;
}, [modified, submitted, formState], 250);
const DocumentFormContextComponent = isDocumentForm ? DocumentFormContext : React.Fragment;
const documentFormContextProps = isDocumentForm ? {
value: contextRef.current
} : {};
const El = el || 'form';
return /*#__PURE__*/_jsx(El, {
action: typeof action === 'function' ? void action : action,
className: classes,
/**
* data-form-ready signals if the form is ready to be used. This is used by our e2e tests
* to wait for the form to be ready before interacting with it, reducing flakiness if the test is run in
* slow network conditions.
*/
"data-form-ready": !processing && isMounted && !initializing,
method: method,
noValidate: true,
onSubmit: e_0 => void contextRef.current.submit({}, e_0),
ref: formRef,
children: /*#__PURE__*/_jsx(DocumentFormContextComponent, {
...documentFormContextProps,
children: /*#__PURE__*/_jsx(FormContext, {
value: contextRef.current,
children: /*#__PURE__*/_jsx(FormWatchContext, {
value: {
fields: formState,
...contextRef.current
},
children: /*#__PURE__*/_jsx(SubmittedContext, {
value: submitted,
children: /*#__PURE__*/_jsx(InitializingContext, {
value: !isMounted || isMounted && initializing,
children: /*#__PURE__*/_jsx(ProcessingContext, {
value: processing,
children: /*#__PURE__*/_jsx(BackgroundProcessingContext, {
value: backgroundProcessing,
children: /*#__PURE__*/_jsx(ModifiedContext, {
value: modified,
children: /*#__PURE__*/_jsx(FormFieldsContext.Provider, {
value: fieldsReducer,
children: children
})
})
})
})
})
})
})
})
})
});
};
export { DocumentFormContext, FormContext, FormFieldsContext, FormWatchContext, ModifiedContext, ProcessingContext, SubmittedContext, useAllFormFields, useDocumentForm, useForm, useFormFields, useFormModified, useFormProcessing, useFormSubmitted, useWatchForm } from './context.js';
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"internal-types.js","sourceRoot":"","sources":["../../../src/v2-v3/internal-types.ts"],"names":[],"mappings":"","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 */\nexport interface RedisPluginClientTypes {\n connection_options?: {\n port?: string;\n host?: string;\n };\n\n address?: string;\n}\n\n// exported from\n// https://github.com/redis/node-redis/blob/v3.1.2/lib/command.js\nexport interface RedisCommand {\n command: string;\n args: string[];\n buffer_args: boolean;\n callback: (err: Error | null, reply: unknown) => void;\n call_on_write: boolean;\n}\n\n// Exported from \"@types/redis@2.8.32\".\nexport type Callback<T> = (err: Error | null, reply: T) => void;\n"]}

View File

@@ -0,0 +1,10 @@
/**
* 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.
*
*/
export * from './generateContent';
export * from './TreeView';
export * from './useLexicalCommandsLog';

View File

@@ -0,0 +1,227 @@
# @jridgewell/gen-mapping
> Generate source maps
`gen-mapping` allows you to generate a source map during transpilation or minification.
With a source map, you're able to trace the original location in the source file, either in Chrome's
DevTools or using a library like [`@jridgewell/trace-mapping`][trace-mapping].
You may already be familiar with the [`source-map`][source-map] package's `SourceMapGenerator`. This
provides the same `addMapping` and `setSourceContent` API.
## Installation
```sh
npm install @jridgewell/gen-mapping
```
## Usage
```typescript
import { GenMapping, addMapping, setSourceContent, toEncodedMap, toDecodedMap } from '@jridgewell/gen-mapping';
const map = new GenMapping({
file: 'output.js',
sourceRoot: 'https://example.com/',
});
setSourceContent(map, 'input.js', `function foo() {}`);
addMapping(map, {
// Lines start at line 1, columns at column 0.
generated: { line: 1, column: 0 },
source: 'input.js',
original: { line: 1, column: 0 },
});
addMapping(map, {
generated: { line: 1, column: 9 },
source: 'input.js',
original: { line: 1, column: 9 },
name: 'foo',
});
assert.deepEqual(toDecodedMap(map), {
version: 3,
file: 'output.js',
names: ['foo'],
sourceRoot: 'https://example.com/',
sources: ['input.js'],
sourcesContent: ['function foo() {}'],
mappings: [
[ [0, 0, 0, 0], [9, 0, 0, 9, 0] ]
],
});
assert.deepEqual(toEncodedMap(map), {
version: 3,
file: 'output.js',
names: ['foo'],
sourceRoot: 'https://example.com/',
sources: ['input.js'],
sourcesContent: ['function foo() {}'],
mappings: 'AAAA,SAASA',
});
```
### Smaller Sourcemaps
Not everything needs to be added to a sourcemap, and needless markings can cause signficantly
larger file sizes. `gen-mapping` exposes `maybeAddSegment`/`maybeAddMapping` APIs that will
intelligently determine if this marking adds useful information. If not, the marking will be
skipped.
```typescript
import { maybeAddMapping } from '@jridgewell/gen-mapping';
const map = new GenMapping();
// Adding a sourceless marking at the beginning of a line isn't useful.
maybeAddMapping(map, {
generated: { line: 1, column: 0 },
});
// Adding a new source marking is useful.
maybeAddMapping(map, {
generated: { line: 1, column: 0 },
source: 'input.js',
original: { line: 1, column: 0 },
});
// But adding another marking pointing to the exact same original location isn't, even if the
// generated column changed.
maybeAddMapping(map, {
generated: { line: 1, column: 9 },
source: 'input.js',
original: { line: 1, column: 0 },
});
assert.deepEqual(toEncodedMap(map), {
version: 3,
names: [],
sources: ['input.js'],
sourcesContent: [null],
mappings: 'AAAA',
});
```
## Benchmarks
```
node v18.0.0
amp.js.map
Memory Usage:
gen-mapping: addSegment 5852872 bytes
gen-mapping: addMapping 7716042 bytes
source-map-js 6143250 bytes
source-map-0.6.1 6124102 bytes
source-map-0.8.0 6121173 bytes
Smallest memory usage is gen-mapping: addSegment
Adding speed:
gen-mapping: addSegment x 441 ops/sec ±2.07% (90 runs sampled)
gen-mapping: addMapping x 350 ops/sec ±2.40% (86 runs sampled)
source-map-js: addMapping x 169 ops/sec ±2.42% (80 runs sampled)
source-map-0.6.1: addMapping x 167 ops/sec ±2.56% (80 runs sampled)
source-map-0.8.0: addMapping x 168 ops/sec ±2.52% (80 runs sampled)
Fastest is gen-mapping: addSegment
Generate speed:
gen-mapping: decoded output x 150,824,370 ops/sec ±0.07% (102 runs sampled)
gen-mapping: encoded output x 663 ops/sec ±0.22% (98 runs sampled)
source-map-js: encoded output x 197 ops/sec ±0.45% (84 runs sampled)
source-map-0.6.1: encoded output x 198 ops/sec ±0.33% (85 runs sampled)
source-map-0.8.0: encoded output x 197 ops/sec ±0.06% (93 runs sampled)
Fastest is gen-mapping: decoded output
***
babel.min.js.map
Memory Usage:
gen-mapping: addSegment 37578063 bytes
gen-mapping: addMapping 37212897 bytes
source-map-js 47638527 bytes
source-map-0.6.1 47690503 bytes
source-map-0.8.0 47470188 bytes
Smallest memory usage is gen-mapping: addMapping
Adding speed:
gen-mapping: addSegment x 31.05 ops/sec ±8.31% (43 runs sampled)
gen-mapping: addMapping x 29.83 ops/sec ±7.36% (51 runs sampled)
source-map-js: addMapping x 20.73 ops/sec ±6.22% (38 runs sampled)
source-map-0.6.1: addMapping x 20.03 ops/sec ±10.51% (38 runs sampled)
source-map-0.8.0: addMapping x 19.30 ops/sec ±8.27% (37 runs sampled)
Fastest is gen-mapping: addSegment
Generate speed:
gen-mapping: decoded output x 381,379,234 ops/sec ±0.29% (96 runs sampled)
gen-mapping: encoded output x 95.15 ops/sec ±2.98% (72 runs sampled)
source-map-js: encoded output x 15.20 ops/sec ±7.41% (33 runs sampled)
source-map-0.6.1: encoded output x 16.36 ops/sec ±10.46% (31 runs sampled)
source-map-0.8.0: encoded output x 16.06 ops/sec ±6.45% (31 runs sampled)
Fastest is gen-mapping: decoded output
***
preact.js.map
Memory Usage:
gen-mapping: addSegment 416247 bytes
gen-mapping: addMapping 419824 bytes
source-map-js 1024619 bytes
source-map-0.6.1 1146004 bytes
source-map-0.8.0 1113250 bytes
Smallest memory usage is gen-mapping: addSegment
Adding speed:
gen-mapping: addSegment x 13,755 ops/sec ±0.15% (98 runs sampled)
gen-mapping: addMapping x 13,013 ops/sec ±0.11% (101 runs sampled)
source-map-js: addMapping x 4,564 ops/sec ±0.21% (98 runs sampled)
source-map-0.6.1: addMapping x 4,562 ops/sec ±0.11% (99 runs sampled)
source-map-0.8.0: addMapping x 4,593 ops/sec ±0.11% (100 runs sampled)
Fastest is gen-mapping: addSegment
Generate speed:
gen-mapping: decoded output x 379,864,020 ops/sec ±0.23% (93 runs sampled)
gen-mapping: encoded output x 14,368 ops/sec ±4.07% (82 runs sampled)
source-map-js: encoded output x 5,261 ops/sec ±0.21% (99 runs sampled)
source-map-0.6.1: encoded output x 5,124 ops/sec ±0.58% (99 runs sampled)
source-map-0.8.0: encoded output x 5,434 ops/sec ±0.33% (96 runs sampled)
Fastest is gen-mapping: decoded output
***
react.js.map
Memory Usage:
gen-mapping: addSegment 975096 bytes
gen-mapping: addMapping 1102981 bytes
source-map-js 2918836 bytes
source-map-0.6.1 2885435 bytes
source-map-0.8.0 2874336 bytes
Smallest memory usage is gen-mapping: addSegment
Adding speed:
gen-mapping: addSegment x 4,772 ops/sec ±0.15% (100 runs sampled)
gen-mapping: addMapping x 4,456 ops/sec ±0.13% (97 runs sampled)
source-map-js: addMapping x 1,618 ops/sec ±0.24% (97 runs sampled)
source-map-0.6.1: addMapping x 1,622 ops/sec ±0.12% (99 runs sampled)
source-map-0.8.0: addMapping x 1,631 ops/sec ±0.12% (100 runs sampled)
Fastest is gen-mapping: addSegment
Generate speed:
gen-mapping: decoded output x 379,107,695 ops/sec ±0.07% (99 runs sampled)
gen-mapping: encoded output x 5,421 ops/sec ±1.60% (89 runs sampled)
source-map-js: encoded output x 2,113 ops/sec ±1.81% (98 runs sampled)
source-map-0.6.1: encoded output x 2,126 ops/sec ±0.10% (100 runs sampled)
source-map-0.8.0: encoded output x 2,176 ops/sec ±0.39% (98 runs sampled)
Fastest is gen-mapping: decoded output
```
[source-map]: https://www.npmjs.com/package/source-map
[trace-mapping]: https://github.com/jridgewell/sourcemaps/tree/main/packages/trace-mapping

View File

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

View File

@@ -0,0 +1 @@
{"version":3,"file":"propagation-api.js","sourceRoot":"","sources":["../../src/propagation-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,sEAAsE;AACtE,qCAAqC;AACrC,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,qCAAqC;AACrC,MAAM,CAAC,MAAM,WAAW,GAAG,cAAc,CAAC,WAAW,EAAE,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\n// Split module-level variable definition into separate files to allow\n// tree-shaking on each api instance.\nimport { PropagationAPI } from './api/propagation';\n/** Entrypoint for propagation API */\nexport const propagation = PropagationAPI.getInstance();\n"]}

View File

@@ -0,0 +1,19 @@
/**
* @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 RefreshCcwDot = createLucideIcon("RefreshCcwDot", [
["path", { d: "M3 2v6h6", key: "18ldww" }],
["path", { d: "M21 12A9 9 0 0 0 6 5.3L3 8", key: "1pbrqz" }],
["path", { d: "M21 22v-6h-6", key: "usdfbe" }],
["path", { d: "M3 12a9 9 0 0 0 15 6.7l3-2.7", key: "1hosoe" }],
["circle", { cx: "12", cy: "12", r: "1", key: "41hilf" }]
]);
export { RefreshCcwDot as default };
//# sourceMappingURL=refresh-ccw-dot.js.map

View File

@@ -0,0 +1,102 @@
import payload from '../index.js';
import { prettySyncLoggerDestination } from '../utilities/logger.js';
/**
* The default logger's options did not allow for forcing sync logging
* Using these options, to force both pretty print and sync logging
*/ const prettySyncLogger = {
loggerDestination: prettySyncLoggerDestination,
loggerOptions: {}
};
export const availableCommands = [
'migrate',
'migrate:create',
'migrate:down',
'migrate:refresh',
'migrate:reset',
'migrate:status',
'migrate:fresh'
];
const availableCommandsMsg = `Available commands: ${availableCommands.join(', ')}`;
export const migrate = async ({ config, migrationDir, parsedArgs })=>{
const { _: args, file, forceAcceptWarning: forceAcceptFromProps, help } = parsedArgs;
const formattedArgs = Object.keys(parsedArgs).map((key)=>{
const formattedKey = key.replace(/^[-_]+/, '');
if (!formattedKey) {
return null;
}
return formattedKey.split('-').map((word, index)=>index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1)).join('');
}).filter(Boolean);
const forceAcceptWarning = forceAcceptFromProps || formattedArgs.includes('forceAcceptWarning');
const skipEmpty = formattedArgs.includes('skipEmpty');
if (help) {
// eslint-disable-next-line no-console
console.log(`\n\n${availableCommandsMsg}\n`); // Avoid having to init payload to get the logger
process.exit(0);
}
process.env.PAYLOAD_MIGRATING = 'true';
// Barebones instance to access database adapter
await payload.init({
config,
disableDBConnect: args[0] === 'migrate:create',
disableOnInit: true,
...prettySyncLogger
});
const adapter = payload.db;
if (!adapter) {
throw new Error('No database adapter found');
}
// Override migrationDir if provided (useful for testing)
if (migrationDir) {
adapter.migrationDir = migrationDir;
}
if (!args.length) {
payload.logger.error({
msg: `No migration command provided. ${availableCommandsMsg}`
});
process.exit(1);
}
switch(args[0]){
case 'migrate':
await adapter.migrate();
break;
case 'migrate:create':
try {
await adapter.createMigration({
file,
forceAcceptWarning,
migrationName: args[1],
payload,
skipEmpty
});
} catch (err) {
const error = err instanceof Error ? err.message : 'Unknown error';
throw new Error(`Error creating migration: ${error}`);
}
break;
case 'migrate:down':
await adapter.migrateDown();
break;
case 'migrate:fresh':
await adapter.migrateFresh({
forceAcceptWarning
});
break;
case 'migrate:refresh':
await adapter.migrateRefresh();
break;
case 'migrate:reset':
await adapter.migrateReset();
break;
case 'migrate:status':
await adapter.migrateStatus();
break;
default:
payload.logger.error({
msg: `Unknown migration command: ${args[0]}. ${availableCommandsMsg}`
});
process.exit(1);
}
payload.logger.info('Done.');
};
//# sourceMappingURL=migrate.js.map

View File

@@ -0,0 +1,45 @@
import { constructFrom } from "../../../constructFrom.mjs";
import { getTimezoneOffsetInMilliseconds } from "../../../_lib/getTimezoneOffsetInMilliseconds.mjs";
import { timezonePatterns } from "../constants.mjs";
import { Parser } from "../Parser.mjs";
import { parseTimezonePattern } from "../utils.mjs";
// Timezone (ISO-8601. +00:00 is `'Z'`)
export class ISOTimezoneWithZParser extends Parser {
priority = 10;
parse(dateString, token) {
switch (token) {
case "X":
return parseTimezonePattern(
timezonePatterns.basicOptionalMinutes,
dateString,
);
case "XX":
return parseTimezonePattern(timezonePatterns.basic, dateString);
case "XXXX":
return parseTimezonePattern(
timezonePatterns.basicOptionalSeconds,
dateString,
);
case "XXXXX":
return parseTimezonePattern(
timezonePatterns.extendedOptionalSeconds,
dateString,
);
case "XXX":
default:
return parseTimezonePattern(timezonePatterns.extended, dateString);
}
}
set(date, flags, value) {
if (flags.timestampIsSet) return date;
return constructFrom(
date,
date.getTime() - getTimezoneOffsetInMilliseconds(date) - value,
);
}
incompatibleTokens = ["t", "T", "x"];
}

View File

@@ -0,0 +1,4 @@
{
"main": "../../cjs/_using_ctx.cjs",
"module": "../../esm/_using_ctx.js"
}

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